app

Local-first trade for farms and co-ops
git clone https://radroots.dev/git/app.git
Log | Files | Refs | README | LICENSE

commit a990c84a3ebc587062990009c68beb9f6d5ba8f6
parent 1d81aa548c60294b62e447da1623dd3ac92a13eb
Author: triesap <tyson@radroots.org>
Date:   Sun,  4 Oct 2026 04:48:39 +0000

build: emit bounded public build provenance (HCP-009)

- Generate allowlisted source, oracle and dependency lock metadata
- Fingerprint admitted web inputs and report actual source dirtiness
- Reject foreign Git identity and unsafe provenance output paths
- Test reproducible metadata and its inclusion in the static artifact

Diffstat:
Aweb/.gitignore | 2++
Mweb/.prettierignore | 1+
Mweb/package.json | 4++--
Mweb/tests/conformance/static.test.ts | 15+++++++++++++++
Aweb/tests/provenance/build-info.test.mjs | 258+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aweb/tools/build-info.mjs | 216+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
6 files changed, 494 insertions(+), 2 deletions(-)

diff --git a/web/.gitignore b/web/.gitignore @@ -0,0 +1,2 @@ +# Generated public build metadata; all other static resources remain source. +/static/build-info.json diff --git a/web/.prettierignore b/web/.prettierignore @@ -4,3 +4,4 @@ build/ test-results/ playwright-report/ AGENTS.md +static/build-info.json diff --git a/web/package.json b/web/package.json @@ -10,10 +10,10 @@ "pnpm": "12.9.1" }, "scripts": { - "build": "node tools/check-source.mjs && vite build", + "build": "node tools/check-source.mjs && node tools/build-info.mjs && vite build", "check": "node tools/check-source.mjs && svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --fail-on-warnings", "lint": "node tools/check-source.mjs && svelte-kit sync && eslint . --max-warnings 0 && prettier --check .", - "test:unit": "node tools/check-source.mjs && svelte-kit sync && vitest run --config vitest.config.ts", + "test:unit": "node tools/check-source.mjs && svelte-kit sync && vitest run --config vitest.config.ts && node --test --test-timeout=10000 tests/provenance/*.test.mjs", "test:conformance": "pnpm build && node --test tests/conformance/*.test.ts", "test:integration": "pnpm build && node --test --test-timeout=10000 tests/integration/*.test.ts", "test:e2e": "pnpm build && playwright test" diff --git a/web/tests/conformance/static.test.ts b/web/tests/conformance/static.test.ts @@ -12,6 +12,21 @@ await test('actual static shell is prerendered and excludes controlled harness c const html = await readFile(new URL('index.html', root), 'utf8'); assert.match(html, /<h1>HarvestCircle<\/h1>/); assert.match(html, /<title>HarvestCircle<\/title>/); + const metadata = await readFile(new URL('build-info.json', root), 'utf8'); + assert.equal( + metadata, + await readFile( + new URL('../../static/build-info.json', import.meta.url), + 'utf8' + ) + ); + const provenance: unknown = JSON.parse(metadata); + assert.ok(provenance && typeof provenance === 'object'); + assert.deepEqual(Object.keys(provenance), [ + 'web_source', + 'radroots_oracle', + 'dependency_locks' + ]); for (const entry of files) { if (!entry.isFile()) continue; const content = await readFile(`${entry.parentPath}/${entry.name}`, 'utf8'); diff --git a/web/tests/provenance/build-info.test.mjs b/web/tests/provenance/build-info.test.mjs @@ -0,0 +1,258 @@ +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { + mkdtemp, + mkdir, + readFile, + writeFile, + rm, + symlink, + link +} from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { test } from 'node:test'; +import { generateBuildInfo } from '../../tools/build-info.mjs'; + +/** @param {Uint8Array} bytes */ +const sha256 = (bytes) => createHash('sha256').update(bytes).digest('hex'); +/** @param {string} root @param {string[]} args */ +function git(root, ...args) { + return execFileSync('git', ['-C', root, ...args], { + encoding: 'utf8' + }).trim(); +} +/** @param {import('node:test').TestContext} t */ +async function fixture(t) { + // Actual immutable selection/lock bytes, never a native tool invocation. + const root = await mkdtemp(path.join(os.tmpdir(), 'hc provenance ')); + t.after(() => rm(root, { recursive: true, force: true })); + await mkdir(path.join(root, 'web/src'), { recursive: true }); + await mkdir(path.join(root, 'core')); + await writeFile( + path.join(root, 'web/src/source.ts'), + 'export const value = 1;\n' + ); + await writeFile( + path.join(root, 'web/.gitignore'), + '/static/build-info.json\n/build/\n' + ); + for (const name of [ + 'radroots.lib.source-lock.v1.toml', + 'core/Cargo.lock', + 'web/pnpm-lock.yaml' + ]) { + await writeFile( + path.join(root, name), + await readFile(new URL('../../../' + name, import.meta.url)) + ); + } + git(root, 'init', '-q'); + git(root, 'add', '.'); + git( + root, + '-c', + 'user.name=Provenance Test', + '-c', + 'user.email=provenance@example.invalid', + 'commit', + '-qm', + 'source fixture' + ); + return { + root, + web: path.join(root, 'web'), + generate: () => generateBuildInfo(path.join(root, 'web')) + }; +} + +await test('allowlist, actual selected oracle/locks, clean identity and deterministic generated output', async (t) => { + const f = await fixture(t); + const first = await f.generate(); + const bytes = await readFile(path.join(f.web, 'static/build-info.json')); + assert.deepEqual(Object.keys(first), [ + 'web_source', + 'radroots_oracle', + 'dependency_locks' + ]); + assert.deepEqual(Object.keys(first.web_source), [ + 'revision', + 'dirty', + 'input_sha256' + ]); + assert.deepEqual(Object.keys(first.radroots_oracle), [ + 'repository', + 'revision', + 'source_lock_sha256' + ]); + assert.deepEqual(Object.keys(first.dependency_locks), [ + 'web_pnpm_sha256', + 'oracle_cargo_sha256' + ]); + assert.equal(first.web_source.revision, git(f.root, 'rev-parse', 'HEAD')); + assert.equal(first.web_source.dirty, false); + assert.equal( + first.radroots_oracle.revision, + '189c49b74b4bafc142b00b76b296477931139e72' + ); + /** @type {Array<[keyof typeof first.dependency_locks, string]>} */ + const locks = [ + ['web_pnpm_sha256', 'web/pnpm-lock.yaml'], + ['oracle_cargo_sha256', 'core/Cargo.lock'] + ]; + for (const [field, name] of locks) { + assert.equal( + first.dependency_locks[field], + sha256(await readFile(path.join(f.root, name))) + ); + } + await mkdir(path.join(f.web, 'build')); + await writeFile(path.join(f.web, 'build/generated.txt'), 'generated output'); + await writeFile(path.join(f.root, 'native-unrelated.txt'), 'not a web input'); + assert.deepEqual(await f.generate(), first); + assert.deepEqual( + await readFile(path.join(f.web, 'static/build-info.json')), + bytes + ); + assert.equal(git(f.root, 'status', '--short', '--', 'web'), ''); + assert.doesNotMatch( + bytes.toString(), + /example.invalid|qualified|GIT_|\/Users\/|hc provenance/ + ); +}); + +for (const mutation of [ + 'modified', + 'staged', + 'deleted', + 'untracked', + 'lock', + 'oracle' +]) { + await test(`actual ${mutation} input dirtiness changes web identity`, async (t) => { + const f = await fixture(t); + const before = await f.generate(); + const file = path.join(f.web, 'src/source.ts'); + if (mutation === 'deleted') await rm(file); + else if (mutation === 'untracked') + await writeFile(path.join(f.web, 'src/new file.ts'), 'new source'); + else if (mutation === 'lock') + await writeFile(path.join(f.web, 'pnpm-lock.yaml'), 'changed web lock'); + else if (mutation === 'oracle') { + const selected = path.join(f.root, 'radroots.lib.source-lock.v1.toml'); + await writeFile( + selected, + (await readFile(selected, 'utf8')).replace( + '189c49b74b4bafc142b00b76b296477931139e72', + 'a'.repeat(40) + ) + ); + } else { + await writeFile(file, 'export const value = 2;\n'); + if (mutation === 'staged') git(f.root, 'add', 'web/src/source.ts'); + } + const after = await f.generate(); + assert.equal(after.web_source.dirty, true); + assert.notEqual( + after.web_source.input_sha256, + before.web_source.input_sha256 + ); + assert.equal(after.web_source.revision, before.web_source.revision); + if (mutation === 'oracle') + assert.equal(after.radroots_oracle.revision, 'a'.repeat(40)); + }); +} + +await test('reject unavailable/malformed selection, mismatched lock, symlink and tracked generated metadata', async (t) => { + const f = await fixture(t); + const selected = path.join(f.root, 'radroots.lib.source-lock.v1.toml'); + const original = await readFile(selected); + await writeFile(selected, 'revision = "bogus"\n'); + await assert.rejects(f.generate, /invalid public Radroots/); + await writeFile( + selected, + Buffer.concat([original, Buffer.from('revision = "duplicate"\n')]) + ); + await assert.rejects(f.generate, /Malformed/); + await rm(selected); + await assert.rejects(f.generate, /ENOENT/); + await writeFile(selected, original); + const cargoLock = path.join(f.root, 'core/Cargo.lock'); + const lockBytes = await readFile(cargoLock); + await writeFile(cargoLock, 'tampered lock'); + await assert.rejects(f.generate, /digest mismatch/); + await writeFile(cargoLock, lockBytes); + await symlink('source.ts', path.join(f.web, 'src/link.ts')); + await assert.rejects(f.generate, /Symlinked/); + await rm(path.join(f.web, 'src/link.ts')); + await f.generate(); + git(f.root, 'add', '-f', 'web/static/build-info.json'); + await assert.rejects(f.generate, /must not be tracked/); +}); + +await test('no Git and enclosing parent Git cannot masquerade as capsule source', async (t) => { + const f = await fixture(t); + await rm(path.join(f.root, '.git'), { recursive: true }); + await assert.rejects(f.generate); + const parent = path.dirname(f.root); + const outer = await mkdtemp(path.join(parent, 'hc outer ')); + t.after(() => rm(outer, { recursive: true, force: true })); + git(outer, 'init', '-q'); + const web = path.join(outer, 'capsule/web'); + await mkdir(web, { recursive: true }); + await assert.rejects(() => generateBuildInfo(web), /HarvestCircle-owned Git/); +}); + +await test('ambient sibling Git redirect and secrets cannot affect metadata', async (t) => { + const f = await fixture(t); + const before = await f.generate(); + const script = new URL('../../tools/build-info.mjs', import.meta.url); + const output = execFileSync( + process.execPath, + [ + '--input-type=module', + '-e', + `import {generateBuildInfo} from ${JSON.stringify(script.href)}; console.log(JSON.stringify(await generateBuildInfo(${JSON.stringify(f.web)})));` + ], + { + env: { + ...process.env, + GIT_DIR: '/unavailable/sibling', + GIT_WORK_TREE: '/private/parent', + HARVESTCIRCLE_SECRET: 'HC_TEST_ONLY_SECRET' + }, + encoding: 'utf8' + } + ); + assert.deepEqual(JSON.parse(output), before); + assert.doesNotMatch( + output, + /HC_TEST_ONLY_SECRET|private\/parent|unavailable/ + ); +}); + +await test('hostile output entries fail promptly without altering source', async (t) => { + const f = await fixture(t); + await f.generate(); + const directory = path.join(f.web, 'static'); + const output = path.join(directory, 'build-info.json'); + const source = path.join(f.web, 'src/source.ts'); + const original = await readFile(source); + for (const kind of ['fifo', 'symlink', 'hardlink', 'directory']) { + await rm(output, { recursive: true, force: true }); + if (kind === 'fifo') execFileSync('mkfifo', [output]); + else if (kind === 'symlink') await symlink(source, output); + else if (kind === 'hardlink') await link(source, output); + else await mkdir(output); + await assert.rejects(f.generate, /Unsafe generated metadata target/); + assert.deepEqual(await readFile(source), original); + } + await rm(directory, { recursive: true }); + await symlink(path.dirname(source), directory); + await assert.rejects( + f.generate, + /Unsafe generated metadata directory|Symlinked build provenance input/ + ); + assert.deepEqual(await readFile(source), original); +}); diff --git a/web/tools/build-info.mjs b/web/tools/build-info.mjs @@ -0,0 +1,216 @@ +import { execFileSync } from 'node:child_process'; +import { createHash, randomUUID } from 'node:crypto'; +import { constants } from 'node:fs'; +import { lstat, mkdir, open, realpath, rename, rm } from 'node:fs/promises'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const generatedPath = 'web/static/build-info.json'; +const sourceLockPath = 'radroots.lib.source-lock.v1.toml'; +const oracleLockPath = 'core/Cargo.lock'; +/** @param {Uint8Array} bytes */ +const digest = (bytes) => createHash('sha256').update(bytes).digest('hex'); + +/** @param {string} file */ +async function readInput(file) { + if ((await realpath(file)) !== file) + throw new Error('Symlinked build provenance input'); + const handle = await open( + file, + constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK + ); + try { + const stat = await handle.stat(); + if (!stat.isFile() || stat.size > 8 * 1024 * 1024) + throw new Error('Unsafe build provenance input'); + const chunks = []; + let size = 0; + for (;;) { + const buffer = Buffer.alloc(64 * 1024); + const { bytesRead } = await handle.read(buffer); + if (!bytesRead) break; + size += bytesRead; + if (size > 8 * 1024 * 1024) + throw new Error('Oversized build provenance input'); + chunks.push(buffer.subarray(0, bytesRead)); + } + const bytes = Buffer.concat(chunks); + return { bytes, executable: Boolean(stat.mode & 0o111) }; + } finally { + await handle.close(); + } +} + +// No ambient Git redirection/config injection may select a sibling or parent. +/** @param {string} root @param {string[]} args */ +function git(root, args) { + const env = Object.fromEntries( + Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_')) + ); + return execFileSync('git', ['-C', root, ...args], { + env, + encoding: 'utf8', + maxBuffer: 8 * 1024 * 1024, + stdio: ['ignore', 'pipe', 'pipe'] + }); +} + +/** @param {Uint8Array} bytes */ +function selectedOracle(bytes) { + const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes); + const fields = new Map(); + for (const line of text.split(/\r?\n/)) { + if (!line.trim() || line.trim().startsWith('#')) continue; + const entry = /^([a-z_][a-z0-9_]*) = "([^"\\]*)"$/.exec(line); + if (!entry || fields.has(entry[1])) + throw new Error('Malformed public Radroots source lock'); + fields.set(entry[1], entry[2]); + } + if ( + fields.get('schema') !== 'radroots.lib.source-lock.v1' || + fields.get('repository') !== 'https://github.com/radrootslabs/lib' || + !/^[a-f0-9]{40}$/.test(fields.get('revision') ?? '') || + fields.get('lockfile') !== oracleLockPath || + !/^[a-f0-9]{64}$/.test(fields.get('lockfile_sha256') ?? '') + ) + throw new Error('Unavailable or invalid public Radroots oracle selection'); + return fields; +} + +/** @param {string} webDirectory */ +export async function generateBuildInfo(webDirectory) { + const web = await realpath(webDirectory); + if (path.basename(web) !== 'web') + throw new Error('Build provenance requires the owned web directory'); + const root = await realpath(path.dirname(web)); + if ( + (await realpath(git(root, ['rev-parse', '--show-toplevel']).trim())) !== + root + ) + throw new Error( + 'Build provenance requires HarvestCircle-owned Git metadata' + ); + const revision = git(root, ['rev-parse', '--verify', 'HEAD']).trim(); + if (!/^[a-f0-9]{40}$/.test(revision)) + throw new Error('Unavailable source revision'); + if (git(root, ['ls-files', '-z', '--', generatedPath])) + throw new Error('Generated build metadata must not be tracked'); + + const sourceLock = await readInput(path.join(root, sourceLockPath)); + const oracle = selectedOracle(sourceLock.bytes); + const oracleLock = await readInput(path.join(root, oracleLockPath)); + const oracleLockDigest = digest(oracleLock.bytes); + if (oracleLockDigest !== oracle.get('lockfile_sha256')) + throw new Error('Selected public oracle dependency lock digest mismatch'); + const webLock = await readInput(path.join(web, 'pnpm-lock.yaml')); + + // Git admits tracked and ordinary untracked inputs, excluding ignored output. + // Only the producer's exact generated file is removed from untracked inputs. + const scope = ['web', sourceLockPath, oracleLockPath]; + const inputs = [ + ...new Set([ + ...git(root, [ + 'ls-files', + '-z', + '--cached', + '--others', + '--exclude-standard', + '--', + ...scope + ]) + .split('\0') + .filter((name) => name && name !== generatedPath), + sourceLockPath, + oracleLockPath, + 'web/pnpm-lock.yaml' + ]) + ].sort(); + const fingerprint = createHash('sha256'); + for (const name of inputs) { + fingerprint.update(JSON.stringify(name) + '\0'); + try { + const input = await readInput(path.join(root, name)); + fingerprint.update(input.executable ? 'executable\0' : 'regular\0'); + fingerprint.update(digest(input.bytes) + '\0'); + } catch (error) { + if (!( + error instanceof Error && + 'code' in error && + error.code === 'ENOENT' + )) + throw error; + fingerprint.update('deleted\0'); + } + } + const status = git(root, [ + 'status', + '--porcelain=v1', + '-z', + '--untracked-files=all', + '--', + ...scope + ]); + const entries = status.split('\0'); + let dirty = false; + for (let i = 0; i < entries.length; i++) { + const entry = entries[i]; + if (!entry) continue; + if (entry.slice(3) !== generatedPath) dirty = true; + if (/[RC]/.test(entry.slice(0, 2))) i++; + } + + // Explicit public allowlist; no environment, host paths, time or qualification. + const metadata = { + web_source: { revision, dirty, input_sha256: fingerprint.digest('hex') }, + radroots_oracle: { + repository: oracle.get('repository'), + revision: oracle.get('revision'), + source_lock_sha256: digest(sourceLock.bytes) + }, + dependency_locks: { + web_pnpm_sha256: digest(webLock.bytes), + oracle_cargo_sha256: oracleLockDigest + } + }; + const directory = path.join(web, 'static'); + await mkdir(directory, { recursive: true }); + if (!(await lstat(directory)).isDirectory()) + throw new Error('Unsafe generated metadata directory'); + const output = path.join(root, generatedPath); + try { + const previous = await lstat(output); + if (!previous.isFile() || previous.nlink !== 1) + throw new Error('Unsafe generated metadata target'); + } catch (error) { + if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT')) + throw error; + } + const temporary = path.join(directory, `.build-info-${randomUUID()}.tmp`); + const handle = await open( + temporary, + constants.O_WRONLY | + constants.O_CREAT | + constants.O_EXCL | + constants.O_NOFOLLOW, + 0o644 + ); + try { + await handle.writeFile(JSON.stringify(metadata, null, 2) + '\n'); + await handle.close(); + await rename(temporary, output); + } finally { + await handle.close(); + await rm(temporary, { force: true }); + } + return metadata; +} + +if ( + process.argv[1] && + path.resolve(process.argv[1]) === fileURLToPath(import.meta.url) +) { + const web = fileURLToPath(new URL('../', import.meta.url)); + if ((await realpath(process.cwd())) !== (await realpath(web))) + throw new Error('Run the build provenance producer from web/'); + await generateBuildInfo(web); +}