/** Source-bound files at a managed replacement. No vendor interpretation or host paths. */ import * as nodeCrypto from 'node:crypto'; const digest = (algorithm: 'sha1' | 'sha256', value: string | Uint8Array): string => nodeCrypto.createHash(algorithm).update(value).digest('hex'); export interface OriginalInputReference { version: 1; /** Relative to the needs file, or to the World configuration after init copies it. */ root: string; manifest: "manifest.json"; sha256: string; inventoryDigest: string; } export interface OriginalInputCapability { version: 1; manifestArg: "--original-inputs"; rootArg: "--original-root"; digestArg: "--original-inputs-sha256"; /** Image paths whose complete overlay contents the consumer requires. */ paths: string[]; } export interface OriginalInputEntry { target: string; type: "file" | "directory" | "link"; mode: number; bytes?: number; sha256?: string; object?: string; link?: string; source: { kind: "image" | "project"; path: string; layer?: string; blob?: string }; } export interface ManagedOriginalInputs { kind: "volter.managed-original-inputs"; version: 1; service: string; family: string; /** Canonical selected service declaration; used to refuse a different stack on reuse. */ declaration: string; source: { image: string; manifest: string; config: string; layers: string[]; commit: string; compose: string; composeSha256: string; composeBytes: number; composeObject: string }; /** Authenticated complete image metadata, before the declared mounts overlay it. */ imageInventory: Array<{ target: string; type: string; mode: number; bytes: number; layer: string; link?: string }>; imageInventoryDigest: string; projectInventory: Array<{ path: string; mode: number; blob: string }>; projectInventoryDigest: string; roots: string[]; /** Complete contents beneath roots, plus every original project bind mount. */ inventory: OriginalInputEntry[]; inventoryDigest: string; start: { imageConfig: Record; service: Record; imageEntrypoint: string[] | null; imageCommand: string[] | null; command?: string[]; entrypoint?: string[]; environment: Record; envFiles: Array<{ path: string; bytes: number; sha256: string; object: string }>; unset: string[]; selfHosts: string[]; mounts: Array<{ kind: string; source?: string; target: string; readOnly: boolean }>; }; } export const originalTarget = (path: string): boolean => path === "/" || (path.startsWith("/") && !path.slice(1).split("/").some(part => !part || part === "." || part === ".." || /[\0\r\n\\]/u.test(part))); export const originalRelative = (path: string): boolean => !!path && !path.split("/").some(part => !part || part === "." || part === ".." || /[\0\r\n\\:]/u.test(part)); const hex = (value: unknown): value is string => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value); const oci = (value: unknown): value is string => typeof value === 'string' && /^sha256:[a-f0-9]{64}$/.test(value); const bytesOf = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0; const strings = (value: unknown): value is string[] => Array.isArray(value) && value.every(entry => typeof entry === 'string' && !/[\0\r\n]/.test(entry)); const bound = 128 * 1024 * 1024; export function referenceOf(value: unknown): OriginalInputReference { if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Original inputs need a versioned reference'); const ref = value as OriginalInputReference; if (ref.version !== 1 || ref.manifest !== 'manifest.json' || typeof ref.root !== 'string' || !originalRelative(ref.root) || !hex(ref.sha256) || !hex(ref.inventoryDigest) || Object.keys(ref).some(key => !['version', 'root', 'manifest', 'sha256', 'inventoryDigest'].includes(key))) throw new Error('Invalid original-input reference'); return { ...ref }; } /** Hash and validate neutral carrier data. The caller supplies I/O; no pack/vendor behavior or import effects. */ export function readSnapshot(bytes: Uint8Array, expected: string, readObject: (path: string, bytes: number) => Uint8Array): { manifest: ManagedOriginalInputs; objects: ReadonlyMap } { if (!(bytes instanceof Uint8Array) || bytes.length > 64 * 1024 * 1024 || !hex(expected) || digest('sha256', bytes) !== expected) throw new Error('Original-input manifest identity differs'); const manifest = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)) as ManagedOriginalInputs; const source = manifest.source, start = manifest.start; if (manifest.kind !== 'volter.managed-original-inputs' || manifest.version !== 1 || typeof manifest.service !== 'string' || !manifest.service || typeof manifest.family !== 'string' || !/^[a-z][a-z0-9-]*$/.test(manifest.family) || typeof manifest.declaration !== 'string' || !source || !/^[a-f0-9]{40}$/.test(source.commit) || !/^[A-Za-z0-9./:_-]+@sha256:[a-f0-9]{64}$/.test(source.image) || !oci(source.manifest) || !oci(source.config) || !Array.isArray(source.layers) || !source.layers.every(oci) || !originalRelative(source.compose) || !Array.isArray(manifest.imageInventory) || !Array.isArray(manifest.projectInventory) || !Array.isArray(manifest.inventory) || !strings(manifest.roots) || !manifest.roots.length || !manifest.roots.every(originalTarget) || new Set(manifest.roots).size !== manifest.roots.length || !hex(manifest.imageInventoryDigest) || digest('sha256', JSON.stringify(manifest.imageInventory)) !== manifest.imageInventoryDigest || !hex(manifest.inventoryDigest) || digest('sha256', JSON.stringify(manifest.inventory)) !== manifest.inventoryDigest || !hex(manifest.projectInventoryDigest) || digest('sha256', JSON.stringify(manifest.projectInventory)) !== manifest.projectInventoryDigest || !start || !start.imageConfig || typeof start.imageConfig !== 'object' || Array.isArray(start.imageConfig) || !start.service || typeof start.service !== 'object' || Array.isArray(start.service) || !strings(start.selfHosts) || !start.selfHosts.length || !strings(start.unset) || !Array.isArray(start.envFiles) || !Array.isArray(start.mounts) || !start.environment || typeof start.environment !== 'object' || Array.isArray(start.environment) || Object.entries(start.environment).some(([key, value]) => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) || typeof value !== 'string') || [start.imageEntrypoint, start.imageCommand].some(value => value !== null && !strings(value)) || [start.command, start.entrypoint].some(value => value !== undefined && !strings(value))) throw new Error('Invalid original-input manifest'); if (JSON.stringify(JSON.parse(manifest.declaration)) !== JSON.stringify(start.service) || start.service.name !== manifest.service || JSON.stringify(start.command) !== JSON.stringify(start.service.command) || JSON.stringify(start.entrypoint) !== JSON.stringify(start.service.entrypoint) || JSON.stringify(start.imageEntrypoint) !== JSON.stringify(start.imageConfig.Entrypoint ?? null) || JSON.stringify(start.imageCommand) !== JSON.stringify(start.imageConfig.Cmd ?? null) || !Array.isArray(start.service.volumes) || JSON.stringify(start.mounts.map(mount => [mount.kind, mount.source ?? null, mount.target, mount.readOnly])) !== JSON.stringify((start.service.volumes as ManagedOriginalInputs['start']['mounts']).map(mount => [mount.kind, mount.source ?? null, mount.target, mount.readOnly]))) throw new Error('Original-input start declaration differs'); const project = new Map(); for (const entry of manifest.projectInventory) { if (!entry || !originalRelative(entry.path) || project.has(entry.path) || ![0o100644, 0o100755, 0o120000, 0o160000].includes(entry.mode) || !/^[a-f0-9]{40}$/.test(entry.blob)) throw new Error('Invalid original project inventory'); project.set(entry.path, entry); } const image = new Map(); for (const entry of manifest.imageInventory) { if (!entry || !originalTarget(entry.target) || image.has(entry.target) || !['file', 'directory', 'link', 'other'].includes(entry.type) || !Number.isInteger(entry.mode) || entry.mode < 0 || entry.mode > 0o7777 || !bytesOf(entry.bytes) || !source.layers.includes(entry.layer) || (entry.type === 'link' && (typeof entry.link !== 'string' || /[\0\r\n\\]/.test(entry.link)))) throw new Error('Invalid original image inventory'); image.set(entry.target, entry); } const targets = new Set(), selected = new Map(), expectedObjects = new Map(); const hold = (entry: { sha256?: string; bytes?: number; object?: string }): void => { if (!hex(entry.sha256) || !bytesOf(entry.bytes) || entry.object !== `objects/${entry.sha256}` || (expectedObjects.has(entry.sha256) && expectedObjects.get(entry.sha256) !== entry.bytes)) throw new Error('Invalid original-input payload identity'); expectedObjects.set(entry.sha256, entry.bytes); }; for (const entry of manifest.inventory) { if (!entry || !originalTarget(entry.target) || targets.has(entry.target) || !['file', 'directory', 'link'].includes(entry.type) || !Number.isInteger(entry.mode) || entry.mode < 0 || entry.mode > 0o7777 || !entry.source || !['image', 'project'].includes(entry.source.kind)) throw new Error('Invalid original-input inventory'); targets.add(entry.target); selected.set(entry.target, entry); if (entry.source.kind === 'image') { const original = image.get(entry.source.path); if (!original || original.layer !== entry.source.layer || original.type !== entry.type || original.mode !== entry.mode || (entry.type === 'file' && original.bytes !== entry.bytes) || (entry.type === 'link' && original.link !== entry.link)) throw new Error('Original-input image provenance differs'); } else { const original = project.get(entry.source.path); if (!originalRelative(entry.source.path) || (entry.type === 'file' && (!original || original.blob !== entry.source.blob || (original.mode & 0o777) !== entry.mode))) throw new Error('Original-input project provenance differs'); } if (entry.type === 'file') hold(entry); else if (entry.object !== undefined || entry.bytes !== undefined || entry.sha256 !== undefined || (entry.type === 'link' && (typeof entry.link !== 'string' || /[\0\r\n\\]/.test(entry.link)))) throw new Error('Invalid original-input non-file'); } for (const mount of start.mounts) if (!mount || !['bind', 'named', 'anonymous'].includes(mount.kind) || !originalTarget(mount.target) || typeof mount.readOnly !== 'boolean' || (mount.source !== undefined && typeof mount.source !== 'string')) throw new Error('Invalid original-input mount declaration'); const roots = new Set(manifest.roots), mounted = new Set(start.mounts.filter(mount => mount.kind === 'bind').map(mount => mount.target)); const under = (path: string, roots: ReadonlySet): boolean => { for (let at = path;; at = at.slice(0, at.lastIndexOf('/')) || '/') { if (roots.has(at)) return true; if (at === '/') return false; } }; for (const entry of image.values()) if (under(entry.target, roots) && !under(entry.target, mounted)) { const captured = selected.get(entry.target); if (!captured || captured.source.kind !== 'image' || captured.source.path !== entry.target) throw new Error('Original image input was omitted from its declared root'); } hold({ sha256: source.composeSha256, bytes: source.composeBytes, object: source.composeObject }); for (const file of start.envFiles) { if (!file || !originalRelative(file.path)) throw new Error('Invalid original-input env_file'); hold(file); } if ([...expectedObjects.values()].reduce((sum, bytes) => sum + bytes, 0) > bound) throw new Error('Original-input snapshot exceeds its byte bound'); const objects = new Map(); for (const [sha256, size] of expectedObjects) { const data = readObject(`objects/${sha256}`, size); if (!(data instanceof Uint8Array) || data.length !== size || digest('sha256', data) !== sha256) throw new Error('Original-input payload bytes differ'); objects.set(sha256, data.slice()); } for (const entry of manifest.inventory) if (entry.type === 'file' && entry.source.kind === 'project') { const data = objects.get(entry.sha256!)!, header = new TextEncoder().encode(`blob ${data.length}\0`), blob = new Uint8Array(header.length + data.length); blob.set(header); blob.set(data, header.length); if (digest('sha1', blob) !== entry.source.blob) throw new Error('Original-input project blob identity differs'); } return { manifest, objects }; }