// Standalone offline reader. Imports must remain Node built-ins only. import { createHash } from 'node:crypto'; import { constants, lstatSync, openSync, fstatSync, readSync, closeSync, realpathSync } from 'node:fs'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; export const materialFileNames = Object.freeze(['README.md', 'lab.mjs', 'lab.test.mjs', 'demo.mjs']); export const materialLimits = Object.freeze({ manifest: 8192, file: 1_048_576, archive: 4_194_304 }); const fixedNames = [...materialFileNames, 'workorder-lab.zip', 'workorder-lab-manifest.json', 'verify-lab-materials.mjs']; class MaterialError extends Error { constructor(code, name) { super(code); this.code = code; this.fixedName = name; } } export function readMaterialFile(directory, name, limit) { if (!fixedNames.includes(name)) throw new MaterialError('fixed-name'); const path = join(directory, name); let fd; try { const initial = lstatSync(path); if (!initial.isFile() || initial.isSymbolicLink()) throw new MaterialError('non-regular', name); if (initial.size > limit) throw new MaterialError('oversized', name); let flags = constants.O_RDONLY; if (process.platform !== 'win32') flags |= (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0); fd = openSync(path, flags); const opened = fstatSync(fd); if (!opened.isFile()) throw new MaterialError('non-regular', name); if (opened.size > limit) throw new MaterialError('oversized', name); if (initial.dev !== opened.dev || initial.ino !== opened.ino) throw new MaterialError('changed-during-read', name); // Never let a growing file turn readFileSync into an unbounded allocation. const buffer = Buffer.alloc(limit + 1); let length = 0; while (length < buffer.length) { const count = readSync(fd, buffer, length, Math.min(65_536, buffer.length - length), length); if (count === 0) break; length += count; } if (length > limit) throw new MaterialError('oversized', name); const after = fstatSync(fd); if (after.size !== length || opened.size !== length || after.mtimeMs !== opened.mtimeMs || after.ctimeMs !== opened.ctimeMs) { throw new MaterialError('changed-during-read', name); } return buffer.subarray(0, length); } catch (error) { if (error instanceof MaterialError) throw error; if (error?.code === 'ENOENT') throw new MaterialError('missing', name); if (error?.code === 'ELOOP') throw new MaterialError('non-regular', name); throw new MaterialError('read-failed', name); } finally { if (fd !== undefined) closeSync(fd); } } const exactKeys = (value, keys) => value !== null && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length === keys.length && keys.every(key => Object.hasOwn(value, key)); const entryValid = (entry, maximum) => exactKeys(entry, ['name', 'bytes', 'sha256']) && Number.isSafeInteger(entry.bytes) && entry.bytes >= 0 && entry.bytes <= maximum && typeof entry.sha256 === 'string' && /^[a-f0-9]{64}$/.test(entry.sha256); export function validMaterialManifest(value) { return exactKeys(value, ['schemaVersion', 'files', 'archive']) && value.schemaVersion === 'workorder-lab-manifest.v1' && Array.isArray(value.files) && value.files.length === 4 && value.files.every(entry => entryValid(entry, materialLimits.file) && materialFileNames.includes(entry.name)) && new Set(value.files.map(entry => entry.name)).size === 4 && entryValid(value.archive, materialLimits.archive) && value.archive.name === 'workorder-lab.zip'; } export function verifyMaterialDirectory(directory) { const bytes = readMaterialFile(directory, 'workorder-lab-manifest.json', materialLimits.manifest); let manifest; try { manifest = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); } catch { throw new MaterialError('manifest-json'); } if (!validMaterialManifest(manifest)) throw new MaterialError('manifest-schema'); // Paths come from this code's allowlist, never from the parsed manifest. for (const name of materialFileNames) { const expected = manifest.files.find(entry => entry.name === name); const actual = readMaterialFile(directory, name, materialLimits.file); if (actual.length !== expected.bytes || createHash('sha256').update(actual).digest('hex') !== expected.sha256) { throw new MaterialError('file-mismatch', name); } } const archive = readMaterialFile(directory, 'workorder-lab.zip', materialLimits.archive); if (archive.length !== manifest.archive.bytes || createHash('sha256').update(archive).digest('hex') !== manifest.archive.sha256) { throw new MaterialError('archive-mismatch', 'workorder-lab.zip'); } return [...materialFileNames, 'workorder-lab.zip']; } // Importing from stdin/eval is not a CLI invocation. Realpath supports a linked // entry; if lookup fails, lexical identity still lets a direct CLI run its checks. let cliEntry = false; if (process.argv[1] && process.argv[1] !== '-') { let entry; try { entry = realpathSync(process.argv[1]); } catch { entry = resolve(process.argv[1]); } cliEntry = entry === fileURLToPath(import.meta.url); } if (cliEntry) { try { if (process.argv.length !== 2) throw new MaterialError('arguments'); const checked = verifyMaterialDirectory(dirname(fileURLToPath(import.meta.url))); for (const name of checked) console.log(`PASS ${name}`); console.log('PASS selected-manifest-bytes'); } catch (error) { const code = error instanceof MaterialError ? error.code : 'read-failed'; const name = error instanceof MaterialError && fixedNames.includes(error.fixedName) ? ` ${error.fixedName}` : ''; console.log(`FAIL ${code}${name}`); process.exitCode = 1; } }