@fluid-app/fluid-cli 0.1.692 → 0.1.694

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
@@ -36,6 +36,10 @@ email. Without `--yes` it asks at a terminal, and refuses when there is no
36
36
  terminal or with `--json`, which prints one object (`status` is
37
37
  `signed_up` or `error`).
38
38
 
39
+ `--agent-access [name]` also asks for a credential an administrator of the new
40
+ company approves for an agent; the command waits, then saves it as a profile.
41
+ It is available when enabled: see [AGENT_ACCESS.md](./AGENT_ACCESS.md).
42
+
39
43
  ## Authentication
40
44
 
41
45
  ```bash
@@ -1,15 +1,17 @@
1
1
  #!/usr/bin/env node
2
- import { $ as sendMfa, A as signInWithBrowser, B as getConfigDir, C as endUnusedSessions, D as primeIdentityProfile, F as resolveIdentityUrl, G as isClientProfile, I as readConfig, K as isIdentityProfile, L as updateConfig, M as clientAccessToken, P as primeClientProfile, Q as redeemIdentityLink, R as writeConfig, T as identityToken, X as fetchUserCompanies, Y as confirmMfa, Z as getFluidApiBase, _ as getAuthToken, _t as rootCommand, bt as walkCommands, c as inputsModeActive, et as signup, g as getActiveProfile, gt as filterCatalog, i as INPUTS_MODE_ENV, j as signOutIdentity, k as sessionFacts, l as registerInputsHook, nt as validateToken, q as FLUID_API_ERROR, s as exitOnInputsError, tt as switchCompany, u as createInputsReader, vt as visibleOptions, w as describeIdentityError, x as resolveCredentialSource, yt as visibleSubcommands, z as isStrictConfig } from "../hook-CV4vUh4j.mjs";
2
+ import { A as redeemIdentityLink, C as FLUID_API_ERROR, D as getFluidApiBase, E as fetchUserCompanies, J as filterCatalog, M as signup, N as switchCompany, O as isInsecureRemoteBase, P as validateToken, Q as walkCommands, T as confirmMfa, X as visibleOptions, Y as rootCommand, Z as visibleSubcommands, _ as getAuthToken, c as inputsModeActive, g as getActiveProfile, i as INPUTS_MODE_ENV, j as sendMfa, k as pollAgentAccess, l as registerInputsHook, s as exitOnInputsError, u as createInputsReader, x as resolveCredentialSource } from "../hook-DJNt29x1.mjs";
3
+ import { A as isClientProfile, C as writeConfig, S as updateConfig, T as getConfigDir, _ as primeClientProfile, b as readConfig, 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 isStrictConfig, x as readStoredConfig, y as resolveIdentityUrl } from "../profiles-CpG6O9Zi.mjs";
3
4
  import { createRequire } from "node:module";
4
- import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
5
+ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
5
6
  import { fileURLToPath, pathToFileURL } from "node:url";
6
7
  import { Argument, Command, Option } from "commander";
7
8
  import { text } from "node:stream/consumers";
8
9
  import chalk from "chalk";
9
10
  import prompts from "prompts";
10
11
  import ora from "ora";
11
- import { createHash, randomBytes } from "node:crypto";
12
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
12
13
  import { dirname, isAbsolute, join, relative, sep } from "node:path";
14
+ import { tmpdir } from "node:os";
13
15
  import { spawn } from "node:child_process";
14
16
  //#region src/commands/commands.ts
15
17
  /**
@@ -1011,12 +1013,32 @@ const loginCommand = buildLoginCommand();
1011
1013
  * confirms the signup, by the emailed link or by signing in with the two
1012
1014
  * `fluid login` steps this command prints.
1013
1015
  */
1016
+ const AGENT_NAME_MAX = 100;
1017
+ const DEFAULT_AGENT_NAME = "Fluid CLI agent";
1018
+ const MIN_POLL_SECONDS = 5;
1019
+ const MAX_BACKOFF_SECONDS = 60;
1020
+ const ISSUING_GRACE_MS = 1200 * 1e3;
1014
1021
  const defaultSignupDeps = {
1015
1022
  api: { signup },
1016
1023
  prompt: (question) => prompts(question),
1017
1024
  spinner: (text) => ora(text).start(),
1018
1025
  log: (line) => console.log(line),
1019
- isInteractive: () => Boolean(process.stdin.isTTY)
1026
+ notice: (line) => console.error(line),
1027
+ isInteractive: () => Boolean(process.stdin.isTTY),
1028
+ agent: {
1029
+ poll: pollAgentAccess,
1030
+ saveProfile: async (name, input, options) => (await import("../client-DU__lstz.mjs")).saveClientProfile(name, input, options),
1031
+ strictConfig: isStrictConfig,
1032
+ stashRecovery: writeRecoveryFile,
1033
+ stderrIsTty: () => Boolean(process.stderr.isTTY),
1034
+ platform: () => process.platform,
1035
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
1036
+ now: Date.now,
1037
+ apiBase: getFluidApiBase,
1038
+ identityUrl: (apiBase) => resolveIdentityUrl(apiBase),
1039
+ profileExists: (name) => Boolean(readStoredConfig().profiles[name]),
1040
+ profileVisible: (name) => Boolean(readConfig().profiles[name])
1041
+ }
1020
1042
  };
1021
1043
  const SUBDOMAIN_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
1022
1044
  const COLOR_PATTERN = /^(?:[a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/;
@@ -1070,6 +1092,11 @@ function buildRequest(opts) {
1070
1092
  code: "INVALID_SUBDOMAIN",
1071
1093
  message: "--subdomain needs at least one letter or digit; it may also hold hyphens, up to 63 characters."
1072
1094
  } };
1095
+ const agentName = typeof opts.agentAccess === "string" ? opts.agentAccess.trim() : "";
1096
+ if ([...agentName].length > AGENT_NAME_MAX) return { error: {
1097
+ code: "AGENT_NAME_INVALID",
1098
+ message: `The --agent-access name can be at most ${AGENT_NAME_MAX} characters.`
1099
+ } };
1073
1100
  const color = opts.color?.trim().replace(/^#/, "");
1074
1101
  if (color !== void 0 && !COLOR_PATTERN.test(color)) return { error: {
1075
1102
  code: "INVALID_COLOR",
@@ -1081,7 +1108,149 @@ function buildRequest(opts) {
1081
1108
  lastName: (opts.lastName ?? "").trim(),
1082
1109
  companyName: (opts.companyName ?? "").trim(),
1083
1110
  subdomain,
1084
- ...color ? { color } : {}
1111
+ ...color ? { color } : {},
1112
+ ...opts.agentAccess ? { agentAccess: { name: agentName || DEFAULT_AGENT_NAME } } : {}
1113
+ } };
1114
+ }
1115
+ /**
1116
+ * Waits for the signup's agent-access request to be approved and stores the
1117
+ * credential it delivers. Polls no faster than Fluid allows, stops on a final
1118
+ * answer or when the request expires, and saves the credential exactly once:
1119
+ * a delivered secret is never shown again, and a second poll revokes it.
1120
+ */
1121
+ async function awaitAgentCredential(access, target, companyName, yes, deps) {
1122
+ const { agent } = deps;
1123
+ const { profileName, apiBase, identityUrl } = target;
1124
+ const giveUpAt = Date.parse(access.expiresAt) + ISSUING_GRACE_MS;
1125
+ let wait = MIN_POLL_SECONDS;
1126
+ let failures = 0;
1127
+ for (;;) {
1128
+ if (Number.isFinite(giveUpAt) && agent.now() >= giveUpAt) return agentFailure("AGENT_ACCESS_EXPIRED");
1129
+ await agent.sleep(wait * 1e3);
1130
+ const answer = await agent.poll(access.handle);
1131
+ wait = MIN_POLL_SECONDS;
1132
+ switch (answer.state) {
1133
+ case "pending":
1134
+ case "issuing_soon":
1135
+ case "slow_down":
1136
+ failures = 0;
1137
+ wait = Math.max(answer.retryAfter ?? 0, MIN_POLL_SECONDS);
1138
+ break;
1139
+ case "retry":
1140
+ failures += 1;
1141
+ wait = Math.max(answer.retryAfter ?? 0, Math.min(MIN_POLL_SECONDS * 2 ** failures, MAX_BACKOFF_SECONDS));
1142
+ break;
1143
+ case "denied": return agentFailure("AGENT_ACCESS_DENIED");
1144
+ case "expired": return agentFailure("AGENT_ACCESS_EXPIRED");
1145
+ case "revoked": return agentFailure("AGENT_ACCESS_REVOKED");
1146
+ case "unavailable": return agentFailure("AGENT_ACCESS_UNAVAILABLE");
1147
+ case "delivered":
1148
+ try {
1149
+ await agent.saveProfile(profileName, {
1150
+ clientId: answer.clientId,
1151
+ clientSecret: answer.clientSecret,
1152
+ org: access.companyUuid,
1153
+ identityUrl,
1154
+ companyName,
1155
+ baseUrl: apiBase
1156
+ }, { replace: yes });
1157
+ if (!agent.profileVisible(profileName)) throw new Error("the saved profile is not visible to this process (strict config)");
1158
+ } catch (error) {
1159
+ const report = reportUnstored(agent, answer, access.companyUuid, identityUrl, errorText(error));
1160
+ let summary = report.summary;
1161
+ try {
1162
+ deps.notice(report.stderr);
1163
+ } catch {
1164
+ summary = report.ifSilent;
1165
+ }
1166
+ return agentFailure("AGENT_ACCESS_NOT_STORED", errorText(error), summary);
1167
+ }
1168
+ return { stored: profileName };
1169
+ }
1170
+ }
1171
+ }
1172
+ /**
1173
+ * Writes `content` to a new mode-0600 file in the CLI config dir, or, if that
1174
+ * fails, in a fresh 0700 temp dir. Returns the path; throws if both fail.
1175
+ */
1176
+ function writeRecoveryFile(content) {
1177
+ const name = `agent-access-recovery-${randomUUID()}.txt`;
1178
+ const write = (dir) => {
1179
+ const file = join(dir, name);
1180
+ writeFileSync(file, content, {
1181
+ mode: 384,
1182
+ flag: "wx"
1183
+ });
1184
+ chmodSync(file, 384);
1185
+ return file;
1186
+ };
1187
+ try {
1188
+ const dir = getConfigDir();
1189
+ mkdirSync(dir, {
1190
+ recursive: true,
1191
+ mode: 448
1192
+ });
1193
+ return write(dir);
1194
+ } catch {
1195
+ return write(mkdtempSync(join(tmpdir(), "fluid-agent-access-")));
1196
+ }
1197
+ }
1198
+ function credentialDetails(delivered, org, identityUrl) {
1199
+ return [
1200
+ `client_id: ${delivered.clientId}`,
1201
+ `client_secret: ${delivered.clientSecret}`,
1202
+ `organization: ${org}`,
1203
+ `token endpoint: ${identityUrl.replace(/\/$/, "")}/token (HTTP Basic client_credentials, resource=${org})`
1204
+ ].join("\n");
1205
+ }
1206
+ const NOT_STORED = "The credential was issued but could not be stored.";
1207
+ function revokeText(clientId) {
1208
+ return `Revoke the issued client (client_id ${clientId}) in the admin's Developer Hub, in the API clients list: its name starts with agent-access:. Then run signup again.`;
1209
+ }
1210
+ /**
1211
+ * What a failed save reports. `stderr` is the text to print and `summary` is the matching message for the
1212
+ * error, so neither claims more than the branch taken. The secret goes to a
1213
+ * private file with only its path printed; without a file (always on win32)
1214
+ * it is printed only when stderr is a terminal.
1215
+ */
1216
+ function reportUnstored(agent, delivered, org, identityUrl, reason) {
1217
+ const head = `The agent's credential was issued but not stored (${reason}). Fluid shows it once.`;
1218
+ const details = credentialDetails(delivered, org, identityUrl);
1219
+ if (agent.platform() !== "win32") try {
1220
+ const file = agent.stashRecovery(details);
1221
+ return {
1222
+ stderr: `${head}\nIts details, including the secret, were written to ${file} (readable only by you). Move them into a secret manager and delete the file; the secret requests access tokens at the token endpoint listed there.`,
1223
+ summary: `${NOT_STORED} Its details, including the secret, were written to ${file} (readable only by you); stderr names the file.`,
1224
+ ifSilent: `${NOT_STORED} Its details, including the secret, were written to ${file} (readable only by you); reporting that on stderr failed.`
1225
+ };
1226
+ } catch {}
1227
+ if (agent.stderrIsTty()) return {
1228
+ stderr: `${head} No private file could be written, so here it is; keep it now:\n${details}`,
1229
+ summary: `${NOT_STORED} No private file could be written, so the details, including the secret, were printed to stderr.`,
1230
+ ifSilent: `${NOT_STORED} No private file could be written and printing to stderr failed, so the secret was not emitted anywhere. ${revokeText(delivered.clientId)}`
1231
+ };
1232
+ const summary = `${NOT_STORED} No private file could be written and stderr is not a terminal, so the secret was not emitted anywhere. ${revokeText(delivered.clientId)}`;
1233
+ return {
1234
+ stderr: summary,
1235
+ summary,
1236
+ ifSilent: summary
1237
+ };
1238
+ }
1239
+ function errorText(error) {
1240
+ return error instanceof Error ? error.message : String(error);
1241
+ }
1242
+ const AGENT_FAILURES = {
1243
+ AGENT_ACCESS_DENIED: "An administrator denied the agent's access request.",
1244
+ AGENT_ACCESS_EXPIRED: "The agent's access request expired before it was approved. Run signup again with a different subdomain to ask anew.",
1245
+ AGENT_ACCESS_REVOKED: "The agent's credential was already delivered, so Fluid revoked it. Run signup again with a different subdomain to ask anew.",
1246
+ AGENT_ACCESS_UNAVAILABLE: "Fluid cannot issue the agent a credential for this company right now.",
1247
+ AGENT_ACCESS_NOT_STORED: NOT_STORED
1248
+ };
1249
+ function agentFailure(code, details, message) {
1250
+ return { failed: {
1251
+ code,
1252
+ message: message ?? AGENT_FAILURES[code] ?? code,
1253
+ ...details ? { details } : {}
1085
1254
  } };
1086
1255
  }
1087
1256
  function printFailure(error, json, deps) {
@@ -1111,6 +1280,33 @@ async function runSignup(opts, deps = defaultSignupDeps) {
1111
1280
  const built = buildRequest(opts);
1112
1281
  if ("error" in built) return printFailure(built.error, json, deps);
1113
1282
  const { request } = built;
1283
+ let target;
1284
+ if (request.agentAccess) {
1285
+ if (deps.agent.strictConfig()) return printFailure({
1286
+ code: "AGENT_ACCESS_STRICT_CONFIG",
1287
+ message: "--agent-access stores the credential as a profile, and strict config hides stored profiles from this process. Unset FLUID_RUNTIME_STRICT_CONFIG or drop --agent-access."
1288
+ }, json, deps);
1289
+ const apiBase = deps.agent.apiBase();
1290
+ if (isInsecureRemoteBase(apiBase)) return printFailure({
1291
+ code: "AGENT_ACCESS_INSECURE_BASE",
1292
+ message: "--agent-access will not run against a plain http API base on another host: the credential would cross the network unencrypted. Use an https API base."
1293
+ }, json, deps);
1294
+ const identityUrl = deps.agent.identityUrl(apiBase);
1295
+ if (!identityUrl) return printFailure({
1296
+ code: "AGENT_ACCESS_NO_IDENTITY",
1297
+ message: "--agent-access needs an identity service, and this API base has none. Set FLUID_IDENTITY_URL or drop --agent-access."
1298
+ }, json, deps);
1299
+ const profileName = `${request.subdomain}-agent`;
1300
+ if (deps.agent.profileExists(profileName) && !opts.yes) return printFailure({
1301
+ code: "PROFILE_EXISTS",
1302
+ message: `Profile "${profileName}" already exists. Pass --yes to replace it.`
1303
+ }, json, deps);
1304
+ target = {
1305
+ profileName,
1306
+ apiBase,
1307
+ identityUrl
1308
+ };
1309
+ }
1114
1310
  if (!opts.yes) {
1115
1311
  const question = `Create ${request.companyName} at subdomain ${request.subdomain}, and email ${request.email} to confirm it?`;
1116
1312
  if (json || !deps.isInteractive()) return printFailure({
@@ -1134,20 +1330,49 @@ async function runSignup(opts, deps = defaultSignupDeps) {
1134
1330
  const created = result.value;
1135
1331
  const next = nextCommands(request.email, created.company.fluidShop, created.company.subdomain);
1136
1332
  if (json) {
1137
- deps.log(JSON.stringify({
1333
+ const base = {
1138
1334
  status: "signed_up",
1139
1335
  company: created.company,
1140
1336
  userCompany: created.userCompany,
1141
1337
  currentlyDue: created.currentlyDue,
1142
1338
  next
1339
+ };
1340
+ if (!created.agentAccess || !target) {
1341
+ deps.log(JSON.stringify(base, null, 2));
1342
+ return 0;
1343
+ }
1344
+ const { approvalUrl, expiresAt } = created.agentAccess;
1345
+ deps.notice(`Waiting for an administrator to approve the agent at ${approvalUrl} (until ${expiresAt}).`);
1346
+ const outcome = await awaitAgentCredential(created.agentAccess, target, created.company.name, Boolean(opts.yes), deps);
1347
+ const agentAccess = "failed" in outcome ? {
1348
+ approvalUrl,
1349
+ expiresAt,
1350
+ status: "error",
1351
+ code: outcome.failed.code,
1352
+ message: outcome.failed.message,
1353
+ ...outcome.failed.details ? { details: outcome.failed.details } : {}
1354
+ } : {
1355
+ approvalUrl,
1356
+ expiresAt,
1357
+ status: "stored",
1358
+ profile: outcome.stored
1359
+ };
1360
+ deps.log(JSON.stringify({
1361
+ ...base,
1362
+ agentAccess
1143
1363
  }, null, 2));
1144
- return 0;
1364
+ return "failed" in outcome ? 1 : 0;
1145
1365
  }
1146
1366
  deps.log(chalk.green(`Signed up ${created.company.name} as ${created.company.fluidShop} (company ${created.company.id}).`));
1147
1367
  if (request.subdomain !== (opts.subdomain ?? "").trim()) deps.log(chalk.dim(`Subdomain sent as ${request.subdomain}.`));
1148
1368
  deps.log(`${request.email} confirms it from the emailed link, or by signing in with the emailed code:`);
1149
1369
  for (const command of next) deps.log(` ${command}`);
1150
1370
  deps.log(chalk.dim("A repeat signup for the same email within an hour normally sends no new email."));
1371
+ if (!created.agentAccess || !target) return 0;
1372
+ deps.log(`An administrator approves the agent at ${created.agentAccess.approvalUrl} (after confirming the signup). Waiting for approval until ${created.agentAccess.expiresAt}...`);
1373
+ const outcome = await awaitAgentCredential(created.agentAccess, target, created.company.name, Boolean(opts.yes), deps);
1374
+ if ("failed" in outcome) return printFailure(outcome.failed, false, deps);
1375
+ deps.log(chalk.green(`Approved. The agent's credential is saved as profile ${outcome.stored}.`));
1151
1376
  return 0;
1152
1377
  }
1153
1378
  /**
@@ -1155,7 +1380,7 @@ async function runSignup(opts, deps = defaultSignupDeps) {
1155
1380
  * function so a test can check the flag parsing without signing up.
1156
1381
  */
1157
1382
  function buildSignupCommand(run = (opts) => runSignup(opts)) {
1158
- return new Command("signup").description("Create a Fluid company with the public signup; the person behind --email confirms it").option("-e, --email <email>", "The person's email address; Fluid emails it to confirm the signup").option("--first-name <name>", "The person's first name").option("--last-name <name>", "The person's last name").option("--company-name <name>", "The company's name").option("--subdomain <subdomain>", "The store's subdomain (acme gives acme.fluid.app); sent lowercase, letters, digits and hyphens only").option("--color <hex>", "Brand colour as 3 or 6 hex digits, such as 0C7CF6").option("-y, --yes", "Sign up without asking").option("--json", "Print the result as JSON").action(async (opts) => {
1383
+ return new Command("signup").description("Create a Fluid company with the public signup; the person behind --email confirms it").option("-e, --email <email>", "The person's email address; Fluid emails it to confirm the signup").option("--first-name <name>", "The person's first name").option("--last-name <name>", "The person's last name").option("--company-name <name>", "The company's name").option("--subdomain <subdomain>", "The store's subdomain (acme gives acme.fluid.app); sent lowercase, letters, digits and hyphens only").option("--color <hex>", "Brand colour as 3 or 6 hex digits, such as 0C7CF6").option("--agent-access [name]", "Also ask for a credential for an agent; waits for an administrator to approve it, then saves it as a profile (when Fluid has agent access enabled)").option("-y, --yes", "Sign up without asking").option("--json", "Print the result as JSON").action(async (opts) => {
1159
1384
  const exitCode = await run(opts);
1160
1385
  if (exitCode !== 0) process.exitCode = exitCode;
1161
1386
  });