feat: v1.1.0 账号化重构 + 三级 Webhook + 设置中心 + Vite 工具链

- 账号化:节点更名账号,/nodes -> /accounts;添加账号直达 Cloudflare OAuth,自动创建账号并同步账号下全部域名(catch-all 邮箱随同步创建)
- 域名:移除手工添加;点击域名『设置 Email Workers』= 部署账号级 Email Worker + Email Routing + catch-all;支持按账号筛选
- Webhook 三级模型:邮箱 -> 域名 -> 全局,收信取第一个命中者;支持自定义请求头与 key(默认 Authorization: Bearer <key>,兼做 X-WmailHub-Signature 签名);独立 webhooks 实体与 /webhooks、/keys 页面删除,Key 管理收进设置模态窗口
- 设置中心:全局 Webhook / 默认 Node Ingress 地址 / 修改密码 / API & MCP Keys(生成、撤销、删除)
- UI:Header 标题副标题紧凑化(修复溢出),LOGO 加版本号 tag(v1.1.0 取自 package.json),各列表页搜索框
- 工具链:前端构建 Bun.build -> Vite(vite 8 + @vitejs/plugin-react)
- 后端:/api/settings、POST /api/domains/:id/setup、0002 迁移(投递行固化三级目标配置);MCP 去 list_webhooks(5 工具);迁移执行器加 _migrations 记录
- 测试:44/44(新增 settings 套件、webhook 三级优先级/SSRF/签名);UI 冒烟 11/11
This commit is contained in:
bigcode
2026-09-30 11:37:38 +08:00
parent d4c1334143
commit 421cfb2f04
47 changed files with 2316 additions and 1431 deletions
+97 -74
View File
@@ -1,28 +1,26 @@
/**
* Node 自动安装管线(docs/02 流程):
* Add Node(建 Node identity + credential) -> Cloudflare OAuth -> 授权回调 ->
* Account/Zone 发现 -> 创建/更新 Email Worker -> 配置 Email Routing ->
* 创建 Domain/Mailbox -> Node Ready。
* 账号(Node)自动安装管线(v1.1.0):
* 添加账号(建 Node identity + credential) -> Cloudflare OAuth -> 授权回调 ->
* Account/Zone 发现 -> 同步账号下全部域名(pending)+ catch-all 邮箱。
*
* 所有步骤幂等,重复执行不产生重复资源;每步状态写入 nodes.provision_steps,
* 供前端安装进度展示。全程不要求用户复制安装命令(docs/10 Phase 4)。
* Email Workers(Worker 部署 + Email Routing + catch-all 规则)不随 OAuth 自动执行,
* 而是在域名列表中按域名单独触发(setupDomainEmail),一个账号只部署一个 Email Worker。
*
* 所有步骤幂等,重复执行不产生重复资源;账号级步骤状态写入 nodes.provision_steps。
*/
import type { Env } from "../env.ts";
import { getCFApi, type CFApi } from "./cfapi.ts";
import { encryptSecret, decryptSecret } from "../db.ts";
import { encryptSecret, decryptSecret, decryptConnectionToken } from "../db.ts";
import { ids, sha256Hex, DEFAULT_RETENTION_SECONDS } from "../../../shared/src/index.ts";
import { nowIso } from "../util.ts";
/** # 成员变量: 安装步骤定义(顺序即展示顺序) **/
/** # 成员变量: 账号安装步骤定义(顺序即展示顺序) **/
export const PROVISION_STEPS = [
{ key: "oauth", label: "Cloudflare OAuth 授权" },
{ key: "identity", label: "Node identity 与 credential" },
{ key: "discover", label: "Account / Zone 发现" },
{ key: "email_worker", label: "Email Worker 创建/更新" },
{ key: "email_routing", label: "Email Routing 配置" },
{ key: "domains", label: "Domain 创建" },
{ key: "mailboxes", label: "Mailbox 创建" },
{ key: "domains", label: "域名与 catch-all 邮箱同步" },
] as const;
/** # 成员变量: 步骤状态 **/
@@ -38,14 +36,14 @@ export function initialSteps(): Record<string, { status: StepStatus; error?: str
}
/** # 函数
* Node 的 Email Worker 脚本名(幂等:同一 Node 固定同名)
* 账号的 Email Worker 脚本名(幂等:同一账号固定同名)
*/
export function emailWorkerNameFor(nodeId: string): string {
return `wmailhub-email-${nodeId.replace(/[^a-z0-9-]/gi, "-").toLowerCase()}`;
}
/** # 函数
* Add Node:创建 node 记录 + node credential(仅存摘要与密文)+ enrollment token。
* 添加账号:创建 node 记录 + node credential(仅存摘要与密文)+ enrollment token。
* 返回 enrollment token 供 Node bootstrap(本地由 dev 脚本自动完成,生产在 UI 展示一次)。
*/
export async function createNode(
@@ -70,7 +68,7 @@ export async function createNode(
nodeId,
opts.name,
opts.ingressUrl,
await encryptText(env, ingressSecret),
await encryptSecret(env, ingressSecret),
enrollmentToken,
new Date(Date.now() + 24 * 3600 * 1000).toISOString(),
JSON.stringify(initialSteps()),
@@ -117,7 +115,7 @@ export async function enrollNode(
.bind(credentialId, node.id, await sha256Hex(secret), await encryptSecret(env, secret), nowIso())
.run();
await env.DB.prepare(
"UPDATE nodes SET credential_id = ?, status = CASE WHEN status = 'pending_oauth' THEN status ELSE status END, updated_at = ? WHERE id = ?",
"UPDATE nodes SET credential_id = ?, updated_at = ? WHERE id = ?",
)
.bind(credentialId, nowIso(), node.id)
.run();
@@ -126,19 +124,11 @@ export async function enrollNode(
node_id: node.id,
credential_id: credentialId,
credential_secret: secret,
ingress_secret: await decryptText(env, node.ingress_secret_enc),
ingress_secret: await decryptSecret(env, node.ingress_secret_enc),
console_url: null,
};
}
async function encryptText(env: Env, text: string): Promise<string> {
return encryptSecret(env, text);
}
async function decryptText(env: Env, blob: string): Promise<string> {
return decryptSecret(env, blob);
}
/** # 成员变量: 授权完成后的完整安装流程参数 **/
export interface ProvisionInput {
nodeId: string;
@@ -147,17 +137,15 @@ export interface ProvisionInput {
}
/** # 函数
* OAuth 授权成功后的自动安装主流程(幂等,可重复调用)。
* 返回是否全部成功;失败时步骤状态里带 error。
* OAuth 授权成功后的自动安装主流程:发现账号 + 同步全部域名(pending)+ catch-all 邮箱。
* 幂等,可重复调用;返回是否全部成功;失败时步骤状态里带 error。
*/
export async function provisionNode(env: Env, input: ProvisionInput): Promise<{ ok: boolean; error?: string }> {
const cf: CFApi = getCFApi(env, env.DB);
const node = await env.DB.prepare(
"SELECT id, name, ingress_url, ingress_secret_enc FROM nodes WHERE id = ?",
)
const node = await env.DB.prepare("SELECT id, name FROM nodes WHERE id = ?")
.bind(input.nodeId)
.first<{ id: string; name: string; ingress_url: string; ingress_secret_enc: string }>();
if (!node) return { ok: false, error: "node not found" };
.first<{ id: string; name: string }>();
if (!node) return { ok: false, error: "account not found" };
const steps = await loadSteps(env, input.nodeId);
const mark = async (key: string, status: StepStatus, error?: string) => {
@@ -175,7 +163,7 @@ export async function provisionNode(env: Env, input: ProvisionInput): Promise<{
// 1. OAuth 授权
await mark("oauth", "done");
// 2. Node identity/credential(在 Add Node 与 enrollment 时完成)
// 2. Node identity/credential(在添加账号与 enrollment 时完成)
await mark("identity", "done");
// 3. Account/Zone 发现
@@ -185,47 +173,25 @@ export async function provisionNode(env: Env, input: ProvisionInput): Promise<{
const account = input.accountId
? accounts.find((a) => a.id === input.accountId) ?? accounts[0]
: accounts[0];
await env.DB.prepare("UPDATE nodes SET cloudflare_account_id = ?, updated_at = ? WHERE id = ?")
.bind(account.id, nowIso(), input.nodeId)
// 自动创建的账号以 Cloudflare 账户名命名
const newName = node.name.startsWith("Cloudflare 账号") ? account.name : node.name;
await env.DB.prepare("UPDATE nodes SET cloudflare_account_id = ?, name = ?, updated_at = ? WHERE id = ?")
.bind(account.id, newName, nowIso(), input.nodeId)
.run();
const zones = await cf.listZones(input.accessToken, account.id);
await mark("discover", "done");
// 4. Email Worker(幂等上传)
await mark("email_worker", "running");
const workerName = emailWorkerNameFor(input.nodeId);
const ingressSecret = await decryptText(env, node.ingress_secret_enc);
await cf.putEmailWorker({
accessToken: input.accessToken,
accountId: account.id,
scriptName: workerName,
ingressUrl: node.ingress_url,
ingressSecret,
});
await mark("email_worker", "done");
// 5+6. 每个 Zone:启用 Email Routing + catch-all -> Worker,并 upsert Domain
await mark("email_routing", "running");
// 4. 同步全部域名(pending,等待逐域名「设置 Email Workers」)+ catch-all 邮箱
await mark("domains", "running");
for (const zone of zones) {
await cf.enableEmailRouting({ accessToken: input.accessToken, zoneId: zone.id });
await cf.setCatchAllRule({
accessToken: input.accessToken,
zoneId: zone.id,
workerName,
});
await upsertDomain(env, {
cloudflareAccountId: account.id,
nodeId: input.nodeId,
name: zone.name,
zoneId: zone.id,
workerId: workerName,
workerId: null,
});
}
await mark("email_routing", "done");
await mark("domains", "done");
// 7. 每个 Domain 创建 catch-all Mailbox(*@domain)
await mark("mailboxes", "running");
const domainRows = await env.DB.prepare("SELECT id, name FROM domains WHERE node_id = ?")
.bind(input.nodeId)
.all<{ id: string; name: string }>();
@@ -236,7 +202,7 @@ export async function provisionNode(env: Env, input: ProvisionInput): Promise<{
isCatchAll: true,
});
}
await mark("mailboxes", "done");
await mark("domains", "done");
await env.DB.prepare("UPDATE nodes SET status = 'offline', updated_at = ? WHERE id = ?")
.bind(nowIso(), input.nodeId)
@@ -258,6 +224,56 @@ export async function provisionNode(env: Env, input: ProvisionInput): Promise<{
}
}
/** # 函数
* 为单个域名配置 Email Workers:部署账号级 Email Worker -> 开启 Email Routing ->
* catch-all 规则指向 Worker -> 域名置 active。幂等,失败信息写入 domains.setup_error。
*/
export async function setupDomainEmail(env: Env, domainId: string): Promise<{ ok: boolean; error?: string }> {
const domain = await env.DB.prepare(
"SELECT id, name, zone_id, node_id FROM domains WHERE id = ?",
)
.bind(domainId)
.first<{ id: string; name: string; zone_id: string | null; node_id: string | null }>();
if (!domain) return { ok: false, error: "domain not found" };
if (!domain.node_id || !domain.zone_id) return { ok: false, error: "domain not bound to a Cloudflare zone" };
const node = await env.DB.prepare(
"SELECT id, cloudflare_account_id, ingress_url, ingress_secret_enc FROM nodes WHERE id = ? AND status != 'revoked'",
)
.bind(domain.node_id)
.first<{ id: string; cloudflare_account_id: string | null; ingress_url: string; ingress_secret_enc: string }>();
if (!node?.cloudflare_account_id) return { ok: false, error: "account not connected via OAuth" };
const accessToken = await decryptConnectionToken(env);
if (!accessToken) return { ok: false, error: "no active Cloudflare OAuth connection" };
const cf: CFApi = getCFApi(env, env.DB);
try {
const workerName = emailWorkerNameFor(node.id);
await cf.putEmailWorker({
accessToken,
accountId: node.cloudflare_account_id,
scriptName: workerName,
ingressUrl: node.ingress_url,
ingressSecret: await decryptSecret(env, node.ingress_secret_enc),
});
await cf.enableEmailRouting({ accessToken, zoneId: domain.zone_id });
await cf.setCatchAllRule({ accessToken, zoneId: domain.zone_id, workerName });
await env.DB.prepare(
"UPDATE domains SET worker_id = ?, status = 'active', setup_error = NULL, updated_at = ? WHERE id = ?",
)
.bind(workerName, nowIso(), domainId)
.run();
return { ok: true };
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
await env.DB.prepare("UPDATE domains SET status = 'error', setup_error = ?, updated_at = ? WHERE id = ?")
.bind(message, nowIso(), domainId)
.run();
return { ok: false, error: message };
}
}
/** # 函数
* 读取并解析 node 的步骤状态
*/
@@ -274,7 +290,7 @@ export async function loadSteps(env: Env, nodeId: string) {
}
/** # 函数
* upsert Domain(按 account+name 幂等)
* upsert Domain(按 account+name 幂等)。无 workerId 时保持/置为 pending(待配置 Email Workers)。
*/
export async function upsertDomain(
env: Env,
@@ -283,28 +299,35 @@ export async function upsertDomain(
nodeId: string;
name: string;
zoneId: string;
workerId: string;
workerId: string | null;
},
): Promise<string> {
const existing = await env.DB.prepare(
"SELECT id FROM domains WHERE cloudflare_account_id = ? AND name = ?",
"SELECT id, worker_id FROM domains WHERE cloudflare_account_id = ? AND name = ?",
)
.bind(d.cloudflareAccountId, d.name)
.first<{ id: string }>();
.first<{ id: string; worker_id: string | null }>();
const now = nowIso();
if (existing) {
await env.DB.prepare(
"UPDATE domains SET node_id = ?, zone_id = ?, worker_id = ?, status = 'active', updated_at = ? WHERE id = ?",
)
.bind(d.nodeId, d.zoneId, d.workerId, now, existing.id)
.run();
// 已配置过 Worker 的域名不回退状态;仅当新配置带 worker 时更新
if (existing.worker_id || !d.workerId) {
await env.DB.prepare("UPDATE domains SET node_id = ?, zone_id = ?, updated_at = ? WHERE id = ?")
.bind(d.nodeId, d.zoneId, now, existing.id)
.run();
} else {
await env.DB.prepare(
"UPDATE domains SET node_id = ?, zone_id = ?, worker_id = ?, status = 'active', updated_at = ? WHERE id = ?",
)
.bind(d.nodeId, d.zoneId, d.workerId, now, existing.id)
.run();
}
return existing.id;
}
const id = ids.domain();
await env.DB.prepare(
"INSERT INTO domains (id, cloudflare_account_id, node_id, name, status, worker_id, zone_id, created_at, updated_at) VALUES (?, ?, ?, ?, 'active', ?, ?, ?, ?)",
"INSERT INTO domains (id, cloudflare_account_id, node_id, name, status, worker_id, zone_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
)
.bind(id, d.cloudflareAccountId, d.nodeId, d.name, d.workerId, d.zoneId, now, now)
.bind(id, d.cloudflareAccountId, d.nodeId, d.name, d.workerId ? "active" : "pending", d.workerId, d.zoneId, now, now)
.run();
return id;
}