import { createHash } from 'node:crypto'; import { parse } from 'parse5'; import { MAX_UPLOAD_BYTES } from '../src/lib/upload-policy.js'; export function validatePublicPath(file) { if (/(^|\/)(?:\.(?:env|dev\.vars)(?:\.|$)|\.(?:git|wrangler|security-artifacts)(?:\/|$)|private-drafts(?:\/|$)|node_modules(?:\/|$))|\.(?:backup|bak|map)$|(?:^|\/)star-letter\.json$/i.test(file)) { throw new Error(`Private or debug file in public output: ${file}`); } } export function validateUpload(file, bytes) { if (bytes.length > MAX_UPLOAD_BYTES) throw new Error(`Upload exceeds 25 MiB: ${file}`); const extension = file.split('.').at(-1)?.toLowerCase(); const starts = (signature) => bytes.subarray(0, signature.length).equals(Buffer.from(signature)); const valid = { png: () => starts([137, 80, 78, 71, 13, 10, 26, 10]), jpg: () => starts([255, 216, 255]), jpeg: () => starts([255, 216, 255]), gif: () => /GIF8[79]a/.test(bytes.subarray(0, 6).toString()), webp: () => bytes.subarray(0, 4).toString() === 'RIFF' && bytes.subarray(8, 12).toString() === 'WEBP', avif: () => bytes.subarray(4, 8).toString() === 'ftyp' && /avif|avis/.test(bytes.subarray(8, 32).toString()), pdf: () => starts([37, 80, 68, 70, 45]), mp4: () => bytes.subarray(4, 8).toString() === 'ftyp' && /isom|iso[2-9]|mp4[12]|avc1|M4V /.test(bytes.subarray(8, 64).toString()), webm: () => starts([26, 69, 223, 163]) && bytes.subarray(4, 4096).includes(Buffer.from('webm')) }; if (!valid[extension]?.()) throw new Error(`Unsupported or mislabeled upload: ${file}. Use PNG, JPEG, GIF, WebP, AVIF, PDF, MP4 or WebM.`); } const credentialPatterns = [ /\bgh[pousr]_[A-Za-z0-9]{30,}\b/, /\bgithub_pat_[A-Za-z0-9_]{50,}\b/, /\bsk-(?:proj-)?[A-Za-z0-9_-]{35,}\b/, /-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/ ]; export function validatePublicText(file, text) { if (credentialPatterns.some((pattern) => pattern.test(text))) throw new Error(`Possible credential in public output: ${file}. Secret values are not logged.`); } export function htmlPolicy(html, { admin = false } = {}) { const hashes = new Set(); const visit = (node) => { for (const attribute of node.attrs ?? []) { if (/^on/i.test(attribute.name)) throw new Error(`Inline event handler in generated HTML: ${attribute.name}`); if (['href', 'src', 'action'].includes(attribute.name) && /^\s*javascript:/i.test(attribute.value)) throw new Error('Executable URL in generated HTML.'); } if (node.tagName === 'script') { const attributes = Object.fromEntries(node.attrs.map(({ name, value }) => [name, value])); if (attributes.src && (!attributes.src.startsWith('/') || attributes.src.startsWith('//'))) throw new Error('External script in generated HTML.'); if (!attributes.src && !['application/json', 'application/ld+json'].includes(attributes.type)) { const location = node.sourceCodeLocation; if (!location?.endTag) throw new Error('Unclosed script in generated HTML.'); const source = html.slice(location.startTag.endOffset, location.endTag.startOffset); hashes.add(`'sha256-${createHash('sha256').update(source).digest('base64')}'`); } } for (const child of node.childNodes ?? []) visit(child); if (node.content) visit(node.content); }; visit(parse(html, { sourceCodeLocationInfo: true })); const directives = { 'default-src': "'none'", 'script-src': ["'self'", ...hashes].join(' '), 'style-src': "'self' 'unsafe-inline'", 'img-src': "'self' data: blob:", 'font-src': "'self' data:", 'connect-src': "'self'", 'form-action': "'self'", 'frame-src': "'none'", 'worker-src': "'none'", 'manifest-src': "'self'", 'media-src': "'self'" }; if (admin) { directives['connect-src'] = "'self' blob: data: https://api.github.com https://www.githubstatus.com https://sveltia-cms-auth.945436608.workers.dev"; directives['img-src'] += ' https://*.githubusercontent.com'; directives['media-src'] = "'self' blob:"; directives['frame-src'] = 'blob:'; directives['worker-src'] = "'self'"; directives['manifest-src'] = 'blob:'; } return Object.entries(directives).map(([key, value]) => `${key} ${value}`).join('; '); } export function htmlAliases(file) { if (file === 'index.html') return ['/', '/index.html', '/index']; if (file.endsWith('/index.html')) { const directory = '/' + file.slice(0, -'index.html'.length); return [directory, directory.slice(0, -1), '/' + file]; } const stem = '/' + file.slice(0, -'.html'.length); return [stem, stem + '/', '/' + file]; } export function policyRules(pages) { const groups = Map.groupBy(pages, ({ file }) => file.includes('/') ? file.split('/')[0] : file); return [...groups.entries()].flatMap(([directory, entries]) => { const policies = new Set(entries.map(({ policy }) => policy)); // Articles share a policy after sanitization. One directory rule keeps publishing // independent of article count; games with different script hashes stay separate. if (entries[0].file.includes('/') && policies.size === 1) { return [`/${directory}`, `/${directory}/*`].map((route) => ({ route, policy: entries[0].policy })); } return entries.flatMap(({ file, policy }) => htmlAliases(file).map((route) => ({ route, policy }))); }); } export function renderHeaders(template, policies) { const routes = new Map(); let headers; for (const [index, line] of template.split(/\r?\n/).entries()) { if (!line.trim() || line.trimStart().startsWith('#')) continue; if (line.startsWith('/')) { if (routes.has(line.trim())) throw new Error(`Duplicate header template route at line ${index + 1}.`); headers = new Map(); routes.set(line.trim(), headers); continue; } const field = line.match(/^\s+([A-Za-z0-9-]+):\s*(.*)$/); if (!headers || !field) throw new Error(`Invalid header template at line ${index + 1}.`); const [, name, value] = field; if (headers.has(name.toLowerCase())) throw new Error(`Duplicate header field at line ${index + 1}.`); headers.set(name.toLowerCase(), { name, value }); } for (const { route, policy } of policies) { const fields = routes.get(route) ?? new Map(); const existing = fields.get('content-security-policy'); fields.set('content-security-policy', { name: 'Content-Security-Policy', value: existing ? `${existing.value}, ${policy}` : policy }); routes.set(route, fields); } if (routes.size > 100) throw new Error('Security headers exceed Pages rule limit.'); return [...routes.entries()].map(([route, fields]) => { const lines = [...fields.values()].map(({ name, value }) => { const field = `${name}: ${value}`; if (Buffer.byteLength(field) > 2000) throw new Error(`Header exceeds Pages length limit: ${route}`); return ' ' + field; }); return [route, ...lines].join('\n'); }).join('\n\n') + '\n'; }