@fluid-app/fluid-cli 0.1.64 → 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 +68 -6
- package/dist/bin/fluid.mjs +822 -101
- package/dist/bin/fluid.mjs.map +1 -1
- package/dist/index.d.mts +73 -17
- 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-6SEVoGMw.mjs +0 -604
- package/dist/token-6SEVoGMw.mjs.map +0 -1
package/dist/bin/fluid.mjs
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
2
|
+
import { A as validateToken, C as FLUID_API_ERROR, D as redeemIdentityLink, E as getFluidApiBase, G as rootCommand, J as walkCommands, K as visibleOptions, O as sendMfa, S as isIdentityProfile, T as fetchUserCompanies, W as filterCatalog, _ as signInWithBrowser, a as resolveCredentialSource, c as updateConfig, f as describeIdentityError, g as sessionFacts, k as switchCompany, l as writeConfig, m as primeIdentityProfile, n as getAuthToken, p as identityToken, q as visibleSubcommands, s as readConfig, t as getActiveProfile, u as getConfigDir, v as signOutIdentity, w as confirmMfa, y as resolveIdentityUrl } from "../token-BUGqpr-U.mjs";
|
|
3
3
|
import { createRequire } from "node:module";
|
|
4
|
-
import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
|
|
5
5
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
6
6
|
import { Argument, Command, Option } from "commander";
|
|
7
|
+
import { text } from "node:stream/consumers";
|
|
7
8
|
import chalk from "chalk";
|
|
8
9
|
import prompts from "prompts";
|
|
9
10
|
import ora from "ora";
|
|
10
|
-
import {
|
|
11
|
-
import { randomBytes } from "node:crypto";
|
|
11
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
12
12
|
import { spawn } from "node:child_process";
|
|
13
|
+
import { dirname, join, sep } from "node:path";
|
|
13
14
|
//#region src/commands/commands.ts
|
|
14
15
|
/**
|
|
15
16
|
* fluid commands — list every installed command, or print the catalog as
|
|
@@ -244,6 +245,139 @@ const completeCommand = new Command("__complete").description("Print completions
|
|
|
244
245
|
process.stdout.write(formatCandidates(completeWords(rootCommand(command), typed), opts.shell));
|
|
245
246
|
});
|
|
246
247
|
//#endregion
|
|
248
|
+
//#region src/auth/identity/profiles.ts
|
|
249
|
+
/**
|
|
250
|
+
* Ending identity sessions when the profiles that use them go away.
|
|
251
|
+
*
|
|
252
|
+
* `fluid switch` gives each company its own profile, and in identity mode
|
|
253
|
+
* those profiles share the session they were switched from. A session is
|
|
254
|
+
* revoked only once no profile is left that uses it.
|
|
255
|
+
*/
|
|
256
|
+
function sessionsIn(config) {
|
|
257
|
+
const found = /* @__PURE__ */ new Map();
|
|
258
|
+
for (const profile of Object.values(config.profiles)) {
|
|
259
|
+
if (!isIdentityProfile(profile)) continue;
|
|
260
|
+
const { auth } = profile;
|
|
261
|
+
found.set(`${auth.identityUrl} ${auth.storageKey}`, auth);
|
|
262
|
+
}
|
|
263
|
+
return found;
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* Revokes every identity session `before` used that `after` no longer does,
|
|
267
|
+
* and deletes its refresh token from the credential store. Resolves with a
|
|
268
|
+
* message for each session that could not be ended cleanly; never rejects.
|
|
269
|
+
*/
|
|
270
|
+
async function endUnusedSessions(before, after) {
|
|
271
|
+
const remaining = sessionsIn(after);
|
|
272
|
+
const problems = [];
|
|
273
|
+
for (const [key, auth] of sessionsIn(before)) {
|
|
274
|
+
if (remaining.has(key)) continue;
|
|
275
|
+
try {
|
|
276
|
+
await signOutIdentity(auth);
|
|
277
|
+
} catch (error) {
|
|
278
|
+
problems.push(describeIdentityError(error));
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
return problems;
|
|
282
|
+
}
|
|
283
|
+
//#endregion
|
|
284
|
+
//#region src/auth/identity/sign-in-path.ts
|
|
285
|
+
/**
|
|
286
|
+
* The path a confirmed code puts the person on. A confirmation that kept any
|
|
287
|
+
* company's legacy token stays on the legacy path: those companies are not
|
|
288
|
+
* flagged, and their tokens are listed exactly as before.
|
|
289
|
+
*/
|
|
290
|
+
function signInPathFor(confirmation) {
|
|
291
|
+
return confirmation.signInPath === "identity" ? "identity" : "legacy";
|
|
292
|
+
}
|
|
293
|
+
//#endregion
|
|
294
|
+
//#region src/auth/pending-login.ts
|
|
295
|
+
/**
|
|
296
|
+
* Email sign-ins started with `fluid login --send-code` and not finished yet.
|
|
297
|
+
*
|
|
298
|
+
* The send and finish steps run as separate processes, and the finish step
|
|
299
|
+
* needs the server's id for the sign-in (`uuid`), which only the send step
|
|
300
|
+
* saw. Keeping it here means an agent carries the emailed code alone. The
|
|
301
|
+
* uuid cannot sign anyone in without that code.
|
|
302
|
+
*
|
|
303
|
+
* One record per address, so a new send replaces the last one. Records live
|
|
304
|
+
* under the config dir (`~/.fluid/pending-logins/`), each named by a hash of
|
|
305
|
+
* the address so the file names do not list who is signing in.
|
|
306
|
+
*/
|
|
307
|
+
const STALE_AFTER_MS = 3600 * 1e3;
|
|
308
|
+
/** The server compares addresses trimmed and lowercased; so does the store. */
|
|
309
|
+
function normaliseEmail(email) {
|
|
310
|
+
return email.trim().toLowerCase();
|
|
311
|
+
}
|
|
312
|
+
function fileName(email) {
|
|
313
|
+
return `${createHash("sha256").update(normaliseEmail(email)).digest("hex")}.json`;
|
|
314
|
+
}
|
|
315
|
+
function isPendingLogin(value) {
|
|
316
|
+
if (typeof value !== "object" || value === null) return false;
|
|
317
|
+
const record = value;
|
|
318
|
+
return typeof record["uuid"] === "string" && typeof record["email"] === "string" && typeof record["shop"] === "string" && typeof record["expiresAt"] === "string" && typeof record["baseUrl"] === "string";
|
|
319
|
+
}
|
|
320
|
+
function readRecord(path) {
|
|
321
|
+
try {
|
|
322
|
+
const parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
323
|
+
return isPendingLogin(parsed) ? parsed : null;
|
|
324
|
+
} catch {
|
|
325
|
+
return null;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
function removeStale(dir, now) {
|
|
329
|
+
let names;
|
|
330
|
+
try {
|
|
331
|
+
names = readdirSync(dir);
|
|
332
|
+
} catch {
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
for (const name of names) {
|
|
336
|
+
if (!name.endsWith(".json")) continue;
|
|
337
|
+
const path = join(dir, name);
|
|
338
|
+
const record = readRecord(path);
|
|
339
|
+
const expiresAt = record ? Date.parse(record.expiresAt) : NaN;
|
|
340
|
+
if (!record || !(expiresAt + STALE_AFTER_MS > now)) rmSync(path, { force: true });
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* The store, in `dir` or by default `<config dir>/pending-logins`, resolved
|
|
345
|
+
* on each call so a changed `FLUID_CONFIG_DIR` is honoured.
|
|
346
|
+
*/
|
|
347
|
+
function createPendingLoginStore(dir) {
|
|
348
|
+
const storeDir = () => dir ?? join(getConfigDir(), "pending-logins");
|
|
349
|
+
return {
|
|
350
|
+
save(record) {
|
|
351
|
+
const base = storeDir();
|
|
352
|
+
mkdirSync(base, {
|
|
353
|
+
recursive: true,
|
|
354
|
+
mode: 448
|
|
355
|
+
});
|
|
356
|
+
removeStale(base, Date.now());
|
|
357
|
+
const tmpPath = join(base, `.pending-${randomBytes(6).toString("hex")}.tmp`);
|
|
358
|
+
try {
|
|
359
|
+
writeFileSync(tmpPath, JSON.stringify(record, null, 2) + "\n", {
|
|
360
|
+
encoding: "utf8",
|
|
361
|
+
mode: 384
|
|
362
|
+
});
|
|
363
|
+
renameSync(tmpPath, join(base, fileName(record.email)));
|
|
364
|
+
} catch (err) {
|
|
365
|
+
try {
|
|
366
|
+
unlinkSync(tmpPath);
|
|
367
|
+
} catch {}
|
|
368
|
+
throw err;
|
|
369
|
+
}
|
|
370
|
+
},
|
|
371
|
+
load(email) {
|
|
372
|
+
const record = readRecord(join(storeDir(), fileName(email)));
|
|
373
|
+
return record && record.email === normaliseEmail(email) ? record : null;
|
|
374
|
+
},
|
|
375
|
+
remove(email) {
|
|
376
|
+
rmSync(join(storeDir(), fileName(email)), { force: true });
|
|
377
|
+
}
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
//#endregion
|
|
247
381
|
//#region src/auth/profiles.ts
|
|
248
382
|
function createFluidProfile({ name, token, companyName, baseUrl, storedAt }) {
|
|
249
383
|
return {
|
|
@@ -254,24 +388,256 @@ function createFluidProfile({ name, token, companyName, baseUrl, storedAt }) {
|
|
|
254
388
|
baseUrl
|
|
255
389
|
};
|
|
256
390
|
}
|
|
391
|
+
/**
|
|
392
|
+
* An identity-mode profile. It holds no token: the refresh token is in the
|
|
393
|
+
* operating system credential store under `auth.storageKey`.
|
|
394
|
+
*/
|
|
395
|
+
function createIdentityProfile({ name, companyName, baseUrl, auth, storedAt }) {
|
|
396
|
+
return {
|
|
397
|
+
name,
|
|
398
|
+
companyName,
|
|
399
|
+
storedAt: storedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
400
|
+
baseUrl,
|
|
401
|
+
auth
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
//#endregion
|
|
405
|
+
//#region src/commands/login-identity.ts
|
|
406
|
+
/**
|
|
407
|
+
* `fluid login` for a company on the identity sign-in path: the browser,
|
|
408
|
+
* a loopback redirect, and a session in the operating system credential
|
|
409
|
+
* store. Reached only when Rails says so (see auth/identity/sign-in-path.ts):
|
|
410
|
+
* a confirmed code answered `sign_in_path: "identity"`, or the person pasted
|
|
411
|
+
* the sign-in link Rails emailed them instead of a code.
|
|
412
|
+
*
|
|
413
|
+
* It reports an outcome rather than printing one, so `fluid login` shows it
|
|
414
|
+
* in text or `--json` like every other sign-in.
|
|
415
|
+
*/
|
|
416
|
+
/** The query parameter Rails puts the sign-in link's token in. */
|
|
417
|
+
const IDENTITY_LINK_PARAM = "identityLink";
|
|
418
|
+
/** The roles the CLI's commands accept, as with a legacy `rep` session. */
|
|
419
|
+
const STAFF_ROLES = new Set([
|
|
420
|
+
"admin",
|
|
421
|
+
"rep",
|
|
422
|
+
"root_admin"
|
|
423
|
+
]);
|
|
424
|
+
/**
|
|
425
|
+
* The token in a pasted identity sign-in link, or null when the input is not
|
|
426
|
+
* such a link.
|
|
427
|
+
*/
|
|
428
|
+
function identityLinkToken(input) {
|
|
429
|
+
const trimmed = input.trim();
|
|
430
|
+
if (!trimmed.includes(`${IDENTITY_LINK_PARAM}=`)) return null;
|
|
431
|
+
try {
|
|
432
|
+
return new URL(trimmed).searchParams.get(IDENTITY_LINK_PARAM) || null;
|
|
433
|
+
} catch {
|
|
434
|
+
return null;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
function failed(code, message) {
|
|
438
|
+
return {
|
|
439
|
+
status: "failed",
|
|
440
|
+
error: {
|
|
441
|
+
code,
|
|
442
|
+
message
|
|
443
|
+
}
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
/** Signs in through the identity service and stores the profile. */
|
|
447
|
+
async function loginWithIdentity(context) {
|
|
448
|
+
const apiBase = context.apiBase ?? getFluidApiBase();
|
|
449
|
+
let identityUrl;
|
|
450
|
+
try {
|
|
451
|
+
identityUrl = resolveIdentityUrl(apiBase);
|
|
452
|
+
} catch (error) {
|
|
453
|
+
return failed("IDENTITY_URL_INVALID", error instanceof Error ? error.message : String(error));
|
|
454
|
+
}
|
|
455
|
+
if (!identityUrl) return failed("IDENTITY_URL_UNKNOWN", `No Fluid identity service is known for ${apiBase}. Set FLUID_IDENTITY_URL to sign in.`);
|
|
456
|
+
context.log("Your company signs in through Fluid's identity service.");
|
|
457
|
+
let signIn;
|
|
458
|
+
try {
|
|
459
|
+
signIn = await signInWithBrowser({
|
|
460
|
+
identityUrl,
|
|
461
|
+
log: context.log
|
|
462
|
+
});
|
|
463
|
+
} catch (error) {
|
|
464
|
+
return failed("IDENTITY_SIGN_IN_FAILED", describeIdentityError(error));
|
|
465
|
+
}
|
|
466
|
+
if (!signIn.facts.roles.some((role) => STAFF_ROLES.has(role))) {
|
|
467
|
+
await signOutIdentity(signIn.auth).catch(() => void 0);
|
|
468
|
+
return failed("SHOPPER_SESSION", "This account does not sign in as an admin or rep, so it cannot sign in to the CLI.");
|
|
469
|
+
}
|
|
470
|
+
const spinner = context.spinner("Loading your company...");
|
|
471
|
+
const company = await context.validateToken(signIn.accessToken, { baseUrl: apiBase });
|
|
472
|
+
const companyName = company.success ? company.value.name : signIn.facts.companyId ?? "Fluid";
|
|
473
|
+
spinner.succeed(`Signed in to ${companyName}`);
|
|
474
|
+
const profileName = context.profileName ?? companyName;
|
|
475
|
+
const decision = await context.decideOverwrite(profileName);
|
|
476
|
+
if (decision !== "replace") {
|
|
477
|
+
await signOutIdentity(signIn.auth).catch(() => void 0);
|
|
478
|
+
return decision === "keep" ? {
|
|
479
|
+
status: "kept",
|
|
480
|
+
profileName
|
|
481
|
+
} : {
|
|
482
|
+
status: "refused",
|
|
483
|
+
profileName
|
|
484
|
+
};
|
|
485
|
+
}
|
|
486
|
+
const before = readConfig();
|
|
487
|
+
const after = updateConfig((config) => ({
|
|
488
|
+
...config,
|
|
489
|
+
activeProfile: profileName,
|
|
490
|
+
profiles: {
|
|
491
|
+
...config.profiles,
|
|
492
|
+
[profileName]: createIdentityProfile({
|
|
493
|
+
name: profileName,
|
|
494
|
+
companyName,
|
|
495
|
+
baseUrl: apiBase,
|
|
496
|
+
auth: signIn.auth
|
|
497
|
+
})
|
|
498
|
+
}
|
|
499
|
+
}));
|
|
500
|
+
for (const problem of await endUnusedSessions(before, after)) context.log(problem);
|
|
501
|
+
return {
|
|
502
|
+
status: "signed_in",
|
|
503
|
+
profileName,
|
|
504
|
+
companyName
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* Redeems a pasted sign-in link with Rails, which confirms the person's
|
|
509
|
+
* company signs in through the identity service, then signs in.
|
|
510
|
+
*/
|
|
511
|
+
async function loginWithIdentityLink(token, context) {
|
|
512
|
+
const spinner = context.spinner("Checking the sign-in link...");
|
|
513
|
+
const redemption = await (context.redeemIdentityLink ?? redeemIdentityLink)(token, { baseUrl: context.apiBase });
|
|
514
|
+
if (!redemption.success) {
|
|
515
|
+
spinner.fail(redemption.error.message);
|
|
516
|
+
if (redemption.error.code === "LINK_GONE") context.onLinkSettled?.();
|
|
517
|
+
return {
|
|
518
|
+
status: "failed",
|
|
519
|
+
error: redemption.error
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
context.onLinkSettled?.();
|
|
523
|
+
spinner.succeed("Sign-in link accepted");
|
|
524
|
+
return loginWithIdentity(context);
|
|
525
|
+
}
|
|
257
526
|
//#endregion
|
|
258
527
|
//#region src/commands/login.ts
|
|
259
528
|
/**
|
|
260
529
|
* fluid login — authenticate via email MFA or API token
|
|
530
|
+
*
|
|
531
|
+
* Besides the interactive sign-in, an email sign-in can run in two steps
|
|
532
|
+
* with no terminal, for an agent: `--send-code` emails the code and saves
|
|
533
|
+
* the server's sign-in id (auth/pending-login.ts), then `--code` redeems
|
|
534
|
+
* it. `--send-code` requires `--shop`, which ties the code to one company:
|
|
535
|
+
* only such a code lets an admin's sign-in confirm a new signup.
|
|
536
|
+
*
|
|
537
|
+
* A company on the identity sign-in path is emailed a link instead of a
|
|
538
|
+
* code, and Rails may answer a confirmed code with `sign_in_path:
|
|
539
|
+
* "identity"`. Either way the sign-in continues through the browser
|
|
540
|
+
* (commands/login-identity.ts); the CLI never picks the path itself.
|
|
541
|
+
*/
|
|
542
|
+
const defaultLoginDeps = {
|
|
543
|
+
api: {
|
|
544
|
+
validateToken,
|
|
545
|
+
sendMfa,
|
|
546
|
+
confirmMfa
|
|
547
|
+
},
|
|
548
|
+
prompt: (question) => prompts(question),
|
|
549
|
+
spinner: (text) => ora(text).start(),
|
|
550
|
+
log: (line) => console.log(line),
|
|
551
|
+
err: (line) => console.error(line),
|
|
552
|
+
env: process.env,
|
|
553
|
+
isInteractive: () => Boolean(process.stdin.isTTY),
|
|
554
|
+
readStdin: () => text(process.stdin),
|
|
555
|
+
pending: createPendingLoginStore()
|
|
556
|
+
};
|
|
557
|
+
const SILENT_SPINNER = {
|
|
558
|
+
succeed: () => {},
|
|
559
|
+
fail: () => {}
|
|
560
|
+
};
|
|
561
|
+
const TWO_STEP_HINT = "Sign in in two steps instead:\n fluid login --send-code --email <email> --shop <shop>\n fluid login --code --email <email> --yes\nwith the emailed code in FLUID_LOGIN_CODE (or --code - to read it from stdin). --yes replaces a profile with the company's name; --name <profile> picks another. Or set FLUID_TOKEN.";
|
|
562
|
+
function createUi(json, deps) {
|
|
563
|
+
return {
|
|
564
|
+
json,
|
|
565
|
+
spinner: (text) => json ? SILENT_SPINNER : deps.spinner(text),
|
|
566
|
+
result: (payload) => {
|
|
567
|
+
if (json) deps.log(JSON.stringify(payload, null, 2));
|
|
568
|
+
},
|
|
569
|
+
fail: (error, spinner) => {
|
|
570
|
+
if (json) {
|
|
571
|
+
deps.log(JSON.stringify({
|
|
572
|
+
status: "error",
|
|
573
|
+
code: error.code,
|
|
574
|
+
message: error.message,
|
|
575
|
+
...error.details ? { details: error.details } : {}
|
|
576
|
+
}, null, 2));
|
|
577
|
+
return 1;
|
|
578
|
+
}
|
|
579
|
+
if (spinner) spinner.fail(chalk.red(error.message));
|
|
580
|
+
else deps.log(chalk.red(error.message));
|
|
581
|
+
if (error.details) deps.log(chalk.dim(error.details));
|
|
582
|
+
return 1;
|
|
583
|
+
}
|
|
584
|
+
};
|
|
585
|
+
}
|
|
586
|
+
/** The shop option for an API call, or no argument at all without one. */
|
|
587
|
+
function shopArgs(shop) {
|
|
588
|
+
return shop ? [{ fluidShop: shop }] : [];
|
|
589
|
+
}
|
|
590
|
+
/** The part of a shop the server matches on: "acme" in "acme.fluid.app". */
|
|
591
|
+
function shopLabel(shop) {
|
|
592
|
+
return (shop.trim().toLowerCase().split(".")[0] ?? "").trim();
|
|
593
|
+
}
|
|
594
|
+
function findByShop(companies, shop) {
|
|
595
|
+
return companies.find((c) => shopLabel(c.shopName) === shopLabel(shop));
|
|
596
|
+
}
|
|
597
|
+
/**
|
|
598
|
+
* Whether the entry's token is an admin or rep session, the only kind the
|
|
599
|
+
* CLI's commands accept. A shopper's code returns a "member" or "customer"
|
|
600
|
+
* token instead. The server types every entry, so one with no type is
|
|
601
|
+
* refused rather than stored.
|
|
261
602
|
*/
|
|
262
|
-
|
|
603
|
+
function isStaffSession(company) {
|
|
604
|
+
return company.authType === "rep";
|
|
605
|
+
}
|
|
606
|
+
function shopperSession(email, company) {
|
|
607
|
+
return {
|
|
608
|
+
code: "SHOPPER_SESSION",
|
|
609
|
+
message: `${email} does not sign in at ${company.shopName} as an admin or rep, so it cannot sign in to the CLI.`
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
/**
|
|
613
|
+
* What to do about profile `profileName` before writing it: replace it when
|
|
614
|
+
* it is new or with `--yes`, ask in a terminal, and refuse otherwise, since
|
|
615
|
+
* no one could answer the question.
|
|
616
|
+
*/
|
|
617
|
+
function overwriteRule(profileName, opts) {
|
|
618
|
+
if (!readConfig().profiles[profileName] || opts.yes) return "replace";
|
|
619
|
+
return opts.interactive ? "ask" : "refuse";
|
|
620
|
+
}
|
|
621
|
+
async function overwriteDecision(profileName, opts, deps) {
|
|
622
|
+
const rule = overwriteRule(profileName, opts);
|
|
623
|
+
if (rule !== "ask") return rule;
|
|
263
624
|
const existing = readConfig().profiles[profileName];
|
|
264
|
-
|
|
265
|
-
const response = await prompts({
|
|
625
|
+
return (await deps.prompt({
|
|
266
626
|
type: "confirm",
|
|
267
627
|
name: "overwrite",
|
|
268
|
-
message: `Profile "${profileName}" already exists (${existing
|
|
628
|
+
message: `Profile "${profileName}" already exists (${existing?.companyName}). Overwrite?`,
|
|
269
629
|
initial: false
|
|
270
|
-
});
|
|
271
|
-
return Boolean(response["overwrite"]);
|
|
630
|
+
}))["overwrite"] ? "replace" : "keep";
|
|
272
631
|
}
|
|
273
|
-
function
|
|
274
|
-
|
|
632
|
+
function profileExists(profileName, codeUsed) {
|
|
633
|
+
return {
|
|
634
|
+
code: "PROFILE_EXISTS",
|
|
635
|
+
message: `Profile "${profileName}" already exists. Pass --yes to replace it` + (codeUsed ? "; the code is used, so send a new one first." : ".")
|
|
636
|
+
};
|
|
637
|
+
}
|
|
638
|
+
async function storeProfile(deps, profileName, token, companyName, baseUrl = getFluidApiBase()) {
|
|
639
|
+
const before = readConfig();
|
|
640
|
+
const after = updateConfig((config) => ({
|
|
275
641
|
...config,
|
|
276
642
|
activeProfile: profileName,
|
|
277
643
|
profiles: {
|
|
@@ -280,77 +646,111 @@ function storeProfile(profileName, token, companyName) {
|
|
|
280
646
|
name: profileName,
|
|
281
647
|
token,
|
|
282
648
|
companyName,
|
|
283
|
-
baseUrl
|
|
649
|
+
baseUrl
|
|
284
650
|
})
|
|
285
651
|
}
|
|
286
652
|
}));
|
|
653
|
+
for (const problem of await endUnusedSessions(before, after)) deps.err(chalk.yellow(problem));
|
|
287
654
|
}
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
655
|
+
function loggedIn(ui, deps, profileName, company) {
|
|
656
|
+
ui.result({
|
|
657
|
+
status: "signed_in",
|
|
658
|
+
profile: profileName,
|
|
659
|
+
company
|
|
660
|
+
});
|
|
661
|
+
if (!ui.json) deps.log(chalk.green(`Logged in as ${chalk.bold(company.name)} (profile: ${chalk.bold(profileName)})`));
|
|
662
|
+
return 0;
|
|
663
|
+
}
|
|
664
|
+
function cancelled(deps) {
|
|
665
|
+
deps.log(chalk.yellow("Login cancelled — existing profile not overwritten."));
|
|
666
|
+
return 0;
|
|
667
|
+
}
|
|
668
|
+
/**
|
|
669
|
+
* What the identity sign-in needs from this run: its output, its overwrite
|
|
670
|
+
* rule, and the API base the sign-in started against. With `--json` the
|
|
671
|
+
* person still needs the sign-in URL, so progress goes to stderr.
|
|
672
|
+
*/
|
|
673
|
+
function identityContext(opts, interactive, ui, deps, apiBase) {
|
|
674
|
+
return {
|
|
675
|
+
profileName: opts.name,
|
|
676
|
+
apiBase,
|
|
677
|
+
log: (line) => ui.json ? deps.err(line) : deps.log(line.startsWith("http") ? line : chalk.cyan(line)),
|
|
678
|
+
spinner: (text) => ui.spinner(text),
|
|
679
|
+
validateToken: (token, options) => deps.api.validateToken(token, {
|
|
680
|
+
baseUrl: apiBase,
|
|
681
|
+
...options
|
|
682
|
+
}),
|
|
683
|
+
redeemIdentityLink: deps.api.redeemIdentityLink,
|
|
684
|
+
decideOverwrite: (profileName) => overwriteDecision(profileName, {
|
|
685
|
+
yes: Boolean(opts.yes),
|
|
686
|
+
interactive
|
|
687
|
+
}, deps)
|
|
688
|
+
};
|
|
689
|
+
}
|
|
690
|
+
function identityResult(outcome, ui, deps) {
|
|
691
|
+
switch (outcome.status) {
|
|
692
|
+
case "signed_in": return loggedIn(ui, deps, outcome.profileName, { name: outcome.companyName });
|
|
693
|
+
case "kept": return cancelled(deps);
|
|
694
|
+
case "refused": return ui.fail(profileExists(outcome.profileName, false));
|
|
695
|
+
case "failed": return ui.fail(outcome.error);
|
|
296
696
|
}
|
|
297
|
-
|
|
697
|
+
}
|
|
698
|
+
const LINK_HINT = "If the email has a sign-in link instead of a code, paste the link here.";
|
|
699
|
+
async function loginWithToken(token, opts, interactive, ui, deps) {
|
|
700
|
+
const spinner = ui.spinner("Validating token...");
|
|
701
|
+
const result = await deps.api.validateToken(token);
|
|
702
|
+
if (!result.success) return ui.fail(result.error, spinner);
|
|
703
|
+
const name = opts.name ?? result.value.name;
|
|
298
704
|
spinner.succeed(chalk.green(`Token valid — ${chalk.bold(result.value.name)}`));
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
|
|
705
|
+
const decision = await overwriteDecision(name, {
|
|
706
|
+
yes: Boolean(opts.yes),
|
|
707
|
+
interactive
|
|
708
|
+
}, deps);
|
|
709
|
+
if (decision === "refuse") return ui.fail(profileExists(name, false));
|
|
710
|
+
if (decision === "keep") return cancelled(deps);
|
|
711
|
+
await storeProfile(deps, name, token, result.value.name);
|
|
712
|
+
return loggedIn(ui, deps, name, { name: result.value.name });
|
|
305
713
|
}
|
|
306
|
-
async function loginWithEmail(
|
|
307
|
-
let email =
|
|
714
|
+
async function loginWithEmail(opts, ui, deps) {
|
|
715
|
+
let email = opts.email;
|
|
308
716
|
if (!email) {
|
|
309
|
-
email = (await
|
|
717
|
+
email = (await deps.prompt({
|
|
310
718
|
type: "text",
|
|
311
719
|
name: "email",
|
|
312
720
|
message: "Enter your email"
|
|
313
721
|
}))["email"];
|
|
314
722
|
if (!email) {
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
return;
|
|
723
|
+
deps.log(chalk.red("No email provided. Aborting."));
|
|
724
|
+
return 1;
|
|
318
725
|
}
|
|
319
726
|
}
|
|
320
|
-
const sendSpinner =
|
|
321
|
-
const sendResult = await sendMfa(email);
|
|
322
|
-
if (!sendResult.success)
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
process.exitCode = 1;
|
|
326
|
-
return;
|
|
327
|
-
}
|
|
328
|
-
const expiresInMs = new Date(sendResult.value.expiresAt).getTime() - Date.now();
|
|
329
|
-
const expiresInMin = Math.round(expiresInMs / 1e3 / 60);
|
|
330
|
-
const expiryNote = expiresInMin > 0 ? `expires in ~${expiresInMin} min` : "code may expire soon — check your email quickly";
|
|
331
|
-
sendSpinner.succeed(`Verification code sent — check your email (${expiryNote})`);
|
|
727
|
+
const sendSpinner = ui.spinner("Sending verification code...");
|
|
728
|
+
const sendResult = await deps.api.sendMfa(email, ...shopArgs(opts.shop));
|
|
729
|
+
if (!sendResult.success) return ui.fail(sendResult.error, sendSpinner);
|
|
730
|
+
sendSpinner.succeed(`Verification code sent — check your email (${expiryNote(sendResult.value.expiresAt)})`);
|
|
731
|
+
if (!ui.json) deps.log(chalk.dim(LINK_HINT));
|
|
332
732
|
const MAX_CODE_ATTEMPTS = 3;
|
|
333
733
|
let confirmResult;
|
|
334
734
|
for (let attempt = 1; attempt <= MAX_CODE_ATTEMPTS; attempt++) {
|
|
335
|
-
const code = (await
|
|
735
|
+
const code = (await deps.prompt({
|
|
336
736
|
type: "text",
|
|
337
737
|
name: "code",
|
|
338
738
|
message: "Enter the 6-digit code"
|
|
339
739
|
}))["code"];
|
|
340
740
|
if (!code) {
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
return;
|
|
741
|
+
deps.log(chalk.red("No code provided. Aborting."));
|
|
742
|
+
return 1;
|
|
344
743
|
}
|
|
744
|
+
const linkToken = identityLinkToken(code);
|
|
745
|
+
if (linkToken) return identityResult(await loginWithIdentityLink(linkToken, identityContext(opts, true, ui, deps)), ui, deps);
|
|
345
746
|
if (!/^\d{6}$/.test(code)) {
|
|
346
|
-
|
|
747
|
+
deps.log(chalk.red("Code must be exactly 6 digits."));
|
|
347
748
|
if (attempt < MAX_CODE_ATTEMPTS) continue;
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
return;
|
|
749
|
+
deps.log(chalk.red("Too many invalid attempts. Aborting."));
|
|
750
|
+
return 1;
|
|
351
751
|
}
|
|
352
|
-
const confirmSpinner =
|
|
353
|
-
confirmResult = await confirmMfa(sendResult.value.uuid, code);
|
|
752
|
+
const confirmSpinner = ui.spinner("Verifying code...");
|
|
753
|
+
confirmResult = await deps.api.confirmMfa(sendResult.value.uuid, code, ...shopArgs(opts.shop));
|
|
354
754
|
if (confirmResult.success) {
|
|
355
755
|
confirmSpinner.succeed("Verified");
|
|
356
756
|
break;
|
|
@@ -359,79 +759,283 @@ async function loginWithEmail(initialEmail, profileName) {
|
|
|
359
759
|
confirmSpinner.fail(chalk.red(`${confirmResult.error.message} (attempt ${attempt}/${MAX_CODE_ATTEMPTS})`));
|
|
360
760
|
continue;
|
|
361
761
|
}
|
|
362
|
-
|
|
363
|
-
if (confirmResult.error.details) console.log(chalk.dim(confirmResult.error.details));
|
|
364
|
-
process.exitCode = 1;
|
|
365
|
-
return;
|
|
762
|
+
return ui.fail(confirmResult.error, confirmSpinner);
|
|
366
763
|
}
|
|
367
|
-
if (!confirmResult?.success) return;
|
|
764
|
+
if (!confirmResult?.success) return 0;
|
|
765
|
+
if (signInPathFor(confirmResult.value) === "identity") return identityResult(await loginWithIdentity(identityContext(opts, true, ui, deps)), ui, deps);
|
|
368
766
|
const { companies } = confirmResult.value;
|
|
369
767
|
if (companies.length === 0) {
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
return;
|
|
768
|
+
deps.log(chalk.red("No companies found for this account."));
|
|
769
|
+
return 1;
|
|
373
770
|
}
|
|
771
|
+
const named = opts.shop ? findByShop(companies, opts.shop) : void 0;
|
|
374
772
|
let selected;
|
|
375
|
-
if (
|
|
773
|
+
if (named) selected = named;
|
|
774
|
+
else if (companies.length === 1) {
|
|
376
775
|
const first = companies[0];
|
|
377
776
|
if (!first) {
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
return;
|
|
777
|
+
deps.log(chalk.red("No companies found for this account."));
|
|
778
|
+
return 1;
|
|
381
779
|
}
|
|
382
780
|
selected = first;
|
|
383
781
|
} else {
|
|
384
|
-
const
|
|
782
|
+
const companyChoices = companies.map((c) => ({
|
|
783
|
+
title: `${c.name} (${c.shopName})`,
|
|
784
|
+
value: c.id
|
|
785
|
+
}));
|
|
786
|
+
const companyId = (await deps.prompt({
|
|
385
787
|
type: "autocomplete",
|
|
386
788
|
name: "companyId",
|
|
387
789
|
message: "Select a company (type to search)",
|
|
388
|
-
choices:
|
|
389
|
-
title: `${c.name} (${c.shopName})`,
|
|
390
|
-
value: c.id
|
|
391
|
-
})),
|
|
790
|
+
choices: companyChoices,
|
|
392
791
|
suggest: (input, choices) => Promise.resolve(input ? choices.filter((c) => c.title.toLowerCase().includes(input.toLowerCase())) : choices)
|
|
393
792
|
}))["companyId"];
|
|
394
793
|
if (companyId === void 0) {
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
return;
|
|
794
|
+
deps.log(chalk.red("No company selected. Aborting."));
|
|
795
|
+
return 1;
|
|
398
796
|
}
|
|
399
797
|
const choice = companies.find((c) => c.id === companyId);
|
|
400
798
|
if (!choice) {
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
return;
|
|
799
|
+
deps.log(chalk.red("Invalid selection. Aborting."));
|
|
800
|
+
return 1;
|
|
404
801
|
}
|
|
405
802
|
selected = choice;
|
|
406
803
|
}
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
804
|
+
if (!isStaffSession(selected)) return ui.fail(shopperSession(email, selected));
|
|
805
|
+
const name = opts.name ?? selected.name;
|
|
806
|
+
if (await overwriteDecision(name, {
|
|
807
|
+
yes: Boolean(opts.yes),
|
|
808
|
+
interactive: true
|
|
809
|
+
}, deps) !== "replace") return cancelled(deps);
|
|
810
|
+
await storeProfile(deps, name, selected.jwt, selected.name);
|
|
811
|
+
return loggedIn(ui, deps, name, { name: selected.name });
|
|
812
|
+
}
|
|
813
|
+
function expiryNote(expiresAtIso) {
|
|
814
|
+
const expiresInMs = new Date(expiresAtIso).getTime() - Date.now();
|
|
815
|
+
const expiresInMin = Math.round(expiresInMs / 1e3 / 60);
|
|
816
|
+
return expiresInMin > 0 ? `expires in ~${expiresInMin} min` : "code may expire soon — check your email quickly";
|
|
817
|
+
}
|
|
818
|
+
const SHELL_SAFE = /^[\w.@+-]+$/;
|
|
819
|
+
/**
|
|
820
|
+
* The command that finishes this sign-in, for a person or agent to run.
|
|
821
|
+
* Values with characters a shell would act on are left as placeholders.
|
|
822
|
+
*/
|
|
823
|
+
function finishCommand(email, shop) {
|
|
824
|
+
const safe = (value, placeholder) => SHELL_SAFE.test(value) ? value : placeholder;
|
|
825
|
+
return `fluid login --code --email ${safe(email, "<email>")} --shop ${safe(shop, "<shop>")}`;
|
|
826
|
+
}
|
|
827
|
+
/** `fluid login --send-code`: email a code, save the sign-in, exit. */
|
|
828
|
+
async function sendCodeStep(opts, ui, deps) {
|
|
829
|
+
if (!opts.email) return ui.fail({
|
|
830
|
+
code: "EMAIL_REQUIRED",
|
|
831
|
+
message: "--send-code needs --email <address>."
|
|
832
|
+
});
|
|
833
|
+
if (!opts.shop) return ui.fail({
|
|
834
|
+
code: "SHOP_REQUIRED",
|
|
835
|
+
message: "--send-code needs --shop <shop>, the company to sign in to (acme or acme.fluid.app). A new signup's response names it as fluid_shop."
|
|
836
|
+
});
|
|
837
|
+
const email = normaliseEmail(opts.email);
|
|
838
|
+
const shop = opts.shop;
|
|
839
|
+
const spinner = ui.spinner("Sending verification code...");
|
|
840
|
+
const sent = await deps.api.sendMfa(email, ...shopArgs(shop));
|
|
841
|
+
if (!sent.success) return ui.fail(sent.error, spinner);
|
|
842
|
+
deps.pending.save({
|
|
843
|
+
uuid: sent.value.uuid,
|
|
844
|
+
email,
|
|
845
|
+
shop,
|
|
846
|
+
expiresAt: sent.value.expiresAt,
|
|
847
|
+
baseUrl: getFluidApiBase()
|
|
848
|
+
});
|
|
849
|
+
spinner.succeed(`If ${email} can sign in at ${shop}, a code is on its way (${expiryNote(sent.value.expiresAt)})`);
|
|
850
|
+
ui.result({
|
|
851
|
+
status: "code_sent",
|
|
852
|
+
email,
|
|
853
|
+
shop,
|
|
854
|
+
expiresAt: sent.value.expiresAt
|
|
855
|
+
});
|
|
856
|
+
if (!ui.json) {
|
|
857
|
+
deps.log(`Finish with: ${finishCommand(email, shop)}`);
|
|
858
|
+
deps.log(chalk.dim("with the code in FLUID_LOGIN_CODE, or add - after --code to read it from stdin. If the email has a sign-in link instead of a code, pass the link the same way. With no terminal, add --yes to replace a profile with the company's name, or --name <profile>."));
|
|
859
|
+
}
|
|
860
|
+
return 0;
|
|
861
|
+
}
|
|
862
|
+
/**
|
|
863
|
+
* The code for the finish step. A bare `--code` reads FLUID_LOGIN_CODE,
|
|
864
|
+
* `--code -` reads stdin, and any other value is the code. Stdin is read
|
|
865
|
+
* only when asked for: an agent's stdin may be a pipe that never closes,
|
|
866
|
+
* and reading it uninvited would wait forever.
|
|
867
|
+
*/
|
|
868
|
+
async function readCode(opts, deps) {
|
|
869
|
+
if (opts.code === "-") return (await deps.readStdin()).trim() || void 0;
|
|
870
|
+
if (typeof opts.code === "string") {
|
|
871
|
+
deps.err(chalk.yellow("Warning: a code passed via --code is visible in shell history and process listings. Prefer FLUID_LOGIN_CODE, or --code - to read it from stdin."));
|
|
872
|
+
return opts.code.trim();
|
|
873
|
+
}
|
|
874
|
+
return deps.env["FLUID_LOGIN_CODE"]?.trim() || void 0;
|
|
875
|
+
}
|
|
876
|
+
/** The server's answer for a code that cannot finish, by error code. */
|
|
877
|
+
function finishError(error, shop) {
|
|
878
|
+
if (error.code === "INVALID_CODE") return {
|
|
879
|
+
code: error.code,
|
|
880
|
+
message: `${error.message}. Five wrong codes lock this sign-in; then run --send-code again.`
|
|
881
|
+
};
|
|
882
|
+
if (error.code === "UUID_NOT_FOUND") return {
|
|
883
|
+
code: error.code,
|
|
884
|
+
message: `This sign-in can't be finished with a code: the shop "${shop}" is wrong, the address is not an admin or rep there, or the company signs in with an emailed link instead (pass that link to --code in place of the code). Check them and run --send-code again.`
|
|
885
|
+
};
|
|
886
|
+
return error;
|
|
887
|
+
}
|
|
888
|
+
/** `fluid login --code`: redeem the code for the saved sign-in. */
|
|
889
|
+
async function finishStep(opts, interactive, ui, deps) {
|
|
890
|
+
if (!opts.email) return ui.fail({
|
|
891
|
+
code: "EMAIL_REQUIRED",
|
|
892
|
+
message: "--code needs --email <address>, the one used with --send-code."
|
|
893
|
+
});
|
|
894
|
+
if (!interactive && !opts.yes && !opts.name) return ui.fail({
|
|
895
|
+
code: "YES_OR_NAME_REQUIRED",
|
|
896
|
+
message: "With no terminal, --code needs --yes, to replace a profile with the company's name, or --name <profile>."
|
|
897
|
+
});
|
|
898
|
+
const email = normaliseEmail(opts.email);
|
|
899
|
+
const record = deps.pending.load(email);
|
|
900
|
+
if (!record) return ui.fail({
|
|
901
|
+
code: "NO_PENDING_LOGIN",
|
|
902
|
+
message: `No sign-in is waiting for ${email}. Run fluid login --send-code --email ${email} first.`
|
|
903
|
+
});
|
|
904
|
+
const { shop } = record;
|
|
905
|
+
if (opts.shop && shopLabel(opts.shop) !== shopLabel(shop)) return ui.fail({
|
|
906
|
+
code: "SHOP_MISMATCH",
|
|
907
|
+
message: `The code for ${email} was sent for ${shop}, not ${opts.shop}.`
|
|
908
|
+
});
|
|
909
|
+
if (!(Date.parse(record.expiresAt) > Date.now())) {
|
|
910
|
+
deps.pending.remove(email);
|
|
911
|
+
return ui.fail({
|
|
912
|
+
code: "CODE_EXPIRED",
|
|
913
|
+
message: `The code for ${email} has expired. Run fluid login --send-code again.`
|
|
914
|
+
});
|
|
915
|
+
}
|
|
916
|
+
const code = await readCode(opts, deps);
|
|
917
|
+
if (!code) return ui.fail({
|
|
918
|
+
code: "NO_CODE",
|
|
919
|
+
message: "No code given. Put it in FLUID_LOGIN_CODE, pass --code - to read it from stdin, or pass it to --code."
|
|
920
|
+
});
|
|
921
|
+
const linkToken = identityLinkToken(code);
|
|
922
|
+
if (!linkToken && !/^\d{6}$/.test(code)) return ui.fail({
|
|
923
|
+
code: "INVALID_CODE_FORMAT",
|
|
924
|
+
message: "The code must be exactly 6 digits."
|
|
925
|
+
});
|
|
926
|
+
const overwrite = {
|
|
927
|
+
yes: Boolean(opts.yes),
|
|
928
|
+
interactive
|
|
929
|
+
};
|
|
930
|
+
if (opts.name && overwriteRule(opts.name, overwrite) === "refuse") return ui.fail(profileExists(opts.name, false));
|
|
931
|
+
if (linkToken) return identityResult(await loginWithIdentityLink(linkToken, {
|
|
932
|
+
...identityContext(opts, interactive, ui, deps, record.baseUrl),
|
|
933
|
+
onLinkSettled: () => deps.pending.remove(email)
|
|
934
|
+
}), ui, deps);
|
|
935
|
+
const spinner = ui.spinner("Verifying code...");
|
|
936
|
+
const confirmed = await deps.api.confirmMfa(record.uuid, code, {
|
|
937
|
+
fluidShop: shop,
|
|
938
|
+
baseUrl: record.baseUrl
|
|
939
|
+
});
|
|
940
|
+
if (!confirmed.success) {
|
|
941
|
+
if (![
|
|
942
|
+
"INVALID_CODE",
|
|
943
|
+
"RATE_LIMITED",
|
|
944
|
+
"API_UNREACHABLE"
|
|
945
|
+
].includes(confirmed.error.code)) deps.pending.remove(email);
|
|
946
|
+
return ui.fail(finishError(confirmed.error, shop), spinner);
|
|
947
|
+
}
|
|
948
|
+
spinner.succeed("Verified");
|
|
949
|
+
deps.pending.remove(email);
|
|
950
|
+
if (signInPathFor(confirmed.value) === "identity") return identityResult(await loginWithIdentity(identityContext(opts, interactive, ui, deps, record.baseUrl)), ui, deps);
|
|
951
|
+
const { companies } = confirmed.value;
|
|
952
|
+
const selected = findByShop(companies, shop);
|
|
953
|
+
if (!selected) {
|
|
954
|
+
if (companies.length === 0) return ui.fail({
|
|
955
|
+
code: "NO_COMPANIES",
|
|
956
|
+
message: "No companies found for this account."
|
|
957
|
+
});
|
|
958
|
+
const shops = companies.map((c) => c.shopName).join(", ");
|
|
959
|
+
return ui.fail({
|
|
960
|
+
code: "SHOP_NOT_FOUND",
|
|
961
|
+
message: `This account has no company at ${shop}. It has: ${shops}.`
|
|
962
|
+
});
|
|
411
963
|
}
|
|
412
|
-
|
|
413
|
-
|
|
964
|
+
if (!isStaffSession(selected)) return ui.fail(shopperSession(email, selected));
|
|
965
|
+
const name = opts.name ?? selected.name;
|
|
966
|
+
const decision = await overwriteDecision(name, overwrite, deps);
|
|
967
|
+
if (decision === "refuse") return ui.fail(profileExists(name, true));
|
|
968
|
+
if (decision === "keep") return cancelled(deps);
|
|
969
|
+
await storeProfile(deps, name, selected.jwt, selected.name, record.baseUrl);
|
|
970
|
+
return loggedIn(ui, deps, name, {
|
|
971
|
+
id: selected.id,
|
|
972
|
+
name: selected.name,
|
|
973
|
+
shop: selected.shopName
|
|
974
|
+
});
|
|
414
975
|
}
|
|
415
|
-
|
|
416
|
-
|
|
976
|
+
/**
|
|
977
|
+
* Run `fluid login` and return its exit code.
|
|
978
|
+
*/
|
|
979
|
+
async function runLogin(opts, deps = defaultLoginDeps) {
|
|
980
|
+
const json = Boolean(opts.json);
|
|
981
|
+
const ui = createUi(json, deps);
|
|
982
|
+
const interactive = deps.isInteractive() && !json && opts.code !== "-";
|
|
983
|
+
if (opts.sendCode || opts.code !== void 0) {
|
|
984
|
+
if (opts.token) return ui.fail({
|
|
985
|
+
code: "FLAG_CONFLICT",
|
|
986
|
+
message: "--token cannot be combined with --send-code or --code."
|
|
987
|
+
});
|
|
988
|
+
if (opts.sendCode && opts.code !== void 0) return ui.fail({
|
|
989
|
+
code: "FLAG_CONFLICT",
|
|
990
|
+
message: "Run --send-code and --code as two separate commands."
|
|
991
|
+
});
|
|
992
|
+
return opts.sendCode ? sendCodeStep(opts, ui, deps) : finishStep(opts, interactive, ui, deps);
|
|
993
|
+
}
|
|
994
|
+
const token = opts.token ?? deps.env["FLUID_TOKEN"];
|
|
417
995
|
if (token) {
|
|
418
|
-
if (opts.token)
|
|
419
|
-
|
|
420
|
-
}
|
|
421
|
-
|
|
996
|
+
if (opts.token) (json ? deps.err : deps.log)(chalk.yellow("Warning: token passed via --token flag is visible in shell history and process listings. Prefer the FLUID_TOKEN environment variable."));
|
|
997
|
+
return loginWithToken(token, opts, interactive, ui, deps);
|
|
998
|
+
}
|
|
999
|
+
if (!interactive) {
|
|
1000
|
+
const why = json ? "fluid login --json cannot ask for the email and code." : "fluid login needs a terminal to ask for the email and code.";
|
|
1001
|
+
return ui.fail({
|
|
1002
|
+
code: "NOT_INTERACTIVE",
|
|
1003
|
+
message: `${why}\n${TWO_STEP_HINT}`
|
|
1004
|
+
});
|
|
1005
|
+
}
|
|
1006
|
+
return loginWithEmail(opts, ui, deps);
|
|
1007
|
+
}
|
|
1008
|
+
/**
|
|
1009
|
+
* The `login` command, running `run` with the parsed options. Built by a
|
|
1010
|
+
* function so a test can check the flag parsing without signing in.
|
|
1011
|
+
*/
|
|
1012
|
+
function buildLoginCommand(run = (opts) => runLogin(opts)) {
|
|
1013
|
+
return new Command("login").description("Authenticate with the Fluid API").option("-t, --token <token>", "API token (skips email flow). Prefer FLUID_TOKEN env var to avoid shell history exposure").option("-e, --email <email>", "Email address for MFA login (required with --send-code and --code)").option("-n, --name <name>", "Profile name (defaults to company name)").option("--shop <shop>", "Sign in to this company (e.g. acme or acme.fluid.app); required with --send-code. An admin's emailed code also confirms a new signup").option("--send-code", "Email a sign-in code and exit, for use without a terminal; finish with --code").option("--code [code]", "Finish a sign-in started with --send-code. Reads the code from FLUID_LOGIN_CODE, or from stdin with --code -; a code given here is visible in shell history").option("-y, --yes", "Replace an existing profile without asking").option("--json", "Print the result as JSON").action(async (opts) => {
|
|
1014
|
+
const exitCode = await run(opts);
|
|
1015
|
+
if (exitCode !== 0) process.exitCode = exitCode;
|
|
1016
|
+
});
|
|
1017
|
+
}
|
|
1018
|
+
const loginCommand = buildLoginCommand();
|
|
422
1019
|
//#endregion
|
|
423
1020
|
//#region src/commands/logout.ts
|
|
424
1021
|
/**
|
|
425
1022
|
* fluid logout — remove stored auth profile(s)
|
|
1023
|
+
*
|
|
1024
|
+
* An identity-mode profile's session is revoked at the identity service and
|
|
1025
|
+
* its refresh token deleted from the credential store, once no remaining
|
|
1026
|
+
* profile uses it. (The identity service's `/signout` is a browser
|
|
1027
|
+
* navigation; a native client revokes its refresh token instead.)
|
|
426
1028
|
*/
|
|
427
|
-
const logoutCommand = new Command("logout").description("Remove stored authentication").option("-a, --all", "Remove all profiles").action((opts) => {
|
|
1029
|
+
const logoutCommand = new Command("logout").description("Remove stored authentication").option("-a, --all", "Remove all profiles").action(async (opts) => {
|
|
428
1030
|
const config = readConfig();
|
|
429
1031
|
if (opts.all) {
|
|
430
|
-
|
|
1032
|
+
const after = {
|
|
431
1033
|
...config,
|
|
432
1034
|
activeProfile: null,
|
|
433
1035
|
profiles: {}
|
|
434
|
-
}
|
|
1036
|
+
};
|
|
1037
|
+
writeConfig(after);
|
|
1038
|
+
for (const problem of await endUnusedSessions(config, after)) console.log(chalk.yellow(problem));
|
|
435
1039
|
console.log(chalk.green("All profiles removed."));
|
|
436
1040
|
return;
|
|
437
1041
|
}
|
|
@@ -442,11 +1046,13 @@ const logoutCommand = new Command("logout").description("Remove stored authentic
|
|
|
442
1046
|
const profileName = config.activeProfile;
|
|
443
1047
|
const { [profileName]: _, ...remainingProfiles } = config.profiles;
|
|
444
1048
|
const nextActive = Object.keys(remainingProfiles)[0] ?? null;
|
|
445
|
-
|
|
1049
|
+
const after = {
|
|
446
1050
|
...config,
|
|
447
1051
|
activeProfile: nextActive,
|
|
448
1052
|
profiles: remainingProfiles
|
|
449
|
-
}
|
|
1053
|
+
};
|
|
1054
|
+
writeConfig(after);
|
|
1055
|
+
for (const problem of await endUnusedSessions(config, after)) console.log(chalk.yellow(problem));
|
|
450
1056
|
console.log(chalk.green(`Logged out of profile ${chalk.bold(profileName)}.`));
|
|
451
1057
|
if (nextActive) console.log(chalk.dim(`Switched to profile ${nextActive}.`));
|
|
452
1058
|
});
|
|
@@ -454,7 +1060,31 @@ const logoutCommand = new Command("logout").description("Remove stored authentic
|
|
|
454
1060
|
//#region src/commands/whoami.ts
|
|
455
1061
|
/**
|
|
456
1062
|
* fluid whoami — show current auth profile and validate against API
|
|
1063
|
+
*
|
|
1064
|
+
* An identity-mode profile is shown from its identity session: the facts
|
|
1065
|
+
* come from the identity service's `/userinfo`, never from decoding a token.
|
|
457
1066
|
*/
|
|
1067
|
+
async function whoamiIdentity(profile) {
|
|
1068
|
+
const spinner = ora("Checking your identity session...").start();
|
|
1069
|
+
let facts;
|
|
1070
|
+
try {
|
|
1071
|
+
({facts} = await identityToken(profile.auth));
|
|
1072
|
+
} catch (error) {
|
|
1073
|
+
spinner.fail(chalk.red(describeIdentityError(error)));
|
|
1074
|
+
console.log(chalk.dim(`Profile: ${profile.name}`));
|
|
1075
|
+
process.exitCode = 1;
|
|
1076
|
+
return;
|
|
1077
|
+
}
|
|
1078
|
+
spinner.succeed(chalk.green("Authenticated (Fluid identity service)"));
|
|
1079
|
+
console.log(` Profile: ${chalk.bold(profile.name)}`);
|
|
1080
|
+
console.log(` Company: ${chalk.bold(profile.companyName)}`);
|
|
1081
|
+
if (facts.companyId) console.log(` Company ID: ${chalk.dim(facts.companyId)}`);
|
|
1082
|
+
console.log(` Subject: ${chalk.dim(facts.subject)}`);
|
|
1083
|
+
if (facts.roles.length > 0) console.log(` Roles: ${facts.roles.join(", ")}`);
|
|
1084
|
+
if (facts.impersonating && facts.actor) console.log(` Acting as: ${chalk.yellow(facts.actor)}`);
|
|
1085
|
+
console.log(` Signed in: ${chalk.dim((/* @__PURE__ */ new Date(facts.authTime * 1e3)).toISOString())}`);
|
|
1086
|
+
console.log(` Stored: ${chalk.dim(profile.storedAt)}`);
|
|
1087
|
+
}
|
|
458
1088
|
const whoamiCommand = new Command("whoami").description("Show the current authenticated profile").action(async () => {
|
|
459
1089
|
const profile = getActiveProfile();
|
|
460
1090
|
if (!profile) {
|
|
@@ -462,8 +1092,12 @@ const whoamiCommand = new Command("whoami").description("Show the current authen
|
|
|
462
1092
|
process.exitCode = 1;
|
|
463
1093
|
return;
|
|
464
1094
|
}
|
|
1095
|
+
if (isIdentityProfile(profile)) {
|
|
1096
|
+
await whoamiIdentity(profile);
|
|
1097
|
+
return;
|
|
1098
|
+
}
|
|
465
1099
|
const spinner = ora("Verifying token...").start();
|
|
466
|
-
const result = await validateToken(profile.token);
|
|
1100
|
+
const result = await validateToken(profile.token ?? "");
|
|
467
1101
|
if (!result.success) {
|
|
468
1102
|
spinner.fail(chalk.red("Token is no longer valid."));
|
|
469
1103
|
console.log(chalk.dim(`Profile: ${profile.name}`));
|
|
@@ -480,6 +1114,10 @@ const whoamiCommand = new Command("whoami").description("Show the current authen
|
|
|
480
1114
|
//#region src/commands/switch.ts
|
|
481
1115
|
/**
|
|
482
1116
|
* fluid switch — switch between companies (fetched from API, with local fallback)
|
|
1117
|
+
*
|
|
1118
|
+
* An identity-mode profile switches by token exchange (Phase 007 FR-3): the
|
|
1119
|
+
* session it signed in with stays as it is, and the new company's profile
|
|
1120
|
+
* remembers the company to exchange into. Nothing secret is written.
|
|
483
1121
|
*/
|
|
484
1122
|
async function localSwitch(profileArg) {
|
|
485
1123
|
const config = readConfig();
|
|
@@ -560,6 +1198,43 @@ async function performSwitch(token, company, baseUrl) {
|
|
|
560
1198
|
}));
|
|
561
1199
|
spinner.succeed(chalk.green(`Switched to ${chalk.bold(companyName)} (profile: ${chalk.bold(companyName)})`));
|
|
562
1200
|
}
|
|
1201
|
+
async function performIdentitySwitch(profile, company, baseUrl) {
|
|
1202
|
+
const spinner = ora(`Switching to ${chalk.bold(company.name)}...`).start();
|
|
1203
|
+
if (!company.uuidV7) {
|
|
1204
|
+
spinner.fail(chalk.red(`${company.name} has no identifier to switch to it by.`));
|
|
1205
|
+
process.exitCode = 1;
|
|
1206
|
+
return;
|
|
1207
|
+
}
|
|
1208
|
+
let org;
|
|
1209
|
+
try {
|
|
1210
|
+
const home = (await sessionFacts(profile.auth)).companyId;
|
|
1211
|
+
org = company.uuidV7 === home ? void 0 : company.uuidV7;
|
|
1212
|
+
await identityToken(profile.auth, org ?? null);
|
|
1213
|
+
} catch (error) {
|
|
1214
|
+
spinner.fail(chalk.red(describeIdentityError(error)));
|
|
1215
|
+
process.exitCode = 1;
|
|
1216
|
+
return;
|
|
1217
|
+
}
|
|
1218
|
+
const { org: _previous, ...session } = profile.auth;
|
|
1219
|
+
const problems = await endUnusedSessions(readConfig(), updateConfig((config) => ({
|
|
1220
|
+
...config,
|
|
1221
|
+
activeProfile: company.name,
|
|
1222
|
+
profiles: {
|
|
1223
|
+
...config.profiles,
|
|
1224
|
+
[company.name]: createIdentityProfile({
|
|
1225
|
+
name: company.name,
|
|
1226
|
+
companyName: company.name,
|
|
1227
|
+
baseUrl,
|
|
1228
|
+
auth: org ? {
|
|
1229
|
+
...session,
|
|
1230
|
+
org
|
|
1231
|
+
} : session
|
|
1232
|
+
})
|
|
1233
|
+
}
|
|
1234
|
+
})));
|
|
1235
|
+
spinner.succeed(chalk.green(`Switched to ${chalk.bold(company.name)} (profile: ${chalk.bold(company.name)})`));
|
|
1236
|
+
for (const problem of problems) console.log(chalk.yellow(problem));
|
|
1237
|
+
}
|
|
563
1238
|
const switchCommand = new Command("switch").description("Switch between companies").argument("[profile]", "Company or profile name to switch to").action(async (profileArg) => {
|
|
564
1239
|
const activeProfile = getActiveProfile();
|
|
565
1240
|
if (!activeProfile) {
|
|
@@ -567,10 +1242,18 @@ const switchCommand = new Command("switch").description("Switch between companie
|
|
|
567
1242
|
process.exitCode = 1;
|
|
568
1243
|
return;
|
|
569
1244
|
}
|
|
570
|
-
const token = activeProfile.token;
|
|
571
1245
|
const activeCompanyName = activeProfile.companyName;
|
|
572
1246
|
const activeBaseUrl = activeProfile.baseUrl ?? getFluidApiBase();
|
|
1247
|
+
const identity = isIdentityProfile(activeProfile) ? activeProfile : null;
|
|
573
1248
|
const spinner = ora("Fetching companies...").start();
|
|
1249
|
+
let token = activeProfile.token ?? "";
|
|
1250
|
+
if (identity) try {
|
|
1251
|
+
token = (await identityToken(identity.auth)).accessToken;
|
|
1252
|
+
} catch (error) {
|
|
1253
|
+
spinner.fail(chalk.red(describeIdentityError(error)));
|
|
1254
|
+
process.exitCode = 1;
|
|
1255
|
+
return;
|
|
1256
|
+
}
|
|
574
1257
|
const result = await fetchUserCompanies(token, activeBaseUrl);
|
|
575
1258
|
if (!result.success) {
|
|
576
1259
|
if (result.error.code === FLUID_API_ERROR.INVALID_TOKEN.code) {
|
|
@@ -593,7 +1276,7 @@ const switchCommand = new Command("switch").description("Switch between companie
|
|
|
593
1276
|
if (profileArg) {
|
|
594
1277
|
const match = companies.find((c) => c.name.toLowerCase() === profileArg.toLowerCase());
|
|
595
1278
|
if (match) {
|
|
596
|
-
await performSwitch(token, match, activeBaseUrl);
|
|
1279
|
+
await (identity ? performIdentitySwitch(identity, match, activeBaseUrl) : performSwitch(token, match, activeBaseUrl));
|
|
597
1280
|
return;
|
|
598
1281
|
}
|
|
599
1282
|
if (readConfig().profiles[profileArg]) {
|
|
@@ -613,9 +1296,32 @@ const switchCommand = new Command("switch").description("Switch between companie
|
|
|
613
1296
|
console.log(chalk.dim("Cancelled."));
|
|
614
1297
|
return;
|
|
615
1298
|
}
|
|
616
|
-
await performSwitch(token, selected, activeBaseUrl);
|
|
1299
|
+
await (identity ? performIdentitySwitch(identity, selected, activeBaseUrl) : performSwitch(token, selected, activeBaseUrl));
|
|
617
1300
|
});
|
|
618
1301
|
//#endregion
|
|
1302
|
+
//#region src/auth/identity/prime.ts
|
|
1303
|
+
/**
|
|
1304
|
+
* Restores an identity-mode profile's session before a command runs, so the
|
|
1305
|
+
* synchronous `getAuthToken()` that plugins call finds a current access
|
|
1306
|
+
* token in memory. Legacy profiles and literal tokens are left alone: no
|
|
1307
|
+
* credential store is touched and no request is made for them.
|
|
1308
|
+
*/
|
|
1309
|
+
/**
|
|
1310
|
+
* Primes the credential a command with these options would use. A session
|
|
1311
|
+
* that cannot be restored is reported on stderr, and the command runs on as
|
|
1312
|
+
* it would with no stored credential.
|
|
1313
|
+
*/
|
|
1314
|
+
async function primeCommandCredential(options) {
|
|
1315
|
+
if (typeof options.token === "string" && options.token) return;
|
|
1316
|
+
const source = resolveCredentialSource(typeof options.profile === "string" && options.profile ? options.profile : void 0);
|
|
1317
|
+
if (source?.kind !== "profile" || !isIdentityProfile(source.profile)) return;
|
|
1318
|
+
try {
|
|
1319
|
+
await primeIdentityProfile(source.profile);
|
|
1320
|
+
} catch (error) {
|
|
1321
|
+
process.stderr.write(`${chalk.yellow(describeIdentityError(error))}\n`);
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
//#endregion
|
|
619
1325
|
//#region src/plugins/discovery.ts
|
|
620
1326
|
/**
|
|
621
1327
|
* Auto-discover @fluid-app CLI plugins.
|
|
@@ -1125,6 +1831,21 @@ program.addCommand(switchCommand);
|
|
|
1125
1831
|
program.addCommand(commandsCommand);
|
|
1126
1832
|
program.addCommand(completionCommand);
|
|
1127
1833
|
program.addCommand(completeCommand, { hidden: true });
|
|
1834
|
+
const selfAuthenticating = new Set([
|
|
1835
|
+
loginCommand,
|
|
1836
|
+
logoutCommand,
|
|
1837
|
+
whoamiCommand,
|
|
1838
|
+
switchCommand,
|
|
1839
|
+
commandsCommand,
|
|
1840
|
+
completionCommand,
|
|
1841
|
+
completeCommand
|
|
1842
|
+
].map((command) => command.name()));
|
|
1843
|
+
program.hook("preAction", async (_program, actionCommand) => {
|
|
1844
|
+
let topLevel = actionCommand;
|
|
1845
|
+
while (topLevel.parent && topLevel.parent !== program) topLevel = topLevel.parent;
|
|
1846
|
+
if (selfAuthenticating.has(topLevel.name())) return;
|
|
1847
|
+
await primeCommandCredential(actionCommand.opts());
|
|
1848
|
+
});
|
|
1128
1849
|
startUpdateCheck({
|
|
1129
1850
|
currentVersion: version,
|
|
1130
1851
|
configDir: getConfigDir(),
|
|
@@ -1135,7 +1856,7 @@ startUpdateCheck({
|
|
|
1135
1856
|
versions: process.versions
|
|
1136
1857
|
});
|
|
1137
1858
|
await loadPlugins(program, packageRoot);
|
|
1138
|
-
program.
|
|
1859
|
+
await program.parseAsync(process.argv, { from: "node" });
|
|
1139
1860
|
//#endregion
|
|
1140
1861
|
export {};
|
|
1141
1862
|
|