diff --git a/.github/scripts/configure-waker-mode.mjs b/.github/scripts/configure-waker-mode.mjs new file mode 100644 index 0000000..3d2503e --- /dev/null +++ b/.github/scripts/configure-waker-mode.mjs @@ -0,0 +1,178 @@ +// 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-d1-migrations.mjs b/.github/scripts/test-d1-migrations.mjs index 2e6753e..40d70c7 100644 --- a/.github/scripts/test-d1-migrations.mjs +++ b/.github/scripts/test-d1-migrations.mjs @@ -215,6 +215,7 @@ test('无前缀:保留 Wrangler 迁移路径及重复执行行为', (t) => { assert.deepEqual(f.query('SELECT name FROM d1_migrations ORDER BY name')[0], [ { name: '0001_init.sql' }, { name: '0002_token_version.sql' }, + { name: '0003_waker_executions.sql' }, ]); assert.match(f.script('d1-prepare-migrations.sh', ''), /already tracked/); assert.match( @@ -233,18 +234,19 @@ test('无前缀:保留 Wrangler 迁移路径及重复执行行为', (t) => { test('无前缀:setup 历史可 baseline 为 Wrangler 历史', (t) => { const f = fixture(t); - f.setup('', ['schema_v1', 'schema_v2']); + f.setup('', ['schema_v1', 'schema_v2', 'schema_v3']); assert.match(f.script('d1-prepare-migrations.sh', ''), /Baselining/); assert.deepEqual(f.query('SELECT name FROM d1_migrations ORDER BY name')[0], [ { name: '0001_init.sql' }, { name: '0002_token_version.sql' }, + { name: '0003_waker_executions.sql' }, ]); }); test('有前缀且已全部执行:只打印空计划,仅执行 SELECT,共享库不变', (t) => { const f = fixture(t); const before = f.shared(); - f.setup('SL', ['schema_v1', 'schema_v2']); + f.setup('SL', ['schema_v1', 'schema_v2', 'schema_v3']); assert.match(f.script('d1-prepare-migrations.sh', 'SL'), /prefixed/); // Bash trace 核对脚本实际调用的每条 D1 SQL,不能只比较最终数据。 const trace = f.run( @@ -268,7 +270,7 @@ test('有前缀且已全部执行:只打印空计划,仅执行 SELECT,共 assert.deepEqual(f.foreignSnapshot(), before); }); -test('有前缀且有待执行迁移:仅应用 v2,保留其他应用的表、索引和数据', (t) => { +test('有前缀且有待执行迁移:仅应用 v2、v3,保留其他应用的表、索引和数据', (t) => { const f = fixture(t); const before = f.shared(); f.setup('SL', ['schema_v1']); @@ -276,11 +278,11 @@ test('有前缀且有待执行迁移:仅应用 v2,保留其他应用的表 VALUES ('sl@example.com','sl-user','hash')`); assert.match( f.script('d1-prefixed-migrations.sh', 'SL'), - /Planned migrations: schema_v2\n/, + /Planned migrations: schema_v2 schema_v3\n/, ); assert.deepEqual( f.query('SELECT name FROM _SL_schema_migrations ORDER BY name')[0], - [{ name: 'schema_v1' }, { name: 'schema_v2' }], + [{ name: 'schema_v1' }, { name: 'schema_v2' }, { name: 'schema_v3' }], ); f.assertOwnIndexes('SL'); assert.deepEqual(f.query('SELECT email,token_version FROM SL_users')[0], [ @@ -298,12 +300,12 @@ test('有前缀的新安装:只创建本应用的表,共享库保持不变', const before = f.shared(); assert.match( f.script('d1-prefixed-migrations.sh', 'SL'), - /Planned migrations: schema_v1 schema_v2/, + /Planned migrations: schema_v1 schema_v2 schema_v3/, ); assert.deepEqual(f.foreignSnapshot(), before); assert.deepEqual( f.query('SELECT name FROM _SL_schema_migrations ORDER BY name')[0], - [{ name: 'schema_v1' }, { name: 'schema_v2' }], + [{ name: 'schema_v1' }, { name: 'schema_v2' }, { name: 'schema_v3' }], ); f.assertOwnIndexes('SL'); }); @@ -331,7 +333,7 @@ test('已知限制:别的应用占用同名索引时,本应用索引会被 f.query('CREATE INDEX idx_links_slug ON ZETA_links(slug)'); assert.match( f.script('d1-prefixed-migrations.sh', 'SL'), - /Planned migrations: schema_v1 schema_v2/, + /Planned migrations: schema_v1 schema_v2 schema_v3/, ); assert.throws(() => f.assertOwnIndexes('SL'), /Expected values/); }); @@ -361,7 +363,7 @@ test('防静默切换:库中已有 prefixed schema + 显式空前缀 → 中 test('回归:共享库他表 + Hop 已有 SL 前缀 → 增量迁移放行,不误杀', (t) => { const f = fixture(t); const before = f.shared(); // 他应用:bare users + ZETA_* - f.setup('SL', ['schema_v1', 'schema_v2']); + f.setup('SL', ['schema_v1', 'schema_v2', 'schema_v3']); assert.match(f.script('d1-prepare-migrations.sh', 'SL'), /prefixed/); assert.match( f.script('d1-prefixed-migrations.sh', 'SL'), @@ -396,11 +398,11 @@ test('回归:仅外来 d1_migrations(别家文件名)+ SL 表全删 → assert.match(f.outputs(), /mode=prefixed/); assert.match( f.script('d1-prefixed-migrations.sh', 'SL'), - /Planned migrations: schema_v1 schema_v2\n/, + /Planned migrations: schema_v1 schema_v2 schema_v3\n/, ); assert.deepEqual( f.query('SELECT name FROM _SL_schema_migrations ORDER BY name')[0], - [{ name: 'schema_v1' }, { name: 'schema_v2' }], + [{ name: 'schema_v1' }, { name: 'schema_v2' }, { name: 'schema_v3' }], ); f.assertOwnIndexes('SL'); assert.deepEqual(f.foreignSnapshot(), before); @@ -485,7 +487,7 @@ for (const scenario of [ assert.doesNotMatch(output, /::error::/); assert.deepEqual( f.query('SELECT name FROM _SL_schema_migrations ORDER BY name')[0], - [{ name: 'schema_v1' }, { name: 'schema_v2' }], + [{ name: 'schema_v1' }, { name: 'schema_v2' }, { name: 'schema_v3' }], ); f.assertOwnIndexes('SL'); assert.deepEqual(f.foreignSnapshot(), before); @@ -534,7 +536,7 @@ for (const scenario of [ assert.match(run(), /Deployed Worker uses TABLE_PREFIX=SL/); assert.deepEqual( f.query('SELECT name FROM _SL_schema_migrations ORDER BY name')[0], - [{ name: 'schema_v1' }, { name: 'schema_v2' }], + [{ name: 'schema_v1' }, { name: 'schema_v2' }, { name: 'schema_v3' }], ); f.assertOwnIndexes('SL'); assert.deepEqual(f.foreignSnapshot(), before); diff --git a/.github/scripts/test-deploy-checks.mjs b/.github/scripts/test-deploy-checks.mjs index 50309dc..98f8655 100644 --- a/.github/scripts/test-deploy-checks.mjs +++ b/.github/scripts/test-deploy-checks.mjs @@ -240,6 +240,84 @@ for (const scenario of [ expectError: '::error::.*TOTP_ENCRYPTION_KEY', ok: false, }, + { + // waker 模式:signing key 必须真的绑在版本上,否则回调一律 500。 + name: 'waker 模式且 WAKER_SIGNING_KEY 已绑定 → 通过', + version: 'uploaded', + percentage: 100, + prefix: 'hop', + env: 'hop', + waker: 'waker', + 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"}', + ], + ok: true, + }, + { + name: 'waker 模式缺 WAKER_SIGNING_KEY 绑定必须失败', + version: 'uploaded', + percentage: 100, + prefix: 'hop', + env: 'hop', + waker: 'waker', + secretBindings: [ + '{"name":"JWT_SECRET","type":"secret_text"}', + '{"name":"SETUP_SECRET","type":"secret_text"}', + '{"name":"TOTP_ENCRYPTION_KEY","type":"secret_text"}', + ], + expectError: 'no secret_text binding for: WAKER_SIGNING_KEY', + ok: false, + }, + { + // 切换完成态:triggers 真的没了才允许通过。 + name: 'waker+remove 且 schedules 为空 → 通过', + 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"}', + ], + 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 为空 → 必须失败', + version: 'uploaded', + percentage: 100, + prefix: 'hop', + env: 'hop', + waker: 'cron', + schedulesEmpty: true, + expectError: "expected exactly '0 3 \\* \\* \\*'", + ok: false, + }, ]) { test(`控制面:${scenario.name}`, (t) => { const f = fixture(t); @@ -267,13 +345,37 @@ esac ); const output = join(f.dir, 'deploy.ndjson'); writeFileSync(output, '{"type":"deploy","version_id":"uploaded"}\n'); + // wrangler.toml is read for account_id by the schedules gate; the curl stub + // answers the Cloudflare schedules API without leaving the machine. + writeFileSync( + join(f.dir, 'wrangler.toml'), + 'name = "hop"\naccount_id = "0123456789abcdef0123456789abcdef"\n', + ); + const schedulesBody = scenario.schedulesEmpty + ? '{"success":true,"result":{"schedules":[]}}' + : '{"success":true,"result":{"schedules":[{"cron":"0 3 * * *"}]}}'; + writeFileSync( + join(f.dir, 'curl'), + `#!/bin/sh +printf '%s\\n' '${schedulesBody}' +`, + { mode: 0o755 }, + ); const run = () => execFileSync('bash', [join(scripts, 'verify-deployment.sh')], { + cwd: f.dir, env: { ...f.env, // 期望值(GitHub 变量解析结果)默认取 SL;用例可单独指定。 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 }), }, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], @@ -286,6 +388,17 @@ esac 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/); + } else { + assert.match(stdout, /Cron schedules: 0 3 \* \* \*/); + } } else { let thrown = null; try { @@ -528,7 +641,7 @@ async function runSmoke(f, extra) { const creds = { ACCOUNT_ID: 'a'.repeat(32), - CLOUDFLARE_API_TOKEN: 'not-a-real-token', + CLOUDFLARE_API_TOKEN: 'test-token-not-a-real-value', }; test('冒烟:未配置 APP_URL 时用 CF API 推导 workers.dev 地址并探测', async (t) => { @@ -664,7 +777,13 @@ function runWriteSecrets(f, values) { const runnerTemp = join(f.dir, 'runner-temp'); mkdirSync(runnerTemp, { recursive: true }); const env = { ...f.env, RUNNER_TEMP: runnerTemp }; - for (const name of ['JWT_SECRET', 'SETUP_SECRET', 'TOTP_ENCRYPTION_KEY']) { + for (const name of [ + 'JWT_SECRET', + 'SETUP_SECRET', + 'TOTP_ENCRYPTION_KEY', + 'WAKER_MODE', + 'WAKER_SIGNING_KEY', + ]) { delete env[name]; } Object.assign(env, values); @@ -755,6 +874,113 @@ test('deploy.yml:Write secrets file 步从仓库 Secret 注入 TOTP_ENCRYPTION ); }); +// ─── waker 双模式:secrets 文件与部署接线 ──────────────────────────────────── + +test('secrets 文件:waker 模式注入 WAKER_SIGNING_KEY', (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); + const parsed = JSON.parse(readFileSync(result.secretsPath, 'utf8')); + assert.deepEqual(Object.keys(parsed).sort(), [ + 'JWT_SECRET', + 'SETUP_SECRET', + 'TOTP_ENCRYPTION_KEY', + 'WAKER_SIGNING_KEY', + ]); + assert.equal( + parsed.WAKER_SIGNING_KEY, + 'waker-test-signing-key-not-a-real-value', + ); + assert.equal(statSync(result.secretsPath).mode & 0o777, 0o600); +}); + +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) => { + 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 parsed = JSON.parse(readFileSync(result.secretsPath, 'utf8')); + assert.deepEqual(Object.keys(parsed).sort(), [ + 'JWT_SECRET', + 'SETUP_SECRET', + 'TOTP_ENCRYPTION_KEY', + ]); +}); + +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('deploy.yml:Verify 步带上解析后的 waker 模式,signing key 只从 Secret 取', () => { + const text = readFileSync( + join(repoRoot, '.github', 'workflows', 'deploy.yml'), + 'utf8', + ); + assert.match( + text, + /WAKER_SIGNING_KEY: \$\{\{ secrets\.WAKER_SIGNING_KEY \}\}/, + 'signing key 只能来自仓库 Secret', + ); + assert.doesNotMatch( + text, + /WAKER_SIGNING_KEY: \$\{\{ vars\./, + 'signing key 不得取自明文变量', + ); +}); + // ─── 改动 B:Deploy 步让 --secrets-file 真正到达 Wrangler ───────────────────── test('deploy.yml:Deploy 步直接调 Wrangler 传 --secrets-file', () => { diff --git a/.github/scripts/test-waker-mode.mjs b/.github/scripts/test-waker-mode.mjs new file mode 100644 index 0000000..767105c --- /dev/null +++ b/.github/scripts/test-waker-mode.mjs @@ -0,0 +1,259 @@ +// 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 610793c..c6baaec 100644 --- a/.github/scripts/verify-deployment.sh +++ b/.github/scripts/verify-deployment.sh @@ -10,6 +10,10 @@ # TABLE_PREFIX — resolved prefix ('' means explicit no prefix) # 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. set -euo pipefail here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" @@ -37,16 +41,24 @@ 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 -missing_secrets="$(jq -r ' +# 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. +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 +missing_secrets="$(jq -r --arg names "$required_secrets" ' ([.resources.bindings[] | select(.type == "secret_text") | .name]) as $bound - | ["JWT_SECRET", "SETUP_SECRET", "TOTP_ENCRYPTION_KEY"] + | ($names | split(" ")) | map(select(. as $name | ($bound | index($name)) == null)) | join(", ")' <<<"$secrets_view")" if [[ -n "$missing_secrets" ]]; then echo "::error::Worker version $version has no secret_text binding for: ${missing_secrets}. The deploy did not apply --secrets-file; re-run the Deploy workflow to re-upload the version with the secrets file." exit 1 fi -echo "Secret bindings on version $version: JWT_SECRET SETUP_SECRET TOTP_ENCRYPTION_KEY" +echo "Secret bindings on version $version: $required_secrets" status="" for attempt in 1 2 3 4 5; do @@ -75,3 +87,40 @@ if [[ "$live" != "$expected" ]]; then exit 1 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. +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." + exit 1 +fi +if [[ -z "${CLOUDFLARE_API_TOKEN:-}" ]]; then + echo "::error::CLOUDFLARE_API_TOKEN is not set; cannot verify cron schedules." + exit 1 +fi +schedules="$(curl -sS --max-time 20 \ + -H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \ + "https://api.cloudflare.com/client/v4/accounts/${account_id}/workers/scripts/${worker_name}/schedules" || true)" +if ! jq -e '.success == true and (.result.schedules | type == "array")' \ + <<<"${schedules:-null}" >/dev/null 2>&1; then + echo "::error::Cloudflare API GET /workers/scripts/${worker_name}/schedules failed or returned an unexpected body ($(jq -c '.errors // empty' <<<"${schedules:-null}" 2>/dev/null || echo unknown)); cannot verify cron schedules." + 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 * * *" +fi diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8312d2a..842390d 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 + run: node --test .github/scripts/test-d1-migrations.mjs .github/scripts/test-deploy-checks.mjs .github/scripts/test-waker-mode.mjs audit: name: Dependency audit diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 198e608..6329c91 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -99,6 +99,20 @@ 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 @@ -141,6 +155,8 @@ jobs: 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 for name in JWT_SECRET SETUP_SECRET TOTP_ENCRYPTION_KEY; do @@ -153,13 +169,26 @@ jobs: const fs = require("node:fs"); const path = require("node:path"); const file = path.join(process.env.RUNNER_TEMP, "secrets.json"); + const secrets = { + JWT_SECRET: process.env.JWT_SECRET, + "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); + } + secrets.WAKER_SIGNING_KEY = key; + } fs.writeFileSync( file, - JSON.stringify({ - JWT_SECRET: process.env.JWT_SECRET, - "SETUP_SECRET": process.env["SETUP_SECRET"], - TOTP_ENCRYPTION_KEY: process.env.TOTP_ENCRYPTION_KEY, - }, null, 2) + "\n", + JSON.stringify(secrets, null, 2) + "\n", { mode: 0o600 }, ); ' @@ -190,6 +219,8 @@ 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 }} 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 fcf19e1..b628e41 100644 --- a/README.md +++ b/README.md @@ -195,6 +195,82 @@ Navigate to your deployed URL and register — the first account is automaticall --- +## Optional: schedule with waker (dual mode) + +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). + +### What each mode deploys + +| `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` | + +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. + +### Variables + +| 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. | + +### Create the waker job (once, in the waker UI) + +Create the `hop` project with its callback URL pointing at this Worker, then add this declarative +job — these values are frozen, copy them verbatim (the job name must match the receiver's key): + +| Field | Value | +|---|---| +| Job name | `nightly-cleanup` | +| Kind / cron | `cron` / `0 3 * * *` | +| Timezone | `UTC` | +| `concurrency` | `forbid` | +| `misfirePolicy` | `skip` | +| `maxRetries` / `backoffSeconds` | `2` / `60` | +| `timeoutSeconds` / `jitterSeconds` | `30` / `0` | + +### Switch and roll 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: + 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. + +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. + +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 +SDK's error code, e.g. `invalid_signature`, `stale_timestamp`, `unknown_job`). Signing keys are +never logged. + +--- + ## Local Development ```bash @@ -333,6 +409,10 @@ 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. | --- diff --git a/README.zh-CN.md b/README.zh-CN.md index a51d39f..f2abc22 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -176,6 +176,75 @@ curl -X POST https://your-worker.workers.dev/api/setup \ --- +## 可选:用 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, +否则平台会把「没跑」当成「跑成功」)。 + +### 两种模式各自部署什么 + +| `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` | + +摘除 Cron Trigger 是一个独立的显式动作:`WAKER_TRIGGERS` 在两种模式下都默认 `keep`,只改 +`WAKER_MODE` 永远不会让应用失去调度。`WAKER_MODE=cron` 与 `WAKER_TRIGGERS=remove` 的组合会让部署 +直接失败——那等于没有任何调度器。即使 cron 模式,部署也会显式写入 `WAKER_MODE`,因为 +`keep_vars = true` 会让上一次 waker 模式的值在 Worker 上继续存活。 + +### 变量 + +| 变量 | 类型 | 必填 | 来源 | 描述 | +|---|---|---|---|---| +| `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 管理面建任务(一次) + +创建 `hop` 项目(回调地址填本 Worker 的公开地址),再建一条声明式任务——以下取值已冻结, +请逐字照抄(任务名必须与 receiver 的 key 完全一致): + +| 字段 | 值 | +|---|---| +| 任务名 | `nightly-cleanup` | +| 类型 / cron | `cron` / `0 3 * * *` | +| 时区 | `UTC` | +| `concurrency` | `forbid` | +| `misfirePolicy` | `skip` | +| `maxRetries` / `backoffSeconds` | `2` / `60` | +| `timeoutSeconds` / `jitterSeconds` | `30` / `0` | + +### 切换与回滚 + +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 的执行记录有成功条目, + Worker 日志出现 `"event":"nightly_cleanup","source":"waker"` 及删除计数与耗时。 +4. 改 `WAKER_TRIGGERS=remove` 再部署:`[triggers]` 被摘除,平台成为唯一调度源。 + +回滚:把 `WAKER_MODE` 改回 `cron`(`WAKER_TRIGGERS` 留空即可)重新部署——`[triggers]` 恢复、 +`/_waker/execute` 回到 404;在 waker 管理面停用或删除该任务,避免平台继续投递。 +数据库无需回滚:`schema_v3` 只加法创建 `{prefix}waker_executions`,cron 模式代码从不读它。 +`WAKER_SIGNING_KEY` 的 Worker 绑定可能仍在(secrets 文件只增不删),cron 模式下无影响, +需要时可在控制台删除。 + +清理结果以结构化 JSON 记录(`nightly_cleanup` 含计数、耗时与触发来源;被拒回调记 +`waker_callback_rejected`,含 HTTP 状态与 SDK 错误码,如 `invalid_signature`、 +`stale_timestamp`、`unknown_job`)。签名密钥永不进日志。 + +--- + ## 本地开发 ```bash @@ -313,6 +382,10 @@ 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 | 回调签名密钥,建项目时一次性展示;不进日志、不进仓库。 | --- diff --git a/apps/worker/.dev.vars.example b/apps/worker/.dev.vars.example index e70fbeb..e3ea0eb 100644 --- a/apps/worker/.dev.vars.example +++ b/apps/worker/.dev.vars.example @@ -21,3 +21,16 @@ APP_ORIGIN= JWT_SECRET= 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= +# WAKER_SIGNING_KEY= diff --git a/apps/worker/migrations/0003_waker_executions.sql b/apps/worker/migrations/0003_waker_executions.sql new file mode 100644 index 0000000..efee1b2 --- /dev/null +++ b/apps/worker/migrations/0003_waker_executions.sql @@ -0,0 +1,13 @@ +-- DO NOT EDIT. Generated from src/lib/migrations.ts (getMigrations("")). +-- Regenerate with: pnpm --filter @hop/worker generate:migrations + +CREATE TABLE waker_executions ( + execution_id TEXT PRIMARY KEY, + job_id TEXT NOT NULL, + job_name TEXT NOT NULL, + scheduled_for INTEGER NOT NULL, + status TEXT NOT NULL, + response_json TEXT, + claimed_at INTEGER NOT NULL, + completed_at INTEGER +); diff --git a/apps/worker/package.json b/apps/worker/package.json index 59ad5f5..7bd7200 100644 --- a/apps/worker/package.json +++ b/apps/worker/package.json @@ -14,7 +14,7 @@ "db:migrate": "wrangler d1 migrations apply DB --remote" }, "dependencies": { - "hono": "^4.6.12", + "hono": "^4.13.14", "jose": "^6.0.0", "otpauth": "^9.3.6", "@simplewebauthn/server": "^13.0.0" diff --git a/apps/worker/src/index.ts b/apps/worker/src/index.ts index 72df779..d779619 100644 --- a/apps/worker/src/index.ts +++ b/apps/worker/src/index.ts @@ -12,7 +12,10 @@ import authRoutes from './routes/auth.js'; import linksRoutes from './routes/links.js'; import redirectHandler from './routes/redirect.js'; import setupRoutes from './routes/setup.js'; +import { wakerRoutes } from './routes/waker.js'; +import { runCleanup } from './services/cleanup.js'; import type { Env, Variables } from './types.js'; +import { CALLBACK_MOUNT_PATH } from './waker/index.js'; const app = new Hono<{ Bindings: Env; Variables: Variables }>(); @@ -120,6 +123,17 @@ app.all('/api/*', (c) => { return apiError(c, 404, 'NOT_FOUND', 'Not found'); }); +// ─── waker callback (optional second scheduler) ─────────────────────────────── +// 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). +app.all(CALLBACK_MOUNT_PATH, (c) => { + return apiError(c, 404, 'NOT_FOUND', 'Not found'); +}); +app.route(CALLBACK_MOUNT_PATH, wakerRoutes()); + // ─── Short link redirect ─────────────────────────────────────────────────────── const SPA_PREFIXES = new Set([...RESERVED_SLUGS].map((s) => `/${s}`)); @@ -161,19 +175,21 @@ export { app }; export default { fetch: app.fetch, - // L-2: Nightly cleanup of expired rows (cron: "0 3 * * *") + // L-2: Nightly cleanup of expired rows (cron "0 3 * * *"; in waker mode the + // platform calls the same runCleanup through /_waker/execute). async scheduled( _event: ScheduledController, env: Env, _ctx: ExecutionContext, ): Promise { - await env.DB.batch([ - env.DB.prepare( - `DELETE FROM ${tbl(env, 'verifications')} WHERE expires_at < unixepoch()`, - ), - env.DB.prepare( - `DELETE FROM ${tbl(env, 'totp_used')} WHERE used_at < unixepoch() - 90`, - ), - ]); + const result = await runCleanup(env); + console.info( + JSON.stringify({ + level: 'info', + event: 'nightly_cleanup', + source: 'cron', + ...result, + }), + ); }, } satisfies ExportedHandler; diff --git a/apps/worker/src/lib/migrations.ts b/apps/worker/src/lib/migrations.ts index 931e7fa..7c7c8db 100644 --- a/apps/worker/src/lib/migrations.ts +++ b/apps/worker/src/lib/migrations.ts @@ -157,6 +157,28 @@ CREATE INDEX IF NOT EXISTS idx_totp_used_at ON ${t('totp_used')}(used_at); fileName: '0002_token_version.sql', sql: ` ALTER TABLE ${t('users')} ADD COLUMN token_version INTEGER NOT NULL DEFAULT 0; +`, + }, + { + // executionId deduplication for waker callbacks (waker migration contract, + // schema_v3). Columns match the waker client SDK's executionLedgerDdl() + // one-for-one, but the SQL is frozen here as a literal: a merged + // migration can never change, even if the SDK's DDL does later. + // Hop's own ledger only — the shared database's other projects' tables + // are never touched. + name: 'schema_v3', + fileName: '0003_waker_executions.sql', + sql: ` +CREATE TABLE IF NOT EXISTS ${t('waker_executions')} ( + execution_id TEXT PRIMARY KEY, + job_id TEXT NOT NULL, + job_name TEXT NOT NULL, + scheduled_for INTEGER NOT NULL, + status TEXT NOT NULL, + response_json TEXT, + claimed_at INTEGER NOT NULL, + completed_at INTEGER +); `, }, ]; diff --git a/apps/worker/src/routes/waker.ts b/apps/worker/src/routes/waker.ts new file mode 100644 index 0000000..4384c4c --- /dev/null +++ b/apps/worker/src/routes/waker.ts @@ -0,0 +1,116 @@ +// HTTP side of the optional waker integration: mount the SDK's receiver at +// /_waker and answer an explicit 404 whenever the integration is off. +// +// 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). +// +// "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. + +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'; + +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. + * + * The receiver's routes are relative to its mount prefix (`POST /execute`), so + * it has to be reached through `app.route(prefix, receiver)`; a throwaway host + * app does exactly that for this one request. Path stripping, 404s inside the + * prefix and every protocol detail stay SDK decisions — this is not a + * hand-written forwarder for the protocol. + */ +function forwardToReceiver( + request: Request, + env: Env, +): Response | Promise { + const host = new Hono(); + host.route( + CALLBACK_MOUNT_PATH, + createWakerCallbackReceiver(env) as unknown as Hono, + ); + return host.fetch(request, env); +} + +/** + * Log a rejected callback without ever touching its body's contents: only the + * HTTP status and the SDK's stable error code (`invalid_signature`, + * `stale_timestamp`, `unknown_job`, `signing_key_missing`, …). Verification and + * registration failures must not disappear silently. + */ +async function logRejection(response: Response): Promise { + if (response.status < 400) return response; + let code: string | null = null; + try { + const body = (await response.clone().json()) as { + error?: { code?: unknown }; + }; + if (typeof body.error?.code === 'string') code = body.error.code; + } catch { + // Non-JSON error body: the status alone is still worth logging. + } + console.warn( + JSON.stringify({ + level: 'warn', + event: 'waker_callback_rejected', + status: response.status, + code, + }), + ); + return response; +} + +/** `app.route('/_waker', wakerRoutes())`, registered before the SPA fallback. */ +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)); + }); + + return routes; +} diff --git a/apps/worker/src/services/cleanup.ts b/apps/worker/src/services/cleanup.ts new file mode 100644 index 0000000..107ecce --- /dev/null +++ b/apps/worker/src/services/cleanup.ts @@ -0,0 +1,51 @@ +// The nightly cleanup's business logic, written once and shared by both +// trigger paths: the native CF Cron Trigger (`scheduled()` in src/index.ts) and +// the waker callback (`/_waker/execute`, src/services/waker.ts). +// +// Both deletes stay exactly as they were before the waker migration: same +// tables (derived through tbl(), so TABLE_PREFIX still decides the names), same +// predicates, one D1 batch. This module only adds the counters the callback +// response and the logs need — it does not change what the cleanup does. + +import { tbl } from '../lib/db.js'; +import type { Env } from '../types.js'; + +export interface CleanupResult { + /** Rows deleted from `{prefix}verifications` (expired verification codes). */ + verifications: number; + /** Rows deleted from `{prefix}totp_used` (codes older than the 90s replay window). */ + totpUsed: number; + /** Wall-clock duration of the batch, in milliseconds. */ + durationMs: number; +} + +/** + * L-2: delete expired verification rows and TOTP codes no longer needed for + * replay protection. + * + * Predicates (frozen by the waker migration contract): + * - `{prefix}verifications`: `expires_at < unixepoch()` + * - `{prefix}totp_used`: `used_at < unixepoch() - 90` (90 **seconds**) + * + * No waitUntil and no try/catch on purpose: a failed batch rejects, so the cron + * invocation fails and the waker callback answers 5xx (the platform retries) + * instead of reporting a success that never happened. + */ +export async function runCleanup( + env: Pick, +): Promise { + const startedAt = Date.now(); + const [verifications, totpUsed] = await env.DB.batch([ + env.DB.prepare( + `DELETE FROM ${tbl(env, 'verifications')} WHERE expires_at < unixepoch()`, + ), + env.DB.prepare( + `DELETE FROM ${tbl(env, 'totp_used')} WHERE used_at < unixepoch() - 90`, + ), + ]); + return { + verifications: verifications?.meta?.changes ?? 0, + totpUsed: totpUsed?.meta?.changes ?? 0, + durationMs: Date.now() - startedAt, + }; +} diff --git a/apps/worker/src/services/waker.ts b/apps/worker/src/services/waker.ts new file mode 100644 index 0000000..da42d1e --- /dev/null +++ b/apps/worker/src/services/waker.ts @@ -0,0 +1,89 @@ +// Waker callback wiring: the platform's POST /_waker/execute → the very same +// nightly cleanup the native Cron Trigger runs (src/services/cleanup.ts). +// +// Contract (frozen by the waker migration contract, spec v1.0 §2): +// - one business function for both entries — this file adds no cleanup logic; +// - the handler awaits the cleanup to completion before returning, so the SDK +// only answers 2xx after the work really ran (never waitUntil + early OK); +// - verification, replay window and error codes live in the vendored SDK +// (src/waker/), never re-implemented here; +// - `executionId` deduplication uses hop's own D1 table +// `{prefix}waker_executions` (schema_v3), derived through tbl() so +// TABLE_PREFIX stays the single source of truth. + +import { tbl } from '../lib/db.js'; +import type { Env } from '../types.js'; +import { + createD1ExecutionLedger, + createWakerReceiver, +} from '../waker/index.js'; +import { runCleanup } from './cleanup.js'; + +/** + * The job name registered in the waker management UI. It must match **exactly** + * — the receiver dispatches by name and answers 404 `unknown_job` otherwise. + */ +export const WAKER_JOB_NIGHTLY_CLEANUP = 'nightly-cleanup'; + +/** + * The declarative cron expression, character-for-character what + * apps/worker/wrangler.toml declares for the native trigger (CF dialect, UTC). + * The waker job is created by hand with this expression, so it is also the + * value to copy there; nothing in hop rewrites it. + */ +export const WAKER_JOB_CRON = '0 3 * * *'; + +/** Suffix of the SDK's executionId ledger table; the prefix comes from tbl(). */ +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. + * + * 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 + * no I/O and callbacks arrive once a day, so this costs nothing measurable. + */ +export function createWakerCallbackReceiver(env: Env) { + return createWakerReceiver({ + jobs: { + [WAKER_JOB_NIGHTLY_CLEANUP]: async (context) => { + const result = await runCleanup(env); + // Structured, credential-free observability: counts + duration. + console.info( + JSON.stringify({ + level: 'info', + event: 'nightly_cleanup', + source: 'waker', + jobName: context.jobName, + executionId: context.executionId, + attempt: context.attempt, + ...result, + }), + ); + return { cleanup: result }; + }, + }, + ledger: createD1ExecutionLedger(env.DB, { + table: tbl(env, WAKER_EXECUTIONS_TABLE), + }), + // The SDK releases the ledger claim and answers 5xx so the platform retries + // with the same executionId; log why it failed instead of swallowing it. + onJobError: (error, context) => { + console.error( + JSON.stringify({ + level: 'error', + event: 'nightly_cleanup_failed', + source: 'waker', + jobName: context.jobName, + executionId: context.executionId, + attempt: context.attempt, + error: error instanceof Error ? error.message : String(error), + }), + ); + }, + }); +} diff --git a/apps/worker/src/types.ts b/apps/worker/src/types.ts index 4845477..3e149c9 100644 --- a/apps/worker/src/types.ts +++ b/apps/worker/src/types.ts @@ -19,10 +19,22 @@ 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_SIGNING_KEY?: string; } export interface Variables { diff --git a/apps/worker/src/waker/README.md b/apps/worker/src/waker/README.md new file mode 100644 index 0000000..a8cdb04 --- /dev/null +++ b/apps/worker/src/waker/README.md @@ -0,0 +1,24 @@ +# apps/worker/src/waker —— waker 客户端 SDK(外部源码拷贝,勿改) + +本目录是 waker 官方客户端 SDK 的**逐字拷贝**,不是 hop 自己的实现: + +| 项 | 值 | +|---|---| +| 来源 | https://github.com/WorkerHub/waker 的 `client/src/` | +| 版本 | `@workerhub/waker-client` 2.0.0(commit `2b1eb68`,2026-10-27) | +| 接入方式 | SDK README 指定的「把 `client/src` 拷进下游项目(如 `src/waker/`)」 | +| 依赖 | 唯一 peer 是 `hono`(hop 已升到 SDK 声明的 `^4.13.14`),不 import waker 平台内部任何模块 | + +七个文件与上游一一对应:`protocol.ts` / `verify.ts` / `ledger.ts` / `receiver.ts` / +`client.ts` / `modes.ts` / `index.ts`。 + +**规则** + +1. 本目录内任何文件都**不得手改**:需要修 SDK 就回 waker 仓库改、发版,再整目录重新拷贝 + (`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 的双模式部署说明)。 diff --git a/apps/worker/src/waker/client.ts b/apps/worker/src/waker/client.ts new file mode 100644 index 0000000..bdc455e --- /dev/null +++ b/apps/worker/src/waker/client.ts @@ -0,0 +1,322 @@ +import { + WAKER_TOKEN_ENV, + WAKER_URL_ENV, + isWakerEnabled, + readEnvString, + type WakerEnvLike, +} from './modes' +import type { JsonValue } from './protocol' +import { CALLBACK_PROTOCOL_VERSION } from './protocol' + +/** + * 注册客户端:调 B4 冻结的注册 API(`/v1/*`,项目令牌鉴权)。 + * + * 覆盖下游真正需要的五件事: + * - `whoami()` 令牌自检(CI / 启动期 sanity check) + * - `syncManifest()` 部署期声明式任务同步 + 对账(幂等) + * - `createOneShot()` 运行时创建一次性任务(`runAt` 毫秒 / ISO / Date) + * - `cancelJob()` 取消 one-shot(幂等) + * - `listJobs()` 本项目任务列表(分页游标同平台契约) + * + * 传输层全部用原生:`fetch` + `AbortSignal.timeout`,不自研重试/超时。平台不可达时的重试 + * 交给调用方(部署期 CI 重跑、运行时业务自己兜底),客户端不隐藏失败。 + * + * 项目身份**只来自令牌**:请求体里不带 `projectId`(平台也会拒绝不一致的写法)。 + */ + +export type WakerJobKind = 'cron' | 'one_shot' +export type WakerJobStatus = 'active' | 'paused' | 'cancelled' | 'completed' +export type WakerMisfirePolicy = 'fire_once' | 'skip' | 'fire_all' +export type WakerConcurrencyPolicy = 'forbid' | 'allow' + +/** 任务策略字段(与平台 `JobPolicies` 一致;未传字段取平台默认值)。 */ +export interface WakerJobPolicies { + misfire: WakerMisfirePolicy + concurrency: WakerConcurrencyPolicy + maxRetries: number + backoffSeconds: number + timeoutSeconds: number + jitterSeconds: number +} + +/** 任务视图(与平台 `JobView` 一致)。 */ +export interface WakerJobView { + id: string + projectId: string + name: string + kind: WakerJobKind + cron: string | null + cronNormalized: string | null + timezone: string + runAt: number | null + payload: JsonValue + policies: WakerJobPolicies + status: WakerJobStatus + nextRunAt: number | null + lastRunAt: number | null + createdAt: number + updatedAt: number +} + +/** 创建任务入参(= `CreateJobInput` 去掉 `projectId`:项目由令牌决定)。 */ +export interface CreateWakerJobInput { + name: string + kind: WakerJobKind + /** `kind: 'cron'` 必填:CF 官方方言 5 字段表达式。 */ + cron?: string + /** `kind: 'one_shot'` 必填:epoch ms 或 ISO 8601 字符串。 */ + runAt?: number | string + timezone?: string + payload?: JsonValue + policies?: Partial + enabled?: boolean +} + +/** 运行时创建一次性任务:`runAt` 额外接受 `Date`(内部转 epoch ms)。 */ +export interface CreateOneShotInput { + name: string + runAt: number | string | Date + timezone?: string + payload?: JsonValue + policies?: Partial + /** false = 创建后先暂停。默认 true。 */ + enabled?: boolean +} + +/** 声明式清单里的一条任务(与平台 `ManifestJobInput` 一致,只支持 cron)。 */ +export interface WakerManifestJob { + name: string + cron: string + timezone?: string + payload?: JsonValue + policies?: Partial + enabled?: boolean +} + +/** 清单对账结果(与平台 `SyncManifestResult` 一致)。 */ +export interface WakerManifestSyncResult { + projectId: string + created: string[] + updated: string[] + unchanged: string[] + paused: string[] + jobs: WakerJobView[] +} + +export interface WakerJobListResult { + jobs: WakerJobView[] + nextCursor: string | null +} + +export interface WakerJobListQuery { + status?: WakerJobStatus + kind?: WakerJobKind + limit?: number + cursor?: string | null +} + +export interface WakerProjectIdentity { + id: string + name: string +} + +/** + * 平台返回的错误(`{ error: { code, message, details? } }`)。 + * + * `code` 是冻结契约里的稳定错误码(`unauthorized` / `invalid_cron` / `job_not_found` / …), + * 调用方按 `code` 分支,不解析文案、不按状态码猜原因。 + */ +export class WakerApiError extends Error { + readonly status: number + readonly code: string + readonly details: unknown + + constructor(input: { status: number; code: string; message: string; details?: unknown }) { + super(`[${input.status} ${input.code}] ${input.message}`) + this.name = 'WakerApiError' + this.status = input.status + this.code = input.code + this.details = input.details ?? null + } +} + +export interface WakerClientOptions { + /** 平台根地址,如 `https://waker.oneboy.app`(不带 `/v1`)。 */ + baseUrl: string + /** 项目令牌(`Authorization: Bearer <项目令牌>`)。只从 secrets 注入。 */ + token: string + /** 注入 fetch(测试 / 特殊运行时)。 */ + fetch?: typeof fetch + /** 单次请求超时(毫秒),默认 10s。 */ + timeoutMs?: number +} + +export interface WakerClient { + whoami(): Promise + listJobs(query?: WakerJobListQuery): Promise + createJob(input: CreateWakerJobInput): Promise + createOneShot(input: CreateOneShotInput): Promise + cancelJob(name: string): Promise + syncManifest(jobs: WakerManifestJob[]): Promise +} + +interface ErrorEnvelope { + error?: { code?: unknown; message?: unknown; details?: unknown } +} + +function normalizeRunAt(runAt: number | string | Date): number | string { + return runAt instanceof Date ? runAt.getTime() : runAt +} + +function safeJson(text: string): unknown { + try { + return JSON.parse(text) + } catch { + return null + } +} + +/** + * 建一个注册客户端。 + * + * ```ts + * const waker = createWakerClient({ baseUrl: env.WAKER_URL, token: env.WAKER_TOKEN }) + * await waker.createOneShot({ name: `letter-${letter.id}`, runAt: deliverAt, payload: { letterId } }) + * ``` + */ +export function createWakerClient(options: WakerClientOptions): WakerClient { + const baseUrl = options.baseUrl.trim().replace(/\/+$/, '') + if (baseUrl.length === 0) throw new Error('createWakerClient: baseUrl 不能为空') + if (options.token.trim().length === 0) throw new Error('createWakerClient: token 不能为空') + + const fetchImpl = options.fetch ?? fetch + const timeoutMs = options.timeoutMs ?? 10_000 + + async function request( + path: string, + init: { method?: string; body?: unknown } = {}, + ): Promise { + const headers: Record = { + authorization: `Bearer ${options.token}`, + accept: 'application/json', + 'user-agent': `waker-sdk/${CALLBACK_PROTOCOL_VERSION}`, + } + if (init.body !== undefined) headers['content-type'] = 'application/json' + + const response = await fetchImpl(`${baseUrl}${path}`, { + method: init.method ?? 'GET', + headers, + ...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }), + signal: AbortSignal.timeout(Math.max(1, timeoutMs)), + }) + + const text = await response.text() + const payload: unknown = text.length === 0 ? null : safeJson(text) + + if (!response.ok) { + const envelope = (payload ?? {}) as ErrorEnvelope + throw new WakerApiError({ + status: response.status, + code: typeof envelope.error?.code === 'string' ? envelope.error.code : `http_${response.status}`, + message: typeof envelope.error?.message === 'string' ? envelope.error.message : text.slice(0, 500), + details: envelope.error?.details, + }) + } + + return payload as T + } + + return { + async whoami() { + const result = await request<{ project: WakerProjectIdentity }>('/v1/whoami') + return result.project + }, + + async listJobs(query = {}) { + const search = new URLSearchParams() + if (query.status !== undefined) search.set('status', query.status) + if (query.kind !== undefined) search.set('kind', query.kind) + if (query.limit !== undefined) search.set('limit', String(query.limit)) + if (query.cursor !== undefined && query.cursor !== null) search.set('cursor', query.cursor) + const suffix = search.size === 0 ? '' : `?${search.toString()}` + return request(`/v1/jobs${suffix}`) + }, + + async createJob(input) { + const result = await request<{ job: WakerJobView }>('/v1/jobs', { + method: 'POST', + body: input, + }) + return result.job + }, + + async createOneShot(input) { + const body: CreateWakerJobInput = { + name: input.name, + kind: 'one_shot', + runAt: normalizeRunAt(input.runAt), + ...(input.timezone === undefined ? {} : { timezone: input.timezone }), + ...(input.payload === undefined ? {} : { payload: input.payload }), + ...(input.policies === undefined ? {} : { policies: input.policies }), + ...(input.enabled === undefined ? {} : { enabled: input.enabled }), + } + const result = await request<{ job: WakerJobView }>('/v1/jobs', { method: 'POST', body }) + return result.job + }, + + async cancelJob(name) { + const result = await request<{ job: WakerJobView }>( + `/v1/jobs/${encodeURIComponent(name)}`, + { method: 'DELETE' }, + ) + return result.job + }, + + async syncManifest(jobs) { + return request('/v1/manifest', { + method: 'PUT', + body: { jobs }, + }) + }, + } +} + +export interface CreateWakerClientFromEnvOptions { + fetch?: typeof fetch + timeoutMs?: number + /** `true` = 已启用 waker 但 `WAKER_URL` / `WAKER_TOKEN` 缺失时抛错(部署期 fail fast)。 */ + required?: boolean +} + +/** + * 可选接入的客户端入口:**只有 `WAKER_MODE=waker` 时才构造客户端**。 + * + * - 原生模式(缺省):返回 `null` —— 不构造、不读令牌、不发请求; + * - waker 模式但 `WAKER_URL` / `WAKER_TOKEN` 缺失:默认也返回 `null`(等同未启用), + * 传 `required: true` 则抛错,用于部署期自检。 + */ +export function createWakerClientFromEnv( + env: WakerEnvLike, + options: CreateWakerClientFromEnvOptions = {}, +): WakerClient | null { + if (!isWakerEnabled(env)) return null + + const baseUrl = readEnvString(env, WAKER_URL_ENV) + const token = readEnvString(env, WAKER_TOKEN_ENV) + if (baseUrl === null || token === null) { + if (options.required === true) { + throw new Error( + `WAKER_MODE=waker 但 ${WAKER_URL_ENV} / ${WAKER_TOKEN_ENV} 未配置:` + + '请把平台根地址写进 [vars]、项目令牌用 `wrangler secret put` 注入。', + ) + } + return null + } + + return createWakerClient({ + baseUrl, + token, + ...(options.fetch === undefined ? {} : { fetch: options.fetch }), + ...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }), + }) +} diff --git a/apps/worker/src/waker/index.ts b/apps/worker/src/waker/index.ts new file mode 100644 index 0000000..928d304 --- /dev/null +++ b/apps/worker/src/waker/index.ts @@ -0,0 +1,18 @@ +/** + * waker 客户端 SDK 出口。 + * + * 对齐三份冻结契约: + * - 回调协议 v2(B3)→ `./protocol` / `./verify` / `./receiver` + * - 注册 API(B4)→ `./client` + * - CF Cron Triggers 方言(B2)→ 声明式任务的 `cron` 字符串原样透传(SDK 不自行解析, + * 校验由平台侧同一份方言解析器负责;SDK 只保证逐字不改地送达) + * + * 可选接入(双模式):`./modes` 提供模式判定,receiver 与注册客户端都只在 + * `WAKER_MODE=waker` 时接线;原生 `scheduled()` 路径 SDK 从不接管。 + */ +export * from './protocol' +export * from './verify' +export * from './ledger' +export * from './receiver' +export * from './client' +export * from './modes' diff --git a/apps/worker/src/waker/ledger.ts b/apps/worker/src/waker/ledger.ts new file mode 100644 index 0000000..44cfdd1 --- /dev/null +++ b/apps/worker/src/waker/ledger.ts @@ -0,0 +1,236 @@ +/** + * executionId 幂等落表 helper(对齐 B3 冻结契约的「`executionId` 随回调下发,下游落表去重」)。 + * + * 语义: + * - 平台重试同一次执行时带**同一个** `executionId`,下游必须只跑一次业务; + * - 首次投递 → `claim` 成功 → 跑业务 → `complete`; + * - 业务失败 → `release`(把占位删掉,让平台的重试能真正重跑); + * - 重复投递 → `claim` 失败 → 直接回 2xx(幂等成功),必要时带上首次的响应体 + * (这样自续的 `nextRunAt` 在重试时也不会丢)。 + * + * 存储用原生能力表达,不自研分布式锁: + * - D1:`INSERT ... ON CONFLICT(execution_id) DO NOTHING` + `meta.changes` 判定,原子且无竞争; + * - 内存:单 isolate 的 `Map`(只用于本地开发 / 测试,Worker 多 isolate 下不保证跨实例去重)。 + */ + +/** 下游本地记录的一条执行。 */ +export interface ExecutionLedgerEntry { + executionId: string + jobId: string + jobName: string + /** 名义到期时刻(epoch ms)。 */ + scheduledFor: number + status: 'claimed' | 'succeeded' + /** 首次成功时的响应体(重复投递时原样回放,保住 `nextRunAt`)。 */ + response: Record | null + claimedAt: number + completedAt: number | null +} + +/** 认领结果:`claimed` = 本次真的跑;`claimed: false` = 已经处理过(幂等命中)。 */ +export interface ExecutionLedgerClaim { + claimed: boolean + /** 已存在的记录(`claimed: false` 时非空;`claimed: true` 时为 null)。 */ + existing: ExecutionLedgerEntry | null +} + +export interface ExecutionLedger { + /** 认领一次执行(原子「插入或忽略」)。 */ + claim(input: { + executionId: string + jobId: string + jobName: string + scheduledFor: number + }): Promise + /** 标记成功并保存响应体(重复投递时回放)。 */ + complete(executionId: string, response: Record | null): Promise + /** 释放占位(业务失败时调用,让重试能重跑)。 */ + release(executionId: string): Promise + /** 读一条记录(幂等命中时回放响应 / 排查用)。 */ + get(executionId: string): Promise +} + +export interface ExecutionLedgerOptions { + /** 过期占位的接管时限(秒):超过它就认为上次执行已崩溃,允许重新认领。默认 600s。 */ + staleClaimSeconds?: number + /** 注入时钟(测试可替换),默认 `Date.now`。 */ + now?: () => number +} + +const DEFAULT_STALE_CLAIM_SECONDS = 600 + +/** D1 的最小结构接口:只用 `prepare().bind().run()/first()`,不引入 `@cloudflare/workers-types`。 */ +export interface D1RunResult { + success?: boolean + meta?: { changes?: number; last_row_id?: number; changed_db?: boolean } +} + +export interface D1StatementLike { + bind(...values: unknown[]): D1StatementLike + run(): Promise + first(): Promise +} + +export interface D1DatabaseLike { + prepare(sql: string): D1StatementLike +} + +/** 幂等表 DDL(下游自己跑一次迁移;表名可用 `table` 选项改写)。 */ +export function executionLedgerDdl(table = 'waker_executions'): string { + return `CREATE TABLE IF NOT EXISTS ${table} ( + execution_id TEXT PRIMARY KEY, + job_id TEXT NOT NULL, + job_name TEXT NOT NULL, + scheduled_for INTEGER NOT NULL, + status TEXT NOT NULL, + response_json TEXT, + claimed_at INTEGER NOT NULL, + completed_at INTEGER +);` +} + +/** 内存实现:本地开发 / 测试用(单 isolate 有效)。 */ +export function createMemoryExecutionLedger( + options: ExecutionLedgerOptions = {}, +): ExecutionLedger { + const now = options.now ?? Date.now + const staleMs = (options.staleClaimSeconds ?? DEFAULT_STALE_CLAIM_SECONDS) * 1000 + const entries = new Map() + + return { + async claim(input) { + const existing = entries.get(input.executionId) + if (existing === undefined) { + entries.set(input.executionId, { + ...input, + status: 'claimed', + response: null, + claimedAt: now(), + completedAt: null, + }) + return { claimed: true, existing: null } + } + // 上次认领后进程崩了(占位一直没释放):超时允许接管,避免这条执行永远被当成「已处理」。 + if (existing.status === 'claimed' && now() - existing.claimedAt > staleMs) { + entries.set(input.executionId, { ...existing, claimedAt: now() }) + return { claimed: true, existing: null } + } + return { claimed: false, existing: { ...existing } } + }, + async complete(executionId, response) { + const existing = entries.get(executionId) + if (existing === undefined) return + entries.set(executionId, { + ...existing, + status: 'succeeded', + response, + completedAt: now(), + }) + }, + async release(executionId) { + const existing = entries.get(executionId) + if (existing !== undefined && existing.status === 'claimed') entries.delete(executionId) + }, + async get(executionId) { + const existing = entries.get(executionId) + return existing === undefined ? null : { ...existing } + }, + } +} + +interface LedgerRow { + execution_id: string + job_id: string + job_name: string + scheduled_for: number + status: string + response_json: string | null + claimed_at: number + completed_at: number | null +} + +function rowToEntry(row: LedgerRow): ExecutionLedgerEntry { + return { + executionId: row.execution_id, + jobId: row.job_id, + jobName: row.job_name, + scheduledFor: row.scheduled_for, + status: row.status === 'succeeded' ? 'succeeded' : 'claimed', + response: row.response_json === null ? null : (JSON.parse(row.response_json) as Record), + claimedAt: row.claimed_at, + completedAt: row.completed_at, + } +} + +/** + * D1 实现(下游项目自己的库,与平台的 WakerDO SQLite 无关)。 + * + * 认领的原子性交给 SQLite 的 `ON CONFLICT DO NOTHING` + `meta.changes`,不做「先查后写」。 + */ +export function createD1ExecutionLedger( + db: D1DatabaseLike, + options: ExecutionLedgerOptions & { table?: string } = {}, +): ExecutionLedger { + const now = options.now ?? Date.now + const table = options.table ?? 'waker_executions' + const staleMs = (options.staleClaimSeconds ?? DEFAULT_STALE_CLAIM_SECONDS) * 1000 + + async function readEntry(executionId: string): Promise { + const row = await db + .prepare(`SELECT * FROM ${table} WHERE execution_id = ?`) + .bind(executionId) + .first() + return row === null ? null : rowToEntry(row) + } + + return { + async claim(input) { + const claimedAt = now() + const insert = await db + .prepare( + `INSERT INTO ${table} (execution_id, job_id, job_name, scheduled_for, status, response_json, claimed_at, completed_at) + VALUES (?, ?, ?, ?, 'claimed', NULL, ?, NULL) + ON CONFLICT(execution_id) DO NOTHING`, + ) + .bind( + input.executionId, + input.jobId, + input.jobName, + input.scheduledFor, + claimedAt, + ) + .run() + + if ((insert.meta?.changes ?? 0) > 0) return { claimed: true, existing: null } + + // 已有记录:succeeded = 真正的重复投递;claimed 且超时 = 上次执行崩了,接管。 + const existing = await readEntry(input.executionId) + if (existing !== null && existing.status === 'claimed' && claimedAt - existing.claimedAt > staleMs) { + const takeover = await db + .prepare( + `UPDATE ${table} SET claimed_at = ? WHERE execution_id = ? AND status = 'claimed' AND claimed_at = ?`, + ) + .bind(claimedAt, input.executionId, existing.claimedAt) + .run() + if ((takeover.meta?.changes ?? 0) > 0) return { claimed: true, existing: null } + } + + return { claimed: false, existing } + }, + async complete(executionId, response) { + await db + .prepare( + `UPDATE ${table} SET status = 'succeeded', response_json = ?, completed_at = ? WHERE execution_id = ?`, + ) + .bind(response === null ? null : JSON.stringify(response), now(), executionId) + .run() + }, + async release(executionId) { + await db + .prepare(`DELETE FROM ${table} WHERE execution_id = ? AND status = 'claimed'`) + .bind(executionId) + .run() + }, + get: readEntry, + } +} diff --git a/apps/worker/src/waker/modes.ts b/apps/worker/src/waker/modes.ts new file mode 100644 index 0000000..1723295 --- /dev/null +++ b/apps/worker/src/waker/modes.ts @@ -0,0 +1,61 @@ +/** + * 双模式(可选接入)—— 父单规格补充二(2026-10-26,SPEC §0/§5/§9)。 + * + * 下游项目默认走**原生 CF Cron Trigger**(`WAKER_MODE=cron`,缺省值), + * 想改用平台调度时把它切成 `WAKER_MODE=waker` 并注入 `WAKER_URL` + 项目令牌 + signing key。 + * + * 「可选接入」在 SDK 层面落到三件事上: + * 1. **默认关闭**:`WAKER_MODE` 缺失 / 取值不认识 → 一律按 `cron`(原生模式)处理, + * 下游不需要为了「不启用」写任何额外代码; + * 2. **不加载**:`cron` 模式下 receiver 不挂载、注册客户端不构造(见 + * {@link mountWakerReceiver} / `createWakerClientFromEnv` 返回 null), + * 参考示例进一步用动态 `import()` 保证 SDK 模块在原生模式下**连求值都不发生**; + * 3. **原生 scheduled() 不受影响**:模式只影响 HTTP 侧的接线,`scheduled()` 是下游自己的 + * 代码路径,SDK 从不接管它。 + */ + +/** 两种模式:原生 CF Cron Trigger(默认) / waker 回调。 */ +export type WakerMode = 'cron' | 'waker' + +/** 模式开关的环境变量名(部署期由 wrangler `[vars]` 或 secrets 注入)。 */ +export const WAKER_MODE_ENV = 'WAKER_MODE' + +/** 平台地址(waker 模式下 SDK 调注册 API 用)。 */ +export const WAKER_URL_ENV = 'WAKER_URL' + +/** 项目令牌(注册 API 鉴权用;只从 secrets 注入,绝不进仓库)。 */ +export const WAKER_TOKEN_ENV = 'WAKER_TOKEN' + +/** 项目 signing key(回调验签用;只从 secrets 注入)。 */ +export const WAKER_SIGNING_KEY_ENV = 'WAKER_SIGNING_KEY' + +export const WAKER_MODE_CRON: WakerMode = 'cron' +export const WAKER_MODE_WAKER: WakerMode = 'waker' + +/** 最小 env 外形:只要可读的键值表,不绑定任何框架泛型。 */ +export type WakerEnvLike = Record | null | undefined + +/** + * 解析当前模式。 + * + * 未知取值按 `cron` 处理(**不是**抛错也不是猜成 waker):可选接入的默认必须是「不动下游」, + * 部署期写错变量最多是「没启用」,不会出现「悄悄改成回调模式却没配密钥」的半死状态。 + */ +export function resolveWakerMode(env: WakerEnvLike): WakerMode { + const raw = env?.[WAKER_MODE_ENV] + if (typeof raw !== 'string') return WAKER_MODE_CRON + return raw.trim().toLowerCase() === WAKER_MODE_WAKER ? WAKER_MODE_WAKER : WAKER_MODE_CRON +} + +/** 是否启用 waker(= 模式为 `waker`)。 */ +export function isWakerEnabled(env: WakerEnvLike): boolean { + return resolveWakerMode(env) === WAKER_MODE_WAKER +} + +/** 从 env 里取一个非空字符串(缺失 / 空白 → null)。 */ +export function readEnvString(env: WakerEnvLike, key: string): string | null { + const raw = env?.[key] + if (typeof raw !== 'string') return null + const trimmed = raw.trim() + return trimmed.length === 0 ? null : trimmed +} diff --git a/apps/worker/src/waker/protocol.ts b/apps/worker/src/waker/protocol.ts new file mode 100644 index 0000000..a2f31b0 --- /dev/null +++ b/apps/worker/src/waker/protocol.ts @@ -0,0 +1,137 @@ +/** + * 回调协议 v2 —— **SDK 侧副本**,与平台 `src/callback/protocol.ts` 逐字对齐。 + * + * 为什么是副本而不是 `import '../../src/callback/protocol'`:SDK 要能被下游项目**整目录拷走** + * (下游仓库看不到本仓的 `src/`),因此 client 只依赖 `hono` + Workers 运行时原生能力, + * 不 import 平台内部任何模块。副本与冻结契约的一致性由 `tests/client-contract.test.ts` + * 逐项断言(常量 / 头名 / 签名规范串 / 请求响应结构都对比),漂移会直接测试失败。 + * + * 协议语义见父单 SPEC §4(B3 冻结): + * - 下游以 Hono 路由挂载 `/_waker`,平台同步 POST `/_waker/execute`; + * - handler 必须 await 到业务完成才回 2xx(平台以 2xx 判成功,非 2xx 走重试/死信); + * - 每项目独立 signing key,HMAC-SHA256 覆盖 `timestamp + executionId + jobId + body`,带时间窗防重放; + * - `executionId` 随回调下发,下游落表去重; + * - one-shot 执行的回调响应可携带 `nextRunAt` 自续。 + */ + +/** 协议版本号:写进请求体的 `protocolVersion`,也是签名头的前缀(`v2=`)。 */ +export const CALLBACK_PROTOCOL_VERSION = 2 + +/** 下游挂载前缀:`app.route('/_waker', createWakerReceiver({ jobs }))`。 */ +export const CALLBACK_MOUNT_PATH = '/_waker' + +/** 回调 endpoint:平台投递的完整路径(= 挂载前缀 + `/execute`)。 */ +export const CALLBACK_PATH = '/_waker/execute' + +/** 回调签名算法(写进契约,便于日后轮换)。 */ +export const CALLBACK_SIGNATURE_ALGORITHM = 'HMAC-SHA256' + +/** 时间窗(秒):`|now - X-Waker-Timestamp| > 300` 视为重放/过期请求,下游必须拒收。 */ +export const CALLBACK_TIMESTAMP_TOLERANCE_SECONDS = 300 + +/** 自续上限(毫秒):`nextRunAt` 最远只能落在「本次执行时刻 + 366 天」之内。 */ +export const MAX_SELF_RENEWAL_HORIZON_MS = 366 * 24 * 60 * 60 * 1000 + +/** HTTP 头名(冻结):下游按这些名字取签名材料。 */ +export const CALLBACK_HEADERS = { + /** epoch **秒**(十进制字符串),参与签名。 */ + timestamp: 'X-Waker-Timestamp', + /** 本次执行 id(= 下游幂等键),参与签名。 */ + executionId: 'X-Waker-Execution-Id', + /** 任务 id,参与签名。 */ + jobId: 'X-Waker-Job-Id', + /** 项目 id,便于下游快速路由/排查;不参与签名(已在 body 里)。 */ + projectId: 'X-Waker-Project-Id', + /** 第几次投递(0 = 首次),便于排查;不参与签名(已在 body 里)。 */ + attempt: 'X-Waker-Attempt', + /** `v2=<小写 hex>`,参与签名校验。 */ + signature: 'X-Waker-Signature', + /** 协议版本,便于下游做灰度。 */ + protocolVersion: 'X-Waker-Protocol-Version', +} as const + +/** 签名头前缀:`v2=`。 */ +export const CALLBACK_SIGNATURE_PREFIX = `v${CALLBACK_PROTOCOL_VERSION}=` + +/** 任务两类型(与平台 `JobKind` 一致)。 */ +export type JobKind = 'cron' | 'one_shot' + +/** 触发来源(与平台 `ExecutionTrigger` 一致)。 */ +export type ExecutionTrigger = 'schedule' | 'manual' + +/** 不透明载荷(平台不解析,原样透传)。 */ +export type JsonValue = + | string + | number + | boolean + | null + | JsonValue[] + | { [key: string]: JsonValue } + +/** + * 签名规范串(**冻结**,逐字节照此拼接): + * + * ``` + * \n\n\n + * ``` + * + * - `timestamp` = `X-Waker-Timestamp` 头里的原始十进制字符串(不做数值归一); + * - `rawBody` = 请求体**原始字节按 UTF-8 解码后的字符串**(必须用未解析的 body, + * `JSON.stringify(JSON.parse(body))` 会改键序/空白,签名必然不匹配)。 + */ +export function buildSignaturePayload(input: { + timestamp: string + executionId: string + jobId: string + body: string +}): string { + return `${input.timestamp}\n${input.executionId}\n${input.jobId}\n${input.body}` +} + +/** 回调请求体(冻结结构):平台 POST 给下游 `/_waker/execute` 的 JSON。 */ +export interface CallbackRequestBody { + /** 协议版本,恒为 2。 */ + protocolVersion: typeof CALLBACK_PROTOCOL_VERSION + /** 执行 id:下游幂等键(同一次执行的重试会带同一个 executionId)。 */ + executionId: string + /** 任务 id(同一 job 的多次执行共享,自续后仍是同一个 job id)。 */ + jobId: string + projectId: string + /** 任务名(= 下游 jobs 表里的 key,下游据此分发到业务 handler)。 */ + jobName: string + kind: JobKind + trigger: ExecutionTrigger + /** 是否补跑(错过窗口后按 misfirePolicy 补的那一次)。 */ + misfire: boolean + /** 第几次投递,0 = 首次。 */ + attempt: number + /** 名义到期时刻(epoch ms)。 */ + scheduledFor: number + /** 本次实际上报时刻(epoch ms,含抖动)。 */ + dispatchedAt: number + /** 平台侧超时(秒):下游应在此之前返回,否则请求会被 abort 并按失败重试。 */ + timeoutSeconds: number + /** 任务载荷(不透明 JSON,平台不解析,原样透传)。 */ + payload: JsonValue +} + +/** 自续时刻:epoch 毫秒数字或 ISO 8601 字符串。 */ +export type NextRunAt = number | string + +/** 回调响应体(冻结):2xx + JSON 即视为成功执行;只有 one-shot 会看 `nextRunAt`。 */ +export interface CallbackResponseBody { + /** + * 自续的下一次执行时刻。平台校验(合法时间戳 / 严格晚于本次执行时刻 / 不超过 366 天上限) + * 通过后以同一 job 系列续期;校验失败不影响本次执行成功,只在执行记录里留 `renewal_error`。 + */ + nextRunAt?: NextRunAt | null + /** 平台忽略的其它字段(下游可自由返回业务信息)。 */ + [key: string]: unknown +} + +/** 把项目根地址规范化为完整回调地址(平台侧同款实现:契约在这里是对称的)。 */ +export function resolveCallbackUrl(baseUrl: string): string { + const trimmed = baseUrl.trim().replace(/\/+$/, '') + if (trimmed.endsWith(CALLBACK_PATH)) return trimmed + return `${trimmed}${CALLBACK_PATH}` +} diff --git a/apps/worker/src/waker/receiver.ts b/apps/worker/src/waker/receiver.ts new file mode 100644 index 0000000..bec53f6 --- /dev/null +++ b/apps/worker/src/waker/receiver.ts @@ -0,0 +1,331 @@ +import { Hono } from 'hono' +import type { Context, Env } from 'hono' + +import type { ExecutionLedger } from './ledger' +import { + CALLBACK_HEADERS, + CALLBACK_MOUNT_PATH, + CALLBACK_PROTOCOL_VERSION, + CALLBACK_TIMESTAMP_TOLERANCE_SECONDS, + type CallbackRequestBody, + type ExecutionTrigger, + type JobKind, + type JsonValue, + type NextRunAt, +} from './protocol' +import { + WAKER_MODE_WAKER, + WAKER_SIGNING_KEY_ENV, + readEnvString, + resolveWakerMode, + type WakerEnvLike, + type WakerMode, +} from './modes' +import { verifyWakerSignature } from './verify' + +/** + * 下游 receiver:`app.route('/_waker', createWakerReceiver({ jobs }))`。 + * + * 设计要点(对齐 B3 回调协议 v2): + * - **不劫持整个 fetch**:只是一个 `/_waker/execute` 路由,下游其它路由完全不受影响; + * - **同步语义**:handler 返回(或 await 完成)后才回 2xx,失败回 5xx 让平台重试, + * 绝不 `waitUntil + 立即 OK`; + * - **验签在前**:body 用未解析的原始字符串验签,时间窗默认 300s; + * - **幂等**:可选 `ledger`(`client/src/ledger.ts`)。重复投递直接回 2xx + 首次响应体回放, + * 业务失败则释放占位,让平台的重试真的重跑; + * - **自续**:handler 返回 `{ nextRunAt }` 即透传给平台(平台自己再校验上限与时序)。 + */ + +/** receiver 内可用的上下文:只给业务需要的字段,不外泄平台内部结构。 */ +export interface WakerJobContext { + /** 任务名(= `jobs` 表的 key)。 */ + jobName: string + /** 执行 id:**下游幂等键**(同一次执行的重试共享)。 */ + executionId: string + /** 任务 id(自续后仍是同一个 job 系列)。 */ + jobId: string + projectId: string + kind: JobKind + trigger: ExecutionTrigger + misfire: boolean + /** 第几次投递,0 = 首次。 */ + attempt: number + /** 名义到期时刻(epoch ms)。 */ + scheduledFor: number + /** 平台投递时刻(epoch ms)。 */ + dispatchedAt: number + /** 平台侧超时(秒):业务应在此之前返回。 */ + timeoutSeconds: number + /** 任务载荷(原样透传,平台不解析)。 */ + payload: JsonValue +} + +/** + * handler 返回值:可以什么都不返回(= 任务完结),也可以带上 `nextRunAt` 自续。 + * 其它字段会原样回给平台(平台忽略),方便下游在响应里带业务信息排障。 + */ +export interface WakerJobOutcome { + /** 自续时刻:epoch ms 或 ISO 8601;不提供 = 任务完结(只对 one-shot 生效)。 */ + nextRunAt?: NextRunAt | null + [key: string]: unknown +} + +export type WakerJobHandler = ( + context: WakerJobContext, +) => WakerJobOutcome | void | Promise + +/** 任务名 → handler。名字与平台里注册的任务名逐字一致(manifest 里声明的同一份名字)。 */ +export type WakerJobHandlers = Record + +/** + * 任务名解析器:one-shot 的任务名常常按业务 id 动态生成(`letter-` / `reminder-tick-`), + * 静态 map 装不下,所以也允许传「名字 → handler」的函数(返回 `null` = 未声明该任务)。 + */ +export type WakerJobResolver = (jobName: string) => WakerJobHandler | null | undefined + +/** `jobs`:静态 map,或名字解析函数。 */ +export type WakerJobs = WakerJobHandlers | WakerJobResolver + +/** 与下游 env 无耦合的最小 Hono 绑定类型。 */ +export interface WakerReceiverEnv { + Bindings: Record +} + +export interface WakerReceiverOptions { + /** 任务名 → handler(静态 map 或解析函数)。 */ + jobs: WakerJobs + /** + * 项目 signing key:静态字符串,或从 env 解析的函数。 + * 缺省从 `env[signingKeyEnv]`(默认 `WAKER_SIGNING_KEY`)读取——只从 secrets 注入。 + */ + signingKey?: string | ((env: WakerEnvLike) => string | null) + /** 从 env 读 signing key 的变量名,默认 `WAKER_SIGNING_KEY`。 */ + signingKeyEnv?: string + /** 幂等账本(可选:不传 = 不做去重,平台的重试会重跑业务)。 */ + ledger?: ExecutionLedger + /** 注入时钟(epoch ms),测试可替换。 */ + now?: () => number + /** 验签时间窗(秒),默认 {@link CALLBACK_TIMESTAMP_TOLERANCE_SECONDS}。 */ + toleranceSeconds?: number + /** 业务 handler 抛错时的回调(打日志/告警用;不回给平台,平台只看状态码)。 */ + onJobError?: (error: unknown, context: WakerJobContext) => void +} + +/** 错误响应体(与平台侧错误体同构:`{ error: { code, message } }`,另加 `ok: false`)。 */ +export interface WakerReceiverErrorBody { + ok: false + error: { code: string; message: string } +} + +function errorBody(code: string, message: string): WakerReceiverErrorBody { + return { ok: false, error: { code, message } } +} + +/** 规范化 `nextRunAt`:只认有限数字与非空字符串,其它一律丢弃(平台校验上限与时序)。 */ +function normalizeNextRunAt(value: unknown): NextRunAt | null { + if (typeof value === 'number' && Number.isFinite(value)) return value + if (typeof value === 'string' && value.trim().length > 0) return value.trim() + return null +} + +function resolveSigningKey(options: WakerReceiverOptions, env: WakerEnvLike): string | null { + if (typeof options.signingKey === 'string') { + return options.signingKey.trim().length === 0 ? null : options.signingKey.trim() + } + if (typeof options.signingKey === 'function') return options.signingKey(env) + return readEnvString(env, options.signingKeyEnv ?? WAKER_SIGNING_KEY_ENV) +} + +function readBodyFields(body: CallbackRequestBody): boolean { + return ( + typeof body.executionId === 'string' && + body.executionId.length > 0 && + typeof body.jobId === 'string' && + body.jobId.length > 0 && + typeof body.jobName === 'string' && + body.jobName.length > 0 && + typeof body.scheduledFor === 'number' + ) +} + +/** + * 建一个只负责 `POST /execute` 的子应用。 + * + * 挂载方式(下游):`app.route('/_waker', createWakerReceiver({ jobs }))`, + * 或直接用 {@link mountWakerReceiver} 走「可选接入」判定。 + */ +export function createWakerReceiver(options: WakerReceiverOptions): Hono { + const receiver = new Hono() + const now = options.now ?? Date.now + + receiver.post('/execute', async (c: Context) => { + // 1) 原始 body 必须先拿到:验签用的是未解析的字节串。 + const rawBody = await c.req.text() + + const timestamp = c.req.header(CALLBACK_HEADERS.timestamp) ?? '' + const executionIdHeader = c.req.header(CALLBACK_HEADERS.executionId) ?? '' + const jobIdHeader = c.req.header(CALLBACK_HEADERS.jobId) ?? '' + const signature = c.req.header(CALLBACK_HEADERS.signature) ?? '' + + if ( + timestamp.length === 0 || + executionIdHeader.length === 0 || + jobIdHeader.length === 0 || + signature.length === 0 + ) { + return c.json(errorBody('invalid_request', '缺少签名头(X-Waker-Timestamp / X-Waker-Execution-Id / X-Waker-Job-Id / X-Waker-Signature)'), 400) + } + + // 2) 验签:时间窗之外的请求一律拒收(防重放)。 + const env = c.env as WakerEnvLike + const secret = resolveSigningKey(options, env) + if (secret === null) { + // fail closed:没有 signing key 就绝不「看起来正常地」放行。 + return c.json(errorBody('signing_key_missing', '服务端未配置 WAKER_SIGNING_KEY,无法验签'), 500) + } + + const verification = await verifyWakerSignature({ + secret, + signature, + timestamp, + executionId: executionIdHeader, + jobId: jobIdHeader, + body: rawBody, + now: now(), + toleranceSeconds: options.toleranceSeconds ?? CALLBACK_TIMESTAMP_TOLERANCE_SECONDS, + }) + if (!verification.ok) { + const stale = verification.reason === 'stale_timestamp' + return c.json( + errorBody( + stale ? 'stale_timestamp' : 'invalid_signature', + stale ? '请求时间戳超出允许窗口(可能是重放)' : `签名校验失败(${verification.reason})`, + ), + 401, + ) + } + + // 3) 解析并校验请求体(签名已覆盖 body,这里只做结构断言,不做信任边界判定)。 + let parsed: unknown + try { + parsed = JSON.parse(rawBody) + } catch { + return c.json(errorBody('invalid_request', '请求体不是合法 JSON'), 400) + } + if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) { + return c.json(errorBody('invalid_request', '请求体必须是 JSON 对象'), 400) + } + const body = parsed as CallbackRequestBody + if (body.protocolVersion !== CALLBACK_PROTOCOL_VERSION) { + return c.json( + errorBody('unsupported_protocol', `不支持的协议版本:${String(body.protocolVersion)}(期望 ${CALLBACK_PROTOCOL_VERSION})`), + 400, + ) + } + if (!readBodyFields(body)) { + return c.json(errorBody('invalid_request', '请求体缺少 executionId / jobId / jobName / scheduledFor'), 400) + } + if (body.executionId !== executionIdHeader || body.jobId !== jobIdHeader) { + return c.json(errorBody('invalid_request', '请求体 id 与签名头不一致'), 400) + } + + // 4) 分发到业务 handler:名字必须与注册时一致,未知名字是部署期错误,明确回 404。 + const handler = + typeof options.jobs === 'function' + ? options.jobs(body.jobName) ?? undefined + : options.jobs[body.jobName] + if (handler === undefined) { + return c.json( + errorBody('unknown_job', `未声明的任务名:${body.jobName}(receiver 的 jobs 里没有这个 key)`), + 404, + ) + } + + const context: WakerJobContext = { + jobName: body.jobName, + executionId: body.executionId, + jobId: body.jobId, + projectId: body.projectId, + kind: body.kind, + trigger: body.trigger, + misfire: body.misfire === true, + attempt: typeof body.attempt === 'number' ? body.attempt : 0, + scheduledFor: body.scheduledFor, + dispatchedAt: body.dispatchedAt, + timeoutSeconds: body.timeoutSeconds, + payload: body.payload, + } + + // 5) 幂等:同一次执行的重试直接回放首次结果(不重跑业务,也不丢 nextRunAt)。 + if (options.ledger !== undefined) { + const claim = await options.ledger.claim({ + executionId: context.executionId, + jobId: context.jobId, + jobName: context.jobName, + scheduledFor: context.scheduledFor, + }) + if (!claim.claimed) { + return c.json({ + ...(claim.existing?.response ?? {}), + ok: true, + duplicate: true, + }) + } + } + + // 6) 跑业务:异常 → 释放占位 + 5xx,让平台重试(重试仍是同一个 executionId)。 + try { + const outcome = await handler(context) + const nextRunAt = normalizeNextRunAt(outcome?.nextRunAt) + // 业务字段原样回给平台(平台只认 nextRunAt,其它字段留着排障),`ok` 由 SDK 兜底置真。 + const response: Record = { ...(outcome ?? {}), ok: true } + if (nextRunAt === null) delete response.nextRunAt + else response.nextRunAt = nextRunAt + + await options.ledger?.complete(context.executionId, response) + return c.json(response) + } catch (error) { + await options.ledger?.release(context.executionId) + options.onJobError?.(error, context) + return c.json(errorBody('job_failed', '任务执行失败,平台将按策略重试'), 500) + } + }) + + return receiver +} + +export interface MountWakerReceiverOptions extends WakerReceiverOptions { + /** 显式模式(优先于 `env`)。 */ + mode?: WakerMode + /** 模式来源:`WAKER_MODE` 从这里读,缺省按 `cron`。 */ + env?: WakerEnvLike +} + +/** + * 可选接入的挂载入口:**只在 `WAKER_MODE=waker` 时**把 receiver 挂到 `/_waker`。 + * + * 返回 `true` = 已挂载(waker 模式);`false` = 原生模式,一条路由都没加。 + * 原生模式下 SDK 只做了一次 env 判定,不构造 receiver、不发任何网络请求。 + * + * waker 模式下若 signing key 缺失会**立刻抛错**(部署期 fail fast), + * 而不是等到第一次回调才发现验不了签。 + */ +export function mountWakerReceiver( + app: Hono, + options: MountWakerReceiverOptions, +): boolean { + const mode = options.mode ?? resolveWakerMode(options.env) + if (mode !== WAKER_MODE_WAKER) return false + + const key = resolveSigningKey(options, options.env ?? null) + if (key === null) { + throw new Error( + `WAKER_MODE=waker 但缺少 signing key(${options.signingKeyEnv ?? WAKER_SIGNING_KEY_ENV}):` + + '请用 `wrangler secret put` 注入建项目时一次性展示的那把 key。', + ) + } + + const receiver = createWakerReceiver(options) + app.route(CALLBACK_MOUNT_PATH, receiver as unknown as Hono) + return true +} diff --git a/apps/worker/src/waker/verify.ts b/apps/worker/src/waker/verify.ts new file mode 100644 index 0000000..c9259de --- /dev/null +++ b/apps/worker/src/waker/verify.ts @@ -0,0 +1,104 @@ +import { + CALLBACK_SIGNATURE_PREFIX, + CALLBACK_TIMESTAMP_TOLERANCE_SECONDS, + buildSignaturePayload, +} from './protocol' + +/** + * HMAC 验签 helper(对齐 B3 冻结契约)。 + * + * 全部用 Workers / Node 都自带的 WebCrypto:`crypto.subtle.importKey` / `crypto.subtle.verify`。 + * **不手搓 HMAC,也不用 `===` 比较签名**——`crypto.subtle.verify` 是原生常量时间实现, + * 自己逐字节比会是计时侧信道。 + */ + +const encoder = new TextEncoder() + +/** 验签失败原因(下游可据此分支:过期 vs 伪造 vs 没带签名)。 */ +export type SignatureFailureReason = + | 'missing_signature' + | 'malformed_signature' + | 'missing_signed_field' + | 'stale_timestamp' + | 'bad_signature' + +export type SignatureVerification = + | { ok: true } + | { ok: false; reason: SignatureFailureReason } + +export interface VerifySignatureInput { + /** 项目 signing key 明文(平台建项目时一次性展示的那把)。 */ + secret: string + /** `X-Waker-Signature` 头原值(`v2=`)。 */ + signature: string + /** `X-Waker-Timestamp` 头原值(epoch 秒的十进制字符串)。 */ + timestamp: string + /** `X-Waker-Execution-Id`。 */ + executionId: string + /** `X-Waker-Job-Id`。 */ + jobId: string + /** 未解析的原始请求体字符串。 */ + body: string + /** 收到请求的时刻(epoch ms),默认 `Date.now()`;测试可注入。 */ + now?: number + /** 时间窗(秒),默认 {@link CALLBACK_TIMESTAMP_TOLERANCE_SECONDS}。 */ + toleranceSeconds?: number +} + +function hexToBytes(hex: string): Uint8Array | null { + if (hex.length === 0 || hex.length % 2 !== 0) return null + const bytes = new Uint8Array(hex.length / 2) + for (let index = 0; index < bytes.length; index += 1) { + const byte = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16) + if (Number.isNaN(byte)) return null + bytes[index] = byte + } + return bytes +} + +/** + * 验签:材料齐全 → 签名格式 → 时间窗(防重放)→ HMAC 常量时间比对。 + * + * 该函数不抛错,所有失败折成 `{ ok: false, reason }`,便于下游直接映射 HTTP 状态码。 + */ +export async function verifyWakerSignature( + input: VerifySignatureInput, +): Promise { + if (input.signature.length === 0) return { ok: false, reason: 'missing_signature' } + if (input.executionId.length === 0 || input.jobId.length === 0 || input.timestamp.length === 0) { + return { ok: false, reason: 'missing_signed_field' } + } + + if (!input.signature.startsWith(CALLBACK_SIGNATURE_PREFIX)) { + return { ok: false, reason: 'malformed_signature' } + } + const provided = hexToBytes(input.signature.slice(CALLBACK_SIGNATURE_PREFIX.length)) + if (provided === null || provided.length !== 32) { + return { ok: false, reason: 'malformed_signature' } + } + + const timestampSeconds = Number(input.timestamp) + if (!Number.isFinite(timestampSeconds)) return { ok: false, reason: 'malformed_signature' } + + const now = input.now ?? Date.now() + const tolerance = input.toleranceSeconds ?? CALLBACK_TIMESTAMP_TOLERANCE_SECONDS + if (Math.abs(now / 1000 - timestampSeconds) > tolerance) { + return { ok: false, reason: 'stale_timestamp' } + } + + const key = await crypto.subtle.importKey( + 'raw', + encoder.encode(input.secret), + { name: 'HMAC', hash: 'SHA-256' }, + false, + ['verify'], + ) + + const valid = await crypto.subtle.verify( + 'HMAC', + key, + provided, + encoder.encode(buildSignaturePayload(input)), + ) + return valid ? { ok: true } : { ok: false, reason: 'bad_signature' } +} diff --git a/apps/worker/test/helpers/env.ts b/apps/worker/test/helpers/env.ts index 3a36113..331bca0 100644 --- a/apps/worker/test/helpers/env.ts +++ b/apps/worker/test/helpers/env.ts @@ -51,6 +51,7 @@ export class MemoryKV { interface D1Result { results: Record[]; + meta: { changes: number }; } class D1Statement { @@ -80,17 +81,27 @@ class D1Statement { const result = this.db.prepare(this.sql).run(...this.params); return { meta: { changes: Number(result.changes) } }; } + + // D1's batch returns one result per statement, with `results` for queries and + // `meta.changes` for writes. node:sqlite cannot report both at once for a + // write, so pick the shape by statement kind. + execute(): D1Result { + const isQuery = /^\s*(select|with|pragma|explain)\b/i.test(this.sql); + if (isQuery) return { ...this.all(), meta: { changes: 0 } }; + return { results: [], ...this.run() }; + } } export class D1Mock { private readonly db: DatabaseSync; // applyMigrations=false yields an empty database so a test can exercise the - // setup/migration runner end-to-end from a blank slate. - constructor(applyMigrations = true) { + // setup/migration runner end-to-end from a blank slate. `prefix` applies the + // same migrations under a TABLE_PREFIX (e.g. 'hop' → hop_waker_executions). + constructor(applyMigrations = true, prefix = '') { this.db = new DatabaseSync(':memory:'); if (applyMigrations) { - for (const migration of getMigrations('')) { + for (const migration of getMigrations(prefix)) { this.db.exec(migration.sql); } } @@ -101,7 +112,7 @@ export class D1Mock { } batch(statements: D1Statement[]): D1Result[] { - return statements.map((s) => s.all()); + return statements.map((s) => s.execute()); } exec(sql: string): void { diff --git a/apps/worker/test/migrations-runner.test.ts b/apps/worker/test/migrations-runner.test.ts index dc67425..71fa655 100644 --- a/apps/worker/test/migrations-runner.test.ts +++ b/apps/worker/test/migrations-runner.test.ts @@ -57,6 +57,7 @@ test('runMigrations 返回实际生效前缀(未配置 → hop)', async () = [ ['schema_v1', 'applied'], ['schema_v2', 'applied'], + ['schema_v3', 'applied'], ], ); }); @@ -105,7 +106,7 @@ test('前缀一致时不误报:prefixed schema + 同名前缀正常迁移', as assert.equal(result.prefix, 'sl'); assert.deepEqual( result.migrations.map((m) => m.status), - ['skipped', 'skipped'], + ['skipped', 'skipped', 'skipped'], ); }); @@ -118,7 +119,7 @@ test('前缀一致时不误报:unprefixed schema + 显式空前缀正常迁移 assert.equal(result.prefix, ''); assert.deepEqual( result.migrations.map((m) => m.status), - ['skipped', 'skipped'], + ['skipped', 'skipped', 'skipped'], ); }); @@ -141,7 +142,7 @@ test('回归:共享库他表 bare users + Hop 已有前缀 → 增量放行不 assert.equal(result.prefix, 'SL'); assert.deepEqual( result.migrations.map((m) => m.status), - ['skipped', 'skipped'], + ['skipped', 'skipped', 'skipped'], ); }); @@ -162,6 +163,7 @@ test('回归:共享库他表(ZETA_*/eNotify_*)+ 显式空前缀 → 不误 [ ['schema_v1', 'applied'], ['schema_v2', 'applied'], + ['schema_v3', 'applied'], ], ); }); @@ -183,6 +185,7 @@ test('回归:仅外来 d1_migrations(别家文件名)+ prefix=SL → 不 [ ['schema_v1', 'applied'], ['schema_v2', 'applied'], + ['schema_v3', 'applied'], ], ); assert.deepEqual( @@ -190,7 +193,7 @@ test('回归:仅外来 d1_migrations(别家文件名)+ prefix=SL → 不 .prepare('SELECT name FROM _SL_schema_migrations ORDER BY name') .all<{ name: string }>() .results.map((r) => r.name), - ['schema_v1', 'schema_v2'], + ['schema_v1', 'schema_v2', 'schema_v3'], ); }); diff --git a/apps/worker/test/setup.test.ts b/apps/worker/test/setup.test.ts index 67b936c..942cf8b 100644 --- a/apps/worker/test/setup.test.ts +++ b/apps/worker/test/setup.test.ts @@ -109,6 +109,7 @@ test('POST /api/setup: 正确 JSON 密钥把迁移应用到空库并返回结果 [ ['schema_v1', 'applied'], ['schema_v2', 'applied'], + ['schema_v3', 'applied'], ], ); }); @@ -299,7 +300,7 @@ test('POST /api/admin/setup: 管理员执行同一迁移逻辑并写审计日志 const body = await res.json(); assert.deepEqual( body.migrations.map((m: { status: string }) => m.status), - ['skipped', 'skipped'], + ['skipped', 'skipped', 'skipped'], ); const row = ctx.db @@ -311,7 +312,7 @@ test('POST /api/admin/setup: 管理员执行同一迁移逻辑并写审计日志 assert.equal(row?.target_id, 'setup'); assert.deepEqual(JSON.parse(row?.details ?? '{}'), { applied: 0, - skipped: 2, + skipped: 3, error: 0, }); }); diff --git a/apps/worker/test/waker-callback.test.ts b/apps/worker/test/waker-callback.test.ts new file mode 100644 index 0000000..c665d96 --- /dev/null +++ b/apps/worker/test/waker-callback.test.ts @@ -0,0 +1,453 @@ +// 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. +// +// The request is signed here with WebCrypto exactly as documented by the +// frozen protocol (`\n\n\n`, HMAC-SHA256, +// `v2=`), so the test exercises the wire contract rather than an internal +// shortcut. +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import worker, { app } from '../src/index.ts'; +import { tbl } from '../src/lib/db.ts'; +import { + WAKER_JOB_CRON, + WAKER_JOB_NIGHTLY_CLEANUP, +} from '../src/services/waker.ts'; +import type { Env } from '../src/types.ts'; +import { CALLBACK_MOUNT_PATH } from '../src/waker/index.ts'; +import { makeEnv, request, type TestEnv } from './helpers/app.ts'; +import { D1Mock } from './helpers/env.ts'; + +const SIGNING_KEY = 'waker-test-signing-key-not-a-real-value'; +const JOB_ID = '9b1f0d6e-6a4f-4b1e-9f2c-1d0c3a5e7b11'; +const PROJECT_ID = '6a2c9f5d-3e8b-4a71-8c0d-5b2f7e9a1c33'; +const encoder = new TextEncoder(); + +interface SignedRequestInput { + executionId?: string; + jobName?: string; + jobId?: string; + /** Epoch seconds written into X-Waker-Timestamp and covered by the signature. */ + timestamp?: number; + key?: string; + bodyOverride?: string; +} + +async function hmacHex(key: string, message: string): Promise { + const cryptoKey = await crypto.subtle.importKey( + 'raw', + encoder.encode(key), + { name: 'HMAC', hash: 'SHA-256' }, + false, + ['sign'], + ); + const signature = await crypto.subtle.sign( + 'HMAC', + cryptoKey, + encoder.encode(message), + ); + return [...new Uint8Array(signature)] + .map((byte) => byte.toString(16).padStart(2, '0')) + .join(''); +} + +interface SignedRequest { + body: string; + headers: Record; +} + +async function signedRequest( + input: SignedRequestInput = {}, +): Promise { + const executionId = input.executionId ?? crypto.randomUUID(); + const jobId = input.jobId ?? JOB_ID; + const timestamp = input.timestamp ?? Math.floor(Date.now() / 1000); + const body = + input.bodyOverride ?? + JSON.stringify({ + protocolVersion: 2, + executionId, + jobId, + projectId: PROJECT_ID, + jobName: input.jobName ?? WAKER_JOB_NIGHTLY_CLEANUP, + kind: 'cron', + trigger: 'schedule', + misfire: false, + attempt: 0, + scheduledFor: Date.now(), + dispatchedAt: Date.now(), + timeoutSeconds: 30, + payload: null, + }); + const signature = await hmacHex( + input.key ?? SIGNING_KEY, + `${timestamp}\n${executionId}\n${jobId}\n${body}`, + ); + return { + body, + headers: { + 'content-type': 'application/json', + 'X-Waker-Timestamp': String(timestamp), + 'X-Waker-Execution-Id': executionId, + 'X-Waker-Job-Id': jobId, + 'X-Waker-Signature': `v2=${signature}`, + }, + }; +} + +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, + }); +} + +function seedExpiredRows(ctx: TestEnv, prefix = 'hop'): void { + const envLike = { TABLE_PREFIX: prefix }; + ctx.env.DB.prepare( + `INSERT INTO ${tbl(envLike, 'verifications')} (identifier, type, code_hash, expires_at) + VALUES ('old@example.com', 'email_otp', 'hash-old', unixepoch() - 10)`, + ).run(); + ctx.env.DB.prepare( + `INSERT INTO ${tbl(envLike, 'verifications')} (identifier, type, code_hash, expires_at) + VALUES ('fresh@example.com', 'email_otp', 'hash-fresh', unixepoch() + 3600)`, + ).run(); + ctx.env.DB.prepare( + `INSERT INTO ${tbl(envLike, 'totp_used')} (user_id, code, used_at) + VALUES ('u1', '111111', unixepoch() - 91)`, + ).run(); + ctx.env.DB.prepare( + `INSERT INTO ${tbl(envLike, 'totp_used')} (user_id, code, used_at) + VALUES ('u1', '222222', unixepoch() - 5)`, + ).run(); +} + +function countRows(ctx: TestEnv, table: string, prefix = 'hop'): number { + const row = ctx.env.DB.prepare( + `SELECT COUNT(*) AS n FROM ${tbl({ TABLE_PREFIX: prefix }, table)}`, + ).first<{ n: number }>(); + return row?.n ?? 0; +} + +function callbackPath(): string { + return `${CALLBACK_MOUNT_PATH}/execute`; +} + +// ─── when the integration is off, the path must answer 404 explicitly ──────── + +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, + }, +]) { + 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, + }); + const signed = await signedRequest(); + const res = await request( + app, + callbackPath(), + { 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); + 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); + }); +} + +test('GET /_waker(无 /execute)也是 JSON 404,不落到短链路由或 SPA', async () => { + const ctx = wakerEnv(); + const res = await request(app, CALLBACK_MOUNT_PATH, { 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 () => { + const ctx = wakerEnv(); + seedExpiredRows(ctx); + const signed = await signedRequest({ executionId: 'exec-ok-1' }); + + const res = await request( + app, + callbackPath(), + { method: 'POST', headers: signed.headers, body: signed.body }, + ctx, + ); + + assert.equal(res.status, 200); + const body = await res.json(); + assert.equal(body.ok, true); + assert.deepEqual(body.cleanup.verifications, 1); + assert.deepEqual(body.cleanup.totpUsed, 1); + assert.equal(typeof body.cleanup.durationMs, 'number'); + + // Only the expired rows went away; the live ones are untouched. + assert.equal(countRows(ctx, 'verifications'), 1); + assert.equal(countRows(ctx, 'totp_used'), 1); + // Ledger row written under the TABLE_PREFIX-derived name. + assert.equal(countRows(ctx, 'waker_executions'), 1); +}); + +test('回调日志含清理计数与耗时,且不含 signing key', async () => { + const ctx = wakerEnv(); + seedExpiredRows(ctx); + const signed = await signedRequest(); + const lines: string[] = []; + const originals = { + log: console.log, + info: console.info, + warn: console.warn, + error: console.error, + }; + for (const level of ['log', 'info', 'warn', 'error'] as const) { + console[level] = (...args: unknown[]) => { + lines.push(args.map(String).join(' ')); + }; + } + try { + const res = await request( + app, + callbackPath(), + { method: 'POST', headers: signed.headers, body: signed.body }, + ctx, + ); + assert.equal(res.status, 200); + } finally { + console.log = originals.log; + console.info = originals.info; + console.warn = originals.warn; + console.error = originals.error; + } + const joined = lines.join('\n'); + assert.match(joined, /"event":"nightly_cleanup"/); + assert.match(joined, /"source":"waker"/); + assert.match(joined, /"verifications":1/); + assert.match(joined, /"totpUsed":1/); + assert.match(joined, /"durationMs":\d+/); + assert.ok(!joined.includes(SIGNING_KEY), '日志不得包含 signing key'); +}); + +// ─── negative cases: verify failures change nothing ────────────────────────── + +test('签名被篡改 → 401 invalid_signature,清理不执行', async () => { + const ctx = wakerEnv(); + seedExpiredRows(ctx); + const signed = await signedRequest(); + const signature = signed.headers['X-Waker-Signature'] ?? ''; + const tampered = `${signature.slice(0, -1)}${signature.endsWith('0') ? '1' : '0'}`; + + const res = await request( + app, + callbackPath(), + { + method: 'POST', + headers: { ...signed.headers, 'X-Waker-Signature': tampered }, + body: signed.body, + }, + ctx, + ); + + assert.equal(res.status, 401); + assert.equal((await res.json()).error.code, 'invalid_signature'); + assert.equal(countRows(ctx, 'verifications'), 2); + assert.equal(countRows(ctx, 'totp_used'), 2); + assert.equal(countRows(ctx, 'waker_executions'), 0); +}); + +test('时间戳超出 300s 窗口 → 401 stale_timestamp,清理不执行', async () => { + const ctx = wakerEnv(); + seedExpiredRows(ctx); + const signed = await signedRequest({ + timestamp: Math.floor(Date.now() / 1000) - 301, + }); + + const res = await request( + app, + callbackPath(), + { method: 'POST', headers: signed.headers, body: signed.body }, + ctx, + ); + + assert.equal(res.status, 401); + assert.equal((await res.json()).error.code, 'stale_timestamp'); + assert.equal(countRows(ctx, 'verifications'), 2); + assert.equal(countRows(ctx, 'waker_executions'), 0); +}); + +test('用错的 signing key 签名 → 401,清理不执行', async () => { + const ctx = wakerEnv(); + seedExpiredRows(ctx); + const signed = await signedRequest({ key: 'not-the-project-key' }); + + const res = await request( + app, + callbackPath(), + { method: 'POST', headers: signed.headers, body: signed.body }, + ctx, + ); + + assert.equal(res.status, 401); + assert.equal(countRows(ctx, 'verifications'), 2); +}); + +test('body 的 executionId 与签名头不一致 → 400,清理不执行', async () => { + const ctx = wakerEnv(); + seedExpiredRows(ctx); + const signed = await signedRequest({ executionId: 'exec-header' }); + const body = JSON.parse(signed.body); + body.executionId = 'exec-body'; + // Re-sign the swapped body so only the header/body identity check can fail. + const timestamp = signed.headers['X-Waker-Timestamp'] ?? ''; + const jobId = signed.headers['X-Waker-Job-Id'] ?? ''; + const swapped = JSON.stringify(body); + const signature = await hmacHex( + SIGNING_KEY, + `${timestamp}\nexec-header\n${jobId}\n${swapped}`, + ); + + const res = await request( + app, + callbackPath(), + { + method: 'POST', + headers: { ...signed.headers, 'X-Waker-Signature': `v2=${signature}` }, + body: swapped, + }, + ctx, + ); + + assert.equal(res.status, 400); + assert.equal((await res.json()).error.code, 'invalid_request'); + assert.equal(countRows(ctx, 'verifications'), 2); +}); + +test('未声明的任务名(与 waker 管理面注册名不一致)→ 404 unknown_job,清理不执行', async () => { + const ctx = wakerEnv(); + seedExpiredRows(ctx); + const signed = await signedRequest({ jobName: 'nightly-cleanup-typo' }); + + const res = await request( + app, + callbackPath(), + { method: 'POST', headers: signed.headers, body: signed.body }, + ctx, + ); + + assert.equal(res.status, 404); + assert.equal((await res.json()).error.code, 'unknown_job'); + 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 () => { + const ctx = wakerEnv(); + seedExpiredRows(ctx); + const signed = await signedRequest({ executionId: 'exec-replay' }); + const send = () => + request( + app, + callbackPath(), + { method: 'POST', headers: signed.headers, body: signed.body }, + ctx, + ); + + const first = await send(); + assert.equal(first.status, 200); + assert.equal((await first.json()).cleanup.verifications, 1); + + // New expired rows appear after the first run: a replayed callback must not + // touch them, proving the second delivery did no work at all. + ctx.env.DB.prepare( + `INSERT INTO ${tbl({ TABLE_PREFIX: 'hop' }, 'verifications')} (identifier, type, code_hash, expires_at) + VALUES ('later@example.com', 'email_otp', 'hash-later', unixepoch() - 10)`, + ).run(); + + const second = await send(); + assert.equal(second.status, 200); + const body = await second.json(); + assert.equal(body.duplicate, true); + assert.equal(countRows(ctx, 'verifications'), 2); // fresh + later, none deleted + assert.equal(countRows(ctx, 'waker_executions'), 1); +}); + +test('清理本身幂等:重跑第二次为无操作', async () => { + const ctx = wakerEnv(); + seedExpiredRows(ctx); + const first = await signedRequest({ executionId: 'exec-rerun-1' }); + const second = await signedRequest({ executionId: 'exec-rerun-2' }); + + const firstRes = await request( + app, + callbackPath(), + { method: 'POST', headers: first.headers, body: first.body }, + ctx, + ); + assert.equal((await firstRes.json()).cleanup.verifications, 1); + + const secondRes = await request( + app, + callbackPath(), + { method: 'POST', headers: second.headers, body: second.body }, + ctx, + ); + const body = await secondRes.json(); + assert.equal(body.cleanup.verifications, 0); + assert.equal(body.cleanup.totpUsed, 0); +}); + +// ─── one business function, two entries ───────────────────────────────────── + +test('原生 scheduled() 与回调共用同一清理函数(两条判据一致)', async () => { + const ctx = wakerEnv(); + seedExpiredRows(ctx); + + await worker.scheduled( + { cron: WAKER_JOB_CRON } as unknown as ScheduledController, + ctx.env, + { + waitUntil: () => {}, + passThroughOnException: () => {}, + } as unknown as ExecutionContext, + ); + + assert.equal(countRows(ctx, 'verifications'), 1); + assert.equal(countRows(ctx, 'totp_used'), 1); +}); diff --git a/apps/worker/test/waker-schema.test.ts b/apps/worker/test/waker-schema.test.ts new file mode 100644 index 0000000..e845d33 --- /dev/null +++ b/apps/worker/test/waker-schema.test.ts @@ -0,0 +1,85 @@ +// schema_v3 — the executionId ledger the waker callback writes through. +// +// Two guarantees the waker migration contract asks for: +// 1. the columns match the waker client SDK's executionLedgerDdl() one for +// one (so SDK upgrades that need a column change fail here, loudly); +// 2. the table name goes through TABLE_PREFIX (hop_waker_executions by +// default) and no other project's table is touched. +import assert from 'node:assert/strict'; +import { DatabaseSync } from 'node:sqlite'; +import { test } from 'node:test'; +import { getMigrations } from '../src/lib/migrations.ts'; +import { executionLedgerDdl } from '../src/waker/ledger.ts'; + +/** Column definitions of a `CREATE TABLE name ( … );` statement, normalised. */ +function columnDefinitions(ddl: string): string[] { + const open = ddl.indexOf('('); + const close = ddl.lastIndexOf(')'); + assert.ok(open > 0 && close > open, `not a CREATE TABLE statement: ${ddl}`); + return ddl + .slice(open + 1, close) + .split('\n') + .map((line) => line.trim().replace(/,$/, '')) + .filter((line) => line.length > 0) + .map((line) => line.replace(/\s+/g, ' ')); +} + +function schemaV3(prefix: string): string { + const migration = getMigrations(prefix).find((m) => m.name === 'schema_v3'); + assert.ok(migration, 'schema_v3 迁移缺失'); + return migration.sql; +} + +test('schema_v3 的列与 SDK executionLedgerDdl() 逐列一致', () => { + const sdk = columnDefinitions(executionLedgerDdl('hop_waker_executions')); + const migration = columnDefinitions(schemaV3('hop')); + assert.deepEqual(migration, sdk); +}); + +test('schema_v3 只建 {prefix}waker_executions 一张表,不碰共享库里其他表', () => { + const sql = schemaV3('hop'); + const statements = sql + .split(';') + .map((s) => s.trim()) + .filter((s) => s.length > 0); + assert.equal(statements.length, 1); + assert.match( + statements[0] ?? '', + /^CREATE TABLE IF NOT EXISTS hop_waker_executions \(/, + ); + assert.doesNotMatch(sql, /DROP |ALTER TABLE (?!hop_waker_executions)/i); +}); + +test('默认前缀下建出 hop_waker_executions,列名与主键符合 SDK 契约', () => { + const db = new DatabaseSync(':memory:'); + db.exec(getMigrations('hop').find((m) => m.name === 'schema_v3')?.sql ?? ''); + const columns = db + .prepare('PRAGMA table_info(hop_waker_executions)') + .all() as { + name: string; + type: string; + notnull: number; + pk: number; + }[]; + assert.deepEqual( + columns.map((c) => c.name), + [ + 'execution_id', + 'job_id', + 'job_name', + 'scheduled_for', + 'status', + 'response_json', + 'claimed_at', + 'completed_at', + ], + ); + assert.equal(columns.find((c) => c.name === 'execution_id')?.pk, 1); + assert.equal(columns.find((c) => c.name === 'response_json')?.notnull, 0); + assert.equal(columns.find((c) => c.name === 'completed_at')?.notnull, 0); +}); + +test('无前缀迁移文件生成内容与 schema_v3 对应(0003)', () => { + const migration = getMigrations('').find((m) => m.name === 'schema_v3'); + assert.equal(migration?.fileName, '0003_waker_executions.sql'); +}); diff --git a/apps/worker/wrangler.toml b/apps/worker/wrangler.toml index 15ee2df..06b8c47 100644 --- a/apps/worker/wrangler.toml +++ b/apps/worker/wrangler.toml @@ -8,6 +8,10 @@ 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" @@ -28,4 +32,8 @@ 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. crons = ["0 3 * * *"] diff --git a/biome.json b/biome.json index 166d55d..febaa84 100644 --- a/biome.json +++ b/biome.json @@ -7,7 +7,11 @@ }, "files": { "ignoreUnknown": false, - "includes": ["**", "!apps/web/src/styles/globals.css"] + "includes": [ + "**", + "!apps/web/src/styles/globals.css", + "!apps/worker/src/waker" + ] }, "formatter": { "enabled": true, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5ef0ed9..6be0cd9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -100,7 +100,7 @@ importers: specifier: ^13.0.0 version: 13.3.3 hono: - specifier: ^4.6.12 + specifier: ^4.13.14 version: 4.13.14 jose: specifier: ^6.0.0 diff --git a/turbo.json b/turbo.json index c122e6c..c67a4c9 100644 --- a/turbo.json +++ b/turbo.json @@ -1,6 +1,13 @@ { "$schema": "https://turbo.build/schema.json", - "globalPassThroughEnv": ["TABLE_PREFIX"], + "globalPassThroughEnv": [ + "TABLE_PREFIX", + "WAKER_MODE", + "WAKER_URL", + "WAKER_TRIGGERS", + "WRANGLER_TOML", + "GITHUB_OUTPUT" + ], "tasks": { "build": { "dependsOn": ["^build"],