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/config.ts
CHANGED
|
@@ -61,6 +61,8 @@ export interface ResolvedInstance {
|
|
|
61
61
|
usesCloudflareOAuth: boolean;
|
|
62
62
|
/** 用户配置的账号绑定,保留未解析的变量引用。 */
|
|
63
63
|
accountIdSetting?: string;
|
|
64
|
+
/** 请求路径随实际 OAuth 令牌的账号变化。 */
|
|
65
|
+
accountIdFromOAuth: boolean;
|
|
64
66
|
accountId?: string;
|
|
65
67
|
/** 模型名,仅 xai 这类按模型调用的供应商使用。 */
|
|
66
68
|
model?: string;
|
|
@@ -91,10 +93,23 @@ export interface ConfigFile {
|
|
|
91
93
|
[key: string]: unknown;
|
|
92
94
|
}
|
|
93
95
|
|
|
96
|
+
/** Cloudflare OAuth 令牌摘要;存在时允许免静态 key 的 cloudflare sdk 实例就绪。 */
|
|
97
|
+
export interface CloudflareOAuthTokenSummary {
|
|
98
|
+
accountId?: string;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** 回填 Cloudflare accountId 时的可选筛选条件。 */
|
|
102
|
+
export interface BackfillCloudflareOptions {
|
|
103
|
+
/** 仅回填指定实例;未传时匹配所有使用 OAuth 的实例。 */
|
|
104
|
+
instanceId?: string;
|
|
105
|
+
}
|
|
106
|
+
|
|
94
107
|
/** 解析配置时的运行时上下文,保持 resolveConfig 纯函数且便于测试隔离。 */
|
|
95
108
|
export interface ResolveConfigOptions {
|
|
96
|
-
/**
|
|
97
|
-
|
|
109
|
+
/** 按实例 ID 索引的 Cloudflare OAuth 令牌摘要。 */
|
|
110
|
+
cloudflareOAuthTokens?: Readonly<Record<string, CloudflareOAuthTokenSummary>>;
|
|
111
|
+
/** 读取凭据失败的实例,undefined 表示整个目录或旧授权迁移失败。 */
|
|
112
|
+
cloudflareOAuthReadFailures?: ReadonlySet<string | undefined>;
|
|
98
113
|
}
|
|
99
114
|
|
|
100
115
|
export interface LoadedConfig {
|
|
@@ -291,7 +306,8 @@ function resolveInstance(
|
|
|
291
306
|
const enabled = booleanValue(raw.enabled, `${label}.enabled`, true);
|
|
292
307
|
const usesCloudflareOAuth = enabled && preset.id === "cloudflare" && mode === "sdk"
|
|
293
308
|
&& auth.type === "bearer" && keys.length === 0;
|
|
294
|
-
const
|
|
309
|
+
const tokens = options?.cloudflareOAuthTokens;
|
|
310
|
+
const oauthToken = usesCloudflareOAuth && tokens && Object.hasOwn(tokens, id) ? tokens[id] : undefined;
|
|
295
311
|
let status: InstanceStatus = "ready";
|
|
296
312
|
if (auth.type === "none" && keys.length === 0) {
|
|
297
313
|
status = "ready";
|
|
@@ -301,7 +317,10 @@ function resolveInstance(
|
|
|
301
317
|
status = "unconfigured";
|
|
302
318
|
const missing = missingVariables(keys, env);
|
|
303
319
|
if (usesCloudflareOAuth) {
|
|
304
|
-
|
|
320
|
+
const failures = options?.cloudflareOAuthReadFailures;
|
|
321
|
+
warnings.push(failures?.has(id) || failures?.has(undefined)
|
|
322
|
+
? "Cloudflare OAuth 凭据暂不可用,详见 /search status"
|
|
323
|
+
: "未配置 API Token,也未登录 Cloudflare OAuth(在 /search 登录)");
|
|
305
324
|
} else {
|
|
306
325
|
warnings.push(missing.length ? `凭证变量未设置:${missing.join(", ")}` : "没有可用凭证");
|
|
307
326
|
}
|
|
@@ -309,7 +328,10 @@ function resolveInstance(
|
|
|
309
328
|
|
|
310
329
|
const paths = resolvePaths(raw.paths, preset, label);
|
|
311
330
|
const accountIdSetting = raw.accountId === undefined ? undefined : stringValue(raw.accountId, `${label}.accountId`).trim();
|
|
312
|
-
const
|
|
331
|
+
const managed = !!accountIdSetting && raw.oauthBackfilledAccountId === accountIdSetting && !secretVariables(accountIdSetting).length;
|
|
332
|
+
const accountIdFromOAuth = usesCloudflareOAuth && (!accountIdSetting || managed);
|
|
333
|
+
const binding = accountIdFromOAuth && oauthToken ? oauthToken.accountId : resolveSecret(accountIdSetting, env);
|
|
334
|
+
const accountId = binding?.trim() || undefined;
|
|
313
335
|
const missingAccountFor = preset.requiresAccountId && !accountId
|
|
314
336
|
? CLOUDFLARE_OPERATIONS.filter((op) => paths[CLOUDFLARE_TOOL_PATHS[op]]?.includes("{accountId}"))
|
|
315
337
|
: [];
|
|
@@ -330,6 +352,7 @@ function resolveInstance(
|
|
|
330
352
|
auth,
|
|
331
353
|
usesCloudflareOAuth,
|
|
332
354
|
accountIdSetting,
|
|
355
|
+
accountIdFromOAuth,
|
|
333
356
|
accountId,
|
|
334
357
|
model: raw.model === undefined ? undefined : requiredString(raw.model, `${label}.model`),
|
|
335
358
|
xSearch: booleanValue(raw.xSearch, `${label}.xSearch`, false),
|
|
@@ -536,20 +559,29 @@ export class ConfigStore {
|
|
|
536
559
|
}
|
|
537
560
|
|
|
538
561
|
/** 从同一份配置快照选择 OAuth 回填目标,没有目标时保留原文件。 */
|
|
539
|
-
backfillCloudflareAccountId(
|
|
562
|
+
backfillCloudflareAccountId(
|
|
563
|
+
accountId: string,
|
|
564
|
+
env: NodeJS.ProcessEnv,
|
|
565
|
+
options: BackfillCloudflareOptions = {},
|
|
566
|
+
): { updatedInstances: string[]; rollback?: () => void } {
|
|
540
567
|
const { raw, text, exists } = this.read();
|
|
541
|
-
if (!exists) return [];
|
|
568
|
+
if (!exists) return { updatedInstances: [] };
|
|
542
569
|
const file = parseConfigText(text, this.path);
|
|
543
570
|
const { instances } = resolveConfig(file, env);
|
|
544
571
|
const updated: string[] = [];
|
|
545
|
-
if (!Array.isArray(file.instances)) return updated;
|
|
572
|
+
if (!Array.isArray(file.instances)) return { updatedInstances: updated };
|
|
546
573
|
for (const [index, instance] of instances.entries()) {
|
|
547
|
-
if (
|
|
574
|
+
if (options.instanceId !== undefined && instance.id !== options.instanceId) continue;
|
|
575
|
+
if (!instance.usesCloudflareOAuth) continue;
|
|
576
|
+
const current = instance.accountIdSetting;
|
|
577
|
+
if (current && (!instance.accountIdFromOAuth || current === accountId)) continue;
|
|
548
578
|
file.instances[index].accountId = accountId;
|
|
579
|
+
file.instances[index].oauthBackfilledAccountId = accountId;
|
|
549
580
|
updated.push(instance.id);
|
|
550
581
|
}
|
|
551
|
-
if (updated.length
|
|
552
|
-
|
|
582
|
+
if (!updated.length) return { updatedInstances: updated };
|
|
583
|
+
const written = this.write(file, raw, exists);
|
|
584
|
+
return { updatedInstances: updated, rollback: () => this.writeRaw(raw, written, true) };
|
|
553
585
|
}
|
|
554
586
|
|
|
555
587
|
save(file: ConfigFile, env: NodeJS.ProcessEnv = process.env, options?: ResolveConfigOptions): void {
|
|
@@ -564,11 +596,15 @@ export class ConfigStore {
|
|
|
564
596
|
return { raw, text: raw.replace(/^\uFEFF/, ""), exists };
|
|
565
597
|
}
|
|
566
598
|
|
|
567
|
-
private write(file: ConfigFile, previousRaw: string, existed: boolean):
|
|
599
|
+
private write(file: ConfigFile, previousRaw: string, existed: boolean): string {
|
|
568
600
|
const newline = previousRaw.includes("\r\n") ? "\r\n" : "\n";
|
|
569
601
|
const bom = previousRaw.startsWith("\uFEFF") ? "\uFEFF" : "";
|
|
570
602
|
const next = bom + `${stringify(file, null, 2)}\n`.replace(/\r?\n/g, newline);
|
|
603
|
+
this.writeRaw(next, previousRaw, existed);
|
|
604
|
+
return next;
|
|
605
|
+
}
|
|
571
606
|
|
|
607
|
+
private writeRaw(next: string, previousRaw: string, existed: boolean): void {
|
|
572
608
|
mkdirSync(dirname(this.path), { recursive: true });
|
|
573
609
|
const temp = `${this.path}.${randomUUID()}.tmp`;
|
|
574
610
|
const mode = existed ? statSync(this.path).mode & 0o777 : 0o600;
|
package/src/http.ts
CHANGED
|
@@ -135,7 +135,7 @@ export interface HttpClientOptions {
|
|
|
135
135
|
fetch?: typeof globalThis.fetch;
|
|
136
136
|
clock?: () => number;
|
|
137
137
|
/** Cloudflare OAuth 令牌来源;仅在 cloudflare sdk 实例未配置静态 keys 时使用。 */
|
|
138
|
-
cloudflareOAuth?: { accessToken(): Promise<string> };
|
|
138
|
+
cloudflareOAuth?: { accessToken(instanceId: string, expectedAccountId?: string): Promise<string> };
|
|
139
139
|
onInstanceFailure?: (failure: ProviderAttempt) => void;
|
|
140
140
|
/** 按密钥的调用次数限额存储;省略时使用仅内存实例。 */
|
|
141
141
|
usage?: UsageStore;
|
|
@@ -317,7 +317,7 @@ export class HttpClient {
|
|
|
317
317
|
private readonly globalUserAgent?: string;
|
|
318
318
|
private readonly fetchImpl: typeof globalThis.fetch;
|
|
319
319
|
private readonly clock: () => number;
|
|
320
|
-
private readonly cloudflareOAuth?:
|
|
320
|
+
private readonly cloudflareOAuth?: HttpClientOptions["cloudflareOAuth"];
|
|
321
321
|
private readonly onInstanceFailure?: HttpClientOptions["onInstanceFailure"];
|
|
322
322
|
private readonly usage: UsageStore;
|
|
323
323
|
private readonly pools = new Map<string, { signature: string; pool: KeyPool }>();
|
|
@@ -442,7 +442,8 @@ export class HttpClient {
|
|
|
442
442
|
if (instance.usesCloudflareOAuth && this.cloudflareOAuth) {
|
|
443
443
|
let token: string;
|
|
444
444
|
try {
|
|
445
|
-
|
|
445
|
+
const expectedAccountId = instance.accountIdFromOAuth ? instance.accountId ?? "" : undefined;
|
|
446
|
+
token = await this.cloudflareOAuth.accessToken(instance.id, expectedAccountId);
|
|
446
447
|
} catch (error) {
|
|
447
448
|
throw new ProviderError({
|
|
448
449
|
instance: instance.id,
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { chmodSync, closeSync, lstatSync, mkdirSync, openSync } from "node:fs";
|
|
2
|
+
|
|
3
|
+
/** 所有进程在同一个短事务内检查和更新 OAuth 文件,网络请求不持锁。 */
|
|
4
|
+
export function withOAuthLock<T>(dir: string, action: () => T): T {
|
|
5
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
6
|
+
const info = lstatSync(dir);
|
|
7
|
+
if (!info.isDirectory()) throw new Error("OAuth 令牌目录必须是普通目录");
|
|
8
|
+
if (process.platform !== "win32" && (info.mode & 0o777) !== 0o700) chmodSync(dir, 0o700);
|
|
9
|
+
|
|
10
|
+
const path = `${dir}.lock.sqlite`;
|
|
11
|
+
try {
|
|
12
|
+
closeSync(openSync(path, "wx", 0o600));
|
|
13
|
+
} catch (error) {
|
|
14
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
|
15
|
+
const lock = lstatSync(path);
|
|
16
|
+
if (!lock.isFile() || (process.platform !== "win32" && (lock.mode & 0o077) !== 0)) {
|
|
17
|
+
throw new Error("OAuth 锁必须是私有普通文件");
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
const sqlite = process.getBuiltinModule("node:sqlite") as typeof import("node:sqlite") | undefined;
|
|
21
|
+
if (!sqlite) throw new Error("OAuth 凭据写入需要 Node 内置的 node:sqlite");
|
|
22
|
+
const db = new sqlite.DatabaseSync(path);
|
|
23
|
+
try {
|
|
24
|
+
db.exec("PRAGMA busy_timeout = 3000; BEGIN IMMEDIATE");
|
|
25
|
+
return action();
|
|
26
|
+
} finally {
|
|
27
|
+
db.close();
|
|
28
|
+
}
|
|
29
|
+
}
|
package/src/settings-ui.ts
CHANGED
|
@@ -13,6 +13,7 @@ import {
|
|
|
13
13
|
type ResolvedInstance,
|
|
14
14
|
} from "./config.ts";
|
|
15
15
|
import {
|
|
16
|
+
LEGACY_OAUTH_TARGET,
|
|
16
17
|
parseAuthorizationCode,
|
|
17
18
|
type LoginResult,
|
|
18
19
|
type LogoutResult,
|
|
@@ -32,6 +33,7 @@ import { resolveSecret, secretVariables } from "./secrets.ts";
|
|
|
32
33
|
/** 面板用到的 Cloudflare OAuth 能力,由 CloudflareOAuth 实现。 */
|
|
33
34
|
export interface PanelOAuth {
|
|
34
35
|
loadToken(): OAuthToken | undefined;
|
|
36
|
+
clearToken(): void;
|
|
35
37
|
beginLogin(): { authorizeUrl: string; state: string; expiresAt: number };
|
|
36
38
|
completeLogin(code: string, state: string): Promise<LoginResult>;
|
|
37
39
|
logout(): Promise<LogoutResult>;
|
|
@@ -69,7 +71,11 @@ export interface PanelSource {
|
|
|
69
71
|
readonly lastSuccess?: string;
|
|
70
72
|
recordSuccess(instance: string): void;
|
|
71
73
|
lastFailure(instance: string): string | undefined;
|
|
72
|
-
|
|
74
|
+
oauthToken?(instanceId: string): OAuthToken | undefined;
|
|
75
|
+
oauthTokens?(): Record<string, OAuthToken>;
|
|
76
|
+
legacyToken?(): OAuthToken | undefined;
|
|
77
|
+
logoutLegacy?(): Promise<LogoutResult>;
|
|
78
|
+
cloudflareOAuth?(instanceId: string, config?: LoadedConfig): PanelOAuth;
|
|
73
79
|
resolveOptions?(): ResolveConfigOptions;
|
|
74
80
|
}
|
|
75
81
|
|
|
@@ -209,13 +215,17 @@ export async function openSearchPanel(
|
|
|
209
215
|
}
|
|
210
216
|
}
|
|
211
217
|
|
|
218
|
+
function instanceOAuthToken(source: PanelSource, instanceId: string, config?: LoadedConfig): OAuthToken | undefined {
|
|
219
|
+
return source.oauthToken ? source.oauthToken(instanceId) : source.cloudflareOAuth?.(instanceId, config)?.loadToken();
|
|
220
|
+
}
|
|
221
|
+
|
|
212
222
|
function rowLabel(source: PanelSource, instance: ResolvedInstance, service?: PanelService): string {
|
|
213
223
|
const parts: string[] = [instance.id, instance.preset.id, instance.mode, stateOf(instance)];
|
|
214
224
|
|
|
215
225
|
const masked = instance.keys.map(maskedKey);
|
|
216
226
|
if (masked.length > 0) {
|
|
217
227
|
parts.push(`凭证 ${masked.join(", ")}`);
|
|
218
|
-
} else if (instance.usesCloudflareOAuth && source.
|
|
228
|
+
} else if (instance.usesCloudflareOAuth && instanceOAuthToken(source, instance.id)) {
|
|
219
229
|
parts.push("OAuth 已登录");
|
|
220
230
|
}
|
|
221
231
|
|
|
@@ -252,7 +262,7 @@ async function manageInstance(ctx: ExtensionCommandContext, deps: Deps, id: stri
|
|
|
252
262
|
const instance = loaded.ok ? loaded.config.instances.find((item) => item.id === id) : undefined;
|
|
253
263
|
const actions: string[] = [];
|
|
254
264
|
if (instance?.usesCloudflareOAuth && deps.source.cloudflareOAuth) {
|
|
255
|
-
const loggedIn = deps.source
|
|
265
|
+
const loggedIn = instanceOAuthToken(deps.source, id, loaded.ok ? loaded.config : undefined) !== undefined;
|
|
256
266
|
actions.push(loggedIn ? PANEL_CHOICES.cfOAuthRelogin : PANEL_CHOICES.cfOAuthLogin);
|
|
257
267
|
if (loggedIn) actions.push(PANEL_CHOICES.cfOAuthLogout);
|
|
258
268
|
}
|
|
@@ -260,9 +270,9 @@ async function manageInstance(ctx: ExtensionCommandContext, deps: Deps, id: stri
|
|
|
260
270
|
|
|
261
271
|
const action = await ctx.ui.select(`实例 ${id}`, actions);
|
|
262
272
|
if (action === PANEL_CHOICES.cfOAuthLogin || action === PANEL_CHOICES.cfOAuthRelogin) {
|
|
263
|
-
await runCloudflareLogin(ctx, deps);
|
|
273
|
+
await runCloudflareLogin(ctx, deps, id);
|
|
264
274
|
} else if (action === PANEL_CHOICES.cfOAuthLogout) {
|
|
265
|
-
await runCloudflareLogout(ctx, deps);
|
|
275
|
+
await runCloudflareLogout(ctx, deps, id);
|
|
266
276
|
} else if (action === PANEL_CHOICES.edit) {
|
|
267
277
|
await editInstance(ctx, deps, id);
|
|
268
278
|
} else if (action === PANEL_CHOICES.test) {
|
|
@@ -344,7 +354,7 @@ async function createInstance(ctx: ExtensionCommandContext, deps: Deps): Promise
|
|
|
344
354
|
}
|
|
345
355
|
|
|
346
356
|
if (useCloudflareOAuth) {
|
|
347
|
-
await runCloudflareLogin(ctx, deps);
|
|
357
|
+
await runCloudflareLogin(ctx, deps, id);
|
|
348
358
|
return;
|
|
349
359
|
}
|
|
350
360
|
|
|
@@ -423,6 +433,7 @@ async function editInstance(ctx: ExtensionCommandContext, deps: Deps, id: string
|
|
|
423
433
|
const value = text.trim();
|
|
424
434
|
if (value) raw.accountId = value;
|
|
425
435
|
else delete raw.accountId;
|
|
436
|
+
delete raw.oauthBackfilledAccountId;
|
|
426
437
|
});
|
|
427
438
|
return;
|
|
428
439
|
}
|
|
@@ -453,10 +464,14 @@ async function editInstance(ctx: ExtensionCommandContext, deps: Deps, id: string
|
|
|
453
464
|
}
|
|
454
465
|
|
|
455
466
|
async function removeInstance(ctx: ExtensionCommandContext, deps: Deps, id: string): Promise<void> {
|
|
456
|
-
const
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
);
|
|
467
|
+
const loaded = loadPanel(deps.source);
|
|
468
|
+
const config = loaded.ok ? loaded.config : undefined;
|
|
469
|
+
const target = config?.instances.find((item) => item.id === id);
|
|
470
|
+
const hasOAuthToken = instanceOAuthToken(deps.source, id, config) !== undefined;
|
|
471
|
+
const confirmText = hasOAuthToken
|
|
472
|
+
? "会从配置里移除该实例,以及它在搜索链、抓取链上的引用,并清除该实例的本地 OAuth 令牌。"
|
|
473
|
+
: "会从配置里移除该实例,以及它在搜索链、抓取链上的引用。";
|
|
474
|
+
const confirmed = await ctx.ui.confirm(`删除实例 ${id}?`, confirmText);
|
|
460
475
|
if (!confirmed) return;
|
|
461
476
|
|
|
462
477
|
const result = write(deps, (file) => removeInstanceFrom(file, id));
|
|
@@ -464,6 +479,10 @@ async function removeInstance(ctx: ExtensionCommandContext, deps: Deps, id: stri
|
|
|
464
479
|
ctx.ui.notify(`未写入:${result.error}。原文件未改动。`, "error");
|
|
465
480
|
return;
|
|
466
481
|
}
|
|
482
|
+
if (hasOAuthToken || target?.usesCloudflareOAuth) {
|
|
483
|
+
deps.source.cloudflareOAuth?.(id, result.config)?.clearToken();
|
|
484
|
+
deps.source.reload();
|
|
485
|
+
}
|
|
467
486
|
const remaining = result.config.instances.length;
|
|
468
487
|
ctx.ui.notify(remaining === 0 ? `已删除 ${id},配置里没有实例了` : `已删除 ${id}`, "info");
|
|
469
488
|
}
|
|
@@ -1014,14 +1033,125 @@ type OAuthDialogOutcome =
|
|
|
1014
1033
|
| { kind: "error"; message: string }
|
|
1015
1034
|
| { kind: "cancelled" };
|
|
1016
1035
|
|
|
1017
|
-
|
|
1018
|
-
|
|
1036
|
+
async function resolveLoginTargetInstance(
|
|
1037
|
+
ctx: ExtensionCommandContext,
|
|
1038
|
+
options: PanelOptions,
|
|
1039
|
+
config: LoadedConfig,
|
|
1040
|
+
instanceId?: string,
|
|
1041
|
+
): Promise<string | undefined> {
|
|
1042
|
+
const eligible = config.instances.filter((item) => item.usesCloudflareOAuth);
|
|
1043
|
+
if (instanceId !== undefined) {
|
|
1044
|
+
const matched = config.instances.find((item) => item.id === instanceId);
|
|
1045
|
+
if (!matched) {
|
|
1046
|
+
ctx.ui.notify(`实例不存在:${instanceId}`, "warning");
|
|
1047
|
+
return undefined;
|
|
1048
|
+
}
|
|
1049
|
+
if (!matched.usesCloudflareOAuth) {
|
|
1050
|
+
ctx.ui.notify(
|
|
1051
|
+
`实例 ${instanceId} 未启用 Cloudflare OAuth(仅未配置静态 keys 的启用 cloudflare sdk 实例可用)`,
|
|
1052
|
+
"warning",
|
|
1053
|
+
);
|
|
1054
|
+
return undefined;
|
|
1055
|
+
}
|
|
1056
|
+
return matched.id;
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
if (eligible.length === 0) {
|
|
1060
|
+
ctx.ui.notify("配置中尚无可用的 Cloudflare OAuth 实例,请先在 /search 新建一个 Cloudflare(OAuth)实例", "warning");
|
|
1061
|
+
return undefined;
|
|
1062
|
+
}
|
|
1063
|
+
if (eligible.length === 1) return eligible[0]!.id;
|
|
1064
|
+
|
|
1065
|
+
if (typeof ctx.ui.select !== "function") {
|
|
1066
|
+
ctx.ui.notify(
|
|
1067
|
+
`存在多个 Cloudflare OAuth 实例(${eligible.map((item) => item.id).join("、")}),请指定实例:/search login cloudflare <实例>`,
|
|
1068
|
+
"warning",
|
|
1069
|
+
);
|
|
1070
|
+
return undefined;
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
const choices = eligible.map((item) => {
|
|
1074
|
+
const token = instanceOAuthToken(options.source, item.id, config);
|
|
1075
|
+
const suffix = token
|
|
1076
|
+
? token.account_id
|
|
1077
|
+
? `已登录:${token.account_id}`
|
|
1078
|
+
: "已登录"
|
|
1079
|
+
: "未登录";
|
|
1080
|
+
return { id: item.id, label: `${item.id}(${suffix})` };
|
|
1081
|
+
});
|
|
1082
|
+
const picked = await ctx.ui.select("选择要登录的 Cloudflare OAuth 实例", choices.map((item) => item.label));
|
|
1083
|
+
if (picked === undefined) {
|
|
1084
|
+
ctx.ui.notify("已取消 Cloudflare OAuth 登录", "info");
|
|
1085
|
+
return undefined;
|
|
1086
|
+
}
|
|
1087
|
+
return choices.find((item) => item.label === picked)?.id;
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
async function resolveLogoutTargetInstance(
|
|
1091
|
+
ctx: ExtensionCommandContext,
|
|
1092
|
+
options: PanelOptions,
|
|
1093
|
+
config: LoadedConfig,
|
|
1094
|
+
instanceId?: string,
|
|
1095
|
+
): Promise<string | undefined> {
|
|
1096
|
+
if (instanceId !== undefined) {
|
|
1097
|
+
if (!/^[A-Za-z0-9_-]+$/.test(instanceId)) {
|
|
1098
|
+
ctx.ui.notify(`实例不存在:${instanceId}`, "warning");
|
|
1099
|
+
return undefined;
|
|
1100
|
+
}
|
|
1101
|
+
return instanceId;
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
const stored = options.source.oauthTokens?.() ?? {};
|
|
1105
|
+
const ids = new Set<string>(Object.keys(stored));
|
|
1106
|
+
for (const item of config.instances) {
|
|
1107
|
+
if (item.usesCloudflareOAuth && instanceOAuthToken(options.source, item.id, config)) {
|
|
1108
|
+
ids.add(item.id);
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
if (options.source.legacyToken?.()) ids.add(LEGACY_OAUTH_TARGET);
|
|
1112
|
+
const loggedInIds = [...ids];
|
|
1113
|
+
if (loggedInIds.length === 0) {
|
|
1114
|
+
ctx.ui.notify("当前未登录 Cloudflare OAuth", "info");
|
|
1115
|
+
return undefined;
|
|
1116
|
+
}
|
|
1117
|
+
if (loggedInIds.length === 1) return loggedInIds[0]!;
|
|
1118
|
+
|
|
1119
|
+
if (typeof ctx.ui.select !== "function") {
|
|
1120
|
+
ctx.ui.notify(
|
|
1121
|
+
`存在多个已登录的 Cloudflare OAuth 实例(${loggedInIds.join("、")}),请指定实例:/search logout cloudflare <实例>`,
|
|
1122
|
+
"warning",
|
|
1123
|
+
);
|
|
1124
|
+
return undefined;
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
const choices = loggedInIds.map((id) => {
|
|
1128
|
+
if (id === LEGACY_OAUTH_TARGET) return { id, label: "旧版 OAuth 授权" };
|
|
1129
|
+
const token = Object.hasOwn(stored, id) ? stored[id] : instanceOAuthToken(options.source, id, config);
|
|
1130
|
+
return { id, label: token?.account_id ? `${id}(accountId ${token.account_id})` : id };
|
|
1131
|
+
});
|
|
1132
|
+
const picked = await ctx.ui.select("选择要退出的 Cloudflare OAuth 实例", choices.map((item) => item.label));
|
|
1133
|
+
if (picked === undefined) {
|
|
1134
|
+
ctx.ui.notify("已取消 Cloudflare OAuth 退出", "info");
|
|
1135
|
+
return undefined;
|
|
1136
|
+
}
|
|
1137
|
+
return choices.find((item) => item.label === picked)?.id;
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
/** 打开 Cloudflare OAuth 登录页面(优先使用 pi 原生 LoginDialogComponent),完成换发与单实例 accountId 回填。 */
|
|
1141
|
+
export async function runCloudflareLogin(
|
|
1142
|
+
ctx: ExtensionCommandContext,
|
|
1143
|
+
options: PanelOptions,
|
|
1144
|
+
instanceId?: string,
|
|
1145
|
+
): Promise<boolean> {
|
|
1019
1146
|
const loaded = loadPanel(options.source);
|
|
1020
1147
|
if (!loaded.ok) {
|
|
1021
1148
|
ctx.ui.notify(`读取配置失败:${loaded.error}`, "error");
|
|
1022
1149
|
return false;
|
|
1023
1150
|
}
|
|
1024
|
-
const
|
|
1151
|
+
const targetId = await resolveLoginTargetInstance(ctx, options, loaded.config, instanceId);
|
|
1152
|
+
if (!targetId) return false;
|
|
1153
|
+
|
|
1154
|
+
const oauth = options.source.cloudflareOAuth?.(targetId, loaded.config);
|
|
1025
1155
|
if (!oauth) {
|
|
1026
1156
|
ctx.ui.notify("当前运行环境未启用 Cloudflare OAuth", "error");
|
|
1027
1157
|
return false;
|
|
@@ -1029,20 +1159,20 @@ export async function runCloudflareLogin(ctx: ExtensionCommandContext, options:
|
|
|
1029
1159
|
|
|
1030
1160
|
const { authorizeUrl, state } = oauth.beginLogin();
|
|
1031
1161
|
const outcome = ctx.mode === "tui" && typeof ctx.ui.custom === "function"
|
|
1032
|
-
? (await showCloudflareLoginDialog(ctx, oauth, authorizeUrl, state)) ?? { kind: "cancelled" as const }
|
|
1033
|
-
: await showCloudflareLoginFallback(ctx, oauth, authorizeUrl, state);
|
|
1162
|
+
? (await showCloudflareLoginDialog(ctx, oauth, targetId, authorizeUrl, state)) ?? { kind: "cancelled" as const }
|
|
1163
|
+
: await showCloudflareLoginFallback(ctx, oauth, targetId, authorizeUrl, state);
|
|
1034
1164
|
|
|
1035
1165
|
if (outcome.kind === "cancelled") {
|
|
1036
1166
|
ctx.ui.notify("已取消 Cloudflare OAuth 登录", "info");
|
|
1037
1167
|
return false;
|
|
1038
1168
|
}
|
|
1039
1169
|
if (outcome.kind === "error") {
|
|
1040
|
-
ctx.ui.notify(`Cloudflare OAuth
|
|
1170
|
+
ctx.ui.notify(`Cloudflare OAuth 登录失败(${targetId}):${outcome.message}`, "error");
|
|
1041
1171
|
return false;
|
|
1042
1172
|
}
|
|
1043
1173
|
|
|
1044
1174
|
options.source.reload();
|
|
1045
|
-
const parts = [
|
|
1175
|
+
const parts = [`Cloudflare OAuth 登录成功(${targetId})`];
|
|
1046
1176
|
if (outcome.result.token.account_id) parts.push(`Account ID:${outcome.result.token.account_id}`);
|
|
1047
1177
|
if (outcome.result.updatedInstances.length > 0) {
|
|
1048
1178
|
parts.push(`已回填实例:${outcome.result.updatedInstances.join(", ")}`);
|
|
@@ -1052,30 +1182,42 @@ export async function runCloudflareLogin(ctx: ExtensionCommandContext, options:
|
|
|
1052
1182
|
return true;
|
|
1053
1183
|
}
|
|
1054
1184
|
|
|
1055
|
-
/**
|
|
1056
|
-
export async function runCloudflareLogout(
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1185
|
+
/** 撤销指定实例的远端 Cloudflare OAuth 授权并删除本地令牌文件。 */
|
|
1186
|
+
export async function runCloudflareLogout(
|
|
1187
|
+
ctx: ExtensionCommandContext,
|
|
1188
|
+
options: PanelOptions,
|
|
1189
|
+
instanceId?: string,
|
|
1190
|
+
): Promise<void> {
|
|
1191
|
+
let targetId = instanceId;
|
|
1192
|
+
let result: LogoutResult;
|
|
1193
|
+
try {
|
|
1194
|
+
if (targetId !== LEGACY_OAUTH_TARGET) {
|
|
1195
|
+
const loaded = loadPanel(options.source);
|
|
1196
|
+
if (!loaded.ok) throw new Error(`读取配置失败:${loaded.error}`);
|
|
1197
|
+
targetId = await resolveLogoutTargetInstance(ctx, options, loaded.config, instanceId);
|
|
1198
|
+
if (!targetId) return;
|
|
1199
|
+
}
|
|
1200
|
+
if (targetId === LEGACY_OAUTH_TARGET && options.source.logoutLegacy) {
|
|
1201
|
+
result = await options.source.logoutLegacy();
|
|
1202
|
+
} else {
|
|
1203
|
+
const oauth = options.source.cloudflareOAuth?.(targetId);
|
|
1204
|
+
if (!oauth) throw new Error("当前运行环境未启用 Cloudflare OAuth");
|
|
1205
|
+
result = await oauth.logout();
|
|
1206
|
+
}
|
|
1207
|
+
} catch (error) {
|
|
1208
|
+
ctx.ui.notify(`Cloudflare OAuth 退出失败:${messageOf(error)}`, "error");
|
|
1065
1209
|
return;
|
|
1066
1210
|
}
|
|
1067
|
-
|
|
1068
|
-
const result = await oauth.logout();
|
|
1069
1211
|
options.source.reload();
|
|
1070
1212
|
if (!result.token) {
|
|
1071
|
-
ctx.ui.notify(
|
|
1213
|
+
ctx.ui.notify(`实例 ${targetId} 当前未登录 Cloudflare OAuth`, "info");
|
|
1072
1214
|
return;
|
|
1073
1215
|
}
|
|
1074
1216
|
if (result.warning) {
|
|
1075
|
-
ctx.ui.notify(
|
|
1217
|
+
ctx.ui.notify(`已清除实例 ${targetId} 的本地 Cloudflare OAuth 令牌(${result.warning})`, "warning");
|
|
1076
1218
|
return;
|
|
1077
1219
|
}
|
|
1078
|
-
ctx.ui.notify(
|
|
1220
|
+
ctx.ui.notify(`已退出 Cloudflare OAuth(${targetId})并清除本地令牌`, "info");
|
|
1079
1221
|
}
|
|
1080
1222
|
|
|
1081
1223
|
/** 动态铺满终端宽度的分隔线,完全依赖宿主传入的 theme,不依赖内部单例。 */
|
|
@@ -1117,6 +1259,7 @@ class CloudflareLoginDialog extends Container {
|
|
|
1117
1259
|
tui: TUI,
|
|
1118
1260
|
theme: Theme,
|
|
1119
1261
|
keybindings: KeybindingsManager,
|
|
1262
|
+
instanceId: string,
|
|
1120
1263
|
authorizeUrl: string,
|
|
1121
1264
|
onSubmit: (raw: string) => Promise<void>,
|
|
1122
1265
|
onCancel: () => void,
|
|
@@ -1129,7 +1272,7 @@ class CloudflareLoginDialog extends Container {
|
|
|
1129
1272
|
|
|
1130
1273
|
const clickHint = process.platform === "darwin" ? "Cmd+Click 打开" : "Ctrl+Click 打开";
|
|
1131
1274
|
this.addChild(new Divider(theme));
|
|
1132
|
-
this.addChild(new Text(theme.fg("accent", theme.bold(
|
|
1275
|
+
this.addChild(new Text(theme.fg("accent", theme.bold(`Cloudflare OAuth 登录(${instanceId})`)), 1, 0));
|
|
1133
1276
|
this.addChild(new Spacer(1));
|
|
1134
1277
|
this.addChild(new Text(theme.fg("accent", hyperlink(authorizeUrl, authorizeUrl)), 1, 0));
|
|
1135
1278
|
this.addChild(new Text(theme.fg("dim", `(${clickHint},或直接复制上方链接到浏览器)`), 1, 0));
|
|
@@ -1180,6 +1323,7 @@ class CloudflareLoginDialog extends Container {
|
|
|
1180
1323
|
async function showCloudflareLoginDialog(
|
|
1181
1324
|
ctx: ExtensionCommandContext,
|
|
1182
1325
|
oauth: PanelOAuth,
|
|
1326
|
+
instanceId: string,
|
|
1183
1327
|
authorizeUrl: string,
|
|
1184
1328
|
state: string,
|
|
1185
1329
|
): Promise<OAuthDialogOutcome> {
|
|
@@ -1188,6 +1332,7 @@ async function showCloudflareLoginDialog(
|
|
|
1188
1332
|
tui,
|
|
1189
1333
|
theme,
|
|
1190
1334
|
keybindings,
|
|
1335
|
+
instanceId,
|
|
1191
1336
|
authorizeUrl,
|
|
1192
1337
|
async (raw) => {
|
|
1193
1338
|
try {
|
|
@@ -1206,11 +1351,12 @@ async function showCloudflareLoginDialog(
|
|
|
1206
1351
|
async function showCloudflareLoginFallback(
|
|
1207
1352
|
ctx: ExtensionCommandContext,
|
|
1208
1353
|
oauth: PanelOAuth,
|
|
1354
|
+
instanceId: string,
|
|
1209
1355
|
authorizeUrl: string,
|
|
1210
1356
|
state: string,
|
|
1211
1357
|
): Promise<OAuthDialogOutcome> {
|
|
1212
1358
|
const raw = await ctx.ui.input(
|
|
1213
|
-
`Cloudflare OAuth
|
|
1359
|
+
`Cloudflare OAuth 登录(${instanceId})\n请在浏览器打开:\n${authorizeUrl}\n授权后粘贴回调页显示的授权码(code)或完整回调链接`,
|
|
1214
1360
|
"code 或完整回调链接",
|
|
1215
1361
|
);
|
|
1216
1362
|
if (raw === undefined) return { kind: "cancelled" };
|