@fluid-app/fluid-cli 0.1.805 → 0.1.807

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.
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { A as confirmMfa, B as validateToken, E as resolveCredentialSource, F as pollAgentAccess, I as redeemIdentityLink, L as sendMfa, M as fetchUserCompanies, N as getFluidApiBase, O as FLUID_API_ERROR, P as isInsecureRemoteBase, R as signup, T as readFdToken, _ as describeCredentialSource, b as getActiveProfile, c as inputsModeActive, et as filterCatalog, g as adoptIdentityProfile, it as walkCommands, j as fetchCompanyShops, l as registerInputsHook, nt as visibleOptions, rt as visibleSubcommands, s as exitOnInputsError, tt as rootCommand, u as createInputsReader, v as findIdentityFallbackCandidates, x as getAuthToken, y as findIdentityFallbackProfile, z as switchCompany } from "../hook-DiCB7h_B.mjs";
3
- import { D as serializeAdoptMarker, E as parseAdoptMarker, F as isStrictConfig, H as isIdentityProfile, I as configLockTimings, L as withConfigLock, M as readStoredConfig, N as updateConfig, O as tradeLegacyToken, P as writeConfig, R as getConfigDir, T as isStalePendingAdopt, V as isClientProfile, _ as clientAccessToken, a as identityToken, c as primeIdentityProfile, d as sessionFacts, f as signInWithBrowser, i as describeIdentityError, j as readConfig, l as profileAccessToken, m as KeyringRefusedError, n as createAdoptionSession, p as signOutIdentity, r as deleteStoredAdoption, t as endUnusedSessions, u as revokeStoredAdoption, w as resolveIdentityUrl, x as primeClientProfile } from "../profiles-Cuz5-llH.mjs";
2
+ import { A as confirmMfa, B as validateToken, E as resolveCredentialSource, F as pollAgentAccess, I as redeemIdentityLink, L as sendMfa, M as fetchUserCompanies, N as getFluidApiBase, O as FLUID_API_ERROR, P as isInsecureRemoteBase, R as signup, T as readFdToken, _ as describeCredentialSource, b as getActiveProfile, c as inputsModeActive, et as filterCatalog, g as adoptIdentityProfile, it as walkCommands, j as fetchCompanyShops, l as registerInputsHook, nt as visibleOptions, rt as visibleSubcommands, s as exitOnInputsError, tt as rootCommand, u as createInputsReader, v as findIdentityFallbackCandidates, x as getAuthToken, y as findIdentityFallbackProfile, z as switchCompany } from "../hook-D3gcCs1d.mjs";
3
+ import { A as createSwitchAdoptRequest, B as withConfigLock, C as primeClientProfile, D as isStalePendingAdopt, E as resolveIdentityUrl, F as readStoredConfig, G as isIdentityProfile, I as updateConfig, L as writeConfig, O as parseAdoptMarker, P as readConfig, R as isStrictConfig, V as getConfigDir, W as isClientProfile, a as describeIdentityError, d as revokeStoredAdoption, f as sessionFacts, g as ADOPT_CLEANUP_TIMEOUT_MS, h as KeyringRefusedError, i as deleteStoredAdoption, j as tradeLegacyToken, k as serializeAdoptMarker, l as primeIdentityProfile, m as signOutIdentity, n as adoptionStorageAvailable, o as identityToken, p as signInWithBrowser, r as createAdoptionSession, t as endUnusedSessions, u as profileAccessToken, y as clientAccessToken, z as configLockTimings } from "../profiles-BxQg0jB_.mjs";
4
4
  import { createRequire } from "node:module";
5
5
  import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
6
6
  import { fileURLToPath, pathToFileURL } from "node:url";
@@ -1796,7 +1796,7 @@ const defaultSignupDeps = {
1796
1796
  isInteractive: () => Boolean(process.stdin.isTTY),
1797
1797
  agent: {
1798
1798
  poll: pollAgentAccess,
1799
- saveProfile: async (name, input, options) => (await import("../client-aqEXGMl_.mjs")).saveClientProfile(name, input, options),
1799
+ saveProfile: async (name, input, options) => (await import("../client-Bg2zc4QQ.mjs")).saveClientProfile(name, input, options),
1800
1800
  strictConfig: isStrictConfig,
1801
1801
  stashRecovery: writeRecoveryFile,
1802
1802
  stderrIsTty: () => Boolean(process.stderr.isTTY),
@@ -2355,6 +2355,218 @@ const whoamiCommand = new Command("whoami").description("Show the current authen
2355
2355
  console.log(` Stored: ${chalk.dim(profile.storedAt)}`);
2356
2356
  });
2357
2357
  //#endregion
2358
+ //#region src/auth/identity/adopt-pending.ts
2359
+ const ADOPT_DEADLINE_MS$1 = 15e3;
2360
+ const ADOPT_RECOVERY_TIMEOUT_MS = 4e3;
2361
+ const ADOPT_RECOVERY_MAX_ATTEMPTS = 5;
2362
+ const PREFIX = "adopt-pending-";
2363
+ const SUFFIX = ".json";
2364
+ function markerFiles() {
2365
+ try {
2366
+ return readdirSync(getConfigDir()).filter((name) => name.startsWith(PREFIX) && name.endsWith(SUFFIX));
2367
+ } catch {
2368
+ return [];
2369
+ }
2370
+ }
2371
+ function remove(name) {
2372
+ try {
2373
+ unlinkSync(join(getConfigDir(), name));
2374
+ } catch {}
2375
+ }
2376
+ function store(name, marker) {
2377
+ try {
2378
+ const dir = getConfigDir();
2379
+ const tmp = join(dir, `.adopt-pending-${randomBytes(6).toString("hex")}.tmp`);
2380
+ writeFileSync(tmp, serializeAdoptMarker(marker), { mode: 384 });
2381
+ renameSync(tmp, join(dir, name));
2382
+ } catch {}
2383
+ }
2384
+ /** Writes the marker for one attempt, atomically; throws when it cannot. */
2385
+ function writePendingAdopt(storageKey, identityUrl) {
2386
+ const dir = getConfigDir();
2387
+ if (!existsSync(dir)) mkdirSync(dir, {
2388
+ recursive: true,
2389
+ mode: 448
2390
+ });
2391
+ const tmp = join(dir, `.adopt-pending-${randomBytes(6).toString("hex")}.tmp`);
2392
+ writeFileSync(tmp, serializeAdoptMarker({
2393
+ storageKey,
2394
+ identityUrl,
2395
+ startedAt: Date.now()
2396
+ }), { mode: 384 });
2397
+ renameSync(tmp, join(dir, `${PREFIX}${storageKey}${SUFFIX}`));
2398
+ }
2399
+ /** Removes the marker for `storageKey`; never throws. */
2400
+ function clearPendingAdopt(storageKey) {
2401
+ remove(`${PREFIX}${storageKey}${SUFFIX}`);
2402
+ }
2403
+ /**
2404
+ * Settles every stale marker left by an attempt that died: one whose key no
2405
+ * profile names has its stored session revoked and deleted, then the marker
2406
+ * goes. A marker still inside the grace belongs to a live attempt and stays.
2407
+ * Never throws; logs outcomes without any token. With `quiet`, a revoked or
2408
+ * empty outcome is not logged; a failure still is.
2409
+ */
2410
+ async function recoverPendingAdopts(options = {}) {
2411
+ const log = options.log ?? ((line) => process.stderr.write(`${line}\n`));
2412
+ const files = markerFiles();
2413
+ if (files.length === 0) return;
2414
+ const budgetEndsAt = Date.now() + ADOPT_RECOVERY_TIMEOUT_MS;
2415
+ try {
2416
+ const committed = new Set(Object.values(readStoredConfig().profiles).flatMap((profile) => profile.auth?.mode === "identity" ? [profile.auth.storageKey] : []));
2417
+ for (const name of files) {
2418
+ let marker;
2419
+ try {
2420
+ marker = parseAdoptMarker(readFileSync(join(getConfigDir(), name), "utf8"));
2421
+ } catch {
2422
+ continue;
2423
+ }
2424
+ if (!marker) {
2425
+ remove(name);
2426
+ continue;
2427
+ }
2428
+ if (!isStalePendingAdopt(marker, Date.now())) continue;
2429
+ if (committed.has(marker.storageKey) || !marker.identityUrl) {
2430
+ remove(name);
2431
+ continue;
2432
+ }
2433
+ const remainingMs = budgetEndsAt - Date.now();
2434
+ if (remainingMs < 500) break;
2435
+ const auth = {
2436
+ mode: "identity",
2437
+ identityUrl: marker.identityUrl,
2438
+ storageKey: marker.storageKey
2439
+ };
2440
+ let outcome = "unconfirmed";
2441
+ try {
2442
+ outcome = await revokeStoredAdoption(auth, remainingMs);
2443
+ } catch {}
2444
+ if (outcome !== "unconfirmed") {
2445
+ remove(name);
2446
+ if (!options.quiet) log(`adopt recovery: ${outcome}`);
2447
+ continue;
2448
+ }
2449
+ const attempts = (marker.attemptCount ?? 0) + 1;
2450
+ if (attempts >= ADOPT_RECOVERY_MAX_ATTEMPTS) if (await deleteStoredAdoption(auth, Math.max(budgetEndsAt - Date.now(), 500)).then(() => true, () => false)) {
2451
+ remove(name);
2452
+ log("adopt recovery: gave up; the stored credential was deleted");
2453
+ } else {
2454
+ store(name, {
2455
+ ...marker,
2456
+ attemptCount: attempts
2457
+ });
2458
+ log("adopt recovery: could not delete the stored credential");
2459
+ }
2460
+ else {
2461
+ store(name, {
2462
+ ...marker,
2463
+ attemptCount: attempts
2464
+ });
2465
+ log("adopt recovery: not confirmed, will retry at the next start");
2466
+ }
2467
+ }
2468
+ } catch {
2469
+ log("adopt recovery: skipped");
2470
+ }
2471
+ }
2472
+ //#endregion
2473
+ //#region src/auth/identity/switch-adopt.ts
2474
+ function identityUrlFor(apiBase) {
2475
+ try {
2476
+ return resolveIdentityUrl(apiBase);
2477
+ } catch {
2478
+ return null;
2479
+ }
2480
+ }
2481
+ /**
2482
+ * Prepares an adopt request for a legacy switch made with `profile`'s token,
2483
+ * or null when that profile is not one the CLI would adopt (no token, owned
2484
+ * by Mist, no identity service for the API base) or the credential store
2485
+ * cannot keep a session.
2486
+ */
2487
+ async function beginSwitchAdoption(profile, apiBase) {
2488
+ if (!profile?.token || profile.mistOwned === true || profile.identityClient !== void 0) return null;
2489
+ const identityUrl = identityUrlFor(apiBase);
2490
+ if (!identityUrl) return null;
2491
+ try {
2492
+ if (!await adoptionStorageAvailable()) return null;
2493
+ const deadline = new AbortController();
2494
+ const held = createAdoptionSession(identityUrl, deadline.signal);
2495
+ const request = await createSwitchAdoptRequest(held.session);
2496
+ const legacyToken = profile.token;
2497
+ return {
2498
+ codeChallenge: request.codeChallenge,
2499
+ complete: (answer, companyName) => land(request, held, deadline, identityUrl, legacyToken, apiBase, answer, companyName)
2500
+ };
2501
+ } catch {
2502
+ return null;
2503
+ }
2504
+ }
2505
+ async function land(request, held, deadline, identityUrl, legacyToken, apiBase, answer, companyName) {
2506
+ const storageKey = held.auth.storageKey;
2507
+ try {
2508
+ writePendingAdopt(storageKey, identityUrl);
2509
+ } catch {
2510
+ return null;
2511
+ }
2512
+ const timer = setTimeout(() => {
2513
+ deadline.abort();
2514
+ }, ADOPT_DEADLINE_MS$1);
2515
+ try {
2516
+ const result = await request.redeem({
2517
+ code: answer.adoptCode,
2518
+ apiBase,
2519
+ legacyToken,
2520
+ targetCompanyId: answer.companyId,
2521
+ fetch: (input, init) => fetch(input, {
2522
+ ...init,
2523
+ signal: init?.signal ? AbortSignal.any([init.signal, deadline.signal]) : deadline.signal
2524
+ })
2525
+ });
2526
+ if (result.outcome !== "adopted") {
2527
+ clearPendingAdopt(storageKey);
2528
+ return null;
2529
+ }
2530
+ let persistAttempted = false;
2531
+ const revoke = async () => {
2532
+ held.beginCleanup(ADOPT_CLEANUP_TIMEOUT_MS);
2533
+ if (!await result.discard().then(() => true, () => false)) return;
2534
+ if (persistAttempted && !held.persistRefused ? await held.unpersist().then(() => true, () => false) : true) clearPendingAdopt(storageKey);
2535
+ };
2536
+ try {
2537
+ if (deadline.signal.aborted) throw new Error("adopt deadline passed");
2538
+ clearTimeout(timer);
2539
+ writePendingAdopt(storageKey, identityUrl);
2540
+ persistAttempted = true;
2541
+ await held.persist();
2542
+ const before = readConfig();
2543
+ const after = updateConfig((config) => ({
2544
+ ...config,
2545
+ activeProfile: companyName,
2546
+ profiles: {
2547
+ ...config.profiles,
2548
+ [companyName]: createIdentityProfile({
2549
+ name: companyName,
2550
+ companyName,
2551
+ baseUrl: apiBase,
2552
+ auth: held.auth
2553
+ })
2554
+ }
2555
+ }));
2556
+ clearPendingAdopt(storageKey);
2557
+ return { problems: await endUnusedSessions(before, after) };
2558
+ } catch {
2559
+ await revoke();
2560
+ return null;
2561
+ }
2562
+ } catch {
2563
+ if (deadline.signal.aborted) clearPendingAdopt(storageKey);
2564
+ return null;
2565
+ } finally {
2566
+ clearTimeout(timer);
2567
+ }
2568
+ }
2569
+ //#endregion
2358
2570
  //#region src/commands/switch.ts
2359
2571
  /**
2360
2572
  * fluid switch — switch between companies (fetched from API, with local fallback)
@@ -2416,7 +2628,22 @@ async function selectCompany(companies, activeCompanyName) {
2416
2628
  }
2417
2629
  async function performSwitch(token, company, baseUrl) {
2418
2630
  const spinner = ora(`Switching to ${chalk.bold(company.name)}...`).start();
2419
- const result = await switchCompany(token, company.id, baseUrl);
2631
+ const adoption = await beginSwitchAdoption(getActiveProfile(), baseUrl ?? getFluidApiBase());
2632
+ let result = await switchCompany(token, company.id, baseUrl, adoption?.codeChallenge);
2633
+ if (result.success && "adoptCode" in result.value) {
2634
+ if (result.value.companyId !== company.id) {
2635
+ spinner.fail(chalk.red("Unexpected response shape from /switch"));
2636
+ process.exitCode = 1;
2637
+ return;
2638
+ }
2639
+ const landed = adoption ? await adoption.complete(result.value, company.name) : null;
2640
+ if (landed) {
2641
+ spinner.succeed(chalk.green(`Switched to ${chalk.bold(company.name)} (profile: ${chalk.bold(company.name)})`));
2642
+ for (const problem of landed.problems) console.log(chalk.yellow(problem));
2643
+ return;
2644
+ }
2645
+ result = await switchCompany(token, company.id, baseUrl);
2646
+ }
2420
2647
  if (!result.success) {
2421
2648
  if (result.error.code === FLUID_API_ERROR.INVALID_TOKEN.code) spinner.fail(chalk.red("Your session has expired. Please run `fluid login` to re-authenticate."));
2422
2649
  else {
@@ -2426,6 +2653,11 @@ async function performSwitch(token, company, baseUrl) {
2426
2653
  process.exitCode = 1;
2427
2654
  return;
2428
2655
  }
2656
+ if ("adoptCode" in result.value) {
2657
+ spinner.fail(chalk.red("Unexpected response shape from /switch"));
2658
+ process.exitCode = 1;
2659
+ return;
2660
+ }
2429
2661
  const { companyName, jwt } = result.value;
2430
2662
  updateConfig((config) => ({
2431
2663
  ...config,
@@ -2754,121 +2986,6 @@ const versionCommand = new Command("version").description("Show the CLI's and pl
2754
2986
  process.stdout.write(opts.json ? JSON.stringify({ packages }, null, 2) + "\n" : formatVersionReport(packages) + "\n");
2755
2987
  });
2756
2988
  //#endregion
2757
- //#region src/auth/identity/adopt-pending.ts
2758
- const ADOPT_CLEANUP_TIMEOUT_MS = 8e3;
2759
- const ADOPT_RECOVERY_TIMEOUT_MS = 4e3;
2760
- const ADOPT_RECOVERY_MAX_ATTEMPTS = 5;
2761
- const PREFIX = "adopt-pending-";
2762
- const SUFFIX = ".json";
2763
- function markerFiles() {
2764
- try {
2765
- return readdirSync(getConfigDir()).filter((name) => name.startsWith(PREFIX) && name.endsWith(SUFFIX));
2766
- } catch {
2767
- return [];
2768
- }
2769
- }
2770
- function remove(name) {
2771
- try {
2772
- unlinkSync(join(getConfigDir(), name));
2773
- } catch {}
2774
- }
2775
- function store(name, marker) {
2776
- try {
2777
- const dir = getConfigDir();
2778
- const tmp = join(dir, `.adopt-pending-${randomBytes(6).toString("hex")}.tmp`);
2779
- writeFileSync(tmp, serializeAdoptMarker(marker), { mode: 384 });
2780
- renameSync(tmp, join(dir, name));
2781
- } catch {}
2782
- }
2783
- /** Writes the marker for one attempt, atomically; throws when it cannot. */
2784
- function writePendingAdopt(storageKey, identityUrl) {
2785
- const dir = getConfigDir();
2786
- if (!existsSync(dir)) mkdirSync(dir, {
2787
- recursive: true,
2788
- mode: 448
2789
- });
2790
- const tmp = join(dir, `.adopt-pending-${randomBytes(6).toString("hex")}.tmp`);
2791
- writeFileSync(tmp, serializeAdoptMarker({
2792
- storageKey,
2793
- identityUrl,
2794
- startedAt: Date.now()
2795
- }), { mode: 384 });
2796
- renameSync(tmp, join(dir, `${PREFIX}${storageKey}${SUFFIX}`));
2797
- }
2798
- /** Removes the marker for `storageKey`; never throws. */
2799
- function clearPendingAdopt(storageKey) {
2800
- remove(`${PREFIX}${storageKey}${SUFFIX}`);
2801
- }
2802
- /**
2803
- * Settles every stale marker left by an attempt that died: one whose key no
2804
- * profile names has its stored session revoked and deleted, then the marker
2805
- * goes. A marker still inside the grace belongs to a live attempt and stays.
2806
- * Never throws; logs outcomes without any token. With `quiet`, a revoked or
2807
- * empty outcome is not logged; a failure still is.
2808
- */
2809
- async function recoverPendingAdopts(options = {}) {
2810
- const log = options.log ?? ((line) => process.stderr.write(`${line}\n`));
2811
- const files = markerFiles();
2812
- if (files.length === 0) return;
2813
- const budgetEndsAt = Date.now() + ADOPT_RECOVERY_TIMEOUT_MS;
2814
- try {
2815
- const committed = new Set(Object.values(readStoredConfig().profiles).flatMap((profile) => profile.auth?.mode === "identity" ? [profile.auth.storageKey] : []));
2816
- for (const name of files) {
2817
- let marker;
2818
- try {
2819
- marker = parseAdoptMarker(readFileSync(join(getConfigDir(), name), "utf8"));
2820
- } catch {
2821
- continue;
2822
- }
2823
- if (!marker) {
2824
- remove(name);
2825
- continue;
2826
- }
2827
- if (!isStalePendingAdopt(marker, Date.now())) continue;
2828
- if (committed.has(marker.storageKey) || !marker.identityUrl) {
2829
- remove(name);
2830
- continue;
2831
- }
2832
- const remainingMs = budgetEndsAt - Date.now();
2833
- if (remainingMs < 500) break;
2834
- const auth = {
2835
- mode: "identity",
2836
- identityUrl: marker.identityUrl,
2837
- storageKey: marker.storageKey
2838
- };
2839
- let outcome = "unconfirmed";
2840
- try {
2841
- outcome = await revokeStoredAdoption(auth, remainingMs);
2842
- } catch {}
2843
- if (outcome !== "unconfirmed") {
2844
- remove(name);
2845
- if (!options.quiet) log(`adopt recovery: ${outcome}`);
2846
- continue;
2847
- }
2848
- const attempts = (marker.attemptCount ?? 0) + 1;
2849
- if (attempts >= ADOPT_RECOVERY_MAX_ATTEMPTS) if (await deleteStoredAdoption(auth, Math.max(budgetEndsAt - Date.now(), 500)).then(() => true, () => false)) {
2850
- remove(name);
2851
- log("adopt recovery: gave up; the stored credential was deleted");
2852
- } else {
2853
- store(name, {
2854
- ...marker,
2855
- attemptCount: attempts
2856
- });
2857
- log("adopt recovery: could not delete the stored credential");
2858
- }
2859
- else {
2860
- store(name, {
2861
- ...marker,
2862
- attemptCount: attempts
2863
- });
2864
- log("adopt recovery: not confirmed, will retry at the next start");
2865
- }
2866
- }
2867
- } catch {
2868
- log("adopt recovery: skipped");
2869
- }
2870
- }
2871
- //#endregion
2872
2989
  //#region src/auth/identity/adopt-legacy.ts
2873
2990
  const ADOPT_BACKOFF_MS = 1440 * 60 * 1e3;
2874
2991
  const ADOPT_UNAVAILABLE_BACKOFF_MS = 900 * 1e3;