build-info.mjs (7671B)
1 import { execFileSync } from 'node:child_process'; 2 import { createHash, randomUUID } from 'node:crypto'; 3 import { constants } from 'node:fs'; 4 import { lstat, mkdir, open, realpath, rename, rm } from 'node:fs/promises'; 5 import path from 'node:path'; 6 import { fileURLToPath } from 'node:url'; 7 8 const generatedPath = 'web/static/build-info.json'; 9 const sourceLockPath = 'radroots.lib.source-lock.v1.toml'; 10 const oracleLockPath = 'core/Cargo.lock'; 11 /** @param {Uint8Array} bytes */ 12 const digest = (bytes) => createHash('sha256').update(bytes).digest('hex'); 13 14 /** @param {string} file */ 15 async function readInput(file) { 16 if ((await realpath(file)) !== file) 17 throw new Error('Symlinked build provenance input'); 18 const handle = await open( 19 file, 20 constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK 21 ); 22 try { 23 const stat = await handle.stat(); 24 if (!stat.isFile() || stat.size > 8 * 1024 * 1024) 25 throw new Error('Unsafe build provenance input'); 26 const chunks = []; 27 let size = 0; 28 for (;;) { 29 const buffer = Buffer.alloc(64 * 1024); 30 const { bytesRead } = await handle.read(buffer); 31 if (!bytesRead) break; 32 size += bytesRead; 33 if (size > 8 * 1024 * 1024) 34 throw new Error('Oversized build provenance input'); 35 chunks.push(buffer.subarray(0, bytesRead)); 36 } 37 const bytes = Buffer.concat(chunks); 38 return { bytes, executable: Boolean(stat.mode & 0o111) }; 39 } finally { 40 await handle.close(); 41 } 42 } 43 44 // No ambient Git redirection/config injection may select a sibling or parent. 45 /** @param {string} root @param {string[]} args */ 46 function git(root, args) { 47 const env = Object.fromEntries( 48 Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_')) 49 ); 50 return execFileSync('git', ['-C', root, ...args], { 51 env, 52 encoding: 'utf8', 53 maxBuffer: 8 * 1024 * 1024, 54 stdio: ['ignore', 'pipe', 'pipe'] 55 }); 56 } 57 58 /** @param {Uint8Array} bytes */ 59 function selectedOracle(bytes) { 60 const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes); 61 const fields = new Map(); 62 for (const line of text.split(/\r?\n/)) { 63 if (!line.trim() || line.trim().startsWith('#')) continue; 64 const entry = /^([a-z_][a-z0-9_]*) = "([^"\\]*)"$/.exec(line); 65 if (!entry || fields.has(entry[1])) 66 throw new Error('Malformed public Radroots source lock'); 67 fields.set(entry[1], entry[2]); 68 } 69 if ( 70 fields.get('schema') !== 'radroots.lib.source-lock.v1' || 71 fields.get('repository') !== 'https://github.com/radrootslabs/lib' || 72 !/^[a-f0-9]{40}$/.test(fields.get('revision') ?? '') || 73 fields.get('lockfile') !== oracleLockPath || 74 !/^[a-f0-9]{64}$/.test(fields.get('lockfile_sha256') ?? '') 75 ) 76 throw new Error('Unavailable or invalid public Radroots oracle selection'); 77 return fields; 78 } 79 80 /** @param {string} webDirectory */ 81 export async function deriveBuildInfo(webDirectory) { 82 const web = await realpath(webDirectory); 83 if (path.basename(web) !== 'web') 84 throw new Error('Build provenance requires the owned web directory'); 85 const root = await realpath(path.dirname(web)); 86 if ( 87 (await realpath(git(root, ['rev-parse', '--show-toplevel']).trim())) !== 88 root 89 ) 90 throw new Error( 91 'Build provenance requires HarvestCircle-owned Git metadata' 92 ); 93 const revision = git(root, ['rev-parse', '--verify', 'HEAD']).trim(); 94 if (!/^[a-f0-9]{40}$/.test(revision)) 95 throw new Error('Unavailable source revision'); 96 if (git(root, ['ls-files', '-z', '--', generatedPath])) 97 throw new Error('Generated build metadata must not be tracked'); 98 99 const sourceLock = await readInput(path.join(root, sourceLockPath)); 100 const oracle = selectedOracle(sourceLock.bytes); 101 const oracleLock = await readInput(path.join(root, oracleLockPath)); 102 const oracleLockDigest = digest(oracleLock.bytes); 103 if (oracleLockDigest !== oracle.get('lockfile_sha256')) 104 throw new Error('Selected public oracle dependency lock digest mismatch'); 105 const webLock = await readInput(path.join(web, 'pnpm-lock.yaml')); 106 107 // Git admits tracked and ordinary untracked inputs, excluding ignored output. 108 // Only the producer's exact generated file is removed from untracked inputs. 109 const scope = ['web', sourceLockPath, oracleLockPath]; 110 const inputs = [ 111 ...new Set([ 112 ...git(root, [ 113 'ls-files', 114 '-z', 115 '--cached', 116 '--others', 117 '--exclude-standard', 118 '--', 119 ...scope 120 ]) 121 .split('\0') 122 .filter((name) => name && name !== generatedPath), 123 sourceLockPath, 124 oracleLockPath, 125 'web/pnpm-lock.yaml' 126 ]) 127 ].sort(); 128 const fingerprint = createHash('sha256'); 129 for (const name of inputs) { 130 fingerprint.update(JSON.stringify(name) + '\0'); 131 try { 132 const input = await readInput(path.join(root, name)); 133 fingerprint.update(input.executable ? 'executable\0' : 'regular\0'); 134 fingerprint.update(digest(input.bytes) + '\0'); 135 } catch (error) { 136 if (!( 137 error instanceof Error && 138 'code' in error && 139 error.code === 'ENOENT' 140 )) 141 throw error; 142 fingerprint.update('deleted\0'); 143 } 144 } 145 const status = git(root, [ 146 'status', 147 '--porcelain=v1', 148 '-z', 149 '--untracked-files=all', 150 '--', 151 ...scope 152 ]); 153 const entries = status.split('\0'); 154 let dirty = false; 155 for (let i = 0; i < entries.length; i++) { 156 const entry = entries[i]; 157 if (!entry) continue; 158 if (entry.slice(3) !== generatedPath) dirty = true; 159 if (/[RC]/.test(entry.slice(0, 2))) i++; 160 } 161 162 // Explicit public allowlist; no environment, host paths, time or qualification. 163 const metadata = { 164 web_source: { revision, dirty, input_sha256: fingerprint.digest('hex') }, 165 radroots_oracle: { 166 repository: oracle.get('repository'), 167 revision: oracle.get('revision'), 168 source_lock_sha256: digest(sourceLock.bytes) 169 }, 170 dependency_locks: { 171 web_pnpm_sha256: digest(webLock.bytes), 172 oracle_cargo_sha256: oracleLockDigest 173 } 174 }; 175 return metadata; 176 } 177 178 /** @param {string} webDirectory */ 179 export async function generateBuildInfo(webDirectory) { 180 const metadata = await deriveBuildInfo(webDirectory); 181 const web = await realpath(webDirectory); 182 const root = await realpath(path.dirname(web)); 183 const directory = path.join(web, 'static'); 184 await mkdir(directory, { recursive: true }); 185 if (!(await lstat(directory)).isDirectory()) 186 throw new Error('Unsafe generated metadata directory'); 187 const output = path.join(root, generatedPath); 188 try { 189 const previous = await lstat(output); 190 if (!previous.isFile() || previous.nlink !== 1) 191 throw new Error('Unsafe generated metadata target'); 192 } catch (error) { 193 if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT')) 194 throw error; 195 } 196 const temporary = path.join(directory, `.build-info-${randomUUID()}.tmp`); 197 const handle = await open( 198 temporary, 199 constants.O_WRONLY | 200 constants.O_CREAT | 201 constants.O_EXCL | 202 constants.O_NOFOLLOW, 203 0o644 204 ); 205 try { 206 await handle.writeFile(JSON.stringify(metadata, null, 2) + '\n'); 207 await handle.close(); 208 await rename(temporary, output); 209 } finally { 210 await handle.close(); 211 await rm(temporary, { force: true }); 212 } 213 return metadata; 214 } 215 216 if ( 217 process.argv[1] && 218 path.resolve(process.argv[1]) === fileURLToPath(import.meta.url) 219 ) { 220 const web = fileURLToPath(new URL('../', import.meta.url)); 221 if ((await realpath(process.cwd())) !== (await realpath(web))) 222 throw new Error('Run the build provenance producer from web/'); 223 await generateBuildInfo(web); 224 }