Repository navigation
Expand file tree
/
Copy pathfiles.ts
More file actions
559 lines (511 loc) · 15.3 KB
/
Copy pathfiles.ts
File metadata and controls
559 lines (511 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
<
8000
div data-line-number="225" class="react-line-number react-code-text" style="padding-right:16px">225226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import JSZip from "jszip";
const execFileAsync = promisify(execFile);
export interface FileCleanResult {
buffer: Buffer;
actions: string[];
findings: Array<{
kind: "metadata" | "c2pa" | "frontmatter";
code: string;
message: string;
count?: number;
verifiable: boolean;
}>;
}
function extOf(path: string): string {
const i = path.lastIndexOf(".");
return i >= 0 ? path.slice(i + 1).toLowerCase() : "";
}
/** PNG: drop tEXt/zTXt/iTXt/eXIf and any chunk whose data mentions c2pa. */
export function cleanPng(buf: Buffer): FileCleanResult {
const actions: string[] = [];
const findings: FileCleanResult["findings"] = [];
if (buf.length < 8 || buf.subarray(0, 8).toString("hex") !== "89504e470d0a1a0a") {
return { buffer: buf, actions, findings };
}
const out: Buffer[] = [buf.subarray(0, 8)];
let offset = 8;
let dropped = 0;
let c2pa = 0;
while (offset + 8 <= buf.length) {
const length = buf.readUInt32BE(offset);
const type = buf.subarray(offset + 4, offset + 8).toString("ascii");
const total = 12 + length;
if (offset + total > buf.length) break;
const chunk = buf.subarray(offset, offset + total);
const data = buf.subarray(offset + 8, offset + 8 + length);
const dropMeta = ["tEXt", "zTXt", "iTXt", "eXIf"].includes(type);
const looksC2pa =
type === "caBX" ||
data.includes(Buffer.from("c2pa")) ||
data.includes(Buffer.from("C2PA")) ||
data.includes(Buffer.from("contentcredentials"));
if (dropMeta || looksC2pa) {
dropped += 1;
if (looksC2pa) c2pa += 1;
} else {
out.push(chunk);
}
offset += total;
}
if (dropped) {
actions.push(`png: removed ${dropped} metadata/ancillary chunk(s)`);
findings.push({
kind: "metadata",
code: "png_metadata",
message: `Removed ${dropped} PNG metadata chunk(s)`,
count: dropped,
verifiable: true,
});
}
if (c2pa) {
findings.push({
kind: "c2pa",
code: "png_c2pa",
message: `Removed ${c2pa} PNG chunk(s) that looked like C2PA/Content Credentials`,
count: c2pa,
verifiable: true,
});
}
return { buffer: Buffer.concat(out), actions, findings };
}
/** JPEG: drop APP1 (EXIF/XMP) and APP11 (often C2PA) segments. */
export function cleanJpeg(buf: Buffer): FileCleanResult {
const actions: string[] = [];
const findings: FileCleanResult["findings"] = [];
if (buf.length < 4 || buf[0] !== 0xff || buf[1] !== 0xd8) {
return { buffer: buf, actions, findings };
}
const out: number[] = [0xff, 0xd8];
let i = 2;
let dropped = 0;
let c2pa = 0;
while (i < buf.length) {
if (buf[i] !== 0xff) {
// Copy through SOS entropy-coded data as-is.
out.push(...buf.subarray(i));
break;
}
const marker = buf[i + 1];
if (marker === 0xd9) {
out.push(0xff, 0xd9);
break;
}
if (marker === 0xda) {
out.push(...buf.subarray(i));
break;
}
// Standalone markers
if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) {
out.push(0xff, marker);
i += 2;
continue;
}
if (i + 4 > buf.length) break;
const len = buf.readUInt16BE(i + 2);
const segEnd = i + 2 + len;
const seg = buf.subarray(i, segEnd);
const drop = marker === 0xe1 || marker === 0xeb; // APP1, APP11
const looksC2pa =
seg.includes(Buffer.from("c2pa")) ||
seg.includes(Buffer.from("C2PA")) ||
marker === 0xeb;
if (drop) {
dropped += 1;
if (looksC2pa) c2pa += 1;
} else {
out.push(...seg);
}
i = segEnd;
}
if (dropped) {
actions.push(`jpeg: removed ${dropped} APP segment(s)`);
findings.push({
kind: "metadata",
code: "jpeg_metadata",
message: `Removed ${dropped} JPEG APP segment(s)`,
count: dropped,
verifiable: true,
});
}
if (c2pa) {
findings.push({
kind: "c2pa",
code: "jpeg_c2pa",
message: `Removed ${c2pa} JPEG segment(s) associated with C2PA/XMP`,
count: c2pa,
verifiable: true,
});
}
return { buffer: Buffer.from(out), actions, findings };
}
const SVG_META_RE =
/<metadata[\s\S]*?<\/metadata>/gi;
const SVG_RDF_RE = /<rdf:RDF[\s\S]*?<\/rdf:RDF>/gi;
export function cleanSvg(text: string): {
text: string;
actions: string[];
findings: FileCleanResult["findings"];
} {
const actions: string[] = [];
const findings: FileCleanResult["findings"] = [];
let out = text;
const meta = out.match(SVG_META_RE)?.length ?? 0;
const rdf = out.match(SVG_RDF_RE)?.length ?? 0;
if (meta) {
out = out.replace(SVG_META_RE, "");
actions.push(`svg: removed ${meta} <metadata> block(s)`);
findings.push({
kind: "metadata",
code: "svg_metadata",
message: `Removed ${meta} SVG metadata block(s)`,
count: meta,
verifiable: true,
});
}
if (rdf) {
out = out.replace(SVG_RDF_RE, "");
actions.push(`svg: removed ${rdf} rdf:RDF block(s)`);
findings.push({
kind: "c2pa",
code: "svg_xmp",
message: `Removed ${rdf} XMP/RDF block(s)`,
count: rdf,
verifiable: true,
});
}
return { text: out, actions, findings };
}
const AI_FRONTMATTER_KEYS = [
"generator",
"ai",
"model",
"created_with",
"provenance",
"c2pa",
];
export function cleanMarkdown(text: string): {
text: string;
actions: string[];
findings: FileCleanResult["findings"];
} {
const actions: string[] = [];
const findings: FileCleanResult["findings"] = [];
if (!text.startsWith("---\n") && !text.startsWith("---\r\n")) {
return { text, actions, findings };
}
const end = text.indexOf("\n---", 4);
if (end < 0) return { text, actions, findings };
const fm = text.slice(4, end);
const body = text.slice(end + 4).replace(/^\r?\n/, "");
const lines = fm.split(/\r?\n/);
const kept: string[] = [];
let dropped = 0;
for (const line of lines) {
const key = line.split(":")[0]?.trim().toLowerCase() ?? "";
if (AI_FRONTMATTER_KEYS.some((k) => key === k || key.startsWith(`${k}_`))) {
dropped += 1;
continue;
}
kept.push(line);
}
if (!dropped) return { text, actions, findings };
const next =
kept.filter((l) => l.trim()).length > 0
? `---\n${kept.join("\n")}\n---\n${body}`
: body;
actions.push(`markdown: dropped ${dropped} AI-ish frontmatter key(s)`);
findings.push({
kind: "frontmatter",
code: "md_frontmatter",
message: `Dropped ${dropped} frontmatter key(s)`,
count: dropped,
verifiable: true,
});
return { text: next, actions, findings };
}
const HTML_META_RE =
/<meta\b[^>]*(name|property)\s*=\s*["'][^"']*(generator|ai|provenance|c2pa)[^"']*["'][^>]*>/gi;
const HTML_JSONLD_AI_RE =
/<script\b[^>]*type=["']application\/ld\+json["'][^>]*>[\s\S]*?(AI|Generative|c2pa|Provable)[\s\S]*?<\/script>/gi;
export function cleanHtml(text: string): {
text: string;
actions: string[];
findings: FileCleanResult["findings"];
} {
const actions: string[] = [];
const findings: FileCleanResult["findings"] = [];
let out = text;
const meta = out.match(HTML_META_RE)?.length ?? 0;
if (meta) {
out = out.replace(HTML_META_RE, "");
actions.push(`html: removed ${meta} AI-ish <meta> tag(s)`);
findings.push({
kind: "metadata",
code: "html_meta",
message: `Removed ${meta} HTML meta tag(s)`,
count: meta,
verifiable: true,
});
}
const jsonld = out.match(HTML_JSONLD_AI_RE)?.length ?? 0;
if (jsonld) {
out = out.replace(HTML_JSONLD_AI_RE, "");
actions.push(`html: removed ${jsonld} JSON-LD block(s) with AI hints`);
findings.push({
kind: "metadata",
code: "html_jsonld",
message: `Removed ${jsonld} JSON-LD block(s)`,
count: jsonld,
verifiable: true,
});
}
return { text: out, actions, findings };
}
async function cleanDocx(buf: Buffer): Promise<FileCleanResult> {
const actions: string[] = [];
const findings: FileCleanResult["findings"] = [];
const zip = await JSZip.loadAsync(buf);
let touched = 0;
for (const name of Object.keys(zip.files)) {
if (
name.startsWith("docProps/") ||
name.startsWith("customXml/") ||
name.includes("provenance")
) {
zip.remove(name);
touched += 1;
}
}
if (touched) {
actions.push(`docx: removed ${touched} docProps/customXml entr(y/ies)`);
findings.push({
kind: "metadata",
code: "docx_props",
message: `Removed ${touched} DOCX property/customXml entr(y/ies)`,
count: touched,
verifiable: true,
});
}
const out = await zip.generateAsync({ type: "nodebuffer" });
return { buffer: out, actions, findings };
}
async function cleanPdfWithExiftool(
inputPath: string,
outputPath: string,
): Promise<FileCleanResult | null> {
try {
await execFileAsync("exiftool", [
"-all=",
"-overwrite_original",
"-o",
outputPath,
inputPath,
]);
const { readFile } = await import("node:fs/promises");
const buffer = await readFile(outputPath);
return {
buffer,
actions: ["pdf: stripped metadata via exiftool"],
findings: [
{
kind: "metadata",
code: "pdf_exiftool",
message: "Stripped PDF metadata with exiftool",
verifiable: true,
},
],
};
} catch {
return null;
}
}
/**
* Best-effort PDF XMP / metadata scrub without exiftool.
* Removes XML packets and clears common Info dictionary string values.
* Does not rebuild xref tables — safe for many PDFs; prefer exiftool when available.
*/
export function cleanPdfBestEffort(buf: Buffer): FileCleanResult {
const actions: string[] = [];
const findings: FileCleanResult["findings"] = [];
let text = buf.toString("latin1");
let changed = 0;
const xmpRe =
/<\?xpacket[\s\S]*?<\?xpacket end=["'][ew]["']\?>/g;
const xmpMatches = text.match(xmpRe)?.length ?? 0;
if (xmpMatches) {
text = text.replace(xmpRe, "");
changed += xmpMatches;
actions.push(`pdf: removed ${xmpMatches} XMP packet(s) (best-effort)`);
findings.push({
kind: "metadata",
code: "pdf_xmp",
message: `Removed ${xmpMatches} embedded XMP packet(s)`,
count: xmpMatches,
verifiable: true,
});
}
8000
const metaStreamRe =
/\/Metadata\s+\d+\s+\d+\s+R/g;
const metaRefs = text.match(metaStreamRe)?.length ?? 0;
if (metaRefs) {
text = text.replace(metaStreamRe, "/Metadata null");
changed += metaRefs;
actions.push(`pdf: nulled ${metaRefs} /Metadata reference(s) (best-effort)`);
findings.push({
kind: "metadata",
code: "pdf_metadata_ref",
message: `Nulled ${metaRefs} /Metadata reference(s)`,
count: metaRefs,
verifiable: true,
});
}
// Clear common document info strings in-place (same length via spaces).
for (const key of ["Title", "Author", "Subject", "Creator", "Producer", "Keywords"]) {
const re = new RegExp(`/${key}\\s*\\((?:\\\\.|[^\\\\)])*\\)`, "g");
text = text.replace(re, (m) => {
changed += 1;
return "/" + key + " (" + " ".repeat(Math.max(0, m.length - key.length - 4)) + ")";
});
}
if (!changed) {
findings.push({
kind: "metadata",
code: "pdf_best_effort_noop",
message:
"No XMP/Info patterns found for best-effort PDF scrub. Install exiftool for deeper cleaning.",
verifiable: false,
});
return { buffer: buf, actions, findings };
}
actions.push(
"pdf: best-effort scrub applied (install exiftool for fuller metadata removal)",
);
return { buffer: Buffer.from(text, "latin1"), actions, findings };
}
export async function cleanFileBuffer(
inputPath: string,
buf: Buffer,
textHint?: string,
): Promise<FileCleanResult> {
const ext = extOf(inputPath);
if (ext === "png") return cleanPng(buf);
if (ext === "jpg" || ext === "jpeg") return cleanJpeg(buf);
if (ext === "svg") {
const src = textHint ?? buf.toString("utf8");
const cleaned = cleanSvg(src);
return {
buffer: Buffer.from(cleaned.text, "utf8"),
actions: cleaned.actions,
findings: cleaned.findings,
};
}
if (ext === "md" || ext === "markdown") {
const src = textHint ?? buf.toString("utf8");
const cleaned = cleanMarkdown(src);
return {
buffer: Buffer.from(cleaned.text, "utf8"),
actions: cleaned.actions,
findings: cleaned.findings,
};
}
if (ext === "html" || ext === "htm") {
const src = textHint ?? buf.toString("utf8");
const cleaned = cleanHtml(src);
return {
buffer: Buffer.from(cleaned.text, "utf8"),
actions: cleaned.actions,
findings: cleaned.findings,
};
}
if (ext === "docx") return cleanDocx(buf);
if (ext === "pdf") {
const { mkdtemp, writeFile, rm } = await import("node:fs/promises");
const { tmpdir } = await import("node:os");
const { join } = await import("node:path");
const dir = await mkdtemp(join(tmpdir(), "markscrub-"));
const inPath = join(dir, "in.pdf");
const outPath = join(dir, "out.pdf");
try {
await writeFile(inPath, buf);
const viaTool = await cleanPdfWithExiftool(inPath, outPath);
if (viaTool) return viaTool;
return cleanPdfBestEffort(buf);
} finally {
await rm(dir, { recursive: true, force: true });
}
}
return { buffer: buf, actions: [], findings: [] };
}
export function inspectFileHints(
inputPath: string,
buf: Buffer,
): FileCleanResult["findings"] {
const findings: FileCleanResult["findings"] = [];
const ext = extOf(inputPath);
const asText =
["md", "markdown", "html", "htm", "svg", "txt"].includes(ext)
? buf.toString("utf8")
: "";
if (buf.includes(Buffer.from("c2pa")) || buf.includes(Buffer.from("C2PA"))) {
findings.push({
kind: "c2pa",
code: "c2pa_bytes",
message: "Byte pattern suggests C2PA / Content Credentials metadata",
verifiable: true,
});
}
if (ext === "png" || ext === "jpg" || ext === "jpeg") {
if (ext === "png" && (buf.includes(Buffer.from("tEXt")) || buf.includes(Buffer.from("iTXt")))) {
findings.push({
kind: "metadata",
code: "png_text_chunks",
message: "PNG contains textual metadata chunks",
verifiable: true,
});
}
}
if (ext === "pdf") {
const latin = buf.toString("latin1");
if (latin.includes("<?xpacket") || latin.includes("/Metadata")) {
findings.push({
kind: "metadata",
code: "pdf_meta_present",
message: "PDF appears to contain XMP or /Metadata references",
verifiable: true,
});
}
}
if (asText) {
if (/<metadata[\s\S]*?<\/metadata>/i.test(asText) || /<rdf:RDF[\s\S]*?<\/rdf:RDF>/i.test(asText)) {
findings.push({
kind: "metadata",
code: "svg_meta_present",
message: "SVG metadata / XMP present",
verifiable: true,
});
}
if (asText.startsWith("---")) {
findings.push({
kind: "frontmatter",
code: "md_frontmatter_present",
message: "Markdown frontmatter present (may include AI keys)",
verifiable: true,
});
}
if (
/<meta\b[^>]*(name|property)\s*=\s*["'][^"']*(generator|ai|provenance|c2pa)[^"']*["'][^>]*>/i.test(
asText,
)
) {
findings.push({
kind: "metadata",
code: "html_meta_present",
message: "HTML contains AI-ish meta tags",
verifiable: true,
});
}
}
return findings;
}