@gusto/baerly-storage 0.3.0 → 0.4.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 (141) hide show
  1. package/README.md +157 -92
  2. package/dist/API.md +64 -32
  3. package/dist/CHANGELOG.md +295 -5
  4. package/dist/RECIPES.md +125 -0
  5. package/dist/THIRD-PARTY-LICENSES.txt +22 -96
  6. package/dist/{app-config-BIzyAKzy.d.ts → app-config-DyiFK3_k.d.ts} +43 -11
  7. package/dist/app-config.d.ts +1 -1
  8. package/dist/auth.d.ts +1 -1
  9. package/dist/auth.js +13 -13
  10. package/dist/auth.js.map +1 -1
  11. package/dist/aws4fetch.esm-p7eEzLCs.js +1702 -0
  12. package/dist/aws4fetch.esm-p7eEzLCs.js.map +1 -0
  13. package/dist/baerly.js +35 -15
  14. package/dist/baerly.js.map +1 -1
  15. package/dist/baerly.spec.json +342 -0
  16. package/dist/{client-BJXF3XJA.d.ts → client-Fe8CwB73.d.ts} +3 -3
  17. package/dist/client-react.d.ts +3 -3
  18. package/dist/client-react.js +4 -4
  19. package/dist/client-react.js.map +1 -1
  20. package/dist/client.d.ts +4 -4
  21. package/dist/client.js +3 -3
  22. package/dist/{cloudflare-Cn2ibODt.js → cloudflare-DzKBrUlg.js} +2 -2
  23. package/dist/{cloudflare-Cn2ibODt.js.map → cloudflare-DzKBrUlg.js.map} +1 -1
  24. package/dist/cloudflare.d.ts +49 -6
  25. package/dist/cloudflare.js +55 -21
  26. package/dist/cloudflare.js.map +1 -1
  27. package/dist/config-1tv0-Yzm.js +2693 -0
  28. package/dist/config-1tv0-Yzm.js.map +1 -0
  29. package/dist/constants-CfeMWQWk.js +222 -0
  30. package/dist/constants-CfeMWQWk.js.map +1 -0
  31. package/dist/{cost-BZ_MDBmn.js → cost-DSMIVqzL.js} +42 -43
  32. package/dist/cost-DSMIVqzL.js.map +1 -0
  33. package/dist/{current-json-DsN7FNY1.js → current-json-C6nhPOm1.js} +6 -204
  34. package/dist/current-json-C6nhPOm1.js.map +1 -0
  35. package/dist/{db-CCT6tDfY.d.ts → db-DsPkOVEH.d.ts} +3 -3
  36. package/dist/{deploy-BKKyGlSJ.js → deploy-DonTr-CV.js} +4 -4
  37. package/dist/{deploy-BKKyGlSJ.js.map → deploy-DonTr-CV.js.map} +1 -1
  38. package/dist/dev-vite.d.ts +9 -5
  39. package/dist/dev-vite.js +5 -4
  40. package/dist/dev-vite.js.map +1 -1
  41. package/dist/dev.d.ts +1 -1
  42. package/dist/dev.js +1 -1
  43. package/dist/{doctor-BVU4GNXN.js → doctor-DSIyCDg_.js} +5 -8
  44. package/dist/{doctor-BVU4GNXN.js.map → doctor-DSIyCDg_.js.map} +1 -1
  45. package/dist/{dump-DPEAKub6.js → dump-Bh5k26VQ.js} +9 -32
  46. package/dist/dump-Bh5k26VQ.js.map +1 -0
  47. package/dist/{errors-DOdL95kK.js → errors-Dfa3p78c.js} +25 -5
  48. package/dist/errors-Dfa3p78c.js.map +1 -0
  49. package/dist/{export-BcuCLFFe.js → export-DtF5tDIM.js} +9 -32
  50. package/dist/{export-BcuCLFFe.js.map → export-DtF5tDIM.js.map} +1 -1
  51. package/dist/{fsck-RXgLOaJG.js → fsck-D_djMO5D.js} +10 -33
  52. package/dist/fsck-D_djMO5D.js.map +1 -0
  53. package/dist/{http-Bd4byR4n.js → http-DxM9MflO.js} +123 -35
  54. package/dist/http-DxM9MflO.js.map +1 -0
  55. package/dist/http.d.ts +42 -26
  56. package/dist/http.js +3 -2
  57. package/dist/{index-DnBGSeuU.d.ts → index-0rZcMBwy.d.ts} +2 -2
  58. package/dist/{index-Cmsxx-ZN.d.ts → index-B6oexfOB.d.ts} +7 -7
  59. package/dist/{index-BDceQQi-.d.ts → index-BNRh23K9.d.ts} +4 -4
  60. package/dist/{index-DW7GT6M2.d.ts → index-BYk9oCNf.d.ts} +193 -163
  61. package/dist/index.d.ts +6 -6
  62. package/dist/index.js +4 -4
  63. package/dist/{indexes-Cx7uMXm0.d.ts → indexes-Dn9hbGQG.d.ts} +2 -2
  64. package/dist/{inspect-DhI49PSi.js → inspect-6WZ-pC7-.js} +10 -33
  65. package/dist/inspect-6WZ-pC7-.js.map +1 -0
  66. package/dist/key-Di6yyxFu.js +35 -0
  67. package/dist/key-Di6yyxFu.js.map +1 -0
  68. package/dist/{log-tail-DXeDkWEp.js → log-tail-D98U1JBo.js} +31 -7
  69. package/dist/log-tail-D98U1JBo.js.map +1 -0
  70. package/dist/{maintenance-CWBQpZ2y.js → maintenance-B4Dki6Ig.js} +77 -22
  71. package/dist/maintenance-B4Dki6Ig.js.map +1 -0
  72. package/dist/{maintenance-BkhUr72A.d.ts → maintenance-B_e0T99L.d.ts} +28 -5
  73. package/dist/{maintenance-C_KSkVjd.js → maintenance-C7coQp4c.js} +17 -16
  74. package/dist/maintenance-C7coQp4c.js.map +1 -0
  75. package/dist/maintenance.d.ts +3 -3
  76. package/dist/maintenance.js +3 -3
  77. package/dist/node.d.ts +168 -65
  78. package/dist/node.js +3 -2
  79. package/dist/{normalize-XWY25_sG.js → normalize-rjnZLwS4.js} +2 -2
  80. package/dist/normalize-rjnZLwS4.js.map +1 -0
  81. package/dist/{observability-BYd-RzEx.js → observability-wzs3-BL_.js} +233 -71
  82. package/dist/observability-wzs3-BL_.js.map +1 -0
  83. package/dist/observability.d.ts +2 -2
  84. package/dist/observability.js +1 -1
  85. package/dist/{plan-DIu_B6fy.js → plan-a7PJHBCy.js} +2 -2
  86. package/dist/{plan-DIu_B6fy.js.map → plan-a7PJHBCy.js.map} +1 -1
  87. package/dist/{query-sQNO5vU_.js → query-rAtXNQQB.js} +96 -207
  88. package/dist/query-rAtXNQQB.js.map +1 -0
  89. package/dist/{rebuild-index-DP4CqSSs.js → rebuild-index-BVzQSZlm.js} +9 -32
  90. package/dist/rebuild-index-BVzQSZlm.js.map +1 -0
  91. package/dist/{request-BEF_OvMh.js → request-u0M51mhJ.js} +3 -3
  92. package/dist/{request-BEF_OvMh.js.map → request-u0M51mhJ.js.map} +1 -1
  93. package/dist/{restore-DpQYef6r.js → restore-R-4rbciV.js} +73 -100
  94. package/dist/restore-R-4rbciV.js.map +1 -0
  95. package/dist/runtime-spec-qL3_lTTU.js +391 -0
  96. package/dist/runtime-spec-qL3_lTTU.js.map +1 -0
  97. package/dist/s3-http-B-z8th6O.d.ts +60 -0
  98. package/dist/s3.d.ts +47 -0
  99. package/dist/s3.js +45 -0
  100. package/dist/s3.js.map +1 -0
  101. package/dist/{shared-secret-BJdSwpgw.js → shared-secret-DgEicd3x.js} +13 -5
  102. package/dist/shared-secret-DgEicd3x.js.map +1 -0
  103. package/dist/src-BG20LZs7.js +2271 -0
  104. package/dist/src-BG20LZs7.js.map +1 -0
  105. package/dist/{src-Db4-qVtM.js → src-CYHFDrKz.js} +51 -8
  106. package/dist/src-CYHFDrKz.js.map +1 -0
  107. package/dist/{src-CWpkSbvJ.js → src-DYZ4H1aF.js} +6 -5
  108. package/dist/src-DYZ4H1aF.js.map +1 -0
  109. package/dist/{subcommand-CP9NY2J4.js → subcommand-DoDA-K7d.js} +44 -6
  110. package/dist/subcommand-DoDA-K7d.js.map +1 -0
  111. package/dist/time-DUqvFMHq.js +119 -0
  112. package/dist/time-DUqvFMHq.js.map +1 -0
  113. package/dist/{usage-CTfDq9HR.js → usage-DBV1eQHC.js} +7 -22
  114. package/dist/usage-DBV1eQHC.js.map +1 -0
  115. package/dist/wire-izfGZDvr.js.map +1 -1
  116. package/package.json +52 -28
  117. package/dist/config-CGyBopy3.js +0 -5326
  118. package/dist/config-CGyBopy3.js.map +0 -1
  119. package/dist/cost-BZ_MDBmn.js.map +0 -1
  120. package/dist/current-json-DsN7FNY1.js.map +0 -1
  121. package/dist/dump-DPEAKub6.js.map +0 -1
  122. package/dist/errors-DOdL95kK.js.map +0 -1
  123. package/dist/fsck-RXgLOaJG.js.map +0 -1
  124. package/dist/http-Bd4byR4n.js.map +0 -1
  125. package/dist/inspect-DhI49PSi.js.map +0 -1
  126. package/dist/log-tail-DXeDkWEp.js.map +0 -1
  127. package/dist/maintenance-CWBQpZ2y.js.map +0 -1
  128. package/dist/maintenance-C_KSkVjd.js.map +0 -1
  129. package/dist/normalize-XWY25_sG.js.map +0 -1
  130. package/dist/observability-BYd-RzEx.js.map +0 -1
  131. package/dist/query-sQNO5vU_.js.map +0 -1
  132. package/dist/rebuild-index-DP4CqSSs.js.map +0 -1
  133. package/dist/restore-DpQYef6r.js.map +0 -1
  134. package/dist/shared-secret-BJdSwpgw.js.map +0 -1
  135. package/dist/src-CWpkSbvJ.js.map +0 -1
  136. package/dist/src-D24wDpzR.js +0 -6247
  137. package/dist/src-D24wDpzR.js.map +0 -1
  138. package/dist/src-Db4-qVtM.js.map +0 -1
  139. package/dist/subcommand-CP9NY2J4.js.map +0 -1
  140. package/dist/usage-CTfDq9HR.js.map +0 -1
  141. /package/dist/{chunk-EAsCxrDo.js → rolldown-runtime-EAsCxrDo.js} +0 -0
@@ -0,0 +1,391 @@
1
+ //#endregion
2
+ //#region packages/server/src/spec/runtime-spec.ts
3
+ const specIr = {
4
+ $schema: "https://baerly.dev/spec/ir-schema.json",
5
+ specVersion: "1",
6
+ kernelVersion: "0.3.0",
7
+ errorCodes: [
8
+ {
9
+ "code": "InvalidConfig",
10
+ "httpStatus": 400,
11
+ "retriable": false,
12
+ "messagePolicy": "contextual",
13
+ "summary": "Caller config or input is invalid."
14
+ },
15
+ {
16
+ "code": "NetworkError",
17
+ "httpStatus": 502,
18
+ "retriable": true,
19
+ "messagePolicy": "scrubbed",
20
+ "summary": "S3/HTTP transport failure (5xx, retries exhausted)."
21
+ },
22
+ {
23
+ "code": "AccessDenied",
24
+ "httpStatus": 403,
25
+ "retriable": false,
26
+ "messagePolicy": "scrubbed",
27
+ "summary": "S3 returned 403 — credentials or bucket policy."
28
+ },
29
+ {
30
+ "code": "InvalidResponse",
31
+ "httpStatus": 502,
32
+ "retriable": false,
33
+ "messagePolicy": "scrubbed",
34
+ "summary": "Server returned unparseable data."
35
+ },
36
+ {
37
+ "code": "Internal",
38
+ "httpStatus": 500,
39
+ "retriable": false,
40
+ "messagePolicy": "scrubbed",
41
+ "summary": "Internal invariant violation — file a bug."
42
+ },
43
+ {
44
+ "code": "SchemaError",
45
+ "httpStatus": 400,
46
+ "retriable": false,
47
+ "messagePolicy": "public",
48
+ "summary": "Document body failed schema validation; carries .issues."
49
+ },
50
+ {
51
+ "code": "Conflict",
52
+ "httpStatus": 409,
53
+ "retriable": true,
54
+ "messagePolicy": "contextual",
55
+ "summary": "Write conflicted (CAS exhausted, duplicate _id, guarded key)."
56
+ },
57
+ {
58
+ "code": "Unauthorized",
59
+ "httpStatus": 401,
60
+ "retriable": false,
61
+ "messagePolicy": "public",
62
+ "summary": "Verifier returned no identity."
63
+ },
64
+ {
65
+ "code": "NotFound",
66
+ "httpStatus": 404,
67
+ "retriable": false,
68
+ "messagePolicy": "public",
69
+ "summary": "Addressed resource does not exist."
70
+ },
71
+ {
72
+ "code": "PayloadTooLarge",
73
+ "httpStatus": 413,
74
+ "retriable": false,
75
+ "messagePolicy": "public",
76
+ "summary": "Request body exceeded MAX_BODY_BYTES."
77
+ },
78
+ {
79
+ "code": "UnsatisfiablePredicate",
80
+ "httpStatus": 400,
81
+ "retriable": false,
82
+ "messagePolicy": "public",
83
+ "summary": "Predicate is well-formed but contradicts itself."
84
+ },
85
+ {
86
+ "code": "UseQueryAwaitedRecorder",
87
+ "httpStatus": null,
88
+ "retriable": false,
89
+ "messagePolicy": "not-on-http",
90
+ "summary": "A useQuery callback awaited a recorder terminal."
91
+ },
92
+ {
93
+ "code": "UnexpectedWriteInQuery",
94
+ "httpStatus": null,
95
+ "retriable": false,
96
+ "messagePolicy": "not-on-http",
97
+ "summary": "A write verb was called inside a useQuery callback."
98
+ },
99
+ {
100
+ "code": "MutationFailed",
101
+ "httpStatus": null,
102
+ "retriable": false,
103
+ "messagePolicy": "not-on-http",
104
+ "summary": "A useMutation callback rejected with a non-BaerlyError."
105
+ }
106
+ ],
107
+ operators: [
108
+ {
109
+ "name": "eq",
110
+ "valueType": "equality",
111
+ "summary": "Strict equality."
112
+ },
113
+ {
114
+ "name": "gt",
115
+ "valueType": "range",
116
+ "summary": "Greater-than; bound is string or finite number."
117
+ },
118
+ {
119
+ "name": "gte",
120
+ "valueType": "range",
121
+ "summary": "Greater-or-equal; bound is string or finite number."
122
+ },
123
+ {
124
+ "name": "lt",
125
+ "valueType": "range",
126
+ "summary": "Less-than; bound is string or finite number."
127
+ },
128
+ {
129
+ "name": "lte",
130
+ "valueType": "range",
131
+ "summary": "Less-or-equal; bound is string or finite number."
132
+ },
133
+ {
134
+ "name": "in",
135
+ "valueType": "set",
136
+ "summary": "Set membership; empty array → UnsatisfiablePredicate."
137
+ }
138
+ ],
139
+ collectionMethods: [
140
+ {
141
+ "name": "first",
142
+ "params": "",
143
+ "returns": "Promise<T | undefined>"
144
+ },
145
+ {
146
+ "name": "all",
147
+ "params": "",
148
+ "returns": "Promise<T[]>"
149
+ },
150
+ {
151
+ "name": "count",
152
+ "params": "",
153
+ "returns": "Promise<number>"
154
+ },
155
+ {
156
+ "name": "get",
157
+ "params": "id: string",
158
+ "returns": "Promise<T | undefined>"
159
+ },
160
+ {
161
+ "name": "where",
162
+ "params": "predicate: PredicateArg<T>",
163
+ "returns": "Query<T>"
164
+ },
165
+ {
166
+ "name": "order",
167
+ "params": "spec: OrderSpec<T>",
168
+ "returns": "Query<T>"
169
+ },
170
+ {
171
+ "name": "limit",
172
+ "params": "n: number",
173
+ "returns": "Query<T>"
174
+ },
175
+ {
176
+ "name": "insert",
177
+ "params": "doc: Partial<T> & DocumentData",
178
+ "returns": "Promise<{ _id: string }>",
179
+ "throws": ["SchemaError", "Conflict"]
180
+ },
181
+ {
182
+ "name": "update",
183
+ "params": "id: string, patch: Partial<T>",
184
+ "returns": "Promise<{ modified: number }>",
185
+ "throws": ["SchemaError", "Conflict"]
186
+ },
187
+ {
188
+ "name": "replace",
189
+ "params": "id: string, doc: T",
190
+ "returns": "Promise<void>",
191
+ "throws": [
192
+ "SchemaError",
193
+ "Conflict",
194
+ "NotFound"
195
+ ]
196
+ },
197
+ {
198
+ "name": "delete",
199
+ "params": "id: string",
200
+ "returns": "Promise<{ deleted: number }>",
201
+ "throws": ["Conflict"]
202
+ }
203
+ ],
204
+ queryMethods: [
205
+ {
206
+ "name": "where",
207
+ "params": "predicate: PredicateArg<T>",
208
+ "returns": "Query<T>"
209
+ },
210
+ {
211
+ "name": "order",
212
+ "params": "spec: OrderSpec<T>",
213
+ "returns": "Query<T>"
214
+ },
215
+ {
216
+ "name": "limit",
217
+ "params": "n: number",
218
+ "returns": "Query<T>"
219
+ },
220
+ {
221
+ "name": "first",
222
+ "params": "",
223
+ "returns": "Promise<T | undefined>"
224
+ },
225
+ {
226
+ "name": "all",
227
+ "params": "",
228
+ "returns": "Promise<T[]>"
229
+ },
230
+ {
231
+ "name": "count",
232
+ "params": "",
233
+ "returns": "Promise<number>"
234
+ },
235
+ {
236
+ "name": "update",
237
+ "params": "patch: Partial<T>",
238
+ "returns": "Promise<{ modified: number }>",
239
+ "throws": ["SchemaError", "Conflict"]
240
+ },
241
+ {
242
+ "name": "delete",
243
+ "params": "",
244
+ "returns": "Promise<{ deleted: number }>",
245
+ "throws": ["Conflict"]
246
+ }
247
+ ],
248
+ storageInterface: [
249
+ {
250
+ "name": "get",
251
+ "params": "key: string, opts?: StorageGetOptions",
252
+ "returns": "Promise<StorageGetResult | null>"
253
+ },
254
+ {
255
+ "name": "put",
256
+ "params": "key: string, body: Uint8Array, opts?: StoragePutOptions",
257
+ "returns": "Promise<StoragePutResult>"
258
+ },
259
+ {
260
+ "name": "delete",
261
+ "params": "key: string, opts?: { signal?: AbortSignal }",
262
+ "returns": "Promise<void>"
263
+ },
264
+ {
265
+ "name": "list",
266
+ "params": "prefix: string, opts?: { startAfter?: string; maxKeys?: number; signal?: AbortSignal }",
267
+ "returns": "AsyncIterable<StorageListEntry>"
268
+ }
269
+ ],
270
+ predicateWire: {
271
+ "clause": {
272
+ "op": "PredicateOpName",
273
+ "field": "string (top-level key or dotted path)",
274
+ "value": "DocumentValue | DocumentValue[] (array iff op==='in')"
275
+ },
276
+ "envelope": { "clauses": "PredicateClause[] (AND across clauses; empty → match-all)" }
277
+ },
278
+ schemaContract: {
279
+ "adapter": "StandardSchemaV1",
280
+ "validatesPostImage": true,
281
+ "idRequired": true,
282
+ "rejectsWith": "SchemaError"
283
+ },
284
+ httpRoutes: [
285
+ {
286
+ "method": "GET",
287
+ "path": "/v1/healthz",
288
+ "auth": "anonymous",
289
+ "summary": "Liveness probe."
290
+ },
291
+ {
292
+ "method": "GET",
293
+ "path": "/v1/spec",
294
+ "auth": "anonymous",
295
+ "summary": "Machine-readable contract; tenant collections only when authed."
296
+ },
297
+ {
298
+ "method": "GET",
299
+ "path": "/v1/c/:collection",
300
+ "auth": "verified",
301
+ "summary": "Read/query a collection (?where=, ?order=, ?limit=)."
302
+ },
303
+ {
304
+ "method": "GET",
305
+ "path": "/v1/c/:collection/:id",
306
+ "auth": "verified",
307
+ "summary": "Read one document by id (404 when absent)."
308
+ },
309
+ {
310
+ "method": "POST",
311
+ "path": "/v1/c/:collection",
312
+ "auth": "verified",
313
+ "summary": "Insert a document."
314
+ },
315
+ {
316
+ "method": "PATCH",
317
+ "path": "/v1/c/:collection/:id",
318
+ "auth": "verified",
319
+ "summary": "Merge-patch a document by id (body { patch })."
320
+ },
321
+ {
322
+ "method": "PUT",
323
+ "path": "/v1/c/:collection/:id",
324
+ "auth": "verified",
325
+ "summary": "Replace a document by id (body { doc })."
326
+ },
327
+ {
328
+ "method": "DELETE",
329
+ "path": "/v1/c/:collection/:id",
330
+ "auth": "verified",
331
+ "summary": "Delete a document by id (204; 404 when absent)."
332
+ },
333
+ {
334
+ "method": "GET",
335
+ "path": "/v1/count",
336
+ "auth": "verified",
337
+ "summary": "Count matching rows."
338
+ },
339
+ {
340
+ "method": "GET",
341
+ "path": "/v1/since",
342
+ "auth": "verified",
343
+ "summary": "Long-poll the collection log tail."
344
+ }
345
+ ]
346
+ };
347
+ /**
348
+ * Build the /v1/spec response body. With no `config` (anonymous caller)
349
+ * the static contract IR is returned verbatim. With a `config` (the
350
+ * request already carried a valid identity), the declared collection
351
+ * names + index names + schema vendor are appended — these are gated
352
+ * behind the verifier so unauthenticated callers can't enumerate tenant
353
+ * collection names.
354
+ */
355
+ function buildSpecResponse(config) {
356
+ if (config === void 0) return specIr;
357
+ const collections = Object.entries(config.collections).map(([name, def]) => {
358
+ const indexes = (def.indexes ?? []).map((ix) => ix.name);
359
+ if (def.schema !== void 0) return {
360
+ name,
361
+ indexes,
362
+ schemaVendor: def.schema["~standard"].vendor
363
+ };
364
+ return {
365
+ name,
366
+ indexes
367
+ };
368
+ });
369
+ return {
370
+ ...specIr,
371
+ collections
372
+ };
373
+ }
374
+ async function handleSpecRequest(request, resolve) {
375
+ let config;
376
+ try {
377
+ const { verifier, config: resolved } = await resolve();
378
+ if (await verifier(request) !== null) config = resolved;
379
+ } catch (error) {
380
+ const reason = error instanceof Error ? error.message : String(error);
381
+ console.warn(`[baerly] /v1/spec degraded to the anonymous contract: ${reason}`);
382
+ }
383
+ return new Response(JSON.stringify(buildSpecResponse(config)), {
384
+ status: 200,
385
+ headers: { "content-type": "application/json" }
386
+ });
387
+ }
388
+ //#endregion
389
+ export { handleSpecRequest as t };
390
+
391
+ //# sourceMappingURL=runtime-spec-qL3_lTTU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime-spec-qL3_lTTU.js","names":["rawSpecIr"],"sources":["../packages/server/spec/baerly.spec.json","../packages/server/src/spec/runtime-spec.ts"],"sourcesContent":["","import type { BaerlyConfig, Verifier } from \"@baerly/protocol\";\nimport type { SpecIR } from \"./ir.ts\";\nimport rawSpecIr from \"../../spec/baerly.spec.json\" with { type: \"json\" };\n\n// Import the JSON as data (not ir.ts which drags the HTTP router into\n// the kernel closure). Cast to SpecIR so callers get typed access to\n// errorCodes, specVersion, etc. without following the ir.ts import chain.\nconst specIr = rawSpecIr as unknown as SpecIR;\n\n/** A declared collection summary, emitted only to authed callers. */\nexport interface SpecCollection {\n readonly name: string;\n readonly indexes: ReadonlyArray<string>;\n readonly schemaVendor?: string;\n}\n\n/** The /v1/spec response: the static IR plus an optional authed collections section. */\nexport type SpecResponse = SpecIR & { collections?: ReadonlyArray<SpecCollection> };\n\n/**\n * Build the /v1/spec response body. With no `config` (anonymous caller)\n * the static contract IR is returned verbatim. With a `config` (the\n * request already carried a valid identity), the declared collection\n * names + index names + schema vendor are appended — these are gated\n * behind the verifier so unauthenticated callers can't enumerate tenant\n * collection names.\n */\nexport function buildSpecResponse(config?: BaerlyConfig): SpecResponse {\n if (config === undefined) {\n return specIr as SpecResponse;\n }\n const collections: SpecCollection[] = Object.entries(config.collections).map(\n ([name, def]): SpecCollection => {\n const indexes = (def.indexes ?? []).map((ix) => ix.name);\n if (def.schema !== undefined) {\n return { name, indexes, schemaVendor: def.schema[\"~standard\"].vendor };\n }\n return { name, indexes };\n },\n );\n return { ...(specIr as SpecResponse), collections };\n}\n\n// Shared `GET /v1/spec` handler for both adapters (keeps the response shape\n// from drifting). `resolve` yields the adapter's verifier + tenant config.\n// Run tolerantly: any `resolve` or verifier failure degrades to the anonymous\n// static contract — it is public infra that must stay up when auth/config is\n// unhealthy. Collections are appended only for a non-null identity, so an\n// unauthenticated probe never enumerates them.\nexport async function handleSpecRequest(\n request: Request,\n resolve: () => Promise<{ verifier: Verifier; config: BaerlyConfig | undefined }>,\n): Promise<Response> {\n let config: BaerlyConfig | undefined;\n try {\n const { verifier, config: resolved } = await resolve();\n const identity = await verifier(request);\n if (identity !== null) {\n config = resolved;\n }\n } catch (error) {\n // A verifier *reject* is `null` (handled above); reaching here means\n // resolve() or the verifier *threw* — the auth backend or tenant config\n // is unhealthy. Stay tolerant (the static contract is public infra and\n // must stay up), but emit one operational signal so the outage isn't\n // invisible on this anonymous, pre-observability route. `console.warn`\n // (not a canonical line) matches the adapters' other ops warnings and\n // keeps this light module out of the observability closure. Log only the\n // error *message*, never the error object: an auth-backend failure can\n // carry credential material (tokens, keys, connection strings) in its\n // fields/stack, and this line lands in plaintext logs.\n const reason = error instanceof Error ? error.message : String(error);\n console.warn(`[baerly] /v1/spec degraded to the anonymous contract: ${reason}`);\n }\n return new Response(JSON.stringify(buildSpecResponse(config)), {\n status: 200,\n headers: { \"content-type\": \"application/json\" },\n });\n}\n"],"mappings":";;ACOA,MAAM,SAASA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAAA;;;;;;;;;AAoBf,SAAgB,kBAAkB,QAAqC;CACrE,IAAI,WAAW,KAAA,GACb,OAAO;CAET,MAAM,cAAgC,OAAO,QAAQ,OAAO,WAAW,CAAC,CAAC,KACtE,CAAC,MAAM,SAAyB;EAC/B,MAAM,WAAW,IAAI,WAAW,CAAC,EAAA,CAAG,KAAK,OAAO,GAAG,IAAI;EACvD,IAAI,IAAI,WAAW,KAAA,GACjB,OAAO;GAAE;GAAM;GAAS,cAAc,IAAI,OAAO,YAAY,CAAC;EAAO;EAEvE,OAAO;GAAE;GAAM;EAAQ;CACzB,CACF;CACA,OAAO;EAAE,GAAI;EAAyB;CAAY;AACpD;AAQA,eAAsB,kBACpB,SACA,SACmB;CACnB,IAAI;CACJ,IAAI;EACF,MAAM,EAAE,UAAU,QAAQ,aAAa,MAAM,QAAQ;EAErD,IAAI,MADmB,SAAS,OAAO,MACtB,MACf,SAAS;CAEb,SAAS,OAAO;EAWd,MAAM,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EACpE,QAAQ,KAAK,yDAAyD,QAAQ;CAChF;CACA,OAAO,IAAI,SAAS,KAAK,UAAU,kBAAkB,MAAM,CAAC,GAAG;EAC7D,QAAQ;EACR,SAAS,EAAE,gBAAgB,mBAAmB;CAChD,CAAC;AACH"}
@@ -0,0 +1,60 @@
1
+ import { _ as StoragePutOptions, g as StorageListEntry, h as StorageGetResult, m as StorageGetOptions, p as Storage, v as StoragePutResult } from "./index-BYk9oCNf.js";
2
+
3
+ //#region packages/adapter-node/src/s3-http.d.ts
4
+ /**
5
+ * Construction-time options for {@link S3HttpStorage}. Everything is
6
+ * optional except `endpoint` and `bucket`; the consumer chooses how
7
+ * to satisfy `fetch` (browser/Node global vs. injected) and `sign`
8
+ * (anonymous Minio vs. SigV4-signed via aws4fetch).
9
+ */
10
+ interface S3HttpStorageOptions {
11
+ /**
12
+ * S3 endpoint URL, e.g. `https://s3.us-east-1.amazonaws.com` or
13
+ * `http://127.0.0.1:9102` (Minio). Trailing slashes are trimmed.
14
+ */
15
+ endpoint: string;
16
+ /** S3 bucket name. */
17
+ bucket: string;
18
+ /**
19
+ * `fetch` implementation. Defaults to `globalThis.fetch.bind(globalThis)`.
20
+ * Tests pass a `vi.fn()` stub.
21
+ */
22
+ fetch?: typeof fetch;
23
+ /**
24
+ * Signs requests before send. Pass `undefined` for anonymous
25
+ * (Minio without creds). The seam is `(req) => Promise<req>` so
26
+ * SigV4 implementations like `aws4fetch.AwsClient.sign` plug in
27
+ * directly.
28
+ */
29
+ sign?: (req: Request) => Promise<Request>;
30
+ /** Max retries for transient (non-permanent) failures. */
31
+ retries?: number;
32
+ /** Initial backoff in ms. */
33
+ backoffMs?: number;
34
+ }
35
+ /**
36
+ * `Storage` impl that speaks the S3 REST API directly. Works against
37
+ * any S3-compatible endpoint — AWS S3, R2 (S3-compat), GCS (S3-compat),
38
+ * Minio. Does not depend on any AWS SDK.
39
+ *
40
+ * Authentication is plugged in via the `sign` callback; this class
41
+ * itself does no SigV4. For Cloudflare Workers, the R2 binding fast
42
+ * path lives in `@baerly/adapter-cloudflare`.
43
+ */
44
+ declare class S3HttpStorage implements Storage {
45
+ #private;
46
+ constructor(options: S3HttpStorageOptions);
47
+ get(key: string, opts?: StorageGetOptions): Promise<StorageGetResult | null>;
48
+ put(key: string, body: Uint8Array, opts?: StoragePutOptions): Promise<StoragePutResult>;
49
+ delete(key: string, opts?: {
50
+ signal?: AbortSignal;
51
+ }): Promise<void>;
52
+ list(prefix: string, opts?: {
53
+ startAfter?: string;
54
+ maxKeys?: number;
55
+ signal?: AbortSignal;
56
+ }): AsyncIterable<StorageListEntry>;
57
+ }
58
+ //#endregion
59
+ export { S3HttpStorageOptions as n, S3HttpStorage as t };
60
+ //# sourceMappingURL=s3-http-B-z8th6O.d.ts.map
package/dist/s3.d.ts ADDED
@@ -0,0 +1,47 @@
1
+ import { n as S3HttpStorageOptions, t as S3HttpStorage } from "./s3-http-B-z8th6O.js";
2
+
3
+ //#region packages/adapter-node/src/s3-signer.d.ts
4
+ /**
5
+ * Static-credential inputs for {@link sigV4Signer}.
6
+ */
7
+ interface SigV4SignerOptions {
8
+ /** AWS access key id (or R2 / Minio equivalent). */
9
+ accessKeyId: string | undefined;
10
+ /** AWS secret access key (or R2 / Minio equivalent). */
11
+ secretAccessKey: string | undefined;
12
+ /**
13
+ * Region, e.g. `"us-east-1"`. R2 ignores the value but `aws4fetch`
14
+ * requires one — use `"auto"` for R2's S3-compat endpoint.
15
+ */
16
+ region: string | undefined;
17
+ /** Optional STS session token for temporary credentials. */
18
+ sessionToken?: string;
19
+ }
20
+ /**
21
+ * Static-credential SigV4 signer for {@link S3HttpStorage}, safe inside
22
+ * a Cloudflare Worker: `aws4fetch` signs with WebCrypto, so there is no
23
+ * `node:crypto` in the closure. Returns the `(req) => Promise<Request>`
24
+ * seam `S3HttpStorageOptions.sign` expects.
25
+ *
26
+ * For rotating credentials, pass your own `(req) => Promise<Request>`
27
+ * to `S3HttpStorage` instead — this helper covers the static case.
28
+ *
29
+ * @example
30
+ * ```ts
31
+ * import { S3HttpStorage, sigV4Signer } from "@gusto/baerly-storage/s3";
32
+ *
33
+ * const storage = new S3HttpStorage({
34
+ * endpoint: env.S3_ENDPOINT,
35
+ * bucket: env.S3_BUCKET,
36
+ * sign: sigV4Signer({
37
+ * accessKeyId: env.AWS_ACCESS_KEY_ID,
38
+ * secretAccessKey: env.AWS_SECRET_ACCESS_KEY,
39
+ * region: env.AWS_REGION,
40
+ * }),
41
+ * });
42
+ * ```
43
+ */
44
+ declare function sigV4Signer(opts: SigV4SignerOptions): (req: Request) => Promise<Request>;
45
+ //#endregion
46
+ export { S3HttpStorage, type S3HttpStorageOptions, type SigV4SignerOptions, sigV4Signer };
47
+ //# sourceMappingURL=s3.d.ts.map
package/dist/s3.js ADDED
@@ -0,0 +1,45 @@
1
+ import { t as BaerlyError } from "./errors-Dfa3p78c.js";
2
+ import { n as S3HttpStorage, t as AwsClient } from "./aws4fetch.esm-p7eEzLCs.js";
3
+ //#region packages/adapter-node/src/s3-signer.ts
4
+ /**
5
+ * Static-credential SigV4 signer for {@link S3HttpStorage}, safe inside
6
+ * a Cloudflare Worker: `aws4fetch` signs with WebCrypto, so there is no
7
+ * `node:crypto` in the closure. Returns the `(req) => Promise<Request>`
8
+ * seam `S3HttpStorageOptions.sign` expects.
9
+ *
10
+ * For rotating credentials, pass your own `(req) => Promise<Request>`
11
+ * to `S3HttpStorage` instead — this helper covers the static case.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * import { S3HttpStorage, sigV4Signer } from "@gusto/baerly-storage/s3";
16
+ *
17
+ * const storage = new S3HttpStorage({
18
+ * endpoint: env.S3_ENDPOINT,
19
+ * bucket: env.S3_BUCKET,
20
+ * sign: sigV4Signer({
21
+ * accessKeyId: env.AWS_ACCESS_KEY_ID,
22
+ * secretAccessKey: env.AWS_SECRET_ACCESS_KEY,
23
+ * region: env.AWS_REGION,
24
+ * }),
25
+ * });
26
+ * ```
27
+ */
28
+ function sigV4Signer(opts) {
29
+ const accessKeyId = (opts.accessKeyId ?? "").trim();
30
+ const secretAccessKey = (opts.secretAccessKey ?? "").trim();
31
+ const region = (opts.region ?? "").trim();
32
+ if (!accessKeyId || !secretAccessKey || !region) throw new BaerlyError("InvalidConfig", "sigV4Signer: `accessKeyId`, `secretAccessKey`, and `region` must be non-empty. Check the credentials passed from your Worker `env` / process env.");
33
+ const client = new AwsClient({
34
+ accessKeyId,
35
+ secretAccessKey,
36
+ sessionToken: opts.sessionToken,
37
+ region,
38
+ service: "s3"
39
+ });
40
+ return (req) => client.sign(req);
41
+ }
42
+ //#endregion
43
+ export { S3HttpStorage, sigV4Signer };
44
+
45
+ //# sourceMappingURL=s3.js.map
package/dist/s3.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"s3.js","names":[],"sources":["../packages/adapter-node/src/s3-signer.ts"],"sourcesContent":["import { BaerlyError } from \"@baerly/protocol\";\nimport { AwsClient } from \"aws4fetch\";\n\n/**\n * Static-credential inputs for {@link sigV4Signer}.\n */\nexport interface SigV4SignerOptions {\n // Typed `string | undefined`, not `string`: the documented usage feeds\n // these straight from a Worker `env` / `process.env`, where an absent key\n // is `undefined` at runtime even when the ambient env type claims `string`.\n // The keys stay required (so a caller can't silently omit one), but the\n // value may be absent — `sigV4Signer` fail-closes on absent/blank below.\n /** AWS access key id (or R2 / Minio equivalent). */\n accessKeyId: string | undefined;\n /** AWS secret access key (or R2 / Minio equivalent). */\n secretAccessKey: string | undefined;\n /**\n * Region, e.g. `\"us-east-1\"`. R2 ignores the value but `aws4fetch`\n * requires one — use `\"auto\"` for R2's S3-compat endpoint.\n */\n region: string | undefined;\n /** Optional STS session token for temporary credentials. */\n sessionToken?: string;\n}\n\n/**\n * Static-credential SigV4 signer for {@link S3HttpStorage}, safe inside\n * a Cloudflare Worker: `aws4fetch` signs with WebCrypto, so there is no\n * `node:crypto` in the closure. Returns the `(req) => Promise<Request>`\n * seam `S3HttpStorageOptions.sign` expects.\n *\n * For rotating credentials, pass your own `(req) => Promise<Request>`\n * to `S3HttpStorage` instead — this helper covers the static case.\n *\n * @example\n * ```ts\n * import { S3HttpStorage, sigV4Signer } from \"@gusto/baerly-storage/s3\";\n *\n * const storage = new S3HttpStorage({\n * endpoint: env.S3_ENDPOINT,\n * bucket: env.S3_BUCKET,\n * sign: sigV4Signer({\n * accessKeyId: env.AWS_ACCESS_KEY_ID,\n * secretAccessKey: env.AWS_SECRET_ACCESS_KEY,\n * region: env.AWS_REGION,\n * }),\n * });\n * ```\n */\nexport function sigV4Signer(opts: SigV4SignerOptions): (req: Request) => Promise<Request> {\n // Fail fast on blank credentials. A wrangler `var` declared but left\n // empty resolves to \"\" — without this guard aws4fetch signs with empty\n // creds and the endpoint answers an opaque 403 on the first request,\n // far from the misconfig. Mirrors the fail-closed contract on\n // `resolveWorkerStorage` and `sharedSecret` (empty `SHARED_SECRET`).\n //\n // Coalesce-then-trim once, then both validate AND sign with the trimmed\n // values. A `var`/env key declared *nowhere* resolves to `undefined` at\n // runtime — the most common misconfig — and a bare `.trim()` on it throws\n // a raw `TypeError` more opaque than the 403 this guard exists to prevent;\n // `?? \"\"` routes absent and blank alike into the fail-closed check.\n // Trimming catches a whitespace-only value (`\" \"`, `\"\\t\\n\"`), truthy in JS\n // but signing-blank in effect, and — critically — feeds the *trimmed*\n // value to `AwsClient`: a stray leading/trailing space on an otherwise\n // valid credential (a copy-paste artifact) would otherwise pass the guard\n // yet sign with the padded value, producing an invalid signature and the\n // same opaque 403. `region` gets the same treatment — an empty region\n // yields a malformed SigV4 scope (`YYYYMMDD//s3/aws4_request`).\n const accessKeyId = (opts.accessKeyId ?? \"\").trim();\n const secretAccessKey = (opts.secretAccessKey ?? \"\").trim();\n const region = (opts.region ?? \"\").trim();\n if (!accessKeyId || !secretAccessKey || !region) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"sigV4Signer: `accessKeyId`, `secretAccessKey`, and `region` must be \" +\n \"non-empty. Check the credentials passed from your Worker `env` / \" +\n \"process env.\",\n );\n }\n const client = new AwsClient({\n accessKeyId,\n secretAccessKey,\n sessionToken: opts.sessionToken,\n region,\n service: \"s3\",\n });\n return (req: Request) => client.sign(req);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,SAAgB,YAAY,MAA8D;CAmBxF,MAAM,eAAe,KAAK,eAAe,GAAA,CAAI,KAAK;CAClD,MAAM,mBAAmB,KAAK,mBAAmB,GAAA,CAAI,KAAK;CAC1D,MAAM,UAAU,KAAK,UAAU,GAAA,CAAI,KAAK;CACxC,IAAI,CAAC,eAAe,CAAC,mBAAmB,CAAC,QACvC,MAAM,IAAI,YACR,iBACA,mJAGF;CAEF,MAAM,SAAS,IAAI,UAAU;EAC3B;EACA;EACA,cAAc,KAAK;EACnB;EACA,SAAS;CACX,CAAC;CACD,QAAQ,QAAiB,OAAO,KAAK,GAAG;AAC1C"}
@@ -1,4 +1,12 @@
1
- import { t as BaerlyError } from "./errors-DOdL95kK.js";
1
+ import { t as BaerlyError } from "./errors-Dfa3p78c.js";
2
+ //#region packages/protocol/src/auth-resolution.ts
3
+ /** Corrective action for a `sharedSecret(...)` preset misconfig; crosses the wire. */
4
+ const SHARED_SECRET_CONFIG_RESOLUTION = "Pass a non-empty `secret` and a non-empty `tenantPrefix` with no \"/\" to sharedSecret({ secret, tenantPrefix }).";
5
+ /** Corrective action for a `bearerJwt(...)` preset misconfig; crosses the wire. */
6
+ const BEARER_JWT_CONFIG_RESOLUTION = "Provide non-empty `issuer`, `audience`, and at least one `algorithms` entry; `tenantClaim` and `tenantPrefix` are mutually exclusive and `tenantPrefix` must be non-empty with no \"/\".";
7
+ /** Corrective action for a `cloudflareAccess(...)` preset misconfig; crosses the wire. */
8
+ const CLOUDFLARE_ACCESS_CONFIG_RESOLUTION = "Pass a non-empty `teamDomain` and a 64-char lowercase-hex `audienceTag` (the Application Audience (AUD) tag from the CF Access app config).";
9
+ //#endregion
2
10
  //#region packages/server/src/auth/internal/timing-safe-equal.ts
3
11
  /**
4
12
  * Constant-time byte-array equality. Length mismatch short-circuits —
@@ -53,8 +61,8 @@ const timingSafeEqual = (a, b) => {
53
61
  * ```
54
62
  */
55
63
  const sharedSecret = (opts) => {
56
- if (opts.secret.length === 0) throw new BaerlyError("InvalidConfig", "sharedSecret: secret must be non-empty");
57
- if (opts.tenantPrefix.length === 0 || opts.tenantPrefix.includes("/")) throw new BaerlyError("InvalidConfig", `sharedSecret: tenantPrefix must be non-empty and "/"-free (got ${JSON.stringify(opts.tenantPrefix)})`);
64
+ if (opts.secret.length === 0) throw new BaerlyError("InvalidConfig", "sharedSecret: secret must be non-empty", void 0, void 0, void 0, SHARED_SECRET_CONFIG_RESOLUTION);
65
+ if (opts.tenantPrefix.length === 0 || opts.tenantPrefix.includes("/")) throw new BaerlyError("InvalidConfig", `sharedSecret: tenantPrefix must be non-empty and "/"-free (got ${JSON.stringify(opts.tenantPrefix)})`, void 0, void 0, void 0, SHARED_SECRET_CONFIG_RESOLUTION);
58
66
  const expected = new TextEncoder().encode(`Bearer ${opts.secret}`);
59
67
  return async (req) => {
60
68
  const header = req.headers.get("Authorization") ?? "";
@@ -66,6 +74,6 @@ const sharedSecret = (opts) => {
66
74
  };
67
75
  };
68
76
  //#endregion
69
- export { sharedSecret as t };
77
+ export { BEARER_JWT_CONFIG_RESOLUTION as n, CLOUDFLARE_ACCESS_CONFIG_RESOLUTION as r, sharedSecret as t };
70
78
 
71
- //# sourceMappingURL=shared-secret-BJdSwpgw.js.map
79
+ //# sourceMappingURL=shared-secret-DgEicd3x.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shared-secret-DgEicd3x.js","names":[],"sources":["../packages/protocol/src/auth-resolution.ts","../packages/server/src/auth/internal/timing-safe-equal.ts","../packages/server/src/auth/presets/shared-secret.ts"],"sourcesContent":["/** Corrective action for a `sharedSecret(...)` preset misconfig; crosses the wire. */\nexport const SHARED_SECRET_CONFIG_RESOLUTION: string =\n 'Pass a non-empty `secret` and a non-empty `tenantPrefix` with no \"/\" to sharedSecret({ secret, tenantPrefix }).';\n\n/** Corrective action for a `bearerJwt(...)` preset misconfig; crosses the wire. */\nexport const BEARER_JWT_CONFIG_RESOLUTION: string =\n 'Provide non-empty `issuer`, `audience`, and at least one `algorithms` entry; `tenantClaim` and `tenantPrefix` are mutually exclusive and `tenantPrefix` must be non-empty with no \"/\".';\n\n/** Corrective action for a `cloudflareAccess(...)` preset misconfig; crosses the wire. */\nexport const CLOUDFLARE_ACCESS_CONFIG_RESOLUTION: string =\n \"Pass a non-empty `teamDomain` and a 64-char lowercase-hex `audienceTag` (the Application Audience (AUD) tag from the CF Access app config).\";\n","/**\n * Constant-time byte-array equality. Length mismatch short-circuits —\n * the attacker already knows the expected length is a few-dozen bytes,\n * so revealing it is a non-secret. The diff loop only runs when the\n * lengths match, so its timing cannot leak the position of the first\n * differing byte.\n *\n * Hoisted out of {@link sharedSecret} so future verifiers can reuse\n * the same implementation — one TODO is easier to land than two.\n */\nexport const timingSafeEqual = (a: Uint8Array, b: Uint8Array): boolean => {\n if (a.length !== b.length) {\n return false;\n }\n let diff = 0;\n for (let i = 0; i < a.length; i++) {\n diff |= a[i]! ^ b[i]!;\n }\n return diff === 0;\n};\n","import { BaerlyError, SHARED_SECRET_CONFIG_RESOLUTION, type Verifier } from \"@baerly/protocol\";\nimport { timingSafeEqual } from \"../internal/timing-safe-equal.ts\";\n\n/**\n * Options for {@link sharedSecret}.\n *\n * - `secret` — the bearer token clients must present. Compared with\n * constant-time `timingSafeEqual` — see {@link sharedSecret} for\n * why naive `===` is not enough.\n * - `tenantPrefix` — the value returned in `VerifierResult.tenantPrefix`.\n * Single-tenant deployments pass a constant (`\"acme\"`). Multi-tenant\n * deployments don't use `sharedSecret`; they reach for `bearerJwt`\n * or `cloudflareAccess` instead.\n */\nexport interface SharedSecretOptions {\n readonly secret: string;\n readonly tenantPrefix: string;\n}\n\n/**\n * Build a `Verifier` that accepts `Authorization: Bearer <secret>`\n * and pins every request to a single tenant. The simplest preset —\n * use for single-tenant deployments before you've stood up an IdP.\n *\n * **Why constant-time compare:** a naive `===` against the bearer\n * token leaks timing information about which character first\n * differed. Real-world relevance over HTTPS is debated, but\n * `timingSafeEqual` is one line of code and erases the question.\n *\n * **Identity shape.** On success the returned `VerifierResult` has:\n * ```ts\n * { tenantPrefix: \"<configured>\", identity: { kind: \"shared-secret\" } }\n * ```\n * `sharedSecret` has no notion of a per-user subject — every caller\n * presenting the bearer is the same principal. Downstream code that\n * wants a stable per-request `sender_sub` should fall back to a\n * synthetic value (`\"shared-secret:\" + tenantPrefix`) when\n * `identity.kind === \"shared-secret\"`. The `kind` field is the\n * discriminant across all preset identities; switch on it instead of\n * sniffing properties.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — `secret` empty or\n * `tenantPrefix` empty / contains \"/\".\n *\n * @example\n * ```ts\n * import { sharedSecret } from \"@gusto/baerly-storage/auth\";\n * const verifier = sharedSecret({\n * secret: env.SHARED_SECRET,\n * tenantPrefix: \"acme\",\n * });\n * ```\n */\nexport const sharedSecret = (opts: SharedSecretOptions): Verifier => {\n if (opts.secret.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"sharedSecret: secret must be non-empty\",\n undefined,\n undefined,\n undefined,\n SHARED_SECRET_CONFIG_RESOLUTION,\n );\n }\n if (opts.tenantPrefix.length === 0 || opts.tenantPrefix.includes(\"/\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `sharedSecret: tenantPrefix must be non-empty and \"/\"-free (got ${JSON.stringify(opts.tenantPrefix)})`,\n undefined,\n undefined,\n undefined,\n SHARED_SECRET_CONFIG_RESOLUTION,\n );\n }\n const expected = new TextEncoder().encode(`Bearer ${opts.secret}`);\n return async (req: Request) => {\n const header = req.headers.get(\"Authorization\") ?? \"\";\n const actual = new TextEncoder().encode(header);\n if (!timingSafeEqual(expected, actual)) {\n return null;\n }\n return { tenantPrefix: opts.tenantPrefix, identity: { kind: \"shared-secret\" } };\n };\n};\n"],"mappings":";;;AACA,MAAa,kCACX;;AAGF,MAAa,+BACX;;AAGF,MAAa,sCACX;;;;;;;;;;;;;ACAF,MAAa,mBAAmB,GAAe,MAA2B;CACxE,IAAI,EAAE,WAAW,EAAE,QACjB,OAAO;CAET,IAAI,OAAO;CACX,KAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,KAC5B,QAAQ,EAAE,KAAM,EAAE;CAEpB,OAAO,SAAS;AAClB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACkCA,MAAa,gBAAgB,SAAwC;CACnE,IAAI,KAAK,OAAO,WAAW,GACzB,MAAM,IAAI,YACR,iBACA,0CACA,KAAA,GACA,KAAA,GACA,KAAA,GACA,+BACF;CAEF,IAAI,KAAK,aAAa,WAAW,KAAK,KAAK,aAAa,SAAS,GAAG,GAClE,MAAM,IAAI,YACR,iBACA,kEAAkE,KAAK,UAAU,KAAK,YAAY,EAAE,IACpG,KAAA,GACA,KAAA,GACA,KAAA,GACA,+BACF;CAEF,MAAM,WAAW,IAAI,YAAY,CAAC,CAAC,OAAO,UAAU,KAAK,QAAQ;CACjE,OAAO,OAAO,QAAiB;EAC7B,MAAM,SAAS,IAAI,QAAQ,IAAI,eAAe,KAAK;EAEnD,IAAI,CAAC,gBAAgB,UADN,IAAI,YAAY,CAAC,CAAC,OAAO,MACJ,CAAC,GACnC,OAAO;EAET,OAAO;GAAE,cAAc,KAAK;GAAc,UAAU,EAAE,MAAM,gBAAgB;EAAE;CAChF;AACF"}