Public: anyone can read this; the crew can change it.
A Windows .reg file reads as a table of keys and values, with what it deletes called out #16786
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/16027-a-windows-reg-file-reads-as-a-table-of-k → main 0 commits fork 1 thread · 1 unresolved
14 files
changed +416
−3
- docs/examples/settings.reg
- docs/features/file-kinds.md
- docs/features/registry.md
- scripts/kinds-guide.ts
- src/http/mcp/tools/read_file.ts
- src/tui/screens/workspace.ts
- src/tui/screens/workspace_registry.ts
- src/web/render/kinds.ts
- src/web/render/reg.ts
- src/web/render/renderers.ts
- test/fuzz-renderers.test.ts
- test/mcp-read-file.test.ts
- test/render-kinds.test.ts
- test/render-registry.test.ts
docs/examples/settings.reg added +12
| @@ -0,0 +1,12 @@ | ||
| 1 | Windows Registry Editor Version 5.00 | |
| 2 | ||
| 3 | ; An export: what it sets, and what it removes. | |
| 4 | [HKEY_CURRENT_USER\Software\Example\App] | |
| 5 | @="Example App" | |
| 6 | "Name"="Example" | |
| 7 | "Enabled"=dword:00000001 | |
| 8 | "Token"=hex:de,ad,be,ef,00,01 | |
| 9 | "Path"=hex(2):25,00,50,00,41,00,54,00,48,00,25,00,00,00 | |
| 10 | "Old setting"=- | |
| 11 | ||
| 12 | [-HKEY_CURRENT_USER\Software\Example\Legacy] |
docs/features/file-kinds.md +1
| @@ -51,6 +51,7 @@ The forge draws a file on its page when its kind is below and it is within the s | ||
| 51 | 51 | - **OpenTimelineIO**, drawn up to 1 MB: `.otio` |
| 52 | 52 | - **Edit list**, drawn up to 1 MB: `.edl` |
| 53 | 53 | - **Playlist**, drawn up to 1 MB: `.m3u`, `.m3u8` |
| 54 | - **Registry export**, drawn up to 1 MB: `.reg` | |
| 54 | 55 | - **Final Cut XML**, drawn up to 1 MB: `.fcpxml` |
| 55 | 56 | - **Kdenlive project**, drawn up to 1 MB: `.kdenlive` |
| 56 | 57 | - **Contacts**, drawn up to 1 MB: `.vcf`, `.vcard` |
docs/features/registry.md added +16
| @@ -0,0 +1,16 @@ | ||
| 1 | --- | |
| 2 | topic: Files in the browser | |
| 3 | row: Windows registry exports (.reg) as keys and typed values, with deletions listed | |
| 4 | --- | |
| 5 | # Registry exports as keys and values | |
| 6 | ||
| 7 | Open a `.reg` file (UTF-16 or ASCII, opening with `Windows Registry Editor Version 5.00` or `REGEDIT4`) in a repository's file view and read one section per key, each value with its name, type (string, dword, qword, binary, expandable string, multi-string) and data. | |
| 8 | ||
| 9 | - What the file deletes, `[-HKEY…]` keys and `"name"=-` values, is a list of its own, "Deleted by this file". | |
| 10 | - A binary value shows its length and its first 32 bytes, never the rest. Nothing on the page runs or links. | |
| 11 | - At most 500 keys, 200 values a key and 500 deletions a list are drawn; the page says how many were left out. **1 MB is the render cap**: a larger file shows its source. | |
| 12 | - A file whose first line is not a registry header is only text; one that names no keys keeps its source, with the reason above it. | |
| 13 | - The terminal workspace opens the same file as a table of key, name, type and data, deletions as rows of type `deleted` (`src/tui/screens/workspace_registry.ts`). | |
| 14 | - The MCP `read_file` tool answers the same facts as `about: {kind: "registry", keys, values, deletedKeys, deletedValues}`. | |
| 15 | ||
| 16 | Try it: open `docs/examples/settings.reg` in this repository's file view. |
scripts/kinds-guide.ts +1 −1
| @@ -13,7 +13,7 @@ export const NAMES: Readonly<Record<FileKind, string>> = { | ||
| 13 | 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", blend: "Blender file", 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 | geojson: "GeoJSON", kml: "KML", calendar: "Calendar", otio: "OpenTimelineIO", edl: "Edit list", playlist: "Playlist", fcpxml: "Final Cut XML", kdenlive: "Kdenlive project", | |
| 16 | geojson: "GeoJSON", kml: "KML", calendar: "Calendar", otio: "OpenTimelineIO", edl: "Edit list", playlist: "Playlist", registry: "Registry export", fcpxml: "Final Cut XML", kdenlive: "Kdenlive project", | |
| 17 | 17 | contacts: "Contacts", mail: "Email", gcode: "G-code", dxf: "DXF drawing", gerber: "Gerber layer", kicad: "KiCad board", mermaid: "Mermaid diagram", drawio: "draw.io diagram", |
| 18 | 18 | excalidraw: "Excalidraw", step: "STEP model", iges: "IGES drawing", ifc: "IFC building model", prproj: "Premiere project", sarif: "SARIF report", lcov: "Coverage (lcov)", junit: "JUnit report", |
| 19 | 19 | opml: "OPML", feed: "RSS or Atom feed", env: "Env example", openapi: "OpenAPI", package: "package.json", manifest: "Dependency manifest", makefile: "Makefile", |
src/http/mcp/tools/read_file.ts +3 −1
| @@ -14,13 +14,14 @@ import { aboutPcd } from "../../../web/render/pcd.ts"; | ||
| 14 | 14 | import { describeMedia } from "../../../text/mp4.ts"; |
| 15 | 15 | import { readXcf } from "../../../web/render/xcf-read.ts"; |
| 16 | 16 | import { readBlend, sayBlend } from "../../../web/render/blend-read.ts"; |
| 17 | import { aboutReg, isRegHead } from "../../../web/render/reg.ts"; | |
| 17 | 18 | import { aboutM3u } from "../../../web/render/m3u.ts"; |
| 18 | 19 | import { aboutTfstate } from "../../../web/render/tfstate.ts"; |
| 19 | 20 | import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts"; |
| 20 | 21 | |
| 21 | 22 | export const tool: Tool = { |
| 22 | 23 | name: "read_file", |
| 23 | 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}; .blend {version, codes}; .torrent {name, size, infoHash, trackers, files}; .m3u {tracks, seconds}", | |
| 24 | 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}; .blend {version, codes}; .torrent {name, size, infoHash, trackers, files}; .m3u {tracks, seconds}; .reg {keys, values, deletedKeys, deletedValues}", | |
| 24 | 25 | description: |
| 25 | 26 | "No shell? Read a file or list a directory at a ref (default branch); over 5 MB: tooLarge.", |
| 26 | 27 | inputSchema: { |
| @@ -101,6 +102,7 @@ function aboutFile(path: string, body: Uint8Array, text: string | undefined): Re | ||
| 101 | 102 | if (/\.blend$/i.test(path)) return aboutBlend(body); |
| 102 | 103 | if (text !== undefined && /\.tfstate$/i.test(path)) return aboutTfstate(text); |
| 103 | 104 | if (text !== undefined && /\.m3u8?$/i.test(path) && body.length <= RENDER_CAP.playlist) return aboutM3u(text); |
| 105 | if (/\.reg$/i.test(path) && body.length <= RENDER_CAP.registry && isRegHead(body)) return aboutReg(body); | |
| 104 | 106 | const media = describeMedia(path, body); |
| 105 | 107 | if (media) return media; |
| 106 | 108 | if (text === undefined) return undefined; |
src/tui/screens/workspace.ts +2 −1
| @@ -106,6 +106,7 @@ import { parquetView } from "./workspace_parquet.ts"; | ||
| 106 | 106 | import { bibView } from "./workspace_bib.ts"; |
| 107 | 107 | import { tfstateView } from "./workspace_tfstate.ts"; |
| 108 | 108 | import { playlistView } from "./workspace_playlist.ts"; |
| 109 | import { registryView } from "./workspace_registry.ts"; | |
| 109 | 110 | import { factsView } from "./workspace_facts.ts"; |
| 110 | 111 | import { depsView } from "./workspace_deps.ts"; |
| 111 | 112 | import { cadView } from "./workspace_cad.ts"; |
| @@ -1634,7 +1635,7 @@ export function workspaceScreen( | ||
| 1634 | 1635 | // bytes as text is how a terminal ends up beeping at you. |
| 1635 | 1636 | const base = looksLikeImage(t.path) ? null : sqliteView(t.path, read.value.body, { table: 0, page: 1 }); |
| 1636 | 1637 | if (base !== null && typeof base !== "string") db = read.value.body; |
| 1637 | 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) ?? tfstateView(t.path, read.value.body) ?? factsView(t.path, read.value.body) ?? cadView(t.path, read.value.body, read.value.size, formatSize)); | |
| 1638 | 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) ?? tfstateView(t.path, read.value.body) ?? registryView(t.path, read.value.body) ?? factsView(t.path, read.value.body) ?? cadView(t.path, read.value.body, read.value.size, formatSize)); | |
| 1638 | 1639 | if (looksLikeImage(t.path)) picture = read.value.body; |
| 1639 | 1640 | else if (book !== null && typeof book !== "string") sheet = book; |
| 1640 | 1641 | else if (typeof book === "string") note = book; |
src/tui/screens/workspace_registry.ts added +30
| @@ -0,0 +1,30 @@ | ||
| 1 | /** | |
| 2 | * A registry export (`.reg`) in the terminal workspace, read the way the page reads it: the same | |
| 3 | * `parseReg`, drawn as a table of key, name, type and data, with what the file deletes as rows of | |
| 4 | * type `deleted` after the values. Same gate and cap as the page (`fileKind`, | |
| 5 | * `RENDER_CAP.registry`); at most `ROW_CAP` rows. Control characters are already dropped by the | |
| 6 | * parser. | |
| 7 | * | |
| 8 | * `registryView(path, body)` answers a table, a sentence (the workspace shows it as its note), or | |
| 9 | * `null` for a file that is not an export. | |
| 10 | */ | |
| 11 | ||
| 12 | import { fileKind, HEAD_BYTES, RENDER_CAP } from "../../web/render/kinds.ts"; | |
| 13 | import { decodeReg, parseReg } from "../../web/render/reg.ts"; | |
| 14 | import type { Table } from "../../text/csv.ts"; | |
| 15 | ||
| 16 | export const ROW_CAP = 2_000; | |
| 17 | ||
| 18 | export function registryView(path: string, body: Uint8Array): Table | string | null { | |
| 19 | if (fileKind(path, body.subarray(0, HEAD_BYTES)) !== "registry") return null; | |
| 20 | if (body.length > RENDER_CAP.registry) | |
| 21 | return `This file is over ${RENDER_CAP.registry / 1_000_000} MB, too large to open here. Download it instead.`; | |
| 22 | const p = parseReg(decodeReg(body)); | |
| 23 | if ("error" in p) return `This file is not drawn as a registry export: ${p.error}.`; | |
| 24 | const header = ["Key", "Name", "Type", "Data"]; | |
| 25 | const rows: string[][] = []; | |
| 26 | for (const k of p.keys) for (const v of k.values) rows.push([k.path, v.name, v.type, v.data]); | |
| 27 | for (const k of p.deletedKeys) rows.push([k, "", "deleted", "key"]); | |
| 28 | for (const v of p.deletedValues) rows.push([v.key, v.name, "deleted", "value"]); | |
| 29 | return { header, rows: rows.slice(0, ROW_CAP), more: Math.max(0, rows.length - ROW_CAP), delimiter: ",", columns: header.length }; | |
| 30 | } |
src/web/render/kinds.ts +7
| @@ -16,6 +16,7 @@ | ||
| 16 | 16 | import { binaryFacts, FACTS_EXTENSIONS } from "./binary-facts.ts"; |
| 17 | 17 | import { isSbomHead } from "./sbom.ts"; |
| 18 | 18 | import { isTfstateHead } from "./tfstate.ts"; |
| 19 | import { isRegHead } from "./reg.ts"; | |
| 19 | 20 | import { isWasm } from "./wasm.ts"; |
| 20 | 21 | import { isBlend } from "./blend-read.ts"; |
| 21 | 22 | import { isXcf } from "./xcf-read.ts"; |
| @@ -64,6 +65,7 @@ export type FileKind = | ||
| 64 | 65 | | "otio" |
| 65 | 66 | | "edl" |
| 66 | 67 | | "playlist" |
| 68 | | "registry" | |
| 67 | 69 | | "fcpxml" |
| 68 | 70 | | "kdenlive" |
| 69 | 71 | | "contacts" |
| @@ -181,6 +183,8 @@ export const RENDER_CAP: Readonly<Record<FileKind, number>> = { | ||
| 181 | 183 | edl: 1 * MB, |
| 182 | 184 | // A playlist is read whole and draws at most 2,000 rows; over 1 MB the source is kept. |
| 183 | 185 | playlist: 1 * MB, |
| 186 | // A registry export is read whole; keys, values and deletions drawn are capped in `reg.ts`. | |
| 187 | registry: 1 * MB, | |
| 184 | 188 | fcpxml: 1 * MB, |
| 185 | 189 | kdenlive: 1 * MB, |
| 186 | 190 | contacts: 1 * MB, |
| @@ -624,6 +628,8 @@ export function fileKind(path: string, head: Uint8Array): FileKind { | ||
| 624 | 628 | if (binaryFacts(extension(path), head) !== undefined) return "cad"; |
| 625 | 629 | // A WebAssembly module opens on `\0asm`, a NUL in its head; the name alone never decides. |
| 626 | 630 | if (extension(path) === "wasm" && isWasm(head)) return "wasm"; |
| 631 | // A UTF-16 export has NULs in its head: its header line decides, not the name alone. | |
| 632 | if (extension(path) === "reg" && isRegHead(head)) return "registry"; | |
| 627 | 633 | // A project is gzip, so its head has NULs: ask before the binary test. |
| 628 | 634 | if (extension(path) === "prproj" && isGzipHead(head)) return "prproj"; |
| 629 | 635 | if (looksBinary(head)) return "binary"; |
| @@ -808,6 +814,7 @@ const SNIFFED_EXTENSIONS: Readonly<Partial<Record<FileKind, readonly string[]>>> | ||
| 808 | 814 | midi: ["mid", "midi"], |
| 809 | 815 | pcd: ["pcd"], |
| 810 | 816 | wasm: ["wasm"], |
| 817 | registry: ["reg"], | |
| 811 | 818 | cad: [...FACTS_EXTENSIONS], |
| 812 | 819 | prproj: ["prproj"], |
| 813 | 820 | kicad: ["kicad_pcb"], |
src/web/render/reg.ts added +228
| @@ -0,0 +1,228 @@ | ||
| 1 | /** | |
| 2 | * A Windows Registry export (`.reg`, UTF-16 or ASCII, head `Windows Registry Editor Version 5.00` | |
| 3 | * or `REGEDIT4`) as one section per key with its values typed (string, dword, binary, …), and | |
| 4 | * what the file deletes (`[-HKEY…]` keys, `"name"=-` values) in lists of their own. The body is | |
| 5 | * bounded by the render cap before anything here reads it; at most `KEY_CAP` keys, `VALUE_CAP` | |
| 6 | * values a key and `DELETE_CAP` deletions a list are drawn, and the page says how many were left | |
| 7 | * out. A binary value shows its length and its first `BYTE_CAP` bytes, never the rest. Every | |
| 8 | * string is escaped. A file with no keys keeps its source, with the reason. | |
| 9 | */ | |
| 10 | ||
| 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 KEY_CAP = 500; | |
| 16 | export const VALUE_CAP = 200; | |
| 17 | export const DELETE_CAP = 500; | |
| 18 | export const BYTE_CAP = 32; | |
| 19 | const TEXT_CAP = 200; | |
| 20 | ||
| 21 | export interface RegValue { | |
| 22 | /** `@` for the key's default value. */ | |
| 23 | readonly name: string; | |
| 24 | /** | |
| 25 | * `string`, `dword`, `qword`, `binary`, `expandable string`, `multi-string`, `none`, `hex(n)`. | |
| 26 | */ | |
| 27 | readonly type: string; | |
| 28 | readonly data: string; | |
| 29 | } | |
| 30 | export interface RegKey { | |
| 31 | readonly path: string; | |
| 32 | readonly values: RegValue[]; | |
| 33 | /** Values the key holds beyond `VALUE_CAP`. */ | |
| 34 | left: number; | |
| 35 | } | |
| 36 | export interface Registry { | |
| 37 | readonly header: string; | |
| 38 | readonly keys: RegKey[]; | |
| 39 | readonly keyTotal: number; | |
| 40 | readonly deletedKeys: string[]; | |
| 41 | readonly deletedKeyTotal: number; | |
| 42 | readonly deletedValues: { readonly key: string; readonly name: string }[]; | |
| 43 | readonly deletedValueTotal: number; | |
| 44 | readonly valueTotal: number; | |
| 45 | } | |
| 46 | export type Parsed = Registry | { readonly error: string }; | |
| 47 | ||
| 48 | const HEADER = /^(Windows Registry Editor Version 5\.00|REGEDIT4)$/i; | |
| 49 | ||
| 50 | /** The body as text: UTF-16 with a byte-order mark (either order), else UTF-8 (BOM dropped). */ | |
| 51 | export function decodeReg(body: Uint8Array): string { | |
| 52 | if (body.length >= 2 && body[0] === 0xff && body[1] === 0xfe) return new TextDecoder("utf-16le").decode(body.subarray(2)); | |
| 53 | if (body.length >= 2 && body[0] === 0xfe && body[1] === 0xff) return new TextDecoder("utf-16be").decode(body.subarray(2)); | |
| 54 | return new TextDecoder().decode(body).replace(/^\uFEFF/, ""); | |
| 55 | } | |
| 56 | ||
| 57 | /** Whether the first bytes open with a registry header line; the extension alone never decides. */ | |
| 58 | export function isRegHead(head: Uint8Array): boolean { | |
| 59 | const first = decodeReg(head.subarray(0, 256)).split(/\r\n|\n|\r/, 1)[0] ?? ""; | |
| 60 | return HEADER.test(first.trim()); | |
| 61 | } | |
| 62 | ||
| 63 | const plain = (s: string): string => s.replace(/[\u0000-\u001f\u007f-\u009f]/g, " "); | |
| 64 | const clip = (s: string): string => (s.length > TEXT_CAP ? `${s.slice(0, TEXT_CAP)}…` : s); | |
| 65 | ||
| 66 | /** A quoted `.reg` string, its `\\` and `\"` undone; undefined when it is not one. */ | |
| 67 | function unquote(s: string): string | undefined { | |
| 68 | if (s.length < 2 || !s.startsWith('"') || !s.endsWith('"')) return undefined; | |
| 69 | return s.slice(1, -1).replace(/\\(["\\])/g, "$1"); | |
| 70 | } | |
| 71 | ||
| 72 | /** The first `max` bytes of a `hex:` list, and how many it names in all. */ | |
| 73 | function hexBytes(list: string, max: number): { bytes: number[]; total: number } { | |
| 74 | const trimmed = list.trim(); | |
| 75 | if (trimmed === "") return { bytes: [], total: 0 }; | |
| 76 | let total = 1; | |
| 77 | for (let i = 0; i < trimmed.length; i++) if (trimmed.charCodeAt(i) === 44) total++; | |
| 78 | const bytes: number[] = []; | |
| 79 | const re = /\s*([0-9a-f]{1,2})\s*(?:,|$)/gi; | |
| 80 | let m: RegExpExecArray | null; | |
| 81 | while (bytes.length < max && (m = re.exec(trimmed)) !== null && m[0] !== "") bytes.push(parseInt(m[1]!, 16)); | |
| 82 | return { bytes, total }; | |
| 83 | } | |
| 84 | ||
| 85 | const HEX_TYPES: Readonly<Record<number, string>> = { | |
| 86 | 0: "none", 1: "string", 2: "expandable string", 3: "binary", 4: "dword", 7: "multi-string", 11: "qword", | |
| 87 | }; | |
| 88 | ||
| 89 | function value(name: string, text: string): RegValue { | |
| 90 | const str = unquote(text); | |
| 91 | if (str !== undefined) return { name, type: "string", data: clip(plain(str)) }; | |
| 92 | const dword = /^dword:([0-9a-f]{1,8})$/i.exec(text); | |
| 93 | if (dword) return { name, type: "dword", data: `0x${dword[1]!.toLowerCase().padStart(8, "0")} (${parseInt(dword[1]!, 16)})` }; | |
| 94 | const hex = /^hex(?:\(([0-9a-f]{1,8})\))?:(.*)$/is.exec(text); | |
| 95 | if (!hex) return { name, type: "unreadable", data: clip(plain(text)) }; | |
| 96 | const code = hex[1] === undefined ? 3 : parseInt(hex[1], 16); | |
| 97 | const type = HEX_TYPES[code] ?? `hex(${hex[1]})`; | |
| 98 | const wide = code === 2 || code === 7; | |
| 99 | const { bytes, total } = hexBytes(hex[2]!, wide ? 2 * TEXT_CAP : BYTE_CAP); | |
| 100 | if (wide) { | |
| 101 | // UTF-16 text; a multi-string's NULs separate its parts. | |
| 102 | const even = bytes.slice(0, bytes.length - (bytes.length % 2)); | |
| 103 | const parts = new TextDecoder("utf-16le").decode(new Uint8Array(even)).split("\0"); | |
| 104 | while (parts.length > 0 && parts[parts.length - 1] === "") parts.pop(); | |
| 105 | return { name, type, data: clip(plain(parts.join(" | "))) }; | |
| 106 | } | |
| 107 | if (code === 11 && total === 8 && bytes.length === 8) { | |
| 108 | let n = 0n; | |
| 109 | for (let i = 7; i >= 0; i--) n = (n << 8n) | BigInt(bytes[i]!); | |
| 110 | return { name, type, data: `0x${n.toString(16)} (${n})` }; | |
| 111 | } | |
| 112 | const shown = bytes.map((b) => b.toString(16).padStart(2, "0")).join(" "); | |
| 113 | const count = `${total.toLocaleString()} ${total === 1 ? "byte" : "bytes"}`; | |
| 114 | return { name, type, data: total === 0 ? count : `${count}: ${shown}${total > bytes.length ? " …" : ""}` }; | |
| 115 | } | |
| 116 | ||
| 117 | /** The index just past the quote that closes a quoted name at the start of the line, or -1. */ | |
| 118 | function nameEnd(line: string): number { | |
| 119 | for (let i = 1; i < line.length; i++) { | |
| 120 | if (line[i] === "\\") i++; | |
| 121 | else if (line[i] === '"') return i + 1; | |
| 122 | } | |
| 123 | return -1; | |
| 124 | } | |
| 125 | ||
| 126 | export function parseReg(text: string): Parsed { | |
| 127 | const lines = text.split(/\r\n|\n|\r/); | |
| 128 | const header = (lines[0] ?? "").trim(); | |
| 129 | if (!HEADER.test(header)) return { error: "it does not open with a registry header" }; | |
| 130 | const keys: RegKey[] = []; | |
| 131 | const deletedKeys: string[] = []; | |
| 132 | const deletedValues: { key: string; name: string }[] = []; | |
| 133 | let keyTotal = 0, deletedKeyTotal = 0, deletedValueTotal = 0, valueTotal = 0; | |
| 134 | let current: RegKey | undefined; // the key now open, when it is drawn | |
| 135 | let currentPath: string | undefined; | |
| 136 | let values = 0; | |
| 137 | for (let i = 1; i < lines.length; i++) { | |
| 138 | let line = lines[i]!.trim(); | |
| 139 | if (line === "" || line.startsWith(";") || line.startsWith("#")) continue; | |
| 140 | // A hex list continues on the next line while a line ends in a backslash. | |
| 141 | while (line.endsWith("\\") && i + 1 < lines.length) line = line.slice(0, -1) + lines[++i]!.trim(); | |
| 142 | if (line.startsWith("[") && line.endsWith("]")) { | |
| 143 | const path = plain(line.slice(1, -1)); | |
| 144 | values = 0; | |
| 145 | current = undefined; | |
| 146 | currentPath = undefined; | |
| 147 | if (path.startsWith("-")) { | |
| 148 | deletedKeyTotal++; | |
| 149 | if (deletedKeys.length < DELETE_CAP) deletedKeys.push(path.slice(1)); | |
| 150 | continue; | |
| 151 | } | |
| 152 | keyTotal++; | |
| 153 | currentPath = path; | |
| 154 | if (keys.length < KEY_CAP) keys.push((current = { path, values: [], left: 0 })); | |
| 155 | continue; | |
| 156 | } | |
| 157 | if (currentPath === undefined) continue; | |
| 158 | const eq = line.startsWith("@") ? 1 : line.startsWith('"') ? nameEnd(line) : -1; | |
| 159 | if (eq < 0 || line[eq] !== "=") continue; | |
| 160 | const name = line.startsWith("@") ? "@" : (unquote(line.slice(0, eq)) ?? line.slice(0, eq)); | |
| 161 | const rest = line.slice(eq + 1).trim(); | |
| 162 | if (rest === "-") { | |
| 163 | deletedValueTotal++; | |
| 164 | if (deletedValues.length < DELETE_CAP) deletedValues.push({ key: currentPath, name: plain(name) }); | |
| 165 | continue; | |
| 166 | } | |
| 167 | valueTotal++; | |
| 168 | values++; | |
| 169 | if (current === undefined) continue; | |
| 170 | if (values <= VALUE_CAP) current.values.push(value(plain(name), rest)); | |
| 171 | else current.left++; | |
| 172 | } | |
| 173 | if (keyTotal + deletedKeyTotal + deletedValueTotal === 0) return { error: "it names no keys" }; | |
| 174 | return { header, keys, keyTotal, deletedKeys, deletedKeyTotal, deletedValues, deletedValueTotal, valueTotal }; | |
| 175 | } | |
| 176 | ||
| 177 | const noun = (n: number, one: string, many: string): string => `${n.toLocaleString()} ${n === 1 ? one : many}`; | |
| 178 | ||
| 179 | export function registry(input: RenderInput): Rendered { | |
| 180 | const p = parseReg(decodeReg(input.body)); | |
| 181 | if ("error" in p) return { content: html``, lines: 0, fallback: `This file is not drawn as a registry export: ${p.error}.` }; | |
| 182 | const code = (s: string): string => `<code>${escapeHtml(s)}</code>`; | |
| 183 | let sections = ""; | |
| 184 | for (const k of p.keys) { | |
| 185 | const rows = k.values | |
| 186 | .map((v) => `<tr><td>${code(v.name)}</td><td>${escapeHtml(v.type)}</td><td>${escapeHtml(v.data)}</td></tr>`) | |
| 187 | .join(""); | |
| 188 | const table = | |
| 189 | k.values.length === 0 | |
| 190 | ? `<p class="muted small">No values.</p>` | |
| 191 | : `<table class="table" data-dense aria-label="Values of ${escapeHtml(k.path)}"><thead><tr><th scope="col">Name</th><th scope="col">Type</th><th scope="col">Data</th></tr></thead><tbody>${rows}</tbody></table>`; | |
| 192 | const left = k.left > 0 ? `<p class="muted small">${noun(k.left, "more value", "more values")} in the raw file.</p>` : ""; | |
| 193 | sections += `<section><h3>${code(k.path)}</h3>${table}${left}</section>`; | |
| 194 | } | |
| 195 | const keysLeft = p.keyTotal - p.keys.length; | |
| 196 | const more = keysLeft > 0 ? `<p class="muted small">Showing ${KEY_CAP.toLocaleString()} of ${p.keyTotal.toLocaleString()} keys. The other ${keysLeft.toLocaleString()} are in the raw file.</p>` : ""; | |
| 197 | let deletes = ""; | |
| 198 | if (p.deletedKeyTotal + p.deletedValueTotal > 0) { | |
| 199 | const table = (label: string, cols: string, rows: string): string => | |
| 200 | `<table class="table" data-dense aria-label="${label}"><thead><tr>${cols}</tr></thead><tbody>${rows}</tbody></table>`; | |
| 201 | const dk = p.deletedKeys.map((k) => `<tr><td>${code(k)}</td></tr>`).join(""); | |
| 202 | const dv = p.deletedValues.map((v) => `<tr><td>${code(v.name)}</td><td>${code(v.key)}</td></tr>`).join(""); | |
| 203 | const cut = (total: number, shown: number): string => (total > shown ? `<p class="muted small">${(total - shown).toLocaleString()} more in the raw file.</p>` : ""); | |
| 204 | deletes = | |
| 205 | `<section aria-label="Deleted by this file"><h3>Deleted by this file</h3>` + | |
| 206 | (p.deletedKeyTotal > 0 ? `<h4>Keys (${p.deletedKeyTotal.toLocaleString()})</h4>${table("Deleted keys", `<th scope="col">Key</th>`, dk)}${cut(p.deletedKeyTotal, p.deletedKeys.length)}` : "") + | |
| 207 | (p.deletedValueTotal > 0 ? `<h4>Values (${p.deletedValueTotal.toLocaleString()})</h4>${table("Deleted values", `<th scope="col">Name</th><th scope="col">In key</th>`, dv)}${cut(p.deletedValueTotal, p.deletedValues.length)}` : "") + | |
| 208 | `</section>`; | |
| 209 | } | |
| 210 | const lead = `${noun(p.keyTotal, "key", "keys")} · ${noun(p.valueTotal, "value", "values")} · ${noun(p.deletedKeyTotal + p.deletedValueTotal, "deletion", "deletions")}`; | |
| 211 | const content = html`<div><p>${p.header} · ${lead}</p>${raw(sections)}${raw(more)}${raw(deletes)}</div>`; | |
| 212 | return { content, lines: 0, summary: `${lead} · ${fileSize(input.size)}` }; | |
| 213 | } | |
| 214 | ||
| 215 | /** The facts the MCP file tool reads: counts, never the values. */ | |
| 216 | export function aboutReg(body: Uint8Array): Record<string, unknown> { | |
| 217 | const p = parseReg(decodeReg(body)); | |
| 218 | if ("error" in p) return { kind: "registry", says: `Registry export, unreadable: ${p.error}` }; | |
| 219 | return { | |
| 220 | kind: "registry", | |
| 221 | header: p.header, | |
| 222 | keys: p.keyTotal, | |
| 223 | values: p.valueTotal, | |
| 224 | deletedKeys: p.deletedKeyTotal, | |
| 225 | deletedValues: p.deletedValueTotal, | |
| 226 | says: `Registry export, ${noun(p.keyTotal, "key", "keys")}, ${noun(p.deletedKeyTotal + p.deletedValueTotal, "deletion", "deletions")}`, | |
| 227 | }; | |
| 228 | } |
src/web/render/renderers.ts +2
| @@ -44,6 +44,7 @@ import { ics } from "./ics.ts"; | ||
| 44 | 44 | import { otio } from "./otio.ts"; |
| 45 | 45 | import { edl } from "./edl.ts"; |
| 46 | 46 | import { m3u } from "./m3u.ts"; |
| 47 | import { registry } from "./reg.ts"; | |
| 47 | 48 | import { fcpxml } from "./fcpxml.ts"; |
| 48 | 49 | import { kdenlive } from "./kdenlive.ts"; |
| 49 | 50 | import { junit } from "./junit.ts"; |
| @@ -184,6 +185,7 @@ export const RENDERERS: Partial<Readonly<Record<FileKind, Renderer>>> = { | ||
| 184 | 185 | otio, |
| 185 | 186 | edl, |
| 186 | 187 | playlist: m3u, |
| 188 | registry, | |
| 187 | 189 | fcpxml, |
| 188 | 190 | kdenlive, |
| 189 | 191 | contacts: vcf, |
test/fuzz-renderers.test.ts +6
| @@ -337,6 +337,12 @@ export const SAMPLES: Readonly<Record<string, { path: string; files: readonly st | ||
| 337 | 337 | "TITLE: <b>T</b>\nFCM: NON-DROP FRAME\n\n001 AX V C 00:00:00:00 00:00:02:00 01:00:00:00 01:00:02:00\n* FROM CLIP NAME: a.mov\n", |
| 338 | 338 | ], |
| 339 | 339 | }, |
| 340 | registry: { | |
| 341 | path: "a.reg", | |
| 342 | files: [ | |
| 343 | 'Windows Registry Editor Version 5.00\n\n[HKEY_CURRENT_USER\\<b>K</b>]\n@="<i>x</i>"\n"a"=dword:00000001\n"b"=hex:de,ad,\\\n be,ef\n"c"=-\n\n[-HKEY_CURRENT_USER\\Gone]\n', | |
| 344 | ], | |
| 345 | }, | |
| 340 | 346 | playlist: { |
| 341 | 347 | path: "list.m3u8", |
| 342 | 348 | files: ["#EXTM3U\n#EXTINF:12.5,<b>T</b>\nhttp://a.test/<i>x</i>.mp3\n#EXTINF:-1,B\n../a b.mp3\n"], |
test/mcp-read-file.test.ts +6
| @@ -99,6 +99,7 @@ beforeAll(async () => { | ||
| 99 | 99 | files: [{ path: "infra/terraform.tfstate", content: JSON.stringify({ version: 4, serial: 2, resources: [{ mode: "managed", type: "aws_db_instance", name: "db", provider: "aws", instances: [{ attributes: { id: "db-1", password: "hunter2" } }] }] }) }], |
| 100 | 100 | }), |
| 101 | 101 | ); |
| 102 | ok(await commitToBranch(app, owner, pub, { message: "registry", files: [{ path: "a.reg", content: "Windows Registry Editor Version 5.00\n\n[HKEY_A\\B]\n\"x\"=dword:1\n\"y\"=-\n[-HKEY_A\\C]\n" }] })); | |
| 102 | 103 | ok(await commitToBranch(app, owner, pub, { message: "lists", files: [ |
| 103 | 104 | { path: "mix.m3u", content: "#EXTM3U\n#EXTINF:61,One\na.mp3\nb.mp3\n" }, |
| 104 | 105 | { path: "big.m3u", content: "#EXTINF:1,x\na.mp3\n".padEnd(1_000_001, "\n") }, |
| @@ -235,3 +236,8 @@ test("a .m3u carries about with its counts; one over the render cap carries none | ||
| 235 | 236 | expect(big.size).toBeGreaterThan(1_000_000); |
| 236 | 237 | expect(big.about).toBeUndefined(); |
| 237 | 238 | }); |
| 239 | ||
| 240 | test("a .reg carries about with its counts", async () => { | |
| 241 | const file = (await read(tok["stranger"]!, { repo: "ada/pub", path: "a.reg" })).value; | |
| 242 | expect(file.about).toMatchObject({ kind: "registry", keys: 1, values: 1, deletedKeys: 1, deletedValues: 1 }); | |
| 243 | }); |
test/render-kinds.test.ts +1
| @@ -103,6 +103,7 @@ const SAMPLES: Record<string, [Uint8Array, FileKind, string]> = { | ||
| 103 | 103 | ics: [enc("BEGIN:VCALENDAR\nEND:VCALENDAR\n"), "calendar", "application/octet-stream"], |
| 104 | 104 | otio: [enc('{"OTIO_SCHEMA":"Timeline.1"}'), "otio", "application/octet-stream"], |
| 105 | 105 | edl: [enc("TITLE: a\n"), "edl", "application/octet-stream"], |
| 106 | reg: [enc("Windows Registry Editor Version 5.00\n"), "registry", "application/octet-stream"], | |
| 106 | 107 | m3u: [enc("#EXTM3U\n"), "playlist", "application/octet-stream"], |
| 107 | 108 | m3u8: [enc("#EXTM3U\n"), "playlist", "application/octet-stream"], |
| 108 | 109 | fcpxml: [enc("<fcpxml/>"), "fcpxml", "application/octet-stream"], |
test/render-registry.test.ts added +101
| @@ -0,0 +1,101 @@ | ||
| 1 | /** Registry exports (.reg): parse, escape, cap, malformed, UTF-16, and the terminal view. */ | |
| 2 | import { describe, expect, test } from "bun:test"; | |
| 3 | import { aboutReg, decodeReg, DELETE_CAP, KEY_CAP, parseReg, registry, VALUE_CAP } from "../src/web/render/reg.ts"; | |
| 4 | import { fileKind, RENDER_CAP } from "../src/web/render/kinds.ts"; | |
| 5 | import { RENDERERS } from "../src/web/render/renderers.ts"; | |
| 6 | import { registryView } from "../src/tui/screens/workspace_registry.ts"; | |
| 7 | ||
| 8 | const enc = (s: string): Uint8Array => new TextEncoder().encode(s); | |
| 9 | const utf16 = (s: string): Uint8Array => { | |
| 10 | const out = new Uint8Array(2 + s.length * 2); | |
| 11 | out[0] = 0xff; | |
| 12 | out[1] = 0xfe; | |
| 13 | for (let i = 0; i < s.length; i++) { | |
| 14 | out[2 + i * 2] = s.charCodeAt(i) & 0xff; | |
| 15 | out[3 + i * 2] = s.charCodeAt(i) >> 8; | |
| 16 | } | |
| 17 | return out; | |
| 18 | }; | |
| 19 | const input = (body: Uint8Array) => ({ path: "a.reg", size: body.length, body, media: "/m", download: "/d" }); | |
| 20 | const HEAD = "Windows Registry Editor Version 5.00\r\n\r\n"; | |
| 21 | const SAMPLE = | |
| 22 | HEAD + | |
| 23 | '[HKEY_CURRENT_USER\\Software\\App]\r\n@="Default"\r\n"Name"="a \\"q\\" \\\\"\r\n"On"=dword:00000001\r\n"Blob"=hex:de,ad,\\\r\n be,ef\r\n"Path"=hex(2):25,00,41,00,00,00\r\n"Big"=hex(b):01,00,00,00,00,00,00,00\r\n"Gone"=-\r\n\r\n[-HKEY_CURRENT_USER\\Software\\Old]\r\n'; | |
| 24 | ||
| 25 | describe("registry", () => { | |
| 26 | test("registered by extension and header; UTF-16 and ASCII; other .reg is text", () => { | |
| 27 | expect(fileKind("a.reg", utf16(SAMPLE))).toBe("registry"); | |
| 28 | expect(fileKind("a.reg", enc("REGEDIT4\n"))).toBe("registry"); | |
| 29 | expect(fileKind("a.reg", enc("hello\n"))).toBe("text"); | |
| 30 | expect(fileKind("a.txt", enc(SAMPLE))).toBe("text"); | |
| 31 | expect(RENDERERS.registry).toBe(registry); | |
| 32 | expect(RENDER_CAP.registry).toBe(1_000_000); | |
| 33 | }); | |
| 34 | ||
| 35 | test("parse: keys, typed values, continuation lines, deletions", () => { | |
| 36 | const p = parseReg(SAMPLE); | |
| 37 | if ("error" in p) throw new Error(p.error); | |
| 38 | expect(p.keys.map((k) => k.path)).toEqual(["HKEY_CURRENT_USER\\Software\\App"]); | |
| 39 | expect(p.keys[0]!.values).toEqual([ | |
| 40 | { name: "@", type: "string", data: "Default" }, | |
| 41 | { name: "Name", type: "string", data: 'a "q" \\' }, | |
| 42 | { name: "On", type: "dword", data: "0x00000001 (1)" }, | |
| 43 | { name: "Blob", type: "binary", data: "4 bytes: de ad be ef" }, | |
| 44 | { name: "Path", type: "expandable string", data: "%A" }, | |
| 45 | { name: "Big", type: "qword", data: "0x1 (1)" }, | |
| 46 | ]); | |
| 47 | expect(p.deletedKeys).toEqual(["HKEY_CURRENT_USER\\Software\\Old"]); | |
| 48 | expect(p.deletedValues).toEqual([{ key: "HKEY_CURRENT_USER\\Software\\App", name: "Gone" }]); | |
| 49 | expect(aboutReg(utf16(SAMPLE))).toMatchObject({ kind: "registry", keys: 1, values: 6, deletedKeys: 1, deletedValues: 1 }); | |
| 50 | expect(decodeReg(utf16("hi"))).toBe("hi"); | |
| 51 | const out = String(registry(input(utf16(SAMPLE))).content); | |
| 52 | expect(out).toContain("Deleted by this file"); | |
| 53 | expect(out).toContain("<td>dword</td><td>0x00000001 (1)</td>"); | |
| 54 | }); | |
| 55 | ||
| 56 | test("every value is escaped", () => { | |
| 57 | const body = enc(HEAD + '[HKEY_A\\<script>1</script>]\n"<b>n</b>"="<img src=x onerror=1>"\n"<i>v</i>"=-\n[-HKEY_<u>]\n'); | |
| 58 | const out = String(registry(input(body)).content); | |
| 59 | expect(out).not.toMatch(/<(script|b|img|i|u)[ >]/); | |
| 60 | expect(out).toContain("<img src=x onerror=1>"); | |
| 61 | }); | |
| 62 | ||
| 63 | test("a hostile file is cut by the caps and says so", () => { | |
| 64 | let t = HEAD + "[HKEY_A]\n"; | |
| 65 | for (let i = 0; i < VALUE_CAP + 5; i++) t += `"v${i}"=dword:1\n`; | |
| 66 | for (let i = 0; i < KEY_CAP + 5; i++) t += `[HKEY_K${i}]\n`; | |
| 67 | for (let i = 0; i < DELETE_CAP + 5; i++) t += `[-HKEY_D${i}]\n`; | |
| 68 | const p = parseReg(t); | |
| 69 | if ("error" in p) throw new Error(p.error); | |
| 70 | expect(p.keys.length).toBe(KEY_CAP); | |
| 71 | expect(p.keys[0]!.values.length).toBe(VALUE_CAP); | |
| 72 | expect(p.keys[0]!.left).toBe(5); | |
| 73 | expect(p.deletedKeys.length).toBe(DELETE_CAP); | |
| 74 | const out = String(registry(input(enc(t))).content); | |
| 75 | expect(out).toContain("of 506 keys"); | |
| 76 | expect(out).toContain("5 more in the raw file"); | |
| 77 | // A binary value never draws more than its first bytes. | |
| 78 | const big = parseReg(HEAD + "[K]\n\"b\"=hex:" + "ab,".repeat(100_000) + "ab\n"); | |
| 79 | if ("error" in big) throw new Error(big.error); | |
| 80 | expect(big.keys[0]!.values[0]!.data).toMatch(/^100,001 bytes: (ab ){31}ab …$/); | |
| 81 | }); | |
| 82 | ||
| 83 | test("malformed keeps the source with a reason", () => { | |
| 84 | expect(registry(input(enc(HEAD))).fallback).toBe("This file is not drawn as a registry export: it names no keys."); | |
| 85 | expect(registry(input(enc("nope\n[K]\n"))).fallback).toContain("does not open with a registry header"); | |
| 86 | expect(parseReg(HEAD + '[K]\n"a"=banana\n"b"="unterminated\n=\n"\n')).toMatchObject({ keys: [{ values: [{ type: "unreadable" }, { type: "unreadable" }] }] }); | |
| 87 | }); | |
| 88 | ||
| 89 | test("terminal: a table with deletions, a refusal over the cap, null for other files", () => { | |
| 90 | const v = registryView("a.reg", utf16(SAMPLE)); | |
| 91 | if (v === null || typeof v === "string") throw new Error("no table"); | |
| 92 | expect(v.rows[2]).toEqual(["HKEY_CURRENT_USER\\Software\\App", "On", "dword", "0x00000001 (1)"]); | |
| 93 | expect(v.rows.slice(-2)).toEqual([ | |
| 94 | ["HKEY_CURRENT_USER\\Software\\Old", "", "deleted", "key"], | |
| 95 | ["HKEY_CURRENT_USER\\Software\\App", "Gone", "deleted", "value"], | |
| 96 | ]); | |
| 97 | expect(registryView("a.txt", enc(SAMPLE))).toBeNull(); | |
| 98 | expect(registryView("a.reg", enc(HEAD + "x".repeat(RENDER_CAP.registry)))).toContain("too large"); | |
| 99 | expect(registryView("a.reg", enc(HEAD))).toBe("This file is not drawn as a registry export: it names no keys."); | |
| 100 | }); | |
| 101 | }); |
new above
offline