@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.
- package/CONTRIBUTING.md +90 -0
- package/LICENSE +202 -0
- package/README.md +269 -2
- package/SECURITY.md +47 -0
- package/dist/assessment.d.ts +5 -0
- package/dist/assessment.js +398 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +792 -0
- package/dist/config.d.ts +242 -0
- package/dist/config.js +298 -0
- package/dist/cve-now.d.ts +5 -0
- package/dist/cve-now.js +413 -0
- package/dist/delivery.d.ts +26 -0
- package/dist/delivery.js +394 -0
- package/dist/ecosystems.d.ts +25 -0
- package/dist/ecosystems.js +254 -0
- package/dist/engine.d.ts +26 -0
- package/dist/engine.js +307 -0
- package/dist/health.d.ts +17 -0
- package/dist/health.js +70 -0
- package/dist/heartbeat.d.ts +13 -0
- package/dist/heartbeat.js +74 -0
- package/dist/http.d.ts +8 -0
- package/dist/http.js +251 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +15 -0
- package/dist/inventory.d.ts +3 -0
- package/dist/inventory.js +143 -0
- package/dist/lock.d.ts +3 -0
- package/dist/lock.js +112 -0
- package/dist/maintenance.d.ts +43 -0
- package/dist/maintenance.js +227 -0
- package/dist/models.d.ts +20 -0
- package/dist/models.js +602 -0
- package/dist/operations.d.ts +17 -0
- package/dist/operations.js +117 -0
- package/dist/providers.d.ts +209 -0
- package/dist/providers.js +459 -0
- package/dist/setup.d.ts +113 -0
- package/dist/setup.js +100 -0
- package/dist/source-error.d.ts +22 -0
- package/dist/source-error.js +56 -0
- package/dist/sources.d.ts +3 -0
- package/dist/sources.js +1071 -0
- package/dist/store.d.ts +71 -0
- package/dist/store.js +651 -0
- package/dist/types.d.ts +247 -0
- package/dist/types.js +1 -0
- package/dist/util.d.ts +6 -0
- package/dist/util.js +14 -0
- package/dist/vendor-sources.d.ts +24 -0
- package/dist/vendor-sources.js +56 -0
- package/docs/configuration.md +406 -0
- package/docs/quality-review.md +104 -0
- package/examples/advisories.json +17 -0
- package/examples/common-systems.yaml +243 -0
- package/examples/libraries.example.txt +16 -0
- package/examples/libraries.example.yaml +38 -0
- package/examples/library-watch.example.yaml +27 -0
- package/examples/security-watch.example.yaml +86 -0
- package/examples/systems.example.yaml +31 -0
- package/package.json +69 -4
package/dist/http.js
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
import { request as httpsRequest } from 'node:https';
|
|
2
|
+
import { request as httpRequest } from 'node:http';
|
|
3
|
+
import { lookup } from 'node:dns';
|
|
4
|
+
import { isIP } from 'node:net';
|
|
5
|
+
import ipaddr from 'ipaddr.js';
|
|
6
|
+
export class NetworkError extends Error {
|
|
7
|
+
code;
|
|
8
|
+
constructor(code) {
|
|
9
|
+
super(code);
|
|
10
|
+
this.code = code;
|
|
11
|
+
this.name = 'NetworkError';
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
const originSchedules = new Map();
|
|
15
|
+
const MAX_COOLDOWN_MS = 3_600_000;
|
|
16
|
+
function pumpOrigin(origin, schedule) {
|
|
17
|
+
clearTimeout(schedule.timer);
|
|
18
|
+
schedule.timer = undefined;
|
|
19
|
+
const delay = Math.max(0, schedule.nextStart, schedule.cooldown) - Date.now();
|
|
20
|
+
if (!schedule.queue.length) {
|
|
21
|
+
if (schedule.active)
|
|
22
|
+
return;
|
|
23
|
+
if (delay <= 0)
|
|
24
|
+
originSchedules.delete(origin);
|
|
25
|
+
else {
|
|
26
|
+
schedule.timer = setTimeout(() => pumpOrigin(origin, schedule), delay);
|
|
27
|
+
schedule.timer.unref();
|
|
28
|
+
}
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
if (delay > 0) {
|
|
32
|
+
schedule.timer = setTimeout(() => pumpOrigin(origin, schedule), delay);
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
const waiter = schedule.queue.shift();
|
|
36
|
+
waiter.cleanup();
|
|
37
|
+
schedule.active++;
|
|
38
|
+
schedule.nextStart = Date.now() + schedule.interval;
|
|
39
|
+
waiter.ready(() => {
|
|
40
|
+
schedule.active--;
|
|
41
|
+
pumpOrigin(origin, schedule);
|
|
42
|
+
});
|
|
43
|
+
pumpOrigin(origin, schedule);
|
|
44
|
+
}
|
|
45
|
+
function originSlot(origin, options, deadline) {
|
|
46
|
+
const interval = options.minIntervalMs ?? 0;
|
|
47
|
+
if (!Number.isFinite(interval) || interval < 0 || interval > MAX_COOLDOWN_MS)
|
|
48
|
+
throw new NetworkError('INVALID_REQUEST_INTERVAL');
|
|
49
|
+
let schedule = originSchedules.get(origin);
|
|
50
|
+
if (!schedule && !interval)
|
|
51
|
+
return Promise.resolve(() => { });
|
|
52
|
+
if (!schedule) {
|
|
53
|
+
schedule = { queue: [], interval, nextStart: 0, cooldown: 0, active: 0 };
|
|
54
|
+
originSchedules.set(origin, schedule);
|
|
55
|
+
}
|
|
56
|
+
const current = schedule;
|
|
57
|
+
current.interval = Math.max(current.interval, interval);
|
|
58
|
+
return new Promise((resolve, reject) => {
|
|
59
|
+
const remove = (code) => {
|
|
60
|
+
const index = current.queue.indexOf(waiter);
|
|
61
|
+
if (index < 0)
|
|
62
|
+
return;
|
|
63
|
+
current.queue.splice(index, 1);
|
|
64
|
+
waiter.cleanup();
|
|
65
|
+
waiter.fail(new NetworkError(code));
|
|
66
|
+
pumpOrigin(origin, current);
|
|
67
|
+
};
|
|
68
|
+
const abort = () => remove('REQUEST_ABORTED');
|
|
69
|
+
const timer = setTimeout(() => remove('REQUEST_TIMEOUT'), Math.max(0, deadline - Date.now()));
|
|
70
|
+
const waiter = {
|
|
71
|
+
ready: resolve,
|
|
72
|
+
fail: reject,
|
|
73
|
+
cleanup: () => {
|
|
74
|
+
clearTimeout(timer);
|
|
75
|
+
options.signal?.removeEventListener('abort', abort);
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
current.queue.push(waiter);
|
|
79
|
+
options.signal?.addEventListener('abort', abort, { once: true });
|
|
80
|
+
if (options.signal?.aborted)
|
|
81
|
+
abort();
|
|
82
|
+
else if (deadline <= Date.now())
|
|
83
|
+
remove('REQUEST_TIMEOUT');
|
|
84
|
+
else
|
|
85
|
+
pumpOrigin(origin, current);
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
function recordCooldown(origin, status, retryAfter) {
|
|
89
|
+
const schedule = originSchedules.get(origin);
|
|
90
|
+
if (!schedule || ![403, 429].includes(status) || typeof retryAfter !== 'string')
|
|
91
|
+
return;
|
|
92
|
+
const value = retryAfter.trim();
|
|
93
|
+
const until = /^\d+$/.test(value) ? Date.now() + Number(value) * 1000 : Date.parse(value);
|
|
94
|
+
if (!(until > Date.now()))
|
|
95
|
+
return;
|
|
96
|
+
schedule.cooldown = Math.max(schedule.cooldown, Math.min(until, Date.now() + MAX_COOLDOWN_MS));
|
|
97
|
+
pumpOrigin(origin, schedule);
|
|
98
|
+
}
|
|
99
|
+
export function isPublicAddress(address) {
|
|
100
|
+
try {
|
|
101
|
+
const parsed = ipaddr.process(address);
|
|
102
|
+
return parsed.range() === 'unicast';
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
export function validateDestination(value, allowPrivate = false) {
|
|
109
|
+
let url;
|
|
110
|
+
try {
|
|
111
|
+
url = new URL(value);
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
throw new NetworkError('INVALID_URL');
|
|
115
|
+
}
|
|
116
|
+
if (url.username ||
|
|
117
|
+
url.password ||
|
|
118
|
+
url.hash ||
|
|
119
|
+
!['https:', ...(allowPrivate ? ['http:'] : [])].includes(url.protocol))
|
|
120
|
+
throw new NetworkError('DESTINATION_DENIED');
|
|
121
|
+
const host = url.hostname.replace(/^\[|\]$/g, '');
|
|
122
|
+
if (!allowPrivate &&
|
|
123
|
+
(host === 'localhost' || host.endsWith('.localhost') || (isIP(host) && !isPublicAddress(host))))
|
|
124
|
+
throw new NetworkError('DESTINATION_DENIED');
|
|
125
|
+
return url;
|
|
126
|
+
}
|
|
127
|
+
export const safeHttp = async (value, options = {}) => {
|
|
128
|
+
if (options.signal?.aborted)
|
|
129
|
+
throw new NetworkError('REQUEST_ABORTED');
|
|
130
|
+
const url = validateDestination(value, options.allowPrivate);
|
|
131
|
+
const maxBytes = options.maxBytes ?? 4_194_304;
|
|
132
|
+
const timeoutMs = options.timeoutMs ?? 20_000;
|
|
133
|
+
const deadline = Date.now() + timeoutMs;
|
|
134
|
+
if (Buffer.byteLength(options.body ?? '') > 2_097_152)
|
|
135
|
+
throw new NetworkError('REQUEST_TOO_LARGE');
|
|
136
|
+
const secureLookup = (hostname, lookupOptions, callback) => {
|
|
137
|
+
lookup(hostname, { all: true, verbatim: true }, (error, addresses) => {
|
|
138
|
+
if (error || !addresses.length) {
|
|
139
|
+
callback(new NetworkError('DNS_FAILED'), '', 4);
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
if (!options.allowPrivate && addresses.some((a) => !isPublicAddress(a.address))) {
|
|
143
|
+
callback(new NetworkError('DESTINATION_DENIED'), '', 4);
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
// Resolve and validate the addresses actually used by the socket, including redirects.
|
|
147
|
+
if (lookupOptions.all)
|
|
148
|
+
callback(null, addresses);
|
|
149
|
+
else
|
|
150
|
+
callback(null, addresses[0].address, addresses[0].family);
|
|
151
|
+
});
|
|
152
|
+
};
|
|
153
|
+
const release = await originSlot(url.origin, options, deadline);
|
|
154
|
+
let response;
|
|
155
|
+
try {
|
|
156
|
+
if (options.signal?.aborted)
|
|
157
|
+
throw new NetworkError('REQUEST_ABORTED');
|
|
158
|
+
if (deadline <= Date.now())
|
|
159
|
+
throw new NetworkError('REQUEST_TIMEOUT');
|
|
160
|
+
response = await new Promise((resolve, reject) => {
|
|
161
|
+
const request = url.protocol === 'https:' ? httpsRequest : httpRequest;
|
|
162
|
+
let connected = false;
|
|
163
|
+
const req = request(url, {
|
|
164
|
+
method: options.method ?? 'GET',
|
|
165
|
+
lookup: secureLookup,
|
|
166
|
+
agent: false,
|
|
167
|
+
signal: options.signal,
|
|
168
|
+
headers: {
|
|
169
|
+
'user-agent': 'Shielda-Security-Watch/0.1',
|
|
170
|
+
'accept-encoding': 'identity',
|
|
171
|
+
...options.headers,
|
|
172
|
+
},
|
|
173
|
+
}, (res) => {
|
|
174
|
+
recordCooldown(url.origin, res.statusCode ?? 0, res.headers['retry-after']);
|
|
175
|
+
const chunks = [];
|
|
176
|
+
let size = 0;
|
|
177
|
+
res.on('data', (chunk) => {
|
|
178
|
+
size += chunk.length;
|
|
179
|
+
if (size > maxBytes) {
|
|
180
|
+
clearTimeout(timer);
|
|
181
|
+
reject(new NetworkError('RESPONSE_TOO_LARGE'));
|
|
182
|
+
res.destroy();
|
|
183
|
+
req.destroy();
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
chunks.push(chunk);
|
|
187
|
+
});
|
|
188
|
+
res.on('error', () => {
|
|
189
|
+
clearTimeout(timer);
|
|
190
|
+
reject(new NetworkError(options.signal?.aborted ? 'REQUEST_ABORTED' : 'RESPONSE_FAILED'));
|
|
191
|
+
});
|
|
192
|
+
res.on('end', () => {
|
|
193
|
+
clearTimeout(timer);
|
|
194
|
+
const headers = Object.fromEntries(Object.entries(res.headers).map(([k, v]) => [k, Array.isArray(v) ? v.join(',') : (v ?? '')]));
|
|
195
|
+
resolve({ status: res.statusCode ?? 0, headers, body: Buffer.concat(chunks).toString('utf8') });
|
|
196
|
+
});
|
|
197
|
+
});
|
|
198
|
+
const timer = setTimeout(() => req.destroy(new NetworkError('REQUEST_TIMEOUT')), Math.max(0, deadline - Date.now()));
|
|
199
|
+
req.on('socket', (socket) => {
|
|
200
|
+
if (!socket.connecting)
|
|
201
|
+
connected = true;
|
|
202
|
+
else
|
|
203
|
+
socket.once('connect', () => (connected = true));
|
|
204
|
+
});
|
|
205
|
+
req.on('error', (error) => {
|
|
206
|
+
clearTimeout(timer);
|
|
207
|
+
const code = 'code' in error ? error.code : undefined;
|
|
208
|
+
const connectionFailed = !connected &&
|
|
209
|
+
(['ECONNREFUSED', 'ENETUNREACH', 'EHOSTUNREACH'].includes(String(code)) ||
|
|
210
|
+
(error instanceof NetworkError && error.code === 'REQUEST_TIMEOUT'));
|
|
211
|
+
reject(options.signal?.aborted
|
|
212
|
+
? new NetworkError('REQUEST_ABORTED')
|
|
213
|
+
: connectionFailed
|
|
214
|
+
? new NetworkError('CONNECTION_FAILED')
|
|
215
|
+
: error instanceof NetworkError
|
|
216
|
+
? error
|
|
217
|
+
: new NetworkError('REQUEST_FAILED'));
|
|
218
|
+
});
|
|
219
|
+
if (options.body)
|
|
220
|
+
req.write(options.body);
|
|
221
|
+
req.end();
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
finally {
|
|
225
|
+
release();
|
|
226
|
+
}
|
|
227
|
+
if ([301, 302, 303, 307, 308].includes(response.status)) {
|
|
228
|
+
const redirects = options.redirects ?? 2;
|
|
229
|
+
if (redirects <= 0 || (options.method && options.method !== 'GET'))
|
|
230
|
+
throw new NetworkError('REDIRECT_DENIED');
|
|
231
|
+
const location = response.headers.location;
|
|
232
|
+
if (!location)
|
|
233
|
+
throw new NetworkError('INVALID_REDIRECT');
|
|
234
|
+
let destination;
|
|
235
|
+
try {
|
|
236
|
+
destination = new URL(location, url).href;
|
|
237
|
+
}
|
|
238
|
+
catch {
|
|
239
|
+
throw new NetworkError('INVALID_REDIRECT');
|
|
240
|
+
}
|
|
241
|
+
const next = validateDestination(destination, options.allowPrivate);
|
|
242
|
+
if (options.allowedRedirectOrigins && !options.allowedRedirectOrigins.includes(next.origin))
|
|
243
|
+
throw new NetworkError('REDIRECT_DENIED');
|
|
244
|
+
const nextOptions = { ...options, redirects: redirects - 1 };
|
|
245
|
+
// Never send authentication headers to a different origin.
|
|
246
|
+
if (next.origin !== url.origin)
|
|
247
|
+
nextOptions.headers = { accept: options.headers?.accept ?? '*/*' };
|
|
248
|
+
return safeHttp(next.href, nextOptions);
|
|
249
|
+
}
|
|
250
|
+
return response;
|
|
251
|
+
};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export * from './types.js';
|
|
2
|
+
export { loadConfig, parseConfig, configSchema } from './config.js';
|
|
3
|
+
export { loadInventory } from './inventory.js';
|
|
4
|
+
export { assess, decide } from './assessment.js';
|
|
5
|
+
export { collectSources } from './sources.js';
|
|
6
|
+
export { ModelAnalyzer, validateAnalysis } from './models.js';
|
|
7
|
+
export { PROVIDERS, PROVIDER_IDS, providerDefinition } from './providers.js';
|
|
8
|
+
export type { ProviderDefinition, ProviderProtocol, ModelProvider, OutputFormat } from './providers.js';
|
|
9
|
+
export { Store } from './store.js';
|
|
10
|
+
export { deliverPending } from './delivery.js';
|
|
11
|
+
export { runScan, readFixture } from './engine.js';
|
|
12
|
+
export { checkHealth } from './health.js';
|
|
13
|
+
export { ECOSYSTEMS, normalizeEcosystem, normalizePackageName, parseLibraryList } from './ecosystems.js';
|
|
14
|
+
export type { Ecosystem, Library } from './ecosystems.js';
|
|
15
|
+
export { HeartbeatMonitor } from './heartbeat.js';
|
|
16
|
+
export { MaintenanceScheduler } from './operations.js';
|
|
17
|
+
export { verifyBackup } from './maintenance.js';
|
|
18
|
+
export type { RetentionPolicy, PruneCounts, PruneReport, BackupVerification } from './maintenance.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export * from './types.js';
|
|
2
|
+
export { loadConfig, parseConfig, configSchema } from './config.js';
|
|
3
|
+
export { loadInventory } from './inventory.js';
|
|
4
|
+
export { assess, decide } from './assessment.js';
|
|
5
|
+
export { collectSources } from './sources.js';
|
|
6
|
+
export { ModelAnalyzer, validateAnalysis } from './models.js';
|
|
7
|
+
export { PROVIDERS, PROVIDER_IDS, providerDefinition } from './providers.js';
|
|
8
|
+
export { Store } from './store.js';
|
|
9
|
+
export { deliverPending } from './delivery.js';
|
|
10
|
+
export { runScan, readFixture } from './engine.js';
|
|
11
|
+
export { checkHealth } from './health.js';
|
|
12
|
+
export { ECOSYSTEMS, normalizeEcosystem, normalizePackageName, parseLibraryList } from './ecosystems.js';
|
|
13
|
+
export { HeartbeatMonitor } from './heartbeat.js';
|
|
14
|
+
export { MaintenanceScheduler } from './operations.js';
|
|
15
|
+
export { verifyBackup } from './maintenance.js';
|
|
@@ -0,0 +1,143 @@
|
|
|
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 { exactLibraryVersion, normalizeEcosystem, normalizePackageName, parseLibrary } from './ecosystems.js';
|
|
6
|
+
import { hash } from './util.js';
|
|
7
|
+
const shortText = z.string().trim().min(1).max(500);
|
|
8
|
+
const npmName = z
|
|
9
|
+
.string()
|
|
10
|
+
.max(214)
|
|
11
|
+
.regex(/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/, 'Expected a canonical npm package name');
|
|
12
|
+
const severity = z.enum(['unknown', 'low', 'medium', 'high', 'critical']);
|
|
13
|
+
const componentSchema = z
|
|
14
|
+
.strictObject({
|
|
15
|
+
id: shortText,
|
|
16
|
+
ecosystem: shortText,
|
|
17
|
+
name: shortText,
|
|
18
|
+
version: shortText.optional(),
|
|
19
|
+
})
|
|
20
|
+
.transform((component) => {
|
|
21
|
+
const ecosystem = normalizeEcosystem(component.ecosystem);
|
|
22
|
+
return {
|
|
23
|
+
...component,
|
|
24
|
+
ecosystem,
|
|
25
|
+
name: normalizePackageName(ecosystem, component.name),
|
|
26
|
+
...(component.version === undefined
|
|
27
|
+
? {}
|
|
28
|
+
: { version: exactLibraryVersion(component.version, ecosystem) }),
|
|
29
|
+
};
|
|
30
|
+
});
|
|
31
|
+
const productSchema = z.strictObject({
|
|
32
|
+
name: shortText,
|
|
33
|
+
version: shortText.optional(),
|
|
34
|
+
keywords: z.array(shortText).max(100).default([]),
|
|
35
|
+
});
|
|
36
|
+
const systemSchema = z.strictObject({
|
|
37
|
+
id: shortText,
|
|
38
|
+
name: shortText,
|
|
39
|
+
environment: shortText.default('unknown'),
|
|
40
|
+
owner: shortText.optional(),
|
|
41
|
+
exposure: z.enum(['internet', 'internal', 'unknown']).default('unknown'),
|
|
42
|
+
criticality: severity.default('unknown'),
|
|
43
|
+
updated_at: z.iso.datetime({ offset: true }),
|
|
44
|
+
components: z.array(componentSchema).max(20_000).default([]),
|
|
45
|
+
libraries: z
|
|
46
|
+
.union([z.array(z.unknown()).max(20_000), z.record(z.string(), z.array(z.unknown()).max(20_000))])
|
|
47
|
+
.optional(),
|
|
48
|
+
products: z.array(productSchema).max(1000).default([]),
|
|
49
|
+
keywords: z.array(shortText).max(100).default([]),
|
|
50
|
+
lockfile: z.string().trim().min(1).max(4096).optional(),
|
|
51
|
+
});
|
|
52
|
+
const inventorySchema = z.strictObject({ systems: z.array(systemSchema).min(1).max(1000) });
|
|
53
|
+
function readBounded(path, maximum) {
|
|
54
|
+
const stat = statSync(path);
|
|
55
|
+
if (!stat.isFile() || stat.size > maximum)
|
|
56
|
+
throw new Error(`Inventory input must be a regular file no larger than ${maximum} bytes: ${path}`);
|
|
57
|
+
const content = readFileSync(path);
|
|
58
|
+
if (content.byteLength > maximum)
|
|
59
|
+
throw new Error(`Inventory input exceeds ${maximum} bytes: ${path}`);
|
|
60
|
+
return content.toString('utf8');
|
|
61
|
+
}
|
|
62
|
+
function record(value) {
|
|
63
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
64
|
+
}
|
|
65
|
+
/** Imports metadata only. No install scripts or package manager commands are executed. */
|
|
66
|
+
function importLockfile(path) {
|
|
67
|
+
const lock = JSON.parse(readBounded(path, 20 * 1024 * 1024));
|
|
68
|
+
if (!record(lock) || (lock.lockfileVersion !== 2 && lock.lockfileVersion !== 3) || !record(lock.packages)) {
|
|
69
|
+
throw new Error(`Expected package-lock v2 or v3 with a packages map: ${path}`);
|
|
70
|
+
}
|
|
71
|
+
const entries = Object.entries(lock.packages);
|
|
72
|
+
if (entries.length > 20_000)
|
|
73
|
+
throw new Error(`Lockfile exceeds 20000 package entries: ${path}`);
|
|
74
|
+
const components = [];
|
|
75
|
+
for (const [location, value] of entries) {
|
|
76
|
+
if (!location || !record(value) || value.link === true)
|
|
77
|
+
continue;
|
|
78
|
+
const match = /(?:^|\/)node_modules\/((?:@[^/]+\/)?[^/]+)$/.exec(location);
|
|
79
|
+
if (!match)
|
|
80
|
+
continue;
|
|
81
|
+
const name = npmName.parse(value.name ?? match[1]);
|
|
82
|
+
const version = value.version === undefined ? undefined : shortText.parse(value.version);
|
|
83
|
+
components.push({
|
|
84
|
+
id: `lock:${location}`,
|
|
85
|
+
ecosystem: 'npm',
|
|
86
|
+
name,
|
|
87
|
+
...(version === undefined ? {} : { version }),
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
return components;
|
|
91
|
+
}
|
|
92
|
+
/** Load a local YAML/JSON inventory, checking its size and schema. */
|
|
93
|
+
export function loadInventory(path) {
|
|
94
|
+
const absolute = resolve(path);
|
|
95
|
+
const document = parseDocument(readBounded(absolute, 2 * 1024 * 1024), { uniqueKeys: true });
|
|
96
|
+
if (document.errors.length)
|
|
97
|
+
throw new Error(`Invalid inventory YAML: ${document.errors[0].message}`);
|
|
98
|
+
const parsed = inventorySchema.parse(document.toJS({ maxAliasCount: 0 }));
|
|
99
|
+
const systemIds = new Set();
|
|
100
|
+
const systems = parsed.systems.map(({ lockfile, libraries, ...system }) => {
|
|
101
|
+
if (systemIds.has(system.id))
|
|
102
|
+
throw new Error(`Duplicate system ID: ${system.id}`);
|
|
103
|
+
systemIds.add(system.id);
|
|
104
|
+
if (libraries) {
|
|
105
|
+
const groups = Array.isArray(libraries) ? [[undefined, libraries]] : Object.entries(libraries);
|
|
106
|
+
const added = new Set(system.components.map((component) => JSON.stringify([component.ecosystem, component.name, component.version ?? null])));
|
|
107
|
+
let count = 0;
|
|
108
|
+
for (const [ecosystem, entries] of groups) {
|
|
109
|
+
if (ecosystem !== undefined)
|
|
110
|
+
normalizeEcosystem(ecosystem);
|
|
111
|
+
for (const entry of entries) {
|
|
112
|
+
if (++count > 20_000)
|
|
113
|
+
throw new Error(`System ${system.id} exceeds 20000 library entries`);
|
|
114
|
+
const library = parseLibrary(entry, ecosystem);
|
|
115
|
+
const key = JSON.stringify([library.ecosystem, library.name, library.version ?? null]);
|
|
116
|
+
if (added.has(key))
|
|
117
|
+
continue;
|
|
118
|
+
added.add(key);
|
|
119
|
+
system.components.push({ id: `library:${hash(key).slice(0, 24)}`, ...library });
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
if (lockfile)
|
|
124
|
+
system.components.push(...importLockfile(resolve(dirname(absolute), lockfile)));
|
|
125
|
+
if (system.components.length > 20_000)
|
|
126
|
+
throw new Error(`System ${system.id} exceeds 20000 components`);
|
|
127
|
+
const componentIds = new Set();
|
|
128
|
+
for (const component of system.components) {
|
|
129
|
+
if (componentIds.has(component.id))
|
|
130
|
+
throw new Error(`Duplicate component ID in ${system.id}: ${component.id}`);
|
|
131
|
+
componentIds.add(component.id);
|
|
132
|
+
}
|
|
133
|
+
const productNames = new Set();
|
|
134
|
+
for (const product of system.products) {
|
|
135
|
+
const name = product.name.toLowerCase();
|
|
136
|
+
if (productNames.has(name))
|
|
137
|
+
throw new Error(`Duplicate product name in ${system.id}: ${product.name}`);
|
|
138
|
+
productNames.add(name);
|
|
139
|
+
}
|
|
140
|
+
return system;
|
|
141
|
+
});
|
|
142
|
+
return { systems };
|
|
143
|
+
}
|
package/dist/lock.d.ts
ADDED
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,43 @@
|
|
|
1
|
+
export interface RetentionPolicy {
|
|
2
|
+
analysis_cache_days?: number;
|
|
3
|
+
evidence_history_days?: number;
|
|
4
|
+
finding_history_days?: number;
|
|
5
|
+
accepted_delivery_days?: number;
|
|
6
|
+
inactive_findings_days?: number;
|
|
7
|
+
unreferenced_evidence_days?: number;
|
|
8
|
+
batch_size?: number;
|
|
9
|
+
}
|
|
10
|
+
export interface PruneCounts {
|
|
11
|
+
analysis_cache: number;
|
|
12
|
+
evidence_history: number;
|
|
13
|
+
finding_history: number;
|
|
14
|
+
accepted_deliveries: number;
|
|
15
|
+
inactive_findings: number;
|
|
16
|
+
unreferenced_evidence: number;
|
|
17
|
+
assessment_bases: number;
|
|
18
|
+
}
|
|
19
|
+
export interface PruneReport {
|
|
20
|
+
applied: boolean;
|
|
21
|
+
planned_at: string;
|
|
22
|
+
counts: PruneCounts;
|
|
23
|
+
total: number;
|
|
24
|
+
more_available: boolean;
|
|
25
|
+
}
|
|
26
|
+
export interface BackupVerification {
|
|
27
|
+
ok: true;
|
|
28
|
+
schema_version: number;
|
|
29
|
+
verified_schema_version: number;
|
|
30
|
+
bytes: number;
|
|
31
|
+
counts: {
|
|
32
|
+
evidence: number;
|
|
33
|
+
findings: number;
|
|
34
|
+
notifications: number;
|
|
35
|
+
budgets: number;
|
|
36
|
+
};
|
|
37
|
+
last_scan_at?: string;
|
|
38
|
+
}
|
|
39
|
+
export declare function validateRetentionPolicy(policy: RetentionPolicy): Required<Pick<RetentionPolicy, 'batch_size'>> & RetentionPolicy;
|
|
40
|
+
/** Restore and inspect a temporary copy. No live database or original backup is replaced. */
|
|
41
|
+
export declare function verifyBackup(path: string, options?: {
|
|
42
|
+
max_bytes?: number;
|
|
43
|
+
}): Promise<BackupVerification>;
|