security-headers.mjs (8980B)
1 import { createHash } from 'node:crypto'; 2 import { isDeepStrictEqual } from 'node:util'; 3 import { constants } from 'node:fs'; 4 import { open, readFile, realpath, writeFile } from 'node:fs/promises'; 5 import path from 'node:path'; 6 import { fileURLToPath } from 'node:url'; 7 import ts from 'typescript'; 8 import { auditOutput } from './check-output.mjs'; 9 import { deploymentRelayPolicy } from '../src/lib/config/deployment-relays.ts'; 10 import { readRelayPolicy } from '../src/lib/config/relays.ts'; 11 12 const digest = (bytes) => createHash('sha256').update(bytes).digest('hex'); 13 14 // Only the retained opaque admission can supply origins. Hints and copied 15 // views are never accepted. This pure observation grants no launch authority. 16 export function relayConnectSources(policy) { 17 const manifest = readRelayPolicy(policy); 18 return [ 19 ...new Set( 20 [...manifest.public, ...manifest.inbox].map(({ origin }) => origin) 21 ) 22 ].sort(); 23 } 24 25 async function readBuilt(web, name) { 26 return readBoundFile(path.join(web, 'build', name)); 27 } 28 29 async function readBoundFile(file) { 30 if ((await realpath(file)) !== file) 31 throw new Error('security_headers_unsafe_input'); 32 const handle = await open( 33 file, 34 constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK 35 ); 36 try { 37 const stat = await handle.stat(); 38 if (!stat.isFile() || stat.nlink !== 1 || stat.size > 8 * 1024 * 1024) 39 throw new Error('security_headers_unsafe_input'); 40 const bytes = await handle.readFile(); 41 if (bytes.length !== stat.size || bytes.length > 8 * 1024 * 1024) 42 throw new Error('security_headers_unsafe_input'); 43 return bytes; 44 } finally { 45 await handle.close(); 46 } 47 } 48 49 async function frameworkStyles(web, artifacts) { 50 const manifestFile = path.join( 51 web, 52 '.svelte-kit/output/client/.vite/manifest.json' 53 ); 54 const manifestBytes = await readBoundFile(manifestFile); 55 const entries = Object.values( 56 JSON.parse(manifestBytes.toString('utf8')) 57 ).filter((entry) => entry.name === 'navigation'); 58 if (entries.length !== 1 || !Object.hasOwn(artifacts, entries[0].file)) 59 throw new Error('security_headers_unreviewed_style_shape'); 60 const file = entries[0].file; 61 const source = await readBuilt(web, file); 62 const styles = extractFrameworkStyleAttributes( 63 file, 64 source, 65 artifacts[file].sha256 66 ); 67 return { manifestFile, manifest_sha256: digest(manifestBytes), styles }; 68 } 69 70 // This finite value permission applies to any element with the exact hash; 71 // CSP cannot restrict a style hash to the announcer node. 72 export function extractFrameworkStyleAttributes( 73 file, 74 source, 75 expectedSourceSha256 76 ) { 77 if (digest(source) !== expectedSourceSha256) 78 throw new Error('security_headers_stale_or_invalid'); 79 const parsed = ts.createSourceFile( 80 file, 81 new TextDecoder('utf-8', { fatal: true }).decode(source), 82 ts.ScriptTarget.Latest, 83 true, 84 ts.ScriptKind.JS 85 ); 86 if (parsed.parseDiagnostics.length) 87 throw new Error('security_headers_unreviewed_style_shape'); 88 const styles = []; 89 function visit(node) { 90 if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) { 91 if (/style\s*=/.test(node.text)) { 92 const match = 93 /^<div id="svelte-announcer" aria-live="assertive" aria-atomic="true" style="([^"]+)"><!><\/div>$/.exec( 94 node.text 95 ); 96 if ( 97 !match || 98 digest(match[1]) !== 99 '4bca8ca6fa1fa2547c3298f2e2442f126ee6d6af1c97353875f0c7d009af663a' 100 ) 101 throw new Error('security_headers_unreviewed_style_shape'); 102 styles.push({ 103 owner: 'svelte-announcer', 104 file, 105 source_sha256: digest(source), 106 style_sha256: digest(match[1]), 107 csp_hash: 108 "'sha256-" + 109 createHash('sha256').update(match[1]).digest('base64') + 110 "'" 111 }); 112 } 113 } else if ( 114 ts.isTemplateExpression(node) && 115 /style\s*=|svelte-announcer/.test(node.getText(parsed)) 116 ) { 117 throw new Error('security_headers_unreviewed_style_shape'); 118 } 119 ts.forEachChild(node, visit); 120 } 121 visit(parsed); 122 if (styles.length !== 1) 123 throw new Error('security_headers_unreviewed_style_shape'); 124 return styles; 125 } 126 127 // Host-neutral SOURCE preparation, bound to the actual production source and 128 // audited compiler bytes. No alternate test policy can substitute for the 129 // policy compiled into this build. HTTPS/host/extension qualification is Q. 130 export async function prepareSecurityHeaders(webDirectory) { 131 const web = path.resolve(webDirectory); 132 const names = await auditOutput(web); 133 const artifacts = {}; 134 const inlineScripts = {}; 135 const hashes = new Set(); 136 for (const name of names) { 137 const bytes = await readBuilt(web, name); 138 artifacts[name] = { sha256: digest(bytes), bytes: bytes.length }; 139 if (!name.endsWith('.html')) continue; 140 const html = new TextDecoder('utf-8', { fatal: true }).decode(bytes); 141 const scripts = [...html.matchAll(/<script>([\s\S]*?)<\/script>/g)]; 142 if ( 143 scripts.length !== 1 || 144 [...html.matchAll(/<script\b/g)].length !== scripts.length 145 ) 146 throw new Error('security_headers_unreviewed_script_shape'); 147 inlineScripts[name] = scripts.map( 148 (match) => 149 "'sha256-" + 150 createHash('sha256').update(match[1]).digest('base64') + 151 "'" 152 ); 153 for (const hash of inlineScripts[name]) hashes.add(hash); 154 } 155 const framework = await frameworkStyles(web, artifacts); 156 const connectSources = relayConnectSources(deploymentRelayPolicy); 157 const csp = [ 158 "default-src 'none'", 159 "script-src 'self' " + [...hashes].sort().join(' '), 160 "style-src 'self'", 161 "style-src-attr 'unsafe-hashes' " + framework.styles[0].csp_hash, 162 "img-src 'self'", 163 "font-src 'self'", 164 'connect-src ' + 165 (connectSources.length ? connectSources.join(' ') : "'none'"), 166 "object-src 'none'", 167 "frame-src 'none'", 168 "frame-ancestors 'none'", 169 "base-uri 'none'", 170 "form-action 'none'", 171 "worker-src 'none'", 172 "manifest-src 'none'" 173 ].join('; '); 174 // A second audit rejects a source/build transition during derivation. 175 if (!isDeepStrictEqual(names, await auditOutput(web))) 176 throw new Error('security_headers_stale_or_invalid'); 177 for (const name of names) 178 if (digest(await readBuilt(web, name)) !== artifacts[name].sha256) 179 throw new Error('security_headers_stale_or_invalid'); 180 if ( 181 digest(await readBoundFile(framework.manifestFile)) !== 182 framework.manifest_sha256 183 ) 184 throw new Error('security_headers_stale_or_invalid'); 185 return { 186 schema: 'harvestcircle.static_security_headers.v1', 187 readiness: 'SOURCE_PREPARATION_ONLY_HOST_QUALIFICATION_PENDING', 188 relay_policy_sha256: digest( 189 JSON.stringify(readRelayPolicy(deploymentRelayPolicy)) 190 ), 191 build_info_sha256: artifacts['build-info.json'].sha256, 192 compiler_manifest_sha256: framework.manifest_sha256, 193 framework_style_attributes: framework.styles, 194 connect_sources: connectSources, 195 inline_scripts: inlineScripts, 196 artifacts, 197 headers: { 198 'Content-Security-Policy': csp, 199 'Referrer-Policy': 'no-referrer', 200 'Permissions-Policy': 201 'camera=(), microphone=(), geolocation=(), payment=(), usb=()', 202 'X-Frame-Options': 'DENY', 203 'X-Content-Type-Options': 'nosniff' 204 } 205 }; 206 } 207 208 export async function verifySecurityHeaders(webDirectory, candidate) { 209 if (!isDeepStrictEqual(candidate, await prepareSecurityHeaders(webDirectory))) 210 throw new Error('security_headers_stale_or_invalid'); 211 } 212 213 if ( 214 process.argv[1] && 215 path.resolve(process.argv[1]) === fileURLToPath(import.meta.url) 216 ) { 217 const web = path.resolve(fileURLToPath(new URL('../', import.meta.url))); 218 const [operation, output, ...extra] = process.argv.slice(2); 219 if ( 220 extra.length || 221 !['prepare', 'check'].includes(operation) || 222 !output || 223 !path.isAbsolute(output) || 224 (await realpath(process.cwd())) !== web 225 ) 226 throw new Error( 227 'Run from web: node tools/security-headers.mjs prepare|check /absolute/external/report.json' 228 ); 229 const destination = path.resolve(output); 230 const capsule = path.dirname(web); 231 if ( 232 destination === capsule || 233 destination.startsWith(capsule + path.sep) || 234 (await realpath(path.dirname(destination))) !== path.dirname(destination) 235 ) 236 throw new Error('Security header evidence must be outside the capsule'); 237 if (operation === 'prepare') { 238 const prepared = await prepareSecurityHeaders(web); 239 await writeFile(destination, JSON.stringify(prepared, null, 2) + '\n', { 240 flag: 'wx', 241 mode: 0o600 242 }); 243 console.log( 244 'Static security headers prepared; actual host qualification remains pending' 245 ); 246 } else { 247 await verifySecurityHeaders( 248 web, 249 JSON.parse(await readFile(destination, 'utf8')) 250 ); 251 console.log('Static security headers match the current audited build'); 252 } 253 }