@blamejs/core 0.7.4 → 0.7.19

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.
@@ -0,0 +1,405 @@
1
+ "use strict";
2
+ /**
3
+ * guard-xml — XML content-safety primitive (b.guardXml).
4
+ *
5
+ * Threat catalog grounded in current research (XXE remains active in
6
+ * 2025-2026 despite 20+ years of awareness):
7
+ * - CVE-2026-24400 AssertJ XXE via toXmlDocument default parser
8
+ * - CVE-2025-3225 sitemap parser XXE
9
+ * - CVE-2024-1455 LangChain XXE
10
+ * - CVE-2024-25062 libxml2 use-after-free with DTD + XInclude
11
+ * - CVE-2024-56171 libxml2 schema use-after-free
12
+ * - CVE-2025-24928 libxml2 stack overflow on DTD validation
13
+ * - CVE-2025-32415 libxml2 schema heap under-read
14
+ * - CVE-2025-27113 libxml2 NULL deref in pattern.c
15
+ * - CVE-2024-8176 libexpat stack overflow (recursive entity expansion)
16
+ *
17
+ * var rv = b.guardXml.validate(input, { profile: "strict" });
18
+ * var safe = b.guardXml.sanitize(input, { profile: "balanced" });
19
+ * var g = b.guardXml.gate({ profile: "strict" });
20
+ *
21
+ * Threat catalog covered:
22
+ *
23
+ * 1. DOCTYPE declarations — refuse unconditionally regardless of
24
+ * profile. Catches billion-laughs entity expansion + external
25
+ * entity loading (XXE) + SYSTEM identifier exfil.
26
+ * 2. <!ENTITY> declarations including parameter entities (% prefix).
27
+ * 3. External entities — file:// / http:// / SYSTEM identifiers in
28
+ * DOCTYPE subset.
29
+ * 4. XInclude — <xi:include href="..."/> remote inclusion.
30
+ * 5. xsi:schemaLocation / xsi:noNamespaceSchemaLocation — operator-
31
+ * controlled schema fetch.
32
+ * 6. Processing instructions — <?xml-stylesheet ...?> CSS injection
33
+ * vector.
34
+ * 7. CDATA sections — often used to hide payloads from naive
35
+ * scanners.
36
+ * 8. XML signature wrapping (xmldsig) — surface that requires
37
+ * careful operator handling; flagged as audit.
38
+ * 9. Bidi / null / control / zero-width chars in element text +
39
+ * attribute values.
40
+ * 10. Anti-DoS caps — total document size, max element count, max
41
+ * attribute count per element, max depth, max attribute value
42
+ * length.
43
+ */
44
+
45
+ var codepointClass = require("./codepoint-class");
46
+ var lazyRequire = require("./lazy-require");
47
+ var gateContract = require("./gate-contract");
48
+ var C = require("./constants");
49
+ var numericBounds = require("./numeric-bounds");
50
+ var { GuardXmlError } = require("./framework-error");
51
+
52
+ var observability = lazyRequire(function () { return require("./observability"); });
53
+ void observability;
54
+
55
+ var _err = GuardXmlError.factory;
56
+
57
+ // ---- Source-level threat detectors ----
58
+
59
+ var DOCTYPE_RE = /<!DOCTYPE\b/i;
60
+ var ENTITY_DECL_RE = /<!ENTITY\b/i;
61
+ var PARAM_ENTITY_RE = /<!ENTITY\s+%/i;
62
+ var EXTERNAL_ENTITY_RE = /\b(SYSTEM|PUBLIC)\s+["'](file|http|https|ftp|gopher|jar|netdoc):/i;
63
+ var XINCLUDE_RE = /<xi:include\b/i;
64
+ var SCHEMA_LOCATION_RE = /\bxsi:(noNamespace)?[Ss]chemaLocation\s*=/;
65
+ var PROCESSING_INSTR_RE = /<\?[A-Za-z][\w:-]*/;
66
+ var CDATA_RE = /<!\[CDATA\[/;
67
+ var XMLDSIG_RE = /<\w*:?Signature\b[^>]*xmldsig/i;
68
+
69
+ // ---- Profile presets ----
70
+
71
+ var PROFILES = Object.freeze({
72
+ "strict": {
73
+ doctypePolicy: "reject",
74
+ entityPolicy: "reject",
75
+ externalEntityPolicy: "reject",
76
+ xincludePolicy: "reject",
77
+ schemaLocationPolicy: "reject",
78
+ processingInstrPolicy: "reject",
79
+ cdataPolicy: "reject",
80
+ xmlDsigPolicy: "audit",
81
+ bidiPolicy: "reject",
82
+ controlPolicy: "reject",
83
+ nullBytePolicy: "reject",
84
+ zeroWidthPolicy: "reject",
85
+ maxBytes: C.BYTES.mib(2),
86
+ maxDepth: 64, // allow:raw-byte-literal — recursion depth, not byte size
87
+ maxElements: 8192, // allow:raw-byte-literal — element count cap, not byte size
88
+ maxAttrsPerElement: 64, // allow:raw-byte-literal — attr count, not byte size
89
+ maxAttrValueBytes: C.BYTES.kib(8),
90
+ },
91
+ "balanced": {
92
+ doctypePolicy: "reject", // DOCTYPE is XXE vector regardless
93
+ entityPolicy: "reject",
94
+ externalEntityPolicy: "reject",
95
+ xincludePolicy: "reject",
96
+ schemaLocationPolicy: "audit",
97
+ processingInstrPolicy: "audit",
98
+ cdataPolicy: "audit",
99
+ xmlDsigPolicy: "audit",
100
+ bidiPolicy: "strip",
101
+ controlPolicy: "strip",
102
+ nullBytePolicy: "strip",
103
+ zeroWidthPolicy: "strip",
104
+ maxBytes: C.BYTES.mib(8),
105
+ maxDepth: 256, // allow:raw-byte-literal — recursion depth, not byte size
106
+ maxElements: 65536, // allow:raw-byte-literal — element count cap, not byte size
107
+ maxAttrsPerElement: 128, // allow:raw-byte-literal — attr count, not byte size
108
+ maxAttrValueBytes: C.BYTES.kib(32),
109
+ },
110
+ "permissive": {
111
+ doctypePolicy: "reject", // billion-laughs class always
112
+ entityPolicy: "reject",
113
+ externalEntityPolicy: "reject",
114
+ xincludePolicy: "audit",
115
+ schemaLocationPolicy: "audit",
116
+ processingInstrPolicy: "audit",
117
+ cdataPolicy: "audit",
118
+ xmlDsigPolicy: "audit",
119
+ bidiPolicy: "audit",
120
+ controlPolicy: "strip",
121
+ nullBytePolicy: "reject",
122
+ zeroWidthPolicy: "strip",
123
+ maxBytes: C.BYTES.mib(64),
124
+ maxDepth: 1024, // allow:raw-byte-literal — recursion depth, not byte size
125
+ maxElements: 262144, // allow:raw-byte-literal — element count cap, not byte size
126
+ maxAttrsPerElement: 256, // allow:raw-byte-literal — attr count, not byte size
127
+ maxAttrValueBytes: C.BYTES.kib(64),
128
+ },
129
+ });
130
+
131
+ var DEFAULTS = Object.freeze(Object.assign({}, PROFILES["strict"], {
132
+ mode: "enforce",
133
+ maxRuntimeMs: C.TIME.seconds(10),
134
+ }));
135
+
136
+ var COMPLIANCE_POSTURES = Object.freeze({
137
+ "hipaa": Object.assign({}, PROFILES["strict"], {
138
+ forensicSnippetBytes: C.BYTES.bytes(256),
139
+ }),
140
+ "pci-dss": Object.assign({}, PROFILES["strict"], {
141
+ forensicSnippetBytes: C.BYTES.bytes(256),
142
+ }),
143
+ "gdpr": Object.assign({}, PROFILES["balanced"], {
144
+ forensicSnippetBytes: C.BYTES.bytes(128),
145
+ }),
146
+ "soc2-cc7": Object.assign({}, PROFILES["strict"], {
147
+ forensicSnippetBytes: C.BYTES.bytes(512),
148
+ }),
149
+ });
150
+
151
+ function _resolveOpts(opts) {
152
+ return gateContract.resolveProfileAndPosture(opts, {
153
+ profiles: PROFILES,
154
+ compliancePostures: COMPLIANCE_POSTURES,
155
+ defaults: DEFAULTS,
156
+ errorClass: GuardXmlError,
157
+ errCodePrefix: "xml",
158
+ });
159
+ }
160
+
161
+ function _detectIssues(input, opts) {
162
+ var issues = [];
163
+ if (typeof input !== "string") {
164
+ return [{ kind: "bad-input", severity: "high",
165
+ snippet: "input is not a string" }];
166
+ }
167
+ if (input.length > opts.maxBytes) {
168
+ return [{ kind: "too-large", severity: "high", ruleId: "xml.too-large",
169
+ snippet: "input " + input.length +
170
+ " bytes exceeds maxBytes " + opts.maxBytes }];
171
+ }
172
+
173
+ // 1. DOCTYPE.
174
+ if (opts.doctypePolicy !== "allow" && DOCTYPE_RE.test(input)) { // allow:regex-no-length-cap — input bounded by maxBytes above
175
+ issues.push({
176
+ kind: "doctype", severity: "critical", ruleId: "xml.doctype",
177
+ snippet: "DOCTYPE declaration (XXE / billion-laughs vector — " +
178
+ "CVE-2026-24400 / CVE-2024-25062 class)",
179
+ });
180
+ }
181
+
182
+ // 2. <!ENTITY> declarations.
183
+ if (opts.entityPolicy !== "allow" && ENTITY_DECL_RE.test(input)) { // allow:regex-no-length-cap — input bounded by maxBytes above
184
+ issues.push({
185
+ kind: "entity-declaration", severity: "critical",
186
+ ruleId: "xml.entity",
187
+ snippet: "<!ENTITY> declaration (entity-expansion DoS vector)",
188
+ });
189
+ if (PARAM_ENTITY_RE.test(input)) { // allow:regex-no-length-cap — input bounded by maxBytes above
190
+ issues.push({
191
+ kind: "parameter-entity", severity: "critical",
192
+ ruleId: "xml.parameter-entity",
193
+ snippet: "parameter entity (% prefix) — out-of-band exfil vector",
194
+ });
195
+ }
196
+ }
197
+
198
+ // 3. External entity references.
199
+ if (opts.externalEntityPolicy !== "allow" && EXTERNAL_ENTITY_RE.test(input)) { // allow:regex-no-length-cap — input bounded by maxBytes above
200
+ issues.push({
201
+ kind: "external-entity", severity: "critical",
202
+ ruleId: "xml.external-entity",
203
+ snippet: "SYSTEM/PUBLIC external entity reference (XXE — file:// / http:// exfil)",
204
+ });
205
+ }
206
+
207
+ // 4. XInclude.
208
+ if (opts.xincludePolicy !== "allow" && XINCLUDE_RE.test(input)) { // allow:regex-no-length-cap — input bounded by maxBytes above
209
+ issues.push({
210
+ kind: "xinclude",
211
+ severity: opts.xincludePolicy === "reject" ? "critical" : "high",
212
+ ruleId: "xml.xinclude",
213
+ snippet: "<xi:include> remote inclusion (XXE-shaped — CVE-2024-25062 class)",
214
+ });
215
+ }
216
+
217
+ // 5. xsi:schemaLocation.
218
+ if (opts.schemaLocationPolicy !== "allow" && SCHEMA_LOCATION_RE.test(input)) { // allow:regex-no-length-cap — input bounded by maxBytes above
219
+ issues.push({
220
+ kind: "schema-location",
221
+ severity: opts.schemaLocationPolicy === "reject" ? "high" : "warn",
222
+ ruleId: "xml.schema-location",
223
+ snippet: "xsi:schemaLocation — operator-controlled schema fetch",
224
+ });
225
+ }
226
+
227
+ // 6. Processing instructions.
228
+ if (opts.processingInstrPolicy !== "allow" && PROCESSING_INSTR_RE.test(input)) { // allow:regex-no-length-cap — input bounded by maxBytes above
229
+ // Skip the standard `<?xml ... ?>` declaration at byte 0.
230
+ var trimmed = input.replace(/^\s*<\?xml\s[^?]*\?>/, "");
231
+ if (PROCESSING_INSTR_RE.test(trimmed)) { // allow:regex-no-length-cap — trimmed input bounded by maxBytes above
232
+ issues.push({
233
+ kind: "processing-instruction",
234
+ severity: opts.processingInstrPolicy === "reject" ? "critical" : "high",
235
+ ruleId: "xml.pi",
236
+ snippet: "XML processing instruction (e.g. xml-stylesheet — CSS injection vector)",
237
+ });
238
+ }
239
+ }
240
+
241
+ // 7. CDATA sections.
242
+ if (opts.cdataPolicy !== "allow" && CDATA_RE.test(input)) { // allow:regex-no-length-cap — input bounded by maxBytes above
243
+ issues.push({
244
+ kind: "cdata",
245
+ severity: opts.cdataPolicy === "reject" ? "critical" : "warn",
246
+ ruleId: "xml.cdata",
247
+ snippet: "CDATA section (often hides payloads from naive scanners)",
248
+ });
249
+ }
250
+
251
+ // 8. XML signature.
252
+ if (opts.xmlDsigPolicy !== "allow" && XMLDSIG_RE.test(input)) { // allow:regex-no-length-cap — input bounded by maxBytes above
253
+ issues.push({
254
+ kind: "xml-signature", severity: "warn",
255
+ ruleId: "xml.xmldsig",
256
+ snippet: "XML signature element — operator must guard against signature wrapping (xmldsig)",
257
+ });
258
+ }
259
+
260
+ // 9. Codepoint-class threats.
261
+ issues.push.apply(issues, codepointClass.detectCharThreats(input, opts, "xml"));
262
+
263
+ // 10. Element + depth + attribute caps via tag count.
264
+ var openTags = (input.match(/<[A-Za-z][\w:-]*/g) || []).length;
265
+ if (openTags > opts.maxElements) {
266
+ issues.push({
267
+ kind: "element-cap", severity: "high",
268
+ ruleId: "xml.element-cap",
269
+ snippet: "element count " + openTags + " exceeds maxElements " + opts.maxElements,
270
+ });
271
+ }
272
+ // Depth: count consecutive nested-open without close (rough estimate).
273
+ var depthEstimate = 0;
274
+ var maxDepthSeen = 0;
275
+ var i = 0;
276
+ while (i < input.length) {
277
+ var lt = input.indexOf("<", i);
278
+ if (lt === -1) break;
279
+ if (input.charAt(lt + 1) === "/") depthEstimate -= 1;
280
+ else if (input.charAt(lt + 1) !== "!" && input.charAt(lt + 1) !== "?") {
281
+ depthEstimate += 1;
282
+ if (depthEstimate > maxDepthSeen) maxDepthSeen = depthEstimate;
283
+ }
284
+ var gt = input.indexOf(">", lt);
285
+ if (gt === -1) break;
286
+ if (input.charAt(gt - 1) === "/") depthEstimate -= 1;
287
+ i = gt + 1;
288
+ }
289
+ if (maxDepthSeen > opts.maxDepth) {
290
+ issues.push({
291
+ kind: "depth-cap", severity: "high", ruleId: "xml.depth-cap",
292
+ snippet: "estimated nesting depth " + maxDepthSeen +
293
+ " exceeds maxDepth " + opts.maxDepth,
294
+ });
295
+ }
296
+
297
+ return issues;
298
+ }
299
+
300
+ // ---- Public surface ----
301
+
302
+ function validate(input, opts) {
303
+ opts = _resolveOpts(opts);
304
+ numericBounds.requireAllPositiveFiniteIntIfPresent(opts,
305
+ ["maxBytes", "maxDepth", "maxElements", "maxAttrsPerElement",
306
+ "maxAttrValueBytes"],
307
+ "guardXml.validate", GuardXmlError, "xml.bad-opt");
308
+ if (typeof input !== "string") {
309
+ return {
310
+ ok: false,
311
+ issues: [{ kind: "bad-input", severity: "high",
312
+ snippet: "input is not a string" }],
313
+ };
314
+ }
315
+ return gateContract.aggregateIssues(_detectIssues(input, opts));
316
+ }
317
+
318
+ function sanitize(input, opts) {
319
+ opts = _resolveOpts(opts);
320
+ if (typeof input !== "string") {
321
+ throw _err("xml.bad-input", "sanitize requires string input");
322
+ }
323
+ // XML sanitization — strip what's strip-able per policy. Critical
324
+ // shapes (DOCTYPE / ENTITY / external / parameter-entity) have no
325
+ // safe sanitization; throw.
326
+ var issues = _detectIssues(input, opts);
327
+ for (var i = 0; i < issues.length; i += 1) {
328
+ if (issues[i].severity === "critical") {
329
+ throw _err(issues[i].ruleId || "xml.refused",
330
+ "guardXml.sanitize: " + issues[i].snippet);
331
+ }
332
+ }
333
+ // Strip character-class threats per policy via the shared helper.
334
+ return codepointClass.applyCharStripPolicies(input, opts);
335
+ }
336
+
337
+ function gate(opts) {
338
+ opts = _resolveOpts(opts);
339
+ return gateContract.buildGuardGate(
340
+ opts.name || "guardXml:" + (opts.profile || "default"),
341
+ opts,
342
+ async function (ctx) {
343
+ var text = gateContract.extractBytesAsText(ctx);
344
+ if (!text) return { ok: true, action: "serve" };
345
+ var rv = validate(text, opts);
346
+ if (rv.issues.length === 0) return { ok: true, action: "serve" };
347
+ var hasCritical = rv.issues.some(function (i) {
348
+ return i.severity === "critical" || i.severity === "high";
349
+ });
350
+ if (!hasCritical) return { ok: true, action: "audit-only", issues: rv.issues };
351
+
352
+ // Sanitize-eligibility: every reject-policy off.
353
+ var canSanitize = opts.doctypePolicy !== "reject" &&
354
+ opts.entityPolicy !== "reject" &&
355
+ opts.externalEntityPolicy !== "reject";
356
+ if (canSanitize) {
357
+ try {
358
+ var clean = sanitize(text, opts);
359
+ return { ok: true, action: "sanitize",
360
+ sanitized: Buffer.from(clean, "utf8"),
361
+ issues: rv.issues };
362
+ } catch (_e) { /* fall through */ }
363
+ }
364
+ return { ok: false, action: "refuse", issues: rv.issues };
365
+ });
366
+ }
367
+
368
+ var buildProfile = gateContract.makeProfileBuilder(PROFILES);
369
+
370
+ function compliancePosture(name) {
371
+ return gateContract.lookupCompliancePosture(name, COMPLIANCE_POSTURES, _err, "xml");
372
+ }
373
+
374
+ var _xmlRulePacks = gateContract.makeRulePackLoader(GuardXmlError, "xml");
375
+ var loadRulePack = _xmlRulePacks.load;
376
+
377
+ module.exports = {
378
+ // ---- guard-* family registry exports ----
379
+ NAME: "xml",
380
+ KIND: "content",
381
+ MIME_TYPES: Object.freeze(["application/xml", "text/xml"]),
382
+ EXTENSIONS: Object.freeze([".xml"]),
383
+ INTEGRATION_FIXTURES: Object.freeze({
384
+ kind: "content",
385
+ contentType: "application/xml",
386
+ extension: ".xml",
387
+ benignBytes: Buffer.from('<?xml version="1.0"?><root><x>1</x></root>', "utf8"),
388
+ // Hostile: DOCTYPE with internal-subset entity declaration (XXE +
389
+ // billion-laughs vector — CVE-2026-24400 / CVE-2024-25062 class).
390
+ hostileBytes: Buffer.from(
391
+ '<?xml version="1.0"?>\n<!DOCTYPE root [<!ENTITY xx "yy">]>\n<root/>',
392
+ "utf8"),
393
+ }),
394
+ // ---- primitive surface ----
395
+ validate: validate,
396
+ sanitize: sanitize,
397
+ gate: gate,
398
+ buildProfile: buildProfile,
399
+ compliancePosture: compliancePosture,
400
+ loadRulePack: loadRulePack,
401
+ PROFILES: PROFILES,
402
+ DEFAULTS: DEFAULTS,
403
+ COMPLIANCE_POSTURES: COMPLIANCE_POSTURES,
404
+ GuardXmlError: GuardXmlError,
405
+ };