Public: anyone can read this; the crew can change it.
A PEM certificate, a CycloneDX or SPDX SBOM and a WebAssembly module open as facts #15724
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/15718-a-pem-certificate-a-cyclonedx-or-spdx-sb → main 0 commits fork
17 files
changed +686
−3
docs/features/file-cert-sbom-wasm.md added +11
| @@ -0,0 +1,11 @@ | ||
| 1 | --- | |
| 2 | topic: Files in the browser | |
| 3 | row: A PEM certificate, a CycloneDX or SPDX SBOM and a WebAssembly module open as facts | |
| 4 | --- | |
| 5 | # A certificate, a bill of materials and a WebAssembly module open as facts | |
| 6 | ||
| 7 | - **`.pem`, `.crt`, `.cer`** with a `-----BEGIN` line: subject, issuer, not-before and not-after with `valid`, `expired` or `not yet valid`, and the subject alternative names (50 a certificate, 10 certificates). Parsed by the runtime's `crypto.X509Certificate`. A file with any PRIVATE KEY block says "This file holds a private key" and draws nothing of it, not even a certificate beside it. (The Source tab is still the file as pushed.) | |
| 8 | - **`.json` with a `bomFormat` or `spdxVersion` key** in its first 4 KB: a table of name, version and licence, 1,000 rows with the count of the rest. Other JSON keeps its view. | |
| 9 | - **`.wasm`** (head `\0asm`): version, imports (module, name, kind) and exports (name, kind), 200 each with the count of the rest. | |
| 10 | ||
| 11 | Every string is escaped. Code: `src/web/render/cert.ts`, `sbom.ts`, `wasm.ts`. Tests: `test/render-cert.test.ts`, `render-sbom.test.ts`, `render-wasm.test.ts`, `fuzz-renderers.test.ts`. |
docs/features/file-kinds.md +3
| @@ -28,6 +28,9 @@ The forge draws a file on its page when its kind is below and it is within the s | ||
| 28 | 28 | - **Font**, drawn up to 20 MB: `.ttf`, `.otf`, `.woff`, `.woff2` |
| 29 | 29 | - **Photoshop**, drawn up to 4 GB: `.psd` |
| 30 | 30 | - **CAD or 3D source (header facts)**, drawn up to 4 GB: `.dwg`, `.blend`, `.fbx` |
| 31 | - **PEM certificate**, drawn up to 1 MB: `.pem`, `.crt`, `.cer` | |
| 32 | - **Bill of materials (CycloneDX, SPDX)**, drawn up to 5 MB: a .json with a bomFormat (CycloneDX) or spdxVersion (SPDX) key | |
| 33 | - **WebAssembly module**, drawn up to 5 MB: `.wasm` | |
| 31 | 34 | - **Config**, drawn up to 1 MB: `.json`, `.jsonc`, `.yaml`, `.yml`, `.toml`, `.conf` |
| 32 | 35 | - **Markdown**, drawn up to 1 MB: `.md`, `.markdown`, `.mdx` |
| 33 | 36 | - **Notebook**, drawn up to 1 MB: `.ipynb` |
scripts/kinds-guide.ts +1 −1
| @@ -11,7 +11,7 @@ export const END = "<!-- file-kinds:end -->"; | ||
| 11 | 11 | export const NAMES: Readonly<Record<FileKind, string>> = { |
| 12 | 12 | image: "Image", svg: "SVG", pdf: "PDF", html: "HTML page", audio: "Audio", video: "Video", csv: "Table (CSV, TSV, JSON lines)", |
| 13 | 13 | sqlite: "SQLite database", parquet: "Parquet", pcap: "Packet capture", model3d: "3D model", archive: "Archive", sheet: "Spreadsheet", document: "Word document", |
| 14 | slides: "Slides", layers: "Layered image", font: "Font", psd: "Photoshop", cad: "CAD or 3D source (header facts)", config: "Config", markdown: "Markdown", | |
| 14 | slides: "Slides", layers: "Layered image", font: "Font", psd: "Photoshop", cad: "CAD or 3D source (header facts)", cert: "PEM certificate", sbom: "Bill of materials (CycloneDX, SPDX)", wasm: "WebAssembly module", config: "Config", markdown: "Markdown", | |
| 15 | 15 | notebook: "Notebook", patch: "Patch", log: "Log", subtitles: "Subtitles", gpx: "GPS track", har: "HTTP archive", |
| 16 | 16 | geojson: "GeoJSON", kml: "KML", calendar: "Calendar", otio: "OpenTimelineIO", edl: "Edit list", fcpxml: "Final Cut XML", kdenlive: "Kdenlive project", |
| 17 | 17 | contacts: "Contacts", mail: "Email", gcode: "G-code", dxf: "DXF drawing", gerber: "Gerber layer", mermaid: "Mermaid diagram", drawio: "draw.io diagram", |
src/tui/screens/workspace.ts +2 −1
| @@ -96,6 +96,7 @@ import { sqliteStep, sqliteView, type SqliteAt } from "./workspace_sqlite.ts"; | ||
| 96 | 96 | import { officeView } from "./workspace_office.ts"; |
| 97 | 97 | import { parquetView } from "./workspace_parquet.ts"; |
| 98 | 98 | import { bibView } from "./workspace_bib.ts"; |
| 99 | import { factsView } from "./workspace_facts.ts"; | |
| 99 | 100 | import { depsView } from "./workspace_deps.ts"; |
| 100 | 101 | import { cadView } from "./workspace_cad.ts"; |
| 101 | 102 | import { layoutTable, type Grid } from "../ui/grid.ts"; |
| @@ -1555,7 +1556,7 @@ export function workspaceScreen( | ||
| 1555 | 1556 | // bytes as text is how a terminal ends up beeping at you. |
| 1556 | 1557 | const base = looksLikeImage(t.path) ? null : sqliteView(t.path, read.value.body, { table: 0, page: 1 }); |
| 1557 | 1558 | if (base !== null && typeof base !== "string") db = read.value.body; |
| 1558 | const book = looksLikeImage(t.path) ? null : (base ?? sheetView(t.path, read.value.body) ?? officeView(t.path, read.value.body) ?? parquetView(t.path, read.value.body) ?? bibView(t.path, read.value.body) ?? cadView(t.path, read.value.body, read.value.size, formatSize)); | |
| 1559 | const book = looksLikeImage(t.path) ? null : (base ?? sheetView(t.path, read.value.body) ?? officeView(t.path, read.value.body) ?? parquetView(t.path, read.value.body) ?? bibView(t.path, read.value.body) ?? factsView(t.path, read.value.body) ?? cadView(t.path, read.value.body, read.value.size, formatSize)); | |
| 1559 | 1560 | if (looksLikeImage(t.path)) picture = read.value.body; |
| 1560 | 1561 | else if (book !== null && typeof book !== "string") sheet = book; |
| 1561 | 1562 | else if (typeof book === "string") note = book; |
src/tui/screens/workspace_facts.ts added +49
| @@ -0,0 +1,49 @@ | ||
| 1 | /** | |
| 2 | * A PEM certificate, a CycloneDX or SPDX bill of materials and a WebAssembly module in the | |
| 3 | * terminal workspace, read the way the page reads them: the same `readCerts`, `parseSbom` and | |
| 4 | * `parseWasm`, drawn as a table. The same gate too: the name (and head) must say so (`fileKind`), | |
| 5 | * under the page's cap. A file holding a private key is never drawn. | |
| 6 | * | |
| 7 | * `factsView(path, body)` answers a table, a sentence (the workspace shows it as its note), or | |
| 8 | * `null` for a file that is none of the three. | |
| 9 | */ | |
| 10 | ||
| 11 | import { fileKind, HEAD_BYTES, RENDER_CAP } from "../../web/render/kinds.ts"; | |
| 12 | import { holdsPrivateKey, readCerts, SAN_CAP } from "../../web/render/cert.ts"; | |
| 13 | import { COMPONENT_CAP, parseSbom } from "../../web/render/sbom.ts"; | |
| 14 | import { parseWasm } from "../../web/render/wasm.ts"; | |
| 15 | import type { Table } from "../../text/csv.ts"; | |
| 16 | ||
| 17 | const table = (header: string[], rows: string[][], more: number): Table => ({ header, rows, more, delimiter: ",", columns: header.length }); | |
| 18 | ||
| 19 | export function factsView(path: string, body: Uint8Array, now: number = Date.now()): Table | string | null { | |
| 20 | const kind = fileKind(path, body.subarray(0, HEAD_BYTES)); | |
| 21 | if (kind !== "cert" && kind !== "sbom" && kind !== "wasm") return null; | |
| 22 | if (body.length > RENDER_CAP[kind]) | |
| 23 | return `This file is over ${RENDER_CAP[kind] / 1_000_000} MB, too large to open here. Download it instead.`; | |
| 24 | if (kind === "cert") { | |
| 25 | const text = new TextDecoder().decode(body); | |
| 26 | if (holdsPrivateKey(text)) return "This file holds a private key. The forge does not draw it."; | |
| 27 | const { certs, total, bad } = readCerts(text, now); | |
| 28 | if (certs.length === 0) return "This file holds no certificate the forge can read."; | |
| 29 | const rows = certs.map((c) => [c.subject, c.issuer, `${c.notAfter} (${c.state})`, c.names.slice(0, SAN_CAP).join(", ")]); | |
| 30 | if (bad > 0) rows.push(["", "", "", `${bad} could not be read`]); | |
| 31 | return table(["Subject", "Issuer", "Not after", "Names"], rows, total - certs.length); | |
| 32 | } | |
| 33 | if (kind === "sbom") { | |
| 34 | const doc = parseSbom(new TextDecoder().decode(body)); | |
| 35 | if ("error" in doc) return `This file is not drawn as a bill of materials: ${doc.error}.`; | |
| 36 | if (doc.components.length === 0) return `${doc.format}: no components.`; | |
| 37 | const shown = doc.components.slice(0, COMPONENT_CAP); | |
| 38 | return table(["Name", "Version", "Licence"], shown.map((c) => [c.name, c.version, c.licence === "" ? "-" : c.licence]), doc.components.length - shown.length); | |
| 39 | } | |
| 40 | const facts = parseWasm(body); | |
| 41 | if (facts === undefined) return "not a readable WebAssembly module"; | |
| 42 | const rows = [ | |
| 43 | ...facts.imports.map((e) => ["import", e.module, e.name, e.kind]), | |
| 44 | ...facts.exports.map((e) => ["export", "", e.name, e.kind]), | |
| 45 | ]; | |
| 46 | const left = facts.importTotal - facts.imports.length + (facts.exportTotal - facts.exports.length); | |
| 47 | if (rows.length === 0) return `WebAssembly version ${facts.version}: no imports or exports.`; | |
| 48 | return table(["Direction", "Module", "Name", "Kind"], rows, left); | |
| 49 | } |
src/web/render/cert.ts added +81
| @@ -0,0 +1,81 @@ | ||
| 1 | /** | |
| 2 | * A PEM certificate (`.pem`, `.crt`, `.cer`) as its facts: subject, issuer, the validity window | |
| 3 | * with a plain word when it has run out, and the subject alternative names. Parsing is the | |
| 4 | * runtime's own `crypto.X509Certificate`; no dependency. A file with a PRIVATE KEY block of any | |
| 5 | * kind is never drawn: it says it holds a private key and nothing else, and no byte of the file is | |
| 6 | * read into the page. At most `CERT_CAP` certificates and `SAN_CAP` names are drawn, and the page | |
| 7 | * says how many were left out. Every string is escaped. | |
| 8 | */ | |
| 9 | ||
| 10 | import { X509Certificate } from "node:crypto"; | |
| 11 | import { escapeHtml, html, raw } from "../html.ts"; | |
| 12 | import { fileSize } from "../ui.ts"; | |
| 13 | import type { Rendered, RenderInput } from "./renderers.ts"; | |
| 14 | ||
| 15 | export const CERT_CAP = 10; | |
| 16 | export const SAN_CAP = 50; | |
| 17 | ||
| 18 | export interface CertFacts { | |
| 19 | readonly subject: string; | |
| 20 | readonly issuer: string; | |
| 21 | readonly notBefore: string; | |
| 22 | readonly notAfter: string; | |
| 23 | /** `valid`, `expired` or `not yet valid`, at the moment asked. */ | |
| 24 | readonly state: "valid" | "expired" | "not yet valid"; | |
| 25 | readonly names: readonly string[]; | |
| 26 | } | |
| 27 | ||
| 28 | /** Whether the text opens any PRIVATE KEY block (RSA, EC, encrypted or plain). */ | |
| 29 | export const holdsPrivateKey = (text: string): boolean => /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/.test(text); | |
| 30 | ||
| 31 | /** The one line a distinguished name makes: `CN=a, O=b`. */ | |
| 32 | const oneLine = (dn: string): string => dn.split("\n").join(", "); | |
| 33 | ||
| 34 | /** The certificates in a PEM text, as facts; one that does not parse is counted in `bad`. */ | |
| 35 | export function readCerts(text: string, now: number): { certs: CertFacts[]; total: number; bad: number } { | |
| 36 | const blocks = text.match(/-----BEGIN CERTIFICATE-----[A-Za-z0-9+/=\s]*?-----END CERTIFICATE-----/g) ?? []; | |
| 37 | const certs: CertFacts[] = []; | |
| 38 | let bad = 0; | |
| 39 | for (const block of blocks.slice(0, CERT_CAP)) { | |
| 40 | try { | |
| 41 | const c = new X509Certificate(block); | |
| 42 | const from = new Date(c.validFrom).getTime(); | |
| 43 | const to = new Date(c.validTo).getTime(); | |
| 44 | const state = now > to ? "expired" : now < from ? "not yet valid" : "valid"; | |
| 45 | const names = (c.subjectAltName ?? "").split(/,\s*/).filter((n) => n !== ""); | |
| 46 | certs.push({ subject: oneLine(c.subject), issuer: oneLine(c.issuer), notBefore: c.validFrom, notAfter: c.validTo, state, names }); | |
| 47 | } catch { | |
| 48 | bad++; | |
| 49 | } | |
| 50 | } | |
| 51 | return { certs, total: blocks.length, bad }; | |
| 52 | } | |
| 53 | ||
| 54 | const row = (k: string, v: string): string => `<div class="status-row"><dt>${escapeHtml(k)}</dt><dd>${escapeHtml(v)}</dd></div>`; | |
| 55 | ||
| 56 | export function cert(input: RenderInput, now: number = Date.now()): Rendered { | |
| 57 | const text = new TextDecoder().decode(input.body); | |
| 58 | if (holdsPrivateKey(text)) | |
| 59 | return { | |
| 60 | lines: 0, | |
| 61 | summary: `${fileSize(input.size)} · holds a private key`, | |
| 62 | content: html`<p><strong>This file holds a private key.</strong></p><p class="muted small">The forge does not draw it. Keep it out of a repository, and replace it if it was ever pushed.</p>`, | |
| 63 | }; | |
| 64 | const { certs, total, bad } = readCerts(text, now); | |
| 65 | if (certs.length === 0) return { content: html``, lines: 0, fallback: "This file holds no certificate the forge can read." }; | |
| 66 | let body = ""; | |
| 67 | for (const c of certs) { | |
| 68 | const names = c.names.slice(0, SAN_CAP).map((n) => escapeHtml(n)).join(", "); | |
| 69 | const more = c.names.length > SAN_CAP ? ` (${(c.names.length - SAN_CAP).toLocaleString()} more)` : ""; | |
| 70 | body += `<dl class="status-rows" aria-label="Certificate">${row("Subject", c.subject)}${row("Issuer", c.issuer)}${row("Not before", c.notBefore)}${row("Not after", `${c.notAfter} (${c.state})`)}<div class="status-row"><dt>Names</dt><dd>${names === "" ? "none" : names}${more}</dd></div></dl>`; | |
| 71 | } | |
| 72 | const left = total - certs.length; | |
| 73 | const note = left > 0 ? `<p class="muted small">Showing ${certs.length} of ${total.toLocaleString()} certificates, ${left.toLocaleString()} left out.</p>` : ""; | |
| 74 | const skipped = bad > 0 ? `<p class="muted small">${bad.toLocaleString()} could not be read.</p>` : ""; | |
| 75 | const first = certs[0]!; | |
| 76 | return { | |
| 77 | lines: 0, | |
| 78 | summary: `${fileSize(input.size)} · certificate ${first.state}`, | |
| 79 | content: html`<div class="cert-view">${raw(body)}${raw(note)}${raw(skipped)}</div>`, | |
| 80 | }; | |
| 81 | } |
src/web/render/kinds.ts +24
| @@ -14,6 +14,8 @@ | ||
| 14 | 14 | */ |
| 15 | 15 | |
| 16 | 16 | import { binaryFacts, FACTS_EXTENSIONS } from "./binary-facts.ts"; |
| 17 | import { isSbomHead } from "./sbom.ts"; | |
| 18 | import { isWasm } from "./wasm.ts"; | |
| 17 | 19 | |
| 18 | 20 | export type FileKind = |
| 19 | 21 | | "image" |
| @@ -36,6 +38,9 @@ export type FileKind = | ||
| 36 | 38 | | "font" |
| 37 | 39 | | "psd" |
| 38 | 40 | | "cad" |
| 41 | | "cert" | |
| 42 | | "sbom" | |
| 43 | | "wasm" | |
| 39 | 44 | | "config" |
| 40 | 45 | | "markdown" |
| 41 | 46 | | "notebook" |
| @@ -126,6 +131,11 @@ export const RENDER_CAP: Readonly<Record<FileKind, number>> = { | ||
| 126 | 131 | psd: 4_000 * MB, |
| 127 | 132 | // Only the first 64 bytes are read, whatever the size. |
| 128 | 133 | cad: 4_000 * MB, |
| 134 | cert: 1 * MB, | |
| 135 | // Parsed whole as JSON; over it the file keeps the config view (`rendererFor`). | |
| 136 | sbom: 5 * MB, | |
| 137 | // Only the import and export sections are read; the page reads the whole body. | |
| 138 | wasm: 5 * MB, | |
| 129 | 139 | config: 1 * MB, |
| 130 | 140 | markdown: 1 * MB, |
| 131 | 141 | notebook: 1 * MB, |
| @@ -330,6 +340,9 @@ const TEXTUAL: Readonly<Record<string, FileKind>> = { | ||
| 330 | 340 | mbox: "mbox", |
| 331 | 341 | bib: "bib", |
| 332 | 342 | proto: "proto", |
| 343 | pem: "cert", | |
| 344 | crt: "cert", | |
| 345 | cer: "cert", | |
| 333 | 346 | }; |
| 334 | 347 | |
| 335 | 348 | /** The three example names; a plain `.env` is never one. */ |
| @@ -528,6 +541,8 @@ export function fileKind(path: string, head: Uint8Array): FileKind { | ||
| 528 | 541 | if (isPcap(path, head)) return "pcap"; |
| 529 | 542 | // A CAD or 3D source is named by its magic as well as its name, and has NULs in its head. |
| 530 | 543 | if (binaryFacts(extension(path), head) !== undefined) return "cad"; |
| 544 | // A WebAssembly module opens on `\0asm`, a NUL in its head; the name alone never decides. | |
| 545 | if (extension(path) === "wasm" && isWasm(head)) return "wasm"; | |
| 531 | 546 | if (looksBinary(head)) return "binary"; |
| 532 | 547 | if (isLcovName(path)) return "lcov"; |
| 533 | 548 | if (isEnvExample(path)) return "env"; |
| @@ -542,6 +557,11 @@ export function fileKind(path: string, head: Uint8Array): FileKind { | ||
| 542 | 557 | if (isWorkflowName(path)) return "workflow"; |
| 543 | 558 | if (isComposeName(path)) return "compose"; |
| 544 | 559 | const ext = extension(path); |
| 560 | // A certificate opens on a PEM line: a `.pem` of anything else (or a DER `.cer`) is only text or | |
| 561 | // binary. | |
| 562 | if (ext === "pem" || ext === "crt" || ext === "cer") return /-----BEGIN /.test(new TextDecoder().decode(head)) ? "cert" : "text"; | |
| 563 | // CycloneDX and SPDX name themselves in a top-level key; any other JSON keeps its view. | |
| 564 | if (ext === "json" && isSbomHead(new TextDecoder().decode(head))) return "sbom"; | |
| 545 | 565 | // Collada opens on a `<COLLADA` root: a `.dae` that does not is only text. |
| 546 | 566 | if (ext === "dae") return /<COLLADA[\s>]/.test(new TextDecoder().decode(head)) ? "model3d" : "text"; |
| 547 | 567 | // A Kdenlive project is MLT XML: a `.kdenlive` whose root is not `<mlt>` is only text. |
| @@ -577,6 +597,7 @@ export function kindByName(path: string): FileKind { | ||
| 577 | 597 | if (isComposeName(path)) return "compose"; |
| 578 | 598 | if (ext === "xlsx") return "sheet"; |
| 579 | 599 | if (ext === "pcap" || ext === "pcapng" || ext === "cap") return "pcap"; |
| 600 | if (ext === "wasm") return "wasm"; | |
| 580 | 601 | if (OFFICE[ext] !== undefined) return OFFICE[ext]!; |
| 581 | 602 | if (FACTS_EXTENSIONS.includes(ext)) return "cad"; |
| 582 | 603 | return MEDIA[ext]?.kind ?? TEXTUAL[ext] ?? "text"; |
| @@ -613,6 +634,7 @@ export const KNOWN_EXTENSIONS: readonly string[] = [ | ||
| 613 | 634 | "pcap", |
| 614 | 635 | "pcapng", |
| 615 | 636 | "cap", |
| 637 | "wasm", | |
| 616 | 638 | ...Object.keys(OFFICE), |
| 617 | 639 | ]; |
| 618 | 640 | |
| @@ -672,6 +694,7 @@ const BY_NAME: Readonly<Partial<Record<FileKind, readonly string[]>>> = { | ||
| 672 | 694 | /** Kinds named in words, not by a name: shown as plain text, never as code. */ |
| 673 | 695 | const BY_CONTENT: Readonly<Partial<Record<FileKind, string>>> = { |
| 674 | 696 | dxf: "a file that opens on 0 then SECTION", |
| 697 | sbom: "a .json with a bomFormat (CycloneDX) or spdxVersion (SPDX) key", | |
| 675 | 698 | text: "any other text", |
| 676 | 699 | binary: "any other bytes", |
| 677 | 700 | }; |
| @@ -684,6 +707,7 @@ const SNIFFED_EXTENSIONS: Readonly<Partial<Record<FileKind, readonly string[]>>> | ||
| 684 | 707 | sheet: ["xlsx"], |
| 685 | 708 | archive: ["zip", "tar", "tgz"], |
| 686 | 709 | pcap: ["pcap", "pcapng", "cap"], |
| 710 | wasm: ["wasm"], | |
| 687 | 711 | cad: [...FACTS_EXTENSIONS], |
| 688 | 712 | }; |
| 689 | 713 |
src/web/render/renderers.ts +9 −1
| @@ -7,6 +7,9 @@ | ||
| 7 | 7 | import type { Html } from "../html.ts"; |
| 8 | 8 | import type { Blob } from "../../view/source.ts"; |
| 9 | 9 | import { archive } from "./archive-view.ts"; |
| 10 | import { cert } from "./cert.ts"; | |
| 11 | import { sbom } from "./sbom.ts"; | |
| 12 | import { wasm } from "./wasm.ts"; | |
| 10 | 13 | import { binaryView } from "./binary-view.ts"; |
| 11 | 14 | import { audio } from "./audio.ts"; |
| 12 | 15 | import { config } from "./config.ts"; |
| @@ -194,6 +197,9 @@ export const RENDERERS: Partial<Readonly<Record<FileKind, Renderer>>> = { | ||
| 194 | 197 | font, |
| 195 | 198 | psd, |
| 196 | 199 | cad: binaryView, |
| 200 | cert, | |
| 201 | sbom, | |
| 202 | wasm, | |
| 197 | 203 | }; |
| 198 | 204 | |
| 199 | 205 | /** |
| @@ -227,12 +233,14 @@ export function rendererFor( | ||
| 227 | 233 | ): { render: Renderer; body: Uint8Array } | undefined { |
| 228 | 234 | // A file the source gave no bytes of is taken at its name: STL, OBJ and |
| 229 | 235 | // glTF have no signature to read anyway. |
| 230 | const kind = | |
| 236 | const named = | |
| 231 | 237 | blob.kind !== "too_large" |
| 232 | 238 | ? fileKind(path, blob.body.subarray(0, HEAD_BYTES)) |
| 233 | 239 | : blob.head !== undefined |
| 234 | 240 | ? fileKind(path, blob.head) |
| 235 | 241 | : kindByName(path); |
| 242 | // A bill of materials too big to parse keeps the JSON view it had, outline and all. | |
| 243 | const kind = named === "sbom" && blob.size > RENDER_CAP.sbom ? "config" : named; | |
| 236 | 244 | // A table's cap is lifted only for a body the source already cut to a prefix. |
| 237 | 245 | const prefixed = kind === "csv" && blob.kind === "text" && blob.partial === true; |
| 238 | 246 | const outlined = kind === "config" && blob.kind === "text" && blob.partial === true && isJsonPath(path); |
src/web/render/sbom.ts added +86
| @@ -0,0 +1,86 @@ | ||
| 1 | /** | |
| 2 | * A CycloneDX (`bomFormat`) or SPDX (`spdxVersion`) JSON document as its components: name, version | |
| 3 | * and licence, one row each, at most `COMPONENT_CAP` of them, with the count of the rest. Any other | |
| 4 | * JSON is not this kind (`isSbomHead`), and a document that fails to parse falls back to the | |
| 5 | * source. Every string is escaped. | |
| 6 | */ | |
| 7 | ||
| 8 | import { escapeHtml, html, raw } from "../html.ts"; | |
| 9 | import { fileSize } from "../ui.ts"; | |
| 10 | import type { Rendered, RenderInput } from "./renderers.ts"; | |
| 11 | ||
| 12 | export const COMPONENT_CAP = 1000; | |
| 13 | ||
| 14 | export interface Component { | |
| 15 | readonly name: string; | |
| 16 | readonly version: string; | |
| 17 | readonly licence: string; | |
| 18 | } | |
| 19 | ||
| 20 | const isObj = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v); | |
| 21 | const str = (v: unknown): string => (typeof v === "string" ? v : typeof v === "number" ? String(v) : ""); | |
| 22 | ||
| 23 | /** Whether the first bytes of a JSON file name one of the two formats as a top-level key. */ | |
| 24 | export const isSbomHead = (head: string): boolean => /"(bomFormat|spdxVersion)"\s*:/.test(head); | |
| 25 | ||
| 26 | function cycloneLicence(c: Record<string, unknown>): string { | |
| 27 | if (!Array.isArray(c.licenses)) return ""; | |
| 28 | const out: string[] = []; | |
| 29 | for (const l of c.licenses) { | |
| 30 | if (!isObj(l)) continue; | |
| 31 | const one = isObj(l.license) ? str(l.license.id) || str(l.license.name) : str(l.expression); | |
| 32 | if (one !== "") out.push(one); | |
| 33 | } | |
| 34 | return out.join(", "); | |
| 35 | } | |
| 36 | ||
| 37 | /** The components of a document and the format it is; an error when it is neither. */ | |
| 38 | export function parseSbom(source: string): { format: string; components: Component[] } | { error: string } { | |
| 39 | let doc: unknown; | |
| 40 | try { | |
| 41 | doc = JSON.parse(source.replace(/^/, "")); | |
| 42 | } catch (e) { | |
| 43 | return { error: `it is not valid JSON (${e instanceof Error ? e.message : "parse error"})` }; | |
| 44 | } | |
| 45 | if (!isObj(doc)) return { error: "it is not a JSON object" }; | |
| 46 | if (str(doc.bomFormat) === "CycloneDX") { | |
| 47 | const list = Array.isArray(doc.components) ? doc.components : []; | |
| 48 | return { | |
| 49 | format: `CycloneDX ${str(doc.specVersion)}`.trim(), | |
| 50 | components: list.filter(isObj).map((c) => ({ name: str(c.name), version: str(c.version), licence: cycloneLicence(c) })), | |
| 51 | }; | |
| 52 | } | |
| 53 | if (str(doc.spdxVersion) !== "") { | |
| 54 | const list = Array.isArray(doc.packages) ? doc.packages : []; | |
| 55 | return { | |
| 56 | format: str(doc.spdxVersion), | |
| 57 | components: list.filter(isObj).map((p) => ({ | |
| 58 | name: str(p.name), | |
| 59 | version: str(p.versionInfo), | |
| 60 | licence: str(p.licenseConcluded) || str(p.licenseDeclared), | |
| 61 | })), | |
| 62 | }; | |
| 63 | } | |
| 64 | return { error: "it is neither CycloneDX nor SPDX" }; | |
| 65 | } | |
| 66 | ||
| 67 | export function sbom(input: RenderInput): Rendered { | |
| 68 | const doc = parseSbom(new TextDecoder().decode(input.body)); | |
| 69 | if ("error" in doc) return { content: html``, lines: 0, fallback: `This file is not drawn as a bill of materials: ${doc.error}.` }; | |
| 70 | const total = doc.components.length; | |
| 71 | const shown = doc.components.slice(0, COMPONENT_CAP); | |
| 72 | let rows = ""; | |
| 73 | for (const c of shown) | |
| 74 | rows += `<tr><td>${escapeHtml(c.name)}</td><td>${escapeHtml(c.version)}</td><td>${escapeHtml(c.licence === "" ? "—" : c.licence)}</td></tr>`; | |
| 75 | const left = total - shown.length; | |
| 76 | const more = left > 0 ? `<p class="muted small">Showing ${COMPONENT_CAP.toLocaleString()} of ${total.toLocaleString()} components, ${left.toLocaleString()} left out. The rest is in the raw file.</p>` : ""; | |
| 77 | const table = | |
| 78 | total === 0 | |
| 79 | ? `<p class="muted small">No components.</p>` | |
| 80 | : `<div class="table-scroll"><table class="table" data-dense aria-label="Components"><thead><tr><th scope="col">Name</th><th scope="col">Version</th><th scope="col">Licence</th></tr></thead><tbody>${rows}</tbody></table></div>`; | |
| 81 | return { | |
| 82 | lines: 0, | |
| 83 | summary: `${total.toLocaleString()} ${total === 1 ? "component" : "components"} · ${doc.format} · ${fileSize(input.size)}`, | |
| 84 | content: html`<div class="sbom-view">${raw(table)}${raw(more)}</div>`, | |
| 85 | }; | |
| 86 | } |
src/web/render/wasm.ts added +148
| @@ -0,0 +1,148 @@ | ||
| 1 | /** | |
| 2 | * A WebAssembly module (`.wasm`, head `\0asm`) as its version and its imports and exports: module, | |
| 3 | * name and kind, at most `NAME_CAP` of each, with the count of the rest. Only the import (2) and | |
| 4 | * export (7) sections are read; every length is checked against the bytes there are, and a module | |
| 5 | * cut short or malformed is drawn as far as it was read, with a note. Names are UTF-8, decoded and | |
| 6 | * escaped. | |
| 7 | */ | |
| 8 | ||
| 9 | import { escapeHtml, html, raw } from "../html.ts"; | |
| 10 | import { fileSize } from "../ui.ts"; | |
| 11 | import type { Rendered, RenderInput } from "./renderers.ts"; | |
| 12 | ||
| 13 | export const NAME_CAP = 200; | |
| 14 | ||
| 15 | const KINDS = ["function", "table", "memory", "global", "tag"] as const; | |
| 16 | ||
| 17 | export interface Entry { | |
| 18 | readonly module: string; | |
| 19 | readonly name: string; | |
| 20 | readonly kind: string; | |
| 21 | } | |
| 22 | export interface WasmFacts { | |
| 23 | readonly version: number; | |
| 24 | readonly imports: readonly Entry[]; | |
| 25 | readonly exports: readonly Entry[]; | |
| 26 | readonly importTotal: number; | |
| 27 | readonly exportTotal: number; | |
| 28 | readonly note?: string; | |
| 29 | } | |
| 30 | ||
| 31 | export const isWasm = (b: Uint8Array): boolean => b.length >= 8 && b[0] === 0 && b[1] === 0x61 && b[2] === 0x73 && b[3] === 0x6d; | |
| 32 | ||
| 33 | class Cut extends Error {} | |
| 34 | ||
| 35 | class Reader { | |
| 36 | at = 0; | |
| 37 | constructor( | |
| 38 | readonly b: Uint8Array, | |
| 39 | readonly end: number, | |
| 40 | ) {} | |
| 41 | byte(): number { | |
| 42 | if (this.at >= this.end) throw new Cut(); | |
| 43 | return this.b[this.at++]!; | |
| 44 | } | |
| 45 | u32(): number { | |
| 46 | let n = 0; | |
| 47 | for (let shift = 0; shift < 35; shift += 7) { | |
| 48 | const x = this.byte(); | |
| 49 | n += (x & 0x7f) * 2 ** shift; | |
| 50 | if ((x & 0x80) === 0) return n; | |
| 51 | } | |
| 52 | throw new Cut(); | |
| 53 | } | |
| 54 | name(): string { | |
| 55 | const n = this.u32(); | |
| 56 | if (n > this.end - this.at) throw new Cut(); | |
| 57 | const s = new TextDecoder().decode(this.b.subarray(this.at, this.at + n)); | |
| 58 | this.at += n; | |
| 59 | return s; | |
| 60 | } | |
| 61 | skip(n: number): void { | |
| 62 | if (n > this.end - this.at) throw new Cut(); | |
| 63 | this.at += n; | |
| 64 | } | |
| 65 | /** A limits pair: flags, min, and a max when bit 0 is set. */ | |
| 66 | limits(): void { | |
| 67 | const f = this.byte(); | |
| 68 | this.u32(); | |
| 69 | if (f & 1) this.u32(); | |
| 70 | } | |
| 71 | } | |
| 72 | ||
| 73 | /** Reads what a module declares. Pure; never throws. */ | |
| 74 | export function parseWasm(b: Uint8Array): WasmFacts | undefined { | |
| 75 | if (!isWasm(b)) return undefined; | |
| 76 | const version = (b[4]! | (b[5]! << 8) | (b[6]! << 16) | (b[7]! << 24)) >>> 0; | |
| 77 | const imports: Entry[] = []; | |
| 78 | const exports: Entry[] = []; | |
| 79 | let importTotal = 0; | |
| 80 | let exportTotal = 0; | |
| 81 | let note: string | undefined; | |
| 82 | try { | |
| 83 | const top = new Reader(b, b.length); | |
| 84 | top.at = 8; | |
| 85 | while (top.at < top.end) { | |
| 86 | const id = top.byte(); | |
| 87 | const size = top.u32(); | |
| 88 | if (size > top.end - top.at) throw new Cut(); | |
| 89 | const sec = new Reader(b, top.at + size); | |
| 90 | sec.at = top.at; | |
| 91 | top.at += size; | |
| 92 | if (id === 2) { | |
| 93 | const n = sec.u32(); | |
| 94 | for (let i = 0; i < n; i++) { | |
| 95 | const module = sec.name(); | |
| 96 | const name = sec.name(); | |
| 97 | const k = sec.byte(); | |
| 98 | if (k === 0) sec.u32(); | |
| 99 | else if (k === 1) { | |
| 100 | sec.byte(); | |
| 101 | sec.limits(); | |
| 102 | } else if (k === 2) sec.limits(); | |
| 103 | else if (k === 3) sec.skip(2); | |
| 104 | else if (k === 4) { | |
| 105 | sec.byte(); | |
| 106 | sec.u32(); | |
| 107 | } else throw new Cut(); | |
| 108 | importTotal++; | |
| 109 | if (imports.length < NAME_CAP) imports.push({ module, name, kind: KINDS[k] ?? "unknown" }); | |
| 110 | } | |
| 111 | } else if (id === 7) { | |
| 112 | const n = sec.u32(); | |
| 113 | for (let i = 0; i < n; i++) { | |
| 114 | const name = sec.name(); | |
| 115 | const k = sec.byte(); | |
| 116 | sec.u32(); | |
| 117 | exportTotal++; | |
| 118 | if (exports.length < NAME_CAP) exports.push({ module: "", name, kind: KINDS[k] ?? "unknown" }); | |
| 119 | } | |
| 120 | } | |
| 121 | } | |
| 122 | } catch (e) { | |
| 123 | if (!(e instanceof Cut)) throw e; | |
| 124 | note = "The module is cut short or malformed; the names above are what could be read."; | |
| 125 | } | |
| 126 | return { version, imports, exports, importTotal, exportTotal, ...(note === undefined ? {} : { note }) }; | |
| 127 | } | |
| 128 | ||
| 129 | function table(title: string, rows: readonly Entry[], total: number, withModule: boolean): string { | |
| 130 | if (total === 0) return `<h3>${title}</h3><p class="muted small">None.</p>`; | |
| 131 | const body = rows | |
| 132 | .map((e) => `<tr>${withModule ? `<td>${escapeHtml(e.module)}</td>` : ""}<td>${escapeHtml(e.name)}</td><td>${escapeHtml(e.kind)}</td></tr>`) | |
| 133 | .join(""); | |
| 134 | const left = total - rows.length; | |
| 135 | const more = left > 0 ? `<p class="muted small">Showing ${NAME_CAP} of ${total.toLocaleString()}, ${left.toLocaleString()} left out.</p>` : ""; | |
| 136 | return `<h3>${title} <span class="muted small">${total.toLocaleString()}</span></h3><div class="table-scroll"><table class="table" data-dense aria-label="${title}"><thead><tr>${withModule ? `<th scope="col">Module</th>` : ""}<th scope="col">Name</th><th scope="col">Kind</th></tr></thead><tbody>${body}</tbody></table></div>${more}`; | |
| 137 | } | |
| 138 | ||
| 139 | export function wasm(input: RenderInput): Rendered { | |
| 140 | const facts = parseWasm(input.body); | |
| 141 | if (facts === undefined) return { content: html``, lines: 0, fallback: "not a readable WebAssembly module" }; | |
| 142 | const note = facts.note === undefined ? "" : `<p class="muted small">${escapeHtml(facts.note)}</p>`; | |
| 143 | return { | |
| 144 | lines: 0, | |
| 145 | summary: `${fileSize(input.size)} · WebAssembly version ${facts.version}`, | |
| 146 | content: html`<div class="wasm-view">${raw(table("Imports", facts.imports, facts.importTotal, true))}${raw(table("Exports", facts.exports, facts.exportTotal, false))}${raw(note)}<p class="small"><a class="btn" href="${input.download}">Download</a></p></div>`, | |
| 147 | }; | |
| 148 | } |
test/cert-fixture.ts added +14
| @@ -0,0 +1,14 @@ | ||
| 1 | // A self-signed ECDSA certificate for CN=forge.test, valid 2026-11-23 to 2126-10-30. | |
| 2 | export const CERT = `-----BEGIN CERTIFICATE----- | |
| 3 | MIIByzCCAXKgAwIBAgIUB0+M+SruoMILR5wI/2E50IGFe1EwCgYIKoZIzj0EAwIw | |
| 4 | JTETMBEGA1UEAwwKZm9yZ2UudGVzdDEOMAwGA1UECgwFRm9yZ2UwIBcNMjYxMTIz | |
| 5 | MDE0OTU4WhgPMjEyNjEwMzAwMTQ5NThaMCUxEzARBgNVBAMMCmZvcmdlLnRlc3Qx | |
| 6 | DjAMBgNVBAoMBUZvcmdlMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAESe9EKHUF | |
| 7 | ThMDP8kqKLhwdnhABsJtKpvS4qMevxdS1T1UW0+IZi1S3orrnMoBoG4i7dUrMmWa | |
| 8 | a0VNI7EmU0OVv6N+MHwwHQYDVR0OBBYEFPRAWkbxXZYps8kSYQKtuy+gh1WgMB8G | |
| 9 | A1UdIwQYMBaAFPRAWkbxXZYps8kSYQKtuy+gh1WgMA8GA1UdEwEB/wQFMAMBAf8w | |
| 10 | KQYDVR0RBCIwIIIKZm9yZ2UudGVzdIIMKi5mb3JnZS50ZXN0hwQKAAABMAoGCCqG | |
| 11 | SM49BAMCA0cAMEQCICZLYMnoA2M4LL3/VHdWxsJsPmqF/G20TqJ6zFZjmEhZAiB7 | |
| 12 | 8UnqzEG75cUoqeomG+HrfxvuDo06bLkYZ/SV8wm6Og== | |
| 13 | -----END CERTIFICATE----- | |
| 14 | `; |
test/fuzz-renderers.test.ts +17
| @@ -125,6 +125,23 @@ export const SAMPLES: Readonly<Record<string, { path: string; files: readonly st | ||
| 125 | 125 | path: "scan.sarif", |
| 126 | 126 | files: ['{"version":"2.1.0","runs":[{"tool":{"driver":{"name":"T"}},"results":[{"ruleId":"R","level":"error","message":{"text":"m"},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"src/a.ts"},"region":{"startLine":3}}}]}]}]}'], |
| 127 | 127 | }, |
| 128 | cert: { | |
| 129 | path: "site.pem", | |
| 130 | files: [ | |
| 131 | "-----BEGIN CERTIFICATE-----\nMIIByzCCAXKgAwIBAgIUB0+M+SruoMILR5wI/2E50IGFe1EwCgYIKoZIzj0EAwIw\nJTETMBEGA1UEAwwKZm9yZ2UudGVzdDEOMAwGA1UECgwFRm9yZ2UwIBcNMjYxMTIz\nMDE0OTU4WhgPMjEyNjEwMzAwMTQ5NThaMCUxEzARBgNVBAMMCmZvcmdlLnRlc3Qx\nDjAMBgNVBAoMBUZvcmdlMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAESe9EKHUF\nThMDP8kqKLhwdnhABsJtKpvS4qMevxdS1T1UW0+IZi1S3orrnMoBoG4i7dUrMmWa\na0VNI7EmU0OVv6N+MHwwHQYDVR0OBBYEFPRAWkbxXZYps8kSYQKtuy+gh1WgMB8G\nA1UdIwQYMBaAFPRAWkbxXZYps8kSYQKtuy+gh1WgMA8GA1UdEwEB/wQFMAMBAf8w\nKQYDVR0RBCIwIIIKZm9yZ2UudGVzdIIMKi5mb3JnZS50ZXN0hwQKAAABMAoGCCqG\nSM49BAMCA0cAMEQCICZLYMnoA2M4LL3/VHdWxsJsPmqF/G20TqJ6zFZjmEhZAiB7\n8UnqzEG75cUoqeomG+HrfxvuDo06bLkYZ/SV8wm6Og==\n-----END CERTIFICATE-----\n", | |
| 132 | ], | |
| 133 | }, | |
| 134 | sbom: { | |
| 135 | path: "bom.json", | |
| 136 | files: [ | |
| 137 | '{"bomFormat":"CycloneDX","specVersion":"1.5","components":[{"name":"a","version":"1","licenses":[{"license":{"id":"MIT"}}]},{"name":"<b>b</b>","version":"javascript:alert(1)"}]}', | |
| 138 | ], | |
| 139 | }, | |
| 140 | wasm: { | |
| 141 | // Every byte below 0x80, so it survives the text round trip: header, one import, one export. | |
| 142 | path: "m.wasm", | |
| 143 | files: ["\u0000asm\u0001\u0000\u0000\u0000\u0002\u0007\u0001\u0001a\u0001b\u0000\u0000\u0007\u0005\u0001\u0001f\u0000\u0000"], | |
| 144 | }, | |
| 128 | 145 | lcov: { |
| 129 | 146 | path: "lcov.info", |
| 130 | 147 | files: ["TN:\nSF:src/a.ts\nFNF:2\nFNH:1\nDA:1,1\nDA:2,0\nLF:2\nLH:1\nBRF:4\nBRH:2\nend_of_record\n"], |
test/render-cert.test.ts added +61
| @@ -0,0 +1,61 @@ | ||
| 1 | import { describe, expect, test } from "bun:test"; | |
| 2 | import { rendererFor } from "../src/web/render/renderers.ts"; | |
| 3 | import type { Blob } from "../src/view/source.ts"; | |
| 4 | import { CERT } from "./cert-fixture.ts"; | |
| 5 | import { cert, holdsPrivateKey } from "../src/web/render/cert.ts"; | |
| 6 | import { fileKind } from "../src/web/render/kinds.ts"; | |
| 7 | import type { RenderInput } from "../src/web/render/renderers.ts"; | |
| 8 | ||
| 9 | const KEY = `-----BEGIN ${"PRIVATE"} KEY----- | |
| 10 | TOPSECRETKEYBODYTOPSECRETKEYBODY | |
| 11 | -----END ${"PRIVATE"} KEY----- | |
| 12 | `; | |
| 13 | const enc = (s: string) => new TextEncoder().encode(s); | |
| 14 | const draw = (text: string, now?: number) => { | |
| 15 | const body = enc(text); | |
| 16 | const input: RenderInput = { path: "a.pem", size: body.length, body, media: "/m", download: "/d" }; | |
| 17 | return cert(input, now); | |
| 18 | }; | |
| 19 | ||
| 20 | describe("a PEM certificate", () => { | |
| 21 | test("shows subject, issuer, validity and names", () => { | |
| 22 | const r = draw(CERT, Date.parse("2027-01-01")); | |
| 23 | const t = r.content.text; | |
| 24 | expect(t).toContain("CN=forge.test, O=Forge"); | |
| 25 | expect(t).toContain("Not before"); | |
| 26 | expect(t).toContain("Nov 23 01:49:58 2026 GMT"); | |
| 27 | expect(t).toContain("(valid)"); | |
| 28 | expect(t).toContain("DNS:forge.test, DNS:*.forge.test, IP Address:10.0.0.1"); | |
| 29 | expect(r.fallback).toBeUndefined(); | |
| 30 | }); | |
| 31 | test("says expired, and not yet valid, in words", () => { | |
| 32 | expect(draw(CERT, Date.parse("2200-01-01")).content.text).toContain("(expired)"); | |
| 33 | expect(draw(CERT, Date.parse("2020-01-01")).content.text).toContain("(not yet valid)"); | |
| 34 | }); | |
| 35 | test("a private key is never drawn, alone or beside a certificate", () => { | |
| 36 | for (const text of [KEY, CERT + KEY, KEY + CERT, KEY.replace("PRIVATE", "RSA PRIVATE"), KEY.replace("PRIVATE", "ENCRYPTED PRIVATE")]) { | |
| 37 | const r = draw(text); | |
| 38 | expect(r.content.text).toContain("holds a private key"); | |
| 39 | expect(r.content.text).not.toContain("TOPSECRET"); | |
| 40 | expect(r.content.text).not.toContain("forge.test"); | |
| 41 | expect(r.summary).toContain("private key"); | |
| 42 | expect(r.fallback).toBeUndefined(); | |
| 43 | } | |
| 44 | expect(holdsPrivateKey(CERT)).toBe(false); | |
| 45 | }); | |
| 46 | test("a broken block falls back to the source, and the kind needs a PEM line", () => { | |
| 47 | const bad = "-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n"; | |
| 48 | expect(draw(bad).fallback).toBeDefined(); | |
| 49 | expect(fileKind("a.crt", enc(CERT))).toBe("cert"); | |
| 50 | expect(fileKind("a.pem", enc("hello"))).toBe("text"); | |
| 51 | expect(fileKind("a.cer", new Uint8Array([0x30, 0x82, 0, 1]))).toBe("binary"); | |
| 52 | }); | |
| 53 | test("the blob page draws a key file as the notice, with no body", () => { | |
| 54 | const body = enc(KEY); | |
| 55 | const found = rendererFor("deploy/key.pem", { kind: "text", body, size: body.length } as Blob); | |
| 56 | expect(found).toBeDefined(); | |
| 57 | const out = found!.render({ path: "deploy/key.pem", size: body.length, body: found!.body, media: "/m", download: "/d" }); | |
| 58 | expect(out.content.text).toContain("holds a private key"); | |
| 59 | expect(out.content.text).not.toContain("TOPSECRET"); | |
| 60 | }); | |
| 61 | }); |
test/render-kinds.test.ts +4
| @@ -124,6 +124,10 @@ const SAMPLES: Record<string, [Uint8Array, FileKind, string]> = { | ||
| 124 | 124 | opml: [enc("<opml/>"), "opml", "application/octet-stream"], |
| 125 | 125 | rss: [enc("<rss/>"), "feed", "application/octet-stream"], |
| 126 | 126 | atom: [enc("<feed/>"), "feed", "application/octet-stream"], |
| 127 | pem: [enc("-----BEGIN CERTIFICATE-----\n"), "cert", "application/octet-stream"], | |
| 128 | crt: [enc("-----BEGIN CERTIFICATE-----\n"), "cert", "application/octet-stream"], | |
| 129 | cer: [enc("-----BEGIN CERTIFICATE-----\n"), "cert", "application/octet-stream"], | |
| 130 | wasm: [of(0, 0x61, 0x73, 0x6d, 1, 0, 0, 0), "wasm", "application/octet-stream"], | |
| 127 | 131 | lcov: [enc("SF:a.ts\nend_of_record\n"), "lcov", "application/octet-stream"], |
| 128 | 132 | }; |
| 129 | 133 |
test/render-sbom.test.ts added +55
| @@ -0,0 +1,55 @@ | ||
| 1 | import { describe, expect, test } from "bun:test"; | |
| 2 | import { fileKind } from "../src/web/render/kinds.ts"; | |
| 3 | import { COMPONENT_CAP, sbom } from "../src/web/render/sbom.ts"; | |
| 4 | import type { RenderInput } from "../src/web/render/renderers.ts"; | |
| 5 | ||
| 6 | const enc = (s: string) => new TextEncoder().encode(s); | |
| 7 | const draw = (text: string) => { | |
| 8 | const body = enc(text); | |
| 9 | const input: RenderInput = { path: "bom.json", size: body.length, body, media: "/m", download: "/d" }; | |
| 10 | return sbom(input); | |
| 11 | }; | |
| 12 | ||
| 13 | const CYCLONE = JSON.stringify({ | |
| 14 | bomFormat: "CycloneDX", | |
| 15 | specVersion: "1.5", | |
| 16 | components: [ | |
| 17 | { name: "left-pad", version: "1.3.0", licenses: [{ license: { id: "MIT" } }] }, | |
| 18 | { name: "<script>x</script>", version: "2", licenses: [{ expression: "MIT OR Apache-2.0" }] }, | |
| 19 | { name: "nolicence" }, | |
| 20 | ], | |
| 21 | }); | |
| 22 | const SPDX = JSON.stringify({ | |
| 23 | spdxVersion: "SPDX-2.3", | |
| 24 | packages: [{ name: "zlib", versionInfo: "1.3", licenseConcluded: "Zlib" }], | |
| 25 | }); | |
| 26 | ||
| 27 | describe("a CycloneDX or SPDX document", () => { | |
| 28 | test("is recognised by its key, other JSON keeps its view", () => { | |
| 29 | expect(fileKind("bom.json", enc(CYCLONE))).toBe("sbom"); | |
| 30 | expect(fileKind("x.spdx.json", enc(SPDX))).toBe("sbom"); | |
| 31 | expect(fileKind("a.json", enc('{"a":1}'))).toBe("config"); | |
| 32 | expect(fileKind("a.json", enc('{"note":"bomFormat"}'))).toBe("config"); | |
| 33 | }); | |
| 34 | test("CycloneDX opens as name, version, licence, escaped", () => { | |
| 35 | const r = draw(CYCLONE); | |
| 36 | expect(r.content.text).toContain("<td>left-pad</td><td>1.3.0</td><td>MIT</td>"); | |
| 37 | expect(r.content.text).toContain("<script>x</script>"); | |
| 38 | expect(r.content.text).not.toContain("<script>"); | |
| 39 | expect(r.content.text).toContain("MIT OR Apache-2.0"); | |
| 40 | expect(r.summary).toContain("3 components"); | |
| 41 | }); | |
| 42 | test("SPDX opens as its packages", () => { | |
| 43 | expect(draw(SPDX).content.text).toContain("<td>zlib</td><td>1.3</td><td>Zlib</td>"); | |
| 44 | }); | |
| 45 | test("caps rows at 1,000 and counts the rest", () => { | |
| 46 | const components = Array.from({ length: COMPONENT_CAP + 5 }, (_, i) => ({ name: `c${i}`, version: "1" })); | |
| 47 | const t = draw(JSON.stringify({ bomFormat: "CycloneDX", components })).content.text; | |
| 48 | expect(t).toContain("<td>c999</td>"); | |
| 49 | expect(t).not.toContain("<td>c1000</td>"); | |
| 50 | expect(t).toContain("5 left out"); | |
| 51 | }); | |
| 52 | test("malformed JSON falls back", () => { | |
| 53 | expect(draw('{"bomFormat":').fallback).toContain("not valid JSON"); | |
| 54 | }); | |
| 55 | }); |
test/render-wasm.test.ts added +61
| @@ -0,0 +1,61 @@ | ||
| 1 | import { describe, expect, test } from "bun:test"; | |
| 2 | import { fileKind } from "../src/web/render/kinds.ts"; | |
| 3 | import { NAME_CAP, parseWasm, wasm } from "../src/web/render/wasm.ts"; | |
| 4 | import type { RenderInput } from "../src/web/render/renderers.ts"; | |
| 5 | ||
| 6 | const HEAD = [0, 0x61, 0x73, 0x6d, 1, 0, 0, 0]; | |
| 7 | const str = (s: string) => [s.length, ...[...s].map((c) => c.charCodeAt(0))]; | |
| 8 | const section = (id: number, body: number[]) => [id, body.length, ...body]; | |
| 9 | /** | |
| 10 | * One function import `env.log`, one memory import `env.mem`, exports `run` (function) and `<b>` | |
| 11 | * (memory). | |
| 12 | */ | |
| 13 | const MODULE = new Uint8Array([ | |
| 14 | ...HEAD, | |
| 15 | ...section(2, [2, ...str("env"), ...str("log"), 0, 0, ...str("env"), ...str("mem"), 2, 0, 1]), | |
| 16 | ...section(7, [2, ...str("run"), 0, 0, ...str("<b>"), 2, 0]), | |
| 17 | ]); | |
| 18 | const draw = (body: Uint8Array) => { | |
| 19 | const input: RenderInput = { path: "m.wasm", size: body.length, body, media: "/m", download: "/d" }; | |
| 20 | return wasm(input); | |
| 21 | }; | |
| 22 | ||
| 23 | describe("a WebAssembly module", () => { | |
| 24 | test("is a wasm by its head and name together", () => { | |
| 25 | expect(fileKind("m.wasm", MODULE)).toBe("wasm"); | |
| 26 | expect(fileKind("m.wasm", new Uint8Array([1, 2, 3, 0]))).toBe("binary"); | |
| 27 | }); | |
| 28 | test("lists version, imports and exports with kinds", () => { | |
| 29 | const f = parseWasm(MODULE)!; | |
| 30 | expect(f.version).toBe(1); | |
| 31 | expect(f.imports).toEqual([ | |
| 32 | { module: "env", name: "log", kind: "function" }, | |
| 33 | { module: "env", name: "mem", kind: "memory" }, | |
| 34 | ]); | |
| 35 | expect(f.exports.map((e) => `${e.name}:${e.kind}`)).toEqual(["run:function", "<b>:memory"]); | |
| 36 | const r = draw(MODULE); | |
| 37 | const t = r.content.text; | |
| 38 | expect(r.summary).toContain("version 1"); | |
| 39 | expect(t).toContain("<td>env</td><td>log</td><td>function</td>"); | |
| 40 | expect(t).toContain("<b>"); | |
| 41 | expect(t).not.toContain("<b>"); | |
| 42 | }); | |
| 43 | test("caps each list at 200 and counts the rest", () => { | |
| 44 | const n = NAME_CAP + 3; | |
| 45 | const body = [n & 0x7f | 0x80, n >> 7, ...Array.from({ length: n }, (_, i) => [...str(`f${i}`), 0, 0]).flat()]; | |
| 46 | const f = parseWasm(bigSection(body))!; | |
| 47 | expect(f.exportTotal).toBe(n); | |
| 48 | expect(f.exports).toHaveLength(NAME_CAP); | |
| 49 | }); | |
| 50 | test("a cut or lying module is drawn as far as it reads, and never throws", () => { | |
| 51 | for (let cut = 8; cut < MODULE.length; cut++) expect(() => draw(MODULE.subarray(0, cut))).not.toThrow(); | |
| 52 | expect(draw(MODULE.subarray(0, MODULE.length - 3)).content.text).toContain("cut short"); | |
| 53 | expect(draw(new Uint8Array([...HEAD, 7, 0xff, 0xff, 0xff, 0xff, 0x0f])).content.text).toContain("cut short"); | |
| 54 | }); | |
| 55 | }); | |
| 56 | ||
| 57 | /** A header and one export section, its size as a two-byte LEB128. */ | |
| 58 | function bigSection(body: number[]): Uint8Array { | |
| 59 | const size = body.length; | |
| 60 | return new Uint8Array([...HEAD, 7, (size & 0x7f) | 0x80, size >> 7, ...body]); | |
| 61 | } |
test/workspace-facts.test.ts added +60
| @@ -0,0 +1,60 @@ | ||
| 1 | import { expect, test } from "bun:test"; | |
| 2 | import { factsView } from "../src/tui/screens/workspace_facts.ts"; | |
| 3 | import { CERT } from "./cert-fixture.ts"; | |
| 4 | ||
| 5 | const enc = (s: string) => new TextEncoder().encode(s); | |
| 6 | const str = (s: string) => [s.length, ...[...s].map((c) => c.charCodeAt(0))]; | |
| 7 | const section = (id: number, body: number[]) => [id, body.length, ...body]; | |
| 8 | const WASM = new Uint8Array([ | |
| 9 | 0, 0x61, 0x73, 0x6d, 1, 0, 0, 0, | |
| 10 | ...section(2, [1, ...str("env"), ...str("log"), 0, 0]), | |
| 11 | ...section(7, [1, ...str("run"), 0, 0]), | |
| 12 | ]); | |
| 13 | const rows = (v: unknown) => (v as { rows: string[][] }).rows; | |
| 14 | const header = (v: unknown) => (v as { header: string[] }).header; | |
| 15 | ||
| 16 | test("an SBOM opens as a table of components", () => { | |
| 17 | const bom = JSON.stringify({ bomFormat: "CycloneDX", components: [{ name: "left-pad", version: "1.0.0" }] }); | |
| 18 | const v = factsView("bom.json", enc(bom)); | |
| 19 | expect(header(v)).toEqual(["Name", "Version", "Licence"]); | |
| 20 | expect(rows(v)[0]).toEqual(["left-pad", "1.0.0", "-"]); | |
| 21 | }); | |
| 22 | ||
| 23 | test("a wasm module opens as its imports and exports, named by direction", () => { | |
| 24 | const v = factsView("a.wasm", WASM); | |
| 25 | expect(header(v)[0]).toBe("Direction"); | |
| 26 | expect(rows(v)).toEqual([ | |
| 27 | ["import", "env", "log", "function"], | |
| 28 | ["export", "", "run", "function"], | |
| 29 | ]); | |
| 30 | expect(factsView("a.wasm", new Uint8Array([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0]))).toContain("no imports or exports"); | |
| 31 | }); | |
| 32 | ||
| 33 | test("a certificate opens as subject, issuer, validity with its state, and names", () => { | |
| 34 | const v = factsView("a.pem", enc(CERT), Date.parse("2027-01-01")); | |
| 35 | expect(header(v)).toEqual(["Subject", "Issuer", "Not after", "Names"]); | |
| 36 | const [row] = rows(v); | |
| 37 | expect(row![0]).toBe("CN=forge.test, O=Forge"); | |
| 38 | expect(row![2]).toContain("(valid)"); | |
| 39 | expect(row![3]).toContain("DNS:forge.test"); | |
| 40 | expect(rows(factsView("a.pem", enc(CERT), Date.parse("2200-01-01")))[0]![2]).toContain("(expired)"); | |
| 41 | }); | |
| 42 | ||
| 43 | test("a block that cannot be read is counted", () => { | |
| 44 | const bad = "-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n"; | |
| 45 | const v = factsView("a.pem", enc(CERT + bad), Date.parse("2027-01-01")); | |
| 46 | expect(rows(v).at(-1)![3]).toBe("1 could not be read"); | |
| 47 | }); | |
| 48 | ||
| 49 | test("a PEM with a private key is never drawn, and a plain file is not ours", () => { | |
| 50 | const v = factsView("k.pem", enc(`-----BEGIN ${"PRIVATE"} KEY-----\nabc\n-----END ${"PRIVATE"} KEY-----\n`)); | |
| 51 | expect(v).toContain("private key"); | |
| 52 | expect(factsView("notes.txt", enc("hello"))).toBeNull(); | |
| 53 | }); | |
| 54 | ||
| 55 | test("a file over the page's cap is not opened", () => { | |
| 56 | const big = enc(CERT + "\n" + "#".repeat(1_100_000)); | |
| 57 | expect(factsView("a.pem", big)).toContain("over 1 MB"); | |
| 58 | const bigBom = enc(`{"bomFormat":"CycloneDX","x":"${"a".repeat(5_100_000)}"}`); | |
| 59 | expect(factsView("bom.json", bigBom)).toContain("over 5 MB"); | |
| 60 | }); |
new above
offline