- 根因:Cloudflare OAuth 的 scope 是点号分隔(account.read),冒号写法不被接受, 授权端点直接返回 error=invalid_scope。默认 scope 改为 account.read zone.read email_routing.write workers_scripts.write - scope 可在设置页自定义(settings.cf_oauth_scopes),需与 App 登记值逐字一致 - 新增 GET /api/oauth/cloudflare/preflight + 设置页「检测授权配置」按钮: 只读探测授权端点(不跟随跳转),区分 登录同意页 / 弹回回调 / Cloudflare /oauth/error, 并把 invalid_scope、invalid_request 翻译成可执行的处置建议 - 回调端点处理 error 参数:不再拿空 code 去兑换 token,改为跳回账号页并弹窗说明原因 (此前会落到 SPA 404 空壳页) - 账号页读取 ?oauth_error= 弹窗展示 Cloudflare 的原始描述 - docs/02 补 Cloudflare OAuth App 配置清单(Redirect URL / Client URI 域名校验 / Promote to public / 点号 scope);83 个测试全通过
130 lines
5.2 KiB
TypeScript
130 lines
5.2 KiB
TypeScript
/**
|
|
* Cloudflare API 抓包桩(仅测试用):
|
|
* 拦截 globalThis.fetch,对 dash.cloudflare.com / api.cloudflare.com 返回固定响应,
|
|
* 并记录真实发出的 HTTP 调用。生产代码里没有任何模拟实现——接入链路跑的始终是
|
|
* RealCFApi,测试只是在传输层把它要访问的 Cloudflare 换成本地桩。
|
|
*/
|
|
|
|
/** # 成员变量: 记录到的 Cloudflare API 调用 **/
|
|
export interface CfCall {
|
|
/** 请求方法 **/
|
|
method: string;
|
|
/** 完整 URL **/
|
|
url: string;
|
|
/** 路径(去掉 base) **/
|
|
path: string;
|
|
/** Authorization 头(OAuth Bearer token) **/
|
|
authorization: string | null;
|
|
/** 请求体文本(URL 编码或 JSON);multipart 上传记 null **/
|
|
body: string | null;
|
|
}
|
|
|
|
/** # 成员变量: 桩的返回数据配置 **/
|
|
export interface CfMockOptions {
|
|
/** /accounts 返回的账户列表 **/
|
|
accounts?: { id: string; name: string }[];
|
|
/** /zones 返回的域名列表 **/
|
|
zones?: { id: string; name: string; account_id: string; status: string }[];
|
|
/** OAuth token 端点签发的 access token **/
|
|
accessToken?: string;
|
|
/** token 端点 HTTP 状态(测失败分支用) **/
|
|
tokenStatus?: number;
|
|
/** 授权端点(dash.cloudflare.com/oauth2/auth)的 Location 跳转目标;不传则跳登录页 **/
|
|
authorizeRedirect?: string;
|
|
}
|
|
|
|
/** # 成员变量: Cloudflare API 桩句柄 **/
|
|
export interface CfMock {
|
|
/** 已记录的调用 **/
|
|
calls: CfCall[];
|
|
/** 恢复原始 fetch **/
|
|
restore(): void;
|
|
/** 是否发生过指定 method + 路径子串的调用 **/
|
|
hit(method: string, pathPart: string): boolean;
|
|
/** 取出第一条匹配调用的 body **/
|
|
bodyOf(method: string, pathPart: string): string | null;
|
|
}
|
|
|
|
const TOKEN_URL = "https://dash.cloudflare.com/oauth2/token";
|
|
const CF_AUTHORIZE_URL = "https://dash.cloudflare.com/oauth2/auth";
|
|
const API_BASE = "https://api.cloudflare.com/client/v4";
|
|
|
|
/** # 函数
|
|
* 安装 Cloudflare API 桩:接管 globalThis.fetch,返回记录与恢复句柄
|
|
* 参数: opts.accounts/zones 决定发现到的资源,tokenStatus 可模拟 token 兑换失败
|
|
*/
|
|
export function installCloudflareMock(opts: CfMockOptions = {}): CfMock {
|
|
const accounts = opts.accounts ?? [{ id: "cf-acct-real-1", name: "Real Cloudflare Account" }];
|
|
const zones = opts.zones ?? [
|
|
{ id: "zone-example", name: "example.com", account_id: accounts[0]?.id ?? "", status: "active" },
|
|
{ id: "zone-demo", name: "demo.com", account_id: accounts[0]?.id ?? "", status: "active" },
|
|
];
|
|
const accessToken = opts.accessToken ?? "cf-oauth-access-token-xyz";
|
|
const calls: CfCall[] = [];
|
|
const original = globalThis.fetch;
|
|
|
|
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
|
|
const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
|
const method = (init?.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase();
|
|
const headers = new Headers(
|
|
init?.headers ?? (input instanceof Request ? input.headers : undefined),
|
|
);
|
|
const rawBody = init?.body;
|
|
const body =
|
|
typeof rawBody === "string"
|
|
? rawBody
|
|
: rawBody instanceof URLSearchParams
|
|
? rawBody.toString()
|
|
: null;
|
|
|
|
calls.push({
|
|
method,
|
|
url,
|
|
path: url.startsWith(API_BASE) ? url.slice(API_BASE.length) : url,
|
|
authorization: headers.get("authorization"),
|
|
// multipart 上传(Email Worker 脚本)读不出文本,只记方法与路径
|
|
body: rawBody instanceof FormData ? null : body,
|
|
});
|
|
|
|
const json = (result: unknown, status = 200) =>
|
|
new Response(JSON.stringify({ success: true, errors: [], messages: [], result }), {
|
|
status,
|
|
headers: { "Content-Type": "application/json" },
|
|
});
|
|
|
|
if (url.startsWith(CF_AUTHORIZE_URL)) {
|
|
const target = opts.authorizeRedirect ?? "https://dash.cloudflare.com/login";
|
|
return new Response(null, { status: 302, headers: { Location: target } });
|
|
}
|
|
if (url === TOKEN_URL) {
|
|
if ((opts.tokenStatus ?? 200) !== 200) {
|
|
return new Response(JSON.stringify({ error: "invalid_grant" }), { status: opts.tokenStatus });
|
|
}
|
|
// OAuth token 端点是裸 JSON(不是 Cloudflare API 的 {success,result} 信封)
|
|
return new Response(JSON.stringify({ access_token: accessToken, expires_in: 3600, token_type: "bearer" }), {
|
|
status: 200,
|
|
headers: { "Content-Type": "application/json" },
|
|
});
|
|
}
|
|
if (url.startsWith(`${API_BASE}/accounts`)) return json(accounts);
|
|
if (url.startsWith(`${API_BASE}/zones`)) {
|
|
if (url.includes("/email/routing/rules/catch_all")) return json({ id: "catch-all-rule" });
|
|
if (url.includes("/email/routing")) return json({ enabled: true });
|
|
return json(zones);
|
|
}
|
|
if (url.includes("/workers/scripts/")) return json({ id: url.split("/").pop() });
|
|
return json(null, 404);
|
|
}) as typeof globalThis.fetch;
|
|
|
|
return {
|
|
calls,
|
|
restore: () => {
|
|
globalThis.fetch = original;
|
|
},
|
|
hit: (method, pathPart) =>
|
|
calls.some((c) => c.method === method.toUpperCase() && c.path.includes(pathPart)),
|
|
bodyOf: (method, pathPart) =>
|
|
calls.find((c) => c.method === method.toUpperCase() && c.path.includes(pathPart))?.body ?? null,
|
|
};
|
|
}
|