From ea97a12b9de88fcd713603ad279660732de650a6 Mon Sep 17 00:00:00 2001 From: mapxn <16299874+mapxn@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:50:32 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20APP=5FURL/RP=5FID/APP=5FORIGIN=20?= =?UTF-8?q?=E6=94=B9=E4=B8=BA=E5=8F=AF=E9=80=89=E5=B9=B6=E4=BB=8E=E8=AF=B7?= =?UTF-8?q?=E6=B1=82=E6=8E=A8=E5=AF=BC=EF=BC=8CAPP=5FNAME=20=E6=94=B6?= =?UTF-8?q?=E6=95=9B=E4=B8=BA=E5=BA=94=E7=94=A8=E5=86=85=E8=AE=BE=E7=BD=AE?= =?UTF-8?q?=20(ONE-437)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 把四个原本必须配置的 Worker 变量降级为「可不配」: - 新增 `apps/worker/src/lib/app-defaults.ts` 作为唯一解析入口: `appUrl(c)` / `rpId(c)` / `appOrigin(c)`(显式 env 优先,否则用请求 origin / hostname)与 `appName(env)`(DB settings.app_name,默认 Hop)。 - `index.ts` 的 securityHeaders、CORS 白名单、`/api/config`;`auth.ts` 的 Cookie Secure、Passkey rpID/rpName 与两处 verify、`/api/admin/email/test` 全部改走该入口,删除 auth.ts / admin.ts / index.ts 里三份重复的 app_name 读取实现。 - `types.ts`:三项改为可选,`APP_NAME` 从 Env 移除。 - 新增 22 项测试覆盖「未配置按请求推导」「配置了 env 胜出」「APP_NAME 全未配 时 /api/config 与 rpName 都是 Hop,管理面改名后两处同步生效」。 - README / README.zh-CN / CLAUDE.md / .dev.vars.example 同步更新。 已配置这三项的存量部署行为不变(显式配置始终优先)。 --- CLAUDE.md | 9 +- README.md | 31 +- README.zh-CN.md | 30 +- apps/worker/.dev.vars.example | 14 +- apps/worker/src/index.ts | 34 +- apps/worker/src/lib/app-defaults.ts | 62 ++++ apps/worker/src/lib/security.ts | 7 +- apps/worker/src/routes/admin.ts | 17 +- apps/worker/src/routes/auth.ts | 52 ++- apps/worker/src/routes/redirect.ts | 13 +- apps/worker/src/types.ts | 10 +- apps/worker/test/app-defaults.test.ts | 470 ++++++++++++++++++++++++++ apps/worker/test/helpers/app.ts | 14 +- 13 files changed, 646 insertions(+), 117 deletions(-) create mode 100644 apps/worker/src/lib/app-defaults.ts create mode 100644 apps/worker/test/app-defaults.test.ts diff --git a/CLAUDE.md b/CLAUDE.md index 6e6520a..6f491ae 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -221,14 +221,13 @@ For local development, put secrets in `apps/worker/.dev.vars` (gitignored). ## wrangler.toml Variables -All set via the Cloudflare dashboard (Variables and Secrets). `keep_vars = true` prevents deployments from overwriting them. The four ordinary variables `APP_NAME` / `APP_URL` / `RP_ID` / `APP_ORIGIN` are set via the CF dashboard only and are **not migrated** by CI; their values must **never change** — `RP_ID` / `APP_ORIGIN` are the WebAuthn passkey relying-party identifiers, and changing them invalidates every user's passkeys. +All set via the Cloudflare dashboard (Variables and Secrets). `keep_vars = true` prevents deployments from overwriting them. `APP_URL` / `RP_ID` / `APP_ORIGIN` are optional and read only through `src/lib/app-defaults.ts` — never directly via `env.*` in routes. Unset, they are derived from the request (origin / hostname); configured, they win. `APP_NAME` is **not** an env var: the app name comes from the admin setting `app_name` (default `Hop`). A configured `RP_ID` / `APP_ORIGIN` must **never change** — they are the WebAuthn relying-party identifiers, and changing them invalidates every user's passkeys. | Var | Required | Description | |---|---|---| -| `APP_URL` | Yes | Canonical origin (`https://yourdomain.com`) | -| `APP_NAME` | Yes | Default app name (overridable in admin UI) | -| `RP_ID` | Yes | WebAuthn relying party ID (domain only, no protocol) | -| `APP_ORIGIN` | Yes | WebAuthn origin (full URL with protocol) | +| `APP_URL` | No | Canonical origin (`https://yourdomain.com`). Default: request origin — used for CORS, HSTS, the refresh cookie's `Secure` flag and the `/404` redirect. | +| `RP_ID` | No | WebAuthn relying party ID (domain only, no protocol). Default: request hostname. | +| `APP_ORIGIN` | No | WebAuthn origin (full URL with protocol). Default: request origin. | | `TABLE_PREFIX` | No | Three-state prefix for all D1 table names. Unset → default `hop` (`hop_users`, `hop_links`, …); a custom value → that value (case preserved, `[^a-zA-Z0-9_]` stripped); explicit empty string → no prefix (deployer accepts table-collision risk). Must be configured **before** running the setup route — changing it after initial setup requires renaming all tables manually. On GitHub Actions, `none` is the reserved word for the explicit empty string (unset/empty both become the default `hop`). A silent switch (database initialised under a different prefix) aborts setup/migrations with an error. | Email sender config and API keys are managed in the **admin UI settings**, not here. diff --git a/README.md b/README.md index 8284003..7bedd71 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,7 @@ Repository variables (the deploy workflow reads these): | `D1_DATABASE_ID` | D1 database ID from the previous step | | `D1_DATABASE_NAME` | (Optional) Only needed if you customized the D1 database name in the previous step; otherwise, no configuration is required | | `TABLE_PREFIX` | (Optional) Production environment variable. The CI reserved word `none` means explicit no prefix. Must equal the Worker's `TABLE_PREFIX` plain-text variable (step 4). | -| `APP_URL` | Production environment variable used by the smoke test; must point at the production URL and equal the Worker's `APP_URL` variable (step 4). | +| `APP_URL` | Production URL used by the smoke test (step 6). Independent of the optional Worker variable of the same name (step 4) — the Worker no longer needs it. | The deploy workflow (`.github/workflows/deploy.yml`) injects the resource IDs into `wrangler.toml` at deploy time via `sed`, so no IDs are ever committed to the repository. @@ -79,10 +79,9 @@ Go to [Cloudflare dashboard](https://dash.cloudflare.com) → **Workers & Pages | Name | Type | Required | Example / Notes | |---|---|---|---| -| `APP_URL` | Variable | Yes | `https://yourdomain.com` — must equal the GitHub `APP_URL` variable (step 3) | -| `APP_NAME` | Variable | Yes | `Hop` — default app name, overridable in admin UI | -| `RP_ID` | Variable | Yes | `yourdomain.com` — WebAuthn relying party ID (domain only) | -| `APP_ORIGIN` | Variable | Yes | `https://yourdomain.com` — WebAuthn origin (full URL) | +| `APP_URL` | Variable | No | Canonical base URL (e.g. `https://yourdomain.com`). Optional — defaults to the origin of each request. Set it only to pin a URL that differs from the one clients hit. | +| `RP_ID` | Variable | No | WebAuthn relying party ID (domain only). Optional — defaults to the request hostname. | +| `APP_ORIGIN` | Variable | No | WebAuthn origin (full URL). Optional — defaults to the origin of each request. | | `TABLE_PREFIX` | Variable | No | Three-state table prefix. Unset → default `hop` (`hop_users`, `hop_links`, …). A custom value → that value, case preserved, `[^a-zA-Z0-9_]` stripped. Explicit empty string → no prefix (deployer accepts the table-collision risk). Must equal the GitHub `TABLE_PREFIX` variable (step 3). Set **before** first setup and never change it once data exists. | | `TOTP_ENCRYPTION_KEY` | Secret | Yes | `openssl rand -hex 32` — encrypts TOTP credentials; rotating it invalidates every bound TOTP. The **only** secret configured in the Cloudflare console and never handled by CI. | @@ -90,7 +89,11 @@ Go to [Cloudflare dashboard](https://dash.cloudflare.com) → **Workers & Pages > > `JWT_SECRET` and `SETUP_SECRET` are **not** configured here — CI uploads them from the GitHub Secrets added in step 3. `TOTP_ENCRYPTION_KEY` is the only secret that stays exclusively in the Cloudflare console. > -> The ordinary variables `APP_NAME` / `APP_URL` / `RP_ID` / `APP_ORIGIN` are set via the **Cloudflare dashboard** only and are **not migrated** by CI; their values must **never change** — `RP_ID` / `APP_ORIGIN` are the WebAuthn passkey relying-party identifiers, and changing them invalidates every user's passkeys. `APP_URL` and `TABLE_PREFIX` are also read by CI as GitHub variables (step 3) for the smoke test and prefix resolution, so keep those two GitHub variables equal to these Worker variables. +> `APP_URL` / `RP_ID` / `APP_ORIGIN` are optional: when unset the Worker derives them from the incoming request (see [Environment Variables](#environment-variables)). An explicit value always wins, so a deployment that already configures them behaves exactly as before. `APP_NAME` is **no longer an env var** — the app name is the admin UI setting `app_name` (default `Hop`). +> +> `RP_ID` / `APP_ORIGIN` are the WebAuthn passkey relying-party identifiers. If you configure them, their values must **never change** — changing them invalidates every user's passkeys. With them unset, the rpID is derived from the hostname the user actually visits, so credentials stay bound to that hostname: visiting through your custom domain behaves like the old explicit config, while visiting through another hostname (e.g. `*.workers.dev`) yields a different rpID and therefore different passkey scope — inherent to a multi-hostname deployment, not a regression. +> +> The GitHub `TABLE_PREFIX` variable (step 3) still feeds prefix resolution; keep it equal to the Worker's `TABLE_PREFIX`. > > Email provider settings (Resend API key, SMTP credentials, etc.) are configured in the **admin UI** after first login — no Cloudflare dashboard config needed. @@ -175,9 +178,10 @@ Navigate to your deployed URL and register — the first account is automaticall ```bash # 1. Create apps/worker/.dev.vars cat > apps/worker/.dev.vars << 'EOF' -APP_URL=http://localhost:8787 -APP_NAME=Hop -RP_ID=localhost +# APP_URL / RP_ID / APP_ORIGIN are optional — unset, they are derived from the +# request URL (http://localhost:8787 → rpID "localhost"). APP_ORIGIN is only +# needed for passkey testing, where the page runs on the Vite dev server +# (:5173) while /api is proxied to the Worker (:8787). APP_ORIGIN=http://localhost:5173 JWT_SECRET=dev-secret-at-least-32-characters-long TOTP_ENCRYPTION_KEY=0000000000000000000000000000000000000000000000000000000000000000 @@ -300,10 +304,9 @@ All variables and secrets are managed in the **Cloudflare dashboard** (Workers & | Variable | Type | Required | Description | |---|---|---|---| -| `APP_URL` | Var | Yes | Canonical base URL (e.g. `https://go.example.com`) | -| `APP_NAME` | Var | Yes | Default app name; overridable in admin UI | -| `RP_ID` | Var | Yes | WebAuthn relying party ID (domain without protocol) | -| `APP_ORIGIN` | Var | Yes | WebAuthn origin (full URL) | +| `APP_URL` | Var | No | Canonical base URL (e.g. `https://go.example.com`). Optional — defaults to the request origin (used for CORS, HSTS, the refresh cookie's `Secure` flag and the `/404` redirect). | +| `RP_ID` | Var | No | WebAuthn relying party ID (domain without protocol). Optional — defaults to the request hostname. | +| `APP_ORIGIN` | Var | No | WebAuthn origin (full URL). Optional — defaults to the request origin. | | `TABLE_PREFIX` | Var | No | Three-state prefix for all D1 table names. Unset → default `hop` (`hop_users`, `hop_links`, …); custom value → that value (case preserved); explicit empty → no prefix. Set once before the first migration — changing it later requires renaming tables. Only alphanumeric and underscore characters are used. | | `JWT_SECRET` | Secret | Yes | HS256 signing key, ≥ 32 chars | | `TOTP_ENCRYPTION_KEY` | Secret | Yes | Hex string from `openssl rand -hex 32` | @@ -317,7 +320,7 @@ All variables and secrets are managed in the **Cloudflare dashboard** (Workers & |---|---|---| | `registration_enabled` | `true` / `false` | Allow new user registration (default: `false`) | | `require_email_verification` | `true` / `false` | Require new users to verify their email before signing in (default: `false`) | -| `app_name` | string | Override displayed app name | +| `app_name` | string | App name shown in the UI, emails and passkey prompts. Default `Hop`. There is no env var for it — this setting is the single source. | | `email_provider` | `resend` / `smtp` | Which email backend to use (default: `resend`) | | `resend_api_key` | string | Resend API key | | `email_from_domain` | domain | Sender domain for Resend, e.g. `example.com` | diff --git a/README.zh-CN.md b/README.zh-CN.md index b54b46d..337f28f 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -70,7 +70,7 @@ | `D1_DATABASE_ID` | 上一步中的 D1 database ID | | `D1_DATABASE_NAME` | (可选)仅当上一步自定义了 D1 数据库名称时才需配置为对应名称,否则无须配置。 | | `TABLE_PREFIX` | (可选)production 环境变量。CI 中保留字 `none` 表示显式无前缀。必须与 Worker 的同名明文变量一致(见第 4 步)。 | -| `APP_URL` | production 环境变量,smoke test 使用,须指向生产 URL,并与 Worker 的 `APP_URL` 变量一致(见第 4 步)。 | +| `APP_URL` | 生产 URL,供 smoke test 使用(见第 6 步)。与第 4 步中同名的 Worker 变量无关——Worker 已不再需要它。 | 部署工作流(`.github/workflows/deploy.yml`)在部署时通过 `sed` 将这些资源 ID 注入 `wrangler.toml`,因此 ID 不会提交到仓库。 @@ -80,10 +80,9 @@ | 名称 | 类型 | 必填 | 示例 / 说明 | |---|---|---|---| -| `APP_URL` | Variable | 是 | `https://yourdomain.com` — 须与 GitHub 中的 `APP_URL` 变量一致(第 3 步) | -| `APP_NAME` | Variable | 是 | `Hop` — 默认应用名称,可在管理界面覆盖 | -| `RP_ID` | Variable | 是 | `yourdomain.com` — WebAuthn 依赖方 ID(仅域名) | -| `APP_ORIGIN` | Variable | 是 | `https://yourdomain.com` — WebAuthn 来源(完整 URL) | +| `APP_URL` | Variable | 否 | 规范基础 URL(例如 `https://yourdomain.com`)。可选——未配置时按每个请求的 origin 推导。仅当需要固定一个与客户端实际访问地址不同的 URL 时才配置。 | +| `RP_ID` | Variable | 否 | WebAuthn 依赖方 ID(仅域名)。可选——未配置时按请求 hostname 推导。 | +| `APP_ORIGIN` | Variable | 否 | WebAuthn 来源(完整 URL)。可选——未配置时按请求 origin 推导。 | | `TABLE_PREFIX` | Variable | 否 | 三态表前缀。未配置 → 默认 `hop`(`hop_users`、`hop_links` 等);配置自定义值 → 该值(保留大小写,剔除 `[^a-zA-Z0-9_]`);显式配置为空字符串 → 无前缀(部署者自担撞表风险)。须与 GitHub 中的 `TABLE_PREFIX` 变量一致(第 3 步)。必须在**首次** setup 前设置,一旦有数据后不得更改。 | | `TOTP_ENCRYPTION_KEY` | Secret | 是 | `openssl rand -hex 32` — 加密 TOTP 凭据,轮换会使已绑定的 TOTP 全部失效。这是**唯一**在 Cloudflare 控制台配置的 Secret,不经 CI。 | @@ -91,7 +90,11 @@ > > `JWT_SECRET` 与 `SETUP_SECRET` **不在此处配置** — 由 CI 从第 3 步添加的 GitHub Secret 上传。只有 `TOTP_ENCRYPTION_KEY` 仅存在于 Cloudflare 控制台、从不经 CI。 > -> 普通变量 `APP_NAME` / `APP_URL` / `RP_ID` / `APP_ORIGIN` 仅在 **Cloudflare 控制台** 设置,不迁移;其值**严禁变更**——`RP_ID` / `APP_ORIGIN` 是 WebAuthn 通行密钥的依赖方标识,一旦变更将导致所有用户的通行密钥失效。`APP_URL` 与 `TABLE_PREFIX` 同时作为 GitHub 变量(第 3 步)供 smoke test 与前缀解析读取,需与这里的 Worker 变量保持同值。 +> `APP_URL` / `RP_ID` / `APP_ORIGIN` 均为可选:未配置时 Worker 按请求推导(见[环境变量](#环境变量))。显式配置始终优先,因此已配置这三项的存量部署行为与改前完全一致。`APP_NAME` **不再是环境变量**——应用名称唯一来源是管理面设置 `app_name`(默认 `Hop`)。 +> +> `RP_ID` / `APP_ORIGIN` 是 WebAuthn 通行密钥的依赖方标识。若配置,其值**严禁变更**——一旦变更将导致所有用户的通行密钥失效。若未配置,rpID 按用户实际访问的 hostname 推导,凭据仍按域名绑定:经正式自定义域名访问与原显式配置等价;经其他域名(例如 `*.workers.dev`)访问会得到不同的 rpID,从而形成不同的通行密钥作用域——这是多域名部署的固有行为,不是本次变更的回归。 +> +> GitHub 中的 `TABLE_PREFIX` 变量(第 3 步)仍供前缀解析读取,需与 Worker 的同名变量保持同值。 > > 邮件提供商设置(Resend API 密钥、SMTP 凭据等)在首次登录后通过**管理界面**配置 — 无需在 Cloudflare 控制台中配置。 @@ -159,9 +162,9 @@ curl -X POST https://your-worker.workers.dev/api/setup \ ```bash # 1. 创建 apps/worker/.dev.vars cat > apps/worker/.dev.vars << 'EOF' -APP_URL=http://localhost:8787 -APP_NAME=Hop -RP_ID=localhost +# APP_URL / RP_ID / APP_ORIGIN 均可选——不配时按请求 URL 推导 +# (http://localhost:8787 → rpID "localhost")。只有测试通行密钥时才需要 +# APP_ORIGIN:此时页面由 Vite dev server(:5173)提供,而 /api 代理到 Worker(:8787)。 APP_ORIGIN=http://localhost:5173 JWT_SECRET=dev-secret-at-least-32-characters-long TOTP_ENCRYPTION_KEY=0000000000000000000000000000000000000000000000000000000000000000 @@ -284,10 +287,9 @@ GET /:slug → 302 跳转到目标 URL | 变量 | 类型 | 必填 | 描述 | |---|---|---|---| -| `APP_URL` | 变量 | 是 | 规范基础 URL(例如 `https://go.example.com`) | -| `APP_NAME` | 变量 | 是 | 默认应用名称;可在管理界面覆盖 | -| `RP_ID` | 变量 | 是 | WebAuthn 依赖方 ID(不含协议的域名) | -| `APP_ORIGIN` | 变量 | 是 | WebAuthn 来源(完整 URL) | +| `APP_URL` | 变量 | 否 | 规范基础 URL(例如 `https://go.example.com`)。可选——未配置时用请求 origin(用于 CORS、HSTS、refresh cookie 的 `Secure` 标记与 `/404` 跳转)。 | +| `RP_ID` | 变量 | 否 | WebAuthn 依赖方 ID(不含协议的域名)。可选——未配置时用请求 hostname。 | +| `APP_ORIGIN` | 变量 | 否 | WebAuthn 来源(完整 URL)。可选——未配置时用请求 origin。 | | `TABLE_PREFIX` | 变量 | 否 | 所有 D1 表名的三态前缀。未配置 → 默认 `hop`(`hop_users`、`hop_links` 等);自定义值 → 该值(保留大小写);显式空 → 无前缀。在第一次迁移前设置一次 — 之后更改需手动重命名所有表。只使用字母数字和下划线字符。 | | `JWT_SECRET` | 密钥 | 是 | HS256 签名密钥,≥ 32 字符 | | `TOTP_ENCRYPTION_KEY` | 密钥 | 是 | 来自 `openssl rand -hex 32` 的十六进制字符串 | @@ -301,7 +303,7 @@ GET /:slug → 302 跳转到目标 URL |---|---|---| | `registration_enabled` | `true` / `false` | 允许新用户注册(默认:`false`) | | `require_email_verification` | `true` / `false` | 要求新用户在登录前验证其邮箱地址(默认:`false`) | -| `app_name` | 字符串 | 覆盖显示的应用名称 | +| `app_name` | 字符串 | 界面、邮件与通行密钥提示中显示的应用名称,默认 `Hop`。没有对应的环境变量——本设置是唯一来源。 | | `email_provider` | `resend` / `smtp` | 使用哪个邮件后端(默认:`resend`) | | `resend_api_key` | 字符串 | Resend API 密钥 | | `email_from_domain` | 域名 | Resend 的发件人域名,例如 `example.com` | diff --git a/apps/worker/.dev.vars.example b/apps/worker/.dev.vars.example index 7fa3096..e70fbeb 100644 --- a/apps/worker/.dev.vars.example +++ b/apps/worker/.dev.vars.example @@ -2,13 +2,15 @@ # Copy this file to apps/worker/.dev.vars and fill in real values. # .dev.vars is gitignored — never commit real secrets. -# ─── Ordinary variables ─────────────────────────────────────────────────────── -# Production values are set via the Cloudflare dashboard (Variables) and are -# NOT migrated by CI. Their values must never change: -# RP_ID / APP_ORIGIN are the WebAuthn passkey relying-party identifiers — -# changing them invalidates every user's passkeys. +# ─── Ordinary variables (all optional) ──────────────────────────────────────── +# Leave these empty to derive them from the request URL: APP_URL/APP_ORIGIN from +# the request origin, RP_ID from the request hostname. An explicit value always +# wins. APP_NAME is gone — the app name is the admin UI setting `app_name` +# (default "Hop"). +# +# APP_ORIGIN is only needed for passkey testing locally: the page is served by +# the Vite dev server (http://localhost:5173) while /api is proxied to :8787. APP_URL= -APP_NAME= RP_ID= APP_ORIGIN= diff --git a/apps/worker/src/index.ts b/apps/worker/src/index.ts index e47b5c6..72df779 100644 --- a/apps/worker/src/index.ts +++ b/apps/worker/src/index.ts @@ -1,5 +1,6 @@ import { Hono } from 'hono'; import { cors } from 'hono/cors'; +import { appName, appUrl } from './lib/app-defaults.js'; import { tbl } from './lib/db.js'; import { apiError } from './lib/errors.js'; import { getCachedSetting, setCachedSetting } from './lib/kv.js'; @@ -39,9 +40,7 @@ app.onError((err, c) => { // ─── Security headers ───────────────────────────────────────────────────────── app.use('/api/*', async (c, next) => { await next(); - for (const [k, v] of Object.entries( - securityHeaders(c.env.APP_URL, API_CSP), - )) { + for (const [k, v] of Object.entries(securityHeaders(appUrl(c), API_CSP))) { c.header(k, v); } }); @@ -50,10 +49,11 @@ app.use('/api/*', async (c, next) => { app.use('/api/*', async (c, next) => { const handler = cors({ origin: (origin) => { - // Trim APP_URL so a stray leading/trailing space in the variable doesn't - // make the allowed-origin list miss every real Origin (which is also why - // HSTS went missing in production). - const allowed = [c.env.APP_URL.trim()]; + // appUrl(c) resolves APP_URL, falling back to this request's origin; trim + // so a stray leading/trailing space in the variable doesn't make the + // allowed-origin list miss every real Origin (which is also why HSTS went + // missing in production). + const allowed = [appUrl(c).trim()]; // 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. @@ -77,23 +77,11 @@ app.use('/api/*', async (c, next) => { // ─── Public config endpoint ─────────────────────────────────────────────────── app.get('/api/config', async (c) => { - const [appNameCached, regCached] = await Promise.all([ - getCachedSetting(c.env.LINKS_KV, 'app_name'), + const [name, regCached] = await Promise.all([ + appName(c.env), getCachedSetting(c.env.LINKS_KV, 'registration_enabled'), ]); - let appName: string; - if (appNameCached !== null) { - appName = appNameCached; - } else { - const row = await c.env.DB.prepare( - `SELECT value FROM ${tbl(c.env, 'settings')} WHERE key = 'app_name'`, - ).first<{ value: string }>(); - appName = row?.value ?? c.env.APP_NAME ?? 'Hop'; - if (row?.value) - await setCachedSetting(c.env.LINKS_KV, 'app_name', row.value); - } - let registrationEnabled: boolean; if (regCached !== null) { registrationEnabled = regCached === 'true'; @@ -106,7 +94,7 @@ app.get('/api/config', async (c) => { registrationEnabled = val === 'true'; } - return c.json({ appName, registrationEnabled }); + return c.json({ appName: name, registrationEnabled }); }); // ─── API Routes ─────────────────────────────────────────────────────────────── @@ -161,7 +149,7 @@ app.all('*', async (c) => { ? crypto.randomUUID() : undefined; for (const [k, v] of Object.entries( - securityHeaders(c.env.APP_URL, spaCsp(nonce)), + securityHeaders(appUrl(c), spaCsp(nonce)), )) { headers.set(k, v); } diff --git a/apps/worker/src/lib/app-defaults.ts b/apps/worker/src/lib/app-defaults.ts new file mode 100644 index 0000000..b287250 --- /dev/null +++ b/apps/worker/src/lib/app-defaults.ts @@ -0,0 +1,62 @@ +// Single resolution entry point for the four deployment-dependent app settings +// that used to be mandatory Worker variables (APP_URL / RP_ID / APP_ORIGIN / +// APP_NAME). Every route must come through here — no route may derive these on +// its own. Rule, uniformly: an explicitly configured variable always wins; +// otherwise the value is derived from the incoming request (or, for the app +// name, from the persisted setting). +// +// Grep guard: `env.APP_URL` / `env.RP_ID` / `env.APP_ORIGIN` / `env.APP_NAME` +// must only appear in this file. + +import type { Context } from 'hono'; +import type { Env, Variables } from '../types.js'; +import { tbl } from './db.js'; +import { getCachedSetting, setCachedSetting } from './kv.js'; + +// Fallback app name when the settings table has no app_name row. APP_NAME is no +// longer an env var: the admin UI setting is the single source of truth. +export const DEFAULT_APP_NAME = 'Hop'; + +type AppContext = Context<{ Bindings: Env; Variables: Variables }>; + +// A variable holding nothing but whitespace counts as "not configured", exactly +// like an unset one — " " is never a usable origin or RP ID. A configured value +// is otherwise returned verbatim (not trimmed): call sites keep their existing +// normalization, so a padded-but-valid value behaves byte-for-byte as before. +function configured(value: string | undefined): string | null { + if (typeof value !== 'string' || value.trim() === '') return null; + return value; +} + +// Canonical base URL of this deployment (scheme + host, no trailing slash). +// Used for CORS allow-listing, HSTS gating, the refresh-cookie Secure flag and +// the /404 redirect target. +export function appUrl(c: AppContext): string { + return configured(c.env.APP_URL) ?? new URL(c.req.url).origin; +} + +// WebAuthn relying-party ID — a bare hostname. +export function rpId(c: AppContext): string { + return configured(c.env.RP_ID) ?? new URL(c.req.url).hostname; +} + +// WebAuthn origin — scheme + host. +export function appOrigin(c: AppContext): string { + return configured(c.env.APP_ORIGIN) ?? new URL(c.req.url).origin; +} + +// App name from the admin UI setting (DB, fronted by the KV cache). The row is +// cached for 60s — including the default — and PUT /api/admin/settings drops +// the cache key on write, so an admin rename is visible immediately. +export async function appName( + env: Pick, +): Promise { + const cached = await getCachedSetting(env.LINKS_KV, 'app_name'); + if (cached !== null) return cached; + const row = await env.DB.prepare( + `SELECT value FROM ${tbl(env, 'settings')} WHERE key = 'app_name'`, + ).first<{ value: string }>(); + const value = row?.value ?? DEFAULT_APP_NAME; + await setCachedSetting(env.LINKS_KV, 'app_name', value); + return value; +} diff --git a/apps/worker/src/lib/security.ts b/apps/worker/src/lib/security.ts index 78a12f1..73045d5 100644 --- a/apps/worker/src/lib/security.ts +++ b/apps/worker/src/lib/security.ts @@ -36,9 +36,10 @@ export function securityHeaders( 'Referrer-Policy': 'strict-origin-when-cross-origin', 'Content-Security-Policy': csp, }; - // Normalize APP_URL before checking its scheme: a stray leading/trailing space - // would otherwise silently suppress HSTS (and break CORS origin matching) even - // though the variable is "correct" apart from the whitespace. + // Normalize the resolved app URL (appUrl(c)) before checking its scheme: a + // stray leading/trailing space would otherwise silently suppress HSTS (and + // break CORS origin matching) even though the variable is "correct" apart + // from the whitespace. if (appUrl.trim().startsWith('https')) { headers['Strict-Transport-Security'] = HSTS; } diff --git a/apps/worker/src/routes/admin.ts b/apps/worker/src/routes/admin.ts index 646e625..b860659 100644 --- a/apps/worker/src/routes/admin.ts +++ b/apps/worker/src/routes/admin.ts @@ -1,4 +1,5 @@ import { Hono } from 'hono'; +import { appName as resolveAppName } from '../lib/app-defaults.js'; import { hashPassword } from '../lib/crypto.js'; import { isUniqueConstraintError, tbl } from '../lib/db.js'; import { EmailConfigError, sendEmail, testEmailHtml } from '../lib/email.js'; @@ -6,8 +7,6 @@ import { checkTestEmailRateLimit, deleteCachedLink, deleteCachedSetting, - getCachedSetting, - setCachedSetting, } from '../lib/kv.js'; import { runMigrations, @@ -54,18 +53,6 @@ async function auditLog( .run(); } -// Read app_name from DB/KV so admin settings changes take effect immediately. -async function getAppName(env: Env): Promise { - const cached = await getCachedSetting(env.LINKS_KV, 'app_name'); - if (cached !== null) return cached; - const row = await env.DB.prepare( - `SELECT value FROM ${tbl(env, 'settings')} WHERE key = 'app_name'`, - ).first<{ value: string }>(); - const val = row?.value ?? env.APP_NAME; - await setCachedSetting(env.LINKS_KV, 'app_name', val); - return val; -} - // ───────────────────────────────────────────────────────────────────────────── // GET /api/admin/stats // ───────────────────────────────────────────────────────────────────────────── @@ -553,7 +540,7 @@ admin.post('/email/test', async (c) => { ); } - const appName = await getAppName(c.env); + const appName = await resolveAppName(c.env); try { await sendEmail(c.env, { diff --git a/apps/worker/src/routes/auth.ts b/apps/worker/src/routes/auth.ts index 45c0acb..40eb632 100644 --- a/apps/worker/src/routes/auth.ts +++ b/apps/worker/src/routes/auth.ts @@ -1,5 +1,11 @@ import type { Context } from 'hono'; import { Hono } from 'hono'; +import { + appOrigin, + appUrl, + appName as resolveAppName, + rpId, +} from '../lib/app-defaults.js'; import { generateOtp, hashPassword, @@ -66,7 +72,9 @@ type AuthContext = Context<{ Bindings: Env; Variables: Variables }>; // ─── Cookie helpers (H4: HttpOnly refresh token) ────────────────────────────── function setRefreshCookie(c: AuthContext, refreshToken: string): void { - const isSecure = c.env.APP_URL.startsWith('https'); + // appUrl(c) resolves APP_URL, falling back to this request's origin, so a + // deployment without APP_URL still gets Secure cookies over https. + const isSecure = appUrl(c).startsWith('https'); c.header( 'Set-Cookie', `refreshToken=${refreshToken}; HttpOnly; SameSite=Strict; Max-Age=604800; Path=/api/auth${isSecure ? '; Secure' : ''}`, @@ -74,7 +82,9 @@ function setRefreshCookie(c: AuthContext, refreshToken: string): void { } function clearRefreshCookie(c: AuthContext): void { - const isSecure = c.env.APP_URL.startsWith('https'); + // appUrl(c) resolves APP_URL, falling back to this request's origin, so a + // deployment without APP_URL still gets Secure cookies over https. + const isSecure = appUrl(c).startsWith('https'); c.header( 'Set-Cookie', `refreshToken=; HttpOnly; SameSite=Strict; Max-Age=0; Path=/api/auth${isSecure ? '; Secure' : ''}`, @@ -139,18 +149,6 @@ async function isEmailVerificationRequired(env: Env): Promise { return val === 'true'; } -// LOW-3: Read app_name from DB/KV so admin settings changes take effect immediately. -async function getAppName(env: Env): Promise { - const cached = await getCachedSetting(env.LINKS_KV, 'app_name'); - if (cached !== null) return cached; - const row = await env.DB.prepare( - `SELECT value FROM ${tbl(env, 'settings')} WHERE key = 'app_name'`, - ).first<{ value: string }>(); - const val = row?.value ?? env.APP_NAME; - await setCachedSetting(env.LINKS_KV, 'app_name', val); - return val; -} - // S4: Dummy hash for constant-time login response when user is not found. // verifyPassword runs full PBKDF2 against this, normalising response time. const TIMING_DUMMY_HASH = @@ -299,7 +297,7 @@ auth.post('/register', async (c) => { const code = generateOtp(6); const codeHash = await sha256(code); const expiresAt = Math.floor(Date.now() / 1000) + 600; - const appName = await getAppName(c.env); + const appName = await resolveAppName(c.env); try { await sendEmail(c.env, { @@ -489,7 +487,7 @@ auth.post('/resend-verify-email', async (c) => { const code = generateOtp(6); const codeHash = await sha256(code); const expiresAt = Math.floor(Date.now() / 1000) + 600; - const appName = await getAppName(c.env); + const appName = await resolveAppName(c.env); try { await sendEmail(c.env, { @@ -819,7 +817,7 @@ auth.post('/2fa/totp/setup', requireAuth, async (c) => { } const secret = generateTotpSecret(); - const appName = await getAppName(c.env); + const appName = await resolveAppName(c.env); const uri = buildTotpUri(secret, userEmail, appName); const encrypted = await encryptTotpSecret(secret, c.env.TOTP_ENCRYPTION_KEY); @@ -1151,7 +1149,7 @@ auth.post('/2fa/email-otp/send-verify', requireAuth, async (c) => { const code = generateOtp(6); const codeHash = await sha256(code); const expiresAt = Math.floor(Date.now() / 1000) + 600; - const appName = await getAppName(c.env); + const appName = await resolveAppName(c.env); try { await sendEmail(c.env, { @@ -1288,7 +1286,7 @@ auth.post('/2fa/email-otp/send', async (c) => { const codeHash = await sha256(code); const expiresAt = Math.floor(Date.now() / 1000) + 600; - const appName = await getAppName(c.env); + const appName = await resolveAppName(c.env); try { await sendEmail(c.env, { @@ -1483,8 +1481,8 @@ auth.post('/2fa/passkey/register-options', requireAuth, async (c) => { } const options = await generateRegistrationOptions({ - rpName: c.env.APP_NAME, - rpID: c.env.RP_ID, + rpName: await resolveAppName(c.env), + rpID: rpId(c), userID: new TextEncoder().encode(userId) as Uint8Array, userName: userEmail, excludeCredentials: existingPasskeys.results.map((pk) => ({ @@ -1546,8 +1544,8 @@ auth.post('/2fa/passkey/register-verify', requireAuth, async (c) => { verification = await verifyPasskeyRegistration( body.response, stored.challenge as string, - c.env.RP_ID, - c.env.APP_ORIGIN, + rpId(c), + appOrigin(c), ); } catch { return apiError( @@ -1723,7 +1721,7 @@ auth.post('/2fa/passkey/verify-options', async (c) => { .all>(); const options = await generateAuthenticationOptions({ - rpID: c.env.RP_ID, + rpID: rpId(c), allowCredentials: passkeys.results.map((pk) => ({ id: pk.id, transports: pk.transports ? JSON.parse(pk.transports) : [], @@ -1828,8 +1826,8 @@ auth.post('/2fa/passkey/verify', async (c) => { verification = await verifyPasskeyAuthentication( body.response, stored.challenge as string, - c.env.RP_ID, - c.env.APP_ORIGIN, + rpId(c), + appOrigin(c), passkey, ); } catch { @@ -2005,7 +2003,7 @@ auth.post('/forgot-password', async (c) => { .bind(email, 'password_reset', codeHash, expiresAt) .run(); - const appName = await getAppName(c.env); + const appName = await resolveAppName(c.env); await sendEmail(c.env, { to: email, subject: `${appName} — Password Reset`, diff --git a/apps/worker/src/routes/redirect.ts b/apps/worker/src/routes/redirect.ts index 0f8d086..0fa0864 100644 --- a/apps/worker/src/routes/redirect.ts +++ b/apps/worker/src/routes/redirect.ts @@ -1,4 +1,5 @@ import { Hono } from 'hono'; +import { appUrl } from '../lib/app-defaults.js'; import { tbl } from '../lib/db.js'; import { getCachedLink, setCachedLink } from '../lib/kv.js'; import { HSTS } from '../lib/security.js'; @@ -22,7 +23,7 @@ function redirectHeaders( 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer', }; - // Same APP_URL normalization as securityHeaders/CORS: a leading/trailing + // Same appUrl(c) normalization as securityHeaders/CORS: a leading/trailing // space must not silently suppress HSTS here either. if (appUrl.trim().startsWith('https')) { headers['Strict-Transport-Security'] = HSTS; @@ -32,6 +33,8 @@ function redirectHeaders( redirect.get('/:slug', async (c) => { const slug = c.req.param('slug'); + // Resolved once: canonical base for the /404 fallback and for HSTS gating. + const base = appUrl(c); // ── 1. KV fast path ──────────────────────────────────────────────────────── let linkData: CachedLink | null = await getCachedLink(c.env.LINKS_KV, slug); @@ -49,7 +52,7 @@ redirect.get('/:slug', async (c) => { if (!row) { return new Response(null, { status: 302, - headers: redirectHeaders(c.env.APP_URL, `${c.env.APP_URL}/404`), + headers: redirectHeaders(base, `${base}/404`), }); } @@ -71,14 +74,14 @@ redirect.get('/:slug', async (c) => { if (!linkData.isActive) { return new Response(null, { status: 302, - headers: redirectHeaders(c.env.APP_URL, `${c.env.APP_URL}/404`), + headers: redirectHeaders(base, `${base}/404`), }); } if (linkData.expiresAt !== null && linkData.expiresAt <= now) { return new Response(null, { status: 302, - headers: redirectHeaders(c.env.APP_URL, `${c.env.APP_URL}/404`), + headers: redirectHeaders(base, `${base}/404`), }); } @@ -111,7 +114,7 @@ redirect.get('/:slug', async (c) => { // ── 5. Redirect ──────────────────────────────────────────────────────────── return new Response(null, { status: 302, - headers: redirectHeaders(c.env.APP_URL, linkData.url), + headers: redirectHeaders(base, linkData.url), }); }); diff --git a/apps/worker/src/types.ts b/apps/worker/src/types.ts index d8a1f6a..4845477 100644 --- a/apps/worker/src/types.ts +++ b/apps/worker/src/types.ts @@ -11,10 +11,12 @@ export interface Env { ASSETS: Fetcher; // Vars - APP_NAME: string; - APP_URL: string; - RP_ID: string; - APP_ORIGIN: string; + // ONE-437: all three are optional — when unset they are derived from the + // request (see lib/app-defaults.ts). APP_NAME is deliberately gone from Env: + // the app name lives only in the admin UI setting (settings.app_name). + APP_URL?: string; + RP_ID?: string; + APP_ORIGIN?: string; TABLE_PREFIX?: string; // Secrets diff --git a/apps/worker/test/app-defaults.test.ts b/apps/worker/test/app-defaults.test.ts new file mode 100644 index 0000000..4fe85c9 --- /dev/null +++ b/apps/worker/test/app-defaults.test.ts @@ -0,0 +1,470 @@ +// ONE-437: APP_URL / RP_ID / APP_ORIGIN became optional — when unset they are +// derived from the incoming request — and APP_NAME is no longer an env var at +// all (the admin UI setting is the single source of truth, default "Hop"). +// +// These tests cover both halves of the rule: an explicitly configured variable +// always wins (byte-for-byte the pre-change behavior), and with nothing +// configured every consumer works off the request URL. +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { Hono } from 'hono'; +import { app } from '../src/index.ts'; +import { appName, appOrigin, appUrl, rpId } from '../src/lib/app-defaults.ts'; +import { HSTS } from '../src/lib/security.ts'; +import admin from '../src/routes/admin.ts'; +import auth from '../src/routes/auth.ts'; +import redirect from '../src/routes/redirect.ts'; +import type { Env, Variables } from '../src/types.ts'; +import { + APP_URL, + accessTokenFor, + makeEnv, + makeEnvWithoutAppVars, + request, + seedUser, + type TestEnv, +} from './helpers/app.ts'; + +const json = (body: unknown, headers: Record = {}) => ({ + method: 'POST', + headers: { 'Content-Type': 'application/json', ...headers }, + body: JSON.stringify(body), +}); + +const bearer = async (token: string) => ({ + Authorization: `Bearer ${token}`, +}); + +// A minimal app whose only job is to expose what the resolver saw, so the +// request-derived branch can be asserted directly (including the origin vs +// hostname distinction, which the port makes visible). +const probe = new Hono<{ Bindings: Env; Variables: Variables }>(); +probe.get('/probe', (c) => + c.json({ appUrl: appUrl(c), rpId: rpId(c), appOrigin: appOrigin(c) }), +); + +async function probeValues(ctx: TestEnv, url: string) { + const res = await request(probe, url, { method: 'GET' }, ctx); + assert.equal(res.status, 200); + return res.json() as Promise<{ + appUrl: string; + rpId: string; + appOrigin: string; + }>; +} + +// ─── Resolvers: request-derived ────────────────────────────────────────────── + +test('resolvers:四项都未配时,appUrl/appOrigin 用请求 origin、rpId 用 hostname', async () => { + const ctx = makeEnvWithoutAppVars(); + const values = await probeValues(ctx, 'https://go.example.com:8443/probe'); + assert.equal(values.appUrl, 'https://go.example.com:8443'); + assert.equal(values.appOrigin, 'https://go.example.com:8443'); + // hostname has no port, origin does — the WebAuthn rpID must never carry one. + assert.equal(values.rpId, 'go.example.com'); +}); + +test('resolvers:显式配置优先于请求推导', async () => { + const ctx = makeEnv({ + APP_URL: 'https://configured.example', + RP_ID: 'configured.example', + APP_ORIGIN: 'https://configured.example:9443', + }); + const values = await probeValues(ctx, 'https://go.example.com:8443/probe'); + assert.equal(values.appUrl, 'https://configured.example'); + assert.equal(values.rpId, 'configured.example'); + assert.equal(values.appOrigin, 'https://configured.example:9443'); +}); + +test('resolvers:仅空白字符的变量视为未配置,按请求推导', async () => { + const ctx = makeEnv({ APP_URL: ' ', RP_ID: ' ', APP_ORIGIN: '\t' }); + const values = await probeValues(ctx, 'http://localhost:8787/probe'); + assert.equal(values.appUrl, 'http://localhost:8787'); + assert.equal(values.rpId, 'localhost'); + assert.equal(values.appOrigin, 'http://localhost:8787'); +}); + +test('resolvers:已配置但带空格的变量原样返回(归一化仍由调用点负责)', async () => { + const ctx = makeEnv({ + APP_URL: ' https://go.example.com ', + RP_ID: ' example.com', + }); + const values = await probeValues(ctx, 'https://other.example/probe'); + assert.equal(values.appUrl, ' https://go.example.com '); + assert.equal(values.rpId, ' example.com'); +}); + +// ─── CORS ──────────────────────────────────────────────────────────────────── + +test('CORS:未配 APP_URL 时回显请求自身 origin', async () => { + const ctx = makeEnvWithoutAppVars(); + const res = await request( + app, + 'https://go.example.com/api/config', + { + method: 'OPTIONS', + headers: { + Origin: 'https://go.example.com', + 'Access-Control-Request-Method': 'GET', + }, + }, + ctx, + ); + assert.equal(res.status, 204); + assert.equal( + res.headers.get('Access-Control-Allow-Origin'), + 'https://go.example.com', + ); +}); + +test('CORS:未配 APP_URL 时其他 origin 不被放行', async () => { + const ctx = makeEnvWithoutAppVars(); + const res = await request( + app, + 'https://go.example.com/api/config', + { + method: 'OPTIONS', + headers: { + Origin: 'https://evil.example', + 'Access-Control-Request-Method': 'GET', + }, + }, + ctx, + ); + assert.equal(res.headers.get('Access-Control-Allow-Origin'), null); +}); + +test('CORS:配了 APP_URL 时以 env 为准(请求 origin 不被放行)', async () => { + const ctx = makeEnv({ APP_URL: 'https://configured.example' }); + const allowed = await request( + app, + 'https://go.example.com/api/config', + { + method: 'OPTIONS', + headers: { + Origin: 'https://configured.example', + 'Access-Control-Request-Method': 'GET', + }, + }, + ctx, + ); + assert.equal( + allowed.headers.get('Access-Control-Allow-Origin'), + 'https://configured.example', + ); + + const denied = await request( + app, + 'https://go.example.com/api/config', + { + method: 'OPTIONS', + headers: { + Origin: 'https://go.example.com', + 'Access-Control-Request-Method': 'GET', + }, + }, + ctx, + ); + assert.equal(denied.headers.get('Access-Control-Allow-Origin'), null); +}); + +// ─── Security headers (HSTS gating) ────────────────────────────────────────── + +test('安全头:未配 APP_URL 时 https 请求带 HSTS、http 请求不带', async () => { + const ctx = makeEnvWithoutAppVars(); + + const https = await request( + app, + 'https://go.example.com/api/health', + { method: 'GET' }, + ctx, + ); + assert.equal(https.headers.get('Strict-Transport-Security'), HSTS); + + const http = await request( + app, + 'http://localhost:8787/api/health', + { method: 'GET' }, + ctx, + ); + assert.equal(http.headers.get('Strict-Transport-Security'), null); +}); + +test('安全头:未配 APP_URL 时 SPA HTML 响应按请求 scheme 决定 HSTS', async () => { + const htmlCtx = () => + makeEnvWithoutAppVars({ + ASSETS: { + fetch: async () => + new Response('', { + headers: { 'content-type': 'text/html; charset=utf-8' }, + }), + }, + }); + + const https = await request( + app, + 'https://go.example.com/login', + { method: 'GET' }, + htmlCtx(), + ); + assert.equal(https.headers.get('Strict-Transport-Security'), HSTS); + + const http = await request( + app, + 'http://localhost:5173/login', + { method: 'GET' }, + htmlCtx(), + ); + assert.equal(http.headers.get('Strict-Transport-Security'), null); +}); + +test('安全头:配了 http APP_URL 时即便请求是 https 也不发 HSTS(env 胜出)', async () => { + const ctx = makeEnv({ APP_URL: 'http://internal.example' }); + const res = await request( + app, + 'https://go.example.com/api/health', + { method: 'GET' }, + ctx, + ); + assert.equal(res.headers.get('Strict-Transport-Security'), null); +}); + +// ─── /404 redirect target ──────────────────────────────────────────────────── + +test('404 跳转:未配 APP_URL 时用请求 origin 拼 /404', async () => { + const ctx = makeEnvWithoutAppVars(); + const res = await request( + redirect, + 'https://go.example.com/missing', + { method: 'GET' }, + ctx, + ); + assert.equal(res.status, 302); + assert.equal(res.headers.get('Location'), 'https://go.example.com/404'); + assert.equal(res.headers.get('Strict-Transport-Security'), HSTS); +}); + +test('404 跳转:配了 APP_URL 时仍用 env 值', async () => { + const ctx = makeEnv({ APP_URL: 'https://configured.example' }); + const res = await request( + redirect, + 'https://go.example.com/missing', + { method: 'GET' }, + ctx, + ); + assert.equal(res.headers.get('Location'), 'https://configured.example/404'); +}); + +// ─── Refresh cookie Secure flag ────────────────────────────────────────────── + +async function loginOver(ctx: TestEnv, url: string) { + 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, + url, + json({ email: 'alice@example.com', password: 'correct-password' }), + ctx, + ); + assert.equal(res.status, 200); + return res.headers.get('Set-Cookie') ?? ''; +} + +test('Cookie Secure:未配 APP_URL 时 https 请求的 refresh cookie 带 Secure', async () => { + const cookie = await loginOver( + makeEnvWithoutAppVars(), + 'https://go.example.com/login', + ); + assert.match(cookie, /HttpOnly/); + assert.match(cookie, /Secure/); +}); + +test('Cookie Secure:未配 APP_URL 时 http 请求的 refresh cookie 不带 Secure', async () => { + const cookie = await loginOver( + makeEnvWithoutAppVars(), + 'http://localhost:8787/login', + ); + assert.match(cookie, /HttpOnly/); + assert.doesNotMatch(cookie, /Secure/); +}); + +test('Cookie Secure:配了 https APP_URL 时 http 请求仍带 Secure(env 胜出)', async () => { + const cookie = await loginOver( + makeEnv({ APP_URL: 'https://configured.example' }), + 'http://localhost:8787/login', + ); + assert.match(cookie, /Secure/); +}); + +// ─── Passkey relying-party parameters ──────────────────────────────────────── + +async function passkeyRegisterOptions(ctx: TestEnv, url: string) { + await seedUser(ctx.db, { + id: 'u1', + email: 'alice@example.com', + username: 'alice', + role: 'user', + isActive: 1, + tokenVersion: 0, + password: 'correct-password', + }); + const token = await accessTokenFor({ + id: 'u1', + email: 'alice@example.com', + role: 'user', + tokenVersion: 0, + }); + const res = await request( + auth, + url, + { method: 'POST', headers: await bearer(token) }, + ctx, + ); + assert.equal(res.status, 200); + const body = (await res.json()) as { + options: { rp: { id: string; name: string } }; + }; + return body.options.rp; +} + +test('Passkey options:未配 RP_ID/APP_ORIGIN 时 rpID 用请求 hostname', async () => { + const rp = await passkeyRegisterOptions( + makeEnvWithoutAppVars(), + 'https://go.example.com:8443/2fa/passkey/register-options', + ); + assert.equal(rp.id, 'go.example.com'); + assert.equal(rp.name, 'Hop'); +}); + +test('Passkey options:配了 RP_ID 时 rpID 用 env 值', async () => { + const rp = await passkeyRegisterOptions( + makeEnv({ + RP_ID: 'configured.example', + APP_ORIGIN: 'https://configured.example', + }), + 'https://go.example.com/2fa/passkey/register-options', + ); + assert.equal(rp.id, 'configured.example'); +}); + +// ─── App name: admin setting is the only source ────────────────────────────── + +test('appName:settings 表有默认行时 /api/config 与 rpName 都是 Hop', async () => { + const ctx = makeEnvWithoutAppVars(); + const config = await request( + app, + 'https://go.example.com/api/config', + { method: 'GET' }, + ctx, + ); + const body = (await config.json()) as { appName: string }; + assert.equal(body.appName, 'Hop'); + + const rp = await passkeyRegisterOptions( + ctx, + 'https://go.example.com/2fa/passkey/register-options', + ); + assert.equal(rp.name, 'Hop'); +}); + +test('appName:settings 表连默认行都没有时落到常量默认 Hop', async () => { + const ctx = makeEnvWithoutAppVars(); + ctx.db.prepare("DELETE FROM settings WHERE key = 'app_name'").run(); + + const config = await request( + app, + 'https://go.example.com/api/config', + { method: 'GET' }, + ctx, + ); + assert.equal(((await config.json()) as { appName: string }).appName, 'Hop'); + + const rp = await passkeyRegisterOptions( + ctx, + 'https://go.example.com/2fa/passkey/register-options', + ); + assert.equal(rp.name, 'Hop'); +}); + +test('appName:管理面改 app_name 后 /api/config 与 rpName 同步生效(缓存失效)', async () => { + const ctx = makeEnvWithoutAppVars(); + await seedUser(ctx.db, { + id: 'admin1', + email: 'admin@example.com', + username: 'admin', + role: 'admin', + isActive: 1, + tokenVersion: 0, + password: 'admin-password', + }); + const adminToken = await accessTokenFor({ + id: 'admin1', + email: 'admin@example.com', + role: 'admin', + tokenVersion: 0, + }); + + // Warm the KV cache with the default first, so the rename below proves the + // cache is invalidated rather than merely cold. + const before = await request( + app, + 'https://go.example.com/api/config', + { method: 'GET' }, + ctx, + ); + assert.equal(((await before.json()) as { appName: string }).appName, 'Hop'); + + const put = await request( + admin, + 'https://go.example.com/settings', + { + method: 'PUT', + headers: { + ...(await bearer(adminToken)), + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ app_name: 'MyHop' }), + }, + ctx, + ); + assert.equal(put.status, 200); + + const after = await request( + app, + 'https://go.example.com/api/config', + { method: 'GET' }, + ctx, + ); + assert.equal(((await after.json()) as { appName: string }).appName, 'MyHop'); + + const rp = await passkeyRegisterOptions( + ctx, + 'https://go.example.com/2fa/passkey/register-options', + ); + assert.equal(rp.name, 'MyHop'); +}); + +test('appName:APP_NAME 已从 Env 移除,不再影响解析结果', async () => { + const ctx = makeEnvWithoutAppVars({ + // A stale deployment could still have the old variable configured in the CF + // dashboard; it must be ignored now that the admin setting is authoritative. + APP_NAME: 'StaleEnvName', + } as unknown as Partial); + const name = await appName(ctx.env); + assert.equal(name, 'Hop'); +}); + +test('四项全配时:appUrl/rpId/appOrigin 与改前 env 直读完全一致', async () => { + const ctx = makeEnv(); + const values = await probeValues(ctx, 'https://go.example.com/probe'); + assert.equal(values.appUrl, APP_URL); + assert.equal(values.rpId, 'example.com'); + assert.equal(values.appOrigin, APP_URL); +}); diff --git a/apps/worker/test/helpers/app.ts b/apps/worker/test/helpers/app.ts index fb6e8dd..fdef0c3 100644 --- a/apps/worker/test/helpers/app.ts +++ b/apps/worker/test/helpers/app.ts @@ -37,7 +37,6 @@ export function makeEnv(overrides: Partial = {}): TestEnv { DB: db, LINKS_KV: kv, ASSETS: { fetch: async () => new Response('assets', { status: 200 }) }, - APP_NAME: 'Hop', APP_URL, RP_ID: 'example.com', APP_ORIGIN: APP_URL, @@ -50,6 +49,19 @@ export function makeEnv(overrides: Partial = {}): TestEnv { return { env, db, kv, waitUntil: [] }; } +// ONE-437: APP_URL / RP_ID / APP_ORIGIN are optional env vars now — a fresh +// deployment configures none of them. This strips all three from the default env +// so a test exercises the request-derived path; pass overrides to configure a +// subset (that is how the "explicit config wins" cases are built). +export function makeEnvWithoutAppVars(overrides: Partial = {}): TestEnv { + return makeEnv({ + APP_URL: undefined, + RP_ID: undefined, + APP_ORIGIN: undefined, + ...overrides, + }); +} + export async function seedUser( db: D1Mock, user: Omit & { password: string },