@rebasepro/server 0.31.0-canary.g902a0ce → 0.32.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 (123) hide show
  1. package/dist/{GCSStorageController-sCw2c4aA.js → GCSStorageController-B3p3aUX-.js} +5 -5
  2. package/dist/{GCSStorageController-sCw2c4aA.js.map → GCSStorageController-B3p3aUX-.js.map} +1 -1
  3. package/dist/{S3StorageController-DDAq8Kt5.js → S3StorageController-C9LjuMhL.js} +5 -5
  4. package/dist/{S3StorageController-DDAq8Kt5.js.map → S3StorageController-C9LjuMhL.js.map} +1 -1
  5. package/dist/{access-CSfmyM87.js → access-BxkEYQh1.js} +6 -6
  6. package/dist/{access-CSfmyM87.js.map → access-BxkEYQh1.js.map} +1 -1
  7. package/dist/{access-CCsVee6z.js → access-D1CTJSLK.js} +3 -1
  8. package/dist/access-D1CTJSLK.js.map +1 -0
  9. package/dist/api/errors.d.ts +4 -0
  10. package/dist/api/rest/api-generator.d.ts +8 -0
  11. package/dist/{auth-Blo1R8rc.js → auth-Bfwjg4Bg.js} +37 -13
  12. package/dist/auth-Bfwjg4Bg.js.map +1 -0
  13. package/dist/auth-secrets-BZUH9916.js +60 -0
  14. package/dist/auth-secrets-BZUH9916.js.map +1 -0
  15. package/dist/backend/create-backend.d.ts +6 -0
  16. package/dist/backend/options.d.ts +10 -0
  17. package/dist/backend/services.d.ts +9 -0
  18. package/dist/{backup-B-1oW6qX.js → backup-g2ohsDe0.js} +7 -7
  19. package/dist/{backup-B-1oW6qX.js.map → backup-g2ohsDe0.js.map} +1 -1
  20. package/dist/boot/bundle.d.ts +11 -1
  21. package/dist/boot/env.d.ts +5 -0
  22. package/dist/boot/security-headers.d.ts +15 -5
  23. package/dist/boot/static-routing.d.ts +58 -0
  24. package/dist/{branch-routes-0xhHXlGq.js → branch-routes-DtNtc0Vh.js} +3 -3
  25. package/dist/{branch-routes-0xhHXlGq.js.map → branch-routes-DtNtc0Vh.js.map} +1 -1
  26. package/dist/{contract-routes-WwMWHWS9.js → contract-routes-CZTlAP7p.js} +3 -3
  27. package/dist/{contract-routes-WwMWHWS9.js.map → contract-routes-CZTlAP7p.js.map} +1 -1
  28. package/dist/{cron-loader-BDN8plQK.js → cron-loader-BBP0kBIl.js} +2 -2
  29. package/dist/{cron-loader-BDN8plQK.js.map → cron-loader-BBP0kBIl.js.map} +1 -1
  30. package/dist/{cron-routes-Cqm5wQsK.js → cron-routes-Du03uJ7K.js} +5 -5
  31. package/dist/{cron-routes-Cqm5wQsK.js.map → cron-routes-Du03uJ7K.js.map} +1 -1
  32. package/dist/{cron-scheduler-DgrsqyQQ.js → cron-scheduler-CopTWKYB.js} +2 -2
  33. package/dist/{cron-scheduler-DgrsqyQQ.js.map → cron-scheduler-CopTWKYB.js.map} +1 -1
  34. package/dist/{cron-store-91cd9Qzv.js → cron-store-FGaZOdMf.js} +3 -3
  35. package/dist/{cron-store-91cd9Qzv.js.map → cron-store-FGaZOdMf.js.map} +1 -1
  36. package/dist/dist-C1vNURUy.js +19354 -0
  37. package/dist/dist-C1vNURUy.js.map +1 -0
  38. package/dist/{errors-DpTMfX77.js → errors-NVbAQU25.js} +5 -1
  39. package/dist/errors-NVbAQU25.js.map +1 -0
  40. package/dist/{filter-dialect-DAVl1Nsm.js → filter-dialect-XtPJOCbD.js} +2 -2
  41. package/dist/{filter-dialect-DAVl1Nsm.js.map → filter-dialect-XtPJOCbD.js.map} +1 -1
  42. package/dist/{function-loader-BeFbN1-A.js → function-loader-D3YEHF6E.js} +2 -2
  43. package/dist/{function-loader-BeFbN1-A.js.map → function-loader-D3YEHF6E.js.map} +1 -1
  44. package/dist/{function-routes-CIwLXsZF.js → function-routes-DNDFIa7t.js} +3 -3
  45. package/dist/{function-routes-CIwLXsZF.js.map → function-routes-DNDFIa7t.js.map} +1 -1
  46. package/dist/functions/index.d.ts +2 -0
  47. package/dist/functions/index.js +162 -1
  48. package/dist/functions/index.js.map +1 -1
  49. package/dist/functions/rate-limit.d.ts +71 -0
  50. package/dist/{history-recorder-CNeqtTaR.js → history-recorder-C5RkbKS2.js} +3 -3
  51. package/dist/{history-recorder-CNeqtTaR.js.map → history-recorder-C5RkbKS2.js.map} +1 -1
  52. package/dist/{history-store-DseUt_dm.js → history-store-DzrJeEKv.js} +2 -2
  53. package/dist/{history-store-DseUt_dm.js.map → history-store-DzrJeEKv.js.map} +1 -1
  54. package/dist/index.d.ts +6 -0
  55. package/dist/index.es.js +1242 -214
  56. package/dist/index.es.js.map +1 -1
  57. package/dist/{internal-tables-CHFJHH7N.js → internal-tables-XxM_NdR_.js} +2 -2
  58. package/dist/{internal-tables-CHFJHH7N.js.map → internal-tables-XxM_NdR_.js.map} +1 -1
  59. package/dist/{jobs-WCyKVsUf.js → jobs-CFUwQTao.js} +3 -3
  60. package/dist/{jobs-WCyKVsUf.js.map → jobs-CFUwQTao.js.map} +1 -1
  61. package/dist/{jwt-JtQiewBW.js → jwt-CqhXs8Iz.js} +3 -3
  62. package/dist/{jwt-JtQiewBW.js.map → jwt-CqhXs8Iz.js.map} +1 -1
  63. package/dist/{keys-BTPoSvUs.js → keys-Btt6ZNqF.js} +2 -2
  64. package/dist/{keys-BTPoSvUs.js.map → keys-Btt6ZNqF.js.map} +1 -1
  65. package/dist/{load-schema-CtyLeq-H.js → load-schema-B4Nv1mwq.js} +33 -40
  66. package/dist/load-schema-B4Nv1mwq.js.map +1 -0
  67. package/dist/{logs-routes-BT4af1Or.js → logs-routes-C3CLYP-n.js} +3 -3
  68. package/dist/{logs-routes-BT4af1Or.js.map → logs-routes-C3CLYP-n.js.map} +1 -1
  69. package/dist/{offline-D_wKJcO3-RV6C9HnX.js → offline-ET6xI1ZO-BQpLQ7wh.js} +124 -7
  70. package/dist/offline-ET6xI1ZO-BQpLQ7wh.js.map +1 -0
  71. package/dist/{offline-store-DtmBwmKE-B17N4609.js → offline-store-DtmBwmKE-C9ba2NJv.js} +3 -3
  72. package/dist/{offline-store-DtmBwmKE-B17N4609.js.map → offline-store-DtmBwmKE-C9ba2NJv.js.map} +1 -1
  73. package/dist/{openapi-generator-mn6hsEmw.js → openapi-generator-CAhJiwBm.js} +4 -4
  74. package/dist/{openapi-generator-mn6hsEmw.js.map → openapi-generator-CAhJiwBm.js.map} +1 -1
  75. package/dist/{project-root-qDQzmsUD.js → project-root-CIrVZi-r.js} +2 -2
  76. package/dist/{project-root-qDQzmsUD.js.map → project-root-CIrVZi-r.js.map} +1 -1
  77. package/dist/{proxy-D18_bcQI.js → proxy-clweqa43.js} +3 -3
  78. package/dist/{proxy-D18_bcQI.js.map → proxy-clweqa43.js.map} +1 -1
  79. package/dist/push/push-options.d.ts +26 -0
  80. package/dist/push/push-routes.d.ts +30 -0
  81. package/dist/push/push-service.d.ts +13 -0
  82. package/dist/push/push-store.d.ts +45 -0
  83. package/dist/push/set-up.d.ts +25 -0
  84. package/dist/push/subscription-input.d.ts +26 -0
  85. package/dist/push/vapid-config.d.ts +35 -0
  86. package/dist/push/web-push-crypto.d.ts +44 -0
  87. package/dist/push/web-push-sender.d.ts +10 -0
  88. package/dist/{query-parser-CkKSbs1s.js → query-parser-Cd70kZO8.js} +6 -6
  89. package/dist/{query-parser-CkKSbs1s.js.map → query-parser-Cd70kZO8.js.map} +1 -1
  90. package/dist/{request-timeout-CpOgfQPK.js → request-timeout-cC3HT1Pf.js} +3 -3
  91. package/dist/{request-timeout-CpOgfQPK.js.map → request-timeout-cC3HT1Pf.js.map} +1 -1
  92. package/dist/{rls-simulator-routes-BxzeNXmI.js → rls-simulator-routes-DI2sYaQt.js} +4 -4
  93. package/dist/{rls-simulator-routes-BxzeNXmI.js.map → rls-simulator-routes-DI2sYaQt.js.map} +1 -1
  94. package/dist/{schema-editor-routes-mPCyks4X.js → schema-editor-routes-DEGwyQmx.js} +5 -5
  95. package/dist/{schema-editor-routes-mPCyks4X.js.map → schema-editor-routes-DEGwyQmx.js.map} +1 -1
  96. package/dist/{schema-tables-D4MEBZFi.js → schema-tables-DKFg6vMV.js} +4 -4
  97. package/dist/{schema-tables-D4MEBZFi.js.map → schema-tables-DKFg6vMV.js.map} +1 -1
  98. package/dist/{schema-tables-routes-D3iLb5XU.js → schema-tables-routes-BfsNG4c4.js} +5 -5
  99. package/dist/{schema-tables-routes-D3iLb5XU.js.map → schema-tables-routes-BfsNG4c4.js.map} +1 -1
  100. package/dist/{securityRuleToConditions-DD40f3ml.js → securityRuleToConditions-Bk5zRSoa.js} +2 -2
  101. package/dist/{securityRuleToConditions-DD40f3ml.js.map → securityRuleToConditions-Bk5zRSoa.js.map} +1 -1
  102. package/dist/{selection-hgC1szl6.js → selection-BOnbJvXD.js} +2 -2
  103. package/dist/{selection-hgC1szl6.js.map → selection-BOnbJvXD.js.map} +1 -1
  104. package/dist/serve-spa.d.ts +12 -0
  105. package/dist/{soft-delete-params-DDRmxT2z.js → soft-delete-params-Dhn0qKFv.js} +2 -2
  106. package/dist/{soft-delete-params-DDRmxT2z.js.map → soft-delete-params-Dhn0qKFv.js.map} +1 -1
  107. package/dist/{sql-export-routes-BKmQZ3xh.js → sql-export-routes-B3oqb1Jw.js} +3 -3
  108. package/dist/{sql-export-routes-BKmQZ3xh.js.map → sql-export-routes-B3oqb1Jw.js.map} +1 -1
  109. package/dist/{src-DLIb1O9l.js → src-CNZB3fuE.js} +192 -3
  110. package/dist/src-CNZB3fuE.js.map +1 -0
  111. package/dist/{table-source-editor-xvccIOH1.js → table-source-editor-D_zNDhEU.js} +3 -3
  112. package/dist/{table-source-editor-xvccIOH1.js.map → table-source-editor-D_zNDhEU.js.map} +1 -1
  113. package/dist/{upload-validation-B-psYLaN.js → upload-validation-BnIwo78L.js} +2 -2
  114. package/dist/{upload-validation-B-psYLaN.js.map → upload-validation-BnIwo78L.js.map} +1 -1
  115. package/package.json +5 -5
  116. package/dist/access-CCsVee6z.js.map +0 -1
  117. package/dist/auth-Blo1R8rc.js.map +0 -1
  118. package/dist/dist-CDIqWaSr.js +0 -19354
  119. package/dist/dist-CDIqWaSr.js.map +0 -1
  120. package/dist/errors-DpTMfX77.js.map +0 -1
  121. package/dist/load-schema-CtyLeq-H.js.map +0 -1
  122. package/dist/offline-D_wKJcO3-RV6C9HnX.js.map +0 -1
  123. package/dist/src-DLIb1O9l.js.map +0 -1
@@ -0,0 +1,60 @@
1
+ import { createRequire as __rebaseCreateRequire } from "module";
2
+ import __rebaseProcess from "process";
3
+ globalThis.process ??= __rebaseProcess;
4
+ __rebaseCreateRequire(import.meta.url);
5
+ //#region ../common/src/collections/auth-secrets.ts
6
+ /** Is this collection the one the auth subsystem stores users in? */
7
+ function isAuthCollection(collection) {
8
+ const auth = collection.auth;
9
+ if (auth === true) return true;
10
+ return typeof auth === "object" && auth !== null && "enabled" in auth && auth.enabled === true;
11
+ }
12
+ /**
13
+ * The secrets of the built-in user store, in both spellings: the key and the
14
+ * column. A redeclaration is free to rename the key — one project's copy says
15
+ * `password_hash` where the default says `passwordHash` — and the column is the
16
+ * same either way. The auth adapter writes these columns
17
+ * (`builtin-auth-adapter`), and no caller may read or set them — an admin
18
+ * included: nobody has a use for a hash.
19
+ *
20
+ * The class, not a list of the columns someone noticed: every credential or
21
+ * token auth keeps on the user row, and every hash of one. The password hash;
22
+ * the email-verification token; the hash of a pending email-change link. A
23
+ * bookkeeping stamp beside them (`tokens_valid_after`, `email_change_sent_at`,
24
+ * `pending_email`) is not a secret and is served like any column. The other
25
+ * credentials auth keeps — refresh, reset and magic-link tokens, MFA secrets,
26
+ * recovery codes, provider identities — live in its own side tables, which no
27
+ * door serves.
28
+ *
29
+ * A name here is withheld whether or not the table declares the column: the
30
+ * runtime reads every physical column, and auth creates these on any auth
31
+ * table (`ensureAuthTablesExist`), so a table that never mentions
32
+ * `email_change_token` still has one. See `restrictedKeys` / `apiHiddenKeys`.
33
+ */
34
+ var AUTH_SECRET_NAMES = /* @__PURE__ */ new Set([
35
+ "passwordHash",
36
+ "password_hash",
37
+ "emailVerificationToken",
38
+ "email_verification_token",
39
+ "emailChangeToken",
40
+ "email_change_token"
41
+ ]);
42
+ /**
43
+ * The keys of the properties on `collection` that hold an auth secret and do not
44
+ * carry `excludeFromApi`. Empty for any collection that is not the user store: a
45
+ * `password_hash` column elsewhere — a CRM importing hashes, say — is that
46
+ * project's data, not this rule's business.
47
+ */
48
+ function authSecretsMissingExclusion(collection) {
49
+ if (!collection.properties || !isAuthCollection(collection)) return [];
50
+ const missing = [];
51
+ for (const [key, property] of Object.entries(collection.properties)) {
52
+ if (!property || property.excludeFromApi) continue;
53
+ if (AUTH_SECRET_NAMES.has(key) || AUTH_SECRET_NAMES.has(property.columnName ?? key)) missing.push(key);
54
+ }
55
+ return missing;
56
+ }
57
+ //#endregion
58
+ export { authSecretsMissingExclusion as n, AUTH_SECRET_NAMES as t };
59
+
60
+ //# sourceMappingURL=auth-secrets-BZUH9916.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth-secrets-BZUH9916.js","names":[],"sources":["../../common/src/collections/auth-secrets.ts"],"sourcesContent":["/**\n * Which columns of the user store are the server's alone, and which properties\n * of a given auth collection hold one without saying so.\n *\n * `users` is the one collection a project is expected to redeclare: it is\n * scaffolded into `config/collections/users.ts` so the panel can present it, and\n * the declaration replaces the default outright rather than merging with it. The\n * flag that goes missing unnoticed in that copy is `excludeFromApi` — the\n * neighbouring `admin.hideFromCollection` and `admin.disabled.hidden` keep the\n * field off the screen and look like they did the job.\n *\n * The rule has two readers and they must agree. The server restores the flag so\n * a read does not serve the scrypt hash and a write cannot set it. The panel\n * needs it just as much: a form opens with a value for every property that is\n * not excluded, and submits that baseline, so a panel that does not know sends\n * `passwordHash: null` with every new user and the server refuses the create.\n */\n\n/**\n * What the rule reads off a collection. A `CollectionConfig` is one; so is a\n * collection a server has loaded and not yet validated.\n */\nexport interface AuthSecretCandidate {\n auth?: unknown;\n properties?: Record<string, { excludeFromApi?: boolean; columnName?: string } | undefined>;\n}\n\n/** Is this collection the one the auth subsystem stores users in? */\nfunction isAuthCollection(collection: AuthSecretCandidate): boolean {\n const auth = collection.auth;\n if (auth === true) return true;\n return typeof auth === \"object\" && auth !== null && \"enabled\" in auth && auth.enabled === true;\n}\n\n/**\n * The secrets of the built-in user store, in both spellings: the key and the\n * column. A redeclaration is free to rename the key — one project's copy says\n * `password_hash` where the default says `passwordHash` — and the column is the\n * same either way. The auth adapter writes these columns\n * (`builtin-auth-adapter`), and no caller may read or set them — an admin\n * included: nobody has a use for a hash.\n *\n * The class, not a list of the columns someone noticed: every credential or\n * token auth keeps on the user row, and every hash of one. The password hash;\n * the email-verification token; the hash of a pending email-change link. A\n * bookkeeping stamp beside them (`tokens_valid_after`, `email_change_sent_at`,\n * `pending_email`) is not a secret and is served like any column. The other\n * credentials auth keeps — refresh, reset and magic-link tokens, MFA secrets,\n * recovery codes, provider identities — live in its own side tables, which no\n * door serves.\n *\n * A name here is withheld whether or not the table declares the column: the\n * runtime reads every physical column, and auth creates these on any auth\n * table (`ensureAuthTablesExist`), so a table that never mentions\n * `email_change_token` still has one. See `restrictedKeys` / `apiHiddenKeys`.\n */\nexport const AUTH_SECRET_NAMES: ReadonlySet<string> = new Set([\n \"passwordHash\", \"password_hash\",\n \"emailVerificationToken\", \"email_verification_token\",\n \"emailChangeToken\", \"email_change_token\"\n]);\n\n/**\n * The keys of the properties on `collection` that hold an auth secret and do not\n * carry `excludeFromApi`. Empty for any collection that is not the user store: a\n * `password_hash` column elsewhere — a CRM importing hashes, say — is that\n * project's data, not this rule's business.\n */\nexport function authSecretsMissingExclusion(collection: AuthSecretCandidate): string[] {\n if (!collection.properties || !isAuthCollection(collection)) return [];\n\n const missing: string[] = [];\n for (const [key, property] of Object.entries(collection.properties)) {\n if (!property || property.excludeFromApi) continue;\n if (AUTH_SECRET_NAMES.has(key) || AUTH_SECRET_NAMES.has(property.columnName ?? key)) missing.push(key);\n }\n return missing;\n}\n"],"mappings":";;;;;;AA4BA,SAAS,iBAAiB,YAA0C;CAChE,MAAM,OAAO,WAAW;CACxB,IAAI,SAAS,MAAM,OAAO;CAC1B,OAAO,OAAO,SAAS,YAAY,SAAS,QAAQ,aAAa,QAAQ,KAAK,YAAY;AAC9F;;;;;;;;;;;;;;;;;;;;;;;AAwBA,IAAa,oCAAyC,IAAI,IAAI;CAC1D;CAAgB;CAChB;CAA0B;CAC1B;CAAoB;AACxB,CAAC;;;;;;;AAQD,SAAgB,4BAA4B,YAA2C;CACnF,IAAI,CAAC,WAAW,cAAc,CAAC,iBAAiB,UAAU,GAAG,OAAO,CAAC;CAErE,MAAM,UAAoB,CAAC;CAC3B,KAAK,MAAM,CAAC,KAAK,aAAa,OAAO,QAAQ,WAAW,UAAU,GAAG;EACjE,IAAI,CAAC,YAAY,SAAS,gBAAgB;EAC1C,IAAI,kBAAkB,IAAI,GAAG,KAAK,kBAAkB,IAAI,SAAS,cAAc,GAAG,GAAG,QAAQ,KAAK,GAAG;CACzG;CACA,OAAO;AACX"}
@@ -95,6 +95,12 @@ export interface RebaseRoutes {
95
95
  * Studio and MCP views render tables from.
96
96
  */
97
97
  schema(): Hono<HonoEnv>;
98
+ /**
99
+ * Web Push subscriptions, normally at `/api/push`: the VAPID key and a
100
+ * signed-in browser's subscribe and unsubscribe. Throws when the backend
101
+ * was created without `push`.
102
+ */
103
+ push(): Hono<HonoEnv>;
98
104
  }
99
105
  /** Where {@link RebaseBackend.mount} puts the backend. */
100
106
  export interface BackendMountOptions {
@@ -929,6 +929,16 @@ export interface RebaseBackendOptions {
929
929
  * ```
930
930
  */
931
931
  jobs?: JobQueueOptions;
932
+ /**
933
+ * Web Push notifications to browsers. Off by default.
934
+ *
935
+ * `true` mounts `/push/key` and `/push/subscriptions` (signed-in callers
936
+ * only), creates `rebase.push_subscriptions`, and makes `rebase.push` send.
937
+ * The VAPID keys come from `REBASE_VAPID_PUBLIC_KEY`,
938
+ * `REBASE_VAPID_PRIVATE_KEY` and `REBASE_VAPID_SUBJECT`; outside
939
+ * production a pair is generated and kept when they are unset.
940
+ */
941
+ push?: boolean | import("../push/push-options.js").PushOptions;
932
942
  /**
933
943
  * Maximum request body size in bytes for API routes (default: 10MB).
934
944
  * Set to 0 to disable the global limit entirely.
@@ -24,6 +24,8 @@ import type { AccessControl } from "../auth/access.js";
24
24
  import type { AuthLimiters } from "../auth/rate-limiter.js";
25
25
  import type { RateLimitStore } from "../auth/rate-limit-store.js";
26
26
  import type { ApiKeyStore } from "../auth/api-keys/api-key-store.js";
27
+ import type { Context } from "hono";
28
+ import type { HonoEnv } from "../api/types.js";
27
29
  export interface BackendServices {
28
30
  /**
29
31
  * Signs and verifies this backend's tokens: sessions, download links, MFA
@@ -40,6 +42,13 @@ export interface BackendServices {
40
42
  * SQL, or `rateLimit.store` — when it has one.
41
43
  */
42
44
  rateLimitStore?: RateLimitStore;
45
+ /**
46
+ * Where a request comes from, by this deployment's proxy rule
47
+ * (`TRUSTED_PROXY_HOPS`): the address the auth limiters count by. Here so
48
+ * a function's `rateLimit` keys by the same address without importing the
49
+ * Node-only code that reads the socket.
50
+ */
51
+ clientAddress?: (c: Context<HonoEnv>) => string;
43
52
  /** Where this backend keeps its API keys (`rk_`), when it keeps any. */
44
53
  apiKeyStore?: ApiKeyStore;
45
54
  /**
@@ -2,13 +2,13 @@ import { createRequire as __rebaseCreateRequire } from "module";
2
2
  import __rebaseProcess from "process";
3
3
  globalThis.process ??= __rebaseProcess;
4
4
  __rebaseCreateRequire(import.meta.url);
5
- import { Pn as __exportAll, jt as parseEnvBoolean } from "./src-DLIb1O9l.js";
5
+ import { Ft as parseEnvBoolean, Rn as __exportAll } from "./src-CNZB3fuE.js";
6
6
  import { a as logger } from "./logger-SigQ2oZJ.js";
7
- import { m as jwtOf } from "./jwt-JtQiewBW.js";
8
- import { i as errorHandler, t as ApiError } from "./errors-DpTMfX77.js";
9
- import { t as S3StorageController } from "./S3StorageController-DDAq8Kt5.js";
10
- import { t as GCSStorageController } from "./GCSStorageController-sCw2c4aA.js";
11
- import { r as isAlreadyExecutingSkip } from "./cron-scheduler-DgrsqyQQ.js";
7
+ import { m as jwtOf } from "./jwt-CqhXs8Iz.js";
8
+ import { i as errorHandler, t as ApiError } from "./errors-NVbAQU25.js";
9
+ import { t as S3StorageController } from "./S3StorageController-C9LjuMhL.js";
10
+ import { t as GCSStorageController } from "./GCSStorageController-B3p3aUX-.js";
11
+ import { r as isAlreadyExecutingSkip } from "./cron-scheduler-CopTWKYB.js";
12
12
  import path from "path";
13
13
  import fs from "fs";
14
14
  import { Hono } from "hono";
@@ -581,4 +581,4 @@ var backup_exports = /* @__PURE__ */ __exportAll({
581
581
  //#endregion
582
582
  export { listBackupObjects as a, readBackupBytes as c, backupStorageFromEnv as i, createBackupLinkRoutes as n, parseBackupDestination as o, createBackupRoutes as r, parseBackupTimestamp as s, backup_exports as t };
583
583
 
584
- //# sourceMappingURL=backup-B-1oW6qX.js.map
584
+ //# sourceMappingURL=backup-g2ohsDe0.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"backup-B-1oW6qX.js","names":[],"sources":["../src/backup/backup-common.ts","../src/backup/backup-storage.ts","../src/backup/backup-routes.ts","../src/backup/backup-schedule.ts","../src/backup/index.ts"],"sourcesContent":["/**\n * Storage-generic backup helpers used by the admin backup routes.\n *\n * These live in server (which owns {@link StorageController}) so the\n * admin API can list backups without depending on the Postgres driver —\n * `server` must not import from `server-postgres`. The `pg_dump`-side\n * copies of the tiny pure parsers live in `@rebasepro/server-postgres`;\n * keep the two in sync if the naming scheme ever changes.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport type { BackupInfo, BackupDestinationKind } from \"@rebasepro/types\";\nimport type { StorageController } from \"../storage\";\nimport { logger } from \"../utils/logger\";\n\nexport type BackupDestination =\n | { kind: \"local\"; path: string }\n | { kind: \"s3\"; bucket: string; prefix: string }\n | { kind: \"gcs\"; bucket: string; prefix: string };\n\n/** Parse a destination string (`s3://…`, `gs://…`, or a local path). */\nexport function parseBackupDestination(out: string): BackupDestination {\n const s3 = out.match(/^s3:\\/\\/([^/]+)\\/?(.*)$/);\n if (s3) return { kind: \"s3\", bucket: s3[1], prefix: s3[2].replace(/\\/+$/, \"\") };\n const gcs = out.match(/^gs:\\/\\/([^/]+)\\/?(.*)$/);\n if (gcs) return { kind: \"gcs\", bucket: gcs[1], prefix: gcs[2].replace(/\\/+$/, \"\") };\n return { kind: \"local\", path: out };\n}\n\n/**\n * Recover the UTC creation time encoded in a `rebase-<db>-<ts>.dump` name.\n * Returns `null` for names that don't match, so foreign objects are ignored.\n */\nexport function parseBackupTimestamp(fileName: string): Date | null {\n const base = fileName.split(\"/\").pop() ?? fileName;\n const match = base.match(/-(\\d{8})T(\\d{6})Z\\.dump$/);\n if (!match) return null;\n const [, ymd, hms] = match;\n const iso =\n `${ymd.slice(0, 4)}-${ymd.slice(4, 6)}-${ymd.slice(6, 8)}` +\n `T${hms.slice(0, 2)}:${hms.slice(2, 4)}:${hms.slice(4, 6)}Z`;\n const date = new Date(iso);\n return Number.isNaN(date.getTime()) ? null : date;\n}\n\n/**\n * A backup is two files: the `.dump`, and beside it a `.globals.sql` holding\n * the cluster roles the dump's GRANTs and RLS policies name. Without that\n * sidecar a restore into a fresh cluster stops at the first GRANT to a role\n * that does not exist there. The CLI uploads, restores and prunes the two as\n * a pair. This listing used to know only the `.dump`, so a backup downloaded\n * from Studio arrived without its roles.\n *\n * The suffix mirrors `globalsFileForDump` in `@rebasepro/server-postgres`.\n */\nconst DUMP_SUFFIX = \".dump\";\nconst GLOBALS_SUFFIX = \".globals.sql\";\n\nfunction globalsKeyFor(dumpKey: string): string {\n return dumpKey.slice(0, -DUMP_SUFFIX.length) + GLOBALS_SUFFIX;\n}\n\n/** The only files the download route will serve. */\nfunction isBackupFile(key: string): boolean {\n return key.endsWith(DUMP_SUFFIX) || key.endsWith(GLOBALS_SUFFIX);\n}\n\n/**\n * How many pages of an object-storage listing to read before giving up — at\n * the providers' 1,000 keys a page, 100,000 objects, or 50,000 backups.\n */\nconst MAX_LIST_PAGES = 100;\n\n/**\n * Every key under a prefix, across pages.\n *\n * S3 and GCS answer a listing a page at a time, in ascending key order, and a\n * backup's key is `rebase-<db>-<UTC timestamp>`. Reading one page therefore\n * returned the OLDEST thousand objects: with retention unset and an hourly\n * schedule, the newest backup the panel and `rebase db backups list` showed\n * stopped advancing after about three weeks, which reads as \"backups stopped\".\n */\nexport async function listAllObjectKeys(\n storage: StorageController,\n prefix: string,\n bucket: string\n): Promise<string[]> {\n const keys: string[] = [];\n let pageToken: string | undefined;\n for (let page = 0; page < MAX_LIST_PAGES; page++) {\n const result = await storage.listObjects(prefix, { bucket, maxResults: 1000, pageToken });\n for (const item of result.items) keys.push(item.fullPath);\n pageToken = result.nextPageToken;\n if (!pageToken) return keys;\n }\n logger.warn(\n `[backups] Stopped listing ${bucket}/${prefix} after ${MAX_LIST_PAGES} pages (${keys.length} objects). ` +\n \"Set BACKUP_RETENTION_DAYS so old backups are pruned, or give the backups a prefix of their own.\"\n );\n return keys;\n}\n\n/**\n * Whether an object key is one the backup routes may serve: a backup file, at\n * the destination's prefix and nowhere else.\n *\n * The local branch has always been held to the backup directory; this branch\n * checked only the suffix, so any `.dump` in the bucket — `uploads/x.dump`, a\n * neighbouring `nightlyish/` prefix — was readable by naming it. A key is taken\n * as written, so a scheme (`s3://other-bucket/…`, which S3StorageController\n * would follow) or a `.`/`..`/empty segment (which a filesystem-backed or\n * S3-compatible store may resolve) is refused rather than interpreted.\n */\nfunction isObjectBackupKey(dest: { prefix: string }, key: string): boolean {\n if (!isBackupFile(key) || /^[a-z][a-z0-9+.-]*:\\/\\//i.test(key)) return false;\n const segments = key.split(\"/\");\n if (segments.some((segment) => segment === \"\" || segment === \".\" || segment === \"..\")) return false;\n return dest.prefix === \"\" || key.startsWith(`${dest.prefix}/`);\n}\n\n/**\n * List the backups at a destination as {@link BackupInfo}, newest first.\n * One entry per `.dump`, with its `.globals.sql` sidecar attached as\n * `globalsKey` when there is one.\n */\nexport async function listBackupObjects(\n dest: BackupDestination,\n storage?: StorageController\n): Promise<BackupInfo[]> {\n if (dest.kind === \"local\") {\n // Asynchronous throughout, a few stats at a time. This runs on the\n // Backups panel's request path, and a year of hourly backups is 8,760\n // dumps: stat'ed synchronously, the server answered nothing else\n // while it listed them.\n const stat = await fs.promises.stat(dest.path).catch(() => null);\n if (!stat) return [];\n const dir = stat.isDirectory() ? dest.path : path.dirname(dest.path);\n const files = await fs.promises.readdir(dir);\n const present = new Set(files);\n const dumps = files.filter((f) => f.endsWith(DUMP_SUFFIX));\n const stats = await mapBounded(dumps, LOCAL_STAT_CONCURRENCY, (f) => fs.promises.stat(path.join(dir, f)));\n return dumps\n .map((f, i): BackupInfo => {\n const full = path.join(dir, f);\n const st = stats[i];\n const createdAt = parseBackupTimestamp(f) ?? st.mtime;\n const globals = globalsKeyFor(f);\n return {\n key: full,\n name: f,\n sizeBytes: st.size,\n createdAt: createdAt.toISOString(),\n destinationKind: \"local\",\n ...(present.has(globals) ? { globalsKey: path.join(dir, globals) } : {})\n };\n })\n .sort(byNewest);\n }\n\n // An empty list is a claim about the bucket. Without a controller for it\n // nothing was read, and the panel said \"No backups yet.\" about a bucket\n // full of them.\n if (!storage) throw new Error(noControllerFor(dest));\n const keys = await listAllObjectKeys(storage, dest.prefix ? `${dest.prefix}/` : \"\", dest.bucket);\n const present = new Set(keys);\n return keys\n .filter((key) => key.endsWith(DUMP_SUFFIX))\n .map((key): BackupInfo => {\n const createdAt = parseBackupTimestamp(key);\n const globals = globalsKeyFor(key);\n return {\n key,\n name: key.split(\"/\").pop() || key,\n createdAt: createdAt ? createdAt.toISOString() : undefined,\n destinationKind: dest.kind as BackupDestinationKind,\n ...(present.has(globals) ? { globalsKey: globals } : {})\n };\n })\n .sort(byNewest);\n}\n\n/** Stats in flight at once while listing a local backup folder. */\nconst LOCAL_STAT_CONCURRENCY = 32;\n\n/** `fn` over `items`, at most `limit` at a time; results in input order. */\nasync function mapBounded<T, R>(items: readonly T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]> {\n const results = new Array<R>(items.length);\n let next = 0;\n const worker = async () => {\n while (next < items.length) {\n const i = next++;\n results[i] = await fn(items[i]);\n }\n };\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));\n return results;\n}\n\nfunction noControllerFor(dest: { kind: \"s3\" | \"gcs\"; bucket: string; prefix: string }): string {\n const scheme = dest.kind === \"s3\" ? \"s3\" : \"gs\";\n return `No storage controller for ${scheme}://${dest.bucket}${dest.prefix ? `/${dest.prefix}` : \"\"}, so its backups cannot be read.`;\n}\n\nfunction byNewest(a: BackupInfo, b: BackupInfo): number {\n const ta = a.createdAt ? Date.parse(a.createdAt) : 0;\n const tb = b.createdAt ? Date.parse(b.createdAt) : 0;\n return tb - ta;\n}\n\n/**\n * The absolute path of a local backup file, or `null` for anything the download\n * route must not serve: a path outside the backup directory, a file that is not\n * a backup, or one that does not exist.\n */\nfunction resolveLocalBackupFile(dest: { path: string }, key: string): string | null {\n const stat = fs.existsSync(dest.path) ? fs.statSync(dest.path) : null;\n const dir = stat?.isDirectory() ? dest.path : path.dirname(dest.path);\n const resolvedDir = path.resolve(dir);\n const resolved = path.resolve(key);\n // Only allow reads inside the backup directory, and only backup files.\n if (!resolved.startsWith(resolvedDir + path.sep) || !isBackupFile(resolved)) {\n return null;\n }\n return fs.existsSync(resolved) ? resolved : null;\n}\n\n/** Read a single backup's bytes. Guards against path traversal for local. */\nexport async function readBackupBytes(\n dest: BackupDestination,\n key: string,\n storage?: StorageController\n): Promise<{ bytes: Uint8Array<ArrayBuffer>; name: string } | null> {\n if (dest.kind === \"local\") {\n const resolved = resolveLocalBackupFile(dest, key);\n if (!resolved) return null;\n return { bytes: new Uint8Array(fs.readFileSync(resolved)), name: path.basename(resolved) };\n }\n\n if (!storage) throw new Error(noControllerFor(dest));\n if (!isObjectBackupKey(dest, key)) return null;\n const file = await storage.getObject(key, dest.bucket);\n if (!file) return null;\n return { bytes: new Uint8Array(await file.arrayBuffer()), name: key.split(\"/\").pop() || key };\n}\n\n/**\n * Whether `key` names a backup the download route would serve, without\n * opening it: the same guards as {@link openBackupStream}, and the file or\n * object is there. An object store without `statObject` is taken at its key —\n * reading the object to find out would be the download itself.\n */\nexport async function findBackup(\n dest: BackupDestination,\n key: string,\n storage?: StorageController\n): Promise<{ name: string } | null> {\n if (dest.kind === \"local\") {\n const resolved = resolveLocalBackupFile(dest, key);\n return resolved ? { name: path.basename(resolved) } : null;\n }\n if (!storage) throw new Error(noControllerFor(dest));\n if (!isObjectBackupKey(dest, key)) return null;\n if (storage.statObject && !(await storage.statObject(key, dest.bucket))) return null;\n return { name: key.split(\"/\").pop() || key };\n}\n\n/**\n * A single backup, opened for streaming, with its size. Same guards as\n * {@link readBackupBytes}.\n *\n * What the download route serves. A dump is the size of the database, and\n * reading it whole put all of it on the API process's heap — twice for a local\n * destination (`readFileSync`, then a copy) and on top of the controller's own\n * buffer for object storage — and a file over 2 GiB never downloaded at all:\n * `readFileSync` throws `ERR_FS_FILE_TOO_LARGE` there.\n *\n * A local file is read from disk as the response is written, and so is an\n * object through a controller with `getObjectStream` (the built-in S3 and GCS\n * ones). A custom controller without it still arrives through\n * {@link StorageController.getObject}, a buffered `File` by contract;\n * streaming that avoids the second copy.\n */\nexport async function openBackupStream(\n dest: BackupDestination,\n key: string,\n storage?: StorageController\n): Promise<{ stream: ReadableStream<Uint8Array>; size: number; name: string } | null> {\n if (dest.kind === \"local\") {\n const resolved = resolveLocalBackupFile(dest, key);\n if (!resolved) return null;\n const { size } = await fs.promises.stat(resolved);\n return { stream: fileStream(resolved), size, name: path.basename(resolved) };\n }\n\n if (!storage) throw new Error(noControllerFor(dest));\n if (!isObjectBackupKey(dest, key)) return null;\n const name = key.split(\"/\").pop() || key;\n if (storage.getObjectStream) {\n const object = await storage.getObjectStream(key, { bucket: dest.bucket });\n return object ? { stream: object.stream, size: object.size, name } : null;\n }\n const file = await storage.getObject(key, dest.bucket);\n if (!file) return null;\n return { stream: file.stream(), size: file.size, name };\n}\n\n/** A file on disk as a web stream, read a chunk at a time as the response is written. */\nfunction fileStream(filePath: string): ReadableStream<Uint8Array> {\n const file = fs.createReadStream(filePath);\n const chunks: AsyncIterator<Buffer> = file[Symbol.asyncIterator]();\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n const next = await chunks.next();\n if (next.done) controller.close();\n else controller.enqueue(next.value);\n },\n cancel() {\n file.destroy();\n }\n });\n}\n","/**\n * The storage controller that reads a backup bucket.\n *\n * A backup destination is its own bucket, named by `BACKUP_DESTINATION`, and\n * the documented backup cron writes to it through a controller it builds from\n * the `S3_*` variables (GCS: application default credentials) — as\n * `rebase db backups list` does. The admin routes have to read it the same way.\n * The app's file storage is not that controller: it is configured for the\n * uploads bucket, it is a local directory in development, and in production\n * without an uploads bucket there is none at all.\n */\nimport { parseEnvBoolean } from \"@rebasepro/types\";\nimport { GCSStorageController } from \"../storage/GCSStorageController\";\nimport { S3StorageController } from \"../storage/S3StorageController\";\nimport type { StorageController } from \"../storage/types\";\nimport { parseBackupDestination, type BackupDestination } from \"./backup-common\";\n\n/** A destination in object storage — `s3://bucket/prefix` or `gs://bucket/prefix`. */\nexport type ObjectBackupDestination = Exclude<BackupDestination, { kind: \"local\" }>;\n\n/** The destination `BACKUP_DESTINATION` names, or `null` when it is unset. */\nexport function backupDestinationFromEnv(env: Record<string, string | undefined>): BackupDestination | null {\n const out = env.BACKUP_DESTINATION?.trim();\n return out ? parseBackupDestination(out) : null;\n}\n\n/** The destination as `BACKUP_DESTINATION` spells it. */\nexport function describeBackupDestination(dest: BackupDestination): string {\n if (dest.kind === \"local\") return dest.path;\n const scheme = dest.kind === \"s3\" ? \"s3\" : \"gs\";\n return `${scheme}://${dest.bucket}${dest.prefix ? `/${dest.prefix}` : \"\"}`;\n}\n\n/**\n * A controller for an object-storage destination's bucket, built from the\n * environment the way the backup cron and `rebase db backups list` build\n * theirs. Throws when an S3 destination has no credentials to read it with.\n */\nexport function backupStorageFromEnv(\n dest: ObjectBackupDestination,\n env: Record<string, string | undefined>\n): StorageController {\n if (dest.kind === \"gcs\") {\n return new GCSStorageController({ type: \"gcs\", bucket: dest.bucket });\n }\n // s3 also covers R2, MinIO and the other S3-compatible stores, through S3_ENDPOINT.\n if (!env.S3_ACCESS_KEY_ID || !env.S3_SECRET_ACCESS_KEY) {\n throw new Error(\n \"An S3 backup destination needs S3_ACCESS_KEY_ID and S3_SECRET_ACCESS_KEY in the environment \" +\n \"— the same S3_* variables the backup cron uses.\"\n );\n }\n return new S3StorageController({\n type: \"s3\",\n bucket: dest.bucket,\n region: env.S3_REGION || \"auto\",\n accessKeyId: env.S3_ACCESS_KEY_ID,\n secretAccessKey: env.S3_SECRET_ACCESS_KEY,\n endpoint: env.S3_ENDPOINT,\n // Unset stays unset, so the controller decides from the endpoint.\n forcePathStyle: parseEnvBoolean(env.S3_FORCE_PATH_STYLE)\n });\n}\n","import { Hono, type Context } from \"hono\";\nimport type { BackupDownloadLink, BackupListing, BackupScheduleStatus } from \"@rebasepro/types\";\nimport type { HonoEnv } from \"../api/types\";\nimport { ApiError, errorHandler } from \"../api/errors\";\nimport { jwtOf, type JwtService } from \"../auth/jwt\";\nimport type { StorageController } from \"../storage/types\";\nimport { BackupDestination, findBackup, listBackupObjects, openBackupStream } from \"./backup-common\";\nimport { backupStorageFromEnv, describeBackupDestination, type ObjectBackupDestination } from \"./backup-storage\";\n\nexport interface BackupRoutesConfig {\n /**\n * Resolve the current backup destination, or `null` when backups are not\n * configured (`BACKUP_DESTINATION` unset). Read lazily so a restart isn't\n * required to pick up config.\n */\n getDestination: () => BackupDestination | null;\n /**\n * The controller that reads an object-storage destination. It has to\n * address the destination's own bucket — never the app's file storage,\n * which is another bucket, a local directory, or nothing. Defaults to\n * {@link backupStorageFromEnv} over `process.env`, which is how the backup\n * cron builds the one it writes with.\n */\n storageFor?: (dest: ObjectBackupDestination) => StorageController;\n /**\n * The scheduled backup job and its last run — see `readBackupSchedule`.\n * Omitted where this process has no cron scheduler; the listing then\n * answers `schedule: null`.\n */\n getSchedule?: () => Promise<BackupScheduleStatus | null>;\n /**\n * True when this process does not run the scheduled jobs (the `api` role\n * of a split deployment). A local destination read here is then this\n * process's disk, not the one the scheduled backup writes to.\n */\n scheduledElsewhere?: boolean;\n}\n\n/** Why a destination could not be read, as the answer says it. */\nfunction unreadable(dest: BackupDestination, err: unknown): ApiError {\n const reason = err instanceof Error ? err.message : String(err);\n return ApiError.serviceUnavailable(`Cannot read the backups at ${describeBackupDestination(dest)}: ${reason}`);\n}\n\n// ─── Download links ──────────────────────────────────────────────────\n\n/**\n * The `purpose` of a download link's token. `verifyAccessToken` refuses\n * any token with a purpose, and the storage, MFA and MCP verifiers each demand\n * their own, so a link is never a session or any other credential, and none of\n * those is a link.\n */\nconst BACKUP_DOWNLOAD_PURPOSE = \"backup-download\";\n/** The token's audience: the one route that redeems it. */\nconst BACKUP_DOWNLOAD_AUDIENCE = \"rebase:admin/backups/download\";\n/** How long a link works. Long enough to start the download, not to pass around. */\nexport const BACKUP_DOWNLOAD_LINK_TTL_SECONDS = 60;\n\n/** What a link grants: one backup, at one destination. */\nfunction linkScope(dest: BackupDestination, key: string): string {\n return `backup:${describeBackupDestination(dest)}:${key}`;\n}\n\n/**\n * Whether `token` is a live link for `key` at `dest`, signed by `jwt` — the\n * backend answering. Never throws: anything else is a no.\n */\nasync function linkGrants(jwt: JwtService, token: string, dest: BackupDestination, key: string): Promise<boolean> {\n if (!jwt.isConfigured()) return false;\n const claims = await jwt.verifyPurposeToken<{ aud?: unknown; scope?: unknown }>(BACKUP_DOWNLOAD_PURPOSE, token)\n .catch(() => null);\n return claims?.aud === BACKUP_DOWNLOAD_AUDIENCE && claims.scope === linkScope(dest, key);\n}\n\n/** The configured destination, or the 400 every backup route answers without one. */\nfunction destinationOf(config: Pick<BackupRoutesConfig, \"getDestination\">): BackupDestination {\n const dest = config.getDestination();\n if (!dest) throw ApiError.badRequest(\"Backups are not configured (set BACKUP_DESTINATION).\");\n return dest;\n}\n\n/** {@link BackupRoutesConfig.storageFor}, with its default, for a destination that has a controller. */\nfunction storageResolver(config: Pick<BackupRoutesConfig, \"storageFor\">): (dest: BackupDestination) => StorageController | undefined {\n const storageFor = config.storageFor ?? ((dest: ObjectBackupDestination) => backupStorageFromEnv(dest, process.env));\n /** The controller for `dest`, or none for a local one. A destination it cannot read is an error, never `[]`. */\n return (dest) => {\n if (dest.kind === \"local\") return undefined;\n try {\n return storageFor(dest);\n } catch (err) {\n throw unreadable(dest, err);\n }\n };\n}\n\n/** One backup's bytes as the response, streamed: a dump is the size of the database. See `openBackupStream`. */\nasync function serveBackup(c: Context<HonoEnv>, dest: BackupDestination, key: string, storage: StorageController | undefined): Promise<Response> {\n const result = await openBackupStream(dest, key, storage);\n if (!result) {\n throw ApiError.notFound(`Backup not found: ${key}`);\n }\n c.header(\"Content-Type\", \"application/octet-stream\");\n c.header(\"Content-Length\", String(result.size));\n c.header(\"Content-Disposition\", `attachment; filename=\"${result.name}\"`);\n // A whole database, and on a link a URL that grants it: nothing in between keeps a copy.\n c.header(\"Cache-Control\", \"no-store\");\n return c.body(result.stream);\n}\n\n/**\n * `GET /download?key=…&token=…`: a download link spent in place of the bearer\n * header, for the one backup it names.\n *\n * Mount it at the backups prefix AHEAD of every gate on the admin prefix: the\n * auth adapter's own admin routers authenticate everything under `/admin`\n * before the Backups gate is reached. A request with no `token` passes\n * through untouched; one with a token is answered here — the backup, or a\n * 401 — and never falls through to the header: a bad link is a bad link.\n *\n * A browser cannot put a header on a navigation, so before links the SDK\n * fetched the dump and held it whole in the tab as a Blob. With a link the\n * browser streams it to disk.\n */\nexport function createBackupLinkRoutes(config: Pick<BackupRoutesConfig, \"getDestination\" | \"storageFor\">): Hono<HonoEnv> {\n const router = new Hono<HonoEnv>();\n router.onError(errorHandler);\n const storageOf = storageResolver(config);\n router.get(\"/download\", async (c, next) => {\n const token = c.req.query(\"token\");\n if (token === undefined) return next();\n const dest = destinationOf(config);\n const key = c.req.query(\"key\") ?? \"\";\n if (!(await linkGrants(jwtOf(c), token, dest, key))) {\n throw ApiError.unauthenticated(\n \"This download link is not valid for this backup, or it has expired. Links last \" +\n `${BACKUP_DOWNLOAD_LINK_TTL_SECONDS} seconds: ask for a new one.`\n );\n }\n return serveBackup(c, dest, key, storageOf(dest));\n });\n return router;\n}\n\n/**\n * Admin REST routes for the Backups panel.\n *\n * Routes (mounted under `/admin/backups`, admin-guarded by the caller):\n * GET / → list available backups, and the scheduled job's last run\n * GET /download → download a backup's bytes (?key=…)\n * POST /download-url → a 60-second link to one backup, `{ key }` → {@link BackupDownloadLink}\n *\n * The link is spent at `GET /download?key=…&token=…`, which\n * {@link createBackupLinkRoutes} answers ahead of the gate.\n */\nexport function createBackupRoutes(config: BackupRoutesConfig): Hono<HonoEnv> {\n const router = new Hono<HonoEnv>();\n router.onError(errorHandler);\n\n const storageOf = storageResolver(config);\n\n router.get(\"/\", async (c) => {\n // Read whether or not a destination is configured: a backup cron with\n // no BACKUP_DESTINATION fails every run, and that is exactly what the\n // panel has to be able to say.\n const schedule = config.getSchedule ? await config.getSchedule() : null;\n const dest = config.getDestination();\n if (!dest) {\n return c.json({ backups: [], destinationKind: \"local\", configured: false, schedule } satisfies BackupListing);\n }\n const backups = await listBackupObjects(dest, storageOf(dest)).catch((err: unknown) => {\n throw unreadable(dest, err);\n });\n // Only where there is a scheduled backup to write elsewhere.\n const localDiskOfThisProcess = dest.kind === \"local\" && config.scheduledElsewhere === true && schedule !== null;\n return c.json({\n backups,\n destinationKind: dest.kind,\n configured: true,\n schedule,\n ...(localDiskOfThisProcess ? { localDiskOfThisProcess } : {})\n } satisfies BackupListing);\n });\n\n router.get(\"/download\", async (c) => {\n const dest = destinationOf(config);\n const key = c.req.query(\"key\");\n if (!key) {\n throw ApiError.badRequest(\"Missing 'key' query parameter.\");\n }\n return serveBackup(c, dest, key, storageOf(dest));\n });\n\n router.post(\"/download-url\", async (c) => {\n const dest = destinationOf(config);\n const body: unknown = await c.req.json().catch(() => null);\n const key = typeof body === \"object\" && body !== null && \"key\" in body ? body.key : undefined;\n if (typeof key !== \"string\" || !key) {\n throw ApiError.badRequest(\"Send the backup's key: { \\\"key\\\": \\\"…\\\" }.\");\n }\n // The download route's own guards, so a link is never minted for a\n // key it would refuse; and the backup is there, so the browser is not\n // sent to a 404 in place of a file.\n if (!(await findBackup(dest, key, storageOf(dest)))) {\n throw ApiError.notFound(`Backup not found: ${key}`);\n }\n const jwt = jwtOf(c);\n if (!jwt.isConfigured()) {\n throw ApiError.serviceUnavailable(\n \"Download links are signed with the JWT secret, and this server has none (auth.jwtSecret). \" +\n \"Download through GET /download with the Authorization header instead.\"\n );\n }\n const token = await jwt.signPurposeToken(\n BACKUP_DOWNLOAD_PURPOSE,\n { aud: BACKUP_DOWNLOAD_AUDIENCE, scope: linkScope(dest, key) },\n BACKUP_DOWNLOAD_LINK_TTL_SECONDS\n );\n const download = new URL(\"download\", c.req.url).pathname;\n return c.json({\n url: `${download}?key=${encodeURIComponent(key)}&token=${encodeURIComponent(token)}`,\n token,\n expiresIn: BACKUP_DOWNLOAD_LINK_TTL_SECONDS\n } satisfies BackupDownloadLink);\n });\n\n return router;\n}\n","/**\n * The scheduled backup job, as the Backups panel reports it.\n *\n * A backup that fails every night has to be visible where the backups are\n * listed. Before this the panel read the destination and nothing else, so a\n * cron that could not run `pg_dump` left an empty list under \"wait for the next\n * scheduled run\" — while each failure sat in `cron_logs`, one panel away.\n */\nimport type {\n BackupRunOutcome,\n BackupScheduleStatus,\n CronJobDefinition,\n CronJobLogEntry,\n CronJobStatus,\n RejectedCronJob\n} from \"@rebasepro/types\";\nimport { isAlreadyExecutingSkip } from \"../cron/cron-scheduler\";\nimport { logger } from \"../utils/logger\";\n\n/**\n * The mark `createBackupCron` (in `@rebasepro/server-postgres`) puts on the\n * definition it returns.\n *\n * A registry symbol, so it is the same value across two installed copies of\n * either package, and neither package has to import the other: `server` must\n * not depend on `server-postgres`. The job cannot be recognised any other way —\n * its id is the cron file's name and its display name is configurable.\n */\nexport const BACKUP_CRON_MARK: unique symbol = Symbol.for(\"rebase.backupCron\");\n\n/** Whether a cron definition is the scheduled backup. */\nexport function isBackupCronDefinition(definition: CronJobDefinition): boolean {\n return Reflect.get(definition, BACKUP_CRON_MARK) === true;\n}\n\n/** The part of the cron scheduler this reads. */\nexport interface BackupScheduleSource {\n jobIdsWhere(predicate: (definition: CronJobDefinition) => boolean): string[];\n rejectedJobsWhere(predicate: (definition: CronJobDefinition) => boolean): RejectedCronJob[];\n fetchJob(id: string): Promise<CronJobStatus | undefined>;\n getJobLogsFromDb(id: string, limit?: number): Promise<CronJobLogEntry[]>;\n}\n\n/**\n * How many recent log entries to look through for the last scheduled run. A\n * skip — a slot that found the previous run still going — is logged as a\n * success with nothing done, and must not stand in for the run it skipped; nor\n * may a run someone started by hand, which is not the schedule's.\n */\nconst RECENT_RUNS = 50;\n\n/** A log entry as the panel reports a run. */\nfunction outcomeOf(entry: CronJobLogEntry): BackupRunOutcome {\n return {\n startedAt: entry.startedAt,\n finishedAt: entry.finishedAt,\n success: entry.success,\n ...(entry.success || !entry.error ? {} : { error: entry.error }),\n manual: entry.manual === true\n };\n}\n\n/**\n * The scheduled backup job and its last run, or `null` when the deployment\n * has none — registered or refused.\n */\nexport async function readBackupSchedule(source: BackupScheduleSource): Promise<BackupScheduleStatus | null> {\n const [jobId] = source.jobIdsWhere(isBackupCronDefinition);\n if (jobId === undefined) {\n // A refused job is not registered, and answered `null` here it read\n // as \"no backup cron\" under a hint to add the file the project has.\n const [refused] = source.rejectedJobsWhere(isBackupCronDefinition);\n return refused\n ? { jobId: refused.id, name: refused.name, schedule: refused.schedule, enabled: false, refused: refused.reason }\n : null;\n }\n\n const job = await source.fetchJob(jobId);\n if (!job) return null;\n // Off because its own definition says so — the documented cron file\n // exports `enabled: false` while BACKUP_SCHEDULE is unset — rather than\n // paused by someone. Resuming that in Cron Jobs would run the placeholder.\n const disabledInCode = !job.enabled &&\n source.jobIdsWhere(definition => isBackupCronDefinition(definition) && definition.enabled === false).includes(jobId);\n\n let recent: CronJobLogEntry[];\n let historyError: string | undefined;\n try {\n recent = await source.getJobLogsFromDb(jobId, RECENT_RUNS);\n } catch (err) {\n // Said, not read as \"has not run yet\". The listing itself still\n // answers: the backups at the destination are worth showing.\n logger.error(`[backups] Could not read the run history of the backup job \"${jobId}\"`, { error: err });\n recent = [];\n historyError = \"The backup job's run history could not be read. The server log has the reason.\";\n }\n const runs = recent.filter(entry => !isAlreadyExecutingSkip(entry));\n // \"Last scheduled backup\" is the schedule's: a later \"Run Now\" that worked\n // hid a failed nightly, and a failed test run read as a failed nightly.\n const lastScheduled = runs.find(entry => entry.manual !== true);\n // A run by hand since then is reported too, as what it is.\n const lastManual = runs.find(entry => entry.manual === true);\n const manualSince = lastManual && (!lastScheduled || lastManual.startedAt > lastScheduled.startedAt)\n ? lastManual\n : undefined;\n\n return {\n jobId,\n name: job.name,\n schedule: job.schedule,\n enabled: job.enabled,\n ...(disabledInCode ? { disabledInCode } : {}),\n ...(job.nextRunAt ? { nextRunAt: job.nextRunAt } : {}),\n ...(historyError ? { historyError } : {}),\n ...(lastScheduled ? { lastRun: outcomeOf(lastScheduled) } : {}),\n ...(manualSince ? { lastManualRun: outcomeOf(manualSince) } : {})\n };\n}\n","/**\n * Storage-generic backup helpers and admin routes for the Backups panel.\n * The `pg_dump`/`pg_restore` machinery lives in `@rebasepro/server-postgres`.\n */\nexport * from \"./backup-common\";\nexport { createBackupRoutes, createBackupLinkRoutes, BACKUP_DOWNLOAD_LINK_TTL_SECONDS } from \"./backup-routes\";\nexport { backupDestinationFromEnv, backupStorageFromEnv } from \"./backup-storage\";\nexport type { ObjectBackupDestination } from \"./backup-storage\";\nexport type { BackupRoutesConfig } from \"./backup-routes\";\nexport { readBackupSchedule, isBackupCronDefinition, BACKUP_CRON_MARK } from \"./backup-schedule\";\nexport type { BackupScheduleSource } from \"./backup-schedule\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,uBAAuB,KAAgC;CACnE,MAAM,KAAK,IAAI,MAAM,yBAAyB;CAC9C,IAAI,IAAI,O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,UAAU,aAAa,EAAE,IAAI,CAAC;EAC7D,GAAI,cAAc,EAAE,eAAe,UAAU,WAAW,EAAE,IAAI,CAAC;CACnE;AACJ"}
1
+ {"version":3,"file":"backup-g2ohsDe0.js","names":[],"sources":["../src/backup/backup-common.ts","../src/backup/backup-storage.ts","../src/backup/backup-routes.ts","../src/backup/backup-schedule.ts","../src/backup/index.ts"],"sourcesContent":["/**\n * Storage-generic backup helpers used by the admin backup routes.\n *\n * These live in server (which owns {@link StorageController}) so the\n * admin API can list backups without depending on the Postgres driver —\n * `server` must not import from `server-postgres`. The `pg_dump`-side\n * copies of the tiny pure parsers live in `@rebasepro/server-postgres`;\n * keep the two in sync if the naming scheme ever changes.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport type { BackupInfo, BackupDestinationKind } from \"@rebasepro/types\";\nimport type { StorageController } from \"../storage\";\nimport { logger } from \"../utils/logger\";\n\nexport type BackupDestination =\n | { kind: \"local\"; path: string }\n | { kind: \"s3\"; bucket: string; prefix: string }\n | { kind: \"gcs\"; bucket: string; prefix: string };\n\n/** Parse a destination string (`s3://…`, `gs://…`, or a local path). */\nexport function parseBackupDestination(out: string): BackupDestination {\n const s3 = out.match(/^s3:\\/\\/([^/]+)\\/?(.*)$/);\n if (s3) return { kind: \"s3\", bucket: s3[1], prefix: s3[2].replace(/\\/+$/, \"\") };\n const gcs = out.match(/^gs:\\/\\/([^/]+)\\/?(.*)$/);\n if (gcs) return { kind: \"gcs\", bucket: gcs[1], prefix: gcs[2].replace(/\\/+$/, \"\") };\n return { kind: \"local\", path: out };\n}\n\n/**\n * Recover the UTC creation time encoded in a `rebase-<db>-<ts>.dump` name.\n * Returns `null` for names that don't match, so foreign objects are ignored.\n */\nexport function parseBackupTimestamp(fileName: string): Date | null {\n const base = fileName.split(\"/\").pop() ?? fileName;\n const match = base.match(/-(\\d{8})T(\\d{6})Z\\.dump$/);\n if (!match) return null;\n const [, ymd, hms] = match;\n const iso =\n `${ymd.slice(0, 4)}-${ymd.slice(4, 6)}-${ymd.slice(6, 8)}` +\n `T${hms.slice(0, 2)}:${hms.slice(2, 4)}:${hms.slice(4, 6)}Z`;\n const date = new Date(iso);\n return Number.isNaN(date.getTime()) ? null : date;\n}\n\n/**\n * A backup is two files: the `.dump`, and beside it a `.globals.sql` holding\n * the cluster roles the dump's GRANTs and RLS policies name. Without that\n * sidecar a restore into a fresh cluster stops at the first GRANT to a role\n * that does not exist there. The CLI uploads, restores and prunes the two as\n * a pair. This listing used to know only the `.dump`, so a backup downloaded\n * from Studio arrived without its roles.\n *\n * The suffix mirrors `globalsFileForDump` in `@rebasepro/server-postgres`.\n */\nconst DUMP_SUFFIX = \".dump\";\nconst GLOBALS_SUFFIX = \".globals.sql\";\n\nfunction globalsKeyFor(dumpKey: string): string {\n return dumpKey.slice(0, -DUMP_SUFFIX.length) + GLOBALS_SUFFIX;\n}\n\n/** The only files the download route will serve. */\nfunction isBackupFile(key: string): boolean {\n return key.endsWith(DUMP_SUFFIX) || key.endsWith(GLOBALS_SUFFIX);\n}\n\n/**\n * How many pages of an object-storage listing to read before giving up — at\n * the providers' 1,000 keys a page, 100,000 objects, or 50,000 backups.\n */\nconst MAX_LIST_PAGES = 100;\n\n/**\n * Every key under a prefix, across pages.\n *\n * S3 and GCS answer a listing a page at a time, in ascending key order, and a\n * backup's key is `rebase-<db>-<UTC timestamp>`. Reading one page therefore\n * returned the OLDEST thousand objects: with retention unset and an hourly\n * schedule, the newest backup the panel and `rebase db backups list` showed\n * stopped advancing after about three weeks, which reads as \"backups stopped\".\n */\nexport async function listAllObjectKeys(\n storage: StorageController,\n prefix: string,\n bucket: string\n): Promise<string[]> {\n const keys: string[] = [];\n let pageToken: string | undefined;\n for (let page = 0; page < MAX_LIST_PAGES; page++) {\n const result = await storage.listObjects(prefix, { bucket, maxResults: 1000, pageToken });\n for (const item of result.items) keys.push(item.fullPath);\n pageToken = result.nextPageToken;\n if (!pageToken) return keys;\n }\n logger.warn(\n `[backups] Stopped listing ${bucket}/${prefix} after ${MAX_LIST_PAGES} pages (${keys.length} objects). ` +\n \"Set BACKUP_RETENTION_DAYS so old backups are pruned, or give the backups a prefix of their own.\"\n );\n return keys;\n}\n\n/**\n * Whether an object key is one the backup routes may serve: a backup file, at\n * the destination's prefix and nowhere else.\n *\n * The local branch has always been held to the backup directory; this branch\n * checked only the suffix, so any `.dump` in the bucket — `uploads/x.dump`, a\n * neighbouring `nightlyish/` prefix — was readable by naming it. A key is taken\n * as written, so a scheme (`s3://other-bucket/…`, which S3StorageController\n * would follow) or a `.`/`..`/empty segment (which a filesystem-backed or\n * S3-compatible store may resolve) is refused rather than interpreted.\n */\nfunction isObjectBackupKey(dest: { prefix: string }, key: string): boolean {\n if (!isBackupFile(key) || /^[a-z][a-z0-9+.-]*:\\/\\//i.test(key)) return false;\n const segments = key.split(\"/\");\n if (segments.some((segment) => segment === \"\" || segment === \".\" || segment === \"..\")) return false;\n return dest.prefix === \"\" || key.startsWith(`${dest.prefix}/`);\n}\n\n/**\n * List the backups at a destination as {@link BackupInfo}, newest first.\n * One entry per `.dump`, with its `.globals.sql` sidecar attached as\n * `globalsKey` when there is one.\n */\nexport async function listBackupObjects(\n dest: BackupDestination,\n storage?: StorageController\n): Promise<BackupInfo[]> {\n if (dest.kind === \"local\") {\n // Asynchronous throughout, a few stats at a time. This runs on the\n // Backups panel's request path, and a year of hourly backups is 8,760\n // dumps: stat'ed synchronously, the server answered nothing else\n // while it listed them.\n const stat = await fs.promises.stat(dest.path).catch(() => null);\n if (!stat) return [];\n const dir = stat.isDirectory() ? dest.path : path.dirname(dest.path);\n const files = await fs.promises.readdir(dir);\n const present = new Set(files);\n const dumps = files.filter((f) => f.endsWith(DUMP_SUFFIX));\n const stats = await mapBounded(dumps, LOCAL_STAT_CONCURRENCY, (f) => fs.promises.stat(path.join(dir, f)));\n return dumps\n .map((f, i): BackupInfo => {\n const full = path.join(dir, f);\n const st = stats[i];\n const createdAt = parseBackupTimestamp(f) ?? st.mtime;\n const globals = globalsKeyFor(f);\n return {\n key: full,\n name: f,\n sizeBytes: st.size,\n createdAt: createdAt.toISOString(),\n destinationKind: \"local\",\n ...(present.has(globals) ? { globalsKey: path.join(dir, globals) } : {})\n };\n })\n .sort(byNewest);\n }\n\n // An empty list is a claim about the bucket. Without a controller for it\n // nothing was read, and the panel said \"No backups yet.\" about a bucket\n // full of them.\n if (!storage) throw new Error(noControllerFor(dest));\n const keys = await listAllObjectKeys(storage, dest.prefix ? `${dest.prefix}/` : \"\", dest.bucket);\n const present = new Set(keys);\n return keys\n .filter((key) => key.endsWith(DUMP_SUFFIX))\n .map((key): BackupInfo => {\n const createdAt = parseBackupTimestamp(key);\n const globals = globalsKeyFor(key);\n return {\n key,\n name: key.split(\"/\").pop() || key,\n createdAt: createdAt ? createdAt.toISOString() : undefined,\n destinationKind: dest.kind as BackupDestinationKind,\n ...(present.has(globals) ? { globalsKey: globals } : {})\n };\n })\n .sort(byNewest);\n}\n\n/** Stats in flight at once while listing a local backup folder. */\nconst LOCAL_STAT_CONCURRENCY = 32;\n\n/** `fn` over `items`, at most `limit` at a time; results in input order. */\nasync function mapBounded<T, R>(items: readonly T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]> {\n const results = new Array<R>(items.length);\n let next = 0;\n const worker = async () => {\n while (next < items.length) {\n const i = next++;\n results[i] = await fn(items[i]);\n }\n };\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));\n return results;\n}\n\nfunction noControllerFor(dest: { kind: \"s3\" | \"gcs\"; bucket: string; prefix: string }): string {\n const scheme = dest.kind === \"s3\" ? \"s3\" : \"gs\";\n return `No storage controller for ${scheme}://${dest.bucket}${dest.prefix ? `/${dest.prefix}` : \"\"}, so its backups cannot be read.`;\n}\n\nfunction byNewest(a: BackupInfo, b: BackupInfo): number {\n const ta = a.createdAt ? Date.parse(a.createdAt) : 0;\n const tb = b.createdAt ? Date.parse(b.createdAt) : 0;\n return tb - ta;\n}\n\n/**\n * The absolute path of a local backup file, or `null` for anything the download\n * route must not serve: a path outside the backup directory, a file that is not\n * a backup, or one that does not exist.\n */\nfunction resolveLocalBackupFile(dest: { path: string }, key: string): string | null {\n const stat = fs.existsSync(dest.path) ? fs.statSync(dest.path) : null;\n const dir = stat?.isDirectory() ? dest.path : path.dirname(dest.path);\n const resolvedDir = path.resolve(dir);\n const resolved = path.resolve(key);\n // Only allow reads inside the backup directory, and only backup files.\n if (!resolved.startsWith(resolvedDir + path.sep) || !isBackupFile(resolved)) {\n return null;\n }\n return fs.existsSync(resolved) ? resolved : null;\n}\n\n/** Read a single backup's bytes. Guards against path traversal for local. */\nexport async function readBackupBytes(\n dest: BackupDestination,\n key: string,\n storage?: StorageController\n): Promise<{ bytes: Uint8Array<ArrayBuffer>; name: string } | null> {\n if (dest.kind === \"local\") {\n const resolved = resolveLocalBackupFile(dest, key);\n if (!resolved) return null;\n return { bytes: new Uint8Array(fs.readFileSync(resolved)), name: path.basename(resolved) };\n }\n\n if (!storage) throw new Error(noControllerFor(dest));\n if (!isObjectBackupKey(dest, key)) return null;\n const file = await storage.getObject(key, dest.bucket);\n if (!file) return null;\n return { bytes: new Uint8Array(await file.arrayBuffer()), name: key.split(\"/\").pop() || key };\n}\n\n/**\n * Whether `key` names a backup the download route would serve, without\n * opening it: the same guards as {@link openBackupStream}, and the file or\n * object is there. An object store without `statObject` is taken at its key —\n * reading the object to find out would be the download itself.\n */\nexport async function findBackup(\n dest: BackupDestination,\n key: string,\n storage?: StorageController\n): Promise<{ name: string } | null> {\n if (dest.kind === \"local\") {\n const resolved = resolveLocalBackupFile(dest, key);\n return resolved ? { name: path.basename(resolved) } : null;\n }\n if (!storage) throw new Error(noControllerFor(dest));\n if (!isObjectBackupKey(dest, key)) return null;\n if (storage.statObject && !(await storage.statObject(key, dest.bucket))) return null;\n return { name: key.split(\"/\").pop() || key };\n}\n\n/**\n * A single backup, opened for streaming, with its size. Same guards as\n * {@link readBackupBytes}.\n *\n * What the download route serves. A dump is the size of the database, and\n * reading it whole put all of it on the API process's heap — twice for a local\n * destination (`readFileSync`, then a copy) and on top of the controller's own\n * buffer for object storage — and a file over 2 GiB never downloaded at all:\n * `readFileSync` throws `ERR_FS_FILE_TOO_LARGE` there.\n *\n * A local file is read from disk as the response is written, and so is an\n * object through a controller with `getObjectStream` (the built-in S3 and GCS\n * ones). A custom controller without it still arrives through\n * {@link StorageController.getObject}, a buffered `File` by contract;\n * streaming that avoids the second copy.\n */\nexport async function openBackupStream(\n dest: BackupDestination,\n key: string,\n storage?: StorageController\n): Promise<{ stream: ReadableStream<Uint8Array>; size: number; name: string } | null> {\n if (dest.kind === \"local\") {\n const resolved = resolveLocalBackupFile(dest, key);\n if (!resolved) return null;\n const { size } = await fs.promises.stat(resolved);\n return { stream: fileStream(resolved), size, name: path.basename(resolved) };\n }\n\n if (!storage) throw new Error(noControllerFor(dest));\n if (!isObjectBackupKey(dest, key)) return null;\n const name = key.split(\"/\").pop() || key;\n if (storage.getObjectStream) {\n const object = await storage.getObjectStream(key, { bucket: dest.bucket });\n return object ? { stream: object.stream, size: object.size, name } : null;\n }\n const file = await storage.getObject(key, dest.bucket);\n if (!file) return null;\n return { stream: file.stream(), size: file.size, name };\n}\n\n/** A file on disk as a web stream, read a chunk at a time as the response is written. */\nfunction fileStream(filePath: string): ReadableStream<Uint8Array> {\n const file = fs.createReadStream(filePath);\n const chunks: AsyncIterator<Buffer> = file[Symbol.asyncIterator]();\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n const next = await chunks.next();\n if (next.done) controller.close();\n else controller.enqueue(next.value);\n },\n cancel() {\n file.destroy();\n }\n });\n}\n","/**\n * The storage controller that reads a backup bucket.\n *\n * A backup destination is its own bucket, named by `BACKUP_DESTINATION`, and\n * the documented backup cron writes to it through a controller it builds from\n * the `S3_*` variables (GCS: application default credentials) — as\n * `rebase db backups list` does. The admin routes have to read it the same way.\n * The app's file storage is not that controller: it is configured for the\n * uploads bucket, it is a local directory in development, and in production\n * without an uploads bucket there is none at all.\n */\nimport { parseEnvBoolean } from \"@rebasepro/types\";\nimport { GCSStorageController } from \"../storage/GCSStorageController\";\nimport { S3StorageController } from \"../storage/S3StorageController\";\nimport type { StorageController } from \"../storage/types\";\nimport { parseBackupDestination, type BackupDestination } from \"./backup-common\";\n\n/** A destination in object storage — `s3://bucket/prefix` or `gs://bucket/prefix`. */\nexport type ObjectBackupDestination = Exclude<BackupDestination, { kind: \"local\" }>;\n\n/** The destination `BACKUP_DESTINATION` names, or `null` when it is unset. */\nexport function backupDestinationFromEnv(env: Record<string, string | undefined>): BackupDestination | null {\n const out = env.BACKUP_DESTINATION?.trim();\n return out ? parseBackupDestination(out) : null;\n}\n\n/** The destination as `BACKUP_DESTINATION` spells it. */\nexport function describeBackupDestination(dest: BackupDestination): string {\n if (dest.kind === \"local\") return dest.path;\n const scheme = dest.kind === \"s3\" ? \"s3\" : \"gs\";\n return `${scheme}://${dest.bucket}${dest.prefix ? `/${dest.prefix}` : \"\"}`;\n}\n\n/**\n * A controller for an object-storage destination's bucket, built from the\n * environment the way the backup cron and `rebase db backups list` build\n * theirs. Throws when an S3 destination has no credentials to read it with.\n */\nexport function backupStorageFromEnv(\n dest: ObjectBackupDestination,\n env: Record<string, string | undefined>\n): StorageController {\n if (dest.kind === \"gcs\") {\n return new GCSStorageController({ type: \"gcs\", bucket: dest.bucket });\n }\n // s3 also covers R2, MinIO and the other S3-compatible stores, through S3_ENDPOINT.\n if (!env.S3_ACCESS_KEY_ID || !env.S3_SECRET_ACCESS_KEY) {\n throw new Error(\n \"An S3 backup destination needs S3_ACCESS_KEY_ID and S3_SECRET_ACCESS_KEY in the environment \" +\n \"— the same S3_* variables the backup cron uses.\"\n );\n }\n return new S3StorageController({\n type: \"s3\",\n bucket: dest.bucket,\n region: env.S3_REGION || \"auto\",\n accessKeyId: env.S3_ACCESS_KEY_ID,\n secretAccessKey: env.S3_SECRET_ACCESS_KEY,\n endpoint: env.S3_ENDPOINT,\n // Unset stays unset, so the controller decides from the endpoint.\n forcePathStyle: parseEnvBoolean(env.S3_FORCE_PATH_STYLE)\n });\n}\n","import { Hono, type Context } from \"hono\";\nimport type { BackupDownloadLink, BackupListing, BackupScheduleStatus } from \"@rebasepro/types\";\nimport type { HonoEnv } from \"../api/types\";\nimport { ApiError, errorHandler } from \"../api/errors\";\nimport { jwtOf, type JwtService } from \"../auth/jwt\";\nimport type { StorageController } from \"../storage/types\";\nimport { BackupDestination, findBackup, listBackupObjects, openBackupStream } from \"./backup-common\";\nimport { backupStorageFromEnv, describeBackupDestination, type ObjectBackupDestination } from \"./backup-storage\";\n\nexport interface BackupRoutesConfig {\n /**\n * Resolve the current backup destination, or `null` when backups are not\n * configured (`BACKUP_DESTINATION` unset). Read lazily so a restart isn't\n * required to pick up config.\n */\n getDestination: () => BackupDestination | null;\n /**\n * The controller that reads an object-storage destination. It has to\n * address the destination's own bucket — never the app's file storage,\n * which is another bucket, a local directory, or nothing. Defaults to\n * {@link backupStorageFromEnv} over `process.env`, which is how the backup\n * cron builds the one it writes with.\n */\n storageFor?: (dest: ObjectBackupDestination) => StorageController;\n /**\n * The scheduled backup job and its last run — see `readBackupSchedule`.\n * Omitted where this process has no cron scheduler; the listing then\n * answers `schedule: null`.\n */\n getSchedule?: () => Promise<BackupScheduleStatus | null>;\n /**\n * True when this process does not run the scheduled jobs (the `api` role\n * of a split deployment). A local destination read here is then this\n * process's disk, not the one the scheduled backup writes to.\n */\n scheduledElsewhere?: boolean;\n}\n\n/** Why a destination could not be read, as the answer says it. */\nfunction unreadable(dest: BackupDestination, err: unknown): ApiError {\n const reason = err instanceof Error ? err.message : String(err);\n return ApiError.serviceUnavailable(`Cannot read the backups at ${describeBackupDestination(dest)}: ${reason}`);\n}\n\n// ─── Download links ──────────────────────────────────────────────────\n\n/**\n * The `purpose` of a download link's token. `verifyAccessToken` refuses\n * any token with a purpose, and the storage, MFA and MCP verifiers each demand\n * their own, so a link is never a session or any other credential, and none of\n * those is a link.\n */\nconst BACKUP_DOWNLOAD_PURPOSE = \"backup-download\";\n/** The token's audience: the one route that redeems it. */\nconst BACKUP_DOWNLOAD_AUDIENCE = \"rebase:admin/backups/download\";\n/** How long a link works. Long enough to start the download, not to pass around. */\nexport const BACKUP_DOWNLOAD_LINK_TTL_SECONDS = 60;\n\n/** What a link grants: one backup, at one destination. */\nfunction linkScope(dest: BackupDestination, key: string): string {\n return `backup:${describeBackupDestination(dest)}:${key}`;\n}\n\n/**\n * Whether `token` is a live link for `key` at `dest`, signed by `jwt` — the\n * backend answering. Never throws: anything else is a no.\n */\nasync function linkGrants(jwt: JwtService, token: string, dest: BackupDestination, key: string): Promise<boolean> {\n if (!jwt.isConfigured()) return false;\n const claims = await jwt.verifyPurposeToken<{ aud?: unknown; scope?: unknown }>(BACKUP_DOWNLOAD_PURPOSE, token)\n .catch(() => null);\n return claims?.aud === BACKUP_DOWNLOAD_AUDIENCE && claims.scope === linkScope(dest, key);\n}\n\n/** The configured destination, or the 400 every backup route answers without one. */\nfunction destinationOf(config: Pick<BackupRoutesConfig, \"getDestination\">): BackupDestination {\n const dest = config.getDestination();\n if (!dest) throw ApiError.badRequest(\"Backups are not configured (set BACKUP_DESTINATION).\");\n return dest;\n}\n\n/** {@link BackupRoutesConfig.storageFor}, with its default, for a destination that has a controller. */\nfunction storageResolver(config: Pick<BackupRoutesConfig, \"storageFor\">): (dest: BackupDestination) => StorageController | undefined {\n const storageFor = config.storageFor ?? ((dest: ObjectBackupDestination) => backupStorageFromEnv(dest, process.env));\n /** The controller for `dest`, or none for a local one. A destination it cannot read is an error, never `[]`. */\n return (dest) => {\n if (dest.kind === \"local\") return undefined;\n try {\n return storageFor(dest);\n } catch (err) {\n throw unreadable(dest, err);\n }\n };\n}\n\n/** One backup's bytes as the response, streamed: a dump is the size of the database. See `openBackupStream`. */\nasync function serveBackup(c: Context<HonoEnv>, dest: BackupDestination, key: string, storage: StorageController | undefined): Promise<Response> {\n const result = await openBackupStream(dest, key, storage);\n if (!result) {\n throw ApiError.notFound(`Backup not found: ${key}`);\n }\n c.header(\"Content-Type\", \"application/octet-stream\");\n c.header(\"Content-Length\", String(result.size));\n c.header(\"Content-Disposition\", `attachment; filename=\"${result.name}\"`);\n // A whole database, and on a link a URL that grants it: nothing in between keeps a copy.\n c.header(\"Cache-Control\", \"no-store\");\n return c.body(result.stream);\n}\n\n/**\n * `GET /download?key=…&token=…`: a download link spent in place of the bearer\n * header, for the one backup it names.\n *\n * Mount it at the backups prefix AHEAD of every gate on the admin prefix: the\n * auth adapter's own admin routers authenticate everything under `/admin`\n * before the Backups gate is reached. A request with no `token` passes\n * through untouched; one with a token is answered here — the backup, or a\n * 401 — and never falls through to the header: a bad link is a bad link.\n *\n * A browser cannot put a header on a navigation, so before links the SDK\n * fetched the dump and held it whole in the tab as a Blob. With a link the\n * browser streams it to disk.\n */\nexport function createBackupLinkRoutes(config: Pick<BackupRoutesConfig, \"getDestination\" | \"storageFor\">): Hono<HonoEnv> {\n const router = new Hono<HonoEnv>();\n router.onError(errorHandler);\n const storageOf = storageResolver(config);\n router.get(\"/download\", async (c, next) => {\n const token = c.req.query(\"token\");\n if (token === undefined) return next();\n const dest = destinationOf(config);\n const key = c.req.query(\"key\") ?? \"\";\n if (!(await linkGrants(jwtOf(c), token, dest, key))) {\n throw ApiError.unauthenticated(\n \"This download link is not valid for this backup, or it has expired. Links last \" +\n `${BACKUP_DOWNLOAD_LINK_TTL_SECONDS} seconds: ask for a new one.`\n );\n }\n return serveBackup(c, dest, key, storageOf(dest));\n });\n return router;\n}\n\n/**\n * Admin REST routes for the Backups panel.\n *\n * Routes (mounted under `/admin/backups`, admin-guarded by the caller):\n * GET / → list available backups, and the scheduled job's last run\n * GET /download → download a backup's bytes (?key=…)\n * POST /download-url → a 60-second link to one backup, `{ key }` → {@link BackupDownloadLink}\n *\n * The link is spent at `GET /download?key=…&token=…`, which\n * {@link createBackupLinkRoutes} answers ahead of the gate.\n */\nexport function createBackupRoutes(config: BackupRoutesConfig): Hono<HonoEnv> {\n const router = new Hono<HonoEnv>();\n router.onError(errorHandler);\n\n const storageOf = storageResolver(config);\n\n router.get(\"/\", async (c) => {\n // Read whether or not a destination is configured: a backup cron with\n // no BACKUP_DESTINATION fails every run, and that is exactly what the\n // panel has to be able to say.\n const schedule = config.getSchedule ? await config.getSchedule() : null;\n const dest = config.getDestination();\n if (!dest) {\n return c.json({ backups: [], destinationKind: \"local\", configured: false, schedule } satisfies BackupListing);\n }\n const backups = await listBackupObjects(dest, storageOf(dest)).catch((err: unknown) => {\n throw unreadable(dest, err);\n });\n // Only where there is a scheduled backup to write elsewhere.\n const localDiskOfThisProcess = dest.kind === \"local\" && config.scheduledElsewhere === true && schedule !== null;\n return c.json({\n backups,\n destinationKind: dest.kind,\n configured: true,\n schedule,\n ...(localDiskOfThisProcess ? { localDiskOfThisProcess } : {})\n } satisfies BackupListing);\n });\n\n router.get(\"/download\", async (c) => {\n const dest = destinationOf(config);\n const key = c.req.query(\"key\");\n if (!key) {\n throw ApiError.badRequest(\"Missing 'key' query parameter.\");\n }\n return serveBackup(c, dest, key, storageOf(dest));\n });\n\n router.post(\"/download-url\", async (c) => {\n const dest = destinationOf(config);\n const body: unknown = await c.req.json().catch(() => null);\n const key = typeof body === \"object\" && body !== null && \"key\" in body ? body.key : undefined;\n if (typeof key !== \"string\" || !key) {\n throw ApiError.badRequest(\"Send the backup's key: { \\\"key\\\": \\\"…\\\" }.\");\n }\n // The download route's own guards, so a link is never minted for a\n // key it would refuse; and the backup is there, so the browser is not\n // sent to a 404 in place of a file.\n if (!(await findBackup(dest, key, storageOf(dest)))) {\n throw ApiError.notFound(`Backup not found: ${key}`);\n }\n const jwt = jwtOf(c);\n if (!jwt.isConfigured()) {\n throw ApiError.serviceUnavailable(\n \"Download links are signed with the JWT secret, and this server has none (auth.jwtSecret). \" +\n \"Download through GET /download with the Authorization header instead.\"\n );\n }\n const token = await jwt.signPurposeToken(\n BACKUP_DOWNLOAD_PURPOSE,\n { aud: BACKUP_DOWNLOAD_AUDIENCE, scope: linkScope(dest, key) },\n BACKUP_DOWNLOAD_LINK_TTL_SECONDS\n );\n const download = new URL(\"download\", c.req.url).pathname;\n return c.json({\n url: `${download}?key=${encodeURIComponent(key)}&token=${encodeURIComponent(token)}`,\n token,\n expiresIn: BACKUP_DOWNLOAD_LINK_TTL_SECONDS\n } satisfies BackupDownloadLink);\n });\n\n return router;\n}\n","/**\n * The scheduled backup job, as the Backups panel reports it.\n *\n * A backup that fails every night has to be visible where the backups are\n * listed. Before this the panel read the destination and nothing else, so a\n * cron that could not run `pg_dump` left an empty list under \"wait for the next\n * scheduled run\" — while each failure sat in `cron_logs`, one panel away.\n */\nimport type {\n BackupRunOutcome,\n BackupScheduleStatus,\n CronJobDefinition,\n CronJobLogEntry,\n CronJobStatus,\n RejectedCronJob\n} from \"@rebasepro/types\";\nimport { isAlreadyExecutingSkip } from \"../cron/cron-scheduler\";\nimport { logger } from \"../utils/logger\";\n\n/**\n * The mark `createBackupCron` (in `@rebasepro/server-postgres`) puts on the\n * definition it returns.\n *\n * A registry symbol, so it is the same value across two installed copies of\n * either package, and neither package has to import the other: `server` must\n * not depend on `server-postgres`. The job cannot be recognised any other way —\n * its id is the cron file's name and its display name is configurable.\n */\nexport const BACKUP_CRON_MARK: unique symbol = Symbol.for(\"rebase.backupCron\");\n\n/** Whether a cron definition is the scheduled backup. */\nexport function isBackupCronDefinition(definition: CronJobDefinition): boolean {\n return Reflect.get(definition, BACKUP_CRON_MARK) === true;\n}\n\n/** The part of the cron scheduler this reads. */\nexport interface BackupScheduleSource {\n jobIdsWhere(predicate: (definition: CronJobDefinition) => boolean): string[];\n rejectedJobsWhere(predicate: (definition: CronJobDefinition) => boolean): RejectedCronJob[];\n fetchJob(id: string): Promise<CronJobStatus | undefined>;\n getJobLogsFromDb(id: string, limit?: number): Promise<CronJobLogEntry[]>;\n}\n\n/**\n * How many recent log entries to look through for the last scheduled run. A\n * skip — a slot that found the previous run still going — is logged as a\n * success with nothing done, and must not stand in for the run it skipped; nor\n * may a run someone started by hand, which is not the schedule's.\n */\nconst RECENT_RUNS = 50;\n\n/** A log entry as the panel reports a run. */\nfunction outcomeOf(entry: CronJobLogEntry): BackupRunOutcome {\n return {\n startedAt: entry.startedAt,\n finishedAt: entry.finishedAt,\n success: entry.success,\n ...(entry.success || !entry.error ? {} : { error: entry.error }),\n manual: entry.manual === true\n };\n}\n\n/**\n * The scheduled backup job and its last run, or `null` when the deployment\n * has none — registered or refused.\n */\nexport async function readBackupSchedule(source: BackupScheduleSource): Promise<BackupScheduleStatus | null> {\n const [jobId] = source.jobIdsWhere(isBackupCronDefinition);\n if (jobId === undefined) {\n // A refused job is not registered, and answered `null` here it read\n // as \"no backup cron\" under a hint to add the file the project has.\n const [refused] = source.rejectedJobsWhere(isBackupCronDefinition);\n return refused\n ? { jobId: refused.id, name: refused.name, schedule: refused.schedule, enabled: false, refused: refused.reason }\n : null;\n }\n\n const job = await source.fetchJob(jobId);\n if (!job) return null;\n // Off because its own definition says so — the documented cron file\n // exports `enabled: false` while BACKUP_SCHEDULE is unset — rather than\n // paused by someone. Resuming that in Cron Jobs would run the placeholder.\n const disabledInCode = !job.enabled &&\n source.jobIdsWhere(definition => isBackupCronDefinition(definition) && definition.enabled === false).includes(jobId);\n\n let recent: CronJobLogEntry[];\n let historyError: string | undefined;\n try {\n recent = await source.getJobLogsFromDb(jobId, RECENT_RUNS);\n } catch (err) {\n // Said, not read as \"has not run yet\". The listing itself still\n // answers: the backups at the destination are worth showing.\n logger.error(`[backups] Could not read the run history of the backup job \"${jobId}\"`, { error: err });\n recent = [];\n historyError = \"The backup job's run history could not be read. The server log has the reason.\";\n }\n const runs = recent.filter(entry => !isAlreadyExecutingSkip(entry));\n // \"Last scheduled backup\" is the schedule's: a later \"Run Now\" that worked\n // hid a failed nightly, and a failed test run read as a failed nightly.\n const lastScheduled = runs.find(entry => entry.manual !== true);\n // A run by hand since then is reported too, as what it is.\n const lastManual = runs.find(entry => entry.manual === true);\n const manualSince = lastManual && (!lastScheduled || lastManual.startedAt > lastScheduled.startedAt)\n ? lastManual\n : undefined;\n\n return {\n jobId,\n name: job.name,\n schedule: job.schedule,\n enabled: job.enabled,\n ...(disabledInCode ? { disabledInCode } : {}),\n ...(job.nextRunAt ? { nextRunAt: job.nextRunAt } : {}),\n ...(historyError ? { historyError } : {}),\n ...(lastScheduled ? { lastRun: outcomeOf(lastScheduled) } : {}),\n ...(manualSince ? { lastManualRun: outcomeOf(manualSince) } : {})\n };\n}\n","/**\n * Storage-generic backup helpers and admin routes for the Backups panel.\n * The `pg_dump`/`pg_restore` machinery lives in `@rebasepro/server-postgres`.\n */\nexport * from \"./backup-common\";\nexport { createBackupRoutes, createBackupLinkRoutes, BACKUP_DOWNLOAD_LINK_TTL_SECONDS } from \"./backup-routes\";\nexport { backupDestinationFromEnv, backupStorageFromEnv } from \"./backup-storage\";\nexport type { ObjectBackupDestination } from \"./backup-storage\";\nexport type { BackupRoutesConfig } from \"./backup-routes\";\nexport { readBackupSchedule, isBackupCronDefinition, BACKUP_CRON_MARK } from \"./backup-schedule\";\nexport type { BackupScheduleSource } from \"./backup-schedule\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,uBAAuB,KAAgC;CACnE,MAAM,KAAK,IAAI,MAAM,yBAAyB;CAC9C,IAAI,IAAI,OAAO;EAAE,MAAM;EAAM,QAAQ,GAAG;EAAI,QAAQ,GAAG,EAAE,CAAC,QAAQ,QAAQ,EAAE;CAAE;CAC9E,MAAM,MAAM,IAAI,MAAM,yBAAyB;CAC/C,IAAI,KAAK,OAAO;EAAE,MAAM;EAAO,QAAQ,IAAI;EAAI,QAAQ,IAAI,EAAE,CAAC,QAAQ,QAAQ,EAAE;CAAE;CAClF,OAAO;EAAE,MAAM;EAAS,MAAM;CAAI;AACtC;;;;;AAMA,SAAgB,qBAAqB,UAA+B;CAEhE,MAAM,SADO,SAAS,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK,SAAA,CACvB,MAAM,0BAA0B;CACnD,IAAI,CAAC,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BAAiB,CAAC,IAAI,WACxB,OAAO,aAAY,eAAc,uBAAuB,UAAU,KAAK,WAAW,YAAY,KAAK,CAAC,CAAC,SAAS,KAAK;CAEvH,IAAI;CACJ,IAAI;CACJ,IAAI;EACA,SAAS,MAAM,OAAO,iBAAiB,OAAO,WAAW;CAC7D,SAAS,KAAK;EAGV,OAAO,MAAM,+DAA+D,MAAM,IAAI,EAAE,OAAO,IAAI,CAAC;EACpG,SAAS,CAAC;EACV,eAAe;CACnB;CACA,MAAM,OAAO,OAAO,QAAO,UAAS,CAAC,uBAAuB,KAAK,CAAC;CAGlE,MAAM,gBAAgB,KAAK,MAAK,UAAS,MAAM,WAAW,IAAI;CAE9D,MAAM,aAAa,KAAK,MAAK,UAAS,MAAM,WAAW,IAAI;CAC3D,MAAM,cAAc,eAAe,CAAC,iBAAiB,WAAW,YAAY,cAAc,aACpF,aACA,KAAA;CAEN,OAAO;EACH;EACA,MAAM,IAAI;EACV,UAAU,IAAI;EACd,SAAS,IAAI;EACb,GAAI,iBAAiB,EAAE,eAAe,IAAI,CAAC;EAC3C,GAAI,IAAI,YAAY,EAAE,WAAW,IAAI,UAAU,IAAI,CAAC;EACpD,GAAI,eAAe,EAAE,aAAa,IAAI,CAAC;EACvC,GAAI,gBAAgB,EAAE,SAAS,UAAU,aAAa,EAAE,IAAI,CAAC;EAC7D,GAAI,cAAc,EAAE,eAAe,UAAU,WAAW,EAAE,IAAI,CAAC;CACnE;AACJ"}
@@ -1,4 +1,4 @@
1
- import { type RebaseBundleManifest, type TableHooks } from "@rebasepro/types";
1
+ import { type RebaseBundleManifest, type RebaseStaticRoute, type TableHooks } from "@rebasepro/types";
2
2
  import type { StorageAuthorize } from "../storage/types.js";
3
3
  /** Thrown when a bundle cannot be read, or claims a contract this runtime cannot honour. */
4
4
  export declare class BundleError extends Error {
@@ -61,6 +61,16 @@ export interface LoadedStaticApp {
61
61
  dir: string;
62
62
  /** Serve `index.html` for unmatched paths under `path`. */
63
63
  spa: boolean;
64
+ /**
65
+ * Paths a custom function answers instead of the build — see
66
+ * {@link RebaseBundleStatic.routes}. Absent when the app declares none.
67
+ */
68
+ routes?: RebaseStaticRoute[];
69
+ /**
70
+ * Origins besides its own that may frame this app — see
71
+ * {@link RebaseBundleStatic.frameAncestors}. Absent when it names none.
72
+ */
73
+ frameAncestors?: string[];
64
74
  }
65
75
  /**
66
76
  * The order static apps are mounted in, which is also the order they are
@@ -175,6 +175,11 @@ export declare const bootEnvExtension: z.ZodObject<{
175
175
  true: "true";
176
176
  false: "false";
177
177
  }>>, z.ZodTransform<boolean, "" | "true" | "false">>;
178
+ REBASE_PUSH: z.ZodPipe<z.ZodDefault<z.ZodEnum<{
179
+ "": "";
180
+ true: "true";
181
+ false: "false";
182
+ }>>, z.ZodTransform<boolean, "" | "true" | "false">>;
178
183
  CORS_ORIGINS: z.ZodOptional<z.ZodString>;
179
184
  REBASE_ROLE: z.ZodPipe<z.ZodDefault<z.ZodEnum<{
180
185
  "": "";
@@ -10,16 +10,26 @@ import type { MiddlewareHandler } from "hono";
10
10
  */
11
11
  export declare function strictTransportSecurity(includeSubDomains: boolean): string;
12
12
  /**
13
- * The Content-Security-Policy every static app is served with.
13
+ * The Content-Security-Policy a static app is served with.
14
14
  *
15
- * Conservative on purpose: it says who may frame the app (this origin only,
16
- * like the `X-Frame-Options: SAMEORIGIN` already sent), forbids plugins, and
17
- * pins `<base>` to this origin. It restricts no script, style, worker, font or
15
+ * Conservative on purpose: it says who may frame the app (this origin, plus
16
+ * the origins the app's `frameAncestors` names), forbids plugins, and pins
17
+ * `<base>` to this origin. It restricts no script, style, worker, font or
18
18
  * connection source, because an app's own build decides those — the CMS admin
19
19
  * runs inline scripts, module workers and third-party sign-in, and a policy
20
20
  * that broke any of them would be one every project had to turn off.
21
+ *
22
+ * Every origin is held to `parseFrameAncestor` before it is written, and a
23
+ * value that is not exactly one origin throws: it is about to become part of
24
+ * a header, where a `;` would start a directive of the caller's choosing.
25
+ *
26
+ * `X-Frame-Options: SAMEORIGIN` is still sent beside it. A browser that reads
27
+ * `frame-ancestors` ignores `X-Frame-Options`, as CSP Level 2 requires, so
28
+ * the origins named here can frame the app.
21
29
  */
22
- export declare const STATIC_APP_CSP = "frame-ancestors 'self'; object-src 'none'; base-uri 'self'";
30
+ export declare function staticAppCsp(frameAncestors?: readonly string[]): string;
31
+ /** {@link staticAppCsp} for an app that names no other origin: `frame-ancestors 'self'`. */
32
+ export declare const STATIC_APP_CSP: string;
23
33
  /**
24
34
  * The `Referrer-Policy` this runtime sends: `strict-origin-when-cross-origin`,
25
35
  * the browsers' own default. A cross-origin request carries the page's origin
@@ -1,3 +1,5 @@
1
+ import type { Env, Hono, MiddlewareHandler } from "hono";
2
+ import { type RebaseStaticRoute } from "@rebasepro/types";
1
3
  import { type StaticAppRequest } from "../serve-spa.js";
2
4
  import { type LoadedStaticApp } from "./bundle.js";
3
5
  /**
@@ -63,3 +65,59 @@ export interface StaticAppMount {
63
65
  * the one resolver instead, and declines whatever another app wins.
64
66
  */
65
67
  export declare function planStaticAppMounts(apps: readonly LoadedStaticApp[]): StaticAppMount[];
68
+ /** A request one of a static app's routes hands to a custom function. */
69
+ export interface StaticRouteMatch {
70
+ /** The app that owns the request, whose route matched. */
71
+ app: LoadedStaticApp;
72
+ route: RebaseStaticRoute;
73
+ /**
74
+ * The function's own URL path: `<api>/functions/<name>`, then whatever a
75
+ * wildcard matched beneath its prefix.
76
+ */
77
+ functionPath: string;
78
+ }
79
+ /**
80
+ * Which static app route answers a request, if any: the one rule, written once.
81
+ *
82
+ * A route applies only where its app is the one that answers the request — by
83
+ * {@link createStaticAppResolver}, the rule every mount asks — so a route on
84
+ * the site at `/` does not reach a request another app owns, on its hostname
85
+ * or under its path. Of that app's routes the most specific wins
86
+ * (`compareStaticRoutes`).
87
+ *
88
+ * Nothing under the API's base path is ever routed. The CLI keeps routes off
89
+ * `/api`, but only the runtime knows `REBASE_BASE_PATH`, and a route over the
90
+ * moved API would hand the function's own URL back to the route that made it.
91
+ *
92
+ * `undefined` when no app declares a route, so a bundle without any installs
93
+ * nothing at all.
94
+ */
95
+ export declare function createStaticRouteResolver(apps: readonly LoadedStaticApp[], apiBasePath: string): ((request: StaticAppRequest) => StaticRouteMatch | undefined) | undefined;
96
+ /**
97
+ * The routes of each static app that sit under the API's base path, and so are
98
+ * never served — the routes' half of {@link staticAppsShadowedByApi}.
99
+ */
100
+ export declare function staticRoutesShadowedByApi(apps: readonly LoadedStaticApp[], apiBasePath: string): Array<{
101
+ app: LoadedStaticApp;
102
+ route: RebaseStaticRoute;
103
+ }>;
104
+ /**
105
+ * Serve static app routes: a request a route matches is dispatched again into
106
+ * `app` as a request for the function's own URL, and its response is the
107
+ * answer.
108
+ *
109
+ * Installed first on the app, before CORS, security headers and metrics, and
110
+ * it answers without calling `next` — so the request passes through every one
111
+ * of them exactly once, as the function's request, and meets the functions
112
+ * group with everything the group expects in front of it: the body limit,
113
+ * CSRF, auth, the scope guard, the rate limit and the function timeout. A
114
+ * forwarder to a functions process answers it as it would answer the
115
+ * function's URL.
116
+ *
117
+ * The request keeps its method, headers (`Host` among them), body, query and
118
+ * the connection it arrived on; only the path changes. The response is the
119
+ * function's, with one header added when it has none: the owning app's
120
+ * Content-Security-Policy, so a routed page can be framed by the origins the
121
+ * app allows and no others.
122
+ */
123
+ export declare function serveStaticAppRoutes<E extends Env>(app: Hono<E>, resolve: (request: StaticAppRequest) => StaticRouteMatch | undefined): MiddlewareHandler<E>;
@@ -2,9 +2,9 @@ import { createRequire as __rebaseCreateRequire } from "module";
2
2
  import __rebaseProcess from "process";
3
3
  globalThis.process ??= __rebaseProcess;
4
4
  __rebaseCreateRequire(import.meta.url);
5
- import { Zt as isBranchAdmin } from "./src-DLIb1O9l.js";
5
+ import { tn as isBranchAdmin } from "./src-CNZB3fuE.js";
6
6
  import { a as logger } from "./logger-SigQ2oZJ.js";
7
- import { t as ApiError } from "./errors-DpTMfX77.js";
7
+ import { t as ApiError } from "./errors-NVbAQU25.js";
8
8
  import { Hono } from "hono";
9
9
  //#region src/api/branch-routes.ts
10
10
  function optionalInteger(value, name) {
@@ -80,4 +80,4 @@ function createBranchRoutes(options) {
80
80
  //#endregion
81
81
  export { createBranchRoutes };
82
82
 
83
- //# sourceMappingURL=branch-routes-0xhHXlGq.js.map
83
+ //# sourceMappingURL=branch-routes-DtNtc0Vh.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"branch-routes-0xhHXlGq.js","names":[],"sources":["../src/api/branch-routes.ts"],"sourcesContent":["import { Hono } from \"hono\";\nimport { isBranchAdmin, type BranchDiffOptions, type BranchMergeOptions, type DatabaseAdmin } from \"@rebasepro/types\";\nimport { ApiError } from \"./errors\";\nimport type { HonoEnv } from \"./types\";\nimport { logger } from \"../utils/logger\";\n\n/**\n * Studio's review of a database branch: what it changed, and merging it.\n *\n * Mounted under `/api/admin/branches` behind the admin gate — `database:write`\n * for both: the diff's sample rows are read as the database owner, outside\n * row-level security, from both databases.\n *\n * Engine-agnostic: the comparison is the driver's (`BranchAdmin.diffBranch`,\n * `mergeBranch`), and a driver without it answers 501. The driver's refusals\n * are `ApiError`s that carry their own status — 404 for a branch that is not\n * there, 409 for a diff that went stale or a merge that would conflict.\n *\n * ```\n * GET /:name/diff?sampleLimit=100&schemas=public,app&maxRowsPerTable=100000\n * POST /:name/merge { expectedFingerprint, onConflict?, skipBlocked?, schemas?, maxRowsPerTable? }\n * ```\n */\nexport interface BranchRoutesOptions {\n /** The default data source's admin capabilities, read per request. */\n getAdmin: () => DatabaseAdmin | undefined;\n}\n\nfunction optionalInteger(value: string | undefined, name: string): number | undefined {\n if (value === undefined || value === \"\") return undefined;\n const parsed = Number(value);\n if (!Number.isInteger(parsed) || parsed < 0) {\n throw ApiError.badRequest(`\\`${name}\\` must be a non-negative integer.`, \"INVALID_INPUT\");\n }\n return parsed;\n}\n\nfunction schemaList(value: unknown): string[] | undefined {\n if (value === undefined || value === null || value === \"\") return undefined;\n const list = typeof value === \"string\" ? value.split(\",\") : value;\n if (!Array.isArray(list) || !list.every((item) => typeof item === \"string\")) {\n throw ApiError.badRequest(\"`schemas` must be a list of schema names.\", \"INVALID_INPUT\");\n }\n const names = list.map((item: string) => item.trim()).filter((item) => item !== \"\");\n return names.length > 0 ? names : undefined;\n}\n\nfunction readMergeRequest(body: unknown): BranchMergeOptions {\n if (typeof body !== \"object\" || body === null || !(\"expectedFingerprint\" in body)\n || typeof body.expectedFingerprint !== \"string\" || body.expectedFingerprint === \"\") {\n throw ApiError.badRequest(\n \"Send `expectedFingerprint`, the `fingerprint` of the diff that was reviewed.\",\n \"INVALID_INPUT\"\n );\n }\n const field = (key: string): unknown => key in body ? Reflect.get(body, key) : undefined;\n const onConflict = field(\"onConflict\");\n if (onConflict !== undefined && onConflict !== \"abort\" && onConflict !== \"branch\" && onConflict !== \"target\") {\n throw ApiError.badRequest(\"`onConflict` must be \\\"abort\\\", \\\"branch\\\" or \\\"target\\\".\", \"INVALID_INPUT\");\n }\n const skipBlocked = field(\"skipBlocked\");\n if (skipBlocked !== undefined && typeof skipBlocked !== \"boolean\") {\n throw ApiError.badRequest(\"`skipBlocked` must be a boolean.\", \"INVALID_INPUT\");\n }\n const maxRows = field(\"maxRowsPerTable\");\n if (maxRows !== undefined && (typeof maxRows !== \"number\" || !Number.isInteger(maxRows) || maxRows < 1)) {\n throw ApiError.badRequest(\"`maxRowsPerTable` must be a positive integer.\", \"INVALID_INPUT\");\n }\n return {\n expectedFingerprint: body.expectedFingerprint,\n onConflict,\n skipBlocked,\n schemas: schemaList(field(\"schemas\")),\n maxRowsPerTable: maxRows\n };\n}\n\nexport function createBranchRoutes(options: BranchRoutesOptions): Hono<HonoEnv> {\n const router = new Hono<HonoEnv>();\n\n const branchAdmin = () => {\n const admin = options.getAdmin();\n if (!isBranchAdmin(admin) || typeof admin.diffBranch !== \"function\" || typeof admin.mergeBranch !== \"function\") {\n throw new ApiError(501, \"BRANCH_DIFF_UNSUPPORTED\",\n \"This data source cannot compare branches. Branching needs a Postgres backend with an admin connection.\");\n }\n return { diffBranch: admin.diffBranch.bind(admin), mergeBranch: admin.mergeBranch.bind(admin) };\n };\n\n router.get(\"/:name/diff\", async (c) => {\n const { diffBranch } = branchAdmin();\n const diffOptions: BranchDiffOptions = {\n sampleLimit: optionalInteger(c.req.query(\"sampleLimit\"), \"sampleLimit\"),\n maxRowsPerTable: optionalInteger(c.req.query(\"maxRowsPerTable\"), \"maxRowsPerTable\"),\n schemas: schemaList(c.req.query(\"schemas\"))\n };\n return c.json(await diffBranch(c.req.param(\"name\"), diffOptions));\n });\n\n router.post(\"/:name/merge\", async (c) => {\n const { mergeBranch } = branchAdmin();\n const name = c.req.param(\"name\");\n const request = readMergeRequest(await c.req.json().catch(() => null));\n const caller = c.get(\"user\");\n const user = typeof caller === \"object\" && caller !== null ? caller : undefined;\n const result = await mergeBranch(name, request);\n // Writes to the main database on someone's say-so: the audit line is\n // the record of whose.\n logger.info(\"[Branch Audit] Branch merged\", {\n branch: name,\n target: result.targetDatabase,\n tables: result.tables.length,\n rows: result.tables.reduce((sum, table) => sum + table.inserted + table.updated + table.deleted, 0),\n onConflict: request.onConflict ?? \"abort\",\n uid: user?.uid ?? \"unknown\",\n ...(c.get(\"apiKey\") ? { apiKey: c.get(\"apiKey\")?.id } : {}),\n requestId: c.get(\"requestId\")\n });\n return c.json(result);\n });\n\n return router;\n}\n"],"mappings":";;;;;;;;;AA4BA,SAAS,gBAAgB,OAA2B,MAAkC;CAClF,IAAI,UAAU,KAAA,KAAa,UAAU,IAAI,OAAO,KAAA;CAChD,MAAM,SAAS,OAAO,KAAK;CAC3B,IAAI,CAAC,OAAO,UAAU,MAAM,KAAK,SAAS,GACtC,MAAM,SAAS,WAAW,KAAK,KAAK,qCAAqC,eAAe;CAE5F,OAAO;AACX;AAEA,SAAS,WAAW,OAAsC;CACtD,IAAI,UAAU,KAAA,KAAa,UAAU,QAAQ,UAAU,IAAI,OAAO,KAAA;CAClE,MAAM,OAAO,OAAO,UAAU,WAAW,MAAM,M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AAC;CAED,OAAO;AACX"}
1
+ {"version":3,"file":"branch-routes-DtNtc0Vh.js","names":[],"sources":["../src/api/branch-routes.ts"],"sourcesContent":["import { Hono } from \"hono\";\nimport { isBranchAdmin, type BranchDiffOptions, type BranchMergeOptions, type DatabaseAdmin } from \"@rebasepro/types\";\nimport { ApiError } from \"./errors\";\nimport type { HonoEnv } from \"./types\";\nimport { logger } from \"../utils/logger\";\n\n/**\n * Studio's review of a database branch: what it changed, and merging it.\n *\n * Mounted under `/api/admin/branches` behind the admin gate — `database:write`\n * for both: the diff's sample rows are read as the database owner, outside\n * row-level security, from both databases.\n *\n * Engine-agnostic: the comparison is the driver's (`BranchAdmin.diffBranch`,\n * `mergeBranch`), and a driver without it answers 501. The driver's refusals\n * are `ApiError`s that carry their own status — 404 for a branch that is not\n * there, 409 for a diff that went stale or a merge that would conflict.\n *\n * ```\n * GET /:name/diff?sampleLimit=100&schemas=public,app&maxRowsPerTable=100000\n * POST /:name/merge { expectedFingerprint, onConflict?, skipBlocked?, schemas?, maxRowsPerTable? }\n * ```\n */\nexport interface BranchRoutesOptions {\n /** The default data source's admin capabilities, read per request. */\n getAdmin: () => DatabaseAdmin | undefined;\n}\n\nfunction optionalInteger(value: string | undefined, name: string): number | undefined {\n if (value === undefined || value === \"\") return undefined;\n const parsed = Number(value);\n if (!Number.isInteger(parsed) || parsed < 0) {\n throw ApiError.badRequest(`\\`${name}\\` must be a non-negative integer.`, \"INVALID_INPUT\");\n }\n return parsed;\n}\n\nfunction schemaList(value: unknown): string[] | undefined {\n if (value === undefined || value === null || value === \"\") return undefined;\n const list = typeof value === \"string\" ? value.split(\",\") : value;\n if (!Array.isArray(list) || !list.every((item) => typeof item === \"string\")) {\n throw ApiError.badRequest(\"`schemas` must be a list of schema names.\", \"INVALID_INPUT\");\n }\n const names = list.map((item: string) => item.trim()).filter((item) => item !== \"\");\n return names.length > 0 ? names : undefined;\n}\n\nfunction readMergeRequest(body: unknown): BranchMergeOptions {\n if (typeof body !== \"object\" || body === null || !(\"expectedFingerprint\" in body)\n || typeof body.expectedFingerprint !== \"string\" || body.expectedFingerprint === \"\") {\n throw ApiError.badRequest(\n \"Send `expectedFingerprint`, the `fingerprint` of the diff that was reviewed.\",\n \"INVALID_INPUT\"\n );\n }\n const field = (key: string): unknown => key in body ? Reflect.get(body, key) : undefined;\n const onConflict = field(\"onConflict\");\n if (onConflict !== undefined && onConflict !== \"abort\" && onConflict !== \"branch\" && onConflict !== \"target\") {\n throw ApiError.badRequest(\"`onConflict` must be \\\"abort\\\", \\\"branch\\\" or \\\"target\\\".\", \"INVALID_INPUT\");\n }\n const skipBlocked = field(\"skipBlocked\");\n if (skipBlocked !== undefined && typeof skipBlocked !== \"boolean\") {\n throw ApiError.badRequest(\"`skipBlocked` must be a boolean.\", \"INVALID_INPUT\");\n }\n const maxRows = field(\"maxRowsPerTable\");\n if (maxRows !== undefined && (typeof maxRows !== \"number\" || !Number.isInteger(maxRows) || maxRows < 1)) {\n throw ApiError.badRequest(\"`maxRowsPerTable` must be a positive integer.\", \"INVALID_INPUT\");\n }\n return {\n expectedFingerprint: body.expectedFingerprint,\n onConflict,\n skipBlocked,\n schemas: schemaList(field(\"schemas\")),\n maxRowsPerTable: maxRows\n };\n}\n\nexport function createBranchRoutes(options: BranchRoutesOptions): Hono<HonoEnv> {\n const router = new Hono<HonoEnv>();\n\n const branchAdmin = () => {\n const admin = options.getAdmin();\n if (!isBranchAdmin(admin) || typeof admin.diffBranch !== \"function\" || typeof admin.mergeBranch !== \"function\") {\n throw new ApiError(501, \"BRANCH_DIFF_UNSUPPORTED\",\n \"This data source cannot compare branches. Branching needs a Postgres backend with an admin connection.\");\n }\n return { diffBranch: admin.diffBranch.bind(admin), mergeBranch: admin.mergeBranch.bind(admin) };\n };\n\n router.get(\"/:name/diff\", async (c) => {\n const { diffBranch } = branchAdmin();\n const diffOptions: BranchDiffOptions = {\n sampleLimit: optionalInteger(c.req.query(\"sampleLimit\"), \"sampleLimit\"),\n maxRowsPerTable: optionalInteger(c.req.query(\"maxRowsPerTable\"), \"maxRowsPerTable\"),\n schemas: schemaList(c.req.query(\"schemas\"))\n };\n return c.json(await diffBranch(c.req.param(\"name\"), diffOptions));\n });\n\n router.post(\"/:name/merge\", async (c) => {\n const { mergeBranch } = branchAdmin();\n const name = c.req.param(\"name\");\n const request = readMergeRequest(await c.req.json().catch(() => null));\n const caller = c.get(\"user\");\n const user = typeof caller === \"object\" && caller !== null ? caller : undefined;\n const result = await mergeBranch(name, request);\n // Writes to the main database on someone's say-so: the audit line is\n // the record of whose.\n logger.info(\"[Branch Audit] Branch merged\", {\n branch: name,\n target: result.targetDatabase,\n tables: result.tables.length,\n rows: result.tables.reduce((sum, table) => sum + table.inserted + table.updated + table.deleted, 0),\n onConflict: request.onConflict ?? \"abort\",\n uid: user?.uid ?? \"unknown\",\n ...(c.get(\"apiKey\") ? { apiKey: c.get(\"apiKey\")?.id } : {}),\n requestId: c.get(\"requestId\")\n });\n return c.json(result);\n });\n\n return router;\n}\n"],"mappings":";;;;;;;;;AA4BA,SAAS,gBAAgB,OAA2B,MAAkC;CAClF,IAAI,UAAU,KAAA,KAAa,UAAU,IAAI,OAAO,KAAA;CAChD,MAAM,SAAS,OAAO,KAAK;CAC3B,IAAI,CAAC,OAAO,UAAU,MAAM,KAAK,SAAS,GACtC,MAAM,SAAS,WAAW,KAAK,KAAK,qCAAqC,eAAe;CAE5F,OAAO;AACX;AAEA,SAAS,WAAW,OAAsC;CACtD,IAAI,UAAU,KAAA,KAAa,UAAU,QAAQ,UAAU,IAAI,OAAO,KAAA;CAClE,MAAM,OAAO,OAAO,UAAU,WAAW,MAAM,MAAM,GAAG,IAAI;CAC5D,IAAI,CAAC,MAAM,QAAQ,IAAI,KAAK,CAAC,KAAK,OAAO,SAAS,OAAO,SAAS,QAAQ,GACtE,MAAM,SAAS,WAAW,6CAA6C,eAAe;CAE1F,MAAM,QAAQ,KAAK,KAAK,SAAiB,KAAK,KAAK,CAAC,CAAC,CAAC,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EACnC,MAAM,cAAiC;GACnC,aAAa,gBAAgB,EAAE,IAAI,MAAM,aAAa,GAAG,aAAa;GACtE,iBAAiB,gBAAgB,EAAE,IAAI,MAAM,iBAAiB,GAAG,iBAAiB;GAClF,SAAS,WAAW,EAAE,IAAI,MAAM,SAAS,CAAC;EAC9C;EACA,OAAO,EAAE,KAAK,MAAM,WAAW,EAAE,IAAI,MAAM,MAAM,GAAG,WAAW,CAAC;CACpE,CAAC;CAED,OAAO,KAAK,gBAAgB,OAAO,MAAM;EACrC,MAAM,EAAE,gBAAgB,YAAY;EACpC,MAAM,OAAO,EAAE,IAAI,MAAM,MAAM;EAC/B,MAAM,UAAU,iBAAiB,MAAM,EAAE,IAAI,KAAK,CAAC,CAAC,YAAY,IAAI,CAAC;EACrE,MAAM,SAAS,EAAE,IAAI,MAAM;EAC3B,MAAM,OAAO,OAAO,WAAW,YAAY,WAAW,OAAO,SAAS,KAAA;EACtE,MAAM,SAAS,MAAM,YAAY,MAAM,OAAO;EAG9C,OAAO,KAAK,gCAAgC;GACxC,QAAQ;GACR,QAAQ,OAAO;GACf,QAAQ,OAAO,OAAO;GACtB,MAAM,OAAO,OAAO,QAAQ,KAAK,UAAU,MAAM,MAAM,WAAW,MAAM,UAAU,MAAM,SAAS,CAAC;GAClG,YAAY,QAAQ,cAAc;GAClC,KAAK,MAAM,OAAO;GAClB,GAAI,EAAE,IAAI,QAAQ,IAAI,EAAE,QAAQ,EAAE,IAAI,QAAQ,CAAC,EAAE,GAAG,IAAI,CAAC;GACzD,WAAW,EAAE,IAAI,WAAW;EAChC,CAAC;EACD,OAAO,EAAE,KAAK,MAAM;CACxB,CAAC;CAED,OAAO;AACX"}
@@ -2,9 +2,9 @@ import { createRequire as __rebaseCreateRequire } from "module";
2
2
  import __rebaseProcess from "process";
3
3
  globalThis.process ??= __rebaseProcess;
4
4
  __rebaseCreateRequire(import.meta.url);
5
- import { Pn as __exportAll, Q as SCHEMA_VERSION_HEADER } from "./src-DLIb1O9l.js";
5
+ import { Q as SCHEMA_VERSION_HEADER, Rn as __exportAll } from "./src-CNZB3fuE.js";
6
6
  import { a as logger } from "./logger-SigQ2oZJ.js";
7
- import { t as ADMIN_SCHEMA_VIEW } from "./schema-tables-D4MEBZFi.js";
7
+ import { t as ADMIN_SCHEMA_VIEW } from "./schema-tables-DKFg6vMV.js";
8
8
  import { Hono } from "hono";
9
9
  //#region src/api/contract-routes.ts
10
10
  var contract_routes_exports = /* @__PURE__ */ __exportAll({ createContractRoutes: () => createContractRoutes });
@@ -58,4 +58,4 @@ function createContractRoutes(config) {
58
58
  //#endregion
59
59
  export { createContractRoutes as n, contract_routes_exports as t };
60
60
 
61
- //# sourceMappingURL=contract-routes-WwMWHWS9.js.map
61
+ //# sourceMappingURL=contract-routes-CZTlAP7p.js.map