@rebasepro/server 0.17.3 → 0.18.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 (147) hide show
  1. package/LICENSE +0 -1
  2. package/README.md +5 -1
  3. package/bin/rebase-server.js +16 -1
  4. package/dist/{GCSStorageController-Bl7nmhdv.js → GCSStorageController-ZXPoNqW3.js} +21 -10
  5. package/dist/GCSStorageController-ZXPoNqW3.js.map +1 -0
  6. package/dist/{S3StorageController-CWvvrRpF.js → S3StorageController-5pAXyv31.js} +24 -10
  7. package/dist/S3StorageController-5pAXyv31.js.map +1 -0
  8. package/dist/admin-roles-vYdp_Pil.js +36 -0
  9. package/dist/admin-roles-vYdp_Pil.js.map +1 -0
  10. package/dist/{admin_block-BX6YULvJ.js → admin_block-0Xu0r6eZ.js} +4 -1
  11. package/dist/admin_block-0Xu0r6eZ.js.map +1 -0
  12. package/dist/api/errors.d.ts +37 -0
  13. package/dist/api/live-schema-routes.d.ts +14 -0
  14. package/dist/api/logs-routes.d.ts +8 -0
  15. package/dist/api/rest/api-generator.d.ts +33 -0
  16. package/dist/api/root-error-handler.d.ts +62 -0
  17. package/dist/api/schema-drift.d.ts +39 -0
  18. package/dist/api/types.d.ts +55 -0
  19. package/dist/{ast-schema-editor-CvkYOvri.js → ast-schema-editor-CNgFJ3NF.js} +23 -7
  20. package/dist/ast-schema-editor-CNgFJ3NF.js.map +1 -0
  21. package/dist/auth/api-keys/api-key-routes.d.ts +12 -0
  22. package/dist/auth/auth-hooks.d.ts +13 -2
  23. package/dist/auth/exclude-auth-secrets.d.ts +14 -0
  24. package/dist/auth/jwt.d.ts +22 -1
  25. package/dist/auth/mfa-routes.d.ts +10 -1
  26. package/dist/auth/middleware.d.ts +22 -0
  27. package/dist/auth/rate-limiter.d.ts +50 -0
  28. package/dist/auth/registration-policy.d.ts +27 -0
  29. package/dist/auth/rls-scope.d.ts +9 -1
  30. package/dist/auth/routes.d.ts +8 -1
  31. package/dist/auth/seed-admin.d.ts +73 -0
  32. package/dist/auth/session-routes.d.ts +10 -0
  33. package/dist/{auth-DkbzMZUS.js → auth-BRiOuyq8.js} +283 -198
  34. package/dist/auth-BRiOuyq8.js.map +1 -0
  35. package/dist/{backup-CRdZkA6c.js → backup-C8P6Cl3G.js} +2 -2
  36. package/dist/{backup-CRdZkA6c.js.map → backup-C8P6Cl3G.js.map} +1 -1
  37. package/dist/boot/boot.d.ts +18 -0
  38. package/dist/boot/bundle.d.ts +29 -6
  39. package/dist/boot/ddl-bootstrap.d.ts +2 -0
  40. package/dist/boot/env.d.ts +30 -1
  41. package/dist/boot/fetch-bundle.d.ts +24 -1
  42. package/dist/boot/options.d.ts +0 -8
  43. package/dist/boot/provision.d.ts +58 -18
  44. package/dist/boot/resource-adapters.d.ts +11 -1
  45. package/dist/boot/resource-resolvers.d.ts +96 -0
  46. package/dist/boot/sources.d.ts +27 -20
  47. package/dist/collections/validate-config.d.ts +29 -0
  48. package/dist/{contract-routes-CHPVKTZW.js → contract-routes-CusnEB5h.js} +24 -9
  49. package/dist/{contract-routes-CHPVKTZW.js.map → contract-routes-CusnEB5h.js.map} +1 -1
  50. package/dist/cron/cron-loader.d.ts +7 -1
  51. package/dist/cron/cron-scheduler.d.ts +48 -2
  52. package/dist/{cron-loader-d9WMFENB.js → cron-loader-DnmIePn_.js} +23 -4
  53. package/dist/cron-loader-DnmIePn_.js.map +1 -0
  54. package/dist/{cron-routes-DSC-kZXI.js → cron-routes-D3x2ydMa.js} +9 -6
  55. package/dist/cron-routes-D3x2ydMa.js.map +1 -0
  56. package/dist/{cron-scheduler-BB82dWuU.js → cron-scheduler-BpPKpl4i.js} +148 -28
  57. package/dist/cron-scheduler-BpPKpl4i.js.map +1 -0
  58. package/dist/{cron-store-KeN8rN63.js → cron-store-CCQXwgVL.js} +5 -5
  59. package/dist/{cron-store-KeN8rN63.js.map → cron-store-CCQXwgVL.js.map} +1 -1
  60. package/dist/{ddl-bootstrap-5YZCZ8qk.js → ddl-bootstrap-CfNvxMuK.js} +26 -2
  61. package/dist/{ddl-bootstrap-5YZCZ8qk.js.map → ddl-bootstrap-CfNvxMuK.js.map} +1 -1
  62. package/dist/email/index.d.ts +1 -0
  63. package/dist/email/unconfigured.d.ts +20 -0
  64. package/dist/env.d.ts +25 -0
  65. package/dist/errors-HjfaPlvY.js +385 -0
  66. package/dist/errors-HjfaPlvY.js.map +1 -0
  67. package/dist/{function-loader-LLdmBFoL.js → function-loader-xnbDAPfa.js} +9 -3
  68. package/dist/{function-loader-LLdmBFoL.js.map → function-loader-xnbDAPfa.js.map} +1 -1
  69. package/dist/function-routes-gQ0EShVG.js +267 -0
  70. package/dist/function-routes-gQ0EShVG.js.map +1 -0
  71. package/dist/functions/define-function.d.ts +6 -3
  72. package/dist/functions/function-routes.d.ts +8 -4
  73. package/dist/functions/index.js +128 -23
  74. package/dist/functions/index.js.map +1 -1
  75. package/dist/{history-recorder-B2pL3X8b.js → history-recorder-B1FwXx9J.js} +3 -3
  76. package/dist/{history-recorder-B2pL3X8b.js.map → history-recorder-B1FwXx9J.js.map} +1 -1
  77. package/dist/{history-store-BUJ-37Sm.js → history-store-LHXaQywp.js} +2 -2
  78. package/dist/{history-store-BUJ-37Sm.js.map → history-store-LHXaQywp.js.map} +1 -1
  79. package/dist/index.d.ts +16 -4
  80. package/dist/index.es.js +16229 -7676
  81. package/dist/index.es.js.map +1 -1
  82. package/dist/init.d.ts +33 -13
  83. package/dist/{jobs-XXXcZrmj.js → jobs-DkkD9mPV.js} +5 -5
  84. package/dist/{jobs-XXXcZrmj.js.map → jobs-DkkD9mPV.js.map} +1 -1
  85. package/dist/{jwt-DNeOn39r.js → jwt-DkhXwMzR.js} +9 -314
  86. package/dist/jwt-DkhXwMzR.js.map +1 -0
  87. package/dist/keys-g8lbVC_o.js +230 -0
  88. package/dist/keys-g8lbVC_o.js.map +1 -0
  89. package/dist/{logger-DS03e908.js → logger-DO2PZc4i.js} +197 -18
  90. package/dist/logger-DO2PZc4i.js.map +1 -0
  91. package/dist/{logs-routes-DB72iQSr.js → logs-routes-CbsTpozn.js} +74 -6
  92. package/dist/logs-routes-CbsTpozn.js.map +1 -0
  93. package/dist/{openapi-generator-CpZp2Fai.js → openapi-generator-BIBbO1Tq.js} +221 -38
  94. package/dist/openapi-generator-BIBbO1Tq.js.map +1 -0
  95. package/dist/{proxy-CMymhnwG.js → proxy-Czngl3p9.js} +2 -2
  96. package/dist/{proxy-CMymhnwG.js.map → proxy-Czngl3p9.js.map} +1 -1
  97. package/dist/{query-parser-DqXNaBIH.js → query-parser-C68Q9EX4.js} +35 -6
  98. package/dist/{query-parser-DqXNaBIH.js.map → query-parser-C68Q9EX4.js.map} +1 -1
  99. package/dist/queues/runtime.d.ts +56 -0
  100. package/dist/{request-timeout-C8gkc-j7.js → request-timeout-DESvlfrS.js} +4 -6
  101. package/dist/request-timeout-DESvlfrS.js.map +1 -0
  102. package/dist/schema-edit/project-root.d.ts +4 -4
  103. package/dist/{schema-editor-routes-DNV_nBhW.js → schema-editor-routes-CcZKh50q.js} +4 -4
  104. package/dist/{schema-editor-routes-DNV_nBhW.js.map → schema-editor-routes-CcZKh50q.js.map} +1 -1
  105. package/dist/{schemas-DBxgjM9A.js → schemas-C3234HWE.js} +2746 -72
  106. package/dist/schemas-C3234HWE.js.map +1 -0
  107. package/dist/singleton.d.ts +6 -4
  108. package/dist/src-DHK4fHkw.js +1002 -0
  109. package/dist/src-DHK4fHkw.js.map +1 -0
  110. package/dist/{src-C9gKj23J.js → src-Dq-I3Ybx.js} +507 -54
  111. package/dist/src-Dq-I3Ybx.js.map +1 -0
  112. package/dist/storage/GCSStorageController.d.ts +5 -0
  113. package/dist/storage/LocalStorageController.d.ts +14 -0
  114. package/dist/storage/S3StorageController.d.ts +8 -0
  115. package/dist/storage/image-transform.d.ts +35 -0
  116. package/dist/storage/keys.d.ts +23 -0
  117. package/dist/storage/policies.d.ts +22 -0
  118. package/dist/storage/routes.d.ts +9 -0
  119. package/dist/storage/tus-handler.d.ts +43 -1
  120. package/dist/storage/types.d.ts +28 -0
  121. package/dist/types-BfKcm9do.js.map +1 -1
  122. package/dist/utils/dev-port.d.ts +18 -0
  123. package/dist/utils/logger.d.ts +60 -0
  124. package/dist/utils/request-logger.d.ts +2 -1
  125. package/package.json +30 -24
  126. package/dist/GCSStorageController-Bl7nmhdv.js.map +0 -1
  127. package/dist/S3StorageController-CWvvrRpF.js.map +0 -1
  128. package/dist/admin_block-BX6YULvJ.js.map +0 -1
  129. package/dist/ast-schema-editor-CvkYOvri.js.map +0 -1
  130. package/dist/auth-DkbzMZUS.js.map +0 -1
  131. package/dist/cron-loader-d9WMFENB.js.map +0 -1
  132. package/dist/cron-routes-DSC-kZXI.js.map +0 -1
  133. package/dist/cron-scheduler-BB82dWuU.js.map +0 -1
  134. package/dist/errors-DBwpj9N8.js +0 -231
  135. package/dist/errors-DBwpj9N8.js.map +0 -1
  136. package/dist/function-routes-ClT6UQpD.js +0 -41
  137. package/dist/function-routes-ClT6UQpD.js.map +0 -1
  138. package/dist/jwt-DNeOn39r.js.map +0 -1
  139. package/dist/logger-DS03e908.js.map +0 -1
  140. package/dist/logs-routes-DB72iQSr.js.map +0 -1
  141. package/dist/openapi-generator-CpZp2Fai.js.map +0 -1
  142. package/dist/request-timeout-C8gkc-j7.js.map +0 -1
  143. package/dist/schemas-DBxgjM9A.js.map +0 -1
  144. package/dist/src-C9gKj23J.js.map +0 -1
  145. package/dist/src-CcOl05Oq.js +0 -552
  146. package/dist/src-CcOl05Oq.js.map +0 -1
  147. package/dist/utils/logging.d.ts +0 -5
@@ -0,0 +1,230 @@
1
+ import { createRequire as __rebaseCreateRequire } from "module";
2
+ import __rebaseProcess from "process";
3
+ globalThis.process ??= __rebaseProcess;
4
+ __rebaseCreateRequire(import.meta.url);
5
+ import { c as DEFAULT_STORAGE_SOURCE_KEY } from "./src-DHK4fHkw.js";
6
+ //#region src/storage/keys.ts
7
+ /**
8
+ * Canonical storage keys and bucket names.
9
+ *
10
+ * Storage is not under RLS, so a `storageAuthorize` hook is the whole access
11
+ * control model — and a hook can only be correct if the key it is shown is the
12
+ * key that is written. That is the invariant this module exists to hold: one
13
+ * canonical string, computed once per request, handed to the hook, to the
14
+ * controller, and to the download token alike.
15
+ *
16
+ * ## Why rejecting beats stripping
17
+ *
18
+ * The previous `sanitizeStorageKey` *stripped* `../` in a single pass. Two
19
+ * things were wrong with that, and only one of them was the obvious one.
20
+ *
21
+ * The obvious one: a single pass is not a fixed point. `....//` contains `../`
22
+ * at offset 2, so removing it leaves `../` behind — the sanitizer manufactured
23
+ * the traversal it was there to remove. `users/alice/....//bob/x` came out as
24
+ * `users/alice/../bob/x`, which a prefix hook reads as alice's (it starts with
25
+ * `users/alice/`) and the filesystem reads as bob's. The hook approved one
26
+ * object and the controller wrote another.
27
+ *
28
+ * The subtler one, and the reason this is a rewrite rather than a loop: even a
29
+ * correct strip is a silent rewrite. A caller who asks to store at `a/../b` and
30
+ * gets an object at `a/b` was not protected, they were misled — and every later
31
+ * read, ownership row and audit line now refers to a path nobody chose. So a key
32
+ * that means something other than what it says is refused (400), not repaired.
33
+ *
34
+ * Note what is NOT traversal under this rule: `....` is an ordinary directory
35
+ * name, and `users/alice/....//bob/x` canonicalizes to
36
+ * `users/alice/..../bob/x` — still comfortably inside alice's prefix, which is
37
+ * exactly right. Only a real `..` segment is refused.
38
+ */
39
+ /**
40
+ * `path.posix.normalize`, without `node:path`.
41
+ *
42
+ * A storage key is a POSIX-shaped string that never touches a filesystem, so
43
+ * reaching for `node:path` to fold `.` and `//` out of it was always a little
44
+ * wrong on its own terms — on Windows the platform `path` would have applied
45
+ * different rules to the same key. It also put the module that every storage
46
+ * read, ownership row and audit line goes through on the list of things that
47
+ * only run in a Node process.
48
+ *
49
+ * This is the algorithm Node implements, transcribed: segments are folded left
50
+ * to right, `..` pops unless it would climb past the root of a relative path,
51
+ * and both the leading and the trailing separator survive the round trip. The
52
+ * `..` branch is unreachable from {@link canonicalStorageKey}, which refuses
53
+ * those keys outright before it gets here — it exists so that this function is
54
+ * *the* normalizer rather than a subset of one, and
55
+ * `storage-keys.property.test.ts` holds it to that with a property test against
56
+ * `path.posix.normalize` itself. Exported for exactly that — nothing outside
57
+ * this module should be normalizing a key.
58
+ */
59
+ function normalizePosix(input) {
60
+ if (input.length === 0) return ".";
61
+ const isAbsolute = input.startsWith("/");
62
+ const trailingSeparator = input.endsWith("/");
63
+ const segments = [];
64
+ for (const segment of input.split("/")) {
65
+ if (segment === "" || segment === ".") continue;
66
+ if (segment === "..") {
67
+ if (segments.length > 0 && segments[segments.length - 1] !== "..") segments.pop();
68
+ else if (!isAbsolute) segments.push("..");
69
+ continue;
70
+ }
71
+ segments.push(segment);
72
+ }
73
+ const joined = segments.join("/");
74
+ if (joined === "") {
75
+ if (isAbsolute) return "/";
76
+ return trailingSeparator ? "./" : ".";
77
+ }
78
+ const withTrailing = trailingSeparator ? `${joined}/` : joined;
79
+ return isAbsolute ? `/${withTrailing}` : withTrailing;
80
+ }
81
+ /** Longest key accepted, in UTF-16 code units. Matches the previous cap. */
82
+ var MAX_STORAGE_KEY_LENGTH = 1024;
83
+ /**
84
+ * A key that cannot be canonicalized. Carries no path back to the caller
85
+ * beyond what they sent, so it is safe to surface as a 400 message.
86
+ */
87
+ var InvalidStorageKeyError = class extends Error {
88
+ constructor(message) {
89
+ super(message);
90
+ this.name = "InvalidStorageKeyError";
91
+ }
92
+ };
93
+ /**
94
+ * Canonicalize a caller-supplied storage key, or throw
95
+ * {@link InvalidStorageKeyError}.
96
+ *
97
+ * Normalizations applied (safe, idempotent, and meaning-preserving):
98
+ * - leading slashes removed — `/a/b` and `a/b` name the same object
99
+ * - `.` segments and repeated slashes collapsed
100
+ *
101
+ * Refusals (the key means something other than what it says):
102
+ * - any `..` segment, on either separator, at any depth
103
+ * - null bytes
104
+ * - keys longer than {@link MAX_STORAGE_KEY_LENGTH}
105
+ *
106
+ * A trailing slash is preserved: it is how the folder route marks a prefix.
107
+ */
108
+ function canonicalStorageKey(rawKey) {
109
+ if (rawKey.includes("\0")) throw new InvalidStorageKeyError("Storage key contains a null byte.");
110
+ if (rawKey.length > 1024) throw new InvalidStorageKeyError(`Storage key exceeds the maximum length of ${MAX_STORAGE_KEY_LENGTH} characters.`);
111
+ if (rawKey.split(/[\\/]/).some((segment) => segment === "..")) throw new InvalidStorageKeyError("Storage key contains a '..' path segment. Keys must name an object directly.");
112
+ const withoutLeadingSlashes = rawKey.replace(/^\/+/, "");
113
+ if (withoutLeadingSlashes === "") return "";
114
+ const denotesDirectory = /(?:^|\/)\.?$/.test(withoutLeadingSlashes);
115
+ const normalized = normalizePosix(withoutLeadingSlashes);
116
+ if (normalized === "." || normalized === "./") return "";
117
+ const key = normalized.replace(/^\.\//, "").replace(/^\/+/, "");
118
+ if (key === "") return "";
119
+ return denotesDirectory && !key.endsWith("/") ? `${key}/` : key;
120
+ }
121
+ /**
122
+ * Canonicalize, or return `null` when the key is not canonicalizable.
123
+ *
124
+ * For callers that must fail closed without an exception — the download-token
125
+ * middleware compares a request path against a granted path, and a key it
126
+ * cannot canonicalize simply matches nothing.
127
+ */
128
+ function tryCanonicalStorageKey(rawKey) {
129
+ try {
130
+ return canonicalStorageKey(rawKey);
131
+ } catch {
132
+ return null;
133
+ }
134
+ }
135
+ /**
136
+ * Canonicalize the storage *source* a request names (`?storageId=`), so that
137
+ * "the default source" has exactly one spelling.
138
+ *
139
+ * The default source can be asked for three ways — the parameter omitted, sent
140
+ * empty, or sent as the literal `(default)` — and all three resolve to the same
141
+ * controller. Without a single spelling, the value derived when a download
142
+ * token is minted and the value derived when it is presented can differ for the
143
+ * same object, which is either a spurious 403 or, if the comparison is dropped
144
+ * to stop those, no scoping at all.
145
+ *
146
+ * Deliberately *not* validated against the registry: this is a naming rule, not
147
+ * an existence check, and it must give the same answer in `auth/` (which has no
148
+ * registry) as in the storage routes. An id that names no source still
149
+ * canonicalizes to itself and simply matches only itself.
150
+ */
151
+ function canonicalStorageId(rawStorageId) {
152
+ if (rawStorageId === void 0 || rawStorageId === null) return DEFAULT_STORAGE_SOURCE_KEY;
153
+ const trimmed = rawStorageId.trim();
154
+ return trimmed === "" ? DEFAULT_STORAGE_SOURCE_KEY : trimmed;
155
+ }
156
+ /** A bucket name that does not name a bucket. See {@link canonicalStorageBucket}. */
157
+ var InvalidStorageBucketError = class extends Error {
158
+ constructor(message) {
159
+ super(message);
160
+ this.name = "InvalidStorageBucketError";
161
+ }
162
+ };
163
+ /**
164
+ * One path segment: letters, digits, `.`, `_`, `-`, first character
165
+ * alphanumeric. Deliberately narrow — it is the intersection of what S3, GCS
166
+ * and a filesystem directory all accept, and it makes `..`, `.tus-uploads`,
167
+ * absolute paths and anything containing a separator unrepresentable.
168
+ */
169
+ var STORAGE_BUCKET_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
170
+ /**
171
+ * Canonicalize a caller-supplied bucket name, or throw
172
+ * {@link InvalidStorageBucketError}.
173
+ *
174
+ * The bucket is the *other* caller-controlled routing value in an upload
175
+ * request, and it was the one nobody validated. `LocalStorageController`
176
+ * builds `join(basePath, bucket)` and then checks containment against that
177
+ * result, so a bucket of `../../etc` moved the boundary rather than crossing
178
+ * it — the guard passed because the guard's reference point was the attacker's.
179
+ * The containment check now resolves against the storage root, and this is the
180
+ * check at the route boundary that stops the value before it gets there.
181
+ *
182
+ * A bucket is configuration, not user data: there is no legitimate caller that
183
+ * needs a separator, a leading dot, or a `..` in one. So this refuses rather
184
+ * than repairs, exactly as {@link canonicalStorageKey} does — a rewritten
185
+ * bucket would silently store the object somewhere the caller did not ask for.
186
+ *
187
+ * Returns `undefined` when the caller named no bucket (absent, or an empty
188
+ * form field), which is how every controller spells "use my default". An empty
189
+ * string used to reach `getFullPath` and resolve to the storage *root* rather
190
+ * than the `default` bucket, which is a third place a bare key did not
191
+ * round-trip.
192
+ */
193
+ function canonicalStorageBucket(rawBucket) {
194
+ if (rawBucket === void 0 || rawBucket === null || rawBucket === "") return void 0;
195
+ if (rawBucket.length > 63) throw new InvalidStorageBucketError(`Storage bucket exceeds the maximum length of 63 characters.`);
196
+ if (!STORAGE_BUCKET_PATTERN.test(rawBucket)) throw new InvalidStorageBucketError("Storage bucket must be a single name of letters, digits, '.', '_' or '-', starting with a letter or digit.");
197
+ return rawBucket;
198
+ }
199
+ /**
200
+ * The prefix an object store's listing should be given for a caller's key, and
201
+ * the key a listing should hand back for a folder.
202
+ *
203
+ * The three controllers answer the same question in two different ways, and
204
+ * they used to disagree about the answer. `LocalStorageController` resolves a
205
+ * *directory* on disk, so `listObjects("products/images")` and
206
+ * `listObjects("products/images/")` both list what is inside it. An object
207
+ * store under `Delimiter: "/"` does not: `Prefix: "products/images"` matches
208
+ * `products/images.txt` and `productsomething/`, and returns none of the files
209
+ * inside `products/images/`. So the same call — the SDK's own documented one —
210
+ * answered one thing against local dev and another against the S3 bucket in
211
+ * production, which is the worst place for a divergence to live.
212
+ *
213
+ * `listingPrefix` is what to *send*: a trailing slash, always, because that is
214
+ * the only spelling that means "inside this folder" to a delimiter listing.
215
+ * `folderKey` is what to *return* for a common prefix: no trailing slash, the
216
+ * form the local controller has always used, so a `fullPath` from a listing is
217
+ * a key you can pass straight back to any of them.
218
+ */
219
+ function listingPrefix(rawPrefix) {
220
+ const key = rawPrefix.replace(/^\/+/, "").replace(/\/+$/, "");
221
+ return key === "" ? void 0 : `${key}/`;
222
+ }
223
+ /** @see listingPrefix */
224
+ function folderKey(rawPrefix) {
225
+ return rawPrefix.replace(/^\/+/, "").replace(/\/+$/, "");
226
+ }
227
+ //#endregion
228
+ export { canonicalStorageKey as a, tryCanonicalStorageKey as c, canonicalStorageId as i, InvalidStorageKeyError as n, folderKey as o, canonicalStorageBucket as r, listingPrefix as s, InvalidStorageBucketError as t };
229
+
230
+ //# sourceMappingURL=keys-g8lbVC_o.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keys-g8lbVC_o.js","names":[],"sources":["../src/storage/keys.ts"],"sourcesContent":["/**\n * Canonical storage keys and bucket names.\n *\n * Storage is not under RLS, so a `storageAuthorize` hook is the whole access\n * control model — and a hook can only be correct if the key it is shown is the\n * key that is written. That is the invariant this module exists to hold: one\n * canonical string, computed once per request, handed to the hook, to the\n * controller, and to the download token alike.\n *\n * ## Why rejecting beats stripping\n *\n * The previous `sanitizeStorageKey` *stripped* `../` in a single pass. Two\n * things were wrong with that, and only one of them was the obvious one.\n *\n * The obvious one: a single pass is not a fixed point. `....//` contains `../`\n * at offset 2, so removing it leaves `../` behind — the sanitizer manufactured\n * the traversal it was there to remove. `users/alice/....//bob/x` came out as\n * `users/alice/../bob/x`, which a prefix hook reads as alice's (it starts with\n * `users/alice/`) and the filesystem reads as bob's. The hook approved one\n * object and the controller wrote another.\n *\n * The subtler one, and the reason this is a rewrite rather than a loop: even a\n * correct strip is a silent rewrite. A caller who asks to store at `a/../b` and\n * gets an object at `a/b` was not protected, they were misled — and every later\n * read, ownership row and audit line now refers to a path nobody chose. So a key\n * that means something other than what it says is refused (400), not repaired.\n *\n * Note what is NOT traversal under this rule: `....` is an ordinary directory\n * name, and `users/alice/....//bob/x` canonicalizes to\n * `users/alice/..../bob/x` — still comfortably inside alice's prefix, which is\n * exactly right. Only a real `..` segment is refused.\n */\n\nimport { DEFAULT_STORAGE_SOURCE_KEY } from \"@rebasepro/types\";\n\n/**\n * `path.posix.normalize`, without `node:path`.\n *\n * A storage key is a POSIX-shaped string that never touches a filesystem, so\n * reaching for `node:path` to fold `.` and `//` out of it was always a little\n * wrong on its own terms — on Windows the platform `path` would have applied\n * different rules to the same key. It also put the module that every storage\n * read, ownership row and audit line goes through on the list of things that\n * only run in a Node process.\n *\n * This is the algorithm Node implements, transcribed: segments are folded left\n * to right, `..` pops unless it would climb past the root of a relative path,\n * and both the leading and the trailing separator survive the round trip. The\n * `..` branch is unreachable from {@link canonicalStorageKey}, which refuses\n * those keys outright before it gets here — it exists so that this function is\n * *the* normalizer rather than a subset of one, and\n * `storage-keys.property.test.ts` holds it to that with a property test against\n * `path.posix.normalize` itself. Exported for exactly that — nothing outside\n * this module should be normalizing a key.\n */\nexport function normalizePosix(input: string): string {\n if (input.length === 0) return \".\";\n const isAbsolute = input.startsWith(\"/\");\n const trailingSeparator = input.endsWith(\"/\");\n\n const segments: string[] = [];\n for (const segment of input.split(\"/\")) {\n if (segment === \"\" || segment === \".\") continue;\n if (segment === \"..\") {\n if (segments.length > 0 && segments[segments.length - 1] !== \"..\") segments.pop();\n else if (!isAbsolute) segments.push(\"..\");\n continue;\n }\n segments.push(segment);\n }\n\n const joined = segments.join(\"/\");\n if (joined === \"\") {\n if (isAbsolute) return \"/\";\n return trailingSeparator ? \"./\" : \".\";\n }\n const withTrailing = trailingSeparator ? `${joined}/` : joined;\n return isAbsolute ? `/${withTrailing}` : withTrailing;\n}\n\n/** Longest key accepted, in UTF-16 code units. Matches the previous cap. */\nexport const MAX_STORAGE_KEY_LENGTH = 1024;\n\n/**\n * A key that cannot be canonicalized. Carries no path back to the caller\n * beyond what they sent, so it is safe to surface as a 400 message.\n */\nexport class InvalidStorageKeyError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"InvalidStorageKeyError\";\n }\n}\n\n/**\n * Canonicalize a caller-supplied storage key, or throw\n * {@link InvalidStorageKeyError}.\n *\n * Normalizations applied (safe, idempotent, and meaning-preserving):\n * - leading slashes removed — `/a/b` and `a/b` name the same object\n * - `.` segments and repeated slashes collapsed\n *\n * Refusals (the key means something other than what it says):\n * - any `..` segment, on either separator, at any depth\n * - null bytes\n * - keys longer than {@link MAX_STORAGE_KEY_LENGTH}\n *\n * A trailing slash is preserved: it is how the folder route marks a prefix.\n */\nexport function canonicalStorageKey(rawKey: string): string {\n if (rawKey.includes(\"\\0\")) {\n throw new InvalidStorageKeyError(\"Storage key contains a null byte.\");\n }\n if (rawKey.length > MAX_STORAGE_KEY_LENGTH) {\n throw new InvalidStorageKeyError(\n `Storage key exceeds the maximum length of ${MAX_STORAGE_KEY_LENGTH} characters.`\n );\n }\n\n // Split on both separators: `path.join` treats `\\` as a separator on\n // Windows, so `..\\` is traversal there even though POSIX reads it as a\n // filename. Checked against the RAW key, before any normalization — the\n // whole point is that `a/../b` is refused rather than quietly turned into\n // `b`.\n if (rawKey.split(/[\\\\/]/).some((segment) => segment === \"..\")) {\n throw new InvalidStorageKeyError(\n \"Storage key contains a '..' path segment. Keys must name an object directly.\"\n );\n }\n\n const withoutLeadingSlashes = rawKey.replace(/^\\/+/, \"\");\n if (withoutLeadingSlashes === \"\") return \"\";\n\n // Whether the key names a *directory* rather than an object: it ends with a\n // separator, or its last segment is the `.` that means \"this directory\".\n //\n // Recorded before normalizing, because normalization drops the\n // distinction in one of those two spellings and not the other: `public/.`\n // becomes `public` while `public/./` stays `public/`. That asymmetry breaks\n // the rule this module states — a trailing slash is preserved, because it is\n // how the folder route marks a prefix — and it is not cosmetic on `list`,\n // where a prefix of `public` also matches `publicity/` and hands back keys\n // the caller never asked for.\n const denotesDirectory = /(?:^|\\/)\\.?$/.test(withoutLeadingSlashes);\n\n // Safe now: with no `..` segment in the input, `normalize` can only collapse\n // `.` and duplicate slashes — it cannot climb.\n const normalized = normalizePosix(withoutLeadingSlashes);\n\n // `normalize(\".\")`, and `normalize(\"./\")` → `./`; neither names an object.\n if (normalized === \".\" || normalized === \"./\") return \"\";\n\n // Defensive: nothing reaching here still carries a leading `./`, since the\n // leading slashes are already gone and `normalize` only emits `./` for a\n // key that normalizes to nothing — which returned above.\n const key = normalized.replace(/^\\.\\//, \"\").replace(/^\\/+/, \"\");\n if (key === \"\") return \"\";\n return denotesDirectory && !key.endsWith(\"/\") ? `${key}/` : key;\n}\n\n/**\n * Canonicalize, or return `null` when the key is not canonicalizable.\n *\n * For callers that must fail closed without an exception — the download-token\n * middleware compares a request path against a granted path, and a key it\n * cannot canonicalize simply matches nothing.\n */\nexport function tryCanonicalStorageKey(rawKey: string): string | null {\n try {\n return canonicalStorageKey(rawKey);\n } catch {\n return null;\n }\n}\n\n/**\n * Canonicalize the storage *source* a request names (`?storageId=`), so that\n * \"the default source\" has exactly one spelling.\n *\n * The default source can be asked for three ways — the parameter omitted, sent\n * empty, or sent as the literal `(default)` — and all three resolve to the same\n * controller. Without a single spelling, the value derived when a download\n * token is minted and the value derived when it is presented can differ for the\n * same object, which is either a spurious 403 or, if the comparison is dropped\n * to stop those, no scoping at all.\n *\n * Deliberately *not* validated against the registry: this is a naming rule, not\n * an existence check, and it must give the same answer in `auth/` (which has no\n * registry) as in the storage routes. An id that names no source still\n * canonicalizes to itself and simply matches only itself.\n */\nexport function canonicalStorageId(rawStorageId: string | undefined | null): string {\n if (rawStorageId === undefined || rawStorageId === null) return DEFAULT_STORAGE_SOURCE_KEY;\n const trimmed = rawStorageId.trim();\n return trimmed === \"\" ? DEFAULT_STORAGE_SOURCE_KEY : trimmed;\n}\n\n/**\n * Longest bucket name accepted. 63 is the S3/GCS limit, and a local bucket is\n * one directory name, so the tighter of the two bounds everything.\n */\nexport const MAX_STORAGE_BUCKET_LENGTH = 63;\n\n/** A bucket name that does not name a bucket. See {@link canonicalStorageBucket}. */\nexport class InvalidStorageBucketError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"InvalidStorageBucketError\";\n }\n}\n\n/**\n * One path segment: letters, digits, `.`, `_`, `-`, first character\n * alphanumeric. Deliberately narrow — it is the intersection of what S3, GCS\n * and a filesystem directory all accept, and it makes `..`, `.tus-uploads`,\n * absolute paths and anything containing a separator unrepresentable.\n */\nconst STORAGE_BUCKET_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\n\n/**\n * Canonicalize a caller-supplied bucket name, or throw\n * {@link InvalidStorageBucketError}.\n *\n * The bucket is the *other* caller-controlled routing value in an upload\n * request, and it was the one nobody validated. `LocalStorageController`\n * builds `join(basePath, bucket)` and then checks containment against that\n * result, so a bucket of `../../etc` moved the boundary rather than crossing\n * it — the guard passed because the guard's reference point was the attacker's.\n * The containment check now resolves against the storage root, and this is the\n * check at the route boundary that stops the value before it gets there.\n *\n * A bucket is configuration, not user data: there is no legitimate caller that\n * needs a separator, a leading dot, or a `..` in one. So this refuses rather\n * than repairs, exactly as {@link canonicalStorageKey} does — a rewritten\n * bucket would silently store the object somewhere the caller did not ask for.\n *\n * Returns `undefined` when the caller named no bucket (absent, or an empty\n * form field), which is how every controller spells \"use my default\". An empty\n * string used to reach `getFullPath` and resolve to the storage *root* rather\n * than the `default` bucket, which is a third place a bare key did not\n * round-trip.\n */\nexport function canonicalStorageBucket(rawBucket: string | undefined | null): string | undefined {\n if (rawBucket === undefined || rawBucket === null || rawBucket === \"\") return undefined;\n if (rawBucket.length > MAX_STORAGE_BUCKET_LENGTH) {\n throw new InvalidStorageBucketError(\n `Storage bucket exceeds the maximum length of ${MAX_STORAGE_BUCKET_LENGTH} characters.`\n );\n }\n if (!STORAGE_BUCKET_PATTERN.test(rawBucket)) {\n throw new InvalidStorageBucketError(\n \"Storage bucket must be a single name of letters, digits, '.', '_' or '-', \" +\n \"starting with a letter or digit.\"\n );\n }\n return rawBucket;\n}\n\n/**\n * The prefix an object store's listing should be given for a caller's key, and\n * the key a listing should hand back for a folder.\n *\n * The three controllers answer the same question in two different ways, and\n * they used to disagree about the answer. `LocalStorageController` resolves a\n * *directory* on disk, so `listObjects(\"products/images\")` and\n * `listObjects(\"products/images/\")` both list what is inside it. An object\n * store under `Delimiter: \"/\"` does not: `Prefix: \"products/images\"` matches\n * `products/images.txt` and `productsomething/`, and returns none of the files\n * inside `products/images/`. So the same call — the SDK's own documented one —\n * answered one thing against local dev and another against the S3 bucket in\n * production, which is the worst place for a divergence to live.\n *\n * `listingPrefix` is what to *send*: a trailing slash, always, because that is\n * the only spelling that means \"inside this folder\" to a delimiter listing.\n * `folderKey` is what to *return* for a common prefix: no trailing slash, the\n * form the local controller has always used, so a `fullPath` from a listing is\n * a key you can pass straight back to any of them.\n */\nexport function listingPrefix(rawPrefix: string): string | undefined {\n const key = rawPrefix.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n return key === \"\" ? undefined : `${key}/`;\n}\n\n/** @see listingPrefix */\nexport function folderKey(rawPrefix: string): string {\n return rawPrefix.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,SAAgB,eAAe,OAAuB;CAClD,IAAI,MAAM,WAAW,GAAG,OAAO;CAC/B,MAAM,aAAa,MAAM,WAAW,GAAG;CACvC,MAAM,oBAAoB,MAAM,SAAS,GAAG;CAE5C,MAAM,WAAqB,CAAC;CAC5B,KAAK,MAAM,WAAW,MAAM,MAAM,GAAG,GAAG;EACpC,IAAI,YAAY,MAAM,YAAY,KAAK;EACvC,IAAI,YAAY,MAAM;GAClB,IAAI,SAAS,SAAS,KAAK,SAAS,SAAS,SAAS,OAAO,MAAM,SAAS,IAAI;QAC3E,IAAI,CAAC,YAAY,SAAS,KAAK,IAAI;GACxC;EACJ;EACA,SAAS,KAAK,OAAO;CACzB;CAEA,MAAM,SAAS,SAAS,KAAK,GAAG;CAChC,IAAI,WAAW,IAAI;EACf,IAAI,YAAY,OAAO;EACvB,OAAO,oBAAoB,OAAO;CACtC;CACA,MAAM,eAAe,oBAAoB,GAAG,OAAO,KAAK;CACxD,OAAO,aAAa,IAAI,iBAAiB;AAC7C;;AAGA,IAAa,yBAAyB;;;;;AAMtC,IAAa,yBAAb,cAA4C,MAAM;CAC9C,YAAY,SAAiB;EACzB,MAAM,OAAO;EACb,KAAK,OAAO;CAChB;AACJ;;;;;;;;;;;;;;;;AAiBA,SAAgB,oBAAoB,QAAwB;CACxD,IAAI,OAAO,SAAS,IAAI,GACpB,MAAM,IAAI,uBAAuB,mCAAmC;CAExE,IAAI,OAAO,SAAA,MACP,MAAM,IAAI,uBACN,6CAA6C,uBAAuB,aACxE;CAQJ,IAAI,OAAO,MAAM,OAAO,CAAC,CAAC,MAAM,YAAY,YAAY,IAAI,GACxD,MAAM,IAAI,uBACN,8EACJ;CAGJ,MAA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AAC3C;;AAGA,SAAgB,UAAU,WAA2B;CACjD,OAAO,UAAU,QAAQ,QAAQ,EAAE,CAAC,CAAC,QAAQ,QAAQ,EAAE;AAC3D"}
@@ -112,13 +112,48 @@ var LOG_PRIORITY = {
112
112
  function isProduction() {
113
113
  return hostEnv().NODE_ENV === "production";
114
114
  }
115
+ /**
116
+ * An explicit level from `config.logging.level`, when a project set one.
117
+ *
118
+ * Outranks `LOG_LEVEL` because it is the more specific statement: an
119
+ * environment variable is the deployment's default, and this is the
120
+ * application saying what it wants regardless of where it runs.
121
+ *
122
+ * There used to be a second, separate mechanism for this — `utils/logging.ts`
123
+ * reassigned `console.debug`/`console.log`/`console.warn` to no-ops — and the
124
+ * two disagreed in a way nobody could have guessed from either: `LOG_LEVEL=warn`
125
+ * silenced this logger's info lines *and* every `console.log` in the process,
126
+ * including a dependency's, including a project's own debugging. It also could
127
+ * not be undone, because the originals were gone.
128
+ */
129
+ var configuredLevel;
130
+ /**
131
+ * Set the level from configuration. `undefined` returns to `LOG_LEVEL`.
132
+ *
133
+ * Read per line rather than captured at construction, so a logger created
134
+ * before configuration is read still honours it — which the singleton below
135
+ * always is.
136
+ */
137
+ function setLogLevel(level) {
138
+ configuredLevel = level;
139
+ }
115
140
  function getMinLevel() {
141
+ if (configuredLevel) return configuredLevel;
116
142
  const env = (hostEnv().LOG_LEVEL || "info").toLowerCase();
117
143
  if (env in LOG_PRIORITY) return env;
118
144
  return "info";
119
145
  }
120
146
  var FAILED_QUERY_MARKER = "Failed query:";
121
- var REDACTED_QUERY = "Failed query: [redacted]";
147
+ /**
148
+ * The marker says how to lift it.
149
+ *
150
+ * Every DDL, RLS and CDC failure ends at this string, and the statement is the
151
+ * whole diagnosis — three of them landed in one boot of a two-database project,
152
+ * each a dead end. The switch existed; nothing named it, in the log or in the
153
+ * docs, so `grep -rn REBASE_LOG_RAW_QUERIES` over the documentation, the
154
+ * templates and the agent skills came back empty.
155
+ */
156
+ var REDACTED_QUERY = "Failed query: [redacted — set REBASE_LOG_RAW_QUERIES=true in development to see it]";
122
157
  var REDACTED_VALUE = "[redacted]";
123
158
  /**
124
159
  * Key fragments whose values are never safe to publish. Compared against the
@@ -145,12 +180,21 @@ function isSensitiveKey(key) {
145
180
  return SENSITIVE_KEY_FRAGMENTS.some((fragment) => normalised.includes(fragment));
146
181
  }
147
182
  /**
148
- * Local escape hatch for the `Failed query:` strip only — the statement is the
149
- * fastest way to diagnose a failing query on a developer machine. Ignored in
183
+ * Whether a SQL statement may be written out at all.
184
+ *
185
+ * The escape hatch for the `Failed query:` strip — the statement is the fastest
186
+ * way to diagnose a failing query on a developer machine. Ignored in
150
187
  * production, so a runtime that inherits the variable cannot leak because of
151
188
  * it, and it never re-enables the key deny-list.
189
+ *
190
+ * Exported because it is the *only* answer to "may this process print SQL", and
191
+ * a driver that wants to trace what it executes has to ask the same question.
192
+ * The Postgres driver used to decide for itself, with a `console.debug` gated
193
+ * on `NODE_ENV` alone: every statement went to stdout whatever `LOG_LEVEL`
194
+ * said, and it went there without passing through the redaction that lives in
195
+ * this file.
152
196
  */
153
- function rawQueriesAllowed() {
197
+ function rawQueryLoggingEnabled() {
154
198
  return hostEnv().NODE_ENV !== "production" && hostEnv().REBASE_LOG_RAW_QUERIES === "true";
155
199
  }
156
200
  /**
@@ -167,12 +211,12 @@ function rawQueriesAllowed() {
167
211
  * before persisting and then logs the result.
168
212
  */
169
213
  function redactSensitiveText(text) {
170
- if (!text.includes(FAILED_QUERY_MARKER) || rawQueriesAllowed()) return text;
214
+ if (!text.includes(FAILED_QUERY_MARKER) || rawQueryLoggingEnabled()) return text;
171
215
  let out = text;
172
216
  let idx = out.indexOf(FAILED_QUERY_MARKER);
173
217
  while (idx !== -1) {
174
218
  if (out.startsWith(REDACTED_QUERY, idx)) {
175
- idx = out.indexOf(FAILED_QUERY_MARKER, idx + 24);
219
+ idx = out.indexOf(FAILED_QUERY_MARKER, idx + 83);
176
220
  continue;
177
221
  }
178
222
  const paramsIdx = out.indexOf("\nparams:", idx);
@@ -183,24 +227,76 @@ function redactSensitiveText(text) {
183
227
  end = eol === -1 ? out.length : eol;
184
228
  }
185
229
  out = out.slice(0, idx) + REDACTED_QUERY + out.slice(end);
186
- idx = out.indexOf(FAILED_QUERY_MARKER, idx + 24);
230
+ idx = out.indexOf(FAILED_QUERY_MARKER, idx + 83);
187
231
  }
188
232
  return out;
189
233
  }
190
234
  /**
191
- * Serialise an Error into a plain object (stack + message), with the query
192
- * text redacted out of both. `query`/`params` own-properties — which
193
- * `DrizzleQueryError` carries beside the message are deliberately not
194
- * copied.
235
+ * Diagnostic own-properties worth carrying up out of an error.
236
+ *
237
+ * These are what a socket failure actually says: `ECONNREFUSED` with the
238
+ * `address` and `port` it was refused on, `ENOTFOUND` with the hostname that
239
+ * did not resolve. They live as own-properties on the Node error rather than in
240
+ * its message, so a serialiser that copies only `message` and `stack` prints a
241
+ * boot failure that names no host, no port and no reason.
242
+ *
243
+ * Deliberately a fixed list rather than "every own-property": `DrizzleQueryError`
244
+ * carries `query` and `params` beside its message, and copying those would put
245
+ * the statement and its bound values — an email, a bcrypt hash — straight back
246
+ * on stdout, which is what the redaction above exists to prevent. Postgres's own
247
+ * `detail` and `hint` are left out for the same reason: `23505` reports
248
+ * `Key (email)=(a@b.c) already exists.`, which is a row's contents.
249
+ */
250
+ var ERROR_DETAIL_KEYS = [
251
+ "code",
252
+ "errno",
253
+ "syscall",
254
+ "address",
255
+ "port",
256
+ "hostname"
257
+ ];
258
+ /** How far the cause chain is followed before the serialiser gives up. */
259
+ var MAX_CAUSE_DEPTH = 4;
260
+ /** How many of an `AggregateError`'s children are serialised. */
261
+ var MAX_AGGREGATE_ERRORS = 4;
262
+ /**
263
+ * Serialise an Error into a plain object, with the query text redacted out of
264
+ * its message and stack. `query`/`params` own-properties — which
265
+ * `DrizzleQueryError` carries beside the message — are deliberately not copied.
266
+ *
267
+ * The chain matters more than the top. Everything a driver rethrows is a
268
+ * wrapper: Drizzle's is `Failed query: SELECT 1` with a stack through drizzle
269
+ * internals, and the sentence that says what is wrong — `connect ECONNREFUSED
270
+ * 127.0.0.1:5432`, `password authentication failed for user "app"` — sits in
271
+ * `.cause`, or inside the `AggregateError.errors` that `net` raises when every
272
+ * resolved address is refused. Serialising only the wrapper is why a boot
273
+ * against a stopped database used to log a redacted query and nothing else.
274
+ *
195
275
  * Handles non-Error values gracefully.
196
276
  */
197
- function serialiseError(value) {
198
- if (value instanceof Error) return {
277
+ function serialiseError(value, depth = 0) {
278
+ const isError = value instanceof Error;
279
+ if (!isError && !(!isError && depth > 0 && Boolean(value) && typeof value === "object" && !Array.isArray(value))) return { value: redactSensitiveText(String(value)) };
280
+ const own = value;
281
+ const out = isError ? {
199
282
  name: value.name,
200
283
  message: redactSensitiveText(value.message),
201
284
  stack: value.stack ? redactSensitiveText(value.stack) : void 0
285
+ } : {
286
+ ...typeof own.name === "string" ? { name: own.name } : {},
287
+ ...typeof own.message === "string" ? { message: redactSensitiveText(own.message) } : {}
202
288
  };
203
- return { value: redactSensitiveText(String(value)) };
289
+ for (const key of ERROR_DETAIL_KEYS) {
290
+ const detail = own[key];
291
+ if (detail === void 0 || detail === null) continue;
292
+ if (typeof detail === "object") continue;
293
+ out[key] = typeof detail === "string" ? redactSensitiveText(detail) : detail;
294
+ }
295
+ if (depth >= MAX_CAUSE_DEPTH) return out;
296
+ if (own.cause !== void 0 && own.cause !== null) out.cause = serialiseError(own.cause, depth + 1);
297
+ const aggregated = own.errors;
298
+ if (Array.isArray(aggregated) && aggregated.length > 0) out.errors = aggregated.slice(0, MAX_AGGREGATE_ERRORS).map((item) => serialiseError(item, depth + 1));
299
+ return out;
204
300
  }
205
301
  /**
206
302
  * Redact one logged value: errors are serialised, strings are stripped of
@@ -230,16 +326,49 @@ function formatData(data) {
230
326
  for (const [key, val] of Object.entries(data)) out[key] = isSensitiveKey(key) ? REDACTED_VALUE : redactValue(val, 0, seen);
231
327
  return out;
232
328
  }
329
+ var sinks = /* @__PURE__ */ new Set();
330
+ /**
331
+ * Tee this logger somewhere else. Returns the unsubscribe.
332
+ *
333
+ * The Studio's Logs Explorer is the caller: its ring buffer used to be fed only
334
+ * by a request middleware, so the panel showed a wall of `GET … 200` and not one
335
+ * of the errors, warnings or diagnoses the server was writing to stdout at the
336
+ * same moment. A log viewer that cannot show you an error is a log viewer
337
+ * nobody opens twice.
338
+ *
339
+ * A sink MUST NOT log. It is called from inside `emit`, so anything that comes
340
+ * back through `logger` recurses; the guard below stops the stack blowing, but
341
+ * the line is dropped rather than delivered, which is its own bug.
342
+ */
343
+ function addLogSink(sink) {
344
+ sinks.add(sink);
345
+ return () => {
346
+ sinks.delete(sink);
347
+ };
348
+ }
349
+ /** Re-entrancy guard: see `addLogSink`. */
350
+ var inSink = false;
351
+ function fanOut(level, message, data) {
352
+ if (sinks.size === 0 || inSink) return;
353
+ inSink = true;
354
+ try {
355
+ for (const sink of sinks) try {
356
+ sink(level, message, data);
357
+ } catch {}
358
+ } finally {
359
+ inSink = false;
360
+ }
361
+ }
233
362
  function createLogger(rawDefaultFields = {}) {
234
- const minLevel = getMinLevel();
235
363
  const defaultFields = formatData(rawDefaultFields) ?? {};
236
364
  function emit(level, message, data) {
237
- if (LOG_PRIORITY[level] < LOG_PRIORITY[minLevel]) return;
365
+ if (LOG_PRIORITY[level] < LOG_PRIORITY[getMinLevel()]) return;
238
366
  const safeMessage = redactSensitiveText(message);
239
367
  const merged = {
240
368
  ...defaultFields,
241
369
  ...formatData(data)
242
370
  };
371
+ fanOut(level, safeMessage, merged);
243
372
  if (isProduction()) {
244
373
  const entry = {
245
374
  severity: GCP_SEVERITY[level],
@@ -278,7 +407,57 @@ function createLogger(rawDefaultFields = {}) {
278
407
  * In development: emits human-readable prefixed lines.
279
408
  */
280
409
  var logger = createLogger();
410
+ /**
411
+ * The cause chain, one readable line per link.
412
+ *
413
+ * `serialiseError` puts the chain in the structured payload, which is the right
414
+ * place for a log aggregator and the wrong place for a person staring at a
415
+ * container that will not start: the sentence they need is inside a JSON blob
416
+ * behind an escaped stack trace. This renders the same chain as lines to print
417
+ * beside the headline, so the first thing on screen after "Failed to start" is
418
+ * `caused by: connect ECONNREFUSED 127.0.0.1:5432 (ECONNREFUSED)`.
419
+ *
420
+ * Redacted like everything else, and bounded by the same depth: a chain is
421
+ * usually two links and never usefully more than four.
422
+ */
423
+ function describeCauseChain(error) {
424
+ const lines = [];
425
+ const seen = /* @__PURE__ */ new Set();
426
+ const walk = (value, depth) => {
427
+ if (depth > MAX_CAUSE_DEPTH || value === void 0 || value === null) return;
428
+ if (typeof value === "object") {
429
+ if (seen.has(value)) return;
430
+ seen.add(value);
431
+ }
432
+ if (depth > 0) {
433
+ const described = describeOneCause(value);
434
+ if (described) lines.push(`caused by: ${described}`);
435
+ }
436
+ if (typeof value !== "object") return;
437
+ const own = value;
438
+ walk(own.cause, depth + 1);
439
+ const aggregated = own.errors;
440
+ if (Array.isArray(aggregated)) for (const item of aggregated.slice(0, MAX_AGGREGATE_ERRORS)) walk(item, depth + 1);
441
+ };
442
+ walk(error, 0);
443
+ return lines;
444
+ }
445
+ /** One cause rendered as `message (CODE) address:port`, or nothing to say. */
446
+ function describeOneCause(value) {
447
+ if (value === null || typeof value !== "object") return redactSensitiveText(String(value)) || void 0;
448
+ const own = value;
449
+ const message = typeof own.message === "string" && own.message ? redactSensitiveText(own.message) : void 0;
450
+ const code = typeof own.code === "string" ? own.code : void 0;
451
+ const endpoint = own.address !== void 0 && own.port !== void 0 ? `${String(own.address)}:${String(own.port)}` : void 0;
452
+ const where = endpoint && !(message ?? "").includes(endpoint) ? endpoint : void 0;
453
+ const parts = [
454
+ message ?? code,
455
+ code && message ? `(${code})` : void 0,
456
+ where
457
+ ].filter(Boolean);
458
+ return parts.length > 0 ? parts.join(" ") : void 0;
459
+ }
281
460
  //#endregion
282
- export { redactSensitiveText as n, hostEnv as r, logger as t };
461
+ export { redactSensitiveText as a, rawQueryLoggingEnabled as i, describeCauseChain as n, setLogLevel as o, logger as r, hostEnv as s, addLogSink as t };
283
462
 
284
- //# sourceMappingURL=logger-DS03e908.js.map
463
+ //# sourceMappingURL=logger-DO2PZc4i.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logger-DO2PZc4i.js","names":[],"sources":["../src/utils/host.ts","../src/utils/logger.ts"],"sourcesContent":["/**\n * The host globals this package reads, behind functions that do not assume Node.\n *\n * `process` is not defined on workerd, on Deno Deploy without the compat flag,\n * or in a browser. That matters here for one specific reason: the portable\n * authoring surface (`@rebasepro/server/functions`) reaches the logger and the\n * error handler, and a bare `process.env.NODE_ENV` inside either of them turns\n * the first log line of a request into a `ReferenceError` on a runtime that has\n * no `process` — a failure that reads as \"the framework crashed\" rather than\n * \"this runtime has no process object\".\n *\n * Nothing here throws and nothing here is async. A runtime that cannot answer\n * gets the empty answer, because every caller in this file's blast radius is\n * choosing a log level or a format, and the safe default for both is the\n * development one.\n *\n * @module\n */\n\n/**\n * Where an adapter with no `process` can publish the environment.\n *\n * Cloudflare Workers hand the environment to the *request*, not to the module,\n * so there is no global to read at import time. An edge adapter that has\n * already seen a request can stash the bag here and every contextless reader in\n * the framework — the logger, chiefly — starts answering correctly.\n *\n * `Symbol.for` rather than a module-local for the same reason the singleton\n * uses it: more than one copy of this module can be loaded into one process,\n * and a module-local would leave every copy but the writer's blind. See\n * `../singleton.ts`.\n *\n * Request-scoped code should NOT read this. Use `getEnv(c)` from\n * `@rebasepro/server/functions`, which reads the binding attached to the\n * request it is serving — the only correct source on a runtime where two\n * concurrent requests can carry different bindings.\n */\nconst ENV_SLOT = Symbol.for(\"@rebasepro/server:host-env\");\n\ntype GlobalWithEnv = typeof globalThis & {\n [ENV_SLOT]?: Record<string, string | undefined>;\n process?: { env?: Record<string, string | undefined> };\n};\n\n/**\n * The process environment, or the closest thing this runtime has to one.\n *\n * Order: a bag published by {@link setHostEnv} first, because an adapter that\n * set one knows more than the ambient globals do; then `process.env`; then\n * nothing.\n */\nexport function hostEnv(): Record<string, string | undefined> {\n const global = globalThis as GlobalWithEnv;\n return global[ENV_SLOT] ?? global.process?.env ?? {};\n}\n\n/**\n * Read one environment variable without touching `process` directly.\n *\n * Trimmed, and blank is treated as absent — a variable declared with no value\n * is the ordinary way to write a compose file or a `.env` line, and every\n * caller in this package means \"unset\" by it. See `resolveFunctionsTimeoutMs`,\n * which learned that the hard way.\n */\nexport function hostEnvVar(name: string): string | undefined {\n const raw = hostEnv()[name];\n if (typeof raw !== \"string\") return undefined;\n const trimmed = raw.trim();\n return trimmed === \"\" ? undefined : trimmed;\n}\n\n/**\n * Publish an environment bag for contextless readers.\n *\n * Called by an adapter for a runtime whose environment is not ambient. Merges\n * rather than replaces, so two adapters (or an adapter plus a test) do not\n * silently erase each other's variables.\n */\nexport function setHostEnv(env: Record<string, string | undefined>): void {\n const global = globalThis as GlobalWithEnv;\n global[ENV_SLOT] = {\n ...(global[ENV_SLOT] ?? {}),\n ...env\n };\n}\n\n/** @internal Test seam — drops anything {@link setHostEnv} published. */\nexport function _clearHostEnv(): void {\n delete (globalThis as GlobalWithEnv)[ENV_SLOT];\n}\n\ntype GlobalWithStdio = typeof globalThis & {\n process?: {\n stdout?: { write?: (chunk: string) => unknown };\n stderr?: { write?: (chunk: string) => unknown };\n };\n};\n\n/**\n * Write one already-formatted line to the process's output.\n *\n * `process.stdout.write` is preferred where it exists because it is the only\n * one of the two that does not append its own formatting to a line that is\n * already a complete JSON document — `console.log` on Node is\n * `process.stdout.write` plus `util.format`, and `util.format` will happily\n * reinterpret a `%s` that appeared inside a user's log message.\n *\n * Where it does not exist, `console` is the runtime's log sink and is what its\n * platform collects.\n */\nexport function writeLine(stream: \"out\" | \"err\", line: string): void {\n const proc = (globalThis as GlobalWithStdio).process;\n const sink = stream === \"err\" ? proc?.stderr : proc?.stdout;\n if (typeof sink?.write === \"function\") {\n sink.write(line + \"\\n\");\n return;\n }\n if (stream === \"err\") console.error(line);\n else console.log(line);\n}\n","/**\n * Structured Logger for Rebase Backend\n *\n * Outputs JSON lines when `NODE_ENV=production`, human-readable prefixed\n * lines otherwise. Designed to work with Google Cloud Logging severity levels.\n *\n * Every line — message and data, at any depth — passes through the redaction\n * below, which strips Drizzle's `Failed query: … / params: …` wrapper and the\n * values of secret-looking keys. See the block above `serialiseError`.\n *\n * Usage:\n * import { logger } from \"./utils/logger\";\n * logger.info(\"Server started\", { port: 3001 });\n * logger.error(\"Request failed\", { path: \"/api/test\", error: err });\n *\n * Every host global goes through `./host`, and that is load-bearing rather than\n * tidy: this module is reachable from `@rebasepro/server/functions`, the\n * authoring surface that has to import cleanly on a runtime with no `process`.\n * A bare `process.env.NODE_ENV` here would make the first log line of the first\n * request on workerd a `ReferenceError`.\n */\nimport { hostEnv, writeLine } from \"./host\";\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\n/** Google Cloud Logging severity strings. */\nconst GCP_SEVERITY: Record<LogLevel, string> = {\n debug: \"DEBUG\",\n info: \"INFO\",\n warn: \"WARNING\",\n error: \"ERROR\"\n};\n\nconst LOG_PRIORITY: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3\n};\n\nexport interface LogEntry {\n severity: string;\n message: string;\n timestamp: string;\n [key: string]: unknown;\n}\n\nexport interface Logger {\n debug(message: string, data?: Record<string, unknown>): void;\n info(message: string, data?: Record<string, unknown>): void;\n warn(message: string, data?: Record<string, unknown>): void;\n error(message: string, data?: Record<string, unknown>): void;\n child(defaultFields: Record<string, unknown>): Logger;\n}\n\nfunction isProduction(): boolean {\n return hostEnv().NODE_ENV === \"production\";\n}\n\n/**\n * An explicit level from `config.logging.level`, when a project set one.\n *\n * Outranks `LOG_LEVEL` because it is the more specific statement: an\n * environment variable is the deployment's default, and this is the\n * application saying what it wants regardless of where it runs.\n *\n * There used to be a second, separate mechanism for this — `utils/logging.ts`\n * reassigned `console.debug`/`console.log`/`console.warn` to no-ops — and the\n * two disagreed in a way nobody could have guessed from either: `LOG_LEVEL=warn`\n * silenced this logger's info lines *and* every `console.log` in the process,\n * including a dependency's, including a project's own debugging. It also could\n * not be undone, because the originals were gone.\n */\nlet configuredLevel: LogLevel | undefined;\n\n/**\n * Set the level from configuration. `undefined` returns to `LOG_LEVEL`.\n *\n * Read per line rather than captured at construction, so a logger created\n * before configuration is read still honours it — which the singleton below\n * always is.\n */\nexport function setLogLevel(level?: LogLevel): void {\n configuredLevel = level;\n}\n\nfunction getMinLevel(): LogLevel {\n if (configuredLevel) return configuredLevel;\n const env = (hostEnv().LOG_LEVEL || \"info\").toLowerCase();\n if (env in LOG_PRIORITY) return env as LogLevel;\n return \"info\";\n}\n\n// ── Redaction ───────────────────────────────────────────────────────\n//\n// Drizzle builds every query failure as\n// `Failed query: ${query}\\nparams: ${params}` (drizzle-orm/errors.js), so the\n// statement *and* every bound value ride along in `.message` and `.stack` of\n// whatever a driver rethrows — an email and a bcrypt hash reach stdout the\n// moment a registration hits a unique violation. The redaction lives here, in\n// the one function every log line passes through, rather than at the ~124\n// `{ error: … }` call sites: a per-site rule is what produced the leak (one\n// file suppressed the stack, four others did not), and the next caller would\n// reintroduce it. Nothing above this line needs to know about it.\n\nconst FAILED_QUERY_MARKER = \"Failed query:\";\n/**\n * The marker says how to lift it.\n *\n * Every DDL, RLS and CDC failure ends at this string, and the statement is the\n * whole diagnosis — three of them landed in one boot of a two-database project,\n * each a dead end. The switch existed; nothing named it, in the log or in the\n * docs, so `grep -rn REBASE_LOG_RAW_QUERIES` over the documentation, the\n * templates and the agent skills came back empty.\n */\nconst REDACTED_QUERY =\n \"Failed query: [redacted — set REBASE_LOG_RAW_QUERIES=true in development to see it]\";\nconst REDACTED_VALUE = \"[redacted]\";\n\n/**\n * Key fragments whose values are never safe to publish. Compared against the\n * key with separators and case removed, so `api_key`, `apiKey` and `API-KEY`\n * all match `apikey`.\n */\nconst SENSITIVE_KEY_FRAGMENTS = [\n \"password\",\n \"passwd\",\n \"passphrase\",\n \"secret\",\n \"token\",\n \"apikey\",\n \"authorization\",\n \"credential\",\n \"cookie\",\n \"privatekey\",\n \"sessionid\"\n];\n\n/** Longest structure the redactor will walk before giving up. */\nconst MAX_REDACT_DEPTH = 8;\n\nfunction isSensitiveKey(key: string): boolean {\n const normalised = key.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n return SENSITIVE_KEY_FRAGMENTS.some(fragment => normalised.includes(fragment));\n}\n\n/**\n * Whether a SQL statement may be written out at all.\n *\n * The escape hatch for the `Failed query:` strip — the statement is the fastest\n * way to diagnose a failing query on a developer machine. Ignored in\n * production, so a runtime that inherits the variable cannot leak because of\n * it, and it never re-enables the key deny-list.\n *\n * Exported because it is the *only* answer to \"may this process print SQL\", and\n * a driver that wants to trace what it executes has to ask the same question.\n * The Postgres driver used to decide for itself, with a `console.debug` gated\n * on `NODE_ENV` alone: every statement went to stdout whatever `LOG_LEVEL`\n * said, and it went there without passing through the redaction that lives in\n * this file.\n */\nexport function rawQueryLoggingEnabled(): boolean {\n return hostEnv().NODE_ENV !== \"production\"\n && hostEnv().REBASE_LOG_RAW_QUERIES === \"true\";\n}\n\n/**\n * Strip every `Failed query: … / params: …` span out of a message or stack,\n * keeping the surrounding text (including stack frames, which carry no user\n * data). When no `params:` line follows the marker the rest of the string is\n * dropped: a statement of unknown extent is treated as sensitive rather than\n * guessed at.\n *\n * Idempotent, and it has to be: an already-redacted span still starts with the\n * marker but has no `params:` line, so a second pass over it would fall into\n * the drop-the-rest branch and eat the stack frames behind it. Redaction runs\n * more than once on the same string in practice — the cron scheduler redacts\n * before persisting and then logs the result.\n */\nexport function redactSensitiveText(text: string): string {\n if (!text.includes(FAILED_QUERY_MARKER) || rawQueryLoggingEnabled()) return text;\n\n let out = text;\n let idx = out.indexOf(FAILED_QUERY_MARKER);\n while (idx !== -1) {\n if (out.startsWith(REDACTED_QUERY, idx)) {\n idx = out.indexOf(FAILED_QUERY_MARKER, idx + REDACTED_QUERY.length);\n continue;\n }\n const paramsIdx = out.indexOf(\"\\nparams:\", idx);\n let end: number;\n if (paramsIdx === -1) {\n end = out.length;\n } else {\n const eol = out.indexOf(\"\\n\", paramsIdx + 1);\n end = eol === -1 ? out.length : eol;\n }\n out = out.slice(0, idx) + REDACTED_QUERY + out.slice(end);\n idx = out.indexOf(FAILED_QUERY_MARKER, idx + REDACTED_QUERY.length);\n }\n return out;\n}\n\n/**\n * Diagnostic own-properties worth carrying up out of an error.\n *\n * These are what a socket failure actually says: `ECONNREFUSED` with the\n * `address` and `port` it was refused on, `ENOTFOUND` with the hostname that\n * did not resolve. They live as own-properties on the Node error rather than in\n * its message, so a serialiser that copies only `message` and `stack` prints a\n * boot failure that names no host, no port and no reason.\n *\n * Deliberately a fixed list rather than \"every own-property\": `DrizzleQueryError`\n * carries `query` and `params` beside its message, and copying those would put\n * the statement and its bound values — an email, a bcrypt hash — straight back\n * on stdout, which is what the redaction above exists to prevent. Postgres's own\n * `detail` and `hint` are left out for the same reason: `23505` reports\n * `Key (email)=(a@b.c) already exists.`, which is a row's contents.\n */\nconst ERROR_DETAIL_KEYS = [\"code\", \"errno\", \"syscall\", \"address\", \"port\", \"hostname\"] as const;\n\n/** How far the cause chain is followed before the serialiser gives up. */\nconst MAX_CAUSE_DEPTH = 4;\n\n/** How many of an `AggregateError`'s children are serialised. */\nconst MAX_AGGREGATE_ERRORS = 4;\n\n/**\n * Serialise an Error into a plain object, with the query text redacted out of\n * its message and stack. `query`/`params` own-properties — which\n * `DrizzleQueryError` carries beside the message — are deliberately not copied.\n *\n * The chain matters more than the top. Everything a driver rethrows is a\n * wrapper: Drizzle's is `Failed query: SELECT 1` with a stack through drizzle\n * internals, and the sentence that says what is wrong — `connect ECONNREFUSED\n * 127.0.0.1:5432`, `password authentication failed for user \"app\"` — sits in\n * `.cause`, or inside the `AggregateError.errors` that `net` raises when every\n * resolved address is refused. Serialising only the wrapper is why a boot\n * against a stopped database used to log a redacted query and nothing else.\n *\n * Handles non-Error values gracefully.\n */\nfunction serialiseError(value: unknown, depth = 0): Record<string, unknown> {\n const isError = value instanceof Error;\n // A cause is not always an Error: drivers throw plain `{ code, address,\n // port }` bags, and stringifying one yields `[object Object]`, which is\n // worse than nothing. Only the named fields are copied out of it — the same\n // fixed list, for the same reason.\n const isDetailBag = !isError && depth > 0 && Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n if (!isError && !isDetailBag) {\n return { value: redactSensitiveText(String(value)) };\n }\n\n const own = value as unknown as Record<string, unknown>;\n const out: Record<string, unknown> = isError\n ? {\n name: (value as Error).name,\n message: redactSensitiveText((value as Error).message),\n stack: (value as Error).stack ? redactSensitiveText((value as Error).stack as string) : undefined\n }\n : {\n ...(typeof own.name === \"string\" ? { name: own.name } : {}),\n ...(typeof own.message === \"string\" ? { message: redactSensitiveText(own.message) } : {})\n };\n\n for (const key of ERROR_DETAIL_KEYS) {\n const detail = own[key];\n if (detail === undefined || detail === null) continue;\n if (typeof detail === \"object\") continue;\n out[key] = typeof detail === \"string\" ? redactSensitiveText(detail) : detail;\n }\n\n if (depth >= MAX_CAUSE_DEPTH) return out;\n\n if (own.cause !== undefined && own.cause !== null) {\n out.cause = serialiseError(own.cause, depth + 1);\n }\n const aggregated = own.errors;\n if (Array.isArray(aggregated) && aggregated.length > 0) {\n out.errors = aggregated\n .slice(0, MAX_AGGREGATE_ERRORS)\n .map(item => serialiseError(item, depth + 1));\n }\n return out;\n}\n\n/**\n * Redact one logged value: errors are serialised, strings are stripped of\n * query text, objects and arrays are walked. Cycles and over-deep structures\n * collapse to a marker rather than throwing — a logger that can fail is worse\n * than one that logs less. (An object referenced twice in one payload is\n * reported as `[circular]` the second time; bounding the walk matters more\n * than rendering a shared reference twice.)\n */\nfunction redactValue(value: unknown, depth: number, seen: WeakSet<object>): unknown {\n // `serialiseError` returns only already-redacted strings, so it is the\n // terminal step — walking its output again would redact twice.\n if (value instanceof Error) return serialiseError(value);\n if (typeof value === \"string\") return redactSensitiveText(value);\n if (value === null || typeof value !== \"object\") return value;\n if (depth >= MAX_REDACT_DEPTH) return \"[truncated]\";\n if (seen.has(value)) return \"[circular]\";\n seen.add(value);\n\n if (Array.isArray(value)) {\n return value.map(item => redactValue(item, depth + 1, seen));\n }\n if (value instanceof Date) return value;\n\n const out: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value as Record<string, unknown>)) {\n out[key] = isSensitiveKey(key) ? REDACTED_VALUE : redactValue(val, depth + 1, seen);\n }\n return out;\n}\n\nfunction formatData(data?: Record<string, unknown>): Record<string, unknown> | undefined {\n if (!data) return undefined;\n const seen = new WeakSet<object>();\n const out: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(data)) {\n out[key] = isSensitiveKey(key) ? REDACTED_VALUE : redactValue(val, 0, seen);\n }\n return out;\n}\n\n/**\n * Something that wants a copy of every line this logger writes.\n *\n * Receives the message and fields *after* redaction, never before: a sink is\n * another destination for the same line, and the one thing that must not vary\n * by destination is whether the query and its bound values are in it.\n */\nexport type LogSink = (\n level: LogLevel,\n message: string,\n data: Record<string, unknown>\n) => void;\n\nconst sinks = new Set<LogSink>();\n\n/**\n * Tee this logger somewhere else. Returns the unsubscribe.\n *\n * The Studio's Logs Explorer is the caller: its ring buffer used to be fed only\n * by a request middleware, so the panel showed a wall of `GET … 200` and not one\n * of the errors, warnings or diagnoses the server was writing to stdout at the\n * same moment. A log viewer that cannot show you an error is a log viewer\n * nobody opens twice.\n *\n * A sink MUST NOT log. It is called from inside `emit`, so anything that comes\n * back through `logger` recurses; the guard below stops the stack blowing, but\n * the line is dropped rather than delivered, which is its own bug.\n */\nexport function addLogSink(sink: LogSink): () => void {\n sinks.add(sink);\n return () => { sinks.delete(sink); };\n}\n\n/** Re-entrancy guard: see `addLogSink`. */\nlet inSink = false;\n\nfunction fanOut(level: LogLevel, message: string, data: Record<string, unknown>): void {\n if (sinks.size === 0 || inSink) return;\n inSink = true;\n try {\n for (const sink of sinks) {\n // One broken sink must not take down the line, nor the request that\n // was writing it.\n try { sink(level, message, data); } catch { /* a broken tee is not the caller's problem */ }\n }\n } finally {\n inSink = false;\n }\n}\n\nfunction createLogger(rawDefaultFields: Record<string, unknown> = {}): Logger {\n // Child fields go through the same pass as per-call data — they are merged\n // into every line this logger emits, so leaving them raw would be a hole\n // the moment `child()` gets its first caller.\n const defaultFields = formatData(rawDefaultFields) ?? {};\n\n function emit(level: LogLevel, message: string, data?: Record<string, unknown>): void {\n // Per line, not captured at construction: the singleton is created when\n // this module is first imported, which is long before a project's\n // `config.logging.level` has been read.\n if (LOG_PRIORITY[level] < LOG_PRIORITY[getMinLevel()]) return;\n\n // The message is redacted too, not just the data: several call sites\n // interpolate `error.message` straight into the line they log.\n const safeMessage = redactSensitiveText(message);\n const merged = { ...defaultFields,\n...formatData(data) };\n\n // Before the write, so a sink still sees the line if stdout is the\n // thing that is broken.\n fanOut(level, safeMessage, merged);\n\n if (isProduction()) {\n // Structured JSON for Cloud Logging\n const entry: LogEntry = {\n severity: GCP_SEVERITY[level],\n message: safeMessage,\n timestamp: new Date().toISOString(),\n ...merged\n };\n const line = JSON.stringify(entry);\n\n if (level === \"error\") {\n writeLine(\"err\", line);\n } else {\n writeLine(\"out\", line);\n }\n } else {\n // Human-readable for development\n const prefix = level === \"error\" ? \"❌\"\n : level === \"warn\" ? \"⚠️\"\n : level === \"info\" ? \"ℹ️\"\n : \"🐛\";\n const extra = Object.keys(merged).length > 0 ? ` ${JSON.stringify(merged)}` : \"\";\n const out = `${prefix} [${level.toUpperCase()}] ${safeMessage}${extra}`;\n\n if (level === \"error\") {\n console.error(out);\n } else if (level === \"warn\") {\n console.warn(out);\n } else {\n console.log(out);\n }\n }\n }\n\n return {\n debug: (msg, data) => emit(\"debug\", msg, data),\n info: (msg, data) => emit(\"info\", msg, data),\n warn: (msg, data) => emit(\"warn\", msg, data),\n error: (msg, data) => emit(\"error\", msg, data),\n child(fields: Record<string, unknown>): Logger {\n return createLogger({ ...defaultFields,\n...fields });\n }\n };\n}\n\n/**\n * Singleton logger instance.\n * In production: emits JSON lines with `severity`, `message`, `timestamp`.\n * In development: emits human-readable prefixed lines.\n */\nexport const logger: Logger = createLogger();\n\n/**\n * The cause chain, one readable line per link.\n *\n * `serialiseError` puts the chain in the structured payload, which is the right\n * place for a log aggregator and the wrong place for a person staring at a\n * container that will not start: the sentence they need is inside a JSON blob\n * behind an escaped stack trace. This renders the same chain as lines to print\n * beside the headline, so the first thing on screen after \"Failed to start\" is\n * `caused by: connect ECONNREFUSED 127.0.0.1:5432 (ECONNREFUSED)`.\n *\n * Redacted like everything else, and bounded by the same depth: a chain is\n * usually two links and never usefully more than four.\n */\nexport function describeCauseChain(error: unknown): string[] {\n const lines: string[] = [];\n const seen = new Set<unknown>();\n\n const walk = (value: unknown, depth: number): void => {\n if (depth > MAX_CAUSE_DEPTH || value === undefined || value === null) return;\n if (typeof value === \"object\") {\n if (seen.has(value)) return;\n seen.add(value);\n }\n if (depth > 0) {\n const described = describeOneCause(value);\n if (described) lines.push(`caused by: ${described}`);\n }\n if (typeof value !== \"object\") return;\n const own = value as Record<string, unknown>;\n walk(own.cause, depth + 1);\n const aggregated = own.errors;\n if (Array.isArray(aggregated)) {\n for (const item of aggregated.slice(0, MAX_AGGREGATE_ERRORS)) walk(item, depth + 1);\n }\n };\n\n walk(error, 0);\n return lines;\n}\n\n/** One cause rendered as `message (CODE) address:port`, or nothing to say. */\nfunction describeOneCause(value: unknown): string | undefined {\n if (value === null || typeof value !== \"object\") {\n const text = redactSensitiveText(String(value));\n return text || undefined;\n }\n const own = value as Record<string, unknown>;\n const message = typeof own.message === \"string\" && own.message\n ? redactSensitiveText(own.message)\n : undefined;\n const code = typeof own.code === \"string\" ? own.code : undefined;\n // Only when the message does not already carry it. Node writes\n // `connect ECONNREFUSED 127.0.0.1:5432` and also sets `address`/`port`, and\n // repeating the endpoint reads like two different facts.\n const endpoint = own.address !== undefined && own.port !== undefined\n ? `${String(own.address)}:${String(own.port)}`\n : undefined;\n const where = endpoint && !(message ?? \"\").includes(endpoint) ? endpoint : undefined;\n const parts = [message ?? code, code && message ? `(${code})` : undefined, where]\n .filter(Boolean);\n return parts.length > 0 ? parts.join(\" \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