diff --git a/CLAUDE.md b/CLAUDE.md index 3f435fc..813e659 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -277,7 +277,7 @@ Re-visiting the setup URL is safe — already-applied migrations return `"skippe ## Email Provider Architecture -Two providers are supported, switchable via the `email_provider` setting in the admin UI: +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` diff --git a/README.md b/README.md index 72b0d78..69ee63a 100644 --- a/README.md +++ b/README.md @@ -309,6 +309,8 @@ All variables and secrets are managed in the **Cloudflare dashboard** (Workers & | `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 | +After saving your email provider configuration, use **Send test email** (`POST /api/admin/email/test`) to verify it works. + --- ## License diff --git a/README.zh-CN.md b/README.zh-CN.md index 3b74f57..e172425 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -301,6 +301,8 @@ GET /:slug → 302 跳转到目标 URL | `smtp_pass` | 字符串 | SMTP 密码(存储在 D1 中) | | `setup_page_enabled` | `0` / `1` | 显示(`1`)或隐藏(`0`)setup 页面;只影响页面可见性,绝不关闭 `POST /api/setup` 迁移通道 | +保存邮件提供商配置后,可用「发送测试邮件」(`POST /api/admin/email/test`)验证配置是否可用。 + --- ## 许可证 diff --git a/apps/worker/src/lib/email.ts b/apps/worker/src/lib/email.ts index edc7add..7f72387 100644 --- a/apps/worker/src/lib/email.ts +++ b/apps/worker/src/lib/email.ts @@ -9,6 +9,18 @@ interface EmailPayload { html: string; } +// Thrown when the selected provider's required settings are missing. Callers +// distinguish this from an upstream send failure via `instanceof` rather than +// matching the message text — an SMTP server reply can itself contain the words +// "not configured" (e.g. "554 Server not configured for mail"), which a +// substring check would misclassify as a configuration error. +export class EmailConfigError extends Error { + constructor(message: string) { + super(message); + this.name = 'EmailConfigError'; + } +} + // Read a setting from KV cache → DB, then populate the cache on a miss. async function getSetting(env: Env, key: string): Promise { const cached = await getCachedSetting(env.LINKS_KV, key); @@ -40,7 +52,7 @@ export async function sendEmail( ]); if (!host || !from) { - throw new Error( + throw new EmailConfigError( 'SMTP is selected as email provider but smtp_host or smtp_from is not configured', ); } @@ -64,7 +76,7 @@ export async function sendEmail( ]); if (!apiKey || !fromDomain) { - throw new Error( + throw new EmailConfigError( 'Resend is selected as email provider but resend_api_key or email_from_domain is not configured in admin settings', ); } @@ -160,3 +172,22 @@ export function otpEmailHtml(appName: string, code: string): string { `.trim(); } + +export function testEmailHtml( + appName: string, + sentAt: Date = new Date(), +): string { + const safeApp = escHtml(appName); + const safeTime = escHtml(sentAt.toISOString()); + return ` + + + + +

${safeApp} — Test Email

+

这是一封测试邮件,说明邮件配置可用。

+

Sent at ${safeTime}

+ + + `.trim(); +} diff --git a/apps/worker/src/lib/kv.ts b/apps/worker/src/lib/kv.ts index a33cfc5..964049c 100644 --- a/apps/worker/src/lib/kv.ts +++ b/apps/worker/src/lib/kv.ts @@ -22,6 +22,8 @@ const KV_PREFIX = { jtiDeny: (jti: string) => `jti_deny:${jti}`, // R4-L4: TOTP confirm rate limiting per user totpConfirmAttempts: (userId: string) => `totp_confirm:${userId}`, + // BE-S6: Per-admin "send test email" rate limiting (5/10min) + testEmailRate: (adminId: string) => `test_email_rate:${adminId}`, }; // ─── Link cache ─────────────────────────────────────────────────────────────── @@ -271,6 +273,22 @@ export async function checkSetupRateLimit( return fixedWindowIncrementWithRetry(kv, KV_PREFIX.setupRate(ip), 3, 600); } +// BE-S6: Per-admin rate limit for the "send test email" endpoint (5/10min) — +// prevents an admin account from mail-bombing arbitrary addresses. 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 checkTestEmailRateLimit( + kv: KVNamespace, + adminId: string, +): Promise<{ allowed: boolean; retryAfter: number }> { + return fixedWindowIncrementWithRetry( + kv, + KV_PREFIX.testEmailRate(adminId), + 5, + 600, + ); +} + // ─── 2FA attempt tracking (C2: max 5 per pending token) ────────────────────── export async function increment2faAttempts( diff --git a/apps/worker/src/routes/admin.ts b/apps/worker/src/routes/admin.ts index 5f17f49..081f16a 100644 --- a/apps/worker/src/routes/admin.ts +++ b/apps/worker/src/routes/admin.ts @@ -1,7 +1,14 @@ import { Hono } from 'hono'; import { hashPassword } from '../lib/crypto.js'; import { isUniqueConstraintError, tbl } from '../lib/db.js'; -import { deleteCachedLink, deleteCachedSetting } from '../lib/kv.js'; +import { EmailConfigError, sendEmail, testEmailHtml } from '../lib/email.js'; +import { + checkTestEmailRateLimit, + deleteCachedLink, + deleteCachedSetting, + getCachedSetting, + setCachedSetting, +} from '../lib/kv.js'; import { runMigrations } from '../lib/migrations-runner.js'; import { parsePagination } from '../lib/params.js'; import { requireAdmin } from '../middleware/auth.js'; @@ -44,6 +51,18 @@ 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 // ───────────────────────────────────────────────────────────────────────────── @@ -502,6 +521,68 @@ admin.put('/settings', async (c) => { return c.json({ success: true }); }); +// ───────────────────────────────────────────────────────────────────────────── +// POST /api/admin/email/test +// ───────────────────────────────────────────────────────────────────────────── +// Sends a test email using the currently-saved provider configuration so an +// admin can verify it works. Rate-limited per admin and audited. +admin.post('/email/test', async (c) => { + const adminId = c.get('userId'); + const body = await c.req.json<{ to?: string }>().catch(() => null); + if (!body) return c.json({ error: 'Invalid JSON body' }, 400); + + const to = typeof body.to === 'string' ? body.to.trim() : ''; + if (!to || to.length > 254 || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(to)) { + return c.json({ error: 'Invalid email address' }, 400); + } + + // BE-S6: Rate limit per admin (5/10min) to stop an admin account from + // mail-bombing arbitrary addresses. Counted on every valid attempt. + const { allowed, retryAfter } = await checkTestEmailRateLimit( + c.env.LINKS_KV, + adminId, + ); + if (!allowed) { + return c.json( + { error: 'Too many test email attempts. Try again later.' }, + 429, + { 'Retry-After': String(retryAfter) }, + ); + } + + const appName = await getAppName(c.env); + + try { + await sendEmail(c.env, { + to, + subject: `${appName} Test Email`, + html: testEmailHtml(appName), + }); + } catch (err) { + if (err instanceof EmailConfigError) { + // Missing provider config — the message names the missing setting keys, + // never their values, so it is safe to surface verbatim. Match on the + // dedicated error type (not the message text) so an upstream SMTP reply + // that happens to contain "not configured" is still treated as a 502. + return c.json({ error: err.message }, 400); + } + // Upstream failure — log a redacted summary (never the error message, which + // can echo SMTP/credential details) and return a generic 502. + console.error( + JSON.stringify({ + level: 'error', + message: 'send test email failed', + requestId: c.get('requestId'), + }), + ); + return c.json({ error: 'Failed to send test email' }, 502); + } + + await auditLog(c.env, adminId, 'test_email', 'email', { to }); + + return c.json({ success: true }); +}); + // ───────────────────────────────────────────────────────────────────────────── // DELETE /api/admin/links/:id // ───────────────────────────────────────────────────────────────────────────── diff --git a/apps/worker/test/admin.test.ts b/apps/worker/test/admin.test.ts new file mode 100644 index 0000000..98e5997 --- /dev/null +++ b/apps/worker/test/admin.test.ts @@ -0,0 +1,205 @@ +// Admin "send test email" endpoint tests — POST /api/admin/email/test. +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { app } from '../src/index.ts'; +import { accessTokenFor, makeEnv, request, seedUser } from './helpers/app.ts'; + +const json = (body: unknown, headers: Record = {}) => ({ + method: 'POST', + headers: { 'Content-Type': 'application/json', ...headers }, + body: JSON.stringify(body), +}); + +async function seedAdmin(ctx: ReturnType): Promise { + await seedUser(ctx.db, { + id: 'a1', + email: 'admin@example.com', + username: 'admin', + role: 'admin', + isActive: 1, + tokenVersion: 0, + password: 'password-1', + }); + return accessTokenFor({ + id: 'a1', + email: 'admin@example.com', + role: 'admin', + tokenVersion: 0, + }); +} + +function configureResend(ctx: ReturnType): void { + ctx.db + .prepare("UPDATE settings SET value = ?1 WHERE key = 'resend_api_key'") + .bind('test-key') + .run(); + ctx.db + .prepare("UPDATE settings SET value = ?1 WHERE key = 'email_from_domain'") + .bind('example.com') + .run(); +} + +test('POST /api/admin/email/test: 未认证 401 / 非管理员 403', async () => { + const ctx = makeEnv(); + await seedUser(ctx.db, { + id: 'u1', + email: 'bob@example.com', + username: 'bob', + role: 'user', + isActive: 1, + tokenVersion: 0, + password: 'password-1', + }); + const userToken = await accessTokenFor({ + id: 'u1', + email: 'bob@example.com', + role: 'user', + tokenVersion: 0, + }); + + const noAuth = await request( + app, + '/api/admin/email/test', + json({ to: 'a@b.com' }), + ctx, + ); + assert.equal(noAuth.status, 401); + + const asUser = await request( + app, + '/api/admin/email/test', + json({ to: 'a@b.com' }, { Authorization: `Bearer ${userToken}` }), + ctx, + ); + assert.equal(asUser.status, 403); +}); + +test('POST /api/admin/email/test: 非法邮箱返回 400', async () => { + const ctx = makeEnv(); + const token = await seedAdmin(ctx); + + const cases: [unknown, string][] = [ + [undefined, '缺少 to'], + ['', '空字符串'], + ['not-an-email', '无 @'], + ['a@b', '无域名后缀'], + [`${'a'.repeat(250)}@example.com`, '长度超 254'], + ]; + for (const [to, label] of cases) { + const res = await request( + app, + '/api/admin/email/test', + json({ to }, { Authorization: `Bearer ${token}` }), + ctx, + ); + assert.equal(res.status, 400, `${label} 应返回 400`); + } +}); + +test('POST /api/admin/email/test: 配置缺失返回 400 且提示可读', async () => { + const ctx = makeEnv(); + const token = await seedAdmin(ctx); + + const res = await request( + app, + '/api/admin/email/test', + json({ to: 'user@example.com' }, { Authorization: `Bearer ${token}` }), + ctx, + ); + assert.equal(res.status, 400); + const body = await res.json(); + assert.match(body.error, /not configured/); + assert.doesNotMatch(body.error, /test-key/); +}); + +test('POST /api/admin/email/test: 上游失败返回 502 且不泄露上游响应', async (t) => { + const ctx = makeEnv(); + const token = await seedAdmin(ctx); + configureResend(ctx); + + const SECRET = 'SUPER-SECRET-UPSTREAM-BODY'; + const originalFetch = globalThis.fetch; + globalThis.fetch = async () => + new Response(JSON.stringify({ error: SECRET }), { status: 500 }); + t.after(() => { + globalThis.fetch = originalFetch; + }); + + const res = await request( + app, + '/api/admin/email/test', + json({ to: 'user@example.com' }, { Authorization: `Bearer ${token}` }), + ctx, + ); + assert.equal(res.status, 502); + const body = await res.json(); + assert.equal(body.error, 'Failed to send test email'); + assert.doesNotMatch(JSON.stringify(body), new RegExp(SECRET)); +}); + +test('POST /api/admin/email/test: 成功发送 200 并写审计日志', async (t) => { + const ctx = makeEnv(); + const token = await seedAdmin(ctx); + configureResend(ctx); + + const originalFetch = globalThis.fetch; + globalThis.fetch = async () => new Response('{"id":"ok"}', { status: 200 }); + t.after(() => { + globalThis.fetch = originalFetch; + }); + + const res = await request( + app, + '/api/admin/email/test', + json({ to: 'user@example.com' }, { Authorization: `Bearer ${token}` }), + ctx, + ); + assert.equal(res.status, 200); + assert.deepEqual(await res.json(), { success: true }); + + const row = ctx.db + .prepare( + `SELECT action, target_id, details FROM audit_logs WHERE action = 'test_email'`, + ) + .first<{ action: string; target_id: string; details: string }>(); + assert.ok(row, '应写入 test_email 审计日志'); + assert.equal(row?.target_id, 'email'); + assert.deepEqual(JSON.parse(row?.details ?? '{}'), { + to: 'user@example.com', + }); +}); + +test('POST /api/admin/email/test: 第 6 次限流 429 + Retry-After', async (t) => { + const ctx = makeEnv(); + const token = await seedAdmin(ctx); + configureResend(ctx); + + const originalFetch = globalThis.fetch; + globalThis.fetch = async () => new Response('{"id":"ok"}', { status: 200 }); + t.after(() => { + globalThis.fetch = originalFetch; + }); + + for (let i = 0; i < 5; i++) { + const res = await request( + app, + '/api/admin/email/test', + json({ to: 'user@example.com' }, { Authorization: `Bearer ${token}` }), + ctx, + ); + assert.equal(res.status, 200, `第 ${i + 1} 次应成功`); + } + + const blocked = await request( + app, + '/api/admin/email/test', + json({ to: 'user@example.com' }, { Authorization: `Bearer ${token}` }), + ctx, + ); + assert.equal(blocked.status, 429); + const retryAfter = Number(blocked.headers.get('Retry-After')); + assert.ok( + Number.isFinite(retryAfter) && retryAfter > 0, + 'Retry-After 应为正数', + ); +}); diff --git a/apps/worker/test/email.test.ts b/apps/worker/test/email.test.ts index 1b33c20..d3f8945 100644 --- a/apps/worker/test/email.test.ts +++ b/apps/worker/test/email.test.ts @@ -3,7 +3,7 @@ // details) must never appear in the error message. import assert from 'node:assert/strict'; import { test } from 'node:test'; -import { sendEmail } from '../src/lib/email.ts'; +import { EmailConfigError, sendEmail } from '../src/lib/email.ts'; import { makeEnv } from './helpers/app.ts'; const SECRET = 'SUPER-SECRET-UPSTREAM-BODY'; @@ -39,3 +39,41 @@ test('sendEmail: Resend 失败不把响应正文带进错误信息 (BE-R2)', asy }, ); }); + +test('sendEmail: Resend 配置缺失抛 EmailConfigError(非普通 Error)', async () => { + const ctx = makeEnv(); // default: resend with empty api_key / from_domain + + await assert.rejects( + () => + sendEmail(ctx.env, { + to: 'user@example.com', + subject: 'hi', + html: '

hi

', + }), + (err: Error) => { + assert.ok(err instanceof EmailConfigError, '应抛 EmailConfigError'); + return true; + }, + ); +}); + +test('sendEmail: SMTP 配置缺失抛 EmailConfigError(非普通 Error)', async () => { + const ctx = makeEnv(); + ctx.db + .prepare("UPDATE settings SET value = ?1 WHERE key = 'email_provider'") + .bind('smtp') + .run(); + + await assert.rejects( + () => + sendEmail(ctx.env, { + to: 'user@example.com', + subject: 'hi', + html: '

hi

', + }), + (err: Error) => { + assert.ok(err instanceof EmailConfigError, '应抛 EmailConfigError'); + return true; + }, + ); +});