@shieldaai/security-watch 0.0.0-stage → 0.1.0-alpha.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 (62) hide show
  1. package/CONTRIBUTING.md +90 -0
  2. package/LICENSE +202 -0
  3. package/README.md +269 -2
  4. package/SECURITY.md +47 -0
  5. package/dist/assessment.d.ts +5 -0
  6. package/dist/assessment.js +398 -0
  7. package/dist/cli.d.ts +2 -0
  8. package/dist/cli.js +792 -0
  9. package/dist/config.d.ts +242 -0
  10. package/dist/config.js +298 -0
  11. package/dist/cve-now.d.ts +5 -0
  12. package/dist/cve-now.js +413 -0
  13. package/dist/delivery.d.ts +26 -0
  14. package/dist/delivery.js +394 -0
  15. package/dist/ecosystems.d.ts +25 -0
  16. package/dist/ecosystems.js +254 -0
  17. package/dist/engine.d.ts +26 -0
  18. package/dist/engine.js +307 -0
  19. package/dist/health.d.ts +17 -0
  20. package/dist/health.js +70 -0
  21. package/dist/heartbeat.d.ts +13 -0
  22. package/dist/heartbeat.js +74 -0
  23. package/dist/http.d.ts +8 -0
  24. package/dist/http.js +251 -0
  25. package/dist/index.d.ts +18 -0
  26. package/dist/index.js +15 -0
  27. package/dist/inventory.d.ts +3 -0
  28. package/dist/inventory.js +143 -0
  29. package/dist/lock.d.ts +3 -0
  30. package/dist/lock.js +112 -0
  31. package/dist/maintenance.d.ts +43 -0
  32. package/dist/maintenance.js +227 -0
  33. package/dist/models.d.ts +20 -0
  34. package/dist/models.js +602 -0
  35. package/dist/operations.d.ts +17 -0
  36. package/dist/operations.js +117 -0
  37. package/dist/providers.d.ts +209 -0
  38. package/dist/providers.js +459 -0
  39. package/dist/setup.d.ts +113 -0
  40. package/dist/setup.js +100 -0
  41. package/dist/source-error.d.ts +22 -0
  42. package/dist/source-error.js +56 -0
  43. package/dist/sources.d.ts +3 -0
  44. package/dist/sources.js +1071 -0
  45. package/dist/store.d.ts +71 -0
  46. package/dist/store.js +651 -0
  47. package/dist/types.d.ts +247 -0
  48. package/dist/types.js +1 -0
  49. package/dist/util.d.ts +6 -0
  50. package/dist/util.js +14 -0
  51. package/dist/vendor-sources.d.ts +24 -0
  52. package/dist/vendor-sources.js +56 -0
  53. package/docs/configuration.md +406 -0
  54. package/docs/quality-review.md +104 -0
  55. package/examples/advisories.json +17 -0
  56. package/examples/common-systems.yaml +243 -0
  57. package/examples/libraries.example.txt +16 -0
  58. package/examples/libraries.example.yaml +38 -0
  59. package/examples/library-watch.example.yaml +27 -0
  60. package/examples/security-watch.example.yaml +86 -0
  61. package/examples/systems.example.yaml +31 -0
  62. package/package.json +69 -4
@@ -0,0 +1,227 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+ import { DatabaseSync } from 'node:sqlite';
4
+ import { closeSync, constants, fstatSync, lstatSync, mkdtempSync, openSync, readSync, rmSync, writeSync, } from 'node:fs';
5
+ import { tmpdir } from 'node:os';
6
+ import { join, resolve } from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ export function validateRetentionPolicy(policy) {
9
+ if (!policy || typeof policy !== 'object' || Array.isArray(policy))
10
+ throw new Error('Invalid retention policy');
11
+ const periods = new Set([
12
+ 'analysis_cache_days',
13
+ 'evidence_history_days',
14
+ 'finding_history_days',
15
+ 'accepted_delivery_days',
16
+ 'inactive_findings_days',
17
+ 'unreferenced_evidence_days',
18
+ ]);
19
+ let selected = false;
20
+ for (const [key, value] of Object.entries(policy)) {
21
+ if (key !== 'batch_size' && !periods.has(key))
22
+ throw new Error('Unknown retention option');
23
+ if (value === undefined)
24
+ continue;
25
+ if (!Number.isSafeInteger(value) || value < 1 || value > (key === 'batch_size' ? 10000 : 3650))
26
+ throw new Error('Retention periods must be 1–3650 days and batch_size must be 1–10000');
27
+ if (key !== 'batch_size')
28
+ selected = true;
29
+ }
30
+ if (!selected)
31
+ throw new Error('Choose at least one retention period');
32
+ return { ...policy, batch_size: policy.batch_size ?? 1000 };
33
+ }
34
+ const runFile = promisify(execFile);
35
+ const DEFAULT_BACKUP_LIMIT = 512 * 1024 ** 2;
36
+ /** Restore and inspect a temporary copy. No live database or original backup is replaced. */
37
+ export async function verifyBackup(path, options = {}) {
38
+ const maxBytes = options.max_bytes ?? DEFAULT_BACKUP_LIMIT;
39
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > 20 * 1024 ** 3)
40
+ throw new Error('Backup byte limit must be between 1 byte and 20 GiB');
41
+ const temporary = mkdtempSync(join(tmpdir(), 'security-watch-verify-'));
42
+ try {
43
+ // Copying an existing SQLite inode in this process could release a live Store's locks.
44
+ // A bounded subprocess also keeps a damaged backup from blocking the worker indefinitely.
45
+ const result = await runFile(process.execPath, [fileURLToPath(import.meta.url), '--verify-copy', resolve(path), temporary, String(maxBytes)], {
46
+ timeout: 60_000,
47
+ killSignal: 'SIGKILL',
48
+ maxBuffer: 32_768,
49
+ env: { NODE_NO_WARNINGS: '1' },
50
+ windowsHide: true,
51
+ });
52
+ const report = JSON.parse(result.stdout);
53
+ if (!report.ok)
54
+ throw new Error(report.error);
55
+ return report;
56
+ }
57
+ catch (error) {
58
+ if (error instanceof Error && error.message.startsWith('Backup '))
59
+ throw error;
60
+ throw new Error('Backup verification failed or exceeded its time limit; the original was not changed');
61
+ }
62
+ finally {
63
+ rmSync(temporary, { recursive: true, force: true });
64
+ }
65
+ }
66
+ function requireStandalone(path) {
67
+ for (const suffix of ['-wal', '-shm', '-journal']) {
68
+ try {
69
+ lstatSync(path + suffix);
70
+ }
71
+ catch (error) {
72
+ if (error.code === 'ENOENT')
73
+ continue;
74
+ throw error;
75
+ }
76
+ throw new Error('Backup must be a standalone snapshot without SQLite sidecar files');
77
+ }
78
+ }
79
+ async function inspectCopy(source, directory, maxBytes) {
80
+ requireStandalone(source);
81
+ const destination = join(directory, 'restored.db');
82
+ const input = openSync(source, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
83
+ let bytes = 0;
84
+ try {
85
+ const before = fstatSync(input);
86
+ if (!before.isFile() || before.nlink !== 1)
87
+ throw new Error('Backup must be a regular file without links');
88
+ if (before.size > maxBytes)
89
+ throw new Error('Backup exceeds the configured byte limit');
90
+ const output = openSync(destination, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
91
+ try {
92
+ const buffer = Buffer.alloc(65_536);
93
+ for (;;) {
94
+ const length = readSync(input, buffer, 0, Math.min(buffer.length, maxBytes - bytes + 1), null);
95
+ if (!length)
96
+ break;
97
+ bytes += length;
98
+ if (bytes > maxBytes)
99
+ throw new Error('Backup exceeds the configured byte limit');
100
+ let offset = 0;
101
+ while (offset < length)
102
+ offset += writeSync(output, buffer, offset, length - offset);
103
+ }
104
+ }
105
+ finally {
106
+ closeSync(output);
107
+ }
108
+ const after = fstatSync(input);
109
+ const current = lstatSync(source);
110
+ if (before.dev !== current.dev ||
111
+ before.ino !== current.ino ||
112
+ !current.isFile() ||
113
+ before.size !== after.size ||
114
+ before.mtimeMs !== after.mtimeMs ||
115
+ before.ctimeMs !== after.ctimeMs ||
116
+ bytes !== before.size)
117
+ throw new Error('Backup changed during verification; create a new snapshot and retry');
118
+ }
119
+ finally {
120
+ closeSync(input);
121
+ }
122
+ requireStandalone(source);
123
+ const { Store, SCHEMA_VERSION } = await import('./store.js');
124
+ let database = new DatabaseSync(destination, { readOnly: true });
125
+ let sourceVersion;
126
+ try {
127
+ database.exec('PRAGMA trusted_schema=OFF; PRAGMA query_only=ON;');
128
+ sourceVersion = Number(database.prepare('PRAGMA user_version').get().user_version);
129
+ if (sourceVersion < 1 || sourceVersion > SCHEMA_VERSION)
130
+ throw new Error('Backup has an unsupported schema version');
131
+ if (database.prepare('PRAGMA quick_check(1)').get().quick_check !== 'ok')
132
+ throw new Error('Backup failed SQLite integrity verification');
133
+ }
134
+ finally {
135
+ database.close();
136
+ }
137
+ // This exercises the same migrations as a restore, exclusively on the private temporary copy.
138
+ const restored = new Store(destination);
139
+ restored.close();
140
+ database = new DatabaseSync(destination, { readOnly: true });
141
+ try {
142
+ database.exec('PRAGMA trusted_schema=OFF; PRAGMA query_only=ON;');
143
+ if (database.prepare('PRAGMA quick_check(1)').get().quick_check !== 'ok' ||
144
+ database.prepare('PRAGMA foreign_key_check').get())
145
+ throw new Error('Backup failed SQLite integrity or relationship verification');
146
+ const requiredColumns = {
147
+ evidence: ['source', 'id', 'payload', 'content_hash', 'fetched_at'],
148
+ metadata: ['key', 'value', 'updated_at'],
149
+ findings: [
150
+ 'id',
151
+ 'payload',
152
+ 'fingerprint',
153
+ 'revision',
154
+ 'acknowledged_revision',
155
+ 'suppressed_until',
156
+ 'suppression_reason',
157
+ 'updated_at',
158
+ ],
159
+ notifications: [
160
+ 'id',
161
+ 'finding_id',
162
+ 'revision',
163
+ 'channel',
164
+ 'payload',
165
+ 'status',
166
+ 'attempts',
167
+ 'available_at',
168
+ 'last_error',
169
+ ],
170
+ budgets: ['day', 'requests', 'tokens', 'usd'],
171
+ finding_revisions: ['finding_id', 'revision', 'payload', 'decision', 'recorded_at'],
172
+ evidence_revisions: ['source', 'id', 'content_hash', 'payload', 'recorded_at'],
173
+ };
174
+ for (const [table, required] of Object.entries(requiredColumns)) {
175
+ if (database.prepare('SELECT type FROM sqlite_schema WHERE name=?').get(table)?.type !== 'table')
176
+ throw new Error('Backup is missing required application tables');
177
+ const columns = new Set(database
178
+ .prepare(`PRAGMA table_info(${table})`)
179
+ .all()
180
+ .map((row) => String(row.name)));
181
+ if (required.some((column) => !columns.has(column)))
182
+ throw new Error('Backup is missing required application columns');
183
+ }
184
+ for (const table of ['evidence', 'findings', 'notifications', 'finding_revisions', 'evidence_revisions'])
185
+ if (database.prepare(`SELECT 1 FROM ${table} WHERE NOT json_valid(payload) LIMIT 1`).get())
186
+ throw new Error('Backup contains invalid saved JSON');
187
+ const count = (table) => Number(database.prepare(`SELECT count(*) AS total FROM ${table}`).get().total);
188
+ const rawScan = database.prepare("SELECT value FROM metadata WHERE key='last_scan'").get()?.value;
189
+ let lastScanAt;
190
+ if (rawScan !== undefined) {
191
+ const scan = JSON.parse(String(rawScan));
192
+ const at = scan?.completed_at ?? scan?.at;
193
+ if (typeof at !== 'string' || !Number.isFinite(Date.parse(at)))
194
+ throw new Error('Backup has invalid scan metadata');
195
+ lastScanAt = new Date(at).toISOString();
196
+ }
197
+ return {
198
+ ok: true,
199
+ schema_version: sourceVersion,
200
+ verified_schema_version: SCHEMA_VERSION,
201
+ bytes,
202
+ counts: {
203
+ evidence: count('evidence'),
204
+ findings: count('findings'),
205
+ notifications: count('notifications'),
206
+ budgets: count('budgets'),
207
+ },
208
+ ...(lastScanAt ? { last_scan_at: lastScanAt } : {}),
209
+ };
210
+ }
211
+ finally {
212
+ database.close();
213
+ }
214
+ }
215
+ if (process.argv[1] &&
216
+ resolve(process.argv[1]) === fileURLToPath(import.meta.url) &&
217
+ process.argv[2] === '--verify-copy') {
218
+ // 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) => {
220
+ process.stdout.write(JSON.stringify(result));
221
+ }, (error) => {
222
+ const message = error instanceof Error && error.message.startsWith('Backup ')
223
+ ? error.message
224
+ : 'Backup verification failed; the snapshot is not a readable application database';
225
+ process.stdout.write(JSON.stringify({ ok: false, error: message }));
226
+ });
227
+ }
@@ -0,0 +1,20 @@
1
+ import type { Assessment, AiAnalysis, Config, Evidence, HttpClient, System } from './types.js';
2
+ export declare const PROMPT_VERSION = "security-watch-9";
3
+ interface ModelState {
4
+ getMeta(key: string): string | undefined;
5
+ setMeta(key: string, value: string): void;
6
+ reserveBudget(day: string, maxRequests: number, maxTokens: number, maxUsd: number | undefined, tokens: number, usd: number | undefined): boolean;
7
+ }
8
+ export declare function validateAnalysis(value: unknown, evidence: Evidence[]): AiAnalysis;
9
+ export declare class ModelAnalyzer {
10
+ private config;
11
+ private store;
12
+ private http;
13
+ private now;
14
+ private signal?;
15
+ private env;
16
+ constructor(config: Config, store: ModelState, http: HttpClient, now?: () => number, signal?: AbortSignal | undefined, env?: Readonly<Record<string, string | undefined>>);
17
+ private call;
18
+ analyze(assessment: Assessment, system: System, evidence: Evidence[]): Promise<Assessment>;
19
+ }
20
+ export {};