From ff6c26d8d4c692a37c6a7eeab95194e1399be214 Mon Sep 17 00:00:00 2001 From: Todos Date: Wed, 28 Oct 2026 17:56:42 +0800 Subject: [PATCH] refactor(waker): enable the callback by signing key alone - Drop WAKER_MODE/WAKER_URL/WAKER_TRIGGERS from the deploy pipeline, the turbo env list and the README; nothing rewrites wrangler.toml any more. - [triggers] stays static: dual run is the default, and switching to waker alone is a separate change that deletes the section. - WAKER_SIGNING_KEY is injected when present and deploys still succeed when absent (receiver fails closed); verify asserts bound/absent. Checkpoint: 8ecyONV4q3YURaBr6u2z9 --- .github/scripts/configure-waker-mode.mjs | 178 ---------------- .github/scripts/test-deploy-checks.mjs | 166 +++++---------- .github/scripts/test-waker-deploy.mjs | 161 ++++++++++++++ .github/scripts/test-waker-mode.mjs | 259 ----------------------- .github/scripts/verify-deployment.sh | 63 +++--- .github/workflows/ci.yml | 2 +- .github/workflows/deploy.yml | 52 ++--- README.md | 75 +++---- README.zh-CN.md | 71 +++---- apps/worker/.dev.vars.example | 15 +- apps/worker/src/index.ts | 16 +- apps/worker/src/routes/waker.ts | 64 ++---- apps/worker/src/services/waker.ts | 5 +- apps/worker/src/types.ts | 15 +- apps/worker/src/waker/README.md | 11 +- apps/worker/test/waker-callback.test.ts | 84 ++++---- apps/worker/wrangler.toml | 14 +- turbo.json | 9 +- 18 files changed, 432 insertions(+), 828 deletions(-) delete mode 100644 .github/scripts/configure-waker-mode.mjs create mode 100644 .github/scripts/test-waker-deploy.mjs delete mode 100644 .github/scripts/test-waker-mode.mjs diff --git a/.github/scripts/configure-waker-mode.mjs b/.github/scripts/configure-waker-mode.mjs deleted file mode 100644 index 3d2503e..0000000 --- a/.github/scripts/configure-waker-mode.mjs +++ /dev/null @@ -1,178 +0,0 @@ -// Deploy-time configuration of the optional waker mode. -// -// The deploy workflow runs this after the resource-ID injection step and before -// the build, so the uploaded version is configured exactly as the GitHub -// variables say: -// -// WAKER_MODE=cron (default) native CF Cron Trigger — `[triggers]` stays, -// WAKER_MODE="cron" is written explicitly (keep_vars=true -// would otherwise leave a previous `waker` value alive), -// no WAKER_URL, no WAKER_SIGNING_KEY is injected. -// WAKER_MODE=waker waker callback mode — WAKER_MODE="waker" and WAKER_URL -// are written. `[triggers]` is removed only with an -// explicit WAKER_TRIGGERS=remove (the switch action); -// the default `keep` is the dual-run state: receiver on, -// native trigger still firing. -// -// Nothing secret is read or written here: WAKER_URL is plain configuration and -// WAKER_SIGNING_KEY never appears in wrangler.toml (the workflow puts it in the -// --secrets-file only). -// -// Usage (from the repository root): -// node .github/scripts/configure-waker-mode.mjs -// Env: WAKER_MODE (cron|waker), WAKER_URL, WAKER_TRIGGERS (keep|remove, keep by -// default), WRANGLER_TOML (optional path override), GITHUB_OUTPUT. -// -// Prints `mode=…` / `triggers=…` to $GITHUB_OUTPUT for later workflow steps. - -import { appendFileSync, readFileSync, writeFileSync } from 'node:fs'; - -const DEFAULT_TOML = 'apps/worker/wrangler.toml'; - -function fail(message) { - console.error(`::error::${message}`); - process.exit(1); -} - -function readEnum(name, raw, allowed, fallback) { - const value = (raw ?? '').trim().toLowerCase(); - if (value === '') return fallback; - if (!allowed.includes(value)) { - fail( - `${name}=${JSON.stringify(raw)} is invalid; expected one of: ${allowed.join(', ')}`, - ); - } - return value; -} - -const mode = readEnum( - 'WAKER_MODE', - process.env.WAKER_MODE, - ['cron', 'waker'], - 'cron', -); -const triggers = readEnum( - 'WAKER_TRIGGERS', - process.env.WAKER_TRIGGERS, - ['keep', 'remove'], - 'keep', -); - -// A cron-mode deploy that removes the native triggers would leave the app with -// no scheduler at all. Refuse instead of silently deploying that state. -if (mode === 'cron' && triggers === 'remove') { - fail( - 'WAKER_MODE=cron with WAKER_TRIGGERS=remove would leave the app without any scheduler; ' + - 'use WAKER_MODE=waker to remove [triggers], or WAKER_TRIGGERS=keep.', - ); -} - -let url = ''; -if (mode === 'waker') { - url = (process.env.WAKER_URL ?? '').trim().replace(/\/+$/, ''); - if (url === '') { - fail( - 'WAKER_MODE=waker requires WAKER_URL (the platform base URL, e.g. https://waker.oneboy.app). ' + - 'It is plain configuration: set it as a GitHub variable.', - ); - } - if (!/^https?:\/\/[^\s"'\\]+$/.test(url)) { - fail( - `WAKER_URL=${JSON.stringify(process.env.WAKER_URL)} is not a plain http(s) URL; ` + - 'it must not contain whitespace, quotes or backslashes.', - ); - } -} - -const tomlPath = process.env.WRANGLER_TOML ?? DEFAULT_TOML; -let toml; -try { - toml = readFileSync(tomlPath, 'utf8'); -} catch (error) { - fail(`cannot read ${tomlPath}: ${error.message}`); -} - -// ─── [triggers] ────────────────────────────────────────────────────────────── - -function hasTriggers(text) { - return ( - /^\[triggers\]\s*$/m.test(text) && /^crons\s*=\s*\[.*\]\s*$/m.test(text) - ); -} - -function stripTriggers(text) { - // The [triggers] block is the last table in hop's wrangler.toml. Header and - // body (comments included) are dropped; a table header that follows (if one - // is ever added) is kept, along with everything after it. - const out = []; - let inTriggers = false; - for (const line of text.split('\n')) { - if (/^\s*\[triggers\]\s*$/.test(line)) { - inTriggers = true; - continue; - } - if (inTriggers) { - // The block ends at the next table header; blank lines and comments that - // belonged to it are dropped with it. - if (/^\s*\[/.test(line)) { - inTriggers = false; - out.push(line); - } - continue; - } - out.push(line); - } - while (out.length > 0 && out[out.length - 1] === '') out.pop(); - return `${out.join('\n')}\n`; -} - -if (triggers === 'keep') { - if (!hasTriggers(toml)) { - fail( - `${tomlPath} has no [triggers] block with a crons entry, but WAKER_TRIGGERS=keep ` + - 'requires the native Cron Trigger to stay. Restore the section in the repository.', - ); - } -} else { - toml = stripTriggers(toml); -} - -// ─── [vars] ────────────────────────────────────────────────────────────────── -// Managed entries are rewritten on every run so a value from an earlier mode -// can never survive inside the file itself. (keep_vars=true in wrangler.toml is -// why WAKER_MODE must always be written, even in cron mode.) - -if (!/^\[vars\]\s*$/m.test(toml)) { - fail(`${tomlPath} has no [vars] section to write WAKER_MODE into.`); -} - -toml = toml - .replace(/^WAKER_MODE\s*=.*\n/gm, '') - .replace(/^WAKER_URL\s*=.*\n/gm, ''); - -const managed = [`WAKER_MODE = "${mode}"`]; -if (mode === 'waker') managed.push(`WAKER_URL = "${url}"`); -toml = toml.replace(/^\[vars\]\s*$/m, `[vars]\n${managed.join('\n')}`); - -writeFileSync(tomlPath, toml); - -// ─── Report ────────────────────────────────────────────────────────────────── - -const outputs = [`mode=${mode}`, `triggers=${triggers}`]; -if (mode === 'waker') outputs.push(`url=${url}`); -if (process.env.GITHUB_OUTPUT) { - appendFileSync(process.env.GITHUB_OUTPUT, `${outputs.join('\n')}\n`); -} - -if (mode === 'waker') { - console.log( - `waker mode: WAKER_MODE=waker WAKER_URL=${url} WAKER_TRIGGERS=${triggers}` + - (triggers === 'keep' - ? ' — dual run: the native Cron Trigger still fires, the receiver is open' - : ' — native [triggers] removed, the platform is the only scheduler'), - ); -} else { - console.log( - `waker mode: WAKER_MODE=cron WAKER_TRIGGERS=${triggers} — native Cron Trigger, waker callback closed`, - ); -} diff --git a/.github/scripts/test-deploy-checks.mjs b/.github/scripts/test-deploy-checks.mjs index 98f8655..beadc7b 100644 --- a/.github/scripts/test-deploy-checks.mjs +++ b/.github/scripts/test-deploy-checks.mjs @@ -241,13 +241,13 @@ for (const scenario of [ ok: false, }, { - // waker 模式:signing key 必须真的绑在版本上,否则回调一律 500。 - name: 'waker 模式且 WAKER_SIGNING_KEY 已绑定 → 通过', + // signing key 已配置:它必须真的绑在版本上,否则回调只会到 03:00 才暴露 500。 + name: '配置了 WAKER_SIGNING_KEY 且已绑定 → 通过', version: 'uploaded', percentage: 100, prefix: 'hop', env: 'hop', - waker: 'waker', + wakerKey: 'bound', secretBindings: [ '{"name":"JWT_SECRET","type":"secret_text"}', '{"name":"SETUP_SECRET","type":"secret_text"}', @@ -257,12 +257,12 @@ for (const scenario of [ ok: true, }, { - name: 'waker 模式缺 WAKER_SIGNING_KEY 绑定必须失败', + name: '配置了 WAKER_SIGNING_KEY 但版本上没有绑定 → 必须失败', version: 'uploaded', percentage: 100, prefix: 'hop', env: 'hop', - waker: 'waker', + wakerKey: 'bound', secretBindings: [ '{"name":"JWT_SECRET","type":"secret_text"}', '{"name":"SETUP_SECRET","type":"secret_text"}', @@ -272,48 +272,22 @@ for (const scenario of [ ok: false, }, { - // 切换完成态:triggers 真的没了才允许通过。 - name: 'waker+remove 且 schedules 为空 → 通过', + // 没配 key:部署照常成功,接收端运行时 fail closed——不是部署失败。 + name: '未配置 WAKER_SIGNING_KEY → 通过(接收端 fail closed)', version: 'uploaded', percentage: 100, prefix: 'hop', env: 'hop', - waker: 'waker', - triggers: 'remove', - schedulesEmpty: true, - secretBindings: [ - '{"name":"JWT_SECRET","type":"secret_text"}', - '{"name":"SETUP_SECRET","type":"secret_text"}', - '{"name":"TOTP_ENCRYPTION_KEY","type":"secret_text"}', - '{"name":"WAKER_SIGNING_KEY","type":"secret_text"}', - ], + wakerKey: 'absent', ok: true, }, { - name: 'waker+remove 但 Worker 仍有 cron schedule → 必须失败', - version: 'uploaded', - percentage: 100, - prefix: 'hop', - env: 'hop', - waker: 'waker', - triggers: 'remove', - secretBindings: [ - '{"name":"JWT_SECRET","type":"secret_text"}', - '{"name":"SETUP_SECRET","type":"secret_text"}', - '{"name":"TOTP_ENCRYPTION_KEY","type":"secret_text"}', - '{"name":"WAKER_SIGNING_KEY","type":"secret_text"}', - ], - expectError: 'still has cron schedule', - ok: false, - }, - { - // 原生模式丢了 schedule 等于清理停摆,必须失败。 - name: 'cron 模式但 schedules 为空 → 必须失败', + // 原生 Cron Trigger 丢了等于清理停摆,必须失败(与 key 无关)。 + name: 'schedules 为空 → 必须失败', version: 'uploaded', percentage: 100, prefix: 'hop', env: 'hop', - waker: 'cron', schedulesEmpty: true, expectError: "expected exactly '0 3 \\* \\* \\*'", ok: false, @@ -370,12 +344,8 @@ printf '%s\\n' '${schedulesBody}' TABLE_PREFIX: scenario.env ?? 'SL', WRANGLER_OUTPUT_FILE_PATH: output, CLOUDFLARE_API_TOKEN: 'test-token-not-a-real-value', - ...(scenario.waker === undefined - ? {} - : { WAKER_MODE: scenario.waker }), - ...(scenario.triggers === undefined - ? {} - : { WAKER_TRIGGERS: scenario.triggers }), + // 解析后的 key 状态由 Write secrets file 步传给 Verify 步。 + WAKER_SIGNING_KEY_EXPECTED: scenario.wakerKey ?? 'absent', }, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], @@ -388,17 +358,15 @@ printf '%s\\n' '${schedulesBody}' stdout, ); assert.match(stdout, /Secret bindings on version uploaded/); - if (scenario.waker === 'waker') { - assert.match(stdout, /Waker mode: callback receiver enabled/); - assert.match(stdout, /WAKER_SIGNING_KEY/); - } else { - assert.doesNotMatch(stdout, /Waker mode:/); - } - if (scenario.waker === 'waker' && scenario.triggers === 'remove') { - assert.match(stdout, /Cron schedules: none/); + if (scenario.wakerKey === 'bound') { + assert.match(stdout, /WAKER_SIGNING_KEY configured — it must be bound/); } else { - assert.match(stdout, /Cron schedules: 0 3 \* \* \*/); + assert.match( + stdout, + /no WAKER_SIGNING_KEY configured — .*fails closed/, + ); } + assert.match(stdout, /Cron schedules: 0 3 \* \* \*/); } else { let thrown = null; try { @@ -544,6 +512,9 @@ for (const scenario of [ toml, new RegExp(`^TABLE_PREFIX = "${scenario.expected}"$`, 'm'), ); + // 部署产物仍带 [triggers]:原生 Cron Trigger 静态保留,流水线不摘它。 + assert.match(toml, /^\[triggers\]$/m); + assert.match(toml, /^crons = \["0 3 \* \* \*"\]$/m); // 残留检查(Inject 步的 grep)通过:所有占位符都已替换。 assert.doesNotMatch(toml, /_PLACEHOLDER/); }); @@ -776,18 +747,25 @@ test('deploy.yml:Smoke 步给自动推导补上 token 与账户 ID', () => { function runWriteSecrets(f, values) { const runnerTemp = join(f.dir, 'runner-temp'); mkdirSync(runnerTemp, { recursive: true }); - const env = { ...f.env, RUNNER_TEMP: runnerTemp }; + const githubOutput = join(runnerTemp, 'github-output'); + writeFileSync(githubOutput, ''); + const env = { + ...f.env, + RUNNER_TEMP: runnerTemp, + GITHUB_OUTPUT: githubOutput, + }; for (const name of [ 'JWT_SECRET', 'SETUP_SECRET', 'TOTP_ENCRYPTION_KEY', - 'WAKER_MODE', 'WAKER_SIGNING_KEY', ]) { delete env[name]; } Object.assign(env, values); const secretsPath = join(runnerTemp, 'secrets.json'); + + const output = () => readFileSync(githubOutput, 'utf8').trim(); try { execFileSync( 'bash', @@ -806,9 +784,10 @@ function runWriteSecrets(f, values) { ok: false, output: `${e.stdout ?? ''}${e.stderr ?? ''}`, secretsPath, + githubOutput: output(), }; } - return { ok: true, output: '', secretsPath }; + return { ok: true, output: '', secretsPath, githubOutput: output() }; } // 测试专用假值:只验证键名与接线,绝不涉及任何真实密钥。 @@ -874,13 +853,12 @@ test('deploy.yml:Write secrets file 步从仓库 Secret 注入 TOTP_ENCRYPTION ); }); -// ─── waker 双模式:secrets 文件与部署接线 ──────────────────────────────────── +// ─── waker 单密钥启停:secrets 文件与部署接线 ───────────────────────────────── -test('secrets 文件:waker 模式注入 WAKER_SIGNING_KEY', (t) => { +test('secrets 文件:配置了 WAKER_SIGNING_KEY 就注入,状态输出 bound', (t) => { const f = fixture(t); const result = runWriteSecrets(f, { ...fakeSecrets, - WAKER_MODE: 'waker', WAKER_SIGNING_KEY: 'waker-test-signing-key-not-a-real-value', }); assert.equal(result.ok, true, result.output); @@ -896,79 +874,41 @@ test('secrets 文件:waker 模式注入 WAKER_SIGNING_KEY', (t) => { 'waker-test-signing-key-not-a-real-value', ); assert.equal(statSync(result.secretsPath).mode & 0o777, 0o600); + assert.equal(result.githubOutput, 'waker_signing_key=bound'); }); -test('secrets 文件:waker 模式缺 WAKER_SIGNING_KEY 时该步失败且不落盘', (t) => { - const f = fixture(t); - const result = runWriteSecrets(f, { ...fakeSecrets, WAKER_MODE: 'waker' }); - assert.equal(result.ok, false, 'waker 模式缺 signing key 必须失败关闭'); - assert.match( - result.output, - /::error::GitHub Secret 'WAKER_SIGNING_KEY' is empty or missing/, - result.output, - ); - assert.equal(existsSync(result.secretsPath), false); -}); - -test('secrets 文件:cron 模式不注入 WAKER_SIGNING_KEY(即使配置了也不带)', (t) => { +test('secrets 文件:未配置 WAKER_SIGNING_KEY 不拦部署,状态输出 absent', (t) => { const f = fixture(t); - const result = runWriteSecrets(f, { - ...fakeSecrets, - WAKER_MODE: 'cron', - WAKER_SIGNING_KEY: 'waker-test-signing-key-not-a-real-value', - }); - assert.equal(result.ok, true, result.output); + const result = runWriteSecrets(f, fakeSecrets); + assert.equal(result.ok, true, '缺少可选 key 不得阻止部署'); const parsed = JSON.parse(readFileSync(result.secretsPath, 'utf8')); assert.deepEqual(Object.keys(parsed).sort(), [ 'JWT_SECRET', 'SETUP_SECRET', 'TOTP_ENCRYPTION_KEY', ]); + assert.equal(result.githubOutput, 'waker_signing_key=absent'); }); -test('deploy.yml:Configure waker mode 步读取三个 GitHub 变量,在 Inject 之后、Deploy 之前', () => { - const text = readFileSync( - join(repoRoot, '.github', 'workflows', 'deploy.yml'), - 'utf8', - ); - const lines = text.split('\n'); - const stepAt = (name) => - lines.findIndex((line) => line.trim() === `- name: ${name}`); - const inject = stepAt('Inject resource IDs'); - const configure = stepAt('Configure waker mode'); - const deploy = stepAt('Deploy'); - assert.ok( - inject !== -1 && configure !== -1 && deploy !== -1, - '缺步骤(Inject / Configure waker mode / Deploy)', - ); - assert.ok(inject < configure, 'Configure 必须在 Inject 之后(占位符已替换)'); - assert.ok(configure < deploy, 'Configure 必须在 Deploy 之前'); - - const end = lines.findIndex( - (line, i) => i > configure && /^\s*- (name|uses):/.test(line), - ); - const step = lines - .slice(configure, end === -1 ? lines.length : end) - .join('\n'); - assert.match(step, /^ {10}WAKER_MODE: \$\{\{ vars\.WAKER_MODE \}\}$/m); - assert.match(step, /^ {10}WAKER_URL: \$\{\{ vars\.WAKER_URL \}\}$/m); - assert.match( - step, - /^ {10}WAKER_TRIGGERS: \$\{\{ vars\.WAKER_TRIGGERS \}\}$/m, - ); - assert.match( - step, - /run: node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON \.github\/scripts\/configure-waker-mode\.mjs$/m, - ); - // 模式结果传给 secrets 文件与 verify 步:两处都必须取自同一步的 output。 - assert.match(text, /WAKER_MODE: \$\{\{ steps\.waker\.outputs\.mode \}\}/); +test('secrets 文件:WAKER_SIGNING_KEY 只有空白也按未配置处理(fail closed)', (t) => { + const f = fixture(t); + const result = runWriteSecrets(f, { + ...fakeSecrets, + WAKER_SIGNING_KEY: ' ', + }); + assert.equal(result.ok, true); + const parsed = JSON.parse(readFileSync(result.secretsPath, 'utf8')); + assert.equal(parsed.WAKER_SIGNING_KEY, undefined); + assert.equal(result.githubOutput, 'waker_signing_key=absent'); }); -test('deploy.yml:Verify 步带上解析后的 waker 模式,signing key 只从 Secret 取', () => { +test('deploy.yml:不再有模式步骤,signing key 只从 Secret 取', () => { const text = readFileSync( join(repoRoot, '.github', 'workflows', 'deploy.yml'), 'utf8', ); + assert.doesNotMatch(text, /Configure waker mode/); + assert.doesNotMatch(text, /configure-waker-mode/); assert.match( text, /WAKER_SIGNING_KEY: \$\{\{ secrets\.WAKER_SIGNING_KEY \}\}/, diff --git a/.github/scripts/test-waker-deploy.mjs b/.github/scripts/test-waker-deploy.mjs new file mode 100644 index 0000000..fc4c20e --- /dev/null +++ b/.github/scripts/test-waker-deploy.mjs @@ -0,0 +1,161 @@ +// Static invariants of the simplified waker wiring: the scheduling config is +// static, the signing key is the only switch, and no deployment variable from +// the old dual-mode design survived anywhere in the pipeline. +// +// Run from the repository root: +// node --test .github/scripts/test-waker-deploy.mjs +import assert from 'node:assert/strict'; +import { existsSync, readdirSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { test } from 'node:test'; +import { fileURLToPath } from 'node:url'; + +const repoRoot = fileURLToPath(new URL('../..', import.meta.url)); +const read = (...parts) => readFileSync(join(repoRoot, ...parts), 'utf8'); + +const wranglerToml = read('apps', 'worker', 'wrangler.toml'); +const deployYml = read('.github', 'workflows', 'deploy.yml'); +const turboJson = read('turbo.json'); +const verifyScript = read('.github', 'scripts', 'verify-deployment.sh'); + +const SELF = fileURLToPath(import.meta.url); + +/** Every pipeline file (workflows + deploy scripts), used for the residue scan. */ +function pipelineFiles(dir = join(repoRoot, '.github')) { + const files = []; + for (const entry of readdirSync(dir, { withFileTypes: true })) { + const full = join(dir, entry.name); + if (entry.isDirectory()) files.push(...pipelineFiles(full)); + else if ( + /\.(ya?ml|mjs|sh)$/.test(entry.name) && + full !== SELF && + // Test files naturally name what they assert is absent; they are not + // pipeline configuration. + !/^test-.*\.mjs$/.test(entry.name) + ) { + files.push(full); + } + } + return files; +} + +// ─── [triggers] is static: the native Cron Trigger is always deployed ──────── + +test('wrangler.toml 的 [triggers] 静态保留,全仓唯一 cron 表达式仍是 0 3 * * *', () => { + assert.match(wranglerToml, /^\[triggers\]$/m); + assert.match(wranglerToml, /^crons = \["0 3 \* \* \*"\]$/m); + assert.equal( + (wranglerToml.match(/^crons\s*=/gm) ?? []).length, + 1, + '只允许一条 crons 声明', + ); + + // 任务名与表达式与 waker 管理面注册的参数逐字一致。 + const service = read('apps', 'worker', 'src', 'services', 'waker.ts'); + assert.match(service, /WAKER_JOB_CRON = '0 3 \* \* \*'/); + assert.match(service, /WAKER_JOB_NIGHTLY_CLEANUP = 'nightly-cleanup'/); +}); + +test('wrangler.toml 不含任何 WAKER_ 变量(启停只认 secrets 里的 signing key)', () => { + assert.doesNotMatch(wranglerToml, /WAKER_/); +}); + +test('流水线不重写 [triggers]:deploy.yml 里没有 triggers 处理,也没有摘除脚本', () => { + assert.doesNotMatch(deployYml, /triggers/i); + // 旧的双模式改写脚本已删除,且 .github/scripts 里没有替代品。 + assert.equal( + existsSync( + join(repoRoot, '.github', 'scripts', 'configure-waker-mode.mjs'), + ), + false, + 'configure-waker-mode.mjs 必须删除', + ); + for (const file of pipelineFiles()) { + assert.doesNotMatch( + readFileSync(file, 'utf8'), + /stripTriggers|configure-waker-mode/, + `${file} 仍在处理 triggers`, + ); + } +}); + +// ─── the three mode variables are gone from the whole pipeline ────────────── + +test('流水线(workflows + scripts)无 WAKER_MODE / WAKER_URL / WAKER_TRIGGERS 残留', () => { + for (const file of pipelineFiles()) { + const text = readFileSync(file, 'utf8'); + for (const name of ['WAKER_MODE', 'WAKER_URL', 'WAKER_TRIGGERS']) { + assert.doesNotMatch(text, new RegExp(name), `${file} 仍引用 ${name}`); + } + } +}); + +test('turbo.json 的 env 名单不再有 waker 模式变量,TABLE_PREFIX 仍透传', () => { + const turbo = JSON.parse(turboJson); + const names = turbo.globalPassThroughEnv ?? []; + assert.deepEqual( + names.filter((name) => name.startsWith('WAKER_')), + [], + 'globalPassThroughEnv 不得再列 WAKER_*', + ); + assert.ok(names.includes('TABLE_PREFIX'), 'TABLE_PREFIX 必须继续透传'); +}); + +// ─── deploy: one optional Secret, injected when present ───────────────────── + +function step(name) { + const lines = deployYml.split('\n'); + const start = lines.findIndex((line) => line.trim() === `- name: ${name}`); + assert.notEqual(start, -1, `deploy.yml 缺少步骤「${name}」`); + const end = lines.findIndex( + (line, i) => i > start && /^\s*- (name|uses):/.test(line), + ); + return lines.slice(start, end === -1 ? lines.length : end).join('\n'); +} + +test('deploy.yml:signing key 只从仓库 Secret 取,绝不来自明文变量', () => { + assert.match( + deployYml, + /WAKER_SIGNING_KEY: \$\{\{ secrets\.WAKER_SIGNING_KEY \}\}/, + ); + assert.doesNotMatch(deployYml, /WAKER_SIGNING_KEY: \$\{\{ vars\./); +}); + +test('deploy.yml:secrets 文件步可选注入 key,并把解析状态交给 Verify 步', () => { + const secretsStep = step('Write secrets file'); + assert.match(secretsStep, /^ {8}id: secrets$/m); + // 必填清单只有与模式无关的三把密钥:signing key 缺失不拦部署(接收端 fail closed)。 + assert.match( + secretsStep, + /for name in JWT_SECRET SETUP_SECRET TOTP_ENCRYPTION_KEY; do/, + ); + assert.match(secretsStep, /waker_signing_key/); + assert.match( + secretsStep, + /const key = \(process\.env\.WAKER_SIGNING_KEY \?\? ""\)\.trim\(\)/, + ); + assert.match(secretsStep, /secrets\.WAKER_SIGNING_KEY = key/); + + const verifyStep = step('Verify deployment'); + assert.match( + verifyStep, + /^ {10}WAKER_SIGNING_KEY_EXPECTED: \$\{\{ steps\.secrets\.outputs\.waker_signing_key \}\}$/m, + ); + + // 顺序:先解析并落盘 secrets,再部署,最后核对绑定。 + const lines = deployYml.split('\n'); + const at = (name) => + lines.findIndex((line) => line.trim() === `- name: ${name}`); + assert.ok(at('Write secrets file') < at('Deploy')); + assert.ok(at('Deploy') < at('Verify deployment')); +}); + +test('verify-deployment.sh:无模式变量,cron 排期恒为 0 3 * * *', () => { + assert.doesNotMatch(verifyScript, /WAKER_MODE|WAKER_TRIGGERS/); + assert.match(verifyScript, /WAKER_SIGNING_KEY_EXPECTED/); + assert.match( + verifyScript, + /expected exactly '0 3 \* \* \*'/, + '排期闸门必须要求原生 Cron Trigger 在场', + ); +}); diff --git a/.github/scripts/test-waker-mode.mjs b/.github/scripts/test-waker-mode.mjs deleted file mode 100644 index 767105c..0000000 --- a/.github/scripts/test-waker-mode.mjs +++ /dev/null @@ -1,259 +0,0 @@ -// Tests for .github/scripts/configure-waker-mode.mjs — the deploy-time rewrite -// that turns the one wrangler.toml into the cron or the waker build. -// -// The most important assertion is the "cron stays as it was" one: with no waker -// variables configured, the generated config must equal the committed file plus -// exactly one explicit `WAKER_MODE = "cron"` line (needed because keep_vars=true -// would otherwise let a previous waker value survive), with [triggers] intact. -import assert from 'node:assert/strict'; -import { execFileSync } from 'node:child_process'; -import { copyFileSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { test } from 'node:test'; -import { fileURLToPath } from 'node:url'; - -const scripts = fileURLToPath(new URL('.', import.meta.url)); -const repoRoot = fileURLToPath(new URL('../..', import.meta.url)); -const scriptPath = join(scripts, 'configure-waker-mode.mjs'); -const committedToml = readFileSync( - join(repoRoot, 'apps', 'worker', 'wrangler.toml'), - 'utf8', -); - -const MANAGED = ['WAKER_MODE', 'WAKER_URL', 'WAKER_TRIGGERS']; - -function fixture(t) { - const dir = mkdtempSync(join(tmpdir(), 'hop-waker-mode-')); - t.after(() => rmSync(dir, { recursive: true, force: true })); - const toml = join(dir, 'wrangler.toml'); - copyFileSync(join(repoRoot, 'apps', 'worker', 'wrangler.toml'), toml); - const githubOutput = join(dir, 'github-output'); - const baseEnv = { ...process.env }; - for (const name of MANAGED) delete baseEnv[name]; - return { - toml, - githubOutput, - run(env = {}) { - const runEnv = { - ...baseEnv, - WRANGLER_TOML: toml, - GITHUB_OUTPUT: githubOutput, - ...env, - }; - try { - const stdout = execFileSync( - 'node', - ['--disable-warning=MODULE_TYPELESS_PACKAGE_JSON', scriptPath], - { env: runEnv, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }, - ); - return { - ok: true, - stdout, - toml: readFileSync(toml, 'utf8'), - output: readFileSync(githubOutput, 'utf8'), - }; - } catch (error) { - return { - ok: false, - output: `${error.stdout ?? ''}${error.stderr ?? ''}`, - }; - } - }, - }; -} - -// ─── cron (default): [triggers] untouched, one explicit mode var ───────────── - -for (const scenario of [ - { name: '所有 waker 变量都未配置', env: {} }, - { name: 'WAKER_MODE=cron(显式)', env: { WAKER_MODE: 'cron' } }, - { - name: 'WAKER_MODE=cron + WAKER_TRIGGERS=keep', - env: { WAKER_MODE: 'cron', WAKER_TRIGGERS: 'keep' }, - }, -]) { - test(`cron 模式(${scenario.name})→ 配置与迁移前一致,只多一行 WAKER_MODE=cron`, (t) => { - const f = fixture(t); - const result = f.run(scenario.env); - assert.equal(result.ok, true, result.output); - - const expected = committedToml.replace( - '[vars]\n', - '[vars]\nWAKER_MODE = "cron"\n', - ); - assert.equal( - result.toml, - expected, - '除了显式 WAKER_MODE 不得有任何其他改动', - ); - - // [triggers] 原样保留:同一表达式、只此一条。 - assert.match(result.toml, /^crons = \["0 3 \* \* \*"\]$/m); - assert.equal((result.toml.match(/^crons\s*=/gm) ?? []).length, 1); - assert.doesNotMatch(result.toml, /^WAKER_URL\s*=/m); - assert.equal(result.output.trim(), 'mode=cron\ntriggers=keep'); - }); -} - -// ─── waker: [triggers] removed, WAKER_URL injected ─────────────────────────── - -test('waker 模式默认 keep(双跑),triggers 保留', (t) => { - const f = fixture(t); - const result = f.run({ - WAKER_MODE: 'waker', - WAKER_URL: 'https://waker.oneboy.app', - }); - assert.equal(result.ok, true, result.output); - assert.match( - result.toml, - /^\[triggers\]\n(?:#[^\n]*\n)*crons = \["0 3 \* \* \*"\]$/m, - ); - assert.match(result.toml, /^WAKER_MODE = "waker"$/m); - assert.equal( - result.output.trim(), - 'mode=waker\ntriggers=keep\nurl=https://waker.oneboy.app', - ); -}); - -test('waker 模式 + WAKER_TRIGGERS=remove → 删除 [triggers]、写入 WAKER_MODE/WAKER_URL', (t) => { - const f = fixture(t); - const result = f.run({ - WAKER_MODE: 'waker', - WAKER_URL: 'https://waker.oneboy.app/', - WAKER_TRIGGERS: 'remove', - }); - assert.equal(result.ok, true, result.output); - assert.doesNotMatch(result.toml, /^\[triggers\]$/m); - assert.doesNotMatch(result.toml, /^crons\s*=/m); - assert.match(result.toml, /^WAKER_MODE = "waker"$/m); - // Trailing slash trimmed so the value is the platform's base URL. - assert.match(result.toml, /^WAKER_URL = "https:\/\/waker\.oneboy\.app"$/m); - // The resource-ID placeholders are left for the injection step / sed. - assert.match(result.toml, /TABLE_PREFIX = "TABLE_PREFIX_PLACEHOLDER"/); - assert.match(result.toml, /database_id = "D1_DATABASE_ID_PLACEHOLDER"/); - assert.equal( - result.output.trim(), - 'mode=waker\ntriggers=remove\nurl=https://waker.oneboy.app', - ); -}); - -test('waker 模式 + WAKER_TRIGGERS=keep → 双跑过渡态(receiver 开、triggers 留)', (t) => { - const f = fixture(t); - const result = f.run({ - WAKER_MODE: 'waker', - WAKER_URL: 'https://waker.oneboy.app', - WAKER_TRIGGERS: 'keep', - }); - assert.equal(result.ok, true, result.output); - assert.match( - result.toml, - /^\[triggers\]\n(?:#[^\n]*\n)*crons = \["0 3 \* \* \*"\]$/m, - ); - assert.match(result.toml, /^WAKER_MODE = "waker"$/m); - assert.match(result.toml, /^WAKER_URL = "https:\/\/waker\.oneboy\.app"$/m); - assert.match(result.stdout, /dual run/); -}); - -test('waker 模式变量大小写与空白被规范化', (t) => { - const f = fixture(t); - const result = f.run({ - WAKER_MODE: ' WAKER ', - WAKER_URL: ' https://waker.oneboy.app ', - }); - assert.equal(result.ok, true, result.output); - assert.match(result.toml, /^WAKER_MODE = "waker"$/m); -}); - -test('重复运行同一文件是幂等的(不重复写 WAKER_MODE / WAKER_URL)', (t) => { - const f = fixture(t); - const first = f.run({ - WAKER_MODE: 'waker', - WAKER_URL: 'https://waker.oneboy.app', - }); - assert.equal(first.ok, true, first.output); - const second = f.run({ - WAKER_MODE: 'waker', - WAKER_URL: 'https://waker.oneboy.app', - }); - assert.equal(second.ok, true, second.output); - assert.equal(second.toml, first.toml); - assert.equal((second.toml.match(/^WAKER_MODE\s*=/gm) ?? []).length, 1); - assert.equal((second.toml.match(/^WAKER_URL\s*=/gm) ?? []).length, 1); -}); - -test('从 waker 模式切回 cron 模式:triggers 恢复、WAKER_URL 不再写入', (t) => { - const f = fixture(t); - const waker = f.run({ - WAKER_MODE: 'waker', - WAKER_URL: 'https://waker.oneboy.app', - }); - assert.equal(waker.ok, true, waker.output); - // 回滚时仓库是全新的,这里先还原成提交版再跑 cron,模拟下一次干净部署。 - copyFileSync(join(repoRoot, 'apps', 'worker', 'wrangler.toml'), f.toml); - const cron = f.run({ WAKER_MODE: 'cron' }); - assert.equal(cron.ok, true, cron.output); - assert.match( - cron.toml, - /^\[triggers\]\n(?:#[^\n]*\n)*crons = \["0 3 \* \* \*"\]$/m, - ); - assert.doesNotMatch(cron.toml, /^WAKER_URL\s*=/m); -}); - -// ─── invalid combinations fail closed ─────────────────────────────────────── - -test('waker 模式缺 WAKER_URL → 部署失败(不留下半配置的回调入口)', (t) => { - const f = fixture(t); - const result = f.run({ WAKER_MODE: 'waker' }); - assert.equal(result.ok, false); - assert.match(result.output, /::error::WAKER_MODE=waker requires WAKER_URL/); -}); - -test('WAKER_URL 含引号/空白 → 部署失败', (t) => { - const f = fixture(t); - const result = f.run({ - WAKER_MODE: 'waker', - WAKER_URL: 'https://waker.oneboy.app "quoted"', - }); - assert.equal(result.ok, false); - assert.match(result.output, /not a plain http\(s\) URL/); -}); - -test('WAKER_MODE 取值未知 → 部署失败(不静默按 cron 部署)', (t) => { - const f = fixture(t); - const result = f.run({ WAKER_MODE: 'wakr' }); - assert.equal(result.ok, false); - assert.match(result.output, /WAKER_MODE="wakr" is invalid/); -}); - -test('WAKER_TRIGGERS 取值未知 → 部署失败', (t) => { - const f = fixture(t); - const result = f.run({ - WAKER_MODE: 'waker', - WAKER_URL: 'https://w.example', - WAKER_TRIGGERS: 'pause', - }); - assert.equal(result.ok, false); - assert.match(result.output, /WAKER_TRIGGERS="pause" is invalid/); -}); - -test('cron 模式 + WAKER_TRIGGERS=remove → 部署失败(否则没有任何调度器)', (t) => { - const f = fixture(t); - const result = f.run({ WAKER_MODE: 'cron', WAKER_TRIGGERS: 'remove' }); - assert.equal(result.ok, false); - assert.match(result.output, /would leave the app without any scheduler/); -}); - -// ─── repo-level cron invariant ─────────────────────────────────────────────── - -test('全仓唯一的 cron 表达式仍是 0 3 * * *,且与 waker 任务参数逐字一致', () => { - assert.equal((committedToml.match(/^crons\s*=/gm) ?? []).length, 1); - assert.match(committedToml, /^crons = \["0 3 \* \* \*"\]$/m); - - const service = readFileSync( - join(repoRoot, 'apps', 'worker', 'src', 'services', 'waker.ts'), - 'utf8', - ); - assert.match(service, /WAKER_JOB_CRON = '0 3 \* \* \*'/); - assert.match(service, /WAKER_JOB_NIGHTLY_CLEANUP = 'nightly-cleanup'/); -}); diff --git a/.github/scripts/verify-deployment.sh b/.github/scripts/verify-deployment.sh index c6baaec..384cf3e 100644 --- a/.github/scripts/verify-deployment.sh +++ b/.github/scripts/verify-deployment.sh @@ -8,12 +8,16 @@ # # Env: WRANGLER_OUTPUT_FILE_PATH — the ND-JSON file `wrangler deploy` wrote # TABLE_PREFIX — resolved prefix ('' means explicit no prefix) +# WAKER_SIGNING_KEY_EXPECTED — 'bound' when the repository Secret existed and +# was injected into the secrets file, 'absent' +# otherwise. Required: 'bound' asserts the key is +# really bound on the uploaded version (a callback +# without it only fails at 03:00 with 500 +# signing_key_missing); 'absent' just records that +# the receiver fails closed. No mode variable. # WORKER_NAME — optional, Worker name for the version lookup # (default 'hop', the name in wrangler.toml) -# WAKER_MODE / WAKER_TRIGGERS — resolved deploy mode; waker+remove must leave -# no cron schedule, every other mode exactly one -# `0 3 * * *` schedule. CLOUDFLARE_API_TOKEN is -# needed for the schedules lookup. +# CLOUDFLARE_API_TOKEN — needed for the schedules lookup. set -euo pipefail here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" @@ -41,14 +45,25 @@ worker_name="${WORKER_NAME:-hop}" secrets_view="$(pnpm exec wrangler versions view "$version" --name "$worker_name" --json)" # Don't turn an unexpected API response into a silent pass. jq -e --arg v "$version" '.id == $v and (.resources.bindings | type == "array")' <<<"$secrets_view" >/dev/null -# WAKER_SIGNING_KEY is required exactly when this deploy ran in waker mode: a -# callback version without it answers 500 signing_key_missing to every -# execution, which only shows up at 03:00. Cron-mode deploys do not inject it. +# WAKER_SIGNING_KEY is the only switch of the callback and is mode-free: when the +# repository Secret exists the secrets file carries it, so the uploaded version +# must have the binding; otherwise the callback fails closed (500 +# signing_key_missing) and nothing is required. There is no mode any more, so the +# rest of the required list is static. required_secrets="JWT_SECRET SETUP_SECRET TOTP_ENCRYPTION_KEY" -if [[ "${WAKER_MODE:-cron}" == "waker" ]]; then - required_secrets="${required_secrets} WAKER_SIGNING_KEY" - echo "Waker mode: callback receiver enabled; WAKER_SIGNING_KEY must be bound" -fi +case "${WAKER_SIGNING_KEY_EXPECTED:-}" in + bound) + required_secrets="${required_secrets} WAKER_SIGNING_KEY" + echo "Waker callback: WAKER_SIGNING_KEY configured — it must be bound on the version" + ;; + absent) + echo "Waker callback: no WAKER_SIGNING_KEY configured — /_waker/execute fails closed (500 signing_key_missing)" + ;; + *) + echo "::error::WAKER_SIGNING_KEY_EXPECTED must be 'bound' or 'absent' (got '${WAKER_SIGNING_KEY_EXPECTED:-}'); cannot verify the waker callback state." + exit 1 + ;; +esac missing_secrets="$(jq -r --arg names "$required_secrets" ' ([.resources.bindings[] | select(.type == "secret_text") | .name]) as $bound | ($names | split(" ")) @@ -88,11 +103,11 @@ if [[ "$live" != "$expected" ]]; then fi echo "TABLE_PREFIX: ${live:-}" -# Cron schedules gate. `wrangler deploy` syncs cron schedules from the config, so -# this is what actually proves the mode's promise: no schedule at all in waker -# mode with WAKER_TRIGGERS=remove, exactly `0 3 * * *` otherwise (native cron, or -# the dual-run transition). The deploy log never shows schedules, so without -# this gate only a human looking at the dashboard would notice a missed switch. +# Cron schedules gate. `wrangler deploy` syncs cron schedules from the config, +# and `[triggers]` is static in wrangler.toml — the pipeline never rewrites it, so +# the native Cron Trigger must always be there. Moving the schedule to waker alone +# is a separate change that deletes [triggers]; once merged, this gate fails until +# it is updated along with that change, which is exactly the review it asks for. account_id="$(sed -n 's/^account_id[[:space:]]*=[[:space:]]*"\([^"]*\)".*/\1/p' wrangler.toml | head -n 1)" if [[ -z "$account_id" ]]; then echo "::error::Cannot read account_id from wrangler.toml; cannot verify cron schedules." @@ -111,16 +126,8 @@ if ! jq -e '.success == true and (.result.schedules | type == "array")' \ exit 1 fi crons="$(jq -r '[.result.schedules[].cron] | sort | join(" ")' <<<"$schedules")" -if [[ "${WAKER_MODE:-cron}" == "waker" && "${WAKER_TRIGGERS:-keep}" == "remove" ]]; then - if [[ -n "$crons" ]]; then - echo "::error::Worker ${worker_name} still has cron schedule(s) '${crons}', but WAKER_MODE=waker + WAKER_TRIGGERS=remove promises none. Re-run the deploy after the [triggers] removal, or delete the schedule in the dashboard." - exit 1 - fi - echo "Cron schedules: none (waker is the only scheduler)" -else - if [[ "$crons" != "0 3 * * *" ]]; then - echo "::error::Worker ${worker_name} has cron schedule(s) '${crons:-}', expected exactly '0 3 * * *' (WAKER_MODE=${WAKER_MODE:-cron}, WAKER_TRIGGERS=${WAKER_TRIGGERS:-keep}). The native Cron Trigger must stay in this mode." - exit 1 - fi - echo "Cron schedules: 0 3 * * *" +if [[ "$crons" != "0 3 * * *" ]]; then + echo "::error::Worker ${worker_name} has cron schedule(s) '${crons:-}', expected exactly '0 3 * * *'. The native Cron Trigger lives in wrangler.toml's static [triggers] section and must stay deployed (waker is a parallel trigger, not a replacement, until [triggers] is removed in a dedicated change)." + exit 1 fi +echo "Cron schedules: 0 3 * * *" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 842390d..f2fc63b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -52,7 +52,7 @@ jobs: run: shellcheck .github/scripts/*.sh - name: Test deploy scripts - run: node --test .github/scripts/test-d1-migrations.mjs .github/scripts/test-deploy-checks.mjs .github/scripts/test-waker-mode.mjs + run: node --test .github/scripts/test-d1-migrations.mjs .github/scripts/test-deploy-checks.mjs .github/scripts/test-waker-deploy.mjs audit: name: Dependency audit diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 6329c91..1136815 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -99,20 +99,6 @@ jobs: exit 1 fi - # Optional second scheduler : rewrite the deploy - # config for WAKER_MODE=cron (default, native Cron Trigger) or - # WAKER_MODE=waker (callback mode; [triggers] removed unless - # WAKER_TRIGGERS=keep asks for the dual-run transition state). Validates - # its inputs and fails the deploy on an inconsistent combination instead - # of shipping a Worker with no scheduler at all. - - name: Configure waker mode - id: waker - env: - WAKER_MODE: ${{ vars.WAKER_MODE }} - WAKER_URL: ${{ vars.WAKER_URL }} - WAKER_TRIGGERS: ${{ vars.WAKER_TRIGGERS }} - run: node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON .github/scripts/configure-waker-mode.mjs - # Build before touching the database so a broken build never leaves a # migrated schema behind. - name: Build @@ -150,12 +136,19 @@ jobs: # or empty, so an empty value can never overwrite a live Cloudflare # Secret. The JSON lives only in $RUNNER_TEMP (mode 600) and is never # written to the repository workspace. + # + # WAKER_SIGNING_KEY is optional and mode-free: when the repository Secret + # exists it is injected (the callback receiver is then enabled); when it + # does not, the deploy still succeeds and /_waker/execute fails closed with + # 500 signing_key_missing. The resolved state is handed to the verify step + # so a version that was supposed to carry the key cannot silently ship + # without it. - name: Write secrets file + id: secrets env: JWT_SECRET: ${{ secrets.JWT_SECRET }} "SETUP_SECRET": ${{ secrets.SETUP_SECRET }} TOTP_ENCRYPTION_KEY: ${{ secrets.TOTP_ENCRYPTION_KEY }} - WAKER_MODE: ${{ steps.waker.outputs.mode }} WAKER_SIGNING_KEY: ${{ secrets.WAKER_SIGNING_KEY }} run: | set -euo pipefail @@ -165,7 +158,7 @@ jobs: exit 1 fi done - node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON -e ' + waker_key="$(node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON -e ' const fs = require("node:fs"); const path = require("node:path"); const file = path.join(process.env.RUNNER_TEMP, "secrets.json"); @@ -174,25 +167,27 @@ jobs: "SETUP_SECRET": process.env["SETUP_SECRET"], TOTP_ENCRYPTION_KEY: process.env.TOTP_ENCRYPTION_KEY, }; - // WAKER_SIGNING_KEY belongs to the waker mode only: cron-mode - // deploys do not inject it, and a waker-mode deploy must have it - // (the callback fails closed without it, so shipping that version - // would only surface as 500s at 03:00). - if (process.env.WAKER_MODE === "waker") { - const key = (process.env.WAKER_SIGNING_KEY ?? "").trim(); - if (key.length === 0) { - console.error("::error::GitHub Secret '\''WAKER_SIGNING_KEY'\'' is empty or missing; WAKER_MODE=waker requires it (create the hop project in the waker admin UI and store the signing key it shows once). Aborting deploy."); - process.exit(1); - } + // The signing key is the only switch of the callback: injected when + // the repository Secret exists, otherwise the callback answers 500 + // signing_key_missing and the native Cron Trigger is unaffected. + const key = (process.env.WAKER_SIGNING_KEY ?? "").trim(); + if (key.length > 0) { secrets.WAKER_SIGNING_KEY = key; + } else { + console.warn("WAKER_SIGNING_KEY is not configured — /_waker/execute will answer 500 signing_key_missing until it is set; the native Cron Trigger is unaffected."); } fs.writeFileSync( file, JSON.stringify(secrets, null, 2) + "\n", { mode: 0o600 }, ); - ' + process.stdout.write(key.length > 0 ? "bound" : "absent"); + ')" chmod 600 "$RUNNER_TEMP/secrets.json" + echo "waker_signing_key=${waker_key}" + if [ -n "${GITHUB_OUTPUT:-}" ]; then + echo "waker_signing_key=${waker_key}" >> "$GITHUB_OUTPUT" + fi # Web and worker were built above; deploy the worker directly so wrangler # can record the uploaded version ID for the verification step. @@ -219,8 +214,7 @@ jobs: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} WRANGLER_OUTPUT_FILE_PATH: ${{ runner.temp }}/wrangler-output.ndjson TABLE_PREFIX: ${{ steps.prefix.outputs.table_prefix }} - WAKER_MODE: ${{ steps.waker.outputs.mode }} - WAKER_TRIGGERS: ${{ steps.waker.outputs.triggers }} + WAKER_SIGNING_KEY_EXPECTED: ${{ steps.secrets.outputs.waker_signing_key }} run: bash ../../.github/scripts/verify-deployment.sh # Probes vars.APP_URL when it is configured; otherwise resolves the diff --git a/README.md b/README.md index b628e41..f8d037b 100644 --- a/README.md +++ b/README.md @@ -195,38 +195,32 @@ Navigate to your deployed URL and register — the first account is automaticall --- -## Optional: schedule with waker (dual mode) +## Optional: also schedule with waker (dual run) Hop's nightly cleanup (expired `verifications` rows, plus `totp_used` rows older than 90 s) runs on the Cloudflare Cron Trigger `0 3 * * *` declared in `apps/worker/wrangler.toml`. A deployment -can optionally move that schedule to [waker](https://github.com/WorkerHub/waker) instead: the -platform calls `POST /_waker/execute`, which runs the **same** cleanup function as `scheduled()`. -The integration is off by default and adds no dependency for self-hosted installs — with no -`WAKER_*` variable set, nothing changes and `/_waker/execute` answers an explicit JSON 404 -(never the SPA's 200 HTML, which waker would read as a successful run). +can also let [waker](https://github.com/WorkerHub/waker) deliver the same job over HTTP: the +platform POSTs `/_waker/execute`, which runs the **same** cleanup function as `scheduled()`. -### What each mode deploys +There is nothing to switch on: one input decides everything — the signing key. -| `WAKER_MODE` | `WAKER_TRIGGERS` | `[triggers]` | `/_waker/execute` | secrets file | -|---|---|---|---|---| -| `cron` (default) | `keep` (default) | kept, `0 3 * * *` | 404 | unchanged | -| `waker` | `keep` (default) → dual run | kept, `0 3 * * *` | enabled | + `WAKER_SIGNING_KEY` | -| `waker` | `remove` (the switch) | removed | enabled | + `WAKER_SIGNING_KEY` | +| `WAKER_SIGNING_KEY` | `/_waker/execute` | Native Cron Trigger | State | +|---|---|---|---| +| Secret absent (or empty) | 500 `signing_key_missing` (JSON) | `0 3 * * *` | fail closed — nothing unverified ever runs | +| Secret present | signature verified, then the cleanup runs | `0 3 * * *` | dual run; the cleanup is idempotent | -Removing the Cron Trigger is a separate, explicit switch: `WAKER_TRIGGERS` defaults to `keep` in -both modes, so switching `WAKER_MODE` alone never leaves the app unscheduled. `WAKER_MODE=cron` -together with `WAKER_TRIGGERS=remove` fails the deploy: it would leave the app with no scheduler at -all. The deploy writes `WAKER_MODE` explicitly even in `cron` mode, because `keep_vars = true` -would otherwise leave a previous `waker` value alive on the Worker. +`[triggers]` is static: it lives in `apps/worker/wrangler.toml` and the pipeline never rewrites it, +so the native trigger is deployed in both states. There is no mode variable, platform URL or +schedule switch to configure — the deployment variables from the earlier dual-mode design are gone; +if your repository still has them, they are ignored and can be deleted. Any path under `/_waker` +that is not routed answers JSON (404 or the SDK's stable error code) — never the SPA's 200 HTML, +which waker would read as a successful run. -### Variables +### The only input: `WAKER_SIGNING_KEY` -| Variable | Type | Required | Source | Description | -|---|---|---|---|---| -| `WAKER_MODE` | Var | No | GitHub `WAKER_MODE` → CI | `cron` (default, native Cron Trigger) or `waker` (platform callback). | -| `WAKER_URL` | Var | waker only | GitHub `WAKER_URL` → CI | Platform base URL, e.g. `https://waker.oneboy.app`. Plain configuration: the deploy refuses `WAKER_MODE=waker` without it, and at runtime a missing value closes the receiver (404). | -| `WAKER_TRIGGERS` | Var | No | GitHub `WAKER_TRIGGERS` → CI | `keep` (default: leave the Cron Trigger in place — the dual-run transition) or `remove` (waker becomes the only scheduler; requires `WAKER_MODE=waker`). | -| `WAKER_SIGNING_KEY` | **Secret** | waker only | GitHub Secret → CI | The hop project's callback signing key, shown **once** when the project is created in the waker UI. Injected only in waker mode; a waker-mode deploy without it fails, and a Worker without it answers 500 `signing_key_missing` instead of running an unverified job. | +| Secret | Required | Source | Description | +|---|---|---|---| +| `WAKER_SIGNING_KEY` | No | GitHub Secret → CI | The hop project's callback signing key, shown **once** when the project is created in the waker UI. When the Secret exists the deploy injects it through `--secrets-file`; when it does not, the deploy still succeeds and the callback answers 500 `signing_key_missing` instead of running an unverified job. Never logged, never committed. | ### Create the waker job (once, in the waker UI) @@ -243,26 +237,26 @@ job — these values are frozen, copy them verbatim (the job name must match the | `maxRetries` / `backoffSeconds` | `2` / `60` | | `timeoutSeconds` / `jitterSeconds` | `30` / `0` | -### Switch and roll back +### Dual run, switching to waker alone, and rolling back 1. Create the `hop` project in waker (callback URL = this Worker's public base URL) and store the signing key it shows once as the GitHub Secret `WAKER_SIGNING_KEY` (same path as the other - runtime secrets — never in the repository). Do not create the job yet: it would start - delivering before the receiver is live. -2. Set `WAKER_MODE=waker` and `WAKER_URL=`, leave `WAKER_TRIGGERS` at its - default `keep`, and deploy. The receiver is live and the Cron Trigger still runs (dual run; - the cleanup is idempotent). -3. Create and enable the `nightly-cleanup` job in waker, then watch one full daily cycle: + runtime secrets — never in the repository). Deploy: the receiver is live next to the Cron + Trigger — the dual-run state, harmless because the cleanup is idempotent. +2. Create and enable the `nightly-cleanup` job in waker, then watch one full daily cycle: waker's executions list shows a success, and the Worker log has `"event":"nightly_cleanup","source":"waker"` with the delete counts and duration. -4. Set `WAKER_TRIGGERS=remove` and deploy again — the Cron Trigger is removed and waker is the - only scheduler. +3. Switch over in a separate, small change: delete the `[triggers]` section from + `apps/worker/wrangler.toml` and merge it on its own. waker is then the only scheduler; nothing + else has to change. + +Rollback: revert that commit (the `[triggers]` section comes back) and redeploy — the Cron Trigger +is back, and waker can keep delivering in parallel or be paused in its UI. No database rollback is +needed: `schema_v3` only adds `{prefix}waker_executions`, which nothing else reads. -Rollback: set `WAKER_MODE=cron` (leave `WAKER_TRIGGERS` unset) and redeploy; `[triggers]` is back -and `/_waker/execute` answers 404. Pause or delete the job in waker so it stops delivering. -No database rollback is needed: `schema_v3` only adds `{prefix}waker_executions`, which the -cron-mode code never reads. The `WAKER_SIGNING_KEY` Worker secret may stay bound (a secrets file -is additive) — harmless in cron mode, removable in the dashboard if you want it gone. +To close the callback instead, delete the Worker's `WAKER_SIGNING_KEY` secret in the dashboard (the +deploy only ever adds secrets, it never removes one): `/_waker/execute` then answers 500 +`signing_key_missing`. Leaving the key bound is harmless as long as the waker job is paused. Cleanup results are logged as structured JSON (`nightly_cleanup` with counts, duration and the trigger source; rejected callbacks as `waker_callback_rejected` with the HTTP status and the @@ -409,10 +403,7 @@ GET /:slug → 302 to destination URL | `JWT_SECRET` | Secret | Yes | GitHub Secret → CI | HS256 signing key, ≥ 32 chars | | `TOTP_ENCRYPTION_KEY` | Secret | Yes | GitHub Secret → CI | Hex string from `openssl rand -hex 32` | | `SETUP_SECRET` | Secret | Yes | GitHub Secret → CI | Secret path for triggering DB migrations via HTTP | -| `WAKER_MODE` | Var | No | GitHub `WAKER_MODE` → CI | `cron` (default, native Cron Trigger) or `waker` (callback). See [Optional: schedule with waker](#optional-schedule-with-waker-dual-mode). | -| `WAKER_URL` | Var | waker only | GitHub `WAKER_URL` → CI | Platform base URL; `WAKER_MODE=waker` fails to deploy without it, and a missing value closes the receiver at runtime. | -| `WAKER_TRIGGERS` | Var | No | GitHub `WAKER_TRIGGERS` → CI | `keep` (default: dual run) or `remove` (waker only; the platform becomes the sole scheduler). | -| `WAKER_SIGNING_KEY` | Secret | waker only | GitHub Secret → CI | Callback signing key, shown once when the project is created in waker. Never logged or committed. | +| `WAKER_SIGNING_KEY` | Secret | No | GitHub Secret → CI | The hop project's callback signing key, shown once when the project is created in waker. Present → the deploy injects it and `/_waker/execute` verifies and runs the cleanup; absent → the deploy still succeeds and the callback answers 500 `signing_key_missing`. See [Optional: also schedule with waker](#optional-also-schedule-with-waker-dual-run). Never logged or committed. | --- diff --git a/README.zh-CN.md b/README.zh-CN.md index f2abc22..eff1d4d 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -176,36 +176,30 @@ curl -X POST https://your-worker.workers.dev/api/setup \ --- -## 可选:用 waker 调度(双模式) +## 可选:同时用 waker 调度(双跑) -hop 的每日清理(过期 `verifications` 行 + 超过 90 秒的 `totp_used` 行)默认由 -`apps/worker/wrangler.toml` 里的 Cloudflare Cron Trigger `0 3 * * *` 驱动。部署可以选择把这套 -调度交给 [waker](https://github.com/WorkerHub/waker):平台回调 `POST /_waker/execute`,执行的是与 -`scheduled()` **同一个**清理函数。该接入默认关闭,对开源自部署零依赖——不配置任何 `WAKER_*` -变量时行为与迁移前完全一致,`/_waker/execute` 返回显式 JSON 404(不会落到 SPA 的 200 HTML, -否则平台会把「没跑」当成「跑成功」)。 +hop 的每日清理(过期 `verifications` 行 + 超过 90 秒的 `totp_used` 行)由 +`apps/worker/wrangler.toml` 里的 Cloudflare Cron Trigger `0 3 * * *` 驱动。部署也可以让 +[waker](https://github.com/WorkerHub/waker) 通过 HTTP 投递同一份任务:平台回调 +`POST /_waker/execute`,执行的是与 `scheduled()` **同一个**清理函数。 -### 两种模式各自部署什么 +没有开关要配,只认一把签名密钥: -| `WAKER_MODE` | `WAKER_TRIGGERS` | `[triggers]` | `/_waker/execute` | secrets 文件 | -|---|---|---|---|---| -| `cron`(默认) | `keep`(默认) | 保留 `0 3 * * *` | 404 | 不变 | -| `waker` | `keep`(默认,双跑过渡) | 保留 `0 3 * * *` | 启用 | 额外注入 `WAKER_SIGNING_KEY` | -| `waker` | `remove`(切换动作) | 删除 | 启用 | 额外注入 `WAKER_SIGNING_KEY` | +| `WAKER_SIGNING_KEY` | `/_waker/execute` | 原生 Cron Trigger | 状态 | +|---|---|---|---| +| 未配置(或为空) | 500 `signing_key_missing`(JSON) | `0 3 * * *` | fail closed —— 绝不执行未验签的任务 | +| 已配置 | 验签通过后执行清理 | `0 3 * * *` | 双跑;清理天然幂等 | -摘除 Cron Trigger 是一个独立的显式动作:`WAKER_TRIGGERS` 在两种模式下都默认 `keep`,只改 -`WAKER_MODE` 永远不会让应用失去调度。`WAKER_MODE=cron` 与 `WAKER_TRIGGERS=remove` 的组合会让部署 -直接失败——那等于没有任何调度器。即使 cron 模式,部署也会显式写入 `WAKER_MODE`,因为 -`keep_vars = true` 会让上一次 waker 模式的值在 Worker 上继续存活。 +`[triggers]` 是静态的:它写在 `apps/worker/wrangler.toml` 里、流水线从不改写,所以两种状态下 +原生 Cron Trigger 都会部署。没有模式变量、没有平台地址、没有调度开关要配——旧版双模式的那些部署 +变量已经删除,仓库里若还留着也会被代码忽略,可以一并删掉。`/_waker` 下任何未挂载的路径都回 JSON +(404 或 SDK 的稳定错误码),永远不会落到 SPA 的 200 HTML(否则平台会把「没跑」当成「跑成功」)。 -### 变量 +### 唯一的输入:`WAKER_SIGNING_KEY` -| 变量 | 类型 | 必填 | 来源 | 描述 | -|---|---|---|---|---| -| `WAKER_MODE` | 变量 | 否 | GitHub `WAKER_MODE` → CI | `cron`(默认,原生 Cron Trigger)或 `waker`(平台回调)。 | -| `WAKER_URL` | 变量 | 仅 waker | GitHub `WAKER_URL` → CI | 平台根地址,例如 `https://waker.oneboy.app`。明文配置:waker 模式缺它会部署失败,运行时缺失也会自动关闭 receiver(404)。 | -| `WAKER_TRIGGERS` | 变量 | 否 | GitHub `WAKER_TRIGGERS` → CI | `keep`(默认:保留 Cron Trigger,双跑过渡)或 `remove`(平台为唯一调度源,要求 `WAKER_MODE=waker`)。 | -| `WAKER_SIGNING_KEY` | **密钥** | 仅 waker | GitHub Secret → CI | hop 项目的回调签名密钥,在 waker 管理面建项目时**一次性**展示。只在 waker 模式注入;缺失则部署失败,Worker 侧缺 key 时回 500 `signing_key_missing`,绝不执行未验签的任务。 | +| 密钥 | 必填 | 来源 | 描述 | +|---|---|---|---| +| `WAKER_SIGNING_KEY` | 否 | GitHub Secret → CI | hop 项目的回调签名密钥,在 waker 管理面建项目时**一次性**展示。仓库里有这个 Secret 时,部署经 `--secrets-file` 注入;没有时部署照样成功,只是回调回 500 `signing_key_missing`,绝不执行未验签的任务。永不进日志、永不进仓库。 | ### 在 waker 管理面建任务(一次) @@ -222,22 +216,22 @@ hop 的每日清理(过期 `verifications` 行 + 超过 90 秒的 `totp_used` | `maxRetries` / `backoffSeconds` | `2` / `60` | | `timeoutSeconds` / `jitterSeconds` | `30` / `0` | -### 切换与回滚 +### 双跑、切到只跑 waker、以及回滚 1. 在 waker 建 `hop` 项目(回调地址填本 Worker 的公网根地址),把一次性展示的 signing key - 存进 GitHub Secret `WAKER_SIGNING_KEY`(与现有运行时密钥同路,绝不进仓库)。 - **先不要建任务**:任务一旦存在就会开始投递,而 receiver 还没上线。 -2. 设 `WAKER_MODE=waker`、`WAKER_URL=<平台地址>`,`WAKER_TRIGGERS` 保持默认 `keep` 后部署。 - receiver 上线,Cron Trigger 仍在跑(双跑;清理天然幂等)。 -3. 在 waker 建并启用 `nightly-cleanup` 任务,观察一个完整日周期:waker 的执行记录有成功条目, + 存进 GitHub Secret `WAKER_SIGNING_KEY`(与现有运行时密钥同路,绝不进仓库)后部署:receiver + 就此上线,Cron Trigger 继续跑——这就是双跑态,清理幂等,重复执行无副作用。 +2. 在 waker 建并启用 `nightly-cleanup` 任务,观察一个完整日周期:waker 的执行记录有成功条目, Worker 日志出现 `"event":"nightly_cleanup","source":"waker"` 及删除计数与耗时。 -4. 改 `WAKER_TRIGGERS=remove` 再部署:`[triggers]` 被摘除,平台成为唯一调度源。 +3. 切换放在单独一个小变更里:删除 `apps/worker/wrangler.toml` 的 `[triggers]` 段,单独提 PR 合并。 + 之后 waker 是唯一调度源,其余什么都不用改。 + +回滚:还原那个提交(`[triggers]` 段回来)重新部署即可——Cron Trigger 恢复,waker 可以继续并行 +投递,也可以在管理面停用任务。数据库无需回滚:`schema_v3` 只加法创建 `{prefix}waker_executions`, +没有别的代码读它。 -回滚:把 `WAKER_MODE` 改回 `cron`(`WAKER_TRIGGERS` 留空即可)重新部署——`[triggers]` 恢复、 -`/_waker/execute` 回到 404;在 waker 管理面停用或删除该任务,避免平台继续投递。 -数据库无需回滚:`schema_v3` 只加法创建 `{prefix}waker_executions`,cron 模式代码从不读它。 -`WAKER_SIGNING_KEY` 的 Worker 绑定可能仍在(secrets 文件只增不删),cron 模式下无影响, -需要时可在控制台删除。 +若只想关掉回调:在控制台删掉 Worker 的 `WAKER_SIGNING_KEY` 密钥(部署只会新增密钥、从不删除), +`/_waker/execute` 随后回 500 `signing_key_missing`;任务已停用时留着这把密钥也无影响。 清理结果以结构化 JSON 记录(`nightly_cleanup` 含计数、耗时与触发来源;被拒回调记 `waker_callback_rejected`,含 HTTP 状态与 SDK 错误码,如 `invalid_signature`、 @@ -382,10 +376,7 @@ GET /:slug → 302 跳转到目标 URL | `JWT_SECRET` | 密钥 | 是 | GitHub Secret → CI | HS256 签名密钥,≥ 32 字符 | | `TOTP_ENCRYPTION_KEY` | 密钥 | 是 | GitHub Secret → CI | 来自 `openssl rand -hex 32` 的十六进制字符串 | | `SETUP_SECRET` | 密钥 | 是 | GitHub Secret → CI | 通过 HTTP 触发数据库迁移的密钥路径 | -| `WAKER_MODE` | 变量 | 否 | GitHub `WAKER_MODE` → CI | `cron`(默认,原生 Cron Trigger)或 `waker`(平台回调)。见 [可选:用 waker 调度](#可选用-waker-调度双模式)。 | -| `WAKER_URL` | 变量 | 仅 waker | GitHub `WAKER_URL` → CI | 平台根地址;waker 模式缺它部署失败,运行时缺失会自动关闭 receiver。 | -| `WAKER_TRIGGERS` | 变量 | 否 | GitHub `WAKER_TRIGGERS` → CI | `keep`(默认:双跑)或 `remove`(仅 waker,平台为唯一调度源)。 | -| `WAKER_SIGNING_KEY` | 密钥 | 仅 waker | GitHub Secret → CI | 回调签名密钥,建项目时一次性展示;不进日志、不进仓库。 | +| `WAKER_SIGNING_KEY` | 密钥 | 否 | GitHub Secret → CI | hop 项目的回调签名密钥,建项目时一次性展示。有值 → 部署注入,`/_waker/execute` 验签后执行清理;无值 → 部署照常成功,回调回 500 `signing_key_missing`。见 [可选:同时用 waker 调度](#可选同时用-waker-调度双跑)。不进日志、不进仓库。 | --- diff --git a/apps/worker/.dev.vars.example b/apps/worker/.dev.vars.example index e3ea0eb..6625e69 100644 --- a/apps/worker/.dev.vars.example +++ b/apps/worker/.dev.vars.example @@ -23,14 +23,9 @@ TOTP_ENCRYPTION_KEY= SETUP_SECRET= # ─── Optional waker integration ─────────────────────────────────────────────── -# Default is the native Cron Trigger: leave WAKER_MODE unset (or set "cron") and -# /_waker/execute answers 404. To try the callback locally, set all three: -# WAKER_MODE=waker -# WAKER_URL=http://localhost:8788 (any plain http(s) URL; it closes the -# receiver when empty and labels logs) -# WAKER_SIGNING_KEY=... (a locally generated test key — never -# the production one; missing key makes -# the callback fail closed with 500) -# WAKER_MODE= -# WAKER_URL= +# The native Cron Trigger is the default and always on. The waker callback is +# switched by the signing key alone: with WAKER_SIGNING_KEY set here, a locally +# signed POST to /_waker/execute verifies and runs the same cleanup; without it +# the callback fails closed with 500 signing_key_missing. Use a locally generated +# test key — never the production one. # WAKER_SIGNING_KEY= diff --git a/apps/worker/src/index.ts b/apps/worker/src/index.ts index d779619..7433679 100644 --- a/apps/worker/src/index.ts +++ b/apps/worker/src/index.ts @@ -123,12 +123,13 @@ app.all('/api/*', (c) => { return apiError(c, 404, 'NOT_FOUND', 'Not found'); }); -// ─── waker callback (optional second scheduler) ─────────────────────────────── +// ─── waker callback (optional second trigger, dual run) ─────────────────────── // Registered before the short-link route and the SPA fallback so the whole -// /_waker prefix is decided here. When the integration is off (the default), -// both the exact path and its children answer a JSON 404 — never the SPA's 200 -// HTML, which waker would mistake for a successful execution. In waker mode the -// sub-app hands POST /_waker/execute to the SDK receiver (see routes/waker.ts). +// /_waker prefix is decided here. The sub-app hands POST /_waker/execute to the +// SDK receiver; whether it actually runs is decided by one thing only — the +// signing key binding (present: verify + run the same cleanup as scheduled(); +// absent: 500 signing_key_missing). Every path under the prefix answers JSON, +// never the SPA's 200 HTML, which waker would mistake for a successful run. app.all(CALLBACK_MOUNT_PATH, (c) => { return apiError(c, 404, 'NOT_FOUND', 'Not found'); }); @@ -175,8 +176,9 @@ export { app }; export default { fetch: app.fetch, - // L-2: Nightly cleanup of expired rows (cron "0 3 * * *"; in waker mode the - // platform calls the same runCleanup through /_waker/execute). + // L-2: Nightly cleanup of expired rows (native Cron Trigger "0 3 * * *", + // static in wrangler.toml; the waker callback runs the same runCleanup through + // /_waker/execute while its signing key is bound — the dual-run state). async scheduled( _event: ScheduledController, env: Env, diff --git a/apps/worker/src/routes/waker.ts b/apps/worker/src/routes/waker.ts index 4384c4c..51c592e 100644 --- a/apps/worker/src/routes/waker.ts +++ b/apps/worker/src/routes/waker.ts @@ -1,47 +1,27 @@ -// HTTP side of the optional waker integration: mount the SDK's receiver at -// /_waker and answer an explicit 404 whenever the integration is off. +// HTTP side of the waker integration: mount the SDK's receiver at /_waker. // -// Why the 404 matters: wrangler.toml serves the SPA with -// `not_found_handling = "single-page-application"`, so an unmounted -// /_waker/execute would fall through to the SPA and answer **200 HTML**. -// waker treats any 2xx as "execution succeeded", so that would silently report -// a nightly cleanup that never ran. Every non-waker state therefore answers a -// JSON 404 (spec v1.0 §2). +// The signing key is the **only** switch — there is no mode variable and no +// second gate: +// - `WAKER_SIGNING_KEY` bound (GitHub Secret → `--secrets-file`) → the SDK +// verifies the HMAC signature, then runs the very same cleanup as +// `scheduled()` (src/services/waker.ts); +// - no key → the SDK fails closed with 500 `signing_key_missing`; it never +// runs a job it could not verify. // -// "Off" means either WAKER_MODE is unset/`cron`, or WAKER_MODE=waker without -// WAKER_URL — a missing WAKER_URL closes the receiver instead of leaving a -// half-configured endpoint open, and the native trigger keeps working. +// Everything under /_waker answers JSON, never the SPA's 200 HTML: wrangler.toml +// serves the SPA with `not_found_handling = "single-page-application"`, and +// waker treats any 2xx as "execution succeeded" — a fall-through would report a +// nightly cleanup that never ran. The receiver answers the protocol errors +// itself; a path it does not route becomes a JSON 404 (host app's notFound). import { Hono } from 'hono'; import { apiError } from '../lib/errors.js'; import { createWakerCallbackReceiver } from '../services/waker.js'; import type { Env, Variables } from '../types.js'; -import { - CALLBACK_MOUNT_PATH, - isWakerEnabled, - readEnvString, - WAKER_URL_ENV, -} from '../waker/index.js'; +import { CALLBACK_MOUNT_PATH } from '../waker/index.js'; type AppEnv = { Bindings: Env; Variables: Variables }; -/** True only when the receiver should answer: waker mode *and* a platform URL. */ -function callbackEnabled(env: Env): boolean { - return ( - isWakerEnabled(envLike(env)) && - readEnvString(envLike(env), WAKER_URL_ENV) !== null - ); -} - -/** - * The SDK types the env as `Record` so it can be used without - * depending on any downstream binding types. Env is an interface (no index - * signature), hence the cast — the SDK only reads named string keys. - */ -function envLike(env: Env): Record { - return env as unknown as Record; -} - /** * Hand one request to the SDK's receiver. * @@ -60,6 +40,9 @@ function forwardToReceiver( CALLBACK_MOUNT_PATH, createWakerCallbackReceiver(env) as unknown as Hono, ); + // Unrouted paths inside the mount must still answer JSON (404), so /_waker + // can never fall through to the SPA fallback below it in src/index.ts. + host.notFound((c) => apiError(c, 404, 'NOT_FOUND', 'Not found')); return host.fetch(request, env); } @@ -96,19 +79,6 @@ export function wakerRoutes(): Hono { const routes = new Hono(); routes.all('*', async (c) => { - if (!callbackEnabled(c.env)) { - if (isWakerEnabled(envLike(c.env))) { - console.warn( - JSON.stringify({ - level: 'warn', - event: 'waker_callback_disabled', - reason: 'missing_url', - env: WAKER_URL_ENV, - }), - ); - } - return apiError(c, 404, 'waker_disabled', 'Waker callback is disabled'); - } return logRejection(await forwardToReceiver(c.req.raw, c.env)); }); diff --git a/apps/worker/src/services/waker.ts b/apps/worker/src/services/waker.ts index da42d1e..e4bc631 100644 --- a/apps/worker/src/services/waker.ts +++ b/apps/worker/src/services/waker.ts @@ -40,8 +40,9 @@ export const WAKER_EXECUTIONS_TABLE = 'waker_executions'; * Build a receiver bound to this request's env. * * The signing key is read by the SDK from `env.WAKER_SIGNING_KEY` (secrets - * only). Missing key → the SDK fails closed with 500 `signing_key_missing`; - * it never runs a job that could not be verified. + * only) and is the integration's only switch: present → verify then run this + * handler; absent → the SDK fails closed with 500 `signing_key_missing`, so it + * never runs a job that could not be verified. * * Built per request because the ledger table name depends on TABLE_PREFIX and * the key on the bindings, both only known at request time. Construction does diff --git a/apps/worker/src/types.ts b/apps/worker/src/types.ts index 3e149c9..4ee341d 100644 --- a/apps/worker/src/types.ts +++ b/apps/worker/src/types.ts @@ -19,21 +19,14 @@ export interface Env { APP_ORIGIN?: string; TABLE_PREFIX?: string; - // Waker integration (optional second scheduler; unset = native cron). - // WAKER_MODE / WAKER_URL are written into [vars] by the deploy workflow from - // GitHub variables (cron is the default when unset). The callback receiver is - // only mounted when WAKER_MODE=waker and WAKER_URL is non-empty; without a - // URL it stays closed and the native Cron Trigger is unaffected. - WAKER_MODE?: string; - WAKER_URL?: string; - // Secrets JWT_SECRET: string; TOTP_ENCRYPTION_KEY: string; SETUP_SECRET: string; - // Waker project signing key (callback HMAC verification). Secrets only: - // GitHub Secrets → `wrangler deploy --secrets-file`. Missing in waker mode - // makes the callback fail closed with 500 `signing_key_missing`. + // Waker project signing key (callback HMAC verification) — and the callback's + // only switch: bound → /_waker/execute verifies then runs the same cleanup as + // scheduled(); absent → it fails closed with 500 `signing_key_missing`. + // Secrets only: GitHub Secret → `wrangler deploy --secrets-file`. WAKER_SIGNING_KEY?: string; } diff --git a/apps/worker/src/waker/README.md b/apps/worker/src/waker/README.md index a8cdb04..cb5555e 100644 --- a/apps/worker/src/waker/README.md +++ b/apps/worker/src/waker/README.md @@ -18,7 +18,10 @@ (`cp client/src/*.ts hop/apps/worker/src/waker/`),并把上面表格的版本与 commit 一起更新。 2. 升级时必须对照 waker 的冻结契约测试(`tests/client.test.ts` 断言 SDK 与平台逐项一致)确认版本; 协议常量(签名规范串、头名、时间窗、`/_waker` 路径)漂移会让回调静默失败。 -3. hop 侧只用它的模式判定(`isWakerEnabled` / `readEnvString` / `WAKER_URL_ENV`)、receiver - (`createWakerReceiver`)与 D1 幂等账本(`createD1ExecutionLedger`);业务接线在 - `src/services/waker.ts`,挂载在 `src/routes/waker.ts`。注册客户端(`client.ts`)在 hop 里 - 不使用——注册路线是「用户在 waker 管理面手动建项目与任务一次」(见 README 的双模式部署说明)。 +3. hop 侧只用它的 receiver(`createWakerReceiver`,验签/幂等/错误码全在 SDK 内)、 + D1 幂等账本(`createD1ExecutionLedger`)与协议常量(`CALLBACK_MOUNT_PATH`);业务接线在 + `src/services/waker.ts`,挂载在 `src/routes/waker.ts`。启停**只认 signing key 绑定** + (`WAKER_SIGNING_KEY`):有 key 则验签后执行,无 key 由 SDK fail closed 回 500 + `signing_key_missing`——hop 侧不读 `modes.ts` 的模式判定(hop 没有任何模式变量;该文件属于上游 + 逐字拷贝,保留但不引用),`client.ts` 的注册客户端在 hop 里也不使用:注册路线是「用户在 waker + 管理面手动建项目与任务」(见 README 的 waker 说明)。 diff --git a/apps/worker/test/waker-callback.test.ts b/apps/worker/test/waker-callback.test.ts index c665d96..9d1305a 100644 --- a/apps/worker/test/waker-callback.test.ts +++ b/apps/worker/test/waker-callback.test.ts @@ -1,6 +1,7 @@ // Waker callback path (spec v1.0 §2/§4): signature verification, replay -// window, executionId deduplication, fail-closed behaviour without a signing -// key, and the explicit 404 whenever the integration is off. +// window, executionId deduplication, and the two states of the only switch — +// signing key bound → the callback runs, absent → it fails closed with 500 +// `signing_key_missing` (never the SPA's 200 HTML). // // The request is signed here with WebCrypto exactly as documented by the // frozen protocol (`\n\n\n`, HMAC-SHA256, @@ -100,8 +101,6 @@ function wakerEnv(overrides: Partial = {}, prefix = 'hop'): TestEnv { return makeEnv({ DB: new D1Mock(true, prefix) as unknown as Env['DB'], TABLE_PREFIX: prefix, - WAKER_MODE: 'waker', - WAKER_URL: 'https://waker.example.com', WAKER_SIGNING_KEY: SIGNING_KEY, ...overrides, }); @@ -138,23 +137,22 @@ function callbackPath(): string { return `${CALLBACK_MOUNT_PATH}/execute`; } -// ─── when the integration is off, the path must answer 404 explicitly ──────── +// ─── the signing key is the only switch: no mode variable exists ───────────── for (const scenario of [ - { name: 'WAKER_MODE 未设置(默认 cron)', mode: undefined, url: undefined }, - { name: 'WAKER_MODE=cron', mode: 'cron', url: 'https://waker.example.com' }, { - name: 'WAKER_MODE=waker 但 WAKER_URL 缺失(receiver 自动关闭)', - mode: 'waker', - url: undefined, + name: 'WAKER_SIGNING_KEY 未绑定', + overrides: { WAKER_SIGNING_KEY: undefined }, + }, + { + name: 'WAKER_SIGNING_KEY 为空字符串', + overrides: { WAKER_SIGNING_KEY: ' ' }, }, ]) { - test(`非 waker 运行时 ${scenario.name} → /_waker/execute 显式 404,不是 SPA 200`, async () => { - const ctx = makeEnv({ - WAKER_MODE: scenario.mode, - WAKER_URL: scenario.url, - WAKER_SIGNING_KEY: SIGNING_KEY, - }); + test(`${scenario.name} → 500 signing_key_missing(JSON,绝不是 SPA 的 200 HTML),清理不执行`, async () => { + const ctx = wakerEnv(scenario.overrides); + seedExpiredRows(ctx); + // A correctly signed request: only the missing key can stop it. const signed = await signedRequest(); const res = await request( app, @@ -162,16 +160,26 @@ for (const scenario of [ { method: 'POST', headers: signed.headers, body: signed.body }, ctx, ); - // ASSETS (the SPA fallback) would answer 200 'assets'; waker reads any 2xx - // as a successful execution, so this must be a JSON 404 instead. - assert.equal(res.status, 404); + // The SPA fallback would answer 200 'assets'; waker reads any 2xx as a + // successful execution, so a missing key must never reach it. + assert.notEqual(res.status, 200); + assert.equal(res.status, 500); assert.match(res.headers.get('content-type') ?? '', /application\/json/); - const body = await res.json(); - assert.equal(body.code, 'waker_disabled'); - assert.equal(countRows(ctx, 'verifications', ''), 0); + assert.equal((await res.json()).error.code, 'signing_key_missing'); + assert.equal(countRows(ctx, 'verifications'), 2); + assert.equal(countRows(ctx, 'totp_used'), 2); + assert.equal(countRows(ctx, 'waker_executions'), 0); }); } +test('无 WAKER_SIGNING_KEY 时未签名的 POST 也是 JSON 4xx(不落到 SPA)', async () => { + const ctx = makeEnv({ WAKER_SIGNING_KEY: undefined }); + const res = await request(app, callbackPath(), { method: 'POST' }, ctx); + assert.equal(res.status, 400); + assert.match(res.headers.get('content-type') ?? '', /application\/json/); + assert.equal((await res.json()).error.code, 'invalid_request'); +}); + test('GET /_waker(无 /execute)也是 JSON 404,不落到短链路由或 SPA', async () => { const ctx = wakerEnv(); const res = await request(app, CALLBACK_MOUNT_PATH, { method: 'GET' }, ctx); @@ -179,9 +187,21 @@ test('GET /_waker(无 /execute)也是 JSON 404,不落到短链路由或 SP assert.match(res.headers.get('content-type') ?? '', /application\/json/); }); +test('/_waker 下其它未挂载路径也是 JSON 404,不落到 SPA', async () => { + const ctx = wakerEnv(); + const res = await request( + app, + `${CALLBACK_MOUNT_PATH}/unknown`, + { method: 'GET' }, + ctx, + ); + assert.equal(res.status, 404); + assert.match(res.headers.get('content-type') ?? '', /application\/json/); +}); + // ─── happy path: same cleanup as the native trigger, counts in the response ── -test('验签通过 → 执行清理、返回计数、executionId 落 {prefix}waker_executions', async () => { +test('有 WAKER_SIGNING_KEY → 验签通过即执行清理、返回计数、executionId 落 {prefix}waker_executions', async () => { const ctx = wakerEnv(); seedExpiredRows(ctx); const signed = await signedRequest({ executionId: 'exec-ok-1' }); @@ -357,24 +377,6 @@ test('未声明的任务名(与 waker 管理面注册名不一致)→ 404 un assert.equal(countRows(ctx, 'verifications'), 2); }); -test('waker 模式但缺 WAKER_SIGNING_KEY → 500 signing_key_missing(失败关闭,不裸奔执行)', async () => { - const ctx = wakerEnv({ WAKER_SIGNING_KEY: undefined }); - seedExpiredRows(ctx); - const signed = await signedRequest(); - - const res = await request( - app, - callbackPath(), - { method: 'POST', headers: signed.headers, body: signed.body }, - ctx, - ); - - assert.equal(res.status, 500); - assert.equal((await res.json()).error.code, 'signing_key_missing'); - assert.equal(countRows(ctx, 'verifications'), 2); - assert.equal(countRows(ctx, 'waker_executions'), 0); -}); - // ─── replay + idempotency ──────────────────────────────────────────────────── test('同一 executionId 重放 → duplicate 且无副作用(清理不重跑)', async () => { diff --git a/apps/worker/wrangler.toml b/apps/worker/wrangler.toml index 06b8c47..cead569 100644 --- a/apps/worker/wrangler.toml +++ b/apps/worker/wrangler.toml @@ -8,10 +8,6 @@ keep_vars = true # TABLE_PREFIX is config-managed: CI replaces this placeholder with the # resolved GitHub variable vars.TABLE_PREFIX before wrangler uploads the # version, so the binding always matches the prefix the migrations used. -# -# WAKER_MODE / WAKER_URL are also written here by the deploy workflow -# (.github/scripts/configure-waker-mode.mjs) when the optional waker scheduling -# mode is enabled — do not add them by hand (see the README's waker section). [vars] TABLE_PREFIX = "TABLE_PREFIX_PLACEHOLDER" @@ -32,8 +28,10 @@ binding = "LINKS_KV" id = "KV_NAMESPACE_ID_PLACEHOLDER" [triggers] -# Native Cron Trigger — the default scheduler. The deploy workflow removes this -# entire section when WAKER_MODE=waker and WAKER_TRIGGERS=remove (the waker -# platform then calls /_waker/execute instead). Keep the expression -# character-for-character: the waker job is created with the same value. +# Native Cron Trigger — static: this section is always deployed and the pipeline +# never rewrites it. The waker callback runs next to it (dual run, the cleanup is +# idempotent) as soon as its signing key is bound; switching the schedule over to +# waker alone is a separate, reviewable change that deletes this section (revert +# that commit to roll back). Keep the expression character-for-character: the +# waker job is created with the same value. crons = ["0 3 * * *"] diff --git a/turbo.json b/turbo.json index c67a4c9..da2e2c3 100644 --- a/turbo.json +++ b/turbo.json @@ -1,13 +1,6 @@ { "$schema": "https://turbo.build/schema.json", - "globalPassThroughEnv": [ - "TABLE_PREFIX", - "WAKER_MODE", - "WAKER_URL", - "WAKER_TRIGGERS", - "WRANGLER_TOML", - "GITHUB_OUTPUT" - ], + "globalPassThroughEnv": ["TABLE_PREFIX", "WRANGLER_TOML", "GITHUB_OUTPUT"], "tasks": { "build": { "dependsOn": ["^build"],