@shieldaai/security-watch 0.1.0-alpha.0 → 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 +4 -2
- package/README.md +173 -48
- package/SECURITY.md +24 -9
- package/dist/assessment.d.ts +12 -1
- package/dist/assessment.js +223 -52
- package/dist/cli.js +340 -27
- package/dist/config.d.ts +62 -2
- package/dist/config.js +88 -5
- package/dist/coverage.d.ts +4 -0
- package/dist/coverage.js +11 -0
- package/dist/cve-now.d.ts +32 -2
- package/dist/cve-now.js +715 -126
- package/dist/cvss4.d.ts +3 -0
- package/dist/cvss4.js +39 -0
- package/dist/delivery.d.ts +34 -2
- package/dist/delivery.js +391 -98
- package/dist/ecosystems.d.ts +23 -0
- package/dist/ecosystems.js +88 -10
- package/dist/engine.d.ts +55 -1
- package/dist/engine.js +101 -20
- package/dist/everyday-words.d.ts +11 -0
- package/dist/everyday-words.js +256 -0
- package/dist/health.d.ts +7 -0
- package/dist/health.js +55 -3
- package/dist/http.d.ts +7 -0
- package/dist/http.js +31 -2
- package/dist/index.d.ts +22 -4
- package/dist/index.js +12 -4
- package/dist/inventory-evidence.d.ts +10 -0
- package/dist/inventory-evidence.js +206 -0
- package/dist/inventory.d.ts +273 -0
- package/dist/inventory.js +210 -17
- package/dist/maintenance.d.ts +5 -0
- package/dist/maintenance.js +73 -5
- package/dist/matching.d.ts +29 -0
- package/dist/matching.js +537 -0
- package/dist/models.d.ts +17 -4
- package/dist/models.js +359 -29
- 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/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/source-error.d.ts +17 -1
- package/dist/source-error.js +18 -3
- package/dist/sources.d.ts +2 -2
- package/dist/sources.js +699 -45
- package/dist/store.d.ts +38 -13
- package/dist/store.js +325 -23
- package/dist/types.d.ts +159 -2
- package/dist/util.d.ts +23 -0
- package/dist/util.js +81 -1
- package/dist/vendor/cvss4-reference.d.ts +2 -0
- package/dist/vendor/cvss4-reference.js +789 -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 +289 -29
- 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/agent-advisories-2026.json +145 -0
- package/examples/agent-advisory-cases-2026.json +397 -0
- package/examples/libraries.example.txt +4 -2
- package/examples/libraries.example.yaml +2 -0
- package/examples/offline-advisory-preview.mjs +42 -0
- package/examples/rehearsal.json +75 -0
- package/examples/systems.example.yaml +4 -0
- package/package.json +23 -7
- package/docs/quality-review.md +0 -104
package/dist/inventory.js
CHANGED
|
@@ -2,20 +2,111 @@ import { readFileSync, statSync } from 'node:fs';
|
|
|
2
2
|
import { dirname, resolve } from 'node:path';
|
|
3
3
|
import { parseDocument } from 'yaml';
|
|
4
4
|
import { z } from 'zod';
|
|
5
|
-
import { exactLibraryVersion, normalizeEcosystem, normalizePackageName, parseLibrary } from './ecosystems.js';
|
|
6
|
-
import { hash } from './util.js';
|
|
7
|
-
|
|
8
|
-
|
|
5
|
+
import { capitalisedName, exactLibraryVersion, mergeNotes, normalizeEcosystem, normalizePackageName, parseLibrary, } from './ecosystems.js';
|
|
6
|
+
import { hash, LINE_BREAKING, singleLine } from './util.js';
|
|
7
|
+
import { importCycloneDx } from './sbom.js';
|
|
8
|
+
// Inventory text is shown in notifications, one value per line. A control character or a Unicode
|
|
9
|
+
// line separator inside a name, owner or note would let that value start a line of its own.
|
|
10
|
+
const shortText = z
|
|
9
11
|
.string()
|
|
10
|
-
.
|
|
11
|
-
.
|
|
12
|
+
.trim()
|
|
13
|
+
.min(1)
|
|
14
|
+
.max(500)
|
|
15
|
+
.refine((value) => !LINE_BREAKING.test(value), 'Control characters are not allowed');
|
|
12
16
|
const severity = z.enum(['unknown', 'low', 'medium', 'high', 'critical']);
|
|
17
|
+
const evidenceText = shortText;
|
|
18
|
+
const referenceText = z
|
|
19
|
+
.string()
|
|
20
|
+
.min(1)
|
|
21
|
+
.max(1000)
|
|
22
|
+
.refine((value) => !LINE_BREAKING.test(value), 'Control characters are not allowed');
|
|
23
|
+
const declaredVerification = z.strictObject({
|
|
24
|
+
status: z.enum(['verified', 'failed', 'unknown']),
|
|
25
|
+
reference: evidenceText,
|
|
26
|
+
recorded_at: z.iso.datetime({ offset: true }),
|
|
27
|
+
recorded_by: evidenceText.optional(),
|
|
28
|
+
});
|
|
29
|
+
const dependencyLinks = z
|
|
30
|
+
.array(z.strictObject({ ref: referenceText, component_id: evidenceText.optional() }))
|
|
31
|
+
.max(1000)
|
|
32
|
+
.refine((links) => new Set(links.map((link) => link.ref)).size === links.length, 'Duplicate dependency reference');
|
|
33
|
+
const dependencyGraph = z
|
|
34
|
+
.array(z.strictObject({ ref: referenceText, depends_on: z.array(referenceText).max(1000) }))
|
|
35
|
+
.max(20_000)
|
|
36
|
+
.refine((entries) => entries.reduce((count, entry) => count + entry.depends_on.length, 0) <= 100_000, 'At most 100000 dependency edges')
|
|
37
|
+
.refine((entries) => new Set(entries.map((entry) => entry.ref)).size === entries.length &&
|
|
38
|
+
entries.every((entry) => new Set(entry.depends_on).size === entry.depends_on.length), 'Duplicate dependency reference');
|
|
39
|
+
const inventoryEvidence = {
|
|
40
|
+
artifact_kind: z
|
|
41
|
+
.enum([
|
|
42
|
+
'application',
|
|
43
|
+
'library',
|
|
44
|
+
'mcp_server',
|
|
45
|
+
'mcp_client',
|
|
46
|
+
'plugin',
|
|
47
|
+
'skill',
|
|
48
|
+
'model',
|
|
49
|
+
'container',
|
|
50
|
+
'other',
|
|
51
|
+
])
|
|
52
|
+
.optional(),
|
|
53
|
+
purl: z
|
|
54
|
+
.string()
|
|
55
|
+
.max(1000)
|
|
56
|
+
.regex(/^pkg:[a-z][a-z0-9.+-]*\/[^\s\u0000-\u001f\u007f]+$/u)
|
|
57
|
+
.optional(),
|
|
58
|
+
source_url: z
|
|
59
|
+
.url()
|
|
60
|
+
.max(2048)
|
|
61
|
+
.refine((value) => {
|
|
62
|
+
const url = new URL(value);
|
|
63
|
+
return url.protocol === 'https:' && !url.username && !url.password && !url.search && !url.hash;
|
|
64
|
+
}, 'Source URL must be HTTPS without credentials, query or fragment')
|
|
65
|
+
.optional(),
|
|
66
|
+
source_revision: evidenceText.optional(),
|
|
67
|
+
sbom_ref: referenceText.optional(),
|
|
68
|
+
dependencies: dependencyLinks.optional(),
|
|
69
|
+
signature_verification: declaredVerification.optional(),
|
|
70
|
+
attestation_verification: declaredVerification.optional(),
|
|
71
|
+
remediation_evidence: z
|
|
72
|
+
.array(z.strictObject({
|
|
73
|
+
event_id: evidenceText,
|
|
74
|
+
stage: z.enum(['proposed', 'changed', 'deployed']),
|
|
75
|
+
verification: z.enum(['supported', 'failed', 'unknown']),
|
|
76
|
+
reference: evidenceText,
|
|
77
|
+
recorded_at: z.iso.datetime({ offset: true }),
|
|
78
|
+
recorded_by: evidenceText.optional(),
|
|
79
|
+
}))
|
|
80
|
+
.max(100)
|
|
81
|
+
.optional(),
|
|
82
|
+
origin: shortText.optional(),
|
|
83
|
+
digest: z
|
|
84
|
+
.string()
|
|
85
|
+
.regex(/^(?:sha256:[a-f0-9]{64}|sha384:[a-f0-9]{96}|sha512:[a-f0-9]{128})$/)
|
|
86
|
+
.optional(),
|
|
87
|
+
provenance: z
|
|
88
|
+
.strictObject({
|
|
89
|
+
source: shortText,
|
|
90
|
+
reference: shortText.optional(),
|
|
91
|
+
recorded_at: z.iso.datetime({ offset: true }).optional(),
|
|
92
|
+
})
|
|
93
|
+
.optional(),
|
|
94
|
+
observation: z
|
|
95
|
+
.strictObject({
|
|
96
|
+
observed_at: z.iso.datetime({ offset: true }),
|
|
97
|
+
method: shortText,
|
|
98
|
+
reference: shortText.optional(),
|
|
99
|
+
})
|
|
100
|
+
.optional(),
|
|
101
|
+
};
|
|
13
102
|
const componentSchema = z
|
|
14
103
|
.strictObject({
|
|
104
|
+
...inventoryEvidence,
|
|
15
105
|
id: shortText,
|
|
16
106
|
ecosystem: shortText,
|
|
17
107
|
name: shortText,
|
|
18
108
|
version: shortText.optional(),
|
|
109
|
+
note: evidenceText.optional(),
|
|
19
110
|
})
|
|
20
111
|
.transform((component) => {
|
|
21
112
|
const ecosystem = normalizeEcosystem(component.ecosystem);
|
|
@@ -32,12 +123,21 @@ const productSchema = z.strictObject({
|
|
|
32
123
|
name: shortText,
|
|
33
124
|
version: shortText.optional(),
|
|
34
125
|
keywords: z.array(shortText).max(100).default([]),
|
|
126
|
+
note: evidenceText.optional(),
|
|
35
127
|
});
|
|
36
128
|
const systemSchema = z.strictObject({
|
|
129
|
+
...inventoryEvidence,
|
|
130
|
+
sbom_dependencies: dependencyGraph.optional(),
|
|
131
|
+
configuration: z
|
|
132
|
+
.record(z.string().min(1).max(100), z.union([shortText, z.boolean(), z.number().finite()]))
|
|
133
|
+
.refine((value) => Object.keys(value).length <= 100, 'At most 100 configuration observations')
|
|
134
|
+
.optional(),
|
|
135
|
+
sbom: z.string().trim().min(1).max(4096).optional(),
|
|
37
136
|
id: shortText,
|
|
38
137
|
name: shortText,
|
|
39
138
|
environment: shortText.default('unknown'),
|
|
40
139
|
owner: shortText.optional(),
|
|
140
|
+
note: evidenceText.optional(),
|
|
41
141
|
exposure: z.enum(['internet', 'internal', 'unknown']).default('unknown'),
|
|
42
142
|
criticality: severity.default('unknown'),
|
|
43
143
|
updated_at: z.iso.datetime({ offset: true }),
|
|
@@ -50,6 +150,23 @@ const systemSchema = z.strictObject({
|
|
|
50
150
|
lockfile: z.string().trim().min(1).max(4096).optional(),
|
|
51
151
|
});
|
|
52
152
|
const inventorySchema = z.strictObject({ systems: z.array(systemSchema).min(1).max(1000) });
|
|
153
|
+
/** Already materialized snapshots cannot import files or expand filesystem references. */
|
|
154
|
+
export const inventorySnapshotSchema = z
|
|
155
|
+
.strictObject({
|
|
156
|
+
systems: z
|
|
157
|
+
.array(systemSchema.omit({ lockfile: true, libraries: true, sbom: true }))
|
|
158
|
+
.min(1)
|
|
159
|
+
.max(1000),
|
|
160
|
+
import_warnings: z.array(z.string().max(2000)).max(1000).optional(),
|
|
161
|
+
name_notices: z.array(z.string().max(2000)).max(1000).optional(),
|
|
162
|
+
})
|
|
163
|
+
.refine((inventory) => {
|
|
164
|
+
const ids = new Set(inventory.systems.map((system) => system.id));
|
|
165
|
+
return (ids.size === inventory.systems.length &&
|
|
166
|
+
inventory.systems.every((system) => new Set(system.components.map((component) => component.id)).size === system.components.length &&
|
|
167
|
+
new Set(system.products.map((product) => product.name.toLowerCase())).size ===
|
|
168
|
+
system.products.length));
|
|
169
|
+
}, 'Duplicate inventory identities');
|
|
53
170
|
function readBounded(path, maximum) {
|
|
54
171
|
const stat = statSync(path);
|
|
55
172
|
if (!stat.isFile() || stat.size > maximum)
|
|
@@ -59,6 +176,9 @@ function readBounded(path, maximum) {
|
|
|
59
176
|
throw new Error(`Inventory input exceeds ${maximum} bytes: ${path}`);
|
|
60
177
|
return content.toString('utf8');
|
|
61
178
|
}
|
|
179
|
+
function shortLabel(value) {
|
|
180
|
+
return singleLine(value, 120);
|
|
181
|
+
}
|
|
62
182
|
function record(value) {
|
|
63
183
|
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
64
184
|
}
|
|
@@ -72,14 +192,29 @@ function importLockfile(path) {
|
|
|
72
192
|
if (entries.length > 20_000)
|
|
73
193
|
throw new Error(`Lockfile exceeds 20000 package entries: ${path}`);
|
|
74
194
|
const components = [];
|
|
195
|
+
const warnings = [];
|
|
75
196
|
for (const [location, value] of entries) {
|
|
76
197
|
if (!location || !record(value) || value.link === true)
|
|
77
198
|
continue;
|
|
78
199
|
const match = /(?:^|\/)node_modules\/((?:@[^/]+\/)?[^/]+)$/.exec(location);
|
|
79
200
|
if (!match)
|
|
80
201
|
continue;
|
|
81
|
-
|
|
82
|
-
|
|
202
|
+
// The location becomes the component's identifier, which is shown in notifications.
|
|
203
|
+
if (LINE_BREAKING.test(location) || location.length > 480) {
|
|
204
|
+
warnings.push(`Lockfile entry ${shortLabel(location)}: the path contains control characters or is too long; not imported.`);
|
|
205
|
+
continue;
|
|
206
|
+
}
|
|
207
|
+
// One entry this application cannot read must not hide every other dependency in the file.
|
|
208
|
+
let name;
|
|
209
|
+
let version;
|
|
210
|
+
try {
|
|
211
|
+
name = normalizePackageName('npm', z.string().parse(value.name ?? match[1]));
|
|
212
|
+
version = value.version === undefined ? undefined : shortText.parse(value.version);
|
|
213
|
+
}
|
|
214
|
+
catch {
|
|
215
|
+
warnings.push(`Lockfile entry ${shortLabel(location)}: unsupported package name or version; not imported.`);
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
83
218
|
components.push({
|
|
84
219
|
id: `lock:${location}`,
|
|
85
220
|
ecosystem: 'npm',
|
|
@@ -87,7 +222,7 @@ function importLockfile(path) {
|
|
|
87
222
|
...(version === undefined ? {} : { version }),
|
|
88
223
|
});
|
|
89
224
|
}
|
|
90
|
-
return components;
|
|
225
|
+
return { components, warnings };
|
|
91
226
|
}
|
|
92
227
|
/** Load a local YAML/JSON inventory, checking its size and schema. */
|
|
93
228
|
export function loadInventory(path) {
|
|
@@ -97,13 +232,30 @@ export function loadInventory(path) {
|
|
|
97
232
|
throw new Error(`Invalid inventory YAML: ${document.errors[0].message}`);
|
|
98
233
|
const parsed = inventorySchema.parse(document.toJS({ maxAliasCount: 0 }));
|
|
99
234
|
const systemIds = new Set();
|
|
100
|
-
const
|
|
235
|
+
const importWarnings = [];
|
|
236
|
+
const nameNotices = [];
|
|
237
|
+
// A hostile or broken import can produce a warning per entry. Keep a bounded number of bounded,
|
|
238
|
+
// single-line messages and say how many more there were.
|
|
239
|
+
let omittedWarnings = 0;
|
|
240
|
+
let omittedNotices = 0;
|
|
241
|
+
const warn = (system, warnings) => {
|
|
242
|
+
for (const warning of warnings) {
|
|
243
|
+
if (importWarnings.length < 200)
|
|
244
|
+
importWarnings.push(singleLine(`${system}: ${warning}`, 400));
|
|
245
|
+
else
|
|
246
|
+
omittedWarnings++;
|
|
247
|
+
}
|
|
248
|
+
};
|
|
249
|
+
const systems = parsed.systems.map(({ lockfile, libraries, sbom, ...system }) => {
|
|
101
250
|
if (systemIds.has(system.id))
|
|
102
251
|
throw new Error(`Duplicate system ID: ${system.id}`);
|
|
103
252
|
systemIds.add(system.id);
|
|
104
253
|
if (libraries) {
|
|
105
254
|
const groups = Array.isArray(libraries) ? [[undefined, libraries]] : Object.entries(libraries);
|
|
106
|
-
const added = new
|
|
255
|
+
const added = new Map(system.components.map((component) => [
|
|
256
|
+
JSON.stringify([component.ecosystem, component.name, component.version ?? null]),
|
|
257
|
+
component,
|
|
258
|
+
]));
|
|
107
259
|
let count = 0;
|
|
108
260
|
for (const [ecosystem, entries] of groups) {
|
|
109
261
|
if (ecosystem !== undefined)
|
|
@@ -113,15 +265,48 @@ export function loadInventory(path) {
|
|
|
113
265
|
throw new Error(`System ${system.id} exceeds 20000 library entries`);
|
|
114
266
|
const library = parseLibrary(entry, ecosystem);
|
|
115
267
|
const key = JSON.stringify([library.ecosystem, library.name, library.version ?? null]);
|
|
116
|
-
|
|
268
|
+
const existing = added.get(key);
|
|
269
|
+
if (existing) {
|
|
270
|
+
// The same library listed twice keeps every place it was said to be used.
|
|
271
|
+
const note = mergeNotes(existing.note, library.note);
|
|
272
|
+
if (note)
|
|
273
|
+
existing.note = note;
|
|
117
274
|
continue;
|
|
118
|
-
|
|
119
|
-
|
|
275
|
+
}
|
|
276
|
+
const component = { id: `library:${hash(key).slice(0, 24)}`, ...library };
|
|
277
|
+
added.set(key, component);
|
|
278
|
+
system.components.push(component);
|
|
120
279
|
}
|
|
121
280
|
}
|
|
122
281
|
}
|
|
123
|
-
|
|
124
|
-
|
|
282
|
+
// Names typed by hand, before anything is imported: a lockfile or SBOM carries the published
|
|
283
|
+
// spelling, a person may have typed `Lodash` for `lodash`. The entry is valid as written (some
|
|
284
|
+
// old packages do have capitals), so this is a notice to read once, not a monitoring fault.
|
|
285
|
+
for (const component of system.components) {
|
|
286
|
+
const notice = capitalisedName(component);
|
|
287
|
+
if (!notice)
|
|
288
|
+
continue;
|
|
289
|
+
if (nameNotices.length < 200)
|
|
290
|
+
nameNotices.push(`${system.id}: ${notice}`);
|
|
291
|
+
else
|
|
292
|
+
omittedNotices++;
|
|
293
|
+
}
|
|
294
|
+
if (sbom) {
|
|
295
|
+
const imported = importCycloneDx(resolve(dirname(absolute), sbom));
|
|
296
|
+
system.components.push(...imported.components);
|
|
297
|
+
if (imported.dependencies.length) {
|
|
298
|
+
system.sbom_dependencies = dependencyGraph.parse([
|
|
299
|
+
...(system.sbom_dependencies ?? []),
|
|
300
|
+
...imported.dependencies,
|
|
301
|
+
]);
|
|
302
|
+
}
|
|
303
|
+
warn(system.id, imported.warnings);
|
|
304
|
+
}
|
|
305
|
+
if (lockfile) {
|
|
306
|
+
const imported = importLockfile(resolve(dirname(absolute), lockfile));
|
|
307
|
+
system.components.push(...imported.components);
|
|
308
|
+
warn(system.id, imported.warnings);
|
|
309
|
+
}
|
|
125
310
|
if (system.components.length > 20_000)
|
|
126
311
|
throw new Error(`System ${system.id} exceeds 20000 components`);
|
|
127
312
|
const componentIds = new Set();
|
|
@@ -139,5 +324,13 @@ export function loadInventory(path) {
|
|
|
139
324
|
}
|
|
140
325
|
return system;
|
|
141
326
|
});
|
|
142
|
-
|
|
327
|
+
if (omittedWarnings)
|
|
328
|
+
importWarnings.push(`${omittedWarnings} more import warning(s) are not shown.`);
|
|
329
|
+
if (omittedNotices)
|
|
330
|
+
nameNotices.push(`${omittedNotices} more name notice(s) are not shown.`);
|
|
331
|
+
return {
|
|
332
|
+
systems,
|
|
333
|
+
...(importWarnings.length ? { import_warnings: importWarnings } : {}),
|
|
334
|
+
...(nameNotices.length ? { name_notices: nameNotices } : {}),
|
|
335
|
+
};
|
|
143
336
|
}
|
package/dist/maintenance.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type PilotReport, type PilotWindow } from './pilot-report.js';
|
|
1
2
|
export interface RetentionPolicy {
|
|
2
3
|
analysis_cache_days?: number;
|
|
3
4
|
evidence_history_days?: number;
|
|
@@ -41,3 +42,7 @@ export declare function validateRetentionPolicy(policy: RetentionPolicy): Requir
|
|
|
41
42
|
export declare function verifyBackup(path: string, options?: {
|
|
42
43
|
max_bytes?: number;
|
|
43
44
|
}): Promise<BackupVerification>;
|
|
45
|
+
/** Keep the original standalone backup free of SQLite's WAL reader coordination files. */
|
|
46
|
+
export declare function readPilotBackupReport(path: string, window: PilotWindow): Promise<PilotReport>;
|
|
47
|
+
/** Bind consumers to the bytes copied and verified by the isolated backup reader. */
|
|
48
|
+
export declare function withPrivatePilotBackup<T>(path: string, inspect: (restored: string, sourceSha256: string) => T | Promise<T>): Promise<T>;
|
package/dist/maintenance.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
1
2
|
import { execFile } from 'node:child_process';
|
|
2
3
|
import { promisify } from 'node:util';
|
|
3
4
|
import { DatabaseSync } from 'node:sqlite';
|
|
@@ -5,6 +6,7 @@ import { closeSync, constants, fstatSync, lstatSync, mkdtempSync, openSync, read
|
|
|
5
6
|
import { tmpdir } from 'node:os';
|
|
6
7
|
import { join, resolve } from 'node:path';
|
|
7
8
|
import { fileURLToPath } from 'node:url';
|
|
9
|
+
import { PilotReportError, validatePilotWindow } from './pilot-report.js';
|
|
8
10
|
export function validateRetentionPolicy(policy) {
|
|
9
11
|
if (!policy || typeof policy !== 'object' || Array.isArray(policy))
|
|
10
12
|
throw new Error('Invalid retention policy');
|
|
@@ -35,14 +37,58 @@ const runFile = promisify(execFile);
|
|
|
35
37
|
const DEFAULT_BACKUP_LIMIT = 512 * 1024 ** 2;
|
|
36
38
|
/** Restore and inspect a temporary copy. No live database or original backup is replaced. */
|
|
37
39
|
export async function verifyBackup(path, options = {}) {
|
|
38
|
-
|
|
40
|
+
return withVerifiedBackup(path, options.max_bytes ?? DEFAULT_BACKUP_LIMIT, false, (report) => report);
|
|
41
|
+
}
|
|
42
|
+
/** Keep the original standalone backup free of SQLite's WAL reader coordination files. */
|
|
43
|
+
export async function readPilotBackupReport(path, window) {
|
|
44
|
+
const range = validatePilotWindow(window, Date.now());
|
|
45
|
+
return withPrivatePilotBackup(path, async (restored) => {
|
|
46
|
+
const { readPilotReport } = await import('./store.js');
|
|
47
|
+
const report = readPilotReport(restored, range);
|
|
48
|
+
report.snapshot.source = 'verified_backup';
|
|
49
|
+
// A standalone backup does not record its capture time or later live worker activity.
|
|
50
|
+
report.snapshot.reviews.oldest_open_age_ms = null;
|
|
51
|
+
if (report.snapshot.source_coverage)
|
|
52
|
+
report.snapshot.source_coverage.freshness = null;
|
|
53
|
+
if (report.snapshot.last_scan)
|
|
54
|
+
report.snapshot.last_scan.age_ms = null;
|
|
55
|
+
return report;
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
/** Bind consumers to the bytes copied and verified by the isolated backup reader. */
|
|
59
|
+
export async function withPrivatePilotBackup(path, inspect) {
|
|
60
|
+
try {
|
|
61
|
+
return await withVerifiedBackup(path, DEFAULT_BACKUP_LIMIT, true, async (verified, restored, sourceSha256) => {
|
|
62
|
+
const { SCHEMA_VERSION } = await import('./store.js');
|
|
63
|
+
// Schema 6 already retains dated revisions and AI reviews. Its copy migrates with unknown receipt times.
|
|
64
|
+
if (verified.schema_version < 6 ||
|
|
65
|
+
verified.verified_schema_version !== SCHEMA_VERSION ||
|
|
66
|
+
!sourceSha256)
|
|
67
|
+
throw new PilotReportError('database');
|
|
68
|
+
return inspect(restored, sourceSha256);
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
if (error instanceof PilotReportError)
|
|
73
|
+
throw error;
|
|
74
|
+
throw new PilotReportError('database');
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
async function withVerifiedBackup(path, maxBytes, requirePrivate, inspect) {
|
|
39
78
|
if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > 20 * 1024 ** 3)
|
|
40
79
|
throw new Error('Backup byte limit must be between 1 byte and 20 GiB');
|
|
41
80
|
const temporary = mkdtempSync(join(tmpdir(), 'security-watch-verify-'));
|
|
42
81
|
try {
|
|
43
82
|
// Copying an existing SQLite inode in this process could release a live Store's locks.
|
|
44
83
|
// A bounded subprocess also keeps a damaged backup from blocking the worker indefinitely.
|
|
45
|
-
const result = await runFile(process.execPath, [
|
|
84
|
+
const result = await runFile(process.execPath, [
|
|
85
|
+
fileURLToPath(import.meta.url),
|
|
86
|
+
'--verify-copy',
|
|
87
|
+
resolve(path),
|
|
88
|
+
temporary,
|
|
89
|
+
String(maxBytes),
|
|
90
|
+
...(requirePrivate ? ['--private'] : []),
|
|
91
|
+
], {
|
|
46
92
|
timeout: 60_000,
|
|
47
93
|
killSignal: 'SIGKILL',
|
|
48
94
|
maxBuffer: 32_768,
|
|
@@ -52,9 +98,12 @@ export async function verifyBackup(path, options = {}) {
|
|
|
52
98
|
const report = JSON.parse(result.stdout);
|
|
53
99
|
if (!report.ok)
|
|
54
100
|
throw new Error(report.error);
|
|
55
|
-
|
|
101
|
+
const { source_sha256, ...verification } = report;
|
|
102
|
+
return await inspect(verification, join(temporary, 'restored.db'), source_sha256);
|
|
56
103
|
}
|
|
57
104
|
catch (error) {
|
|
105
|
+
if (error instanceof PilotReportError)
|
|
106
|
+
throw error;
|
|
58
107
|
if (error instanceof Error && error.message.startsWith('Backup '))
|
|
59
108
|
throw error;
|
|
60
109
|
throw new Error('Backup verification failed or exceeded its time limit; the original was not changed');
|
|
@@ -76,8 +125,9 @@ function requireStandalone(path) {
|
|
|
76
125
|
throw new Error('Backup must be a standalone snapshot without SQLite sidecar files');
|
|
77
126
|
}
|
|
78
127
|
}
|
|
79
|
-
async function inspectCopy(source, directory, maxBytes) {
|
|
128
|
+
async function inspectCopy(source, directory, maxBytes, requirePrivate) {
|
|
80
129
|
requireStandalone(source);
|
|
130
|
+
const digest = requirePrivate ? createHash('sha256') : undefined;
|
|
81
131
|
const destination = join(directory, 'restored.db');
|
|
82
132
|
const input = openSync(source, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
83
133
|
let bytes = 0;
|
|
@@ -85,6 +135,8 @@ async function inspectCopy(source, directory, maxBytes) {
|
|
|
85
135
|
const before = fstatSync(input);
|
|
86
136
|
if (!before.isFile() || before.nlink !== 1)
|
|
87
137
|
throw new Error('Backup must be a regular file without links');
|
|
138
|
+
if (requirePrivate && process.platform !== 'win32' && (before.mode & 0o077) !== 0)
|
|
139
|
+
throw new Error('Backup must have private permissions');
|
|
88
140
|
if (before.size > maxBytes)
|
|
89
141
|
throw new Error('Backup exceeds the configured byte limit');
|
|
90
142
|
const output = openSync(destination, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
|
|
@@ -97,6 +149,7 @@ async function inspectCopy(source, directory, maxBytes) {
|
|
|
97
149
|
bytes += length;
|
|
98
150
|
if (bytes > maxBytes)
|
|
99
151
|
throw new Error('Backup exceeds the configured byte limit');
|
|
152
|
+
digest?.update(buffer.subarray(0, length));
|
|
100
153
|
let offset = 0;
|
|
101
154
|
while (offset < length)
|
|
102
155
|
offset += writeSync(output, buffer, offset, length - offset);
|
|
@@ -165,8 +218,20 @@ async function inspectCopy(source, directory, maxBytes) {
|
|
|
165
218
|
'status',
|
|
166
219
|
'attempts',
|
|
167
220
|
'available_at',
|
|
221
|
+
'accepted_at',
|
|
168
222
|
'last_error',
|
|
169
223
|
],
|
|
224
|
+
ai_reviews: [
|
|
225
|
+
'finding_id',
|
|
226
|
+
'revision',
|
|
227
|
+
'reason',
|
|
228
|
+
'status',
|
|
229
|
+
'evidence_refs',
|
|
230
|
+
'created_at',
|
|
231
|
+
'reviewed_at',
|
|
232
|
+
'reviewer',
|
|
233
|
+
'note',
|
|
234
|
+
],
|
|
170
235
|
budgets: ['day', 'requests', 'tokens', 'usd'],
|
|
171
236
|
finding_revisions: ['finding_id', 'revision', 'payload', 'decision', 'recorded_at'],
|
|
172
237
|
evidence_revisions: ['source', 'id', 'content_hash', 'payload', 'recorded_at'],
|
|
@@ -184,6 +249,8 @@ async function inspectCopy(source, directory, maxBytes) {
|
|
|
184
249
|
for (const table of ['evidence', 'findings', 'notifications', 'finding_revisions', 'evidence_revisions'])
|
|
185
250
|
if (database.prepare(`SELECT 1 FROM ${table} WHERE NOT json_valid(payload) LIMIT 1`).get())
|
|
186
251
|
throw new Error('Backup contains invalid saved JSON');
|
|
252
|
+
if (database.prepare('SELECT 1 FROM ai_reviews WHERE NOT json_valid(evidence_refs) LIMIT 1').get())
|
|
253
|
+
throw new Error('Backup contains invalid review evidence');
|
|
187
254
|
const count = (table) => Number(database.prepare(`SELECT count(*) AS total FROM ${table}`).get().total);
|
|
188
255
|
const rawScan = database.prepare("SELECT value FROM metadata WHERE key='last_scan'").get()?.value;
|
|
189
256
|
let lastScanAt;
|
|
@@ -196,6 +263,7 @@ async function inspectCopy(source, directory, maxBytes) {
|
|
|
196
263
|
}
|
|
197
264
|
return {
|
|
198
265
|
ok: true,
|
|
266
|
+
...(digest ? { source_sha256: digest.digest('hex') } : {}),
|
|
199
267
|
schema_version: sourceVersion,
|
|
200
268
|
verified_schema_version: SCHEMA_VERSION,
|
|
201
269
|
bytes,
|
|
@@ -216,7 +284,7 @@ if (process.argv[1] &&
|
|
|
216
284
|
resolve(process.argv[1]) === fileURLToPath(import.meta.url) &&
|
|
217
285
|
process.argv[2] === '--verify-copy') {
|
|
218
286
|
// Let module initialization finish before the restore imports Store, which uses the policy types above.
|
|
219
|
-
void inspectCopy(process.argv[3], process.argv[4], Number(process.argv[5])).then((result) => {
|
|
287
|
+
void inspectCopy(process.argv[3], process.argv[4], Number(process.argv[5]), process.argv[6] === '--private').then((result) => {
|
|
220
288
|
process.stdout.write(JSON.stringify(result));
|
|
221
289
|
}, (error) => {
|
|
222
290
|
const message = error instanceof Error && error.message.startsWith('Backup ')
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { Ecosystem } from './ecosystems.js';
|
|
2
|
+
import type { Inventory } from './types.js';
|
|
3
|
+
export declare function mentions(text: string, needle: string): boolean;
|
|
4
|
+
/**
|
|
5
|
+
* Whether prose names this package. A name that is not an English word counts wherever it appears.
|
|
6
|
+
* An English word counts only when the text is about packages, names a release of it, or (for a
|
|
7
|
+
* word that is not among the commonest) writes it as a name. So "buffer overflow in a router" does
|
|
8
|
+
* not match the npm package `buffer`, "federal entities" does not match `entities`, "Next.js" does
|
|
9
|
+
* match `next`, and "a flaw in Express" does match `express`. A name written with a version, such
|
|
10
|
+
* as `send@0.19.0`, always counts.
|
|
11
|
+
*/
|
|
12
|
+
export declare function packageMentioned(text: string, component: {
|
|
13
|
+
ecosystem: Ecosystem;
|
|
14
|
+
name: string;
|
|
15
|
+
}): boolean;
|
|
16
|
+
export interface InventoryMatcher {
|
|
17
|
+
/** Identity keys of every inventory component. */
|
|
18
|
+
packages: Set<string>;
|
|
19
|
+
/** Product names, product keywords and system keywords: terms the operator chose on purpose. */
|
|
20
|
+
declared(text: string): boolean;
|
|
21
|
+
/** Any inventory package named in prose, under the everyday-word rule above. */
|
|
22
|
+
packageNamed(text: string): boolean;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Built once per loaded inventory; a scan compares thousands of records against the same names.
|
|
26
|
+
* Adding or removing entries on the same object rebuilds it. Renaming a component in place (other
|
|
27
|
+
* than the last one of a system) is not noticed: pass a new inventory object after such an edit.
|
|
28
|
+
*/
|
|
29
|
+
export declare function inventoryMatcher(inventory: Inventory): InventoryMatcher;
|