@rebasepro/cli 0.32.0 → 0.33.1

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 (29) hide show
  1. package/dist/{build-BfdT-AUR.js → build-E5hfEWKj.js} +13 -2
  2. package/dist/build-E5hfEWKj.js.map +1 -0
  3. package/dist/{cloud-MqnyPnmX.js → cloud-DNJyUU0T.js} +310 -120
  4. package/dist/cloud-DNJyUU0T.js.map +1 -0
  5. package/dist/codemod/collections-to-tables/customization.d.ts +5 -0
  6. package/dist/{command-D9g46gg9.js → command-Bks5xkrQ.js} +22 -3
  7. package/dist/command-Bks5xkrQ.js.map +1 -0
  8. package/dist/commands/cloud/env.d.ts +11 -1
  9. package/dist/commands/cloud/service-key.d.ts +33 -1
  10. package/dist/{doctor-2Jlau0Rm.js → doctor-FaBObSlb.js} +21 -3
  11. package/dist/doctor-FaBObSlb.js.map +1 -0
  12. package/dist/doctor-environment.d.ts +9 -0
  13. package/dist/index.es.js +9 -9
  14. package/dist/legacy-layout-DI2VeQSV.js +36 -0
  15. package/dist/legacy-layout-DI2VeQSV.js.map +1 -0
  16. package/dist/{logs-CIgfLBsu.js → logs-DpuMukJe.js} +2 -2
  17. package/dist/{logs-CIgfLBsu.js.map → logs-DpuMukJe.js.map} +1 -1
  18. package/dist/{migrate-Cx8-Y4TG.js → migrate-CSY9ZDKy.js} +3 -3
  19. package/dist/{migrate-Cx8-Y4TG.js.map → migrate-CSY9ZDKy.js.map} +1 -1
  20. package/dist/{upgrade-DhpUFb6p.js → upgrade-ZASvgxWM.js} +38 -6
  21. package/dist/{upgrade-DhpUFb6p.js.map → upgrade-ZASvgxWM.js.map} +1 -1
  22. package/dist/utils/legacy-layout.d.ts +22 -0
  23. package/package.json +10 -10
  24. package/templates/overlays/baas/backend/package.json +3 -1
  25. package/templates/template/backend/package.json +3 -1
  26. package/dist/build-BfdT-AUR.js.map +0 -1
  27. package/dist/cloud-MqnyPnmX.js.map +0 -1
  28. package/dist/command-D9g46gg9.js.map +0 -1
  29. package/dist/doctor-2Jlau0Rm.js.map +0 -1
@@ -1,13 +1,14 @@
1
1
  import { i as recordEvent, l as durationBucket } from "./telemetry-EVtASbKb.js";
2
2
  import { i as switchOn } from "./args-DHyrshtI.js";
3
3
  import { c as findProjectRoot, p as requireProjectRoot } from "./project-DALmhb5R.js";
4
- import { _ as findBackendApp, b as loadManifest, h as cmsMountOf, w as selectDeployApp, y as formatAppAddress } from "./manifest-RjqxfCpb.js";
4
+ import { C as resolveBackendPaths, _ as findBackendApp, b as loadManifest, h as cmsMountOf, w as selectDeployApp, y as formatAppAddress } from "./manifest-RjqxfCpb.js";
5
5
  import { t as cliUserAgent } from "./version-ONIeo7jl.js";
6
6
  import { E as toolStdio, c as buildBundle, r as UNVENDORED_COST, w as unvendoredReason } from "./bundle-CIiKGrte.js";
7
7
  import { $ as resolveCloudTarget, A as linkedEphemeralGrant, B as projectHost, C as getContextOrg, D as isJsonMode, E as initOutputMode, F as parseCloudArgs, G as reportError, H as readLink, I as printGroupHelp, J as requireInteractive, K as requireClient, L as printJson, M as note, N as noteBlank, O as isKnownControlPlane, P as openUrl, Q as requireSessionClient, R as probeToken, S as freshAccessToken, T as grantProjectOf, U as refuseDirectLink, V as projectLinkPath, W as removeLink, X as requireProject, Y as requireKnownAction, Z as requireProjectRef, _ as ephemeralGrantFor, _t as isTokenCapability, a as billingAccountIdOf, at as setCurrentContext, b as fetchTenantBaseDomain, bt as scopesForOrgCapabilities, c as colorStatus, ct as warn, d as createCloudClient, dt as ORG_CAPABILITIES, et as resolveCloudUrl, f as displayProjectRef, ft as ORG_CAPABILITY_NAMES, g as envToken, gt as isOrgCapability, h as emitHelp, ht as capabilitiesInScopes, i as appKeyExpiryNote, it as setContextOrg, j as lookupProjectId, k as keyValues, l as confirmDestructive, lt as writeLink, m as emit, mt as TOKEN_CAPABILITY_NAMES, n as GLOBAL_HELP_FLAGS, nt as resolveTimeoutMs, o as cloudRow, ot as storedGrantForLink, p as dotenvSets, pt as TOKEN_CAPABILITIES, q as requireCloudRow, r as TOKEN_ENV, rt as saveEphemeralGrant, s as cloudRows, st as success, t as GLOBAL_CLOUD_FLAGS, tt as resolveProjectRef, ut as ALWAYS_SCOPES, v as fail, vt as orgCapabilitiesInScopes, w as grantForLink, x as forgetEphemeralGrant, xt as wantsRawError, y as fetchDeployTargets, yt as scopesForCapabilities, z as projectDotenvSetsAppKey } from "./context-BOMEoKxn.js";
8
8
  import { n as foldFrontendIntoBundle, r as foldableApps } from "./fold-static-2t3UUX4z.js";
9
+ import { n as legacyCollectionsDir, r as legacyLayoutRefusal, t as MIGRATE_COMMAND } from "./legacy-layout-DI2VeQSV.js";
9
10
  import { n as deriveOptionsFor, r as deriveResourceGraph } from "./derive-Mky_u59_.js";
10
- import { t as buildAssetApp } from "./build-BfdT-AUR.js";
11
+ import { t as buildAssetApp } from "./build-E5hfEWKj.js";
11
12
  import { a as parseLogLine, c as resolveOrigin, i as isErrorLine, l as resolveTail, n as debugCommand, o as parseSince, s as printDebugHelp, t as SERVER_MAX_TAIL_LINES } from "./debug-nNbbxAeo.js";
12
13
  import { cronCommand, isMissingRoute } from "./cron-ZRXsla0v.js";
13
14
  import chalk from "chalk";
@@ -17,7 +18,7 @@ import os from "os";
17
18
  import path from "path";
18
19
  import { execFileSync, spawn } from "child_process";
19
20
  import dotenv from "dotenv";
20
- import { DEFAULT_STORAGE_SOURCE_KEY } from "@rebasepro/types";
21
+ import { BUNDLE_FORMAT_VERSION, DEFAULT_STORAGE_SOURCE_KEY } from "@rebasepro/types";
21
22
  import fs$1 from "node:fs";
22
23
  import inquirer from "inquirer";
23
24
  import { RebaseApiError, createRebaseClient } from "@rebasepro/client";
@@ -4720,6 +4721,175 @@ function fmtDate(value) {
4720
4721
  return isNaN(d.getTime()) ? value : d.toLocaleString();
4721
4722
  }
4722
4723
  //#endregion
4724
+ //#region src/commands/cloud/service-key.ts
4725
+ /**
4726
+ * `rebase cloud service-key [rotate]`: the project's `REBASE_SERVICE_KEY`,
4727
+ * admin on the app's own API, and replacing it.
4728
+ *
4729
+ * The control plane derives the key from the project and a generation, and
4730
+ * injects it into the app. `rotate` issues the next generation and restarts
4731
+ * the app onto it in the background; the old key keeps working until that
4732
+ * restart has come up, and nothing after. Anything that copied the old key —
4733
+ * a script, a CI job, an agent's deployed code that printed it — is refused
4734
+ * from then on. A claim rotates it too.
4735
+ *
4736
+ * Without an action, prints the generation, when it was last rotated and
4737
+ * whether a rotation is still restarting the app. The key itself is
4738
+ * `rebase cloud env reveal REBASE_SERVICE_KEY`. Calls `GET` and `POST
4739
+ * /credentials/:projectId/service-key[/rotate]`, owners and admins, signed in.
4740
+ *
4741
+ * ## `--preview <name>`
4742
+ *
4743
+ * A backend preview (`rebase cloud deploy --preview`) runs with a service key
4744
+ * of its own, minted on its first deploy and kept across redeploys; production's
4745
+ * key answers 401 there. `service-key --preview <name>` prints that key, and
4746
+ * `rotate --preview <name>` writes a new one and restarts only the preview's
4747
+ * pod onto it. Calls `POST /previews/:projectId/:name/service-key/reveal` and
4748
+ * `…/rotate`, which ask what production's reveal asks: the organization's owner
4749
+ * or admin role, `project:env` on an access token, and a claimed project. So an
4750
+ * access token with the `env` capability reaches it, as it reaches `env
4751
+ * reveal`, and a login is not required.
4752
+ *
4753
+ * @module
4754
+ */
4755
+ /** What `service-key` says on a control plane that has no `credentials` function yet. */
4756
+ var SERVICE_KEY_UNSERVED = {
4757
+ what: "service-key rotation",
4758
+ hint: "Nothing was changed. `rebase cloud env reveal REBASE_SERVICE_KEY` still reads the current key."
4759
+ };
4760
+ /** What `service-key --preview` says on a control plane without the preview key routes. */
4761
+ var PREVIEW_SERVICE_KEY_UNSERVED = {
4762
+ what: "a preview's own service key",
4763
+ hint: "Nothing was changed. The preview still runs with the key its first deploy gave it."
4764
+ };
4765
+ var SERVICE_KEY_FLAGS = {
4766
+ /**
4767
+ * A backend preview's own key instead of production's, the preview named by
4768
+ * the positional after the action. A switch, as `deploy --preview` and
4769
+ * `logs --preview <name>` have it: the dispatcher's list of flags that take
4770
+ * a value is one list for the family (`value-flags.test.ts`).
4771
+ */
4772
+ "--preview": Boolean };
4773
+ var SERVICE_KEY_ACTIONS = ["rotate"];
4774
+ async function readStatus(client, projectId) {
4775
+ return client.functions.invoke("credentials", void 0, {
4776
+ method: "GET",
4777
+ path: `${encodeURIComponent(projectId)}/service-key`
4778
+ });
4779
+ }
4780
+ function printStatus(status, label) {
4781
+ console.log("");
4782
+ console.log(chalk.bold(` 🛡 Service key — ${label}`));
4783
+ console.log("");
4784
+ console.log(` Generation ${status.generation}`);
4785
+ console.log(` Rotated ${status.rotatedAt ? new Date(status.rotatedAt).toLocaleString() : chalk.gray("never")}`);
4786
+ if (status.pending) {
4787
+ console.log("");
4788
+ console.log(chalk.yellow(" The app has not restarted onto the newest key yet; the previous one still works until it has."));
4789
+ }
4790
+ console.log("");
4791
+ console.log(chalk.gray(` Read it with ${chalk.bold("rebase cloud env reveal REBASE_SERVICE_KEY")}; replace it with ${chalk.bold("rebase cloud service-key rotate")}.`));
4792
+ console.log(chalk.gray(` A backend preview has a key of its own: ${chalk.bold("rebase cloud service-key --preview <name>")}.`));
4793
+ console.log("");
4794
+ }
4795
+ /**
4796
+ * The preview `--preview` names, as the control plane spells it.
4797
+ *
4798
+ * Only trimmed and lowercased: the control plane decides which names exist,
4799
+ * and answers `not_found` for the rest. `deploy`'s stricter name check is for
4800
+ * a name about to be created.
4801
+ */
4802
+ function previewNameArg(raw, usage) {
4803
+ const name = (raw ?? "").trim().toLowerCase();
4804
+ if (name === "") fail(`Name the preview: \`${usage}\`.`, "`rebase cloud previews` lists them.", "usage");
4805
+ return name;
4806
+ }
4807
+ function previewKeyPath(projectId, name, action) {
4808
+ return `${encodeURIComponent(projectId)}/${encodeURIComponent(name)}/service-key/${action}`;
4809
+ }
4810
+ /** Read a backend preview's own key. `env reveal REBASE_SERVICE_KEY --preview <name>` lands here too. */
4811
+ async function revealPreviewServiceKey(client, projectId, name) {
4812
+ let res;
4813
+ try {
4814
+ res = await client.functions.invoke("previews", {}, { path: previewKeyPath(projectId, name, "reveal") });
4815
+ } catch (e) {
4816
+ reportCallError(e, "Failed to read the preview's service key", PREVIEW_SERVICE_KEY_UNSERVED);
4817
+ }
4818
+ emit(() => {
4819
+ console.log("");
4820
+ console.log(` ${chalk.bold(res.key)}=${res.value}`);
4821
+ console.log("");
4822
+ console.log(chalk.gray(` Preview ${chalk.bold(res.preview)} (${res.url}) only. Production's key is \`rebase cloud env reveal REBASE_SERVICE_KEY\`.`));
4823
+ console.log("");
4824
+ }, res);
4825
+ }
4826
+ async function rotatePreviewServiceKey(client, projectId, label, name, yes) {
4827
+ await confirmDestructive({
4828
+ yes,
4829
+ prompt: `Rotate the service key of ${label}? Its pod restarts onto a new key, and anything using the old one is refused once it has. Production is not touched.`
4830
+ });
4831
+ let rotation;
4832
+ try {
4833
+ rotation = await client.functions.invoke("previews", {}, { path: previewKeyPath(projectId, name, "rotate") });
4834
+ } catch (e) {
4835
+ reportCallError(e, "Failed to rotate the preview's service key", PREVIEW_SERVICE_KEY_UNSERVED);
4836
+ }
4837
+ emit(() => {
4838
+ success(`Issued a new service key for ${label}.`);
4839
+ note(rotation.state === "pending" ? "The preview has no pod running: its next deploy starts on the new key." : "Its pod is restarting onto it; the old key works until the new pod is ready.");
4840
+ note(`Read it with \`rebase cloud service-key --preview ${name}\`.`);
4841
+ }, rotation);
4842
+ }
4843
+ async function serviceKeyCommand(rawArgs) {
4844
+ const parsed = parseCloudArgs({
4845
+ spec: SERVICE_KEY_FLAGS,
4846
+ rawArgs,
4847
+ commandWords: 2,
4848
+ command: "cloud service-key",
4849
+ maxPositionals: 2
4850
+ });
4851
+ const preview = parsed.flags["--preview"] === true;
4852
+ const words = preview && parsed.positionals.length === 2 && parsed.positionals[1] === "rotate" ? [parsed.positionals[1], parsed.positionals[0]] : parsed.positionals;
4853
+ const action = preview ? words.length === 2 || words[0] === "rotate" ? words[0] : void 0 : words[0];
4854
+ if (!preview && words.length > 1) fail(`\`rebase cloud service-key ${words.join(" ")}\`: one action at most.`, "A preview is named after --preview.", "usage");
4855
+ requireKnownAction("service-key", action, SERVICE_KEY_ACTIONS);
4856
+ if (preview) {
4857
+ const name = previewNameArg(words.length === 2 ? words[1] : action === void 0 ? words[0] : void 0, `rebase cloud service-key ${action ? `${action} ` : ""}--preview <name>`);
4858
+ const { client } = await requireClient(rawArgs);
4859
+ const projectId = await requireProject(rawArgs, client);
4860
+ if (action === "rotate") return rotatePreviewServiceKey(client, projectId, `preview "${name}" of project ${displayProjectRef(rawArgs) || projectId}`, name, Boolean(parsed.flags["--yes"]));
4861
+ return revealPreviewServiceKey(client, projectId, name);
4862
+ }
4863
+ const { client } = await requireSessionClient(rawArgs, "rotate a project's service key");
4864
+ const projectId = await requireProject(rawArgs, client);
4865
+ const label = `project ${displayProjectRef(rawArgs) || projectId}`;
4866
+ if (action !== "rotate") {
4867
+ let status;
4868
+ try {
4869
+ status = await readStatus(client, projectId);
4870
+ } catch (e) {
4871
+ reportCallError(e, "Failed to read the service key's state", SERVICE_KEY_UNSERVED);
4872
+ }
4873
+ emit(() => printStatus(status, label), status);
4874
+ return;
4875
+ }
4876
+ await confirmDestructive({
4877
+ yes: Boolean(parsed.flags["--yes"]),
4878
+ prompt: `Rotate the service key of ${label}? The app restarts onto a new key, and anything using the old one is refused once it has.`
4879
+ });
4880
+ let rotation;
4881
+ try {
4882
+ rotation = await client.functions.invoke("credentials", {}, { path: `${encodeURIComponent(projectId)}/service-key/rotate` });
4883
+ } catch (e) {
4884
+ reportCallError(e, "Failed to rotate the service key", SERVICE_KEY_UNSERVED);
4885
+ }
4886
+ emit(() => {
4887
+ success(`Issued service key generation ${rotation.generation} for ${label}.`);
4888
+ note(rotation.state === "pending" ? "A deploy is running: the next deploy carries the new key. The old one works until then." : "The app is restarting onto it; the old key works until the restart has finished. Follow it with `rebase cloud service-key`.");
4889
+ note("Read the new key with `rebase cloud env reveal REBASE_SERVICE_KEY` once the restart is done.");
4890
+ }, rotation);
4891
+ }
4892
+ //#endregion
4723
4893
  //#region src/commands/cloud/env.ts
4724
4894
  /**
4725
4895
  * `rebase cloud env` — a project's environment variables.
@@ -4735,7 +4905,8 @@ function fmtDate(value) {
4735
4905
  * --preview` hands a variable back to production's value. A backend preview
4736
4906
  * starts from a copy of production's environment, live third-party keys
4737
4907
  * included; this is how a preview gets a test key instead, or none. Production
4738
- * is never changed by any of them.
4908
+ * is never changed by any of them. `reveal REBASE_SERVICE_KEY --preview <name>`
4909
+ * prints one backend preview's own service key (`service-key --preview`).
4739
4910
  *
4740
4911
  * Values are the sharp edge here. The list endpoint returns keys and never
4741
4912
  * values by design (a page load is not consent to spray a customer's secrets
@@ -5038,32 +5209,29 @@ async function setEnv(rawArgs) {
5038
5209
  }
5039
5210
  }
5040
5211
  /**
5041
- * The variable `env unset` / `env reveal` names.
5212
+ * {@link resolveEnvKeyArg}, and whether `--preview` was given (`unset` and
5213
+ * `reset` take it).
5042
5214
  *
5043
- * `unset` is a delete, and the operand filter aimed it at the wrong variable:
5044
- * `rebase cloud env unset -p acme` removed a variable called "acme" from the
5045
- * linked project instead of reporting a missing KEY, and `env unset -p acme
5046
- * KEY` removed "acme" instead of KEY. Both read `--project`'s value as the
5047
- * operand — a plain word in the right position that no flag filter can catch.
5048
- *
5049
- * `action` is the word the caller used (`unset`, `rm`, `delete`, `reveal`); the
5050
- * count of command words is the same for all of them.
5215
+ * `reveal` takes it too, with the preview's name after it, and only for
5216
+ * `REBASE_SERVICE_KEY` — the one value a backend preview holds that is neither
5217
+ * production's nor an override `env list --preview` already shows. The name
5218
+ * is a positional, as in `logs --preview <name>`, so `--preview` stays the
5219
+ * switch it is everywhere else.
5051
5220
  */
5052
- function resolveEnvKeyArg(rawArgs, action) {
5053
- return resolveEnvKeyArgs(rawArgs, action).key;
5054
- }
5055
- /** {@link resolveEnvKeyArg}, and whether `--preview` was given (`unset` and `reset` take it). */
5056
5221
  function resolveEnvKeyArgs(rawArgs, action) {
5057
5222
  const { flags, positionals } = parseCloudArgs({
5058
- spec: action === "reveal" ? {} : ENV_PREVIEW_FLAGS,
5223
+ spec: ENV_PREVIEW_FLAGS,
5059
5224
  rawArgs,
5060
5225
  commandWords: 3,
5061
5226
  command: `cloud env ${action}`,
5062
- maxPositionals: 1
5227
+ maxPositionals: action === "reveal" ? 2 : 1
5063
5228
  });
5229
+ const preview = flags["--preview"] === true;
5230
+ if (positionals.length > 1 && !preview) fail(`\`rebase cloud env ${action} ${positionals.join(" ")}\`: one KEY at most.`, "A preview is named after --preview.", "usage");
5064
5231
  return {
5065
5232
  key: positionals[0],
5066
- preview: flags["--preview"] === true,
5233
+ preview,
5234
+ previewName: positionals[1],
5067
5235
  yes: flags["--yes"] === true
5068
5236
  };
5069
5237
  }
@@ -5148,8 +5316,14 @@ async function resetPreviewEnv(rawArgs) {
5148
5316
  });
5149
5317
  }
5150
5318
  async function revealEnv(rawArgs) {
5151
- const key = resolveEnvKeyArg(rawArgs, "reveal");
5152
- if (!key) fail("Usage: rebase cloud env reveal KEY", void 0, "usage");
5319
+ const { key, preview, previewName } = resolveEnvKeyArgs(rawArgs, "reveal");
5320
+ if (!key) fail("Usage: rebase cloud env reveal KEY [--preview <name>]", void 0, "usage");
5321
+ if (preview) {
5322
+ if (key !== "REBASE_SERVICE_KEY") fail(`Only REBASE_SERVICE_KEY is revealed per preview; ${key} is not one a preview holds of its own.`, "A preview runs with production's variables and the overrides `rebase cloud env list --preview` shows.", "usage");
5323
+ const name = previewNameArg(previewName, "rebase cloud env reveal REBASE_SERVICE_KEY --preview <name>");
5324
+ const { client } = await requireClient(rawArgs);
5325
+ return revealPreviewServiceKey(client, await requireProject(rawArgs, client), name);
5326
+ }
5153
5327
  const { client } = await requireClient(rawArgs);
5154
5328
  const projectId = await requireProject(rawArgs, client);
5155
5329
  const projectRef = displayProjectRef(rawArgs);
@@ -5307,7 +5481,8 @@ function printEnvHelp() {
5307
5481
  {
5308
5482
  action: "reveal",
5309
5483
  args: "KEY",
5310
- description: "Print one non-secret value"
5484
+ description: "Print one non-secret value",
5485
+ flags: [["--preview <name>", "REBASE_SERVICE_KEY only: that backend preview's own key, as `service-key --preview` prints it"]]
5311
5486
  },
5312
5487
  {
5313
5488
  action: "pull",
@@ -8281,6 +8456,14 @@ async function deployBundle(opts) {
8281
8456
  });
8282
8457
  return;
8283
8458
  }
8459
+ if (target.app.type === "backend") {
8460
+ const tablesDir = resolveBackendPaths(target.app, projectRoot).tables;
8461
+ const legacy = legacyCollectionsDir(projectRoot, tablesDir);
8462
+ if (legacy) {
8463
+ const refusal = legacyLayoutRefusal(legacy, tablesDir);
8464
+ fail(refusal.message, refusal.hint, "legacy_layout");
8465
+ }
8466
+ }
8284
8467
  progress(chalk.gray(" Building bundle..."));
8285
8468
  const backend = {
8286
8469
  name: target.name,
@@ -8407,6 +8590,7 @@ async function uploadAndTrigger(opts) {
8407
8590
  startedAt: opts.startedAt,
8408
8591
  projectRoot
8409
8592
  });
8593
+ if (manifest.bundleFormat < BUNDLE_FORMAT_VERSION) fail(`${path.relative(process.cwd(), bundleDir) || "."} is a format-${manifest.bundleFormat} bundle, built from config/collections, and Rebase Cloud takes format ${BUNDLE_FORMAT_VERSION} (backend/schema). Nothing was uploaded.`, `In the project, run \`${MIGRATE_COMMAND}\`, commit, then \`rebase build\` with this CLI and deploy that bundle.`, "bundle_format_too_old");
8410
8594
  if (manifest.hooks?.native) {
8411
8595
  const names = (manifest.hooks.nativeModules ?? []).map((m) => m.name).join(", ");
8412
8596
  fail(`This bundle depends on native modules${names ? ` (${names})` : ""}, which the managed runtime cannot run.`, "Remove the native dependency, or deploy on the custom runtime.");
@@ -10686,6 +10870,7 @@ function printOrgsHelp() {
10686
10870
  * domains add <domain> Register a host (starts, does not finish, setup)
10687
10871
  * domains verify [domain] Check the host's published DNS now; live only if it passes
10688
10872
  * domains primary <domain> Make a verified host the canonical one
10873
+ * domains redirect <domain> Answer a host with a 308 to the primary (`--off` serves it again)
10689
10874
  * domains remove <domain> Stop serving a host
10690
10875
  *
10691
10876
  * A project's hosts are rows of the control plane's `project_domains` table,
@@ -10730,6 +10915,7 @@ function rowEntry(row) {
10730
10915
  id: row.id,
10731
10916
  host: row.host,
10732
10917
  primary: row.primary === true,
10918
+ ...row.redirectToPrimary === true ? { redirectToPrimary: true } : {},
10733
10919
  status: row.status === "verified" ? "verified" : "pending",
10734
10920
  verifiedAt: row.verifiedAt ?? null,
10735
10921
  isApex: row.isApex,
@@ -10826,6 +11012,9 @@ async function domainsCommand(action, rawArgs) {
10826
11012
  case "primary":
10827
11013
  await primaryDomain(rawArgs);
10828
11014
  break;
11015
+ case "redirect":
11016
+ await redirectDomain(rawArgs);
11017
+ break;
10829
11018
  case "remove":
10830
11019
  case "rm":
10831
11020
  case "delete":
@@ -10865,7 +11054,8 @@ async function listDomains(rawArgs) {
10865
11054
  }
10866
11055
  for (const d of set.domains) {
10867
11056
  const status = d.status === "verified" ? chalk.green(d.status) : chalk.yellow(d.status);
10868
- console.log(` ${chalk.bold(d.host)} ${status}${d.primary && set.domains.length > 1 ? chalk.gray(" primary") : ""}`);
11057
+ const role = d.primary && set.domains.length > 1 ? chalk.gray(" primary") : d.redirectToPrimary ? chalk.gray(" redirects to the primary") : "";
11058
+ console.log(` ${chalk.bold(d.host)} ${status}${role}`);
10869
11059
  if (d.verifiedAt) console.log(chalk.gray(` verified ${d.verifiedAt}`));
10870
11060
  if (d.status !== "verified") printRecords(d.instructions);
10871
11061
  }
@@ -11031,6 +11221,68 @@ async function primaryDomain(rawArgs) {
11031
11221
  changed: !unchanged
11032
11222
  });
11033
11223
  }
11224
+ /**
11225
+ * Answer one host with a permanent redirect (308) to the primary, path and
11226
+ * query kept, instead of serving the project on it — or, with `--off`, serve it
11227
+ * again.
11228
+ *
11229
+ * Per host and off by default, because a project may serve distinct hosts on
11230
+ * purpose (an `api.` host beside the site). What it is for is the other case:
11231
+ * `www.example.com` and `example.com` serving one site are two origins to a
11232
+ * browser, and whatever is keyed on the origin — Google sign-in's authorised
11233
+ * origins first — works on one and fails on the other.
11234
+ */
11235
+ async function redirectDomain(rawArgs) {
11236
+ const { flags, positionals } = parseCloudArgs({
11237
+ spec: { "--off": Boolean },
11238
+ rawArgs,
11239
+ commandWords: 3,
11240
+ command: "cloud domains redirect",
11241
+ maxPositionals: 1
11242
+ });
11243
+ const named = positionals[0];
11244
+ const on = flags["--off"] !== true;
11245
+ if (!named) fail("Usage: rebase cloud domains redirect <domain> [--off]", "Name the host to send to the primary, e.g. `rebase cloud domains redirect www.example.com`.", "usage");
11246
+ const { client } = await requireClient(rawArgs);
11247
+ const projectId = await requireProject(rawArgs, client);
11248
+ const projectRef = displayProjectRef(rawArgs);
11249
+ let set;
11250
+ try {
11251
+ set = await loadDomains(client, projectId);
11252
+ } catch (e) {
11253
+ reportError(e, "Failed to load custom domains");
11254
+ }
11255
+ if (set.model === "column") fail("This control plane serves one custom domain per project, so there is no other host to redirect.", "`rebase cloud domains list` shows the one it serves.", "not_served");
11256
+ const target = pickDomain(set, named, "redirect");
11257
+ if (target.id === null) fail(`${target.host} is held outside this project's host list, so it cannot redirect.`, `Add it to the list first: \`rebase cloud domains add ${target.host}\`, then \`rebase cloud domains verify ${target.host}\`.`, "usage");
11258
+ if (on && target.primary) {
11259
+ const other = set.domains.find((d) => !d.primary && d.status === "verified");
11260
+ fail(`${target.host} is the primary host: the other hosts redirect to it.`, other ? `Make another host primary first: \`rebase cloud domains primary ${other.host}\`.` : "Add and verify the host it should redirect to, and make that one primary.", "domain_is_primary");
11261
+ }
11262
+ let res;
11263
+ try {
11264
+ res = await client.functions.invoke("domains", { redirect: on }, { path: `${projectId}/${target.id}/redirect` });
11265
+ } catch (e) {
11266
+ reportError(e, on ? "Failed to redirect the domain" : "Failed to stop the redirect");
11267
+ }
11268
+ const redirectsTo = res.redirectsTo ?? null;
11269
+ emit(() => {
11270
+ if (!on) success(`${target.host} is served by project ${projectRef} again`);
11271
+ else if (redirectsTo) success(`${target.host} now redirects to https://${redirectsTo} (308, path and query kept)`);
11272
+ else {
11273
+ success(`${target.host} will redirect to the primary host`);
11274
+ if (res.notInEffect) console.log(chalk.yellow(` Not in effect yet: ${res.notInEffect}`));
11275
+ }
11276
+ }, {
11277
+ success: true,
11278
+ projectId,
11279
+ id: target.id,
11280
+ host: target.host,
11281
+ redirectToPrimary: on,
11282
+ redirectsTo,
11283
+ ...res.notInEffect ? { notInEffect: res.notInEffect } : {}
11284
+ });
11285
+ }
11034
11286
  async function removeDomain(rawArgs) {
11035
11287
  const { flags: args, positionals } = parseCloudArgs({
11036
11288
  spec: {},
@@ -11094,6 +11346,11 @@ function printDomainsHelp() {
11094
11346
  args: "<domain>",
11095
11347
  description: "Make a verified host the canonical one, the address links are built from"
11096
11348
  },
11349
+ {
11350
+ action: "redirect",
11351
+ args: "<domain> [--off]",
11352
+ description: "Answer a host with a 308 to the primary instead of serving it"
11353
+ },
11097
11354
  {
11098
11355
  action: "remove",
11099
11356
  args: "<domain>",
@@ -11101,7 +11358,7 @@ function printDomainsHelp() {
11101
11358
  }
11102
11359
  ],
11103
11360
  notes: [
11104
- "A project can be served on several hosts; each is verified on its own.",
11361
+ "A project can be served on several hosts; each is verified on its own, and each serves the project unless it redirects.",
11105
11362
  "A CNAME is invalid at a zone apex: use an A record there and a CNAME below it.",
11106
11363
  "`list` prints the exact records to add — copy them rather than deriving them."
11107
11364
  ]
@@ -12532,92 +12789,6 @@ async function appKeyCommand(rawArgs) {
12532
12789
  });
12533
12790
  }
12534
12791
  //#endregion
12535
- //#region src/commands/cloud/service-key.ts
12536
- /**
12537
- * `rebase cloud service-key [rotate]`: the project's `REBASE_SERVICE_KEY`,
12538
- * admin on the app's own API, and replacing it.
12539
- *
12540
- * The control plane derives the key from the project and a generation, and
12541
- * injects it into the app. `rotate` issues the next generation and restarts
12542
- * the app onto it in the background; the old key keeps working until that
12543
- * restart has come up, and nothing after. Anything that copied the old key —
12544
- * a script, a CI job, an agent's deployed code that printed it — is refused
12545
- * from then on. A claim rotates it too.
12546
- *
12547
- * Without an action, prints the generation, when it was last rotated and
12548
- * whether a rotation is still restarting the app. The key itself is
12549
- * `rebase cloud env reveal REBASE_SERVICE_KEY`. Calls `GET` and `POST
12550
- * /credentials/:projectId/service-key[/rotate]`, owners and admins, signed in.
12551
- *
12552
- * @module
12553
- */
12554
- /** What `service-key` says on a control plane that has no `credentials` function yet. */
12555
- var SERVICE_KEY_UNSERVED = {
12556
- what: "service-key rotation",
12557
- hint: "Nothing was changed. `rebase cloud env reveal REBASE_SERVICE_KEY` still reads the current key."
12558
- };
12559
- var SERVICE_KEY_FLAGS = {};
12560
- var SERVICE_KEY_ACTIONS = ["rotate"];
12561
- async function readStatus(client, projectId) {
12562
- return client.functions.invoke("credentials", void 0, {
12563
- method: "GET",
12564
- path: `${encodeURIComponent(projectId)}/service-key`
12565
- });
12566
- }
12567
- function printStatus(status, label) {
12568
- console.log("");
12569
- console.log(chalk.bold(` 🛡 Service key — ${label}`));
12570
- console.log("");
12571
- console.log(` Generation ${status.generation}`);
12572
- console.log(` Rotated ${status.rotatedAt ? new Date(status.rotatedAt).toLocaleString() : chalk.gray("never")}`);
12573
- if (status.pending) {
12574
- console.log("");
12575
- console.log(chalk.yellow(" The app has not restarted onto the newest key yet; the previous one still works until it has."));
12576
- }
12577
- console.log("");
12578
- console.log(chalk.gray(` Read it with ${chalk.bold("rebase cloud env reveal REBASE_SERVICE_KEY")}; replace it with ${chalk.bold("rebase cloud service-key rotate")}.`));
12579
- console.log("");
12580
- }
12581
- async function serviceKeyCommand(rawArgs) {
12582
- const parsed = parseCloudArgs({
12583
- spec: SERVICE_KEY_FLAGS,
12584
- rawArgs,
12585
- commandWords: 2,
12586
- command: "cloud service-key",
12587
- maxPositionals: 1
12588
- });
12589
- const action = parsed.positionals[0];
12590
- requireKnownAction("service-key", action, SERVICE_KEY_ACTIONS);
12591
- const { client } = await requireSessionClient(rawArgs, "rotate a project's service key");
12592
- const projectId = await requireProject(rawArgs, client);
12593
- const label = `project ${displayProjectRef(rawArgs) || projectId}`;
12594
- if (action !== "rotate") {
12595
- let status;
12596
- try {
12597
- status = await readStatus(client, projectId);
12598
- } catch (e) {
12599
- reportCallError(e, "Failed to read the service key's state", SERVICE_KEY_UNSERVED);
12600
- }
12601
- emit(() => printStatus(status, label), status);
12602
- return;
12603
- }
12604
- await confirmDestructive({
12605
- yes: Boolean(parsed.flags["--yes"]),
12606
- prompt: `Rotate the service key of ${label}? The app restarts onto a new key, and anything using the old one is refused once it has.`
12607
- });
12608
- let rotation;
12609
- try {
12610
- rotation = await client.functions.invoke("credentials", {}, { path: `${encodeURIComponent(projectId)}/service-key/rotate` });
12611
- } catch (e) {
12612
- reportCallError(e, "Failed to rotate the service key", SERVICE_KEY_UNSERVED);
12613
- }
12614
- emit(() => {
12615
- success(`Issued service key generation ${rotation.generation} for ${label}.`);
12616
- note(rotation.state === "pending" ? "A deploy is running: the next deploy carries the new key. The old one works until then." : "The app is restarting onto it; the old key works until the restart has finished. Follow it with `rebase cloud service-key`.");
12617
- note("Read the new key with `rebase cloud env reveal REBASE_SERVICE_KEY` once the restart is done.");
12618
- }, rotation);
12619
- }
12620
- //#endregion
12621
12792
  //#region src/commands/cloud/guests.ts
12622
12793
  /**
12623
12794
  * `rebase cloud guests [delete <id> | prune --older-than <age>]`: the guest
@@ -13948,11 +14119,27 @@ var ACTION_HELP = {
13948
14119
  "domains primary": {
13949
14120
  command: "cloud domains primary",
13950
14121
  usage: "cloud domains primary <domain>",
13951
- summary: "Make one of the project's verified domains its canonical host: the address links and redirects are built from. The project keeps serving its other domains.",
14122
+ summary: "Make one of the project's verified domains its canonical host: the address links are built from, and the one `domains redirect` sends the others to. The project keeps serving its other domains as themselves unless each is told to redirect.",
13952
14123
  flags: [],
13953
14124
  examples: ["rebase cloud domains primary app.example.com"],
13954
14125
  notes: ["Only a verified domain can be primary: run `domains verify <domain>` first.", "Refused with not_served by a control plane that keeps a single domain per project."]
13955
14126
  },
14127
+ "domains redirect": {
14128
+ command: "cloud domains redirect",
14129
+ usage: "cloud domains redirect <domain> [--off]",
14130
+ summary: "Answer one of the project's domains with a permanent redirect (308) to the primary domain, keeping the path and the query, instead of serving the project on it. Use it for `www.` beside an apex: two hosts serving one site are two origins, and Google sign-in, cookies and passkeys each work on one and fail on the other.",
14131
+ flags: [["--off", "Serve the domain again instead of redirecting it"]],
14132
+ examples: [
14133
+ "rebase cloud domains primary example.com",
14134
+ "rebase cloud domains redirect www.example.com",
14135
+ "rebase cloud domains redirect www.example.com --off"
14136
+ ],
14137
+ notes: [
14138
+ "Off by default, per domain: a project serving an `api.` host beside its site keeps both.",
14139
+ "In effect while the domain is verified and another domain is primary; until then it is stored and says so.",
14140
+ "Never applies to the primary itself, to the project's <slug>.rebase.website host, or to a domain an app is served on (an app `path` with a hostname in rebase.json)."
14141
+ ]
14142
+ },
13956
14143
  "domains remove": {
13957
14144
  command: "cloud domains remove",
13958
14145
  usage: "cloud domains remove <domain>",
@@ -14120,18 +14307,21 @@ var ACTION_HELP = {
14120
14307
  },
14121
14308
  "service-key": {
14122
14309
  command: "cloud service-key",
14123
- usage: "cloud service-key [rotate]",
14124
- summary: "The project's REBASE_SERVICE_KEY, admin on the app's own API. Without an action, prints its generation, when it was last rotated and whether the app is still restarting onto the newest one (never the key: that is `rebase cloud env reveal REBASE_SERVICE_KEY`). `rotate` issues a new key and restarts the app onto it; the old key works until the restart has finished and nothing after. Refused while a deploy is running. Owners and admins, signed in.",
14125
- flags: [],
14310
+ usage: "cloud service-key [rotate] [--preview <name>]",
14311
+ summary: "The project's REBASE_SERVICE_KEY, admin on the app's own API. Without an action, prints its generation, when it was last rotated and whether the app is still restarting onto the newest one (never the key: that is `rebase cloud env reveal REBASE_SERVICE_KEY`). `rotate` issues a new key and restarts the app onto it; the old key works until the restart has finished and nothing after. Refused while a deploy is running. Owners and admins, signed in. With `--preview <name>`, the same for one backend preview's own key: without an action it prints that key, and `rotate` restarts only the preview's pod.",
14312
+ flags: [["--preview <name>", "A backend preview's own key instead of production's: printed, or with `rotate` replaced"]],
14126
14313
  examples: [
14127
14314
  "rebase cloud service-key",
14128
14315
  "rebase cloud service-key rotate",
14129
- "rebase cloud service-key rotate --yes --json"
14316
+ "rebase cloud service-key rotate --yes --json",
14317
+ "rebase cloud service-key --preview new-quiz",
14318
+ "rebase cloud service-key rotate --preview new-quiz --yes"
14130
14319
  ],
14131
14320
  notes: [
14132
14321
  "Anything that copied the old key (a script, a CI job) is refused once the restart has finished.",
14133
14322
  "Claiming a project rotates its service key too.",
14134
- "It runs with your login: no access-token capability grants it, so REBASE_TOKEN is refused."
14323
+ "It runs with your login: no access-token capability grants it, so REBASE_TOKEN is refused.",
14324
+ "A backend preview's key is its own: minted at its first deploy, kept across redeploys, and production's key answers 401 there. `--preview` asks what `env reveal` asks — the owner or admin role, and a token with the env capability on a claimed project — and never touches production's key or pod."
14135
14325
  ]
14136
14326
  },
14137
14327
  guests: {
@@ -15217,8 +15407,8 @@ var CLOUD_GROUPS = [
15217
15407
  {
15218
15408
  action: "service-key",
15219
15409
  section: "Config",
15220
- args: "[rotate]",
15221
- description: "REBASE_SERVICE_KEY, admin on the app's API: its state, and replacing it. Owners and admins"
15410
+ args: "[rotate] [--preview <name>]",
15411
+ description: "REBASE_SERVICE_KEY, admin on the app's API: its state, and replacing it; a backend preview's own with --preview. Owners and admins"
15222
15412
  },
15223
15413
  {
15224
15414
  action: "orgs",
@@ -15301,4 +15491,4 @@ function printCloudHelp() {
15301
15491
  //#endregion
15302
15492
  export { CLOUD_GROUP_NAMES, GROUP_ALIASES, cloudCommand };
15303
15493
 
15304
- //# sourceMappingURL=cloud-MqnyPnmX.js.map
15494
+ //# sourceMappingURL=cloud-DNJyUU0T.js.map