From 3a7d65077e70b861bd836f66080b7afeb0da2cd9 Mon Sep 17 00:00:00 2001 From: Todos Date: Sun, 18 Oct 2026 00:31:35 +0800 Subject: [PATCH 1/2] feat(worker): add test baseline, schema single-source, and low hardening - BE-Q2/CI-C1: node:test route tests for auth/links/redirect backed by an in-memory SQLite D1 (node:sqlite) and tsx for .js->.ts resolution; wired `pnpm test` into CI so deploy is gated on it - BE-Q1: generate migrations/*.sql from lib/migrations.ts and assert consistency in a test - BE-Q3: app.onError with structured logging and a per-request id - BE-S9: forgot-password sends email via waitUntil (timing side-channel) - BE-S10: CORS allows localhost origins only on plain-http (dev) - BE-S11: SPA/static responses get security headers plus a Vite-compatible CSP - BE-S12: totp setup becomes POST (route + client.ts call) - BE-C4: delete stale verification codes before inserting new ones - BE-R2: redact Resend failure before logging - CI-C9: tag.yml verifies CI on main, release.yml validates tag source/format, vite dev proxy target configurable via env Checkpoint: ZsFIsGEbQRfT1JpslSW3E --- .github/workflows/ci.yml | 5 + .github/workflows/release.yml | 48 +++ .github/workflows/tag.yml | 33 ++ apps/web/src/api/client.ts | 4 +- apps/web/vite.config.ts | 4 +- apps/worker/migrations/0001_init.sql | 52 ++-- apps/worker/migrations/0002_token_version.sql | 5 +- apps/worker/package.json | 4 +- apps/worker/scripts/generate-migrations.ts | 43 +++ apps/worker/src/index.ts | 64 ++-- apps/worker/src/lib/email.ts | 10 +- apps/worker/src/lib/migrations.ts | 12 +- apps/worker/src/lib/security.ts | 32 ++ apps/worker/src/lib/smtp.ts | 6 +- apps/worker/src/routes/auth.ts | 76 +++-- apps/worker/src/types.ts | 1 + apps/worker/test/auth.test.ts | 283 ++++++++++++++++++ apps/worker/test/email.test.ts | 41 +++ apps/worker/test/helpers/app.ts | 126 ++++++++ apps/worker/test/helpers/env.ts | 106 +++++++ apps/worker/test/links.test.ts | 194 ++++++++++++ apps/worker/test/migrations.test.ts | 46 +++ apps/worker/test/redirect.test.ts | 84 ++++++ pnpm-lock.yaml | 31 +- 24 files changed, 1217 insertions(+), 93 deletions(-) create mode 100644 apps/worker/scripts/generate-migrations.ts create mode 100644 apps/worker/src/lib/security.ts create mode 100644 apps/worker/test/auth.test.ts create mode 100644 apps/worker/test/email.test.ts create mode 100644 apps/worker/test/helpers/app.ts create mode 100644 apps/worker/test/helpers/env.ts create mode 100644 apps/worker/test/links.test.ts create mode 100644 apps/worker/test/migrations.test.ts create mode 100644 apps/worker/test/redirect.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 304bb83..6a998d1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -41,6 +41,11 @@ jobs: - name: Build run: pnpm build + # CI-C1: unit tests are part of CI, which the deploy workflow gates on — + # so a regression in auth/links/redirect can no longer auto-deploy. + - name: Test + run: pnpm test + # Deploy scripts: local D1 migration scenarios plus smoke/verify checks. # No Cloudflare credentials needed. - name: Shellcheck deploy scripts diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7933e0c..d474f97 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -22,6 +22,54 @@ jobs: permissions: contents: write steps: + # CI-C9: validate the tag's format and origin before creating a release — + # a release must point at a real tag that is reachable from main. + - name: Validate tag + uses: actions/github-script@v9 + env: + TAG: ${{ inputs.tag || github.ref_name }} + with: + script: | + const tag = process.env.TAG; + if (!/^v\d+\.\d+\.\d+$/.test(tag)) { + core.setFailed(`Invalid tag format "${tag}"; must match v...`); + return; + } + let ref; + try { + ({ data: ref } = await github.rest.git.getRef({ + owner: context.repo.owner, + repo: context.repo.repo, + ref: `tags/${tag}`, + })); + } catch { + core.setFailed(`Tag "${tag}" does not exist in the repository.`); + return; + } + // Resolve annotated tags down to the commit they point at. + let sha = ref.object.sha; + if (ref.object.type === 'tag') { + const { data: tagObj } = await github.rest.git.getTag({ + owner: context.repo.owner, + repo: context.repo.repo, + tag_sha: sha, + }); + sha = tagObj.object.sha; + } + const { data: cmp } = await github.rest.repos.compareCommits({ + owner: context.repo.owner, + repo: context.repo.repo, + base: 'main', + head: sha, + }); + if (cmp.status === 'ahead' || cmp.status === 'diverged') { + core.setFailed( + `Tag "${tag}" (${sha}) is not on main (status: ${cmp.status}); refusing to release.`, + ); + return; + } + core.info(`Tag "${tag}" (${sha}) is on main (status: ${cmp.status}).`); + - name: Create GitHub Release uses: actions/github-script@v9 env: diff --git a/.github/workflows/tag.yml b/.github/workflows/tag.yml index 4e50ab2..edae37e 100644 --- a/.github/workflows/tag.yml +++ b/.github/workflows/tag.yml @@ -15,6 +15,7 @@ jobs: runs-on: ubuntu-latest permissions: contents: write + actions: read env: TAG: ${{ inputs.tag }} @@ -46,6 +47,38 @@ jobs: fi echo "✅ Tag '$TAG' does not exist, proceeding..." + # CI-C9: never tag a commit whose CI did not pass — a tag feeds straight + # into release.yml, so it must only point at a verified main HEAD. + - name: Verify main CI passed + uses: actions/github-script@v9 + env: + WORKFLOW_NAME: CI + with: + script: | + const { stdout } = await exec.getExecOutput('git', ['rev-parse', 'HEAD']); + const sha = stdout.trim(); + core.info(`Checking CI status for main@${sha}`); + const { data } = await github.rest.actions.listWorkflowRunsForRepo({ + owner: context.repo.owner, + repo: context.repo.repo, + workflow_id: process.env.WORKFLOW_NAME, + head_sha: sha, + per_page: 10, + }); + const runs = data.workflow_runs; + if (runs.length === 0) { + core.setFailed(`No CI run found for main@${sha}; run CI on main before tagging.`); + return; + } + const latest = runs[0]; + if (latest.status !== 'completed' || latest.conclusion !== 'success') { + core.setFailed( + `CI for main@${sha} is ${latest.status}/${latest.conclusion}; tag only after a successful CI run.`, + ); + return; + } + core.info(`CI for main@${sha} succeeded (run ${latest.id}).`); + - name: Configure Git run: | git config user.name "github-actions[bot]" diff --git a/apps/web/src/api/client.ts b/apps/web/src/api/client.ts index b9a0f1b..5456f3e 100644 --- a/apps/web/src/api/client.ts +++ b/apps/web/src/api/client.ts @@ -260,7 +260,9 @@ export const authApi = { // TOTP totpSetup: () => - request<{ secret: string; uri: string }>('/auth/2fa/totp/setup'), + request<{ secret: string; uri: string }>('/auth/2fa/totp/setup', { + method: 'POST', + }), totpConfirm: (code: string) => request<{ success: boolean; backupCodes: string[] }>( '/auth/2fa/totp/confirm', diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 5dcfd96..2702708 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -13,7 +13,9 @@ export default defineConfig({ server: { proxy: { '/api': { - target: 'http://localhost:8787', + // CI-C9: the worker origin is configurable so local setups that run the + // worker on a different host/port don't have to edit this file. + target: process.env.API_PROXY_TARGET ?? 'http://localhost:8787', changeOrigin: true, }, }, diff --git a/apps/worker/migrations/0001_init.sql b/apps/worker/migrations/0001_init.sql index a644613..1938a45 100644 --- a/apps/worker/migrations/0001_init.sql +++ b/apps/worker/migrations/0001_init.sql @@ -1,6 +1,7 @@ --- This is the canonical schema for a fresh deployment. +-- DO NOT EDIT. Generated from src/lib/migrations.ts (getMigrations("")). +-- Regenerate with: pnpm --filter @shortlink/worker generate:migrations -CREATE TABLE users ( +CREATE TABLE IF NOT EXISTS users ( id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), email TEXT UNIQUE NOT NULL, username TEXT UNIQUE NOT NULL, @@ -15,8 +16,7 @@ CREATE TABLE users ( created_at INTEGER NOT NULL DEFAULT (unixepoch()), updated_at INTEGER NOT NULL DEFAULT (unixepoch()) ); - -CREATE TABLE passkeys ( +CREATE TABLE IF NOT EXISTS passkeys ( id TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, public_key TEXT NOT NULL, @@ -27,9 +27,8 @@ CREATE TABLE passkeys ( created_at INTEGER NOT NULL DEFAULT (unixepoch()), last_used_at INTEGER ); -CREATE INDEX idx_passkeys_user_id ON passkeys(user_id); - -CREATE TABLE links ( +CREATE INDEX IF NOT EXISTS idx_passkeys_user_id ON passkeys(user_id); +CREATE TABLE IF NOT EXISTS links ( id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, slug TEXT UNIQUE NOT NULL, @@ -41,11 +40,10 @@ CREATE TABLE links ( created_at INTEGER NOT NULL DEFAULT (unixepoch()), updated_at INTEGER NOT NULL DEFAULT (unixepoch()) ); -CREATE INDEX idx_links_slug ON links(slug); -CREATE INDEX idx_links_user_id ON links(user_id); -CREATE INDEX idx_links_expires_at ON links(expires_at) WHERE expires_at IS NOT NULL; - -CREATE TABLE click_logs ( +CREATE INDEX IF NOT EXISTS idx_links_slug ON links(slug); +CREATE INDEX IF NOT EXISTS idx_links_user_id ON links(user_id); +CREATE INDEX IF NOT EXISTS idx_links_expires_at ON links(expires_at) WHERE expires_at IS NOT NULL; +CREATE TABLE IF NOT EXISTS click_logs ( id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), link_id TEXT NOT NULL REFERENCES links(id) ON DELETE CASCADE, ip_address TEXT, @@ -58,11 +56,10 @@ CREATE TABLE click_logs ( os TEXT, created_at INTEGER NOT NULL DEFAULT (unixepoch()) ); -CREATE INDEX idx_click_logs_link_id ON click_logs(link_id); -CREATE INDEX idx_click_logs_created_at ON click_logs(created_at); -CREATE INDEX idx_click_logs_link_time ON click_logs(link_id, created_at); - -CREATE TABLE verifications ( +CREATE INDEX IF NOT EXISTS idx_click_logs_link_id ON click_logs(link_id); +CREATE INDEX IF NOT EXISTS idx_click_logs_created_at ON click_logs(created_at); +CREATE INDEX IF NOT EXISTS idx_click_logs_link_time ON click_logs(link_id, created_at); +CREATE TABLE IF NOT EXISTS verifications ( id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), identifier TEXT NOT NULL, type TEXT NOT NULL CHECK (type IN ('email_otp', 'password_reset', 'email_verify')), @@ -72,14 +69,13 @@ CREATE TABLE verifications ( used INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL DEFAULT (unixepoch()) ); -CREATE INDEX idx_verifications_identifier ON verifications(identifier, type); - -CREATE TABLE settings ( +CREATE INDEX IF NOT EXISTS idx_verifications_identifier ON verifications(identifier, type); +CREATE TABLE IF NOT EXISTS settings ( key TEXT PRIMARY KEY, value TEXT NOT NULL, updated_at INTEGER NOT NULL DEFAULT (unixepoch()) ); -INSERT INTO settings (key, value) VALUES +INSERT OR IGNORE INTO settings (key, value) VALUES ('registration_enabled', 'true'), ('require_email_verification', 'false'), ('app_name', 'ShortLink'), @@ -92,8 +88,7 @@ INSERT INTO settings (key, value) VALUES ('resend_api_key', ''), ('email_from_domain', ''), ('email_from_name', ''); - -CREATE TABLE audit_logs ( +CREATE TABLE IF NOT EXISTS audit_logs ( id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), admin_id TEXT REFERENCES users(id) ON DELETE SET NULL, action TEXT NOT NULL, @@ -101,14 +96,13 @@ CREATE TABLE audit_logs ( details TEXT, created_at INTEGER NOT NULL DEFAULT (unixepoch()) ); -CREATE INDEX idx_audit_logs_admin_id ON audit_logs(admin_id); -CREATE INDEX idx_audit_logs_created_at ON audit_logs(created_at); -CREATE INDEX idx_audit_logs_target_id ON audit_logs(target_id); - -CREATE TABLE totp_used ( +CREATE INDEX IF NOT EXISTS idx_audit_logs_admin_id ON audit_logs(admin_id); +CREATE INDEX IF NOT EXISTS idx_audit_logs_created_at ON audit_logs(created_at); +CREATE INDEX IF NOT EXISTS idx_audit_logs_target_id ON audit_logs(target_id); +CREATE TABLE IF NOT EXISTS totp_used ( user_id TEXT NOT NULL, code TEXT NOT NULL, used_at INTEGER NOT NULL DEFAULT (unixepoch()), PRIMARY KEY (user_id, code) ); -CREATE INDEX idx_totp_used_at ON totp_used(used_at); +CREATE INDEX IF NOT EXISTS idx_totp_used_at ON totp_used(used_at); diff --git a/apps/worker/migrations/0002_token_version.sql b/apps/worker/migrations/0002_token_version.sql index 607355b..2e13608 100644 --- a/apps/worker/migrations/0002_token_version.sql +++ b/apps/worker/migrations/0002_token_version.sql @@ -1,5 +1,4 @@ --- BE-S3/S4: per-user token_version — bumping it revokes all of a user's sessions --- (password change/reset, admin disable/demote). Keep in sync with the `schema_v2` --- migration embedded in routes/setup.ts. +-- DO NOT EDIT. Generated from src/lib/migrations.ts (getMigrations("")). +-- Regenerate with: pnpm --filter @shortlink/worker generate:migrations ALTER TABLE users ADD COLUMN token_version INTEGER NOT NULL DEFAULT 0; diff --git a/apps/worker/package.json b/apps/worker/package.json index b97dc9d..7409355 100644 --- a/apps/worker/package.json +++ b/apps/worker/package.json @@ -7,7 +7,8 @@ "dev": "wrangler dev", "build": "tsc --noEmit", "typecheck": "tsc --noEmit", - "test": "node --test test/*.test.ts", + "test": "node --import tsx --test test/*.test.ts", + "generate:migrations": "node --import tsx scripts/generate-migrations.ts", "deploy": "wrangler deploy", "db:migrate:local": "wrangler d1 migrations apply DB --local", "db:migrate": "wrangler d1 migrations apply DB --remote" @@ -20,6 +21,7 @@ }, "devDependencies": { "@cloudflare/workers-types": "^4.20241205.0", + "tsx": "^4.23.15", "typescript": "^6.0.0", "wrangler": "^4.0.0" } diff --git a/apps/worker/scripts/generate-migrations.ts b/apps/worker/scripts/generate-migrations.ts new file mode 100644 index 0000000..1fbee64 --- /dev/null +++ b/apps/worker/scripts/generate-migrations.ts @@ -0,0 +1,43 @@ +// Generates apps/worker/migrations/*.sql from src/lib/migrations.ts +// (getMigrations('')), so the wrangler migration files and the setup-route / +// prefixed migrations share a single source of truth. +// +// Run from apps/worker: `node --import tsx scripts/generate-migrations.ts` +// (or `pnpm generate:migrations`). The consistency test in +// test/migrations.test.ts fails if a checked-in .sql file drifts from the +// generated content. +import { mkdirSync, writeFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { getMigrations } from '../src/lib/migrations.ts'; + +const here = dirname(fileURLToPath(import.meta.url)); +const migrationsDir = join(here, '..', 'migrations'); + +const HEADER = + '-- DO NOT EDIT. Generated from src/lib/migrations.ts (getMigrations("")).\n' + + '-- Regenerate with: pnpm --filter @shortlink/worker generate:migrations\n'; + +// Map of wrangler migration file name -> file content. +export function renderMigrationFiles(): Record { + const files: Record = {}; + for (const migration of getMigrations('')) { + files[migration.fileName] = `${HEADER}\n${migration.sql.trim()}\n`; + } + return files; +} + +function isMain(): boolean { + return ( + process.argv[1] !== undefined && + import.meta.url === pathToFileURL(process.argv[1]).href + ); +} + +if (isMain()) { + mkdirSync(migrationsDir, { recursive: true }); + for (const [name, content] of Object.entries(renderMigrationFiles())) { + writeFileSync(join(migrationsDir, name), content); + console.log(`wrote migrations/${name}`); + } +} diff --git a/apps/worker/src/index.ts b/apps/worker/src/index.ts index 203bbc2..f481e24 100644 --- a/apps/worker/src/index.ts +++ b/apps/worker/src/index.ts @@ -2,6 +2,7 @@ import { Hono } from 'hono'; import { cors } from 'hono/cors'; import { tbl } from './lib/db.js'; import { getCachedSetting, setCachedSetting } from './lib/kv.js'; +import { API_CSP, SPA_CSP, securityHeaders } from './lib/security.js'; import { RESERVED_SLUGS } from './lib/slug.js'; import adminRoutes from './routes/admin.js'; import analyticsRoutes from './routes/analytics.js'; @@ -13,21 +14,34 @@ import type { Env, Variables } from './types.js'; const app = new Hono<{ Bindings: Env; Variables: Variables }>(); +// ─── Request ID + structured error handling (BE-Q3) ─────────────────────────── +app.use('*', async (c, next) => { + c.set('requestId', crypto.randomUUID()); + await next(); +}); + +// BE-Q3: log unhandled errors with structured fields (path, error name, +// requestId) and never leak internal details to the client. +app.onError((err, c) => { + console.error( + JSON.stringify({ + level: 'error', + path: c.req.path, + method: c.req.method, + error: err instanceof Error ? err.name : typeof err, + requestId: c.get('requestId'), + }), + ); + return c.json({ error: 'Internal Server Error' }, 500); +}); + // ─── Security headers ───────────────────────────────────────────────────────── app.use('/api/*', async (c, next) => { await next(); - c.header('X-Content-Type-Options', 'nosniff'); - c.header('X-Frame-Options', 'DENY'); - c.header('Referrer-Policy', 'strict-origin-when-cross-origin'); - c.header( - 'Content-Security-Policy', - "default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'self'", - ); - if (c.env.APP_URL.startsWith('https')) { - c.header( - 'Strict-Transport-Security', - 'max-age=63072000; includeSubDomains', - ); + for (const [k, v] of Object.entries( + securityHeaders(c.env.APP_URL, API_CSP), + )) { + c.header(k, v); } }); @@ -35,11 +49,14 @@ app.use('/api/*', async (c, next) => { app.use('/api/*', async (c, next) => { const handler = cors({ origin: (origin) => { - const allowed = [ - c.env.APP_URL, - 'http://localhost:5173', - 'http://localhost:4173', - ]; + const allowed = [c.env.APP_URL]; + // BE-S10: allow the Vite dev-server origins only when the Worker itself is + // served over plain http (wrangler dev on localhost). Production is always + // https, so a page served from a localhost port cannot ride the CORS + // allow-list against the deployed API. + if (new URL(c.req.url).protocol === 'http:') { + allowed.push('http://localhost:5173', 'http://localhost:4173'); + } return allowed.includes(origin) ? origin : null; }, allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], @@ -112,7 +129,18 @@ app.get('/:slug', async (c, next) => { }); // Fallback — forward all unmatched requests to Workers Assets (SPA + static files) -app.all('*', (c) => c.env.ASSETS.fetch(c.req.url) as unknown as Response); +app.all('*', async (c) => { + const res = await c.env.ASSETS.fetch(c.req.url); + // BE-S11: the /api/* middleware above does not cover SPA/static responses, so + // attach security headers (including a Vite-compatible CSP) here. + const headers = new Headers(res.headers); + for (const [k, v] of Object.entries( + securityHeaders(c.env.APP_URL, SPA_CSP), + )) { + headers.set(k, v); + } + return new Response(res.body, { status: res.status, headers }); +}); export default { fetch: app.fetch, diff --git a/apps/worker/src/lib/email.ts b/apps/worker/src/lib/email.ts index 7952e29..edc7add 100644 --- a/apps/worker/src/lib/email.ts +++ b/apps/worker/src/lib/email.ts @@ -87,8 +87,14 @@ export async function sendEmail( }); if (!res.ok) { - const text = await res.text(); - throw new Error(`Resend error ${res.status}: ${text}`); + // BE-R2: don't fold the upstream response body into the error — it can echo + // SMTP/credential configuration. Log a redacted summary (status only) and + // throw a generic error so nothing sensitive reaches the client or the logs. + console.error('sendEmail failed', { + provider: 'resend', + status: res.status, + }); + throw new Error(`Resend request failed with status ${res.status}`); } } diff --git a/apps/worker/src/lib/migrations.ts b/apps/worker/src/lib/migrations.ts index 6741db6..a16c9e3 100644 --- a/apps/worker/src/lib/migrations.ts +++ b/apps/worker/src/lib/migrations.ts @@ -28,11 +28,20 @@ export function createMigrationsTableSql(prefix: string): string { // Returns migrations parameterised by the table prefix so setup works whether // TABLE_PREFIX is empty or set to a custom value. -export function getMigrations(p: string): { name: string; sql: string }[] { +export interface Migration { + name: string; + // wrangler migration file this corresponds to (migrations/). + // The numeric prefix maps to the migration name via the schema_vN convention. + fileName: string; + sql: string; +} + +export function getMigrations(p: string): Migration[] { const t = (name: string) => tbl(p, name); return [ { name: 'schema_v1', + fileName: '0001_init.sql', sql: ` CREATE TABLE IF NOT EXISTS ${t('users')} ( id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), @@ -145,6 +154,7 @@ CREATE INDEX IF NOT EXISTS idx_totp_used_at ON ${t('totp_used')}(used_at); // BE-S3/S4: per-user token_version — bumping it revokes all of a user's // sessions (password change/reset, admin disable/demote). name: 'schema_v2', + fileName: '0002_token_version.sql', sql: ` ALTER TABLE ${t('users')} ADD COLUMN token_version INTEGER NOT NULL DEFAULT 0; `, diff --git a/apps/worker/src/lib/security.ts b/apps/worker/src/lib/security.ts new file mode 100644 index 0000000..6ed5005 --- /dev/null +++ b/apps/worker/src/lib/security.ts @@ -0,0 +1,32 @@ +// Security headers applied to API and SPA (Workers Assets) responses. + +// CSP for JSON API responses — no scripts/styles at all. +export const API_CSP = + "default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'self'"; + +// CSP for the Vite-built SPA. Kept deliberately permissive where the build +// requires it: +// - script-src 'unsafe-eval': recharts (via decimal.js) and qrcode call +// `Function("return this")()` at module init, so omitting it breaks those +// pages (verified by grepping dist/assets/*.js). +// - style-src 'unsafe-inline': React/recharts set inline style attributes. +// - img-src data:: the TOTP QR code is rendered from a data: URL. +export const SPA_CSP = + "default-src 'self'; script-src 'self' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'"; + +export function securityHeaders( + appUrl: string, + csp: string, +): Record { + const headers: Record = { + 'X-Content-Type-Options': 'nosniff', + 'X-Frame-Options': 'DENY', + 'Referrer-Policy': 'strict-origin-when-cross-origin', + 'Content-Security-Policy': csp, + }; + if (appUrl.startsWith('https')) { + headers['Strict-Transport-Security'] = + 'max-age=63072000; includeSubDomains'; + } + return headers; +} diff --git a/apps/worker/src/lib/smtp.ts b/apps/worker/src/lib/smtp.ts index 66bfa76..a701d70 100644 --- a/apps/worker/src/lib/smtp.ts +++ b/apps/worker/src/lib/smtp.ts @@ -1,5 +1,6 @@ -import { connect } from 'cloudflare:sockets'; - +// `cloudflare:sockets` is imported lazily inside sendViaSMTP so that importing +// this module under Node (unit tests) does not fail to resolve a +// Cloudflare-only module specifier. The runtime (workerd) provides it. export interface SmtpConfig { host: string; port: number; @@ -48,6 +49,7 @@ export async function sendViaSMTP( ): Promise { const isImplicitTls = config.port === 465; + const { connect } = await import('cloudflare:sockets'); const socket = connect({ hostname: config.host, port: config.port }, { secureTransport: isImplicitTls ? 'on' : 'off', allowHalfOpen: true, diff --git a/apps/worker/src/routes/auth.ts b/apps/worker/src/routes/auth.ts index fda0de4..f307f2b 100644 --- a/apps/worker/src/routes/auth.ts +++ b/apps/worker/src/routes/auth.ts @@ -288,6 +288,14 @@ auth.post('/register', async (c) => { ); } + // BE-C4: delete any previous unused code for this identifier before storing + // the new one, so a user always has at most one pending code of each type. + await c.env.DB.prepare( + `DELETE FROM ${tbl(c.env, 'verifications')} WHERE identifier = ?1 AND type = 'email_verify' AND used = 0`, + ) + .bind(newUser.id) + .run(); + await c.env.DB.prepare( `INSERT INTO ${tbl(c.env, 'verifications')} (identifier, type, code_hash, expires_at) VALUES (?1, ?2, ?3, ?4)`, ) @@ -695,8 +703,10 @@ auth.post('/change-password', requireAuth, async (c) => { // 2FA — TOTP // ═════════════════════════════════════════════════════════════════════════════ -// GET /api/auth/2fa/totp/setup -auth.get('/2fa/totp/setup', requireAuth, async (c) => { +// POST /api/auth/2fa/totp/setup +// BE-S12: POST (not GET) — the endpoint has a write side effect (it regenerates +// and overwrites totp_secret), so GET semantics were wrong. +auth.post('/2fa/totp/setup', requireAuth, async (c) => { const userId = c.get('userId'); const userEmail = c.get('userEmail'); @@ -1640,33 +1650,45 @@ auth.post('/forgot-password', async (c) => { if (!user) return c.json({ success: true }); // silent — no enumeration - const code = generateOtp(6); - const codeHash = await sha256(code); - const expiresAt = Math.floor(Date.now() / 1000) + 600; - const appName = await getAppName(c.env); - - try { - await sendEmail(c.env, { - to: email, - subject: `${appName} — Password Reset`, - html: resetPasswordEmailHtml(appName, code), - }); - } catch { - return c.json({ error: 'Failed to send email. Please try again.' }, 500); - } + // BE-S9: send the reset email out-of-band so the response time no longer + // reveals whether the address is registered (previously the send happened + // inline, so an existing address took hundreds of ms longer to respond). + c.executionCtx.waitUntil( + (async () => { + const code = generateOtp(6); + const codeHash = await sha256(code); + const expiresAt = Math.floor(Date.now() / 1000) + 600; + const appName = await getAppName(c.env); + + try { + await sendEmail(c.env, { + to: email, + subject: `${appName} — Password Reset`, + html: resetPasswordEmailHtml(appName, code), + }); + } catch (err) { + // BE-R2: log only a redacted form — never the upstream response body. + console.error( + 'forgot-password email failed', + err instanceof Error ? err.name : typeof err, + ); + return; + } - // Invalidate any previous unused reset codes for this email - await c.env.DB.prepare( - `DELETE FROM ${tbl(c.env, 'verifications')} WHERE identifier = ?1 AND type = 'password_reset' AND used = 0`, - ) - .bind(email) - .run(); + // Invalidate any previous unused reset codes for this email + await c.env.DB.prepare( + `DELETE FROM ${tbl(c.env, 'verifications')} WHERE identifier = ?1 AND type = 'password_reset' AND used = 0`, + ) + .bind(email) + .run(); - await c.env.DB.prepare( - `INSERT INTO ${tbl(c.env, 'verifications')} (identifier, type, code_hash, expires_at) VALUES (?1, ?2, ?3, ?4)`, - ) - .bind(email, 'password_reset', codeHash, expiresAt) - .run(); + await c.env.DB.prepare( + `INSERT INTO ${tbl(c.env, 'verifications')} (identifier, type, code_hash, expires_at) VALUES (?1, ?2, ?3, ?4)`, + ) + .bind(email, 'password_reset', codeHash, expiresAt) + .run(); + })(), + ); return c.json({ success: true }); }); diff --git a/apps/worker/src/types.ts b/apps/worker/src/types.ts index 019bf26..d8a1f6a 100644 --- a/apps/worker/src/types.ts +++ b/apps/worker/src/types.ts @@ -29,6 +29,7 @@ export interface Variables { userEmail: string; userJti: string; userTokenExp: number; // S1: used to compute exact denylist TTL from token expiry + requestId: string; // BE-Q3: set per request for structured error logging } // ─── DB row types ──────────────────────────────────────────────────────────── diff --git a/apps/worker/test/auth.test.ts b/apps/worker/test/auth.test.ts new file mode 100644 index 0000000..45a6558 --- /dev/null +++ b/apps/worker/test/auth.test.ts @@ -0,0 +1,283 @@ +// BE-Q2: auth critical-path tests — login, refresh (rotation + token_version +// revocation) and change-password revocation. Uses the real routes, real JWT +// signing/verification, and an in-memory SQLite D1 with the real migrations. +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import auth from '../src/routes/auth.ts'; +import { + accessTokenFor, + makeEnv, + refreshTokenFor, + request, + seedUser, +} from './helpers/app.ts'; + +const json = (body: unknown, headers: Record = {}) => ({ + method: 'POST', + headers: { 'Content-Type': 'application/json', ...headers }, + body: JSON.stringify(body), +}); + +test('login: 正确凭据签发 access token 并设置 HttpOnly refresh cookie', async () => { + const ctx = makeEnv(); + await seedUser(ctx.db, { + id: 'u1', + email: 'alice@example.com', + username: 'alice', + role: 'user', + isActive: 1, + tokenVersion: 0, + password: 'correct-password', + }); + + const res = await request( + auth, + '/login', + json({ email: 'alice@example.com', password: 'correct-password' }), + ctx, + ); + assert.equal(res.status, 200); + const body = await res.json(); + assert.ok(body.accessToken, 'expected an access token'); + assert.equal(body.user.email, 'alice@example.com'); + const cookie = res.headers.get('Set-Cookie') ?? ''; + assert.match(cookie, /refreshToken=[^;]+/); + assert.match(cookie, /HttpOnly/); + assert.match(cookie, /SameSite=Strict/); + assert.match(cookie, /Secure/); +}); + +test('login: 密码错误返回 401', async () => { + const ctx = makeEnv(); + await seedUser(ctx.db, { + id: 'u1', + email: 'alice@example.com', + username: 'alice', + role: 'user', + isActive: 1, + tokenVersion: 0, + password: 'correct-password', + }); + + const res = await request( + auth, + '/login', + json({ email: 'alice@example.com', password: 'wrong-password' }), + ctx, + ); + assert.equal(res.status, 401); +}); + +test('login: 连续失败触发限流返回 429', async () => { + const ctx = makeEnv(); + await seedUser(ctx.db, { + id: 'u1', + email: 'alice@example.com', + username: 'alice', + role: 'user', + isActive: 1, + tokenVersion: 0, + password: 'correct-password', + }); + + for (let i = 0; i < 10; i++) { + const res = await request( + auth, + '/login', + json({ email: 'alice@example.com', password: 'wrong-password' }), + ctx, + ); + assert.equal(res.status, 401, `attempt ${i + 1} should be a 401`); + } + const blocked = await request( + auth, + '/login', + json({ email: 'alice@example.com', password: 'correct-password' }), + ctx, + ); + assert.equal(blocked.status, 429); +}); + +test('refresh: 有效 refresh token 轮换出新 access token', async () => { + const ctx = makeEnv(); + await seedUser(ctx.db, { + id: 'u1', + email: 'alice@example.com', + username: 'alice', + role: 'user', + isActive: 1, + tokenVersion: 0, + password: 'correct-password', + }); + const rt = await refreshTokenFor('u1', 0); + + const res = await request( + auth, + '/refresh', + { method: 'POST', headers: { Cookie: `refreshToken=${rt}` } }, + ctx, + ); + assert.equal(res.status, 200); + const body = await res.json(); + assert.ok(body.accessToken, 'expected a fresh access token'); +}); + +test('refresh: token_version 不匹配则吊销(401)', async () => { + const ctx = makeEnv(); + await seedUser(ctx.db, { + id: 'u1', + email: 'alice@example.com', + username: 'alice', + role: 'user', + isActive: 1, + tokenVersion: 1, + password: 'correct-password', + }); + // Signed for the previous token_version (0), but the account is now at 1. + const rt = await refreshTokenFor('u1', 0); + + const res = await request( + auth, + '/refresh', + { method: 'POST', headers: { Cookie: `refreshToken=${rt}` } }, + ctx, + ); + assert.equal(res.status, 401); +}); + +test('change-password 自增 token_version,旧 refresh token 随之失效', async () => { + const ctx = makeEnv(); + await seedUser(ctx.db, { + id: 'u1', + email: 'alice@example.com', + username: 'alice', + role: 'user', + isActive: 1, + tokenVersion: 0, + password: 'old-password', + }); + const access = await accessTokenFor({ + id: 'u1', + email: 'alice@example.com', + role: 'user', + tokenVersion: 0, + }); + const rt = await refreshTokenFor('u1', 0); + + const change = await request( + auth, + '/change-password', + json( + { currentPassword: 'old-password', newPassword: 'new-password-1' }, + { Authorization: `Bearer ${access}` }, + ), + ctx, + ); + assert.equal(change.status, 200); + + const row = ctx.db + .prepare('SELECT token_version FROM users WHERE id = ?1') + .bind('u1') + .first<{ token_version: number }>(); + assert.equal(row?.token_version, 1); + + const refresh = await request( + auth, + '/refresh', + { method: 'POST', headers: { Cookie: `refreshToken=${rt}` } }, + ctx, + ); + assert.equal(refresh.status, 401); +}); + +test('forgot-password: 已注册与未注册邮箱都立即返回 success(BE-S9)', async (t) => { + const ctx = makeEnv(); + await seedUser(ctx.db, { + id: 'u1', + email: 'alice@example.com', + username: 'alice', + role: 'user', + isActive: 1, + tokenVersion: 0, + password: 'correct-password', + }); + + // Configure Resend + a fake upstream so the async send actually stores a code. + ctx.db + .prepare("UPDATE settings SET value = ?1 WHERE key = 'resend_api_key'") + .bind('test-key') + .run(); + ctx.db + .prepare("UPDATE settings SET value = ?1 WHERE key = 'email_from_domain'") + .bind('example.com') + .run(); + const originalFetch = globalThis.fetch; + globalThis.fetch = async () => new Response('{"id":"ok"}', { status: 200 }); + t.after(() => { + globalThis.fetch = originalFetch; + }); + + const found = await request( + auth, + '/forgot-password', + json({ email: 'alice@example.com' }), + ctx, + ); + assert.equal(found.status, 200); + await Promise.all(ctx.waitUntil); + const stored = ctx.db + .prepare( + "SELECT COUNT(*) AS n FROM verifications WHERE identifier = ?1 AND type = 'password_reset' AND used = 0", + ) + .bind('alice@example.com') + .first<{ n: number }>(); + assert.equal(stored?.n, 1); + + const missing = await request( + auth, + '/forgot-password', + json({ email: 'nobody@example.com' }), + ctx, + ); + assert.equal(missing.status, 200); +}); + +test('2fa/totp/setup: 只接受 POST(BE-S12)', async () => { + const ctx = makeEnv(); + await seedUser(ctx.db, { + id: 'u1', + email: 'alice@example.com', + username: 'alice', + role: 'user', + isActive: 1, + tokenVersion: 0, + password: 'correct-password', + }); + const access = await accessTokenFor({ + id: 'u1', + email: 'alice@example.com', + role: 'user', + tokenVersion: 0, + }); + + const get = await request( + auth, + '/2fa/totp/setup', + { method: 'GET', headers: { Authorization: `Bearer ${access}` } }, + ctx, + ); + // Hono returns 404 (not 200) for a path that has no GET handler — the old + // GET-based endpoint is gone. + assert.equal(get.status, 404); + + const post = await request( + auth, + '/2fa/totp/setup', + { method: 'POST', headers: { Authorization: `Bearer ${access}` } }, + ctx, + ); + assert.equal(post.status, 200); + const body = await post.json(); + assert.ok(body.secret); + assert.match(body.uri, /^otpauth:\/\//); +}); diff --git a/apps/worker/test/email.test.ts b/apps/worker/test/email.test.ts new file mode 100644 index 0000000..1b33c20 --- /dev/null +++ b/apps/worker/test/email.test.ts @@ -0,0 +1,41 @@ +// BE-R2: send-email failures must be redacted before they are logged or +// thrown — the upstream Resend response body (which can echo credential/config +// details) must never appear in the error message. +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { sendEmail } from '../src/lib/email.ts'; +import { makeEnv } from './helpers/app.ts'; + +const SECRET = 'SUPER-SECRET-UPSTREAM-BODY'; + +test('sendEmail: Resend 失败不把响应正文带进错误信息 (BE-R2)', async (t) => { + const ctx = makeEnv(); + ctx.db + .prepare("UPDATE settings SET value = ?1 WHERE key = 'resend_api_key'") + .bind('test-api-key') + .run(); + ctx.db + .prepare("UPDATE settings SET value = ?1 WHERE key = 'email_from_domain'") + .bind('example.com') + .run(); + + const originalFetch = globalThis.fetch; + globalThis.fetch = async () => + new Response(JSON.stringify({ error: SECRET }), { status: 500 }); + t.after(() => { + globalThis.fetch = originalFetch; + }); + + await assert.rejects( + () => + sendEmail(ctx.env, { + to: 'user@example.com', + subject: 'hi', + html: '

hi

', + }), + (err: Error) => { + assert.ok(!err.message.includes(SECRET), '错误信息泄露了上游响应正文'); + return true; + }, + ); +}); diff --git a/apps/worker/test/helpers/app.ts b/apps/worker/test/helpers/app.ts new file mode 100644 index 0000000..28edc26 --- /dev/null +++ b/apps/worker/test/helpers/app.ts @@ -0,0 +1,126 @@ +// Shared harness for the worker route tests: builds an Env with an in-memory +// D1 + KV, seeds users, and signs real JWTs so the auth middleware is exercised +// end-to-end (rather than stubbed out). +import type { Hono } from 'hono'; +import { hashPassword } from '../../src/lib/crypto.ts'; +import { signAccessToken, signRefreshToken } from '../../src/lib/jwt.ts'; +import type { Env } from '../../src/types.ts'; +import { D1Mock, MemoryKV } from './env.ts'; + +export const TEST_SECRET = + 'test-secret-0123456789abcdef0123456789abcdef0123456789'; +export const APP_URL = 'https://example.com'; + +export interface SeedUser { + id: string; + email: string; + username: string; + role: 'admin' | 'user'; + isActive: number; + tokenVersion: number; + password: string; +} + +export interface TestEnv { + env: Env; + db: D1Mock; + kv: MemoryKV; + // Background tasks scheduled via ctx.waitUntil (e.g. forgot-password email, + // click logging) — captured so a test can await them. + waitUntil: Promise[]; +} + +export function makeEnv(overrides: Partial = {}): TestEnv { + const db = new D1Mock(); + const kv = new MemoryKV(); + const env = { + DB: db, + LINKS_KV: kv, + ASSETS: { fetch: async () => new Response('assets', { status: 200 }) }, + APP_NAME: 'ShortLink', + APP_URL, + RP_ID: 'example.com', + APP_ORIGIN: APP_URL, + TABLE_PREFIX: '', + JWT_SECRET: TEST_SECRET, + TOTP_ENCRYPTION_KEY: '0'.repeat(64), + SETUP_SECRET: 'test-setup-secret', + ...overrides, + } as unknown as Env; + return { env, db, kv, waitUntil: [] }; +} + +export async function seedUser( + db: D1Mock, + user: Omit & { password: string }, +): Promise { + const passwordHash = await hashPassword(user.password); + db.prepare( + `INSERT INTO users (id, email, username, password_hash, role, is_active, token_version) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)`, + ) + .bind( + user.id, + user.email, + user.username, + passwordHash, + user.role, + user.isActive, + user.tokenVersion, + ) + .run(); + return user.id; +} + +export async function accessTokenFor( + user: { + id: string; + email: string; + role: 'admin' | 'user'; + tokenVersion: number; + }, + secret = TEST_SECRET, +): Promise { + const { token } = await signAccessToken( + { + sub: user.id, + role: user.role, + email: user.email, + tv: user.tokenVersion, + }, + secret, + ); + return token; +} + +export async function refreshTokenFor( + userId: string, + tv: number, + secret = TEST_SECRET, +): Promise { + const { token } = await signRefreshToken(userId, tv, secret); + return token; +} + +export interface AppContext { + env: Env; + db: D1Mock; + kv: MemoryKV; + waitUntil: Promise[]; +} + +export function request( + app: Hono, + path: string, + init: RequestInit, + ctx: AppContext, +): Promise { + const executionCtx = { + waitUntil: (promise: Promise) => { + ctx.waitUntil.push(promise); + }, + passThroughOnException: () => {}, + props: {}, + }; + return app.request(path, init, ctx.env, executionCtx); +} diff --git a/apps/worker/test/helpers/env.ts b/apps/worker/test/helpers/env.ts new file mode 100644 index 0000000..f0bba05 --- /dev/null +++ b/apps/worker/test/helpers/env.ts @@ -0,0 +1,106 @@ +// In-memory D1 (backed by Node's built-in SQLite) and KV fakes for route tests. +// The schema comes from the real migrations (src/lib/migrations.ts), so the +// tests exercise the routes against the same DDL that production applies. +import { DatabaseSync } from 'node:sqlite'; +import { getMigrations } from '../../src/lib/migrations.ts'; + +// ─── KV ────────────────────────────────────────────────────────────────────── + +export class MemoryKV { + private store = new Map< + string, + { value: string; expiresAt: number | null } + >(); + + async get(key: string, type?: 'json'): Promise { + const entry = this.store.get(key); + if (!entry) return null; + if (entry.expiresAt !== null && entry.expiresAt < Date.now() / 1000) { + this.store.delete(key); + return null; + } + if (type === 'json') { + try { + return JSON.parse(entry.value); + } catch { + return null; + } + } + return entry.value; + } + + async put( + key: string, + value: string, + opts?: { expirationTtl?: number }, + ): Promise { + this.store.set(key, { + value, + expiresAt: opts?.expirationTtl + ? Math.floor(Date.now() / 1000) + opts.expirationTtl + : null, + }); + } + + async delete(key: string): Promise { + this.store.delete(key); + } +} + +// ─── D1 (SQLite-backed) ────────────────────────────────────────────────────── + +interface D1Result { + results: Record[]; +} + +class D1Statement { + private params: unknown[] = []; + + constructor( + private readonly db: DatabaseSync, + private readonly sql: string, + ) {} + + bind(...params: unknown[]): this { + this.params = params; + return this; + } + + first(): T | null { + const row = this.db.prepare(this.sql).get(...this.params); + return (row ?? null) as T | null; + } + + all(): { results: T[] } { + const rows = this.db.prepare(this.sql).all(...this.params) as T[]; + return { results: rows }; + } + + run(): { meta: { changes: number } } { + const result = this.db.prepare(this.sql).run(...this.params); + return { meta: { changes: Number(result.changes) } }; + } +} + +export class D1Mock { + private readonly db: DatabaseSync; + + constructor() { + this.db = new DatabaseSync(':memory:'); + for (const migration of getMigrations('')) { + this.db.exec(migration.sql); + } + } + + prepare(sql: string): D1Statement { + return new D1Statement(this.db, sql); + } + + batch(statements: D1Statement[]): D1Result[] { + return statements.map((s) => s.all()); + } + + exec(sql: string): void { + this.db.exec(sql); + } +} diff --git a/apps/worker/test/links.test.ts b/apps/worker/test/links.test.ts new file mode 100644 index 0000000..6df75ab --- /dev/null +++ b/apps/worker/test/links.test.ts @@ -0,0 +1,194 @@ +// BE-Q2: links critical-path tests — create (validation), update, and +// ownership/permission checks. Real auth middleware (JWT + D1) is exercised. +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import links from '../src/routes/links.ts'; +import { accessTokenFor, makeEnv, request, seedUser } from './helpers/app.ts'; + +const json = (body: unknown, headers: Record = {}) => ({ + method: 'POST', + headers: { 'Content-Type': 'application/json', ...headers }, + body: JSON.stringify(body), +}); + +async function setupUsers(ctx: Awaited>) { + await seedUser(ctx.db, { + id: 'u1', + email: 'alice@example.com', + username: 'alice', + role: 'user', + isActive: 1, + tokenVersion: 0, + password: 'password-1', + }); + await seedUser(ctx.db, { + id: 'u2', + email: 'bob@example.com', + username: 'bob', + role: 'user', + isActive: 1, + tokenVersion: 0, + password: 'password-2', + }); + const alice = await accessTokenFor({ + id: 'u1', + email: 'alice@example.com', + role: 'user', + tokenVersion: 0, + }); + const bob = await accessTokenFor({ + id: 'u2', + email: 'bob@example.com', + role: 'user', + tokenVersion: 0, + }); + return { alice, bob }; +} + +test('POST /: 创建合法链接返回 201 并分配 slug', async () => { + const ctx = makeEnv(); + const { alice } = await setupUsers(ctx); + + const res = await request( + links, + '/', + json( + { destinationUrl: 'https://example.org/page' }, + { Authorization: `Bearer ${alice}` }, + ), + ctx, + ); + assert.equal(res.status, 201); + const body = await res.json(); + assert.ok(body.link.id, 'expected a link id'); + assert.ok(body.link.slug, 'expected a generated slug'); + assert.equal(body.link.destination_url, 'https://example.org/page'); + assert.equal(body.link.user_seq, 1); +}); + +test('POST /: 拒绝非 http/https 协议(javascript:)', async () => { + const ctx = makeEnv(); + const { alice } = await setupUsers(ctx); + + const res = await request( + links, + '/', + json( + { destinationUrl: 'javascript:alert(1)' }, + { Authorization: `Bearer ${alice}` }, + ), + ctx, + ); + assert.equal(res.status, 400); +}); + +test('POST /: 拒绝保留 slug', async () => { + const ctx = makeEnv(); + const { alice } = await setupUsers(ctx); + + const res = await request( + links, + '/', + json( + { destinationUrl: 'https://example.org', customSlug: 'dashboard' }, + { Authorization: `Bearer ${alice}` }, + ), + ctx, + ); + assert.equal(res.status, 400); +}); + +test('权限: 其他用户读取该链接返回 404', async () => { + const ctx = makeEnv(); + const { alice, bob } = await setupUsers(ctx); + + const created = await request( + links, + '/', + json( + { destinationUrl: 'https://example.org/page' }, + { Authorization: `Bearer ${alice}` }, + ), + ctx, + ); + const id = (await created.json()).link.id as string; + + const res = await request( + links, + `/${id}`, + { method: 'GET', headers: { Authorization: `Bearer ${bob}` } }, + ctx, + ); + assert.equal(res.status, 404); +}); + +test('PUT /:id: 所有者可更新,其他用户更新返回 404', async () => { + const ctx = makeEnv(); + const { alice, bob } = await setupUsers(ctx); + + const created = await request( + links, + '/', + json( + { destinationUrl: 'https://example.org/page' }, + { Authorization: `Bearer ${alice}` }, + ), + ctx, + ); + const id = (await created.json()).link.id as string; + + const byOwner = await request( + links, + `/${id}`, + { + method: 'PUT', + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${alice}`, + }, + body: JSON.stringify({ title: 'new title' }), + }, + ctx, + ); + assert.equal(byOwner.status, 200); + assert.equal((await byOwner.json()).link.title, 'new title'); + + const byOther = await request( + links, + `/${id}`, + { + method: 'PUT', + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${bob}`, + }, + body: JSON.stringify({ title: 'hijacked' }), + }, + ctx, + ); + assert.equal(byOther.status, 404); +}); + +test('DELETE /:id: 其他用户删除返回 404', async () => { + const ctx = makeEnv(); + const { alice, bob } = await setupUsers(ctx); + + const created = await request( + links, + '/', + json( + { destinationUrl: 'https://example.org/page' }, + { Authorization: `Bearer ${alice}` }, + ), + ctx, + ); + const id = (await created.json()).link.id as string; + + const res = await request( + links, + `/${id}`, + { method: 'DELETE', headers: { Authorization: `Bearer ${bob}` } }, + ctx, + ); + assert.equal(res.status, 404); +}); diff --git a/apps/worker/test/migrations.test.ts b/apps/worker/test/migrations.test.ts new file mode 100644 index 0000000..9c67bac --- /dev/null +++ b/apps/worker/test/migrations.test.ts @@ -0,0 +1,46 @@ +// BE-Q1: schema single source of truth. The wrangler migration files +// (migrations/*.sql) must be generated from src/lib/migrations.ts — this test +// fails if they drift apart, so CI catches a schema edit that only touches one +// of the two copies. +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { test } from 'node:test'; +import { fileURLToPath } from 'node:url'; +import { renderMigrationFiles } from '../scripts/generate-migrations.ts'; +import { getMigrations } from '../src/lib/migrations.ts'; + +const migrationsDir = join( + dirname(fileURLToPath(import.meta.url)), + '..', + 'migrations', +); + +test('每个 wrangler 迁移文件都来自 getMigrations(""),内容一致 (BE-Q1)', () => { + const expected = renderMigrationFiles(); + const names = Object.keys(expected); + assert.ok(names.length > 0, 'expected at least one migration file'); + + for (const name of names) { + const onDisk = readFileSync(join(migrationsDir, name), 'utf8'); + assert.equal( + onDisk, + expected[name], + `${name} 与生成内容不一致,请运行 generate:migrations`, + ); + } +}); + +test('迁移名与文件名遵循 schema_vN <-> NNNN_*.sql 约定 (BE-Q1)', () => { + for (const migration of getMigrations('')) { + const match = /^schema_v(\d+)$/.exec(migration.name); + assert.ok(match, `migration name ${migration.name} must be schema_vN`); + const num = match?.[1] ?? ''; + assert.equal( + migration.fileName, + `${num.padStart(4, '0')}_${migration.fileName.split('_').slice(1).join('_')}`, + `${migration.name} 的 fileName 数字前缀必须与版本号一致`, + ); + assert.match(migration.fileName, /^\d{4}_.+\.sql$/); + } +}); diff --git a/apps/worker/test/redirect.test.ts b/apps/worker/test/redirect.test.ts new file mode 100644 index 0000000..713157b --- /dev/null +++ b/apps/worker/test/redirect.test.ts @@ -0,0 +1,84 @@ +// BE-Q2: redirect critical-path tests — active redirect, expired link, and +// deactivated link all fall back to /404; missing slug too. +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import redirect from '../src/routes/redirect.ts'; +import { APP_URL, makeEnv, request, seedUser } from './helpers/app.ts'; + +function insertLink( + ctx: Awaited>, + fields: { + id: string; + slug: string; + isActive: number; + expiresAt: number | null; + }, +): void { + ctx.db + .prepare( + `INSERT INTO links (id, user_id, slug, destination_url, title, expires_at, is_active, user_seq) + VALUES (?1, ?2, ?3, ?4, NULL, ?5, ?6, 1)`, + ) + .bind( + fields.id, + 'u1', + fields.slug, + 'https://example.org/target', + fields.expiresAt, + fields.isActive, + ) + .run(); +} + +async function setup(ctx: Awaited>) { + await seedUser(ctx.db, { + id: 'u1', + email: 'alice@example.com', + username: 'alice', + role: 'user', + isActive: 1, + tokenVersion: 0, + password: 'password-1', + }); +} + +test('redirect: 活动链接 302 跳转到目标地址', async () => { + const ctx = makeEnv(); + await setup(ctx); + insertLink(ctx, { id: 'l1', slug: 'abc', isActive: 1, expiresAt: null }); + + const res = await request(redirect, '/abc', { method: 'GET' }, ctx); + assert.equal(res.status, 302); + assert.equal(res.headers.get('Location'), 'https://example.org/target'); + assert.equal(res.headers.get('Referrer-Policy'), 'no-referrer'); +}); + +test('redirect: 过期链接跳转到 /404', async () => { + const ctx = makeEnv(); + await setup(ctx); + const past = Math.floor(Date.now() / 1000) - 100; + insertLink(ctx, { id: 'l1', slug: 'expired', isActive: 1, expiresAt: past }); + + const res = await request(redirect, '/expired', { method: 'GET' }, ctx); + assert.equal(res.status, 302); + assert.equal(res.headers.get('Location'), `${APP_URL}/404`); +}); + +test('redirect: 停用链接跳转到 /404', async () => { + const ctx = makeEnv(); + await setup(ctx); + insertLink(ctx, { id: 'l1', slug: 'off', isActive: 0, expiresAt: null }); + + const res = await request(redirect, '/off', { method: 'GET' }, ctx); + assert.equal(res.status, 302); + assert.equal(res.headers.get('Location'), `${APP_URL}/404`); +}); + +test('redirect: 不存在的 slug 跳转到 /404', async () => { + const ctx = makeEnv(); + await setup(ctx); + + const res = await request(redirect, '/missing', { method: 'GET' }, ctx); + assert.equal(res.status, 302); + assert.equal(res.headers.get('Location'), `${APP_URL}/404`); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index bf0b0bd..55bd5d3 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -53,7 +53,7 @@ importers: devDependencies: '@tailwindcss/vite': specifier: ^4.0.0 - version: 4.3.3(vite@8.0.16(@types/node@25.6.0)(esbuild@0.28.1)(jiti@2.7.0)) + version: 4.3.3(vite@8.0.16(@types/node@25.6.0)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.23.15)) '@types/qrcode': specifier: ^1.5.6 version: 1.5.6 @@ -65,7 +65,7 @@ importers: version: 19.2.7(@types/react@19.2.18) '@vitejs/plugin-react': specifier: ^6.0.0 - version: 6.1.2(vite@8.0.16(@types/node@25.6.0)(esbuild@0.28.1)(jiti@2.7.0)) + version: 6.1.2(vite@8.0.16(@types/node@25.6.0)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.23.15)) autoprefixer: specifier: ^10.4.20 version: 10.6.1(postcss@8.5.28) @@ -80,7 +80,7 @@ importers: version: 6.0.3 vite: specifier: ^8.0.0 - version: 8.0.16(@types/node@25.6.0)(esbuild@0.28.1)(jiti@2.7.0) + version: 8.0.16(@types/node@25.6.0)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.23.15) apps/worker: dependencies: @@ -100,6 +100,9 @@ importers: '@cloudflare/workers-types': specifier: ^4.20241205.0 version: 4.20260702.1 + tsx: + specifier: ^4.23.15 + version: 4.23.15 typescript: specifier: ^6.0.0 version: 6.0.3 @@ -1463,6 +1466,11 @@ packages: tslib@2.8.1: resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} + tsx@4.23.15: + resolution: {integrity: sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==} + engines: {node: '>=18.0.0'} + hasBin: true + tsyringe@4.10.0: resolution: {integrity: sha512-axr3IdNuVIxnaK5XGEUFTu3YmAQ6lllgrvqfEoR16g/HGnYY/6We4oWENtAnzK6/LpJ2ur9PAb80RBt7/U4ugw==} engines: {node: '>= 6.0.0'} @@ -2151,12 +2159,12 @@ snapshots: '@tailwindcss/oxide-win32-arm64-msvc': 4.3.3 '@tailwindcss/oxide-win32-x64-msvc': 4.3.3 - '@tailwindcss/vite@4.3.3(vite@8.0.16(@types/node@25.6.0)(esbuild@0.28.1)(jiti@2.7.0))': + '@tailwindcss/vite@4.3.3(vite@8.0.16(@types/node@25.6.0)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.23.15))': dependencies: '@tailwindcss/node': 4.3.3 '@tailwindcss/oxide': 4.3.3 tailwindcss: 4.3.3 - vite: 8.0.16(@types/node@25.6.0)(esbuild@0.28.1)(jiti@2.7.0) + vite: 8.0.16(@types/node@25.6.0)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.23.15) '@tanstack/query-core@5.104.3': {} @@ -2230,10 +2238,10 @@ snapshots: '@types/use-sync-external-store@0.0.6': {} - '@vitejs/plugin-react@6.1.2(vite@8.0.16(@types/node@25.6.0)(esbuild@0.28.1)(jiti@2.7.0))': + '@vitejs/plugin-react@6.1.2(vite@8.0.16(@types/node@25.6.0)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.23.15))': dependencies: '@rolldown/pluginutils': 1.0.1 - vite: 8.0.16(@types/node@25.6.0)(esbuild@0.28.1)(jiti@2.7.0) + vite: 8.0.16(@types/node@25.6.0)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.23.15) ansi-regex@5.0.1: {} @@ -2705,6 +2713,12 @@ snapshots: tslib@2.8.1: {} + tsx@4.23.15: + dependencies: + esbuild: 0.28.1 + optionalDependencies: + fsevents: 2.3.3 + tsyringe@4.10.0: dependencies: tslib: 1.14.1 @@ -2755,7 +2769,7 @@ snapshots: d3-time: 3.1.0 d3-timer: 3.0.1 - vite@8.0.16(@types/node@25.6.0)(esbuild@0.28.1)(jiti@2.7.0): + vite@8.0.16(@types/node@25.6.0)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.23.15): dependencies: lightningcss: 1.32.0 picomatch: 4.0.4 @@ -2767,6 +2781,7 @@ snapshots: esbuild: 0.28.1 fsevents: 2.3.3 jiti: 2.7.0 + tsx: 4.23.15 which-module@2.0.1: {} From bc5115c8de11e3a09ddab64cc3d6a78fce143034 Mon Sep 17 00:00:00 2001 From: Todos Date: Sun, 18 Oct 2026 07:53:11 +0800 Subject: [PATCH 2/2] =?UTF-8?q?fix(worker):=20address=20review=20=E2=80=94?= =?UTF-8?q?=20CI=20lookup,=20CORS=20host,=20migration=20semantics,=20forgo?= =?UTF-8?q?t-password=20ordering?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - tag.yml: query the CI workflow via listWorkflowRuns (workflow file + push event) instead of the repo-wide list, so the tag workflow itself is never mistaken for CI - index.ts: only allow localhost CORS origins over http on a loopback host, not merely on http scheme - generate-migrations: strip idempotency markers when rendering .sql so the wrangler migrations keep their fail-if-exists semantics; lib/migrations.ts SQL is unchanged; add an existing-object test - auth.ts: persist the reset code before sending the email and wrap the whole forgot-password background task in a redacted catch Checkpoint: UBfQSDzaq25VhKiTMGKwP --- .github/workflows/tag.yml | 25 +++++++------ apps/worker/migrations/0001_init.sql | 42 +++++++++++----------- apps/worker/scripts/generate-migrations.ts | 16 ++++++++- apps/worker/src/index.ts | 14 +++++--- apps/worker/src/routes/auth.ts | 40 ++++++++++----------- apps/worker/test/migrations.test.ts | 12 +++++++ 6 files changed, 89 insertions(+), 60 deletions(-) diff --git a/.github/workflows/tag.yml b/.github/workflows/tag.yml index edae37e..d33f14d 100644 --- a/.github/workflows/tag.yml +++ b/.github/workflows/tag.yml @@ -52,32 +52,31 @@ jobs: - name: Verify main CI passed uses: actions/github-script@v9 env: - WORKFLOW_NAME: CI + WORKFLOW_FILE: ci.yml with: script: | const { stdout } = await exec.getExecOutput('git', ['rev-parse', 'HEAD']); const sha = stdout.trim(); core.info(`Checking CI status for main@${sha}`); - const { data } = await github.rest.actions.listWorkflowRunsForRepo({ + // Filter by workflow file (not the repo-wide list) so this very tag + // workflow run is not mistaken for CI, and only accept a push run. + const { data } = await github.rest.actions.listWorkflowRuns({ owner: context.repo.owner, repo: context.repo.repo, - workflow_id: process.env.WORKFLOW_NAME, + workflow_id: process.env.WORKFLOW_FILE, head_sha: sha, - per_page: 10, + event: 'push', }); - const runs = data.workflow_runs; - if (runs.length === 0) { - core.setFailed(`No CI run found for main@${sha}; run CI on main before tagging.`); - return; - } - const latest = runs[0]; - if (latest.status !== 'completed' || latest.conclusion !== 'success') { + const ciRun = data.workflow_runs.find( + (run) => run.status === 'completed' && run.conclusion === 'success', + ); + if (!ciRun) { core.setFailed( - `CI for main@${sha} is ${latest.status}/${latest.conclusion}; tag only after a successful CI run.`, + `No successful CI (push) run found for main@${sha}; run CI on main before tagging.`, ); return; } - core.info(`CI for main@${sha} succeeded (run ${latest.id}).`); + core.info(`CI for main@${sha} succeeded (run ${ciRun.id}).`); - name: Configure Git run: | diff --git a/apps/worker/migrations/0001_init.sql b/apps/worker/migrations/0001_init.sql index 1938a45..0acc69c 100644 --- a/apps/worker/migrations/0001_init.sql +++ b/apps/worker/migrations/0001_init.sql @@ -1,7 +1,7 @@ -- DO NOT EDIT. Generated from src/lib/migrations.ts (getMigrations("")). -- Regenerate with: pnpm --filter @shortlink/worker generate:migrations -CREATE TABLE IF NOT EXISTS users ( +CREATE TABLE users ( id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), email TEXT UNIQUE NOT NULL, username TEXT UNIQUE NOT NULL, @@ -16,7 +16,7 @@ CREATE TABLE IF NOT EXISTS users ( created_at INTEGER NOT NULL DEFAULT (unixepoch()), updated_at INTEGER NOT NULL DEFAULT (unixepoch()) ); -CREATE TABLE IF NOT EXISTS passkeys ( +CREATE TABLE passkeys ( id TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, public_key TEXT NOT NULL, @@ -27,8 +27,8 @@ CREATE TABLE IF NOT EXISTS passkeys ( created_at INTEGER NOT NULL DEFAULT (unixepoch()), last_used_at INTEGER ); -CREATE INDEX IF NOT EXISTS idx_passkeys_user_id ON passkeys(user_id); -CREATE TABLE IF NOT EXISTS links ( +CREATE INDEX idx_passkeys_user_id ON passkeys(user_id); +CREATE TABLE links ( id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, slug TEXT UNIQUE NOT NULL, @@ -40,10 +40,10 @@ CREATE TABLE IF NOT EXISTS links ( created_at INTEGER NOT NULL DEFAULT (unixepoch()), updated_at INTEGER NOT NULL DEFAULT (unixepoch()) ); -CREATE INDEX IF NOT EXISTS idx_links_slug ON links(slug); -CREATE INDEX IF NOT EXISTS idx_links_user_id ON links(user_id); -CREATE INDEX IF NOT EXISTS idx_links_expires_at ON links(expires_at) WHERE expires_at IS NOT NULL; -CREATE TABLE IF NOT EXISTS click_logs ( +CREATE INDEX idx_links_slug ON links(slug); +CREATE INDEX idx_links_user_id ON links(user_id); +CREATE INDEX idx_links_expires_at ON links(expires_at) WHERE expires_at IS NOT NULL; +CREATE TABLE click_logs ( id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), link_id TEXT NOT NULL REFERENCES links(id) ON DELETE CASCADE, ip_address TEXT, @@ -56,10 +56,10 @@ CREATE TABLE IF NOT EXISTS click_logs ( os TEXT, created_at INTEGER NOT NULL DEFAULT (unixepoch()) ); -CREATE INDEX IF NOT EXISTS idx_click_logs_link_id ON click_logs(link_id); -CREATE INDEX IF NOT EXISTS idx_click_logs_created_at ON click_logs(created_at); -CREATE INDEX IF NOT EXISTS idx_click_logs_link_time ON click_logs(link_id, created_at); -CREATE TABLE IF NOT EXISTS verifications ( +CREATE INDEX idx_click_logs_link_id ON click_logs(link_id); +CREATE INDEX idx_click_logs_created_at ON click_logs(created_at); +CREATE INDEX idx_click_logs_link_time ON click_logs(link_id, created_at); +CREATE TABLE verifications ( id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), identifier TEXT NOT NULL, type TEXT NOT NULL CHECK (type IN ('email_otp', 'password_reset', 'email_verify')), @@ -69,13 +69,13 @@ CREATE TABLE IF NOT EXISTS verifications ( used INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL DEFAULT (unixepoch()) ); -CREATE INDEX IF NOT EXISTS idx_verifications_identifier ON verifications(identifier, type); -CREATE TABLE IF NOT EXISTS settings ( +CREATE INDEX idx_verifications_identifier ON verifications(identifier, type); +CREATE TABLE settings ( key TEXT PRIMARY KEY, value TEXT NOT NULL, updated_at INTEGER NOT NULL DEFAULT (unixepoch()) ); -INSERT OR IGNORE INTO settings (key, value) VALUES +INSERT INTO settings (key, value) VALUES ('registration_enabled', 'true'), ('require_email_verification', 'false'), ('app_name', 'ShortLink'), @@ -88,7 +88,7 @@ INSERT OR IGNORE INTO settings (key, value) VALUES ('resend_api_key', ''), ('email_from_domain', ''), ('email_from_name', ''); -CREATE TABLE IF NOT EXISTS audit_logs ( +CREATE TABLE audit_logs ( id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), admin_id TEXT REFERENCES users(id) ON DELETE SET NULL, action TEXT NOT NULL, @@ -96,13 +96,13 @@ CREATE TABLE IF NOT EXISTS audit_logs ( details TEXT, created_at INTEGER NOT NULL DEFAULT (unixepoch()) ); -CREATE INDEX IF NOT EXISTS idx_audit_logs_admin_id ON audit_logs(admin_id); -CREATE INDEX IF NOT EXISTS idx_audit_logs_created_at ON audit_logs(created_at); -CREATE INDEX IF NOT EXISTS idx_audit_logs_target_id ON audit_logs(target_id); -CREATE TABLE IF NOT EXISTS totp_used ( +CREATE INDEX idx_audit_logs_admin_id ON audit_logs(admin_id); +CREATE INDEX idx_audit_logs_created_at ON audit_logs(created_at); +CREATE INDEX idx_audit_logs_target_id ON audit_logs(target_id); +CREATE TABLE totp_used ( user_id TEXT NOT NULL, code TEXT NOT NULL, used_at INTEGER NOT NULL DEFAULT (unixepoch()), PRIMARY KEY (user_id, code) ); -CREATE INDEX IF NOT EXISTS idx_totp_used_at ON totp_used(used_at); +CREATE INDEX idx_totp_used_at ON totp_used(used_at); diff --git a/apps/worker/scripts/generate-migrations.ts b/apps/worker/scripts/generate-migrations.ts index 1fbee64..2bfdd77 100644 --- a/apps/worker/scripts/generate-migrations.ts +++ b/apps/worker/scripts/generate-migrations.ts @@ -18,11 +18,25 @@ const HEADER = '-- DO NOT EDIT. Generated from src/lib/migrations.ts (getMigrations("")).\n' + '-- Regenerate with: pnpm --filter @shortlink/worker generate:migrations\n'; +// The setup route and the prefixed deploy path run getMigrations() directly, +// which uses idempotent forms (CREATE TABLE IF NOT EXISTS / INSERT OR IGNORE) so +// they can re-run safely. The wrangler migration files, by contrast, must keep +// their original fail-if-exists semantics: wrangler tracks applied migrations, +// so a repeated CREATE TABLE should error rather than silently skip. Strip the +// idempotency markers when rendering the .sql files. +function toWranglerSql(sql: string): string { + return sql + .replace(/CREATE TABLE IF NOT EXISTS /gi, 'CREATE TABLE ') + .replace(/CREATE INDEX IF NOT EXISTS /gi, 'CREATE INDEX ') + .replace(/INSERT OR IGNORE INTO /gi, 'INSERT INTO '); +} + // Map of wrangler migration file name -> file content. export function renderMigrationFiles(): Record { const files: Record = {}; for (const migration of getMigrations('')) { - files[migration.fileName] = `${HEADER}\n${migration.sql.trim()}\n`; + files[migration.fileName] = + `${HEADER}\n${toWranglerSql(migration.sql).trim()}\n`; } return files; } diff --git a/apps/worker/src/index.ts b/apps/worker/src/index.ts index f481e24..8c92e98 100644 --- a/apps/worker/src/index.ts +++ b/apps/worker/src/index.ts @@ -50,11 +50,15 @@ app.use('/api/*', async (c, next) => { const handler = cors({ origin: (origin) => { const allowed = [c.env.APP_URL]; - // BE-S10: allow the Vite dev-server origins only when the Worker itself is - // served over plain http (wrangler dev on localhost). Production is always - // https, so a page served from a localhost port cannot ride the CORS - // allow-list against the deployed API. - if (new URL(c.req.url).protocol === 'http:') { + // BE-S10: allow the Vite dev-server origins only when the Worker is reached + // over plain http on a loopback host (i.e. wrangler dev). A deployed Worker + // is served from a real hostname, so neither condition holds in production. + const url = new URL(c.req.url); + const isLoopback = + url.hostname === 'localhost' || + url.hostname === '127.0.0.1' || + url.hostname === '::1'; + if (url.protocol === 'http:' && isLoopback) { allowed.push('http://localhost:5173', 'http://localhost:4173'); } return allowed.includes(origin) ? origin : null; diff --git a/apps/worker/src/routes/auth.ts b/apps/worker/src/routes/auth.ts index f307f2b..4829cac 100644 --- a/apps/worker/src/routes/auth.ts +++ b/apps/worker/src/routes/auth.ts @@ -1655,12 +1655,26 @@ auth.post('/forgot-password', async (c) => { // inline, so an existing address took hundreds of ms longer to respond). c.executionCtx.waitUntil( (async () => { - const code = generateOtp(6); - const codeHash = await sha256(code); - const expiresAt = Math.floor(Date.now() / 1000) + 600; - const appName = await getAppName(c.env); - try { + const code = generateOtp(6); + const codeHash = await sha256(code); + const expiresAt = Math.floor(Date.now() / 1000) + 600; + + // Persist the code BEFORE sending, so a user never receives a code that + // failed to store. Invalidate any previous unused reset codes first. + await c.env.DB.prepare( + `DELETE FROM ${tbl(c.env, 'verifications')} WHERE identifier = ?1 AND type = 'password_reset' AND used = 0`, + ) + .bind(email) + .run(); + + await c.env.DB.prepare( + `INSERT INTO ${tbl(c.env, 'verifications')} (identifier, type, code_hash, expires_at) VALUES (?1, ?2, ?3, ?4)`, + ) + .bind(email, 'password_reset', codeHash, expiresAt) + .run(); + + const appName = await getAppName(c.env); await sendEmail(c.env, { to: email, subject: `${appName} — Password Reset`, @@ -1669,24 +1683,10 @@ auth.post('/forgot-password', async (c) => { } catch (err) { // BE-R2: log only a redacted form — never the upstream response body. console.error( - 'forgot-password email failed', + 'forgot-password background task failed', err instanceof Error ? err.name : typeof err, ); - return; } - - // Invalidate any previous unused reset codes for this email - await c.env.DB.prepare( - `DELETE FROM ${tbl(c.env, 'verifications')} WHERE identifier = ?1 AND type = 'password_reset' AND used = 0`, - ) - .bind(email) - .run(); - - await c.env.DB.prepare( - `INSERT INTO ${tbl(c.env, 'verifications')} (identifier, type, code_hash, expires_at) VALUES (?1, ?2, ?3, ?4)`, - ) - .bind(email, 'password_reset', codeHash, expiresAt) - .run(); })(), ); diff --git a/apps/worker/test/migrations.test.ts b/apps/worker/test/migrations.test.ts index 9c67bac..e386403 100644 --- a/apps/worker/test/migrations.test.ts +++ b/apps/worker/test/migrations.test.ts @@ -5,6 +5,7 @@ import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; +import { DatabaseSync } from 'node:sqlite'; import { test } from 'node:test'; import { fileURLToPath } from 'node:url'; import { renderMigrationFiles } from '../scripts/generate-migrations.ts'; @@ -44,3 +45,14 @@ test('迁移名与文件名遵循 schema_vN <-> NNNN_*.sql 约定 (BE-Q1)', () = assert.match(migration.fileName, /^\d{4}_.+\.sql$/); } }); + +// The wrangler migration files must keep their original fail-if-exists +// semantics (no IF NOT EXISTS / OR IGNORE), so re-applying one to an already +// migrated database errors instead of silently skipping — wrangler tracks +// applied migrations and this error is the guard against schema drift. +test('无前缀 wrangler 迁移在对象已存在时仍报错,保留原语义 (BE-Q1)', () => { + const files = renderMigrationFiles(); + const db = new DatabaseSync(':memory:'); + db.exec(files['0001_init.sql']); + assert.throws(() => db.exec(files['0001_init.sql']), /already exists/); +});