@fluid-app/fluid-cli 0.1.65 → 0.1.66

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -67,6 +67,23 @@ With no terminal, `fluid login` fails at once rather than waiting at a
67
67
  prompt, unless it has a token (`--token` or `FLUID_TOKEN`) or runs one of
68
68
  the two steps (`--send-code`, `--code`).
69
69
 
70
+ ### Companies on Fluid's identity sign-in
71
+
72
+ Fluid decides per company whether it signs in through the identity service.
73
+ For such a company the email has a sign-in link instead of a code. Paste the
74
+ link at the code prompt, or, without a terminal, give it to `--code` the same
75
+ way as a code (in `FLUID_LOGIN_CODE` or on stdin). `fluid login` then opens
76
+ your browser to sign in and receives the result on a one-time server at
77
+ `http://127.0.0.1:<port>/callback`. The sign-in URL is printed too (on stderr
78
+ with `--json`), for a terminal with no browser to open.
79
+
80
+ In this mode no token is written to `config.json`. The refresh token is kept in
81
+ the operating system credential store (macOS Keychain, Windows Credential
82
+ Manager, or the Secret Service on Linux), and access tokens only in memory.
83
+ `fluid switch` moves company by token exchange, `fluid whoami` reads the
84
+ identity session, and `fluid logout` revokes the session. Every other company
85
+ signs in exactly as before.
86
+
70
87
  ## Plugins
71
88
 
72
89
  Install plugins alongside the core CLI to add commands:
@@ -141,13 +158,15 @@ to turn it off.
141
158
 
142
159
  ## Environment Variables
143
160
 
144
- | Variable | Description |
145
- | ----------------------- | ------------------------------------------------ |
146
- | `FLUID_TOKEN` | API token (alternative to `fluid login`) |
147
- | `FLUID_LOGIN_CODE` | Emailed code read by `fluid login --code` |
148
- | `FLUID_API_BASE` | API base URL (default: `https://api.fluid.app`) |
149
- | `FLUID_CONFIG_DIR` | Override config directory (default: `~/.fluid/`) |
150
- | `FLUID_NO_UPDATE_CHECK` | Turn off the daily update notice |
161
+ | Variable | Description |
162
+ | ----------------------- | ----------------------------------------------------------- |
163
+ | `FLUID_TOKEN` | API token (alternative to `fluid login`) |
164
+ | `FLUID_LOGIN_CODE` | Emailed code read by `fluid login --code` |
165
+ | `FLUID_API_BASE` | API base URL (default: `https://api.fluid.app`) |
166
+ | `FLUID_CONFIG_DIR` | Override config directory (default: `~/.fluid/`) |
167
+ | `FLUID_IDENTITY_URL` | Identity service origin (default: follows `FLUID_API_BASE`) |
168
+ | `FLUID_NO_BROWSER` | Print the sign-in URL without opening a browser |
169
+ | `FLUID_NO_UPDATE_CHECK` | Turn off the daily update notice |
151
170
 
152
171
  ## Development
153
172
 
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { F as walkCommands, M as rootCommand, N as visibleOptions, P as visibleSubcommands, _ as validateToken, a as readConfig, d as FLUID_API_ERROR, f as confirmMfa, g as switchCompany, h as sendMfa, j as filterCatalog, l as getConfigDir, m as getFluidApiBase, n as getAuthToken, o as updateConfig, p as fetchUserCompanies, s as writeConfig, t as getActiveProfile } from "../token-DnFYT9pe.mjs";
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
4
  import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
5
5
  import { fileURLToPath, pathToFileURL } from "node:url";
@@ -9,8 +9,8 @@ import chalk from "chalk";
9
9
  import prompts from "prompts";
10
10
  import ora from "ora";
11
11
  import { createHash, randomBytes } from "node:crypto";
12
- import { dirname, join, sep } from "node:path";
13
12
  import { spawn } from "node:child_process";
13
+ import { dirname, join, sep } from "node:path";
14
14
  //#region src/commands/commands.ts
15
15
  /**
16
16
  * fluid commands — list every installed command, or print the catalog as
@@ -245,6 +245,52 @@ const completeCommand = new Command("__complete").description("Print completions
245
245
  process.stdout.write(formatCandidates(completeWords(rootCommand(command), typed), opts.shell));
246
246
  });
247
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
248
294
  //#region src/auth/pending-login.ts
249
295
  /**
250
296
  * Email sign-ins started with `fluid login --send-code` and not finished yet.
@@ -342,6 +388,141 @@ function createFluidProfile({ name, token, companyName, baseUrl, storedAt }) {
342
388
  baseUrl
343
389
  };
344
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
+ }
345
526
  //#endregion
346
527
  //#region src/commands/login.ts
347
528
  /**
@@ -352,6 +533,11 @@ function createFluidProfile({ name, token, companyName, baseUrl, storedAt }) {
352
533
  * the server's sign-in id (auth/pending-login.ts), then `--code` redeems
353
534
  * it. `--send-code` requires `--shop`, which ties the code to one company:
354
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.
355
541
  */
356
542
  const defaultLoginDeps = {
357
543
  api: {
@@ -449,8 +635,9 @@ function profileExists(profileName, codeUsed) {
449
635
  message: `Profile "${profileName}" already exists. Pass --yes to replace it` + (codeUsed ? "; the code is used, so send a new one first." : ".")
450
636
  };
451
637
  }
452
- function storeProfile(profileName, token, companyName, baseUrl = getFluidApiBase()) {
453
- updateConfig((config) => ({
638
+ async function storeProfile(deps, profileName, token, companyName, baseUrl = getFluidApiBase()) {
639
+ const before = readConfig();
640
+ const after = updateConfig((config) => ({
454
641
  ...config,
455
642
  activeProfile: profileName,
456
643
  profiles: {
@@ -463,6 +650,7 @@ function storeProfile(profileName, token, companyName, baseUrl = getFluidApiBase
463
650
  })
464
651
  }
465
652
  }));
653
+ for (const problem of await endUnusedSessions(before, after)) deps.err(chalk.yellow(problem));
466
654
  }
467
655
  function loggedIn(ui, deps, profileName, company) {
468
656
  ui.result({
@@ -477,6 +665,37 @@ function cancelled(deps) {
477
665
  deps.log(chalk.yellow("Login cancelled — existing profile not overwritten."));
478
666
  return 0;
479
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);
696
+ }
697
+ }
698
+ const LINK_HINT = "If the email has a sign-in link instead of a code, paste the link here.";
480
699
  async function loginWithToken(token, opts, interactive, ui, deps) {
481
700
  const spinner = ui.spinner("Validating token...");
482
701
  const result = await deps.api.validateToken(token);
@@ -489,7 +708,7 @@ async function loginWithToken(token, opts, interactive, ui, deps) {
489
708
  }, deps);
490
709
  if (decision === "refuse") return ui.fail(profileExists(name, false));
491
710
  if (decision === "keep") return cancelled(deps);
492
- storeProfile(name, token, result.value.name);
711
+ await storeProfile(deps, name, token, result.value.name);
493
712
  return loggedIn(ui, deps, name, { name: result.value.name });
494
713
  }
495
714
  async function loginWithEmail(opts, ui, deps) {
@@ -509,6 +728,7 @@ async function loginWithEmail(opts, ui, deps) {
509
728
  const sendResult = await deps.api.sendMfa(email, ...shopArgs(opts.shop));
510
729
  if (!sendResult.success) return ui.fail(sendResult.error, sendSpinner);
511
730
  sendSpinner.succeed(`Verification code sent — check your email (${expiryNote(sendResult.value.expiresAt)})`);
731
+ if (!ui.json) deps.log(chalk.dim(LINK_HINT));
512
732
  const MAX_CODE_ATTEMPTS = 3;
513
733
  let confirmResult;
514
734
  for (let attempt = 1; attempt <= MAX_CODE_ATTEMPTS; attempt++) {
@@ -521,6 +741,8 @@ async function loginWithEmail(opts, ui, deps) {
521
741
  deps.log(chalk.red("No code provided. Aborting."));
522
742
  return 1;
523
743
  }
744
+ const linkToken = identityLinkToken(code);
745
+ if (linkToken) return identityResult(await loginWithIdentityLink(linkToken, identityContext(opts, true, ui, deps)), ui, deps);
524
746
  if (!/^\d{6}$/.test(code)) {
525
747
  deps.log(chalk.red("Code must be exactly 6 digits."));
526
748
  if (attempt < MAX_CODE_ATTEMPTS) continue;
@@ -540,6 +762,7 @@ async function loginWithEmail(opts, ui, deps) {
540
762
  return ui.fail(confirmResult.error, confirmSpinner);
541
763
  }
542
764
  if (!confirmResult?.success) return 0;
765
+ if (signInPathFor(confirmResult.value) === "identity") return identityResult(await loginWithIdentity(identityContext(opts, true, ui, deps)), ui, deps);
543
766
  const { companies } = confirmResult.value;
544
767
  if (companies.length === 0) {
545
768
  deps.log(chalk.red("No companies found for this account."));
@@ -584,7 +807,7 @@ async function loginWithEmail(opts, ui, deps) {
584
807
  yes: Boolean(opts.yes),
585
808
  interactive: true
586
809
  }, deps) !== "replace") return cancelled(deps);
587
- storeProfile(name, selected.jwt, selected.name);
810
+ await storeProfile(deps, name, selected.jwt, selected.name);
588
811
  return loggedIn(ui, deps, name, { name: selected.name });
589
812
  }
590
813
  function expiryNote(expiresAtIso) {
@@ -632,7 +855,7 @@ async function sendCodeStep(opts, ui, deps) {
632
855
  });
633
856
  if (!ui.json) {
634
857
  deps.log(`Finish with: ${finishCommand(email, shop)}`);
635
- deps.log(chalk.dim("with the code in FLUID_LOGIN_CODE, or add - after --code to read it from stdin. With no terminal, add --yes to replace a profile with the company's name, or --name <profile>."));
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>."));
636
859
  }
637
860
  return 0;
638
861
  }
@@ -658,7 +881,7 @@ function finishError(error, shop) {
658
881
  };
659
882
  if (error.code === "UUID_NOT_FOUND") return {
660
883
  code: error.code,
661
- 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. Check them and run --send-code again.`
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.`
662
885
  };
663
886
  return error;
664
887
  }
@@ -695,7 +918,8 @@ async function finishStep(opts, interactive, ui, deps) {
695
918
  code: "NO_CODE",
696
919
  message: "No code given. Put it in FLUID_LOGIN_CODE, pass --code - to read it from stdin, or pass it to --code."
697
920
  });
698
- if (!/^\d{6}$/.test(code)) return ui.fail({
921
+ const linkToken = identityLinkToken(code);
922
+ if (!linkToken && !/^\d{6}$/.test(code)) return ui.fail({
699
923
  code: "INVALID_CODE_FORMAT",
700
924
  message: "The code must be exactly 6 digits."
701
925
  });
@@ -704,6 +928,10 @@ async function finishStep(opts, interactive, ui, deps) {
704
928
  interactive
705
929
  };
706
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);
707
935
  const spinner = ui.spinner("Verifying code...");
708
936
  const confirmed = await deps.api.confirmMfa(record.uuid, code, {
709
937
  fluidShop: shop,
@@ -719,6 +947,7 @@ async function finishStep(opts, interactive, ui, deps) {
719
947
  }
720
948
  spinner.succeed("Verified");
721
949
  deps.pending.remove(email);
950
+ if (signInPathFor(confirmed.value) === "identity") return identityResult(await loginWithIdentity(identityContext(opts, interactive, ui, deps, record.baseUrl)), ui, deps);
722
951
  const { companies } = confirmed.value;
723
952
  const selected = findByShop(companies, shop);
724
953
  if (!selected) {
@@ -737,7 +966,7 @@ async function finishStep(opts, interactive, ui, deps) {
737
966
  const decision = await overwriteDecision(name, overwrite, deps);
738
967
  if (decision === "refuse") return ui.fail(profileExists(name, true));
739
968
  if (decision === "keep") return cancelled(deps);
740
- storeProfile(name, selected.jwt, selected.name, record.baseUrl);
969
+ await storeProfile(deps, name, selected.jwt, selected.name, record.baseUrl);
741
970
  return loggedIn(ui, deps, name, {
742
971
  id: selected.id,
743
972
  name: selected.name,
@@ -791,15 +1020,22 @@ const loginCommand = buildLoginCommand();
791
1020
  //#region src/commands/logout.ts
792
1021
  /**
793
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.)
794
1028
  */
795
- 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) => {
796
1030
  const config = readConfig();
797
1031
  if (opts.all) {
798
- writeConfig({
1032
+ const after = {
799
1033
  ...config,
800
1034
  activeProfile: null,
801
1035
  profiles: {}
802
- });
1036
+ };
1037
+ writeConfig(after);
1038
+ for (const problem of await endUnusedSessions(config, after)) console.log(chalk.yellow(problem));
803
1039
  console.log(chalk.green("All profiles removed."));
804
1040
  return;
805
1041
  }
@@ -810,11 +1046,13 @@ const logoutCommand = new Command("logout").description("Remove stored authentic
810
1046
  const profileName = config.activeProfile;
811
1047
  const { [profileName]: _, ...remainingProfiles } = config.profiles;
812
1048
  const nextActive = Object.keys(remainingProfiles)[0] ?? null;
813
- writeConfig({
1049
+ const after = {
814
1050
  ...config,
815
1051
  activeProfile: nextActive,
816
1052
  profiles: remainingProfiles
817
- });
1053
+ };
1054
+ writeConfig(after);
1055
+ for (const problem of await endUnusedSessions(config, after)) console.log(chalk.yellow(problem));
818
1056
  console.log(chalk.green(`Logged out of profile ${chalk.bold(profileName)}.`));
819
1057
  if (nextActive) console.log(chalk.dim(`Switched to profile ${nextActive}.`));
820
1058
  });
@@ -822,7 +1060,31 @@ const logoutCommand = new Command("logout").description("Remove stored authentic
822
1060
  //#region src/commands/whoami.ts
823
1061
  /**
824
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.
825
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
+ }
826
1088
  const whoamiCommand = new Command("whoami").description("Show the current authenticated profile").action(async () => {
827
1089
  const profile = getActiveProfile();
828
1090
  if (!profile) {
@@ -830,8 +1092,12 @@ const whoamiCommand = new Command("whoami").description("Show the current authen
830
1092
  process.exitCode = 1;
831
1093
  return;
832
1094
  }
1095
+ if (isIdentityProfile(profile)) {
1096
+ await whoamiIdentity(profile);
1097
+ return;
1098
+ }
833
1099
  const spinner = ora("Verifying token...").start();
834
- const result = await validateToken(profile.token);
1100
+ const result = await validateToken(profile.token ?? "");
835
1101
  if (!result.success) {
836
1102
  spinner.fail(chalk.red("Token is no longer valid."));
837
1103
  console.log(chalk.dim(`Profile: ${profile.name}`));
@@ -848,6 +1114,10 @@ const whoamiCommand = new Command("whoami").description("Show the current authen
848
1114
  //#region src/commands/switch.ts
849
1115
  /**
850
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.
851
1121
  */
852
1122
  async function localSwitch(profileArg) {
853
1123
  const config = readConfig();
@@ -928,6 +1198,43 @@ async function performSwitch(token, company, baseUrl) {
928
1198
  }));
929
1199
  spinner.succeed(chalk.green(`Switched to ${chalk.bold(companyName)} (profile: ${chalk.bold(companyName)})`));
930
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
+ }
931
1238
  const switchCommand = new Command("switch").description("Switch between companies").argument("[profile]", "Company or profile name to switch to").action(async (profileArg) => {
932
1239
  const activeProfile = getActiveProfile();
933
1240
  if (!activeProfile) {
@@ -935,10 +1242,18 @@ const switchCommand = new Command("switch").description("Switch between companie
935
1242
  process.exitCode = 1;
936
1243
  return;
937
1244
  }
938
- const token = activeProfile.token;
939
1245
  const activeCompanyName = activeProfile.companyName;
940
1246
  const activeBaseUrl = activeProfile.baseUrl ?? getFluidApiBase();
1247
+ const identity = isIdentityProfile(activeProfile) ? activeProfile : null;
941
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
+ }
942
1257
  const result = await fetchUserCompanies(token, activeBaseUrl);
943
1258
  if (!result.success) {
944
1259
  if (result.error.code === FLUID_API_ERROR.INVALID_TOKEN.code) {
@@ -961,7 +1276,7 @@ const switchCommand = new Command("switch").description("Switch between companie
961
1276
  if (profileArg) {
962
1277
  const match = companies.find((c) => c.name.toLowerCase() === profileArg.toLowerCase());
963
1278
  if (match) {
964
- await performSwitch(token, match, activeBaseUrl);
1279
+ await (identity ? performIdentitySwitch(identity, match, activeBaseUrl) : performSwitch(token, match, activeBaseUrl));
965
1280
  return;
966
1281
  }
967
1282
  if (readConfig().profiles[profileArg]) {
@@ -981,9 +1296,32 @@ const switchCommand = new Command("switch").description("Switch between companie
981
1296
  console.log(chalk.dim("Cancelled."));
982
1297
  return;
983
1298
  }
984
- await performSwitch(token, selected, activeBaseUrl);
1299
+ await (identity ? performIdentitySwitch(identity, selected, activeBaseUrl) : performSwitch(token, selected, activeBaseUrl));
985
1300
  });
986
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
987
1325
  //#region src/plugins/discovery.ts
988
1326
  /**
989
1327
  * Auto-discover @fluid-app CLI plugins.
@@ -1493,6 +1831,21 @@ program.addCommand(switchCommand);
1493
1831
  program.addCommand(commandsCommand);
1494
1832
  program.addCommand(completionCommand);
1495
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
+ });
1496
1849
  startUpdateCheck({
1497
1850
  currentVersion: version,
1498
1851
  configDir: getConfigDir(),
@@ -1503,7 +1856,7 @@ startUpdateCheck({
1503
1856
  versions: process.versions
1504
1857
  });
1505
1858
  await loadPlugins(program, packageRoot);
1506
- program.parse(process.argv, { from: "node" });
1859
+ await program.parseAsync(process.argv, { from: "node" });
1507
1860
  //#endregion
1508
1861
  export {};
1509
1862