@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
@@ -0,0 +1,553 @@
1
+ "use strict";
2
+ /**
3
+ * api-encrypt — end-to-end PQC payload encryption for operator-
4
+ * controlled clients.
5
+ *
6
+ * TLS protects browser ↔ load-balancer; api-encrypt protects request
7
+ * and response bodies *end-to-end* through every intermediate hop
8
+ * (LB → app cleartext segment, sidecar proxy, queue, log aggregator,
9
+ * APM tooling). A tampered byte anywhere downstream of the encrypted
10
+ * boundary fails the AEAD tag at this middleware before the route
11
+ * handler runs.
12
+ *
13
+ * Threat model targets:
14
+ * - Stripped-or-MITM TLS at any internal hop
15
+ * - Body capture at log aggregators / APM tooling
16
+ * - Replay (timestamp + nonce window catches it)
17
+ * - Forged client requests (no key holder = no valid ciphertext)
18
+ *
19
+ * What it does NOT defend against:
20
+ * - Semantic attacks from authorized clients (a key-holder can
21
+ * encrypt a malicious payload validly — safe-schema is the next
22
+ * layer)
23
+ * - Server-side key compromise
24
+ * - Application logic bugs in handlers
25
+ *
26
+ * The encryption layer is for operator-controlled clients (your
27
+ * mobile app, your service-to-service traffic). Public APIs that
28
+ * accept third-party callers should use TLS + webhook signatures
29
+ * instead — the encryption requires a key bootstrap step.
30
+ *
31
+ * Wire format (request body, JSON):
32
+ *
33
+ * {
34
+ * _ek: "<base64 envelope>", // session key wrapped to server pubkey
35
+ * _ct: "<base64 packed>", // payload encrypted with session key
36
+ * _ts: 1738000000000, // unix ms
37
+ * _nonce: "<32 hex>" // 16 random bytes, replay-checked
38
+ * }
39
+ *
40
+ * Wire format (response body, JSON):
41
+ *
42
+ * { _ct: "<base64 packed>" } // same session key, fresh nonce
43
+ *
44
+ * Crypto:
45
+ * - _ek is the framework's standard envelope encrypt:
46
+ * ML-KEM-1024 + P-384 ECDH hybrid → SHAKE256 KDF → XChaCha20-Poly1305
47
+ * The plaintext inside the envelope is the base64-encoded session key.
48
+ * - _ct is the framework's encryptPacked symmetric format:
49
+ * 1-byte version + 24-byte XChaCha20-Poly1305 nonce + ciphertext + tag
50
+ * Keyed by the session key recovered from _ek.
51
+ *
52
+ * Operator API:
53
+ *
54
+ * var apiEncrypt = b.middleware.apiEncrypt({
55
+ * keypair: { publicKey, privateKey, ecPublicKey, ecPrivateKey },
56
+ * replayWindowMs: C.TIME.minutes(5),
57
+ * nonceStore: b.nonceStore.create({ backend: 'cluster' }),
58
+ * exemptPaths: ["/healthz", "/.well-known/blamejs-pubkey"],
59
+ * contentTypes: ["application/json"], // default; pass null to disable
60
+ * });
61
+ * router.use(apiEncrypt);
62
+ * router.get("/.well-known/blamejs-pubkey", apiEncrypt.publishPublicKey());
63
+ *
64
+ * // Outbound (server-to-server, browser/mobile, etc.):
65
+ * var client = b.middleware.apiEncrypt.client({ pubkey });
66
+ * var { body, decryptResponse } = client.encryptRequest({ msg: "hi" });
67
+ *
68
+ * // Server-to-server with framework HTTP client:
69
+ * var enc = b.httpClient.encrypted({ pubkey, baseUrl: "https://service" });
70
+ * var resp = await enc.request({ method: "POST", path: "/api/widget", body: { ... } });
71
+ *
72
+ * Key rotation:
73
+ * To rotate the server keypair, generate a new keypair and pass BOTH
74
+ * the new and the previous keypair to the middleware as `keypairs`:
75
+ *
76
+ * b.middleware.apiEncrypt({
77
+ * keypairs: [newKeypair, prevKeypair],
78
+ * ...
79
+ * });
80
+ *
81
+ * keypairs[0] is the "active" keypair — published by publishPublicKey()
82
+ * so new client-side bootstraps pin to it. Both keypairs are tried
83
+ * when decrypting `_ek`, so in-flight requests still encrypted to the
84
+ * previous keypair continue to decrypt for as long as the previous
85
+ * keypair stays in the array. Operators drop the previous keypair
86
+ * from the array once the rotation overlap window has elapsed.
87
+ *
88
+ * Failure surfacing:
89
+ * AEAD tag failure / stale timestamp / replay / malformed envelope
90
+ * all return 400 with the same body { error: "encrypted-payload-rejected" }.
91
+ * The category that actually matched lands in the audit event +
92
+ * b.events.API_ENCRYPT_FAILURE so operators get metrics / alerting
93
+ * without leaking which check the attacker tripped. Missing _ek /
94
+ * _ct / _ts / _nonce on a non-exempt path is distinguishable in the
95
+ * response ("encrypted-payload-required") so operators with hybrid
96
+ * public/private routes can debug their wiring.
97
+ */
98
+
99
+ var crypto = require("../crypto");
100
+ var C = require("../constants");
101
+ var lazyRequire = require("../lazy-require");
102
+ var nonceStoreLib = require("../nonce-store");
103
+ var validateOpts = require("../validate-opts");
104
+ var { defineClass } = require("../framework-error");
105
+
106
+ var audit = lazyRequire(function () { return require("../audit"); });
107
+ var events = lazyRequire(function () { return require("../events"); });
108
+ var httpClient = lazyRequire(function () { return require("../http-client"); });
109
+ var logger = lazyRequire(function () { return require("../log").boot("api-encrypt"); });
110
+
111
+ var ApiEncryptError = defineClass("ApiEncryptError", { withStatusCode: true });
112
+
113
+ var DEFAULT_REPLAY_WINDOW_MS = C.TIME.minutes(5);
114
+ var DEFAULT_CONTENT_TYPES = ["application/json"];
115
+ var SESSION_KEY_BYTES = 32;
116
+ var REQUEST_NONCE_BYTES = 16;
117
+
118
+ function _err(code, message, statusCode) {
119
+ return new ApiEncryptError(code, message, true, statusCode || 400);
120
+ }
121
+
122
+ function _validateKeypair(kp, label) {
123
+ if (!kp || typeof kp !== "object") {
124
+ throw _err("INVALID_KEYPAIR", "apiEncrypt: " + label + " is required", 500);
125
+ }
126
+ if (typeof kp.publicKey !== "string" || typeof kp.privateKey !== "string") {
127
+ throw _err("INVALID_KEYPAIR",
128
+ "apiEncrypt: " + label + ".publicKey + .privateKey are required (ML-KEM-1024 PEM)", 500);
129
+ }
130
+ if (typeof kp.ecPublicKey !== "string" || typeof kp.ecPrivateKey !== "string") {
131
+ throw _err("INVALID_KEYPAIR",
132
+ "apiEncrypt: " + label + ".ecPublicKey + .ecPrivateKey are required (P-384 PEM hybrid)", 500);
133
+ }
134
+ }
135
+
136
+ // Resolve the operator's keypair input into an ordered array. The
137
+ // first keypair is "active" — used by publishPublicKey() and as the
138
+ // hint for response encryption (responses use the per-request session
139
+ // key, so the active keypair only matters for what the bootstrap
140
+ // endpoint advertises). Every keypair in the array is tried in order
141
+ // when decrypting `_ek` so that during a rotation overlap window,
142
+ // in-flight requests encrypted to a previous keypair still decrypt
143
+ // successfully.
144
+ function _resolveKeypairs(opts) {
145
+ if (Array.isArray(opts.keypairs)) {
146
+ if (opts.keypairs.length === 0) {
147
+ throw _err("INVALID_KEYPAIR", "apiEncrypt: keypairs must be a non-empty array", 500);
148
+ }
149
+ opts.keypairs.forEach(function (kp, i) { _validateKeypair(kp, "keypairs[" + i + "]"); });
150
+ return opts.keypairs.slice();
151
+ }
152
+ if (opts.keypair) {
153
+ _validateKeypair(opts.keypair, "keypair");
154
+ return [opts.keypair];
155
+ }
156
+ throw _err("INVALID_KEYPAIR",
157
+ "apiEncrypt: { keypair } or { keypairs: [...] } is required", 500);
158
+ }
159
+
160
+ function _writeRejection(res, code, body) {
161
+ if (res.headersSent || res.writableEnded) return;
162
+ if (typeof res.writeHead === "function") {
163
+ res.writeHead(code, { "Content-Type": "application/json" });
164
+ res.end(JSON.stringify(body));
165
+ }
166
+ }
167
+
168
+ // ---- Server-side middleware ----
169
+
170
+ function create(opts) {
171
+ opts = opts || {};
172
+ validateOpts(opts, [
173
+ "keypair", "keypairs", "replayWindowMs", "pruneIntervalMs",
174
+ "nonceStore", "exemptPaths", "contentTypes", "audit",
175
+ ], "middleware.apiEncrypt");
176
+ var keypairs = _resolveKeypairs(opts);
177
+ var activeKeypair = keypairs[0];
178
+ var replayWindowMs = opts.replayWindowMs || DEFAULT_REPLAY_WINDOW_MS;
179
+ // The spec calls for a sweep cadence of replayWindowMs/2 — short
180
+ // enough that expired nonces don't pile up but not so frequent the
181
+ // sweep query becomes a hot path. Operators can override.
182
+ var pruneIntervalMs = opts.pruneIntervalMs != null
183
+ ? opts.pruneIntervalMs : Math.max(C.TIME.seconds(30), Math.floor(replayWindowMs / 2));
184
+ var nonceStore = opts.nonceStore || nonceStoreLib.create({ backend: "memory" });
185
+ var exemptPaths = Array.isArray(opts.exemptPaths) ? opts.exemptPaths.slice() : [];
186
+ // contentTypes scoping — middleware only operates on requests whose
187
+ // Content-Type is in this list. Default JSON; operators with more
188
+ // exotic clients (form-encoded, gRPC-web, etc.) widen the list.
189
+ // Set to null/false/empty array to disable content-type filtering
190
+ // (treat every non-exempt request as encrypted).
191
+ var contentTypes = opts.contentTypes === null || opts.contentTypes === false
192
+ ? null
193
+ : (Array.isArray(opts.contentTypes) && opts.contentTypes.length > 0
194
+ ? opts.contentTypes.slice()
195
+ : DEFAULT_CONTENT_TYPES.slice());
196
+ var auditOn = opts.audit !== false;
197
+ var lastPruneAt = 0;
198
+
199
+ function _isExempt(req) {
200
+ var p = req.pathname || (req.url || "/").split("?")[0];
201
+ for (var i = 0; i < exemptPaths.length; i++) {
202
+ var rule = exemptPaths[i];
203
+ if (typeof rule === "string" ? p === rule || p.indexOf(rule + "/") === 0 : rule.test(p)) {
204
+ return true;
205
+ }
206
+ }
207
+ return false;
208
+ }
209
+
210
+ function _matchesContentType(req) {
211
+ if (!contentTypes) return true; // filtering disabled
212
+ var ct = req.headers && (req.headers["content-type"] || req.headers["Content-Type"]);
213
+ if (typeof ct !== "string") return false;
214
+ // Strip parameters like "; charset=utf-8"
215
+ var bare = ct.split(";")[0].trim().toLowerCase();
216
+ for (var i = 0; i < contentTypes.length; i++) {
217
+ if (contentTypes[i].toLowerCase() === bare) return true;
218
+ }
219
+ return false;
220
+ }
221
+
222
+ function _emitFailure(req, reason) {
223
+ var info = {
224
+ reason: reason,
225
+ ip: (req.socket && req.socket.remoteAddress) || null,
226
+ path: req.pathname || (req.url || "/").split("?")[0],
227
+ method: req.method,
228
+ ts: new Date().toISOString(),
229
+ requestId: req.requestId || null,
230
+ };
231
+ if (auditOn) {
232
+ audit().safeEmit({
233
+ actor: { ip: info.ip },
234
+ action: "system.api_encrypt.failure",
235
+ outcome: "denied",
236
+ reason: reason,
237
+ metadata: { reason: reason, path: info.path, method: info.method },
238
+ requestId: info.requestId,
239
+ });
240
+ }
241
+ try { events().emit(events().EVENTS.API_ENCRYPT_FAILURE, info); }
242
+ catch (_e) { /* events best-effort */ }
243
+ }
244
+
245
+ function _maybePrune() {
246
+ var now = Date.now();
247
+ if (now - lastPruneAt < pruneIntervalMs) return;
248
+ lastPruneAt = now;
249
+ nonceStore.purgeExpired().catch(function (e) {
250
+ try {
251
+ logger().warn("nonce-store prune failed: " + ((e && e.message) || String(e)));
252
+ } catch (_e) { /* logger best-effort */ }
253
+ });
254
+ }
255
+
256
+ function _wrapResJson(res, sessionKey) {
257
+ var origJson = res.json;
258
+ res.json = function (data) {
259
+ try {
260
+ var ptBuf = Buffer.from(JSON.stringify(data), "utf8");
261
+ var ctBuf = crypto.encryptPacked(ptBuf, sessionKey);
262
+ var encrypted = { _ct: ctBuf.toString("base64") };
263
+ if (typeof origJson === "function") {
264
+ return origJson.call(res, encrypted);
265
+ }
266
+ // Fallback if router didn't install res.json yet.
267
+ if (!res.headersSent) {
268
+ res.writeHead(res.statusCode || 200, { "Content-Type": "application/json" });
269
+ }
270
+ res.end(JSON.stringify(encrypted));
271
+ } catch (e) {
272
+ try {
273
+ logger().error("response encryption failed: " + ((e && e.message) || String(e)));
274
+ } catch (_e) {}
275
+ if (!res.headersSent) {
276
+ res.writeHead(500, { "Content-Type": "application/json" });
277
+ }
278
+ res.end(JSON.stringify({ error: "response-encryption-failed" }));
279
+ }
280
+ };
281
+ }
282
+
283
+ async function middleware(req, res, next) {
284
+ if (_isExempt(req)) return next();
285
+ if (!_matchesContentType(req)) return next();
286
+
287
+ var body = req.body;
288
+ if (!body || typeof body !== "object") {
289
+ _emitFailure(req, "shape");
290
+ return _writeRejection(res, 400, { error: "encrypted-payload-required" });
291
+ }
292
+ var ek = body._ek, ct = body._ct, ts = body._ts, nonce = body._nonce;
293
+ if (typeof ek !== "string" || typeof ct !== "string" ||
294
+ typeof ts !== "number" || typeof nonce !== "string") {
295
+ _emitFailure(req, "shape");
296
+ return _writeRejection(res, 400, { error: "encrypted-payload-required" });
297
+ }
298
+
299
+ // Replay window — must be within ±replayWindowMs of server clock.
300
+ var now = Date.now();
301
+ if (Math.abs(now - ts) > replayWindowMs) {
302
+ _emitFailure(req, "stale");
303
+ return _writeRejection(res, 400, { error: "encrypted-payload-rejected" });
304
+ }
305
+
306
+ // Nonce check + insert atomically. Loser of the insert race
307
+ // (= already-seen nonce within the replay window) is a replay.
308
+ // Hash the nonce before storage so a leaked DB / table dump
309
+ // doesn't reveal the original 16-byte client nonces (the spec's
310
+ // "sealed nonce hash"). SHA3 is deterministic so PRIMARY KEY
311
+ // conflict detection still works.
312
+ var nonceHash = crypto.sha3Hash(nonce, "hex");
313
+ var expireAt = now + replayWindowMs;
314
+ var freshNonce;
315
+ try { freshNonce = await nonceStore.checkAndInsert(nonceHash, expireAt); }
316
+ catch (_e) {
317
+ _emitFailure(req, "nonce-store-error");
318
+ return _writeRejection(res, 500, { error: "nonce-store-unavailable" });
319
+ }
320
+ if (!freshNonce) {
321
+ _emitFailure(req, "replay");
322
+ return _writeRejection(res, 400, { error: "encrypted-payload-rejected" });
323
+ }
324
+
325
+ // Decrypt _ek → session key. During a rotation overlap window,
326
+ // some clients still hold the previous server pubkey — try each
327
+ // keypair in order. The active keypair is keypairs[0]; older
328
+ // rotated-out keypairs follow. AEAD failure on every keypair =
329
+ // genuine bad ciphertext.
330
+ var sessionKey = null;
331
+ for (var ki = 0; ki < keypairs.length; ki++) {
332
+ try {
333
+ var sessionKeyB64 = crypto.decrypt(ek, keypairs[ki]);
334
+ var candidate = Buffer.from(sessionKeyB64, "base64");
335
+ if (candidate.length === SESSION_KEY_BYTES) {
336
+ sessionKey = candidate;
337
+ break;
338
+ }
339
+ } catch (_e) { /* try next keypair */ }
340
+ }
341
+ if (!sessionKey) {
342
+ _emitFailure(req, "tag");
343
+ return _writeRejection(res, 400, { error: "encrypted-payload-rejected" });
344
+ }
345
+
346
+ // Decrypt _ct → cleartext payload bytes → JSON object.
347
+ var clearObj;
348
+ try {
349
+ var ctBuf = Buffer.from(ct, "base64");
350
+ var ptBuf = crypto.decryptPacked(ctBuf, sessionKey);
351
+ clearObj = JSON.parse(ptBuf.toString("utf8"));
352
+ } catch (_e) {
353
+ _emitFailure(req, "tag");
354
+ return _writeRejection(res, 400, { error: "encrypted-payload-rejected" });
355
+ }
356
+
357
+ // Replace req.body with cleartext, stash session key for any
358
+ // operator code that wants to attach extra encrypted side-channel
359
+ // data (e.g. send a follow-up encrypted SSE event).
360
+ req.body = clearObj;
361
+ req.apiEncryptSessionKey = sessionKey;
362
+
363
+ _wrapResJson(res, sessionKey);
364
+ _maybePrune();
365
+
366
+ return next();
367
+ }
368
+
369
+ // Route handler that publishes the server's public keys for client
370
+ // bootstrap. Returns the PEM strings + KEM ID + a stable cache hint
371
+ // so clients can pin / rotate based on the published keys.
372
+ function publishPublicKey() {
373
+ return function publishHandler(_req, res) {
374
+ var body = {
375
+ publicKey: activeKeypair.publicKey,
376
+ ecPublicKey: activeKeypair.ecPublicKey,
377
+ kemId: C.ACTIVE.KEM,
378
+ cipherId: C.ACTIVE.CIPHER,
379
+ kdfId: C.ACTIVE.KDF,
380
+ };
381
+ if (typeof res.json === "function") return res.json(body);
382
+ if (!res.headersSent) {
383
+ res.writeHead(200, { "Content-Type": "application/json" });
384
+ }
385
+ res.end(JSON.stringify(body));
386
+ };
387
+ }
388
+
389
+ middleware.publishPublicKey = publishPublicKey;
390
+ middleware.close = function () {
391
+ if (typeof nonceStore.close === "function") nonceStore.close();
392
+ };
393
+
394
+ return middleware;
395
+ }
396
+
397
+ // ---- Client-side helper ----
398
+ //
399
+ // Operators import this in their browser/mobile/native code or in
400
+ // service-to-service callers. The pubkey shape MUST match what
401
+ // publishPublicKey() returns: { publicKey, ecPublicKey, kemId,
402
+ // cipherId, kdfId }.
403
+
404
+ function client(opts) {
405
+ opts = opts || {};
406
+ validateOpts(opts, ["pubkey"], "middleware.apiEncrypt.client");
407
+ if (!opts.pubkey || typeof opts.pubkey !== "object") {
408
+ throw _err("CLIENT_INVALID_PUBKEY",
409
+ "apiEncrypt.client: opts.pubkey is required ({ publicKey, ecPublicKey })", 500);
410
+ }
411
+ if (typeof opts.pubkey.publicKey !== "string" ||
412
+ typeof opts.pubkey.ecPublicKey !== "string") {
413
+ throw _err("CLIENT_INVALID_PUBKEY",
414
+ "apiEncrypt.client: pubkey.publicKey + ecPublicKey must be PEM strings", 500);
415
+ }
416
+ var pubkey = opts.pubkey;
417
+
418
+ function encryptRequest(payload) {
419
+ if (payload === undefined) payload = null;
420
+ var sessionKey = crypto.generateBytes(SESSION_KEY_BYTES);
421
+ var ek = crypto.encrypt(sessionKey.toString("base64"), pubkey);
422
+ var ptBuf = Buffer.from(JSON.stringify(payload), "utf8");
423
+ var ctBuf = crypto.encryptPacked(ptBuf, sessionKey);
424
+ var requestNonce = crypto.generateBytes(REQUEST_NONCE_BYTES).toString("hex");
425
+ var ts = Date.now();
426
+ return {
427
+ body: {
428
+ _ek: ek,
429
+ _ct: ctBuf.toString("base64"),
430
+ _ts: ts,
431
+ _nonce: requestNonce,
432
+ },
433
+ // Captured-closure decrypt — safe to pass back to the caller.
434
+ // sessionKey lives only in this closure; once the closure goes
435
+ // out of scope it can be garbage-collected.
436
+ decryptResponse: function (responseBody) {
437
+ if (!responseBody || typeof responseBody !== "object" ||
438
+ typeof responseBody._ct !== "string") {
439
+ throw _err("CLIENT_RESPONSE_SHAPE",
440
+ "apiEncrypt.client: response missing _ct field");
441
+ }
442
+ var resCtBuf = Buffer.from(responseBody._ct, "base64");
443
+ var resPtBuf = crypto.decryptPacked(resCtBuf, sessionKey);
444
+ return JSON.parse(resPtBuf.toString("utf8"));
445
+ },
446
+ };
447
+ }
448
+
449
+ return { encryptRequest: encryptRequest };
450
+ }
451
+
452
+ // ---- Server-to-server convenience ----
453
+ //
454
+ // Wraps the framework's HTTP client so service-to-service callers
455
+ // don't have to juggle encryptRequest + httpClient.request +
456
+ // JSON parsing + decryptResponse on every call. The pubkey is the
457
+ // callee's public bootstrap document (the JSON `publishPublicKey()`
458
+ // returns) so this helper works between any two blamejs instances.
459
+ //
460
+ // var enc = b.httpClient.encrypted({
461
+ // pubkey: callee.pubkey, // { publicKey, ecPublicKey }
462
+ // baseUrl: "https://callee.example",
463
+ // headers: { Authorization: "Bearer ..." },
464
+ // });
465
+ // var resp = await enc.request({
466
+ // method: "POST",
467
+ // path: "/api/widget",
468
+ // body: { user: "alice" },
469
+ // });
470
+ // resp.body // → decrypted plaintext object
471
+ //
472
+ // The helper handles only JSON-shaped request/response payloads,
473
+ // matching the middleware's contentTypes default.
474
+ function httpClientEncrypted(opts) {
475
+ opts = opts || {};
476
+ validateOpts(opts, [
477
+ "pubkey", "baseUrl", "headers", "method",
478
+ ], "middleware.apiEncrypt.httpClient");
479
+ if (!opts.pubkey) {
480
+ throw _err("CLIENT_INVALID_PUBKEY",
481
+ "httpClient.encrypted: opts.pubkey is required (the callee's bootstrap doc)", 500);
482
+ }
483
+ var clientCtx = client({ pubkey: opts.pubkey });
484
+ var baseUrl = opts.baseUrl ? String(opts.baseUrl).replace(/\/$/, "") : "";
485
+ var defaultHdrs = opts.headers || {};
486
+ var defaultMethod = opts.method || "POST";
487
+
488
+ function _resolveUrl(reqOpts) {
489
+ if (typeof reqOpts.url === "string" && reqOpts.url.length > 0) return reqOpts.url;
490
+ if (typeof reqOpts.path === "string" && reqOpts.path.length > 0) {
491
+ if (!baseUrl) {
492
+ throw _err("CLIENT_INVALID_URL",
493
+ "httpClient.encrypted.request: { path } requires opts.baseUrl at create time", 500);
494
+ }
495
+ return baseUrl + (reqOpts.path[0] === "/" ? reqOpts.path : "/" + reqOpts.path);
496
+ }
497
+ throw _err("CLIENT_INVALID_URL",
498
+ "httpClient.encrypted.request: requires { url } or { path } (with opts.baseUrl)", 500);
499
+ }
500
+
501
+ async function request(reqOpts) {
502
+ reqOpts = reqOpts || {};
503
+ var url = _resolveUrl(reqOpts);
504
+ var encrypted = clientCtx.encryptRequest(
505
+ reqOpts.body !== undefined ? reqOpts.body : null
506
+ );
507
+
508
+ // Merge headers — operator's per-request headers win over default
509
+ // headers, but Content-Type is forced because the encrypted body
510
+ // is always JSON.
511
+ var headers = Object.assign({}, defaultHdrs, reqOpts.headers || {});
512
+ headers["Content-Type"] = "application/json";
513
+
514
+ var passThrough = {};
515
+ var passable = ["allowedProtocols", "idleTimeoutMs", "maxResponseBytes",
516
+ "agent", "errorClass"];
517
+ for (var i = 0; i < passable.length; i++) {
518
+ if (reqOpts[passable[i]] !== undefined) passThrough[passable[i]] = reqOpts[passable[i]];
519
+ }
520
+
521
+ var rawBody = Buffer.from(JSON.stringify(encrypted.body), "utf8");
522
+ var resp = await httpClient().request(Object.assign({
523
+ url: url,
524
+ method: reqOpts.method || defaultMethod,
525
+ headers: headers,
526
+ body: rawBody,
527
+ }, passThrough));
528
+
529
+ // Empty body → no decryption (e.g. 204 No Content).
530
+ if (!resp.body || resp.body.length === 0) {
531
+ return { statusCode: resp.statusCode, headers: resp.headers, body: null };
532
+ }
533
+ var parsed;
534
+ try { parsed = JSON.parse(resp.body.toString("utf8")); }
535
+ catch (e) {
536
+ throw _err("CLIENT_RESPONSE_NOT_JSON",
537
+ "httpClient.encrypted: response body is not valid JSON: " + e.message);
538
+ }
539
+ return {
540
+ statusCode: resp.statusCode,
541
+ headers: resp.headers,
542
+ body: encrypted.decryptResponse(parsed),
543
+ };
544
+ }
545
+
546
+ return { request: request };
547
+ }
548
+
549
+ module.exports = Object.assign(create, {
550
+ client: client,
551
+ httpClient: httpClientEncrypted,
552
+ ApiEncryptError: ApiEncryptError,
553
+ });