@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.
Files changed (110) hide show
  1. package/CHANGELOG.md +170 -0
  2. package/CONTRIBUTING.md +92 -0
  3. package/LICENSE +202 -0
  4. package/README.md +394 -2
  5. package/SECURITY.md +62 -0
  6. package/dist/assessment.d.ts +16 -0
  7. package/dist/assessment.js +569 -0
  8. package/dist/cli.d.ts +2 -0
  9. package/dist/cli.js +1105 -0
  10. package/dist/config.d.ts +302 -0
  11. package/dist/config.js +381 -0
  12. package/dist/coverage.d.ts +4 -0
  13. package/dist/coverage.js +11 -0
  14. package/dist/cve-now.d.ts +35 -0
  15. package/dist/cve-now.js +1002 -0
  16. package/dist/cvss4.d.ts +3 -0
  17. package/dist/cvss4.js +39 -0
  18. package/dist/delivery.d.ts +58 -0
  19. package/dist/delivery.js +687 -0
  20. package/dist/ecosystems.d.ts +48 -0
  21. package/dist/ecosystems.js +332 -0
  22. package/dist/engine.d.ts +80 -0
  23. package/dist/engine.js +388 -0
  24. package/dist/everyday-words.d.ts +11 -0
  25. package/dist/everyday-words.js +256 -0
  26. package/dist/health.d.ts +24 -0
  27. package/dist/health.js +122 -0
  28. package/dist/heartbeat.d.ts +13 -0
  29. package/dist/heartbeat.js +74 -0
  30. package/dist/http.d.ts +15 -0
  31. package/dist/http.js +280 -0
  32. package/dist/index.d.ts +36 -0
  33. package/dist/index.js +23 -0
  34. package/dist/inventory-evidence.d.ts +10 -0
  35. package/dist/inventory-evidence.js +206 -0
  36. package/dist/inventory.d.ts +276 -0
  37. package/dist/inventory.js +336 -0
  38. package/dist/lock.d.ts +3 -0
  39. package/dist/lock.js +112 -0
  40. package/dist/maintenance.d.ts +48 -0
  41. package/dist/maintenance.js +295 -0
  42. package/dist/matching.d.ts +29 -0
  43. package/dist/matching.js +537 -0
  44. package/dist/models.d.ts +33 -0
  45. package/dist/models.js +932 -0
  46. package/dist/operations.d.ts +17 -0
  47. package/dist/operations.js +117 -0
  48. package/dist/pilot-cases.d.ts +171 -0
  49. package/dist/pilot-cases.js +330 -0
  50. package/dist/pilot-input.d.ts +16 -0
  51. package/dist/pilot-input.js +125 -0
  52. package/dist/pilot-recall.d.ts +166 -0
  53. package/dist/pilot-recall.js +231 -0
  54. package/dist/pilot-report.d.ts +113 -0
  55. package/dist/pilot-report.js +279 -0
  56. package/dist/pilot-responses.d.ts +111 -0
  57. package/dist/pilot-responses.js +159 -0
  58. package/dist/providers.d.ts +209 -0
  59. package/dist/providers.js +459 -0
  60. package/dist/python-version.d.ts +3 -0
  61. package/dist/python-version.js +30 -0
  62. package/dist/rehearsal.d.ts +440 -0
  63. package/dist/rehearsal.js +372 -0
  64. package/dist/sbom.d.ts +13 -0
  65. package/dist/sbom.js +193 -0
  66. package/dist/setup.d.ts +113 -0
  67. package/dist/setup.js +100 -0
  68. package/dist/source-error.d.ts +38 -0
  69. package/dist/source-error.js +71 -0
  70. package/dist/sources.d.ts +3 -0
  71. package/dist/sources.js +1725 -0
  72. package/dist/store.d.ts +96 -0
  73. package/dist/store.js +953 -0
  74. package/dist/types.d.ts +404 -0
  75. package/dist/types.js +1 -0
  76. package/dist/util.d.ts +29 -0
  77. package/dist/util.js +94 -0
  78. package/dist/vendor/cvss4-reference.d.ts +2 -0
  79. package/dist/vendor/cvss4-reference.js +789 -0
  80. package/dist/vendor-sources.d.ts +24 -0
  81. package/dist/vendor-sources.js +56 -0
  82. package/dist/word-filter.d.ts +3 -0
  83. package/dist/word-filter.js +3291 -0
  84. package/docs/alert-outcome-evaluation.md +150 -0
  85. package/docs/compatibility.md +35 -0
  86. package/docs/configuration.md +666 -0
  87. package/docs/cvss-v4-support.md +41 -0
  88. package/docs/offline-advisory-preview.md +114 -0
  89. package/docs/offline-rehearsal.md +44 -0
  90. package/docs/pilot-cases.md +58 -0
  91. package/docs/pilot-recall.md +124 -0
  92. package/docs/pilot-report.md +52 -0
  93. package/docs/validation/alert-outcome-evaluation-2026-11-05.json +2935 -0
  94. package/docs/validation/cvss-v4-reference-parity-2026-11-05.json +93 -0
  95. package/docs/validation/rehearsal-accepted-2026-11-05.json +175 -0
  96. package/docs/validation/rehearsal-unknown-2026-11-05.json +175 -0
  97. package/docs/vendor/cvss-v4-LICENSE.txt +22 -0
  98. package/docs/vendor/cvss-v4-provenance.json +38 -0
  99. package/examples/advisories.json +17 -0
  100. package/examples/agent-advisories-2026.json +145 -0
  101. package/examples/agent-advisory-cases-2026.json +397 -0
  102. package/examples/common-systems.yaml +243 -0
  103. package/examples/libraries.example.txt +18 -0
  104. package/examples/libraries.example.yaml +40 -0
  105. package/examples/library-watch.example.yaml +27 -0
  106. package/examples/offline-advisory-preview.mjs +42 -0
  107. package/examples/rehearsal.json +75 -0
  108. package/examples/security-watch.example.yaml +86 -0
  109. package/examples/systems.example.yaml +35 -0
  110. package/package.json +85 -4
@@ -0,0 +1,336 @@
1
+ import { readFileSync, statSync } from 'node:fs';
2
+ import { dirname, resolve } from 'node:path';
3
+ import { parseDocument } from 'yaml';
4
+ import { z } from 'zod';
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
11
+ .string()
12
+ .trim()
13
+ .min(1)
14
+ .max(500)
15
+ .refine((value) => !LINE_BREAKING.test(value), 'Control characters are not allowed');
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
+ };
102
+ const componentSchema = z
103
+ .strictObject({
104
+ ...inventoryEvidence,
105
+ id: shortText,
106
+ ecosystem: shortText,
107
+ name: shortText,
108
+ version: shortText.optional(),
109
+ note: evidenceText.optional(),
110
+ })
111
+ .transform((component) => {
112
+ const ecosystem = normalizeEcosystem(component.ecosystem);
113
+ return {
114
+ ...component,
115
+ ecosystem,
116
+ name: normalizePackageName(ecosystem, component.name),
117
+ ...(component.version === undefined
118
+ ? {}
119
+ : { version: exactLibraryVersion(component.version, ecosystem) }),
120
+ };
121
+ });
122
+ const productSchema = z.strictObject({
123
+ name: shortText,
124
+ version: shortText.optional(),
125
+ keywords: z.array(shortText).max(100).default([]),
126
+ note: evidenceText.optional(),
127
+ });
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(),
136
+ id: shortText,
137
+ name: shortText,
138
+ environment: shortText.default('unknown'),
139
+ owner: shortText.optional(),
140
+ note: evidenceText.optional(),
141
+ exposure: z.enum(['internet', 'internal', 'unknown']).default('unknown'),
142
+ criticality: severity.default('unknown'),
143
+ updated_at: z.iso.datetime({ offset: true }),
144
+ components: z.array(componentSchema).max(20_000).default([]),
145
+ libraries: z
146
+ .union([z.array(z.unknown()).max(20_000), z.record(z.string(), z.array(z.unknown()).max(20_000))])
147
+ .optional(),
148
+ products: z.array(productSchema).max(1000).default([]),
149
+ keywords: z.array(shortText).max(100).default([]),
150
+ lockfile: z.string().trim().min(1).max(4096).optional(),
151
+ });
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');
170
+ function readBounded(path, maximum) {
171
+ const stat = statSync(path);
172
+ if (!stat.isFile() || stat.size > maximum)
173
+ throw new Error(`Inventory input must be a regular file no larger than ${maximum} bytes: ${path}`);
174
+ const content = readFileSync(path);
175
+ if (content.byteLength > maximum)
176
+ throw new Error(`Inventory input exceeds ${maximum} bytes: ${path}`);
177
+ return content.toString('utf8');
178
+ }
179
+ function shortLabel(value) {
180
+ return singleLine(value, 120);
181
+ }
182
+ function record(value) {
183
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
184
+ }
185
+ /** Imports metadata only. No install scripts or package manager commands are executed. */
186
+ function importLockfile(path) {
187
+ const lock = JSON.parse(readBounded(path, 20 * 1024 * 1024));
188
+ if (!record(lock) || (lock.lockfileVersion !== 2 && lock.lockfileVersion !== 3) || !record(lock.packages)) {
189
+ throw new Error(`Expected package-lock v2 or v3 with a packages map: ${path}`);
190
+ }
191
+ const entries = Object.entries(lock.packages);
192
+ if (entries.length > 20_000)
193
+ throw new Error(`Lockfile exceeds 20000 package entries: ${path}`);
194
+ const components = [];
195
+ const warnings = [];
196
+ for (const [location, value] of entries) {
197
+ if (!location || !record(value) || value.link === true)
198
+ continue;
199
+ const match = /(?:^|\/)node_modules\/((?:@[^/]+\/)?[^/]+)$/.exec(location);
200
+ if (!match)
201
+ continue;
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
+ }
218
+ components.push({
219
+ id: `lock:${location}`,
220
+ ecosystem: 'npm',
221
+ name,
222
+ ...(version === undefined ? {} : { version }),
223
+ });
224
+ }
225
+ return { components, warnings };
226
+ }
227
+ /** Load a local YAML/JSON inventory, checking its size and schema. */
228
+ export function loadInventory(path) {
229
+ const absolute = resolve(path);
230
+ const document = parseDocument(readBounded(absolute, 2 * 1024 * 1024), { uniqueKeys: true });
231
+ if (document.errors.length)
232
+ throw new Error(`Invalid inventory YAML: ${document.errors[0].message}`);
233
+ const parsed = inventorySchema.parse(document.toJS({ maxAliasCount: 0 }));
234
+ const systemIds = new Set();
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 }) => {
250
+ if (systemIds.has(system.id))
251
+ throw new Error(`Duplicate system ID: ${system.id}`);
252
+ systemIds.add(system.id);
253
+ if (libraries) {
254
+ const groups = Array.isArray(libraries) ? [[undefined, libraries]] : Object.entries(libraries);
255
+ const added = new Map(system.components.map((component) => [
256
+ JSON.stringify([component.ecosystem, component.name, component.version ?? null]),
257
+ component,
258
+ ]));
259
+ let count = 0;
260
+ for (const [ecosystem, entries] of groups) {
261
+ if (ecosystem !== undefined)
262
+ normalizeEcosystem(ecosystem);
263
+ for (const entry of entries) {
264
+ if (++count > 20_000)
265
+ throw new Error(`System ${system.id} exceeds 20000 library entries`);
266
+ const library = parseLibrary(entry, ecosystem);
267
+ const key = JSON.stringify([library.ecosystem, library.name, library.version ?? null]);
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;
274
+ continue;
275
+ }
276
+ const component = { id: `library:${hash(key).slice(0, 24)}`, ...library };
277
+ added.set(key, component);
278
+ system.components.push(component);
279
+ }
280
+ }
281
+ }
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
+ }
310
+ if (system.components.length > 20_000)
311
+ throw new Error(`System ${system.id} exceeds 20000 components`);
312
+ const componentIds = new Set();
313
+ for (const component of system.components) {
314
+ if (componentIds.has(component.id))
315
+ throw new Error(`Duplicate component ID in ${system.id}: ${component.id}`);
316
+ componentIds.add(component.id);
317
+ }
318
+ const productNames = new Set();
319
+ for (const product of system.products) {
320
+ const name = product.name.toLowerCase();
321
+ if (productNames.has(name))
322
+ throw new Error(`Duplicate product name in ${system.id}: ${product.name}`);
323
+ productNames.add(name);
324
+ }
325
+ return system;
326
+ });
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
+ };
336
+ }
package/dist/lock.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ /** Hold a SQLite lock in a separate file. Process exit releases it, so reused PIDs cannot keep it locked. */
2
+ export declare function acquireLock(database: string): () => void;
3
+ export declare function unlockStoppedWorker(database: string): void;
package/dist/lock.js ADDED
@@ -0,0 +1,112 @@
1
+ import { mkdirSync, writeFileSync, readFileSync, unlinkSync, openSync, closeSync, fstatSync, fchmodSync, ftruncateSync, lstatSync, constants, } from 'node:fs';
2
+ import { dirname } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { DatabaseSync } from 'node:sqlite';
5
+ function privateLockDatabase(path) {
6
+ try {
7
+ lstatSync(path);
8
+ }
9
+ catch (error) {
10
+ if (error.code !== 'ENOENT')
11
+ throw error;
12
+ try {
13
+ const fd = openSync(path, constants.O_CREAT | constants.O_EXCL | constants.O_RDWR | constants.O_NOFOLLOW, 0o600);
14
+ closeSync(fd);
15
+ }
16
+ catch (createError) {
17
+ if (createError.code !== 'EEXIST')
18
+ throw createError;
19
+ }
20
+ }
21
+ // Closing another descriptor for an existing SQLite file would release this process's locks.
22
+ const stat = lstatSync(path);
23
+ if (stat.isSymbolicLink())
24
+ throw new Error('Worker lock files must not be symbolic links');
25
+ if (!stat.isFile() || stat.nlink !== 1)
26
+ throw new Error('Worker lock files must be regular files without hard links');
27
+ if (process.platform !== 'win32' && (stat.mode & 0o077) !== 0)
28
+ throw new Error('Worker lock database must have private permissions; stop the worker and set mode 0600');
29
+ }
30
+ function openPrivateFile(path) {
31
+ let fd;
32
+ try {
33
+ fd = openSync(path, constants.O_CREAT | constants.O_RDWR | constants.O_NOFOLLOW | constants.O_NONBLOCK, 0o600);
34
+ }
35
+ catch (error) {
36
+ if (error.code === 'ELOOP')
37
+ throw new Error('Worker lock files must not be symbolic links');
38
+ throw error;
39
+ }
40
+ try {
41
+ const stat = fstatSync(fd);
42
+ if (!stat.isFile() || stat.nlink !== 1)
43
+ throw new Error('Worker lock files must be regular files without hard links');
44
+ fchmodSync(fd, 0o600);
45
+ return fd;
46
+ }
47
+ catch (error) {
48
+ closeSync(fd);
49
+ throw error;
50
+ }
51
+ }
52
+ /** Hold a SQLite lock in a separate file. Process exit releases it, so reused PIDs cannot keep it locked. */
53
+ export function acquireLock(database) {
54
+ if (database === ':memory:')
55
+ return () => { };
56
+ const path = `${database}.worker-lock`;
57
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
58
+ privateLockDatabase(path);
59
+ const connection = new DatabaseSync(path);
60
+ try {
61
+ connection.exec('PRAGMA busy_timeout=0; BEGIN EXCLUSIVE;');
62
+ }
63
+ catch {
64
+ connection.close();
65
+ throw new Error('Another scan or worker is using this database.');
66
+ }
67
+ const nonce = randomUUID();
68
+ const metadata = `${database}.lock`;
69
+ try {
70
+ const fd = openPrivateFile(metadata);
71
+ try {
72
+ // Truncate only after verifying the opened file, so links cannot redirect this write.
73
+ ftruncateSync(fd, 0);
74
+ writeFileSync(fd, JSON.stringify({ pid: process.pid, nonce, started_at: new Date().toISOString() }));
75
+ }
76
+ finally {
77
+ closeSync(fd);
78
+ }
79
+ }
80
+ catch (error) {
81
+ connection.exec('ROLLBACK');
82
+ connection.close();
83
+ throw error;
84
+ }
85
+ let released = false;
86
+ return () => {
87
+ if (released)
88
+ return;
89
+ released = true;
90
+ try {
91
+ const fd = openSync(metadata, constants.O_RDONLY | constants.O_NOFOLLOW);
92
+ try {
93
+ if (fstatSync(fd).isFile() && JSON.parse(readFileSync(fd, 'utf8')).nonce === nonce)
94
+ unlinkSync(metadata);
95
+ }
96
+ finally {
97
+ closeSync(fd);
98
+ }
99
+ }
100
+ catch {
101
+ /* Metadata is informational. */
102
+ }
103
+ finally {
104
+ connection.exec('ROLLBACK');
105
+ connection.close();
106
+ }
107
+ };
108
+ }
109
+ export function unlockStoppedWorker(database) {
110
+ // Successfully acquiring the OS lock proves no other worker owns it. Never delete the SQLite lock file.
111
+ acquireLock(database)();
112
+ }
@@ -0,0 +1,48 @@
1
+ import { type PilotReport, type PilotWindow } from './pilot-report.js';
2
+ export interface RetentionPolicy {
3
+ analysis_cache_days?: number;
4
+ evidence_history_days?: number;
5
+ finding_history_days?: number;
6
+ accepted_delivery_days?: number;
7
+ inactive_findings_days?: number;
8
+ unreferenced_evidence_days?: number;
9
+ batch_size?: number;
10
+ }
11
+ export interface PruneCounts {
12
+ analysis_cache: number;
13
+ evidence_history: number;
14
+ finding_history: number;
15
+ accepted_deliveries: number;
16
+ inactive_findings: number;
17
+ unreferenced_evidence: number;
18
+ assessment_bases: number;
19
+ }
20
+ export interface PruneReport {
21
+ applied: boolean;
22
+ planned_at: string;
23
+ counts: PruneCounts;
24
+ total: number;
25
+ more_available: boolean;
26
+ }
27
+ export interface BackupVerification {
28
+ ok: true;
29
+ schema_version: number;
30
+ verified_schema_version: number;
31
+ bytes: number;
32
+ counts: {
33
+ evidence: number;
34
+ findings: number;
35
+ notifications: number;
36
+ budgets: number;
37
+ };
38
+ last_scan_at?: string;
39
+ }
40
+ export declare function validateRetentionPolicy(policy: RetentionPolicy): Required<Pick<RetentionPolicy, 'batch_size'>> & RetentionPolicy;
41
+ /** Restore and inspect a temporary copy. No live database or original backup is replaced. */
42
+ export declare function verifyBackup(path: string, options?: {
43
+ max_bytes?: number;
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>;