@shieldaai/security-watch 0.0.0-stage → 1.0.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/CHANGELOG.md +170 -0
- package/CONTRIBUTING.md +92 -0
- package/LICENSE +202 -0
- package/README.md +394 -2
- package/SECURITY.md +62 -0
- package/dist/assessment.d.ts +16 -0
- package/dist/assessment.js +569 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +1105 -0
- package/dist/config.d.ts +302 -0
- package/dist/config.js +381 -0
- package/dist/coverage.d.ts +4 -0
- package/dist/coverage.js +11 -0
- package/dist/cve-now.d.ts +35 -0
- package/dist/cve-now.js +1002 -0
- package/dist/cvss4.d.ts +3 -0
- package/dist/cvss4.js +39 -0
- package/dist/delivery.d.ts +58 -0
- package/dist/delivery.js +687 -0
- package/dist/ecosystems.d.ts +48 -0
- package/dist/ecosystems.js +332 -0
- package/dist/engine.d.ts +80 -0
- package/dist/engine.js +388 -0
- package/dist/everyday-words.d.ts +11 -0
- package/dist/everyday-words.js +256 -0
- package/dist/health.d.ts +24 -0
- package/dist/health.js +122 -0
- package/dist/heartbeat.d.ts +13 -0
- package/dist/heartbeat.js +74 -0
- package/dist/http.d.ts +15 -0
- package/dist/http.js +280 -0
- package/dist/index.d.ts +36 -0
- package/dist/index.js +23 -0
- package/dist/inventory-evidence.d.ts +10 -0
- package/dist/inventory-evidence.js +206 -0
- package/dist/inventory.d.ts +276 -0
- package/dist/inventory.js +336 -0
- package/dist/lock.d.ts +3 -0
- package/dist/lock.js +112 -0
- package/dist/maintenance.d.ts +48 -0
- package/dist/maintenance.js +295 -0
- package/dist/matching.d.ts +29 -0
- package/dist/matching.js +537 -0
- package/dist/models.d.ts +33 -0
- package/dist/models.js +932 -0
- package/dist/operations.d.ts +17 -0
- package/dist/operations.js +117 -0
- package/dist/pilot-cases.d.ts +171 -0
- package/dist/pilot-cases.js +330 -0
- package/dist/pilot-input.d.ts +16 -0
- package/dist/pilot-input.js +125 -0
- package/dist/pilot-recall.d.ts +166 -0
- package/dist/pilot-recall.js +231 -0
- package/dist/pilot-report.d.ts +113 -0
- package/dist/pilot-report.js +279 -0
- package/dist/pilot-responses.d.ts +111 -0
- package/dist/pilot-responses.js +159 -0
- package/dist/providers.d.ts +209 -0
- package/dist/providers.js +459 -0
- package/dist/python-version.d.ts +3 -0
- package/dist/python-version.js +30 -0
- package/dist/rehearsal.d.ts +440 -0
- package/dist/rehearsal.js +372 -0
- package/dist/sbom.d.ts +13 -0
- package/dist/sbom.js +193 -0
- package/dist/setup.d.ts +113 -0
- package/dist/setup.js +100 -0
- package/dist/source-error.d.ts +38 -0
- package/dist/source-error.js +71 -0
- package/dist/sources.d.ts +3 -0
- package/dist/sources.js +1725 -0
- package/dist/store.d.ts +96 -0
- package/dist/store.js +953 -0
- package/dist/types.d.ts +404 -0
- package/dist/types.js +1 -0
- package/dist/util.d.ts +29 -0
- package/dist/util.js +94 -0
- package/dist/vendor/cvss4-reference.d.ts +2 -0
- package/dist/vendor/cvss4-reference.js +789 -0
- package/dist/vendor-sources.d.ts +24 -0
- package/dist/vendor-sources.js +56 -0
- package/dist/word-filter.d.ts +3 -0
- package/dist/word-filter.js +3291 -0
- package/docs/alert-outcome-evaluation.md +150 -0
- package/docs/compatibility.md +35 -0
- package/docs/configuration.md +666 -0
- package/docs/cvss-v4-support.md +41 -0
- package/docs/offline-advisory-preview.md +114 -0
- package/docs/offline-rehearsal.md +44 -0
- package/docs/pilot-cases.md +58 -0
- package/docs/pilot-recall.md +124 -0
- package/docs/pilot-report.md +52 -0
- package/docs/validation/alert-outcome-evaluation-2026-11-05.json +2935 -0
- package/docs/validation/cvss-v4-reference-parity-2026-11-05.json +93 -0
- package/docs/validation/rehearsal-accepted-2026-11-05.json +175 -0
- package/docs/validation/rehearsal-unknown-2026-11-05.json +175 -0
- package/docs/vendor/cvss-v4-LICENSE.txt +22 -0
- package/docs/vendor/cvss-v4-provenance.json +38 -0
- package/examples/advisories.json +17 -0
- package/examples/agent-advisories-2026.json +145 -0
- package/examples/agent-advisory-cases-2026.json +397 -0
- package/examples/common-systems.yaml +243 -0
- package/examples/libraries.example.txt +18 -0
- package/examples/libraries.example.yaml +40 -0
- package/examples/library-watch.example.yaml +27 -0
- package/examples/offline-advisory-preview.mjs +42 -0
- package/examples/rehearsal.json +75 -0
- package/examples/security-watch.example.yaml +86 -0
- package/examples/systems.example.yaml +35 -0
- package/package.json +85 -4
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { Config } from './types.js';
|
|
2
|
+
import type { Store } from './store.js';
|
|
3
|
+
export interface MaintenanceRun {
|
|
4
|
+
ok: boolean;
|
|
5
|
+
attempted_at: string;
|
|
6
|
+
last_success_at: string | null;
|
|
7
|
+
backup_created: boolean;
|
|
8
|
+
backups_removed: number;
|
|
9
|
+
rows_removed: number;
|
|
10
|
+
more_available: boolean;
|
|
11
|
+
error: string | null;
|
|
12
|
+
}
|
|
13
|
+
/** Opt-in maintenance. Backups are verified before rotation or retention removes anything. */
|
|
14
|
+
export declare class MaintenanceScheduler {
|
|
15
|
+
private nextAt;
|
|
16
|
+
tick(store: Store, config: Config, now?: number): Promise<MaintenanceRun | undefined>;
|
|
17
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { linkSync, lstatSync, mkdirSync, mkdtempSync, opendirSync, rmSync, unlinkSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { verifyBackup } from './maintenance.js';
|
|
5
|
+
function backupFiles(directory) {
|
|
6
|
+
const result = [];
|
|
7
|
+
const folder = opendirSync(directory);
|
|
8
|
+
try {
|
|
9
|
+
let count = 0;
|
|
10
|
+
for (let entry = folder.readSync(); entry; entry = folder.readSync()) {
|
|
11
|
+
if (++count > 10_000)
|
|
12
|
+
throw new Error('Backup directory contains too many entries');
|
|
13
|
+
if (!/^security-watch-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-[a-f0-9-]{36}\.db$/.test(entry.name))
|
|
14
|
+
continue;
|
|
15
|
+
const stat = lstatSync(join(directory, entry.name));
|
|
16
|
+
if (!stat.isFile() || stat.nlink !== 1 || (process.platform !== 'win32' && stat.mode & 0o077))
|
|
17
|
+
throw new Error('Backup files must be private regular files without links');
|
|
18
|
+
result.push(entry.name);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
finally {
|
|
22
|
+
folder.closeSync();
|
|
23
|
+
}
|
|
24
|
+
return result.sort().reverse();
|
|
25
|
+
}
|
|
26
|
+
function savedRun(store) {
|
|
27
|
+
const raw = store.getMeta('maintenance:last_run');
|
|
28
|
+
try {
|
|
29
|
+
const parsed = JSON.parse(raw ?? 'null');
|
|
30
|
+
if (parsed &&
|
|
31
|
+
typeof parsed === 'object' &&
|
|
32
|
+
'ok' in parsed &&
|
|
33
|
+
typeof parsed.ok === 'boolean' &&
|
|
34
|
+
'attempted_at' in parsed &&
|
|
35
|
+
typeof parsed.attempted_at === 'string' &&
|
|
36
|
+
Number.isFinite(Date.parse(parsed.attempted_at)))
|
|
37
|
+
return parsed;
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
// Invalid history does not postpone maintenance indefinitely.
|
|
41
|
+
}
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
/** Opt-in maintenance. Backups are verified before rotation or retention removes anything. */
|
|
45
|
+
export class MaintenanceScheduler {
|
|
46
|
+
nextAt = 0;
|
|
47
|
+
async tick(store, config, now = Date.now()) {
|
|
48
|
+
const settings = config.maintenance;
|
|
49
|
+
if (!settings)
|
|
50
|
+
return undefined;
|
|
51
|
+
const previous = savedRun(store);
|
|
52
|
+
if (!this.nextAt && previous) {
|
|
53
|
+
const attempted = Date.parse(previous.attempted_at);
|
|
54
|
+
if (attempted <= now)
|
|
55
|
+
this.nextAt =
|
|
56
|
+
attempted +
|
|
57
|
+
(previous.ok ? settings.interval_hours : Math.min(settings.interval_hours, 1)) * 3_600_000;
|
|
58
|
+
}
|
|
59
|
+
if (now < this.nextAt)
|
|
60
|
+
return undefined;
|
|
61
|
+
this.nextAt = now + Math.min(settings.interval_hours, 1) * 3_600_000;
|
|
62
|
+
const report = {
|
|
63
|
+
ok: false,
|
|
64
|
+
attempted_at: new Date(now).toISOString(),
|
|
65
|
+
last_success_at: typeof previous?.last_success_at === 'string' ? previous.last_success_at : null,
|
|
66
|
+
backup_created: false,
|
|
67
|
+
backups_removed: 0,
|
|
68
|
+
rows_removed: 0,
|
|
69
|
+
more_available: false,
|
|
70
|
+
error: null,
|
|
71
|
+
};
|
|
72
|
+
try {
|
|
73
|
+
if (settings.backup) {
|
|
74
|
+
const { directory, max_bytes } = settings.backup;
|
|
75
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
76
|
+
const folder = lstatSync(directory);
|
|
77
|
+
if (!folder.isDirectory() ||
|
|
78
|
+
folder.isSymbolicLink() ||
|
|
79
|
+
(process.platform !== 'win32' && folder.mode & 0o077))
|
|
80
|
+
throw new Error('Backup directory must be private');
|
|
81
|
+
backupFiles(directory);
|
|
82
|
+
const filename = `security-watch-${report.attempted_at.replace(/[:.]/g, '-')}-${randomUUID()}.db`;
|
|
83
|
+
const path = join(directory, filename);
|
|
84
|
+
const temporary = mkdtempSync(join(directory, '.verify-backup-'));
|
|
85
|
+
try {
|
|
86
|
+
const candidate = join(temporary, 'snapshot.db');
|
|
87
|
+
await store.backup(candidate);
|
|
88
|
+
await verifyBackup(candidate, { max_bytes });
|
|
89
|
+
linkSync(candidate, path);
|
|
90
|
+
}
|
|
91
|
+
finally {
|
|
92
|
+
rmSync(temporary, { recursive: true, force: true });
|
|
93
|
+
}
|
|
94
|
+
report.backup_created = true;
|
|
95
|
+
for (const old of backupFiles(directory)
|
|
96
|
+
.filter((name) => name !== filename)
|
|
97
|
+
.slice(settings.backup.keep - 1)) {
|
|
98
|
+
unlinkSync(join(directory, old));
|
|
99
|
+
report.backups_removed++;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
if (settings.retention) {
|
|
103
|
+
const pruning = store.prune(settings.retention, now, true);
|
|
104
|
+
report.rows_removed = pruning.total;
|
|
105
|
+
report.more_available = pruning.more_available;
|
|
106
|
+
}
|
|
107
|
+
report.ok = true;
|
|
108
|
+
report.last_success_at = report.attempted_at;
|
|
109
|
+
this.nextAt = now + settings.interval_hours * 3_600_000;
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
report.error = 'Maintenance failed. Check storage space, backup permissions and retention settings.';
|
|
113
|
+
}
|
|
114
|
+
store.setMeta('maintenance:last_run', JSON.stringify(report));
|
|
115
|
+
return report;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { type PilotWindow } from './pilot-report.js';
|
|
3
|
+
declare const feedbackSchema: z.ZodObject<{
|
|
4
|
+
version: z.ZodLiteral<1>;
|
|
5
|
+
packet_id: z.ZodString;
|
|
6
|
+
reviews: z.ZodArray<z.ZodObject<{
|
|
7
|
+
case_id: z.ZodString;
|
|
8
|
+
reviewer: z.ZodString;
|
|
9
|
+
blinded: z.ZodLiteral<true>;
|
|
10
|
+
label: z.ZodEnum<{
|
|
11
|
+
abstain: "abstain";
|
|
12
|
+
benign: "benign";
|
|
13
|
+
must_review: "must_review";
|
|
14
|
+
urgent: "urgent";
|
|
15
|
+
}>;
|
|
16
|
+
}, z.core.$strict>>;
|
|
17
|
+
adjudications: z.ZodArray<z.ZodObject<{
|
|
18
|
+
case_id: z.ZodString;
|
|
19
|
+
adjudicator: z.ZodString;
|
|
20
|
+
label: z.ZodEnum<{
|
|
21
|
+
abstain: "abstain";
|
|
22
|
+
benign: "benign";
|
|
23
|
+
must_review: "must_review";
|
|
24
|
+
urgent: "urgent";
|
|
25
|
+
}>;
|
|
26
|
+
}, z.core.$strict>>;
|
|
27
|
+
}, z.core.$strict>;
|
|
28
|
+
export type PilotFeedback = z.infer<typeof feedbackSchema>;
|
|
29
|
+
declare const lookup: z.ZodObject<{
|
|
30
|
+
event_ref: z.ZodString;
|
|
31
|
+
system_ref: z.ZodString;
|
|
32
|
+
component_ref: z.ZodNullable<z.ZodString>;
|
|
33
|
+
evidence_refs: z.ZodArray<z.ZodString>;
|
|
34
|
+
}, z.core.$strict>;
|
|
35
|
+
type Case = z.infer<typeof lookup> & {
|
|
36
|
+
case_id: string;
|
|
37
|
+
recorded_at: string;
|
|
38
|
+
};
|
|
39
|
+
export interface PilotCasePacket {
|
|
40
|
+
version: 1;
|
|
41
|
+
mode: 'private_pilot_cases';
|
|
42
|
+
packet_id: string;
|
|
43
|
+
window: PilotWindow;
|
|
44
|
+
excluded_revisions: number;
|
|
45
|
+
cases: Case[];
|
|
46
|
+
}
|
|
47
|
+
declare const deliveryJob: z.ZodObject<{
|
|
48
|
+
channel: z.ZodEnum<{
|
|
49
|
+
email: "email";
|
|
50
|
+
slack: "slack";
|
|
51
|
+
}>;
|
|
52
|
+
mode: z.ZodEnum<{
|
|
53
|
+
digest: "digest";
|
|
54
|
+
notify: "notify";
|
|
55
|
+
}>;
|
|
56
|
+
status: z.ZodEnum<{
|
|
57
|
+
accepted: "accepted";
|
|
58
|
+
failed: "failed";
|
|
59
|
+
pending: "pending";
|
|
60
|
+
sending: "sending";
|
|
61
|
+
unknown: "unknown";
|
|
62
|
+
}>;
|
|
63
|
+
accepted_at: z.ZodNullable<z.ZodNumber>;
|
|
64
|
+
}, z.core.$strip>;
|
|
65
|
+
type DeliveryRevision = Pick<Case, 'event_ref' | 'system_ref' | 'component_ref'> & {
|
|
66
|
+
jobs: z.infer<typeof deliveryJob>[];
|
|
67
|
+
};
|
|
68
|
+
type Cohort = {
|
|
69
|
+
packet: PilotCasePacket;
|
|
70
|
+
routes: Map<string, {
|
|
71
|
+
immediate: boolean;
|
|
72
|
+
quiet: boolean;
|
|
73
|
+
}>;
|
|
74
|
+
deliveryRevisions: DeliveryRevision[];
|
|
75
|
+
};
|
|
76
|
+
export declare function loadPilotCohort(backup: string, window: PilotWindow, includeDelivery?: boolean): Promise<Cohort>;
|
|
77
|
+
/** Private local research pointers suitable for blinded review by authorized analysts. */
|
|
78
|
+
export declare function createPilotCasePacket(backup: string, window: PilotWindow): Promise<PilotCasePacket>;
|
|
79
|
+
export declare function readPilotFeedback(path: string): PilotFeedback;
|
|
80
|
+
export declare function metric(numerator: number, denominator: number): {
|
|
81
|
+
numerator: number;
|
|
82
|
+
denominator: number;
|
|
83
|
+
rate: number | null;
|
|
84
|
+
};
|
|
85
|
+
export declare function latencySummary(samples: number[]): {
|
|
86
|
+
count: number;
|
|
87
|
+
median_ms: number | null;
|
|
88
|
+
p95_ms: number | null;
|
|
89
|
+
};
|
|
90
|
+
type RouteScope = Pick<PilotCasePacket, 'packet_id' | 'window' | 'excluded_revisions'>;
|
|
91
|
+
declare function grade(packet: RouteScope, routes: Cohort['routes'], feedback: PilotFeedback, evidenceDisagreements?: ReadonlySet<string>): {
|
|
92
|
+
version: 1;
|
|
93
|
+
mode: 'pilot_score';
|
|
94
|
+
window: PilotWindow;
|
|
95
|
+
coverage: {
|
|
96
|
+
eligible: number;
|
|
97
|
+
excluded: number;
|
|
98
|
+
unreviewed: number;
|
|
99
|
+
single_review: number;
|
|
100
|
+
agreements: number;
|
|
101
|
+
disagreements: number;
|
|
102
|
+
adjudicated: number;
|
|
103
|
+
unresolved_conflicts: number;
|
|
104
|
+
abstained: number;
|
|
105
|
+
scored: number;
|
|
106
|
+
};
|
|
107
|
+
policy: {
|
|
108
|
+
urgent_immediate: {
|
|
109
|
+
numerator: number;
|
|
110
|
+
denominator: number;
|
|
111
|
+
rate: number | null;
|
|
112
|
+
};
|
|
113
|
+
quiet_risk: {
|
|
114
|
+
numerator: number;
|
|
115
|
+
denominator: number;
|
|
116
|
+
rate: number | null;
|
|
117
|
+
};
|
|
118
|
+
unnecessary_immediate: {
|
|
119
|
+
numerator: number;
|
|
120
|
+
denominator: number;
|
|
121
|
+
rate: number | null;
|
|
122
|
+
};
|
|
123
|
+
};
|
|
124
|
+
unmeasured: {
|
|
125
|
+
population_urgent_recall: null;
|
|
126
|
+
delivered_false_alert_rate: null;
|
|
127
|
+
};
|
|
128
|
+
};
|
|
129
|
+
export type PilotScore = ReturnType<typeof grade>;
|
|
130
|
+
/** Internal replay hook for a frozen external roster. The caller accounts for every enrolled target. */
|
|
131
|
+
export declare function gradePilotRoutes(scope: RouteScope, routes: Cohort['routes'], feedback: PilotFeedback, evidenceDisagreements: ReadonlySet<string>): {
|
|
132
|
+
version: 1;
|
|
133
|
+
mode: 'pilot_score';
|
|
134
|
+
window: PilotWindow;
|
|
135
|
+
coverage: {
|
|
136
|
+
eligible: number;
|
|
137
|
+
excluded: number;
|
|
138
|
+
unreviewed: number;
|
|
139
|
+
single_review: number;
|
|
140
|
+
agreements: number;
|
|
141
|
+
disagreements: number;
|
|
142
|
+
adjudicated: number;
|
|
143
|
+
unresolved_conflicts: number;
|
|
144
|
+
abstained: number;
|
|
145
|
+
scored: number;
|
|
146
|
+
};
|
|
147
|
+
policy: {
|
|
148
|
+
urgent_immediate: {
|
|
149
|
+
numerator: number;
|
|
150
|
+
denominator: number;
|
|
151
|
+
rate: number | null;
|
|
152
|
+
};
|
|
153
|
+
quiet_risk: {
|
|
154
|
+
numerator: number;
|
|
155
|
+
denominator: number;
|
|
156
|
+
rate: number | null;
|
|
157
|
+
};
|
|
158
|
+
unnecessary_immediate: {
|
|
159
|
+
numerator: number;
|
|
160
|
+
denominator: number;
|
|
161
|
+
rate: number | null;
|
|
162
|
+
};
|
|
163
|
+
};
|
|
164
|
+
unmeasured: {
|
|
165
|
+
population_urgent_recall: null;
|
|
166
|
+
delivered_false_alert_rate: null;
|
|
167
|
+
};
|
|
168
|
+
};
|
|
169
|
+
/** Aggregate policy quality on the resolved subset of a frozen, explicitly accounted-for revision cohort. */
|
|
170
|
+
export declare function scorePilotCases(backup: string, window: PilotWindow, feedback: PilotFeedback): Promise<PilotScore>;
|
|
171
|
+
export {};
|
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { capturePilotWindow, dataArray, dataFields, readPrivatePilotJson } from './pilot-input.js';
|
|
3
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
import { withPrivatePilotBackup } from './maintenance.js';
|
|
6
|
+
import { PilotReportError, validatePilotWindow } from './pilot-report.js';
|
|
7
|
+
const MAX_REVISIONS = 1000;
|
|
8
|
+
const reference = z
|
|
9
|
+
.string()
|
|
10
|
+
.min(1)
|
|
11
|
+
.max(512)
|
|
12
|
+
.regex(/^[^\u0000-\u001f\u007f]+$/u);
|
|
13
|
+
const id = z.string().regex(/^[a-f0-9]{64}$/u);
|
|
14
|
+
// The pilot owner provisions one canonical opaque handle per person. Reject alternative spellings.
|
|
15
|
+
const reviewer = z.string().regex(/^[a-z][a-z0-9_-]{0,63}$/u);
|
|
16
|
+
const label = z.enum(['urgent', 'must_review', 'benign', 'abstain']);
|
|
17
|
+
const review = z.strictObject({ case_id: id, reviewer, blinded: z.literal(true), label });
|
|
18
|
+
const adjudication = z.strictObject({ case_id: id, adjudicator: reviewer, label });
|
|
19
|
+
const feedbackSchema = z.strictObject({
|
|
20
|
+
version: z.literal(1),
|
|
21
|
+
packet_id: id,
|
|
22
|
+
reviews: z.array(review).max(2 * MAX_REVISIONS),
|
|
23
|
+
adjudications: z.array(adjudication).max(MAX_REVISIONS),
|
|
24
|
+
});
|
|
25
|
+
const decision = z.object({
|
|
26
|
+
action: z.enum(['notify', 'digest', 'record']),
|
|
27
|
+
channels: z.array(z.enum(['slack', 'email'])).max(2),
|
|
28
|
+
review: z.enum(['ai_general_news', 'ai_not_affected', 'ai_irrelevant']).optional(),
|
|
29
|
+
});
|
|
30
|
+
const lookup = z.strictObject({
|
|
31
|
+
event_ref: reference,
|
|
32
|
+
system_ref: reference,
|
|
33
|
+
component_ref: reference.nullable(),
|
|
34
|
+
evidence_refs: z.array(reference).max(64),
|
|
35
|
+
});
|
|
36
|
+
const deliveryJob = z.object({
|
|
37
|
+
channel: z.enum(['slack', 'email']),
|
|
38
|
+
mode: z.enum(['notify', 'digest']),
|
|
39
|
+
status: z.enum(['pending', 'sending', 'accepted', 'unknown', 'failed']),
|
|
40
|
+
accepted_at: z.number().int().nonnegative().max(8.64e15).nullable(),
|
|
41
|
+
});
|
|
42
|
+
function invalidFeedback() {
|
|
43
|
+
throw new PilotReportError('labels');
|
|
44
|
+
}
|
|
45
|
+
function readCohort(db, sourceHash, range, includeDelivery) {
|
|
46
|
+
const { start, end, from, until } = range;
|
|
47
|
+
// A retry or digest for an older revision may first be accepted inside this study window.
|
|
48
|
+
const priorRevisions = includeDelivery
|
|
49
|
+
? `UNION ALL SELECT r.finding_id,r.revision,r.recorded_at,r.payload,r.decision
|
|
50
|
+
FROM (SELECT DISTINCT finding_id,revision FROM notifications WHERE accepted_at>=? AND accepted_at<?) n
|
|
51
|
+
JOIN finding_revisions r USING(finding_id,revision) WHERE r.recorded_at>0 AND r.recorded_at<?`
|
|
52
|
+
: '';
|
|
53
|
+
const revisions = `SELECT finding_id,revision,recorded_at,payload,decision FROM finding_revisions
|
|
54
|
+
WHERE recorded_at>0 AND recorded_at>=? AND recorded_at<? ${priorRevisions}`;
|
|
55
|
+
const params = includeDelivery ? [start, end, start, end, start] : [start, end];
|
|
56
|
+
if (includeDelivery &&
|
|
57
|
+
db
|
|
58
|
+
.prepare('SELECT 1 FROM notifications WHERE accepted_at>=? AND accepted_at<? LIMIT 1 OFFSET ?')
|
|
59
|
+
.get(start, end, 2 * MAX_REVISIONS))
|
|
60
|
+
throw new PilotReportError('bounds');
|
|
61
|
+
// Sample all eligible revisions in the chosen period or reject it. A truncated prefix biases scoring.
|
|
62
|
+
const counted = db
|
|
63
|
+
.prepare(`SELECT COUNT(*) AS n, MAX(bytes) AS max_bytes, SUM(bytes) AS total_bytes, MAX(decision_bytes) AS max_decision FROM (
|
|
64
|
+
SELECT length(CAST(payload AS BLOB)) AS bytes, length(CAST(decision AS BLOB)) AS decision_bytes
|
|
65
|
+
FROM (${revisions}) LIMIT ?)`)
|
|
66
|
+
.get(...params, MAX_REVISIONS + 1);
|
|
67
|
+
if (Number(counted.n) > MAX_REVISIONS ||
|
|
68
|
+
Number(counted.max_bytes) > 256 * 1024 ||
|
|
69
|
+
Number(counted.total_bytes) > 32 * 1024 * 1024 ||
|
|
70
|
+
Number(counted.max_decision) > 16384)
|
|
71
|
+
throw new PilotReportError('bounds');
|
|
72
|
+
const digest = (...parts) => createHash('sha256').update(JSON.stringify(parts)).digest('hex');
|
|
73
|
+
const packetId = digest('security-watch.pilot-cases.v1', sourceHash, from, until);
|
|
74
|
+
const packet = {
|
|
75
|
+
version: 1,
|
|
76
|
+
mode: 'private_pilot_cases',
|
|
77
|
+
packet_id: packetId,
|
|
78
|
+
window: { from, until },
|
|
79
|
+
excluded_revisions: 0,
|
|
80
|
+
cases: [],
|
|
81
|
+
};
|
|
82
|
+
const routes = new Map();
|
|
83
|
+
const deliveryRevisions = [];
|
|
84
|
+
// Read only typed metadata for the two possible channels on each exact immutable revision.
|
|
85
|
+
const jobsForRevision = includeDelivery
|
|
86
|
+
? db.prepare(`SELECT channel,status,accepted_at,length(CAST(payload AS BLOB)) AS bytes,
|
|
87
|
+
CASE WHEN length(CAST(payload AS BLOB))<=524288 THEN json_extract(payload,'$.mode') END AS mode,
|
|
88
|
+
CASE WHEN length(CAST(payload AS BLOB))<=524288 THEN
|
|
89
|
+
json_extract(payload,'$.assessment.id') IS ? AND json_extract(payload,'$.assessment.event_id') IS ?
|
|
90
|
+
AND json_extract(payload,'$.assessment.system_id') IS ? AND json_extract(payload,'$.assessment.component_id') IS ?
|
|
91
|
+
END AS same_target
|
|
92
|
+
FROM notifications WHERE finding_id=? AND revision=? AND (? OR (accepted_at>=? AND accepted_at<?)) LIMIT 3`)
|
|
93
|
+
: undefined;
|
|
94
|
+
let notificationBytes = 0;
|
|
95
|
+
// Only the coordinator's verified copy is opened. Actual model conclusions and reference labels never enter the packet.
|
|
96
|
+
for (const row of db
|
|
97
|
+
.prepare(`SELECT finding_id, revision, recorded_at,
|
|
98
|
+
json_extract(decision,'$.action') AS action, json_extract(decision,'$.review') AS review,
|
|
99
|
+
json_type(decision,'$.channels') AS channels_kind, json_extract(decision,'$.channels') AS channels,
|
|
100
|
+
json_type(payload,'$.evidence_ids') AS evidence_kind,
|
|
101
|
+
json_extract(payload,'$.id') AS saved_id, json_extract(payload,'$.category') AS category,
|
|
102
|
+
json_type(payload,'$.active') AS active, json_type(payload,'$.withdrawn') AS withdrawn,
|
|
103
|
+
json_extract(payload,'$.event_id') AS event_ref,json_extract(payload,'$.system_id') AS system_ref,
|
|
104
|
+
json_extract(payload,'$.component_id') AS component_ref,json_extract(payload,'$.evidence_ids') AS evidence_refs
|
|
105
|
+
FROM (${revisions}) ORDER BY recorded_at,finding_id,revision`)
|
|
106
|
+
.iterate(...params)) {
|
|
107
|
+
if (typeof row.finding_id !== 'string' ||
|
|
108
|
+
row.finding_id !== row.saved_id ||
|
|
109
|
+
typeof row.revision !== 'number' ||
|
|
110
|
+
!Number.isSafeInteger(row.revision) ||
|
|
111
|
+
row.revision < 1 ||
|
|
112
|
+
typeof row.recorded_at !== 'number' ||
|
|
113
|
+
!Number.isSafeInteger(row.recorded_at) ||
|
|
114
|
+
!['health', 'library', 'product', 'malware', 'news'].includes(String(row.category)) ||
|
|
115
|
+
![null, 'true', 'false'].includes(row.active) ||
|
|
116
|
+
![null, 'true', 'false'].includes(row.withdrawn))
|
|
117
|
+
throw new PilotReportError('data');
|
|
118
|
+
if (row.category === 'health' || row.active === 'false' || row.withdrawn === 'true') {
|
|
119
|
+
if (row.recorded_at >= start)
|
|
120
|
+
packet.excluded_revisions++;
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
if (row.evidence_kind !== 'array' || row.channels_kind !== 'array')
|
|
124
|
+
throw new PilotReportError('data');
|
|
125
|
+
const fields = lookup.safeParse({
|
|
126
|
+
event_ref: row.event_ref,
|
|
127
|
+
system_ref: row.system_ref,
|
|
128
|
+
component_ref: row.component_ref,
|
|
129
|
+
evidence_refs: JSON.parse(String(row.evidence_refs)),
|
|
130
|
+
});
|
|
131
|
+
const policy = decision.safeParse({
|
|
132
|
+
action: row.action,
|
|
133
|
+
channels: JSON.parse(String(row.channels)),
|
|
134
|
+
review: row.review ?? undefined,
|
|
135
|
+
});
|
|
136
|
+
if (!fields.success || !policy.success)
|
|
137
|
+
throw new PilotReportError('data');
|
|
138
|
+
if (jobsForRevision) {
|
|
139
|
+
const jobRows = jobsForRevision.all(row.finding_id, fields.data.event_ref, fields.data.system_ref, fields.data.component_ref, row.finding_id, row.revision, Number(row.recorded_at >= start), start, end);
|
|
140
|
+
if (new Set(jobRows.map((job) => job.channel)).size !== jobRows.length)
|
|
141
|
+
throw new PilotReportError('data');
|
|
142
|
+
const jobs = jobRows.map((job) => {
|
|
143
|
+
notificationBytes += Number(job.bytes);
|
|
144
|
+
if (Number(job.bytes) > 512 * 1024 || notificationBytes > 64 * 1024 * 1024)
|
|
145
|
+
throw new PilotReportError('bounds');
|
|
146
|
+
const parsed = deliveryJob.safeParse(job);
|
|
147
|
+
if (job.same_target !== 1 ||
|
|
148
|
+
!parsed.success ||
|
|
149
|
+
(parsed.data.status !== 'accepted' && parsed.data.accepted_at !== null))
|
|
150
|
+
throw new PilotReportError('data');
|
|
151
|
+
// A backwards wall clock cannot establish when this job was accepted.
|
|
152
|
+
if (parsed.data.accepted_at !== null && parsed.data.accepted_at < Number(row.recorded_at))
|
|
153
|
+
parsed.data.accepted_at = null;
|
|
154
|
+
return parsed.data;
|
|
155
|
+
});
|
|
156
|
+
const { event_ref, system_ref, component_ref } = fields.data;
|
|
157
|
+
if (jobs.length)
|
|
158
|
+
deliveryRevisions.push({ event_ref, system_ref, component_ref, jobs });
|
|
159
|
+
}
|
|
160
|
+
if (row.recorded_at < start)
|
|
161
|
+
continue;
|
|
162
|
+
const caseId = digest('security-watch.pilot-case.v1', packetId, row.finding_id, row.revision);
|
|
163
|
+
const action = policy.data;
|
|
164
|
+
routes.set(caseId, {
|
|
165
|
+
immediate: action.action === 'notify' && action.channels.length > 0,
|
|
166
|
+
quiet: (action.action === 'record' || action.channels.length === 0) && action.review === undefined,
|
|
167
|
+
});
|
|
168
|
+
packet.cases.push({
|
|
169
|
+
case_id: caseId,
|
|
170
|
+
recorded_at: new Date(row.recorded_at).toISOString(),
|
|
171
|
+
...fields.data,
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
return { packet, routes, deliveryRevisions };
|
|
175
|
+
}
|
|
176
|
+
export async function loadPilotCohort(backup, window, includeDelivery = false) {
|
|
177
|
+
const range = capturePilotWindow(window);
|
|
178
|
+
return withPrivatePilotBackup(backup, (path, digest) => {
|
|
179
|
+
const db = new DatabaseSync(path, { readOnly: true });
|
|
180
|
+
try {
|
|
181
|
+
db.exec('PRAGMA trusted_schema=OFF; PRAGMA query_only=ON; BEGIN');
|
|
182
|
+
return readCohort(db, digest, range, includeDelivery);
|
|
183
|
+
}
|
|
184
|
+
finally {
|
|
185
|
+
db.close();
|
|
186
|
+
}
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
/** Private local research pointers suitable for blinded review by authorized analysts. */
|
|
190
|
+
export async function createPilotCasePacket(backup, window) {
|
|
191
|
+
return (await loadPilotCohort(backup, window)).packet;
|
|
192
|
+
}
|
|
193
|
+
export function readPilotFeedback(path) {
|
|
194
|
+
return validateFeedback(readPrivatePilotJson(path, 'labels'));
|
|
195
|
+
}
|
|
196
|
+
function validateFeedback(input) {
|
|
197
|
+
const fields = dataFields(input, Object.keys(feedbackSchema.shape), 'labels');
|
|
198
|
+
if (fields.version !== 1 || typeof fields.packet_id !== 'string' || fields.packet_id.length !== 64)
|
|
199
|
+
invalidFeedback();
|
|
200
|
+
function captureRows(rows, max, names) {
|
|
201
|
+
return dataArray(rows, max, 'labels').map((row) => {
|
|
202
|
+
const captured = dataFields(row, names, 'labels');
|
|
203
|
+
for (const value of Object.values(captured))
|
|
204
|
+
if (typeof value !== 'boolean' && (typeof value !== 'string' || value.length > 64))
|
|
205
|
+
invalidFeedback();
|
|
206
|
+
return captured;
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
fields.reviews = captureRows(fields.reviews, 2 * MAX_REVISIONS, Object.keys(review.shape));
|
|
210
|
+
fields.adjudications = captureRows(fields.adjudications, MAX_REVISIONS, Object.keys(adjudication.shape));
|
|
211
|
+
const parsed = feedbackSchema.safeParse(fields);
|
|
212
|
+
if (!parsed.success)
|
|
213
|
+
invalidFeedback();
|
|
214
|
+
return parsed.data;
|
|
215
|
+
}
|
|
216
|
+
export function metric(numerator, denominator) {
|
|
217
|
+
return { numerator, denominator, rate: denominator ? numerator / denominator : null };
|
|
218
|
+
}
|
|
219
|
+
export function latencySummary(samples) {
|
|
220
|
+
samples.sort((a, b) => a - b);
|
|
221
|
+
const middle = Math.floor(samples.length / 2);
|
|
222
|
+
return {
|
|
223
|
+
count: samples.length,
|
|
224
|
+
median_ms: samples.length
|
|
225
|
+
? (samples[middle] + samples[Math.floor((samples.length - 1) / 2)]) / 2
|
|
226
|
+
: null,
|
|
227
|
+
p95_ms: samples[Math.ceil(samples.length * 0.95) - 1] ?? null,
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
function grade(packet, routes, feedback, evidenceDisagreements) {
|
|
231
|
+
if (feedback.packet_id !== packet.packet_id)
|
|
232
|
+
invalidFeedback();
|
|
233
|
+
const pairs = new Map();
|
|
234
|
+
for (const row of feedback.reviews) {
|
|
235
|
+
const pair = pairs.get(row.case_id) ?? [];
|
|
236
|
+
if (!routes.has(row.case_id) || pair.length >= 2 || pair.some((other) => other.reviewer === row.reviewer))
|
|
237
|
+
invalidFeedback();
|
|
238
|
+
pair.push(row);
|
|
239
|
+
pairs.set(row.case_id, pair);
|
|
240
|
+
}
|
|
241
|
+
const resolutions = new Map();
|
|
242
|
+
for (const row of feedback.adjudications) {
|
|
243
|
+
const pair = pairs.get(row.case_id);
|
|
244
|
+
if (!pair ||
|
|
245
|
+
pair.length !== 2 ||
|
|
246
|
+
(pair[0].label === pair[1].label && !evidenceDisagreements?.has(row.case_id)) ||
|
|
247
|
+
pair.some((r) => r.reviewer === row.adjudicator) ||
|
|
248
|
+
resolutions.has(row.case_id))
|
|
249
|
+
invalidFeedback();
|
|
250
|
+
resolutions.set(row.case_id, row.label);
|
|
251
|
+
}
|
|
252
|
+
const coverage = {
|
|
253
|
+
eligible: routes.size,
|
|
254
|
+
excluded: packet.excluded_revisions,
|
|
255
|
+
unreviewed: 0,
|
|
256
|
+
single_review: 0,
|
|
257
|
+
agreements: 0,
|
|
258
|
+
disagreements: 0,
|
|
259
|
+
adjudicated: resolutions.size,
|
|
260
|
+
unresolved_conflicts: 0,
|
|
261
|
+
abstained: 0,
|
|
262
|
+
scored: 0,
|
|
263
|
+
};
|
|
264
|
+
let urgent = 0, risk = 0, benign = 0, immediateUrgent = 0, quietRisk = 0, immediateBenign = 0;
|
|
265
|
+
for (const [caseId, route] of routes) {
|
|
266
|
+
const pair = pairs.get(caseId);
|
|
267
|
+
if (!pair) {
|
|
268
|
+
coverage.unreviewed++;
|
|
269
|
+
continue;
|
|
270
|
+
}
|
|
271
|
+
if (pair.length === 1) {
|
|
272
|
+
coverage.single_review++;
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
let referenceLabel = pair[0].label;
|
|
276
|
+
if (referenceLabel === pair[1].label && !evidenceDisagreements?.has(caseId))
|
|
277
|
+
coverage.agreements++;
|
|
278
|
+
else {
|
|
279
|
+
coverage.disagreements++;
|
|
280
|
+
const resolution = resolutions.get(caseId);
|
|
281
|
+
if (!resolution) {
|
|
282
|
+
coverage.unresolved_conflicts++;
|
|
283
|
+
continue;
|
|
284
|
+
}
|
|
285
|
+
referenceLabel = resolution;
|
|
286
|
+
}
|
|
287
|
+
if (referenceLabel === 'abstain') {
|
|
288
|
+
coverage.abstained++;
|
|
289
|
+
continue;
|
|
290
|
+
}
|
|
291
|
+
coverage.scored++;
|
|
292
|
+
if (referenceLabel === 'benign') {
|
|
293
|
+
benign++;
|
|
294
|
+
if (route.immediate)
|
|
295
|
+
immediateBenign++;
|
|
296
|
+
}
|
|
297
|
+
else {
|
|
298
|
+
risk++;
|
|
299
|
+
if (route.quiet)
|
|
300
|
+
quietRisk++;
|
|
301
|
+
if (referenceLabel === 'urgent') {
|
|
302
|
+
urgent++;
|
|
303
|
+
if (route.immediate)
|
|
304
|
+
immediateUrgent++;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
return {
|
|
309
|
+
version: 1,
|
|
310
|
+
mode: 'pilot_score',
|
|
311
|
+
window: packet.window,
|
|
312
|
+
coverage,
|
|
313
|
+
policy: {
|
|
314
|
+
urgent_immediate: metric(immediateUrgent, urgent),
|
|
315
|
+
quiet_risk: metric(quietRisk, risk),
|
|
316
|
+
unnecessary_immediate: metric(immediateBenign, benign),
|
|
317
|
+
},
|
|
318
|
+
unmeasured: { population_urgent_recall: null, delivered_false_alert_rate: null },
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
/** Internal replay hook for a frozen external roster. The caller accounts for every enrolled target. */
|
|
322
|
+
export function gradePilotRoutes(scope, routes, feedback, evidenceDisagreements) {
|
|
323
|
+
return grade(scope, routes, validateFeedback(feedback), evidenceDisagreements);
|
|
324
|
+
}
|
|
325
|
+
/** Aggregate policy quality on the resolved subset of a frozen, explicitly accounted-for revision cohort. */
|
|
326
|
+
export async function scorePilotCases(backup, window, feedback) {
|
|
327
|
+
const captured = validateFeedback(feedback);
|
|
328
|
+
const { packet, routes } = await loadPilotCohort(backup, window);
|
|
329
|
+
return grade(packet, routes, captured);
|
|
330
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type PilotWindow } from './pilot-report.js';
|
|
2
|
+
type InputProblem = 'window' | 'labels' | 'incidents' | 'responses';
|
|
3
|
+
export declare function pilotInstant(value: unknown, problem: InputProblem): string;
|
|
4
|
+
/** Copy only own enumerable data properties. Public API values may originate outside a JSON parser. */
|
|
5
|
+
export declare function dataFields(input: unknown, names: readonly string[], problem: InputProblem): Record<string, unknown>;
|
|
6
|
+
export declare function dataArray(rows: unknown, max: number, problem: InputProblem): unknown[];
|
|
7
|
+
export declare function capturePilotWindow(window: PilotWindow): {
|
|
8
|
+
from: string;
|
|
9
|
+
until: string;
|
|
10
|
+
start: number;
|
|
11
|
+
end: number;
|
|
12
|
+
days: number;
|
|
13
|
+
};
|
|
14
|
+
/** Read bounded private feedback without following links or opening a special file for blocking I/O. */
|
|
15
|
+
export declare function readPrivatePilotJson(path: string, problem: InputProblem): unknown;
|
|
16
|
+
export {};
|