pi-auto-web-search 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/LICENSE +21 -0
- package/README.md +195 -0
- package/README_EN.md +195 -0
- package/extensions/web-search.ts +18 -0
- package/package.json +56 -0
- package/src/adapters/anysearch.ts +107 -0
- package/src/adapters/cloudflare.ts +139 -0
- package/src/adapters/deepseek.ts +108 -0
- package/src/adapters/exa.ts +161 -0
- package/src/adapters/firecrawl.ts +202 -0
- package/src/adapters/index.ts +22 -0
- package/src/adapters/tavily.ts +148 -0
- package/src/adapters/tencent.ts +172 -0
- package/src/adapters/types.ts +122 -0
- package/src/adapters/util.ts +93 -0
- package/src/adapters/xai.ts +176 -0
- package/src/base-url.ts +40 -0
- package/src/cloudflare-oauth.ts +551 -0
- package/src/config.ts +547 -0
- package/src/http.ts +777 -0
- package/src/key-pool.ts +144 -0
- package/src/key-quota.ts +532 -0
- package/src/presets.ts +129 -0
- package/src/search-service.ts +411 -0
- package/src/secrets.ts +78 -0
- package/src/settings-ui.ts +1279 -0
- package/src/tools.ts +928 -0
|
@@ -0,0 +1,551 @@
|
|
|
1
|
+
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
closeSync,
|
|
4
|
+
existsSync,
|
|
5
|
+
mkdirSync,
|
|
6
|
+
openSync,
|
|
7
|
+
readFileSync,
|
|
8
|
+
renameSync,
|
|
9
|
+
unlinkSync,
|
|
10
|
+
writeFileSync,
|
|
11
|
+
} from "node:fs";
|
|
12
|
+
import { homedir } from "node:os";
|
|
13
|
+
import { dirname, join } from "node:path";
|
|
14
|
+
import { ConfigStore, type CloudflareOAuthConfig } from "./config.ts";
|
|
15
|
+
import { resolveSecret } from "./secrets.ts";
|
|
16
|
+
|
|
17
|
+
/** 默认令牌文件路径。 */
|
|
18
|
+
export const DEFAULT_TOKEN_PATH = join(homedir(), ".pi", "agent", "search-oauth.json");
|
|
19
|
+
|
|
20
|
+
/** 默认配置文件路径,登录后回填 accountId。 */
|
|
21
|
+
export const DEFAULT_CONFIG_PATH = join(homedir(), ".pi", "agent", "search.json");
|
|
22
|
+
|
|
23
|
+
/** 剩余寿命低于该秒数即刷新。 */
|
|
24
|
+
export const REFRESH_MARGIN_SECONDS = 60;
|
|
25
|
+
|
|
26
|
+
/** 授权链接与 code_verifier 的保留时长。 */
|
|
27
|
+
export const STATE_TTL_MS = 10 * 60 * 1000;
|
|
28
|
+
|
|
29
|
+
/** 账号列表端点,不在 cloudflareOAuth 配置里。 */
|
|
30
|
+
const DEFAULT_ACCOUNTS_URL = "https://api.cloudflare.com/client/v4/accounts";
|
|
31
|
+
|
|
32
|
+
/** 撤销端点,与授权端点同域。 */
|
|
33
|
+
const DEFAULT_REVOKE_URL = "https://dash.cloudflare.com/oauth2/revoke";
|
|
34
|
+
|
|
35
|
+
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
36
|
+
|
|
37
|
+
const REQUEST_ID_HEADERS = ["cf-ray", "x-request-id"];
|
|
38
|
+
|
|
39
|
+
/** 令牌文件内容,字段名与文件一致。 */
|
|
40
|
+
export interface OAuthToken {
|
|
41
|
+
access_token: string;
|
|
42
|
+
refresh_token: string;
|
|
43
|
+
/** 过期时间,epoch 秒。 */
|
|
44
|
+
expires_at: number;
|
|
45
|
+
scopes: string[];
|
|
46
|
+
account_id: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** OAuth 协议或流程错误;code 对齐上游 error 字段,消息里不带令牌。 */
|
|
50
|
+
export class OAuthError extends Error {
|
|
51
|
+
readonly code: string;
|
|
52
|
+
readonly status?: number;
|
|
53
|
+
readonly requestId?: string;
|
|
54
|
+
|
|
55
|
+
constructor(code: string, message: string, init: { status?: number; requestId?: string } = {}) {
|
|
56
|
+
super(message);
|
|
57
|
+
this.name = "OAuthError";
|
|
58
|
+
this.code = code;
|
|
59
|
+
this.status = init.status;
|
|
60
|
+
this.requestId = init.requestId;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** 一次登录的结果:令牌已落盘,accountId 回填情况一并带出。 */
|
|
65
|
+
export interface LoginResult {
|
|
66
|
+
token: OAuthToken;
|
|
67
|
+
/** 被写入 accountId 的实例 id。 */
|
|
68
|
+
updatedInstances: string[];
|
|
69
|
+
/** 账号查询或配置回填失败的原因,令牌仍然有效。 */
|
|
70
|
+
warning?: string;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** 一次登出的结果:远端撤销失败时本地令牌照样清除。 */
|
|
74
|
+
export interface LogoutResult {
|
|
75
|
+
token?: OAuthToken;
|
|
76
|
+
/** 远端撤销失败的原因。 */
|
|
77
|
+
warning?: string;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export interface CloudflareOAuthOptions {
|
|
81
|
+
/** 配置里的 cloudflareOAuth 段,授权链接与换发都用它。 */
|
|
82
|
+
config: CloudflareOAuthConfig;
|
|
83
|
+
tokenPath?: string;
|
|
84
|
+
configPath?: string;
|
|
85
|
+
fetch?: typeof globalThis.fetch;
|
|
86
|
+
/** 返回 epoch 毫秒。 */
|
|
87
|
+
clock?: () => number;
|
|
88
|
+
accountsUrl?: string;
|
|
89
|
+
revokeUrl?: string;
|
|
90
|
+
timeoutMs?: number;
|
|
91
|
+
env?: NodeJS.ProcessEnv;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
interface PendingLogin {
|
|
95
|
+
verifier: string;
|
|
96
|
+
createdAt: number;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** 32 字节随机数,base64url 无填充,共 43 个字符。 */
|
|
100
|
+
export function createCodeVerifier(): string {
|
|
101
|
+
return randomBytes(32).toString("base64url");
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** PKCE S256 挑战值。 */
|
|
105
|
+
export function codeChallenge(verifier: string): string {
|
|
106
|
+
return createHash("sha256").update(verifier).digest("base64url");
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** 解析粘贴的授权码或完整回调链接;带 state 时校验与本次授权一致。 */
|
|
110
|
+
export function parseAuthorizationCode(
|
|
111
|
+
raw: string,
|
|
112
|
+
expectedState?: string,
|
|
113
|
+
): { code: string; state?: string } {
|
|
114
|
+
const text = raw.trim();
|
|
115
|
+
if (!text) throw new OAuthError("invalid_code", "授权码不能为空");
|
|
116
|
+
|
|
117
|
+
let params: URLSearchParams | undefined;
|
|
118
|
+
if (/^https?:\/\//i.test(text)) {
|
|
119
|
+
try {
|
|
120
|
+
params = new URL(text).searchParams;
|
|
121
|
+
} catch {
|
|
122
|
+
throw new OAuthError("invalid_code", "回调链接格式无效,请粘贴授权码或完整回调 URL");
|
|
123
|
+
}
|
|
124
|
+
} else if (text.startsWith("?") || /(?:^|&)code=/.test(text)) {
|
|
125
|
+
params = new URLSearchParams(text.replace(/^\?/, ""));
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
if (!params) return { code: text };
|
|
129
|
+
|
|
130
|
+
const error = params.get("error")?.trim();
|
|
131
|
+
if (error) {
|
|
132
|
+
const desc = params.get("error_description")?.trim();
|
|
133
|
+
throw new OAuthError(error, desc ? `Cloudflare 拒绝授权(${error}):${desc}` : `Cloudflare 拒绝授权(${error})`);
|
|
134
|
+
}
|
|
135
|
+
const code = params.get("code")?.trim();
|
|
136
|
+
if (!code) throw new OAuthError("invalid_code", "回调链接缺少 code 参数,请粘贴完整链接或授权码");
|
|
137
|
+
|
|
138
|
+
const state = params.get("state")?.trim() || undefined;
|
|
139
|
+
if (expectedState && state && state !== expectedState) {
|
|
140
|
+
throw new OAuthError("invalid_state", "回调链接的 state 与本次授权不匹配,请重新发起登录");
|
|
141
|
+
}
|
|
142
|
+
return { code, state };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** 读取本地保存的 OAuth 令牌;缺失或损坏时返回 undefined。 */
|
|
146
|
+
export function readOAuthToken(path: string = DEFAULT_TOKEN_PATH): OAuthToken | undefined {
|
|
147
|
+
return readTokenFile(path);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** 授权链接;公共客户端只带 client_id 与 PKCE。 */
|
|
151
|
+
export function buildAuthorizeUrl(config: CloudflareOAuthConfig, state: string, challenge: string): string {
|
|
152
|
+
const url = new URL(config.authorizeUrl);
|
|
153
|
+
url.searchParams.set("response_type", "code");
|
|
154
|
+
url.searchParams.set("client_id", config.clientId);
|
|
155
|
+
url.searchParams.set("redirect_uri", config.redirectUri);
|
|
156
|
+
url.searchParams.set("scope", config.scopes);
|
|
157
|
+
url.searchParams.set("state", state);
|
|
158
|
+
url.searchParams.set("code_challenge", challenge);
|
|
159
|
+
url.searchParams.set("code_challenge_method", "S256");
|
|
160
|
+
return url.toString();
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** 把 account_id 写进缺少 accountId 的 cloudflare 实例,返回被更新的实例 id;配置文件不存在时跳过。 */
|
|
164
|
+
export function backfillAccountId(
|
|
165
|
+
configPath: string,
|
|
166
|
+
accountId: string,
|
|
167
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
168
|
+
): string[] {
|
|
169
|
+
if (!accountId || !configPath || !existsSync(configPath)) return [];
|
|
170
|
+
const updated: string[] = [];
|
|
171
|
+
new ConfigStore(configPath).update((file) => {
|
|
172
|
+
if (!Array.isArray(file.instances)) return;
|
|
173
|
+
for (const entry of file.instances) {
|
|
174
|
+
if (!isRecord(entry) || entry.preset !== "cloudflare") continue;
|
|
175
|
+
if (typeof entry.id !== "string") continue;
|
|
176
|
+
// 用户已经写了具体账号就不覆盖;未解析的变量按待回填处理。
|
|
177
|
+
const current = typeof entry.accountId === "string" ? resolveSecret(entry.accountId, env) : undefined;
|
|
178
|
+
if (current) continue;
|
|
179
|
+
entry.accountId = accountId;
|
|
180
|
+
updated.push(entry.id);
|
|
181
|
+
}
|
|
182
|
+
}, env);
|
|
183
|
+
return updated;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
187
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** scope 可能是空格分隔的字符串或数组。 */
|
|
191
|
+
function scopesOf(value: unknown): string[] {
|
|
192
|
+
if (typeof value === "string") return value.split(/\s+/).filter((item) => item !== "");
|
|
193
|
+
if (Array.isArray(value)) return value.filter((item): item is string => typeof item === "string");
|
|
194
|
+
return [];
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** 解析 token 端点响应;缺少 refresh_token 或 scope 时沿用旧值。 */
|
|
198
|
+
function parseGrant(
|
|
199
|
+
body: Record<string, unknown>,
|
|
200
|
+
previous: { refreshToken: string; scopes: string[] },
|
|
201
|
+
nowMs: number,
|
|
202
|
+
): OAuthToken {
|
|
203
|
+
const accessToken = typeof body.access_token === "string" ? body.access_token.trim() : "";
|
|
204
|
+
const tokenType = typeof body.token_type === "string" ? body.token_type.trim().toLowerCase() : "";
|
|
205
|
+
const expiresIn = Number(body.expires_in);
|
|
206
|
+
const missing: string[] = [];
|
|
207
|
+
if (!accessToken) missing.push("access_token");
|
|
208
|
+
if (tokenType !== "bearer") missing.push("token_type");
|
|
209
|
+
if (!Number.isFinite(expiresIn) || expiresIn <= 0) missing.push("expires_in");
|
|
210
|
+
if (missing.length > 0) {
|
|
211
|
+
throw new OAuthError("invalid_token_response", `OAuth 响应缺少必要字段:${missing.join("、")}`);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const refreshToken = typeof body.refresh_token === "string" ? body.refresh_token.trim() : "";
|
|
215
|
+
const scopes = scopesOf(body.scope);
|
|
216
|
+
return {
|
|
217
|
+
access_token: accessToken,
|
|
218
|
+
refresh_token: refreshToken || previous.refreshToken,
|
|
219
|
+
expires_at: Math.floor(nowMs / 1000) + expiresIn,
|
|
220
|
+
scopes: scopes.length > 0 ? scopes : previous.scopes,
|
|
221
|
+
account_id: "",
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** 读取令牌文件;文件缺失或内容不合法都按未登录处理。 */
|
|
226
|
+
function readTokenFile(path: string): OAuthToken | undefined {
|
|
227
|
+
let text: string;
|
|
228
|
+
try {
|
|
229
|
+
text = readFileSync(path, "utf8");
|
|
230
|
+
} catch {
|
|
231
|
+
return undefined;
|
|
232
|
+
}
|
|
233
|
+
let parsed: unknown;
|
|
234
|
+
try {
|
|
235
|
+
parsed = JSON.parse(text);
|
|
236
|
+
} catch {
|
|
237
|
+
return undefined;
|
|
238
|
+
}
|
|
239
|
+
if (!isRecord(parsed)) return undefined;
|
|
240
|
+
const accessToken = parsed.access_token;
|
|
241
|
+
const expiresAt = parsed.expires_at;
|
|
242
|
+
if (typeof accessToken !== "string" || !accessToken) return undefined;
|
|
243
|
+
if (typeof expiresAt !== "number" || !Number.isFinite(expiresAt)) return undefined;
|
|
244
|
+
return {
|
|
245
|
+
access_token: accessToken,
|
|
246
|
+
refresh_token: typeof parsed.refresh_token === "string" ? parsed.refresh_token : "",
|
|
247
|
+
expires_at: expiresAt,
|
|
248
|
+
scopes: scopesOf(parsed.scopes),
|
|
249
|
+
account_id: typeof parsed.account_id === "string" ? parsed.account_id : "",
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** 原子写入令牌文件;临时文件以 0600 创建,rename 后权限随之保留。 */
|
|
254
|
+
function writeTokenFile(path: string, token: OAuthToken): void {
|
|
255
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
256
|
+
const temp = `${path}.${randomUUID()}.tmp`;
|
|
257
|
+
const payload = `${JSON.stringify(token, null, 2)}\n`;
|
|
258
|
+
const fd = openSync(temp, "wx", 0o600);
|
|
259
|
+
try {
|
|
260
|
+
try {
|
|
261
|
+
writeFileSync(fd, payload, "utf8");
|
|
262
|
+
} finally {
|
|
263
|
+
closeSync(fd);
|
|
264
|
+
}
|
|
265
|
+
renameSync(temp, path);
|
|
266
|
+
} finally {
|
|
267
|
+
if (existsSync(temp)) unlinkSync(temp);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function errorMessage(error: unknown): string {
|
|
272
|
+
return error instanceof Error ? error.message : String(error);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** 上游错误描述:OAuth 端点用 error_description,Cloudflare v4 用 errors[0].message。 */
|
|
276
|
+
function descriptionOf(body: Record<string, unknown>): string {
|
|
277
|
+
if (typeof body.error_description === "string" && body.error_description.trim()) {
|
|
278
|
+
return body.error_description.trim();
|
|
279
|
+
}
|
|
280
|
+
const errors = body.errors;
|
|
281
|
+
if (Array.isArray(errors)) {
|
|
282
|
+
const first = errors.find((item) => isRecord(item) && typeof item.message === "string");
|
|
283
|
+
if (isRecord(first) && typeof first.message === "string") return first.message;
|
|
284
|
+
}
|
|
285
|
+
return "";
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
function requestIdOf(headers: Headers, body: Record<string, unknown>): string | undefined {
|
|
289
|
+
for (const name of ["request_id", "requestId"]) {
|
|
290
|
+
const value = body[name];
|
|
291
|
+
if (typeof value === "string" && value) return value;
|
|
292
|
+
}
|
|
293
|
+
for (const name of REQUEST_ID_HEADERS) {
|
|
294
|
+
const value = headers.get(name);
|
|
295
|
+
if (value) return value;
|
|
296
|
+
}
|
|
297
|
+
return undefined;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** Cloudflare 授权码 + 粘贴流程:PKCE、令牌换发与刷新、账号回填、撤销与本地令牌文件。 */
|
|
301
|
+
export class CloudflareOAuth {
|
|
302
|
+
readonly tokenPath: string;
|
|
303
|
+
readonly configPath: string;
|
|
304
|
+
|
|
305
|
+
private readonly config: CloudflareOAuthConfig;
|
|
306
|
+
private readonly fetchImpl: typeof globalThis.fetch;
|
|
307
|
+
private readonly clock: () => number;
|
|
308
|
+
private readonly accountsUrl: string;
|
|
309
|
+
private readonly revokeUrl: string;
|
|
310
|
+
private readonly timeoutMs: number;
|
|
311
|
+
private readonly env: NodeJS.ProcessEnv;
|
|
312
|
+
private readonly pending = new Map<string, PendingLogin>();
|
|
313
|
+
private refreshing: Promise<OAuthToken> | undefined;
|
|
314
|
+
|
|
315
|
+
constructor(options: CloudflareOAuthOptions) {
|
|
316
|
+
this.config = options.config;
|
|
317
|
+
this.tokenPath = options.tokenPath ?? DEFAULT_TOKEN_PATH;
|
|
318
|
+
this.configPath = options.configPath ?? DEFAULT_CONFIG_PATH;
|
|
319
|
+
this.fetchImpl = options.fetch ?? globalThis.fetch;
|
|
320
|
+
this.clock = options.clock ?? Date.now;
|
|
321
|
+
this.accountsUrl = options.accountsUrl ?? DEFAULT_ACCOUNTS_URL;
|
|
322
|
+
this.revokeUrl = options.revokeUrl ?? DEFAULT_REVOKE_URL;
|
|
323
|
+
this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
324
|
+
this.env = options.env ?? process.env;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** 生成授权链接并把 state 与 code_verifier 留在内存,10 分钟过期。 */
|
|
328
|
+
beginLogin(): { authorizeUrl: string; state: string; expiresAt: number } {
|
|
329
|
+
const now = this.clock();
|
|
330
|
+
for (const [state, pending] of this.pending) {
|
|
331
|
+
if (now - pending.createdAt >= STATE_TTL_MS) this.pending.delete(state);
|
|
332
|
+
}
|
|
333
|
+
const state = randomBytes(16).toString("base64url");
|
|
334
|
+
const verifier = createCodeVerifier();
|
|
335
|
+
this.pending.set(state, { verifier, createdAt: now });
|
|
336
|
+
return {
|
|
337
|
+
authorizeUrl: buildAuthorizeUrl(this.config, state, codeChallenge(verifier)),
|
|
338
|
+
state,
|
|
339
|
+
expiresAt: now + STATE_TTL_MS,
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** 用粘贴回来的授权码换令牌,回填 accountId 后落盘。 */
|
|
344
|
+
async completeLogin(code: string, state: string): Promise<LoginResult> {
|
|
345
|
+
const verifier = this.takeVerifier(state);
|
|
346
|
+
const token = await this.exchangeCode(code, verifier);
|
|
347
|
+
|
|
348
|
+
let warning: string | undefined;
|
|
349
|
+
try {
|
|
350
|
+
token.account_id = await this.fetchAccountId(token.access_token);
|
|
351
|
+
} catch (error) {
|
|
352
|
+
warning = `accountId 回填失败:${errorMessage(error)}`;
|
|
353
|
+
}
|
|
354
|
+
this.saveToken(token);
|
|
355
|
+
|
|
356
|
+
let updatedInstances: string[] = [];
|
|
357
|
+
if (token.account_id) {
|
|
358
|
+
try {
|
|
359
|
+
updatedInstances = backfillAccountId(this.configPath, token.account_id, this.env);
|
|
360
|
+
} catch (error) {
|
|
361
|
+
const detail = `配置回填失败:${errorMessage(error)}`;
|
|
362
|
+
warning = warning ? `${warning};${detail}` : detail;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
return { token, updatedInstances, warning };
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/** 取可用于请求的 access token;60 秒内到期先刷新。 */
|
|
369
|
+
async accessToken(): Promise<string> {
|
|
370
|
+
const token = this.loadToken();
|
|
371
|
+
if (!token) throw this.notLoggedIn();
|
|
372
|
+
if (!this.isExpiring(token)) return token.access_token;
|
|
373
|
+
const refreshed = await this.refreshToken();
|
|
374
|
+
return refreshed.access_token;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/** 刷新令牌;同一时刻只发一次请求,响应没有 refresh_token 时沿用旧值。 */
|
|
378
|
+
async refreshToken(): Promise<OAuthToken> {
|
|
379
|
+
const current = this.loadToken();
|
|
380
|
+
if (!current) throw this.notLoggedIn();
|
|
381
|
+
if (!current.refresh_token) {
|
|
382
|
+
throw new OAuthError("not_logged_in", `令牌没有 refresh_token,请重新授权:${this.tokenPath}`);
|
|
383
|
+
}
|
|
384
|
+
if (!this.refreshing) {
|
|
385
|
+
this.refreshing = this.refresh(current).finally(() => {
|
|
386
|
+
this.refreshing = undefined;
|
|
387
|
+
});
|
|
388
|
+
}
|
|
389
|
+
return this.refreshing;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** 撤销远端授权并删除本地令牌;撤销失败也清除本地文件。 */
|
|
393
|
+
async logout(): Promise<LogoutResult> {
|
|
394
|
+
const token = this.loadToken();
|
|
395
|
+
let warning: string | undefined;
|
|
396
|
+
if (token?.refresh_token) {
|
|
397
|
+
try {
|
|
398
|
+
await this.postForm(this.revokeUrl, {
|
|
399
|
+
token: token.refresh_token,
|
|
400
|
+
token_type_hint: "refresh_token",
|
|
401
|
+
client_id: this.config.clientId,
|
|
402
|
+
});
|
|
403
|
+
} catch (error) {
|
|
404
|
+
warning = `撤销授权失败:${errorMessage(error)}`;
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
this.clearToken();
|
|
408
|
+
return { token, warning };
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/** 读令牌文件;文件缺失或内容不合法时返回 undefined。 */
|
|
412
|
+
loadToken(): OAuthToken | undefined {
|
|
413
|
+
return readTokenFile(this.tokenPath);
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/** 删除令牌文件。 */
|
|
417
|
+
clearToken(): void {
|
|
418
|
+
if (existsSync(this.tokenPath)) unlinkSync(this.tokenPath);
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
private async refresh(current: OAuthToken): Promise<OAuthToken> {
|
|
422
|
+
const body = await this.postForm(this.config.tokenUrl, {
|
|
423
|
+
grant_type: "refresh_token",
|
|
424
|
+
refresh_token: current.refresh_token,
|
|
425
|
+
client_id: this.config.clientId,
|
|
426
|
+
});
|
|
427
|
+
const granted = parseGrant(
|
|
428
|
+
body,
|
|
429
|
+
{ refreshToken: current.refresh_token, scopes: current.scopes },
|
|
430
|
+
this.clock(),
|
|
431
|
+
);
|
|
432
|
+
granted.account_id = current.account_id;
|
|
433
|
+
this.saveToken(granted);
|
|
434
|
+
return granted;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
private async exchangeCode(code: string, verifier: string): Promise<OAuthToken> {
|
|
438
|
+
const body = await this.postForm(this.config.tokenUrl, {
|
|
439
|
+
grant_type: "authorization_code",
|
|
440
|
+
code,
|
|
441
|
+
redirect_uri: this.config.redirectUri,
|
|
442
|
+
client_id: this.config.clientId,
|
|
443
|
+
code_verifier: verifier,
|
|
444
|
+
});
|
|
445
|
+
return parseGrant(body, { refreshToken: "", scopes: [] }, this.clock());
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/** 列出账号并取第一个的 id;没有账号时返回空字符串。 */
|
|
449
|
+
private async fetchAccountId(accessToken: string): Promise<string> {
|
|
450
|
+
const url = new URL(this.accountsUrl);
|
|
451
|
+
url.searchParams.set("per_page", "50");
|
|
452
|
+
const { status, body, requestId } = await this.send(url.toString(), {
|
|
453
|
+
headers: { Authorization: `Bearer ${accessToken}` },
|
|
454
|
+
});
|
|
455
|
+
const result = body.result;
|
|
456
|
+
if (status >= 400 || !Array.isArray(result)) {
|
|
457
|
+
throw this.rejected("accounts_request_failed", status, requestId, body);
|
|
458
|
+
}
|
|
459
|
+
const first = result.find((item) => isRecord(item) && typeof item.id === "string");
|
|
460
|
+
return isRecord(first) && typeof first.id === "string" ? first.id : "";
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
private saveToken(token: OAuthToken): void {
|
|
464
|
+
writeTokenFile(this.tokenPath, token);
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
private isExpiring(token: OAuthToken): boolean {
|
|
468
|
+
return token.expires_at * 1000 - this.clock() <= REFRESH_MARGIN_SECONDS * 1000;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
private takeVerifier(state: string): string {
|
|
472
|
+
const pending = this.pending.get(state);
|
|
473
|
+
this.pending.delete(state);
|
|
474
|
+
if (!pending) {
|
|
475
|
+
throw new OAuthError("invalid_state", "授权流程状态不匹配,请重新发起授权");
|
|
476
|
+
}
|
|
477
|
+
if (this.clock() - pending.createdAt >= STATE_TTL_MS) {
|
|
478
|
+
throw new OAuthError("invalid_state", "授权流程已超过 10 分钟,请重新发起授权");
|
|
479
|
+
}
|
|
480
|
+
return pending.verifier;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
private notLoggedIn(): OAuthError {
|
|
484
|
+
return new OAuthError("not_logged_in", `尚未登录 Cloudflare,令牌文件不存在:${this.tokenPath}`);
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/** 非 2xx 或带 error 字段的统一错误;消息只保留状态码、错误码与 request_id。 */
|
|
488
|
+
private rejected(
|
|
489
|
+
code: string,
|
|
490
|
+
status: number,
|
|
491
|
+
requestId: string | undefined,
|
|
492
|
+
body: Record<string, unknown>,
|
|
493
|
+
): OAuthError {
|
|
494
|
+
const description = descriptionOf(body);
|
|
495
|
+
const detail = description ? `:${description}` : "";
|
|
496
|
+
const request = requestId ? `(request_id=${requestId})` : "";
|
|
497
|
+
const label = code.startsWith("http_") ? code : `${code} HTTP ${status}`;
|
|
498
|
+
const message = `OAuth 请求被拒绝(${label})${detail}${request}`;
|
|
499
|
+
return new OAuthError(code, message, { status, requestId });
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/** 表单 POST:application/x-www-form-urlencoded,公共客户端不带 secret。 */
|
|
503
|
+
private async postForm(url: string, form: Record<string, string>): Promise<Record<string, unknown>> {
|
|
504
|
+
const { status, body, requestId } = await this.send(url, {
|
|
505
|
+
method: "POST",
|
|
506
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
507
|
+
body: new URLSearchParams(form).toString(),
|
|
508
|
+
});
|
|
509
|
+
const error = typeof body.error === "string" ? body.error.trim() : "";
|
|
510
|
+
if (status >= 400 || error) throw this.rejected(error || `http_${status}`, status, requestId, body);
|
|
511
|
+
return body;
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
private async send(
|
|
515
|
+
url: string,
|
|
516
|
+
init: { method?: string; headers?: Record<string, string>; body?: string },
|
|
517
|
+
): Promise<{ status: number; body: Record<string, unknown>; requestId?: string }> {
|
|
518
|
+
let response: Response;
|
|
519
|
+
let text: string;
|
|
520
|
+
try {
|
|
521
|
+
response = await this.fetchImpl(url, {
|
|
522
|
+
method: init.method ?? "GET",
|
|
523
|
+
headers: { Accept: "application/json", ...init.headers },
|
|
524
|
+
body: init.body,
|
|
525
|
+
signal: AbortSignal.timeout(this.timeoutMs),
|
|
526
|
+
});
|
|
527
|
+
text = await response.text();
|
|
528
|
+
} catch (error) {
|
|
529
|
+
throw new OAuthError("network_error", `OAuth 请求失败:${errorMessage(error)}`);
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
let body: Record<string, unknown> = {};
|
|
533
|
+
if (text.trim()) {
|
|
534
|
+
let parsed: unknown;
|
|
535
|
+
try {
|
|
536
|
+
parsed = JSON.parse(text);
|
|
537
|
+
} catch {
|
|
538
|
+
throw new OAuthError("invalid_response", `OAuth 响应不是 JSON(HTTP ${response.status})`, {
|
|
539
|
+
status: response.status,
|
|
540
|
+
});
|
|
541
|
+
}
|
|
542
|
+
if (!isRecord(parsed)) {
|
|
543
|
+
throw new OAuthError("invalid_response", `OAuth 响应不是对象(HTTP ${response.status})`, {
|
|
544
|
+
status: response.status,
|
|
545
|
+
});
|
|
546
|
+
}
|
|
547
|
+
body = parsed;
|
|
548
|
+
}
|
|
549
|
+
return { status: response.status, body, requestId: requestIdOf(response.headers, body) };
|
|
550
|
+
}
|
|
551
|
+
}
|