Public: anyone can read this; the crew can change it.
A .torrent lists the files it names, their sizes and its trackers #16534
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/16024-a-torrent-lists-the-files-it-names-their → main 0 commits fork 3 threads · 3 unresolved
13 files
changed +428
−3
- docs/features/file-kinds.md
- docs/samples/hello.torrent
- scripts/kinds-guide.ts
- src/http/mcp/tools/read_file.ts
- src/tui/screens/workspace_facts.ts
- src/web/render/kinds.ts
- src/web/render/renderers.ts
- src/web/render/torrent.ts
- test/fuzz-renderers.test.ts
- test/mcp-read-file.test.ts
- test/render-kinds.test.ts
- test/render-torrent.test.ts
- test/workspace-facts.test.ts
docs/features/file-kinds.md +1
| @@ -18,6 +18,7 @@ The forge draws a file on its page when its kind is below and it is within the s | ||
| 18 | 18 | - **SQLite database**, drawn up to 5 MB: `.db`, `.sqlite`, `.sqlite3` |
| 19 | 19 | - **Parquet**, drawn up to 5 MB: `.parquet` |
| 20 | 20 | - **Packet capture**, drawn up to 5 MB: `.pcap`, `.pcapng`, `.cap` |
| 21 | - **Torrent (BitTorrent metainfo)**, drawn up to 5 MB: `.torrent` | |
| 21 | 22 | - **MIDI file**, drawn up to 5 MB: `.mid`, `.midi` |
| 22 | 23 | - **Point cloud (PCD)**, drawn up to 5 MB: `.pcd` |
| 23 | 24 | - **3D model**, drawn up to 100 MB: `.stl`, `.3mf`, `.ply`, `.glb`, `.gltf`, `.obj`, `.dae` |
docs/samples/hello.torrent added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | d8:announce31:http://tracker.example/announce7:comment22:A sample for the forge4:infod6:lengthi11e4:name9:hello.txt12:piece lengthi16384e6:pieces20:ee↵ |
scripts/kinds-guide.ts +1 −1
| @@ -10,7 +10,7 @@ export const END = "<!-- file-kinds:end -->"; | ||
| 10 | 10 | /** The name a person says for each kind. A new kind without one fails the type check. */ |
| 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 | sqlite: "SQLite database", parquet: "Parquet", pcap: "Packet capture", pcd: "Point cloud (PCD)", midi: "MIDI file", model3d: "3D model", archive: "Archive", sheet: "Spreadsheet", document: "Word document", | |
| 13 | sqlite: "SQLite database", parquet: "Parquet", pcap: "Packet capture", torrent: "Torrent (BitTorrent metainfo)", pcd: "Point cloud (PCD)", midi: "MIDI file", model3d: "3D model", archive: "Archive", sheet: "Spreadsheet", document: "Word document", | |
| 14 | 14 | slides: "Slides", layers: "Layered image", font: "Font", psd: "Photoshop", xcf: "GIMP", 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", |
src/http/mcp/tools/read_file.ts +3 −1
| @@ -9,6 +9,7 @@ import { RENDER_CAP } from "../../../web/render/kinds.ts"; | ||
| 9 | 9 | import { kicadFacts, parseKicad } from "../../../web/render/kicad.ts"; |
| 10 | 10 | import { aboutUsd } from "../../../web/render/usd.ts"; |
| 11 | 11 | import { readMidi, Unreadable } from "../../../web/render/midi.ts"; |
| 12 | import { aboutTorrent } from "../../../web/render/torrent.ts"; | |
| 12 | 13 | import { aboutPcd } from "../../../web/render/pcd.ts"; |
| 13 | 14 | import { describeMedia } from "../../../text/mp4.ts"; |
| 14 | 15 | import { readXcf } from "../../../web/render/xcf-read.ts"; |
| @@ -17,7 +18,7 @@ import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts" | ||
| 17 | 18 | |
| 18 | 19 | export const tool: Tool = { |
| 19 | 20 | name: "read_file", |
| 20 | doc: "`{ repo, path, ref? }`: a file (utf-8 or base64) or a directory listing at a ref, as GET …/contents; MP4/MOV/M4A files also carry about: {kind, seconds, width?, height?, says}, a .pcd {kind: pcd, points, width, height, data, fields, bounds?, says}; .mid {bpm, tracks}; .ifc {says}", | |
| 21 | doc: "`{ repo, path, ref? }`: a file (utf-8 or base64) or a directory listing at a ref, as GET …/contents; MP4/MOV/M4A files also carry about: {kind, seconds, width?, height?, says}, a .pcd {kind: pcd, points, width, height, data, fields, bounds?, says}; .mid {bpm, tracks}; .ifc {says}; .torrent {name, size, infoHash, trackers, files}", | |
| 21 | 22 | description: |
| 22 | 23 | "No shell? Read a file or list a directory at a ref (default branch); over 5 MB: tooLarge.", |
| 23 | 24 | inputSchema: { |
| @@ -92,6 +93,7 @@ function aboutFile(path: string, body: Uint8Array, text: string | undefined): Re | ||
| 92 | 93 | if (usd) return usd; |
| 93 | 94 | } |
| 94 | 95 | if (/\.midi?$/i.test(path)) return aboutMidi(body); |
| 96 | if (/\.torrent$/i.test(path)) return aboutTorrent(body); | |
| 95 | 97 | if (/\.pcd$/i.test(path)) return aboutPcd(body); |
| 96 | 98 | if (/\.xcf$/i.test(path)) return aboutXcf(body); |
| 97 | 99 | if (text !== undefined && /\.tfstate$/i.test(path)) return aboutTfstate(text); |
src/tui/screens/workspace_facts.ts +20 −1
| @@ -14,13 +14,15 @@ import { readCerts, SAN_CAP } from "../../web/render/cert.ts"; | ||
| 14 | 14 | import { COMPONENT_CAP, parseSbom } from "../../web/render/sbom.ts"; |
| 15 | 15 | import { parseWasm } from "../../web/render/wasm.ts"; |
| 16 | 16 | import { readMidi, Unreadable } from "../../web/render/midi.ts"; |
| 17 | import { readTorrent, Unreadable as TorrentUnreadable } from "../../web/render/torrent.ts"; | |
| 18 | import { fileSize } from "../../web/ui.ts"; | |
| 17 | 19 | import type { Table } from "../../text/csv.ts"; |
| 18 | 20 | |
| 19 | 21 | const table = (header: string[], rows: string[][], more: number): Table => ({ header, rows, more, delimiter: ",", columns: header.length }); |
| 20 | 22 | |
| 21 | 23 | export function factsView(path: string, body: Uint8Array, now: number = Date.now()): Table | string | null { |
| 22 | 24 | const kind = fileKind(path, body.subarray(0, HEAD_BYTES)); |
| 23 | if (kind !== "cert" && kind !== "sbom" && kind !== "wasm" && kind !== "midi") return null; | |
| 25 | if (kind !== "cert" && kind !== "sbom" && kind !== "wasm" && kind !== "midi" && kind !== "torrent") return null; | |
| 24 | 26 | if (body.length > RENDER_CAP[kind]) |
| 25 | 27 | return `This file is over ${RENDER_CAP[kind] / 1_000_000} MB, too large to open here. Download it instead.`; |
| 26 | 28 | if (kind === "cert") { |
| @@ -32,6 +34,23 @@ export function factsView(path: string, body: Uint8Array, now: number = Date.now | ||
| 32 | 34 | if (bad > 0) rows.push(["", "", "", `${bad} could not be read`]); |
| 33 | 35 | return table(["Subject", "Issuer", "Not after", "Names"], rows, total - certs.length); |
| 34 | 36 | } |
| 37 | if (kind === "torrent") { | |
| 38 | try { | |
| 39 | const t = readTorrent(body); | |
| 40 | const rows = [ | |
| 41 | ["name", t.name], | |
| 42 | ["size", fileSize(t.size)], | |
| 43 | ["piece length", fileSize(t.pieceLength)], | |
| 44 | ["info hash", t.infoHash], | |
| 45 | ...t.trackers.map((u) => ["tracker", u]), | |
| 46 | ...t.files.map((f) => ["file", `${f.path} (${fileSize(f.length)})`]), | |
| 47 | ]; | |
| 48 | return table(["Fact", "Value"], rows, t.trackerTotal - t.trackers.length + t.fileTotal - t.files.length); | |
| 49 | } catch (e) { | |
| 50 | if (e instanceof TorrentUnreadable) return `This file is not drawn as a torrent: ${e.message}.`; | |
| 51 | throw e; | |
| 52 | } | |
| 53 | } | |
| 35 | 54 | if (kind === "midi") { |
| 36 | 55 | try { |
| 37 | 56 | const m = readMidi(body); |
src/web/render/kinds.ts +11
| @@ -30,6 +30,7 @@ export type FileKind = | ||
| 30 | 30 | | "sqlite" |
| 31 | 31 | | "parquet" |
| 32 | 32 | | "pcap" |
| 33 | | "torrent" | |
| 33 | 34 | | "midi" |
| 34 | 35 | | "pcd" |
| 35 | 36 | | "model3d" |
| @@ -130,6 +131,8 @@ export const RENDER_CAP: Readonly<Record<FileKind, number>> = { | ||
| 130 | 131 | parquet: 5 * MB, |
| 131 | 132 | // Packet records are walked by their headers; the page reads the whole body. |
| 132 | 133 | pcap: 5 * MB, |
| 134 | // Bencode is walked once, bounded by depth and value count; the page reads the whole body. | |
| 135 | torrent: 5 * MB, | |
| 133 | 136 | // Events are walked by their lengths, bounded by the chunk; the page reads the whole body. |
| 134 | 137 | midi: 5 * MB, |
| 135 | 138 | // Parsed whole for its header and a sample of at most 5,000 points; over it the source is kept. |
| @@ -587,6 +590,10 @@ function confirmed(path: string, head: Uint8Array): Media | undefined { | ||
| 587 | 590 | return media; |
| 588 | 591 | } |
| 589 | 592 | |
| 593 | /** A metainfo is a bencoded dictionary: `d`, then the length of its first key. */ | |
| 594 | const isTorrent = (path: string, head: Uint8Array): boolean => | |
| 595 | extension(path) === "torrent" && head[0] === 0x64 && head[1]! >= 0x31 && head[1]! <= 0x39; | |
| 596 | ||
| 590 | 597 | /** |
| 591 | 598 | * What a file is, from its name and its first bytes (`HEAD_BYTES` is enough). |
| 592 | 599 | * A name the bytes contradict — a `.png` that is not a PNG — is read as the |
| @@ -600,6 +607,7 @@ export function fileKind(path: string, head: Uint8Array): FileKind { | ||
| 600 | 607 | if (office !== undefined) return office; |
| 601 | 608 | if (isArchive(path, head)) return "archive"; |
| 602 | 609 | if (isPcap(path, head)) return "pcap"; |
| 610 | if (isTorrent(path, head)) return "torrent"; | |
| 603 | 611 | if (isMidi(path, head)) return "midi"; |
| 604 | 612 | if (isPcd(path, head)) return "pcd"; |
| 605 | 613 | // A CAD or 3D source is named by its magic as well as its name, and has NULs in its head. |
| @@ -669,6 +677,7 @@ export function kindByName(path: string): FileKind { | ||
| 669 | 677 | if (isComposeName(path)) return "compose"; |
| 670 | 678 | if (ext === "xlsx") return "sheet"; |
| 671 | 679 | if (ext === "pcap" || ext === "pcapng" || ext === "cap") return "pcap"; |
| 680 | if (ext === "torrent") return "torrent"; | |
| 672 | 681 | if (ext === "mid" || ext === "midi") return "midi"; |
| 673 | 682 | if (ext === "pcd") return "pcd"; |
| 674 | 683 | if (ext === "wasm") return "wasm"; |
| @@ -709,6 +718,7 @@ export const KNOWN_EXTENSIONS: readonly string[] = [ | ||
| 709 | 718 | "pcap", |
| 710 | 719 | "pcapng", |
| 711 | 720 | "cap", |
| 721 | "torrent", | |
| 712 | 722 | "mid", |
| 713 | 723 | "midi", |
| 714 | 724 | "wasm", |
| @@ -784,6 +794,7 @@ const SNIFFED_EXTENSIONS: Readonly<Partial<Record<FileKind, readonly string[]>>> | ||
| 784 | 794 | sheet: ["xlsx"], |
| 785 | 795 | archive: ["zip", "tar", "tgz"], |
| 786 | 796 | pcap: ["pcap", "pcapng", "cap"], |
| 797 | torrent: ["torrent"], | |
| 787 | 798 | midi: ["mid", "midi"], |
| 788 | 799 | pcd: ["pcd"], |
| 789 | 800 | wasm: ["wasm"], |
src/web/render/renderers.ts +2
| @@ -79,6 +79,7 @@ import { ora } from "./ora.ts"; | ||
| 79 | 79 | import { sqlite } from "./sqlite.ts"; |
| 80 | 80 | import { parquet } from "./parquet.ts"; |
| 81 | 81 | import { pcap } from "./pcap.ts"; |
| 82 | import { torrent } from "./torrent.ts"; | |
| 82 | 83 | import { midi } from "./midi.ts"; |
| 83 | 84 | import { pcd } from "./pcd.ts"; |
| 84 | 85 | import { subtitles } from "./subtitles.ts"; |
| @@ -152,6 +153,7 @@ export const RENDERERS: Partial<Readonly<Record<FileKind, Renderer>>> = { | ||
| 152 | 153 | sqlite, |
| 153 | 154 | parquet, |
| 154 | 155 | pcap, |
| 156 | torrent, | |
| 155 | 157 | midi, |
| 156 | 158 | pcd, |
| 157 | 159 | audio, |
src/web/render/torrent.ts added +252
| @@ -0,0 +1,252 @@ | ||
| 1 | /** | |
| 2 | * A BitTorrent metainfo (.torrent) as facts: name, total size, piece length, info hash, trackers | |
| 3 | * and a file table. Bencode is read by hand, nothing is fetched and nothing runs. | |
| 4 | * | |
| 5 | * Bounds: the file is capped by `RENDER_CAP.torrent` before it gets here; every read is checked | |
| 6 | * against the bytes left; nesting is `DEPTH_CAP` deep and the walk counts `NODE_CAP` values, so a | |
| 7 | * hostile file cannot recurse or loop without end; a length that overruns the file is an error, | |
| 8 | * never an allocation. Only `FILE_CAP` files and `TRACKER_CAP` trackers are drawn; the rest are | |
| 9 | * counted. A file that does not parse keeps the source view with one sentence. | |
| 10 | */ | |
| 11 | ||
| 12 | import { createHash } from "node:crypto"; | |
| 13 | import { escapeHtml, html, raw } from "../html.ts"; | |
| 14 | import { fileSize } from "../ui.ts"; | |
| 15 | import type { Rendered, RenderInput } from "./renderers.ts"; | |
| 16 | ||
| 17 | export const FILE_CAP = 500; | |
| 18 | export const TRACKER_CAP = 50; | |
| 19 | const DEPTH_CAP = 32; | |
| 20 | const NODE_CAP = 500_000; | |
| 21 | ||
| 22 | /** Thrown with a sentence-sized reason when the file cannot be shown as a torrent. */ | |
| 23 | export class Unreadable extends Error {} | |
| 24 | ||
| 25 | type Value = number | Uint8Array | Value[] | { [key: string]: Value }; | |
| 26 | type Dict = { [key: string]: Value }; | |
| 27 | ||
| 28 | interface Span { value: Value; start: number; end: number } | |
| 29 | ||
| 30 | const DIGIT0 = 0x30; | |
| 31 | const DIGIT9 = 0x39; | |
| 32 | ||
| 33 | class Reader { | |
| 34 | private pos = 0; | |
| 35 | private nodes = 0; | |
| 36 | /** The raw span of the top-level `info` value, whose SHA-1 is the info hash. */ | |
| 37 | info: { start: number; end: number } | undefined; | |
| 38 | constructor(private readonly b: Uint8Array) {} | |
| 39 | ||
| 40 | private int(stop: number): number { | |
| 41 | const start = this.pos; | |
| 42 | if (this.b[this.pos] === 0x2d) this.pos++; | |
| 43 | const digits = this.pos; | |
| 44 | while (this.pos < this.b.length && this.b[this.pos]! >= DIGIT0 && this.b[this.pos]! <= DIGIT9) this.pos++; | |
| 45 | const n = this.pos - digits; | |
| 46 | if (n === 0 || n > 16 || this.b[this.pos] !== stop) throw new Unreadable("a number in it is malformed"); | |
| 47 | const text = new TextDecoder().decode(this.b.subarray(start, this.pos)); | |
| 48 | if ((this.b[digits] === DIGIT0 && n > 1) || text === "-0") throw new Unreadable("a number in it is malformed"); | |
| 49 | this.pos++; | |
| 50 | return Number(text); | |
| 51 | } | |
| 52 | ||
| 53 | value(depth: number): Span { | |
| 54 | if (++this.nodes > NODE_CAP) throw new Unreadable("it holds too many values"); | |
| 55 | if (depth > DEPTH_CAP) throw new Unreadable("it is nested too deeply"); | |
| 56 | if (this.pos >= this.b.length) throw new Unreadable("it ends inside a value"); | |
| 57 | const start = this.pos; | |
| 58 | const c = this.b[this.pos]!; | |
| 59 | if (c === 0x69) { | |
| 60 | this.pos++; | |
| 61 | return { value: this.int(0x65), start, end: this.pos }; | |
| 62 | } | |
| 63 | if (c >= DIGIT0 && c <= DIGIT9) { | |
| 64 | const len = this.int(0x3a); | |
| 65 | if (len < 0 || len > this.b.length - this.pos) throw new Unreadable("a length in it runs past the end of the file"); | |
| 66 | const s = this.b.subarray(this.pos, this.pos + len); | |
| 67 | this.pos += len; | |
| 68 | return { value: s, start, end: this.pos }; | |
| 69 | } | |
| 70 | if (c === 0x6c) { | |
| 71 | this.pos++; | |
| 72 | const list: Value[] = []; | |
| 73 | while (this.b[this.pos] !== 0x65) list.push(this.value(depth + 1).value); | |
| 74 | this.pos++; | |
| 75 | return { value: list, start, end: this.pos }; | |
| 76 | } | |
| 77 | if (c === 0x64) { | |
| 78 | this.pos++; | |
| 79 | const dict: Dict = Object.create(null) as Dict; | |
| 80 | while (this.b[this.pos] !== 0x65) { | |
| 81 | const key = this.value(depth + 1).value; | |
| 82 | if (!(key instanceof Uint8Array)) throw new Unreadable("a dictionary key in it is not a string"); | |
| 83 | const name = new TextDecoder().decode(key); | |
| 84 | const v = this.value(depth + 1); | |
| 85 | if (depth === 0 && name === "info") this.info = { start: v.start, end: v.end }; | |
| 86 | dict[name] = v.value; | |
| 87 | } | |
| 88 | this.pos++; | |
| 89 | return { value: dict, start, end: this.pos }; | |
| 90 | } | |
| 91 | throw new Unreadable("it is not bencoded"); | |
| 92 | } | |
| 93 | ||
| 94 | done(): boolean { | |
| 95 | return this.pos === this.b.length; | |
| 96 | } | |
| 97 | } | |
| 98 | ||
| 99 | export interface TorrentFile { readonly path: string; readonly length: number } | |
| 100 | export interface Torrent { | |
| 101 | readonly name: string; | |
| 102 | readonly size: number; | |
| 103 | readonly pieceLength: number; | |
| 104 | readonly pieces: number; | |
| 105 | readonly infoHash: string; | |
| 106 | readonly private: boolean; | |
| 107 | readonly comment: string; | |
| 108 | readonly createdBy: string; | |
| 109 | readonly created: string; | |
| 110 | readonly trackers: readonly string[]; | |
| 111 | readonly trackerTotal: number; | |
| 112 | readonly files: readonly TorrentFile[]; | |
| 113 | readonly fileTotal: number; | |
| 114 | } | |
| 115 | ||
| 116 | const text = (v: Value | undefined): string => (v instanceof Uint8Array ? new TextDecoder().decode(v) : ""); | |
| 117 | const isDict = (v: Value | undefined): v is Dict => typeof v === "object" && v !== null && !(v instanceof Uint8Array) && !Array.isArray(v); | |
| 118 | const length = (v: Value | undefined): number => { | |
| 119 | if (typeof v !== "number" || v < 0) throw new Unreadable("a file length in it is not a size"); | |
| 120 | return v; | |
| 121 | }; | |
| 122 | ||
| 123 | /** The torrent as plain data; throws `Unreadable` when it is not a metainfo this can show. */ | |
| 124 | export function readTorrent(body: Uint8Array): Torrent { | |
| 125 | if (body.length < 2 || body[0] !== 0x64) throw new Unreadable("it is not a bencoded dictionary"); | |
| 126 | const r = new Reader(body); | |
| 127 | const top = r.value(0).value; | |
| 128 | if (!r.done()) throw new Unreadable("it has bytes after the dictionary"); | |
| 129 | if (!isDict(top) || !isDict(top["info"]) || r.info === undefined) throw new Unreadable("it has no info dictionary"); | |
| 130 | const info = top["info"]; | |
| 131 | const pieceLength = info["piece length"]; | |
| 132 | const pieces = info["pieces"]; | |
| 133 | if (typeof pieceLength !== "number" || pieceLength <= 0) throw new Unreadable("its piece length is missing"); | |
| 134 | if (!(pieces instanceof Uint8Array) || pieces.length % 20 !== 0) throw new Unreadable("its piece hashes are missing (a version 2 only torrent is not read here)"); | |
| 135 | const name = text(info["name.utf-8"]) || text(info["name"]); | |
| 136 | ||
| 137 | const files: TorrentFile[] = []; | |
| 138 | let fileTotal = 0; | |
| 139 | let size = 0; | |
| 140 | const list = info["files"]; | |
| 141 | if (Array.isArray(list)) { | |
| 142 | for (const f of list) { | |
| 143 | if (!isDict(f) || !Array.isArray(f["path"])) throw new Unreadable("a file entry in it is malformed"); | |
| 144 | const n = length(f["length"]); | |
| 145 | size += n; | |
| 146 | if (!Number.isSafeInteger(size)) throw new Unreadable("its total size is out of range"); | |
| 147 | fileTotal++; | |
| 148 | if (files.length < FILE_CAP) { | |
| 149 | const parts = (Array.isArray(f["path.utf-8"]) ? f["path.utf-8"] : f["path"]).map((p) => text(p)); | |
| 150 | files.push({ path: parts.join("/"), length: n }); | |
| 151 | } | |
| 152 | } | |
| 153 | } else { | |
| 154 | size = length(info["length"]); | |
| 155 | fileTotal = 1; | |
| 156 | files.push({ path: name, length: size }); | |
| 157 | } | |
| 158 | ||
| 159 | const trackers: string[] = []; | |
| 160 | const seen = new Set<string>(); | |
| 161 | const add = (v: Value | undefined): void => { | |
| 162 | const t = text(v); | |
| 163 | if (t === "" || seen.has(t)) return; | |
| 164 | seen.add(t); | |
| 165 | if (trackers.length < TRACKER_CAP) trackers.push(t); | |
| 166 | }; | |
| 167 | add(top["announce"]); | |
| 168 | const tiers = top["announce-list"]; | |
| 169 | if (Array.isArray(tiers)) for (const tier of tiers) if (Array.isArray(tier)) for (const t of tier) add(t); | |
| 170 | ||
| 171 | const when = top["creation date"]; | |
| 172 | const date = typeof when === "number" && when >= 0 && when < 8.64e12 / 1000 ? new Date(when * 1000).toISOString().slice(0, 10) : ""; | |
| 173 | return { | |
| 174 | name, | |
| 175 | size, | |
| 176 | pieceLength, | |
| 177 | pieces: pieces.length / 20, | |
| 178 | infoHash: createHash("sha1").update(body.subarray(r.info.start, r.info.end)).digest("hex"), | |
| 179 | private: info["private"] === 1, | |
| 180 | comment: text(top["comment"]), | |
| 181 | createdBy: text(top["created by"]), | |
| 182 | created: date, | |
| 183 | trackers, | |
| 184 | trackerTotal: seen.size, | |
| 185 | files, | |
| 186 | fileTotal, | |
| 187 | }; | |
| 188 | } | |
| 189 | ||
| 190 | /** The facts as the MCP file tool answers them. */ | |
| 191 | export function aboutTorrent(body: Uint8Array): Record<string, unknown> { | |
| 192 | try { | |
| 193 | const t = readTorrent(body); | |
| 194 | return { | |
| 195 | kind: "torrent", | |
| 196 | name: t.name, | |
| 197 | size: t.size, | |
| 198 | pieceLength: t.pieceLength, | |
| 199 | pieces: t.pieces, | |
| 200 | infoHash: t.infoHash, | |
| 201 | private: t.private, | |
| 202 | trackers: t.trackers, | |
| 203 | files: t.files.slice(0, 20).map((f) => [f.path, f.length]), | |
| 204 | fileTotal: t.fileTotal, | |
| 205 | says: `torrent, ${t.fileTotal} file${t.fileTotal === 1 ? "" : "s"}, ${fileSize(t.size)}`, | |
| 206 | }; | |
| 207 | } catch (e) { | |
| 208 | return { kind: "torrent", says: `torrent, unreadable: ${e instanceof Unreadable ? e.message : "it could not be read"}` }; | |
| 209 | } | |
| 210 | } | |
| 211 | ||
| 212 | const plural = (n: number, one: string): string => `${n.toLocaleString()} ${one}${n === 1 ? "" : "s"}`; | |
| 213 | const clean = (s: string): string => escapeHtml(s.replace(/[\u0000-\u001f\u007f]/g, "�")); | |
| 214 | ||
| 215 | export function torrent(input: RenderInput): Rendered { | |
| 216 | let t: Torrent; | |
| 217 | try { | |
| 218 | t = readTorrent(input.body); | |
| 219 | } catch (e) { | |
| 220 | const why = e instanceof Unreadable ? e.message : "it could not be read"; | |
| 221 | return { content: html``, lines: 0, fallback: `This torrent cannot be shown as facts: ${why}.` }; | |
| 222 | } | |
| 223 | const summary = `torrent · ${plural(t.fileTotal, "file")} · ${fileSize(t.size)}`; | |
| 224 | const facts: [string, string][] = [ | |
| 225 | ["Name", t.name], | |
| 226 | ["Total size", `${fileSize(t.size)} (${t.size.toLocaleString()} bytes)`], | |
| 227 | ["Piece length", fileSize(t.pieceLength)], | |
| 228 | ["Pieces", t.pieces.toLocaleString()], | |
| 229 | ["Info hash", t.infoHash], | |
| 230 | ]; | |
| 231 | if (t.private) facts.push(["Private", "yes"]); | |
| 232 | if (t.created !== "") facts.push(["Created", t.created]); | |
| 233 | if (t.createdBy !== "") facts.push(["Created by", t.createdBy]); | |
| 234 | if (t.comment !== "") facts.push(["Comment", t.comment]); | |
| 235 | const dl = facts.map(([k, v]) => `<div class="status-row"><dt>${escapeHtml(k)}</dt><dd>${clean(v)}</dd></div>`).join(""); | |
| 236 | const trackers = t.trackers.map((u) => `<tr><td>${clean(u)}</td></tr>`).join(""); | |
| 237 | const rows = t.files | |
| 238 | .map((f) => `<tr><td>${clean(f.path)}</td><td class="num">${fileSize(f.length)}</td></tr>`) | |
| 239 | .join(""); | |
| 240 | const notes: string[] = []; | |
| 241 | if (t.trackerTotal > t.trackers.length) notes.push(`${(t.trackerTotal - t.trackers.length).toLocaleString()} more trackers are not shown.`); | |
| 242 | if (t.fileTotal > t.files.length) notes.push(`${(t.fileTotal - t.files.length).toLocaleString()} of ${t.fileTotal.toLocaleString()} files are not shown.`); | |
| 243 | const content = [ | |
| 244 | `<dl class="status-rows" aria-label="Torrent">${dl}</dl>`, | |
| 245 | t.trackers.length === 0 | |
| 246 | ? `<p class="muted small">No trackers are named.</p>` | |
| 247 | : `<div class="csv-scroll"><table class="table" data-dense aria-label="Trackers"><thead><tr><th>Tracker</th></tr></thead><tbody>${trackers}</tbody></table></div>`, | |
| 248 | `<div class="csv-scroll"><table class="table" data-dense aria-label="Files"><thead><tr><th>File</th><th class="num">Size</th></tr></thead><tbody>${rows}</tbody></table></div>`, | |
| 249 | ...notes.map((n) => `<p class="muted small">${escapeHtml(n)}</p>`), | |
| 250 | ].join("\n"); | |
| 251 | return { content: html`${raw(content)}`, lines: 0, summary }; | |
| 252 | } |
test/fuzz-renderers.test.ts +9
| @@ -177,6 +177,14 @@ export const SAMPLES: Readonly<Record<string, { path: string; files: readonly st | ||
| 177 | 177 | path: "m.wasm", |
| 178 | 178 | files: ["\u0000asm\u0001\u0000\u0000\u0000\u0002\u0007\u0001\u0001a\u0001b\u0000\u0000\u0007\u0005\u0001\u0001f\u0000\u0000"], |
| 179 | 179 | }, |
| 180 | torrent: { | |
| 181 | // Every byte below 0x80 so it survives the text round trip: one file, one tracker, a 20-byte | |
| 182 | // piece. | |
| 183 | path: "a.torrent", | |
| 184 | files: [ | |
| 185 | "d8:announce21:http://t.test/a?x=<b>4:infod6:lengthi5e4:name5:<b>a<12:piece lengthi16384e6:pieces20:aaaaaaaaaaaaaaaaaaaaee", | |
| 186 | ], | |
| 187 | }, | |
| 180 | 188 | lcov: { |
| 181 | 189 | path: "lcov.info", |
| 182 | 190 | 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"], |
| @@ -672,6 +680,7 @@ export const RAW_PATHS: Readonly<Record<string, string>> = { | ||
| 672 | 680 | sqlite: "a.sqlite", |
| 673 | 681 | parquet: "a.parquet", |
| 674 | 682 | pcap: "a.pcap", |
| 683 | torrent: "a.torrent", | |
| 675 | 684 | archive: "a.zip", |
| 676 | 685 | sheet: "a.xlsx", |
| 677 | 686 | document: "a.docx", |
test/mcp-read-file.test.ts +8
| @@ -84,6 +84,7 @@ beforeAll(async () => { | ||
| 84 | 84 | files: [ |
| 85 | 85 | { path: "song.mid", content: Uint8Array.from([0x4d, 0x54, 0x68, 0x64, 0, 0, 0, 6, 0, 0, 0, 1, 1, 0xe0, 0x4d, 0x54, 0x72, 0x6b, 0, 0, 0, 12, 0, 0x90, 60, 100, 0x60, 0x80, 60, 0, 0, 0xff, 0x2f, 0]) }, |
| 86 | 86 | { path: "bad.mid", content: "not midi" }, |
| 87 | { path: "a.torrent", content: "d8:announce6:http:/4:infod6:lengthi5e4:name1:a12:piece lengthi16384e6:pieces20:aaaaaaaaaaaaaaaaaaaaee" }, | |
| 87 | 88 | { path: "cube.stl", content: binaryBox(40, 20, 10) }, |
| 88 | 89 | { path: "cube-ascii.STL", content: asciiBox(40, 20, 10) }, |
| 89 | 90 | { path: "broken.stl", content: binaryBox(1, 1, 1).subarray(0, 100) }, |
| @@ -164,6 +165,13 @@ test("a MIDI file is described by its tracks, tempo and first notes", async () = | ||
| 164 | 165 | expect((await read(t, { repo: "ada/pub", path: "bad.mid" })).value.about.says).toContain("unreadable"); |
| 165 | 166 | }); |
| 166 | 167 | |
| 168 | test("a torrent is described by its name, size, hash and trackers", async () => { | |
| 169 | const t = tok["stranger"]!; | |
| 170 | const about = (await read(t, { repo: "ada/pub", path: "a.torrent" })).value.about; | |
| 171 | expect(about).toMatchObject({ kind: "torrent", name: "a", size: 5, pieceLength: 16384, trackers: ["http:/"], fileTotal: 1 }); | |
| 172 | expect(about.infoHash).toMatch(/^[0-9a-f]{40}$/); | |
| 173 | }); | |
| 174 | ||
| 167 | 175 | test("a config file says whether it parses; other files carry no about", async () => { |
| 168 | 176 | const t = tok["owner"]!; |
| 169 | 177 | const bad = await read(t, { repo: "ada/pub", path: "bad.json" }); |
test/render-kinds.test.ts +1
| @@ -139,6 +139,7 @@ const SAMPLES: Record<string, [Uint8Array, FileKind, string]> = { | ||
| 139 | 139 | crt: [enc("-----BEGIN CERTIFICATE-----\n"), "cert", "application/octet-stream"], |
| 140 | 140 | cer: [enc("-----BEGIN CERTIFICATE-----\n"), "cert", "application/octet-stream"], |
| 141 | 141 | wasm: [of(0, 0x61, 0x73, 0x6d, 1, 0, 0, 0), "wasm", "application/octet-stream"], |
| 142 | torrent: [enc("d4:infod4:name1:aee"), "torrent", "application/octet-stream"], | |
| 142 | 143 | lcov: [enc("SF:a.ts\nend_of_record\n"), "lcov", "application/octet-stream"], |
| 143 | 144 | }; |
| 144 | 145 |
test/render-torrent.test.ts added +103
| @@ -0,0 +1,103 @@ | ||
| 1 | /** A .torrent (built here) as facts: parse, escape, cap, malformed. */ | |
| 2 | import { describe, expect, test } from "bun:test"; | |
| 3 | import { createHash } from "node:crypto"; | |
| 4 | import { fileKind, kindMatches, RENDER_CAP } from "../src/web/render/kinds.ts"; | |
| 5 | import { aboutTorrent, FILE_CAP, readTorrent, torrent } from "../src/web/render/torrent.ts"; | |
| 6 | import type { Blob } from "../src/view/source.ts"; | |
| 7 | import { RENDERERS, rendererFor } from "../src/web/render/renderers.ts"; | |
| 8 | ||
| 9 | const enc = (s: string) => new TextEncoder().encode(s); | |
| 10 | const cat = (...parts: Uint8Array[]) => new Uint8Array(Buffer.concat(parts)); | |
| 11 | const str = (s: string) => `${s.length}:${s}`; | |
| 12 | const PIECES = "p".repeat(20); | |
| 13 | const INFO = (extra = "") => `d${str("length")}i5e${str("name")}${str("a.iso")}${str("piece length")}i16384e${str("pieces")}20:${PIECES}${extra}e`; | |
| 14 | const META = (info: string, top = "") => enc(`d${str("announce")}${str("http://t.test/a")}${top}${str("info")}${info}e`); | |
| 15 | const draw = (body: Uint8Array) => torrent({ path: "a.torrent", size: body.length, body, media: "/m", download: "/d" }); | |
| 16 | ||
| 17 | describe("a torrent", () => { | |
| 18 | test("is a torrent by its name and bencode head together", () => { | |
| 19 | const body = META(INFO()); | |
| 20 | expect(fileKind("a.torrent", body)).toBe("torrent"); | |
| 21 | expect(fileKind("a.torrent", enc("hello"))).toBe("text"); | |
| 22 | expect(RENDERERS.torrent).toBeDefined(); | |
| 23 | expect(kindMatches("torrent")).toEqual([".torrent"]); | |
| 24 | expect(RENDER_CAP.torrent).toBe(5_000_000); | |
| 25 | }); | |
| 26 | ||
| 27 | test("lists name, size, piece length, info hash and trackers", () => { | |
| 28 | const info = INFO(); | |
| 29 | const t = readTorrent(META(info, `${str("announce-list")}ll${str("http://u.test/b")}el${str("http://t.test/a")}ee`)); | |
| 30 | expect(t).toMatchObject({ name: "a.iso", size: 5, pieceLength: 16384, pieces: 1 }); | |
| 31 | expect(t.infoHash).toBe(createHash("sha1").update(enc(info)).digest("hex")); | |
| 32 | expect(t.trackers).toEqual(["http://t.test/a", "http://u.test/b"]); | |
| 33 | const r = draw(META(info)); | |
| 34 | expect(r.summary).toBe("torrent · 1 file · 5 B"); | |
| 35 | expect(r.content.text).toContain(t.infoHash); | |
| 36 | expect(r.content.text).toContain("<td>http://t.test/a</td>"); | |
| 37 | }); | |
| 38 | ||
| 39 | test("lists a multi-file torrent's files and sums their sizes", () => { | |
| 40 | const files = `${str("files")}ld${str("length")}i10e${str("path")}l${str("d")}${str("x.txt")}eed${str("length")}i20e${str("path")}l${str("y")}eee`; | |
| 41 | const info = `d${files}${str("name")}${str("dir")}${str("piece length")}i16384e${str("pieces")}20:${PIECES}e`; | |
| 42 | const t = readTorrent(META(info)); | |
| 43 | expect(t.size).toBe(30); | |
| 44 | expect(t.files.map((f) => f.path)).toEqual(["d/x.txt", "y"]); | |
| 45 | expect(draw(META(info)).summary).toContain("2 files"); | |
| 46 | }); | |
| 47 | ||
| 48 | test("escapes every value drawn from the file", () => { | |
| 49 | const info = `d${str("length")}i1e${str("name")}${str("<script>x</script>")}${str("piece length")}i16384e${str("pieces")}20:${PIECES}e`; | |
| 50 | const body = META(info, `${str("comment")}${str('"><img src=x onerror=1>')}`); | |
| 51 | const t = draw(cat(body)).content.text; | |
| 52 | expect(t).not.toContain("<script>"); | |
| 53 | expect(t).not.toContain("<img"); | |
| 54 | expect(t).toContain("<script>"); | |
| 55 | const tracker = enc(`d${str("announce")}${str("<i>t</i>")}${str("info")}${INFO()}e`); | |
| 56 | expect(draw(tracker).content.text).toContain("<i>t</i>"); | |
| 57 | }); | |
| 58 | ||
| 59 | test("draws FILE_CAP files and counts the rest", () => { | |
| 60 | const one = `d${str("length")}i1e${str("path")}l${str("f")}ee`; | |
| 61 | const info = `d${str("files")}l${one.repeat(FILE_CAP + 5)}e${str("name")}${str("n")}${str("piece length")}i16384e${str("pieces")}20:${PIECES}e`; | |
| 62 | const body = META(info); | |
| 63 | const t = readTorrent(body); | |
| 64 | expect(t.files.length).toBe(FILE_CAP); | |
| 65 | expect(t.fileTotal).toBe(FILE_CAP + 5); | |
| 66 | expect(draw(body).content.text).toContain("5 of 505 files are not shown."); | |
| 67 | }); | |
| 68 | ||
| 69 | test("a file over the cap keeps the source view and says why", () => { | |
| 70 | const blob: Blob = { kind: "text", body: new Uint8Array(0), size: RENDER_CAP.torrent + 1 }; | |
| 71 | expect(rendererFor("a.torrent", blob)).toBeUndefined(); | |
| 72 | }); | |
| 73 | ||
| 74 | test("hostile structure is refused before it loops or recurses", () => { | |
| 75 | const deep = enc(`d${str("info")}${"l".repeat(5000)}`); | |
| 76 | expect(() => readTorrent(deep)).toThrow("deeply"); | |
| 77 | expect(() => readTorrent(enc(`d${str("info")}d${str("a")}999999999:xee`))).toThrow("past the end"); | |
| 78 | expect(() => readTorrent(enc(`d${str("info")}${"i1e".repeat(1)}`))).toThrow(); | |
| 79 | const many = enc(`d${str("info")}l${"i1e".repeat(600_000)}ee`); | |
| 80 | expect(() => readTorrent(many)).toThrow("too many"); | |
| 81 | const lying = META(INFO().replace("i5e", "i99999999999999999999e")); | |
| 82 | expect(() => readTorrent(lying)).toThrow(); | |
| 83 | }); | |
| 84 | ||
| 85 | test("a malformed file falls back with one sentence", () => { | |
| 86 | for (const bad of [enc("d"), enc("d4:infoe"), enc("de"), META(INFO().replace("20:", "19:")), cat(META(INFO()), enc("x"))]) { | |
| 87 | const r = draw(bad); | |
| 88 | expect(r.fallback).toMatch(/^This torrent cannot be shown as facts: .+\.$/); | |
| 89 | } | |
| 90 | }); | |
| 91 | ||
| 92 | test("trackers repeated past the cap are counted once", () => { | |
| 93 | const urls = Array.from({ length: 60 }, (_, i) => str(`http://t${i}.test/a`)).join(""); | |
| 94 | const t = readTorrent(META(INFO(), `${str("announce-list")}ll${urls}${urls}ee`)); | |
| 95 | expect(t.trackerTotal).toBe(61); | |
| 96 | }); | |
| 97 | ||
| 98 | test("the MCP file tool's facts match", () => { | |
| 99 | const about = aboutTorrent(META(INFO())); | |
| 100 | expect(about).toMatchObject({ kind: "torrent", name: "a.iso", size: 5, trackers: ["http://t.test/a"], fileTotal: 1 }); | |
| 101 | expect(aboutTorrent(enc("nope"))["says"]).toContain("unreadable"); | |
| 102 | }); | |
| 103 | }); |
test/workspace-facts.test.ts +16
| @@ -71,3 +71,19 @@ test("a MIDI file opens as a table of tracks with their notes and tempo", () => | ||
| 71 | 71 | expect(rows(v)).toEqual([["1", "Piano", "1", "1"]]); |
| 72 | 72 | expect(factsView("a.mid", enc("MThd"))).toContain("not drawn as MIDI"); |
| 73 | 73 | }); |
| 74 | ||
| 75 | test("a torrent opens as its name, size, info hash, trackers and files", () => { | |
| 76 | const s = (v: string) => `${v.length}:${v}`; | |
| 77 | const pieces = "p".repeat(20); | |
| 78 | const file = (n: number, p: string) => `d${s("length")}i${n}e${s("path")}l${s(p)}ee`; | |
| 79 | const info = `d${s("files")}l${file(10, "x.txt")}${file(20, "y")}e${s("name")}${s("dir")}${s("piece length")}i16384e${s("pieces")}20:${pieces}e`; | |
| 80 | const body = enc(`d${s("announce")}${s("http://t.test/a")}${s("info")}${info}e`); | |
| 81 | const v = factsView("a.torrent", body); | |
| 82 | expect(header(v)).toEqual(["Fact", "Value"]); | |
| 83 | const r = rows(v); | |
| 84 | expect(r[0]).toEqual(["name", "dir"]); | |
| 85 | expect(r.map((x) => x[0])).toEqual(["name", "size", "piece length", "info hash", "tracker", "file", "file"]); | |
| 86 | expect(r[3]![1]).toBe(new Bun.CryptoHasher("sha1").update(info).digest("hex")); | |
| 87 | expect(r[5]![1]).toContain("x.txt (10 B)"); | |
| 88 | expect(factsView("a.torrent", enc("d4:infoe"))).toContain("not drawn as a torrent"); | |
| 89 | }); |
new above
offline
This helper sits between the
fileKinddoc comment andfileKind, so the comment now documentsisTorrent. Move it above that comment.