@renovatebot/osv-offline 4.1.1 → 4.2.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/README.md CHANGED
@@ -6,12 +6,20 @@
6
6
 
7
7
  ## Environment variables
8
8
 
9
- | Name | Description | Default |
10
- | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
11
- | `OSV_OFFLINE_ROOT_DIR` | Directory of the downloaded databases | `<tmpdir>/osv-offline` |
12
- | `OSV_OFFLINE_DATABASE_URL` | URL of the database zip | `https://github.com/renovatebot/osv-offline/releases/latest/download/osv-offline.zip` |
13
- | `OSV_OFFLINE_DISABLE_DOWNLOAD` | Set to `true` to use the databases in `OSV_OFFLINE_ROOT_DIR` without downloading them | - |
14
- | `OSV_OFFLINE_MAX_AGE` | How old the downloaded databases may be before they are downloaded again, as a [`ms`](https://github.com/vercel/ms) duration, e.g. `4h` | `1d` |
9
+ | Name | Description | Default |
10
+ | -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
11
+ | `OSV_OFFLINE_ROOT_DIR` | Directory of the downloaded databases | `<tmpdir>/osv-offline` |
12
+ | `OSV_OFFLINE_DATABASE_FORMAT` | `zip` downloads all databases as one zip; `split` downloads each ecosystem on its first query, and again only when it changed | `zip` |
13
+ | `OSV_OFFLINE_DATABASE_URL` | URL of the database zip | `https://github.com/renovatebot/osv-offline/releases/latest/download/osv-offline.zip` |
14
+ | `OSV_OFFLINE_DATABASE_INDEX_URL` | URL of the `index.json` of the split format | `https://renovatebot.github.io/osv-offline/v2/index.json` |
15
+ | `OSV_OFFLINE_DISABLE_DOWNLOAD` | Set to `true` to use the databases in `OSV_OFFLINE_ROOT_DIR` without downloading them | - |
16
+ | `OSV_OFFLINE_MAX_AGE` | How old the downloaded databases may be before they are downloaded again, as a [`ms`](https://github.com/vercel/ms) duration, e.g. `4h` | `1d` |
17
+
18
+ ### Split format
19
+
20
+ With `OSV_OFFLINE_DATABASE_FORMAT=split`, the databases are downloaded from `https://github.com/renovatebot/osv-offline/releases/download/database/`, as listed by the index on `https://renovatebot.github.io/osv-offline/`. When outgoing traffic is restricted, allow `github.com`, `release-assets.githubusercontent.com` (where the downloads redirect to) and `renovatebot.github.io`.
21
+
22
+ To mirror the split format, copy `index.json` without its `baseUrl` and the files it lists into one directory, and set `OSV_OFFLINE_DATABASE_INDEX_URL` to the mirrored `index.json`. Files are resolved relative to the index then.
15
23
 
16
24
  ## License
17
25
 
@@ -1,2 +1,6 @@
1
1
  import { Result } from './types.ts';
2
+ /**
3
+ * Returns how many milliseconds old the local databases may be before they are downloaded again: `OSV_OFFLINE_MAX_AGE` (e.g. `4h`), or one day.
4
+ */
5
+ export declare function getMaxAge(): number;
2
6
  export declare function tryDownloadDb(): Promise<Result>;
@@ -13,7 +13,7 @@ const defaultMaxAge = '1d';
13
13
  /**
14
14
  * Returns how many milliseconds old the local databases may be before they are downloaded again: `OSV_OFFLINE_MAX_AGE` (e.g. `4h`), or one day.
15
15
  */
16
- function getMaxAge() {
16
+ export function getMaxAge() {
17
17
  const value = process.env.OSV_OFFLINE_MAX_AGE;
18
18
  if (!value) {
19
19
  return ms(defaultMaxAge);
@@ -1,6 +1,7 @@
1
1
  import { Ecosystem, Osv } from '@renovatebot/osv-offline-db';
2
2
  export declare class OsvOffline {
3
3
  private osvOfflineDb;
4
+ private readonly splitDownloader;
4
5
  protected constructor();
5
6
  /**
6
7
  * Asynchronous code required as part of class instantiation
@@ -1,9 +1,19 @@
1
1
  import { OsvOfflineDb } from '@renovatebot/osv-offline-db';
2
2
  import { tryDownloadDb } from "./download.js";
3
+ import { SplitDownloader } from "./split.js";
3
4
  import debug from 'debug';
4
5
  const logger = debug('osv-offline:download');
6
+ /**
7
+ * Whether the databases are downloaded in the split format, one ecosystem at a time, instead of as one zip.
8
+ */
9
+ function useSplitFormat() {
10
+ return process.env.OSV_OFFLINE_DATABASE_FORMAT?.toLowerCase() === 'split';
11
+ }
5
12
  export class OsvOffline {
6
13
  osvOfflineDb;
14
+ splitDownloader = useSplitFormat()
15
+ ? new SplitDownloader()
16
+ : undefined;
7
17
  constructor() {
8
18
  logger('Initializing databases ...');
9
19
  this.osvOfflineDb = OsvOfflineDb.create();
@@ -13,6 +23,10 @@ export class OsvOffline {
13
23
  * Asynchronous code required as part of class instantiation
14
24
  */
15
25
  static async initialize() {
26
+ // the split format downloads each ecosystem on its first query
27
+ if (useSplitFormat()) {
28
+ return;
29
+ }
16
30
  const result = await tryDownloadDb();
17
31
  if (!result.success) {
18
32
  throw result.error;
@@ -34,6 +48,7 @@ export class OsvOffline {
34
48
  * @returns An array of {@link Osv.Vulnerability} or an empty array if none are found
35
49
  */
36
50
  async getVulnerabilities(ecosystem, packageName) {
51
+ await this.splitDownloader?.ensure(ecosystem);
37
52
  return this.osvOfflineDb.query(ecosystem, packageName);
38
53
  }
39
54
  [Symbol.dispose]() {
@@ -0,0 +1,36 @@
1
+ import { type Ecosystem } from '@renovatebot/osv-offline-db';
2
+ /**
3
+ * Downloads the databases of the split format: each ecosystem on its first use, and again only when it changed.
4
+ */
5
+ export declare class SplitDownloader {
6
+ private readonly indexUrl;
7
+ private readonly maxAge;
8
+ private index;
9
+ private readonly checked;
10
+ /**
11
+ * Makes sure the files of `ecosystem` are up-to-date. Failures are logged and existing files are kept; without an
12
+ * existing database, failures are thrown. A failed update is retried after a short delay.
13
+ */
14
+ ensure(ecosystem: Ecosystem): Promise<void>;
15
+ /**
16
+ * Updates the files of `ecosystem` when needed, and returns when they were last checked against the index.
17
+ */
18
+ private update;
19
+ /**
20
+ * Downloads the files of `ecosystem` when they differ from the index, and returns when the index was fetched.
21
+ */
22
+ private updateFromIndex;
23
+ /**
24
+ * Returns the index, fetching it when it's missing, older than the maximum age, or `refresh` is set.
25
+ */
26
+ private getIndex;
27
+ /**
28
+ * Downloads a compressed file, decompresses it to `target`, and checks its size and SHA-256.
29
+ */
30
+ private download;
31
+ /**
32
+ * Whether the database of `ecosystem` exists. Its index is optional, the database is read without it.
33
+ */
34
+ private hasDatabase;
35
+ private getStatePath;
36
+ }
@@ -0,0 +1,220 @@
1
+ import { OsvOfflineDb, getIndexFileName, parseSplitIndex, } from '@renovatebot/osv-offline-db';
2
+ import debug from 'debug';
3
+ import fs from 'fs-extra';
4
+ import got from 'got';
5
+ import { createHash } from 'node:crypto';
6
+ import { createWriteStream } from 'node:fs';
7
+ import path from 'node:path';
8
+ import { Transform } from 'node:stream';
9
+ import { pipeline } from 'node:stream/promises';
10
+ import { createZstdDecompress } from 'node:zlib';
11
+ import { getMaxAge } from "./download.js";
12
+ const logger = debug('osv-offline:split');
13
+ const defaultIndexUrl = 'https://renovatebot.github.io/osv-offline/v2/index.json';
14
+ /** how long to wait before retrying a failed update, so an unreachable host isn't requested on every query */
15
+ const retryDelay = 5 * 60 * 1000;
16
+ /**
17
+ * Passes the data through, computing its SHA-256, and fails when it's larger than `maxSize`.
18
+ */
19
+ class Digest extends Transform {
20
+ maxSize;
21
+ name;
22
+ hash = createHash('sha256');
23
+ size = 0;
24
+ constructor(maxSize, name) {
25
+ super();
26
+ this.maxSize = maxSize;
27
+ this.name = name;
28
+ }
29
+ _transform(chunk, _encoding, callback) {
30
+ this.size += chunk.length;
31
+ if (this.size > this.maxSize) {
32
+ callback(new Error(`${this.name} is larger than ${this.maxSize} bytes`));
33
+ return;
34
+ }
35
+ this.hash.update(chunk);
36
+ callback(null, chunk);
37
+ }
38
+ digest() {
39
+ return this.hash.digest('hex');
40
+ }
41
+ }
42
+ function getDatabaseFileName(ecosystem) {
43
+ return `${ecosystem.toLowerCase()}.nedb`;
44
+ }
45
+ function isNotFound(err) {
46
+ return (err.response?.statusCode === 404);
47
+ }
48
+ /**
49
+ * Downloads the databases of the split format: each ecosystem on its first use, and again only when it changed.
50
+ */
51
+ export class SplitDownloader {
52
+ indexUrl = process.env.OSV_OFFLINE_DATABASE_INDEX_URL ?? defaultIndexUrl;
53
+ maxAge = getMaxAge();
54
+ index;
55
+ checked = new Map();
56
+ /**
57
+ * Makes sure the files of `ecosystem` are up-to-date. Failures are logged and existing files are kept; without an
58
+ * existing database, failures are thrown. A failed update is retried after a short delay.
59
+ */
60
+ ensure(ecosystem) {
61
+ if (process.env.OSV_OFFLINE_DISABLE_DOWNLOAD?.toLowerCase() === 'true') {
62
+ return Promise.resolve();
63
+ }
64
+ const checked = this.checked.get(ecosystem);
65
+ if (checked && Date.now() < checked.expires) {
66
+ return checked.promise;
67
+ }
68
+ // concurrent calls share the update; one which never settles is replaced after the maximum age
69
+ const entry = {
70
+ promise: Promise.resolve(),
71
+ expires: Date.now() + this.maxAge,
72
+ };
73
+ entry.promise = (async () => {
74
+ try {
75
+ entry.expires = (await this.update(ecosystem)) + this.maxAge;
76
+ }
77
+ catch (err) {
78
+ entry.expires = Date.now() + Math.min(retryDelay, this.maxAge);
79
+ if (!(await this.hasDatabase(ecosystem))) {
80
+ throw err;
81
+ }
82
+ logger(`Updating ecosystem '${ecosystem}' failed: ${String(err)}`);
83
+ }
84
+ })();
85
+ this.checked.set(ecosystem, entry);
86
+ return entry.promise;
87
+ }
88
+ /**
89
+ * Updates the files of `ecosystem` when needed, and returns when they were last checked against the index.
90
+ */
91
+ async update(ecosystem) {
92
+ const statePath = this.getStatePath(ecosystem);
93
+ const stateStat = await fs.stat(statePath).catch(() => null);
94
+ const age = stateStat ? Date.now() - stateStat.mtimeMs : Infinity;
95
+ // an mtime in the future, e.g. from clock skew, counts as outdated, so it can't extend the maximum age; a second
96
+ // of tolerance, as file times are more precise than Date.now()
97
+ if (stateStat &&
98
+ age > -1000 &&
99
+ age < this.maxAge &&
100
+ (await this.hasDatabase(ecosystem))) {
101
+ logger(`Ecosystem '${ecosystem}' is up-to-date.`);
102
+ return stateStat.mtimeMs;
103
+ }
104
+ try {
105
+ return await this.updateFromIndex(ecosystem, false);
106
+ }
107
+ catch (err) {
108
+ if (!isNotFound(err)) {
109
+ throw err;
110
+ }
111
+ // the index may be outdated, e.g. served by a caching proxy
112
+ logger(`File of ecosystem '${ecosystem}' not found, retrying ...`);
113
+ return await this.updateFromIndex(ecosystem, true);
114
+ }
115
+ }
116
+ /**
117
+ * Downloads the files of `ecosystem` when they differ from the index, and returns when the index was fetched.
118
+ */
119
+ async updateFromIndex(ecosystem, refresh) {
120
+ const { value: index, fetched } = await this.getIndex(refresh);
121
+ const files = index.ecosystems[ecosystem];
122
+ if (!files) {
123
+ logger(`No files for ecosystem '${ecosystem}' in the index.`);
124
+ return fetched;
125
+ }
126
+ const statePath = this.getStatePath(ecosystem);
127
+ const state = (await fs
128
+ .readJson(statePath)
129
+ .catch(() => null));
130
+ if (state?.database === files.database.sha256 &&
131
+ state.index === files.index.sha256 &&
132
+ (await this.hasDatabase(ecosystem))) {
133
+ logger(`Ecosystem '${ecosystem}' is unchanged.`);
134
+ // the files are as fresh as the index they were checked against
135
+ await fs.utimes(statePath, new Date(fetched), new Date(fetched));
136
+ return fetched;
137
+ }
138
+ logger(`Downloading ecosystem '${ecosystem}' ...`);
139
+ await fs.ensureDir(OsvOfflineDb.rootDirectory);
140
+ const tmpDir = await fs.mkdtemp(path.join(OsvOfflineDb.rootDirectory, '.download-'));
141
+ try {
142
+ const baseUrl = index.baseUrl ?? this.indexUrl;
143
+ const indexPath = path.join(tmpDir, getIndexFileName(ecosystem));
144
+ const databasePath = path.join(tmpDir, getDatabaseFileName(ecosystem));
145
+ await this.download(new URL(files.index.file, baseUrl), files.index, indexPath);
146
+ await this.download(new URL(files.database.file, baseUrl), files.database, databasePath);
147
+ // the index first, so a reader never pairs a new database with an old index; it checks they match anyway
148
+ for (const file of [indexPath, databasePath]) {
149
+ await fs.rename(file, path.join(OsvOfflineDb.rootDirectory, path.basename(file)));
150
+ }
151
+ const newState = {
152
+ database: files.database.sha256,
153
+ index: files.index.sha256,
154
+ };
155
+ await fs.writeJson(statePath, newState);
156
+ await fs.utimes(statePath, new Date(fetched), new Date(fetched));
157
+ logger(`Downloading ecosystem '${ecosystem}' done.`);
158
+ return fetched;
159
+ }
160
+ finally {
161
+ await fs.remove(tmpDir);
162
+ }
163
+ }
164
+ /**
165
+ * Returns the index, fetching it when it's missing, older than the maximum age, or `refresh` is set.
166
+ */
167
+ async getIndex(refresh) {
168
+ if (this.index &&
169
+ !refresh &&
170
+ Date.now() - this.index.fetched < this.maxAge) {
171
+ return this.index;
172
+ }
173
+ const url = new URL(this.indexUrl);
174
+ const headers = {};
175
+ if (refresh) {
176
+ // bypass caching proxies, which may still serve an outdated index
177
+ url.searchParams.set('t', Date.now().toString());
178
+ headers['cache-control'] = 'no-cache';
179
+ }
180
+ else if (this.index?.lastModified) {
181
+ headers['if-modified-since'] = this.index.lastModified;
182
+ }
183
+ const response = await got(url, { headers });
184
+ if (response.statusCode === 304 && this.index) {
185
+ this.index.fetched = Date.now();
186
+ return this.index;
187
+ }
188
+ const index = parseSplitIndex(response.body);
189
+ if (!index) {
190
+ throw new Error(`Invalid index at ${this.indexUrl}`);
191
+ }
192
+ this.index = {
193
+ value: index,
194
+ fetched: Date.now(),
195
+ lastModified: response.headers['last-modified'],
196
+ };
197
+ return this.index;
198
+ }
199
+ /**
200
+ * Downloads a compressed file, decompresses it to `target`, and checks its size and SHA-256.
201
+ */
202
+ async download(url, file, target) {
203
+ const digest = new Digest(file.size, file.file);
204
+ // limits the decompressed size, so a broken or malicious file can't fill the disk
205
+ const limit = new Digest(file.uncompressedSize, file.file);
206
+ await pipeline(got.stream(url), digest, createZstdDecompress(), limit, createWriteStream(target));
207
+ if (digest.digest() !== file.sha256) {
208
+ throw new Error(`Checksum mismatch for ${file.file}`);
209
+ }
210
+ }
211
+ /**
212
+ * Whether the database of `ecosystem` exists. Its index is optional, the database is read without it.
213
+ */
214
+ async hasDatabase(ecosystem) {
215
+ return await fs.pathExists(path.join(OsvOfflineDb.rootDirectory, getDatabaseFileName(ecosystem)));
216
+ }
217
+ getStatePath(ecosystem) {
218
+ return path.join(OsvOfflineDb.rootDirectory, `${ecosystem.toLowerCase()}.split.json`);
219
+ }
220
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@renovatebot/osv-offline",
3
- "version": "4.1.1",
3
+ "version": "4.2.0",
4
4
  "main": "dist/index.js",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -12,7 +12,7 @@
12
12
  "url": "https://github.com/renovatebot/osv-offline.git"
13
13
  },
14
14
  "dependencies": {
15
- "@renovatebot/osv-offline-db": "4.1.1",
15
+ "@renovatebot/osv-offline-db": "4.2.0",
16
16
  "debug": "^4.4.3",
17
17
  "fs-extra": "^11.4.1",
18
18
  "got": "^15.1.0",