@blamejs/core 0.7.4 → 0.7.18

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 (180) hide show
  1. package/CHANGELOG.md +423 -395
  2. package/README.md +150 -149
  3. package/bin/blamejs.js +0 -0
  4. package/index.js +308 -284
  5. package/lib/api-key.js +660 -663
  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.js +311 -311
  16. package/lib/auth/lockout.js +436 -436
  17. package/lib/auth/oauth.js +721 -721
  18. package/lib/auth/passkey.js +181 -181
  19. package/lib/auth/password.js +594 -594
  20. package/lib/backup/bundle.js +217 -217
  21. package/lib/backup/crypto.js +176 -176
  22. package/lib/backup/index.js +515 -515
  23. package/lib/backup/manifest.js +282 -282
  24. package/lib/break-glass.js +1338 -1338
  25. package/lib/bundler.js +441 -441
  26. package/lib/cache-redis.js +256 -256
  27. package/lib/cache.js +1206 -1206
  28. package/lib/canonical-json.js +115 -115
  29. package/lib/chain-writer.js +234 -234
  30. package/lib/cli-helpers.js +206 -206
  31. package/lib/cli.js +2334 -2334
  32. package/lib/cluster-provider-db.js +317 -317
  33. package/lib/cluster-storage.js +226 -226
  34. package/lib/cluster.js +703 -703
  35. package/lib/codepoint-class.js +196 -0
  36. package/lib/config-drift.js +301 -301
  37. package/lib/consent.js +222 -222
  38. package/lib/constants.js +191 -191
  39. package/lib/cookies.js +315 -315
  40. package/lib/credential-hash.js +322 -322
  41. package/lib/crypto.js +266 -266
  42. package/lib/csv.js +275 -286
  43. package/lib/db-declare-row-policy.js +267 -267
  44. package/lib/db-declare-view.js +420 -421
  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/file-upload.js +213 -10
  56. package/lib/forms.js +422 -422
  57. package/lib/framework-error.js +293 -215
  58. package/lib/framework-schema.js +717 -717
  59. package/lib/gate-contract.js +971 -0
  60. package/lib/guard-all.js +405 -0
  61. package/lib/guard-archive.js +739 -0
  62. package/lib/guard-csv.js +816 -0
  63. package/lib/guard-email.js +744 -0
  64. package/lib/guard-filename.js +724 -0
  65. package/lib/guard-html.js +976 -0
  66. package/lib/guard-json.js +729 -0
  67. package/lib/guard-markdown.js +586 -0
  68. package/lib/guard-svg.js +976 -0
  69. package/lib/guard-xml.js +405 -0
  70. package/lib/guard-yaml.js +529 -0
  71. package/lib/handlers.js +350 -350
  72. package/lib/http-client-cookie-jar.js +508 -508
  73. package/lib/http-client.js +1195 -1195
  74. package/lib/i18n.js +878 -878
  75. package/lib/jobs.js +185 -185
  76. package/lib/log-stream-cloudwatch.js +369 -369
  77. package/lib/log-stream-local.js +146 -146
  78. package/lib/log-stream-otlp-grpc.js +410 -410
  79. package/lib/log-stream-otlp.js +286 -286
  80. package/lib/log-stream-syslog.js +302 -302
  81. package/lib/log-stream-webhook.js +199 -199
  82. package/lib/log-stream.js +330 -330
  83. package/lib/log.js +500 -500
  84. package/lib/mail-bounce.js +528 -528
  85. package/lib/mail-dkim.js +369 -362
  86. package/lib/mail.js +981 -962
  87. package/lib/metrics.js +683 -683
  88. package/lib/middleware/api-encrypt.js +936 -936
  89. package/lib/middleware/attach-user.js +157 -157
  90. package/lib/middleware/body-parser.js +1170 -1091
  91. package/lib/middleware/bot-guard.js +178 -178
  92. package/lib/middleware/compression.js +452 -452
  93. package/lib/middleware/cors.js +314 -314
  94. package/lib/middleware/csp-nonce.js +348 -348
  95. package/lib/middleware/csrf-protect.js +316 -316
  96. package/lib/middleware/db-role-for.js +264 -264
  97. package/lib/middleware/health.js +392 -392
  98. package/lib/middleware/index.js +79 -79
  99. package/lib/middleware/rate-limit.js +358 -358
  100. package/lib/middleware/request-id.js +61 -61
  101. package/lib/middleware/request-log.js +168 -168
  102. package/lib/middleware/require-auth.js +104 -104
  103. package/lib/middleware/security-headers.js +116 -116
  104. package/lib/middleware/sse.js +166 -166
  105. package/lib/migrations.js +383 -383
  106. package/lib/mtls-ca.js +518 -518
  107. package/lib/mtls-engine-default.js +481 -481
  108. package/lib/network-dns.js +632 -632
  109. package/lib/network-heartbeat.js +290 -290
  110. package/lib/network-nts.js +574 -574
  111. package/lib/network-proxy.js +265 -265
  112. package/lib/network-tls.js +328 -328
  113. package/lib/network.js +233 -233
  114. package/lib/notify.js +612 -612
  115. package/lib/ntp-check.js +229 -229
  116. package/lib/numeric-bounds.js +111 -91
  117. package/lib/object-store/azure-blob-bucket-ops.js +349 -349
  118. package/lib/object-store/azure-blob.js +488 -488
  119. package/lib/object-store/gcs-bucket-ops.js +351 -351
  120. package/lib/object-store/gcs.js +519 -519
  121. package/lib/object-store/http-put.js +153 -153
  122. package/lib/object-store/index.js +197 -197
  123. package/lib/object-store/sigv4-bucket-ops.js +1092 -1092
  124. package/lib/object-store/sigv4.js +903 -903
  125. package/lib/observability.js +151 -151
  126. package/lib/otel-export.js +269 -269
  127. package/lib/pagination.js +464 -464
  128. package/lib/parsers/index.js +80 -80
  129. package/lib/parsers/safe-env.js +642 -642
  130. package/lib/parsers/safe-ini.js +292 -292
  131. package/lib/parsers/safe-toml.js +784 -784
  132. package/lib/parsers/safe-xml.js +390 -390
  133. package/lib/parsers/safe-yaml.js +1015 -1015
  134. package/lib/permissions.js +708 -708
  135. package/lib/pqc-agent.js +87 -87
  136. package/lib/pqc-gate.js +279 -279
  137. package/lib/protobuf-encoder.js +190 -190
  138. package/lib/protocol-dispatcher.js +161 -161
  139. package/lib/pubsub-redis.js +167 -167
  140. package/lib/pubsub.js +429 -429
  141. package/lib/queue-local.js +476 -476
  142. package/lib/queue-redis.js +745 -745
  143. package/lib/queue-sqs.js +319 -319
  144. package/lib/queue.js +695 -695
  145. package/lib/redis-client.js +519 -519
  146. package/lib/request-helpers.js +340 -340
  147. package/lib/restore-bundle.js +237 -237
  148. package/lib/restore-rollback.js +259 -259
  149. package/lib/restore.js +409 -409
  150. package/lib/retry.js +376 -376
  151. package/lib/router.js +748 -748
  152. package/lib/safe-async.js +735 -735
  153. package/lib/safe-buffer.js +237 -237
  154. package/lib/safe-json.js +541 -541
  155. package/lib/safe-schema.js +1266 -1266
  156. package/lib/safe-url.js +159 -159
  157. package/lib/scheduler.js +706 -706
  158. package/lib/security-assert.js +373 -373
  159. package/lib/seeders.js +618 -618
  160. package/lib/session.js +478 -478
  161. package/lib/slug.js +269 -269
  162. package/lib/ssrf-guard.js +401 -401
  163. package/lib/static.js +184 -4
  164. package/lib/storage.js +471 -471
  165. package/lib/subject.js +281 -281
  166. package/lib/template.js +791 -791
  167. package/lib/testing.js +798 -798
  168. package/lib/time.js +310 -310
  169. package/lib/totp.js +302 -302
  170. package/lib/tracing.js +494 -494
  171. package/lib/uuid.js +132 -132
  172. package/lib/validate-opts.js +340 -319
  173. package/lib/vault/index.js +308 -308
  174. package/lib/vault/rotate.js +784 -784
  175. package/lib/vault/wrap.js +296 -296
  176. package/lib/vendor/noble-ciphers.cjs +9 -9
  177. package/lib/webhook.js +595 -595
  178. package/lib/websocket.js +1048 -1048
  179. package/package.json +77 -77
  180. package/sbom.cyclonedx.json +7 -7
package/lib/safe-json.js CHANGED
@@ -1,541 +1,541 @@
1
- "use strict";
2
- /**
3
- * Security-focused, fault-tolerant JSON utilities + lightweight schema
4
- * validation with extensible format registry.
5
- *
6
- * Native JSON.parse leaves several footguns to the caller:
7
- * - No size limit — large inputs DoS the parser thread
8
- * - No depth limit — deeply nested input can stack-overflow downstream code
9
- * - __proto__ / constructor / prototype keys land in the result and can be
10
- * turned into prototype pollution by any later object-merge / clone
11
- * - Errors include only a character position, no surrounding context
12
- *
13
- * This module fixes all of the above with conservative defaults and adds a
14
- * lightweight schema validator (a strict subset of JSON Schema) so apps
15
- * can declare what they expect at the trust boundary.
16
- *
17
- * Public API:
18
- *
19
- * json.parse(input, opts?) → value | throws SafeJsonError
20
- * (with opts.collectErrors: { ok, value, errors[] })
21
- * json.parseOrDefault(input, fallback, opts?) → value (no throw)
22
- * json.stringify(value, opts?) → string | throws SafeJsonError
23
- * json.canonical(value, opts?) → string (sorted keys)
24
- * json.validate(value, schema, opts?) → value | throws
25
- * (with opts.collectErrors: { ok, value, errors[] })
26
- * json.registerFormat(name, validator) → register a custom format
27
- * json.formats → built-in format names
28
- * json.SafeJsonError → error class
29
- *
30
- * Validation modes (opts.collectErrors):
31
- * - default (throw): fails loudly on first error — right for trust boundaries
32
- * (HTTP body parse, sealed payload deserialize, config load).
33
- * The throw IS the security signal; HTTP middleware catches
34
- * it and emits a 400 with .path / .code.
35
- * - collectErrors:true: returns { ok, value, errors[] } — right for form-style
36
- * bulk validation where the user needs to see every field
37
- * that failed in one round-trip.
38
- *
39
- * Defaults:
40
- * maxBytes: 1 MiB
41
- * maxDepth: 100
42
- * allowProto: false
43
- * onCircular: "throw"
44
- *
45
- * Schema dialect (JSON Schema subset):
46
- * { type: 'string'|'number'|'integer'|'boolean'|'null'|'array'|'object',
47
- * enum: [...],
48
- * // string
49
- * minLength, maxLength, pattern, format,
50
- * // number
51
- * minimum, maximum, exclusiveMinimum, exclusiveMaximum,
52
- * // array
53
- * minItems, maxItems, items: <schema>,
54
- * // object
55
- * required: [...], properties: { key: <schema>, ... }, additionalProperties: bool
56
- * }
57
- *
58
- * Schemas are app-developer-supplied (not user-controlled); regex patterns
59
- * are trusted not to be ReDoS-prone. Format validators in the built-in
60
- * registry are anchored / bounded.
61
- */
62
-
63
- // ---- Error class ----
64
-
65
- var C = require("./constants");
66
- var safeBuffer = require("./safe-buffer");
67
- var safeUrl = require("./safe-url");
68
- var time = require("./time");
69
- var { FrameworkError } = require("./framework-error");
70
-
71
- class SafeJsonError extends FrameworkError {
72
- constructor(message, code, path) {
73
- super(message);
74
- this.name = "SafeJsonError";
75
- this.code = code || "json/invalid";
76
- this.path = path || null;
77
- this.isSafeJsonError = true;
78
- }
79
- }
80
-
81
- var ABSOLUTE_MAX_BYTES = C.BYTES.mib(64);
82
- var ABSOLUTE_MAX_DEPTH = 1_000;
83
-
84
- // IPv6 has 8 16-bit hextets per RFC 4291; named so the call sites in
85
- // formats.ipv6 don't carry a bare 8 integer literal.
86
- var IPV6_HEXTET_COUNT = 0x8;
87
- var DEFAULT_MAX_BYTES = C.BYTES.mib(1);
88
- var DEFAULT_MAX_DEPTH = 100;
89
-
90
- var POISONED_KEYS = new Set(["__proto__", "constructor", "prototype"]);
91
-
92
- // ---- parse ----
93
-
94
- function parse(input, opts) {
95
- opts = opts || {};
96
-
97
- var maxBytes = _capInt(opts.maxBytes, DEFAULT_MAX_BYTES, ABSOLUTE_MAX_BYTES);
98
- input = safeBuffer.normalizeText(input, {
99
- maxBytes: maxBytes,
100
- errorClass: SafeJsonError,
101
- typeCode: "json/wrong-input-type",
102
- sizeCode: "json/too-large",
103
- typeMessage: "input must be a string, Buffer, or Uint8Array",
104
- });
105
-
106
- var maxDepth = _capInt(opts.maxDepth, DEFAULT_MAX_DEPTH, ABSOLUTE_MAX_DEPTH);
107
- var allowProto = !!opts.allowProto;
108
-
109
- var parsed;
110
- try {
111
- parsed = JSON.parse(input, allowProto ? undefined : _stripProtoKeys);
112
- } catch (e) {
113
- throw new SafeJsonError("invalid JSON: " + e.message, "json/syntax");
114
- }
115
-
116
- _walkAndCheck(parsed, 0, maxDepth, allowProto);
117
-
118
- // Optional schema validation (preferred over expectType / requiredKeys)
119
- if (opts.schema) {
120
- if (opts.collectErrors) {
121
- var result = validate(parsed, opts.schema, { collectErrors: true });
122
- // Always return the same shape parse promised: a value or an
123
- // { ok, value, errors[] } object. Caller signals which they want
124
- // via opts.collectErrors.
125
- return result;
126
- }
127
- validate(parsed, opts.schema);
128
- return parsed;
129
- }
130
-
131
- // Legacy lightweight type assertion (for callers that don't supply a schema)
132
- if (opts.expectType) {
133
- var actual = _typeName(parsed);
134
- if (actual !== opts.expectType) {
135
- throw new SafeJsonError("expected " + opts.expectType + " at root, got " + actual, "json/type-mismatch");
136
- }
137
- }
138
- if (Array.isArray(opts.requiredKeys) && parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
139
- for (var i = 0; i < opts.requiredKeys.length; i++) {
140
- if (!Object.prototype.hasOwnProperty.call(parsed, opts.requiredKeys[i])) {
141
- throw new SafeJsonError("missing required key '" + opts.requiredKeys[i] + "'", "json/missing-key");
142
- }
143
- }
144
- }
145
-
146
- return parsed;
147
- }
148
-
149
- function parseOrDefault(input, fallback, opts) {
150
- try { return parse(input, opts); }
151
- catch (_e) { return fallback; }
152
- }
153
-
154
- function _stripProtoKeys(key, value) {
155
- if (POISONED_KEYS.has(key)) return undefined;
156
- return value;
157
- }
158
-
159
- function _walkAndCheck(value, depth, maxDepth, allowProto) {
160
- if (depth > maxDepth) {
161
- throw new SafeJsonError("nesting exceeds maxDepth (" + maxDepth + ")", "json/too-deep");
162
- }
163
- if (value === null || typeof value !== "object") return;
164
- if (Array.isArray(value)) {
165
- for (var i = 0; i < value.length; i++) _walkAndCheck(value[i], depth + 1, maxDepth, allowProto);
166
- return;
167
- }
168
- if (!allowProto) {
169
- POISONED_KEYS.forEach(function (k) {
170
- if (Object.prototype.hasOwnProperty.call(value, k)) delete value[k];
171
- });
172
- }
173
- for (var k in value) {
174
- if (Object.prototype.hasOwnProperty.call(value, k)) {
175
- _walkAndCheck(value[k], depth + 1, maxDepth, allowProto);
176
- }
177
- }
178
- }
179
-
180
- function _typeName(v) {
181
- if (v === null) return "null";
182
- if (Array.isArray(v)) return "array";
183
- return typeof v;
184
- }
185
-
186
- // ---- stringify ----
187
-
188
- function stringify(value, opts) {
189
- opts = opts || {};
190
- var onCircular = opts.onCircular || "throw";
191
- var replacement = opts.circularReplacement !== undefined ? opts.circularReplacement : "[Circular]";
192
- var allowProto = !!opts.allowProto;
193
- var indent = opts.indent || 0;
194
-
195
- // For "replace" mode, we pre-clean the tree manually because JSON.stringify
196
- // will throw on cycles before the replacer can rewrite them. The cleaning
197
- // walk uses stack-discipline (add on descend, remove on ascend) so SHARED
198
- // subtrees aren't falsely flagged as circular.
199
- var input = value;
200
- if (onCircular === "replace") {
201
- input = _cleanCycles(value, replacement, allowProto);
202
- }
203
-
204
- function replacer(key, val) {
205
- if (!allowProto && POISONED_KEYS.has(key)) return undefined;
206
- return val;
207
- }
208
-
209
- try {
210
- return JSON.stringify(input, replacer, indent);
211
- } catch (e) {
212
- if (e && e.isSafeJsonError) throw e;
213
- // JSON.stringify throws TypeError "Converting circular structure to JSON"
214
- // when it hits a cycle in throw mode.
215
- if (e instanceof TypeError && /circular/i.test(e.message)) {
216
- throw new SafeJsonError("circular reference: " + e.message, "json/circular");
217
- }
218
- throw new SafeJsonError("stringify failed: " + e.message, "json/stringify");
219
- }
220
- }
221
-
222
- // Walk the value, substituting any references that would create a cycle
223
- // with `replacement`. Uses an active-stack Set so SHARED non-circular
224
- // subtrees are preserved (only true cycles are replaced).
225
- function _cleanCycles(value, replacement, allowProto) {
226
- var stack = new Set();
227
-
228
- function walk(v) {
229
- if (v === null || typeof v !== "object") return v;
230
- if (stack.has(v)) return replacement;
231
- stack.add(v);
232
- var out;
233
- if (Array.isArray(v)) {
234
- out = new Array(v.length);
235
- for (var i = 0; i < v.length; i++) out[i] = walk(v[i]);
236
- } else {
237
- out = {};
238
- for (var k in v) {
239
- if (!Object.prototype.hasOwnProperty.call(v, k)) continue;
240
- if (!allowProto && POISONED_KEYS.has(k)) continue;
241
- out[k] = walk(v[k]);
242
- }
243
- }
244
- stack.delete(v);
245
- return out;
246
- }
247
-
248
- return walk(value);
249
- }
250
-
251
- // ---- canonical ----
252
-
253
- function canonical(value, _opts) {
254
- if (typeof value === "undefined") return "null";
255
-
256
- function ser(v) {
257
- if (v === null || typeof v === "boolean") return JSON.stringify(v);
258
- if (typeof v === "number") {
259
- if (!Number.isFinite(v)) {
260
- throw new SafeJsonError("non-finite number cannot be canonicalized", "json/non-finite");
261
- }
262
- return JSON.stringify(v);
263
- }
264
- if (typeof v === "string") return JSON.stringify(v);
265
- if (Array.isArray(v)) return "[" + v.map(ser).join(",") + "]";
266
- if (typeof v === "object") {
267
- var keys = Object.keys(v).filter(function (k) { return !POISONED_KEYS.has(k); }).sort();
268
- var pairs = keys.map(function (k) { return JSON.stringify(k) + ":" + ser(v[k]); });
269
- return "{" + pairs.join(",") + "}";
270
- }
271
- throw new SafeJsonError("cannot canonicalize value of type " + typeof v, "json/uncanonical");
272
- }
273
-
274
- return ser(value);
275
- }
276
-
277
- // ---- format registry ----
278
-
279
- // Anchored and bounded — nothing here is ReDoS-prone.
280
- var formats = {
281
- // Structural-only email check (no RFC 5322 attempt). Keeps complexity O(n).
282
- // Length cap prevents pathological backtracking against long inputs.
283
- email: function (v) {
284
- return typeof v === "string" && v.length <= 254 &&
285
- /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v);
286
- },
287
- // URL must parse via WHATWG URL and use http(s)/ws(s) — adjust per app
288
- url: function (v) {
289
- if (typeof v !== "string") return false;
290
- try {
291
- var u = safeUrl.parse(v, { allowedProtocols: ["http:", "https:", "ws:", "wss:"] });
292
- return !!u;
293
- } catch (_e) { return false; }
294
- },
295
- uuid: function (v) {
296
- return typeof v === "string" &&
297
- /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(v);
298
- },
299
- // Crockford base32, 26 chars, must start with [0-7] (timestamp range)
300
- ulid: function (v) {
301
- return typeof v === "string" && /^[0-7][0-9A-HJKMNP-TV-Z]{25}$/.test(v);
302
- },
303
- "iso8601-date": function (v) {
304
- if (typeof v !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(v)) return false;
305
- var d = new Date(v);
306
- return !isNaN(d.getTime()) && d.toISOString().slice(0, 10) === v;
307
- },
308
- "iso8601-datetime": function (v) {
309
- if (typeof v !== "string") return false;
310
- var d = new Date(v);
311
- return !isNaN(d.getTime()) &&
312
- d.toISOString().replace(time.ISO_MS_RE, "Z") === v.replace(time.ISO_MS_RE, "Z");
313
- },
314
- ipv4: function (v) {
315
- if (typeof v !== "string") return false;
316
- var parts = v.split(".");
317
- if (parts.length !== 4) return false;
318
- for (var i = 0; i < 4; i++) {
319
- if (!/^\d{1,3}$/.test(parts[i])) return false;
320
- var n = Number(parts[i]);
321
- if (n < 0 || n > 255) return false;
322
- if (parts[i] !== String(n)) return false; // no leading zeros
323
- }
324
- return true;
325
- },
326
- // RFC 4291 / RFC 5952 IPv6 — accepts all common forms:
327
- // - Full 8 groups: 2001:0db8:85a3:0000:0000:8a2e:0370:7334
328
- // - Compressed: 2001:db8::1, ::1, ::, fe80::abcd
329
- // - IPv4-mapped: ::ffff:192.168.1.1
330
- // - Mixed case: 2001:DB8::1
331
- // Rejects: multiple ::, > 8 groups, non-hex chars, groups > 4 hex digits,
332
- // zone IDs (%eth0 etc — not appropriate for portable data).
333
- ipv6: function (v) {
334
- if (typeof v !== "string" || v.length === 0 || v.length > 45) return false;
335
- if (v.indexOf("%") !== -1) return false; // zone IDs not allowed
336
- if (v.indexOf(":::") !== -1) return false;
337
-
338
- var doubleColon = v.indexOf("::");
339
- var hasDouble = doubleColon !== -1;
340
- if (hasDouble && v.indexOf("::", doubleColon + 2) !== -1) return false;
341
-
342
- var leftParts, rightParts;
343
- if (hasDouble) {
344
- var left = v.slice(0, doubleColon);
345
- var right = v.slice(doubleColon + 2);
346
- leftParts = left ? left.split(":") : [];
347
- rightParts = right ? right.split(":") : [];
348
- } else {
349
- leftParts = v.split(":");
350
- rightParts = [];
351
- }
352
-
353
- // IPv4-mapped suffix (::ffff:192.0.2.1, 2001:db8::192.0.2.1, etc.)
354
- var tail = hasDouble ? rightParts : leftParts;
355
- if (tail.length > 0 && tail[tail.length - 1].indexOf(".") !== -1) {
356
- if (!formats.ipv4(tail[tail.length - 1])) return false;
357
- tail.pop();
358
- // IPv4 is 32 bits = 2 IPv6 groups; insert two synthetic groups
359
- tail.push("0", "0");
360
- }
361
-
362
- var totalParts = leftParts.length + rightParts.length;
363
- if (hasDouble) {
364
- // Compressed form must replace AT LEAST ONE missing group (otherwise
365
- // it would be a redundant ::), so total < IPV6_HEXTET_COUNT is required.
366
- if (totalParts >= IPV6_HEXTET_COUNT) return false;
367
- } else {
368
- if (totalParts !== IPV6_HEXTET_COUNT) return false;
369
- }
370
-
371
- var all = leftParts.concat(rightParts);
372
- for (var i = 0; i < all.length; i++) {
373
- if (!/^[0-9a-fA-F]{1,4}$/.test(all[i])) return false;
374
- }
375
- return true;
376
- },
377
- ip: function (v) { return formats.ipv4(v) || formats.ipv6(v); },
378
- hex: function (v) { return safeBuffer.isHex(v); },
379
- // Generic non-empty token: alphanumeric + a few safe punctuation
380
- slug: function (v) { return typeof v === "string" && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(v); },
381
- };
382
-
383
- function registerFormat(name, validator) {
384
- if (typeof name !== "string" || !/^[a-z][a-z0-9-]*$/.test(name)) {
385
- throw new SafeJsonError("format name must match [a-z][a-z0-9-]*: " + name, "json/bad-format-name");
386
- }
387
- if (typeof validator !== "function") {
388
- throw new SafeJsonError("format validator must be a function", "json/bad-format-validator");
389
- }
390
- formats[name] = validator;
391
- }
392
-
393
- // ---- validate ----
394
-
395
- function validate(value, schema, opts) {
396
- opts = opts || {};
397
- if (!schema || typeof schema !== "object") {
398
- throw new SafeJsonError("validate: schema must be an object", "json/bad-schema");
399
- }
400
-
401
- if (opts.collectErrors) {
402
- var errors = [];
403
- _validateNode(value, schema, "$", function (err) { errors.push(err); });
404
- if (errors.length === 0) return { ok: true, value: value, errors: [] };
405
- return { ok: false, value: value, errors: errors };
406
- }
407
- // Throw mode (default)
408
- _validateNode(value, schema, "$", function (err) { throw err; });
409
- return value;
410
- }
411
-
412
- // Core validation walker. Calls report(error) on every failure. In throw
413
- // mode the report callback throws — control unwinds via the throw. In
414
- // collect mode the report callback pushes; we use early-returns at fatal
415
- // points (type mismatch on a node) to avoid noisy follow-on errors that
416
- // would all be downstream of the same root cause.
417
- function _validateNode(value, schema, path, report) {
418
- // Type check — if it fails, the value-specific constraints below would
419
- // produce noisy duplicate errors. Bail this node after reporting.
420
- if (schema.type) {
421
- if (schema.type === "integer") {
422
- if (typeof value !== "number" || !Number.isInteger(value)) {
423
- report(new SafeJsonError(path + ": expected integer, got " + _typeName(value), "json/validation", path));
424
- return;
425
- }
426
- } else if (_typeName(value) !== schema.type) {
427
- report(new SafeJsonError(path + ": expected " + schema.type + ", got " + _typeName(value), "json/validation", path));
428
- return;
429
- }
430
- }
431
-
432
- // Enum (independent of type)
433
- if (Array.isArray(schema.enum)) {
434
- if (schema.enum.indexOf(value) === -1) {
435
- report(new SafeJsonError(
436
- path + ": value not in enum (" + JSON.stringify(schema.enum) + ")",
437
- "json/validation", path
438
- ));
439
- }
440
- }
441
-
442
- // String constraints
443
- if (typeof value === "string") {
444
- if (schema.minLength != null && value.length < schema.minLength) {
445
- report(new SafeJsonError(path + ": string length " + value.length + " < minLength " + schema.minLength, "json/validation", path));
446
- }
447
- if (schema.maxLength != null && value.length > schema.maxLength) {
448
- report(new SafeJsonError(path + ": string length " + value.length + " > maxLength " + schema.maxLength, "json/validation", path));
449
- }
450
- if (schema.pattern) {
451
- var re = schema.pattern instanceof RegExp ? schema.pattern : new RegExp(schema.pattern);
452
- if (!re.test(value)) {
453
- report(new SafeJsonError(path + ": does not match pattern", "json/validation", path));
454
- }
455
- }
456
- if (schema.format) {
457
- var f = formats[schema.format];
458
- if (!f) {
459
- report(new SafeJsonError(path + ": unknown format '" + schema.format + "'", "json/unknown-format", path));
460
- } else if (!f(value)) {
461
- report(new SafeJsonError(path + ": does not match format '" + schema.format + "'", "json/validation", path));
462
- }
463
- }
464
- }
465
-
466
- // Number constraints
467
- if (typeof value === "number") {
468
- if (schema.minimum != null && value < schema.minimum) {
469
- report(new SafeJsonError(path + ": " + value + " < minimum " + schema.minimum, "json/validation", path));
470
- }
471
- if (schema.exclusiveMinimum != null && value <= schema.exclusiveMinimum) {
472
- report(new SafeJsonError(path + ": " + value + " <= exclusiveMinimum " + schema.exclusiveMinimum, "json/validation", path));
473
- }
474
- if (schema.maximum != null && value > schema.maximum) {
475
- report(new SafeJsonError(path + ": " + value + " > maximum " + schema.maximum, "json/validation", path));
476
- }
477
- if (schema.exclusiveMaximum != null && value >= schema.exclusiveMaximum) {
478
- report(new SafeJsonError(path + ": " + value + " >= exclusiveMaximum " + schema.exclusiveMaximum, "json/validation", path));
479
- }
480
- }
481
-
482
- // Array constraints
483
- if (Array.isArray(value)) {
484
- if (schema.minItems != null && value.length < schema.minItems) {
485
- report(new SafeJsonError(path + ": array length " + value.length + " < minItems " + schema.minItems, "json/validation", path));
486
- }
487
- if (schema.maxItems != null && value.length > schema.maxItems) {
488
- report(new SafeJsonError(path + ": array length " + value.length + " > maxItems " + schema.maxItems, "json/validation", path));
489
- }
490
- if (schema.items) {
491
- for (var i = 0; i < value.length; i++) {
492
- _validateNode(value[i], schema.items, path + "[" + i + "]", report);
493
- }
494
- }
495
- }
496
-
497
- // Object constraints
498
- if (value !== null && typeof value === "object" && !Array.isArray(value)) {
499
- if (Array.isArray(schema.required)) {
500
- for (var rk = 0; rk < schema.required.length; rk++) {
501
- if (!Object.prototype.hasOwnProperty.call(value, schema.required[rk])) {
502
- report(new SafeJsonError(path + ": missing required key '" + schema.required[rk] + "'", "json/validation", path));
503
- }
504
- }
505
- }
506
- var allowAdditional = schema.additionalProperties !== false;
507
- if (schema.properties) {
508
- for (var k in value) {
509
- if (!Object.prototype.hasOwnProperty.call(value, k)) continue;
510
- if (Object.prototype.hasOwnProperty.call(schema.properties, k)) {
511
- _validateNode(value[k], schema.properties[k], path + "." + k, report);
512
- } else if (!allowAdditional) {
513
- report(new SafeJsonError(path + ": unknown key '" + k + "'", "json/validation", path + "." + k));
514
- }
515
- }
516
- }
517
- }
518
- }
519
-
520
- // ---- helpers ----
521
-
522
- function _capInt(value, defaultValue, ceiling) {
523
- if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return defaultValue;
524
- return Math.min(Math.floor(value), ceiling);
525
- }
526
-
527
- module.exports = {
528
- parse: parse,
529
- parseOrDefault: parseOrDefault,
530
- stringify: stringify,
531
- canonical: canonical,
532
- validate: validate,
533
- registerFormat: registerFormat,
534
- formats: formats,
535
- SafeJsonError: SafeJsonError,
536
- DEFAULT_MAX_BYTES: DEFAULT_MAX_BYTES,
537
- DEFAULT_MAX_DEPTH: DEFAULT_MAX_DEPTH,
538
- ABSOLUTE_MAX_BYTES: ABSOLUTE_MAX_BYTES,
539
- ABSOLUTE_MAX_DEPTH: ABSOLUTE_MAX_DEPTH,
540
- POISONED_KEYS: Array.from(POISONED_KEYS),
541
- };
1
+ "use strict";
2
+ /**
3
+ * Security-focused, fault-tolerant JSON utilities + lightweight schema
4
+ * validation with extensible format registry.
5
+ *
6
+ * Native JSON.parse leaves several footguns to the caller:
7
+ * - No size limit — large inputs DoS the parser thread
8
+ * - No depth limit — deeply nested input can stack-overflow downstream code
9
+ * - __proto__ / constructor / prototype keys land in the result and can be
10
+ * turned into prototype pollution by any later object-merge / clone
11
+ * - Errors include only a character position, no surrounding context
12
+ *
13
+ * This module fixes all of the above with conservative defaults and adds a
14
+ * lightweight schema validator (a strict subset of JSON Schema) so apps
15
+ * can declare what they expect at the trust boundary.
16
+ *
17
+ * Public API:
18
+ *
19
+ * json.parse(input, opts?) → value | throws SafeJsonError
20
+ * (with opts.collectErrors: { ok, value, errors[] })
21
+ * json.parseOrDefault(input, fallback, opts?) → value (no throw)
22
+ * json.stringify(value, opts?) → string | throws SafeJsonError
23
+ * json.canonical(value, opts?) → string (sorted keys)
24
+ * json.validate(value, schema, opts?) → value | throws
25
+ * (with opts.collectErrors: { ok, value, errors[] })
26
+ * json.registerFormat(name, validator) → register a custom format
27
+ * json.formats → built-in format names
28
+ * json.SafeJsonError → error class
29
+ *
30
+ * Validation modes (opts.collectErrors):
31
+ * - default (throw): fails loudly on first error — right for trust boundaries
32
+ * (HTTP body parse, sealed payload deserialize, config load).
33
+ * The throw IS the security signal; HTTP middleware catches
34
+ * it and emits a 400 with .path / .code.
35
+ * - collectErrors:true: returns { ok, value, errors[] } — right for form-style
36
+ * bulk validation where the user needs to see every field
37
+ * that failed in one round-trip.
38
+ *
39
+ * Defaults:
40
+ * maxBytes: 1 MiB
41
+ * maxDepth: 100
42
+ * allowProto: false
43
+ * onCircular: "throw"
44
+ *
45
+ * Schema dialect (JSON Schema subset):
46
+ * { type: 'string'|'number'|'integer'|'boolean'|'null'|'array'|'object',
47
+ * enum: [...],
48
+ * // string
49
+ * minLength, maxLength, pattern, format,
50
+ * // number
51
+ * minimum, maximum, exclusiveMinimum, exclusiveMaximum,
52
+ * // array
53
+ * minItems, maxItems, items: <schema>,
54
+ * // object
55
+ * required: [...], properties: { key: <schema>, ... }, additionalProperties: bool
56
+ * }
57
+ *
58
+ * Schemas are app-developer-supplied (not user-controlled); regex patterns
59
+ * are trusted not to be ReDoS-prone. Format validators in the built-in
60
+ * registry are anchored / bounded.
61
+ */
62
+
63
+ // ---- Error class ----
64
+
65
+ var C = require("./constants");
66
+ var safeBuffer = require("./safe-buffer");
67
+ var safeUrl = require("./safe-url");
68
+ var time = require("./time");
69
+ var { FrameworkError } = require("./framework-error");
70
+
71
+ class SafeJsonError extends FrameworkError {
72
+ constructor(message, code, path) {
73
+ super(message);
74
+ this.name = "SafeJsonError";
75
+ this.code = code || "json/invalid";
76
+ this.path = path || null;
77
+ this.isSafeJsonError = true;
78
+ }
79
+ }
80
+
81
+ var ABSOLUTE_MAX_BYTES = C.BYTES.mib(64);
82
+ var ABSOLUTE_MAX_DEPTH = 1_000;
83
+
84
+ // IPv6 has 8 16-bit hextets per RFC 4291; named so the call sites in
85
+ // formats.ipv6 don't carry a bare 8 integer literal.
86
+ var IPV6_HEXTET_COUNT = 0x8;
87
+ var DEFAULT_MAX_BYTES = C.BYTES.mib(1);
88
+ var DEFAULT_MAX_DEPTH = 100;
89
+
90
+ var POISONED_KEYS = new Set(["__proto__", "constructor", "prototype"]);
91
+
92
+ // ---- parse ----
93
+
94
+ function parse(input, opts) {
95
+ opts = opts || {};
96
+
97
+ var maxBytes = _capInt(opts.maxBytes, DEFAULT_MAX_BYTES, ABSOLUTE_MAX_BYTES);
98
+ input = safeBuffer.normalizeText(input, {
99
+ maxBytes: maxBytes,
100
+ errorClass: SafeJsonError,
101
+ typeCode: "json/wrong-input-type",
102
+ sizeCode: "json/too-large",
103
+ typeMessage: "input must be a string, Buffer, or Uint8Array",
104
+ });
105
+
106
+ var maxDepth = _capInt(opts.maxDepth, DEFAULT_MAX_DEPTH, ABSOLUTE_MAX_DEPTH);
107
+ var allowProto = !!opts.allowProto;
108
+
109
+ var parsed;
110
+ try {
111
+ parsed = JSON.parse(input, allowProto ? undefined : _stripProtoKeys);
112
+ } catch (e) {
113
+ throw new SafeJsonError("invalid JSON: " + e.message, "json/syntax");
114
+ }
115
+
116
+ _walkAndCheck(parsed, 0, maxDepth, allowProto);
117
+
118
+ // Optional schema validation (preferred over expectType / requiredKeys)
119
+ if (opts.schema) {
120
+ if (opts.collectErrors) {
121
+ var result = validate(parsed, opts.schema, { collectErrors: true });
122
+ // Always return the same shape parse promised: a value or an
123
+ // { ok, value, errors[] } object. Caller signals which they want
124
+ // via opts.collectErrors.
125
+ return result;
126
+ }
127
+ validate(parsed, opts.schema);
128
+ return parsed;
129
+ }
130
+
131
+ // Legacy lightweight type assertion (for callers that don't supply a schema)
132
+ if (opts.expectType) {
133
+ var actual = _typeName(parsed);
134
+ if (actual !== opts.expectType) {
135
+ throw new SafeJsonError("expected " + opts.expectType + " at root, got " + actual, "json/type-mismatch");
136
+ }
137
+ }
138
+ if (Array.isArray(opts.requiredKeys) && parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
139
+ for (var i = 0; i < opts.requiredKeys.length; i++) {
140
+ if (!Object.prototype.hasOwnProperty.call(parsed, opts.requiredKeys[i])) {
141
+ throw new SafeJsonError("missing required key '" + opts.requiredKeys[i] + "'", "json/missing-key");
142
+ }
143
+ }
144
+ }
145
+
146
+ return parsed;
147
+ }
148
+
149
+ function parseOrDefault(input, fallback, opts) {
150
+ try { return parse(input, opts); }
151
+ catch (_e) { return fallback; }
152
+ }
153
+
154
+ function _stripProtoKeys(key, value) {
155
+ if (POISONED_KEYS.has(key)) return undefined;
156
+ return value;
157
+ }
158
+
159
+ function _walkAndCheck(value, depth, maxDepth, allowProto) {
160
+ if (depth > maxDepth) {
161
+ throw new SafeJsonError("nesting exceeds maxDepth (" + maxDepth + ")", "json/too-deep");
162
+ }
163
+ if (value === null || typeof value !== "object") return;
164
+ if (Array.isArray(value)) {
165
+ for (var i = 0; i < value.length; i++) _walkAndCheck(value[i], depth + 1, maxDepth, allowProto);
166
+ return;
167
+ }
168
+ if (!allowProto) {
169
+ POISONED_KEYS.forEach(function (k) {
170
+ if (Object.prototype.hasOwnProperty.call(value, k)) delete value[k];
171
+ });
172
+ }
173
+ for (var k in value) {
174
+ if (Object.prototype.hasOwnProperty.call(value, k)) {
175
+ _walkAndCheck(value[k], depth + 1, maxDepth, allowProto);
176
+ }
177
+ }
178
+ }
179
+
180
+ function _typeName(v) {
181
+ if (v === null) return "null";
182
+ if (Array.isArray(v)) return "array";
183
+ return typeof v;
184
+ }
185
+
186
+ // ---- stringify ----
187
+
188
+ function stringify(value, opts) {
189
+ opts = opts || {};
190
+ var onCircular = opts.onCircular || "throw";
191
+ var replacement = opts.circularReplacement !== undefined ? opts.circularReplacement : "[Circular]";
192
+ var allowProto = !!opts.allowProto;
193
+ var indent = opts.indent || 0;
194
+
195
+ // For "replace" mode, we pre-clean the tree manually because JSON.stringify
196
+ // will throw on cycles before the replacer can rewrite them. The cleaning
197
+ // walk uses stack-discipline (add on descend, remove on ascend) so SHARED
198
+ // subtrees aren't falsely flagged as circular.
199
+ var input = value;
200
+ if (onCircular === "replace") {
201
+ input = _cleanCycles(value, replacement, allowProto);
202
+ }
203
+
204
+ function replacer(key, val) {
205
+ if (!allowProto && POISONED_KEYS.has(key)) return undefined;
206
+ return val;
207
+ }
208
+
209
+ try {
210
+ return JSON.stringify(input, replacer, indent);
211
+ } catch (e) {
212
+ if (e && e.isSafeJsonError) throw e;
213
+ // JSON.stringify throws TypeError "Converting circular structure to JSON"
214
+ // when it hits a cycle in throw mode.
215
+ if (e instanceof TypeError && /circular/i.test(e.message)) {
216
+ throw new SafeJsonError("circular reference: " + e.message, "json/circular");
217
+ }
218
+ throw new SafeJsonError("stringify failed: " + e.message, "json/stringify");
219
+ }
220
+ }
221
+
222
+ // Walk the value, substituting any references that would create a cycle
223
+ // with `replacement`. Uses an active-stack Set so SHARED non-circular
224
+ // subtrees are preserved (only true cycles are replaced).
225
+ function _cleanCycles(value, replacement, allowProto) {
226
+ var stack = new Set();
227
+
228
+ function walk(v) {
229
+ if (v === null || typeof v !== "object") return v;
230
+ if (stack.has(v)) return replacement;
231
+ stack.add(v);
232
+ var out;
233
+ if (Array.isArray(v)) {
234
+ out = new Array(v.length);
235
+ for (var i = 0; i < v.length; i++) out[i] = walk(v[i]);
236
+ } else {
237
+ out = {};
238
+ for (var k in v) {
239
+ if (!Object.prototype.hasOwnProperty.call(v, k)) continue;
240
+ if (!allowProto && POISONED_KEYS.has(k)) continue;
241
+ out[k] = walk(v[k]);
242
+ }
243
+ }
244
+ stack.delete(v);
245
+ return out;
246
+ }
247
+
248
+ return walk(value);
249
+ }
250
+
251
+ // ---- canonical ----
252
+
253
+ function canonical(value, _opts) {
254
+ if (typeof value === "undefined") return "null";
255
+
256
+ function ser(v) {
257
+ if (v === null || typeof v === "boolean") return JSON.stringify(v);
258
+ if (typeof v === "number") {
259
+ if (!Number.isFinite(v)) {
260
+ throw new SafeJsonError("non-finite number cannot be canonicalized", "json/non-finite");
261
+ }
262
+ return JSON.stringify(v);
263
+ }
264
+ if (typeof v === "string") return JSON.stringify(v);
265
+ if (Array.isArray(v)) return "[" + v.map(ser).join(",") + "]";
266
+ if (typeof v === "object") {
267
+ var keys = Object.keys(v).filter(function (k) { return !POISONED_KEYS.has(k); }).sort();
268
+ var pairs = keys.map(function (k) { return JSON.stringify(k) + ":" + ser(v[k]); });
269
+ return "{" + pairs.join(",") + "}";
270
+ }
271
+ throw new SafeJsonError("cannot canonicalize value of type " + typeof v, "json/uncanonical");
272
+ }
273
+
274
+ return ser(value);
275
+ }
276
+
277
+ // ---- format registry ----
278
+
279
+ // Anchored and bounded — nothing here is ReDoS-prone.
280
+ var formats = {
281
+ // Structural-only email check (no RFC 5322 attempt). Keeps complexity O(n).
282
+ // Length cap prevents pathological backtracking against long inputs.
283
+ email: function (v) {
284
+ return typeof v === "string" && v.length <= 254 &&
285
+ /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v);
286
+ },
287
+ // URL must parse via WHATWG URL and use http(s)/ws(s) — adjust per app
288
+ url: function (v) {
289
+ if (typeof v !== "string") return false;
290
+ try {
291
+ var u = safeUrl.parse(v, { allowedProtocols: ["http:", "https:", "ws:", "wss:"] });
292
+ return !!u;
293
+ } catch (_e) { return false; }
294
+ },
295
+ uuid: function (v) {
296
+ return typeof v === "string" &&
297
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(v);
298
+ },
299
+ // Crockford base32, 26 chars, must start with [0-7] (timestamp range)
300
+ ulid: function (v) {
301
+ return typeof v === "string" && /^[0-7][0-9A-HJKMNP-TV-Z]{25}$/.test(v);
302
+ },
303
+ "iso8601-date": function (v) {
304
+ if (typeof v !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(v)) return false;
305
+ var d = new Date(v);
306
+ return !isNaN(d.getTime()) && d.toISOString().slice(0, 10) === v;
307
+ },
308
+ "iso8601-datetime": function (v) {
309
+ if (typeof v !== "string") return false;
310
+ var d = new Date(v);
311
+ return !isNaN(d.getTime()) &&
312
+ d.toISOString().replace(time.ISO_MS_RE, "Z") === v.replace(time.ISO_MS_RE, "Z");
313
+ },
314
+ ipv4: function (v) {
315
+ if (typeof v !== "string") return false;
316
+ var parts = v.split(".");
317
+ if (parts.length !== 4) return false;
318
+ for (var i = 0; i < 4; i++) {
319
+ if (!/^\d{1,3}$/.test(parts[i])) return false;
320
+ var n = Number(parts[i]);
321
+ if (n < 0 || n > 255) return false;
322
+ if (parts[i] !== String(n)) return false; // no leading zeros
323
+ }
324
+ return true;
325
+ },
326
+ // RFC 4291 / RFC 5952 IPv6 — accepts all common forms:
327
+ // - Full 8 groups: 2001:0db8:85a3:0000:0000:8a2e:0370:7334
328
+ // - Compressed: 2001:db8::1, ::1, ::, fe80::abcd
329
+ // - IPv4-mapped: ::ffff:192.168.1.1
330
+ // - Mixed case: 2001:DB8::1
331
+ // Rejects: multiple ::, > 8 groups, non-hex chars, groups > 4 hex digits,
332
+ // zone IDs (%eth0 etc — not appropriate for portable data).
333
+ ipv6: function (v) {
334
+ if (typeof v !== "string" || v.length === 0 || v.length > 45) return false;
335
+ if (v.indexOf("%") !== -1) return false; // zone IDs not allowed
336
+ if (v.indexOf(":::") !== -1) return false;
337
+
338
+ var doubleColon = v.indexOf("::");
339
+ var hasDouble = doubleColon !== -1;
340
+ if (hasDouble && v.indexOf("::", doubleColon + 2) !== -1) return false;
341
+
342
+ var leftParts, rightParts;
343
+ if (hasDouble) {
344
+ var left = v.slice(0, doubleColon);
345
+ var right = v.slice(doubleColon + 2);
346
+ leftParts = left ? left.split(":") : [];
347
+ rightParts = right ? right.split(":") : [];
348
+ } else {
349
+ leftParts = v.split(":");
350
+ rightParts = [];
351
+ }
352
+
353
+ // IPv4-mapped suffix (::ffff:192.0.2.1, 2001:db8::192.0.2.1, etc.)
354
+ var tail = hasDouble ? rightParts : leftParts;
355
+ if (tail.length > 0 && tail[tail.length - 1].indexOf(".") !== -1) {
356
+ if (!formats.ipv4(tail[tail.length - 1])) return false;
357
+ tail.pop();
358
+ // IPv4 is 32 bits = 2 IPv6 groups; insert two synthetic groups
359
+ tail.push("0", "0");
360
+ }
361
+
362
+ var totalParts = leftParts.length + rightParts.length;
363
+ if (hasDouble) {
364
+ // Compressed form must replace AT LEAST ONE missing group (otherwise
365
+ // it would be a redundant ::), so total < IPV6_HEXTET_COUNT is required.
366
+ if (totalParts >= IPV6_HEXTET_COUNT) return false;
367
+ } else {
368
+ if (totalParts !== IPV6_HEXTET_COUNT) return false;
369
+ }
370
+
371
+ var all = leftParts.concat(rightParts);
372
+ for (var i = 0; i < all.length; i++) {
373
+ if (!/^[0-9a-fA-F]{1,4}$/.test(all[i])) return false;
374
+ }
375
+ return true;
376
+ },
377
+ ip: function (v) { return formats.ipv4(v) || formats.ipv6(v); },
378
+ hex: function (v) { return safeBuffer.isHex(v); },
379
+ // Generic non-empty token: alphanumeric + a few safe punctuation
380
+ slug: function (v) { return typeof v === "string" && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(v); },
381
+ };
382
+
383
+ function registerFormat(name, validator) {
384
+ if (typeof name !== "string" || !/^[a-z][a-z0-9-]*$/.test(name)) {
385
+ throw new SafeJsonError("format name must match [a-z][a-z0-9-]*: " + name, "json/bad-format-name");
386
+ }
387
+ if (typeof validator !== "function") {
388
+ throw new SafeJsonError("format validator must be a function", "json/bad-format-validator");
389
+ }
390
+ formats[name] = validator;
391
+ }
392
+
393
+ // ---- validate ----
394
+
395
+ function validate(value, schema, opts) {
396
+ opts = opts || {};
397
+ if (!schema || typeof schema !== "object") {
398
+ throw new SafeJsonError("validate: schema must be an object", "json/bad-schema");
399
+ }
400
+
401
+ if (opts.collectErrors) {
402
+ var errors = [];
403
+ _validateNode(value, schema, "$", function (err) { errors.push(err); });
404
+ if (errors.length === 0) return { ok: true, value: value, errors: [] };
405
+ return { ok: false, value: value, errors: errors };
406
+ }
407
+ // Throw mode (default)
408
+ _validateNode(value, schema, "$", function (err) { throw err; });
409
+ return value;
410
+ }
411
+
412
+ // Core validation walker. Calls report(error) on every failure. In throw
413
+ // mode the report callback throws — control unwinds via the throw. In
414
+ // collect mode the report callback pushes; we use early-returns at fatal
415
+ // points (type mismatch on a node) to avoid noisy follow-on errors that
416
+ // would all be downstream of the same root cause.
417
+ function _validateNode(value, schema, path, report) {
418
+ // Type check — if it fails, the value-specific constraints below would
419
+ // produce noisy duplicate errors. Bail this node after reporting.
420
+ if (schema.type) {
421
+ if (schema.type === "integer") {
422
+ if (typeof value !== "number" || !Number.isInteger(value)) {
423
+ report(new SafeJsonError(path + ": expected integer, got " + _typeName(value), "json/validation", path));
424
+ return;
425
+ }
426
+ } else if (_typeName(value) !== schema.type) {
427
+ report(new SafeJsonError(path + ": expected " + schema.type + ", got " + _typeName(value), "json/validation", path));
428
+ return;
429
+ }
430
+ }
431
+
432
+ // Enum (independent of type)
433
+ if (Array.isArray(schema.enum)) {
434
+ if (schema.enum.indexOf(value) === -1) {
435
+ report(new SafeJsonError(
436
+ path + ": value not in enum (" + JSON.stringify(schema.enum) + ")",
437
+ "json/validation", path
438
+ ));
439
+ }
440
+ }
441
+
442
+ // String constraints
443
+ if (typeof value === "string") {
444
+ if (schema.minLength != null && value.length < schema.minLength) {
445
+ report(new SafeJsonError(path + ": string length " + value.length + " < minLength " + schema.minLength, "json/validation", path));
446
+ }
447
+ if (schema.maxLength != null && value.length > schema.maxLength) {
448
+ report(new SafeJsonError(path + ": string length " + value.length + " > maxLength " + schema.maxLength, "json/validation", path));
449
+ }
450
+ if (schema.pattern) {
451
+ var re = schema.pattern instanceof RegExp ? schema.pattern : new RegExp(schema.pattern);
452
+ if (!re.test(value)) {
453
+ report(new SafeJsonError(path + ": does not match pattern", "json/validation", path));
454
+ }
455
+ }
456
+ if (schema.format) {
457
+ var f = formats[schema.format];
458
+ if (!f) {
459
+ report(new SafeJsonError(path + ": unknown format '" + schema.format + "'", "json/unknown-format", path));
460
+ } else if (!f(value)) {
461
+ report(new SafeJsonError(path + ": does not match format '" + schema.format + "'", "json/validation", path));
462
+ }
463
+ }
464
+ }
465
+
466
+ // Number constraints
467
+ if (typeof value === "number") {
468
+ if (schema.minimum != null && value < schema.minimum) {
469
+ report(new SafeJsonError(path + ": " + value + " < minimum " + schema.minimum, "json/validation", path));
470
+ }
471
+ if (schema.exclusiveMinimum != null && value <= schema.exclusiveMinimum) {
472
+ report(new SafeJsonError(path + ": " + value + " <= exclusiveMinimum " + schema.exclusiveMinimum, "json/validation", path));
473
+ }
474
+ if (schema.maximum != null && value > schema.maximum) {
475
+ report(new SafeJsonError(path + ": " + value + " > maximum " + schema.maximum, "json/validation", path));
476
+ }
477
+ if (schema.exclusiveMaximum != null && value >= schema.exclusiveMaximum) {
478
+ report(new SafeJsonError(path + ": " + value + " >= exclusiveMaximum " + schema.exclusiveMaximum, "json/validation", path));
479
+ }
480
+ }
481
+
482
+ // Array constraints
483
+ if (Array.isArray(value)) {
484
+ if (schema.minItems != null && value.length < schema.minItems) {
485
+ report(new SafeJsonError(path + ": array length " + value.length + " < minItems " + schema.minItems, "json/validation", path));
486
+ }
487
+ if (schema.maxItems != null && value.length > schema.maxItems) {
488
+ report(new SafeJsonError(path + ": array length " + value.length + " > maxItems " + schema.maxItems, "json/validation", path));
489
+ }
490
+ if (schema.items) {
491
+ for (var i = 0; i < value.length; i++) {
492
+ _validateNode(value[i], schema.items, path + "[" + i + "]", report);
493
+ }
494
+ }
495
+ }
496
+
497
+ // Object constraints
498
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) {
499
+ if (Array.isArray(schema.required)) {
500
+ for (var rk = 0; rk < schema.required.length; rk++) {
501
+ if (!Object.prototype.hasOwnProperty.call(value, schema.required[rk])) {
502
+ report(new SafeJsonError(path + ": missing required key '" + schema.required[rk] + "'", "json/validation", path));
503
+ }
504
+ }
505
+ }
506
+ var allowAdditional = schema.additionalProperties !== false;
507
+ if (schema.properties) {
508
+ for (var k in value) {
509
+ if (!Object.prototype.hasOwnProperty.call(value, k)) continue;
510
+ if (Object.prototype.hasOwnProperty.call(schema.properties, k)) {
511
+ _validateNode(value[k], schema.properties[k], path + "." + k, report);
512
+ } else if (!allowAdditional) {
513
+ report(new SafeJsonError(path + ": unknown key '" + k + "'", "json/validation", path + "." + k));
514
+ }
515
+ }
516
+ }
517
+ }
518
+ }
519
+
520
+ // ---- helpers ----
521
+
522
+ function _capInt(value, defaultValue, ceiling) {
523
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return defaultValue;
524
+ return Math.min(Math.floor(value), ceiling);
525
+ }
526
+
527
+ module.exports = {
528
+ parse: parse,
529
+ parseOrDefault: parseOrDefault,
530
+ stringify: stringify,
531
+ canonical: canonical,
532
+ validate: validate,
533
+ registerFormat: registerFormat,
534
+ formats: formats,
535
+ SafeJsonError: SafeJsonError,
536
+ DEFAULT_MAX_BYTES: DEFAULT_MAX_BYTES,
537
+ DEFAULT_MAX_DEPTH: DEFAULT_MAX_DEPTH,
538
+ ABSOLUTE_MAX_BYTES: ABSOLUTE_MAX_BYTES,
539
+ ABSOLUTE_MAX_DEPTH: ABSOLUTE_MAX_DEPTH,
540
+ POISONED_KEYS: Array.from(POISONED_KEYS),
541
+ };