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 apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"dev": "vite",
"build": "tsc --noEmit && vite build",
"typecheck": "tsc --noEmit",
"test": "node --test src/api/client.test.ts src/lib/utils.test.ts src/lib/apiErrorCodes.test.ts src/lib/setup.test.ts",
"test": "node --test src/api/client.test.ts src/lib/utils.test.ts src/lib/apiErrorCodes.test.ts src/lib/setup.test.ts src/lib/testEmail.test.ts",
"preview": "vite preview"
},
"dependencies": {
Expand Down
9 changes: 9 additions & 0 deletions apps/web/src/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -726,6 +726,15 @@ export const adminApi = {
// Runs the same schema-migration routine as POST /api/setup, keyed to the
// admin session (no setup secret required).
runSetup: () => request<SetupResult>('/admin/setup', { method: 'POST' }),
// Sends a test email through the currently saved email settings. The backend
// reports success as `{ success: true }`; failures carry the status code the
// UI maps to a readable message (400 config/address, 429 with Retry-After,
// 502 send failure).
sendTestEmail: (to: string) =>
request<{ success: boolean }>('/admin/email/test', {
method: 'POST',
body: JSON.stringify({ to }),
}),
};

// Re-export WebAuthn types used by auth API
Expand Down
12 changes: 12 additions & 0 deletions apps/web/src/i18n/locales/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,18 @@ export const en = {
runSetup: 'Check & Upgrade Database',
runSetupDesc:
'Run pending database migrations. Already-applied migrations are reported as skipped.',
sendTestEmail: 'Send Test Email',
testEmailRecipient: 'Recipient Email',
testEmailNote:
'The test uses the saved email settings. Save your changes first to test them.',
testEmailSuccess: 'Test email sent successfully',
testEmailErrorBadRequest:
'Invalid recipient or email not configured. Check the address and save your email settings.',
testEmailErrorTooManyRequests:
'Too many requests. Try again in {{seconds}}s.',
testEmailErrorSendFailed:
'Failed to send the test email. Check your email provider settings.',
testEmailErrorGeneric: 'Failed to send the test email. Please try again.',
},
toast: {
sessionExpired: 'Session expired. Please sign in again.',
Expand Down
9 changes: 9 additions & 0 deletions apps/web/src/i18n/locales/zh-CN.ts
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,15 @@ export const zhCN: Translations = {
setupPageDisabled: '已关闭',
runSetup: '检查并升级数据库',
runSetupDesc: '执行待处理的数据库迁移,已应用的迁移将显示为「已跳过」。',
sendTestEmail: '发送测试邮件',
testEmailRecipient: '收件地址',
testEmailNote: '测试使用已保存的邮件设置,修改后请先保存。',
testEmailSuccess: '测试邮件发送成功',
testEmailErrorBadRequest:
'收件地址无效或邮件未配置,请检查地址并保存邮件设置。',
testEmailErrorTooManyRequests: '请求过于频繁,请在 {{seconds}} 秒后重试。',
testEmailErrorSendFailed: '测试邮件发送失败,请检查邮件服务商配置。',
testEmailErrorGeneric: '测试邮件发送失败,请重试。',
},
toast: {
sessionExpired: '登录已过期,请重新登录。',
Expand Down
195 changes: 195 additions & 0 deletions apps/web/src/lib/testEmail.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
import assert from 'node:assert/strict';
import { afterEach, describe, test } from 'node:test';
import {
ApiRequestError,
adminApi,
SessionExpiredError,
} from '../api/client.ts';
import { en } from '../i18n/locales/en.ts';
import { zhCN } from '../i18n/locales/zh-CN.ts';
import { formatTestEmailError, resolveTestEmailError } from './testEmail.ts';

// Admin "send test email" frontend behaviour, pinned down with a stubbed fetch
// and pure helpers (same style as setup.test.ts — no extra test dependencies).
// The AdminSettingsPage component is not rendered here; its error/success
// display logic is extracted into the pure functions asserted below.

const originalFetch = globalThis.fetch;

function jsonResponse(
body: unknown,
status = 200,
headers?: Record<string, string>,
): Response {
return new Response(JSON.stringify(body), { status, headers });
}

function mockFetch(
handler: (url: string, init?: RequestInit) => Response | Promise<Response>,
): string[] {
const calls: string[] = [];
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input);
calls.push(url);
return handler(url, init);
}) as typeof fetch;
return calls;
}

afterEach(() => {
globalThis.fetch = originalFetch;
});

describe('adminApi.sendTestEmail', () => {
test('posts the recipient and returns success', async () => {
const calls = mockFetch((url, init) => {
assert.match(url, /\/api\/admin\/email\/test$/);
assert.equal(init?.method, 'POST');
assert.deepEqual(JSON.parse(String(init?.body)), { to: 'a@example.com' });
return jsonResponse({ success: true });
});

const result = await adminApi.sendTestEmail('a@example.com');

assert.equal(calls.length, 1);
assert.equal(result.success, true);
});

test('surfaces the status and Retry-After seconds on a 429', async () => {
mockFetch(
() =>
new Response(JSON.stringify({ error: 'Too many requests.' }), {
status: 429,
headers: { 'Retry-After': '30', 'Content-Type': 'application/json' },
}),
);

await assert.rejects(
adminApi.sendTestEmail('a@example.com'),
(error: unknown) => {
assert.ok(error instanceof ApiRequestError);
assert.equal(error.status, 429);
assert.equal(error.retryAfter, 30);
return true;
},
);
});

test('surfaces the status on a 502 send failure', async () => {
mockFetch(() => jsonResponse({ error: 'Failed to send' }, 502));

await assert.rejects(
adminApi.sendTestEmail('a@example.com'),
(error: unknown) => {
assert.ok(error instanceof ApiRequestError);
assert.equal(error.status, 502);
return true;
},
);
});
});

describe('resolveTestEmailError', () => {
test('maps 400, 429 and 502 to their status keys', () => {
assert.deepEqual(resolveTestEmailError({ status: 400 }), {
key: 'admin.testEmailErrorBadRequest',
});
assert.deepEqual(resolveTestEmailError({ status: 502 }), {
key: 'admin.testEmailErrorSendFailed',
});
});

test('maps a 429 with Retry-After to the localized too-many-requests key', () => {
assert.deepEqual(resolveTestEmailError({ status: 429, retryAfter: 45 }), {
key: 'admin.testEmailErrorTooManyRequests',
params: { seconds: 45 },
});
});

test('falls back to the generic key for unmatched errors', () => {
assert.deepEqual(resolveTestEmailError({ status: 500 }), {
key: 'admin.testEmailErrorGeneric',
});
assert.deepEqual(resolveTestEmailError(new Error('boom')), {
key: 'admin.testEmailErrorGeneric',
});
assert.deepEqual(resolveTestEmailError(undefined), {
key: 'admin.testEmailErrorGeneric',
});
});

test('is silent for a session-expired error', () => {
assert.equal(resolveTestEmailError(new SessionExpiredError()), null);
});
});

describe('formatTestEmailError', () => {
function makeT(locale: unknown) {
const resolve = (obj: unknown, path: string): string => {
let curr = obj;
for (const p of path.split('.')) {
curr = (curr as Record<string, unknown>)[p];
}
return String(curr);
};
return (key: string, params?: Record<string, string | number>): string => {
let text = resolve(locale, key);
if (params) {
for (const [k, v] of Object.entries(params)) {
text = text.replace(`{{${k}}}`, String(v));
}
}
return text;
};
}

test('returns null when there is no error to show', () => {
assert.equal(formatTestEmailError(null, makeT(en)), null);
});

test('interpolates the Retry-After seconds into the localized message', () => {
const msg = resolveTestEmailError({ status: 429, retryAfter: 45 });
assert.equal(
formatTestEmailError(msg, makeT(en)),
'Too many requests. Try again in 45s.',
);
assert.equal(
formatTestEmailError(msg, makeT(zhCN)),
'请求过于频繁,请在 45 秒后重试。',
);
});
});

describe('test email i18n keys', () => {
function resolve(obj: unknown, path: string): unknown {
let curr = obj;
for (const p of path.split('.')) {
if (curr == null || typeof curr !== 'object') return undefined;
curr = (curr as Record<string, unknown>)[p];
}
return curr;
}

test('resolve to non-empty strings in both locales', () => {
const keys = [
'admin.sendTestEmail',
'admin.testEmailRecipient',
'admin.testEmailNote',
'admin.testEmailSuccess',
'admin.testEmailErrorBadRequest',
'admin.testEmailErrorTooManyRequests',
'admin.testEmailErrorSendFailed',
'admin.testEmailErrorGeneric',
];
for (const key of keys) {
assert.equal(typeof resolve(en, key), 'string', `${key} (en) is missing`);
assert.equal(
typeof resolve(zhCN, key),
'string',
`${key} (zh-CN) is missing`,
);
assert.ok((resolve(en, key) as string).length > 0, `${key} (en) empty`);
assert.ok((resolve(zhCN, key) as string).length > 0, `${key} (zh) empty`);
}
});
});
55 changes: 55 additions & 0 deletions apps/web/src/lib/testEmail.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import type { TFunction, TranslationKey } from '@/i18n';
import { isSessionExpiredError } from '../api/client.ts';

// Pure, testable helpers for the admin "send test email" action. Kept free of
// React so they run under `node --test`; the runtime import below is relative
// (`.ts`) because Node's type stripping does no `@/` alias resolution.

export type TestEmailErrorMsg = {
key: TranslationKey;
params?: Record<string, string | number>;
};

// Structural view of what a test-email API error looks like.
export interface TestEmailErrorLike {
status: number;
retryAfter?: number;
}

// Maps a test-email failure to a localized message. The endpoint returns a
// plain `{ error }` body without a `code`, so the status code drives the
// mapping: 400 is a config/address problem, 429 is rate-limiting (with
// Retry-After seconds), 502 is a send failure, and everything else falls back
// to a generic key rather than leaking an untranslated backend/network string.
// Returns null for a session-expired error so callers stay quiet (AuthProvider
// shows the single global toast).
export function resolveTestEmailError(
error: unknown,
): TestEmailErrorMsg | null {
if (isSessionExpiredError(error)) return null;
if (error && typeof error === 'object') {
const e = error as TestEmailErrorLike;
switch (e.status) {
case 400:
return { key: 'admin.testEmailErrorBadRequest' };
case 429:
return {
key: 'admin.testEmailErrorTooManyRequests',
params: { seconds: e.retryAfter ?? 0 },
};
case 502:
return { key: 'admin.testEmailErrorSendFailed' };
}
}
return { key: 'admin.testEmailErrorGeneric' };
}

// Turns a resolved test-email error into its display string, or null when there
// is nothing to show (no error, or a session-expired error handled elsewhere).
export function formatTestEmailError(
msg: TestEmailErrorMsg | null,
t: TFunction,
): string | null {
if (!msg) return null;
return t(msg.key, msg.params);
}
Loading
Loading