@aliyunrds/ctxdb-dsh 0.0.0-stage → 0.0.1-beta.3

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.
@@ -0,0 +1,1988 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __ctxdbCreateRequire } from "node:module"; const require = __ctxdbCreateRequire(import.meta.url);
3
+
4
+ // ../../plugins/dsh-plugins/src/configure.ts
5
+ import { spawnSync } from "node:child_process";
6
+ import { existsSync as existsSync3, mkdirSync as mkdirSync3, mkdtempSync, readFileSync as readFileSync3, realpathSync, rmSync, writeFileSync as writeFileSync3 } from "node:fs";
7
+ import { homedir as homedir2, tmpdir } from "node:os";
8
+ import { basename, dirname as dirname6, join as join5, resolve as resolve2 } from "node:path";
9
+ import { createInterface } from "node:readline/promises";
10
+ import { Writable } from "node:stream";
11
+ import { fileURLToPath } from "node:url";
12
+ import { parseArgs } from "node:util";
13
+
14
+ // src/lib/open-browser.ts
15
+ import { spawn } from "node:child_process";
16
+ import { platform } from "node:os";
17
+ function openBrowser(url) {
18
+ try {
19
+ const parsed = new URL(url);
20
+ if (parsed.protocol !== "https:" || parsed.username || parsed.password) return Promise.resolve(false);
21
+ } catch {
22
+ return Promise.resolve(false);
23
+ }
24
+ const os = platform();
25
+ const command = os === "darwin" ? { file: "open", args: [url] } : os === "win32" ? { file: "rundll32.exe", args: ["url.dll,FileProtocolHandler", url] } : { file: "xdg-open", args: [url] };
26
+ return new Promise((resolve3) => {
27
+ try {
28
+ const child = spawn(command.file, command.args, { detached: true, stdio: "ignore", windowsHide: true, shell: false });
29
+ const timer = setTimeout(() => resolve3(true), 2e3);
30
+ const finish = (opened) => {
31
+ clearTimeout(timer);
32
+ resolve3(opened);
33
+ };
34
+ child.once("error", () => finish(false));
35
+ child.once("exit", (code) => finish(code === 0));
36
+ child.unref();
37
+ } catch {
38
+ resolve3(false);
39
+ }
40
+ });
41
+ }
42
+
43
+ // ../shared/src/sites.ts
44
+ var PUBLIC_SITES = {
45
+ cn: {
46
+ baseUrl: "https://api.cn-hangzhou.agentcontext.aliyuncs.com",
47
+ aliases: ["https://context-database.aliyuncs.com"],
48
+ authorizationUrl: "https://rdsnext.console.aliyun.com/contextDbCliAuthorization/cn-hangzhou"
49
+ },
50
+ intl: {
51
+ baseUrl: "https://context-database.ap-southeast-1.aliyuncs.com",
52
+ aliases: [],
53
+ authorizationUrl: "https://rds.console.alibabacloud.com/contextDbCliAuthorization/ap-southeast-1"
54
+ }
55
+ };
56
+ function normalizeBaseUrl(value) {
57
+ try {
58
+ const parsed = new URL(value.trim());
59
+ if (!parsed.protocol || !parsed.hostname) return null;
60
+ parsed.pathname = parsed.pathname.replace(/\/+$/, "");
61
+ const normalized = parsed.toString();
62
+ return normalized.endsWith("/") ? normalized.slice(0, -1) : normalized;
63
+ } catch {
64
+ return null;
65
+ }
66
+ }
67
+ function publicSiteForUrl(value) {
68
+ const normalized = normalizeBaseUrl(value);
69
+ return Object.keys(PUBLIC_SITES).find((site) => {
70
+ const preset = PUBLIC_SITES[site];
71
+ return [preset.baseUrl, ...preset.aliases].some((url) => url === normalized);
72
+ });
73
+ }
74
+
75
+ // ../shared/src/debug-policy.ts
76
+ var OFFICIAL_PRODUCTION_BASE_URLS = Object.values(PUBLIC_SITES).flatMap((site) => [site.baseUrl, ...site.aliases]);
77
+
78
+ // ../shared/src/recall-trace.ts
79
+ var RECALL_TRACE_MAX_BYTES = 10 * 1024 * 1024;
80
+ var RECALL_TRACE_OUTCOMES = [
81
+ "success",
82
+ "empty",
83
+ "timeout",
84
+ "malformed_response",
85
+ "http_error"
86
+ ];
87
+ var TRACE_OUTCOMES = new Set(RECALL_TRACE_OUTCOMES);
88
+
89
+ // ../shared/src/auth-config.ts
90
+ import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
91
+ import { createHash, randomBytes } from "node:crypto";
92
+ import { dirname } from "node:path";
93
+ var AuthConfigError = class extends Error {
94
+ constructor(message) {
95
+ super(message);
96
+ this.name = "AuthConfigError";
97
+ }
98
+ };
99
+ function readAuthConfig(path) {
100
+ if (!existsSync(path)) return { version: 2, agents: {} };
101
+ let raw;
102
+ try {
103
+ raw = JSON.parse(readFileSync(path, "utf8"));
104
+ } catch {
105
+ throw new AuthConfigError("Invalid ctxdb.json; repair the JSON before changing authentication.");
106
+ }
107
+ if (raw?.version !== 2 || !object(raw.agents) || raw.logins !== void 0 && !object(raw.logins)) {
108
+ throw new AuthConfigError("Unsupported ctxdb configuration; authentication was not changed.");
109
+ }
110
+ return raw;
111
+ }
112
+ function object(value) {
113
+ return !!value && typeof value === "object" && !Array.isArray(value);
114
+ }
115
+ function ownAuthProfile(raw, agent2) {
116
+ const value = Object.hasOwn(raw.agents, agent2) ? raw.agents[agent2] : void 0;
117
+ if (value !== void 0 && !object(value)) throw new AuthConfigError("Invalid agent configuration; repair its section in ctxdb.json.");
118
+ return value ?? {};
119
+ }
120
+ function requireLoginId(id) {
121
+ if (typeof id !== "string" || id === "default" || !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(id) || ["__proto__", "constructor", "prototype"].includes(id)) throw new AuthConfigError("Invalid login ID; use an ID from ctxdb auth status --all.");
122
+ }
123
+ function newLoginId(agent2, logins) {
124
+ requireLoginId(`${agent2}-00000000`);
125
+ for (let attempt = 0; attempt < 16; attempt++) {
126
+ const id = `${agent2}-${randomBytes(4).toString("hex")}`;
127
+ if (!Object.hasOwn(logins ?? {}, id)) return id;
128
+ }
129
+ throw new AuthConfigError("Cannot allocate a unique login ID; retry login.");
130
+ }
131
+ function loginUsers(raw, id) {
132
+ return Object.keys(raw.agents).filter((agent2) => ownAuthProfile(raw, agent2).access_credential === id).sort();
133
+ }
134
+ function validateLoginChoice(section) {
135
+ if (Object.hasOwn(section, "credential_ref")) {
136
+ if (typeof section.credential_ref !== "string" || !/^[a-f0-9]{32}$/.test(section.credential_ref)) throw new AuthConfigError("Invalid credential_ref; explicitly select --api-key or --login again.");
137
+ if (Object.hasOwn(section, "access_credential") || section.api_key || section.oauth_credential_ref) throw new AuthConfigError("Conflicting credential_ref and access_credential/api_key/oauth_credential_ref. Keep one authentication choice.");
138
+ }
139
+ if (!Object.hasOwn(section, "access_credential")) return;
140
+ if (section.access_credential === null) return;
141
+ requireLoginId(section.access_credential);
142
+ if (section.api_key || section.oauth_credential_ref) {
143
+ throw new AuthConfigError("Conflicting access_credential and api_key/oauth_credential_ref in this Agent. Keep one authentication choice, or use setup --api-key/--login to replace it.");
144
+ }
145
+ }
146
+ function authSnapshot(raw, agent2) {
147
+ const s = ownAuthProfile(raw, agent2), d = ownAuthProfile(raw, "default");
148
+ const fields = (s2) => ["credential_ref", "access_credential", "oauth_credential_ref", "api_key", "base_url"].map((k) => [k, Object.hasOwn(s2, k), s2[k]]);
149
+ return createHash("sha256").update(JSON.stringify([
150
+ fields(s),
151
+ s.access_credential ? raw.logins?.[s.access_credential] : void 0,
152
+ agent2 !== "default" && !Object.hasOwn(s, "credential_ref") && !Object.hasOwn(s, "access_credential") && !s.oauth_credential_ref && !Object.hasOwn(s, "api_key") ? fields(d) : void 0
153
+ ])).digest("hex");
154
+ }
155
+ function assertAuthSnapshot(raw, agent2, expected) {
156
+ if (authSnapshot(raw, agent2) !== expected) throw new AuthConfigError("Authentication changed while this operation was running. The newer choice was preserved; retry the command.");
157
+ }
158
+ function withAuthConfigLock(path, task) {
159
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
160
+ const lock = path + ".oauth-config.lock", deadline = Date.now() + 1e4;
161
+ let fd;
162
+ while (true) {
163
+ try {
164
+ fd = openSync(lock, "wx", 384);
165
+ break;
166
+ } catch (error) {
167
+ if (error.code !== "EEXIST") throw new AuthConfigError("Cannot lock ctxdb configuration.");
168
+ if (Date.now() >= deadline) throw new AuthConfigError("Configuration is locked. Check the previous CLI process before removing a stale .oauth-config.lock file.");
169
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 25);
170
+ }
171
+ }
172
+ try {
173
+ return task();
174
+ } finally {
175
+ closeSync(fd);
176
+ unlinkSync(lock);
177
+ }
178
+ }
179
+ function updateAuthConfig(path, task) {
180
+ return withAuthConfigLock(path, () => {
181
+ const raw = readAuthConfig(path), result = task(raw);
182
+ writeAuthConfig(path, raw);
183
+ return result;
184
+ });
185
+ }
186
+ function writeAuthConfig(path, raw) {
187
+ const temporary = path + "." + randomBytes(12).toString("hex") + ".tmp";
188
+ let fd;
189
+ try {
190
+ fd = openSync(temporary, "wx", 384);
191
+ writeFileSync(fd, JSON.stringify(raw, null, 2) + "\n");
192
+ fsyncSync(fd);
193
+ closeSync(fd);
194
+ fd = void 0;
195
+ renameSync(temporary, path);
196
+ if (process.platform !== "win32") {
197
+ try {
198
+ const dir = openSync(dirname(path), "r");
199
+ try {
200
+ fsyncSync(dir);
201
+ } finally {
202
+ closeSync(dir);
203
+ }
204
+ } catch {
205
+ }
206
+ }
207
+ } finally {
208
+ if (fd !== void 0) closeSync(fd);
209
+ if (existsSync(temporary)) unlinkSync(temporary);
210
+ }
211
+ }
212
+
213
+ // ../shared/src/auth-trace.ts
214
+ var AUTH_TRACE_MAX_BYTES = 2 * 1024 * 1024;
215
+ function authTrace(trace, event, fields) {
216
+ try {
217
+ trace?.emit(event, fields);
218
+ } catch {
219
+ }
220
+ }
221
+
222
+ // ../shared/src/device-flow.ts
223
+ import { setTimeout as delay } from "node:timers/promises";
224
+
225
+ // ../shared/src/oauth-refresh.ts
226
+ var OAUTH_REFRESH_TIMEOUT_MS = 1e4;
227
+ var OAUTH_REFRESH_ATTEMPT_MS = 4e3;
228
+ var REFRESH_RETRY_DELAY_MS = 200;
229
+ var REFRESH_RETRY_COOLDOWN_MS = 1e3;
230
+ var OAuthRefreshError = class extends Error {
231
+ outcome;
232
+ reason;
233
+ constructor(outcome, reason) {
234
+ super(`OAuth refresh ${outcome}: ${reason}`);
235
+ this.name = "OAuthRefreshError";
236
+ this.outcome = outcome;
237
+ this.reason = reason;
238
+ }
239
+ };
240
+ function readRefreshFailure(value) {
241
+ if (!value || typeof value !== "object") return null;
242
+ const v = value;
243
+ if (!["server_rejected", "connection_failed", "request_timeout", "transport_unknown", "response_invalid", "server_error"].includes(v.reason) || !Number.isSafeInteger(v.at)) return null;
244
+ return { reason: v.reason, at: v.at };
245
+ }
246
+
247
+ // ../shared/src/device-flow.ts
248
+ var DeviceFlowError = class extends Error {
249
+ code;
250
+ constructor(code) {
251
+ super(code === "service_unavailable" ? "ContextDB authentication service is unavailable. No automatic retry was performed; start a new login later if authorization could not be completed." : `ContextDB device authorization: ${code}. Start a new login if authorization could not be completed.`);
252
+ this.name = "DeviceFlowError";
253
+ this.code = code;
254
+ }
255
+ };
256
+ var invalid = () => new DeviceFlowError("invalid_response");
257
+ var scopes = ["read_only", "read_write", "default"];
258
+ var clientId = "ctxdb-cli";
259
+ var grantType = "urn:ietf:params:oauth:grant-type:device_code";
260
+ function normalizeCoreOrigin(value) {
261
+ let url;
262
+ try {
263
+ url = new URL(value);
264
+ } catch {
265
+ throw new Error("Invalid Core server origin");
266
+ }
267
+ const local = ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname);
268
+ if (url.username || url.password || url.search || url.hash || url.pathname !== "/" || !(url.protocol === "https:" || local && url.protocol === "http:")) throw new Error("Invalid Core server origin");
269
+ return url.origin;
270
+ }
271
+ var CoreDeviceClient = class {
272
+ baseUrl;
273
+ trace;
274
+ fetchImpl;
275
+ now;
276
+ requestTimeoutMs;
277
+ sleep;
278
+ constructor(baseUrl, options = {}) {
279
+ this.trace = options.trace;
280
+ this.baseUrl = normalizeCoreOrigin(baseUrl);
281
+ this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
282
+ this.now = options.now ?? Date.now;
283
+ this.requestTimeoutMs = options.requestTimeoutMs ?? 3e4;
284
+ this.sleep = options.sleep ?? ((ms, signal) => delay(ms, void 0, { signal }));
285
+ }
286
+ async login(options) {
287
+ const started = this.now();
288
+ const initial = await this.post("/v1/auth/device/authorize", {
289
+ client_id: clientId,
290
+ ...options.initialAgent === void 0 ? {} : { initial_agent: options.initialAgent }
291
+ }, options.signal);
292
+ if (!initial.ok) throw new DeviceFlowError("request_rejected");
293
+ const data = initial.data;
294
+ const requestId = text(data.request_id, 32), userCode = text(data.user_code, 9), code = text(data.device_code, 43);
295
+ if (!/^[0-9a-f]{32}$/.test(requestId) || !/^[0-9A-HJKMNP-TV-Z]{4}-[0-9A-HJKMNP-TV-Z]{4}$/.test(userCode) || !/^[A-Za-z0-9_-]{43}$/.test(code)) throw invalid();
296
+ const expiresIn = integer(data.expires_in, 1, 3600);
297
+ let interval = integer(data.interval, 1, 3600);
298
+ const deadline = started + expiresIn * 1e3;
299
+ options.onPrompt({ requestId, userCode, expiresIn, interval });
300
+ while (true) {
301
+ if (options.signal?.aborted) throw new DeviceFlowError("cancelled");
302
+ if (this.now() >= deadline) throw new DeviceFlowError("expired_token");
303
+ try {
304
+ await this.sleep(Math.min(interval * 1e3, deadline - this.now()), options.signal);
305
+ } catch {
306
+ throw new DeviceFlowError("cancelled");
307
+ }
308
+ if (this.now() >= deadline) throw new DeviceFlowError("expired_token");
309
+ const issuedAt = this.now();
310
+ const result = await this.post("/v1/auth/device/token", { grant_type: grantType, client_id: clientId, device_code: code }, options.signal);
311
+ if (result.ok) {
312
+ try {
313
+ return loginResult(result.data, this.baseUrl, issuedAt, this.now());
314
+ } catch (error2) {
315
+ authTrace(this.trace, "payload.failure", { endpoint: "poll", phase: "payload", error: error2 });
316
+ throw error2;
317
+ }
318
+ }
319
+ const error = result.data.error;
320
+ if (error === "authorization_pending") continue;
321
+ if (error === "slow_down") {
322
+ interval = Math.max(interval + 5, integer(result.data.interval, 1, 3605));
323
+ continue;
324
+ }
325
+ if (error === "access_denied" || error === "expired_token" || error === "invalid_grant") throw new DeviceFlowError(error);
326
+ throw new DeviceFlowError("request_rejected");
327
+ }
328
+ }
329
+ async refresh(refreshToken, baseUrl, options) {
330
+ this.requireSameOrigin(baseUrl);
331
+ const result = await this.post("/v1/auth/token/refresh", { refresh_token: secret(refreshToken) }, void 0, options?.timeoutMs);
332
+ if (!result.ok) throw new OAuthRefreshError("retryable", "server_error");
333
+ try {
334
+ return credentialResult(result.data);
335
+ } catch (error) {
336
+ authTrace(this.trace, "payload.failure", { endpoint: "refresh", phase: "payload", error });
337
+ throw new OAuthRefreshError("retryable", "response_invalid");
338
+ }
339
+ }
340
+ async revoke(refreshToken, baseUrl) {
341
+ this.requireSameOrigin(baseUrl);
342
+ const result = await this.post("/v1/auth/token/revoke", { refresh_token: secret(refreshToken) });
343
+ if (!result.ok) throw new DeviceFlowError("request_rejected");
344
+ }
345
+ requireSameOrigin(baseUrl) {
346
+ if (normalizeCoreOrigin(baseUrl) !== this.baseUrl) throw new Error("OAuth credential Core origin cannot change");
347
+ }
348
+ async post(path, body, signal, timeoutMs = this.requestTimeoutMs) {
349
+ const endpoint = path === "/v1/auth/device/authorize" ? "authorize" : path === "/v1/auth/device/token" ? "poll" : path === "/v1/auth/token/refresh" ? "refresh" : "revoke";
350
+ authTrace(this.trace, "http.start", { endpoint, timeout_ms: timeoutMs });
351
+ if (signal?.aborted) {
352
+ authTrace(this.trace, "http.failure", { endpoint, phase: "fetch", aborted: true, error: new DeviceFlowError("cancelled") });
353
+ throw new DeviceFlowError("cancelled");
354
+ }
355
+ let phase = "fetch", requestId, status, timeoutFired = false;
356
+ const controller = new AbortController();
357
+ const abort = () => controller.abort();
358
+ signal?.addEventListener("abort", abort, { once: true });
359
+ const timer = setTimeout(() => {
360
+ timeoutFired = true;
361
+ abort();
362
+ }, timeoutMs);
363
+ timer.unref?.();
364
+ try {
365
+ const response = await this.fetchImpl(this.baseUrl + path, {
366
+ method: "POST",
367
+ body: JSON.stringify(body),
368
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
369
+ redirect: "error",
370
+ credentials: "omit",
371
+ cache: "no-store",
372
+ signal: controller.signal
373
+ });
374
+ status = response.status;
375
+ requestId = response.headers.get("x-request-id") ?? response.headers.get("requestid") ?? void 0;
376
+ authTrace(this.trace, "http.headers", { endpoint, http_status: status, request_id: requestId });
377
+ phase = "body";
378
+ const bodyText = await boundedText(response);
379
+ phase = "json";
380
+ const parsed = JSON.parse(bodyText);
381
+ phase = "envelope";
382
+ const box = object2(parsed);
383
+ requestId = typeof box.requestId === "string" ? box.requestId : requestId;
384
+ if (!Number.isInteger(box.errorCode)) throw invalid();
385
+ const ok = response.ok && box.errorCode === 0;
386
+ const data = (!ok || path === "/v1/auth/token/revoke") && box.data == null ? {} : object2(box.data);
387
+ authTrace(this.trace, "http.response", { endpoint, http_status: status, request_id: requestId, server_code: box.errorCode, server_error: typeof data.error === "string" ? data.error : void 0 });
388
+ if (endpoint === "refresh" && response.status === 401 && box.errorCode === 4013 && box.data == null && typeof box.errorMessage === "string" && /^(?:AUTH_INVALID_TOKEN: )?token rejected: (invalid_refresh|invalid_policy|expired|revoked|replay|principal_unavailable)$/.test(box.errorMessage)) {
389
+ throw new OAuthRefreshError("invalid", "server_rejected");
390
+ }
391
+ if (!ok && response.status >= 500) throw new DeviceFlowError("service_unavailable");
392
+ return { ok, data };
393
+ } catch (error) {
394
+ authTrace(this.trace, "http.failure", {
395
+ endpoint,
396
+ phase,
397
+ http_status: status,
398
+ request_id: requestId,
399
+ aborted: controller.signal.aborted,
400
+ timeout_fired: timeoutFired,
401
+ error
402
+ });
403
+ if (endpoint === "refresh") {
404
+ if (error instanceof OAuthRefreshError) throw error;
405
+ if (timeoutFired) throw new OAuthRefreshError("retryable", "request_timeout");
406
+ const cause = error instanceof TypeError ? error.cause : void 0;
407
+ const reason = status === void 0 ? ["ENOTFOUND", "EAI_AGAIN", "ECONNREFUSED", "UND_ERR_CONNECT_TIMEOUT"].includes(cause?.code ?? "") ? "connection_failed" : "transport_unknown" : error instanceof DeviceFlowError && error.code === "service_unavailable" ? "server_error" : "response_invalid";
408
+ throw new OAuthRefreshError("retryable", reason);
409
+ }
410
+ if (signal?.aborted) throw new DeviceFlowError("cancelled");
411
+ if (phase === "json") throw invalid();
412
+ if (error instanceof DeviceFlowError) throw error;
413
+ throw new DeviceFlowError("network_error");
414
+ } finally {
415
+ clearTimeout(timer);
416
+ signal?.removeEventListener("abort", abort);
417
+ }
418
+ }
419
+ };
420
+ function text(value, maximum) {
421
+ if (typeof value !== "string" || !value || value.length > maximum || /[\x00-\x1f\x7f]/.test(value)) throw invalid();
422
+ return value;
423
+ }
424
+ function integer(value, min, max) {
425
+ if (!Number.isSafeInteger(value) || value < min || value > max) throw invalid();
426
+ return value;
427
+ }
428
+ function secret(value) {
429
+ const token = text(value, 8192);
430
+ if (/\s/.test(token)) throw invalid();
431
+ return token;
432
+ }
433
+ function object2(value) {
434
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw invalid();
435
+ return value;
436
+ }
437
+ function credentialResult(data) {
438
+ if (data.token_type !== "Bearer" || !scopes.includes(data.scope)) throw invalid();
439
+ return {
440
+ access_token: secret(data.access_token),
441
+ refresh_token: secret(data.refresh_token),
442
+ token_type: "Bearer",
443
+ expires_in: integer(data.expires_in, 1, 3600),
444
+ session_id: text(data.session_id, 64),
445
+ scope: data.scope
446
+ };
447
+ }
448
+ function loginResult(data, baseUrl, issuedAt, now) {
449
+ const tokens = credentialResult(data), scope = tokens.scope;
450
+ if (data.client_id !== clientId || scope !== "default") throw invalid();
451
+ const expiresAt = issuedAt + tokens.expires_in * 1e3;
452
+ if (expiresAt <= now) throw invalid();
453
+ return {
454
+ baseUrl,
455
+ workspaceId: text(data.workspace_id, 64),
456
+ memberId: text(data.member_id, 64),
457
+ scope,
458
+ clientId,
459
+ sessionId: tokens.session_id,
460
+ accountDisplay: text(data.account_display, 256),
461
+ issuedAt,
462
+ expiresAt,
463
+ accessToken: tokens.access_token,
464
+ refreshToken: tokens.refresh_token
465
+ };
466
+ }
467
+ async function boundedText(response) {
468
+ if (!response.body || Number(response.headers.get("content-length")) > 65536) throw invalid();
469
+ const reader = response.body.getReader();
470
+ const chunks = [];
471
+ let size = 0;
472
+ try {
473
+ while (true) {
474
+ const { done, value } = await reader.read();
475
+ if (done) break;
476
+ size += value.byteLength;
477
+ if (size > 65536) {
478
+ await reader.cancel();
479
+ throw invalid();
480
+ }
481
+ chunks.push(value);
482
+ }
483
+ return Buffer.concat(chunks).toString("utf8");
484
+ } finally {
485
+ reader.releaseLock();
486
+ }
487
+ }
488
+
489
+ // ../shared/src/oauth-credentials.ts
490
+ import { randomBytes as randomBytes4 } from "node:crypto";
491
+
492
+ // ../shared/src/credentials/local-credential-provider.ts
493
+ import { createHash as createHash3, randomBytes as randomBytes3 } from "node:crypto";
494
+ import { homedir } from "node:os";
495
+ import { join } from "node:path";
496
+
497
+ // ../shared/src/credentials/storage.ts
498
+ import { constants, closeSync as closeSync2, existsSync as existsSync2, fstatSync, fsyncSync as fsyncSync2, lstatSync, mkdirSync as mkdirSync2, openSync as openSync2, readFileSync as readFileSync2, readSync, renameSync as renameSync2, unlinkSync as unlinkSync2, writeFileSync as writeFileSync2 } from "node:fs";
499
+ import { randomBytes as randomBytes2, createHash as createHash2 } from "node:crypto";
500
+ import { dirname as dirname2 } from "node:path";
501
+ import { setTimeout as delay2 } from "node:timers/promises";
502
+ function assertStoragePath(path, directory = false) {
503
+ const s = lstatSync(path);
504
+ if (s.isSymbolicLink() || (directory ? !s.isDirectory() : !s.isFile())) throw new Error("credentials: invalid storage path");
505
+ }
506
+ function prepareStorage(path) {
507
+ const dir = dirname2(path);
508
+ if (!existsSync2(dir)) {
509
+ mkdirSync2(dir, { recursive: true, mode: 448 });
510
+ }
511
+ assertStoragePath(dir, true);
512
+ }
513
+ function readCredentialFile(path) {
514
+ if (!existsSync2(path)) return void 0;
515
+ assertStoragePath(dirname2(path), true);
516
+ assertStoragePath(path);
517
+ const fd = openSync2(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
518
+ try {
519
+ const stat = fstatSync(fd);
520
+ if (!stat.isFile() || stat.size > 16 * 1024 * 1024) throw new Error("credentials: invalid storage");
521
+ return readFileSync2(fd, "utf8");
522
+ } finally {
523
+ closeSync2(fd);
524
+ }
525
+ }
526
+ function atomicCredentialWrite(path, value) {
527
+ prepareStorage(path);
528
+ if (existsSync2(path)) assertStoragePath(path);
529
+ const temp = path + "." + randomBytes2(12).toString("hex") + ".tmp";
530
+ let fd;
531
+ try {
532
+ fd = openSync2(temp, "wx", 384);
533
+ writeFileSync2(fd, JSON.stringify(value, null, 2) + "\n");
534
+ fsyncSync2(fd);
535
+ closeSync2(fd);
536
+ fd = void 0;
537
+ renameSync2(temp, path);
538
+ if (process.platform !== "win32") {
539
+ try {
540
+ const dir = openSync2(dirname2(path), "r");
541
+ try {
542
+ fsyncSync2(dir);
543
+ } finally {
544
+ closeSync2(dir);
545
+ }
546
+ } catch {
547
+ }
548
+ }
549
+ } finally {
550
+ if (fd !== void 0) closeSync2(fd);
551
+ if (existsSync2(temp)) unlinkSync2(temp);
552
+ }
553
+ }
554
+ function withCredentialWriteLock(path, operation) {
555
+ prepareStorage(path);
556
+ const lock = path + ".lock", deadline = Date.now() + 1e4;
557
+ let fd;
558
+ while (true) {
559
+ try {
560
+ fd = openSync2(lock, "wx", 384);
561
+ break;
562
+ } catch (error) {
563
+ if (error.code !== "EEXIST") throw error;
564
+ if (Date.now() >= deadline) throw new Error("credentials: writer lock is busy; check the previous CLI process");
565
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
566
+ }
567
+ }
568
+ try {
569
+ return operation();
570
+ } finally {
571
+ closeSync2(fd);
572
+ unlinkSync2(lock);
573
+ }
574
+ }
575
+ function operationLockPath(path, key) {
576
+ return path + "." + createHash2("sha256").update(key).digest("hex") + ".lock";
577
+ }
578
+ var CredentialLockOwnerExitedError = class extends Error {
579
+ code = "lock_owner_exited";
580
+ constructor() {
581
+ super("credentials: lock_owner_exited");
582
+ this.name = "CredentialLockOwnerExitedError";
583
+ }
584
+ };
585
+ function sameLockFile(a, b) {
586
+ return a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs && a.birthtimeMs === b.birthtimeMs;
587
+ }
588
+ function readLockOwner(lock) {
589
+ const before = lstatSync(lock);
590
+ if (!before.isFile() || before.size < 1 || before.size > 10) return void 0;
591
+ const fd = openSync2(lock, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
592
+ try {
593
+ const stat = fstatSync(fd);
594
+ if (!stat.isFile() || !sameLockFile(before, stat)) return void 0;
595
+ const bytes = Buffer.alloc(11), length = readSync(fd, bytes, 0, bytes.length, 0);
596
+ const value = bytes.subarray(0, length).toString("utf8");
597
+ if (length !== stat.size || !/^[1-9][0-9]{0,9}$/.test(value)) return void 0;
598
+ const pid = Number(value);
599
+ if (pid > 2147483647 || !sameLockFile(stat, fstatSync(fd))) return void 0;
600
+ return { pid, stat };
601
+ } finally {
602
+ closeSync2(fd);
603
+ }
604
+ }
605
+ function inspectOperationLock(lock) {
606
+ try {
607
+ const before = readLockOwner(lock);
608
+ if (!before) return "busy";
609
+ try {
610
+ process.kill(before.pid, 0);
611
+ return "busy";
612
+ } catch (error) {
613
+ if (error.code !== "ESRCH") return "busy";
614
+ }
615
+ const after = readLockOwner(lock);
616
+ return after && before.pid === after.pid && sameLockFile(before.stat, after.stat) ? "owner_exited" : "retry";
617
+ } catch (error) {
618
+ return error.code === "ENOENT" ? "retry" : "busy";
619
+ }
620
+ }
621
+ async function withCredentialOperation(path, key, operation, options = {}) {
622
+ prepareStorage(path);
623
+ const lock = operationLockPath(path, key), deadline = Date.now() + (options.lockWaitMs ?? 3e4);
624
+ while (true) {
625
+ options.signal?.throwIfAborted();
626
+ let fd;
627
+ try {
628
+ fd = openSync2(lock, "wx", 384);
629
+ } catch (error) {
630
+ if (error.code !== "EEXIST") throw error;
631
+ const state = inspectOperationLock(lock);
632
+ if (state === "owner_exited") throw new CredentialLockOwnerExitedError();
633
+ if (Date.now() >= deadline) throw new Error("credentials: credential_busy");
634
+ if (state === "retry") continue;
635
+ await delay2(25, void 0, { signal: options.signal });
636
+ continue;
637
+ }
638
+ try {
639
+ writeFileSync2(fd, String(process.pid));
640
+ } finally {
641
+ closeSync2(fd);
642
+ }
643
+ try {
644
+ return await operation();
645
+ } finally {
646
+ unlinkSync2(lock);
647
+ }
648
+ }
649
+ }
650
+
651
+ // ../shared/src/credentials/types.ts
652
+ var ACTIVE_CONTEXTDB_CREDENTIAL = "contextdb/active";
653
+
654
+ // ../shared/src/credentials/local-credential-provider.ts
655
+ function defaultCredentialsPath() {
656
+ return join(homedir(), ".ctxdb", "credentials.json");
657
+ }
658
+ var object3 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
659
+ var fail = (message) => {
660
+ throw new Error("credentials: " + message);
661
+ };
662
+ function origin(value) {
663
+ if (typeof value !== "string" || !value) return fail("invalid service URL");
664
+ let u;
665
+ try {
666
+ u = new URL(value);
667
+ } catch {
668
+ return fail("invalid service URL");
669
+ }
670
+ if (!["http:", "https:"].includes(u.protocol) || u.username || u.password || u.search || u.hash) return fail("invalid service URL");
671
+ return u.toString().replace(/\/$/, "");
672
+ }
673
+ function validateApi(raw, internal, v1 = false) {
674
+ if (!object3(raw.payload) || typeof raw.payload.api_key !== "string" || !raw.payload.api_key) fail("invalid api-key payload");
675
+ const metadata = v1 ? raw.payload : raw.metadata;
676
+ origin(metadata.base_url);
677
+ if (internal) {
678
+ origin(metadata.login_server);
679
+ if (!object3(raw.metadata) || !["browser-loopback", "device-code"].includes(raw.metadata.authorization_method) || typeof raw.metadata.issued_at !== "string" || !Number.isFinite(Date.parse(raw.metadata.issued_at))) fail("invalid api-key metadata");
680
+ }
681
+ }
682
+ function validate(key, raw) {
683
+ if (!object3(raw) || !["api-key", "oauth-session"].includes(raw.kind) || !object3(raw.payload) || !object3(raw.metadata) || !object3(raw.metadata.owner) || !["ready", "refreshing", "reauth_required", "logged_out"].includes(raw.metadata.state) || typeof raw.metadata.generation !== "string" || !/^[a-f0-9]{32}$/.test(raw.metadata.generation) || !Number.isSafeInteger(raw.metadata.revision) || raw.metadata.revision < 1) fail("invalid credential record");
684
+ if (key === ACTIVE_CONTEXTDB_CREDENTIAL) {
685
+ if (raw.kind !== "api-key" || raw.metadata.owner.distribution !== "internal" || raw.metadata.state !== "ready") fail("invalid contextdb/active record");
686
+ } else if (!/^[a-f0-9]{32}$/.test(key) || raw.metadata.owner.distribution !== "public" || typeof raw.metadata.owner.agent !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(raw.metadata.owner.agent) || raw.metadata.owner.loginId !== void 0 && (typeof raw.metadata.owner.loginId !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(raw.metadata.owner.loginId))) fail("invalid credential ownership");
687
+ const fields = raw.kind === "api-key" ? ["api_key"] : ["ready", "refreshing"].includes(raw.metadata.state) ? ["accessToken", "refreshToken"] : [];
688
+ if (Object.keys(raw.payload).length !== fields.length || fields.some((field) => typeof raw.payload[field] !== "string" || !raw.payload[field])) fail("invalid credential payload; only credential values are allowed");
689
+ if (raw.kind === "api-key") validateApi(raw, key === ACTIVE_CONTEXTDB_CREDENTIAL);
690
+ }
691
+ function readDocument(path) {
692
+ const bytes = readCredentialFile(path);
693
+ if (bytes === void 0) return { version: 2, records: {} };
694
+ let doc;
695
+ try {
696
+ doc = JSON.parse(bytes);
697
+ } catch {
698
+ return fail("credentials.json is not valid JSON");
699
+ }
700
+ if (!object3(doc) || ![1, 2].includes(doc.version) || !object3(doc.records)) return fail("unsupported credentials.json schema/version");
701
+ if (doc.version === 1) {
702
+ if (Object.keys(doc.records).some((k) => k !== ACTIVE_CONTEXTDB_CREDENTIAL)) fail("unsupported record key in v1 credentials");
703
+ const active = doc.records[ACTIVE_CONTEXTDB_CREDENTIAL];
704
+ if (active !== void 0) {
705
+ if (active.kind !== "api-key") fail("unsupported record kind");
706
+ validateApi(active, true, true);
707
+ }
708
+ } else for (const [key, record] of Object.entries(doc.records)) validate(key, record);
709
+ return doc;
710
+ }
711
+ function upgrade(doc) {
712
+ if (doc.version === 2) return doc;
713
+ const record = doc.records[ACTIVE_CONTEXTDB_CREDENTIAL];
714
+ return { ...doc, version: 2, records: record ? { [ACTIVE_CONTEXTDB_CREDENTIAL]: legacy(record) } : {} };
715
+ }
716
+ function legacy(record) {
717
+ const { api_key, ...details } = record.payload;
718
+ return { kind: record.kind, payload: { api_key }, metadata: {
719
+ ...details,
720
+ ...record.metadata,
721
+ base_url: record.payload.base_url,
722
+ login_server: record.payload.login_server,
723
+ owner: { distribution: "internal" },
724
+ state: "ready",
725
+ revision: 1,
726
+ generation: createHash3("sha256").update(JSON.stringify(record)).digest("hex").slice(0, 32)
727
+ } };
728
+ }
729
+ function snapshot(doc, key) {
730
+ const raw = Object.hasOwn(doc.records, key) ? doc.records[key] : void 0;
731
+ const record = raw && (doc.version === 1 ? legacy(raw) : raw);
732
+ return { key, record, fingerprint: createHash3("sha256").update(JSON.stringify(record) ?? "missing").digest("hex") };
733
+ }
734
+ function apiRecord(record) {
735
+ if (!record) return void 0;
736
+ if (record.kind !== "api-key" || record.metadata.owner.distribution !== "internal") return fail("invalid contextdb/active record");
737
+ return {
738
+ kind: "api-key",
739
+ payload: { apiKey: record.payload.api_key },
740
+ metadata: {
741
+ baseUrl: origin(record.metadata.base_url),
742
+ loginServer: origin(record.metadata.login_server),
743
+ authorizationMethod: record.metadata.authorization_method,
744
+ issuedAt: record.metadata.issued_at
745
+ }
746
+ };
747
+ }
748
+ function internalCandidate(record) {
749
+ return {
750
+ kind: "api-key",
751
+ payload: { api_key: record.payload.apiKey },
752
+ metadata: {
753
+ base_url: record.metadata.baseUrl,
754
+ login_server: record.metadata.loginServer,
755
+ authorization_method: record.metadata.authorizationMethod,
756
+ issued_at: record.metadata.issuedAt,
757
+ owner: { distribution: "internal" },
758
+ state: "ready"
759
+ }
760
+ };
761
+ }
762
+ var LocalCredentialProvider = class {
763
+ listeners = /* @__PURE__ */ new Set();
764
+ path;
765
+ constructor(path = defaultCredentialsPath()) {
766
+ this.path = path;
767
+ }
768
+ snapshot(key) {
769
+ return snapshot(readDocument(this.path), key);
770
+ }
771
+ readStoredRecord(key) {
772
+ return this.snapshot(key).record;
773
+ }
774
+ async readRecord(key) {
775
+ return apiRecord(this.readStoredRecord(key));
776
+ }
777
+ async describeRecord(key) {
778
+ const r = this.readStoredRecord(key);
779
+ return { configured: !!r && r.metadata.state === "ready", kind: r?.kind, writable: true };
780
+ }
781
+ onRecordUpdated(listener) {
782
+ this.listeners.add(listener);
783
+ return () => this.listeners.delete(listener);
784
+ }
785
+ /** Synchronous short commit; callbacks may acquire a config lock, never the reverse. */
786
+ transaction(operation) {
787
+ return withCredentialWriteLock(this.path, () => {
788
+ let doc = readDocument(this.path);
789
+ const read = (key) => snapshot(doc, key);
790
+ const check = (expected) => {
791
+ if (read(expected.key).fingerprint !== expected.fingerprint) fail("authentication changed; the newer credential was preserved, retry the command");
792
+ };
793
+ const save = () => {
794
+ doc = upgrade(doc);
795
+ atomicCredentialWrite(this.path, doc);
796
+ };
797
+ return operation({
798
+ read,
799
+ put: (key, candidate, expected) => {
800
+ if (expected) {
801
+ if (expected.key !== key) fail("invalid commit target");
802
+ check(expected);
803
+ }
804
+ const before = read(key), previous = before.record;
805
+ const next = { kind: candidate.kind, payload: candidate.payload, metadata: {
806
+ ...candidate.metadata,
807
+ generation: previous?.metadata.generation ?? randomBytes3(16).toString("hex"),
808
+ revision: (previous?.metadata.revision ?? 0) + 1
809
+ } };
810
+ validate(key, next);
811
+ doc = upgrade(doc);
812
+ doc.records[key] = next;
813
+ save();
814
+ return { before, after: read(key) };
815
+ },
816
+ remove: (expected) => {
817
+ check(expected);
818
+ if (!read(expected.key).record) return;
819
+ doc = upgrade(doc);
820
+ delete doc.records[expected.key];
821
+ save();
822
+ }
823
+ });
824
+ });
825
+ }
826
+ commit(key, record, expected = this.snapshot(key)) {
827
+ return this.transaction((tx) => tx.put(key, record, expected));
828
+ }
829
+ rollback(receipt) {
830
+ return this.transaction((tx) => {
831
+ if (tx.read(receipt.after.key).fingerprint !== receipt.after.fingerprint) return false;
832
+ if (receipt.before.record) tx.put(receipt.after.key, receipt.before.record, receipt.after);
833
+ else tx.remove(receipt.after);
834
+ return true;
835
+ });
836
+ }
837
+ async modifyRecord(key, mutate, signal) {
838
+ const before = this.snapshot(key), next = await mutate(apiRecord(before.record));
839
+ signal?.throwIfAborted();
840
+ if (next === void 0) return apiRecord(before.record);
841
+ const receipt = this.commit(key, internalCandidate(next), before);
842
+ for (const listener of this.listeners) {
843
+ try {
844
+ listener(key);
845
+ } catch {
846
+ }
847
+ }
848
+ return apiRecord(receipt.after.record);
849
+ }
850
+ async deleteRecord(key, signal) {
851
+ signal?.throwIfAborted();
852
+ const before = this.snapshot(key);
853
+ this.transaction((tx) => tx.remove(before));
854
+ for (const listener of this.listeners) {
855
+ try {
856
+ listener(key);
857
+ } catch {
858
+ }
859
+ }
860
+ }
861
+ };
862
+
863
+ // ../shared/src/oauth-credentials.ts
864
+ var OAuthCredentialError = class extends Error {
865
+ code;
866
+ constructor(code, interruptedOwner) {
867
+ const messages = {
868
+ login_required: "OAuth session needs login; run ctxdb login for this profile.",
869
+ credential_busy: "OAuth credential is busy. If its previous process crashed, run ctxdb login for a new credential.",
870
+ invalid_profile: "OAuth credential does not belong to this profile.",
871
+ unsafe_storage: "OAuth credential storage is inaccessible or invalid.",
872
+ refresh_retryable: "OAuth refresh is temporarily unavailable; credentials were preserved. The next request will retry automatically after a short cooldown.",
873
+ refresh_interrupted: "The previous OAuth refresh did not finish saving credentials. Check local credential storage and auth debug logs before recovering this login."
874
+ };
875
+ let message = messages[code];
876
+ if (code === "login_required" && interruptedOwner !== void 0) {
877
+ const id = typeof interruptedOwner === "string" ? interruptedOwner : interruptedOwner.loginId;
878
+ requireProfile(id);
879
+ const selector = typeof interruptedOwner === "string" ? "--agent" : "--login";
880
+ message = `Previous OAuth credential operation was interrupted; run ctxdb login ${selector} ${id} to reauthorize this login.`;
881
+ }
882
+ super(message);
883
+ this.name = "OAuthCredentialError";
884
+ this.code = code;
885
+ }
886
+ };
887
+ var loginRequired = () => new OAuthCredentialError("login_required");
888
+ var unsafe = () => new OAuthCredentialError("unsafe_storage");
889
+ var delay3 = (ms) => new Promise((resolve3) => setTimeout(resolve3, ms));
890
+ var OAuthSessionStore = class {
891
+ provider;
892
+ now;
893
+ lockWaitMs;
894
+ trace;
895
+ path;
896
+ constructor(path, options = {}) {
897
+ this.trace = options.trace;
898
+ this.path = path;
899
+ this.provider = new LocalCredentialProvider(path);
900
+ this.now = options.now ?? Date.now;
901
+ this.lockWaitMs = options.lockWaitMs ?? 3e4;
902
+ }
903
+ saveLogin(profile, session, loginId) {
904
+ requireProfile(profile);
905
+ validateSession(session);
906
+ if (loginId !== void 0) requireProfile(loginId);
907
+ const ref = randomBytes4(16).toString("hex");
908
+ this.write(ref, { profile, ...loginId ? { loginId } : {}, state: "ready", session });
909
+ return ref;
910
+ }
911
+ status(ref, owner) {
912
+ const record = this.read(ref, owner);
913
+ if (!record) return { state: "missing" };
914
+ const s = record.session;
915
+ return {
916
+ state: record.state === "ready" && record.refreshFailure ? "refresh_retryable" : record.state,
917
+ refreshFailure: record.refreshFailure ?? null,
918
+ profile: record.profile,
919
+ baseUrl: s.baseUrl,
920
+ workspaceId: s.workspaceId,
921
+ memberId: s.memberId,
922
+ clientId: s.clientId,
923
+ scope: s.scope,
924
+ sessionId: s.sessionId,
925
+ accountDisplay: s.accountDisplay,
926
+ accessExpiresAt: s.expiresAt
927
+ };
928
+ }
929
+ async resolve(ref, owner, transport) {
930
+ const first = this.read(ref, owner);
931
+ authTrace(this.trace, "credential.read", {
932
+ state: first?.state ?? "missing",
933
+ session_id: first?.session.sessionId,
934
+ login_id: first?.loginId,
935
+ access_expires_at: first?.session.expiresAt
936
+ });
937
+ if (!first || ["reauth_required", "logged_out"].includes(first.state)) throw loginRequired();
938
+ if (first.state === "ready" && !first.refreshFailure && !this.needsRefresh(first.session)) {
939
+ authTrace(this.trace, "credential.cache_hit", { reason: "cache" });
940
+ return authorization(first.session);
941
+ }
942
+ return this.withLock(ref, owner, async () => {
943
+ const current = this.read(ref, owner);
944
+ if (!current || ["reauth_required", "logged_out"].includes(current.state)) throw loginRequired();
945
+ if (current.state === "refreshing") throw new OAuthCredentialError("refresh_interrupted");
946
+ if (!this.needsRefresh(current.session)) {
947
+ if (current.refreshFailure) this.write(ref, { ...current, refreshFailure: null });
948
+ authTrace(this.trace, "credential.cache_hit", { reason: "refreshed_by_peer" });
949
+ return authorization(current.session);
950
+ }
951
+ const sinceFailure = current.refreshFailure ? this.now() - current.refreshFailure.at : Infinity;
952
+ if (sinceFailure >= 0 && sinceFailure < REFRESH_RETRY_COOLDOWN_MS) {
953
+ authTrace(this.trace, "refresh.cooldown", { reason: current.refreshFailure?.reason });
954
+ throw new OAuthCredentialError("refresh_retryable");
955
+ }
956
+ const deadline = this.now() + OAUTH_REFRESH_TIMEOUT_MS;
957
+ for (let attempt = 1; ; attempt++) {
958
+ const latest = await this.readForRefresh(ref, owner);
959
+ if (!latest || ["reauth_required", "logged_out"].includes(latest.state)) throw loginRequired();
960
+ if (attempt === 1) this.write(ref, { ...latest, state: "refreshing", refreshFailure: null });
961
+ const started = this.now();
962
+ let next, phase = "request";
963
+ authTrace(this.trace, "refresh.start", { attempt, session_id: latest.session.sessionId, login_id: latest.loginId });
964
+ try {
965
+ const response = await transport.refresh(
966
+ latest.session.refreshToken,
967
+ latest.session.baseUrl,
968
+ { timeoutMs: Math.max(1, Math.min(OAUTH_REFRESH_ATTEMPT_MS, deadline - started)) }
969
+ );
970
+ phase = "rotation";
971
+ next = rotated(latest.session, response, started, this.trace);
972
+ } catch (error) {
973
+ const failure = error instanceof OAuthRefreshError ? error : new OAuthRefreshError("retryable", "transport_unknown");
974
+ authTrace(this.trace, "refresh.failure", { phase, attempt, reason: failure.reason, error });
975
+ if (failure.outcome === "invalid") {
976
+ this.write(ref, { ...latest, state: "reauth_required", refreshFailure: null });
977
+ throw loginRequired();
978
+ }
979
+ if (attempt < 2 && deadline - this.now() > REFRESH_RETRY_DELAY_MS) {
980
+ authTrace(this.trace, "refresh.retry", { attempt, reason: failure.reason, wait_ms: REFRESH_RETRY_DELAY_MS });
981
+ await delay3(REFRESH_RETRY_DELAY_MS);
982
+ continue;
983
+ }
984
+ this.write(ref, { ...latest, state: "ready", refreshFailure: { reason: failure.reason, at: this.now() } });
985
+ throw new OAuthCredentialError("refresh_retryable");
986
+ }
987
+ for (let save = 1; ; save++) {
988
+ try {
989
+ this.write(ref, { ...latest, state: "ready", session: next, refreshFailure: null });
990
+ break;
991
+ } catch (error) {
992
+ authTrace(this.trace, "refresh.failure", { phase: "persist", attempt: save, error });
993
+ if (save >= 2) throw unsafe();
994
+ authTrace(this.trace, "refresh.retry", { phase: "persist", attempt: save, wait_ms: REFRESH_RETRY_DELAY_MS });
995
+ await delay3(REFRESH_RETRY_DELAY_MS);
996
+ }
997
+ }
998
+ if (next.expiresAt <= this.now()) {
999
+ authTrace(this.trace, "refresh.failure", { phase: "rotation", reason: "expired_response" });
1000
+ throw new OAuthCredentialError("refresh_retryable");
1001
+ }
1002
+ authTrace(this.trace, "refresh.success", { access_expires_at: next.expiresAt });
1003
+ return authorization(next);
1004
+ }
1005
+ });
1006
+ }
1007
+ async share(ref, profile, loginId, commit) {
1008
+ requireProfile(loginId);
1009
+ return this.withLock(ref, profile, async () => {
1010
+ const current = this.read(ref, profile);
1011
+ if (!current || current.state !== "ready") throw loginRequired();
1012
+ if (current.loginId && current.loginId !== loginId) throw new OAuthCredentialError("invalid_profile");
1013
+ const receipt = this.write(ref, { ...current, loginId });
1014
+ try {
1015
+ return commit();
1016
+ } catch (error) {
1017
+ this.provider.rollback(receipt);
1018
+ throw error;
1019
+ }
1020
+ });
1021
+ }
1022
+ /** Setup changes the DATA endpoint without replacing the identity or racing a refresh. */
1023
+ async changeBaseUrl(ref, owner, baseUrl, beforeWrite) {
1024
+ await this.withLock(ref, owner, async () => {
1025
+ this.provider.transaction((tx) => {
1026
+ beforeWrite();
1027
+ const current = this.read(ref, owner);
1028
+ if (!current || current.state !== "ready") throw loginRequired();
1029
+ const session = { ...current.session, baseUrl };
1030
+ validateSession(session);
1031
+ const before = tx.read(ref), candidate = credentialForSession({ ...current, session });
1032
+ tx.put(ref, { ...candidate, metadata: { ...before.record?.metadata, ...candidate.metadata } }, before);
1033
+ });
1034
+ });
1035
+ }
1036
+ async logout(ref, owner, transport, beforeRevoke = () => {
1037
+ }) {
1038
+ return this.withLock(ref, owner, async () => {
1039
+ const current = this.read(ref, owner);
1040
+ this.provider.transaction((tx) => {
1041
+ beforeRevoke();
1042
+ const before = tx.read(ref);
1043
+ if (current && before.record) tx.put(ref, { ...before.record, metadata: { ...before.record.metadata, state: "logged_out" }, payload: {} }, before);
1044
+ });
1045
+ let remoteRevoked = false;
1046
+ try {
1047
+ if (current?.session.refreshToken && current.state !== "logged_out") {
1048
+ await transport.revoke(current.session.refreshToken, current.session.baseUrl);
1049
+ remoteRevoked = true;
1050
+ }
1051
+ } catch {
1052
+ }
1053
+ return { remoteRevoked };
1054
+ });
1055
+ }
1056
+ /** Release config references under the write lock, then delete an unused session.
1057
+ * Waiting on the operation lock first lets an in-flight refresh supply its latest RT.
1058
+ * Returning false from release preserves a session that still has users.
1059
+ */
1060
+ async retire(ref, owner, transport, release) {
1061
+ return this.withLock(ref, owner, async () => {
1062
+ const current = this.read(ref, owner);
1063
+ const removed = this.provider.transaction((tx) => {
1064
+ if (!release()) return false;
1065
+ tx.remove(tx.read(ref));
1066
+ return true;
1067
+ });
1068
+ if (!removed) return { removed: false, remoteRevoked: false, remoteUnconfirmed: false };
1069
+ if (!current || current.state === "logged_out") return { removed: true, remoteRevoked: false, remoteUnconfirmed: false };
1070
+ try {
1071
+ if (!current.session.refreshToken) throw loginRequired();
1072
+ await transport.revoke(current.session.refreshToken, current.session.baseUrl);
1073
+ return { removed: true, remoteRevoked: true, remoteUnconfirmed: false };
1074
+ } catch {
1075
+ return { removed: true, remoteRevoked: false, remoteUnconfirmed: true };
1076
+ }
1077
+ });
1078
+ }
1079
+ needsRefresh(session) {
1080
+ return this.now() >= session.expiresAt - Math.min(3e4, (session.expiresAt - session.issuedAt) / 2);
1081
+ }
1082
+ async readForRefresh(ref, owner) {
1083
+ for (let attempt = 1; ; attempt++) {
1084
+ try {
1085
+ return this.read(ref, owner);
1086
+ } catch (error) {
1087
+ if (attempt >= 2 || !(error instanceof OAuthCredentialError) || error.code !== "unsafe_storage") throw error;
1088
+ authTrace(this.trace, "refresh.retry", { phase: "read", attempt, wait_ms: REFRESH_RETRY_DELAY_MS, error });
1089
+ await delay3(REFRESH_RETRY_DELAY_MS);
1090
+ }
1091
+ }
1092
+ }
1093
+ read(ref, owner) {
1094
+ if (!/^[a-f0-9]{32}$/.test(ref)) throw unsafe();
1095
+ requireProfile(typeof owner === "string" ? owner : owner.loginId);
1096
+ let stored;
1097
+ try {
1098
+ stored = this.provider.readStoredRecord(ref);
1099
+ } catch (error) {
1100
+ authTrace(this.trace, "credential.read.failure", { error });
1101
+ throw unsafe();
1102
+ }
1103
+ if (!stored) return void 0;
1104
+ if (stored.kind !== "oauth-session" || stored.metadata.owner.distribution !== "public") throw new OAuthCredentialError("invalid_profile");
1105
+ const who = stored.metadata.owner;
1106
+ if (typeof owner === "string" ? who.agent !== owner : who.loginId !== owner.loginId) throw new OAuthCredentialError("invalid_profile");
1107
+ return {
1108
+ profile: who.agent,
1109
+ loginId: who.loginId,
1110
+ state: stored.metadata.state,
1111
+ session: oauthSessionFromCredential(stored),
1112
+ refreshFailure: readRefreshFailure(stored.metadata.refreshFailure)
1113
+ };
1114
+ }
1115
+ write(ref, doc) {
1116
+ authTrace(this.trace, "credential.write.start", { state: doc.state });
1117
+ try {
1118
+ const before = this.provider.snapshot(ref);
1119
+ if (before.record && ["logged_out", "reauth_required"].includes(before.record.metadata.state)) throw loginRequired();
1120
+ const candidate = credentialForSession(doc);
1121
+ const receipt = this.provider.commit(ref, { ...candidate, metadata: { ...before.record?.metadata, ...candidate.metadata } }, before);
1122
+ authTrace(this.trace, "credential.write.success", { state: doc.state });
1123
+ return receipt;
1124
+ } catch (error) {
1125
+ authTrace(this.trace, "credential.write.failure", { state: doc.state, error });
1126
+ throw error;
1127
+ }
1128
+ }
1129
+ async withLock(ref, owner, task) {
1130
+ if (!/^[a-f0-9]{32}$/.test(ref)) throw unsafe();
1131
+ const started = Date.now();
1132
+ let acquired = false;
1133
+ authTrace(this.trace, "lock.wait", { timeout_ms: this.lockWaitMs });
1134
+ try {
1135
+ return await withCredentialOperation(this.path, ref, async () => {
1136
+ acquired = true;
1137
+ authTrace(this.trace, "lock.acquired", { wait_ms: Date.now() - started });
1138
+ return task();
1139
+ }, { lockWaitMs: this.lockWaitMs });
1140
+ } catch (error) {
1141
+ if (!acquired) authTrace(this.trace, "lock.failure", { wait_ms: Date.now() - started, error: error instanceof Error && error.message === "credentials: credential_busy" ? new OAuthCredentialError("credential_busy") : error });
1142
+ if (error instanceof CredentialLockOwnerExitedError) throw new OAuthCredentialError("login_required", owner);
1143
+ if (error instanceof Error && error.message === "credentials: credential_busy") throw new OAuthCredentialError("credential_busy");
1144
+ throw error;
1145
+ }
1146
+ }
1147
+ };
1148
+ function oauthSessionCandidate(profile, session, loginId) {
1149
+ requireProfile(profile);
1150
+ validateSession(session);
1151
+ if (loginId !== void 0) requireProfile(loginId);
1152
+ return credentialForSession({ profile, loginId, state: "ready", session });
1153
+ }
1154
+ function credentialForSession(doc) {
1155
+ const { accessToken, refreshToken, ...metadata } = doc.session;
1156
+ return {
1157
+ kind: "oauth-session",
1158
+ payload: ["ready", "refreshing"].includes(doc.state) ? { accessToken, refreshToken } : {},
1159
+ metadata: {
1160
+ ...metadata,
1161
+ owner: { distribution: "public", agent: doc.profile, ...doc.loginId ? { loginId: doc.loginId } : {} },
1162
+ state: doc.state,
1163
+ refreshFailure: doc.refreshFailure ?? null,
1164
+ authorization_method: "device-code"
1165
+ }
1166
+ };
1167
+ }
1168
+ function oauthSessionFromCredential(record) {
1169
+ if (record.kind !== "oauth-session") throw unsafe();
1170
+ const m = record.metadata, p = record.payload;
1171
+ const session = {
1172
+ baseUrl: m.baseUrl,
1173
+ workspaceId: m.workspaceId,
1174
+ memberId: m.memberId,
1175
+ clientId: m.clientId,
1176
+ scope: m.scope,
1177
+ sessionId: m.sessionId,
1178
+ accountDisplay: m.accountDisplay,
1179
+ issuedAt: m.issuedAt,
1180
+ expiresAt: m.expiresAt,
1181
+ accessToken: p.accessToken,
1182
+ refreshToken: p.refreshToken
1183
+ };
1184
+ validateSession(session, ["ready", "refreshing"].includes(m.state));
1185
+ return session;
1186
+ }
1187
+ function requireProfile(profile) {
1188
+ if (typeof profile !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(profile)) throw new OAuthCredentialError("invalid_profile");
1189
+ }
1190
+ function validateSession(s, requireTokens = true) {
1191
+ if (!s || typeof s !== "object" || s.clientId !== "ctxdb-cli" || !["read_only", "read_write", "default"].includes(s.scope) || !Number.isSafeInteger(s.issuedAt) || !Number.isSafeInteger(s.expiresAt) || s.expiresAt - s.issuedAt < 1e3 || s.expiresAt - s.issuedAt > 36e5) throw unsafe();
1192
+ for (const value of [s.workspaceId, s.memberId, s.sessionId, s.accountDisplay]) {
1193
+ if (typeof value !== "string" || !value || value.length > 256 || /[\r\n\x00-\x1f]/.test(value)) throw unsafe();
1194
+ }
1195
+ for (const value of requireTokens ? [s.accessToken, s.refreshToken] : []) {
1196
+ if (typeof value !== "string" || !value || value.length > 8192 || /\s/.test(value)) throw unsafe();
1197
+ }
1198
+ let url;
1199
+ try {
1200
+ url = new URL(s.baseUrl);
1201
+ } catch {
1202
+ throw unsafe();
1203
+ }
1204
+ const loopback = ["127.0.0.1", "[::1]", "localhost"].includes(url.hostname);
1205
+ if (url.username || url.password || url.search || url.hash || url.pathname !== "/" || !(url.protocol === "https:" || loopback && url.protocol === "http:")) throw unsafe();
1206
+ }
1207
+ function rotated(current, response, issuedAt, trace) {
1208
+ if (!response || response.token_type !== "Bearer" || response.session_id !== current.sessionId || response.scope !== current.scope || !Number.isSafeInteger(response.expires_in) || response.expires_in < 1 || response.expires_in > 3600 || response.refresh_token === current.refreshToken) {
1209
+ const reason = !response ? "invalid_rotation" : response.session_id !== current.sessionId ? "session_mismatch" : response.scope !== current.scope ? "scope_mismatch" : response.refresh_token === current.refreshToken ? "unchanged_refresh_token" : "invalid_rotation";
1210
+ authTrace(trace, "refresh.failure", { phase: "rotation", reason });
1211
+ throw new OAuthRefreshError("retryable", "response_invalid");
1212
+ }
1213
+ const next = {
1214
+ ...current,
1215
+ accessToken: response.access_token,
1216
+ refreshToken: response.refresh_token,
1217
+ issuedAt,
1218
+ expiresAt: issuedAt + response.expires_in * 1e3
1219
+ };
1220
+ try {
1221
+ validateSession(next);
1222
+ } catch {
1223
+ throw new OAuthRefreshError("retryable", "response_invalid");
1224
+ }
1225
+ return next;
1226
+ }
1227
+ function authorization(session) {
1228
+ return { scheme: "Bearer", value: session.accessToken, baseUrl: session.baseUrl, expiresAt: session.expiresAt };
1229
+ }
1230
+
1231
+ // ../shared/src/oauth-profile.ts
1232
+ import { dirname as dirname3, join as join2, resolve } from "node:path";
1233
+ function oauthProfile(reference, configPath, profile, baseUrl) {
1234
+ if (reference === void 0) return void 0;
1235
+ if (typeof reference !== "string" || !/^[a-f0-9]{32}$/.test(reference) || !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(profile)) throw new OAuthCredentialError("unsafe_storage");
1236
+ const path = resolve(configPath);
1237
+ return {
1238
+ reference,
1239
+ profile,
1240
+ configPath: path,
1241
+ credentialsPath: join2(dirname3(path), "credentials.json"),
1242
+ baseUrl: normalizeCoreOrigin(baseUrl)
1243
+ };
1244
+ }
1245
+ function oauthProfileFromConfig(raw, path, agent2, baseUrlOverride, trace) {
1246
+ const section = ownAuthProfile(raw, agent2);
1247
+ validateLoginChoice(section);
1248
+ if (section.access_credential === null) return void 0;
1249
+ if (Object.hasOwn(section, "access_credential")) {
1250
+ const id = section.access_credential;
1251
+ requireLoginId(id);
1252
+ const record = raw.logins && Object.hasOwn(raw.logins, id) ? raw.logins[id] : void 0;
1253
+ if (!record?.credential_ref) throw new AuthConfigError("access_credential points to a missing login. Use ctxdb auth status --all and explicitly bind a valid login or log in again.");
1254
+ return storedProfile(record.credential_ref, path, agent2, id, baseUrlOverride, trace);
1255
+ }
1256
+ return storedProfile(section.oauth_credential_ref, path, agent2, void 0, baseUrlOverride, trace);
1257
+ }
1258
+ function storedProfile(reference, path, agent2, loginId, baseUrlOverride, trace) {
1259
+ const descriptor = oauthProfile(reference, path, agent2, "https://api.cn-hangzhou.agentcontext.aliyuncs.com");
1260
+ if (!descriptor) return void 0;
1261
+ const profile = { ...descriptor, ...loginId ? { loginId } : {} };
1262
+ const status = new OAuthSessionStore(profile.credentialsPath, { trace }).status(profile.reference, oauthOwner(profile));
1263
+ if (!("baseUrl" in status) || typeof status.baseUrl !== "string") throw new OAuthCredentialError("login_required");
1264
+ profile.baseUrl = normalizeCoreOrigin(status.baseUrl);
1265
+ if (baseUrlOverride && normalizeCoreOrigin(baseUrlOverride) !== profile.baseUrl) {
1266
+ throw new AuthConfigError("Requested base URL does not match the login Core origin; no token was sent.");
1267
+ }
1268
+ return profile;
1269
+ }
1270
+ function oauthOwner(profile) {
1271
+ return profile.loginId ? { loginId: profile.loginId } : profile.profile;
1272
+ }
1273
+ function oauthProfileStatus(profile, trace) {
1274
+ const status = new OAuthSessionStore(profile.credentialsPath, { trace }).status(profile.reference, oauthOwner(profile));
1275
+ if (typeof status.baseUrl === "string" && normalizeCoreOrigin(status.baseUrl) !== profile.baseUrl) {
1276
+ throw new AuthConfigError("Requested base URL does not match the login Core origin; no token was sent.");
1277
+ }
1278
+ return status;
1279
+ }
1280
+
1281
+ // ../shared/src/login-bindings.ts
1282
+ import { randomBytes as randomBytes5 } from "node:crypto";
1283
+ import { dirname as dirname4, join as join3 } from "node:path";
1284
+
1285
+ // ../shared/src/data-endpoint.ts
1286
+ var DEFAULT_DATA_BASE_URL = PUBLIC_SITES.cn.baseUrl;
1287
+
1288
+ // ../shared/src/login-bindings.ts
1289
+ function selectedLogin(path, agent2) {
1290
+ return oauthProfileFromConfig(readAuthConfig(path), path, agent2);
1291
+ }
1292
+ function namedLogin(raw, path, name) {
1293
+ if (name === "default") {
1294
+ const selected = oauthProfileFromConfig(raw, path, "default");
1295
+ if (!selected) throw new AuthConfigError("default has no login. Run ctxdb login first, or specify an existing login ID.");
1296
+ return selected;
1297
+ }
1298
+ requireLoginId(name);
1299
+ const ref = raw.logins && Object.hasOwn(raw.logins, name) ? raw.logins[name]?.credential_ref : void 0;
1300
+ if (!ref) throw new AuthConfigError("Login ID was not found. Run ctxdb auth status --all.");
1301
+ const temporary = { ...oauthProfile(ref, path, name, DEFAULT_DATA_BASE_URL), loginId: name };
1302
+ const status = new OAuthSessionStore(temporary.credentialsPath).status(ref, { loginId: name });
1303
+ if (!("baseUrl" in status) || typeof status.baseUrl !== "string") throw new AuthConfigError("Login credential is missing; log in again.");
1304
+ return { ...temporary, baseUrl: normalizeCoreOrigin(status.baseUrl) };
1305
+ }
1306
+ function setChoice(raw, agent2, choice) {
1307
+ const s = { ...ownAuthProfile(raw, agent2) };
1308
+ delete s.api_key;
1309
+ delete s.oauth_credential_ref;
1310
+ delete s.access_credential;
1311
+ delete s.credential_ref;
1312
+ if (choice.credentialRef !== void 0) s.credential_ref = choice.credentialRef;
1313
+ else s.access_credential = choice.loginId ?? null;
1314
+ delete s.base_url;
1315
+ raw.agents[agent2] = s;
1316
+ }
1317
+ function groupSnapshot(raw, profile) {
1318
+ if (!profile?.loginId) return "";
1319
+ return JSON.stringify([raw.logins?.[profile.loginId], loginUsers(raw, profile.loginId).map((a) => [a, authSnapshot(raw, a)])]);
1320
+ }
1321
+ function beginLogin(path, agent2, name) {
1322
+ const raw = readAuthConfig(path);
1323
+ const previous = name !== void 0 ? namedLogin(raw, path, name) : selectedLogin(path, agent2);
1324
+ const update = name !== void 0 || agent2 === "default";
1325
+ const loginId = update && previous?.loginId ? previous.loginId : newLoginId(name !== void 0 && previous ? previous.profile : agent2, raw.logins);
1326
+ return {
1327
+ path,
1328
+ agent: agent2,
1329
+ name,
1330
+ previous,
1331
+ loginId,
1332
+ update,
1333
+ snapshot: authSnapshot(raw, agent2),
1334
+ previousState: previous ? oauthProfileStatus(previous).state : void 0,
1335
+ group: update ? groupSnapshot(raw, previous) : "",
1336
+ users: update && previous?.loginId ? loginUsers(raw, previous.loginId) : [agent2]
1337
+ };
1338
+ }
1339
+ function commitLogin(pending, reference, baseUrl, updateConfig) {
1340
+ const { path, agent: agent2, previous, loginId, update } = pending;
1341
+ const next = { ...oauthProfile(reference, path, agent2, baseUrl), loginId };
1342
+ if (oauthProfileStatus(next).state !== "ready") throw new AuthConfigError("New credential is not ready; the old login was preserved.");
1343
+ updateAuthentication(path, (raw) => {
1344
+ assertAuthSnapshot(raw, agent2, pending.snapshot);
1345
+ if (previous && pending.previousState !== "logged_out" && oauthProfileStatus(previous).state === "logged_out") {
1346
+ throw new AuthConfigError("Login was revoked during authorization; retry login. The late result was not saved.");
1347
+ }
1348
+ if (update && groupSnapshot(raw, previous) !== pending.group) throw new AuthConfigError("The shared login or its users changed during authorization. Retry and confirm the current users.");
1349
+ raw.logins ??= {};
1350
+ if (!(update && previous?.loginId) && Object.hasOwn(raw.logins, loginId)) throw new AuthConfigError("Login ID already exists; retry login.");
1351
+ raw.logins[loginId] = { ...raw.logins[loginId], credential_ref: reference };
1352
+ if (update && previous?.loginId) {
1353
+ for (const user of loginUsers(raw, loginId)) {
1354
+ oauthProfileFromConfig(raw, path, user);
1355
+ delete ownAuthProfile(raw, user).base_url;
1356
+ }
1357
+ }
1358
+ if (pending.name === void 0) setChoice(raw, agent2, { loginId });
1359
+ else if (!previous?.loginId) setChoice(raw, "default", { loginId });
1360
+ updateConfig?.(raw);
1361
+ });
1362
+ }
1363
+ function keyCandidate(agent2, apiKey, baseUrl) {
1364
+ return { kind: "api-key", payload: { api_key: apiKey }, metadata: { base_url: baseUrl, owner: { distribution: "public", agent: agent2 }, state: "ready", authorization_method: "api-key" } };
1365
+ }
1366
+ function updateAuthentication(path, task) {
1367
+ return new LocalCredentialProvider(join3(dirname4(path), "credentials.json")).transaction((tx) => {
1368
+ const created = [];
1369
+ try {
1370
+ return updateAuthConfig(path, (raw) => {
1371
+ const before = structuredClone(raw), snapshot2 = authSnapshot(raw, "default");
1372
+ const result = task(raw), d = ownAuthProfile(before, "default");
1373
+ if (snapshot2 !== authSnapshot(raw, "default") && typeof d.api_key === "string" && d.api_key) {
1374
+ const selected = (s) => ["credential_ref", "access_credential", "api_key"].some((k) => Object.hasOwn(s, k)) || !!s.oauth_credential_ref;
1375
+ for (const agent2 of Object.keys(before.agents)) {
1376
+ if (agent2 === "default") continue;
1377
+ const prior = ownAuthProfile(before, agent2), current = ownAuthProfile(raw, agent2);
1378
+ if (selected(prior) || selected(current)) continue;
1379
+ const baseUrl = prior.base_url ?? d.base_url ?? DEFAULT_DATA_BASE_URL, ref = randomBytes5(16).toString("hex");
1380
+ created.push(tx.put(ref, keyCandidate(agent2, d.api_key, baseUrl)));
1381
+ current.credential_ref = ref;
1382
+ delete current.base_url;
1383
+ }
1384
+ }
1385
+ return result;
1386
+ });
1387
+ } catch (error) {
1388
+ for (const receipt of created) {
1389
+ try {
1390
+ tx.remove(receipt.after);
1391
+ } catch {
1392
+ try {
1393
+ process.stderr.write("Credential cleanup could not be confirmed; inspect auth status before retrying.\n");
1394
+ } catch {
1395
+ }
1396
+ }
1397
+ }
1398
+ throw error;
1399
+ }
1400
+ });
1401
+ }
1402
+
1403
+ // ../shared/src/login-cleanup.ts
1404
+ function referenced(raw, reference) {
1405
+ return Object.values(raw.agents).some((s) => s.oauth_credential_ref === reference || s.credential_ref === reference) || Object.entries(raw.logins ?? {}).some(([id, entry]) => entry.credential_ref === reference && loginUsers(raw, id).length > 0);
1406
+ }
1407
+ async function releaseLogin(profile, transport, detach = () => {
1408
+ }) {
1409
+ return new OAuthSessionStore(profile.credentialsPath).retire(profile.reference, oauthOwner(profile), transport, () => updateAuthConfig(profile.configPath, (raw) => {
1410
+ detach(raw);
1411
+ if (referenced(raw, profile.reference)) return false;
1412
+ for (const [id, entry] of Object.entries(raw.logins ?? {})) {
1413
+ if (entry.credential_ref === profile.reference) delete raw.logins[id];
1414
+ }
1415
+ return true;
1416
+ }));
1417
+ }
1418
+ async function collectUnusedLogins(path, transport, previous) {
1419
+ const raw = readAuthConfig(path), candidates = /* @__PURE__ */ new Map();
1420
+ if (previous) candidates.set(previous.reference, previous);
1421
+ for (const [id, entry] of Object.entries(raw.logins ?? {})) {
1422
+ if (loginUsers(raw, id).length) continue;
1423
+ const profile = { ...oauthProfile(entry.credential_ref, path, id, "https://api.cn-hangzhou.agentcontext.aliyuncs.com"), loginId: id };
1424
+ if (profile.reference) candidates.set(profile.reference, profile);
1425
+ }
1426
+ let removed = 0, unconfirmed = 0;
1427
+ for (const profile of candidates.values()) {
1428
+ try {
1429
+ const result = await releaseLogin(profile, transport);
1430
+ if (result.removed) removed++;
1431
+ if (result.remoteUnconfirmed) unconfirmed++;
1432
+ } catch {
1433
+ unconfirmed++;
1434
+ }
1435
+ }
1436
+ return { removed, unconfirmed };
1437
+ }
1438
+
1439
+ // ../shared/src/authorization/authorization-service.ts
1440
+ var AuthorizationError = class extends Error {
1441
+ code;
1442
+ constructor(message, code) {
1443
+ super(message);
1444
+ this.code = code;
1445
+ this.name = "AuthorizationError";
1446
+ }
1447
+ };
1448
+ var AuthorizationDeclinedError = class extends Error {
1449
+ constructor(message = "authorization declined") {
1450
+ super(message);
1451
+ this.name = "AuthorizationDeclinedError";
1452
+ }
1453
+ };
1454
+ var AuthorizationService = class {
1455
+ flows = /* @__PURE__ */ new Map();
1456
+ running = /* @__PURE__ */ new Map();
1457
+ credentials;
1458
+ constructor(credentials) {
1459
+ this.credentials = credentials;
1460
+ }
1461
+ registerFlow(flow) {
1462
+ if (this.flows.has(flow.key)) throw new AuthorizationError("authorization flow already registered", "DUPLICATE_FLOW");
1463
+ this.flows.set(flow.key, flow);
1464
+ return () => {
1465
+ this.flows.delete(flow.key);
1466
+ this.running.get(flow.key)?.abort();
1467
+ };
1468
+ }
1469
+ list() {
1470
+ return [...this.flows.values()].map((flow) => ({ key: flow.key, label: flow.label, methods: flow.methods, inFlight: this.running.has(flow.key) }));
1471
+ }
1472
+ cancel(key) {
1473
+ this.running.get(key)?.abort();
1474
+ }
1475
+ async begin(request) {
1476
+ const flow = this.flows.get(request.key);
1477
+ if (!flow) throw new AuthorizationError("no authorization flow", "NO_FLOW");
1478
+ const method = request.method ?? flow.methods[0].id;
1479
+ if (!flow.methods.some((m) => m.id === method)) throw new AuthorizationError("authorization method is not supported", "UNKNOWN_METHOD");
1480
+ if (this.running.has(request.key)) throw new AuthorizationError("authorization already running", "ALREADY_IN_FLIGHT");
1481
+ if (request.signal?.aborted) return { status: "cancelled" };
1482
+ const provider = this.credentials, key = request.credentialKey ?? request.key;
1483
+ const before = !request.target && provider ? provider.snapshot(key) : void 0;
1484
+ const controller = new AbortController(), withdraw = () => controller.abort(request.signal?.reason);
1485
+ request.signal?.addEventListener("abort", withdraw, { once: true });
1486
+ this.running.set(request.key, controller);
1487
+ const warn = (message) => {
1488
+ try {
1489
+ request.warn?.(message);
1490
+ } catch {
1491
+ }
1492
+ };
1493
+ const target = request.target ?? {
1494
+ commit: (candidate2) => {
1495
+ if (!provider || !before) throw new AuthorizationError("authorization target required", "NO_TARGET");
1496
+ return provider.commit(key, candidate2, before);
1497
+ },
1498
+ rollback: (receipt2) => provider.rollback(receipt2),
1499
+ retirePrevious: async () => {
1500
+ if (before?.record) await flow.revoke(before.record);
1501
+ }
1502
+ };
1503
+ let candidate, receipt, committed = false;
1504
+ try {
1505
+ candidate = await flow.run({
1506
+ method,
1507
+ signal: controller.signal,
1508
+ notify: (notice) => {
1509
+ try {
1510
+ request.interaction.notify(notice);
1511
+ } catch {
1512
+ }
1513
+ },
1514
+ prompt: (prompt) => request.interaction.prompt(prompt)
1515
+ });
1516
+ controller.signal.throwIfAborted();
1517
+ if (!candidate) throw new AuthorizationError("authorization completed without a candidate credential", "NOT_COMMITTED");
1518
+ await flow.validate?.(candidate, controller.signal);
1519
+ controller.signal.throwIfAborted();
1520
+ receipt = target.commit(candidate);
1521
+ committed = true;
1522
+ try {
1523
+ if (request.finalize) {
1524
+ controller.signal.throwIfAborted();
1525
+ await request.finalize();
1526
+ controller.signal.throwIfAborted();
1527
+ }
1528
+ } catch (error) {
1529
+ try {
1530
+ committed = !target.rollback(receipt);
1531
+ } catch {
1532
+ warn("The previous local credential could not be restored; inspect auth status before retrying.");
1533
+ }
1534
+ throw error;
1535
+ }
1536
+ try {
1537
+ await target.retirePrevious?.();
1538
+ } catch {
1539
+ warn(request.previousCleanupWarning ?? "New login saved; previous credential cleanup could not be confirmed.");
1540
+ }
1541
+ return { status: "authorized" };
1542
+ } catch (error) {
1543
+ if (candidate && !committed) {
1544
+ try {
1545
+ target.discard?.();
1546
+ } catch {
1547
+ warn("New login was not saved; local credential cleanup needs attention.");
1548
+ }
1549
+ try {
1550
+ await flow.revoke(candidate);
1551
+ } catch {
1552
+ warn("New login was not saved; session cleanup could not be confirmed.");
1553
+ }
1554
+ }
1555
+ if (controller.signal.aborted || error instanceof AuthorizationDeclinedError) return { status: "cancelled" };
1556
+ throw error;
1557
+ } finally {
1558
+ request.signal?.removeEventListener("abort", withdraw);
1559
+ this.running.delete(request.key);
1560
+ }
1561
+ }
1562
+ };
1563
+
1564
+ // ../shared/src/authorization/public-target.ts
1565
+ import { dirname as dirname5, join as join4 } from "node:path";
1566
+ function publicAuthorizationTarget(pending, revoke, trace, updateConfig) {
1567
+ const path = join4(dirname5(pending.path), "credentials.json"), store = new OAuthSessionStore(path, { trace }), provider = new LocalCredentialProvider(path);
1568
+ let reference, published = false;
1569
+ return {
1570
+ commit(candidate) {
1571
+ authTrace(trace, "login.commit.start");
1572
+ try {
1573
+ const session = oauthSessionFromCredential(candidate);
1574
+ reference = store.saveLogin(pending.agent, session, pending.loginId);
1575
+ commitLogin(pending, reference, session.baseUrl, updateConfig);
1576
+ published = true;
1577
+ authTrace(trace, "login.commit.success", { login_id: pending.loginId, session_id: session.sessionId });
1578
+ return reference;
1579
+ } catch (error) {
1580
+ authTrace(trace, "login.commit.failure", { error });
1581
+ throw error;
1582
+ }
1583
+ },
1584
+ // Public login has no integration finalize step after publishing. A successful commit is final.
1585
+ rollback() {
1586
+ return false;
1587
+ },
1588
+ discard() {
1589
+ if (!reference || published) return;
1590
+ const snapshot2 = provider.snapshot(reference);
1591
+ if (snapshot2.record) {
1592
+ provider.transaction((tx) => tx.remove(snapshot2));
1593
+ }
1594
+ },
1595
+ async retirePrevious() {
1596
+ const result = await collectUnusedLogins(pending.path, revoke, pending.previous);
1597
+ if (result.unconfirmed) throw new Error("Previous session cleanup unconfirmed");
1598
+ }
1599
+ };
1600
+ }
1601
+
1602
+ // ../../plugins/dsh-plugins/src/settings-contract.ts
1603
+ var packageName = "@aliyunrds/ctxdb-dsh";
1604
+ var settingsNamespace = "aliyunContextdbSettings";
1605
+ var settingsEndpoint = `${settingsNamespace}/auth`;
1606
+ var memoryScopeFields = ["project_id", "user_id", "agent_id", "app_id"];
1607
+ var memoryRecallFields = ["project_id", "user_id", "agent_id", "app_id"];
1608
+ function parseMemoryScope(input) {
1609
+ if (!input || typeof input !== "object" || Array.isArray(input)) return;
1610
+ const values = input;
1611
+ const scope = {};
1612
+ for (const field of memoryScopeFields) {
1613
+ if (!Object.hasOwn(values, field)) continue;
1614
+ const value = values[field];
1615
+ if (field === "app_id" && value === null) {
1616
+ scope.app_id = null;
1617
+ continue;
1618
+ }
1619
+ if (typeof value !== "string" || value.length > 256 || /[\x00-\x1f\x7f]/.test(value) || value.trim() === "*") return;
1620
+ scope[field] = value.trim();
1621
+ }
1622
+ return scope;
1623
+ }
1624
+ function parseMemoryRecallFilters(input) {
1625
+ if (!input || typeof input !== "object" || Array.isArray(input)) return;
1626
+ const values = input;
1627
+ const filters = {};
1628
+ for (const field of memoryRecallFields) {
1629
+ if (!Object.hasOwn(values, field)) continue;
1630
+ const value = values[field];
1631
+ if (typeof value !== "boolean") return;
1632
+ filters[field] = value;
1633
+ }
1634
+ return filters;
1635
+ }
1636
+ function parseRequest(input) {
1637
+ if (input && typeof input === "object" && !Array.isArray(input)) {
1638
+ const { action, site, apiKey, pendingId, setting, enabled, scope: rawScope, recallFilters: rawFilters } = input;
1639
+ if (action === "status" || action === "disconnect" || action === "use-login") return { action };
1640
+ if (action === "cancel" && typeof pendingId === "string" && pendingId.length === 36) return { action, pendingId };
1641
+ if (action === "set-context" && (setting === "autoRecall" || setting === "autoCapture") && typeof enabled === "boolean") {
1642
+ return { action, setting, enabled };
1643
+ }
1644
+ if (action === "set-memory-scope") {
1645
+ const scope = parseMemoryScope(rawScope);
1646
+ const recallFilters = parseMemoryRecallFilters(rawFilters);
1647
+ if (scope && (rawFilters === void 0 || recallFilters)) return { action, scope, recallFilters };
1648
+ }
1649
+ if (site === "cn" || site === "intl") {
1650
+ if (action === "start") return { action, site };
1651
+ if (action === "save-key" && typeof apiKey === "string" && apiKey.length <= 4096) return { action, site, apiKey };
1652
+ }
1653
+ }
1654
+ throw new Error("Invalid ContextDB request.");
1655
+ }
1656
+ var settingsInvocation = {
1657
+ id: `${packageName}#${settingsEndpoint}`,
1658
+ service: settingsNamespace,
1659
+ namespace: settingsNamespace,
1660
+ method: "auth",
1661
+ invocation: { kind: "direct" },
1662
+ parameters: [{
1663
+ name: "request",
1664
+ wire: "request",
1665
+ source: "json",
1666
+ codec: { mode: "strict", typeSymbol: `${packageName}#SettingsRequest`, create: () => ({ parse: parseRequest }) }
1667
+ }],
1668
+ cancellation: { parameter: "signal" },
1669
+ result: { mode: "src-json" }
1670
+ };
1671
+
1672
+ // ../../plugins/dsh-plugins/src/auth.ts
1673
+ import { randomUUID } from "node:crypto";
1674
+ var agent = "dsh";
1675
+ function createDeviceLogin(path) {
1676
+ let attempt;
1677
+ let phase = "idle";
1678
+ let loggingOut = false;
1679
+ const transport = { revoke: (token, origin2) => new CoreDeviceClient(origin2).revoke(token, origin2) };
1680
+ function begin(site, signal, selectOnSuccess = false) {
1681
+ if (attempt || loggingOut) throw new Error("A ContextDB connection operation is already in progress.");
1682
+ if (signal?.aborted) throw new Error("ContextDB authorization was cancelled.");
1683
+ const preset = PUBLIC_SITES[site];
1684
+ const previousSelection = selectOnSuccess ? JSON.stringify(readAuthConfig(path).dsh_auth) : void 0;
1685
+ const pending = beginLogin(path, agent);
1686
+ const client = new CoreDeviceClient(preset.baseUrl);
1687
+ const controller = new AbortController();
1688
+ const authorization2 = new AuthorizationService();
1689
+ const id = randomUUID();
1690
+ const first = Promise.withResolvers();
1691
+ authorization2.registerFlow({
1692
+ key: "device",
1693
+ label: "ContextDB",
1694
+ methods: [{ id: "device", label: "Browser authorization" }],
1695
+ async run(session) {
1696
+ const login = await client.login({
1697
+ initialAgent: agent,
1698
+ signal: session.signal,
1699
+ onPrompt({ userCode }) {
1700
+ const url = new URL(preset.authorizationUrl);
1701
+ url.searchParams.set("user_code", userCode);
1702
+ first.resolve({ id, userCode, url: url.toString() });
1703
+ }
1704
+ });
1705
+ return oauthSessionCandidate(agent, login, pending.loginId);
1706
+ },
1707
+ async revoke(candidate) {
1708
+ const login = oauthSessionFromCredential(candidate);
1709
+ await transport.revoke(login.refreshToken, login.baseUrl);
1710
+ }
1711
+ });
1712
+ phase = "waiting";
1713
+ const withdraw = () => controller.abort();
1714
+ signal?.addEventListener("abort", withdraw, { once: true });
1715
+ const done = authorization2.begin({
1716
+ key: "device",
1717
+ signal: controller.signal,
1718
+ target: publicAuthorizationTarget(pending, transport, void 0, selectOnSuccess ? (raw) => {
1719
+ if (JSON.stringify(raw.dsh_auth) !== previousSelection) {
1720
+ throw new Error("ContextDB authentication changed during authorization.");
1721
+ }
1722
+ raw.dsh_auth = { mode: "oauth" };
1723
+ } : void 0),
1724
+ interaction: { notify() {
1725
+ }, async prompt() {
1726
+ throw new Error("Unexpected ContextDB authorization prompt");
1727
+ } },
1728
+ warn: () => {
1729
+ phase = "cleanup-unconfirmed";
1730
+ }
1731
+ }).then((outcome) => {
1732
+ if (outcome.status === "cancelled") {
1733
+ phase = "cancelled";
1734
+ first.reject(new Error("ContextDB authorization was cancelled."));
1735
+ } else if (phase !== "cleanup-unconfirmed") {
1736
+ phase = "connected";
1737
+ }
1738
+ return phase;
1739
+ }).catch((error) => {
1740
+ phase = error instanceof DeviceFlowError && error.code === "expired_token" ? "expired" : error instanceof DeviceFlowError && error.code === "access_denied" ? "cancelled" : "failed";
1741
+ first.reject(new Error("ContextDB could not complete authorization."));
1742
+ return phase;
1743
+ }).finally(() => {
1744
+ attempt = void 0;
1745
+ });
1746
+ attempt = { id, site, controller, done };
1747
+ return { prompt: first.promise, done, detach: () => signal?.removeEventListener("abort", withdraw) };
1748
+ }
1749
+ async function start(site, signal, options) {
1750
+ const login = begin(site, signal, options?.selectOnSuccess);
1751
+ try {
1752
+ return await login.prompt;
1753
+ } finally {
1754
+ login.detach();
1755
+ }
1756
+ }
1757
+ async function authorize(site, onPrompt, signal) {
1758
+ const login = begin(site, signal, true);
1759
+ try {
1760
+ const prompt = await login.prompt.catch(() => void 0);
1761
+ if (prompt && !signal.aborted) onPrompt(prompt);
1762
+ return await login.done;
1763
+ } catch (error) {
1764
+ await cancel();
1765
+ throw error;
1766
+ } finally {
1767
+ login.detach();
1768
+ }
1769
+ }
1770
+ function status() {
1771
+ const profile = selectedLogin(path, agent);
1772
+ const status2 = profile && oauthProfileStatus(profile);
1773
+ return {
1774
+ phase,
1775
+ pendingId: attempt?.id,
1776
+ pendingSite: attempt?.site,
1777
+ site: profile && publicSiteForUrl(profile.baseUrl),
1778
+ connection: status2 && "workspaceId" in status2 ? {
1779
+ ready: status2.state === "ready" || status2.state === "refresh_retryable",
1780
+ workspaceId: status2.workspaceId,
1781
+ memberId: status2.memberId,
1782
+ scope: status2.scope
1783
+ } : void 0
1784
+ };
1785
+ }
1786
+ async function cancel(id) {
1787
+ const current = attempt;
1788
+ if (!current || id !== void 0 && current.id !== id) return;
1789
+ current.controller.abort();
1790
+ await current.done;
1791
+ return phase;
1792
+ }
1793
+ async function logout() {
1794
+ if (loggingOut) throw new Error("ContextDB is already disconnecting.");
1795
+ loggingOut = true;
1796
+ try {
1797
+ await cancel();
1798
+ const snapshot2 = authSnapshot(readAuthConfig(path), agent);
1799
+ const profile = selectedLogin(path, agent);
1800
+ if (!profile) return "idle";
1801
+ const result = await releaseLogin(profile, transport, (raw) => {
1802
+ assertAuthSnapshot(raw, agent, snapshot2);
1803
+ ownAuthProfile(raw, agent).access_credential = null;
1804
+ });
1805
+ phase = result.remoteUnconfirmed ? "cleanup-unconfirmed" : "idle";
1806
+ return phase;
1807
+ } finally {
1808
+ loggingOut = false;
1809
+ }
1810
+ }
1811
+ return { start, authorize, status, cancel, logout };
1812
+ }
1813
+
1814
+ // ../../plugins/dsh-plugins/src/configure.ts
1815
+ var usage = `Usage: dsh plugin --profile <name> exec ctxdb-dsh configure [--site cn|intl] [--key-stdin | --device-code]
1816
+ ctxdb-dsh configure --profile <name> [--site cn|intl] [--key-stdin | --device-code]`;
1817
+ function profilesDirectory() {
1818
+ const home = process.env.DSH_HOME?.trim() ? process.env.DSH_HOME : join5(homedir2(), ".dsh");
1819
+ return resolve2(home.replace(/^~(?=$|[/\\])/, () => homedir2()), "profiles");
1820
+ }
1821
+ function hasPlugin(dir) {
1822
+ return existsSync3(join5(dir, "node_modules", "@aliyunrds", "ctxdb-dsh", "package.json"));
1823
+ }
1824
+ async function readKey(piped) {
1825
+ if (piped && !process.stdin.isTTY) return readFileSync3(0, "utf8").replace(/\r?\n$/, "");
1826
+ if (!process.stdin.isTTY || piped) throw new Error("Use a terminal or pipe the key with --key-stdin.");
1827
+ const muted = new Writable({ write(_chunk, _encoding, done) {
1828
+ done();
1829
+ } });
1830
+ const input = createInterface({ input: process.stdin, output: muted, terminal: true });
1831
+ const abort = new AbortController();
1832
+ input.once("SIGINT", () => abort.abort());
1833
+ input.once("close", () => abort.abort());
1834
+ process.stderr.write("ContextDB API Key: ");
1835
+ try {
1836
+ return await input.question("", { signal: abort.signal });
1837
+ } catch {
1838
+ throw new Error("ContextDB configuration cancelled.");
1839
+ } finally {
1840
+ input.close();
1841
+ process.stderr.write("\n");
1842
+ }
1843
+ }
1844
+ async function configureDeviceCode(profileDir, site) {
1845
+ const device = createDeviceLogin(join5(profileDir, "aliyun-contextdb", "ctxdb.json"));
1846
+ const controller = new AbortController();
1847
+ const interrupt = () => controller.abort();
1848
+ process.once("SIGINT", interrupt);
1849
+ process.once("SIGTERM", interrupt);
1850
+ try {
1851
+ const phase = await device.authorize(site, (prompt) => {
1852
+ console.error(`Open this link to authorize ContextDB: ${prompt.url}`);
1853
+ console.error(`User code: ${prompt.userCode}
1854
+ Waiting for authorization. Press Ctrl+C to cancel.`);
1855
+ void openBrowser(prompt.url);
1856
+ }, controller.signal);
1857
+ if (phase !== "connected" && phase !== "cleanup-unconfirmed") {
1858
+ console.error(phase === "cancelled" ? "ContextDB authorization was cancelled or denied." : phase === "expired" ? "ContextDB device code expired. Run configure again." : "ContextDB could not complete authorization. Run configure again.");
1859
+ return controller.signal.aborted ? 130 : 1;
1860
+ }
1861
+ const { connection } = device.status();
1862
+ if (!connection?.ready) {
1863
+ console.error("ContextDB authorization could not be read back. Run configure again.");
1864
+ return 1;
1865
+ }
1866
+ console.log(`ContextDB connected to Workspace ${connection.workspaceId}, Member ${connection.memberId} (${site}), profile ${basename(profileDir)}.`);
1867
+ if (phase === "cleanup-unconfirmed") console.error("Previous session revocation could not be confirmed.");
1868
+ return 0;
1869
+ } finally {
1870
+ process.removeListener("SIGINT", interrupt);
1871
+ process.removeListener("SIGTERM", interrupt);
1872
+ }
1873
+ }
1874
+ async function main(args) {
1875
+ if (args.length === 1 && args[0] === "--help") {
1876
+ console.log(usage);
1877
+ return 0;
1878
+ }
1879
+ let parsed;
1880
+ try {
1881
+ parsed = parseArgs({
1882
+ args,
1883
+ allowPositionals: true,
1884
+ tokens: true,
1885
+ options: {
1886
+ help: { type: "boolean" },
1887
+ profile: { type: "string" },
1888
+ site: { type: "string", default: "cn" },
1889
+ "key-stdin": { type: "boolean" },
1890
+ "device-code": { type: "boolean" }
1891
+ }
1892
+ });
1893
+ } catch {
1894
+ console.error(usage);
1895
+ return 2;
1896
+ }
1897
+ const site = parsed.values.site;
1898
+ const deviceCode = parsed.values["device-code"] === true;
1899
+ const piped = parsed.values["key-stdin"] === true;
1900
+ const options = parsed.tokens.filter((token) => token.kind === "option");
1901
+ if (parsed.positionals.length !== 1 || parsed.positionals[0] !== "configure" || site !== "cn" && site !== "intl" || new Set(options.map((token) => token.name)).size !== options.length) {
1902
+ console.error(usage);
1903
+ return 2;
1904
+ }
1905
+ if (parsed.values.help) {
1906
+ console.log(usage);
1907
+ return 0;
1908
+ }
1909
+ if (deviceCode && piped) {
1910
+ console.error("--device-code and --key-stdin are mutually exclusive.\n" + usage);
1911
+ return 2;
1912
+ }
1913
+ const requested = parsed.values.profile;
1914
+ if (requested !== void 0 && (typeof requested !== "string" || !requested || /[/\\\x00]/.test(requested) || [".", "..", "node_modules"].includes(requested) || process.platform === "win32" && /[<>:"|?*\x00-\x1f]/.test(requested))) {
1915
+ console.error("Invalid DSH profile name.");
1916
+ return 2;
1917
+ }
1918
+ const cwd = process.cwd();
1919
+ const name = basename(cwd);
1920
+ const profiles = profilesDirectory();
1921
+ const insideProfile = basename(dirname6(cwd)) === "profiles" && hasPlugin(cwd);
1922
+ const fromExec = insideProfile && process.env.npm_command === "exec";
1923
+ if (typeof requested === "string" && !fromExec) {
1924
+ if (!hasPlugin(join5(profiles, requested))) {
1925
+ console.error("Install the ContextDB plugin in the target DSH profile first.");
1926
+ return 2;
1927
+ }
1928
+ const flags = ["--site", site, ...deviceCode ? ["--device-code"] : piped ? ["--key-stdin"] : []];
1929
+ const child = process.platform === "win32" ? spawnSync(
1930
+ process.env.ComSpec ?? "cmd.exe",
1931
+ ["/d", "/s", "/v:off", "/c", `dsh plugin --profile "%CTXDB_DSH_TARGET%" exec ctxdb-dsh configure ${flags.join(" ")}`],
1932
+ { env: { ...process.env, CTXDB_DSH_TARGET: requested }, stdio: "inherit", windowsVerbatimArguments: true }
1933
+ ) : spawnSync("dsh", ["plugin", "--profile", requested, "exec", "ctxdb-dsh", "configure", ...flags], { stdio: "inherit" });
1934
+ if (child.error) console.error("Could not start dsh. Check that dsh is on PATH.");
1935
+ return child.status ?? 1;
1936
+ }
1937
+ if (!insideProfile || requested !== void 0 && requested !== name) {
1938
+ console.error(insideProfile ? "The configure profile must match the profile selected by dsh plugin." : usage);
1939
+ return 2;
1940
+ }
1941
+ const configuredDir = join5(profiles, name);
1942
+ const profileDir = existsSync3(configuredDir) && realpathSync(configuredDir) === cwd ? configuredDir : cwd;
1943
+ if (deviceCode) return configureDeviceCode(profileDir, site);
1944
+ let key;
1945
+ try {
1946
+ key = await readKey(piped);
1947
+ } catch (error) {
1948
+ console.error(error.message);
1949
+ return 2;
1950
+ }
1951
+ if (!key || /\s/.test(key)) {
1952
+ console.error("Enter a ContextDB API Key without whitespace.");
1953
+ return 2;
1954
+ }
1955
+ const temporary = mkdtempSync(join5(tmpdir(), "ctxdb-dsh-configure-"));
1956
+ try {
1957
+ const runner = join5(temporary, "profiles", "ctxdb-configure");
1958
+ mkdirSync3(runner, { recursive: true });
1959
+ writeFileSync3(join5(runner, "package.json"), JSON.stringify({ private: true, dsh: { profile: { bundles: [] } } }));
1960
+ writeFileSync3(join5(runner, "credentials-root.yml"), "[]\n");
1961
+ writeFileSync3(join5(runner, "cordis.patch.yml"), JSON.stringify([{ insert: [{
1962
+ id: "aliyun-contextdb-configure",
1963
+ name: fileURLToPath(new URL("./configure-host.js", import.meta.url)),
1964
+ config: { site, profileDir }
1965
+ }] }]), { mode: 384 });
1966
+ const options2 = {
1967
+ env: { ...process.env, DSH_HOME: temporary, DSH_TELEMETRY_DISABLED: "1" },
1968
+ input: key,
1969
+ stdio: ["pipe", "inherit", "inherit"],
1970
+ timeout: 3e4
1971
+ };
1972
+ const result = process.platform === "win32" ? spawnSync(
1973
+ process.env.ComSpec ?? "cmd.exe",
1974
+ ["/d", "/s", "/v:off", "/c", "dsh --profile ctxdb-configure"],
1975
+ { ...options2, windowsVerbatimArguments: true }
1976
+ ) : spawnSync("dsh", ["--profile", "ctxdb-configure"], options2);
1977
+ if (result.error) console.error("Could not start the DSH configuration process. Check that dsh is on PATH and try again.");
1978
+ return result.status ?? 1;
1979
+ } finally {
1980
+ rmSync(temporary, { recursive: true, force: true });
1981
+ }
1982
+ }
1983
+ try {
1984
+ process.exitCode = await main(process.argv.slice(2));
1985
+ } catch {
1986
+ console.error("Could not configure ContextDB. Check the DSH installation and profile permissions.");
1987
+ process.exitCode = 1;
1988
+ }