@vltpkg/security-archive 1.0.0-rc.23 → 1.0.0-rc.25
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/dist/browser.d.ts +16 -0
- package/dist/browser.js +35 -0
- package/dist/index.d.ts +82 -0
- package/dist/index.js +395 -0
- package/dist/types.d.ts +91 -0
- package/dist/types.js +29 -0
- package/dist/update-expired.d.ts +32 -0
- package/dist/update-expired.js +153 -0
- package/package.json +11 -6
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { PackageReportData, SecurityArchiveLike } from './types.ts';
|
|
2
|
+
import type { DepID } from '@vltpkg/dep-id';
|
|
3
|
+
export * from './types.ts';
|
|
4
|
+
/**
|
|
5
|
+
* A database of security information for given packages in a graph.
|
|
6
|
+
*/
|
|
7
|
+
export declare class SecurityArchive extends Map<DepID, PackageReportData> implements SecurityArchiveLike {
|
|
8
|
+
/**
|
|
9
|
+
* Whether the security archive is valid.
|
|
10
|
+
*/
|
|
11
|
+
ok: boolean;
|
|
12
|
+
/**
|
|
13
|
+
* Loads a security archive from a valid JSON dump.
|
|
14
|
+
*/
|
|
15
|
+
static load(dump: unknown): SecurityArchive | undefined;
|
|
16
|
+
}
|
package/dist/browser.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { asDepID } from '@vltpkg/dep-id/browser';
|
|
2
|
+
import { error } from '@vltpkg/error-cause';
|
|
3
|
+
import { asPackageReportData } from "./types.js";
|
|
4
|
+
export * from "./types.js";
|
|
5
|
+
const isObj = (o) => !!o && typeof o === 'object';
|
|
6
|
+
const isSecurityArchiveJSON = (json) => isObj(json) &&
|
|
7
|
+
Object.entries(json).every(([key, value]) => typeof key === 'string' && isObj(value));
|
|
8
|
+
const asSecurityArchiveJSON = (json) => {
|
|
9
|
+
if (!isSecurityArchiveJSON(json)) {
|
|
10
|
+
throw error('Invalid security archive JSON', { found: json });
|
|
11
|
+
}
|
|
12
|
+
return json;
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* A database of security information for given packages in a graph.
|
|
16
|
+
*/
|
|
17
|
+
export class SecurityArchive extends Map {
|
|
18
|
+
/**
|
|
19
|
+
* Whether the security archive is valid.
|
|
20
|
+
*/
|
|
21
|
+
ok = false;
|
|
22
|
+
/**
|
|
23
|
+
* Loads a security archive from a valid JSON dump.
|
|
24
|
+
*/
|
|
25
|
+
static load(dump) {
|
|
26
|
+
if (dump === undefined)
|
|
27
|
+
return undefined;
|
|
28
|
+
const archive = new SecurityArchive();
|
|
29
|
+
const json = asSecurityArchiveJSON(dump);
|
|
30
|
+
for (const [key, value] of Object.entries(json)) {
|
|
31
|
+
archive.set(asDepID(key), asPackageReportData(value));
|
|
32
|
+
}
|
|
33
|
+
return archive;
|
|
34
|
+
}
|
|
35
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { LRUCache } from 'lru-cache';
|
|
2
|
+
import type { DepID } from '@vltpkg/dep-id';
|
|
3
|
+
import type { PackageReportData, SecurityArchiveLike, SecurityArchiveRefreshOptions } from './types.ts';
|
|
4
|
+
export * from './types.ts';
|
|
5
|
+
export declare const targetSecurityRegisty = "https://registry.npmjs.org/";
|
|
6
|
+
export type JSONItemResponse = {
|
|
7
|
+
namespace?: `@{string}`;
|
|
8
|
+
name: string;
|
|
9
|
+
version: string;
|
|
10
|
+
score: {
|
|
11
|
+
overall: number;
|
|
12
|
+
license: number;
|
|
13
|
+
maintenance: number;
|
|
14
|
+
quality: number;
|
|
15
|
+
supplyChain: number;
|
|
16
|
+
vulnerability: number;
|
|
17
|
+
};
|
|
18
|
+
};
|
|
19
|
+
export type DBReadEntry = {
|
|
20
|
+
depID: string;
|
|
21
|
+
now: number;
|
|
22
|
+
report: string;
|
|
23
|
+
start: number;
|
|
24
|
+
ttl: number;
|
|
25
|
+
};
|
|
26
|
+
export type DBWriteEntry = [string, string, number, number];
|
|
27
|
+
export type SecurityArchiveOptions = LRUCache.OptionsBase<DepID, PackageReportData, unknown> & {
|
|
28
|
+
/**
|
|
29
|
+
* Security archive does not supports a fetch-on-demand model.
|
|
30
|
+
*/
|
|
31
|
+
fetchMethod?: undefined;
|
|
32
|
+
/**
|
|
33
|
+
* An optional value for the path in which to store the sqlite db.
|
|
34
|
+
*/
|
|
35
|
+
path?: string;
|
|
36
|
+
/**
|
|
37
|
+
* Number of retries attempts to reach the remote security API.
|
|
38
|
+
*/
|
|
39
|
+
retries?: number;
|
|
40
|
+
};
|
|
41
|
+
export declare const version: string;
|
|
42
|
+
/**
|
|
43
|
+
* A database of security information for given packages from a list of nodes.
|
|
44
|
+
*
|
|
45
|
+
* Using the SecurityArchive.refresh() method will update the local cache
|
|
46
|
+
* with information from the socket.dev APIs or load from the local storage
|
|
47
|
+
* if available. Information about package security is then available
|
|
48
|
+
* using the SecurityArchive.get() method.
|
|
49
|
+
*/
|
|
50
|
+
export declare class SecurityArchive extends LRUCache<DepID, PackageReportData> implements SecurityArchiveLike {
|
|
51
|
+
#private;
|
|
52
|
+
/**
|
|
53
|
+
* True if the refresh process was successful and report data is available
|
|
54
|
+
* for all public registry packages from the initial list of nodes.
|
|
55
|
+
*/
|
|
56
|
+
ok: boolean;
|
|
57
|
+
/**
|
|
58
|
+
* Creates a new security archive instance and starts the refresh process.
|
|
59
|
+
*/
|
|
60
|
+
static start(options: SecurityArchiveOptions & SecurityArchiveRefreshOptions): Promise<SecurityArchive>;
|
|
61
|
+
/**
|
|
62
|
+
* By default, limits to 100K entries in the in-memory archive.
|
|
63
|
+
*/
|
|
64
|
+
static get defaultMax(): number;
|
|
65
|
+
/**
|
|
66
|
+
* By default, entries are cached for 3 hours.
|
|
67
|
+
*/
|
|
68
|
+
static get defaultTtl(): number;
|
|
69
|
+
constructor(options?: SecurityArchiveOptions);
|
|
70
|
+
/**
|
|
71
|
+
* Starts the security archive by providing an array of {@link NodeLike} instances,
|
|
72
|
+
* its registry-based nodes are going to be used as valid potential entries.
|
|
73
|
+
*
|
|
74
|
+
* Any entry that is missing from the persisted cached values are going
|
|
75
|
+
* to be requested in a batch-request to the remote socket.dev API.
|
|
76
|
+
*/
|
|
77
|
+
refresh({ nodes }: SecurityArchiveRefreshOptions): Promise<void>;
|
|
78
|
+
/**
|
|
79
|
+
* Outputs the current in-memory cache as a JSON object.
|
|
80
|
+
*/
|
|
81
|
+
toJSON(): Record<DepID, PackageReportData>;
|
|
82
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,395 @@
|
|
|
1
|
+
var _a;
|
|
2
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
3
|
+
import { spawn } from 'node:child_process';
|
|
4
|
+
import { mkdirSync } from 'node:fs';
|
|
5
|
+
import { dirname } from 'node:path';
|
|
6
|
+
import { LRUCache } from 'lru-cache';
|
|
7
|
+
import pRetry, { AbortError } from 'p-retry';
|
|
8
|
+
import { loadPackageJson } from 'package-json-from-dist';
|
|
9
|
+
import { asDepID, splitDepID, baseDepID } from '@vltpkg/dep-id';
|
|
10
|
+
import { error } from '@vltpkg/error-cause';
|
|
11
|
+
import { XDG } from '@vltpkg/xdg';
|
|
12
|
+
import { asPackageReportData } from "./types.js";
|
|
13
|
+
import { __CODE_SPLIT_SCRIPT_NAME } from "./update-expired.js";
|
|
14
|
+
export * from "./types.js";
|
|
15
|
+
const SOCKET_API_V0_URL = 'https://api.socket.dev/v0/purl?alerts=true';
|
|
16
|
+
const SOCKET_PUBLIC_API_TOKEN = 'sktsec_t_--RAN5U4ivauy4w37-6aoKyYPDt5ZbaT5JBVMqiwKo_api';
|
|
17
|
+
export const targetSecurityRegisty = 'https://registry.npmjs.org/';
|
|
18
|
+
/**
|
|
19
|
+
* Only the public npm registry has information available in the
|
|
20
|
+
* socket.dev API. This function checks if a given depID is pointing
|
|
21
|
+
* to the public npm registry and returns `true` if it does.
|
|
22
|
+
*/
|
|
23
|
+
const usesTargetRegistry = (node) => {
|
|
24
|
+
const depID = node.id;
|
|
25
|
+
const specOptions = node.options;
|
|
26
|
+
const [nodeType, nodeRegistry] = splitDepID(depID);
|
|
27
|
+
if (nodeType !== 'registry') {
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
const reg = specOptions.registries?.[nodeRegistry];
|
|
31
|
+
return reg === targetSecurityRegisty;
|
|
32
|
+
};
|
|
33
|
+
// Loads the version number to be used in the User-Agent header
|
|
34
|
+
export const { version } = loadPackageJson(import.meta.filename, process.env.__VLT_INTERNAL_CLI_PACKAGE_JSON);
|
|
35
|
+
/**
|
|
36
|
+
* A database of security information for given packages from a list of nodes.
|
|
37
|
+
*
|
|
38
|
+
* Using the SecurityArchive.refresh() method will update the local cache
|
|
39
|
+
* with information from the socket.dev APIs or load from the local storage
|
|
40
|
+
* if available. Information about package security is then available
|
|
41
|
+
* using the SecurityArchive.get() method.
|
|
42
|
+
*/
|
|
43
|
+
export class SecurityArchive extends LRUCache {
|
|
44
|
+
#expired = new Set();
|
|
45
|
+
#path;
|
|
46
|
+
#retries;
|
|
47
|
+
#nodesByName = new Map();
|
|
48
|
+
#nodesByID = new Map();
|
|
49
|
+
/**
|
|
50
|
+
* True if the refresh process was successful and report data is available
|
|
51
|
+
* for all public registry packages from the initial list of nodes.
|
|
52
|
+
*/
|
|
53
|
+
ok = false;
|
|
54
|
+
/**
|
|
55
|
+
* Creates a new security archive instance and starts the refresh process.
|
|
56
|
+
*/
|
|
57
|
+
static async start(options) {
|
|
58
|
+
const archive = new _a(options);
|
|
59
|
+
await archive.refresh(options);
|
|
60
|
+
return archive;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* By default, limits to 100K entries in the in-memory archive.
|
|
64
|
+
*/
|
|
65
|
+
static get defaultMax() {
|
|
66
|
+
return 100_000;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* By default, entries are cached for 3 hours.
|
|
70
|
+
*/
|
|
71
|
+
static get defaultTtl() {
|
|
72
|
+
return 1000 * 60 * 60 * 3;
|
|
73
|
+
}
|
|
74
|
+
constructor(options = {}) {
|
|
75
|
+
super({
|
|
76
|
+
max: _a.defaultMax,
|
|
77
|
+
ttl: _a.defaultTtl,
|
|
78
|
+
...options,
|
|
79
|
+
allowStale: true,
|
|
80
|
+
});
|
|
81
|
+
this.#path =
|
|
82
|
+
options.path ?? new XDG('vlt').cache('security-archive.db');
|
|
83
|
+
this.#retries = options.retries ?? 3;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Retrieves a node using its name and version.
|
|
87
|
+
*/
|
|
88
|
+
#retrieveNodeByNameVersion(name, version) {
|
|
89
|
+
for (const node of this.#nodesByName.get(name) ?? []) {
|
|
90
|
+
if (node.version === version) {
|
|
91
|
+
return node;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Opens a connection to the database at the given path.
|
|
97
|
+
*/
|
|
98
|
+
#openDatabase() {
|
|
99
|
+
mkdirSync(dirname(this.#path), { recursive: true });
|
|
100
|
+
const db = new DatabaseSync(this.#path);
|
|
101
|
+
db.exec('CREATE TABLE IF NOT EXISTS cache ' +
|
|
102
|
+
'(depID TEXT PRIMARY KEY, report TEXT, ttl INTEGER, start INTEGER) ' +
|
|
103
|
+
// WITHOUT ROWID models a key=value storage,
|
|
104
|
+
// enforcing depID must be unique and not null
|
|
105
|
+
// while using less space and more efficient lookups
|
|
106
|
+
// https://www.sqlite.org/withoutrowid.html
|
|
107
|
+
'WITHOUT ROWID');
|
|
108
|
+
db.exec('PRAGMA journal_mode = WAL');
|
|
109
|
+
db.exec('PRAGMA synchronous = NORMAL');
|
|
110
|
+
return db;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Loads all valid items found in the database into the in-memory cache.
|
|
114
|
+
*/
|
|
115
|
+
#loadItemsFromDatabase(db, nodes) {
|
|
116
|
+
const depIDs = [];
|
|
117
|
+
for (const node of nodes) {
|
|
118
|
+
depIDs.push(`'${baseDepID(node.id)}'`);
|
|
119
|
+
}
|
|
120
|
+
// retrieves from the db packages using their dep-id reference
|
|
121
|
+
// and only include entries that have a valid TTL value
|
|
122
|
+
const dbRead = db.prepare('SELECT depID, report, start, ttl, ' +
|
|
123
|
+
`(SELECT UNIXEPOCH('subsecond') * 1000) as now ` +
|
|
124
|
+
'FROM cache ' +
|
|
125
|
+
`WHERE depID IN (${depIDs.join(',')})`);
|
|
126
|
+
// reset the list of expired entries
|
|
127
|
+
this.#expired.clear();
|
|
128
|
+
for (const entry of dbRead.all()) {
|
|
129
|
+
const { depID, now, report, start, ttl } = entry;
|
|
130
|
+
const id = baseDepID(asDepID(depID));
|
|
131
|
+
try {
|
|
132
|
+
this.set(id, asPackageReportData(JSON.parse(report)), {
|
|
133
|
+
ttl,
|
|
134
|
+
start,
|
|
135
|
+
});
|
|
136
|
+
// stale values are queued up as expired for revalidation
|
|
137
|
+
if (start + ttl < now) {
|
|
138
|
+
this.#expired.add(id);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
// prune any invalid entries from the database
|
|
143
|
+
db.prepare('DELETE FROM cache WHERE depID = ?').run(depID);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
// Spawn a detached process to revalidate expired entries in the
|
|
147
|
+
// background so that cli commands (vlt ls, vlt query) don't hang
|
|
148
|
+
// waiting for stale-while-revalidate requests to complete.
|
|
149
|
+
this.#spawnUpdateExpired();
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Spawns a detached child process to revalidate expired entries.
|
|
153
|
+
* The process runs independently — the main process does not wait for it.
|
|
154
|
+
*/
|
|
155
|
+
#spawnUpdateExpired() {
|
|
156
|
+
const expired = [];
|
|
157
|
+
for (const depID of this.#expired) {
|
|
158
|
+
const node = this.#nodesByID.get(baseDepID(depID));
|
|
159
|
+
/* c8 ignore start */
|
|
160
|
+
if (!node?.version || !node.name) {
|
|
161
|
+
// skip any missing node or nodes without a version/name, this
|
|
162
|
+
// should not happen, but some optional dependencies might
|
|
163
|
+
// end up in this state when reading from the lockfile
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
/* c8 ignore stop */
|
|
167
|
+
expired.push({
|
|
168
|
+
depID: baseDepID(depID),
|
|
169
|
+
name: node.name,
|
|
170
|
+
version: node.version,
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
if (!expired.length) {
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
const isDeno = globalThis.Deno !=
|
|
177
|
+
undefined;
|
|
178
|
+
const payload = {
|
|
179
|
+
dbPath: this.#path,
|
|
180
|
+
retries: this.#retries,
|
|
181
|
+
ttl: _a.defaultTtl,
|
|
182
|
+
expired,
|
|
183
|
+
};
|
|
184
|
+
const args = [];
|
|
185
|
+
// Deno on Windows does not support detached processes
|
|
186
|
+
/* c8 ignore next */
|
|
187
|
+
const detached = !(isDeno && process.platform === 'win32');
|
|
188
|
+
/* c8 ignore start */
|
|
189
|
+
if (isDeno) {
|
|
190
|
+
args.push('--unstable-node-globals', '--unstable-bare-node-builtins');
|
|
191
|
+
}
|
|
192
|
+
/* c8 ignore stop */
|
|
193
|
+
args.push(__CODE_SPLIT_SCRIPT_NAME);
|
|
194
|
+
const proc = spawn(process.execPath, args, {
|
|
195
|
+
detached,
|
|
196
|
+
stdio: ['pipe', 'ignore', 'ignore'],
|
|
197
|
+
env: { ...process.env },
|
|
198
|
+
});
|
|
199
|
+
proc.stdin.write(JSON.stringify(payload));
|
|
200
|
+
proc.stdin.end();
|
|
201
|
+
/* c8 ignore start */
|
|
202
|
+
if (detached) {
|
|
203
|
+
proc.unref();
|
|
204
|
+
}
|
|
205
|
+
/* c8 ignore stop */
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* Queues up all required packages that are missing from the archive.
|
|
209
|
+
*/
|
|
210
|
+
#queueUpRequiredPackages() {
|
|
211
|
+
const queue = new Set();
|
|
212
|
+
for (const node of this.#nodesByID.values()) {
|
|
213
|
+
const normalizedId = baseDepID(node.id);
|
|
214
|
+
// only queue up valid public registry
|
|
215
|
+
// references that are missing from the archive
|
|
216
|
+
// also skips any pkg marked as expired
|
|
217
|
+
if (usesTargetRegistry(node) &&
|
|
218
|
+
!this.has(normalizedId) &&
|
|
219
|
+
!this.#expired.has(normalizedId)) {
|
|
220
|
+
const purl = `pkg:npm/${node.name}@${node.version}`;
|
|
221
|
+
queue.add({ purl });
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
return queue;
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Fetches security information from the socket.dev API.
|
|
228
|
+
* Returns a string of NDJSON data.
|
|
229
|
+
*/
|
|
230
|
+
async #retrieveRemoteData(queue) {
|
|
231
|
+
// fetch information from the socket.dev API
|
|
232
|
+
const req = await fetch(SOCKET_API_V0_URL, {
|
|
233
|
+
method: 'POST',
|
|
234
|
+
headers: {
|
|
235
|
+
Authorization: `Basic ${Buffer.from(`${SOCKET_PUBLIC_API_TOKEN}:`).toString('base64url')}`,
|
|
236
|
+
'User-Agent': `@vltpkg/security-archive/${version}`,
|
|
237
|
+
},
|
|
238
|
+
body: JSON.stringify({
|
|
239
|
+
components: Array.from(queue),
|
|
240
|
+
}),
|
|
241
|
+
});
|
|
242
|
+
// on missing valid auth or API, it should abort the retry logic
|
|
243
|
+
if (req.status === 404) {
|
|
244
|
+
throw new AbortError('Missing API');
|
|
245
|
+
}
|
|
246
|
+
// on any other error throws an error that will trigger retry
|
|
247
|
+
if (!req.ok || !(req.status >= 200 && req.status <= 299)) {
|
|
248
|
+
throw error('Failed to fetch security data', { response: req });
|
|
249
|
+
}
|
|
250
|
+
const str = await req.text();
|
|
251
|
+
return str.trim() + '\n';
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Parses and load NDJSON data into the in-memory cache.
|
|
255
|
+
* Returns a set of dep ids that were successfully loaded.
|
|
256
|
+
*/
|
|
257
|
+
#loadFromNDJSON(str) {
|
|
258
|
+
// builds a set of dep ids that were successfully fetched and loaded
|
|
259
|
+
const fetchedDepIDs = new Set();
|
|
260
|
+
const json = str.split('}\n');
|
|
261
|
+
for (const line of json) {
|
|
262
|
+
if (!line.trim())
|
|
263
|
+
continue;
|
|
264
|
+
const data = JSON.parse(line + '}');
|
|
265
|
+
const scope = data.namespace ? `${data.namespace}/` : '';
|
|
266
|
+
const name = `${scope}${data.name}`;
|
|
267
|
+
const node = this.#retrieveNodeByNameVersion(name, data.version);
|
|
268
|
+
if (node) {
|
|
269
|
+
const normalizedId = baseDepID(node.id);
|
|
270
|
+
fetchedDepIDs.add(baseDepID(node.id));
|
|
271
|
+
// Calculate average score from all score components
|
|
272
|
+
const scoreComponents = [
|
|
273
|
+
data.score.license,
|
|
274
|
+
data.score.maintenance,
|
|
275
|
+
data.score.quality,
|
|
276
|
+
data.score.supplyChain,
|
|
277
|
+
data.score.vulnerability,
|
|
278
|
+
];
|
|
279
|
+
const newAverageScore = Number((scoreComponents.reduce((sum, score) => sum + score, 0) /
|
|
280
|
+
scoreComponents.length).toFixed(2));
|
|
281
|
+
// Add average score to the score object
|
|
282
|
+
const scoreWithNewAverage = {
|
|
283
|
+
...data.score,
|
|
284
|
+
overall: newAverageScore,
|
|
285
|
+
};
|
|
286
|
+
this.set(normalizedId, asPackageReportData({
|
|
287
|
+
...data,
|
|
288
|
+
score: scoreWithNewAverage,
|
|
289
|
+
}));
|
|
290
|
+
}
|
|
291
|
+
else {
|
|
292
|
+
// eslint-disable-next-line no-console
|
|
293
|
+
console.warn(`security-archive: failed to find node for ${scope}${data.name}@${data.version} found in the response.`);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
return fetchedDepIDs;
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* Store new in-memory items to the database.
|
|
300
|
+
*/
|
|
301
|
+
#storeNewItemsToDatabase(db, depIDs) {
|
|
302
|
+
const insertData = [];
|
|
303
|
+
for (const depID of depIDs) {
|
|
304
|
+
const entry = this.info(depID);
|
|
305
|
+
if (entry?.start && entry.ttl) {
|
|
306
|
+
insertData.push([
|
|
307
|
+
depID,
|
|
308
|
+
JSON.stringify(entry.value),
|
|
309
|
+
entry.start,
|
|
310
|
+
entry.ttl,
|
|
311
|
+
]);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
const dbWrite = db.prepare('INSERT OR REPLACE INTO cache (depID, report, start, ttl) ' +
|
|
315
|
+
'VALUES (?, ?, ?, ?)');
|
|
316
|
+
for (const data of insertData) {
|
|
317
|
+
dbWrite.run(...data);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* Validates that all public-registry packages in the nodes
|
|
322
|
+
* have a valid report data in the current in-memory cache.
|
|
323
|
+
*/
|
|
324
|
+
#validateReportData() {
|
|
325
|
+
for (const node of this.#nodesByID.values()) {
|
|
326
|
+
if (usesTargetRegistry(node)) {
|
|
327
|
+
if (!this.has(baseDepID(node.id))) {
|
|
328
|
+
this.ok = false;
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
this.ok = true;
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* Starts the security archive by providing an array of {@link NodeLike} instances,
|
|
337
|
+
* its registry-based nodes are going to be used as valid potential entries.
|
|
338
|
+
*
|
|
339
|
+
* Any entry that is missing from the persisted cached values are going
|
|
340
|
+
* to be requested in a batch-request to the remote socket.dev API.
|
|
341
|
+
*/
|
|
342
|
+
async refresh({ nodes }) {
|
|
343
|
+
// should start by clearing the current in-memory cache
|
|
344
|
+
this.clear();
|
|
345
|
+
const db = this.#openDatabase();
|
|
346
|
+
// indexes nodes by name and id for quick lookup
|
|
347
|
+
this.#nodesByName.clear();
|
|
348
|
+
this.#nodesByID.clear();
|
|
349
|
+
for (const node of nodes) {
|
|
350
|
+
/* c8 ignore start */
|
|
351
|
+
const setByName = this.#nodesByName.get(node.name ?? '') ?? new Set();
|
|
352
|
+
setByName.add(node);
|
|
353
|
+
this.#nodesByName.set(node.name ?? '', setByName);
|
|
354
|
+
/* c8 ignore stop */
|
|
355
|
+
this.#nodesByID.set(baseDepID(node.id), node);
|
|
356
|
+
}
|
|
357
|
+
try {
|
|
358
|
+
this.#loadItemsFromDatabase(db, nodes);
|
|
359
|
+
const queue = this.#queueUpRequiredPackages();
|
|
360
|
+
// only reach for the remote API if there are packages queued up
|
|
361
|
+
if (queue.size > 0) {
|
|
362
|
+
// Parse the response data
|
|
363
|
+
const res = await pRetry(() => this.#retrieveRemoteData(queue), { retries: this.#retries });
|
|
364
|
+
const ids = this.#loadFromNDJSON(res);
|
|
365
|
+
this.#storeNewItemsToDatabase(db, ids);
|
|
366
|
+
}
|
|
367
|
+
// validates the refresh process was successful
|
|
368
|
+
this.#validateReportData();
|
|
369
|
+
}
|
|
370
|
+
finally {
|
|
371
|
+
this.#close(db);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
/**
|
|
375
|
+
* Closes the database connection and cleans up the internal state.
|
|
376
|
+
*/
|
|
377
|
+
#close(db) {
|
|
378
|
+
// close db connection
|
|
379
|
+
db.exec('PRAGMA optimize');
|
|
380
|
+
db.close();
|
|
381
|
+
// clean up internal state
|
|
382
|
+
this.#expired.clear();
|
|
383
|
+
}
|
|
384
|
+
/**
|
|
385
|
+
* Outputs the current in-memory cache as a JSON object.
|
|
386
|
+
*/
|
|
387
|
+
toJSON() {
|
|
388
|
+
const obj = {};
|
|
389
|
+
for (const [key, value] of this.dump()) {
|
|
390
|
+
obj[key] = value.value;
|
|
391
|
+
}
|
|
392
|
+
return obj;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
_a = SecurityArchive;
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import type { DepID } from '@vltpkg/dep-id';
|
|
2
|
+
import type { NodeLike } from '@vltpkg/types';
|
|
3
|
+
/**
|
|
4
|
+
* Parameter options for initializing a security archive.
|
|
5
|
+
*/
|
|
6
|
+
export type SecurityArchiveRefreshOptions = {
|
|
7
|
+
/**
|
|
8
|
+
* A @link{GraphLike} instance to find what packages the
|
|
9
|
+
* security archive should have.
|
|
10
|
+
*/
|
|
11
|
+
nodes: NodeLike[];
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* An interface for interacting with a security archive.
|
|
15
|
+
*/
|
|
16
|
+
export interface SecurityArchiveLike {
|
|
17
|
+
get: (depId: DepID) => PackageReportData | undefined;
|
|
18
|
+
set: (depId: DepID, data: PackageReportData) => void;
|
|
19
|
+
delete: (depId: DepID) => void;
|
|
20
|
+
has: (depId: DepID) => boolean;
|
|
21
|
+
clear: () => void;
|
|
22
|
+
ok?: boolean;
|
|
23
|
+
}
|
|
24
|
+
export declare const isSecurityArchiveLike: (o: unknown) => o is SecurityArchiveLike;
|
|
25
|
+
export declare const asSecurityArchiveLike: (o: unknown) => SecurityArchiveLike;
|
|
26
|
+
/**
|
|
27
|
+
* Package alert extra information.
|
|
28
|
+
*/
|
|
29
|
+
export type PackageAlertProps = {
|
|
30
|
+
lastPublish: string;
|
|
31
|
+
cveId?: `CVE-${string}`;
|
|
32
|
+
cwes?: {
|
|
33
|
+
id: `CWE-${string}`;
|
|
34
|
+
}[];
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* A known alert for a given package.
|
|
38
|
+
*/
|
|
39
|
+
export type PackageAlert = {
|
|
40
|
+
key: string;
|
|
41
|
+
type: string;
|
|
42
|
+
severity: 'low' | 'medium' | 'high' | 'critical';
|
|
43
|
+
category: string;
|
|
44
|
+
props?: PackageAlertProps;
|
|
45
|
+
};
|
|
46
|
+
/**
|
|
47
|
+
* The scores for a given package
|
|
48
|
+
*/
|
|
49
|
+
export type PackageScore = {
|
|
50
|
+
/**
|
|
51
|
+
* The average of all score factors. (0-1)
|
|
52
|
+
*/
|
|
53
|
+
overall: number;
|
|
54
|
+
/**
|
|
55
|
+
* Score factors relating to package licensing (0-1)
|
|
56
|
+
*/
|
|
57
|
+
license: number;
|
|
58
|
+
/**
|
|
59
|
+
* Score factors relating to package maintenance (0-1)
|
|
60
|
+
*/
|
|
61
|
+
maintenance: number;
|
|
62
|
+
/**
|
|
63
|
+
* Score factors relating to code quality (0-1)
|
|
64
|
+
*/
|
|
65
|
+
quality: number;
|
|
66
|
+
/**
|
|
67
|
+
* Score factors relating to supply chain security (0-1)
|
|
68
|
+
*/
|
|
69
|
+
supplyChain: number;
|
|
70
|
+
/**
|
|
71
|
+
* Score factors relating to package vulnerabilities (0-1)
|
|
72
|
+
*/
|
|
73
|
+
vulnerability: number;
|
|
74
|
+
};
|
|
75
|
+
/**
|
|
76
|
+
* The report data for a given package.
|
|
77
|
+
*/
|
|
78
|
+
export type PackageReportData = {
|
|
79
|
+
id: string;
|
|
80
|
+
author: string[];
|
|
81
|
+
size: number;
|
|
82
|
+
type: 'npm';
|
|
83
|
+
namespace?: `@${string}`;
|
|
84
|
+
name: string;
|
|
85
|
+
version: string;
|
|
86
|
+
license: string;
|
|
87
|
+
alerts: PackageAlert[];
|
|
88
|
+
score: PackageScore;
|
|
89
|
+
};
|
|
90
|
+
export declare const isPackageReportData: (o: unknown) => o is PackageReportData;
|
|
91
|
+
export declare const asPackageReportData: (o: unknown) => PackageReportData;
|
package/dist/types.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { error } from '@vltpkg/error-cause';
|
|
2
|
+
export const isSecurityArchiveLike = (o) => typeof o === 'object' &&
|
|
3
|
+
o != null &&
|
|
4
|
+
'get' in o &&
|
|
5
|
+
'set' in o &&
|
|
6
|
+
'delete' in o &&
|
|
7
|
+
'has' in o &&
|
|
8
|
+
'clear' in o;
|
|
9
|
+
export const asSecurityArchiveLike = (o) => {
|
|
10
|
+
if (!isSecurityArchiveLike(o)) {
|
|
11
|
+
throw error('Invalid security archive like', { found: o });
|
|
12
|
+
}
|
|
13
|
+
return o;
|
|
14
|
+
};
|
|
15
|
+
export const isPackageReportData = (o) => typeof o === 'object' &&
|
|
16
|
+
o != null &&
|
|
17
|
+
'id' in o &&
|
|
18
|
+
'type' in o &&
|
|
19
|
+
'name' in o &&
|
|
20
|
+
'version' in o &&
|
|
21
|
+
'alerts' in o &&
|
|
22
|
+
'score' in o &&
|
|
23
|
+
o.type === 'npm';
|
|
24
|
+
export const asPackageReportData = (o) => {
|
|
25
|
+
if (!isPackageReportData(o)) {
|
|
26
|
+
throw error('Invalid package report data', { found: o });
|
|
27
|
+
}
|
|
28
|
+
return o;
|
|
29
|
+
};
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { DepID } from '@vltpkg/dep-id';
|
|
2
|
+
import type EventEmitter from 'node:events';
|
|
3
|
+
export declare const __CODE_SPLIT_SCRIPT_NAME: string;
|
|
4
|
+
export declare const version: string;
|
|
5
|
+
/**
|
|
6
|
+
* Serialized payload sent to the detached process via stdin.
|
|
7
|
+
*/
|
|
8
|
+
export type UpdateExpiredPayload = {
|
|
9
|
+
/** Path to the sqlite database */
|
|
10
|
+
dbPath: string;
|
|
11
|
+
/** Number of retries for fetching remote data */
|
|
12
|
+
retries: number;
|
|
13
|
+
/** TTL in ms to use for new entries */
|
|
14
|
+
ttl: number;
|
|
15
|
+
/** Expired entries to revalidate */
|
|
16
|
+
expired: ExpiredEntry[];
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Minimal serialized information for each expired entry.
|
|
20
|
+
* Only carries what's needed for the API call + DB write.
|
|
21
|
+
*/
|
|
22
|
+
export type ExpiredEntry = {
|
|
23
|
+
depID: DepID;
|
|
24
|
+
name: string;
|
|
25
|
+
version: string;
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Main entrypoint for the detached process.
|
|
29
|
+
* Reads a JSON payload from stdin, fetches updated security data,
|
|
30
|
+
* and writes it back to the SQLite database.
|
|
31
|
+
*/
|
|
32
|
+
export declare const main: (input?: EventEmitter) => Promise<boolean>;
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
2
|
+
import { mkdirSync } from 'node:fs';
|
|
3
|
+
import { dirname } from 'node:path';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import pRetry, { AbortError } from 'p-retry';
|
|
6
|
+
import { asDepID, baseDepID } from '@vltpkg/dep-id';
|
|
7
|
+
import { error } from '@vltpkg/error-cause';
|
|
8
|
+
import { loadPackageJson } from 'package-json-from-dist';
|
|
9
|
+
import { asPackageReportData } from "./types.js";
|
|
10
|
+
export const __CODE_SPLIT_SCRIPT_NAME = import.meta.filename;
|
|
11
|
+
const SOCKET_API_V0_URL = 'https://api.socket.dev/v0/purl?alerts=true';
|
|
12
|
+
const SOCKET_PUBLIC_API_TOKEN = 'sktsec_t_--RAN5U4ivauy4w37-6aoKyYPDt5ZbaT5JBVMqiwKo_api';
|
|
13
|
+
export const { version } = loadPackageJson(import.meta.filename, process.env.__VLT_INTERNAL_CLI_PACKAGE_JSON);
|
|
14
|
+
/* c8 ignore start */
|
|
15
|
+
const isMain = (path) => path === __CODE_SPLIT_SCRIPT_NAME ||
|
|
16
|
+
path === pathToFileURL(__CODE_SPLIT_SCRIPT_NAME).toString();
|
|
17
|
+
/* c8 ignore stop */
|
|
18
|
+
/**
|
|
19
|
+
* Fetches security information from the socket.dev API.
|
|
20
|
+
*/
|
|
21
|
+
const retrieveRemoteData = async (queue, retries) => {
|
|
22
|
+
return pRetry(async () => {
|
|
23
|
+
const req = await fetch(SOCKET_API_V0_URL, {
|
|
24
|
+
method: 'POST',
|
|
25
|
+
headers: {
|
|
26
|
+
Authorization: `Basic ${Buffer.from(`${SOCKET_PUBLIC_API_TOKEN}:`).toString('base64url')}`,
|
|
27
|
+
'User-Agent': `@vltpkg/security-archive/${version}`,
|
|
28
|
+
},
|
|
29
|
+
body: JSON.stringify({
|
|
30
|
+
components: Array.from(queue),
|
|
31
|
+
}),
|
|
32
|
+
});
|
|
33
|
+
if (req.status === 404) {
|
|
34
|
+
throw new AbortError('Missing API');
|
|
35
|
+
}
|
|
36
|
+
if (!req.ok || !(req.status >= 200 && req.status <= 299)) {
|
|
37
|
+
throw error('Failed to fetch security data', {
|
|
38
|
+
response: req,
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
const str = await req.text();
|
|
42
|
+
return str.trim() + '\n';
|
|
43
|
+
}, { retries });
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* Main entrypoint for the detached process.
|
|
47
|
+
* Reads a JSON payload from stdin, fetches updated security data,
|
|
48
|
+
* and writes it back to the SQLite database.
|
|
49
|
+
*/
|
|
50
|
+
export const main = async (input = process.stdin) => {
|
|
51
|
+
const payload = await new Promise((resolve, reject) => {
|
|
52
|
+
const chunks = [];
|
|
53
|
+
let chunkLen = 0;
|
|
54
|
+
input.on('data', (chunk) => {
|
|
55
|
+
chunks.push(chunk);
|
|
56
|
+
chunkLen += chunk.length;
|
|
57
|
+
});
|
|
58
|
+
input.on('end', () => {
|
|
59
|
+
try {
|
|
60
|
+
const raw = Buffer.concat(chunks, chunkLen).toString();
|
|
61
|
+
resolve(JSON.parse(raw));
|
|
62
|
+
/* c8 ignore start */
|
|
63
|
+
}
|
|
64
|
+
catch (err) {
|
|
65
|
+
reject(err);
|
|
66
|
+
}
|
|
67
|
+
/* c8 ignore stop */
|
|
68
|
+
});
|
|
69
|
+
/* c8 ignore next */
|
|
70
|
+
input.on('error', reject);
|
|
71
|
+
});
|
|
72
|
+
const { dbPath, retries, ttl, expired } = payload;
|
|
73
|
+
if (!expired.length) {
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
76
|
+
// Build purl queue from expired entries
|
|
77
|
+
const expiredQueue = new Set();
|
|
78
|
+
// Build a lookup map: name@version -> depID
|
|
79
|
+
const entryByNameVersion = new Map();
|
|
80
|
+
for (const entry of expired) {
|
|
81
|
+
const purl = `pkg:npm/${entry.name}@${entry.version}`;
|
|
82
|
+
expiredQueue.add({ purl });
|
|
83
|
+
entryByNameVersion.set(`${entry.name}@${entry.version}`, entry);
|
|
84
|
+
}
|
|
85
|
+
// Fetch updated data
|
|
86
|
+
const res = await retrieveRemoteData(expiredQueue, retries);
|
|
87
|
+
// Parse NDJSON response and collect results
|
|
88
|
+
const now = Date.now();
|
|
89
|
+
const results = [];
|
|
90
|
+
const json = res.split('}\n');
|
|
91
|
+
for (const line of json) {
|
|
92
|
+
if (!line.trim())
|
|
93
|
+
continue;
|
|
94
|
+
const data = JSON.parse(line + '}');
|
|
95
|
+
const scope = data.namespace ? `${data.namespace}/` : '';
|
|
96
|
+
const name = `${scope}${data.name}`;
|
|
97
|
+
const key = `${name}@${data.version}`;
|
|
98
|
+
const entry = entryByNameVersion.get(key);
|
|
99
|
+
if (!entry) {
|
|
100
|
+
// eslint-disable-next-line no-console
|
|
101
|
+
console.warn(`security-archive: failed to find entry for ${key} found in the response.`);
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
// Calculate average score from all score components
|
|
105
|
+
const scoreComponents = [
|
|
106
|
+
data.score.license,
|
|
107
|
+
data.score.maintenance,
|
|
108
|
+
data.score.quality,
|
|
109
|
+
data.score.supplyChain,
|
|
110
|
+
data.score.vulnerability,
|
|
111
|
+
];
|
|
112
|
+
const newAverageScore = Number((scoreComponents.reduce((sum, score) => sum + score, 0) /
|
|
113
|
+
scoreComponents.length).toFixed(2));
|
|
114
|
+
const reportData = asPackageReportData({
|
|
115
|
+
...data,
|
|
116
|
+
score: { ...data.score, overall: newAverageScore },
|
|
117
|
+
});
|
|
118
|
+
results.push({
|
|
119
|
+
depID: baseDepID(asDepID(entry.depID)),
|
|
120
|
+
report: JSON.stringify(reportData),
|
|
121
|
+
start: now,
|
|
122
|
+
ttl,
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
if (!results.length) {
|
|
126
|
+
return false;
|
|
127
|
+
}
|
|
128
|
+
// Write to database
|
|
129
|
+
mkdirSync(dirname(dbPath), { recursive: true });
|
|
130
|
+
const db = new DatabaseSync(dbPath);
|
|
131
|
+
db.exec('CREATE TABLE IF NOT EXISTS cache ' +
|
|
132
|
+
'(depID TEXT PRIMARY KEY, report TEXT, ttl INTEGER, start INTEGER) ' +
|
|
133
|
+
'WITHOUT ROWID');
|
|
134
|
+
db.exec('PRAGMA journal_mode = WAL');
|
|
135
|
+
db.exec('PRAGMA synchronous = NORMAL');
|
|
136
|
+
const dbWrite = db.prepare('INSERT OR REPLACE INTO cache (depID, report, start, ttl) ' +
|
|
137
|
+
'VALUES (?, ?, ?, ?)');
|
|
138
|
+
for (const { depID, report, start, ttl: entryTtl } of results) {
|
|
139
|
+
dbWrite.run(depID, report, start, entryTtl);
|
|
140
|
+
}
|
|
141
|
+
db.exec('PRAGMA optimize');
|
|
142
|
+
db.close();
|
|
143
|
+
return true;
|
|
144
|
+
};
|
|
145
|
+
/* c8 ignore start */
|
|
146
|
+
if (isMain(process.argv[1])) {
|
|
147
|
+
process.title = 'vlt-security-archive-update';
|
|
148
|
+
const res = await main(process.stdin);
|
|
149
|
+
if (!res) {
|
|
150
|
+
process.exit(1);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
/* c8 ignore stop */
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vltpkg/security-archive",
|
|
3
3
|
"description": "A database of security information of packages",
|
|
4
|
-
"version": "1.0.0-rc.
|
|
4
|
+
"version": "1.0.0-rc.25",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
7
7
|
"url": "git+https://github.com/vltpkg/vltpkg.git",
|
|
@@ -12,11 +12,11 @@
|
|
|
12
12
|
"email": "support@vlt.sh"
|
|
13
13
|
},
|
|
14
14
|
"dependencies": {
|
|
15
|
-
"@vltpkg/dep-id": "1.0.0-rc.
|
|
16
|
-
"@vltpkg/error-cause": "1.0.0-rc.
|
|
17
|
-
"@vltpkg/spec": "1.0.0-rc.
|
|
18
|
-
"@vltpkg/types": "1.0.0-rc.
|
|
19
|
-
"@vltpkg/xdg": "1.0.0-rc.
|
|
15
|
+
"@vltpkg/dep-id": "1.0.0-rc.25",
|
|
16
|
+
"@vltpkg/error-cause": "1.0.0-rc.25",
|
|
17
|
+
"@vltpkg/spec": "1.0.0-rc.25",
|
|
18
|
+
"@vltpkg/types": "1.0.0-rc.25",
|
|
19
|
+
"@vltpkg/xdg": "1.0.0-rc.25",
|
|
20
20
|
"lru-cache": "^11.2.4",
|
|
21
21
|
"p-retry": "^7.1.1",
|
|
22
22
|
"package-json-from-dist": "^1.0.1"
|
|
@@ -63,6 +63,11 @@
|
|
|
63
63
|
"import": {
|
|
64
64
|
"default": "./dist/browser.js"
|
|
65
65
|
}
|
|
66
|
+
},
|
|
67
|
+
"./update-expired": {
|
|
68
|
+
"import": {
|
|
69
|
+
"default": "./dist/update-expired.js"
|
|
70
|
+
}
|
|
66
71
|
}
|
|
67
72
|
},
|
|
68
73
|
"files": [
|