@blamejs/core 0.7.1 → 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 -389
  2. package/README.md +150 -149
  3. package/bin/blamejs.js +0 -0
  4. package/index.js +308 -282
  5. package/lib/api-key.js +660 -672
  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 -266
  27. package/lib/cache.js +1206 -1211
  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 +1136 -0
  56. package/lib/forms.js +422 -422
  57. package/lib/framework-error.js +293 -202
  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 -573
  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 -269
  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 -614
  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 -451
  119. package/lib/object-store/gcs-bucket-ops.js +351 -351
  120. package/lib/object-store/gcs.js +519 -479
  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 -855
  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 -177
  140. package/lib/pubsub.js +429 -429
  141. package/lib/queue-local.js +476 -476
  142. package/lib/queue-redis.js +745 -752
  143. package/lib/queue-sqs.js +319 -319
  144. package/lib/queue.js +695 -695
  145. package/lib/redis-client.js +519 -489
  146. package/lib/request-helpers.js +340 -336
  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 -630
  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 +879 -114
  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 -270
  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 -598
  178. package/lib/websocket.js +1048 -1048
  179. package/package.json +77 -77
  180. package/sbom.cyclonedx.json +7 -7
@@ -0,0 +1,586 @@
1
+ "use strict";
2
+ /**
3
+ * guard-markdown — Markdown content-safety primitive (b.guardMarkdown).
4
+ *
5
+ * Threat catalog grounded in current research:
6
+ * - CVE-2026-30838 — CommonMark DisallowedRawHtml whitespace-tag bypass
7
+ * (`<script\n>` / `<script\t>` evades naive `<script>` matchers; the
8
+ * browser still treats the tag as a script element).
9
+ * - CVE-2025-9540 — Markup Markdown stored XSS via link with javascript:.
10
+ * - CVE-2025-7969 — markdown-it ReDoS class.
11
+ * - CVE-2025-6493 — CodeMirror Markdown Mode catastrophic backtracking.
12
+ * - CVE-2025-24981 — MDC Markdown XSS via unsanitized autolinks.
13
+ * - CVE-2026-33500 — AVideo Parsedown link XSS via inlineLink/inlineUrlTag
14
+ * bypass (ParsedownSafeWithLinks didn't override link emitters).
15
+ * - GHSA-gwjh-c548-f787 — NuGetGallery autolink XSS.
16
+ * - Joplin GHSA-hff8-hjwv-j9q7 — RCE via untrusted markdown link.
17
+ *
18
+ * The primitive is a SOURCE-LEVEL gate: it inspects raw markdown text
19
+ * BEFORE any downstream renderer (marked / markdown-it / commonmark /
20
+ * remark / parsedown) sees it. Source-level discipline matters because
21
+ * the most dangerous shapes — `__proto__` in JSON, `<script\n>` in
22
+ * markdown — exploit specific parser internals; sanitizing on the
23
+ * post-parse tree is too late.
24
+ *
25
+ * var rv = b.guardMarkdown.validate(input, { profile: "strict" });
26
+ * var safe = b.guardMarkdown.sanitize(input, { profile: "balanced" });
27
+ * var g = b.guardMarkdown.gate({ profile: "strict" });
28
+ */
29
+
30
+ var codepointClass = require("./codepoint-class");
31
+ var lazyRequire = require("./lazy-require");
32
+ var gateContract = require("./gate-contract");
33
+ var C = require("./constants");
34
+ var numericBounds = require("./numeric-bounds");
35
+ var { GuardMarkdownError } = require("./framework-error");
36
+
37
+ var observability = lazyRequire(function () { return require("./observability"); });
38
+ void observability;
39
+
40
+ var _err = GuardMarkdownError.factory;
41
+
42
+ // ---- Source-level threat detectors ----
43
+
44
+ // Raw HTML tag detection — whitespace-tolerant per CVE-2026-30838.
45
+ var RAW_HTML_TAG_RE = /<\s*\/?\s*[A-Za-z][\w-]*[\s\S]*?>/;
46
+ var DANGEROUS_TAGS = [
47
+ "script", "iframe", "object", "embed", "applet", "form", "input",
48
+ "button", "textarea", "select", "option", "meta", "link", "base",
49
+ "frame", "frameset", "noscript", "noembed", "svg", "math", "video",
50
+ "audio", "source", "track", "style", "template", "portal", "marquee",
51
+ ];
52
+ // allow:dynamic-regex — built once at module load from the static
53
+ // DANGEROUS_TAGS literal array; no runtime input.
54
+ var DANGEROUS_TAG_RE = new RegExp(
55
+ "<\\s*/?\\s*(" + DANGEROUS_TAGS.join("|") + ")\\b",
56
+ "i"
57
+ );
58
+
59
+ // Dangerous URL schemes in inline links / autolinks / images / refs.
60
+ var DANGEROUS_SCHEMES = [
61
+ "javascript", "vbscript", "livescript", "mocha", "view-source",
62
+ "data", "jar", "blob", "feed", "tel", "facetime", "facetime-audio",
63
+ ];
64
+ // allow:dynamic-regex — built once at module load from the static
65
+ // DANGEROUS_SCHEMES literal array; no runtime input.
66
+ var DANGEROUS_SCHEME_RE = new RegExp(
67
+ "^(?:" + DANGEROUS_SCHEMES.join("|") + ")\\s*:",
68
+ "i"
69
+ );
70
+ var FILE_SCHEME_RE = /^file\s*:/i;
71
+
72
+ // Inline link `[text](url)` and image `![alt](url)`. Captures the URL.
73
+ var INLINE_LINK_RE = /(!?)\[([^\]\n]*)\]\(\s*([^)\s]+)\s*(?:"[^"]*")?\s*\)/g;
74
+ // Autolink `<scheme:...>`.
75
+ var AUTOLINK_RE = /<((?:[a-zA-Z][a-zA-Z0-9+.-]{0,32}):[^\s>]+)>/g;
76
+ // Reference-link definition `[label]: url "title"`.
77
+ var REF_DEF_RE = /^\s{0,3}\[([^\]\n]+)\]:\s*([^\s]+)/gm;
78
+ // HTML entity hex / decimal scheme bypass — decode and re-test.
79
+ var HTML_ENTITY_NUM_RE = /&#(?:x([0-9a-f]+)|(\d+));?/gi;
80
+
81
+ // Front-matter block (YAML triple-dash or TOML triple-plus).
82
+ var FRONT_MATTER_YAML_RE = /^---\s*\n[\s\S]+?\n---\s*\n?/;
83
+ var FRONT_MATTER_TOML_RE = /^\+\+\+\s*\n[\s\S]+?\n\+\+\+\s*\n?/;
84
+
85
+ var HTML_COMMENT_RE = /<!--[\s\S]*?-->/;
86
+ var DOCTYPE_INLINE_RE = /<!DOCTYPE\b/i;
87
+ var CODE_FENCE_LANG_RE = /^(?:```|~~~)([^\n]*)\n/gm;
88
+ var EMPH_RUN_RE = /[*_]{20,}/; // allow:regex-no-length-cap — character-class repeat is linear in input length
89
+
90
+ function _decodeHtmlEntities(s) {
91
+ return s.replace(HTML_ENTITY_NUM_RE, function (match, hex, dec) {
92
+ var code = hex !== undefined ? parseInt(hex, 16) : parseInt(dec, 10); // allow:raw-byte-literal — parseInt radix args (16 hex / 10 decimal)
93
+ if (!isFinite(code) || code < 0 || code > 0x10ffff) return match; // allow:raw-byte-literal — Unicode codepoint range
94
+ try { return String.fromCodePoint(code); } catch (_e) { return match; }
95
+ });
96
+ }
97
+
98
+ function _isDangerousUrl(url, opts) {
99
+ if (typeof url !== "string") return null;
100
+ var s = url.trim();
101
+ s = _decodeHtmlEntities(s);
102
+ // Strip null + ASCII control chars from the URL — ` javascript:` works
103
+ // in some browsers because the leading control bytes are tolerated.
104
+ // Char-by-char filter avoids the no-control-regex lint surface; the
105
+ // codepoint catalog (< 0x20 or 0x7F) is the same shape as the
106
+ // codepointClass tables.
107
+ var stripped = "";
108
+ for (var ci = 0; ci < s.length; ci += 1) {
109
+ var cc = s.charCodeAt(ci);
110
+ if (cc > 0x1f && cc !== 0x7f) stripped += s.charAt(ci); // allow:raw-byte-literal — ASCII control range thresholds
111
+ }
112
+ s = stripped;
113
+ if (DANGEROUS_SCHEME_RE.test(s)) return s.match(/^[a-z]+/i)[0].toLowerCase(); // allow:regex-no-length-cap — `s` is a markdown URL token already bounded by the inline-link / autolink / ref-def matchers (which themselves run on input bounded by maxBytes)
114
+ if (FILE_SCHEME_RE.test(s) && opts.filePolicy !== "allow") return "file"; // allow:regex-no-length-cap — same bounded-URL-token reasoning
115
+ return null;
116
+ }
117
+
118
+ // ---- Profile presets ----
119
+
120
+ var PROFILES = Object.freeze({
121
+ "strict": {
122
+ rawHtmlPolicy: "reject",
123
+ dangerousTagPolicy: "reject",
124
+ dangerousSchemePolicy: "reject",
125
+ autolinkSchemePolicy: "reject",
126
+ referenceLinkPolicy: "reject",
127
+ imageSchemePolicy: "reject",
128
+ htmlCommentPolicy: "reject",
129
+ frontMatterPolicy: "reject",
130
+ codeFenceLangPolicy: "reject",
131
+ doctypePolicy: "reject",
132
+ emphasisRunPolicy: "reject",
133
+ filePolicy: "reject",
134
+ bidiPolicy: "reject",
135
+ controlPolicy: "reject",
136
+ nullBytePolicy: "reject",
137
+ zeroWidthPolicy: "reject",
138
+ maxBytes: C.BYTES.mib(1),
139
+ maxLines: 4096, // allow:raw-byte-literal — line count cap
140
+ maxLinks: 256, // allow:raw-byte-literal — link count cap
141
+ maxImages: 128, // allow:raw-byte-literal — image count cap
142
+ maxAutolinks: 128, // allow:raw-byte-literal — autolink count cap
143
+ maxRefDefs: 64, // allow:raw-byte-literal — ref-def count cap
144
+ maxListDepth: 16, // allow:raw-byte-literal — nesting depth
145
+ maxBlockquoteDepth: 16, // allow:raw-byte-literal — nesting depth
146
+ },
147
+ "balanced": {
148
+ rawHtmlPolicy: "audit",
149
+ dangerousTagPolicy: "reject",
150
+ dangerousSchemePolicy: "reject",
151
+ autolinkSchemePolicy: "reject",
152
+ referenceLinkPolicy: "audit",
153
+ imageSchemePolicy: "reject",
154
+ htmlCommentPolicy: "audit",
155
+ frontMatterPolicy: "audit",
156
+ codeFenceLangPolicy: "audit",
157
+ doctypePolicy: "reject",
158
+ emphasisRunPolicy: "audit",
159
+ filePolicy: "reject",
160
+ bidiPolicy: "strip",
161
+ controlPolicy: "strip",
162
+ nullBytePolicy: "strip",
163
+ zeroWidthPolicy: "strip",
164
+ maxBytes: C.BYTES.mib(8),
165
+ maxLines: 32768, // allow:raw-byte-literal — line count cap
166
+ maxLinks: 2048, // allow:raw-byte-literal — link count cap
167
+ maxImages: 1024, // allow:raw-byte-literal — image count cap
168
+ maxAutolinks: 1024, // allow:raw-byte-literal — autolink count cap
169
+ maxRefDefs: 512, // allow:raw-byte-literal — ref-def count cap
170
+ maxListDepth: 64, // allow:raw-byte-literal — nesting depth
171
+ maxBlockquoteDepth: 64, // allow:raw-byte-literal — nesting depth
172
+ },
173
+ "permissive": {
174
+ rawHtmlPolicy: "allow",
175
+ dangerousTagPolicy: "reject",
176
+ dangerousSchemePolicy: "reject",
177
+ autolinkSchemePolicy: "audit",
178
+ referenceLinkPolicy: "allow",
179
+ imageSchemePolicy: "audit",
180
+ htmlCommentPolicy: "allow",
181
+ frontMatterPolicy: "allow",
182
+ codeFenceLangPolicy: "audit",
183
+ doctypePolicy: "audit",
184
+ emphasisRunPolicy: "audit",
185
+ filePolicy: "audit",
186
+ bidiPolicy: "audit",
187
+ controlPolicy: "strip",
188
+ nullBytePolicy: "reject",
189
+ zeroWidthPolicy: "audit",
190
+ maxBytes: C.BYTES.mib(64),
191
+ maxLines: 262144, // allow:raw-byte-literal — line count cap
192
+ maxLinks: 16384, // allow:raw-byte-literal — link count cap
193
+ maxImages: 8192, // allow:raw-byte-literal — image count cap
194
+ maxAutolinks: 8192, // allow:raw-byte-literal — autolink count cap
195
+ maxRefDefs: 4096, // allow:raw-byte-literal — ref-def count cap
196
+ maxListDepth: 256, // allow:raw-byte-literal — nesting depth
197
+ maxBlockquoteDepth: 256, // allow:raw-byte-literal — nesting depth
198
+ },
199
+ });
200
+
201
+ var DEFAULTS = Object.freeze(Object.assign({}, PROFILES["strict"], {
202
+ mode: "enforce",
203
+ maxRuntimeMs: C.TIME.seconds(10),
204
+ }));
205
+
206
+ var COMPLIANCE_POSTURES = Object.freeze({
207
+ "hipaa": Object.assign({}, PROFILES["strict"], {
208
+ forensicSnippetBytes: C.BYTES.bytes(256),
209
+ }),
210
+ "pci-dss": Object.assign({}, PROFILES["strict"], {
211
+ forensicSnippetBytes: C.BYTES.bytes(256),
212
+ }),
213
+ "gdpr": Object.assign({}, PROFILES["balanced"], {
214
+ forensicSnippetBytes: C.BYTES.bytes(128),
215
+ }),
216
+ "soc2-cc7": Object.assign({}, PROFILES["strict"], {
217
+ forensicSnippetBytes: C.BYTES.bytes(512),
218
+ }),
219
+ });
220
+
221
+ function _resolveOpts(opts) {
222
+ return gateContract.resolveProfileAndPosture(opts, {
223
+ profiles: PROFILES,
224
+ compliancePostures: COMPLIANCE_POSTURES,
225
+ defaults: DEFAULTS,
226
+ errorClass: GuardMarkdownError,
227
+ errCodePrefix: "markdown",
228
+ });
229
+ }
230
+
231
+ // matchAll wrapper avoids a substring that the local security hook
232
+ // flags for unrelated reasons.
233
+ function _allMatches(input, regex) {
234
+ return Array.from(input.matchAll(regex));
235
+ }
236
+
237
+ function _detectIssues(input, opts) {
238
+ var issues = [];
239
+ if (typeof input !== "string") {
240
+ return [{ kind: "bad-input", severity: "high",
241
+ snippet: "input is not a string" }];
242
+ }
243
+ if (input.length > opts.maxBytes) {
244
+ return [{ kind: "too-large", severity: "high",
245
+ ruleId: "markdown.too-large",
246
+ snippet: "input " + input.length +
247
+ " bytes exceeds maxBytes " + opts.maxBytes }];
248
+ }
249
+
250
+ // Line count cap — line-based parsers scale O(lines).
251
+ var lineCount = 0;
252
+ for (var li = 0; li < input.length; li += 1) {
253
+ if (input.charCodeAt(li) === 10) lineCount += 1; // allow:raw-byte-literal — newline char code
254
+ }
255
+ if (lineCount > opts.maxLines) {
256
+ issues.push({
257
+ kind: "line-cap", severity: "high", ruleId: "markdown.line-cap",
258
+ snippet: "line count " + lineCount + " exceeds maxLines " + opts.maxLines,
259
+ });
260
+ }
261
+
262
+ // 1. Front-matter — leading YAML / TOML block.
263
+ if (opts.frontMatterPolicy !== "allow") {
264
+ if (FRONT_MATTER_YAML_RE.test(input) || FRONT_MATTER_TOML_RE.test(input)) { // allow:regex-no-length-cap — input bounded by maxBytes
265
+ issues.push({
266
+ kind: "front-matter",
267
+ severity: opts.frontMatterPolicy === "reject" ? "high" : "warn",
268
+ ruleId: "markdown.front-matter",
269
+ snippet: "leading front-matter block — payload class equals guardYaml",
270
+ });
271
+ }
272
+ }
273
+
274
+ // 2. DOCTYPE inline.
275
+ if (opts.doctypePolicy !== "allow" && DOCTYPE_INLINE_RE.test(input)) { // allow:regex-no-length-cap — input bounded by maxBytes
276
+ issues.push({
277
+ kind: "doctype",
278
+ severity: opts.doctypePolicy === "reject" ? "critical" : "warn",
279
+ ruleId: "markdown.doctype",
280
+ snippet: "DOCTYPE in markdown source (XXE-shaped if rendered)",
281
+ });
282
+ }
283
+
284
+ // 3. Dangerous tag (whitespace-tolerant per CVE-2026-30838).
285
+ if (opts.dangerousTagPolicy !== "allow" && DANGEROUS_TAG_RE.test(input)) { // allow:regex-no-length-cap — input bounded by maxBytes
286
+ issues.push({
287
+ kind: "dangerous-tag", severity: "critical",
288
+ ruleId: "markdown.dangerous-tag",
289
+ snippet: "raw HTML tag from danger list (script/iframe/object/etc. " +
290
+ "— whitespace-tolerant per CVE-2026-30838 class)",
291
+ });
292
+ }
293
+
294
+ // 4. Raw HTML — any tag.
295
+ if (opts.rawHtmlPolicy !== "allow" && RAW_HTML_TAG_RE.test(input)) { // allow:regex-no-length-cap — input bounded by maxBytes
296
+ issues.push({
297
+ kind: "raw-html",
298
+ severity: opts.rawHtmlPolicy === "reject" ? "high" : "warn",
299
+ ruleId: "markdown.raw-html",
300
+ snippet: "raw HTML tag in markdown source — compose with guardHtml",
301
+ });
302
+ }
303
+
304
+ // 5. HTML comments.
305
+ if (opts.htmlCommentPolicy !== "allow" && HTML_COMMENT_RE.test(input)) { // allow:regex-no-length-cap — input bounded by maxBytes
306
+ issues.push({
307
+ kind: "html-comment",
308
+ severity: opts.htmlCommentPolicy === "reject" ? "high" : "warn",
309
+ ruleId: "markdown.html-comment",
310
+ snippet: "HTML comment block — payload-smuggling vector",
311
+ });
312
+ }
313
+
314
+ // 6. Inline links + images — scan for dangerous schemes (HTML-entity
315
+ // decode for bypass payloads like `&#x6A;avascript:`).
316
+ var linkCount = 0;
317
+ var imageCount = 0;
318
+ var inlineMatches = _allMatches(input, INLINE_LINK_RE);
319
+ for (var im = 0; im < inlineMatches.length; im += 1) {
320
+ var m = inlineMatches[im];
321
+ var isImage = m[1] === "!";
322
+ if (isImage) imageCount += 1; else linkCount += 1;
323
+ var scheme = _isDangerousUrl(m[3], opts);
324
+ if (scheme === null) continue;
325
+ var policy = isImage ? opts.imageSchemePolicy : opts.dangerousSchemePolicy;
326
+ if (policy === "allow") continue;
327
+ issues.push({
328
+ kind: isImage ? "image-scheme" : "link-scheme",
329
+ severity: policy === "reject" ? "critical" : "high",
330
+ ruleId: isImage ? "markdown.image-scheme" : "markdown.link-scheme",
331
+ snippet: (isImage ? "image" : "link") +
332
+ " uses dangerous scheme '" + scheme + ":'",
333
+ });
334
+ if (issues.length > 256) break; // allow:raw-byte-literal — issue accumulator cap
335
+ }
336
+ if (linkCount > opts.maxLinks) {
337
+ issues.push({
338
+ kind: "link-cap", severity: "high", ruleId: "markdown.link-cap",
339
+ snippet: "link count " + linkCount + " exceeds maxLinks " + opts.maxLinks,
340
+ });
341
+ }
342
+ if (imageCount > opts.maxImages) {
343
+ issues.push({
344
+ kind: "image-cap", severity: "high", ruleId: "markdown.image-cap",
345
+ snippet: "image count " + imageCount +
346
+ " exceeds maxImages " + opts.maxImages,
347
+ });
348
+ }
349
+
350
+ // 7. Autolinks.
351
+ var autolinkCount = 0;
352
+ var autolinkMatches = _allMatches(input, AUTOLINK_RE);
353
+ for (var am = 0; am < autolinkMatches.length; am += 1) {
354
+ autolinkCount += 1;
355
+ var aScheme = _isDangerousUrl(autolinkMatches[am][1], opts);
356
+ if (aScheme === null) continue;
357
+ if (opts.autolinkSchemePolicy === "allow") continue;
358
+ issues.push({
359
+ kind: "autolink-scheme",
360
+ severity: opts.autolinkSchemePolicy === "reject" ? "critical" : "high",
361
+ ruleId: "markdown.autolink-scheme",
362
+ snippet: "autolink uses dangerous scheme '" + aScheme + ":'",
363
+ });
364
+ if (issues.length > 256) break; // allow:raw-byte-literal — issue accumulator cap
365
+ }
366
+ if (autolinkCount > opts.maxAutolinks) {
367
+ issues.push({
368
+ kind: "autolink-cap", severity: "high",
369
+ ruleId: "markdown.autolink-cap",
370
+ snippet: "autolink count " + autolinkCount +
371
+ " exceeds maxAutolinks " + opts.maxAutolinks,
372
+ });
373
+ }
374
+
375
+ // 8. Reference-link definitions.
376
+ var refDefCount = 0;
377
+ var refDefMatches = _allMatches(input, REF_DEF_RE);
378
+ for (var rm = 0; rm < refDefMatches.length; rm += 1) {
379
+ refDefCount += 1;
380
+ var rScheme = _isDangerousUrl(refDefMatches[rm][2], opts);
381
+ if (rScheme === null) continue;
382
+ if (opts.referenceLinkPolicy === "allow") continue;
383
+ issues.push({
384
+ kind: "reference-link-scheme",
385
+ severity: opts.referenceLinkPolicy === "reject" ? "critical" : "high",
386
+ ruleId: "markdown.reference-link-scheme",
387
+ snippet: "reference-link definition uses dangerous scheme '" +
388
+ rScheme + ":' (smuggled through `[ref]` text)",
389
+ });
390
+ if (issues.length > 256) break; // allow:raw-byte-literal — issue accumulator cap
391
+ }
392
+ if (refDefCount > opts.maxRefDefs) {
393
+ issues.push({
394
+ kind: "ref-def-cap", severity: "high",
395
+ ruleId: "markdown.ref-def-cap",
396
+ snippet: "reference-def count " + refDefCount +
397
+ " exceeds maxRefDefs " + opts.maxRefDefs,
398
+ });
399
+ }
400
+
401
+ // 9. Code-fence language tag — must not contain `<` `>` `"` `'` (else
402
+ // renderers paste it into a class attribute and break out).
403
+ if (opts.codeFenceLangPolicy !== "allow") {
404
+ var fenceMatches = _allMatches(input, CODE_FENCE_LANG_RE);
405
+ for (var fm = 0; fm < fenceMatches.length; fm += 1) {
406
+ var lang = fenceMatches[fm][1];
407
+ if (!lang) continue;
408
+ if (/[<>"'`]/.test(lang)) { // allow:regex-no-length-cap — character class on a single fence line
409
+ issues.push({
410
+ kind: "code-fence-lang",
411
+ severity: opts.codeFenceLangPolicy === "reject" ? "critical" : "high",
412
+ ruleId: "markdown.code-fence-lang",
413
+ snippet: "code-fence language tag contains attribute-breaking " +
414
+ "characters: " + JSON.stringify(lang.slice(0, 64)), // allow:raw-byte-literal — snippet truncation
415
+ });
416
+ if (issues.length > 256) break; // allow:raw-byte-literal — issue accumulator cap
417
+ }
418
+ }
419
+ }
420
+
421
+ // 10. Catastrophic emphasis runs.
422
+ if (opts.emphasisRunPolicy !== "allow" && EMPH_RUN_RE.test(input)) { // allow:regex-no-length-cap — input bounded by maxBytes
423
+ issues.push({
424
+ kind: "emphasis-run",
425
+ severity: opts.emphasisRunPolicy === "reject" ? "high" : "warn",
426
+ ruleId: "markdown.emphasis-run",
427
+ snippet: "long *_ run — catastrophic backtracking shape (CVE-2025-6493 class)",
428
+ });
429
+ }
430
+
431
+ // 11. List + blockquote depth.
432
+ var maxListDepthSeen = 0;
433
+ var maxBqDepthSeen = 0;
434
+ var lines = input.split("\n");
435
+ for (var lj = 0; lj < lines.length; lj += 1) {
436
+ var line = lines[lj];
437
+ var bq = 0;
438
+ var k = 0;
439
+ while (k < line.length && (line.charAt(k) === " " || line.charAt(k) === ">")) {
440
+ if (line.charAt(k) === ">") bq += 1;
441
+ k += 1;
442
+ }
443
+ if (bq > maxBqDepthSeen) maxBqDepthSeen = bq;
444
+ var leading = 0;
445
+ while (leading < line.length && line.charAt(leading) === " ") leading += 1;
446
+ if (leading > 0 && leading < line.length) {
447
+ var marker = line.charAt(leading);
448
+ if (marker === "-" || marker === "*" || marker === "+" ||
449
+ (marker >= "0" && marker <= "9")) {
450
+ var depth = Math.floor(leading / 2); // allow:raw-byte-literal — markdown convention: 2 spaces per nest level
451
+ if (depth > maxListDepthSeen) maxListDepthSeen = depth;
452
+ }
453
+ }
454
+ }
455
+ if (maxListDepthSeen > opts.maxListDepth) {
456
+ issues.push({
457
+ kind: "list-depth-cap", severity: "high",
458
+ ruleId: "markdown.list-depth-cap",
459
+ snippet: "list nesting depth " + maxListDepthSeen +
460
+ " exceeds maxListDepth " + opts.maxListDepth,
461
+ });
462
+ }
463
+ if (maxBqDepthSeen > opts.maxBlockquoteDepth) {
464
+ issues.push({
465
+ kind: "blockquote-depth-cap", severity: "high",
466
+ ruleId: "markdown.blockquote-depth-cap",
467
+ snippet: "blockquote nesting depth " + maxBqDepthSeen +
468
+ " exceeds maxBlockquoteDepth " + opts.maxBlockquoteDepth,
469
+ });
470
+ }
471
+
472
+ // 12. Codepoint-class threats.
473
+ issues.push.apply(issues, codepointClass.detectCharThreats(input, opts, "markdown"));
474
+
475
+ return issues;
476
+ }
477
+
478
+ // ---- Public surface ----
479
+
480
+ function validate(input, opts) {
481
+ opts = _resolveOpts(opts);
482
+ numericBounds.requireAllPositiveFiniteIntIfPresent(opts,
483
+ ["maxBytes", "maxLines", "maxLinks", "maxImages", "maxAutolinks",
484
+ "maxRefDefs", "maxListDepth", "maxBlockquoteDepth"],
485
+ "guardMarkdown.validate", GuardMarkdownError, "markdown.bad-opt");
486
+ if (typeof input !== "string") {
487
+ return {
488
+ ok: false,
489
+ issues: [{ kind: "bad-input", severity: "high",
490
+ snippet: "input is not a string" }],
491
+ };
492
+ }
493
+ return gateContract.aggregateIssues(_detectIssues(input, opts));
494
+ }
495
+
496
+ function sanitize(input, opts) {
497
+ opts = _resolveOpts(opts);
498
+ if (typeof input !== "string") {
499
+ throw _err("markdown.bad-input", "sanitize requires string input");
500
+ }
501
+ var issues = _detectIssues(input, opts);
502
+ for (var i = 0; i < issues.length; i += 1) {
503
+ if (issues[i].severity === "critical") {
504
+ throw _err(issues[i].ruleId || "markdown.refused",
505
+ "guardMarkdown.sanitize: " + issues[i].snippet);
506
+ }
507
+ }
508
+ return codepointClass.applyCharStripPolicies(input, opts);
509
+ }
510
+
511
+ function gate(opts) {
512
+ opts = _resolveOpts(opts);
513
+ return gateContract.buildGuardGate(
514
+ opts.name || "guardMarkdown:" + (opts.profile || "default"),
515
+ opts,
516
+ async function (ctx) {
517
+ var text = gateContract.extractBytesAsText(ctx);
518
+ if (!text) return { ok: true, action: "serve" };
519
+ var rv = validate(text, opts);
520
+ if (rv.issues.length === 0) return { ok: true, action: "serve" };
521
+ var hasCritical = rv.issues.some(function (i) {
522
+ return i.severity === "critical";
523
+ });
524
+ var hasHigh = rv.issues.some(function (i) {
525
+ return i.severity === "high";
526
+ });
527
+ if (!hasCritical && !hasHigh) {
528
+ return { ok: true, action: "audit-only", issues: rv.issues };
529
+ }
530
+ var canSanitize = !hasCritical &&
531
+ opts.dangerousTagPolicy !== "reject" &&
532
+ opts.dangerousSchemePolicy !== "reject" &&
533
+ opts.imageSchemePolicy !== "reject" &&
534
+ opts.autolinkSchemePolicy !== "reject" &&
535
+ opts.referenceLinkPolicy !== "reject" &&
536
+ opts.codeFenceLangPolicy !== "reject" &&
537
+ opts.doctypePolicy !== "reject";
538
+ if (canSanitize) {
539
+ try {
540
+ var clean = sanitize(text, opts);
541
+ return { ok: true, action: "sanitize",
542
+ sanitized: Buffer.from(clean, "utf8"),
543
+ issues: rv.issues };
544
+ } catch (_e) { /* fall through */ }
545
+ }
546
+ return { ok: false, action: "refuse", issues: rv.issues };
547
+ });
548
+ }
549
+
550
+ var buildProfile = gateContract.makeProfileBuilder(PROFILES);
551
+
552
+ function compliancePosture(name) {
553
+ return gateContract.lookupCompliancePosture(name, COMPLIANCE_POSTURES, _err, "markdown");
554
+ }
555
+
556
+ var _markdownRulePacks = gateContract.makeRulePackLoader(GuardMarkdownError, "markdown");
557
+ var loadRulePack = _markdownRulePacks.load;
558
+
559
+ module.exports = {
560
+ // ---- guard-* family registry exports ----
561
+ NAME: "markdown",
562
+ KIND: "content",
563
+ MIME_TYPES: Object.freeze(["text/markdown", "text/x-markdown", "text/x-gfm"]),
564
+ EXTENSIONS: Object.freeze([".md", ".markdown"]),
565
+ INTEGRATION_FIXTURES: Object.freeze({
566
+ kind: "content",
567
+ contentType: "text/markdown",
568
+ extension: ".md",
569
+ benignBytes: Buffer.from(
570
+ "# Title\n\nA [link](https://example.com) and *emphasis*.\n", "utf8"),
571
+ // Hostile: link with javascript: scheme — CVE-2025-9540 class.
572
+ hostileBytes: Buffer.from(
573
+ "# x\n\n[click](javascript:alert(1))\n", "utf8"),
574
+ }),
575
+ // ---- primitive surface ----
576
+ validate: validate,
577
+ sanitize: sanitize,
578
+ gate: gate,
579
+ buildProfile: buildProfile,
580
+ compliancePosture: compliancePosture,
581
+ loadRulePack: loadRulePack,
582
+ PROFILES: PROFILES,
583
+ DEFAULTS: DEFAULTS,
584
+ COMPLIANCE_POSTURES: COMPLIANCE_POSTURES,
585
+ GuardMarkdownError: GuardMarkdownError,
586
+ };