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
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`)验证配置是否可用。

---

## 许可证
Expand Down
35 changes: 33 additions & 2 deletions apps/worker/src/lib/email.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> {
const cached = await getCachedSetting(env.LINKS_KV, key);
Expand Down Expand Up @@ -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',
);
}
Expand All @@ -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',
);
}
Expand Down Expand Up @@ -160,3 +172,22 @@ export function otpEmailHtml(appName: string, code: string): string {
</html>
`.trim();
}

export function testEmailHtml(
appName: string,
sentAt: Date = new Date(),
): string {
const safeApp = escHtml(appName);
const safeTime = escHtml(sentAt.toISOString());
return `
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"></head>
<body style="font-family:sans-serif;max-width:480px;margin:40px auto;padding:0 16px">
<h2 style="color:#1a1a1a">${safeApp} — Test Email</h2>
<p style="color:#444;font-size:15px">这是一封测试邮件,说明邮件配置可用。</p>
<p style="color:#888;font-size:13px">Sent at ${safeTime}</p>
</body>
</html>
`.trim();
}
18 changes: 18 additions & 0 deletions apps/worker/src/lib/kv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 ───────────────────────────────────────────────────────────────
Expand Down Expand Up @@ -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(
Expand Down
83 changes: 82 additions & 1 deletion apps/worker/src/routes/admin.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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<string> {
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
// ─────────────────────────────────────────────────────────────────────────────
Expand Down Expand Up @@ -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
// ─────────────────────────────────────────────────────────────────────────────
Expand Down
Loading
Loading