@rebasepro/server 0.22.0 → 0.24.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 (211) hide show
  1. package/README.md +1 -1
  2. package/bin/rebase-server.js +4 -2
  3. package/dist/{GCSStorageController-CLIJXwGS.js → GCSStorageController-BSiP1c-f.js} +57 -29
  4. package/dist/GCSStorageController-BSiP1c-f.js.map +1 -0
  5. package/dist/{S3StorageController-Dcuf8lMA.js → S3StorageController-CAwFRgjV.js} +19 -7
  6. package/dist/S3StorageController-CAwFRgjV.js.map +1 -0
  7. package/dist/api/ast-schema-editor.d.ts +127 -1
  8. package/dist/api/errors.d.ts +9 -0
  9. package/dist/api/live-schema-routes.d.ts +52 -8
  10. package/dist/api/logs-routes.d.ts +39 -1
  11. package/dist/api/openapi-generator.d.ts +17 -0
  12. package/dist/api/rest/api-generator.d.ts +158 -42
  13. package/dist/api/rest/auth-collection-writes.d.ts +85 -0
  14. package/dist/api/rest/field-access-query.d.ts +6 -2
  15. package/dist/api/rest/idempotency.d.ts +7 -1
  16. package/dist/api/rest/nested-write-access.d.ts +46 -0
  17. package/dist/api/rest/write-validation.d.ts +34 -2
  18. package/dist/api/types.d.ts +17 -1
  19. package/dist/{ast-schema-editor-CslO8Oje.js → ast-schema-editor-CWqS_sLJ.js} +411 -13
  20. package/dist/ast-schema-editor-CWqS_sLJ.js.map +1 -0
  21. package/dist/auth/access.d.ts +105 -0
  22. package/dist/auth/adapter-middleware.d.ts +2 -1
  23. package/dist/auth/address-ownership.d.ts +68 -0
  24. package/dist/auth/admin-roles-route.d.ts +4 -2
  25. package/dist/auth/admin-roles.d.ts +17 -20
  26. package/dist/auth/admin-user-ops.d.ts +35 -2
  27. package/dist/auth/admin-users-route.d.ts +1 -0
  28. package/dist/auth/api-keys/api-key-middleware.d.ts +56 -55
  29. package/dist/auth/api-keys/api-key-routes.d.ts +41 -11
  30. package/dist/auth/api-keys/api-key-store.d.ts +31 -8
  31. package/dist/auth/api-keys/api-key-types.d.ts +14 -16
  32. package/dist/auth/api-keys/http-operation.d.ts +19 -0
  33. package/dist/auth/api-keys/index.d.ts +11 -11
  34. package/dist/auth/api-keys/key-grant.d.ts +41 -0
  35. package/dist/auth/api-keys/legacy-permissions.d.ts +33 -0
  36. package/dist/auth/auth-hooks.d.ts +50 -7
  37. package/dist/auth/builtin-auth-adapter.d.ts +8 -0
  38. package/dist/auth/captcha.d.ts +5 -0
  39. package/dist/auth/cookie-utils.d.ts +7 -0
  40. package/dist/auth/deliverable-address.d.ts +6 -0
  41. package/dist/auth/email-change-routes.d.ts +41 -0
  42. package/dist/auth/expired-token-sweep.d.ts +67 -0
  43. package/dist/auth/impersonation.d.ts +110 -0
  44. package/dist/auth/index.d.ts +4 -2
  45. package/dist/auth/interfaces.d.ts +146 -65
  46. package/dist/auth/jwt.d.ts +66 -3
  47. package/dist/auth/magic-link-routes.d.ts +2 -6
  48. package/dist/auth/mfa-routes.d.ts +2 -9
  49. package/dist/auth/middleware.d.ts +17 -5
  50. package/dist/auth/oauth-signin-policy.d.ts +25 -8
  51. package/dist/auth/otp-routes.d.ts +2 -6
  52. package/dist/auth/passwordless-signup.d.ts +27 -0
  53. package/dist/auth/platform-token.d.ts +122 -0
  54. package/dist/auth/rate-limiter.d.ts +72 -1
  55. package/dist/auth/routes.d.ts +45 -0
  56. package/dist/auth/scope-routes.d.ts +22 -0
  57. package/dist/auth/session-routes.d.ts +18 -6
  58. package/dist/auth/token-revocation.d.ts +53 -1
  59. package/dist/auth/verify-credential.d.ts +28 -0
  60. package/dist/{auth-CCDpk2rn.js → auth-DMLngxn_.js} +2712 -711
  61. package/dist/auth-DMLngxn_.js.map +1 -0
  62. package/dist/backend-DTAOsLQc.js +30 -0
  63. package/dist/backend-DTAOsLQc.js.map +1 -0
  64. package/dist/backup/backup-common.d.ts +29 -0
  65. package/dist/backup/backup-routes.d.ts +24 -4
  66. package/dist/backup/backup-schedule.d.ts +33 -0
  67. package/dist/backup/backup-storage.d.ts +14 -0
  68. package/dist/backup/index.d.ts +2 -0
  69. package/dist/backup-CN0s50D2.js +444 -0
  70. package/dist/backup-CN0s50D2.js.map +1 -0
  71. package/dist/boot/bundle.d.ts +19 -0
  72. package/dist/boot/driver.d.ts +10 -0
  73. package/dist/boot/env.d.ts +51 -6
  74. package/dist/boot/fetch-bundle.d.ts +18 -1
  75. package/dist/boot/rls-audit-option.d.ts +26 -0
  76. package/dist/boot/security-headers.d.ts +26 -0
  77. package/dist/boot/sources.d.ts +1 -0
  78. package/dist/boot/static-routing.d.ts +56 -0
  79. package/dist/collection_patch-BRu-BvDv.js +472 -0
  80. package/dist/collection_patch-BRu-BvDv.js.map +1 -0
  81. package/dist/{contract-routes-eLxV0le1.js → contract-routes-fz8i4pxs.js} +17 -4
  82. package/dist/contract-routes-fz8i4pxs.js.map +1 -0
  83. package/dist/cron/cron-routes.d.ts +7 -2
  84. package/dist/cron/cron-scheduler.d.ts +146 -21
  85. package/dist/cron/cron-store.d.ts +76 -8
  86. package/dist/cron/index.d.ts +1 -1
  87. package/dist/{cron-loader-CQjvjpEw.js → cron-loader-CwaANlOG.js} +4 -4
  88. package/dist/cron-loader-CwaANlOG.js.map +1 -0
  89. package/dist/cron-routes-Bc-SB0Se.js +96 -0
  90. package/dist/cron-routes-Bc-SB0Se.js.map +1 -0
  91. package/dist/{cron-scheduler-COPQxlEq.js → cron-scheduler-CYQgco86.js} +427 -83
  92. package/dist/cron-scheduler-CYQgco86.js.map +1 -0
  93. package/dist/{cron-store-BYGZFNWk.js → cron-store-D2Q9-Aco.js} +139 -23
  94. package/dist/cron-store-D2Q9-Aco.js.map +1 -0
  95. package/dist/{ddl-bootstrap-CfNvxMuK.js → ddl-bootstrap-BaqMSa4Y.js} +3 -26
  96. package/dist/ddl-bootstrap-BaqMSa4Y.js.map +1 -0
  97. package/dist/email/index.d.ts +2 -2
  98. package/dist/email/link-base.d.ts +5 -4
  99. package/dist/email/smtp-email-service.d.ts +13 -1
  100. package/dist/email/templates.d.ts +31 -0
  101. package/dist/email/types.d.ts +29 -2
  102. package/dist/env.d.ts +25 -7
  103. package/dist/{errors-DWsX4yTd.js → errors-D6_y86c5.js} +102 -8
  104. package/dist/errors-D6_y86c5.js.map +1 -0
  105. package/dist/{function-loader-xnbDAPfa.js → function-loader-D7o5Epjj.js} +2 -2
  106. package/dist/{function-loader-xnbDAPfa.js.map → function-loader-D7o5Epjj.js.map} +1 -1
  107. package/dist/{function-routes-Chet4-lB.js → function-routes-CaNG4waN.js} +24 -12
  108. package/dist/function-routes-CaNG4waN.js.map +1 -0
  109. package/dist/functions/context.d.ts +17 -6
  110. package/dist/functions/guards.d.ts +22 -5
  111. package/dist/functions/index.d.ts +2 -2
  112. package/dist/functions/index.js +90 -36
  113. package/dist/functions/index.js.map +1 -1
  114. package/dist/{history-recorder-BQmB0P_j.js → history-recorder-Nr8zLvoU.js} +9 -7
  115. package/dist/history-recorder-Nr8zLvoU.js.map +1 -0
  116. package/dist/{history-store-CetkrBBD.js → history-store-rcAm_xFR.js} +2 -2
  117. package/dist/{history-store-CetkrBBD.js.map → history-store-rcAm_xFR.js.map} +1 -1
  118. package/dist/index.d.ts +14 -4
  119. package/dist/index.es.js +5733 -1551
  120. package/dist/index.es.js.map +1 -1
  121. package/dist/init/docs.d.ts +5 -2
  122. package/dist/init/health.d.ts +17 -2
  123. package/dist/init/shutdown.d.ts +18 -3
  124. package/dist/init.d.ts +54 -0
  125. package/dist/jobs/index.d.ts +2 -2
  126. package/dist/jobs/job-queue.d.ts +23 -2
  127. package/dist/jobs/job-store.d.ts +37 -5
  128. package/dist/jobs/types.d.ts +8 -6
  129. package/dist/{jobs-Bjr8DZAi.js → jobs-DqYNfquG.js} +306 -167
  130. package/dist/jobs-DqYNfquG.js.map +1 -0
  131. package/dist/{jwt-C4OW-DNq.js → jwt-R6bSPMjk.js} +114 -38
  132. package/dist/{jwt-C4OW-DNq.js.map → jwt-R6bSPMjk.js.map} +1 -1
  133. package/dist/{keys-Qfc4XieN.js → keys-GAVZqbqx.js} +18 -17
  134. package/dist/{keys-Qfc4XieN.js.map → keys-GAVZqbqx.js.map} +1 -1
  135. package/dist/{logger-DO2PZc4i.js → logger-D-S-hO5e.js} +26 -3
  136. package/dist/logger-D-S-hO5e.js.map +1 -0
  137. package/dist/{logs-routes-3EEzPjhl.js → logs-routes-DAdv37GI.js} +54 -11
  138. package/dist/logs-routes-DAdv37GI.js.map +1 -0
  139. package/dist/mcp/consent-page.d.ts +1 -1
  140. package/dist/mcp/mcp-routes.d.ts +45 -2
  141. package/dist/mcp/mcp-tools.d.ts +22 -10
  142. package/dist/mcp/oauth-metadata.d.ts +21 -16
  143. package/dist/mcp/oauth-routes.d.ts +34 -1
  144. package/dist/mcp/oauth-store.d.ts +29 -13
  145. package/dist/metrics/history-recorder.d.ts +1 -1
  146. package/dist/{openapi-generator-D8uFz-LW.js → openapi-generator-DAq_XVDu.js} +135 -22
  147. package/dist/openapi-generator-DAq_XVDu.js.map +1 -0
  148. package/dist/{proxy-Czngl3p9.js → proxy-qRlqeUmO.js} +2 -2
  149. package/dist/{proxy-Czngl3p9.js.map → proxy-qRlqeUmO.js.map} +1 -1
  150. package/dist/{query-parser-BleZmY18.js → query-parser-BgiKJKvc.js} +41 -82
  151. package/dist/query-parser-BgiKJKvc.js.map +1 -0
  152. package/dist/{request-timeout-C_4C2BeR.js → request-timeout-DgH7j8qO.js} +3 -3
  153. package/dist/{request-timeout-C_4C2BeR.js.map → request-timeout-DgH7j8qO.js.map} +1 -1
  154. package/dist/rls-audit/index.d.ts +4 -0
  155. package/dist/schema-edit/apply-schema-change.d.ts +63 -3
  156. package/dist/schema-edit/project-root.d.ts +3 -2
  157. package/dist/schema-edit/remote-source.d.ts +9 -4
  158. package/dist/{schema-editor-routes-DdLihzp0.js → schema-editor-routes-oIyuWl3L.js} +12 -7
  159. package/dist/schema-editor-routes-oIyuWl3L.js.map +1 -0
  160. package/dist/serve-spa.d.ts +58 -0
  161. package/dist/services/routed-realtime-service.d.ts +11 -0
  162. package/dist/soft-delete-params-BWPilMPF.js +59 -0
  163. package/dist/soft-delete-params-BWPilMPF.js.map +1 -0
  164. package/dist/{src-Br6ARbs6.js → src-CatHFUym.js} +439 -45
  165. package/dist/src-CatHFUym.js.map +1 -0
  166. package/dist/{src-1vL-I1Po.js → src-I3aG1PcY.js} +371 -81
  167. package/dist/src-I3aG1PcY.js.map +1 -0
  168. package/dist/storage/GCSStorageController.d.ts +13 -1
  169. package/dist/storage/LocalStorageController.d.ts +2 -0
  170. package/dist/storage/S3StorageController.d.ts +2 -0
  171. package/dist/storage/index.d.ts +2 -2
  172. package/dist/storage/keys.d.ts +12 -0
  173. package/dist/storage/property-limits.d.ts +41 -6
  174. package/dist/storage/rendition-cache.d.ts +11 -1
  175. package/dist/storage/request-keys.d.ts +82 -0
  176. package/dist/storage/requested-object.d.ts +74 -0
  177. package/dist/storage/routes.d.ts +36 -18
  178. package/dist/storage/tus-handler.d.ts +30 -5
  179. package/dist/storage/types.d.ts +36 -1
  180. package/dist/types-BfKcm9do.js.map +1 -1
  181. package/dist/utils/logger.d.ts +12 -0
  182. package/package.json +9 -9
  183. package/dist/GCSStorageController-CLIJXwGS.js.map +0 -1
  184. package/dist/S3StorageController-Dcuf8lMA.js.map +0 -1
  185. package/dist/admin-roles-vYdp_Pil.js +0 -36
  186. package/dist/admin-roles-vYdp_Pil.js.map +0 -1
  187. package/dist/admin_block-DxKLmdiv.js +0 -206
  188. package/dist/admin_block-DxKLmdiv.js.map +0 -1
  189. package/dist/ast-schema-editor-CslO8Oje.js.map +0 -1
  190. package/dist/auth/api-keys/api-key-permission-guard.d.ts +0 -65
  191. package/dist/auth-CCDpk2rn.js.map +0 -1
  192. package/dist/backup-DzI9jLwc.js +0 -192
  193. package/dist/backup-DzI9jLwc.js.map +0 -1
  194. package/dist/contract-routes-eLxV0le1.js.map +0 -1
  195. package/dist/cron-loader-CQjvjpEw.js.map +0 -1
  196. package/dist/cron-routes-B7CRGfiq.js +0 -72
  197. package/dist/cron-routes-B7CRGfiq.js.map +0 -1
  198. package/dist/cron-scheduler-COPQxlEq.js.map +0 -1
  199. package/dist/cron-store-BYGZFNWk.js.map +0 -1
  200. package/dist/ddl-bootstrap-CfNvxMuK.js.map +0 -1
  201. package/dist/errors-DWsX4yTd.js.map +0 -1
  202. package/dist/function-routes-Chet4-lB.js.map +0 -1
  203. package/dist/history-recorder-BQmB0P_j.js.map +0 -1
  204. package/dist/jobs-Bjr8DZAi.js.map +0 -1
  205. package/dist/logger-DO2PZc4i.js.map +0 -1
  206. package/dist/logs-routes-3EEzPjhl.js.map +0 -1
  207. package/dist/openapi-generator-D8uFz-LW.js.map +0 -1
  208. package/dist/query-parser-BleZmY18.js.map +0 -1
  209. package/dist/schema-editor-routes-DdLihzp0.js.map +0 -1
  210. package/dist/src-1vL-I1Po.js.map +0 -1
  211. package/dist/src-Br6ARbs6.js.map +0 -1
@@ -0,0 +1,444 @@
1
+ import { createRequire as __rebaseCreateRequire } from "module";
2
+ import __rebaseProcess from "process";
3
+ globalThis.process ??= __rebaseProcess;
4
+ __rebaseCreateRequire(import.meta.url);
5
+ import { n as __exportAll } from "./rolldown-runtime-dW7B1o5h.js";
6
+ import "./src-CatHFUym.js";
7
+ import { a as parseEnvBoolean, r as isAlreadyExecutingSkip } from "./cron-scheduler-CYQgco86.js";
8
+ import { r as logger } from "./logger-D-S-hO5e.js";
9
+ import { r as errorHandler, t as ApiError } from "./errors-D6_y86c5.js";
10
+ import { t as S3StorageController } from "./S3StorageController-CAwFRgjV.js";
11
+ import { t as GCSStorageController } from "./GCSStorageController-BSiP1c-f.js";
12
+ import fs from "fs";
13
+ import path from "path";
14
+ import { Hono } from "hono";
15
+ //#region src/backup/backup-common.ts
16
+ /**
17
+ * Storage-generic backup helpers used by the admin backup routes.
18
+ *
19
+ * These live in server (which owns {@link StorageController}) so the
20
+ * admin API can list backups without depending on the Postgres driver —
21
+ * `server` must not import from `server-postgres`. The `pg_dump`-side
22
+ * copies of the tiny pure parsers live in `@rebasepro/server-postgres`;
23
+ * keep the two in sync if the naming scheme ever changes.
24
+ */
25
+ /** Parse a destination string (`s3://…`, `gs://…`, or a local path). */
26
+ function parseBackupDestination(out) {
27
+ const s3 = out.match(/^s3:\/\/([^/]+)\/?(.*)$/);
28
+ if (s3) return {
29
+ kind: "s3",
30
+ bucket: s3[1],
31
+ prefix: s3[2].replace(/\/+$/, "")
32
+ };
33
+ const gcs = out.match(/^gs:\/\/([^/]+)\/?(.*)$/);
34
+ if (gcs) return {
35
+ kind: "gcs",
36
+ bucket: gcs[1],
37
+ prefix: gcs[2].replace(/\/+$/, "")
38
+ };
39
+ return {
40
+ kind: "local",
41
+ path: out
42
+ };
43
+ }
44
+ /**
45
+ * Recover the UTC creation time encoded in a `rebase-<db>-<ts>.dump` name.
46
+ * Returns `null` for names that don't match, so foreign objects are ignored.
47
+ */
48
+ function parseBackupTimestamp(fileName) {
49
+ const match = (fileName.split("/").pop() ?? fileName).match(/-(\d{8})T(\d{6})Z\.dump$/);
50
+ if (!match) return null;
51
+ const [, ymd, hms] = match;
52
+ const iso = `${ymd.slice(0, 4)}-${ymd.slice(4, 6)}-${ymd.slice(6, 8)}T${hms.slice(0, 2)}:${hms.slice(2, 4)}:${hms.slice(4, 6)}Z`;
53
+ const date = new Date(iso);
54
+ return Number.isNaN(date.getTime()) ? null : date;
55
+ }
56
+ /**
57
+ * A backup is two files: the `.dump`, and beside it a `.globals.sql` holding
58
+ * the cluster roles the dump's GRANTs and RLS policies name. Without that
59
+ * sidecar a restore into a fresh cluster stops at the first GRANT to a role
60
+ * that does not exist there. The CLI uploads, restores and prunes the two as
61
+ * a pair. This listing used to know only the `.dump`, so a backup downloaded
62
+ * from Studio arrived without its roles.
63
+ *
64
+ * The suffix mirrors `globalsFileForDump` in `@rebasepro/server-postgres`.
65
+ */
66
+ var DUMP_SUFFIX = ".dump";
67
+ var GLOBALS_SUFFIX = ".globals.sql";
68
+ function globalsKeyFor(dumpKey) {
69
+ return dumpKey.slice(0, -5) + GLOBALS_SUFFIX;
70
+ }
71
+ /** The only files the download route will serve. */
72
+ function isBackupFile(key) {
73
+ return key.endsWith(DUMP_SUFFIX) || key.endsWith(GLOBALS_SUFFIX);
74
+ }
75
+ /**
76
+ * How many pages of an object-storage listing to read before giving up — at
77
+ * the providers' 1,000 keys a page, 100,000 objects, or 50,000 backups.
78
+ */
79
+ var MAX_LIST_PAGES = 100;
80
+ /**
81
+ * Every key under a prefix, across pages.
82
+ *
83
+ * S3 and GCS answer a listing a page at a time, in ascending key order, and a
84
+ * backup's key is `rebase-<db>-<UTC timestamp>`. Reading one page therefore
85
+ * returned the OLDEST thousand objects: with retention unset and an hourly
86
+ * schedule, the newest backup the panel and `rebase db backups list` showed
87
+ * stopped advancing after about three weeks, which reads as "backups stopped".
88
+ */
89
+ async function listAllObjectKeys(storage, prefix, bucket) {
90
+ const keys = [];
91
+ let pageToken;
92
+ for (let page = 0; page < MAX_LIST_PAGES; page++) {
93
+ const result = await storage.listObjects(prefix, {
94
+ bucket,
95
+ maxResults: 1e3,
96
+ pageToken
97
+ });
98
+ for (const item of result.items) keys.push(item.fullPath);
99
+ pageToken = result.nextPageToken;
100
+ if (!pageToken) return keys;
101
+ }
102
+ logger.warn(`[backups] Stopped listing ${bucket}/${prefix} after ${MAX_LIST_PAGES} pages (${keys.length} objects). Set BACKUP_RETENTION_DAYS so old backups are pruned, or give the backups a prefix of their own.`);
103
+ return keys;
104
+ }
105
+ /**
106
+ * Whether an object key is one the backup routes may serve: a backup file, at
107
+ * the destination's prefix and nowhere else.
108
+ *
109
+ * The local branch has always been held to the backup directory; this branch
110
+ * checked only the suffix, so any `.dump` in the bucket — `uploads/x.dump`, a
111
+ * neighbouring `nightlyish/` prefix — was readable by naming it. A key is taken
112
+ * as written, so a scheme (`s3://other-bucket/…`, which S3StorageController
113
+ * would follow) or a `.`/`..`/empty segment (which a filesystem-backed or
114
+ * S3-compatible store may resolve) is refused rather than interpreted.
115
+ */
116
+ function isObjectBackupKey(dest, key) {
117
+ if (!isBackupFile(key) || /^[a-z][a-z0-9+.-]*:\/\//i.test(key)) return false;
118
+ if (key.split("/").some((segment) => segment === "" || segment === "." || segment === "..")) return false;
119
+ return dest.prefix === "" || key.startsWith(`${dest.prefix}/`);
120
+ }
121
+ /**
122
+ * List the backups at a destination as {@link BackupInfo}, newest first.
123
+ * One entry per `.dump`, with its `.globals.sql` sidecar attached as
124
+ * `globalsKey` when there is one.
125
+ */
126
+ async function listBackupObjects(dest, storage) {
127
+ if (dest.kind === "local") {
128
+ if (!fs.existsSync(dest.path)) return [];
129
+ const dir = fs.statSync(dest.path).isDirectory() ? dest.path : path.dirname(dest.path);
130
+ if (!fs.existsSync(dir)) return [];
131
+ const files = fs.readdirSync(dir);
132
+ const present = new Set(files);
133
+ return files.filter((f) => f.endsWith(DUMP_SUFFIX)).map((f) => {
134
+ const full = path.join(dir, f);
135
+ const st = fs.statSync(full);
136
+ const createdAt = parseBackupTimestamp(f) ?? st.mtime;
137
+ const globals = globalsKeyFor(f);
138
+ return {
139
+ key: full,
140
+ name: f,
141
+ sizeBytes: st.size,
142
+ createdAt: createdAt.toISOString(),
143
+ destinationKind: "local",
144
+ ...present.has(globals) ? { globalsKey: path.join(dir, globals) } : {}
145
+ };
146
+ }).sort(byNewest);
147
+ }
148
+ if (!storage) throw new Error(noControllerFor(dest));
149
+ const keys = await listAllObjectKeys(storage, dest.prefix ? `${dest.prefix}/` : "", dest.bucket);
150
+ const present = new Set(keys);
151
+ return keys.filter((key) => key.endsWith(DUMP_SUFFIX)).map((key) => {
152
+ const createdAt = parseBackupTimestamp(key);
153
+ const globals = globalsKeyFor(key);
154
+ return {
155
+ key,
156
+ name: key.split("/").pop() || key,
157
+ createdAt: createdAt ? createdAt.toISOString() : void 0,
158
+ destinationKind: dest.kind,
159
+ ...present.has(globals) ? { globalsKey: globals } : {}
160
+ };
161
+ }).sort(byNewest);
162
+ }
163
+ function noControllerFor(dest) {
164
+ return `No storage controller for ${dest.kind === "s3" ? "s3" : "gs"}://${dest.bucket}${dest.prefix ? `/${dest.prefix}` : ""}, so its backups cannot be read.`;
165
+ }
166
+ function byNewest(a, b) {
167
+ const ta = a.createdAt ? Date.parse(a.createdAt) : 0;
168
+ return (b.createdAt ? Date.parse(b.createdAt) : 0) - ta;
169
+ }
170
+ /**
171
+ * The absolute path of a local backup file, or `null` for anything the download
172
+ * route must not serve: a path outside the backup directory, a file that is not
173
+ * a backup, or one that does not exist.
174
+ */
175
+ function resolveLocalBackupFile(dest, key) {
176
+ const dir = (fs.existsSync(dest.path) ? fs.statSync(dest.path) : null)?.isDirectory() ? dest.path : path.dirname(dest.path);
177
+ const resolvedDir = path.resolve(dir);
178
+ const resolved = path.resolve(key);
179
+ if (!resolved.startsWith(resolvedDir + path.sep) || !isBackupFile(resolved)) return null;
180
+ return fs.existsSync(resolved) ? resolved : null;
181
+ }
182
+ /** Read a single backup's bytes. Guards against path traversal for local. */
183
+ async function readBackupBytes(dest, key, storage) {
184
+ if (dest.kind === "local") {
185
+ const resolved = resolveLocalBackupFile(dest, key);
186
+ if (!resolved) return null;
187
+ return {
188
+ bytes: new Uint8Array(fs.readFileSync(resolved)),
189
+ name: path.basename(resolved)
190
+ };
191
+ }
192
+ if (!storage) throw new Error(noControllerFor(dest));
193
+ if (!isObjectBackupKey(dest, key)) return null;
194
+ const file = await storage.getObject(key, dest.bucket);
195
+ if (!file) return null;
196
+ return {
197
+ bytes: new Uint8Array(await file.arrayBuffer()),
198
+ name: key.split("/").pop() || key
199
+ };
200
+ }
201
+ /**
202
+ * A single backup, opened for streaming, with its size. Same guards as
203
+ * {@link readBackupBytes}.
204
+ *
205
+ * What the download route serves. A dump is the size of the database, and
206
+ * reading it whole put all of it on the API process's heap — twice for a local
207
+ * destination (`readFileSync`, then a copy) and on top of the controller's own
208
+ * buffer for object storage — and a file over 2 GiB never downloaded at all:
209
+ * `readFileSync` throws `ERR_FS_FILE_TOO_LARGE` there.
210
+ *
211
+ * A local file is read from disk as the response is written. Object storage
212
+ * still arrives through {@link StorageController.getObject}, which is a
213
+ * buffered `File` by contract; streaming that avoids the second copy.
214
+ */
215
+ async function openBackupStream(dest, key, storage) {
216
+ if (dest.kind === "local") {
217
+ const resolved = resolveLocalBackupFile(dest, key);
218
+ if (!resolved) return null;
219
+ const { size } = await fs.promises.stat(resolved);
220
+ return {
221
+ stream: fileStream(resolved),
222
+ size,
223
+ name: path.basename(resolved)
224
+ };
225
+ }
226
+ if (!storage) throw new Error(noControllerFor(dest));
227
+ if (!isObjectBackupKey(dest, key)) return null;
228
+ const file = await storage.getObject(key, dest.bucket);
229
+ if (!file) return null;
230
+ return {
231
+ stream: file.stream(),
232
+ size: file.size,
233
+ name: key.split("/").pop() || key
234
+ };
235
+ }
236
+ /** A file on disk as a web stream, read a chunk at a time as the response is written. */
237
+ function fileStream(filePath) {
238
+ const file = fs.createReadStream(filePath);
239
+ const chunks = file[Symbol.asyncIterator]();
240
+ return new ReadableStream({
241
+ async pull(controller) {
242
+ const next = await chunks.next();
243
+ if (next.done) controller.close();
244
+ else controller.enqueue(next.value);
245
+ },
246
+ cancel() {
247
+ file.destroy();
248
+ }
249
+ });
250
+ }
251
+ //#endregion
252
+ //#region src/backup/backup-storage.ts
253
+ /**
254
+ * The storage controller that reads a backup bucket.
255
+ *
256
+ * A backup destination is its own bucket, named by `BACKUP_DESTINATION`, and
257
+ * the documented backup cron writes to it through a controller it builds from
258
+ * the `S3_*` variables (GCS: application default credentials) — as
259
+ * `rebase db backups list` does. The admin routes have to read it the same way.
260
+ * The app's file storage is not that controller: it is configured for the
261
+ * uploads bucket, it is a local directory in development, and in production
262
+ * without an uploads bucket there is none at all.
263
+ */
264
+ /** The destination as `BACKUP_DESTINATION` spells it. */
265
+ function describeBackupDestination(dest) {
266
+ if (dest.kind === "local") return dest.path;
267
+ return `${dest.kind === "s3" ? "s3" : "gs"}://${dest.bucket}${dest.prefix ? `/${dest.prefix}` : ""}`;
268
+ }
269
+ /**
270
+ * A controller for an object-storage destination's bucket, built from the
271
+ * environment the way the backup cron and `rebase db backups list` build
272
+ * theirs. Throws when an S3 destination has no credentials to read it with.
273
+ */
274
+ function backupStorageFromEnv(dest, env) {
275
+ if (dest.kind === "gcs") return new GCSStorageController({
276
+ type: "gcs",
277
+ bucket: dest.bucket
278
+ });
279
+ if (!env.S3_ACCESS_KEY_ID || !env.S3_SECRET_ACCESS_KEY) throw new Error("S3_ACCESS_KEY_ID and S3_SECRET_ACCESS_KEY are not set in this server's environment. Set the same S3_* variables the backup cron uses.");
280
+ return new S3StorageController({
281
+ type: "s3",
282
+ bucket: dest.bucket,
283
+ region: env.S3_REGION || "auto",
284
+ accessKeyId: env.S3_ACCESS_KEY_ID,
285
+ secretAccessKey: env.S3_SECRET_ACCESS_KEY,
286
+ endpoint: env.S3_ENDPOINT,
287
+ forcePathStyle: parseEnvBoolean(env.S3_FORCE_PATH_STYLE)
288
+ });
289
+ }
290
+ //#endregion
291
+ //#region src/backup/backup-routes.ts
292
+ /** Why a destination could not be read, as the answer says it. */
293
+ function unreadable(dest, err) {
294
+ const reason = err instanceof Error ? err.message : String(err);
295
+ return ApiError.serviceUnavailable(`Cannot read the backups at ${describeBackupDestination(dest)}: ${reason}`);
296
+ }
297
+ /**
298
+ * Admin REST routes for the Backups panel.
299
+ *
300
+ * Routes (mounted under `/admin/backups`, admin-guarded by the caller):
301
+ * GET / → list available backups, and the scheduled job's last run
302
+ * GET /download → download a backup's bytes (?key=…)
303
+ */
304
+ function createBackupRoutes(config) {
305
+ const router = new Hono();
306
+ router.onError(errorHandler);
307
+ const storageFor = config.storageFor ?? ((dest) => backupStorageFromEnv(dest, process.env));
308
+ /** The controller for `dest`, or none for a local one. A destination it cannot read is an error, never `[]`. */
309
+ const storageOf = (dest) => {
310
+ if (dest.kind === "local") return void 0;
311
+ try {
312
+ return storageFor(dest);
313
+ } catch (err) {
314
+ throw unreadable(dest, err);
315
+ }
316
+ };
317
+ router.get("/", async (c) => {
318
+ const schedule = config.getSchedule ? await config.getSchedule() : null;
319
+ const dest = config.getDestination();
320
+ if (!dest) return c.json({
321
+ backups: [],
322
+ destinationKind: "local",
323
+ configured: false,
324
+ schedule
325
+ });
326
+ const backups = await listBackupObjects(dest, storageOf(dest)).catch((err) => {
327
+ throw unreadable(dest, err);
328
+ });
329
+ const localDiskOfThisProcess = dest.kind === "local" && config.scheduledElsewhere === true && schedule !== null;
330
+ return c.json({
331
+ backups,
332
+ destinationKind: dest.kind,
333
+ configured: true,
334
+ schedule,
335
+ ...localDiskOfThisProcess ? { localDiskOfThisProcess } : {}
336
+ });
337
+ });
338
+ router.get("/download", async (c) => {
339
+ const dest = config.getDestination();
340
+ if (!dest) throw ApiError.badRequest("Backups are not configured (set BACKUP_DESTINATION).");
341
+ const key = c.req.query("key");
342
+ if (!key) throw ApiError.badRequest("Missing 'key' query parameter.");
343
+ const result = await openBackupStream(dest, key, storageOf(dest));
344
+ if (!result) throw ApiError.notFound(`Backup not found: ${key}`);
345
+ c.header("Content-Type", "application/octet-stream");
346
+ c.header("Content-Length", String(result.size));
347
+ c.header("Content-Disposition", `attachment; filename="${result.name}"`);
348
+ return c.body(result.stream);
349
+ });
350
+ return router;
351
+ }
352
+ //#endregion
353
+ //#region src/backup/backup-schedule.ts
354
+ /**
355
+ * The mark `createBackupCron` (in `@rebasepro/server-postgres`) puts on the
356
+ * definition it returns.
357
+ *
358
+ * A registry symbol, so it is the same value across two installed copies of
359
+ * either package, and neither package has to import the other: `server` must
360
+ * not depend on `server-postgres`. The job cannot be recognised any other way —
361
+ * its id is the cron file's name and its display name is configurable.
362
+ */
363
+ var BACKUP_CRON_MARK = Symbol.for("rebase.backupCron");
364
+ /** Whether a cron definition is the scheduled backup. */
365
+ function isBackupCronDefinition(definition) {
366
+ return Reflect.get(definition, BACKUP_CRON_MARK) === true;
367
+ }
368
+ /**
369
+ * How many recent log entries to look through for the last scheduled run. A
370
+ * skip — a slot that found the previous run still going — is logged as a
371
+ * success with nothing done, and must not stand in for the run it skipped; nor
372
+ * may a run someone started by hand, which is not the schedule's.
373
+ */
374
+ var RECENT_RUNS = 50;
375
+ /** A log entry as the panel reports a run. */
376
+ function outcomeOf(entry) {
377
+ return {
378
+ startedAt: entry.startedAt,
379
+ finishedAt: entry.finishedAt,
380
+ success: entry.success,
381
+ ...entry.success || !entry.error ? {} : { error: entry.error },
382
+ manual: entry.manual === true
383
+ };
384
+ }
385
+ /**
386
+ * The scheduled backup job and its last run, or `null` when the deployment
387
+ * has none — registered or refused.
388
+ */
389
+ async function readBackupSchedule(source) {
390
+ const [jobId] = source.jobIdsWhere(isBackupCronDefinition);
391
+ if (jobId === void 0) {
392
+ const [refused] = source.rejectedJobsWhere(isBackupCronDefinition);
393
+ return refused ? {
394
+ jobId: refused.id,
395
+ name: refused.name,
396
+ schedule: refused.schedule,
397
+ enabled: false,
398
+ refused: refused.reason
399
+ } : null;
400
+ }
401
+ const job = await source.fetchJob(jobId);
402
+ if (!job) return null;
403
+ const disabledInCode = !job.enabled && source.jobIdsWhere((definition) => isBackupCronDefinition(definition) && definition.enabled === false).includes(jobId);
404
+ let recent;
405
+ let historyError;
406
+ try {
407
+ recent = await source.getJobLogsFromDb(jobId, RECENT_RUNS);
408
+ } catch (err) {
409
+ logger.error(`[backups] Could not read the run history of the backup job "${jobId}"`, { error: err });
410
+ recent = [];
411
+ historyError = "The backup job's run history could not be read. The server log has the reason.";
412
+ }
413
+ const runs = recent.filter((entry) => !isAlreadyExecutingSkip(entry));
414
+ const lastScheduled = runs.find((entry) => entry.manual !== true);
415
+ const lastManual = runs.find((entry) => entry.manual === true);
416
+ const manualSince = lastManual && (!lastScheduled || lastManual.startedAt > lastScheduled.startedAt) ? lastManual : void 0;
417
+ return {
418
+ jobId,
419
+ name: job.name,
420
+ schedule: job.schedule,
421
+ enabled: job.enabled,
422
+ ...disabledInCode ? { disabledInCode } : {},
423
+ ...job.nextRunAt ? { nextRunAt: job.nextRunAt } : {},
424
+ ...historyError ? { historyError } : {},
425
+ ...lastScheduled ? { lastRun: outcomeOf(lastScheduled) } : {},
426
+ ...manualSince ? { lastManualRun: outcomeOf(manualSince) } : {}
427
+ };
428
+ }
429
+ //#endregion
430
+ //#region src/backup/index.ts
431
+ var backup_exports = /* @__PURE__ */ __exportAll({
432
+ createBackupRoutes: () => createBackupRoutes,
433
+ listAllObjectKeys: () => listAllObjectKeys,
434
+ listBackupObjects: () => listBackupObjects,
435
+ openBackupStream: () => openBackupStream,
436
+ parseBackupDestination: () => parseBackupDestination,
437
+ parseBackupTimestamp: () => parseBackupTimestamp,
438
+ readBackupBytes: () => readBackupBytes,
439
+ readBackupSchedule: () => readBackupSchedule
440
+ });
441
+ //#endregion
442
+ export { parseBackupTimestamp as a, parseBackupDestination as i, createBackupRoutes as n, readBackupBytes as o, listBackupObjects as r, backup_exports as t };
443
+
444
+ //# sourceMappingURL=backup-CN0s50D2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backup-CN0s50D2.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 if (!fs.existsSync(dest.path)) return [];\n const stat = fs.statSync(dest.path);\n const dir = stat.isDirectory() ? dest.path : path.dirname(dest.path);\n if (!fs.existsSync(dir)) return [];\n const files = fs.readdirSync(dir);\n const present = new Set(files);\n return files\n .filter((f) => f.endsWith(DUMP_SUFFIX))\n .map((f): BackupInfo => {\n const full = path.join(dir, f);\n const st = fs.statSync(full);\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\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 * 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. Object storage\n * still arrives through {@link StorageController.getObject}, which is a\n * buffered `File` by contract; 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 file = await storage.getObject(key, dest.bucket);\n if (!file) return null;\n return { stream: file.stream(), size: file.size, name: key.split(\"/\").pop() || key };\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 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 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 \"S3_ACCESS_KEY_ID and S3_SECRET_ACCESS_KEY are not set in this server's environment. \" +\n \"Set 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 } from \"hono\";\nimport type { BackupListing, BackupScheduleStatus } from \"@rebasepro/types\";\nimport type { HonoEnv } from \"../api/types\";\nimport { ApiError, errorHandler } from \"../api/errors\";\nimport type { StorageController } from \"../storage/types\";\nimport { BackupDestination, 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/**\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 */\nexport function createBackupRoutes(config: BackupRoutesConfig): Hono<HonoEnv> {\n const router = new Hono<HonoEnv>();\n router.onError(errorHandler);\n\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 const storageOf = (dest: BackupDestination): StorageController | undefined => {\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 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 = config.getDestination();\n if (!dest) {\n throw ApiError.badRequest(\"Backups are not configured (set BACKUP_DESTINATION).\");\n }\n const key = c.req.query(\"key\");\n if (!key) {\n throw ApiError.badRequest(\"Missing 'key' query parameter.\");\n }\n // Streamed: a dump is the size of the database. See `openBackupStream`.\n const result = await openBackupStream(dest, key, storageOf(dest));\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 return c.body(result.stream);\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 } from \"./backup-routes\";\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,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AU,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"}
@@ -37,11 +37,30 @@ export interface LoadedBundle {
37
37
  export interface LoadedStaticApp {
38
38
  /** Public base path, e.g. `/` or `/admin`. */
39
39
  path: string;
40
+ /**
41
+ * The one hostname this app answers on, lowercase — see
42
+ * {@link RebaseBundleStatic.host}. Absent means every hostname.
43
+ */
44
+ host?: string;
40
45
  /** Absolute path to the built assets. */
41
46
  dir: string;
42
47
  /** Serve `index.html` for unmatched paths under `path`. */
43
48
  spa: boolean;
44
49
  }
50
+ /**
51
+ * The order static apps are mounted in, which is also the order they are
52
+ * matched in: longest path first, and at an equal path the app that names a
53
+ * hostname before the one that does not.
54
+ *
55
+ * Longest first because the "/"-rooted app's catch-all would otherwise claim
56
+ * every sibling's URLs. Host first at an equal path because `admin.example.com`
57
+ * at "/" is a more specific claim than "every hostname" at "/" — the host-less
58
+ * app still answers on every other hostname, it just loses this one.
59
+ *
60
+ * The CLI orders `entry.static` the same way when it builds; this does not rely
61
+ * on that, because a bundle's order is whatever the program that wrote it chose.
62
+ */
63
+ export declare function compareStaticApps(a: Pick<LoadedStaticApp, "path" | "host">, b: Pick<LoadedStaticApp, "path" | "host">): number;
45
64
  /**
46
65
  * The file that makes a directory a bundle.
47
66
  *
@@ -76,6 +76,16 @@ export interface BundleSchema {
76
76
  * workspace running from source.
77
77
  */
78
78
  export declare function bundleResolutionRoots(bundleDir: string): string[];
79
+ /**
80
+ * What to `import()` for a package the bundle may have brought with it: its
81
+ * entry under the first of `resolveFrom` that has it installed, else the bare
82
+ * name, which resolves from wherever the runtime itself is installed.
83
+ */
84
+ export declare function resolveBundlePackage(packageName: string, resolveFrom: string[]): {
85
+ specifier: string;
86
+ /** Where the package was found, when it resolved from a `node_modules` tree. */
87
+ packageDir?: string;
88
+ };
79
89
  /**
80
90
  * Wrap a `DatabaseAdapter` as a `BackendBootstrapper` carrying a registry id.
81
91
  *