feat: fetch, кеш и lock с SHA-256 фактических байтов (BHL-021)

- bhl fetch/verify: lock.json (sha256 байтов, без LF-нормализации),
  несовпадение суммы прерывает использование артефакта
- missing-file/unexpected-file/missing-cache — явные диагностики
- офлайн validate зафиксированной версии после загрузки (тест)
- validate.ts: Ajv strict-отказ и битый JSON — диагностики вместо crash
- пакет: 36/36 тестов
This commit is contained in:
Suslov-MD
2026-11-29 01:21:02 +03:00
parent 3cb069422f
commit 64f6f3ccb3
5 changed files with 565 additions and 21 deletions
+121
View File
@@ -1,6 +1,7 @@
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import path from 'node:path';
import { emit, ExitCode, failEnvelope, okEnvelope } from './envelope.ts';
import { fetchSpec, verifyCache } from './fetch.ts';
import { renderSpec } from './render.ts';
import { resolveProfiles } from './resolve.ts';
import { specList, specShow, validateManifest } from './spec.ts';
@@ -15,6 +16,8 @@ const USAGE_MESSAGE =
'profile resolve <spec-root> [--profile <id>] [--preset <id>]; ' +
'report validate <report.json> [--spec-root <path>]; ' +
'manifest validate <manifest.yaml> [--spec-root <path>]; ' +
'fetch <release-dir> --version <semver> --cache <dir>; ' +
'verify --version <semver> --cache <dir>; ' +
'JSON envelope on stdout; exit codes: 0 ok, 1 validation failed, 2 usage, ' +
'3 not implemented, 4 internal.';
@@ -319,6 +322,118 @@ function runSpec(command: string, rest: readonly string[]): number {
return emitSpecShow(parsed);
}
interface FetchFlags {
version?: string;
cache?: string;
positional: string[];
}
const FETCH_FLAGS: Readonly<Record<string, 'version' | 'cache'>> = {
'--version': 'version',
'--cache': 'cache',
};
function takeFetchFlag(
args: readonly string[],
cursor: number,
target: FetchFlags,
arg: string,
): { next: number } | { error: string } {
const flag = FETCH_FLAGS[arg];
const value = args[cursor + 1];
if (flag === undefined || value === undefined) {
return { error: `missing value for ${arg}` };
}
target[flag] = value;
return { next: cursor + 2 };
}
function parseFetchArgs(args: readonly string[]): FetchFlags | { error: string } {
const target: FetchFlags = { positional: [] };
let cursor = 0;
while (cursor < args.length) {
const arg = args[cursor] ?? '';
if (FETCH_FLAGS[arg] !== undefined) {
const taken = takeFetchFlag(args, cursor, target, arg);
if ('error' in taken) {
return taken;
}
cursor = taken.next;
continue;
}
if (arg.startsWith('--')) {
return { error: `unknown flag ${arg}` };
}
target.positional.push(arg);
cursor += 1;
}
return target;
}
function fetchUsage(parsed: FetchFlags): string {
if (parsed.positional.length !== 1) {
return 'fetch requires exactly one <release-dir>';
}
if (parsed.version === undefined) {
return 'fetch requires --version <semver>';
}
if (parsed.cache === undefined) {
return 'fetch requires --cache <dir>';
}
return '';
}
function runFetch(command: string, rest: readonly string[]): number {
const parsed = parseFetchArgs(rest);
if ('error' in parsed) {
emit(failEnvelope(command, 'USAGE', parsed.error));
return ExitCode.Usage;
}
const usageError = fetchUsage(parsed);
if (usageError !== '') {
emit(failEnvelope(command, 'USAGE', usageError));
return ExitCode.Usage;
}
const source = parsed.positional[0] ?? '';
const version = parsed.version ?? '';
const cache = parsed.cache ?? '';
const result = fetchSpec(source, cache, version);
const data = { source, version, cache, files: result.files, errors: result.diagnostics };
if (!result.ok) {
return emitValidationFailure(command, data, result.diagnostics.length);
}
emit(okEnvelope(command, data));
return ExitCode.Ok;
}
function runVerify(command: string, rest: readonly string[]): number {
const parsed = parseFetchArgs(rest);
if ('error' in parsed) {
emit(failEnvelope(command, 'USAGE', parsed.error));
return ExitCode.Usage;
}
if (
parsed.version === undefined ||
parsed.cache === undefined ||
parsed.positional.length !== 0
) {
emit(failEnvelope(command, 'USAGE', 'verify requires --version <semver> --cache <dir>'));
return ExitCode.Usage;
}
const result = verifyCache(parsed.cache, parsed.version);
const data = {
version: parsed.version,
cache: parsed.cache,
files: result.files,
errors: result.diagnostics,
};
if (!result.ok) {
return emitValidationFailure(command, data, result.diagnostics.length);
}
emit(okEnvelope(command, data));
return ExitCode.Ok;
}
function runManifest(command: string, rest: readonly string[]): number {
const [sub, ...args] = rest;
if (sub !== 'validate') {
@@ -432,6 +547,12 @@ export function run(argv: readonly string[]): number {
if (command === 'report') {
return runReport(command, rest);
}
if (command === 'fetch') {
return runFetch(command, rest);
}
if (command === 'verify') {
return runVerify(command, rest);
}
if (command === 'audit') {
emit(failEnvelope(command, 'NOT_IMPLEMENTED', `${command} is not implemented yet`));
return ExitCode.NotImplemented;
+188
View File
@@ -0,0 +1,188 @@
import { createHash } from 'node:crypto';
import {
copyFileSync,
existsSync,
mkdirSync,
readdirSync,
readFileSync,
statSync,
writeFileSync,
} from 'node:fs';
import path from 'node:path';
import type { Diagnostic } from './validate.ts';
export interface CacheResult {
ok: boolean;
diagnostics: Diagnostic[];
files: number;
}
interface LockEntry {
path: string;
digest: string;
}
interface LockDocument {
version: string;
algorithm: string;
files: LockEntry[];
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function isLock(value: unknown): value is LockDocument {
if (!isRecord(value)) {
return false;
}
return (
typeof value['version'] === 'string' &&
Array.isArray(value['files']) &&
typeof value['algorithm'] === 'string'
);
}
function walkFiles(dir: string, prefix = ''): string[] {
const result: string[] = [];
for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) =>
a.name.localeCompare(b.name),
)) {
const rel = prefix === '' ? entry.name : `${prefix}/${entry.name}`;
if (entry.isDirectory()) {
result.push(...walkFiles(path.join(dir, entry.name), rel));
} else if (entry.isFile()) {
result.push(rel);
}
}
return result;
}
function digestOf(file: string): string {
return createHash('sha256').update(readFileSync(file)).digest('hex');
}
function copyTree(source: string, target: string): string[] {
const files = walkFiles(source);
for (const rel of files) {
const to = path.join(target, rel);
mkdirSync(path.dirname(to), { recursive: true });
copyFileSync(path.join(source, rel), to);
}
return files;
}
function lockPath(cacheDir: string, version: string): string {
return path.join(cacheDir, version, 'lock.json');
}
function specDir(cacheDir: string, version: string): string {
return path.join(cacheDir, version, 'spec');
}
export function fetchSpec(source: string, cacheDir: string, version: string): CacheResult {
const diagnostics: Diagnostic[] = [];
if (!existsSync(source) || !statSync(source).isDirectory()) {
return {
ok: false,
diagnostics: [
{
file: source,
code: 'missing-directory',
message: 'release source directory is required',
},
],
files: 0,
};
}
const target = specDir(cacheDir, version);
mkdirSync(target, { recursive: true });
const files = copyTree(source, target);
const lock: LockDocument = {
version,
algorithm: 'sha256',
files: files
.map((rel) => ({ path: rel, digest: digestOf(path.join(target, rel)) }))
.sort((a, b) => a.path.localeCompare(b.path)),
};
writeFileSync(lockPath(cacheDir, version), `${JSON.stringify(lock, null, 2)}\n`, 'utf8');
return { ok: true, diagnostics, files: files.length };
}
function readLock(lockFile: string, diagnostics: Diagnostic[]): LockDocument | undefined {
if (!existsSync(lockFile)) {
diagnostics.push({ file: lockFile, code: 'missing-cache', message: 'version is not in cache' });
return undefined;
}
try {
const parsed: unknown = JSON.parse(readFileSync(lockFile, 'utf8'));
if (!isLock(parsed)) {
diagnostics.push({ file: lockFile, code: 'parse-error', message: 'lock.json is malformed' });
return undefined;
}
return parsed;
} catch {
diagnostics.push({
file: lockFile,
code: 'parse-error',
message: 'lock.json is not valid JSON',
});
return undefined;
}
}
function checkEntries(lock: LockDocument, root: string, diagnostics: Diagnostic[]): void {
for (const entry of lock.files) {
const file = path.join(root, entry.path);
if (!existsSync(file)) {
diagnostics.push({
file,
code: 'missing-file',
message: `cached file ${entry.path} is missing`,
});
continue;
}
if (digestOf(file) !== entry.digest) {
diagnostics.push({
file,
code: 'checksum-mismatch',
message: `cached file ${entry.path} does not match lock (sha256 of bytes)`,
});
}
}
}
function checkExtras(lock: LockDocument, root: string, diagnostics: Diagnostic[]): void {
const expected = new Set(lock.files.map((entry) => entry.path));
for (const rel of walkFiles(root)) {
if (!expected.has(rel)) {
diagnostics.push({
file: path.join(root, rel),
code: 'unexpected-file',
message: `file ${rel} is not in lock`,
});
}
}
}
export function verifyCache(cacheDir: string, version: string): CacheResult {
const diagnostics: Diagnostic[] = [];
const lockFile = lockPath(cacheDir, version);
const lock = readLock(lockFile, diagnostics);
if (lock === undefined) {
return { ok: false, diagnostics, files: 0 };
}
const root = specDir(cacheDir, version);
if (!existsSync(root)) {
diagnostics.push({
file: root,
code: 'missing-cache',
message: 'cached spec directory is missing',
});
return { ok: false, diagnostics, files: 0 };
}
checkEntries(lock, root, diagnostics);
checkExtras(lock, root, diagnostics);
diagnostics.sort((a, b) => `${a.file} ${a.code}`.localeCompare(`${b.file} ${b.code}`));
return { ok: diagnostics.length === 0, diagnostics, files: lock.files.length };
}
+28 -14
View File
@@ -137,6 +137,33 @@ class Validator {
this.diagnostics.push(item);
}
private addSchemaFile(schemasDir: string, name: string): void {
const file = `schemas/${name}`;
let text: string;
try {
text = readFileSync(path.join(schemasDir, name), 'utf8');
} catch {
this.push(file, 'read-error', 'schema file is not readable');
return;
}
let parsed: unknown;
try {
parsed = JSON.parse(text);
} catch {
this.push(file, 'parse-error', 'schema file is not valid JSON');
return;
}
if (!isSchema(parsed)) {
this.push(file, 'parse-error', 'schema must be an object or boolean');
return;
}
try {
this.ajv.addSchema(parsed);
} catch {
this.push(file, 'schema-error', 'schema is rejected by Ajv strict mode');
}
}
private addSchemas(): boolean {
const schemasDir = path.join(this.root, 'schemas');
if (!existsSync(schemasDir)) {
@@ -155,20 +182,7 @@ class Validator {
return false;
}
for (const name of names) {
const file = `schemas/${name}`;
let text: string;
try {
text = readFileSync(path.join(schemasDir, name), 'utf8');
} catch {
this.push(file, 'read-error', 'schema file is not readable');
continue;
}
const parsed: unknown = JSON.parse(text);
if (isSchema(parsed)) {
this.ajv.addSchema(parsed);
} else {
this.push(file, 'parse-error', 'schema must be an object or boolean');
}
this.addSchemaFile(schemasDir, name);
}
return true;
}