Public: anyone can read this; the crew can change it.

An IGES drawing and a Premiere project open as readable summaries, not 'Binary file' #15725

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/15717-an-iges-drawing-and-a-premiere-project-o → main 0 commits fork 2 threads · 2 unresolved

  • Merged. scout/15717-an-iges-drawing-and-a-premiere-project-o was merged into main as a388452.

Review

Sign in to review this change.
11 files changed +449 −31
docs/features/file-kinds.md +2
@@ -52,6 +52,8 @@ The forge draws a file on its page when its kind is below and it is within the s
5252 - **draw.io diagram**, drawn up to 1 MB: `.drawio`
5353 - **Excalidraw**, drawn up to 1 MB: `.excalidraw`
5454 - **STEP model**, drawn up to 5 MB: `.step`, `.stp`
55 - **IGES drawing**, drawn up to 5 MB: `.iges`, `.igs`
56 - **Premiere project**, drawn up to 10 MB: `.prproj`
5557 - **SARIF report**, drawn up to 5 MB: `.sarif`
5658 - **Coverage (lcov)**, drawn up to 5 MB: `.lcov`, `lcov.info`
5759 - **JUnit report**, drawn up to 5 MB: `*.junit.xml`, `TEST-*.xml`, `.xml with a <testsuite> root`
scripts/kinds-guide.ts +1 −1
@@ -15,7 +15,7 @@ export const NAMES: Readonly<Record<FileKind, string>> = {
1515 notebook: "Notebook", patch: "Patch", log: "Log", subtitles: "Subtitles", gpx: "GPS track", har: "HTTP archive",
1616 geojson: "GeoJSON", kml: "KML", calendar: "Calendar", otio: "OpenTimelineIO", edl: "Edit list", fcpxml: "Final Cut XML", kdenlive: "Kdenlive project",
1717 contacts: "Contacts", mail: "Email", gcode: "G-code", dxf: "DXF drawing", gerber: "Gerber layer", mermaid: "Mermaid diagram", drawio: "draw.io diagram",
18 excalidraw: "Excalidraw", step: "STEP model", sarif: "SARIF report", lcov: "Coverage (lcov)", junit: "JUnit report",
18 excalidraw: "Excalidraw", step: "STEP model", iges: "IGES drawing", prproj: "Premiere project", sarif: "SARIF report", lcov: "Coverage (lcov)", junit: "JUnit report",
1919 opml: "OPML", feed: "RSS or Atom feed", env: "Env example", openapi: "OpenAPI", package: "package.json", manifest: "Dependency manifest", makefile: "Makefile",
2020 dockerfile: "Dockerfile", workflow: "GitHub workflow", compose: "Compose file", sql: "SQL", graphql: "GraphQL",
2121 epub: "EPUB book", mbox: "Mailbox", bib: "Bibliography", proto: "Protocol Buffers", ini: "INI or properties", rtf: "Rich text", xml: "XML", text: "Other text", binary: "Other binary",
src/web/render/iges.ts added +148
@@ -0,0 +1,148 @@
1 /**
2 * An IGES drawing (`.igs`, `.iges`, fixed 80-column text) as one table: the
3 * Start section's words, the Global section's facts (product, file, system,
4 * author, units, date) and the entities counted by type from the Directory
5 * Entry section. Column 73 of every line names its section (S, G, D, P, T);
6 * a file with no S, G, D, P and T line, or with no Global parameters, falls
7 * back to the source. Nothing is drawn and no parameter data is parsed: the
8 * counts are a summary read from each entry's first line. Every string is
9 * escaped by `html`.
10 */
11
12 import { html } from "../html.ts";
13 import type { Rendered, RenderInput } from "./renderers.ts";
14 import { RENDER_CAP } from "./kinds.ts";
15 import { fileSize } from "../ui.ts";
16
17 const START_LINES = 20;
18 const TEXT_CHARS = 200;
19
20 /** Entity type numbers a person knows by name; any other shows as `Entity N`. */
21 export const ENTITY_NAMES: Readonly<Record<number, string>> = {
22 100: "Circular arc", 102: "Composite curve", 104: "Conic arc", 106: "Copious data", 108: "Plane",
23 110: "Line", 112: "Parametric spline curve", 114: "Parametric spline surface", 116: "Point",
24 118: "Ruled surface", 120: "Surface of revolution", 122: "Tabulated cylinder", 124: "Transformation matrix",
25 126: "Rational B-spline curve", 128: "Rational B-spline surface", 130: "Offset curve", 140: "Offset surface",
26 142: "Curve on a parametric surface", 144: "Trimmed surface", 186: "Manifold solid B-rep object",
27 202: "Angular dimension", 206: "Diameter dimension", 210: "General label", 212: "General note",
28 214: "Leader (arrow)", 216: "Linear dimension", 218: "Ordinate dimension", 220: "Point dimension",
29 222: "Radius dimension", 228: "General symbol", 230: "Sectioned area", 308: "Subfigure definition",
30 314: "Color definition", 402: "Associativity instance", 404: "Drawing", 406: "Property",
31 408: "Singular subfigure instance", 410: "View", 412: "Rectangular array", 414: "Circular array",
32 };
33
34 const UNITS: Readonly<Record<number, string>> = {
35 1: "inches", 2: "millimeters", 4: "feet", 5: "miles", 6: "meters", 7: "kilometers", 8: "mils",
36 9: "microns", 10: "centimeters", 11: "microinches",
37 };
38
39 export interface Drawing {
40 readonly start: string[];
41 readonly facts: [string, string][];
42 /** Entity type number and count, most first. */
43 readonly types: [number, number][];
44 readonly entities: number;
45 }
46
47 /**
48 * The Global section's parameters: delimiters default to `,` and `;`, and `nHtext` is Hollerith.
49 */
50 export function globalParams(text: string): string[] {
51 let sep = ",";
52 let end = ";";
53 const first = /^\s*1H(.)/.exec(text);
54 if (first !== null) {
55 sep = first[1] ?? ",";
56 const second = /^\s*1H(.)/.exec(text.slice(text.indexOf(sep, first[0].length - 1) + 2));
57 if (second !== null) end = second[1] ?? ";";
58 }
59 const out: string[] = [];
60 let cur = "";
61 let i = 0;
62 while (i < text.length && out.length < 40) {
63 const h = cur.trim() === "" ? /^\s*(\d{1,6})H/.exec(text.slice(i, i + 12)) : null;
64 if (h !== null) {
65 const len = Number(h[1]);
66 i += h[0].length;
67 cur = text.slice(i, i + len);
68 i += len;
69 continue;
70 }
71 const c = text[i++]!;
72 if (c === sep || c === end) {
73 out.push(cur.trim());
74 cur = "";
75 if (c === end) break;
76 } else if (cur.trim() === "" || cur.length < TEXT_CHARS) cur += c;
77 }
78 return out;
79 }
80
81 /** Read an IGES file's text. Pure. An error string when it is no drawing. */
82 export function readIges(text: string): Drawing | { error: string } {
83 const lines = text.replace(/^/, "").split(/\r?\n/);
84 const sections: Record<string, string[]> = { S: [], G: [], D: [], P: [], T: [] };
85 for (const line of lines) {
86 if (line.length < 73) continue;
87 const letter = line[72]!;
88 if (!(letter in sections) || !/^\s*\d+\s*$/.test(line.slice(73))) continue;
89 sections[letter]!.push(line.slice(0, 72));
90 }
91 for (const letter of ["S", "G", "D", "P", "T"])
92 if (sections[letter]!.length === 0) return { error: `it has no ${letter} section line (column 73)` };
93
94 const p = globalParams(sections.G!.map((l) => l.trimEnd()).join("").replace(/\s+$/, ""));
95 if (p.length < 15) return { error: "its Global section has too few parameters" };
96 const units = Number(p[13]);
97 const unitName = (p[14] ?? "").trim();
98 const facts: [string, string][] = [];
99 const add = (k: string, v: string | undefined): void => {
100 if (v !== undefined && v.trim() !== "") facts.push([k, v.trim().slice(0, TEXT_CHARS)]);
101 };
102 add("Product", p[2]);
103 add("File", p[3]);
104 add("System", p[4]);
105 add("Translator", p[5]);
106 add("Units", UNITS[units] ?? (unitName === "" ? undefined : unitName));
107 add("Written", p[17]);
108 add("Author", p[20]);
109 add("Organization", p[21]);
110 add("IGES version", p[22]);
111
112 const counts = new Map<number, number>();
113 let entities = 0;
114 // Each entity takes two lines; the type number is in columns 1-8 of the first.
115 sections.D!.forEach((line, i) => {
116 if (i % 2 !== 0) return;
117 const t = Number(line.slice(0, 8).trim());
118 if (!Number.isInteger(t) || t <= 0) return;
119 counts.set(t, (counts.get(t) ?? 0) + 1);
120 entities++;
121 });
122 return {
123 start: sections.S!.map((l) => l.trimEnd()).filter((l) => l !== "").slice(0, START_LINES),
124 facts,
125 types: [...counts].sort((a, b) => b[1] - a[1] || a[0] - b[0]),
126 entities,
127 };
128 }
129
130 const n = (x: number): string => x.toLocaleString("en");
131 export const entityName = (t: number): string => ENTITY_NAMES[t] ?? `Entity ${t}`;
132
133 const rows = (list: [string, string][]) =>
134 html`${list.map(([k, v]) => html`<div class="status-row"><dt>${k}</dt><dd>${v}</dd></div>`)}`;
135
136 export function iges(input: RenderInput): Rendered {
137 const fall = (why: string): Rendered => ({ content: html``, lines: 0, fallback: `This file is shown as text because ${why}.` });
138 if (input.size > RENDER_CAP.iges || input.body.length > RENDER_CAP.iges) return fall("it is too large to summarise");
139 const d = readIges(new TextDecoder().decode(input.body));
140 if ("error" in d) return fall(d.error);
141 const content = html`<section>
142 <dl class="status-rows" aria-label="Drawing">${rows([...d.facts, ["Entities", `${n(d.entities)} in ${n(d.types.length)} types`]])}</dl>
143 ${d.start.length > 0 ? html`<h3>Start</h3><p class="small">${d.start.join(" ")}</p>` : html``}
144 <h3>Entity types</h3>
145 <dl class="status-rows" aria-label="Entity types">${rows(d.types.map(([t, c]) => [`${t} ${entityName(t)}`, n(c)]))}</dl>
146 </section>`;
147 return { content, lines: 0, summary: `${n(d.entities)} entities · ${fileSize(input.size)}` };
148 }
src/web/render/kinds.ts +19
@@ -60,6 +60,8 @@ export type FileKind =
6060 | "drawio"
6161 | "excalidraw"
6262 | "step"
63 | "iges"
64 | "prproj"
6365 | "sarif"
6466 | "lcov"
6567 | "junit"
@@ -152,6 +154,9 @@ export const RENDER_CAP: Readonly<Record<FileKind, number>> = {
152154 drawio: 1 * MB,
153155 excalidraw: 1 * MB,
154156 step: 5 * MB,
157 iges: 5 * MB,
158 // The compressed size; the inflated text is capped again in `prproj.ts`.
159 prproj: 10 * MB,
155160 sarif: 5 * MB,
156161 lcov: 5 * MB,
157162 junit: 5 * MB,
@@ -319,6 +324,8 @@ const TEXTUAL: Readonly<Record<string, FileKind>> = {
319324 excalidraw: "excalidraw",
320325 step: "step",
321326 stp: "step",
327 iges: "iges",
328 igs: "iges",
322329 sarif: "sarif",
323330 opml: "opml",
324331 rss: "feed",
@@ -431,6 +438,13 @@ const isGerberHead = (head: Uint8Array): boolean =>
431438 const isStepHead = (head: Uint8Array): boolean =>
432439 /^\uFEFF?\s*ISO-10303-21\s*;/.test(new TextDecoder().decode(head.subarray(0, 64)));
433440
441 /** An IGES file's first line is 80 columns with `S` in column 73 and a sequence number after it. */
442 const isIgesHead = (head: Uint8Array): boolean =>
443 /^\uFEFF?[^\r\n]{72}S\s*\d+\s*(?:\r?\n|$)/.test(new TextDecoder().decode(head.subarray(0, 120)));
444
445 /** A Premiere project is gzip: it opens on the bytes 1f 8b. */
446 const isGzipHead = (head: Uint8Array): boolean => head[0] === 0x1f && head[1] === 0x8b;
447
434448 /** A classic pcap or a pcapng capture opens on its magic number, in either byte order. */
435449 const isPcap = (path: string, head: Uint8Array): boolean =>
436450 (extension(path) === "pcap" || extension(path) === "pcapng" || extension(path) === "cap") &&
@@ -528,6 +542,8 @@ export function fileKind(path: string, head: Uint8Array): FileKind {
528542 if (isPcap(path, head)) return "pcap";
529543 // A CAD or 3D source is named by its magic as well as its name, and has NULs in its head.
530544 if (binaryFacts(extension(path), head) !== undefined) return "cad";
545 // A project is gzip, so its head has NULs: ask before the binary test.
546 if (extension(path) === "prproj" && isGzipHead(head)) return "prproj";
531547 if (looksBinary(head)) return "binary";
532548 if (isLcovName(path)) return "lcov";
533549 if (isEnvExample(path)) return "env";
@@ -547,6 +563,7 @@ export function fileKind(path: string, head: Uint8Array): FileKind {
547563 // A Kdenlive project is MLT XML: a `.kdenlive` whose root is not `<mlt>` is only text.
548564 if (ext === "kdenlive") return isMltHead(head) ? "kdenlive" : "text";
549565 if (ext === "step" || ext === "stp") return isStepHead(head) ? "step" : "text";
566 if (ext === "iges" || ext === "igs") return isIgesHead(head) ? "iges" : "text";
550567 if (ext === "gbr" || ext === "gtl" || ext === "gbl") return isGerberHead(head) ? "gerber" : "text";
551568 // RTF opens on `{\rtf`: a `.rtf` whose bytes say otherwise is only text.
552569 if (ext === "rtf") return /^\uFEFF?\s*\{\\rtf/.test(new TextDecoder().decode(head.subarray(0, 16))) ? "rtf" : "text";
@@ -579,6 +596,7 @@ export function kindByName(path: string): FileKind {
579596 if (ext === "pcap" || ext === "pcapng" || ext === "cap") return "pcap";
580597 if (OFFICE[ext] !== undefined) return OFFICE[ext]!;
581598 if (FACTS_EXTENSIONS.includes(ext)) return "cad";
599 if (ext === "prproj") return "prproj";
582600 return MEDIA[ext]?.kind ?? TEXTUAL[ext] ?? "text";
583601 }
584602
@@ -685,6 +703,7 @@ const SNIFFED_EXTENSIONS: Readonly<Partial<Record<FileKind, readonly string[]>>>
685703 archive: ["zip", "tar", "tgz"],
686704 pcap: ["pcap", "pcapng", "cap"],
687705 cad: [...FACTS_EXTENSIONS],
706 prproj: ["prproj"],
688707 };
689708
690709 /** What names a kind, for the guide: extensions and file names, each once, to show as code. */
src/web/render/prproj.ts added +102
@@ -0,0 +1,102 @@
1 /**
2 * An Adobe Premiere project (`.prproj`, gzipped XML) as a summary: each
3 * sequence's name and frame rate, and the project's track and clip counts.
4 * The inflated text is capped (INFLATE_CAP) before it is read, so a gzip bomb
5 * stops at the cap and the file falls back; bytes that are not gzip never
6 * reach here (`kinds.ts` leaves them a download). The XML is not parsed into
7 * a tree: sequences are `<Sequence>` elements with a `<Name>` after them,
8 * tracks are `VideoClipTrack` and `AudioClipTrack` elements, and clips are
9 * `VideoClipTrackItem` and `AudioClipTrackItem` elements, counted across
10 * the project (not per sequence). Frame rate is read from a `FrameRate` in
11 * ticks (254,016,000,000 to the second). The element names are from memory
12 * of Premiere's format, not checked against a real project: a file that does
13 * not use them shows zero counts or falls back. Every string is escaped by `html`.
14 */
15
16 import { gunzipSync } from "node:zlib";
17 import { html } from "../html.ts";
18 import { decode } from "./gpx.ts";
19 import type { Rendered, RenderInput } from "./renderers.ts";
20 import { RENDER_CAP } from "./kinds.ts";
21 import { fileSize } from "../ui.ts";
22
23 /** The most XML text read from one project, however small its gzip. */
24 export const INFLATE_CAP = 32_000_000;
25 export const SEQUENCE_CAP = 50;
26 const TICKS_PER_SECOND = 254_016_000_000;
27
28 export interface Project {
29 readonly sequences: { name: string; fps: string }[];
30 readonly sequenceCount: number;
31 readonly videoTracks: number;
32 readonly audioTracks: number;
33 readonly videoClips: number;
34 readonly audioClips: number;
35 }
36
37 /** Frames a second from a tick count a frame, to at most two decimals; "" when it is no rate. */
38 export function fpsFromTicks(ticks: number): string {
39 if (!Number.isFinite(ticks) || ticks <= 0) return "";
40 const fps = TICKS_PER_SECOND / ticks;
41 return fps < 1 || fps > 1000 ? "" : `${Number(fps.toFixed(2))} fps`;
42 }
43
44 const count = (xml: string, tag: string): number => xml.match(new RegExp(`<${tag}[\\s>/]`, "g"))?.length ?? 0;
45
46 /** Inflate with the cap; an error string when it is not gzip or inflates past the cap. */
47 export function inflate(body: Uint8Array): string | { error: string } {
48 try {
49 return new TextDecoder().decode(gunzipSync(body, { maxOutputLength: INFLATE_CAP }));
50 } catch (e) {
51 return { error: e instanceof RangeError ? "it inflates past the size the page reads" : "it is not valid gzip" };
52 }
53 }
54
55 /** Read a project's XML. Pure. An error string when it is no Premiere project. */
56 export function readPrproj(xml: string): Project | { error: string } {
57 if (!/<PremiereData[\s>]/.test(xml)) return { error: "it has no PremiereData root" };
58 const starts = [...xml.matchAll(/<Sequence[\s>]/g)].map((m) => m.index!);
59 const sequences: { name: string; fps: string }[] = [];
60 starts.forEach((at, i) => {
61 if (sequences.length >= SEQUENCE_CAP) return;
62 const win = xml.slice(at, starts[i + 1] ?? xml.length);
63 const name = /<Name>([^<]{0,300})<\/Name>/.exec(win)?.[1];
64 const ticks = /<FrameRate>(\d{1,18})<\/FrameRate>/.exec(win)?.[1];
65 sequences.push({ name: decode(name ?? "").trim() || "(unnamed)", fps: ticks === undefined ? "" : fpsFromTicks(Number(ticks)) });
66 });
67 return {
68 sequences,
69 sequenceCount: starts.length,
70 videoTracks: count(xml, "VideoClipTrack"),
71 audioTracks: count(xml, "AudioClipTrack"),
72 videoClips: count(xml, "VideoClipTrackItem"),
73 audioClips: count(xml, "AudioClipTrackItem"),
74 };
75 }
76
77 const n = (x: number): string => x.toLocaleString("en");
78
79 export function prproj(input: RenderInput): Rendered {
80 const fall = (why: string): Rendered => ({ content: html``, lines: 0, fallback: `This file is shown as text because ${why}.` });
81 if (input.size > RENDER_CAP.prproj || input.body.length > RENDER_CAP.prproj) return fall("it is too large to summarise");
82 const xml = inflate(input.body);
83 if (typeof xml !== "string") return fall(xml.error);
84 const p = readPrproj(xml);
85 if ("error" in p) return fall(p.error);
86 const row = (k: string, v: string) => html`<div class="status-row"><dt>${k}</dt><dd>${v}</dd></div>`;
87 const content = html`<section>
88 <dl class="status-rows" aria-label="Project">
89 ${row("Sequences", n(p.sequenceCount))}
90 ${row("Video tracks", n(p.videoTracks))}
91 ${row("Audio tracks", n(p.audioTracks))}
92 ${row("Video clips", n(p.videoClips))}
93 ${row("Audio clips", n(p.audioClips))}
94 </dl>
95 ${p.sequences.length > 0
96 ? html`<h3>Sequences</h3><dl class="status-rows" aria-label="Sequences">${p.sequences.map((s) => row(s.name, s.fps || "frame rate not stated"))}</dl>${p.sequenceCount > p.sequences.length ? html`<p class="muted small">${n(p.sequenceCount - p.sequences.length)} more</p>` : html``}`
97 : html``}
98 <p class="muted small">Counts are across the whole project, not per sequence.</p>
99 </section>`;
100 const clips = p.videoClips + p.audioClips;
101 return { content, lines: 0, summary: `${n(p.sequenceCount)} ${p.sequenceCount === 1 ? "sequence" : "sequences"} · ${n(clips)} ${clips === 1 ? "clip" : "clips"} · ${fileSize(input.size)}` };
102 }
src/web/render/renderers.ts +4
@@ -28,6 +28,8 @@ import { dxf } from "./dxf.ts";
2828 import { gerber } from "./gerber.ts";
2929 import { drawio, excalidraw, mermaid } from "./diagram.ts";
3030 import { step } from "./step.ts";
31 import { iges } from "./iges.ts";
32 import { prproj } from "./prproj.ts";
3133 import { gcode } from "./gcode.ts";
3234 import { gpx } from "./gpx.ts";
3335 import { har } from "./har.ts";
@@ -155,6 +157,8 @@ export const RENDERERS: Partial<Readonly<Record<FileKind, Renderer>>> = {
155157 drawio,
156158 excalidraw,
157159 step,
160 iges,
161 prproj,
158162 geojson,
159163 kml,
160164 calendar: ics,
test/fuzz-renderers.test.ts +21 −30
@@ -17,35 +17,20 @@ import type { Blob } from "../src/view/source.ts";
1717
1818 const encoder = new TextEncoder();
1919
20 /** What a hostile file tries to smuggle into the page. */
21 export const HOSTILE = [
22 "<script>alert(1)</script>",
23 "<ScRiPt src=//x.test/a.js>",
24 '"><img src=x onerror=alert(1)>',
25 "'><svg onload=alert(1)>",
26 "javascript:alert(1)",
27 " JaVaScRiPt:alert(1)",
28 "[x](javascript:alert(1))",
29 "![x](javascript:alert(1))",
30 "<a href=\"javascript:alert(1)\">x</a>",
31 "<iframe src=javascript:alert(1)>",
32 "\u0000",
33 "\ud800",
34 "\udfff",
35 "\u001b[31m",
36 "\u001b]8;;javascript:alert(1)\u0007x\u001b]8;;\u0007",
37 "&lt;script&gt;",
38 "\r\n",
39 "\n",
40 "\t",
41 ",",
42 '"',
43 "'",
44 "<",
45 ">",
46 "&",
47 "x".repeat(5000),
48 ];
20 import { HOSTILE } from "./helpers/hostile.ts";
21 export { HOSTILE };
22
23 /**
24 * A small valid IGES file: every line is 72 columns of text, a section letter, a sequence number.
25 */
26 function igesFile(): string {
27 const l = (t: string, c: string, n: number): string => `${t.padEnd(72)}${c}${String(n).padStart(7)}`;
28 const g = "1H,,1H;,3Hp<b>,3Hf.i,3Hsys,3Hpre,32,38,6,308,15,3Hp<b>,1.,2,2HMM,1,0.01,13H260102.030405,1E-06,100.,3HAda,3HOrg,11,0,;";
29 return [
30 l("<b>start</b>", "S", 1), l(g.slice(0, 72), "G", 1), l(g.slice(72), "G", 2),
31 l(" 110 1", "D", 1), l(" 110", "D", 2), l("1P0", "P", 1), l("S 1G 2D 2P 1", "T", 1),
32 ].join("\n") + "\n";
33 }
4934
5035 /**
5136 * A valid file of each kind; a case is one of these with hostile text spliced in. The kind is what
@@ -305,6 +290,10 @@ export const SAMPLES: Readonly<Record<string, { path: string; files: readonly st
305290 '<?xml version="1.0"?><rss version="2.0"><channel><title>N</title><item><title>&lt;b&gt;x&lt;/b&gt;</title><link>https://a.test/1</link><pubDate>Thu, 01 Jan 2026 10:00:00 GMT</pubDate></item><item><title>J</title><link>javascript:alert(1)</link></item></channel></rss>',
306291 ],
307292 },
293 iges: {
294 path: "part.igs",
295 files: [igesFile()],
296 },
308297 step: {
309298 path: "part.step",
310299 files: [
@@ -333,6 +322,7 @@ export const SAMPLES: Readonly<Record<string, { path: string; files: readonly st
333322 * generator cannot splice text into without a fixture to start from.
334323 */
335324 export const EXCLUDED: Readonly<Record<string, string>> = {
325 prproj: "gzipped XML, so the splice cannot reach it; test/render-prproj.test.ts gzips every HOSTILE string into <Name> and feeds it truncated and non-UTF-8 gzip",
336326 image: "an <img> pointing at the media route; only the header's width and height are read",
337327 svg: "an <img> pointing at the media route, served under a sandbox policy; no byte enters the page",
338328 pdf: "a viewer pointing at the media route; no byte enters the page",
@@ -510,7 +500,7 @@ describe("fuzz: file renderers", () => {
510500 const out = render(input(sample.path, text, all));
511501 assertInert(out.content.text);
512502 },
513 Math.min(Number(process.env["FUZZ_RUNS"] ?? 250), 250),
503 Math.min(Number(process.env["FUZZ_RUNS"] ?? 120), 120),
514504 );
515505 });
516506 });
@@ -606,6 +596,7 @@ export const RAW_PATHS: Readonly<Record<string, string>> = {
606596 layers: "a.ora",
607597 font: "a.ttf",
608598 psd: "a.psd",
599 prproj: "a.prproj",
609600 cad: "a.dwg",
610601 text: "notes.txt",
611602 binary: "a.bin",
test/helpers/hostile.ts added +29
@@ -0,0 +1,29 @@
1 /** What a hostile file tries to smuggle into the page. */
2 export const HOSTILE = [
3 "<script>alert(1)</script>",
4 "<ScRiPt src=//x.test/a.js>",
5 '"><img src=x onerror=alert(1)>',
6 "'><svg onload=alert(1)>",
7 "javascript:alert(1)",
8 " JaVaScRiPt:alert(1)",
9 "[x](javascript:alert(1))",
10 "![x](javascript:alert(1))",
11 "<a href=\"javascript:alert(1)\">x</a>",
12 "<iframe src=javascript:alert(1)>",
13 "\u0000",
14 "\ud800",
15 "\udfff",
16 "\u001b[31m",
17 "\u001b]8;;javascript:alert(1)\u0007x\u001b]8;;\u0007",
18 "&lt;script&gt;",
19 "\r\n",
20 "\n",
21 "\t",
22 ",",
23 '"',
24 "'",
25 "<",
26 ">",
27 "&",
28 "x".repeat(5000),
29 ];
test/render-iges.test.ts added +62
@@ -0,0 +1,62 @@
1 /** IGES drawings as one summary table. */
2 import { describe, expect, test } from "bun:test";
3 import { iges, readIges } from "../src/web/render/iges.ts";
4 import { fileKind, RENDER_CAP } from "../src/web/render/kinds.ts";
5 import { RENDERERS } from "../src/web/render/renderers.ts";
6
7 const enc = (s: string): Uint8Array => new TextEncoder().encode(s);
8 /** One 80-column line: 72 columns of text, the section letter, a 7-digit sequence number. */
9 const line = (text: string, sec: string, n: number): string => `${text.padEnd(72)}${sec}${String(n).padStart(7)}`;
10 const entry = (type: number, n: number): string[] => [
11 line(`${String(type).padStart(8)}${String(n).padStart(8)}`, "D", n),
12 line(`${String(type).padStart(8)}`, "D", n + 1),
13 ];
14 const G =
15 "1H,,1H;,7Hbracket,10Hbracket.igs,5HCADXX,3Hv<1,32,38,6,308,15,7Hbracket,1.,2,2HMM,1,0.01,13H260102.030405,1E-06,100.,3HAda,4HAcme,11,0,;";
16 const FILE = [
17 line("A <b>drawing</b> of a bracket", "S", 1),
18 line(G.slice(0, 72), "G", 1),
19 line(G.slice(72), "G", 2),
20 ...entry(110, 1),
21 ...entry(110, 3),
22 ...entry(100, 5),
23 ...entry(999, 7),
24 line("1P0", "P", 1),
25 line("S 1G 2D 8P 1", "T", 1),
26 ].join("\n") + "\n";
27 const draw = (text: string, size = text.length) =>
28 iges({ path: "a.igs", size, body: enc(text), media: "/m", download: "/d" });
29
30 describe("iges", () => {
31 test("registered, by extension and by its section letters", () => {
32 expect(fileKind("a.igs", enc(FILE))).toBe("iges");
33 expect(fileKind("a.IGES", enc(FILE))).toBe("iges");
34 expect(fileKind("a.igs", enc("hello\n"))).toBe("text");
35 expect(fileKind("a.txt", enc(FILE))).toBe("text");
36 expect(RENDERERS.iges).toBe(iges);
37 expect(RENDER_CAP.iges).toBeGreaterThan(0);
38 });
39
40 test("a drawing gives its header, units and entity counts", () => {
41 const d = readIges(FILE);
42 if ("error" in d) throw new Error(d.error);
43 expect(d.entities).toBe(4);
44 expect(d.types[0]).toEqual([110, 2]);
45 expect(d.facts).toContainEqual(["Units", "millimeters"]);
46 expect(d.facts).toContainEqual(["Product", "bracket"]);
47 expect(d.facts).toContainEqual(["Author", "Ada"]);
48 const out = String(draw(FILE).content);
49 expect(out).toContain("<dt>110 Line</dt><dd>2</dd>");
50 expect(out).toContain("<dt>999 Entity 999</dt>");
51 expect(out).toContain("&lt;b&gt;drawing&lt;/b&gt;");
52 expect(out).not.toContain("<b>drawing");
53 });
54
55 test("a file without every section stays text, never throws", () => {
56 const noT = FILE.split("\n").filter((l) => l[72] !== "T").join("\n");
57 expect(draw(noT).fallback).toContain("no T section");
58 expect(draw("").fallback).toBeDefined();
59 expect(draw("x".repeat(500)).fallback).toBeDefined();
60 expect(draw(FILE, RENDER_CAP.iges + 1).fallback).toContain("too large");
61 });
62 });
test/render-kinds.test.ts +3
@@ -8,6 +8,7 @@ import { describe, expect, test } from "bun:test";
88 import { parseRange } from "../src/http/range.ts";
99 import { fileKind, KNOWN_EXTENSIONS, mediaType, type FileKind } from "../src/web/render/kinds.ts";
1010
11 const igesHead = new TextEncoder().encode(`${"x".padEnd(72)}S 1\n`);
1112 const enc = (s: string): Uint8Array => new TextEncoder().encode(s);
1213 const of = (...b: number[]): Uint8Array => new Uint8Array(b);
1314 const box = (brand: string): Uint8Array => enc(`\0\0\0\x20ftyp${brand}`);
@@ -109,6 +110,8 @@ const SAMPLES: Record<string, [Uint8Array, FileKind, string]> = {
109110 drawio: [enc("<mxfile/>"), "drawio", "application/octet-stream"],
110111 excalidraw: [enc("{}"), "excalidraw", "application/octet-stream"],
111112 step: [enc("ISO-10303-21;\nHEADER;\n"), "step", "application/octet-stream"],
113 iges: [igesHead, "iges", "application/octet-stream"],
114 igs: [igesHead, "iges", "application/octet-stream"],
112115 stp: [enc("ISO-10303-21;\nHEADER;\n"), "step", "application/octet-stream"],
113116 har: [enc(`{"log":{"entries":[]}}`), "har", "application/octet-stream"],
114117 sql: [enc("CREATE TABLE a (id int);\n"), "sql", "application/octet-stream"],
test/render-prproj.test.ts added +58
@@ -0,0 +1,58 @@
1 /** Premiere projects as a summary of sequences, tracks and clips. */
2 import { describe, expect, test } from "bun:test";
3 import { gzipSync } from "node:zlib";
4 import { INFLATE_CAP, fpsFromTicks, prproj, readPrproj } from "../src/web/render/prproj.ts";
5 import { fileKind, RENDER_CAP } from "../src/web/render/kinds.ts";
6 import { RENDERERS } from "../src/web/render/renderers.ts";
7 import { HOSTILE } from "./helpers/hostile.ts";
8
9 const XML = `<?xml version="1.0" encoding="UTF-8" ?><PremiereData Version="3">
10 <Sequence ObjectUID="a"><Node/><Name>Main &lt;cut&gt;</Name><FrameRate>10160640000</FrameRate></Sequence>
11 <Sequence ObjectUID="b"><Name>Promo</Name></Sequence>
12 <VideoClipTrack ObjectID="1"/><VideoClipTrack ObjectID="2"/><AudioClipTrack ObjectID="3"/>
13 <VideoClipTrackItem ObjectID="4"/><VideoClipTrackItem ObjectID="5"/><VideoClipTrackItem ObjectID="6"/><AudioClipTrackItem ObjectID="7"/>
14 </PremiereData>`;
15 const gz = (s: string): Uint8Array => new Uint8Array(gzipSync(Buffer.from(s)));
16 const draw = (body: Uint8Array) => prproj({ path: "a.prproj", size: body.length, body, media: "/m", download: "/d" });
17
18 describe("prproj", () => {
19 test("registered by extension and gzip magic; other bytes stay a download", () => {
20 expect(fileKind("a.prproj", gz(XML))).toBe("prproj");
21 expect(fileKind("a.prproj", new TextEncoder().encode("\0\0 not gzip"))).toBe("binary");
22 expect(fileKind("a.bin", gz(XML))).not.toBe("prproj");
23 expect(RENDERERS.prproj).toBe(prproj);
24 expect(RENDER_CAP.prproj).toBeGreaterThan(0);
25 });
26
27 test("names the sequences, frame rate and counts", () => {
28 expect(fpsFromTicks(10160640000)).toBe("25 fps");
29 const p = readPrproj(XML);
30 if ("error" in p) throw new Error(p.error);
31 expect(p.sequences).toEqual([{ name: "Main <cut>", fps: "25 fps" }, { name: "Promo", fps: "" }]);
32 expect([p.videoTracks, p.audioTracks, p.videoClips, p.audioClips]).toEqual([2, 1, 3, 1]);
33 const out = String(draw(gz(XML)).content);
34 expect(out).toContain("Main &lt;cut&gt;");
35 expect(out).toContain("25 fps");
36 expect(out).toContain("<dt>Video clips</dt><dd>3</dd>");
37 });
38
39 test("a bomb, a non-gzip body and a foreign XML fall back, never throw", () => {
40 const bomb = gz("<PremiereData>" + " ".repeat(INFLATE_CAP + 1000));
41 expect(draw(bomb).fallback).toContain("inflates past");
42 expect(draw(new TextEncoder().encode("plain")).fallback).toContain("not valid gzip");
43 expect(draw(gz("<other/>")).fallback).toContain("no PremiereData");
44 });
45
46 test("hostile text in a sequence name, a truncated gzip and non-UTF-8 bytes never throw or leak a tag", () => {
47 const bad = (out: string) => !/<script|<img|<svg|<iframe|\son\w+=|<a\s/i.test(out.replace(/<\/?(section|dl|div|dt|dd|h3|p)\b[^>]*>/g, ""));
48 for (const h of HOSTILE) {
49 const out = draw(gz(`<PremiereData><Sequence><Name>${h}</Name></Sequence></PremiereData>`));
50 expect(bad(String(out.content))).toBe(true);
51 }
52 const whole = gz(XML);
53 expect(draw(whole.slice(0, whole.length >> 1)).fallback).toBeTruthy();
54 const junk = new Uint8Array(gzipSync(Buffer.from([0xff, 0xfe, 0xc3, 0x28, 0x80, 0x3c, 0x3e])));
55 expect(() => draw(junk)).not.toThrow();
56 expect(bad(String(draw(junk).content))).toBe(true);
57 });
58 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs