@blamejs/core 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/CHANGELOG.md +230 -0
  2. package/LICENSE +201 -0
  3. package/LTS-CALENDAR.md +29 -0
  4. package/MIGRATING.md +7 -0
  5. package/NOTICE +59 -0
  6. package/README.md +100 -0
  7. package/bin/blamejs.js +13 -0
  8. package/index.js +253 -0
  9. package/lib/api-key.js +705 -0
  10. package/lib/api-snapshot.js +335 -0
  11. package/lib/app-shutdown.js +381 -0
  12. package/lib/app.js +364 -0
  13. package/lib/atomic-file.js +525 -0
  14. package/lib/audit-chain.js +168 -0
  15. package/lib/audit-sign.js +319 -0
  16. package/lib/audit-tools.js +682 -0
  17. package/lib/audit.js +753 -0
  18. package/lib/auth/jwt.js +280 -0
  19. package/lib/auth/oauth.js +691 -0
  20. package/lib/auth/passkey.js +185 -0
  21. package/lib/auth/password.js +139 -0
  22. package/lib/auth/totp.js +17 -0
  23. package/lib/auth-header.js +81 -0
  24. package/lib/backup/bundle.js +219 -0
  25. package/lib/backup/crypto.js +174 -0
  26. package/lib/backup/index.js +490 -0
  27. package/lib/backup/manifest.js +275 -0
  28. package/lib/bundler.js +295 -0
  29. package/lib/cache.js +819 -0
  30. package/lib/chain-writer.js +234 -0
  31. package/lib/cli-helpers.js +201 -0
  32. package/lib/cli.js +1377 -0
  33. package/lib/cluster-provider-db.js +245 -0
  34. package/lib/cluster-storage.js +166 -0
  35. package/lib/cluster.js +691 -0
  36. package/lib/consent.js +222 -0
  37. package/lib/constants.js +186 -0
  38. package/lib/cookies.js +293 -0
  39. package/lib/credential-hash.js +303 -0
  40. package/lib/crypto-field.js +159 -0
  41. package/lib/crypto.js +250 -0
  42. package/lib/db-query.js +297 -0
  43. package/lib/db-schema.js +250 -0
  44. package/lib/db.js +1054 -0
  45. package/lib/deprecate.js +226 -0
  46. package/lib/dev.js +324 -0
  47. package/lib/error-page.js +424 -0
  48. package/lib/events.js +135 -0
  49. package/lib/external-db.js +422 -0
  50. package/lib/forms.js +378 -0
  51. package/lib/framework-error.js +189 -0
  52. package/lib/framework-schema.js +604 -0
  53. package/lib/handlers.js +350 -0
  54. package/lib/html-balance.js +227 -0
  55. package/lib/http-client.js +615 -0
  56. package/lib/i18n.js +780 -0
  57. package/lib/jobs.js +181 -0
  58. package/lib/lazy-require.js +48 -0
  59. package/lib/log-stream-local.js +137 -0
  60. package/lib/log-stream-webhook.js +170 -0
  61. package/lib/log-stream.js +211 -0
  62. package/lib/log.js +355 -0
  63. package/lib/mail-bounce.js +507 -0
  64. package/lib/mail.js +701 -0
  65. package/lib/metrics.js +647 -0
  66. package/lib/middleware/api-encrypt.js +553 -0
  67. package/lib/middleware/attach-user.js +156 -0
  68. package/lib/middleware/body-parser.js +883 -0
  69. package/lib/middleware/bot-guard.js +148 -0
  70. package/lib/middleware/compression.js +436 -0
  71. package/lib/middleware/cors.js +236 -0
  72. package/lib/middleware/csp-nonce.js +332 -0
  73. package/lib/middleware/csrf-protect.js +275 -0
  74. package/lib/middleware/error-handler.js +46 -0
  75. package/lib/middleware/health.js +358 -0
  76. package/lib/middleware/index.js +52 -0
  77. package/lib/middleware/rate-limit.js +319 -0
  78. package/lib/middleware/request-id.js +53 -0
  79. package/lib/middleware/require-auth.js +95 -0
  80. package/lib/middleware/security-headers.js +91 -0
  81. package/lib/migrations.js +353 -0
  82. package/lib/mtls-ca.js +333 -0
  83. package/lib/mtls-engine-default.js +285 -0
  84. package/lib/nonce-store.js +177 -0
  85. package/lib/notify.js +643 -0
  86. package/lib/ntp-check.js +178 -0
  87. package/lib/object-store/azure-blob.js +467 -0
  88. package/lib/object-store/gcs.js +469 -0
  89. package/lib/object-store/http-put.js +153 -0
  90. package/lib/object-store/index.js +140 -0
  91. package/lib/object-store/local.js +163 -0
  92. package/lib/object-store/retry.js +15 -0
  93. package/lib/object-store/sigv4.js +535 -0
  94. package/lib/observability.js +114 -0
  95. package/lib/pagination.js +371 -0
  96. package/lib/parsers/index.js +64 -0
  97. package/lib/parsers/safe-csv.js +224 -0
  98. package/lib/parsers/safe-env.js +614 -0
  99. package/lib/parsers/safe-toml.js +745 -0
  100. package/lib/parsers/safe-xml.js +379 -0
  101. package/lib/parsers/safe-yaml.js +977 -0
  102. package/lib/permissions.js +430 -0
  103. package/lib/pqc-agent.js +85 -0
  104. package/lib/pqc-gate.js +266 -0
  105. package/lib/protocol-dispatcher.js +144 -0
  106. package/lib/queue-local.js +327 -0
  107. package/lib/queue.js +430 -0
  108. package/lib/redact.js +192 -0
  109. package/lib/render.js +193 -0
  110. package/lib/request-helpers.js +178 -0
  111. package/lib/restore-bundle.js +239 -0
  112. package/lib/restore-rollback.js +254 -0
  113. package/lib/restore.js +301 -0
  114. package/lib/retry.js +329 -0
  115. package/lib/router.js +437 -0
  116. package/lib/safe-async.js +520 -0
  117. package/lib/safe-buffer.js +162 -0
  118. package/lib/safe-json.js +532 -0
  119. package/lib/safe-schema.js +1176 -0
  120. package/lib/safe-sql.js +157 -0
  121. package/lib/safe-url.js +109 -0
  122. package/lib/scheduler.js +680 -0
  123. package/lib/seeders.js +622 -0
  124. package/lib/session.js +304 -0
  125. package/lib/slug.js +243 -0
  126. package/lib/static.js +268 -0
  127. package/lib/storage.js +470 -0
  128. package/lib/subject.js +281 -0
  129. package/lib/template.js +781 -0
  130. package/lib/testing.js +621 -0
  131. package/lib/totp.js +285 -0
  132. package/lib/tracing.js +484 -0
  133. package/lib/validate-opts.js +56 -0
  134. package/lib/vault/index.js +299 -0
  135. package/lib/vault/passphrase-ops.js +311 -0
  136. package/lib/vault/passphrase-source.js +198 -0
  137. package/lib/vault/rotate.js +761 -0
  138. package/lib/vault/wrap.js +289 -0
  139. package/lib/vendor/MANIFEST.json +84 -0
  140. package/lib/vendor/argon2/argon2.cjs +466 -0
  141. package/lib/vendor/argon2/argon2.d.cts +62 -0
  142. package/lib/vendor/argon2/package.json +1 -0
  143. package/lib/vendor/argon2/prebuilds/darwin-arm64/argon2.armv8.glibc.node +0 -0
  144. package/lib/vendor/argon2/prebuilds/darwin-x64/argon2.glibc.node +0 -0
  145. package/lib/vendor/argon2/prebuilds/freebsd-arm64/argon2.armv8.glibc.node +0 -0
  146. package/lib/vendor/argon2/prebuilds/freebsd-x64/argon2.glibc.node +0 -0
  147. package/lib/vendor/argon2/prebuilds/linux-arm/argon2.armv7.glibc.node +0 -0
  148. package/lib/vendor/argon2/prebuilds/linux-arm/argon2.armv7.musl.node +0 -0
  149. package/lib/vendor/argon2/prebuilds/linux-arm64/argon2.armv8.glibc.node +0 -0
  150. package/lib/vendor/argon2/prebuilds/linux-arm64/argon2.armv8.musl.node +0 -0
  151. package/lib/vendor/argon2/prebuilds/linux-x64/argon2.glibc.node +0 -0
  152. package/lib/vendor/argon2/prebuilds/linux-x64/argon2.musl.node +0 -0
  153. package/lib/vendor/argon2/prebuilds/win32-x64/argon2.glibc.node +0 -0
  154. package/lib/vendor/noble-ciphers.cjs +9 -0
  155. package/lib/vendor/pki.cjs +181 -0
  156. package/lib/vendor/simplewebauthn-server.cjs +328 -0
  157. package/lib/webhook.js +632 -0
  158. package/lib/websocket-channels.js +413 -0
  159. package/lib/websocket.js +833 -0
  160. package/package.json +39 -0
@@ -0,0 +1,532 @@
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 { FrameworkError } = require("./framework-error");
68
+
69
+ class SafeJsonError extends FrameworkError {
70
+ constructor(message, code, path) {
71
+ super(message);
72
+ this.name = "SafeJsonError";
73
+ this.code = code || "json/invalid";
74
+ this.path = path || null;
75
+ this.isSafeJsonError = true;
76
+ }
77
+ }
78
+
79
+ var ABSOLUTE_MAX_BYTES = C.BYTES.mib(64);
80
+ var ABSOLUTE_MAX_DEPTH = 1000;
81
+ var DEFAULT_MAX_BYTES = C.BYTES.mib(1);
82
+ var DEFAULT_MAX_DEPTH = 100;
83
+
84
+ var POISONED_KEYS = new Set(["__proto__", "constructor", "prototype"]);
85
+
86
+ // ---- parse ----
87
+
88
+ function parse(input, opts) {
89
+ opts = opts || {};
90
+
91
+ var maxBytes = _capInt(opts.maxBytes, DEFAULT_MAX_BYTES, ABSOLUTE_MAX_BYTES);
92
+ input = safeBuffer.normalizeText(input, {
93
+ maxBytes: maxBytes,
94
+ errorClass: SafeJsonError,
95
+ typeCode: "json/wrong-input-type",
96
+ sizeCode: "json/too-large",
97
+ typeMessage: "input must be a string, Buffer, or Uint8Array",
98
+ });
99
+
100
+ var maxDepth = _capInt(opts.maxDepth, DEFAULT_MAX_DEPTH, ABSOLUTE_MAX_DEPTH);
101
+ var allowProto = !!opts.allowProto;
102
+
103
+ var parsed;
104
+ try {
105
+ parsed = JSON.parse(input, allowProto ? undefined : _stripProtoKeys);
106
+ } catch (e) {
107
+ throw new SafeJsonError("invalid JSON: " + e.message, "json/syntax");
108
+ }
109
+
110
+ _walkAndCheck(parsed, 0, maxDepth, allowProto);
111
+
112
+ // Optional schema validation (preferred over expectType / requiredKeys)
113
+ if (opts.schema) {
114
+ if (opts.collectErrors) {
115
+ var result = validate(parsed, opts.schema, { collectErrors: true });
116
+ // Always return the same shape parse promised: a value or an
117
+ // { ok, value, errors[] } object. Caller signals which they want
118
+ // via opts.collectErrors.
119
+ return result;
120
+ }
121
+ validate(parsed, opts.schema);
122
+ return parsed;
123
+ }
124
+
125
+ // Legacy lightweight type assertion (for callers that don't supply a schema)
126
+ if (opts.expectType) {
127
+ var actual = _typeName(parsed);
128
+ if (actual !== opts.expectType) {
129
+ throw new SafeJsonError("expected " + opts.expectType + " at root, got " + actual, "json/type-mismatch");
130
+ }
131
+ }
132
+ if (Array.isArray(opts.requiredKeys) && parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
133
+ for (var i = 0; i < opts.requiredKeys.length; i++) {
134
+ if (!Object.prototype.hasOwnProperty.call(parsed, opts.requiredKeys[i])) {
135
+ throw new SafeJsonError("missing required key '" + opts.requiredKeys[i] + "'", "json/missing-key");
136
+ }
137
+ }
138
+ }
139
+
140
+ return parsed;
141
+ }
142
+
143
+ function parseOrDefault(input, fallback, opts) {
144
+ try { return parse(input, opts); }
145
+ catch (_e) { return fallback; }
146
+ }
147
+
148
+ function _stripProtoKeys(key, value) {
149
+ if (POISONED_KEYS.has(key)) return undefined;
150
+ return value;
151
+ }
152
+
153
+ function _walkAndCheck(value, depth, maxDepth, allowProto) {
154
+ if (depth > maxDepth) {
155
+ throw new SafeJsonError("nesting exceeds maxDepth (" + maxDepth + ")", "json/too-deep");
156
+ }
157
+ if (value === null || typeof value !== "object") return;
158
+ if (Array.isArray(value)) {
159
+ for (var i = 0; i < value.length; i++) _walkAndCheck(value[i], depth + 1, maxDepth, allowProto);
160
+ return;
161
+ }
162
+ if (!allowProto) {
163
+ POISONED_KEYS.forEach(function (k) {
164
+ if (Object.prototype.hasOwnProperty.call(value, k)) delete value[k];
165
+ });
166
+ }
167
+ for (var k in value) {
168
+ if (Object.prototype.hasOwnProperty.call(value, k)) {
169
+ _walkAndCheck(value[k], depth + 1, maxDepth, allowProto);
170
+ }
171
+ }
172
+ }
173
+
174
+ function _typeName(v) {
175
+ if (v === null) return "null";
176
+ if (Array.isArray(v)) return "array";
177
+ return typeof v;
178
+ }
179
+
180
+ // ---- stringify ----
181
+
182
+ function stringify(value, opts) {
183
+ opts = opts || {};
184
+ var onCircular = opts.onCircular || "throw";
185
+ var replacement = opts.circularReplacement !== undefined ? opts.circularReplacement : "[Circular]";
186
+ var allowProto = !!opts.allowProto;
187
+ var indent = opts.indent || 0;
188
+
189
+ // For "replace" mode, we pre-clean the tree manually because JSON.stringify
190
+ // will throw on cycles before the replacer can rewrite them. The cleaning
191
+ // walk uses stack-discipline (add on descend, remove on ascend) so SHARED
192
+ // subtrees aren't falsely flagged as circular.
193
+ var input = value;
194
+ if (onCircular === "replace") {
195
+ input = _cleanCycles(value, replacement, allowProto);
196
+ }
197
+
198
+ function replacer(key, val) {
199
+ if (!allowProto && POISONED_KEYS.has(key)) return undefined;
200
+ return val;
201
+ }
202
+
203
+ try {
204
+ return JSON.stringify(input, replacer, indent);
205
+ } catch (e) {
206
+ if (e && e.isSafeJsonError) throw e;
207
+ // JSON.stringify throws TypeError "Converting circular structure to JSON"
208
+ // when it hits a cycle in throw mode.
209
+ if (e instanceof TypeError && /circular/i.test(e.message)) {
210
+ throw new SafeJsonError("circular reference: " + e.message, "json/circular");
211
+ }
212
+ throw new SafeJsonError("stringify failed: " + e.message, "json/stringify");
213
+ }
214
+ }
215
+
216
+ // Walk the value, substituting any references that would create a cycle
217
+ // with `replacement`. Uses an active-stack Set so SHARED non-circular
218
+ // subtrees are preserved (only true cycles are replaced).
219
+ function _cleanCycles(value, replacement, allowProto) {
220
+ var stack = new Set();
221
+
222
+ function walk(v) {
223
+ if (v === null || typeof v !== "object") return v;
224
+ if (stack.has(v)) return replacement;
225
+ stack.add(v);
226
+ var out;
227
+ if (Array.isArray(v)) {
228
+ out = new Array(v.length);
229
+ for (var i = 0; i < v.length; i++) out[i] = walk(v[i]);
230
+ } else {
231
+ out = {};
232
+ for (var k in v) {
233
+ if (!Object.prototype.hasOwnProperty.call(v, k)) continue;
234
+ if (!allowProto && POISONED_KEYS.has(k)) continue;
235
+ out[k] = walk(v[k]);
236
+ }
237
+ }
238
+ stack.delete(v);
239
+ return out;
240
+ }
241
+
242
+ return walk(value);
243
+ }
244
+
245
+ // ---- canonical ----
246
+
247
+ function canonical(value, _opts) {
248
+ if (typeof value === "undefined") return "null";
249
+
250
+ function ser(v) {
251
+ if (v === null || typeof v === "boolean") return JSON.stringify(v);
252
+ if (typeof v === "number") {
253
+ if (!Number.isFinite(v)) {
254
+ throw new SafeJsonError("non-finite number cannot be canonicalized", "json/non-finite");
255
+ }
256
+ return JSON.stringify(v);
257
+ }
258
+ if (typeof v === "string") return JSON.stringify(v);
259
+ if (Array.isArray(v)) return "[" + v.map(ser).join(",") + "]";
260
+ if (typeof v === "object") {
261
+ var keys = Object.keys(v).filter(function (k) { return !POISONED_KEYS.has(k); }).sort();
262
+ var pairs = keys.map(function (k) { return JSON.stringify(k) + ":" + ser(v[k]); });
263
+ return "{" + pairs.join(",") + "}";
264
+ }
265
+ throw new SafeJsonError("cannot canonicalize value of type " + typeof v, "json/uncanonical");
266
+ }
267
+
268
+ return ser(value);
269
+ }
270
+
271
+ // ---- format registry ----
272
+
273
+ // Anchored and bounded — nothing here is ReDoS-prone.
274
+ var formats = {
275
+ // Structural-only email check (no RFC 5322 attempt). Keeps complexity O(n).
276
+ // Length cap prevents pathological backtracking against long inputs.
277
+ email: function (v) {
278
+ return typeof v === "string" && v.length <= 254 &&
279
+ /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v);
280
+ },
281
+ // URL must parse via WHATWG URL and use http(s)/ws(s)/file/data — adjust per app
282
+ url: function (v) {
283
+ if (typeof v !== "string") return false;
284
+ try { var u = new URL(v); return ["http:", "https:", "ws:", "wss:"].indexOf(u.protocol) !== -1; }
285
+ catch (_e) { return false; }
286
+ },
287
+ uuid: function (v) {
288
+ return typeof v === "string" &&
289
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(v);
290
+ },
291
+ // Crockford base32, 26 chars, must start with [0-7] (timestamp range)
292
+ ulid: function (v) {
293
+ return typeof v === "string" && /^[0-7][0-9A-HJKMNP-TV-Z]{25}$/.test(v);
294
+ },
295
+ "iso8601-date": function (v) {
296
+ if (typeof v !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(v)) return false;
297
+ var d = new Date(v);
298
+ return !isNaN(d.getTime()) && d.toISOString().slice(0, 10) === v;
299
+ },
300
+ "iso8601-datetime": function (v) {
301
+ if (typeof v !== "string") return false;
302
+ var d = new Date(v);
303
+ return !isNaN(d.getTime()) && d.toISOString().replace(/\.\d{3}Z$/, "Z") === v.replace(/\.\d{3}Z$/, "Z");
304
+ },
305
+ ipv4: function (v) {
306
+ if (typeof v !== "string") return false;
307
+ var parts = v.split(".");
308
+ if (parts.length !== 4) return false;
309
+ for (var i = 0; i < 4; i++) {
310
+ if (!/^\d{1,3}$/.test(parts[i])) return false;
311
+ var n = Number(parts[i]);
312
+ if (n < 0 || n > 255) return false;
313
+ if (parts[i] !== String(n)) return false; // no leading zeros
314
+ }
315
+ return true;
316
+ },
317
+ // RFC 4291 / RFC 5952 IPv6 — accepts all common forms:
318
+ // - Full 8 groups: 2001:0db8:85a3:0000:0000:8a2e:0370:7334
319
+ // - Compressed: 2001:db8::1, ::1, ::, fe80::abcd
320
+ // - IPv4-mapped: ::ffff:192.168.1.1
321
+ // - Mixed case: 2001:DB8::1
322
+ // Rejects: multiple ::, > 8 groups, non-hex chars, groups > 4 hex digits,
323
+ // zone IDs (%eth0 etc — not appropriate for portable data).
324
+ ipv6: function (v) {
325
+ if (typeof v !== "string" || v.length === 0 || v.length > 45) return false;
326
+ if (v.indexOf("%") !== -1) return false; // zone IDs not allowed
327
+ if (v.indexOf(":::") !== -1) return false;
328
+
329
+ var doubleColon = v.indexOf("::");
330
+ var hasDouble = doubleColon !== -1;
331
+ if (hasDouble && v.indexOf("::", doubleColon + 2) !== -1) return false;
332
+
333
+ var leftParts, rightParts;
334
+ if (hasDouble) {
335
+ var left = v.slice(0, doubleColon);
336
+ var right = v.slice(doubleColon + 2);
337
+ leftParts = left ? left.split(":") : [];
338
+ rightParts = right ? right.split(":") : [];
339
+ } else {
340
+ leftParts = v.split(":");
341
+ rightParts = [];
342
+ }
343
+
344
+ // IPv4-mapped suffix (::ffff:192.0.2.1, 2001:db8::192.0.2.1, etc.)
345
+ var tail = hasDouble ? rightParts : leftParts;
346
+ if (tail.length > 0 && tail[tail.length - 1].indexOf(".") !== -1) {
347
+ if (!formats.ipv4(tail[tail.length - 1])) return false;
348
+ tail.pop();
349
+ // IPv4 is 32 bits = 2 IPv6 groups; insert two synthetic groups
350
+ tail.push("0", "0");
351
+ }
352
+
353
+ var totalParts = leftParts.length + rightParts.length;
354
+ if (hasDouble) {
355
+ // Compressed form must replace AT LEAST ONE missing group (otherwise
356
+ // it would be a redundant ::), so total < 8 is required.
357
+ if (totalParts >= 8) return false;
358
+ } else {
359
+ if (totalParts !== 8) return false;
360
+ }
361
+
362
+ var all = leftParts.concat(rightParts);
363
+ for (var i = 0; i < all.length; i++) {
364
+ if (!/^[0-9a-fA-F]{1,4}$/.test(all[i])) return false;
365
+ }
366
+ return true;
367
+ },
368
+ ip: function (v) { return formats.ipv4(v) || formats.ipv6(v); },
369
+ hex: function (v) { return typeof v === "string" && /^[0-9a-fA-F]+$/.test(v); },
370
+ // Generic non-empty token: alphanumeric + a few safe punctuation
371
+ slug: function (v) { return typeof v === "string" && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(v); },
372
+ };
373
+
374
+ function registerFormat(name, validator) {
375
+ if (typeof name !== "string" || !/^[a-z][a-z0-9-]*$/.test(name)) {
376
+ throw new SafeJsonError("format name must match [a-z][a-z0-9-]*: " + name, "json/bad-format-name");
377
+ }
378
+ if (typeof validator !== "function") {
379
+ throw new SafeJsonError("format validator must be a function", "json/bad-format-validator");
380
+ }
381
+ formats[name] = validator;
382
+ }
383
+
384
+ // ---- validate ----
385
+
386
+ function validate(value, schema, opts) {
387
+ opts = opts || {};
388
+ if (!schema || typeof schema !== "object") {
389
+ throw new SafeJsonError("validate: schema must be an object", "json/bad-schema");
390
+ }
391
+
392
+ if (opts.collectErrors) {
393
+ var errors = [];
394
+ _validateNode(value, schema, "$", function (err) { errors.push(err); });
395
+ if (errors.length === 0) return { ok: true, value: value, errors: [] };
396
+ return { ok: false, value: value, errors: errors };
397
+ }
398
+ // Throw mode (default)
399
+ _validateNode(value, schema, "$", function (err) { throw err; });
400
+ return value;
401
+ }
402
+
403
+ // Core validation walker. Calls report(error) on every failure. In throw
404
+ // mode the report callback throws — control unwinds via the throw. In
405
+ // collect mode the report callback pushes; we use early-returns at fatal
406
+ // points (type mismatch on a node) to avoid noisy follow-on errors that
407
+ // would all be downstream of the same root cause.
408
+ function _validateNode(value, schema, path, report) {
409
+ // Type check — if it fails, the value-specific constraints below would
410
+ // produce noisy duplicate errors. Bail this node after reporting.
411
+ if (schema.type) {
412
+ if (schema.type === "integer") {
413
+ if (typeof value !== "number" || !Number.isInteger(value)) {
414
+ report(new SafeJsonError(path + ": expected integer, got " + _typeName(value), "json/validation", path));
415
+ return;
416
+ }
417
+ } else if (_typeName(value) !== schema.type) {
418
+ report(new SafeJsonError(path + ": expected " + schema.type + ", got " + _typeName(value), "json/validation", path));
419
+ return;
420
+ }
421
+ }
422
+
423
+ // Enum (independent of type)
424
+ if (Array.isArray(schema.enum)) {
425
+ if (schema.enum.indexOf(value) === -1) {
426
+ report(new SafeJsonError(
427
+ path + ": value not in enum (" + JSON.stringify(schema.enum) + ")",
428
+ "json/validation", path
429
+ ));
430
+ }
431
+ }
432
+
433
+ // String constraints
434
+ if (typeof value === "string") {
435
+ if (schema.minLength != null && value.length < schema.minLength) {
436
+ report(new SafeJsonError(path + ": string length " + value.length + " < minLength " + schema.minLength, "json/validation", path));
437
+ }
438
+ if (schema.maxLength != null && value.length > schema.maxLength) {
439
+ report(new SafeJsonError(path + ": string length " + value.length + " > maxLength " + schema.maxLength, "json/validation", path));
440
+ }
441
+ if (schema.pattern) {
442
+ var re = schema.pattern instanceof RegExp ? schema.pattern : new RegExp(schema.pattern);
443
+ if (!re.test(value)) {
444
+ report(new SafeJsonError(path + ": does not match pattern", "json/validation", path));
445
+ }
446
+ }
447
+ if (schema.format) {
448
+ var f = formats[schema.format];
449
+ if (!f) {
450
+ report(new SafeJsonError(path + ": unknown format '" + schema.format + "'", "json/unknown-format", path));
451
+ } else if (!f(value)) {
452
+ report(new SafeJsonError(path + ": does not match format '" + schema.format + "'", "json/validation", path));
453
+ }
454
+ }
455
+ }
456
+
457
+ // Number constraints
458
+ if (typeof value === "number") {
459
+ if (schema.minimum != null && value < schema.minimum) {
460
+ report(new SafeJsonError(path + ": " + value + " < minimum " + schema.minimum, "json/validation", path));
461
+ }
462
+ if (schema.exclusiveMinimum != null && value <= schema.exclusiveMinimum) {
463
+ report(new SafeJsonError(path + ": " + value + " <= exclusiveMinimum " + schema.exclusiveMinimum, "json/validation", path));
464
+ }
465
+ if (schema.maximum != null && value > schema.maximum) {
466
+ report(new SafeJsonError(path + ": " + value + " > maximum " + schema.maximum, "json/validation", path));
467
+ }
468
+ if (schema.exclusiveMaximum != null && value >= schema.exclusiveMaximum) {
469
+ report(new SafeJsonError(path + ": " + value + " >= exclusiveMaximum " + schema.exclusiveMaximum, "json/validation", path));
470
+ }
471
+ }
472
+
473
+ // Array constraints
474
+ if (Array.isArray(value)) {
475
+ if (schema.minItems != null && value.length < schema.minItems) {
476
+ report(new SafeJsonError(path + ": array length " + value.length + " < minItems " + schema.minItems, "json/validation", path));
477
+ }
478
+ if (schema.maxItems != null && value.length > schema.maxItems) {
479
+ report(new SafeJsonError(path + ": array length " + value.length + " > maxItems " + schema.maxItems, "json/validation", path));
480
+ }
481
+ if (schema.items) {
482
+ for (var i = 0; i < value.length; i++) {
483
+ _validateNode(value[i], schema.items, path + "[" + i + "]", report);
484
+ }
485
+ }
486
+ }
487
+
488
+ // Object constraints
489
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) {
490
+ if (Array.isArray(schema.required)) {
491
+ for (var rk = 0; rk < schema.required.length; rk++) {
492
+ if (!Object.prototype.hasOwnProperty.call(value, schema.required[rk])) {
493
+ report(new SafeJsonError(path + ": missing required key '" + schema.required[rk] + "'", "json/validation", path));
494
+ }
495
+ }
496
+ }
497
+ var allowAdditional = schema.additionalProperties !== false;
498
+ if (schema.properties) {
499
+ for (var k in value) {
500
+ if (!Object.prototype.hasOwnProperty.call(value, k)) continue;
501
+ if (Object.prototype.hasOwnProperty.call(schema.properties, k)) {
502
+ _validateNode(value[k], schema.properties[k], path + "." + k, report);
503
+ } else if (!allowAdditional) {
504
+ report(new SafeJsonError(path + ": unknown key '" + k + "'", "json/validation", path + "." + k));
505
+ }
506
+ }
507
+ }
508
+ }
509
+ }
510
+
511
+ // ---- helpers ----
512
+
513
+ function _capInt(value, defaultValue, ceiling) {
514
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return defaultValue;
515
+ return Math.min(Math.floor(value), ceiling);
516
+ }
517
+
518
+ module.exports = {
519
+ parse: parse,
520
+ parseOrDefault: parseOrDefault,
521
+ stringify: stringify,
522
+ canonical: canonical,
523
+ validate: validate,
524
+ registerFormat: registerFormat,
525
+ formats: formats,
526
+ SafeJsonError: SafeJsonError,
527
+ DEFAULT_MAX_BYTES: DEFAULT_MAX_BYTES,
528
+ DEFAULT_MAX_DEPTH: DEFAULT_MAX_DEPTH,
529
+ ABSOLUTE_MAX_BYTES: ABSOLUTE_MAX_BYTES,
530
+ ABSOLUTE_MAX_DEPTH: ABSOLUTE_MAX_DEPTH,
531
+ POISONED_KEYS: Array.from(POISONED_KEYS),
532
+ };