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:
@@ -1,9 +1,10 @@
|
||||
---
|
||||
id: BHL-021
|
||||
title: Реализовать fetch, кеш, lock и контрольные суммы
|
||||
status: To Do
|
||||
status: Done
|
||||
assignee: []
|
||||
created_date: '2026-11-28T14:25:44Z'
|
||||
updated_date: '2026-11-28T22:21:02Z'
|
||||
labels: []
|
||||
milestone: m-2
|
||||
dependencies:
|
||||
@@ -23,14 +24,26 @@ ordinal: 21000
|
||||
|
||||
## Acceptance Criteria
|
||||
<!-- AC:BEGIN -->
|
||||
- [ ] #1 Несовпадение контрольной суммы артефакта прерывает его использование с явной диагностикой
|
||||
- [ ] #2 Аудит зафиксированной версии работает офлайн после загрузки
|
||||
- [x] #1 Несовпадение контрольной суммы артефакта прерывает его использование с явной диагностикой
|
||||
- [x] #2 Аудит зафиксированной версии работает офлайн после загрузки
|
||||
<!-- AC:END -->
|
||||
|
||||
## Definition of Done
|
||||
<!-- DOD:BEGIN -->
|
||||
- [ ] #1 npm run check пройден (для изменений материалов и документации)
|
||||
- [ ] #2 Местный quality gate затронутого модуля пройден (для кода и конфигурации)
|
||||
- [ ] #3 В записи нет секретов, персональных путей и непубликуемых идентификаторов
|
||||
- [ ] #4 Состояние задачи в Backlog.md актуально: прогресс, блокеры, следующий шаг
|
||||
- [x] #1 npm run check пройден (для изменений материалов и документации)
|
||||
- [x] #2 Местный quality gate затронутого модуля пройден (для кода и конфигурации)
|
||||
- [x] #3 В записи нет секретов, персональных путей и непубликуемых идентификаторов
|
||||
- [x] #4 Состояние задачи в Backlog.md актуально: прогресс, блокеры, следующий шаг
|
||||
<!-- DOD:END -->
|
||||
|
||||
## Comments
|
||||
|
||||
<!-- COMMENTS:BEGIN -->
|
||||
created: 2026-11-28T22:21:02Z
|
||||
|
||||
---
|
||||
|
||||
bhl fetch <release-dir> --version --cache: копирует релиз в кеш <cache>/<version>/spec и пишет lock.json (SHA-256 фактических байтов без LF-нормализации, сортированный по путям, детерминированный). bhl verify: checksum-mismatch прерывает использование артефакта, missing-file/unexpected-file/missing-cache детектируются; после fetch validate зафиксированной версии работает офлайн без источника (тест). Пакет 36/36.
|
||||
|
||||
---
|
||||
<!-- COMMENTS:END -->
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import {
|
||||
appendFileSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
unlinkSync,
|
||||
writeFileSync,
|
||||
} from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
const cli = path.join(import.meta.dirname, '..', 'src', 'cli.ts');
|
||||
|
||||
const SCHEMAS = {
|
||||
'domain.schema.json': {
|
||||
$id: 'https://baseline-harness.dev/spec/schemas/domain.schema.json',
|
||||
type: 'object',
|
||||
required: ['id', 'title', 'description'],
|
||||
properties: {
|
||||
id: { type: 'string', pattern: '^dom-[a-z0-9-]+$' },
|
||||
title: { type: 'string' },
|
||||
description: { type: 'string' },
|
||||
},
|
||||
},
|
||||
'capability.schema.json': {
|
||||
$id: 'https://baseline-harness.dev/spec/schemas/capability.schema.json',
|
||||
type: 'object',
|
||||
required: ['id', 'domain', 'title', 'description'],
|
||||
properties: {
|
||||
id: { type: 'string', pattern: '^cap-[a-z0-9-]+$' },
|
||||
domain: { type: 'string' },
|
||||
title: { type: 'string' },
|
||||
description: { type: 'string' },
|
||||
},
|
||||
},
|
||||
'parameter.schema.json': {
|
||||
$id: 'https://baseline-harness.dev/spec/schemas/parameter.schema.json',
|
||||
type: 'object',
|
||||
required: ['id', 'type'],
|
||||
properties: {
|
||||
id: { type: 'string', pattern: '^param-[a-z0-9-]+$' },
|
||||
type: { enum: ['integer', 'string', 'boolean', 'enum'] },
|
||||
},
|
||||
},
|
||||
'requirement.schema.json': {
|
||||
$id: 'https://baseline-harness.dev/spec/schemas/requirement.schema.json',
|
||||
type: 'object',
|
||||
required: ['id', 'domain', 'capability', 'level', 'statement'],
|
||||
properties: {
|
||||
id: { type: 'string', pattern: '^req-[a-z0-9-]+$' },
|
||||
domain: { type: 'string' },
|
||||
capability: { type: 'string' },
|
||||
statement: { type: 'string' },
|
||||
level: { enum: ['MUST', 'MUST NOT', 'SHOULD', 'SHOULD NOT', 'MAY'] },
|
||||
},
|
||||
},
|
||||
'antipattern.schema.json': {
|
||||
$id: 'https://baseline-harness.dev/spec/schemas/antipattern.schema.json',
|
||||
type: 'object',
|
||||
required: ['id', 'level'],
|
||||
properties: {
|
||||
id: { type: 'string', pattern: '^ant-[a-z0-9-]+$' },
|
||||
level: { enum: ['SHOULD NOT', 'MUST NOT'] },
|
||||
},
|
||||
},
|
||||
'normative-change.schema.json': {
|
||||
$id: 'https://baseline-harness.dev/spec/schemas/normative-change.schema.json',
|
||||
type: 'object',
|
||||
properties: { id: { type: 'string' } },
|
||||
},
|
||||
};
|
||||
|
||||
const RELEASE_FILES = {
|
||||
'domains/dom-build.yaml':
|
||||
'id: dom-build\ntitle: Сборка\ndescription: Требования к сборке примера.\n',
|
||||
'capabilities/cap-verify.yaml':
|
||||
'id: cap-verify\ndomain: dom-build\ntitle: Проверка\ndescription: Требования к проверкам примера.\n',
|
||||
'requirements/req-alpha.yaml':
|
||||
'id: req-alpha\ndomain: dom-build\ncapability: cap-verify\nstatement: Релиз MUST проходить проверку.\nlevel: MUST\n',
|
||||
'parameters/.gitkeep': '',
|
||||
'antipatterns/.gitkeep': '',
|
||||
'CHANGELOG.yaml': 'changes: []\n',
|
||||
};
|
||||
|
||||
function tempDir(prefix) {
|
||||
return mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||
}
|
||||
|
||||
function makeRelease(t) {
|
||||
const source = tempDir('bhl-release-');
|
||||
mkdirSync(path.join(source, 'schemas'), { recursive: true });
|
||||
for (const [name, schema] of Object.entries(SCHEMAS)) {
|
||||
writeFileSync(path.join(source, 'schemas', name), JSON.stringify(schema), 'utf8');
|
||||
}
|
||||
for (const [name, contents] of Object.entries(RELEASE_FILES)) {
|
||||
const target = path.join(source, name);
|
||||
mkdirSync(path.dirname(target), { recursive: true });
|
||||
writeFileSync(target, contents, 'utf8');
|
||||
}
|
||||
const cache = tempDir('bhl-cache-');
|
||||
t.after(() => {
|
||||
rmSync(source, { recursive: true, force: true });
|
||||
rmSync(cache, { recursive: true, force: true });
|
||||
});
|
||||
return { source, cache };
|
||||
}
|
||||
|
||||
function runCli(...args) {
|
||||
const proc = spawnSync(process.execPath, [cli, ...args], { encoding: 'utf8' });
|
||||
return { code: proc.status, envelope: JSON.parse(proc.stdout) };
|
||||
}
|
||||
|
||||
function readLockText(cache, version) {
|
||||
return readFileSync(path.join(cache, version, 'lock.json'), 'utf8');
|
||||
}
|
||||
|
||||
function fetchAndVerify(t) {
|
||||
const { source, cache } = makeRelease(t);
|
||||
const fetched = runCli('fetch', source, '--version', '0.1.0', '--cache', cache);
|
||||
assert.equal(fetched.code, 0);
|
||||
const verified = runCli('verify', '--version', '0.1.0', '--cache', cache);
|
||||
return { source, cache, fetched, verified };
|
||||
}
|
||||
|
||||
function codes(result) {
|
||||
return result.envelope.data.errors.map((item) => item.code);
|
||||
}
|
||||
|
||||
test('fetch кладёт релиз в кеш с lock из SHA-256 фактических байтов', (t) => {
|
||||
const { cache, fetched, verified } = fetchAndVerify(t);
|
||||
assert.equal(verified.code, 0);
|
||||
assert.equal(fetched.envelope.data.files, 12);
|
||||
const lock = JSON.parse(readLockText(cache, '0.1.0'));
|
||||
assert.equal(lock.algorithm, 'sha256');
|
||||
assert.equal(lock.files.length, 12);
|
||||
assert.deepEqual(
|
||||
lock.files.map((entry) => entry.path),
|
||||
[...lock.files.map((entry) => entry.path)].sort((a, b) => a.localeCompare(b)),
|
||||
);
|
||||
assert.ok(lock.files.some((entry) => entry.path === 'CHANGELOG.yaml'));
|
||||
for (const entry of lock.files) {
|
||||
assert.match(entry.digest, /^[a-f0-9]{64}$/);
|
||||
}
|
||||
});
|
||||
|
||||
test('битый кеш прерывает использование артефакта с явной диагностикой', (t) => {
|
||||
const { cache } = fetchAndVerify(t);
|
||||
appendFileSync(
|
||||
path.join(cache, '0.1.0', 'spec', 'requirements', 'req-alpha.yaml'),
|
||||
'x\n',
|
||||
'utf8',
|
||||
);
|
||||
const verified = runCli('verify', '--version', '0.1.0', '--cache', cache);
|
||||
assert.equal(verified.code, 1);
|
||||
assert.ok(codes(verified).includes('checksum-mismatch'));
|
||||
});
|
||||
|
||||
test('удалённый или лишний файл в кеше обнаруживается', (t) => {
|
||||
const { cache } = fetchAndVerify(t);
|
||||
unlinkSync(path.join(cache, '0.1.0', 'spec', 'CHANGELOG.yaml'));
|
||||
assert.ok(
|
||||
codes(runCli('verify', '--version', '0.1.0', '--cache', cache)).includes('missing-file'),
|
||||
);
|
||||
const extra = fetchAndVerify(t);
|
||||
writeFileSync(path.join(extra.cache, '0.1.0', 'spec', 'EXTRA.md'), 'лишний\n', 'utf8');
|
||||
assert.ok(
|
||||
codes(runCli('verify', '--version', '0.1.0', '--cache', extra.cache)).includes(
|
||||
'unexpected-file',
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
test('офлайн-повтор: verify и validate зафиксированной версии работают без источника', (t) => {
|
||||
const { source, cache } = fetchAndVerify(t);
|
||||
rmSync(source, { recursive: true, force: true });
|
||||
const verified = runCli('verify', '--version', '0.1.0', '--cache', cache);
|
||||
assert.equal(verified.code, 0);
|
||||
const validated = runCli('validate', path.join(cache, '0.1.0', 'spec'));
|
||||
assert.equal(validated.code, 0);
|
||||
assert.deepEqual(validated.envelope.data.errors, []);
|
||||
});
|
||||
|
||||
test('отсутствующий кеш даёт missing-cache', (t) => {
|
||||
const { cache } = makeRelease(t);
|
||||
const verified = runCli('verify', '--version', '0.9.9', '--cache', cache);
|
||||
assert.equal(verified.code, 1);
|
||||
assert.ok(codes(verified).includes('missing-cache'));
|
||||
});
|
||||
|
||||
test('fetch детерминирован: повторный fetch даёт идентичный lock', (t) => {
|
||||
const { source, cache } = makeRelease(t);
|
||||
const first = runCli('fetch', source, '--version', '0.1.0', '--cache', cache);
|
||||
const lockFirst = readLockText(cache, '0.1.0');
|
||||
const second = runCli('fetch', source, '--version', '0.1.0', '--cache', cache);
|
||||
assert.equal(first.code, 0);
|
||||
assert.equal(second.code, 0);
|
||||
assert.equal(readLockText(cache, '0.1.0'), lockFirst);
|
||||
});
|
||||
|
||||
test('использование fetch и verify', () => {
|
||||
assert.equal(runCli('fetch', '/tmp/x').code, 2);
|
||||
assert.equal(runCli('verify').code, 2);
|
||||
assert.equal(runCli('verify', '--version', '1.0.0').code, 2);
|
||||
});
|
||||
Reference in New Issue
Block a user