@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,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
+ };