@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
@@ -0,0 +1,529 @@
1
+ "use strict";
2
+ /**
3
+ * guard-yaml — YAML content-safety primitive (b.guardYaml).
4
+ *
5
+ * Threat catalog grounded in current research (multiple 2025-2026
6
+ * deserialization + DoS CVEs in popular YAML libraries):
7
+ * - CVE-2026-24009 Docling / PyYAML unsafe load → RCE
8
+ * - CVE-2026-27807 MarkUs YAML alias billion-laughs DoS
9
+ * - CVE-2025-68664 LangChain deserialization → RCE
10
+ * - CVE-2025-61301 / CVE-2025-61303 YAML library DoS family
11
+ * ("Laughter in the Wild" study across 14 libraries / 10 languages)
12
+ * - CVE-2022-1471 SnakeYAML constructor RCE
13
+ * - CVE-2020-1747 / CVE-2020-14343 PyYAML FullLoader RCE chain
14
+ * - CVE-2017-18342 PyYAML python/object/apply RCE
15
+ *
16
+ * var rv = b.guardYaml.validate(input, { profile: "strict" });
17
+ * var safe = b.guardYaml.parse(input, { profile: "strict" });
18
+ * var g = b.guardYaml.gate({ profile: "strict" });
19
+ *
20
+ * Threat catalog covered (all source-level — operator's downstream
21
+ * parser may be pyyaml/snakeyaml/js-yaml; the guard refuses hostile
22
+ * sources before any parser sees them):
23
+ *
24
+ * 1. Tag-injection RCE — language-specific deserialization tags
25
+ * with prefixes !!python/ / !!java. / !!ruby/ / !!perl/ / !!js/
26
+ * / !!cs/ / !!net/ / !!system. and the !!apply / !!new family.
27
+ * Refused regardless of profile under strict.
28
+ *
29
+ * 2. Anchor / alias recursion (billion laughs) — &anchor declares,
30
+ * *alias references. Recursive aliasing amplifies a small input
31
+ * into GiB on parse. Caps via maxAnchors + maxAliasDepth + total
32
+ * node count.
33
+ *
34
+ * 3. Multi-document streams — operators expecting a single doc
35
+ * silently get the first one and ignore the rest, which can mask
36
+ * hostile content.
37
+ *
38
+ * 4. Norway problem — YAML 1.1 (still default in pyyaml + libyaml
39
+ * in 2026) treats unquoted no/yes/y/n/on/off as booleans. Country
40
+ * code "NO" → false.
41
+ *
42
+ * 5. Leading-zero octals — 0777 parses as octal 511 in YAML 1.1.
43
+ *
44
+ * 6. Duplicate keys — YAML 1.2 SHOULD-unique; parsers silently
45
+ * last-wins, same threat shape as JSON duplicate-key smuggling.
46
+ *
47
+ * 7. Local + custom user tags — even when not language-specific,
48
+ * surface that suggests a non-safe parser is downstream.
49
+ *
50
+ * 8. Merge-key chain depth (<<: *anchor) — anchor-chain DoS.
51
+ *
52
+ * 9. Bidi / null / control / zero-width chars in scalar values.
53
+ *
54
+ * 10. Anti-DoS caps — total document size, total node count, max
55
+ * anchors, max alias depth, max document count, max scalar
56
+ * length, max depth.
57
+ */
58
+
59
+ var codepointClass = require("./codepoint-class");
60
+ var lazyRequire = require("./lazy-require");
61
+ var gateContract = require("./gate-contract");
62
+ var C = require("./constants");
63
+ var numericBounds = require("./numeric-bounds");
64
+ var safeYamlLazy = lazyRequire(function () { return require("./parsers/safe-yaml"); });
65
+ var { GuardYamlError } = require("./framework-error");
66
+
67
+ var observability = lazyRequire(function () { return require("./observability"); });
68
+ void observability;
69
+
70
+ var _err = GuardYamlError.factory;
71
+
72
+ // ---- Source-level threat detectors ----
73
+
74
+ // Dangerous tag prefixes — language-specific deserialization triggers.
75
+ var DANGEROUS_TAG_PREFIXES = Object.freeze([
76
+ "!!python/", "!!java.", "!!ruby/", "!!perl/", "!!js/", "!!cs/",
77
+ "!!net/", "!!system.", "!!eval", "!!exec", "!!new", "!!apply",
78
+ ]);
79
+
80
+ // YAML 1.2 core tag allowlist — when allowing tags at all, only these
81
+ // are permitted under balanced.
82
+ var SAFE_CORE_TAGS = Object.freeze([
83
+ "!!str", "!!int", "!!float", "!!bool", "!!null",
84
+ "!!seq", "!!map", "!!set", "!!omap", "!!pairs",
85
+ "!!binary", "!!timestamp", "!!merge",
86
+ ]);
87
+
88
+ // Anchor declaration — &name. Alias reference — *name.
89
+ var ANCHOR_DECL_RE = /(^|\s|:|-)(&[A-Za-z_][A-Za-z0-9_-]*)/g;
90
+ var ALIAS_REF_RE = /(^|\s|:|-|\[|\{|,)(\*[A-Za-z_][A-Za-z0-9_-]*)/g;
91
+
92
+ // Norway problem — unquoted YAML 1.1 boolean-shaped tokens at scalar
93
+ // position. true/false ARE valid YAML 1.2 booleans so we don't flag
94
+ // them; only the no/yes/y/n/on/off quirks fire.
95
+ var NORWAY_BOOL_QUIRK_RE = /:\s*(no|yes|y|n|on|off)\b/gi;
96
+
97
+ // Leading-zero octals — 0777 etc. at scalar position.
98
+ var LEADING_ZERO_OCTAL_RE = /:\s*0\d+\b/g;
99
+
100
+ // Merge keys — <<: *anchor chain.
101
+ var MERGE_KEY_RE = /<<\s*:\s*\*/;
102
+
103
+ // ---- Profile presets ----
104
+
105
+ var PROFILES = Object.freeze({
106
+ "strict": {
107
+ tagPolicy: "reject",
108
+ aliasPolicy: "reject",
109
+ multiDocPolicy: "reject",
110
+ norwayPolicy: "reject",
111
+ leadingZeroPolicy: "reject",
112
+ duplicateKeyPolicy: "reject",
113
+ mergeKeyPolicy: "reject",
114
+ bidiPolicy: "reject",
115
+ controlPolicy: "reject",
116
+ nullBytePolicy: "reject",
117
+ zeroWidthPolicy: "reject",
118
+ safeCoreTagsAllowed: false,
119
+ maxBytes: C.BYTES.mib(2),
120
+ maxDepth: 8, // allow:raw-byte-literal — recursion depth, not byte size
121
+ maxAnchors: 16, // allow:raw-byte-literal — anchor count cap, not byte size
122
+ maxAliasDepth: 1, // allow:raw-byte-literal — alias chain cap, not byte size
123
+ maxDocuments: 1, // allow:raw-byte-literal — doc count cap, not byte size
124
+ maxNodes: 1024, // allow:raw-byte-literal — node count cap, not byte size
125
+ maxScalarLength: C.BYTES.kib(8),
126
+ },
127
+ "balanced": {
128
+ tagPolicy: "audit",
129
+ aliasPolicy: "audit",
130
+ multiDocPolicy: "audit",
131
+ norwayPolicy: "audit",
132
+ leadingZeroPolicy: "audit",
133
+ duplicateKeyPolicy: "audit",
134
+ mergeKeyPolicy: "audit",
135
+ bidiPolicy: "strip",
136
+ controlPolicy: "strip",
137
+ nullBytePolicy: "strip",
138
+ zeroWidthPolicy: "strip",
139
+ safeCoreTagsAllowed: true,
140
+ maxBytes: C.BYTES.mib(8),
141
+ maxDepth: 32, // allow:raw-byte-literal — recursion depth, not byte size
142
+ maxAnchors: 64, // allow:raw-byte-literal — anchor count cap, not byte size
143
+ maxAliasDepth: 3, // allow:raw-byte-literal — alias chain cap, not byte size
144
+ maxDocuments: 16, // allow:raw-byte-literal — doc count cap, not byte size
145
+ maxNodes: 16384, // allow:raw-byte-literal — node count cap, not byte size
146
+ maxScalarLength: C.BYTES.kib(64),
147
+ },
148
+ "permissive": {
149
+ tagPolicy: "audit",
150
+ aliasPolicy: "audit",
151
+ multiDocPolicy: "audit",
152
+ norwayPolicy: "audit",
153
+ leadingZeroPolicy: "audit",
154
+ duplicateKeyPolicy: "audit",
155
+ mergeKeyPolicy: "audit",
156
+ bidiPolicy: "audit",
157
+ controlPolicy: "strip",
158
+ nullBytePolicy: "reject",
159
+ zeroWidthPolicy: "strip",
160
+ safeCoreTagsAllowed: true,
161
+ maxBytes: C.BYTES.mib(64),
162
+ maxDepth: 64, // allow:raw-byte-literal — recursion depth, not byte size
163
+ maxAnchors: 1024, // allow:raw-byte-literal — anchor count cap, not byte size
164
+ maxAliasDepth: 8, // allow:raw-byte-literal — alias chain cap, not byte size
165
+ maxDocuments: 256, // allow:raw-byte-literal — doc count cap, not byte size
166
+ maxNodes: 65536, // allow:raw-byte-literal — node count cap, not byte size
167
+ maxScalarLength: C.BYTES.kib(256),
168
+ },
169
+ });
170
+
171
+ var DEFAULTS = Object.freeze(Object.assign({}, PROFILES["strict"], {
172
+ mode: "enforce",
173
+ maxRuntimeMs: C.TIME.seconds(10),
174
+ }));
175
+
176
+ var COMPLIANCE_POSTURES = Object.freeze({
177
+ "hipaa": Object.assign({}, PROFILES["strict"], {
178
+ forensicSnippetBytes: C.BYTES.bytes(256),
179
+ }),
180
+ "pci-dss": Object.assign({}, PROFILES["strict"], {
181
+ forensicSnippetBytes: C.BYTES.bytes(256),
182
+ }),
183
+ "gdpr": Object.assign({}, PROFILES["balanced"], {
184
+ forensicSnippetBytes: C.BYTES.bytes(128),
185
+ }),
186
+ "soc2-cc7": Object.assign({}, PROFILES["strict"], {
187
+ forensicSnippetBytes: C.BYTES.bytes(512),
188
+ }),
189
+ });
190
+
191
+ // ---- Helpers ----
192
+
193
+ function _resolveOpts(opts) {
194
+ return gateContract.resolveProfileAndPosture(opts, {
195
+ profiles: PROFILES,
196
+ compliancePostures: COMPLIANCE_POSTURES,
197
+ defaults: DEFAULTS,
198
+ errorClass: GuardYamlError,
199
+ errCodePrefix: "yaml",
200
+ });
201
+ }
202
+
203
+ function _isDangerousTag(tag) {
204
+ for (var i = 0; i < DANGEROUS_TAG_PREFIXES.length; i += 1) {
205
+ if (tag.indexOf(DANGEROUS_TAG_PREFIXES[i]) === 0) return true;
206
+ }
207
+ return false;
208
+ }
209
+
210
+ function _isSafeCoreTag(tag) {
211
+ return SAFE_CORE_TAGS.indexOf(tag) !== -1;
212
+ }
213
+
214
+ // _scanTags — find every tag-prefix occurrence in the source.
215
+ function _scanTags(text) {
216
+ var matches = [];
217
+ var iter = text.matchAll(/(^|\s)(![A-Za-z][\w./:-]*|!![A-Za-z][\w./:-]*)/g);
218
+ var m;
219
+ for (m of iter) {
220
+ var tag = m[2];
221
+ var kind;
222
+ if (_isDangerousTag(tag)) kind = "dangerous";
223
+ else if (_isSafeCoreTag(tag)) kind = "safe-core";
224
+ else kind = "custom";
225
+ matches.push({ tag: tag, location: m.index, kind: kind });
226
+ }
227
+ return matches;
228
+ }
229
+
230
+ function _detectIssues(input, opts) {
231
+ var issues = [];
232
+ if (typeof input !== "string") {
233
+ return [{ kind: "bad-input", severity: "high",
234
+ snippet: "input is not a string" }];
235
+ }
236
+ if (input.length > opts.maxBytes) {
237
+ return [{ kind: "too-large", severity: "high", ruleId: "yaml.too-large",
238
+ snippet: "input " + input.length +
239
+ " bytes exceeds maxBytes " + opts.maxBytes }];
240
+ }
241
+
242
+ // 1. Tag-injection scan.
243
+ var tagHits = _scanTags(input);
244
+ for (var ti = 0; ti < tagHits.length; ti += 1) {
245
+ var t = tagHits[ti];
246
+ if (t.kind === "dangerous") {
247
+ issues.push({
248
+ kind: "dangerous-tag", severity: "critical",
249
+ ruleId: "yaml.dangerous-tag",
250
+ location: t.location,
251
+ snippet: "deserialization-tag injection " + JSON.stringify(t.tag) +
252
+ " (CVE-2026-24009 / CVE-2022-1471 class)",
253
+ });
254
+ } else if (t.kind === "custom") {
255
+ if (opts.tagPolicy === "reject" ||
256
+ (opts.tagPolicy === "audit" && !opts.safeCoreTagsAllowed)) {
257
+ issues.push({
258
+ kind: "custom-tag",
259
+ severity: opts.tagPolicy === "reject" ? "critical" : "high",
260
+ ruleId: "yaml.custom-tag",
261
+ location: t.location,
262
+ snippet: "custom tag " + JSON.stringify(t.tag) +
263
+ " (suggests non-safe parser downstream)",
264
+ });
265
+ }
266
+ } else if (t.kind === "safe-core") {
267
+ if (opts.tagPolicy === "reject" || !opts.safeCoreTagsAllowed) {
268
+ issues.push({
269
+ kind: "core-tag",
270
+ severity: opts.tagPolicy === "reject" ? "high" : "warn",
271
+ ruleId: "yaml.core-tag",
272
+ location: t.location,
273
+ snippet: "YAML 1.2 core tag " + JSON.stringify(t.tag),
274
+ });
275
+ }
276
+ }
277
+ }
278
+
279
+ // 2. Anchor / alias recursion scan.
280
+ var anchors = [];
281
+ var aIter = input.matchAll(ANCHOR_DECL_RE);
282
+ var aM;
283
+ for (aM of aIter) anchors.push(aM[2]);
284
+ var aliases = [];
285
+ var alIter = input.matchAll(ALIAS_REF_RE);
286
+ var alM;
287
+ for (alM of alIter) aliases.push(alM[2]);
288
+ if (anchors.length > opts.maxAnchors) {
289
+ issues.push({
290
+ kind: "anchor-cap", severity: "high",
291
+ ruleId: "yaml.anchor-cap",
292
+ snippet: "anchor declarations " + anchors.length +
293
+ " exceeds maxAnchors " + opts.maxAnchors,
294
+ });
295
+ }
296
+ if ((anchors.length > 0 || aliases.length > 0) && opts.aliasPolicy === "reject") {
297
+ issues.push({
298
+ kind: "alias-disabled", severity: "critical",
299
+ ruleId: "yaml.alias",
300
+ snippet: "anchors/aliases refused under strict (billion-laughs vector — " +
301
+ "CVE-2026-27807 MarkUs class)",
302
+ });
303
+ }
304
+ // alias-amplification ratio: aliases / anchors. Billion-laughs shape
305
+ // is ratio >= 8. Independent of maxAnchors absolute cap (which is
306
+ // about overall load); ratio is about exponential expansion shape.
307
+ var ampRatio = aliases.length / Math.max(anchors.length, 1);
308
+ if (anchors.length >= 1 && ampRatio >= 8) { // allow:raw-byte-literal — multiplier ratio, not byte size
309
+ issues.push({
310
+ kind: "alias-explosion", severity: "critical",
311
+ ruleId: "yaml.alias-explosion",
312
+ snippet: "alias-reference count " + aliases.length +
313
+ " amplifies " + ampRatio.toFixed(1) +
314
+ "x against " + anchors.length + " anchor(s) (billion-laughs shape)",
315
+ });
316
+ }
317
+
318
+ // 3. Multi-document.
319
+ var docs = (input.match(/(^|\n)---\s/g) || []).length;
320
+ if (docs > 0 && opts.multiDocPolicy !== "allow") {
321
+ if (opts.multiDocPolicy === "reject" ||
322
+ (docs + 1) > opts.maxDocuments) {
323
+ issues.push({
324
+ kind: "multi-document",
325
+ severity: opts.multiDocPolicy === "reject" ? "critical" : "high",
326
+ ruleId: "yaml.multi-document",
327
+ snippet: "multi-document stream (" + (docs + 1) +
328
+ " docs) — first-doc-wins silently masks the rest",
329
+ });
330
+ }
331
+ }
332
+
333
+ // 4. Norway-problem implicit booleans.
334
+ if (opts.norwayPolicy !== "allow") {
335
+ var norwayIter = input.matchAll(NORWAY_BOOL_QUIRK_RE);
336
+ var norwayM;
337
+ var seen = false;
338
+ for (norwayM of norwayIter) {
339
+ if (!seen) {
340
+ issues.push({
341
+ kind: "norway-implicit-bool",
342
+ severity: opts.norwayPolicy === "reject" ? "critical" : "warn",
343
+ ruleId: "yaml.norway",
344
+ location: norwayM.index,
345
+ snippet: "implicit YAML 1.1 boolean " + JSON.stringify(norwayM[1]) +
346
+ " (Norway problem — country code 'NO' parses as false; " +
347
+ "quote scalars to disambiguate)",
348
+ });
349
+ seen = true;
350
+ }
351
+ }
352
+ }
353
+
354
+ // 5. Leading-zero octals.
355
+ if (opts.leadingZeroPolicy !== "allow") {
356
+ if (LEADING_ZERO_OCTAL_RE.test(input)) { // allow:regex-no-length-cap — input bounded by maxBytes above
357
+ issues.push({
358
+ kind: "leading-zero-octal",
359
+ severity: opts.leadingZeroPolicy === "reject" ? "high" : "warn",
360
+ ruleId: "yaml.leading-zero",
361
+ snippet: "leading-zero numeric (parses as octal in YAML 1.1)",
362
+ });
363
+ }
364
+ }
365
+
366
+ // 6. Merge-key chain depth.
367
+ if (opts.mergeKeyPolicy !== "allow" && MERGE_KEY_RE.test(input)) { // allow:regex-no-length-cap — input bounded by maxBytes above
368
+ issues.push({
369
+ kind: "merge-key",
370
+ severity: opts.mergeKeyPolicy === "reject" ? "high" : "warn",
371
+ ruleId: "yaml.merge-key",
372
+ snippet: "merge-key with anchor reference (anchor-chain DoS vector)",
373
+ });
374
+ }
375
+
376
+ // 7. Codepoint-class threats.
377
+ issues.push.apply(issues, codepointClass.detectCharThreats(input, opts, "yaml"));
378
+
379
+ // 8. Duplicate keys via per-indent block-mapping scan. Done BEFORE
380
+ // parse because some parsers refuse-on-duplicate, and we want the
381
+ // duplicate-key issue surfaced regardless of parser strictness.
382
+ if (opts.duplicateKeyPolicy !== "allow") {
383
+ var dups = _detectDuplicateKeysYaml(input);
384
+ for (var di = 0; di < dups.length; di += 1) {
385
+ issues.push({
386
+ kind: "duplicate-key",
387
+ severity: opts.duplicateKeyPolicy === "reject" ? "critical" : "warn",
388
+ ruleId: "yaml.duplicate-key",
389
+ snippet: "duplicate key " + JSON.stringify(dups[di]) +
390
+ " (YAML 1.2 SHOULD-unique; parsers silently last-wins)",
391
+ });
392
+ }
393
+ }
394
+
395
+ // 9. Try parse via b.parsers.yaml.
396
+ try {
397
+ safeYamlLazy().parse(input, {
398
+ maxBytes: opts.maxBytes,
399
+ maxDepth: opts.maxDepth,
400
+ maxKeys: opts.maxNodes,
401
+ });
402
+ } catch (e) {
403
+ issues.push({
404
+ kind: "parse-failed", severity: "critical", ruleId: "yaml.parse",
405
+ snippet: "YAML parse failed: " + (e && e.message),
406
+ });
407
+ }
408
+
409
+ return issues;
410
+ }
411
+
412
+ function _detectDuplicateKeysYaml(text) {
413
+ var dups = Object.create(null);
414
+ var lines = text.split(/\r?\n/);
415
+ var indentScopes = Object.create(null);
416
+ for (var i = 0; i < lines.length; i += 1) {
417
+ var line = lines[i];
418
+ if (line.length === 0 || /^\s*#/.test(line)) continue;
419
+ var indentMatch = line.match(/^(\s*)([^\s].*?):(\s|$)/);
420
+ if (!indentMatch) continue;
421
+ var indent = indentMatch[1].length;
422
+ var key = indentMatch[2].trim();
423
+ if (key.charAt(0) === "-" || key.charAt(0) === "[" || key.charAt(0) === "{") continue;
424
+ if (!indentScopes[indent]) indentScopes[indent] = Object.create(null);
425
+ if (indentScopes[indent][key]) dups[key] = true;
426
+ else indentScopes[indent][key] = true;
427
+ Object.keys(indentScopes).forEach(function (k) {
428
+ if (Number(k) > indent) delete indentScopes[k];
429
+ });
430
+ }
431
+ return Object.keys(dups);
432
+ }
433
+
434
+ // ---- Public surface ----
435
+
436
+ function validate(input, opts) {
437
+ opts = _resolveOpts(opts);
438
+ numericBounds.requireAllPositiveFiniteIntIfPresent(opts,
439
+ ["maxBytes", "maxDepth", "maxAnchors", "maxAliasDepth",
440
+ "maxDocuments", "maxNodes", "maxScalarLength"],
441
+ "guardYaml.validate", GuardYamlError, "yaml.bad-opt");
442
+ if (typeof input !== "string") {
443
+ return {
444
+ ok: false,
445
+ issues: [{ kind: "bad-input", severity: "high",
446
+ snippet: "input is not a string" }],
447
+ };
448
+ }
449
+ return gateContract.aggregateIssues(_detectIssues(input, opts));
450
+ }
451
+
452
+ function parse(input, opts) {
453
+ opts = _resolveOpts(opts);
454
+ if (typeof input !== "string") {
455
+ throw _err("yaml.bad-input", "parse requires string input");
456
+ }
457
+ var issues = _detectIssues(input, opts);
458
+ for (var i = 0; i < issues.length; i += 1) {
459
+ if (issues[i].severity === "critical") {
460
+ throw _err(issues[i].ruleId || "yaml.refused",
461
+ "guardYaml.parse: " + issues[i].snippet);
462
+ }
463
+ }
464
+ return safeYamlLazy().parse(input, {
465
+ maxBytes: opts.maxBytes,
466
+ maxDepth: opts.maxDepth,
467
+ maxKeys: opts.maxNodes,
468
+ });
469
+ }
470
+
471
+ function gate(opts) {
472
+ opts = _resolveOpts(opts);
473
+ return gateContract.buildGuardGate(
474
+ opts.name || "guardYaml:" + (opts.profile || "default"),
475
+ opts,
476
+ async function (ctx) {
477
+ var text = gateContract.extractBytesAsText(ctx);
478
+ if (!text) return { ok: true, action: "serve" };
479
+ var rv = validate(text, opts);
480
+ if (rv.issues.length === 0) return { ok: true, action: "serve" };
481
+ var hasCritical = rv.issues.some(function (i) {
482
+ return i.severity === "critical" || i.severity === "high";
483
+ });
484
+ if (!hasCritical) return { ok: true, action: "audit-only", issues: rv.issues };
485
+ return { ok: false, action: "refuse", issues: rv.issues };
486
+ });
487
+ }
488
+
489
+ var buildProfile = gateContract.makeProfileBuilder(PROFILES);
490
+
491
+ function compliancePosture(name) {
492
+ return gateContract.lookupCompliancePosture(name, COMPLIANCE_POSTURES, _err, "yaml");
493
+ }
494
+
495
+ var _yamlRulePacks = gateContract.makeRulePackLoader(GuardYamlError, "yaml");
496
+ var loadRulePack = _yamlRulePacks.load;
497
+
498
+ module.exports = {
499
+ // ---- guard-* family registry exports ----
500
+ NAME: "yaml",
501
+ KIND: "content",
502
+ MIME_TYPES: Object.freeze([
503
+ "application/yaml", "application/x-yaml", "text/yaml", "text/x-yaml",
504
+ ]),
505
+ EXTENSIONS: Object.freeze([".yml", ".yaml"]),
506
+ INTEGRATION_FIXTURES: Object.freeze({
507
+ kind: "content",
508
+ contentType: "application/yaml",
509
+ extension: ".yaml",
510
+ benignBytes: Buffer.from('name: alice\nage: 30\n', "utf8"),
511
+ // Hostile: deserialization-tag injection (CVE-2026-24009 PyYAML
512
+ // class). Parser-runtime would attempt to instantiate the named
513
+ // language-specific class.
514
+ hostileBytes: Buffer.from("!!python/object/new:cls\nargs: [\"x\"]\n", "utf8"),
515
+ }),
516
+ // ---- primitive surface ----
517
+ validate: validate,
518
+ parse: parse,
519
+ gate: gate,
520
+ buildProfile: buildProfile,
521
+ compliancePosture: compliancePosture,
522
+ loadRulePack: loadRulePack,
523
+ PROFILES: PROFILES,
524
+ DEFAULTS: DEFAULTS,
525
+ COMPLIANCE_POSTURES: COMPLIANCE_POSTURES,
526
+ DANGEROUS_TAG_PREFIXES: DANGEROUS_TAG_PREFIXES,
527
+ SAFE_CORE_TAGS: SAFE_CORE_TAGS,
528
+ GuardYamlError: GuardYamlError,
529
+ };