Skip to content

Claude's answers, rendered: Markdown, math, charts and diagrams drawn in the Claude Code terminal. Independent project, not affiliated with Anthropic.

TypeScript claude-code-mod

Typst: compile and probe answer text in a root of their own, not /

razorback160b611df75e75
diff --git a/hooks/lib/typst.ts b/hooks/lib/typst.ts
index db1fd7a..eac5fed 100644
--- a/hooks/lib/typst.ts
+++ b/hooks/lib/typst.ts
@@ -17,10 +17,12 @@ import { clockAfter, envGet, fsExists, fsList, fsRead, fsWrite, processRun, spaw
// The typst command and its environment. Network off (see NO_NETWORK) and a
// package cache of our own, so only the vendored packages load, and the
// fonts of S.fontPaths (Ghostty's own font). `fonts`:
-// the lean font folder (fonts.ts) in place of all system fonts.
+// the lean font folder (fonts.ts) in place of all system fonts. `run`: the
+// root that STAGE_SH made, so the answer's code reads no other file.
export function typstCall(o: {
typst: string
root: string
+ run: string
cache: string
ppi: number
inputs: Readonly<Record<string, string | number>>
@@ -29,19 +31,145 @@ export function typstCall(o: {
}): { argv: string[]; env: Record<string, string> } {
const argv = [
o.typst, 'compile',
- '--root', '/',
+ '--root', o.run,
'--package-path', `${o.root}/render/packages`,
...fontArgs(o.fonts),
'--format', 'png',
'--diagnostic-format', 'short',
'--ppi', o.ppi.toFixed(4),
...Object.entries(o.inputs).flatMap(([k, v]) => ['--input', `${k}=${v}`]),
- `${o.root}/render/md.typ`,
+ templateIn(o.run, o.root),
o.out,
]
return { argv, env: noNetworkEnv(o.cache) }
}
+// ---- The root of a compile: only the files the mod puts there -------------
+// md.typ evals the answer's ```typst blocks (and math), and Typst lets code
+// read any file under its root. So a compile and a probe of answer text run
+// with a root of their own: a new private folder in the key folder, with
+// each file the template needs at its own path (so the inputs and doc.json
+// keep their paths). STAGE_SH makes it, from $1 the folder, $2 the plugin
+// root, $3 the doc JSON's path (its text on stdin), $4 the theme folder and
+// then the allowed images (all paths as rootPathOf gives them):
+// - render/: md.typ copied (Typst wants its main file inside the root) and
+// links to the rest of the plugin's render folder;
+// - the doc JSON, a file of its own (a compile of the same key at the same
+// time has its own folder);
+// - a link to the theme folder (a built-in one is in render/ already);
+// - a link to each image (and each image its SVG links to) that is a file
+// with an image name, also after its links (so a link named .png to
+// another file is not one). An image under a linked folder is there
+// already, and no folder is made through a link.
+// Typst follows the links; any other path is not found, and `..` can not
+// leave the root.
+export const STAGE_SH = [
+ 'umask 077',
+ 'r=$1 p=$2 d=$3 t=$4',
+ 'shift 4',
+ 'mkdir "$r" && mkdir -p "$r$p/render" "$r${d%/*}" || exit 1',
+ 'ln -s "$p"/render/* "$r$p/render/" && rm "$r$p/render/md.typ" && cp "$p/render/md.typ" "$r$p/render/md.typ" && cat > "$r$d" || exit 1',
+ 'case $t in',
+ ' "$p/render/"*) ;;',
+ ' /?*) if [ -d "$t" ] && [ ! -e "$r$t" ]; then mkdir -p "$r${t%/*}" && ln -s "$t" "$r$t" || exit 1; fi ;;',
+ 'esac',
+ 'for f; do',
+ ' case $f in',
+ ' *//*|*/./*|*/../*|*/.|*/..|"$p/render/"*|"$t/"*) continue ;;',
+ ' /?*) ;;',
+ ' *) continue ;;',
+ ' esac',
+ ' g=$f n=0',
+ ' while [ -L "$g" ] && [ $n -lt 40 ]; do',
+ ' l=$(readlink "$g") || break',
+ ' case $l in /*) g=$l ;; *) g=${g%/*}/$l ;; esac',
+ ' n=$((n + 1))',
+ ' done',
+ ' [ -L "$g" ] && continue',
+ ' case $(printf %s "${g##*/}" | tr A-Z a-z) in',
+ ' *.png|*.jpg|*.jpeg|*.gif|*.svg|*.webp) [ -f "$g" ] && [ ! -e "$r$f" ] && mkdir -p "$r${f%/*}" && ln -s "$g" "$r$f" ;;',
+ ' esac',
+ 'done',
+ 'exit 0',
+].join('\n')
+
+// A path as Typst reads it in its root: `.`, `..` and empty parts resolved
+// by name; null when `..` goes above the root.
+export function rootPathOf(path: string): string | null {
+ const parts: string[] = []
+ for (const part of path.split('/')) {
+ if (part === '' || part === '.') continue
+ if (part !== '..') parts.push(part)
+ else if (parts.pop() === undefined) return null
+ }
+ return `/${parts.join('/')}`
+}
+
+// The template's main file in a run folder.
+export const templateIn = (run: string, root: string) => `${run}${rootPathOf(root) ?? ''}/render/md.typ`
+
+// The doc JSON the template reads: the base folder, the segments and the
+// allow-list of images (path and full path of each, existingImages).
+export type Doc = { base: string; segments: readonly string[]; images: readonly string[] }
+
+// The full paths of a doc's allowed images (the odd entries), as in the root.
+export const imageFullsOf = (images: readonly string[]) =>
+ images.filter((_, i) => i % 2 === 1).map(rootPathOf).filter((p): p is string => !!p)
+
+// The arguments of STAGE_SH for a run folder: the images by their full
+// paths (and the images their SVGs link to), each once.
+export function stageArgs(run: string, root: string, docPath: string, themeDir: string, images: readonly string[], linked: readonly string[] = []): string[] {
+ return [run, rootPathOf(root) ?? '', rootPathOf(docPath) ?? '', rootPathOf(themeDir) ?? '', ...new Set([...imageFullsOf(images), ...linked])]
+}
+
+const IMAGE_NAME = /\.(png|jpe?g|gif|svg|webp)$/i
+
+// The images an SVG at `full` links to by a relative path (Typst loads them
+// from the SVG's folder in the root; it refuses absolute ones), as paths in
+// the root.
+export function svgLinksOf(svg: string, full: string): string[] {
+ const dir = full.replace(/\/[^/]*$/, '')
+ const found: string[] = []
+ for (const m of svg.matchAll(/\bhref\s*=\s*(["'])([^"']*)\1/g)) {
+ const href = m[2]!.trim()
+ if (!href || href.startsWith('#') || href.startsWith('/') || /^[a-z][a-z0-9+.-]*:/i.test(href)) continue
+ const path = rootPathOf(`${dir}/${href}`)
+ if (path && IMAGE_NAME.test(path)) found.push(path)
+ }
+ return found
+}
+
+// The images the allowed SVGs of `images` link to.
+async function svgLinks($: EngineInterface, images: readonly string[]): Promise<string[]> {
+ const found: string[] = []
+ for (const full of new Set(imageFullsOf(images).filter(p => /\.svg$/i.test(p)))) {
+ const svg = await fsRead($, full).catch(() => '')
+ if (typeof svg === 'string') found.push(...svgLinksOf(svg, full))
+ }
+ return found
+}
+
+let runs = 0
+// A new run folder's name in key folder `dir` (unique in this load, and
+// random across loads and sessions).
+const runFolderIn = (dir: string) => `${dir}/r-${(++runs).toString(36)}${Math.random().toString(36).slice(2, 10)}`
+
+// Runs `use` with a root of its own for `doc` (STAGE_SH), then removes it.
+// When the root can not be made, `use` still runs: Typst then finds no
+// template there and fails (never a wider root); the folder is left to the
+// 2-day sweep (it may be another run's, when its name was taken).
+export async function inRoot<T>($: EngineInterface, job: Job, dir: string, doc: Doc, use: (run: string) => Promise<T>): Promise<T> {
+ const run = runFolderIn(dir)
+ const args = stageArgs(run, job.env.root, `${dir}/doc.json`, job.themeDir, doc.images, await svgLinks($, doc.images))
+ const made = await processRun($, ['sh', '-c', STAGE_SH, 'sh', ...args], { stdin: JSON.stringify(doc), timeoutMs: 10000 }).catch(() => null)
+ if (made?.exitCode !== 0) await logDebug($, job.env.cache, `the root ${run} could not be made: ${made?.stderr ?? 'sh did not run'}`)
+ try {
+ return await use(run)
+ } finally {
+ if (made?.exitCode === 0) void Promise.resolve(processRun($, ['rm', '-rf', run], { timeoutMs: 10000 })).catch(() => undefined)
+ }
+}
+
// The arguments that load only the fonts of a lean folder (and Typst's own).
export const fontArgs = (fonts?: string) => (fonts ? ['--ignore-system-fonts', '--font-path', fonts] : [])
@@ -49,7 +177,8 @@ export const fontArgs = (fonts?: string) => (fonts ? ['--ignore-system-fonts', '
// that fits `box` (in pixels), never larger than its own pixel size: at 72
// ppi, 1 pt is 1 pixel. For a PDF, `page` is the page (it fits the box,
// larger too), and the errors are in the human format: only it has the
-// hint with the page count of a page that does not exist.
+// hint with the page count of a page that does not exist. It runs no
+// answer code, so it keeps the root at / (it only reads the file).
export function convertCall(o: {
typst: string
root: string
@@ -366,28 +495,29 @@ async function runFonts($: EngineInterface, job: Job, fonts: string, run: (fonts
return run()
}
-export async function runTypst($: EngineInterface, job: Job, segments: readonly string[], dir: string, tag: string, isSafe: boolean, signal?: AbortSignal): Promise<Ran> {
- const { inputs, ppi } = typstInputs(job, segments, dir, isSafe)
- return runFonts($, job, await leanFor($, job, segments), fonts => {
- const { argv, env: vars } = typstCall({ typst: job.env.typst!, root: job.env.root, cache: job.env.cache, ppi, inputs, out: `${dir}/${tag}-{0p}.png`, ...(fonts ? { fonts } : {}) })
+export async function runTypst($: EngineInterface, job: Job, doc: Doc, dir: string, tag: string, isSafe: boolean, signal?: AbortSignal): Promise<Ran> {
+ const { inputs, ppi } = typstInputs(job, doc.segments, dir, isSafe)
+ const fonts = await leanFor($, job, doc.segments)
+ return inRoot($, job, dir, doc, run => runFonts($, job, fonts, fonts => {
+ const { argv, env: vars } = typstCall({ typst: job.env.typst!, root: job.env.root, run, cache: job.env.cache, ppi, inputs, out: `${dir}/${tag}-{0p}.png`, ...(fonts ? { fonts } : {}) })
return runKillable($, argv, { env: vars, timeoutMs: COMPILE_TIMEOUT_MS, ...(signal ? { signal } : {}) })
- })
+ }))
}
// ---- The probe: where the words are ---------------------------------------
// `typst query` of the template's <mdpos> marks with probe=1: the PNG
-// compile's own inputs (and `page`), root, package path, fonts and env (no
-// ppi, format or out).
-export function probeCall(o: { typst: string; root: string; cache: string; inputs: Readonly<Record<string, string | number>>; fonts?: string }): { argv: string[]; env: Record<string, string> } {
+// compile's own inputs (and `page`), root (a run folder of its own), package
+// path, fonts and env (no ppi, format or out).
+export function probeCall(o: { typst: string; root: string; run: string; cache: string; inputs: Readonly<Record<string, string | number>>; fonts?: string }): { argv: string[]; env: Record<string, string> } {
const argv = [
o.typst, 'query',
- '--root', '/',
+ '--root', o.run,
'--package-path', `${o.root}/render/packages`,
...fontArgs(o.fonts),
'--diagnostic-format', 'short',
...Object.entries({ ...o.inputs, probe: 1 }).flatMap(([k, v]) => ['--input', `${k}=${v}`]),
- `${o.root}/render/md.typ`,
+ templateIn(o.run, o.root),
'<mdpos>',
'--field', 'value',
]
@@ -406,19 +536,23 @@ export const isSafePage = (file: string) => /\/[bd]-\d+\.png$/.test(file)
export async function probePage(
$: EngineInterface, job: Job, dir: string, o: { page: number; pages: number; isSafe: boolean },
): Promise<Positions | null> {
- let segments: unknown
+ let kept: Partial<Doc> | null = null
try {
- segments = (JSON.parse((await fsRead($, `${dir}/doc.json`)) as string) as { segments?: unknown }).segments
+ kept = JSON.parse((await fsRead($, `${dir}/doc.json`)) as string) as Partial<Doc>
} catch {
return null
}
+ const segments = kept?.segments
if (!Array.isArray(segments) || segments.length !== o.pages || !job.env.typst) return null
const typst = job.env.typst
- const { inputs, ppi } = typstInputs(job, segments as string[], dir, o.isSafe)
- const ran = await runFonts($, job, await leanFor($, job, segments as string[]), fonts => {
- const { argv, env } = probeCall({ typst, root: job.env.root, cache: job.env.cache, inputs: { ...inputs, page: o.page + 1 }, ...(fonts ? { fonts } : {}) })
+ const images = Array.isArray(kept!.images) ? kept!.images.filter((p): p is string => typeof p === 'string') : []
+ const doc: Doc = { base: typeof kept!.base === 'string' ? kept!.base : '', segments, images }
+ const { inputs, ppi } = typstInputs(job, segments, dir, o.isSafe)
+ const fonts = await leanFor($, job, segments)
+ const ran = await inRoot($, job, dir, doc, run => runFonts($, job, fonts, fonts => {
+ const { argv, env } = probeCall({ typst, root: job.env.root, run, cache: job.env.cache, inputs: { ...inputs, page: o.page + 1 }, ...(fonts ? { fonts } : {}) })
return runKillable($, argv, { env, timeoutMs: COMPILE_TIMEOUT_MS })
- })
+ }))
if (ran.exitCode !== 0) {
await logDebug($, job.env.cache, `probe ${dir} page ${o.page + 1} failed:\n${ran.stderr}`)
return null
@@ -474,7 +608,7 @@ export async function compile($: EngineInterface, job: Job, signal?: AbortSignal
let tag = 'a'
let isSafe = false
- let ran = await runTypst($, job, segments, dir, tag, false, signal)
+ let ran = await runTypst($, job, { base, segments, images }, dir, tag, false, signal)
let note: string | undefined
if (ran.isCancelled) return 'cancelled'
if (ran.exitCode !== 0) {
@@ -484,7 +618,7 @@ export async function compile($: EngineInterface, job: Job, signal?: AbortSignal
note = firstLine(ran.stderr.split('\n').find(l => /error:/i.test(l)) ?? ran.stderr).replace(/^.*error:\s*/i, '')
tag = 'b'
isSafe = true
- ran = await runTypst($, job, segments, dir, tag, true, signal)
+ ran = await runTypst($, job, { base, segments, images }, dir, tag, true, signal)
if (ran.isCancelled) return 'cancelled'
if (ran.exitCode !== 0) {
await logDebug($, job.env.cache, `compile ${job.key} with safe=1 failed:\n${ran.stderr}`)
@@ -502,7 +636,7 @@ export async function compile($: EngineInterface, job: Job, signal?: AbortSignal
if (cut.length > segments.length) {
if (signal?.aborted) return 'cancelled'
await fsWrite($, `${dir}/doc.json`, JSON.stringify({ base, segments: cut, images }))
- const again = await runTypst($, job, cut, dir, isSafe ? 'd' : 'c', isSafe, signal)
+ const again = await runTypst($, job, { base, segments: cut, images }, dir, isSafe ? 'd' : 'c', isSafe, signal)
if (again.isCancelled) return 'cancelled'
const split = again.exitCode === 0 ? await pagesOfRun($, job, dir, isSafe ? 'd' : 'c', cut) : null
if (split) {
diff --git a/tests/fonts.test.ts b/tests/fonts.test.ts
index 443c58d..88035d3 100644
--- a/tests/fonts.test.ts
+++ b/tests/fonts.test.ts
@@ -213,7 +213,7 @@ test('only plain text uses the lean set', () => {
})
test('the lean folder goes into the compile and probe calls only when given', () => {
- const o = { typst: '/t', root: '/r', cache: '/c', ppi: 144, inputs: { theme: 'dark' }, out: '/o/a-{0p}.png' }
+ const o = { typst: '/t', root: '/r', run: '/c/k/r-1', cache: '/c', ppi: 144, inputs: { theme: 'dark' }, out: '/o/a-{0p}.png' }
expect(typstCall(o).argv).not.toContain('--ignore-system-fonts')
const lean = typstCall({ ...o, fonts: '/c/fonts-1' }).argv
expect(lean.slice(lean.indexOf('--ignore-system-fonts'), lean.indexOf('--ignore-system-fonts') + 3)).toEqual(['--ignore-system-fonts', '--font-path', '/c/fonts-1'])
diff --git a/tests/pure.test.ts b/tests/pure.test.ts
index 021e13e..72bcbb7 100644
--- a/tests/pure.test.ts
+++ b/tests/pure.test.ts
@@ -460,7 +460,7 @@ test('the terminal font is read from iTerm2 and Ghostty settings', () => {
})
test('typst also reads the font folder of the font that Ghostty carries, when there is one', () => {
- const call = () => typstCall({ typst: 't', root: '/mod', cache: '/tmp/c', ppi: 144, inputs: {}, out: '/tmp/o.png' })
+ const call = () => typstCall({ typst: 't', root: '/mod', run: '/tmp/c/k/r-1', cache: '/tmp/c', ppi: 144, inputs: {}, out: '/tmp/o.png' })
expect(call().env.TYPST_FONT_PATHS).toBe(undefined)
S.fontPaths = '/home/u/.cache/cc-intelligent-ui/fonts/ghostty-1'
try {
@@ -472,7 +472,7 @@ test('typst also reads the font folder of the font that Ghostty carries, when th
test('typst runs with the network off and its own package cache', () => {
const { argv, env } = typstCall({
- typst: '/opt/homebrew/bin/typst', root: '/mod', cache: '/tmp/c', ppi: 210.5,
+ typst: '/opt/homebrew/bin/typst', root: '/mod', run: '/tmp/c/k/r-1', cache: '/tmp/c', ppi: 210.5,
inputs: { theme: 'dark', width: 698.4, 'term-font': 'MesloLGS NF', doc: '/tmp/c/k/doc.json' },
out: '/tmp/c/k/a-{0p}.png',
})
@@ -481,7 +481,9 @@ test('typst runs with the network off and its own package cache', () => {
expect(argv[argv.indexOf('--package-path') + 1]).toBe('/mod/render/packages')
expect(argv[argv.indexOf('--ppi') + 1]).toBe('210.5000')
expect(argv.includes('term-font=MesloLGS NF')).toBe(true)
- expect(argv.slice(-2)).toEqual(['/mod/render/md.typ', '/tmp/c/k/a-{0p}.png'])
+ // The root is the run folder; the template is its copy there.
+ expect(argv[argv.indexOf('--root') + 1]).toBe('/tmp/c/k/r-1')
+ expect(argv.slice(-2)).toEqual(['/tmp/c/k/r-1/mod/render/md.typ', '/tmp/c/k/a-{0p}.png'])
expect(env.HTTPS_PROXY).toBe('http://127.0.0.1:9')
expect(env.HTTP_PROXY).toBe('http://127.0.0.1:9')
expect(env.ALL_PROXY).toBe('http://127.0.0.1:9')
diff --git a/tests/root-sh-test.sh b/tests/root-sh-test.sh
new file mode 100644
index 0000000..06c6d2e
--- /dev/null
+++ b/tests/root-sh-test.sh
@@ -0,0 +1,138 @@
+#!/bin/sh
+# Makes the root of a compile with STAGE_SH (hooks/lib/typst.ts) in sh, dash
+# and bash, and compiles render/md.typ in it with the real Typst, as the mod
+# does: answer code reads no file outside the root (/etc/hosts, a file by its
+# path, `..`, /dev/zero, a link named .png to a text file), while the
+# template, the theme and the allowed images still load; the folder is
+# private, a folder is never used twice, and nothing is made through a link.
+# Usage: sh tests/root-sh-test.sh (exit 0 when all pass; the compiles skip with no typst)
+set -u
+here=$(cd "$(dirname "$0")/.." && pwd -P)
+tmp=$(mktemp -d "${TMPDIR:-/tmp}/iui-root-test.XXXXXX")
+tmp=$(cd "$tmp" && pwd -P)
+trap 'rm -rf "$tmp"' EXIT
+pass=0
+fail=0
+ok() { pass=$((pass + 1)); }
+bad() { fail=$((fail + 1)); echo "FAIL: $*"; }
+
+# The TypeScript array as sh: each '...' line, the escapes undone.
+stage_sh=$(perl -e 'local $/; $_ = <STDIN>; /export const STAGE_SH = \[\n(.*?)\n\]\.join/s or exit 1;
+ print join("\n", map { s/^\s*\x27//; s/\x27,?\s*$//; s/\\\\/\\/g; $_ } split /\n/, $1)' < "$here/hooks/lib/typst.ts")
+[ -n "$stage_sh" ] && ok || bad "STAGE_SH: not found in typst.ts"
+
+# The answer's folder: a picture, a link to it, a link named .png to a text
+# file, a folder named .png; a secret text file and a theme of the user.
+base=$tmp/base theme=$tmp/themes/mine secret=$tmp/secret.txt
+mkdir -p "$base/dir.png" "$tmp/themes"
+cp -R "$here/render/themes/claude-code" "$theme"
+echo 'SECRET-WORDS-42' > "$secret"
+if command -v typst >/dev/null 2>&1; then
+ printf '#set page(width: 40pt, height: 20pt, fill: blue)\n' | typst compile -f png - "$base/pic.png"
+else
+ printf '\211PNG\r\n\032\n' > "$base/pic.png"
+fi
+ln -s pic.png "$base/ok.png"
+ln -s "$secret" "$base/link.png"
+touch "$tmp/marker"
+
+shells=
+for s in sh dash bash; do command -v "$s" >/dev/null 2>&1 && shells="$shells $s"; done
+n=0
+for s in $shells; do
+ [ "$s" = bash ] && s='bash --posix'
+ n=$((n + 1)); k=$tmp/cache/k$n; r=$k/r-1
+ mkdir -p "$k"
+ printf '{"doc":%s}' "$n" | $s -c "$stage_sh" sh "$r" "$here" "$k/doc.json" "$theme" \
+ "$base/pic.png" "$base/ok.png" "$base/link.png" "$base/dir.png" "$here/render/themes/evil.png" "$theme/evil.png" \
+ "$base/x/../evil.png" "relative.png" "$tmp/missing.png"
+ [ $? = 0 ] && ok || bad "$s: STAGE_SH failed"
+ case $(ls -ld "$r") in drwx------*) ok ;; *) bad "$s: the run folder is not private ($(ls -ld "$r"))" ;; esac
+ [ -f "$r$here/render/md.typ" ] && [ ! -L "$r$here/render/md.typ" ] && cmp -s "$here/render/md.typ" "$r$here/render/md.typ" && ok || bad "$s: md.typ is not a copy"
+ [ -L "$r$here/render/theme.typ" ] && [ -L "$r$here/render/themes" ] && ok || bad "$s: the rest of render/ is not linked"
+ [ "$(cat "$r$k/doc.json")" = "{\"doc\":$n}" ] && ok || bad "$s: the doc JSON is not stdin"
+ [ -L "$r$theme" ] && [ -f "$r$theme/theme.json" ] && ok || bad "$s: no theme link"
+ [ -L "$r$base/pic.png" ] && [ -L "$r$base/ok.png" ] && ok || bad "$s: an allowed image is not linked"
+ for no in "$base/link.png" "$base/dir.png" "$base/evil.png" "$base/x" "$tmp/missing.png" /relative.png "$theme/evil.png"; do
+ [ ! -e "$r$no" ] && [ ! -L "$r$no" ] && ok || bad "$s: $no is in the root"
+ done
+ # Nothing is made through the links (in the plugin or the theme).
+ [ -z "$(find "$here/render" "$theme" -newer "$tmp/marker" 2>/dev/null)" ] && ok || bad "$s: files made through a link: $(find "$here/render" "$theme" -newer "$tmp/marker")"
+ # A folder that is there is never used again.
+ printf '{}' | $s -c "$stage_sh" sh "$r" "$here" "$k/doc.json" "$theme" 2>/dev/null && bad "$s: an old folder was used again" || ok
+ # A built-in theme is in render/ already: no link of its own.
+ printf '{}' | $s -c "$stage_sh" sh "$k/r-2" "$here" "$k/doc.json" "$here/render/themes/vscode" && [ -f "$k/r-2$here/render/themes/vscode/theme.json" ] \
+ && [ ! -L "$k/r-2$here/render/themes/vscode" ] && ok || bad "$s: a built-in theme"
+done
+[ -z "$(find "$here/render" -newer "$tmp/marker" 2>/dev/null)" ] && ok || bad "files made in render/"
+
+if ! command -v typst >/dev/null 2>&1; then
+ echo "root-sh-test: $pass passed, $fail failed (compiles skipped: no typst)"
+ [ "$fail" = 0 ]; exit
+fi
+
+# Compiles Markdown $2 (with base, images $3...) as the mod does, in a new
+# root; the errors in $tmp/err. A run longer than 20 s is stopped.
+runs=0
+compile() {
+ name=$1 md=$2
+ shift 2
+ runs=$((runs + 1)); k=$tmp/cache/c$runs
+ mkdir -p "$k"
+ printf '%s' "$md" | perl -e 'my ($b, @i) = @ARGV; local $/; my $m = <STDIN>; my $q = sub { my $s = shift; $s =~ s/(["\\])/\\$1/g; $s =~ s/\n/\\n/g; "\"$s\"" };
+ print "{\"base\": ", $q->($b), ", \"segments\": [", $q->($m), "], \"images\": [", join(", ", map { $q->($_) } @i), "]}"' "$base" "$@" \
+ | sh -c "$stage_sh" sh "$k/r" "$here" "$k/doc.json" "$theme" $(i=0; for p; do i=$((i + 1)); [ $((i % 2)) = 0 ] && echo "$p"; done) \
+ || { bad "$name: STAGE_SH failed"; return 1; }
+ perl -e 'alarm 20; exec @ARGV' typst compile --root "$k/r" --package-path "$here/render/packages" --input theme=dark --input width=400 \
+ --input "theme-dir=$theme" --input "doc=$k/doc.json" "$k/r$here/render/md.typ" "$tmp/$name.png" > "$tmp/err" 2>&1
+}
+
+# The mod's own answer: a picture by a relative path, one by its link and by
+# its full path, math, a table, a diagram, a code block.
+answer='# Title
+
+A picture ![p](pic.png), its link ![o](ok.png) and ![f](BASE/pic.png).
+
+Math $e^(i pi) + 1 = 0$ and $$\int_0^1 x^2 dx$$
+
+| a | b |
+|---|--:|
+| 1 | 22 |
+
+```typst
+#import "@preview/fletcher:0.5.8" as fletcher: diagram, node, edge
+#diagram(node-stroke: theme.fg, node((0, 0), [A]), edge("-|>"), node((1, 0), [B]))
+```
+
+```python
+print("hi")
+```'
+answer=$(printf '%s' "$answer" | sed "s#BASE#$base#")
+compile answer "$answer" pic.png "$base/pic.png" ok.png "$base/ok.png" "$base/pic.png" "$base/pic.png" \
+ && ok || bad "an answer with pictures, math, a table and a diagram: $(head -n 3 "$tmp/err")"
+compile allowed '```typst
+#image("'"$base"'/pic.png", width: 1cm) #read("'"$base"'/pic.png", encoding: none).len()
+```' pic.png "$base/pic.png" && ok || bad "an allowed image read by a block: $(head -n 3 "$tmp/err")"
+
+# A block that reads a file outside the root fails (the mod then shows it
+# as code), and says why: not found, or out of the root.
+for code in \
+ '#read("/etc/hosts")' '#include "/etc/hosts"' '#import "/etc/hosts"' '#image("/etc/hosts")' '#json("/etc/hosts")' '#csv("/etc/hosts")' \
+ "#read(\"$secret\")" "#include \"$secret\"" "#csv(\"$secret\")" '#read("../../../../../../../../../../etc/hosts")' \
+ "#read(\"$here/render/../../../../../../../../etc/hosts\")" "#read(\"$theme/../../secret.txt\")" '#read("/dev/zero").len()' \
+ "#read(\"$base/link.png\")" "#image(\"$base/link.png\")" "#read(\"$base/dir.png/../../secret.txt\")"; do
+ md=$(printf 'Text.\n\n```typst\n%s\n```\n' "$code")
+ if compile attack "$md" pic.png "$base/pic.png" link.png "$base/link.png"; then
+ bad "$code: compiled"
+ elif grep -q 'file not found\|escape the project root' "$tmp/err" && ! grep -q 'SECRET-WORDS\|localhost' "$tmp/err"; then ok
+ else bad "$code: $(head -n 3 "$tmp/err")"
+ fi
+done
+# The same block with the root at / (as before) reads the file: the test is real.
+compile wide "$(printf 'Text.\n\n```typst\n#read("%s")\n```\n' "$secret")" && bad "a read of the secret compiled" || ok
+typst compile --root / --package-path "$here/render/packages" --input theme=dark --input width=400 --input "theme-dir=$theme" \
+ --input "doc=$tmp/cache/c$runs/r$tmp/cache/c$runs/doc.json" "$here/render/md.typ" "$tmp/old.png" > /dev/null 2>&1 \
+ && ok || bad "with the root at /, a read of the secret did not compile (the test shows nothing)"
+
+echo "root-sh-test: $pass passed, $fail failed"
+[ "$fail" = 0 ]
diff --git a/tests/root.test.ts b/tests/root.test.ts
new file mode 100644
index 0000000..30191b2
--- /dev/null
+++ b/tests/root.test.ts
@@ -0,0 +1,172 @@
+import { expect, test } from 'claude-code/testing'
+
+import { compile, forgetTouches, probePage, rootPathOf, STAGE_SH, stageArgs, svgLinksOf } from '../hooks/lib/typst'
+import { DEFAULT_METRICS, leanDirs, type Env, type Job } from '../hooks/lib/state'
+import { DEFAULT_CELL } from '../hooks/lib/settings'
+
+// Typst's root for answer text: a run folder of its own (STAGE_SH), never `/`.
+
+const HEAD = '89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 06 40 00 00 00 40'
+
+const env: Env = {
+ typst: '/usr/bin/typst', canDraw: true, inline: false, cache: '/c', cwd: '/w', root: '/r', isMac: true, stamp: '1', home: '/h',
+ claudeTmp: '', termFont: '', designs: '/d', metrics: DEFAULT_METRICS,
+}
+let keys = 0
+const jobOf = (text: string): Job => ({
+ key: `k${++keys}`, requestId: 'r', text, columns: 100, cell: DEFAULT_CELL, theme: 'dark', size: 100, grid: true, themeDir: '/h/.claude/cc-intelligent-ui/themes/mine', env, epoch: 0,
+})
+
+// A host with typst: notes each process (argv, stdin) in order, and each
+// typst argv. `fails(argv)` says when typst fails; `stage` the exit code of
+// STAGE_SH; `exists` the files there are.
+function host(o: { fails?: (argv: string[]) => boolean; stage?: number; exists?: string[]; files?: Record<string, string> } = {}) {
+ const runs: { argv: string[]; stdin?: string }[] = []
+ const typst: string[][] = []
+ const files = new Map<string, string>(Object.entries(o.files ?? {}))
+ const run = (stdout: string, exitCode = 0) => ({ exitCode, stdout, stderr: '' })
+ const $ = {
+ fs: {
+ read: async (path: string) => {
+ if (!files.has(path)) throw new Error('ENOENT')
+ return files.get(path)!
+ },
+ write: async (path: string, text: string) => {
+ files.set(path, text)
+ },
+ exists: async (path: string) => (o.exists ?? []).includes(path),
+ list: async () => ['a-1.png', 'b-1.png'].map(name => ({ name, kind: 'file', size: 1, mtimeMs: 1, isLink: false })),
+ },
+ process: {
+ run: async (argv: string[], init?: { stdin?: string }) => {
+ runs.push({ argv, ...(init?.stdin !== undefined ? { stdin: init.stdin } : {}) })
+ if (argv[2] === STAGE_SH) return run('', o.stage ?? 0)
+ if (argv.join(' ').includes('od -An')) return run(argv.filter(a => a.endsWith('.png')).map(() => `${HEAD}\n@\n`).join(''))
+ return run('')
+ },
+ spawn: (request: { argv: string[] }) => {
+ const argv = request.argv.slice(4)
+ typst.push(argv)
+ runs.push({ argv })
+ const fail = o.fails?.(argv) ?? false
+ return (async function* () {
+ yield { stream: 'stdout' as const, text: argv[1] === 'query' ? '4242\n[]' : '4242\n' }
+ if (fail) yield { stream: 'stderr' as const, text: 'error: boom' }
+ return { code: fail ? 1 : 0, signal: null }
+ })()
+ },
+ },
+ clock: { after: () => ({ cancel() {} }) },
+ } as any
+ return { $, runs, typst, files }
+}
+
+const reset = () => {
+ leanDirs.clear()
+ forgetTouches()
+}
+const rootOf = (argv: string[]) => argv[argv.indexOf('--root') + 1]!
+const stages = (h: ReturnType<typeof host>) => h.runs.filter(r => r.argv[2] === STAGE_SH)
+// Lets the removal of a run folder (not waited for) start.
+const settle = async () => {
+ for (let i = 0; i < 20; i++) await Promise.resolve()
+}
+
+test('a compile runs typst in a new run folder of its key folder, never with the root at /', async () => {
+ reset()
+ const h = host({ exists: ['/w/pic.png'] })
+ const job = jobOf('A picture ![p](pic.png) and a block:\n\n```typst\n#read("/etc/hosts")\n```')
+ expect(await compile(h.$, job)).not.toBe('failed')
+ await settle()
+ expect(h.typst.length).toBe(1)
+ const argv = h.typst[0]!
+ const run = rootOf(argv)
+ expect(argv).toContain('--root')
+ expect(run).not.toBe('/')
+ expect(run.startsWith(`/c/${job.key}/r-`)).toBe(true)
+ // The template is the copy in the run folder (at its own path there).
+ expect(argv).toContain(`${run}/r/render/md.typ`)
+ expect(argv).not.toContain('/r/render/md.typ')
+ // The inputs keep their paths: the run folder has the files there.
+ expect(argv).toContain(`doc=/c/${job.key}/doc.json`)
+ expect(argv).toContain(`theme-dir=${job.themeDir}`)
+ // The folder is made first, with the doc JSON (as written) and the image.
+ const [stage] = stages(h)
+ expect(stage!.argv.slice(4)).toEqual([run, '/r', `/c/${job.key}/doc.json`, job.themeDir, '/w/pic.png'])
+ expect(stage!.stdin).toBe(h.files.get(`/c/${job.key}/doc.json`))
+ expect(h.runs.indexOf(stage!)).toBeLessThan(h.runs.findIndex(r => r.argv === argv))
+ // It goes after the run.
+ expect(h.runs.some(r => r.argv.join(' ') === `rm -rf ${run}`)).toBe(true)
+ reset()
+})
+
+test('the safe retry and the probe each run in a run folder of their own', async () => {
+ reset()
+ const h = host({ fails: argv => !argv.includes('safe=1') })
+ const job = jobOf('Some text.')
+ const result = await compile(h.$, job)
+ expect(result).not.toBe('failed')
+ expect(h.typst.length).toBe(2)
+ const [first, safe] = h.typst.map(rootOf)
+ expect(first).not.toBe(safe)
+ await probePage(h.$, job, `/c/${job.key}`, { page: 0, pages: 1, isSafe: true })
+ const probe = h.typst[2]!
+ expect(probe[1]).toBe('query')
+ expect(rootOf(probe).startsWith(`/c/${job.key}/r-`)).toBe(true)
+ expect(new Set(h.typst.map(rootOf)).size).toBe(3)
+ // No typst run anywhere has the root at /.
+ for (const argv of h.typst) expect(rootOf(argv)).not.toBe('/')
+ // The probe's folder has the doc JSON the compile wrote.
+ expect(stages(h)[2]!.stdin).toBe(h.files.get(`/c/${job.key}/doc.json`))
+ reset()
+})
+
+test('two compiles of the same key at once never share a run folder', async () => {
+ reset()
+ const h = host()
+ const job = jobOf('Same text.')
+ await Promise.all([compile(h.$, job), compile(h.$, { ...job })])
+ const roots = h.typst.map(rootOf)
+ expect(roots.length).toBe(2)
+ expect(roots[0]).not.toBe(roots[1])
+ reset()
+})
+
+test('when the run folder can not be made, typst still gets that folder as its root (it then fails), never /', async () => {
+ reset()
+ const h = host({ stage: 1, fails: () => true })
+ expect(await compile(h.$, jobOf('Text.'))).toBe('failed')
+ expect(h.typst.length).toBe(2)
+ for (const argv of h.typst) expect(rootOf(argv).startsWith('/c/k')).toBe(true)
+ reset()
+})
+
+test('paths in the root are resolved by name; a path above the root is none', () => {
+ expect(rootPathOf('/a/./b//c/../d.png')).toBe('/a/b/d.png')
+ expect(rootPathOf('/a/b/')).toBe('/a/b')
+ expect(rootPathOf('/../etc/hosts')).toBe(null)
+ expect(rootPathOf('/a/../../etc/hosts')).toBe(null)
+ expect(rootPathOf('/')).toBe('/')
+})
+
+test('the run folder gets each allowed image once, by its full path in the root', () => {
+ const images = ['pic.png', '/w/pic.png', './pic.png', '/w/./pic.png', 'x/../../up.png', '/w/x/../../up.png', '/../bad.png', '/../bad.png']
+ expect(stageArgs('/c/k/r-1', '/r/', '/c/k/doc.json', '/t//mine', images)).toEqual(['/c/k/r-1', '/r', '/c/k/doc.json', '/t/mine', '/w/pic.png', '/up.png'])
+ expect(stageArgs('/c/k/r-1', '/r', '/c/k/doc.json', '/t', [], ['/w/a.png', '/w/a.png'])).toEqual(['/c/k/r-1', '/r', '/c/k/doc.json', '/t', '/w/a.png'])
+})
+
+test("an SVG's linked images: relative image paths only, from the SVG's folder", () => {
+ const svg = [
+ '<image href="a.png"/>', '<image xlink:href=\'../up/b.JPG\'/>', '<image href="/etc/x.png"/>', '<image href="data:image/png;base64,AA"/>',
+ '<image href="https://x/y.png"/>', '<use href="#z"/>', '<image href="notes.txt"/>', '<image href="../../../../../x.png"/>',
+ ].join('')
+ expect(svgLinksOf(svg, '/w/pics/s.svg')).toEqual(['/w/pics/a.png', '/w/up/b.JPG'])
+})
+
+test('an allowed SVG gets the images it links to in the run folder', async () => {
+ reset()
+ const h = host({ exists: ['/w/s.svg'], files: { '/w/s.svg': '<svg><image href="pic.png"/></svg>' } })
+ await compile(h.$, jobOf('![s](s.svg)'))
+ expect(stages(h)[0]!.argv.slice(8)).toEqual(['/w/s.svg', '/w/pic.png'])
+ reset()
+})