feat: v2.1.0 界面与凭据改进 —— 单一 API/MCP Key、邮件 Markdown 正文、/inboxs 域名筛选、暗色主题

- 单一 Key:API 与 MCP 共用一个 wmh_ Key,凭据迁移至 settings 表(0004 删除 api_credentials)
- Markdown:入库时 HTML→Markdown(mailhook 同思路),webhook payload 新增 markdown 字段
- /emails 路由改为 /inboxs 并支持域名筛选;设置按钮移入头像下拉
- 主题切换按钮(头像左侧,亮/暗持久化);设置模态仅 全局 Webhook/账号密码 两 tab 且高度限屏
- 列表操作列按钮加 SVG 图标;mailboxes 去 Webhook 列;最近邮件加收件人列
This commit is contained in:
bigcode
2026-09-30 13:27:28 +08:00
parent fec96e49cc
commit 7370cce784
38 changed files with 1281 additions and 512 deletions
+86 -60
View File
@@ -1,18 +1,19 @@
/** 应用框架:100vh 布局(侧栏 + 顶栏页面标题 + 内容区滚动),会话守卫 + 设置入口 */
/** 应用框架:100vh 布局(侧栏 + 顶栏页面标题 + 内容区滚动),会话守卫 + 主题切换 + 头像下拉(设置/退出) */
import { useEffect, useState } from "react";
import { Outlet, useLocation, useNavigate } from "react-router-dom";
import { Avatar, Button, Dropdown, Layout, Menu, Tooltip } from "antd";
import { Avatar, Button, Dropdown, Layout, Menu } from "antd";
import {
DashboardOutlined,
MailOutlined,
CloudServerOutlined,
GlobalOutlined,
SettingOutlined,
UserOutlined,
LogoutOutlined,
SettingOutlined,
} from "@ant-design/icons";
import { health, logout, me } from "./api.ts";
import { SettingsModal } from "./components/SettingsModal.tsx";
import { useTheme } from "./theme-context.ts";
const { Sider, Header, Content } = Layout;
@@ -22,7 +23,7 @@ const MENU_ITEMS = [
{ key: "/accounts", icon: <CloudServerOutlined />, label: "账号 Accounts" },
{ key: "/domains", icon: <GlobalOutlined />, label: "域名 Domains" },
{ key: "/mailboxes", icon: <MailOutlined />, label: "邮箱 Mailboxes" },
{ key: "/emails", icon: <MailOutlined />, label: "邮件 Emails" },
{ key: "/inboxs", icon: <MailOutlined />, label: "收件箱 Inboxs" },
];
/** # 成员变量: 路由 -> 页面标题/副标题 **/
@@ -31,15 +32,29 @@ const PAGE_META: Record<string, { title: string; subtitle: string }> = {
"/accounts": { title: "账号", subtitle: "通过 Cloudflare OAuth 接入的 Cloudflare 账号(Email Worker 直连)" },
"/domains": { title: "域名", subtitle: "OAuth 自动同步的收件域名与 Email Workers" },
"/mailboxes": { title: "邮箱", subtitle: "收件地址、保留策略与邮箱级 Webhook" },
"/emails": { title: "邮件", subtitle: "已接收邮件(默认保留 1 天)" },
"/inboxs": { title: "收件箱", subtitle: "已接收邮件(默认保留 1 天),支持按域名筛选" },
};
/** # 成员变量: 主题切换按钮的太阳/月亮 SVG 图标 **/
const SunIcon = (
<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
<circle cx="12" cy="12" r="4" />
<path d="M12 2v2m0 16v2M4.9 4.9l1.4 1.4m11.4 11.4 1.4 1.4M2 12h2m16 0h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4" />
</svg>
);
const MoonIcon = (
<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z" />
</svg>
);
/** # 函数
* 应用框架组件:未登录跳 /login;顶栏展示页面标题 + 设置入口;侧栏品牌带版本号
* 应用框架组件:未登录跳 /login;顶栏展示页面标题 + 主题切换 + 头像下拉;侧栏品牌带版本号
*/
export function App() {
const navigate = useNavigate();
const location = useLocation();
const { dark, toggle } = useTheme();
const [ready, setReady] = useState(false);
const [username, setUsername] = useState("");
const [version, setVersion] = useState("");
@@ -62,67 +77,78 @@ export function App() {
const meta = PAGE_META[location.pathname] ?? { title: "WmailHub", subtitle: "" };
return (
<Layout className="app-layout">
<Sider width={228} className="app-sider" theme="light">
<div className="brand">
<img src="/logo.svg" alt="WmailHub" />
<span className="name">WmailHub</span>
{/* 版本号小一号、居上对齐(来源 package.json) */}
{version && <span className="brand-version">v{version}</span>}
</div>
<Menu
mode="inline"
selectedKeys={[location.pathname]}
items={MENU_ITEMS}
onClick={({ key }) => navigate(key)}
style={{ borderInlineEnd: "none" }}
/>
</Sider>
<Layout>
<Header className="app-header">
<div className="header-meta">
<div className="title">{meta.title}</div>
<div className="subtitle">{meta.subtitle}</div>
<>
<Layout className="app-layout">
<Sider width={228} className="app-sider" theme={dark ? "dark" : "light"}>
<div className="brand">
<img src="/logo.svg" alt="WmailHub" />
<span className="name">WmailHub</span>
{/* 版本号小一号、居上对齐(来源 package.json) */}
{version && <span className="brand-version">v{version}</span>}
</div>
<div style={{ display: "flex", alignItems: "center", gap: 14 }}>
<Tooltip title="设置(全局 Webhook / 密码 / API & MCP Keys)">
<Menu
mode="inline"
selectedKeys={[location.pathname]}
items={MENU_ITEMS}
onClick={({ key }) => navigate(key)}
style={{ borderInlineEnd: "none" }}
/>
</Sider>
<Layout>
<Header className="app-header">
<div className="header-meta">
<div className="title">{meta.title}</div>
<div className="subtitle">{meta.subtitle}</div>
</div>
<div style={{ display: "flex", alignItems: "center", gap: 14 }}>
{/* 主题切换:亮↔暗,位于头像左侧 */}
<Button
type="text"
icon={<SettingOutlined />}
onClick={() => setSettingsOpen(true)}
aria-label="设置"
aria-label="切换主题"
title={dark ? "切换到亮色模式" : "切换到暗色模式"}
icon={dark ? SunIcon : MoonIcon}
onClick={toggle}
/>
</Tooltip>
{/* Dropdown 子元素必须是 DOM 元素(antd v6 坑),所以外包 div */}
<div>
<Dropdown
menu={{
items: [
{
key: "logout",
icon: <LogoutOutlined />,
label: "退出登录",
onClick: async () => {
await logout().catch(() => undefined);
window.location.href = "/login";
{/* 设置入口收进头像下拉 */}
<div>
<Dropdown
menu={{
items: [
{
key: "settings",
icon: <SettingOutlined />,
label: "设置",
onClick: () => setSettingsOpen(true),
},
},
],
}}
>
<div style={{ display: "flex", alignItems: "center", gap: 8, cursor: "pointer" }}>
<Avatar size={30} icon={<UserOutlined />} />
<span>{username}</span>
</div>
</Dropdown>
{
type: "divider" as const,
},
{
key: "logout",
icon: <LogoutOutlined />,
label: "退出登录",
onClick: async () => {
await logout().catch(() => undefined);
window.location.href = "/login";
},
},
],
}}
>
<div style={{ display: "flex", alignItems: "center", gap: 8, cursor: "pointer" }}>
<Avatar size={30} icon={<UserOutlined />} />
<span>{username}</span>
</div>
</Dropdown>
</div>
</div>
</div>
</Header>
<Content className="app-content">
<Outlet />
</Content>
</Header>
<Content className="app-content">
<Outlet />
</Content>
</Layout>
</Layout>
<SettingsModal open={settingsOpen} onClose={() => setSettingsOpen(false)} />
</Layout>
</>
);
}
+22 -21
View File
@@ -99,7 +99,14 @@ export const stats = () =>
deliveries_pending: number;
oauth_connections: number;
worker_credentials: number;
recent_emails: { id: string; subject: string; from_address: string; received_at: string; size: number }[];
recent_emails: {
id: string;
subject: string;
from_address: string;
to_addresses: string;
received_at: string;
size: number;
}[];
}>("/api/admin/stats");
/** 手动触发 Cron */
@@ -243,8 +250,13 @@ export interface EmailRow {
attachment_count: number;
}
export const listEmails = (params: { mailbox_id?: string; q?: string; limit?: number; offset?: number }) =>
api<{ items: EmailRow[]; total: number }>(`/api/emails${qs(params)}`);
export const listEmails = (params: {
domain_id?: string;
mailbox_id?: string;
q?: string;
limit?: number;
offset?: number;
}) => api<{ items: EmailRow[]; total: number }>(`/api/emails${qs(params)}`);
export interface EmailDetail {
email: EmailRow & { text_body: string | null; html_body: string | null; raw_storage_key: string; cc_addresses: string };
@@ -260,6 +272,7 @@ export const deleteEmail = (id: string) => api(`/api/emails/${id}`, "DELETE");
export interface SettingsInfo {
username: string;
webhook: { url: string; headers: Record<string, string>; has_key: boolean; key_last4: string };
api_key: { has_key: boolean; key_last4: string; created_at: string | null };
}
export const getSettings = () => api<SettingsInfo>("/api/settings");
@@ -272,23 +285,11 @@ export const putSettings = (body: {
export const changePassword = (old_password: string, new_password: string) =>
api("/api/settings/password", "PUT", { old_password, new_password });
/* ---- API/MCP Keys(设置模态窗口内使用) ---- */
/* ---- API/MCP Key(单一 Key,设置模态窗口内使用;API 与 MCP 共用) ---- */
export interface KeyRow {
id: string;
kind: "api" | "mcp";
name: string;
key_last4: string;
created_at: string;
revoked_at: string | null;
last_used_at: string | null;
}
/** 生成(轮换)Key:明文仅本次返回 */
export const createApiKey = () =>
api<{ ok: boolean; key: string; created_at: string }>("/api/settings/api-key", "POST");
export const listKeys = () => api<{ items: KeyRow[] }>("/api/keys");
export const createKey = (kind: "api" | "mcp", name?: string) =>
api<{ ok: boolean; id: string; kind: string; key: string }>("/api/keys", "POST", { kind, name });
export const revokeKey = (id: string) => api(`/api/keys/${id}/revoke`, "POST");
export const deleteKey = (id: string) => api(`/api/keys/${id}`, "DELETE");
/** 撤销并删除 Key */
export const deleteApiKey = () => api("/api/settings/api-key", "DELETE");
+155 -166
View File
@@ -1,35 +1,31 @@
/**
* 设置模态窗口(v2.0.0):
* - 基本设置:全局 Webhook(url/自定义头/key)+ 修改密码
* - API Keys / MCP Keys:wmh_ 凭据的生成、撤销、删除(原 /keys 页面收拢于此)
* 设置模态窗口(v2.1.0):
* - 两个 tab:全局 Webhook(含 API/MCP Key 卡片)、账号密码
* - 单一 API/MCP Key(API 与 MCP 共用),凭据存 settings 表,明文仅生成时返回一次
* - 内容高度不超过屏幕(超出滚动)
*/
import { useCallback, useEffect, useState } from "react";
import {
Alert,
App,
Button,
Card,
Descriptions,
Form,
Input,
Modal,
Space,
Table,
Tabs,
Tag,
Typography,
App,
Popconfirm,
Space,
Tabs,
Typography,
} from "antd";
import { PlusOutlined } from "@ant-design/icons";
import {
changePassword,
createKey,
deleteKey,
getSettings,
listKeys,
putSettings,
revokeKey,
type KeyRow,
type SettingsInfo,
} from "../api.ts";
CopyOutlined,
DeleteOutlined,
KeyOutlined,
PlusOutlined,
} from "@ant-design/icons";
import { changePassword, createApiKey, deleteApiKey, getSettings, putSettings, type SettingsInfo } from "../api.ts";
/** # 函数
* 设置模态窗口组件
@@ -51,12 +47,21 @@ export function SettingsModal({ open, onClose }: { open: boolean; onClose: () =>
}, [open, load]);
return (
<Modal title="设置" open={open} onCancel={onClose} footer={null} width={760} destroyOnHidden>
<Modal
title="设置"
open={open}
onCancel={onClose}
footer={null}
width={720}
centered
destroyOnHidden
// 高度不超过屏幕:内容区受限滚动
styles={{ body: { maxHeight: "calc(100vh - 180px)", overflowY: "auto", paddingRight: 8 } }}
>
<Tabs
items={[
{ key: "general", label: "基本设置", children: info ? <GeneralTab info={info} onSaved={load} /> : null },
{ key: "api", label: "API Keys", children: <KeysTab kind="api" /> },
{ key: "mcp", label: "MCP Keys", children: <KeysTab kind="mcp" /> },
{ key: "webhook", label: "全局 Webhook", children: info ? <WebhookTab info={info} onSaved={load} /> : null },
{ key: "password", label: "账号密码", children: <PasswordTab /> },
]}
/>
</Modal>
@@ -71,16 +76,11 @@ interface WebhookFormValues {
}
/** # 函数
* 基本设置:全局 Webhook + 修改密码
* 全局 Webhook tab:Webhook 表单 + 单一 API/MCP Key 卡片
*/
function GeneralTab({ info, onSaved }: { info: SettingsInfo; onSaved: () => void }) {
function WebhookTab({ info, onSaved }: { info: SettingsInfo; onSaved: () => void }) {
const { message } = App.useApp();
const [webhookForm] = Form.useForm<WebhookFormValues>();
const [pwdForm] = Form.useForm<{
old_password: string;
new_password: string;
confirm: string;
}>();
const [saving, setSaving] = useState(false);
useEffect(() => {
@@ -117,22 +117,9 @@ function GeneralTab({ info, onSaved }: { info: SettingsInfo; onSaved: () => void
}
};
/** 修改密码 */
const savePassword = async () => {
const values = await pwdForm.validateFields();
try {
await changePassword(values.old_password, values.new_password);
message.success("密码已更新");
pwdForm.resetFields();
} catch (err) {
message.error(err instanceof Error ? err.message : "修改失败");
}
};
return (
<Space orientation="vertical" size="large" style={{ width: "100%" }}>
<Form form={webhookForm} layout="vertical">
<Typography.Title level={5}>全局 Webhook</Typography.Title>
<Alert
type="info"
showIcon
@@ -165,153 +152,155 @@ function GeneralTab({ info, onSaved }: { info: SettingsInfo; onSaved: () => void
</Button>
</Form>
<Form form={pwdForm} layout="vertical" onFinish={() => void savePassword()}>
<Typography.Title level={5}>修改密码</Typography.Title>
<Form.Item name="old_password" label="原密码" rules={[{ required: true, message: "请输入原密码" }]}>
<Input.Password autoComplete="current-password" />
</Form.Item>
<Form.Item name="new_password" label="新密码(至少 6 位)" rules={[{ required: true, min: 6, message: "至少 6 位" }]}>
<Input.Password autoComplete="new-password" />
</Form.Item>
<Form.Item
name="confirm"
label="确认新密码"
dependencies={["new_password"]}
rules={[
{ required: true, message: "请再次输入" },
({ getFieldValue }) => ({
validator: (_, v) =>
!v || v === getFieldValue("new_password")
? Promise.resolve()
: Promise.reject(new Error("两次输入不一致")),
}),
]}
>
<Input.Password autoComplete="new-password" />
</Form.Item>
<Button type="primary" htmlType="submit">
更新密码
</Button>
</Form>
<ApiKeyCard apiKey={info.api_key} onChanged={onSaved} />
</Space>
);
}
/** # 函数
* API/MCP Key 管理表格
* API/MCP Key 卡片:单一 Key,API 与 MCP 接口共用;生成/轮换与撤销
*/
function KeysTab({ kind }: { kind: "api" | "mcp" }) {
function ApiKeyCard({
apiKey,
onChanged,
}: {
apiKey: SettingsInfo["api_key"];
onChanged: () => void;
}) {
const { message, modal } = App.useApp();
const [items, setItems] = useState<KeyRow[]>([]);
const [loading, setLoading] = useState(false);
const [q, setQ] = useState("");
const [busy, setBusy] = useState(false);
const load = useCallback(async () => {
setLoading(true);
try {
setItems((await listKeys()).items.filter((k) => k.kind === kind));
} finally {
setLoading(false);
}
}, [kind]);
useEffect(() => {
void load();
}, [load]);
const filtered = items.filter((k) =>
`${k.name} ${k.key_last4}`.toLowerCase().includes(q.trim().toLowerCase()),
);
/** 生成新 key:明文仅展示一次 */
/** 生成(轮换)key:明文仅展示一次 */
const create = async () => {
setBusy(true);
try {
const res = await createKey(kind);
const res = await createApiKey();
modal.info({
title: `${kind === "api" ? "API" : "MCP"} Key 已生成(仅显示一次)`,
title: "API/MCP Key 已生成(仅显示一次)",
content: (
<div>
<Typography.Paragraph copyable className="mono" style={{ marginBottom: 4 }}>
{res.key}
</Typography.Paragraph>
<Typography.Text type="secondary">请立即保存;关闭后无法再次查看。</Typography.Text>
<Typography.Text type="secondary">API 与 MCP 接口共用此 Key;请立即保存,关闭后无法再次查看。</Typography.Text>
</div>
),
});
void load();
onChanged();
} catch (err) {
message.error(err instanceof Error ? err.message : "生成失败");
} finally {
setBusy(false);
}
};
/** 撤销删除 key */
const remove = async () => {
setBusy(true);
try {
await deleteApiKey();
message.success("已撤销并删除 Key");
onChanged();
} catch (err) {
message.error(err instanceof Error ? err.message : "操作失败");
} finally {
setBusy(false);
}
};
return (
<div>
<div className="page-toolbar">
<Input
allowClear
placeholder="搜索名称 / 尾号"
style={{ width: 220 }}
onChange={(e) => setQ(e.target.value)}
/>
<Button type="primary" icon={<PlusOutlined />} onClick={() => void create()}>
生成 {kind === "api" ? "API" : "MCP"} Key
</Button>
</div>
<Table
rowKey="id"
size="small"
loading={loading}
dataSource={filtered}
pagination={false}
columns={[
{ title: "名称", dataIndex: "name", ellipsis: true },
{ title: "尾号", dataIndex: "key_last4", width: 80, render: (v: string) => <span className="mono">****{v}</span> },
{
title: "状态",
dataIndex: "revoked_at",
width: 90,
render: (v: string | null) => (v ? <Tag color="error">已撤销</Tag> : <Tag color="success">有效</Tag>),
},
{ title: "创建时间", dataIndex: "created_at", width: 165, render: (v: string) => new Date(v).toLocaleString() },
{
title: "最近使用",
dataIndex: "last_used_at",
width: 165,
render: (v: string | null) => (v ? new Date(v).toLocaleString() : "-"),
},
{
title: "操作",
width: 130,
render: (_: unknown, row: KeyRow) => (
<Space>
{!row.revoked_at && (
<Popconfirm
title="撤销后使用该 Key 的请求将被拒绝,确认?"
onConfirm={async () => {
await revokeKey(row.id);
message.success("已撤销");
void load();
}}
>
<Button size="small">撤销</Button>
</Popconfirm>
)}
<Button
size="small"
danger
onClick={async () => {
await deleteKey(row.id);
message.success("已删除");
void load();
}}
>
删除
</Button>
</Space>
),
},
]}
<Card size="small" title={<span><KeyOutlined style={{ marginRight: 8 }} />API / MCP Key</span>}>
<Alert
type="info"
showIcon
style={{ marginBottom: 12 }}
message="Console API(/api/v1)与 MCP(/api/v1/mcp)共用同一个 Key;生成新 Key 后旧 Key 立即失效。"
/>
</div>
<Descriptions size="small" column={1} style={{ marginBottom: 12 }}>
<Descriptions.Item label="状态">
{apiKey.has_key ? (
<span>
<span className="mono">****{apiKey.key_last4}</span>{" "}
<Typography.Text type="secondary">
{apiKey.created_at ? `创建于 ${new Date(apiKey.created_at).toLocaleString()}` : ""}
</Typography.Text>
</span>
) : (
<Typography.Text type="secondary">未生成</Typography.Text>
)}
</Descriptions.Item>
</Descriptions>
<Space>
<Button
type="primary"
icon={apiKey.has_key ? <CopyOutlined /> : <PlusOutlined />}
loading={busy}
onClick={() => void create()}
>
{apiKey.has_key ? "重新生成(轮换)" : "生成 Key"}
</Button>
{apiKey.has_key && (
<Popconfirm title="撤销后使用该 Key 的请求将被拒绝,确认?" onConfirm={() => void remove()}>
<Button danger icon={<DeleteOutlined />} disabled={busy}>
撤销
</Button>
</Popconfirm>
)}
</Space>
</Card>
);
}
/** # 函数
* 账号密码 tab:修改登录密码
*/
function PasswordTab() {
const { message } = App.useApp();
const [pwdForm] = Form.useForm<{
old_password: string;
new_password: string;
confirm: string;
}>();
/** 修改密码 */
const savePassword = async () => {
const values = await pwdForm.validateFields();
try {
await changePassword(values.old_password, values.new_password);
message.success("密码已更新");
pwdForm.resetFields();
} catch (err) {
message.error(err instanceof Error ? err.message : "修改失败");
}
};
return (
<Form form={pwdForm} layout="vertical" onFinish={() => void savePassword()}>
<Form.Item name="old_password" label="原密码" rules={[{ required: true, message: "请输入原密码" }]}>
<Input.Password autoComplete="current-password" />
</Form.Item>
<Form.Item name="new_password" label="新密码(至少 6 位)" rules={[{ required: true, min: 6, message: "至少 6 位" }]}>
<Input.Password autoComplete="new-password" />
</Form.Item>
<Form.Item
name="confirm"
label="确认新密码"
dependencies={["new_password"]}
rules={[
{ required: true, message: "请再次输入" },
({ getFieldValue }) => ({
validator: (_, v) =>
!v || v === getFieldValue("new_password")
? Promise.resolve()
: Promise.reject(new Error("两次输入不一致")),
}),
]}
>
<Input.Password autoComplete="new-password" />
</Form.Item>
<Button type="primary" htmlType="submit">
更新密码
</Button>
</Form>
);
}
+29 -11
View File
@@ -1,10 +1,11 @@
/** 前端入口:antd v6 + react-router(Vite 构建) */
import React from "react";
/** 前端入口:antd v6 + react-router(Vite 构建);亮/暗主题状态在顶层持有 */
import React, { useEffect, useState } from "react";
import { createRoot } from "react-dom/client";
import { ConfigProvider, App as AntdApp } from "antd";
import zhCN from "antd/locale/zh_CN";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import { antdTheme } from "./theme.ts";
import { applyDarkMode, buildAntdTheme, loadDarkMode } from "./theme.ts";
import { ThemeContext } from "./theme-context.ts";
import "./styles.css";
import { App } from "./App.tsx";
import { LoginPage } from "./pages/Login.tsx";
@@ -13,10 +14,10 @@ import { DashboardPage } from "./pages/Dashboard.tsx";
import { AccountsPage } from "./pages/Accounts.tsx";
import { DomainsPage } from "./pages/Domains.tsx";
import { MailboxesPage } from "./pages/Mailboxes.tsx";
import { EmailsPage } from "./pages/Emails.tsx";
import { InboxPage } from "./pages/Inbox.tsx";
import { setUnauthorizedHandler } from "./api.ts";
/** # 成员变量: 路由表 **/
/** # 成员变量: 路由表(邮件页路由 /inboxs,v2.1.0) **/
const router = createBrowserRouter([
{ path: "/login", element: <LoginPage /> },
{ path: "/oauth/sim/authorize", element: <OAuthSimPage /> },
@@ -28,11 +29,32 @@ const router = createBrowserRouter([
{ path: "accounts", element: <AccountsPage /> },
{ path: "domains", element: <DomainsPage /> },
{ path: "mailboxes", element: <MailboxesPage /> },
{ path: "emails", element: <EmailsPage /> },
{ path: "inboxs", element: <InboxPage /> },
],
},
]);
/** # 函数
* 顶层壳:持有主题状态,注入 Context 与 ConfigProvider
*/
function Shell() {
const [dark, setDark] = useState(loadDarkMode);
useEffect(() => {
applyDarkMode(dark);
}, [dark]);
return (
<ThemeContext.Provider value={{ dark, toggle: () => setDark((v) => !v) }}>
<ConfigProvider locale={zhCN} theme={buildAntdTheme(dark)}>
<AntdApp>
<RouterProvider router={router} />
</AntdApp>
</ConfigProvider>
</ThemeContext.Provider>
);
}
/** 未登录统一跳登录页 */
setUnauthorizedHandler(() => {
if (!location.pathname.startsWith("/login")) {
@@ -42,10 +64,6 @@ setUnauthorizedHandler(() => {
createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<ConfigProvider locale={zhCN} theme={antdTheme}>
<AntdApp>
<RouterProvider router={router} />
</AntdApp>
</ConfigProvider>
<Shell />
</React.StrictMode>,
);
+2 -1
View File
@@ -13,7 +13,7 @@ import {
Typography,
App,
} from "antd";
import { PlusOutlined, ReloadOutlined, SearchOutlined } from "@ant-design/icons";
import { DeleteOutlined, PlusOutlined, ReloadOutlined, SearchOutlined } from "@ant-design/icons";
import {
deleteAccount,
getAccount,
@@ -167,6 +167,7 @@ export function AccountsPage() {
<Button
size="small"
danger
icon={<DeleteOutlined />}
onClick={(e) => {
e.stopPropagation();
modal.confirm({
+23 -4
View File
@@ -4,14 +4,33 @@ import { Button, Card, Col, Row, Statistic, Table, message } from "antd";
import { ReloadOutlined, ClearOutlined } from "@ant-design/icons";
import { health, runCron, stats } from "../api.ts";
/** # 成员变量: 最近邮件表格列 **/
/** # 成员变量: 最近邮件表格列(含收件人) **/
const recentColumns = [
{ title: "主题", dataIndex: "subject", ellipsis: true },
{ title: "发件人", dataIndex: "from_address", width: 240, ellipsis: true },
{ title: "大小", dataIndex: "size", width: 100, render: (v: number) => fmtSize(v) },
{ title: "接收时间", dataIndex: "received_at", width: 190, render: (v: string) => new Date(v).toLocaleString() },
{ title: "发件人", dataIndex: "from_address", width: 200, ellipsis: true },
{
title: "收件人",
dataIndex: "to_addresses",
width: 200,
ellipsis: true,
render: (v: string | null) => firstRecipient(v) ?? "-",
},
{ title: "大小", dataIndex: "size", width: 90, render: (v: number) => fmtSize(v) },
{ title: "接收时间", dataIndex: "received_at", width: 180, render: (v: string) => new Date(v).toLocaleString() },
];
/** # 函数
* 取收件人列表第一个地址(JSON 数组字段)
*/
function firstRecipient(s: string | null): string | null {
try {
const v = JSON.parse(s ?? "[]");
return Array.isArray(v) && typeof v[0] === "string" && v[0] ? v[0] : null;
} catch {
return null;
}
}
/** # 函数
* 字节数格式化
*/
+4 -3
View File
@@ -5,7 +5,7 @@
*/
import { useCallback, useEffect, useMemo, useState } from "react";
import { Button, Card, Drawer, Input, Select, Space, Table, Tag, Tooltip, Typography, App } from "antd";
import { ReloadOutlined, SearchOutlined } from "@ant-design/icons";
import { CloudUploadOutlined, DeleteOutlined, ReloadOutlined, SearchOutlined } from "@ant-design/icons";
import {
deleteDomain,
listDomainAccounts,
@@ -132,17 +132,18 @@ export function DomainsPage() {
render: (_: unknown, row: DomainRow) => (
<Space onClick={(e) => e.stopPropagation()}>
{row.status !== "active" ? (
<Button size="small" type="primary" onClick={() => void runSetup(row)}>
<Button size="small" type="primary" icon={<CloudUploadOutlined />} onClick={() => void runSetup(row)}>
设置 Email Workers
</Button>
) : (
<Button size="small" onClick={() => void runSetup(row)}>
<Button size="small" icon={<ReloadOutlined />} onClick={() => void runSetup(row)}>
重新配置
</Button>
)}
<Button
size="small"
danger
icon={<DeleteOutlined />}
onClick={() =>
modal.confirm({
title: `删除域名 ${row.name}?`,
@@ -1,8 +1,28 @@
/** 邮件页:搜索、分页、详情(正文/HTML 预览/附件/raw 下载) */
/** 收件箱页(/inboxs):域名筛选、搜索、分页、详情(正文/HTML 预览/附件/raw 下载) */
import { useCallback, useEffect, useState } from "react";
import { Button, Card, Descriptions, Drawer, Input, Space, Table, Tag, Typography, App, Popconfirm, Modal } from "antd";
import { ReloadOutlined, SearchOutlined } from "@ant-design/icons";
import { deleteEmail, getEmail, listEmails, type EmailDetail, type EmailRow } from "../api.ts";
import {
Button,
Card,
Descriptions,
Drawer,
Input,
Select,
Space,
Table,
Tag,
Typography,
App,
Popconfirm,
Modal,
} from "antd";
import {
DeleteOutlined,
DownloadOutlined,
EyeOutlined,
ReloadOutlined,
SearchOutlined,
} from "@ant-design/icons";
import { deleteEmail, getEmail, listDomains, listEmails, type EmailDetail, type EmailRow } from "../api.ts";
/** # 函数
* 字节数格式化
@@ -21,8 +41,8 @@ const columns = [
ellipsis: true,
render: (v: string | null) => v ?? <span className="muted">(无主题)</span>,
},
{ title: "发件人", dataIndex: "from_address", width: 220, ellipsis: true },
{ title: "邮箱", dataIndex: "mailbox_address", width: 200, ellipsis: true, render: (v: string | null) => v ?? "-" },
{ title: "发件人", dataIndex: "from_address", width: 200, ellipsis: true },
{ title: "邮箱", dataIndex: "mailbox_address", width: 190, ellipsis: true, render: (v: string | null) => v ?? "-" },
{
title: "附件",
dataIndex: "attachment_count",
@@ -45,15 +65,17 @@ const columns = [
];
/** # 函数
* 邮件页组件
* 收件箱页组件
*/
export function EmailsPage() {
export function InboxPage() {
const { message } = App.useApp();
const [items, setItems] = useState<EmailRow[]>([]);
const [total, setTotal] = useState(0);
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(20);
const [q, setQ] = useState("");
const [domainId, setDomainId] = useState<string | undefined>();
const [domains, setDomains] = useState<{ id: string; name: string }[]>([]);
const [loading, setLoading] = useState(false);
const [detail, setDetail] = useState<EmailDetail | null>(null);
const [htmlPreview, setHtmlPreview] = useState(false);
@@ -61,18 +83,28 @@ export function EmailsPage() {
const load = useCallback(async () => {
setLoading(true);
try {
const res = await listEmails({ q, limit: pageSize, offset: (page - 1) * pageSize });
const res = await listEmails({ q, domain_id: domainId, limit: pageSize, offset: (page - 1) * pageSize });
setItems(res.items);
setTotal(res.total);
} finally {
setLoading(false);
}
}, [q, page, pageSize]);
}, [q, domainId, page, pageSize]);
useEffect(() => {
void load();
}, [load]);
useEffect(() => {
void (async () => {
try {
setDomains((await listDomains()).items.map((d) => ({ id: d.id, name: d.name })));
} catch {
// 域名选项加载失败不阻塞页面
}
})();
}, []);
return (
<div>
<div className="page-toolbar">
@@ -81,12 +113,25 @@ export function EmailsPage() {
allowClear
prefix={<SearchOutlined />}
placeholder="搜索主题 / 发件人"
style={{ width: 280 }}
style={{ width: 260 }}
onChange={(e) => {
setQ(e.target.value);
setPage(1);
}}
/>
<Select
allowClear
showSearch
optionFilterProp="label"
placeholder="按域名筛选"
style={{ width: 200 }}
options={domains.map((d) => ({ value: d.id, label: d.name }))}
value={domainId}
onChange={(v) => {
setDomainId(v);
setPage(1);
}}
/>
</Space>
<Button icon={<ReloadOutlined />} onClick={() => void load()} />
</div>
@@ -126,10 +171,10 @@ export function EmailsPage() {
extra={
detail && (
<Space>
<Button size="small" onClick={() => setHtmlPreview((v) => !v)} disabled={!detail.email.html_body}>
<Button size="small" icon={<EyeOutlined />} onClick={() => setHtmlPreview((v) => !v)} disabled={!detail.email.html_body}>
{htmlPreview ? "显示文本" : "HTML 预览"}
</Button>
<Button size="small" href={`/api/emails/${detail.email.id}/raw`} target="_blank">
<Button size="small" icon={<DownloadOutlined />} href={`/api/emails/${detail.email.id}/raw`} target="_blank">
下载 .eml
</Button>
<Popconfirm
@@ -141,7 +186,7 @@ export function EmailsPage() {
void load();
}}
>
<Button size="small" danger>
<Button size="small" danger icon={<DeleteOutlined />}>
删除
</Button>
</Popconfirm>
@@ -174,6 +219,7 @@ export function EmailsPage() {
<Button
key={att.id}
size="small"
icon={<DownloadOutlined />}
href={`/api/emails/${detail.email.id}/attachments/${att.id}`}
target="_blank"
>
+3 -8
View File
@@ -1,7 +1,7 @@
/** 邮箱页:创建/停用/删除/保留策略/邮箱级 Webhook;支持搜索 */
import { useCallback, useEffect, useMemo, useState } from "react";
import { Button, Card, Form, Input, InputNumber, Modal, Select, Space, Switch, Table, Tag, App } from "antd";
import { PlusOutlined, ReloadOutlined, SearchOutlined } from "@ant-design/icons";
import { ApiOutlined, DeleteOutlined, PlusOutlined, ReloadOutlined, SearchOutlined } from "@ant-design/icons";
import {
createMailbox,
deleteMailbox,
@@ -97,12 +97,6 @@ export function MailboxesPage() {
width: 95,
render: (v: string) => <Tag color={v === "active" ? "success" : "default"}>{v}</Tag>,
},
{
title: "Webhook",
width: 90,
render: (_: unknown, row: MailboxRow) =>
row.webhook_url ? <Tag color="blue">已配置</Tag> : <span className="muted">-</span>,
},
{
title: "保留(秒)",
dataIndex: "retention_seconds",
@@ -122,12 +116,13 @@ export function MailboxesPage() {
width: 150,
render: (_: unknown, row: MailboxRow) => (
<Space>
<Button size="small" onClick={() => setWebhookTarget(row)}>
<Button size="small" icon={<ApiOutlined />} onClick={() => setWebhookTarget(row)}>
Webhook
</Button>
<Button
size="small"
danger
icon={<DeleteOutlined />}
onClick={() =>
modal.confirm({
title: `删除邮箱 ${row.address}?`,
+27
View File
@@ -20,6 +20,33 @@ body,
border-right: 1px solid rgba(5, 5, 5, 0.06);
}
/* 暗色主题下的边框/文字覆盖(data-theme 由主题切换维护) */
[data-theme="dark"] .app-sider,
[data-theme="dark"] .app-header {
border-color: rgba(253, 253, 253, 0.12);
}
[data-theme="dark"] .app-sider .brand .name,
[data-theme="dark"] .app-header .title {
color: rgba(255, 255, 255, 0.88);
}
[data-theme="dark"] .app-header .subtitle,
[data-theme="dark"] .muted {
color: rgba(255, 255, 255, 0.45);
}
[data-theme="dark"] .brand-version {
color: #85a5ff;
background: rgba(133, 165, 255, 0.12);
border-color: rgba(133, 165, 255, 0.35);
}
[data-theme="dark"] .email-html-frame {
background: #fff; /* HTML 邮件按原样渲染,保持白色底 */
border-color: rgba(253, 253, 253, 0.15);
}
.app-sider .brand {
display: flex;
align-items: center;
+15
View File
@@ -0,0 +1,15 @@
/** 主题上下文:App 框架读取当前模式与切换函数(状态保存在 main.tsx 顶层) */
import { createContext, useContext } from "react";
/** # 成员变量: 主题上下文 **/
export const ThemeContext = createContext<{ dark: boolean; toggle: () => void }>({
dark: false,
toggle: () => undefined,
});
/** # 函数
* 组件内读取主题状态
*/
export function useTheme() {
return useContext(ThemeContext);
}
+58 -19
View File
@@ -1,25 +1,64 @@
/** antd v6 主题配置:默认主题 + 少量 token 覆写(主色与品牌一致) */
/** antd v6 主题配置:亮/暗双主题(暗色用 darkAlgorithm),品牌色一致 */
import type { ThemeConfig } from "antd";
import { theme } from "antd";
/** # 成员变量: 品牌主色 **/
export const BRAND_COLOR = "#2f54eb";
/** # 成员变量: antd 主题 */
export const antdTheme: ThemeConfig = {
token: {
colorPrimary: BRAND_COLOR,
borderRadius: 8,
fontFamily:
"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif",
},
components: {
Layout: {
siderBg: "#ffffff",
headerBg: "#ffffff",
headerHeight: 64,
},
Card: {
headerHeight: 56,
},
},
/** # 成员变量: 主题存储键(localStorage) **/
export const THEME_STORAGE_KEY = "wmh_theme";
/** # 成员变量: 亮色主题基础 token(两种主题共用) **/
const baseToken = {
colorPrimary: BRAND_COLOR,
borderRadius: 8,
fontFamily:
"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif",
};
/** # 函数
* 构建主题配置
* 参数: dark - 是否暗色模式
* 返回值: antd ThemeConfig
*/
export function buildAntdTheme(dark: boolean): ThemeConfig {
return {
algorithm: dark ? [theme.darkAlgorithm] : undefined,
token: {
...baseToken,
},
components: {
Layout: {
siderBg: dark ? "#141414" : "#ffffff",
headerBg: dark ? "#141414" : "#ffffff",
headerHeight: 64,
},
Card: {
headerHeight: 56,
},
},
};
}
/** # 函数
* 读取本地存储的主题偏好(默认亮色)
*/
export function loadDarkMode(): boolean {
try {
return localStorage.getItem(THEME_STORAGE_KEY) === "dark";
} catch {
return false;
}
}
/** # 函数
* 持久化主题偏好并同步 <html data-theme>(供 styles.css 暗色覆盖)
*/
export function applyDarkMode(dark: boolean): void {
try {
localStorage.setItem(THEME_STORAGE_KEY, dark ? "dark" : "light");
} catch {
// 隐私模式等场景忽略
}
document.documentElement.dataset.theme = dark ? "dark" : "light";
}
-3
View File
@@ -6,7 +6,6 @@
* /api/auth/* 用户登录/登出/会话(cookie)
* /api/accounts|domains|mailboxes|emails 管理资源 CRUD(会话保护)
* /api/settings/* 设置:全局 Webhook / 改密码(会话保护)
* /api/keys/* API/MCP Key 管理(会话保护;设置模态窗口内使用)
* /api/oauth/* Cloudflare OAuth(会话保护)
* /api/admin/* 版本/统计/Cron(会话保护)
* /internal/email/* Email Worker 内部协议:authorize / ingest(HMAC 签名,docs/11)
@@ -23,7 +22,6 @@ import { authRoutes } from "./auth.ts";
import { internalRoutes } from "./routes/internal.ts";
import { resourceRoutes } from "./routes/resources.ts";
import { settingsRoutes } from "./routes/settings.ts";
import { keyRoutes } from "./routes/keys.ts";
import { oauthRoutes } from "./routes/oauth.ts";
import { apiV1Routes } from "./routes/apiv1.ts";
import { mcpRoutes } from "./routes/mcp.ts";
@@ -55,7 +53,6 @@ export function createApp(
app.route("/internal", internalRoutes());
app.route("/api/oauth", oauthRoutes());
app.route("/api/settings", settingsRoutes());
app.route("/api/keys", keyRoutes());
app.route("/api/admin", adminRoutes());
app.route("/api/v1/mcp", mcpRoutes());
app.route("/api/v1", apiV1Routes());
-3
View File
@@ -75,9 +75,6 @@ export interface ScheduledEvent {
export interface AppVars {
/** 已登录用户 ID(cookie 会话) **/
userId?: string;
/** 已认证 API/MCP Key 信息 **/
apiKeyKind?: "api" | "mcp";
apiKeyId?: string;
/** internal 路由中已读出的原始请求体(workerAuth 中间件缓存) **/
rawBody?: Uint8Array;
/** internal 路由中通过校验的 worker credential id **/
+24 -49
View File
@@ -1,12 +1,10 @@
/**
* Console 中间件:会话守卫、API/MCP Key 守卫、CSRF Origin 校验。
* Console 中间件:会话守卫、API/MCP Key 守卫(单一 Key)、CSRF Origin 校验。
*/
import type { Env } from "./env.ts";
import type { AppVars } from "./env.ts";
import type { Env, AppVars } from "./env.ts";
import { readSessionCookie, verifySessionToken } from "./auth.ts";
import { keyHash } from "./db.ts";
import { nowIso } from "./util.ts";
import { getSetting, keyHash } from "./db.ts";
import type { Context, Next } from "hono";
type Ctx = Context<{ Bindings: Env; Variables: AppVars }>;
@@ -43,56 +41,33 @@ export async function csrfOriginCheck(c: Ctx, next: Next) {
}
/** # 函数
* API/MCP Key 守卫工厂:校验 Authorization: Bearer wmh_... 并限定 kind。
* 通过后 c.set("apiKeyKind"/"apiKeyId")。
* 参数: kind - 允许的凭据类型
* API/MCP Key 守卫:校验 Authorization: Bearer wmh_...(settings 表单一 Key)。
* API 与 MCP 共用同一 Key(docs/07 v2.1.0),不再区分 kind。
*/
export function requireApiKey(kind: "api" | "mcp") {
return async (c: Ctx, next: Next) => {
const auth = c.req.header("Authorization") ?? "";
const m = /^Bearer\s+(.+)$/i.exec(auth);
const key = m?.[1]?.trim();
if (!key || !key.startsWith("wmh_")) {
return c.json({ error: "missing or invalid api key" }, 401);
}
const row = await c.env.DB.prepare(
"SELECT id, kind, revoked_at FROM api_credentials WHERE key_hash = ?",
)
.bind(await keyHash(key))
.first<{ id: string; kind: string; revoked_at: string | null }>();
if (!row || row.revoked_at) return c.json({ error: "invalid or revoked api key" }, 401);
if (row.kind !== kind) {
return c.json({ error: `this endpoint requires a ${kind} key` }, 403);
}
c.set("apiKeyKind", row.kind as "api" | "mcp");
c.set("apiKeyId", row.id);
// 记录最近使用时间(尽力而为,不阻塞请求;本地运行时无 ExecutionContext 时直接后台执行)
const touch = c.env.DB.prepare("UPDATE api_credentials SET last_used_at = ? WHERE id = ?")
.bind(nowIso(), row.id)
.run();
try {
c.executionCtx.waitUntil(touch);
} catch {
void touch;
}
await next();
};
export async function requireApiKey(c: Ctx, next: Next) {
const key = await bearerKey(c.req.raw);
if (!key) return c.json({ error: "missing or invalid api key" }, 401);
if (!(await verifyApiKey(c.env, key))) return c.json({ error: "invalid or revoked api key" }, 401);
await next();
}
/** # 函数
* 解析并校验 Bearer Key(返回凭据行);供 /api/v1 统一入口使用
* 校验 Bearer Key 是否为 settings 表中的单一 Key
* 参数: env - 运行环境;key - 明文 Key
* 返回值: 有效 true,否则 false
*/
export async function resolveApiKey(
env: Env,
request: Request,
): Promise<{ ok: true; id: string; kind: "api" | "mcp" } | { ok: false; status: number; error: string }> {
export async function verifyApiKey(env: Env, key: string): Promise<boolean> {
const hash = await getSetting(env, "api_key_hash");
if (!hash) return false;
return hash === (await keyHash(key));
}
/** # 函数
* 从 Authorization 头解析 Bearer Key(须 wmh_ 前缀)
*/
async function bearerKey(request: Request): Promise<string | null> {
const auth = request.headers.get("Authorization") ?? "";
const m = /^Bearer\s+(.+)$/i.exec(auth);
const key = m?.[1]?.trim();
if (!key || !key.startsWith("wmh_")) return { ok: false, status: 401, error: "missing or invalid api key" };
const row = await env.DB.prepare("SELECT id, kind, revoked_at FROM api_credentials WHERE key_hash = ?")
.bind(await keyHash(key))
.first<{ id: string; kind: string; revoked_at: string | null }>();
if (!row || row.revoked_at) return { ok: false, status: 401, error: "invalid or revoked api key" };
return { ok: true, id: row.id, kind: row.kind as "api" | "mcp" };
return key && key.startsWith("wmh_") ? key : null;
}
+1 -1
View File
@@ -45,7 +45,7 @@ export function adminRoutes(): App {
worker_credentials: await count("SELECT COUNT(*) AS n FROM worker_credentials WHERE status = 'active'"),
};
const recent = await c.env.DB.prepare(
`SELECT id, subject, from_address, received_at, size FROM emails
`SELECT id, subject, from_address, to_addresses, received_at, size FROM emails
WHERE expires_at > ? ORDER BY received_at DESC LIMIT 8`,
)
.bind(now)
+1 -1
View File
@@ -16,7 +16,7 @@ type App = Hono<{ Bindings: Env; Variables: AppVars }>;
*/
export function apiV1Routes(): App {
const app = new Hono<{ Bindings: Env; Variables: AppVars }>();
app.use("*", requireApiKey("api"));
app.use("*", requireApiKey);
/** 账号列表 */
app.get("/accounts", async (c) => {
-66
View File
@@ -1,66 +0,0 @@
/**
* Console API / MCP 凭据管理路由。
* Key 规范:wmh_ 开头 + 随机串,总长 32;库中只存 SHA-256,明文仅创建时返回一次。
*/
import { Hono } from "hono";
import type { Env, AppVars } from "../env.ts";
import { requireSession } from "../middleware.ts";
import { generateWmailKey, isValidWmailKey } from "../../../shared/src/index.ts";
import { keyHash } from "../db.ts";
import { ids } from "../../../shared/src/index.ts";
import { nowIso, readJson } from "../util.ts";
type App = Hono<{ Bindings: Env; Variables: AppVars }>;
/** # 函数
* 装配 API/MCP Key 管理路由(会话保护)
*/
export function keyRoutes(): App {
const app = new Hono<{ Bindings: Env; Variables: AppVars }>();
app.use("*", requireSession);
/** 列表(仅前 4 位尾缀,不返回明文) */
app.get("/", async (c) => {
const rows = await c.env.DB.prepare(
`SELECT id, kind, name, key_last4, created_at, revoked_at, last_used_at
FROM api_credentials ORDER BY created_at DESC`,
).all();
return c.json({ items: rows.results });
});
/** 生成新 Key(kind = api | mcp) */
app.post("/", async (c) => {
const body = await readJson<{ kind?: string; name?: string }>(c.req.raw);
const kind = body.kind === "mcp" ? "mcp" : body.kind === "api" ? "api" : null;
if (!kind) return c.json({ error: "kind must be api or mcp" }, 400);
const key = generateWmailKey();
if (!isValidWmailKey(key)) return c.json({ error: "key generator broken" }, 500);
const id = ids.apiKey();
await c.env.DB.prepare(
"INSERT INTO api_credentials (id, kind, name, key_hash, key_last4, created_at) VALUES (?, ?, ?, ?, ?, ?)",
)
.bind(id, kind, (body.name ?? "").trim() || (kind === "api" ? "Console API Key" : "Console MCP Key"), await keyHash(key), key.slice(-4), nowIso())
.run();
return c.json({ ok: true, id, kind, key }, 201);
});
/** 撤销 Key */
app.post("/:id/revoke", async (c) => {
const id = c.req.param("id");
const res = await c.env.DB.prepare("UPDATE api_credentials SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL")
.bind(nowIso(), id)
.run();
if (!res.meta?.changes) return c.json({ error: "not found or already revoked" }, 404);
return c.json({ ok: true });
});
/** 彻底删除 Key 记录 */
app.delete("/:id", async (c) => {
const id = c.req.param("id");
await c.env.DB.prepare("DELETE FROM api_credentials WHERE id = ?").bind(id).run();
return c.json({ ok: true });
});
return app;
}
+1 -1
View File
@@ -80,7 +80,7 @@ const TOOLS = [
export function mcpRoutes(): App {
const app = new Hono<{ Bindings: Env; Variables: AppVars }>();
app.use("*", requireApiKey("mcp"));
app.use("*", requireApiKey);
app.post("/", async (c) => {
const rpc = await readJson<JsonRpcRequest>(c.req.raw);
+5
View File
@@ -348,6 +348,7 @@ function installEmailRoutes(app: App) {
const url = new URL(c.req.url);
const { limit, offset } = pageParams(url);
const mailboxId = url.searchParams.get("mailbox_id");
const domainId = url.searchParams.get("domain_id");
const q = url.searchParams.get("q");
const conds: string[] = [];
const binds: unknown[] = [];
@@ -355,6 +356,10 @@ function installEmailRoutes(app: App) {
conds.push("mailbox_id = ?");
binds.push(mailboxId);
}
if (domainId) {
conds.push("m.domain_id = ?");
binds.push(domainId);
}
if (q) {
conds.push("(subject LIKE ? OR from_address LIKE ?)");
binds.push(`%${q}%`, `%${q}%`);
+46 -7
View File
@@ -1,16 +1,24 @@
/**
* 设置路由(v2.0.0):
* GET /api/settings 读取:全局 Webhook / 当前用户
* PUT /api/settings 保存:全局 Webhook
* PUT /api/settings/password 修改登录密码
* API/MCP Key 管理沿用 /api/keys(前端设置模态窗口内调用)。
* 设置路由(v2.1.0):
* GET /api/settings 读取:全局 Webhook / API Key 元信息 / 当前用户
* PUT /api/settings 保存:全局 Webhook
* POST /api/settings/api-key 生成(轮换)单一 API/MCP Key,明文仅返回一次
* DEL /api/settings/api-key 撤销并删除 API Key
* PUT /api/settings/password 修改登录密码
* API 与 MCP 共用同一 Key,凭据存 settings 表(不再单独建表)。
*/
import { Hono } from "hono";
import type { Env, AppVars } from "../env.ts";
import { requireSession } from "../middleware.ts";
import { checkWebhookUrl, hashPassword, verifyPassword } from "../../../shared/src/index.ts";
import { getSetting } from "../db.ts";
import {
checkWebhookUrl,
generateWmailKey,
hashPassword,
isValidWmailKey,
verifyPassword,
} from "../../../shared/src/index.ts";
import { getSetting, keyHash, setSetting } from "../db.ts";
import {
getGlobalWebhookKey,
normalizeWebhookHeaders,
@@ -20,6 +28,17 @@ import { nowIso, readJson } from "../util.ts";
type App = Hono<{ Bindings: Env; Variables: AppVars }>;
/** # 函数
* 读取 API Key 元信息(只有 last4,无明文)
*/
async function apiKeyMeta(env: Env): Promise<{ has_key: boolean; key_last4: string; created_at: string | null }> {
const [last4, createdAt] = await Promise.all([
getSetting(env, "api_key_last4"),
getSetting(env, "api_key_created_at"),
]);
return { has_key: Boolean(last4), key_last4: last4 ?? "", created_at: createdAt ?? null };
}
/** # 函数
* 装配设置路由(会话保护)
*/
@@ -50,6 +69,7 @@ export function settingsRoutes(): App {
return c.json({
username: user?.username ?? "",
webhook,
api_key: await apiKeyMeta(c.env),
});
});
@@ -83,6 +103,25 @@ export function settingsRoutes(): App {
return c.json({ ok: true });
});
/** 生成(轮换)API/MCP Key:明文仅本次返回;旧 Key 立即失效 */
app.post("/api-key", async (c) => {
const key = generateWmailKey();
if (!isValidWmailKey(key)) return c.json({ error: "key generator broken" }, 500);
const createdAt = nowIso();
await setSetting(c.env, "api_key_hash", await keyHash(key));
await setSetting(c.env, "api_key_last4", key.slice(-4));
await setSetting(c.env, "api_key_created_at", createdAt);
return c.json({ ok: true, key, created_at: createdAt }, 201);
});
/** 撤销并删除 API Key */
app.delete("/api-key", async (c) => {
for (const k of ["api_key_hash", "api_key_last4", "api_key_created_at"]) {
await c.env.DB.prepare("DELETE FROM settings WHERE key = ?").bind(k).run();
}
return c.json({ ok: true });
});
/** 修改登录密码 */
app.put("/password", async (c) => {
const body = await readJson<{ old_password?: string; new_password?: string }>(c.req.raw);
+9 -2
View File
@@ -11,6 +11,7 @@
import PostalMime from "postal-mime";
import type { Env } from "../env.ts";
import {
htmlToMarkdown,
ids,
DEFAULT_RETENTION_SECONDS,
MAX_EMAIL_BYTES,
@@ -159,11 +160,16 @@ export async function ingestEmail(env: Env, input: IngestInput): Promise<IngestR
});
}
// Markdown 正文:HTML 优先转换,其次纯文本(mailhook 同思路;webhook 投递使用)
const markdownBody = parsed?.html
? htmlToMarkdown(parsed.html)
: (parsed?.text ?? "");
// 入库
await env.DB.prepare(
`INSERT INTO emails (id, account_id, mailbox_id, message_id, from_address, to_addresses, cc_addresses,
subject, text_body, html_body, raw_storage_key, size, received_at, expires_at, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
subject, text_body, html_body, markdown_body, raw_storage_key, size, received_at, expires_at, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.bind(
emailId,
@@ -176,6 +182,7 @@ export async function ingestEmail(env: Env, input: IngestInput): Promise<IngestR
parsed?.subject ?? "(unparsable mail)",
parsed?.text ?? null,
parsed?.html ?? null,
markdownBody || null,
rawKey,
input.raw.byteLength,
receivedAt,
+13 -1
View File
@@ -22,6 +22,7 @@ import {
WEBHOOK_MAX_ATTEMPTS,
WEBHOOK_RETRY_BASE_MS,
} from "../../../shared/src/index.ts";
import { htmlToMarkdown } from "../../../shared/src/index.ts";
import { encryptSecret, decryptSecret, getAesKey, getSetting, setSetting } from "../db.ts";
import { nowIso } from "../util.ts";
@@ -211,6 +212,8 @@ export function buildWebhookPayload(email: {
toAddresses: string;
subject: string | null;
textBody: string | null;
htmlBody: string | null;
markdownBody: string | null;
receivedAt: string;
}): Record<string, unknown> {
return {
@@ -221,6 +224,11 @@ export function buildWebhookPayload(email: {
to: safeParseArray(email.toAddresses),
subject: email.subject,
text: email.textBody,
// Markdown 正文(HTML 转换优先,纯文本兜底);v2.1.0 新增
markdown:
email.markdownBody ??
(email.htmlBody ? htmlToMarkdown(email.htmlBody) : null) ??
email.textBody,
received_at: email.receivedAt,
};
}
@@ -305,6 +313,8 @@ interface DueDeliveryRow {
to_addresses: string;
subject: string | null;
text_body: string | null;
html_body: string | null;
markdown_body: string | null;
received_at: string;
expires_at: string;
}
@@ -323,7 +333,7 @@ export async function processDueDeliveries(
const due = await env.DB.prepare(
`SELECT d.id AS delivery_id, d.url, d.headers, d.key_enc, d.attempt_count,
e.id AS email_id, e.mailbox_id, e.from_address, e.to_addresses, e.subject, e.text_body,
e.received_at, e.expires_at
e.html_body, e.markdown_body, e.received_at, e.expires_at
FROM webhook_deliveries d
JOIN emails e ON e.id = d.email_id
WHERE d.status IN ('pending', 'failed')
@@ -362,6 +372,8 @@ export async function processDueDeliveries(
toAddresses: row.to_addresses,
subject: row.subject,
textBody: row.text_body,
htmlBody: row.html_body,
markdownBody: row.markdown_body,
receivedAt: row.received_at,
});
const result = await attemptDelivery(