/** Cloudflare OAuth(本地 sim 模式)测试:Connect Account 自动接入、域名同步、state CSRF、setup Email Workers、Worker 凭据 */ import { describe, expect, test } from "bun:test"; import { authedFetch, loginCookie, makeTestEnv } from "./helpers.ts"; describe("Cloudflare OAuth(sim 模式,Connect Cloudflare Account)", () => { test("start 自动建账号;approve 完成自动接入并同步域名;setup 配置 Email Workers", async () => { const t = await makeTestEnv(); const cookie = await loginCookie(t); // Connect Cloudflare Account:start 自动创建账号记录 const start = (await ( await authedFetch(t, cookie, "http://localhost/api/oauth/cloudflare/start") ).json()) as { url: string; state: string }; expect(start.url).toContain("/oauth/sim/authorize?state="); // sim approve(等价于用户在 Cloudflare 授权页点击同意) const approve = (await ( await authedFetch(t, cookie, "http://localhost/api/oauth/cloudflare/sim/approve", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ state: start.state }), }) ).json()) as { ok: boolean; error?: string; account_id: string }; expect(approve.ok).toBe(true); // 接入结果:发现 + 域名同步 + Email Worker 部署 + Worker 凭据签发 const detail = (await ( await authedFetch(t, cookie, `http://localhost/api/accounts/${approve.account_id}`) ).json()) as { account: { status: string; cloudflare_account_id: string | null; name: string; worker_id: string | null }; steps: Record; domains: { name: string }[]; credential: { worker_id: string; secret_last4: string; status: string } | null; }; expect(detail.account.status).toBe("active"); // 接入完成(无心跳概念) expect(detail.account.cloudflare_account_id).toBe("sim-account-0001"); expect(detail.account.name).toBe("WmailHub Sim Account"); // 自动命名替换为 CF 账户名 for (const key of ["oauth", "discover", "domains", "worker"]) { expect(detail.steps[key].status).toBe("done"); } expect(detail.account.worker_id).toContain("wmailhub-email-"); // Worker credential 已签发(库中不存明文 secret) expect(detail.credential).not.toBeNull(); expect(detail.credential!.worker_id).toBe(detail.account.worker_id!); const credRow = await t.env.DB.prepare( "SELECT secret_hash, secret_enc, secret_last4 FROM worker_credentials WHERE cloudflare_account_id = ?", ) .bind(approve.account_id) .first<{ secret_hash: string; secret_enc: string; secret_last4: string }>(); expect(credRow?.secret_enc).toBeTruthy(); expect(credRow!.secret_last4.length).toBe(4); // OAuth 只同步域名,Email Routing 按域名手动触发 expect(detail.domains.map((d) => d.name)).toEqual( expect.arrayContaining(["example.test", "demo.test", "mailbox.dev"]), ); const domList = (await ( await authedFetch(t, cookie, "http://localhost/api/domains") ).json()) as { items: { id: string; name: string; status: string; account_id: string | null }[] }; // 种子环境自带一个 cfacct-1 下的 example.test(active);OAuth 同步出的新域名均为 pending const synced = domList.items.filter((d) => ["demo.test", "mailbox.dev"].includes(d.name)); expect(synced.length).toBe(2); for (const d of synced) expect(d.status).toBe("pending"); // catch-all 邮箱已随同步创建 const mb = await t.env.DB.prepare("SELECT address FROM mailboxes WHERE is_catch_all = 1").all<{ address: string }>(); expect(mb.results.map((r) => r.address)).toContain("*@example.test"); // setup:为同步出的 example.test 配置 Email Workers(Worker 幂等重部署 + Routing + catch-all 规则) const example = domList.items.find((d) => d.name === "example.test" && d.status === "pending")!; const setup = (await ( await authedFetch(t, cookie, `http://localhost/api/domains/${example.id}/setup`, { method: "POST" }) ).json()) as { ok: boolean; error?: string }; expect(setup.ok).toBe(true); const after = (await ( await authedFetch(t, cookie, "http://localhost/api/domains") ).json()) as { items: { id: string; name: string; status: string; worker_id: string | null }[] }; const exampleAfter = after.items.find((d) => d.id === example.id)!; expect(exampleAfter.status).toBe("active"); expect(exampleAfter.worker_id).toContain("wmailhub-email-"); // sim 资源记录(Email Worker / Routing rule 只在 setup 后出现) const sim = await t.env.DB.prepare("SELECT kind FROM cf_sim_resources").all<{ kind: string }>(); const kinds = sim.results.map((r) => r.kind); expect(kinds).toContain("zone"); expect(kinds).toContain("email_worker"); expect(kinds).toContain("routing_rule"); // OAuth token 已加密入库(不含明文 token) const conn = await t.env.DB.prepare("SELECT encrypted_access_token FROM oauth_connections").first<{ encrypted_access_token: string; }>(); expect(conn?.encrypted_access_token).toBeTruthy(); expect(conn!.encrypted_access_token.startsWith("sim_")).toBe(false); }); test("state 一次性:重放 approve 被拒(OAuth CSRF 防护)", async () => { const t = await makeTestEnv(); const cookie = await loginCookie(t); const { state } = (await ( await authedFetch(t, cookie, "http://localhost/api/oauth/cloudflare/start") ).json()) as { state: string }; const first = await authedFetch(t, cookie, "http://localhost/api/oauth/cloudflare/sim/approve", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ state }), }); expect(first.status).toBe(200); // state 已消费,重放被拒 const second = await authedFetch(t, cookie, "http://localhost/api/oauth/cloudflare/sim/approve", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ state }), }); expect(second.status).toBe(400); }); test("伪造/过期 state 被拒;真实 callback 端点同样拒绝", async () => { const t = await makeTestEnv(); const cookie = await loginCookie(t); const bad = await authedFetch(t, cookie, "http://localhost/api/oauth/cloudflare/sim/approve", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ state: "cfstate_forged" }), }); expect(bad.status).toBe(400); const cb = await authedFetch(t, cookie, "http://localhost/api/oauth/cloudflare/callback?code=x&state=forged"); expect(cb.status).toBe(400); }); test("rotate:Worker credential 轮换,secret 仅本次可见且已配置域名自动重部署", async () => { const t = await makeTestEnv(); const cookie = await loginCookie(t); // 自动接入一个账号(approve 走完 worker 步骤:部署 + 签发凭据) await authedFetch(t, cookie, "http://localhost/api/oauth/cloudflare/start"); const start = (await ( await authedFetch(t, cookie, "http://localhost/api/oauth/cloudflare/start") ).json()) as { state: string }; const approve = (await ( await authedFetch(t, cookie, "http://localhost/api/oauth/cloudflare/sim/approve", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ state: start.state }), }) ).json()) as { ok: boolean; account_id: string }; const accountId = approve.account_id; const rotated = (await ( await authedFetch(t, cookie, `http://localhost/api/accounts/${accountId}/rotate`, { method: "POST" }) ).json()) as { ok: boolean; worker_id: string; secret: string; redeployed: string[] }; expect(rotated.ok).toBe(true); expect(rotated.secret.startsWith("whs_")).toBe(true); // 库中不存明文 secret;旧 credential 已撤销,新 credential 生效 const creds = await t.env.DB.prepare( "SELECT status FROM worker_credentials WHERE cloudflare_account_id = ?", ) .bind(accountId) .all<{ status: string }>(); expect(creds.results.filter((r) => r.status === "active").length).toBe(1); expect(creds.results.filter((r) => r.status === "revoked").length).toBe(1); }); test("旧 Node 协议接口已移除(/api/internal/enroll 不再可用)", async () => { const t = await makeTestEnv(); // 该路径已无路由;管理面中间件按未授权拒绝,不会返回 enrollment 结果 const resp = await t.app.fetch( new Request("http://localhost/api/internal/enroll", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ enrollment_token: "wenr_x" }), }), t.env, ); expect(resp.status).toBe(401); }); });