@fluid-app/fluid-cli 0.1.802 → 0.1.804

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-DjcOPPI_.mjs";
3
- import { A as isStrictConfig, C as tradeLegacyToken, D as readStoredConfig, E as readConfig, I as isClientProfile, L as isIdentityProfile, M as withConfigLock, N as getConfigDir, O as updateConfig, S as resolveIdentityUrl, c as profileAccessToken, d as signOutIdentity, f as KeyringRefusedError, h as clientAccessToken, i as identityToken, j as configLockTimings, k as writeConfig, l as sessionFacts, n as createAdoptionSession, r as describeIdentityError, s as primeIdentityProfile, t as endUnusedSessions, u as signInWithBrowser, y as primeClientProfile } from "../profiles-B6V5IBeX.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-gZNPgx85.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";
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-DeZ9F-Hm.mjs")).saveClientProfile(name, input, options),
1799
+ saveProfile: async (name, input, options) => (await import("../client-aqEXGMl_.mjs")).saveClientProfile(name, input, options),
1800
1800
  strictConfig: isStrictConfig,
1801
1801
  stashRecovery: writeRecoveryFile,
1802
1802
  stderrIsTty: () => Boolean(process.stderr.isTTY),
@@ -2310,7 +2310,7 @@ async function whoamiEnvToken(token, source) {
2310
2310
  spinner.succeed(chalk.green("Authenticated (token from FLUID_TOKEN)"));
2311
2311
  printSource(source);
2312
2312
  console.log(` Company: ${chalk.bold(result.value.name)}`);
2313
- if (token.startsWith(COMPANY_TOKEN_PREFIX)) console.log(chalk.yellow(" A company API token has no user. Where Sites and Sites hosting are on for the company and its role may change themes, it can create and deploy company sites; sharing, featuring and previews need a signed-in admin: run `fluid login`."));
2313
+ if (token.startsWith(COMPANY_TOKEN_PREFIX)) console.log(chalk.yellow(" A company API token has no user. Where Sites and Sites hosting are on for the company and its role may change themes, it can create and deploy company sites; sharing, featuring and deleting need a signed-in admin, and `fluid sites preview-url` needs a member's own login: run `fluid login`."));
2314
2314
  if (!baseUrl) console.log(chalk.yellow(" FLUID_API_BASE is not set. With FLUID_TOKEN and no saved login, the sites commands need it, such as https://api.fluid.app."));
2315
2315
  }
2316
2316
  const whoamiCommand = new Command("whoami").description("Show the current authenticated profile").action(async () => {
@@ -2754,6 +2754,121 @@ const versionCommand = new Command("version").description("Show the CLI's and pl
2754
2754
  process.stdout.write(opts.json ? JSON.stringify({ packages }, null, 2) + "\n" : formatVersionReport(packages) + "\n");
2755
2755
  });
2756
2756
  //#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
2757
2872
  //#region src/auth/identity/adopt-legacy.ts
2758
2873
  const ADOPT_BACKOFF_MS = 1440 * 60 * 1e3;
2759
2874
  const ADOPT_UNAVAILABLE_BACKOFF_MS = 900 * 1e3;
@@ -2863,40 +2978,48 @@ async function trade(profile, signal, expired, remainingMs) {
2863
2978
  return null;
2864
2979
  }
2865
2980
  const held = createAdoptionSession(identityUrl, signal);
2981
+ const storageKey = held.auth.storageKey;
2866
2982
  const result = await tradeLegacyToken({
2867
2983
  legacyToken: profile.token,
2868
2984
  apiBase,
2869
2985
  session: held.session,
2870
2986
  requestTimeoutMs: ADOPT_TIMEOUT_MS,
2871
- fetch: withSignal(signal)
2987
+ fetch: withSignal(signal),
2988
+ beforeRedeem: () => writePendingAdopt(storageKey, identityUrl),
2989
+ beforeDiscard: () => held.beginCleanup(ADOPT_CLEANUP_TIMEOUT_MS)
2872
2990
  });
2873
- if (result.outcome === "not_targeted" || result.outcome === "refused") {
2874
- recordBackoff(profile, ADOPT_BACKOFF_MS);
2991
+ if (result.outcome !== "adopted") {
2992
+ clearPendingAdopt(storageKey);
2993
+ if (result.outcome === "not_targeted" || result.outcome === "refused") recordBackoff(profile, ADOPT_BACKOFF_MS);
2875
2994
  return null;
2876
2995
  }
2877
- if (result.outcome === "unavailable" || expired()) return null;
2878
- const revoke = async () => {
2879
- if (expired()) return;
2880
- await result.discard().catch(() => void 0);
2996
+ let persistAttempted = false;
2997
+ const cleanup = async () => {
2998
+ held.beginCleanup(ADOPT_CLEANUP_TIMEOUT_MS);
2999
+ if (!await result.discard().then(() => true, () => false)) return;
3000
+ if (persistAttempted && !held.persistRefused ? await held.unpersist().then(() => true, () => false) : true) clearPendingAdopt(storageKey);
2881
3001
  };
3002
+ if (expired()) {
3003
+ await cleanup();
3004
+ return null;
3005
+ }
2882
3006
  try {
3007
+ persistAttempted = true;
2883
3008
  await held.persist();
2884
3009
  } catch (error) {
2885
3010
  if (error instanceof KeyringRefusedError) recordBackoff(profile, ADOPT_BACKOFF_MS);
2886
- await revoke();
3011
+ await cleanup();
2887
3012
  return null;
2888
3013
  }
2889
3014
  const lockWaitMs = Math.min(configLockTimings.timeoutMs, remainingMs() - MIN_LOCK_WAIT_MS);
2890
3015
  try {
2891
- if (lockWaitMs <= 0) throw new Error("No time left to rewrite the profile.");
3016
+ if (lockWaitMs <= 0 || expired()) throw new Error("No time left to rewrite the profile.");
2892
3017
  convert(profile, held.auth, lockWaitMs);
2893
3018
  } catch {
2894
- if (!expired()) {
2895
- await held.unpersist().catch(() => void 0);
2896
- await revoke();
2897
- }
3019
+ await cleanup();
2898
3020
  return null;
2899
3021
  }
3022
+ clearPendingAdopt(storageKey);
2900
3023
  recordBackoff(profile, null);
2901
3024
  const { token: _token, gitSyncActor: _actor, ...rest } = profile;
2902
3025
  return {
@@ -2922,7 +3045,9 @@ async function trade(profile, signal, expired, remainingMs) {
2922
3045
  */
2923
3046
  async function primeCommandCredential(options) {
2924
3047
  if (typeof options.token === "string" && options.token) return;
2925
- const source = resolveCredentialSource(typeof options.profile === "string" && options.profile ? options.profile : void 0);
3048
+ const profileName = typeof options.profile === "string" && options.profile ? options.profile : void 0;
3049
+ await recoverPendingAdopts({ quiet: options.json === true || options.format === "json" });
3050
+ const source = resolveCredentialSource(profileName);
2926
3051
  if (source?.kind !== "profile") return;
2927
3052
  let { profile } = source;
2928
3053
  if (profile.token && !isIdentityProfile(profile) && !isClientProfile(profile) && !findIdentityFallbackProfile(profile)) {