Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ shortlink/
│ │ │ │ ├── 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 # POST /setup — HTTP-triggered DB migration (schema_v1 + schema_v2)
│ │ │ │ └── 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/
Expand All @@ -105,6 +105,7 @@ shortlink/
│ │ │ ├── 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)
Expand Down Expand Up @@ -166,7 +167,7 @@ Stored AES-256-GCM encrypted in D1. The encryption key (`TOTP_ENCRYPTION_KEY`) i
| `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) | 900s |
| `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 |
Expand Down Expand Up @@ -243,10 +244,12 @@ Two files in `apps/worker/migrations/`:
- `0002_token_version.sql` — adds `users.token_version` for session revocation

**HTTP setup route (production):**
`POST /setup` with `X-Setup-Secret` header runs migrations embedded in `routes/setup.ts`. Two migrations:
`POST /api/setup` (legacy alias `/setup`) with a JSON body `{"secret": "<SETUP_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"`.

---
Expand All @@ -260,7 +263,7 @@ Re-visiting the setup URL is safe — already-applied migrations return `"skippe
- 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}`); secret passed via header and compared in constant time
- 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
Expand Down
29 changes: 23 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,13 +108,15 @@ it as a secret, and do not change it once data exists. The GitHub `APP_URL` vari
point at the production URL. `CLOUDFLARE_API_TOKEN` needs edit access to the D1 database
and edit/version-read access to the Worker.

You no longer need to call `/setup` after each deploy. For manual deployments or
emergencies it can still be triggered with a `POST` request carrying the setup secret in
a header (it is no longer accepted in the URL):
You no longer need to call the setup endpoint after each deploy. For manual
deployments or emergencies it can still be triggered with a `POST` request carrying the
setup secret in a JSON body (the legacy `X-Setup-Secret` header still works, and the
secret is no longer accepted in the URL):

```
curl -X POST https://your-worker.workers.dev/setup \
-H "X-Setup-Secret: <SETUP_SECRET>"
curl -X POST https://your-worker.workers.dev/api/setup \
-H "Content-Type: application/json" \
-d '{"secret": "<SETUP_SECRET>"}'
```

Response on success:
Expand All @@ -126,7 +128,13 @@ Response on success:
}
```

Re-running it is safe — already-applied migrations return `"skipped"`.
Re-running it is safe — already-applied migrations return `"skipped"`. The endpoint is
rate-limited to 3 attempts per IP per 10 minutes (once exceeded it returns `429` with a
`Retry-After` header). `GET /api/setup/state` reports `{ "enabled": true | false }` based
on the `setup_page_enabled` setting (defaults to enabled when unset); it only hides the
setup page, it does not disable the `POST` migration channel. When logged in as an admin,
migrations can also be run from the admin panel via `POST /api/admin/setup` — no setup
secret needed, not IP rate-limited, and each run is written to the audit log.

After deploying, the workflow first confirms through the Cloudflare API that the uploaded
version serves 100% of production traffic, then probes the public URL. A `403` carrying
Expand Down Expand Up @@ -240,6 +248,14 @@ The Vite dev server proxies `/api` requests to `:8787` automatically.
| DELETE | `/api/admin/links/:id` | Delete any link |
| GET | `/api/admin/settings` | Get global settings |
| PUT | `/api/admin/settings` | Update global settings |
| POST | `/api/admin/setup` | Run schema migrations as admin (no setup secret; writes an audit log) |

### Setup (unauthenticated)

| Method | Path | Description |
|---|---|---|
| GET | `/api/setup/state` | Public — `{ "enabled": true \| false }` from `setup_page_enabled` |
| POST | `/api/setup` | Run schema migrations; JSON body `{"secret": "<SETUP_SECRET>"}` (legacy `X-Setup-Secret` header also works), 3 attempts / IP / 10 min |

### Miscellaneous

Expand Down Expand Up @@ -289,6 +305,7 @@ All variables and secrets are managed in the **Cloudflare dashboard** (Workers &
| `smtp_from` | email address | Sender address, e.g. `noreply@example.com` |
| `smtp_user` | string | SMTP username (leave blank for unauthenticated relay) |
| `smtp_pass` | string | SMTP password (stored in D1) |
| `setup_page_enabled` | `0` / `1` | Show (`1`) or hide (`0`) the setup page; only affects page visibility, never the `POST /api/setup` migration channel |

---

Expand Down
24 changes: 19 additions & 5 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,12 +107,13 @@ GitHub Actions 会在部署代码**之前**自动执行迁移:无前缀时仍
不要把它设为 Secret,也不要在已有数据后更换前缀。GitHub 中的 `APP_URL` 也必须指向生产地址。
现有 `CLOUDFLARE_API_TOKEN` 需要有目标 D1 的编辑权限和 Worker 的编辑/版本读取权限。

无需在每次部署后调用 `/setup`。手动部署或应急操作仍可通过 `POST` 请求触发,
密钥放在请求头中(不再通过 URL 传递):
无需在每次部署后调用 setup 接口。手动部署或应急操作仍可通过 `POST` 请求触发,
密钥放在 JSON body 中(旧的 `X-Setup-Secret` 请求头仍兼容,密钥不再通过 URL 传递):

```
curl -X POST https://your-worker.workers.dev/setup \
-H "X-Setup-Secret: <SETUP_SECRET>"
curl -X POST https://your-worker.workers.dev/api/setup \
-H "Content-Type: application/json" \
-d '{"secret": "<SETUP_SECRET>"}'
```

成功响应:
Expand All @@ -124,7 +125,11 @@ curl -X POST https://your-worker.workers.dev/setup \
}
```

重复调用是安全的,已执行的迁移会返回 `"skipped"`。自动部署不需要手动调用。
重复调用是安全的,已执行的迁移会返回 `"skipped"`。该接口按 IP 限流为每 10 分钟 3 次
(超限返回 `429` 并带 `Retry-After` 头)。`GET /api/setup/state` 返回
`{ "enabled": true | false }`,反映 `setup_page_enabled` 设置(未设置时默认启用),
它只隐藏 setup 页面、不会关闭 `POST` 迁移通道。以管理员身份登录后,也可在管理面板
通过 `POST /api/admin/setup` 触发迁移 — 无需 setup 密钥、不受 IP 限流,且每次执行都会写入审计日志。
部署后还会通过 Cloudflare API 核对本次上传的版本承载 100% 流量,再检查公开 URL。
公开 URL 返回带 `cf-mitigated: challenge` 的 403 时仅警告(HTTP/数据库检查未能验证),
其余非 2xx 或错误的 JSON 均失败;无需关闭 Bot Fight Mode。
Expand Down Expand Up @@ -235,6 +240,14 @@ Vite 开发服务器会自动将 `/api` 请求代理到 `:8787`。
| DELETE | `/api/admin/links/:id` | 删除任意链接 |
| GET | `/api/admin/settings` | 获取全局设置 |
| PUT | `/api/admin/settings` | 更新全局设置 |
| POST | `/api/admin/setup` | 以管理员身份执行数据库迁移(无需 setup 密钥;写入审计日志) |

### Setup(无需认证)

| 方法 | 路径 | 描述 |
|---|---|---|
| GET | `/api/setup/state` | 公开接口 — 根据 `setup_page_enabled` 返回 `{ "enabled": true \| false }` |
| POST | `/api/setup` | 执行数据库迁移;JSON body `{"secret": "<SETUP_SECRET>"}`(旧的 `X-Setup-Secret` 请求头仍兼容),每 IP 每 10 分钟限 3 次 |

### 其他

Expand Down Expand Up @@ -284,6 +297,7 @@ GET /:slug → 302 跳转到目标 URL
| `smtp_from` | 邮件地址 | 发件人地址,例如 `noreply@example.com` |
| `smtp_user` | 字符串 | SMTP 用户名(留空则使用未认证中继) |
| `smtp_pass` | 字符串 | SMTP 密码(存储在 D1 中) |
| `setup_page_enabled` | `0` / `1` | 显示(`1`)或隐藏(`0`)setup 页面;只影响页面可见性,绝不关闭 `POST /api/setup` 迁移通道 |

---

Expand Down
3 changes: 3 additions & 0 deletions apps/worker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@ app.route('/api/analytics', analyticsRoutes);
app.route('/api/admin', adminRoutes);

// ─── Setup / migration endpoint ───────────────────────────────────────────────
// Mounted at /api/setup to match the rest of the public API; /setup is kept as a
// backward-compatible alias for callers that predate the /api prefix.
app.route('/api/setup', setupRoutes);
app.route('/setup', setupRoutes);

// ─── Health check ─────────────────────────────────────────────────────────────
Expand Down
44 changes: 32 additions & 12 deletions apps/worker/src/lib/kv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,14 +153,16 @@ export async function deletePending2fa(
// the limit before writes settle. A Cloudflare WAF rate-limit rule is the primary
// enforcement layer; this provides a defence-in-depth best-effort guard.

// Fixed-window counter. Returns true (allowed) unless the key is already at
// `limit`; records the attempt by incrementing the stored count.
async function fixedWindowIncrement(
// Fixed-window counter. Records the attempt by incrementing the stored count,
// then reports whether it is still within `limit`. The detailed variant also
// returns how many seconds remain in the current window so callers can send an
// exact Retry-After header.
async function fixedWindowIncrementWithRetry(
kv: KVNamespace,
key: string,
limit: number,
windowSec: number,
): Promise<boolean> {
): Promise<{ allowed: boolean; retryAfter: number }> {
const current = await kv.get(key);
const now = Math.floor(Date.now() / 1000);

Expand All @@ -172,7 +174,7 @@ async function fixedWindowIncrement(
expirationTtl: windowSec,
},
);
return true;
return { allowed: true, retryAfter: 0 };
}

let entry: { count: number; windowEnd: number };
Expand All @@ -186,17 +188,33 @@ async function fixedWindowIncrement(
expirationTtl: windowSec,
},
);
return true;
return { allowed: true, retryAfter: 0 };
}

if (entry.count >= limit) return false;
if (entry.count >= limit) {
return {
allowed: false,
retryAfter: Math.max(entry.windowEnd - now, 0),
};
}
const remaining = Math.max(entry.windowEnd - now, 1);
await kv.put(
key,
JSON.stringify({ count: entry.count + 1, windowEnd: entry.windowEnd }),
{ expirationTtl: remaining },
);
return true;
return { allowed: true, retryAfter: 0 };
}

// Boolean convenience wrapper for callers that only need allow/deny.
async function fixedWindowIncrement(
kv: KVNamespace,
key: string,
limit: number,
windowSec: number,
): Promise<boolean> {
return (await fixedWindowIncrementWithRetry(kv, key, limit, windowSec))
.allowed;
}

// BE-S6: Rate limit login on two dimensions — email (10/15min) and IP (20/15min).
Expand Down Expand Up @@ -242,13 +260,15 @@ export async function checkForgotPasswordIpRateLimit(
return fixedWindowIncrement(kv, KV_PREFIX.forgotPasswordIp(ip), 10, 3600);
}

// BE-S5: IP rate limit for the setup/migration endpoint (5/15min) — prevents
// online brute-forcing of the setup secret.
// BE-S5: IP rate limit for the setup/migration endpoint (3/10min) — prevents
// online brute-forcing of the setup secret. Returns whether the attempt is
// allowed and, when not, how many seconds remain in the window so the caller
// can send an exact Retry-After header.
export async function checkSetupRateLimit(
kv: KVNamespace,
ip: string,
): Promise<boolean> {
return fixedWindowIncrement(kv, KV_PREFIX.setupRate(ip), 5, 900);
): Promise<{ allowed: boolean; retryAfter: number }> {
return fixedWindowIncrementWithRetry(kv, KV_PREFIX.setupRate(ip), 3, 600);
}

// ─── 2FA attempt tracking (C2: max 5 per pending token) ──────────────────────
Expand Down
78 changes: 78 additions & 0 deletions apps/worker/src/lib/migrations-runner.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import type { Env } from '../types.js';
import {
createMigrationsTableSql,
getMigrations,
migrationsTable,
} from './migrations.js';

// Shared schema-migration execution, parameterised by TABLE_PREFIX. Both the
// secret-keyed HTTP endpoint (routes/setup.ts → POST /api/setup) and the
// admin-session endpoint (routes/admin.ts → POST /api/admin/setup) call this so
// the two stay byte-compatible.

export interface MigrationResult {
name: string;
status: 'applied' | 'skipped' | 'error';
error?: string;
}

export interface RunMigrationsResult {
migrations: MigrationResult[];
}

// D1's exec() only processes the first line of a multi-line string.
// Strip SQL line comments and collapse all whitespace to a single line.
function toSingleLine(sql: string): string {
return sql
.split('\n')
.map((line) => {
const idx = line.indexOf('--');
return idx >= 0 ? line.slice(0, idx) : line;
})
.join(' ')
.replace(/\s+/g, ' ')
.trim();
}

// Applies every migration in getMigrations(prefix) not yet recorded in
// `${prefix}schema_migrations`, stopping at the first error (which is reported
// inline rather than thrown, preserving the original setup-route semantics).
export async function runMigrations(
env: Pick<Env, 'DB' | 'TABLE_PREFIX'>,
): Promise<RunMigrationsResult> {
const prefix = env.TABLE_PREFIX ?? '';
const historyTable = migrationsTable(prefix);

// Use prepare().run() for single-statement DDL — avoids exec()'s newline limitation
await env.DB.prepare(createMigrationsTableSql(prefix)).run();

const { results } = await env.DB.prepare(
`SELECT name FROM ${historyTable}`,
).all<{ name: string }>();
const applied = new Set(results.map((r) => r.name));

const migrations: MigrationResult[] = [];

for (const migration of getMigrations(prefix)) {
if (applied.has(migration.name)) {
migrations.push({ name: migration.name, status: 'skipped' });
continue;
}
try {
await env.DB.exec(toSingleLine(migration.sql));
await env.DB.prepare(`INSERT INTO ${historyTable} (name) VALUES (?)`)
.bind(migration.name)
.run();
migrations.push({ name: migration.name, status: 'applied' });
} catch (err) {
migrations.push({
name: migration.name,
status: 'error',
error: String(err),
});
break;
}
}

return { migrations };
}
Loading
Loading