@blamejs/core 0.7.18 → 0.7.19

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 (167) hide show
  1. package/CHANGELOG.md +425 -423
  2. package/README.md +150 -150
  3. package/bin/blamejs.js +0 -0
  4. package/index.js +310 -308
  5. package/lib/api-key.js +660 -660
  6. package/lib/api-snapshot.js +338 -338
  7. package/lib/app-shutdown.js +385 -385
  8. package/lib/app.js +365 -365
  9. package/lib/archive.js +250 -250
  10. package/lib/atomic-file.js +544 -544
  11. package/lib/audit-chain.js +177 -177
  12. package/lib/audit-sign.js +344 -344
  13. package/lib/audit-tools.js +677 -677
  14. package/lib/audit.js +766 -766
  15. package/lib/auth/jwt-external.js +365 -0
  16. package/lib/auth/jwt.js +337 -311
  17. package/lib/auth/lockout.js +436 -436
  18. package/lib/auth/oauth.js +721 -721
  19. package/lib/auth/passkey.js +181 -181
  20. package/lib/auth/password.js +628 -594
  21. package/lib/backup/bundle.js +217 -217
  22. package/lib/backup/crypto.js +176 -176
  23. package/lib/backup/index.js +515 -515
  24. package/lib/backup/manifest.js +282 -282
  25. package/lib/break-glass.js +1338 -1338
  26. package/lib/bundler.js +441 -441
  27. package/lib/cache-redis.js +256 -256
  28. package/lib/cache.js +1206 -1206
  29. package/lib/canonical-json.js +115 -115
  30. package/lib/chain-writer.js +234 -234
  31. package/lib/cli-helpers.js +206 -206
  32. package/lib/cli.js +2334 -2334
  33. package/lib/cluster-provider-db.js +317 -317
  34. package/lib/cluster-storage.js +226 -226
  35. package/lib/cluster.js +703 -703
  36. package/lib/config-drift.js +301 -301
  37. package/lib/consent.js +222 -222
  38. package/lib/constants.js +191 -191
  39. package/lib/cookies.js +315 -315
  40. package/lib/credential-hash.js +322 -322
  41. package/lib/crypto.js +266 -266
  42. package/lib/csv.js +275 -275
  43. package/lib/db-declare-row-policy.js +267 -267
  44. package/lib/db-declare-view.js +420 -420
  45. package/lib/db-query.js +406 -406
  46. package/lib/db-schema.js +319 -319
  47. package/lib/db.js +1288 -1288
  48. package/lib/deprecate.js +222 -222
  49. package/lib/dev.js +335 -335
  50. package/lib/dual-control.js +473 -473
  51. package/lib/error-page.js +420 -420
  52. package/lib/external-db-migrate.js +441 -441
  53. package/lib/external-db.js +1061 -1061
  54. package/lib/file-type.js +273 -273
  55. package/lib/forms.js +422 -422
  56. package/lib/framework-error.js +293 -293
  57. package/lib/framework-schema.js +717 -717
  58. package/lib/handlers.js +350 -350
  59. package/lib/http-client-cookie-jar.js +508 -508
  60. package/lib/http-client.js +1195 -1195
  61. package/lib/i18n.js +878 -878
  62. package/lib/jobs.js +185 -185
  63. package/lib/log-stream-cloudwatch.js +369 -369
  64. package/lib/log-stream-local.js +146 -146
  65. package/lib/log-stream-otlp-grpc.js +410 -410
  66. package/lib/log-stream-otlp.js +286 -286
  67. package/lib/log-stream-syslog.js +302 -302
  68. package/lib/log-stream-webhook.js +199 -199
  69. package/lib/log-stream.js +330 -330
  70. package/lib/log.js +500 -500
  71. package/lib/mail-bounce.js +528 -528
  72. package/lib/mail-dkim.js +369 -369
  73. package/lib/mail.js +981 -981
  74. package/lib/metrics.js +683 -683
  75. package/lib/middleware/api-encrypt.js +936 -936
  76. package/lib/middleware/attach-user.js +157 -157
  77. package/lib/middleware/bearer-auth.js +152 -0
  78. package/lib/middleware/body-parser.js +1170 -1170
  79. package/lib/middleware/bot-guard.js +178 -178
  80. package/lib/middleware/compression.js +452 -452
  81. package/lib/middleware/cors.js +314 -314
  82. package/lib/middleware/csp-nonce.js +348 -348
  83. package/lib/middleware/csrf-protect.js +316 -316
  84. package/lib/middleware/db-role-for.js +264 -264
  85. package/lib/middleware/health.js +392 -392
  86. package/lib/middleware/index.js +82 -79
  87. package/lib/middleware/rate-limit.js +358 -358
  88. package/lib/middleware/request-id.js +61 -61
  89. package/lib/middleware/request-log.js +168 -168
  90. package/lib/middleware/require-auth.js +104 -104
  91. package/lib/middleware/security-headers.js +116 -116
  92. package/lib/middleware/sse.js +166 -166
  93. package/lib/migrations.js +383 -383
  94. package/lib/mtls-ca.js +518 -518
  95. package/lib/mtls-engine-default.js +481 -481
  96. package/lib/network-dns.js +632 -632
  97. package/lib/network-heartbeat.js +290 -290
  98. package/lib/network-nts.js +574 -574
  99. package/lib/network-proxy.js +265 -265
  100. package/lib/network-tls.js +328 -328
  101. package/lib/network.js +233 -233
  102. package/lib/notify.js +612 -612
  103. package/lib/ntp-check.js +229 -229
  104. package/lib/numeric-bounds.js +111 -111
  105. package/lib/object-store/azure-blob-bucket-ops.js +349 -349
  106. package/lib/object-store/azure-blob.js +488 -488
  107. package/lib/object-store/gcs-bucket-ops.js +351 -351
  108. package/lib/object-store/gcs.js +519 -519
  109. package/lib/object-store/http-put.js +153 -153
  110. package/lib/object-store/index.js +197 -197
  111. package/lib/object-store/sigv4-bucket-ops.js +1092 -1092
  112. package/lib/object-store/sigv4.js +903 -903
  113. package/lib/observability.js +151 -151
  114. package/lib/otel-export.js +269 -269
  115. package/lib/pagination.js +464 -464
  116. package/lib/parsers/index.js +80 -80
  117. package/lib/parsers/safe-env.js +642 -642
  118. package/lib/parsers/safe-ini.js +292 -292
  119. package/lib/parsers/safe-toml.js +784 -784
  120. package/lib/parsers/safe-xml.js +390 -390
  121. package/lib/parsers/safe-yaml.js +1015 -1015
  122. package/lib/permissions.js +708 -708
  123. package/lib/pqc-agent.js +87 -87
  124. package/lib/pqc-gate.js +279 -279
  125. package/lib/protobuf-encoder.js +190 -190
  126. package/lib/protocol-dispatcher.js +161 -161
  127. package/lib/pubsub-redis.js +167 -167
  128. package/lib/pubsub.js +429 -429
  129. package/lib/queue-local.js +476 -476
  130. package/lib/queue-redis.js +745 -745
  131. package/lib/queue-sqs.js +319 -319
  132. package/lib/queue.js +695 -695
  133. package/lib/redis-client.js +519 -519
  134. package/lib/request-helpers.js +340 -340
  135. package/lib/restore-bundle.js +237 -237
  136. package/lib/restore-rollback.js +259 -259
  137. package/lib/restore.js +409 -409
  138. package/lib/retry.js +376 -376
  139. package/lib/router.js +748 -748
  140. package/lib/safe-async.js +735 -735
  141. package/lib/safe-buffer.js +237 -237
  142. package/lib/safe-json.js +541 -541
  143. package/lib/safe-schema.js +1266 -1266
  144. package/lib/safe-url.js +159 -159
  145. package/lib/scheduler.js +706 -706
  146. package/lib/security-assert.js +373 -373
  147. package/lib/seeders.js +618 -618
  148. package/lib/session.js +535 -478
  149. package/lib/slug.js +269 -269
  150. package/lib/ssrf-guard.js +401 -401
  151. package/lib/storage.js +471 -471
  152. package/lib/subject.js +281 -281
  153. package/lib/template.js +791 -791
  154. package/lib/testing.js +798 -798
  155. package/lib/time.js +310 -310
  156. package/lib/totp.js +302 -302
  157. package/lib/tracing.js +494 -494
  158. package/lib/uuid.js +132 -132
  159. package/lib/validate-opts.js +340 -340
  160. package/lib/vault/index.js +308 -308
  161. package/lib/vault/rotate.js +784 -784
  162. package/lib/vault/wrap.js +296 -296
  163. package/lib/vendor/noble-ciphers.cjs +9 -9
  164. package/lib/webhook.js +595 -595
  165. package/lib/websocket.js +1048 -1048
  166. package/package.json +77 -77
  167. package/sbom.cyclonedx.json +7 -7
package/lib/storage.js CHANGED
@@ -1,471 +1,471 @@
1
- "use strict";
2
- /**
3
- * Storage abstraction — multi-backend, classification-routed, residency-
4
- * enforced file storage with per-file vault-sealed encryption.
5
- *
6
- * Two configuration shapes (both supported, internally normalized to
7
- * the multi-backend form):
8
- *
9
- * 1. Single-backend (legacy shape — preserved):
10
- * storage.init({ backend: 'local', uploadDir: './data/uploads' })
11
- *
12
- * 2. Multi-backend:
13
- * storage.init({
14
- * backends: {
15
- * 'eu-private': { protocol: 'http-put', baseUrl: '...',
16
- * classifications: ['personal'], residencyTag: 'EU' },
17
- * 'us-ops': { protocol: 'local', rootDir: '/data/ops',
18
- * classifications: ['operational', 'public'],
19
- * residencyTag: 'US' },
20
- * },
21
- * defaultClassification: 'personal',
22
- * refuseUnclassified: true,
23
- * });
24
- *
25
- * Classification routing (per-call):
26
- * storage.saveFile(buf, 'invoice.pdf', { classification: 'personal' })
27
- * → routes to a backend whose `classifications` includes 'personal'.
28
- * storage.saveFile(buf, 'logo.png', { backend: 'us-ops' })
29
- * → explicit backend; framework still validates the backend serves
30
- * the classification.
31
- *
32
- * Residency enforcement (boot-time):
33
- * - If db.getDataResidency() declares a region, every backend serving the
34
- * 'personal' classification must have residencyTag === region (or be
35
- * listed in dataResidency.allowedStorageRegions).
36
- * - Refuses to boot otherwise — catches operator misconfiguration where
37
- * a US-region backend was configured for personal data in an EU app.
38
- *
39
- * Audit hooks:
40
- * - Every saveFile records a 'system.storage.write' event with metadata
41
- * { backend, classification, residencyTag, sizeBytes }.
42
- * - getFile records 'system.storage.read'.
43
- * - delete records 'system.storage.delete'.
44
- *
45
- * Public API (sync entry, async ops since backends may be remote):
46
- * storage.init(opts) (sync)
47
- * storage.saveFile(buffer, key, opts?) async → { storedPath, encryptionKey, backend, classification }
48
- * storage.getFileBuffer(storedPath, sealedKey, opts?) async → Buffer
49
- * storage.getFileStream(storedPath, sealedKey, opts?) async → Readable
50
- * storage.saveRaw(buffer, key, opts?) async → { storedPath, backend }
51
- * storage.getRawBuffer(storedPath, opts?) async → Buffer
52
- * storage.deleteFile(storedPath, opts?) async → boolean
53
- * storage.exists(storedPath, opts?) async → boolean
54
- * storage.presignedUploadUrl(key, opts?) → { url, method, headers, expiresAt }
55
- * storage.presignedDownloadUrl(key, opts?) → { url, method, headers, expiresAt }
56
- * storage.presignedUploadPolicy(key, opts) → { url, method, fields, expiresAt, maxBytes, enforcement }
57
- * storage.listBackends() → [{ name, protocol, classifications, residencyTag }]
58
- * storage.getBackend(name) → backend instance (or null)
59
- */
60
- var C = require("./constants");
61
- var { generateBytes, encryptPacked, decryptPacked } = require("./crypto");
62
- var objectStore = require("./object-store");
63
- var lazyRequire = require("./lazy-require");
64
- var { StorageError } = require("./framework-error");
65
-
66
- var vault = lazyRequire(function () { return require("./vault"); });
67
- var audit = lazyRequire(function () { return require("./audit"); });
68
- var db = lazyRequire(function () { return require("./db"); });
69
-
70
- var initialized = false;
71
- var backends = {}; // name → backend instance from object-store
72
- var defaultClassification = null;
73
- var refuseUnclassified = false;
74
-
75
- var _err = StorageError.factory;
76
-
77
- // ---- Init ----
78
-
79
- function init(opts) {
80
- if (initialized) return;
81
- if (!opts) throw _err("INVALID_CONFIG", "storage.init() requires options", true);
82
-
83
- // Normalize single-backend config into multi-backend form
84
- var normalized = _normalizeConfig(opts);
85
-
86
- defaultClassification = normalized.defaultClassification;
87
- refuseUnclassified = !!normalized.refuseUnclassified;
88
-
89
- backends = {};
90
- for (var name in normalized.backends) {
91
- var cfg = Object.assign({}, normalized.backends[name], { name: name });
92
- backends[name] = objectStore.buildBackend(cfg);
93
- }
94
-
95
- // Boot-time residency validation
96
- _validateResidency();
97
-
98
- initialized = true;
99
- }
100
-
101
- function _normalizeConfig(opts) {
102
- if (opts.backends) {
103
- return {
104
- backends: opts.backends,
105
- defaultClassification: opts.defaultClassification || null,
106
- refuseUnclassified: !!opts.refuseUnclassified,
107
- };
108
- }
109
- // Single-backend syntax: { backend, uploadDir, ... }
110
- if (opts.backend) {
111
- if (opts.backend === "s3") {
112
- throw _err("INVALID_CONFIG",
113
- "storage backend 's3' is now spelled 'sigv4' (covers AWS S3, R2, B2, " +
114
- "MinIO, Wasabi, Tigris, DO Spaces, IDrive e2, Storj, Linode). " +
115
- "Use { backend: 'sigv4', endpoint, region, bucket, accessKeyId, secretAccessKey }.",
116
- true);
117
- }
118
- if (opts.backend === "local") {
119
- return {
120
- backends: {
121
- "default": {
122
- protocol: "local",
123
- rootDir: opts.uploadDir,
124
- classifications: ["*"],
125
- residencyTag: "unrestricted",
126
- },
127
- },
128
- defaultClassification: null,
129
- refuseUnclassified: false,
130
- };
131
- }
132
- if (opts.backend === "http-put" || opts.backend === "sigv4" || opts.backend === "gcs" || opts.backend === "azure-blob") {
133
- // Forward as-is; user provided a single-backend spec for a remote protocol
134
- return {
135
- backends: { "default": Object.assign({}, opts, { name: undefined }) },
136
- defaultClassification: null,
137
- refuseUnclassified: false,
138
- };
139
- }
140
- throw _err("INVALID_CONFIG",
141
- "storage.init: unknown backend '" + opts.backend + "'", true);
142
- }
143
- throw _err("INVALID_CONFIG",
144
- "storage.init: must provide either { backend } or { backends }", true);
145
- }
146
-
147
- function _validateResidency() {
148
- var residency;
149
- try { residency = db().getDataResidency(); } catch (_e) { residency = null; }
150
- if (!residency || !residency.region) return;
151
-
152
- var allowed = [residency.region].concat(residency.allowedStorageRegions || []);
153
-
154
- for (var name in backends) {
155
- var b = backends[name];
156
- var serves = b.classifications.indexOf("*") !== -1 || b.classifications.indexOf("personal") !== -1;
157
- if (!serves) continue;
158
- if (allowed.indexOf(b.residencyTag) === -1) {
159
- throw _err(
160
- "RESIDENCY_VIOLATION",
161
- "backend '" + name + "' serves 'personal' data with residencyTag '" + b.residencyTag +
162
- "' but app's dataResidency.region is '" + residency.region + "' (allowed: " + allowed.join(", ") + ")",
163
- true
164
- );
165
- }
166
- }
167
-
168
- // If defaultClassification is 'personal', confirm at least one backend serves it
169
- if (defaultClassification === "personal") {
170
- var found = false;
171
- for (var n in backends) {
172
- if (backends[n].servesClassification("personal")) { found = true; break; }
173
- }
174
- if (!found) {
175
- throw _err("NO_PERSONAL_BACKEND",
176
- "defaultClassification='personal' but no backend declares 'personal' in classifications", true);
177
- }
178
- }
179
- }
180
-
181
- // ---- Backend selection ----
182
-
183
- function _pickBackend(opts) {
184
- opts = opts || {};
185
- if (opts.backend) {
186
- var b = backends[opts.backend];
187
- if (!b) throw _err("UNKNOWN_BACKEND", "no backend named '" + opts.backend + "'", true);
188
- if (opts.classification && !b.servesClassification(opts.classification)) {
189
- throw _err("CLASSIFICATION_MISMATCH",
190
- "backend '" + opts.backend + "' does not serve classification '" + opts.classification + "'", true);
191
- }
192
- return { backend: b, classification: opts.classification || null };
193
- }
194
-
195
- // refuseUnclassified forces every call to declare classification explicitly,
196
- // even when defaultClassification is configured. The default is for
197
- // convenience; refuseUnclassified is for explicit boundary enforcement.
198
- if (refuseUnclassified && !opts.classification) {
199
- throw _err("UNCLASSIFIED",
200
- "saveFile requires { classification } (or set { backend } explicitly); " +
201
- "framework is configured with refuseUnclassified: true", true);
202
- }
203
- var classification = opts.classification || defaultClassification;
204
- if (!classification) {
205
- // No classification + no refusal → pick any backend
206
- for (var n in backends) return { backend: backends[n], classification: null };
207
- throw _err("NO_BACKENDS", "no backends configured", true);
208
- }
209
-
210
- for (var name in backends) {
211
- if (backends[name].servesClassification(classification)) {
212
- return { backend: backends[name], classification: classification };
213
- }
214
- }
215
- throw _err("NO_BACKEND_FOR_CLASSIFICATION",
216
- "no backend serves classification '" + classification + "'", true);
217
- }
218
-
219
- // ---- File encryption helpers ----
220
-
221
- function _encryptBuffer(buffer) {
222
- var key = generateBytes(C.BYTES.bytes(32));
223
- var packed = encryptPacked(buffer, key);
224
- var sealedKey = vault().seal(key.toString("base64"));
225
- return { data: packed, encryptionKey: sealedKey };
226
- }
227
-
228
- function _decryptBuffer(packed, sealedKey) {
229
- if (!sealedKey) {
230
- throw _err("KEY_REQUIRED", "encryptionKey is required (no legacy plaintext support)", true);
231
- }
232
- var key = Buffer.from(vault().unseal(sealedKey), "base64");
233
- return decryptPacked(packed, key);
234
- }
235
-
236
- // ---- Audit emission ----
237
-
238
- function _emit(action, info) {
239
- // safeEmit handles default-fill + try/catch. Audit must never block
240
- // storage operations — if it fails the missing entry shows up at the
241
- // next chain verify.
242
- audit().safeEmit({ action: action, ...(info || {}) });
243
- }
244
-
245
- // ---- Public API ----
246
-
247
- async function saveFile(buffer, key, opts) {
248
- _requireInit();
249
- if (!Buffer.isBuffer(buffer)) throw _err("INVALID_BODY", "saveFile body must be a Buffer", true);
250
- opts = opts || {};
251
- var picked = _pickBackend(opts);
252
- var enc = _encryptBuffer(buffer);
253
- var result = await picked.backend.put(key, enc.data, opts);
254
- _emit("system.storage.write", {
255
- metadata: {
256
- backend: picked.backend.name,
257
- classification: picked.classification,
258
- residencyTag: picked.backend.residencyTag,
259
- key: key,
260
- sizeBytes: result.size != null ? result.size : enc.data.length,
261
- },
262
- });
263
- return {
264
- storedPath: key,
265
- encryptionKey: enc.encryptionKey,
266
- backend: picked.backend.name,
267
- classification: picked.classification,
268
- };
269
- }
270
-
271
- async function getFileBuffer(key, sealedKey, opts) {
272
- _requireInit();
273
- opts = opts || {};
274
- var picked = _pickBackend(opts);
275
- var packed = await picked.backend.get(key);
276
- var decrypted = _decryptBuffer(packed, sealedKey);
277
- _emit("system.storage.read", {
278
- metadata: {
279
- backend: picked.backend.name,
280
- key: key,
281
- sizeBytes: decrypted.length,
282
- },
283
- });
284
- return decrypted;
285
- }
286
-
287
- async function getFileStream(key, sealedKey, opts) {
288
- // Buffer-then-stream: per-file XChaCha20 encryption needs the whole
289
- // ciphertext to verify the AEAD tag before any plaintext can be released
290
- // to the consumer. Chunked-encryption with per-chunk AEAD would let us
291
- // stream end-to-end, but at the cost of finer-grained tampering windows.
292
- var buf = await getFileBuffer(key, sealedKey, opts);
293
- return require("stream").Readable.from(buf);
294
- }
295
-
296
- async function saveRaw(buffer, key, opts) {
297
- _requireInit();
298
- if (!Buffer.isBuffer(buffer)) throw _err("INVALID_BODY", "saveRaw body must be a Buffer", true);
299
- opts = opts || {};
300
- var picked = _pickBackend(opts);
301
- var result = await picked.backend.put(key, buffer, opts);
302
- _emit("system.storage.write", {
303
- metadata: {
304
- backend: picked.backend.name,
305
- classification: picked.classification,
306
- residencyTag: picked.backend.residencyTag,
307
- key: key,
308
- sizeBytes: result.size != null ? result.size : buffer.length,
309
- raw: true,
310
- },
311
- });
312
- return { storedPath: key, backend: picked.backend.name };
313
- }
314
-
315
- async function getRawBuffer(key, opts) {
316
- _requireInit();
317
- opts = opts || {};
318
- var picked = _pickBackend(opts);
319
- return picked.backend.get(key);
320
- }
321
-
322
- async function deleteFile(key, opts) {
323
- _requireInit();
324
- opts = opts || {};
325
- var picked = _pickBackend(opts);
326
- var result = await picked.backend.delete(key);
327
- _emit("system.storage.delete", {
328
- metadata: {
329
- backend: picked.backend.name,
330
- key: key,
331
- existed: result,
332
- },
333
- });
334
- return result;
335
- }
336
-
337
- async function exists(key, opts) {
338
- _requireInit();
339
- opts = opts || {};
340
- var picked = _pickBackend(opts);
341
- try {
342
- await picked.backend.head(key);
343
- return true;
344
- } catch (e) {
345
- if (e && e.code === "NOT_FOUND") return false;
346
- throw e;
347
- }
348
- }
349
-
350
- function listBackends() {
351
- _requireInit();
352
- var out = [];
353
- for (var name in backends) {
354
- out.push({
355
- name: name,
356
- protocol: backends[name].protocol,
357
- classifications: backends[name].classifications.slice(),
358
- residencyTag: backends[name].residencyTag,
359
- breakerState: backends[name].breaker.getState(),
360
- });
361
- }
362
- return out;
363
- }
364
-
365
- function _presign(direction, key, opts) {
366
- _requireInit();
367
- if (typeof key !== "string" || key.length === 0) {
368
- throw _err("INVALID_KEY", "presigned" + direction + "Url: key is required", true);
369
- }
370
- opts = opts || {};
371
- var picked = _pickBackend(opts);
372
- var fnName = "presigned" + direction + "Url";
373
- if (typeof picked.backend[fnName] !== "function") {
374
- throw _err("PRESIGN_NOT_SUPPORTED",
375
- "backend '" + picked.backend.name + "' (protocol '" + picked.backend.protocol +
376
- "') does not support presigned " + direction.toLowerCase() + " URLs", true);
377
- }
378
- var result = picked.backend[fnName](Object.assign({}, opts, { key: key }));
379
- _emit("system.storage.presign", {
380
- metadata: {
381
- direction: direction.toLowerCase(),
382
- backend: picked.backend.name,
383
- classification: picked.classification,
384
- residencyTag: picked.backend.residencyTag,
385
- key: key,
386
- expiresAt: result.expiresAt,
387
- },
388
- });
389
- return result;
390
- }
391
-
392
- function presignedUploadUrl(key, opts) { return _presign("Upload", key, opts); }
393
- function presignedDownloadUrl(key, opts) { return _presign("Download", key, opts); }
394
-
395
- // presignedUploadPolicy — issues a POST-form policy (or vendor-equivalent
396
- // PUT) that the client uses to upload directly to the object store with
397
- // server-side body-size enforcement. Distinct from presignedUploadUrl
398
- // because that signs only the URL; this signs a full policy document
399
- // that includes a content-length-range condition.
400
- //
401
- // Vendor enforcement:
402
- // sigv4 — content-length-range condition; S3 rejects bodies outside
403
- // gcs — content-length-range condition; GCS rejects bodies outside
404
- // azure — SAS doesn't natively cap body size; returns SAS PUT URL
405
- // with enforcement: "client-only" — operator must HEAD the
406
- // blob post-upload and reject if oversize
407
- // local — NOT_SUPPORTED (use saveFile directly)
408
- // http-put — NOT_SUPPORTED (no signing convention)
409
- function presignedUploadPolicy(key, opts) {
410
- _requireInit();
411
- if (typeof key !== "string" || key.length === 0) {
412
- throw _err("INVALID_KEY", "presignedUploadPolicy: key is required", true);
413
- }
414
- opts = opts || {};
415
- var picked = _pickBackend(opts);
416
- if (typeof picked.backend.presignedUploadPolicy !== "function") {
417
- throw _err("PRESIGN_NOT_SUPPORTED",
418
- "backend '" + picked.backend.name + "' (protocol '" + picked.backend.protocol +
419
- "') does not support presigned upload policies", true);
420
- }
421
- var result = picked.backend.presignedUploadPolicy(Object.assign({}, opts, { key: key }));
422
- _emit("system.storage.presign", {
423
- metadata: {
424
- direction: "upload-policy",
425
- backend: picked.backend.name,
426
- classification: picked.classification,
427
- residencyTag: picked.backend.residencyTag,
428
- key: key,
429
- expiresAt: result.expiresAt,
430
- maxBytes: result.maxBytes,
431
- enforcement: result.enforcement,
432
- },
433
- });
434
- return result;
435
- }
436
-
437
- function getBackend(name) {
438
- _requireInit();
439
- return backends[name] || null;
440
- }
441
-
442
- function _requireInit() {
443
- if (!initialized) throw _err("NOT_INITIALIZED", "storage.init() must be called before any file operation", true);
444
- }
445
-
446
- function _resetForTest() {
447
- initialized = false;
448
- backends = {};
449
- defaultClassification = null;
450
- refuseUnclassified = false;
451
- vault.reset();
452
- audit.reset();
453
- db.reset();
454
- }
455
-
456
- module.exports = {
457
- init: init,
458
- saveFile: saveFile,
459
- getFileBuffer: getFileBuffer,
460
- getFileStream: getFileStream,
461
- saveRaw: saveRaw,
462
- getRawBuffer: getRawBuffer,
463
- deleteFile: deleteFile,
464
- exists: exists,
465
- presignedUploadUrl: presignedUploadUrl,
466
- presignedDownloadUrl: presignedDownloadUrl,
467
- presignedUploadPolicy: presignedUploadPolicy,
468
- listBackends: listBackends,
469
- getBackend: getBackend,
470
- _resetForTest: _resetForTest,
471
- };
1
+ "use strict";
2
+ /**
3
+ * Storage abstraction — multi-backend, classification-routed, residency-
4
+ * enforced file storage with per-file vault-sealed encryption.
5
+ *
6
+ * Two configuration shapes (both supported, internally normalized to
7
+ * the multi-backend form):
8
+ *
9
+ * 1. Single-backend (legacy shape — preserved):
10
+ * storage.init({ backend: 'local', uploadDir: './data/uploads' })
11
+ *
12
+ * 2. Multi-backend:
13
+ * storage.init({
14
+ * backends: {
15
+ * 'eu-private': { protocol: 'http-put', baseUrl: '...',
16
+ * classifications: ['personal'], residencyTag: 'EU' },
17
+ * 'us-ops': { protocol: 'local', rootDir: '/data/ops',
18
+ * classifications: ['operational', 'public'],
19
+ * residencyTag: 'US' },
20
+ * },
21
+ * defaultClassification: 'personal',
22
+ * refuseUnclassified: true,
23
+ * });
24
+ *
25
+ * Classification routing (per-call):
26
+ * storage.saveFile(buf, 'invoice.pdf', { classification: 'personal' })
27
+ * → routes to a backend whose `classifications` includes 'personal'.
28
+ * storage.saveFile(buf, 'logo.png', { backend: 'us-ops' })
29
+ * → explicit backend; framework still validates the backend serves
30
+ * the classification.
31
+ *
32
+ * Residency enforcement (boot-time):
33
+ * - If db.getDataResidency() declares a region, every backend serving the
34
+ * 'personal' classification must have residencyTag === region (or be
35
+ * listed in dataResidency.allowedStorageRegions).
36
+ * - Refuses to boot otherwise — catches operator misconfiguration where
37
+ * a US-region backend was configured for personal data in an EU app.
38
+ *
39
+ * Audit hooks:
40
+ * - Every saveFile records a 'system.storage.write' event with metadata
41
+ * { backend, classification, residencyTag, sizeBytes }.
42
+ * - getFile records 'system.storage.read'.
43
+ * - delete records 'system.storage.delete'.
44
+ *
45
+ * Public API (sync entry, async ops since backends may be remote):
46
+ * storage.init(opts) (sync)
47
+ * storage.saveFile(buffer, key, opts?) async → { storedPath, encryptionKey, backend, classification }
48
+ * storage.getFileBuffer(storedPath, sealedKey, opts?) async → Buffer
49
+ * storage.getFileStream(storedPath, sealedKey, opts?) async → Readable
50
+ * storage.saveRaw(buffer, key, opts?) async → { storedPath, backend }
51
+ * storage.getRawBuffer(storedPath, opts?) async → Buffer
52
+ * storage.deleteFile(storedPath, opts?) async → boolean
53
+ * storage.exists(storedPath, opts?) async → boolean
54
+ * storage.presignedUploadUrl(key, opts?) → { url, method, headers, expiresAt }
55
+ * storage.presignedDownloadUrl(key, opts?) → { url, method, headers, expiresAt }
56
+ * storage.presignedUploadPolicy(key, opts) → { url, method, fields, expiresAt, maxBytes, enforcement }
57
+ * storage.listBackends() → [{ name, protocol, classifications, residencyTag }]
58
+ * storage.getBackend(name) → backend instance (or null)
59
+ */
60
+ var C = require("./constants");
61
+ var { generateBytes, encryptPacked, decryptPacked } = require("./crypto");
62
+ var objectStore = require("./object-store");
63
+ var lazyRequire = require("./lazy-require");
64
+ var { StorageError } = require("./framework-error");
65
+
66
+ var vault = lazyRequire(function () { return require("./vault"); });
67
+ var audit = lazyRequire(function () { return require("./audit"); });
68
+ var db = lazyRequire(function () { return require("./db"); });
69
+
70
+ var initialized = false;
71
+ var backends = {}; // name → backend instance from object-store
72
+ var defaultClassification = null;
73
+ var refuseUnclassified = false;
74
+
75
+ var _err = StorageError.factory;
76
+
77
+ // ---- Init ----
78
+
79
+ function init(opts) {
80
+ if (initialized) return;
81
+ if (!opts) throw _err("INVALID_CONFIG", "storage.init() requires options", true);
82
+
83
+ // Normalize single-backend config into multi-backend form
84
+ var normalized = _normalizeConfig(opts);
85
+
86
+ defaultClassification = normalized.defaultClassification;
87
+ refuseUnclassified = !!normalized.refuseUnclassified;
88
+
89
+ backends = {};
90
+ for (var name in normalized.backends) {
91
+ var cfg = Object.assign({}, normalized.backends[name], { name: name });
92
+ backends[name] = objectStore.buildBackend(cfg);
93
+ }
94
+
95
+ // Boot-time residency validation
96
+ _validateResidency();
97
+
98
+ initialized = true;
99
+ }
100
+
101
+ function _normalizeConfig(opts) {
102
+ if (opts.backends) {
103
+ return {
104
+ backends: opts.backends,
105
+ defaultClassification: opts.defaultClassification || null,
106
+ refuseUnclassified: !!opts.refuseUnclassified,
107
+ };
108
+ }
109
+ // Single-backend syntax: { backend, uploadDir, ... }
110
+ if (opts.backend) {
111
+ if (opts.backend === "s3") {
112
+ throw _err("INVALID_CONFIG",
113
+ "storage backend 's3' is now spelled 'sigv4' (covers AWS S3, R2, B2, " +
114
+ "MinIO, Wasabi, Tigris, DO Spaces, IDrive e2, Storj, Linode). " +
115
+ "Use { backend: 'sigv4', endpoint, region, bucket, accessKeyId, secretAccessKey }.",
116
+ true);
117
+ }
118
+ if (opts.backend === "local") {
119
+ return {
120
+ backends: {
121
+ "default": {
122
+ protocol: "local",
123
+ rootDir: opts.uploadDir,
124
+ classifications: ["*"],
125
+ residencyTag: "unrestricted",
126
+ },
127
+ },
128
+ defaultClassification: null,
129
+ refuseUnclassified: false,
130
+ };
131
+ }
132
+ if (opts.backend === "http-put" || opts.backend === "sigv4" || opts.backend === "gcs" || opts.backend === "azure-blob") {
133
+ // Forward as-is; user provided a single-backend spec for a remote protocol
134
+ return {
135
+ backends: { "default": Object.assign({}, opts, { name: undefined }) },
136
+ defaultClassification: null,
137
+ refuseUnclassified: false,
138
+ };
139
+ }
140
+ throw _err("INVALID_CONFIG",
141
+ "storage.init: unknown backend '" + opts.backend + "'", true);
142
+ }
143
+ throw _err("INVALID_CONFIG",
144
+ "storage.init: must provide either { backend } or { backends }", true);
145
+ }
146
+
147
+ function _validateResidency() {
148
+ var residency;
149
+ try { residency = db().getDataResidency(); } catch (_e) { residency = null; }
150
+ if (!residency || !residency.region) return;
151
+
152
+ var allowed = [residency.region].concat(residency.allowedStorageRegions || []);
153
+
154
+ for (var name in backends) {
155
+ var b = backends[name];
156
+ var serves = b.classifications.indexOf("*") !== -1 || b.classifications.indexOf("personal") !== -1;
157
+ if (!serves) continue;
158
+ if (allowed.indexOf(b.residencyTag) === -1) {
159
+ throw _err(
160
+ "RESIDENCY_VIOLATION",
161
+ "backend '" + name + "' serves 'personal' data with residencyTag '" + b.residencyTag +
162
+ "' but app's dataResidency.region is '" + residency.region + "' (allowed: " + allowed.join(", ") + ")",
163
+ true
164
+ );
165
+ }
166
+ }
167
+
168
+ // If defaultClassification is 'personal', confirm at least one backend serves it
169
+ if (defaultClassification === "personal") {
170
+ var found = false;
171
+ for (var n in backends) {
172
+ if (backends[n].servesClassification("personal")) { found = true; break; }
173
+ }
174
+ if (!found) {
175
+ throw _err("NO_PERSONAL_BACKEND",
176
+ "defaultClassification='personal' but no backend declares 'personal' in classifications", true);
177
+ }
178
+ }
179
+ }
180
+
181
+ // ---- Backend selection ----
182
+
183
+ function _pickBackend(opts) {
184
+ opts = opts || {};
185
+ if (opts.backend) {
186
+ var b = backends[opts.backend];
187
+ if (!b) throw _err("UNKNOWN_BACKEND", "no backend named '" + opts.backend + "'", true);
188
+ if (opts.classification && !b.servesClassification(opts.classification)) {
189
+ throw _err("CLASSIFICATION_MISMATCH",
190
+ "backend '" + opts.backend + "' does not serve classification '" + opts.classification + "'", true);
191
+ }
192
+ return { backend: b, classification: opts.classification || null };
193
+ }
194
+
195
+ // refuseUnclassified forces every call to declare classification explicitly,
196
+ // even when defaultClassification is configured. The default is for
197
+ // convenience; refuseUnclassified is for explicit boundary enforcement.
198
+ if (refuseUnclassified && !opts.classification) {
199
+ throw _err("UNCLASSIFIED",
200
+ "saveFile requires { classification } (or set { backend } explicitly); " +
201
+ "framework is configured with refuseUnclassified: true", true);
202
+ }
203
+ var classification = opts.classification || defaultClassification;
204
+ if (!classification) {
205
+ // No classification + no refusal → pick any backend
206
+ for (var n in backends) return { backend: backends[n], classification: null };
207
+ throw _err("NO_BACKENDS", "no backends configured", true);
208
+ }
209
+
210
+ for (var name in backends) {
211
+ if (backends[name].servesClassification(classification)) {
212
+ return { backend: backends[name], classification: classification };
213
+ }
214
+ }
215
+ throw _err("NO_BACKEND_FOR_CLASSIFICATION",
216
+ "no backend serves classification '" + classification + "'", true);
217
+ }
218
+
219
+ // ---- File encryption helpers ----
220
+
221
+ function _encryptBuffer(buffer) {
222
+ var key = generateBytes(C.BYTES.bytes(32));
223
+ var packed = encryptPacked(buffer, key);
224
+ var sealedKey = vault().seal(key.toString("base64"));
225
+ return { data: packed, encryptionKey: sealedKey };
226
+ }
227
+
228
+ function _decryptBuffer(packed, sealedKey) {
229
+ if (!sealedKey) {
230
+ throw _err("KEY_REQUIRED", "encryptionKey is required (no legacy plaintext support)", true);
231
+ }
232
+ var key = Buffer.from(vault().unseal(sealedKey), "base64");
233
+ return decryptPacked(packed, key);
234
+ }
235
+
236
+ // ---- Audit emission ----
237
+
238
+ function _emit(action, info) {
239
+ // safeEmit handles default-fill + try/catch. Audit must never block
240
+ // storage operations — if it fails the missing entry shows up at the
241
+ // next chain verify.
242
+ audit().safeEmit({ action: action, ...(info || {}) });
243
+ }
244
+
245
+ // ---- Public API ----
246
+
247
+ async function saveFile(buffer, key, opts) {
248
+ _requireInit();
249
+ if (!Buffer.isBuffer(buffer)) throw _err("INVALID_BODY", "saveFile body must be a Buffer", true);
250
+ opts = opts || {};
251
+ var picked = _pickBackend(opts);
252
+ var enc = _encryptBuffer(buffer);
253
+ var result = await picked.backend.put(key, enc.data, opts);
254
+ _emit("system.storage.write", {
255
+ metadata: {
256
+ backend: picked.backend.name,
257
+ classification: picked.classification,
258
+ residencyTag: picked.backend.residencyTag,
259
+ key: key,
260
+ sizeBytes: result.size != null ? result.size : enc.data.length,
261
+ },
262
+ });
263
+ return {
264
+ storedPath: key,
265
+ encryptionKey: enc.encryptionKey,
266
+ backend: picked.backend.name,
267
+ classification: picked.classification,
268
+ };
269
+ }
270
+
271
+ async function getFileBuffer(key, sealedKey, opts) {
272
+ _requireInit();
273
+ opts = opts || {};
274
+ var picked = _pickBackend(opts);
275
+ var packed = await picked.backend.get(key);
276
+ var decrypted = _decryptBuffer(packed, sealedKey);
277
+ _emit("system.storage.read", {
278
+ metadata: {
279
+ backend: picked.backend.name,
280
+ key: key,
281
+ sizeBytes: decrypted.length,
282
+ },
283
+ });
284
+ return decrypted;
285
+ }
286
+
287
+ async function getFileStream(key, sealedKey, opts) {
288
+ // Buffer-then-stream: per-file XChaCha20 encryption needs the whole
289
+ // ciphertext to verify the AEAD tag before any plaintext can be released
290
+ // to the consumer. Chunked-encryption with per-chunk AEAD would let us
291
+ // stream end-to-end, but at the cost of finer-grained tampering windows.
292
+ var buf = await getFileBuffer(key, sealedKey, opts);
293
+ return require("stream").Readable.from(buf);
294
+ }
295
+
296
+ async function saveRaw(buffer, key, opts) {
297
+ _requireInit();
298
+ if (!Buffer.isBuffer(buffer)) throw _err("INVALID_BODY", "saveRaw body must be a Buffer", true);
299
+ opts = opts || {};
300
+ var picked = _pickBackend(opts);
301
+ var result = await picked.backend.put(key, buffer, opts);
302
+ _emit("system.storage.write", {
303
+ metadata: {
304
+ backend: picked.backend.name,
305
+ classification: picked.classification,
306
+ residencyTag: picked.backend.residencyTag,
307
+ key: key,
308
+ sizeBytes: result.size != null ? result.size : buffer.length,
309
+ raw: true,
310
+ },
311
+ });
312
+ return { storedPath: key, backend: picked.backend.name };
313
+ }
314
+
315
+ async function getRawBuffer(key, opts) {
316
+ _requireInit();
317
+ opts = opts || {};
318
+ var picked = _pickBackend(opts);
319
+ return picked.backend.get(key);
320
+ }
321
+
322
+ async function deleteFile(key, opts) {
323
+ _requireInit();
324
+ opts = opts || {};
325
+ var picked = _pickBackend(opts);
326
+ var result = await picked.backend.delete(key);
327
+ _emit("system.storage.delete", {
328
+ metadata: {
329
+ backend: picked.backend.name,
330
+ key: key,
331
+ existed: result,
332
+ },
333
+ });
334
+ return result;
335
+ }
336
+
337
+ async function exists(key, opts) {
338
+ _requireInit();
339
+ opts = opts || {};
340
+ var picked = _pickBackend(opts);
341
+ try {
342
+ await picked.backend.head(key);
343
+ return true;
344
+ } catch (e) {
345
+ if (e && e.code === "NOT_FOUND") return false;
346
+ throw e;
347
+ }
348
+ }
349
+
350
+ function listBackends() {
351
+ _requireInit();
352
+ var out = [];
353
+ for (var name in backends) {
354
+ out.push({
355
+ name: name,
356
+ protocol: backends[name].protocol,
357
+ classifications: backends[name].classifications.slice(),
358
+ residencyTag: backends[name].residencyTag,
359
+ breakerState: backends[name].breaker.getState(),
360
+ });
361
+ }
362
+ return out;
363
+ }
364
+
365
+ function _presign(direction, key, opts) {
366
+ _requireInit();
367
+ if (typeof key !== "string" || key.length === 0) {
368
+ throw _err("INVALID_KEY", "presigned" + direction + "Url: key is required", true);
369
+ }
370
+ opts = opts || {};
371
+ var picked = _pickBackend(opts);
372
+ var fnName = "presigned" + direction + "Url";
373
+ if (typeof picked.backend[fnName] !== "function") {
374
+ throw _err("PRESIGN_NOT_SUPPORTED",
375
+ "backend '" + picked.backend.name + "' (protocol '" + picked.backend.protocol +
376
+ "') does not support presigned " + direction.toLowerCase() + " URLs", true);
377
+ }
378
+ var result = picked.backend[fnName](Object.assign({}, opts, { key: key }));
379
+ _emit("system.storage.presign", {
380
+ metadata: {
381
+ direction: direction.toLowerCase(),
382
+ backend: picked.backend.name,
383
+ classification: picked.classification,
384
+ residencyTag: picked.backend.residencyTag,
385
+ key: key,
386
+ expiresAt: result.expiresAt,
387
+ },
388
+ });
389
+ return result;
390
+ }
391
+
392
+ function presignedUploadUrl(key, opts) { return _presign("Upload", key, opts); }
393
+ function presignedDownloadUrl(key, opts) { return _presign("Download", key, opts); }
394
+
395
+ // presignedUploadPolicy — issues a POST-form policy (or vendor-equivalent
396
+ // PUT) that the client uses to upload directly to the object store with
397
+ // server-side body-size enforcement. Distinct from presignedUploadUrl
398
+ // because that signs only the URL; this signs a full policy document
399
+ // that includes a content-length-range condition.
400
+ //
401
+ // Vendor enforcement:
402
+ // sigv4 — content-length-range condition; S3 rejects bodies outside
403
+ // gcs — content-length-range condition; GCS rejects bodies outside
404
+ // azure — SAS doesn't natively cap body size; returns SAS PUT URL
405
+ // with enforcement: "client-only" — operator must HEAD the
406
+ // blob post-upload and reject if oversize
407
+ // local — NOT_SUPPORTED (use saveFile directly)
408
+ // http-put — NOT_SUPPORTED (no signing convention)
409
+ function presignedUploadPolicy(key, opts) {
410
+ _requireInit();
411
+ if (typeof key !== "string" || key.length === 0) {
412
+ throw _err("INVALID_KEY", "presignedUploadPolicy: key is required", true);
413
+ }
414
+ opts = opts || {};
415
+ var picked = _pickBackend(opts);
416
+ if (typeof picked.backend.presignedUploadPolicy !== "function") {
417
+ throw _err("PRESIGN_NOT_SUPPORTED",
418
+ "backend '" + picked.backend.name + "' (protocol '" + picked.backend.protocol +
419
+ "') does not support presigned upload policies", true);
420
+ }
421
+ var result = picked.backend.presignedUploadPolicy(Object.assign({}, opts, { key: key }));
422
+ _emit("system.storage.presign", {
423
+ metadata: {
424
+ direction: "upload-policy",
425
+ backend: picked.backend.name,
426
+ classification: picked.classification,
427
+ residencyTag: picked.backend.residencyTag,
428
+ key: key,
429
+ expiresAt: result.expiresAt,
430
+ maxBytes: result.maxBytes,
431
+ enforcement: result.enforcement,
432
+ },
433
+ });
434
+ return result;
435
+ }
436
+
437
+ function getBackend(name) {
438
+ _requireInit();
439
+ return backends[name] || null;
440
+ }
441
+
442
+ function _requireInit() {
443
+ if (!initialized) throw _err("NOT_INITIALIZED", "storage.init() must be called before any file operation", true);
444
+ }
445
+
446
+ function _resetForTest() {
447
+ initialized = false;
448
+ backends = {};
449
+ defaultClassification = null;
450
+ refuseUnclassified = false;
451
+ vault.reset();
452
+ audit.reset();
453
+ db.reset();
454
+ }
455
+
456
+ module.exports = {
457
+ init: init,
458
+ saveFile: saveFile,
459
+ getFileBuffer: getFileBuffer,
460
+ getFileStream: getFileStream,
461
+ saveRaw: saveRaw,
462
+ getRawBuffer: getRawBuffer,
463
+ deleteFile: deleteFile,
464
+ exists: exists,
465
+ presignedUploadUrl: presignedUploadUrl,
466
+ presignedDownloadUrl: presignedDownloadUrl,
467
+ presignedUploadPolicy: presignedUploadPolicy,
468
+ listBackends: listBackends,
469
+ getBackend: getBackend,
470
+ _resetForTest: _resetForTest,
471
+ };