@intellectual-frontiers/grc 0.0.0-stage → 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Intellectual Frontiers
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,9 @@
1
- # Temporary Holding Version
1
+ # @intellectual-frontiers/grc
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Governance, risk and compliance as code: typed catalogs, controls, verdicts, findings and waivers, the hash-chained evidence ledger, coverage, freshness, drift and the risk register, and the findings, assessments and attestations written as OCSF, OSCAL, CycloneDX and in-toto; with a host that loads the settings of packs, runs them as signals and signs; the same code on Bun and Node 26.
4
+
5
+ ```sh
6
+ bun add @intellectual-frontiers/grc # or: npm install @intellectual-frontiers/grc
7
+ ```
8
+
9
+ Sources and specifications: https://github.com/intellectual-frontiers/.github/tree/main/commons/grc
@@ -0,0 +1,247 @@
1
+ /**
2
+ * Assessment: what findings, evidence and declarations add up to (commons 0001-grc FR-010 to FR-015). Every function is pure and takes the
3
+ * instant it judges at as a value.
4
+ *
5
+ * - **Coverage** rolls each catalog control (a requirement) or control up as `gap`, `untested`, `partial`, `addressed` or `covered` (FR-010).
6
+ * - **Freshness** holds the newest evidence to a cadence (an ISO 8601 duration): `fresh`, `due` within the last tenth of the cadence, or
7
+ * `stale`, with the instant it falls due (FR-011).
8
+ * - **Drift** compares a declared and an observed view of keyed records: added, removed and changed, each change with its field's path
9
+ * and both values, in key order (FR-012).
10
+ * - The **change-impact gate** reads declarations of paths (globs) to controls and judges a change `allowed` or `blocked`, with every
11
+ * reason (FR-013).
12
+ * - The **risk register** levels each risk by NIST SP 800-30 Rev. 1's Table I-2 and reports those past their review (FR-014).
13
+ * - The **trace** relates each requirement to the mechanisms that enforce it and the evidence they gave, and names those with none (FR-015).
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * import { riskLevel } from "./assess.js";
18
+ * riskLevel("moderate", "very-high"); // "high"
19
+ * ```
20
+ *
21
+ * @module
22
+ */
23
+ import { type Decoder } from "@intellectual-frontiers/core";
24
+ import { type Catalog, type CatalogControl, type ControlRef, type Duration, type Finding, type Instant, type Outcome, type Role } from "./grc.js";
25
+ import type { Json } from "@intellectual-frontiers/formats/json5";
26
+ import type { Sha256 } from "@intellectual-frontiers/crypto/sha256";
27
+ /** The findings of the newest assessment of each control and subject: for each, those with the latest `at`. */
28
+ export declare function newestFindings(findings: readonly Finding[]): readonly Finding[];
29
+ /** How well a requirement or control is met, from the worst to the best. */
30
+ export type CoverageStatus = "gap" | "untested" | "partial" | "addressed" | "covered";
31
+ /**
32
+ * The coverage that subjects' outcomes give, `not-applicable` ones left out: `untested` where none is left, `partial` where one is
33
+ * neither passing nor accepted, `addressed` where every one passes or is accepted and at least one is accepted, `covered` where every one
34
+ * passes.
35
+ */
36
+ export declare function coverageOf(outcomes: readonly Outcome[]): Exclude<CoverageStatus, "gap">;
37
+ /** A control's coverage from the newest findings of it. */
38
+ export type ControlCoverage = {
39
+ readonly control: string;
40
+ readonly status: Exclude<CoverageStatus, "gap">;
41
+ readonly outcome: Outcome;
42
+ };
43
+ /** Each control's coverage, in the order given, from the newest findings of each control and subject. */
44
+ export declare function controlCoverage(controls: readonly {
45
+ readonly id: string;
46
+ }[], findings: readonly Finding[]): readonly ControlCoverage[];
47
+ /** A requirement's coverage: the catalog control, the controls that implement it, and how well they meet it. */
48
+ export type RequirementCoverage<C extends string = string, I extends string = string> = {
49
+ readonly requirement: ControlRef<C, I>;
50
+ readonly status: CoverageStatus;
51
+ readonly outcome: Outcome;
52
+ readonly controls: readonly string[];
53
+ };
54
+ /**
55
+ * Every control of a catalog as a requirement, in the catalog's order: `gap` where no control implements it, else the coverage of the
56
+ * newest findings of every control that does (`untested` where there are none).
57
+ */
58
+ export declare function requirementCoverage<C extends string, E extends CatalogControl>(catalog: Catalog<C, E>, controls: readonly {
59
+ readonly id: string;
60
+ readonly implements: readonly ControlRef[];
61
+ }[], findings: readonly Finding[]): readonly RequirementCoverage<C, E["id"]>[];
62
+ /** Whether evidence is recent enough for its cadence. */
63
+ export type FreshnessStatus = "fresh" | "due" | "stale";
64
+ /** How fresh evidence is: its status, the newest evidence, when it falls due (`null` past the year 9999) and when the `due` window opens. */
65
+ export type Freshness = {
66
+ readonly status: FreshnessStatus;
67
+ readonly cadence: string;
68
+ readonly newest: Instant | null;
69
+ readonly dueAt: Instant | null;
70
+ readonly dueFrom: Instant | null;
71
+ };
72
+ /**
73
+ * The freshness at `at` of evidence observed at the given instants, held to a cadence: it falls due one cadence after the newest; it is
74
+ * `stale` after that instant, `due` in the last tenth of the cadence up to and at it, `fresh` before. No evidence at all is `stale`, due at `at`.
75
+ */
76
+ export declare function freshness(cadence: Duration, evidence: readonly Instant[], at: Instant): Freshness;
77
+ /** The freshness of each control's newest finding, held to the control's cadence, in the order given. */
78
+ export declare function controlFreshness(controls: readonly {
79
+ readonly id: string;
80
+ readonly cadence: Duration;
81
+ }[], findings: readonly Finding[], at: Instant): readonly {
82
+ readonly control: string;
83
+ readonly freshness: Freshness;
84
+ }[];
85
+ /** One step of a field's path: a member name or an array index. */
86
+ export type PathStep = string | number;
87
+ /** A field that differs: its path inside the record, and its value on each side (absent where that side does not have it). */
88
+ export type FieldChange = {
89
+ readonly path: readonly PathStep[];
90
+ readonly field: string;
91
+ readonly declared?: Json;
92
+ readonly observed?: Json;
93
+ };
94
+ /** What differs between a declared and an observed view of keyed records, each list in key order. */
95
+ export type Drift = {
96
+ readonly added: readonly {
97
+ readonly key: string;
98
+ readonly value: Json;
99
+ }[];
100
+ readonly removed: readonly {
101
+ readonly key: string;
102
+ readonly value: Json;
103
+ }[];
104
+ readonly changed: readonly {
105
+ readonly key: string;
106
+ readonly changes: readonly FieldChange[];
107
+ }[];
108
+ };
109
+ /** Keyed records: a map, or an object whose members are the records. */
110
+ export type KeyedView = ReadonlyMap<string, Json> | {
111
+ readonly [key: string]: Json;
112
+ };
113
+ /** A field's path as text, `$` for the record itself: `$.ports[0]`, `$["a b"]`. */
114
+ export declare function formatFieldPath(path: readonly PathStep[]): string;
115
+ /** The field changes between two values: objects compared member by member in key order, arrays index by index, anything else whole. */
116
+ export declare function fieldChanges(declared: Json, observed: Json): readonly FieldChange[];
117
+ /** The drift from what is declared to what is observed: records only observed are added, only declared removed, in both but different changed. */
118
+ export declare function drift(declared: KeyedView, observed: KeyedView): Drift;
119
+ /** Paths (globs) and the controls a change to them bears on. */
120
+ export type ImpactDeclaration = {
121
+ readonly paths: readonly string[];
122
+ readonly controls: readonly string[];
123
+ };
124
+ /** A change: the paths it touches, the reviews it says it needs (by role) and the reviews given. */
125
+ export type Change = {
126
+ readonly paths: readonly string[];
127
+ readonly needsReview?: readonly Role[];
128
+ readonly reviewedBy?: readonly Role[];
129
+ };
130
+ /** The outcomes that block a change to the paths of a control. */
131
+ export type BlockingOutcome = "fail" | "error" | "gap";
132
+ /** Why a change is blocked. */
133
+ export type GateReason = {
134
+ readonly kind: "control";
135
+ readonly control: string;
136
+ readonly outcome: BlockingOutcome;
137
+ readonly paths: readonly string[];
138
+ } | {
139
+ readonly kind: "review";
140
+ readonly role: Role;
141
+ };
142
+ /** A control a change bears on, and the touched paths declared for it. */
143
+ export type Touched = {
144
+ readonly control: string;
145
+ readonly paths: readonly string[];
146
+ };
147
+ /** The gate's judgement of a change, with every control it touches; where blocked, every reason. */
148
+ export type GateDecision = {
149
+ readonly kind: "allowed";
150
+ readonly touched: readonly Touched[];
151
+ } | {
152
+ readonly kind: "blocked";
153
+ readonly touched: readonly Touched[];
154
+ readonly reasons: readonly [GateReason, ...GateReason[]];
155
+ };
156
+ /** A gate reason as one sentence. */
157
+ export declare function formatGateReason(r: GateReason): string;
158
+ /** Each control's newest outcome: the join of its newest findings' outcomes. */
159
+ export declare function newestOutcomes(findings: readonly Finding[]): ReadonlyMap<string, Outcome>;
160
+ /**
161
+ * A change judged against the declarations and each control's newest outcome: `blocked` where a touched path is declared for a control
162
+ * whose outcome is `fail`, `error` or `gap` (a control with no outcome does not block), or where a review the change needs was not given;
163
+ * else `allowed`. Reasons: controls in id order, then reviews in role order.
164
+ */
165
+ export declare function gate(declarations: readonly ImpactDeclaration[], change: Change, outcomes: ReadonlyMap<string, Outcome>): GateDecision;
166
+ /** An impact declaration as a file holds it. */
167
+ export declare const impactDeclarationDecoder: Decoder<ImpactDeclaration>;
168
+ /** NIST SP 800-30's five qualitative levels, from the least to the greatest. */
169
+ export declare const RISK_LEVELS: readonly ["very-low", "low", "moderate", "high", "very-high"];
170
+ /** A qualitative level of likelihood, impact or risk (NIST SP 800-30 Rev. 1, Appendices G to I). */
171
+ export type RiskLevel = (typeof RISK_LEVELS)[number];
172
+ /**
173
+ * NIST SP 800-30 Rev. 1, Table I-2, "Assessment scale – level of risk (combination of likelihood and impact)": the level of risk for a
174
+ * likelihood (the row) and an impact (the column).
175
+ */
176
+ export declare const RISK_MATRIX: Readonly<Record<RiskLevel, Readonly<Record<RiskLevel, RiskLevel>>>>;
177
+ /** The level of risk of a likelihood and an impact, by Table I-2. */
178
+ export declare function riskLevel(likelihood: RiskLevel, impact: RiskLevel): RiskLevel;
179
+ /** What is done about a risk. */
180
+ export type Treatment = "accept" | "mitigate" | "transfer" | "avoid";
181
+ /** A risk as it is written: the level is computed. */
182
+ export type RiskInput = {
183
+ readonly id: string;
184
+ readonly title: string;
185
+ readonly description?: string;
186
+ readonly likelihood: RiskLevel;
187
+ readonly impact: RiskLevel;
188
+ readonly treatment: Treatment;
189
+ readonly owner: Role;
190
+ readonly reviewBy: Instant;
191
+ readonly controls?: readonly string[];
192
+ };
193
+ /** A risk with its level. */
194
+ export type Risk = RiskInput & {
195
+ readonly level: RiskLevel;
196
+ };
197
+ /** A risk past its review date at the instant the register was taken. */
198
+ export type OverdueReview = {
199
+ readonly risk: string;
200
+ readonly owner: Role;
201
+ readonly reviewBy: Instant;
202
+ };
203
+ /** A register: its risks from the greatest level to the least (then by id), and those past their review. */
204
+ export type RiskRegister = {
205
+ readonly at: Instant;
206
+ readonly risks: readonly Risk[];
207
+ readonly overdue: readonly OverdueReview[];
208
+ };
209
+ /** A risk with its level computed. */
210
+ export declare function defineRisk(r: RiskInput): Risk;
211
+ /** The register of some risks at an instant: each levelled, and each whose review date is before the instant reported overdue. */
212
+ export declare function riskRegister(risks: readonly RiskInput[], at: Instant): RiskRegister;
213
+ /** A risk as a file holds it. */
214
+ export declare const riskDecoder: Decoder<RiskInput>;
215
+ /** What enforces requirements: a control, a policy, a process, named by its id. */
216
+ export type Mechanism<R extends string = string> = {
217
+ readonly id: string;
218
+ readonly enforces: readonly R[];
219
+ };
220
+ /** A piece of evidence a mechanism gave. */
221
+ export type EvidenceLink = {
222
+ readonly mechanism: string;
223
+ readonly digest: Sha256;
224
+ };
225
+ /** Why a requirement is unproven: no mechanism enforces it, or none that does gave evidence. */
226
+ export type Unproven = "unenforced" | "unevidenced";
227
+ /** One requirement's trace: each mechanism that enforces it with the evidence it gave (digests in order, once each). */
228
+ export type RequirementTrace<R extends string = string> = {
229
+ readonly requirement: R;
230
+ readonly status: "proven" | Unproven;
231
+ readonly mechanisms: readonly {
232
+ readonly id: string;
233
+ readonly evidence: readonly Sha256[];
234
+ }[];
235
+ };
236
+ /** Every requirement's trace in the order given, and those unproven. */
237
+ export type Trace<R extends string = string> = {
238
+ readonly requirements: readonly RequirementTrace<R>[];
239
+ readonly unproven: readonly {
240
+ readonly requirement: R;
241
+ readonly reason: Unproven;
242
+ }[];
243
+ };
244
+ /** The trace of requirements to mechanisms to evidence; a requirement is proven where a mechanism that enforces it gave evidence. */
245
+ export declare function trace<const R extends string>(requirements: readonly R[], mechanisms: readonly Mechanism<NoInfer<R>>[], evidence: readonly EvidenceLink[]): Trace<R>;
246
+ /** The evidence that findings carry, as links from their controls (the mechanisms) to the digests. */
247
+ export declare function evidenceOfFindings(findings: readonly Finding[]): readonly EvidenceLink[];
package/dist/assess.js ADDED
@@ -0,0 +1,289 @@
1
+ // Spec: 0001-grc FR-010
2
+ /**
3
+ * Assessment: what findings, evidence and declarations add up to (commons 0001-grc FR-010 to FR-015). Every function is pure and takes the
4
+ * instant it judges at as a value.
5
+ *
6
+ * - **Coverage** rolls each catalog control (a requirement) or control up as `gap`, `untested`, `partial`, `addressed` or `covered` (FR-010).
7
+ * - **Freshness** holds the newest evidence to a cadence (an ISO 8601 duration): `fresh`, `due` within the last tenth of the cadence, or
8
+ * `stale`, with the instant it falls due (FR-011).
9
+ * - **Drift** compares a declared and an observed view of keyed records: added, removed and changed, each change with its field's path
10
+ * and both values, in key order (FR-012).
11
+ * - The **change-impact gate** reads declarations of paths (globs) to controls and judges a change `allowed` or `blocked`, with every
12
+ * reason (FR-013).
13
+ * - The **risk register** levels each risk by NIST SP 800-30 Rev. 1's Table I-2 and reports those past their review (FR-014).
14
+ * - The **trace** relates each requirement to the mechanisms that enforce it and the evidence they gave, and names those with none (FR-015).
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * import { riskLevel } from "./assess.ts";
19
+ * riskLevel("moderate", "very-high"); // "high"
20
+ * ```
21
+ *
22
+ * @module
23
+ */
24
+ import { absurd, array, literal, object, string } from "@intellectual-frontiers/core";
25
+ import { addDuration, compareInstants, epochMs, glob, instantDecoder, instantFromEpochMs, joinAll, latestInstant, roleDecoder, } from "./grc.js";
26
+ const byText = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
27
+ /** The findings of the newest assessment of each control and subject: for each, those with the latest `at`. */
28
+ export function newestFindings(findings) {
29
+ const latest = new Map();
30
+ for (const f of findings) {
31
+ const k = JSON.stringify([f.control.id, f.subject.kind, f.subject.id]);
32
+ const seen = latest.get(k);
33
+ if (seen === undefined || compareInstants(f.at, seen) > 0)
34
+ latest.set(k, f.at);
35
+ }
36
+ return findings.filter((f) => latest.get(JSON.stringify([f.control.id, f.subject.kind, f.subject.id])) === f.at);
37
+ }
38
+ /**
39
+ * The coverage that subjects' outcomes give, `not-applicable` ones left out: `untested` where none is left, `partial` where one is
40
+ * neither passing nor accepted, `addressed` where every one passes or is accepted and at least one is accepted, `covered` where every one
41
+ * passes.
42
+ */
43
+ export function coverageOf(outcomes) {
44
+ const applicable = outcomes.filter((o) => o !== "not-applicable");
45
+ if (applicable.length === 0)
46
+ return "untested";
47
+ if (applicable.some((o) => o !== "pass" && o !== "accepted"))
48
+ return "partial";
49
+ return applicable.includes("accepted") ? "addressed" : "covered";
50
+ }
51
+ /** Each control's coverage, in the order given, from the newest findings of each control and subject. */
52
+ export function controlCoverage(controls, findings) {
53
+ const newest = newestFindings(findings);
54
+ return controls.map((c) => {
55
+ const outcomes = newest.filter((f) => f.control.id === c.id).map((f) => f.outcome);
56
+ return { control: c.id, status: coverageOf(outcomes), outcome: joinAll(outcomes) };
57
+ });
58
+ }
59
+ /**
60
+ * Every control of a catalog as a requirement, in the catalog's order: `gap` where no control implements it, else the coverage of the
61
+ * newest findings of every control that does (`untested` where there are none).
62
+ */
63
+ export function requirementCoverage(catalog, controls, findings) {
64
+ const newest = newestFindings(findings);
65
+ return catalog.ids.map((id) => {
66
+ const implementing = controls.filter((c) => c.implements.some((r) => r.catalog === catalog.id && r.id === id)).map((c) => c.id);
67
+ const outcomes = newest.filter((f) => implementing.includes(f.control.id)).map((f) => f.outcome);
68
+ return {
69
+ requirement: catalog.control(id),
70
+ status: implementing.length === 0 ? "gap" : coverageOf(outcomes),
71
+ outcome: joinAll(outcomes),
72
+ controls: implementing,
73
+ };
74
+ });
75
+ }
76
+ /**
77
+ * The freshness at `at` of evidence observed at the given instants, held to a cadence: it falls due one cadence after the newest; it is
78
+ * `stale` after that instant, `due` in the last tenth of the cadence up to and at it, `fresh` before. No evidence at all is `stale`, due at `at`.
79
+ */
80
+ export function freshness(cadence, evidence, at) {
81
+ const newest = latestInstant(evidence);
82
+ if (newest === undefined)
83
+ return { status: "stale", cadence: cadence.text, newest: null, dueAt: at, dueFrom: at };
84
+ const dueAt = addDuration(newest, cadence);
85
+ if (dueAt === undefined)
86
+ return { status: "fresh", cadence: cadence.text, newest, dueAt: null, dueFrom: null };
87
+ const length = epochMs(dueAt) - epochMs(newest);
88
+ const dueFrom = instantFromEpochMs(epochMs(dueAt) - length / 10) ?? newest;
89
+ const status = compareInstants(at, dueAt) > 0 ? "stale" : compareInstants(at, dueFrom) >= 0 ? "due" : "fresh";
90
+ return { status, cadence: cadence.text, newest, dueAt, dueFrom };
91
+ }
92
+ /** The freshness of each control's newest finding, held to the control's cadence, in the order given. */
93
+ export function controlFreshness(controls, findings, at) {
94
+ return controls.map((c) => ({
95
+ control: c.id,
96
+ freshness: freshness(c.cadence, findings.filter((f) => f.control.id === c.id).map((f) => f.at), at),
97
+ }));
98
+ }
99
+ /** A field's path as text, `$` for the record itself: `$.ports[0]`, `$["a b"]`. */
100
+ export function formatFieldPath(path) {
101
+ return path.reduce((s, p) => (typeof p === "number" ? `${s}[${p}]` : /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(p) ? `${s}.${p}` : `${s}[${JSON.stringify(p)}]`), "$");
102
+ }
103
+ function isObject(v) {
104
+ return typeof v === "object" && v !== null && !Array.isArray(v);
105
+ }
106
+ function isList(v) {
107
+ return Array.isArray(v);
108
+ }
109
+ function sameJson(a, b) {
110
+ if (isList(a) && isList(b))
111
+ return a.length === b.length && a.every((x, i) => b[i] !== undefined && sameJson(x, b[i]));
112
+ if (isObject(a) && isObject(b)) {
113
+ const ka = Object.keys(a).sort();
114
+ const kb = Object.keys(b).sort();
115
+ return (ka.length === kb.length &&
116
+ ka.every((k, i) => {
117
+ const x = a[k];
118
+ const y = b[k];
119
+ return k === kb[i] && x !== undefined && y !== undefined && sameJson(x, y);
120
+ }));
121
+ }
122
+ return a === b;
123
+ }
124
+ function change(path, declared, observed) {
125
+ return {
126
+ path,
127
+ field: formatFieldPath(path),
128
+ ...(declared === undefined ? {} : { declared }),
129
+ ...(observed === undefined ? {} : { observed }),
130
+ };
131
+ }
132
+ function diff(path, a, b, out) {
133
+ if (a === undefined || b === undefined) {
134
+ if (a !== b)
135
+ out.push(change(path, a, b));
136
+ return;
137
+ }
138
+ if (isObject(a) && isObject(b)) {
139
+ for (const k of [...new Set([...Object.keys(a), ...Object.keys(b)])].sort())
140
+ diff([...path, k], a[k], b[k], out);
141
+ }
142
+ else if (isList(a) && isList(b)) {
143
+ for (let i = 0; i < Math.max(a.length, b.length); i++)
144
+ diff([...path, i], a[i], b[i], out);
145
+ }
146
+ else if (!sameJson(a, b))
147
+ out.push(change(path, a, b));
148
+ }
149
+ /** The field changes between two values: objects compared member by member in key order, arrays index by index, anything else whole. */
150
+ export function fieldChanges(declared, observed) {
151
+ const out = [];
152
+ diff([], declared, observed, out);
153
+ return out;
154
+ }
155
+ function entriesOf(view) {
156
+ return view instanceof Map ? view : new Map(Object.entries(view));
157
+ }
158
+ /** The drift from what is declared to what is observed: records only observed are added, only declared removed, in both but different changed. */
159
+ export function drift(declared, observed) {
160
+ const d = entriesOf(declared);
161
+ const o = entriesOf(observed);
162
+ const keys = [...new Set([...d.keys(), ...o.keys()])].sort(byText);
163
+ const added = [];
164
+ const removed = [];
165
+ const changed = [];
166
+ for (const key of keys) {
167
+ const a = d.get(key);
168
+ const b = o.get(key);
169
+ if (a === undefined && b !== undefined)
170
+ added.push({ key, value: b });
171
+ else if (b === undefined && a !== undefined)
172
+ removed.push({ key, value: a });
173
+ else if (a !== undefined && b !== undefined) {
174
+ const changes = fieldChanges(a, b);
175
+ if (changes.length > 0)
176
+ changed.push({ key, changes });
177
+ }
178
+ }
179
+ return { added, removed, changed };
180
+ }
181
+ /** A gate reason as one sentence. */
182
+ export function formatGateReason(r) {
183
+ switch (r.kind) {
184
+ case "control":
185
+ return `control ${r.control} is ${r.outcome} and the change touches ${r.paths.join(", ")}`;
186
+ case "review":
187
+ return `the change needs a review by ${r.role}, not given`;
188
+ default:
189
+ return absurd(r);
190
+ }
191
+ }
192
+ /** Each control's newest outcome: the join of its newest findings' outcomes. */
193
+ export function newestOutcomes(findings) {
194
+ const groups = new Map();
195
+ for (const f of newestFindings(findings))
196
+ groups.set(f.control.id, [...(groups.get(f.control.id) ?? []), f.outcome]);
197
+ return new Map([...groups].map(([k, v]) => [k, joinAll(v)]));
198
+ }
199
+ /**
200
+ * A change judged against the declarations and each control's newest outcome: `blocked` where a touched path is declared for a control
201
+ * whose outcome is `fail`, `error` or `gap` (a control with no outcome does not block), or where a review the change needs was not given;
202
+ * else `allowed`. Reasons: controls in id order, then reviews in role order.
203
+ */
204
+ export function gate(declarations, change, outcomes) {
205
+ const compiled = declarations.map((d) => ({ globs: d.paths.map(glob), controls: d.controls }));
206
+ const byControl = new Map();
207
+ for (const path of change.paths)
208
+ for (const d of compiled)
209
+ if (d.globs.some((g) => g.test(path)))
210
+ for (const c of d.controls)
211
+ byControl.set(c, (byControl.get(c) ?? new Set()).add(path));
212
+ const touched = [...byControl.keys()]
213
+ .sort(byText)
214
+ .map((control) => ({ control, paths: [...(byControl.get(control) ?? [])].sort(byText) }));
215
+ const reasons = [];
216
+ for (const t of touched) {
217
+ const outcome = outcomes.get(t.control);
218
+ if (outcome === "fail" || outcome === "error" || outcome === "gap")
219
+ reasons.push({ kind: "control", control: t.control, outcome, paths: t.paths });
220
+ }
221
+ const given = new Set(change.reviewedBy ?? []);
222
+ for (const role of [...new Set(change.needsReview ?? [])].sort(byText))
223
+ if (!given.has(role))
224
+ reasons.push({ kind: "review", role });
225
+ const [first, ...rest] = reasons;
226
+ return first === undefined ? { kind: "allowed", touched } : { kind: "blocked", touched, reasons: [first, ...rest] };
227
+ }
228
+ /** An impact declaration as a file holds it. */
229
+ export const impactDeclarationDecoder = object({ paths: array(string), controls: array(string) });
230
+ // ---------------------------------------------------------------------------------------------------------------------------- risk (FR-014)
231
+ /** NIST SP 800-30's five qualitative levels, from the least to the greatest. */
232
+ export const RISK_LEVELS = ["very-low", "low", "moderate", "high", "very-high"];
233
+ /**
234
+ * NIST SP 800-30 Rev. 1, Table I-2, "Assessment scale – level of risk (combination of likelihood and impact)": the level of risk for a
235
+ * likelihood (the row) and an impact (the column).
236
+ */
237
+ export const RISK_MATRIX = {
238
+ "very-high": { "very-low": "very-low", low: "low", moderate: "moderate", high: "high", "very-high": "very-high" },
239
+ high: { "very-low": "very-low", low: "low", moderate: "moderate", high: "high", "very-high": "very-high" },
240
+ moderate: { "very-low": "very-low", low: "low", moderate: "moderate", high: "moderate", "very-high": "high" },
241
+ low: { "very-low": "very-low", low: "low", moderate: "low", high: "low", "very-high": "moderate" },
242
+ "very-low": { "very-low": "very-low", low: "very-low", moderate: "very-low", high: "low", "very-high": "low" },
243
+ };
244
+ /** The level of risk of a likelihood and an impact, by Table I-2. */
245
+ export function riskLevel(likelihood, impact) {
246
+ return RISK_MATRIX[likelihood][impact];
247
+ }
248
+ /** A risk with its level computed. */
249
+ export function defineRisk(r) {
250
+ return { ...r, level: riskLevel(r.likelihood, r.impact) };
251
+ }
252
+ /** The register of some risks at an instant: each levelled, and each whose review date is before the instant reported overdue. */
253
+ export function riskRegister(risks, at) {
254
+ const levelled = risks.map(defineRisk).sort((a, b) => RISK_LEVELS.indexOf(b.level) - RISK_LEVELS.indexOf(a.level) || byText(a.id, b.id));
255
+ const overdue = levelled
256
+ .filter((r) => compareInstants(r.reviewBy, at) < 0)
257
+ .map((r) => ({ risk: r.id, owner: r.owner, reviewBy: r.reviewBy }));
258
+ return { at, risks: levelled, overdue };
259
+ }
260
+ const levelDecoder = literal(...RISK_LEVELS);
261
+ /** A risk as a file holds it. */
262
+ export const riskDecoder = object({
263
+ id: string,
264
+ title: string,
265
+ likelihood: levelDecoder,
266
+ impact: levelDecoder,
267
+ treatment: literal("accept", "mitigate", "transfer", "avoid"),
268
+ owner: roleDecoder,
269
+ reviewBy: instantDecoder,
270
+ }, { description: string, controls: array(string) });
271
+ /** The trace of requirements to mechanisms to evidence; a requirement is proven where a mechanism that enforces it gave evidence. */
272
+ export function trace(requirements, mechanisms, evidence) {
273
+ const byMechanism = new Map();
274
+ for (const e of evidence)
275
+ byMechanism.set(e.mechanism, (byMechanism.get(e.mechanism) ?? new Set()).add(e.digest));
276
+ const traces = requirements.map((requirement) => {
277
+ const ms = mechanisms
278
+ .filter((m) => m.enforces.includes(requirement))
279
+ .map((m) => ({ id: m.id, evidence: [...(byMechanism.get(m.id) ?? [])].sort(byText) }));
280
+ const status = ms.length === 0 ? "unenforced" : ms.some((m) => m.evidence.length > 0) ? "proven" : "unevidenced";
281
+ return { requirement, status, mechanisms: ms };
282
+ });
283
+ const unproven = traces.flatMap((t) => (t.status === "proven" ? [] : [{ requirement: t.requirement, reason: t.status }]));
284
+ return { requirements: traces, unproven };
285
+ }
286
+ /** The evidence that findings carry, as links from their controls (the mechanisms) to the digests. */
287
+ export function evidenceOfFindings(findings) {
288
+ return findings.flatMap((f) => f.evidence.map((digest) => ({ mechanism: f.control.id, digest })));
289
+ }