@fluid-app/fluid-cli 0.1.801 → 0.1.802
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/dist/bin/fluid.mjs +209 -42
- package/dist/bin/fluid.mjs.map +1 -1
- package/dist/client-DeZ9F-Hm.mjs +2 -0
- package/dist/{hook-gdAJafKe.mjs → hook-DjcOPPI_.mjs} +15 -4
- package/dist/{hook-gdAJafKe.mjs.map → hook-DjcOPPI_.mjs.map} +1 -1
- package/dist/index.d.mts +13 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/{profiles-CbMJHi-u.mjs → profiles-B6V5IBeX.mjs} +723 -219
- package/dist/profiles-B6V5IBeX.mjs.map +1 -0
- package/package.json +1 -1
- package/dist/client-DsG9CMhN.mjs +0 -2
- package/dist/profiles-CbMJHi-u.mjs.map +0 -1
|
@@ -1,8 +1,9 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
1
2
|
import { closeSync, existsSync, linkSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
|
|
2
3
|
import { dirname, join } from "node:path";
|
|
3
4
|
import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
4
5
|
import { homedir } from "node:os";
|
|
5
|
-
import { execFile } from "node:child_process";
|
|
6
|
+
import { execFile, spawn } from "node:child_process";
|
|
6
7
|
import { createServer } from "node:http";
|
|
7
8
|
//#region src/config/types.ts
|
|
8
9
|
/** Whether a profile signs in through the identity service. */
|
|
@@ -46,6 +47,141 @@ function getConfigFilePath() {
|
|
|
46
47
|
return join(getConfigDir(), "config.json");
|
|
47
48
|
}
|
|
48
49
|
//#endregion
|
|
50
|
+
//#region src/config/lock.ts
|
|
51
|
+
/** The config lock could not be acquired in time. */
|
|
52
|
+
var ConfigLockTimeoutError = class extends Error {
|
|
53
|
+
constructor(lockPath) {
|
|
54
|
+
super(`The config lock ${lockPath} is held by another fluid process. If no fluid command is running, remove that file and try again.`);
|
|
55
|
+
this.lockPath = lockPath;
|
|
56
|
+
this.name = "ConfigLockTimeoutError";
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
const configLockTimings = {
|
|
60
|
+
timeoutMs: 5e3,
|
|
61
|
+
staleMs: 3e4,
|
|
62
|
+
breakStaleMs: 5e3
|
|
63
|
+
};
|
|
64
|
+
const lockIo = { write: writeSync };
|
|
65
|
+
const RETRY_MS = 25;
|
|
66
|
+
const heldLocks = /* @__PURE__ */ new Set();
|
|
67
|
+
function sleep(ms) {
|
|
68
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
69
|
+
}
|
|
70
|
+
function ageMs(path) {
|
|
71
|
+
try {
|
|
72
|
+
return Date.now() - statSync(path).mtimeMs;
|
|
73
|
+
} catch {
|
|
74
|
+
return -1;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
function isStale(path, staleMs) {
|
|
78
|
+
return ageMs(path) > staleMs;
|
|
79
|
+
}
|
|
80
|
+
function holderAlive(content) {
|
|
81
|
+
const pid = Number(/:(\d+)$/.exec(content)?.[1]);
|
|
82
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
83
|
+
try {
|
|
84
|
+
process.kill(pid, 0);
|
|
85
|
+
return true;
|
|
86
|
+
} catch (error) {
|
|
87
|
+
return error.code === "EPERM";
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
function hasHolderPid(content) {
|
|
91
|
+
return /:\d+$/.test(content);
|
|
92
|
+
}
|
|
93
|
+
function isLockStale(path) {
|
|
94
|
+
if (ageMs(path) <= configLockTimings.staleMs) return false;
|
|
95
|
+
try {
|
|
96
|
+
const content = readFileSync(path, "utf8");
|
|
97
|
+
return !hasHolderPid(content) || !holderAlive(content);
|
|
98
|
+
} catch {
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
function tryCreate(path, content) {
|
|
103
|
+
const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
104
|
+
try {
|
|
105
|
+
const fd = openSync(tmp, "wx", 384);
|
|
106
|
+
try {
|
|
107
|
+
lockIo.write(fd, content);
|
|
108
|
+
} finally {
|
|
109
|
+
closeSync(fd);
|
|
110
|
+
}
|
|
111
|
+
try {
|
|
112
|
+
linkSync(tmp, path);
|
|
113
|
+
return true;
|
|
114
|
+
} catch {
|
|
115
|
+
return false;
|
|
116
|
+
}
|
|
117
|
+
} finally {
|
|
118
|
+
try {
|
|
119
|
+
unlinkSync(tmp);
|
|
120
|
+
} catch {}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
function newContent() {
|
|
124
|
+
return `${randomUUID()}:${process.pid}`;
|
|
125
|
+
}
|
|
126
|
+
function release(path, content) {
|
|
127
|
+
try {
|
|
128
|
+
if (readFileSync(path, "utf8") === content) unlinkSync(path);
|
|
129
|
+
} catch {}
|
|
130
|
+
}
|
|
131
|
+
function breakStale(lockPath) {
|
|
132
|
+
const breakPath = `${lockPath}.break`;
|
|
133
|
+
const token = newContent();
|
|
134
|
+
if (!tryCreate(breakPath, token)) {
|
|
135
|
+
if (isStale(breakPath, configLockTimings.breakStaleMs)) try {
|
|
136
|
+
unlinkSync(breakPath);
|
|
137
|
+
} catch {}
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
try {
|
|
141
|
+
if (isLockStale(lockPath)) try {
|
|
142
|
+
unlinkSync(lockPath);
|
|
143
|
+
} catch {}
|
|
144
|
+
} finally {
|
|
145
|
+
release(breakPath, token);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Runs `fn` while holding an exclusive lock file next to the config, so
|
|
150
|
+
* concurrent config writers cannot interleave. Re-entrant within this
|
|
151
|
+
* process: a nested call for the held lock just runs `fn`. A lock
|
|
152
|
+
* older than the stale timeout is treated as abandoned, and removed under a
|
|
153
|
+
* second short-lived lock so only one contender breaks it, only when its
|
|
154
|
+
* holder process is gone or it records no holder.
|
|
155
|
+
*
|
|
156
|
+
* @param fn [() => T] Synchronous work to run under the lock.
|
|
157
|
+
* @param timeoutMs [number] How long to wait for the lock; defaults to the
|
|
158
|
+
* standard timeout.
|
|
159
|
+
* @return [T] The result of `fn`.
|
|
160
|
+
* @raise [ConfigLockTimeoutError] When the lock stays held past the timeout.
|
|
161
|
+
*/
|
|
162
|
+
function withConfigLock(fn, timeoutMs = configLockTimings.timeoutMs) {
|
|
163
|
+
const lockPath = `${getConfigFilePath()}.lock`;
|
|
164
|
+
if (heldLocks.has(lockPath)) return fn();
|
|
165
|
+
mkdirSync(dirname(lockPath), {
|
|
166
|
+
recursive: true,
|
|
167
|
+
mode: 448
|
|
168
|
+
});
|
|
169
|
+
const token = newContent();
|
|
170
|
+
const deadline = Date.now() + timeoutMs;
|
|
171
|
+
while (!tryCreate(lockPath, token)) {
|
|
172
|
+
if (isLockStale(lockPath)) breakStale(lockPath);
|
|
173
|
+
if (Date.now() >= deadline) throw new ConfigLockTimeoutError(lockPath);
|
|
174
|
+
sleep(RETRY_MS);
|
|
175
|
+
}
|
|
176
|
+
heldLocks.add(lockPath);
|
|
177
|
+
try {
|
|
178
|
+
return fn();
|
|
179
|
+
} finally {
|
|
180
|
+
heldLocks.delete(lockPath);
|
|
181
|
+
release(lockPath, token);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
//#endregion
|
|
49
185
|
//#region src/config/strict.ts
|
|
50
186
|
/**
|
|
51
187
|
* Whether this process runs under a host that supplies the base URL and
|
|
@@ -140,9 +276,11 @@ function withDurableWorkspaceAliases(config) {
|
|
|
140
276
|
} : config;
|
|
141
277
|
}
|
|
142
278
|
function updateConfig(updater) {
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
279
|
+
return withConfigLock(() => {
|
|
280
|
+
const updated = updater(readStoredConfig());
|
|
281
|
+
writeConfig(updated);
|
|
282
|
+
return updated;
|
|
283
|
+
});
|
|
146
284
|
}
|
|
147
285
|
//#endregion
|
|
148
286
|
//#region ../../platform/api-client-core/src/api-error-shape.ts
|
|
@@ -257,6 +395,20 @@ var ApiError = class ApiError extends Error {
|
|
|
257
395
|
};
|
|
258
396
|
}
|
|
259
397
|
};
|
|
398
|
+
function getBearer(headers) {
|
|
399
|
+
if (!headers) return null;
|
|
400
|
+
let value = null;
|
|
401
|
+
if (headers instanceof Headers) value = headers.get("authorization");
|
|
402
|
+
else {
|
|
403
|
+
const matches = (Array.isArray(headers) ? headers : Object.entries(headers)).filter(([name]) => name.toLowerCase() === "authorization");
|
|
404
|
+
if (matches.length > 1) return null;
|
|
405
|
+
value = matches[0]?.[1] ?? null;
|
|
406
|
+
}
|
|
407
|
+
if (value === null) return null;
|
|
408
|
+
const normalised = value.trim();
|
|
409
|
+
if (normalised.includes(",")) return null;
|
|
410
|
+
return /^Bearer\s+(.+)$/i.exec(normalised)?.[1]?.trim() ?? null;
|
|
411
|
+
}
|
|
260
412
|
function getStringRequestId(value) {
|
|
261
413
|
if (typeof value !== "string") return;
|
|
262
414
|
const trimmed = value.trim();
|
|
@@ -277,6 +429,10 @@ function getRequestIdFromJsonBody(body) {
|
|
|
277
429
|
function isApiError(error) {
|
|
278
430
|
return error instanceof ApiError;
|
|
279
431
|
}
|
|
432
|
+
/** A request that failed before a full response arrived: status 0. */
|
|
433
|
+
function networkApiError(error, requestId) {
|
|
434
|
+
return new ApiError(`Network error: ${error instanceof Error ? error.message : "Unknown network error"}`, 0, null, requestId);
|
|
435
|
+
}
|
|
280
436
|
/**
|
|
281
437
|
* Creates a configured fetch client instance
|
|
282
438
|
*/
|
|
@@ -296,7 +452,10 @@ function createFetchClient(config) {
|
|
|
296
452
|
};
|
|
297
453
|
if (getAuthToken) {
|
|
298
454
|
const token = await getAuthToken();
|
|
299
|
-
if (token)
|
|
455
|
+
if (token) {
|
|
456
|
+
for (const key of Object.keys(headers)) if (key.toLowerCase() === "authorization") delete headers[key];
|
|
457
|
+
headers.Authorization = `Bearer ${token}`;
|
|
458
|
+
}
|
|
300
459
|
}
|
|
301
460
|
return headers;
|
|
302
461
|
}
|
|
@@ -335,9 +494,9 @@ function createFetchClient(config) {
|
|
|
335
494
|
* Shared response handler for both JSON and FormData requests.
|
|
336
495
|
* Handles auth errors, non-OK responses, 204 No Content, and JSON parsing.
|
|
337
496
|
*/
|
|
338
|
-
async function handleResponse(response, method, _url) {
|
|
497
|
+
async function handleResponse(response, method, _url, sentBearer, responseType = "json") {
|
|
339
498
|
const headerRequestId = getRequestIdFromHeaders(response.headers);
|
|
340
|
-
if (response.status === 401 && onAuthError) onAuthError();
|
|
499
|
+
if (response.status === 401 && onAuthError) onAuthError(sentBearer);
|
|
341
500
|
if (!response.ok) {
|
|
342
501
|
const errorText = await response.text().catch(() => "");
|
|
343
502
|
if (response.headers.get("content-type")?.includes("application/json")) {
|
|
@@ -357,6 +516,11 @@ function createFetchClient(config) {
|
|
|
357
516
|
})() : void 0) || `${method} request failed with status ${response.status}`, response.status, body ? toApiErrorData(body) : parsed, headerRequestId ?? getRequestIdFromJsonBody(parsed), body);
|
|
358
517
|
} else throw new ApiError(`${method} request failed with status ${response.status}`, response.status, null, headerRequestId);
|
|
359
518
|
}
|
|
519
|
+
if (responseType === "text") try {
|
|
520
|
+
return await response.text();
|
|
521
|
+
} catch (readError) {
|
|
522
|
+
throw networkApiError(readError, headerRequestId);
|
|
523
|
+
}
|
|
360
524
|
if (response.status === 204 || response.headers.get("content-length") === "0") return null;
|
|
361
525
|
if (response.headers.get("content-type")?.includes("application/json")) {
|
|
362
526
|
const responseText = await response.text();
|
|
@@ -380,7 +544,11 @@ function createFetchClient(config) {
|
|
|
380
544
|
async function fetchWithNetworkRetry(url, fetchOptions, signal) {
|
|
381
545
|
let retryCount = 0;
|
|
382
546
|
while (true) try {
|
|
383
|
-
|
|
547
|
+
const sentBearer = getBearer(fetchOptions.headers);
|
|
548
|
+
return {
|
|
549
|
+
response: await fetch(url, fetchOptions),
|
|
550
|
+
sentBearer
|
|
551
|
+
};
|
|
384
552
|
} catch (networkError) {
|
|
385
553
|
if (signal?.aborted || retryCount >= maxNetworkRetries) throw networkError;
|
|
386
554
|
retryCount += 1;
|
|
@@ -392,10 +560,11 @@ function createFetchClient(config) {
|
|
|
392
560
|
* Main request function
|
|
393
561
|
*/
|
|
394
562
|
async function request(endpoint, options = {}) {
|
|
395
|
-
const { method = "GET", headers: customHeaders, params, body, signal, priority } = options;
|
|
563
|
+
const { method = "GET", headers: customHeaders, params, body, signal, priority, responseType } = options;
|
|
396
564
|
const url = params ? buildUrl(endpoint, params) : joinUrl(endpoint);
|
|
397
565
|
const headers = await buildHeaders(customHeaders);
|
|
398
566
|
let response;
|
|
567
|
+
let sentBearer;
|
|
399
568
|
try {
|
|
400
569
|
const fetchOptions = {
|
|
401
570
|
method,
|
|
@@ -407,11 +576,11 @@ function createFetchClient(config) {
|
|
|
407
576
|
const serializedBody = body && method !== "GET" ? JSON.stringify(body) : null;
|
|
408
577
|
if (serializedBody) fetchOptions.body = serializedBody;
|
|
409
578
|
if (signal) fetchOptions.signal = signal;
|
|
410
|
-
response = await fetchWithNetworkRetry(url, fetchOptions, signal);
|
|
579
|
+
({response, sentBearer} = await fetchWithNetworkRetry(url, fetchOptions, signal));
|
|
411
580
|
} catch (networkError) {
|
|
412
|
-
throw
|
|
581
|
+
throw networkApiError(networkError);
|
|
413
582
|
}
|
|
414
|
-
return handleResponse(response, method, url);
|
|
583
|
+
return handleResponse(response, method, url, sentBearer, responseType);
|
|
415
584
|
}
|
|
416
585
|
/**
|
|
417
586
|
* Request with FormData (for file uploads)
|
|
@@ -422,6 +591,7 @@ function createFetchClient(config) {
|
|
|
422
591
|
const headers = await buildHeaders(customHeaders);
|
|
423
592
|
delete headers["Content-Type"];
|
|
424
593
|
let response;
|
|
594
|
+
let sentBearer;
|
|
425
595
|
try {
|
|
426
596
|
const fetchOptions = {
|
|
427
597
|
method,
|
|
@@ -432,11 +602,11 @@ function createFetchClient(config) {
|
|
|
432
602
|
if (cache) fetchOptions.cache = cache;
|
|
433
603
|
if (priority) fetchOptions.priority = priority;
|
|
434
604
|
if (signal) fetchOptions.signal = signal;
|
|
435
|
-
response = await fetchWithNetworkRetry(url, fetchOptions, signal);
|
|
605
|
+
({response, sentBearer} = await fetchWithNetworkRetry(url, fetchOptions, signal));
|
|
436
606
|
} catch (networkError) {
|
|
437
|
-
throw
|
|
607
|
+
throw networkApiError(networkError);
|
|
438
608
|
}
|
|
439
|
-
return handleResponse(response, method, url);
|
|
609
|
+
return handleResponse(response, method, url, sentBearer);
|
|
440
610
|
}
|
|
441
611
|
return {
|
|
442
612
|
request,
|
|
@@ -496,7 +666,7 @@ function createHeyApiErrorInterceptor(options = {}) {
|
|
|
496
666
|
return new ApiError(`Network error: ${error instanceof Error ? error.message : "Unknown network error"}`, 0, null);
|
|
497
667
|
}
|
|
498
668
|
if (response.ok && error instanceof SyntaxError) return new ApiError("Failed to parse response as JSON", response.status, null, getRequestId(response, null));
|
|
499
|
-
options.onResponseError?.(response);
|
|
669
|
+
options.onResponseError?.(response, request);
|
|
500
670
|
const method = request?.method ?? requestOptions.method ?? "GET";
|
|
501
671
|
const errorRecord = toApiErrorBody(error);
|
|
502
672
|
const requestId = getRequestId(response, errorRecord);
|
|
@@ -1852,6 +2022,8 @@ function createNativeSession(config) {
|
|
|
1852
2022
|
};
|
|
1853
2023
|
const listeners = /* @__PURE__ */ new Set();
|
|
1854
2024
|
let generation = 0;
|
|
2025
|
+
let restoring = 0;
|
|
2026
|
+
const adoptRedemptions = /* @__PURE__ */ new Map();
|
|
1855
2027
|
let redeemed = 0;
|
|
1856
2028
|
let sendSeq = 0;
|
|
1857
2029
|
let redeemedSeq = 0;
|
|
@@ -2265,6 +2437,140 @@ function createNativeSession(config) {
|
|
|
2265
2437
|
}
|
|
2266
2438
|
throw new SessionError("temporarily_unavailable", "The session moved company while a token was being issued; retry.");
|
|
2267
2439
|
}
|
|
2440
|
+
/**
|
|
2441
|
+
* Redeems a grant at `/token` for a new chain and adopts it: the one path
|
|
2442
|
+
* a sign-in code and an adopt code both take.
|
|
2443
|
+
*/
|
|
2444
|
+
class UnconfirmedAdopt extends Error {
|
|
2445
|
+
constructor(cap, error) {
|
|
2446
|
+
super(error.message);
|
|
2447
|
+
this.cap = cap;
|
|
2448
|
+
this.error = error;
|
|
2449
|
+
}
|
|
2450
|
+
}
|
|
2451
|
+
async function redeemGrant(grant, discardUnconfirmed = false) {
|
|
2452
|
+
let answered = () => {};
|
|
2453
|
+
const redemption = new Promise((resolve) => {
|
|
2454
|
+
answered = resolve;
|
|
2455
|
+
});
|
|
2456
|
+
const started = generation;
|
|
2457
|
+
if (!discardUnconfirmed) for (const cancelAdopt of adoptRedemptions.values()) cancelAdopt();
|
|
2458
|
+
const earlier = [...redemptions].filter((e) => !adoptRedemptions.has(e));
|
|
2459
|
+
redemptions.add(redemption);
|
|
2460
|
+
let cancelled = false;
|
|
2461
|
+
let cancel = () => {};
|
|
2462
|
+
if (discardUnconfirmed) adoptRedemptions.set(redemption, () => {
|
|
2463
|
+
cancelled = true;
|
|
2464
|
+
cancel();
|
|
2465
|
+
});
|
|
2466
|
+
let sent;
|
|
2467
|
+
let sequence;
|
|
2468
|
+
let token;
|
|
2469
|
+
try {
|
|
2470
|
+
if (earlier.length > 0) {
|
|
2471
|
+
let timer;
|
|
2472
|
+
const bound = new Promise((resolve) => {
|
|
2473
|
+
timer = setTimeout(() => resolve("expired"), REDEMPTION_WAIT_MS);
|
|
2474
|
+
});
|
|
2475
|
+
const waited = await Promise.race([Promise.all(earlier), bound]);
|
|
2476
|
+
clearTimeout(timer);
|
|
2477
|
+
if (waited === "expired" && earlier.some((e) => redemptions.has(e))) throw new SessionError("temporarily_unavailable", "An earlier sign-in is still being redeemed; retry.");
|
|
2478
|
+
}
|
|
2479
|
+
if (started !== generation || signOutsRunning > 0) throw new SessionError("not_signed_in");
|
|
2480
|
+
if (cancelled) throw new SessionError("temporarily_unavailable");
|
|
2481
|
+
sent = capture();
|
|
2482
|
+
sequence = sendSeq += 1;
|
|
2483
|
+
const abort = new AbortController();
|
|
2484
|
+
const abandoned = new SessionError("temporarily_unavailable", "The identity service did not answer the sign-in in time.");
|
|
2485
|
+
let deadline;
|
|
2486
|
+
const lapsed = new Promise((_, reject) => {
|
|
2487
|
+
cancel = () => {
|
|
2488
|
+
abort.abort();
|
|
2489
|
+
reject(abandoned);
|
|
2490
|
+
};
|
|
2491
|
+
deadline = setTimeout(cancel, REDEMPTION_DEADLINE_MS);
|
|
2492
|
+
});
|
|
2493
|
+
const sending = createToken({
|
|
2494
|
+
client,
|
|
2495
|
+
signal: abort.signal,
|
|
2496
|
+
body: grant
|
|
2497
|
+
});
|
|
2498
|
+
sending.catch(() => void 0);
|
|
2499
|
+
try {
|
|
2500
|
+
token = await Promise.race([sending, lapsed]);
|
|
2501
|
+
} catch (redeemError) {
|
|
2502
|
+
if (redeemError === abandoned) throw abandoned;
|
|
2503
|
+
throw classifyRefreshFailure(redeemError) === "unavailable" ? new SessionError("temporarily_unavailable") : new SessionError("redemption_failed", "The code was not redeemed.");
|
|
2504
|
+
} finally {
|
|
2505
|
+
clearTimeout(deadline);
|
|
2506
|
+
}
|
|
2507
|
+
} finally {
|
|
2508
|
+
adoptRedemptions.delete(redemption);
|
|
2509
|
+
redemptions.delete(redemption);
|
|
2510
|
+
answered();
|
|
2511
|
+
}
|
|
2512
|
+
const refreshToken = token.refresh_token;
|
|
2513
|
+
if (!refreshToken) throw new SessionError("redemption_failed", "The identity service issued no refresh token to a native client.");
|
|
2514
|
+
if (redeemedSeq > sequence) throw new SessionError("not_signed_in");
|
|
2515
|
+
if (sent.out !== generation) {
|
|
2516
|
+
if (sent.red === redeemed) await revokeQuietly(refreshToken);
|
|
2517
|
+
throw new SessionError("not_signed_in");
|
|
2518
|
+
}
|
|
2519
|
+
redeemed += 1;
|
|
2520
|
+
redeemedSeq = sequence;
|
|
2521
|
+
const cap = capture();
|
|
2522
|
+
tracker.signingIn();
|
|
2523
|
+
target = null;
|
|
2524
|
+
pickedOrg = null;
|
|
2525
|
+
held = null;
|
|
2526
|
+
chain = null;
|
|
2527
|
+
let confirmed = () => {};
|
|
2528
|
+
latestRedemption = {
|
|
2529
|
+
red: redeemed,
|
|
2530
|
+
confirmation: new Promise((resolve) => {
|
|
2531
|
+
confirmed = resolve;
|
|
2532
|
+
})
|
|
2533
|
+
};
|
|
2534
|
+
const announced = announceLatest;
|
|
2535
|
+
latestChanged = new Promise((resolve) => {
|
|
2536
|
+
announceLatest = resolve;
|
|
2537
|
+
});
|
|
2538
|
+
announced();
|
|
2539
|
+
let landed = false;
|
|
2540
|
+
try {
|
|
2541
|
+
const facts = await adopt(token, cap);
|
|
2542
|
+
commit(cap, () => {
|
|
2543
|
+
pickedOrg = token.picked_org ?? null;
|
|
2544
|
+
});
|
|
2545
|
+
landed = isCurrent(cap) && current() !== null;
|
|
2546
|
+
return {
|
|
2547
|
+
facts,
|
|
2548
|
+
cap
|
|
2549
|
+
};
|
|
2550
|
+
} catch (adoptError) {
|
|
2551
|
+
if (adoptError instanceof SessionError) throw adoptError;
|
|
2552
|
+
const settled = await settleUnfinishedSignIn(refreshToken, cap, adoptError);
|
|
2553
|
+
if (discardUnconfirmed && settled.code === "temporarily_unavailable") throw new UnconfirmedAdopt(cap, settled);
|
|
2554
|
+
throw settled;
|
|
2555
|
+
} finally {
|
|
2556
|
+
confirmed(landed);
|
|
2557
|
+
}
|
|
2558
|
+
}
|
|
2559
|
+
/**
|
|
2560
|
+
* Signs out only while `cap`'s redemption is still the session's, and never
|
|
2561
|
+
* waits: false, touching nothing, once it was superseded. While another
|
|
2562
|
+
* redemption is in flight it also answers false, since that one may replace
|
|
2563
|
+
* the session; if the in-flight one then fails and `cap` is still current,
|
|
2564
|
+
* the cleanup runs once it settles, so a rejected adoption cannot linger.
|
|
2565
|
+
*/
|
|
2566
|
+
function signOutIfCurrent(cap) {
|
|
2567
|
+
if (!isCurrent(cap)) return Promise.resolve(false);
|
|
2568
|
+
if (redemptions.size > 0) {
|
|
2569
|
+
Promise.allSettled([...redemptions]).then(() => isCurrent(cap) && redemptions.size === 0 ? session.signOut() : void 0).catch(() => void 0);
|
|
2570
|
+
return Promise.resolve(false);
|
|
2571
|
+
}
|
|
2572
|
+
return session.signOut().then(() => true);
|
|
2573
|
+
}
|
|
2268
2574
|
const session = {
|
|
2269
2575
|
async restore(options) {
|
|
2270
2576
|
if (options && "org" in options) {
|
|
@@ -2275,12 +2581,15 @@ function createNativeSession(config) {
|
|
|
2275
2581
|
}
|
|
2276
2582
|
}
|
|
2277
2583
|
if (current()) return snapshot.facts;
|
|
2584
|
+
restoring += 1;
|
|
2278
2585
|
try {
|
|
2279
2586
|
await freshToken();
|
|
2280
2587
|
return snapshot.facts;
|
|
2281
2588
|
} catch (error) {
|
|
2282
2589
|
if (error instanceof SessionError && (error.code === "not_signed_in" || error.code === "session_expired")) return null;
|
|
2283
2590
|
throw error;
|
|
2591
|
+
} finally {
|
|
2592
|
+
restoring -= 1;
|
|
2284
2593
|
}
|
|
2285
2594
|
},
|
|
2286
2595
|
async beginSignIn(options) {
|
|
@@ -2324,104 +2633,38 @@ function createNativeSession(config) {
|
|
|
2324
2633
|
if (error) throw new SessionError(error === "access_denied" || error === "login_required" || error === "account_selection_required" || error === "temporarily_unavailable" ? error : "redemption_failed", `The identity service answered ${error}.`);
|
|
2325
2634
|
const code = callback.searchParams.get("code");
|
|
2326
2635
|
if (!code) throw new SessionError("redemption_failed", "The redirect had no code.");
|
|
2327
|
-
|
|
2328
|
-
|
|
2329
|
-
|
|
2636
|
+
const { facts } = await redeemGrant({
|
|
2637
|
+
grant_type: "authorization_code",
|
|
2638
|
+
code,
|
|
2639
|
+
redirect_uri: request.redirectUri,
|
|
2640
|
+
client_id: config.clientId,
|
|
2641
|
+
code_verifier: request.verifier
|
|
2330
2642
|
});
|
|
2331
|
-
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
let
|
|
2643
|
+
return facts;
|
|
2644
|
+
},
|
|
2645
|
+
async redeemAdopt(grant) {
|
|
2646
|
+
const busy = () => signOutsRunning > 0 || redemptions.size > 0 || restoring > 0 || pending !== null || refreshes.size > 0 || snapshot.facts !== null || held !== null || grant.epoch !== void 0 && grant.epoch !== generation;
|
|
2647
|
+
if (busy()) throw new SessionError("not_signed_in");
|
|
2648
|
+
let stored;
|
|
2337
2649
|
try {
|
|
2338
|
-
|
|
2339
|
-
|
|
2340
|
-
|
|
2341
|
-
timer = setTimeout(() => resolve("expired"), REDEMPTION_WAIT_MS);
|
|
2342
|
-
});
|
|
2343
|
-
const waited = await Promise.race([Promise.all(earlier), bound]);
|
|
2344
|
-
clearTimeout(timer);
|
|
2345
|
-
if (waited === "expired" && earlier.some((e) => redemptions.has(e))) throw new SessionError("temporarily_unavailable", "An earlier sign-in is still being redeemed; retry.");
|
|
2346
|
-
}
|
|
2347
|
-
if (started !== generation || signOutsRunning > 0) throw new SessionError("not_signed_in");
|
|
2348
|
-
sent = capture();
|
|
2349
|
-
sequence = sendSeq += 1;
|
|
2350
|
-
const abort = new AbortController();
|
|
2351
|
-
const abandoned = new SessionError("temporarily_unavailable", "The identity service did not answer the sign-in in time.");
|
|
2352
|
-
let deadline;
|
|
2353
|
-
const lapsed = new Promise((_, reject) => {
|
|
2354
|
-
deadline = setTimeout(() => {
|
|
2355
|
-
abort.abort();
|
|
2356
|
-
reject(abandoned);
|
|
2357
|
-
}, REDEMPTION_DEADLINE_MS);
|
|
2358
|
-
});
|
|
2359
|
-
const sending = createToken({
|
|
2360
|
-
client,
|
|
2361
|
-
signal: abort.signal,
|
|
2362
|
-
body: {
|
|
2363
|
-
grant_type: "authorization_code",
|
|
2364
|
-
code,
|
|
2365
|
-
redirect_uri: request.redirectUri,
|
|
2366
|
-
client_id: config.clientId,
|
|
2367
|
-
code_verifier: request.verifier
|
|
2368
|
-
}
|
|
2369
|
-
});
|
|
2370
|
-
sending.catch(() => void 0);
|
|
2371
|
-
try {
|
|
2372
|
-
token = await Promise.race([sending, lapsed]);
|
|
2373
|
-
} catch (redeemError) {
|
|
2374
|
-
if (redeemError === abandoned) throw abandoned;
|
|
2375
|
-
throw classifyRefreshFailure(redeemError) === "unavailable" ? new SessionError("temporarily_unavailable") : new SessionError("redemption_failed", "The code was not redeemed.");
|
|
2376
|
-
} finally {
|
|
2377
|
-
clearTimeout(deadline);
|
|
2378
|
-
}
|
|
2379
|
-
} finally {
|
|
2380
|
-
redemptions.delete(redemption);
|
|
2381
|
-
answered();
|
|
2382
|
-
}
|
|
2383
|
-
const refreshToken = token.refresh_token;
|
|
2384
|
-
if (!refreshToken) throw new SessionError("redemption_failed", "The identity service issued no refresh token to a native client.");
|
|
2385
|
-
if (redeemedSeq > sequence) throw new SessionError("not_signed_in");
|
|
2386
|
-
if (sent.out !== generation) {
|
|
2387
|
-
if (sent.red === redeemed) await revokeQuietly(refreshToken);
|
|
2388
|
-
throw new SessionError("not_signed_in");
|
|
2650
|
+
stored = await store.get();
|
|
2651
|
+
} catch {
|
|
2652
|
+
throw new SessionError("temporarily_unavailable");
|
|
2389
2653
|
}
|
|
2390
|
-
|
|
2391
|
-
|
|
2392
|
-
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
|
|
2398
|
-
|
|
2399
|
-
|
|
2400
|
-
|
|
2401
|
-
confirmation: new Promise((resolve) => {
|
|
2402
|
-
confirmed = resolve;
|
|
2403
|
-
})
|
|
2654
|
+
if (stored !== null || busy()) throw new SessionError("not_signed_in");
|
|
2655
|
+
const { facts, cap } = await redeemGrant({
|
|
2656
|
+
grant_type: "urn:fluid:params:oauth:grant-type:adopt",
|
|
2657
|
+
adopt_code: grant.adoptCode,
|
|
2658
|
+
code_verifier: grant.codeVerifier,
|
|
2659
|
+
client_id: config.clientId
|
|
2660
|
+
}, true);
|
|
2661
|
+
return {
|
|
2662
|
+
facts,
|
|
2663
|
+
isCurrent: () => isCurrent(cap),
|
|
2664
|
+
discard: () => signOutIfCurrent(cap)
|
|
2404
2665
|
};
|
|
2405
|
-
const announced = announceLatest;
|
|
2406
|
-
latestChanged = new Promise((resolve) => {
|
|
2407
|
-
announceLatest = resolve;
|
|
2408
|
-
});
|
|
2409
|
-
announced();
|
|
2410
|
-
let landed = false;
|
|
2411
|
-
try {
|
|
2412
|
-
const facts = await adopt(token, cap);
|
|
2413
|
-
commit(cap, () => {
|
|
2414
|
-
pickedOrg = token.picked_org ?? null;
|
|
2415
|
-
});
|
|
2416
|
-
landed = isCurrent(cap) && current() !== null;
|
|
2417
|
-
return facts;
|
|
2418
|
-
} catch (adoptError) {
|
|
2419
|
-
if (adoptError instanceof SessionError) throw adoptError;
|
|
2420
|
-
throw await settleUnfinishedSignIn(refreshToken, cap, adoptError);
|
|
2421
|
-
} finally {
|
|
2422
|
-
confirmed(landed);
|
|
2423
|
-
}
|
|
2424
2666
|
},
|
|
2667
|
+
epoch: () => generation,
|
|
2425
2668
|
async getAccessToken(options) {
|
|
2426
2669
|
const fresh = current();
|
|
2427
2670
|
if (fresh && fresh.accessToken !== options?.replacing) return fresh.accessToken;
|
|
@@ -2550,6 +2793,16 @@ function createNativeSession(config) {
|
|
|
2550
2793
|
};
|
|
2551
2794
|
}
|
|
2552
2795
|
};
|
|
2796
|
+
const redeemAdopt = session.redeemAdopt;
|
|
2797
|
+
session.redeemAdopt = async (grant) => {
|
|
2798
|
+
try {
|
|
2799
|
+
return await tracked(redeemAdopt(grant));
|
|
2800
|
+
} catch (error) {
|
|
2801
|
+
if (!(error instanceof UnconfirmedAdopt)) throw error;
|
|
2802
|
+
await signOutIfCurrent(error.cap).catch(() => void 0);
|
|
2803
|
+
throw error.error;
|
|
2804
|
+
}
|
|
2805
|
+
};
|
|
2553
2806
|
const completeSignIn = session.completeSignIn;
|
|
2554
2807
|
session.completeSignIn = (callbackUrl) => tracked(completeSignIn(callbackUrl));
|
|
2555
2808
|
return session;
|
|
@@ -2588,134 +2841,196 @@ function createKeyringSecureStorage(options) {
|
|
|
2588
2841
|
}
|
|
2589
2842
|
};
|
|
2590
2843
|
}
|
|
2844
|
+
/** Keeps values in this process's memory only; nothing survives a restart. */
|
|
2845
|
+
function createMemorySecureStorage() {
|
|
2846
|
+
const entries = /* @__PURE__ */ new Map();
|
|
2847
|
+
return {
|
|
2848
|
+
entries,
|
|
2849
|
+
async get(key) {
|
|
2850
|
+
return entries.get(key) ?? null;
|
|
2851
|
+
},
|
|
2852
|
+
async set(key, value) {
|
|
2853
|
+
entries.set(key, value);
|
|
2854
|
+
},
|
|
2855
|
+
async delete(key) {
|
|
2856
|
+
entries.delete(key);
|
|
2857
|
+
}
|
|
2858
|
+
};
|
|
2859
|
+
}
|
|
2591
2860
|
//#endregion
|
|
2592
|
-
//#region src/
|
|
2593
|
-
/**
|
|
2594
|
-
|
|
2595
|
-
|
|
2596
|
-
|
|
2597
|
-
|
|
2598
|
-
|
|
2599
|
-
|
|
2600
|
-
|
|
2601
|
-
|
|
2602
|
-
|
|
2603
|
-
|
|
2604
|
-
|
|
2605
|
-
|
|
2606
|
-
|
|
2607
|
-
|
|
2608
|
-
function
|
|
2609
|
-
|
|
2861
|
+
//#region ../../platform/auth/src/native/trade-legacy-token.ts
|
|
2862
|
+
/**
|
|
2863
|
+
* Trades a legacy Fluid token for a native identity session with no browser
|
|
2864
|
+
* hop (RFC 004 S3.4g): Rails mints a PKCE-bound adopt code for the legacy
|
|
2865
|
+
* bearer, and the session redeems it at the identity service's `/token`.
|
|
2866
|
+
* The legacy token is never altered here; the caller removes it only after
|
|
2867
|
+
* an `adopted` result.
|
|
2868
|
+
*/
|
|
2869
|
+
const REQUEST_TIMEOUT_MS = 15e3;
|
|
2870
|
+
function record(value) {
|
|
2871
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
2872
|
+
}
|
|
2873
|
+
function idText(value) {
|
|
2874
|
+
if (typeof value === "number" && Number.isFinite(value)) return String(value);
|
|
2875
|
+
return typeof value === "string" && value.trim() ? value.trim() : null;
|
|
2876
|
+
}
|
|
2877
|
+
function meIdentityOf(raw) {
|
|
2878
|
+
const root = record(raw);
|
|
2879
|
+
if (!root) return null;
|
|
2880
|
+
const wrapped = record(root["me"]) ?? record(root["user"]);
|
|
2881
|
+
const user = record(wrapped?.["user"]) ?? wrapped ?? root;
|
|
2882
|
+
const company = record(wrapped?.["company"]) ?? record(root["company"]);
|
|
2883
|
+
const userId = idText(user["id"]);
|
|
2884
|
+
const companyId = company ? idText(company["id"]) : null;
|
|
2885
|
+
return userId && companyId ? {
|
|
2886
|
+
userId,
|
|
2887
|
+
companyId
|
|
2888
|
+
} : null;
|
|
2610
2889
|
}
|
|
2611
|
-
function
|
|
2890
|
+
async function readMe(doFetch, apiBase, token, timeoutMs) {
|
|
2891
|
+
let response;
|
|
2892
|
+
const abort = new AbortController();
|
|
2893
|
+
const timer = setTimeout(() => abort.abort(), timeoutMs);
|
|
2612
2894
|
try {
|
|
2613
|
-
|
|
2895
|
+
response = await doFetch(`${apiBase}/api/me`, {
|
|
2896
|
+
headers: {
|
|
2897
|
+
Authorization: `Bearer ${token}`,
|
|
2898
|
+
Accept: "application/json"
|
|
2899
|
+
},
|
|
2900
|
+
signal: abort.signal
|
|
2901
|
+
});
|
|
2614
2902
|
} catch {
|
|
2615
|
-
|
|
2903
|
+
clearTimeout(timer);
|
|
2904
|
+
return { kind: "unavailable" };
|
|
2616
2905
|
}
|
|
2617
|
-
|
|
2618
|
-
|
|
2619
|
-
|
|
2620
|
-
}
|
|
2621
|
-
function holderAlive(content) {
|
|
2622
|
-
const pid = Number(/:(\d+)$/.exec(content)?.[1]);
|
|
2623
|
-
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
2624
|
-
try {
|
|
2625
|
-
process.kill(pid, 0);
|
|
2626
|
-
return true;
|
|
2627
|
-
} catch (error) {
|
|
2628
|
-
return error.code === "EPERM";
|
|
2906
|
+
if (response.status >= 500 || response.status === 429) {
|
|
2907
|
+
clearTimeout(timer);
|
|
2908
|
+
return { kind: "unavailable" };
|
|
2629
2909
|
}
|
|
2630
|
-
|
|
2631
|
-
|
|
2632
|
-
|
|
2633
|
-
}
|
|
2634
|
-
function isLockStale(path) {
|
|
2635
|
-
if (ageMs(path) <= configLockTimings.staleMs) return false;
|
|
2636
|
-
try {
|
|
2637
|
-
const content = readFileSync(path, "utf8");
|
|
2638
|
-
return !hasHolderPid(content) || !holderAlive(content);
|
|
2639
|
-
} catch {
|
|
2640
|
-
return false;
|
|
2910
|
+
if (!response.ok) {
|
|
2911
|
+
clearTimeout(timer);
|
|
2912
|
+
return { kind: "refused" };
|
|
2641
2913
|
}
|
|
2642
|
-
}
|
|
2643
|
-
function tryCreate(path, content) {
|
|
2644
|
-
const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
2645
2914
|
try {
|
|
2646
|
-
const
|
|
2647
|
-
|
|
2648
|
-
|
|
2649
|
-
|
|
2650
|
-
|
|
2651
|
-
|
|
2652
|
-
|
|
2653
|
-
linkSync(tmp, path);
|
|
2654
|
-
return true;
|
|
2655
|
-
} catch {
|
|
2656
|
-
return false;
|
|
2657
|
-
}
|
|
2915
|
+
const me = meIdentityOf(await response.json());
|
|
2916
|
+
return me ? {
|
|
2917
|
+
kind: "ok",
|
|
2918
|
+
me
|
|
2919
|
+
} : { kind: "refused" };
|
|
2920
|
+
} catch {
|
|
2921
|
+
return abort.signal.aborted ? { kind: "unavailable" } : { kind: "refused" };
|
|
2658
2922
|
} finally {
|
|
2659
|
-
|
|
2660
|
-
unlinkSync(tmp);
|
|
2661
|
-
} catch {}
|
|
2923
|
+
clearTimeout(timer);
|
|
2662
2924
|
}
|
|
2663
2925
|
}
|
|
2664
|
-
function
|
|
2665
|
-
|
|
2666
|
-
|
|
2667
|
-
|
|
2926
|
+
async function mintAdoptCode(doFetch, apiBase, legacyToken, challenge, timeoutMs) {
|
|
2927
|
+
let response;
|
|
2928
|
+
const abort = new AbortController();
|
|
2929
|
+
const timer = setTimeout(() => abort.abort(), timeoutMs);
|
|
2668
2930
|
try {
|
|
2669
|
-
|
|
2670
|
-
|
|
2671
|
-
|
|
2672
|
-
|
|
2673
|
-
|
|
2674
|
-
|
|
2675
|
-
|
|
2676
|
-
|
|
2677
|
-
|
|
2678
|
-
|
|
2679
|
-
|
|
2931
|
+
response = await doFetch(`${apiBase}/api/identity/adopt_code`, {
|
|
2932
|
+
method: "POST",
|
|
2933
|
+
headers: {
|
|
2934
|
+
Authorization: `Bearer ${legacyToken}`,
|
|
2935
|
+
"Content-Type": "application/json",
|
|
2936
|
+
Accept: "application/json"
|
|
2937
|
+
},
|
|
2938
|
+
body: JSON.stringify({
|
|
2939
|
+
code_challenge: challenge,
|
|
2940
|
+
code_challenge_method: "S256"
|
|
2941
|
+
}),
|
|
2942
|
+
signal: abort.signal
|
|
2943
|
+
});
|
|
2944
|
+
} catch {
|
|
2945
|
+
clearTimeout(timer);
|
|
2946
|
+
return { kind: "unavailable" };
|
|
2947
|
+
}
|
|
2948
|
+
if (response.status === 404) {
|
|
2949
|
+
clearTimeout(timer);
|
|
2950
|
+
return { kind: "not_targeted" };
|
|
2951
|
+
}
|
|
2952
|
+
if (response.status >= 500 || response.status === 429) {
|
|
2953
|
+
clearTimeout(timer);
|
|
2954
|
+
return { kind: "unavailable" };
|
|
2955
|
+
}
|
|
2956
|
+
if (!response.ok) {
|
|
2957
|
+
clearTimeout(timer);
|
|
2958
|
+
return { kind: "refused" };
|
|
2680
2959
|
}
|
|
2681
2960
|
try {
|
|
2682
|
-
|
|
2683
|
-
|
|
2684
|
-
|
|
2961
|
+
const code = record(await response.json())?.["code"];
|
|
2962
|
+
return typeof code === "string" && code ? {
|
|
2963
|
+
kind: "ok",
|
|
2964
|
+
code
|
|
2965
|
+
} : { kind: "refused" };
|
|
2966
|
+
} catch {
|
|
2967
|
+
return abort.signal.aborted ? { kind: "unavailable" } : { kind: "refused" };
|
|
2685
2968
|
} finally {
|
|
2686
|
-
|
|
2969
|
+
clearTimeout(timer);
|
|
2687
2970
|
}
|
|
2688
2971
|
}
|
|
2689
2972
|
/**
|
|
2690
|
-
*
|
|
2691
|
-
* concurrent no-replace profile saves cannot both succeed (other
|
|
2692
|
-
* `updateConfig` callers do not take this lock). A lock
|
|
2693
|
-
* older than the stale timeout is treated as abandoned, and removed under a
|
|
2694
|
-
* second short-lived lock so only one contender breaks it, only when its
|
|
2695
|
-
* holder process is gone or it records no holder.
|
|
2973
|
+
* Trades `legacyToken` for an identity session held by `session`.
|
|
2696
2974
|
*
|
|
2697
|
-
*
|
|
2698
|
-
*
|
|
2699
|
-
*
|
|
2975
|
+
* Returns `adopted` once the session is stored and its user and company match
|
|
2976
|
+
* the legacy token's, as `/api/me` answers for each. A session that lands on
|
|
2977
|
+
* another user or company is signed out again and the trade is `refused`.
|
|
2978
|
+
* `not_targeted` means Rails does not offer adoption to this company;
|
|
2979
|
+
* `unavailable` means a network or server failure worth retrying later.
|
|
2700
2980
|
*/
|
|
2701
|
-
function
|
|
2702
|
-
const
|
|
2703
|
-
|
|
2704
|
-
|
|
2705
|
-
|
|
2981
|
+
async function tradeLegacyToken(options) {
|
|
2982
|
+
const doFetch = options.fetch ?? ((...args) => fetch(...args));
|
|
2983
|
+
const finish = (result) => {
|
|
2984
|
+
options.log?.(result.outcome === "refused" ? `adopt outcome: refused (${result.reason})` : `adopt outcome: ${result.outcome}`);
|
|
2985
|
+
return result;
|
|
2986
|
+
};
|
|
2987
|
+
if (options.session.facts() !== null) return finish({ outcome: "unavailable" });
|
|
2988
|
+
const timeoutMs = options.requestTimeoutMs ?? REQUEST_TIMEOUT_MS;
|
|
2989
|
+
const epoch = options.session.epoch();
|
|
2990
|
+
const verifier = createCodeVerifier(options.crypto);
|
|
2991
|
+
const challenge = await createCodeChallenge(verifier, options.crypto);
|
|
2992
|
+
const minted = await mintAdoptCode(doFetch, options.apiBase, options.legacyToken, challenge, timeoutMs);
|
|
2993
|
+
if (minted.kind === "not_targeted") return finish({ outcome: "not_targeted" });
|
|
2994
|
+
if (minted.kind === "unavailable") return finish({ outcome: "unavailable" });
|
|
2995
|
+
if (minted.kind === "refused") return finish({
|
|
2996
|
+
outcome: "refused",
|
|
2997
|
+
reason: "mint_refused"
|
|
2706
2998
|
});
|
|
2707
|
-
|
|
2708
|
-
const deadline = Date.now() + configLockTimings.timeoutMs;
|
|
2709
|
-
while (!tryCreate(lockPath, token)) {
|
|
2710
|
-
if (isLockStale(lockPath)) breakStale(lockPath);
|
|
2711
|
-
if (Date.now() >= deadline) throw new ConfigLockTimeoutError(lockPath);
|
|
2712
|
-
sleep(RETRY_MS);
|
|
2713
|
-
}
|
|
2999
|
+
let adoptedSession;
|
|
2714
3000
|
try {
|
|
2715
|
-
|
|
2716
|
-
|
|
2717
|
-
|
|
3001
|
+
adoptedSession = await options.session.redeemAdopt({
|
|
3002
|
+
adoptCode: minted.code,
|
|
3003
|
+
codeVerifier: verifier,
|
|
3004
|
+
epoch
|
|
3005
|
+
});
|
|
3006
|
+
} catch (error) {
|
|
3007
|
+
if (error instanceof SessionError && error.code !== "temporarily_unavailable" && error.code !== "not_signed_in") return finish({
|
|
3008
|
+
outcome: "refused",
|
|
3009
|
+
reason: "grant_refused"
|
|
3010
|
+
});
|
|
3011
|
+
return finish({ outcome: "unavailable" });
|
|
2718
3012
|
}
|
|
3013
|
+
const discard = async (result) => {
|
|
3014
|
+
await adoptedSession.discard().catch(() => void 0);
|
|
3015
|
+
return finish(result);
|
|
3016
|
+
};
|
|
3017
|
+
const [legacy, adopted] = await Promise.all([readMe(doFetch, options.apiBase, options.legacyToken, timeoutMs), options.session.getAccessToken().then((token) => readMe(doFetch, options.apiBase, token, timeoutMs)).catch(() => ({ kind: "unavailable" }))]);
|
|
3018
|
+
if (!adoptedSession.isCurrent()) return finish({ outcome: "unavailable" });
|
|
3019
|
+
if (legacy.kind === "unavailable" || adopted.kind === "unavailable") return discard({ outcome: "unavailable" });
|
|
3020
|
+
if (legacy.kind !== "ok" || adopted.kind !== "ok") return discard({
|
|
3021
|
+
outcome: "refused",
|
|
3022
|
+
reason: "landing_unverifiable"
|
|
3023
|
+
});
|
|
3024
|
+
if (legacy.me.userId !== adopted.me.userId || legacy.me.companyId !== adopted.me.companyId) return discard({
|
|
3025
|
+
outcome: "refused",
|
|
3026
|
+
reason: "landing_mismatch"
|
|
3027
|
+
});
|
|
3028
|
+
return finish({
|
|
3029
|
+
outcome: "adopted",
|
|
3030
|
+
facts: adoptedSession.facts,
|
|
3031
|
+
isCurrent: () => adoptedSession.isCurrent(),
|
|
3032
|
+
discard: () => adoptedSession.discard()
|
|
3033
|
+
});
|
|
2719
3034
|
}
|
|
2720
3035
|
//#endregion
|
|
2721
3036
|
//#region src/auth/identity/environment.ts
|
|
@@ -2950,7 +3265,7 @@ async function saveClientProfile(name, input, options = {}) {
|
|
|
2950
3265
|
let before;
|
|
2951
3266
|
let after;
|
|
2952
3267
|
try {
|
|
2953
|
-
|
|
3268
|
+
[before, after] = withConfigLock(() => {
|
|
2954
3269
|
return [readConfig(), updateConfig((config) => {
|
|
2955
3270
|
if (options.replace === false && config.profiles[name]) throw new ProfileExistsError(name);
|
|
2956
3271
|
return {
|
|
@@ -2962,8 +3277,7 @@ async function saveClientProfile(name, input, options = {}) {
|
|
|
2962
3277
|
}
|
|
2963
3278
|
};
|
|
2964
3279
|
})];
|
|
2965
|
-
};
|
|
2966
|
-
[before, after] = options.replace === false ? withConfigLock(write) : write();
|
|
3280
|
+
});
|
|
2967
3281
|
} catch (error) {
|
|
2968
3282
|
try {
|
|
2969
3283
|
await storage.delete(storageKey);
|
|
@@ -3011,6 +3325,159 @@ function openBrowser(url) {
|
|
|
3011
3325
|
execFile(launch.command, launch.args, () => void 0);
|
|
3012
3326
|
} catch {}
|
|
3013
3327
|
}
|
|
3328
|
+
const CHILD_SCRIPT = `
|
|
3329
|
+
const MISSING = /no (matching )?entry|not found/i;
|
|
3330
|
+
let input = "";
|
|
3331
|
+
process.stdin.setEncoding("utf8");
|
|
3332
|
+
process.stdin.on("data", (chunk) => { input += chunk; });
|
|
3333
|
+
process.stdin.on("end", () => {
|
|
3334
|
+
const out = (value) => process.stdout.write(JSON.stringify(value), () => process.exit(0));
|
|
3335
|
+
try {
|
|
3336
|
+
const request = JSON.parse(input);
|
|
3337
|
+
const { Entry } = require(request.module);
|
|
3338
|
+
const entry = request.op === "get"
|
|
3339
|
+
? new Entry(request.service, request.account)
|
|
3340
|
+
: new Entry(request.service, request.account, { linux: { store: "secret-service" } });
|
|
3341
|
+
if (request.op === "set") {
|
|
3342
|
+
entry.setPassword(request.value);
|
|
3343
|
+
out({ ok: true });
|
|
3344
|
+
} else if (request.op === "get") {
|
|
3345
|
+
try {
|
|
3346
|
+
out({ ok: true, value: entry.getPassword() ?? null });
|
|
3347
|
+
} catch (error) {
|
|
3348
|
+
if (!MISSING.test(String(error && error.message))) throw error;
|
|
3349
|
+
out({ ok: true, value: null });
|
|
3350
|
+
}
|
|
3351
|
+
} else {
|
|
3352
|
+
try {
|
|
3353
|
+
entry.deletePassword();
|
|
3354
|
+
} catch (error) {
|
|
3355
|
+
if (!MISSING.test(String(error && error.message))) throw error;
|
|
3356
|
+
}
|
|
3357
|
+
out({ ok: true });
|
|
3358
|
+
}
|
|
3359
|
+
} catch (error) {
|
|
3360
|
+
out({ ok: false });
|
|
3361
|
+
}
|
|
3362
|
+
});
|
|
3363
|
+
`;
|
|
3364
|
+
/** The credential store answered, and refused the request. */
|
|
3365
|
+
var KeyringRefusedError = class extends SecureStorageUnavailableError {};
|
|
3366
|
+
function unavailable(reason) {
|
|
3367
|
+
return new SecureStorageUnavailableError(`The operating system credential store did not answer (${reason}).`);
|
|
3368
|
+
}
|
|
3369
|
+
function runChild(options, request) {
|
|
3370
|
+
return new Promise((resolve, reject) => {
|
|
3371
|
+
if (options.signal?.aborted) {
|
|
3372
|
+
reject(unavailable("abandoned"));
|
|
3373
|
+
return;
|
|
3374
|
+
}
|
|
3375
|
+
let settled = false;
|
|
3376
|
+
let timer;
|
|
3377
|
+
const settle = (finish) => {
|
|
3378
|
+
if (settled) return;
|
|
3379
|
+
settled = true;
|
|
3380
|
+
clearTimeout(timer);
|
|
3381
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
3382
|
+
child?.stdout?.destroy();
|
|
3383
|
+
child?.stdin?.destroy();
|
|
3384
|
+
finish();
|
|
3385
|
+
};
|
|
3386
|
+
let child;
|
|
3387
|
+
let payload;
|
|
3388
|
+
const onAbort = () => {
|
|
3389
|
+
settle(() => {
|
|
3390
|
+
child?.kill("SIGKILL");
|
|
3391
|
+
reject(unavailable("abandoned"));
|
|
3392
|
+
});
|
|
3393
|
+
};
|
|
3394
|
+
try {
|
|
3395
|
+
const launch = options.launch?.() ?? {
|
|
3396
|
+
file: process.execPath,
|
|
3397
|
+
args: ["-e", CHILD_SCRIPT]
|
|
3398
|
+
};
|
|
3399
|
+
payload = JSON.stringify({
|
|
3400
|
+
...request,
|
|
3401
|
+
service: options.service ?? "fluid-cli",
|
|
3402
|
+
module: options.modulePath?.() ?? createRequire(import.meta.url).resolve("@napi-rs/keyring")
|
|
3403
|
+
});
|
|
3404
|
+
child = spawn(launch.file, [...launch.args], {
|
|
3405
|
+
stdio: [
|
|
3406
|
+
"pipe",
|
|
3407
|
+
"pipe",
|
|
3408
|
+
"ignore"
|
|
3409
|
+
],
|
|
3410
|
+
windowsHide: true,
|
|
3411
|
+
env: {
|
|
3412
|
+
...process.env,
|
|
3413
|
+
ELECTRON_RUN_AS_NODE: "1"
|
|
3414
|
+
}
|
|
3415
|
+
});
|
|
3416
|
+
} catch {
|
|
3417
|
+
reject(unavailable("spawn failed"));
|
|
3418
|
+
return;
|
|
3419
|
+
}
|
|
3420
|
+
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
3421
|
+
const events = child;
|
|
3422
|
+
let output = "";
|
|
3423
|
+
child.stdout?.setEncoding("utf8");
|
|
3424
|
+
child.stdout?.on("data", (chunk) => {
|
|
3425
|
+
output += chunk;
|
|
3426
|
+
});
|
|
3427
|
+
child.stdin?.on("error", () => void 0);
|
|
3428
|
+
events.on("error", () => {
|
|
3429
|
+
settle(() => reject(unavailable("spawn failed")));
|
|
3430
|
+
});
|
|
3431
|
+
events.on("close", () => {
|
|
3432
|
+
settle(() => {
|
|
3433
|
+
try {
|
|
3434
|
+
const answer = JSON.parse(output);
|
|
3435
|
+
if (answer.ok) resolve(answer.value ?? null);
|
|
3436
|
+
else reject(new KeyringRefusedError("The operating system credential store refused the request."));
|
|
3437
|
+
} catch {
|
|
3438
|
+
reject(unavailable("no answer"));
|
|
3439
|
+
}
|
|
3440
|
+
});
|
|
3441
|
+
});
|
|
3442
|
+
timer = setTimeout(() => {
|
|
3443
|
+
settle(() => {
|
|
3444
|
+
child.kill("SIGKILL");
|
|
3445
|
+
child.stdout?.destroy();
|
|
3446
|
+
child.stdin?.destroy();
|
|
3447
|
+
reject(unavailable("timed out"));
|
|
3448
|
+
});
|
|
3449
|
+
}, options.timeoutMs ?? 5e3);
|
|
3450
|
+
child.stdin?.end(payload);
|
|
3451
|
+
});
|
|
3452
|
+
}
|
|
3453
|
+
/**
|
|
3454
|
+
* A credential store whose every call runs in a child process that is killed
|
|
3455
|
+
* after `timeoutMs`, because the native binding blocks the calling thread and
|
|
3456
|
+
* a locked or unresponsive keyring would otherwise stall the CLI. A call that
|
|
3457
|
+
* times out, crashes or cannot start rejects with
|
|
3458
|
+
* `SecureStorageUnavailableError`.
|
|
3459
|
+
*/
|
|
3460
|
+
function createChildKeyringStorage(options = {}) {
|
|
3461
|
+
return {
|
|
3462
|
+
get: (key) => runChild(options, {
|
|
3463
|
+
op: "get",
|
|
3464
|
+
account: key
|
|
3465
|
+
}),
|
|
3466
|
+
set: async (key, value) => {
|
|
3467
|
+
await runChild(options, {
|
|
3468
|
+
op: "set",
|
|
3469
|
+
account: key,
|
|
3470
|
+
value
|
|
3471
|
+
});
|
|
3472
|
+
},
|
|
3473
|
+
delete: async (key) => {
|
|
3474
|
+
await runChild(options, {
|
|
3475
|
+
op: "delete",
|
|
3476
|
+
account: key
|
|
3477
|
+
});
|
|
3478
|
+
}
|
|
3479
|
+
};
|
|
3480
|
+
}
|
|
3014
3481
|
//#endregion
|
|
3015
3482
|
//#region src/auth/identity/loopback.ts
|
|
3016
3483
|
/**
|
|
@@ -3125,6 +3592,7 @@ async function startLoopbackServer(options = {}) {
|
|
|
3125
3592
|
}
|
|
3126
3593
|
let deps = {
|
|
3127
3594
|
storage: loadKeyringStorage,
|
|
3595
|
+
adoptionStorage: async (signal) => createChildKeyringStorage({ signal }),
|
|
3128
3596
|
openBrowser,
|
|
3129
3597
|
now: Date.now,
|
|
3130
3598
|
callbackTimeoutMs: DEFAULT_CALLBACK_TIMEOUT_MS,
|
|
@@ -3422,6 +3890,42 @@ async function signInWithBrowser(options) {
|
|
|
3422
3890
|
recovered
|
|
3423
3891
|
};
|
|
3424
3892
|
}
|
|
3893
|
+
/**
|
|
3894
|
+
* An empty session for trading a legacy token. It lives in memory, with no
|
|
3895
|
+
* credential store involved, until `persist` is called on an adopted result.
|
|
3896
|
+
* `signal` cancels the session's requests.
|
|
3897
|
+
*/
|
|
3898
|
+
function createAdoptionSession(identityUrl, signal) {
|
|
3899
|
+
const storageKey = `identity.${randomUUID()}`;
|
|
3900
|
+
const memory = createMemorySecureStorage();
|
|
3901
|
+
return {
|
|
3902
|
+
auth: {
|
|
3903
|
+
mode: "identity",
|
|
3904
|
+
identityUrl,
|
|
3905
|
+
storageKey
|
|
3906
|
+
},
|
|
3907
|
+
session: createNativeSession({
|
|
3908
|
+
identityUrl,
|
|
3909
|
+
clientId: IDENTITY_CLIENT_ID,
|
|
3910
|
+
redirectUri: RESTORE_REDIRECT_URI,
|
|
3911
|
+
storage: memory,
|
|
3912
|
+
storageKey,
|
|
3913
|
+
fetch: signal ? (input, init) => (deps.fetch ?? fetch)(input, {
|
|
3914
|
+
...init,
|
|
3915
|
+
signal: init?.signal ? AbortSignal.any([init.signal, signal]) : signal
|
|
3916
|
+
}) : deps.fetch,
|
|
3917
|
+
now: deps.now
|
|
3918
|
+
}),
|
|
3919
|
+
persist: async () => {
|
|
3920
|
+
const refreshToken = await memory.get(storageKey);
|
|
3921
|
+
if (!refreshToken) throw new Error("The adopted session holds no token.");
|
|
3922
|
+
await (await deps.adoptionStorage(signal)).set(storageKey, refreshToken);
|
|
3923
|
+
},
|
|
3924
|
+
unpersist: async () => {
|
|
3925
|
+
await (await deps.adoptionStorage(signal)).delete(storageKey);
|
|
3926
|
+
}
|
|
3927
|
+
};
|
|
3928
|
+
}
|
|
3425
3929
|
/** A sentence for the user about an identity failure. */
|
|
3426
3930
|
function describeIdentityError(error) {
|
|
3427
3931
|
if (error instanceof SessionError) switch (error.code) {
|
|
@@ -3493,6 +3997,6 @@ async function endUnusedSessions(before, after) {
|
|
|
3493
3997
|
return problems;
|
|
3494
3998
|
}
|
|
3495
3999
|
//#endregion
|
|
3496
|
-
export {
|
|
4000
|
+
export { isStrictConfig as A, tradeLegacyToken as C, readStoredConfig as D, readConfig as E, createDefaultConfig as F, isClientProfile as I, isIdentityProfile as L, withConfigLock as M, getConfigDir as N, updateConfig as O, getConfigFilePath as P, resolveIdentityUrl as S, createFetchClient as T, invalidateClientToken as _, isRoleNotGrantedError as a, saveClientProfile as b, profileAccessToken as c, signOutIdentity as d, KeyringRefusedError as f, deleteClientSecret as g, clientAccessToken as h, identityToken as i, configLockTimings as j, writeConfig as k, sessionFacts as l, ProfileExistsError as m, createAdoptionSession as n, peekIdentityToken as o, OrphanedClientSecretError as p, describeIdentityError as r, primeIdentityProfile as s, endUnusedSessions as t, signInWithBrowser as u, peekClientToken as v, ApiError as w, IDENTITY_ROOT_COMPANY_ID as x, primeClientProfile as y };
|
|
3497
4001
|
|
|
3498
|
-
//# sourceMappingURL=profiles-
|
|
4002
|
+
//# sourceMappingURL=profiles-B6V5IBeX.mjs.map
|