@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,295 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { execFile } from 'node:child_process';
3
+ import { promisify } from 'node:util';
4
+ import { DatabaseSync } from 'node:sqlite';
5
+ import { closeSync, constants, fstatSync, lstatSync, mkdtempSync, openSync, readSync, rmSync, writeSync, } from 'node:fs';
6
+ import { tmpdir } from 'node:os';
7
+ import { join, resolve } from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { PilotReportError, validatePilotWindow } from './pilot-report.js';
10
+ export function validateRetentionPolicy(policy) {
11
+ if (!policy || typeof policy !== 'object' || Array.isArray(policy))
12
+ throw new Error('Invalid retention policy');
13
+ const periods = new Set([
14
+ 'analysis_cache_days',
15
+ 'evidence_history_days',
16
+ 'finding_history_days',
17
+ 'accepted_delivery_days',
18
+ 'inactive_findings_days',
19
+ 'unreferenced_evidence_days',
20
+ ]);
21
+ let selected = false;
22
+ for (const [key, value] of Object.entries(policy)) {
23
+ if (key !== 'batch_size' && !periods.has(key))
24
+ throw new Error('Unknown retention option');
25
+ if (value === undefined)
26
+ continue;
27
+ if (!Number.isSafeInteger(value) || value < 1 || value > (key === 'batch_size' ? 10000 : 3650))
28
+ throw new Error('Retention periods must be 1–3650 days and batch_size must be 1–10000');
29
+ if (key !== 'batch_size')
30
+ selected = true;
31
+ }
32
+ if (!selected)
33
+ throw new Error('Choose at least one retention period');
34
+ return { ...policy, batch_size: policy.batch_size ?? 1000 };
35
+ }
36
+ const runFile = promisify(execFile);
37
+ const DEFAULT_BACKUP_LIMIT = 512 * 1024 ** 2;
38
+ /** Restore and inspect a temporary copy. No live database or original backup is replaced. */
39
+ export async function verifyBackup(path, options = {}) {
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) {
78
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > 20 * 1024 ** 3)
79
+ throw new Error('Backup byte limit must be between 1 byte and 20 GiB');
80
+ const temporary = mkdtempSync(join(tmpdir(), 'security-watch-verify-'));
81
+ try {
82
+ // Copying an existing SQLite inode in this process could release a live Store's locks.
83
+ // A bounded subprocess also keeps a damaged backup from blocking the worker indefinitely.
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
+ ], {
92
+ timeout: 60_000,
93
+ killSignal: 'SIGKILL',
94
+ maxBuffer: 32_768,
95
+ env: { NODE_NO_WARNINGS: '1' },
96
+ windowsHide: true,
97
+ });
98
+ const report = JSON.parse(result.stdout);
99
+ if (!report.ok)
100
+ throw new Error(report.error);
101
+ const { source_sha256, ...verification } = report;
102
+ return await inspect(verification, join(temporary, 'restored.db'), source_sha256);
103
+ }
104
+ catch (error) {
105
+ if (error instanceof PilotReportError)
106
+ throw error;
107
+ if (error instanceof Error && error.message.startsWith('Backup '))
108
+ throw error;
109
+ throw new Error('Backup verification failed or exceeded its time limit; the original was not changed');
110
+ }
111
+ finally {
112
+ rmSync(temporary, { recursive: true, force: true });
113
+ }
114
+ }
115
+ function requireStandalone(path) {
116
+ for (const suffix of ['-wal', '-shm', '-journal']) {
117
+ try {
118
+ lstatSync(path + suffix);
119
+ }
120
+ catch (error) {
121
+ if (error.code === 'ENOENT')
122
+ continue;
123
+ throw error;
124
+ }
125
+ throw new Error('Backup must be a standalone snapshot without SQLite sidecar files');
126
+ }
127
+ }
128
+ async function inspectCopy(source, directory, maxBytes, requirePrivate) {
129
+ requireStandalone(source);
130
+ const digest = requirePrivate ? createHash('sha256') : undefined;
131
+ const destination = join(directory, 'restored.db');
132
+ const input = openSync(source, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
133
+ let bytes = 0;
134
+ try {
135
+ const before = fstatSync(input);
136
+ if (!before.isFile() || before.nlink !== 1)
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');
140
+ if (before.size > maxBytes)
141
+ throw new Error('Backup exceeds the configured byte limit');
142
+ const output = openSync(destination, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
143
+ try {
144
+ const buffer = Buffer.alloc(65_536);
145
+ for (;;) {
146
+ const length = readSync(input, buffer, 0, Math.min(buffer.length, maxBytes - bytes + 1), null);
147
+ if (!length)
148
+ break;
149
+ bytes += length;
150
+ if (bytes > maxBytes)
151
+ throw new Error('Backup exceeds the configured byte limit');
152
+ digest?.update(buffer.subarray(0, length));
153
+ let offset = 0;
154
+ while (offset < length)
155
+ offset += writeSync(output, buffer, offset, length - offset);
156
+ }
157
+ }
158
+ finally {
159
+ closeSync(output);
160
+ }
161
+ const after = fstatSync(input);
162
+ const current = lstatSync(source);
163
+ if (before.dev !== current.dev ||
164
+ before.ino !== current.ino ||
165
+ !current.isFile() ||
166
+ before.size !== after.size ||
167
+ before.mtimeMs !== after.mtimeMs ||
168
+ before.ctimeMs !== after.ctimeMs ||
169
+ bytes !== before.size)
170
+ throw new Error('Backup changed during verification; create a new snapshot and retry');
171
+ }
172
+ finally {
173
+ closeSync(input);
174
+ }
175
+ requireStandalone(source);
176
+ const { Store, SCHEMA_VERSION } = await import('./store.js');
177
+ let database = new DatabaseSync(destination, { readOnly: true });
178
+ let sourceVersion;
179
+ try {
180
+ database.exec('PRAGMA trusted_schema=OFF; PRAGMA query_only=ON;');
181
+ sourceVersion = Number(database.prepare('PRAGMA user_version').get().user_version);
182
+ if (sourceVersion < 1 || sourceVersion > SCHEMA_VERSION)
183
+ throw new Error('Backup has an unsupported schema version');
184
+ if (database.prepare('PRAGMA quick_check(1)').get().quick_check !== 'ok')
185
+ throw new Error('Backup failed SQLite integrity verification');
186
+ }
187
+ finally {
188
+ database.close();
189
+ }
190
+ // This exercises the same migrations as a restore, exclusively on the private temporary copy.
191
+ const restored = new Store(destination);
192
+ restored.close();
193
+ database = new DatabaseSync(destination, { readOnly: true });
194
+ try {
195
+ database.exec('PRAGMA trusted_schema=OFF; PRAGMA query_only=ON;');
196
+ if (database.prepare('PRAGMA quick_check(1)').get().quick_check !== 'ok' ||
197
+ database.prepare('PRAGMA foreign_key_check').get())
198
+ throw new Error('Backup failed SQLite integrity or relationship verification');
199
+ const requiredColumns = {
200
+ evidence: ['source', 'id', 'payload', 'content_hash', 'fetched_at'],
201
+ metadata: ['key', 'value', 'updated_at'],
202
+ findings: [
203
+ 'id',
204
+ 'payload',
205
+ 'fingerprint',
206
+ 'revision',
207
+ 'acknowledged_revision',
208
+ 'suppressed_until',
209
+ 'suppression_reason',
210
+ 'updated_at',
211
+ ],
212
+ notifications: [
213
+ 'id',
214
+ 'finding_id',
215
+ 'revision',
216
+ 'channel',
217
+ 'payload',
218
+ 'status',
219
+ 'attempts',
220
+ 'available_at',
221
+ 'accepted_at',
222
+ 'last_error',
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
+ ],
235
+ budgets: ['day', 'requests', 'tokens', 'usd'],
236
+ finding_revisions: ['finding_id', 'revision', 'payload', 'decision', 'recorded_at'],
237
+ evidence_revisions: ['source', 'id', 'content_hash', 'payload', 'recorded_at'],
238
+ };
239
+ for (const [table, required] of Object.entries(requiredColumns)) {
240
+ if (database.prepare('SELECT type FROM sqlite_schema WHERE name=?').get(table)?.type !== 'table')
241
+ throw new Error('Backup is missing required application tables');
242
+ const columns = new Set(database
243
+ .prepare(`PRAGMA table_info(${table})`)
244
+ .all()
245
+ .map((row) => String(row.name)));
246
+ if (required.some((column) => !columns.has(column)))
247
+ throw new Error('Backup is missing required application columns');
248
+ }
249
+ for (const table of ['evidence', 'findings', 'notifications', 'finding_revisions', 'evidence_revisions'])
250
+ if (database.prepare(`SELECT 1 FROM ${table} WHERE NOT json_valid(payload) LIMIT 1`).get())
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');
254
+ const count = (table) => Number(database.prepare(`SELECT count(*) AS total FROM ${table}`).get().total);
255
+ const rawScan = database.prepare("SELECT value FROM metadata WHERE key='last_scan'").get()?.value;
256
+ let lastScanAt;
257
+ if (rawScan !== undefined) {
258
+ const scan = JSON.parse(String(rawScan));
259
+ const at = scan?.completed_at ?? scan?.at;
260
+ if (typeof at !== 'string' || !Number.isFinite(Date.parse(at)))
261
+ throw new Error('Backup has invalid scan metadata');
262
+ lastScanAt = new Date(at).toISOString();
263
+ }
264
+ return {
265
+ ok: true,
266
+ ...(digest ? { source_sha256: digest.digest('hex') } : {}),
267
+ schema_version: sourceVersion,
268
+ verified_schema_version: SCHEMA_VERSION,
269
+ bytes,
270
+ counts: {
271
+ evidence: count('evidence'),
272
+ findings: count('findings'),
273
+ notifications: count('notifications'),
274
+ budgets: count('budgets'),
275
+ },
276
+ ...(lastScanAt ? { last_scan_at: lastScanAt } : {}),
277
+ };
278
+ }
279
+ finally {
280
+ database.close();
281
+ }
282
+ }
283
+ if (process.argv[1] &&
284
+ resolve(process.argv[1]) === fileURLToPath(import.meta.url) &&
285
+ process.argv[2] === '--verify-copy') {
286
+ // Let module initialization finish before the restore imports Store, which uses the policy types above.
287
+ void inspectCopy(process.argv[3], process.argv[4], Number(process.argv[5]), process.argv[6] === '--private').then((result) => {
288
+ process.stdout.write(JSON.stringify(result));
289
+ }, (error) => {
290
+ const message = error instanceof Error && error.message.startsWith('Backup ')
291
+ ? error.message
292
+ : 'Backup verification failed; the snapshot is not a readable application database';
293
+ process.stdout.write(JSON.stringify({ ok: false, error: message }));
294
+ });
295
+ }
@@ -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;