@blamejs/core 0.7.18 → 0.7.20

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 (169) hide show
  1. package/CHANGELOG.md +427 -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 +350 -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 +399 -316
  84. package/lib/middleware/db-role-for.js +264 -264
  85. package/lib/middleware/fetch-metadata.js +129 -0
  86. package/lib/middleware/health.js +392 -392
  87. package/lib/middleware/index.js +85 -79
  88. package/lib/middleware/rate-limit.js +358 -358
  89. package/lib/middleware/request-id.js +61 -61
  90. package/lib/middleware/request-log.js +168 -168
  91. package/lib/middleware/require-auth.js +104 -104
  92. package/lib/middleware/security-headers.js +121 -116
  93. package/lib/middleware/sse.js +166 -166
  94. package/lib/migrations.js +383 -383
  95. package/lib/mtls-ca.js +518 -518
  96. package/lib/mtls-engine-default.js +481 -481
  97. package/lib/network-dns.js +632 -632
  98. package/lib/network-heartbeat.js +290 -290
  99. package/lib/network-nts.js +574 -574
  100. package/lib/network-proxy.js +265 -265
  101. package/lib/network-tls.js +328 -328
  102. package/lib/network.js +233 -233
  103. package/lib/notify.js +612 -612
  104. package/lib/ntp-check.js +229 -229
  105. package/lib/numeric-bounds.js +111 -111
  106. package/lib/object-store/azure-blob-bucket-ops.js +349 -349
  107. package/lib/object-store/azure-blob.js +488 -488
  108. package/lib/object-store/gcs-bucket-ops.js +351 -351
  109. package/lib/object-store/gcs.js +519 -519
  110. package/lib/object-store/http-put.js +153 -153
  111. package/lib/object-store/index.js +197 -197
  112. package/lib/object-store/sigv4-bucket-ops.js +1092 -1092
  113. package/lib/object-store/sigv4.js +903 -903
  114. package/lib/observability.js +151 -151
  115. package/lib/otel-export.js +269 -269
  116. package/lib/pagination.js +464 -464
  117. package/lib/parsers/index.js +80 -80
  118. package/lib/parsers/safe-env.js +642 -642
  119. package/lib/parsers/safe-ini.js +292 -292
  120. package/lib/parsers/safe-toml.js +784 -784
  121. package/lib/parsers/safe-xml.js +390 -390
  122. package/lib/parsers/safe-yaml.js +1015 -1015
  123. package/lib/permissions.js +708 -708
  124. package/lib/pqc-agent.js +87 -87
  125. package/lib/pqc-gate.js +279 -279
  126. package/lib/protobuf-encoder.js +190 -190
  127. package/lib/protocol-dispatcher.js +161 -161
  128. package/lib/pubsub-redis.js +167 -167
  129. package/lib/pubsub.js +429 -429
  130. package/lib/queue-local.js +476 -476
  131. package/lib/queue-redis.js +745 -745
  132. package/lib/queue-sqs.js +319 -319
  133. package/lib/queue.js +695 -695
  134. package/lib/redis-client.js +519 -519
  135. package/lib/request-helpers.js +340 -340
  136. package/lib/restore-bundle.js +237 -237
  137. package/lib/restore-rollback.js +259 -259
  138. package/lib/restore.js +409 -409
  139. package/lib/retry.js +376 -376
  140. package/lib/router.js +748 -748
  141. package/lib/safe-async.js +735 -735
  142. package/lib/safe-buffer.js +237 -237
  143. package/lib/safe-json.js +541 -541
  144. package/lib/safe-schema.js +1266 -1266
  145. package/lib/safe-url.js +159 -159
  146. package/lib/scheduler.js +706 -706
  147. package/lib/security-assert.js +373 -373
  148. package/lib/seeders.js +618 -618
  149. package/lib/session.js +535 -478
  150. package/lib/slug.js +269 -269
  151. package/lib/ssrf-guard.js +401 -401
  152. package/lib/static.js +7 -5
  153. package/lib/storage.js +471 -471
  154. package/lib/subject.js +281 -281
  155. package/lib/template.js +791 -791
  156. package/lib/testing.js +798 -798
  157. package/lib/time.js +310 -310
  158. package/lib/totp.js +302 -302
  159. package/lib/tracing.js +494 -494
  160. package/lib/uuid.js +132 -132
  161. package/lib/validate-opts.js +340 -340
  162. package/lib/vault/index.js +308 -308
  163. package/lib/vault/rotate.js +784 -784
  164. package/lib/vault/wrap.js +296 -296
  165. package/lib/vendor/noble-ciphers.cjs +9 -9
  166. package/lib/webhook.js +595 -595
  167. package/lib/websocket.js +1048 -1048
  168. package/package.json +77 -77
  169. package/sbom.cyclonedx.json +7 -7
@@ -1,508 +1,508 @@
1
- "use strict";
2
- /**
3
- * b.httpClient.cookieJar — outbound HTTP cookie store.
4
- *
5
- * Holds Set-Cookie state across requests so successive calls in a flow
6
- * (login → list → mutate → logout, OAuth code-exchange → userinfo, etc.)
7
- * carry the right Cookie header without operators threading it by hand.
8
- * RFC 6265 attribute coverage: Domain / Path / Expires / Max-Age /
9
- * HttpOnly / Secure / SameSite. Public Suffix List (PSL) awareness is
10
- * out of scope — operators wiring jars against trusted upstream
11
- * domains don't need it; for cross-eTLD safety in untrusted contexts,
12
- * use a per-domain jar and validate the host against an allowlist.
13
- *
14
- * var jar = b.httpClient.cookieJar.create(); // in-memory
15
- * await b.httpClient.request({ url: loginUrl, method: "POST", body, jar });
16
- * await b.httpClient.request({ url: meUrl, jar }); // session cookie attaches
17
- *
18
- * Three persistence modes:
19
- *
20
- * memory — in-process Map. Restart loses everything.
21
- * vault — every cookie value is sealed via b.vault.seal before it
22
- * lands in the in-process Map, so a memory dump or core
23
- * file doesn't expose plaintext values:
24
- *
25
- * b.httpClient.cookieJar.create({ persist: "vault", vault: b.vault })
26
- *
27
- * file — on-disk persistence at opts.file (absolute path). Loaded
28
- * at create() if the file exists; flushed (debounced via
29
- * opts.flushDebounceMs, default 100ms) on every set / clear
30
- * / setFromSerialized. Pass `vault` alongside `file` to
31
- * seal the on-disk bytes; without vault the file is
32
- * plaintext JSON (operator chose the threat model).
33
- *
34
- * b.httpClient.cookieJar.create({
35
- * persist: "file",
36
- * file: "/var/lib/myapp/jar.json",
37
- * vault: b.vault, // optional but recommended
38
- * })
39
- *
40
- * The file mode survives process restart. Cluster-shared persistence
41
- * (multiple nodes sharing one jar) is out of scope; operators with
42
- * that need wire a custom jar via the same shape as the returned
43
- * object (setFromResponse / cookieHeaderFor / getAll / etc.).
44
- *
45
- * Outbound filtering follows RFC 6265 §5.4:
46
- * - Domain: exact-host match by default; Domain attribute allows
47
- * subdomain match (host must be a suffix of cookie.domain).
48
- * - Path: request path must equal cookie.path or be path-below.
49
- * - Secure: cookie only attaches when the request URL is https:.
50
- * - Expiry: rows past Expires / Max-Age don't attach.
51
- * - Sort: longer path first, then earlier creation time.
52
- *
53
- * Cookie shape returned from getAll():
54
- *
55
- * {
56
- * name, value, domain, path, hostOnly,
57
- * expiresAt, // unix ms, or null for session cookies
58
- * httpOnly, secure, sameSite, // attributes
59
- * createdAt, updatedAt,
60
- * }
61
- */
62
-
63
- var fs = require("node:fs");
64
- var path = require("node:path");
65
- var C = require("./constants");
66
- var numericBounds = require("./numeric-bounds");
67
- var safeAsync = require("./safe-async");
68
- var safeJson = require("./safe-json");
69
- var safeUrl = require("./safe-url");
70
- var validateOpts = require("./validate-opts");
71
- var { defineClass } = require("./framework-error");
72
-
73
- var CookieJarError = defineClass("CookieJarError", { alwaysPermanent: true });
74
- var _err = CookieJarError.factory;
75
-
76
- var DEFAULTS = Object.freeze({
77
- persist: "memory",
78
- flushDebounceMs: 100,
79
- });
80
-
81
- var VALID_PERSIST = new Set(["memory", "vault", "file"]);
82
- var VALID_SAMESITE = new Set(["Strict", "Lax", "None"]);
83
-
84
- // ---- Set-Cookie parser ----
85
-
86
- function _parseHttpDate(s) {
87
- // node:Date handles RFC 1123 / 850 / asctime — sufficient for HTTP-date.
88
- var t = Date.parse(s);
89
- return isNaN(t) ? null : t;
90
- }
91
-
92
- function _parseSetCookie(line) {
93
- if (typeof line !== "string" || line.length === 0) return null;
94
- var semi = line.indexOf(";");
95
- var head = (semi === -1 ? line : line.slice(0, semi)).trim();
96
- var eq = head.indexOf("=");
97
- if (eq <= 0) return null;
98
- var name = head.slice(0, eq).trim();
99
- var value = head.slice(eq + 1).trim();
100
- if (!name) return null;
101
-
102
- var attrs = {};
103
- if (semi !== -1) {
104
- var rest = line.slice(semi + 1);
105
- var parts = rest.split(";");
106
- for (var i = 0; i < parts.length; i++) {
107
- var p = parts[i].trim();
108
- if (!p) continue;
109
- var pi = p.indexOf("=");
110
- var k, v;
111
- if (pi === -1) { k = p; v = ""; }
112
- else { k = p.slice(0, pi).trim(); v = p.slice(pi + 1).trim(); }
113
- attrs[k.toLowerCase()] = v;
114
- }
115
- }
116
- return { name: name, value: value, attrs: attrs };
117
- }
118
-
119
- // ---- Domain / Path matching ----
120
-
121
- function _domainMatch(host, cookieDomain) {
122
- if (host === cookieDomain) return true;
123
- if (host.length > cookieDomain.length &&
124
- host.endsWith(cookieDomain) &&
125
- host.charAt(host.length - cookieDomain.length - 1) === ".") {
126
- return true;
127
- }
128
- return false;
129
- }
130
-
131
- function _pathMatch(reqPath, cookiePath) {
132
- if (cookiePath === reqPath) return true;
133
- if (reqPath.indexOf(cookiePath) === 0) {
134
- if (cookiePath.charAt(cookiePath.length - 1) === "/") return true;
135
- if (reqPath.charAt(cookiePath.length) === "/") return true;
136
- }
137
- return false;
138
- }
139
-
140
- function _defaultPath(reqPath) {
141
- // RFC 6265 §5.1.4: take everything up to the last "/", or "/" if none.
142
- if (typeof reqPath !== "string" || reqPath.length === 0) return "/";
143
- var qm = reqPath.indexOf("?");
144
- var p = qm === -1 ? reqPath : reqPath.slice(0, qm);
145
- if (p.charAt(0) !== "/") return "/";
146
- var lastSlash = p.lastIndexOf("/");
147
- if (lastSlash <= 0) return "/";
148
- return p.slice(0, lastSlash);
149
- }
150
-
151
- // ---- Public create ----
152
-
153
- function create(opts) {
154
- opts = opts || {};
155
- var persist = opts.persist === undefined ? DEFAULTS.persist : opts.persist;
156
- if (!VALID_PERSIST.has(persist)) {
157
- throw _err("BAD_OPT", "cookieJar.create: persist must be 'memory' | 'vault' | 'file', got " +
158
- JSON.stringify(persist));
159
- }
160
- var vault = opts.vault || null;
161
- if (persist === "vault") {
162
- if (!vault || typeof vault.seal !== "function" || typeof vault.unseal !== "function") {
163
- throw _err("BAD_OPT",
164
- "cookieJar.create: persist: 'vault' requires opts.vault with seal/unseal (pass b.vault)");
165
- }
166
- }
167
- var filePath = null;
168
- if (persist === "file") {
169
- validateOpts.requireNonEmptyString(opts.file, "cookieJar.create: persist: 'file' opts.file (absolute path)", CookieJarError, "BAD_OPT");
170
- filePath = opts.file;
171
- // Refuse relative paths so a process running in a different cwd
172
- // doesn't accidentally serialize to a sibling directory.
173
- if (!path.isAbsolute(filePath)) {
174
- throw _err("BAD_OPT",
175
- "cookieJar.create: opts.file must be an absolute path, got " + JSON.stringify(filePath));
176
- }
177
- }
178
- if (opts.flushDebounceMs !== undefined && !numericBounds.isNonNegativeFiniteInt(opts.flushDebounceMs)) {
179
- throw _err("BAD_OPT", "cookieJar.create: flushDebounceMs must be a non-negative finite integer; got " +
180
- numericBounds.shape(opts.flushDebounceMs));
181
- }
182
- var flushDebounceMs = opts.flushDebounceMs !== undefined ? opts.flushDebounceMs : DEFAULTS.flushDebounceMs;
183
- var clock = typeof opts.clock === "function" ? opts.clock : Date.now;
184
-
185
- // Storage map keyed by `<domain>|<path>|<name>` so a (domain, path)
186
- // tuple can hold multiple cookies, but a same-tuple-same-name update
187
- // replaces the prior row per RFC 6265 §5.3.
188
- var store = new Map();
189
-
190
- function _seal(plain) {
191
- if (persist !== "vault" || plain === undefined || plain === null) return String(plain == null ? "" : plain);
192
- return vault.seal(String(plain));
193
- }
194
- function _unseal(blob) {
195
- if (persist !== "vault" || blob === undefined || blob === null) return blob == null ? "" : String(blob);
196
- return String(vault.unseal(blob));
197
- }
198
-
199
- function _setOne(reqUrl, parsed) {
200
- var u;
201
- try { u = safeUrl.parse(reqUrl, { allowedProtocols: safeUrl.ALLOW_HTTP_ALL }); }
202
- catch (_e) { return; }
203
- var host = u.hostname.toLowerCase();
204
- var attrs = parsed.attrs || {};
205
-
206
- // Domain attribute: lower-case, leading-dot stripped (RFC 6265bis).
207
- var domainAttr = attrs.domain;
208
- var domain;
209
- var hostOnly;
210
- if (domainAttr) {
211
- var d = String(domainAttr).toLowerCase();
212
- if (d.charAt(0) === ".") d = d.slice(1);
213
- // Don't accept a Domain that the request host doesn't match.
214
- if (!_domainMatch(host, d)) return;
215
- domain = d;
216
- hostOnly = false;
217
- } else {
218
- domain = host;
219
- hostOnly = true;
220
- }
221
-
222
- var path = (typeof attrs.path === "string" && attrs.path.charAt(0) === "/")
223
- ? attrs.path : _defaultPath(u.pathname);
224
-
225
- // Expires / Max-Age. Max-Age wins when both present (RFC 6265 §5.2.2).
226
- var now = clock();
227
- var expiresAt = null;
228
- if (attrs["max-age"] !== undefined) {
229
- var maxAge = parseInt(attrs["max-age"], 10);
230
- if (!isNaN(maxAge)) {
231
- expiresAt = maxAge <= 0 ? 0 : (now + C.TIME.seconds(maxAge));
232
- }
233
- } else if (attrs.expires) {
234
- expiresAt = _parseHttpDate(attrs.expires);
235
- }
236
-
237
- // Max-Age=0 / past Expires → delete an existing matching row.
238
- var key = domain + "|" + path + "|" + parsed.name;
239
- if (expiresAt !== null && expiresAt <= now) {
240
- store.delete(key);
241
- return;
242
- }
243
-
244
- var sameSiteRaw = attrs.samesite;
245
- var sameSite = null;
246
- if (typeof sameSiteRaw === "string") {
247
- var ssLc = sameSiteRaw.toLowerCase();
248
- if (ssLc === "strict") sameSite = "Strict";
249
- else if (ssLc === "lax") sameSite = "Lax";
250
- else if (ssLc === "none") sameSite = "None";
251
- }
252
-
253
- var prior = store.get(key);
254
- store.set(key, {
255
- name: parsed.name,
256
- value: _seal(parsed.value),
257
- domain: domain,
258
- path: path,
259
- hostOnly: hostOnly,
260
- expiresAt: expiresAt,
261
- httpOnly: Object.prototype.hasOwnProperty.call(attrs, "httponly"),
262
- secure: Object.prototype.hasOwnProperty.call(attrs, "secure"),
263
- sameSite: sameSite,
264
- createdAt: prior ? prior.createdAt : now,
265
- updatedAt: now,
266
- });
267
- }
268
-
269
- // ---- Public API ----
270
-
271
- function setFromResponse(reqUrl, setCookieHeader) {
272
- if (!setCookieHeader) return;
273
- var lines = Array.isArray(setCookieHeader) ? setCookieHeader : [setCookieHeader];
274
- for (var i = 0; i < lines.length; i++) {
275
- var parsed = _parseSetCookie(lines[i]);
276
- if (parsed) _setOne(reqUrl, parsed);
277
- }
278
- }
279
-
280
- function cookieHeaderFor(reqUrl) {
281
- var u;
282
- try { u = safeUrl.parse(reqUrl, { allowedProtocols: safeUrl.ALLOW_HTTP_ALL }); }
283
- catch (_e) { return null; }
284
- var host = u.hostname.toLowerCase();
285
- var path = u.pathname || "/";
286
- var isSecure = u.protocol === "https:";
287
- var now = clock();
288
-
289
- var matches = [];
290
- for (var entry of store.values()) {
291
- // Expiry
292
- if (entry.expiresAt !== null && entry.expiresAt <= now) continue;
293
- // Domain
294
- if (entry.hostOnly) {
295
- if (entry.domain !== host) continue;
296
- } else {
297
- if (!_domainMatch(host, entry.domain)) continue;
298
- }
299
- // Path
300
- if (!_pathMatch(path, entry.path)) continue;
301
- // Secure
302
- if (entry.secure && !isSecure) continue;
303
- matches.push(entry);
304
- }
305
- if (matches.length === 0) return null;
306
-
307
- // Sort: longer path first, then earlier creation time.
308
- matches.sort(function (a, b) {
309
- if (a.path.length !== b.path.length) return b.path.length - a.path.length;
310
- return a.createdAt - b.createdAt;
311
- });
312
- var pieces = matches.map(function (e) {
313
- return e.name + "=" + _unseal(e.value);
314
- });
315
- return pieces.join("; ");
316
- }
317
-
318
- function getAll() {
319
- var now = clock();
320
- var out = [];
321
- for (var entry of store.values()) {
322
- if (entry.expiresAt !== null && entry.expiresAt <= now) continue;
323
- out.push({
324
- name: entry.name,
325
- value: _unseal(entry.value),
326
- domain: entry.domain,
327
- path: entry.path,
328
- hostOnly: entry.hostOnly,
329
- expiresAt: entry.expiresAt,
330
- httpOnly: entry.httpOnly,
331
- secure: entry.secure,
332
- sameSite: entry.sameSite,
333
- createdAt: entry.createdAt,
334
- updatedAt: entry.updatedAt,
335
- });
336
- }
337
- return out;
338
- }
339
-
340
- function clear(filter) {
341
- if (!filter) {
342
- var n = store.size;
343
- store.clear();
344
- return n;
345
- }
346
- if (typeof filter !== "object") {
347
- throw _err("BAD_OPT", "cookieJar.clear: filter must be an object or undefined");
348
- }
349
- var purged = 0;
350
- var keysToDelete = [];
351
- for (var pair of store.entries()) {
352
- var key = pair[0];
353
- var entry = pair[1];
354
- if (filter.domain && entry.domain !== filter.domain) continue;
355
- if (filter.name && entry.name !== filter.name) continue;
356
- if (filter.path && entry.path !== filter.path) continue;
357
- keysToDelete.push(key);
358
- }
359
- for (var i = 0; i < keysToDelete.length; i++) {
360
- store.delete(keysToDelete[i]);
361
- purged++;
362
- }
363
- return purged;
364
- }
365
-
366
- function size() {
367
- var now = clock();
368
- var n = 0;
369
- for (var entry of store.values()) {
370
- if (entry.expiresAt !== null && entry.expiresAt <= now) continue;
371
- n++;
372
- }
373
- return n;
374
- }
375
-
376
- // Round-trip helpers — operators with restart-survival needs serialize
377
- // via getAll(), persist however they like, restore via setFromSerialized.
378
- function setFromSerialized(rows) {
379
- if (!Array.isArray(rows)) {
380
- throw _err("BAD_OPT", "cookieJar.setFromSerialized: rows must be an array");
381
- }
382
- var now = clock();
383
- for (var i = 0; i < rows.length; i++) {
384
- var r = rows[i];
385
- if (!r || typeof r.name !== "string" || typeof r.domain !== "string" || typeof r.path !== "string") continue;
386
- var key = r.domain + "|" + r.path + "|" + r.name;
387
- if (r.expiresAt !== null && r.expiresAt !== undefined && r.expiresAt <= now) continue;
388
- store.set(key, {
389
- name: r.name,
390
- value: _seal(r.value),
391
- domain: r.domain,
392
- path: r.path,
393
- hostOnly: !!r.hostOnly,
394
- expiresAt: typeof r.expiresAt === "number" ? r.expiresAt : null,
395
- httpOnly: !!r.httpOnly,
396
- secure: !!r.secure,
397
- sameSite: VALID_SAMESITE.has(r.sameSite) ? r.sameSite : null,
398
- createdAt: typeof r.createdAt === "number" ? r.createdAt : now,
399
- updatedAt: typeof r.updatedAt === "number" ? r.updatedAt : now,
400
- });
401
- }
402
- }
403
-
404
- // Raw-store accessor for tests — returns the literal Map entries with
405
- // the value field as it sits in memory (sealed when persist === "vault").
406
- // Operators don't call this; if they need stored state, getAll() returns
407
- // the unsealed form. Exposed so the no-plaintext assertion is verifiable.
408
- function _storeForTest() {
409
- var rows = [];
410
- for (var entry of store.values()) {
411
- rows.push({
412
- name: entry.name,
413
- valueRaw: entry.value,
414
- domain: entry.domain,
415
- path: entry.path,
416
- expiresAt: entry.expiresAt,
417
- });
418
- }
419
- return rows;
420
- }
421
-
422
- // ---- File persistence ----
423
- // When persist === "file", load on construct + flush on every write
424
- // (debounced). On-disk format is JSON of getAll() output. If a vault
425
- // is also passed, the file is sealed via vault.seal so the on-disk
426
- // bytes are encrypted at rest; otherwise plaintext (operator chose
427
- // the threat model by passing or omitting vault).
428
- function _flushSync() {
429
- if (!filePath) return;
430
- var rows = getAll();
431
- var serialized = JSON.stringify(rows);
432
- var blob = vault ? vault.seal(serialized) : serialized;
433
- fs.writeFileSync(filePath, blob);
434
- }
435
- var flushScheduler = safeAsync.makeScheduledFlush(flushDebounceMs, function () {
436
- if (!filePath) return;
437
- try { _flushSync(); } catch (_e) { /* operator can call flush() to retry */ }
438
- });
439
- function _scheduleFlush() {
440
- if (!filePath) return;
441
- flushScheduler.schedule();
442
- }
443
- function flush() {
444
- flushScheduler.cancel();
445
- _flushSync();
446
- }
447
- function close() {
448
- flushScheduler.cancel();
449
- if (filePath) try { _flushSync(); } catch (_e) { /* best-effort */ }
450
- }
451
-
452
- // Wrap mutating entrypoints so each write schedules a flush. The
453
- // wrappers go on the returned object — the underlying function
454
- // declarations stay intact so other internal callers reach them.
455
- var setFromResponseAndFlush = function (reqUrl, hdr) {
456
- setFromResponse(reqUrl, hdr); _scheduleFlush();
457
- };
458
- var clearAndFlush = function (filter) {
459
- var n = clear(filter); _scheduleFlush(); return n;
460
- };
461
- var setFromSerializedAndFlush = function (rows) {
462
- setFromSerialized(rows); _scheduleFlush();
463
- };
464
-
465
- // Initial load from file. Missing file is fine (first run).
466
- // Persist file may be operator-tampered (or vault-sealed) — route through
467
- // safeJson with an explicit byte cap so a maliciously-large file can't
468
- // OOM the process before the parse fails.
469
- if (filePath && fs.existsSync(filePath)) {
470
- try {
471
- var raw = fs.readFileSync(filePath, "utf8");
472
- var serialized = vault ? vault.unseal(raw) : raw;
473
- if (serialized && serialized.length > 0) {
474
- var rows = safeJson.parse(serialized, { maxBytes: C.BYTES.mib(16) });
475
- setFromSerialized(rows);
476
- }
477
- } catch (e) {
478
- throw _err("LOAD_FAILED",
479
- "cookieJar.create: failed to load persist file '" + filePath + "': " +
480
- (e.message || String(e)));
481
- }
482
- }
483
-
484
- return {
485
- setFromResponse: filePath ? setFromResponseAndFlush : setFromResponse,
486
- cookieHeaderFor: cookieHeaderFor,
487
- getAll: getAll,
488
- clear: filePath ? clearAndFlush : clear,
489
- size: size,
490
- setFromSerialized: filePath ? setFromSerializedAndFlush : setFromSerialized,
491
- flush: flush,
492
- close: close,
493
- persist: persist,
494
- file: filePath,
495
- _storeForTest: _storeForTest,
496
- };
497
- }
498
-
499
- module.exports = {
500
- create: create,
501
- CookieJarError: CookieJarError,
502
- DEFAULTS: DEFAULTS,
503
- // Exposed for tests + advanced operator wiring.
504
- _parseSetCookie: _parseSetCookie,
505
- };
506
- // safeUrl reserved for future scheme validation hooks (e.g. operator-supplied
507
- // allowedProtocols filter on cookie attachment paths).
508
- void safeUrl;
1
+ "use strict";
2
+ /**
3
+ * b.httpClient.cookieJar — outbound HTTP cookie store.
4
+ *
5
+ * Holds Set-Cookie state across requests so successive calls in a flow
6
+ * (login → list → mutate → logout, OAuth code-exchange → userinfo, etc.)
7
+ * carry the right Cookie header without operators threading it by hand.
8
+ * RFC 6265 attribute coverage: Domain / Path / Expires / Max-Age /
9
+ * HttpOnly / Secure / SameSite. Public Suffix List (PSL) awareness is
10
+ * out of scope — operators wiring jars against trusted upstream
11
+ * domains don't need it; for cross-eTLD safety in untrusted contexts,
12
+ * use a per-domain jar and validate the host against an allowlist.
13
+ *
14
+ * var jar = b.httpClient.cookieJar.create(); // in-memory
15
+ * await b.httpClient.request({ url: loginUrl, method: "POST", body, jar });
16
+ * await b.httpClient.request({ url: meUrl, jar }); // session cookie attaches
17
+ *
18
+ * Three persistence modes:
19
+ *
20
+ * memory — in-process Map. Restart loses everything.
21
+ * vault — every cookie value is sealed via b.vault.seal before it
22
+ * lands in the in-process Map, so a memory dump or core
23
+ * file doesn't expose plaintext values:
24
+ *
25
+ * b.httpClient.cookieJar.create({ persist: "vault", vault: b.vault })
26
+ *
27
+ * file — on-disk persistence at opts.file (absolute path). Loaded
28
+ * at create() if the file exists; flushed (debounced via
29
+ * opts.flushDebounceMs, default 100ms) on every set / clear
30
+ * / setFromSerialized. Pass `vault` alongside `file` to
31
+ * seal the on-disk bytes; without vault the file is
32
+ * plaintext JSON (operator chose the threat model).
33
+ *
34
+ * b.httpClient.cookieJar.create({
35
+ * persist: "file",
36
+ * file: "/var/lib/myapp/jar.json",
37
+ * vault: b.vault, // optional but recommended
38
+ * })
39
+ *
40
+ * The file mode survives process restart. Cluster-shared persistence
41
+ * (multiple nodes sharing one jar) is out of scope; operators with
42
+ * that need wire a custom jar via the same shape as the returned
43
+ * object (setFromResponse / cookieHeaderFor / getAll / etc.).
44
+ *
45
+ * Outbound filtering follows RFC 6265 §5.4:
46
+ * - Domain: exact-host match by default; Domain attribute allows
47
+ * subdomain match (host must be a suffix of cookie.domain).
48
+ * - Path: request path must equal cookie.path or be path-below.
49
+ * - Secure: cookie only attaches when the request URL is https:.
50
+ * - Expiry: rows past Expires / Max-Age don't attach.
51
+ * - Sort: longer path first, then earlier creation time.
52
+ *
53
+ * Cookie shape returned from getAll():
54
+ *
55
+ * {
56
+ * name, value, domain, path, hostOnly,
57
+ * expiresAt, // unix ms, or null for session cookies
58
+ * httpOnly, secure, sameSite, // attributes
59
+ * createdAt, updatedAt,
60
+ * }
61
+ */
62
+
63
+ var fs = require("node:fs");
64
+ var path = require("node:path");
65
+ var C = require("./constants");
66
+ var numericBounds = require("./numeric-bounds");
67
+ var safeAsync = require("./safe-async");
68
+ var safeJson = require("./safe-json");
69
+ var safeUrl = require("./safe-url");
70
+ var validateOpts = require("./validate-opts");
71
+ var { defineClass } = require("./framework-error");
72
+
73
+ var CookieJarError = defineClass("CookieJarError", { alwaysPermanent: true });
74
+ var _err = CookieJarError.factory;
75
+
76
+ var DEFAULTS = Object.freeze({
77
+ persist: "memory",
78
+ flushDebounceMs: 100,
79
+ });
80
+
81
+ var VALID_PERSIST = new Set(["memory", "vault", "file"]);
82
+ var VALID_SAMESITE = new Set(["Strict", "Lax", "None"]);
83
+
84
+ // ---- Set-Cookie parser ----
85
+
86
+ function _parseHttpDate(s) {
87
+ // node:Date handles RFC 1123 / 850 / asctime — sufficient for HTTP-date.
88
+ var t = Date.parse(s);
89
+ return isNaN(t) ? null : t;
90
+ }
91
+
92
+ function _parseSetCookie(line) {
93
+ if (typeof line !== "string" || line.length === 0) return null;
94
+ var semi = line.indexOf(";");
95
+ var head = (semi === -1 ? line : line.slice(0, semi)).trim();
96
+ var eq = head.indexOf("=");
97
+ if (eq <= 0) return null;
98
+ var name = head.slice(0, eq).trim();
99
+ var value = head.slice(eq + 1).trim();
100
+ if (!name) return null;
101
+
102
+ var attrs = {};
103
+ if (semi !== -1) {
104
+ var rest = line.slice(semi + 1);
105
+ var parts = rest.split(";");
106
+ for (var i = 0; i < parts.length; i++) {
107
+ var p = parts[i].trim();
108
+ if (!p) continue;
109
+ var pi = p.indexOf("=");
110
+ var k, v;
111
+ if (pi === -1) { k = p; v = ""; }
112
+ else { k = p.slice(0, pi).trim(); v = p.slice(pi + 1).trim(); }
113
+ attrs[k.toLowerCase()] = v;
114
+ }
115
+ }
116
+ return { name: name, value: value, attrs: attrs };
117
+ }
118
+
119
+ // ---- Domain / Path matching ----
120
+
121
+ function _domainMatch(host, cookieDomain) {
122
+ if (host === cookieDomain) return true;
123
+ if (host.length > cookieDomain.length &&
124
+ host.endsWith(cookieDomain) &&
125
+ host.charAt(host.length - cookieDomain.length - 1) === ".") {
126
+ return true;
127
+ }
128
+ return false;
129
+ }
130
+
131
+ function _pathMatch(reqPath, cookiePath) {
132
+ if (cookiePath === reqPath) return true;
133
+ if (reqPath.indexOf(cookiePath) === 0) {
134
+ if (cookiePath.charAt(cookiePath.length - 1) === "/") return true;
135
+ if (reqPath.charAt(cookiePath.length) === "/") return true;
136
+ }
137
+ return false;
138
+ }
139
+
140
+ function _defaultPath(reqPath) {
141
+ // RFC 6265 §5.1.4: take everything up to the last "/", or "/" if none.
142
+ if (typeof reqPath !== "string" || reqPath.length === 0) return "/";
143
+ var qm = reqPath.indexOf("?");
144
+ var p = qm === -1 ? reqPath : reqPath.slice(0, qm);
145
+ if (p.charAt(0) !== "/") return "/";
146
+ var lastSlash = p.lastIndexOf("/");
147
+ if (lastSlash <= 0) return "/";
148
+ return p.slice(0, lastSlash);
149
+ }
150
+
151
+ // ---- Public create ----
152
+
153
+ function create(opts) {
154
+ opts = opts || {};
155
+ var persist = opts.persist === undefined ? DEFAULTS.persist : opts.persist;
156
+ if (!VALID_PERSIST.has(persist)) {
157
+ throw _err("BAD_OPT", "cookieJar.create: persist must be 'memory' | 'vault' | 'file', got " +
158
+ JSON.stringify(persist));
159
+ }
160
+ var vault = opts.vault || null;
161
+ if (persist === "vault") {
162
+ if (!vault || typeof vault.seal !== "function" || typeof vault.unseal !== "function") {
163
+ throw _err("BAD_OPT",
164
+ "cookieJar.create: persist: 'vault' requires opts.vault with seal/unseal (pass b.vault)");
165
+ }
166
+ }
167
+ var filePath = null;
168
+ if (persist === "file") {
169
+ validateOpts.requireNonEmptyString(opts.file, "cookieJar.create: persist: 'file' opts.file (absolute path)", CookieJarError, "BAD_OPT");
170
+ filePath = opts.file;
171
+ // Refuse relative paths so a process running in a different cwd
172
+ // doesn't accidentally serialize to a sibling directory.
173
+ if (!path.isAbsolute(filePath)) {
174
+ throw _err("BAD_OPT",
175
+ "cookieJar.create: opts.file must be an absolute path, got " + JSON.stringify(filePath));
176
+ }
177
+ }
178
+ if (opts.flushDebounceMs !== undefined && !numericBounds.isNonNegativeFiniteInt(opts.flushDebounceMs)) {
179
+ throw _err("BAD_OPT", "cookieJar.create: flushDebounceMs must be a non-negative finite integer; got " +
180
+ numericBounds.shape(opts.flushDebounceMs));
181
+ }
182
+ var flushDebounceMs = opts.flushDebounceMs !== undefined ? opts.flushDebounceMs : DEFAULTS.flushDebounceMs;
183
+ var clock = typeof opts.clock === "function" ? opts.clock : Date.now;
184
+
185
+ // Storage map keyed by `<domain>|<path>|<name>` so a (domain, path)
186
+ // tuple can hold multiple cookies, but a same-tuple-same-name update
187
+ // replaces the prior row per RFC 6265 §5.3.
188
+ var store = new Map();
189
+
190
+ function _seal(plain) {
191
+ if (persist !== "vault" || plain === undefined || plain === null) return String(plain == null ? "" : plain);
192
+ return vault.seal(String(plain));
193
+ }
194
+ function _unseal(blob) {
195
+ if (persist !== "vault" || blob === undefined || blob === null) return blob == null ? "" : String(blob);
196
+ return String(vault.unseal(blob));
197
+ }
198
+
199
+ function _setOne(reqUrl, parsed) {
200
+ var u;
201
+ try { u = safeUrl.parse(reqUrl, { allowedProtocols: safeUrl.ALLOW_HTTP_ALL }); }
202
+ catch (_e) { return; }
203
+ var host = u.hostname.toLowerCase();
204
+ var attrs = parsed.attrs || {};
205
+
206
+ // Domain attribute: lower-case, leading-dot stripped (RFC 6265bis).
207
+ var domainAttr = attrs.domain;
208
+ var domain;
209
+ var hostOnly;
210
+ if (domainAttr) {
211
+ var d = String(domainAttr).toLowerCase();
212
+ if (d.charAt(0) === ".") d = d.slice(1);
213
+ // Don't accept a Domain that the request host doesn't match.
214
+ if (!_domainMatch(host, d)) return;
215
+ domain = d;
216
+ hostOnly = false;
217
+ } else {
218
+ domain = host;
219
+ hostOnly = true;
220
+ }
221
+
222
+ var path = (typeof attrs.path === "string" && attrs.path.charAt(0) === "/")
223
+ ? attrs.path : _defaultPath(u.pathname);
224
+
225
+ // Expires / Max-Age. Max-Age wins when both present (RFC 6265 §5.2.2).
226
+ var now = clock();
227
+ var expiresAt = null;
228
+ if (attrs["max-age"] !== undefined) {
229
+ var maxAge = parseInt(attrs["max-age"], 10);
230
+ if (!isNaN(maxAge)) {
231
+ expiresAt = maxAge <= 0 ? 0 : (now + C.TIME.seconds(maxAge));
232
+ }
233
+ } else if (attrs.expires) {
234
+ expiresAt = _parseHttpDate(attrs.expires);
235
+ }
236
+
237
+ // Max-Age=0 / past Expires → delete an existing matching row.
238
+ var key = domain + "|" + path + "|" + parsed.name;
239
+ if (expiresAt !== null && expiresAt <= now) {
240
+ store.delete(key);
241
+ return;
242
+ }
243
+
244
+ var sameSiteRaw = attrs.samesite;
245
+ var sameSite = null;
246
+ if (typeof sameSiteRaw === "string") {
247
+ var ssLc = sameSiteRaw.toLowerCase();
248
+ if (ssLc === "strict") sameSite = "Strict";
249
+ else if (ssLc === "lax") sameSite = "Lax";
250
+ else if (ssLc === "none") sameSite = "None";
251
+ }
252
+
253
+ var prior = store.get(key);
254
+ store.set(key, {
255
+ name: parsed.name,
256
+ value: _seal(parsed.value),
257
+ domain: domain,
258
+ path: path,
259
+ hostOnly: hostOnly,
260
+ expiresAt: expiresAt,
261
+ httpOnly: Object.prototype.hasOwnProperty.call(attrs, "httponly"),
262
+ secure: Object.prototype.hasOwnProperty.call(attrs, "secure"),
263
+ sameSite: sameSite,
264
+ createdAt: prior ? prior.createdAt : now,
265
+ updatedAt: now,
266
+ });
267
+ }
268
+
269
+ // ---- Public API ----
270
+
271
+ function setFromResponse(reqUrl, setCookieHeader) {
272
+ if (!setCookieHeader) return;
273
+ var lines = Array.isArray(setCookieHeader) ? setCookieHeader : [setCookieHeader];
274
+ for (var i = 0; i < lines.length; i++) {
275
+ var parsed = _parseSetCookie(lines[i]);
276
+ if (parsed) _setOne(reqUrl, parsed);
277
+ }
278
+ }
279
+
280
+ function cookieHeaderFor(reqUrl) {
281
+ var u;
282
+ try { u = safeUrl.parse(reqUrl, { allowedProtocols: safeUrl.ALLOW_HTTP_ALL }); }
283
+ catch (_e) { return null; }
284
+ var host = u.hostname.toLowerCase();
285
+ var path = u.pathname || "/";
286
+ var isSecure = u.protocol === "https:";
287
+ var now = clock();
288
+
289
+ var matches = [];
290
+ for (var entry of store.values()) {
291
+ // Expiry
292
+ if (entry.expiresAt !== null && entry.expiresAt <= now) continue;
293
+ // Domain
294
+ if (entry.hostOnly) {
295
+ if (entry.domain !== host) continue;
296
+ } else {
297
+ if (!_domainMatch(host, entry.domain)) continue;
298
+ }
299
+ // Path
300
+ if (!_pathMatch(path, entry.path)) continue;
301
+ // Secure
302
+ if (entry.secure && !isSecure) continue;
303
+ matches.push(entry);
304
+ }
305
+ if (matches.length === 0) return null;
306
+
307
+ // Sort: longer path first, then earlier creation time.
308
+ matches.sort(function (a, b) {
309
+ if (a.path.length !== b.path.length) return b.path.length - a.path.length;
310
+ return a.createdAt - b.createdAt;
311
+ });
312
+ var pieces = matches.map(function (e) {
313
+ return e.name + "=" + _unseal(e.value);
314
+ });
315
+ return pieces.join("; ");
316
+ }
317
+
318
+ function getAll() {
319
+ var now = clock();
320
+ var out = [];
321
+ for (var entry of store.values()) {
322
+ if (entry.expiresAt !== null && entry.expiresAt <= now) continue;
323
+ out.push({
324
+ name: entry.name,
325
+ value: _unseal(entry.value),
326
+ domain: entry.domain,
327
+ path: entry.path,
328
+ hostOnly: entry.hostOnly,
329
+ expiresAt: entry.expiresAt,
330
+ httpOnly: entry.httpOnly,
331
+ secure: entry.secure,
332
+ sameSite: entry.sameSite,
333
+ createdAt: entry.createdAt,
334
+ updatedAt: entry.updatedAt,
335
+ });
336
+ }
337
+ return out;
338
+ }
339
+
340
+ function clear(filter) {
341
+ if (!filter) {
342
+ var n = store.size;
343
+ store.clear();
344
+ return n;
345
+ }
346
+ if (typeof filter !== "object") {
347
+ throw _err("BAD_OPT", "cookieJar.clear: filter must be an object or undefined");
348
+ }
349
+ var purged = 0;
350
+ var keysToDelete = [];
351
+ for (var pair of store.entries()) {
352
+ var key = pair[0];
353
+ var entry = pair[1];
354
+ if (filter.domain && entry.domain !== filter.domain) continue;
355
+ if (filter.name && entry.name !== filter.name) continue;
356
+ if (filter.path && entry.path !== filter.path) continue;
357
+ keysToDelete.push(key);
358
+ }
359
+ for (var i = 0; i < keysToDelete.length; i++) {
360
+ store.delete(keysToDelete[i]);
361
+ purged++;
362
+ }
363
+ return purged;
364
+ }
365
+
366
+ function size() {
367
+ var now = clock();
368
+ var n = 0;
369
+ for (var entry of store.values()) {
370
+ if (entry.expiresAt !== null && entry.expiresAt <= now) continue;
371
+ n++;
372
+ }
373
+ return n;
374
+ }
375
+
376
+ // Round-trip helpers — operators with restart-survival needs serialize
377
+ // via getAll(), persist however they like, restore via setFromSerialized.
378
+ function setFromSerialized(rows) {
379
+ if (!Array.isArray(rows)) {
380
+ throw _err("BAD_OPT", "cookieJar.setFromSerialized: rows must be an array");
381
+ }
382
+ var now = clock();
383
+ for (var i = 0; i < rows.length; i++) {
384
+ var r = rows[i];
385
+ if (!r || typeof r.name !== "string" || typeof r.domain !== "string" || typeof r.path !== "string") continue;
386
+ var key = r.domain + "|" + r.path + "|" + r.name;
387
+ if (r.expiresAt !== null && r.expiresAt !== undefined && r.expiresAt <= now) continue;
388
+ store.set(key, {
389
+ name: r.name,
390
+ value: _seal(r.value),
391
+ domain: r.domain,
392
+ path: r.path,
393
+ hostOnly: !!r.hostOnly,
394
+ expiresAt: typeof r.expiresAt === "number" ? r.expiresAt : null,
395
+ httpOnly: !!r.httpOnly,
396
+ secure: !!r.secure,
397
+ sameSite: VALID_SAMESITE.has(r.sameSite) ? r.sameSite : null,
398
+ createdAt: typeof r.createdAt === "number" ? r.createdAt : now,
399
+ updatedAt: typeof r.updatedAt === "number" ? r.updatedAt : now,
400
+ });
401
+ }
402
+ }
403
+
404
+ // Raw-store accessor for tests — returns the literal Map entries with
405
+ // the value field as it sits in memory (sealed when persist === "vault").
406
+ // Operators don't call this; if they need stored state, getAll() returns
407
+ // the unsealed form. Exposed so the no-plaintext assertion is verifiable.
408
+ function _storeForTest() {
409
+ var rows = [];
410
+ for (var entry of store.values()) {
411
+ rows.push({
412
+ name: entry.name,
413
+ valueRaw: entry.value,
414
+ domain: entry.domain,
415
+ path: entry.path,
416
+ expiresAt: entry.expiresAt,
417
+ });
418
+ }
419
+ return rows;
420
+ }
421
+
422
+ // ---- File persistence ----
423
+ // When persist === "file", load on construct + flush on every write
424
+ // (debounced). On-disk format is JSON of getAll() output. If a vault
425
+ // is also passed, the file is sealed via vault.seal so the on-disk
426
+ // bytes are encrypted at rest; otherwise plaintext (operator chose
427
+ // the threat model by passing or omitting vault).
428
+ function _flushSync() {
429
+ if (!filePath) return;
430
+ var rows = getAll();
431
+ var serialized = JSON.stringify(rows);
432
+ var blob = vault ? vault.seal(serialized) : serialized;
433
+ fs.writeFileSync(filePath, blob);
434
+ }
435
+ var flushScheduler = safeAsync.makeScheduledFlush(flushDebounceMs, function () {
436
+ if (!filePath) return;
437
+ try { _flushSync(); } catch (_e) { /* operator can call flush() to retry */ }
438
+ });
439
+ function _scheduleFlush() {
440
+ if (!filePath) return;
441
+ flushScheduler.schedule();
442
+ }
443
+ function flush() {
444
+ flushScheduler.cancel();
445
+ _flushSync();
446
+ }
447
+ function close() {
448
+ flushScheduler.cancel();
449
+ if (filePath) try { _flushSync(); } catch (_e) { /* best-effort */ }
450
+ }
451
+
452
+ // Wrap mutating entrypoints so each write schedules a flush. The
453
+ // wrappers go on the returned object — the underlying function
454
+ // declarations stay intact so other internal callers reach them.
455
+ var setFromResponseAndFlush = function (reqUrl, hdr) {
456
+ setFromResponse(reqUrl, hdr); _scheduleFlush();
457
+ };
458
+ var clearAndFlush = function (filter) {
459
+ var n = clear(filter); _scheduleFlush(); return n;
460
+ };
461
+ var setFromSerializedAndFlush = function (rows) {
462
+ setFromSerialized(rows); _scheduleFlush();
463
+ };
464
+
465
+ // Initial load from file. Missing file is fine (first run).
466
+ // Persist file may be operator-tampered (or vault-sealed) — route through
467
+ // safeJson with an explicit byte cap so a maliciously-large file can't
468
+ // OOM the process before the parse fails.
469
+ if (filePath && fs.existsSync(filePath)) {
470
+ try {
471
+ var raw = fs.readFileSync(filePath, "utf8");
472
+ var serialized = vault ? vault.unseal(raw) : raw;
473
+ if (serialized && serialized.length > 0) {
474
+ var rows = safeJson.parse(serialized, { maxBytes: C.BYTES.mib(16) });
475
+ setFromSerialized(rows);
476
+ }
477
+ } catch (e) {
478
+ throw _err("LOAD_FAILED",
479
+ "cookieJar.create: failed to load persist file '" + filePath + "': " +
480
+ (e.message || String(e)));
481
+ }
482
+ }
483
+
484
+ return {
485
+ setFromResponse: filePath ? setFromResponseAndFlush : setFromResponse,
486
+ cookieHeaderFor: cookieHeaderFor,
487
+ getAll: getAll,
488
+ clear: filePath ? clearAndFlush : clear,
489
+ size: size,
490
+ setFromSerialized: filePath ? setFromSerializedAndFlush : setFromSerialized,
491
+ flush: flush,
492
+ close: close,
493
+ persist: persist,
494
+ file: filePath,
495
+ _storeForTest: _storeForTest,
496
+ };
497
+ }
498
+
499
+ module.exports = {
500
+ create: create,
501
+ CookieJarError: CookieJarError,
502
+ DEFAULTS: DEFAULTS,
503
+ // Exposed for tests + advanced operator wiring.
504
+ _parseSetCookie: _parseSetCookie,
505
+ };
506
+ // safeUrl reserved for future scheme validation hooks (e.g. operator-supplied
507
+ // allowedProtocols filter on cookie attachment paths).
508
+ void safeUrl;