@fluid-app/fluid-cli 0.1.808 → 0.1.810
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/dist/bin/fluid.d.mts +1 -1
- package/dist/bin/fluid.mjs +470 -112
- package/dist/bin/fluid.mjs.map +1 -1
- package/dist/{profiles-BxQg0jB_.mjs → client-B1TfaVpZ.mjs} +268 -450
- package/dist/client-B1TfaVpZ.mjs.map +1 -0
- package/dist/client-CqGzBXXg.mjs +1 -0
- package/dist/{hook-CeUgW5IS.mjs → hook-C37dIffA.mjs} +90 -53
- package/dist/hook-C37dIffA.mjs.map +1 -0
- package/dist/index.d.mts +109 -161
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +39 -32
- package/dist/index.mjs.map +1 -1
- package/package.json +7 -7
- package/dist/client-Bg2zc4QQ.mjs +0 -2
- package/dist/hook-CeUgW5IS.mjs.map +0 -1
- package/dist/profiles-BxQg0jB_.mjs.map +0 -1
package/dist/bin/fluid.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fluid.mjs","names":["SITES_PLUGIN","readAll","ADOPT_DEADLINE_MS","ADOPT_DEADLINE_MS","version"],"sources":["../../src/update/notifier.ts","../../src/plugins/discovery.ts","../../src/plugins/prefer-installation.ts","../../src/plugins/missing-plugin.ts","../../src/commands/commands.ts","../../src/completion/complete.ts","../../src/commands/completion.ts","../../src/auth/identity/sign-in-path.ts","../../src/auth/pending-login.ts","../../src/auth/profiles.ts","../../src/utils/shell.ts","../../src/commands/login-identity.ts","../../src/commands/login.ts","../../src/commands/signup.ts","../../src/commands/logout.ts","../../src/commands/profiles.ts","../../src/commands/whoami.ts","../../src/auth/identity/adopt-pending.ts","../../src/auth/identity/switch-adopt.ts","../../src/commands/switch.ts","../../src/plugins/format-load-line.ts","../../src/plugins/resolve-load-path.ts","../../src/plugins/should-log-plugin-loads.ts","../../src/plugins/loader.ts","../../src/commands/version.ts","../../src/auth/identity/adopt-legacy.ts","../../src/auth/identity/prime.ts","../../src/bin/fluid.ts"],"sourcesContent":["/**\n * Tell a person at a terminal, or a coding agent running the CLI for one,\n * that a newer fluid CLI, or a newer Sites plugin beside it, is on npm. npm\n * is asked at most once a day. The check never holds a command open: a run\n * prints what the last check found, and a stale cache is refreshed by a\n * detached child process for next time.\n */\n\nimport { spawn } from \"node:child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport {\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n renameSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { basename, dirname, join, sep } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { LoadedPlugin } from \"../plugins/loader.js\";\n\nexport const PACKAGE_NAME = \"@fluid-app/fluid-cli\";\n/**\n * The plugin that adds the Sites commands. It ships on its own, so a CLI\n * that is up to date can still run a Sites plugin too old for a teammate's\n * site, and its notice is the only hint of that.\n */\nexport const SITES_PLUGIN_NAME = \"@fluid-app/fluid-cli-member-site\";\nexport const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;\n/** The argument the CLI entry point treats as \"refresh the cache and exit\". */\nexport const REFRESH_ARG = \"__refresh-update-check\";\nconst FETCH_TIMEOUT_MS = 5000;\nconst CACHE_FILE = \"update-check.json\";\n/**\n * A coding agent sees the notice once a day: the run that creates the day's\n * claim file, `update-notice-<UTC date>`, shows it. Creating a file that\n * doesn't exist yet succeeds for one run only, however many run at once.\n */\nconst AGENT_NOTICE_CLAIM = \"update-notice-\";\n\nexport interface UpdateCache {\n /** When a check was last started, successful or not. */\n readonly checkedAt: string;\n /** The newest version any check has seen; null before the first success. */\n readonly latest: string | null;\n /** The newest Sites plugin any check has seen; absent before one has. */\n readonly sitesPluginLatest?: string;\n}\n\nexport interface UpdateCheckEnvironment {\n readonly env: NodeJS.ProcessEnv;\n readonly stdoutIsTTY: boolean;\n readonly stderrIsTTY: boolean;\n /** Real path of the running CLI entry point. */\n readonly entryPath: string;\n /** `process.versions`; an `electron` entry means a bundling app runs us. */\n readonly versions?: Partial<Record<string, string>>;\n}\n\n/**\n * Variables coding agents set on the commands they run: the shared\n * `AI_AGENT`, Claude Code, Codex, Cursor's and Gemini's CLIs, and our own\n * `FLUID_AGENT` for any other.\n */\nconst AGENT_ENV = [\n \"FLUID_AGENT\",\n \"AI_AGENT\",\n \"CLAUDECODE\",\n \"CODEX_SANDBOX\",\n \"CODEX_THREAD_ID\",\n \"CURSOR_AGENT\",\n \"GEMINI_CLI\",\n] as const;\n\n/** Whether a coding agent, rather than a person, is running this command. */\nfunction isAgentRun(env: NodeJS.ProcessEnv): boolean {\n return AGENT_ENV.some((name) => {\n const value = env[name]?.trim().toLowerCase();\n return Boolean(value) && value !== \"0\" && value !== \"false\";\n });\n}\n\n/** Who sees the notice: a person at a terminal, a coding agent, or no one. */\nexport type NoticeAudience = \"person\" | \"agent\";\n\n/** Whether an Electron app, such as Mist, is running the CLI it bundles. */\nfunction isElectronRun(\n env: NodeJS.ProcessEnv,\n versions: Partial<Record<string, string>> = {},\n): boolean {\n return Boolean(env[\"ELECTRON_RUN_AS_NODE\"] || versions[\"electron\"]);\n}\n\n/**\n * Only an installed CLI checks, for a person at a terminal or a coding agent\n * (whose output is piped). Other piped runs, CI, a workspace build and a\n * copy an Electron app bundles (the app updates it) stay quiet.\n */\nexport function updateCheckAudience({\n env,\n stdoutIsTTY,\n stderrIsTTY,\n entryPath,\n versions,\n}: UpdateCheckEnvironment): NoticeAudience | null {\n if (env[\"FLUID_NO_UPDATE_CHECK\"] || env[\"NO_UPDATE_NOTIFIER\"]) return null;\n if (env[\"CI\"]) return null;\n if (isElectronRun(env, versions)) return null;\n if (!entryPath.includes(`${sep}node_modules${sep}`)) return null;\n if (stdoutIsTTY && stderrIsTTY) return \"person\";\n return isAgentRun(env) ? \"agent\" : null;\n}\n\nfunction parseVersion(version: string): [number, number, number] | null {\n const match = /^(\\d+)\\.(\\d+)\\.(\\d+)$/.exec(version.trim());\n if (!match) return null;\n return [Number(match[1]), Number(match[2]), Number(match[3])];\n}\n\n/** True when `latest` is a newer release than `current`. Prereleases never count. */\nexport function isNewer(current: string, latest: string): boolean {\n const a = parseVersion(current);\n const b = parseVersion(latest);\n if (!a || !b) return false;\n for (let i = 0; i < 3; i += 1) {\n if (b[i]! !== a[i]!) return b[i]! > a[i]!;\n }\n return false;\n}\n\nexport type PackageManager = \"npm\" | \"pnpm\" | \"yarn\" | \"yarn-classic\" | \"bun\";\n\n/** How the running CLI was installed, which decides the update command. */\nexport type InstallKind =\n | { readonly kind: \"global\"; readonly manager: PackageManager }\n | { readonly kind: \"npx\" }\n | {\n readonly kind: \"local\";\n readonly manager: PackageManager;\n readonly projectDir: string;\n };\n\nconst LOCKFILES: ReadonlyArray<readonly [string, PackageManager]> = [\n [\"pnpm-lock.yaml\", \"pnpm\"],\n [\"bun.lock\", \"bun\"],\n [\"bun.lockb\", \"bun\"],\n [\"yarn.lock\", \"yarn\"],\n [\"package-lock.json\", \"npm\"],\n [\"npm-shrinkwrap.json\", \"npm\"],\n];\n\nfunction projectManager(\n projectDir: string,\n exists: (path: string) => boolean,\n): PackageManager {\n // A workspace member has its lockfile at the workspace root, above it.\n for (let dir = projectDir; ; dir = dirname(dir)) {\n for (const [file, manager] of LOCKFILES) {\n if (!exists(join(dir, file))) continue;\n if (manager !== \"yarn\") return manager;\n return exists(join(dir, \".yarnrc.yml\")) ? \"yarn\" : \"yarn-classic\";\n }\n if (dirname(dir) === dir) return \"npm\";\n }\n}\n\n/**\n * Work out from the entry point's real path how the CLI was installed: an\n * npx cache run, a global install (npm's `lib/node_modules`, or npm on\n * Windows, pnpm's and yarn's global directories), or else a project's own\n * `node_modules`.\n */\nexport function detectInstallKind(\n entryPath: string,\n exists: (path: string) => boolean = existsSync,\n): InstallKind {\n const path = entryPath.replaceAll(\"\\\\\", \"/\");\n if (path.includes(\"/_npx/\")) return { kind: \"npx\" };\n if (/\\/pnpm\\/global\\//i.test(path))\n return { kind: \"global\", manager: \"pnpm\" };\n if (/\\/yarn\\/global\\//i.test(path) || path.includes(\"/.yarn-global/\")) {\n return { kind: \"global\", manager: \"yarn-classic\" };\n }\n if (/\\/\\.bun\\/install\\/global\\//.test(path)) {\n return { kind: \"global\", manager: \"bun\" };\n }\n const modules = path.indexOf(\"/node_modules/\");\n const before = modules === -1 ? path : path.slice(0, modules);\n const projectDir = entryPath.slice(0, modules === -1 ? 0 : modules);\n // npm's global root is `<prefix>/lib`, or `%APPDATA%\\npm` on Windows, and\n // neither holds a package.json. A project that happens to live in a\n // directory named `lib` does, and is updated in place.\n const npmGlobalShape = before.endsWith(\"/lib\") || /\\/npm$/i.test(before);\n if (npmGlobalShape && !exists(join(projectDir, \"package.json\"))) {\n return { kind: \"global\", manager: \"npm\" };\n }\n return {\n kind: \"local\",\n manager: projectManager(projectDir, exists),\n projectDir,\n };\n}\n\nconst PLUGINS_NOTE = \"(and any @fluid-app/fluid-cli-* plugins you use)\";\n\nfunction globalCommand(manager: PackageManager, pkg: string): string {\n switch (manager) {\n case \"npm\":\n return `npm install -g ${pkg}`;\n case \"pnpm\":\n return `pnpm add -g ${pkg}@latest`;\n case \"yarn\":\n case \"yarn-classic\":\n return `yarn global add ${pkg}@latest`;\n case \"bun\":\n return `bun add -g ${pkg}@latest`;\n }\n}\n\nfunction localCommand(manager: PackageManager, pkg: string): string {\n switch (manager) {\n case \"npm\":\n return `npm install ${pkg}@latest`;\n case \"pnpm\":\n return `pnpm update --latest ${pkg}`;\n case \"yarn\":\n return `yarn up ${pkg}@latest`;\n case \"yarn-classic\":\n return `yarn upgrade --latest ${pkg}`;\n case \"bun\":\n return `bun update --latest ${pkg}`;\n }\n}\n\n/** The command that updates `pkg` for this install. */\nexport function updateCommand(install: InstallKind, pkg: string): string {\n switch (install.kind) {\n case \"global\":\n return globalCommand(install.manager, pkg);\n case \"npx\":\n return `npx ${pkg}@latest`;\n case \"local\":\n return localCommand(install.manager, pkg);\n }\n}\n\n/**\n * The line that says how to update `pkg` for this install. The CLI's own\n * names the plugins too, unless a plugin's own notice follows it.\n */\nfunction updateInstruction(\n install: InstallKind,\n pkg: string = PACKAGE_NAME,\n notePlugins = true,\n): string {\n const command = updateCommand(install, pkg);\n const note = notePlugins ? ` ${PLUGINS_NOTE}` : \"\";\n switch (install.kind) {\n case \"global\":\n return `Run: ${command}${note}\\n`;\n case \"npx\":\n return `Run: ${command} to use the latest version\\n`;\n case \"local\":\n return `Run in ${install.projectDir}: ${command}${note}\\n`;\n }\n}\n\nconst OPT_OUT = \"Set FLUID_NO_UPDATE_CHECK=1 to stop these notices.\";\n\n/** A package npm has a newer release of than the copy this run used. */\ninterface PendingUpdate {\n /** How the notice names it. */\n readonly name: string;\n readonly pkg: string;\n readonly installed: string;\n readonly latest: string;\n readonly install: InstallKind;\n}\n\nfunction cliUpdate(\n current: string,\n latest: string,\n install: InstallKind,\n): PendingUpdate | null {\n if (!isNewer(current, latest)) return null;\n return {\n name: \"fluid\",\n pkg: PACKAGE_NAME,\n installed: current,\n latest,\n install,\n };\n}\n\n/** Whether the CLI's update also names the plugins: no plugin's own follows. */\nfunction notesPlugins(\n update: PendingUpdate,\n updates: readonly PendingUpdate[],\n): boolean {\n return (\n update.pkg === PACKAGE_NAME &&\n updates.every(({ pkg }) => pkg === PACKAGE_NAME)\n );\n}\n\n/** A person's notice: each update and how to run it, under one opt-out line. */\nfunction personNotice(updates: readonly PendingUpdate[]): string {\n const bodies = updates.map(\n (update) =>\n `\\nUpdate available for ${update.name}: ${update.installed} → ${update.latest}\\n` +\n updateInstruction(\n update.install,\n update.pkg,\n notesPlugins(update, updates),\n ),\n );\n return `${bodies.join(\"\")}${OPT_OUT}\\n`;\n}\n\n/** A coding agent's notice: one line, with the command for each update. */\nfunction agentNotice(updates: readonly PendingUpdate[]): string {\n const parts = updates.map((update) => {\n const { name, installed, latest, install, pkg } = update;\n const where = install.kind === \"local\" ? ` in ${install.projectDir}` : \"\";\n const plugins = notesPlugins(update, updates)\n ? \", and update any @fluid-app/fluid-cli-* plugins you use\"\n : \"\";\n return `${name} ${installed} → ${latest} (run${where}: ${updateCommand(install, pkg)}${plugins})`;\n });\n return (\n `Update available: ${parts.join(\"; \")}. ` +\n `An older version can lack newer commands, options and config keys. ${OPT_OUT}\\n`\n );\n}\n\nexport function updateNotice(\n current: string,\n latest: string,\n install: InstallKind = { kind: \"global\", manager: \"npm\" },\n): string | null {\n const update = cliUpdate(current, latest, install);\n return update && personNotice([update]);\n}\n\n/**\n * The packages Mist ships: under its app's resources, in\n * `app.asar.unpacked/node_modules/@fluid-app/`. Its app is a\n * `Fluid Mist.app` bundle on macOS, wherever it was moved; its Windows\n * installer puts it in `%LOCALAPPDATA%\\mist-desktop\\app-<version>`, and\n * its Linux packages in `/usr/lib/mist-desktop`.\n */\nconst MIST_PACKAGES = new RegExp(\n \"(?:\" +\n [\n String.raw`[\\\\/]Fluid Mist\\.app[\\\\/]Contents[\\\\/]Resources`,\n String.raw`^[a-z]:[\\\\/]Users[\\\\/][^\\\\/]+[\\\\/]AppData[\\\\/]Local[\\\\/]mist-desktop[\\\\/]app-[^\\\\/]+[\\\\/]resources`,\n String.raw`^/usr/lib/mist-desktop/resources`,\n ].join(\"|\") +\n \")\" +\n String.raw`[\\\\/]app\\.asar\\.unpacked[\\\\/]node_modules[\\\\/]@fluid-app[\\\\/]`,\n \"i\",\n);\n\n/**\n * Whether the package at `path` is a copy Mist ships, which updates with\n * Mist. Mist also runs other CLIs, such as a project's own, through\n * Electron, so its path decides, not how it runs.\n */\nexport function isMistBundled(path: string): boolean {\n return MIST_PACKAGES.test(path);\n}\n\n/**\n * Whether the install root `root` is an Electron app's unpacked resources:\n * an `app.asar.unpacked` folder beside the app's `app.asar` archive, which\n * Electron always writes together. No package manager command updates a\n * copy there, whichever app it came with; a project folder that is only\n * named so has no archive beside it.\n */\nexport function isAppResources(root: string): boolean {\n if (basename(root).toLowerCase() !== \"app.asar.unpacked\") return false;\n try {\n return statSync(join(dirname(root), \"app.asar\")).isFile();\n } catch {\n return false;\n }\n}\n\n/** The folder before the first `node_modules` in a path: its install's root. */\nexport function installRoot(path: string): string | null {\n const at = path.replaceAll(\"\\\\\", \"/\").indexOf(\"/node_modules/\");\n return at === -1 ? null : path.slice(0, at);\n}\n\n/**\n * The version and install root of `pkg` loaded from `source`, read from its\n * package.json. Null for a workspace build, which no notice is for, or when\n * the file can't be read.\n */\nexport function loadedPackage(\n source: string,\n pkg: string,\n): { version: string; root: string } | null {\n let path: string;\n try {\n path = fileURLToPath(source);\n } catch {\n return null;\n }\n const marker = `/node_modules/${pkg}/`;\n const at = path.replaceAll(\"\\\\\", \"/\").lastIndexOf(marker);\n const root = installRoot(path);\n if (at === -1 || root === null) return null;\n try {\n const { version } = JSON.parse(\n readFileSync(\n join(path.slice(0, at + marker.length), \"package.json\"),\n \"utf8\",\n ),\n ) as { version?: unknown };\n return typeof version === \"string\" ? { version, root } : null;\n } catch {\n return null;\n }\n}\n\n/**\n * How `pkg`, installed under `root`, was installed, read from its own path\n * as the CLI's is: globally, by an npx run, or in a project, updated with\n * that project's package manager.\n */\nexport function packageInstallKind(root: string, pkg: string): InstallKind {\n return detectInstallKind(join(root, \"node_modules\", pkg, \"package.json\"));\n}\n\n/**\n * The Sites plugin's update, for the copy this run loaded, when npm has a\n * newer one. An npx run fetches its packages each time, so it has none.\n */\nfunction sitesPluginUpdate(\n options: StartUpdateCheckOptions,\n latest: string | undefined,\n): PendingUpdate | null {\n if (!latest) return null;\n const plugin = options\n .loadedPlugins?.()\n .find((loaded) => loaded.name === SITES_PLUGIN_NAME);\n const installed = plugin && loadedPackage(plugin.source, SITES_PLUGIN_NAME);\n if (!installed || !isNewer(installed.version, latest)) return null;\n const install = packageInstallKind(installed.root, SITES_PLUGIN_NAME);\n if (install.kind === \"npx\") return null;\n return {\n name: \"the Sites plugin (fluid sites)\",\n pkg: SITES_PLUGIN_NAME,\n installed: installed.version,\n latest,\n install,\n };\n}\n\n/** Everything the last check found to update. */\nfunction pendingUpdates(\n options: StartUpdateCheckOptions,\n cache: UpdateCache,\n): PendingUpdate[] {\n const cli = cache.latest\n ? cliUpdate(\n options.currentVersion,\n cache.latest,\n detectInstallKind(options.entryPath),\n )\n : null;\n const plugin = sitesPluginUpdate(options, cache.sitesPluginLatest);\n return [cli, plugin].filter((update) => update !== null);\n}\n\nexport function readUpdateCache(configDir: string): UpdateCache | null {\n try {\n const data = JSON.parse(\n readFileSync(join(configDir, CACHE_FILE), \"utf8\"),\n ) as Partial<UpdateCache>;\n if (typeof data.checkedAt !== \"string\") return null;\n const latest = typeof data.latest === \"string\" ? data.latest : null;\n return {\n checkedAt: data.checkedAt,\n latest,\n ...(typeof data.sitesPluginLatest === \"string\"\n ? { sitesPluginLatest: data.sitesPluginLatest }\n : {}),\n };\n } catch {\n return null;\n }\n}\n\n/**\n * Write the cache, reporting whether it landed. The JSON goes to a fresh\n * file opened exclusively, then is renamed over the cache: a rename replaces\n * a symlink planted at the cache path instead of writing through it, so a\n * shared FLUID_CONFIG_DIR can't aim this write at another of the user's files.\n */\nexport function writeUpdateCache(\n configDir: string,\n cache: UpdateCache,\n): boolean {\n const temp = join(\n configDir,\n `.${CACHE_FILE}.${randomBytes(6).toString(\"hex\")}`,\n );\n try {\n mkdirSync(configDir, { recursive: true });\n writeFileSync(temp, JSON.stringify(cache) + \"\\n\", { flag: \"wx\" });\n renameSync(temp, join(configDir, CACHE_FILE));\n return true;\n } catch {\n // A read-only config directory only costs the notice.\n try {\n rmSync(temp, { force: true });\n } catch {\n // Nothing was written if the directory itself is unusable.\n }\n return false;\n }\n}\n\nexport function isStale(cache: UpdateCache | null, now: Date): boolean {\n if (!cache) return true;\n const checkedAt = Date.parse(cache.checkedAt);\n return (\n Number.isNaN(checkedAt) || now.getTime() - checkedAt >= CHECK_INTERVAL_MS\n );\n}\n\nexport async function fetchLatestVersion(\n fetchImpl: typeof fetch = fetch,\n pkg: string = PACKAGE_NAME,\n): Promise<string | null> {\n try {\n const response = await fetchImpl(\n `https://registry.npmjs.org/${pkg}/latest`,\n { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) },\n );\n if (!response.ok) return null;\n const body = (await response.json()) as { version?: unknown };\n return typeof body.version === \"string\" ? body.version : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Ask npm for the latest CLI and Sites plugin and record them. Runs in the\n * detached child; a failure leaves the last known versions and the throttle\n * stamp in place.\n */\nexport async function refreshUpdateCache(\n configDir: string,\n fetchImpl: typeof fetch = fetch,\n now: Date = new Date(),\n): Promise<void> {\n const [latest, sitesPluginLatest] = await Promise.all([\n fetchLatestVersion(fetchImpl),\n fetchLatestVersion(fetchImpl, SITES_PLUGIN_NAME),\n ]);\n if (!latest && !sitesPluginLatest) return;\n const known = readUpdateCache(configDir);\n const plugin = sitesPluginLatest ?? known?.sitesPluginLatest;\n writeUpdateCache(configDir, {\n checkedAt: now.toISOString(),\n latest: latest ?? known?.latest ?? null,\n ...(plugin ? { sitesPluginLatest: plugin } : {}),\n });\n}\n\n/** Start `node <entry> __refresh-update-check` detached, so this run never waits on npm. */\nexport function spawnRefresh(entryPath: string): void {\n try {\n const child = spawn(process.execPath, [entryPath, REFRESH_ARG], {\n detached: true,\n stdio: \"ignore\",\n windowsHide: true,\n });\n child.on(\"error\", () => {});\n child.unref();\n } catch {\n // No refresh this time; the throttle stamp retries tomorrow.\n }\n}\n\nexport interface StartUpdateCheckOptions extends UpdateCheckEnvironment {\n readonly currentVersion: string;\n readonly configDir: string;\n readonly now?: Date;\n /** Called with the notice when the process exits. */\n readonly onExit?: (listener: () => void) => void;\n /**\n * The plugins the run loaded, asked for at exit: the Sites plugin's notice\n * is for the copy that ran. Without it there is no plugin notice.\n */\n readonly loadedPlugins?: () => readonly LoadedPlugin[];\n /**\n * Whether the command that ran keeps the notice from `audience`, asked at\n * exit: an agent's from JSON it may merge stderr into, and anyone's from\n * a command such as `fluid version`, which reports updates itself.\n */\n readonly quiet?: (audience: NoticeAudience) => boolean;\n readonly refresh?: (entryPath: string) => void;\n}\n\n/** The name of the claim file for the UTC day `now` falls on. */\nfunction agentNoticeClaim(now: Date): string {\n return `${AGENT_NOTICE_CLAIM}${now.toISOString().slice(0, 10)}`;\n}\n\n/**\n * Show an agent the notice if this run is the first to claim the day. The\n * claim is created exclusively, so it never writes through a planted link,\n * and an unwritable config directory shows an agent nothing. Earlier days'\n * claims are removed; a later day's, from a run that started after this\n * one's day ended, is kept.\n */\nfunction showAgentNotice(\n configDir: string,\n updates: readonly PendingUpdate[],\n now: Date,\n): void {\n const claim = agentNoticeClaim(now);\n try {\n writeFileSync(join(configDir, claim), \"\", { flag: \"wx\" });\n } catch {\n return;\n }\n process.stderr.write(agentNotice(updates));\n try {\n for (const name of readdirSync(configDir)) {\n // The ISO dates sort as text, so this removes only earlier days.\n if (name.startsWith(AGENT_NOTICE_CLAIM) && name < claim) {\n rmSync(join(configDir, name), { force: true });\n }\n }\n } catch {\n // An old claim left behind costs nothing.\n }\n}\n\n/**\n * Print the cached notice when the command finishes (to an agent, at most\n * once a day) and, when the last check started a day ago or more, stamp the\n * cache and refresh it in a detached process. The stamp throttles failed and\n * concurrent checks to one a day while keeping the last known version, and\n * its notice, in place.\n */\nexport function startUpdateCheck(options: StartUpdateCheckOptions): void {\n const audience = updateCheckAudience(options);\n if (!audience) return;\n\n const now = options.now ?? new Date();\n const cache = readUpdateCache(options.configDir);\n if (cache?.latest || cache?.sitesPluginLatest) {\n const onExit =\n options.onExit ??\n ((listener: () => void) => process.once(\"exit\", listener));\n // Worked out at exit, so a run never waits on the plugin's package.json.\n onExit(() => {\n if (options.quiet?.(audience)) return;\n // Most of an agent's commands end after the day is claimed, so that is\n // checked before any install is looked at.\n if (\n audience === \"agent\" &&\n existsSync(join(options.configDir, agentNoticeClaim(now)))\n ) {\n return;\n }\n const updates = pendingUpdates(options, cache);\n if (updates.length === 0) return;\n if (audience === \"person\") process.stderr.write(personNotice(updates));\n else showAgentNotice(options.configDir, updates, now);\n });\n }\n\n if (!isStale(cache, now)) return;\n const stamped = writeUpdateCache(options.configDir, {\n checkedAt: now.toISOString(),\n latest: cache?.latest ?? null,\n ...(cache?.sitesPluginLatest\n ? { sitesPluginLatest: cache.sitesPluginLatest }\n : {}),\n });\n // Without the stamp there is no throttle, and the child couldn't record\n // what it found either, so an unwritable cache never starts a refresh.\n if (stamped) (options.refresh ?? spawnRefresh)(options.entryPath);\n}\n","/**\n * Auto-discover @fluid-app CLI plugins.\n *\n * Three discovery strategies run in order:\n *\n * 1a. **node_modules scan (cwd)** — look in `<cwd>/node_modules/@fluid-app/`\n * for directories whose names match the plugin naming convention.\n * This is the primary mechanism for project-local plugin installs.\n *\n * 1b. **node_modules scan (CLI install location)** — look in the\n * `node_modules/@fluid-app/` directory containing the CLI core package\n * itself. This covers global installs where plugins are sibling packages\n * under the same global `node_modules/`.\n *\n * 2. **Workspace scan** — walk upward from the CLI core package root to the\n * monorepo workspace root, then scan `packages/` for sibling plugin\n * packages. This covers the pnpm-workspace development case where\n * plugins are not symlinked into `node_modules`.\n *\n * Only first-party @fluid-app scoped packages are loaded.\n */\n\nimport { isStrictConfig } from \"../config/strict.js\";\nimport { existsSync, readFileSync, readdirSync, realpathSync } from \"node:fs\";\nimport { dirname, isAbsolute, join, relative } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\n\nconst PLUGIN_SCOPE = \"@fluid-app\";\n\n/**\n * A plugin package name must match one of these patterns:\n * - @fluid-app/fluid-cli-* (standard)\n * - @fluid-app/*-cli-commands (v2025-06 style)\n */\nfunction isPluginName(packageName: string): boolean {\n if (!packageName.startsWith(`${PLUGIN_SCOPE}/`)) return false;\n const bare = packageName.slice(`${PLUGIN_SCOPE}/`.length);\n return bare.startsWith(\"fluid-cli-\") || bare.endsWith(\"-cli-commands\");\n}\n\n// Strategy 1: node_modules scan (production / published installs)\n\nfunction discoverFromNodeModules(basePath: string): DiscoveredPlugin[] {\n const scopeDir = join(basePath, \"node_modules\", PLUGIN_SCOPE);\n\n if (!existsSync(scopeDir)) return [];\n\n return readdirSync(scopeDir, { withFileTypes: true })\n .filter(\n (entry) =>\n (entry.isDirectory() || entry.isSymbolicLink()) &&\n isPluginName(`${PLUGIN_SCOPE}/${entry.name}`),\n )\n .map((entry) => {\n const name = `${PLUGIN_SCOPE}/${entry.name}`;\n const entryDir = join(scopeDir, entry.name);\n // Resolve symlinks (pnpm workspace links) to file:// URLs so the\n // dynamic import works regardless of pnpm's strict module resolution.\n try {\n const realDir = realpathSync(entryDir);\n const distEntry = join(realDir, \"dist\", \"index.mjs\");\n if (existsSync(distEntry)) {\n return { name, importSpecifier: pathToFileURL(distEntry).href };\n }\n } catch {\n // Broken symlink or other fs error — fall through to bare specifier\n }\n // Fallback to bare specifier for non-workspace (published) installs\n return { name, importSpecifier: name };\n });\n}\n\n// Strategy 2: workspace scan (pnpm monorepo development)\n\nfunction findWorkspaceRoot(startDir: string): string | null {\n let dir = startDir;\n while (true) {\n if (\n existsSync(join(dir, \"pnpm-workspace.yaml\")) ||\n existsSync(join(dir, \"pnpm-workspace.yml\"))\n ) {\n return dir;\n }\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\nfunction readPackageName(dir: string): string | null {\n const pkgPath = join(dir, \"package.json\");\n if (!existsSync(pkgPath)) return null;\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as {\n name?: string;\n };\n return pkg.name ?? null;\n } catch {\n return null;\n }\n}\n\nexport interface DiscoveredPlugin {\n name: string;\n importSpecifier: string;\n}\n\nexport interface PluginDiscoveryOptions {\n /**\n * Prefer plugins installed beside this CLI over same-named packages in the\n * target project's node_modules. Desktop callers use this so an older\n * project-local plugin cannot override the command contract bundled with\n * the app. Normal project-local CLI invocations keep the existing order.\n */\n preferInstallation?: boolean;\n /**\n * Load only plugins whose entry file, after realpath, sits under the CLI\n * installation's own node_modules, or under the CLI's own monorepo\n * `packages/` when the CLI core is at `<workspace>/packages/cli/core`.\n * A bare plugin name is resolved by Node itself, as the loader's import\n * would, and the file it resolves to is what gets imported. No other\n * directory is trusted, and a plugin that cannot be resolved or placed\n * under one of those two is skipped. Used for the input-resolve pass, which runs\n * before the user has approved anything.\n */\n installationOnly?: boolean;\n /** Test seam: resolves a bare specifier to a file URL the way Node does. */\n resolveSpecifier?: (specifier: string) => string;\n /** Test seam for the CLI core package directory. */\n coreDir?: string;\n /** Test seam for the directory containing the CLI installation. */\n installationBasePath?: string;\n}\n\nfunction discoverFromWorkspace(startDir: string): DiscoveredPlugin[] {\n const workspaceRoot = findWorkspaceRoot(startDir);\n if (!workspaceRoot) return [];\n\n const results: DiscoveredPlugin[] = [];\n const packagesDir = join(workspaceRoot, \"packages\");\n if (!existsSync(packagesDir)) return [];\n\n // Scan exactly two levels deep under packages/ (e.g. packages/cli/themes,\n // packages/cli/v2025-06). This matches the monorepo convention where all\n // packages live at packages/<domain>/<package>/.\n // If a plugin is added at a different depth, update this scan accordingly.\n let domainDirs: string[];\n try {\n domainDirs = readdirSync(packagesDir, { withFileTypes: true })\n .filter((e) => e.isDirectory())\n .map((e) => join(packagesDir, e.name));\n } catch {\n return [];\n }\n\n for (const domainDir of domainDirs) {\n let subDirs: string[];\n try {\n subDirs = readdirSync(domainDir, { withFileTypes: true })\n .filter((e) => e.isDirectory())\n .map((e) => join(domainDir, e.name));\n } catch {\n continue;\n }\n\n for (const subDir of subDirs) {\n const name = readPackageName(subDir);\n if (!name || !name.startsWith(`${PLUGIN_SCOPE}/`) || !isPluginName(name))\n continue;\n\n const distEntry = join(subDir, \"dist\", \"index.mjs\");\n if (!existsSync(distEntry)) {\n continue;\n }\n\n results.push({\n name,\n importSpecifier: pathToFileURL(distEntry).href,\n });\n }\n }\n\n return results;\n}\n\n// Exported API\n\n/** Resolved once — the CLI core package root (`packages/cli/core/`). */\nexport const corePackageDir = dirname(\n dirname(dirname(fileURLToPath(import.meta.url))),\n);\n\n/**\n * The monorepo the CLI core at `coreDir` was built in: its workspace root,\n * found walking up from `searchFrom`, when the core is that workspace's\n * `packages/cli/core`. Null for any installed copy.\n */\nexport function cliWorkspaceRoot(\n coreDir: string = corePackageDir,\n searchFrom: string = coreDir,\n): string | null {\n const workspace = findWorkspaceRoot(searchFrom);\n if (workspace === null) return null;\n try {\n return relative(realpathSync(workspace), realpathSync(coreDir)) ===\n join(\"packages\", \"cli\", \"core\")\n ? workspace\n : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Discover installed plugin packages. Returns a de-duplicated, sorted list\n * of `{ name, importSpecifier }` objects.\n *\n * @param basePath - Directory to scan for `node_modules/@fluid-app/`\n * @param searchFrom - Starting directory for workspace root detection\n * (walked upward via `findWorkspaceRoot`). Pass `null` to skip workspace\n * scanning (useful in tests). Defaults to `corePackageDir`.\n */\nexport function discoverPlugins(\n basePath: string,\n searchFrom?: string | null,\n options: PluginDiscoveryOptions = {},\n): DiscoveredPlugin[] {\n const seen = new Set<string>();\n const results: DiscoveredPlugin[] = [];\n\n const addPlugins = (plugins: DiscoveredPlugin[]) => {\n for (const plugin of plugins) {\n if (seen.has(plugin.name)) continue;\n seen.add(plugin.name);\n results.push(plugin);\n }\n };\n\n const cliParent =\n options.installationBasePath ?? dirname(dirname(dirname(corePackageDir)));\n const projectPlugins = () =>\n isStrictConfig() ? [] : discoverFromNodeModules(basePath);\n const installationPlugins = () =>\n cliParent === basePath && !isStrictConfig()\n ? []\n : discoverFromNodeModules(cliParent);\n const workspacePlugins = () => {\n if (searchFrom === null) return [];\n return discoverFromWorkspace(\n searchFrom ?? options.coreDir ?? corePackageDir,\n );\n };\n\n if (options.installationOnly) {\n const trustedRoots: string[] = [];\n const trust = (dir: string | null) => {\n if (dir === null) return;\n try {\n trustedRoots.push(realpathSync(dir));\n } catch {}\n };\n trust(join(cliParent, \"node_modules\"));\n const workspace =\n searchFrom === null\n ? null\n : cliWorkspaceRoot(options.coreDir ?? corePackageDir, searchFrom);\n if (workspace !== null) trust(join(workspace, \"packages\"));\n const resolveBare =\n options.resolveSpecifier ?? ((name: string) => import.meta.resolve(name));\n const inside = (file: string): boolean =>\n trustedRoots.some((root) => {\n const rel = relative(root, file);\n return rel !== \"\" && !rel.startsWith(\"..\") && !isAbsolute(rel);\n });\n const validated = (plugin: DiscoveredPlugin): DiscoveredPlugin | null => {\n try {\n const file = plugin.importSpecifier.startsWith(\"file:\")\n ? fileURLToPath(plugin.importSpecifier)\n : fileURLToPath(resolveBare(plugin.name));\n const real = realpathSync(file);\n return inside(real)\n ? { name: plugin.name, importSpecifier: pathToFileURL(real).href }\n : null;\n } catch {\n return null;\n }\n };\n const keep = (plugins: DiscoveredPlugin[]): DiscoveredPlugin[] =>\n plugins.flatMap((plugin) => validated(plugin) ?? []);\n addPlugins(keep(discoverFromNodeModules(cliParent)));\n if (workspace !== null) addPlugins(keep(workspacePlugins()));\n } else if (options.preferInstallation) {\n addPlugins(installationPlugins());\n // In a monorepo development build, resolveFluidBinary() deliberately\n // realpaths the CLI into packages/cli/core. Its sibling plugins are then\n // discovered from the workspace rather than an installation-level\n // node_modules, so they are part of the same trusted CLI installation.\n addPlugins(workspacePlugins());\n addPlugins(projectPlugins());\n } else {\n addPlugins(projectPlugins());\n addPlugins(installationPlugins());\n addPlugins(workspacePlugins());\n }\n\n return results.sort((a, b) => a.name.localeCompare(b.name));\n}\n\n/**\n * Dynamically import a plugin module and return its default export.\n *\n * @internal Not intended for external callers. Only called with specifiers\n * produced by {@link discoverPlugins}:\n * - bare package names (e.g. `@fluid-app/fluid-cli-portal`) from the\n * node_modules scan, validated by {@link isPluginName}.\n * - `file://` URLs from {@link discoverFromWorkspace}, which constructs\n * them internally from validated workspace paths (`packages/` tree,\n * `dist/index.mjs`). These are trusted internal specifiers.\n */\nexport async function importPlugin(specifier: string): Promise<unknown> {\n // file:// URLs are trusted — they originate from discoverFromWorkspace\n // which builds them from validated workspace paths under packages/.\n // For bare package names, verify they match the plugin naming convention.\n if (!specifier.startsWith(\"file://\") && !isPluginName(specifier)) {\n throw new Error(`Refusing to import non-plugin package: ${specifier}`);\n }\n const mod = (await import(specifier)) as Record<string, unknown>;\n return mod[\"default\"] ?? mod;\n}\n","/**\n * Whether a host that owns this CLI run, such as Mist, asked for the plugins\n * installed beside the CLI over a project's own (FLUID_CLI_PREFER_INSTALLATION_PLUGINS=1).\n */\nexport function prefersInstallationPlugins(\n env: NodeJS.ProcessEnv = process.env,\n): boolean {\n return env[\"FLUID_CLI_PREFER_INSTALLATION_PLUGINS\"] === \"1\";\n}\n","import type { Command } from \"commander\";\nimport { realpathSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { readConfig } from \"../config/config.js\";\nimport {\n SITES_PLUGIN_NAME as SITES_PLUGIN,\n installRoot,\n isAppResources,\n isMistBundled,\n} from \"../update/notifier.js\";\nimport { cliWorkspaceRoot } from \"./discovery.js\";\nimport { prefersInstallationPlugins } from \"./prefer-installation.js\";\n\n/** How a Mist dev build builds the plugins its workspace CLI loads. */\nconst MIST_RUNTIME_BUILD =\n \"pnpm --filter mist-desktop build:runtime-deps, then restart Mist\";\n\n/** The Sites plugin's top-level commands: core can't ask an unloaded plugin. */\nconst SITES_COMMANDS = new Set([\"sites\", \"deploy\", \"member-site\", \"vault\"]);\n\nexport interface MissingPluginOptions {\n /** The config's allow-list; read from the config when left out. */\n readonly enabledPlugins?: readonly string[] | null;\n /** Real path of a file in the running CLI's package. */\n readonly entryPath?: string;\n /** The monorepo the running CLI was built in; null for an installed copy. */\n readonly workspaceRoot?: string | null;\n /** Whether Mist runs this CLI; read from the environment when left out. */\n readonly preferInstallation?: boolean;\n}\n\n/**\n * What gets the Sites plugin for the running CLI, as a clause. A workspace\n * build loads the plugin's own build in its checkout, which only building it\n * makes, through Mist's runtime build when Mist runs it (Mist's CLI runs\n * prefer installation plugins). A copy an app bundles,\n * such as Mist's, comes with that app, so no global install reaches it. Any\n * other copy installs it with npm.\n */\nfunction pluginStep(\n entryPath: string,\n workspaceRoot: string | null,\n mist: boolean,\n): string {\n if (workspaceRoot !== null) {\n const build = mist\n ? MIST_RUNTIME_BUILD\n : `pnpm --filter ${SITES_PLUGIN} build`;\n return `build it in ${workspaceRoot} with ${build}`;\n }\n if (isMistBundled(entryPath)) {\n return \"reinstall or update Mist, which ships the Sites plugin\";\n }\n const root = installRoot(entryPath);\n if (root !== null && isAppResources(root)) {\n return \"reinstall or update the app this CLI comes with, which ships the Sites plugin\";\n }\n return `install or update it with npm install -g ${SITES_PLUGIN}`;\n}\n\n/**\n * Why `fluid <name>` (or `fluid help <name>`) is missing when the Sites plugin\n * adds it and no loaded plugin did, since commander's \"unknown command\" reads\n * as if Fluid has no Sites, and what gets the plugin for this CLI. When\n * `enabledPlugins` leaves the plugin out, an install changes nothing, so the\n * hint says to add it there first. Null otherwise.\n */\nexport function missingPluginHint(\n program: Command,\n args: readonly string[],\n options: MissingPluginOptions = {},\n): string | null {\n const name = args[0] === \"help\" ? args[1] : args[0];\n if (name === undefined || !SITES_COMMANDS.has(name)) return null;\n const loaded = program.commands.some(\n (command) => command.name() === name || command.aliases().includes(name),\n );\n if (loaded) return null;\n const enabledPlugins =\n options.enabledPlugins === undefined\n ? readConfig().enabledPlugins\n : options.enabledPlugins;\n const step = pluginStep(\n options.entryPath ?? realpathSync(fileURLToPath(import.meta.url)),\n options.workspaceRoot === undefined\n ? cliWorkspaceRoot()\n : options.workspaceRoot,\n options.preferInstallation ?? prefersInstallationPlugins(),\n );\n const reason =\n enabledPlugins !== null && !enabledPlugins.includes(SITES_PLUGIN)\n ? `which enabledPlugins in your Fluid config leaves out. Add ${SITES_PLUGIN} to it, and if it still isn't loaded, ${step}`\n : `which is not loaded. To load it, ${step}`;\n return `fluid ${name} comes from the Sites plugin, ${reason}.`;\n}\n","/**\n * fluid commands — list every installed command, or print the catalog as\n * JSON for agents and documentation generators.\n */\n\nimport { Command } from \"commander\";\nimport { createRequire } from \"node:module\";\nimport {\n filterCatalog,\n rootCommand,\n walkCommands,\n type CatalogEntry,\n} from \"../catalog/walk.js\";\nimport { missingPluginHint } from \"../plugins/missing-plugin.js\";\n\nconst require = createRequire(import.meta.url);\nconst { version } = require(\"../../package.json\") as { version: string };\n\nfunction usage(entry: CatalogEntry): string {\n const args = entry.arguments.map((arg) => {\n const name = arg.variadic ? `${arg.name}...` : arg.name;\n return arg.required ? `<${name}>` : `[${name}]`;\n });\n return [entry.command, ...args].join(\" \");\n}\n\nexport function formatCatalogText(entries: readonly CatalogEntry[]): string {\n const runnable = entries.filter((entry) => entry.runnable);\n const width = Math.min(\n 48,\n Math.max(0, ...runnable.map((entry) => usage(entry).length)),\n );\n return runnable\n .map((entry) => {\n const line = usage(entry);\n const summary = entry.description.split(\"\\n\", 1)[0] ?? \"\";\n return summary ? `${line.padEnd(width)} ${summary}` : line;\n })\n .join(\"\\n\");\n}\n\nexport const commandsCommand = new Command(\"commands\")\n .description(\"List installed commands; --json prints the full catalog\")\n .argument(\"[prefix...]\", \"Only list commands under this one, e.g. `domains`\")\n .option(\"--json\", \"Print the catalog as JSON\", false)\n .action((prefix: string[], opts: { json: boolean }, command: Command) => {\n const root = rootCommand(command);\n\n const entries = filterCatalog(walkCommands(root), root, prefix);\n if (entries.length === 0) {\n const hint = missingPluginHint(root, prefix);\n process.stderr.write(\n JSON.stringify({\n error: `No command named \"${prefix.join(\" \")}\".`,\n ...(hint ? { hint } : {}),\n }) + \"\\n\",\n );\n process.exitCode = 1;\n return;\n }\n\n if (opts.json) {\n process.stdout.write(\n JSON.stringify(\n { cli: root.name(), version, commands: entries },\n null,\n 2,\n ) + \"\\n\",\n );\n return;\n }\n process.stdout.write(formatCatalogText(entries) + \"\\n\");\n });\n","/**\n * Shell completion. The scripts `fluid completion <shell>` prints pipe the\n * words typed so far into the hidden `fluid __complete`, so completions come\n * from the plugins actually installed rather than a list frozen at install.\n * The words go over stdin, never argv: a half-typed `--token <value>` must\n * not show up in another user's process list.\n */\n\nimport type { Command, Option } from \"commander\";\nimport { visibleOptions, visibleSubcommands } from \"../catalog/walk.js\";\n\nexport const SHELLS = [\"bash\", \"zsh\", \"fish\"] as const;\nexport type Shell = (typeof SHELLS)[number];\n\nexport interface Candidate {\n readonly value: string;\n readonly description: string;\n}\n\nfunction findOption(chain: readonly Command[], word: string): Option | null {\n const flag = word.split(\"=\", 1)[0] ?? word;\n for (const command of [...chain].reverse()) {\n const match = command.options.find(\n (option) => option.long === flag || option.short === flag,\n );\n if (match) return match;\n }\n return null;\n}\n\nfunction splitAssignment(word: string): [string, string] {\n const at = word.indexOf(\"=\");\n return [word.slice(0, at), word.slice(at + 1)];\n}\n\nfunction choicesFor(option: Option, typed: string): Candidate[] {\n return (option.argChoices ?? [])\n .filter((choice) => choice.startsWith(typed))\n .map((choice) => ({ value: choice, description: \"\" }));\n}\n\nfunction findSubcommand(command: Command, word: string): Command | null {\n return (\n visibleSubcommands(command).find(\n (sub) => sub.name() === word || sub.aliases().includes(word),\n ) ?? null\n );\n}\n\n/**\n * Complete the last of `words`, the words after the program name.\n * Where a flag's value is expected, offers the flag's choices if it has\n * any; otherwise returns nothing so the shell falls back to files.\n */\nexport function completeWords(\n root: Command,\n words: readonly string[],\n): Candidate[] {\n const partial = words.at(-1) ?? \"\";\n const chain: Command[] = [root];\n let current = root;\n let awaitingValue: Option | null = null;\n let operandsOnly = false;\n // Operands typed for `current`; only the first can name a subcommand.\n let operands = 0;\n\n const prior = words.slice(0, -1);\n for (const [index, word] of prior.entries()) {\n if (awaitingValue) {\n // Bash splits `--flag=value` at the `=`, so the value follows it.\n if (word !== \"=\" || prior[index - 1] === \"=\") awaitingValue = null;\n continue;\n }\n if (!operandsOnly && word === \"--\") {\n operandsOnly = true;\n continue;\n }\n if (!operandsOnly && word.startsWith(\"-\")) {\n const option = findOption(chain, word);\n awaitingValue = option?.required && !word.includes(\"=\") ? option : null;\n continue;\n }\n const sub = operands === 0 ? findSubcommand(current, word) : null;\n if (sub) {\n current = sub;\n chain.push(sub);\n } else {\n operands += 1;\n }\n }\n\n if (awaitingValue) {\n // After bash's split the partial is the bare `=` before any value.\n const typed = partial === \"=\" ? \"\" : partial;\n return choicesFor(awaitingValue, typed);\n }\n\n if (!operandsOnly && partial.startsWith(\"--\") && partial.includes(\"=\")) {\n // zsh and fish keep `--flag=value` as one word, and so must the reply.\n const [flag = \"\", typed = \"\"] = splitAssignment(partial);\n const option = findOption(chain, flag);\n if (!option?.required && !option?.optional) return [];\n return choicesFor(option, typed).map((choice) => ({\n ...choice,\n value: `${flag}=${choice.value}`,\n }));\n }\n\n if (!operandsOnly && partial.startsWith(\"-\")) {\n const seen = new Set<string>();\n const candidates: Candidate[] = [];\n for (const command of [...chain].reverse()) {\n for (const option of visibleOptions(command)) {\n // The program's --version belongs to `fluid` alone.\n if (option.long === \"--version\" && command !== current) continue;\n for (const value of [option.long, option.short]) {\n if (!value || seen.has(value)) continue;\n seen.add(value);\n candidates.push({ value, description: option.description });\n }\n }\n }\n candidates.push({ value: \"--help\", description: \"Show help\" });\n return candidates.filter((c) => c.value.startsWith(partial));\n }\n\n const candidates: Candidate[] = [];\n if (operands === 0) {\n for (const sub of visibleSubcommands(current)) {\n for (const name of [sub.name(), ...sub.aliases()]) {\n candidates.push({ value: name, description: sub.description() });\n }\n }\n }\n const args = current.registeredArguments;\n const last = args.at(-1);\n const argument = args[operands] ?? (last?.variadic ? last : undefined);\n for (const choice of argument?.argChoices ?? []) {\n candidates.push({\n value: choice,\n description: argument?.description ?? \"\",\n });\n }\n return candidates.filter((c) => c.value.startsWith(partial));\n}\n\n/**\n * The words the scripts pipe in: each followed by a NUL, the program name\n * first. Returns the words after the program name, at least one.\n */\nexport function parseCompletionInput(input: string): string[] {\n const words = input.split(\"\\0\");\n // The text after the last NUL is the empty tail of the final terminator.\n words.pop();\n const typed = words.slice(1);\n return typed.length > 0 ? typed : [\"\"];\n}\n\nfunction firstLine(text: string): string {\n return text.split(\"\\n\", 1)[0]?.trim() ?? \"\";\n}\n\n/** One candidate per line, in the shape each shell's script reads. */\nexport function formatCandidates(\n candidates: readonly Candidate[],\n shell: Shell,\n): string {\n const lines = candidates.map(({ value, description }) => {\n const summary = firstLine(description);\n switch (shell) {\n case \"bash\":\n return value;\n case \"zsh\":\n // _describe splits on the first unescaped colon.\n return summary\n ? `${value.replaceAll(\":\", \"\\\\:\")}:${summary}`\n : value.replaceAll(\":\", \"\\\\:\");\n case \"fish\":\n return summary ? `${value}\\t${summary}` : value;\n }\n });\n return lines.length > 0 ? `${lines.join(\"\\n\")}\\n` : \"\";\n}\n\nexport function completionScript(shell: Shell): string {\n switch (shell) {\n case \"bash\":\n // Words are copied one by one: bash 3.2, macOS's /bin/bash, joins\n // a quoted array slice into one word while IFS is a newline.\n return `# fluid bash completion\n_fluid_complete() {\n local -a words\n local i\n for ((i = 0; i <= COMP_CWORD; i++)); do words+=(\"\\${COMP_WORDS[i]}\"); done\n local IFS=$'\\\\n'\n COMPREPLY=($(printf '%s\\\\0' \"\\${words[@]}\" | fluid __complete --shell bash 2>/dev/null))\n}\ncomplete -o default -F _fluid_complete fluid\n`;\n case \"zsh\":\n return `#compdef fluid\n# fluid zsh completion\n_fluid() {\n local -a candidates\n candidates=(\"\\${(@f)$(printf '%s\\\\0' \"\\${(@)words[1,CURRENT]}\" | fluid __complete --shell zsh 2>/dev/null)}\")\n candidates=(\\${candidates:#})\n if (( \\${#candidates} )); then\n _describe -t fluid 'fluid' candidates\n else\n _files\n fi\n}\nif [[ \\${zsh_eval_context[-1]} == loadautofunc ]]; then\n _fluid \"$@\"\nelse\n compdef _fluid fluid\nfi\n`;\n case \"fish\":\n // The current token goes through a variable so an empty one is still\n // sent: a bare (commandline -ct) expands to no argument at all.\n return `# fluid fish completion\nfunction __fluid_complete\n set -l current (commandline -ct)\n set -l candidates (string join0 -- (commandline -opc) \"$current\" | fluid __complete --shell fish 2>/dev/null)\n if set -q candidates[1]\n printf '%s\\\\n' $candidates\n else\n __fish_complete_path \"$current\"\n end\nend\ncomplete -c fluid -f -a '(__fluid_complete)'\n`;\n }\n}\n\nexport const COMPLETION_INSTALL_HELP = `\nInstall:\n bash echo 'eval \"$(fluid completion bash)\"' >> ~/.bashrc\n zsh fluid completion zsh > \"\\${fpath[1]}/_fluid\" (or eval \"$(fluid completion zsh)\" in ~/.zshrc)\n fish fluid completion fish > ~/.config/fish/completions/fluid.fish\n`;\n","/**\n * fluid completion <shell> — print a shell completion script.\n * fluid __complete — the hidden command that script pipes the typed words\n * into on each tab.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { Argument, Command, Option } from \"commander\";\nimport {\n completeWords,\n completionScript,\n COMPLETION_INSTALL_HELP,\n formatCandidates,\n parseCompletionInput,\n SHELLS,\n type Shell,\n} from \"../completion/complete.js\";\nimport { rootCommand } from \"../catalog/walk.js\";\n\nexport const completionCommand = new Command(\"completion\")\n .description(\"Print a shell completion script for bash, zsh or fish\")\n .addArgument(new Argument(\"<shell>\", \"Shell to complete in\").choices(SHELLS))\n .addHelpText(\"after\", COMPLETION_INSTALL_HELP)\n .action((shell: Shell) => {\n process.stdout.write(completionScript(shell));\n });\n\nexport const completeCommand = new Command(\"__complete\")\n .description(\"Print completions for the words typed so far\")\n .addOption(\n new Option(\"--shell <shell>\", \"Output format\")\n .choices(SHELLS)\n .default(\"bash\"),\n )\n .action((opts: { shell: Shell }, command: Command) => {\n // The words arrive on stdin, NUL-terminated, never as arguments.\n const typed = parseCompletionInput(readFileSync(0, \"utf8\"));\n process.stdout.write(\n formatCandidates(completeWords(rootCommand(command), typed), opts.shell),\n );\n });\n","/**\n * Which way a sign-in completes, as Rails decides it from the company flag\n * (Phase 007 INV-7.1). The CLI never decides it on its own.\n *\n * Mirrors apps/fluid-login: the email step answers every address the same\n * way, and a person whose company is flagged is emailed a sign-in link\n * instead of a code. When a code is confirmed, `confirm_mfa` answers\n * `sign_in_path: \"identity\"` once every company the code covered signs in\n * through the identity service, and hands out no token for them\n * (`Identity::LegacySignInGate`).\n */\n\nimport type { ConfirmMfaResponse } from \"../fluid-api.js\";\n\nexport type SignInPath = \"identity\" | \"legacy\";\n\n/**\n * The path a confirmed code puts the person on. A confirmation that kept any\n * company's legacy token stays on the legacy path: those companies are not\n * flagged, and their tokens are listed exactly as before.\n */\nexport function signInPathFor(confirmation: ConfirmMfaResponse): SignInPath {\n return confirmation.signInPath === \"identity\" ? \"identity\" : \"legacy\";\n}\n","/**\n * Email sign-ins started with `fluid login --send-code` and not finished yet.\n *\n * The send and finish steps run as separate processes, and the finish step\n * needs the server's id for the sign-in (`uuid`), which only the send step\n * saw. Keeping it here means an agent carries the emailed code alone. The\n * uuid cannot sign anyone in without that code.\n *\n * One record per address, so a new send replaces the last one. Records live\n * under the config dir (`~/.fluid/pending-logins/`), each named by a hash of\n * the address so the file names do not list who is signing in.\n */\n\nimport { createHash, randomBytes } from \"node:crypto\";\nimport {\n mkdirSync,\n readdirSync,\n readFileSync,\n renameSync,\n rmSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\nimport { getConfigDir } from \"../config/paths.js\";\n\nexport interface PendingLogin {\n readonly uuid: string;\n /** Normalised with `normaliseEmail`. */\n readonly email: string;\n /** The company the code was sent for; the finish step confirms it. */\n readonly shop: string;\n readonly expiresAt: string;\n /** The API the code was sent from; the finish step confirms against it. */\n readonly baseUrl: string;\n}\n\nexport interface PendingLoginStore {\n save(record: PendingLogin): void;\n load(email: string): PendingLogin | null;\n remove(email: string): void;\n}\n\n// A record this long past its expiry can never be finished, so the next\n// save removes it, along with any record it cannot read.\nconst STALE_AFTER_MS = 60 * 60 * 1000;\n\n/** The server compares addresses trimmed and lowercased; so does the store. */\nexport function normaliseEmail(email: string): string {\n return email.trim().toLowerCase();\n}\n\nfunction fileName(email: string): string {\n const hash = createHash(\"sha256\").update(normaliseEmail(email)).digest(\"hex\");\n return `${hash}.json`;\n}\n\nfunction isPendingLogin(value: unknown): value is PendingLogin {\n if (typeof value !== \"object\" || value === null) return false;\n const record = value as Record<string, unknown>;\n return (\n typeof record[\"uuid\"] === \"string\" &&\n typeof record[\"email\"] === \"string\" &&\n typeof record[\"shop\"] === \"string\" &&\n typeof record[\"expiresAt\"] === \"string\" &&\n typeof record[\"baseUrl\"] === \"string\"\n );\n}\n\nfunction readRecord(path: string): PendingLogin | null {\n try {\n const parsed: unknown = JSON.parse(readFileSync(path, \"utf8\"));\n return isPendingLogin(parsed) ? parsed : null;\n } catch {\n return null;\n }\n}\n\nfunction removeStale(dir: string, now: number): void {\n let names: string[];\n try {\n names = readdirSync(dir);\n } catch {\n return;\n }\n for (const name of names) {\n if (!name.endsWith(\".json\")) continue;\n const path = join(dir, name);\n const record = readRecord(path);\n const expiresAt = record ? Date.parse(record.expiresAt) : NaN;\n if (!record || !(expiresAt + STALE_AFTER_MS > now)) {\n rmSync(path, { force: true });\n }\n }\n}\n\n/**\n * The store, in `dir` or by default `<config dir>/pending-logins`, resolved\n * on each call so a changed `FLUID_CONFIG_DIR` is honoured.\n */\nexport function createPendingLoginStore(dir?: string): PendingLoginStore {\n const storeDir = () => dir ?? join(getConfigDir(), \"pending-logins\");\n\n return {\n save(record) {\n const base = storeDir();\n mkdirSync(base, { recursive: true, mode: 0o700 });\n removeStale(base, Date.now());\n\n // Written to a temp file and renamed over the record, as config.json\n // is, so a crash never leaves half a record and the 0o600 mode applies\n // to every write rather than only the first.\n const tmpPath = join(\n base,\n `.pending-${randomBytes(6).toString(\"hex\")}.tmp`,\n );\n try {\n writeFileSync(tmpPath, JSON.stringify(record, null, 2) + \"\\n\", {\n encoding: \"utf8\",\n mode: 0o600,\n });\n renameSync(tmpPath, join(base, fileName(record.email)));\n } catch (err) {\n try {\n unlinkSync(tmpPath);\n } catch {\n // The temp file may not exist yet.\n }\n throw err;\n }\n },\n\n load(email) {\n const record = readRecord(join(storeDir(), fileName(email)));\n return record && record.email === normaliseEmail(email) ? record : null;\n },\n\n remove(email) {\n rmSync(join(storeDir(), fileName(email)), { force: true });\n },\n };\n}\n","/**\n * Helpers for constructing stored auth profiles.\n */\n\nimport type { FluidProfile, IdentityProfileAuth } from \"../config/types.js\";\n\ninterface CreateFluidProfileInput {\n readonly name: string;\n readonly token: string;\n readonly companyName: string;\n readonly baseUrl: string;\n readonly storedAt?: string;\n}\n\nexport function createFluidProfile({\n name,\n token,\n companyName,\n baseUrl,\n storedAt,\n}: CreateFluidProfileInput): FluidProfile {\n return {\n name,\n token,\n companyName,\n storedAt: storedAt ?? new Date().toISOString(),\n baseUrl,\n };\n}\n\ninterface CreateIdentityProfileInput {\n readonly name: string;\n readonly companyName: string;\n readonly baseUrl: string;\n readonly auth: IdentityProfileAuth;\n readonly storedAt?: string;\n}\n\n/**\n * An identity-mode profile. It holds no token: the refresh token is in the\n * operating system credential store under `auth.storageKey`.\n */\nexport function createIdentityProfile({\n name,\n companyName,\n baseUrl,\n auth,\n storedAt,\n}: CreateIdentityProfileInput): FluidProfile {\n return {\n name,\n companyName,\n storedAt: storedAt ?? new Date().toISOString(),\n baseUrl,\n auth,\n };\n}\n","// Characters an email, shop or profile name can hold that are safe to paste\n// into a shell. No leading \"-\", which a command would read as a flag.\nconst SHELL_SAFE = /^[\\w@+][\\w.@+-]*$/;\n\n/**\n * The value for a printed command, or the placeholder when it holds\n * characters a shell would act on.\n */\nexport function shellSafe(value: string, placeholder: string): string {\n return SHELL_SAFE.test(value) ? value : placeholder;\n}\n","/**\n * `fluid login` for a company on the identity sign-in path: the browser,\n * a loopback redirect, and a session in the operating system credential\n * store. Reached only when Rails says so (see auth/identity/sign-in-path.ts):\n * a confirmed code answered `sign_in_path: \"identity\"`, or the person pasted\n * the sign-in link Rails emailed them instead of a code.\n *\n * It reports an outcome rather than printing one, so `fluid login` shows it\n * in text or `--json` like every other sign-in.\n */\n\nimport {\n getFluidApiBase,\n redeemIdentityLink,\n type validateToken,\n} from \"../auth/fluid-api.js\";\nimport {\n IDENTITY_ROOT_COMPANY_ID,\n resolveIdentityUrl,\n} from \"../auth/identity/environment.js\";\nimport { endUnusedSessions } from \"../auth/identity/profiles.js\";\nimport {\n describeIdentityError,\n identityToken,\n signInWithBrowser,\n signOutIdentity,\n} from \"../auth/identity/session.js\";\nimport { createIdentityProfile } from \"../auth/profiles.js\";\nimport { readConfig, updateConfig } from \"../config/config.js\";\nimport type { FluidConfig } from \"../config/types.js\";\nimport type { CliError } from \"../utils/errors.js\";\n\n/** The query parameter Rails puts the sign-in link's token in. */\nconst IDENTITY_LINK_PARAM = \"identityLink\";\n\n/** The roles the CLI's commands accept, as with a legacy `rep` session. */\nconst STAFF_ROLES = new Set([\"admin\", \"rep\", \"root_admin\"]);\n\n/**\n * The token in a pasted identity sign-in link, or null when the input is not\n * such a link.\n */\nexport function identityLinkToken(input: string): string | null {\n const trimmed = input.trim();\n if (!trimmed.includes(`${IDENTITY_LINK_PARAM}=`)) return null;\n try {\n const url = new URL(trimmed);\n return url.searchParams.get(IDENTITY_LINK_PARAM) || null;\n } catch {\n return null;\n }\n}\n\ninterface Spinner {\n succeed(text?: string): unknown;\n fail(text?: string): unknown;\n}\n\nexport interface IdentityLoginContext {\n /** `--name`: the profile to store, instead of the company's name. */\n readonly profileName?: string;\n /** The API base the sign-in started against. Defaults to the CLI's. */\n readonly apiBase?: string;\n /** The email the person typed; it only pre-fills the browser sign-in. */\n readonly loginHint?: string;\n /** The company (uuid_v7) the sign-in must land in. */\n readonly org?: string;\n /** Ask for credentials even when the browser holds a session. */\n readonly forceLogin?: boolean;\n /** Progress lines for the person, the sign-in URL among them. */\n readonly log: (line: string) => void;\n readonly spinner: (text: string) => Spinner;\n readonly validateToken: typeof validateToken;\n readonly redeemIdentityLink?: typeof redeemIdentityLink;\n /**\n * Called once a pasted link is spent or reported gone, never on a failure\n * that leaves it redeemable, so a caller tracking the sign-in can keep it\n * for a retry.\n */\n readonly onLinkSettled?: () => void;\n /** Whether an existing profile of this name may be replaced. */\n readonly decideOverwrite: (\n profileName: string,\n ) => Promise<\"replace\" | \"keep\" | \"refuse\">;\n}\n\nexport type IdentityLoginOutcome =\n | {\n readonly status: \"signed_in\";\n readonly profileName: string;\n readonly companyName: string;\n }\n | { readonly status: \"failed\"; readonly error: CliError }\n /** The person chose to keep the existing profile. */\n | { readonly status: \"kept\"; readonly profileName: string }\n /** An existing profile would be replaced and no one could be asked. */\n | { readonly status: \"refused\"; readonly profileName: string };\n\nfunction failed(code: string, message: string): IdentityLoginOutcome {\n return { status: \"failed\", error: { code, message } };\n}\n\n/**\n * What pins an identity sign-in to the account and company a sign-in\n * confirmed: the company, when known, and a fresh login so the browser's\n * existing session is not reused.\n */\nexport function pinnedIdentity(companyUuid?: string): {\n readonly org?: string;\n readonly forceLogin: true;\n} {\n return { ...(companyUuid ? { org: companyUuid } : {}), forceLogin: true };\n}\n\n/** Signs in through the identity service and stores the profile. */\nexport async function loginWithIdentity(\n context: IdentityLoginContext,\n): Promise<IdentityLoginOutcome> {\n const apiBase = context.apiBase ?? getFluidApiBase();\n let identityUrl: string | null;\n try {\n identityUrl = resolveIdentityUrl(apiBase);\n } catch (error) {\n return failed(\n \"IDENTITY_URL_INVALID\",\n error instanceof Error ? error.message : String(error),\n );\n }\n if (!identityUrl) {\n return failed(\n \"IDENTITY_URL_UNKNOWN\",\n `No Fluid identity service is known for ${apiBase}. Set FLUID_IDENTITY_URL to sign in.`,\n );\n }\n\n context.log(\"Your company signs in through Fluid's identity service.\");\n let signIn: Awaited<ReturnType<typeof signInWithBrowser>>;\n try {\n signIn = await signInWithBrowser({\n identityUrl,\n log: context.log,\n loginHint: context.loginHint,\n org: context.org,\n prompt: context.forceLogin ? \"login\" : undefined,\n });\n } catch (error) {\n return failed(\"IDENTITY_SIGN_IN_FAILED\", describeIdentityError(error));\n }\n\n if (\n context.org &&\n signIn.facts.companyId &&\n signIn.facts.companyId !== context.org\n ) {\n await signOutIdentity(signIn.auth).catch(() => undefined);\n return failed(\n \"IDENTITY_COMPANY_MISMATCH\",\n \"The browser signed in to a different company than the sign-in link was for. Sign out of the browser's Fluid session and try again.\",\n );\n }\n\n // The CLI's commands take an admin or rep session, never a shopper's.\n if (!signIn.facts.roles.some((role) => STAFF_ROLES.has(role))) {\n await signOutIdentity(signIn.auth).catch(() => undefined);\n return failed(\n \"SHOPPER_SESSION\",\n \"This account does not sign in as an admin or rep, so it cannot sign in to the CLI.\",\n );\n }\n\n const companyless = !signIn.facts.companyId;\n if (companyless && !signIn.facts.roles.includes(\"root_admin\")) {\n await signOutIdentity(signIn.auth).catch(() => undefined);\n return failed(\n \"IDENTITY_NO_COMPANY\",\n \"This sign-in is not in a company. Run `fluid login --shop <company>` to sign in to one.\",\n );\n }\n if (companyless && signIn.recovered && !context.org && !signIn.pickedOrg) {\n await signOutIdentity(signIn.auth).catch(() => undefined);\n return failed(\n \"IDENTITY_SIGN_IN_FAILED\",\n \"The sign-in finished without knowing which company you picked. Run `fluid login` again.\",\n );\n }\n const rootFallback = companyless && !context.org && !signIn.pickedOrg;\n const org = companyless\n ? (context.org ?? signIn.pickedOrg ?? IDENTITY_ROOT_COMPANY_ID)\n : undefined;\n const auth = org ? { ...signIn.auth, org } : signIn.auth;\n\n let accessToken = signIn.accessToken;\n if (org) {\n try {\n accessToken = (await identityToken(auth, org)).accessToken;\n } catch (error) {\n await signOutIdentity(signIn.auth).catch(() => undefined);\n return failed(\n \"IDENTITY_COMPANY_EXCHANGE_FAILED\",\n `Could not sign in to the company: ${describeIdentityError(error)}`,\n );\n }\n }\n\n // The company's display name; the session itself knows only its id.\n const spinner = context.spinner(\"Loading your company...\");\n // Asked of the API the sign-in started against, never the environment's.\n const company = rootFallback\n ? null\n : await context.validateToken(accessToken, { baseUrl: apiBase });\n const companyName = rootFallback\n ? \"Fluid\"\n : company?.success\n ? company.value.name\n : (org ?? signIn.facts.companyId ?? \"Fluid\");\n spinner.succeed(`Signed in to ${companyName}`);\n\n const profileName = context.profileName ?? companyName;\n const decision = await context.decideOverwrite(profileName);\n if (decision !== \"replace\") {\n await signOutIdentity(signIn.auth).catch(() => undefined);\n return decision === \"keep\"\n ? { status: \"kept\", profileName }\n : { status: \"refused\", profileName };\n }\n\n let before: FluidConfig;\n let after: FluidConfig;\n try {\n before = readConfig();\n after = updateConfig((config) => ({\n ...config,\n activeProfile: profileName,\n profiles: {\n ...config.profiles,\n [profileName]: createIdentityProfile({\n name: profileName,\n companyName,\n baseUrl: apiBase,\n auth,\n }),\n },\n }));\n } catch (error) {\n await signOutIdentity(signIn.auth).catch(() => undefined);\n throw error;\n }\n // A profile this one replaced may have been the last user of its session.\n for (const problem of await endUnusedSessions(before, after)) {\n context.log(problem);\n }\n\n return { status: \"signed_in\", profileName, companyName };\n}\n\n/**\n * Redeems a pasted sign-in link with Rails, which confirms the person's\n * company signs in through the identity service, then signs in.\n */\nexport async function loginWithIdentityLink(\n token: string,\n context: IdentityLoginContext,\n): Promise<IdentityLoginOutcome> {\n const spinner = context.spinner(\"Checking the sign-in link...\");\n const redemption = await (context.redeemIdentityLink ?? redeemIdentityLink)(\n token,\n { baseUrl: context.apiBase },\n );\n if (!redemption.success) {\n spinner.fail(redemption.error.message);\n // Only a link Rails reports as gone is settled; any other failure may\n // not have spent it, so the caller keeps what it needs to retry.\n if (redemption.error.code === \"LINK_GONE\") context.onLinkSettled?.();\n return { status: \"failed\", error: redemption.error };\n }\n context.onLinkSettled?.();\n spinner.succeed(\"Sign-in link accepted\");\n return loginWithIdentity({\n ...context,\n ...pinnedIdentity(redemption.value.companyUuid),\n });\n}\n","/**\n * fluid login — authenticate via email MFA or API token\n *\n * Besides the interactive sign-in, an email sign-in can run in two steps\n * with no terminal, for an agent: `--send-code` emails the code and saves\n * the server's sign-in id (auth/pending-login.ts), then `--code` redeems\n * it. `--send-code` requires `--shop`, which ties the code to one company:\n * only such a code lets an admin's sign-in confirm a new signup.\n *\n * A company on the identity sign-in path is emailed a link instead of a\n * code, and Rails may answer a confirmed code with `sign_in_path:\n * \"identity\"`. Either way the sign-in continues through the browser\n * (commands/login-identity.ts); the CLI never picks the path itself.\n */\n\nimport { text as readAll } from \"node:stream/consumers\";\nimport { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport prompts from \"prompts\";\nimport ora from \"ora\";\nimport {\n validateToken,\n sendMfa,\n confirmMfa,\n getFluidApiBase,\n type redeemIdentityLink,\n type CompanyChoice,\n type FluidApiError,\n} from \"../auth/fluid-api.js\";\nimport { endUnusedSessions } from \"../auth/identity/profiles.js\";\nimport { signInPathFor } from \"../auth/identity/sign-in-path.js\";\nimport {\n createPendingLoginStore,\n normaliseEmail,\n type PendingLoginStore,\n} from \"../auth/pending-login.js\";\nimport { createFluidProfile } from \"../auth/profiles.js\";\nimport { updateConfig, readConfig } from \"../config/config.js\";\nimport type { FluidProfile } from \"../config/types.js\";\nimport type { CliError } from \"../utils/errors.js\";\nimport { shellSafe } from \"../utils/shell.js\";\nimport {\n identityLinkToken,\n loginWithIdentity,\n pinnedIdentity,\n loginWithIdentityLink,\n type IdentityLoginContext,\n type IdentityLoginOutcome,\n} from \"./login-identity.js\";\n\nexport interface LoginOptions {\n readonly token?: string;\n readonly email?: string;\n readonly name?: string;\n readonly shop?: string;\n readonly sendCode?: boolean;\n /**\n * `true` for a bare `--code`, which reads FLUID_LOGIN_CODE; `\"-\"` reads\n * stdin; anything else is the code itself.\n */\n readonly code?: string | boolean;\n readonly yes?: boolean;\n readonly json?: boolean;\n}\n\ninterface Spinner {\n succeed(text?: string): unknown;\n fail(text?: string): unknown;\n}\n\n/**\n * Everything `runLogin` reaches outside itself, so a test can stand in for\n * the API, the prompts, the terminal and the console without loading\n * commander or reloading this module.\n */\nexport interface LoginDeps {\n readonly api: {\n readonly validateToken: typeof validateToken;\n readonly sendMfa: typeof sendMfa;\n readonly confirmMfa: typeof confirmMfa;\n /** Defaults to the real redemption when a caller does not stand one in. */\n readonly redeemIdentityLink?: typeof redeemIdentityLink;\n };\n readonly prompt: (\n question: prompts.PromptObject,\n ) => Promise<prompts.Answers<string>>;\n readonly spinner: (text: string) => Spinner;\n /** stdout: results, and in text mode every message. */\n readonly log: (line: string) => void;\n /** stderr: warnings that must not mix into `--json` output. */\n readonly err: (line: string) => void;\n readonly env: NodeJS.ProcessEnv;\n /**\n * Whether a person can answer a prompt. `prompts` reads stdin, and on a\n * closed stdin (an agent's subprocess) it never settles, so node exits 0\n * having done nothing.\n */\n readonly isInteractive: () => boolean;\n readonly readStdin: () => Promise<string>;\n readonly pending: PendingLoginStore;\n}\n\nexport const defaultLoginDeps: LoginDeps = {\n api: { validateToken, sendMfa, confirmMfa },\n prompt: (question) => prompts(question),\n spinner: (text) => ora(text).start(),\n log: (line) => console.log(line),\n err: (line) => console.error(line),\n env: process.env,\n isInteractive: () => Boolean(process.stdin.isTTY),\n readStdin: () => readAll(process.stdin),\n pending: createPendingLoginStore(),\n};\n\nconst SILENT_SPINNER: Spinner = { succeed: () => {}, fail: () => {} };\n\nconst TWO_STEP_HINT =\n \"Sign in in two steps instead:\\n\" +\n \" fluid login --send-code --email <email> --shop <shop>\\n\" +\n \" fluid login --code --email <email> --yes\\n\" +\n \"with the emailed code in FLUID_LOGIN_CODE (or --code - to read it from stdin). \" +\n \"--yes replaces a profile with the company's name; --name <profile> picks another. Or set FLUID_TOKEN.\";\n\n/** Output for one run: spinners and text, or a single JSON object. */\ninterface Ui {\n readonly json: boolean;\n spinner(text: string): Spinner;\n /** Print the run's JSON result; text mode prints its own lines. */\n result(payload: Record<string, unknown>): void;\n /** Report a failure and return the exit code. */\n fail(error: CliError, spinner?: Spinner): number;\n}\n\nfunction createUi(json: boolean, deps: LoginDeps): Ui {\n return {\n json,\n spinner: (text) => (json ? SILENT_SPINNER : deps.spinner(text)),\n result: (payload) => {\n if (json) deps.log(JSON.stringify(payload, null, 2));\n },\n fail: (error, spinner) => {\n if (json) {\n deps.log(\n JSON.stringify(\n {\n status: \"error\",\n code: error.code,\n message: error.message,\n ...(error.details ? { details: error.details } : {}),\n },\n null,\n 2,\n ),\n );\n return 1;\n }\n if (spinner) spinner.fail(chalk.red(error.message));\n else deps.log(chalk.red(error.message));\n if (error.details) deps.log(chalk.dim(error.details));\n return 1;\n },\n };\n}\n\n/** The shop option for an API call, or no argument at all without one. */\nfunction shopArgs(shop: string | undefined): [] | [{ fluidShop: string }] {\n return shop ? [{ fluidShop: shop }] : [];\n}\n\n/** The part of a shop the server matches on: \"acme\" in \"acme.fluid.app\". */\nfunction shopLabel(shop: string): string {\n return (shop.trim().toLowerCase().split(\".\")[0] ?? \"\").trim();\n}\n\nfunction findByShop(\n companies: readonly CompanyChoice[],\n shop: string,\n): CompanyChoice | undefined {\n return companies.find((c) => shopLabel(c.shopName) === shopLabel(shop));\n}\n\n/**\n * Whether the entry's token is an admin or rep session, the only kind the\n * CLI's commands accept. A shopper's code returns a \"member\" or \"customer\"\n * token instead. The server types every entry, so one with no type is\n * refused rather than stored.\n */\nfunction isStaffSession(company: CompanyChoice): boolean {\n return company.authType === \"rep\";\n}\n\nfunction shopperSession(email: string, company: CompanyChoice): CliError {\n return {\n code: \"SHOPPER_SESSION\",\n message: `${email} does not sign in at ${company.shopName} as an admin or rep, so it cannot sign in to the CLI.`,\n };\n}\n\ninterface OverwriteOptions {\n readonly yes: boolean;\n readonly interactive: boolean;\n}\n\n/**\n * What to do about profile `profileName` before writing it: replace it when\n * it is new or with `--yes`, ask in a terminal, and refuse otherwise, since\n * no one could answer the question.\n */\nfunction overwriteRule(\n profileName: string,\n opts: OverwriteOptions,\n): \"replace\" | \"ask\" | \"refuse\" {\n if (!readConfig().profiles[profileName] || opts.yes) return \"replace\";\n return opts.interactive ? \"ask\" : \"refuse\";\n}\n\nasync function overwriteDecision(\n profileName: string,\n opts: OverwriteOptions,\n deps: LoginDeps,\n): Promise<\"replace\" | \"keep\" | \"refuse\"> {\n const rule = overwriteRule(profileName, opts);\n if (rule !== \"ask\") return rule;\n\n const existing = readConfig().profiles[profileName];\n const response = await deps.prompt({\n type: \"confirm\",\n name: \"overwrite\",\n message: `Profile \"${profileName}\" already exists (${existing?.companyName}). Overwrite?`,\n initial: false,\n });\n return response[\"overwrite\"] ? \"replace\" : \"keep\";\n}\n\nfunction isLegacyProfile(profile: FluidProfile | undefined): boolean {\n return (\n profile !== undefined &&\n !profile.auth &&\n typeof profile.token === \"string\" &&\n profile.token !== \"\"\n );\n}\n\nfunction profileExists(profileName: string, codeUsed: boolean): CliError {\n return {\n code: \"PROFILE_EXISTS\",\n message:\n `Profile \"${profileName}\" already exists. Pass --yes to replace it` +\n (codeUsed ? \"; the code is used, so send a new one first.\" : \".\"),\n };\n}\n\nasync function storeProfile(\n deps: LoginDeps,\n profileName: string,\n token: string,\n companyName: string,\n baseUrl: string = getFluidApiBase(),\n): Promise<void> {\n const before = readConfig();\n const after = updateConfig((config) => ({\n ...config,\n activeProfile: profileName,\n profiles: {\n ...config.profiles,\n [profileName]: createFluidProfile({\n name: profileName,\n token,\n companyName,\n baseUrl,\n }),\n },\n }));\n // Replacing an identity-mode profile ends its session if nothing else\n // uses it, so no refresh token is left behind in the credential store.\n for (const problem of await endUnusedSessions(before, after)) {\n deps.err(chalk.yellow(problem));\n }\n}\n\nfunction loggedIn(\n ui: Ui,\n deps: LoginDeps,\n profileName: string,\n company: {\n readonly name: string;\n readonly id?: number;\n readonly shop?: string;\n },\n): number {\n ui.result({ status: \"signed_in\", profile: profileName, company });\n if (!ui.json) {\n deps.log(\n chalk.green(\n `Logged in as ${chalk.bold(company.name)} (profile: ${chalk.bold(profileName)})`,\n ),\n );\n }\n return 0;\n}\n\nfunction cancelled(deps: LoginDeps): number {\n deps.log(chalk.yellow(\"Login cancelled — existing profile not overwritten.\"));\n return 0;\n}\n\n/**\n * What the identity sign-in needs from this run: its output, its overwrite\n * rule, and the API base the sign-in started against. With `--json` the\n * person still needs the sign-in URL, so progress goes to stderr.\n */\nfunction identityContext(\n opts: LoginOptions,\n interactive: boolean,\n ui: Ui,\n deps: LoginDeps,\n apiBase?: string,\n): IdentityLoginContext {\n return {\n profileName: opts.name,\n apiBase,\n log: (line) =>\n ui.json\n ? deps.err(line)\n : deps.log(line.startsWith(\"http\") ? line : chalk.cyan(line)),\n spinner: (text) => ui.spinner(text),\n // Every request of this sign-in goes to `apiBase` when it has one: a\n // two-step sign-in's is the API its code was sent from.\n validateToken: (token, options) =>\n deps.api.validateToken(token, { baseUrl: apiBase, ...options }),\n redeemIdentityLink: deps.api.redeemIdentityLink,\n decideOverwrite: (profileName) => {\n if (isLegacyProfile(readConfig().profiles[profileName])) {\n const notice = `Replaced legacy profile \"${profileName}\" with a One Auth sign-in.`;\n if (ui.json) deps.err(notice);\n else deps.log(chalk.dim(notice));\n return Promise.resolve(\"replace\");\n }\n return overwriteDecision(\n profileName,\n { yes: Boolean(opts.yes), interactive },\n deps,\n );\n },\n };\n}\n\nfunction identityResult(\n outcome: IdentityLoginOutcome,\n ui: Ui,\n deps: LoginDeps,\n): number {\n switch (outcome.status) {\n case \"signed_in\":\n return loggedIn(ui, deps, outcome.profileName, {\n name: outcome.companyName,\n });\n case \"kept\":\n return cancelled(deps);\n case \"refused\":\n return ui.fail(profileExists(outcome.profileName, false));\n case \"failed\":\n return ui.fail(outcome.error);\n }\n}\n\nconst LINK_HINT =\n \"If the email has a sign-in link instead of a code, paste the link here.\";\n\nasync function loginWithToken(\n token: string,\n opts: LoginOptions,\n interactive: boolean,\n ui: Ui,\n deps: LoginDeps,\n): Promise<number> {\n const spinner = ui.spinner(\"Validating token...\");\n const result = await deps.api.validateToken(token);\n\n if (!result.success) return ui.fail(result.error, spinner);\n\n const name = opts.name ?? result.value.name;\n\n // Stop spinner before potential interactive prompt to avoid terminal corruption\n spinner.succeed(\n chalk.green(`Token valid — ${chalk.bold(result.value.name)}`),\n );\n\n const decision = await overwriteDecision(\n name,\n { yes: Boolean(opts.yes), interactive },\n deps,\n );\n if (decision === \"refuse\") return ui.fail(profileExists(name, false));\n if (decision === \"keep\") return cancelled(deps);\n\n await storeProfile(deps, name, token, result.value.name);\n return loggedIn(ui, deps, name, { name: result.value.name });\n}\n\nasync function loginWithEmail(\n opts: LoginOptions,\n ui: Ui,\n deps: LoginDeps,\n): Promise<number> {\n // 1. Prompt for email\n let email = opts.email;\n if (!email) {\n const response = await deps.prompt({\n type: \"text\",\n name: \"email\",\n message: \"Enter your email\",\n });\n email = response[\"email\"] as string | undefined;\n if (!email) {\n deps.log(chalk.red(\"No email provided. Aborting.\"));\n return 1;\n }\n }\n\n // 2. Send MFA code\n const sendSpinner = ui.spinner(\"Sending verification code...\");\n const sendResult = await deps.api.sendMfa(\n email,\n opts.shop\n ? { fluidShop: opts.shop, identityHint: true }\n : { identityHint: true },\n );\n\n if (!sendResult.success) return ui.fail(sendResult.error, sendSpinner);\n\n if (sendResult.value.signInPath === \"identity\") {\n if (opts.shop && !sendResult.value.companyUuid) {\n return ui.fail(\n {\n code: \"SHOP_NOT_RESOLVED\",\n message: `Could not resolve ${opts.shop} for browser sign-in. Run \"fluid login\" without --shop and pick the shop in the browser.`,\n },\n sendSpinner,\n );\n }\n sendSpinner.succeed(\"Opening your browser to sign in\");\n return identityResult(\n await loginWithIdentity({\n ...identityContext(opts, true, ui, deps),\n ...(opts.shop ? pinnedIdentity(sendResult.value.companyUuid) : {}),\n loginHint: normaliseEmail(email),\n }),\n ui,\n deps,\n );\n }\n\n sendSpinner.succeed(\n `Verification code sent — check your email (${expiryNote(sendResult.value.expiresAt)})`,\n );\n if (!ui.json) deps.log(chalk.dim(LINK_HINT));\n\n // 3. Prompt for verification code (retry up to 3 times on invalid code)\n const MAX_CODE_ATTEMPTS = 3;\n let confirmResult;\n for (let attempt = 1; attempt <= MAX_CODE_ATTEMPTS; attempt++) {\n const codeResponse = await deps.prompt({\n type: \"text\",\n name: \"code\",\n message: \"Enter the 6-digit code\",\n });\n const code = codeResponse[\"code\"] as string | undefined;\n if (!code) {\n deps.log(chalk.red(\"No code provided. Aborting.\"));\n return 1;\n }\n // A flagged company's person is emailed a link, not a code.\n const linkToken = identityLinkToken(code);\n if (linkToken) {\n return identityResult(\n await loginWithIdentityLink(linkToken, {\n ...identityContext(opts, true, ui, deps),\n loginHint: normaliseEmail(email),\n }),\n ui,\n deps,\n );\n }\n if (!/^\\d{6}$/.test(code)) {\n deps.log(chalk.red(\"Code must be exactly 6 digits.\"));\n if (attempt < MAX_CODE_ATTEMPTS) continue;\n deps.log(chalk.red(\"Too many invalid attempts. Aborting.\"));\n return 1;\n }\n\n const confirmSpinner = ui.spinner(\"Verifying code...\");\n confirmResult = await deps.api.confirmMfa(\n sendResult.value.uuid,\n code,\n ...shopArgs(opts.shop),\n );\n\n if (confirmResult.success) {\n confirmSpinner.succeed(\"Verified\");\n break;\n }\n\n // Retryable: wrong code, still have attempts left\n if (\n confirmResult.error.code === \"INVALID_CODE\" &&\n attempt < MAX_CODE_ATTEMPTS\n ) {\n confirmSpinner.fail(\n chalk.red(\n `${confirmResult.error.message} (attempt ${attempt}/${MAX_CODE_ATTEMPTS})`,\n ),\n );\n continue;\n }\n\n // Non-retryable (expired, unreachable, etc.) or final attempt. The server\n // refuses a sign-in it cannot finish with a code as it refuses a wrong\n // code, so the last refusal names those reasons too.\n if (confirmResult.error.code === \"INVALID_CODE\") {\n return ui.fail(\n {\n ...confirmResult.error,\n message: `${confirmResult.error.message}. If the code was right, the shop or the address may be wrong, or the company may sign in with an emailed link. Run fluid login again to start over.`,\n },\n confirmSpinner,\n );\n }\n // This flow keeps no challenge, so a restored contact needs a new code.\n if (confirmResult.error.code === \"CONTACT_MISSING\") {\n return ui.fail(\n {\n ...confirmResult.error,\n message: `${confirmResult.error.message}, then run fluid login again.`,\n },\n confirmSpinner,\n );\n }\n return ui.fail(confirmResult.error, confirmSpinner);\n }\n\n if (!confirmResult?.success) return 0;\n\n // Every company the code covered signs in through the identity service,\n // so Rails handed out no token (Phase 007 INV-7.5).\n if (signInPathFor(confirmResult.value) === \"identity\") {\n return identityResult(\n await loginWithIdentity({\n ...identityContext(opts, true, ui, deps),\n loginHint: normaliseEmail(email),\n ...pinnedIdentity(confirmResult.value.companyUuid),\n }),\n ui,\n deps,\n );\n }\n\n const { companies } = confirmResult.value;\n\n if (companies.length === 0) {\n deps.log(chalk.red(\"No companies found for this account.\"));\n return 1;\n }\n\n // 4. Select company (auto-select if only one, or the one --shop names)\n const named = opts.shop ? findByShop(companies, opts.shop) : undefined;\n let selected: CompanyChoice;\n if (named) {\n selected = named;\n } else if (companies.length === 1) {\n const first = companies[0];\n if (!first) {\n deps.log(chalk.red(\"No companies found for this account.\"));\n return 1;\n }\n selected = first;\n } else {\n // Key on `c.id`, not the array index, and resolve via `.find` —\n // `prompts` autocomplete returns the raw typed string on Enter when\n // the user hasn't arrow-key-highlighted a filtered choice, so an\n // array-index lookup ends up asking for `companies[\"Fluid\"]` and\n // failing with \"Invalid selection\". Same shape as `switch.ts`.\n const companyChoices = companies.map((c) => ({\n title: `${c.name} (${c.shopName})`,\n value: c.id,\n }));\n\n const selectResponse = await deps.prompt({\n type: \"autocomplete\",\n name: \"companyId\",\n message: \"Select a company (type to search)\",\n choices: companyChoices,\n suggest: (input, choices) =>\n Promise.resolve(\n input\n ? choices.filter((c) =>\n c.title.toLowerCase().includes(input.toLowerCase()),\n )\n : choices,\n ),\n });\n\n const companyId = selectResponse[\"companyId\"] as number | undefined;\n\n if (companyId === undefined) {\n deps.log(chalk.red(\"No company selected. Aborting.\"));\n return 1;\n }\n const choice = companies.find((c) => c.id === companyId);\n if (!choice) {\n deps.log(chalk.red(\"Invalid selection. Aborting.\"));\n return 1;\n }\n selected = choice;\n }\n\n if (!isStaffSession(selected)) {\n return ui.fail(shopperSession(email, selected));\n }\n\n // 5. Store profile\n const name = opts.name ?? selected.name;\n\n const decision = await overwriteDecision(\n name,\n { yes: Boolean(opts.yes), interactive: true },\n deps,\n );\n if (decision !== \"replace\") return cancelled(deps);\n\n await storeProfile(deps, name, selected.jwt, selected.name);\n return loggedIn(ui, deps, name, { name: selected.name });\n}\n\nfunction expiryNote(expiresAtIso: string): string {\n const expiresInMs = new Date(expiresAtIso).getTime() - Date.now();\n const expiresInMin = Math.round(expiresInMs / 1000 / 60);\n return expiresInMin > 0\n ? `expires in ~${expiresInMin} min`\n : \"code may expire soon — check your email quickly\";\n}\n\n/**\n * The command that finishes this sign-in, for a person or agent to run.\n * Values with characters a shell would act on are left as placeholders.\n */\nfunction finishCommand(email: string, shop: string): string {\n return `fluid login --code --email ${shellSafe(email, \"<email>\")} --shop ${shellSafe(shop, \"<shop>\")}`;\n}\n\n/** `fluid login --send-code`: email a code, save the sign-in, exit. */\nasync function sendCodeStep(\n opts: LoginOptions,\n ui: Ui,\n deps: LoginDeps,\n): Promise<number> {\n if (!opts.email) {\n return ui.fail({\n code: \"EMAIL_REQUIRED\",\n message: \"--send-code needs --email <address>.\",\n });\n }\n // A code sent without a shop is tied to the person, not to a company, so\n // finishing it signs in without confirming a new company's signup.\n if (!opts.shop) {\n return ui.fail({\n code: \"SHOP_REQUIRED\",\n message:\n \"--send-code needs --shop <shop>, the company to sign in to (acme or acme.fluid.app). For a new signup, `fluid signup` prints it as fluidShop.\",\n });\n }\n const email = normaliseEmail(opts.email);\n const shop = opts.shop;\n\n const spinner = ui.spinner(\"Sending verification code...\");\n const sent = await deps.api.sendMfa(email, ...shopArgs(shop));\n if (!sent.success) return ui.fail(sent.error, spinner);\n\n deps.pending.save({\n uuid: sent.value.uuid,\n email,\n shop,\n expiresAt: sent.value.expiresAt,\n baseUrl: getFluidApiBase(),\n });\n\n // The server answers the same whether or not the address can sign in\n // there, so this cannot promise that a code was sent.\n spinner.succeed(\n `If ${email} can sign in at ${shop}, a code is on its way (${expiryNote(sent.value.expiresAt)})`,\n );\n ui.result({\n status: \"code_sent\",\n email,\n shop,\n expiresAt: sent.value.expiresAt,\n });\n if (!ui.json) {\n deps.log(`Finish with: ${finishCommand(email, shop)}`);\n deps.log(\n chalk.dim(\n \"with the code in FLUID_LOGIN_CODE, or add - after --code to read it from stdin. \" +\n \"If the email has a sign-in link instead of a code, pass the link the same way. \" +\n \"With no terminal, add --yes to replace a profile with the company's name, or --name <profile>.\",\n ),\n );\n }\n return 0;\n}\n\n/**\n * The code for the finish step. A bare `--code` reads FLUID_LOGIN_CODE,\n * `--code -` reads stdin, and any other value is the code. Stdin is read\n * only when asked for: an agent's stdin may be a pipe that never closes,\n * and reading it uninvited would wait forever.\n */\nasync function readCode(\n opts: LoginOptions,\n deps: LoginDeps,\n): Promise<string | undefined> {\n if (opts.code === \"-\") {\n return (await deps.readStdin()).trim() || undefined;\n }\n if (typeof opts.code === \"string\") {\n deps.err(\n chalk.yellow(\n \"Warning: a code passed via --code is visible in shell history and process listings. \" +\n \"Prefer FLUID_LOGIN_CODE, or --code - to read it from stdin.\",\n ),\n );\n return opts.code.trim();\n }\n return deps.env[\"FLUID_LOGIN_CODE\"]?.trim() || undefined;\n}\n\n/** The server's answer for a code that cannot finish, by error code. */\nfunction finishError(error: FluidApiError, shop: string): CliError {\n // The server answers a sign-in it cannot finish with a code exactly as it\n // answers a wrong code, so the reasons are listed here together.\n if (error.code === \"INVALID_CODE\") {\n return {\n code: error.code,\n message:\n `${error.message}. If the code is right, the shop \"${shop}\" may be wrong, ` +\n \"the address may not be an admin or rep there, or the company may sign in with an emailed link instead. \" +\n \"If it does, pass that link to --code in place of the code. Five wrong codes lock this sign-in. \" +\n \"If no code arrived, run --send-code again.\",\n };\n }\n if (error.code === \"SIGN_IN_UNFINISHED\") {\n return {\n code: error.code,\n message: `${error.message} (shop \"${shop}\"): run --send-code again.`,\n };\n }\n // The saved sign-in is kept, so the same code finishes it later.\n if (error.code === \"CONTACT_MISSING\") {\n return {\n code: error.code,\n message: `${error.message}, then run --code again with the same code.`,\n };\n }\n return error;\n}\n\n/** `fluid login --code`: redeem the code for the saved sign-in. */\nasync function finishStep(\n opts: LoginOptions,\n interactive: boolean,\n ui: Ui,\n deps: LoginDeps,\n): Promise<number> {\n if (!opts.email) {\n return ui.fail({\n code: \"EMAIL_REQUIRED\",\n message: \"--code needs --email <address>, the one used with --send-code.\",\n });\n }\n // Without a terminal no one can answer \"replace the profile?\", and the\n // profile's name (the company's) is known only once the code is spent.\n // Asking for the choice now means the code is never spent on a refusal.\n if (!interactive && !opts.yes && !opts.name) {\n return ui.fail({\n code: \"YES_OR_NAME_REQUIRED\",\n message:\n \"With no terminal, --code needs --yes, to replace a profile with the company's name, or --name <profile>.\",\n });\n }\n const email = normaliseEmail(opts.email);\n\n const record = deps.pending.load(email);\n if (!record) {\n return ui.fail({\n code: \"NO_PENDING_LOGIN\",\n message: `No sign-in is waiting for ${email}. Run fluid login --send-code --email ${email} first.`,\n });\n }\n // The code is tied to the shop it was sent for, so that is the one\n // confirmed; a --shop here only has to agree with it.\n const { shop } = record;\n if (opts.shop && shopLabel(opts.shop) !== shopLabel(shop)) {\n return ui.fail({\n code: \"SHOP_MISMATCH\",\n message: `The code for ${email} was sent for ${shop}, not ${opts.shop}.`,\n });\n }\n\n if (!(Date.parse(record.expiresAt) > Date.now())) {\n deps.pending.remove(email);\n return ui.fail({\n code: \"CODE_EXPIRED\",\n message: `The code for ${email} has expired. Run fluid login --send-code again.`,\n });\n }\n\n const code = await readCode(opts, deps);\n if (!code) {\n return ui.fail({\n code: \"NO_CODE\",\n message:\n \"No code given. Put it in FLUID_LOGIN_CODE, pass --code - to read it from stdin, or pass it to --code.\",\n });\n }\n // A flagged company's person is emailed a link, not a code: redeeming it\n // finishes this sign-in through the identity service instead.\n const linkToken = identityLinkToken(code);\n if (!linkToken && !/^\\d{6}$/.test(code)) {\n return ui.fail({\n code: \"INVALID_CODE_FORMAT\",\n message: \"The code must be exactly 6 digits.\",\n });\n }\n\n // Confirming a code, or redeeming a link, uses it up, so a named profile\n // that would be refused is checked first. Without a terminal, the check\n // above has already required --yes or --name. A link signs in through\n // One Auth, which replaces a legacy profile without asking.\n const overwrite = { yes: Boolean(opts.yes), interactive };\n if (\n opts.name &&\n !(linkToken && isLegacyProfile(readConfig().profiles[opts.name])) &&\n overwriteRule(opts.name, overwrite) === \"refuse\"\n ) {\n return ui.fail(profileExists(opts.name, false));\n }\n\n if (linkToken) {\n return identityResult(\n await loginWithIdentityLink(linkToken, {\n ...identityContext(opts, interactive, ui, deps, record.baseUrl),\n loginHint: normaliseEmail(email),\n // The pending sign-in ends only once the link is spent or gone; a\n // failure that may not have spent it keeps it for a retry.\n onLinkSettled: () => deps.pending.remove(email),\n }),\n ui,\n deps,\n );\n }\n\n const spinner = ui.spinner(\"Verifying code...\");\n const confirmed = await deps.api.confirmMfa(record.uuid, code, {\n fluidShop: shop,\n baseUrl: record.baseUrl,\n });\n if (!confirmed.success) {\n // A wrong code may be retried. A rate limit or an unreachable server\n // may not have spent it, so the sign-in is kept for one more try; if\n // the code was spent after all, that try is refused as a wrong code (a\n // 410 on servers before ENG-2877, which ends the sign-in). A\n // missing contact leaves the code unspent, so it works again once the\n // contact is restored. Anything else ends this sign-in now.\n const retryable = [\n \"INVALID_CODE\",\n \"RATE_LIMITED\",\n \"API_UNREACHABLE\",\n \"CONTACT_MISSING\",\n ];\n if (!retryable.includes(confirmed.error.code)) deps.pending.remove(email);\n return ui.fail(finishError(confirmed.error, shop), spinner);\n }\n spinner.succeed(\"Verified\");\n deps.pending.remove(email);\n\n // Rails handed out no token: every company the code covered signs in\n // through the identity service (Phase 007 INV-7.5).\n if (signInPathFor(confirmed.value) === \"identity\") {\n return identityResult(\n await loginWithIdentity({\n ...identityContext(opts, interactive, ui, deps, record.baseUrl),\n loginHint: normaliseEmail(email),\n ...pinnedIdentity(confirmed.value.companyUuid),\n }),\n ui,\n deps,\n );\n }\n\n const { companies } = confirmed.value;\n const selected = findByShop(companies, shop);\n if (!selected) {\n if (companies.length === 0) {\n return ui.fail({\n code: \"NO_COMPANIES\",\n message: \"No companies found for this account.\",\n });\n }\n const shops = companies.map((c) => c.shopName).join(\", \");\n return ui.fail({\n code: \"SHOP_NOT_FOUND\",\n message: `This account has no company at ${shop}. It has: ${shops}.`,\n });\n }\n\n if (!isStaffSession(selected)) {\n return ui.fail(shopperSession(email, selected));\n }\n\n const name = opts.name ?? selected.name;\n const decision = await overwriteDecision(name, overwrite, deps);\n if (decision === \"refuse\") return ui.fail(profileExists(name, true));\n if (decision === \"keep\") return cancelled(deps);\n\n await storeProfile(deps, name, selected.jwt, selected.name, record.baseUrl);\n return loggedIn(ui, deps, name, {\n id: selected.id,\n name: selected.name,\n shop: selected.shopName,\n });\n}\n\n/**\n * Run `fluid login` and return its exit code.\n */\nexport async function runLogin(\n opts: LoginOptions,\n deps: LoginDeps = defaultLoginDeps,\n): Promise<number> {\n const json = Boolean(opts.json);\n const ui = createUi(json, deps);\n // `--json` is for a program reading the output, which cannot answer a\n // prompt either. Nor can a run that reads the code from stdin with\n // `--code -`: stdin has ended by the time a prompt would read it.\n const interactive = deps.isInteractive() && !json && opts.code !== \"-\";\n\n if (opts.sendCode || opts.code !== undefined) {\n if (opts.token) {\n return ui.fail({\n code: \"FLAG_CONFLICT\",\n message: \"--token cannot be combined with --send-code or --code.\",\n });\n }\n if (opts.sendCode && opts.code !== undefined) {\n return ui.fail({\n code: \"FLAG_CONFLICT\",\n message: \"Run --send-code and --code as two separate commands.\",\n });\n }\n // FLUID_TOKEN is left alone here: an agent may have one exported from\n // an earlier sign-in, and these flags ask for an email sign-in.\n return opts.sendCode\n ? sendCodeStep(opts, ui, deps)\n : finishStep(opts, interactive, ui, deps);\n }\n\n // Accept token from env var to avoid shell history / process listing exposure\n const token = opts.token ?? deps.env[\"FLUID_TOKEN\"];\n if (token) {\n if (opts.token) {\n (json ? deps.err : deps.log)(\n chalk.yellow(\n \"Warning: token passed via --token flag is visible in shell history and process listings. \" +\n \"Prefer the FLUID_TOKEN environment variable.\",\n ),\n );\n }\n return loginWithToken(token, opts, interactive, ui, deps);\n }\n\n if (!interactive) {\n const why = json\n ? \"fluid login --json cannot ask for the email and code.\"\n : \"fluid login needs a terminal to ask for the email and code.\";\n return ui.fail({\n code: \"NOT_INTERACTIVE\",\n message: `${why}\\n${TWO_STEP_HINT}`,\n });\n }\n return loginWithEmail(opts, ui, deps);\n}\n\n/**\n * The `login` command, running `run` with the parsed options. Built by a\n * function so a test can check the flag parsing without signing in.\n */\nexport function buildLoginCommand(\n run: (opts: LoginOptions) => Promise<number> = (opts) => runLogin(opts),\n): Command {\n return new Command(\"login\")\n .description(\"Authenticate with the Fluid API\")\n .option(\n \"-t, --token <token>\",\n \"API token (skips email flow). Prefer FLUID_TOKEN env var to avoid shell history exposure\",\n )\n .option(\n \"-e, --email <email>\",\n \"Email address for MFA login (required with --send-code and --code)\",\n )\n .option(\"-n, --name <name>\", \"Profile name (defaults to company name)\")\n .option(\n \"--shop <shop>\",\n \"Sign in to this company (e.g. acme or acme.fluid.app); required with --send-code. An admin's emailed code also confirms a new signup\",\n )\n .option(\n \"--send-code\",\n \"Email a sign-in code and exit, for use without a terminal; finish with --code\",\n )\n .option(\n \"--code [code]\",\n \"Finish a sign-in started with --send-code. Reads the code from FLUID_LOGIN_CODE, or from stdin with --code -; a code given here is visible in shell history\",\n )\n .option(\"-y, --yes\", \"Replace an existing profile without asking\")\n .option(\"--json\", \"Print the result as JSON\")\n .action(async (opts: LoginOptions) => {\n const exitCode = await run(opts);\n if (exitCode !== 0) process.exitCode = exitCode;\n });\n}\n\nexport const loginCommand = buildLoginCommand();\n","/**\n * fluid signup — create a Fluid company with the public signup endpoint\n *\n * Runs before any sign-in, so it calls `POST /api/company` directly rather\n * than through a profile's client. The person behind the email then\n * confirms the signup, by the emailed link or by signing in with the two\n * `fluid login` steps this command prints.\n */\n\nimport { chmodSync, mkdirSync, mkdtempSync, writeFileSync } from \"node:fs\";\nimport { randomUUID } from \"node:crypto\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\nimport prompts from \"prompts\";\nimport {\n getFluidApiBase,\n isInsecureRemoteBase,\n pollAgentAccess,\n signup,\n type AgentAccessPoll,\n type AgentAccessRequestHandle,\n type SignupError,\n type SignupRequest,\n} from \"../auth/fluid-api.js\";\nimport type { ClientProfileInput } from \"../auth/identity/client.js\";\nimport { readConfig, readStoredConfig } from \"../config/config.js\";\nimport { isStrictConfig } from \"../config/strict.js\";\nimport { resolveIdentityUrl } from \"../auth/identity/environment.js\";\nimport { normaliseEmail } from \"../auth/pending-login.js\";\nimport { shellSafe } from \"../utils/shell.js\";\nimport { getConfigDir } from \"../config/paths.js\";\n\nexport interface SignupOptions {\n readonly email?: string;\n readonly firstName?: string;\n readonly lastName?: string;\n readonly companyName?: string;\n readonly subdomain?: string;\n readonly color?: string;\n readonly yes?: boolean;\n readonly json?: boolean;\n /** `true` for the default agent name, or the name given. */\n readonly agentAccess?: string | boolean;\n}\n\nconst AGENT_NAME_MAX = 100;\nconst DEFAULT_AGENT_NAME = \"Fluid CLI agent\";\nconst MIN_POLL_SECONDS = 5;\nconst MAX_BACKOFF_SECONDS = 60;\nconst ISSUING_GRACE_MS = 20 * 60 * 1000;\n\ninterface Spinner {\n stop(): unknown;\n}\n\n/** Everything `runSignup` reaches outside itself, for tests. */\nexport interface SignupDeps {\n readonly api: { readonly signup: typeof signup };\n readonly prompt: (\n question: prompts.PromptObject,\n ) => Promise<prompts.Answers<string>>;\n /** Shown in text mode while the signup runs, which can take a while. */\n readonly spinner: (text: string) => Spinner;\n readonly log: (line: string) => void;\n /** Progress for a person while `--json` keeps stdout to one document. */\n readonly notice: (line: string) => void;\n readonly isInteractive: () => boolean;\n readonly agent: {\n readonly poll: (handle: string) => Promise<AgentAccessPoll>;\n readonly saveProfile: (\n name: string,\n input: ClientProfileInput,\n options: { readonly replace: boolean },\n ) => Promise<unknown>;\n readonly strictConfig: () => boolean;\n /** Writes text to a private file and returns its path; throws if no location works. */\n readonly stashRecovery: (text: string) => string;\n readonly stderrIsTty: () => boolean;\n readonly platform: () => string;\n readonly sleep: (ms: number) => Promise<void>;\n readonly now: () => number;\n readonly apiBase: () => string;\n readonly identityUrl: (apiBase: string) => string | null;\n readonly profileExists: (name: string) => boolean;\n readonly profileVisible: (name: string) => boolean;\n };\n}\n\nexport const defaultSignupDeps: SignupDeps = {\n api: { signup },\n prompt: (question) => prompts(question),\n spinner: (text) => ora(text).start(),\n log: (line) => console.log(line),\n notice: (line) => console.error(line),\n isInteractive: () => Boolean(process.stdin.isTTY),\n agent: {\n poll: pollAgentAccess,\n saveProfile: async (name, input, options) =>\n (await import(\"../auth/identity/client.js\")).saveClientProfile(\n name,\n input,\n options,\n ),\n strictConfig: isStrictConfig,\n stashRecovery: writeRecoveryFile,\n stderrIsTty: () => Boolean(process.stderr.isTTY),\n platform: () => process.platform,\n sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),\n now: Date.now,\n apiBase: getFluidApiBase,\n identityUrl: (apiBase) => resolveIdentityUrl(apiBase),\n profileExists: (name) => Boolean(readStoredConfig().profiles[name]),\n profileVisible: (name) => Boolean(readConfig().profiles[name]),\n },\n};\n\n// The same DNS-label rule the server validates a new subdomain against.\nconst SUBDOMAIN_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\nconst COLOR_PATTERN = /^(?:[a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/;\nconst EMAIL_PATTERN = /^[^\\s@]+@[^\\s@]+$/;\n\n/**\n * The subdomain as the server would store it: lowercase, letters, digits\n * and hyphens only, at most 63 characters, no hyphen at either end. The\n * server checks \"is taken\" against the value as sent, before it cleans it\n * up, so sending the clean form keeps that check meaningful.\n */\nexport function normaliseSubdomain(raw: string): string {\n const trimmed = (value: string) => value.replace(/^-+|-+$/g, \"\");\n return trimmed(\n trimmed(raw.toLowerCase())\n .replace(/[^a-z0-9-]/g, \"\")\n .slice(0, 63),\n );\n}\n\n/**\n * The two commands that sign in to the new company and confirm it. The\n * second names its own profile rather than passing `--yes`, which would\n * replace an existing profile that happens to share the company's name.\n * If a profile with that name exists, login refuses `--name` before the code\n * is spent when there is no terminal, and asks first at one.\n */\nexport function nextCommands(\n email: string,\n fluidShop: string,\n subdomain: string,\n): string[] {\n const safeEmail = shellSafe(email, \"<email>\");\n const safeShop = shellSafe(fluidShop, \"<shop>\");\n return [\n `fluid login --send-code --email ${safeEmail} --shop ${safeShop}`,\n `fluid login --code --email ${safeEmail} --shop ${safeShop} --name ${shellSafe(subdomain, \"<profile>\")}`,\n ];\n}\n\nconst REQUIRED_FLAGS: ReadonlyArray<[keyof SignupOptions, string]> = [\n [\"email\", \"--email\"],\n [\"firstName\", \"--first-name\"],\n [\"lastName\", \"--last-name\"],\n [\"companyName\", \"--company-name\"],\n [\"subdomain\", \"--subdomain\"],\n];\n\n/** The request to send, or why the flags can't make one. */\nfunction buildRequest(\n opts: SignupOptions,\n): { request: SignupRequest } | { error: SignupError } {\n const missing = REQUIRED_FLAGS.filter(([key]) => {\n const value = opts[key];\n return typeof value !== \"string\" || value.trim() === \"\";\n }).map(([, flag]) => flag);\n if (missing.length > 0) {\n return {\n error: {\n code: \"FLAGS_REQUIRED\",\n message: `fluid signup needs ${missing.join(\", \")}.`,\n },\n };\n }\n\n const email = normaliseEmail(opts.email ?? \"\");\n if (!EMAIL_PATTERN.test(email)) {\n return {\n error: {\n code: \"INVALID_EMAIL\",\n message: `${email} is not an email address.`,\n },\n };\n }\n\n const subdomain = normaliseSubdomain(opts.subdomain ?? \"\");\n if (!SUBDOMAIN_PATTERN.test(subdomain)) {\n return {\n error: {\n code: \"INVALID_SUBDOMAIN\",\n message:\n \"--subdomain needs at least one letter or digit; it may also hold hyphens, up to 63 characters.\",\n },\n };\n }\n\n const agentName =\n typeof opts.agentAccess === \"string\" ? opts.agentAccess.trim() : \"\";\n if ([...agentName].length > AGENT_NAME_MAX) {\n return {\n error: {\n code: \"AGENT_NAME_INVALID\",\n message: `The --agent-access name can be at most ${AGENT_NAME_MAX} characters.`,\n },\n };\n }\n\n const color = opts.color?.trim().replace(/^#/, \"\");\n if (color !== undefined && !COLOR_PATTERN.test(color)) {\n return {\n error: {\n code: \"INVALID_COLOR\",\n message: \"--color must be a 3- or 6-digit hex colour, such as 0C7CF6.\",\n },\n };\n }\n\n return {\n request: {\n email,\n firstName: (opts.firstName ?? \"\").trim(),\n lastName: (opts.lastName ?? \"\").trim(),\n companyName: (opts.companyName ?? \"\").trim(),\n subdomain,\n ...(color ? { color } : {}),\n ...(opts.agentAccess\n ? {\n agentAccess: {\n name: agentName || DEFAULT_AGENT_NAME,\n },\n }\n : {}),\n },\n };\n}\n\ninterface AgentTarget {\n readonly profileName: string;\n readonly apiBase: string;\n readonly identityUrl: string;\n}\n\ntype AgentOutcome =\n | { readonly stored: string }\n | { readonly failed: SignupError };\n\n/**\n * Waits for the signup's agent-access request to be approved and stores the\n * credential it delivers. Polls no faster than Fluid allows, stops on a final\n * answer or when the request expires, and saves the credential exactly once:\n * a delivered secret is never shown again, and a second poll revokes it.\n */\nasync function awaitAgentCredential(\n access: AgentAccessRequestHandle,\n target: AgentTarget,\n companyName: string,\n yes: boolean,\n deps: SignupDeps,\n): Promise<AgentOutcome> {\n const { agent } = deps;\n const { profileName, apiBase, identityUrl } = target;\n const giveUpAt = Date.parse(access.expiresAt) + ISSUING_GRACE_MS;\n let wait = MIN_POLL_SECONDS;\n let failures = 0;\n for (;;) {\n if (Number.isFinite(giveUpAt) && agent.now() >= giveUpAt) {\n return agentFailure(\"AGENT_ACCESS_EXPIRED\");\n }\n await agent.sleep(wait * 1000);\n const answer = await agent.poll(access.handle);\n wait = MIN_POLL_SECONDS;\n switch (answer.state) {\n case \"pending\":\n case \"issuing_soon\":\n case \"slow_down\":\n failures = 0;\n wait = Math.max(answer.retryAfter ?? 0, MIN_POLL_SECONDS);\n break;\n case \"retry\":\n failures += 1;\n wait = Math.max(\n answer.retryAfter ?? 0,\n Math.min(MIN_POLL_SECONDS * 2 ** failures, MAX_BACKOFF_SECONDS),\n );\n break;\n case \"denied\":\n return agentFailure(\"AGENT_ACCESS_DENIED\");\n case \"expired\":\n return agentFailure(\"AGENT_ACCESS_EXPIRED\");\n case \"revoked\":\n return agentFailure(\"AGENT_ACCESS_REVOKED\");\n case \"unavailable\":\n return agentFailure(\"AGENT_ACCESS_UNAVAILABLE\");\n case \"delivered\": {\n try {\n await agent.saveProfile(\n profileName,\n {\n clientId: answer.clientId,\n clientSecret: answer.clientSecret,\n org: access.companyUuid,\n identityUrl,\n companyName,\n baseUrl: apiBase,\n },\n { replace: yes },\n );\n if (!agent.profileVisible(profileName)) {\n throw new Error(\n \"the saved profile is not visible to this process (strict config)\",\n );\n }\n } catch (error) {\n const report = reportUnstored(\n agent,\n answer,\n access.companyUuid,\n identityUrl,\n errorText(error),\n );\n let summary = report.summary;\n try {\n deps.notice(report.stderr);\n } catch {\n summary = report.ifSilent;\n }\n return agentFailure(\n \"AGENT_ACCESS_NOT_STORED\",\n errorText(error),\n summary,\n );\n }\n return { stored: profileName };\n }\n }\n }\n}\n\n/**\n * Writes `content` to a new mode-0600 file in the CLI config dir, or, if that\n * fails, in a fresh 0700 temp dir. Returns the path; throws if both fail.\n */\nexport function writeRecoveryFile(content: string): string {\n const name = `agent-access-recovery-${randomUUID()}.txt`;\n const write = (dir: string): string => {\n const file = join(dir, name);\n writeFileSync(file, content, { mode: 0o600, flag: \"wx\" });\n chmodSync(file, 0o600);\n return file;\n };\n try {\n const dir = getConfigDir();\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n return write(dir);\n } catch {\n return write(mkdtempSync(join(tmpdir(), \"fluid-agent-access-\")));\n }\n}\n\nfunction credentialDetails(\n delivered: { readonly clientId: string; readonly clientSecret: string },\n org: string,\n identityUrl: string,\n): string {\n return [\n `client_id: ${delivered.clientId}`,\n `client_secret: ${delivered.clientSecret}`,\n `organization: ${org}`,\n `token endpoint: ${identityUrl.replace(/\\/$/, \"\")}/token (HTTP Basic client_credentials, resource=${org})`,\n ].join(\"\\n\");\n}\n\nconst NOT_STORED = \"The credential was issued but could not be stored.\";\n\nfunction revokeText(clientId: string): string {\n 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.`;\n}\n\n/**\n * What a failed save reports. `stderr` is the text to print and `summary` is the matching message for the\n * error, so neither claims more than the branch taken. The secret goes to a\n * private file with only its path printed; without a file (always on win32)\n * it is printed only when stderr is a terminal.\n */\nfunction reportUnstored(\n agent: SignupDeps[\"agent\"],\n delivered: { readonly clientId: string; readonly clientSecret: string },\n org: string,\n identityUrl: string,\n reason: string,\n): {\n readonly stderr: string;\n readonly summary: string;\n readonly ifSilent: string;\n} {\n const head = `The agent's credential was issued but not stored (${reason}). Fluid shows it once.`;\n const details = credentialDetails(delivered, org, identityUrl);\n if (agent.platform() !== \"win32\") {\n try {\n const file = agent.stashRecovery(details);\n return {\n 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.`,\n summary: `${NOT_STORED} Its details, including the secret, were written to ${file} (readable only by you); stderr names the file.`,\n ifSilent: `${NOT_STORED} Its details, including the secret, were written to ${file} (readable only by you); reporting that on stderr failed.`,\n };\n } catch {\n // Fall through to the terminal or the revoke instructions.\n }\n }\n if (agent.stderrIsTty()) {\n return {\n stderr: `${head} No private file could be written, so here it is; keep it now:\\n${details}`,\n summary: `${NOT_STORED} No private file could be written, so the details, including the secret, were printed to stderr.`,\n ifSilent: `${NOT_STORED} No private file could be written and printing to stderr failed, so the secret was not emitted anywhere. ${revokeText(delivered.clientId)}`,\n };\n }\n 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)}`;\n return { stderr: summary, summary, ifSilent: summary };\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nconst AGENT_FAILURES: Record<string, string> = {\n AGENT_ACCESS_DENIED: \"An administrator denied the agent's access request.\",\n AGENT_ACCESS_EXPIRED:\n \"The agent's access request expired before it was approved. Run signup again with a different subdomain to ask anew.\",\n AGENT_ACCESS_REVOKED:\n \"The agent's credential was already delivered, so Fluid revoked it. Run signup again with a different subdomain to ask anew.\",\n AGENT_ACCESS_UNAVAILABLE:\n \"Fluid cannot issue the agent a credential for this company right now.\",\n AGENT_ACCESS_NOT_STORED: NOT_STORED,\n};\n\nfunction agentFailure(\n code: string,\n details?: string,\n message?: string,\n): AgentOutcome {\n return {\n failed: {\n code,\n message: message ?? AGENT_FAILURES[code] ?? code,\n ...(details ? { details } : {}),\n },\n };\n}\n\n// A plain CliError fits too: every field SignupError adds is optional.\nfunction printFailure(\n error: SignupError,\n json: boolean,\n deps: SignupDeps,\n): number {\n if (json) {\n deps.log(\n JSON.stringify(\n {\n status: \"error\",\n code: error.code,\n message: error.message,\n ...(error.status !== undefined ? { httpStatus: error.status } : {}),\n ...(error.errors ? { errors: error.errors } : {}),\n ...(error.retryAfter !== undefined\n ? { retryAfter: error.retryAfter }\n : {}),\n ...(error.details ? { details: error.details } : {}),\n },\n null,\n 2,\n ),\n );\n return 1;\n }\n deps.log(chalk.red(error.message));\n if (error.errors) deps.log(chalk.dim(JSON.stringify(error.errors)));\n if (error.retryAfter !== undefined) {\n deps.log(chalk.dim(`Retry after ${error.retryAfter} seconds.`));\n }\n if (error.details) deps.log(chalk.dim(error.details));\n return 1;\n}\n\n/**\n * Run `fluid signup` and return its exit code.\n */\nexport async function runSignup(\n opts: SignupOptions,\n deps: SignupDeps = defaultSignupDeps,\n): Promise<number> {\n const json = Boolean(opts.json);\n const built = buildRequest(opts);\n if (\"error\" in built) return printFailure(built.error, json, deps);\n const { request } = built;\n let target: AgentTarget | undefined;\n if (request.agentAccess) {\n if (deps.agent.strictConfig()) {\n return printFailure(\n {\n code: \"AGENT_ACCESS_STRICT_CONFIG\",\n message:\n \"--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.\",\n },\n json,\n deps,\n );\n }\n const apiBase = deps.agent.apiBase();\n if (isInsecureRemoteBase(apiBase)) {\n return printFailure(\n {\n code: \"AGENT_ACCESS_INSECURE_BASE\",\n message:\n \"--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.\",\n },\n json,\n deps,\n );\n }\n const identityUrl = deps.agent.identityUrl(apiBase);\n if (!identityUrl) {\n return printFailure(\n {\n code: \"AGENT_ACCESS_NO_IDENTITY\",\n message:\n \"--agent-access needs an identity service, and this API base has none. Set FLUID_IDENTITY_URL or drop --agent-access.\",\n },\n json,\n deps,\n );\n }\n const profileName = `${request.subdomain}-agent`;\n if (deps.agent.profileExists(profileName) && !opts.yes) {\n return printFailure(\n {\n code: \"PROFILE_EXISTS\",\n message: `Profile \"${profileName}\" already exists. Pass --yes to replace it.`,\n },\n json,\n deps,\n );\n }\n target = { profileName, apiBase, identityUrl };\n }\n\n if (!opts.yes) {\n const question = `Create ${request.companyName} at subdomain ${request.subdomain}, and email ${request.email} to confirm it?`;\n // `--json` is for a program reading the output, which cannot answer a\n // prompt, and a closed stdin never answers one either.\n if (json || !deps.isInteractive()) {\n return printFailure(\n {\n code: \"CONFIRM_REQUIRED\",\n message: `${question} Pass --yes to confirm.`,\n },\n json,\n deps,\n );\n }\n const answer = await deps.prompt({\n type: \"confirm\",\n name: \"ok\",\n message: question,\n initial: false,\n });\n if (!answer[\"ok\"]) {\n return printFailure(\n { code: \"CANCELLED\", message: \"Cancelled.\" },\n json,\n deps,\n );\n }\n }\n\n const spinner = json ? undefined : deps.spinner(\"Signing up...\");\n const result = await deps.api.signup(request);\n spinner?.stop();\n if (!result.success) return printFailure(result.error, json, deps);\n\n const created = result.value;\n const next = nextCommands(\n request.email,\n created.company.fluidShop,\n created.company.subdomain,\n );\n if (json) {\n const base = {\n status: \"signed_up\",\n company: created.company,\n userCompany: created.userCompany,\n currentlyDue: created.currentlyDue,\n next,\n };\n if (!created.agentAccess || !target) {\n deps.log(JSON.stringify(base, null, 2));\n return 0;\n }\n const { approvalUrl, expiresAt } = created.agentAccess;\n deps.notice(\n `Waiting for an administrator to approve the agent at ${approvalUrl} (until ${expiresAt}).`,\n );\n const outcome = await awaitAgentCredential(\n created.agentAccess,\n target,\n created.company.name,\n Boolean(opts.yes),\n deps,\n );\n const agentAccess =\n \"failed\" in outcome\n ? {\n approvalUrl,\n expiresAt,\n status: \"error\",\n code: outcome.failed.code,\n message: outcome.failed.message,\n ...(outcome.failed.details\n ? { details: outcome.failed.details }\n : {}),\n }\n : {\n approvalUrl,\n expiresAt,\n status: \"stored\",\n profile: outcome.stored,\n };\n deps.log(JSON.stringify({ ...base, agentAccess }, null, 2));\n return \"failed\" in outcome ? 1 : 0;\n }\n\n deps.log(\n chalk.green(\n `Signed up ${created.company.name} as ${created.company.fluidShop} (company ${created.company.id}).`,\n ),\n );\n if (request.subdomain !== (opts.subdomain ?? \"\").trim()) {\n deps.log(chalk.dim(`Subdomain sent as ${request.subdomain}.`));\n }\n deps.log(\n `${request.email} confirms it from the emailed link, or by signing in with the emailed code:`,\n );\n for (const command of next) deps.log(` ${command}`);\n deps.log(\n chalk.dim(\n \"A repeat signup for the same email within an hour normally sends no new email.\",\n ),\n );\n if (!created.agentAccess || !target) return 0;\n\n deps.log(\n `An administrator approves the agent at ${created.agentAccess.approvalUrl} (after confirming the signup). Waiting for approval until ${created.agentAccess.expiresAt}...`,\n );\n const outcome = await awaitAgentCredential(\n created.agentAccess,\n target,\n created.company.name,\n Boolean(opts.yes),\n deps,\n );\n if (\"failed\" in outcome) return printFailure(outcome.failed, false, deps);\n deps.log(\n chalk.green(\n `Approved. The agent's credential is saved as profile ${outcome.stored}.`,\n ),\n );\n return 0;\n}\n\n/**\n * The `signup` command, running `run` with the parsed options. Built by a\n * function so a test can check the flag parsing without signing up.\n */\nexport function buildSignupCommand(\n run: (opts: SignupOptions) => Promise<number> = (opts) => runSignup(opts),\n): Command {\n return new Command(\"signup\")\n .description(\n \"Create a Fluid company with the public signup; the person behind --email confirms it\",\n )\n .option(\n \"-e, --email <email>\",\n \"The person's email address; Fluid emails it to confirm the signup\",\n )\n .option(\"--first-name <name>\", \"The person's first name\")\n .option(\"--last-name <name>\", \"The person's last name\")\n .option(\"--company-name <name>\", \"The company's name\")\n .option(\n \"--subdomain <subdomain>\",\n \"The store's subdomain (acme gives acme.fluid.app); sent lowercase, letters, digits and hyphens only\",\n )\n .option(\n \"--color <hex>\",\n \"Brand colour as 3 or 6 hex digits, such as 0C7CF6\",\n )\n .option(\n \"--agent-access [name]\",\n \"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)\",\n )\n .option(\"-y, --yes\", \"Sign up without asking\")\n .option(\"--json\", \"Print the result as JSON\")\n .action(async (opts: SignupOptions) => {\n const exitCode = await run(opts);\n if (exitCode !== 0) process.exitCode = exitCode;\n });\n}\n\nexport const signupCommand = buildSignupCommand();\n","/**\n * fluid logout — remove stored auth profile(s)\n *\n * An identity-mode profile's session is revoked at the identity service and\n * its refresh token deleted from the credential store, once no remaining\n * profile uses it. (The identity service's `/signout` is a browser\n * navigation; a native client revokes its refresh token instead.)\n */\n\nimport { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport { endUnusedSessions } from \"../auth/identity/profiles.js\";\nimport { readConfig, writeConfig } from \"../config/config.js\";\nimport { withConfigLock } from \"../config/lock.js\";\nimport type { FluidConfig } from \"../config/types.js\";\n\nexport const logoutCommand = new Command(\"logout\")\n .description(\"Remove stored authentication\")\n .option(\"-a, --all\", \"Remove all profiles\")\n .action(async (opts: { all?: boolean }) => {\n let before: FluidConfig | undefined;\n let after: FluidConfig | undefined;\n withConfigLock(() => {\n const config = readConfig();\n if (opts.all) {\n before = config;\n after = { ...config, activeProfile: null, profiles: {} };\n } else if (config.activeProfile) {\n before = config;\n const { [config.activeProfile]: _, ...remainingProfiles } =\n config.profiles;\n after = {\n ...config,\n activeProfile: Object.keys(remainingProfiles)[0] ?? null,\n profiles: remainingProfiles,\n };\n }\n if (after) writeConfig(after);\n });\n\n if (!before || !after) {\n console.log(chalk.yellow(\"Not currently logged in.\"));\n return;\n }\n\n for (const problem of await endUnusedSessions(before, after)) {\n console.log(chalk.yellow(problem));\n }\n\n if (opts.all) {\n console.log(chalk.green(\"All profiles removed.\"));\n return;\n }\n\n console.log(\n chalk.green(`Logged out of profile ${chalk.bold(before.activeProfile)}.`),\n );\n if (after.activeProfile) {\n console.log(chalk.dim(`Switched to profile ${after.activeProfile}.`));\n }\n });\n","/**\n * fluid profiles — list stored auth profiles. Never prints a secret: a\n * client profile shows its client id and company, and the secret stays in the\n * operating system credential store.\n */\n\nimport { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport { readConfig } from \"../config/config.js\";\nimport type { FluidProfile } from \"../config/types.js\";\n\nfunction modeOf(profile: FluidProfile): string {\n return profile.auth?.mode ?? \"token\";\n}\n\nexport const profilesCommand = new Command(\"profiles\")\n .description(\"List stored profiles\")\n .action(() => {\n const config = readConfig();\n const profiles = Object.values(config.profiles);\n if (profiles.length === 0) {\n console.log(chalk.yellow(\"No profiles stored. Run `fluid login` first.\"));\n return;\n }\n for (const profile of profiles) {\n const active = profile.name === config.activeProfile ? \" (active)\" : \"\";\n console.log(`${chalk.bold(profile.name)}${active}`);\n console.log(` Mode: ${modeOf(profile)}`);\n console.log(` Company: ${profile.companyName}`);\n if (profile.auth?.mode === \"client\") {\n console.log(` Client: ${profile.auth.clientId}`);\n console.log(` Org: ${profile.auth.org}`);\n }\n }\n });\n","/**\n * fluid whoami — show current auth profile and validate against API\n *\n * An identity-mode profile is shown from its identity session: the facts\n * come from the identity service's `/userinfo`, never from decoding a token.\n */\n\nimport { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\nimport { clientAccessToken } from \"../auth/identity/client.js\";\nimport {\n type CredentialSourceDescription,\n describeCredentialSource,\n getActiveProfile,\n resolveCredentialSource,\n} from \"../auth/token.js\";\nimport { validateToken } from \"../auth/fluid-api.js\";\nimport {\n describeIdentityError,\n identityToken,\n} from \"../auth/identity/session.js\";\nimport {\n type ClientProfile,\n type IdentityProfile,\n isClientProfile,\n isIdentityProfile,\n} from \"../config/types.js\";\n\nfunction sourceLabel(source: CredentialSourceDescription): string {\n if (source.envVar) return source.envVar;\n if (source.origin === \"fluidrc\")\n return `.fluidrc profile ${source.profileName}`;\n if (source.origin === \"explicit\") return `profile ${source.profileName}`;\n return `config.json profile ${source.profileName}`;\n}\n\nfunction printSource(source: CredentialSourceDescription): void {\n console.log(` Source: ${chalk.bold(sourceLabel(source))}`);\n console.log(` Mode: ${source.mode}`);\n}\n\nasync function whoamiIdentity(\n profile: IdentityProfile,\n source: CredentialSourceDescription,\n): Promise<void> {\n const spinner = ora(\"Checking your identity session...\").start();\n let facts;\n try {\n ({ facts } = await identityToken(profile.auth));\n } catch (error) {\n spinner.fail(chalk.red(describeIdentityError(error)));\n console.log(chalk.dim(`Profile: ${profile.name}`));\n process.exitCode = 1;\n return;\n }\n\n spinner.succeed(chalk.green(\"Authenticated (Fluid identity service)\"));\n console.log(` Profile: ${chalk.bold(profile.name)}`);\n printSource(source);\n console.log(` Company: ${chalk.bold(profile.companyName)}`);\n if (facts.companyId) {\n console.log(` Company ID: ${chalk.dim(facts.companyId)}`);\n }\n console.log(` Subject: ${chalk.dim(facts.subject)}`);\n if (facts.roles.length > 0) {\n console.log(` Roles: ${facts.roles.join(\", \")}`);\n }\n if (facts.impersonating && facts.actor) {\n console.log(` Acting as: ${chalk.yellow(facts.actor)}`);\n }\n console.log(\n ` Signed in: ${chalk.dim(new Date(facts.authTime * 1000).toISOString())}`,\n );\n console.log(` Stored: ${chalk.dim(profile.storedAt)}`);\n}\n\nasync function whoamiClient(\n profile: ClientProfile,\n source: CredentialSourceDescription,\n): Promise<void> {\n const spinner = ora(\"Requesting a token for this client...\").start();\n try {\n await clientAccessToken(profile);\n } catch (error) {\n spinner.fail(chalk.red(describeIdentityError(error)));\n console.log(chalk.dim(`Profile: ${profile.name}`));\n process.exitCode = 1;\n return;\n }\n spinner.succeed(chalk.green(\"Authenticated (client credentials)\"));\n console.log(` Profile: ${chalk.bold(profile.name)}`);\n console.log(` Company: ${chalk.bold(profile.companyName)}`);\n printSource(source);\n console.log(` Client ID: ${chalk.dim(profile.auth.clientId)}`);\n console.log(` Org: ${chalk.dim(profile.auth.org)}`);\n console.log(` Stored: ${chalk.dim(profile.storedAt)}`);\n}\n\n/** The prefix of a company API token, which has no user. */\nconst COMPANY_TOKEN_PREFIX = \"PT-\";\n\n/**\n * Check a token from FLUID_TOKEN (or FLUID_TOKEN_FD), which every other\n * command uses before any saved login, against FLUID_API_BASE.\n *\n * token - The token the environment holds.\n * source - Where that token came from.\n *\n * Returns nothing; sets the exit code when the token is refused.\n */\nasync function whoamiEnvToken(\n token: string,\n source: CredentialSourceDescription,\n): Promise<void> {\n const baseUrl = process.env[\"FLUID_API_BASE\"];\n const spinner = ora(\"Verifying the token from FLUID_TOKEN...\").start();\n const result = await validateToken(token, baseUrl ? { baseUrl } : {});\n if (!result.success) {\n spinner.fail(chalk.red(\"The token in FLUID_TOKEN was refused.\"));\n console.log(chalk.dim(result.error.message));\n process.exitCode = 1;\n return;\n }\n\n spinner.succeed(chalk.green(\"Authenticated (token from FLUID_TOKEN)\"));\n printSource(source);\n console.log(` Company: ${chalk.bold(result.value.name)}`);\n if (token.startsWith(COMPANY_TOKEN_PREFIX)) {\n console.log(\n chalk.yellow(\n \" 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`.\",\n ),\n );\n }\n if (!baseUrl) {\n console.log(\n chalk.yellow(\n \" FLUID_API_BASE is not set. With FLUID_TOKEN and no saved login, the sites commands need it, such as https://api.fluid.app.\",\n ),\n );\n }\n}\n\nexport const whoamiCommand = new Command(\"whoami\")\n .description(\"Show the current authenticated profile\")\n .action(async () => {\n const source = resolveCredentialSource();\n const description = source ? describeCredentialSource(source) : null;\n if (source?.kind === \"token\" && description) {\n await whoamiEnvToken(source.token, description);\n return;\n }\n\n const profile =\n source?.kind === \"profile\" ? source.profile : getActiveProfile();\n\n if (!profile) {\n console.log(\n chalk.yellow(\"Not logged in. Run `fluid login` to authenticate.\"),\n );\n process.exitCode = 1;\n return;\n }\n\n const profileSource: CredentialSourceDescription = description ?? {\n origin: \"active\",\n mode: isIdentityProfile(profile)\n ? \"identity\"\n : isClientProfile(profile)\n ? \"client\"\n : \"legacy\",\n profileName: profile.name,\n };\n\n if (isIdentityProfile(profile)) {\n await whoamiIdentity(profile, profileSource);\n return;\n }\n\n if (isClientProfile(profile)) {\n await whoamiClient(profile, profileSource);\n return;\n }\n\n const spinner = ora(\"Verifying token...\").start();\n // Check the token against FLUID_API_BASE, else the API the profile was\n // made for, as the site commands do, so a staging or local login is not\n // checked against production.\n const result = await validateToken(profile.token ?? \"\", {\n baseUrl: process.env[\"FLUID_API_BASE\"] || profile.baseUrl,\n });\n\n if (!result.success) {\n spinner.fail(chalk.red(\"Token is no longer valid.\"));\n console.log(chalk.dim(`Profile: ${profile.name}`));\n console.log(chalk.dim(\"Run `fluid login` to re-authenticate.\"));\n process.exitCode = 1;\n return;\n }\n\n spinner.succeed(chalk.green(\"Authenticated\"));\n console.log(` Profile: ${chalk.bold(profile.name)}`);\n printSource(profileSource);\n console.log(` Company: ${chalk.bold(result.value.name)}`);\n console.log(` Stored: ${chalk.dim(profile.storedAt)}`);\n });\n","import {\n existsSync,\n mkdirSync,\n readFileSync,\n readdirSync,\n renameSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\nimport { randomBytes } from \"node:crypto\";\n\nimport {\n isStalePendingAdopt,\n parseAdoptMarker,\n type PendingAdoptMarker,\n serializeAdoptMarker,\n} from \"@fluid-app/auth/native\";\n\nimport { readStoredConfig } from \"../../config/config.js\";\nimport { getConfigDir } from \"../../config/paths.js\";\nimport { deleteStoredAdoption, revokeStoredAdoption } from \"./session.js\";\n\nexport const ADOPT_DEADLINE_MS = 15_000;\nexport { ADOPT_CLEANUP_TIMEOUT_MS } from \"./adopt-timeouts.js\";\nexport const ADOPT_RECOVERY_TIMEOUT_MS = 4_000;\nexport const ADOPT_RECOVERY_MIN_MS = 500;\nconst ADOPT_RECOVERY_MAX_ATTEMPTS = 5;\n\nconst PREFIX = \"adopt-pending-\";\nconst SUFFIX = \".json\";\n\nfunction markerFiles(): string[] {\n try {\n return readdirSync(getConfigDir()).filter(\n (name) => name.startsWith(PREFIX) && name.endsWith(SUFFIX),\n );\n } catch {\n return [];\n }\n}\n\nfunction remove(name: string): void {\n try {\n unlinkSync(join(getConfigDir(), name));\n } catch {\n // Already gone.\n }\n}\n\nfunction store(name: string, marker: PendingAdoptMarker): void {\n try {\n const dir = getConfigDir();\n const tmp = join(\n dir,\n `.adopt-pending-${randomBytes(6).toString(\"hex\")}.tmp`,\n );\n writeFileSync(tmp, serializeAdoptMarker(marker), { mode: 0o600 });\n renameSync(tmp, join(dir, name));\n } catch {\n // The old marker stays, so the next start retries.\n }\n}\n\n/** Writes the marker for one attempt, atomically; throws when it cannot. */\nexport function writePendingAdopt(\n storageKey: string,\n identityUrl: string,\n): void {\n const dir = getConfigDir();\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });\n const tmp = join(dir, `.adopt-pending-${randomBytes(6).toString(\"hex\")}.tmp`);\n writeFileSync(\n tmp,\n serializeAdoptMarker({ storageKey, identityUrl, startedAt: Date.now() }),\n { mode: 0o600 },\n );\n renameSync(tmp, join(dir, `${PREFIX}${storageKey}${SUFFIX}`));\n}\n\n/** Removes the marker for `storageKey`; never throws. */\nexport function clearPendingAdopt(storageKey: string): void {\n remove(`${PREFIX}${storageKey}${SUFFIX}`);\n}\n\n/**\n * Settles every stale marker left by an attempt that died: one whose key no\n * profile names has its stored session revoked and deleted, then the marker\n * goes. A marker still inside the grace belongs to a live attempt and stays.\n * Never throws; logs outcomes without any token. With `quiet`, a revoked or\n * empty outcome is not logged; a failure still is.\n */\nexport async function recoverPendingAdopts(\n options: {\n readonly log?: (line: string) => void;\n readonly quiet?: boolean;\n } = {},\n): Promise<void> {\n const log =\n options.log ?? ((line: string) => process.stderr.write(`${line}\\n`));\n const files = markerFiles();\n if (files.length === 0) return;\n const budgetEndsAt = Date.now() + ADOPT_RECOVERY_TIMEOUT_MS;\n try {\n const committed = new Set(\n Object.values(readStoredConfig().profiles).flatMap((profile) =>\n profile.auth?.mode === \"identity\" ? [profile.auth.storageKey] : [],\n ),\n );\n for (const name of files) {\n let marker;\n try {\n marker = parseAdoptMarker(\n readFileSync(join(getConfigDir(), name), \"utf8\"),\n );\n } catch {\n continue;\n }\n if (!marker) {\n remove(name);\n continue;\n }\n if (!isStalePendingAdopt(marker, Date.now())) continue;\n if (committed.has(marker.storageKey) || !marker.identityUrl) {\n remove(name);\n continue;\n }\n const remainingMs = budgetEndsAt - Date.now();\n if (remainingMs < ADOPT_RECOVERY_MIN_MS) break;\n const auth = {\n mode: \"identity\",\n identityUrl: marker.identityUrl,\n storageKey: marker.storageKey,\n } as const;\n let outcome: \"revoked\" | \"none\" | \"unconfirmed\" = \"unconfirmed\";\n try {\n outcome = await revokeStoredAdoption(auth, remainingMs);\n } catch {\n // Counted below.\n }\n if (outcome !== \"unconfirmed\") {\n remove(name);\n if (!options.quiet) log(`adopt recovery: ${outcome}`);\n continue;\n }\n const attempts = (marker.attemptCount ?? 0) + 1;\n if (attempts >= ADOPT_RECOVERY_MAX_ATTEMPTS) {\n const deleted = await deleteStoredAdoption(\n auth,\n Math.max(budgetEndsAt - Date.now(), ADOPT_RECOVERY_MIN_MS),\n ).then(\n () => true,\n () => false,\n );\n if (deleted) {\n remove(name);\n log(\"adopt recovery: gave up; the stored credential was deleted\");\n } else {\n store(name, { ...marker, attemptCount: attempts });\n log(\"adopt recovery: could not delete the stored credential\");\n }\n } else {\n store(name, { ...marker, attemptCount: attempts });\n log(\"adopt recovery: not confirmed, will retry at the next start\");\n }\n }\n } catch {\n log(\"adopt recovery: skipped\");\n }\n}\n","import {\n createSwitchAdoptRequest,\n type SwitchAdoptRequest,\n} from \"@fluid-app/auth/native\";\n\nimport { readConfig, updateConfig } from \"../../config/config.js\";\nimport type { FluidProfile } from \"../../config/types.js\";\nimport { createIdentityProfile } from \"../profiles.js\";\nimport type { SwitchAdoptAnswer } from \"../fluid-api.js\";\nimport { resolveIdentityUrl } from \"./environment.js\";\nimport {\n ADOPT_CLEANUP_TIMEOUT_MS,\n ADOPT_DEADLINE_MS,\n clearPendingAdopt,\n writePendingAdopt,\n} from \"./adopt-pending.js\";\nimport { endUnusedSessions } from \"./profiles.js\";\nimport {\n adoptionStorageAvailable,\n createAdoptionSession,\n type AdoptionSession,\n} from \"./session.js\";\n\nexport interface SwitchAdoption {\n readonly codeChallenge: string;\n /**\n * Redeems the code a switch answered, stores the session and writes the\n * target company's identity profile, all or nothing. Null when it did not land; otherwise\n * any problems ending the sessions the write replaced.\n */\n readonly complete: (\n answer: SwitchAdoptAnswer,\n companyName: string,\n ) => Promise<{ readonly problems: string[] } | null>;\n}\n\nfunction identityUrlFor(apiBase: string): string | null {\n try {\n return resolveIdentityUrl(apiBase);\n } catch {\n return null;\n }\n}\n\n/**\n * Prepares an adopt request for a legacy switch made with `profile`'s token,\n * or null when that profile is not one the CLI would adopt (no token, owned\n * by Mist, no identity service for the API base) or the credential store\n * cannot keep a session.\n */\nexport async function beginSwitchAdoption(\n profile: FluidProfile | null | undefined,\n apiBase: string,\n): Promise<SwitchAdoption | null> {\n if (\n !profile?.token ||\n profile.mistOwned === true ||\n profile.identityClient !== undefined\n ) {\n return null;\n }\n const identityUrl = identityUrlFor(apiBase);\n if (!identityUrl) return null;\n try {\n if (!(await adoptionStorageAvailable())) return null;\n const deadline = new AbortController();\n const held = createAdoptionSession(identityUrl, deadline.signal);\n const request = await createSwitchAdoptRequest(held.session);\n const legacyToken = profile.token;\n return {\n codeChallenge: request.codeChallenge,\n complete: (answer, companyName) =>\n land(\n request,\n held,\n deadline,\n identityUrl,\n legacyToken,\n apiBase,\n answer,\n companyName,\n ),\n };\n } catch {\n return null;\n }\n}\n\nasync function land(\n request: SwitchAdoptRequest,\n held: AdoptionSession,\n deadline: AbortController,\n identityUrl: string,\n legacyToken: string,\n apiBase: string,\n answer: SwitchAdoptAnswer,\n companyName: string,\n): Promise<{ readonly problems: string[] } | null> {\n const storageKey = held.auth.storageKey;\n try {\n writePendingAdopt(storageKey, identityUrl);\n } catch {\n return null;\n }\n const timer = setTimeout(() => {\n deadline.abort();\n }, ADOPT_DEADLINE_MS);\n try {\n const result = await request.redeem({\n code: answer.adoptCode,\n apiBase,\n legacyToken,\n targetCompanyId: answer.companyId,\n fetch: (input, init) =>\n fetch(input, {\n ...init,\n signal: init?.signal\n ? AbortSignal.any([init.signal, deadline.signal])\n : deadline.signal,\n }),\n });\n if (result.outcome !== \"adopted\") {\n clearPendingAdopt(storageKey);\n return null;\n }\n let persistAttempted = false;\n const revoke = async (): Promise<void> => {\n held.beginCleanup(ADOPT_CLEANUP_TIMEOUT_MS);\n const revoked = await result.discard().then(\n () => true,\n () => false,\n );\n if (!revoked) return;\n const clean =\n persistAttempted && !held.persistRefused\n ? await held.unpersist().then(\n () => true,\n () => false,\n )\n : true;\n if (clean) clearPendingAdopt(storageKey);\n };\n try {\n if (deadline.signal.aborted) throw new Error(\"adopt deadline passed\");\n clearTimeout(timer);\n writePendingAdopt(storageKey, identityUrl);\n persistAttempted = true;\n await held.persist();\n const before = readConfig();\n const after = updateConfig((config) => ({\n ...config,\n activeProfile: companyName,\n profiles: {\n ...config.profiles,\n [companyName]: createIdentityProfile({\n name: companyName,\n companyName,\n baseUrl: apiBase,\n auth: held.auth,\n }),\n },\n }));\n clearPendingAdopt(storageKey);\n return { problems: await endUnusedSessions(before, after) };\n } catch {\n await revoke();\n return null;\n }\n } catch {\n if (deadline.signal.aborted) clearPendingAdopt(storageKey);\n return null;\n } finally {\n clearTimeout(timer);\n }\n}\n","/**\n * fluid switch — switch between companies (fetched from API, with local fallback)\n *\n * An identity-mode profile switches by token exchange (Phase 007 FR-3): the\n * session it signed in with stays as it is, and the new company's profile\n * remembers the company to exchange into. Nothing secret is written.\n */\n\nimport { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport prompts from \"prompts\";\nimport ora from \"ora\";\nimport {\n fetchUserCompanies,\n switchCompany,\n FLUID_API_ERROR,\n getFluidApiBase,\n type UserCompany,\n} from \"../auth/fluid-api.js\";\nimport { endUnusedSessions } from \"../auth/identity/profiles.js\";\nimport { beginSwitchAdoption } from \"../auth/identity/switch-adopt.js\";\nimport {\n describeIdentityError,\n identityToken,\n sessionFacts,\n} from \"../auth/identity/session.js\";\nimport { createFluidProfile, createIdentityProfile } from \"../auth/profiles.js\";\nimport { getActiveProfile } from \"../auth/token.js\";\nimport { readConfig, updateConfig } from \"../config/config.js\";\nimport {\n type IdentityProfile,\n isClientProfile,\n isIdentityProfile,\n} from \"../config/types.js\";\n\nasync function localSwitch(profileArg?: string): Promise<void> {\n const config = readConfig();\n const profileNames = Object.keys(config.profiles);\n\n if (profileNames.length === 0) {\n console.log(chalk.yellow(\"No profiles stored. Run `fluid login` first.\"));\n process.exitCode = 1;\n return;\n }\n\n let targetProfile = profileArg;\n\n if (!targetProfile) {\n const profileChoices = profileNames.map((name) => ({\n title: name === config.activeProfile ? `${name} (active)` : name,\n value: name,\n }));\n\n const response = await prompts({\n type: \"autocomplete\",\n name: \"profile\",\n message: \"Select a profile (type to search)\",\n choices: profileChoices,\n suggest: (input, choices) =>\n Promise.resolve(\n input\n ? choices.filter((c) =>\n c.value.toLowerCase().includes(input.toLowerCase()),\n )\n : choices,\n ),\n });\n targetProfile = response[\"profile\"] as string | undefined;\n\n if (!targetProfile) {\n console.log(chalk.dim(\"Cancelled.\"));\n return;\n }\n }\n\n if (!config.profiles[targetProfile]) {\n console.log(chalk.red(`Profile \"${targetProfile}\" not found.`));\n console.log(chalk.dim(`Available: ${profileNames.join(\", \")}`));\n process.exitCode = 1;\n return;\n }\n\n updateConfig((c) => ({ ...c, activeProfile: targetProfile! }));\n console.log(chalk.green(`Switched to profile ${chalk.bold(targetProfile)}.`));\n}\n\nasync function selectCompany(\n companies: UserCompany[],\n activeCompanyName: string | undefined,\n): Promise<UserCompany | undefined> {\n const companyChoices = companies.map((c) => ({\n title:\n c.name === activeCompanyName\n ? `${c.name} ${chalk.dim(\"(active)\")}`\n : c.name,\n value: c.id,\n }));\n\n const response = await prompts({\n type: \"autocomplete\",\n name: \"companyId\",\n message: \"Select a company (type to search)\",\n choices: companyChoices,\n suggest: (input, choices) =>\n Promise.resolve(\n input\n ? choices.filter((c) =>\n c.title.toLowerCase().includes(input.toLowerCase()),\n )\n : choices,\n ),\n });\n\n const companyId = response[\"companyId\"] as number | undefined;\n if (companyId === undefined) return undefined;\n return companies.find((c) => c.id === companyId);\n}\n\nasync function performSwitch(\n token: string,\n company: UserCompany,\n baseUrl?: string,\n): Promise<void> {\n const spinner = ora(`Switching to ${chalk.bold(company.name)}...`).start();\n const adoption = await beginSwitchAdoption(\n getActiveProfile(),\n baseUrl ?? getFluidApiBase(),\n );\n let result = await switchCompany(\n token,\n company.id,\n baseUrl,\n adoption?.codeChallenge,\n );\n\n if (result.success && \"adoptCode\" in result.value) {\n if (result.value.companyId !== company.id) {\n spinner.fail(chalk.red(\"Unexpected response shape from /switch\"));\n process.exitCode = 1;\n return;\n }\n const landed = adoption\n ? await adoption.complete(result.value, company.name)\n : null;\n if (landed) {\n spinner.succeed(\n chalk.green(\n `Switched to ${chalk.bold(company.name)} (profile: ${chalk.bold(company.name)})`,\n ),\n );\n for (const problem of landed.problems) {\n console.log(chalk.yellow(problem));\n }\n return;\n }\n result = await switchCompany(token, company.id, baseUrl);\n }\n\n if (!result.success) {\n if (result.error.code === FLUID_API_ERROR.INVALID_TOKEN.code) {\n spinner.fail(\n chalk.red(\n \"Your session has expired. Please run `fluid login` to re-authenticate.\",\n ),\n );\n } else {\n spinner.fail(chalk.red(result.error.message));\n if (result.error.details) {\n console.log(chalk.dim(result.error.details));\n }\n }\n process.exitCode = 1;\n return;\n }\n\n if (\"adoptCode\" in result.value) {\n spinner.fail(chalk.red(\"Unexpected response shape from /switch\"));\n process.exitCode = 1;\n return;\n }\n\n const { companyName, jwt } = result.value;\n\n updateConfig((config) => ({\n ...config,\n activeProfile: companyName,\n profiles: {\n ...config.profiles,\n [companyName]: createFluidProfile({\n name: companyName,\n token: jwt,\n companyName,\n baseUrl: baseUrl ?? getFluidApiBase(),\n }),\n },\n }));\n\n spinner.succeed(\n chalk.green(\n `Switched to ${chalk.bold(companyName)} (profile: ${chalk.bold(companyName)})`,\n ),\n );\n}\n\nasync function performIdentitySwitch(\n profile: IdentityProfile,\n company: UserCompany,\n baseUrl: string,\n): Promise<void> {\n const spinner = ora(`Switching to ${chalk.bold(company.name)}...`).start();\n if (!company.uuidV7) {\n spinner.fail(\n chalk.red(`${company.name} has no identifier to switch to it by.`),\n );\n process.exitCode = 1;\n return;\n }\n\n let org: string | undefined;\n try {\n // Back to the company the session signed in to needs no exchange.\n const home = (await sessionFacts(profile.auth)).companyId;\n org = company.uuidV7 === home ? undefined : company.uuidV7;\n await identityToken(profile.auth, org ?? null);\n } catch (error) {\n spinner.fail(chalk.red(describeIdentityError(error)));\n process.exitCode = 1;\n return;\n }\n\n const { org: _previous, ...session } = profile.auth;\n const before = readConfig();\n const after = updateConfig((config) => ({\n ...config,\n activeProfile: company.name,\n profiles: {\n ...config.profiles,\n [company.name]: createIdentityProfile({\n name: company.name,\n companyName: company.name,\n baseUrl,\n auth: org ? { ...session, org } : session,\n }),\n },\n }));\n const problems = await endUnusedSessions(before, after);\n\n spinner.succeed(\n chalk.green(\n `Switched to ${chalk.bold(company.name)} (profile: ${chalk.bold(company.name)})`,\n ),\n );\n for (const problem of problems) console.log(chalk.yellow(problem));\n}\n\nexport const switchCommand = new Command(\"switch\")\n .description(\"Switch between companies\")\n .argument(\"[profile]\", \"Company or profile name to switch to\")\n .action(async (profileArg?: string) => {\n const activeProfile = getActiveProfile();\n\n if (!activeProfile) {\n console.log(chalk.yellow(\"Not logged in. Run `fluid login` first.\"));\n process.exitCode = 1;\n return;\n }\n\n if (isClientProfile(activeProfile)) {\n await localSwitch(profileArg);\n return;\n }\n\n const activeCompanyName = activeProfile.companyName;\n const activeBaseUrl = activeProfile.baseUrl ?? getFluidApiBase();\n const identity = isIdentityProfile(activeProfile) ? activeProfile : null;\n\n // Fetch companies from API\n const spinner = ora(\"Fetching companies...\").start();\n let token = activeProfile.token ?? \"\";\n if (identity) {\n try {\n token = (await identityToken(identity.auth)).accessToken;\n } catch (error) {\n spinner.fail(chalk.red(describeIdentityError(error)));\n process.exitCode = 1;\n return;\n }\n }\n const result = await fetchUserCompanies(token, activeBaseUrl);\n\n if (!result.success) {\n if (result.error.code === FLUID_API_ERROR.INVALID_TOKEN.code) {\n spinner.fail(\n chalk.red(\n \"Your session has expired. Please run `fluid login` to re-authenticate.\",\n ),\n );\n process.exitCode = 1;\n return;\n }\n spinner.warn(\n chalk.yellow(\n `Could not fetch companies from API: ${result.error.message}`,\n ),\n );\n console.log(chalk.dim(\"Falling back to locally stored profiles.\"));\n await localSwitch(profileArg);\n return;\n }\n\n const companies = result.value;\n spinner.succeed(\n `Found ${companies.length} company${companies.length === 1 ? \"\" : \"ies\"}`,\n );\n\n if (companies.length === 0) {\n console.log(chalk.yellow(\"No companies found for this account.\"));\n process.exitCode = 1;\n return;\n }\n\n // If a profile argument was passed, match against API companies first\n if (profileArg) {\n const match = companies.find(\n (c) => c.name.toLowerCase() === profileArg.toLowerCase(),\n );\n\n if (match) {\n await (identity\n ? performIdentitySwitch(identity, match, activeBaseUrl)\n : performSwitch(token, match, activeBaseUrl));\n return;\n }\n\n // Fall back to local profile matching\n const config = readConfig();\n if (config.profiles[profileArg]) {\n updateConfig((c) => ({ ...c, activeProfile: profileArg! }));\n console.log(\n chalk.green(`Switched to profile ${chalk.bold(profileArg)}.`),\n );\n return;\n }\n\n console.log(chalk.red(`Company or profile \"${profileArg}\" not found.`));\n process.exitCode = 1;\n return;\n }\n\n // Interactive selection\n const selected = await selectCompany(companies, activeCompanyName);\n if (!selected) {\n console.log(chalk.dim(\"Cancelled.\"));\n return;\n }\n\n await (identity\n ? performIdentitySwitch(identity, selected, activeBaseUrl)\n : performSwitch(token, selected, activeBaseUrl));\n });\n","/**\n * Format one-line diagnostics naming a CLI plugin build and where it was\n * resolved from. The resolved path is the load-bearing detail: a workspace\n * build and a published copy share the same name and version, so the path is\n * the only thing that distinguishes them. See CURRENT-3218.\n */\n\nimport { fileURLToPath } from \"node:url\";\n\nexport interface PluginLoadInfo {\n readonly name: string;\n readonly version: string;\n /**\n * Where the plugin was resolved from — an absolute `file://` URL (workspace\n * or published install, resolved upstream) or, only when resolution failed,\n * a bare package name.\n */\n readonly importSpecifier: string;\n /**\n * Whether installation-bundled plugins were preferred over project-local\n * ones (`FLUID_CLI_PREFER_INSTALLATION_PLUGINS=1`, set by Mist).\n */\n readonly preferInstallation: boolean;\n}\n\nexport interface PluginLoadFailureInfo {\n readonly name: string;\n readonly importSpecifier: string;\n readonly preferInstallation: boolean;\n readonly message: string;\n}\n\nexport function modeLabel(preferInstallation: boolean): string {\n return preferInstallation ? \"installation-preferred\" : \"project-first\";\n}\n\n/**\n * Render a specifier for display: `file://` URLs become absolute filesystem\n * paths; anything else is shown verbatim. Never throws — a malformed `file://`\n * specifier falls back to its raw form so a diagnostic can never turn a\n * successful load into a reported failure.\n */\nexport function displaySource(importSpecifier: string): string {\n if (!importSpecifier.startsWith(\"file://\")) return importSpecifier;\n try {\n return fileURLToPath(importSpecifier);\n } catch {\n return importSpecifier;\n }\n}\n\nexport function formatPluginLoadLine(info: PluginLoadInfo): string {\n return `Loaded plugin ${info.name}@${info.version} from ${displaySource(\n info.importSpecifier,\n )} [${modeLabel(info.preferInstallation)}]`;\n}\n\nexport function formatPluginLoadFailure(info: PluginLoadFailureInfo): string {\n return `Failed to load plugin ${info.name} from ${displaySource(\n info.importSpecifier,\n )} [${modeLabel(info.preferInstallation)}]: ${info.message}`;\n}\n","/**\n * Resolve a plugin import specifier to a concrete path for diagnostics.\n *\n * The node_modules discovery strategy falls back to a bare package name when it\n * cannot realpath a workspace symlink — precisely the published-install case\n * where the path is the only thing that would reveal a stale plugin winning.\n * Resolving the bare specifier recovers that path. See CURRENT-3218.\n */\n\nexport type Resolver = (specifier: string) => string;\n\nconst defaultResolver: Resolver = (specifier) => import.meta.resolve(specifier);\n\n/**\n * Return a `file://` URL for `importSpecifier`. `file://` specifiers (already\n * resolved by discovery) pass through untouched; bare specifiers are resolved\n * via `resolve`. If resolution throws, the bare specifier is returned so a\n * diagnostic degrades gracefully rather than failing the load.\n */\nexport function resolveLoadPath(\n importSpecifier: string,\n resolve: Resolver = defaultResolver,\n): string {\n if (importSpecifier.startsWith(\"file://\")) return importSpecifier;\n try {\n return resolve(importSpecifier);\n } catch {\n return importSpecifier;\n }\n}\n","/**\n * Decide whether to print the per-plugin \"Loaded plugin …\" diagnostics.\n *\n * A monorepo checkout resolves ~a dozen plugin packages, so emitting a line\n * for each on every command (including `--help` and tab-completion, and into\n * Mist's captured stderr dialog) is noise. The success diagnostics are gated\n * behind an explicit opt-in; load *failures* are always surfaced by the loader\n * regardless of this flag. See CURRENT-3218.\n */\n\nfunction isTruthyFlag(value: string | undefined): boolean {\n return value === \"1\" || value === \"true\";\n}\n\nexport function shouldLogPluginLoads(\n argv: readonly string[] = process.argv,\n env: NodeJS.ProcessEnv = process.env,\n): boolean {\n if (argv.includes(\"--verbose\")) return true;\n return isTruthyFlag(env[\"FLUID_CLI_DEBUG\"] ?? env[\"FLUID_CLI_VERBOSE\"]);\n}\n","/**\n * Plugin loader — orchestrates discovery and registration\n */\n\nimport type { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport { getConfigDir } from \"../config/paths.js\";\nimport { getAuthToken } from \"../auth/token.js\";\nimport { readConfig } from \"../config/config.js\";\nimport { INPUTS_MODE_ENV } from \"../inputs/hook.js\";\nimport { createInputsReader } from \"../inputs/reader.js\";\nimport type { FluidPlugin, PluginContext } from \"./types.js\";\nimport { discoverPlugins, importPlugin } from \"./discovery.js\";\nimport { prefersInstallationPlugins } from \"./prefer-installation.js\";\nimport {\n formatPluginLoadLine,\n formatPluginLoadFailure,\n} from \"./format-load-line.js\";\nimport { resolveLoadPath } from \"./resolve-load-path.js\";\nimport { shouldLogPluginLoads } from \"./should-log-plugin-loads.js\";\n\nfunction isFluidPlugin(value: unknown): value is FluidPlugin {\n if (typeof value !== \"object\" || value === null) return false;\n const obj = value as Record<string, unknown>;\n return (\n typeof obj[\"name\"] === \"string\" &&\n typeof obj[\"version\"] === \"string\" &&\n typeof obj[\"register\"] === \"function\"\n );\n}\n\n/** A plugin this run registered, and the file it was imported from. */\nexport interface LoadedPlugin {\n /** The package name, such as `@fluid-app/fluid-cli-member-site`. */\n readonly name: string;\n /** A `file://` URL, or the bare specifier when it couldn't be resolved. */\n readonly source: string;\n}\n\nconst loaded: LoadedPlugin[] = [];\n\n/** The plugins the last loadPlugins registered, in the order it did. */\nexport function loadedPlugins(): readonly LoadedPlugin[] {\n return loaded;\n}\n\n/**\n * Discover, import, and register all installed plugins\n */\nexport async function loadPlugins(\n program: Command,\n basePath: string,\n): Promise<void> {\n loaded.length = 0;\n const preferInstallation = prefersInstallationPlugins();\n const discovered = discoverPlugins(basePath, undefined, {\n preferInstallation,\n installationOnly:\n process.env[INPUTS_MODE_ENV] === \"resolve\" ||\n Boolean(process.env[\"FLUID_TOKEN_FD\"]),\n });\n const { enabledPlugins } = readConfig();\n\n // If enabledPlugins is set, only load explicitly allowed plugins.\n // This acts as an allow-list to prevent accidental supply-chain execution.\n const allowedSet = enabledPlugins !== null ? new Set(enabledPlugins) : null;\n const plugins = allowedSet\n ? discovered.filter((p) => allowedSet.has(p.name))\n : discovered;\n\n if (plugins.length === 0) return;\n\n const ctx: PluginContext = {\n program,\n getAuthToken,\n configDir: getConfigDir(),\n inputs: createInputsReader(),\n };\n\n // Success diagnostics are opt-in (a checkout resolves ~a dozen plugins);\n // load failures below are always surfaced. See CURRENT-3218.\n const verbose = shouldLogPluginLoads();\n\n for (const { name, importSpecifier } of plugins) {\n // Resolve to a concrete path so a published install is distinguishable\n // from a workspace build at a glance.\n const source = resolveLoadPath(importSpecifier);\n try {\n const exported = await importPlugin(importSpecifier);\n\n if (!isFluidPlugin(exported)) {\n console.warn(\n chalk.yellow(`Warning: ${name} does not export a valid FluidPlugin`),\n );\n continue;\n }\n\n await exported.register(ctx);\n loaded.push({ name, source });\n\n if (verbose) {\n console.error(\n chalk.dim(\n formatPluginLoadLine({\n name: exported.name,\n version: exported.version,\n importSpecifier: source,\n preferInstallation,\n }),\n ),\n );\n }\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n // Always name what failed to load and from where — this is exactly the\n // invisible-artifact failure the diagnostic exists to catch.\n console.warn(\n chalk.yellow(\n `Warning: ${formatPluginLoadFailure({\n name,\n importSpecifier: source,\n preferInstallation,\n message,\n })}`,\n ),\n );\n }\n }\n}\n","/**\n * `fluid version`: the CLI's and each loaded plugin's version, npm's latest,\n * and the command that updates each. A person or a coding agent runs it to\n * learn whether a missing command, option or config key needs an update.\n */\n\nimport { realpathSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { Command } from \"commander\";\nimport { loadedPlugins, type LoadedPlugin } from \"../plugins/loader.js\";\nimport {\n PACKAGE_NAME,\n fetchLatestVersion,\n installRoot,\n isAppResources,\n isMistBundled,\n isNewer,\n loadedPackage,\n packageInstallKind,\n updateCommand,\n} from \"../update/notifier.js\";\n\nconst require = createRequire(import.meta.url);\nconst { version } = require(\"../../package.json\") as { version: string };\n\n/**\n * How to update a package: a command and, for a project's own copy, the\n * folder to run it in; or the app a bundled copy comes with.\n */\nexport type PackageUpdate =\n | { readonly command: string; readonly directory: string | null }\n | { readonly app: \"Mist\" };\n\nexport interface PackageVersion {\n readonly name: string;\n /** Null when its package.json can't be read, as for a workspace build. */\n readonly installed: string | null;\n /** npm's latest version; null when npm couldn't be reached. */\n readonly latest: string | null;\n /**\n * How to update it, when npm has a newer version and this copy can be\n * updated; otherwise null.\n */\n readonly update: PackageUpdate | null;\n}\n\nexport interface VersionReportOptions {\n /** Real path of a file in the running CLI's package. */\n readonly entryPath: string;\n readonly currentVersion: string;\n readonly plugins: readonly LoadedPlugin[];\n readonly fetchImpl?: typeof fetch;\n}\n\n/**\n * How to update `name`, installed under `root` (null for a workspace\n * build). A copy Mist ships updates with Mist. No command updates a copy\n * inside another app's resources, or a plugin in an npx run's cache, as an\n * npx run fetches only the CLI afresh.\n */\nfunction updateFor(name: string, root: string | null): PackageUpdate | null {\n if (root === null) return null;\n if (isMistBundled(join(root, \"node_modules\", name))) return { app: \"Mist\" };\n if (isAppResources(root)) return null;\n const install = packageInstallKind(root, name);\n if (install.kind === \"npx\" && name !== PACKAGE_NAME) return null;\n return {\n command: updateCommand(install, name),\n directory: install.kind === \"local\" ? install.projectDir : null,\n };\n}\n\n/** The CLI and each plugin, with npm's latest versions asked for at once. */\nexport async function versionReport({\n entryPath,\n currentVersion,\n plugins,\n fetchImpl = fetch,\n}: VersionReportOptions): Promise<PackageVersion[]> {\n const packages = [\n {\n name: PACKAGE_NAME,\n installed: currentVersion,\n root: installRoot(entryPath),\n },\n ...plugins.map(({ name, source }) => {\n const loaded = loadedPackage(source, name);\n return {\n name,\n installed: loaded?.version ?? null,\n root: loaded?.root ?? null,\n };\n }),\n ];\n return Promise.all(\n packages.map(async ({ name, installed, root }) => {\n const latest = await fetchLatestVersion(fetchImpl, name);\n const behind =\n latest !== null && installed !== null && isNewer(installed, latest);\n // Only a package that's behind needs its install looked at.\n const update = behind ? updateFor(name, root) : null;\n return { name, installed, latest, update };\n }),\n );\n}\n\n/**\n * The text report's update. It never prints a project's folder, which a\n * shell could read as code if the line were pasted into one; `--json` gives\n * the folder as a field of its own.\n */\nfunction updateText(update: PackageUpdate): string {\n if (\"app\" in update) return `update ${update.app}, which brings its own copy`;\n return update.directory === null\n ? `run ${update.command}`\n : `run ${update.command} in that project; fluid version --json shows its folder`;\n}\n\nfunction statusText({ installed, latest, update }: PackageVersion): string {\n if (latest === null) {\n return \"latest unknown (not on npm, or npm couldn't be reached)\";\n }\n if (installed === null) return `latest ${latest}`;\n if (installed === latest || isNewer(latest, installed)) return \"up to date\";\n // A version that doesn't compare, such as a prerelease, isn't called up to\n // date, and gets no command.\n if (!isNewer(installed, latest)) return `latest ${latest}`;\n return `latest ${latest}: ${update ? updateText(update) : \"no command updates this copy\"}`;\n}\n\nexport function formatVersionReport(\n packages: readonly PackageVersion[],\n): string {\n const nameWidth = Math.max(...packages.map(({ name }) => name.length));\n const versionWidth = Math.max(\n ...packages.map(({ installed }) => (installed ?? \"?\").length),\n );\n return packages\n .map(\n (entry) =>\n `${entry.name.padEnd(nameWidth)} ${(entry.installed ?? \"?\").padEnd(versionWidth)} ${statusText(entry)}`,\n )\n .join(\"\\n\");\n}\n\nexport const versionCommand = new Command(\"version\")\n .description(\n \"Show the CLI's and plugins' versions, npm's latest, and how to update\",\n )\n .option(\"--json\", \"Print the versions as JSON\", false)\n .action(async (opts: { json: boolean }) => {\n const packages = await versionReport({\n entryPath: realpathSync(fileURLToPath(import.meta.url)),\n currentVersion: version,\n plugins: loadedPlugins(),\n });\n process.stdout.write(\n opts.json\n ? JSON.stringify({ packages }, null, 2) + \"\\n\"\n : formatVersionReport(packages) + \"\\n\",\n );\n });\n","import {\n existsSync,\n mkdirSync,\n readFileSync,\n renameSync,\n writeFileSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\nimport { createHash, randomBytes } from \"node:crypto\";\n\nimport { tradeLegacyToken } from \"@fluid-app/auth/native\";\n\nimport { getFluidApiBase } from \"../fluid-api.js\";\nimport { updateConfig } from \"../../config/config.js\";\nimport { configLockTimings, withConfigLock } from \"../../config/lock.js\";\nimport { getConfigDir } from \"../../config/paths.js\";\nimport type { FluidProfile, IdentityProfile } from \"../../config/types.js\";\nimport { resolveIdentityUrl } from \"./environment.js\";\nimport { KeyringRefusedError } from \"./keyring-child.js\";\nimport {\n ADOPT_CLEANUP_TIMEOUT_MS,\n clearPendingAdopt,\n writePendingAdopt,\n} from \"./adopt-pending.js\";\nimport { createAdoptionSession } from \"./session.js\";\n\nexport const ADOPT_BACKOFF_MS = 24 * 60 * 60 * 1000;\nexport const ADOPT_UNAVAILABLE_BACKOFF_MS = 15 * 60 * 1000;\nconst ADOPT_TIMEOUT_MS = 5_000;\nexport const ADOPT_DEADLINE_MS = 6_000;\nconst MIN_LOCK_WAIT_MS = 250;\nconst BACKOFF_FILE = \"adopt-backoff.json\";\n\ntype Backoff = Record<string, number>;\n\nfunction backoffPath(): string {\n return join(getConfigDir(), BACKOFF_FILE);\n}\n\nfunction backoffKey(profile: FluidProfile): string {\n const digest = createHash(\"sha256\")\n .update(profile.token ?? \"\")\n .digest(\"hex\")\n .slice(0, 12);\n return `${profile.name}\\u0000${profile.companyName}\\u0000${digest}`;\n}\n\nfunction readBackoff(): Backoff {\n try {\n const parsed: unknown = JSON.parse(readFileSync(backoffPath(), \"utf8\"));\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Backoff)\n : {};\n } catch {\n return {};\n }\n}\n\nfunction recordBackoff(profile: FluidProfile, ms: number | null): void {\n try {\n const now = Date.now();\n const next: Backoff = {};\n for (const [key, until] of Object.entries(readBackoff())) {\n if (typeof until === \"number\" && until > now) next[key] = until;\n }\n if (ms === null) delete next[backoffKey(profile)];\n else next[backoffKey(profile)] = now + ms;\n const dir = getConfigDir();\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });\n const tmp = join(\n dir,\n `.adopt-backoff-${randomBytes(6).toString(\"hex\")}.tmp`,\n );\n writeFileSync(tmp, JSON.stringify(next), { mode: 0o600 });\n renameSync(tmp, backoffPath());\n } catch {\n // The back-off is an optimisation; a command never fails on it.\n }\n}\n\nfunction inBackoff(profile: FluidProfile): boolean {\n const until = readBackoff()[backoffKey(profile)];\n return typeof until === \"number\" && until > Date.now();\n}\n\nfunction convert(\n profile: FluidProfile,\n auth: IdentityProfile[\"auth\"],\n lockTimeoutMs: number,\n): void {\n withConfigLock(() => {\n updateConfig((config) => {\n const current = config.profiles[profile.name];\n if (!current || current.token !== profile.token) {\n throw new Error(\"The profile changed while it was being adopted.\");\n }\n const { token: _token, gitSyncActor: _actor, ...rest } = current;\n return {\n ...config,\n profiles: { ...config.profiles, [profile.name]: { ...rest, auth } },\n };\n });\n }, lockTimeoutMs);\n}\n\nfunction ownedByMist(profile: FluidProfile): boolean {\n return profile.mistOwned === true || profile.identityClient !== undefined;\n}\n\nfunction withSignal(signal: AbortSignal): typeof fetch {\n return (input, init) =>\n fetch(input, {\n ...init,\n signal: init?.signal ? AbortSignal.any([init.signal, signal]) : signal,\n });\n}\n\n/**\n * Trades a stored legacy profile's token for an identity session and, once\n * the session is stored and verified, rewrites the profile to identity mode\n * and drops its plaintext token. Every other outcome keeps the profile as it\n * is, and the whole attempt gives up after {@link ADOPT_DEADLINE_MS}: a trade\n * that finishes later is ignored and never persisted or converted. A back-off is on file before the trade\n * starts. Profiles Mist owns are never traded. Never throws; resolves with\n * the converted profile, or null.\n */\nexport async function adoptLegacyProfile(\n profile: FluidProfile,\n): Promise<IdentityProfile | null> {\n if (!profile.token || ownedByMist(profile) || inBackoff(profile)) {\n return null;\n }\n recordBackoff(profile, ADOPT_UNAVAILABLE_BACKOFF_MS);\n const abort = new AbortController();\n const deadlineAt = Date.now() + ADOPT_DEADLINE_MS;\n let expired = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<null>((resolve) => {\n timer = setTimeout(() => {\n expired = true;\n abort.abort();\n resolve(null);\n }, ADOPT_DEADLINE_MS);\n });\n const attempt = trade(\n profile as FluidProfile & { readonly token: string },\n abort.signal,\n () => expired,\n () => deadlineAt - Date.now(),\n ).catch(() => null);\n try {\n return await Promise.race([attempt, deadline]);\n } finally {\n clearTimeout(timer);\n }\n}\n\nasync function trade(\n profile: FluidProfile & { readonly token: string },\n signal: AbortSignal,\n expired: () => boolean,\n remainingMs: () => number,\n): Promise<IdentityProfile | null> {\n const apiBase = profile.baseUrl ?? getFluidApiBase();\n const identityUrl = resolveIdentityUrl(apiBase);\n if (!identityUrl) {\n recordBackoff(profile, null);\n return null;\n }\n const held = createAdoptionSession(identityUrl, signal);\n const storageKey = held.auth.storageKey;\n const result = await tradeLegacyToken({\n legacyToken: profile.token,\n apiBase,\n session: held.session,\n requestTimeoutMs: ADOPT_TIMEOUT_MS,\n fetch: withSignal(signal),\n beforeRedeem: () => writePendingAdopt(storageKey, identityUrl),\n beforeDiscard: () => held.beginCleanup(ADOPT_CLEANUP_TIMEOUT_MS),\n });\n if (result.outcome !== \"adopted\") {\n clearPendingAdopt(storageKey);\n if (result.outcome === \"not_targeted\" || result.outcome === \"refused\") {\n recordBackoff(profile, ADOPT_BACKOFF_MS);\n }\n return null;\n }\n let persistAttempted = false;\n const cleanup = async (): Promise<void> => {\n held.beginCleanup(ADOPT_CLEANUP_TIMEOUT_MS);\n const revoked = await result.discard().then(\n () => true,\n () => false,\n );\n if (!revoked) return;\n const clean = persistAttempted && !held.persistRefused\n ? await held.unpersist().then(\n () => true,\n () => false,\n )\n : true;\n if (clean) clearPendingAdopt(storageKey);\n };\n if (expired()) {\n await cleanup();\n return null;\n }\n try {\n persistAttempted = true;\n await held.persist();\n } catch (error) {\n if (error instanceof KeyringRefusedError) {\n recordBackoff(profile, ADOPT_BACKOFF_MS);\n }\n await cleanup();\n return null;\n }\n const lockWaitMs = Math.min(\n configLockTimings.timeoutMs,\n remainingMs() - MIN_LOCK_WAIT_MS,\n );\n try {\n if (lockWaitMs <= 0 || expired()) {\n throw new Error(\"No time left to rewrite the profile.\");\n }\n convert(profile, held.auth, lockWaitMs);\n } catch {\n await cleanup();\n return null;\n }\n clearPendingAdopt(storageKey);\n recordBackoff(profile, null);\n const { token: _token, gitSyncActor: _actor, ...rest } = profile;\n return { ...rest, auth: held.auth };\n}\n","/**\n * Restores an identity-mode profile's session before a command runs, so the\n * synchronous `getAuthToken()` that plugins call finds a current access\n * token in memory. Literal tokens are left alone, and so is a legacy profile\n * unless an identity profile on the same API base exists: only then is its\n * token checked with the API, and a rejected one is replaced for the process\n * by the one identity profile whose authenticated shop matches the legacy\n * profile's; none or several matching leaves the token alone.\n */\n\nimport chalk from \"chalk\";\n\nimport {\n type FluidProfile,\n type IdentityProfile,\n isClientProfile,\n isIdentityProfile,\n} from \"../../config/types.js\";\nimport { readConfig } from \"../../config/config.js\";\nimport { fetchCompanyShops, validateToken } from \"../fluid-api.js\";\nimport {\n adoptIdentityProfile,\n findIdentityFallbackCandidates,\n findIdentityFallbackProfile,\n resolveCredentialSource,\n} from \"../token.js\";\nimport { adoptLegacyProfile } from \"./adopt-legacy.js\";\nimport { recoverPendingAdopts } from \"./adopt-pending.js\";\nimport { primeClientProfile } from \"./client.js\";\nimport {\n describeIdentityError,\n primeIdentityProfile,\n profileAccessToken,\n} from \"./session.js\";\n\nexport interface CommandCredentialOptions {\n readonly token?: unknown;\n readonly profile?: unknown;\n readonly json?: unknown;\n readonly format?: unknown;\n}\n\n/**\n * Primes the credential a command with these options would use. A session\n * that cannot be restored is reported on stderr, and the command runs on as\n * it would with no stored credential.\n */\nexport async function primeCommandCredential(\n options: CommandCredentialOptions,\n): Promise<void> {\n if (typeof options.token === \"string\" && options.token) return;\n const profileName =\n typeof options.profile === \"string\" && options.profile\n ? options.profile\n : undefined;\n await recoverPendingAdopts({\n quiet: options.json === true || options.format === \"json\",\n });\n const source = resolveCredentialSource(profileName);\n if (source?.kind !== \"profile\") return;\n let { profile } = source;\n if (\n profile.token &&\n !isIdentityProfile(profile) &&\n !isClientProfile(profile) &&\n !findIdentityFallbackProfile(profile)\n ) {\n const adopted = await adoptLegacyProfile(profile);\n const stored = adopted ?? readConfig().profiles[profile.name];\n if (isIdentityProfile(stored)) profile = stored;\n }\n if (\n (source.origin === \"fluidrc\" || source.origin === \"active\") &&\n !isIdentityProfile(profile) &&\n !isClientProfile(profile)\n ) {\n await adoptFallbackForDeadToken(profile);\n return;\n }\n try {\n if (isIdentityProfile(profile)) await primeIdentityProfile(profile);\n else if (isClientProfile(profile)) await primeClientProfile(profile);\n } catch (error) {\n process.stderr.write(`${chalk.yellow(describeIdentityError(error))}\\n`);\n }\n}\n\nconst normalizeShop = (shop: string): string =>\n shop\n .toLowerCase()\n .replace(/^https?:\\/\\//, \"\")\n .replace(/\\/.*$/, \"\")\n .replace(/\\.fluid\\.app$/, \"\");\n\nasync function authenticatedShopMatches(\n identity: IdentityProfile,\n wanted: string,\n): Promise<boolean> {\n try {\n await primeIdentityProfile(identity);\n const shops = await fetchCompanyShops(await profileAccessToken(identity), {\n baseUrl: identity.baseUrl,\n });\n return shops.some((shop) => normalizeShop(shop) === wanted);\n } catch {\n return false;\n }\n}\n\nasync function adoptFallbackForDeadToken(profile: FluidProfile): Promise<void> {\n if (!profile.token) return;\n const groups = findIdentityFallbackCandidates(profile);\n if (groups.length === 0) return;\n const checked = await validateToken(\n profile.token,\n profile.baseUrl ? { baseUrl: profile.baseUrl } : {},\n );\n if (checked.success || checked.error.code !== \"INVALID_TOKEN\") return;\n if (!profile.fluidShop) return;\n const wanted = normalizeShop(profile.fluidShop);\n let identity: IdentityProfile | undefined;\n for (const group of groups) {\n const matches: IdentityProfile[] = [];\n for (const candidate of group) {\n if (await authenticatedShopMatches(candidate, wanted)) {\n matches.push(candidate);\n }\n }\n if (matches.length > 1) return;\n if (matches.length === 1) {\n identity = matches[0];\n break;\n }\n }\n if (!identity) return;\n adoptIdentityProfile(identity, profile.name);\n process.stderr.write(\n `${chalk.yellow(\n `The token from profile \"${profile.name}\" was rejected (401); using identity profile \"${identity.name}\" instead.`,\n )}\\n`,\n );\n}\n","#!/usr/bin/env node\n\nimport { createRequire } from \"node:module\";\nimport { realpathSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { Command } from \"commander\";\nimport { commandsCommand } from \"../commands/commands.js\";\nimport { completeCommand, completionCommand } from \"../commands/completion.js\";\nimport { loginCommand } from \"../commands/login.js\";\nimport { signupCommand } from \"../commands/signup.js\";\nimport { logoutCommand } from \"../commands/logout.js\";\nimport { profilesCommand } from \"../commands/profiles.js\";\nimport { whoamiCommand } from \"../commands/whoami.js\";\nimport { switchCommand } from \"../commands/switch.js\";\nimport { versionCommand } from \"../commands/version.js\";\nimport {\n exitOnInputsError,\n inputsModeActive,\n registerInputsHook,\n} from \"../inputs/hook.js\";\nimport { primeCommandCredential } from \"../auth/identity/prime.js\";\nimport { readFdToken } from \"../auth/token.js\";\nimport { loadedPlugins, loadPlugins } from \"../plugins/loader.js\";\nimport { missingPluginHint } from \"../plugins/missing-plugin.js\";\nimport { getConfigDir } from \"../config/paths.js\";\nimport {\n REFRESH_ARG,\n refreshUpdateCache,\n startUpdateCheck,\n type NoticeAudience,\n} from \"../update/notifier.js\";\n\nconst require = createRequire(import.meta.url);\nconst { version } = require(\"../../package.json\") as { version: string };\n\n// The detached update check re-runs this entry point; it only refreshes the\n// cache, without loading plugins or parsing commands.\nif (process.argv[2] === REFRESH_ARG) {\n await refreshUpdateCache(getConfigDir());\n process.exit(0);\n}\n\n// The bearer is read before any plugin is discovered, and with one present\n// only installation plugins load, so no project code runs in this process.\ntry {\n readFdToken();\n} catch (error) {\n console.error(error instanceof Error ? error.message : String(error));\n process.exit(1);\n}\n\nconst packageRoot = process.cwd();\n\nconst program = new Command();\n\nprogram.name(\"fluid\").description(\"Fluid Commerce CLI\").version(version);\n\n// Built-in auth commands, and the signup that comes before them\nprogram.addCommand(signupCommand);\nprogram.addCommand(loginCommand);\nprogram.addCommand(logoutCommand);\nprogram.addCommand(whoamiCommand);\nprogram.addCommand(profilesCommand);\nprogram.addCommand(switchCommand);\n\n// Discovery: the command catalog, versions and shell completion\nprogram.addCommand(commandsCommand);\nprogram.addCommand(versionCommand);\nprogram.addCommand(completionCommand);\nprogram.addCommand(completeCommand, { hidden: true });\n\n// Commands that resolve their own credential, or need none.\nconst selfAuthenticating = new Set(\n [\n signupCommand,\n loginCommand,\n logoutCommand,\n whoamiCommand,\n profilesCommand,\n switchCommand,\n commandsCommand,\n versionCommand,\n completionCommand,\n completeCommand,\n ].map((command) => command.name()),\n);\n\nregisterInputsHook(program);\n\n// Commands that keep the update notice from everyone: completion, and\n// `fluid version`, which reports updates itself.\nconst quietNoticeCommands = new Set<Command>([completeCommand, versionCommand]);\n\n// What the command that runs keeps the update notice from: everyone, for the\n// commands above; an agent, for JSON (`--json`, or a domain command's\n// `--format`, json by default), which it may merge stderr into.\nlet quietFor: NoticeAudience[] = [];\n\n// An identity-mode profile's access token lives only in memory, so restore\n// its session before any other command runs; plugins read the token\n// synchronously through getAuthToken().\nprogram.hook(\"preAction\", async (_program, actionCommand) => {\n const opts = actionCommand.optsWithGlobals();\n if (quietNoticeCommands.has(actionCommand)) quietFor = [\"person\", \"agent\"];\n else if (opts[\"json\"] === true || opts[\"format\"] === \"json\") {\n quietFor = [\"agent\"];\n } else quietFor = [];\n let topLevel: Command = actionCommand;\n while (topLevel.parent && topLevel.parent !== program) {\n topLevel = topLevel.parent;\n }\n if (selfAuthenticating.has(topLevel.name())) return;\n await primeCommandCredential(opts);\n});\n\n// Real path of this entry point: how the CLI was installed.\nconst entryPath = realpathSync(fileURLToPath(import.meta.url));\n\nif (!inputsModeActive(process.env)) {\n startUpdateCheck({\n currentVersion: version,\n configDir: getConfigDir(),\n env: process.env,\n stdoutIsTTY: Boolean(process.stdout.isTTY),\n stderrIsTTY: Boolean(process.stderr.isTTY),\n entryPath,\n versions: process.versions,\n loadedPlugins,\n quiet: (audience) => quietFor.includes(audience),\n });\n}\n\n// Discover and load all plugins (auto-discovered from node_modules and workspace)\nawait loadPlugins(program, packageRoot);\n\nconst missingPlugin = missingPluginHint(program, process.argv.slice(2), {\n entryPath,\n});\nif (missingPlugin) program.error(missingPlugin, { exitCode: 1 });\n\ntry {\n await program.parseAsync(process.argv, { from: \"node\" });\n} catch (error) {\n exitOnInputsError(error);\n throw error;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAa,eAAe;;;;;;AAM5B,MAAa,oBAAoB;;AAGjC,MAAa,cAAc;AAC3B,MAAM,mBAAmB;AACzB,MAAM,aAAa;;;;;;AAMnB,MAAM,qBAAqB;;;;;;AA0B3B,MAAM,YAAY;CAChB;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;AAGD,SAAS,WAAW,KAA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B;AAC5C,KAAI,oBAAoB,IAAI,cAAc,CAAE,YAAW,CAAC,UAAU,QAAQ;UACjE,KAAK,YAAY,QAAQ,KAAK,cAAc,OACnD,YAAW,CAAC,QAAQ;KACf,YAAW,EAAE;CACpB,IAAI,WAAoB;AACxB,QAAO,SAAS,UAAU,SAAS,WAAW,QAC5C,YAAW,SAAS;AAEtB,KAAI,mBAAmB,IAAI,SAAS,MAAM,CAAC,CAAE;AAC7C,OAAM,uBAAuB,KAAK;EAClC;AAGF,MAAM,YAAY,aAAa,cAAc,OAAO,KAAK,IAAI,CAAC;AAE9D,IAAI,CAAC,iBAAiB,QAAQ,IAAI,CAChC,kBAAiB;CACf,gBAAgB;CAChB,WAAW,cAAc;CACzB,KAAK,QAAQ;CACb,aAAa,QAAQ,QAAQ,OAAO,MAAM;CAC1C,aAAa,QAAQ,QAAQ,OAAO,MAAM;CAC1C;CACA,UAAU,QAAQ;CAClB;CACA,QAAQ,aAAa,SAAS,SAAS,SAAS;CACjD,CAAC;AAIJ,MAAM,YAAY,SAAS,YAAY;AAEvC,MAAM,gBAAgB,kBAAkB,SAAS,QAAQ,KAAK,MAAM,EAAE,EAAE,EACtE,WACD,CAAC;AACF,IAAI,cAAe,SAAQ,MAAM,eAAe,EAAE,UAAU,GAAG,CAAC;AAEhE,IAAI;AACF,OAAM,QAAQ,WAAW,QAAQ,MAAM,EAAE,MAAM,QAAQ,CAAC;SACjD,OAAO;AACd,mBAAkB,MAAM;AACxB,OAAM"}
|
|
1
|
+
{"version":3,"file":"fluid.mjs","names":["SITES_PLUGIN","version","readAll","ADOPT_DEADLINE_MS","ADOPT_DEADLINE_MS","version"],"sources":["../../src/update/notifier.ts","../../src/plugins/discovery.ts","../../src/plugins/prefer-installation.ts","../../src/plugins/missing-plugin.ts","../../src/commands/commands.ts","../../src/completion/complete.ts","../../src/commands/completion.ts","../../../../platform/auth/src/native/trade-legacy-token.ts","../../../../platform/auth/src/native/adopt-marker.ts","../../src/auth/identity/sign-in-path.ts","../../src/auth/pending-login.ts","../../src/auth/profiles.ts","../../src/utils/shell.ts","../../src/commands/login-identity.ts","../../src/commands/login.ts","../../src/commands/signup.ts","../../src/commands/logout.ts","../../src/commands/profiles.ts","../../src/commands/whoami.ts","../../src/auth/identity/adopt-pending.ts","../../src/auth/identity/switch-adopt.ts","../../src/commands/switch.ts","../../src/plugins/format-load-line.ts","../../src/plugins/resolve-load-path.ts","../../src/plugins/should-log-plugin-loads.ts","../../src/plugins/loader.ts","../../src/commands/version.ts","../../src/auth/identity/adopt-legacy.ts","../../src/auth/identity/prime.ts","../../src/bin/fluid.ts"],"sourcesContent":["/**\n * Tell a person at a terminal, or a coding agent running the CLI for one,\n * that a newer fluid CLI, or a newer Sites plugin beside it, is on npm. npm\n * is asked at most once a day. The check never holds a command open: a run\n * prints what the last check found, and a stale cache is refreshed by a\n * detached child process for next time.\n */\n\nimport { spawn } from \"node:child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport {\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n renameSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { basename, dirname, join, sep } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { LoadedPlugin } from \"../plugins/loader.js\";\n\nexport const PACKAGE_NAME = \"@fluid-app/fluid-cli\";\n/**\n * The plugin that adds the Sites commands. It ships on its own, so a CLI\n * that is up to date can still run a Sites plugin too old for a teammate's\n * site, and its notice is the only hint of that.\n */\nexport const SITES_PLUGIN_NAME = \"@fluid-app/fluid-cli-member-site\";\nexport const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;\n/** The argument the CLI entry point treats as \"refresh the cache and exit\". */\nexport const REFRESH_ARG = \"__refresh-update-check\";\nconst FETCH_TIMEOUT_MS = 5000;\nconst CACHE_FILE = \"update-check.json\";\n/**\n * A coding agent sees the notice once a day: the run that creates the day's\n * claim file, `update-notice-<UTC date>`, shows it. Creating a file that\n * doesn't exist yet succeeds for one run only, however many run at once.\n */\nconst AGENT_NOTICE_CLAIM = \"update-notice-\";\n\nexport interface UpdateCache {\n /** When a check was last started, successful or not. */\n readonly checkedAt: string;\n /** The newest version any check has seen; null before the first success. */\n readonly latest: string | null;\n /** The newest Sites plugin any check has seen; absent before one has. */\n readonly sitesPluginLatest?: string;\n}\n\nexport interface UpdateCheckEnvironment {\n readonly env: NodeJS.ProcessEnv;\n readonly stdoutIsTTY: boolean;\n readonly stderrIsTTY: boolean;\n /** Real path of the running CLI entry point. */\n readonly entryPath: string;\n /** `process.versions`; an `electron` entry means a bundling app runs us. */\n readonly versions?: Partial<Record<string, string>>;\n}\n\n/**\n * Variables coding agents set on the commands they run: the shared\n * `AI_AGENT`, Claude Code, Codex, Cursor's and Gemini's CLIs, and our own\n * `FLUID_AGENT` for any other.\n */\nconst AGENT_ENV = [\n \"FLUID_AGENT\",\n \"AI_AGENT\",\n \"CLAUDECODE\",\n \"CODEX_SANDBOX\",\n \"CODEX_THREAD_ID\",\n \"CURSOR_AGENT\",\n \"GEMINI_CLI\",\n] as const;\n\n/** Whether a coding agent, rather than a person, is running this command. */\nfunction isAgentRun(env: NodeJS.ProcessEnv): boolean {\n return AGENT_ENV.some((name) => {\n const value = env[name]?.trim().toLowerCase();\n return Boolean(value) && value !== \"0\" && value !== \"false\";\n });\n}\n\n/** Who sees the notice: a person at a terminal, a coding agent, or no one. */\nexport type NoticeAudience = \"person\" | \"agent\";\n\n/** Whether an Electron app, such as Mist, is running the CLI it bundles. */\nfunction isElectronRun(\n env: NodeJS.ProcessEnv,\n versions: Partial<Record<string, string>> = {},\n): boolean {\n return Boolean(env[\"ELECTRON_RUN_AS_NODE\"] || versions[\"electron\"]);\n}\n\n/**\n * Only an installed CLI checks, for a person at a terminal or a coding agent\n * (whose output is piped). Other piped runs, CI, a workspace build and a\n * copy an Electron app bundles (the app updates it) stay quiet.\n */\nexport function updateCheckAudience({\n env,\n stdoutIsTTY,\n stderrIsTTY,\n entryPath,\n versions,\n}: UpdateCheckEnvironment): NoticeAudience | null {\n if (env[\"FLUID_NO_UPDATE_CHECK\"] || env[\"NO_UPDATE_NOTIFIER\"]) return null;\n if (env[\"CI\"]) return null;\n if (isElectronRun(env, versions)) return null;\n if (!entryPath.includes(`${sep}node_modules${sep}`)) return null;\n if (stdoutIsTTY && stderrIsTTY) return \"person\";\n return isAgentRun(env) ? \"agent\" : null;\n}\n\nfunction parseVersion(version: string): [number, number, number] | null {\n const match = /^(\\d+)\\.(\\d+)\\.(\\d+)$/.exec(version.trim());\n if (!match) return null;\n return [Number(match[1]), Number(match[2]), Number(match[3])];\n}\n\n/** True when `latest` is a newer release than `current`. Prereleases never count. */\nexport function isNewer(current: string, latest: string): boolean {\n const a = parseVersion(current);\n const b = parseVersion(latest);\n if (!a || !b) return false;\n for (let i = 0; i < 3; i += 1) {\n if (b[i]! !== a[i]!) return b[i]! > a[i]!;\n }\n return false;\n}\n\nexport type PackageManager = \"npm\" | \"pnpm\" | \"yarn\" | \"yarn-classic\" | \"bun\";\n\n/** How the running CLI was installed, which decides the update command. */\nexport type InstallKind =\n | { readonly kind: \"global\"; readonly manager: PackageManager }\n | { readonly kind: \"npx\" }\n | {\n readonly kind: \"local\";\n readonly manager: PackageManager;\n readonly projectDir: string;\n };\n\nconst LOCKFILES: ReadonlyArray<readonly [string, PackageManager]> = [\n [\"pnpm-lock.yaml\", \"pnpm\"],\n [\"bun.lock\", \"bun\"],\n [\"bun.lockb\", \"bun\"],\n [\"yarn.lock\", \"yarn\"],\n [\"package-lock.json\", \"npm\"],\n [\"npm-shrinkwrap.json\", \"npm\"],\n];\n\nfunction projectManager(\n projectDir: string,\n exists: (path: string) => boolean,\n): PackageManager {\n // A workspace member has its lockfile at the workspace root, above it.\n for (let dir = projectDir; ; dir = dirname(dir)) {\n for (const [file, manager] of LOCKFILES) {\n if (!exists(join(dir, file))) continue;\n if (manager !== \"yarn\") return manager;\n return exists(join(dir, \".yarnrc.yml\")) ? \"yarn\" : \"yarn-classic\";\n }\n if (dirname(dir) === dir) return \"npm\";\n }\n}\n\n/**\n * Work out from the entry point's real path how the CLI was installed: an\n * npx cache run, a global install (npm's `lib/node_modules`, or npm on\n * Windows, pnpm's and yarn's global directories), or else a project's own\n * `node_modules`.\n */\nexport function detectInstallKind(\n entryPath: string,\n exists: (path: string) => boolean = existsSync,\n): InstallKind {\n const path = entryPath.replaceAll(\"\\\\\", \"/\");\n if (path.includes(\"/_npx/\")) return { kind: \"npx\" };\n if (/\\/pnpm\\/global\\//i.test(path))\n return { kind: \"global\", manager: \"pnpm\" };\n if (/\\/yarn\\/global\\//i.test(path) || path.includes(\"/.yarn-global/\")) {\n return { kind: \"global\", manager: \"yarn-classic\" };\n }\n if (/\\/\\.bun\\/install\\/global\\//.test(path)) {\n return { kind: \"global\", manager: \"bun\" };\n }\n const modules = path.indexOf(\"/node_modules/\");\n const before = modules === -1 ? path : path.slice(0, modules);\n const projectDir = entryPath.slice(0, modules === -1 ? 0 : modules);\n // npm's global root is `<prefix>/lib`, or `%APPDATA%\\npm` on Windows, and\n // neither holds a package.json. A project that happens to live in a\n // directory named `lib` does, and is updated in place.\n const npmGlobalShape = before.endsWith(\"/lib\") || /\\/npm$/i.test(before);\n if (npmGlobalShape && !exists(join(projectDir, \"package.json\"))) {\n return { kind: \"global\", manager: \"npm\" };\n }\n return {\n kind: \"local\",\n manager: projectManager(projectDir, exists),\n projectDir,\n };\n}\n\nconst PLUGINS_NOTE = \"(and any @fluid-app/fluid-cli-* plugins you use)\";\n\nfunction globalCommand(manager: PackageManager, pkg: string): string {\n switch (manager) {\n case \"npm\":\n return `npm install -g ${pkg}`;\n case \"pnpm\":\n return `pnpm add -g ${pkg}@latest`;\n case \"yarn\":\n case \"yarn-classic\":\n return `yarn global add ${pkg}@latest`;\n case \"bun\":\n return `bun add -g ${pkg}@latest`;\n }\n}\n\nfunction localCommand(manager: PackageManager, pkg: string): string {\n switch (manager) {\n case \"npm\":\n return `npm install ${pkg}@latest`;\n case \"pnpm\":\n return `pnpm update --latest ${pkg}`;\n case \"yarn\":\n return `yarn up ${pkg}@latest`;\n case \"yarn-classic\":\n return `yarn upgrade --latest ${pkg}`;\n case \"bun\":\n return `bun update --latest ${pkg}`;\n }\n}\n\n/** The command that updates `pkg` for this install. */\nexport function updateCommand(install: InstallKind, pkg: string): string {\n switch (install.kind) {\n case \"global\":\n return globalCommand(install.manager, pkg);\n case \"npx\":\n return `npx ${pkg}@latest`;\n case \"local\":\n return localCommand(install.manager, pkg);\n }\n}\n\n/**\n * The line that says how to update `pkg` for this install. The CLI's own\n * names the plugins too, unless a plugin's own notice follows it.\n */\nfunction updateInstruction(\n install: InstallKind,\n pkg: string = PACKAGE_NAME,\n notePlugins = true,\n): string {\n const command = updateCommand(install, pkg);\n const note = notePlugins ? ` ${PLUGINS_NOTE}` : \"\";\n switch (install.kind) {\n case \"global\":\n return `Run: ${command}${note}\\n`;\n case \"npx\":\n return `Run: ${command} to use the latest version\\n`;\n case \"local\":\n return `Run in ${install.projectDir}: ${command}${note}\\n`;\n }\n}\n\nconst OPT_OUT = \"Set FLUID_NO_UPDATE_CHECK=1 to stop these notices.\";\n\n/** A package npm has a newer release of than the copy this run used. */\ninterface PendingUpdate {\n /** How the notice names it. */\n readonly name: string;\n readonly pkg: string;\n readonly installed: string;\n readonly latest: string;\n readonly install: InstallKind;\n}\n\nfunction cliUpdate(\n current: string,\n latest: string,\n install: InstallKind,\n): PendingUpdate | null {\n if (!isNewer(current, latest)) return null;\n return {\n name: \"fluid\",\n pkg: PACKAGE_NAME,\n installed: current,\n latest,\n install,\n };\n}\n\n/** Whether the CLI's update also names the plugins: no plugin's own follows. */\nfunction notesPlugins(\n update: PendingUpdate,\n updates: readonly PendingUpdate[],\n): boolean {\n return (\n update.pkg === PACKAGE_NAME &&\n updates.every(({ pkg }) => pkg === PACKAGE_NAME)\n );\n}\n\n/** A person's notice: each update and how to run it, under one opt-out line. */\nfunction personNotice(updates: readonly PendingUpdate[]): string {\n const bodies = updates.map(\n (update) =>\n `\\nUpdate available for ${update.name}: ${update.installed} → ${update.latest}\\n` +\n updateInstruction(\n update.install,\n update.pkg,\n notesPlugins(update, updates),\n ),\n );\n return `${bodies.join(\"\")}${OPT_OUT}\\n`;\n}\n\n/** A coding agent's notice: one line, with the command for each update. */\nfunction agentNotice(updates: readonly PendingUpdate[]): string {\n const parts = updates.map((update) => {\n const { name, installed, latest, install, pkg } = update;\n const where = install.kind === \"local\" ? ` in ${install.projectDir}` : \"\";\n const plugins = notesPlugins(update, updates)\n ? \", and update any @fluid-app/fluid-cli-* plugins you use\"\n : \"\";\n return `${name} ${installed} → ${latest} (run${where}: ${updateCommand(install, pkg)}${plugins})`;\n });\n return (\n `Update available: ${parts.join(\"; \")}. ` +\n `An older version can lack newer commands, options and config keys. ${OPT_OUT}\\n`\n );\n}\n\nexport function updateNotice(\n current: string,\n latest: string,\n install: InstallKind = { kind: \"global\", manager: \"npm\" },\n): string | null {\n const update = cliUpdate(current, latest, install);\n return update && personNotice([update]);\n}\n\n/**\n * The packages Mist ships: under its app's resources, in\n * `app.asar.unpacked/node_modules/@fluid-app/`. Its app is a\n * `Fluid Mist.app` bundle on macOS, wherever it was moved; its Windows\n * installer puts it in `%LOCALAPPDATA%\\mist-desktop\\app-<version>`, and\n * its Linux packages in `/usr/lib/mist-desktop`.\n */\nconst MIST_PACKAGES = new RegExp(\n \"(?:\" +\n [\n String.raw`[\\\\/]Fluid Mist\\.app[\\\\/]Contents[\\\\/]Resources`,\n String.raw`^[a-z]:[\\\\/]Users[\\\\/][^\\\\/]+[\\\\/]AppData[\\\\/]Local[\\\\/]mist-desktop[\\\\/]app-[^\\\\/]+[\\\\/]resources`,\n String.raw`^/usr/lib/mist-desktop/resources`,\n ].join(\"|\") +\n \")\" +\n String.raw`[\\\\/]app\\.asar\\.unpacked[\\\\/]node_modules[\\\\/]@fluid-app[\\\\/]`,\n \"i\",\n);\n\n/**\n * Whether the package at `path` is a copy Mist ships, which updates with\n * Mist. Mist also runs other CLIs, such as a project's own, through\n * Electron, so its path decides, not how it runs.\n */\nexport function isMistBundled(path: string): boolean {\n return MIST_PACKAGES.test(path);\n}\n\n/**\n * Whether the install root `root` is an Electron app's unpacked resources:\n * an `app.asar.unpacked` folder beside the app's `app.asar` archive, which\n * Electron always writes together. No package manager command updates a\n * copy there, whichever app it came with; a project folder that is only\n * named so has no archive beside it.\n */\nexport function isAppResources(root: string): boolean {\n if (basename(root).toLowerCase() !== \"app.asar.unpacked\") return false;\n try {\n return statSync(join(dirname(root), \"app.asar\")).isFile();\n } catch {\n return false;\n }\n}\n\n/** The folder before the first `node_modules` in a path: its install's root. */\nexport function installRoot(path: string): string | null {\n const at = path.replaceAll(\"\\\\\", \"/\").indexOf(\"/node_modules/\");\n return at === -1 ? null : path.slice(0, at);\n}\n\n/**\n * The version and install root of `pkg` loaded from `source`, read from its\n * package.json. Null for a workspace build, which no notice is for, or when\n * the file can't be read.\n */\nexport function loadedPackage(\n source: string,\n pkg: string,\n): { version: string; root: string } | null {\n let path: string;\n try {\n path = fileURLToPath(source);\n } catch {\n return null;\n }\n const marker = `/node_modules/${pkg}/`;\n const at = path.replaceAll(\"\\\\\", \"/\").lastIndexOf(marker);\n const root = installRoot(path);\n if (at === -1 || root === null) return null;\n try {\n const { version } = JSON.parse(\n readFileSync(\n join(path.slice(0, at + marker.length), \"package.json\"),\n \"utf8\",\n ),\n ) as { version?: unknown };\n return typeof version === \"string\" ? { version, root } : null;\n } catch {\n return null;\n }\n}\n\n/**\n * How `pkg`, installed under `root`, was installed, read from its own path\n * as the CLI's is: globally, by an npx run, or in a project, updated with\n * that project's package manager.\n */\nexport function packageInstallKind(root: string, pkg: string): InstallKind {\n return detectInstallKind(join(root, \"node_modules\", pkg, \"package.json\"));\n}\n\n/**\n * The Sites plugin's update, for the copy this run loaded, when npm has a\n * newer one. An npx run fetches its packages each time, so it has none.\n */\nfunction sitesPluginUpdate(\n options: StartUpdateCheckOptions,\n latest: string | undefined,\n): PendingUpdate | null {\n if (!latest) return null;\n const plugin = options\n .loadedPlugins?.()\n .find((loaded) => loaded.name === SITES_PLUGIN_NAME);\n const installed = plugin && loadedPackage(plugin.source, SITES_PLUGIN_NAME);\n if (!installed || !isNewer(installed.version, latest)) return null;\n const install = packageInstallKind(installed.root, SITES_PLUGIN_NAME);\n if (install.kind === \"npx\") return null;\n return {\n name: \"the Sites plugin (fluid sites)\",\n pkg: SITES_PLUGIN_NAME,\n installed: installed.version,\n latest,\n install,\n };\n}\n\n/** Everything the last check found to update. */\nfunction pendingUpdates(\n options: StartUpdateCheckOptions,\n cache: UpdateCache,\n): PendingUpdate[] {\n const cli = cache.latest\n ? cliUpdate(\n options.currentVersion,\n cache.latest,\n detectInstallKind(options.entryPath),\n )\n : null;\n const plugin = sitesPluginUpdate(options, cache.sitesPluginLatest);\n return [cli, plugin].filter((update) => update !== null);\n}\n\nexport function readUpdateCache(configDir: string): UpdateCache | null {\n try {\n const data = JSON.parse(\n readFileSync(join(configDir, CACHE_FILE), \"utf8\"),\n ) as Partial<UpdateCache>;\n if (typeof data.checkedAt !== \"string\") return null;\n const latest = typeof data.latest === \"string\" ? data.latest : null;\n return {\n checkedAt: data.checkedAt,\n latest,\n ...(typeof data.sitesPluginLatest === \"string\"\n ? { sitesPluginLatest: data.sitesPluginLatest }\n : {}),\n };\n } catch {\n return null;\n }\n}\n\n/**\n * Write the cache, reporting whether it landed. The JSON goes to a fresh\n * file opened exclusively, then is renamed over the cache: a rename replaces\n * a symlink planted at the cache path instead of writing through it, so a\n * shared FLUID_CONFIG_DIR can't aim this write at another of the user's files.\n */\nexport function writeUpdateCache(\n configDir: string,\n cache: UpdateCache,\n): boolean {\n const temp = join(\n configDir,\n `.${CACHE_FILE}.${randomBytes(6).toString(\"hex\")}`,\n );\n try {\n mkdirSync(configDir, { recursive: true });\n writeFileSync(temp, JSON.stringify(cache) + \"\\n\", { flag: \"wx\" });\n renameSync(temp, join(configDir, CACHE_FILE));\n return true;\n } catch {\n // A read-only config directory only costs the notice.\n try {\n rmSync(temp, { force: true });\n } catch {\n // Nothing was written if the directory itself is unusable.\n }\n return false;\n }\n}\n\nexport function isStale(cache: UpdateCache | null, now: Date): boolean {\n if (!cache) return true;\n const checkedAt = Date.parse(cache.checkedAt);\n return (\n Number.isNaN(checkedAt) || now.getTime() - checkedAt >= CHECK_INTERVAL_MS\n );\n}\n\nexport async function fetchLatestVersion(\n fetchImpl: typeof fetch = fetch,\n pkg: string = PACKAGE_NAME,\n): Promise<string | null> {\n try {\n const response = await fetchImpl(\n `https://registry.npmjs.org/${pkg}/latest`,\n { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) },\n );\n if (!response.ok) return null;\n const body = (await response.json()) as { version?: unknown };\n return typeof body.version === \"string\" ? body.version : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Ask npm for the latest CLI and Sites plugin and record them. Runs in the\n * detached child; a failure leaves the last known versions and the throttle\n * stamp in place.\n */\nexport async function refreshUpdateCache(\n configDir: string,\n fetchImpl: typeof fetch = fetch,\n now: Date = new Date(),\n): Promise<void> {\n const [latest, sitesPluginLatest] = await Promise.all([\n fetchLatestVersion(fetchImpl),\n fetchLatestVersion(fetchImpl, SITES_PLUGIN_NAME),\n ]);\n if (!latest && !sitesPluginLatest) return;\n const known = readUpdateCache(configDir);\n const plugin = sitesPluginLatest ?? known?.sitesPluginLatest;\n writeUpdateCache(configDir, {\n checkedAt: now.toISOString(),\n latest: latest ?? known?.latest ?? null,\n ...(plugin ? { sitesPluginLatest: plugin } : {}),\n });\n}\n\n/** Start `node <entry> __refresh-update-check` detached, so this run never waits on npm. */\nexport function spawnRefresh(entryPath: string): void {\n try {\n const child = spawn(process.execPath, [entryPath, REFRESH_ARG], {\n detached: true,\n stdio: \"ignore\",\n windowsHide: true,\n });\n child.on(\"error\", () => {});\n child.unref();\n } catch {\n // No refresh this time; the throttle stamp retries tomorrow.\n }\n}\n\nexport interface StartUpdateCheckOptions extends UpdateCheckEnvironment {\n readonly currentVersion: string;\n readonly configDir: string;\n readonly now?: Date;\n /** Called with the notice when the process exits. */\n readonly onExit?: (listener: () => void) => void;\n /**\n * The plugins the run loaded, asked for at exit: the Sites plugin's notice\n * is for the copy that ran. Without it there is no plugin notice.\n */\n readonly loadedPlugins?: () => readonly LoadedPlugin[];\n /**\n * Whether the command that ran keeps the notice from `audience`, asked at\n * exit: an agent's from JSON it may merge stderr into, and anyone's from\n * a command such as `fluid version`, which reports updates itself.\n */\n readonly quiet?: (audience: NoticeAudience) => boolean;\n readonly refresh?: (entryPath: string) => void;\n}\n\n/** The name of the claim file for the UTC day `now` falls on. */\nfunction agentNoticeClaim(now: Date): string {\n return `${AGENT_NOTICE_CLAIM}${now.toISOString().slice(0, 10)}`;\n}\n\n/**\n * Show an agent the notice if this run is the first to claim the day. The\n * claim is created exclusively, so it never writes through a planted link,\n * and an unwritable config directory shows an agent nothing. Earlier days'\n * claims are removed; a later day's, from a run that started after this\n * one's day ended, is kept.\n */\nfunction showAgentNotice(\n configDir: string,\n updates: readonly PendingUpdate[],\n now: Date,\n): void {\n const claim = agentNoticeClaim(now);\n try {\n writeFileSync(join(configDir, claim), \"\", { flag: \"wx\" });\n } catch {\n return;\n }\n process.stderr.write(agentNotice(updates));\n try {\n for (const name of readdirSync(configDir)) {\n // The ISO dates sort as text, so this removes only earlier days.\n if (name.startsWith(AGENT_NOTICE_CLAIM) && name < claim) {\n rmSync(join(configDir, name), { force: true });\n }\n }\n } catch {\n // An old claim left behind costs nothing.\n }\n}\n\n/**\n * Print the cached notice when the command finishes (to an agent, at most\n * once a day) and, when the last check started a day ago or more, stamp the\n * cache and refresh it in a detached process. The stamp throttles failed and\n * concurrent checks to one a day while keeping the last known version, and\n * its notice, in place.\n */\nexport function startUpdateCheck(options: StartUpdateCheckOptions): void {\n const audience = updateCheckAudience(options);\n if (!audience) return;\n\n const now = options.now ?? new Date();\n const cache = readUpdateCache(options.configDir);\n if (cache?.latest || cache?.sitesPluginLatest) {\n const onExit =\n options.onExit ??\n ((listener: () => void) => process.once(\"exit\", listener));\n // Worked out at exit, so a run never waits on the plugin's package.json.\n onExit(() => {\n if (options.quiet?.(audience)) return;\n // Most of an agent's commands end after the day is claimed, so that is\n // checked before any install is looked at.\n if (\n audience === \"agent\" &&\n existsSync(join(options.configDir, agentNoticeClaim(now)))\n ) {\n return;\n }\n const updates = pendingUpdates(options, cache);\n if (updates.length === 0) return;\n if (audience === \"person\") process.stderr.write(personNotice(updates));\n else showAgentNotice(options.configDir, updates, now);\n });\n }\n\n if (!isStale(cache, now)) return;\n const stamped = writeUpdateCache(options.configDir, {\n checkedAt: now.toISOString(),\n latest: cache?.latest ?? null,\n ...(cache?.sitesPluginLatest\n ? { sitesPluginLatest: cache.sitesPluginLatest }\n : {}),\n });\n // Without the stamp there is no throttle, and the child couldn't record\n // what it found either, so an unwritable cache never starts a refresh.\n if (stamped) (options.refresh ?? spawnRefresh)(options.entryPath);\n}\n","/**\n * Auto-discover @fluid-app CLI plugins.\n *\n * Three discovery strategies run in order:\n *\n * 1a. **node_modules scan (cwd)** — look in `<cwd>/node_modules/@fluid-app/`\n * for directories whose names match the plugin naming convention.\n * This is the primary mechanism for project-local plugin installs.\n *\n * 1b. **node_modules scan (CLI install location)** — look in the\n * `node_modules/@fluid-app/` directory containing the CLI core package\n * itself. This covers global installs where plugins are sibling packages\n * under the same global `node_modules/`.\n *\n * 2. **Workspace scan** — walk upward from the CLI core package root to the\n * monorepo workspace root, then scan `packages/` for sibling plugin\n * packages. This covers the pnpm-workspace development case where\n * plugins are not symlinked into `node_modules`.\n *\n * Only first-party @fluid-app scoped packages are loaded.\n */\n\nimport { isStrictConfig } from \"../config/strict.js\";\nimport { existsSync, readFileSync, readdirSync, realpathSync } from \"node:fs\";\nimport { dirname, isAbsolute, join, relative } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\n\nconst PLUGIN_SCOPE = \"@fluid-app\";\n\n/**\n * A plugin package name must match one of these patterns:\n * - @fluid-app/fluid-cli-* (standard)\n * - @fluid-app/*-cli-commands (v2025-06 style)\n */\nfunction isPluginName(packageName: string): boolean {\n if (!packageName.startsWith(`${PLUGIN_SCOPE}/`)) return false;\n const bare = packageName.slice(`${PLUGIN_SCOPE}/`.length);\n return bare.startsWith(\"fluid-cli-\") || bare.endsWith(\"-cli-commands\");\n}\n\n// Strategy 1: node_modules scan (production / published installs)\n\nfunction discoverFromNodeModules(basePath: string): DiscoveredPlugin[] {\n const scopeDir = join(basePath, \"node_modules\", PLUGIN_SCOPE);\n\n if (!existsSync(scopeDir)) return [];\n\n return readdirSync(scopeDir, { withFileTypes: true })\n .filter(\n (entry) =>\n (entry.isDirectory() || entry.isSymbolicLink()) &&\n isPluginName(`${PLUGIN_SCOPE}/${entry.name}`),\n )\n .map((entry) => {\n const name = `${PLUGIN_SCOPE}/${entry.name}`;\n const entryDir = join(scopeDir, entry.name);\n // Resolve symlinks (pnpm workspace links) to file:// URLs so the\n // dynamic import works regardless of pnpm's strict module resolution.\n try {\n const realDir = realpathSync(entryDir);\n const distEntry = join(realDir, \"dist\", \"index.mjs\");\n if (existsSync(distEntry)) {\n return { name, importSpecifier: pathToFileURL(distEntry).href };\n }\n } catch {\n // Broken symlink or other fs error — fall through to bare specifier\n }\n // Fallback to bare specifier for non-workspace (published) installs\n return { name, importSpecifier: name };\n });\n}\n\n// Strategy 2: workspace scan (pnpm monorepo development)\n\nfunction findWorkspaceRoot(startDir: string): string | null {\n let dir = startDir;\n while (true) {\n if (\n existsSync(join(dir, \"pnpm-workspace.yaml\")) ||\n existsSync(join(dir, \"pnpm-workspace.yml\"))\n ) {\n return dir;\n }\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\nfunction readPackageName(dir: string): string | null {\n const pkgPath = join(dir, \"package.json\");\n if (!existsSync(pkgPath)) return null;\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as {\n name?: string;\n };\n return pkg.name ?? null;\n } catch {\n return null;\n }\n}\n\nexport interface DiscoveredPlugin {\n name: string;\n importSpecifier: string;\n}\n\nexport interface PluginDiscoveryOptions {\n /**\n * Prefer plugins installed beside this CLI over same-named packages in the\n * target project's node_modules. Desktop callers use this so an older\n * project-local plugin cannot override the command contract bundled with\n * the app. Normal project-local CLI invocations keep the existing order.\n */\n preferInstallation?: boolean;\n /**\n * Load only plugins whose entry file, after realpath, sits under the CLI\n * installation's own node_modules, or under the CLI's own monorepo\n * `packages/` when the CLI core is at `<workspace>/packages/cli/core`.\n * A bare plugin name is resolved by Node itself, as the loader's import\n * would, and the file it resolves to is what gets imported. No other\n * directory is trusted, and a plugin that cannot be resolved or placed\n * under one of those two is skipped. Used for the input-resolve pass, which runs\n * before the user has approved anything.\n */\n installationOnly?: boolean;\n /** Test seam: resolves a bare specifier to a file URL the way Node does. */\n resolveSpecifier?: (specifier: string) => string;\n /** Test seam for the CLI core package directory. */\n coreDir?: string;\n /** Test seam for the directory containing the CLI installation. */\n installationBasePath?: string;\n}\n\nfunction discoverFromWorkspace(startDir: string): DiscoveredPlugin[] {\n const workspaceRoot = findWorkspaceRoot(startDir);\n if (!workspaceRoot) return [];\n\n const results: DiscoveredPlugin[] = [];\n const packagesDir = join(workspaceRoot, \"packages\");\n if (!existsSync(packagesDir)) return [];\n\n // Scan exactly two levels deep under packages/ (e.g. packages/cli/themes,\n // packages/cli/v2025-06). This matches the monorepo convention where all\n // packages live at packages/<domain>/<package>/.\n // If a plugin is added at a different depth, update this scan accordingly.\n let domainDirs: string[];\n try {\n domainDirs = readdirSync(packagesDir, { withFileTypes: true })\n .filter((e) => e.isDirectory())\n .map((e) => join(packagesDir, e.name));\n } catch {\n return [];\n }\n\n for (const domainDir of domainDirs) {\n let subDirs: string[];\n try {\n subDirs = readdirSync(domainDir, { withFileTypes: true })\n .filter((e) => e.isDirectory())\n .map((e) => join(domainDir, e.name));\n } catch {\n continue;\n }\n\n for (const subDir of subDirs) {\n const name = readPackageName(subDir);\n if (!name || !name.startsWith(`${PLUGIN_SCOPE}/`) || !isPluginName(name))\n continue;\n\n const distEntry = join(subDir, \"dist\", \"index.mjs\");\n if (!existsSync(distEntry)) {\n continue;\n }\n\n results.push({\n name,\n importSpecifier: pathToFileURL(distEntry).href,\n });\n }\n }\n\n return results;\n}\n\n// Exported API\n\n/** Resolved once — the CLI core package root (`packages/cli/core/`). */\nexport const corePackageDir = dirname(\n dirname(dirname(fileURLToPath(import.meta.url))),\n);\n\n/**\n * The monorepo the CLI core at `coreDir` was built in: its workspace root,\n * found walking up from `searchFrom`, when the core is that workspace's\n * `packages/cli/core`. Null for any installed copy.\n */\nexport function cliWorkspaceRoot(\n coreDir: string = corePackageDir,\n searchFrom: string = coreDir,\n): string | null {\n const workspace = findWorkspaceRoot(searchFrom);\n if (workspace === null) return null;\n try {\n return relative(realpathSync(workspace), realpathSync(coreDir)) ===\n join(\"packages\", \"cli\", \"core\")\n ? workspace\n : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Discover installed plugin packages. Returns a de-duplicated, sorted list\n * of `{ name, importSpecifier }` objects.\n *\n * @param basePath - Directory to scan for `node_modules/@fluid-app/`\n * @param searchFrom - Starting directory for workspace root detection\n * (walked upward via `findWorkspaceRoot`). Pass `null` to skip workspace\n * scanning (useful in tests). Defaults to `corePackageDir`.\n */\nexport function discoverPlugins(\n basePath: string,\n searchFrom?: string | null,\n options: PluginDiscoveryOptions = {},\n): DiscoveredPlugin[] {\n const seen = new Set<string>();\n const results: DiscoveredPlugin[] = [];\n\n const addPlugins = (plugins: DiscoveredPlugin[]) => {\n for (const plugin of plugins) {\n if (seen.has(plugin.name)) continue;\n seen.add(plugin.name);\n results.push(plugin);\n }\n };\n\n const cliParent =\n options.installationBasePath ?? dirname(dirname(dirname(corePackageDir)));\n const projectPlugins = () =>\n isStrictConfig() ? [] : discoverFromNodeModules(basePath);\n const installationPlugins = () =>\n cliParent === basePath && !isStrictConfig()\n ? []\n : discoverFromNodeModules(cliParent);\n const workspacePlugins = () => {\n if (searchFrom === null) return [];\n return discoverFromWorkspace(\n searchFrom ?? options.coreDir ?? corePackageDir,\n );\n };\n\n if (options.installationOnly) {\n const trustedRoots: string[] = [];\n const trust = (dir: string | null) => {\n if (dir === null) return;\n try {\n trustedRoots.push(realpathSync(dir));\n } catch {}\n };\n trust(join(cliParent, \"node_modules\"));\n const workspace =\n searchFrom === null\n ? null\n : cliWorkspaceRoot(options.coreDir ?? corePackageDir, searchFrom);\n if (workspace !== null) trust(join(workspace, \"packages\"));\n const resolveBare =\n options.resolveSpecifier ?? ((name: string) => import.meta.resolve(name));\n const inside = (file: string): boolean =>\n trustedRoots.some((root) => {\n const rel = relative(root, file);\n return rel !== \"\" && !rel.startsWith(\"..\") && !isAbsolute(rel);\n });\n const validated = (plugin: DiscoveredPlugin): DiscoveredPlugin | null => {\n try {\n const file = plugin.importSpecifier.startsWith(\"file:\")\n ? fileURLToPath(plugin.importSpecifier)\n : fileURLToPath(resolveBare(plugin.name));\n const real = realpathSync(file);\n return inside(real)\n ? { name: plugin.name, importSpecifier: pathToFileURL(real).href }\n : null;\n } catch {\n return null;\n }\n };\n const keep = (plugins: DiscoveredPlugin[]): DiscoveredPlugin[] =>\n plugins.flatMap((plugin) => validated(plugin) ?? []);\n addPlugins(keep(discoverFromNodeModules(cliParent)));\n if (workspace !== null) addPlugins(keep(workspacePlugins()));\n } else if (options.preferInstallation) {\n addPlugins(installationPlugins());\n // In a monorepo development build, resolveFluidBinary() deliberately\n // realpaths the CLI into packages/cli/core. Its sibling plugins are then\n // discovered from the workspace rather than an installation-level\n // node_modules, so they are part of the same trusted CLI installation.\n addPlugins(workspacePlugins());\n addPlugins(projectPlugins());\n } else {\n addPlugins(projectPlugins());\n addPlugins(installationPlugins());\n addPlugins(workspacePlugins());\n }\n\n return results.sort((a, b) => a.name.localeCompare(b.name));\n}\n\n/**\n * Dynamically import a plugin module and return its default export.\n *\n * @internal Not intended for external callers. Only called with specifiers\n * produced by {@link discoverPlugins}:\n * - bare package names (e.g. `@fluid-app/fluid-cli-portal`) from the\n * node_modules scan, validated by {@link isPluginName}.\n * - `file://` URLs from {@link discoverFromWorkspace}, which constructs\n * them internally from validated workspace paths (`packages/` tree,\n * `dist/index.mjs`). These are trusted internal specifiers.\n */\nexport async function importPlugin(specifier: string): Promise<unknown> {\n // file:// URLs are trusted — they originate from discoverFromWorkspace\n // which builds them from validated workspace paths under packages/.\n // For bare package names, verify they match the plugin naming convention.\n if (!specifier.startsWith(\"file://\") && !isPluginName(specifier)) {\n throw new Error(`Refusing to import non-plugin package: ${specifier}`);\n }\n const mod = (await import(specifier)) as Record<string, unknown>;\n return mod[\"default\"] ?? mod;\n}\n","/**\n * Whether a host that owns this CLI run, such as Mist, asked for the plugins\n * installed beside the CLI over a project's own (FLUID_CLI_PREFER_INSTALLATION_PLUGINS=1).\n */\nexport function prefersInstallationPlugins(\n env: NodeJS.ProcessEnv = process.env,\n): boolean {\n return env[\"FLUID_CLI_PREFER_INSTALLATION_PLUGINS\"] === \"1\";\n}\n","import type { Command } from \"commander\";\nimport { realpathSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { readConfig } from \"../config/config.js\";\nimport {\n SITES_PLUGIN_NAME as SITES_PLUGIN,\n installRoot,\n isAppResources,\n isMistBundled,\n} from \"../update/notifier.js\";\nimport { cliWorkspaceRoot } from \"./discovery.js\";\nimport { prefersInstallationPlugins } from \"./prefer-installation.js\";\n\n/** How a Mist dev build builds the plugins its workspace CLI loads. */\nconst MIST_RUNTIME_BUILD =\n \"pnpm --filter mist-desktop build:runtime-deps, then restart Mist\";\n\n/** The Sites plugin's top-level commands: core can't ask an unloaded plugin. */\nconst SITES_COMMANDS = new Set([\"sites\", \"deploy\", \"member-site\", \"vault\"]);\n\nexport interface MissingPluginOptions {\n /** The config's allow-list; read from the config when left out. */\n readonly enabledPlugins?: readonly string[] | null;\n /** Real path of a file in the running CLI's package. */\n readonly entryPath?: string;\n /** The monorepo the running CLI was built in; null for an installed copy. */\n readonly workspaceRoot?: string | null;\n /** Whether Mist runs this CLI; read from the environment when left out. */\n readonly preferInstallation?: boolean;\n}\n\n/**\n * What gets the Sites plugin for the running CLI, as a clause. A workspace\n * build loads the plugin's own build in its checkout, which only building it\n * makes, through Mist's runtime build when Mist runs it (Mist's CLI runs\n * prefer installation plugins). A copy an app bundles,\n * such as Mist's, comes with that app, so no global install reaches it. Any\n * other copy installs it with npm.\n */\nfunction pluginStep(\n entryPath: string,\n workspaceRoot: string | null,\n mist: boolean,\n): string {\n if (workspaceRoot !== null) {\n const build = mist\n ? MIST_RUNTIME_BUILD\n : `pnpm --filter ${SITES_PLUGIN} build`;\n return `build it in ${workspaceRoot} with ${build}`;\n }\n if (isMistBundled(entryPath)) {\n return \"reinstall or update Mist, which ships the Sites plugin\";\n }\n const root = installRoot(entryPath);\n if (root !== null && isAppResources(root)) {\n return \"reinstall or update the app this CLI comes with, which ships the Sites plugin\";\n }\n return `install or update it with npm install -g ${SITES_PLUGIN}`;\n}\n\n/**\n * Why `fluid <name>` (or `fluid help <name>`) is missing when the Sites plugin\n * adds it and no loaded plugin did, since commander's \"unknown command\" reads\n * as if Fluid has no Sites, and what gets the plugin for this CLI. When\n * `enabledPlugins` leaves the plugin out, an install changes nothing, so the\n * hint says to add it there first. Null otherwise.\n */\nexport function missingPluginHint(\n program: Command,\n args: readonly string[],\n options: MissingPluginOptions = {},\n): string | null {\n const name = args[0] === \"help\" ? args[1] : args[0];\n if (name === undefined || !SITES_COMMANDS.has(name)) return null;\n const loaded = program.commands.some(\n (command) => command.name() === name || command.aliases().includes(name),\n );\n if (loaded) return null;\n const enabledPlugins =\n options.enabledPlugins === undefined\n ? readConfig().enabledPlugins\n : options.enabledPlugins;\n const step = pluginStep(\n options.entryPath ?? realpathSync(fileURLToPath(import.meta.url)),\n options.workspaceRoot === undefined\n ? cliWorkspaceRoot()\n : options.workspaceRoot,\n options.preferInstallation ?? prefersInstallationPlugins(),\n );\n const reason =\n enabledPlugins !== null && !enabledPlugins.includes(SITES_PLUGIN)\n ? `which enabledPlugins in your Fluid config leaves out. Add ${SITES_PLUGIN} to it, and if it still isn't loaded, ${step}`\n : `which is not loaded. To load it, ${step}`;\n return `fluid ${name} comes from the Sites plugin, ${reason}.`;\n}\n","/**\n * fluid commands — list every installed command, or print the catalog as\n * JSON for agents and documentation generators.\n */\n\nimport { Command } from \"commander\";\nimport { createRequire } from \"node:module\";\nimport {\n filterCatalog,\n rootCommand,\n walkCommands,\n type CatalogEntry,\n} from \"../catalog/walk.js\";\nimport { missingPluginHint } from \"../plugins/missing-plugin.js\";\n\nconst require = createRequire(import.meta.url);\nconst { version } = require(\"../../package.json\") as { version: string };\n\nfunction usage(entry: CatalogEntry): string {\n const args = entry.arguments.map((arg) => {\n const name = arg.variadic ? `${arg.name}...` : arg.name;\n return arg.required ? `<${name}>` : `[${name}]`;\n });\n return [entry.command, ...args].join(\" \");\n}\n\nexport function formatCatalogText(entries: readonly CatalogEntry[]): string {\n const runnable = entries.filter((entry) => entry.runnable);\n const width = Math.min(\n 48,\n Math.max(0, ...runnable.map((entry) => usage(entry).length)),\n );\n return runnable\n .map((entry) => {\n const line = usage(entry);\n const summary = entry.description.split(\"\\n\", 1)[0] ?? \"\";\n return summary ? `${line.padEnd(width)} ${summary}` : line;\n })\n .join(\"\\n\");\n}\n\nexport const commandsCommand = new Command(\"commands\")\n .description(\"List installed commands; --json prints the full catalog\")\n .argument(\"[prefix...]\", \"Only list commands under this one, e.g. `domains`\")\n .option(\"--json\", \"Print the catalog as JSON\", false)\n .action((prefix: string[], opts: { json: boolean }, command: Command) => {\n const root = rootCommand(command);\n\n const entries = filterCatalog(walkCommands(root), root, prefix);\n if (entries.length === 0) {\n const hint = missingPluginHint(root, prefix);\n process.stderr.write(\n JSON.stringify({\n error: `No command named \"${prefix.join(\" \")}\".`,\n ...(hint ? { hint } : {}),\n }) + \"\\n\",\n );\n process.exitCode = 1;\n return;\n }\n\n if (opts.json) {\n process.stdout.write(\n JSON.stringify(\n { cli: root.name(), version, commands: entries },\n null,\n 2,\n ) + \"\\n\",\n );\n return;\n }\n process.stdout.write(formatCatalogText(entries) + \"\\n\");\n });\n","/**\n * Shell completion. The scripts `fluid completion <shell>` prints pipe the\n * words typed so far into the hidden `fluid __complete`, so completions come\n * from the plugins actually installed rather than a list frozen at install.\n * The words go over stdin, never argv: a half-typed `--token <value>` must\n * not show up in another user's process list.\n */\n\nimport type { Command, Option } from \"commander\";\nimport { visibleOptions, visibleSubcommands } from \"../catalog/walk.js\";\n\nexport const SHELLS = [\"bash\", \"zsh\", \"fish\"] as const;\nexport type Shell = (typeof SHELLS)[number];\n\nexport interface Candidate {\n readonly value: string;\n readonly description: string;\n}\n\nfunction findOption(chain: readonly Command[], word: string): Option | null {\n const flag = word.split(\"=\", 1)[0] ?? word;\n for (const command of [...chain].reverse()) {\n const match = command.options.find(\n (option) => option.long === flag || option.short === flag,\n );\n if (match) return match;\n }\n return null;\n}\n\nfunction splitAssignment(word: string): [string, string] {\n const at = word.indexOf(\"=\");\n return [word.slice(0, at), word.slice(at + 1)];\n}\n\nfunction choicesFor(option: Option, typed: string): Candidate[] {\n return (option.argChoices ?? [])\n .filter((choice) => choice.startsWith(typed))\n .map((choice) => ({ value: choice, description: \"\" }));\n}\n\nfunction findSubcommand(command: Command, word: string): Command | null {\n return (\n visibleSubcommands(command).find(\n (sub) => sub.name() === word || sub.aliases().includes(word),\n ) ?? null\n );\n}\n\n/**\n * Complete the last of `words`, the words after the program name.\n * Where a flag's value is expected, offers the flag's choices if it has\n * any; otherwise returns nothing so the shell falls back to files.\n */\nexport function completeWords(\n root: Command,\n words: readonly string[],\n): Candidate[] {\n const partial = words.at(-1) ?? \"\";\n const chain: Command[] = [root];\n let current = root;\n let awaitingValue: Option | null = null;\n let operandsOnly = false;\n // Operands typed for `current`; only the first can name a subcommand.\n let operands = 0;\n\n const prior = words.slice(0, -1);\n for (const [index, word] of prior.entries()) {\n if (awaitingValue) {\n // Bash splits `--flag=value` at the `=`, so the value follows it.\n if (word !== \"=\" || prior[index - 1] === \"=\") awaitingValue = null;\n continue;\n }\n if (!operandsOnly && word === \"--\") {\n operandsOnly = true;\n continue;\n }\n if (!operandsOnly && word.startsWith(\"-\")) {\n const option = findOption(chain, word);\n awaitingValue = option?.required && !word.includes(\"=\") ? option : null;\n continue;\n }\n const sub = operands === 0 ? findSubcommand(current, word) : null;\n if (sub) {\n current = sub;\n chain.push(sub);\n } else {\n operands += 1;\n }\n }\n\n if (awaitingValue) {\n // After bash's split the partial is the bare `=` before any value.\n const typed = partial === \"=\" ? \"\" : partial;\n return choicesFor(awaitingValue, typed);\n }\n\n if (!operandsOnly && partial.startsWith(\"--\") && partial.includes(\"=\")) {\n // zsh and fish keep `--flag=value` as one word, and so must the reply.\n const [flag = \"\", typed = \"\"] = splitAssignment(partial);\n const option = findOption(chain, flag);\n if (!option?.required && !option?.optional) return [];\n return choicesFor(option, typed).map((choice) => ({\n ...choice,\n value: `${flag}=${choice.value}`,\n }));\n }\n\n if (!operandsOnly && partial.startsWith(\"-\")) {\n const seen = new Set<string>();\n const candidates: Candidate[] = [];\n for (const command of [...chain].reverse()) {\n for (const option of visibleOptions(command)) {\n // The program's --version belongs to `fluid` alone.\n if (option.long === \"--version\" && command !== current) continue;\n for (const value of [option.long, option.short]) {\n if (!value || seen.has(value)) continue;\n seen.add(value);\n candidates.push({ value, description: option.description });\n }\n }\n }\n candidates.push({ value: \"--help\", description: \"Show help\" });\n return candidates.filter((c) => c.value.startsWith(partial));\n }\n\n const candidates: Candidate[] = [];\n if (operands === 0) {\n for (const sub of visibleSubcommands(current)) {\n for (const name of [sub.name(), ...sub.aliases()]) {\n candidates.push({ value: name, description: sub.description() });\n }\n }\n }\n const args = current.registeredArguments;\n const last = args.at(-1);\n const argument = args[operands] ?? (last?.variadic ? last : undefined);\n for (const choice of argument?.argChoices ?? []) {\n candidates.push({\n value: choice,\n description: argument?.description ?? \"\",\n });\n }\n return candidates.filter((c) => c.value.startsWith(partial));\n}\n\n/**\n * The words the scripts pipe in: each followed by a NUL, the program name\n * first. Returns the words after the program name, at least one.\n */\nexport function parseCompletionInput(input: string): string[] {\n const words = input.split(\"\\0\");\n // The text after the last NUL is the empty tail of the final terminator.\n words.pop();\n const typed = words.slice(1);\n return typed.length > 0 ? typed : [\"\"];\n}\n\nfunction firstLine(text: string): string {\n return text.split(\"\\n\", 1)[0]?.trim() ?? \"\";\n}\n\n/** One candidate per line, in the shape each shell's script reads. */\nexport function formatCandidates(\n candidates: readonly Candidate[],\n shell: Shell,\n): string {\n const lines = candidates.map(({ value, description }) => {\n const summary = firstLine(description);\n switch (shell) {\n case \"bash\":\n return value;\n case \"zsh\":\n // _describe splits on the first unescaped colon.\n return summary\n ? `${value.replaceAll(\":\", \"\\\\:\")}:${summary}`\n : value.replaceAll(\":\", \"\\\\:\");\n case \"fish\":\n return summary ? `${value}\\t${summary}` : value;\n }\n });\n return lines.length > 0 ? `${lines.join(\"\\n\")}\\n` : \"\";\n}\n\nexport function completionScript(shell: Shell): string {\n switch (shell) {\n case \"bash\":\n // Words are copied one by one: bash 3.2, macOS's /bin/bash, joins\n // a quoted array slice into one word while IFS is a newline.\n return `# fluid bash completion\n_fluid_complete() {\n local -a words\n local i\n for ((i = 0; i <= COMP_CWORD; i++)); do words+=(\"\\${COMP_WORDS[i]}\"); done\n local IFS=$'\\\\n'\n COMPREPLY=($(printf '%s\\\\0' \"\\${words[@]}\" | fluid __complete --shell bash 2>/dev/null))\n}\ncomplete -o default -F _fluid_complete fluid\n`;\n case \"zsh\":\n return `#compdef fluid\n# fluid zsh completion\n_fluid() {\n local -a candidates\n candidates=(\"\\${(@f)$(printf '%s\\\\0' \"\\${(@)words[1,CURRENT]}\" | fluid __complete --shell zsh 2>/dev/null)}\")\n candidates=(\\${candidates:#})\n if (( \\${#candidates} )); then\n _describe -t fluid 'fluid' candidates\n else\n _files\n fi\n}\nif [[ \\${zsh_eval_context[-1]} == loadautofunc ]]; then\n _fluid \"$@\"\nelse\n compdef _fluid fluid\nfi\n`;\n case \"fish\":\n // The current token goes through a variable so an empty one is still\n // sent: a bare (commandline -ct) expands to no argument at all.\n return `# fluid fish completion\nfunction __fluid_complete\n set -l current (commandline -ct)\n set -l candidates (string join0 -- (commandline -opc) \"$current\" | fluid __complete --shell fish 2>/dev/null)\n if set -q candidates[1]\n printf '%s\\\\n' $candidates\n else\n __fish_complete_path \"$current\"\n end\nend\ncomplete -c fluid -f -a '(__fluid_complete)'\n`;\n }\n}\n\nexport const COMPLETION_INSTALL_HELP = `\nInstall:\n bash echo 'eval \"$(fluid completion bash)\"' >> ~/.bashrc\n zsh fluid completion zsh > \"\\${fpath[1]}/_fluid\" (or eval \"$(fluid completion zsh)\" in ~/.zshrc)\n fish fluid completion fish > ~/.config/fish/completions/fluid.fish\n`;\n","/**\n * fluid completion <shell> — print a shell completion script.\n * fluid __complete — the hidden command that script pipes the typed words\n * into on each tab.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { Argument, Command, Option } from \"commander\";\nimport {\n completeWords,\n completionScript,\n COMPLETION_INSTALL_HELP,\n formatCandidates,\n parseCompletionInput,\n SHELLS,\n type Shell,\n} from \"../completion/complete.js\";\nimport { rootCommand } from \"../catalog/walk.js\";\n\nexport const completionCommand = new Command(\"completion\")\n .description(\"Print a shell completion script for bash, zsh or fish\")\n .addArgument(new Argument(\"<shell>\", \"Shell to complete in\").choices(SHELLS))\n .addHelpText(\"after\", COMPLETION_INSTALL_HELP)\n .action((shell: Shell) => {\n process.stdout.write(completionScript(shell));\n });\n\nexport const completeCommand = new Command(\"__complete\")\n .description(\"Print completions for the words typed so far\")\n .addOption(\n new Option(\"--shell <shell>\", \"Output format\")\n .choices(SHELLS)\n .default(\"bash\"),\n )\n .action((opts: { shell: Shell }, command: Command) => {\n // The words arrive on stdin, NUL-terminated, never as arguments.\n const typed = parseCompletionInput(readFileSync(0, \"utf8\"));\n process.stdout.write(\n formatCandidates(completeWords(rootCommand(command), typed), opts.shell),\n );\n });\n","/**\n * Trades a legacy Fluid token for a native identity session with no browser\n * hop (RFC 004 S3.4g): Rails mints a PKCE-bound adopt code for the legacy\n * bearer, and the session redeems it at the identity service's `/token`.\n * The legacy token is never altered here; the caller removes it only after\n * an `adopted` result.\n */\n\nimport { createCodeChallenge, createCodeVerifier } from \"../session/pkce\";\nimport type { PkceCrypto } from \"../session/pkce\";\nimport type { SessionFacts } from \"../session/types\";\nimport { SessionError } from \"../session/types\";\nimport type { AdoptedSession, NativeSession } from \"./secure-session\";\n\nconst REQUEST_TIMEOUT_MS = 15_000;\n\nexport type TradeReason =\n | \"mint_refused\"\n | \"grant_refused\"\n | \"landing_mismatch\"\n | \"landing_unverifiable\";\n\nexport type TradeResult =\n | {\n readonly outcome: \"adopted\";\n readonly facts: SessionFacts;\n /** Whether the session is still the one this trade opened. */\n readonly isCurrent: () => boolean;\n /** Signs the adopted session out again, only while it is still this trade's. */\n readonly discard: () => Promise<boolean>;\n }\n | { readonly outcome: \"not_targeted\" }\n | { readonly outcome: \"refused\"; readonly reason: TradeReason }\n | { readonly outcome: \"unavailable\" };\n\nexport interface TradeLegacyTokenOptions {\n /** The legacy Rails token to trade; it is only ever sent to `apiBase`. */\n readonly legacyToken: string;\n /** The Fluid API origin that issued the token, for example `https://api.fluid.app`. */\n readonly apiBase: string;\n /** The native session that will hold the identity session on success. */\n readonly session: NativeSession;\n readonly fetch?: typeof fetch;\n readonly crypto?: PkceCrypto;\n /** Receives one line naming the outcome; never a token, code or verifier. */\n readonly log?: (message: string) => void;\n readonly requestTimeoutMs?: number;\n /** Called right before this trade discards a session it redeemed. */\n readonly beforeDiscard?: () => void;\n /**\n * Awaited after a successful mint and before the redeem. When it throws\n * the trade is `unavailable` and nothing is redeemed.\n */\n readonly beforeRedeem?: () => Promise<void> | void;\n}\n\ninterface MeIdentity {\n readonly userId: string;\n readonly companyId: string;\n}\n\ntype MeRead =\n | { readonly kind: \"ok\"; readonly me: MeIdentity }\n | { readonly kind: \"unavailable\" }\n | { readonly kind: \"refused\" };\n\nfunction record(value: unknown): Record<string, unknown> | null {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null;\n}\n\nfunction idText(value: unknown): string | null {\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return String(value);\n }\n return typeof value === \"string\" && value.trim() ? value.trim() : null;\n}\n\nfunction meIdentityOf(raw: unknown): MeIdentity | null {\n const outer = record(raw);\n if (!outer) return null;\n const root = record(outer[\"data\"]) ?? outer;\n const wrapped = record(root[\"me\"]) ?? record(root[\"user\"]);\n const user = record(wrapped?.[\"user\"]) ?? wrapped ?? root;\n const company = record(wrapped?.[\"company\"]) ?? record(root[\"company\"]);\n const userId = idText(user[\"legacy_id\"] ?? user[\"id\"]);\n const companyId = company\n ? idText(company[\"legacy_id\"] ?? company[\"id\"])\n : null;\n return userId && companyId ? { userId, companyId } : null;\n}\n\nasync function readMe(\n doFetch: typeof fetch,\n apiBase: string,\n token: string,\n timeoutMs: number,\n): Promise<MeRead> {\n let response: Response;\n const abort = new AbortController();\n const timer = setTimeout(() => abort.abort(), timeoutMs);\n try {\n response = await doFetch(\n `${apiBase}/api/v2026-10/me?include=company,legacy_ids`,\n {\n headers: {\n Authorization: `Bearer ${token}`,\n Accept: \"application/json\",\n },\n signal: abort.signal,\n },\n );\n } catch {\n clearTimeout(timer);\n return { kind: \"unavailable\" };\n }\n if (response.status >= 500 || response.status === 429) {\n clearTimeout(timer);\n return { kind: \"unavailable\" };\n }\n if (!response.ok) {\n clearTimeout(timer);\n return { kind: \"refused\" };\n }\n try {\n const me = meIdentityOf(await response.json());\n return me ? { kind: \"ok\", me } : { kind: \"refused\" };\n } catch {\n return abort.signal.aborted ? { kind: \"unavailable\" } : { kind: \"refused\" };\n } finally {\n clearTimeout(timer);\n }\n}\n\ntype Minted =\n | { readonly kind: \"ok\"; readonly code: string }\n | { readonly kind: \"not_targeted\" }\n | { readonly kind: \"refused\" }\n | { readonly kind: \"unavailable\" };\n\nasync function mintAdoptCode(\n doFetch: typeof fetch,\n apiBase: string,\n legacyToken: string,\n challenge: string,\n timeoutMs: number,\n): Promise<Minted> {\n let response: Response;\n const abort = new AbortController();\n const timer = setTimeout(() => abort.abort(), timeoutMs);\n try {\n response = await doFetch(`${apiBase}/api/identity/adopt_code`, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${legacyToken}`,\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n },\n body: JSON.stringify({\n code_challenge: challenge,\n code_challenge_method: \"S256\",\n }),\n signal: abort.signal,\n });\n } catch {\n clearTimeout(timer);\n return { kind: \"unavailable\" };\n }\n if (response.status === 404) {\n clearTimeout(timer);\n return { kind: \"not_targeted\" };\n }\n if (response.status >= 500 || response.status === 429) {\n clearTimeout(timer);\n return { kind: \"unavailable\" };\n }\n if (!response.ok) {\n clearTimeout(timer);\n return { kind: \"refused\" };\n }\n try {\n const code = record(await response.json())?.[\"code\"];\n return typeof code === \"string\" && code\n ? { kind: \"ok\", code }\n : { kind: \"refused\" };\n } catch {\n return abort.signal.aborted ? { kind: \"unavailable\" } : { kind: \"refused\" };\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * Trades `legacyToken` for an identity session held by `session`.\n *\n * Returns `adopted` once the session is stored and its user and company match\n * the legacy token's, as `/api/me` answers for each. A session that lands on\n * another user or company is signed out again and the trade is `refused`.\n * `not_targeted` means Rails does not offer adoption to this company;\n * `unavailable` means a network or server failure worth retrying later.\n */\nexport async function tradeLegacyToken(\n options: TradeLegacyTokenOptions,\n): Promise<TradeResult> {\n const doFetch = options.fetch ?? ((...args) => fetch(...args));\n const finish = (result: TradeResult): TradeResult => {\n options.log?.(\n result.outcome === \"refused\"\n ? `adopt outcome: refused (${result.reason})`\n : `adopt outcome: ${result.outcome}`,\n );\n return result;\n };\n\n if (options.session.facts() !== null) {\n return finish({ outcome: \"unavailable\" });\n }\n\n const timeoutMs = options.requestTimeoutMs ?? REQUEST_TIMEOUT_MS;\n const epoch = options.session.epoch();\n const verifier = createCodeVerifier(options.crypto);\n const challenge = await createCodeChallenge(verifier, options.crypto);\n const minted = await mintAdoptCode(\n doFetch,\n options.apiBase,\n options.legacyToken,\n challenge,\n timeoutMs,\n );\n if (minted.kind === \"not_targeted\")\n return finish({ outcome: \"not_targeted\" });\n if (minted.kind === \"unavailable\") return finish({ outcome: \"unavailable\" });\n if (minted.kind === \"refused\") {\n return finish({ outcome: \"refused\", reason: \"mint_refused\" });\n }\n\n try {\n await options.beforeRedeem?.();\n } catch {\n return finish({ outcome: \"unavailable\" });\n }\n\n return landAdoptCode({\n session: options.session,\n doFetch,\n apiBase: options.apiBase,\n legacyToken: options.legacyToken,\n code: minted.code,\n verifier,\n epoch,\n timeoutMs,\n finish,\n expectedCompanyId: null,\n beforeDiscard: options.beforeDiscard,\n });\n}\n\ninterface LandOptions {\n readonly session: NativeSession;\n readonly doFetch: typeof fetch;\n readonly apiBase: string;\n readonly legacyToken: string;\n readonly code: string;\n readonly verifier: string;\n readonly epoch: number;\n readonly timeoutMs: number;\n readonly finish: (result: TradeResult) => TradeResult;\n readonly expectedCompanyId: string | null;\n readonly beforeDiscard?: (() => void) | undefined;\n}\n\nasync function landAdoptCode(options: LandOptions): Promise<TradeResult> {\n const { session, doFetch, apiBase, legacyToken, timeoutMs, finish } = options;\n let adoptedSession: AdoptedSession;\n try {\n adoptedSession = await session.redeemAdopt({\n adoptCode: options.code,\n codeVerifier: options.verifier,\n epoch: options.epoch,\n });\n } catch (error) {\n if (\n error instanceof SessionError &&\n error.code !== \"temporarily_unavailable\" &&\n error.code !== \"not_signed_in\"\n ) {\n return finish({ outcome: \"refused\", reason: \"grant_refused\" });\n }\n return finish({ outcome: \"unavailable\" });\n }\n\n const discard = async (result: TradeResult): Promise<TradeResult> => {\n try {\n options.beforeDiscard?.();\n } catch {\n // A hook must not keep the session from being signed out.\n }\n await adoptedSession.discard().catch(() => undefined);\n return finish(result);\n };\n const [legacy, adopted] = await Promise.all([\n readMe(doFetch, apiBase, legacyToken, timeoutMs),\n session\n .getAccessToken()\n .then((token) => readMe(doFetch, apiBase, token, timeoutMs))\n .catch((): MeRead => ({ kind: \"unavailable\" })),\n ]);\n if (!adoptedSession.isCurrent()) return finish({ outcome: \"unavailable\" });\n if (legacy.kind === \"unavailable\" || adopted.kind === \"unavailable\") {\n return discard({ outcome: \"unavailable\" });\n }\n if (legacy.kind !== \"ok\" || adopted.kind !== \"ok\") {\n return discard({ outcome: \"refused\", reason: \"landing_unverifiable\" });\n }\n const wantedCompany = options.expectedCompanyId ?? legacy.me.companyId;\n if (\n legacy.me.userId !== adopted.me.userId ||\n wantedCompany !== adopted.me.companyId\n ) {\n return discard({ outcome: \"refused\", reason: \"landing_mismatch\" });\n }\n return finish({\n outcome: \"adopted\",\n facts: adoptedSession.facts,\n isCurrent: () => adoptedSession.isCurrent(),\n discard: () => adoptedSession.discard(),\n });\n}\n\nexport interface RedeemSwitchAdoptOptions {\n /** The `adopt.code` a company switch answered. */\n readonly code: string;\n /** The Fluid API origin that answered, for example `https://api.fluid.app`. */\n readonly apiBase: string;\n /** The bearer the switch was made with; it is only ever sent to `apiBase`. */\n readonly legacyToken: string;\n /** The company the switch targeted, as `/api/me` names it. */\n readonly targetCompanyId: string | number;\n readonly fetch?: typeof fetch;\n /** Receives one line naming the outcome; never a token, code or verifier. */\n readonly log?: (message: string) => void;\n readonly requestTimeoutMs?: number;\n}\n\nexport interface SwitchAdoptRequest {\n readonly codeChallenge: string;\n readonly codeChallengeMethod: \"S256\";\n /** Redeems the code the switch answered, once, for the target company. */\n readonly redeem: (options: RedeemSwitchAdoptOptions) => Promise<TradeResult>;\n}\n\n/**\n * Prepares the PKCE challenge a company switch sends as `adopt`, and the\n * redeem that lands the answered code. `redeem` reports `adopted` only when\n * the session names the legacy bearer's user in the target company; any other\n * landing is signed out again and `refused`.\n */\nexport async function createSwitchAdoptRequest(\n session: NativeSession,\n crypto?: PkceCrypto,\n): Promise<SwitchAdoptRequest> {\n const epoch = session.epoch();\n const verifier = createCodeVerifier(crypto);\n const codeChallenge = await createCodeChallenge(verifier, crypto);\n return {\n codeChallenge,\n codeChallengeMethod: \"S256\",\n redeem: async (options) => {\n const finish = (result: TradeResult): TradeResult => {\n options.log?.(\n result.outcome === \"refused\"\n ? `switch adopt outcome: refused (${result.reason})`\n : `switch adopt outcome: ${result.outcome}`,\n );\n return result;\n };\n if (session.facts() !== null) return finish({ outcome: \"unavailable\" });\n return landAdoptCode({\n session,\n doFetch: options.fetch ?? ((...args) => fetch(...args)),\n apiBase: options.apiBase,\n legacyToken: options.legacyToken,\n code: options.code,\n verifier,\n epoch,\n timeoutMs: options.requestTimeoutMs ?? REQUEST_TIMEOUT_MS,\n finish,\n expectedCompanyId: String(options.targetCompanyId),\n });\n },\n };\n}\n","/**\n * A pending-adopt marker: written once a legacy trade has minted an adopt\n * code and before it is redeemed, so a crash after the redeem leaves a\n * record that something may need revoking. It names the credential slot,\n * never a token.\n */\n\nexport const ADOPT_MARKER_GRACE_MS = 30_000;\n\nexport interface PendingAdoptMarker {\n readonly storageKey: string;\n readonly identityUrl?: string;\n readonly startedAt: number;\n readonly attemptCount?: number;\n}\n\n/** The marker as the text a file holds. */\nexport function serializeAdoptMarker(marker: PendingAdoptMarker): string {\n return JSON.stringify({\n storageKey: marker.storageKey,\n ...(marker.identityUrl ? { identityUrl: marker.identityUrl } : {}),\n startedAt: marker.startedAt,\n ...(marker.attemptCount ? { attemptCount: marker.attemptCount } : {}),\n });\n}\n\n/** The marker `text` holds, or null when it is not one. */\nexport function parseAdoptMarker(text: string): PendingAdoptMarker | null {\n try {\n const raw: unknown = JSON.parse(text);\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return null;\n const { storageKey, identityUrl, startedAt, attemptCount } = raw as Record<\n string,\n unknown\n >;\n if (typeof storageKey !== \"string\" || !storageKey) return null;\n if (typeof startedAt !== \"number\" || !Number.isFinite(startedAt)) {\n return null;\n }\n return {\n storageKey,\n startedAt,\n ...(typeof attemptCount === \"number\" && attemptCount > 0\n ? { attemptCount }\n : {}),\n ...(typeof identityUrl === \"string\" && identityUrl\n ? { identityUrl }\n : {}),\n };\n } catch {\n return null;\n }\n}\n\n/**\n * Whether `marker` is old enough that no live attempt can still own it.\n * The grace must outlast the attempt's deadline plus its cleanup.\n */\nexport function isStalePendingAdopt(\n marker: PendingAdoptMarker,\n now: number,\n graceMs: number = ADOPT_MARKER_GRACE_MS,\n): boolean {\n return now - marker.startedAt >= graceMs;\n}\n","/**\n * Which way a sign-in completes, as Rails decides it from the company flag\n * (Phase 007 INV-7.1). The CLI never decides it on its own.\n *\n * Mirrors apps/fluid-login: the email step answers every address the same\n * way, and a person whose company is flagged is emailed a sign-in link\n * instead of a code. When a code is confirmed, `confirm_mfa` answers\n * `sign_in_path: \"identity\"` once every company the code covered signs in\n * through the identity service, and hands out no token for them\n * (`Identity::LegacySignInGate`).\n */\n\nimport type { ConfirmMfaResponse } from \"../fluid-api.js\";\n\nexport type SignInPath = \"identity\" | \"legacy\";\n\n/**\n * The path a confirmed code puts the person on. A confirmation that kept any\n * company's legacy token stays on the legacy path: those companies are not\n * flagged, and their tokens are listed exactly as before.\n */\nexport function signInPathFor(confirmation: ConfirmMfaResponse): SignInPath {\n return confirmation.signInPath === \"identity\" ? \"identity\" : \"legacy\";\n}\n","/**\n * Email sign-ins started with `fluid login --send-code` and not finished yet.\n *\n * The send and finish steps run as separate processes, and the finish step\n * needs the server's id for the sign-in (`uuid`), which only the send step\n * saw. Keeping it here means an agent carries the emailed code alone. The\n * uuid cannot sign anyone in without that code.\n *\n * One record per address, so a new send replaces the last one. Records live\n * under the config dir (`~/.fluid/pending-logins/`), each named by a hash of\n * the address so the file names do not list who is signing in.\n */\n\nimport { createHash, randomBytes } from \"node:crypto\";\nimport {\n mkdirSync,\n readdirSync,\n readFileSync,\n renameSync,\n rmSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\nimport { getConfigDir } from \"../config/paths.js\";\n\nexport interface PendingLogin {\n readonly uuid: string;\n /** Normalised with `normaliseEmail`. */\n readonly email: string;\n /** The company the code was sent for; the finish step confirms it. */\n readonly shop: string;\n readonly expiresAt: string;\n /** The API the code was sent from; the finish step confirms against it. */\n readonly baseUrl: string;\n}\n\nexport interface PendingLoginStore {\n save(record: PendingLogin): void;\n load(email: string): PendingLogin | null;\n remove(email: string): void;\n}\n\n// A record this long past its expiry can never be finished, so the next\n// save removes it, along with any record it cannot read.\nconst STALE_AFTER_MS = 60 * 60 * 1000;\n\n/** The server compares addresses trimmed and lowercased; so does the store. */\nexport function normaliseEmail(email: string): string {\n return email.trim().toLowerCase();\n}\n\nfunction fileName(email: string): string {\n const hash = createHash(\"sha256\").update(normaliseEmail(email)).digest(\"hex\");\n return `${hash}.json`;\n}\n\nfunction isPendingLogin(value: unknown): value is PendingLogin {\n if (typeof value !== \"object\" || value === null) return false;\n const record = value as Record<string, unknown>;\n return (\n typeof record[\"uuid\"] === \"string\" &&\n typeof record[\"email\"] === \"string\" &&\n typeof record[\"shop\"] === \"string\" &&\n typeof record[\"expiresAt\"] === \"string\" &&\n typeof record[\"baseUrl\"] === \"string\"\n );\n}\n\nfunction readRecord(path: string): PendingLogin | null {\n try {\n const parsed: unknown = JSON.parse(readFileSync(path, \"utf8\"));\n return isPendingLogin(parsed) ? parsed : null;\n } catch {\n return null;\n }\n}\n\nfunction removeStale(dir: string, now: number): void {\n let names: string[];\n try {\n names = readdirSync(dir);\n } catch {\n return;\n }\n for (const name of names) {\n if (!name.endsWith(\".json\")) continue;\n const path = join(dir, name);\n const record = readRecord(path);\n const expiresAt = record ? Date.parse(record.expiresAt) : NaN;\n if (!record || !(expiresAt + STALE_AFTER_MS > now)) {\n rmSync(path, { force: true });\n }\n }\n}\n\n/**\n * The store, in `dir` or by default `<config dir>/pending-logins`, resolved\n * on each call so a changed `FLUID_CONFIG_DIR` is honoured.\n */\nexport function createPendingLoginStore(dir?: string): PendingLoginStore {\n const storeDir = () => dir ?? join(getConfigDir(), \"pending-logins\");\n\n return {\n save(record) {\n const base = storeDir();\n mkdirSync(base, { recursive: true, mode: 0o700 });\n removeStale(base, Date.now());\n\n // Written to a temp file and renamed over the record, as config.json\n // is, so a crash never leaves half a record and the 0o600 mode applies\n // to every write rather than only the first.\n const tmpPath = join(\n base,\n `.pending-${randomBytes(6).toString(\"hex\")}.tmp`,\n );\n try {\n writeFileSync(tmpPath, JSON.stringify(record, null, 2) + \"\\n\", {\n encoding: \"utf8\",\n mode: 0o600,\n });\n renameSync(tmpPath, join(base, fileName(record.email)));\n } catch (err) {\n try {\n unlinkSync(tmpPath);\n } catch {\n // The temp file may not exist yet.\n }\n throw err;\n }\n },\n\n load(email) {\n const record = readRecord(join(storeDir(), fileName(email)));\n return record && record.email === normaliseEmail(email) ? record : null;\n },\n\n remove(email) {\n rmSync(join(storeDir(), fileName(email)), { force: true });\n },\n };\n}\n","/**\n * Helpers for constructing stored auth profiles.\n */\n\nimport type { FluidProfile, IdentityProfileAuth } from \"../config/types.js\";\n\ninterface CreateFluidProfileInput {\n readonly name: string;\n readonly token: string;\n readonly companyName: string;\n readonly baseUrl: string;\n readonly storedAt?: string;\n}\n\nexport function createFluidProfile({\n name,\n token,\n companyName,\n baseUrl,\n storedAt,\n}: CreateFluidProfileInput): FluidProfile {\n return {\n name,\n token,\n companyName,\n storedAt: storedAt ?? new Date().toISOString(),\n baseUrl,\n };\n}\n\ninterface CreateIdentityProfileInput {\n readonly name: string;\n readonly companyName: string;\n readonly baseUrl: string;\n readonly auth: IdentityProfileAuth;\n readonly storedAt?: string;\n}\n\n/**\n * An identity-mode profile. It holds no token: the refresh token is in the\n * operating system credential store under `auth.storageKey`.\n */\nexport function createIdentityProfile({\n name,\n companyName,\n baseUrl,\n auth,\n storedAt,\n}: CreateIdentityProfileInput): FluidProfile {\n return {\n name,\n companyName,\n storedAt: storedAt ?? new Date().toISOString(),\n baseUrl,\n auth,\n };\n}\n","// Characters an email, shop or profile name can hold that are safe to paste\n// into a shell. No leading \"-\", which a command would read as a flag.\nconst SHELL_SAFE = /^[\\w@+][\\w.@+-]*$/;\n\n/**\n * The value for a printed command, or the placeholder when it holds\n * characters a shell would act on.\n */\nexport function shellSafe(value: string, placeholder: string): string {\n return SHELL_SAFE.test(value) ? value : placeholder;\n}\n","/**\n * `fluid login` for a company on the identity sign-in path: the browser,\n * a loopback redirect, and a session in the operating system credential\n * store. Reached only when Rails says so (see auth/identity/sign-in-path.ts):\n * a confirmed code answered `sign_in_path: \"identity\"`, or the person pasted\n * the sign-in link Rails emailed them instead of a code.\n *\n * It reports an outcome rather than printing one, so `fluid login` shows it\n * in text or `--json` like every other sign-in.\n */\n\nimport {\n getFluidApiBase,\n redeemIdentityLink,\n type validateToken,\n} from \"../auth/fluid-api.js\";\nimport {\n IDENTITY_ROOT_COMPANY_ID,\n resolveIdentityUrl,\n} from \"../auth/identity/environment.js\";\nimport { endUnusedSessions } from \"../auth/identity/profiles.js\";\nimport {\n describeIdentityError,\n identityToken,\n signInWithBrowser,\n signOutIdentity,\n} from \"../auth/identity/session.js\";\nimport { createIdentityProfile } from \"../auth/profiles.js\";\nimport { readConfig, updateConfig } from \"../config/config.js\";\nimport type { FluidConfig } from \"../config/types.js\";\nimport type { CliError } from \"../utils/errors.js\";\n\n/** The query parameter Rails puts the sign-in link's token in. */\nconst IDENTITY_LINK_PARAM = \"identityLink\";\n\n/** The roles the CLI's commands accept, as with a legacy `rep` session. */\nconst STAFF_ROLES = new Set([\"admin\", \"rep\", \"root_admin\"]);\n\n/**\n * The token in a pasted identity sign-in link, or null when the input is not\n * such a link.\n */\nexport function identityLinkToken(input: string): string | null {\n const trimmed = input.trim();\n if (!trimmed.includes(`${IDENTITY_LINK_PARAM}=`)) return null;\n try {\n const url = new URL(trimmed);\n return url.searchParams.get(IDENTITY_LINK_PARAM) || null;\n } catch {\n return null;\n }\n}\n\ninterface Spinner {\n succeed(text?: string): unknown;\n fail(text?: string): unknown;\n}\n\nexport interface IdentityLoginContext {\n /** `--name`: the profile to store, instead of the company's name. */\n readonly profileName?: string;\n /** The API base the sign-in started against. Defaults to the CLI's. */\n readonly apiBase?: string;\n /** The email the person typed; it only pre-fills the browser sign-in. */\n readonly loginHint?: string;\n /** The company (uuid_v7) the sign-in must land in. */\n readonly org?: string;\n /** Ask for credentials even when the browser holds a session. */\n readonly forceLogin?: boolean;\n /** Progress lines for the person, the sign-in URL among them. */\n readonly log: (line: string) => void;\n readonly spinner: (text: string) => Spinner;\n readonly validateToken: typeof validateToken;\n readonly redeemIdentityLink?: typeof redeemIdentityLink;\n /**\n * Called once a pasted link is spent or reported gone, never on a failure\n * that leaves it redeemable, so a caller tracking the sign-in can keep it\n * for a retry.\n */\n readonly onLinkSettled?: () => void;\n /** Whether an existing profile of this name may be replaced. */\n readonly decideOverwrite: (\n profileName: string,\n ) => Promise<\"replace\" | \"keep\" | \"refuse\">;\n}\n\nexport type IdentityLoginOutcome =\n | {\n readonly status: \"signed_in\";\n readonly profileName: string;\n readonly companyName: string;\n }\n | { readonly status: \"failed\"; readonly error: CliError }\n /** The person chose to keep the existing profile. */\n | { readonly status: \"kept\"; readonly profileName: string }\n /** An existing profile would be replaced and no one could be asked. */\n | { readonly status: \"refused\"; readonly profileName: string };\n\nfunction failed(code: string, message: string): IdentityLoginOutcome {\n return { status: \"failed\", error: { code, message } };\n}\n\n/**\n * What pins an identity sign-in to the account and company a sign-in\n * confirmed: the company, when known, and a fresh login so the browser's\n * existing session is not reused.\n */\nexport function pinnedIdentity(companyUuid?: string): {\n readonly org?: string;\n readonly forceLogin: true;\n} {\n return { ...(companyUuid ? { org: companyUuid } : {}), forceLogin: true };\n}\n\n/** Signs in through the identity service and stores the profile. */\nexport async function loginWithIdentity(\n context: IdentityLoginContext,\n): Promise<IdentityLoginOutcome> {\n const apiBase = context.apiBase ?? getFluidApiBase();\n let identityUrl: string | null;\n try {\n identityUrl = resolveIdentityUrl(apiBase);\n } catch (error) {\n return failed(\n \"IDENTITY_URL_INVALID\",\n error instanceof Error ? error.message : String(error),\n );\n }\n if (!identityUrl) {\n return failed(\n \"IDENTITY_URL_UNKNOWN\",\n `No Fluid identity service is known for ${apiBase}. Set FLUID_IDENTITY_URL to sign in.`,\n );\n }\n\n context.log(\"Your company signs in through Fluid's identity service.\");\n let signIn: Awaited<ReturnType<typeof signInWithBrowser>>;\n try {\n signIn = await signInWithBrowser({\n identityUrl,\n log: context.log,\n loginHint: context.loginHint,\n org: context.org,\n prompt: context.forceLogin ? \"login\" : undefined,\n });\n } catch (error) {\n return failed(\"IDENTITY_SIGN_IN_FAILED\", describeIdentityError(error));\n }\n\n if (\n context.org &&\n signIn.facts.companyId &&\n signIn.facts.companyId !== context.org\n ) {\n await signOutIdentity(signIn.auth).catch(() => undefined);\n return failed(\n \"IDENTITY_COMPANY_MISMATCH\",\n \"The browser signed in to a different company than the sign-in link was for. Sign out of the browser's Fluid session and try again.\",\n );\n }\n\n // The CLI's commands take an admin or rep session, never a shopper's.\n if (!signIn.facts.roles.some((role) => STAFF_ROLES.has(role))) {\n await signOutIdentity(signIn.auth).catch(() => undefined);\n return failed(\n \"SHOPPER_SESSION\",\n \"This account does not sign in as an admin or rep, so it cannot sign in to the CLI.\",\n );\n }\n\n const companyless = !signIn.facts.companyId;\n if (companyless && !signIn.facts.roles.includes(\"root_admin\")) {\n await signOutIdentity(signIn.auth).catch(() => undefined);\n return failed(\n \"IDENTITY_NO_COMPANY\",\n \"This sign-in is not in a company. Run `fluid login --shop <company>` to sign in to one.\",\n );\n }\n if (companyless && signIn.recovered && !context.org && !signIn.pickedOrg) {\n await signOutIdentity(signIn.auth).catch(() => undefined);\n return failed(\n \"IDENTITY_SIGN_IN_FAILED\",\n \"The sign-in finished without knowing which company you picked. Run `fluid login` again.\",\n );\n }\n const rootFallback = companyless && !context.org && !signIn.pickedOrg;\n const org = companyless\n ? (context.org ?? signIn.pickedOrg ?? IDENTITY_ROOT_COMPANY_ID)\n : undefined;\n const auth = org ? { ...signIn.auth, org } : signIn.auth;\n\n let accessToken = signIn.accessToken;\n if (org) {\n try {\n accessToken = (await identityToken(auth, org)).accessToken;\n } catch (error) {\n await signOutIdentity(signIn.auth).catch(() => undefined);\n return failed(\n \"IDENTITY_COMPANY_EXCHANGE_FAILED\",\n `Could not sign in to the company: ${describeIdentityError(error)}`,\n );\n }\n }\n\n // The company's display name; the session itself knows only its id.\n const spinner = context.spinner(\"Loading your company...\");\n // Asked of the API the sign-in started against, never the environment's.\n const company = rootFallback\n ? null\n : await context.validateToken(accessToken, { baseUrl: apiBase });\n const companyName = rootFallback\n ? \"Fluid\"\n : company?.success\n ? company.value.name\n : (org ?? signIn.facts.companyId ?? \"Fluid\");\n spinner.succeed(`Signed in to ${companyName}`);\n\n const profileName = context.profileName ?? companyName;\n const decision = await context.decideOverwrite(profileName);\n if (decision !== \"replace\") {\n await signOutIdentity(signIn.auth).catch(() => undefined);\n return decision === \"keep\"\n ? { status: \"kept\", profileName }\n : { status: \"refused\", profileName };\n }\n\n let before: FluidConfig;\n let after: FluidConfig;\n try {\n before = readConfig();\n after = updateConfig((config) => ({\n ...config,\n activeProfile: profileName,\n profiles: {\n ...config.profiles,\n [profileName]: createIdentityProfile({\n name: profileName,\n companyName,\n baseUrl: apiBase,\n auth,\n }),\n },\n }));\n } catch (error) {\n await signOutIdentity(signIn.auth).catch(() => undefined);\n throw error;\n }\n // A profile this one replaced may have been the last user of its session.\n for (const problem of await endUnusedSessions(before, after)) {\n context.log(problem);\n }\n\n return { status: \"signed_in\", profileName, companyName };\n}\n\n/**\n * Redeems a pasted sign-in link with Rails, which confirms the person's\n * company signs in through the identity service, then signs in.\n */\nexport async function loginWithIdentityLink(\n token: string,\n context: IdentityLoginContext,\n): Promise<IdentityLoginOutcome> {\n const spinner = context.spinner(\"Checking the sign-in link...\");\n const redemption = await (context.redeemIdentityLink ?? redeemIdentityLink)(\n token,\n { baseUrl: context.apiBase },\n );\n if (!redemption.success) {\n spinner.fail(redemption.error.message);\n // Only a link Rails reports as gone is settled; any other failure may\n // not have spent it, so the caller keeps what it needs to retry.\n if (redemption.error.code === \"LINK_GONE\") context.onLinkSettled?.();\n return { status: \"failed\", error: redemption.error };\n }\n context.onLinkSettled?.();\n spinner.succeed(\"Sign-in link accepted\");\n return loginWithIdentity({\n ...context,\n ...pinnedIdentity(redemption.value.companyUuid),\n });\n}\n","/**\n * fluid login — authenticate via email MFA or API token\n *\n * Besides the interactive sign-in, an email sign-in can run in two steps\n * with no terminal, for an agent: `--send-code` emails the code and saves\n * the server's sign-in id (auth/pending-login.ts), then `--code` redeems\n * it. `--send-code` requires `--shop`, which ties the code to one company:\n * only such a code lets an admin's sign-in confirm a new signup.\n *\n * A company on the identity sign-in path is emailed a link instead of a\n * code, and Rails may answer a confirmed code with `sign_in_path:\n * \"identity\"`. Either way the sign-in continues through the browser\n * (commands/login-identity.ts); the CLI never picks the path itself.\n */\n\nimport { text as readAll } from \"node:stream/consumers\";\nimport { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport prompts from \"prompts\";\nimport ora from \"ora\";\nimport {\n validateToken,\n sendMfa,\n confirmMfa,\n getFluidApiBase,\n type redeemIdentityLink,\n type CompanyChoice,\n type FluidApiError,\n} from \"../auth/fluid-api.js\";\nimport { endUnusedSessions } from \"../auth/identity/profiles.js\";\nimport { signInPathFor } from \"../auth/identity/sign-in-path.js\";\nimport {\n createPendingLoginStore,\n normaliseEmail,\n type PendingLoginStore,\n} from \"../auth/pending-login.js\";\nimport { createFluidProfile } from \"../auth/profiles.js\";\nimport { updateConfig, readConfig } from \"../config/config.js\";\nimport type { FluidProfile } from \"../config/types.js\";\nimport type { CliError } from \"../utils/errors.js\";\nimport { shellSafe } from \"../utils/shell.js\";\nimport {\n identityLinkToken,\n loginWithIdentity,\n pinnedIdentity,\n loginWithIdentityLink,\n type IdentityLoginContext,\n type IdentityLoginOutcome,\n} from \"./login-identity.js\";\n\nexport interface LoginOptions {\n readonly token?: string;\n readonly email?: string;\n readonly name?: string;\n readonly shop?: string;\n readonly sendCode?: boolean;\n /**\n * `true` for a bare `--code`, which reads FLUID_LOGIN_CODE; `\"-\"` reads\n * stdin; anything else is the code itself.\n */\n readonly code?: string | boolean;\n readonly yes?: boolean;\n readonly json?: boolean;\n}\n\ninterface Spinner {\n succeed(text?: string): unknown;\n fail(text?: string): unknown;\n}\n\n/**\n * Everything `runLogin` reaches outside itself, so a test can stand in for\n * the API, the prompts, the terminal and the console without loading\n * commander or reloading this module.\n */\nexport interface LoginDeps {\n readonly api: {\n readonly validateToken: typeof validateToken;\n readonly sendMfa: typeof sendMfa;\n readonly confirmMfa: typeof confirmMfa;\n /** Defaults to the real redemption when a caller does not stand one in. */\n readonly redeemIdentityLink?: typeof redeemIdentityLink;\n };\n readonly prompt: (\n question: prompts.PromptObject,\n ) => Promise<prompts.Answers<string>>;\n readonly spinner: (text: string) => Spinner;\n /** stdout: results, and in text mode every message. */\n readonly log: (line: string) => void;\n /** stderr: warnings that must not mix into `--json` output. */\n readonly err: (line: string) => void;\n readonly env: NodeJS.ProcessEnv;\n /**\n * Whether a person can answer a prompt. `prompts` reads stdin, and on a\n * closed stdin (an agent's subprocess) it never settles, so node exits 0\n * having done nothing.\n */\n readonly isInteractive: () => boolean;\n readonly readStdin: () => Promise<string>;\n readonly pending: PendingLoginStore;\n}\n\nexport const defaultLoginDeps: LoginDeps = {\n api: { validateToken, sendMfa, confirmMfa },\n prompt: (question) => prompts(question),\n spinner: (text) => ora(text).start(),\n log: (line) => console.log(line),\n err: (line) => console.error(line),\n env: process.env,\n isInteractive: () => Boolean(process.stdin.isTTY),\n readStdin: () => readAll(process.stdin),\n pending: createPendingLoginStore(),\n};\n\nconst SILENT_SPINNER: Spinner = { succeed: () => {}, fail: () => {} };\n\nconst TWO_STEP_HINT =\n \"Sign in in two steps instead:\\n\" +\n \" fluid login --send-code --email <email> --shop <shop>\\n\" +\n \" fluid login --code --email <email> --yes\\n\" +\n \"with the emailed code in FLUID_LOGIN_CODE (or --code - to read it from stdin). \" +\n \"--yes replaces a profile with the company's name; --name <profile> picks another. Or set FLUID_TOKEN.\";\n\n/** Output for one run: spinners and text, or a single JSON object. */\ninterface Ui {\n readonly json: boolean;\n spinner(text: string): Spinner;\n /** Print the run's JSON result; text mode prints its own lines. */\n result(payload: Record<string, unknown>): void;\n /** Report a failure and return the exit code. */\n fail(error: CliError, spinner?: Spinner): number;\n}\n\nfunction createUi(json: boolean, deps: LoginDeps): Ui {\n return {\n json,\n spinner: (text) => (json ? SILENT_SPINNER : deps.spinner(text)),\n result: (payload) => {\n if (json) deps.log(JSON.stringify(payload, null, 2));\n },\n fail: (error, spinner) => {\n if (json) {\n deps.log(\n JSON.stringify(\n {\n status: \"error\",\n code: error.code,\n message: error.message,\n ...(error.details ? { details: error.details } : {}),\n },\n null,\n 2,\n ),\n );\n return 1;\n }\n if (spinner) spinner.fail(chalk.red(error.message));\n else deps.log(chalk.red(error.message));\n if (error.details) deps.log(chalk.dim(error.details));\n return 1;\n },\n };\n}\n\n/** The shop option for an API call, or no argument at all without one. */\nfunction shopArgs(shop: string | undefined): [] | [{ fluidShop: string }] {\n return shop ? [{ fluidShop: shop }] : [];\n}\n\n/** The part of a shop the server matches on: \"acme\" in \"acme.fluid.app\". */\nfunction shopLabel(shop: string): string {\n return (shop.trim().toLowerCase().split(\".\")[0] ?? \"\").trim();\n}\n\nfunction findByShop(\n companies: readonly CompanyChoice[],\n shop: string,\n): CompanyChoice | undefined {\n return companies.find((c) => shopLabel(c.shopName) === shopLabel(shop));\n}\n\n/**\n * Whether the entry's token is an admin or rep session, the only kind the\n * CLI's commands accept. A shopper's code returns a \"member\" or \"customer\"\n * token instead. The server types every entry, so one with no type is\n * refused rather than stored.\n */\nfunction isStaffSession(company: CompanyChoice): boolean {\n return company.authType === \"rep\";\n}\n\nfunction shopperSession(email: string, company: CompanyChoice): CliError {\n return {\n code: \"SHOPPER_SESSION\",\n message: `${email} does not sign in at ${company.shopName} as an admin or rep, so it cannot sign in to the CLI.`,\n };\n}\n\ninterface OverwriteOptions {\n readonly yes: boolean;\n readonly interactive: boolean;\n}\n\n/**\n * What to do about profile `profileName` before writing it: replace it when\n * it is new or with `--yes`, ask in a terminal, and refuse otherwise, since\n * no one could answer the question.\n */\nfunction overwriteRule(\n profileName: string,\n opts: OverwriteOptions,\n): \"replace\" | \"ask\" | \"refuse\" {\n if (!readConfig().profiles[profileName] || opts.yes) return \"replace\";\n return opts.interactive ? \"ask\" : \"refuse\";\n}\n\nasync function overwriteDecision(\n profileName: string,\n opts: OverwriteOptions,\n deps: LoginDeps,\n): Promise<\"replace\" | \"keep\" | \"refuse\"> {\n const rule = overwriteRule(profileName, opts);\n if (rule !== \"ask\") return rule;\n\n const existing = readConfig().profiles[profileName];\n const response = await deps.prompt({\n type: \"confirm\",\n name: \"overwrite\",\n message: `Profile \"${profileName}\" already exists (${existing?.companyName}). Overwrite?`,\n initial: false,\n });\n return response[\"overwrite\"] ? \"replace\" : \"keep\";\n}\n\nfunction isLegacyProfile(profile: FluidProfile | undefined): boolean {\n return (\n profile !== undefined &&\n !profile.auth &&\n typeof profile.token === \"string\" &&\n profile.token !== \"\"\n );\n}\n\nfunction profileExists(profileName: string, codeUsed: boolean): CliError {\n return {\n code: \"PROFILE_EXISTS\",\n message:\n `Profile \"${profileName}\" already exists. Pass --yes to replace it` +\n (codeUsed ? \"; the code is used, so send a new one first.\" : \".\"),\n };\n}\n\nasync function storeProfile(\n deps: LoginDeps,\n profileName: string,\n token: string,\n companyName: string,\n baseUrl: string = getFluidApiBase(),\n): Promise<void> {\n const before = readConfig();\n const after = updateConfig((config) => ({\n ...config,\n activeProfile: profileName,\n profiles: {\n ...config.profiles,\n [profileName]: createFluidProfile({\n name: profileName,\n token,\n companyName,\n baseUrl,\n }),\n },\n }));\n // Replacing an identity-mode profile ends its session if nothing else\n // uses it, so no refresh token is left behind in the credential store.\n for (const problem of await endUnusedSessions(before, after)) {\n deps.err(chalk.yellow(problem));\n }\n}\n\nfunction loggedIn(\n ui: Ui,\n deps: LoginDeps,\n profileName: string,\n company: {\n readonly name: string;\n readonly id?: number;\n readonly shop?: string;\n },\n): number {\n ui.result({ status: \"signed_in\", profile: profileName, company });\n if (!ui.json) {\n deps.log(\n chalk.green(\n `Logged in as ${chalk.bold(company.name)} (profile: ${chalk.bold(profileName)})`,\n ),\n );\n }\n return 0;\n}\n\nfunction cancelled(deps: LoginDeps): number {\n deps.log(chalk.yellow(\"Login cancelled — existing profile not overwritten.\"));\n return 0;\n}\n\n/**\n * What the identity sign-in needs from this run: its output, its overwrite\n * rule, and the API base the sign-in started against. With `--json` the\n * person still needs the sign-in URL, so progress goes to stderr.\n */\nfunction identityContext(\n opts: LoginOptions,\n interactive: boolean,\n ui: Ui,\n deps: LoginDeps,\n apiBase?: string,\n): IdentityLoginContext {\n return {\n profileName: opts.name,\n apiBase,\n log: (line) =>\n ui.json\n ? deps.err(line)\n : deps.log(line.startsWith(\"http\") ? line : chalk.cyan(line)),\n spinner: (text) => ui.spinner(text),\n // Every request of this sign-in goes to `apiBase` when it has one: a\n // two-step sign-in's is the API its code was sent from.\n validateToken: (token, options) =>\n deps.api.validateToken(token, { baseUrl: apiBase, ...options }),\n redeemIdentityLink: deps.api.redeemIdentityLink,\n decideOverwrite: (profileName) => {\n if (isLegacyProfile(readConfig().profiles[profileName])) {\n const notice = `Replaced legacy profile \"${profileName}\" with a One Auth sign-in.`;\n if (ui.json) deps.err(notice);\n else deps.log(chalk.dim(notice));\n return Promise.resolve(\"replace\");\n }\n return overwriteDecision(\n profileName,\n { yes: Boolean(opts.yes), interactive },\n deps,\n );\n },\n };\n}\n\nfunction identityResult(\n outcome: IdentityLoginOutcome,\n ui: Ui,\n deps: LoginDeps,\n): number {\n switch (outcome.status) {\n case \"signed_in\":\n return loggedIn(ui, deps, outcome.profileName, {\n name: outcome.companyName,\n });\n case \"kept\":\n return cancelled(deps);\n case \"refused\":\n return ui.fail(profileExists(outcome.profileName, false));\n case \"failed\":\n return ui.fail(outcome.error);\n }\n}\n\nconst LINK_HINT =\n \"If the email has a sign-in link instead of a code, paste the link here.\";\n\nasync function loginWithToken(\n token: string,\n opts: LoginOptions,\n interactive: boolean,\n ui: Ui,\n deps: LoginDeps,\n): Promise<number> {\n const spinner = ui.spinner(\"Validating token...\");\n const result = await deps.api.validateToken(token);\n\n if (!result.success) return ui.fail(result.error, spinner);\n\n const name = opts.name ?? result.value.name;\n\n // Stop spinner before potential interactive prompt to avoid terminal corruption\n spinner.succeed(\n chalk.green(`Token valid — ${chalk.bold(result.value.name)}`),\n );\n\n const decision = await overwriteDecision(\n name,\n { yes: Boolean(opts.yes), interactive },\n deps,\n );\n if (decision === \"refuse\") return ui.fail(profileExists(name, false));\n if (decision === \"keep\") return cancelled(deps);\n\n await storeProfile(deps, name, token, result.value.name);\n return loggedIn(ui, deps, name, { name: result.value.name });\n}\n\nasync function loginWithEmail(\n opts: LoginOptions,\n ui: Ui,\n deps: LoginDeps,\n): Promise<number> {\n // 1. Prompt for email\n let email = opts.email;\n if (!email) {\n const response = await deps.prompt({\n type: \"text\",\n name: \"email\",\n message: \"Enter your email\",\n });\n email = response[\"email\"] as string | undefined;\n if (!email) {\n deps.log(chalk.red(\"No email provided. Aborting.\"));\n return 1;\n }\n }\n\n // 2. Send MFA code\n const sendSpinner = ui.spinner(\"Sending verification code...\");\n const sendResult = await deps.api.sendMfa(\n email,\n opts.shop\n ? { fluidShop: opts.shop, identityHint: true }\n : { identityHint: true },\n );\n\n if (!sendResult.success) return ui.fail(sendResult.error, sendSpinner);\n\n if (sendResult.value.signInPath === \"identity\") {\n if (opts.shop && !sendResult.value.companyUuid) {\n return ui.fail(\n {\n code: \"SHOP_NOT_RESOLVED\",\n message: `Could not resolve ${opts.shop} for browser sign-in. Run \"fluid login\" without --shop and pick the shop in the browser.`,\n },\n sendSpinner,\n );\n }\n sendSpinner.succeed(\"Opening your browser to sign in\");\n return identityResult(\n await loginWithIdentity({\n ...identityContext(opts, true, ui, deps),\n ...(opts.shop ? pinnedIdentity(sendResult.value.companyUuid) : {}),\n loginHint: normaliseEmail(email),\n }),\n ui,\n deps,\n );\n }\n\n sendSpinner.succeed(\n `Verification code sent — check your email (${expiryNote(sendResult.value.expiresAt)})`,\n );\n if (!ui.json) deps.log(chalk.dim(LINK_HINT));\n\n // 3. Prompt for verification code (retry up to 3 times on invalid code)\n const MAX_CODE_ATTEMPTS = 3;\n let confirmResult;\n for (let attempt = 1; attempt <= MAX_CODE_ATTEMPTS; attempt++) {\n const codeResponse = await deps.prompt({\n type: \"text\",\n name: \"code\",\n message: \"Enter the 6-digit code\",\n });\n const code = codeResponse[\"code\"] as string | undefined;\n if (!code) {\n deps.log(chalk.red(\"No code provided. Aborting.\"));\n return 1;\n }\n // A flagged company's person is emailed a link, not a code.\n const linkToken = identityLinkToken(code);\n if (linkToken) {\n return identityResult(\n await loginWithIdentityLink(linkToken, {\n ...identityContext(opts, true, ui, deps),\n loginHint: normaliseEmail(email),\n }),\n ui,\n deps,\n );\n }\n if (!/^\\d{6}$/.test(code)) {\n deps.log(chalk.red(\"Code must be exactly 6 digits.\"));\n if (attempt < MAX_CODE_ATTEMPTS) continue;\n deps.log(chalk.red(\"Too many invalid attempts. Aborting.\"));\n return 1;\n }\n\n const confirmSpinner = ui.spinner(\"Verifying code...\");\n confirmResult = await deps.api.confirmMfa(\n sendResult.value.uuid,\n code,\n ...shopArgs(opts.shop),\n );\n\n if (confirmResult.success) {\n confirmSpinner.succeed(\"Verified\");\n break;\n }\n\n // Retryable: wrong code, still have attempts left\n if (\n confirmResult.error.code === \"INVALID_CODE\" &&\n attempt < MAX_CODE_ATTEMPTS\n ) {\n confirmSpinner.fail(\n chalk.red(\n `${confirmResult.error.message} (attempt ${attempt}/${MAX_CODE_ATTEMPTS})`,\n ),\n );\n continue;\n }\n\n // Non-retryable (expired, unreachable, etc.) or final attempt. The server\n // refuses a sign-in it cannot finish with a code as it refuses a wrong\n // code, so the last refusal names those reasons too.\n if (confirmResult.error.code === \"INVALID_CODE\") {\n return ui.fail(\n {\n ...confirmResult.error,\n message: `${confirmResult.error.message}. If the code was right, the shop or the address may be wrong, or the company may sign in with an emailed link. Run fluid login again to start over.`,\n },\n confirmSpinner,\n );\n }\n // This flow keeps no challenge, so a restored contact needs a new code.\n if (confirmResult.error.code === \"CONTACT_MISSING\") {\n return ui.fail(\n {\n ...confirmResult.error,\n message: `${confirmResult.error.message}, then run fluid login again.`,\n },\n confirmSpinner,\n );\n }\n return ui.fail(confirmResult.error, confirmSpinner);\n }\n\n if (!confirmResult?.success) return 0;\n\n // Every company the code covered signs in through the identity service,\n // so Rails handed out no token (Phase 007 INV-7.5).\n if (signInPathFor(confirmResult.value) === \"identity\") {\n return identityResult(\n await loginWithIdentity({\n ...identityContext(opts, true, ui, deps),\n loginHint: normaliseEmail(email),\n ...pinnedIdentity(confirmResult.value.companyUuid),\n }),\n ui,\n deps,\n );\n }\n\n const { companies } = confirmResult.value;\n\n if (companies.length === 0) {\n deps.log(chalk.red(\"No companies found for this account.\"));\n return 1;\n }\n\n // 4. Select company (auto-select if only one, or the one --shop names)\n const named = opts.shop ? findByShop(companies, opts.shop) : undefined;\n let selected: CompanyChoice;\n if (named) {\n selected = named;\n } else if (companies.length === 1) {\n const first = companies[0];\n if (!first) {\n deps.log(chalk.red(\"No companies found for this account.\"));\n return 1;\n }\n selected = first;\n } else {\n // Key on `c.id`, not the array index, and resolve via `.find` —\n // `prompts` autocomplete returns the raw typed string on Enter when\n // the user hasn't arrow-key-highlighted a filtered choice, so an\n // array-index lookup ends up asking for `companies[\"Fluid\"]` and\n // failing with \"Invalid selection\". Same shape as `switch.ts`.\n const companyChoices = companies.map((c) => ({\n title: `${c.name} (${c.shopName})`,\n value: c.id,\n }));\n\n const selectResponse = await deps.prompt({\n type: \"autocomplete\",\n name: \"companyId\",\n message: \"Select a company (type to search)\",\n choices: companyChoices,\n suggest: (input, choices) =>\n Promise.resolve(\n input\n ? choices.filter((c) =>\n c.title.toLowerCase().includes(input.toLowerCase()),\n )\n : choices,\n ),\n });\n\n const companyId = selectResponse[\"companyId\"] as number | undefined;\n\n if (companyId === undefined) {\n deps.log(chalk.red(\"No company selected. Aborting.\"));\n return 1;\n }\n const choice = companies.find((c) => c.id === companyId);\n if (!choice) {\n deps.log(chalk.red(\"Invalid selection. Aborting.\"));\n return 1;\n }\n selected = choice;\n }\n\n if (!isStaffSession(selected)) {\n return ui.fail(shopperSession(email, selected));\n }\n\n // 5. Store profile\n const name = opts.name ?? selected.name;\n\n const decision = await overwriteDecision(\n name,\n { yes: Boolean(opts.yes), interactive: true },\n deps,\n );\n if (decision !== \"replace\") return cancelled(deps);\n\n await storeProfile(deps, name, selected.jwt, selected.name);\n return loggedIn(ui, deps, name, { name: selected.name });\n}\n\nfunction expiryNote(expiresAtIso: string): string {\n const expiresInMs = new Date(expiresAtIso).getTime() - Date.now();\n const expiresInMin = Math.round(expiresInMs / 1000 / 60);\n return expiresInMin > 0\n ? `expires in ~${expiresInMin} min`\n : \"code may expire soon — check your email quickly\";\n}\n\n/**\n * The command that finishes this sign-in, for a person or agent to run.\n * Values with characters a shell would act on are left as placeholders.\n */\nfunction finishCommand(email: string, shop: string): string {\n return `fluid login --code --email ${shellSafe(email, \"<email>\")} --shop ${shellSafe(shop, \"<shop>\")}`;\n}\n\n/** `fluid login --send-code`: email a code, save the sign-in, exit. */\nasync function sendCodeStep(\n opts: LoginOptions,\n ui: Ui,\n deps: LoginDeps,\n): Promise<number> {\n if (!opts.email) {\n return ui.fail({\n code: \"EMAIL_REQUIRED\",\n message: \"--send-code needs --email <address>.\",\n });\n }\n // A code sent without a shop is tied to the person, not to a company, so\n // finishing it signs in without confirming a new company's signup.\n if (!opts.shop) {\n return ui.fail({\n code: \"SHOP_REQUIRED\",\n message:\n \"--send-code needs --shop <shop>, the company to sign in to (acme or acme.fluid.app). For a new signup, `fluid signup` prints it as fluidShop.\",\n });\n }\n const email = normaliseEmail(opts.email);\n const shop = opts.shop;\n\n const spinner = ui.spinner(\"Sending verification code...\");\n const sent = await deps.api.sendMfa(email, ...shopArgs(shop));\n if (!sent.success) return ui.fail(sent.error, spinner);\n\n deps.pending.save({\n uuid: sent.value.uuid,\n email,\n shop,\n expiresAt: sent.value.expiresAt,\n baseUrl: getFluidApiBase(),\n });\n\n // The server answers the same whether or not the address can sign in\n // there, so this cannot promise that a code was sent.\n spinner.succeed(\n `If ${email} can sign in at ${shop}, a code is on its way (${expiryNote(sent.value.expiresAt)})`,\n );\n ui.result({\n status: \"code_sent\",\n email,\n shop,\n expiresAt: sent.value.expiresAt,\n });\n if (!ui.json) {\n deps.log(`Finish with: ${finishCommand(email, shop)}`);\n deps.log(\n chalk.dim(\n \"with the code in FLUID_LOGIN_CODE, or add - after --code to read it from stdin. \" +\n \"If the email has a sign-in link instead of a code, pass the link the same way. \" +\n \"With no terminal, add --yes to replace a profile with the company's name, or --name <profile>.\",\n ),\n );\n }\n return 0;\n}\n\n/**\n * The code for the finish step. A bare `--code` reads FLUID_LOGIN_CODE,\n * `--code -` reads stdin, and any other value is the code. Stdin is read\n * only when asked for: an agent's stdin may be a pipe that never closes,\n * and reading it uninvited would wait forever.\n */\nasync function readCode(\n opts: LoginOptions,\n deps: LoginDeps,\n): Promise<string | undefined> {\n if (opts.code === \"-\") {\n return (await deps.readStdin()).trim() || undefined;\n }\n if (typeof opts.code === \"string\") {\n deps.err(\n chalk.yellow(\n \"Warning: a code passed via --code is visible in shell history and process listings. \" +\n \"Prefer FLUID_LOGIN_CODE, or --code - to read it from stdin.\",\n ),\n );\n return opts.code.trim();\n }\n return deps.env[\"FLUID_LOGIN_CODE\"]?.trim() || undefined;\n}\n\n/** The server's answer for a code that cannot finish, by error code. */\nfunction finishError(error: FluidApiError, shop: string): CliError {\n // The server answers a sign-in it cannot finish with a code exactly as it\n // answers a wrong code, so the reasons are listed here together.\n if (error.code === \"INVALID_CODE\") {\n return {\n code: error.code,\n message:\n `${error.message}. If the code is right, the shop \"${shop}\" may be wrong, ` +\n \"the address may not be an admin or rep there, or the company may sign in with an emailed link instead. \" +\n \"If it does, pass that link to --code in place of the code. Five wrong codes lock this sign-in. \" +\n \"If no code arrived, run --send-code again.\",\n };\n }\n if (error.code === \"SIGN_IN_UNFINISHED\") {\n return {\n code: error.code,\n message: `${error.message} (shop \"${shop}\"): run --send-code again.`,\n };\n }\n // The saved sign-in is kept, so the same code finishes it later.\n if (error.code === \"CONTACT_MISSING\") {\n return {\n code: error.code,\n message: `${error.message}, then run --code again with the same code.`,\n };\n }\n return error;\n}\n\n/** `fluid login --code`: redeem the code for the saved sign-in. */\nasync function finishStep(\n opts: LoginOptions,\n interactive: boolean,\n ui: Ui,\n deps: LoginDeps,\n): Promise<number> {\n if (!opts.email) {\n return ui.fail({\n code: \"EMAIL_REQUIRED\",\n message: \"--code needs --email <address>, the one used with --send-code.\",\n });\n }\n // Without a terminal no one can answer \"replace the profile?\", and the\n // profile's name (the company's) is known only once the code is spent.\n // Asking for the choice now means the code is never spent on a refusal.\n if (!interactive && !opts.yes && !opts.name) {\n return ui.fail({\n code: \"YES_OR_NAME_REQUIRED\",\n message:\n \"With no terminal, --code needs --yes, to replace a profile with the company's name, or --name <profile>.\",\n });\n }\n const email = normaliseEmail(opts.email);\n\n const record = deps.pending.load(email);\n if (!record) {\n return ui.fail({\n code: \"NO_PENDING_LOGIN\",\n message: `No sign-in is waiting for ${email}. Run fluid login --send-code --email ${email} first.`,\n });\n }\n // The code is tied to the shop it was sent for, so that is the one\n // confirmed; a --shop here only has to agree with it.\n const { shop } = record;\n if (opts.shop && shopLabel(opts.shop) !== shopLabel(shop)) {\n return ui.fail({\n code: \"SHOP_MISMATCH\",\n message: `The code for ${email} was sent for ${shop}, not ${opts.shop}.`,\n });\n }\n\n if (!(Date.parse(record.expiresAt) > Date.now())) {\n deps.pending.remove(email);\n return ui.fail({\n code: \"CODE_EXPIRED\",\n message: `The code for ${email} has expired. Run fluid login --send-code again.`,\n });\n }\n\n const code = await readCode(opts, deps);\n if (!code) {\n return ui.fail({\n code: \"NO_CODE\",\n message:\n \"No code given. Put it in FLUID_LOGIN_CODE, pass --code - to read it from stdin, or pass it to --code.\",\n });\n }\n // A flagged company's person is emailed a link, not a code: redeeming it\n // finishes this sign-in through the identity service instead.\n const linkToken = identityLinkToken(code);\n if (!linkToken && !/^\\d{6}$/.test(code)) {\n return ui.fail({\n code: \"INVALID_CODE_FORMAT\",\n message: \"The code must be exactly 6 digits.\",\n });\n }\n\n // Confirming a code, or redeeming a link, uses it up, so a named profile\n // that would be refused is checked first. Without a terminal, the check\n // above has already required --yes or --name. A link signs in through\n // One Auth, which replaces a legacy profile without asking.\n const overwrite = { yes: Boolean(opts.yes), interactive };\n if (\n opts.name &&\n !(linkToken && isLegacyProfile(readConfig().profiles[opts.name])) &&\n overwriteRule(opts.name, overwrite) === \"refuse\"\n ) {\n return ui.fail(profileExists(opts.name, false));\n }\n\n if (linkToken) {\n return identityResult(\n await loginWithIdentityLink(linkToken, {\n ...identityContext(opts, interactive, ui, deps, record.baseUrl),\n loginHint: normaliseEmail(email),\n // The pending sign-in ends only once the link is spent or gone; a\n // failure that may not have spent it keeps it for a retry.\n onLinkSettled: () => deps.pending.remove(email),\n }),\n ui,\n deps,\n );\n }\n\n const spinner = ui.spinner(\"Verifying code...\");\n const confirmed = await deps.api.confirmMfa(record.uuid, code, {\n fluidShop: shop,\n baseUrl: record.baseUrl,\n });\n if (!confirmed.success) {\n // A wrong code may be retried. A rate limit or an unreachable server\n // may not have spent it, so the sign-in is kept for one more try; if\n // the code was spent after all, that try is refused as a wrong code (a\n // 410 on servers before ENG-2877, which ends the sign-in). A\n // missing contact leaves the code unspent, so it works again once the\n // contact is restored. Anything else ends this sign-in now.\n const retryable = [\n \"INVALID_CODE\",\n \"RATE_LIMITED\",\n \"API_UNREACHABLE\",\n \"CONTACT_MISSING\",\n ];\n if (!retryable.includes(confirmed.error.code)) deps.pending.remove(email);\n return ui.fail(finishError(confirmed.error, shop), spinner);\n }\n spinner.succeed(\"Verified\");\n deps.pending.remove(email);\n\n // Rails handed out no token: every company the code covered signs in\n // through the identity service (Phase 007 INV-7.5).\n if (signInPathFor(confirmed.value) === \"identity\") {\n return identityResult(\n await loginWithIdentity({\n ...identityContext(opts, interactive, ui, deps, record.baseUrl),\n loginHint: normaliseEmail(email),\n ...pinnedIdentity(confirmed.value.companyUuid),\n }),\n ui,\n deps,\n );\n }\n\n const { companies } = confirmed.value;\n const selected = findByShop(companies, shop);\n if (!selected) {\n if (companies.length === 0) {\n return ui.fail({\n code: \"NO_COMPANIES\",\n message: \"No companies found for this account.\",\n });\n }\n const shops = companies.map((c) => c.shopName).join(\", \");\n return ui.fail({\n code: \"SHOP_NOT_FOUND\",\n message: `This account has no company at ${shop}. It has: ${shops}.`,\n });\n }\n\n if (!isStaffSession(selected)) {\n return ui.fail(shopperSession(email, selected));\n }\n\n const name = opts.name ?? selected.name;\n const decision = await overwriteDecision(name, overwrite, deps);\n if (decision === \"refuse\") return ui.fail(profileExists(name, true));\n if (decision === \"keep\") return cancelled(deps);\n\n await storeProfile(deps, name, selected.jwt, selected.name, record.baseUrl);\n return loggedIn(ui, deps, name, {\n id: selected.id,\n name: selected.name,\n shop: selected.shopName,\n });\n}\n\n/**\n * Run `fluid login` and return its exit code.\n */\nexport async function runLogin(\n opts: LoginOptions,\n deps: LoginDeps = defaultLoginDeps,\n): Promise<number> {\n const json = Boolean(opts.json);\n const ui = createUi(json, deps);\n // `--json` is for a program reading the output, which cannot answer a\n // prompt either. Nor can a run that reads the code from stdin with\n // `--code -`: stdin has ended by the time a prompt would read it.\n const interactive = deps.isInteractive() && !json && opts.code !== \"-\";\n\n if (opts.sendCode || opts.code !== undefined) {\n if (opts.token) {\n return ui.fail({\n code: \"FLAG_CONFLICT\",\n message: \"--token cannot be combined with --send-code or --code.\",\n });\n }\n if (opts.sendCode && opts.code !== undefined) {\n return ui.fail({\n code: \"FLAG_CONFLICT\",\n message: \"Run --send-code and --code as two separate commands.\",\n });\n }\n // FLUID_TOKEN is left alone here: an agent may have one exported from\n // an earlier sign-in, and these flags ask for an email sign-in.\n return opts.sendCode\n ? sendCodeStep(opts, ui, deps)\n : finishStep(opts, interactive, ui, deps);\n }\n\n // Accept token from env var to avoid shell history / process listing exposure\n const token = opts.token ?? deps.env[\"FLUID_TOKEN\"];\n if (token) {\n if (opts.token) {\n (json ? deps.err : deps.log)(\n chalk.yellow(\n \"Warning: token passed via --token flag is visible in shell history and process listings. \" +\n \"Prefer the FLUID_TOKEN environment variable.\",\n ),\n );\n }\n return loginWithToken(token, opts, interactive, ui, deps);\n }\n\n if (!interactive) {\n const why = json\n ? \"fluid login --json cannot ask for the email and code.\"\n : \"fluid login needs a terminal to ask for the email and code.\";\n return ui.fail({\n code: \"NOT_INTERACTIVE\",\n message: `${why}\\n${TWO_STEP_HINT}`,\n });\n }\n return loginWithEmail(opts, ui, deps);\n}\n\n/**\n * The `login` command, running `run` with the parsed options. Built by a\n * function so a test can check the flag parsing without signing in.\n */\nexport function buildLoginCommand(\n run: (opts: LoginOptions) => Promise<number> = (opts) => runLogin(opts),\n): Command {\n return new Command(\"login\")\n .description(\"Authenticate with the Fluid API\")\n .option(\n \"-t, --token <token>\",\n \"API token (skips email flow). Prefer FLUID_TOKEN env var to avoid shell history exposure\",\n )\n .option(\n \"-e, --email <email>\",\n \"Email address for MFA login (required with --send-code and --code)\",\n )\n .option(\"-n, --name <name>\", \"Profile name (defaults to company name)\")\n .option(\n \"--shop <shop>\",\n \"Sign in to this company (e.g. acme or acme.fluid.app); required with --send-code. An admin's emailed code also confirms a new signup\",\n )\n .option(\n \"--send-code\",\n \"Email a sign-in code and exit, for use without a terminal; finish with --code\",\n )\n .option(\n \"--code [code]\",\n \"Finish a sign-in started with --send-code. Reads the code from FLUID_LOGIN_CODE, or from stdin with --code -; a code given here is visible in shell history\",\n )\n .option(\"-y, --yes\", \"Replace an existing profile without asking\")\n .option(\"--json\", \"Print the result as JSON\")\n .action(async (opts: LoginOptions) => {\n const exitCode = await run(opts);\n if (exitCode !== 0) process.exitCode = exitCode;\n });\n}\n\nexport const loginCommand = buildLoginCommand();\n","/**\n * fluid signup — create a Fluid company with the public signup endpoint\n *\n * Runs before any sign-in, so it calls `POST /api/company` directly rather\n * than through a profile's client. The person behind the email then\n * confirms the signup, by the emailed link or by signing in with the two\n * `fluid login` steps this command prints.\n */\n\nimport { chmodSync, mkdirSync, mkdtempSync, writeFileSync } from \"node:fs\";\nimport { randomUUID } from \"node:crypto\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\nimport prompts from \"prompts\";\nimport {\n getFluidApiBase,\n isInsecureRemoteBase,\n pollAgentAccess,\n signup,\n type AgentAccessPoll,\n type AgentAccessRequestHandle,\n type SignupError,\n type SignupRequest,\n} from \"../auth/fluid-api.js\";\nimport type { ClientProfileInput } from \"../auth/identity/client.js\";\nimport { readConfig, readStoredConfig } from \"../config/config.js\";\nimport { isStrictConfig } from \"../config/strict.js\";\nimport { resolveIdentityUrl } from \"../auth/identity/environment.js\";\nimport { normaliseEmail } from \"../auth/pending-login.js\";\nimport { shellSafe } from \"../utils/shell.js\";\nimport { getConfigDir } from \"../config/paths.js\";\n\nexport interface SignupOptions {\n readonly email?: string;\n readonly firstName?: string;\n readonly lastName?: string;\n readonly companyName?: string;\n readonly subdomain?: string;\n readonly color?: string;\n readonly yes?: boolean;\n readonly json?: boolean;\n /** `true` for the default agent name, or the name given. */\n readonly agentAccess?: string | boolean;\n}\n\nconst AGENT_NAME_MAX = 100;\nconst DEFAULT_AGENT_NAME = \"Fluid CLI agent\";\nconst MIN_POLL_SECONDS = 5;\nconst MAX_BACKOFF_SECONDS = 60;\nconst ISSUING_GRACE_MS = 20 * 60 * 1000;\n\ninterface Spinner {\n stop(): unknown;\n}\n\n/** Everything `runSignup` reaches outside itself, for tests. */\nexport interface SignupDeps {\n readonly api: { readonly signup: typeof signup };\n readonly prompt: (\n question: prompts.PromptObject,\n ) => Promise<prompts.Answers<string>>;\n /** Shown in text mode while the signup runs, which can take a while. */\n readonly spinner: (text: string) => Spinner;\n readonly log: (line: string) => void;\n /** Progress for a person while `--json` keeps stdout to one document. */\n readonly notice: (line: string) => void;\n readonly isInteractive: () => boolean;\n readonly agent: {\n readonly poll: (handle: string) => Promise<AgentAccessPoll>;\n readonly saveProfile: (\n name: string,\n input: ClientProfileInput,\n options: { readonly replace: boolean },\n ) => Promise<unknown>;\n readonly strictConfig: () => boolean;\n /** Writes text to a private file and returns its path; throws if no location works. */\n readonly stashRecovery: (text: string) => string;\n readonly stderrIsTty: () => boolean;\n readonly platform: () => string;\n readonly sleep: (ms: number) => Promise<void>;\n readonly now: () => number;\n readonly apiBase: () => string;\n readonly identityUrl: (apiBase: string) => string | null;\n readonly profileExists: (name: string) => boolean;\n readonly profileVisible: (name: string) => boolean;\n };\n}\n\nexport const defaultSignupDeps: SignupDeps = {\n api: { signup },\n prompt: (question) => prompts(question),\n spinner: (text) => ora(text).start(),\n log: (line) => console.log(line),\n notice: (line) => console.error(line),\n isInteractive: () => Boolean(process.stdin.isTTY),\n agent: {\n poll: pollAgentAccess,\n saveProfile: async (name, input, options) =>\n (await import(\"../auth/identity/client.js\")).saveClientProfile(\n name,\n input,\n options,\n ),\n strictConfig: isStrictConfig,\n stashRecovery: writeRecoveryFile,\n stderrIsTty: () => Boolean(process.stderr.isTTY),\n platform: () => process.platform,\n sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),\n now: Date.now,\n apiBase: getFluidApiBase,\n identityUrl: (apiBase) => resolveIdentityUrl(apiBase),\n profileExists: (name) => Boolean(readStoredConfig().profiles[name]),\n profileVisible: (name) => Boolean(readConfig().profiles[name]),\n },\n};\n\n// The same DNS-label rule the server validates a new subdomain against.\nconst SUBDOMAIN_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\nconst COLOR_PATTERN = /^(?:[a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/;\nconst EMAIL_PATTERN = /^[^\\s@]+@[^\\s@]+$/;\n\n/**\n * The subdomain as the server would store it: lowercase, letters, digits\n * and hyphens only, at most 63 characters, no hyphen at either end. The\n * server checks \"is taken\" against the value as sent, before it cleans it\n * up, so sending the clean form keeps that check meaningful.\n */\nexport function normaliseSubdomain(raw: string): string {\n const trimmed = (value: string) => value.replace(/^-+|-+$/g, \"\");\n return trimmed(\n trimmed(raw.toLowerCase())\n .replace(/[^a-z0-9-]/g, \"\")\n .slice(0, 63),\n );\n}\n\n/**\n * The two commands that sign in to the new company and confirm it. The\n * second names its own profile rather than passing `--yes`, which would\n * replace an existing profile that happens to share the company's name.\n * If a profile with that name exists, login refuses `--name` before the code\n * is spent when there is no terminal, and asks first at one.\n */\nexport function nextCommands(\n email: string,\n fluidShop: string,\n subdomain: string,\n): string[] {\n const safeEmail = shellSafe(email, \"<email>\");\n const safeShop = shellSafe(fluidShop, \"<shop>\");\n return [\n `fluid login --send-code --email ${safeEmail} --shop ${safeShop}`,\n `fluid login --code --email ${safeEmail} --shop ${safeShop} --name ${shellSafe(subdomain, \"<profile>\")}`,\n ];\n}\n\nconst REQUIRED_FLAGS: ReadonlyArray<[keyof SignupOptions, string]> = [\n [\"email\", \"--email\"],\n [\"firstName\", \"--first-name\"],\n [\"lastName\", \"--last-name\"],\n [\"companyName\", \"--company-name\"],\n [\"subdomain\", \"--subdomain\"],\n];\n\n/** The request to send, or why the flags can't make one. */\nfunction buildRequest(\n opts: SignupOptions,\n): { request: SignupRequest } | { error: SignupError } {\n const missing = REQUIRED_FLAGS.filter(([key]) => {\n const value = opts[key];\n return typeof value !== \"string\" || value.trim() === \"\";\n }).map(([, flag]) => flag);\n if (missing.length > 0) {\n return {\n error: {\n code: \"FLAGS_REQUIRED\",\n message: `fluid signup needs ${missing.join(\", \")}.`,\n },\n };\n }\n\n const email = normaliseEmail(opts.email ?? \"\");\n if (!EMAIL_PATTERN.test(email)) {\n return {\n error: {\n code: \"INVALID_EMAIL\",\n message: `${email} is not an email address.`,\n },\n };\n }\n\n const subdomain = normaliseSubdomain(opts.subdomain ?? \"\");\n if (!SUBDOMAIN_PATTERN.test(subdomain)) {\n return {\n error: {\n code: \"INVALID_SUBDOMAIN\",\n message:\n \"--subdomain needs at least one letter or digit; it may also hold hyphens, up to 63 characters.\",\n },\n };\n }\n\n const agentName =\n typeof opts.agentAccess === \"string\" ? opts.agentAccess.trim() : \"\";\n if ([...agentName].length > AGENT_NAME_MAX) {\n return {\n error: {\n code: \"AGENT_NAME_INVALID\",\n message: `The --agent-access name can be at most ${AGENT_NAME_MAX} characters.`,\n },\n };\n }\n\n const color = opts.color?.trim().replace(/^#/, \"\");\n if (color !== undefined && !COLOR_PATTERN.test(color)) {\n return {\n error: {\n code: \"INVALID_COLOR\",\n message: \"--color must be a 3- or 6-digit hex colour, such as 0C7CF6.\",\n },\n };\n }\n\n return {\n request: {\n email,\n firstName: (opts.firstName ?? \"\").trim(),\n lastName: (opts.lastName ?? \"\").trim(),\n companyName: (opts.companyName ?? \"\").trim(),\n subdomain,\n ...(color ? { color } : {}),\n ...(opts.agentAccess\n ? {\n agentAccess: {\n name: agentName || DEFAULT_AGENT_NAME,\n },\n }\n : {}),\n },\n };\n}\n\ninterface AgentTarget {\n readonly profileName: string;\n readonly apiBase: string;\n readonly identityUrl: string;\n}\n\ntype AgentOutcome =\n | { readonly stored: string }\n | { readonly failed: SignupError };\n\n/**\n * Waits for the signup's agent-access request to be approved and stores the\n * credential it delivers. Polls no faster than Fluid allows, stops on a final\n * answer or when the request expires, and saves the credential exactly once:\n * a delivered secret is never shown again, and a second poll revokes it.\n */\nasync function awaitAgentCredential(\n access: AgentAccessRequestHandle,\n target: AgentTarget,\n companyName: string,\n yes: boolean,\n deps: SignupDeps,\n): Promise<AgentOutcome> {\n const { agent } = deps;\n const { profileName, apiBase, identityUrl } = target;\n const giveUpAt = Date.parse(access.expiresAt) + ISSUING_GRACE_MS;\n let wait = MIN_POLL_SECONDS;\n let failures = 0;\n for (;;) {\n if (Number.isFinite(giveUpAt) && agent.now() >= giveUpAt) {\n return agentFailure(\"AGENT_ACCESS_EXPIRED\");\n }\n await agent.sleep(wait * 1000);\n const answer = await agent.poll(access.handle);\n wait = MIN_POLL_SECONDS;\n switch (answer.state) {\n case \"pending\":\n case \"issuing_soon\":\n case \"slow_down\":\n failures = 0;\n wait = Math.max(answer.retryAfter ?? 0, MIN_POLL_SECONDS);\n break;\n case \"retry\":\n failures += 1;\n wait = Math.max(\n answer.retryAfter ?? 0,\n Math.min(MIN_POLL_SECONDS * 2 ** failures, MAX_BACKOFF_SECONDS),\n );\n break;\n case \"denied\":\n return agentFailure(\"AGENT_ACCESS_DENIED\");\n case \"expired\":\n return agentFailure(\"AGENT_ACCESS_EXPIRED\");\n case \"revoked\":\n return agentFailure(\"AGENT_ACCESS_REVOKED\");\n case \"unavailable\":\n return agentFailure(\"AGENT_ACCESS_UNAVAILABLE\");\n case \"delivered\": {\n try {\n await agent.saveProfile(\n profileName,\n {\n clientId: answer.clientId,\n clientSecret: answer.clientSecret,\n org: access.companyUuid,\n identityUrl,\n companyName,\n baseUrl: apiBase,\n },\n { replace: yes },\n );\n if (!agent.profileVisible(profileName)) {\n throw new Error(\n \"the saved profile is not visible to this process (strict config)\",\n );\n }\n } catch (error) {\n const report = reportUnstored(\n agent,\n answer,\n access.companyUuid,\n identityUrl,\n errorText(error),\n );\n let summary = report.summary;\n try {\n deps.notice(report.stderr);\n } catch {\n summary = report.ifSilent;\n }\n return agentFailure(\n \"AGENT_ACCESS_NOT_STORED\",\n errorText(error),\n summary,\n );\n }\n return { stored: profileName };\n }\n }\n }\n}\n\n/**\n * Writes `content` to a new mode-0600 file in the CLI config dir, or, if that\n * fails, in a fresh 0700 temp dir. Returns the path; throws if both fail.\n */\nexport function writeRecoveryFile(content: string): string {\n const name = `agent-access-recovery-${randomUUID()}.txt`;\n const write = (dir: string): string => {\n const file = join(dir, name);\n writeFileSync(file, content, { mode: 0o600, flag: \"wx\" });\n chmodSync(file, 0o600);\n return file;\n };\n try {\n const dir = getConfigDir();\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n return write(dir);\n } catch {\n return write(mkdtempSync(join(tmpdir(), \"fluid-agent-access-\")));\n }\n}\n\nfunction credentialDetails(\n delivered: { readonly clientId: string; readonly clientSecret: string },\n org: string,\n identityUrl: string,\n): string {\n return [\n `client_id: ${delivered.clientId}`,\n `client_secret: ${delivered.clientSecret}`,\n `organization: ${org}`,\n `token endpoint: ${identityUrl.replace(/\\/$/, \"\")}/token (HTTP Basic client_credentials, resource=${org})`,\n ].join(\"\\n\");\n}\n\nconst NOT_STORED = \"The credential was issued but could not be stored.\";\n\nfunction revokeText(clientId: string): string {\n 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.`;\n}\n\n/**\n * What a failed save reports. `stderr` is the text to print and `summary` is the matching message for the\n * error, so neither claims more than the branch taken. The secret goes to a\n * private file with only its path printed; without a file (always on win32)\n * it is printed only when stderr is a terminal.\n */\nfunction reportUnstored(\n agent: SignupDeps[\"agent\"],\n delivered: { readonly clientId: string; readonly clientSecret: string },\n org: string,\n identityUrl: string,\n reason: string,\n): {\n readonly stderr: string;\n readonly summary: string;\n readonly ifSilent: string;\n} {\n const head = `The agent's credential was issued but not stored (${reason}). Fluid shows it once.`;\n const details = credentialDetails(delivered, org, identityUrl);\n if (agent.platform() !== \"win32\") {\n try {\n const file = agent.stashRecovery(details);\n return {\n 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.`,\n summary: `${NOT_STORED} Its details, including the secret, were written to ${file} (readable only by you); stderr names the file.`,\n ifSilent: `${NOT_STORED} Its details, including the secret, were written to ${file} (readable only by you); reporting that on stderr failed.`,\n };\n } catch {\n // Fall through to the terminal or the revoke instructions.\n }\n }\n if (agent.stderrIsTty()) {\n return {\n stderr: `${head} No private file could be written, so here it is; keep it now:\\n${details}`,\n summary: `${NOT_STORED} No private file could be written, so the details, including the secret, were printed to stderr.`,\n ifSilent: `${NOT_STORED} No private file could be written and printing to stderr failed, so the secret was not emitted anywhere. ${revokeText(delivered.clientId)}`,\n };\n }\n 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)}`;\n return { stderr: summary, summary, ifSilent: summary };\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nconst AGENT_FAILURES: Record<string, string> = {\n AGENT_ACCESS_DENIED: \"An administrator denied the agent's access request.\",\n AGENT_ACCESS_EXPIRED:\n \"The agent's access request expired before it was approved. Run signup again with a different subdomain to ask anew.\",\n AGENT_ACCESS_REVOKED:\n \"The agent's credential was already delivered, so Fluid revoked it. Run signup again with a different subdomain to ask anew.\",\n AGENT_ACCESS_UNAVAILABLE:\n \"Fluid cannot issue the agent a credential for this company right now.\",\n AGENT_ACCESS_NOT_STORED: NOT_STORED,\n};\n\nfunction agentFailure(\n code: string,\n details?: string,\n message?: string,\n): AgentOutcome {\n return {\n failed: {\n code,\n message: message ?? AGENT_FAILURES[code] ?? code,\n ...(details ? { details } : {}),\n },\n };\n}\n\n// A plain CliError fits too: every field SignupError adds is optional.\nfunction printFailure(\n error: SignupError,\n json: boolean,\n deps: SignupDeps,\n): number {\n if (json) {\n deps.log(\n JSON.stringify(\n {\n status: \"error\",\n code: error.code,\n message: error.message,\n ...(error.status !== undefined ? { httpStatus: error.status } : {}),\n ...(error.errors ? { errors: error.errors } : {}),\n ...(error.retryAfter !== undefined\n ? { retryAfter: error.retryAfter }\n : {}),\n ...(error.details ? { details: error.details } : {}),\n },\n null,\n 2,\n ),\n );\n return 1;\n }\n deps.log(chalk.red(error.message));\n if (error.errors) deps.log(chalk.dim(JSON.stringify(error.errors)));\n if (error.retryAfter !== undefined) {\n deps.log(chalk.dim(`Retry after ${error.retryAfter} seconds.`));\n }\n if (error.details) deps.log(chalk.dim(error.details));\n return 1;\n}\n\n/**\n * Run `fluid signup` and return its exit code.\n */\nexport async function runSignup(\n opts: SignupOptions,\n deps: SignupDeps = defaultSignupDeps,\n): Promise<number> {\n const json = Boolean(opts.json);\n const built = buildRequest(opts);\n if (\"error\" in built) return printFailure(built.error, json, deps);\n const { request } = built;\n let target: AgentTarget | undefined;\n if (request.agentAccess) {\n if (deps.agent.strictConfig()) {\n return printFailure(\n {\n code: \"AGENT_ACCESS_STRICT_CONFIG\",\n message:\n \"--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.\",\n },\n json,\n deps,\n );\n }\n const apiBase = deps.agent.apiBase();\n if (isInsecureRemoteBase(apiBase)) {\n return printFailure(\n {\n code: \"AGENT_ACCESS_INSECURE_BASE\",\n message:\n \"--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.\",\n },\n json,\n deps,\n );\n }\n const identityUrl = deps.agent.identityUrl(apiBase);\n if (!identityUrl) {\n return printFailure(\n {\n code: \"AGENT_ACCESS_NO_IDENTITY\",\n message:\n \"--agent-access needs an identity service, and this API base has none. Set FLUID_IDENTITY_URL or drop --agent-access.\",\n },\n json,\n deps,\n );\n }\n const profileName = `${request.subdomain}-agent`;\n if (deps.agent.profileExists(profileName) && !opts.yes) {\n return printFailure(\n {\n code: \"PROFILE_EXISTS\",\n message: `Profile \"${profileName}\" already exists. Pass --yes to replace it.`,\n },\n json,\n deps,\n );\n }\n target = { profileName, apiBase, identityUrl };\n }\n\n if (!opts.yes) {\n const question = `Create ${request.companyName} at subdomain ${request.subdomain}, and email ${request.email} to confirm it?`;\n // `--json` is for a program reading the output, which cannot answer a\n // prompt, and a closed stdin never answers one either.\n if (json || !deps.isInteractive()) {\n return printFailure(\n {\n code: \"CONFIRM_REQUIRED\",\n message: `${question} Pass --yes to confirm.`,\n },\n json,\n deps,\n );\n }\n const answer = await deps.prompt({\n type: \"confirm\",\n name: \"ok\",\n message: question,\n initial: false,\n });\n if (!answer[\"ok\"]) {\n return printFailure(\n { code: \"CANCELLED\", message: \"Cancelled.\" },\n json,\n deps,\n );\n }\n }\n\n const spinner = json ? undefined : deps.spinner(\"Signing up...\");\n const result = await deps.api.signup(request);\n spinner?.stop();\n if (!result.success) return printFailure(result.error, json, deps);\n\n const created = result.value;\n const next = nextCommands(\n request.email,\n created.company.fluidShop,\n created.company.subdomain,\n );\n if (json) {\n const base = {\n status: \"signed_up\",\n company: created.company,\n userCompany: created.userCompany,\n currentlyDue: created.currentlyDue,\n next,\n };\n if (!created.agentAccess || !target) {\n deps.log(JSON.stringify(base, null, 2));\n return 0;\n }\n const { approvalUrl, expiresAt } = created.agentAccess;\n deps.notice(\n `Waiting for an administrator to approve the agent at ${approvalUrl} (until ${expiresAt}).`,\n );\n const outcome = await awaitAgentCredential(\n created.agentAccess,\n target,\n created.company.name,\n Boolean(opts.yes),\n deps,\n );\n const agentAccess =\n \"failed\" in outcome\n ? {\n approvalUrl,\n expiresAt,\n status: \"error\",\n code: outcome.failed.code,\n message: outcome.failed.message,\n ...(outcome.failed.details\n ? { details: outcome.failed.details }\n : {}),\n }\n : {\n approvalUrl,\n expiresAt,\n status: \"stored\",\n profile: outcome.stored,\n };\n deps.log(JSON.stringify({ ...base, agentAccess }, null, 2));\n return \"failed\" in outcome ? 1 : 0;\n }\n\n deps.log(\n chalk.green(\n `Signed up ${created.company.name} as ${created.company.fluidShop} (company ${created.company.id}).`,\n ),\n );\n if (request.subdomain !== (opts.subdomain ?? \"\").trim()) {\n deps.log(chalk.dim(`Subdomain sent as ${request.subdomain}.`));\n }\n deps.log(\n `${request.email} confirms it from the emailed link, or by signing in with the emailed code:`,\n );\n for (const command of next) deps.log(` ${command}`);\n deps.log(\n chalk.dim(\n \"A repeat signup for the same email within an hour normally sends no new email.\",\n ),\n );\n if (!created.agentAccess || !target) return 0;\n\n deps.log(\n `An administrator approves the agent at ${created.agentAccess.approvalUrl} (after confirming the signup). Waiting for approval until ${created.agentAccess.expiresAt}...`,\n );\n const outcome = await awaitAgentCredential(\n created.agentAccess,\n target,\n created.company.name,\n Boolean(opts.yes),\n deps,\n );\n if (\"failed\" in outcome) return printFailure(outcome.failed, false, deps);\n deps.log(\n chalk.green(\n `Approved. The agent's credential is saved as profile ${outcome.stored}.`,\n ),\n );\n return 0;\n}\n\n/**\n * The `signup` command, running `run` with the parsed options. Built by a\n * function so a test can check the flag parsing without signing up.\n */\nexport function buildSignupCommand(\n run: (opts: SignupOptions) => Promise<number> = (opts) => runSignup(opts),\n): Command {\n return new Command(\"signup\")\n .description(\n \"Create a Fluid company with the public signup; the person behind --email confirms it\",\n )\n .option(\n \"-e, --email <email>\",\n \"The person's email address; Fluid emails it to confirm the signup\",\n )\n .option(\"--first-name <name>\", \"The person's first name\")\n .option(\"--last-name <name>\", \"The person's last name\")\n .option(\"--company-name <name>\", \"The company's name\")\n .option(\n \"--subdomain <subdomain>\",\n \"The store's subdomain (acme gives acme.fluid.app); sent lowercase, letters, digits and hyphens only\",\n )\n .option(\n \"--color <hex>\",\n \"Brand colour as 3 or 6 hex digits, such as 0C7CF6\",\n )\n .option(\n \"--agent-access [name]\",\n \"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)\",\n )\n .option(\"-y, --yes\", \"Sign up without asking\")\n .option(\"--json\", \"Print the result as JSON\")\n .action(async (opts: SignupOptions) => {\n const exitCode = await run(opts);\n if (exitCode !== 0) process.exitCode = exitCode;\n });\n}\n\nexport const signupCommand = buildSignupCommand();\n","/**\n * fluid logout — remove stored auth profile(s)\n *\n * An identity-mode profile's session is revoked at the identity service and\n * its refresh token deleted from the credential store, once no remaining\n * profile uses it. (The identity service's `/signout` is a browser\n * navigation; a native client revokes its refresh token instead.)\n */\n\nimport { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport { endUnusedSessions } from \"../auth/identity/profiles.js\";\nimport { readConfig, writeConfig } from \"../config/config.js\";\nimport { withConfigLock } from \"../config/lock.js\";\nimport type { FluidConfig } from \"../config/types.js\";\n\nexport const logoutCommand = new Command(\"logout\")\n .description(\"Remove stored authentication\")\n .option(\"-a, --all\", \"Remove all profiles\")\n .action(async (opts: { all?: boolean }) => {\n let before: FluidConfig | undefined;\n let after: FluidConfig | undefined;\n withConfigLock(() => {\n const config = readConfig();\n if (opts.all) {\n before = config;\n after = { ...config, activeProfile: null, profiles: {} };\n } else if (config.activeProfile) {\n before = config;\n const { [config.activeProfile]: _, ...remainingProfiles } =\n config.profiles;\n after = {\n ...config,\n activeProfile: Object.keys(remainingProfiles)[0] ?? null,\n profiles: remainingProfiles,\n };\n }\n if (after) writeConfig(after);\n });\n\n if (!before || !after) {\n console.log(chalk.yellow(\"Not currently logged in.\"));\n return;\n }\n\n for (const problem of await endUnusedSessions(before, after)) {\n console.log(chalk.yellow(problem));\n }\n\n if (opts.all) {\n console.log(chalk.green(\"All profiles removed.\"));\n return;\n }\n\n console.log(\n chalk.green(`Logged out of profile ${chalk.bold(before.activeProfile)}.`),\n );\n if (after.activeProfile) {\n console.log(chalk.dim(`Switched to profile ${after.activeProfile}.`));\n }\n });\n","/**\n * fluid profiles — list stored auth profiles. Never prints a secret: a\n * client profile shows its client id and company, and the secret stays in the\n * operating system credential store.\n */\n\nimport { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport { readConfig } from \"../config/config.js\";\nimport type { FluidProfile } from \"../config/types.js\";\n\nfunction modeOf(profile: FluidProfile): string {\n return profile.auth?.mode ?? \"token\";\n}\n\nexport const profilesCommand = new Command(\"profiles\")\n .description(\"List stored profiles\")\n .action(() => {\n const config = readConfig();\n const profiles = Object.values(config.profiles);\n if (profiles.length === 0) {\n console.log(chalk.yellow(\"No profiles stored. Run `fluid login` first.\"));\n return;\n }\n for (const profile of profiles) {\n const active = profile.name === config.activeProfile ? \" (active)\" : \"\";\n console.log(`${chalk.bold(profile.name)}${active}`);\n console.log(` Mode: ${modeOf(profile)}`);\n console.log(` Company: ${profile.companyName}`);\n if (profile.auth?.mode === \"client\") {\n console.log(` Client: ${profile.auth.clientId}`);\n console.log(` Org: ${profile.auth.org}`);\n }\n }\n });\n","/**\n * fluid whoami — show current auth profile and validate against API\n *\n * An identity-mode profile is shown from its identity session: the facts\n * come from the identity service's `/userinfo`, never from decoding a token.\n */\n\nimport { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\nimport { clientAccessToken } from \"../auth/identity/client.js\";\nimport {\n type CredentialSourceDescription,\n describeCredentialSource,\n getActiveProfile,\n resolveCredentialSource,\n} from \"../auth/token.js\";\nimport { validateToken } from \"../auth/fluid-api.js\";\nimport {\n describeIdentityError,\n identityToken,\n} from \"../auth/identity/session.js\";\nimport {\n type ClientProfile,\n type IdentityProfile,\n isClientProfile,\n isIdentityProfile,\n} from \"../config/types.js\";\n\nfunction sourceLabel(source: CredentialSourceDescription): string {\n if (source.envVar) return source.envVar;\n if (source.origin === \"fluidrc\")\n return `.fluidrc profile ${source.profileName}`;\n if (source.origin === \"explicit\") return `profile ${source.profileName}`;\n return `config.json profile ${source.profileName}`;\n}\n\nfunction printSource(source: CredentialSourceDescription): void {\n console.log(` Source: ${chalk.bold(sourceLabel(source))}`);\n console.log(` Mode: ${source.mode}`);\n}\n\nasync function whoamiIdentity(\n profile: IdentityProfile,\n source: CredentialSourceDescription,\n): Promise<void> {\n const spinner = ora(\"Checking your identity session...\").start();\n let facts;\n try {\n ({ facts } = await identityToken(profile.auth));\n } catch (error) {\n spinner.fail(chalk.red(describeIdentityError(error)));\n console.log(chalk.dim(`Profile: ${profile.name}`));\n process.exitCode = 1;\n return;\n }\n\n spinner.succeed(chalk.green(\"Authenticated (Fluid identity service)\"));\n console.log(` Profile: ${chalk.bold(profile.name)}`);\n printSource(source);\n console.log(` Company: ${chalk.bold(profile.companyName)}`);\n if (facts.companyId) {\n console.log(` Company ID: ${chalk.dim(facts.companyId)}`);\n }\n console.log(` Subject: ${chalk.dim(facts.subject)}`);\n if (facts.roles.length > 0) {\n console.log(` Roles: ${facts.roles.join(\", \")}`);\n }\n if (facts.impersonating && facts.actor) {\n console.log(` Acting as: ${chalk.yellow(facts.actor)}`);\n }\n console.log(\n ` Signed in: ${chalk.dim(new Date(facts.authTime * 1000).toISOString())}`,\n );\n console.log(` Stored: ${chalk.dim(profile.storedAt)}`);\n}\n\nasync function whoamiClient(\n profile: ClientProfile,\n source: CredentialSourceDescription,\n): Promise<void> {\n const spinner = ora(\"Requesting a token for this client...\").start();\n try {\n await clientAccessToken(profile);\n } catch (error) {\n spinner.fail(chalk.red(describeIdentityError(error)));\n console.log(chalk.dim(`Profile: ${profile.name}`));\n process.exitCode = 1;\n return;\n }\n spinner.succeed(chalk.green(\"Authenticated (client credentials)\"));\n console.log(` Profile: ${chalk.bold(profile.name)}`);\n console.log(` Company: ${chalk.bold(profile.companyName)}`);\n printSource(source);\n console.log(` Client ID: ${chalk.dim(profile.auth.clientId)}`);\n console.log(` Org: ${chalk.dim(profile.auth.org)}`);\n console.log(` Stored: ${chalk.dim(profile.storedAt)}`);\n}\n\n/** The prefix of a company API token, which has no user. */\nconst COMPANY_TOKEN_PREFIX = \"PT-\";\n\n/**\n * Check a token from FLUID_TOKEN (or FLUID_TOKEN_FD), which every other\n * command uses before any saved login, against FLUID_API_BASE.\n *\n * token - The token the environment holds.\n * source - Where that token came from.\n *\n * Returns nothing; sets the exit code when the token is refused.\n */\nasync function whoamiEnvToken(\n token: string,\n source: CredentialSourceDescription,\n): Promise<void> {\n const baseUrl = process.env[\"FLUID_API_BASE\"];\n const spinner = ora(\"Verifying the token from FLUID_TOKEN...\").start();\n const result = await validateToken(token, baseUrl ? { baseUrl } : {});\n if (!result.success) {\n spinner.fail(chalk.red(\"The token in FLUID_TOKEN was refused.\"));\n console.log(chalk.dim(result.error.message));\n process.exitCode = 1;\n return;\n }\n\n spinner.succeed(chalk.green(\"Authenticated (token from FLUID_TOKEN)\"));\n printSource(source);\n console.log(` Company: ${chalk.bold(result.value.name)}`);\n if (token.startsWith(COMPANY_TOKEN_PREFIX)) {\n console.log(\n chalk.yellow(\n \" 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`.\",\n ),\n );\n }\n if (!baseUrl) {\n console.log(\n chalk.yellow(\n \" FLUID_API_BASE is not set. With FLUID_TOKEN and no saved login, the sites commands need it, such as https://api.fluid.app.\",\n ),\n );\n }\n}\n\nexport const whoamiCommand = new Command(\"whoami\")\n .description(\"Show the current authenticated profile\")\n .action(async () => {\n const source = resolveCredentialSource();\n const description = source ? describeCredentialSource(source) : null;\n if (source?.kind === \"token\" && description) {\n await whoamiEnvToken(source.token, description);\n return;\n }\n\n const profile =\n source?.kind === \"profile\" ? source.profile : getActiveProfile();\n\n if (!profile) {\n console.log(\n chalk.yellow(\"Not logged in. Run `fluid login` to authenticate.\"),\n );\n process.exitCode = 1;\n return;\n }\n\n const profileSource: CredentialSourceDescription = description ?? {\n origin: \"active\",\n mode: isIdentityProfile(profile)\n ? \"identity\"\n : isClientProfile(profile)\n ? \"client\"\n : \"legacy\",\n profileName: profile.name,\n };\n\n if (isIdentityProfile(profile)) {\n await whoamiIdentity(profile, profileSource);\n return;\n }\n\n if (isClientProfile(profile)) {\n await whoamiClient(profile, profileSource);\n return;\n }\n\n const spinner = ora(\"Verifying token...\").start();\n // Check the token against FLUID_API_BASE, else the API the profile was\n // made for, as the site commands do, so a staging or local login is not\n // checked against production.\n const result = await validateToken(profile.token ?? \"\", {\n baseUrl: process.env[\"FLUID_API_BASE\"] || profile.baseUrl,\n });\n\n if (!result.success) {\n spinner.fail(chalk.red(\"Token is no longer valid.\"));\n console.log(chalk.dim(`Profile: ${profile.name}`));\n console.log(chalk.dim(\"Run `fluid login` to re-authenticate.\"));\n process.exitCode = 1;\n return;\n }\n\n spinner.succeed(chalk.green(\"Authenticated\"));\n console.log(` Profile: ${chalk.bold(profile.name)}`);\n printSource(profileSource);\n console.log(` Company: ${chalk.bold(result.value.name)}`);\n console.log(` Stored: ${chalk.dim(profile.storedAt)}`);\n });\n","import {\n existsSync,\n mkdirSync,\n readFileSync,\n readdirSync,\n renameSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\nimport { randomBytes } from \"node:crypto\";\n\nimport {\n isStalePendingAdopt,\n parseAdoptMarker,\n type PendingAdoptMarker,\n serializeAdoptMarker,\n} from \"@fluid-app/auth/native\";\n\nimport { readStoredConfig } from \"../../config/config.js\";\nimport { getConfigDir } from \"../../config/paths.js\";\nimport { deleteStoredAdoption, revokeStoredAdoption } from \"./session.js\";\n\nexport const ADOPT_DEADLINE_MS = 15_000;\nexport { ADOPT_CLEANUP_TIMEOUT_MS } from \"./adopt-timeouts.js\";\nexport const ADOPT_RECOVERY_TIMEOUT_MS = 4_000;\nexport const ADOPT_RECOVERY_MIN_MS = 500;\nconst ADOPT_RECOVERY_MAX_ATTEMPTS = 5;\n\nconst PREFIX = \"adopt-pending-\";\nconst SUFFIX = \".json\";\n\nfunction markerFiles(): string[] {\n try {\n return readdirSync(getConfigDir()).filter(\n (name) => name.startsWith(PREFIX) && name.endsWith(SUFFIX),\n );\n } catch {\n return [];\n }\n}\n\nfunction remove(name: string): void {\n try {\n unlinkSync(join(getConfigDir(), name));\n } catch {\n // Already gone.\n }\n}\n\nfunction store(name: string, marker: PendingAdoptMarker): void {\n try {\n const dir = getConfigDir();\n const tmp = join(\n dir,\n `.adopt-pending-${randomBytes(6).toString(\"hex\")}.tmp`,\n );\n writeFileSync(tmp, serializeAdoptMarker(marker), { mode: 0o600 });\n renameSync(tmp, join(dir, name));\n } catch {\n // The old marker stays, so the next start retries.\n }\n}\n\n/** Writes the marker for one attempt, atomically; throws when it cannot. */\nexport function writePendingAdopt(\n storageKey: string,\n identityUrl: string,\n): void {\n const dir = getConfigDir();\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });\n const tmp = join(dir, `.adopt-pending-${randomBytes(6).toString(\"hex\")}.tmp`);\n writeFileSync(\n tmp,\n serializeAdoptMarker({ storageKey, identityUrl, startedAt: Date.now() }),\n { mode: 0o600 },\n );\n renameSync(tmp, join(dir, `${PREFIX}${storageKey}${SUFFIX}`));\n}\n\n/** Removes the marker for `storageKey`; never throws. */\nexport function clearPendingAdopt(storageKey: string): void {\n remove(`${PREFIX}${storageKey}${SUFFIX}`);\n}\n\n/**\n * Settles every stale marker left by an attempt that died: one whose key no\n * profile names has its stored session revoked and deleted, then the marker\n * goes. A marker still inside the grace belongs to a live attempt and stays.\n * Never throws; logs outcomes without any token. With `quiet`, a revoked or\n * empty outcome is not logged; a failure still is.\n */\nexport async function recoverPendingAdopts(\n options: {\n readonly log?: (line: string) => void;\n readonly quiet?: boolean;\n } = {},\n): Promise<void> {\n const log =\n options.log ?? ((line: string) => process.stderr.write(`${line}\\n`));\n const files = markerFiles();\n if (files.length === 0) return;\n const budgetEndsAt = Date.now() + ADOPT_RECOVERY_TIMEOUT_MS;\n try {\n const committed = new Set(\n Object.values(readStoredConfig().profiles).flatMap((profile) =>\n profile.auth?.mode === \"identity\" ? [profile.auth.storageKey] : [],\n ),\n );\n for (const name of files) {\n let marker;\n try {\n marker = parseAdoptMarker(\n readFileSync(join(getConfigDir(), name), \"utf8\"),\n );\n } catch {\n continue;\n }\n if (!marker) {\n remove(name);\n continue;\n }\n if (!isStalePendingAdopt(marker, Date.now())) continue;\n if (committed.has(marker.storageKey) || !marker.identityUrl) {\n remove(name);\n continue;\n }\n const remainingMs = budgetEndsAt - Date.now();\n if (remainingMs < ADOPT_RECOVERY_MIN_MS) break;\n const auth = {\n mode: \"identity\",\n identityUrl: marker.identityUrl,\n storageKey: marker.storageKey,\n } as const;\n let outcome: \"revoked\" | \"none\" | \"unconfirmed\" = \"unconfirmed\";\n try {\n outcome = await revokeStoredAdoption(auth, remainingMs);\n } catch {\n // Counted below.\n }\n if (outcome !== \"unconfirmed\") {\n remove(name);\n if (!options.quiet) log(`adopt recovery: ${outcome}`);\n continue;\n }\n const attempts = (marker.attemptCount ?? 0) + 1;\n if (attempts >= ADOPT_RECOVERY_MAX_ATTEMPTS) {\n const deleted = await deleteStoredAdoption(\n auth,\n Math.max(budgetEndsAt - Date.now(), ADOPT_RECOVERY_MIN_MS),\n ).then(\n () => true,\n () => false,\n );\n if (deleted) {\n remove(name);\n log(\"adopt recovery: gave up; the stored credential was deleted\");\n } else {\n store(name, { ...marker, attemptCount: attempts });\n log(\"adopt recovery: could not delete the stored credential\");\n }\n } else {\n store(name, { ...marker, attemptCount: attempts });\n log(\"adopt recovery: not confirmed, will retry at the next start\");\n }\n }\n } catch {\n log(\"adopt recovery: skipped\");\n }\n}\n","import {\n createSwitchAdoptRequest,\n type SwitchAdoptRequest,\n} from \"@fluid-app/auth/native\";\n\nimport { readConfig, updateConfig } from \"../../config/config.js\";\nimport type { FluidProfile } from \"../../config/types.js\";\nimport { createIdentityProfile } from \"../profiles.js\";\nimport type { SwitchAdoptAnswer } from \"../fluid-api.js\";\nimport { resolveIdentityUrl } from \"./environment.js\";\nimport {\n ADOPT_CLEANUP_TIMEOUT_MS,\n ADOPT_DEADLINE_MS,\n clearPendingAdopt,\n writePendingAdopt,\n} from \"./adopt-pending.js\";\nimport { endUnusedSessions } from \"./profiles.js\";\nimport {\n adoptionStorageAvailable,\n createAdoptionSession,\n type AdoptionSession,\n} from \"./session.js\";\n\nexport interface SwitchAdoption {\n readonly codeChallenge: string;\n /**\n * Redeems the code a switch answered, stores the session and writes the\n * target company's identity profile, all or nothing. Null when it did not land; otherwise\n * any problems ending the sessions the write replaced.\n */\n readonly complete: (\n answer: SwitchAdoptAnswer,\n companyName: string,\n ) => Promise<{ readonly problems: string[] } | null>;\n}\n\nfunction identityUrlFor(apiBase: string): string | null {\n try {\n return resolveIdentityUrl(apiBase);\n } catch {\n return null;\n }\n}\n\n/**\n * Prepares an adopt request for a legacy switch made with `profile`'s token,\n * or null when that profile is not one the CLI would adopt (no token, owned\n * by Mist, no identity service for the API base) or the credential store\n * cannot keep a session.\n */\nexport async function beginSwitchAdoption(\n profile: FluidProfile | null | undefined,\n apiBase: string,\n): Promise<SwitchAdoption | null> {\n if (\n !profile?.token ||\n profile.mistOwned === true ||\n profile.identityClient !== undefined\n ) {\n return null;\n }\n const identityUrl = identityUrlFor(apiBase);\n if (!identityUrl) return null;\n try {\n if (!(await adoptionStorageAvailable())) return null;\n const deadline = new AbortController();\n const held = createAdoptionSession(identityUrl, deadline.signal);\n const request = await createSwitchAdoptRequest(held.session);\n const legacyToken = profile.token;\n return {\n codeChallenge: request.codeChallenge,\n complete: (answer, companyName) =>\n land(\n request,\n held,\n deadline,\n identityUrl,\n legacyToken,\n apiBase,\n answer,\n companyName,\n ),\n };\n } catch {\n return null;\n }\n}\n\nasync function land(\n request: SwitchAdoptRequest,\n held: AdoptionSession,\n deadline: AbortController,\n identityUrl: string,\n legacyToken: string,\n apiBase: string,\n answer: SwitchAdoptAnswer,\n companyName: string,\n): Promise<{ readonly problems: string[] } | null> {\n const storageKey = held.auth.storageKey;\n try {\n writePendingAdopt(storageKey, identityUrl);\n } catch {\n return null;\n }\n const timer = setTimeout(() => {\n deadline.abort();\n }, ADOPT_DEADLINE_MS);\n try {\n const result = await request.redeem({\n code: answer.adoptCode,\n apiBase,\n legacyToken,\n targetCompanyId: answer.companyId,\n fetch: (input, init) =>\n fetch(input, {\n ...init,\n signal: init?.signal\n ? AbortSignal.any([init.signal, deadline.signal])\n : deadline.signal,\n }),\n });\n if (result.outcome !== \"adopted\") {\n if (result.outcome !== \"unavailable\") clearPendingAdopt(storageKey);\n return null;\n }\n let persistAttempted = false;\n const revoke = async (): Promise<void> => {\n held.beginCleanup(ADOPT_CLEANUP_TIMEOUT_MS);\n const revoked = await result.discard().then(\n () => true,\n () => false,\n );\n if (!revoked) return;\n const clean =\n persistAttempted && !held.persistRefused\n ? await held.unpersist().then(\n () => true,\n () => false,\n )\n : true;\n if (clean) clearPendingAdopt(storageKey);\n };\n try {\n if (deadline.signal.aborted) throw new Error(\"adopt deadline passed\");\n clearTimeout(timer);\n writePendingAdopt(storageKey, identityUrl);\n persistAttempted = true;\n await held.persist();\n const before = readConfig();\n const after = updateConfig((config) => ({\n ...config,\n activeProfile: companyName,\n profiles: {\n ...config.profiles,\n [companyName]: createIdentityProfile({\n name: companyName,\n companyName,\n baseUrl: apiBase,\n auth: held.auth,\n }),\n },\n }));\n clearPendingAdopt(storageKey);\n return { problems: await endUnusedSessions(before, after) };\n } catch {\n await revoke();\n return null;\n }\n } catch {\n return null;\n } finally {\n clearTimeout(timer);\n }\n}\n","/**\n * fluid switch — switch between companies (fetched from API, with local fallback)\n *\n * An identity-mode profile switches by token exchange (Phase 007 FR-3): the\n * session it signed in with stays as it is, and the new company's profile\n * remembers the company to exchange into. Nothing secret is written.\n */\n\nimport { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport prompts from \"prompts\";\nimport ora from \"ora\";\nimport {\n fetchUserCompanies,\n switchCompany,\n DEFAULT_FLUID_API_BASE,\n FLUID_API_ERROR,\n getFluidApiBase,\n type UserCompany,\n} from \"../auth/fluid-api.js\";\nimport { endUnusedSessions } from \"../auth/identity/profiles.js\";\nimport { beginSwitchAdoption } from \"../auth/identity/switch-adopt.js\";\nimport {\n describeIdentityError,\n identityToken,\n isIdentitySessionEnded,\n sessionFacts,\n} from \"../auth/identity/session.js\";\nimport { SessionError } from \"@fluid-app/auth/native\";\nimport { createFluidProfile, createIdentityProfile } from \"../auth/profiles.js\";\nimport { getActiveProfile } from \"../auth/token.js\";\nimport { readConfig, updateConfig } from \"../config/config.js\";\nimport {\n type FluidConfig,\n type FluidProfile,\n type IdentityProfile,\n type IdentityProfileAuth,\n isClientProfile,\n isIdentityProfile,\n} from \"../config/types.js\";\n\nfunction signInCommand(profile: FluidProfile): string {\n const shop = profile.fluidShop\n ?.toLowerCase()\n .replace(/^https?:\\/\\//, \"\")\n .replace(/\\/.*$/, \"\")\n .replace(/\\.fluid\\.app$/, \"\");\n return shop ? `fluid login --shop ${shop}` : \"fluid login\";\n}\n\nfunction hasCustomBase(profile: FluidProfile): profile is FluidProfile & {\n baseUrl: string;\n} {\n return Boolean(profile.baseUrl && profile.baseUrl !== DEFAULT_FLUID_API_BASE);\n}\n\nexport function signInAgainHint(\n profile: FluidProfile,\n platform: string = process.platform,\n): string {\n const login = signInCommand(profile);\n if (!hasCustomBase(profile)) return login;\n return platform === \"win32\"\n ? `$env:FLUID_API_BASE=\"${profile.baseUrl}\"; ${login}`\n : `FLUID_API_BASE=${profile.baseUrl} ${login}`;\n}\n\nfunction signInAgainInstruction(\n profile: FluidProfile,\n platform: string = process.platform,\n): string {\n const hint = signInAgainHint(profile, platform);\n if (platform !== \"win32\" || !hasCustomBase(profile)) {\n return `run \\`${hint}\\``;\n }\n const cmd = `set \"FLUID_API_BASE=${profile.baseUrl}\" && ${signInCommand(profile)}`;\n return `run \\`${hint}\\` in PowerShell or \\`${cmd}\\` in cmd.exe`;\n}\n\n/**\n * The auth for a profile in `org`'s company on the live session `profile`\n * holds, after proving the session can reach it by exchange.\n */\nasync function authForCompany(\n profile: IdentityProfile,\n org: string,\n): Promise<IdentityProfileAuth> {\n // Back to the company the session signed in to needs no exchange.\n const home = (await sessionFacts(profile.auth)).companyId;\n const target = org === home ? undefined : org;\n await identityToken(profile.auth, target ?? null);\n const { org: _previous, ...session } = profile.auth;\n return target ? { ...session, org: target } : session;\n}\n\ntype Activation =\n | {\n readonly kind: \"activated\";\n readonly before: FluidConfig;\n readonly after: FluidConfig;\n }\n | { readonly kind: \"removed\" | \"replaced\" };\n\n/**\n * Makes `name` the active profile, writing `replacement` over it first when\n * given, only if the stored profile is still the one stamped `storedAt`.\n * The check runs inside the config lock, on the config as it is now, so a\n * profile another process removed or rewrote during the restore is never\n * activated.\n */\nfunction activateUnchanged(\n name: string,\n storedAt: string,\n replacement?: FluidProfile,\n): Activation {\n let outcome: Activation = { kind: \"removed\" };\n updateConfig((config) => {\n const current = config.profiles[name];\n if (!current) {\n outcome = { kind: \"removed\" };\n return config;\n }\n if (current.storedAt !== storedAt) {\n outcome = { kind: \"replaced\" };\n return config;\n }\n const after = {\n ...config,\n activeProfile: name,\n profiles: replacement\n ? { ...config.profiles, [name]: replacement }\n : config.profiles,\n };\n outcome = { kind: \"activated\", before: config, after };\n return after;\n });\n return outcome;\n}\n\nfunction reportNotActivated(name: string, kind: \"removed\" | \"replaced\"): void {\n console.log(\n chalk.red(\n kind === \"removed\"\n ? `Profile ${name} was removed while switching.`\n : `Profile ${name} was changed while switching; run \\`fluid switch ${name}\\` again.`,\n ),\n );\n process.exitCode = 1;\n}\n\nasync function activateStoredProfile(\n name: string,\n active: IdentityProfile | null,\n baseUrl: string,\n): Promise<void> {\n const target = readConfig().profiles[name];\n if (!target) {\n reportNotActivated(name, \"removed\");\n return;\n }\n let replacement: FluidProfile | undefined;\n if (isIdentityProfile(target)) {\n try {\n await identityToken(target.auth);\n } catch (error) {\n if (!isIdentitySessionEnded(error)) {\n console.log(chalk.red(describeIdentityError(error)));\n process.exitCode = 1;\n return;\n }\n const org = target.auth.org;\n const sameEnvironment =\n active !== null &&\n target.auth.identityUrl === active.auth.identityUrl &&\n (target.baseUrl ?? getFluidApiBase()) === baseUrl;\n if (!active || !org || !sameEnvironment) {\n console.log(\n chalk.red(\n `Your sign-in for ${name} has ended; ${signInAgainInstruction(target)}.`,\n ),\n );\n process.exitCode = 1;\n return;\n }\n try {\n replacement = {\n ...createIdentityProfile({\n name,\n companyName: target.companyName,\n baseUrl: target.baseUrl ?? baseUrl,\n auth: await authForCompany(active, org),\n }),\n ...(target.fluidShop ? { fluidShop: target.fluidShop } : {}),\n };\n } catch (recoveryError) {\n const described = describeIdentityError(recoveryError);\n console.log(\n chalk.red(\n recoveryError instanceof SessionError &&\n recoveryError.code === \"access_denied\"\n ? `${described} Sign in again: ${signInAgainInstruction(target)}.`\n : described,\n ),\n );\n process.exitCode = 1;\n return;\n }\n }\n }\n const result = activateUnchanged(name, target.storedAt, replacement);\n if (result.kind !== \"activated\") {\n reportNotActivated(name, result.kind);\n return;\n }\n console.log(chalk.green(`Switched to profile ${chalk.bold(name)}.`));\n if (replacement) {\n for (const problem of await endUnusedSessions(\n result.before,\n result.after,\n )) {\n console.log(chalk.yellow(problem));\n }\n }\n}\n\nasync function localSwitch(\n profileArg?: string,\n active: IdentityProfile | null = null,\n baseUrl: string = getFluidApiBase(),\n): Promise<void> {\n const config = readConfig();\n const profileNames = Object.keys(config.profiles);\n\n if (profileNames.length === 0) {\n console.log(chalk.yellow(\"No profiles stored. Run `fluid login` first.\"));\n process.exitCode = 1;\n return;\n }\n\n let targetProfile = profileArg;\n\n if (!targetProfile) {\n const profileChoices = profileNames.map((name) => ({\n title: name === config.activeProfile ? `${name} (active)` : name,\n value: name,\n }));\n\n const response = await prompts({\n type: \"autocomplete\",\n name: \"profile\",\n message: \"Select a profile (type to search)\",\n choices: profileChoices,\n suggest: (input, choices) =>\n Promise.resolve(\n input\n ? choices.filter((c) =>\n c.value.toLowerCase().includes(input.toLowerCase()),\n )\n : choices,\n ),\n });\n targetProfile = response[\"profile\"] as string | undefined;\n\n if (!targetProfile) {\n console.log(chalk.dim(\"Cancelled.\"));\n return;\n }\n }\n\n if (!config.profiles[targetProfile]) {\n console.log(chalk.red(`Profile \"${targetProfile}\" not found.`));\n console.log(chalk.dim(`Available: ${profileNames.join(\", \")}`));\n process.exitCode = 1;\n return;\n }\n\n await activateStoredProfile(targetProfile, active, baseUrl);\n}\n\nasync function selectCompany(\n companies: UserCompany[],\n activeCompanyName: string | undefined,\n): Promise<UserCompany | undefined> {\n const companyChoices = companies.map((c) => ({\n title:\n c.name === activeCompanyName\n ? `${c.name} ${chalk.dim(\"(active)\")}`\n : c.name,\n value: c.id,\n }));\n\n const response = await prompts({\n type: \"autocomplete\",\n name: \"companyId\",\n message: \"Select a company (type to search)\",\n choices: companyChoices,\n suggest: (input, choices) =>\n Promise.resolve(\n input\n ? choices.filter((c) =>\n c.title.toLowerCase().includes(input.toLowerCase()),\n )\n : choices,\n ),\n });\n\n const companyId = response[\"companyId\"] as number | undefined;\n if (companyId === undefined) return undefined;\n return companies.find((c) => c.id === companyId);\n}\n\nasync function performSwitch(\n token: string,\n company: UserCompany,\n baseUrl?: string,\n): Promise<void> {\n const spinner = ora(`Switching to ${chalk.bold(company.name)}...`).start();\n const adoption = await beginSwitchAdoption(\n getActiveProfile(),\n baseUrl ?? getFluidApiBase(),\n );\n let result = await switchCompany(\n token,\n company.id,\n baseUrl,\n adoption?.codeChallenge,\n );\n\n if (result.success && \"adoptCode\" in result.value) {\n if (result.value.companyId !== company.id) {\n spinner.fail(chalk.red(\"Unexpected response shape from /switch\"));\n process.exitCode = 1;\n return;\n }\n const landed = adoption\n ? await adoption.complete(result.value, company.name)\n : null;\n if (landed) {\n spinner.succeed(\n chalk.green(\n `Switched to ${chalk.bold(company.name)} (profile: ${chalk.bold(company.name)})`,\n ),\n );\n for (const problem of landed.problems) {\n console.log(chalk.yellow(problem));\n }\n return;\n }\n result = await switchCompany(token, company.id, baseUrl);\n }\n\n if (!result.success) {\n if (result.error.code === FLUID_API_ERROR.INVALID_TOKEN.code) {\n spinner.fail(\n chalk.red(\n \"Your session has expired. Please run `fluid login` to re-authenticate.\",\n ),\n );\n } else {\n spinner.fail(chalk.red(result.error.message));\n if (result.error.details) {\n console.log(chalk.dim(result.error.details));\n }\n }\n process.exitCode = 1;\n return;\n }\n\n if (\"adoptCode\" in result.value) {\n spinner.fail(chalk.red(\"Unexpected response shape from /switch\"));\n process.exitCode = 1;\n return;\n }\n\n const { companyName, jwt } = result.value;\n\n updateConfig((config) => ({\n ...config,\n activeProfile: companyName,\n profiles: {\n ...config.profiles,\n [companyName]: createFluidProfile({\n name: companyName,\n token: jwt,\n companyName,\n baseUrl: baseUrl ?? getFluidApiBase(),\n }),\n },\n }));\n\n spinner.succeed(\n chalk.green(\n `Switched to ${chalk.bold(companyName)} (profile: ${chalk.bold(companyName)})`,\n ),\n );\n}\n\nasync function performIdentitySwitch(\n profile: IdentityProfile,\n company: UserCompany,\n baseUrl: string,\n): Promise<void> {\n const spinner = ora(`Switching to ${chalk.bold(company.name)}...`).start();\n if (!company.uuidV7) {\n spinner.fail(\n chalk.red(`${company.name} has no identifier to switch to it by.`),\n );\n process.exitCode = 1;\n return;\n }\n\n let auth: IdentityProfileAuth;\n try {\n auth = await authForCompany(profile, company.uuidV7);\n } catch (error) {\n spinner.fail(chalk.red(describeIdentityError(error)));\n process.exitCode = 1;\n return;\n }\n\n const before = readConfig();\n const after = updateConfig((config) => ({\n ...config,\n activeProfile: company.name,\n profiles: {\n ...config.profiles,\n [company.name]: createIdentityProfile({\n name: company.name,\n companyName: company.name,\n baseUrl,\n auth,\n }),\n },\n }));\n const problems = await endUnusedSessions(before, after);\n\n spinner.succeed(\n chalk.green(\n `Switched to ${chalk.bold(company.name)} (profile: ${chalk.bold(company.name)})`,\n ),\n );\n for (const problem of problems) console.log(chalk.yellow(problem));\n}\n\nexport const switchCommand = new Command(\"switch\")\n .description(\"Switch between companies\")\n .argument(\"[profile]\", \"Company or profile name to switch to\")\n .action(async (profileArg?: string) => {\n const activeProfile = getActiveProfile();\n\n if (!activeProfile) {\n console.log(chalk.yellow(\"Not logged in. Run `fluid login` first.\"));\n process.exitCode = 1;\n return;\n }\n\n if (isClientProfile(activeProfile)) {\n await localSwitch(profileArg);\n return;\n }\n\n const activeCompanyName = activeProfile.companyName;\n const activeBaseUrl = activeProfile.baseUrl ?? getFluidApiBase();\n const identity = isIdentityProfile(activeProfile) ? activeProfile : null;\n\n // Fetch companies from API\n const spinner = ora(\"Fetching companies...\").start();\n let token = activeProfile.token ?? \"\";\n if (identity) {\n try {\n token = (await identityToken(identity.auth)).accessToken;\n } catch (error) {\n spinner.fail(chalk.red(describeIdentityError(error)));\n process.exitCode = 1;\n return;\n }\n }\n const result = await fetchUserCompanies(token, activeBaseUrl);\n\n if (!result.success) {\n if (result.error.code === FLUID_API_ERROR.INVALID_TOKEN.code) {\n spinner.fail(\n chalk.red(\n \"Your session has expired. Please run `fluid login` to re-authenticate.\",\n ),\n );\n process.exitCode = 1;\n return;\n }\n spinner.warn(\n chalk.yellow(\n `Could not fetch companies from API: ${result.error.message}`,\n ),\n );\n console.log(chalk.dim(\"Falling back to locally stored profiles.\"));\n await localSwitch(profileArg, identity, activeBaseUrl);\n return;\n }\n\n const companies = result.value;\n spinner.succeed(\n `Found ${companies.length} company${companies.length === 1 ? \"\" : \"ies\"}`,\n );\n\n if (companies.length === 0) {\n console.log(chalk.yellow(\"No companies found for this account.\"));\n process.exitCode = 1;\n return;\n }\n\n // If a profile argument was passed, match against API companies first\n if (profileArg) {\n const match = companies.find(\n (c) => c.name.toLowerCase() === profileArg.toLowerCase(),\n );\n\n if (match) {\n await (identity\n ? performIdentitySwitch(identity, match, activeBaseUrl)\n : performSwitch(token, match, activeBaseUrl));\n return;\n }\n\n // Fall back to local profile matching\n const config = readConfig();\n if (config.profiles[profileArg]) {\n await activateStoredProfile(profileArg, identity, activeBaseUrl);\n return;\n }\n\n console.log(chalk.red(`Company or profile \"${profileArg}\" not found.`));\n process.exitCode = 1;\n return;\n }\n\n // Interactive selection\n const selected = await selectCompany(companies, activeCompanyName);\n if (!selected) {\n console.log(chalk.dim(\"Cancelled.\"));\n return;\n }\n\n await (identity\n ? performIdentitySwitch(identity, selected, activeBaseUrl)\n : performSwitch(token, selected, activeBaseUrl));\n });\n","/**\n * Format one-line diagnostics naming a CLI plugin build and where it was\n * resolved from. The resolved path is the load-bearing detail: a workspace\n * build and a published copy share the same name and version, so the path is\n * the only thing that distinguishes them. See CURRENT-3218.\n */\n\nimport { fileURLToPath } from \"node:url\";\n\nexport interface PluginLoadInfo {\n readonly name: string;\n readonly version: string;\n /**\n * Where the plugin was resolved from — an absolute `file://` URL (workspace\n * or published install, resolved upstream) or, only when resolution failed,\n * a bare package name.\n */\n readonly importSpecifier: string;\n /**\n * Whether installation-bundled plugins were preferred over project-local\n * ones (`FLUID_CLI_PREFER_INSTALLATION_PLUGINS=1`, set by Mist).\n */\n readonly preferInstallation: boolean;\n}\n\nexport interface PluginLoadFailureInfo {\n readonly name: string;\n readonly importSpecifier: string;\n readonly preferInstallation: boolean;\n readonly message: string;\n}\n\nexport function modeLabel(preferInstallation: boolean): string {\n return preferInstallation ? \"installation-preferred\" : \"project-first\";\n}\n\n/**\n * Render a specifier for display: `file://` URLs become absolute filesystem\n * paths; anything else is shown verbatim. Never throws — a malformed `file://`\n * specifier falls back to its raw form so a diagnostic can never turn a\n * successful load into a reported failure.\n */\nexport function displaySource(importSpecifier: string): string {\n if (!importSpecifier.startsWith(\"file://\")) return importSpecifier;\n try {\n return fileURLToPath(importSpecifier);\n } catch {\n return importSpecifier;\n }\n}\n\nexport function formatPluginLoadLine(info: PluginLoadInfo): string {\n return `Loaded plugin ${info.name}@${info.version} from ${displaySource(\n info.importSpecifier,\n )} [${modeLabel(info.preferInstallation)}]`;\n}\n\nexport function formatPluginLoadFailure(info: PluginLoadFailureInfo): string {\n return `Failed to load plugin ${info.name} from ${displaySource(\n info.importSpecifier,\n )} [${modeLabel(info.preferInstallation)}]: ${info.message}`;\n}\n","/**\n * Resolve a plugin import specifier to a concrete path for diagnostics.\n *\n * The node_modules discovery strategy falls back to a bare package name when it\n * cannot realpath a workspace symlink — precisely the published-install case\n * where the path is the only thing that would reveal a stale plugin winning.\n * Resolving the bare specifier recovers that path. See CURRENT-3218.\n */\n\nexport type Resolver = (specifier: string) => string;\n\nconst defaultResolver: Resolver = (specifier) => import.meta.resolve(specifier);\n\n/**\n * Return a `file://` URL for `importSpecifier`. `file://` specifiers (already\n * resolved by discovery) pass through untouched; bare specifiers are resolved\n * via `resolve`. If resolution throws, the bare specifier is returned so a\n * diagnostic degrades gracefully rather than failing the load.\n */\nexport function resolveLoadPath(\n importSpecifier: string,\n resolve: Resolver = defaultResolver,\n): string {\n if (importSpecifier.startsWith(\"file://\")) return importSpecifier;\n try {\n return resolve(importSpecifier);\n } catch {\n return importSpecifier;\n }\n}\n","/**\n * Decide whether to print the per-plugin \"Loaded plugin …\" diagnostics.\n *\n * A monorepo checkout resolves ~a dozen plugin packages, so emitting a line\n * for each on every command (including `--help` and tab-completion, and into\n * Mist's captured stderr dialog) is noise. The success diagnostics are gated\n * behind an explicit opt-in; load *failures* are always surfaced by the loader\n * regardless of this flag. See CURRENT-3218.\n */\n\nfunction isTruthyFlag(value: string | undefined): boolean {\n return value === \"1\" || value === \"true\";\n}\n\nexport function shouldLogPluginLoads(\n argv: readonly string[] = process.argv,\n env: NodeJS.ProcessEnv = process.env,\n): boolean {\n if (argv.includes(\"--verbose\")) return true;\n return isTruthyFlag(env[\"FLUID_CLI_DEBUG\"] ?? env[\"FLUID_CLI_VERBOSE\"]);\n}\n","/**\n * Plugin loader — orchestrates discovery and registration\n */\n\nimport type { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport { getConfigDir } from \"../config/paths.js\";\nimport { getAuthToken } from \"../auth/token.js\";\nimport { readConfig } from \"../config/config.js\";\nimport { INPUTS_MODE_ENV } from \"../inputs/hook.js\";\nimport { createInputsReader } from \"../inputs/reader.js\";\nimport type { FluidPlugin, PluginContext } from \"./types.js\";\nimport { discoverPlugins, importPlugin } from \"./discovery.js\";\nimport { prefersInstallationPlugins } from \"./prefer-installation.js\";\nimport {\n formatPluginLoadLine,\n formatPluginLoadFailure,\n} from \"./format-load-line.js\";\nimport { resolveLoadPath } from \"./resolve-load-path.js\";\nimport { shouldLogPluginLoads } from \"./should-log-plugin-loads.js\";\n\nfunction isFluidPlugin(value: unknown): value is FluidPlugin {\n if (typeof value !== \"object\" || value === null) return false;\n const obj = value as Record<string, unknown>;\n return (\n typeof obj[\"name\"] === \"string\" &&\n typeof obj[\"version\"] === \"string\" &&\n typeof obj[\"register\"] === \"function\"\n );\n}\n\n/** A plugin this run registered, and the file it was imported from. */\nexport interface LoadedPlugin {\n /** The package name, such as `@fluid-app/fluid-cli-member-site`. */\n readonly name: string;\n /** A `file://` URL, or the bare specifier when it couldn't be resolved. */\n readonly source: string;\n}\n\nconst loaded: LoadedPlugin[] = [];\n\n/** The plugins the last loadPlugins registered, in the order it did. */\nexport function loadedPlugins(): readonly LoadedPlugin[] {\n return loaded;\n}\n\n/**\n * Discover, import, and register all installed plugins\n */\nexport async function loadPlugins(\n program: Command,\n basePath: string,\n): Promise<void> {\n loaded.length = 0;\n const preferInstallation = prefersInstallationPlugins();\n const discovered = discoverPlugins(basePath, undefined, {\n preferInstallation,\n installationOnly:\n process.env[INPUTS_MODE_ENV] === \"resolve\" ||\n Boolean(process.env[\"FLUID_TOKEN_FD\"]),\n });\n const { enabledPlugins } = readConfig();\n\n // If enabledPlugins is set, only load explicitly allowed plugins.\n // This acts as an allow-list to prevent accidental supply-chain execution.\n const allowedSet = enabledPlugins !== null ? new Set(enabledPlugins) : null;\n const plugins = allowedSet\n ? discovered.filter((p) => allowedSet.has(p.name))\n : discovered;\n\n if (plugins.length === 0) return;\n\n const ctx: PluginContext = {\n program,\n getAuthToken,\n configDir: getConfigDir(),\n inputs: createInputsReader(),\n };\n\n // Success diagnostics are opt-in (a checkout resolves ~a dozen plugins);\n // load failures below are always surfaced. See CURRENT-3218.\n const verbose = shouldLogPluginLoads();\n\n for (const { name, importSpecifier } of plugins) {\n // Resolve to a concrete path so a published install is distinguishable\n // from a workspace build at a glance.\n const source = resolveLoadPath(importSpecifier);\n try {\n const exported = await importPlugin(importSpecifier);\n\n if (!isFluidPlugin(exported)) {\n console.warn(\n chalk.yellow(`Warning: ${name} does not export a valid FluidPlugin`),\n );\n continue;\n }\n\n await exported.register(ctx);\n loaded.push({ name, source });\n\n if (verbose) {\n console.error(\n chalk.dim(\n formatPluginLoadLine({\n name: exported.name,\n version: exported.version,\n importSpecifier: source,\n preferInstallation,\n }),\n ),\n );\n }\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n // Always name what failed to load and from where — this is exactly the\n // invisible-artifact failure the diagnostic exists to catch.\n console.warn(\n chalk.yellow(\n `Warning: ${formatPluginLoadFailure({\n name,\n importSpecifier: source,\n preferInstallation,\n message,\n })}`,\n ),\n );\n }\n }\n}\n","/**\n * `fluid version`: the CLI's and each loaded plugin's version, npm's latest,\n * and the command that updates each. A person or a coding agent runs it to\n * learn whether a missing command, option or config key needs an update.\n */\n\nimport { realpathSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { Command } from \"commander\";\nimport { loadedPlugins, type LoadedPlugin } from \"../plugins/loader.js\";\nimport {\n PACKAGE_NAME,\n fetchLatestVersion,\n installRoot,\n isAppResources,\n isMistBundled,\n isNewer,\n loadedPackage,\n packageInstallKind,\n updateCommand,\n} from \"../update/notifier.js\";\n\nconst require = createRequire(import.meta.url);\nconst { version } = require(\"../../package.json\") as { version: string };\n\n/**\n * How to update a package: a command and, for a project's own copy, the\n * folder to run it in; or the app a bundled copy comes with.\n */\nexport type PackageUpdate =\n | { readonly command: string; readonly directory: string | null }\n | { readonly app: \"Mist\" };\n\nexport interface PackageVersion {\n readonly name: string;\n /** Null when its package.json can't be read, as for a workspace build. */\n readonly installed: string | null;\n /** npm's latest version; null when npm couldn't be reached. */\n readonly latest: string | null;\n /**\n * How to update it, when npm has a newer version and this copy can be\n * updated; otherwise null.\n */\n readonly update: PackageUpdate | null;\n}\n\nexport interface VersionReportOptions {\n /** Real path of a file in the running CLI's package. */\n readonly entryPath: string;\n readonly currentVersion: string;\n readonly plugins: readonly LoadedPlugin[];\n readonly fetchImpl?: typeof fetch;\n}\n\n/**\n * How to update `name`, installed under `root` (null for a workspace\n * build). A copy Mist ships updates with Mist. No command updates a copy\n * inside another app's resources, or a plugin in an npx run's cache, as an\n * npx run fetches only the CLI afresh.\n */\nfunction updateFor(name: string, root: string | null): PackageUpdate | null {\n if (root === null) return null;\n if (isMistBundled(join(root, \"node_modules\", name))) return { app: \"Mist\" };\n if (isAppResources(root)) return null;\n const install = packageInstallKind(root, name);\n if (install.kind === \"npx\" && name !== PACKAGE_NAME) return null;\n return {\n command: updateCommand(install, name),\n directory: install.kind === \"local\" ? install.projectDir : null,\n };\n}\n\n/** The CLI and each plugin, with npm's latest versions asked for at once. */\nexport async function versionReport({\n entryPath,\n currentVersion,\n plugins,\n fetchImpl = fetch,\n}: VersionReportOptions): Promise<PackageVersion[]> {\n const packages = [\n {\n name: PACKAGE_NAME,\n installed: currentVersion,\n root: installRoot(entryPath),\n },\n ...plugins.map(({ name, source }) => {\n const loaded = loadedPackage(source, name);\n return {\n name,\n installed: loaded?.version ?? null,\n root: loaded?.root ?? null,\n };\n }),\n ];\n return Promise.all(\n packages.map(async ({ name, installed, root }) => {\n const latest = await fetchLatestVersion(fetchImpl, name);\n const behind =\n latest !== null && installed !== null && isNewer(installed, latest);\n // Only a package that's behind needs its install looked at.\n const update = behind ? updateFor(name, root) : null;\n return { name, installed, latest, update };\n }),\n );\n}\n\n/**\n * The text report's update. It never prints a project's folder, which a\n * shell could read as code if the line were pasted into one; `--json` gives\n * the folder as a field of its own.\n */\nfunction updateText(update: PackageUpdate): string {\n if (\"app\" in update) return `update ${update.app}, which brings its own copy`;\n return update.directory === null\n ? `run ${update.command}`\n : `run ${update.command} in that project; fluid version --json shows its folder`;\n}\n\nfunction statusText({ installed, latest, update }: PackageVersion): string {\n if (latest === null) {\n return \"latest unknown (not on npm, or npm couldn't be reached)\";\n }\n if (installed === null) return `latest ${latest}`;\n if (installed === latest || isNewer(latest, installed)) return \"up to date\";\n // A version that doesn't compare, such as a prerelease, isn't called up to\n // date, and gets no command.\n if (!isNewer(installed, latest)) return `latest ${latest}`;\n return `latest ${latest}: ${update ? updateText(update) : \"no command updates this copy\"}`;\n}\n\nexport function formatVersionReport(\n packages: readonly PackageVersion[],\n): string {\n const nameWidth = Math.max(...packages.map(({ name }) => name.length));\n const versionWidth = Math.max(\n ...packages.map(({ installed }) => (installed ?? \"?\").length),\n );\n return packages\n .map(\n (entry) =>\n `${entry.name.padEnd(nameWidth)} ${(entry.installed ?? \"?\").padEnd(versionWidth)} ${statusText(entry)}`,\n )\n .join(\"\\n\");\n}\n\nexport const versionCommand = new Command(\"version\")\n .description(\n \"Show the CLI's and plugins' versions, npm's latest, and how to update\",\n )\n .option(\"--json\", \"Print the versions as JSON\", false)\n .action(async (opts: { json: boolean }) => {\n const packages = await versionReport({\n entryPath: realpathSync(fileURLToPath(import.meta.url)),\n currentVersion: version,\n plugins: loadedPlugins(),\n });\n process.stdout.write(\n opts.json\n ? JSON.stringify({ packages }, null, 2) + \"\\n\"\n : formatVersionReport(packages) + \"\\n\",\n );\n });\n","import {\n existsSync,\n mkdirSync,\n readFileSync,\n renameSync,\n writeFileSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\nimport { createHash, randomBytes } from \"node:crypto\";\n\nimport { tradeLegacyToken } from \"@fluid-app/auth/native\";\n\nimport { getFluidApiBase } from \"../fluid-api.js\";\nimport { updateConfig } from \"../../config/config.js\";\nimport { configLockTimings, withConfigLock } from \"../../config/lock.js\";\nimport { getConfigDir } from \"../../config/paths.js\";\nimport type { FluidProfile, IdentityProfile } from \"../../config/types.js\";\nimport { resolveIdentityUrl } from \"./environment.js\";\nimport { KeyringRefusedError } from \"./keyring-child.js\";\nimport {\n ADOPT_CLEANUP_TIMEOUT_MS,\n clearPendingAdopt,\n writePendingAdopt,\n} from \"./adopt-pending.js\";\nimport { createAdoptionSession } from \"./session.js\";\n\nexport const ADOPT_BACKOFF_MS = 24 * 60 * 60 * 1000;\nexport const ADOPT_UNAVAILABLE_BACKOFF_MS = 15 * 60 * 1000;\nconst ADOPT_TIMEOUT_MS = 5_000;\nexport const ADOPT_DEADLINE_MS = 6_000;\nconst MIN_LOCK_WAIT_MS = 250;\nconst BACKOFF_FILE = \"adopt-backoff.json\";\n\ntype Backoff = Record<string, number>;\n\nfunction backoffPath(): string {\n return join(getConfigDir(), BACKOFF_FILE);\n}\n\nfunction backoffKey(profile: FluidProfile): string {\n const digest = createHash(\"sha256\")\n .update(profile.token ?? \"\")\n .digest(\"hex\")\n .slice(0, 12);\n return `${profile.name}\\u0000${profile.companyName}\\u0000${digest}`;\n}\n\nfunction readBackoff(): Backoff {\n try {\n const parsed: unknown = JSON.parse(readFileSync(backoffPath(), \"utf8\"));\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Backoff)\n : {};\n } catch {\n return {};\n }\n}\n\nfunction recordBackoff(profile: FluidProfile, ms: number | null): void {\n try {\n const now = Date.now();\n const next: Backoff = {};\n for (const [key, until] of Object.entries(readBackoff())) {\n if (typeof until === \"number\" && until > now) next[key] = until;\n }\n if (ms === null) delete next[backoffKey(profile)];\n else next[backoffKey(profile)] = now + ms;\n const dir = getConfigDir();\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });\n const tmp = join(\n dir,\n `.adopt-backoff-${randomBytes(6).toString(\"hex\")}.tmp`,\n );\n writeFileSync(tmp, JSON.stringify(next), { mode: 0o600 });\n renameSync(tmp, backoffPath());\n } catch {\n // The back-off is an optimisation; a command never fails on it.\n }\n}\n\nfunction inBackoff(profile: FluidProfile): boolean {\n const until = readBackoff()[backoffKey(profile)];\n return typeof until === \"number\" && until > Date.now();\n}\n\nfunction convert(\n profile: FluidProfile,\n auth: IdentityProfile[\"auth\"],\n lockTimeoutMs: number,\n): void {\n withConfigLock(() => {\n updateConfig((config) => {\n const current = config.profiles[profile.name];\n if (!current || current.token !== profile.token) {\n throw new Error(\"The profile changed while it was being adopted.\");\n }\n const { token: _token, gitSyncActor: _actor, ...rest } = current;\n return {\n ...config,\n profiles: { ...config.profiles, [profile.name]: { ...rest, auth } },\n };\n });\n }, lockTimeoutMs);\n}\n\nfunction ownedByMist(profile: FluidProfile): boolean {\n return profile.mistOwned === true || profile.identityClient !== undefined;\n}\n\nfunction withSignal(signal: AbortSignal): typeof fetch {\n return (input, init) =>\n fetch(input, {\n ...init,\n signal: init?.signal ? AbortSignal.any([init.signal, signal]) : signal,\n });\n}\n\n/**\n * Trades a stored legacy profile's token for an identity session and, once\n * the session is stored and verified, rewrites the profile to identity mode\n * and drops its plaintext token. Every other outcome keeps the profile as it\n * is, and the whole attempt gives up after {@link ADOPT_DEADLINE_MS}: a trade\n * that finishes later is ignored and never persisted or converted. A back-off is on file before the trade\n * starts. Profiles Mist owns are never traded. Never throws; resolves with\n * the converted profile, or null.\n */\nexport async function adoptLegacyProfile(\n profile: FluidProfile,\n): Promise<IdentityProfile | null> {\n if (!profile.token || ownedByMist(profile) || inBackoff(profile)) {\n return null;\n }\n recordBackoff(profile, ADOPT_UNAVAILABLE_BACKOFF_MS);\n const abort = new AbortController();\n const deadlineAt = Date.now() + ADOPT_DEADLINE_MS;\n let expired = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<null>((resolve) => {\n timer = setTimeout(() => {\n expired = true;\n abort.abort();\n resolve(null);\n }, ADOPT_DEADLINE_MS);\n });\n const attempt = trade(\n profile as FluidProfile & { readonly token: string },\n abort.signal,\n () => expired,\n () => deadlineAt - Date.now(),\n ).catch(() => null);\n try {\n return await Promise.race([attempt, deadline]);\n } finally {\n clearTimeout(timer);\n }\n}\n\nasync function trade(\n profile: FluidProfile & { readonly token: string },\n signal: AbortSignal,\n expired: () => boolean,\n remainingMs: () => number,\n): Promise<IdentityProfile | null> {\n const apiBase = profile.baseUrl ?? getFluidApiBase();\n const identityUrl = resolveIdentityUrl(apiBase);\n if (!identityUrl) {\n recordBackoff(profile, null);\n return null;\n }\n const held = createAdoptionSession(identityUrl, signal);\n const storageKey = held.auth.storageKey;\n const result = await tradeLegacyToken({\n legacyToken: profile.token,\n apiBase,\n session: held.session,\n requestTimeoutMs: ADOPT_TIMEOUT_MS,\n fetch: withSignal(signal),\n beforeRedeem: () => writePendingAdopt(storageKey, identityUrl),\n beforeDiscard: () => held.beginCleanup(ADOPT_CLEANUP_TIMEOUT_MS),\n });\n if (result.outcome !== \"adopted\") {\n clearPendingAdopt(storageKey);\n if (result.outcome === \"not_targeted\" || result.outcome === \"refused\") {\n recordBackoff(profile, ADOPT_BACKOFF_MS);\n }\n return null;\n }\n let persistAttempted = false;\n const cleanup = async (): Promise<void> => {\n held.beginCleanup(ADOPT_CLEANUP_TIMEOUT_MS);\n const revoked = await result.discard().then(\n () => true,\n () => false,\n );\n if (!revoked) return;\n const clean = persistAttempted && !held.persistRefused\n ? await held.unpersist().then(\n () => true,\n () => false,\n )\n : true;\n if (clean) clearPendingAdopt(storageKey);\n };\n if (expired()) {\n await cleanup();\n return null;\n }\n try {\n persistAttempted = true;\n await held.persist();\n } catch (error) {\n if (error instanceof KeyringRefusedError) {\n recordBackoff(profile, ADOPT_BACKOFF_MS);\n }\n await cleanup();\n return null;\n }\n const lockWaitMs = Math.min(\n configLockTimings.timeoutMs,\n remainingMs() - MIN_LOCK_WAIT_MS,\n );\n try {\n if (lockWaitMs <= 0 || expired()) {\n throw new Error(\"No time left to rewrite the profile.\");\n }\n convert(profile, held.auth, lockWaitMs);\n } catch {\n await cleanup();\n return null;\n }\n clearPendingAdopt(storageKey);\n recordBackoff(profile, null);\n const { token: _token, gitSyncActor: _actor, ...rest } = profile;\n return { ...rest, auth: held.auth };\n}\n","/**\n * Restores an identity-mode profile's session before a command runs, so the\n * synchronous `getAuthToken()` that plugins call finds a current access\n * token in memory. Literal tokens are left alone, and so is a legacy profile\n * unless an identity profile on the same API base exists: only then is its\n * token checked with the API, and a rejected one is replaced for the process\n * by the one identity profile whose authenticated shop matches the legacy\n * profile's; none or several matching leaves the token alone.\n */\n\nimport chalk from \"chalk\";\n\nimport {\n type FluidProfile,\n type IdentityProfile,\n isClientProfile,\n isIdentityProfile,\n} from \"../../config/types.js\";\nimport { readConfig } from \"../../config/config.js\";\nimport { fetchCompanyShops, validateToken } from \"../fluid-api.js\";\nimport {\n adoptIdentityProfile,\n findIdentityFallbackCandidates,\n findIdentityFallbackProfile,\n resolveCredentialSource,\n} from \"../token.js\";\nimport { adoptLegacyProfile } from \"./adopt-legacy.js\";\nimport { recoverPendingAdopts } from \"./adopt-pending.js\";\nimport { primeClientProfile } from \"./client.js\";\nimport {\n describeIdentityError,\n markIdentityFailureReported,\n primeIdentityProfile,\n profileAccessToken,\n} from \"./session.js\";\n\nexport interface CommandCredentialOptions {\n readonly token?: unknown;\n readonly profile?: unknown;\n readonly json?: unknown;\n readonly format?: unknown;\n}\n\n/**\n * Primes the credential a command with these options would use. A session\n * that cannot be restored is reported on stderr, and the command runs on as\n * it would with no stored credential.\n */\nexport async function primeCommandCredential(\n options: CommandCredentialOptions,\n): Promise<void> {\n if (typeof options.token === \"string\" && options.token) return;\n const profileName =\n typeof options.profile === \"string\" && options.profile\n ? options.profile\n : undefined;\n await recoverPendingAdopts({\n quiet: options.json === true || options.format === \"json\",\n });\n const source = resolveCredentialSource(profileName);\n if (source?.kind !== \"profile\") return;\n let { profile } = source;\n if (\n profile.token &&\n !isIdentityProfile(profile) &&\n !isClientProfile(profile) &&\n !findIdentityFallbackProfile(profile)\n ) {\n const adopted = await adoptLegacyProfile(profile);\n const stored = adopted ?? readConfig().profiles[profile.name];\n if (isIdentityProfile(stored)) profile = stored;\n }\n if (\n (source.origin === \"fluidrc\" || source.origin === \"active\") &&\n !isIdentityProfile(profile) &&\n !isClientProfile(profile)\n ) {\n await adoptFallbackForDeadToken(profile);\n return;\n }\n try {\n if (isIdentityProfile(profile)) await primeIdentityProfile(profile);\n else if (isClientProfile(profile)) await primeClientProfile(profile);\n } catch (error) {\n const message = describeIdentityError(error);\n process.stderr.write(`${chalk.yellow(message)}\\n`);\n markIdentityFailureReported(message);\n }\n}\n\nconst normalizeShop = (shop: string): string =>\n shop\n .toLowerCase()\n .replace(/^https?:\\/\\//, \"\")\n .replace(/\\/.*$/, \"\")\n .replace(/\\.fluid\\.app$/, \"\");\n\nasync function authenticatedShopMatches(\n identity: IdentityProfile,\n wanted: string,\n): Promise<boolean> {\n try {\n await primeIdentityProfile(identity);\n const shops = await fetchCompanyShops(await profileAccessToken(identity), {\n baseUrl: identity.baseUrl,\n });\n return shops.some((shop) => normalizeShop(shop) === wanted);\n } catch {\n return false;\n }\n}\n\nasync function adoptFallbackForDeadToken(profile: FluidProfile): Promise<void> {\n if (!profile.token) return;\n const groups = findIdentityFallbackCandidates(profile);\n if (groups.length === 0) return;\n const checked = await validateToken(\n profile.token,\n profile.baseUrl ? { baseUrl: profile.baseUrl } : {},\n );\n if (checked.success || checked.error.code !== \"INVALID_TOKEN\") return;\n if (!profile.fluidShop) return;\n const wanted = normalizeShop(profile.fluidShop);\n let identity: IdentityProfile | undefined;\n for (const group of groups) {\n const matches: IdentityProfile[] = [];\n for (const candidate of group) {\n if (await authenticatedShopMatches(candidate, wanted)) {\n matches.push(candidate);\n }\n }\n if (matches.length > 1) return;\n if (matches.length === 1) {\n identity = matches[0];\n break;\n }\n }\n if (!identity) return;\n adoptIdentityProfile(identity, profile.name);\n process.stderr.write(\n `${chalk.yellow(\n `The token from profile \"${profile.name}\" was rejected (401); using identity profile \"${identity.name}\" instead.`,\n )}\\n`,\n );\n}\n","#!/usr/bin/env node\n\nimport { createRequire } from \"node:module\";\nimport { realpathSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { Command } from \"commander\";\nimport { commandsCommand } from \"../commands/commands.js\";\nimport { completeCommand, completionCommand } from \"../commands/completion.js\";\nimport { loginCommand } from \"../commands/login.js\";\nimport { signupCommand } from \"../commands/signup.js\";\nimport { logoutCommand } from \"../commands/logout.js\";\nimport { profilesCommand } from \"../commands/profiles.js\";\nimport { whoamiCommand } from \"../commands/whoami.js\";\nimport { switchCommand } from \"../commands/switch.js\";\nimport { versionCommand } from \"../commands/version.js\";\nimport {\n exitOnInputsError,\n inputsModeActive,\n registerInputsHook,\n} from \"../inputs/hook.js\";\nimport { primeCommandCredential } from \"../auth/identity/prime.js\";\nimport { readFdToken } from \"../auth/token.js\";\nimport { loadedPlugins, loadPlugins } from \"../plugins/loader.js\";\nimport { missingPluginHint } from \"../plugins/missing-plugin.js\";\nimport { getConfigDir } from \"../config/paths.js\";\nimport {\n REFRESH_ARG,\n refreshUpdateCache,\n startUpdateCheck,\n type NoticeAudience,\n} from \"../update/notifier.js\";\n\nconst require = createRequire(import.meta.url);\nconst { version } = require(\"../../package.json\") as { version: string };\n\n// The detached update check re-runs this entry point; it only refreshes the\n// cache, without loading plugins or parsing commands.\nif (process.argv[2] === REFRESH_ARG) {\n await refreshUpdateCache(getConfigDir());\n process.exit(0);\n}\n\n// The bearer is read before any plugin is discovered, and with one present\n// only installation plugins load, so no project code runs in this process.\ntry {\n readFdToken();\n} catch (error) {\n console.error(error instanceof Error ? error.message : String(error));\n process.exit(1);\n}\n\nconst packageRoot = process.cwd();\n\nconst program = new Command();\n\nprogram.name(\"fluid\").description(\"Fluid Commerce CLI\").version(version);\n\n// Built-in auth commands, and the signup that comes before them\nprogram.addCommand(signupCommand);\nprogram.addCommand(loginCommand);\nprogram.addCommand(logoutCommand);\nprogram.addCommand(whoamiCommand);\nprogram.addCommand(profilesCommand);\nprogram.addCommand(switchCommand);\n\n// Discovery: the command catalog, versions and shell completion\nprogram.addCommand(commandsCommand);\nprogram.addCommand(versionCommand);\nprogram.addCommand(completionCommand);\nprogram.addCommand(completeCommand, { hidden: true });\n\n// Commands that resolve their own credential, or need none.\nconst selfAuthenticating = new Set(\n [\n signupCommand,\n loginCommand,\n logoutCommand,\n whoamiCommand,\n profilesCommand,\n switchCommand,\n commandsCommand,\n versionCommand,\n completionCommand,\n completeCommand,\n ].map((command) => command.name()),\n);\n\nregisterInputsHook(program);\n\n// Commands that keep the update notice from everyone: completion, and\n// `fluid version`, which reports updates itself.\nconst quietNoticeCommands = new Set<Command>([completeCommand, versionCommand]);\n\n// What the command that runs keeps the update notice from: everyone, for the\n// commands above; an agent, for JSON (`--json`, or a domain command's\n// `--format`, json by default), which it may merge stderr into.\nlet quietFor: NoticeAudience[] = [];\n\n// An identity-mode profile's access token lives only in memory, so restore\n// its session before any other command runs; plugins read the token\n// synchronously through getAuthToken().\nprogram.hook(\"preAction\", async (_program, actionCommand) => {\n const opts = actionCommand.optsWithGlobals();\n if (quietNoticeCommands.has(actionCommand)) quietFor = [\"person\", \"agent\"];\n else if (opts[\"json\"] === true || opts[\"format\"] === \"json\") {\n quietFor = [\"agent\"];\n } else quietFor = [];\n let topLevel: Command = actionCommand;\n while (topLevel.parent && topLevel.parent !== program) {\n topLevel = topLevel.parent;\n }\n if (selfAuthenticating.has(topLevel.name())) return;\n await primeCommandCredential(opts);\n});\n\n// Real path of this entry point: how the CLI was installed.\nconst entryPath = realpathSync(fileURLToPath(import.meta.url));\n\nif (!inputsModeActive(process.env)) {\n startUpdateCheck({\n currentVersion: version,\n configDir: getConfigDir(),\n env: process.env,\n stdoutIsTTY: Boolean(process.stdout.isTTY),\n stderrIsTTY: Boolean(process.stderr.isTTY),\n entryPath,\n versions: process.versions,\n loadedPlugins,\n quiet: (audience) => quietFor.includes(audience),\n });\n}\n\n// Discover and load all plugins (auto-discovered from node_modules and workspace)\nawait loadPlugins(program, packageRoot);\n\nconst missingPlugin = missingPluginHint(program, process.argv.slice(2), {\n entryPath,\n});\nif (missingPlugin) program.error(missingPlugin, { exitCode: 1 });\n\ntry {\n await program.parseAsync(process.argv, { from: \"node\" });\n} catch (error) {\n exitOnInputsError(error);\n throw error;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAa,eAAe;;;;;;AAM5B,MAAa,oBAAoB;;AAGjC,MAAa,cAAc;AAC3B,MAAM,mBAAmB;AACzB,MAAM,aAAa;;;;;;AAMnB,MAAM,qBAAqB;;;;;;AA0B3B,MAAM,YAAY;CAChB;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,SAAS,WAAW,KAAiC;CACnD,OAAO,UAAU,MAAM,SAAS;EAC9B,MAAM,QAAQ,IAAI,KAAK,EAAE,KAAK,CAAC,CAAC,YAAY;EAC5C,OAAO,QAAQ,KAAK,KAAK,UAAU,OAAO,UAAU;CACtD,CAAC;AACH;;AAMA,SAAS,cACP,KACA,WAA4C,CAAC,GACpC;CACT,OAAO,QAAQ,IAAI,2BAA2B,SAAS,WAAW;AACpE;;;;;;AAOA,SAAgB,oBAAoB,EAClC,KACA,aACA,aACA,WACA,YACgD;CAChD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