pi-auto-web-search 0.1.2 → 1.2.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 +4 -0
- package/README.md +8 -5
- package/README_EN.md +8 -5
- package/package.json +1 -1
- package/src/cloudflare-oauth.ts +411 -132
- package/src/config.ts +48 -12
- package/src/http.ts +4 -3
- package/src/oauth-lock.ts +29 -0
- package/src/settings-ui.ts +180 -34
- package/src/tools.ts +189 -53
package/src/cloudflare-oauth.ts
CHANGED
|
@@ -2,19 +2,28 @@ import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
|
2
2
|
import {
|
|
3
3
|
closeSync,
|
|
4
4
|
existsSync,
|
|
5
|
-
mkdirSync,
|
|
6
5
|
openSync,
|
|
6
|
+
readdirSync,
|
|
7
7
|
readFileSync,
|
|
8
8
|
renameSync,
|
|
9
|
+
statSync,
|
|
9
10
|
unlinkSync,
|
|
10
11
|
writeFileSync,
|
|
11
12
|
} from "node:fs";
|
|
12
13
|
import { homedir } from "node:os";
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
14
|
+
import { join } from "node:path";
|
|
15
|
+
import { isDeepStrictEqual } from "node:util";
|
|
16
|
+
import { ConfigStore, type BackfillCloudflareOptions, type CloudflareOAuthConfig } from "./config.ts";
|
|
17
|
+
import { withOAuthLock } from "./oauth-lock.ts";
|
|
15
18
|
|
|
16
|
-
/**
|
|
17
|
-
export const
|
|
19
|
+
/** 默认多实例 OAuth 令牌目录。 */
|
|
20
|
+
export const DEFAULT_TOKEN_DIR = join(homedir(), ".pi", "agent", "search-oauth");
|
|
21
|
+
|
|
22
|
+
/** 旧版全局单令牌文件路径,检测到后按目标实例自动转换。 */
|
|
23
|
+
export const DEFAULT_LEGACY_TOKEN_PATH = join(homedir(), ".pi", "agent", "search-oauth.json");
|
|
24
|
+
|
|
25
|
+
/** 旧授权的退出目标,与合法实例 ID 不重名。 */
|
|
26
|
+
export const LEGACY_OAUTH_TARGET = "@legacy";
|
|
18
27
|
|
|
19
28
|
/** 默认配置文件路径,登录后回填 accountId。 */
|
|
20
29
|
export const DEFAULT_CONFIG_PATH = join(homedir(), ".pi", "agent", "search.json");
|
|
@@ -77,9 +86,12 @@ export interface LogoutResult {
|
|
|
77
86
|
}
|
|
78
87
|
|
|
79
88
|
export interface CloudflareOAuthOptions {
|
|
89
|
+
/** 该令牌绑定的 Cloudflare 实例 ID。 */
|
|
90
|
+
instanceId: string;
|
|
80
91
|
/** 配置里的 cloudflareOAuth 段,授权链接与换发都用它。 */
|
|
81
92
|
config: CloudflareOAuthConfig;
|
|
82
|
-
|
|
93
|
+
/** 多实例令牌保存目录,默认 ~/.pi/agent/search-oauth。 */
|
|
94
|
+
tokenDir?: string;
|
|
83
95
|
configPath?: string;
|
|
84
96
|
fetch?: typeof globalThis.fetch;
|
|
85
97
|
/** 返回 epoch 毫秒。 */
|
|
@@ -141,8 +153,231 @@ export function parseAuthorizationCode(
|
|
|
141
153
|
return { code, state };
|
|
142
154
|
}
|
|
143
155
|
|
|
144
|
-
|
|
145
|
-
|
|
156
|
+
const INSTANCE_ID_RE = /^[A-Za-z0-9_-]+$/;
|
|
157
|
+
|
|
158
|
+
function isEnoent(error: unknown): boolean {
|
|
159
|
+
return typeof error === "object" && error !== null && (error as NodeJS.ErrnoException).code === "ENOENT";
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function unlinkIfExists(path: string): void {
|
|
163
|
+
try {
|
|
164
|
+
unlinkSync(path);
|
|
165
|
+
} catch (error) {
|
|
166
|
+
if (!isEnoent(error)) throw error;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function assertInstanceId(instanceId: string): string {
|
|
171
|
+
if (!INSTANCE_ID_RE.test(instanceId)) {
|
|
172
|
+
throw new Error(`Cloudflare OAuth 实例 ID 格式无效:${instanceId}`);
|
|
173
|
+
}
|
|
174
|
+
return instanceId;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** 构造实例令牌文件名:<instanceId>+<accountId>.json,缺失 accountId 时为 <instanceId>.json。 */
|
|
178
|
+
export function instanceTokenFileName(instanceId: string, accountId?: string): string {
|
|
179
|
+
assertInstanceId(instanceId);
|
|
180
|
+
const safeAccount = (accountId ?? "").trim().replace(/[^A-Za-z0-9_-]+/g, "");
|
|
181
|
+
return safeAccount ? `${instanceId}+${safeAccount}.json` : `${instanceId}.json`;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** 从令牌文件名提取实例 ID;非约定格式的 .json 或临时文件返回 undefined。 */
|
|
185
|
+
export function instanceIdFromTokenFile(fileName: string): string | undefined {
|
|
186
|
+
if (!fileName.endsWith(".json")) return undefined;
|
|
187
|
+
const stem = fileName.slice(0, -".json".length);
|
|
188
|
+
const plusIndex = stem.indexOf("+");
|
|
189
|
+
if (plusIndex === -1) return INSTANCE_ID_RE.test(stem) ? stem : undefined;
|
|
190
|
+
if (stem.indexOf("+", plusIndex + 1) !== -1) return undefined;
|
|
191
|
+
const instanceId = stem.slice(0, plusIndex);
|
|
192
|
+
const accountPart = stem.slice(plusIndex + 1);
|
|
193
|
+
return INSTANCE_ID_RE.test(instanceId) && INSTANCE_ID_RE.test(accountPart) ? instanceId : undefined;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** 判断目录里的文件名是否归属指定实例。 */
|
|
197
|
+
export function isInstanceTokenFile(fileName: string, instanceId: string): boolean {
|
|
198
|
+
return instanceIdFromTokenFile(fileName) === instanceId;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** 列出指定实例在令牌目录下的全部候选文件,按修改时间倒序排列。 */
|
|
202
|
+
export function findInstanceTokenFiles(tokenDir: string, instanceId: string): string[] {
|
|
203
|
+
if (!INSTANCE_ID_RE.test(instanceId)) return [];
|
|
204
|
+
let entries: string[];
|
|
205
|
+
try {
|
|
206
|
+
entries = readdirSync(tokenDir);
|
|
207
|
+
} catch (error) {
|
|
208
|
+
if (isEnoent(error)) return [];
|
|
209
|
+
throw error;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const matched: { name: string; path: string; mtimeMs: number }[] = [];
|
|
213
|
+
for (const name of entries) {
|
|
214
|
+
if (!isInstanceTokenFile(name, instanceId)) continue;
|
|
215
|
+
const fullPath = join(tokenDir, name);
|
|
216
|
+
try {
|
|
217
|
+
matched.push({ name, path: fullPath, mtimeMs: statSync(fullPath).mtimeMs });
|
|
218
|
+
} catch (error) {
|
|
219
|
+
if (!isEnoent(error)) throw error;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
matched.sort((a, b) => b.mtimeMs - a.mtimeMs || b.name.localeCompare(a.name));
|
|
224
|
+
return matched.map((item) => item.path);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** 读取指定实例的有效 OAuth 令牌及路径;文件损坏时原样保留并返回 undefined。 */
|
|
228
|
+
export function readInstanceOAuthToken(
|
|
229
|
+
tokenDir: string,
|
|
230
|
+
instanceId: string,
|
|
231
|
+
): { path: string; token: OAuthToken } | undefined {
|
|
232
|
+
for (const path of findInstanceTokenFiles(tokenDir, instanceId)) {
|
|
233
|
+
const token = readTokenFile(path);
|
|
234
|
+
if (token) return { path, token };
|
|
235
|
+
}
|
|
236
|
+
return undefined;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** 读取令牌目录下全部有效实例令牌,按实例 ID 映射。 */
|
|
240
|
+
export function readAllInstanceOAuthTokens(
|
|
241
|
+
tokenDir: string,
|
|
242
|
+
onError?: (instanceId: string | undefined, error: unknown) => void,
|
|
243
|
+
): Record<string, OAuthToken> {
|
|
244
|
+
const tokens: Record<string, OAuthToken> = Object.create(null);
|
|
245
|
+
let entries: string[];
|
|
246
|
+
try {
|
|
247
|
+
entries = readdirSync(tokenDir);
|
|
248
|
+
} catch (error) {
|
|
249
|
+
if (!isEnoent(error)) {
|
|
250
|
+
if (!onError) throw error;
|
|
251
|
+
onError(undefined, error);
|
|
252
|
+
}
|
|
253
|
+
return tokens;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
const ids = new Set<string>();
|
|
257
|
+
for (const name of entries) {
|
|
258
|
+
const id = instanceIdFromTokenFile(name);
|
|
259
|
+
if (id) ids.add(id);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
for (const id of [...ids].sort()) {
|
|
263
|
+
try {
|
|
264
|
+
const found = readInstanceOAuthToken(tokenDir, id);
|
|
265
|
+
if (found) tokens[id] = found.token;
|
|
266
|
+
else onError?.(id, new Error("未读到有效的 OAuth 令牌文件"));
|
|
267
|
+
} catch (error) {
|
|
268
|
+
if (!onError) throw error;
|
|
269
|
+
onError(id, error);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
return tokens;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
type BeforeTokenPublish = () => (() => void) | undefined;
|
|
276
|
+
|
|
277
|
+
/** 在持锁期间安装令牌,不能接管仅大小写不同的其他实例的文件名。 */
|
|
278
|
+
function installToken(tokenDir: string, instanceId: string, token: OAuthToken, beforePublish?: BeforeTokenPublish): string {
|
|
279
|
+
assertInstanceId(instanceId);
|
|
280
|
+
for (const name of readdirSync(tokenDir)) {
|
|
281
|
+
const id = instanceIdFromTokenFile(name);
|
|
282
|
+
if (id && id !== instanceId && id.toLowerCase() === instanceId.toLowerCase()) {
|
|
283
|
+
throw new Error(`OAuth 实例名与已存凭据仅大小写不同:${instanceId}、${id}`);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
const existing = findInstanceTokenFiles(tokenDir, instanceId);
|
|
287
|
+
const requested = join(tokenDir, instanceTokenFileName(instanceId, token.account_id));
|
|
288
|
+
const target = existing.find(path => path.toLowerCase() === requested.toLowerCase()) ?? requested;
|
|
289
|
+
writeTokenFile(target, token, beforePublish);
|
|
290
|
+
for (const path of existing) {
|
|
291
|
+
if (path !== target) unlinkIfExists(path);
|
|
292
|
+
}
|
|
293
|
+
return target;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** 将实例令牌原子写入并清理该实例的旧文件名。 */
|
|
297
|
+
export function saveInstanceOAuthToken(tokenDir: string, instanceId: string, token: OAuthToken): string {
|
|
298
|
+
return withOAuthLock(tokenDir, () => installToken(tokenDir, instanceId, token));
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function removeTokenFiles(tokenDir: string, instanceId: string): void {
|
|
302
|
+
for (const path of findInstanceTokenFiles(tokenDir, instanceId)) unlinkIfExists(path);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** 在同一次写锁内清理实例文件并取出需要撤销的授权。 */
|
|
306
|
+
function takeInstanceToken(tokenDir: string, instanceId: string): OAuthToken | undefined {
|
|
307
|
+
if (!existsSync(tokenDir)) return undefined;
|
|
308
|
+
return withOAuthLock(tokenDir, () => {
|
|
309
|
+
const token = readInstanceOAuthToken(tokenDir, instanceId)?.token;
|
|
310
|
+
removeTokenFiles(tokenDir, instanceId);
|
|
311
|
+
return token;
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
export function clearInstanceOAuthTokens(tokenDir: string, instanceId: string): void {
|
|
316
|
+
takeInstanceToken(tokenDir, instanceId);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function ownerOfGrant(tokenDir: string, token: OAuthToken): string | undefined {
|
|
320
|
+
return Object.entries(readAllInstanceOAuthTokens(tokenDir)).find(([, other]) =>
|
|
321
|
+
other.access_token === token.access_token || (!!token.refresh_token && other.refresh_token === token.refresh_token),
|
|
322
|
+
)?.[0];
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** 只有唯一或明确选定的实例能认领旧授权,读回成功后才删除源文件。 */
|
|
326
|
+
export function migrateLegacyOAuthToken(options: {
|
|
327
|
+
legacyTokenPath: string;
|
|
328
|
+
tokenDir: string;
|
|
329
|
+
instanceIds: readonly string[];
|
|
330
|
+
targetId?: string;
|
|
331
|
+
}): string[] {
|
|
332
|
+
const { legacyTokenPath, tokenDir, targetId } = options;
|
|
333
|
+
const ids = [...new Set(options.instanceIds)];
|
|
334
|
+
if (targetId !== undefined && !ids.includes(targetId)) throw new Error(`不是已启用的 OAuth 实例:${targetId}`);
|
|
335
|
+
const id = targetId ?? (ids.length === 1 ? ids[0] : undefined);
|
|
336
|
+
if (!id || !statSync(legacyTokenPath, { throwIfNoEntry: false })) return [];
|
|
337
|
+
assertInstanceId(id);
|
|
338
|
+
return withOAuthLock(tokenDir, () => {
|
|
339
|
+
const legacy = readTokenFile(legacyTokenPath);
|
|
340
|
+
if (!legacy) return [];
|
|
341
|
+
const files = findInstanceTokenFiles(tokenDir, id);
|
|
342
|
+
const owner = ownerOfGrant(tokenDir, legacy);
|
|
343
|
+
if (owner && owner !== id) throw new Error(`旧授权已经由实例 ${owner} 使用,未迁移`);
|
|
344
|
+
if (files.length > 0) {
|
|
345
|
+
if (files.length !== 1 || !isDeepStrictEqual(readTokenFile(files[0]!), legacy)) {
|
|
346
|
+
throw new Error(`实例 ${id} 已有凭据文件,未覆盖,旧文件已保留`);
|
|
347
|
+
}
|
|
348
|
+
unlinkSync(legacyTokenPath);
|
|
349
|
+
return [id];
|
|
350
|
+
}
|
|
351
|
+
const target = installToken(tokenDir, id, legacy);
|
|
352
|
+
try {
|
|
353
|
+
if (!isDeepStrictEqual(readTokenFile(target), legacy)) throw new Error("迁移后未能读回相同的 OAuth 凭据");
|
|
354
|
+
unlinkSync(legacyTokenPath);
|
|
355
|
+
} catch (error) {
|
|
356
|
+
unlinkIfExists(target);
|
|
357
|
+
throw error;
|
|
358
|
+
}
|
|
359
|
+
return [id];
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** 退出仍在旧文件中的授权,无需创建或启用实例。 */
|
|
364
|
+
export async function logoutLegacyOAuth(options: {
|
|
365
|
+
legacyTokenPath: string; tokenDir: string; config: CloudflareOAuthConfig; fetch?: typeof globalThis.fetch; revokeUrl?: string;
|
|
366
|
+
}): Promise<LogoutResult> {
|
|
367
|
+
if (!statSync(options.legacyTokenPath, { throwIfNoEntry: false })) return {};
|
|
368
|
+
const token = withOAuthLock(options.tokenDir, () => {
|
|
369
|
+
const stored = readTokenFile(options.legacyTokenPath);
|
|
370
|
+
if (!stored) throw new Error("无法读取旧版 OAuth 凭据,原文件已保留");
|
|
371
|
+
const owner = ownerOfGrant(options.tokenDir, stored);
|
|
372
|
+
if (owner) throw new Error(`旧授权仍由实例 ${owner} 使用,请先完成迁移`);
|
|
373
|
+
unlinkSync(options.legacyTokenPath);
|
|
374
|
+
return stored;
|
|
375
|
+
});
|
|
376
|
+
return new OAuthHttp(options.fetch).revoke(token, options.config.clientId, options.revokeUrl ?? DEFAULT_REVOKE_URL);
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** 读取指定路径的 OAuth 令牌文件;缺失或损坏时返回 undefined。 */
|
|
380
|
+
export function readOAuthToken(path: string): OAuthToken | undefined {
|
|
146
381
|
return readTokenFile(path);
|
|
147
382
|
}
|
|
148
383
|
|
|
@@ -159,14 +394,15 @@ export function buildAuthorizeUrl(config: CloudflareOAuthConfig, state: string,
|
|
|
159
394
|
return url.toString();
|
|
160
395
|
}
|
|
161
396
|
|
|
162
|
-
/**
|
|
397
|
+
/** 登录后给目标实例写入 accountId。 */
|
|
163
398
|
export function backfillAccountId(
|
|
164
399
|
configPath: string,
|
|
165
400
|
accountId: string,
|
|
166
401
|
env: NodeJS.ProcessEnv = process.env,
|
|
402
|
+
options: BackfillCloudflareOptions = {},
|
|
167
403
|
): string[] {
|
|
168
404
|
if (!accountId.trim() || !configPath) return [];
|
|
169
|
-
return new ConfigStore(configPath).backfillCloudflareAccountId(accountId, env);
|
|
405
|
+
return new ConfigStore(configPath).backfillCloudflareAccountId(accountId, env, options).updatedInstances;
|
|
170
406
|
}
|
|
171
407
|
|
|
172
408
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
@@ -213,8 +449,9 @@ function readTokenFile(path: string): OAuthToken | undefined {
|
|
|
213
449
|
let text: string;
|
|
214
450
|
try {
|
|
215
451
|
text = readFileSync(path, "utf8");
|
|
216
|
-
} catch {
|
|
217
|
-
return undefined;
|
|
452
|
+
} catch (error) {
|
|
453
|
+
if (isEnoent(error)) return undefined;
|
|
454
|
+
throw error;
|
|
218
455
|
}
|
|
219
456
|
let parsed: unknown;
|
|
220
457
|
try {
|
|
@@ -236,9 +473,8 @@ function readTokenFile(path: string): OAuthToken | undefined {
|
|
|
236
473
|
};
|
|
237
474
|
}
|
|
238
475
|
|
|
239
|
-
/**
|
|
240
|
-
function writeTokenFile(path: string, token: OAuthToken): void {
|
|
241
|
-
mkdirSync(dirname(path), { recursive: true });
|
|
476
|
+
/** 原子写入令牌文件;目录权限 0700,临时文件以 0600 创建,rename 后权限随之保留。 */
|
|
477
|
+
function writeTokenFile(path: string, token: OAuthToken, beforePublish?: BeforeTokenPublish): void {
|
|
242
478
|
const temp = `${path}.${randomUUID()}.tmp`;
|
|
243
479
|
const payload = `${JSON.stringify(token, null, 2)}\n`;
|
|
244
480
|
const fd = openSync(temp, "wx", 0o600);
|
|
@@ -248,7 +484,13 @@ function writeTokenFile(path: string, token: OAuthToken): void {
|
|
|
248
484
|
} finally {
|
|
249
485
|
closeSync(fd);
|
|
250
486
|
}
|
|
251
|
-
|
|
487
|
+
const rollback = beforePublish?.();
|
|
488
|
+
try {
|
|
489
|
+
renameSync(temp, path);
|
|
490
|
+
} catch (error) {
|
|
491
|
+
rollback?.();
|
|
492
|
+
throw error;
|
|
493
|
+
}
|
|
252
494
|
} finally {
|
|
253
495
|
if (existsSync(temp)) unlinkSync(temp);
|
|
254
496
|
}
|
|
@@ -283,33 +525,130 @@ function requestIdOf(headers: Headers, body: Record<string, unknown>): string |
|
|
|
283
525
|
return undefined;
|
|
284
526
|
}
|
|
285
527
|
|
|
286
|
-
|
|
528
|
+
class OAuthHttp {
|
|
529
|
+
private readonly fetchImpl: typeof globalThis.fetch;
|
|
530
|
+
private readonly timeoutMs: number;
|
|
531
|
+
|
|
532
|
+
constructor(fetchImpl = globalThis.fetch, timeoutMs = DEFAULT_TIMEOUT_MS) {
|
|
533
|
+
this.fetchImpl = fetchImpl;
|
|
534
|
+
this.timeoutMs = timeoutMs;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
async revoke(token: OAuthToken | undefined, clientId: string, url: string): Promise<LogoutResult> {
|
|
538
|
+
let warning: string | undefined;
|
|
539
|
+
if (token?.refresh_token) {
|
|
540
|
+
try {
|
|
541
|
+
await this.postForm(url, {
|
|
542
|
+
token: token.refresh_token,
|
|
543
|
+
token_type_hint: "refresh_token",
|
|
544
|
+
client_id: clientId,
|
|
545
|
+
});
|
|
546
|
+
} catch (error) {
|
|
547
|
+
warning = `撤销授权失败:${errorMessage(error)}`;
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
return { token, warning };
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
/** 非 2xx 或带 error 字段的统一错误;消息只保留状态码、错误码与 request_id。 */
|
|
554
|
+
rejected(
|
|
555
|
+
code: string,
|
|
556
|
+
status: number,
|
|
557
|
+
requestId: string | undefined,
|
|
558
|
+
body: Record<string, unknown>,
|
|
559
|
+
): OAuthError {
|
|
560
|
+
const description = descriptionOf(body);
|
|
561
|
+
const detail = description ? `:${description}` : "";
|
|
562
|
+
const request = requestId ? `(request_id=${requestId})` : "";
|
|
563
|
+
const label = code.startsWith("http_") ? code : `${code} HTTP ${status}`;
|
|
564
|
+
const message = `OAuth 请求被拒绝(${label})${detail}${request}`;
|
|
565
|
+
return new OAuthError(code, message, { status, requestId });
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
/** 表单 POST:application/x-www-form-urlencoded,公共客户端不带 secret。 */
|
|
569
|
+
async postForm(url: string, form: Record<string, string>): Promise<Record<string, unknown>> {
|
|
570
|
+
const { status, body, requestId } = await this.send(url, {
|
|
571
|
+
method: "POST",
|
|
572
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
573
|
+
body: new URLSearchParams(form).toString(),
|
|
574
|
+
});
|
|
575
|
+
const error = typeof body.error === "string" ? body.error.trim() : "";
|
|
576
|
+
if (status >= 400 || error) throw this.rejected(error || `http_${status}`, status, requestId, body);
|
|
577
|
+
return body;
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
async send(
|
|
581
|
+
url: string,
|
|
582
|
+
init: { method?: string; headers?: Record<string, string>; body?: string },
|
|
583
|
+
): Promise<{ status: number; body: Record<string, unknown>; requestId?: string }> {
|
|
584
|
+
let response: Response;
|
|
585
|
+
let text: string;
|
|
586
|
+
try {
|
|
587
|
+
response = await this.fetchImpl(url, {
|
|
588
|
+
method: init.method ?? "GET",
|
|
589
|
+
headers: { Accept: "application/json", ...init.headers },
|
|
590
|
+
body: init.body,
|
|
591
|
+
signal: AbortSignal.timeout(this.timeoutMs),
|
|
592
|
+
});
|
|
593
|
+
text = await response.text();
|
|
594
|
+
} catch (error) {
|
|
595
|
+
throw new OAuthError("network_error", `OAuth 请求失败:${errorMessage(error)}`);
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
let body: Record<string, unknown> = {};
|
|
599
|
+
if (text.trim()) {
|
|
600
|
+
let parsed: unknown;
|
|
601
|
+
try {
|
|
602
|
+
parsed = JSON.parse(text);
|
|
603
|
+
} catch {
|
|
604
|
+
throw new OAuthError("invalid_response", `OAuth 响应不是 JSON(HTTP ${response.status})`, {
|
|
605
|
+
status: response.status,
|
|
606
|
+
});
|
|
607
|
+
}
|
|
608
|
+
if (!isRecord(parsed)) {
|
|
609
|
+
throw new OAuthError("invalid_response", `OAuth 响应不是对象(HTTP ${response.status})`, {
|
|
610
|
+
status: response.status,
|
|
611
|
+
});
|
|
612
|
+
}
|
|
613
|
+
body = parsed;
|
|
614
|
+
}
|
|
615
|
+
return { status: response.status, body, requestId: requestIdOf(response.headers, body) };
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/** Cloudflare 授权码 + 粘贴流程:PKCE、令牌换发与刷新、账号回填、撤销与按实例独立存放的令牌文件。 */
|
|
287
620
|
export class CloudflareOAuth {
|
|
288
|
-
readonly
|
|
621
|
+
readonly instanceId: string;
|
|
622
|
+
readonly tokenDir: string;
|
|
289
623
|
readonly configPath: string;
|
|
290
624
|
|
|
291
625
|
private readonly config: CloudflareOAuthConfig;
|
|
292
|
-
private readonly
|
|
626
|
+
private readonly http: OAuthHttp;
|
|
293
627
|
private readonly clock: () => number;
|
|
294
628
|
private readonly accountsUrl: string;
|
|
295
629
|
private readonly revokeUrl: string;
|
|
296
|
-
private readonly timeoutMs: number;
|
|
297
630
|
private readonly env: NodeJS.ProcessEnv;
|
|
298
631
|
private readonly pending = new Map<string, PendingLogin>();
|
|
299
632
|
private refreshing: Promise<OAuthToken> | undefined;
|
|
300
633
|
|
|
301
634
|
constructor(options: CloudflareOAuthOptions) {
|
|
635
|
+
this.instanceId = assertInstanceId(options.instanceId);
|
|
302
636
|
this.config = options.config;
|
|
303
|
-
this.
|
|
637
|
+
this.tokenDir = options.tokenDir ?? DEFAULT_TOKEN_DIR;
|
|
304
638
|
this.configPath = options.configPath ?? DEFAULT_CONFIG_PATH;
|
|
305
|
-
this.
|
|
639
|
+
this.http = new OAuthHttp(options.fetch, options.timeoutMs);
|
|
306
640
|
this.clock = options.clock ?? Date.now;
|
|
307
641
|
this.accountsUrl = options.accountsUrl ?? DEFAULT_ACCOUNTS_URL;
|
|
308
642
|
this.revokeUrl = options.revokeUrl ?? DEFAULT_REVOKE_URL;
|
|
309
|
-
this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
310
643
|
this.env = options.env ?? process.env;
|
|
311
644
|
}
|
|
312
645
|
|
|
646
|
+
/** 返回当前实例在目录里的令牌文件路径;尚无文件时返回 undefined。 */
|
|
647
|
+
tokenPath(): string | undefined {
|
|
648
|
+
return readInstanceOAuthToken(this.tokenDir, this.instanceId)?.path
|
|
649
|
+
?? findInstanceTokenFiles(this.tokenDir, this.instanceId)[0];
|
|
650
|
+
}
|
|
651
|
+
|
|
313
652
|
/** 生成授权链接并把 state 与 code_verifier 留在内存,10 分钟过期。 */
|
|
314
653
|
beginLogin(): { authorizeUrl: string; state: string; expiresAt: number } {
|
|
315
654
|
const now = this.clock();
|
|
@@ -326,9 +665,10 @@ export class CloudflareOAuth {
|
|
|
326
665
|
};
|
|
327
666
|
}
|
|
328
667
|
|
|
329
|
-
/**
|
|
668
|
+
/** 用粘贴回来的授权码换令牌,按 <instanceId>+<accountId>.json 落盘并回填当前实例的 accountId。 */
|
|
330
669
|
async completeLogin(code: string, state: string): Promise<LoginResult> {
|
|
331
670
|
const verifier = this.takeVerifier(state);
|
|
671
|
+
const previous = this.loadToken();
|
|
332
672
|
const token = await this.exchangeCode(code, verifier);
|
|
333
673
|
|
|
334
674
|
let warning: string | undefined;
|
|
@@ -337,27 +677,32 @@ export class CloudflareOAuth {
|
|
|
337
677
|
} catch (error) {
|
|
338
678
|
warning = `accountId 回填失败:${errorMessage(error)}`;
|
|
339
679
|
}
|
|
340
|
-
this.saveToken(token);
|
|
341
|
-
|
|
342
680
|
let updatedInstances: string[] = [];
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
681
|
+
this.saveIfCurrent(previous, token, () => {
|
|
682
|
+
const store = new ConfigStore(this.configPath);
|
|
683
|
+
if (!token.account_id) {
|
|
684
|
+
warning ??= "Cloudflare 未返回可用账号";
|
|
685
|
+
if (previous || store.load(this.env).instances.find(item => item.id === this.instanceId)?.accountIdSetting) {
|
|
686
|
+
throw new OAuthError("account_lookup_failed", `${warning},未更改现有凭据或账号绑定`);
|
|
687
|
+
}
|
|
688
|
+
return undefined;
|
|
349
689
|
}
|
|
350
|
-
|
|
690
|
+
const binding = store.backfillCloudflareAccountId(token.account_id, this.env, { instanceId: this.instanceId });
|
|
691
|
+
updatedInstances = binding.updatedInstances;
|
|
692
|
+
return binding.rollback;
|
|
693
|
+
});
|
|
351
694
|
return { token, updatedInstances, warning };
|
|
352
695
|
}
|
|
353
696
|
|
|
354
697
|
/** 取可用于请求的 access token;60 秒内到期先刷新。 */
|
|
355
|
-
async accessToken(): Promise<string> {
|
|
356
|
-
const
|
|
357
|
-
if (!
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
698
|
+
async accessToken(expectedAccountId?: string): Promise<string> {
|
|
699
|
+
const current = this.loadToken();
|
|
700
|
+
if (!current) throw this.notLoggedIn();
|
|
701
|
+
const token = this.isExpiring(current) ? await this.refreshToken() : current;
|
|
702
|
+
if (expectedAccountId !== undefined && token.account_id !== expectedAccountId) {
|
|
703
|
+
throw new OAuthError("credentials_changed", "OAuth 账号已切换,未向旧账号端点发送请求");
|
|
704
|
+
}
|
|
705
|
+
return token.access_token;
|
|
361
706
|
}
|
|
362
707
|
|
|
363
708
|
/** 刷新令牌;同一时刻只发一次请求,响应没有 refresh_token 时沿用旧值。 */
|
|
@@ -365,7 +710,10 @@ export class CloudflareOAuth {
|
|
|
365
710
|
const current = this.loadToken();
|
|
366
711
|
if (!current) throw this.notLoggedIn();
|
|
367
712
|
if (!current.refresh_token) {
|
|
368
|
-
throw new OAuthError(
|
|
713
|
+
throw new OAuthError(
|
|
714
|
+
"not_logged_in",
|
|
715
|
+
`实例 ${this.instanceId} 的令牌没有 refresh_token,请重新授权:${this.tokenPath() ?? this.tokenDir}`,
|
|
716
|
+
);
|
|
369
717
|
}
|
|
370
718
|
if (!this.refreshing) {
|
|
371
719
|
this.refreshing = this.refresh(current).finally(() => {
|
|
@@ -375,37 +723,24 @@ export class CloudflareOAuth {
|
|
|
375
723
|
return this.refreshing;
|
|
376
724
|
}
|
|
377
725
|
|
|
378
|
-
/**
|
|
726
|
+
/** 撤销远端授权并删除当前实例的本地令牌;撤销失败也清除本地文件。 */
|
|
379
727
|
async logout(): Promise<LogoutResult> {
|
|
380
|
-
const token = this.
|
|
381
|
-
|
|
382
|
-
if (token?.refresh_token) {
|
|
383
|
-
try {
|
|
384
|
-
await this.postForm(this.revokeUrl, {
|
|
385
|
-
token: token.refresh_token,
|
|
386
|
-
token_type_hint: "refresh_token",
|
|
387
|
-
client_id: this.config.clientId,
|
|
388
|
-
});
|
|
389
|
-
} catch (error) {
|
|
390
|
-
warning = `撤销授权失败:${errorMessage(error)}`;
|
|
391
|
-
}
|
|
392
|
-
}
|
|
393
|
-
this.clearToken();
|
|
394
|
-
return { token, warning };
|
|
728
|
+
const token = takeInstanceToken(this.tokenDir, this.instanceId);
|
|
729
|
+
return this.http.revoke(token, this.config.clientId, this.revokeUrl);
|
|
395
730
|
}
|
|
396
731
|
|
|
397
|
-
/**
|
|
732
|
+
/** 读当前实例令牌文件;文件缺失或内容不合法时返回 undefined。 */
|
|
398
733
|
loadToken(): OAuthToken | undefined {
|
|
399
|
-
return
|
|
734
|
+
return readInstanceOAuthToken(this.tokenDir, this.instanceId)?.token;
|
|
400
735
|
}
|
|
401
736
|
|
|
402
|
-
/**
|
|
737
|
+
/** 删除当前实例的令牌文件。 */
|
|
403
738
|
clearToken(): void {
|
|
404
|
-
|
|
739
|
+
clearInstanceOAuthTokens(this.tokenDir, this.instanceId);
|
|
405
740
|
}
|
|
406
741
|
|
|
407
742
|
private async refresh(current: OAuthToken): Promise<OAuthToken> {
|
|
408
|
-
const body = await this.postForm(this.config.tokenUrl, {
|
|
743
|
+
const body = await this.http.postForm(this.config.tokenUrl, {
|
|
409
744
|
grant_type: "refresh_token",
|
|
410
745
|
refresh_token: current.refresh_token,
|
|
411
746
|
client_id: this.config.clientId,
|
|
@@ -416,12 +751,12 @@ export class CloudflareOAuth {
|
|
|
416
751
|
this.clock(),
|
|
417
752
|
);
|
|
418
753
|
granted.account_id = current.account_id;
|
|
419
|
-
this.
|
|
754
|
+
this.saveIfCurrent(current, granted);
|
|
420
755
|
return granted;
|
|
421
756
|
}
|
|
422
757
|
|
|
423
758
|
private async exchangeCode(code: string, verifier: string): Promise<OAuthToken> {
|
|
424
|
-
const body = await this.postForm(this.config.tokenUrl, {
|
|
759
|
+
const body = await this.http.postForm(this.config.tokenUrl, {
|
|
425
760
|
grant_type: "authorization_code",
|
|
426
761
|
code,
|
|
427
762
|
redirect_uri: this.config.redirectUri,
|
|
@@ -435,19 +770,24 @@ export class CloudflareOAuth {
|
|
|
435
770
|
private async fetchAccountId(accessToken: string): Promise<string> {
|
|
436
771
|
const url = new URL(this.accountsUrl);
|
|
437
772
|
url.searchParams.set("per_page", "50");
|
|
438
|
-
const { status, body, requestId } = await this.send(url.toString(), {
|
|
773
|
+
const { status, body, requestId } = await this.http.send(url.toString(), {
|
|
439
774
|
headers: { Authorization: `Bearer ${accessToken}` },
|
|
440
775
|
});
|
|
441
776
|
const result = body.result;
|
|
442
777
|
if (status >= 400 || !Array.isArray(result)) {
|
|
443
|
-
throw this.rejected("accounts_request_failed", status, requestId, body);
|
|
778
|
+
throw this.http.rejected("accounts_request_failed", status, requestId, body);
|
|
444
779
|
}
|
|
445
780
|
const first = result.find((item) => isRecord(item) && typeof item.id === "string");
|
|
446
781
|
return isRecord(first) && typeof first.id === "string" ? first.id : "";
|
|
447
782
|
}
|
|
448
783
|
|
|
449
|
-
private
|
|
450
|
-
|
|
784
|
+
private saveIfCurrent(previous: OAuthToken | undefined, token: OAuthToken, beforePublish?: BeforeTokenPublish): void {
|
|
785
|
+
withOAuthLock(this.tokenDir, () => {
|
|
786
|
+
if (!isDeepStrictEqual(previous, this.loadToken())) {
|
|
787
|
+
throw new OAuthError("credentials_changed", "此实例的 OAuth 凭据已变更,本次结果未使用");
|
|
788
|
+
}
|
|
789
|
+
installToken(this.tokenDir, this.instanceId, token, beforePublish);
|
|
790
|
+
});
|
|
451
791
|
}
|
|
452
792
|
|
|
453
793
|
private isExpiring(token: OAuthToken): boolean {
|
|
@@ -467,71 +807,10 @@ export class CloudflareOAuth {
|
|
|
467
807
|
}
|
|
468
808
|
|
|
469
809
|
private notLoggedIn(): OAuthError {
|
|
470
|
-
return new OAuthError(
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
private rejected(
|
|
475
|
-
code: string,
|
|
476
|
-
status: number,
|
|
477
|
-
requestId: string | undefined,
|
|
478
|
-
body: Record<string, unknown>,
|
|
479
|
-
): OAuthError {
|
|
480
|
-
const description = descriptionOf(body);
|
|
481
|
-
const detail = description ? `:${description}` : "";
|
|
482
|
-
const request = requestId ? `(request_id=${requestId})` : "";
|
|
483
|
-
const label = code.startsWith("http_") ? code : `${code} HTTP ${status}`;
|
|
484
|
-
const message = `OAuth 请求被拒绝(${label})${detail}${request}`;
|
|
485
|
-
return new OAuthError(code, message, { status, requestId });
|
|
486
|
-
}
|
|
487
|
-
|
|
488
|
-
/** 表单 POST:application/x-www-form-urlencoded,公共客户端不带 secret。 */
|
|
489
|
-
private async postForm(url: string, form: Record<string, string>): Promise<Record<string, unknown>> {
|
|
490
|
-
const { status, body, requestId } = await this.send(url, {
|
|
491
|
-
method: "POST",
|
|
492
|
-
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
493
|
-
body: new URLSearchParams(form).toString(),
|
|
494
|
-
});
|
|
495
|
-
const error = typeof body.error === "string" ? body.error.trim() : "";
|
|
496
|
-
if (status >= 400 || error) throw this.rejected(error || `http_${status}`, status, requestId, body);
|
|
497
|
-
return body;
|
|
810
|
+
return new OAuthError(
|
|
811
|
+
"not_logged_in",
|
|
812
|
+
`实例 ${this.instanceId} 尚未登录 Cloudflare,未找到令牌文件(目录:${this.tokenDir})`,
|
|
813
|
+
);
|
|
498
814
|
}
|
|
499
815
|
|
|
500
|
-
private async send(
|
|
501
|
-
url: string,
|
|
502
|
-
init: { method?: string; headers?: Record<string, string>; body?: string },
|
|
503
|
-
): Promise<{ status: number; body: Record<string, unknown>; requestId?: string }> {
|
|
504
|
-
let response: Response;
|
|
505
|
-
let text: string;
|
|
506
|
-
try {
|
|
507
|
-
response = await this.fetchImpl(url, {
|
|
508
|
-
method: init.method ?? "GET",
|
|
509
|
-
headers: { Accept: "application/json", ...init.headers },
|
|
510
|
-
body: init.body,
|
|
511
|
-
signal: AbortSignal.timeout(this.timeoutMs),
|
|
512
|
-
});
|
|
513
|
-
text = await response.text();
|
|
514
|
-
} catch (error) {
|
|
515
|
-
throw new OAuthError("network_error", `OAuth 请求失败:${errorMessage(error)}`);
|
|
516
|
-
}
|
|
517
|
-
|
|
518
|
-
let body: Record<string, unknown> = {};
|
|
519
|
-
if (text.trim()) {
|
|
520
|
-
let parsed: unknown;
|
|
521
|
-
try {
|
|
522
|
-
parsed = JSON.parse(text);
|
|
523
|
-
} catch {
|
|
524
|
-
throw new OAuthError("invalid_response", `OAuth 响应不是 JSON(HTTP ${response.status})`, {
|
|
525
|
-
status: response.status,
|
|
526
|
-
});
|
|
527
|
-
}
|
|
528
|
-
if (!isRecord(parsed)) {
|
|
529
|
-
throw new OAuthError("invalid_response", `OAuth 响应不是对象(HTTP ${response.status})`, {
|
|
530
|
-
status: response.status,
|
|
531
|
-
});
|
|
532
|
-
}
|
|
533
|
-
body = parsed;
|
|
534
|
-
}
|
|
535
|
-
return { status: response.status, body, requestId: requestIdOf(response.headers, body) };
|
|
536
|
-
}
|
|
537
816
|
}
|