From 3dc3e21a2af5f5d62573d8b3b8ac8c0adb6600b5 Mon Sep 17 00:00:00 2001 From: mapxn <16299874+mapxn@users.noreply.github.com> Date: Mon, 26 Oct 2026 16:44:52 +0800 Subject: [PATCH 1/2] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=20Hop=20=E5=A4=A7?= =?UTF-8?q?=E5=B0=8F=E5=86=99=E6=A0=87=E8=AF=86=E7=AC=A6=E5=B9=B6=E5=AF=B9?= =?UTF-8?q?=E9=BD=90=20CF=20Worker=20hop=20(ONE-431)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 93fe1b05 把机器标识符也大写化成 Hop,导致 CF 部署与 D1 迁移测试失败。 本提交逐处分类:机器标识符一律小写 hop,用户可见品牌显示保持 Hop。 - wrangler 配置 name: Hop -> hop(对齐 CF 现有 Worker hop) - .github/scripts/test-d1-migrations.mjs 夹具 name/database_name 小写,临时目录前缀同步 - npm workspace 包名 @Hop/web、@Hop/worker -> @hop/*,turbo.json dependsOn、 apps/worker/tsconfig.json 路径别名、migrations 注释与 generate-migrations 生成头同步 - deploy.yml D1_DATABASE_NAME fallback 'Hop' -> 'shortlink'(既有共享 D1 资源名兜底,不新建/不改名数据库) - smtp.ts EHLO Hop -> EHLO hop,Message-ID 后缀 @Hop -> @hop - 恢复 93fe1b05 误删的根 CLAUDE.md(取 9049d19 原文,仅做最小品牌更新) --- .github/scripts/test-d1-migrations.mjs | 6 +- .github/scripts/test-deploy-checks.mjs | 2 +- .github/workflows/deploy.yml | 2 +- CLAUDE.md | 294 ++++++++++++++++++ apps/web/package.json | 2 +- apps/worker/migrations/0001_init.sql | 2 +- apps/worker/migrations/0002_token_version.sql | 2 +- apps/worker/package.json | 2 +- apps/worker/scripts/generate-migrations.ts | 2 +- apps/worker/src/lib/smtp.ts | 6 +- apps/worker/tsconfig.json | 2 +- apps/worker/wrangler.toml | 2 +- turbo.json | 2 +- 13 files changed, 310 insertions(+), 16 deletions(-) create mode 100644 CLAUDE.md diff --git a/.github/scripts/test-d1-migrations.mjs b/.github/scripts/test-d1-migrations.mjs index 563db1e..432ab42 100644 --- a/.github/scripts/test-d1-migrations.mjs +++ b/.github/scripts/test-d1-migrations.mjs @@ -17,16 +17,16 @@ const scripts = fileURLToPath(new URL('.', import.meta.url)); const worker = fileURLToPath(new URL('../../apps/worker/', import.meta.url)); function fixture(t) { - const cwd = mkdtempSync(join(tmpdir(), 'Hop-d1-test-')); + const cwd = mkdtempSync(join(tmpdir(), 'hop-d1-test-')); t.after(() => rmSync(cwd, { recursive: true, force: true })); writeFileSync(join(cwd, 'package.json'), '{"private":true}'); writeFileSync( join(cwd, 'wrangler.toml'), - `name = "Hop-migration-test" + `name = "hop-migration-test" compatibility_date = "2025-04-01" [[d1_databases]] binding = "DB" -database_name = "Hop-test" +database_name = "hop-test" database_id = "00000000-0000-0000-0000-000000000000" migrations_dir = "migrations" `, diff --git a/.github/scripts/test-deploy-checks.mjs b/.github/scripts/test-deploy-checks.mjs index 4fb52c8..b2e2486 100644 --- a/.github/scripts/test-deploy-checks.mjs +++ b/.github/scripts/test-deploy-checks.mjs @@ -14,7 +14,7 @@ const scripts = fileURLToPath(new URL('.', import.meta.url)); const exec = promisify(execFile); function fixture(t) { - const dir = mkdtempSync(join(tmpdir(), 'Hop-deploy-test-')); + const dir = mkdtempSync(join(tmpdir(), 'hop-deploy-test-')); t.after(() => rmSync(dir, { recursive: true, force: true })); // 仅跳过重试等待,不替换 curl 或 jq。 writeFileSync(join(dir, 'sleep'), '#!/bin/sh\nexit 0\n', { mode: 0o755 }); diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 80dad13..cb30a5e 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -58,7 +58,7 @@ jobs: - name: Inject resource IDs env: D1_DATABASE_ID: ${{ vars.D1_DATABASE_ID }} - D1_DATABASE_NAME: ${{ vars.D1_DATABASE_NAME || 'Hop' }} + D1_DATABASE_NAME: ${{ vars.D1_DATABASE_NAME || 'shortlink' }} KV_NAMESPACE_ID: ${{ vars.KV_NAMESPACE_ID }} CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }} run: | diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..fbfefba --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,294 @@ +# Hop — Claude Code Guide + +## Project Overview + +Hop is a URL shortener running entirely on Cloudflare's platform. It is a pnpm monorepo managed with Turborepo: + +- **`apps/worker`** — Cloudflare Worker (Hono.js + TypeScript backend + static asset serving) +- **`apps/web`** — React + Vite SPA (built output is served via Workers Assets) + +The Worker serves both the API (`/api/*`) and the compiled frontend, so there is only one deployment unit. + +--- + +## Commands + +### Root (run from `/`) +```bash +pnpm dev # turbo: runs both worker dev + web dev concurrently +pnpm build # turbo: typecheck + build web +pnpm typecheck # turbo: tsc --noEmit on both packages +pnpm test # turbo: worker unit tests (node --test, apps/worker/test/*.test.ts) +pnpm deploy # turbo: builds web then deploys worker +``` + +### Worker only (`apps/worker/`) +```bash +pnpm dev # wrangler dev (local mode) +pnpm build # tsc --noEmit +pnpm deploy # wrangler deploy +pnpm db:migrate:local # apply D1 migrations locally +pnpm db:migrate # apply D1 migrations to production +``` + +### Web only (`apps/web/`) +```bash +pnpm dev # vite dev server (port 5173, proxies /api → :8787) +pnpm build # tsc + vite build (output: apps/web/dist/) +``` + +--- + +## Local Development Setup + +1. **Install dependencies** + ```bash + pnpm install + ``` + +2. **Create Cloudflare resources** (one-time) + ```bash + wrangler d1 create shortlink + wrangler kv namespace create LINKS_KV + ``` + Update `apps/worker/wrangler.toml` with the returned IDs. + +3. **Apply migrations locally** + ```bash + cd apps/worker + pnpm db:migrate:local + ``` + +4. **Set secrets** (dev environment uses local .dev.vars or wrangler secret) + ```bash + # Create apps/worker/.dev.vars for local development: + JWT_SECRET=your-random-string-32-chars-min + TOTP_ENCRYPTION_KEY= + SETUP_SECRET=local-setup-secret + ``` + Email provider credentials (Resend API key, SMTP settings) are configured via the **admin UI** after first login — not in `.dev.vars`. + +5. **Start both apps** + ```bash + pnpm dev + # Worker: http://localhost:8787 + # Web: http://localhost:5173 (proxies /api to :8787) + ``` + +--- + +## Project Structure + +``` +hop/ +├── apps/ +│ ├── worker/ +│ │ ├── src/ +│ │ │ ├── index.ts # App entry: mounts routes, security headers, CORS, cron handler +│ │ │ ├── types.ts # Env, Variables, LinkRow, UserRow, CachedLink types +│ │ │ ├── routes/ +│ │ │ │ ├── auth.ts # All auth: register, login, logout, refresh, me, change-password, 2FA setup+verify, forgot/reset password +│ │ │ │ ├── links.ts # Link CRUD (user-scoped) +│ │ │ │ ├── analytics.ts # Per-link and summary click analytics (D1 batch queries) +│ │ │ │ ├── admin.ts # Admin: user mgmt, link mgmt, settings +│ │ │ │ ├── redirect.ts # /:slug redirect + async click logging +│ │ │ │ └── setup.ts # GET /api/setup/state + POST /api/setup — HTTP-triggered DB migration (schema_v1 + schema_v2) +│ │ │ ├── middleware/ +│ │ │ │ └── auth.ts # requireAuth and requireAdmin middleware (JWT verification) +│ │ │ └── lib/ +│ │ │ ├── crypto.ts # PBKDF2 password hash/verify; AES-256-GCM encrypt/decrypt TOTP +│ │ │ ├── db.ts # tbl(env, name) helper: applies the three-state TABLE_PREFIX to all table names +│ │ │ ├── table-prefix.ts # DEFAULT_TABLE_PREFIX + three-state resolveTablePrefix() (single source) +│ │ │ ├── jwt.ts # issueTokenPair, verifyAccessToken, verifyRefreshToken +│ │ │ ├── slug.ts # generateSlug (rejection-sampling), isValidSlug, isReservedSlug, RESERVED_SLUGS +│ │ │ ├── totp.ts # TOTP generate/verify with otpauth library +│ │ │ ├── webauthn.ts # WebAuthn helpers wrapping @simplewebauthn/server +│ │ │ ├── email.ts # Provider dispatch: Resend API or SMTP; otpEmailHtml + resetPasswordEmailHtml templates +│ │ │ ├── smtp.ts # SMTP client over cloudflare:sockets (STARTTLS + implicit TLS) +│ │ │ ├── kv.ts # All KV operations (link cache, challenge store, rate limiting) +│ │ │ ├── migrations-runner.ts # runMigrations() shared by POST /api/setup and POST /api/admin/setup +│ │ │ └── ua.ts # User-agent parsing (device/browser/OS detection) +│ │ ├── migrations/ +│ │ │ └── 0001_init.sql # Canonical schema: all tables + default settings rows (used by wrangler d1 migrations apply) +│ │ └── wrangler.toml +│ └── web/ +│ └── src/ +│ ├── App.tsx # Root component: React Router route definitions +│ ├── main.tsx +│ ├── api/ +│ │ └── client.ts # fetch wrapper with in-flight refresh dedup +│ ├── contexts/ +│ │ ├── AppConfigContext.tsx # Fetches /api/config (appName, registrationEnabled) +│ │ ├── AuthContext.tsx # BroadcastChannel cross-tab auth sync +│ │ └── ThemeContext.tsx # Dark/light theme management +│ ├── i18n/ +│ │ ├── index.tsx # i18n provider and useTranslation hook +│ │ └── locales/ +│ │ ├── en.ts # English strings +│ │ └── zh-CN.ts # Simplified Chinese strings +│ └── pages/ +│ ├── auth/ # Login, Register, TwoFactor, ForgotPassword pages +│ ├── dashboard/ # Links list, Analytics, Account Settings +│ └── admin/ # Users, Links overview, Global Settings +``` + +--- + +## Architecture Decisions + +### Single Deployment Unit +The Worker serves both API and SPA. `wrangler.toml` sets `[assets] directory = "../web/dist"` with `not_found_handling = "single-page-application"`. Hono handles `/api/*` and `/:slug` (short links); everything else falls through to the static SPA. + +SPA routes (login, dashboard, etc.) are protected from being caught as short-link slugs via the `RESERVED_SLUGS` set in `lib/slug.ts`. This is the single source of truth — `index.ts` derives `SPA_PREFIXES` from it directly. + +### JWT Authentication +- Access token: 15-minute lifetime, HS256, stored in memory only +- Refresh token: 7-day lifetime, stored in HttpOnly cookie +- Pending 2FA token: 10-minute lifetime, JTI stored in KV; invalidated after use +- Algorithm pinned to `HS256` at verification (prevents `alg: none` attacks) +- Refresh tokens have server-side JTI denylist in KV + +### Password Hashing +PBKDF2-SHA256 via WebCrypto (Workers has no bcrypt). 100,000 iterations. Format: `v1:{base64-salt}:{base64-hash}`. The `v1:` prefix allows iterating to higher work factors in the future. + +### TOTP Secret Storage +Stored AES-256-GCM encrypted in D1. The encryption key (`TOTP_ENCRYPTION_KEY`) is a hex string set via `wrangler secret put`. CryptoKey objects are cached in-memory per `(keyHex, usage)` pair to avoid re-importing on every request. + +### TOTP Replay Prevention +`totp_used(user_id, code PK, used_at)` table in D1. `INSERT OR IGNORE` is atomic — no TOCTOU window. A nightly cron (`0 3 * * *`) purges rows older than 90 seconds. The same cron purges expired `verifications` rows. + +### KV Key Namespace + +| Prefix | Purpose | TTL | +|---|---|---| +| `link:{slug}` | Short link cache | 21600s (6h) | +| `passkey_challenge:{id}` | WebAuthn challenge | 300s | +| `otp_rate:{email}` | Email OTP rate limit (also used by forgot-password) | 600s | +| `login_attempts:{email}` | Login brute-force rate limit (email dimension) | 900s | +| `login_attempts_ip:{ip}` | Login brute-force rate limit (IP dimension) | 900s | +| `register_rate:{ip}` | Registration rate limit (IP) | 3600s | +| `forgot_pw_rate:{ip}` | Forgot-password rate limit (IP) | 3600s | +| `setup_rate:{ip}` | Setup/migration endpoint rate limit (IP) | 600s | +| `2fa_attempts:{jti}` | General 2FA attempt counter | 600s | +| `passkey_opts:{jti}` | Passkey options attempt counter | 600s | +| `totp_confirm:{userId}` | TOTP setup confirm attempt counter | 120s | +| `pending_2fa:{jti}` | Pending 2FA token payload | 600s | +| `jti_deny:{jti}` | JTI denylist (refresh + access token revocation) | variable (token remaining TTL) | +| `setting:{key}` | Settings cache (all keys incl. SMTP) | 60s | + +### Redirect Flow (Critical Path) +``` +GET /:slug + 1. KV.get("link:{slug}") — fast path + 2. D1 query if KV miss — populates KV on hit + 3. Validate is_active + expires_at + 4. waitUntil(INSERT INTO click_logs) — non-blocking, failure swallowed + 5. 302 → destination_url + Referrer-Policy: no-referrer — prevents slug leakage to destination +``` + +### Cross-Tab Auth Sync +`AuthContext.tsx` opens a `BroadcastChannel('auth')` on mount. After login or token refresh, the new access token is broadcast to other tabs so they don't trigger redundant refresh requests. + +### App Config +`AppConfigContext.tsx` fetches `GET /api/config` on mount and exposes `appName` and `registrationEnabled` to the entire frontend. Used to conditionally hide the Register link and display the correct app name. + +### Internationalization +`i18n/` provides a lightweight provider and `useTranslation()` hook. Supported locales: English (`en`) and Simplified Chinese (`zh-CN`). Language preference is persisted in `localStorage`. + +### Forgot Password Flow +Two-step unauthenticated password reset via email: +1. `POST /api/auth/forgot-password` — takes `email`, generates a 6-digit code, stores in `verifications` table with `type = 'password_reset'` (10-minute TTL), sends a reset email. Always returns `{ success: true }` regardless of whether the email exists (prevents user enumeration). Rate-limited via the same `otp_rate:{email}` KV bucket as Email OTP (3 sends per 10 minutes). +2. `POST /api/auth/reset-password` — takes `email`, `code`, `newPassword`. Validates the code hash against the `verifications` row, max 3 failed attempts before the code is locked. On success, updates `password_hash` and marks the verification as used. + +Frontend: `/forgot-password` page with a 2-step form (email → code + new password). Link shown on the login page. + +--- + +## Secrets Reference + +| Secret | How to generate | Set via | +|---|---|---| +| `JWT_SECRET` | Any random string ≥ 32 chars | Cloudflare dashboard or `wrangler secret put JWT_SECRET` | +| `TOTP_ENCRYPTION_KEY` | `openssl rand -hex 32` | Cloudflare dashboard or `wrangler secret put TOTP_ENCRYPTION_KEY` | +| `SETUP_SECRET` | `openssl rand -hex 24` | Cloudflare dashboard or `wrangler secret put SETUP_SECRET` | + +Email provider credentials (`resend_api_key`, SMTP settings) are configured in the **admin UI** — not as Worker secrets. + +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. + +| 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) | +| `TABLE_PREFIX` | No | Three-state prefix for all D1 table names. Unset → default `sl` (`sl_users`, `sl_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 `sl`). 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. + +--- + +## Database Migrations + +There are two migration paths: + +**`wrangler d1 migrations apply` (local dev):** +Two files in `apps/worker/migrations/`: +- `0001_init.sql` — canonical schema: all tables (users, passkeys, links, click_logs, verifications, settings, audit_logs, totp_used) + default settings rows +- `0002_token_version.sql` — adds `users.token_version` for session revocation + +**HTTP setup route (production):** +The public initialization page lives at `/setup` (an SPA route). `POST /api/setup` with a JSON body `{"secret": ""}` runs migrations via the shared `lib/migrations-runner.ts` (`runMigrations`). Two migrations: +- `schema_v1` — identical DDL as `0001_init.sql`, but parameterized by `TABLE_PREFIX` and tracked in `__schema_migrations` table +- `schema_v2` — adds `token_version` to `users` (mirrors `0002_token_version.sql`) + +The legacy `X-Setup-Secret` header is still accepted when the body is empty. The endpoint is rate-limited to 3 attempts per IP per 10 minutes (counted before the secret check; a `429` carries a `Retry-After` header). `GET /api/setup/state` (public) reports `{ enabled }` from the `setup_page_enabled` setting (default enabled); `GET /api/setup/*` returns `405` pointing at the POST form. An admin can run the same migrations keylessly via `POST /api/admin/setup` (no IP rate limit; writes an audit log entry). `setup_page_enabled` only hides the setup page — it never disables the `POST` migration channel. + +Re-visiting the setup URL is safe — already-applied migrations return `"skipped"`. + +--- + +## Security Notes + +- All routes check `is_active` on the user before completing authentication +- 2FA method bypass prevented: email-otp endpoints gate on `email_2fa_enabled`; TOTP on `totp_enabled` +- Passkey registration capped at 10 per user +- Forgot-password endpoint never reveals whether an email exists (always returns success) +- Password reset codes: max 3 wrong attempts per code; rate-limited 3 sends per 10 min per email +- Login brute-force limited to 10 attempts per 15-minute window per email, plus 20 per IP (`login_attempts:{email}` + `login_attempts_ip:{ip}` KV) +- Registration and forgot-password additionally rate-limited per IP (`register_rate:{ip}`, `forgot_pw_rate:{ip}`) +- Setup/migration endpoint rate-limited per IP (`setup_rate:{ip}`, 3 per 10 min, counted before the secret check); secret sent in the JSON body (legacy header fallback) and compared in constant time +- `cf-connecting-ip` used for IP logging (cannot be forged); `x-forwarded-for` ignored +- User-Agent and Referer headers truncated before storage (512 and 2048 bytes respectively) +- `app_name` setting validated: 1–64 chars, no HTML-special or CR/LF characters +- LIKE queries escape `%`, `_`, `\` metacharacters +- `expiresAt` validated with `Number.isSafeInteger()` to reject NaN/Infinity +- SMTP settings (`smtp_host`, `smtp_user`, `smtp_pass`, `smtp_from`) are validated against CR/LF injection; `smtp_from` validated as a valid email address; `smtp_port` validated as integer 1–65535 +- SMTP STARTTLS failure aborts the send (never falls back to plaintext); SMTP I/O and Resend fetch both carry 10s timeouts +- SMTP passwords are stored in plain text in D1 (but masked in audit logs and never returned by the settings API) — for production deployments where this is a concern, use Resend with a Worker secret instead + +--- + +## Email Provider Architecture + +Two providers are supported, switchable via the `email_provider` setting in the admin UI. After saving your configuration, admins can verify it with **Send test email** (`POST /api/admin/email/test`, rate-limited 5/10min per admin). + +### Resend (default) +- Provider: `resend` +- Configured via `resend_api_key`, `email_from_domain`, `email_from_name` settings in the admin UI (stored in D1, cached in KV for 60s) +- No Worker secrets or wrangler.toml vars required + +### Custom SMTP +- Provider: `smtp` +- All settings stored in the `settings` DB table (cached in KV for 60s) +- SMTP client implemented in `src/lib/smtp.ts` using `cloudflare:sockets` TCP API +- Supports implicit TLS (port 465) and STARTTLS (port 587 or others) +- AUTH LOGIN authentication; unauthenticated relay also supported (leave user/pass empty) +- HTML body encoded as base64 (RFC 2045, 76-char line wrap) — no 8BITMIME negotiation needed diff --git a/apps/web/package.json b/apps/web/package.json index a5f237c..83e9566 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -1,5 +1,5 @@ { - "name": "@Hop/web", + "name": "@hop/web", "version": "1.0.0", "private": true, "type": "module", diff --git a/apps/worker/migrations/0001_init.sql b/apps/worker/migrations/0001_init.sql index 5cf130f..98216f6 100644 --- a/apps/worker/migrations/0001_init.sql +++ b/apps/worker/migrations/0001_init.sql @@ -1,5 +1,5 @@ -- DO NOT EDIT. Generated from src/lib/migrations.ts (getMigrations("")). --- Regenerate with: pnpm --filter @Hop/worker generate:migrations +-- Regenerate with: pnpm --filter @hop/worker generate:migrations CREATE TABLE users ( id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), diff --git a/apps/worker/migrations/0002_token_version.sql b/apps/worker/migrations/0002_token_version.sql index 632232d..90c5219 100644 --- a/apps/worker/migrations/0002_token_version.sql +++ b/apps/worker/migrations/0002_token_version.sql @@ -1,4 +1,4 @@ -- DO NOT EDIT. Generated from src/lib/migrations.ts (getMigrations("")). --- Regenerate with: pnpm --filter @Hop/worker generate:migrations +-- Regenerate with: pnpm --filter @hop/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 e96d275..59ad5f5 100644 --- a/apps/worker/package.json +++ b/apps/worker/package.json @@ -1,5 +1,5 @@ { - "name": "@Hop/worker", + "name": "@hop/worker", "version": "1.0.0", "private": true, "type": "module", diff --git a/apps/worker/scripts/generate-migrations.ts b/apps/worker/scripts/generate-migrations.ts index b273fac..ec35c91 100644 --- a/apps/worker/scripts/generate-migrations.ts +++ b/apps/worker/scripts/generate-migrations.ts @@ -16,7 +16,7 @@ const migrationsDir = join(here, '..', 'migrations'); const HEADER = '-- DO NOT EDIT. Generated from src/lib/migrations.ts (getMigrations("")).\n' + - '-- Regenerate with: pnpm --filter @Hop/worker generate:migrations\n'; + '-- Regenerate with: pnpm --filter @hop/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 diff --git a/apps/worker/src/lib/smtp.ts b/apps/worker/src/lib/smtp.ts index 61de968..0fad715 100644 --- a/apps/worker/src/lib/smtp.ts +++ b/apps/worker/src/lib/smtp.ts @@ -61,7 +61,7 @@ export async function sendViaSMTP( await session.expect(220); // Send initial EHLO - await session.cmd('EHLO Hop'); + await session.cmd('EHLO hop'); await session.expect(250); // Upgrade to TLS for non-implicit-TLS connections @@ -117,7 +117,7 @@ class SmtpSession { this.buf = ''; // discard any buffered plain-text data // Re-issue EHLO on the now-TLS channel - await this.cmd('EHLO Hop'); + await this.cmd('EHLO hop'); await this.expect(250); } @@ -144,7 +144,7 @@ class SmtpSession { await this.expect(354); const date = new Date().toUTCString(); - const msgId = `<${Date.now()}.${Math.random().toString(36).slice(2)}@Hop>`; + const msgId = `<${Date.now()}.${Math.random().toString(36).slice(2)}@hop>`; // Encode body as base64 — safe for all character sets without 8BITMIME negotiation const b64Body = wrapBase64(encodeUtf8Base64(html)); diff --git a/apps/worker/tsconfig.json b/apps/worker/tsconfig.json index e654b02..cdb3142 100644 --- a/apps/worker/tsconfig.json +++ b/apps/worker/tsconfig.json @@ -13,7 +13,7 @@ "outDir": "./dist", "rootDir": "./src", "paths": { - "@Hop/shared": ["../../packages/shared/src/index.ts"] + "@hop/shared": ["../../packages/shared/src/index.ts"] } }, "include": ["src/**/*"], diff --git a/apps/worker/wrangler.toml b/apps/worker/wrangler.toml index 0b4ba8b..b52f328 100644 --- a/apps/worker/wrangler.toml +++ b/apps/worker/wrangler.toml @@ -1,4 +1,4 @@ -name = "Hop" +name = "hop" main = "src/index.ts" compatibility_date = "2025-04-01" account_id = "CLOUDFLARE_ACCOUNT_ID_PLACEHOLDER" diff --git a/turbo.json b/turbo.json index 885e80a..c122e6c 100644 --- a/turbo.json +++ b/turbo.json @@ -17,7 +17,7 @@ "cache": false }, "deploy": { - "dependsOn": ["@Hop/web#build", "build"], + "dependsOn": ["@hop/web#build", "build"], "cache": false, "passThroughEnv": ["CLOUDFLARE_API_TOKEN"] } From e96f0e0da85eb62e8ae8b678faa5173899f29a6f Mon Sep 17 00:00:00 2001 From: mapxn <16299874+mapxn@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:00:50 +0800 Subject: [PATCH 2/2] =?UTF-8?q?feat:=20=E9=BB=98=E8=AE=A4=20TABLE=5FPREFIX?= =?UTF-8?q?=20=E4=BB=8E=20sl=20=E6=94=B9=E4=B8=BA=20hop?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 按用户要求把代码缺省的表前缀从 sl 改成 hop(三态语义不变: undefined → 默认 hop、'' → 无前缀、其他值原样保留大小写)。 - apps/worker/src/lib/table-prefix.ts: DEFAULT_TABLE_PREFIX 'sl' -> 'hop' - 同步默认值断言与用例名:table-prefix.test.ts、migrations-runner.test.ts、 test-deploy-checks.mjs(resolve-table-prefix / worker-table-prefix 三态) - 同步脚本注释与文档中的默认值说明:d1-prepare-migrations.sh、 worker-table-prefix.sh、resolve-table-prefix.mjs、verify-deployment.sh、 README.md、README.zh-CN.md、CLAUDE.md(含升级提示:旧安装需显式 TABLE_PREFIX=sl) 生产部署的 TABLE_PREFIX(明文变量 SL)与线上 D1 数据不受影响,未做任何数据迁移。 --- .github/scripts/d1-prepare-migrations.sh | 4 ++-- .github/scripts/resolve-table-prefix.mjs | 2 +- .github/scripts/test-deploy-checks.mjs | 8 ++++---- .github/scripts/verify-deployment.sh | 2 +- .github/scripts/worker-table-prefix.sh | 2 +- CLAUDE.md | 2 +- README.md | 9 +++++---- README.zh-CN.md | 8 ++++---- apps/worker/src/lib/table-prefix.ts | 4 ++-- apps/worker/test/migrations-runner.test.ts | 4 ++-- apps/worker/test/table-prefix.test.ts | 12 ++++++------ 11 files changed, 29 insertions(+), 28 deletions(-) diff --git a/.github/scripts/d1-prepare-migrations.sh b/.github/scripts/d1-prepare-migrations.sh index 8c9515d..a33ae51 100755 --- a/.github/scripts/d1-prepare-migrations.sh +++ b/.github/scripts/d1-prepare-migrations.sh @@ -16,7 +16,7 @@ # prefixed — TABLE_PREFIX is in use; migrations/*.sql are not prefix-aware, # so d1-prefixed-migrations.sh applies the setup-route migrations # -# Three-state TABLE_PREFIX (unset → 'sl', '' → no prefix, other → as-is) is +# Three-state TABLE_PREFIX (unset → 'hop', '' → no prefix, other → as-is) is # resolved by the deploy workflow before this script runs; a silent switch # (database already initialised under a different prefix) aborts with an error. # @@ -33,7 +33,7 @@ if [[ "$location" != remote && "$location" != local ]]; then fi # Three-state resolution: the deploy workflow already resolves vars.TABLE_PREFIX -# (none → '', unset/empty → 'sl') before calling this script. When invoked +# (none → '', unset/empty → 'hop') before calling this script. When invoked # directly with TABLE_PREFIX unset, resolve it to the project default. # `${TABLE_PREFIX+x}` is empty when unset and 'x' when set (even to ''), which # is portable across bash 3.x and 5.x. diff --git a/.github/scripts/resolve-table-prefix.mjs b/.github/scripts/resolve-table-prefix.mjs index dd36f17..9b3f69c 100644 --- a/.github/scripts/resolve-table-prefix.mjs +++ b/.github/scripts/resolve-table-prefix.mjs @@ -3,7 +3,7 @@ // GitHub Actions `vars.TABLE_PREFIX` cannot distinguish "unset" from "empty", // so the deploy workflow uses a reserved word to preserve the three runtime // states: -// unset / empty → DEFAULT_TABLE_PREFIX ('sl') +// unset / empty → DEFAULT_TABLE_PREFIX ('hop') // 'none' → '' (explicit no prefix; the deployer accepts the // table-collision risk) // anything else → as-is diff --git a/.github/scripts/test-deploy-checks.mjs b/.github/scripts/test-deploy-checks.mjs index b2e2486..58a8141 100644 --- a/.github/scripts/test-deploy-checks.mjs +++ b/.github/scripts/test-deploy-checks.mjs @@ -159,8 +159,8 @@ esac // ─── CI 三态解析(none 约定)───────────────────────────────────────────────── for (const scenario of [ - { name: 'vars 未设 → 默认 sl', env: undefined, expected: 'sl' }, - { name: 'vars 为空 → 默认 sl', env: '', expected: 'sl' }, + { name: 'vars 未设 → 默认 hop', env: undefined, expected: 'hop' }, + { name: 'vars 为空 → 默认 hop', env: '', expected: 'hop' }, { name: 'vars 为保留字 none → 空字符串', env: 'none', expected: '' }, { name: 'vars 为其他值 → 原样(含大小写)', env: 'SL', expected: 'SL' }, ]) { @@ -184,7 +184,7 @@ for (const scenario of [ }); } -test('worker-table-prefix.sh:未设置绑定 → 默认 sl', (t) => { +test('worker-table-prefix.sh:未设置绑定 → 默认 hop', (t) => { const f = fixture(t); writeFileSync( join(f.dir, 'pnpm'), @@ -202,5 +202,5 @@ esac [join(scripts, 'worker-table-prefix.sh'), 'v1'], { env: f.env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }, ); - assert.equal(out, 'sl'); + assert.equal(out, 'hop'); }); diff --git a/.github/scripts/verify-deployment.sh b/.github/scripts/verify-deployment.sh index 0f328e2..23b7701 100644 --- a/.github/scripts/verify-deployment.sh +++ b/.github/scripts/verify-deployment.sh @@ -42,7 +42,7 @@ done live="$(bash "$here/worker-table-prefix.sh" "$version")" live="${live//[^A-Za-z0-9_]/}" # worker-table-prefix.sh already maps an unset Worker binding to the default -# 'sl'; compare literally (case-sensitive) so e.g. production `SL` is never +# 'hop'; compare literally (case-sensitive) so e.g. production `SL` is never # folded into `sl` and reported as a false match. expected="${TABLE_PREFIX:-}" if [[ "$live" != "$expected" ]]; then diff --git a/.github/scripts/worker-table-prefix.sh b/.github/scripts/worker-table-prefix.sh index 54f284a..b0cba30 100644 --- a/.github/scripts/worker-table-prefix.sh +++ b/.github/scripts/worker-table-prefix.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash # Prints the effective TABLE_PREFIX of a deployed Worker version. When the -# Worker has no TABLE_PREFIX binding, the project default ('sl') is printed — +# Worker has no TABLE_PREFIX binding, the project default ('hop') is printed — # matching the runtime three-state resolution in src/lib/table-prefix.ts. # Run from apps/worker (needs wrangler.toml with real IDs injected). # diff --git a/CLAUDE.md b/CLAUDE.md index fbfefba..6e6520a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -229,7 +229,7 @@ All set via the Cloudflare dashboard (Variables and Secrets). `keep_vars = true` | `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) | -| `TABLE_PREFIX` | No | Three-state prefix for all D1 table names. Unset → default `sl` (`sl_users`, `sl_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 `sl`). A silent switch (database initialised under a different prefix) aborts setup/migrations with an error. | +| `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 e606287..8284003 100644 --- a/README.md +++ b/README.md @@ -83,7 +83,7 @@ Go to [Cloudflare dashboard](https://dash.cloudflare.com) → **Workers & Pages | `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) | -| `TABLE_PREFIX` | Variable | No | Three-state table prefix. Unset → default `sl` (`sl_users`, `sl_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. | +| `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. | > `keep_vars = true` is set in `wrangler.toml`, so deployments will never overwrite these values. @@ -110,7 +110,7 @@ and prints the planned migrations in the log. Migrations must stay backward comp only add tables, indexes or columns — never drop, rename or rewrite existing data. GitHub Actions cannot distinguish an unset `vars.TABLE_PREFIX` from an empty one, so -the deploy workflow resolves it to the three runtime states: **unset or empty → `sl`** +the deploy workflow resolves it to the three runtime states: **unset or empty → `hop`** (the default), **`none` → explicit empty string** (no prefix), **anything else → as-is**. > **Upgrade warning** — a legacy deployment that never set a prefix used unprefixed @@ -118,7 +118,8 @@ the deploy workflow resolves it to the three runtime states: **unset or empty > under, setup and migrations **abort with an error** instead of silently switching to > a different (usually empty) set of tables. Configure `TABLE_PREFIX` to its previous > value (`TABLE_PREFIX=''`, or `TABLE_PREFIX=none` in CI, to keep unprefixed tables) -> before upgrading. +> before upgrading. Installations created before the `sl` → `hop` default change that +> relied on the bare default (`sl_users`, …) must set `TABLE_PREFIX=sl` explicitly. When using a prefix, set `TABLE_PREFIX` under the GitHub **production environment → Variables** to exactly the same value as the Worker's `TABLE_PREFIX` **plain-text @@ -303,7 +304,7 @@ All variables and secrets are managed in the **Cloudflare dashboard** (Workers & | `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) | -| `TABLE_PREFIX` | Var | No | Three-state prefix for all D1 table names. Unset → default `sl` (`sl_users`, `sl_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. | +| `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` | | `SETUP_SECRET` | Secret | Yes | Secret path for triggering DB migrations via HTTP | diff --git a/README.zh-CN.md b/README.zh-CN.md index a0a9cde..b54b46d 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -84,7 +84,7 @@ | `APP_NAME` | Variable | 是 | `Hop` — 默认应用名称,可在管理界面覆盖 | | `RP_ID` | Variable | 是 | `yourdomain.com` — WebAuthn 依赖方 ID(仅域名) | | `APP_ORIGIN` | Variable | 是 | `https://yourdomain.com` — WebAuthn 来源(完整 URL) | -| `TABLE_PREFIX` | Variable | 否 | 三态表前缀。未配置 → 默认 `sl`(`sl_users`、`sl_links` 等);配置自定义值 → 该值(保留大小写,剔除 `[^a-zA-Z0-9_]`);显式配置为空字符串 → 无前缀(部署者自担撞表风险)。须与 GitHub 中的 `TABLE_PREFIX` 变量一致(第 3 步)。必须在**首次** setup 前设置,一旦有数据后不得更改。 | +| `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。 | > `wrangler.toml` 中设置了 `keep_vars = true`,因此部署不会覆盖这些值。 @@ -110,9 +110,9 @@ GitHub Actions 会在部署代码**之前**自动执行迁移:无前缀时仍 `apps/worker/src/lib/migrations.ts`,按 `__schema_migrations` 跳过已执行项, 并在日志中打印待执行计划。迁移必须向后兼容,只添加表、索引或列,不删除、重命名或修改现有数据。 -GitHub Actions 无法区分「未设置的 `vars.TABLE_PREFIX`」与「空字符串」,因此部署脚本按三态约定解析:**未设置或为空 → 默认 `sl`**;**保留字 `none` → 显式空字符串**(无前缀);**其他值 → 原样使用**。 +GitHub Actions 无法区分「未设置的 `vars.TABLE_PREFIX`」与「空字符串」,因此部署脚本按三态约定解析:**未设置或为空 → 默认 `hop`**;**保留字 `none` → 显式空字符串**(无前缀);**其他值 → 原样使用**。 -> **升级警告** — 从未配置过前缀的旧部署使用无前缀表。若解析出的前缀与库中已初始化的前缀不一致,setup 与迁移会**中止报错**,而不是静默切换到另一套(通常是空的)表。升级前请先把 `TABLE_PREFIX` 配成原值(保持无前缀则配置 `TABLE_PREFIX=''`,CI 中为 `TABLE_PREFIX=none`)。 +> **升级警告** — 从未配置过前缀的旧部署使用无前缀表。若解析出的前缀与库中已初始化的前缀不一致,setup 与迁移会**中止报错**,而不是静默切换到另一套(通常是空的)表。升级前请先把 `TABLE_PREFIX` 配成原值(保持无前缀则配置 `TABLE_PREFIX=''`,CI 中为 `TABLE_PREFIX=none`)。在 `sl` → `hop` 默认值变更前依赖默认前缀(`sl_users` 等)的部署,需显式配置 `TABLE_PREFIX=sl`。 使用前缀时,在 GitHub 的 **production environment → Variables** 中设置 `TABLE_PREFIX`,与 Cloudflare Worker 的同名**明文变量**完全一致(例如 `SL`,仅字母、数字和下划线)。 @@ -288,7 +288,7 @@ GET /:slug → 302 跳转到目标 URL | `APP_NAME` | 变量 | 是 | 默认应用名称;可在管理界面覆盖 | | `RP_ID` | 变量 | 是 | WebAuthn 依赖方 ID(不含协议的域名) | | `APP_ORIGIN` | 变量 | 是 | WebAuthn 来源(完整 URL) | -| `TABLE_PREFIX` | 变量 | 否 | 所有 D1 表名的三态前缀。未配置 → 默认 `sl`(`sl_users`、`sl_links` 等);自定义值 → 该值(保留大小写);显式空 → 无前缀。在第一次迁移前设置一次 — 之后更改需手动重命名所有表。只使用字母数字和下划线字符。 | +| `TABLE_PREFIX` | 变量 | 否 | 所有 D1 表名的三态前缀。未配置 → 默认 `hop`(`hop_users`、`hop_links` 等);自定义值 → 该值(保留大小写);显式空 → 无前缀。在第一次迁移前设置一次 — 之后更改需手动重命名所有表。只使用字母数字和下划线字符。 | | `JWT_SECRET` | 密钥 | 是 | HS256 签名密钥,≥ 32 字符 | | `TOTP_ENCRYPTION_KEY` | 密钥 | 是 | 来自 `openssl rand -hex 32` 的十六进制字符串 | | `SETUP_SECRET` | 密钥 | 是 | 通过 HTTP 触发数据库迁移的密钥路径 | diff --git a/apps/worker/src/lib/table-prefix.ts b/apps/worker/src/lib/table-prefix.ts index 3b1e404..ac3d275 100644 --- a/apps/worker/src/lib/table-prefix.ts +++ b/apps/worker/src/lib/table-prefix.ts @@ -2,7 +2,7 @@ // // Three states, distinguished at the call site by whether TABLE_PREFIX is // `undefined` versus the empty string: -// undefined → DEFAULT_TABLE_PREFIX ('sl') +// undefined → DEFAULT_TABLE_PREFIX ('hop') // '' → '' (no prefix — the deployer accepts the table-collision risk) // any other → the value with [^a-zA-Z0-9_] stripped, case preserved // @@ -10,7 +10,7 @@ // .github/scripts/d1-migrations.mjs (through migrations.ts) via Node's built-in // TypeScript type stripping. -export const DEFAULT_TABLE_PREFIX = 'sl'; +export const DEFAULT_TABLE_PREFIX = 'hop'; // Three-state resolution of a raw TABLE_PREFIX value. export function resolveTablePrefix(raw: string | undefined): string { diff --git a/apps/worker/test/migrations-runner.test.ts b/apps/worker/test/migrations-runner.test.ts index 8473fc3..d666272 100644 --- a/apps/worker/test/migrations-runner.test.ts +++ b/apps/worker/test/migrations-runner.test.ts @@ -27,13 +27,13 @@ function initializedDb(prefix: string): D1Mock { return db; } -test('runMigrations 返回实际生效前缀(未配置 → sl)', async () => { +test('runMigrations 返回实际生效前缀(未配置 → hop)', async () => { const db = new D1Mock(false); const result = await runMigrations({ DB: db as unknown as never, TABLE_PREFIX: undefined, }); - assert.equal(result.prefix, 'sl'); + assert.equal(result.prefix, 'hop'); assert.deepEqual( result.migrations.map((m) => [m.name, m.status]), [ diff --git a/apps/worker/test/table-prefix.test.ts b/apps/worker/test/table-prefix.test.ts index 915994b..d54abd8 100644 --- a/apps/worker/test/table-prefix.test.ts +++ b/apps/worker/test/table-prefix.test.ts @@ -8,12 +8,12 @@ import { resolveTablePrefix, } from '../src/lib/table-prefix.ts'; -test('默认前缀常量是 sl', () => { - assert.equal(DEFAULT_TABLE_PREFIX, 'sl'); +test('默认前缀常量是 hop', () => { + assert.equal(DEFAULT_TABLE_PREFIX, 'hop'); }); -test('三态解析:未配置(undefined)→ 默认 sl', () => { - assert.equal(resolveTablePrefix(undefined), 'sl'); +test('三态解析:未配置(undefined)→ 默认 hop', () => { + assert.equal(resolveTablePrefix(undefined), 'hop'); }); test('三态解析:显式空字符串 → 无前缀', () => { @@ -41,8 +41,8 @@ test('tbl 在表名前补下划线,无前缀则原样返回', () => { }); test('db.ts 的 tbl(env, name) 走同一三态解析', () => { - assert.equal(tbl({ TABLE_PREFIX: undefined }, 'users'), 'sl_users'); - assert.equal(tbl({}, 'users'), 'sl_users'); + assert.equal(tbl({ TABLE_PREFIX: undefined }, 'users'), 'hop_users'); + assert.equal(tbl({}, 'users'), 'hop_users'); assert.equal(tbl({ TABLE_PREFIX: '' }, 'users'), 'users'); assert.equal(tbl({ TABLE_PREFIX: 'SL' }, 'users'), 'SL_users'); });