@fluid-app/fluid-cli 0.1.799 → 0.1.801

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 walkCommands, A as pollAgentAccess, D as fetchUserCompanies, E as confirmMfa, F as validateToken, M as sendMfa, N as signup, O as getFluidApiBase, P as switchCompany, Q as visibleSubcommands, S as resolveCredentialSource, X as rootCommand, Y as filterCatalog, Z as visibleOptions, _ as getAuthToken, c as inputsModeActive, g as getActiveProfile, j as redeemIdentityLink, k as isInsecureRemoteBase, l as registerInputsHook, s as exitOnInputsError, u as createInputsReader, w as FLUID_API_ERROR, x as readFdToken } from "../hook-Bi6S629V.mjs";
3
- import { A as isClientProfile, C as readStoredConfig, D as getConfigDir, E as isStrictConfig, S as readConfig, T as writeConfig, _ as primeClientProfile, c as sessionFacts, j as isIdentityProfile, l as signInWithBrowser, n as describeIdentityError, o as primeIdentityProfile, p as clientAccessToken, r as identityToken, t as endUnusedSessions, u as signOutIdentity, w as updateConfig, y as resolveIdentityUrl } from "../profiles-Sitg25-8.mjs";
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-gdAJafKe.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";
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";
@@ -1142,9 +1142,31 @@ async function loginWithIdentity(context) {
1142
1142
  await signOutIdentity(signIn.auth).catch(() => void 0);
1143
1143
  return failed("SHOPPER_SESSION", "This account does not sign in as an admin or rep, so it cannot sign in to the CLI.");
1144
1144
  }
1145
+ const companyless = !signIn.facts.companyId;
1146
+ if (companyless && !signIn.facts.roles.includes("root_admin")) {
1147
+ await signOutIdentity(signIn.auth).catch(() => void 0);
1148
+ return failed("IDENTITY_NO_COMPANY", "This sign-in is not in a company. Run `fluid login --shop <company>` to sign in to one.");
1149
+ }
1150
+ if (companyless && signIn.recovered && !context.org && !signIn.pickedOrg) {
1151
+ await signOutIdentity(signIn.auth).catch(() => void 0);
1152
+ return failed("IDENTITY_SIGN_IN_FAILED", "The sign-in finished without knowing which company you picked. Run `fluid login` again.");
1153
+ }
1154
+ const rootFallback = companyless && !context.org && !signIn.pickedOrg;
1155
+ const org = companyless ? context.org ?? signIn.pickedOrg ?? "017b4195-f90f-7f66-962b-e5a3e1c9748e" : void 0;
1156
+ const auth = org ? {
1157
+ ...signIn.auth,
1158
+ org
1159
+ } : signIn.auth;
1160
+ let accessToken = signIn.accessToken;
1161
+ if (org) try {
1162
+ accessToken = (await identityToken(auth, org)).accessToken;
1163
+ } catch (error) {
1164
+ await signOutIdentity(signIn.auth).catch(() => void 0);
1165
+ return failed("IDENTITY_COMPANY_EXCHANGE_FAILED", `Could not sign in to the company: ${describeIdentityError(error)}`);
1166
+ }
1145
1167
  const spinner = context.spinner("Loading your company...");
1146
- const company = await context.validateToken(signIn.accessToken, { baseUrl: apiBase });
1147
- const companyName = company.success ? company.value.name : signIn.facts.companyId ?? "Fluid";
1168
+ const company = rootFallback ? null : await context.validateToken(accessToken, { baseUrl: apiBase });
1169
+ const companyName = rootFallback ? "Fluid" : company?.success ? company.value.name : org ?? signIn.facts.companyId ?? "Fluid";
1148
1170
  spinner.succeed(`Signed in to ${companyName}`);
1149
1171
  const profileName = context.profileName ?? companyName;
1150
1172
  const decision = await context.decideOverwrite(profileName);
@@ -1168,7 +1190,7 @@ async function loginWithIdentity(context) {
1168
1190
  name: profileName,
1169
1191
  companyName,
1170
1192
  baseUrl: apiBase,
1171
- auth: signIn.auth
1193
+ auth
1172
1194
  })
1173
1195
  }
1174
1196
  }));
@@ -1767,7 +1789,7 @@ const defaultSignupDeps = {
1767
1789
  isInteractive: () => Boolean(process.stdin.isTTY),
1768
1790
  agent: {
1769
1791
  poll: pollAgentAccess,
1770
- saveProfile: async (name, input, options) => (await import("../client-8ZkZdMPP.mjs")).saveClientProfile(name, input, options),
1792
+ saveProfile: async (name, input, options) => (await import("../client-DsG9CMhN.mjs")).saveClientProfile(name, input, options),
1771
1793
  strictConfig: isStrictConfig,
1772
1794
  stashRecovery: writeRecoveryFile,
1773
1795
  stderrIsTty: () => Boolean(process.stderr.isTTY),
@@ -2202,7 +2224,17 @@ const profilesCommand = new Command("profiles").description("List stored profile
2202
2224
  * An identity-mode profile is shown from its identity session: the facts
2203
2225
  * come from the identity service's `/userinfo`, never from decoding a token.
2204
2226
  */
2205
- async function whoamiIdentity(profile) {
2227
+ function sourceLabel(source) {
2228
+ if (source.envVar) return source.envVar;
2229
+ if (source.origin === "fluidrc") return `.fluidrc profile ${source.profileName}`;
2230
+ if (source.origin === "explicit") return `profile ${source.profileName}`;
2231
+ return `config.json profile ${source.profileName}`;
2232
+ }
2233
+ function printSource(source) {
2234
+ console.log(` Source: ${chalk.bold(sourceLabel(source))}`);
2235
+ console.log(` Mode: ${source.mode}`);
2236
+ }
2237
+ async function whoamiIdentity(profile, source) {
2206
2238
  const spinner = ora("Checking your identity session...").start();
2207
2239
  let facts;
2208
2240
  try {
@@ -2215,6 +2247,7 @@ async function whoamiIdentity(profile) {
2215
2247
  }
2216
2248
  spinner.succeed(chalk.green("Authenticated (Fluid identity service)"));
2217
2249
  console.log(` Profile: ${chalk.bold(profile.name)}`);
2250
+ printSource(source);
2218
2251
  console.log(` Company: ${chalk.bold(profile.companyName)}`);
2219
2252
  if (facts.companyId) console.log(` Company ID: ${chalk.dim(facts.companyId)}`);
2220
2253
  console.log(` Subject: ${chalk.dim(facts.subject)}`);
@@ -2223,7 +2256,7 @@ async function whoamiIdentity(profile) {
2223
2256
  console.log(` Signed in: ${chalk.dim((/* @__PURE__ */ new Date(facts.authTime * 1e3)).toISOString())}`);
2224
2257
  console.log(` Stored: ${chalk.dim(profile.storedAt)}`);
2225
2258
  }
2226
- async function whoamiClient(profile) {
2259
+ async function whoamiClient(profile, source) {
2227
2260
  const spinner = ora("Requesting a token for this client...").start();
2228
2261
  try {
2229
2262
  await clientAccessToken(profile);
@@ -2236,7 +2269,7 @@ async function whoamiClient(profile) {
2236
2269
  spinner.succeed(chalk.green("Authenticated (client credentials)"));
2237
2270
  console.log(` Profile: ${chalk.bold(profile.name)}`);
2238
2271
  console.log(` Company: ${chalk.bold(profile.companyName)}`);
2239
- console.log(` Mode: client`);
2272
+ printSource(source);
2240
2273
  console.log(` Client ID: ${chalk.dim(profile.auth.clientId)}`);
2241
2274
  console.log(` Org: ${chalk.dim(profile.auth.org)}`);
2242
2275
  console.log(` Stored: ${chalk.dim(profile.storedAt)}`);
@@ -2248,10 +2281,11 @@ const COMPANY_TOKEN_PREFIX = "PT-";
2248
2281
  * command uses before any saved login, against FLUID_API_BASE.
2249
2282
  *
2250
2283
  * token - The token the environment holds.
2284
+ * source - Where that token came from.
2251
2285
  *
2252
2286
  * Returns nothing; sets the exit code when the token is refused.
2253
2287
  */
2254
- async function whoamiEnvToken(token) {
2288
+ async function whoamiEnvToken(token, source) {
2255
2289
  const baseUrl = process.env["FLUID_API_BASE"];
2256
2290
  const spinner = ora("Verifying the token from FLUID_TOKEN...").start();
2257
2291
  const result = await validateToken(token, baseUrl ? { baseUrl } : {});
@@ -2262,28 +2296,35 @@ async function whoamiEnvToken(token) {
2262
2296
  return;
2263
2297
  }
2264
2298
  spinner.succeed(chalk.green("Authenticated (token from FLUID_TOKEN)"));
2299
+ printSource(source);
2265
2300
  console.log(` Company: ${chalk.bold(result.value.name)}`);
2266
2301
  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`."));
2267
2302
  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."));
2268
2303
  }
2269
2304
  const whoamiCommand = new Command("whoami").description("Show the current authenticated profile").action(async () => {
2270
2305
  const source = resolveCredentialSource();
2271
- if (source?.kind === "token") {
2272
- await whoamiEnvToken(source.token);
2306
+ const description = source ? describeCredentialSource(source) : null;
2307
+ if (source?.kind === "token" && description) {
2308
+ await whoamiEnvToken(source.token, description);
2273
2309
  return;
2274
2310
  }
2275
- const profile = getActiveProfile();
2311
+ const profile = source?.kind === "profile" ? source.profile : getActiveProfile();
2276
2312
  if (!profile) {
2277
2313
  console.log(chalk.yellow("Not logged in. Run `fluid login` to authenticate."));
2278
2314
  process.exitCode = 1;
2279
2315
  return;
2280
2316
  }
2317
+ const profileSource = description ?? {
2318
+ origin: "active",
2319
+ mode: isIdentityProfile(profile) ? "identity" : isClientProfile(profile) ? "client" : "legacy",
2320
+ profileName: profile.name
2321
+ };
2281
2322
  if (isIdentityProfile(profile)) {
2282
- await whoamiIdentity(profile);
2323
+ await whoamiIdentity(profile, profileSource);
2283
2324
  return;
2284
2325
  }
2285
2326
  if (isClientProfile(profile)) {
2286
- await whoamiClient(profile);
2327
+ await whoamiClient(profile, profileSource);
2287
2328
  return;
2288
2329
  }
2289
2330
  const spinner = ora("Verifying token...").start();
@@ -2297,6 +2338,7 @@ const whoamiCommand = new Command("whoami").description("Show the current authen
2297
2338
  }
2298
2339
  spinner.succeed(chalk.green("Authenticated"));
2299
2340
  console.log(` Profile: ${chalk.bold(profile.name)}`);
2341
+ printSource(profileSource);
2300
2342
  console.log(` Company: ${chalk.bold(result.value.name)}`);
2301
2343
  console.log(` Stored: ${chalk.dim(profile.storedAt)}`);
2302
2344
  });
@@ -2704,8 +2746,11 @@ const versionCommand = new Command("version").description("Show the CLI's and pl
2704
2746
  /**
2705
2747
  * Restores an identity-mode profile's session before a command runs, so the
2706
2748
  * synchronous `getAuthToken()` that plugins call finds a current access
2707
- * token in memory. Legacy profiles and literal tokens are left alone: no
2708
- * credential store is touched and no request is made for them.
2749
+ * token in memory. Literal tokens are left alone, and so is a legacy profile
2750
+ * unless an identity profile on the same API base exists: only then is its
2751
+ * token checked with the API, and a rejected one is replaced for the process
2752
+ * by the one identity profile whose authenticated shop matches the legacy
2753
+ * profile's; none or several matching leaves the token alone.
2709
2754
  */
2710
2755
  /**
2711
2756
  * Primes the credential a command with these options would use. A session
@@ -2717,6 +2762,10 @@ async function primeCommandCredential(options) {
2717
2762
  const source = resolveCredentialSource(typeof options.profile === "string" && options.profile ? options.profile : void 0);
2718
2763
  if (source?.kind !== "profile") return;
2719
2764
  const { profile } = source;
2765
+ if ((source.origin === "fluidrc" || source.origin === "active") && !isIdentityProfile(profile) && !isClientProfile(profile)) {
2766
+ await adoptFallbackForDeadToken(profile);
2767
+ return;
2768
+ }
2720
2769
  try {
2721
2770
  if (isIdentityProfile(profile)) await primeIdentityProfile(profile);
2722
2771
  else if (isClientProfile(profile)) await primeClientProfile(profile);
@@ -2724,6 +2773,37 @@ async function primeCommandCredential(options) {
2724
2773
  process.stderr.write(`${chalk.yellow(describeIdentityError(error))}\n`);
2725
2774
  }
2726
2775
  }
2776
+ const normalizeShop = (shop) => shop.toLowerCase().replace(/^https?:\/\//, "").replace(/\/.*$/, "").replace(/\.fluid\.app$/, "");
2777
+ async function authenticatedShopMatches(identity, wanted) {
2778
+ try {
2779
+ await primeIdentityProfile(identity);
2780
+ return (await fetchCompanyShops(await profileAccessToken(identity), { baseUrl: identity.baseUrl })).some((shop) => normalizeShop(shop) === wanted);
2781
+ } catch {
2782
+ return false;
2783
+ }
2784
+ }
2785
+ async function adoptFallbackForDeadToken(profile) {
2786
+ if (!profile.token) return;
2787
+ const groups = findIdentityFallbackCandidates(profile);
2788
+ if (groups.length === 0) return;
2789
+ const checked = await validateToken(profile.token, profile.baseUrl ? { baseUrl: profile.baseUrl } : {});
2790
+ if (checked.success || checked.error.code !== "INVALID_TOKEN") return;
2791
+ if (!profile.fluidShop) return;
2792
+ const wanted = normalizeShop(profile.fluidShop);
2793
+ let identity;
2794
+ for (const group of groups) {
2795
+ const matches = [];
2796
+ for (const candidate of group) if (await authenticatedShopMatches(candidate, wanted)) matches.push(candidate);
2797
+ if (matches.length > 1) return;
2798
+ if (matches.length === 1) {
2799
+ identity = matches[0];
2800
+ break;
2801
+ }
2802
+ }
2803
+ if (!identity) return;
2804
+ adoptIdentityProfile(identity, profile.name);
2805
+ process.stderr.write(`${chalk.yellow(`The token from profile "${profile.name}" was rejected (401); using identity profile "${identity.name}" instead.`)}\n`);
2806
+ }
2727
2807
  //#endregion
2728
2808
  //#region src/bin/fluid.ts
2729
2809
  const { version } = createRequire(import.meta.url)("../../package.json");
@@ -2773,7 +2853,7 @@ program.hook("preAction", async (_program, actionCommand) => {
2773
2853
  let topLevel = actionCommand;
2774
2854
  while (topLevel.parent && topLevel.parent !== program) topLevel = topLevel.parent;
2775
2855
  if (selfAuthenticating.has(topLevel.name())) return;
2776
- await primeCommandCredential(actionCommand.opts());
2856
+ await primeCommandCredential(opts);
2777
2857
  });
2778
2858
  const entryPath = realpathSync(fileURLToPath(import.meta.url));
2779
2859
  if (!inputsModeActive(process.env)) startUpdateCheck({