@fluid-app/fluid-cli 0.1.65 → 0.1.66
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/README.md +26 -7
- package/dist/bin/fluid.mjs +373 -20
- package/dist/bin/fluid.mjs.map +1 -1
- package/dist/index.d.mts +56 -15
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +29 -281
- package/dist/index.mjs.map +1 -1
- package/dist/token-BUGqpr-U.mjs +2975 -0
- package/dist/token-BUGqpr-U.mjs.map +1 -0
- package/package.json +3 -1
- package/dist/token-DnFYT9pe.mjs +0 -624
- package/dist/token-DnFYT9pe.mjs.map +0 -1
|
@@ -0,0 +1,2975 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
3
|
+
import { execFile } from "node:child_process";
|
|
4
|
+
import { createServer } from "node:http";
|
|
5
|
+
import { dirname, join } from "node:path";
|
|
6
|
+
import { homedir } from "node:os";
|
|
7
|
+
//#region src/catalog/annotations.ts
|
|
8
|
+
const ANNOTATION = Symbol.for("@fluid-app/fluid-cli.command-annotation");
|
|
9
|
+
/**
|
|
10
|
+
* Record the endpoints a command calls and whether it writes, so
|
|
11
|
+
* `fluid commands --json` can list them. Returns the command for chaining.
|
|
12
|
+
*/
|
|
13
|
+
function describeCommand(command, annotation) {
|
|
14
|
+
const target = command;
|
|
15
|
+
target[ANNOTATION] = {
|
|
16
|
+
...target[ANNOTATION],
|
|
17
|
+
...annotation
|
|
18
|
+
};
|
|
19
|
+
return command;
|
|
20
|
+
}
|
|
21
|
+
function readAnnotation(command) {
|
|
22
|
+
return command[ANNOTATION] ?? null;
|
|
23
|
+
}
|
|
24
|
+
//#endregion
|
|
25
|
+
//#region src/catalog/walk.ts
|
|
26
|
+
function isHidden(command) {
|
|
27
|
+
return command._hidden === true;
|
|
28
|
+
}
|
|
29
|
+
function isRunnable(command) {
|
|
30
|
+
return command._actionHandler != null;
|
|
31
|
+
}
|
|
32
|
+
function visibleSubcommands(command) {
|
|
33
|
+
return command.commands.filter((sub) => !isHidden(sub));
|
|
34
|
+
}
|
|
35
|
+
function visibleOptions(command) {
|
|
36
|
+
return command.options.filter((option) => !option.hidden);
|
|
37
|
+
}
|
|
38
|
+
function describeOption(option) {
|
|
39
|
+
return {
|
|
40
|
+
flags: option.flags,
|
|
41
|
+
long: option.long ?? null,
|
|
42
|
+
short: option.short ?? null,
|
|
43
|
+
description: option.description,
|
|
44
|
+
takesValue: option.required,
|
|
45
|
+
optionalValue: option.optional,
|
|
46
|
+
required: option.mandatory,
|
|
47
|
+
defaultValue: option.defaultValue
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
function describeArgument(argument) {
|
|
51
|
+
return {
|
|
52
|
+
name: argument.name(),
|
|
53
|
+
description: argument.description,
|
|
54
|
+
required: argument.required,
|
|
55
|
+
variadic: argument.variadic
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
function inferWrites(command, declared) {
|
|
59
|
+
if (declared !== void 0) return declared;
|
|
60
|
+
return command.options.some((option) => option.long === "--yes") ? true : null;
|
|
61
|
+
}
|
|
62
|
+
function walkCommands(root) {
|
|
63
|
+
const entries = [];
|
|
64
|
+
function visit(command, path, ancestors) {
|
|
65
|
+
const annotation = readAnnotation(command);
|
|
66
|
+
const subcommands = visibleSubcommands(command);
|
|
67
|
+
entries.push({
|
|
68
|
+
command: path.join(" "),
|
|
69
|
+
path,
|
|
70
|
+
description: command.description(),
|
|
71
|
+
aliases: command.aliases(),
|
|
72
|
+
arguments: command.registeredArguments.map(describeArgument),
|
|
73
|
+
options: visibleOptions(command).map(describeOption),
|
|
74
|
+
inheritsOptionsFrom: ancestors.filter((ancestor) => visibleOptions(ancestor).some((option) => option.long !== "--version")).map((ancestor) => commandPath(ancestor).join(" ")),
|
|
75
|
+
subcommands: subcommands.map((sub) => sub.name()),
|
|
76
|
+
runnable: isRunnable(command),
|
|
77
|
+
writes: inferWrites(command, annotation?.writes),
|
|
78
|
+
endpoints: annotation?.endpoints ?? null
|
|
79
|
+
});
|
|
80
|
+
for (const sub of subcommands) visit(sub, [...path, sub.name()], [...ancestors, command]);
|
|
81
|
+
}
|
|
82
|
+
visit(root, [root.name()], []);
|
|
83
|
+
return entries;
|
|
84
|
+
}
|
|
85
|
+
function rootCommand(command) {
|
|
86
|
+
let root = command;
|
|
87
|
+
while (root.parent) root = root.parent;
|
|
88
|
+
return root;
|
|
89
|
+
}
|
|
90
|
+
function commandPath(command) {
|
|
91
|
+
const path = [];
|
|
92
|
+
for (let c = command; c; c = c.parent) path.unshift(c.name());
|
|
93
|
+
return path;
|
|
94
|
+
}
|
|
95
|
+
/** Keep the entries at or under `prefix`, matching names or aliases. */
|
|
96
|
+
function filterCatalog(entries, root, prefix) {
|
|
97
|
+
let target = root;
|
|
98
|
+
for (const word of prefix) {
|
|
99
|
+
const next = visibleSubcommands(target).find((sub) => sub.name() === word || sub.aliases().includes(word));
|
|
100
|
+
if (!next) return [];
|
|
101
|
+
target = next;
|
|
102
|
+
}
|
|
103
|
+
const base = commandPath(target);
|
|
104
|
+
return entries.filter((entry) => base.every((word, index) => entry.path[index] === word));
|
|
105
|
+
}
|
|
106
|
+
//#endregion
|
|
107
|
+
//#region src/utils/result.ts
|
|
108
|
+
function success(value) {
|
|
109
|
+
return {
|
|
110
|
+
success: true,
|
|
111
|
+
value
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
function failure(error) {
|
|
115
|
+
return {
|
|
116
|
+
success: false,
|
|
117
|
+
error
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
function isSuccess(result) {
|
|
121
|
+
return result.success === true;
|
|
122
|
+
}
|
|
123
|
+
function isFailure(result) {
|
|
124
|
+
return result.success === false;
|
|
125
|
+
}
|
|
126
|
+
function tryCatch(fn) {
|
|
127
|
+
try {
|
|
128
|
+
return success(fn());
|
|
129
|
+
} catch (error) {
|
|
130
|
+
return failure(error instanceof Error ? error : new Error(String(error)));
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
async function tryCatchAsync(fn) {
|
|
134
|
+
try {
|
|
135
|
+
return success(await fn());
|
|
136
|
+
} catch (error) {
|
|
137
|
+
return failure(error instanceof Error ? error : new Error(String(error)));
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
function unwrap(result) {
|
|
141
|
+
if (isSuccess(result)) return result.value;
|
|
142
|
+
if (result.error instanceof Error) throw result.error;
|
|
143
|
+
throw new Error(typeof result.error === "object" && result.error !== null ? JSON.stringify(result.error) : String(result.error));
|
|
144
|
+
}
|
|
145
|
+
function unwrapOr(result, defaultValue) {
|
|
146
|
+
if (isSuccess(result)) return result.value;
|
|
147
|
+
return defaultValue;
|
|
148
|
+
}
|
|
149
|
+
function mapResult(result, fn) {
|
|
150
|
+
if (isSuccess(result)) return success(fn(result.value));
|
|
151
|
+
return result;
|
|
152
|
+
}
|
|
153
|
+
function mapError(result, fn) {
|
|
154
|
+
if (isFailure(result)) return failure(fn(result.error));
|
|
155
|
+
return result;
|
|
156
|
+
}
|
|
157
|
+
function isError(value) {
|
|
158
|
+
return value instanceof Error;
|
|
159
|
+
}
|
|
160
|
+
function isNodeError(value) {
|
|
161
|
+
return value instanceof Error && "code" in value;
|
|
162
|
+
}
|
|
163
|
+
function getErrorMessage$1(error) {
|
|
164
|
+
if (error instanceof Error) return error.message;
|
|
165
|
+
if (typeof error === "string") return error;
|
|
166
|
+
return String(error);
|
|
167
|
+
}
|
|
168
|
+
//#endregion
|
|
169
|
+
//#region src/auth/fluid-api.ts
|
|
170
|
+
const API_TIMEOUT_MS = 1e4;
|
|
171
|
+
function getFluidApiBase() {
|
|
172
|
+
return process.env["FLUID_API_BASE"] ?? "https://api.fluid.app";
|
|
173
|
+
}
|
|
174
|
+
function makeSignal() {
|
|
175
|
+
const controller = new AbortController();
|
|
176
|
+
const timer = setTimeout(() => controller.abort(), API_TIMEOUT_MS);
|
|
177
|
+
return {
|
|
178
|
+
signal: controller.signal,
|
|
179
|
+
cleanup: () => clearTimeout(timer)
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
const FLUID_API_ERROR = {
|
|
183
|
+
INVALID_TOKEN: {
|
|
184
|
+
code: "INVALID_TOKEN",
|
|
185
|
+
message: "Token is invalid or expired"
|
|
186
|
+
},
|
|
187
|
+
API_UNREACHABLE: {
|
|
188
|
+
code: "API_UNREACHABLE",
|
|
189
|
+
message: "Could not reach the Fluid API"
|
|
190
|
+
},
|
|
191
|
+
UUID_NOT_FOUND: {
|
|
192
|
+
code: "UUID_NOT_FOUND",
|
|
193
|
+
message: "Verification session not found"
|
|
194
|
+
},
|
|
195
|
+
CODE_EXPIRED: {
|
|
196
|
+
code: "CODE_EXPIRED",
|
|
197
|
+
message: "Verification code has expired, was already used, or is locked after too many attempts — please request a new one"
|
|
198
|
+
},
|
|
199
|
+
RATE_LIMITED: {
|
|
200
|
+
code: "RATE_LIMITED",
|
|
201
|
+
message: "Too many sign-in requests — wait a minute and try again"
|
|
202
|
+
},
|
|
203
|
+
INVALID_CODE: {
|
|
204
|
+
code: "INVALID_CODE",
|
|
205
|
+
message: "Invalid verification code"
|
|
206
|
+
},
|
|
207
|
+
COMPANY_NOT_FOUND: {
|
|
208
|
+
code: "COMPANY_NOT_FOUND",
|
|
209
|
+
message: "Company not found"
|
|
210
|
+
},
|
|
211
|
+
SWITCH_FAILED: {
|
|
212
|
+
code: "SWITCH_FAILED",
|
|
213
|
+
message: "Failed to switch company"
|
|
214
|
+
},
|
|
215
|
+
LINK_GONE: {
|
|
216
|
+
code: "LINK_GONE",
|
|
217
|
+
message: "This sign-in link has expired or was already used — run `fluid login` for a new one"
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
function createApiError(template, details) {
|
|
221
|
+
return {
|
|
222
|
+
code: template.code,
|
|
223
|
+
message: template.message,
|
|
224
|
+
details
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Validate a token against the Fluid API and return company info.
|
|
229
|
+
* `baseUrl` is the API the token belongs to; it defaults to the CLI's.
|
|
230
|
+
*/
|
|
231
|
+
async function validateToken(token, options = {}) {
|
|
232
|
+
const { signal, cleanup } = makeSignal();
|
|
233
|
+
try {
|
|
234
|
+
const response = await fetch(`${options.baseUrl ?? getFluidApiBase()}/api/company/v1/companies/me`, {
|
|
235
|
+
method: "GET",
|
|
236
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
237
|
+
signal
|
|
238
|
+
});
|
|
239
|
+
if (response.ok) {
|
|
240
|
+
const name = (await response.json())?.data?.company?.name;
|
|
241
|
+
if (!name) return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, "Unexpected response shape from /companies/me"));
|
|
242
|
+
return success({ name });
|
|
243
|
+
}
|
|
244
|
+
if (response.status === 401 || response.status === 403) return failure(createApiError(FLUID_API_ERROR.INVALID_TOKEN, `HTTP ${response.status}: Check that your token is valid and non-expired.`));
|
|
245
|
+
const body = await response.text();
|
|
246
|
+
return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, `HTTP ${response.status}: ${body}`));
|
|
247
|
+
} catch (err) {
|
|
248
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
249
|
+
return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, message));
|
|
250
|
+
} finally {
|
|
251
|
+
cleanup();
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Send a multi-factor authentication code to the given email address.
|
|
256
|
+
* The API answers 201 whether or not the address can sign in
|
|
257
|
+
* (anti-enumeration).
|
|
258
|
+
*
|
|
259
|
+
* With `fluidShop`, the server ties the code to the person's membership in
|
|
260
|
+
* that company, so redeeming it signs in to that company alone and, for an
|
|
261
|
+
* admin's emailed code, confirms a new signup.
|
|
262
|
+
*/
|
|
263
|
+
async function sendMfa(email, options = {}) {
|
|
264
|
+
const { signal, cleanup } = makeSignal();
|
|
265
|
+
try {
|
|
266
|
+
const response = await fetch(`${getFluidApiBase()}/api/authentication/send_mfa`, {
|
|
267
|
+
method: "POST",
|
|
268
|
+
headers: { "Content-Type": "application/json" },
|
|
269
|
+
body: JSON.stringify(options.fluidShop ? {
|
|
270
|
+
email,
|
|
271
|
+
fluid_shop: options.fluidShop
|
|
272
|
+
} : { email }),
|
|
273
|
+
signal
|
|
274
|
+
});
|
|
275
|
+
if (response.status === 201) {
|
|
276
|
+
const data = await response.json();
|
|
277
|
+
const uuid = data.multi_factor_authentication?.uuid;
|
|
278
|
+
const expiresAt = data.multi_factor_authentication?.verification_code_expires_at;
|
|
279
|
+
if (!uuid || !expiresAt) return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, "Unexpected response shape from /send_mfa"));
|
|
280
|
+
return success({
|
|
281
|
+
uuid,
|
|
282
|
+
expiresAt
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
const body = await response.text();
|
|
286
|
+
if (response.status === 429) return failure(createApiError(FLUID_API_ERROR.RATE_LIMITED, `HTTP 429: ${body}`));
|
|
287
|
+
return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, `HTTP ${response.status}: ${body}`));
|
|
288
|
+
} catch (err) {
|
|
289
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
290
|
+
return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, message));
|
|
291
|
+
} finally {
|
|
292
|
+
cleanup();
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Confirm a multi-factor authentication code and retrieve company JWTs.
|
|
297
|
+
*
|
|
298
|
+
* `baseUrl` is the API the code was sent from; a sign-in finished in a
|
|
299
|
+
* later process passes the one it saved, not the current environment's.
|
|
300
|
+
*/
|
|
301
|
+
async function confirmMfa(uuid, code, options = {}) {
|
|
302
|
+
const { signal, cleanup } = makeSignal();
|
|
303
|
+
const apiBase = options.baseUrl ?? getFluidApiBase();
|
|
304
|
+
try {
|
|
305
|
+
const response = await fetch(`${apiBase}/api/authentication/confirm_mfa`, {
|
|
306
|
+
method: "POST",
|
|
307
|
+
headers: { "Content-Type": "application/json" },
|
|
308
|
+
body: JSON.stringify({
|
|
309
|
+
uuid,
|
|
310
|
+
multi_factor_authentication: { verification_code: code },
|
|
311
|
+
...options.fluidShop ? { fluid_shop: options.fluidShop } : {}
|
|
312
|
+
}),
|
|
313
|
+
signal
|
|
314
|
+
});
|
|
315
|
+
if (response.ok) {
|
|
316
|
+
const data = await response.json();
|
|
317
|
+
if (!data.authenticated) return failure(createApiError(FLUID_API_ERROR.INVALID_CODE, "Authentication was not confirmed by the server"));
|
|
318
|
+
const companies = Array.isArray(data.companies) ? data.companies : [];
|
|
319
|
+
return success({
|
|
320
|
+
authType: data.auth_type ?? "",
|
|
321
|
+
companies: companies.map((c) => ({
|
|
322
|
+
id: c.id,
|
|
323
|
+
name: c.name,
|
|
324
|
+
shopName: c.shop_name,
|
|
325
|
+
jwt: c.jwt,
|
|
326
|
+
...c.auth_type ? { authType: c.auth_type } : {}
|
|
327
|
+
})),
|
|
328
|
+
signInPath: data.sign_in_path === "identity" ? "identity" : "legacy"
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
if (response.status === 404) return failure(createApiError(FLUID_API_ERROR.UUID_NOT_FOUND));
|
|
332
|
+
if (response.status === 410) return failure(createApiError(FLUID_API_ERROR.CODE_EXPIRED));
|
|
333
|
+
if (response.status === 422) return failure(createApiError(FLUID_API_ERROR.INVALID_CODE));
|
|
334
|
+
const body = await response.text();
|
|
335
|
+
if (response.status === 429) return failure(createApiError(FLUID_API_ERROR.RATE_LIMITED, `HTTP 429: ${body}`));
|
|
336
|
+
return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, `HTTP ${response.status}: ${body}`));
|
|
337
|
+
} catch (err) {
|
|
338
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
339
|
+
return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, message));
|
|
340
|
+
} finally {
|
|
341
|
+
cleanup();
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* Redeem the single-use token in an identity sign-in email, the email a
|
|
346
|
+
* person whose company signs in through the identity service receives
|
|
347
|
+
* instead of a code. Rails answers 410 for a forged, expired, or used link.
|
|
348
|
+
*/
|
|
349
|
+
async function redeemIdentityLink(token, options = {}) {
|
|
350
|
+
const { signal, cleanup } = makeSignal();
|
|
351
|
+
try {
|
|
352
|
+
const response = await fetch(`${options.baseUrl ?? getFluidApiBase()}/api/v2026-10/single-sign-ons/identity-link-redemptions`, {
|
|
353
|
+
method: "POST",
|
|
354
|
+
headers: { "Content-Type": "application/json" },
|
|
355
|
+
body: JSON.stringify({ token }),
|
|
356
|
+
signal
|
|
357
|
+
});
|
|
358
|
+
if (response.ok) {
|
|
359
|
+
const data = await response.json();
|
|
360
|
+
if (data.sign_in_path !== "identity" || !data.fluid_shop) return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, "Unexpected response shape from /identity-link-redemptions"));
|
|
361
|
+
return success({
|
|
362
|
+
signInPath: "identity",
|
|
363
|
+
fluidShop: data.fluid_shop
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
if (response.status === 410 || response.status === 404) return failure(createApiError(FLUID_API_ERROR.LINK_GONE));
|
|
367
|
+
const body = await response.text();
|
|
368
|
+
return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, `HTTP ${response.status}: ${body}`));
|
|
369
|
+
} catch (err) {
|
|
370
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
371
|
+
return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, message));
|
|
372
|
+
} finally {
|
|
373
|
+
cleanup();
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
/**
|
|
377
|
+
* Fetch all companies the authenticated user has access to.
|
|
378
|
+
*/
|
|
379
|
+
async function fetchUserCompanies(token, baseUrl) {
|
|
380
|
+
const { signal, cleanup } = makeSignal();
|
|
381
|
+
const apiBase = baseUrl ?? getFluidApiBase();
|
|
382
|
+
try {
|
|
383
|
+
const response = await fetch(`${apiBase}/api/me`, {
|
|
384
|
+
method: "GET",
|
|
385
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
386
|
+
signal
|
|
387
|
+
});
|
|
388
|
+
if (response.ok) {
|
|
389
|
+
const data = await response.json();
|
|
390
|
+
return success((Array.isArray(data.companies) ? data.companies : []).map((c) => ({
|
|
391
|
+
id: c.id,
|
|
392
|
+
name: c.name,
|
|
393
|
+
...typeof c.uuid_v7 === "string" ? { uuidV7: c.uuid_v7 } : {}
|
|
394
|
+
})));
|
|
395
|
+
}
|
|
396
|
+
if (response.status === 401 || response.status === 403) return failure(createApiError(FLUID_API_ERROR.INVALID_TOKEN, `HTTP ${response.status}`));
|
|
397
|
+
const body = await response.text();
|
|
398
|
+
return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, `HTTP ${response.status}: ${body}`));
|
|
399
|
+
} catch (err) {
|
|
400
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
401
|
+
return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, message));
|
|
402
|
+
} finally {
|
|
403
|
+
cleanup();
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
/**
|
|
407
|
+
* Switch to a different company and receive a new JWT.
|
|
408
|
+
*
|
|
409
|
+
* Response shape (from @fluid-app/auth SwitchCompanyResponse):
|
|
410
|
+
* { company: { id, name, fluid_shop, jwt }, meta: { request_id, timestamp } }
|
|
411
|
+
*/
|
|
412
|
+
async function switchCompany(token, companyId, baseUrl) {
|
|
413
|
+
const { signal, cleanup } = makeSignal();
|
|
414
|
+
const apiBase = baseUrl ?? getFluidApiBase();
|
|
415
|
+
try {
|
|
416
|
+
const response = await fetch(`${apiBase}/api/authentication/company/${companyId}/switch`, {
|
|
417
|
+
method: "PUT",
|
|
418
|
+
headers: {
|
|
419
|
+
Authorization: `Bearer ${token}`,
|
|
420
|
+
"Content-Type": "application/json"
|
|
421
|
+
},
|
|
422
|
+
signal
|
|
423
|
+
});
|
|
424
|
+
if (response.ok) {
|
|
425
|
+
const company = (await response.json()).company;
|
|
426
|
+
if (!company?.jwt) return failure(createApiError(FLUID_API_ERROR.SWITCH_FAILED, "Unexpected response shape from /switch"));
|
|
427
|
+
return success({
|
|
428
|
+
companyId: company.id,
|
|
429
|
+
companyName: company.name,
|
|
430
|
+
fluidShop: company.fluid_shop,
|
|
431
|
+
jwt: company.jwt
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
if (response.status === 404) return failure(createApiError(FLUID_API_ERROR.COMPANY_NOT_FOUND, `Company ${companyId} not found`));
|
|
435
|
+
if (response.status === 401 || response.status === 403) return failure(createApiError(FLUID_API_ERROR.INVALID_TOKEN, `HTTP ${response.status}`));
|
|
436
|
+
const body = await response.text();
|
|
437
|
+
return failure(createApiError(FLUID_API_ERROR.SWITCH_FAILED, `HTTP ${response.status}: ${body}`));
|
|
438
|
+
} catch (err) {
|
|
439
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
440
|
+
return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, message));
|
|
441
|
+
} finally {
|
|
442
|
+
cleanup();
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
//#endregion
|
|
446
|
+
//#region src/config/types.ts
|
|
447
|
+
/** Whether a profile signs in through the identity service. */
|
|
448
|
+
function isIdentityProfile(profile) {
|
|
449
|
+
return profile?.auth?.mode === "identity";
|
|
450
|
+
}
|
|
451
|
+
function createDefaultConfig() {
|
|
452
|
+
return {
|
|
453
|
+
activeProfile: null,
|
|
454
|
+
profiles: {},
|
|
455
|
+
plugins: {},
|
|
456
|
+
enabledPlugins: null
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
//#endregion
|
|
460
|
+
//#region ../../platform/api-client-core/src/api-error-shape.ts
|
|
461
|
+
/**
|
|
462
|
+
* Narrows a parsed JSON error payload to the envelope contract. Arrays and
|
|
463
|
+
* primitives are not envelopes, so they resolve to `null` — their content is
|
|
464
|
+
* still reachable through `ApiError.data`.
|
|
465
|
+
*/
|
|
466
|
+
function toApiErrorBody(value) {
|
|
467
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
468
|
+
return value;
|
|
469
|
+
}
|
|
470
|
+
/**
|
|
471
|
+
* The single unwrap rule, shared by every producer of `ApiError`.
|
|
472
|
+
*
|
|
473
|
+
* `??` rather than `||` so an explicitly empty `errors` (`""`, `0`, `false`)
|
|
474
|
+
* is preserved instead of silently falling back to the whole envelope.
|
|
475
|
+
*/
|
|
476
|
+
function toApiErrorData(body) {
|
|
477
|
+
if (!body) return null;
|
|
478
|
+
return body.errors ?? body;
|
|
479
|
+
}
|
|
480
|
+
//#endregion
|
|
481
|
+
//#region ../../platform/api-client-core/src/fetch-client.ts
|
|
482
|
+
/**
|
|
483
|
+
* API Error class compatible with fluid-admin's ApiError
|
|
484
|
+
*/
|
|
485
|
+
var ApiError = class ApiError extends Error {
|
|
486
|
+
status;
|
|
487
|
+
/**
|
|
488
|
+
* The unwrapped field-error bag. See `ApiErrorData`; the contract is
|
|
489
|
+
* documented in `docs/api-error-data-contract.md`.
|
|
490
|
+
*/
|
|
491
|
+
data;
|
|
492
|
+
/**
|
|
493
|
+
* The full error response envelope. Read `error_message`, `error`, `status`
|
|
494
|
+
* and nested `errors` from here — `data` has already unwrapped one level.
|
|
495
|
+
*/
|
|
496
|
+
body;
|
|
497
|
+
requestId;
|
|
498
|
+
constructor(message, status, data, requestId, body) {
|
|
499
|
+
super(message);
|
|
500
|
+
this.name = "ApiError";
|
|
501
|
+
this.status = status;
|
|
502
|
+
this.data = data ?? null;
|
|
503
|
+
this.body = body ?? null;
|
|
504
|
+
this.requestId = requestId;
|
|
505
|
+
if ("captureStackTrace" in Error) Error.captureStackTrace(this, ApiError);
|
|
506
|
+
}
|
|
507
|
+
toJSON() {
|
|
508
|
+
return {
|
|
509
|
+
name: this.name,
|
|
510
|
+
message: this.message,
|
|
511
|
+
status: this.status,
|
|
512
|
+
data: this.data,
|
|
513
|
+
body: this.body,
|
|
514
|
+
requestId: this.requestId
|
|
515
|
+
};
|
|
516
|
+
}
|
|
517
|
+
};
|
|
518
|
+
function getStringRequestId(value) {
|
|
519
|
+
if (typeof value !== "string") return;
|
|
520
|
+
const trimmed = value.trim();
|
|
521
|
+
return trimmed.length > 0 ? trimmed : void 0;
|
|
522
|
+
}
|
|
523
|
+
function getRequestIdFromHeaders(headers) {
|
|
524
|
+
return getStringRequestId(headers.get("x-request-id")) ?? getStringRequestId(headers.get("request-id")) ?? getStringRequestId(headers.get("X-Request-ID"));
|
|
525
|
+
}
|
|
526
|
+
function getRequestIdFromJsonBody(body) {
|
|
527
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) return;
|
|
528
|
+
const record = body;
|
|
529
|
+
const meta = record.meta;
|
|
530
|
+
return getStringRequestId(record.request_id) ?? getStringRequestId(record.requestId) ?? (meta && typeof meta === "object" && !Array.isArray(meta) ? getStringRequestId(meta.request_id) ?? getStringRequestId(meta.requestId) : void 0);
|
|
531
|
+
}
|
|
532
|
+
/**
|
|
533
|
+
* Type guard for ApiError
|
|
534
|
+
*/
|
|
535
|
+
function isApiError(error) {
|
|
536
|
+
return error instanceof ApiError;
|
|
537
|
+
}
|
|
538
|
+
/**
|
|
539
|
+
* Creates a configured fetch client instance
|
|
540
|
+
*/
|
|
541
|
+
function createFetchClient(config) {
|
|
542
|
+
const { baseUrl, getAuthToken, onAuthError, defaultHeaders = {}, credentials, cache, networkRetry, throwOnInvalidJson = false } = config;
|
|
543
|
+
const maxNetworkRetries = Math.max(0, networkRetry?.maxRetries ?? 0);
|
|
544
|
+
const baseNetworkRetryDelayMs = Math.max(0, networkRetry?.baseDelayMs ?? 0);
|
|
545
|
+
/**
|
|
546
|
+
* Build headers for a request
|
|
547
|
+
*/
|
|
548
|
+
async function buildHeaders(customHeaders) {
|
|
549
|
+
const headers = {
|
|
550
|
+
Accept: "application/json",
|
|
551
|
+
"Content-Type": "application/json",
|
|
552
|
+
...defaultHeaders,
|
|
553
|
+
...customHeaders
|
|
554
|
+
};
|
|
555
|
+
if (getAuthToken) {
|
|
556
|
+
const token = await getAuthToken();
|
|
557
|
+
if (token) headers.Authorization = `Bearer ${token}`;
|
|
558
|
+
}
|
|
559
|
+
return headers;
|
|
560
|
+
}
|
|
561
|
+
/**
|
|
562
|
+
* Join baseUrl + endpoint via string concatenation (matches fetchApi).
|
|
563
|
+
* Using `new URL(endpoint, baseUrl)` would strip any path prefix from
|
|
564
|
+
* baseUrl (e.g. "/api") when the endpoint starts with "/".
|
|
565
|
+
*/
|
|
566
|
+
function joinUrl(endpoint) {
|
|
567
|
+
return `${baseUrl}${endpoint}`;
|
|
568
|
+
}
|
|
569
|
+
/**
|
|
570
|
+
* Build URL with query parameters for GET requests
|
|
571
|
+
* Compatible with fluid-admin's query param handling
|
|
572
|
+
*/
|
|
573
|
+
function buildUrl(endpoint, params) {
|
|
574
|
+
const fullUrl = joinUrl(endpoint);
|
|
575
|
+
if (!params || Object.keys(params).length === 0) return fullUrl;
|
|
576
|
+
const queryString = new URLSearchParams();
|
|
577
|
+
Object.entries(params).forEach(([key, value]) => {
|
|
578
|
+
if (value === void 0 || value === null) return;
|
|
579
|
+
if (Array.isArray(value)) {
|
|
580
|
+
const arrayKey = key.endsWith("[]") ? key : `${key}[]`;
|
|
581
|
+
value.forEach((item) => queryString.append(arrayKey, String(item)));
|
|
582
|
+
} else if (typeof value === "object") Object.entries(value).forEach(([subKey, subValue]) => {
|
|
583
|
+
if (subValue === void 0 || subValue === null) return;
|
|
584
|
+
if (Array.isArray(subValue)) subValue.forEach((item) => queryString.append(`${key}[${subKey}][]`, String(item)));
|
|
585
|
+
else queryString.append(`${key}[${subKey}]`, String(subValue));
|
|
586
|
+
});
|
|
587
|
+
else queryString.append(key, String(value));
|
|
588
|
+
});
|
|
589
|
+
const qs = queryString.toString();
|
|
590
|
+
return qs ? `${fullUrl}?${qs}` : fullUrl;
|
|
591
|
+
}
|
|
592
|
+
/**
|
|
593
|
+
* Shared response handler for both JSON and FormData requests.
|
|
594
|
+
* Handles auth errors, non-OK responses, 204 No Content, and JSON parsing.
|
|
595
|
+
*/
|
|
596
|
+
async function handleResponse(response, method, _url) {
|
|
597
|
+
const headerRequestId = getRequestIdFromHeaders(response.headers);
|
|
598
|
+
if (response.status === 401 && onAuthError) onAuthError();
|
|
599
|
+
if (!response.ok) {
|
|
600
|
+
const errorText = await response.text().catch(() => "");
|
|
601
|
+
if (response.headers.get("content-type")?.includes("application/json")) {
|
|
602
|
+
let parsed;
|
|
603
|
+
try {
|
|
604
|
+
parsed = JSON.parse(errorText);
|
|
605
|
+
} catch {
|
|
606
|
+
throw new ApiError(errorText.slice(0, 200) || `${method} request failed with status ${response.status}`, response.status, null, headerRequestId);
|
|
607
|
+
}
|
|
608
|
+
const body = toApiErrorBody(parsed);
|
|
609
|
+
throw new ApiError((body ? (() => {
|
|
610
|
+
const nestedError = typeof body.error === "object" && body.error !== null ? body.error.message : void 0;
|
|
611
|
+
const directError = typeof body.error === "string" ? body.error : void 0;
|
|
612
|
+
const message = typeof body.message === "string" ? body.message : void 0;
|
|
613
|
+
const errorMessage = typeof body.error_message === "string" ? body.error_message : void 0;
|
|
614
|
+
return message || errorMessage || directError || (typeof nestedError === "string" ? nestedError : void 0);
|
|
615
|
+
})() : void 0) || `${method} request failed with status ${response.status}`, response.status, body ? toApiErrorData(body) : parsed, headerRequestId ?? getRequestIdFromJsonBody(parsed), body);
|
|
616
|
+
} else throw new ApiError(`${method} request failed with status ${response.status}`, response.status, null, headerRequestId);
|
|
617
|
+
}
|
|
618
|
+
if (response.status === 204 || response.headers.get("content-length") === "0") return null;
|
|
619
|
+
if (response.headers.get("content-type")?.includes("application/json")) {
|
|
620
|
+
const responseText = await response.text();
|
|
621
|
+
try {
|
|
622
|
+
return JSON.parse(responseText);
|
|
623
|
+
} catch {
|
|
624
|
+
if (throwOnInvalidJson) throw new ApiError("Failed to parse response as JSON", response.status, null, headerRequestId);
|
|
625
|
+
return responseText ? responseText : null;
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
return null;
|
|
629
|
+
}
|
|
630
|
+
function getNetworkRetryDelayMs(retryAttempt) {
|
|
631
|
+
return baseNetworkRetryDelayMs * 2 ** (retryAttempt - 1);
|
|
632
|
+
}
|
|
633
|
+
async function waitForNetworkRetry(retryAttempt) {
|
|
634
|
+
const delayMs = getNetworkRetryDelayMs(retryAttempt);
|
|
635
|
+
if (delayMs <= 0) return;
|
|
636
|
+
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
637
|
+
}
|
|
638
|
+
async function fetchWithNetworkRetry(url, fetchOptions, signal) {
|
|
639
|
+
let retryCount = 0;
|
|
640
|
+
while (true) try {
|
|
641
|
+
return await fetch(url, fetchOptions);
|
|
642
|
+
} catch (networkError) {
|
|
643
|
+
if (signal?.aborted || retryCount >= maxNetworkRetries) throw networkError;
|
|
644
|
+
retryCount += 1;
|
|
645
|
+
await waitForNetworkRetry(retryCount);
|
|
646
|
+
if (signal?.aborted) throw networkError;
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
/**
|
|
650
|
+
* Main request function
|
|
651
|
+
*/
|
|
652
|
+
async function request(endpoint, options = {}) {
|
|
653
|
+
const { method = "GET", headers: customHeaders, params, body, signal, priority } = options;
|
|
654
|
+
const url = params ? buildUrl(endpoint, params) : joinUrl(endpoint);
|
|
655
|
+
const headers = await buildHeaders(customHeaders);
|
|
656
|
+
let response;
|
|
657
|
+
try {
|
|
658
|
+
const fetchOptions = {
|
|
659
|
+
method,
|
|
660
|
+
headers
|
|
661
|
+
};
|
|
662
|
+
if (credentials) fetchOptions.credentials = credentials;
|
|
663
|
+
if (cache) fetchOptions.cache = cache;
|
|
664
|
+
if (priority) fetchOptions.priority = priority;
|
|
665
|
+
const serializedBody = body && method !== "GET" ? JSON.stringify(body) : null;
|
|
666
|
+
if (serializedBody) fetchOptions.body = serializedBody;
|
|
667
|
+
if (signal) fetchOptions.signal = signal;
|
|
668
|
+
response = await fetchWithNetworkRetry(url, fetchOptions, signal);
|
|
669
|
+
} catch (networkError) {
|
|
670
|
+
throw new ApiError(`Network error: ${networkError instanceof Error ? networkError.message : "Unknown network error"}`, 0, null);
|
|
671
|
+
}
|
|
672
|
+
return handleResponse(response, method, url);
|
|
673
|
+
}
|
|
674
|
+
/**
|
|
675
|
+
* Request with FormData (for file uploads)
|
|
676
|
+
*/
|
|
677
|
+
async function requestWithFormData(endpoint, formData, options = {}) {
|
|
678
|
+
const { method = "POST", headers: customHeaders, signal, priority } = options;
|
|
679
|
+
const url = joinUrl(endpoint);
|
|
680
|
+
const headers = await buildHeaders(customHeaders);
|
|
681
|
+
delete headers["Content-Type"];
|
|
682
|
+
let response;
|
|
683
|
+
try {
|
|
684
|
+
const fetchOptions = {
|
|
685
|
+
method,
|
|
686
|
+
headers,
|
|
687
|
+
body: formData
|
|
688
|
+
};
|
|
689
|
+
if (credentials) fetchOptions.credentials = credentials;
|
|
690
|
+
if (cache) fetchOptions.cache = cache;
|
|
691
|
+
if (priority) fetchOptions.priority = priority;
|
|
692
|
+
if (signal) fetchOptions.signal = signal;
|
|
693
|
+
response = await fetchWithNetworkRetry(url, fetchOptions, signal);
|
|
694
|
+
} catch (networkError) {
|
|
695
|
+
throw new ApiError(`Network error: ${networkError instanceof Error ? networkError.message : "Unknown network error"}`, 0, null);
|
|
696
|
+
}
|
|
697
|
+
return handleResponse(response, method, url);
|
|
698
|
+
}
|
|
699
|
+
return {
|
|
700
|
+
request,
|
|
701
|
+
requestWithFormData,
|
|
702
|
+
get: (endpoint, params, options) => request(endpoint, {
|
|
703
|
+
...options,
|
|
704
|
+
method: "GET",
|
|
705
|
+
...params && { params }
|
|
706
|
+
}),
|
|
707
|
+
post: (endpoint, body, options) => request(endpoint, {
|
|
708
|
+
...options,
|
|
709
|
+
method: "POST",
|
|
710
|
+
body
|
|
711
|
+
}),
|
|
712
|
+
put: (endpoint, body, options) => request(endpoint, {
|
|
713
|
+
...options,
|
|
714
|
+
method: "PUT",
|
|
715
|
+
body
|
|
716
|
+
}),
|
|
717
|
+
patch: (endpoint, body, options) => request(endpoint, {
|
|
718
|
+
...options,
|
|
719
|
+
method: "PATCH",
|
|
720
|
+
body
|
|
721
|
+
}),
|
|
722
|
+
delete: (endpoint, options) => request(endpoint, {
|
|
723
|
+
...options,
|
|
724
|
+
method: "DELETE"
|
|
725
|
+
})
|
|
726
|
+
};
|
|
727
|
+
}
|
|
728
|
+
//#endregion
|
|
729
|
+
//#region ../../platform/api-client-core/src/hey-api-error-policy.ts
|
|
730
|
+
function getNonEmptyString(value) {
|
|
731
|
+
if (typeof value !== "string") return;
|
|
732
|
+
const trimmed = value.trim();
|
|
733
|
+
return trimmed.length > 0 ? trimmed : void 0;
|
|
734
|
+
}
|
|
735
|
+
function getRequestId(response, error) {
|
|
736
|
+
const meta = toApiErrorBody(error?.meta);
|
|
737
|
+
return getNonEmptyString(response.headers.get("x-request-id")) ?? getNonEmptyString(response.headers.get("request-id")) ?? getNonEmptyString(error?.request_id) ?? getNonEmptyString(error?.requestId) ?? getNonEmptyString(meta?.request_id) ?? getNonEmptyString(meta?.requestId);
|
|
738
|
+
}
|
|
739
|
+
function getErrorMessage(error, fallback) {
|
|
740
|
+
const nestedError = toApiErrorBody(error.error);
|
|
741
|
+
return getNonEmptyString(error.message) ?? getNonEmptyString(error.error_message) ?? getNonEmptyString(nestedError?.message) ?? fallback;
|
|
742
|
+
}
|
|
743
|
+
/**
|
|
744
|
+
* Creates an error interceptor compatible with generated Hey API fetch clients.
|
|
745
|
+
* Consumer-specific auth and cancellation policy is supplied through callbacks,
|
|
746
|
+
* keeping this package independent from generated client types.
|
|
747
|
+
*/
|
|
748
|
+
function createHeyApiErrorInterceptor(options = {}) {
|
|
749
|
+
return (error, response, request, requestOptions) => {
|
|
750
|
+
if (!response) {
|
|
751
|
+
if (error instanceof ApiError) return error;
|
|
752
|
+
if (options.shouldPassThroughTransportError?.(error)) return error;
|
|
753
|
+
if (!request) return error;
|
|
754
|
+
return new ApiError(`Network error: ${error instanceof Error ? error.message : "Unknown network error"}`, 0, null);
|
|
755
|
+
}
|
|
756
|
+
if (response.ok && error instanceof SyntaxError) return new ApiError("Failed to parse response as JSON", response.status, null, getRequestId(response, null));
|
|
757
|
+
options.onResponseError?.(response);
|
|
758
|
+
const method = request?.method ?? requestOptions.method ?? "GET";
|
|
759
|
+
const errorRecord = toApiErrorBody(error);
|
|
760
|
+
const requestId = getRequestId(response, errorRecord);
|
|
761
|
+
if (errorRecord) return new ApiError(getErrorMessage(errorRecord, `${method} request failed`), response.status, toApiErrorData(errorRecord), requestId, errorRecord);
|
|
762
|
+
const isJson = response.headers.get("content-type")?.includes("application/json");
|
|
763
|
+
const text = getNonEmptyString(error);
|
|
764
|
+
return new ApiError(isJson && text ? text.slice(0, 200) : `${method} request failed with status ${response.status}`, response.status, isJson ? error : null, requestId, null);
|
|
765
|
+
};
|
|
766
|
+
}
|
|
767
|
+
//#endregion
|
|
768
|
+
//#region ../../api-clients/hey-api-fetch-runtime/src/generated/core/bodySerializer.gen.ts
|
|
769
|
+
const serializeUrlSearchParamsPair = (data, key, value) => {
|
|
770
|
+
if (typeof value === "string") data.append(key, value);
|
|
771
|
+
else data.append(key, JSON.stringify(value));
|
|
772
|
+
};
|
|
773
|
+
const jsonBodySerializer = { bodySerializer: (body) => JSON.stringify(body, (_key, value) => typeof value === "bigint" ? value.toString() : value) };
|
|
774
|
+
const urlSearchParamsBodySerializer = { bodySerializer: (body) => {
|
|
775
|
+
const data = new URLSearchParams();
|
|
776
|
+
Object.entries(body).forEach(([key, value]) => {
|
|
777
|
+
if (value === void 0 || value === null) return;
|
|
778
|
+
if (Array.isArray(value)) value.forEach((v) => serializeUrlSearchParamsPair(data, key, v));
|
|
779
|
+
else serializeUrlSearchParamsPair(data, key, value);
|
|
780
|
+
});
|
|
781
|
+
return data.toString();
|
|
782
|
+
} };
|
|
783
|
+
Object.entries({
|
|
784
|
+
$body_: "body",
|
|
785
|
+
$headers_: "headers",
|
|
786
|
+
$path_: "path",
|
|
787
|
+
$query_: "query"
|
|
788
|
+
});
|
|
789
|
+
//#endregion
|
|
790
|
+
//#region ../../api-clients/hey-api-fetch-runtime/src/generated/core/serverSentEvents.gen.ts
|
|
791
|
+
function createSseClient({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }) {
|
|
792
|
+
let lastEventId;
|
|
793
|
+
const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
794
|
+
const createStream = async function* () {
|
|
795
|
+
let retryDelay = sseDefaultRetryDelay ?? 3e3;
|
|
796
|
+
let attempt = 0;
|
|
797
|
+
const signal = options.signal ?? new AbortController().signal;
|
|
798
|
+
while (true) {
|
|
799
|
+
if (signal.aborted) break;
|
|
800
|
+
attempt++;
|
|
801
|
+
const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
|
|
802
|
+
if (lastEventId !== void 0) headers.set("Last-Event-ID", lastEventId);
|
|
803
|
+
try {
|
|
804
|
+
const requestInit = {
|
|
805
|
+
redirect: "follow",
|
|
806
|
+
...options,
|
|
807
|
+
body: options.serializedBody,
|
|
808
|
+
headers,
|
|
809
|
+
signal
|
|
810
|
+
};
|
|
811
|
+
let request = new Request(url, requestInit);
|
|
812
|
+
if (onRequest) request = await onRequest(url, requestInit);
|
|
813
|
+
const response = await (options.fetch ?? globalThis.fetch)(request);
|
|
814
|
+
if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
|
|
815
|
+
if (!response.body) throw new Error("No body in SSE response");
|
|
816
|
+
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
|
|
817
|
+
let buffer = "";
|
|
818
|
+
const abortHandler = () => {
|
|
819
|
+
try {
|
|
820
|
+
reader.cancel();
|
|
821
|
+
} catch {}
|
|
822
|
+
};
|
|
823
|
+
signal.addEventListener("abort", abortHandler);
|
|
824
|
+
try {
|
|
825
|
+
while (true) {
|
|
826
|
+
const { done, value } = await reader.read();
|
|
827
|
+
if (done) break;
|
|
828
|
+
buffer += value;
|
|
829
|
+
buffer = buffer.replace(/\r\n?/g, "\n");
|
|
830
|
+
const chunks = buffer.split("\n\n");
|
|
831
|
+
buffer = chunks.pop() ?? "";
|
|
832
|
+
for (const chunk of chunks) {
|
|
833
|
+
const lines = chunk.split("\n");
|
|
834
|
+
const dataLines = [];
|
|
835
|
+
let eventName;
|
|
836
|
+
for (const line of lines) if (line.startsWith("data:")) dataLines.push(line.replace(/^data:\s*/, ""));
|
|
837
|
+
else if (line.startsWith("event:")) eventName = line.replace(/^event:\s*/, "");
|
|
838
|
+
else if (line.startsWith("id:")) lastEventId = line.replace(/^id:\s*/, "");
|
|
839
|
+
else if (line.startsWith("retry:")) {
|
|
840
|
+
const parsed = Number.parseInt(line.replace(/^retry:\s*/, ""), 10);
|
|
841
|
+
if (!Number.isNaN(parsed)) retryDelay = parsed;
|
|
842
|
+
}
|
|
843
|
+
let data;
|
|
844
|
+
let parsedJson = false;
|
|
845
|
+
if (dataLines.length) {
|
|
846
|
+
const rawData = dataLines.join("\n");
|
|
847
|
+
try {
|
|
848
|
+
data = JSON.parse(rawData);
|
|
849
|
+
parsedJson = true;
|
|
850
|
+
} catch {
|
|
851
|
+
data = rawData;
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
if (parsedJson) {
|
|
855
|
+
if (responseValidator) await responseValidator(data);
|
|
856
|
+
if (responseTransformer) data = await responseTransformer(data);
|
|
857
|
+
}
|
|
858
|
+
onSseEvent?.({
|
|
859
|
+
data,
|
|
860
|
+
event: eventName,
|
|
861
|
+
id: lastEventId,
|
|
862
|
+
retry: retryDelay
|
|
863
|
+
});
|
|
864
|
+
if (dataLines.length) yield data;
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
} finally {
|
|
868
|
+
signal.removeEventListener("abort", abortHandler);
|
|
869
|
+
reader.releaseLock();
|
|
870
|
+
}
|
|
871
|
+
break;
|
|
872
|
+
} catch (error) {
|
|
873
|
+
onSseError?.(error);
|
|
874
|
+
if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) break;
|
|
875
|
+
await sleep(Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 3e4));
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
};
|
|
879
|
+
return { stream: createStream() };
|
|
880
|
+
}
|
|
881
|
+
//#endregion
|
|
882
|
+
//#region ../../api-clients/hey-api-fetch-runtime/src/generated/core/pathSerializer.gen.ts
|
|
883
|
+
const separatorArrayExplode = (style) => {
|
|
884
|
+
switch (style) {
|
|
885
|
+
case "label": return ".";
|
|
886
|
+
case "matrix": return ";";
|
|
887
|
+
case "simple": return ",";
|
|
888
|
+
default: return "&";
|
|
889
|
+
}
|
|
890
|
+
};
|
|
891
|
+
const separatorArrayNoExplode = (style) => {
|
|
892
|
+
switch (style) {
|
|
893
|
+
case "form": return ",";
|
|
894
|
+
case "pipeDelimited": return "|";
|
|
895
|
+
case "spaceDelimited": return "%20";
|
|
896
|
+
default: return ",";
|
|
897
|
+
}
|
|
898
|
+
};
|
|
899
|
+
const separatorObjectExplode = (style) => {
|
|
900
|
+
switch (style) {
|
|
901
|
+
case "label": return ".";
|
|
902
|
+
case "matrix": return ";";
|
|
903
|
+
case "simple": return ",";
|
|
904
|
+
default: return "&";
|
|
905
|
+
}
|
|
906
|
+
};
|
|
907
|
+
const serializeArrayParam = ({ allowReserved, explode, name, style, value }) => {
|
|
908
|
+
if (!explode) {
|
|
909
|
+
const joinedValues = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
|
|
910
|
+
switch (style) {
|
|
911
|
+
case "label": return `.${joinedValues}`;
|
|
912
|
+
case "matrix": return `;${name}=${joinedValues}`;
|
|
913
|
+
case "simple": return joinedValues;
|
|
914
|
+
default: return `${name}=${joinedValues}`;
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
const separator = separatorArrayExplode(style);
|
|
918
|
+
const joinedValues = value.map((v) => {
|
|
919
|
+
if (style === "label" || style === "simple") return allowReserved ? v : encodeURIComponent(v);
|
|
920
|
+
return serializePrimitiveParam({
|
|
921
|
+
allowReserved,
|
|
922
|
+
name,
|
|
923
|
+
value: v
|
|
924
|
+
});
|
|
925
|
+
}).join(separator);
|
|
926
|
+
return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
|
|
927
|
+
};
|
|
928
|
+
const serializePrimitiveParam = ({ allowReserved, name, value }) => {
|
|
929
|
+
if (value === void 0 || value === null) return "";
|
|
930
|
+
if (typeof value === "object") throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");
|
|
931
|
+
return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
|
|
932
|
+
};
|
|
933
|
+
const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly }) => {
|
|
934
|
+
if (value instanceof Date) return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
|
|
935
|
+
if (style !== "deepObject" && !explode) {
|
|
936
|
+
let values = [];
|
|
937
|
+
Object.entries(value).forEach(([key, v]) => {
|
|
938
|
+
values = [
|
|
939
|
+
...values,
|
|
940
|
+
key,
|
|
941
|
+
allowReserved ? v : encodeURIComponent(v)
|
|
942
|
+
];
|
|
943
|
+
});
|
|
944
|
+
const joinedValues = values.join(",");
|
|
945
|
+
switch (style) {
|
|
946
|
+
case "form": return `${name}=${joinedValues}`;
|
|
947
|
+
case "label": return `.${joinedValues}`;
|
|
948
|
+
case "matrix": return `;${name}=${joinedValues}`;
|
|
949
|
+
default: return joinedValues;
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
const separator = separatorObjectExplode(style);
|
|
953
|
+
const joinedValues = Object.entries(value).map(([key, v]) => serializePrimitiveParam({
|
|
954
|
+
allowReserved,
|
|
955
|
+
name: style === "deepObject" ? `${name}[${key}]` : key,
|
|
956
|
+
value: v
|
|
957
|
+
})).join(separator);
|
|
958
|
+
return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
|
|
959
|
+
};
|
|
960
|
+
//#endregion
|
|
961
|
+
//#region ../../api-clients/hey-api-fetch-runtime/src/generated/core/utils.gen.ts
|
|
962
|
+
const PATH_PARAM_RE = /\{[^{}]+\}/g;
|
|
963
|
+
const defaultPathSerializer = ({ path, url: _url }) => {
|
|
964
|
+
let url = _url;
|
|
965
|
+
const matches = _url.match(PATH_PARAM_RE);
|
|
966
|
+
if (matches) for (const match of matches) {
|
|
967
|
+
let explode = false;
|
|
968
|
+
let name = match.substring(1, match.length - 1);
|
|
969
|
+
let style = "simple";
|
|
970
|
+
if (name.endsWith("*")) {
|
|
971
|
+
explode = true;
|
|
972
|
+
name = name.substring(0, name.length - 1);
|
|
973
|
+
}
|
|
974
|
+
if (name.startsWith(".")) {
|
|
975
|
+
name = name.substring(1);
|
|
976
|
+
style = "label";
|
|
977
|
+
} else if (name.startsWith(";")) {
|
|
978
|
+
name = name.substring(1);
|
|
979
|
+
style = "matrix";
|
|
980
|
+
}
|
|
981
|
+
const value = path[name];
|
|
982
|
+
if (value === void 0 || value === null) continue;
|
|
983
|
+
if (Array.isArray(value)) {
|
|
984
|
+
url = url.replace(match, serializeArrayParam({
|
|
985
|
+
explode,
|
|
986
|
+
name,
|
|
987
|
+
style,
|
|
988
|
+
value
|
|
989
|
+
}));
|
|
990
|
+
continue;
|
|
991
|
+
}
|
|
992
|
+
if (typeof value === "object") {
|
|
993
|
+
url = url.replace(match, serializeObjectParam({
|
|
994
|
+
explode,
|
|
995
|
+
name,
|
|
996
|
+
style,
|
|
997
|
+
value,
|
|
998
|
+
valueOnly: true
|
|
999
|
+
}));
|
|
1000
|
+
continue;
|
|
1001
|
+
}
|
|
1002
|
+
if (style === "matrix") {
|
|
1003
|
+
url = url.replace(match, `;${serializePrimitiveParam({
|
|
1004
|
+
name,
|
|
1005
|
+
value
|
|
1006
|
+
})}`);
|
|
1007
|
+
continue;
|
|
1008
|
+
}
|
|
1009
|
+
const replaceValue = encodeURIComponent(style === "label" ? `.${value}` : value);
|
|
1010
|
+
url = url.replace(match, replaceValue);
|
|
1011
|
+
}
|
|
1012
|
+
return url;
|
|
1013
|
+
};
|
|
1014
|
+
const getUrl = ({ baseUrl, path, query, querySerializer, url: _url }) => {
|
|
1015
|
+
const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
|
|
1016
|
+
let url = (baseUrl ?? "") + pathUrl;
|
|
1017
|
+
if (path) url = defaultPathSerializer({
|
|
1018
|
+
path,
|
|
1019
|
+
url
|
|
1020
|
+
});
|
|
1021
|
+
let search = query ? querySerializer(query) : "";
|
|
1022
|
+
if (search.startsWith("?")) search = search.substring(1);
|
|
1023
|
+
if (search) url += `?${search}`;
|
|
1024
|
+
return url;
|
|
1025
|
+
};
|
|
1026
|
+
function getValidRequestBody(options) {
|
|
1027
|
+
const hasBody = options.body !== void 0;
|
|
1028
|
+
if (hasBody && options.bodySerializer) {
|
|
1029
|
+
if ("serializedBody" in options) return options.serializedBody !== void 0 && options.serializedBody !== "" ? options.serializedBody : null;
|
|
1030
|
+
return options.body !== "" ? options.body : null;
|
|
1031
|
+
}
|
|
1032
|
+
if (hasBody) return options.body;
|
|
1033
|
+
}
|
|
1034
|
+
//#endregion
|
|
1035
|
+
//#region ../../api-clients/hey-api-fetch-runtime/src/generated/core/auth.gen.ts
|
|
1036
|
+
const getAuthToken$1 = async (auth, callback) => {
|
|
1037
|
+
const token = typeof callback === "function" ? await callback(auth) : callback;
|
|
1038
|
+
if (!token) return;
|
|
1039
|
+
if (auth.scheme === "bearer") return `Bearer ${token}`;
|
|
1040
|
+
if (auth.scheme === "basic") return `Basic ${btoa(token)}`;
|
|
1041
|
+
return token;
|
|
1042
|
+
};
|
|
1043
|
+
//#endregion
|
|
1044
|
+
//#region ../../api-clients/hey-api-fetch-runtime/src/generated/client/utils.gen.ts
|
|
1045
|
+
const createQuerySerializer = ({ parameters = {}, ...args } = {}) => {
|
|
1046
|
+
const querySerializer = (queryParams) => {
|
|
1047
|
+
const search = [];
|
|
1048
|
+
if (queryParams && typeof queryParams === "object") for (const name in queryParams) {
|
|
1049
|
+
const value = queryParams[name];
|
|
1050
|
+
if (value === void 0 || value === null) continue;
|
|
1051
|
+
const options = parameters[name] || args;
|
|
1052
|
+
if (Array.isArray(value)) {
|
|
1053
|
+
const serializedArray = serializeArrayParam({
|
|
1054
|
+
allowReserved: options.allowReserved,
|
|
1055
|
+
explode: true,
|
|
1056
|
+
name,
|
|
1057
|
+
style: "form",
|
|
1058
|
+
value,
|
|
1059
|
+
...options.array
|
|
1060
|
+
});
|
|
1061
|
+
if (serializedArray) search.push(serializedArray);
|
|
1062
|
+
} else if (typeof value === "object") {
|
|
1063
|
+
const serializedObject = serializeObjectParam({
|
|
1064
|
+
allowReserved: options.allowReserved,
|
|
1065
|
+
explode: true,
|
|
1066
|
+
name,
|
|
1067
|
+
style: "deepObject",
|
|
1068
|
+
value,
|
|
1069
|
+
...options.object
|
|
1070
|
+
});
|
|
1071
|
+
if (serializedObject) search.push(serializedObject);
|
|
1072
|
+
} else {
|
|
1073
|
+
const serializedPrimitive = serializePrimitiveParam({
|
|
1074
|
+
allowReserved: options.allowReserved,
|
|
1075
|
+
name,
|
|
1076
|
+
value
|
|
1077
|
+
});
|
|
1078
|
+
if (serializedPrimitive) search.push(serializedPrimitive);
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
return search.join("&");
|
|
1082
|
+
};
|
|
1083
|
+
return querySerializer;
|
|
1084
|
+
};
|
|
1085
|
+
/**
|
|
1086
|
+
* Infers parseAs value from provided Content-Type header.
|
|
1087
|
+
*/
|
|
1088
|
+
const getParseAs = (contentType) => {
|
|
1089
|
+
if (!contentType) return "stream";
|
|
1090
|
+
const cleanContent = contentType.split(";")[0]?.trim();
|
|
1091
|
+
if (!cleanContent) return;
|
|
1092
|
+
if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) return "json";
|
|
1093
|
+
if (cleanContent === "multipart/form-data") return "formData";
|
|
1094
|
+
if ([
|
|
1095
|
+
"application/",
|
|
1096
|
+
"audio/",
|
|
1097
|
+
"image/",
|
|
1098
|
+
"video/"
|
|
1099
|
+
].some((type) => cleanContent.startsWith(type))) return "blob";
|
|
1100
|
+
if (cleanContent.startsWith("text/")) return "text";
|
|
1101
|
+
};
|
|
1102
|
+
const checkForExistence = (options, name) => {
|
|
1103
|
+
if (!name) return false;
|
|
1104
|
+
if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) return true;
|
|
1105
|
+
return false;
|
|
1106
|
+
};
|
|
1107
|
+
async function setAuthParams(options) {
|
|
1108
|
+
for (const auth of options.security ?? []) {
|
|
1109
|
+
if (checkForExistence(options, auth.name)) continue;
|
|
1110
|
+
const token = await getAuthToken$1(auth, options.auth);
|
|
1111
|
+
if (!token) continue;
|
|
1112
|
+
const name = auth.name ?? "Authorization";
|
|
1113
|
+
switch (auth.in) {
|
|
1114
|
+
case "query":
|
|
1115
|
+
if (!options.query) options.query = {};
|
|
1116
|
+
options.query[name] = token;
|
|
1117
|
+
break;
|
|
1118
|
+
case "cookie":
|
|
1119
|
+
options.headers.append("Cookie", `${name}=${token}`);
|
|
1120
|
+
break;
|
|
1121
|
+
default:
|
|
1122
|
+
options.headers.set(name, token);
|
|
1123
|
+
break;
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
const buildUrl = (options) => getUrl({
|
|
1128
|
+
baseUrl: options.baseUrl,
|
|
1129
|
+
path: options.path,
|
|
1130
|
+
query: options.query,
|
|
1131
|
+
querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
|
|
1132
|
+
url: options.url
|
|
1133
|
+
});
|
|
1134
|
+
const mergeConfigs = (a, b) => {
|
|
1135
|
+
const config = {
|
|
1136
|
+
...a,
|
|
1137
|
+
...b
|
|
1138
|
+
};
|
|
1139
|
+
if (config.baseUrl?.endsWith("/")) config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
|
|
1140
|
+
config.headers = mergeHeaders(a.headers, b.headers);
|
|
1141
|
+
return config;
|
|
1142
|
+
};
|
|
1143
|
+
const headersEntries = (headers) => {
|
|
1144
|
+
const entries = [];
|
|
1145
|
+
headers.forEach((value, key) => {
|
|
1146
|
+
entries.push([key, value]);
|
|
1147
|
+
});
|
|
1148
|
+
return entries;
|
|
1149
|
+
};
|
|
1150
|
+
const mergeHeaders = (...headers) => {
|
|
1151
|
+
const mergedHeaders = new Headers();
|
|
1152
|
+
for (const header of headers) {
|
|
1153
|
+
if (!header) continue;
|
|
1154
|
+
const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
|
|
1155
|
+
for (const [key, value] of iterator) if (value === null) mergedHeaders.delete(key);
|
|
1156
|
+
else if (Array.isArray(value)) for (const v of value) mergedHeaders.append(key, v);
|
|
1157
|
+
else if (value !== void 0) mergedHeaders.set(key, typeof value === "object" ? JSON.stringify(value) : value);
|
|
1158
|
+
}
|
|
1159
|
+
return mergedHeaders;
|
|
1160
|
+
};
|
|
1161
|
+
var Interceptors = class {
|
|
1162
|
+
fns = [];
|
|
1163
|
+
clear() {
|
|
1164
|
+
this.fns = [];
|
|
1165
|
+
}
|
|
1166
|
+
eject(id) {
|
|
1167
|
+
const index = this.getInterceptorIndex(id);
|
|
1168
|
+
if (this.fns[index]) this.fns[index] = null;
|
|
1169
|
+
}
|
|
1170
|
+
exists(id) {
|
|
1171
|
+
const index = this.getInterceptorIndex(id);
|
|
1172
|
+
return Boolean(this.fns[index]);
|
|
1173
|
+
}
|
|
1174
|
+
getInterceptorIndex(id) {
|
|
1175
|
+
if (typeof id === "number") return this.fns[id] ? id : -1;
|
|
1176
|
+
return this.fns.indexOf(id);
|
|
1177
|
+
}
|
|
1178
|
+
update(id, fn) {
|
|
1179
|
+
const index = this.getInterceptorIndex(id);
|
|
1180
|
+
if (this.fns[index]) {
|
|
1181
|
+
this.fns[index] = fn;
|
|
1182
|
+
return id;
|
|
1183
|
+
}
|
|
1184
|
+
return false;
|
|
1185
|
+
}
|
|
1186
|
+
use(fn) {
|
|
1187
|
+
this.fns.push(fn);
|
|
1188
|
+
return this.fns.length - 1;
|
|
1189
|
+
}
|
|
1190
|
+
};
|
|
1191
|
+
const createInterceptors = () => ({
|
|
1192
|
+
error: new Interceptors(),
|
|
1193
|
+
request: new Interceptors(),
|
|
1194
|
+
response: new Interceptors()
|
|
1195
|
+
});
|
|
1196
|
+
const defaultQuerySerializer = createQuerySerializer({
|
|
1197
|
+
allowReserved: false,
|
|
1198
|
+
array: {
|
|
1199
|
+
explode: true,
|
|
1200
|
+
style: "form"
|
|
1201
|
+
},
|
|
1202
|
+
object: {
|
|
1203
|
+
explode: true,
|
|
1204
|
+
style: "deepObject"
|
|
1205
|
+
}
|
|
1206
|
+
});
|
|
1207
|
+
const defaultHeaders = { "Content-Type": "application/json" };
|
|
1208
|
+
const createConfig = (override = {}) => ({
|
|
1209
|
+
...jsonBodySerializer,
|
|
1210
|
+
headers: defaultHeaders,
|
|
1211
|
+
parseAs: "auto",
|
|
1212
|
+
querySerializer: defaultQuerySerializer,
|
|
1213
|
+
...override
|
|
1214
|
+
});
|
|
1215
|
+
//#endregion
|
|
1216
|
+
//#region ../../api-clients/hey-api-fetch-runtime/src/generated/client/client.gen.ts
|
|
1217
|
+
const createClient = (config = {}) => {
|
|
1218
|
+
let _config = mergeConfigs(createConfig(), config);
|
|
1219
|
+
const getConfig = () => ({ ..._config });
|
|
1220
|
+
const setConfig = (config) => {
|
|
1221
|
+
_config = mergeConfigs(_config, config);
|
|
1222
|
+
return getConfig();
|
|
1223
|
+
};
|
|
1224
|
+
const interceptors = createInterceptors();
|
|
1225
|
+
const beforeRequest = async (options) => {
|
|
1226
|
+
const opts = {
|
|
1227
|
+
..._config,
|
|
1228
|
+
...options,
|
|
1229
|
+
fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
|
|
1230
|
+
headers: mergeHeaders(_config.headers, options.headers),
|
|
1231
|
+
serializedBody: void 0
|
|
1232
|
+
};
|
|
1233
|
+
if (opts.security) await setAuthParams(opts);
|
|
1234
|
+
if (opts.requestValidator) await opts.requestValidator(opts);
|
|
1235
|
+
if (opts.body !== void 0 && opts.bodySerializer) opts.serializedBody = opts.bodySerializer(opts.body);
|
|
1236
|
+
if (opts.body === void 0 || opts.serializedBody === "") opts.headers.delete("Content-Type");
|
|
1237
|
+
const resolvedOpts = opts;
|
|
1238
|
+
return {
|
|
1239
|
+
opts: resolvedOpts,
|
|
1240
|
+
url: buildUrl(resolvedOpts)
|
|
1241
|
+
};
|
|
1242
|
+
};
|
|
1243
|
+
const request = async (options) => {
|
|
1244
|
+
const throwOnError = options.throwOnError ?? _config.throwOnError;
|
|
1245
|
+
const responseStyle = options.responseStyle ?? _config.responseStyle;
|
|
1246
|
+
let request;
|
|
1247
|
+
let response;
|
|
1248
|
+
try {
|
|
1249
|
+
const { opts, url } = await beforeRequest(options);
|
|
1250
|
+
const requestInit = {
|
|
1251
|
+
redirect: "follow",
|
|
1252
|
+
...opts,
|
|
1253
|
+
body: getValidRequestBody(opts)
|
|
1254
|
+
};
|
|
1255
|
+
request = new Request(url, requestInit);
|
|
1256
|
+
for (const fn of interceptors.request.fns) if (fn) request = await fn(request, opts);
|
|
1257
|
+
const _fetch = opts.fetch;
|
|
1258
|
+
response = await _fetch(request);
|
|
1259
|
+
for (const fn of interceptors.response.fns) if (fn) response = await fn(response, request, opts);
|
|
1260
|
+
const result = {
|
|
1261
|
+
request,
|
|
1262
|
+
response
|
|
1263
|
+
};
|
|
1264
|
+
if (response.ok) {
|
|
1265
|
+
const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
|
|
1266
|
+
if (response.status === 204 || response.headers.get("Content-Length") === "0") {
|
|
1267
|
+
let emptyData;
|
|
1268
|
+
switch (parseAs) {
|
|
1269
|
+
case "arrayBuffer":
|
|
1270
|
+
case "blob":
|
|
1271
|
+
case "text":
|
|
1272
|
+
emptyData = await response[parseAs]();
|
|
1273
|
+
break;
|
|
1274
|
+
case "formData":
|
|
1275
|
+
emptyData = new FormData();
|
|
1276
|
+
break;
|
|
1277
|
+
case "stream":
|
|
1278
|
+
emptyData = response.body;
|
|
1279
|
+
break;
|
|
1280
|
+
default:
|
|
1281
|
+
emptyData = {};
|
|
1282
|
+
break;
|
|
1283
|
+
}
|
|
1284
|
+
return opts.responseStyle === "data" ? emptyData : {
|
|
1285
|
+
data: emptyData,
|
|
1286
|
+
...result
|
|
1287
|
+
};
|
|
1288
|
+
}
|
|
1289
|
+
let data;
|
|
1290
|
+
switch (parseAs) {
|
|
1291
|
+
case "arrayBuffer":
|
|
1292
|
+
case "blob":
|
|
1293
|
+
case "formData":
|
|
1294
|
+
case "text":
|
|
1295
|
+
data = await response[parseAs]();
|
|
1296
|
+
break;
|
|
1297
|
+
case "json": {
|
|
1298
|
+
const text = await response.text();
|
|
1299
|
+
data = text ? JSON.parse(text) : {};
|
|
1300
|
+
break;
|
|
1301
|
+
}
|
|
1302
|
+
case "stream": return opts.responseStyle === "data" ? response.body : {
|
|
1303
|
+
data: response.body,
|
|
1304
|
+
...result
|
|
1305
|
+
};
|
|
1306
|
+
}
|
|
1307
|
+
if (parseAs === "json") {
|
|
1308
|
+
if (opts.responseValidator) await opts.responseValidator(data);
|
|
1309
|
+
if (opts.responseTransformer) data = await opts.responseTransformer(data);
|
|
1310
|
+
}
|
|
1311
|
+
return opts.responseStyle === "data" ? data : {
|
|
1312
|
+
data,
|
|
1313
|
+
...result
|
|
1314
|
+
};
|
|
1315
|
+
}
|
|
1316
|
+
const textError = await response.text();
|
|
1317
|
+
let jsonError;
|
|
1318
|
+
try {
|
|
1319
|
+
jsonError = JSON.parse(textError);
|
|
1320
|
+
} catch {}
|
|
1321
|
+
throw jsonError ?? textError;
|
|
1322
|
+
} catch (error) {
|
|
1323
|
+
let finalError = error;
|
|
1324
|
+
for (const fn of interceptors.error.fns) if (fn) finalError = await fn(finalError, response, request, options);
|
|
1325
|
+
finalError = finalError || {};
|
|
1326
|
+
if (throwOnError) throw finalError;
|
|
1327
|
+
return responseStyle === "data" ? void 0 : {
|
|
1328
|
+
error: finalError,
|
|
1329
|
+
request,
|
|
1330
|
+
response
|
|
1331
|
+
};
|
|
1332
|
+
}
|
|
1333
|
+
};
|
|
1334
|
+
const makeMethodFn = (method) => (options) => request({
|
|
1335
|
+
...options,
|
|
1336
|
+
method
|
|
1337
|
+
});
|
|
1338
|
+
const makeSseFn = (method) => async (options) => {
|
|
1339
|
+
const { opts, url } = await beforeRequest(options);
|
|
1340
|
+
return createSseClient({
|
|
1341
|
+
...opts,
|
|
1342
|
+
body: opts.body,
|
|
1343
|
+
method,
|
|
1344
|
+
onRequest: async (url, init) => {
|
|
1345
|
+
let request = new Request(url, init);
|
|
1346
|
+
for (const fn of interceptors.request.fns) if (fn) request = await fn(request, opts);
|
|
1347
|
+
return request;
|
|
1348
|
+
},
|
|
1349
|
+
serializedBody: getValidRequestBody(opts),
|
|
1350
|
+
url
|
|
1351
|
+
});
|
|
1352
|
+
};
|
|
1353
|
+
const _buildUrl = (options) => buildUrl({
|
|
1354
|
+
..._config,
|
|
1355
|
+
...options
|
|
1356
|
+
});
|
|
1357
|
+
return {
|
|
1358
|
+
buildUrl: _buildUrl,
|
|
1359
|
+
connect: makeMethodFn("CONNECT"),
|
|
1360
|
+
delete: makeMethodFn("DELETE"),
|
|
1361
|
+
get: makeMethodFn("GET"),
|
|
1362
|
+
getConfig,
|
|
1363
|
+
head: makeMethodFn("HEAD"),
|
|
1364
|
+
interceptors,
|
|
1365
|
+
options: makeMethodFn("OPTIONS"),
|
|
1366
|
+
patch: makeMethodFn("PATCH"),
|
|
1367
|
+
post: makeMethodFn("POST"),
|
|
1368
|
+
put: makeMethodFn("PUT"),
|
|
1369
|
+
request,
|
|
1370
|
+
setConfig,
|
|
1371
|
+
sse: {
|
|
1372
|
+
connect: makeSseFn("CONNECT"),
|
|
1373
|
+
delete: makeSseFn("DELETE"),
|
|
1374
|
+
get: makeSseFn("GET"),
|
|
1375
|
+
head: makeSseFn("HEAD"),
|
|
1376
|
+
options: makeSseFn("OPTIONS"),
|
|
1377
|
+
patch: makeSseFn("PATCH"),
|
|
1378
|
+
post: makeSseFn("POST"),
|
|
1379
|
+
put: makeSseFn("PUT"),
|
|
1380
|
+
trace: makeSseFn("TRACE")
|
|
1381
|
+
},
|
|
1382
|
+
trace: makeMethodFn("TRACE")
|
|
1383
|
+
};
|
|
1384
|
+
};
|
|
1385
|
+
//#endregion
|
|
1386
|
+
//#region ../../api-clients/identity/src/hey-api-client.ts
|
|
1387
|
+
function isAbortError(error) {
|
|
1388
|
+
return error instanceof DOMException && error.name === "AbortError" || error instanceof Error && error.name === "AbortError";
|
|
1389
|
+
}
|
|
1390
|
+
/**
|
|
1391
|
+
* Creates an identity service Hey API client with the shared ApiError shape.
|
|
1392
|
+
*
|
|
1393
|
+
* Only bearer credentials are ever attached. Confidential clients that
|
|
1394
|
+
* authenticate with HTTP Basic are servers and do not use this package.
|
|
1395
|
+
*/
|
|
1396
|
+
function createIdentityHeyApiClient(config) {
|
|
1397
|
+
const client = createClient({
|
|
1398
|
+
auth: async (auth) => {
|
|
1399
|
+
if (auth.scheme !== "bearer") return void 0;
|
|
1400
|
+
return await config.getAccessToken?.() ?? void 0;
|
|
1401
|
+
},
|
|
1402
|
+
baseUrl: config.baseUrl,
|
|
1403
|
+
credentials: config.credentials ?? "include",
|
|
1404
|
+
fetch: config.fetch,
|
|
1405
|
+
headers: {
|
|
1406
|
+
Accept: "application/json",
|
|
1407
|
+
...config.defaultHeaders
|
|
1408
|
+
},
|
|
1409
|
+
throwOnError: true
|
|
1410
|
+
});
|
|
1411
|
+
client.interceptors.error.use(createHeyApiErrorInterceptor({
|
|
1412
|
+
onResponseError: (response) => {
|
|
1413
|
+
if (response.status === 401) config.onAuthError?.();
|
|
1414
|
+
},
|
|
1415
|
+
shouldPassThroughTransportError: isAbortError
|
|
1416
|
+
}));
|
|
1417
|
+
return client;
|
|
1418
|
+
}
|
|
1419
|
+
const OAUTH_ERROR_CODES = new Set([
|
|
1420
|
+
"invalid_request",
|
|
1421
|
+
"invalid_client",
|
|
1422
|
+
"invalid_grant",
|
|
1423
|
+
"unauthorized_client",
|
|
1424
|
+
"unsupported_grant_type",
|
|
1425
|
+
"invalid_scope",
|
|
1426
|
+
"invalid_target",
|
|
1427
|
+
"invalid_token",
|
|
1428
|
+
"login_required",
|
|
1429
|
+
"access_denied",
|
|
1430
|
+
"account_selection_required",
|
|
1431
|
+
"server_error",
|
|
1432
|
+
"temporarily_unavailable",
|
|
1433
|
+
"slow_down"
|
|
1434
|
+
]);
|
|
1435
|
+
/** Narrows an unknown string to an RFC 6749 error code from the contract. */
|
|
1436
|
+
function isOAuthErrorCode(value) {
|
|
1437
|
+
return typeof value === "string" && OAUTH_ERROR_CODES.has(value);
|
|
1438
|
+
}
|
|
1439
|
+
/**
|
|
1440
|
+
* Reads the RFC 6749 `error` code from a failed identity call, or null when the
|
|
1441
|
+
* failure carried none (a network error, or a body of another shape).
|
|
1442
|
+
*/
|
|
1443
|
+
function oauthErrorCode(error) {
|
|
1444
|
+
if (!(error instanceof ApiError)) return null;
|
|
1445
|
+
const code = error.body?.error;
|
|
1446
|
+
return isOAuthErrorCode(code) ? code : null;
|
|
1447
|
+
}
|
|
1448
|
+
//#endregion
|
|
1449
|
+
//#region ../../api-clients/identity/src/hey-api/sdk.gen.ts
|
|
1450
|
+
/**
|
|
1451
|
+
* Token endpoint
|
|
1452
|
+
*
|
|
1453
|
+
* One endpoint for every grant. Browser clients omit `refresh_token` and
|
|
1454
|
+
* send the per-client HttpOnly refresh cookie on a credentialed request.
|
|
1455
|
+
* Native and confidential clients send `refresh_token` in the body.
|
|
1456
|
+
*
|
|
1457
|
+
* Token exchange (RFC 8693) serves company switch, role narrowing, and
|
|
1458
|
+
* root-admin company entry (Phase 007 FR-3, FR-4). The caller presents
|
|
1459
|
+
* its own live principal access token as `subject_token`: the token
|
|
1460
|
+
* must have been issued by this service to the calling client, so an
|
|
1461
|
+
* exchange never moves a token between applications. What the new
|
|
1462
|
+
* token may name is read from the synced directory at that moment, and
|
|
1463
|
+
* it can never name a company or a role the subject does not hold
|
|
1464
|
+
* there:
|
|
1465
|
+
*
|
|
1466
|
+
* - Company switch: `org` names another company. The subject needs an
|
|
1467
|
+
* active, unlocked membership there, in a company that is active and
|
|
1468
|
+
* either carries the sign-in flag or is reported eligible; one that is
|
|
1469
|
+
* neither is refused `invalid_target` as not yet available on the new
|
|
1470
|
+
* sign-in. `roles` defaults to that membership's role.
|
|
1471
|
+
* - Role narrowing: `org` is omitted or names the token's own company,
|
|
1472
|
+
* and `roles` lists fewer roles. Each must be held in that company now
|
|
1473
|
+
* and rank no higher than the subject token's roles (`root_admin`
|
|
1474
|
+
* over `admin` over `rep`); nothing may add a role within that
|
|
1475
|
+
* company (`invalid_scope`). Narrowing is a view, not a boundary: a
|
|
1476
|
+
* switch answers with the target membership's role, so a narrowed
|
|
1477
|
+
* token that switches away and back holds what the directory holds.
|
|
1478
|
+
* `org` is compared case-insensitively, so the token's own company
|
|
1479
|
+
* in any case is a narrowing, and it must be a uuid
|
|
1480
|
+
* (`invalid_request`); the new token names it in lower case.
|
|
1481
|
+
* - Company entry: a root admin's token, platform-scoped or already in
|
|
1482
|
+
* another company, names any active company without a membership.
|
|
1483
|
+
* The new token keeps `root_admin`. Any other token asking the same
|
|
1484
|
+
* is refused `invalid_target`.
|
|
1485
|
+
*
|
|
1486
|
+
* A role is held only as Rails grants it, because Rails checks a
|
|
1487
|
+
* token's roles against its own records and refuses one it would not
|
|
1488
|
+
* grant: `admin` through an admin membership, `rep` through a rep
|
|
1489
|
+
* membership, and `root_admin` through the principal's flag. The
|
|
1490
|
+
* directory reads `rep` from the membership's role or its
|
|
1491
|
+
* `rep_standing`, so an admin whom Rails also holds as a rep, and a
|
|
1492
|
+
* root admin who is a rep in the company, can narrow to `rep`; an
|
|
1493
|
+
* admin membership alone does not hold it, so an admin with no rep
|
|
1494
|
+
* membership cannot.
|
|
1495
|
+
*
|
|
1496
|
+
* The new token keeps the subject token's `sub`, `sid`, `auth_time`,
|
|
1497
|
+
* and `amr`; the target company's session bound and flush apply, and
|
|
1498
|
+
* past them the exchange is refused `invalid_grant`. It never expires
|
|
1499
|
+
* later than the subject token, so it may carry less than the usual
|
|
1500
|
+
* lifetime, and the subject token stays valid until its own expiry.
|
|
1501
|
+
* The response carries no refresh token and the caller's refresh chain
|
|
1502
|
+
* does not move: a caller that stays in the target company exchanges
|
|
1503
|
+
* again after it refreshes. Revoking a token revokes every token
|
|
1504
|
+
* exchanged from it, on introspection and on the revocation list, and
|
|
1505
|
+
* an exchanged token introspects inactive once the directory no longer
|
|
1506
|
+
* entitles it to its company and roles. Every exchange, issued,
|
|
1507
|
+
* withheld, or refused, writes an audit record naming the subject, the
|
|
1508
|
+
* source and target organizations, and the grant type.
|
|
1509
|
+
*
|
|
1510
|
+
* A request authenticated by the refresh *cookie* must carry an `Origin`
|
|
1511
|
+
* that is registered for the client named in `client_id`, derived from
|
|
1512
|
+
* that client's redirect URIs. A missing, `null`, or non-matching
|
|
1513
|
+
* Origin is refused with `invalid_request`, the cookie is never
|
|
1514
|
+
* consulted, and nothing is rotated. The refresh cookies are
|
|
1515
|
+
* `SameSite=None` so that a first-party app can refresh from its own
|
|
1516
|
+
* origin, which means any page could otherwise make the browser attach
|
|
1517
|
+
* another client's cookie: a page on one registered client's origin
|
|
1518
|
+
* naming a second client would have read the second client's access
|
|
1519
|
+
* token out of the response, and a cross-site form post could have
|
|
1520
|
+
* rotated a chain from anywhere. `Access-Control-Allow-Origin` is
|
|
1521
|
+
* likewise echoed only for the origin of the client named in the
|
|
1522
|
+
* request. Body-token requests from native and confidential clients
|
|
1523
|
+
* consult no cookie and are unaffected.
|
|
1524
|
+
*
|
|
1525
|
+
* Client authentication depends on the grant, which an OpenAPI security
|
|
1526
|
+
* requirement cannot express because it applies to the whole
|
|
1527
|
+
* operation. `x-client-authentication` states the rule and
|
|
1528
|
+
* implementations must enforce it: `client_credentials` always requires
|
|
1529
|
+
* HTTP Basic client authentication and answers 401 `invalid_client`
|
|
1530
|
+
* without it. Token exchange takes HTTP Basic from a confidential client
|
|
1531
|
+
* or `client_id` from a public one, whose proof is that the subject
|
|
1532
|
+
* token was issued to it; a request that identifies no client is
|
|
1533
|
+
* answered 401 `invalid_client`. The anonymous alternative exists
|
|
1534
|
+
* otherwise only for public clients redeeming a code with PKCE or
|
|
1535
|
+
* refreshing.
|
|
1536
|
+
*
|
|
1537
|
+
*
|
|
1538
|
+
* One exception (Phase 008 FR-3): a publishable client, the successor
|
|
1539
|
+
* of a public token, has no secret. It asks for `client_credentials` by
|
|
1540
|
+
* naming itself with `client_id` in a simple form post, with no
|
|
1541
|
+
* Authorization header, from a page whose `Origin` matches its allowed
|
|
1542
|
+
* origins. Any other origin, or none, is answered 401
|
|
1543
|
+
* `invalid_client`. Its origin is echoed in
|
|
1544
|
+
* `Access-Control-Allow-Origin` without
|
|
1545
|
+
* `Access-Control-Allow-Credentials`, and is never on the preflight
|
|
1546
|
+
* allow-list of the credentialed endpoints. Its token carries
|
|
1547
|
+
* `allowed_origins`, so a resource server can refuse it from anywhere
|
|
1548
|
+
* else without asking this service.
|
|
1549
|
+
*
|
|
1550
|
+
* A grant type this endpoint does not serve answers 400
|
|
1551
|
+
* `unsupported_grant_type` before the client is looked at, whatever
|
|
1552
|
+
* credentials came with it.
|
|
1553
|
+
*
|
|
1554
|
+
* A client mirrored from Rails' OAuth::Client registrations (Phase 008
|
|
1555
|
+
* FR-6) is issued for with the v202610 rules it was registered under:
|
|
1556
|
+
* no `scope` receives its default scope, unknown scopes are dropped
|
|
1557
|
+
* rather than refused, and only a request that leaves nothing is
|
|
1558
|
+
* `invalid_scope`. Its `resource` is `urn:fluid:store:<uuid>`: a
|
|
1559
|
+
* droplet must send one and is issued for a store only while it is
|
|
1560
|
+
* installed there, with the scopes the installation grants; a platform
|
|
1561
|
+
* client may name any store; any other client may name none. A
|
|
1562
|
+
* resource that is sent but blank is `invalid_target`, never treated
|
|
1563
|
+
* as absent.
|
|
1564
|
+
*
|
|
1565
|
+
* A mirrored client's `authorization_code` grant redeems a code Rails'
|
|
1566
|
+
* consent screen minted through `POST /internal/oauth/codes`, with
|
|
1567
|
+
* OAuth::CodeRedeemer's checks in its order: the code, `client_id`, and
|
|
1568
|
+
* `redirect_uri` are required (`invalid_request`); the code must be
|
|
1569
|
+
* this client's, for exactly this `redirect_uri`, unused and unexpired
|
|
1570
|
+
* (`invalid_grant`); a code minted with a challenge needs its S256
|
|
1571
|
+
* `code_verifier` (`invalid_request` when missing, `invalid_grant`
|
|
1572
|
+
* when wrong). A refused redemption does not spend the code. A code
|
|
1573
|
+
* owned by an MCP authorization or an analytics consent is refused
|
|
1574
|
+
* `invalid_grant`, unspent: its resource redeems it. Any client
|
|
1575
|
+
* authentication failure is a 401 for a mirrored client. The answer is
|
|
1576
|
+
* a `typ: client` token with the code's scope and store, and, when the
|
|
1577
|
+
* client may refresh, an opaque `frt_` refresh token.
|
|
1578
|
+
*
|
|
1579
|
+
* A `frt_` refresh token is judged before its client, as Rails judges
|
|
1580
|
+
* it: unknown is `invalid_grant`; a confidential client's token needs
|
|
1581
|
+
* that client's Basic credentials (401 `invalid_client`); a public
|
|
1582
|
+
* client's token must name its client in `client_id`
|
|
1583
|
+
* (`invalid_request` when it names none, `invalid_grant` when it
|
|
1584
|
+
* names another). A token presented again after it rotated is a
|
|
1585
|
+
* replay: its whole family is revoked, with every unexpired access
|
|
1586
|
+
* token issued from it, and the answer is `invalid_grant`. Two
|
|
1587
|
+
* attempts of one relay operation that race, one finding the token
|
|
1588
|
+
* the other just spent, are one refresh: the loser is answered 503
|
|
1589
|
+
* `temporarily_unavailable` and the family stands.
|
|
1590
|
+
*
|
|
1591
|
+
* A client mirrored from Rails is answered only through Rails' relay:
|
|
1592
|
+
* every grant for one must carry Rails' own credential in
|
|
1593
|
+
* `Fluid-Relay-Authorization` (services/identity/README.md, "Rate
|
|
1594
|
+
* limits"), since Rails checks the client against its current
|
|
1595
|
+
* record first. Asked directly, the answer is 400
|
|
1596
|
+
* `unauthorized_client` and nothing is spent. A requested `scope` may narrow the token's
|
|
1597
|
+
* but never widen it (`invalid_scope`). A refresh request that names no
|
|
1598
|
+
* client and carries no `frt_` token answers `invalid_request` when the
|
|
1599
|
+
* token is missing and `invalid_grant` otherwise.
|
|
1600
|
+
*
|
|
1601
|
+
*/
|
|
1602
|
+
const createToken = (options) => options.client.post({
|
|
1603
|
+
...urlSearchParamsBodySerializer,
|
|
1604
|
+
responseStyle: "data",
|
|
1605
|
+
security: [{
|
|
1606
|
+
scheme: "basic",
|
|
1607
|
+
type: "http"
|
|
1608
|
+
}],
|
|
1609
|
+
url: "/token",
|
|
1610
|
+
...options,
|
|
1611
|
+
headers: {
|
|
1612
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
1613
|
+
...options.headers
|
|
1614
|
+
}
|
|
1615
|
+
});
|
|
1616
|
+
/**
|
|
1617
|
+
* Session facts for the presented principal token
|
|
1618
|
+
*
|
|
1619
|
+
* Returns the facts a first-party app may show or branch on, so that no
|
|
1620
|
+
* app decodes a token (Phase 006 FR-1). Answers 401 for an expired or
|
|
1621
|
+
* malformed token, a client token, or a token whose session was revoked.
|
|
1622
|
+
* Browser callers on a registered client origin are allowed by CORS.
|
|
1623
|
+
*
|
|
1624
|
+
*/
|
|
1625
|
+
const getUserinfo = (options) => options.client.get({
|
|
1626
|
+
responseStyle: "data",
|
|
1627
|
+
security: [{
|
|
1628
|
+
scheme: "bearer",
|
|
1629
|
+
type: "http"
|
|
1630
|
+
}],
|
|
1631
|
+
url: "/userinfo",
|
|
1632
|
+
...options
|
|
1633
|
+
});
|
|
1634
|
+
/**
|
|
1635
|
+
* RFC 7009 revocation
|
|
1636
|
+
*
|
|
1637
|
+
* Revoking a refresh token revokes its session, which is how sign-out
|
|
1638
|
+
* ends every app on that session at once (INV-13). Revoking a v202610
|
|
1639
|
+
* refresh token (`frt_`) ends its family with every access token issued
|
|
1640
|
+
* from it, as Rails revokes one (`OAuth::TokenRevoker#revoke_family`).
|
|
1641
|
+
*
|
|
1642
|
+
* The token must have been issued to the calling client (RFC 7009
|
|
1643
|
+
* section 2.1). A caller that presents another client's token is
|
|
1644
|
+
* answered `200` with nothing revoked, exactly as an unknown token is:
|
|
1645
|
+
* telling the two apart would turn this endpoint into an oracle for
|
|
1646
|
+
* which token strings are live. The refusal is audited.
|
|
1647
|
+
*
|
|
1648
|
+
* Two ways to call it. A confidential client authenticates with HTTP
|
|
1649
|
+
* Basic. A public client -- a browser or native app signing out, which
|
|
1650
|
+
* has no secret to present -- names itself with `client_id` and proves
|
|
1651
|
+
* itself with the token: a public caller may revoke only a token
|
|
1652
|
+
* already issued to that same client. A browser client may omit `token`
|
|
1653
|
+
* and send its per-client refresh cookie instead.
|
|
1654
|
+
*
|
|
1655
|
+
* A request authenticated by that cookie must carry an `Origin`
|
|
1656
|
+
* registered for the client named in `client_id`, derived from its
|
|
1657
|
+
* redirect URIs. A missing, `null`, or non-matching Origin is refused
|
|
1658
|
+
* with `400 invalid_request`, the cookie is never consulted and nothing
|
|
1659
|
+
* is revoked. Without that rule the `SameSite=None` refresh cookie
|
|
1660
|
+
* would make sign-out forgeable: a cross-site form post, which needs no
|
|
1661
|
+
* CORS preflight, could end anyone's identity session. The refusal is
|
|
1662
|
+
* an error rather than the `200` a non-owner gets, because no token is
|
|
1663
|
+
* ever looked up, so it discloses nothing.
|
|
1664
|
+
*
|
|
1665
|
+
*/
|
|
1666
|
+
const revokeToken = (options) => options.client.post({
|
|
1667
|
+
...urlSearchParamsBodySerializer,
|
|
1668
|
+
responseStyle: "data",
|
|
1669
|
+
security: [{
|
|
1670
|
+
scheme: "basic",
|
|
1671
|
+
type: "http"
|
|
1672
|
+
}],
|
|
1673
|
+
url: "/revoke",
|
|
1674
|
+
...options,
|
|
1675
|
+
headers: {
|
|
1676
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
1677
|
+
...options.headers
|
|
1678
|
+
}
|
|
1679
|
+
});
|
|
1680
|
+
//#endregion
|
|
1681
|
+
//#region ../../platform/auth/src/constants.ts
|
|
1682
|
+
/**
|
|
1683
|
+
* Auth Constants
|
|
1684
|
+
*
|
|
1685
|
+
* These constants define the default values for authentication
|
|
1686
|
+
* configuration and storage keys.
|
|
1687
|
+
*/
|
|
1688
|
+
/**
|
|
1689
|
+
* Authentication-related constants with sensible defaults.
|
|
1690
|
+
*/
|
|
1691
|
+
const AUTH_CONSTANTS = {
|
|
1692
|
+
TOKEN_GRACE_PERIOD_MS: 3e4,
|
|
1693
|
+
COOKIE_MAX_AGE: 777600
|
|
1694
|
+
};
|
|
1695
|
+
//#endregion
|
|
1696
|
+
//#region ../../platform/auth/src/session/facts.ts
|
|
1697
|
+
/** Maps `/userinfo` onto the facts an app reads. */
|
|
1698
|
+
function toSessionFacts(info, expiresAt, exchanged = false) {
|
|
1699
|
+
const actor = info.act?.sub ?? null;
|
|
1700
|
+
return {
|
|
1701
|
+
subject: info.sub,
|
|
1702
|
+
companyId: info.org ?? null,
|
|
1703
|
+
roles: [...info.roles],
|
|
1704
|
+
actor,
|
|
1705
|
+
impersonating: actor !== null,
|
|
1706
|
+
sessionId: info.sid,
|
|
1707
|
+
authTime: info.auth_time,
|
|
1708
|
+
authMethods: [...info.amr],
|
|
1709
|
+
expiresAt,
|
|
1710
|
+
exchanged
|
|
1711
|
+
};
|
|
1712
|
+
}
|
|
1713
|
+
//#endregion
|
|
1714
|
+
//#region ../../platform/auth/src/session/pkce.ts
|
|
1715
|
+
function base64Url(bytes) {
|
|
1716
|
+
let binary = "";
|
|
1717
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
1718
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
1719
|
+
}
|
|
1720
|
+
function randomString(byteLength, cryptoImpl) {
|
|
1721
|
+
const bytes = new Uint8Array(byteLength);
|
|
1722
|
+
cryptoImpl.getRandomValues(bytes);
|
|
1723
|
+
return base64Url(bytes);
|
|
1724
|
+
}
|
|
1725
|
+
/** A 43-character verifier from 32 random bytes, the RFC 7636 minimum. */
|
|
1726
|
+
function createCodeVerifier(cryptoImpl = crypto) {
|
|
1727
|
+
return randomString(32, cryptoImpl);
|
|
1728
|
+
}
|
|
1729
|
+
/** An unguessable `state` binding the callback to this tab's request. */
|
|
1730
|
+
function createState(cryptoImpl = crypto) {
|
|
1731
|
+
return randomString(32, cryptoImpl);
|
|
1732
|
+
}
|
|
1733
|
+
/** `BASE64URL(SHA256(verifier))`, the S256 challenge. */
|
|
1734
|
+
async function createCodeChallenge(verifier, cryptoImpl = crypto) {
|
|
1735
|
+
const digest = await cryptoImpl.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
|
|
1736
|
+
return base64Url(new Uint8Array(digest));
|
|
1737
|
+
}
|
|
1738
|
+
//#endregion
|
|
1739
|
+
//#region ../../platform/auth/src/session/refresher.ts
|
|
1740
|
+
/**
|
|
1741
|
+
* Single-flight refresh (INV-6.6).
|
|
1742
|
+
*
|
|
1743
|
+
* Every caller that finds the token stale shares one in-flight refresh, so
|
|
1744
|
+
* twenty concurrent requests with an expired token cause one call to the
|
|
1745
|
+
* identity service, and one fallback redirect if it fails.
|
|
1746
|
+
*
|
|
1747
|
+
* Refresh is a credentialed request to the identity domain that relies on its
|
|
1748
|
+
* HttpOnly, per-client refresh cookie; the page never holds a refresh token
|
|
1749
|
+
* (INV-6.2). When the browser cannot send that cookie, for example because it
|
|
1750
|
+
* blocks third-party cookies, the identity service refuses the grant and the
|
|
1751
|
+
* session falls back to the silent `prompt=none` redirect.
|
|
1752
|
+
*/
|
|
1753
|
+
function createRefresher(run) {
|
|
1754
|
+
let inflight = null;
|
|
1755
|
+
return {
|
|
1756
|
+
refresh() {
|
|
1757
|
+
inflight ??= run().finally(() => {
|
|
1758
|
+
inflight = null;
|
|
1759
|
+
});
|
|
1760
|
+
return inflight;
|
|
1761
|
+
},
|
|
1762
|
+
inFlight() {
|
|
1763
|
+
return inflight !== null;
|
|
1764
|
+
}
|
|
1765
|
+
};
|
|
1766
|
+
}
|
|
1767
|
+
function classifyRefreshFailure(error) {
|
|
1768
|
+
const code = oauthErrorCode(error);
|
|
1769
|
+
if (code === "temporarily_unavailable" || code === "slow_down" || code === "server_error") return "unavailable";
|
|
1770
|
+
if (code) return "rejected";
|
|
1771
|
+
if (isApiError(error)) return error.status === 0 || error.status >= 500 || error.status === 429 ? "unavailable" : "rejected";
|
|
1772
|
+
return "unavailable";
|
|
1773
|
+
}
|
|
1774
|
+
//#endregion
|
|
1775
|
+
//#region ../../platform/auth/src/session/types.ts
|
|
1776
|
+
var SessionError = class extends Error {
|
|
1777
|
+
code;
|
|
1778
|
+
constructor(code, message) {
|
|
1779
|
+
super(message ?? code);
|
|
1780
|
+
this.name = "SessionError";
|
|
1781
|
+
this.code = code;
|
|
1782
|
+
}
|
|
1783
|
+
};
|
|
1784
|
+
//#endregion
|
|
1785
|
+
//#region ../../platform/auth/src/native/secure-session.ts
|
|
1786
|
+
/**
|
|
1787
|
+
* Native secure session: the authorization code flow with PKCE for public
|
|
1788
|
+
* clients that are not browsers (the CLI, `apps/mist-desktop`,
|
|
1789
|
+
* `apps/portal-mobile`), FR-7.
|
|
1790
|
+
*
|
|
1791
|
+
* The client opens the system browser at the URL `beginSignIn()` returns and
|
|
1792
|
+
* hands the redirect it receives (a loopback request for the CLI and
|
|
1793
|
+
* desktop, an app-claimed link on mobile) to `completeSignIn()`. The rotating
|
|
1794
|
+
* refresh token then lives only in the injected {@link SecureStorage}, which
|
|
1795
|
+
* each client backs with its operating system's credential store (INV-6.2);
|
|
1796
|
+
* the access token lives only in memory. A restart restores the session from
|
|
1797
|
+
* storage without a prompt. Facts come from `/userinfo`, never from decoding
|
|
1798
|
+
* a token (INV-6.3).
|
|
1799
|
+
*
|
|
1800
|
+
* Nothing here touches `window`, the DOM, cookies, or Web Storage, so it runs
|
|
1801
|
+
* in Node, Electron's main process, and React Native alike.
|
|
1802
|
+
*/
|
|
1803
|
+
/**
|
|
1804
|
+
* The longest sign-out waits for a sign-in or refresh already in flight
|
|
1805
|
+
* before it revokes regardless.
|
|
1806
|
+
*/
|
|
1807
|
+
const SIGN_OUT_WAIT_MS = 5e3;
|
|
1808
|
+
function sameRedirect(callback, redirectUri) {
|
|
1809
|
+
return callback.protocol === redirectUri.protocol && callback.host === redirectUri.host && callback.pathname === redirectUri.pathname;
|
|
1810
|
+
}
|
|
1811
|
+
function createNativeSession(config) {
|
|
1812
|
+
const now = config.now ?? Date.now;
|
|
1813
|
+
const storageKey = config.storageKey ?? `fluid-identity.${config.clientId}`;
|
|
1814
|
+
let storageQueue = Promise.resolve();
|
|
1815
|
+
function serial(operation) {
|
|
1816
|
+
const next = storageQueue.then(operation, operation);
|
|
1817
|
+
storageQueue = next.catch(() => void 0);
|
|
1818
|
+
return next;
|
|
1819
|
+
}
|
|
1820
|
+
const store = {
|
|
1821
|
+
get: () => serial(() => config.storage.get(storageKey)),
|
|
1822
|
+
set: (value) => serial(() => config.storage.set(storageKey, value)),
|
|
1823
|
+
delete: () => serial(() => config.storage.delete(storageKey)),
|
|
1824
|
+
deleteIf: (value) => serial(async () => {
|
|
1825
|
+
if (await config.storage.get(storageKey) === value) await config.storage.delete(storageKey);
|
|
1826
|
+
})
|
|
1827
|
+
};
|
|
1828
|
+
const grace = AUTH_CONSTANTS.TOKEN_GRACE_PERIOD_MS;
|
|
1829
|
+
let held = null;
|
|
1830
|
+
let pending = null;
|
|
1831
|
+
let snapshot = {
|
|
1832
|
+
status: "idle",
|
|
1833
|
+
facts: null,
|
|
1834
|
+
error: null
|
|
1835
|
+
};
|
|
1836
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
1837
|
+
let generation = 0;
|
|
1838
|
+
let signOutsRunning = 0;
|
|
1839
|
+
const client = createIdentityHeyApiClient({
|
|
1840
|
+
baseUrl: config.identityUrl,
|
|
1841
|
+
credentials: "omit",
|
|
1842
|
+
fetch: config.fetch,
|
|
1843
|
+
getAccessToken: () => held?.accessToken
|
|
1844
|
+
});
|
|
1845
|
+
function update(patch) {
|
|
1846
|
+
snapshot = {
|
|
1847
|
+
...snapshot,
|
|
1848
|
+
...patch
|
|
1849
|
+
};
|
|
1850
|
+
for (const listener of listeners) listener(snapshot);
|
|
1851
|
+
}
|
|
1852
|
+
/**
|
|
1853
|
+
* Keeps a newly issued token pair: the refresh token goes to secure storage
|
|
1854
|
+
* before the access token is used, so a crash cannot lose a rotation the
|
|
1855
|
+
* server has already made. A response without a refresh token (the reuse
|
|
1856
|
+
* grace absorbed a concurrent rotation) keeps the stored one.
|
|
1857
|
+
*/
|
|
1858
|
+
async function adopt(token, started) {
|
|
1859
|
+
if (started !== generation) {
|
|
1860
|
+
if (token.refresh_token) await revokeQuietly(token.refresh_token);
|
|
1861
|
+
throw new SessionError("not_signed_in");
|
|
1862
|
+
}
|
|
1863
|
+
if (token.refresh_token) await store.set(token.refresh_token);
|
|
1864
|
+
if (started !== generation) {
|
|
1865
|
+
if (token.refresh_token) {
|
|
1866
|
+
await store.deleteIf(token.refresh_token);
|
|
1867
|
+
await revokeQuietly(token.refresh_token);
|
|
1868
|
+
}
|
|
1869
|
+
throw new SessionError("not_signed_in");
|
|
1870
|
+
}
|
|
1871
|
+
held = {
|
|
1872
|
+
accessToken: token.access_token,
|
|
1873
|
+
expiresAt: now() + token.expires_in * 1e3
|
|
1874
|
+
};
|
|
1875
|
+
const info = await getUserinfo({ client });
|
|
1876
|
+
if (started !== generation) {
|
|
1877
|
+
held = null;
|
|
1878
|
+
throw new SessionError("not_signed_in");
|
|
1879
|
+
}
|
|
1880
|
+
const facts = toSessionFacts(info, held.expiresAt);
|
|
1881
|
+
update({
|
|
1882
|
+
status: "authenticated",
|
|
1883
|
+
facts,
|
|
1884
|
+
error: null
|
|
1885
|
+
});
|
|
1886
|
+
return facts;
|
|
1887
|
+
}
|
|
1888
|
+
function revoke(refreshToken) {
|
|
1889
|
+
return revokeToken({
|
|
1890
|
+
client,
|
|
1891
|
+
body: {
|
|
1892
|
+
token: refreshToken,
|
|
1893
|
+
token_type_hint: "refresh_token",
|
|
1894
|
+
client_id: config.clientId
|
|
1895
|
+
}
|
|
1896
|
+
});
|
|
1897
|
+
}
|
|
1898
|
+
async function revokeQuietly(refreshToken) {
|
|
1899
|
+
try {
|
|
1900
|
+
await revoke(refreshToken);
|
|
1901
|
+
} catch {}
|
|
1902
|
+
}
|
|
1903
|
+
/**
|
|
1904
|
+
* A code was redeemed for `refreshToken`, but the sign-in did not finish:
|
|
1905
|
+
* storing the credential or reading `/userinfo` failed. The code is spent,
|
|
1906
|
+
* so the session it opened is never just dropped. When the identity service
|
|
1907
|
+
* could not answer and the credential is safely stored, it is kept, and
|
|
1908
|
+
* `restore()` finishes the sign-in once the service answers. Otherwise, or
|
|
1909
|
+
* when the service rejected the token it issued, the session is ended: the
|
|
1910
|
+
* credential is deleted and revoked, so nothing live is left behind.
|
|
1911
|
+
*
|
|
1912
|
+
* Resolves with the error `completeSignIn()` rejects with.
|
|
1913
|
+
*/
|
|
1914
|
+
async function settleUnfinishedSignIn(refreshToken, error) {
|
|
1915
|
+
held = null;
|
|
1916
|
+
let kept = false;
|
|
1917
|
+
if (classifyRefreshFailure(error) === "unavailable") try {
|
|
1918
|
+
kept = await store.get() === refreshToken;
|
|
1919
|
+
} catch {
|
|
1920
|
+
kept = false;
|
|
1921
|
+
}
|
|
1922
|
+
if (kept) {
|
|
1923
|
+
const unavailable = new SessionError("temporarily_unavailable", "Signed in, but the identity service could not confirm the session yet; restore() finishes it.");
|
|
1924
|
+
update({ error: unavailable });
|
|
1925
|
+
return unavailable;
|
|
1926
|
+
}
|
|
1927
|
+
try {
|
|
1928
|
+
await store.deleteIf(refreshToken);
|
|
1929
|
+
} catch {}
|
|
1930
|
+
await revokeQuietly(refreshToken);
|
|
1931
|
+
update({
|
|
1932
|
+
status: "unauthenticated",
|
|
1933
|
+
facts: null,
|
|
1934
|
+
error: null
|
|
1935
|
+
});
|
|
1936
|
+
return new SessionError("redemption_failed", "The sign-in could not be completed, so the session it opened was ended.");
|
|
1937
|
+
}
|
|
1938
|
+
/** Sign-ins and refreshes in flight, which can each rotate the credential. */
|
|
1939
|
+
const work = /* @__PURE__ */ new Set();
|
|
1940
|
+
function tracked(promise) {
|
|
1941
|
+
work.add(promise);
|
|
1942
|
+
const forgetWork = () => {
|
|
1943
|
+
work.delete(promise);
|
|
1944
|
+
};
|
|
1945
|
+
promise.then(forgetWork, forgetWork);
|
|
1946
|
+
return promise;
|
|
1947
|
+
}
|
|
1948
|
+
/** Waits for work in flight, at most `signOutWaitMs`. */
|
|
1949
|
+
async function settleWork() {
|
|
1950
|
+
if (work.size === 0) return;
|
|
1951
|
+
let timer;
|
|
1952
|
+
const bound = new Promise((resolve) => {
|
|
1953
|
+
timer = setTimeout(resolve, config.signOutWaitMs ?? SIGN_OUT_WAIT_MS);
|
|
1954
|
+
});
|
|
1955
|
+
await Promise.race([Promise.allSettled([...work]), bound]);
|
|
1956
|
+
clearTimeout(timer);
|
|
1957
|
+
}
|
|
1958
|
+
async function forget(error) {
|
|
1959
|
+
held = null;
|
|
1960
|
+
await store.delete();
|
|
1961
|
+
update({
|
|
1962
|
+
status: "unauthenticated",
|
|
1963
|
+
facts: null,
|
|
1964
|
+
error
|
|
1965
|
+
});
|
|
1966
|
+
}
|
|
1967
|
+
/**
|
|
1968
|
+
* Exchanges the stored refresh token. A refusal deletes it: the identity
|
|
1969
|
+
* service has ended that chain, so it can never succeed again. An outage
|
|
1970
|
+
* keeps it, since nothing was consumed.
|
|
1971
|
+
*/
|
|
1972
|
+
const refresher = createRefresher(() => tracked(runRefresh()));
|
|
1973
|
+
async function runRefresh() {
|
|
1974
|
+
if (signOutsRunning > 0) throw new SessionError("not_signed_in");
|
|
1975
|
+
const started = generation;
|
|
1976
|
+
const refreshToken = await store.get();
|
|
1977
|
+
if (!refreshToken) {
|
|
1978
|
+
await forget(null);
|
|
1979
|
+
throw new SessionError("not_signed_in");
|
|
1980
|
+
}
|
|
1981
|
+
let token;
|
|
1982
|
+
try {
|
|
1983
|
+
token = await createToken({
|
|
1984
|
+
client,
|
|
1985
|
+
body: {
|
|
1986
|
+
grant_type: "refresh_token",
|
|
1987
|
+
client_id: config.clientId,
|
|
1988
|
+
refresh_token: refreshToken
|
|
1989
|
+
}
|
|
1990
|
+
});
|
|
1991
|
+
} catch (error) {
|
|
1992
|
+
if (started !== generation) throw new SessionError("not_signed_in");
|
|
1993
|
+
if (classifyRefreshFailure(error) === "unavailable") {
|
|
1994
|
+
const unavailable = new SessionError("temporarily_unavailable");
|
|
1995
|
+
update({ error: unavailable });
|
|
1996
|
+
throw unavailable;
|
|
1997
|
+
}
|
|
1998
|
+
const expired = new SessionError("session_expired", `The identity service refused the stored refresh token (${oauthErrorCode(error) ?? "rejected"}).`);
|
|
1999
|
+
await forget(expired);
|
|
2000
|
+
throw expired;
|
|
2001
|
+
}
|
|
2002
|
+
try {
|
|
2003
|
+
await adopt(token, started);
|
|
2004
|
+
} catch (error) {
|
|
2005
|
+
if (error instanceof SessionError) throw error;
|
|
2006
|
+
if (classifyRefreshFailure(error) === "unavailable") {
|
|
2007
|
+
held = null;
|
|
2008
|
+
throw new SessionError("temporarily_unavailable");
|
|
2009
|
+
}
|
|
2010
|
+
const expired = new SessionError("session_expired", "The identity service rejected the token it issued.");
|
|
2011
|
+
await forget(expired);
|
|
2012
|
+
throw expired;
|
|
2013
|
+
}
|
|
2014
|
+
if (!held) throw new SessionError("not_signed_in");
|
|
2015
|
+
return held;
|
|
2016
|
+
}
|
|
2017
|
+
const session = {
|
|
2018
|
+
async restore() {
|
|
2019
|
+
if (held && now() < held.expiresAt - grace) return snapshot.facts;
|
|
2020
|
+
try {
|
|
2021
|
+
await refresher.refresh();
|
|
2022
|
+
return snapshot.facts;
|
|
2023
|
+
} catch (error) {
|
|
2024
|
+
if (error instanceof SessionError && (error.code === "not_signed_in" || error.code === "session_expired")) return null;
|
|
2025
|
+
throw error;
|
|
2026
|
+
}
|
|
2027
|
+
},
|
|
2028
|
+
async beginSignIn(options) {
|
|
2029
|
+
const cryptoImpl = config.crypto;
|
|
2030
|
+
const verifier = createCodeVerifier(cryptoImpl);
|
|
2031
|
+
const state = createState(cryptoImpl);
|
|
2032
|
+
const challenge = await createCodeChallenge(verifier, cryptoImpl);
|
|
2033
|
+
pending = {
|
|
2034
|
+
state,
|
|
2035
|
+
verifier
|
|
2036
|
+
};
|
|
2037
|
+
const url = new URL("/authorize", config.identityUrl);
|
|
2038
|
+
url.searchParams.set("response_type", "code");
|
|
2039
|
+
url.searchParams.set("client_id", config.clientId);
|
|
2040
|
+
url.searchParams.set("redirect_uri", config.redirectUri);
|
|
2041
|
+
url.searchParams.set("state", state);
|
|
2042
|
+
url.searchParams.set("code_challenge", challenge);
|
|
2043
|
+
url.searchParams.set("code_challenge_method", "S256");
|
|
2044
|
+
if (options?.prompt) url.searchParams.set("prompt", options.prompt);
|
|
2045
|
+
if (options?.org) url.searchParams.set("org", options.org);
|
|
2046
|
+
return url.toString();
|
|
2047
|
+
},
|
|
2048
|
+
async completeSignIn(callbackUrl) {
|
|
2049
|
+
const request = pending;
|
|
2050
|
+
pending = null;
|
|
2051
|
+
if (signOutsRunning > 0) throw new SessionError("not_signed_in");
|
|
2052
|
+
const started = generation;
|
|
2053
|
+
let callback;
|
|
2054
|
+
try {
|
|
2055
|
+
callback = new URL(callbackUrl);
|
|
2056
|
+
} catch {
|
|
2057
|
+
throw new SessionError("state_mismatch", "The redirect was not a URL.");
|
|
2058
|
+
}
|
|
2059
|
+
const state = callback.searchParams.get("state");
|
|
2060
|
+
if (!request || !sameRedirect(callback, new URL(config.redirectUri)) || state === null || state !== request.state) throw new SessionError("state_mismatch", "The redirect did not match a sign-in this client started.");
|
|
2061
|
+
const error = callback.searchParams.get("error");
|
|
2062
|
+
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}.`);
|
|
2063
|
+
const code = callback.searchParams.get("code");
|
|
2064
|
+
if (!code) throw new SessionError("redemption_failed", "The redirect had no code.");
|
|
2065
|
+
let token;
|
|
2066
|
+
try {
|
|
2067
|
+
token = await createToken({
|
|
2068
|
+
client,
|
|
2069
|
+
body: {
|
|
2070
|
+
grant_type: "authorization_code",
|
|
2071
|
+
code,
|
|
2072
|
+
redirect_uri: config.redirectUri,
|
|
2073
|
+
client_id: config.clientId,
|
|
2074
|
+
code_verifier: request.verifier
|
|
2075
|
+
}
|
|
2076
|
+
});
|
|
2077
|
+
} catch (redeemError) {
|
|
2078
|
+
throw classifyRefreshFailure(redeemError) === "unavailable" ? new SessionError("temporarily_unavailable") : new SessionError("redemption_failed", "The code was not redeemed.");
|
|
2079
|
+
}
|
|
2080
|
+
if (!token.refresh_token) throw new SessionError("redemption_failed", "The identity service issued no refresh token to a native client.");
|
|
2081
|
+
try {
|
|
2082
|
+
return await adopt(token, started);
|
|
2083
|
+
} catch (adoptError) {
|
|
2084
|
+
if (adoptError instanceof SessionError) throw adoptError;
|
|
2085
|
+
throw await settleUnfinishedSignIn(token.refresh_token, adoptError);
|
|
2086
|
+
}
|
|
2087
|
+
},
|
|
2088
|
+
async getAccessToken(options) {
|
|
2089
|
+
const current = held && now() < held.expiresAt - grace ? held : null;
|
|
2090
|
+
if (current && current.accessToken !== options?.replacing) return current.accessToken;
|
|
2091
|
+
return (await refresher.refresh()).accessToken;
|
|
2092
|
+
},
|
|
2093
|
+
facts() {
|
|
2094
|
+
return snapshot.facts;
|
|
2095
|
+
},
|
|
2096
|
+
snapshot() {
|
|
2097
|
+
return snapshot;
|
|
2098
|
+
},
|
|
2099
|
+
async signOut() {
|
|
2100
|
+
signOutsRunning += 1;
|
|
2101
|
+
pending = null;
|
|
2102
|
+
held = null;
|
|
2103
|
+
let refreshToken;
|
|
2104
|
+
try {
|
|
2105
|
+
await settleWork();
|
|
2106
|
+
generation += 1;
|
|
2107
|
+
refreshToken = await store.get();
|
|
2108
|
+
await store.delete();
|
|
2109
|
+
} finally {
|
|
2110
|
+
signOutsRunning -= 1;
|
|
2111
|
+
}
|
|
2112
|
+
update({
|
|
2113
|
+
status: "unauthenticated",
|
|
2114
|
+
facts: null,
|
|
2115
|
+
error: null
|
|
2116
|
+
});
|
|
2117
|
+
if (!refreshToken) return;
|
|
2118
|
+
try {
|
|
2119
|
+
await revoke(refreshToken);
|
|
2120
|
+
} catch {
|
|
2121
|
+
const error = new SessionError("sign_out_failed", "Signed out on this device, but the identity service did not confirm revoking the session.");
|
|
2122
|
+
update({ error });
|
|
2123
|
+
throw error;
|
|
2124
|
+
}
|
|
2125
|
+
},
|
|
2126
|
+
subscribe(listener) {
|
|
2127
|
+
listeners.add(listener);
|
|
2128
|
+
return () => {
|
|
2129
|
+
listeners.delete(listener);
|
|
2130
|
+
};
|
|
2131
|
+
}
|
|
2132
|
+
};
|
|
2133
|
+
const completeSignIn = session.completeSignIn;
|
|
2134
|
+
session.completeSignIn = (callbackUrl) => tracked(completeSignIn(callbackUrl));
|
|
2135
|
+
return session;
|
|
2136
|
+
}
|
|
2137
|
+
//#endregion
|
|
2138
|
+
//#region ../../platform/auth/src/native/storage-adapters.ts
|
|
2139
|
+
/** Raised when the platform offers no protected store for a credential. */
|
|
2140
|
+
var SecureStorageUnavailableError = class extends Error {
|
|
2141
|
+
constructor(message) {
|
|
2142
|
+
super(message);
|
|
2143
|
+
this.name = "SecureStorageUnavailableError";
|
|
2144
|
+
}
|
|
2145
|
+
};
|
|
2146
|
+
function isMissingEntry(error) {
|
|
2147
|
+
return error instanceof Error && /no (matching )?entry|not found/i.test(error.message);
|
|
2148
|
+
}
|
|
2149
|
+
function createKeyringSecureStorage(options) {
|
|
2150
|
+
return {
|
|
2151
|
+
async get(key) {
|
|
2152
|
+
try {
|
|
2153
|
+
return options.entry(options.service, key).getPassword() ?? null;
|
|
2154
|
+
} catch (error) {
|
|
2155
|
+
if (isMissingEntry(error)) return null;
|
|
2156
|
+
throw error;
|
|
2157
|
+
}
|
|
2158
|
+
},
|
|
2159
|
+
async set(key, value) {
|
|
2160
|
+
options.entry(options.service, key).setPassword(value);
|
|
2161
|
+
},
|
|
2162
|
+
async delete(key) {
|
|
2163
|
+
try {
|
|
2164
|
+
options.entry(options.service, key).deletePassword();
|
|
2165
|
+
} catch (error) {
|
|
2166
|
+
if (!isMissingEntry(error)) throw error;
|
|
2167
|
+
}
|
|
2168
|
+
}
|
|
2169
|
+
};
|
|
2170
|
+
}
|
|
2171
|
+
//#endregion
|
|
2172
|
+
//#region ../../platform/auth/src/session/exchange.ts
|
|
2173
|
+
/**
|
|
2174
|
+
* Token exchange (RFC 8693): company switch, role narrowing, and a root
|
|
2175
|
+
* admin's company entry (Phase 007 FR-3, FR-4).
|
|
2176
|
+
*
|
|
2177
|
+
* An exchanged token comes with no refresh token and never outlives the token
|
|
2178
|
+
* it was made from, while the session's own refresh chain keeps the company
|
|
2179
|
+
* it was opened with. So the company and roles a tab moved to are remembered
|
|
2180
|
+
* as an exchange target, and the session exchanges into it again after every
|
|
2181
|
+
* refresh. The target is a company id and role names, which are not secrets
|
|
2182
|
+
* and grant nothing on their own; it lives in sessionStorage so a reload of
|
|
2183
|
+
* the same tab stays where it was, and other tabs keep their own.
|
|
2184
|
+
*/
|
|
2185
|
+
const TOKEN_EXCHANGE_GRANT = "urn:ietf:params:oauth:grant-type:token-exchange";
|
|
2186
|
+
const ACCESS_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token";
|
|
2187
|
+
/**
|
|
2188
|
+
* Exchanges `subjectToken`, the session's own chain token, for one naming
|
|
2189
|
+
* `target`. The request carries no cookie: an exchange is judged on its
|
|
2190
|
+
* subject token alone and sets nothing.
|
|
2191
|
+
*/
|
|
2192
|
+
function exchangeToken(client, clientId, subjectToken, target) {
|
|
2193
|
+
return createToken({
|
|
2194
|
+
client,
|
|
2195
|
+
body: {
|
|
2196
|
+
grant_type: TOKEN_EXCHANGE_GRANT,
|
|
2197
|
+
client_id: clientId,
|
|
2198
|
+
subject_token: subjectToken,
|
|
2199
|
+
subject_token_type: ACCESS_TOKEN_TYPE,
|
|
2200
|
+
requested_token_type: ACCESS_TOKEN_TYPE,
|
|
2201
|
+
org: target.org,
|
|
2202
|
+
...target.roles ? { roles: target.roles.join(" ") } : {}
|
|
2203
|
+
},
|
|
2204
|
+
credentials: "omit"
|
|
2205
|
+
});
|
|
2206
|
+
}
|
|
2207
|
+
function classifyExchangeFailure(error) {
|
|
2208
|
+
if (classifyRefreshFailure(error) === "unavailable") return "unavailable";
|
|
2209
|
+
const code = oauthErrorCode(error);
|
|
2210
|
+
if (code === "invalid_request" || code === "invalid_token") return "unusable";
|
|
2211
|
+
return "refused";
|
|
2212
|
+
}
|
|
2213
|
+
//#endregion
|
|
2214
|
+
//#region ../../platform/auth/src/native/exchange.ts
|
|
2215
|
+
/**
|
|
2216
|
+
* Token exchange for native clients (Phase 007 FR-3): moves a native
|
|
2217
|
+
* session's access token to another company, or narrows its roles, without a
|
|
2218
|
+
* new sign-in.
|
|
2219
|
+
*
|
|
2220
|
+
* The exchanged token comes with no refresh token and never outlives the
|
|
2221
|
+
* subject token, so the client keeps its own refresh chain in its
|
|
2222
|
+
* {@link NativeSession} and exchanges again after every refresh. The exchange
|
|
2223
|
+
* target, a company id and role names, is not a secret and grants nothing on
|
|
2224
|
+
* its own, so a client may remember it in its plain configuration.
|
|
2225
|
+
*/
|
|
2226
|
+
/**
|
|
2227
|
+
* Exchanges `subjectToken`, the session's own access token from
|
|
2228
|
+
* `NativeSession.getAccessToken()`, for one naming `target`.
|
|
2229
|
+
*
|
|
2230
|
+
* Rejects with `access_denied` when the identity service refuses the target,
|
|
2231
|
+
* `session_expired` when it does not accept the subject token (refresh it and
|
|
2232
|
+
* try again), and `temporarily_unavailable` when it could not answer.
|
|
2233
|
+
*/
|
|
2234
|
+
async function exchangeNativeToken(config, subjectToken, target) {
|
|
2235
|
+
const now = config.now ?? Date.now;
|
|
2236
|
+
const client = createIdentityHeyApiClient({
|
|
2237
|
+
baseUrl: config.identityUrl,
|
|
2238
|
+
credentials: "omit",
|
|
2239
|
+
fetch: config.fetch
|
|
2240
|
+
});
|
|
2241
|
+
let accessToken;
|
|
2242
|
+
let expiresAt;
|
|
2243
|
+
try {
|
|
2244
|
+
const token = await exchangeToken(client, config.clientId, subjectToken, target);
|
|
2245
|
+
accessToken = token.access_token;
|
|
2246
|
+
expiresAt = now() + token.expires_in * 1e3;
|
|
2247
|
+
} catch (error) {
|
|
2248
|
+
const failure = classifyExchangeFailure(error);
|
|
2249
|
+
if (failure === "unavailable") throw new SessionError("temporarily_unavailable");
|
|
2250
|
+
if (failure === "unusable") throw new SessionError("session_expired", "The identity service did not accept the token to exchange.");
|
|
2251
|
+
throw new SessionError("access_denied", "The identity service refused the exchange.");
|
|
2252
|
+
}
|
|
2253
|
+
try {
|
|
2254
|
+
const info = await getUserinfo({
|
|
2255
|
+
client,
|
|
2256
|
+
auth: accessToken
|
|
2257
|
+
});
|
|
2258
|
+
return {
|
|
2259
|
+
accessToken,
|
|
2260
|
+
expiresAt,
|
|
2261
|
+
facts: toSessionFacts(info, expiresAt, true)
|
|
2262
|
+
};
|
|
2263
|
+
} catch (error) {
|
|
2264
|
+
if (classifyRefreshFailure(error) === "unavailable") throw new SessionError("temporarily_unavailable");
|
|
2265
|
+
throw new SessionError("access_denied", "The identity service rejected the token it exchanged.");
|
|
2266
|
+
}
|
|
2267
|
+
}
|
|
2268
|
+
//#endregion
|
|
2269
|
+
//#region src/auth/identity/browser.ts
|
|
2270
|
+
/**
|
|
2271
|
+
* Opens a URL in the user's default browser. Best effort: the sign-in URL is
|
|
2272
|
+
* always printed too, for a terminal with no browser to open.
|
|
2273
|
+
*/
|
|
2274
|
+
function opener(url) {
|
|
2275
|
+
switch (process.platform) {
|
|
2276
|
+
case "darwin": return {
|
|
2277
|
+
command: "open",
|
|
2278
|
+
args: [url]
|
|
2279
|
+
};
|
|
2280
|
+
case "win32": return {
|
|
2281
|
+
command: "rundll32",
|
|
2282
|
+
args: ["url.dll,FileProtocolHandler", url]
|
|
2283
|
+
};
|
|
2284
|
+
default: return {
|
|
2285
|
+
command: "xdg-open",
|
|
2286
|
+
args: [url]
|
|
2287
|
+
};
|
|
2288
|
+
}
|
|
2289
|
+
}
|
|
2290
|
+
function openBrowser(url) {
|
|
2291
|
+
if (process.env["FLUID_NO_BROWSER"]) return;
|
|
2292
|
+
const launch = opener(url);
|
|
2293
|
+
try {
|
|
2294
|
+
execFile(launch.command, launch.args, () => void 0);
|
|
2295
|
+
} catch {}
|
|
2296
|
+
}
|
|
2297
|
+
//#endregion
|
|
2298
|
+
//#region src/auth/identity/environment.ts
|
|
2299
|
+
/**
|
|
2300
|
+
* Which identity service the CLI signs in with, following the API base the
|
|
2301
|
+
* CLI already talks to (`FLUID_API_BASE`, production by default).
|
|
2302
|
+
*/
|
|
2303
|
+
/** The CLI's registered public client at the identity service. */
|
|
2304
|
+
const IDENTITY_CLIENT_ID = "fluid-cli";
|
|
2305
|
+
/** The credential store service name the CLI files its sessions under. */
|
|
2306
|
+
const KEYRING_SERVICE = "fluid-cli";
|
|
2307
|
+
const PRODUCTION_IDENTITY_URL = "https://identity.fluid.app";
|
|
2308
|
+
const STAGING_IDENTITY_URL = "https://identity.stage.fluid.app";
|
|
2309
|
+
const STAGING_API_HOSTS = [/\.fluid-staging\.app$/, /\.stage\.fluid\.app$/];
|
|
2310
|
+
function isLoopbackHost(hostname) {
|
|
2311
|
+
return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" || hostname.endsWith(".localhost");
|
|
2312
|
+
}
|
|
2313
|
+
/**
|
|
2314
|
+
* The identity service origin for an API base, or null when the API base
|
|
2315
|
+
* names no environment with an identity service (a local Rails, say) and
|
|
2316
|
+
* `FLUID_IDENTITY_URL` does not name one either.
|
|
2317
|
+
*
|
|
2318
|
+
* `FLUID_IDENTITY_URL` overrides the derivation. It must be `https`, or
|
|
2319
|
+
* `http` on a loopback host for local development.
|
|
2320
|
+
*/
|
|
2321
|
+
function resolveIdentityUrl(apiBase, env = process.env) {
|
|
2322
|
+
const override = env["FLUID_IDENTITY_URL"];
|
|
2323
|
+
if (override) {
|
|
2324
|
+
let url;
|
|
2325
|
+
try {
|
|
2326
|
+
url = new URL(override);
|
|
2327
|
+
} catch {
|
|
2328
|
+
throw new Error(`FLUID_IDENTITY_URL is not a URL: ${override}`);
|
|
2329
|
+
}
|
|
2330
|
+
if (!(url.protocol === "https:" || url.protocol === "http:" && isLoopbackHost(url.hostname))) throw new Error("FLUID_IDENTITY_URL must use https (http only on a loopback host).");
|
|
2331
|
+
return url.origin;
|
|
2332
|
+
}
|
|
2333
|
+
let hostname;
|
|
2334
|
+
try {
|
|
2335
|
+
hostname = new URL(apiBase).hostname;
|
|
2336
|
+
} catch {
|
|
2337
|
+
return null;
|
|
2338
|
+
}
|
|
2339
|
+
if (hostname === "api.fluid.app") return PRODUCTION_IDENTITY_URL;
|
|
2340
|
+
if (STAGING_API_HOSTS.some((pattern) => pattern.test(hostname))) return STAGING_IDENTITY_URL;
|
|
2341
|
+
return null;
|
|
2342
|
+
}
|
|
2343
|
+
//#endregion
|
|
2344
|
+
//#region src/auth/identity/keyring.ts
|
|
2345
|
+
/**
|
|
2346
|
+
* The operating system credential store for identity sessions: macOS
|
|
2347
|
+
* Keychain, Windows Credential Manager, or the Secret Service on Linux,
|
|
2348
|
+
* through `@napi-rs/keyring`.
|
|
2349
|
+
*
|
|
2350
|
+
* The binding is loaded only when an identity session needs it, so a
|
|
2351
|
+
* platform without a prebuilt binary keeps every legacy command working.
|
|
2352
|
+
* There is no fallback to a file: without a credential store, identity
|
|
2353
|
+
* sign-in refuses to run (Phase 006 AC-7.2).
|
|
2354
|
+
*/
|
|
2355
|
+
let loaded = null;
|
|
2356
|
+
function loadKeyringStorage() {
|
|
2357
|
+
loaded ??= import("@napi-rs/keyring").then(({ Entry }) => createKeyringSecureStorage({
|
|
2358
|
+
entry: (service, account) => new Entry(service, account),
|
|
2359
|
+
service: KEYRING_SERVICE
|
|
2360
|
+
}), (error) => {
|
|
2361
|
+
loaded = null;
|
|
2362
|
+
throw new SecureStorageUnavailableError(`The operating system credential store could not be loaded (${error instanceof Error ? error.message : String(error)}).`);
|
|
2363
|
+
});
|
|
2364
|
+
return loaded;
|
|
2365
|
+
}
|
|
2366
|
+
//#endregion
|
|
2367
|
+
//#region src/auth/identity/loopback.ts
|
|
2368
|
+
/**
|
|
2369
|
+
* The loopback redirect for a native sign-in (RFC 8252 sections 7.3 and 8.3):
|
|
2370
|
+
* a one-shot HTTP server on 127.0.0.1, on a port the operating system picks,
|
|
2371
|
+
* that takes the identity service's redirect to `/callback`.
|
|
2372
|
+
*
|
|
2373
|
+
* It answers only the redirect for the sign-in in progress: a request to any
|
|
2374
|
+
* other path, or one whose `state` is not this sign-in's, is refused and the
|
|
2375
|
+
* server keeps waiting. It closes after the one redirect it accepts, or when
|
|
2376
|
+
* the wait times out.
|
|
2377
|
+
*/
|
|
2378
|
+
const CALLBACK_PATH = "/callback";
|
|
2379
|
+
const DEFAULT_CALLBACK_TIMEOUT_MS = 300 * 1e3;
|
|
2380
|
+
var LoopbackTimeoutError = class extends Error {
|
|
2381
|
+
constructor() {
|
|
2382
|
+
super("Timed out waiting for the browser to finish signing in.");
|
|
2383
|
+
this.name = "LoopbackTimeoutError";
|
|
2384
|
+
}
|
|
2385
|
+
};
|
|
2386
|
+
function sameState(received, expected) {
|
|
2387
|
+
const a = Buffer.from(received);
|
|
2388
|
+
const b = Buffer.from(expected);
|
|
2389
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
2390
|
+
}
|
|
2391
|
+
function escapeHtml(text) {
|
|
2392
|
+
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
2393
|
+
}
|
|
2394
|
+
function page(response, status, title, message) {
|
|
2395
|
+
const body = `<!doctype html><html><head><meta charset="utf-8"><title>${escapeHtml(title)}</title></head><body style="font-family:system-ui,sans-serif;max-width:32rem;margin:4rem auto;padding:0 1rem"><h1 style="font-size:1.25rem">${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p></body></html>`;
|
|
2396
|
+
response.writeHead(status, {
|
|
2397
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
2398
|
+
"Cache-Control": "no-store",
|
|
2399
|
+
"Referrer-Policy": "no-referrer",
|
|
2400
|
+
Connection: "close"
|
|
2401
|
+
});
|
|
2402
|
+
response.end(body);
|
|
2403
|
+
}
|
|
2404
|
+
/** Starts the server on 127.0.0.1 with an ephemeral port. */
|
|
2405
|
+
async function startLoopbackServer(options = {}) {
|
|
2406
|
+
const timeoutMs = options.timeoutMs ?? 3e5;
|
|
2407
|
+
let expectedState = null;
|
|
2408
|
+
let settle = null;
|
|
2409
|
+
let done = false;
|
|
2410
|
+
let timer;
|
|
2411
|
+
const server = createServer((request, response) => {
|
|
2412
|
+
const url = new URL(request.url ?? "/", "http://127.0.0.1");
|
|
2413
|
+
if (done) {
|
|
2414
|
+
page(response, 410, "Sign-in finished", "You can close this tab.");
|
|
2415
|
+
return;
|
|
2416
|
+
}
|
|
2417
|
+
if (request.method !== "GET" || url.pathname !== "/callback") {
|
|
2418
|
+
page(response, 404, "Not found", "This is not a Fluid CLI sign-in.");
|
|
2419
|
+
return;
|
|
2420
|
+
}
|
|
2421
|
+
const state = url.searchParams.get("state");
|
|
2422
|
+
if (expectedState === null || state === null || !sameState(state, expectedState)) {
|
|
2423
|
+
page(response, 400, "Sign-in not recognised", "This redirect does not belong to the sign-in the Fluid CLI is waiting for.");
|
|
2424
|
+
return;
|
|
2425
|
+
}
|
|
2426
|
+
done = true;
|
|
2427
|
+
const failed = url.searchParams.has("error");
|
|
2428
|
+
page(response, failed ? 400 : 200, failed ? "Sign-in did not complete" : "Signed in to the Fluid CLI", failed ? "Return to your terminal for details." : "You can close this tab and return to your terminal.");
|
|
2429
|
+
const callbackUrl = new URL(request.url ?? "/", redirectUri).toString();
|
|
2430
|
+
const waiting = settle;
|
|
2431
|
+
settle = null;
|
|
2432
|
+
waiting?.resolve(callbackUrl);
|
|
2433
|
+
close();
|
|
2434
|
+
});
|
|
2435
|
+
await new Promise((resolve, reject) => {
|
|
2436
|
+
server.once("error", reject);
|
|
2437
|
+
server.listen(0, "127.0.0.1", () => {
|
|
2438
|
+
server.off("error", reject);
|
|
2439
|
+
resolve();
|
|
2440
|
+
});
|
|
2441
|
+
});
|
|
2442
|
+
const { port } = server.address();
|
|
2443
|
+
const redirectUri = `http://127.0.0.1:${port}${CALLBACK_PATH}`;
|
|
2444
|
+
let closing = null;
|
|
2445
|
+
function close() {
|
|
2446
|
+
done = true;
|
|
2447
|
+
clearTimeout(timer);
|
|
2448
|
+
const waiting = settle;
|
|
2449
|
+
settle = null;
|
|
2450
|
+
waiting?.reject(/* @__PURE__ */ new Error("The sign-in was cancelled."));
|
|
2451
|
+
closing ??= new Promise((resolve) => {
|
|
2452
|
+
server.close(() => resolve());
|
|
2453
|
+
server.closeAllConnections();
|
|
2454
|
+
});
|
|
2455
|
+
return closing;
|
|
2456
|
+
}
|
|
2457
|
+
return {
|
|
2458
|
+
redirectUri,
|
|
2459
|
+
waitForCallback(state) {
|
|
2460
|
+
if (done) return Promise.reject(/* @__PURE__ */ new Error("The loopback server is closed."));
|
|
2461
|
+
if (settle || expectedState !== null) return Promise.reject(/* @__PURE__ */ new Error("Already waiting for a callback."));
|
|
2462
|
+
expectedState = state;
|
|
2463
|
+
return new Promise((resolve, reject) => {
|
|
2464
|
+
settle = {
|
|
2465
|
+
resolve,
|
|
2466
|
+
reject
|
|
2467
|
+
};
|
|
2468
|
+
timer = setTimeout(() => {
|
|
2469
|
+
settle = null;
|
|
2470
|
+
reject(new LoopbackTimeoutError());
|
|
2471
|
+
close();
|
|
2472
|
+
}, timeoutMs);
|
|
2473
|
+
});
|
|
2474
|
+
},
|
|
2475
|
+
close
|
|
2476
|
+
};
|
|
2477
|
+
}
|
|
2478
|
+
let deps = {
|
|
2479
|
+
storage: loadKeyringStorage,
|
|
2480
|
+
openBrowser,
|
|
2481
|
+
now: Date.now,
|
|
2482
|
+
callbackTimeoutMs: DEFAULT_CALLBACK_TIMEOUT_MS,
|
|
2483
|
+
finishRetryDelaysMs: [
|
|
2484
|
+
1e3,
|
|
2485
|
+
2e3,
|
|
2486
|
+
4e3
|
|
2487
|
+
]
|
|
2488
|
+
};
|
|
2489
|
+
const RESTORE_REDIRECT_URI = "http://127.0.0.1/callback";
|
|
2490
|
+
/** How long before expiry a held token counts as stale. */
|
|
2491
|
+
const EXPIRY_MARGIN_MS = 3e4;
|
|
2492
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
2493
|
+
/** The latest token handed out per profile, for synchronous readers. */
|
|
2494
|
+
const latest = /* @__PURE__ */ new Map();
|
|
2495
|
+
const refreshTimers = /* @__PURE__ */ new Map();
|
|
2496
|
+
function sessionKey(auth) {
|
|
2497
|
+
return `${auth.identityUrl} ${auth.storageKey}`;
|
|
2498
|
+
}
|
|
2499
|
+
async function heldSession(auth) {
|
|
2500
|
+
const key = sessionKey(auth);
|
|
2501
|
+
const existing = sessions.get(key);
|
|
2502
|
+
if (existing) return existing;
|
|
2503
|
+
const storage = await deps.storage();
|
|
2504
|
+
const raced = sessions.get(key);
|
|
2505
|
+
if (raced) return raced;
|
|
2506
|
+
const held = {
|
|
2507
|
+
session: createNativeSession({
|
|
2508
|
+
identityUrl: auth.identityUrl,
|
|
2509
|
+
clientId: IDENTITY_CLIENT_ID,
|
|
2510
|
+
redirectUri: RESTORE_REDIRECT_URI,
|
|
2511
|
+
storage,
|
|
2512
|
+
storageKey: auth.storageKey,
|
|
2513
|
+
fetch: deps.fetch,
|
|
2514
|
+
now: deps.now
|
|
2515
|
+
}),
|
|
2516
|
+
exchanged: /* @__PURE__ */ new Map()
|
|
2517
|
+
};
|
|
2518
|
+
sessions.set(key, held);
|
|
2519
|
+
return held;
|
|
2520
|
+
}
|
|
2521
|
+
async function exchangeInto(auth, held, org) {
|
|
2522
|
+
const config = {
|
|
2523
|
+
identityUrl: auth.identityUrl,
|
|
2524
|
+
clientId: IDENTITY_CLIENT_ID,
|
|
2525
|
+
fetch: deps.fetch,
|
|
2526
|
+
now: deps.now
|
|
2527
|
+
};
|
|
2528
|
+
const target = {
|
|
2529
|
+
org,
|
|
2530
|
+
roles: null
|
|
2531
|
+
};
|
|
2532
|
+
const subject = await held.session.getAccessToken();
|
|
2533
|
+
let exchanged;
|
|
2534
|
+
try {
|
|
2535
|
+
exchanged = await exchangeNativeToken(config, subject, target);
|
|
2536
|
+
} catch (error) {
|
|
2537
|
+
if (!(error instanceof SessionError) || error.code !== "session_expired") throw error;
|
|
2538
|
+
exchanged = await exchangeNativeToken(config, await held.session.getAccessToken({ replacing: subject }), target);
|
|
2539
|
+
}
|
|
2540
|
+
held.exchanged.set(org, exchanged);
|
|
2541
|
+
return exchanged;
|
|
2542
|
+
}
|
|
2543
|
+
/**
|
|
2544
|
+
* A current access token for an identity profile and the facts behind it,
|
|
2545
|
+
* restoring the session from the credential store without a prompt and
|
|
2546
|
+
* refreshing or exchanging as needed. `org` defaults to the company the
|
|
2547
|
+
* profile moved to; null asks for the session's own company. Rejects with
|
|
2548
|
+
* `not_signed_in` when no session is stored or the stored one has ended.
|
|
2549
|
+
*/
|
|
2550
|
+
async function identityToken(auth, org = auth.org ?? null) {
|
|
2551
|
+
const held = await heldSession(auth);
|
|
2552
|
+
const facts = await held.session.restore();
|
|
2553
|
+
if (!facts) throw new SessionError("not_signed_in", "No identity session is stored.");
|
|
2554
|
+
const accessToken = await held.session.getAccessToken();
|
|
2555
|
+
const chainFacts = held.session.facts() ?? facts;
|
|
2556
|
+
if (!org || org === chainFacts.companyId) return {
|
|
2557
|
+
accessToken,
|
|
2558
|
+
expiresAt: chainFacts.expiresAt,
|
|
2559
|
+
facts: chainFacts
|
|
2560
|
+
};
|
|
2561
|
+
const cached = held.exchanged.get(org);
|
|
2562
|
+
if (cached && deps.now() < cached.expiresAt - EXPIRY_MARGIN_MS) return cached;
|
|
2563
|
+
return exchangeInto(auth, held, org);
|
|
2564
|
+
}
|
|
2565
|
+
/** The company the session itself signed in to, with no exchange. */
|
|
2566
|
+
async function sessionFacts(auth) {
|
|
2567
|
+
return (await identityToken(auth, null)).facts;
|
|
2568
|
+
}
|
|
2569
|
+
/**
|
|
2570
|
+
* An access token for a profile, recorded for {@link peekIdentityToken}.
|
|
2571
|
+
*/
|
|
2572
|
+
async function profileAccessToken(profile) {
|
|
2573
|
+
const token = await identityToken(profile.auth);
|
|
2574
|
+
latest.set(profile.name, {
|
|
2575
|
+
token: token.accessToken,
|
|
2576
|
+
expiresAt: token.expiresAt
|
|
2577
|
+
});
|
|
2578
|
+
return token.accessToken;
|
|
2579
|
+
}
|
|
2580
|
+
/**
|
|
2581
|
+
* The token last handed out for a profile while it is still current, for
|
|
2582
|
+
* synchronous readers such as plugins' `getAuthToken()`. Null when the
|
|
2583
|
+
* profile's session has not been primed in this process.
|
|
2584
|
+
*/
|
|
2585
|
+
function peekIdentityToken(profileName) {
|
|
2586
|
+
const held = latest.get(profileName);
|
|
2587
|
+
if (!held || deps.now() >= held.expiresAt - EXPIRY_MARGIN_MS) return null;
|
|
2588
|
+
return held.token;
|
|
2589
|
+
}
|
|
2590
|
+
/**
|
|
2591
|
+
* Restores a profile's session before a command runs, so synchronous token
|
|
2592
|
+
* readers find a current token in memory, and keeps it current for a
|
|
2593
|
+
* long-running command by refreshing shortly before it expires. The timer
|
|
2594
|
+
* never keeps the process alive.
|
|
2595
|
+
*/
|
|
2596
|
+
async function primeIdentityProfile(profile) {
|
|
2597
|
+
await profileAccessToken(profile);
|
|
2598
|
+
const held = latest.get(profile.name);
|
|
2599
|
+
if (!held) return;
|
|
2600
|
+
clearTimeout(refreshTimers.get(profile.name));
|
|
2601
|
+
const delay = Math.max(held.expiresAt - deps.now() - 2 * EXPIRY_MARGIN_MS, 5e3);
|
|
2602
|
+
const timer = setTimeout(() => {
|
|
2603
|
+
refreshTimers.delete(profile.name);
|
|
2604
|
+
primeIdentityProfile(profile).catch(() => {});
|
|
2605
|
+
}, delay);
|
|
2606
|
+
timer.unref();
|
|
2607
|
+
refreshTimers.set(profile.name, timer);
|
|
2608
|
+
}
|
|
2609
|
+
/**
|
|
2610
|
+
* Revokes the session's refresh token and deletes it from the credential
|
|
2611
|
+
* store. Rejects with `sign_out_failed` when the credential was deleted but
|
|
2612
|
+
* the identity service did not confirm the revocation.
|
|
2613
|
+
*/
|
|
2614
|
+
async function signOutIdentity(auth) {
|
|
2615
|
+
const held = await heldSession(auth);
|
|
2616
|
+
sessions.delete(sessionKey(auth));
|
|
2617
|
+
await held.session.signOut();
|
|
2618
|
+
}
|
|
2619
|
+
/**
|
|
2620
|
+
* Finishes a sign-in the identity service could not confirm. Its code may
|
|
2621
|
+
* already be redeemed and its session stored, and the code is spent either
|
|
2622
|
+
* way, so the stored session is the only way in: it is restored, retrying
|
|
2623
|
+
* while the service stays unavailable. Whenever that does not succeed --
|
|
2624
|
+
* nothing was stored, the service ended the session, the credential store
|
|
2625
|
+
* failed, or the service never answered -- the session is signed out
|
|
2626
|
+
* (revoked and deleted) before the error is reported, so no live session is
|
|
2627
|
+
* left behind with no profile naming it.
|
|
2628
|
+
*/
|
|
2629
|
+
async function finishStoredSignIn(session, unavailable) {
|
|
2630
|
+
let failure = unavailable;
|
|
2631
|
+
try {
|
|
2632
|
+
for (const delay of deps.finishRetryDelaysMs) {
|
|
2633
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
2634
|
+
try {
|
|
2635
|
+
const facts = await session.restore();
|
|
2636
|
+
if (facts) return facts;
|
|
2637
|
+
failure = unavailable;
|
|
2638
|
+
break;
|
|
2639
|
+
} catch (error) {
|
|
2640
|
+
failure = error;
|
|
2641
|
+
if (!(error instanceof SessionError) || error.code !== "temporarily_unavailable") break;
|
|
2642
|
+
}
|
|
2643
|
+
}
|
|
2644
|
+
} catch (error) {
|
|
2645
|
+
failure = error;
|
|
2646
|
+
}
|
|
2647
|
+
await session.signOut().catch(() => void 0);
|
|
2648
|
+
throw failure;
|
|
2649
|
+
}
|
|
2650
|
+
/**
|
|
2651
|
+
* Signs in through the system browser: opens the identity service's
|
|
2652
|
+
* `/authorize` with PKCE, takes the redirect on a loopback server, and
|
|
2653
|
+
* redeems the code. The refresh token goes to the credential store under a
|
|
2654
|
+
* new key, which the returned `auth` names.
|
|
2655
|
+
*/
|
|
2656
|
+
async function signInWithBrowser(options) {
|
|
2657
|
+
const storage = await deps.storage();
|
|
2658
|
+
const storageKey = `identity.${randomUUID()}`;
|
|
2659
|
+
await storage.set(storageKey, "pending");
|
|
2660
|
+
await storage.delete(storageKey);
|
|
2661
|
+
const server = await startLoopbackServer({ timeoutMs: deps.callbackTimeoutMs });
|
|
2662
|
+
const session = createNativeSession({
|
|
2663
|
+
identityUrl: options.identityUrl,
|
|
2664
|
+
clientId: IDENTITY_CLIENT_ID,
|
|
2665
|
+
redirectUri: server.redirectUri,
|
|
2666
|
+
storage,
|
|
2667
|
+
storageKey,
|
|
2668
|
+
fetch: deps.fetch,
|
|
2669
|
+
now: deps.now
|
|
2670
|
+
});
|
|
2671
|
+
let callbackUrl;
|
|
2672
|
+
try {
|
|
2673
|
+
const authorizeUrl = await session.beginSignIn(options.org ? { org: options.org } : void 0);
|
|
2674
|
+
const state = new URL(authorizeUrl).searchParams.get("state") ?? "";
|
|
2675
|
+
options.log("Opening your browser to sign in. If it does not open, visit:");
|
|
2676
|
+
options.log(authorizeUrl);
|
|
2677
|
+
deps.openBrowser(authorizeUrl);
|
|
2678
|
+
callbackUrl = await server.waitForCallback(state);
|
|
2679
|
+
} finally {
|
|
2680
|
+
await server.close();
|
|
2681
|
+
}
|
|
2682
|
+
let facts;
|
|
2683
|
+
try {
|
|
2684
|
+
facts = await session.completeSignIn(callbackUrl);
|
|
2685
|
+
} catch (error) {
|
|
2686
|
+
if (!(error instanceof SessionError) || error.code !== "temporarily_unavailable") throw error;
|
|
2687
|
+
facts = await finishStoredSignIn(session, error);
|
|
2688
|
+
}
|
|
2689
|
+
const auth = {
|
|
2690
|
+
mode: "identity",
|
|
2691
|
+
identityUrl: options.identityUrl,
|
|
2692
|
+
storageKey
|
|
2693
|
+
};
|
|
2694
|
+
sessions.set(sessionKey(auth), {
|
|
2695
|
+
session,
|
|
2696
|
+
exchanged: /* @__PURE__ */ new Map()
|
|
2697
|
+
});
|
|
2698
|
+
return {
|
|
2699
|
+
auth,
|
|
2700
|
+
facts,
|
|
2701
|
+
accessToken: await session.getAccessToken()
|
|
2702
|
+
};
|
|
2703
|
+
}
|
|
2704
|
+
/** A sentence for the user about an identity failure. */
|
|
2705
|
+
function describeIdentityError(error) {
|
|
2706
|
+
if (error instanceof SessionError) switch (error.code) {
|
|
2707
|
+
case "not_signed_in":
|
|
2708
|
+
case "session_expired": return "Your Fluid sign-in has ended. Run `fluid login` to sign in again.";
|
|
2709
|
+
case "access_denied": return "The Fluid identity service refused the request.";
|
|
2710
|
+
case "account_selection_required": return "Choose a company in the browser to finish signing in.";
|
|
2711
|
+
case "state_mismatch": return "The browser returned a sign-in this CLI did not start.";
|
|
2712
|
+
case "temporarily_unavailable": return "The Fluid identity service could not be reached. Try again shortly.";
|
|
2713
|
+
case "sign_out_failed": return "Signed out on this machine, but the identity service did not confirm ending the session.";
|
|
2714
|
+
default: return `Identity sign-in failed (${error.code}).`;
|
|
2715
|
+
}
|
|
2716
|
+
if (error instanceof Error && error.name === "SecureStorageUnavailableError") return `Identity sign-in needs the operating system credential store (Keychain, Credential Manager, or Secret Service). ${error.message}`;
|
|
2717
|
+
return error instanceof Error ? error.message : String(error);
|
|
2718
|
+
}
|
|
2719
|
+
//#endregion
|
|
2720
|
+
//#region src/config/paths.ts
|
|
2721
|
+
/**
|
|
2722
|
+
* XDG-compliant config directory resolution
|
|
2723
|
+
*
|
|
2724
|
+
* Priority:
|
|
2725
|
+
* 1. FLUID_CONFIG_DIR env var (explicit override)
|
|
2726
|
+
* 2. ~/.fluid/ on macOS (convention for CLI tools)
|
|
2727
|
+
* 3. %APPDATA%/fluid/ on Windows
|
|
2728
|
+
* 4. $XDG_CONFIG_HOME/fluid/ on Linux (XDG spec)
|
|
2729
|
+
* 5. ~/.config/fluid/ fallback on Linux
|
|
2730
|
+
*/
|
|
2731
|
+
function getConfigDir() {
|
|
2732
|
+
const envOverride = process.env["FLUID_CONFIG_DIR"];
|
|
2733
|
+
if (envOverride) return envOverride;
|
|
2734
|
+
if (process.platform === "darwin") return join(homedir(), ".fluid");
|
|
2735
|
+
if (process.platform === "win32") return join(process.env["APPDATA"] ?? join(homedir(), "AppData", "Roaming"), "fluid");
|
|
2736
|
+
const xdgConfig = process.env["XDG_CONFIG_HOME"];
|
|
2737
|
+
if (xdgConfig) return join(xdgConfig, "fluid");
|
|
2738
|
+
return join(homedir(), ".config", "fluid");
|
|
2739
|
+
}
|
|
2740
|
+
function getConfigFilePath() {
|
|
2741
|
+
return join(getConfigDir(), "config.json");
|
|
2742
|
+
}
|
|
2743
|
+
//#endregion
|
|
2744
|
+
//#region src/config/config.ts
|
|
2745
|
+
/**
|
|
2746
|
+
* Read/write config.json with atomic writes and safe defaults
|
|
2747
|
+
*/
|
|
2748
|
+
function readConfig() {
|
|
2749
|
+
const configPath = getConfigFilePath();
|
|
2750
|
+
if (!existsSync(configPath)) return createDefaultConfig();
|
|
2751
|
+
const raw = readFileSync(configPath, "utf8");
|
|
2752
|
+
let parsed;
|
|
2753
|
+
try {
|
|
2754
|
+
parsed = JSON.parse(raw);
|
|
2755
|
+
} catch {
|
|
2756
|
+
return createDefaultConfig();
|
|
2757
|
+
}
|
|
2758
|
+
return withDurableWorkspaceAliases({
|
|
2759
|
+
...createDefaultConfig(),
|
|
2760
|
+
...parsed
|
|
2761
|
+
});
|
|
2762
|
+
}
|
|
2763
|
+
function writeConfig(config) {
|
|
2764
|
+
const configPath = getConfigFilePath();
|
|
2765
|
+
const dir = dirname(configPath);
|
|
2766
|
+
mkdirSync(dir, {
|
|
2767
|
+
recursive: true,
|
|
2768
|
+
mode: 448
|
|
2769
|
+
});
|
|
2770
|
+
const tmpPath = join(dir, `.fluid-config-${randomBytes(6).toString("hex")}.tmp`);
|
|
2771
|
+
try {
|
|
2772
|
+
writeFileSync(tmpPath, JSON.stringify(withDurableWorkspaceAliases(config), null, 2) + "\n", {
|
|
2773
|
+
encoding: "utf8",
|
|
2774
|
+
mode: 384
|
|
2775
|
+
});
|
|
2776
|
+
renameSync(tmpPath, configPath);
|
|
2777
|
+
} catch (err) {
|
|
2778
|
+
try {
|
|
2779
|
+
unlinkSync(tmpPath);
|
|
2780
|
+
} catch {}
|
|
2781
|
+
throw err;
|
|
2782
|
+
}
|
|
2783
|
+
}
|
|
2784
|
+
function workspaceSlug(value) {
|
|
2785
|
+
return value.toLowerCase().trim().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
|
|
2786
|
+
}
|
|
2787
|
+
function storefrontSlug(value) {
|
|
2788
|
+
return workspaceSlug((value.trim().replace(/^[a-z][a-z0-9+.-]*:\/\//i, "").split(/[/?#]/, 1)[0]?.replace(/:\d+$/, "") ?? "").replace(/\.fluid\.app$/i, ""));
|
|
2789
|
+
}
|
|
2790
|
+
/** Preserve rename history even when `fluid logout` clears the profiles that
|
|
2791
|
+
* originally carried it. Derivation on read migrates existing config files;
|
|
2792
|
+
* normalization on every write makes the migration durable before profiles
|
|
2793
|
+
* are removed. */
|
|
2794
|
+
function withDurableWorkspaceAliases(config) {
|
|
2795
|
+
const aliases = {};
|
|
2796
|
+
const add = (storefront, candidates) => {
|
|
2797
|
+
const key = storefrontSlug(storefront);
|
|
2798
|
+
if (!key) return;
|
|
2799
|
+
const values = new Set(aliases[key] ?? []);
|
|
2800
|
+
for (const candidate of candidates) {
|
|
2801
|
+
const slug = workspaceSlug(candidate);
|
|
2802
|
+
if (slug) values.add(slug);
|
|
2803
|
+
}
|
|
2804
|
+
if (values.size > 0) aliases[key] = [...values];
|
|
2805
|
+
};
|
|
2806
|
+
for (const [storefront, candidates] of Object.entries(config.workspaceAliasesByFluidShop ?? {})) {
|
|
2807
|
+
if (!Array.isArray(candidates)) continue;
|
|
2808
|
+
add(storefront, candidates.filter((candidate) => typeof candidate === "string"));
|
|
2809
|
+
}
|
|
2810
|
+
for (const profile of Object.values(config.profiles)) if (profile.fluidShop) add(profile.fluidShop, [profile.name, profile.companyName]);
|
|
2811
|
+
return Object.keys(aliases).length > 0 || config.workspaceAliasesByFluidShop !== void 0 ? {
|
|
2812
|
+
...config,
|
|
2813
|
+
workspaceAliasesByFluidShop: aliases
|
|
2814
|
+
} : config;
|
|
2815
|
+
}
|
|
2816
|
+
function updateConfig(updater) {
|
|
2817
|
+
const updated = updater(readConfig());
|
|
2818
|
+
writeConfig(updated);
|
|
2819
|
+
return updated;
|
|
2820
|
+
}
|
|
2821
|
+
//#endregion
|
|
2822
|
+
//#region src/config/project-config.ts
|
|
2823
|
+
/**
|
|
2824
|
+
* Project-level config (.fluidrc) reader.
|
|
2825
|
+
*
|
|
2826
|
+
* Walks upward from a starting directory to find a `.fluidrc` file.
|
|
2827
|
+
* The file is JSON with a `profile` field that maps to a profile name
|
|
2828
|
+
* in `~/.fluid/config.json`.
|
|
2829
|
+
*
|
|
2830
|
+
* This allows portal repos to pin themselves to a specific CLI profile
|
|
2831
|
+
* so that `fluid portal pull` / `push` always use the correct company
|
|
2832
|
+
* credentials, regardless of which profile is globally active.
|
|
2833
|
+
*/
|
|
2834
|
+
const RC_FILENAME = ".fluidrc";
|
|
2835
|
+
/** Cached result keyed by the starting directory. */
|
|
2836
|
+
let cachedResult;
|
|
2837
|
+
/**
|
|
2838
|
+
* Walk upward from `startDir` looking for a `.fluidrc` file.
|
|
2839
|
+
*
|
|
2840
|
+
* Returns the parsed config when found, or `null` if no valid `.fluidrc`
|
|
2841
|
+
* exists in any ancestor directory.
|
|
2842
|
+
*
|
|
2843
|
+
* The result is cached per starting directory for the lifetime of the
|
|
2844
|
+
* process — CLI commands are short-lived so stale-cache is not a concern.
|
|
2845
|
+
*/
|
|
2846
|
+
function findProjectConfig(startDir) {
|
|
2847
|
+
if (cachedResult && cachedResult.dir === startDir) return cachedResult.config;
|
|
2848
|
+
let dir = startDir;
|
|
2849
|
+
while (true) {
|
|
2850
|
+
const rcPath = join(dir, RC_FILENAME);
|
|
2851
|
+
if (existsSync(rcPath)) {
|
|
2852
|
+
try {
|
|
2853
|
+
const raw = readFileSync(rcPath, "utf8");
|
|
2854
|
+
const parsed = JSON.parse(raw);
|
|
2855
|
+
if (typeof parsed.profile === "string" && parsed.profile.length > 0) {
|
|
2856
|
+
const config = { profile: parsed.profile };
|
|
2857
|
+
cachedResult = {
|
|
2858
|
+
dir: startDir,
|
|
2859
|
+
config
|
|
2860
|
+
};
|
|
2861
|
+
return config;
|
|
2862
|
+
}
|
|
2863
|
+
} catch {}
|
|
2864
|
+
cachedResult = {
|
|
2865
|
+
dir: startDir,
|
|
2866
|
+
config: null
|
|
2867
|
+
};
|
|
2868
|
+
return null;
|
|
2869
|
+
}
|
|
2870
|
+
const parent = dirname(dir);
|
|
2871
|
+
if (parent === dir) break;
|
|
2872
|
+
dir = parent;
|
|
2873
|
+
}
|
|
2874
|
+
cachedResult = {
|
|
2875
|
+
dir: startDir,
|
|
2876
|
+
config: null
|
|
2877
|
+
};
|
|
2878
|
+
return null;
|
|
2879
|
+
}
|
|
2880
|
+
//#endregion
|
|
2881
|
+
//#region src/auth/token.ts
|
|
2882
|
+
/**
|
|
2883
|
+
* Token storage and retrieval from config
|
|
2884
|
+
*/
|
|
2885
|
+
/**
|
|
2886
|
+
* Resolve the credential for a named profile, or for the active one when
|
|
2887
|
+
* omitted.
|
|
2888
|
+
*
|
|
2889
|
+
* Resolution order (when `profileName` is omitted — mirrors
|
|
2890
|
+
* `createCommandContext` in domain/context.ts):
|
|
2891
|
+
* 1. `FLUID_TOKEN` / `FLUID_API_TOKEN` environment variables
|
|
2892
|
+
* 2. Project-level `.fluidrc` profile (walks upward from cwd)
|
|
2893
|
+
* 3. Global active profile from `~/.fluid/config.json`
|
|
2894
|
+
*
|
|
2895
|
+
* When `profileName` is provided explicitly (e.g. via `--profile` flag),
|
|
2896
|
+
* it takes precedence over the environment variables, `.fluidrc`, and the
|
|
2897
|
+
* active profile.
|
|
2898
|
+
*/
|
|
2899
|
+
function resolveCredentialSource(profileName) {
|
|
2900
|
+
const config = readConfig();
|
|
2901
|
+
if (profileName) {
|
|
2902
|
+
const profile = config.profiles[profileName];
|
|
2903
|
+
return profile ? {
|
|
2904
|
+
kind: "profile",
|
|
2905
|
+
profile
|
|
2906
|
+
} : null;
|
|
2907
|
+
}
|
|
2908
|
+
const envToken = process.env["FLUID_TOKEN"] ?? process.env["FLUID_API_TOKEN"];
|
|
2909
|
+
if (envToken) return {
|
|
2910
|
+
kind: "token",
|
|
2911
|
+
token: envToken
|
|
2912
|
+
};
|
|
2913
|
+
const projectConfig = findProjectConfig(process.cwd());
|
|
2914
|
+
if (projectConfig?.profile) {
|
|
2915
|
+
const profile = config.profiles[projectConfig.profile];
|
|
2916
|
+
if (profile) return {
|
|
2917
|
+
kind: "profile",
|
|
2918
|
+
profile
|
|
2919
|
+
};
|
|
2920
|
+
}
|
|
2921
|
+
if (!config.activeProfile) return null;
|
|
2922
|
+
const profile = config.profiles[config.activeProfile];
|
|
2923
|
+
return profile ? {
|
|
2924
|
+
kind: "profile",
|
|
2925
|
+
profile
|
|
2926
|
+
} : null;
|
|
2927
|
+
}
|
|
2928
|
+
/**
|
|
2929
|
+
* Get the auth token for a named profile, or the active profile when omitted,
|
|
2930
|
+
* in the order {@link resolveCredentialSource} describes.
|
|
2931
|
+
*
|
|
2932
|
+
* An identity-mode profile keeps no token in the config file. Its access
|
|
2933
|
+
* token lives in this process's memory once the session has been restored,
|
|
2934
|
+
* which the CLI does before running a command; until then, and after its
|
|
2935
|
+
* session ends, this returns null. Prefer {@link getAuthTokenAsync}, which
|
|
2936
|
+
* restores and refreshes the session itself.
|
|
2937
|
+
*/
|
|
2938
|
+
function getAuthToken(profileName) {
|
|
2939
|
+
const source = resolveCredentialSource(profileName);
|
|
2940
|
+
if (!source) return null;
|
|
2941
|
+
if (source.kind === "token") return source.token;
|
|
2942
|
+
if (isIdentityProfile(source.profile)) return peekIdentityToken(source.profile.name);
|
|
2943
|
+
return source.profile.token ?? null;
|
|
2944
|
+
}
|
|
2945
|
+
/**
|
|
2946
|
+
* Like {@link getAuthToken}, but restores, refreshes, or exchanges an
|
|
2947
|
+
* identity-mode profile's session as needed. Resolves with null when there
|
|
2948
|
+
* is no credential; rejects when an identity session has ended.
|
|
2949
|
+
*/
|
|
2950
|
+
async function getAuthTokenAsync(profileName) {
|
|
2951
|
+
const source = resolveCredentialSource(profileName);
|
|
2952
|
+
if (!source) return null;
|
|
2953
|
+
if (source.kind === "token") return source.token;
|
|
2954
|
+
if (isIdentityProfile(source.profile)) return profileAccessToken(source.profile);
|
|
2955
|
+
return source.profile.token ?? null;
|
|
2956
|
+
}
|
|
2957
|
+
/**
|
|
2958
|
+
* Get the active profile, or null if not logged in
|
|
2959
|
+
*/
|
|
2960
|
+
function getActiveProfile() {
|
|
2961
|
+
const config = readConfig();
|
|
2962
|
+
if (!config.activeProfile) return null;
|
|
2963
|
+
return config.profiles[config.activeProfile] ?? null;
|
|
2964
|
+
}
|
|
2965
|
+
/**
|
|
2966
|
+
* List all stored profile names
|
|
2967
|
+
*/
|
|
2968
|
+
function listProfileNames() {
|
|
2969
|
+
const config = readConfig();
|
|
2970
|
+
return Object.keys(config.profiles);
|
|
2971
|
+
}
|
|
2972
|
+
//#endregion
|
|
2973
|
+
export { validateToken as A, tryCatch as B, FLUID_API_ERROR as C, redeemIdentityLink as D, getFluidApiBase as E, isNodeError as F, rootCommand as G, unwrap as H, isSuccess as I, walkCommands as J, visibleOptions as K, mapError as L, getErrorMessage$1 as M, isError as N, sendMfa as O, isFailure as P, mapResult as R, isIdentityProfile as S, fetchUserCompanies as T, unwrapOr as U, tryCatchAsync as V, filterCatalog as W, describeCommand as Y, signInWithBrowser as _, resolveCredentialSource as a, createFetchClient as b, updateConfig as c, getConfigFilePath as d, describeIdentityError as f, sessionFacts as g, profileAccessToken as h, listProfileNames as i, failure as j, switchCompany as k, writeConfig as l, primeIdentityProfile as m, getAuthToken as n, findProjectConfig as o, identityToken as p, visibleSubcommands as q, getAuthTokenAsync as r, readConfig as s, getActiveProfile as t, getConfigDir as u, signOutIdentity as v, confirmMfa as w, createDefaultConfig as x, resolveIdentityUrl as y, success as z };
|
|
2974
|
+
|
|
2975
|
+
//# sourceMappingURL=token-BUGqpr-U.mjs.map
|