From f9dd84659c0ce5bc418cc746d221e30913ba7ae9 Mon Sep 17 00:00:00 2001 From: Delusions6515 <213381333+Delusions6515@users.noreply.github.com> Date: Sun, 27 Sep 2026 10:10:08 +0800 Subject: [PATCH] =?UTF-8?q?refactor(backend):=20=E6=97=A0=E9=9C=80?= =?UTF-8?q?=E5=A4=96=E6=8C=82=20shoutrrr=20/=20send=20push=20without=20its?= =?UTF-8?q?=20binary=20(#651)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * refactor(backend): send Node push notifications in process Bundle the pinned shoutrrr-ts sender in the standalone Node artifact, retain the existing HTTP template path, and document unsupported services. Keep configured URLs out of migrated-path diagnostics and clean up test polling on timeout. * feat(backend): route Node notifications through configured HTTP transport Pin shoutrrr-ts v0.2.0 and adapt notification requests to Sub-Store's HTTP client. Verify GET bodies, cross-host authorization stripping, and actual delivery from the standalone Node bundle. --- README.md | 8 + backend/bundle-esbuild.js | 22 +- backend/package.json | 1 + backend/pnpm-lock.yaml | 22 +- .../src/test/runtime/runtime-manifest.spec.js | 84 ++++++- .../src/test/vendor/open-api-notify.spec.js | 228 ++++++++++++++++++ backend/src/vendor/open-api.js | 78 +++--- 7 files changed, 400 insertions(+), 43 deletions(-) create mode 100644 backend/src/test/vendor/open-api-notify.spec.js diff --git a/README.md b/README.md index e00ae9eb..1221e0c6 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,14 @@ Sub-Store also supports a configurable browser CORS allowlist for the backend AP - Proxy App modules use the `cors` module argument; the default is `https://sub-store.vercel.app,http://substore.stash,https://substore.stash`. - Multiple origins can be separated by commas. Origins are matched exactly by scheme, host, and port. Set the value to `*` only when you accept the risk of any website reading the local backend through browser CORS. +## Node push notifications + +For Node deployments, `SUB_STORE_PUSH_SERVICE` accepts a Shoutrrr URL or an existing HTTP/HTTPS URL template. Shoutrrr URLs are sent in-process with [shoutrrr-ts](https://github.com/Delusions6515/shoutrrr-ts); a separate `shoutrrr` executable is no longer used or required. HTTP/HTTPS URL templates still use the existing request path and `[推送标题]` / `[推送内容]` placeholders. + +The supported Shoutrrr URL families are Generic Webhook (`generic://`, `generic+https://`, `generic+http://`), Bark, Discord, Gotify, Google Chat (`hangouts://` alias), IFTTT, Join, Mattermost, ntfy, OpsGenie, Pushover, Pushbullet, Rocket.Chat, Slack, Microsoft Teams, Telegram, and Zulip. **Matrix (`matrix://`) and SMTP (`smtp://`) are not supported, and there is no fallback to the old executable.** Check existing configurations before upgrading; unsupported URLs produce a notification error instead of sending. See [upstream compatibility details](https://github.com/Delusions6515/shoutrrr-ts/blob/main/COMPATIBILITY.md) for URL options and caveats. Upstream checks use local Go-compatibility fixtures, not verified live delivery to every provider. The backend's tested Node version is in `.node-version`; check the upstream package for its current Node support. + +Push URLs may contain secrets: treat `SUB_STORE_PUSH_SERVICE` as privileged configuration. Diagnostics from the Shoutrrr path do not print the configured URL. This change does not alter the HTTP/HTTPS URL template path or its existing logging behavior. + ## Core functionalities: 1. Conversion among various formats. diff --git a/backend/bundle-esbuild.js b/backend/bundle-esbuild.js index 63ed9fcf..b4303c1f 100644 --- a/backend/bundle-esbuild.js +++ b/backend/bundle-esbuild.js @@ -77,7 +77,7 @@ function createRuntimeManifest({ metafiles, content }) { requiresProcessGlobal: /\bprocess\b/.test(content), workerThreads: builtins.has('worker_threads'), childProcess: builtins.has('child_process'), - externalBinary: ['shoutrrr'], + externalBinary: [], testedNode: fs .readFileSync(path.join(__dirname, '..', '.node-version'), 'utf8') .trim(), @@ -99,9 +99,16 @@ const nodeBuiltinExternalPlugin = { }; !(async () => { - const version = JSON.parse( - fs.readFileSync(path.join(__dirname, 'package.json'), 'utf-8'), - ).version.trim(); + let version; + try { + version = JSON.parse( + fs.readFileSync(path.join(__dirname, 'package.json'), 'utf-8'), + ).version.trim(); + } catch (error) { + throw new Error('cannot read backend package version', { + cause: error, + }); + } const artifacts = [ { src: 'src/main.js', dest: 'sub-store.min.js' }, @@ -164,6 +171,13 @@ const nodeBuiltinExternalPlugin = { /eval\(('|")(require\(('|").*?('|")\))('|")\)/g, '$2', ); + // Browser builds retain an inert import; the Node pass resolves and bundles + // the ESM package into its standalone CommonJS artifact. + const shoutrrrImport = `eval('import("shoutrrr-ts")')`; + if (!content.includes(shoutrrrImport)) { + throw new Error('missing Shoutrrr import boundary in browser artifact'); + } + content = content.replace(shoutrrrImport, 'import("shoutrrr-ts")'); fs.writeFileSync( path.join(__dirname, 'dist/sub-store.no-bundle.js'), content, diff --git a/backend/package.json b/backend/package.json index 5b101d9f..4174b1bb 100644 --- a/backend/package.json +++ b/backend/package.json @@ -45,6 +45,7 @@ "ms": "^2.1.3", "nanoid": "^3.3.3", "semver": "^7.6.3", + "shoutrrr-ts": "https://github.com/Delusions6515/shoutrrr-ts/releases/download/v0.2.0/shoutrrr-ts-0.2.0.tgz", "undici": "^8.8.0", "yaml": "^2.9.0" }, diff --git a/backend/pnpm-lock.yaml b/backend/pnpm-lock.yaml index 064b9504..fdd1971f 100644 --- a/backend/pnpm-lock.yaml +++ b/backend/pnpm-lock.yaml @@ -77,6 +77,9 @@ importers: semver: specifier: ^7.6.3 version: 7.8.0 + shoutrrr-ts: + specifier: https://github.com/Delusions6515/shoutrrr-ts/releases/download/v0.2.0/shoutrrr-ts-0.2.0.tgz + version: https://github.com/Delusions6515/shoutrrr-ts/releases/download/v0.2.0/shoutrrr-ts-0.2.0.tgz undici: specifier: ^8.8.0 version: 8.8.0 @@ -2396,6 +2399,11 @@ packages: resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} engines: {node: '>=8'} + shoutrrr-ts@https://github.com/Delusions6515/shoutrrr-ts/releases/download/v0.2.0/shoutrrr-ts-0.2.0.tgz: + resolution: {integrity: sha512-K/Cj26Dbg1epa163VfprhsP50aFmGTi71ocI9ch0uSZFdUr+P11bgLGdk88bX2w/w/nlwm8jZJ5dCugfYhqDUw==, tarball: https://github.com/Delusions6515/shoutrrr-ts/releases/download/v0.2.0/shoutrrr-ts-0.2.0.tgz} + version: 0.2.0 + engines: {node: ^22.0.0 || ^24.0.0} + side-channel-list@1.0.1: resolution: {integrity: sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==} engines: {node: '>= 0.4'} @@ -2450,10 +2458,6 @@ packages: resolution: {integrity: sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ==} engines: {node: '>= 0.4'} - string-width@4.2.0: - resolution: {integrity: sha512-zUz5JD+tgqtuDjMhwIg5uFVV3dtqZ9yQJlZVfq4I01/K5Paj5UHj7VyrQOJvzawSVlKpObApbfD0Ed6yJc+1eg==} - engines: {node: '>=8'} - string-width@4.2.2: resolution: {integrity: sha512-XBJbT3N4JhVumXE0eoLU9DCjcaF92KLNqTmFCnG1pf8duUxFGwtP6AD6nkjw9a3IdiRtL3E2w3JDiE/xi3vOeA==} engines: {node: '>=8'} @@ -3518,7 +3522,7 @@ snapshots: '@isaacs/cliui@8.0.2': dependencies: string-width: 5.1.2 - string-width-cjs: string-width@4.2.0 + string-width-cjs: string-width@4.2.3 strip-ansi: 7.2.0 strip-ansi-cjs: strip-ansi@6.0.1 wrap-ansi: 8.1.0 @@ -5272,6 +5276,8 @@ snapshots: shebang-regex@3.0.0: {} + shoutrrr-ts@https://github.com/Delusions6515/shoutrrr-ts/releases/download/v0.2.0/shoutrrr-ts-0.2.0.tgz: {} + side-channel-list@1.0.1: dependencies: es-errors: 1.3.0 @@ -5329,12 +5335,6 @@ snapshots: es-errors: 1.3.0 internal-slot: 1.1.0 - string-width@4.2.0: - dependencies: - emoji-regex: 8.0.0 - is-fullwidth-code-point: 3.0.0 - strip-ansi: 6.0.0 - string-width@4.2.2: dependencies: emoji-regex: 8.0.0 diff --git a/backend/src/test/runtime/runtime-manifest.spec.js b/backend/src/test/runtime/runtime-manifest.spec.js index 4917ca4a..b97608a1 100644 --- a/backend/src/test/runtime/runtime-manifest.spec.js +++ b/backend/src/test/runtime/runtime-manifest.spec.js @@ -2,7 +2,9 @@ import { expect } from 'chai'; import fs from 'fs'; import os from 'os'; import path from 'path'; -import { spawnSync } from 'child_process'; +import { spawn, spawnSync } from 'child_process'; +import http from 'http'; +import { describe, it } from 'mocha'; const backendPath = path.resolve(__dirname, '../../..'); @@ -74,8 +76,88 @@ describe('runtime manifest bundle', function () { expect(result.status).to.equal(0); expect(manifest.npm).not.to.include('iconv-lite'); + expect(manifest.npm).not.to.include('shoutrrr-ts'); + expect(manifest.externalBinary).to.deep.equal([]); + const nodeBundle = fs.readFileSync( + path.join(fixturePath, 'dist/sub-store.bundle.js'), + 'utf8', + ); + expect(nodeBundle).to.include( + 'service is not supported by shoutrrr-ts', + ); + expect(nodeBundle).not.to.include('import("shoutrrr-ts")'); } finally { fs.rmSync(root, { recursive: true, force: true }); } }); + + it('delivers a notification from the standalone Node bundle', async function () { + this.timeout(20000); + const { root, fixturePath } = createFixture(); + let child; + const webhook = http.createServer(async (request, response) => { + const chunks = []; + for await (const chunk of request) chunks.push(chunk); + received = Buffer.concat(chunks).toString(); + response.end('ok'); + }); + let received; + try { + fs.copyFileSync( + path.join(backendPath, '..', '.node-version'), + path.join(root, '.node-version'), + ); + const build = spawnSync(process.execPath, ['bundle-esbuild.js'], { + cwd: fixturePath, + encoding: 'utf8', + }); + expect(build.status, build.stderr).to.equal(0); + await new Promise((resolve) => + webhook.listen(0, '127.0.0.1', resolve), + ); + const portServer = http.createServer(); + await new Promise((resolve) => + portServer.listen(0, '127.0.0.1', resolve), + ); + const port = portServer.address().port; + await new Promise((resolve) => portServer.close(resolve)); + child = spawn(process.execPath, ['dist/sub-store.bundle.js'], { + cwd: fixturePath, + env: { + ...process.env, + SUB_STORE_BACKEND_API_HOST: '127.0.0.1', + SUB_STORE_BACKEND_API_PORT: `${port}`, + SUB_STORE_DATA_BASE_PATH: root, + SUB_STORE_PUSH_SERVICE: `generic+http://127.0.0.1:${ + webhook.address().port + }/notify`, + }, + stdio: 'ignore', + }); + const deadline = Date.now() + 10000; + while (Date.now() < deadline && !received) { + try { + await fetch( + `http://127.0.0.1:${port}/api/file/smoke?fakeFile=1&url=http%3A%2F%2F127.0.0.1%3A1%2Foffline`, + ); + } catch { + // Wait for the standalone server to start. + } + await new Promise((resolve) => setTimeout(resolve, 100)); + } + expect( + received, + 'standalone bundle did not deliver a notification', + ).to.be.a('string'); + } finally { + if (child && child.exitCode === null) { + child.kill(); + await new Promise((resolve) => child.once('exit', resolve)); + } + if (webhook.listening) { + await new Promise((resolve) => webhook.close(resolve)); + } + fs.rmSync(root, { recursive: true, force: true }); + } + }); }); diff --git a/backend/src/test/vendor/open-api-notify.spec.js b/backend/src/test/vendor/open-api-notify.spec.js new file mode 100644 index 00000000..d5ab05ac --- /dev/null +++ b/backend/src/test/vendor/open-api-notify.spec.js @@ -0,0 +1,228 @@ +import { expect } from 'chai'; +import http from 'http'; +import { afterEach, describe, it } from 'mocha'; +import { OpenAPI } from '@/vendor/open-api'; + +describe('Node push notifications', function () { + this.timeout(10000); + + const previousPush = process.env.SUB_STORE_PUSH_SERVICE; + const previousLog = console.log; + let server; + let logs; + + afterEach(async function () { + console.log = previousLog; + if (previousPush === undefined) + delete process.env.SUB_STORE_PUSH_SERVICE; + else process.env.SUB_STORE_PUSH_SERVICE = previousPush; + if (server) { + await new Promise((resolve) => server.close(resolve)); + server = undefined; + } + }); + + function captureLogs() { + logs = []; + console.log = (...args) => logs.push(args.join(' ')); + } + + function waitForLog(text) { + return new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + clearInterval(check); + reject(new Error(`missing log: ${text}`)); + }, 3000); + const check = setInterval(() => { + if (logs.some((line) => line.includes(text))) { + clearTimeout(timeout); + clearInterval(check); + resolve(); + } + }, 10); + }); + } + + async function listen(handler) { + server = http.createServer(handler); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + return `127.0.0.1:${server.address().port}`; + } + + it('sends the existing assembled message through the in-process sender', async function () { + let received; + const host = await listen(async (request, response) => { + let body = ''; + for await (const chunk of request) body += chunk; + received = { method: request.method, body }; + response.end('ok'); + }); + process.env.SUB_STORE_PUSH_SERVICE = `generic+http://${host}/notify`; + captureLogs(); + + expect( + OpenAPI.prototype.notify('Title', 'Subtitle', 'Content', { + 'open-url': 'https://example.test/open', + 'media-url': 'https://example.test/image', + }), + ).to.equal(undefined); + await waitForLog('[Push Service]'); + + expect(received).to.include({ method: 'POST' }); + expect(received.body).to.include( + 'Title\nSubtitle\nContent\n点击跳转: https://example.test/open\n多媒体: https://example.test/image', + ); + expect(logs.join('\n')).not.to.include('shoutrrr:'); + }); + + it('sends Generic GET bodies through the host HTTP client', async function () { + let received; + const host = await listen(async (request, response) => { + const chunks = []; + for await (const chunk of request) chunks.push(chunk); + received = { + method: request.method, + body: Buffer.concat(chunks).toString(), + }; + response.end('ok'); + }); + process.env.SUB_STORE_PUSH_SERVICE = `generic://${host}/notify?disabletls=yes&method=GET`; + captureLogs(); + OpenAPI.prototype.notify('Title', '', 'Body'); + await waitForLog('[Push Service]'); + expect(received).to.deep.equal({ + method: 'GET', + body: 'Title\n\nBody', + }); + }); + + it('delivers Generic methods without an HTTP convenience helper', async function () { + let received; + const host = await listen(async (request, response) => { + let body = ''; + for await (const chunk of request) body += chunk; + received = { method: request.method, body }; + response.end('ok'); + }); + process.env.SUB_STORE_PUSH_SERVICE = `generic://${host}/notify?disabletls=yes&method=PROPFIND`; + captureLogs(); + OpenAPI.prototype.notify('Title', '', 'Body'); + await waitForLog('[Push Service]'); + expect(received).to.deep.equal({ + method: 'PROPFIND', + body: 'Title\n\nBody', + }); + expect(logs.join('\n')).to.include('RES: sent'); + }); + + it('does not forward Generic authorization to a redirected host', async function () { + let forwarded; + const destination = http.createServer((request, response) => { + forwarded = request.headers.authorization; + response.end('ok'); + }); + await new Promise((resolve) => + destination.listen(0, '127.0.0.1', resolve), + ); + try { + const host = await listen((_request, response) => { + response.writeHead(307, { + location: `http://localhost:${ + destination.address().port + }/final`, + }); + response.end(); + }); + process.env.SUB_STORE_PUSH_SERVICE = `generic://${host}/notify?disabletls=yes&@authorization=synthetic-secret`; + captureLogs(); + OpenAPI.prototype.notify('Title', '', 'Body'); + await waitForLog('RES: sent'); + expect(forwarded).to.equal(undefined); + } finally { + await new Promise((resolve) => destination.close(resolve)); + } + }); + + it('does not send anything without push configuration', async function () { + delete process.env.SUB_STORE_PUSH_SERVICE; + captureLogs(); + expect(OpenAPI.prototype.notify('Title', '', 'Body')).to.equal( + undefined, + ); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(logs).to.have.length(1); + expect(logs[0]).to.include('[Notify] Title'); + }); + + it('keeps HTTP URL template handling separate', async function () { + let requested; + const host = await listen((request, response) => { + requested = request.url; + response.end('ok'); + }); + process.env.SUB_STORE_PUSH_SERVICE = `http://${host}/[推送标题]?body=[推送内容]`; + captureLogs(); + OpenAPI.prototype.notify('Title', 'Subtitle', 'Content'); + await waitForLog('RES: 200'); + expect(requested).to.equal('/Title?body=Subtitle%0AContent'); + }); + + it('reports unsupported services without logging credential-bearing URLs', async function () { + process.env.SUB_STORE_PUSH_SERVICE = + 'matrix://secret-user:secret-pass@example.test/secret-path?token=secret-query'; + captureLogs(); + OpenAPI.prototype.notify('Title', '', 'Body'); + await waitForLog('service is not supported'); + const output = logs.join('\n'); + for (const secret of [ + 'secret-user', + 'secret-pass', + 'secret-path', + 'secret-query', + ]) { + expect(output).not.to.include(secret); + } + }); + + it('does not log arbitrary secret-bearing webhook query fields', async function () { + const host = await listen((_request, response) => response.end('ok')); + process.env.SUB_STORE_PUSH_SERVICE = `generic+http://${host}/notify?code=synthetic-secret-value`; + captureLogs(); + OpenAPI.prototype.notify('Title', '', 'Body'); + await waitForLog('RES: sent'); + expect(logs.join('\n')).not.to.include('synthetic-secret-value'); + }); + + it('reports malformed URLs and rejected provider responses', async function () { + captureLogs(); + process.env.SUB_STORE_PUSH_SERVICE = 'not-a-url'; + OpenAPI.prototype.notify('Title', '', 'Body'); + await waitForLog('ERROR:'); + expect(logs.join('\n')).not.to.include('not-a-url'); + + const host = await listen((_request, response) => { + response.statusCode = 500; + response.end('failure'); + }); + process.env.SUB_STORE_PUSH_SERVICE = `generic+http://${host}/notify`; + captureLogs(); + OpenAPI.prototype.notify('Title', '', 'Body'); + await waitForLog('ERROR:'); + }); + + it('does not leak credentials from hostnames when sending fails', async function () { + for (const url of [ + // Invalid service options fail URL validation before any network call. + 'ifttt://synthetic-secret.example.test', + 'pushbullet://short-secret/device-id', + ]) { + process.env.SUB_STORE_PUSH_SERVICE = url; + captureLogs(); + OpenAPI.prototype.notify('Title', '', 'Body'); + await waitForLog('ERROR:'); + expect(logs.join('\n')).not.to.include( + url.split('://')[1].split(/[/?]/)[0], + ); + } + }); +}); diff --git a/backend/src/vendor/open-api.js b/backend/src/vendor/open-api.js index 07ae2edb..8538a9fa 100644 --- a/backend/src/vendor/open-api.js +++ b/backend/src/vendor/open-api.js @@ -1,6 +1,5 @@ /* eslint-disable no-undef */ import { installConsoleLogCapture } from '@/utils/debug-logs'; -import getChildProcess from '@/runtime/child-process'; import getFs from '@/runtime/fs'; const isQX = typeof $task !== 'undefined'; @@ -334,33 +333,25 @@ export class OpenAPI { ); }); } else { - const { execFile } = getChildProcess(); - execFile( - 'shoutrrr', - [ - 'send', - '--url', - push, - '--message', - `${title}\n${subtitle}\n${content_}`, - ], - (error, stdout, stderr) => { - if (error) { - console.log( - `[Push Service] URL: ${push}\nERROR: ${error}`, - ); - return; - } - if (stderr) { - console.log( - `[Push Service] URL: ${push}\nstderr: ${stderr}`, - ); - } + // Keep the ESM package out of browser artifacts; the Node bundle + // replaces this evaluated import with a bundled dynamic import. + eval('import("shoutrrr-ts")') + .then(({ send }) => + send(push, `${title}\n${subtitle}\n${content_}`, { + transport: createNotificationTransport(HTTP()), + }).then( + () => console.log('[Push Service] RES: sent'), + (error) => + console.log( + `[Push Service] ERROR: ${error.message}`, + ), + ), + ) + .catch(() => console.log( - `[Push Service] URL: ${push}\nstdout: ${stdout}`, - ); - }, - ); + '[Push Service] ERROR: notification delivery failed', + ), + ); } } } @@ -417,6 +408,39 @@ export function ENV() { }; } +// Keep notification requests on the same proxy/timeout policy as other Node HTTP calls. +// HTTP() follows redirects with Undici's redirect interceptor, which strips +// authorization/cookie headers on cross-origin redirects. Its timeout bounds +// the observed outcome but does not prove the underlying request was aborted. +function createNotificationTransport(client) { + return async (url, init = {}) => { + const body = init.body; + if ( + body != null && + typeof body !== 'string' && + !(body instanceof Uint8Array) && + !(body instanceof ArrayBuffer) + ) { + throw new Error('unsupported notification request body'); + } + const headers = Object.fromEntries(new Headers(init.headers).entries()); + const response = await client.request({ + url, + method: init.method || 'GET', + headers, + body: body instanceof ArrayBuffer ? new Uint8Array(body) : body, + encoding: null, + timeout: 8000, + }); + return new Response( + [204, 205, 304].includes(response.statusCode) + ? null + : response.body, + { status: response.statusCode }, + ); + }; +} + export function HTTP(defaultOptions = { baseURL: '' }) { const { isQX, isLoon, isSurge, isNode, isGUIforCores, isEgern } = ENV(); const methods = [