@fluid-app/fluid-cli 0.1.692 → 0.1.694
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 +4 -0
- package/dist/bin/fluid.mjs +233 -8
- package/dist/bin/fluid.mjs.map +1 -1
- package/dist/client-DU__lstz.mjs +2 -0
- package/dist/hook-DJNt29x1.mjs +1377 -0
- package/dist/hook-DJNt29x1.mjs.map +1 -0
- package/dist/index.d.mts +15 -0
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -1
- package/dist/index.mjs.map +1 -1
- package/dist/{hook-CV4vUh4j.mjs → profiles-CpG6O9Zi.mjs} +84 -1290
- package/dist/profiles-CpG6O9Zi.mjs.map +1 -0
- package/package.json +1 -1
- package/dist/hook-CV4vUh4j.mjs.map +0 -1
|
@@ -0,0 +1,1377 @@
|
|
|
1
|
+
import { A as isClientProfile, a as peekIdentityToken, b as readConfig, g as peekClientToken, j as isIdentityProfile, p as clientAccessToken, s as profileAccessToken } from "./profiles-CpG6O9Zi.mjs";
|
|
2
|
+
import { closeSync, constants, existsSync, fstatSync, openSync, readFileSync, readdirSync, realpathSync, writeSync } from "node:fs";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { dirname, isAbsolute, join, sep } from "node:path";
|
|
5
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
6
|
+
//#region src/catalog/annotations.ts
|
|
7
|
+
const ANNOTATION = Symbol.for("@fluid-app/fluid-cli.command-annotation");
|
|
8
|
+
/**
|
|
9
|
+
* Record the endpoints a command calls and whether it writes, so
|
|
10
|
+
* `fluid commands --json` can list them. Returns the command for chaining.
|
|
11
|
+
*/
|
|
12
|
+
function describeCommand(command, annotation) {
|
|
13
|
+
const target = command;
|
|
14
|
+
target[ANNOTATION] = {
|
|
15
|
+
...target[ANNOTATION],
|
|
16
|
+
...annotation
|
|
17
|
+
};
|
|
18
|
+
return command;
|
|
19
|
+
}
|
|
20
|
+
function readAnnotation(command) {
|
|
21
|
+
return command[ANNOTATION] ?? null;
|
|
22
|
+
}
|
|
23
|
+
//#endregion
|
|
24
|
+
//#region src/catalog/walk.ts
|
|
25
|
+
function isHidden(command) {
|
|
26
|
+
return command._hidden === true;
|
|
27
|
+
}
|
|
28
|
+
function isRunnable(command) {
|
|
29
|
+
return command._actionHandler != null;
|
|
30
|
+
}
|
|
31
|
+
function visibleSubcommands(command) {
|
|
32
|
+
return command.commands.filter((sub) => !isHidden(sub));
|
|
33
|
+
}
|
|
34
|
+
function visibleOptions(command) {
|
|
35
|
+
return command.options.filter((option) => !option.hidden);
|
|
36
|
+
}
|
|
37
|
+
function describeOption(option) {
|
|
38
|
+
return {
|
|
39
|
+
flags: option.flags,
|
|
40
|
+
long: option.long ?? null,
|
|
41
|
+
short: option.short ?? null,
|
|
42
|
+
description: option.description,
|
|
43
|
+
takesValue: option.required,
|
|
44
|
+
optionalValue: option.optional,
|
|
45
|
+
required: option.mandatory,
|
|
46
|
+
defaultValue: option.defaultValue
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
function describeArgument(argument) {
|
|
50
|
+
return {
|
|
51
|
+
name: argument.name(),
|
|
52
|
+
description: argument.description,
|
|
53
|
+
required: argument.required,
|
|
54
|
+
variadic: argument.variadic
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
function inferWrites(command, declared) {
|
|
58
|
+
if (declared !== void 0) return declared;
|
|
59
|
+
return command.options.some((option) => option.long === "--yes") ? true : null;
|
|
60
|
+
}
|
|
61
|
+
function walkCommands(root) {
|
|
62
|
+
const entries = [];
|
|
63
|
+
function visit(command, path, ancestors) {
|
|
64
|
+
const annotation = readAnnotation(command);
|
|
65
|
+
const subcommands = visibleSubcommands(command);
|
|
66
|
+
entries.push({
|
|
67
|
+
command: path.join(" "),
|
|
68
|
+
path,
|
|
69
|
+
description: command.description(),
|
|
70
|
+
aliases: command.aliases(),
|
|
71
|
+
arguments: command.registeredArguments.map(describeArgument),
|
|
72
|
+
options: visibleOptions(command).map(describeOption),
|
|
73
|
+
inheritsOptionsFrom: ancestors.filter((ancestor) => visibleOptions(ancestor).some((option) => option.long !== "--version")).map((ancestor) => commandPath$1(ancestor).join(" ")),
|
|
74
|
+
subcommands: subcommands.map((sub) => sub.name()),
|
|
75
|
+
runnable: isRunnable(command),
|
|
76
|
+
writes: inferWrites(command, annotation?.writes),
|
|
77
|
+
endpoints: annotation?.endpoints ?? null
|
|
78
|
+
});
|
|
79
|
+
for (const sub of subcommands) visit(sub, [...path, sub.name()], [...ancestors, command]);
|
|
80
|
+
}
|
|
81
|
+
visit(root, [root.name()], []);
|
|
82
|
+
return entries;
|
|
83
|
+
}
|
|
84
|
+
function rootCommand(command) {
|
|
85
|
+
let root = command;
|
|
86
|
+
while (root.parent) root = root.parent;
|
|
87
|
+
return root;
|
|
88
|
+
}
|
|
89
|
+
function commandPath$1(command) {
|
|
90
|
+
const path = [];
|
|
91
|
+
for (let c = command; c; c = c.parent) path.unshift(c.name());
|
|
92
|
+
return path;
|
|
93
|
+
}
|
|
94
|
+
/** Keep the entries at or under `prefix`, matching names or aliases. */
|
|
95
|
+
function filterCatalog(entries, root, prefix) {
|
|
96
|
+
let target = root;
|
|
97
|
+
for (const word of prefix) {
|
|
98
|
+
const next = visibleSubcommands(target).find((sub) => sub.name() === word || sub.aliases().includes(word));
|
|
99
|
+
if (!next) return [];
|
|
100
|
+
target = next;
|
|
101
|
+
}
|
|
102
|
+
const base = commandPath$1(target);
|
|
103
|
+
return entries.filter((entry) => base.every((word, index) => entry.path[index] === word));
|
|
104
|
+
}
|
|
105
|
+
//#endregion
|
|
106
|
+
//#region package.json
|
|
107
|
+
var version = "0.1.694";
|
|
108
|
+
//#endregion
|
|
109
|
+
//#region src/auth/client-headers.ts
|
|
110
|
+
const CLIENT_HEADERS = {
|
|
111
|
+
"X-Fluid-Client": "cli",
|
|
112
|
+
"X-Fluid-Client-Version": version
|
|
113
|
+
};
|
|
114
|
+
//#endregion
|
|
115
|
+
//#region src/utils/result.ts
|
|
116
|
+
function success(value) {
|
|
117
|
+
return {
|
|
118
|
+
success: true,
|
|
119
|
+
value
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
function failure(error) {
|
|
123
|
+
return {
|
|
124
|
+
success: false,
|
|
125
|
+
error
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
function isSuccess(result) {
|
|
129
|
+
return result.success === true;
|
|
130
|
+
}
|
|
131
|
+
function isFailure(result) {
|
|
132
|
+
return result.success === false;
|
|
133
|
+
}
|
|
134
|
+
function tryCatch(fn) {
|
|
135
|
+
try {
|
|
136
|
+
return success(fn());
|
|
137
|
+
} catch (error) {
|
|
138
|
+
return failure(error instanceof Error ? error : new Error(String(error)));
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
async function tryCatchAsync(fn) {
|
|
142
|
+
try {
|
|
143
|
+
return success(await fn());
|
|
144
|
+
} catch (error) {
|
|
145
|
+
return failure(error instanceof Error ? error : new Error(String(error)));
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
function unwrap(result) {
|
|
149
|
+
if (isSuccess(result)) return result.value;
|
|
150
|
+
if (result.error instanceof Error) throw result.error;
|
|
151
|
+
throw new Error(typeof result.error === "object" && result.error !== null ? JSON.stringify(result.error) : String(result.error));
|
|
152
|
+
}
|
|
153
|
+
function unwrapOr(result, defaultValue) {
|
|
154
|
+
if (isSuccess(result)) return result.value;
|
|
155
|
+
return defaultValue;
|
|
156
|
+
}
|
|
157
|
+
function mapResult(result, fn) {
|
|
158
|
+
if (isSuccess(result)) return success(fn(result.value));
|
|
159
|
+
return result;
|
|
160
|
+
}
|
|
161
|
+
function mapError(result, fn) {
|
|
162
|
+
if (isFailure(result)) return failure(fn(result.error));
|
|
163
|
+
return result;
|
|
164
|
+
}
|
|
165
|
+
function isError(value) {
|
|
166
|
+
return value instanceof Error;
|
|
167
|
+
}
|
|
168
|
+
function isNodeError(value) {
|
|
169
|
+
return value instanceof Error && "code" in value;
|
|
170
|
+
}
|
|
171
|
+
function getErrorMessage(error) {
|
|
172
|
+
if (error instanceof Error) return error.message;
|
|
173
|
+
if (typeof error === "string") return error;
|
|
174
|
+
return String(error);
|
|
175
|
+
}
|
|
176
|
+
//#endregion
|
|
177
|
+
//#region src/auth/fluid-api.ts
|
|
178
|
+
/**
|
|
179
|
+
* Fluid API client for authentication operations, and the public signup
|
|
180
|
+
* that comes before any of them
|
|
181
|
+
*/
|
|
182
|
+
const API_TIMEOUT_MS = 1e4;
|
|
183
|
+
const SIGNUP_TIMEOUT_MS = 6e4;
|
|
184
|
+
/** Whether `base` is plain http to a host other than this machine. */
|
|
185
|
+
function isInsecureRemoteBase(base) {
|
|
186
|
+
let url;
|
|
187
|
+
try {
|
|
188
|
+
url = new URL(base);
|
|
189
|
+
} catch {
|
|
190
|
+
return false;
|
|
191
|
+
}
|
|
192
|
+
if (url.protocol !== "http:") return false;
|
|
193
|
+
const host = url.hostname;
|
|
194
|
+
return !(host === "localhost" || host === "127.0.0.1" || host === "[::1]" || host.endsWith(".localhost"));
|
|
195
|
+
}
|
|
196
|
+
function getFluidApiBase() {
|
|
197
|
+
return process.env["FLUID_API_BASE"] ?? "https://api.fluid.app";
|
|
198
|
+
}
|
|
199
|
+
function makeSignal(timeoutMs = API_TIMEOUT_MS) {
|
|
200
|
+
const controller = new AbortController();
|
|
201
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
202
|
+
return {
|
|
203
|
+
signal: controller.signal,
|
|
204
|
+
cleanup: () => clearTimeout(timer)
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
const FLUID_API_ERROR = {
|
|
208
|
+
INVALID_TOKEN: {
|
|
209
|
+
code: "INVALID_TOKEN",
|
|
210
|
+
message: "Token is invalid or expired"
|
|
211
|
+
},
|
|
212
|
+
API_UNREACHABLE: {
|
|
213
|
+
code: "API_UNREACHABLE",
|
|
214
|
+
message: "Could not reach the Fluid API"
|
|
215
|
+
},
|
|
216
|
+
SIGN_IN_UNFINISHED: {
|
|
217
|
+
code: "SIGN_IN_UNFINISHED",
|
|
218
|
+
message: "This sign-in can't be finished. Check the shop and the address, then request a new code"
|
|
219
|
+
},
|
|
220
|
+
CODE_EXPIRED: {
|
|
221
|
+
code: "CODE_EXPIRED",
|
|
222
|
+
message: "Verification code has expired, was already used, or is locked after too many attempts — please request a new one"
|
|
223
|
+
},
|
|
224
|
+
RATE_LIMITED: {
|
|
225
|
+
code: "RATE_LIMITED",
|
|
226
|
+
message: "Too many sign-in requests — wait a minute and try again"
|
|
227
|
+
},
|
|
228
|
+
INVALID_CODE: {
|
|
229
|
+
code: "INVALID_CODE",
|
|
230
|
+
message: "Verification code is invalid, expired, already used, or locked after too many attempts"
|
|
231
|
+
},
|
|
232
|
+
CONTACT_MISSING: {
|
|
233
|
+
code: "CONTACT_MISSING",
|
|
234
|
+
message: "The code is right, but the email or phone it was sent to is no longer on this account. Ask the company's admin to restore it"
|
|
235
|
+
},
|
|
236
|
+
COMPANY_NOT_FOUND: {
|
|
237
|
+
code: "COMPANY_NOT_FOUND",
|
|
238
|
+
message: "Company not found"
|
|
239
|
+
},
|
|
240
|
+
SWITCH_FAILED: {
|
|
241
|
+
code: "SWITCH_FAILED",
|
|
242
|
+
message: "Failed to switch company"
|
|
243
|
+
},
|
|
244
|
+
LINK_GONE: {
|
|
245
|
+
code: "LINK_GONE",
|
|
246
|
+
message: "This sign-in link has expired or was already used — run `fluid login` for a new one"
|
|
247
|
+
}
|
|
248
|
+
};
|
|
249
|
+
function createApiError(template, details) {
|
|
250
|
+
return {
|
|
251
|
+
code: template.code,
|
|
252
|
+
message: template.message,
|
|
253
|
+
details
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Validate a token against the Fluid API and return company info.
|
|
258
|
+
* `baseUrl` is the API the token belongs to; it defaults to the CLI's.
|
|
259
|
+
*/
|
|
260
|
+
async function validateToken(token, options = {}) {
|
|
261
|
+
const { signal, cleanup } = makeSignal();
|
|
262
|
+
const apiBase = options.baseUrl ?? getFluidApiBase();
|
|
263
|
+
try {
|
|
264
|
+
const response = await fetch(`${apiBase}/api/company/v1/companies/me`, {
|
|
265
|
+
method: "GET",
|
|
266
|
+
headers: {
|
|
267
|
+
...CLIENT_HEADERS,
|
|
268
|
+
Authorization: `Bearer ${token}`
|
|
269
|
+
},
|
|
270
|
+
signal
|
|
271
|
+
});
|
|
272
|
+
if (response.ok) {
|
|
273
|
+
const name = (await response.json())?.data?.company?.name;
|
|
274
|
+
if (!name) return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, "Unexpected response shape from /companies/me"));
|
|
275
|
+
return success({ name });
|
|
276
|
+
}
|
|
277
|
+
if (response.status === 403) return await staffCompanyFromMe(token, apiBase, signal);
|
|
278
|
+
if (response.status === 401) return failure(createApiError(FLUID_API_ERROR.INVALID_TOKEN, `HTTP ${response.status}: Check that your token is valid and non-expired.`));
|
|
279
|
+
const body = await response.text();
|
|
280
|
+
return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, `HTTP ${response.status}: ${body}`));
|
|
281
|
+
} catch (err) {
|
|
282
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
283
|
+
return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, message));
|
|
284
|
+
} finally {
|
|
285
|
+
cleanup();
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
/** The roles a CLI login may hold, as `/api/me` names them. */
|
|
289
|
+
const STAFF_ROLES = new Set(["admin", "rep"]);
|
|
290
|
+
/**
|
|
291
|
+
* The company of an admin's or a rep's login, from `/api/me`. A token it
|
|
292
|
+
* refuses, or one that belongs to a customer, is invalid for the CLI; any
|
|
293
|
+
* other failure, or an answer with no company name, leaves the API
|
|
294
|
+
* unreachable, as `/companies/me` does.
|
|
295
|
+
*/
|
|
296
|
+
async function staffCompanyFromMe(token, apiBase, signal) {
|
|
297
|
+
const response = await fetch(`${apiBase}/api/me`, {
|
|
298
|
+
method: "GET",
|
|
299
|
+
headers: {
|
|
300
|
+
...CLIENT_HEADERS,
|
|
301
|
+
Authorization: `Bearer ${token}`
|
|
302
|
+
},
|
|
303
|
+
signal
|
|
304
|
+
});
|
|
305
|
+
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.`));
|
|
306
|
+
if (!response.ok) {
|
|
307
|
+
const body = await response.text();
|
|
308
|
+
return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, `HTTP ${response.status} from /api/me: ${body}`));
|
|
309
|
+
}
|
|
310
|
+
const data = await response.json();
|
|
311
|
+
if (typeof data?.role !== "string" || !STAFF_ROLES.has(data.role)) return failure(createApiError(FLUID_API_ERROR.INVALID_TOKEN, "This login is not an admin's or a rep's, so it cannot be used with the CLI."));
|
|
312
|
+
const name = data.company?.name;
|
|
313
|
+
if (typeof name !== "string" || name === "") return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, "Unexpected response shape from /api/me"));
|
|
314
|
+
return success({ name });
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* Send a multi-factor authentication code to the given email address.
|
|
318
|
+
* The API answers 201 whether or not the address can sign in
|
|
319
|
+
* (anti-enumeration).
|
|
320
|
+
*
|
|
321
|
+
* With `fluidShop`, the server ties the code to the person's membership in
|
|
322
|
+
* that company, so redeeming it signs in to that company alone and, for an
|
|
323
|
+
* admin's emailed code, confirms a new signup.
|
|
324
|
+
*/
|
|
325
|
+
async function sendMfa(email, options = {}) {
|
|
326
|
+
const { signal, cleanup } = makeSignal();
|
|
327
|
+
try {
|
|
328
|
+
const response = await fetch(`${getFluidApiBase()}/api/authentication/send_mfa`, {
|
|
329
|
+
method: "POST",
|
|
330
|
+
headers: {
|
|
331
|
+
...CLIENT_HEADERS,
|
|
332
|
+
"Content-Type": "application/json"
|
|
333
|
+
},
|
|
334
|
+
body: JSON.stringify(options.fluidShop ? {
|
|
335
|
+
email,
|
|
336
|
+
fluid_shop: options.fluidShop
|
|
337
|
+
} : { email }),
|
|
338
|
+
signal
|
|
339
|
+
});
|
|
340
|
+
if (response.status === 201) {
|
|
341
|
+
const data = await response.json();
|
|
342
|
+
const uuid = data.multi_factor_authentication?.uuid;
|
|
343
|
+
const expiresAt = data.multi_factor_authentication?.verification_code_expires_at;
|
|
344
|
+
if (!uuid || !expiresAt) return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, "Unexpected response shape from /send_mfa"));
|
|
345
|
+
return success({
|
|
346
|
+
uuid,
|
|
347
|
+
expiresAt
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
const body = await response.text();
|
|
351
|
+
if (response.status === 429) return failure(createApiError(FLUID_API_ERROR.RATE_LIMITED, `HTTP 429: ${body}`));
|
|
352
|
+
return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, `HTTP ${response.status}: ${body}`));
|
|
353
|
+
} catch (err) {
|
|
354
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
355
|
+
return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, message));
|
|
356
|
+
} finally {
|
|
357
|
+
cleanup();
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Confirm a multi-factor authentication code and retrieve company JWTs.
|
|
362
|
+
*
|
|
363
|
+
* `baseUrl` is the API the code was sent from; a sign-in finished in a
|
|
364
|
+
* later process passes the one it saved, not the current environment's.
|
|
365
|
+
*/
|
|
366
|
+
async function confirmMfa(uuid, code, options = {}) {
|
|
367
|
+
const { signal, cleanup } = makeSignal();
|
|
368
|
+
const apiBase = options.baseUrl ?? getFluidApiBase();
|
|
369
|
+
try {
|
|
370
|
+
const response = await fetch(`${apiBase}/api/authentication/confirm_mfa`, {
|
|
371
|
+
method: "POST",
|
|
372
|
+
headers: {
|
|
373
|
+
...CLIENT_HEADERS,
|
|
374
|
+
"Content-Type": "application/json"
|
|
375
|
+
},
|
|
376
|
+
body: JSON.stringify({
|
|
377
|
+
uuid,
|
|
378
|
+
multi_factor_authentication: { verification_code: code },
|
|
379
|
+
...options.fluidShop ? { fluid_shop: options.fluidShop } : {}
|
|
380
|
+
}),
|
|
381
|
+
signal
|
|
382
|
+
});
|
|
383
|
+
if (response.ok) {
|
|
384
|
+
const data = await response.json();
|
|
385
|
+
if (!data.authenticated) return failure(createApiError(FLUID_API_ERROR.INVALID_CODE, "Authentication was not confirmed by the server"));
|
|
386
|
+
const companies = Array.isArray(data.companies) ? data.companies : [];
|
|
387
|
+
return success({
|
|
388
|
+
authType: data.auth_type ?? "",
|
|
389
|
+
companies: companies.map((c) => ({
|
|
390
|
+
id: c.id,
|
|
391
|
+
name: c.name,
|
|
392
|
+
shopName: c.shop_name,
|
|
393
|
+
jwt: c.jwt,
|
|
394
|
+
...c.auth_type ? { authType: c.auth_type } : {}
|
|
395
|
+
})),
|
|
396
|
+
signInPath: data.sign_in_path === "identity" ? "identity" : "legacy"
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
if (response.status === 404) return failure(createApiError(FLUID_API_ERROR.SIGN_IN_UNFINISHED));
|
|
400
|
+
if (response.status === 410) return failure(createApiError(FLUID_API_ERROR.CODE_EXPIRED));
|
|
401
|
+
const body = await response.text();
|
|
402
|
+
if (response.status === 422) return failure(createApiError(namesVerificationChannel(body) ? FLUID_API_ERROR.CONTACT_MISSING : FLUID_API_ERROR.INVALID_CODE));
|
|
403
|
+
if (response.status === 429) return failure(createApiError(FLUID_API_ERROR.RATE_LIMITED, `HTTP 429: ${body}`));
|
|
404
|
+
return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, `HTTP ${response.status}: ${body}`));
|
|
405
|
+
} catch (err) {
|
|
406
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
407
|
+
return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, message));
|
|
408
|
+
} finally {
|
|
409
|
+
cleanup();
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
/**
|
|
413
|
+
* Redeem the single-use token in an identity sign-in email, the email a
|
|
414
|
+
* person whose company signs in through the identity service receives
|
|
415
|
+
* instead of a code. Rails answers 410 for a forged, expired, or used link.
|
|
416
|
+
*/
|
|
417
|
+
async function redeemIdentityLink(token, options = {}) {
|
|
418
|
+
const { signal, cleanup } = makeSignal();
|
|
419
|
+
try {
|
|
420
|
+
const response = await fetch(`${options.baseUrl ?? getFluidApiBase()}/api/v2026-10/single-sign-ons/identity-link-redemptions`, {
|
|
421
|
+
method: "POST",
|
|
422
|
+
headers: {
|
|
423
|
+
...CLIENT_HEADERS,
|
|
424
|
+
"Content-Type": "application/json"
|
|
425
|
+
},
|
|
426
|
+
body: JSON.stringify({ token }),
|
|
427
|
+
signal
|
|
428
|
+
});
|
|
429
|
+
if (response.ok) {
|
|
430
|
+
const data = await response.json();
|
|
431
|
+
if (data.sign_in_path !== "identity" || !data.fluid_shop) return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, "Unexpected response shape from /identity-link-redemptions"));
|
|
432
|
+
return success({
|
|
433
|
+
signInPath: "identity",
|
|
434
|
+
fluidShop: data.fluid_shop
|
|
435
|
+
});
|
|
436
|
+
}
|
|
437
|
+
if (response.status === 410 || response.status === 404) return failure(createApiError(FLUID_API_ERROR.LINK_GONE));
|
|
438
|
+
const body = await response.text();
|
|
439
|
+
return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, `HTTP ${response.status}: ${body}`));
|
|
440
|
+
} catch (err) {
|
|
441
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
442
|
+
return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, message));
|
|
443
|
+
} finally {
|
|
444
|
+
cleanup();
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
/**
|
|
448
|
+
* Fetch all companies the authenticated user has access to.
|
|
449
|
+
*/
|
|
450
|
+
async function fetchUserCompanies(token, baseUrl) {
|
|
451
|
+
const { signal, cleanup } = makeSignal();
|
|
452
|
+
const apiBase = baseUrl ?? getFluidApiBase();
|
|
453
|
+
try {
|
|
454
|
+
const response = await fetch(`${apiBase}/api/me`, {
|
|
455
|
+
method: "GET",
|
|
456
|
+
headers: {
|
|
457
|
+
...CLIENT_HEADERS,
|
|
458
|
+
Authorization: `Bearer ${token}`
|
|
459
|
+
},
|
|
460
|
+
signal
|
|
461
|
+
});
|
|
462
|
+
if (response.ok) {
|
|
463
|
+
const data = await response.json();
|
|
464
|
+
return success((Array.isArray(data.companies) ? data.companies : []).map((c) => ({
|
|
465
|
+
id: c.id,
|
|
466
|
+
name: c.name,
|
|
467
|
+
...typeof c.uuid_v7 === "string" ? { uuidV7: c.uuid_v7 } : {}
|
|
468
|
+
})));
|
|
469
|
+
}
|
|
470
|
+
if (response.status === 401 || response.status === 403) return failure(createApiError(FLUID_API_ERROR.INVALID_TOKEN, `HTTP ${response.status}`));
|
|
471
|
+
const body = await response.text();
|
|
472
|
+
return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, `HTTP ${response.status}: ${body}`));
|
|
473
|
+
} catch (err) {
|
|
474
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
475
|
+
return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, message));
|
|
476
|
+
} finally {
|
|
477
|
+
cleanup();
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
/**
|
|
481
|
+
* Switch to a different company and receive a new JWT.
|
|
482
|
+
*
|
|
483
|
+
* Response shape (from @fluid-app/auth SwitchCompanyResponse):
|
|
484
|
+
* { company: { id, name, fluid_shop, jwt }, meta: { request_id, timestamp } }
|
|
485
|
+
*/
|
|
486
|
+
async function switchCompany(token, companyId, baseUrl) {
|
|
487
|
+
const { signal, cleanup } = makeSignal();
|
|
488
|
+
const apiBase = baseUrl ?? getFluidApiBase();
|
|
489
|
+
try {
|
|
490
|
+
const response = await fetch(`${apiBase}/api/authentication/company/${companyId}/switch`, {
|
|
491
|
+
method: "PUT",
|
|
492
|
+
headers: {
|
|
493
|
+
...CLIENT_HEADERS,
|
|
494
|
+
Authorization: `Bearer ${token}`,
|
|
495
|
+
"Content-Type": "application/json"
|
|
496
|
+
},
|
|
497
|
+
signal
|
|
498
|
+
});
|
|
499
|
+
if (response.ok) {
|
|
500
|
+
const company = (await response.json()).company;
|
|
501
|
+
if (!company?.jwt) return failure(createApiError(FLUID_API_ERROR.SWITCH_FAILED, "Unexpected response shape from /switch"));
|
|
502
|
+
return success({
|
|
503
|
+
companyId: company.id,
|
|
504
|
+
companyName: company.name,
|
|
505
|
+
fluidShop: company.fluid_shop,
|
|
506
|
+
jwt: company.jwt
|
|
507
|
+
});
|
|
508
|
+
}
|
|
509
|
+
if (response.status === 404) return failure(createApiError(FLUID_API_ERROR.COMPANY_NOT_FOUND, `Company ${companyId} not found`));
|
|
510
|
+
if (response.status === 401 || response.status === 403) return failure(createApiError(FLUID_API_ERROR.INVALID_TOKEN, `HTTP ${response.status}`));
|
|
511
|
+
const body = await response.text();
|
|
512
|
+
return failure(createApiError(FLUID_API_ERROR.SWITCH_FAILED, `HTTP ${response.status}: ${body}`));
|
|
513
|
+
} catch (err) {
|
|
514
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
515
|
+
return failure(createApiError(FLUID_API_ERROR.API_UNREACHABLE, message));
|
|
516
|
+
} finally {
|
|
517
|
+
cleanup();
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
const SIGNUP_ERROR = {
|
|
521
|
+
SUBDOMAIN_TAKEN: {
|
|
522
|
+
code: "SUBDOMAIN_TAKEN",
|
|
523
|
+
message: "That subdomain belongs to another company. Pick another, unless an earlier signup of yours sent it: then the company exists, so sign in instead."
|
|
524
|
+
},
|
|
525
|
+
SIGNUP_MAY_EXIST: {
|
|
526
|
+
code: "SIGNUP_MAY_EXIST",
|
|
527
|
+
message: "The signup failed, and the company may still have been created. Run the same command once more with the same subdomain: if it then says the subdomain is taken, the company exists, so sign in instead."
|
|
528
|
+
},
|
|
529
|
+
SIGNUP_INVALID: {
|
|
530
|
+
code: "SIGNUP_INVALID",
|
|
531
|
+
message: "Fluid rejected the signup. See errors for each field."
|
|
532
|
+
},
|
|
533
|
+
RATE_LIMITED: {
|
|
534
|
+
code: "RATE_LIMITED",
|
|
535
|
+
message: "Too many signups from this address or for this email. Failed attempts count too, so wait out the retry time before trying again."
|
|
536
|
+
},
|
|
537
|
+
SIGNUP_FORBIDDEN: {
|
|
538
|
+
code: "SIGNUP_FORBIDDEN",
|
|
539
|
+
message: "Fluid refused this signup. Don't retry; contact Fluid support."
|
|
540
|
+
},
|
|
541
|
+
SIGNUP_OUTCOME_UNKNOWN: {
|
|
542
|
+
code: "SIGNUP_OUTCOME_UNKNOWN",
|
|
543
|
+
message: "No usable answer from Fluid, so the company may or may not have been created. Check before retrying: sign in, or run the same command once more and read a 'subdomain is taken' as created."
|
|
544
|
+
}
|
|
545
|
+
};
|
|
546
|
+
function signupError(template, extra = {}) {
|
|
547
|
+
return {
|
|
548
|
+
code: template.code,
|
|
549
|
+
message: template.message,
|
|
550
|
+
...extra
|
|
551
|
+
};
|
|
552
|
+
}
|
|
553
|
+
function asRecord(value) {
|
|
554
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
555
|
+
}
|
|
556
|
+
/** Whether a confirm 422 body names the verification channel. */
|
|
557
|
+
function namesVerificationChannel(body) {
|
|
558
|
+
try {
|
|
559
|
+
const errors = asRecord(asRecord(JSON.parse(body))?.errors);
|
|
560
|
+
return errors !== void 0 && fieldMessages(errors, "multi_factor_authentication", "verification_channel").length > 0;
|
|
561
|
+
} catch {
|
|
562
|
+
return false;
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
function fieldMessages(errors, record, field) {
|
|
566
|
+
const messages = asRecord(errors[record])?.[field];
|
|
567
|
+
return Array.isArray(messages) ? messages.filter((m) => typeof m === "string") : [];
|
|
568
|
+
}
|
|
569
|
+
function signupRejection(body) {
|
|
570
|
+
const errors = asRecord(asRecord(body)?.["errors"]) ?? {};
|
|
571
|
+
if (fieldMessages(errors, "company", "subdomain").some((m) => m.includes("taken"))) return signupError(SIGNUP_ERROR.SUBDOMAIN_TAKEN, {
|
|
572
|
+
status: 422,
|
|
573
|
+
errors
|
|
574
|
+
});
|
|
575
|
+
if (fieldMessages(errors, "company", "base").length > 0) return signupError(SIGNUP_ERROR.SIGNUP_MAY_EXIST, {
|
|
576
|
+
status: 422,
|
|
577
|
+
errors
|
|
578
|
+
});
|
|
579
|
+
return signupError(SIGNUP_ERROR.SIGNUP_INVALID, {
|
|
580
|
+
status: 422,
|
|
581
|
+
errors
|
|
582
|
+
});
|
|
583
|
+
}
|
|
584
|
+
function readSignup(body) {
|
|
585
|
+
const root = asRecord(body);
|
|
586
|
+
const company = asRecord(root?.["company"]);
|
|
587
|
+
const userCompany = asRecord(root?.["user_company"]);
|
|
588
|
+
const due = asRecord(root?.["requirements"])?.["currently_due"];
|
|
589
|
+
if (typeof company?.["id"] !== "number" || typeof company["fluid_shop"] !== "string" || typeof userCompany?.["id"] !== "number") return;
|
|
590
|
+
const agent = readAgentAccess(root?.["agent_access"]);
|
|
591
|
+
return {
|
|
592
|
+
company: {
|
|
593
|
+
id: company["id"],
|
|
594
|
+
name: String(company["name"] ?? ""),
|
|
595
|
+
subdomain: String(company["subdomain"] ?? ""),
|
|
596
|
+
fluidShop: company["fluid_shop"]
|
|
597
|
+
},
|
|
598
|
+
userCompany: {
|
|
599
|
+
id: userCompany["id"],
|
|
600
|
+
email: String(userCompany["email"] ?? "")
|
|
601
|
+
},
|
|
602
|
+
currentlyDue: Array.isArray(due) ? due.filter((d) => typeof d === "string") : [],
|
|
603
|
+
...agent ? { agentAccess: agent } : {}
|
|
604
|
+
};
|
|
605
|
+
}
|
|
606
|
+
function readAgentAccess(value) {
|
|
607
|
+
const agent = asRecord(value);
|
|
608
|
+
const handle = agent?.["handle"];
|
|
609
|
+
const approvalUrl = agent?.["approval_url"];
|
|
610
|
+
const expiresAt = agent?.["expires_at"];
|
|
611
|
+
const companyUuid = agent?.["company_uuid"];
|
|
612
|
+
if (typeof handle !== "string" || typeof approvalUrl !== "string" || typeof expiresAt !== "string" || typeof companyUuid !== "string" || !handle) return;
|
|
613
|
+
return {
|
|
614
|
+
handle,
|
|
615
|
+
approvalUrl,
|
|
616
|
+
expiresAt,
|
|
617
|
+
companyUuid
|
|
618
|
+
};
|
|
619
|
+
}
|
|
620
|
+
async function readJson(response) {
|
|
621
|
+
try {
|
|
622
|
+
return await response.json();
|
|
623
|
+
} catch {
|
|
624
|
+
return;
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
/**
|
|
628
|
+
* Sign up a new company with the public, unauthenticated `POST /api/company`.
|
|
629
|
+
*
|
|
630
|
+
* Sends exactly one request and never retries it: a 422 can follow a saved
|
|
631
|
+
* company, and every attempt, failed or not, counts toward the per-IP and
|
|
632
|
+
* per-email signup limits.
|
|
633
|
+
*/
|
|
634
|
+
async function signup(request) {
|
|
635
|
+
const { signal, cleanup } = makeSignal(SIGNUP_TIMEOUT_MS);
|
|
636
|
+
try {
|
|
637
|
+
const response = await fetch(`${getFluidApiBase()}/api/company`, {
|
|
638
|
+
method: "POST",
|
|
639
|
+
headers: {
|
|
640
|
+
...CLIENT_HEADERS,
|
|
641
|
+
"Content-Type": "application/json"
|
|
642
|
+
},
|
|
643
|
+
body: JSON.stringify({
|
|
644
|
+
user: {
|
|
645
|
+
first_name: request.firstName,
|
|
646
|
+
last_name: request.lastName,
|
|
647
|
+
email: request.email
|
|
648
|
+
},
|
|
649
|
+
company: {
|
|
650
|
+
name: request.companyName,
|
|
651
|
+
subdomain: request.subdomain,
|
|
652
|
+
...request.color ? { color: request.color } : {}
|
|
653
|
+
},
|
|
654
|
+
...request.agentAccess ? { agent_access: { name: request.agentAccess.name } } : {}
|
|
655
|
+
}),
|
|
656
|
+
signal
|
|
657
|
+
});
|
|
658
|
+
const body = await readJson(response);
|
|
659
|
+
if (response.status === 200) {
|
|
660
|
+
const created = readSignup(body);
|
|
661
|
+
return created ? success(created) : failure(signupError(SIGNUP_ERROR.SIGNUP_OUTCOME_UNKNOWN, {
|
|
662
|
+
status: 200,
|
|
663
|
+
details: "Unexpected response shape from POST /api/company"
|
|
664
|
+
}));
|
|
665
|
+
}
|
|
666
|
+
if (response.status === 422) return failure(signupRejection(body));
|
|
667
|
+
if (response.status === 429) {
|
|
668
|
+
const retryAfter = asRecord(body)?.["retry_after"];
|
|
669
|
+
return failure(signupError(SIGNUP_ERROR.RATE_LIMITED, {
|
|
670
|
+
status: 429,
|
|
671
|
+
...typeof retryAfter === "number" ? { retryAfter } : {}
|
|
672
|
+
}));
|
|
673
|
+
}
|
|
674
|
+
if (response.status === 403) return failure(signupError(SIGNUP_ERROR.SIGNUP_FORBIDDEN, { status: 403 }));
|
|
675
|
+
return failure(signupError(SIGNUP_ERROR.SIGNUP_OUTCOME_UNKNOWN, {
|
|
676
|
+
status: response.status,
|
|
677
|
+
details: `HTTP ${response.status}`
|
|
678
|
+
}));
|
|
679
|
+
} catch (err) {
|
|
680
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
681
|
+
return failure(signupError(SIGNUP_ERROR.SIGNUP_OUTCOME_UNKNOWN, { details: message }));
|
|
682
|
+
} finally {
|
|
683
|
+
cleanup();
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
function retryAfterSeconds(response) {
|
|
687
|
+
const value = Number(response.headers.get("Retry-After"));
|
|
688
|
+
return Number.isFinite(value) && value > 0 ? value : void 0;
|
|
689
|
+
}
|
|
690
|
+
/**
|
|
691
|
+
* Asks once for the outcome of an agent-access request. The handle goes in
|
|
692
|
+
* the POST body only: Fluid treats one in the URL as leaked and expires the
|
|
693
|
+
* request. Anything unclear or transient comes back as `retry`; a 404 or a
|
|
694
|
+
* 409 means the request cannot succeed.
|
|
695
|
+
*/
|
|
696
|
+
async function pollAgentAccess(handle) {
|
|
697
|
+
const { signal, cleanup } = makeSignal();
|
|
698
|
+
try {
|
|
699
|
+
const response = await fetch(`${getFluidApiBase()}/api/agent-access/v1/poll`, {
|
|
700
|
+
method: "POST",
|
|
701
|
+
headers: {
|
|
702
|
+
...CLIENT_HEADERS,
|
|
703
|
+
"Content-Type": "application/json"
|
|
704
|
+
},
|
|
705
|
+
body: JSON.stringify({ handle }),
|
|
706
|
+
redirect: "error",
|
|
707
|
+
signal
|
|
708
|
+
});
|
|
709
|
+
const retryAfter = retryAfterSeconds(response);
|
|
710
|
+
const body = asRecord(await readJson(response));
|
|
711
|
+
const status = body?.["status"];
|
|
712
|
+
if (response.status === 429) return {
|
|
713
|
+
state: "slow_down",
|
|
714
|
+
retryAfter: retryAfter ?? 5
|
|
715
|
+
};
|
|
716
|
+
if (response.status === 503 && status === "unavailable") return {
|
|
717
|
+
state: "slow_down",
|
|
718
|
+
retryAfter: retryAfter ?? 60
|
|
719
|
+
};
|
|
720
|
+
if (response.status === 404 || response.status === 409) return { state: "unavailable" };
|
|
721
|
+
if (response.status === 200) {
|
|
722
|
+
if (status === "pending" || status === "issuing_soon") return {
|
|
723
|
+
state: status,
|
|
724
|
+
...retryAfter ? { retryAfter } : {}
|
|
725
|
+
};
|
|
726
|
+
if (status === "denied" || status === "expired" || status === "revoked") return { state: status };
|
|
727
|
+
const clientId = body?.["client_id"];
|
|
728
|
+
const clientSecret = body?.["client_secret"];
|
|
729
|
+
if (status === "delivered" && typeof clientId === "string" && typeof clientSecret === "string" && clientId && clientSecret) return {
|
|
730
|
+
state: "delivered",
|
|
731
|
+
clientId,
|
|
732
|
+
clientSecret
|
|
733
|
+
};
|
|
734
|
+
}
|
|
735
|
+
return {
|
|
736
|
+
state: "retry",
|
|
737
|
+
...retryAfter ? { retryAfter } : {}
|
|
738
|
+
};
|
|
739
|
+
} catch {
|
|
740
|
+
return { state: "retry" };
|
|
741
|
+
} finally {
|
|
742
|
+
cleanup();
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
//#endregion
|
|
746
|
+
//#region src/config/project-config.ts
|
|
747
|
+
/**
|
|
748
|
+
* Project-level config (.fluidrc) reader.
|
|
749
|
+
*
|
|
750
|
+
* Walks upward from a starting directory to find a `.fluidrc` file.
|
|
751
|
+
* The file is JSON with a `profile` field that maps to a profile name
|
|
752
|
+
* in `~/.fluid/config.json`.
|
|
753
|
+
*
|
|
754
|
+
* This allows portal repos to pin themselves to a specific CLI profile
|
|
755
|
+
* so that `fluid portal pull` / `push` always use the correct company
|
|
756
|
+
* credentials, regardless of which profile is globally active.
|
|
757
|
+
*/
|
|
758
|
+
const RC_FILENAME = ".fluidrc";
|
|
759
|
+
/** Cached result keyed by the starting directory. */
|
|
760
|
+
let cachedResult;
|
|
761
|
+
/**
|
|
762
|
+
* Walk upward from `startDir` looking for a `.fluidrc` file.
|
|
763
|
+
*
|
|
764
|
+
* Returns the parsed config when found, or `null` if no valid `.fluidrc`
|
|
765
|
+
* exists in any ancestor directory.
|
|
766
|
+
*
|
|
767
|
+
* The result is cached per starting directory for the lifetime of the
|
|
768
|
+
* process — CLI commands are short-lived so stale-cache is not a concern.
|
|
769
|
+
*/
|
|
770
|
+
function findProjectConfig(startDir) {
|
|
771
|
+
if (cachedResult && cachedResult.dir === startDir) return cachedResult.config;
|
|
772
|
+
let dir = startDir;
|
|
773
|
+
while (true) {
|
|
774
|
+
const rcPath = join(dir, RC_FILENAME);
|
|
775
|
+
if (existsSync(rcPath)) {
|
|
776
|
+
try {
|
|
777
|
+
const raw = readFileSync(rcPath, "utf8");
|
|
778
|
+
const parsed = JSON.parse(raw);
|
|
779
|
+
if (typeof parsed.profile === "string" && parsed.profile.length > 0) {
|
|
780
|
+
const config = { profile: parsed.profile };
|
|
781
|
+
cachedResult = {
|
|
782
|
+
dir: startDir,
|
|
783
|
+
config
|
|
784
|
+
};
|
|
785
|
+
return config;
|
|
786
|
+
}
|
|
787
|
+
} catch {}
|
|
788
|
+
cachedResult = {
|
|
789
|
+
dir: startDir,
|
|
790
|
+
config: null
|
|
791
|
+
};
|
|
792
|
+
return null;
|
|
793
|
+
}
|
|
794
|
+
const parent = dirname(dir);
|
|
795
|
+
if (parent === dir) break;
|
|
796
|
+
dir = parent;
|
|
797
|
+
}
|
|
798
|
+
cachedResult = {
|
|
799
|
+
dir: startDir,
|
|
800
|
+
config: null
|
|
801
|
+
};
|
|
802
|
+
return null;
|
|
803
|
+
}
|
|
804
|
+
//#endregion
|
|
805
|
+
//#region src/auth/token.ts
|
|
806
|
+
/**
|
|
807
|
+
* Token storage and retrieval from config
|
|
808
|
+
*/
|
|
809
|
+
/**
|
|
810
|
+
* Resolve the credential for a named profile, or for the active one when
|
|
811
|
+
* omitted.
|
|
812
|
+
*
|
|
813
|
+
* Resolution order (when `profileName` is omitted — mirrors
|
|
814
|
+
* `createCommandContext` in domain/context.ts):
|
|
815
|
+
* 1. `FLUID_TOKEN` / `FLUID_API_TOKEN` environment variables
|
|
816
|
+
* 2. Project-level `.fluidrc` profile (walks upward from cwd)
|
|
817
|
+
* 3. Global active profile from `~/.fluid/config.json`
|
|
818
|
+
*
|
|
819
|
+
* When `profileName` is provided explicitly (e.g. via `--profile` flag),
|
|
820
|
+
* it takes precedence over the environment variables, `.fluidrc`, and the
|
|
821
|
+
* active profile.
|
|
822
|
+
*/
|
|
823
|
+
function resolveCredentialSource(profileName) {
|
|
824
|
+
const config = readConfig();
|
|
825
|
+
if (profileName) {
|
|
826
|
+
const profile = config.profiles[profileName];
|
|
827
|
+
return profile ? {
|
|
828
|
+
kind: "profile",
|
|
829
|
+
profile
|
|
830
|
+
} : null;
|
|
831
|
+
}
|
|
832
|
+
const envToken = process.env["FLUID_TOKEN"] ?? process.env["FLUID_API_TOKEN"];
|
|
833
|
+
if (envToken) return {
|
|
834
|
+
kind: "token",
|
|
835
|
+
token: envToken
|
|
836
|
+
};
|
|
837
|
+
const projectConfig = findProjectConfig(process.cwd());
|
|
838
|
+
if (projectConfig?.profile) {
|
|
839
|
+
const profile = config.profiles[projectConfig.profile];
|
|
840
|
+
if (profile) return {
|
|
841
|
+
kind: "profile",
|
|
842
|
+
profile
|
|
843
|
+
};
|
|
844
|
+
}
|
|
845
|
+
if (!config.activeProfile) return null;
|
|
846
|
+
const profile = config.profiles[config.activeProfile];
|
|
847
|
+
return profile ? {
|
|
848
|
+
kind: "profile",
|
|
849
|
+
profile
|
|
850
|
+
} : null;
|
|
851
|
+
}
|
|
852
|
+
/**
|
|
853
|
+
* Get the auth token for a named profile, or the active profile when omitted,
|
|
854
|
+
* in the order {@link resolveCredentialSource} describes.
|
|
855
|
+
*
|
|
856
|
+
* An identity-mode profile keeps no token in the config file. Its access
|
|
857
|
+
* token lives in this process's memory once the session has been restored,
|
|
858
|
+
* which the CLI does before running a command; until then, and after its
|
|
859
|
+
* session ends, this returns null. Prefer {@link getAuthTokenAsync}, which
|
|
860
|
+
* restores and refreshes the session itself.
|
|
861
|
+
*/
|
|
862
|
+
function getAuthToken(profileName) {
|
|
863
|
+
const source = resolveCredentialSource(profileName);
|
|
864
|
+
if (!source) return null;
|
|
865
|
+
if (source.kind === "token") return source.token;
|
|
866
|
+
if (isIdentityProfile(source.profile)) return peekIdentityToken(source.profile.name);
|
|
867
|
+
if (isClientProfile(source.profile)) return peekClientToken(source.profile);
|
|
868
|
+
return source.profile.token ?? null;
|
|
869
|
+
}
|
|
870
|
+
/**
|
|
871
|
+
* Like {@link getAuthToken}, but restores, refreshes, or exchanges an
|
|
872
|
+
* identity-mode profile's session as needed. Resolves with null when there
|
|
873
|
+
* is no credential; rejects when an identity session has ended.
|
|
874
|
+
*/
|
|
875
|
+
async function getAuthTokenAsync(profileName) {
|
|
876
|
+
const source = resolveCredentialSource(profileName);
|
|
877
|
+
if (!source) return null;
|
|
878
|
+
if (source.kind === "token") return source.token;
|
|
879
|
+
if (isIdentityProfile(source.profile)) return profileAccessToken(source.profile);
|
|
880
|
+
if (isClientProfile(source.profile)) return clientAccessToken(source.profile);
|
|
881
|
+
return source.profile.token ?? null;
|
|
882
|
+
}
|
|
883
|
+
/**
|
|
884
|
+
* Like {@link getAuthTokenAsync}, for a token that acts only as `roles`. An
|
|
885
|
+
* admin who is also a rep holds an `admin` token by default, which an API that
|
|
886
|
+
* wants a rep refuses; this asks the identity service to narrow the session to
|
|
887
|
+
* `roles` in the company (RFC 8693), and holds that token apart from the
|
|
888
|
+
* default one, which every other reader keeps getting.
|
|
889
|
+
*
|
|
890
|
+
* Only an identity-mode profile can be narrowed. A literal token
|
|
891
|
+
* (`FLUID_TOKEN`) and a legacy profile come back exactly as
|
|
892
|
+
* {@link getAuthTokenAsync} returns them, because their token already is what
|
|
893
|
+
* it is. Resolves with null when there is no credential. Rejects with an
|
|
894
|
+
* error {@link isRoleNotGrantedError} recognises when the person does not
|
|
895
|
+
* hold `roles` in the company, and when an identity session has ended.
|
|
896
|
+
*/
|
|
897
|
+
async function getRoleAuthTokenAsync(roles, profileName) {
|
|
898
|
+
const source = resolveCredentialSource(profileName);
|
|
899
|
+
if (!source) return null;
|
|
900
|
+
if (source.kind === "token") return source.token;
|
|
901
|
+
if (isIdentityProfile(source.profile)) return profileAccessToken(source.profile, roles);
|
|
902
|
+
if (isClientProfile(source.profile)) return clientAccessToken(source.profile);
|
|
903
|
+
return source.profile.token ?? null;
|
|
904
|
+
}
|
|
905
|
+
/**
|
|
906
|
+
* Get the active profile, or null if not logged in
|
|
907
|
+
*/
|
|
908
|
+
function getActiveProfile() {
|
|
909
|
+
const config = readConfig();
|
|
910
|
+
if (!config.activeProfile) return null;
|
|
911
|
+
return config.profiles[config.activeProfile] ?? null;
|
|
912
|
+
}
|
|
913
|
+
/**
|
|
914
|
+
* List all stored profile names
|
|
915
|
+
*/
|
|
916
|
+
function listProfileNames() {
|
|
917
|
+
const config = readConfig();
|
|
918
|
+
return Object.keys(config.profiles);
|
|
919
|
+
}
|
|
920
|
+
//#endregion
|
|
921
|
+
//#region src/inputs/declare.ts
|
|
922
|
+
const resolvers = /* @__PURE__ */ new WeakMap();
|
|
923
|
+
/**
|
|
924
|
+
* Declares the local inputs a command's action reads.
|
|
925
|
+
*
|
|
926
|
+
* command - the leaf command whose action reads the inputs
|
|
927
|
+
* resolver - maps commander's parsed opts and args to the input specs; it
|
|
928
|
+
* must be a pure function of opts and args and must not touch the filesystem
|
|
929
|
+
*
|
|
930
|
+
* Returns the command.
|
|
931
|
+
*/
|
|
932
|
+
function declareInputs(command, resolver) {
|
|
933
|
+
resolvers.set(command, resolver);
|
|
934
|
+
return command;
|
|
935
|
+
}
|
|
936
|
+
function getInputResolver(command) {
|
|
937
|
+
return resolvers.get(command);
|
|
938
|
+
}
|
|
939
|
+
//#endregion
|
|
940
|
+
//#region src/inputs/scope.ts
|
|
941
|
+
let internalDepth = 0;
|
|
942
|
+
const asyncScope = new AsyncLocalStorage();
|
|
943
|
+
/** True while the inputs implementation itself is touching the filesystem. */
|
|
944
|
+
function inInternalRead() {
|
|
945
|
+
return internalDepth > 0 || asyncScope.getStore() === true;
|
|
946
|
+
}
|
|
947
|
+
function withInternalReads(fn) {
|
|
948
|
+
internalDepth++;
|
|
949
|
+
try {
|
|
950
|
+
return fn();
|
|
951
|
+
} finally {
|
|
952
|
+
internalDepth--;
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
/**
|
|
956
|
+
* Async form of withInternalReads. The scope follows fn's own async
|
|
957
|
+
* continuations only; unrelated concurrent work stays guarded.
|
|
958
|
+
*/
|
|
959
|
+
async function withInternalReadsAsync(fn) {
|
|
960
|
+
return asyncScope.run(true, fn);
|
|
961
|
+
}
|
|
962
|
+
//#endregion
|
|
963
|
+
//#region src/inputs/paths.ts
|
|
964
|
+
function lexicalPath(path, cwd = process.cwd()) {
|
|
965
|
+
return isAbsolute(path) ? path : `${cwd}${sep}${path}`;
|
|
966
|
+
}
|
|
967
|
+
/**
|
|
968
|
+
* The path rule for resolve and expect mode (default mode reads the lexical
|
|
969
|
+
* path so /dev/stdin works): make the path absolute without normalizing, then realpath it natively so `..` after a symlink keeps OS
|
|
970
|
+
* semantics. Throws when the path does not exist.
|
|
971
|
+
*/
|
|
972
|
+
function canonicalPath(path, cwd = process.cwd()) {
|
|
973
|
+
const lexical = lexicalPath(path, cwd);
|
|
974
|
+
return {
|
|
975
|
+
lexical,
|
|
976
|
+
canonical: withInternalReads(() => realpathSync.native(lexical))
|
|
977
|
+
};
|
|
978
|
+
}
|
|
979
|
+
//#endregion
|
|
980
|
+
//#region src/inputs/tree.ts
|
|
981
|
+
function normalizeIgnore(ignore) {
|
|
982
|
+
const out = /* @__PURE__ */ new Set();
|
|
983
|
+
for (const pattern of ignore ?? []) {
|
|
984
|
+
const segments = pattern.split("/");
|
|
985
|
+
if (pattern === "" || /[*?[\]{}]/.test(pattern) || segments.some((s) => s === "" || s === "." || s === "..")) throw new Error(`Invalid tree ignore pattern: ${JSON.stringify(pattern)}`);
|
|
986
|
+
out.add(pattern);
|
|
987
|
+
}
|
|
988
|
+
return [...out].sort(compare);
|
|
989
|
+
}
|
|
990
|
+
function ignoreKey(ignore, skipDotNames = false) {
|
|
991
|
+
return skipDotNames ? JSON.stringify({
|
|
992
|
+
ignore,
|
|
993
|
+
skipDotNames: true
|
|
994
|
+
}) : JSON.stringify(ignore);
|
|
995
|
+
}
|
|
996
|
+
function normalizeSkipDotNames(value) {
|
|
997
|
+
if (value === void 0 || typeof value === "boolean") return value === true;
|
|
998
|
+
throw new Error(`Invalid tree skipDotNames: ${JSON.stringify(value) ?? String(value)}`);
|
|
999
|
+
}
|
|
1000
|
+
function compare(a, b) {
|
|
1001
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
1002
|
+
}
|
|
1003
|
+
/**
|
|
1004
|
+
* The single ignore matcher for tree inputs, used by resolve, expect and
|
|
1005
|
+
* default mode alike. A pattern without "/" matches an entry's basename at
|
|
1006
|
+
* any depth; a pattern with "/" matches a root-relative path. A match on a
|
|
1007
|
+
* directory also excludes every descendant.
|
|
1008
|
+
*
|
|
1009
|
+
* rel - "/"-separated path relative to the tree root
|
|
1010
|
+
* ignore - patterns from normalizeIgnore
|
|
1011
|
+
*
|
|
1012
|
+
* Returns true when rel or any ancestor directory of rel is ignored.
|
|
1013
|
+
*/
|
|
1014
|
+
function isIgnored(rel, ignore) {
|
|
1015
|
+
const segments = rel.split("/");
|
|
1016
|
+
let prefix = "";
|
|
1017
|
+
for (const segment of segments) {
|
|
1018
|
+
prefix = prefix === "" ? segment : `${prefix}/${segment}`;
|
|
1019
|
+
if (ignore.includes(segment) || ignore.includes(prefix)) return true;
|
|
1020
|
+
}
|
|
1021
|
+
return false;
|
|
1022
|
+
}
|
|
1023
|
+
/**
|
|
1024
|
+
* Lists the regular files under an already canonical root as sorted
|
|
1025
|
+
* "/"-separated relative paths. Symlink entries are skipped at list time in
|
|
1026
|
+
* every mode. Throws if a directory being walked is not its own canonical
|
|
1027
|
+
* path. With skipDotNames, every entry whose name starts with "." is skipped
|
|
1028
|
+
* before its directory is read.
|
|
1029
|
+
*/
|
|
1030
|
+
function listTreeFiles(root, ignore, skipDotNames = false) {
|
|
1031
|
+
const out = [];
|
|
1032
|
+
const walk = (dir, relDir) => {
|
|
1033
|
+
assertCanonicalDir(dir);
|
|
1034
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
1035
|
+
const rel = relDir === "" ? entry.name : `${relDir}/${entry.name}`;
|
|
1036
|
+
if (skipDotNames && entry.name.startsWith(".")) continue;
|
|
1037
|
+
if (isIgnored(rel, ignore)) continue;
|
|
1038
|
+
if (entry.isDirectory()) walk(join(dir, entry.name), rel);
|
|
1039
|
+
else if (entry.isFile()) out.push(rel);
|
|
1040
|
+
}
|
|
1041
|
+
};
|
|
1042
|
+
withInternalReads(() => walk(root, ""));
|
|
1043
|
+
return out.sort(compare);
|
|
1044
|
+
}
|
|
1045
|
+
function assertCanonicalDir(dir) {
|
|
1046
|
+
if (realpathSync.native(dir) !== dir) throw new Error(`Tree directory changed during read: ${dir}`);
|
|
1047
|
+
}
|
|
1048
|
+
/**
|
|
1049
|
+
* Reads one tree member from a canonical root. Rejects a non-canonical parent
|
|
1050
|
+
* directory and a symlinked or non-regular final component (O_NOFOLLOW).
|
|
1051
|
+
* Known residual: a parent directory swapped between the canonical check and
|
|
1052
|
+
* the open is not detected; it needs a local writer to the tree during the
|
|
1053
|
+
* command, and Node has no openat2.
|
|
1054
|
+
*/
|
|
1055
|
+
function readTreeFileFromDisk(root, rel) {
|
|
1056
|
+
return withInternalReads(() => {
|
|
1057
|
+
const path = join(root, rel);
|
|
1058
|
+
assertCanonicalDir(join(root, dirname(rel)));
|
|
1059
|
+
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
1060
|
+
try {
|
|
1061
|
+
if (!fstatSync(fd).isFile()) throw new Error(`Tree member is not a regular file: ${path}`);
|
|
1062
|
+
return readFileSync(fd);
|
|
1063
|
+
} finally {
|
|
1064
|
+
closeSync(fd);
|
|
1065
|
+
}
|
|
1066
|
+
});
|
|
1067
|
+
}
|
|
1068
|
+
//#endregion
|
|
1069
|
+
//#region src/inputs/snapshot.ts
|
|
1070
|
+
function treeKey(root, ignore, skipDotNames = false) {
|
|
1071
|
+
return `${root}\0${ignoreKey(ignore, skipDotNames)}`;
|
|
1072
|
+
}
|
|
1073
|
+
function sha256(data) {
|
|
1074
|
+
return createHash("sha256").update(data).digest("hex");
|
|
1075
|
+
}
|
|
1076
|
+
function resolveInputs(specs, cwd = process.cwd()) {
|
|
1077
|
+
return withInternalReads(() => {
|
|
1078
|
+
const snapshot = {
|
|
1079
|
+
files: /* @__PURE__ */ new Map(),
|
|
1080
|
+
aliases: /* @__PURE__ */ new Map(),
|
|
1081
|
+
trees: /* @__PURE__ */ new Map(),
|
|
1082
|
+
treeAliases: /* @__PURE__ */ new Map(),
|
|
1083
|
+
refs: /* @__PURE__ */ new Map()
|
|
1084
|
+
};
|
|
1085
|
+
const entries = [];
|
|
1086
|
+
for (const spec of specs) if (spec.kind === "ref") {
|
|
1087
|
+
snapshot.refs.set(spec.name, spec.value);
|
|
1088
|
+
entries.push({
|
|
1089
|
+
kind: "ref",
|
|
1090
|
+
name: spec.name,
|
|
1091
|
+
value: spec.value
|
|
1092
|
+
});
|
|
1093
|
+
} else if (spec.kind === "file" || spec.kind === "config") {
|
|
1094
|
+
const { lexical, canonical: path } = canonicalPath(spec.path, cwd);
|
|
1095
|
+
const content = readFileSync(path);
|
|
1096
|
+
snapshot.aliases.set(lexical, path);
|
|
1097
|
+
snapshot.aliases.set(path, path);
|
|
1098
|
+
snapshot.files.set(path, content);
|
|
1099
|
+
entries.push({
|
|
1100
|
+
kind: spec.kind,
|
|
1101
|
+
path,
|
|
1102
|
+
sha256: sha256(content),
|
|
1103
|
+
size: content.length
|
|
1104
|
+
});
|
|
1105
|
+
} else {
|
|
1106
|
+
if (spec.kind !== "tree" || typeof spec.path !== "string") throw new Error("Invalid tree input spec");
|
|
1107
|
+
const { lexical, canonical: root } = canonicalPath(spec.path, cwd);
|
|
1108
|
+
const ignore = normalizeIgnore(spec.ignore);
|
|
1109
|
+
const skipDot = normalizeSkipDotNames(spec.skipDotNames);
|
|
1110
|
+
const members = /* @__PURE__ */ new Map();
|
|
1111
|
+
const files = [];
|
|
1112
|
+
for (const rel of listTreeFiles(root, ignore, skipDot)) {
|
|
1113
|
+
const content = readTreeFileFromDisk(root, rel);
|
|
1114
|
+
members.set(rel, content);
|
|
1115
|
+
files.push({
|
|
1116
|
+
path: rel,
|
|
1117
|
+
sha256: sha256(content),
|
|
1118
|
+
size: content.length
|
|
1119
|
+
});
|
|
1120
|
+
}
|
|
1121
|
+
snapshot.treeAliases.set(lexical, root);
|
|
1122
|
+
snapshot.treeAliases.set(root, root);
|
|
1123
|
+
snapshot.trees.set(treeKey(root, ignore, skipDot), members);
|
|
1124
|
+
entries.push({
|
|
1125
|
+
kind: "tree",
|
|
1126
|
+
path: root,
|
|
1127
|
+
ignore,
|
|
1128
|
+
...skipDot ? { skipDotNames: true } : {},
|
|
1129
|
+
files
|
|
1130
|
+
});
|
|
1131
|
+
}
|
|
1132
|
+
return {
|
|
1133
|
+
entries,
|
|
1134
|
+
snapshot
|
|
1135
|
+
};
|
|
1136
|
+
});
|
|
1137
|
+
}
|
|
1138
|
+
function sortKey(entry) {
|
|
1139
|
+
const id = entry.kind === "ref" ? entry.name : entry.kind === "tree" ? `${entry.path}\0${ignoreKey(entry.ignore, entry.skipDotNames === true)}` : entry.path;
|
|
1140
|
+
return `${entry.kind}\0${id}`;
|
|
1141
|
+
}
|
|
1142
|
+
function canonicalEntries(entries) {
|
|
1143
|
+
return entries.map((e) => {
|
|
1144
|
+
if (e.kind === "ref") return {
|
|
1145
|
+
kind: "ref",
|
|
1146
|
+
name: e.name,
|
|
1147
|
+
value: e.value
|
|
1148
|
+
};
|
|
1149
|
+
if (e.kind === "tree") return {
|
|
1150
|
+
kind: "tree",
|
|
1151
|
+
path: e.path,
|
|
1152
|
+
ignore: [...e.ignore],
|
|
1153
|
+
...e.skipDotNames === true ? { skipDotNames: true } : {},
|
|
1154
|
+
files: e.files.map((f) => ({
|
|
1155
|
+
path: f.path,
|
|
1156
|
+
sha256: f.sha256,
|
|
1157
|
+
size: f.size
|
|
1158
|
+
}))
|
|
1159
|
+
};
|
|
1160
|
+
return {
|
|
1161
|
+
kind: e.kind,
|
|
1162
|
+
path: e.path,
|
|
1163
|
+
sha256: e.sha256,
|
|
1164
|
+
size: e.size
|
|
1165
|
+
};
|
|
1166
|
+
}).sort((a, b) => {
|
|
1167
|
+
const ka = sortKey(a);
|
|
1168
|
+
const kb = sortKey(b);
|
|
1169
|
+
return ka < kb ? -1 : ka > kb ? 1 : 0;
|
|
1170
|
+
});
|
|
1171
|
+
}
|
|
1172
|
+
function manifestJson(command, entries) {
|
|
1173
|
+
return JSON.stringify({
|
|
1174
|
+
version: 1,
|
|
1175
|
+
command,
|
|
1176
|
+
inputs: canonicalEntries(entries)
|
|
1177
|
+
});
|
|
1178
|
+
}
|
|
1179
|
+
//#endregion
|
|
1180
|
+
//#region src/inputs/reader.ts
|
|
1181
|
+
let activeSnapshot = null;
|
|
1182
|
+
function setActiveSnapshot(snapshot) {
|
|
1183
|
+
activeSnapshot = snapshot;
|
|
1184
|
+
}
|
|
1185
|
+
var InputsUndeclaredError = class extends Error {
|
|
1186
|
+
constructor(path) {
|
|
1187
|
+
super(`Undeclared input read: ${path}`);
|
|
1188
|
+
this.name = "InputsUndeclaredError";
|
|
1189
|
+
}
|
|
1190
|
+
};
|
|
1191
|
+
function declaredKey(path, snapshot) {
|
|
1192
|
+
const lexical = lexicalPath(path);
|
|
1193
|
+
const key = snapshot.aliases.get(lexical) ?? lexical;
|
|
1194
|
+
return snapshot.files.has(key) ? key : void 0;
|
|
1195
|
+
}
|
|
1196
|
+
function bytes(content, encoding) {
|
|
1197
|
+
return encoding ? content.toString(encoding) : Buffer.from(content);
|
|
1198
|
+
}
|
|
1199
|
+
function snapshotTree(rootPath, ignore, skipDot, snapshot) {
|
|
1200
|
+
const root = snapshot.treeAliases.get(lexicalPath(rootPath)) ?? rootPath;
|
|
1201
|
+
const members = snapshot.trees.get(treeKey(root, ignore, skipDot));
|
|
1202
|
+
if (!members) throw new InputsUndeclaredError(rootPath);
|
|
1203
|
+
return {
|
|
1204
|
+
root,
|
|
1205
|
+
members
|
|
1206
|
+
};
|
|
1207
|
+
}
|
|
1208
|
+
function openTree(rootPath, options) {
|
|
1209
|
+
const ignore = normalizeIgnore(options?.ignore);
|
|
1210
|
+
const skipDot = normalizeSkipDotNames(options?.skipDotNames);
|
|
1211
|
+
let disk;
|
|
1212
|
+
const fromDisk = () => {
|
|
1213
|
+
if (!disk) {
|
|
1214
|
+
const root = canonicalPath(rootPath).canonical;
|
|
1215
|
+
disk = {
|
|
1216
|
+
root,
|
|
1217
|
+
known: new Set(listTreeFiles(root, ignore, skipDot))
|
|
1218
|
+
};
|
|
1219
|
+
}
|
|
1220
|
+
return disk;
|
|
1221
|
+
};
|
|
1222
|
+
if (activeSnapshot) snapshotTree(rootPath, ignore, skipDot, activeSnapshot);
|
|
1223
|
+
else fromDisk();
|
|
1224
|
+
return {
|
|
1225
|
+
get root() {
|
|
1226
|
+
return activeSnapshot ? snapshotTree(rootPath, ignore, skipDot, activeSnapshot).root : fromDisk().root;
|
|
1227
|
+
},
|
|
1228
|
+
list() {
|
|
1229
|
+
if (activeSnapshot) return [...snapshotTree(rootPath, ignore, skipDot, activeSnapshot).members.keys()];
|
|
1230
|
+
return [...fromDisk().known];
|
|
1231
|
+
},
|
|
1232
|
+
readFile(rel, encoding) {
|
|
1233
|
+
const missing = () => new InputsUndeclaredError(`${rootPath}/${rel}`);
|
|
1234
|
+
if (activeSnapshot) {
|
|
1235
|
+
const content = snapshotTree(rootPath, ignore, skipDot, activeSnapshot).members.get(rel);
|
|
1236
|
+
if (!content) throw missing();
|
|
1237
|
+
return bytes(content, encoding);
|
|
1238
|
+
}
|
|
1239
|
+
const { root, known } = fromDisk();
|
|
1240
|
+
if (!known.has(rel)) throw missing();
|
|
1241
|
+
return bytes(readTreeFileFromDisk(root, rel), encoding);
|
|
1242
|
+
}
|
|
1243
|
+
};
|
|
1244
|
+
}
|
|
1245
|
+
/**
|
|
1246
|
+
* The reader behind ctx.inputs. Outside expect mode it reads from disk; once
|
|
1247
|
+
* an expect-mode snapshot is active it serves only that snapshot and throws
|
|
1248
|
+
* for anything undeclared.
|
|
1249
|
+
*/
|
|
1250
|
+
function createInputsReader() {
|
|
1251
|
+
return {
|
|
1252
|
+
isExpecting: () => activeSnapshot !== null,
|
|
1253
|
+
ref(name) {
|
|
1254
|
+
const snapshot = activeSnapshot;
|
|
1255
|
+
if (!snapshot) return void 0;
|
|
1256
|
+
const value = snapshot.refs.get(name);
|
|
1257
|
+
if (value === void 0) throw new InputsUndeclaredError(`ref ${name}`);
|
|
1258
|
+
return value;
|
|
1259
|
+
},
|
|
1260
|
+
tree: openTree,
|
|
1261
|
+
readFile(path, encoding) {
|
|
1262
|
+
const snapshot = activeSnapshot;
|
|
1263
|
+
if (!snapshot) {
|
|
1264
|
+
const content = withInternalReads(() => readFileSync(lexicalPath(path)));
|
|
1265
|
+
return encoding ? content.toString(encoding) : content;
|
|
1266
|
+
}
|
|
1267
|
+
const key = declaredKey(path, snapshot);
|
|
1268
|
+
const content = key === void 0 ? void 0 : snapshot.files.get(key);
|
|
1269
|
+
if (!content) throw new InputsUndeclaredError(path);
|
|
1270
|
+
return encoding ? content.toString(encoding) : Buffer.from(content);
|
|
1271
|
+
}
|
|
1272
|
+
};
|
|
1273
|
+
}
|
|
1274
|
+
//#endregion
|
|
1275
|
+
//#region src/inputs/hook.ts
|
|
1276
|
+
const INPUTS_MODE_ENV = "FLUID_INPUTS_MODE";
|
|
1277
|
+
const INPUTS_EXPECT_ENV = "FLUID_INPUTS_EXPECT";
|
|
1278
|
+
const INPUTS_UNDECLARED_CODE = "inputs_undeclared";
|
|
1279
|
+
const INPUTS_UNDECLARED_EXIT = 64;
|
|
1280
|
+
const INPUTS_MISMATCH_CODE = "inputs_mismatch";
|
|
1281
|
+
const INPUTS_MISMATCH_EXIT = 65;
|
|
1282
|
+
function writeAll(fd, text) {
|
|
1283
|
+
const buffer = Buffer.from(text);
|
|
1284
|
+
let offset = 0;
|
|
1285
|
+
while (offset < buffer.length) try {
|
|
1286
|
+
offset += writeSync(fd, buffer, offset);
|
|
1287
|
+
} catch (error) {
|
|
1288
|
+
if (error.code !== "EAGAIN") throw error;
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
const processIo = {
|
|
1292
|
+
env: process.env,
|
|
1293
|
+
stdout: (text) => writeAll(1, text),
|
|
1294
|
+
stderr: (text) => writeAll(2, text),
|
|
1295
|
+
exit: (code) => process.exit(code)
|
|
1296
|
+
};
|
|
1297
|
+
function inputsModeActive(env) {
|
|
1298
|
+
return env["FLUID_INPUTS_MODE"] !== void 0 || env["FLUID_INPUTS_EXPECT"] !== void 0;
|
|
1299
|
+
}
|
|
1300
|
+
function commandPath(command) {
|
|
1301
|
+
const names = [];
|
|
1302
|
+
for (let c = command; c; c = c.parent) names.unshift(c.name());
|
|
1303
|
+
return names.join(" ");
|
|
1304
|
+
}
|
|
1305
|
+
function readManifest(path) {
|
|
1306
|
+
try {
|
|
1307
|
+
const parsed = JSON.parse(withInternalReads(() => readFileSync(path, "utf8")));
|
|
1308
|
+
if (!Array.isArray(parsed.inputs)) return null;
|
|
1309
|
+
return {
|
|
1310
|
+
version: parsed.version,
|
|
1311
|
+
command: parsed.command,
|
|
1312
|
+
inputs: canonicalEntries(parsed.inputs)
|
|
1313
|
+
};
|
|
1314
|
+
} catch {
|
|
1315
|
+
return null;
|
|
1316
|
+
}
|
|
1317
|
+
}
|
|
1318
|
+
function inputsPreAction(actionCommand, io = processIo) {
|
|
1319
|
+
const mode = io.env[INPUTS_MODE_ENV];
|
|
1320
|
+
const expectPath = io.env[INPUTS_EXPECT_ENV];
|
|
1321
|
+
setActiveSnapshot(null);
|
|
1322
|
+
if (mode === void 0 && expectPath === void 0) return;
|
|
1323
|
+
const resolveMode = mode === "resolve";
|
|
1324
|
+
if (mode !== void 0 && !resolveMode || expectPath === "" || resolveMode && expectPath !== void 0) {
|
|
1325
|
+
io.stderr(`${INPUTS_MISMATCH_CODE}\n`);
|
|
1326
|
+
return io.exit(65);
|
|
1327
|
+
}
|
|
1328
|
+
const resolver = getInputResolver(actionCommand);
|
|
1329
|
+
if (!resolver) {
|
|
1330
|
+
io.stderr(`${INPUTS_UNDECLARED_CODE}\n`);
|
|
1331
|
+
return io.exit(64);
|
|
1332
|
+
}
|
|
1333
|
+
let resolved;
|
|
1334
|
+
try {
|
|
1335
|
+
resolved = resolveInputs(resolver(actionCommand.optsWithGlobals(), actionCommand.args));
|
|
1336
|
+
} catch (error) {
|
|
1337
|
+
if (resolveMode) {
|
|
1338
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1339
|
+
io.stderr(`${message}\n`);
|
|
1340
|
+
return io.exit(1);
|
|
1341
|
+
}
|
|
1342
|
+
io.stderr(`${INPUTS_MISMATCH_CODE}\n`);
|
|
1343
|
+
return io.exit(65);
|
|
1344
|
+
}
|
|
1345
|
+
if (resolveMode) {
|
|
1346
|
+
io.stdout(`${manifestJson(commandPath(actionCommand), resolved.entries)}\n`);
|
|
1347
|
+
return io.exit(0);
|
|
1348
|
+
}
|
|
1349
|
+
const expected = readManifest(expectPath);
|
|
1350
|
+
if (!expected || expected.version !== 1 || expected.command !== commandPath(actionCommand) || JSON.stringify(expected.inputs) !== JSON.stringify(canonicalEntries(resolved.entries))) {
|
|
1351
|
+
io.stderr(`${INPUTS_MISMATCH_CODE}\n`);
|
|
1352
|
+
return io.exit(65);
|
|
1353
|
+
}
|
|
1354
|
+
setActiveSnapshot(resolved.snapshot);
|
|
1355
|
+
}
|
|
1356
|
+
/**
|
|
1357
|
+
* Registers the inputs preAction hook. Register it before any credential
|
|
1358
|
+
* hook.
|
|
1359
|
+
*/
|
|
1360
|
+
function registerInputsHook(program, io = processIo) {
|
|
1361
|
+
program.hook("preAction", (_program, actionCommand) => {
|
|
1362
|
+
inputsPreAction(actionCommand, io);
|
|
1363
|
+
});
|
|
1364
|
+
}
|
|
1365
|
+
/**
|
|
1366
|
+
* Maps an undeclared read in expect mode to the fixed undeclared exit; any
|
|
1367
|
+
* other error is returned to the caller untouched.
|
|
1368
|
+
*/
|
|
1369
|
+
function exitOnInputsError(error, io = processIo) {
|
|
1370
|
+
if (!(error instanceof InputsUndeclaredError)) return;
|
|
1371
|
+
io.stderr(`${INPUTS_UNDECLARED_CODE}\n`);
|
|
1372
|
+
io.exit(64);
|
|
1373
|
+
}
|
|
1374
|
+
//#endregion
|
|
1375
|
+
export { describeCommand as $, redeemIdentityLink as A, isSuccess as B, FLUID_API_ERROR as C, getFluidApiBase as D, fetchUserCompanies as E, failure as F, tryCatchAsync as G, mapResult as H, getErrorMessage as I, filterCatalog as J, unwrap as K, isError as L, signup as M, switchCompany as N, isInsecureRemoteBase as O, validateToken as P, walkCommands as Q, isFailure as R, findProjectConfig as S, confirmMfa as T, success as U, mapError as V, tryCatch as W, visibleOptions as X, rootCommand as Y, visibleSubcommands as Z, getAuthToken as _, INPUTS_UNDECLARED_CODE as a, listProfileNames as b, inputsModeActive as c, setActiveSnapshot as d, inInternalRead as f, getActiveProfile as g, declareInputs as h, INPUTS_MODE_ENV as i, sendMfa as j, pollAgentAccess as k, registerInputsHook as l, withInternalReadsAsync as m, INPUTS_MISMATCH_CODE as n, INPUTS_UNDECLARED_EXIT as o, withInternalReads as p, unwrapOr as q, INPUTS_MISMATCH_EXIT as r, exitOnInputsError as s, INPUTS_EXPECT_ENV as t, createInputsReader as u, getAuthTokenAsync as v, SIGNUP_ERROR as w, resolveCredentialSource as x, getRoleAuthTokenAsync as y, isNodeError as z };
|
|
1376
|
+
|
|
1377
|
+
//# sourceMappingURL=hook-DJNt29x1.mjs.map
|