@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,816 @@
1
+ "use strict";
2
+ /**
3
+ * guard-csv — CSV content-safety primitive (b.guardCsv).
4
+ *
5
+ * Wraps lib/csv.js (RFC 4180 parse + stringify) with the broader threat
6
+ * catalog operators face when emitting CSVs from user-supplied data,
7
+ * plus the b.gateContract composition contract for use as a gate inside
8
+ * b.staticServe / b.fileUpload / b.mail / b.objectStore.
9
+ *
10
+ * var out = b.guardCsv.serialize(rows, { profile: "strict" });
11
+ * var rv = b.guardCsv.validate(input, { profile: "strict" });
12
+ * var s = b.guardCsv.sanitize(input, { profile: "balanced" });
13
+ * var g = b.guardCsv.gate({ profile: "strict" });
14
+ * b.staticServe.create({ contentSafety: { ".csv": g } });
15
+ *
16
+ * Threat-detection regex literals are composed PROGRAMMATICALLY from
17
+ * numeric codepoint ranges (BIDI_RANGES / C0_CTRL_RANGES / etc.) so the
18
+ * source file never embeds the attack characters themselves — only their
19
+ * codepoint numbers. This mirrors the way an attacker would compose the
20
+ * payload (programmatic codepoint emission, not literal typing) and
21
+ * keeps the source ASCII-clean (zero irregular-whitespace lint findings,
22
+ * no eslint-disable comments, machine-greppable as data tables).
23
+ *
24
+ * Threat catalog covered:
25
+ *
26
+ * - Formula injection (5 modes: prefix-tab / prefix-quote /
27
+ * wrap-with-quotes-and-prefix / reject / allowlist) with all 8
28
+ * ASCII triggers (= + - @ TAB CR LF |) plus full-width variants
29
+ * (U+FF1D / U+FF0B / U+FF0D / U+FF20) per OWASP locale catalog.
30
+ * - Dangerous-function denylist — WEBSERVICE / HYPERLINK / IMAGE /
31
+ * IMPORT* / RTD / DDE / CALL / GOOGLEFINANCE / GOOGLETRANSLATE.
32
+ * - Unicode bidi override (CVE-2021-42574 Trojan Source).
33
+ * - Homoglyph detection (Cyrillic / Greek / fullwidth Latin) when
34
+ * mixed with ASCII letters in the same cell.
35
+ * - C0 control chars (minus tab / lf / cr — those are dialect chars
36
+ * the parser handles separately).
37
+ * - Null byte detection (single canonical handling — strip / reject).
38
+ * - BOM injection mid-stream (any BOM past byte 0).
39
+ * - Zero-width chars (ZWSP / ZWNJ / ZWJ / WJ / SHY).
40
+ * - Dialect ambiguity (mixed line endings) — strict refuses.
41
+ * - CSV-bomb caps: per-cell, total, sanitize amplification ratio.
42
+ * - Numeric precision loss (above Number.MAX_SAFE_INTEGER → decimal
43
+ * string per policy).
44
+ * - Trailing whitespace exfiltration policy (trim / preserve / reject).
45
+ * - PII redaction via composes b.redact when piiPolicy === "redact".
46
+ * - Schema-bound serializer with type / regex / range / nullable
47
+ * validation.
48
+ * - Profiles: strict (OWASP-aligned, prefix-tab default per OWASP) /
49
+ * balanced / permissive / email-attachment.
50
+ * - Compliance postures: hipaa / pci-dss / gdpr / soc2-cc7.
51
+ * - Operator extensibility: profile composition, custom rules, hooks
52
+ * (beforeCheck / afterCheck / onIssue / onSanitize / onRefuse /
53
+ * onAudit), threat-intel feeds, sandbox isolation, snapshot tests.
54
+ */
55
+
56
+ var codepointClass = require("./codepoint-class");
57
+ var csv = require("./csv");
58
+ var C = require("./constants");
59
+ var lazyRequire = require("./lazy-require");
60
+ var numericBounds = require("./numeric-bounds");
61
+ var gateContract = require("./gate-contract");
62
+ var validateOpts = require("./validate-opts");
63
+ var { GuardCsvError } = require("./framework-error");
64
+
65
+ var observability = lazyRequire(function () { return require("./observability"); });
66
+ void observability;
67
+
68
+ var _err = GuardCsvError.factory;
69
+
70
+ // Shared codepoint catalog (BIDI / C0_CTRL / ZERO_WIDTH ranges and
71
+ // pre-compiled regexes) lives in lib/codepoint-class.js.
72
+
73
+ // CSV-specific homoglyph catalog — visual-confusable letter ranges that
74
+ // homoglyph against ASCII:
75
+ // Cyrillic U+0400-U+04FF
76
+ // Greek U+0370-U+03FF
77
+ // Fullwidth U+FF21-U+FF5A
78
+ var HOMOGLYPH_RANGES = [[0x0400, 0x04FF], [0x0370, 0x03FF], [0xFF21, 0xFF5A]];
79
+
80
+ // Formula-prefix triggers — every char that signals "this cell is a
81
+ // formula" to a spreadsheet evaluator:
82
+ // ASCII = + - @ TAB CR LF |
83
+ // Full-width = U+FF1D + U+FF0B - U+FF0D @ U+FF20
84
+ var FORMULA_PREFIX_CPS = [0x3D, 0x2B, 0x2D, 0x40, 0x09, 0x0D, 0x0A, 0x7C,
85
+ 0xFF1D, 0xFF0B, 0xFF0D, 0xFF20];
86
+
87
+ // Spreadsheet functions on the dangerous-function denylist (per OWASP /
88
+ // bishopfox / Veracode catalogs). Surfaced as critical regardless of the
89
+ // broader formulaInjectionPolicy.
90
+ var DANGEROUS_FUNCTIONS = Object.freeze([
91
+ "WEBSERVICE", "HYPERLINK", "IMAGE", "DDE", "RTD", "CALL",
92
+ "IMPORTXML", "IMPORTRANGE", "IMPORTHTML", "IMPORTFEED", "IMPORTDATA",
93
+ "GOOGLEFINANCE", "GOOGLETRANSLATE",
94
+ ]);
95
+
96
+ // ---- Codepoint helpers (proxied to lib/codepoint-class) ----
97
+
98
+ var HEX_RADIX = 16; // allow:raw-byte-literal — base-16 radix, not byte size
99
+ var _hex4 = codepointClass.hex4;
100
+ var _charClass = codepointClass.charClass;
101
+ var _fromCp = codepointClass.fromCp;
102
+ function _stringFromCps(cps) {
103
+ return cps.map(_fromCp).join("");
104
+ }
105
+
106
+ // ---- Compiled detectors ----
107
+ // Shared regexes pulled from lib/codepoint-class; CSV-specific ones
108
+ // (homoglyph + leading-BOM) compiled here.
109
+
110
+ var BIDI_RE = codepointClass.BIDI_RE;
111
+ var BIDI_RE_G = codepointClass.BIDI_RE_G;
112
+ var C0_CTRL_RE = codepointClass.C0_CTRL_RE;
113
+ var C0_CTRL_RE_G = codepointClass.C0_CTRL_RE_G;
114
+ var ZERO_WIDTH_RE = codepointClass.ZERO_WIDTH_RE;
115
+ var ZW_RE_G = codepointClass.ZW_RE_G;
116
+ var NULL_RE_G = codepointClass.NULL_RE_G;
117
+ var HOMOGLYPH_RE = new RegExp("[" + _charClass(HOMOGLYPH_RANGES) + "]"); // allow:dynamic-regex — codepoints from HOMOGLYPH_RANGES literal table
118
+ var HOMOGLYPH_G = new RegExp("[" + _charClass(HOMOGLYPH_RANGES) + "]", "g"); // allow:dynamic-regex — codepoints from HOMOGLYPH_RANGES literal table
119
+ var BOM_RE_LEAD = new RegExp("^" + _hex4(0xFEFF)); // allow:dynamic-regex — single literal codepoint U+FEFF
120
+ var BOM_RE_G = new RegExp(_hex4(0xFEFF), "g"); // allow:dynamic-regex — single literal codepoint U+FEFF
121
+
122
+ // Formula-trigger character class assembled from FORMULA_PREFIX_CPS:
123
+ // [=+\-@\t\r\u3D...] — used inside the "<line-start or delimiter>"
124
+ // formula-prefix scan and the dangerous-function scan.
125
+ var FORMULA_TRIGGER_CLASS = (function () {
126
+ var parts = FORMULA_PREFIX_CPS.map(function (cp) {
127
+ if (cp === 0x2D) return "\\-"; // hyphen literal inside char class
128
+ if (cp === 0x5C) return "\\\\"; // backslash safety
129
+ return _hex4(cp);
130
+ });
131
+ return "[" + parts.join("") + "]";
132
+ })();
133
+
134
+ // allow:dynamic-regex — class composed from FORMULA_PREFIX_CPS literal table
135
+ var FORMULA_SCAN_RE = new RegExp(
136
+ "(^|[,;\\t|])\"?(" + FORMULA_TRIGGER_CLASS + ")"
137
+ );
138
+ // allow:dynamic-regex — class composed from FORMULA_PREFIX_CPS literal table
139
+ var DANGER_SCAN_RE = new RegExp(
140
+ "(^|[,;\\t|])\"?" + FORMULA_TRIGGER_CLASS + "([A-Z][A-Z0-9_.]*)\\b",
141
+ "g"
142
+ );
143
+ // allow:dynamic-regex — class composed from FORMULA_PREFIX_CPS literal table
144
+ var ALLOWLIST_FIRST_WORD_RE = new RegExp(
145
+ "^" + FORMULA_TRIGGER_CLASS + "([A-Z]+)\\b"
146
+ );
147
+
148
+ var NULL_BYTE = codepointClass.NULL_BYTE;
149
+ var BOM_CHAR = codepointClass.BOM_CHAR;
150
+
151
+ // FORMULA_PREFIXES — array of single-char strings; iteration cost is
152
+ // the same as a Set for n=12. _stringFromCps keeps the source ASCII.
153
+ var FORMULA_PREFIXES = Object.freeze(_stringFromCps(FORMULA_PREFIX_CPS).split(""));
154
+
155
+ // Default row count cap for serialize. 2^20 ~ 1M rows.
156
+ var DEFAULT_MAX_ROWS = 0x100000;
157
+
158
+ // Forensic-snippet sizes per compliance posture.
159
+ var FORENSIC_SNIPPET_HIPAA = C.BYTES.bytes(256);
160
+ var FORENSIC_SNIPPET_PCI_DSS = C.BYTES.bytes(256);
161
+ var FORENSIC_SNIPPET_GDPR = C.BYTES.bytes(128);
162
+ var FORENSIC_SNIPPET_SOC2 = C.BYTES.bytes(512);
163
+
164
+ // ---- Profile presets ----
165
+
166
+ var PROFILES = Object.freeze({
167
+ "strict": {
168
+ formulaInjectionPolicy: "prefix-tab", // OWASP-recommended Excel-resistant mitigation
169
+ bidiCharPolicy: "reject",
170
+ homoglyphPolicy: "audit",
171
+ controlCharPolicy: "reject",
172
+ nullByteHandling: "reject",
173
+ trailingWhitespacePolicy: "trim",
174
+ bomPrefix: false,
175
+ dialectPolicy: "strict",
176
+ nullSemantics: "empty-string",
177
+ numericPrecisionPolicy: "decimal-string-above-safe-int",
178
+ dateFormat: "iso8601",
179
+ },
180
+ "balanced": {
181
+ formulaInjectionPolicy: "prefix-tab",
182
+ bidiCharPolicy: "strip",
183
+ homoglyphPolicy: "audit",
184
+ controlCharPolicy: "strip",
185
+ nullByteHandling: "strip",
186
+ trailingWhitespacePolicy: "preserve",
187
+ bomPrefix: false,
188
+ dialectPolicy: "strict",
189
+ nullSemantics: "empty-string",
190
+ numericPrecisionPolicy: "decimal-string-above-safe-int",
191
+ dateFormat: "iso8601",
192
+ },
193
+ "permissive": {
194
+ formulaInjectionPolicy: "prefix-tab",
195
+ bidiCharPolicy: "audit",
196
+ homoglyphPolicy: "audit",
197
+ controlCharPolicy: "strip",
198
+ nullByteHandling: "strip",
199
+ trailingWhitespacePolicy: "preserve",
200
+ bomPrefix: false,
201
+ dialectPolicy: "permissive",
202
+ nullSemantics: "empty-string",
203
+ numericPrecisionPolicy: "scientific",
204
+ dateFormat: "iso8601",
205
+ },
206
+ "email-attachment": {
207
+ formulaInjectionPolicy: "wrap-with-quotes-and-prefix",
208
+ bidiCharPolicy: "strip",
209
+ homoglyphPolicy: "audit",
210
+ controlCharPolicy: "strip",
211
+ nullByteHandling: "strip",
212
+ trailingWhitespacePolicy: "trim",
213
+ bomPrefix: true,
214
+ dialectPolicy: "strict",
215
+ nullSemantics: "empty-string",
216
+ numericPrecisionPolicy: "decimal-string-above-safe-int",
217
+ dateFormat: "iso8601",
218
+ },
219
+ });
220
+
221
+ var DEFAULTS = Object.freeze({
222
+ delimiter: ",",
223
+ lineEnding: "\r\n",
224
+ encoding: "utf-8",
225
+ locale: "C",
226
+ formulaInjectionPolicy: "prefix-tab",
227
+ formulasAllowlist: Object.freeze(["SUM", "AVERAGE", "COUNT", "MIN", "MAX", "IF", "CONCATENATE"]),
228
+ dangerousFunctions: DANGEROUS_FUNCTIONS,
229
+ bomPrefix: false,
230
+ maxRows: DEFAULT_MAX_ROWS,
231
+ maxCellBytes: C.BYTES.kib(64),
232
+ maxTotalBytes: C.BYTES.gib(1),
233
+ maxColumns: 0x400,
234
+ sanitizeAmplificationCap: 1.5,
235
+ controlCharPolicy: "reject",
236
+ bidiCharPolicy: "reject",
237
+ homoglyphPolicy: "audit",
238
+ nullByteHandling: "reject",
239
+ trailingWhitespacePolicy: "trim",
240
+ dialectPolicy: "strict",
241
+ nullSemantics: "empty-string",
242
+ nullMarker: "\\N",
243
+ preserveLeadingZeros: false,
244
+ preserveBooleanStrings: false,
245
+ preserveDateStrings: false,
246
+ dateFormat: "iso8601",
247
+ numericPrecisionPolicy: "decimal-string-above-safe-int",
248
+ piiPolicy: "preserve",
249
+ forensicSnippetBytes: 0,
250
+ mode: "enforce",
251
+ maxRuntimeMs: C.TIME.seconds(30),
252
+ });
253
+
254
+ var COMPLIANCE_POSTURES = Object.freeze({
255
+ "hipaa": {
256
+ formulaInjectionPolicy: "prefix-tab",
257
+ bidiCharPolicy: "reject",
258
+ controlCharPolicy: "reject",
259
+ nullByteHandling: "reject",
260
+ piiPolicy: "redact",
261
+ forensicSnippetBytes: FORENSIC_SNIPPET_HIPAA,
262
+ },
263
+ "pci-dss": {
264
+ formulaInjectionPolicy: "prefix-tab",
265
+ bidiCharPolicy: "reject",
266
+ controlCharPolicy: "reject",
267
+ nullByteHandling: "reject",
268
+ piiPolicy: "redact",
269
+ forensicSnippetBytes: FORENSIC_SNIPPET_PCI_DSS,
270
+ },
271
+ "gdpr": {
272
+ formulaInjectionPolicy: "prefix-tab",
273
+ bidiCharPolicy: "strip",
274
+ controlCharPolicy: "strip",
275
+ piiPolicy: "redact",
276
+ forensicSnippetBytes: FORENSIC_SNIPPET_GDPR,
277
+ },
278
+ "soc2-cc7": {
279
+ formulaInjectionPolicy: "prefix-tab",
280
+ bidiCharPolicy: "reject",
281
+ controlCharPolicy: "reject",
282
+ nullByteHandling: "reject",
283
+ forensicSnippetBytes: FORENSIC_SNIPPET_SOC2,
284
+ },
285
+ });
286
+
287
+ // ---- Internal helpers ----
288
+
289
+ function _firstMatch(text, re) {
290
+ if (typeof text !== "string") return null;
291
+ var m = text.match(re);
292
+ if (!m) return null;
293
+ return { index: m.index, char: m[0] };
294
+ }
295
+
296
+ function _detectIssues(text, opts) {
297
+ var issues = [];
298
+ if (typeof text !== "string") return issues;
299
+
300
+ var bomIdx = text.indexOf(BOM_CHAR);
301
+ if (bomIdx > 0 || (bomIdx === 0 && !opts.bomPrefix)) {
302
+ issues.push({
303
+ kind: "bom-mid-stream", severity: "high", ruleId: "csv.bom",
304
+ location: bomIdx, snippet: "BOM at byte " + bomIdx,
305
+ });
306
+ }
307
+
308
+ if (opts.bidiCharPolicy !== "allow") {
309
+ var bidiMatch = _firstMatch(text, BIDI_RE);
310
+ if (bidiMatch) {
311
+ issues.push({
312
+ kind: "bidi-override", severity: "critical", ruleId: "csv.bidi",
313
+ location: bidiMatch.index,
314
+ snippet: "Unicode bidi override at byte " + bidiMatch.index +
315
+ " (CVE-2021-42574 Trojan Source)",
316
+ });
317
+ }
318
+ }
319
+
320
+ if (opts.controlCharPolicy !== "allow") {
321
+ var ctrlMatch = _firstMatch(text, C0_CTRL_RE);
322
+ if (ctrlMatch) {
323
+ issues.push({
324
+ kind: "control-char", severity: "high", ruleId: "csv.control",
325
+ location: ctrlMatch.index,
326
+ snippet: "C0 control char U+" + ctrlMatch.char.charCodeAt(0).toString(HEX_RADIX) +
327
+ " at byte " + ctrlMatch.index,
328
+ });
329
+ }
330
+ }
331
+
332
+ var nullIdx = text.indexOf(NULL_BYTE);
333
+ if (nullIdx >= 0 && opts.nullByteHandling !== "allow") {
334
+ issues.push({
335
+ kind: "null-byte", severity: "critical", ruleId: "csv.null-byte",
336
+ location: nullIdx, snippet: "null byte at " + nullIdx,
337
+ });
338
+ }
339
+
340
+ if (opts.homoglyphPolicy !== "allow" && /[A-Za-z]/.test(text)) {
341
+ var homoMatch = _firstMatch(text, HOMOGLYPH_RE);
342
+ if (homoMatch) {
343
+ issues.push({
344
+ kind: "homoglyph", severity: "warn", ruleId: "csv.homoglyph",
345
+ location: homoMatch.index,
346
+ snippet: "homoglyph U+" + homoMatch.char.charCodeAt(0).toString(HEX_RADIX) +
347
+ " mixed with ASCII at byte " + homoMatch.index,
348
+ });
349
+ }
350
+ }
351
+
352
+ var zwMatch = _firstMatch(text, ZERO_WIDTH_RE);
353
+ if (zwMatch) {
354
+ issues.push({
355
+ kind: "zero-width", severity: "warn", ruleId: "csv.zero-width",
356
+ location: zwMatch.index,
357
+ snippet: "zero-width char U+" + zwMatch.char.charCodeAt(0).toString(HEX_RADIX) +
358
+ " at byte " + zwMatch.index,
359
+ });
360
+ }
361
+
362
+ if (opts.formulaInjectionPolicy !== "audit-only" && opts.formulaInjectionPolicy !== "allow") {
363
+ var formulaMatch = _firstMatch(text, FORMULA_SCAN_RE);
364
+ if (formulaMatch) {
365
+ issues.push({
366
+ kind: "formula-prefix-cell", severity: "critical",
367
+ ruleId: "csv.formula-injection",
368
+ location: formulaMatch.index,
369
+ snippet: "cell beginning with formula trigger " +
370
+ JSON.stringify(formulaMatch.char.slice(-1)) +
371
+ " at byte " + formulaMatch.index,
372
+ });
373
+ }
374
+ }
375
+
376
+ if (Array.isArray(opts.dangerousFunctions) && opts.dangerousFunctions.length > 0) {
377
+ var dangerIter = text.matchAll(DANGER_SCAN_RE);
378
+ var dangerMatch;
379
+ for (dangerMatch of dangerIter) {
380
+ var fn = dangerMatch[2].toUpperCase();
381
+ if (opts.dangerousFunctions.indexOf(fn) !== -1) {
382
+ issues.push({
383
+ kind: "dangerous-function", severity: "critical",
384
+ ruleId: "csv.dangerous-function",
385
+ location: dangerMatch.index,
386
+ snippet: "spreadsheet function " + JSON.stringify(fn) +
387
+ " is on the dangerous-function denylist (exfiltration / RCE vector)",
388
+ });
389
+ }
390
+ }
391
+ }
392
+
393
+ if (opts.dialectPolicy === "strict") {
394
+ var hasCrlf = text.indexOf("\r\n") !== -1;
395
+ var hasLfOnly = /[^\r]\n/.test(text);
396
+ var hasCrOnly = /\r[^\n]/.test(text);
397
+ if ((hasCrlf && hasLfOnly) || (hasCrlf && hasCrOnly) || (hasLfOnly && hasCrOnly)) {
398
+ issues.push({
399
+ kind: "dialect-mixed-line-endings", severity: "high",
400
+ ruleId: "csv.dialect", snippet: "mixed line endings",
401
+ });
402
+ }
403
+ }
404
+
405
+ return issues;
406
+ }
407
+
408
+ function _stripIssues(text, opts) {
409
+ if (typeof text !== "string") return text;
410
+ var out = text;
411
+ if (opts.bomPrefix !== true) out = out.replace(BOM_RE_LEAD, "");
412
+ out = out.replace(BOM_RE_G, "");
413
+ if (opts.bidiCharPolicy === "strip") out = out.replace(BIDI_RE_G, "");
414
+ if (opts.controlCharPolicy === "strip") out = out.replace(C0_CTRL_RE_G, "");
415
+ if (opts.nullByteHandling === "strip") out = out.replace(NULL_RE_G, "");
416
+ if (opts.homoglyphPolicy === "strip") out = out.replace(HOMOGLYPH_G, "");
417
+ out = out.replace(ZW_RE_G, "");
418
+ if (opts.trailingWhitespacePolicy === "trim") {
419
+ out = out.split("\n").map(function (line) {
420
+ return line.replace(/[ \t]+$/g, "");
421
+ }).join("\n");
422
+ }
423
+ return out;
424
+ }
425
+
426
+ function _resolveOpts(opts) {
427
+ return gateContract.resolveProfileAndPosture(opts, {
428
+ profiles: PROFILES,
429
+ compliancePostures: COMPLIANCE_POSTURES,
430
+ defaults: DEFAULTS,
431
+ errorClass: GuardCsvError,
432
+ errCodePrefix: "csv",
433
+ });
434
+ }
435
+
436
+ // ---- Cell-level escape with full threat application ----
437
+
438
+ function escapeCell(value, opts) {
439
+ opts = Object.assign({}, DEFAULTS, opts || {});
440
+ var str = value == null ? "" : String(value);
441
+
442
+ if (str.length > opts.maxCellBytes) {
443
+ throw _err("csv.cell-too-large", "cell exceeds maxCellBytes " + opts.maxCellBytes);
444
+ }
445
+
446
+ if (opts.nullByteHandling === "reject" && str.indexOf(NULL_BYTE) !== -1) {
447
+ throw _err("csv.null-byte", "cell contains null byte");
448
+ }
449
+ if (opts.controlCharPolicy === "reject" && C0_CTRL_RE.test(str)) { // allow:regex-no-length-cap — str length capped by maxCellBytes above
450
+ throw _err("csv.control", "cell contains C0 control character");
451
+ }
452
+ if (opts.bidiCharPolicy === "reject" && BIDI_RE.test(str)) { // allow:regex-no-length-cap — str length capped by maxCellBytes above
453
+ throw _err("csv.bidi", "cell contains Unicode bidi override (CVE-2021-42574)");
454
+ }
455
+
456
+ if (opts.nullByteHandling === "strip") str = str.replace(NULL_RE_G, "");
457
+ if (opts.controlCharPolicy === "strip") str = str.replace(C0_CTRL_RE_G, "");
458
+ if (opts.bidiCharPolicy === "strip") str = str.replace(BIDI_RE_G, "");
459
+
460
+ if (opts.trailingWhitespacePolicy === "trim") {
461
+ str = str.replace(/[ \t]+$/g, "");
462
+ } else if (opts.trailingWhitespacePolicy === "reject" && /[ \t]+$/.test(str)) {
463
+ throw _err("csv.trailing-whitespace", "cell has trailing whitespace");
464
+ }
465
+
466
+ if (typeof value === "number" &&
467
+ opts.numericPrecisionPolicy === "decimal-string-above-safe-int") {
468
+ if (Math.abs(value) > Number.MAX_SAFE_INTEGER) {
469
+ str = value.toLocaleString("en-US", {
470
+ useGrouping: false, maximumFractionDigits: 0,
471
+ });
472
+ }
473
+ }
474
+ if (typeof value === "bigint") {
475
+ if (opts.numericPrecisionPolicy === "reject-bigint") {
476
+ throw _err("csv.bigint", "BigInt values rejected per numericPrecisionPolicy");
477
+ }
478
+ str = value.toString();
479
+ }
480
+
481
+ if (str.length > 0 && FORMULA_PREFIXES.indexOf(str.charAt(0)) !== -1) {
482
+ var policy = opts.formulaInjectionPolicy;
483
+ if (policy === "reject") {
484
+ throw _err("csv.formula-injection",
485
+ "cell starts with formula prefix " + JSON.stringify(str.charAt(0)));
486
+ } else if (policy === "prefix-tab") {
487
+ str = "\t" + str;
488
+ } else if (policy === "prefix-quote") {
489
+ str = "'" + str;
490
+ } else if (policy === "wrap-with-quotes-and-prefix") {
491
+ str = "'" + str;
492
+ } else if (policy === "allowlist") {
493
+ var firstWord = str.match(ALLOWLIST_FIRST_WORD_RE);
494
+ if (firstWord && opts.formulasAllowlist.indexOf(firstWord[1]) === -1) {
495
+ str = "'" + str;
496
+ }
497
+ }
498
+ }
499
+
500
+ return str;
501
+ }
502
+
503
+ // ---- Schema-bound serializer ----
504
+
505
+ function schema(spec) {
506
+ validateOpts.requireObject(spec, "guardCsv.schema", GuardCsvError);
507
+ if (!Array.isArray(spec.columns)) {
508
+ throw _err("csv.bad-schema", "schema.columns must be an array");
509
+ }
510
+ var cols = spec.columns.slice();
511
+
512
+ return {
513
+ serialize: function (rows, opts) {
514
+ opts = opts || {};
515
+ var validated = [];
516
+ for (var ri = 0; ri < rows.length; ri += 1) {
517
+ var row = rows[ri];
518
+ var validatedRow = {};
519
+ for (var ci = 0; ci < cols.length; ci += 1) {
520
+ var col = cols[ci];
521
+ var v = row[col.name];
522
+ if (v == null) {
523
+ if (col.nullable === false) {
524
+ throw _err("csv.schema-null",
525
+ "column " + JSON.stringify(col.name) +
526
+ " is non-nullable; row " + ri + " has null");
527
+ }
528
+ validatedRow[col.name] = v;
529
+ continue;
530
+ }
531
+ if (col.type === "string" && typeof v !== "string") {
532
+ throw _err("csv.schema-type",
533
+ "column " + JSON.stringify(col.name) +
534
+ " expects string at row " + ri);
535
+ }
536
+ if (col.type === "number" && typeof v !== "number") {
537
+ throw _err("csv.schema-type",
538
+ "column " + JSON.stringify(col.name) +
539
+ " expects number at row " + ri);
540
+ }
541
+ if (col.type === "boolean" && typeof v !== "boolean") {
542
+ throw _err("csv.schema-type",
543
+ "column " + JSON.stringify(col.name) +
544
+ " expects boolean at row " + ri);
545
+ }
546
+ if (col.regex && !col.regex.test(String(v))) {
547
+ throw _err("csv.schema-regex",
548
+ "column " + JSON.stringify(col.name) +
549
+ " value " + JSON.stringify(v) +
550
+ " at row " + ri + " does not match regex " + col.regex);
551
+ }
552
+ if (col.type === "number" && typeof col.min === "number" && v < col.min) {
553
+ throw _err("csv.schema-range",
554
+ "column " + JSON.stringify(col.name) + " < min at row " + ri);
555
+ }
556
+ if (col.type === "number" && typeof col.max === "number" && v > col.max) {
557
+ throw _err("csv.schema-range",
558
+ "column " + JSON.stringify(col.name) + " > max at row " + ri);
559
+ }
560
+ validatedRow[col.name] = v;
561
+ }
562
+ validated.push(validatedRow);
563
+ }
564
+ return serialize(validated, Object.assign({
565
+ headers: cols.map(function (c) { return c.name; }),
566
+ }, opts));
567
+ },
568
+ validate: function (input, opts) {
569
+ return validate(input, Object.assign({ schema: spec }, opts || {}));
570
+ },
571
+ columns: cols,
572
+ };
573
+ }
574
+
575
+ // ---- Module-level entry points ----
576
+
577
+ function serialize(rows, opts) {
578
+ opts = _resolveOpts(opts);
579
+ numericBounds.requireAllPositiveFiniteIntIfPresent(opts,
580
+ ["maxRows", "maxCellBytes", "maxTotalBytes"],
581
+ "guardCsv.serialize", GuardCsvError, "csv.bad-opt");
582
+
583
+ if (!Array.isArray(rows)) {
584
+ throw _err("csv.bad-input",
585
+ "serialize: rows must be an array, got " + typeof rows);
586
+ }
587
+ if (rows.length > opts.maxRows) {
588
+ throw _err("csv.too-many-rows",
589
+ "row count " + rows.length + " exceeds maxRows " + opts.maxRows);
590
+ }
591
+
592
+ var redactor = (opts.piiPolicy === "redact" && opts.redact) ? opts.redact : null;
593
+
594
+ var escapedRows = [];
595
+ for (var ri = 0; ri < rows.length; ri += 1) {
596
+ var row = rows[ri];
597
+ var escapedRow;
598
+ if (Array.isArray(row)) {
599
+ escapedRow = row.map(function (v) {
600
+ var ev = escapeCell(v, opts);
601
+ if (Buffer.byteLength(ev, "utf8") > opts.maxCellBytes) {
602
+ throw _err("csv.cell-too-large",
603
+ "cell at row " + ri + " exceeds maxCellBytes " + opts.maxCellBytes);
604
+ }
605
+ if (redactor && typeof ev === "string") ev = redactor.string(ev);
606
+ return ev;
607
+ });
608
+ } else if (row !== null && typeof row === "object") {
609
+ escapedRow = {};
610
+ var keys = Object.keys(row);
611
+ if (keys.length > opts.maxColumns) {
612
+ throw _err("csv.too-many-columns",
613
+ "row " + ri + " has " + keys.length + " columns; max " + opts.maxColumns);
614
+ }
615
+ for (var ki = 0; ki < keys.length; ki += 1) {
616
+ var ev2 = escapeCell(row[keys[ki]], opts);
617
+ if (Buffer.byteLength(ev2, "utf8") > opts.maxCellBytes) {
618
+ throw _err("csv.cell-too-large",
619
+ "cell at row " + ri + " column " + JSON.stringify(keys[ki]) +
620
+ " exceeds maxCellBytes");
621
+ }
622
+ if (redactor && typeof ev2 === "string") ev2 = redactor.string(ev2);
623
+ escapedRow[keys[ki]] = ev2;
624
+ }
625
+ } else {
626
+ throw _err("csv.bad-input", "rows must be arrays or plain objects");
627
+ }
628
+ escapedRows.push(escapedRow);
629
+ }
630
+
631
+ var out = csv.stringify(escapedRows, {
632
+ delimiter: opts.delimiter,
633
+ quote: opts.quote || "\"",
634
+ eol: opts.lineEnding,
635
+ alwaysQuote: opts.alwaysQuote || false,
636
+ columns: opts.headers || null,
637
+ header: opts.headers !== false,
638
+ });
639
+
640
+ var totalBytes = Buffer.byteLength(out, "utf8");
641
+ if (opts.bomPrefix) {
642
+ out = BOM_CHAR + out;
643
+ totalBytes += 3;
644
+ }
645
+ if (totalBytes > opts.maxTotalBytes) {
646
+ throw _err("csv.total-too-large",
647
+ "output size " + totalBytes + " bytes exceeds maxTotalBytes " + opts.maxTotalBytes);
648
+ }
649
+ return out;
650
+ }
651
+
652
+ function validate(input, opts) {
653
+ opts = _resolveOpts(opts);
654
+ return gateContract.runIssueValidator(input, opts, _detectIssues);
655
+ }
656
+
657
+ function sanitize(input, opts) {
658
+ opts = _resolveOpts(opts);
659
+ var text = typeof input === "string"
660
+ ? input
661
+ : (Buffer.isBuffer(input) ? input.toString("utf8") : null);
662
+ if (text == null) {
663
+ throw _err("csv.bad-input", "sanitize requires string or Buffer input");
664
+ }
665
+ var sanitized = _stripIssues(text, opts);
666
+ var amplification = sanitized.length / Math.max(text.length, 1);
667
+ if (amplification > opts.sanitizeAmplificationCap) {
668
+ throw _err("csv.sanitize-amplified",
669
+ "sanitize grew output " + amplification.toFixed(2) +
670
+ "x; cap " + opts.sanitizeAmplificationCap);
671
+ }
672
+ return sanitized;
673
+ }
674
+
675
+ function detect(input) {
676
+ var text = typeof input === "string"
677
+ ? input
678
+ : (Buffer.isBuffer(input) ? input.toString("utf8") : null);
679
+ if (text == null) {
680
+ return {
681
+ delimiter: null, hasHeader: false, encoding: null,
682
+ lineEnding: null, dialect: "unknown", confidence: 0,
683
+ };
684
+ }
685
+ var crlf = (text.match(/\r\n/g) || []).length;
686
+ var lfOnly = (text.match(/[^\r]\n/g) || []).length;
687
+ var crOnly = (text.match(/\r[^\n]/g) || []).length;
688
+ var lineEnding = crlf >= lfOnly && crlf >= crOnly
689
+ ? "\r\n"
690
+ : (lfOnly >= crOnly ? "\n" : "\r");
691
+ var firstLine = text.split(/\r\n|\r|\n/)[0] || "";
692
+ var counts = { ",": 0, ";": 0, "\t": 0, "|": 0 };
693
+ for (var i = 0; i < firstLine.length; i += 1) {
694
+ var c = firstLine.charAt(i);
695
+ if (counts[c] !== undefined) counts[c] += 1;
696
+ }
697
+ var delim = ","; var max = 0;
698
+ Object.keys(counts).forEach(function (k) {
699
+ if (counts[k] > max) { max = counts[k]; delim = k; }
700
+ });
701
+ return {
702
+ delimiter: delim,
703
+ hasHeader: /^[A-Za-z]/.test(firstLine),
704
+ encoding: text.charCodeAt(0) === 0xFEFF ? "utf-8-sig" : "utf-8",
705
+ lineEnding: lineEnding,
706
+ dialect: (crlf > 0 && (lfOnly > 0 || crOnly > 0)) ? "mixed" : "consistent",
707
+ confidence: max > 0 ? 0.9 : 0.5,
708
+ };
709
+ }
710
+
711
+ // ---- Gate factory (b.gateContract shape) ----
712
+
713
+ function gate(opts) {
714
+ opts = _resolveOpts(opts);
715
+ return gateContract.buildGuardGate(
716
+ opts.name || "guardCsv:" + (opts.profile || "default"),
717
+ opts,
718
+ async function (ctx) {
719
+ var text = gateContract.extractBytesAsText(ctx);
720
+ if (!text) return { ok: true, action: "serve" };
721
+ var rv = validate(text, opts);
722
+
723
+ var operatorIssues = [];
724
+ if (Array.isArray(opts.operatorRules)) {
725
+ for (var ri = 0; ri < opts.operatorRules.length; ri += 1) {
726
+ var rule = opts.operatorRules[ri];
727
+ try {
728
+ if (rule.detect && rule.detect({ bytes: text, ctx: ctx })) {
729
+ operatorIssues.push({
730
+ kind: rule.id, severity: rule.severity || "warn",
731
+ ruleId: rule.id, snippet: rule.reason || rule.id,
732
+ });
733
+ }
734
+ } catch (_e) { /* operator rule best-effort */ }
735
+ }
736
+ }
737
+ var allIssues = rv.issues.concat(operatorIssues);
738
+
739
+ if (allIssues.length === 0) return { ok: true, action: "serve" };
740
+ var hasCritical = allIssues.some(function (i) {
741
+ return i.severity === "critical" || i.severity === "high";
742
+ });
743
+ if (!hasCritical) {
744
+ return { ok: true, action: "audit-only", issues: allIssues };
745
+ }
746
+
747
+ if (opts.formulaInjectionPolicy !== "reject" &&
748
+ opts.bidiCharPolicy !== "reject" &&
749
+ opts.controlCharPolicy !== "reject" &&
750
+ opts.nullByteHandling !== "reject") {
751
+ try {
752
+ var clean = sanitize(text, opts);
753
+ var hasFormulaIssue = allIssues.some(function (i) {
754
+ return i.kind === "formula-prefix-cell" ||
755
+ i.kind === "dangerous-function";
756
+ });
757
+ if (hasFormulaIssue) {
758
+ var parsedRows = csv.parse(clean, { header: false });
759
+ clean = serialize(parsedRows, Object.assign({}, opts, { headers: false }));
760
+ }
761
+ return {
762
+ ok: true, action: "sanitize",
763
+ sanitized: Buffer.from(clean, "utf8"),
764
+ issues: allIssues,
765
+ };
766
+ } catch (_e) { /* fall through to refuse */ }
767
+ }
768
+
769
+ return { ok: false, action: "refuse", issues: allIssues };
770
+ });
771
+ }
772
+
773
+ var buildProfile = gateContract.makeProfileBuilder(PROFILES);
774
+
775
+ function compliancePosture(name) {
776
+ return gateContract.lookupCompliancePosture(name, COMPLIANCE_POSTURES, _err, "csv");
777
+ }
778
+
779
+ var _csvRulePacks = gateContract.makeRulePackLoader(GuardCsvError, "csv");
780
+ var loadRulePack = _csvRulePacks.load;
781
+
782
+ module.exports = {
783
+ // ---- guard-* family registry exports (consumed by b.guardAll) ----
784
+ NAME: "csv",
785
+ KIND: "content", // content-bytes guard (consumes ctx.bytes)
786
+ MIME_TYPES: Object.freeze(["text/csv"]),
787
+ EXTENSIONS: Object.freeze([".csv"]),
788
+ // ---- adaptive integration-test fixtures (consumed by layer-5 host harness) ----
789
+ INTEGRATION_FIXTURES: Object.freeze({
790
+ kind: "content",
791
+ contentType: "text/csv",
792
+ extension: ".csv",
793
+ benignBytes: Buffer.from("name,age\r\nalice,30\r\n", "utf8"),
794
+ // Hostile: cell starts with formula trigger `=cmd|x` — strict
795
+ // profile prepends TAB so spreadsheets disarm at evaluation time;
796
+ // gate's check returns refuse for any critical/high issue.
797
+ hostileBytes: Buffer.from("name,formula\r\nalice,=cmd|x\r\n", "utf8"),
798
+ }),
799
+ // ---- primitive surface ----
800
+ serialize: serialize,
801
+ validate: validate,
802
+ sanitize: sanitize,
803
+ escapeCell: escapeCell,
804
+ detect: detect,
805
+ schema: schema,
806
+ gate: gate,
807
+ buildProfile: buildProfile,
808
+ compliancePosture: compliancePosture,
809
+ loadRulePack: loadRulePack,
810
+ PROFILES: PROFILES,
811
+ DEFAULTS: DEFAULTS,
812
+ COMPLIANCE_POSTURES: COMPLIANCE_POSTURES,
813
+ FORMULA_PREFIXES: FORMULA_PREFIXES,
814
+ DANGEROUS_FUNCTIONS: DANGEROUS_FUNCTIONS,
815
+ GuardCsvError: GuardCsvError,
816
+ };