coldpin 0.0.0-stage → 1.5.1

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 (102) hide show
  1. package/ACCESSIBILITY.md +17 -0
  2. package/CHANGELOG.md +97 -0
  3. package/CONTRIBUTING.md +36 -0
  4. package/LICENSE +98 -0
  5. package/MAINTENANCE.md +33 -0
  6. package/README.md +142 -2
  7. package/SECURITY.md +34 -0
  8. package/TESTING.md +26 -0
  9. package/agents/coldpin-auditor.md +47 -0
  10. package/agents/coldpin-compliance.md +38 -0
  11. package/agents/coldpin-confusion-auditor.md +38 -0
  12. package/agents/coldpin-discoverer.md +37 -0
  13. package/agents/coldpin-forensics.md +38 -0
  14. package/agents/coldpin-inspector.md +37 -0
  15. package/agents/coldpin-manifest-auditor.md +38 -0
  16. package/assets/icon.svg +7 -0
  17. package/catalog/mcp-schema-pin.json +14 -0
  18. package/catalog/plugin.oms.sig +19 -0
  19. package/catalog/sigma/npx-suspicious-child-process-linux.yml +54 -0
  20. package/catalog/sigma/npx-suspicious-child-process.yml +49 -0
  21. package/catalog/triage-rules.json +104 -0
  22. package/docs/assets/readme-header.svg +21 -0
  23. package/docs/designs/SITEMAP.md +14 -0
  24. package/docs/designs/coldpin.md +68 -0
  25. package/docs/fact-ledger.md +36 -0
  26. package/docs/faq.md +31 -0
  27. package/docs/getting_started.md +62 -0
  28. package/docs/harnesses.md +45 -0
  29. package/docs/privacy.md +27 -0
  30. package/docs/verification/skill-inspector-self-audit.md +33 -0
  31. package/examples/.coldpin.policy.example.json +27 -0
  32. package/examples/.npmrc.example +8 -0
  33. package/examples/mcp_config.private-registry.example.json +42 -0
  34. package/hooks.json +47 -0
  35. package/lib/analysis/parity-and-bisect.mjs +1371 -0
  36. package/lib/analysis/static-triage.mjs +4572 -0
  37. package/lib/cache/sqlite-store.mjs +251 -0
  38. package/lib/cli.mjs +427 -0
  39. package/lib/compliance/audit-log.mjs +357 -0
  40. package/lib/config/policy.mjs +780 -0
  41. package/lib/core/path-confinement.mjs +289 -0
  42. package/lib/core/workflows.mjs +1205 -0
  43. package/lib/discovery/slopsquat-guard.mjs +289 -0
  44. package/lib/hook.mjs +1038 -0
  45. package/lib/intel/registry-osv.mjs +1681 -0
  46. package/lib/mcp/report-store.mjs +175 -0
  47. package/lib/mcp/server.mjs +1387 -0
  48. package/lib/mcp/stdio-transport.mjs +289 -0
  49. package/lib/mcp/tool-catalog.mjs +273 -0
  50. package/lib/mcp/types.mjs +95 -0
  51. package/lib/mcp.mjs +19 -0
  52. package/lib/quarantine/safe-unpack.mjs +568 -0
  53. package/lib/types.mjs +383 -0
  54. package/lib/verdict/engine-and-formatters.mjs +895 -0
  55. package/mcp_config.json +21 -0
  56. package/package.json +71 -3
  57. package/plugin.json +54 -0
  58. package/rules/AGENTS.md +18 -0
  59. package/rules/coldpin-incident-checklist.md +18 -0
  60. package/rules/coldpin-manifest-guard.md +14 -0
  61. package/server.json +38 -0
  62. package/skills/coldpin/BENCHMARK.md +166 -0
  63. package/skills/coldpin/SKILL.md +110 -0
  64. package/skills/coldpin/TEST.md +13 -0
  65. package/skills/coldpin/agents/openai.yaml +6 -0
  66. package/skills/coldpin/assets/icon.svg +7 -0
  67. package/skills/coldpin/assets/runtime-contract.yaml +105 -0
  68. package/skills/coldpin/evals/evals.json +60 -0
  69. package/skills/coldpin/references/aspect-compliance-audit.md +27 -0
  70. package/skills/coldpin/references/aspect-discovery.md +26 -0
  71. package/skills/coldpin/references/aspect-forensics-rea.md +26 -0
  72. package/skills/coldpin/references/aspect-inspection.md +26 -0
  73. package/skills/coldpin/references/aspect-manifest-confusion.md +26 -0
  74. package/skills/coldpin/references/enterprise-policy-schema.md +65 -0
  75. package/skills/coldpin/references/evidence-card-spec.md +27 -0
  76. package/skills/coldpin/references/rea-integration-playbook.md +34 -0
  77. package/skills/coldpin/references/threat-taxonomy.md +35 -0
  78. package/skills/coldpin/skill-card.md +62 -0
  79. package/skills/coldpin/skill.oms.sig +19 -0
  80. package/skills/coldpin/test_scenarios.yaml +61 -0
  81. package/skills/coldpin-audit/SKILL.md +39 -0
  82. package/skills/coldpin-incident/SKILL.md +37 -0
  83. package/src/analysis/parity-and-bisect.ts +1368 -0
  84. package/src/analysis/static-triage.ts +4569 -0
  85. package/src/cache/sqlite-store.ts +248 -0
  86. package/src/cli.ts +424 -0
  87. package/src/compliance/audit-log.ts +354 -0
  88. package/src/config/policy.ts +777 -0
  89. package/src/core/path-confinement.ts +286 -0
  90. package/src/core/workflows.ts +1202 -0
  91. package/src/discovery/slopsquat-guard.ts +286 -0
  92. package/src/hook.ts +1035 -0
  93. package/src/intel/registry-osv.ts +1678 -0
  94. package/src/mcp/report-store.ts +172 -0
  95. package/src/mcp/server.ts +1384 -0
  96. package/src/mcp/stdio-transport.ts +286 -0
  97. package/src/mcp/tool-catalog.ts +270 -0
  98. package/src/mcp/types.ts +92 -0
  99. package/src/mcp.ts +16 -0
  100. package/src/quarantine/safe-unpack.ts +565 -0
  101. package/src/types.ts +380 -0
  102. package/src/verdict/engine-and-formatters.ts +892 -0
@@ -0,0 +1,568 @@
1
+ import { createHash } from "node:crypto";
2
+ import { Readable, Transform } from "node:stream";
3
+ import { pipeline } from "node:stream/promises";
4
+ import { createGunzip } from "node:zlib";
5
+
6
+
7
+ const WINDOWS_RESERVED_NAMES = new Set([
8
+ "con",
9
+ "prn",
10
+ "aux",
11
+ "nul",
12
+ "com1",
13
+ "com2",
14
+ "com3",
15
+ "com4",
16
+ "com5",
17
+ "com6",
18
+ "com7",
19
+ "com8",
20
+ "com9",
21
+ "lpt1",
22
+ "lpt2",
23
+ "lpt3",
24
+ "lpt4",
25
+ "lpt5",
26
+ "lpt6",
27
+ "lpt7",
28
+ "lpt8",
29
+ "lpt9",
30
+ ]);
31
+
32
+ function readAsciiZ(buf , start , length ) {
33
+ let end = start;
34
+ const max = Math.min(buf.length, start + length);
35
+ while (end < max && buf[end] !== 0) end++;
36
+ return buf.subarray(start, end).toString("utf8");
37
+ }
38
+
39
+ function parseOctalOrBase256(buf , start , length ) {
40
+ const first = buf[start] ?? 0;
41
+ if ((first & 0x80) !== 0) {
42
+ // GNU base-256 big-endian unsigned integer
43
+ let val = first & 0x7f;
44
+ for (let i = 1; i < length; i++) {
45
+ val = val * 256 + (buf[start + i] ?? 0);
46
+ }
47
+ return val;
48
+ }
49
+ const str = readAsciiZ(buf, start, length).trim();
50
+ if (!str) return 0;
51
+ const parsed = Number.parseInt(str, 8);
52
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : -1;
53
+ }
54
+
55
+ function verifyTarHeaderChecksum(header ) {
56
+ const stored = parseOctalOrBase256(header, 148, 8);
57
+ if (stored < 0) return false;
58
+ let unsignedSum = 0;
59
+ let signedSum = 0;
60
+ for (let i = 0; i < 512; i++) {
61
+ const b = i >= 148 && i < 156 ? 0x20 : (header[i] ?? 0);
62
+ unsignedSum += b;
63
+ signedSum += b > 127 ? b - 256 : b;
64
+ }
65
+ return stored === unsignedSum || stored === signedSum;
66
+ }
67
+
68
+ const HIDDEN_ARCHIVE_UNICODE_RE = /[\u200b-\u200f\u202a-\u202e\u2060-\u2064\u2066-\u2069\ufeff\u00ad\u{e0000}-\u{e007f}]/u;
69
+
70
+ function parsePaxRecords(data ) {
71
+ const out = {};
72
+ let offset = 0;
73
+ while (offset < data.length) {
74
+ const spaceIdx = data.indexOf(0x20, offset);
75
+ if (spaceIdx === -1) return { records: out, malformed: true };
76
+ const lenStr = data.subarray(offset, spaceIdx).toString("ascii");
77
+ if (!/^\d+$/.test(lenStr)) return { records: out, malformed: true };
78
+ const recLen = Number.parseInt(lenStr, 10);
79
+ if (!Number.isFinite(recLen) || recLen <= spaceIdx - offset + 1 || offset + recLen > data.length) {
80
+ return { records: out, malformed: true };
81
+ }
82
+ if (data[offset + recLen - 1] !== 0x0a) {
83
+ return { records: out, malformed: true };
84
+ }
85
+ const record = data.subarray(spaceIdx + 1, offset + recLen - 1).toString("utf8");
86
+ const eqIdx = record.indexOf("=");
87
+ if (eqIdx <= 0) {
88
+ return { records: out, malformed: true };
89
+ }
90
+ out[record.slice(0, eqIdx)] = record.slice(eqIdx + 1);
91
+ offset += recLen;
92
+ }
93
+ return { records: out, malformed: false };
94
+ }
95
+
96
+ export function validateArchivePath(rawPath )
97
+
98
+
99
+
100
+ {
101
+ if (!rawPath || rawPath.includes("\0")) {
102
+ return { safe: false, normalized: rawPath, reason: "Empty path or embedded NUL byte" };
103
+ }
104
+ // Reject control characters
105
+ for (let i = 0; i < rawPath.length; i++) {
106
+ const code = rawPath.charCodeAt(i);
107
+ if (code < 0x20 || code === 0x7f) {
108
+ return { safe: false, normalized: rawPath, reason: "Control character in archive path" };
109
+ }
110
+ }
111
+ // Reject backslashes, Windows drive letters, NTFS ADS colons, leading slash
112
+ if (rawPath.includes("\\")) {
113
+ return { safe: false, normalized: rawPath, reason: "Backslash path separator rejected" };
114
+ }
115
+ if (rawPath.startsWith("/")) {
116
+ return { safe: false, normalized: rawPath, reason: "Absolute path rejected (Zip Slip)" };
117
+ }
118
+ if (/^[a-zA-Z]:/.test(rawPath) || rawPath.includes(":")) {
119
+ return { safe: false, normalized: rawPath, reason: "Drive letter or NTFS Alternate Data Stream colon rejected" };
120
+ }
121
+ if (/[<>"|?*]/.test(rawPath)) {
122
+ return { safe: false, normalized: rawPath, reason: "Windows-illegal filename character (< > \" | ? *) rejected" };
123
+ }
124
+ if (HIDDEN_ARCHIVE_UNICODE_RE.test(rawPath)) {
125
+ return { safe: false, normalized: rawPath, reason: "Hidden or bidirectional Unicode character in archive path rejected" };
126
+ }
127
+
128
+ let cleaned = rawPath.replace(/^\.\//, "");
129
+ if (cleaned.startsWith("package/")) {
130
+ cleaned = cleaned.slice("package/".length);
131
+ } else if (cleaned === "package") {
132
+ cleaned = "";
133
+ }
134
+ cleaned = cleaned.replace(/\/+$/, "");
135
+ if (!cleaned) return { safe: true, normalized: "" };
136
+
137
+ const segments = cleaned.split("/");
138
+ for (const seg of segments) {
139
+ if (!seg || seg === "." || seg === "..") {
140
+ return { safe: false, normalized: rawPath, reason: `Path traversal segment '${seg}' rejected (Zip Slip)` };
141
+ }
142
+ if (seg.endsWith(".") || seg.endsWith(" ")) {
143
+ return { safe: false, normalized: rawPath, reason: `Windows trailing dot/space segment '${seg}' rejected` };
144
+ }
145
+ const baseName = seg.split(".")[0]?.toLowerCase() ?? "";
146
+ if (WINDOWS_RESERVED_NAMES.has(baseName)) {
147
+ return { safe: false, normalized: rawPath, reason: `Windows reserved device name '${seg}' rejected` };
148
+ }
149
+ }
150
+
151
+ return { safe: true, normalized: segments.join("/") };
152
+ }
153
+
154
+ async function gunzipWithHardCap(
155
+ compressed ,
156
+ maxUncompressedBytes ,
157
+ ) {
158
+ const chunks = [];
159
+ let totalBytes = 0;
160
+ let capped = false;
161
+
162
+ const capTransform = new Transform({
163
+ transform(chunk , _enc, cb) {
164
+ totalBytes += chunk.length;
165
+ if (totalBytes > maxUncompressedBytes) {
166
+ capped = true;
167
+ cb(new Error(`UNCOMPRESSED_CAP_EXCEEDED:${maxUncompressedBytes}`));
168
+ return;
169
+ }
170
+ chunks.push(Buffer.from(chunk));
171
+ cb();
172
+ },
173
+ });
174
+
175
+ try {
176
+ await pipeline(Readable.from([compressed]), createGunzip(), capTransform);
177
+ return { ok: true, buffer: Buffer.concat(chunks), totalBytes, capped: false };
178
+ } catch (err) {
179
+ const msg = err instanceof Error ? err.message : String(err);
180
+ return { ok: false, buffer: Buffer.alloc(0), totalBytes, capped, error: msg };
181
+ }
182
+ }
183
+
184
+ export function computeSha512Integrity(buf ) {
185
+ return `sha512-${createHash("sha512").update(buf).digest("base64")}`;
186
+ }
187
+
188
+ /**
189
+ * In-memory zero-execution streaming tarball verifier & unpacker.
190
+ * Never writes untrusted files to disk; prevents Zip-Slip, symlink escapes,
191
+ * duplicate-entry parser differentials, Windows NTFS collisions, and zip bombs.
192
+ */
193
+ export async function unpackTarballInMemory(
194
+ tarballBuffer ,
195
+ policy ,
196
+ expectedIntegrity ,
197
+ ) {
198
+ const observations = [];
199
+ const unknowns = [];
200
+ const entries = [];
201
+
202
+ const tarball_sha512 = computeSha512Integrity(tarballBuffer);
203
+
204
+ if (expectedIntegrity && expectedIntegrity !== tarball_sha512) {
205
+ observations.push({
206
+ code: "TARBALL_INTEGRITY_MISMATCH",
207
+ severity: "CRITICAL",
208
+ path: "<tarball>",
209
+ attack_id: "T1195.002",
210
+ detail: `Tarball SHA-512 mismatch: expected ${expectedIntegrity}, observed ${tarball_sha512}.`,
211
+ });
212
+ return {
213
+ ok: false,
214
+ tarball_sha512,
215
+ compressed_bytes: tarballBuffer.length,
216
+ uncompressed_bytes: 0,
217
+ entries,
218
+ observations,
219
+ unknowns,
220
+ halted_by_cap: false,
221
+ };
222
+ }
223
+
224
+ if (tarballBuffer.length > policy.max_compressed_bytes) {
225
+ unknowns.push(
226
+ `ARCHIVE_COMPRESSED_CAP_EXCEEDED: ${tarballBuffer.length} bytes > ${policy.max_compressed_bytes} bytes.`,
227
+ );
228
+ return {
229
+ ok: false,
230
+ tarball_sha512,
231
+ compressed_bytes: tarballBuffer.length,
232
+ uncompressed_bytes: 0,
233
+ entries,
234
+ observations,
235
+ unknowns,
236
+ halted_by_cap: true,
237
+ };
238
+ }
239
+
240
+ // Detect gzip magic (0x1f 0x8b) vs raw tar buffer
241
+ const isGzip = tarballBuffer.length >= 2 && tarballBuffer[0] === 0x1f && tarballBuffer[1] === 0x8b;
242
+ let tarBuf ;
243
+ let uncompressedBytes ;
244
+
245
+ if (isGzip) {
246
+ const gunzipped = await gunzipWithHardCap(tarballBuffer, policy.max_uncompressed_bytes);
247
+ if (!gunzipped.ok) {
248
+ if (gunzipped.capped) {
249
+ unknowns.push(
250
+ `ARCHIVE_UNCOMPRESSED_CAP_EXCEEDED: decompressed stream exceeded ${policy.max_uncompressed_bytes} bytes (potential zip bomb).`,
251
+ );
252
+ observations.push({
253
+ code: "ARCHIVE_DECOMPRESSION_BOMB",
254
+ severity: "HIGH",
255
+ path: "<tarball>",
256
+ attack_id: "T1499",
257
+ detail: `Decompressed archive exceeded configured hard cap of ${policy.max_uncompressed_bytes} bytes.`,
258
+ });
259
+ return {
260
+ ok: false,
261
+ tarball_sha512,
262
+ compressed_bytes: tarballBuffer.length,
263
+ uncompressed_bytes: gunzipped.totalBytes,
264
+ entries,
265
+ observations,
266
+ unknowns,
267
+ halted_by_cap: true,
268
+ };
269
+ }
270
+ unknowns.push(`ARCHIVE_GUNZIP_ERROR: ${gunzipped.error ?? "malformed gzip stream"}`);
271
+ return {
272
+ ok: false,
273
+ tarball_sha512,
274
+ compressed_bytes: tarballBuffer.length,
275
+ uncompressed_bytes: 0,
276
+ entries,
277
+ observations,
278
+ unknowns,
279
+ halted_by_cap: false,
280
+ };
281
+ }
282
+ tarBuf = gunzipped.buffer;
283
+ uncompressedBytes = gunzipped.totalBytes;
284
+ } else {
285
+ if (tarballBuffer.length > policy.max_uncompressed_bytes) {
286
+ unknowns.push(`ARCHIVE_UNCOMPRESSED_CAP_EXCEEDED: ${tarballBuffer.length} bytes.`);
287
+ return {
288
+ ok: false,
289
+ tarball_sha512,
290
+ compressed_bytes: tarballBuffer.length,
291
+ uncompressed_bytes: tarballBuffer.length,
292
+ entries,
293
+ observations,
294
+ unknowns,
295
+ halted_by_cap: true,
296
+ };
297
+ }
298
+ tarBuf = tarballBuffer;
299
+ uncompressedBytes = tarballBuffer.length;
300
+ }
301
+
302
+ const seenExact = new Set ();
303
+ const seenLower = new Map ();
304
+ let globalPax = {};
305
+ let pendingPax = null;
306
+ let pendingGnuLongName = null;
307
+ let offset = 0;
308
+ let fileCount = 0;
309
+
310
+ while (offset + 512 <= tarBuf.length) {
311
+ const header = tarBuf.subarray(offset, offset + 512);
312
+ // Two zero blocks signal end of tar archive
313
+ let allZero = true;
314
+ for (let i = 0; i < 512; i++) {
315
+ if (header[i] !== 0) {
316
+ allZero = false;
317
+ break;
318
+ }
319
+ }
320
+ if (allZero) {
321
+ // Detect tar EOF polyglot / single-zero-block smuggling: any non-zero byte after a zero block is hostile
322
+ let trailingNonZeroOffset = -1;
323
+ for (let j = offset + 512; j < tarBuf.length; j++) {
324
+ if (tarBuf[j] !== 0) {
325
+ trailingNonZeroOffset = j;
326
+ break;
327
+ }
328
+ }
329
+ if (trailingNonZeroOffset !== -1) {
330
+ observations.push({
331
+ code: "ARCHIVE_EOF_POLYGLOT_SMUGGLING",
332
+ severity: "CRITICAL",
333
+ path: "<tarball>",
334
+ attack_id: "T1195.002",
335
+ detail: `Non-zero trailing bytes found at offset ${trailingNonZeroOffset} after tar EOF zero block (tar polyglot/single-zero-block smuggling risk).`,
336
+ });
337
+ return {
338
+ ok: false,
339
+ tarball_sha512,
340
+ compressed_bytes: tarballBuffer.length,
341
+ uncompressed_bytes: uncompressedBytes,
342
+ entries,
343
+ observations,
344
+ unknowns,
345
+ halted_by_cap: false,
346
+ };
347
+ }
348
+ break;
349
+ }
350
+
351
+ if (!verifyTarHeaderChecksum(header)) {
352
+ observations.push({
353
+ code: "ARCHIVE_CORRUPT_HEADER_CHECKSUM",
354
+ severity: "CRITICAL",
355
+ path: "<tarball>",
356
+ attack_id: "T1195.002",
357
+ detail: `Tar header checksum verification failed at byte offset ${offset} (corrupted or polyglot archive).`,
358
+ });
359
+ return {
360
+ ok: false,
361
+ tarball_sha512,
362
+ compressed_bytes: tarballBuffer.length,
363
+ uncompressed_bytes: uncompressedBytes,
364
+ entries,
365
+ observations,
366
+ unknowns,
367
+ halted_by_cap: false,
368
+ };
369
+ }
370
+
371
+ const nameField = readAsciiZ(header, 0, 100);
372
+ const prefixField = readAsciiZ(header, 345, 155);
373
+ const typeFlag = String.fromCharCode(header[156] ?? 0);
374
+ const mergedPax = typeFlag === "x" || typeFlag === "g" ? null : { ...globalPax, ...(pendingPax ?? {}) };
375
+ const paxSizeRaw = mergedPax?.["size"];
376
+ let size = parseOctalOrBase256(header, 124, 12);
377
+ if (paxSizeRaw !== undefined) {
378
+ if (!/^\d+$/.test(paxSizeRaw)) {
379
+ observations.push({
380
+ code: "ARCHIVE_MALFORMED_PAX_HEADER",
381
+ severity: "CRITICAL",
382
+ path: "<tarball>",
383
+ attack_id: "T1195.002",
384
+ detail: `Malformed non-numeric PAX size override at byte offset ${offset}.`,
385
+ });
386
+ return {
387
+ ok: false,
388
+ tarball_sha512,
389
+ compressed_bytes: tarballBuffer.length,
390
+ uncompressed_bytes: uncompressedBytes,
391
+ entries,
392
+ observations,
393
+ unknowns,
394
+ halted_by_cap: false,
395
+ };
396
+ }
397
+ const parsedPaxSize = Number.parseInt(paxSizeRaw, 10);
398
+ if (Number.isFinite(parsedPaxSize) && parsedPaxSize >= 0) {
399
+ size = parsedPaxSize;
400
+ }
401
+ }
402
+ offset += 512;
403
+
404
+ if (size < 0 || offset + size > tarBuf.length) {
405
+ unknowns.push(`ARCHIVE_MALFORMED_HEADER: invalid tar entry size at offset ${offset - 512}.`);
406
+ return {
407
+ ok: false,
408
+ tarball_sha512,
409
+ compressed_bytes: tarballBuffer.length,
410
+ uncompressed_bytes: uncompressedBytes,
411
+ entries,
412
+ observations,
413
+ unknowns,
414
+ halted_by_cap: false,
415
+ };
416
+ }
417
+
418
+ const content = tarBuf.subarray(offset, offset + size);
419
+ const paddedSize = Math.ceil(size / 512) * 512;
420
+ offset += paddedSize;
421
+
422
+ // PAX extended header ('x') or global PAX ('g')
423
+ if (typeFlag === "x" || typeFlag === "g") {
424
+ const parsedPax = parsePaxRecords(content);
425
+ if (parsedPax.malformed) {
426
+ observations.push({
427
+ code: "ARCHIVE_MALFORMED_PAX_HEADER",
428
+ severity: "CRITICAL",
429
+ path: "<tarball>",
430
+ attack_id: "T1195.002",
431
+ detail: `Malformed or truncated PAX '${typeFlag}' extended header (parser differential risk).`,
432
+ });
433
+ return {
434
+ ok: false,
435
+ tarball_sha512,
436
+ compressed_bytes: tarballBuffer.length,
437
+ uncompressed_bytes: uncompressedBytes,
438
+ entries,
439
+ observations,
440
+ unknowns,
441
+ halted_by_cap: false,
442
+ };
443
+ }
444
+ if (typeFlag === "x") pendingPax = parsedPax.records;
445
+ else globalPax = { ...globalPax, ...parsedPax.records };
446
+ continue;
447
+ }
448
+ // GNU LongLink filename ('L')
449
+ if (typeFlag === "L") {
450
+ pendingGnuLongName = content.toString("utf8").replace(/\0+$/, "");
451
+ continue;
452
+ }
453
+
454
+ const combinedName =
455
+ mergedPax?.["path"] ??
456
+ pendingGnuLongName ??
457
+ (prefixField ? `${prefixField}/${nameField}` : nameField);
458
+ const hasPaxLinkPath = Boolean(mergedPax?.["linkpath"]);
459
+ pendingPax = null;
460
+ pendingGnuLongName = null;
461
+
462
+ // Reject symlinks, hardlinks, GNU LongLink targets ('K'), character/block devices, FIFOs, or PAX linkpath smuggling
463
+ if (
464
+ hasPaxLinkPath ||
465
+ typeFlag === "1" ||
466
+ typeFlag === "2" ||
467
+ typeFlag === "3" ||
468
+ typeFlag === "4" ||
469
+ typeFlag === "6" ||
470
+ typeFlag === "K"
471
+ ) {
472
+ observations.push({
473
+ code: "ARCHIVE_UNSAFE_LINK_OR_DEVICE",
474
+ severity: "CRITICAL",
475
+ path: combinedName,
476
+ attack_id: "T1546",
477
+ detail: `Rejected non-regular tar entry (typeflag='${typeFlag}'${hasPaxLinkPath ? ", pax_linkpath" : ""}) at '${combinedName}'.`,
478
+ });
479
+ continue;
480
+ }
481
+
482
+ // Directories ('5'): validate path safety, do not add to file list
483
+ const pathCheck = validateArchivePath(combinedName);
484
+ if (!pathCheck.safe) {
485
+ observations.push({
486
+ code: "ARCHIVE_PATH_TRAVERSAL_OR_WINDOWS_HAZARD",
487
+ severity: "CRITICAL",
488
+ path: combinedName,
489
+ attack_id: "T1546",
490
+ detail: `${pathCheck.reason ?? "Unsafe archive path"}: '${combinedName}'.`,
491
+ });
492
+ continue;
493
+ }
494
+
495
+ if (typeFlag === "5" || !pathCheck.normalized) continue;
496
+
497
+ // Only allow regular files ('0' or '\0')
498
+ if (typeFlag !== "0" && typeFlag !== "\0") {
499
+ unknowns.push(`ARCHIVE_UNSUPPORTED_TYPEFLAG: '${typeFlag}' on '${pathCheck.normalized}'.`);
500
+ continue;
501
+ }
502
+
503
+ fileCount++;
504
+ if (fileCount > policy.max_files) {
505
+ unknowns.push(`ARCHIVE_FILE_COUNT_CAP_EXCEEDED: > ${policy.max_files} files.`);
506
+ return {
507
+ ok: false,
508
+ tarball_sha512,
509
+ compressed_bytes: tarballBuffer.length,
510
+ uncompressed_bytes: uncompressedBytes,
511
+ entries,
512
+ observations,
513
+ unknowns,
514
+ halted_by_cap: true,
515
+ };
516
+ }
517
+
518
+ // Reject duplicate archive entries (prevents tar parser differential attacks)
519
+ if (seenExact.has(pathCheck.normalized)) {
520
+ observations.push({
521
+ code: "ARCHIVE_DUPLICATE_ENTRY_DIFFERENTIAL",
522
+ severity: "CRITICAL",
523
+ path: pathCheck.normalized,
524
+ attack_id: "T1195.002",
525
+ detail: `Duplicate archive entry '${pathCheck.normalized}' detected (parser differential smuggling risk).`,
526
+ });
527
+ continue;
528
+ }
529
+ seenExact.add(pathCheck.normalized);
530
+
531
+ // Reject Windows/macOS case-insensitive filename collisions (Index.js vs index.js)
532
+ const lower = pathCheck.normalized.toLowerCase();
533
+ const prior = seenLower.get(lower);
534
+ if (prior) {
535
+ observations.push({
536
+ code: "ARCHIVE_CASE_COLLISION",
537
+ severity: "HIGH",
538
+ path: pathCheck.normalized,
539
+ attack_id: "T1195.002",
540
+ detail: `Case-insensitive filename collision between '${prior}' and '${pathCheck.normalized}' (NTFS/APFS hazard).`,
541
+ });
542
+ continue;
543
+ }
544
+ seenLower.set(lower, pathCheck.normalized);
545
+
546
+ const sha256 = createHash("sha256").update(content).digest("hex");
547
+ entries.push({
548
+ path: pathCheck.normalized,
549
+ size: content.length,
550
+ sha256,
551
+ content,
552
+ });
553
+ }
554
+
555
+ return {
556
+ ok: true,
557
+ tarball_sha512,
558
+ compressed_bytes: tarballBuffer.length,
559
+ uncompressed_bytes: uncompressedBytes,
560
+ entries,
561
+ observations,
562
+ unknowns,
563
+ halted_by_cap: false,
564
+ };
565
+ }
566
+
567
+
568
+ //# sourceURL=quarantine/safe-unpack.ts