@mitre/hdf-engine 3.7.0 → 3.7.1-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +6 -6
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { EvaluatedRequirement, HDFBaseline, HDFResults, RequirementResult, Severity } from "@mitre/hdf-schema";
|
|
2
2
|
//#region src/version.d.ts
|
|
3
|
-
export declare const engineVersion = "3.7.
|
|
3
|
+
export declare const engineVersion = "3.7.1";
|
|
4
4
|
//#endregion
|
|
5
5
|
//#region src/merge.d.ts
|
|
6
6
|
/** One input to merge: a results document and the name it is recorded under. */
|
package/dist/index.js
CHANGED
|
@@ -2,7 +2,7 @@ import { impactToSeverity, validateInputSize, worstStatus } from "@mitre/hdf-uti
|
|
|
2
2
|
import { parseBaseline, parseResults } from "@mitre/hdf-parsers";
|
|
3
3
|
import { createHash } from "node:crypto";
|
|
4
4
|
//#region src/version.ts
|
|
5
|
-
const engineVersion = "3.7.
|
|
5
|
+
const engineVersion = "3.7.1";
|
|
6
6
|
//#endregion
|
|
7
7
|
//#region src/merge.ts
|
|
8
8
|
/** Provenance label keys written on every merged baseline (ADR-0016 §3). */
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/version.ts","../src/merge.ts","../src/detect.ts","../src/compliance.ts","../src/safematch.ts","../src/query.ts","../src/loader.ts","../src/evidence.ts"],"sourcesContent":["// Library version, kept on the workspace lockstep with package.json (the Go\n// peer is hdf-engine/go/engine.go Version(); index.test.ts pins both to\n// package.json). It lives in its own module so engines that stamp it into\n// documents (merge.ts) can import it without a cycle through index.ts.\nexport const engineVersion = '3.7.0';\n","// Merge engine — the TypeScript peer of hdf-engine/go/merge.go (ADR-0016).\n// Combines several results documents into one multi-baseline results document:\n// one baseline per input baseline renamed `<tool>/<original>`, per-baseline\n// provenance in labels, each input's root provenance verbatim under\n// extensions[\"hdf-merge\"]. Union semantics — nothing deduplicated, re-keyed or\n// dropped. Deterministic for the same inputs in the same order. Kept at\n// behavioural parity with Go (see test/merge.test.ts / go/merge_test.go).\n\nimport type { HDFResults, EvaluatedBaseline, Component } from '@mitre/hdf-schema';\nimport { engineVersion } from './version.js';\n\n/** One input to merge: a results document and the name it is recorded under. */\nexport interface MergeSource {\n name: string;\n doc: HDFResults;\n}\n\nexport type MergeWarningKind = 'duplicate-baseline-name' | 'label-overwritten';\n\n/** A non-fatal condition merge reports rather than silently resolving. */\nexport interface MergeWarning {\n kind: MergeWarningKind;\n /** Merged baseline name. */\n name: string;\n /** Merged baseline positions. */\n indices: number[];\n /** Set for label warnings only: the label key that was replaced or removed. */\n label?: string;\n}\n\nexport interface MergeResult {\n results: HDFResults;\n warnings: MergeWarning[];\n}\n\n/** Provenance label keys written on every merged baseline (ADR-0016 §3). */\nexport const LABEL_TOOL = 'tool';\nexport const LABEL_TOOL_VERSION = 'toolVersion';\nexport const LABEL_SOURCE_DOCUMENT = 'sourceDocument';\n\nconst MERGE_GENERATOR_NAME = 'hdf-merge';\nconst MERGE_EXTENSION_KEY = 'hdf-merge';\n\n/**\n * merge combines the sources, in order, into one results document. Returns the\n * document and any warnings (a collision or overwrite is never an error);\n * throws only when there is nothing to merge. Inputs are not mutated.\n */\nexport function merge(sources: MergeSource[]): MergeResult {\n if (sources.length === 0) {\n throw new Error('merge: no sources');\n }\n\n const baselines: EvaluatedBaseline[] = [];\n const components: Component[] = [];\n const warnings: MergeWarning[] = [];\n const seenComponent = new Set<string>();\n const provenance: Record<string, unknown>[] = [];\n const positionsByName = new Map<string, number[]>();\n let latest: HDFResults['timestamp'];\n\n sources.forEach((src, index) => {\n const prefix = toolPrefix(src.doc, index);\n const version = toolVersion(src.doc);\n\n for (const b of src.doc.baselines ?? []) {\n const name = `${prefix}/${b.name}`;\n const pos = baselines.length;\n const labels: Record<string, string> = { ...(b.labels ?? {}) };\n\n setLabel(warnings, labels, LABEL_TOOL, prefix, name, pos);\n if (version !== '') {\n setLabel(warnings, labels, LABEL_TOOL_VERSION, version, name, pos);\n } else if (LABEL_TOOL_VERSION in labels) {\n delete labels[LABEL_TOOL_VERSION];\n warnings.push({ kind: 'label-overwritten', name, indices: [pos], label: LABEL_TOOL_VERSION });\n }\n setLabel(warnings, labels, LABEL_SOURCE_DOCUMENT, src.name, name, pos);\n\n const positions = positionsByName.get(name);\n if (positions) positions.push(pos);\n else positionsByName.set(name, [pos]);\n\n baselines.push({ ...b, name, labels });\n }\n\n for (const c of src.doc.components ?? []) {\n if (c.componentId !== undefined) {\n if (seenComponent.has(c.componentId)) continue;\n seenComponent.add(c.componentId);\n }\n components.push(c);\n }\n\n if (src.doc.timestamp !== undefined && (latest === undefined || millis(src.doc.timestamp) > millis(latest))) {\n latest = src.doc.timestamp;\n }\n\n provenance.push(sourceProvenance(index, src));\n });\n\n for (const [name, positions] of positionsByName) {\n if (positions.length > 1) {\n warnings.push({ kind: 'duplicate-baseline-name', name, indices: positions });\n }\n }\n\n // Key order is fixed so the same inputs serialize identically on every run.\n const results: HDFResults = {\n baselines,\n ...(components.length > 0 ? { components } : {}),\n extensions: { [MERGE_EXTENSION_KEY]: { version: engineVersion, sources: provenance } },\n generator: { name: MERGE_GENERATOR_NAME, version: engineVersion },\n ...(latest !== undefined ? { timestamp: latest } : {}),\n };\n return { results, warnings };\n}\n\nfunction setLabel(\n warnings: MergeWarning[],\n labels: Record<string, string>,\n key: string,\n value: string,\n name: string,\n pos: number,\n): void {\n if (key in labels) {\n warnings.push({ kind: 'label-overwritten', name, indices: [pos], label: key });\n }\n labels[key] = value;\n}\n\n/** `<tool>` of a merged baseline name: tool.name → generator.name → doc<N>, lower-cased and trimmed. */\nfunction toolPrefix(doc: HDFResults, index: number): string {\n const tool = normalizeName(doc.tool?.name);\n if (tool !== '') return tool;\n const generator = normalizeName(doc.generator?.name);\n if (generator !== '') return generator;\n return `doc${index}`;\n}\n\nfunction normalizeName(s: string | undefined): string {\n return (s ?? '').trim().toLowerCase();\n}\n\n/**\n * millis reads a document timestamp for comparison. The schema type is Date,\n * but a document parsed from JSON carries the RFC 3339 string verbatim (the\n * loader does not revive dates), so both are accepted; the value itself is\n * carried through unchanged so output stays byte-faithful to the input.\n */\nfunction millis(ts: Date | string): number {\n return ts instanceof Date ? ts.getTime() : Date.parse(ts);\n}\n\nfunction toolVersion(doc: HDFResults): string {\n return (doc.tool?.version ?? '').trim();\n}\n\n/** One input's root metadata, verbatim, for extensions[\"hdf-merge\"].sources[]. */\nfunction sourceProvenance(index: number, src: MergeSource): Record<string, unknown> {\n const entry: Record<string, unknown> = { index, name: src.name };\n if (src.doc.tool !== undefined) entry.tool = src.doc.tool;\n if (src.doc.generator !== undefined) entry.generator = src.doc.generator;\n if (src.doc.timestamp !== undefined) entry.timestamp = src.doc.timestamp;\n if (src.doc.runner !== undefined) entry.runner = src.doc.runner;\n return entry;\n}\n","// Document-type detection — the TypeScript peer of hdf-engine/go/detect.go.\n// Fingerprints an HDF document by its root keys and returns the schema type\n// string. Kept at behavioural parity with the Go implementation (see\n// go/detect_test.go and src/detect.test.ts, which assert both against the same\n// bundled schema examples).\n\n/** The eight HDF document type strings, matching validators.Type* in Go. */\nexport type HdfDocType =\n | 'results'\n | 'baseline'\n | 'system'\n | 'plan'\n | 'amendments'\n | 'evidence-package'\n | 'comparison'\n | 'requirement-change-event'\n | '';\n\n/**\n * Detect fingerprints an HDF document by its root keys and returns the schema\n * type string, or '' when the input is not a JSON object or matches no known\n * HDF document type.\n */\nexport function detect(input: string): HdfDocType {\n let parsed: unknown;\n try {\n parsed = JSON.parse(input);\n } catch {\n return '';\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n return '';\n }\n const doc = parsed as Record<string, unknown>;\n const has = (...keys: string[]): boolean =>\n keys.every((k) => Object.prototype.hasOwnProperty.call(doc, k));\n\n // Most specific first. A requirement-change-event carries the singular\n // requirementId together with the state/before/after triad — a combination\n // no other HDF document type has — so it is checked ahead of the rest.\n if (has('requirementId', 'state', 'before', 'after')) return 'requirement-change-event';\n\n if (has('contents')) return 'evidence-package';\n if (has('overrides')) return 'amendments';\n if (has('assessments')) return 'plan';\n if (has('comparisonMode')) return 'comparison';\n if (has('baselines')) return 'results';\n if (has('components')) return 'system';\n if (has('requirements')) return 'baseline';\n return '';\n}\n","// Compliance & threshold engine — the TypeScript peer of\n// hdf-engine/go/compliance.go. Pure functions, kept at behavioural parity with\n// the Go implementation (see test/compliance.test.ts, which runs both over the\n// same fixture). Violation message formats match the Go fmt.Sprintf output.\n\nimport type { HDFResults, EvaluatedRequirement, RequirementResult, Severity } from '@mitre/hdf-schema';\nimport { worstStatus, impactToSeverity } from '@mitre/hdf-utilities';\n\n/** Threshold status-key constants (SAF CLI-compatible keys). */\nexport const THRESHOLD_PASSED = 'passed';\nexport const THRESHOLD_FAILED = 'failed';\nexport const THRESHOLD_SKIPPED = 'skipped';\nexport const THRESHOLD_ERROR = 'error';\nexport const THRESHOLD_NO_IMPACT = 'no_impact';\n\nexport interface SeverityCounts {\n critical: number;\n high: number;\n medium: number;\n low: number;\n /** The schema's fifth severity; also absorbs a severity that cannot be derived or is not in the enum. */\n informational: number;\n total: number;\n}\n\nexport interface StatusCounts {\n passed: SeverityCounts;\n failed: SeverityCounts;\n skipped: SeverityCounts;\n error: SeverityCounts;\n noImpact: SeverityCounts;\n}\n\nexport interface ControlIDMapping {\n id: string;\n status: string;\n severity: string;\n}\n\nexport interface ThresholdBound {\n min?: number;\n max?: number;\n controls?: string[];\n}\n\nexport interface ThresholdSeverity {\n critical?: ThresholdBound;\n high?: ThresholdBound;\n medium?: ThresholdBound;\n low?: ThresholdBound;\n informational?: ThresholdBound;\n /** Pre-3.7 spelling of `informational`, normalized on read and never written. */\n none?: ThresholdBound;\n total?: ThresholdBound;\n}\n\nexport interface ComplianceBound {\n min?: number;\n max?: number;\n}\n\nexport interface ThresholdConfig {\n compliance?: ComplianceBound;\n passed?: ThresholdSeverity;\n failed?: ThresholdSeverity;\n skipped?: ThresholdSeverity;\n error?: ThresholdSeverity;\n noImpact?: ThresholdSeverity;\n}\n\nfunction newSeverityCounts(): SeverityCounts {\n return { critical: 0, high: 0, medium: 0, low: 0, informational: 0, total: 0 };\n}\n\nfunction newStatusCounts(): StatusCounts {\n return {\n passed: newSeverityCounts(),\n failed: newSeverityCounts(),\n skipped: newSeverityCounts(),\n error: newSeverityCounts(),\n noImpact: newSeverityCounts(),\n };\n}\n\n/**\n * overallStatus is the canonical worst-wins roll-up of a requirement's result\n * statuses, delegated to @mitre/hdf-utilities worstStatus (error > failed >\n * passed > notApplicable > notReviewed; empty → notReviewed). No local rank\n * switch — the TS peer of the Go overallStatus dedup (supersedes hdf-libs-ixhx).\n */\nexport function overallStatus(results: RequirementResult[]): string {\n return worstStatus(results.map((r) => String(r.status)));\n}\n\n/**\n * deriveSeverity determines the severity string from impact and optional explicit\n * severity, using impactToSeverity. Both paths yield a value from the schema's\n * severity enum: an explicit informational and an impact-derived one are the same\n * thing and must not land in different buckets.\n */\nexport function deriveSeverity(impact: number, severity?: Severity | null): string {\n // Presence-based, matching Go DeriveSeverity's `if severity != nil`: an explicit\n // severity — including an empty string — is returned verbatim; only a\n // null/undefined severity derives from impact. Testing truthiness here would\n // send \"\" through the impact path and diverge from Go (bead 4908.20).\n if (severity != null) {\n return String(severity);\n }\n return impactToSeverity(impact);\n}\n\nfunction statusBucket(counts: StatusCounts, status: string): SeverityCounts {\n switch (status) {\n case 'passed':\n return counts.passed;\n case 'failed':\n return counts.failed;\n case 'error':\n return counts.error;\n case 'notApplicable':\n return counts.noImpact;\n case 'notReviewed':\n return counts.skipped;\n default:\n return counts.skipped;\n }\n}\n\nfunction addCount(counts: StatusCounts, status: string, severity: string): void {\n const sc = statusBucket(counts, status);\n sc.total++;\n switch (severity) {\n case 'critical':\n sc.critical++;\n break;\n case 'high':\n sc.high++;\n break;\n case 'medium':\n sc.medium++;\n break;\n case 'low':\n sc.low++;\n break;\n default:\n // Informational plus anything outside the enum: an unrecognized severity\n // is counted, never dropped, so a malformed document still gates.\n sc.informational++;\n }\n}\n\nfunction statusToThresholdKey(status: string): string {\n switch (status) {\n case 'passed':\n return THRESHOLD_PASSED;\n case 'failed':\n return THRESHOLD_FAILED;\n case 'notReviewed':\n return THRESHOLD_SKIPPED;\n case 'error':\n return THRESHOLD_ERROR;\n case 'notApplicable':\n return THRESHOLD_NO_IMPACT;\n default:\n return THRESHOLD_SKIPPED;\n }\n}\n\n/** CountControlsByStatusSeverity counts requirements by overall status and severity. */\nexport function countControlsByStatusSeverity(results: HDFResults): StatusCounts {\n const counts = newStatusCounts();\n for (const baseline of results.baselines ?? []) {\n for (const req of baseline.requirements ?? []) {\n addCount(counts, overallStatus(req.results ?? []), deriveSeverity(req.impact, reqSeverity(req)));\n }\n }\n return counts;\n}\n\n/**\n * countControlsByStatus counts requirements by a caller-resolved status — the\n * injected-resolver twin of countControlsByStatusSeverity (which counts raw\n * result statuses with no override awareness). statusOf returns each\n * requirement's status in the schema vocabulary (passed/failed/notApplicable/\n * notReviewed/error); an empty or unrecognized value counts as skipped, and an\n * absent resolver yields all-skipped. Callers build effective-status rollups\n * (e.g. compliance with and without agent-attributed overrides) without the\n * engine binding to any one status convention. Parity: go/compliance.go.\n */\nexport function countControlsByStatus(\n results: HDFResults,\n statusOf?: (req: EvaluatedRequirement) => string,\n): StatusCounts {\n const counts = newStatusCounts();\n for (const baseline of results.baselines ?? []) {\n for (const req of baseline.requirements ?? []) {\n const status = statusOf ? statusOf(req) : '';\n addCount(counts, status, deriveSeverity(req.impact, reqSeverity(req)));\n }\n }\n return counts;\n}\n\n/**\n * agentOverrideCount counts the status overrides across a result set whose\n * applied-by identity type is \"agent\" — the detective count. Deterministic\n * from_vex/system overrides are excluded so the count is a meaningful AI-scrutiny\n * signal. Parity: go/compliance.go AgentOverrideCount.\n */\nexport function agentOverrideCount(results: HDFResults): number {\n let count = 0;\n for (const baseline of results.baselines ?? []) {\n for (const req of baseline.requirements ?? []) {\n for (const o of req.statusOverrides ?? []) {\n if (o.appliedBy?.type === 'agent') {\n count++;\n }\n }\n }\n }\n return count;\n}\n\n/** MapControlIDs builds control ID → status/severity mappings from a result set. */\nexport function mapControlIDs(results: HDFResults): ControlIDMapping[] {\n const mappings: ControlIDMapping[] = [];\n for (const baseline of results.baselines ?? []) {\n for (const req of baseline.requirements ?? []) {\n const status = overallStatus(req.results ?? []);\n mappings.push({\n id: req.id,\n status: statusToThresholdKey(status),\n severity: deriveSeverity(req.impact, reqSeverity(req)),\n });\n }\n }\n return mappings;\n}\n\n/**\n * mapControlIDsByStatus builds control ID → status/severity mappings using a\n * caller-resolved status — the injected-resolver twin of mapControlIDs (which\n * maps raw result statuses). statusOf returns each requirement's status in the\n * schema vocabulary; an empty or unrecognized value maps to skipped, and an\n * absent resolver yields all-skipped. Callers build effective-status control\n * listings (the same injection pattern as countControlsByStatus). Parity:\n * go/compliance.go MapControlIDsByStatus.\n */\nexport function mapControlIDsByStatus(\n results: HDFResults,\n statusOf?: (req: EvaluatedRequirement) => string,\n): ControlIDMapping[] {\n const mappings: ControlIDMapping[] = [];\n for (const baseline of results.baselines ?? []) {\n for (const req of baseline.requirements ?? []) {\n const status = statusOf ? statusOf(req) : '';\n mappings.push({\n id: req.id,\n status: statusToThresholdKey(status),\n severity: deriveSeverity(req.impact, reqSeverity(req)),\n });\n }\n }\n return mappings;\n}\n\nfunction reqSeverity(req: EvaluatedRequirement): Severity | null {\n return (req.severity ?? null) as Severity | null;\n}\n\n/**\n * calculateCompliance returns the compliance percentage rounded to two decimals:\n * passed / (passed + failed + skipped + error) * 100; notApplicable excluded.\n */\nexport function calculateCompliance(counts: StatusCounts): number {\n const relevant = counts.passed.total + counts.failed.total + counts.skipped.total + counts.error.total;\n if (relevant === 0) {\n return 0;\n }\n const pct = (counts.passed.total / relevant) * 100;\n return Math.round(pct * 100) / 100;\n}\n\n/**\n * normalizeLegacySeverity folds the pre-3.7 `none` key into `informational`. A\n * spec setting both is refused rather than resolved: the two name one bucket, so\n * silently honouring one would drop a bound the author wrote.\n */\nfunction normalizeLegacySeverity(config: ThresholdConfig): string[] {\n const violations: string[] = [];\n const sections: [string, ThresholdSeverity | undefined][] = [\n [THRESHOLD_PASSED, config.passed],\n [THRESHOLD_FAILED, config.failed],\n [THRESHOLD_SKIPPED, config.skipped],\n [THRESHOLD_ERROR, config.error],\n [THRESHOLD_NO_IMPACT, config.noImpact],\n ];\n for (const [name, ts] of sections) {\n if (!ts?.none) continue;\n if (ts.informational) {\n violations.push(\n `${name}: both 'none' and 'informational' are set; 'none' is the pre-3.7 spelling of the same bucket`,\n );\n continue;\n }\n ts.informational = ts.none;\n delete ts.none;\n }\n return violations;\n}\n\n/**\n * validateThresholds checks all threshold bounds against observed counts and\n * compliance, returning human-readable violation messages (empty when all pass).\n */\nexport function validateThresholds(\n config: ThresholdConfig,\n counts: StatusCounts,\n compliance: number,\n controlMap: ControlIDMapping[],\n): string[] {\n const violations: string[] = [];\n\n // Every construction path lands here, so the legacy spelling is resolved once\n // rather than in each caller.\n violations.push(...normalizeLegacySeverity(config));\n\n const actualControls = new Map<string, ControlIDMapping>();\n for (const m of controlMap) {\n actualControls.set(m.id, m);\n }\n\n if (config.compliance) {\n if (config.compliance.min !== undefined && compliance < config.compliance.min) {\n violations.push(`compliance ${compliance.toFixed(2)}% is below minimum ${config.compliance.min.toFixed(2)}%`);\n }\n if (config.compliance.max !== undefined && compliance > config.compliance.max) {\n violations.push(`compliance ${compliance.toFixed(2)}% exceeds maximum ${config.compliance.max.toFixed(2)}%`);\n }\n }\n\n violations.push(...checkSeverityThreshold(THRESHOLD_PASSED, config.passed, counts.passed, actualControls));\n violations.push(...checkSeverityThreshold(THRESHOLD_FAILED, config.failed, counts.failed, actualControls));\n violations.push(...checkSeverityThreshold(THRESHOLD_SKIPPED, config.skipped, counts.skipped, actualControls));\n violations.push(...checkSeverityThreshold(THRESHOLD_ERROR, config.error, counts.error, actualControls));\n violations.push(...checkSeverityThreshold(THRESHOLD_NO_IMPACT, config.noImpact, counts.noImpact, actualControls));\n\n return violations;\n}\n\nfunction checkSeverityThreshold(\n status: string,\n threshold: ThresholdSeverity | undefined,\n actual: SeverityCounts,\n actualControls: Map<string, ControlIDMapping>,\n): string[] {\n if (!threshold) {\n return [];\n }\n const violations: string[] = [];\n const check = (label: string, bound: ThresholdBound | undefined, actualCount: number): void => {\n if (!bound) {\n return;\n }\n const path = `${status}.${label}`;\n if (bound.min !== undefined && actualCount < bound.min) {\n violations.push(`${path}: ${actualCount} is below minimum ${bound.min}`);\n }\n if (bound.max !== undefined && actualCount > bound.max) {\n violations.push(`${path}: ${actualCount} exceeds maximum ${bound.max}`);\n }\n for (const expectedID of bound.controls ?? []) {\n const ac = actualControls.get(expectedID);\n if (!ac) {\n violations.push(`${path}: expected control ${expectedID} not found in results`);\n } else if (ac.status !== status || ac.severity !== label) {\n violations.push(\n `${path}: control ${expectedID} expected ${status}/${label} but found ${ac.status}/${ac.severity}`,\n );\n }\n }\n };\n\n check('critical', threshold.critical, actual.critical);\n check('high', threshold.high, actual.high);\n check('medium', threshold.medium, actual.medium);\n check('low', threshold.low, actual.low);\n check('informational', threshold.informational, actual.informational);\n check('total', threshold.total, actual.total);\n\n return violations;\n}\n","// Glob matching — the TypeScript peer of hdf-engine/go/safematch.go. Kept at\n// behavioural parity with the Go matcher.\n\nconst MAX_PATTERN_LENGTH = 256;\n\nconst REGEX_SPECIAL = new Set(['.', '+', '^', '$', '(', ')', '[', ']', '{', '}', '|', '\\\\']);\n\n/**\n * globToRegex converts a glob pattern (with * and ? wildcards) to an anchored\n * regular expression, escaping every other regex metacharacter exactly once. A\n * single pass avoids re-escaping the backslash introduced by escaping an earlier\n * metacharacter (the doubled-backslash defect that made any dotted pattern match\n * nothing).\n */\nexport function globToRegex(glob: string): string {\n let result = '^';\n for (const ch of glob) {\n if (ch === '*') {\n result += '.*';\n } else if (ch === '?') {\n result += '.';\n } else if (REGEX_SPECIAL.has(ch)) {\n result += '\\\\' + ch;\n } else {\n result += ch;\n }\n }\n return result + '$';\n}\n\n/**\n * safeGlobMatch converts a glob pattern to a regex and matches case-insensitively.\n * Returns false for over-length or invalid patterns (fail-safe), mirroring the\n * Go matcher's length cap and error handling.\n */\nconst byteEncoder = new TextEncoder();\n\n/** byteLength returns the UTF-8 byte length, matching Go's len(string). */\nfunction byteLength(s: string): number {\n return byteEncoder.encode(s).length;\n}\n\nexport function safeGlobMatch(s: string, pattern: string): boolean {\n // Cap on UTF-8 byte length (matching Go's len(pattern)), and — like Go's\n // compileSafeRegex — re-cap the EXPANDED regex, so an over-length glob or a\n // small glob that expands past the limit is rejected identically in both\n // languages (not just capped on the raw glob's UTF-16 length).\n if (byteLength(pattern) > MAX_PATTERN_LENGTH) {\n return false;\n }\n const rx = globToRegex(pattern);\n if (byteLength(rx) > MAX_PATTERN_LENGTH) {\n return false;\n }\n let re: RegExp;\n try {\n re = new RegExp(rx, 'i');\n } catch {\n return false;\n }\n return re.test(s);\n}\n","// Requirements query engine — the TypeScript peer of hdf-engine/go/filter.go.\n// A pure filter(results, options) with no shared mutable state, kept at\n// behavioural parity with the Go implementation (see test/query.test.ts, which\n// runs both over the same fixture).\n\nimport type { HDFResults, EvaluatedRequirement } from '@mitre/hdf-schema';\nimport { deriveSeverity } from './compliance.js';\nimport { safeGlobMatch } from './safematch.js';\n\n/**\n * FilterOptions configures a requirements query. Every filter input arrives here;\n * distinct filters combine with AND, repeated values within a filter with OR.\n * statusOf resolves a requirement's display status, injected so the engine stays\n * agnostic to the caller's status-string convention (undefined → empty status).\n */\nexport interface FilterOptions {\n status?: string[];\n severity?: string[];\n impact?: string;\n cci?: string[];\n nist?: string[];\n id?: string;\n tag?: string[];\n search?: string;\n baseline?: string;\n limit?: number;\n count?: boolean;\n statusOf?: (control: EvaluatedRequirement) => string;\n}\n\n/**\n * A single query result row. baselineIndex and index are the match's position in\n * the result set (results.baselines[baselineIndex].requirements[index]) and are\n * the only unique identity a match has: baseline names repeat in shipped\n * converter output and requirement ids repeat within a baseline, so (baseline,\n * id) is not a key. Address the source requirement by position, never by name.\n */\nexport interface Match {\n id: string;\n title: string;\n status: string;\n impact: number;\n severity: string;\n baseline: string;\n baselineIndex: number;\n index: number;\n}\n\ntype FilterFunc = (control: EvaluatedRequirement, status: string, severity: string) => boolean;\n\n/**\n * filter returns the requirements across the result set's baselines that satisfy\n * options. Applies to requirement collections (results/baseline documents); the\n * calling adapter rejects document types that carry no requirements.\n */\nexport function filter(results: HDFResults, options: FilterOptions): Match[] {\n const filters = buildFilters(options);\n const matches: Match[] = [];\n\n for (const [baselineIndex, baseline] of (results.baselines ?? []).entries()) {\n if (options.baseline && !matchesGlob(baseline.name, options.baseline)) {\n continue;\n }\n for (const [index, control] of (baseline.requirements ?? []).entries()) {\n if (options.limit && options.limit > 0 && matches.length >= options.limit && !options.count) {\n return matches;\n }\n\n const status = options.statusOf ? options.statusOf(control) : '';\n // Explicit STIG severity wins; impact-derived only as a fallback — the\n // canonical rule shared with the compliance counts (deriveSeverity), so\n // query rows and compliance never disagree on a requirement's severity.\n const severity = deriveSeverity(control.impact, control.severity ?? null);\n\n if (!applyFilters(control, status, severity, filters)) {\n continue;\n }\n\n matches.push({\n id: control.id,\n title: control.title ?? '',\n status,\n impact: control.impact,\n severity,\n baseline: baseline.name,\n baselineIndex,\n index,\n });\n }\n }\n return matches;\n}\n\nfunction buildFilters(options: FilterOptions): FilterFunc[] {\n const filters: FilterFunc[] = [];\n\n if (options.status && options.status.length > 0) {\n const statuses = options.status.map((s) => s.toLowerCase());\n filters.push((_c, s) => statuses.includes(s.toLowerCase()));\n }\n\n if (options.severity && options.severity.length > 0) {\n const severities = options.severity.map((s) => s.toLowerCase());\n filters.push((_c, _s, severity) => severities.includes(severity));\n }\n\n if (options.impact) {\n const [op, val] = parseImpactFilter(options.impact);\n filters.push((c) => compareImpact(c.impact, op, val));\n }\n\n if (options.cci && options.cci.length > 0) {\n const ccis = options.cci.map((c) => c.toUpperCase());\n filters.push((c) => ccis.some((cci) => tagContains(c.tags, 'cci', cci)));\n }\n\n if (options.nist && options.nist.length > 0) {\n const nist = options.nist;\n filters.push((c) => nist.some((n) => tagMatchesGlob(c.tags, 'nist', n)));\n }\n\n if (options.id) {\n const id = options.id;\n filters.push(\n (c) =>\n tagContains(c.tags, 'stig_id', id) ||\n tagContains(c.tags, 'gid', id) ||\n tagContains(c.tags, 'gtitle', id) ||\n c.id === id,\n );\n }\n\n if (options.tag && options.tag.length > 0) {\n const tagFilters: { key: string; value: string }[] = [];\n for (const t of options.tag) {\n const idx = t.indexOf(':');\n if (idx >= 0) {\n tagFilters.push({ key: t.slice(0, idx), value: t.slice(idx + 1) });\n }\n }\n if (tagFilters.length > 0) {\n filters.push((c) => tagFilters.some((tf) => tagMatchesGlob(c.tags, tf.key, tf.value)));\n }\n }\n\n if (options.search) {\n const search = options.search.toLowerCase();\n filters.push((c) => {\n if (c.id.toLowerCase().includes(search)) return true;\n if (c.title && c.title.toLowerCase().includes(search)) return true;\n for (const desc of c.descriptions ?? []) {\n if (desc.data.toLowerCase().includes(search)) return true;\n }\n return false;\n });\n }\n\n return filters;\n}\n\nfunction applyFilters(\n control: EvaluatedRequirement,\n status: string,\n severity: string,\n filters: FilterFunc[],\n): boolean {\n return filters.every((f) => f(control, status, severity));\n}\n\n// DECIMAL_FLOAT is the shared impact-filter operand grammar — a plain decimal:\n// optional sign, digits with an optional fraction (or a leading-dot fraction),\n// optional decimal exponent. It excludes the forms JS Number() accepts but that\n// make no sense as a 0.0–1.0 threshold and diverge from Go strconv.ParseFloat:\n// hex/binary/octal integers (0x1f→31, 0b101→5, 0o17→15) and Infinity. The Go\n// engine applies the identical pattern so a filter is accepted or rejected the\n// same in both languages (bead 4908.15).\nconst DECIMAL_FLOAT = /^[+-]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][+-]?\\d+)?$/;\n\n// parseDecimal parses a plain-decimal operand, returning null for anything\n// outside the shared grammar (including overflow to Infinity, e.g. '1e400', so\n// Go's ParseFloat ErrRange rejection is mirrored).\nfunction parseDecimal(s: string): number | null {\n if (!DECIMAL_FLOAT.test(s)) return null;\n const v = Number(s);\n return Number.isFinite(v) ? v : null;\n}\n\n// An invalid operand safe-degrades to ('=', NaN), which compareImpact treats as\n// matching NOTHING — mirroring the Go engine's `return ok && compareImpact(...)`.\n// It must never coerce to ('=', 0), which silently returns confidently-wrong\n// impact==0 rows for a typo'd or garbage filter.\nexport function parseImpactFilter(f: string): [string, number] {\n const trimmed = f.trim();\n for (const op of ['>=', '<=', '>', '<', '=']) {\n if (trimmed.startsWith(op)) {\n const v = parseDecimal(trimmed.slice(op.length).trim());\n return v === null ? ['=', NaN] : [op, v];\n }\n }\n const v = parseDecimal(trimmed);\n return v === null ? ['=', NaN] : ['=', v];\n}\n\nexport function compareImpact(impact: number, op: string, val: number): boolean {\n switch (op) {\n case '>':\n return impact > val;\n case '>=':\n return impact >= val;\n case '<':\n return impact < val;\n case '<=':\n return impact <= val;\n case '=':\n return impact === val;\n default:\n return false;\n }\n}\n\nexport function tagContains(tags: Record<string, unknown>, key: string, value: string): boolean {\n const tagVal = tags?.[key];\n if (tagVal === undefined) {\n return false;\n }\n const want = value.toLowerCase();\n if (typeof tagVal === 'string') {\n return tagVal.toLowerCase() === want;\n }\n if (Array.isArray(tagVal)) {\n return tagVal.some((item) => typeof item === 'string' && item.toLowerCase() === want);\n }\n return false;\n}\n\nexport function tagMatchesGlob(tags: Record<string, unknown>, key: string, pattern: string): boolean {\n const tagVal = tags?.[key];\n if (tagVal === undefined) {\n return false;\n }\n if (typeof tagVal === 'string') {\n return safeGlobMatch(tagVal, pattern);\n }\n if (Array.isArray(tagVal)) {\n return tagVal.some((item) => typeof item === 'string' && safeGlobMatch(item, pattern));\n }\n return false;\n}\n\n/** matchesGlob reports whether s matches the glob pattern (case-insensitive). */\nexport function matchesGlob(s: string, pattern: string): boolean {\n return safeGlobMatch(s, pattern);\n}\n","// Document loader engine core — the TypeScript peer of hdf-engine/go/loader.go,\n// kept at behavioural parity (see loader.test.ts + the Go parity test, which\n// run both over the same fixtures). Pure and schema-typed: size-guard first,\n// wire-format + document-type detection, then the canonical parse for the\n// results/baseline types. No cache, no degraded envelope — those are MCP\n// concerns layered on top in hdf-cli/internal/mcp/loader.\n\nimport type { HDFResults, HDFBaseline } from '@mitre/hdf-schema';\nimport { validateInputSize } from '@mitre/hdf-utilities';\nimport { parseResults, parseBaseline } from '@mitre/hdf-parsers';\nimport { detect, type HdfDocType } from './detect.js';\n\n/** Wire encoding of loader input (parity with Go InputFormat). */\nexport type InputFormat = 'json' | 'ndjson';\n\nexport interface LoadResult {\n format: InputFormat;\n docType: HdfDocType;\n results?: HDFResults;\n baseline?: HDFBaseline;\n /** Non-empty when detected as results/baseline but the parse/validate failed. */\n parseError?: string;\n valid: boolean;\n}\n\n/**\n * load is the schema-typed loader core. In order: validateInputSize (FIRST,\n * before any parse; maxSize <= 0 uses the default), wire-format detection\n * (JSON vs NDJSON), document-type detection (detect), then the canonical\n * hdf-parsers parse for the results and baseline types. Other types are\n * detected but not parsed here.\n */\nexport function load(input: string | Uint8Array, maxSize = 0): LoadResult {\n validateInputSize(input, maxSize); // first op — throws on oversize\n\n const text = typeof input === 'string' ? input : new TextDecoder().decode(input);\n const result: LoadResult = {\n format: detectFormat(text),\n docType: detect(text),\n valid: false,\n };\n\n if (result.docType === 'results') {\n const r = parseResults(text);\n if (r.success && r.data) {\n result.results = r.data;\n result.valid = true;\n } else {\n result.parseError = r.error;\n }\n } else if (result.docType === 'baseline') {\n const r = parseBaseline(text);\n if (r.success && r.data) {\n result.baseline = r.data;\n result.valid = true;\n } else {\n result.parseError = r.error;\n }\n }\n\n return result;\n}\n\n/**\n * detectFormat classifies input as a single JSON document or newline-delimited\n * JSON, consistent with the Go core: NDJSON is two or more non-blank lines that\n * each independently parse as a complete JSON value. A pretty-printed single\n * object stays 'json' (its first line is not itself a complete JSON value).\n */\nexport function detectFormat(text: string): InputFormat {\n const lines = text.split('\\n').filter((l) => l.trim() !== '');\n const [first, second] = lines;\n if (first === undefined || second === undefined) {\n return 'json';\n }\n if (isCompleteJSON(first) && isCompleteJSON(second)) {\n return 'ndjson';\n }\n return 'json';\n}\n\n// isCompleteJSON reports whether s is a single complete JSON value with no\n// trailing content — the per-line test the NDJSON classifier applies. JSON.parse\n// already rejects trailing garbage, so a successful parse is sufficient.\nfunction isCompleteJSON(s: string): boolean {\n try {\n JSON.parse(s);\n return true;\n } catch {\n return false;\n }\n}\n","// Evidence-verify engine — the TypeScript peer of hdf-engine/go/evidence.go.\n// Pure, filesystem-agnostic core of `hdf evidence verify` (ADR-0007 §11):\n// content-checksum classification and plan/results completeness. All filesystem\n// IO and path confinement stay in the caller, injected as a FetchFn. Kept at\n// behavioural parity with the Go implementation (see test/evidence.test.ts,\n// which runs both over the same fixtures).\n\nimport { createHash } from 'node:crypto';\nimport { agentOverrideCount } from './compliance.js';\nimport type { HDFResults } from '@mitre/hdf-schema';\n\n/** Classifies a single content entry's checksum verification. */\nexport type ChecksumStatus = 'match' | 'mismatch' | 'skipped' | 'error';\n\n/** One content entry of an evidence package: a referenced document and its\n * recorded checksum ('' when the entry carries none). */\nexport interface EvidenceContent {\n uri: string;\n type: string;\n checksum: string;\n}\n\n/** The verification outcome for one content entry. */\nexport interface ChecksumResult {\n uri: string;\n type: string;\n status: ChecksumStatus;\n expected?: string;\n actual?: string;\n error?: string;\n}\n\n/** Reports which planned baselines are covered by results. */\nexport interface CompletenessResult {\n planned: string[];\n covered: string[];\n missing: string[];\n complete: boolean;\n}\n\n/** Resolves a content URI to its bytes. The caller owns path confinement\n * (HDF_MCP_ROOT for the MCP, the package directory for the CLI). Throws when the\n * uri cannot be read. */\nexport type FetchFn = (uri: string) => Uint8Array;\n\ntype RawObject = Record<string, unknown>;\n\n/** Go decodes into a typed struct, so a JSON `null` document leaves zero values\n * while a wrong-typed one is a decode error. These three helpers give the TS\n * peer the same split instead of asserting a shape onto untrusted input. */\nfunction parseDocument(text: string, what: string): RawObject {\n const doc: unknown = JSON.parse(text);\n if (doc === null) return {};\n if (typeof doc !== 'object' || Array.isArray(doc)) {\n throw new Error(`parse ${what}: cannot unmarshal ${describe(doc)} into an object`);\n }\n return doc as RawObject;\n}\n\nfunction objectArray(value: unknown, what: string, field: string): RawObject[] {\n if (value === undefined || value === null) return [];\n if (!Array.isArray(value)) {\n throw new Error(`parse ${what}: cannot unmarshal ${describe(value)} into ${field}`);\n }\n return value.map((entry: unknown) => {\n if (entry === null) return {};\n if (typeof entry !== 'object' || Array.isArray(entry)) {\n throw new Error(`parse ${what}: cannot unmarshal ${describe(entry)} into a ${field} entry`);\n }\n return entry as RawObject;\n });\n}\n\nfunction str(value: unknown): string {\n return typeof value === 'string' ? value : '';\n}\n\nfunction describe(value: unknown): string {\n return Array.isArray(value) ? 'array' : value === null ? 'null' : typeof value;\n}\n\n/** Extracts the planRef and content entries from an evidence-package document. */\nexport function parseEvidencePackage(pkg: string): { planRef: string; contents: EvidenceContent[] } {\n const doc = parseDocument(pkg, 'evidence package');\n const contents: EvidenceContent[] = objectArray(doc.contents, 'evidence package', 'contents').map((c) => {\n const checksum = c.checksum;\n return {\n uri: str(c.uri),\n type: str(c.type),\n checksum: typeof checksum === 'object' && checksum !== null ? str((checksum as RawObject).value) : '',\n };\n });\n return { planRef: str(doc.planRef), contents };\n}\n\n/** Verifies each content entry's sha256 against fetch(uri), preserving entry\n * order. No checksum → skipped; a fetch throw → error; hash mismatch → mismatch\n * (carrying expected+actual). */\nexport function verifyChecksums(contents: EvidenceContent[], fetch: FetchFn): ChecksumResult[] {\n return contents.map((c) => {\n const r: ChecksumResult = { uri: c.uri, type: c.type, status: 'skipped' };\n if (c.checksum === '') {\n return r;\n }\n let data: Uint8Array;\n try {\n data = fetch(c.uri);\n } catch (e) {\n return { ...r, status: 'error', error: e instanceof Error ? e.message : String(e) };\n }\n const actual = sha256Hex(data);\n if (actual === c.checksum) {\n return { ...r, status: 'match' };\n }\n return { ...r, status: 'mismatch', expected: c.checksum, actual };\n });\n}\n\n/** Extracts assessment baselineRefs from a plan document, deduped in first-seen\n * order. */\nexport function plannedBaselineRefs(plan: string): string[] {\n const doc = parseDocument(plan, 'plan');\n const refs = objectArray(doc.assessments, 'plan', 'assessments')\n .map((a) => str(a.baselineRef))\n .filter((s) => s !== '');\n return dedupe(refs);\n}\n\n/** Extracts baseline names from a results document, deduped in first-seen order. */\nexport function coveredBaselineNames(results: string): string[] {\n const doc = parseDocument(results, 'results');\n const names = objectArray(doc.baselines, 'results', 'baselines')\n .map((b) => str(b.name))\n .filter((s) => s !== '');\n return dedupe(names);\n}\n\n/** Concatenates the covered baseline names of every hdf-results document the\n * package references, in entry order. An entry that cannot be fetched or parsed\n * is skipped: checksum verification is what reports a read failure, and a\n * partial coverage list is what the completeness diff needs. */\nexport function coveredBaselinesInPackage(contents: EvidenceContent[], fetch: FetchFn): string[] {\n const covered: string[] = [];\n forEachResultsDocument(contents, fetch, (text) => {\n try {\n covered.push(...coveredBaselineNames(text));\n } catch {\n return;\n }\n });\n return covered;\n}\n\n/** Sums the agent-attributed override count across every hdf-results document\n * the package references. Unreadable or unparseable entries are skipped. */\nexport function agentOverridesInPackage(contents: EvidenceContent[], fetch: FetchFn): number {\n let total = 0;\n forEachResultsDocument(contents, fetch, (text) => {\n try {\n total += agentOverrideCount(JSON.parse(text) as HDFResults);\n } catch {\n return;\n }\n });\n return total;\n}\n\n/** Fetches each referenced hdf-results document in entry order, skipping\n * entries that carry no uri or cannot be read. */\nfunction forEachResultsDocument(\n contents: EvidenceContent[],\n fetch: FetchFn,\n visit: (text: string) => void\n): void {\n for (const c of contents) {\n if (c.type !== 'hdf-results' || c.uri === '') {\n continue;\n }\n let data: Uint8Array;\n try {\n data = fetch(c.uri);\n } catch {\n continue;\n }\n visit(new TextDecoder().decode(data));\n }\n}\n\n/** Diffs planned baseline refs against covered baseline names. A planned ref is\n * covered when some results baseline shares its name. Missing is sorted so the\n * outcome is deterministic across languages and runs. */\nexport function completeness(planned: string[], covered: string[]): CompletenessResult {\n const coveredSet = new Set(covered);\n const missing = planned.filter((p) => !coveredSet.has(p)).sort();\n return { planned, covered, missing, complete: missing.length === 0 };\n}\n\nfunction sha256Hex(data: Uint8Array): string {\n return createHash('sha256').update(data).digest('hex');\n}\n\nfunction dedupe(input: string[]): string[] {\n const seen = new Set<string>();\n const out: string[] = [];\n for (const s of input) {\n if (!seen.has(s)) {\n seen.add(s);\n out.push(s);\n }\n }\n return out;\n}\n"],"mappings":";;;;AAIA,MAAa,gBAAgB;;;;ACgC7B,MAAa,aAAa;AAC1B,MAAa,qBAAqB;AAClC,MAAa,wBAAwB;AAErC,MAAM,uBAAuB;AAC7B,MAAM,sBAAsB;;;;;;AAO5B,SAAgB,MAAM,SAAqC;CACzD,IAAI,QAAQ,WAAW,GACrB,MAAM,IAAI,MAAM,mBAAmB;CAGrC,MAAM,YAAiC,CAAC;CACxC,MAAM,aAA0B,CAAC;CACjC,MAAM,WAA2B,CAAC;CAClC,MAAM,gCAAgB,IAAI,IAAY;CACtC,MAAM,aAAwC,CAAC;CAC/C,MAAM,kCAAkB,IAAI,IAAsB;CAClD,IAAI;CAEJ,QAAQ,SAAS,KAAK,UAAU;EAC9B,MAAM,SAAS,WAAW,IAAI,KAAK,KAAK;EACxC,MAAM,UAAU,YAAY,IAAI,GAAG;EAEnC,KAAK,MAAM,KAAK,IAAI,IAAI,aAAa,CAAC,GAAG;GACvC,MAAM,OAAO,GAAG,OAAO,GAAG,EAAE;GAC5B,MAAM,MAAM,UAAU;GACtB,MAAM,SAAiC,EAAE,GAAI,EAAE,UAAU,CAAC,EAAG;GAE7D,SAAS,UAAU,QAAQ,YAAY,QAAQ,MAAM,GAAG;GACxD,IAAI,YAAY,IACd,SAAS,UAAU,QAAQ,oBAAoB,SAAS,MAAM,GAAG;QAC5D,IAAA,iBAA0B,QAAQ;IACvC,OAAO,OA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,OAAO;EAAE;EAAS;EAAS;EAAS,UAAU,QAAQ,WAAW;CAAE;AACrE;AAEA,SAAS,UAAU,MAA0B;CAC3C,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,OAAO,KAAK;AACvD;AAEA,SAAS,OAAO,OAA2B;CACzC,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,MAAgB,CAAC;CACvB,KAAK,MAAM,KAAK,OACd,IAAI,CAAC,KAAK,IAAI,CAAC,GAAG;EAChB,KAAK,IAAI,CAAC;EACV,IAAI,KAAK,CAAC;CACZ;CAEF,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/version.ts","../src/merge.ts","../src/detect.ts","../src/compliance.ts","../src/safematch.ts","../src/query.ts","../src/loader.ts","../src/evidence.ts"],"sourcesContent":["// Library version, kept on the workspace lockstep with package.json (the Go\n// peer is hdf-engine/go/engine.go Version(); index.test.ts pins both to\n// package.json). It lives in its own module so engines that stamp it into\n// documents (merge.ts) can import it without a cycle through index.ts.\nexport const engineVersion = '3.7.1';\n","// Merge engine — the TypeScript peer of hdf-engine/go/merge.go (ADR-0016).\n// Combines several results documents into one multi-baseline results document:\n// one baseline per input baseline renamed `<tool>/<original>`, per-baseline\n// provenance in labels, each input's root provenance verbatim under\n// extensions[\"hdf-merge\"]. Union semantics — nothing deduplicated, re-keyed or\n// dropped. Deterministic for the same inputs in the same order. Kept at\n// behavioural parity with Go (see test/merge.test.ts / go/merge_test.go).\n\nimport type { HDFResults, EvaluatedBaseline, Component } from '@mitre/hdf-schema';\nimport { engineVersion } from './version.js';\n\n/** One input to merge: a results document and the name it is recorded under. */\nexport interface MergeSource {\n name: string;\n doc: HDFResults;\n}\n\nexport type MergeWarningKind = 'duplicate-baseline-name' | 'label-overwritten';\n\n/** A non-fatal condition merge reports rather than silently resolving. */\nexport interface MergeWarning {\n kind: MergeWarningKind;\n /** Merged baseline name. */\n name: string;\n /** Merged baseline positions. */\n indices: number[];\n /** Set for label warnings only: the label key that was replaced or removed. */\n label?: string;\n}\n\nexport interface MergeResult {\n results: HDFResults;\n warnings: MergeWarning[];\n}\n\n/** Provenance label keys written on every merged baseline (ADR-0016 §3). */\nexport const LABEL_TOOL = 'tool';\nexport const LABEL_TOOL_VERSION = 'toolVersion';\nexport const LABEL_SOURCE_DOCUMENT = 'sourceDocument';\n\nconst MERGE_GENERATOR_NAME = 'hdf-merge';\nconst MERGE_EXTENSION_KEY = 'hdf-merge';\n\n/**\n * merge combines the sources, in order, into one results document. Returns the\n * document and any warnings (a collision or overwrite is never an error);\n * throws only when there is nothing to merge. Inputs are not mutated.\n */\nexport function merge(sources: MergeSource[]): MergeResult {\n if (sources.length === 0) {\n throw new Error('merge: no sources');\n }\n\n const baselines: EvaluatedBaseline[] = [];\n const components: Component[] = [];\n const warnings: MergeWarning[] = [];\n const seenComponent = new Set<string>();\n const provenance: Record<string, unknown>[] = [];\n const positionsByName = new Map<string, number[]>();\n let latest: HDFResults['timestamp'];\n\n sources.forEach((src, index) => {\n const prefix = toolPrefix(src.doc, index);\n const version = toolVersion(src.doc);\n\n for (const b of src.doc.baselines ?? []) {\n const name = `${prefix}/${b.name}`;\n const pos = baselines.length;\n const labels: Record<string, string> = { ...(b.labels ?? {}) };\n\n setLabel(warnings, labels, LABEL_TOOL, prefix, name, pos);\n if (version !== '') {\n setLabel(warnings, labels, LABEL_TOOL_VERSION, version, name, pos);\n } else if (LABEL_TOOL_VERSION in labels) {\n delete labels[LABEL_TOOL_VERSION];\n warnings.push({ kind: 'label-overwritten', name, indices: [pos], label: LABEL_TOOL_VERSION });\n }\n setLabel(warnings, labels, LABEL_SOURCE_DOCUMENT, src.name, name, pos);\n\n const positions = positionsByName.get(name);\n if (positions) positions.push(pos);\n else positionsByName.set(name, [pos]);\n\n baselines.push({ ...b, name, labels });\n }\n\n for (const c of src.doc.components ?? []) {\n if (c.componentId !== undefined) {\n if (seenComponent.has(c.componentId)) continue;\n seenComponent.add(c.componentId);\n }\n components.push(c);\n }\n\n if (src.doc.timestamp !== undefined && (latest === undefined || millis(src.doc.timestamp) > millis(latest))) {\n latest = src.doc.timestamp;\n }\n\n provenance.push(sourceProvenance(index, src));\n });\n\n for (const [name, positions] of positionsByName) {\n if (positions.length > 1) {\n warnings.push({ kind: 'duplicate-baseline-name', name, indices: positions });\n }\n }\n\n // Key order is fixed so the same inputs serialize identically on every run.\n const results: HDFResults = {\n baselines,\n ...(components.length > 0 ? { components } : {}),\n extensions: { [MERGE_EXTENSION_KEY]: { version: engineVersion, sources: provenance } },\n generator: { name: MERGE_GENERATOR_NAME, version: engineVersion },\n ...(latest !== undefined ? { timestamp: latest } : {}),\n };\n return { results, warnings };\n}\n\nfunction setLabel(\n warnings: MergeWarning[],\n labels: Record<string, string>,\n key: string,\n value: string,\n name: string,\n pos: number,\n): void {\n if (key in labels) {\n warnings.push({ kind: 'label-overwritten', name, indices: [pos], label: key });\n }\n labels[key] = value;\n}\n\n/** `<tool>` of a merged baseline name: tool.name → generator.name → doc<N>, lower-cased and trimmed. */\nfunction toolPrefix(doc: HDFResults, index: number): string {\n const tool = normalizeName(doc.tool?.name);\n if (tool !== '') return tool;\n const generator = normalizeName(doc.generator?.name);\n if (generator !== '') return generator;\n return `doc${index}`;\n}\n\nfunction normalizeName(s: string | undefined): string {\n return (s ?? '').trim().toLowerCase();\n}\n\n/**\n * millis reads a document timestamp for comparison. The schema type is Date,\n * but a document parsed from JSON carries the RFC 3339 string verbatim (the\n * loader does not revive dates), so both are accepted; the value itself is\n * carried through unchanged so output stays byte-faithful to the input.\n */\nfunction millis(ts: Date | string): number {\n return ts instanceof Date ? ts.getTime() : Date.parse(ts);\n}\n\nfunction toolVersion(doc: HDFResults): string {\n return (doc.tool?.version ?? '').trim();\n}\n\n/** One input's root metadata, verbatim, for extensions[\"hdf-merge\"].sources[]. */\nfunction sourceProvenance(index: number, src: MergeSource): Record<string, unknown> {\n const entry: Record<string, unknown> = { index, name: src.name };\n if (src.doc.tool !== undefined) entry.tool = src.doc.tool;\n if (src.doc.generator !== undefined) entry.generator = src.doc.generator;\n if (src.doc.timestamp !== undefined) entry.timestamp = src.doc.timestamp;\n if (src.doc.runner !== undefined) entry.runner = src.doc.runner;\n return entry;\n}\n","// Document-type detection — the TypeScript peer of hdf-engine/go/detect.go.\n// Fingerprints an HDF document by its root keys and returns the schema type\n// string. Kept at behavioural parity with the Go implementation (see\n// go/detect_test.go and src/detect.test.ts, which assert both against the same\n// bundled schema examples).\n\n/** The eight HDF document type strings, matching validators.Type* in Go. */\nexport type HdfDocType =\n | 'results'\n | 'baseline'\n | 'system'\n | 'plan'\n | 'amendments'\n | 'evidence-package'\n | 'comparison'\n | 'requirement-change-event'\n | '';\n\n/**\n * Detect fingerprints an HDF document by its root keys and returns the schema\n * type string, or '' when the input is not a JSON object or matches no known\n * HDF document type.\n */\nexport function detect(input: string): HdfDocType {\n let parsed: unknown;\n try {\n parsed = JSON.parse(input);\n } catch {\n return '';\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n return '';\n }\n const doc = parsed as Record<string, unknown>;\n const has = (...keys: string[]): boolean =>\n keys.every((k) => Object.prototype.hasOwnProperty.call(doc, k));\n\n // Most specific first. A requirement-change-event carries the singular\n // requirementId together with the state/before/after triad — a combination\n // no other HDF document type has — so it is checked ahead of the rest.\n if (has('requirementId', 'state', 'before', 'after')) return 'requirement-change-event';\n\n if (has('contents')) return 'evidence-package';\n if (has('overrides')) return 'amendments';\n if (has('assessments')) return 'plan';\n if (has('comparisonMode')) return 'comparison';\n if (has('baselines')) return 'results';\n if (has('components')) return 'system';\n if (has('requirements')) return 'baseline';\n return '';\n}\n","// Compliance & threshold engine — the TypeScript peer of\n// hdf-engine/go/compliance.go. Pure functions, kept at behavioural parity with\n// the Go implementation (see test/compliance.test.ts, which runs both over the\n// same fixture). Violation message formats match the Go fmt.Sprintf output.\n\nimport type { HDFResults, EvaluatedRequirement, RequirementResult, Severity } from '@mitre/hdf-schema';\nimport { worstStatus, impactToSeverity } from '@mitre/hdf-utilities';\n\n/** Threshold status-key constants (SAF CLI-compatible keys). */\nexport const THRESHOLD_PASSED = 'passed';\nexport const THRESHOLD_FAILED = 'failed';\nexport const THRESHOLD_SKIPPED = 'skipped';\nexport const THRESHOLD_ERROR = 'error';\nexport const THRESHOLD_NO_IMPACT = 'no_impact';\n\nexport interface SeverityCounts {\n critical: number;\n high: number;\n medium: number;\n low: number;\n /** The schema's fifth severity; also absorbs a severity that cannot be derived or is not in the enum. */\n informational: number;\n total: number;\n}\n\nexport interface StatusCounts {\n passed: SeverityCounts;\n failed: SeverityCounts;\n skipped: SeverityCounts;\n error: SeverityCounts;\n noImpact: SeverityCounts;\n}\n\nexport interface ControlIDMapping {\n id: string;\n status: string;\n severity: string;\n}\n\nexport interface ThresholdBound {\n min?: number;\n max?: number;\n controls?: string[];\n}\n\nexport interface ThresholdSeverity {\n critical?: ThresholdBound;\n high?: ThresholdBound;\n medium?: ThresholdBound;\n low?: ThresholdBound;\n informational?: ThresholdBound;\n /** Pre-3.7 spelling of `informational`, normalized on read and never written. */\n none?: ThresholdBound;\n total?: ThresholdBound;\n}\n\nexport interface ComplianceBound {\n min?: number;\n max?: number;\n}\n\nexport interface ThresholdConfig {\n compliance?: ComplianceBound;\n passed?: ThresholdSeverity;\n failed?: ThresholdSeverity;\n skipped?: ThresholdSeverity;\n error?: ThresholdSeverity;\n noImpact?: ThresholdSeverity;\n}\n\nfunction newSeverityCounts(): SeverityCounts {\n return { critical: 0, high: 0, medium: 0, low: 0, informational: 0, total: 0 };\n}\n\nfunction newStatusCounts(): StatusCounts {\n return {\n passed: newSeverityCounts(),\n failed: newSeverityCounts(),\n skipped: newSeverityCounts(),\n error: newSeverityCounts(),\n noImpact: newSeverityCounts(),\n };\n}\n\n/**\n * overallStatus is the canonical worst-wins roll-up of a requirement's result\n * statuses, delegated to @mitre/hdf-utilities worstStatus (error > failed >\n * passed > notApplicable > notReviewed; empty → notReviewed). No local rank\n * switch — the TS peer of the Go overallStatus dedup (supersedes hdf-libs-ixhx).\n */\nexport function overallStatus(results: RequirementResult[]): string {\n return worstStatus(results.map((r) => String(r.status)));\n}\n\n/**\n * deriveSeverity determines the severity string from impact and optional explicit\n * severity, using impactToSeverity. Both paths yield a value from the schema's\n * severity enum: an explicit informational and an impact-derived one are the same\n * thing and must not land in different buckets.\n */\nexport function deriveSeverity(impact: number, severity?: Severity | null): string {\n // Presence-based, matching Go DeriveSeverity's `if severity != nil`: an explicit\n // severity — including an empty string — is returned verbatim; only a\n // null/undefined severity derives from impact. Testing truthiness here would\n // send \"\" through the impact path and diverge from Go (bead 4908.20).\n if (severity != null) {\n return String(severity);\n }\n return impactToSeverity(impact);\n}\n\nfunction statusBucket(counts: StatusCounts, status: string): SeverityCounts {\n switch (status) {\n case 'passed':\n return counts.passed;\n case 'failed':\n return counts.failed;\n case 'error':\n return counts.error;\n case 'notApplicable':\n return counts.noImpact;\n case 'notReviewed':\n return counts.skipped;\n default:\n return counts.skipped;\n }\n}\n\nfunction addCount(counts: StatusCounts, status: string, severity: string): void {\n const sc = statusBucket(counts, status);\n sc.total++;\n switch (severity) {\n case 'critical':\n sc.critical++;\n break;\n case 'high':\n sc.high++;\n break;\n case 'medium':\n sc.medium++;\n break;\n case 'low':\n sc.low++;\n break;\n default:\n // Informational plus anything outside the enum: an unrecognized severity\n // is counted, never dropped, so a malformed document still gates.\n sc.informational++;\n }\n}\n\nfunction statusToThresholdKey(status: string): string {\n switch (status) {\n case 'passed':\n return THRESHOLD_PASSED;\n case 'failed':\n return THRESHOLD_FAILED;\n case 'notReviewed':\n return THRESHOLD_SKIPPED;\n case 'error':\n return THRESHOLD_ERROR;\n case 'notApplicable':\n return THRESHOLD_NO_IMPACT;\n default:\n return THRESHOLD_SKIPPED;\n }\n}\n\n/** CountControlsByStatusSeverity counts requirements by overall status and severity. */\nexport function countControlsByStatusSeverity(results: HDFResults): StatusCounts {\n const counts = newStatusCounts();\n for (const baseline of results.baselines ?? []) {\n for (const req of baseline.requirements ?? []) {\n addCount(counts, overallStatus(req.results ?? []), deriveSeverity(req.impact, reqSeverity(req)));\n }\n }\n return counts;\n}\n\n/**\n * countControlsByStatus counts requirements by a caller-resolved status — the\n * injected-resolver twin of countControlsByStatusSeverity (which counts raw\n * result statuses with no override awareness). statusOf returns each\n * requirement's status in the schema vocabulary (passed/failed/notApplicable/\n * notReviewed/error); an empty or unrecognized value counts as skipped, and an\n * absent resolver yields all-skipped. Callers build effective-status rollups\n * (e.g. compliance with and without agent-attributed overrides) without the\n * engine binding to any one status convention. Parity: go/compliance.go.\n */\nexport function countControlsByStatus(\n results: HDFResults,\n statusOf?: (req: EvaluatedRequirement) => string,\n): StatusCounts {\n const counts = newStatusCounts();\n for (const baseline of results.baselines ?? []) {\n for (const req of baseline.requirements ?? []) {\n const status = statusOf ? statusOf(req) : '';\n addCount(counts, status, deriveSeverity(req.impact, reqSeverity(req)));\n }\n }\n return counts;\n}\n\n/**\n * agentOverrideCount counts the status overrides across a result set whose\n * applied-by identity type is \"agent\" — the detective count. Deterministic\n * from_vex/system overrides are excluded so the count is a meaningful AI-scrutiny\n * signal. Parity: go/compliance.go AgentOverrideCount.\n */\nexport function agentOverrideCount(results: HDFResults): number {\n let count = 0;\n for (const baseline of results.baselines ?? []) {\n for (const req of baseline.requirements ?? []) {\n for (const o of req.statusOverrides ?? []) {\n if (o.appliedBy?.type === 'agent') {\n count++;\n }\n }\n }\n }\n return count;\n}\n\n/** MapControlIDs builds control ID → status/severity mappings from a result set. */\nexport function mapControlIDs(results: HDFResults): ControlIDMapping[] {\n const mappings: ControlIDMapping[] = [];\n for (const baseline of results.baselines ?? []) {\n for (const req of baseline.requirements ?? []) {\n const status = overallStatus(req.results ?? []);\n mappings.push({\n id: req.id,\n status: statusToThresholdKey(status),\n severity: deriveSeverity(req.impact, reqSeverity(req)),\n });\n }\n }\n return mappings;\n}\n\n/**\n * mapControlIDsByStatus builds control ID → status/severity mappings using a\n * caller-resolved status — the injected-resolver twin of mapControlIDs (which\n * maps raw result statuses). statusOf returns each requirement's status in the\n * schema vocabulary; an empty or unrecognized value maps to skipped, and an\n * absent resolver yields all-skipped. Callers build effective-status control\n * listings (the same injection pattern as countControlsByStatus). Parity:\n * go/compliance.go MapControlIDsByStatus.\n */\nexport function mapControlIDsByStatus(\n results: HDFResults,\n statusOf?: (req: EvaluatedRequirement) => string,\n): ControlIDMapping[] {\n const mappings: ControlIDMapping[] = [];\n for (const baseline of results.baselines ?? []) {\n for (const req of baseline.requirements ?? []) {\n const status = statusOf ? statusOf(req) : '';\n mappings.push({\n id: req.id,\n status: statusToThresholdKey(status),\n severity: deriveSeverity(req.impact, reqSeverity(req)),\n });\n }\n }\n return mappings;\n}\n\nfunction reqSeverity(req: EvaluatedRequirement): Severity | null {\n return (req.severity ?? null) as Severity | null;\n}\n\n/**\n * calculateCompliance returns the compliance percentage rounded to two decimals:\n * passed / (passed + failed + skipped + error) * 100; notApplicable excluded.\n */\nexport function calculateCompliance(counts: StatusCounts): number {\n const relevant = counts.passed.total + counts.failed.total + counts.skipped.total + counts.error.total;\n if (relevant === 0) {\n return 0;\n }\n const pct = (counts.passed.total / relevant) * 100;\n return Math.round(pct * 100) / 100;\n}\n\n/**\n * normalizeLegacySeverity folds the pre-3.7 `none` key into `informational`. A\n * spec setting both is refused rather than resolved: the two name one bucket, so\n * silently honouring one would drop a bound the author wrote.\n */\nfunction normalizeLegacySeverity(config: ThresholdConfig): string[] {\n const violations: string[] = [];\n const sections: [string, ThresholdSeverity | undefined][] = [\n [THRESHOLD_PASSED, config.passed],\n [THRESHOLD_FAILED, config.failed],\n [THRESHOLD_SKIPPED, config.skipped],\n [THRESHOLD_ERROR, config.error],\n [THRESHOLD_NO_IMPACT, config.noImpact],\n ];\n for (const [name, ts] of sections) {\n if (!ts?.none) continue;\n if (ts.informational) {\n violations.push(\n `${name}: both 'none' and 'informational' are set; 'none' is the pre-3.7 spelling of the same bucket`,\n );\n continue;\n }\n ts.informational = ts.none;\n delete ts.none;\n }\n return violations;\n}\n\n/**\n * validateThresholds checks all threshold bounds against observed counts and\n * compliance, returning human-readable violation messages (empty when all pass).\n */\nexport function validateThresholds(\n config: ThresholdConfig,\n counts: StatusCounts,\n compliance: number,\n controlMap: ControlIDMapping[],\n): string[] {\n const violations: string[] = [];\n\n // Every construction path lands here, so the legacy spelling is resolved once\n // rather than in each caller.\n violations.push(...normalizeLegacySeverity(config));\n\n const actualControls = new Map<string, ControlIDMapping>();\n for (const m of controlMap) {\n actualControls.set(m.id, m);\n }\n\n if (config.compliance) {\n if (config.compliance.min !== undefined && compliance < config.compliance.min) {\n violations.push(`compliance ${compliance.toFixed(2)}% is below minimum ${config.compliance.min.toFixed(2)}%`);\n }\n if (config.compliance.max !== undefined && compliance > config.compliance.max) {\n violations.push(`compliance ${compliance.toFixed(2)}% exceeds maximum ${config.compliance.max.toFixed(2)}%`);\n }\n }\n\n violations.push(...checkSeverityThreshold(THRESHOLD_PASSED, config.passed, counts.passed, actualControls));\n violations.push(...checkSeverityThreshold(THRESHOLD_FAILED, config.failed, counts.failed, actualControls));\n violations.push(...checkSeverityThreshold(THRESHOLD_SKIPPED, config.skipped, counts.skipped, actualControls));\n violations.push(...checkSeverityThreshold(THRESHOLD_ERROR, config.error, counts.error, actualControls));\n violations.push(...checkSeverityThreshold(THRESHOLD_NO_IMPACT, config.noImpact, counts.noImpact, actualControls));\n\n return violations;\n}\n\nfunction checkSeverityThreshold(\n status: string,\n threshold: ThresholdSeverity | undefined,\n actual: SeverityCounts,\n actualControls: Map<string, ControlIDMapping>,\n): string[] {\n if (!threshold) {\n return [];\n }\n const violations: string[] = [];\n const check = (label: string, bound: ThresholdBound | undefined, actualCount: number): void => {\n if (!bound) {\n return;\n }\n const path = `${status}.${label}`;\n if (bound.min !== undefined && actualCount < bound.min) {\n violations.push(`${path}: ${actualCount} is below minimum ${bound.min}`);\n }\n if (bound.max !== undefined && actualCount > bound.max) {\n violations.push(`${path}: ${actualCount} exceeds maximum ${bound.max}`);\n }\n for (const expectedID of bound.controls ?? []) {\n const ac = actualControls.get(expectedID);\n if (!ac) {\n violations.push(`${path}: expected control ${expectedID} not found in results`);\n } else if (ac.status !== status || ac.severity !== label) {\n violations.push(\n `${path}: control ${expectedID} expected ${status}/${label} but found ${ac.status}/${ac.severity}`,\n );\n }\n }\n };\n\n check('critical', threshold.critical, actual.critical);\n check('high', threshold.high, actual.high);\n check('medium', threshold.medium, actual.medium);\n check('low', threshold.low, actual.low);\n check('informational', threshold.informational, actual.informational);\n check('total', threshold.total, actual.total);\n\n return violations;\n}\n","// Glob matching — the TypeScript peer of hdf-engine/go/safematch.go. Kept at\n// behavioural parity with the Go matcher.\n\nconst MAX_PATTERN_LENGTH = 256;\n\nconst REGEX_SPECIAL = new Set(['.', '+', '^', '$', '(', ')', '[', ']', '{', '}', '|', '\\\\']);\n\n/**\n * globToRegex converts a glob pattern (with * and ? wildcards) to an anchored\n * regular expression, escaping every other regex metacharacter exactly once. A\n * single pass avoids re-escaping the backslash introduced by escaping an earlier\n * metacharacter (the doubled-backslash defect that made any dotted pattern match\n * nothing).\n */\nexport function globToRegex(glob: string): string {\n let result = '^';\n for (const ch of glob) {\n if (ch === '*') {\n result += '.*';\n } else if (ch === '?') {\n result += '.';\n } else if (REGEX_SPECIAL.has(ch)) {\n result += '\\\\' + ch;\n } else {\n result += ch;\n }\n }\n return result + '$';\n}\n\n/**\n * safeGlobMatch converts a glob pattern to a regex and matches case-insensitively.\n * Returns false for over-length or invalid patterns (fail-safe), mirroring the\n * Go matcher's length cap and error handling.\n */\nconst byteEncoder = new TextEncoder();\n\n/** byteLength returns the UTF-8 byte length, matching Go's len(string). */\nfunction byteLength(s: string): number {\n return byteEncoder.encode(s).length;\n}\n\nexport function safeGlobMatch(s: string, pattern: string): boolean {\n // Cap on UTF-8 byte length (matching Go's len(pattern)), and — like Go's\n // compileSafeRegex — re-cap the EXPANDED regex, so an over-length glob or a\n // small glob that expands past the limit is rejected identically in both\n // languages (not just capped on the raw glob's UTF-16 length).\n if (byteLength(pattern) > MAX_PATTERN_LENGTH) {\n return false;\n }\n const rx = globToRegex(pattern);\n if (byteLength(rx) > MAX_PATTERN_LENGTH) {\n return false;\n }\n let re: RegExp;\n try {\n re = new RegExp(rx, 'i');\n } catch {\n return false;\n }\n return re.test(s);\n}\n","// Requirements query engine — the TypeScript peer of hdf-engine/go/filter.go.\n// A pure filter(results, options) with no shared mutable state, kept at\n// behavioural parity with the Go implementation (see test/query.test.ts, which\n// runs both over the same fixture).\n\nimport type { HDFResults, EvaluatedRequirement } from '@mitre/hdf-schema';\nimport { deriveSeverity } from './compliance.js';\nimport { safeGlobMatch } from './safematch.js';\n\n/**\n * FilterOptions configures a requirements query. Every filter input arrives here;\n * distinct filters combine with AND, repeated values within a filter with OR.\n * statusOf resolves a requirement's display status, injected so the engine stays\n * agnostic to the caller's status-string convention (undefined → empty status).\n */\nexport interface FilterOptions {\n status?: string[];\n severity?: string[];\n impact?: string;\n cci?: string[];\n nist?: string[];\n id?: string;\n tag?: string[];\n search?: string;\n baseline?: string;\n limit?: number;\n count?: boolean;\n statusOf?: (control: EvaluatedRequirement) => string;\n}\n\n/**\n * A single query result row. baselineIndex and index are the match's position in\n * the result set (results.baselines[baselineIndex].requirements[index]) and are\n * the only unique identity a match has: baseline names repeat in shipped\n * converter output and requirement ids repeat within a baseline, so (baseline,\n * id) is not a key. Address the source requirement by position, never by name.\n */\nexport interface Match {\n id: string;\n title: string;\n status: string;\n impact: number;\n severity: string;\n baseline: string;\n baselineIndex: number;\n index: number;\n}\n\ntype FilterFunc = (control: EvaluatedRequirement, status: string, severity: string) => boolean;\n\n/**\n * filter returns the requirements across the result set's baselines that satisfy\n * options. Applies to requirement collections (results/baseline documents); the\n * calling adapter rejects document types that carry no requirements.\n */\nexport function filter(results: HDFResults, options: FilterOptions): Match[] {\n const filters = buildFilters(options);\n const matches: Match[] = [];\n\n for (const [baselineIndex, baseline] of (results.baselines ?? []).entries()) {\n if (options.baseline && !matchesGlob(baseline.name, options.baseline)) {\n continue;\n }\n for (const [index, control] of (baseline.requirements ?? []).entries()) {\n if (options.limit && options.limit > 0 && matches.length >= options.limit && !options.count) {\n return matches;\n }\n\n const status = options.statusOf ? options.statusOf(control) : '';\n // Explicit STIG severity wins; impact-derived only as a fallback — the\n // canonical rule shared with the compliance counts (deriveSeverity), so\n // query rows and compliance never disagree on a requirement's severity.\n const severity = deriveSeverity(control.impact, control.severity ?? null);\n\n if (!applyFilters(control, status, severity, filters)) {\n continue;\n }\n\n matches.push({\n id: control.id,\n title: control.title ?? '',\n status,\n impact: control.impact,\n severity,\n baseline: baseline.name,\n baselineIndex,\n index,\n });\n }\n }\n return matches;\n}\n\nfunction buildFilters(options: FilterOptions): FilterFunc[] {\n const filters: FilterFunc[] = [];\n\n if (options.status && options.status.length > 0) {\n const statuses = options.status.map((s) => s.toLowerCase());\n filters.push((_c, s) => statuses.includes(s.toLowerCase()));\n }\n\n if (options.severity && options.severity.length > 0) {\n const severities = options.severity.map((s) => s.toLowerCase());\n filters.push((_c, _s, severity) => severities.includes(severity));\n }\n\n if (options.impact) {\n const [op, val] = parseImpactFilter(options.impact);\n filters.push((c) => compareImpact(c.impact, op, val));\n }\n\n if (options.cci && options.cci.length > 0) {\n const ccis = options.cci.map((c) => c.toUpperCase());\n filters.push((c) => ccis.some((cci) => tagContains(c.tags, 'cci', cci)));\n }\n\n if (options.nist && options.nist.length > 0) {\n const nist = options.nist;\n filters.push((c) => nist.some((n) => tagMatchesGlob(c.tags, 'nist', n)));\n }\n\n if (options.id) {\n const id = options.id;\n filters.push(\n (c) =>\n tagContains(c.tags, 'stig_id', id) ||\n tagContains(c.tags, 'gid', id) ||\n tagContains(c.tags, 'gtitle', id) ||\n c.id === id,\n );\n }\n\n if (options.tag && options.tag.length > 0) {\n const tagFilters: { key: string; value: string }[] = [];\n for (const t of options.tag) {\n const idx = t.indexOf(':');\n if (idx >= 0) {\n tagFilters.push({ key: t.slice(0, idx), value: t.slice(idx + 1) });\n }\n }\n if (tagFilters.length > 0) {\n filters.push((c) => tagFilters.some((tf) => tagMatchesGlob(c.tags, tf.key, tf.value)));\n }\n }\n\n if (options.search) {\n const search = options.search.toLowerCase();\n filters.push((c) => {\n if (c.id.toLowerCase().includes(search)) return true;\n if (c.title && c.title.toLowerCase().includes(search)) return true;\n for (const desc of c.descriptions ?? []) {\n if (desc.data.toLowerCase().includes(search)) return true;\n }\n return false;\n });\n }\n\n return filters;\n}\n\nfunction applyFilters(\n control: EvaluatedRequirement,\n status: string,\n severity: string,\n filters: FilterFunc[],\n): boolean {\n return filters.every((f) => f(control, status, severity));\n}\n\n// DECIMAL_FLOAT is the shared impact-filter operand grammar — a plain decimal:\n// optional sign, digits with an optional fraction (or a leading-dot fraction),\n// optional decimal exponent. It excludes the forms JS Number() accepts but that\n// make no sense as a 0.0–1.0 threshold and diverge from Go strconv.ParseFloat:\n// hex/binary/octal integers (0x1f→31, 0b101→5, 0o17→15) and Infinity. The Go\n// engine applies the identical pattern so a filter is accepted or rejected the\n// same in both languages (bead 4908.15).\nconst DECIMAL_FLOAT = /^[+-]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][+-]?\\d+)?$/;\n\n// parseDecimal parses a plain-decimal operand, returning null for anything\n// outside the shared grammar (including overflow to Infinity, e.g. '1e400', so\n// Go's ParseFloat ErrRange rejection is mirrored).\nfunction parseDecimal(s: string): number | null {\n if (!DECIMAL_FLOAT.test(s)) return null;\n const v = Number(s);\n return Number.isFinite(v) ? v : null;\n}\n\n// An invalid operand safe-degrades to ('=', NaN), which compareImpact treats as\n// matching NOTHING — mirroring the Go engine's `return ok && compareImpact(...)`.\n// It must never coerce to ('=', 0), which silently returns confidently-wrong\n// impact==0 rows for a typo'd or garbage filter.\nexport function parseImpactFilter(f: string): [string, number] {\n const trimmed = f.trim();\n for (const op of ['>=', '<=', '>', '<', '=']) {\n if (trimmed.startsWith(op)) {\n const v = parseDecimal(trimmed.slice(op.length).trim());\n return v === null ? ['=', NaN] : [op, v];\n }\n }\n const v = parseDecimal(trimmed);\n return v === null ? ['=', NaN] : ['=', v];\n}\n\nexport function compareImpact(impact: number, op: string, val: number): boolean {\n switch (op) {\n case '>':\n return impact > val;\n case '>=':\n return impact >= val;\n case '<':\n return impact < val;\n case '<=':\n return impact <= val;\n case '=':\n return impact === val;\n default:\n return false;\n }\n}\n\nexport function tagContains(tags: Record<string, unknown>, key: string, value: string): boolean {\n const tagVal = tags?.[key];\n if (tagVal === undefined) {\n return false;\n }\n const want = value.toLowerCase();\n if (typeof tagVal === 'string') {\n return tagVal.toLowerCase() === want;\n }\n if (Array.isArray(tagVal)) {\n return tagVal.some((item) => typeof item === 'string' && item.toLowerCase() === want);\n }\n return false;\n}\n\nexport function tagMatchesGlob(tags: Record<string, unknown>, key: string, pattern: string): boolean {\n const tagVal = tags?.[key];\n if (tagVal === undefined) {\n return false;\n }\n if (typeof tagVal === 'string') {\n return safeGlobMatch(tagVal, pattern);\n }\n if (Array.isArray(tagVal)) {\n return tagVal.some((item) => typeof item === 'string' && safeGlobMatch(item, pattern));\n }\n return false;\n}\n\n/** matchesGlob reports whether s matches the glob pattern (case-insensitive). */\nexport function matchesGlob(s: string, pattern: string): boolean {\n return safeGlobMatch(s, pattern);\n}\n","// Document loader engine core — the TypeScript peer of hdf-engine/go/loader.go,\n// kept at behavioural parity (see loader.test.ts + the Go parity test, which\n// run both over the same fixtures). Pure and schema-typed: size-guard first,\n// wire-format + document-type detection, then the canonical parse for the\n// results/baseline types. No cache, no degraded envelope — those are MCP\n// concerns layered on top in hdf-cli/internal/mcp/loader.\n\nimport type { HDFResults, HDFBaseline } from '@mitre/hdf-schema';\nimport { validateInputSize } from '@mitre/hdf-utilities';\nimport { parseResults, parseBaseline } from '@mitre/hdf-parsers';\nimport { detect, type HdfDocType } from './detect.js';\n\n/** Wire encoding of loader input (parity with Go InputFormat). */\nexport type InputFormat = 'json' | 'ndjson';\n\nexport interface LoadResult {\n format: InputFormat;\n docType: HdfDocType;\n results?: HDFResults;\n baseline?: HDFBaseline;\n /** Non-empty when detected as results/baseline but the parse/validate failed. */\n parseError?: string;\n valid: boolean;\n}\n\n/**\n * load is the schema-typed loader core. In order: validateInputSize (FIRST,\n * before any parse; maxSize <= 0 uses the default), wire-format detection\n * (JSON vs NDJSON), document-type detection (detect), then the canonical\n * hdf-parsers parse for the results and baseline types. Other types are\n * detected but not parsed here.\n */\nexport function load(input: string | Uint8Array, maxSize = 0): LoadResult {\n validateInputSize(input, maxSize); // first op — throws on oversize\n\n const text = typeof input === 'string' ? input : new TextDecoder().decode(input);\n const result: LoadResult = {\n format: detectFormat(text),\n docType: detect(text),\n valid: false,\n };\n\n if (result.docType === 'results') {\n const r = parseResults(text);\n if (r.success && r.data) {\n result.results = r.data;\n result.valid = true;\n } else {\n result.parseError = r.error;\n }\n } else if (result.docType === 'baseline') {\n const r = parseBaseline(text);\n if (r.success && r.data) {\n result.baseline = r.data;\n result.valid = true;\n } else {\n result.parseError = r.error;\n }\n }\n\n return result;\n}\n\n/**\n * detectFormat classifies input as a single JSON document or newline-delimited\n * JSON, consistent with the Go core: NDJSON is two or more non-blank lines that\n * each independently parse as a complete JSON value. A pretty-printed single\n * object stays 'json' (its first line is not itself a complete JSON value).\n */\nexport function detectFormat(text: string): InputFormat {\n const lines = text.split('\\n').filter((l) => l.trim() !== '');\n const [first, second] = lines;\n if (first === undefined || second === undefined) {\n return 'json';\n }\n if (isCompleteJSON(first) && isCompleteJSON(second)) {\n return 'ndjson';\n }\n return 'json';\n}\n\n// isCompleteJSON reports whether s is a single complete JSON value with no\n// trailing content — the per-line test the NDJSON classifier applies. JSON.parse\n// already rejects trailing garbage, so a successful parse is sufficient.\nfunction isCompleteJSON(s: string): boolean {\n try {\n JSON.parse(s);\n return true;\n } catch {\n return false;\n }\n}\n","// Evidence-verify engine — the TypeScript peer of hdf-engine/go/evidence.go.\n// Pure, filesystem-agnostic core of `hdf evidence verify` (ADR-0007 §11):\n// content-checksum classification and plan/results completeness. All filesystem\n// IO and path confinement stay in the caller, injected as a FetchFn. Kept at\n// behavioural parity with the Go implementation (see test/evidence.test.ts,\n// which runs both over the same fixtures).\n\nimport { createHash } from 'node:crypto';\nimport { agentOverrideCount } from './compliance.js';\nimport type { HDFResults } from '@mitre/hdf-schema';\n\n/** Classifies a single content entry's checksum verification. */\nexport type ChecksumStatus = 'match' | 'mismatch' | 'skipped' | 'error';\n\n/** One content entry of an evidence package: a referenced document and its\n * recorded checksum ('' when the entry carries none). */\nexport interface EvidenceContent {\n uri: string;\n type: string;\n checksum: string;\n}\n\n/** The verification outcome for one content entry. */\nexport interface ChecksumResult {\n uri: string;\n type: string;\n status: ChecksumStatus;\n expected?: string;\n actual?: string;\n error?: string;\n}\n\n/** Reports which planned baselines are covered by results. */\nexport interface CompletenessResult {\n planned: string[];\n covered: string[];\n missing: string[];\n complete: boolean;\n}\n\n/** Resolves a content URI to its bytes. The caller owns path confinement\n * (HDF_MCP_ROOT for the MCP, the package directory for the CLI). Throws when the\n * uri cannot be read. */\nexport type FetchFn = (uri: string) => Uint8Array;\n\ntype RawObject = Record<string, unknown>;\n\n/** Go decodes into a typed struct, so a JSON `null` document leaves zero values\n * while a wrong-typed one is a decode error. These three helpers give the TS\n * peer the same split instead of asserting a shape onto untrusted input. */\nfunction parseDocument(text: string, what: string): RawObject {\n const doc: unknown = JSON.parse(text);\n if (doc === null) return {};\n if (typeof doc !== 'object' || Array.isArray(doc)) {\n throw new Error(`parse ${what}: cannot unmarshal ${describe(doc)} into an object`);\n }\n return doc as RawObject;\n}\n\nfunction objectArray(value: unknown, what: string, field: string): RawObject[] {\n if (value === undefined || value === null) return [];\n if (!Array.isArray(value)) {\n throw new Error(`parse ${what}: cannot unmarshal ${describe(value)} into ${field}`);\n }\n return value.map((entry: unknown) => {\n if (entry === null) return {};\n if (typeof entry !== 'object' || Array.isArray(entry)) {\n throw new Error(`parse ${what}: cannot unmarshal ${describe(entry)} into a ${field} entry`);\n }\n return entry as RawObject;\n });\n}\n\nfunction str(value: unknown): string {\n return typeof value === 'string' ? value : '';\n}\n\nfunction describe(value: unknown): string {\n return Array.isArray(value) ? 'array' : value === null ? 'null' : typeof value;\n}\n\n/** Extracts the planRef and content entries from an evidence-package document. */\nexport function parseEvidencePackage(pkg: string): { planRef: string; contents: EvidenceContent[] } {\n const doc = parseDocument(pkg, 'evidence package');\n const contents: EvidenceContent[] = objectArray(doc.contents, 'evidence package', 'contents').map((c) => {\n const checksum = c.checksum;\n return {\n uri: str(c.uri),\n type: str(c.type),\n checksum: typeof checksum === 'object' && checksum !== null ? str((checksum as RawObject).value) : '',\n };\n });\n return { planRef: str(doc.planRef), contents };\n}\n\n/** Verifies each content entry's sha256 against fetch(uri), preserving entry\n * order. No checksum → skipped; a fetch throw → error; hash mismatch → mismatch\n * (carrying expected+actual). */\nexport function verifyChecksums(contents: EvidenceContent[], fetch: FetchFn): ChecksumResult[] {\n return contents.map((c) => {\n const r: ChecksumResult = { uri: c.uri, type: c.type, status: 'skipped' };\n if (c.checksum === '') {\n return r;\n }\n let data: Uint8Array;\n try {\n data = fetch(c.uri);\n } catch (e) {\n return { ...r, status: 'error', error: e instanceof Error ? e.message : String(e) };\n }\n const actual = sha256Hex(data);\n if (actual === c.checksum) {\n return { ...r, status: 'match' };\n }\n return { ...r, status: 'mismatch', expected: c.checksum, actual };\n });\n}\n\n/** Extracts assessment baselineRefs from a plan document, deduped in first-seen\n * order. */\nexport function plannedBaselineRefs(plan: string): string[] {\n const doc = parseDocument(plan, 'plan');\n const refs = objectArray(doc.assessments, 'plan', 'assessments')\n .map((a) => str(a.baselineRef))\n .filter((s) => s !== '');\n return dedupe(refs);\n}\n\n/** Extracts baseline names from a results document, deduped in first-seen order. */\nexport function coveredBaselineNames(results: string): string[] {\n const doc = parseDocument(results, 'results');\n const names = objectArray(doc.baselines, 'results', 'baselines')\n .map((b) => str(b.name))\n .filter((s) => s !== '');\n return dedupe(names);\n}\n\n/** Concatenates the covered baseline names of every hdf-results document the\n * package references, in entry order. An entry that cannot be fetched or parsed\n * is skipped: checksum verification is what reports a read failure, and a\n * partial coverage list is what the completeness diff needs. */\nexport function coveredBaselinesInPackage(contents: EvidenceContent[], fetch: FetchFn): string[] {\n const covered: string[] = [];\n forEachResultsDocument(contents, fetch, (text) => {\n try {\n covered.push(...coveredBaselineNames(text));\n } catch {\n return;\n }\n });\n return covered;\n}\n\n/** Sums the agent-attributed override count across every hdf-results document\n * the package references. Unreadable or unparseable entries are skipped. */\nexport function agentOverridesInPackage(contents: EvidenceContent[], fetch: FetchFn): number {\n let total = 0;\n forEachResultsDocument(contents, fetch, (text) => {\n try {\n total += agentOverrideCount(JSON.parse(text) as HDFResults);\n } catch {\n return;\n }\n });\n return total;\n}\n\n/** Fetches each referenced hdf-results document in entry order, skipping\n * entries that carry no uri or cannot be read. */\nfunction forEachResultsDocument(\n contents: EvidenceContent[],\n fetch: FetchFn,\n visit: (text: string) => void\n): void {\n for (const c of contents) {\n if (c.type !== 'hdf-results' || c.uri === '') {\n continue;\n }\n let data: Uint8Array;\n try {\n data = fetch(c.uri);\n } catch {\n continue;\n }\n visit(new TextDecoder().decode(data));\n }\n}\n\n/** Diffs planned baseline refs against covered baseline names. A planned ref is\n * covered when some results baseline shares its name. Missing is sorted so the\n * outcome is deterministic across languages and runs. */\nexport function completeness(planned: string[], covered: string[]): CompletenessResult {\n const coveredSet = new Set(covered);\n const missing = planned.filter((p) => !coveredSet.has(p)).sort();\n return { planned, covered, missing, complete: missing.length === 0 };\n}\n\nfunction sha256Hex(data: Uint8Array): string {\n return createHash('sha256').update(data).digest('hex');\n}\n\nfunction dedupe(input: string[]): string[] {\n const seen = new Set<string>();\n const out: string[] = [];\n for (const s of input) {\n if (!seen.has(s)) {\n seen.add(s);\n out.push(s);\n }\n }\n return out;\n}\n"],"mappings":";;;;AAIA,MAAa,gBAAgB;;;;ACgC7B,MAAa,aAAa;AAC1B,MAAa,qBAAqB;AAClC,MAAa,wBAAwB;AAErC,MAAM,uBAAuB;AAC7B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version": "3.7.
|
|
3
|
+
"version": "3.7.1-rc.1",
|
|
4
4
|
"description": "Shared schema-typed read-side engines for HDF documents — detection, query/filtering, and compliance rollups",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
@@ -25,13 +25,13 @@
|
|
|
25
25
|
"author": "MITRE Corporation",
|
|
26
26
|
"license": "Apache-2.0",
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@mitre/hdf-schema": "^3.7.
|
|
29
|
-
"@mitre/hdf-utilities": "^3.7.
|
|
30
|
-
"@mitre/hdf-parsers": "^3.7.
|
|
28
|
+
"@mitre/hdf-schema": "^3.7.1-rc.1",
|
|
29
|
+
"@mitre/hdf-utilities": "^3.7.1-rc.1",
|
|
30
|
+
"@mitre/hdf-parsers": "^3.7.1-rc.1"
|
|
31
31
|
},
|
|
32
32
|
"devDependencies": {
|
|
33
|
-
"@mitre/hdf-fixtures": "^3.7.
|
|
34
|
-
"@mitre/hdf-validators": "^3.7.
|
|
33
|
+
"@mitre/hdf-fixtures": "^3.7.1-rc.1",
|
|
34
|
+
"@mitre/hdf-validators": "^3.7.1-rc.1"
|
|
35
35
|
},
|
|
36
36
|
"engines": {
|
|
37
37
|
"node": ">=22.0.0"
|