feat: bhl audit — детерминированный движок аудита (BHL-026)
- встроенные проверки: команда качества, lockfile, CI-конфиг по Effective Spec - subject: отпечаток дерева SHA-256 + git revision/dirty (git из PATH — узкое исключение sonarjs/no-os-command-from-path в eslint.config.mjs) - evidence с fingerprint байтов; FAIL доказателен (отсутствие — наблюдение) - отчёт проходит report validate; повторный аудит идентичен (тесты) - требования без проверки → UNKNOWN/semantic/low; пакет 41/41
This commit is contained in:
@@ -0,0 +1,332 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { resolveProfiles } from './resolve.ts';
|
||||
import type { Diagnostic } from './validate.ts';
|
||||
|
||||
export interface AuditOptions {
|
||||
projectDir: string;
|
||||
specRoot: string;
|
||||
profileIds: readonly string[];
|
||||
presetIds: readonly string[];
|
||||
generatedAt: string;
|
||||
}
|
||||
|
||||
export interface AuditResult {
|
||||
ok: boolean;
|
||||
report: Record<string, unknown> | undefined;
|
||||
diagnostics: readonly Diagnostic[];
|
||||
}
|
||||
|
||||
interface CheckOutcome {
|
||||
status: 'PASS' | 'FAIL';
|
||||
rationale: string;
|
||||
evidence: Record<string, unknown>[];
|
||||
}
|
||||
|
||||
function absenceEvidence(locator: string, description: string): Record<string, unknown>[] {
|
||||
return [
|
||||
{
|
||||
kind: 'other',
|
||||
locator,
|
||||
description,
|
||||
captured_at: EPOCH_DATE,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const SKIP_DIRS = new Set(['.git', 'node_modules', 'out']);
|
||||
// captured_at по схеме — календарная дата; детерминированная эпоха для встроенных проверок.
|
||||
const EPOCH_DATE = '1970-01-01';
|
||||
const REPORT_STATUSES = [
|
||||
'PASS',
|
||||
'FAIL',
|
||||
'PARTIAL',
|
||||
'EXEMPT',
|
||||
'NOT_APPLICABLE',
|
||||
'UNKNOWN',
|
||||
'BLOCKED',
|
||||
] as const;
|
||||
const LOCKFILES = [
|
||||
'package-lock.json',
|
||||
'yarn.lock',
|
||||
'pnpm-lock.yaml',
|
||||
'npm-shrinkwrap.json',
|
||||
'Gemfile.lock',
|
||||
'go.sum',
|
||||
'uv.lock',
|
||||
'poetry.lock',
|
||||
'Cargo.lock',
|
||||
];
|
||||
|
||||
function sha256(data: Buffer | string): string {
|
||||
return `sha256:${createHash('sha256').update(data).digest('hex')}`;
|
||||
}
|
||||
|
||||
function walkFiles(dir: string, prefix: string, acc: string[]): void {
|
||||
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()) {
|
||||
if (!SKIP_DIRS.has(entry.name)) {
|
||||
walkFiles(path.join(dir, entry.name), rel, acc);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (entry.isFile()) {
|
||||
acc.push(rel);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function treeFingerprint(dir: string): string {
|
||||
const files: string[] = [];
|
||||
walkFiles(dir, '', files);
|
||||
const hash = createHash('sha256');
|
||||
for (const file of files) {
|
||||
hash
|
||||
.update(file)
|
||||
.update('\u0000')
|
||||
.update(readFileSync(path.join(dir, file)))
|
||||
.update('\u0000');
|
||||
}
|
||||
return `sha256:${hash.digest('hex')}`;
|
||||
}
|
||||
|
||||
function gitInfo(dir: string): { revision?: string; dirty?: boolean } {
|
||||
// git намеренно берётся из PATH оператора: это необязательные метаданные аудита,
|
||||
// отсутствие git даёт пустой объект, а не сбой (см. eslint.config.mjs, src/audit.ts).
|
||||
const rev = spawnSync('git', ['-C', dir, 'rev-parse', 'HEAD'], { encoding: 'utf8' });
|
||||
if (rev.status !== 0) {
|
||||
return {};
|
||||
}
|
||||
const status = spawnSync('git', ['-C', dir, 'status', '--porcelain'], { encoding: 'utf8' });
|
||||
return { revision: rev.stdout.trim(), dirty: status.stdout.trim() !== '' };
|
||||
}
|
||||
|
||||
function evidenceFor(file: string, locator: string, description: string): Record<string, unknown> {
|
||||
const bytes = readFileSync(file);
|
||||
return {
|
||||
kind: 'file',
|
||||
description,
|
||||
locator,
|
||||
fingerprint: sha256(bytes),
|
||||
captured_at: EPOCH_DATE,
|
||||
};
|
||||
}
|
||||
|
||||
function readText(file: string): string {
|
||||
try {
|
||||
return readFileSync(file, 'utf8');
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
function getProp(obj: unknown, key: string): unknown {
|
||||
if (typeof obj === 'object' && obj !== null) {
|
||||
return Reflect.get(obj, key);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function declaresQuality(pkg: unknown): boolean {
|
||||
const scripts = getProp(pkg, 'scripts');
|
||||
return (
|
||||
typeof scripts === 'object' && scripts !== null && ('quality' in scripts || 'check' in scripts)
|
||||
);
|
||||
}
|
||||
|
||||
function checkQualityCommand(dir: string): CheckOutcome {
|
||||
const candidates: [string, (text: string) => boolean][] = [
|
||||
[
|
||||
'package.json',
|
||||
(text) => {
|
||||
try {
|
||||
return declaresQuality(JSON.parse(text));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
],
|
||||
['Makefile', (text) => /^quality:/m.test(text)],
|
||||
];
|
||||
for (const [name, matches] of candidates) {
|
||||
const file = path.join(dir, name);
|
||||
if (existsSync(file) && matches(readText(file))) {
|
||||
return {
|
||||
status: 'PASS',
|
||||
rationale: `Воспроизводимая команда качества объявлена в ${name}.`,
|
||||
evidence: [evidenceFor(file, name, `${name} объявляет команду качества`)],
|
||||
};
|
||||
}
|
||||
}
|
||||
return {
|
||||
status: 'FAIL',
|
||||
rationale:
|
||||
'Не найдено объявленной команды качества (package.json scripts.quality|check или Makefile цель quality).',
|
||||
evidence: absenceEvidence(
|
||||
'package.json, Makefile',
|
||||
'Ни package.json с scripts.quality|check, ни Makefile с целью quality не найдены.',
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function checkPresence(
|
||||
dir: string,
|
||||
candidates: readonly string[],
|
||||
label: string,
|
||||
rationaleFail: string,
|
||||
): CheckOutcome {
|
||||
for (const name of candidates) {
|
||||
const file = path.join(dir, name);
|
||||
if (existsSync(file) && statSync(file).isFile()) {
|
||||
return {
|
||||
status: 'PASS',
|
||||
rationale: `${label}: найден ${name}.`,
|
||||
evidence: [evidenceFor(file, name, `${label} зафиксирован`)],
|
||||
};
|
||||
}
|
||||
}
|
||||
return {
|
||||
status: 'FAIL',
|
||||
rationale: rationaleFail,
|
||||
evidence: absenceEvidence(candidates.join(', '), `${label}: ни один из кандидатов не найден.`),
|
||||
};
|
||||
}
|
||||
|
||||
function ciCandidates(dir: string): string[] {
|
||||
const fixed = ['.gitlab-ci.yml', 'Jenkinsfile', '.buildkite/pipeline.yml'];
|
||||
const workflows = path.join(dir, '.github', 'workflows');
|
||||
const extra: string[] = [];
|
||||
if (existsSync(workflows)) {
|
||||
for (const name of readdirSync(workflows)) {
|
||||
if (/\.ya?ml$/.test(name)) {
|
||||
extra.push(`.github/workflows/${name}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
return [...extra, ...fixed];
|
||||
}
|
||||
|
||||
const CHECKS: Readonly<Record<string, (dir: string) => CheckOutcome>> = {
|
||||
'req-synth-alpha': checkQualityCommand,
|
||||
'req-synth-beta': (dir) =>
|
||||
checkPresence(
|
||||
dir,
|
||||
LOCKFILES,
|
||||
'Блокировка зависимостей',
|
||||
'Не найден lockfile ни в одном из известных форматов.',
|
||||
),
|
||||
'req-synth-gamma': (dir) =>
|
||||
checkPresence(
|
||||
dir,
|
||||
ciCandidates(dir),
|
||||
'Конфигурация CI',
|
||||
'Не найдена конфигурация CI (.github/workflows/*.yml, .gitlab-ci.yml и др.).',
|
||||
),
|
||||
};
|
||||
|
||||
function unknownFinding(requirement: string): Record<string, unknown> {
|
||||
return {
|
||||
requirement,
|
||||
status: 'UNKNOWN',
|
||||
method: 'semantic',
|
||||
confidence: 'low',
|
||||
rationale:
|
||||
'Детерминированная проверка для этого требования не реализована; требуется семантический аудит.',
|
||||
evidence: [
|
||||
{
|
||||
kind: 'observation',
|
||||
description:
|
||||
'Встроенный реестр детерминированных проверок не содержит записи о требовании.',
|
||||
captured_at: new Date(0).toISOString(),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function buildFinding(projectDir: string, requirement: string): Record<string, unknown> {
|
||||
const check = CHECKS[requirement];
|
||||
if (check === undefined) {
|
||||
return unknownFinding(requirement);
|
||||
}
|
||||
const outcome = check(projectDir);
|
||||
const finding: Record<string, unknown> = {
|
||||
requirement,
|
||||
status: outcome.status,
|
||||
method: 'deterministic',
|
||||
rationale: outcome.rationale,
|
||||
evidence: outcome.evidence,
|
||||
};
|
||||
return finding;
|
||||
}
|
||||
|
||||
function summarize(findings: readonly Readonly<Record<string, unknown>>[]): Record<string, number> {
|
||||
const summary: Record<string, number> = {};
|
||||
for (const status of REPORT_STATUSES) {
|
||||
summary[status] = 0;
|
||||
}
|
||||
for (const finding of findings) {
|
||||
const status = finding['status'];
|
||||
if (typeof status === 'string') {
|
||||
summary[status] = (summary[status] ?? 0) + 1;
|
||||
}
|
||||
}
|
||||
return summary;
|
||||
}
|
||||
|
||||
function packageVersion(): string {
|
||||
try {
|
||||
const version = getProp(
|
||||
JSON.parse(readFileSync(path.join(import.meta.dirname, '..', 'package.json'), 'utf8')),
|
||||
'version',
|
||||
);
|
||||
if (typeof version === 'string') {
|
||||
return version;
|
||||
}
|
||||
} catch {
|
||||
// fall through to default
|
||||
}
|
||||
return '0.0.0';
|
||||
}
|
||||
|
||||
export function runAudit(options: AuditOptions): AuditResult {
|
||||
const diagnostics: Diagnostic[] = [];
|
||||
const resolution = resolveProfiles(options.specRoot, options.profileIds, options.presetIds);
|
||||
diagnostics.push(...resolution.diagnostics);
|
||||
if (!resolution.ok) {
|
||||
return { ok: false, report: undefined, diagnostics };
|
||||
}
|
||||
const requirements = resolution.effective
|
||||
.map((entry) => entry.requirement)
|
||||
.sort((a, b) => a.localeCompare(b));
|
||||
const findings = requirements.map((requirement) => buildFinding(options.projectDir, requirement));
|
||||
const fingerprint = treeFingerprint(options.projectDir);
|
||||
const git = gitInfo(options.projectDir);
|
||||
const subject: Record<string, unknown> = {
|
||||
kind: git.revision === undefined ? 'directory' : 'repository',
|
||||
fingerprint,
|
||||
};
|
||||
Object.assign(subject, git);
|
||||
const report: Record<string, unknown> = {
|
||||
id: `rep-audit-${fingerprint.slice(7, 23)}`,
|
||||
generated_at: options.generatedAt,
|
||||
tool: { name: 'bhl', version: packageVersion() },
|
||||
subject,
|
||||
spec_version: '0.0.0',
|
||||
profiles: resolution.profiles,
|
||||
findings,
|
||||
summary: summarize(findings),
|
||||
};
|
||||
return { ok: true, report, diagnostics };
|
||||
}
|
||||
|
||||
export function writeAuditReport(result: AuditResult, out: string): void {
|
||||
if (result.report !== undefined) {
|
||||
writeFileSync(out, `${JSON.stringify(result.report, null, 2)}\n`, 'utf8');
|
||||
}
|
||||
}
|
||||
+110
-3
@@ -1,5 +1,6 @@
|
||||
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { runAudit, writeAuditReport } from './audit.ts';
|
||||
import { emit, ExitCode, failEnvelope, okEnvelope } from './envelope.ts';
|
||||
import { fetchSpec, verifyCache } from './fetch.ts';
|
||||
import { renderReport, renderSpec } from './render.ts';
|
||||
@@ -9,7 +10,7 @@ import { validateReport } from './report.ts';
|
||||
import { validateSpec } from './validate.ts';
|
||||
|
||||
const USAGE_MESSAGE =
|
||||
'Usage: bhl <version|validate|spec|profile|report|manifest|audit> [args]; ' +
|
||||
'Usage: bhl <version|validate|spec|profile|report|manifest|fetch|verify|audit> [args]; ' +
|
||||
'spec list [--spec-root <path>] [--domain <id>] [--capability <id>]; ' +
|
||||
'spec show <req-id> [--spec-root <path>]; ' +
|
||||
'spec render --spec-root <path> --out <dir>; ' +
|
||||
@@ -19,6 +20,8 @@ const USAGE_MESSAGE =
|
||||
'manifest validate <manifest.yaml> [--spec-root <path>]; ' +
|
||||
'fetch <release-dir> --version <semver> --cache <dir>; ' +
|
||||
'verify --version <semver> --cache <dir>; ' +
|
||||
'audit <project-dir> --out <report.json> [--spec-root <path>] [--profile <id>] ' +
|
||||
'[--preset <id>] [--generated-at <iso>]; ' +
|
||||
'JSON envelope on stdout; exit codes: 0 ok, 1 validation failed, 2 usage, ' +
|
||||
'3 not implemented, 4 internal.';
|
||||
|
||||
@@ -461,6 +464,111 @@ function runVerify(command: string, rest: readonly string[]): number {
|
||||
return ExitCode.Ok;
|
||||
}
|
||||
|
||||
const AUDIT_FLAGS: Readonly<
|
||||
Record<string, 'spec-root' | 'out' | 'generated-at' | 'profile' | 'preset'>
|
||||
> = {
|
||||
'--spec-root': 'spec-root',
|
||||
'--out': 'out',
|
||||
'--generated-at': 'generated-at',
|
||||
'--profile': 'profile',
|
||||
'--preset': 'preset',
|
||||
};
|
||||
|
||||
interface AuditFlags {
|
||||
root: string;
|
||||
out?: string;
|
||||
generatedAt?: string;
|
||||
profiles: string[];
|
||||
presets: string[];
|
||||
positional: string[];
|
||||
}
|
||||
|
||||
function takeAuditFlag(
|
||||
args: readonly string[],
|
||||
cursor: number,
|
||||
target: AuditFlags,
|
||||
arg: string,
|
||||
): { next: number } | { error: string } {
|
||||
const flag = AUDIT_FLAGS[arg];
|
||||
const value = args[cursor + 1];
|
||||
if (flag === undefined || value === undefined) {
|
||||
return { error: `missing value for ${arg}` };
|
||||
}
|
||||
if (flag === 'spec-root') {
|
||||
target.root = value;
|
||||
} else if (flag === 'out') {
|
||||
target.out = value;
|
||||
} else if (flag === 'generated-at') {
|
||||
target.generatedAt = value;
|
||||
} else if (flag === 'profile') {
|
||||
target.profiles.push(value);
|
||||
} else {
|
||||
target.presets.push(value);
|
||||
}
|
||||
return { next: cursor + 2 };
|
||||
}
|
||||
|
||||
function parseAuditArgs(args: readonly string[]): AuditFlags | { error: string } {
|
||||
const target: AuditFlags = { root: 'spec', profiles: [], presets: [], positional: [] };
|
||||
let cursor = 0;
|
||||
while (cursor < args.length) {
|
||||
const arg = args[cursor] ?? '';
|
||||
if (AUDIT_FLAGS[arg] !== undefined) {
|
||||
const taken = takeAuditFlag(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 runAuditCommand(command: string, rest: readonly string[]): number {
|
||||
const parsed = parseAuditArgs(rest);
|
||||
if ('error' in parsed) {
|
||||
emit(failEnvelope(command, 'USAGE', parsed.error));
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
const projectDir = parsed.positional[0];
|
||||
const out = parsed.out;
|
||||
if (projectDir === undefined || parsed.positional.length !== 1 || out === undefined) {
|
||||
emit(failEnvelope(command, 'USAGE', 'audit requires <project-dir> and --out <report.json>'));
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
const generatedAt = parsed.generatedAt ?? new Date().toISOString().slice(0, 10);
|
||||
const result = runAudit({
|
||||
projectDir,
|
||||
specRoot: parsed.root,
|
||||
profileIds: parsed.profiles,
|
||||
presetIds: parsed.presets,
|
||||
generatedAt,
|
||||
});
|
||||
if (!result.ok || result.report === undefined) {
|
||||
return emitValidationFailure(
|
||||
command,
|
||||
{ project: projectDir, errors: result.diagnostics },
|
||||
result.diagnostics.length,
|
||||
);
|
||||
}
|
||||
mkdirSync(path.dirname(out), { recursive: true });
|
||||
writeAuditReport(result, out);
|
||||
emit(
|
||||
okEnvelope(command, {
|
||||
project: projectDir,
|
||||
out,
|
||||
summary: result.report['summary'],
|
||||
}),
|
||||
);
|
||||
return ExitCode.Ok;
|
||||
}
|
||||
|
||||
function runManifest(command: string, rest: readonly string[]): number {
|
||||
const [sub, ...args] = rest;
|
||||
if (sub !== 'validate') {
|
||||
@@ -607,8 +715,7 @@ export function run(argv: readonly string[]): number {
|
||||
return runVerify(command, rest);
|
||||
}
|
||||
if (command === 'audit') {
|
||||
emit(failEnvelope(command, 'NOT_IMPLEMENTED', `${command} is not implemented yet`));
|
||||
return ExitCode.NotImplemented;
|
||||
return runAuditCommand(command, rest);
|
||||
}
|
||||
emit(failEnvelope(command, 'USAGE', USAGE_MESSAGE));
|
||||
return ExitCode.Usage;
|
||||
|
||||
@@ -243,7 +243,7 @@ class Resolver {
|
||||
this.root = root;
|
||||
}
|
||||
|
||||
run(profileIds: string[], presetIds: string[]): ResolveResult {
|
||||
run(profileIds: readonly string[], presetIds: readonly string[]): ResolveResult {
|
||||
if (!this.addSchemas()) {
|
||||
return { ok: false, profiles: [], effective: [], diagnostics: this.diagnostics };
|
||||
}
|
||||
@@ -314,8 +314,8 @@ class Resolver {
|
||||
}
|
||||
|
||||
private selectProfiles(
|
||||
profileIds: string[],
|
||||
presetIds: string[],
|
||||
profileIds: readonly string[],
|
||||
presetIds: readonly string[],
|
||||
profiles: Record<string, ProfileDoc>,
|
||||
presets: Record<string, string[]>,
|
||||
): ProfileDoc[] {
|
||||
@@ -567,8 +567,8 @@ function requirementParameters(
|
||||
|
||||
export function resolveProfiles(
|
||||
root: string,
|
||||
profileIds: string[],
|
||||
presetIds: string[],
|
||||
profileIds: readonly string[],
|
||||
presetIds: readonly string[],
|
||||
): ResolveResult {
|
||||
return new Resolver(root).run(profileIds, presetIds);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user