From 3c9a33d2e1ddf5404151b64b752d5b4d4299153e Mon Sep 17 00:00:00 2001 From: xream Date: Tue, 9 Jun 2026 15:29:57 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20Node=20=E7=8E=AF=E5=A2=83=E6=97=A5?= =?UTF-8?q?=E5=BF=97=E6=96=B0=E5=A2=9E=E6=97=A5=E6=9C=9F=E6=97=B6=E9=97=B4?= =?UTF-8?q?;=20=E4=BC=98=E5=8C=96=E6=97=A5=E5=BF=97=E6=98=BE=E7=A4=BA?= =?UTF-8?q?=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/package.json | 2 +- backend/src/test/restful/logs.spec.js | 170 +++++++++++++++++++++++++- backend/src/utils/debug-logs.js | 35 +++++- 3 files changed, 198 insertions(+), 9 deletions(-) diff --git a/backend/package.json b/backend/package.json index 3feaa38f..148025a0 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "sub-store", - "version": "2.24.9", + "version": "2.24.10", "description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and Shadowrocket.", "main": "src/main.js", "packageManager": "pnpm@11.0.9", diff --git a/backend/src/test/restful/logs.spec.js b/backend/src/test/restful/logs.spec.js index 91b44892..5109c365 100644 --- a/backend/src/test/restful/logs.spec.js +++ b/backend/src/test/restful/logs.spec.js @@ -8,6 +8,7 @@ let appendLogEntry; let getLogEntries; let clearLogEntries; let clearLogSettingsCache; +let prependConsoleTimestamp; let registerLogRoutes; let registerSettingsRoutes; let originalRead; @@ -28,10 +29,7 @@ ${'\u2505'.repeat(44)} const DEFAULT_IGNORED_NOISE_LOGS = [ '[sub-store] INFO: Surge AnyTLS Parser is activated', '[sub-store] ERROR: Fallback Base64 Pre-processor error: decoded line does not start with protocol', -]; -const DEFAULT_VISIBLE_PREPROCESSOR_LOGS = [ - '[sub-store] INFO: Pre-processor [Fallback Base64 Pre-processor] activated', - '[sub-store] INFO: Pre-processor [Clash Pre-processor] activated', + '[sub-store] INFO: [CORS] allowed origins: https://sub-store.vercel.app,http://127.0.0.1:8888 (env:SUB_STORE_CORS_ALLOWED_ORIGINS)', ]; function createRouteApp() { @@ -88,6 +86,12 @@ function createResponse(routePath) { }; } +function loadDebugLogsModuleFresh() { + const modulePath = require.resolve('../../utils/debug-logs'); + delete require.cache[modulePath]; + return require('../../utils/debug-logs'); +} + describe('logs routes', function () { before(async function () { ({ default: $ } = require('@/core/app')); @@ -96,6 +100,7 @@ describe('logs routes', function () { getLogEntries, clearLogEntries, clearLogSettingsCache, + prependConsoleTimestamp, } = require('@/utils/debug-logs')); ({ default: registerLogRoutes } = require('@/restful/logs')); ({ default: registerSettingsRoutes } = require('@/restful/settings')); @@ -138,6 +143,157 @@ describe('logs routes', function () { expect(storedLogs[1].message).to.equal('[unknown] ERROR: third'); }); + it('prefixes locale timestamp in string console output arguments', function () { + const args = ['route log', { ok: true }]; + const originalToLocaleString = Date.prototype.toLocaleString; + + try { + Date.prototype.toLocaleString = () => 'TEST_LOCALE_TIME'; + + const timestampedArgs = prependConsoleTimestamp(args, { + isNode: true, + }); + + expect(timestampedArgs).to.deep.equal([ + 'TEST_LOCALE_TIME route log', + { ok: true }, + ]); + expect(args).to.deep.equal(['route log', { ok: true }]); + } finally { + Date.prototype.toLocaleString = originalToLocaleString; + } + }); + + it('preserves node console format placeholders when timestamping', function () { + const { format } = require('util'); + const originalToLocaleString = Date.prototype.toLocaleString; + + try { + Date.prototype.toLocaleString = () => 'TEST_LOCALE_TIME'; + + const timestampedArgs = prependConsoleTimestamp( + ['route log %s %d', 'ok', 1], + { isNode: true }, + ); + + expect(timestampedArgs).to.deep.equal([ + 'TEST_LOCALE_TIME route log %s %d', + 'ok', + 1, + ]); + expect(format(...timestampedArgs)).to.equal( + 'TEST_LOCALE_TIME route log ok 1', + ); + } finally { + Date.prototype.toLocaleString = originalToLocaleString; + } + }); + + it('does not treat timestamp percent signs as console format placeholders', function () { + const { format } = require('util'); + const originalToLocaleString = Date.prototype.toLocaleString; + + try { + Date.prototype.toLocaleString = () => 'TEST_%s_TIME'; + + const stringArgs = prependConsoleTimestamp(['route log %s', 'ok'], { + isNode: true, + }); + const objectArgs = prependConsoleTimestamp([{ ok: true }], { + isNode: true, + }); + + expect(format(...stringArgs)).to.equal('TEST_%s_TIME route log ok'); + expect(format(...objectArgs)).to.equal('TEST_%s_TIME { ok: true }'); + } finally { + Date.prototype.toLocaleString = originalToLocaleString; + } + }); + + it('keeps locale timestamp separate for non-string console output arguments', function () { + const args = [{ ok: true }, 'route log']; + const originalToLocaleString = Date.prototype.toLocaleString; + + try { + Date.prototype.toLocaleString = () => 'TEST_LOCALE_TIME'; + + const timestampedArgs = prependConsoleTimestamp(args, { + isNode: true, + }); + + expect(timestampedArgs).to.deep.equal([ + 'TEST_LOCALE_TIME', + { ok: true }, + 'route log', + ]); + expect(args).to.deep.equal([{ ok: true }, 'route log']); + } finally { + Date.prototype.toLocaleString = originalToLocaleString; + } + }); + + it('prints locale timestamp for empty node console output arguments', function () { + const originalToLocaleString = Date.prototype.toLocaleString; + + try { + Date.prototype.toLocaleString = () => 'TEST_LOCALE_TIME'; + + expect(prependConsoleTimestamp([], { isNode: true })).to.deep.equal( + ['TEST_LOCALE_TIME'], + ); + } finally { + Date.prototype.toLocaleString = originalToLocaleString; + } + }); + + it('does not prepend locale timestamp outside node runtime', function () { + const args = ['route log', { ok: true }]; + + expect(prependConsoleTimestamp(args, { isNode: false })).to.deep.equal( + args, + ); + }); + + it('captures console logs outside node runtime', function () { + const consoleMethods = ['log', 'info', 'warn', 'error', 'debug']; + const originalConsole = Object.fromEntries( + consoleMethods.map((method) => [method, console[method]]), + ); + const testState = { + [SETTINGS_KEY]: { logsMaxCount: 500 }, + [LOGS_KEY]: '[]', + }; + const testApp = { + env: { isNode: false }, + read(key) { + return testState[key]; + }, + write(data, key) { + testState[key] = data; + return true; + }, + }; + const { installConsoleLogCapture: installConsoleLogCaptureFresh } = + loadDebugLogsModuleFresh(); + + try { + consoleMethods.forEach((method) => { + console[method] = () => {}; + }); + + installConsoleLogCaptureFresh(testApp); + console.log('route log'); + + const storedLogs = JSON.parse(testState[LOGS_KEY]); + expect(storedLogs).to.have.length(1); + expect(storedLogs[0].message).to.equal('[unknown] LOG: route log'); + } finally { + consoleMethods.forEach((method) => { + console[method] = originalConsole[method]; + }); + } + }); + it('disables persistent log cache IO when logsMaxCount is zero', function () { state[SETTINGS_KEY] = { logsMaxCount: 0 }; state[LOGS_KEY] = JSON.stringify([ @@ -488,7 +644,10 @@ describe('logs routes', function () { appendLogEntry($, 'info', ['before change 2']); appendLogEntry($, 'info', ['before change 3']); - await patchHandler({ body: { logsMaxCount: 1 } }, createResponse('/api/settings')); + await patchHandler( + { body: { logsMaxCount: 1 } }, + createResponse('/api/settings'), + ); appendLogEntry($, 'info', ['after change']); @@ -496,5 +655,4 @@ describe('logs routes', function () { expect(storedLogs).to.have.length(1); expect(storedLogs[0].message).to.equal('[unknown] INFO: after change'); }); - }); diff --git a/backend/src/utils/debug-logs.js b/backend/src/utils/debug-logs.js index a32a9b01..3a33b256 100644 --- a/backend/src/utils/debug-logs.js +++ b/backend/src/utils/debug-logs.js @@ -17,6 +17,7 @@ const DEFAULT_IGNORED_SINGLE_LINE_LOG_MESSAGE_RES = [ // /^Pre-processor \[Fallback Base64 Pre-processor\] activated$/, /^Pre-processor \[.+\] activated!?$/, /^Fallback Base64 Pre-processor error: decoded line does not start with protocol$/, + /^\[CORS\] allowed origins: .+$/, ]; let consoleCaptureInstalled = false; @@ -24,6 +25,31 @@ let isAppendingConsoleLog = false; let cachedLogsMaxCount = null; let cachedLogsMaxCountExpiresAt = 0; +export function prependConsoleTimestamp(args, { isNode } = {}) { + const consoleArgs = Array.from(args || []); + if (!isNode) { + return consoleArgs; + } + + const timestamp = new Date().toLocaleString(); + if (typeof consoleArgs[0] === 'string') { + const [format, ...restArgs] = consoleArgs; + const safeTimestamp = restArgs.length + ? escapeConsoleFormatLiteral(timestamp) + : timestamp; + return [`${safeTimestamp} ${format}`, ...restArgs]; + } + + const safeTimestamp = consoleArgs.length + ? escapeConsoleFormatLiteral(timestamp) + : timestamp; + return [safeTimestamp, ...consoleArgs]; +} + +function escapeConsoleFormatLiteral(value) { + return `${value}`.replace(/%/g, '%%'); +} + export function normalizeLogLimit(value, fallback = DEFAULT_LOG_LIMIT) { const normalizedFallback = normalizePositiveInteger( fallback, @@ -149,14 +175,19 @@ export function clearLogEntries($) { } export function installConsoleLogCapture($) { - if (consoleCaptureInstalled || typeof console === 'undefined') return; + if (consoleCaptureInstalled || typeof console === 'undefined') { + return; + } consoleCaptureInstalled = true; LOG_LEVELS.forEach((level) => { const original = console[level]; if (typeof original !== 'function') return; console[level] = function (...args) { - original.apply(console, args); + original.apply( + console, + prependConsoleTimestamp(args, { isNode: $.env.isNode }), + ); if (isAppendingConsoleLog) return; try { isAppendingConsoleLog = true;