@fluid-app/fluid-cli 0.1.800 → 0.1.802

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 { $ as filterCatalog, A as fetchCompanyShops, D as FLUID_API_ERROR, F as redeemIdentityLink, I as sendMfa, L as signup, M as getFluidApiBase, N as isInsecureRemoteBase, P as pollAgentAccess, R as switchCompany, T as resolveCredentialSource, _ as describeCredentialSource, b as getAuthToken, c as inputsModeActive, et as rootCommand, g as adoptIdentityProfile, j as fetchUserCompanies, k as confirmMfa, l as registerInputsHook, nt as visibleSubcommands, rt as walkCommands, s as exitOnInputsError, tt as visibleOptions, u as createInputsReader, v as findIdentityFallbackCandidates, w as readFdToken, y as getActiveProfile, z as validateToken } from "../hook-D8P8RTOU.mjs";
3
- import { C as readConfig, D as isStrictConfig, E as writeConfig, M as isIdentityProfile, O as getConfigDir, T as updateConfig, _ as primeClientProfile, b as resolveIdentityUrl, c as sessionFacts, j as isClientProfile, l as signInWithBrowser, n as describeIdentityError, o as primeIdentityProfile, p as clientAccessToken, r as identityToken, s as profileAccessToken, t as endUnusedSessions, u as signOutIdentity, w as readStoredConfig } from "../profiles-CbMJHi-u.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-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";
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";
@@ -1180,20 +1180,27 @@ async function loginWithIdentity(context) {
1180
1180
  profileName
1181
1181
  };
1182
1182
  }
1183
- const before = readConfig();
1184
- const after = updateConfig((config) => ({
1185
- ...config,
1186
- activeProfile: profileName,
1187
- profiles: {
1188
- ...config.profiles,
1189
- [profileName]: createIdentityProfile({
1190
- name: profileName,
1191
- companyName,
1192
- baseUrl: apiBase,
1193
- auth
1194
- })
1195
- }
1196
- }));
1183
+ let before;
1184
+ let after;
1185
+ try {
1186
+ before = readConfig();
1187
+ after = updateConfig((config) => ({
1188
+ ...config,
1189
+ activeProfile: profileName,
1190
+ profiles: {
1191
+ ...config.profiles,
1192
+ [profileName]: createIdentityProfile({
1193
+ name: profileName,
1194
+ companyName,
1195
+ baseUrl: apiBase,
1196
+ auth
1197
+ })
1198
+ }
1199
+ }));
1200
+ } catch (error) {
1201
+ await signOutIdentity(signIn.auth).catch(() => void 0);
1202
+ throw error;
1203
+ }
1197
1204
  for (const problem of await endUnusedSessions(before, after)) context.log(problem);
1198
1205
  return {
1199
1206
  status: "signed_in",
@@ -1789,7 +1796,7 @@ const defaultSignupDeps = {
1789
1796
  isInteractive: () => Boolean(process.stdin.isTTY),
1790
1797
  agent: {
1791
1798
  poll: pollAgentAccess,
1792
- saveProfile: async (name, input, options) => (await import("../client-DsG9CMhN.mjs")).saveClientProfile(name, input, options),
1799
+ saveProfile: async (name, input, options) => (await import("../client-DeZ9F-Hm.mjs")).saveClientProfile(name, input, options),
1793
1800
  strictConfig: isStrictConfig,
1794
1801
  stashRecovery: writeRecoveryFile,
1795
1802
  stderrIsTty: () => Boolean(process.stderr.isTTY),
@@ -2159,34 +2166,39 @@ const signupCommand = buildSignupCommand();
2159
2166
  * navigation; a native client revokes its refresh token instead.)
2160
2167
  */
2161
2168
  const logoutCommand = new Command("logout").description("Remove stored authentication").option("-a, --all", "Remove all profiles").action(async (opts) => {
2162
- const config = readConfig();
2163
- if (opts.all) {
2164
- const after = {
2165
- ...config,
2166
- activeProfile: null,
2167
- profiles: {}
2168
- };
2169
- writeConfig(after);
2170
- for (const problem of await endUnusedSessions(config, after)) console.log(chalk.yellow(problem));
2171
- console.log(chalk.green("All profiles removed."));
2169
+ let before;
2170
+ let after;
2171
+ withConfigLock(() => {
2172
+ const config = readConfig();
2173
+ if (opts.all) {
2174
+ before = config;
2175
+ after = {
2176
+ ...config,
2177
+ activeProfile: null,
2178
+ profiles: {}
2179
+ };
2180
+ } else if (config.activeProfile) {
2181
+ before = config;
2182
+ const { [config.activeProfile]: _, ...remainingProfiles } = config.profiles;
2183
+ after = {
2184
+ ...config,
2185
+ activeProfile: Object.keys(remainingProfiles)[0] ?? null,
2186
+ profiles: remainingProfiles
2187
+ };
2188
+ }
2189
+ if (after) writeConfig(after);
2190
+ });
2191
+ if (!before || !after) {
2192
+ console.log(chalk.yellow("Not currently logged in."));
2172
2193
  return;
2173
2194
  }
2174
- if (!config.activeProfile) {
2175
- console.log(chalk.yellow("Not currently logged in."));
2195
+ for (const problem of await endUnusedSessions(before, after)) console.log(chalk.yellow(problem));
2196
+ if (opts.all) {
2197
+ console.log(chalk.green("All profiles removed."));
2176
2198
  return;
2177
2199
  }
2178
- const profileName = config.activeProfile;
2179
- const { [profileName]: _, ...remainingProfiles } = config.profiles;
2180
- const nextActive = Object.keys(remainingProfiles)[0] ?? null;
2181
- const after = {
2182
- ...config,
2183
- activeProfile: nextActive,
2184
- profiles: remainingProfiles
2185
- };
2186
- writeConfig(after);
2187
- for (const problem of await endUnusedSessions(config, after)) console.log(chalk.yellow(problem));
2188
- console.log(chalk.green(`Logged out of profile ${chalk.bold(profileName)}.`));
2189
- if (nextActive) console.log(chalk.dim(`Switched to profile ${nextActive}.`));
2200
+ console.log(chalk.green(`Logged out of profile ${chalk.bold(before.activeProfile)}.`));
2201
+ if (after.activeProfile) console.log(chalk.dim(`Switched to profile ${after.activeProfile}.`));
2190
2202
  });
2191
2203
  //#endregion
2192
2204
  //#region src/commands/profiles.ts
@@ -2742,6 +2754,157 @@ const versionCommand = new Command("version").description("Show the CLI's and pl
2742
2754
  process.stdout.write(opts.json ? JSON.stringify({ packages }, null, 2) + "\n" : formatVersionReport(packages) + "\n");
2743
2755
  });
2744
2756
  //#endregion
2757
+ //#region src/auth/identity/adopt-legacy.ts
2758
+ const ADOPT_BACKOFF_MS = 1440 * 60 * 1e3;
2759
+ const ADOPT_UNAVAILABLE_BACKOFF_MS = 900 * 1e3;
2760
+ const ADOPT_TIMEOUT_MS = 5e3;
2761
+ const ADOPT_DEADLINE_MS = 6e3;
2762
+ const MIN_LOCK_WAIT_MS = 250;
2763
+ const BACKOFF_FILE = "adopt-backoff.json";
2764
+ function backoffPath() {
2765
+ return join(getConfigDir(), BACKOFF_FILE);
2766
+ }
2767
+ function backoffKey(profile) {
2768
+ const digest = createHash("sha256").update(profile.token ?? "").digest("hex").slice(0, 12);
2769
+ return `${profile.name}\u0000${profile.companyName}\u0000${digest}`;
2770
+ }
2771
+ function readBackoff() {
2772
+ try {
2773
+ const parsed = JSON.parse(readFileSync(backoffPath(), "utf8"));
2774
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
2775
+ } catch {
2776
+ return {};
2777
+ }
2778
+ }
2779
+ function recordBackoff(profile, ms) {
2780
+ try {
2781
+ const now = Date.now();
2782
+ const next = {};
2783
+ for (const [key, until] of Object.entries(readBackoff())) if (typeof until === "number" && until > now) next[key] = until;
2784
+ if (ms === null) delete next[backoffKey(profile)];
2785
+ else next[backoffKey(profile)] = now + ms;
2786
+ const dir = getConfigDir();
2787
+ if (!existsSync(dir)) mkdirSync(dir, {
2788
+ recursive: true,
2789
+ mode: 448
2790
+ });
2791
+ const tmp = join(dir, `.adopt-backoff-${randomBytes(6).toString("hex")}.tmp`);
2792
+ writeFileSync(tmp, JSON.stringify(next), { mode: 384 });
2793
+ renameSync(tmp, backoffPath());
2794
+ } catch {}
2795
+ }
2796
+ function inBackoff(profile) {
2797
+ const until = readBackoff()[backoffKey(profile)];
2798
+ return typeof until === "number" && until > Date.now();
2799
+ }
2800
+ function convert(profile, auth, lockTimeoutMs) {
2801
+ withConfigLock(() => {
2802
+ updateConfig((config) => {
2803
+ const current = config.profiles[profile.name];
2804
+ if (!current || current.token !== profile.token) throw new Error("The profile changed while it was being adopted.");
2805
+ const { token: _token, gitSyncActor: _actor, ...rest } = current;
2806
+ return {
2807
+ ...config,
2808
+ profiles: {
2809
+ ...config.profiles,
2810
+ [profile.name]: {
2811
+ ...rest,
2812
+ auth
2813
+ }
2814
+ }
2815
+ };
2816
+ });
2817
+ }, lockTimeoutMs);
2818
+ }
2819
+ function ownedByMist(profile) {
2820
+ return profile.mistOwned === true || profile.identityClient !== void 0;
2821
+ }
2822
+ function withSignal(signal) {
2823
+ return (input, init) => fetch(input, {
2824
+ ...init,
2825
+ signal: init?.signal ? AbortSignal.any([init.signal, signal]) : signal
2826
+ });
2827
+ }
2828
+ /**
2829
+ * Trades a stored legacy profile's token for an identity session and, once
2830
+ * the session is stored and verified, rewrites the profile to identity mode
2831
+ * and drops its plaintext token. Every other outcome keeps the profile as it
2832
+ * is, and the whole attempt gives up after {@link ADOPT_DEADLINE_MS}: a trade
2833
+ * that finishes later is ignored and never persisted or converted. A back-off is on file before the trade
2834
+ * starts. Profiles Mist owns are never traded. Never throws; resolves with
2835
+ * the converted profile, or null.
2836
+ */
2837
+ async function adoptLegacyProfile(profile) {
2838
+ if (!profile.token || ownedByMist(profile) || inBackoff(profile)) return null;
2839
+ recordBackoff(profile, ADOPT_UNAVAILABLE_BACKOFF_MS);
2840
+ const abort = new AbortController();
2841
+ const deadlineAt = Date.now() + ADOPT_DEADLINE_MS;
2842
+ let expired = false;
2843
+ let timer;
2844
+ const deadline = new Promise((resolve) => {
2845
+ timer = setTimeout(() => {
2846
+ expired = true;
2847
+ abort.abort();
2848
+ resolve(null);
2849
+ }, ADOPT_DEADLINE_MS);
2850
+ });
2851
+ const attempt = trade(profile, abort.signal, () => expired, () => deadlineAt - Date.now()).catch(() => null);
2852
+ try {
2853
+ return await Promise.race([attempt, deadline]);
2854
+ } finally {
2855
+ clearTimeout(timer);
2856
+ }
2857
+ }
2858
+ async function trade(profile, signal, expired, remainingMs) {
2859
+ const apiBase = profile.baseUrl ?? getFluidApiBase();
2860
+ const identityUrl = resolveIdentityUrl(apiBase);
2861
+ if (!identityUrl) {
2862
+ recordBackoff(profile, null);
2863
+ return null;
2864
+ }
2865
+ const held = createAdoptionSession(identityUrl, signal);
2866
+ const result = await tradeLegacyToken({
2867
+ legacyToken: profile.token,
2868
+ apiBase,
2869
+ session: held.session,
2870
+ requestTimeoutMs: ADOPT_TIMEOUT_MS,
2871
+ fetch: withSignal(signal)
2872
+ });
2873
+ if (result.outcome === "not_targeted" || result.outcome === "refused") {
2874
+ recordBackoff(profile, ADOPT_BACKOFF_MS);
2875
+ return null;
2876
+ }
2877
+ if (result.outcome === "unavailable" || expired()) return null;
2878
+ const revoke = async () => {
2879
+ if (expired()) return;
2880
+ await result.discard().catch(() => void 0);
2881
+ };
2882
+ try {
2883
+ await held.persist();
2884
+ } catch (error) {
2885
+ if (error instanceof KeyringRefusedError) recordBackoff(profile, ADOPT_BACKOFF_MS);
2886
+ await revoke();
2887
+ return null;
2888
+ }
2889
+ const lockWaitMs = Math.min(configLockTimings.timeoutMs, remainingMs() - MIN_LOCK_WAIT_MS);
2890
+ try {
2891
+ if (lockWaitMs <= 0) throw new Error("No time left to rewrite the profile.");
2892
+ convert(profile, held.auth, lockWaitMs);
2893
+ } catch {
2894
+ if (!expired()) {
2895
+ await held.unpersist().catch(() => void 0);
2896
+ await revoke();
2897
+ }
2898
+ return null;
2899
+ }
2900
+ recordBackoff(profile, null);
2901
+ const { token: _token, gitSyncActor: _actor, ...rest } = profile;
2902
+ return {
2903
+ ...rest,
2904
+ auth: held.auth
2905
+ };
2906
+ }
2907
+ //#endregion
2745
2908
  //#region src/auth/identity/prime.ts
2746
2909
  /**
2747
2910
  * Restores an identity-mode profile's session before a command runs, so the
@@ -2761,7 +2924,11 @@ async function primeCommandCredential(options) {
2761
2924
  if (typeof options.token === "string" && options.token) return;
2762
2925
  const source = resolveCredentialSource(typeof options.profile === "string" && options.profile ? options.profile : void 0);
2763
2926
  if (source?.kind !== "profile") return;
2764
- const { profile } = source;
2927
+ let { profile } = source;
2928
+ if (profile.token && !isIdentityProfile(profile) && !isClientProfile(profile) && !findIdentityFallbackProfile(profile)) {
2929
+ const stored = await adoptLegacyProfile(profile) ?? readConfig().profiles[profile.name];
2930
+ if (isIdentityProfile(stored)) profile = stored;
2931
+ }
2765
2932
  if ((source.origin === "fluidrc" || source.origin === "active") && !isIdentityProfile(profile) && !isClientProfile(profile)) {
2766
2933
  await adoptFallbackForDeadToken(profile);
2767
2934
  return;