@rebasepro/cli 0.33.2 → 0.34.0

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.
Files changed (95) hide show
  1. package/dist/{agent-setup-Cg_zBWoW.js → agent-setup-CGeAuP0Q.js} +2 -2
  2. package/dist/{agent-setup-Cg_zBWoW.js.map → agent-setup-CGeAuP0Q.js.map} +1 -1
  3. package/dist/{api-keys-fPQ55DCm.js → api-keys-DaWN8dyI.js} +3 -3
  4. package/dist/{api-keys-fPQ55DCm.js.map → api-keys-DaWN8dyI.js.map} +1 -1
  5. package/dist/{api-TbmW33D7.js → api-zx1wSK5a.js} +2 -2
  6. package/dist/{api-TbmW33D7.js.map → api-zx1wSK5a.js.map} +1 -1
  7. package/dist/{apps-DBTRoOeP.js → apps-D6vtDrkJ.js} +3 -3
  8. package/dist/{apps-DBTRoOeP.js.map → apps-D6vtDrkJ.js.map} +1 -1
  9. package/dist/{auth-BpyYLEFY.js → auth-DY7kU0z-.js} +8 -8
  10. package/dist/{auth-BpyYLEFY.js.map → auth-DY7kU0z-.js.map} +1 -1
  11. package/dist/{auth-session-B6aT0Dyj.js → auth-session-DCG96UGH.js} +4 -4
  12. package/dist/{auth-session-B6aT0Dyj.js.map → auth-session-DCG96UGH.js.map} +1 -1
  13. package/dist/{build-E5hfEWKj.js → build-D0egCUfU.js} +4 -4
  14. package/dist/{build-E5hfEWKj.js.map → build-D0egCUfU.js.map} +1 -1
  15. package/dist/{bundle-CIiKGrte.js → bundle-DhdhtD8K.js} +3 -3
  16. package/dist/{bundle-CIiKGrte.js.map → bundle-DhdhtD8K.js.map} +1 -1
  17. package/dist/{cloud-DNJyUU0T.js → cloud-DOR7bxDw.js} +218 -27
  18. package/dist/cloud-DOR7bxDw.js.map +1 -0
  19. package/dist/{command-Bks5xkrQ.js → command-BzSP5gBh.js} +2 -2
  20. package/dist/{command-Bks5xkrQ.js.map → command-BzSP5gBh.js.map} +1 -1
  21. package/dist/commands/cloud/db-connect.d.ts +31 -1
  22. package/dist/commands/cloud/db-query.d.ts +16 -0
  23. package/dist/commands/cloud/index.d.ts +1 -0
  24. package/dist/commands/cloud/resources.d.ts +19 -1
  25. package/dist/commands/dev.d.ts +15 -0
  26. package/dist/commands/users.d.ts +1 -0
  27. package/dist/{context-BOMEoKxn.js → context-xt20FMFA.js} +5 -1
  28. package/dist/{context-BOMEoKxn.js.map → context-xt20FMFA.js.map} +1 -1
  29. package/dist/{cron-CpUsQ739.js → cron-BGkXIB1N.js} +4 -4
  30. package/dist/{cron-CpUsQ739.js.map → cron-BGkXIB1N.js.map} +1 -1
  31. package/dist/{cron-ZRXsla0v.js → cron-CJ6Xk42E.js} +3 -3
  32. package/dist/{cron-ZRXsla0v.js.map → cron-CJ6Xk42E.js.map} +1 -1
  33. package/dist/{data-BJ9AZFUC.js → data-BpkvtCUe.js} +3 -3
  34. package/dist/{data-BJ9AZFUC.js.map → data-BpkvtCUe.js.map} +1 -1
  35. package/dist/{debug-nNbbxAeo.js → debug-C7Ss34XB.js} +2 -2
  36. package/dist/{debug-nNbbxAeo.js.map → debug-C7Ss34XB.js.map} +1 -1
  37. package/dist/{derive-Mky_u59_.js → derive-ChP6vgfi.js} +2 -2
  38. package/dist/{derive-Mky_u59_.js.map → derive-ChP6vgfi.js.map} +1 -1
  39. package/dist/{dev-bj6dEeSQ.js → dev-C7n36E6f.js} +23 -2
  40. package/dist/dev-C7n36E6f.js.map +1 -0
  41. package/dist/{doctor-FaBObSlb.js → doctor-D0o54XSQ.js} +2 -2
  42. package/dist/{doctor-FaBObSlb.js.map → doctor-D0o54XSQ.js.map} +1 -1
  43. package/dist/{fold-static-2t3UUX4z.js → fold-static-DTpaqbB0.js} +2 -2
  44. package/dist/{fold-static-2t3UUX4z.js.map → fold-static-DTpaqbB0.js.map} +1 -1
  45. package/dist/{function-portability-BIvlvR9q.js → function-portability-Dppl6uqg.js} +24 -5
  46. package/dist/{function-portability-BIvlvR9q.js.map → function-portability-Dppl6uqg.js.map} +1 -1
  47. package/dist/function-portability.d.ts +9 -0
  48. package/dist/{functions-B4JR6EZL.js → functions-DLuuldt2.js} +4 -4
  49. package/dist/{functions-B4JR6EZL.js.map → functions-DLuuldt2.js.map} +1 -1
  50. package/dist/{generate_sdk-ByD-gTsK.js → generate_sdk-UT1lwwRT.js} +2 -2
  51. package/dist/{generate_sdk-ByD-gTsK.js.map → generate_sdk-UT1lwwRT.js.map} +1 -1
  52. package/dist/index.es.js +39 -39
  53. package/dist/{init-DHCe5mJ5.js → init-u5Xmr1Ct.js} +4 -4
  54. package/dist/{init-DHCe5mJ5.js.map → init-u5Xmr1Ct.js.map} +1 -1
  55. package/dist/{logs-DpuMukJe.js → logs-DBYRSs6W.js} +4 -4
  56. package/dist/{logs-DpuMukJe.js.map → logs-DBYRSs6W.js.map} +1 -1
  57. package/dist/{migrate-CSY9ZDKy.js → migrate-Cw1FkvUK.js} +3 -3
  58. package/dist/{migrate-CSY9ZDKy.js.map → migrate-Cw1FkvUK.js.map} +1 -1
  59. package/dist/{normalize-imports-P86NVfpo.js → normalize-imports-E4yA1HfW.js} +2 -2
  60. package/dist/{normalize-imports-P86NVfpo.js.map → normalize-imports-E4yA1HfW.js.map} +1 -1
  61. package/dist/{project-command-Cl9EZzjr.js → project-command-7EGMemEy.js} +5 -5
  62. package/dist/{project-command-Cl9EZzjr.js.map → project-command-7EGMemEy.js.map} +1 -1
  63. package/dist/{resources-Db3USuPO.js → resources-CE6BeL94.js} +2 -2
  64. package/dist/{resources-Db3USuPO.js.map → resources-CE6BeL94.js.map} +1 -1
  65. package/dist/{rls-BxrQ0P50.js → rls-BxWLfEKl.js} +3 -3
  66. package/dist/{rls-BxrQ0P50.js.map → rls-BxWLfEKl.js.map} +1 -1
  67. package/dist/{schema-_FzZEoB8.js → schema-D8xFSBbN.js} +7 -6
  68. package/dist/{schema-_FzZEoB8.js.map → schema-D8xFSBbN.js.map} +1 -1
  69. package/dist/schema-reconcile-D_wvZY91.js +2 -0
  70. package/dist/{schema-show-h72UJ9zH.js → schema-show-C7bY7SgE.js} +3 -3
  71. package/dist/{schema-show-h72UJ9zH.js.map → schema-show-C7bY7SgE.js.map} +1 -1
  72. package/dist/{skills-DQ2bZGkj.js → skills-C8WdRTFg.js} +4 -4
  73. package/dist/{skills-DQ2bZGkj.js.map → skills-C8WdRTFg.js.map} +1 -1
  74. package/dist/{start-Cjx4W0bJ.js → start-CN_9C205.js} +2 -2
  75. package/dist/{start-Cjx4W0bJ.js.map → start-CN_9C205.js.map} +1 -1
  76. package/dist/{status-CDBk25VO.js → status-HWlZbY1E.js} +2 -2
  77. package/dist/{status-CDBk25VO.js.map → status-HWlZbY1E.js.map} +1 -1
  78. package/dist/{storage-Clc8dLG8.js → storage-DBE8lgH-.js} +9 -9
  79. package/dist/{storage-Clc8dLG8.js.map → storage-DBE8lgH-.js.map} +1 -1
  80. package/dist/{storage-objects-CfRKlTDe.js → storage-objects-ljDmtuH7.js} +3 -3
  81. package/dist/{storage-objects-CfRKlTDe.js.map → storage-objects-ljDmtuH7.js.map} +1 -1
  82. package/dist/{users-5PkqBY6R.js → users-DrJEtL9k.js} +9 -6
  83. package/dist/users-DrJEtL9k.js.map +1 -0
  84. package/package.json +10 -10
  85. package/templates/template/.cursorrules +2 -1
  86. package/templates/template/.github/copilot-instructions.md +2 -1
  87. package/templates/template/.windsurfrules +2 -1
  88. package/templates/template/AGENTS.md +2 -1
  89. package/templates/template/CLAUDE.md +2 -1
  90. package/templates/template/ai-instructions.md +5 -2
  91. package/templates/template/frontend/src/index.css +13 -0
  92. package/dist/cloud-DNJyUU0T.js.map +0 -1
  93. package/dist/dev-bj6dEeSQ.js.map +0 -1
  94. package/dist/schema-reconcile-DV14XY4o.js +0 -2
  95. package/dist/users-5PkqBY6R.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"apps-DBTRoOeP.js","names":[],"sources":["../src/commands/apps.ts"],"sourcesContent":["/**\n * CLI command: rebase apps\n *\n * Inspect the apps this repository contributes to a project, adopt a\n * `rebase.json` for a project that predates it, and print the client bootstrap\n * an app needs to reach its backend.\n *\n * The distinction that runs through all of this: a *repository* declares apps,\n * a *project* owns them. Two repositories can contribute to the same project and\n * never know about each other, which is what makes a separate frontend repo — or\n * a mobile app with no repo relationship at all — an ordinary thing rather than\n * a special case.\n */\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport type { RebaseAppConfig, RebaseProjectManifest } from \"@rebasepro/types\";\nimport { failAsJson, requireProjectRoot } from \"../utils/project\";\nimport { devServerUrl, runningBackendUrl } from \"../utils/dev-server\";\nimport { parseCommandArgs, wantsHelp } from \"../utils/args\";\nimport {\n assessManagedCompatibility,\n DEFAULT_TABLES_DIR,\n findBackendApp,\n formatAppAddress,\n loadManifest,\n ManifestError,\n manifestExists,\n staticAppAddress,\n synthesizeManifest,\n writeManifest\n} from \"../manifest\";\nimport { readLink } from \"./cloud/context\";\nimport { unknownCommand } from \"../utils/unknown-command\";\nimport { foldableApps } from \"../fold-static\";\n\nfunction printHelp(): void {\n console.log(`\n${chalk.bold(\"rebase apps\")} — the apps this repository contributes\n\n${chalk.bold(\"Usage\")}\n rebase apps list List declared apps and their build outputs\n rebase apps init Write a rebase.json inferred from this project\n rebase apps config <app> Print the client configuration for an app\n\n${chalk.bold(\"Options\")}\n --json Machine-readable output\n --force Replace an existing rebase.json (apps init), keeping\n each app's name, path and cms\n -h, --help Show this help\n`.trim());\n}\n\n/** Everything the switch below dispatches, for the did-you-mean. */\nexport const APPS_SUBCOMMANDS = [\"list\", \"init\", \"config\"] as const;\n\nexport async function appsCommand(subcommand: string | undefined, rawArgs: string[] = []): Promise<void> {\n // Help is answered before parsing, so `rebase apps config --help` prints the\n // page rather than being rejected for naming no app.\n if (!subcommand || subcommand === \"--help\" || wantsHelp(rawArgs)) {\n printHelp();\n return;\n }\n\n // Only `apps` is a command word here: this one parser serves every\n // subcommand, so the subcommand stays in the positionals and the app name\n // `apps config` takes follows it.\n const { flags: args, positionals } = parseCommandArgs({\n spec: {\n \"--json\": Boolean,\n \"--force\": Boolean\n },\n rawArgs,\n commandWords: 1,\n command: \"apps\",\n maxPositionals: 2\n });\n\n switch (subcommand) {\n case \"list\":\n await listApps(Boolean(args[\"--json\"]));\n break;\n case \"init\":\n if (positionals[1] !== undefined) {\n // It never registered one app: the name was ignored and the\n // whole manifest inferred, which is not what the reader asked for.\n console.error(chalk.red(`✗ rebase apps init takes no app name (got \"${positionals[1]}\").`));\n console.error(chalk.dim(\" It infers every app from this project and writes the whole rebase.json.\"));\n console.error(chalk.dim(\" To add one app, declare it under \\\"apps\\\" in rebase.json.\"));\n process.exit(1);\n }\n await initManifest(Boolean(args[\"--force\"]));\n break;\n case \"config\":\n await printAppConfig(positionals[1], Boolean(args[\"--json\"]));\n break;\n default:\n unknownCommand(subcommand, APPS_SUBCOMMANDS, \"apps\");\n }\n}\n\n/**\n * One app's line in `rebase apps list`.\n *\n * A static app shows its full address — the https URL when its `path` gives it\n * a hostname — and the CMS as the address a browser would open. `CMS at /` on\n * an app that lives on `admin.example.com` reads as the project's own root,\n * which is the one place that CMS is not.\n */\nexport function describeApp(name: string, app: RebaseAppConfig): string {\n switch (app.type) {\n case \"backend\":\n return app.runtime === \"custom\"\n // The context is named only when it is not the project, which is\n // the case where it changes what you would type. A workspace app\n // builds from the workspace root, and a listing that showed only\n // the Dockerfile implied a `docker build .` beside it that fails.\n ? `custom runtime — ${app.dockerfile ?? \"Dockerfile\"}`\n + (app.context && app.context !== \".\" ? ` (context: ${app.context})` : \"\")\n : `managed runtime, tables: ${app.tables ?? DEFAULT_TABLES_DIR}`;\n case \"static\": {\n const address = staticAppAddress(name, app);\n return `${app.root} → ${app.output} @ ${formatAppAddress(address)}`\n + (app.cms ? ` ${chalk.magenta(`CMS at ${formatAppAddress({ ...address, path: app.cms })}`)}` : \"\");\n }\n default:\n return \"\";\n }\n}\n\nasync function listApps(asJson: boolean): Promise<void> {\n const projectRoot = requireProjectRoot();\n const loaded = loadManifestOrExit(projectRoot, asJson);\n const compatibility = assessManagedCompatibility(loaded.manifest);\n\n if (asJson) {\n console.log(JSON.stringify(\n {\n source: loaded.source,\n rebase: loaded.manifest.rebase,\n apps: loaded.manifest.apps,\n managed: compatibility\n },\n null,\n 2\n ));\n return;\n }\n\n if (loaded.source === \"synthesized\") {\n console.log(chalk.dim(\"No rebase.json — showing the layout inferred from this project.\"));\n console.log(chalk.dim(`Run ${chalk.cyan(\"rebase apps init\")} to write it down.\\n`));\n }\n\n console.log(chalk.bold(`Rebase ${loaded.manifest.rebase}`));\n console.log(\"\");\n\n const entries = Object.entries(loaded.manifest.apps);\n if (entries.length === 0) {\n console.log(chalk.yellow(\"No apps declared.\"));\n return;\n }\n\n const width = Math.max(...entries.map(([name]) => name.length));\n for (const [name, app] of entries) {\n console.log(\n ` ${chalk.cyan(name.padEnd(width))} ${chalk.dim(app.type.padEnd(8))} ${describeApp(name, app)}`\n );\n }\n\n console.log(\"\");\n if (compatibility.eligible) {\n console.log(chalk.green(\"✓ Eligible for the managed runtime.\"));\n } else {\n console.log(chalk.yellow(\"• Uses the custom runtime:\"));\n for (const reason of compatibility.reasons) {\n console.log(chalk.dim(` ${reason}`));\n }\n }\n}\n\n/** A static app's `root`, compared as a directory: `./frontend/` is `frontend`. */\nfunction sameRoot(a: string, b: string): boolean {\n const normal = (root: string): string => path.posix.normalize(root.replace(/\\\\/g, \"/\")).replace(/\\/+$/, \"\");\n return normal(a) === normal(b);\n}\n\n/**\n * Re-infer over a manifest the project already declares, keeping what only the\n * declaration knows.\n *\n * An inferred app takes the name the file gives the app it matches — the\n * backend, or the static app with the same `root` — and that app's `path`,\n * `cms`, `routes` and `frameAncestors`. The name is the app's identity on a\n * deployed project, so renaming it would deploy a second app beside the first.\n * `path` can carry the hostname the app is registered on. `cms` is a client-side\n * route that nothing in the project shows, and the routes and the origins that\n * may frame the app are decisions nothing in the project records. Everything\n * else is inferred again, which is what `--force` asks for.\n *\n * A declared app the inference does not find is returned in `removed`, so the\n * command can say so rather than drop it in silence.\n */\nfunction keepDeclaredIdentity(\n inferred: RebaseProjectManifest,\n declared: RebaseProjectManifest\n): { manifest: RebaseProjectManifest; removed: Array<{ name: string; app: RebaseAppConfig }> } {\n const apps: Record<string, RebaseAppConfig> = {};\n const matched = new Set<string>();\n\n for (const [name, app] of Object.entries(inferred.apps)) {\n if (app.type === \"backend\") {\n const backend = findBackendApp(declared);\n const keptName = backend && !matched.has(backend.name) ? backend.name : name;\n matched.add(keptName);\n apps[keptName] = app;\n continue;\n }\n const match = Object.entries(declared.apps).find(([declaredName, candidate]) =>\n !matched.has(declaredName) && candidate.type === \"static\" && sameRoot(candidate.root, app.root));\n const declaredApp = match?.[1];\n if (!match || declaredApp?.type !== \"static\") {\n apps[name] = app;\n continue;\n }\n const keptName = match[0];\n matched.add(keptName);\n const address = declaredApp.path ?? app.path;\n apps[keptName] = {\n ...app,\n ...(address !== undefined ? { path: address } : {}),\n ...(declaredApp.cms !== undefined ? { cms: declaredApp.cms } : {}),\n ...(declaredApp.routes !== undefined ? { routes: declaredApp.routes } : {}),\n ...(declaredApp.frameAncestors !== undefined ? { frameAncestors: declaredApp.frameAncestors } : {})\n };\n }\n\n const removed = Object.entries(declared.apps)\n .filter(([name]) => !matched.has(name))\n .map(([name, app]) => ({ name, app }));\n return { manifest: { ...inferred, apps }, removed };\n}\n\nasync function initManifest(force: boolean): Promise<void> {\n const projectRoot = requireProjectRoot();\n\n let declared: RebaseProjectManifest | undefined;\n if (manifestExists(projectRoot)) {\n if (!force) {\n console.error(chalk.red(\"✗ rebase.json already exists.\"));\n console.error(chalk.dim(\" Pass --force to replace it with an inferred one, keeping each app's name, path and cms.\"));\n process.exit(1);\n }\n try {\n declared = loadManifest(projectRoot).manifest;\n } catch (err) {\n if (!(err instanceof ManifestError)) throw err;\n const issues = err.issues.map(issue => `${issue.path ? `${issue.path}: ` : \"\"}${issue.message}`);\n console.log(chalk.yellow(\"• The existing rebase.json is invalid, so no app name, path or cms in it is kept:\"));\n for (const issue of issues.length > 0 ? issues : [err.message]) console.log(chalk.dim(` ${issue}`));\n }\n }\n\n const inferred = synthesizeManifest(projectRoot);\n const { manifest, removed } = declared\n ? keepDeclaredIdentity(inferred, declared)\n : { manifest: inferred, removed: [] };\n const filePath = writeManifest(projectRoot, manifest);\n\n console.log(chalk.green(`✓ Wrote ${path.relative(projectRoot, filePath)}`));\n console.log(\"\");\n for (const [name, app] of Object.entries(manifest.apps)) {\n console.log(` ${chalk.cyan(name)} ${chalk.dim(`(${app.type})`)}`);\n }\n for (const { name, app } of removed) {\n const where = app.type === \"static\" ? `, root ${app.root}` : \"\";\n console.log(` ${chalk.yellow(name)} ${chalk.dim(`(${app.type}${where})`)} ${chalk.yellow(\"— not found in this project, removed\")}`);\n }\n\n const compatibility = assessManagedCompatibility(manifest);\n if (!compatibility.eligible) {\n console.log(\"\");\n console.log(chalk.yellow(\"This project will use the custom runtime:\"));\n for (const reason of compatibility.reasons) {\n console.log(chalk.dim(` ${reason}`));\n }\n }\n}\n\n/**\n * Print what a client needs to reach this project.\n *\n * Never prints a secret. The API URL and an app's publishable identity are meant\n * to ship inside a client bundle; anything that is not safe there does not belong\n * in output that will inevitably be pasted into a `.env` that gets committed.\n */\nasync function printAppConfig(appName: string | undefined, asJson: boolean): Promise<void> {\n const projectRoot = requireProjectRoot();\n const loaded = loadManifestOrExit(projectRoot, asJson);\n\n if (!appName) {\n if (asJson) {\n failAsJson(\"Which app? Usage: rebase apps config <app>\", \"app_not_named\",\n `Declared: ${Object.keys(loaded.manifest.apps).join(\", \") || \"(none)\"}`);\n }\n console.error(chalk.red(\"✗ Which app? Usage: rebase apps config <app>\"));\n process.exit(1);\n }\n\n const app = loaded.manifest.apps[appName];\n if (!app) {\n if (asJson) {\n failAsJson(`No app named \"${appName}\" in rebase.json.`, \"app_not_found\",\n `Declared: ${Object.keys(loaded.manifest.apps).join(\", \") || \"(none)\"}`);\n }\n console.error(chalk.red(`✗ No app named \"${appName}\" in rebase.json.`));\n console.error(chalk.dim(` Declared: ${Object.keys(loaded.manifest.apps).join(\", \") || \"(none)\"}`));\n process.exit(1);\n }\n\n const link = readLink(projectRoot);\n // An app the backend bundle serves calls the API on its own origin, so the\n // right value is empty — wherever the project is linked, and whatever a\n // dev server once wrote down. A URL here is baked into the build and\n // follows the bundle into production.\n const sameOrigin = servedByBackend(loaded.manifest, appName);\n const apiUrl = sameOrigin ? \"\" : resolveApiUrl(projectRoot, link);\n\n const config = {\n app: appName,\n type: app.type,\n apiUrl: apiUrl ?? null,\n sameOrigin,\n project: link?.projectId ?? link?.slug ?? null\n };\n\n if (asJson) {\n console.log(JSON.stringify(config, null, 2));\n return;\n }\n\n if (sameOrigin) {\n console.log(chalk.bold(`# ${appName}`));\n console.log(\"\");\n console.log(\"VITE_API_URL=\");\n console.log(\"\");\n console.log(chalk.dim(`Empty on purpose: \\`rebase build\\` folds ${appName} into the backend bundle, so it`));\n console.log(chalk.dim(\"calls the API on the same origin it is served from, locally and deployed alike.\"));\n console.log(chalk.dim(\"(`rebase dev` points it at the dev backend by itself.)\"));\n return;\n }\n\n // Whether the checkout is linked is a fact about the link, not about\n // whether `rebase dev` happens to be running: a running dev's address\n // used to fill the same slot, and the notice disappeared with it.\n if (!link?.apiUrl) {\n console.log(chalk.yellow(\"This checkout is not linked to a project yet.\"));\n // `rebase cloud link`, not `rebase link`. There has never been a\n // top-level `link` command — `cli.ts` dispatches `cloud`, and the link\n // lives inside that family — so this hint named something that exits 1\n // on the very screen that exists to tell you what to run next.\n console.log(chalk.dim(` Run ${chalk.cyan(\"rebase cloud link\")} (cloud) or ${chalk.cyan(\"rebase cloud link <url>\")} (self-hosted).`));\n console.log(chalk.dim(` Until then, this is the address ${chalk.cyan(\"rebase dev\")} serves this project on.`));\n console.log(\"\");\n }\n\n console.log(chalk.bold(`# ${appName}`));\n console.log(\"\");\n // Unlinked: the dev backend this project runs on, not a fixed 3001 — `rebase dev`\n // derives a port per project.\n console.log(`VITE_API_URL=${apiUrl ?? devServerUrl(projectRoot).url}`);\n console.log(\"\");\n console.log(chalk.dim(\"Then, in the app:\"));\n console.log(chalk.dim(\" const rebase = createRebaseClient({ baseUrl: import.meta.env.VITE_API_URL });\"));\n}\n\n/**\n * Work out the API base URL for this checkout.\n *\n * Prefers an explicit link, then the dev server's own record of where it bound.\n * The dev port is chosen dynamically, so a hardcoded default would be wrong on\n * any machine running more than one project.\n */\nfunction resolveApiUrl(projectRoot: string, link: ReturnType<typeof readLink>): string | undefined {\n if (link?.apiUrl) return link.apiUrl;\n // Only a dev server that is still running: the state file outlives the\n // process, and a port nothing listens on is not an address.\n return runningBackendUrl(projectRoot) ?? undefined;\n}\n\n/**\n * Whether `rebase build` folds this static app into the backend bundle, which\n * then serves it on the API's own origin: a managed backend, and an app with\n * built output to fold. The same predicate the build folds by.\n */\nexport function servedByBackend(manifest: ReturnType<typeof loadManifest>[\"manifest\"], appName: string): boolean {\n const backend = findBackendApp(manifest);\n if (!backend || backend.app.type !== \"backend\" || backend.app.runtime === \"custom\") return false;\n return foldableApps(manifest).apps.some(app => app.name === appName);\n}\n\nfunction loadManifestOrExit(projectRoot: string, asJson = false): ReturnType<typeof loadManifest> {\n try {\n return loadManifest(projectRoot);\n } catch (err) {\n if (err instanceof ManifestError) {\n // A caller that asked for JSON gets one on this exit too. It used\n // to get the human bullet list on stderr and an empty stdout —\n // `apps list --json` against the one manifest a caller most needs\n // to be told about.\n if (asJson) {\n failAsJson(err.message, \"manifest_invalid\", \"Fix rebase.json, then run this again.\",\n err.issues.map(issue => ({ path: issue.path, message: issue.message })));\n }\n console.error(chalk.red(`✗ ${err.message}`));\n for (const issue of err.issues) {\n console.error(chalk.red(` ${issue.path ? `${issue.path}: ` : \"\"}${issue.message}`));\n }\n process.exit(1);\n }\n throw err;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAmCA,SAAS,YAAkB;CACvB,QAAQ,IAAI;EACd,MAAM,KAAK,aAAa,EAAE;;EAE1B,MAAM,KAAK,OAAO,EAAE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,IAAI,iFAAiF,CAAC;AAC5G;;;;;;;;AASA,SAAS,cAAc,aAAqB,MAAuD;CAC/F,IAAI,MAAM,QAAQ,OAAO,KAAK;CAG9B,OAAO,kBAAkB,WAAW,KAAK,KAAA;AAC7C;;;;;;AAOA,SAAgB,gBAAgB,UAAuD,SAA0B;CAC7G,MAAM,UAAU,eAAe,QAAQ;CACvC,IAAI,CAAC,WAAW,QAAQ,IAAI,SAAS,aAAa,QAAQ,IAAI,YAAY,UAAU,OAAO;CAC3F,OAAO,aAAa,QAAQ,CAAC,CAAC,KAAK,MAAK,QAAO,IAAI,SAAS,OAAO;AACvE;AAEA,SAAS,mBAAmB,aAAqB,SAAS,OAAwC;CAC9F,IAAI;EACA,OAAO,aAAa,WAAW;CACnC,SAAS,KAAK;EACV,IAAI,eAAe,eAAe;GAK9B,IAAI,QACA,WAAW,IAAI,SAAS,oBAAoB,yCACxC,IAAI,OAAO,KAAI,WAAU;IAAE,MAAM,MAAM;IAAM,SAAS,MAAM;GAAQ,EAAE,CAAC;GAE/E,QAAQ,MAAM,MAAM,IAAI,KAAK,IAAI,SAAS,CAAC;GAC3C,KAAK,MAAM,SAAS,IAAI,QACpB,QAAQ,MAAM,MAAM,IAAI,OAAO,MAAM,OAAO,GAAG,MAAM,KAAK,MAAM,KAAK,MAAM,SAAS,CAAC;GAEzF,QAAQ,KAAK,CAAC;EAClB;EACA,MAAM;CACV;AACJ"}
1
+ {"version":3,"file":"apps-D6vtDrkJ.js","names":[],"sources":["../src/commands/apps.ts"],"sourcesContent":["/**\n * CLI command: rebase apps\n *\n * Inspect the apps this repository contributes to a project, adopt a\n * `rebase.json` for a project that predates it, and print the client bootstrap\n * an app needs to reach its backend.\n *\n * The distinction that runs through all of this: a *repository* declares apps,\n * a *project* owns them. Two repositories can contribute to the same project and\n * never know about each other, which is what makes a separate frontend repo — or\n * a mobile app with no repo relationship at all — an ordinary thing rather than\n * a special case.\n */\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport type { RebaseAppConfig, RebaseProjectManifest } from \"@rebasepro/types\";\nimport { failAsJson, requireProjectRoot } from \"../utils/project\";\nimport { devServerUrl, runningBackendUrl } from \"../utils/dev-server\";\nimport { parseCommandArgs, wantsHelp } from \"../utils/args\";\nimport {\n assessManagedCompatibility,\n DEFAULT_TABLES_DIR,\n findBackendApp,\n formatAppAddress,\n loadManifest,\n ManifestError,\n manifestExists,\n staticAppAddress,\n synthesizeManifest,\n writeManifest\n} from \"../manifest\";\nimport { readLink } from \"./cloud/context\";\nimport { unknownCommand } from \"../utils/unknown-command\";\nimport { foldableApps } from \"../fold-static\";\n\nfunction printHelp(): void {\n console.log(`\n${chalk.bold(\"rebase apps\")} — the apps this repository contributes\n\n${chalk.bold(\"Usage\")}\n rebase apps list List declared apps and their build outputs\n rebase apps init Write a rebase.json inferred from this project\n rebase apps config <app> Print the client configuration for an app\n\n${chalk.bold(\"Options\")}\n --json Machine-readable output\n --force Replace an existing rebase.json (apps init), keeping\n each app's name, path and cms\n -h, --help Show this help\n`.trim());\n}\n\n/** Everything the switch below dispatches, for the did-you-mean. */\nexport const APPS_SUBCOMMANDS = [\"list\", \"init\", \"config\"] as const;\n\nexport async function appsCommand(subcommand: string | undefined, rawArgs: string[] = []): Promise<void> {\n // Help is answered before parsing, so `rebase apps config --help` prints the\n // page rather than being rejected for naming no app.\n if (!subcommand || subcommand === \"--help\" || wantsHelp(rawArgs)) {\n printHelp();\n return;\n }\n\n // Only `apps` is a command word here: this one parser serves every\n // subcommand, so the subcommand stays in the positionals and the app name\n // `apps config` takes follows it.\n const { flags: args, positionals } = parseCommandArgs({\n spec: {\n \"--json\": Boolean,\n \"--force\": Boolean\n },\n rawArgs,\n commandWords: 1,\n command: \"apps\",\n maxPositionals: 2\n });\n\n switch (subcommand) {\n case \"list\":\n await listApps(Boolean(args[\"--json\"]));\n break;\n case \"init\":\n if (positionals[1] !== undefined) {\n // It never registered one app: the name was ignored and the\n // whole manifest inferred, which is not what the reader asked for.\n console.error(chalk.red(`✗ rebase apps init takes no app name (got \"${positionals[1]}\").`));\n console.error(chalk.dim(\" It infers every app from this project and writes the whole rebase.json.\"));\n console.error(chalk.dim(\" To add one app, declare it under \\\"apps\\\" in rebase.json.\"));\n process.exit(1);\n }\n await initManifest(Boolean(args[\"--force\"]));\n break;\n case \"config\":\n await printAppConfig(positionals[1], Boolean(args[\"--json\"]));\n break;\n default:\n unknownCommand(subcommand, APPS_SUBCOMMANDS, \"apps\");\n }\n}\n\n/**\n * One app's line in `rebase apps list`.\n *\n * A static app shows its full address — the https URL when its `path` gives it\n * a hostname — and the CMS as the address a browser would open. `CMS at /` on\n * an app that lives on `admin.example.com` reads as the project's own root,\n * which is the one place that CMS is not.\n */\nexport function describeApp(name: string, app: RebaseAppConfig): string {\n switch (app.type) {\n case \"backend\":\n return app.runtime === \"custom\"\n // The context is named only when it is not the project, which is\n // the case where it changes what you would type. A workspace app\n // builds from the workspace root, and a listing that showed only\n // the Dockerfile implied a `docker build .` beside it that fails.\n ? `custom runtime — ${app.dockerfile ?? \"Dockerfile\"}`\n + (app.context && app.context !== \".\" ? ` (context: ${app.context})` : \"\")\n : `managed runtime, tables: ${app.tables ?? DEFAULT_TABLES_DIR}`;\n case \"static\": {\n const address = staticAppAddress(name, app);\n return `${app.root} → ${app.output} @ ${formatAppAddress(address)}`\n + (app.cms ? ` ${chalk.magenta(`CMS at ${formatAppAddress({ ...address, path: app.cms })}`)}` : \"\");\n }\n default:\n return \"\";\n }\n}\n\nasync function listApps(asJson: boolean): Promise<void> {\n const projectRoot = requireProjectRoot();\n const loaded = loadManifestOrExit(projectRoot, asJson);\n const compatibility = assessManagedCompatibility(loaded.manifest);\n\n if (asJson) {\n console.log(JSON.stringify(\n {\n source: loaded.source,\n rebase: loaded.manifest.rebase,\n apps: loaded.manifest.apps,\n managed: compatibility\n },\n null,\n 2\n ));\n return;\n }\n\n if (loaded.source === \"synthesized\") {\n console.log(chalk.dim(\"No rebase.json — showing the layout inferred from this project.\"));\n console.log(chalk.dim(`Run ${chalk.cyan(\"rebase apps init\")} to write it down.\\n`));\n }\n\n console.log(chalk.bold(`Rebase ${loaded.manifest.rebase}`));\n console.log(\"\");\n\n const entries = Object.entries(loaded.manifest.apps);\n if (entries.length === 0) {\n console.log(chalk.yellow(\"No apps declared.\"));\n return;\n }\n\n const width = Math.max(...entries.map(([name]) => name.length));\n for (const [name, app] of entries) {\n console.log(\n ` ${chalk.cyan(name.padEnd(width))} ${chalk.dim(app.type.padEnd(8))} ${describeApp(name, app)}`\n );\n }\n\n console.log(\"\");\n if (compatibility.eligible) {\n console.log(chalk.green(\"✓ Eligible for the managed runtime.\"));\n } else {\n console.log(chalk.yellow(\"• Uses the custom runtime:\"));\n for (const reason of compatibility.reasons) {\n console.log(chalk.dim(` ${reason}`));\n }\n }\n}\n\n/** A static app's `root`, compared as a directory: `./frontend/` is `frontend`. */\nfunction sameRoot(a: string, b: string): boolean {\n const normal = (root: string): string => path.posix.normalize(root.replace(/\\\\/g, \"/\")).replace(/\\/+$/, \"\");\n return normal(a) === normal(b);\n}\n\n/**\n * Re-infer over a manifest the project already declares, keeping what only the\n * declaration knows.\n *\n * An inferred app takes the name the file gives the app it matches — the\n * backend, or the static app with the same `root` — and that app's `path`,\n * `cms`, `routes` and `frameAncestors`. The name is the app's identity on a\n * deployed project, so renaming it would deploy a second app beside the first.\n * `path` can carry the hostname the app is registered on. `cms` is a client-side\n * route that nothing in the project shows, and the routes and the origins that\n * may frame the app are decisions nothing in the project records. Everything\n * else is inferred again, which is what `--force` asks for.\n *\n * A declared app the inference does not find is returned in `removed`, so the\n * command can say so rather than drop it in silence.\n */\nfunction keepDeclaredIdentity(\n inferred: RebaseProjectManifest,\n declared: RebaseProjectManifest\n): { manifest: RebaseProjectManifest; removed: Array<{ name: string; app: RebaseAppConfig }> } {\n const apps: Record<string, RebaseAppConfig> = {};\n const matched = new Set<string>();\n\n for (const [name, app] of Object.entries(inferred.apps)) {\n if (app.type === \"backend\") {\n const backend = findBackendApp(declared);\n const keptName = backend && !matched.has(backend.name) ? backend.name : name;\n matched.add(keptName);\n apps[keptName] = app;\n continue;\n }\n const match = Object.entries(declared.apps).find(([declaredName, candidate]) =>\n !matched.has(declaredName) && candidate.type === \"static\" && sameRoot(candidate.root, app.root));\n const declaredApp = match?.[1];\n if (!match || declaredApp?.type !== \"static\") {\n apps[name] = app;\n continue;\n }\n const keptName = match[0];\n matched.add(keptName);\n const address = declaredApp.path ?? app.path;\n apps[keptName] = {\n ...app,\n ...(address !== undefined ? { path: address } : {}),\n ...(declaredApp.cms !== undefined ? { cms: declaredApp.cms } : {}),\n ...(declaredApp.routes !== undefined ? { routes: declaredApp.routes } : {}),\n ...(declaredApp.frameAncestors !== undefined ? { frameAncestors: declaredApp.frameAncestors } : {})\n };\n }\n\n const removed = Object.entries(declared.apps)\n .filter(([name]) => !matched.has(name))\n .map(([name, app]) => ({ name, app }));\n return { manifest: { ...inferred, apps }, removed };\n}\n\nasync function initManifest(force: boolean): Promise<void> {\n const projectRoot = requireProjectRoot();\n\n let declared: RebaseProjectManifest | undefined;\n if (manifestExists(projectRoot)) {\n if (!force) {\n console.error(chalk.red(\"✗ rebase.json already exists.\"));\n console.error(chalk.dim(\" Pass --force to replace it with an inferred one, keeping each app's name, path and cms.\"));\n process.exit(1);\n }\n try {\n declared = loadManifest(projectRoot).manifest;\n } catch (err) {\n if (!(err instanceof ManifestError)) throw err;\n const issues = err.issues.map(issue => `${issue.path ? `${issue.path}: ` : \"\"}${issue.message}`);\n console.log(chalk.yellow(\"• The existing rebase.json is invalid, so no app name, path or cms in it is kept:\"));\n for (const issue of issues.length > 0 ? issues : [err.message]) console.log(chalk.dim(` ${issue}`));\n }\n }\n\n const inferred = synthesizeManifest(projectRoot);\n const { manifest, removed } = declared\n ? keepDeclaredIdentity(inferred, declared)\n : { manifest: inferred, removed: [] };\n const filePath = writeManifest(projectRoot, manifest);\n\n console.log(chalk.green(`✓ Wrote ${path.relative(projectRoot, filePath)}`));\n console.log(\"\");\n for (const [name, app] of Object.entries(manifest.apps)) {\n console.log(` ${chalk.cyan(name)} ${chalk.dim(`(${app.type})`)}`);\n }\n for (const { name, app } of removed) {\n const where = app.type === \"static\" ? `, root ${app.root}` : \"\";\n console.log(` ${chalk.yellow(name)} ${chalk.dim(`(${app.type}${where})`)} ${chalk.yellow(\"— not found in this project, removed\")}`);\n }\n\n const compatibility = assessManagedCompatibility(manifest);\n if (!compatibility.eligible) {\n console.log(\"\");\n console.log(chalk.yellow(\"This project will use the custom runtime:\"));\n for (const reason of compatibility.reasons) {\n console.log(chalk.dim(` ${reason}`));\n }\n }\n}\n\n/**\n * Print what a client needs to reach this project.\n *\n * Never prints a secret. The API URL and an app's publishable identity are meant\n * to ship inside a client bundle; anything that is not safe there does not belong\n * in output that will inevitably be pasted into a `.env` that gets committed.\n */\nasync function printAppConfig(appName: string | undefined, asJson: boolean): Promise<void> {\n const projectRoot = requireProjectRoot();\n const loaded = loadManifestOrExit(projectRoot, asJson);\n\n if (!appName) {\n if (asJson) {\n failAsJson(\"Which app? Usage: rebase apps config <app>\", \"app_not_named\",\n `Declared: ${Object.keys(loaded.manifest.apps).join(\", \") || \"(none)\"}`);\n }\n console.error(chalk.red(\"✗ Which app? Usage: rebase apps config <app>\"));\n process.exit(1);\n }\n\n const app = loaded.manifest.apps[appName];\n if (!app) {\n if (asJson) {\n failAsJson(`No app named \"${appName}\" in rebase.json.`, \"app_not_found\",\n `Declared: ${Object.keys(loaded.manifest.apps).join(\", \") || \"(none)\"}`);\n }\n console.error(chalk.red(`✗ No app named \"${appName}\" in rebase.json.`));\n console.error(chalk.dim(` Declared: ${Object.keys(loaded.manifest.apps).join(\", \") || \"(none)\"}`));\n process.exit(1);\n }\n\n const link = readLink(projectRoot);\n // An app the backend bundle serves calls the API on its own origin, so the\n // right value is empty — wherever the project is linked, and whatever a\n // dev server once wrote down. A URL here is baked into the build and\n // follows the bundle into production.\n const sameOrigin = servedByBackend(loaded.manifest, appName);\n const apiUrl = sameOrigin ? \"\" : resolveApiUrl(projectRoot, link);\n\n const config = {\n app: appName,\n type: app.type,\n apiUrl: apiUrl ?? null,\n sameOrigin,\n project: link?.projectId ?? link?.slug ?? null\n };\n\n if (asJson) {\n console.log(JSON.stringify(config, null, 2));\n return;\n }\n\n if (sameOrigin) {\n console.log(chalk.bold(`# ${appName}`));\n console.log(\"\");\n console.log(\"VITE_API_URL=\");\n console.log(\"\");\n console.log(chalk.dim(`Empty on purpose: \\`rebase build\\` folds ${appName} into the backend bundle, so it`));\n console.log(chalk.dim(\"calls the API on the same origin it is served from, locally and deployed alike.\"));\n console.log(chalk.dim(\"(`rebase dev` points it at the dev backend by itself.)\"));\n return;\n }\n\n // Whether the checkout is linked is a fact about the link, not about\n // whether `rebase dev` happens to be running: a running dev's address\n // used to fill the same slot, and the notice disappeared with it.\n if (!link?.apiUrl) {\n console.log(chalk.yellow(\"This checkout is not linked to a project yet.\"));\n // `rebase cloud link`, not `rebase link`. There has never been a\n // top-level `link` command — `cli.ts` dispatches `cloud`, and the link\n // lives inside that family — so this hint named something that exits 1\n // on the very screen that exists to tell you what to run next.\n console.log(chalk.dim(` Run ${chalk.cyan(\"rebase cloud link\")} (cloud) or ${chalk.cyan(\"rebase cloud link <url>\")} (self-hosted).`));\n console.log(chalk.dim(` Until then, this is the address ${chalk.cyan(\"rebase dev\")} serves this project on.`));\n console.log(\"\");\n }\n\n console.log(chalk.bold(`# ${appName}`));\n console.log(\"\");\n // Unlinked: the dev backend this project runs on, not a fixed 3001 — `rebase dev`\n // derives a port per project.\n console.log(`VITE_API_URL=${apiUrl ?? devServerUrl(projectRoot).url}`);\n console.log(\"\");\n console.log(chalk.dim(\"Then, in the app:\"));\n console.log(chalk.dim(\" const rebase = createRebaseClient({ baseUrl: import.meta.env.VITE_API_URL });\"));\n}\n\n/**\n * Work out the API base URL for this checkout.\n *\n * Prefers an explicit link, then the dev server's own record of where it bound.\n * The dev port is chosen dynamically, so a hardcoded default would be wrong on\n * any machine running more than one project.\n */\nfunction resolveApiUrl(projectRoot: string, link: ReturnType<typeof readLink>): string | undefined {\n if (link?.apiUrl) return link.apiUrl;\n // Only a dev server that is still running: the state file outlives the\n // process, and a port nothing listens on is not an address.\n return runningBackendUrl(projectRoot) ?? undefined;\n}\n\n/**\n * Whether `rebase build` folds this static app into the backend bundle, which\n * then serves it on the API's own origin: a managed backend, and an app with\n * built output to fold. The same predicate the build folds by.\n */\nexport function servedByBackend(manifest: ReturnType<typeof loadManifest>[\"manifest\"], appName: string): boolean {\n const backend = findBackendApp(manifest);\n if (!backend || backend.app.type !== \"backend\" || backend.app.runtime === \"custom\") return false;\n return foldableApps(manifest).apps.some(app => app.name === appName);\n}\n\nfunction loadManifestOrExit(projectRoot: string, asJson = false): ReturnType<typeof loadManifest> {\n try {\n return loadManifest(projectRoot);\n } catch (err) {\n if (err instanceof ManifestError) {\n // A caller that asked for JSON gets one on this exit too. It used\n // to get the human bullet list on stderr and an empty stdout —\n // `apps list --json` against the one manifest a caller most needs\n // to be told about.\n if (asJson) {\n failAsJson(err.message, \"manifest_invalid\", \"Fix rebase.json, then run this again.\",\n err.issues.map(issue => ({ path: issue.path, message: issue.message })));\n }\n console.error(chalk.red(`✗ ${err.message}`));\n for (const issue of err.issues) {\n console.error(chalk.red(` ${issue.path ? `${issue.path}: ` : \"\"}${issue.message}`));\n }\n process.exit(1);\n }\n throw err;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAmCA,SAAS,YAAkB;CACvB,QAAQ,IAAI;EACd,MAAM,KAAK,aAAa,EAAE;;EAE1B,MAAM,KAAK,OAAO,EAAE;;;;;EAKpB,MAAM,KAAK,SAAS,EAAE;;;;;EAKtB,KAAK,CAAC;AACR;;AAGA,IAAa,mBAAmB;CAAC;CAAQ;CAAQ;AAAQ;AAEzD,eAAsB,YAAY,YAAgC,UAAoB,CAAC,GAAkB;CAGrG,IAAI,CAAC,cAAc,eAAe,YAAY,UAAU,OAAO,GAAG;EAC9D,UAAU;EACV;CAC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,CAAC,WAAW,QAAQ,IAAI,SAAS,aAAa,QAAQ,IAAI,YAAY,UAAU,OAAO;CAC3F,OAAO,aAAa,QAAQ,CAAC,CAAC,KAAK,MAAK,QAAO,IAAI,SAAS,OAAO;AACvE;AAEA,SAAS,mBAAmB,aAAqB,SAAS,OAAwC;CAC9F,IAAI;EACA,OAAO,aAAa,WAAW;CACnC,SAAS,KAAK;EACV,IAAI,eAAe,eAAe;GAK9B,IAAI,QACA,WAAW,IAAI,SAAS,oBAAoB,yCACxC,IAAI,OAAO,KAAI,WAAU;IAAE,MAAM,MAAM;IAAM,SAAS,MAAM;GAAQ,EAAE,CAAC;GAE/E,QAAQ,MAAM,MAAM,IAAI,KAAK,IAAI,SAAS,CAAC;GAC3C,KAAK,MAAM,SAAS,IAAI,QACpB,QAAQ,MAAM,MAAM,IAAI,OAAO,MAAM,OAAO,GAAG,MAAM,KAAK,MAAM,KAAK,MAAM,SAAS,CAAC;GAEzF,QAAQ,KAAK,CAAC;EAClB;EACA,MAAM;CACV;AACJ"}
@@ -1,8 +1,8 @@
1
1
  import { a as redactConnectionPasswords, n as unknownCommand } from "./unknown-command-DnZ2uhGs.js";
2
2
  import { a as wantsHelp, n as parseCommandArgs } from "./args-DHyrshtI.js";
3
3
  import { d as readEnvFile, f as requireBackendDir, g as resolveTsx, o as findEnvFile, p as requireProjectRoot, r as exitDependenciesNotInstalled } from "./project-DALmhb5R.js";
4
- import { _ as resolveBackendAddress, f as cloudTargetNote, l as startProjectCommand } from "./project-command-Cl9EZzjr.js";
5
- import "./api-keys-fPQ55DCm.js";
4
+ import { _ as resolveBackendAddress, f as cloudTargetNote, l as startProjectCommand } from "./project-command-7EGMemEy.js";
5
+ import "./api-keys-DaWN8dyI.js";
6
6
  import chalk from "chalk";
7
7
  import fs from "fs";
8
8
  import path from "path";
@@ -82,31 +82,31 @@ async function authCommand(subcommand, rawArgs) {
82
82
  await resetPassword(rawArgs);
83
83
  break;
84
84
  case "login": {
85
- const { authLogin } = await import("./auth-session-B6aT0Dyj.js");
85
+ const { authLogin } = await import("./auth-session-DCG96UGH.js");
86
86
  startProjectCommand(rawArgs);
87
87
  await authLogin(rawArgs);
88
88
  break;
89
89
  }
90
90
  case "logout": {
91
- const { authLogout } = await import("./auth-session-B6aT0Dyj.js");
91
+ const { authLogout } = await import("./auth-session-DCG96UGH.js");
92
92
  startProjectCommand(rawArgs);
93
93
  await authLogout(rawArgs);
94
94
  break;
95
95
  }
96
96
  case "whoami": {
97
- const { authWhoami } = await import("./auth-session-B6aT0Dyj.js");
97
+ const { authWhoami } = await import("./auth-session-DCG96UGH.js");
98
98
  startProjectCommand(rawArgs);
99
99
  await authWhoami(rawArgs);
100
100
  break;
101
101
  }
102
102
  case "emails": {
103
- const { authEmails } = await import("./auth-session-B6aT0Dyj.js");
103
+ const { authEmails } = await import("./auth-session-DCG96UGH.js");
104
104
  startProjectCommand(rawArgs);
105
105
  await authEmails(rawArgs);
106
106
  break;
107
107
  }
108
108
  case "keys": {
109
- const { authKeys } = await import("./auth-session-B6aT0Dyj.js");
109
+ const { authKeys } = await import("./auth-session-DCG96UGH.js");
110
110
  startProjectCommand(rawArgs);
111
111
  await authKeys(rawArgs);
112
112
  break;
@@ -555,4 +555,4 @@ ${chalk.gray("rebase users reset-password does the same reset on any target (--u
555
555
  //#endregion
556
556
  export { AUTH_SUBCOMMANDS, authCommand };
557
557
 
558
- //# sourceMappingURL=auth-BpyYLEFY.js.map
558
+ //# sourceMappingURL=auth-DY7kU0z-.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"auth-BpyYLEFY.js","names":[],"sources":["../src/commands/auth.ts"],"sourcesContent":["/**\n * CLI command: rebase auth <action>\n *\n * Subcommands:\n * reset-password — Reset a user's password (HTTP first, the database as a fallback)\n * login, logout, whoami — a person's session on a running app (`auth-session.ts`)\n * emails — the development mailbox\n * keys — your own personal API keys\n */\nimport chalk from \"chalk\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport { spawn } from \"child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport {\n requireProjectRoot,\n requireBackendDir,\n findEnvFile,\n readEnvFile,\n resolveTsx,\n exitDependenciesNotInstalled\n} from \"../utils/project\";\nimport { parseEnvBoolean } from \"@rebasepro/types\";\nimport { unknownCommand } from \"../utils/unknown-command\";\nimport { redactConnectionPasswords } from \"../utils/redact\";\nimport type { PreparedDatabase } from \"../dev-db/prepare\";\nimport type { DevDatabaseSource } from \"../dev-db/resolve\";\n\n/** The backend was reached and refused: not a reason to fall back to the database. */\nclass ApiAnswered extends Error {}\n\n/** Everything the switch below dispatches, for the did-you-mean. */\nexport const AUTH_SUBCOMMANDS = [\"reset-password\", \"login\", \"logout\", \"whoami\", \"emails\", \"keys\"] as const;\nimport { parseCommandArgs, wantsHelp } from \"../utils/args\";\nimport { startProjectCommand } from \"../utils/project-command\";\nimport { cloudTargetNote, resolveBackendAddress } from \"./api-keys\";\n\n/** A user as the admin API returns it, reduced to what this command needs. */\nexport interface ResolvedUser {\n id: string;\n email: string;\n}\n\n/**\n * Pick the user with exactly this email out of a search response.\n *\n * `/api/admin/users?search=` is an `ILIKE '%…%'` over email **or display\n * name**, ordered by role count descending. This used to take row `[0]` and\n * reset it, then print the email it had been *given* as confirmation — so two\n * ordinary situations ended in a successful-looking reset of somebody else's\n * account:\n *\n * - a substring collision: `bob@example.com` also matches\n * `robert.bob@example.com`;\n * - a display name, which is user-controlled and accepted up to 255\n * characters with no constraint on its content, containing an address\n * belonging to someone else.\n *\n * The ordering makes it worse rather than better — `array_length(roles) DESC\n * NULLS LAST` puts the most privileged match first, so the account most likely\n * to be reset by mistake is an admin's.\n *\n * Returns `undefined` when nothing matched exactly, which the caller reports\n * rather than falling through to a guess. The direct-database fallback below\n * has always matched with `eq(usersTable.email, email)`; this is the same\n * definition, so the command no longer resets different accounts depending on\n * whether the backend happened to be running.\n */\nexport function selectUserForEmail(payload: unknown, email: string): ResolvedUser | undefined {\n const wanted = email.trim().toLowerCase();\n if (!wanted) return undefined;\n\n const rows: unknown[] = Array.isArray(payload)\n ? payload\n : (payload && typeof payload === \"object\" && Array.isArray((payload as { users?: unknown }).users)\n ? (payload as { users: unknown[] }).users\n : []);\n\n for (const row of rows) {\n if (!row || typeof row !== \"object\") continue;\n const record = row as Record<string, unknown>;\n const rowEmail = typeof record.email === \"string\" ? record.email.trim().toLowerCase() : undefined;\n if (!rowEmail || rowEmail !== wanted) continue;\n\n const id = typeof record.id === \"string\"\n ? record.id\n : (typeof record.uid === \"string\" ? record.uid : undefined);\n if (!id) continue;\n\n return { id, email: record.email as string };\n }\n\n return undefined;\n}\n\nexport async function authCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n // `--help` is answered here and never reaches a handler. `cli.ts` only\n // rewrites the subcommand to `\"--help\"` when no subcommand was named, so\n // `rebase auth reset-password --help` used to *run the reset*: `--help`\n // became the email, the backend was contacted, `.tmp-reset-password.ts` was\n // written into the user's `backend/`, and a database UPDATE ran for a user\n // named `--help`. A flag whose whole job is to print text cannot be allowed\n // to reach code that writes.\n if (!subcommand || subcommand === \"--help\" || wantsHelp(rawArgs)) {\n printAuthHelp();\n return;\n }\n\n switch (subcommand) {\n case \"reset-password\":\n await resetPassword(rawArgs);\n break;\n case \"login\": {\n const { authLogin } = await import(\"./auth-session\");\n startProjectCommand(rawArgs);\n await authLogin(rawArgs);\n break;\n }\n case \"logout\": {\n const { authLogout } = await import(\"./auth-session\");\n startProjectCommand(rawArgs);\n await authLogout(rawArgs);\n break;\n }\n case \"whoami\": {\n const { authWhoami } = await import(\"./auth-session\");\n startProjectCommand(rawArgs);\n await authWhoami(rawArgs);\n break;\n }\n case \"emails\": {\n const { authEmails } = await import(\"./auth-session\");\n startProjectCommand(rawArgs);\n await authEmails(rawArgs);\n break;\n }\n case \"keys\": {\n const { authKeys } = await import(\"./auth-session\");\n startProjectCommand(rawArgs);\n await authKeys(rawArgs);\n break;\n }\n default:\n unknownCommand(subcommand, AUTH_SUBCOMMANDS, \"auth\");\n }\n}\n\n/**\n * The flags `rebase auth reset-password` takes.\n *\n * `-p` was advertised in this command's own help and never declared here, so\n * `arg` — running permissively — pushed it into the positionals and the value\n * *after* it shifted out of reach: anyone following the help set the account's\n * password to the two-character string `-p`. Declared now, and `auth.test.ts`\n * asserts that the help and this spec list the same aliases.\n */\nexport const RESET_PASSWORD_FLAGS = {\n \"--email\": String,\n \"--password\": String,\n \"-e\": \"--email\",\n \"-p\": \"--password\"\n} as const;\n\n/**\n * Which account, and which password, this invocation names.\n *\n * Both may still be absent — the caller reports a missing email — but neither\n * can be a flag. `parseCommandArgs` parses the whole line strictly, so an\n * undeclared flag is an error rather than a positional. That is what stops\n * `rebase auth reset-password bob@example.com --debug` from setting Bob's\n * password to `--debug`, which is the flag the CLI itself prints after every\n * failure as the thing to re-run with.\n *\n * Exported so its tests can drive the real parser rather than a copy of it.\n */\nexport function resolveResetPasswordArgs(rawArgs: string[]): {\n email?: string;\n password?: string;\n} {\n const { flags, positionals } = parseCommandArgs({\n spec: RESET_PASSWORD_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"auth reset-password\",\n maxPositionals: 2\n });\n\n // Everywhere else in the CLI `-p` is `--project`. Here it has always been\n // `--password`, and it keeps working — with one warning per run naming the\n // spelling that will not change.\n if (rawArgs.slice(2).includes(\"-p\")) {\n process.stderr.write(chalk.yellow(\" ⚠ -p is deprecated in `rebase auth reset-password`: use --password (elsewhere -p means --project).\\n\"));\n }\n\n // Both spellings are supported: `<email> [password]` and `--email/--password`.\n return {\n email: flags[\"--email\"] || positionals[0],\n password: flags[\"--password\"] || positionals[1]\n };\n}\n\n/**\n * A password for a reset that was not given one.\n *\n * This used to be a constant, and `--help` printed it as the default. Reset is\n * the documented way back into an account nobody can sign in to — an admin,\n * usually — so the recovery path set every such account to a fixed string that\n * ships inside a public repository and a published npm package, and left it\n * there until somebody remembered to change it.\n *\n * base64url of 18 random bytes: 24 characters, ~144 bits, no shell-quoting\n * hazard, and nothing that reads like a placeholder somebody might keep.\n */\nexport function generatePassword(): string {\n return randomBytes(18).toString(\"base64url\");\n}\n\n/**\n * What a refusing backend said, from its `{ error: { message, code } }` body.\n *\n * The body used to be printed as it came, so a weak password read\n * `{\"error\":{\"message\":\"…\",\"code\":\"…\"}}`. A body that is not the envelope is\n * still shown, since it is the only account of the refusal there is.\n */\nasync function refusalReason(response: Response): Promise<string> {\n const text = await response.text().catch(() => \"\");\n try {\n const parsed: unknown = JSON.parse(text);\n const error = parsed && typeof parsed === \"object\" && \"error\" in parsed ? parsed.error : undefined;\n if (error && typeof error === \"object\" && \"message\" in error && typeof error.message === \"string\") {\n const code = \"code\" in error && typeof error.code === \"string\" ? ` (${error.code})` : \"\";\n return `${error.message}${code}`;\n }\n } catch {\n // Not JSON: the text is the answer.\n }\n return text.trim() || `${response.status} ${response.statusText}`.trim();\n}\n\nasync function resetPassword(rawArgs: string[]): Promise<void> {\n const { email, password: providedPassword } = resolveResetPasswordArgs(rawArgs);\n // Generated once, so both reset paths set and report the same thing.\n const wasGenerated = !providedPassword;\n const newPassword = providedPassword || generatePassword();\n\n if (!email) {\n console.error(chalk.red(\"✗ Email is required.\"));\n console.log(\"\");\n console.log(chalk.gray(\" Usage: rebase auth reset-password <email> [new-password]\"));\n console.log(chalk.gray(\" rebase auth reset-password --email user@example.com --password NewPass123!\"));\n process.exit(1);\n }\n\n const projectRoot = requireProjectRoot();\n\n // 1. Try API-first reset\n // Was a single-key regex, which did not match `export REBASE_SERVICE_KEY=…`\n // and kept a trailing `# comment` in the value. The command then fell\n // through to the direct-database path as though no key were configured.\n const envFile = findEnvFile(projectRoot);\n const envServiceKey: string | undefined = readEnvFile(projectRoot).REBASE_SERVICE_KEY;\n\n let serviceKey = process.env.REBASE_SERVICE_KEY || envServiceKey;\n\n const statePath = path.join(projectRoot, \".rebase\", \"state.json\");\n if (fs.existsSync(statePath)) {\n try {\n const state = JSON.parse(fs.readFileSync(statePath, \"utf8\")) as Record<string, unknown>;\n if (state && typeof state === \"object\" && typeof state.serviceKey === \"string\" && !serviceKey) {\n serviceKey = state.serviceKey;\n }\n } catch {\n // Ignore\n }\n }\n\n // Where the service key may go: a REBASE_BASE_URL the developer named, or\n // this project's backend while the pid that recorded it is alive — see\n // `resolveBackendAddress`. `.rebase/state.json`'s address on its own, and\n // `.rebase-dev-url`, outlive a killed `rebase dev`, and the port they name\n // may be another server's by now. With neither, the reset goes to the\n // database directly.\n const address = resolveBackendAddress(readEnvFile(projectRoot), projectRoot);\n const cloudNote = cloudTargetNote(address);\n if (cloudNote) console.error(chalk.yellow(` ⚠ ${cloudNote}`));\n const baseUrl = address.url;\n\n if (baseUrl && serviceKey) {\n console.log(\"Trying API-first reset via running backend...\");\n try {\n const finalPass = newPassword;\n const cleanBaseUrl = baseUrl.replace(/\\/+$/, \"\");\n // Not `limit=1`: the search is fuzzy and ordered by role count, so\n // the exact match is not necessarily first — asking for one row can\n // make it unreachable. Ask for a page, then match exactly.\n const searchUrl = `${cleanBaseUrl}/api/admin/users?search=${encodeURIComponent(email)}&limit=50`;\n const searchRes = await fetch(searchUrl, {\n headers: {\n \"Authorization\": `Bearer ${serviceKey}`,\n \"Accept\": \"application/json\"\n }\n });\n if (!searchRes.ok) {\n throw new ApiAnswered(`Failed to list users: ${searchRes.status} ${searchRes.statusText}`);\n }\n const searchData = await searchRes.json() as unknown;\n if (!searchData || typeof searchData !== \"object\") {\n throw new Error(\"Invalid response format from user search API.\");\n }\n\n const matched = selectUserForEmail(searchData, email);\n if (!matched) {\n throw new ApiAnswered(`No user has the email ${email}.`);\n }\n\n const resetUrl = `${cleanBaseUrl}/api/admin/users/${matched.id}/reset-password`;\n const resetRes = await fetch(resetUrl, {\n method: \"POST\",\n headers: {\n \"Authorization\": `Bearer ${serviceKey}`,\n \"Content-Type\": \"application/json\",\n \"Accept\": \"application/json\"\n },\n body: JSON.stringify({ password: finalPass })\n });\n\n if (!resetRes.ok) {\n throw new ApiAnswered(`Password reset refused: ${await refusalReason(resetRes)}`);\n }\n\n console.log(\"API reset successful.\");\n console.log(chalk.bold(\" 🔑 Rebase Auth — Reset Password (via API)\"));\n console.log(\"\");\n // The address as stored, not as typed — they differ in case often\n // enough that echoing the input hides which account was touched.\n console.log(` ${chalk.gray(\"Email:\")} ${matched.email}`);\n // Echoed only when we invented it. A password the operator typed\n // is already theirs; printing it again only adds scrollback.\n console.log(` ${chalk.gray(\"Password:\")} ${wasGenerated ? finalPass : \"*\".repeat(finalPass.length)}`);\n console.log(\"\");\n return;\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n // The backend answered and said no — a password too weak, a user\n // it does not have. That answer stands: writing the hash straight\n // into the database instead skipped the strength rule it had just\n // applied, and ended no sessions. Only a backend that could not be\n // reached is a reason to go round it.\n if (err instanceof ApiAnswered) {\n console.error(chalk.red(`✗ ${errMsg}`));\n process.exitCode = 1;\n return;\n }\n console.warn(chalk.yellow(\"API reset failed, falling back to direct database update...\"));\n console.warn(chalk.gray(` Details: ${errMsg}`));\n }\n }\n\n // 2. Direct-DB Fallback\n const backendDir = requireBackendDir(projectRoot);\n const tsxBin = resolveTsx(projectRoot);\n\n if (!tsxBin) {\n exitDependenciesNotInstalled(projectRoot);\n }\n\n // The database the `db` family would use, resolved — and, for a remembered\n // compose container that is stopped, started — the same way. A stock\n // scaffold leaves DATABASE_URL commented out and runs on the managed\n // database, which only exists in a child's environment when something puts\n // it there — without this the script connected with libpq's defaults,\n // localhost:5432 as the OS user. An external DATABASE_URL adds nothing\n // here: the child already reads it.\n let prepared: PreparedDatabase;\n try {\n const { ensureDockerDatabase } = await import(\"./db\");\n await ensureDockerDatabase(projectRoot, rawArgs);\n const { prepareDatabaseEnv } = await import(\"../dev-db/prepare\");\n prepared = await prepareDatabaseEnv(projectRoot, {\n onProgress: (message) => console.log(chalk.gray(` ${message}`))\n });\n } catch (err) {\n console.error(chalk.red(\"✗ Direct database update failed.\"));\n console.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n\n // Opened here first, so a database that does not answer gets the banner\n // every other command prints — not the script's raw error and stack — and\n // no script is written for it.\n const { databaseUrlOf } = await import(\"./db\");\n const url = databaseUrlOf(prepared, readEnvFile(projectRoot));\n if (url) {\n const failure = await databaseOpenFailure(url, prepared.database.source);\n if (failure) {\n for (const line of failure) console.error(line);\n process.exit(1);\n }\n }\n\n try {\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n env.REBASE_RESET_EMAIL = email;\n env.REBASE_RESET_PASSWORD = newPassword;\n env.REBASE_ENV_FILE_PATH = envFile || path.join(projectRoot, \".env\");\n Object.assign(env, prepared.env);\n\n const scriptContent = resetPasswordScript(wasGenerated, parseEnvBoolean(process.env.REBASE_DEBUG) === true);\n\n const tmpScriptPath = path.join(backendDir, \".tmp-reset-password.ts\");\n fs.writeFileSync(tmpScriptPath, scriptContent, \"utf-8\");\n\n console.log(\"\");\n console.log(chalk.bold(\" 🔑 Rebase Auth — Reset Password (Direct DB Fallback)\"));\n console.log(\"\");\n console.log(` ${chalk.gray(\"Email:\")} ${email}`);\n console.log(` ${chalk.gray(\"Database:\")} ${prepared.description}`);\n if (!wasGenerated) {\n console.log(` ${chalk.gray(\"Password:\")} ${\"*\".repeat(newPassword.length)}`);\n }\n console.log(\"\");\n\n const child = spawn(tsxBin, [tmpScriptPath], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n\n // The script is written into the user's backend directory, so every\n // exit has to remove it. Without an `error` handler a failed spawn\n // raises an unhandled event, the process dies before `close`, and\n // `.tmp-reset-password.ts` is left behind to be committed.\n const cleanup = () => {\n try { fs.unlinkSync(tmpScriptPath); } catch { /* already gone */ }\n };\n\n return new Promise((resolve) => {\n child.on(\"error\", (err) => {\n cleanup();\n console.error(chalk.red(\"✗ Could not run the reset script.\"));\n console.error(chalk.gray(` ${err.message}`));\n process.exit(1);\n });\n child.on(\"close\", (code) => {\n cleanup();\n if (code !== 0) {\n process.exit(code ?? 1);\n }\n resolve();\n });\n });\n } catch (err) {\n console.error(chalk.red(\"✗ Direct database update failed.\"));\n console.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n}\n\n/**\n * Why the database the fallback would reset in cannot be opened, as the lines\n * to print — or null when it opens.\n *\n * A stopped database, refused credentials and a database name the server does\n * not have get the boxed banner the other commands print; anything else is one\n * sentence. Either way the password was not reset and no script was written.\n */\nasync function databaseOpenFailure(url: string, source: DevDatabaseSource): Promise<string[] | null> {\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString: url, connectionTimeoutMillis: 10_000 });\n client.on(\"error\", () => undefined);\n try {\n await client.connect();\n await client.query(\"SELECT 1\");\n return null;\n } catch (error) {\n const { connectionErrorText, connectionFailureBanner, connectionRefusedFixes } =\n await import(\"../dev-db/connection-banner\");\n const consequence = \"The password was not reset.\";\n return connectionFailureBanner(url, error, { consequence, fixes: connectionRefusedFixes(source) }) ?? [\n chalk.red(`✗ Could not open the database: ${redactConnectionPasswords(connectionErrorText(error))}`),\n chalk.gray(` ${consequence}`)\n ];\n } finally {\n await client.end().catch(() => undefined);\n }\n}\n\n/**\n * The script the direct-database fallback runs under the project's own tsx, so\n * it resolves the project's `@rebasepro/server-postgres` and schema.\n *\n * It ends the account's sessions in the transaction that sets the password,\n * as every door through the API does (`replaceUserPassword`): the refresh\n * tokens and outstanding reset links go, and `tokens_valid_after` voids the\n * access tokens already handed out. An operator resetting a phished account\n * with the backend down is the case this exists for, and a reset that left the\n * attacker's refresh token minting access tokens did not recover anything.\n *\n * It exits 0 only when a row was updated: a missing user and a thrown error are\n * both exit 1. `echoPassword` prints the new password, for a generated one;\n * `showStack` prints a failure's stack rather than its sentence (`--debug`).\n *\n * Exported so its tests can run it.\n */\nexport function resetPasswordScript(echoPassword: boolean, showStack = false): string {\n return `\nimport { createPostgresDatabaseConnection } from \"@rebasepro/server-postgres\";\nimport { hashPassword } from \"@rebasepro/server\";\nimport { getTableConfig } from \"drizzle-orm/pg-core\";\nimport * as dotenv from \"dotenv\";\nimport path from \"path\";\nimport fs from \"fs\";\n\ndotenv.config({ path: process.env.REBASE_ENV_FILE_PATH, quiet: true });\n\n// Lowercased, as every address is stored (\\`normalizeEmail\\`): matched as\n// typed, \"Ops@Acme.test\" found no row.\nconst email = process.env.REBASE_RESET_EMAIL!.trim().toLowerCase();\nconst newPassword = process.env.REBASE_RESET_PASSWORD!;\n\nconst quote = (identifier: string) => '\"' + identifier.replace(/\"/g, '\"\"') + '\"';\n\nasync function resetPassword() {\n const { pool } = createPostgresDatabaseConnection(process.env.DATABASE_URL!);\n const hash = await hashPassword(newPassword);\n\n let usersTable;\n try {\n const schemaPath = path.resolve(\"./src/schema.generated.ts\");\n if (fs.existsSync(schemaPath)) {\n const schema = await import(\"file://\" + schemaPath);\n usersTable = schema.users || schema.tables?.users;\n }\n } catch (e) {\n // ignore and fallback\n }\n\n if (!usersTable) {\n const pgServer = await import(\"@rebasepro/server-postgres\");\n usersTable = pgServer.users;\n }\n\n // The physical names, from the table object: the collection may map its\n // properties to other columns, and the statements below are plain SQL.\n const { name: tableName, schema: tableSchema } = getTableConfig(usersTable);\n const usersSchema = tableSchema || \"public\";\n const users = quote(usersSchema) + \".\" + quote(tableName);\n const idColumn = quote(usersTable.id.name);\n const emailColumn = quote(usersTable.email.name);\n const passwordColumn = quote((usersTable.passwordHash ?? usersTable.password_hash).name);\n // Where \\`ensureAuthTablesExist\\` puts the tables that hang off the users\n // table: beside it, or in \\`rebase\\` when it lives in \\`public\\`.\n const authSchema = usersSchema === \"public\" ? \"rebase\" : usersSchema;\n\n const client = await pool.connect();\n try {\n // A database nothing has booted against — or a managed one \\`db reset\\`\n // emptied — has no users table, and so no account to reset. Said as\n // that, not as pg's \\`relation … does not exist\\`.\n const usersTable = await client.query(\"SELECT to_regclass($1) IS NOT NULL AS present\", [users]);\n if (!usersTable.rows[0]?.present) {\n console.error(\"✗ \" + users + \" does not exist in this database, so it holds no account to reset.\");\n console.error(\" Nothing was changed. \\`rebase dev\\` creates it the first time it boots against this database.\");\n process.exit(1);\n }\n\n await client.query(\"BEGIN\");\n const updated = await client.query(\n \"UPDATE \" + users + \" SET \" + passwordColumn + \" = $1 WHERE \" + emailColumn + \" = $2 \" +\n \"RETURNING \" + idColumn + \" AS id, \" + emailColumn + \" AS email\",\n [hash, email]\n );\n if (updated.rows.length === 0) {\n await client.query(\"ROLLBACK\");\n // Nothing was updated, so nothing was reset. Exiting 0 here reported\n // success for a no-op, which is what a script would have believed.\n console.error(\"✗ User not found: \" + email);\n process.exit(1);\n }\n const uid = updated.rows[0].id;\n\n // A table or column the server has not created yet (it never booted\n // against this database) holds no session to end.\n const watermark = await client.query(\n \"SELECT 1 FROM information_schema.columns WHERE table_schema = $1 AND table_name = $2 AND column_name = 'tokens_valid_after'\",\n [usersSchema, tableName]\n );\n if (watermark.rows.length > 0) {\n await client.query(\"UPDATE \" + users + \" SET tokens_valid_after = NOW() WHERE \" + idColumn + \" = $1\", [uid]);\n }\n for (const table of [\"refresh_tokens\", \"password_reset_tokens\"]) {\n const qualified = quote(authSchema) + \".\" + quote(table);\n const present = await client.query(\"SELECT to_regclass($1) IS NOT NULL AS present\", [qualified]);\n if (present.rows[0]?.present) {\n await client.query(\"DELETE FROM \" + qualified + \" WHERE uid = $1\", [uid]);\n }\n }\n await client.query(\"COMMIT\");\n\n console.log(\"✅ Password reset for: \" + updated.rows[0].email);\n console.log(\" Every session of this account has ended.\");\n ${echoPassword ? 'console.log(\" Password: \" + newPassword);' : \"\"}\n process.exit(0);\n } catch (error) {\n await client.query(\"ROLLBACK\").catch(() => undefined);\n throw error;\n } finally {\n client.release();\n }\n}\n\n// A thrown error is a failed reset, and exits like one — a refused connection\n// that exits 0 reads as a reset to anything checking the exit code. Said as a\n// sentence: the stack is the script's own, and only --debug asks for it.\nconst describe = (error: unknown): string => {\n if (error instanceof AggregateError && !error.message && error.errors.length > 0) return describe(error.errors[0]);\n const message = error instanceof Error ? error.message : String(error);\n const code = error && typeof error === \"object\" && \"code\" in error && typeof error.code === \"string\" ? error.code : \"\";\n return code && !message.includes(code) ? message + \" (\" + code + \")\" : message;\n};\nresetPassword().catch((error) => {\n ${showStack ? \"console.error(error);\" : \"console.error(\\\"✗ The password was not reset: \\\" + describe(error));\"}\n process.exit(1);\n});\n`;\n}\n\nfunction printAuthHelp() {\n console.log(`\n${chalk.bold(\"rebase auth\")} — Authentication: a person's session on a running app, resets, the dev mailbox\n\n${chalk.green.bold(\"Usage\")}\n rebase auth ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"reset-password\")} Reset a user's password ${chalk.gray(\"(the running server, else the database directly)\")}\n ${chalk.blue.bold(\"login\")} Sign in to a running app as a person; the session is kept in ~/.rebase/sessions.json\n ${chalk.blue.bold(\"logout\")} End that session, here and on the server\n ${chalk.blue.bold(\"whoami\")} Who the server takes you to be, and the scopes you hold\n ${chalk.blue.bold(\"emails\")} The development mailbox: the auth mail a server with no SMTP_HOST captured\n ${chalk.blue.bold(\"keys\")} Your own personal API keys: list, create, revoke ${chalk.gray(\"(needs auth.personalKeys)\")}\n\n${chalk.green.bold(\"reset-password Options\")}\n ${chalk.blue(\"--email, -e\")} User's email address\n ${chalk.blue(\"--password\")} New password (default: one is generated and printed)\n ${chalk.gray(\"-p still works for --password here, and warns: elsewhere -p means --project\")}\n\n${chalk.green.bold(\"login Options\")}\n ${chalk.blue(\"--email <address>\")} Sign in with this account's password (asked for at a terminal)\n ${chalk.blue(\"--password <pass>\")} The password, for scripts\n ${chalk.blue(\"--code <code>\")} The second factor, when the account has two-factor authentication on\n ${chalk.blue(\"--web\")} Sign in through the browser (the server's device sign-in) ${chalk.gray(\"— the default when it offers one\")}\n ${chalk.blue(\"--no-browser\")} Print the browser link instead of opening it\n\n${chalk.green.bold(\"emails Options\")}\n ${chalk.blue(\"--latest\")} Only the newest message\n ${chalk.blue(\"--to <address>\")} Only messages to this address\n ${chalk.blue(\"--links\")} Print only the links, one per line\n ${chalk.blue(\"--clear\")} Empty the mailbox\n\n${chalk.green.bold(\"keys Options\")} ${chalk.gray(\"rebase auth keys [list|create|revoke <id>]\")}\n ${chalk.blue(\"--name <name>\")} The new key's name\n ${chalk.blue(\"--scopes <scopes>\")} What it may do, e.g. data:read:posts (never more than you hold)\n ${chalk.blue(\"--expires-in <days>\")} When it stops working\n\n${chalk.green.bold(\"Target options\")} ${chalk.gray(\"(login, logout, whoami, emails, keys)\")}\n ${chalk.blue(\"--project <slug>\")} A Rebase Cloud project (login goes to the app's own address)\n ${chalk.blue(\"--cloud\")} The Rebase Cloud project this directory is linked to\n ${chalk.blue(\"--url <server>\")} A server at this address (else REBASE_BASE_URL, then \\`rebase dev\\`)\n ${chalk.blue(\"--token <bearer>\")} Send this bearer instead (whoami, emails)\n ${chalk.blue(\"--session\")} Send the stored session (whoami and keys do by default)\n ${chalk.blue(\"--anon\")} Send no credential\n ${chalk.blue(\"--json\")} Machine-readable output (also when piped)\n ${chalk.blue(\"--yes\")} Skip confirmation prompts\n\n${chalk.green.bold(\"Examples\")}\n rebase auth reset-password user@example.com\n rebase auth reset-password --email user@example.com --password MyNewPass!\n rebase auth login --email ada@example.com\n rebase auth emails --latest --links\n\n${chalk.gray(\"rebase users reset-password does the same reset on any target (--url, --project); this one also works with the server stopped.\")}\n`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA6BA,IAAM,cAAN,cAA0B,MAAM,CAAC;;AAGjC,IAAa,mBAAmB;CAAC;CAAkB;CAAS;CAAU;CAAU;CAAU;AAAM;;;;;;;;;;;;;;;;;;;;;;;;;;AAoChG,SAAgB,mBAAmB,SAAkB,OAAyC;CAC1F,MAAM,SAAS,MAAM,KAAK,CAAC,CAAC,YAAY;CACxC,IAAI,CAAC,QAAQ,OAAO,KAAA;CAEpB,MAAM,OAAkB,MAAM,QAAQ,OAAO,IACvC,UACC,WAAW,OAAO,YAAY,YAAY,MAAM,QAAS,QAAgC,KAAK,IAC1F,QAAiC,QAClC,CAAC;CAEX,KAAK,MAAM,OAAO,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MAAM,KAAK,SAAS,EAAE;IACtB,MAAM,KAAK,SAAS,EAAE;;EAExB,MAAM,MAAM,KAAK,cAAc,EAAE,IAAI,MAAM,KAAK,4CAA4C,EAAE;IAC5F,MAAM,KAAK,eAAe,EAAE;IAC5B,MAAM,KAAK,mBAAmB,EAAE;IAChC,MAAM,KAAK,qBAAqB,EAAE;;EAEpC,MAAM,MAAM,KAAK,gBAAgB,EAAE,IAAI,MAAM,KAAK,uCAAuC,EAAE;IACzF,MAAM,KAAK,kBAAkB,EAAE;IAC/B,MAAM,KAAK,SAAS,EAAE;IACtB,MAAM,KAAK,gBAAgB,EAAE;IAC7B,MAAM,KAAK,kBAAkB,EAAE;IAC/B,MAAM,KAAK,WAAW,EAAE;IACxB,MAAM,KAAK,QAAQ,EAAE;IACrB,MAAM,KAAK,QAAQ,EAAE;IACrB,MAAM,KAAK,OAAO,EAAE;;EAEtB,MAAM,MAAM,KAAK,UAAU,EAAE;;;;;;EAM7B,MAAM,KAAK,gIAAgI,EAAE;CAC9I;AACD"}
1
+ {"version":3,"file":"auth-DY7kU0z-.js","names":[],"sources":["../src/commands/auth.ts"],"sourcesContent":["/**\n * CLI command: rebase auth <action>\n *\n * Subcommands:\n * reset-password — Reset a user's password (HTTP first, the database as a fallback)\n * login, logout, whoami — a person's session on a running app (`auth-session.ts`)\n * emails — the development mailbox\n * keys — your own personal API keys\n */\nimport chalk from \"chalk\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport { spawn } from \"child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport {\n requireProjectRoot,\n requireBackendDir,\n findEnvFile,\n readEnvFile,\n resolveTsx,\n exitDependenciesNotInstalled\n} from \"../utils/project\";\nimport { parseEnvBoolean } from \"@rebasepro/types\";\nimport { unknownCommand } from \"../utils/unknown-command\";\nimport { redactConnectionPasswords } from \"../utils/redact\";\nimport type { PreparedDatabase } from \"../dev-db/prepare\";\nimport type { DevDatabaseSource } from \"../dev-db/resolve\";\n\n/** The backend was reached and refused: not a reason to fall back to the database. */\nclass ApiAnswered extends Error {}\n\n/** Everything the switch below dispatches, for the did-you-mean. */\nexport const AUTH_SUBCOMMANDS = [\"reset-password\", \"login\", \"logout\", \"whoami\", \"emails\", \"keys\"] as const;\nimport { parseCommandArgs, wantsHelp } from \"../utils/args\";\nimport { startProjectCommand } from \"../utils/project-command\";\nimport { cloudTargetNote, resolveBackendAddress } from \"./api-keys\";\n\n/** A user as the admin API returns it, reduced to what this command needs. */\nexport interface ResolvedUser {\n id: string;\n email: string;\n}\n\n/**\n * Pick the user with exactly this email out of a search response.\n *\n * `/api/admin/users?search=` is an `ILIKE '%…%'` over email **or display\n * name**, ordered by role count descending. This used to take row `[0]` and\n * reset it, then print the email it had been *given* as confirmation — so two\n * ordinary situations ended in a successful-looking reset of somebody else's\n * account:\n *\n * - a substring collision: `bob@example.com` also matches\n * `robert.bob@example.com`;\n * - a display name, which is user-controlled and accepted up to 255\n * characters with no constraint on its content, containing an address\n * belonging to someone else.\n *\n * The ordering makes it worse rather than better — `array_length(roles) DESC\n * NULLS LAST` puts the most privileged match first, so the account most likely\n * to be reset by mistake is an admin's.\n *\n * Returns `undefined` when nothing matched exactly, which the caller reports\n * rather than falling through to a guess. The direct-database fallback below\n * has always matched with `eq(usersTable.email, email)`; this is the same\n * definition, so the command no longer resets different accounts depending on\n * whether the backend happened to be running.\n */\nexport function selectUserForEmail(payload: unknown, email: string): ResolvedUser | undefined {\n const wanted = email.trim().toLowerCase();\n if (!wanted) return undefined;\n\n const rows: unknown[] = Array.isArray(payload)\n ? payload\n : (payload && typeof payload === \"object\" && Array.isArray((payload as { users?: unknown }).users)\n ? (payload as { users: unknown[] }).users\n : []);\n\n for (const row of rows) {\n if (!row || typeof row !== \"object\") continue;\n const record = row as Record<string, unknown>;\n const rowEmail = typeof record.email === \"string\" ? record.email.trim().toLowerCase() : undefined;\n if (!rowEmail || rowEmail !== wanted) continue;\n\n const id = typeof record.id === \"string\"\n ? record.id\n : (typeof record.uid === \"string\" ? record.uid : undefined);\n if (!id) continue;\n\n return { id, email: record.email as string };\n }\n\n return undefined;\n}\n\nexport async function authCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n // `--help` is answered here and never reaches a handler. `cli.ts` only\n // rewrites the subcommand to `\"--help\"` when no subcommand was named, so\n // `rebase auth reset-password --help` used to *run the reset*: `--help`\n // became the email, the backend was contacted, `.tmp-reset-password.ts` was\n // written into the user's `backend/`, and a database UPDATE ran for a user\n // named `--help`. A flag whose whole job is to print text cannot be allowed\n // to reach code that writes.\n if (!subcommand || subcommand === \"--help\" || wantsHelp(rawArgs)) {\n printAuthHelp();\n return;\n }\n\n switch (subcommand) {\n case \"reset-password\":\n await resetPassword(rawArgs);\n break;\n case \"login\": {\n const { authLogin } = await import(\"./auth-session\");\n startProjectCommand(rawArgs);\n await authLogin(rawArgs);\n break;\n }\n case \"logout\": {\n const { authLogout } = await import(\"./auth-session\");\n startProjectCommand(rawArgs);\n await authLogout(rawArgs);\n break;\n }\n case \"whoami\": {\n const { authWhoami } = await import(\"./auth-session\");\n startProjectCommand(rawArgs);\n await authWhoami(rawArgs);\n break;\n }\n case \"emails\": {\n const { authEmails } = await import(\"./auth-session\");\n startProjectCommand(rawArgs);\n await authEmails(rawArgs);\n break;\n }\n case \"keys\": {\n const { authKeys } = await import(\"./auth-session\");\n startProjectCommand(rawArgs);\n await authKeys(rawArgs);\n break;\n }\n default:\n unknownCommand(subcommand, AUTH_SUBCOMMANDS, \"auth\");\n }\n}\n\n/**\n * The flags `rebase auth reset-password` takes.\n *\n * `-p` was advertised in this command's own help and never declared here, so\n * `arg` — running permissively — pushed it into the positionals and the value\n * *after* it shifted out of reach: anyone following the help set the account's\n * password to the two-character string `-p`. Declared now, and `auth.test.ts`\n * asserts that the help and this spec list the same aliases.\n */\nexport const RESET_PASSWORD_FLAGS = {\n \"--email\": String,\n \"--password\": String,\n \"-e\": \"--email\",\n \"-p\": \"--password\"\n} as const;\n\n/**\n * Which account, and which password, this invocation names.\n *\n * Both may still be absent — the caller reports a missing email — but neither\n * can be a flag. `parseCommandArgs` parses the whole line strictly, so an\n * undeclared flag is an error rather than a positional. That is what stops\n * `rebase auth reset-password bob@example.com --debug` from setting Bob's\n * password to `--debug`, which is the flag the CLI itself prints after every\n * failure as the thing to re-run with.\n *\n * Exported so its tests can drive the real parser rather than a copy of it.\n */\nexport function resolveResetPasswordArgs(rawArgs: string[]): {\n email?: string;\n password?: string;\n} {\n const { flags, positionals } = parseCommandArgs({\n spec: RESET_PASSWORD_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"auth reset-password\",\n maxPositionals: 2\n });\n\n // Everywhere else in the CLI `-p` is `--project`. Here it has always been\n // `--password`, and it keeps working — with one warning per run naming the\n // spelling that will not change.\n if (rawArgs.slice(2).includes(\"-p\")) {\n process.stderr.write(chalk.yellow(\" ⚠ -p is deprecated in `rebase auth reset-password`: use --password (elsewhere -p means --project).\\n\"));\n }\n\n // Both spellings are supported: `<email> [password]` and `--email/--password`.\n return {\n email: flags[\"--email\"] || positionals[0],\n password: flags[\"--password\"] || positionals[1]\n };\n}\n\n/**\n * A password for a reset that was not given one.\n *\n * This used to be a constant, and `--help` printed it as the default. Reset is\n * the documented way back into an account nobody can sign in to — an admin,\n * usually — so the recovery path set every such account to a fixed string that\n * ships inside a public repository and a published npm package, and left it\n * there until somebody remembered to change it.\n *\n * base64url of 18 random bytes: 24 characters, ~144 bits, no shell-quoting\n * hazard, and nothing that reads like a placeholder somebody might keep.\n */\nexport function generatePassword(): string {\n return randomBytes(18).toString(\"base64url\");\n}\n\n/**\n * What a refusing backend said, from its `{ error: { message, code } }` body.\n *\n * The body used to be printed as it came, so a weak password read\n * `{\"error\":{\"message\":\"…\",\"code\":\"…\"}}`. A body that is not the envelope is\n * still shown, since it is the only account of the refusal there is.\n */\nasync function refusalReason(response: Response): Promise<string> {\n const text = await response.text().catch(() => \"\");\n try {\n const parsed: unknown = JSON.parse(text);\n const error = parsed && typeof parsed === \"object\" && \"error\" in parsed ? parsed.error : undefined;\n if (error && typeof error === \"object\" && \"message\" in error && typeof error.message === \"string\") {\n const code = \"code\" in error && typeof error.code === \"string\" ? ` (${error.code})` : \"\";\n return `${error.message}${code}`;\n }\n } catch {\n // Not JSON: the text is the answer.\n }\n return text.trim() || `${response.status} ${response.statusText}`.trim();\n}\n\nasync function resetPassword(rawArgs: string[]): Promise<void> {\n const { email, password: providedPassword } = resolveResetPasswordArgs(rawArgs);\n // Generated once, so both reset paths set and report the same thing.\n const wasGenerated = !providedPassword;\n const newPassword = providedPassword || generatePassword();\n\n if (!email) {\n console.error(chalk.red(\"✗ Email is required.\"));\n console.log(\"\");\n console.log(chalk.gray(\" Usage: rebase auth reset-password <email> [new-password]\"));\n console.log(chalk.gray(\" rebase auth reset-password --email user@example.com --password NewPass123!\"));\n process.exit(1);\n }\n\n const projectRoot = requireProjectRoot();\n\n // 1. Try API-first reset\n // Was a single-key regex, which did not match `export REBASE_SERVICE_KEY=…`\n // and kept a trailing `# comment` in the value. The command then fell\n // through to the direct-database path as though no key were configured.\n const envFile = findEnvFile(projectRoot);\n const envServiceKey: string | undefined = readEnvFile(projectRoot).REBASE_SERVICE_KEY;\n\n let serviceKey = process.env.REBASE_SERVICE_KEY || envServiceKey;\n\n const statePath = path.join(projectRoot, \".rebase\", \"state.json\");\n if (fs.existsSync(statePath)) {\n try {\n const state = JSON.parse(fs.readFileSync(statePath, \"utf8\")) as Record<string, unknown>;\n if (state && typeof state === \"object\" && typeof state.serviceKey === \"string\" && !serviceKey) {\n serviceKey = state.serviceKey;\n }\n } catch {\n // Ignore\n }\n }\n\n // Where the service key may go: a REBASE_BASE_URL the developer named, or\n // this project's backend while the pid that recorded it is alive — see\n // `resolveBackendAddress`. `.rebase/state.json`'s address on its own, and\n // `.rebase-dev-url`, outlive a killed `rebase dev`, and the port they name\n // may be another server's by now. With neither, the reset goes to the\n // database directly.\n const address = resolveBackendAddress(readEnvFile(projectRoot), projectRoot);\n const cloudNote = cloudTargetNote(address);\n if (cloudNote) console.error(chalk.yellow(` ⚠ ${cloudNote}`));\n const baseUrl = address.url;\n\n if (baseUrl && serviceKey) {\n console.log(\"Trying API-first reset via running backend...\");\n try {\n const finalPass = newPassword;\n const cleanBaseUrl = baseUrl.replace(/\\/+$/, \"\");\n // Not `limit=1`: the search is fuzzy and ordered by role count, so\n // the exact match is not necessarily first — asking for one row can\n // make it unreachable. Ask for a page, then match exactly.\n const searchUrl = `${cleanBaseUrl}/api/admin/users?search=${encodeURIComponent(email)}&limit=50`;\n const searchRes = await fetch(searchUrl, {\n headers: {\n \"Authorization\": `Bearer ${serviceKey}`,\n \"Accept\": \"application/json\"\n }\n });\n if (!searchRes.ok) {\n throw new ApiAnswered(`Failed to list users: ${searchRes.status} ${searchRes.statusText}`);\n }\n const searchData = await searchRes.json() as unknown;\n if (!searchData || typeof searchData !== \"object\") {\n throw new Error(\"Invalid response format from user search API.\");\n }\n\n const matched = selectUserForEmail(searchData, email);\n if (!matched) {\n throw new ApiAnswered(`No user has the email ${email}.`);\n }\n\n const resetUrl = `${cleanBaseUrl}/api/admin/users/${matched.id}/reset-password`;\n const resetRes = await fetch(resetUrl, {\n method: \"POST\",\n headers: {\n \"Authorization\": `Bearer ${serviceKey}`,\n \"Content-Type\": \"application/json\",\n \"Accept\": \"application/json\"\n },\n body: JSON.stringify({ password: finalPass })\n });\n\n if (!resetRes.ok) {\n throw new ApiAnswered(`Password reset refused: ${await refusalReason(resetRes)}`);\n }\n\n console.log(\"API reset successful.\");\n console.log(chalk.bold(\" 🔑 Rebase Auth — Reset Password (via API)\"));\n console.log(\"\");\n // The address as stored, not as typed — they differ in case often\n // enough that echoing the input hides which account was touched.\n console.log(` ${chalk.gray(\"Email:\")} ${matched.email}`);\n // Echoed only when we invented it. A password the operator typed\n // is already theirs; printing it again only adds scrollback.\n console.log(` ${chalk.gray(\"Password:\")} ${wasGenerated ? finalPass : \"*\".repeat(finalPass.length)}`);\n console.log(\"\");\n return;\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n // The backend answered and said no — a password too weak, a user\n // it does not have. That answer stands: writing the hash straight\n // into the database instead skipped the strength rule it had just\n // applied, and ended no sessions. Only a backend that could not be\n // reached is a reason to go round it.\n if (err instanceof ApiAnswered) {\n console.error(chalk.red(`✗ ${errMsg}`));\n process.exitCode = 1;\n return;\n }\n console.warn(chalk.yellow(\"API reset failed, falling back to direct database update...\"));\n console.warn(chalk.gray(` Details: ${errMsg}`));\n }\n }\n\n // 2. Direct-DB Fallback\n const backendDir = requireBackendDir(projectRoot);\n const tsxBin = resolveTsx(projectRoot);\n\n if (!tsxBin) {\n exitDependenciesNotInstalled(projectRoot);\n }\n\n // The database the `db` family would use, resolved — and, for a remembered\n // compose container that is stopped, started — the same way. A stock\n // scaffold leaves DATABASE_URL commented out and runs on the managed\n // database, which only exists in a child's environment when something puts\n // it there — without this the script connected with libpq's defaults,\n // localhost:5432 as the OS user. An external DATABASE_URL adds nothing\n // here: the child already reads it.\n let prepared: PreparedDatabase;\n try {\n const { ensureDockerDatabase } = await import(\"./db\");\n await ensureDockerDatabase(projectRoot, rawArgs);\n const { prepareDatabaseEnv } = await import(\"../dev-db/prepare\");\n prepared = await prepareDatabaseEnv(projectRoot, {\n onProgress: (message) => console.log(chalk.gray(` ${message}`))\n });\n } catch (err) {\n console.error(chalk.red(\"✗ Direct database update failed.\"));\n console.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n\n // Opened here first, so a database that does not answer gets the banner\n // every other command prints — not the script's raw error and stack — and\n // no script is written for it.\n const { databaseUrlOf } = await import(\"./db\");\n const url = databaseUrlOf(prepared, readEnvFile(projectRoot));\n if (url) {\n const failure = await databaseOpenFailure(url, prepared.database.source);\n if (failure) {\n for (const line of failure) console.error(line);\n process.exit(1);\n }\n }\n\n try {\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n env.REBASE_RESET_EMAIL = email;\n env.REBASE_RESET_PASSWORD = newPassword;\n env.REBASE_ENV_FILE_PATH = envFile || path.join(projectRoot, \".env\");\n Object.assign(env, prepared.env);\n\n const scriptContent = resetPasswordScript(wasGenerated, parseEnvBoolean(process.env.REBASE_DEBUG) === true);\n\n const tmpScriptPath = path.join(backendDir, \".tmp-reset-password.ts\");\n fs.writeFileSync(tmpScriptPath, scriptContent, \"utf-8\");\n\n console.log(\"\");\n console.log(chalk.bold(\" 🔑 Rebase Auth — Reset Password (Direct DB Fallback)\"));\n console.log(\"\");\n console.log(` ${chalk.gray(\"Email:\")} ${email}`);\n console.log(` ${chalk.gray(\"Database:\")} ${prepared.description}`);\n if (!wasGenerated) {\n console.log(` ${chalk.gray(\"Password:\")} ${\"*\".repeat(newPassword.length)}`);\n }\n console.log(\"\");\n\n const child = spawn(tsxBin, [tmpScriptPath], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n\n // The script is written into the user's backend directory, so every\n // exit has to remove it. Without an `error` handler a failed spawn\n // raises an unhandled event, the process dies before `close`, and\n // `.tmp-reset-password.ts` is left behind to be committed.\n const cleanup = () => {\n try { fs.unlinkSync(tmpScriptPath); } catch { /* already gone */ }\n };\n\n return new Promise((resolve) => {\n child.on(\"error\", (err) => {\n cleanup();\n console.error(chalk.red(\"✗ Could not run the reset script.\"));\n console.error(chalk.gray(` ${err.message}`));\n process.exit(1);\n });\n child.on(\"close\", (code) => {\n cleanup();\n if (code !== 0) {\n process.exit(code ?? 1);\n }\n resolve();\n });\n });\n } catch (err) {\n console.error(chalk.red(\"✗ Direct database update failed.\"));\n console.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n}\n\n/**\n * Why the database the fallback would reset in cannot be opened, as the lines\n * to print — or null when it opens.\n *\n * A stopped database, refused credentials and a database name the server does\n * not have get the boxed banner the other commands print; anything else is one\n * sentence. Either way the password was not reset and no script was written.\n */\nasync function databaseOpenFailure(url: string, source: DevDatabaseSource): Promise<string[] | null> {\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString: url, connectionTimeoutMillis: 10_000 });\n client.on(\"error\", () => undefined);\n try {\n await client.connect();\n await client.query(\"SELECT 1\");\n return null;\n } catch (error) {\n const { connectionErrorText, connectionFailureBanner, connectionRefusedFixes } =\n await import(\"../dev-db/connection-banner\");\n const consequence = \"The password was not reset.\";\n return connectionFailureBanner(url, error, { consequence, fixes: connectionRefusedFixes(source) }) ?? [\n chalk.red(`✗ Could not open the database: ${redactConnectionPasswords(connectionErrorText(error))}`),\n chalk.gray(` ${consequence}`)\n ];\n } finally {\n await client.end().catch(() => undefined);\n }\n}\n\n/**\n * The script the direct-database fallback runs under the project's own tsx, so\n * it resolves the project's `@rebasepro/server-postgres` and schema.\n *\n * It ends the account's sessions in the transaction that sets the password,\n * as every door through the API does (`replaceUserPassword`): the refresh\n * tokens and outstanding reset links go, and `tokens_valid_after` voids the\n * access tokens already handed out. An operator resetting a phished account\n * with the backend down is the case this exists for, and a reset that left the\n * attacker's refresh token minting access tokens did not recover anything.\n *\n * It exits 0 only when a row was updated: a missing user and a thrown error are\n * both exit 1. `echoPassword` prints the new password, for a generated one;\n * `showStack` prints a failure's stack rather than its sentence (`--debug`).\n *\n * Exported so its tests can run it.\n */\nexport function resetPasswordScript(echoPassword: boolean, showStack = false): string {\n return `\nimport { createPostgresDatabaseConnection } from \"@rebasepro/server-postgres\";\nimport { hashPassword } from \"@rebasepro/server\";\nimport { getTableConfig } from \"drizzle-orm/pg-core\";\nimport * as dotenv from \"dotenv\";\nimport path from \"path\";\nimport fs from \"fs\";\n\ndotenv.config({ path: process.env.REBASE_ENV_FILE_PATH, quiet: true });\n\n// Lowercased, as every address is stored (\\`normalizeEmail\\`): matched as\n// typed, \"Ops@Acme.test\" found no row.\nconst email = process.env.REBASE_RESET_EMAIL!.trim().toLowerCase();\nconst newPassword = process.env.REBASE_RESET_PASSWORD!;\n\nconst quote = (identifier: string) => '\"' + identifier.replace(/\"/g, '\"\"') + '\"';\n\nasync function resetPassword() {\n const { pool } = createPostgresDatabaseConnection(process.env.DATABASE_URL!);\n const hash = await hashPassword(newPassword);\n\n let usersTable;\n try {\n const schemaPath = path.resolve(\"./src/schema.generated.ts\");\n if (fs.existsSync(schemaPath)) {\n const schema = await import(\"file://\" + schemaPath);\n usersTable = schema.users || schema.tables?.users;\n }\n } catch (e) {\n // ignore and fallback\n }\n\n if (!usersTable) {\n const pgServer = await import(\"@rebasepro/server-postgres\");\n usersTable = pgServer.users;\n }\n\n // The physical names, from the table object: the collection may map its\n // properties to other columns, and the statements below are plain SQL.\n const { name: tableName, schema: tableSchema } = getTableConfig(usersTable);\n const usersSchema = tableSchema || \"public\";\n const users = quote(usersSchema) + \".\" + quote(tableName);\n const idColumn = quote(usersTable.id.name);\n const emailColumn = quote(usersTable.email.name);\n const passwordColumn = quote((usersTable.passwordHash ?? usersTable.password_hash).name);\n // Where \\`ensureAuthTablesExist\\` puts the tables that hang off the users\n // table: beside it, or in \\`rebase\\` when it lives in \\`public\\`.\n const authSchema = usersSchema === \"public\" ? \"rebase\" : usersSchema;\n\n const client = await pool.connect();\n try {\n // A database nothing has booted against — or a managed one \\`db reset\\`\n // emptied — has no users table, and so no account to reset. Said as\n // that, not as pg's \\`relation … does not exist\\`.\n const usersTable = await client.query(\"SELECT to_regclass($1) IS NOT NULL AS present\", [users]);\n if (!usersTable.rows[0]?.present) {\n console.error(\"✗ \" + users + \" does not exist in this database, so it holds no account to reset.\");\n console.error(\" Nothing was changed. \\`rebase dev\\` creates it the first time it boots against this database.\");\n process.exit(1);\n }\n\n await client.query(\"BEGIN\");\n const updated = await client.query(\n \"UPDATE \" + users + \" SET \" + passwordColumn + \" = $1 WHERE \" + emailColumn + \" = $2 \" +\n \"RETURNING \" + idColumn + \" AS id, \" + emailColumn + \" AS email\",\n [hash, email]\n );\n if (updated.rows.length === 0) {\n await client.query(\"ROLLBACK\");\n // Nothing was updated, so nothing was reset. Exiting 0 here reported\n // success for a no-op, which is what a script would have believed.\n console.error(\"✗ User not found: \" + email);\n process.exit(1);\n }\n const uid = updated.rows[0].id;\n\n // A table or column the server has not created yet (it never booted\n // against this database) holds no session to end.\n const watermark = await client.query(\n \"SELECT 1 FROM information_schema.columns WHERE table_schema = $1 AND table_name = $2 AND column_name = 'tokens_valid_after'\",\n [usersSchema, tableName]\n );\n if (watermark.rows.length > 0) {\n await client.query(\"UPDATE \" + users + \" SET tokens_valid_after = NOW() WHERE \" + idColumn + \" = $1\", [uid]);\n }\n for (const table of [\"refresh_tokens\", \"password_reset_tokens\"]) {\n const qualified = quote(authSchema) + \".\" + quote(table);\n const present = await client.query(\"SELECT to_regclass($1) IS NOT NULL AS present\", [qualified]);\n if (present.rows[0]?.present) {\n await client.query(\"DELETE FROM \" + qualified + \" WHERE uid = $1\", [uid]);\n }\n }\n await client.query(\"COMMIT\");\n\n console.log(\"✅ Password reset for: \" + updated.rows[0].email);\n console.log(\" Every session of this account has ended.\");\n ${echoPassword ? 'console.log(\" Password: \" + newPassword);' : \"\"}\n process.exit(0);\n } catch (error) {\n await client.query(\"ROLLBACK\").catch(() => undefined);\n throw error;\n } finally {\n client.release();\n }\n}\n\n// A thrown error is a failed reset, and exits like one — a refused connection\n// that exits 0 reads as a reset to anything checking the exit code. Said as a\n// sentence: the stack is the script's own, and only --debug asks for it.\nconst describe = (error: unknown): string => {\n if (error instanceof AggregateError && !error.message && error.errors.length > 0) return describe(error.errors[0]);\n const message = error instanceof Error ? error.message : String(error);\n const code = error && typeof error === \"object\" && \"code\" in error && typeof error.code === \"string\" ? error.code : \"\";\n return code && !message.includes(code) ? message + \" (\" + code + \")\" : message;\n};\nresetPassword().catch((error) => {\n ${showStack ? \"console.error(error);\" : \"console.error(\\\"✗ The password was not reset: \\\" + describe(error));\"}\n process.exit(1);\n});\n`;\n}\n\nfunction printAuthHelp() {\n console.log(`\n${chalk.bold(\"rebase auth\")} — Authentication: a person's session on a running app, resets, the dev mailbox\n\n${chalk.green.bold(\"Usage\")}\n rebase auth ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"reset-password\")} Reset a user's password ${chalk.gray(\"(the running server, else the database directly)\")}\n ${chalk.blue.bold(\"login\")} Sign in to a running app as a person; the session is kept in ~/.rebase/sessions.json\n ${chalk.blue.bold(\"logout\")} End that session, here and on the server\n ${chalk.blue.bold(\"whoami\")} Who the server takes you to be, and the scopes you hold\n ${chalk.blue.bold(\"emails\")} The development mailbox: the auth mail a server with no SMTP_HOST captured\n ${chalk.blue.bold(\"keys\")} Your own personal API keys: list, create, revoke ${chalk.gray(\"(needs auth.personalKeys)\")}\n\n${chalk.green.bold(\"reset-password Options\")}\n ${chalk.blue(\"--email, -e\")} User's email address\n ${chalk.blue(\"--password\")} New password (default: one is generated and printed)\n ${chalk.gray(\"-p still works for --password here, and warns: elsewhere -p means --project\")}\n\n${chalk.green.bold(\"login Options\")}\n ${chalk.blue(\"--email <address>\")} Sign in with this account's password (asked for at a terminal)\n ${chalk.blue(\"--password <pass>\")} The password, for scripts\n ${chalk.blue(\"--code <code>\")} The second factor, when the account has two-factor authentication on\n ${chalk.blue(\"--web\")} Sign in through the browser (the server's device sign-in) ${chalk.gray(\"— the default when it offers one\")}\n ${chalk.blue(\"--no-browser\")} Print the browser link instead of opening it\n\n${chalk.green.bold(\"emails Options\")}\n ${chalk.blue(\"--latest\")} Only the newest message\n ${chalk.blue(\"--to <address>\")} Only messages to this address\n ${chalk.blue(\"--links\")} Print only the links, one per line\n ${chalk.blue(\"--clear\")} Empty the mailbox\n\n${chalk.green.bold(\"keys Options\")} ${chalk.gray(\"rebase auth keys [list|create|revoke <id>]\")}\n ${chalk.blue(\"--name <name>\")} The new key's name\n ${chalk.blue(\"--scopes <scopes>\")} What it may do, e.g. data:read:posts (never more than you hold)\n ${chalk.blue(\"--expires-in <days>\")} When it stops working\n\n${chalk.green.bold(\"Target options\")} ${chalk.gray(\"(login, logout, whoami, emails, keys)\")}\n ${chalk.blue(\"--project <slug>\")} A Rebase Cloud project (login goes to the app's own address)\n ${chalk.blue(\"--cloud\")} The Rebase Cloud project this directory is linked to\n ${chalk.blue(\"--url <server>\")} A server at this address (else REBASE_BASE_URL, then \\`rebase dev\\`)\n ${chalk.blue(\"--token <bearer>\")} Send this bearer instead (whoami, emails)\n ${chalk.blue(\"--session\")} Send the stored session (whoami and keys do by default)\n ${chalk.blue(\"--anon\")} Send no credential\n ${chalk.blue(\"--json\")} Machine-readable output (also when piped)\n ${chalk.blue(\"--yes\")} Skip confirmation prompts\n\n${chalk.green.bold(\"Examples\")}\n rebase auth reset-password user@example.com\n rebase auth reset-password --email user@example.com --password MyNewPass!\n rebase auth login --email ada@example.com\n rebase auth emails --latest --links\n\n${chalk.gray(\"rebase users reset-password does the same reset on any target (--url, --project); this one also works with the server stopped.\")}\n`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA6BA,IAAM,cAAN,cAA0B,MAAM,CAAC;;AAGjC,IAAa,mBAAmB;CAAC;CAAkB;CAAS;CAAU;CAAU;CAAU;AAAM;;;;;;;;;;;;;;;;;;;;;;;;;;AAoChG,SAAgB,mBAAmB,SAAkB,OAAyC;CAC1F,MAAM,SAAS,MAAM,KAAK,CAAC,CAAC,YAAY;CACxC,IAAI,CAAC,QAAQ,OAAO,KAAA;CAEpB,MAAM,OAAkB,MAAM,QAAQ,OAAO,IACvC,UACC,WAAW,OAAO,YAAY,YAAY,MAAM,QAAS,QAAgC,KAAK,IAC1F,QAAiC,QAClC,CAAC;CAEX,KAAK,MAAM,OAAO,MAAM;EACpB,IAAI,CAAC,OAAO,OAAO,QAAQ,UAAU;EACrC,MAAM,SAAS;EACf,MAAM,WAAW,OAAO,OAAO,UAAU,WAAW,OAAO,MAAM,KAAK,CAAC,CAAC,YAAY,IAAI,KAAA;EACxF,IAAI,CAAC,YAAY,aAAa,QAAQ;EAEtC,MAAM,KAAK,OAAO,OAAO,OAAO,WAC1B,OAAO,KACN,OAAO,OAAO,QAAQ,WAAW,OAAO,MAAM,KAAA;EACrD,IAA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AAM,KAAK,kBAAkB,EAAE;IAC/B,MAAM,KAAK,SAAS,EAAE;IACtB,MAAM,KAAK,gBAAgB,EAAE;IAC7B,MAAM,KAAK,kBAAkB,EAAE;IAC/B,MAAM,KAAK,WAAW,EAAE;IACxB,MAAM,KAAK,QAAQ,EAAE;IACrB,MAAM,KAAK,QAAQ,EAAE;IACrB,MAAM,KAAK,OAAO,EAAE;;EAEtB,MAAM,MAAM,KAAK,UAAU,EAAE;;;;;;EAM7B,MAAM,KAAK,gIAAgI,EAAE;CAC9I;AACD"}
@@ -1,7 +1,7 @@
1
1
  import { n as parseCommandArgs, t as UsageError } from "./args-DHyrshtI.js";
2
2
  import { t as cliUserAgent } from "./version-ONIeo7jl.js";
3
- import { a as projectTarget, b as storedSession, c as requestJson, d as PROJECT_TARGET_FLAGS, m as forgetSession, n as isRecord, o as recordsOf, r as parsedLine, u as stringOf, v as saveSession, y as sessionKey } from "./project-command-Cl9EZzjr.js";
4
- import { D as isJsonMode, M as note, ct as warn, l as confirmDestructive, m as emit, st as success, v as fail } from "./context-BOMEoKxn.js";
3
+ import { a as projectTarget, b as storedSession, c as requestJson, d as PROJECT_TARGET_FLAGS, m as forgetSession, n as isRecord, o as recordsOf, r as parsedLine, u as stringOf, v as saveSession, y as sessionKey } from "./project-command-7EGMemEy.js";
4
+ import { D as isJsonMode, M as note, ct as warn, l as confirmDestructive, m as emit, st as success, v as fail } from "./context-xt20FMFA.js";
5
5
  import chalk from "chalk";
6
6
  import inquirer from "inquirer";
7
7
  //#region src/commands/auth-session.ts
@@ -147,7 +147,7 @@ async function signInWithBrowser(auth, openBrowser) {
147
147
  const started = await auth.startDeviceLogin({ clientName: `Rebase CLI on ${(await import("os")).hostname()}` });
148
148
  process.stderr.write(`To sign in, open ${started.verificationUriComplete}\n and check that it shows the code ${started.userCode}.\n`);
149
149
  if (openBrowser && atTerminal()) {
150
- const { openUrl } = await import("./context-BOMEoKxn.js").then((n) => n.u);
150
+ const { openUrl } = await import("./context-xt20FMFA.js").then((n) => n.u);
151
151
  openUrl(started.verificationUriComplete);
152
152
  }
153
153
  const deadline = Date.now() + started.expiresIn * 1e3;
@@ -368,4 +368,4 @@ async function authKeys(rawArgs) {
368
368
  //#endregion
369
369
  export { authEmails, authKeys, authLogin, authLogout, authWhoami };
370
370
 
371
- //# sourceMappingURL=auth-session-B6aT0Dyj.js.map
371
+ //# sourceMappingURL=auth-session-DCG96UGH.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"auth-session-B6aT0Dyj.js","names":[],"sources":["../src/commands/auth-session.ts"],"sourcesContent":["/**\n * CLI commands: rebase auth login | logout | whoami | emails | keys\n *\n * A person's session on a running app — not on Rebase Cloud's control plane,\n * which is `rebase cloud login`. Some of an app's routes answer a person and\n * never a machine: the RLS simulator, the impersonation and simulation\n * headers, live schema apply (a commit needs an author), personal API keys.\n * The service key will never reach them, by design. `rebase auth login`\n * stores a session for one server in `~/.rebase/sessions.json` (keyed by its\n * origin, never in the project directory), and every project command sends\n * it on `--session`; `rebase rls simulate` and `rebase auth keys` send it by\n * default.\n *\n * `auth emails` is the other thing a terminal needs while building auth\n * flows: the development mailbox — every sign-in, reset and magic-link mail a\n * server with no SMTP_HOST captured instead of sending, with its links.\n */\nimport type arg from \"arg\";\nimport chalk from \"chalk\";\nimport inquirer from \"inquirer\";\n\nimport { parseCommandArgs, UsageError } from \"../utils/args\";\nimport {\n PROJECT_TARGET_FLAGS,\n forgetSession,\n saveSession,\n sessionKey,\n storedSession,\n type ProjectTarget\n} from \"../utils/project-target\";\nimport {\n emit,\n fail,\n isJsonMode,\n isRecord,\n parsedLine,\n projectTarget,\n recordsOf,\n requestJson,\n stringOf\n} from \"../utils/project-command\";\nimport { cliUserAgent } from \"../utils/version\";\nimport { confirmDestructive, note, success, warn } from \"./cloud/context\";\n\n/** The subcommands this module answers, beside `reset-password` in `auth.ts`. */\nexport const AUTH_SESSION_SUBCOMMANDS = [\"login\", \"logout\", \"whoami\", \"emails\", \"keys\"] as const;\n\n/** The access token's expiry, from its `exp` claim, in epoch milliseconds. */\nexport function tokenExpiry(token: string): number {\n const payload = token.split(\".\")[1];\n if (payload) {\n try {\n const claims: unknown = JSON.parse(Buffer.from(payload, \"base64url\").toString(\"utf8\"));\n if (isRecord(claims) && typeof claims.exp === \"number\") return claims.exp * 1000;\n } catch {\n // Not a JWT we can read: fall through to a short, safe guess.\n }\n }\n return Date.now() + 15 * 60_000;\n}\n\nfunction atTerminal(): boolean {\n return !isJsonMode() && process.stdin.isTTY === true;\n}\n\n/** The origin a session is for: the target, reached with no credential of its own. */\nasync function originTarget(flags: Readonly<Record<string, unknown>>, command: string): Promise<ProjectTarget> {\n return projectTarget({ ...flags, \"--anon\": true, \"--token\": undefined, \"--session\": undefined }, { command });\n}\n\n/* ═══════════════════════════════════════════════════════════════\n login\n ═══════════════════════════════════════════════════════════════ */\n\nexport const AUTH_LOGIN_FLAGS = {\n ...PROJECT_TARGET_FLAGS,\n \"--email\": String,\n \"-e\": \"--email\",\n \"--password\": String,\n \"--code\": String,\n \"--web\": Boolean,\n \"--no-browser\": Boolean\n} satisfies arg.Spec;\n\ntype SignedIn = { user: unknown; accessToken: string; refreshToken?: string };\n\nexport async function authLogin(rawArgs: string[]): Promise<void> {\n const { flags } = parsedLine(() => parseCommandArgs({\n spec: AUTH_LOGIN_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"auth login\",\n maxPositionals: 0\n }));\n if (flags[\"--token\"] || flags[\"--session\"] || flags[\"--anon\"]) {\n fail(\"`rebase auth login` signs in; --token, --session and --anon pick a credential for other commands.\", undefined, \"usage\");\n }\n const target = await originTarget(flags, \"auth login\");\n const origin = target.baseUrl;\n const { createRebaseClient } = await import(\"@rebasepro/client\");\n const client = createRebaseClient({\n baseUrl: origin,\n realtime: false,\n headers: { \"User-Agent\": cliUserAgent() },\n auth: { persistSession: false, autoRefresh: false }\n });\n\n const config = await requestJson(target, \"/api/auth/config\", `Could not read how ${origin} signs people in`).catch(() => null);\n const deviceLogin = isRecord(config) && (config.deviceLogin === true || isRecord(config.deviceLogin));\n\n let signedIn: SignedIn;\n const email = flags[\"--email\"];\n if (flags[\"--web\"] || (!email && deviceLogin)) {\n if (!deviceLogin) {\n fail(`${origin} does not offer signing in through a browser.`, \"Pass --email <address> to sign in with a password.\", \"device_login_unavailable\");\n }\n signedIn = await signInWithBrowser(client.auth, flags[\"--no-browser\"] !== true);\n } else {\n let address = email;\n if (!address) {\n if (!atTerminal()) fail(\"Signing in needs an email and a password, and there is no terminal to ask on.\", \"Pass --email <address> --password <password>.\", \"input_required\");\n ({ address } = await inquirer.prompt([{ type: \"input\", name: \"address\", message: \"Email:\" }]));\n }\n let password = flags[\"--password\"];\n if (!password) {\n if (!atTerminal()) fail(\"Signing in needs a password, and there is no terminal to ask on.\", \"Pass --password <password>.\", \"input_required\");\n ({ password } = await inquirer.prompt([{ type: \"password\", name: \"password\", message: \"Password:\", mask: \"*\" }]));\n }\n const who = String(address ?? \"\").trim();\n const secret = String(password ?? \"\");\n signedIn = await withSecondFactor(client.auth, flags[\"--code\"], () => client.auth.signInWithEmail(who, secret));\n }\n\n const user = isRecord(signedIn.user) ? signedIn.user : {};\n const roles = Array.isArray(user.roles) ? user.roles.map(String) : [];\n saveSession(origin, {\n accessToken: signedIn.accessToken,\n ...(signedIn.refreshToken ? { refreshToken: signedIn.refreshToken } : {}),\n expiresAt: tokenExpiry(signedIn.accessToken),\n ...(stringOf(user.email) ? { email: stringOf(user.email) } : {}),\n ...(stringOf(user.uid ?? user.id) ? { uid: stringOf(user.uid ?? user.id) } : {})\n });\n emit(() => {\n success(`Signed in to ${sessionKey(origin)} as ${stringOf(user.email) ?? stringOf(user.uid) ?? \"?\"}${roles.length ? ` (${roles.join(\", \")})` : \"\"}.`);\n note(chalk.gray(\"Commands send this session with --session; `rebase rls simulate` and `rebase auth keys` send it by default.\"));\n }, { origin: sessionKey(origin), user: { uid: stringOf(user.uid ?? user.id) ?? null, email: stringOf(user.email) ?? null, roles } });\n}\n\ntype ProjectAuth = Awaited<ReturnType<typeof import(\"@rebasepro/client\")[\"createRebaseClient\"]>>[\"auth\"];\n\n/** The `MFA_REQUIRED` refusal's details: the pending token and the factors to answer with. */\nfunction pendingSecondFactor(error: unknown): { mfaToken: string; factors: Array<{ id: string; name: string }> } | null {\n if (!isRecord(error) || error.code !== \"MFA_REQUIRED\" || !isRecord(error.details)) return null;\n const mfaToken = stringOf(error.details.mfaToken);\n const factors = recordsOf(error.details.factors)\n .map(f => ({ id: stringOf(f.id) ?? \"\", name: stringOf(f.friendlyName) ?? stringOf(f.factorType) ?? \"factor\" }))\n .filter(f => f.id);\n return mfaToken && factors.length > 0 ? { mfaToken, factors } : null;\n}\n\n/** Run a sign-in; when the account has two-factor authentication on, answer the challenge. */\nasync function withSecondFactor(auth: ProjectAuth, code: string | undefined, signIn: () => Promise<SignedIn>): Promise<SignedIn> {\n try {\n return await signIn();\n } catch (e) {\n const pending = pendingSecondFactor(e);\n if (!pending) throw e;\n let answer = code;\n if (!answer) {\n if (!atTerminal()) fail(\"This account has two-factor authentication on, and there is no terminal to ask for the code on.\", \"Pass --code <code>.\", \"mfa_required\");\n ({ answer } = await inquirer.prompt([{ type: \"input\", name: \"answer\", message: \"Code from your authenticator app (or a recovery code):\" }]));\n }\n const options = { mfaToken: pending.mfaToken };\n const { challengeId } = await auth.mfa.challenge(pending.factors[0].id, options);\n return auth.mfa.verifyChallenge(challengeId, String(answer ?? \"\").replace(/\\s+/g, \"\"), options);\n }\n}\n\n/** The framework's device sign-in: show the link and code, then poll until it is approved. */\nasync function signInWithBrowser(auth: ProjectAuth, openBrowser: boolean): Promise<SignedIn> {\n const started = await auth.startDeviceLogin({ clientName: `Rebase CLI on ${(await import(\"os\")).hostname()}` });\n process.stderr.write(`To sign in, open ${started.verificationUriComplete}\\n and check that it shows the code ${started.userCode}.\\n`);\n if (openBrowser && atTerminal()) {\n const { openUrl } = await import(\"./cloud/context\");\n openUrl(started.verificationUriComplete);\n }\n const deadline = Date.now() + started.expiresIn * 1000;\n let interval = started.interval;\n while (Date.now() < deadline) {\n await new Promise(resolve => setTimeout(resolve, interval * 1000));\n const result = await auth.pollDeviceLogin(started.deviceCode);\n if (result.status === \"approved\") return { user: result.user, accessToken: result.accessToken, refreshToken: result.refreshToken };\n if (result.status === \"denied\") fail(\"The sign-in was denied in the browser.\", undefined, \"access_denied\");\n if (result.status === \"expired\") break;\n interval = result.interval;\n }\n fail(\"The sign-in link expired before it was approved.\", \"Run `rebase auth login` again.\", \"expired_token\");\n}\n\n/* ═══════════════════════════════════════════════════════════════\n logout / whoami\n ═══════════════════════════════════════════════════════════════ */\n\nexport const AUTH_LOGOUT_FLAGS = { ...PROJECT_TARGET_FLAGS } satisfies arg.Spec;\n\nexport async function authLogout(rawArgs: string[]): Promise<void> {\n const { flags } = parsedLine(() => parseCommandArgs({\n spec: AUTH_LOGOUT_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"auth logout\",\n maxPositionals: 0\n }));\n const target = await originTarget(flags, \"auth logout\");\n const session = storedSession(target.baseUrl);\n if (!session) {\n emit(() => note(`No session is stored for ${sessionKey(target.baseUrl)}.`), { origin: sessionKey(target.baseUrl), signedOut: false });\n return;\n }\n // End it on the server too, so the refresh token stops working there and\n // not only here. A server that cannot be reached still loses it locally.\n if (session.refreshToken) {\n await target.request(\"/api/auth/logout\", { method: \"POST\", json: { refreshToken: session.refreshToken }, timeoutMs: 10_000 }).catch(() => undefined);\n }\n forgetSession(target.baseUrl);\n emit(() => success(`Signed out of ${sessionKey(target.baseUrl)}.`), { origin: sessionKey(target.baseUrl), signedOut: true });\n}\n\nexport const AUTH_WHOAMI_FLAGS = { ...PROJECT_TARGET_FLAGS } satisfies arg.Spec;\n\n/**\n * Who the server takes this command to be: `/api/auth/me` for a person's\n * session or token, and the scopes the credential holds (`/api/auth/scopes`),\n * which answers keys and the service key too.\n */\nexport async function authWhoami(rawArgs: string[]): Promise<void> {\n const { flags } = parsedLine(() => parseCommandArgs({\n spec: AUTH_WHOAMI_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"auth whoami\",\n maxPositionals: 0\n }));\n const usesSession = !flags[\"--token\"] && !flags[\"--anon\"];\n const target = await projectTarget(flags, { command: \"auth whoami\", ...(usesSession && !flags[\"--session\"] ? { defaultCredential: \"person\" as const } : {}) });\n const scopes = await requestJson(target, \"/api/auth/scopes\", \"Failed to read what this credential holds\");\n const me = target.credential === \"session\" || target.credential === \"token\"\n ? await target.request(\"/api/auth/me\", { timeoutMs: 15_000 }).then(async res => (res.ok ? res.json() as Promise<unknown> : null)).catch(() => null)\n : null;\n const user = isRecord(me) && isRecord(me.user) ? me.user : isRecord(me) ? me : undefined;\n const held = isRecord(scopes) && Array.isArray(scopes.held) ? scopes.held.map(String) : [];\n emit(() => {\n console.log(` ${chalk.gray(\"server\".padEnd(10))}${target.label}`);\n console.log(` ${chalk.gray(\"as\".padEnd(10))}${user ? `${stringOf(user.email) ?? stringOf(user.uid) ?? \"?\"} (${target.credential})` : target.credential}`);\n if (user && Array.isArray(user.roles)) console.log(` ${chalk.gray(\"roles\".padEnd(10))}${user.roles.map(String).join(\", \") || chalk.gray(\"none\")}`);\n console.log(` ${chalk.gray(\"scopes\".padEnd(10))}${held.length ? held.join(\", \") : chalk.gray(\"none\")}`);\n }, { server: target.label, credential: target.credential, user: user ?? null, scopes: held });\n}\n\n/* ═══════════════════════════════════════════════════════════════\n emails — the development mailbox\n ═══════════════════════════════════════════════════════════════ */\n\nexport const AUTH_EMAILS_FLAGS = {\n ...PROJECT_TARGET_FLAGS,\n \"--latest\": Boolean,\n \"--to\": String,\n \"--clear\": Boolean,\n \"--links\": Boolean\n} satisfies arg.Spec;\n\nexport async function authEmails(rawArgs: string[]): Promise<void> {\n const { flags } = parsedLine(() => parseCommandArgs({\n spec: AUTH_EMAILS_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"auth emails\",\n maxPositionals: 0\n }));\n const target = await projectTarget(flags, { command: \"auth emails\" });\n if (flags[\"--clear\"]) {\n await requestJson(target, \"/api/admin/dev/emails\", \"Failed to clear the development mailbox\", { method: \"DELETE\" });\n emit(() => success(\"Cleared the development mailbox.\"), { cleared: true });\n return;\n }\n const body = await requestJson(target, \"/api/admin/dev/emails\", \"Failed to read the development mailbox\");\n let messages = recordsOf(isRecord(body) ? body.messages : undefined);\n if (flags[\"--to\"]) {\n const to = flags[\"--to\"].toLowerCase();\n messages = messages.filter(message => stringOf(message.to)?.toLowerCase().includes(to));\n }\n if (flags[\"--latest\"]) messages = messages.slice(0, 1);\n if (flags[\"--links\"]) {\n // Only the links, one per line: what a script pipes into the next step.\n for (const message of messages) for (const link of Array.isArray(message.links) ? message.links : []) process.stdout.write(`${String(link)}\\n`);\n return;\n }\n emit(() => {\n if (messages.length === 0) return note(\"The development mailbox is empty.\");\n for (const message of messages) {\n console.log(` ${chalk.gray(stringOf(message.at) ?? \"\")} ${chalk.bold(stringOf(message.to) ?? \"?\")} ${stringOf(message.subject) ?? \"\"}`);\n for (const link of Array.isArray(message.links) ? message.links : []) console.log(` ${chalk.cyan(String(link))}`);\n }\n }, { messages });\n}\n\n/* ═══════════════════════════════════════════════════════════════\n keys — your own personal API keys\n ═══════════════════════════════════════════════════════════════ */\n\nexport const AUTH_KEYS_FLAGS = {\n ...PROJECT_TARGET_FLAGS,\n \"--name\": String,\n \"-n\": \"--name\",\n \"--scopes\": [String],\n \"--expires-in\": String\n} satisfies arg.Spec;\n\n/**\n * A person's own `rk_` keys (`/api/auth/keys`): list, create, revoke. They act\n * as their owner, with the owner's live roles, narrowed to the scopes named.\n * The server answers a person's session only, and only when the auth table\n * sets `auth.personalKeys: true`. Service keys are `rebase api-keys`.\n */\nexport async function authKeys(rawArgs: string[]): Promise<void> {\n const { flags, positionals } = parsedLine(() => parseCommandArgs({\n spec: AUTH_KEYS_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"auth keys\",\n maxPositionals: 2\n }));\n const action = positionals[0] ?? \"list\";\n if (![\"list\", \"create\", \"revoke\"].includes(action)) {\n const { unknownCommand } = await import(\"../utils/unknown-command\");\n unknownCommand(action, [\"list\", \"create\", \"revoke\"], \"auth keys\");\n }\n const target = await projectTarget(flags, { command: \"auth keys\", defaultCredential: \"person\" });\n\n if (action === \"create\") {\n const { scopes, expiresAt } = parsedLine(() => {\n const list = (flags[\"--scopes\"] ?? []).flatMap(s => s.split(\",\")).map(s => s.trim()).filter(Boolean);\n if (list.length === 0) throw new UsageError(\"rebase auth keys create needs --scopes, e.g. --scopes data:read:posts (never more than you hold).\");\n let expires: string | undefined;\n if (flags[\"--expires-in\"]) {\n const days = Number(flags[\"--expires-in\"].replace(/d$/, \"\"));\n if (!Number.isFinite(days) || days <= 0) throw new UsageError(\"--expires-in takes a number of days, e.g. 30 or 30d.\");\n expires = new Date(Date.now() + days * 86_400_000).toISOString();\n }\n return { scopes: list, expiresAt: expires };\n });\n const body = await requestJson(target, \"/api/auth/keys\", \"Failed to create the key\", {\n method: \"POST\",\n json: { name: flags[\"--name\"] ?? \"CLI key\", scopes, ...(expiresAt ? { expires_at: expiresAt } : {}) }\n });\n const secret = isRecord(body) ? stringOf(body.key) ?? (isRecord(body.key) ? stringOf(body.key.key) : undefined) : undefined;\n emit(() => {\n success(`Created a personal key holding ${scopes.join(\", \")}.`);\n if (secret) warn(\"It is shown this once:\", secret);\n }, body);\n return;\n }\n\n if (action === \"revoke\") {\n const id = parsedLine(() => {\n if (!positionals[1]) throw new UsageError(\"rebase auth keys revoke needs the key's id (`rebase auth keys` lists them).\");\n return positionals[1];\n });\n await confirmDestructive({ yes: flags[\"--yes\"] === true, prompt: `Revoke your key ${id} on ${target.label}? Anything using it stops working.` });\n await requestJson(target, `/api/auth/keys/${encodeURIComponent(id)}`, `Failed to revoke ${id}`, { method: \"DELETE\" });\n emit(() => success(`Revoked ${id}.`), { id, revoked: true });\n return;\n }\n\n const body = await requestJson(target, \"/api/auth/keys\", \"Failed to list your keys\");\n const keys = recordsOf(isRecord(body) ? body.keys : body);\n emit(() => {\n if (keys.length === 0) return note(\"You have no personal keys on this server.\");\n for (const key of keys) {\n const scopes = Array.isArray(key.scopes) ? key.scopes.map(String).join(\", \") : \"\";\n const state = key.revoked_at ? chalk.red(\"revoked\") : chalk.green(\"active\");\n console.log(` ${chalk.bold(stringOf(key.name) ?? \"?\")} ${chalk.gray(`[${stringOf(key.key_prefix) ?? \"\"}•••]`)} ${state} ${chalk.gray(stringOf(key.id) ?? \"\")}`);\n if (scopes) console.log(chalk.gray(` ${scopes}`));\n }\n }, body);\n}\n"],"mappings":";;;;;;;;AAgDA,SAAgB,YAAY,OAAuB;CAC/C,MAAM,UAAU,MAAM,MAAM,GAAG,CAAC,CAAC;CACjC,IAAI,SACA,IAAI;EACA,MAAM,SAAkB,KAAK,MAAM,OAAO,KAAK,SAAS,WAAW,CAAC,CAAC,SAAS,MAAM,CAAC;EACrF,IAAI,SAAS,MAAM,KAAK,OAAO,OAAO,QAAQ,UAAU,OAAO,OAAO,MAAM;CAChF,QAAQ,CAER;CAEJ,OAAO,KAAK,IAAI,IAAI,KAAK;AAC7B;AAEA,SAAS,aAAsB;CAC3B,OAAO,CAAC,WAAW,KAAK,QAAQ,MAAM,UAAU;AACpD;;AAGA,eAAe,aAAa,OAA0C,SAAyC;CAC3G,OAAO,cAAc;EAAE,GAAG;EAAO,UAAU;EAAM,WAAW,KAAA;EAAW,aAAa,KAAA;CAAU,GAAG,EAAE,QAAQ,CAAC;AAChH;AAMA,IAAa,mBAAmB;CAC5B,GAAG;CACH,WAAW;CACX,MAAM;CACN,cAAc;CACd,UAAU;CACV,SAAS;CACT,gBAAgB;AACpB;AAIA,eAAsB,UAAU,SAAkC;CAC9D,MAAM,EAAE,UAAU,iBAAiB,iBAAiB;EAChD,MAAM;EACN;EACA,cAAc;EACd,SAAS;EACT,gBAAgB;CACpB,CAAC,CAAC;CACF,IAAI,MAAM,cAAc,MAAM,gBAAgB,MAAM,WAChD,KAAK,qGAAqG,KAAA,GAAW,OAAO;CAEhI,MAAM,SAAS,M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,MAAM,OAAO,MAAM;GACpB,MAAM,SAAS,MAAM,QAAQ,IAAI,MAAM,IAAI,IAAI,OAAO,IAAI,MAAM,CAAC,CAAC,KAAK,IAAI,IAAI;GAC/E,MAAM,QAAQ,IAAI,aAAa,MAAM,IAAI,SAAS,IAAI,MAAM,MAAM,QAAQ;GAC1E,QAAQ,IAAI,KAAK,MAAM,KAAK,SAAS,IAAI,IAAI,KAAK,GAAG,EAAE,GAAG,MAAM,KAAK,IAAI,SAAS,IAAI,UAAU,KAAK,GAAG,KAAK,EAAE,GAAG,MAAM,IAAI,MAAM,KAAK,SAAS,IAAI,EAAE,KAAK,EAAE,GAAG;GAChK,IAAI,QAAQ,QAAQ,IAAI,MAAM,KAAK,SAAS,QAAQ,CAAC;EACzD;CACJ,GAAG,IAAI;AACX"}
1
+ {"version":3,"file":"auth-session-DCG96UGH.js","names":[],"sources":["../src/commands/auth-session.ts"],"sourcesContent":["/**\n * CLI commands: rebase auth login | logout | whoami | emails | keys\n *\n * A person's session on a running app — not on Rebase Cloud's control plane,\n * which is `rebase cloud login`. Some of an app's routes answer a person and\n * never a machine: the RLS simulator, the impersonation and simulation\n * headers, live schema apply (a commit needs an author), personal API keys.\n * The service key will never reach them, by design. `rebase auth login`\n * stores a session for one server in `~/.rebase/sessions.json` (keyed by its\n * origin, never in the project directory), and every project command sends\n * it on `--session`; `rebase rls simulate` and `rebase auth keys` send it by\n * default.\n *\n * `auth emails` is the other thing a terminal needs while building auth\n * flows: the development mailbox — every sign-in, reset and magic-link mail a\n * server with no SMTP_HOST captured instead of sending, with its links.\n */\nimport type arg from \"arg\";\nimport chalk from \"chalk\";\nimport inquirer from \"inquirer\";\n\nimport { parseCommandArgs, UsageError } from \"../utils/args\";\nimport {\n PROJECT_TARGET_FLAGS,\n forgetSession,\n saveSession,\n sessionKey,\n storedSession,\n type ProjectTarget\n} from \"../utils/project-target\";\nimport {\n emit,\n fail,\n isJsonMode,\n isRecord,\n parsedLine,\n projectTarget,\n recordsOf,\n requestJson,\n stringOf\n} from \"../utils/project-command\";\nimport { cliUserAgent } from \"../utils/version\";\nimport { confirmDestructive, note, success, warn } from \"./cloud/context\";\n\n/** The subcommands this module answers, beside `reset-password` in `auth.ts`. */\nexport const AUTH_SESSION_SUBCOMMANDS = [\"login\", \"logout\", \"whoami\", \"emails\", \"keys\"] as const;\n\n/** The access token's expiry, from its `exp` claim, in epoch milliseconds. */\nexport function tokenExpiry(token: string): number {\n const payload = token.split(\".\")[1];\n if (payload) {\n try {\n const claims: unknown = JSON.parse(Buffer.from(payload, \"base64url\").toString(\"utf8\"));\n if (isRecord(claims) && typeof claims.exp === \"number\") return claims.exp * 1000;\n } catch {\n // Not a JWT we can read: fall through to a short, safe guess.\n }\n }\n return Date.now() + 15 * 60_000;\n}\n\nfunction atTerminal(): boolean {\n return !isJsonMode() && process.stdin.isTTY === true;\n}\n\n/** The origin a session is for: the target, reached with no credential of its own. */\nasync function originTarget(flags: Readonly<Record<string, unknown>>, command: string): Promise<ProjectTarget> {\n return projectTarget({ ...flags, \"--anon\": true, \"--token\": undefined, \"--session\": undefined }, { command });\n}\n\n/* ═══════════════════════════════════════════════════════════════\n login\n ═══════════════════════════════════════════════════════════════ */\n\nexport const AUTH_LOGIN_FLAGS = {\n ...PROJECT_TARGET_FLAGS,\n \"--email\": String,\n \"-e\": \"--email\",\n \"--password\": String,\n \"--code\": String,\n \"--web\": Boolean,\n \"--no-browser\": Boolean\n} satisfies arg.Spec;\n\ntype SignedIn = { user: unknown; accessToken: string; refreshToken?: string };\n\nexport async function authLogin(rawArgs: string[]): Promise<void> {\n const { flags } = parsedLine(() => parseCommandArgs({\n spec: AUTH_LOGIN_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"auth login\",\n maxPositionals: 0\n }));\n if (flags[\"--token\"] || flags[\"--session\"] || flags[\"--anon\"]) {\n fail(\"`rebase auth login` signs in; --token, --session and --anon pick a credential for other commands.\", undefined, \"usage\");\n }\n const target = await originTarget(flags, \"auth login\");\n const origin = target.baseUrl;\n const { createRebaseClient } = await import(\"@rebasepro/client\");\n const client = createRebaseClient({\n baseUrl: origin,\n realtime: false,\n headers: { \"User-Agent\": cliUserAgent() },\n auth: { persistSession: false, autoRefresh: false }\n });\n\n const config = await requestJson(target, \"/api/auth/config\", `Could not read how ${origin} signs people in`).catch(() => null);\n const deviceLogin = isRecord(config) && (config.deviceLogin === true || isRecord(config.deviceLogin));\n\n let signedIn: SignedIn;\n const email = flags[\"--email\"];\n if (flags[\"--web\"] || (!email && deviceLogin)) {\n if (!deviceLogin) {\n fail(`${origin} does not offer signing in through a browser.`, \"Pass --email <address> to sign in with a password.\", \"device_login_unavailable\");\n }\n signedIn = await signInWithBrowser(client.auth, flags[\"--no-browser\"] !== true);\n } else {\n let address = email;\n if (!address) {\n if (!atTerminal()) fail(\"Signing in needs an email and a password, and there is no terminal to ask on.\", \"Pass --email <address> --password <password>.\", \"input_required\");\n ({ address } = await inquirer.prompt([{ type: \"input\", name: \"address\", message: \"Email:\" }]));\n }\n let password = flags[\"--password\"];\n if (!password) {\n if (!atTerminal()) fail(\"Signing in needs a password, and there is no terminal to ask on.\", \"Pass --password <password>.\", \"input_required\");\n ({ password } = await inquirer.prompt([{ type: \"password\", name: \"password\", message: \"Password:\", mask: \"*\" }]));\n }\n const who = String(address ?? \"\").trim();\n const secret = String(password ?? \"\");\n signedIn = await withSecondFactor(client.auth, flags[\"--code\"], () => client.auth.signInWithEmail(who, secret));\n }\n\n const user = isRecord(signedIn.user) ? signedIn.user : {};\n const roles = Array.isArray(user.roles) ? user.roles.map(String) : [];\n saveSession(origin, {\n accessToken: signedIn.accessToken,\n ...(signedIn.refreshToken ? { refreshToken: signedIn.refreshToken } : {}),\n expiresAt: tokenExpiry(signedIn.accessToken),\n ...(stringOf(user.email) ? { email: stringOf(user.email) } : {}),\n ...(stringOf(user.uid ?? user.id) ? { uid: stringOf(user.uid ?? user.id) } : {})\n });\n emit(() => {\n success(`Signed in to ${sessionKey(origin)} as ${stringOf(user.email) ?? stringOf(user.uid) ?? \"?\"}${roles.length ? ` (${roles.join(\", \")})` : \"\"}.`);\n note(chalk.gray(\"Commands send this session with --session; `rebase rls simulate` and `rebase auth keys` send it by default.\"));\n }, { origin: sessionKey(origin), user: { uid: stringOf(user.uid ?? user.id) ?? null, email: stringOf(user.email) ?? null, roles } });\n}\n\ntype ProjectAuth = Awaited<ReturnType<typeof import(\"@rebasepro/client\")[\"createRebaseClient\"]>>[\"auth\"];\n\n/** The `MFA_REQUIRED` refusal's details: the pending token and the factors to answer with. */\nfunction pendingSecondFactor(error: unknown): { mfaToken: string; factors: Array<{ id: string; name: string }> } | null {\n if (!isRecord(error) || error.code !== \"MFA_REQUIRED\" || !isRecord(error.details)) return null;\n const mfaToken = stringOf(error.details.mfaToken);\n const factors = recordsOf(error.details.factors)\n .map(f => ({ id: stringOf(f.id) ?? \"\", name: stringOf(f.friendlyName) ?? stringOf(f.factorType) ?? \"factor\" }))\n .filter(f => f.id);\n return mfaToken && factors.length > 0 ? { mfaToken, factors } : null;\n}\n\n/** Run a sign-in; when the account has two-factor authentication on, answer the challenge. */\nasync function withSecondFactor(auth: ProjectAuth, code: string | undefined, signIn: () => Promise<SignedIn>): Promise<SignedIn> {\n try {\n return await signIn();\n } catch (e) {\n const pending = pendingSecondFactor(e);\n if (!pending) throw e;\n let answer = code;\n if (!answer) {\n if (!atTerminal()) fail(\"This account has two-factor authentication on, and there is no terminal to ask for the code on.\", \"Pass --code <code>.\", \"mfa_required\");\n ({ answer } = await inquirer.prompt([{ type: \"input\", name: \"answer\", message: \"Code from your authenticator app (or a recovery code):\" }]));\n }\n const options = { mfaToken: pending.mfaToken };\n const { challengeId } = await auth.mfa.challenge(pending.factors[0].id, options);\n return auth.mfa.verifyChallenge(challengeId, String(answer ?? \"\").replace(/\\s+/g, \"\"), options);\n }\n}\n\n/** The framework's device sign-in: show the link and code, then poll until it is approved. */\nasync function signInWithBrowser(auth: ProjectAuth, openBrowser: boolean): Promise<SignedIn> {\n const started = await auth.startDeviceLogin({ clientName: `Rebase CLI on ${(await import(\"os\")).hostname()}` });\n process.stderr.write(`To sign in, open ${started.verificationUriComplete}\\n and check that it shows the code ${started.userCode}.\\n`);\n if (openBrowser && atTerminal()) {\n const { openUrl } = await import(\"./cloud/context\");\n openUrl(started.verificationUriComplete);\n }\n const deadline = Date.now() + started.expiresIn * 1000;\n let interval = started.interval;\n while (Date.now() < deadline) {\n await new Promise(resolve => setTimeout(resolve, interval * 1000));\n const result = await auth.pollDeviceLogin(started.deviceCode);\n if (result.status === \"approved\") return { user: result.user, accessToken: result.accessToken, refreshToken: result.refreshToken };\n if (result.status === \"denied\") fail(\"The sign-in was denied in the browser.\", undefined, \"access_denied\");\n if (result.status === \"expired\") break;\n interval = result.interval;\n }\n fail(\"The sign-in link expired before it was approved.\", \"Run `rebase auth login` again.\", \"expired_token\");\n}\n\n/* ═══════════════════════════════════════════════════════════════\n logout / whoami\n ═══════════════════════════════════════════════════════════════ */\n\nexport const AUTH_LOGOUT_FLAGS = { ...PROJECT_TARGET_FLAGS } satisfies arg.Spec;\n\nexport async function authLogout(rawArgs: string[]): Promise<void> {\n const { flags } = parsedLine(() => parseCommandArgs({\n spec: AUTH_LOGOUT_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"auth logout\",\n maxPositionals: 0\n }));\n const target = await originTarget(flags, \"auth logout\");\n const session = storedSession(target.baseUrl);\n if (!session) {\n emit(() => note(`No session is stored for ${sessionKey(target.baseUrl)}.`), { origin: sessionKey(target.baseUrl), signedOut: false });\n return;\n }\n // End it on the server too, so the refresh token stops working there and\n // not only here. A server that cannot be reached still loses it locally.\n if (session.refreshToken) {\n await target.request(\"/api/auth/logout\", { method: \"POST\", json: { refreshToken: session.refreshToken }, timeoutMs: 10_000 }).catch(() => undefined);\n }\n forgetSession(target.baseUrl);\n emit(() => success(`Signed out of ${sessionKey(target.baseUrl)}.`), { origin: sessionKey(target.baseUrl), signedOut: true });\n}\n\nexport const AUTH_WHOAMI_FLAGS = { ...PROJECT_TARGET_FLAGS } satisfies arg.Spec;\n\n/**\n * Who the server takes this command to be: `/api/auth/me` for a person's\n * session or token, and the scopes the credential holds (`/api/auth/scopes`),\n * which answers keys and the service key too.\n */\nexport async function authWhoami(rawArgs: string[]): Promise<void> {\n const { flags } = parsedLine(() => parseCommandArgs({\n spec: AUTH_WHOAMI_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"auth whoami\",\n maxPositionals: 0\n }));\n const usesSession = !flags[\"--token\"] && !flags[\"--anon\"];\n const target = await projectTarget(flags, { command: \"auth whoami\", ...(usesSession && !flags[\"--session\"] ? { defaultCredential: \"person\" as const } : {}) });\n const scopes = await requestJson(target, \"/api/auth/scopes\", \"Failed to read what this credential holds\");\n const me = target.credential === \"session\" || target.credential === \"token\"\n ? await target.request(\"/api/auth/me\", { timeoutMs: 15_000 }).then(async res => (res.ok ? res.json() as Promise<unknown> : null)).catch(() => null)\n : null;\n const user = isRecord(me) && isRecord(me.user) ? me.user : isRecord(me) ? me : undefined;\n const held = isRecord(scopes) && Array.isArray(scopes.held) ? scopes.held.map(String) : [];\n emit(() => {\n console.log(` ${chalk.gray(\"server\".padEnd(10))}${target.label}`);\n console.log(` ${chalk.gray(\"as\".padEnd(10))}${user ? `${stringOf(user.email) ?? stringOf(user.uid) ?? \"?\"} (${target.credential})` : target.credential}`);\n if (user && Array.isArray(user.roles)) console.log(` ${chalk.gray(\"roles\".padEnd(10))}${user.roles.map(String).join(\", \") || chalk.gray(\"none\")}`);\n console.log(` ${chalk.gray(\"scopes\".padEnd(10))}${held.length ? held.join(\", \") : chalk.gray(\"none\")}`);\n }, { server: target.label, credential: target.credential, user: user ?? null, scopes: held });\n}\n\n/* ═══════════════════════════════════════════════════════════════\n emails — the development mailbox\n ═══════════════════════════════════════════════════════════════ */\n\nexport const AUTH_EMAILS_FLAGS = {\n ...PROJECT_TARGET_FLAGS,\n \"--latest\": Boolean,\n \"--to\": String,\n \"--clear\": Boolean,\n \"--links\": Boolean\n} satisfies arg.Spec;\n\nexport async function authEmails(rawArgs: string[]): Promise<void> {\n const { flags } = parsedLine(() => parseCommandArgs({\n spec: AUTH_EMAILS_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"auth emails\",\n maxPositionals: 0\n }));\n const target = await projectTarget(flags, { command: \"auth emails\" });\n if (flags[\"--clear\"]) {\n await requestJson(target, \"/api/admin/dev/emails\", \"Failed to clear the development mailbox\", { method: \"DELETE\" });\n emit(() => success(\"Cleared the development mailbox.\"), { cleared: true });\n return;\n }\n const body = await requestJson(target, \"/api/admin/dev/emails\", \"Failed to read the development mailbox\");\n let messages = recordsOf(isRecord(body) ? body.messages : undefined);\n if (flags[\"--to\"]) {\n const to = flags[\"--to\"].toLowerCase();\n messages = messages.filter(message => stringOf(message.to)?.toLowerCase().includes(to));\n }\n if (flags[\"--latest\"]) messages = messages.slice(0, 1);\n if (flags[\"--links\"]) {\n // Only the links, one per line: what a script pipes into the next step.\n for (const message of messages) for (const link of Array.isArray(message.links) ? message.links : []) process.stdout.write(`${String(link)}\\n`);\n return;\n }\n emit(() => {\n if (messages.length === 0) return note(\"The development mailbox is empty.\");\n for (const message of messages) {\n console.log(` ${chalk.gray(stringOf(message.at) ?? \"\")} ${chalk.bold(stringOf(message.to) ?? \"?\")} ${stringOf(message.subject) ?? \"\"}`);\n for (const link of Array.isArray(message.links) ? message.links : []) console.log(` ${chalk.cyan(String(link))}`);\n }\n }, { messages });\n}\n\n/* ═══════════════════════════════════════════════════════════════\n keys — your own personal API keys\n ═══════════════════════════════════════════════════════════════ */\n\nexport const AUTH_KEYS_FLAGS = {\n ...PROJECT_TARGET_FLAGS,\n \"--name\": String,\n \"-n\": \"--name\",\n \"--scopes\": [String],\n \"--expires-in\": String\n} satisfies arg.Spec;\n\n/**\n * A person's own `rk_` keys (`/api/auth/keys`): list, create, revoke. They act\n * as their owner, with the owner's live roles, narrowed to the scopes named.\n * The server answers a person's session only, and only when the auth table\n * sets `auth.personalKeys: true`. Service keys are `rebase api-keys`.\n */\nexport async function authKeys(rawArgs: string[]): Promise<void> {\n const { flags, positionals } = parsedLine(() => parseCommandArgs({\n spec: AUTH_KEYS_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"auth keys\",\n maxPositionals: 2\n }));\n const action = positionals[0] ?? \"list\";\n if (![\"list\", \"create\", \"revoke\"].includes(action)) {\n const { unknownCommand } = await import(\"../utils/unknown-command\");\n unknownCommand(action, [\"list\", \"create\", \"revoke\"], \"auth keys\");\n }\n const target = await projectTarget(flags, { command: \"auth keys\", defaultCredential: \"person\" });\n\n if (action === \"create\") {\n const { scopes, expiresAt } = parsedLine(() => {\n const list = (flags[\"--scopes\"] ?? []).flatMap(s => s.split(\",\")).map(s => s.trim()).filter(Boolean);\n if (list.length === 0) throw new UsageError(\"rebase auth keys create needs --scopes, e.g. --scopes data:read:posts (never more than you hold).\");\n let expires: string | undefined;\n if (flags[\"--expires-in\"]) {\n const days = Number(flags[\"--expires-in\"].replace(/d$/, \"\"));\n if (!Number.isFinite(days) || days <= 0) throw new UsageError(\"--expires-in takes a number of days, e.g. 30 or 30d.\");\n expires = new Date(Date.now() + days * 86_400_000).toISOString();\n }\n return { scopes: list, expiresAt: expires };\n });\n const body = await requestJson(target, \"/api/auth/keys\", \"Failed to create the key\", {\n method: \"POST\",\n json: { name: flags[\"--name\"] ?? \"CLI key\", scopes, ...(expiresAt ? { expires_at: expiresAt } : {}) }\n });\n const secret = isRecord(body) ? stringOf(body.key) ?? (isRecord(body.key) ? stringOf(body.key.key) : undefined) : undefined;\n emit(() => {\n success(`Created a personal key holding ${scopes.join(\", \")}.`);\n if (secret) warn(\"It is shown this once:\", secret);\n }, body);\n return;\n }\n\n if (action === \"revoke\") {\n const id = parsedLine(() => {\n if (!positionals[1]) throw new UsageError(\"rebase auth keys revoke needs the key's id (`rebase auth keys` lists them).\");\n return positionals[1];\n });\n await confirmDestructive({ yes: flags[\"--yes\"] === true, prompt: `Revoke your key ${id} on ${target.label}? Anything using it stops working.` });\n await requestJson(target, `/api/auth/keys/${encodeURIComponent(id)}`, `Failed to revoke ${id}`, { method: \"DELETE\" });\n emit(() => success(`Revoked ${id}.`), { id, revoked: true });\n return;\n }\n\n const body = await requestJson(target, \"/api/auth/keys\", \"Failed to list your keys\");\n const keys = recordsOf(isRecord(body) ? body.keys : body);\n emit(() => {\n if (keys.length === 0) return note(\"You have no personal keys on this server.\");\n for (const key of keys) {\n const scopes = Array.isArray(key.scopes) ? key.scopes.map(String).join(\", \") : \"\";\n const state = key.revoked_at ? chalk.red(\"revoked\") : chalk.green(\"active\");\n console.log(` ${chalk.bold(stringOf(key.name) ?? \"?\")} ${chalk.gray(`[${stringOf(key.key_prefix) ?? \"\"}•••]`)} ${state} ${chalk.gray(stringOf(key.id) ?? \"\")}`);\n if (scopes) console.log(chalk.gray(` ${scopes}`));\n }\n }, body);\n}\n"],"mappings":";;;;;;;;AAgDA,SAAgB,YAAY,OAAuB;CAC/C,MAAM,UAAU,MAAM,MAAM,GAAG,CAAC,CAAC;CACjC,IAAI,SACA,IAAI;EACA,MAAM,SAAkB,KAAK,MAAM,OAAO,KAAK,SAAS,WAAW,CAAC,CAAC,SAAS,MAAM,CAAC;EACrF,IAAI,SAAS,MAAM,KAAK,OAAO,OAAO,QAAQ,UAAU,OAAO,OAAO,MAAM;CAChF,QAAQ,CAER;CAEJ,OAAO,KAAK,IAAI,IAAI,KAAK;AAC7B;AAEA,SAAS,aAAsB;CAC3B,OAAO,CAAC,WAAW,KAAK,QAAQ,MAAM,UAAU;AACpD;;AAGA,eAAe,aAAa,OAA0C,SAAyC;CAC3G,OAAO,cAAc;EAAE,GAAG;EAAO,UAAU;EAAM,WAAW,KAAA;EAAW,aAAa,KAAA;CAAU,GAAG,EAAE,QAAQ,CAAC;AAChH;AAMA,IAAa,mBAAmB;CAC5B,GAAG;CACH,WAAW;CACX,MAAM;CACN,cAAc;CACd,UAAU;CACV,SAAS;CACT,gBAAgB;AACpB;AAIA,eAAsB,UAAU,SAA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AAS;EAAK,CAAC;EAC3D;CACJ;CAEA,MAAM,OAAO,MAAM,YAAY,QAAQ,kBAAkB,0BAA0B;CACnF,MAAM,OAAO,UAAU,SAAS,IAAI,IAAI,KAAK,OAAO,IAAI;CACxD,WAAW;EACP,IAAI,KAAK,WAAW,GAAG,OAAO,KAAK,2CAA2C;EAC9E,KAAK,MAAM,OAAO,MAAM;GACpB,MAAM,SAAS,MAAM,QAAQ,IAAI,MAAM,IAAI,IAAI,OAAO,IAAI,MAAM,CAAC,CAAC,KAAK,IAAI,IAAI;GAC/E,MAAM,QAAQ,IAAI,aAAa,MAAM,IAAI,SAAS,IAAI,MAAM,MAAM,QAAQ;GAC1E,QAAQ,IAAI,KAAK,MAAM,KAAK,SAAS,IAAI,IAAI,KAAK,GAAG,EAAE,GAAG,MAAM,KAAK,IAAI,SAAS,IAAI,UAAU,KAAK,GAAG,KAAK,EAAE,GAAG,MAAM,IAAI,MAAM,KAAK,SAAS,IAAI,EAAE,KAAK,EAAE,GAAG;GAChK,IAAI,QAAQ,QAAQ,IAAI,MAAM,KAAK,SAAS,QAAQ,CAAC;EACzD;CACJ,GAAG,IAAI;AACX"}
@@ -4,11 +4,11 @@ import { a as wantsHelp, n as parseCommandArgs, t as UsageError } from "./args-D
4
4
  import { p as requireProjectRoot } from "./project-DALmhb5R.js";
5
5
  import { C as resolveBackendPaths, T as staticAppAddress, _ as findBackendApp, b as loadManifest, l as ManifestError, m as buildableApps, y as formatAppAddress } from "./manifest-RjqxfCpb.js";
6
6
  import { n as cliVersion } from "./version-ONIeo7jl.js";
7
- import { E as toolStdio, _ as detectFrameworkDepDrift, c as buildBundle, l as buildStaticBundle, n as DEFAULT_BUNDLE_DIR, r as UNVENDORED_COST, w as unvendoredReason } from "./bundle-CIiKGrte.js";
7
+ import { E as toolStdio, _ as detectFrameworkDepDrift, c as buildBundle, l as buildStaticBundle, n as DEFAULT_BUNDLE_DIR, r as UNVENDORED_COST, w as unvendoredReason } from "./bundle-DhdhtD8K.js";
8
8
  import { i as assertBackendGuarded } from "./backend-guard-Cf8eMK_f.js";
9
- import { i as staticBuildEnv, n as foldFrontendIntoBundle, t as assertBuiltForPath } from "./fold-static-2t3UUX4z.js";
9
+ import { i as staticBuildEnv, n as foldFrontendIntoBundle, t as assertBuiltForPath } from "./fold-static-DTpaqbB0.js";
10
10
  import { n as legacyCollectionsDir, r as legacyLayoutRefusal } from "./legacy-layout-DI2VeQSV.js";
11
- import { l as writeResourceGraphFile, n as deriveOptionsFor, r as deriveResourceGraph, t as RESOURCE_GRAPH_FILENAME } from "./derive-Mky_u59_.js";
11
+ import { l as writeResourceGraphFile, n as deriveOptionsFor, r as deriveResourceGraph, t as RESOURCE_GRAPH_FILENAME } from "./derive-ChP6vgfi.js";
12
12
  import chalk from "chalk";
13
13
  import fs from "fs";
14
14
  import path from "path";
@@ -365,4 +365,4 @@ async function runWorkspaceBuilds(projectRoot) {
365
365
  //#endregion
366
366
  export { build_exports as n, buildAssetApp as t };
367
367
 
368
- //# sourceMappingURL=build-E5hfEWKj.js.map
368
+ //# sourceMappingURL=build-D0egCUfU.js.map