@blamejs/core 0.4.1

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