Archived
邮件路由 15 条:账号 CRUD / 探测 / 立即拉取 / 试发 / 入站出站 / 附件原件 / 重新投递;领域错误翻状态码,厂商失败在 body 里说
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TM4kUBvekALu9qqmp7D3wr
This commit is contained in:
@@ -0,0 +1,116 @@
|
||||
/**
|
||||
* 邮件路由:zod 校验 → 用例 → 领域错误翻状态码;厂商失败在 200 的 body 里如实说。
|
||||
* 不挂鉴权中间件(归属由路由覆盖测试与注册表测试兜);用例是真的,store 是内存的,provider 是假的。
|
||||
*/
|
||||
import { Hono } from 'hono';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { createMailService, createPostalMimeParser } from '@modules/mail';
|
||||
import type { AppEnv } from '../http-env.ts';
|
||||
import { registerMailRoutes } from '../routes/mail.ts';
|
||||
import { account, eml, fakeProvider, fixedClock, memoryAccounts, memoryAttachments, memoryInbound, memoryOutbound, plainSecrets, rawMessage, seqIds } from '../../modules/mail/__tests__/fakes.ts';
|
||||
|
||||
function harness() {
|
||||
const clock = fixedClock();
|
||||
const accounts = memoryAccounts(clock);
|
||||
const imap = fakeProvider('imap-smtp');
|
||||
const mail = createMailService({
|
||||
accounts,
|
||||
inbound: memoryInbound(),
|
||||
outbound: memoryOutbound(),
|
||||
attachments: memoryAttachments(),
|
||||
providers: { 'imap-smtp': imap, wecom: fakeProvider('wecom') },
|
||||
mime: createPostalMimeParser(),
|
||||
secrets: plainSecrets,
|
||||
clock,
|
||||
ids: seqIds('x'),
|
||||
notify: { changed: () => undefined },
|
||||
});
|
||||
const app = new Hono<AppEnv>();
|
||||
registerMailRoutes(app, { mail });
|
||||
const json = (method: string, path: string, body?: unknown) =>
|
||||
app.request(path, { method, headers: { 'content-type': 'application/json' }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
|
||||
return { app, mail, accounts, imap, json };
|
||||
}
|
||||
const input = { kind: 'imap-smtp', name: '销售', address: 'sales@we.com', isDefault: true, secret: { password: 'pw-1234' } };
|
||||
|
||||
describe('账号路由', () => {
|
||||
it('列表 / 建 / 取 / 改 / 删;400 / 404 / 409', async () => {
|
||||
const h = harness();
|
||||
expect(await (await h.json('GET', '/api/gov/mail/accounts')).json()).toEqual({ accounts: [] });
|
||||
expect((await h.json('POST', '/api/gov/mail/accounts', { kind: 'imap-smtp' })).status).toBe(400);
|
||||
const created = await h.json('POST', '/api/gov/mail/accounts', input);
|
||||
expect(created.status).toBe(200);
|
||||
const view = (await created.json()) as { id: string; secretBound: boolean };
|
||||
expect(view.secretBound).toBe(true);
|
||||
expect(JSON.stringify(view)).not.toContain('pw-1234');
|
||||
expect((await h.json('POST', '/api/gov/mail/accounts', input)).status).toBe(409);
|
||||
expect((await h.json('GET', `/api/gov/mail/accounts/${view.id}`)).status).toBe(200);
|
||||
expect((await h.json('GET', '/api/gov/mail/accounts/nope')).status).toBe(404);
|
||||
expect((await h.json('PUT', `/api/gov/mail/accounts/${view.id}`, { ...input, displayName: '销售部' })).status).toBe(200);
|
||||
expect(await (await h.json('DELETE', `/api/gov/mail/accounts/${view.id}`)).json()).toEqual({ ok: true });
|
||||
expect((await h.json('DELETE', `/api/gov/mail/accounts/${view.id}`)).status).toBe(404);
|
||||
});
|
||||
|
||||
it('探测:草稿没密码 412;已存账号 200 且厂商失败在 body 里', async () => {
|
||||
const h = harness();
|
||||
expect((await h.json('POST', '/api/gov/mail/accounts/probe', { ...input, secret: undefined })).status).toBe(412);
|
||||
const view = (await (await h.json('POST', '/api/gov/mail/accounts', input)).json()) as { id: string };
|
||||
expect((await h.json('POST', '/api/gov/mail/accounts/probe?accountId=' + view.id, { ...input, secret: undefined })).status).toBe(200);
|
||||
h.imap.probeWith({ kind: 'imap-smtp', receive: { ok: false, error: '535 pw-1234 bad' }, send: { checked: true, ok: true } });
|
||||
const res = await h.json('POST', `/api/gov/mail/accounts/${view.id}/probe`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toMatchObject({ receive: { ok: false, error: '535 *** bad' } });
|
||||
});
|
||||
|
||||
it('立即拉取:200 outcome;停用 412;租约被占 409', async () => {
|
||||
const h = harness();
|
||||
await h.accounts.save(account());
|
||||
h.imap.queue(rawMessage('uid:v1:1', eml({ messageId: '<m1@a>' })));
|
||||
expect(await (await h.json('POST', '/api/gov/mail/accounts/acc-1/poll')).json()).toMatchObject({ pulled: 1, stored: 1 });
|
||||
await h.accounts.save(account({ enabled: false }));
|
||||
expect((await h.json('POST', '/api/gov/mail/accounts/acc-1/poll')).status).toBe(412);
|
||||
await h.accounts.save(account({ pollingUntil: new Date('2027-01-01T00:00:00Z') }));
|
||||
expect((await h.json('POST', '/api/gov/mail/accounts/acc-1/poll')).status).toBe(409);
|
||||
});
|
||||
|
||||
it('试发:成功与厂商失败都是 200,state 说话;入参错 400', async () => {
|
||||
const h = harness();
|
||||
await h.accounts.save(account());
|
||||
const ok = await h.json('POST', '/api/gov/mail/accounts/acc-1/send-test', { to: 'me@we.com', subject: '试发', text: '正文' });
|
||||
expect(await ok.json()).toMatchObject({ state: 'sent', messageId: '<x-1@we.com>' });
|
||||
h.imap.failSendWith(new Error('535 nope'));
|
||||
expect(await (await h.json('POST', '/api/gov/mail/accounts/acc-1/send-test', { to: 'me@we.com', subject: '试发', text: '正文' })).json()).toMatchObject({ state: 'failed', error: '535 nope' });
|
||||
expect((await h.json('POST', '/api/gov/mail/accounts/acc-1/send-test', { to: 'not-mail', subject: '', text: '' })).status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('入站 / 出站路由', () => {
|
||||
it('列表(limit)/ 详情 / 附件 / 原件 / 重新投递;404 各就各位', async () => {
|
||||
const h = harness();
|
||||
await h.accounts.save(account());
|
||||
h.mail.subscribe('spy', async () => undefined);
|
||||
h.imap.queue(rawMessage('uid:v1:1', eml({ messageId: '<m1@a>', attachment: { name: 'a.txt', contentType: 'text/plain', content: 'hi' } })));
|
||||
await h.json('POST', '/api/gov/mail/accounts/acc-1/poll');
|
||||
const list = (await (await h.json('GET', '/api/gov/mail/inbound?accountId=acc-1&limit=10')).json()) as { mails: Array<{ id: string; deliveries: unknown[] }> };
|
||||
expect(list.mails).toHaveLength(1);
|
||||
expect(list.mails[0]?.deliveries).toHaveLength(1);
|
||||
const id = list.mails[0]!.id;
|
||||
expect((await h.json('GET', `/api/gov/mail/inbound/${id}`)).status).toBe(200);
|
||||
expect((await h.json('GET', '/api/gov/mail/inbound/nope')).status).toBe(404);
|
||||
const att = (await (await h.json('GET', `/api/gov/mail/inbound/${id}/attachments/0`)).json()) as { name: string; dataBase64: string };
|
||||
expect(att.name).toBe('a.txt');
|
||||
expect(Buffer.from(att.dataBase64, 'base64').toString()).toBe('hi');
|
||||
expect((await h.json('GET', `/api/gov/mail/inbound/${id}/attachments/7`)).status).toBe(404);
|
||||
const raw = (await (await h.json('GET', `/api/gov/mail/inbound/${id}/raw`)).json()) as { contentType: string };
|
||||
expect(raw.contentType).toBe('message/rfc822');
|
||||
expect(await (await app_request_redeliver(h, id)).json()).toMatchObject({ deliveries: [{ subscriber: 'spy', state: 'done' }] });
|
||||
expect((await h.json('POST', `/api/gov/mail/inbound/${id}/redeliver`, { subscriber: 'nobody' })).status).toBe(404);
|
||||
expect((await h.json('GET', '/api/gov/mail/inbound?limit=0')).status).toBe(400);
|
||||
expect(await (await h.json('GET', '/api/gov/mail/outbound')).json()).toEqual({ mails: [] });
|
||||
});
|
||||
});
|
||||
|
||||
/** 空 body 的 POST:redeliver 的 body 是可省的 */
|
||||
function app_request_redeliver(h: ReturnType<typeof harness>, id: string): Promise<Response> {
|
||||
return Promise.resolve(h.app.request(`/api/gov/mail/inbound/${id}/redeliver`, { method: 'POST' }));
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
/**
|
||||
* 邮件收发路由(设计稿 §7.2;ADR-013)。归属在契约的 access 上,中间件统一判;
|
||||
* 这里只做 zod 校验、调用用例、把领域错误翻成状态码。
|
||||
* 探测 / 试发 / 拉取的**厂商失败在 200 的 body 里如实说** —— 不是接口错误。
|
||||
*/
|
||||
import type { Context, Hono } from 'hono';
|
||||
import type { ApiError } from '@contracts';
|
||||
import {
|
||||
createMailAccountRoute,
|
||||
deleteMailAccountRoute,
|
||||
getMailAccountRoute,
|
||||
getMailInboundRoute,
|
||||
listMailAccountsRoute,
|
||||
listMailInboundRoute,
|
||||
listMailOutboundRoute,
|
||||
mailAttachmentRoute,
|
||||
mailRawRoute,
|
||||
pollMailAccountRoute,
|
||||
probeMailAccountRoute,
|
||||
probeMailDraftRoute,
|
||||
redeliverMailInboundRoute,
|
||||
sendTestMailRoute,
|
||||
updateMailAccountRoute,
|
||||
} from '@contracts';
|
||||
import type { MailService } from '@modules/mail';
|
||||
import {
|
||||
MailAccountDisabledError,
|
||||
MailAccountNameTakenError,
|
||||
MailAccountNotFoundError,
|
||||
MailAttachmentNotFoundError,
|
||||
MailInboundNotFoundError,
|
||||
MailNoDefaultAccountError,
|
||||
MailPollBusyError,
|
||||
MailSecretMissingError,
|
||||
MailSendInvalidError,
|
||||
MailSubscriberUnknownError,
|
||||
} from '@modules/mail';
|
||||
import type { AppEnv } from '../http-env.ts';
|
||||
import { staffOf } from '../http-env.ts';
|
||||
|
||||
export type MailRouteDeps = { readonly mail: MailService };
|
||||
|
||||
/** 领域错误 → 状态码;认不出的交回 onError(500) */
|
||||
export function mailErrorResponse(error: unknown): { status: 400 | 404 | 409 | 412; body: ApiError } | undefined {
|
||||
if (
|
||||
error instanceof MailAccountNotFoundError ||
|
||||
error instanceof MailInboundNotFoundError ||
|
||||
error instanceof MailAttachmentNotFoundError ||
|
||||
error instanceof MailSubscriberUnknownError
|
||||
) {
|
||||
return { status: 404, body: { code: 'not-found', message: error.message } };
|
||||
}
|
||||
if (error instanceof MailAccountNameTakenError || error instanceof MailPollBusyError) {
|
||||
return { status: 409, body: { code: 'conflict', message: error.message } };
|
||||
}
|
||||
if (error instanceof MailAccountDisabledError || error instanceof MailNoDefaultAccountError || error instanceof MailSecretMissingError) {
|
||||
return { status: 412, body: { code: 'precondition-failed', message: error.message } };
|
||||
}
|
||||
if (error instanceof MailSendInvalidError) {
|
||||
return { status: 400, body: { code: 'validation-failed', message: error.message, detail: error.problems } };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function invalid(c: Context<AppEnv>, message: string, detail: unknown): Response {
|
||||
const body: ApiError = { code: 'validation-failed', message, detail };
|
||||
return c.json(body, 400);
|
||||
}
|
||||
|
||||
async function jsonBody(c: Context<AppEnv>): Promise<unknown> {
|
||||
const text = await c.req.text();
|
||||
if (text.trim() === '') return {};
|
||||
try {
|
||||
return JSON.parse(text) as unknown;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function registerMailRoutes(app: Hono<AppEnv>, deps: MailRouteDeps): void {
|
||||
const { mail } = deps;
|
||||
|
||||
const guarded = async (c: Context<AppEnv>, run: () => Promise<Response>): Promise<Response> => {
|
||||
try {
|
||||
return await run();
|
||||
} catch (error) {
|
||||
const mapped = mailErrorResponse(error);
|
||||
if (mapped === undefined) throw error;
|
||||
return c.json(mapped.body, mapped.status);
|
||||
}
|
||||
};
|
||||
|
||||
/* ── 账号 ── */
|
||||
|
||||
app.get(listMailAccountsRoute.path, async (c) => c.json({ accounts: await mail.listAccounts() }));
|
||||
|
||||
app.post(createMailAccountRoute.path, async (c) => {
|
||||
const parsed = createMailAccountRoute.body.safeParse(await jsonBody(c));
|
||||
if (!parsed.success) return invalid(c, '账号入参不合法', parsed.error.issues);
|
||||
return guarded(c, async () => c.json(await mail.createAccount(parsed.data)));
|
||||
});
|
||||
|
||||
app.post(probeMailDraftRoute.path, async (c) => {
|
||||
const parsed = probeMailDraftRoute.body.safeParse(await jsonBody(c));
|
||||
if (!parsed.success) return invalid(c, '账号入参不合法', parsed.error.issues);
|
||||
const accountId = c.req.query('accountId');
|
||||
return guarded(c, async () =>
|
||||
c.json(await mail.probe({ input: parsed.data, ...(accountId === undefined || accountId === '' ? {} : { accountId }) })),
|
||||
);
|
||||
});
|
||||
|
||||
app.get(getMailAccountRoute.path, async (c) => guarded(c, async () => c.json(await mail.getAccount(c.req.param('accountId')))));
|
||||
|
||||
app.put(updateMailAccountRoute.path, async (c) => {
|
||||
const parsed = updateMailAccountRoute.body.safeParse(await jsonBody(c));
|
||||
if (!parsed.success) return invalid(c, '账号入参不合法', parsed.error.issues);
|
||||
return guarded(c, async () => c.json(await mail.updateAccount(c.req.param('accountId'), parsed.data)));
|
||||
});
|
||||
|
||||
app.delete(deleteMailAccountRoute.path, async (c) =>
|
||||
guarded(c, async () => {
|
||||
await mail.deleteAccount(c.req.param('accountId'));
|
||||
return c.json({ ok: true as const });
|
||||
}),
|
||||
);
|
||||
|
||||
app.post(probeMailAccountRoute.path, async (c) => guarded(c, async () => c.json(await mail.probe({ accountId: c.req.param('accountId') }))));
|
||||
|
||||
app.post(pollMailAccountRoute.path, async (c) => guarded(c, async () => c.json(await mail.pollNow(c.req.param('accountId')))));
|
||||
|
||||
app.post(sendTestMailRoute.path, async (c) => {
|
||||
const parsed = sendTestMailRoute.body.safeParse(await jsonBody(c));
|
||||
if (!parsed.success) return invalid(c, '试发入参不合法', parsed.error.issues);
|
||||
const me = staffOf(c);
|
||||
return guarded(c, async () =>
|
||||
c.json(
|
||||
await mail.send({
|
||||
accountId: c.req.param('accountId'),
|
||||
to: [parsed.data.to],
|
||||
cc: [],
|
||||
bcc: [],
|
||||
subject: parsed.data.subject,
|
||||
text: parsed.data.text,
|
||||
references: [],
|
||||
attachments: [],
|
||||
requestedBy: { kind: 'ops', ...(me === undefined ? {} : { staffId: me.id }) },
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
/* ── 入站 ── */
|
||||
|
||||
app.get(listMailInboundRoute.path, async (c) => {
|
||||
const query = listMailInboundRoute.query.safeParse(c.req.query());
|
||||
if (!query.success) return invalid(c, '查询参数不合法', query.error.issues);
|
||||
return c.json({ mails: await mail.listInbound({ accountId: query.data.accountId, limit: query.data.limit }) });
|
||||
});
|
||||
|
||||
app.get(getMailInboundRoute.path, async (c) => guarded(c, async () => c.json(await mail.getInbound(c.req.param('mailId')))));
|
||||
|
||||
app.get(mailAttachmentRoute.path, async (c) => {
|
||||
const params = mailAttachmentRoute.params.safeParse({ mailId: c.req.param('mailId'), index: c.req.param('index') });
|
||||
if (!params.success) return invalid(c, '附件序号不合法', params.error.issues);
|
||||
return guarded(c, async () => {
|
||||
const file = await mail.attachment(params.data.mailId, params.data.index);
|
||||
return c.json({ name: file.name, contentType: file.contentType, dataBase64: Buffer.from(file.bytes).toString('base64') });
|
||||
});
|
||||
});
|
||||
|
||||
app.get(mailRawRoute.path, async (c) =>
|
||||
guarded(c, async () => {
|
||||
const file = await mail.raw(c.req.param('mailId'));
|
||||
return c.json({ name: file.name, contentType: 'message/rfc822' as const, dataBase64: Buffer.from(file.bytes).toString('base64') });
|
||||
}),
|
||||
);
|
||||
|
||||
app.post(redeliverMailInboundRoute.path, async (c) => {
|
||||
const parsed = redeliverMailInboundRoute.body.safeParse(await jsonBody(c));
|
||||
if (!parsed.success) return invalid(c, '入参不合法', parsed.error.issues);
|
||||
return guarded(c, async () => c.json({ deliveries: await mail.redeliver(c.req.param('mailId'), parsed.data.subscriber) }));
|
||||
});
|
||||
|
||||
/* ── 出站 ── */
|
||||
|
||||
app.get(listMailOutboundRoute.path, async (c) => {
|
||||
const query = listMailOutboundRoute.query.safeParse(c.req.query());
|
||||
if (!query.success) return invalid(c, '查询参数不合法', query.error.issues);
|
||||
return c.json({ mails: await mail.listOutbound({ accountId: query.data.accountId, limit: query.data.limit }) });
|
||||
});
|
||||
}
|
||||
@@ -28,6 +28,7 @@ import { registerRegistrationRoutes } from './routes/registration.ts';
|
||||
import { registerGovernanceOpsRoutes } from './routes/governance-ops.ts';
|
||||
import { registerGovernanceRoutes } from './routes/governance.ts';
|
||||
import { registerIngestRoutes } from './routes/ingest.ts';
|
||||
import { registerMailRoutes } from './routes/mail.ts';
|
||||
import { registerStreamRoute } from './routes/stream.ts';
|
||||
import { registerWorkbenchRoutes } from './routes/workbench.ts';
|
||||
|
||||
@@ -119,6 +120,7 @@ export function createServer(container: Container): Hono<AppEnv> {
|
||||
registerDeskApprovalRoutes(app, container);
|
||||
registerRegistrationRoutes(app, container);
|
||||
registerGovernanceOpsRoutes(app, container);
|
||||
registerMailRoutes(app, container);
|
||||
registerIngestRoutes(app, container);
|
||||
registerStreamRoute(app, container.broadcaster);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user