korveniq 1.0.3 → 1.0.5
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 +34 -5
- package/bin/index.js +39 -0
- package/lib/build-profile.json +2 -2
- package/lib/chat.js +11 -1
- package/lib/settings.js +35 -1
- package/lib/update-commands.js +125 -0
- package/lib/update-install.js +287 -0
- package/lib/update-recover.js +251 -0
- package/lib/update-semver.js +56 -0
- package/lib/update-source.js +221 -0
- package/lib/update-state.js +341 -0
- package/lib/update-tar.js +140 -0
- package/lib/update-view.js +124 -0
- package/lib/update.js +243 -0
- package/package.json +4 -4
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* lib/update-recover.js
|
|
6
|
+
* -----------------------------------------------------------------------------
|
|
7
|
+
* Finishes or undoes an installation that was interrupted (lib/update-install.js). It is used in two ways:
|
|
8
|
+
*
|
|
9
|
+
* - as a module, by the installer itself (a failed installation is rolled back by the same code) and by a CLI that
|
|
10
|
+
* finds a leftover journal when it starts;
|
|
11
|
+
* - as a program: while files are being swapped, the `korveniq` command points to a COPY of this file (and of
|
|
12
|
+
* update-state.js) in <state>/recovery. If the installer is killed, or the machine stops, the next `korveniq`
|
|
13
|
+
* runs that copy, which repairs the installation, points the command back and runs it.
|
|
14
|
+
*
|
|
15
|
+
* Because it must work when the package folder is missing, it uses only Node and update-state.js.
|
|
16
|
+
*
|
|
17
|
+
* The journal (<state>/swap.json) records what was being swapped. What to do is decided from the file system, so it
|
|
18
|
+
* does not matter between which two steps the interruption happened, including during a recovery:
|
|
19
|
+
*
|
|
20
|
+
* not committed, no installed folder put the previous one back
|
|
21
|
+
* not committed, the new folder is installed it never passed its check: put the previous one back
|
|
22
|
+
* not committed, the old folder is installed nothing was moved
|
|
23
|
+
* committed the new version stays
|
|
24
|
+
* some other folder is installed npm (or a person) replaced it meanwhile: leave it alone
|
|
25
|
+
* npm is at work and the folder is not ours touch nothing yet (the journal stays for a later attempt)
|
|
26
|
+
*
|
|
27
|
+
* Nothing in the journal is used as a path except the name of the work folder, which must have the expected form.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
const fs = require('fs');
|
|
31
|
+
const os = require('os');
|
|
32
|
+
const path = require('path');
|
|
33
|
+
const crypto = require('crypto');
|
|
34
|
+
const state = require('./update-state');
|
|
35
|
+
|
|
36
|
+
const JOURNAL = 'swap.json';
|
|
37
|
+
const WORK_RE = /^work-[0-9a-f]{16}$/;
|
|
38
|
+
const LAUNCHER_FILES = ['update-recover.js', 'update-state.js'];
|
|
39
|
+
|
|
40
|
+
/** The fixed layout around a state folder. */
|
|
41
|
+
function layout(stateDir) {
|
|
42
|
+
const modulesDir = path.dirname(stateDir);
|
|
43
|
+
const prefix = path.dirname(path.dirname(modulesDir));
|
|
44
|
+
const root = path.join(modulesDir, state.NAME);
|
|
45
|
+
return {
|
|
46
|
+
stateDir,
|
|
47
|
+
modulesDir,
|
|
48
|
+
root,
|
|
49
|
+
link: path.join(prefix, 'bin', state.NAME),
|
|
50
|
+
entry: path.join(root, 'bin', 'index.js'),
|
|
51
|
+
journal: path.join(stateDir, JOURNAL),
|
|
52
|
+
launcher: path.join(stateDir, 'recovery', 'update-recover.js'),
|
|
53
|
+
command: state.manualCommand(prefix),
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Which installed folder this is, or null when there is none. The same value before and after a rename, a different one
|
|
59
|
+
* for any other installation. The inode alone is not enough: Linux gives a new folder the number of one just deleted.
|
|
60
|
+
* So the package.json inside counts too (its content and modification time).
|
|
61
|
+
*/
|
|
62
|
+
function identity(dir) {
|
|
63
|
+
let folder;
|
|
64
|
+
try {
|
|
65
|
+
folder = fs.lstatSync(dir, { bigint: true });
|
|
66
|
+
} catch (err) {
|
|
67
|
+
if (err.code === 'ENOENT') return null;
|
|
68
|
+
throw err;
|
|
69
|
+
}
|
|
70
|
+
let inside = '-';
|
|
71
|
+
try {
|
|
72
|
+
const file = path.join(dir, 'package.json');
|
|
73
|
+
const hash = crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
|
|
74
|
+
inside = `${fs.lstatSync(file, { bigint: true }).mtimeNs}:${hash}`;
|
|
75
|
+
} catch {
|
|
76
|
+
/* half written, or not a package */
|
|
77
|
+
}
|
|
78
|
+
return `${folder.dev}:${folder.ino}:${inside}`;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Make a rename or a new file survive a power failure, as far as the system allows. */
|
|
82
|
+
function syncPath(file) {
|
|
83
|
+
let fd = null;
|
|
84
|
+
try {
|
|
85
|
+
fd = fs.openSync(file, 'r');
|
|
86
|
+
fs.fsyncSync(fd);
|
|
87
|
+
} catch {
|
|
88
|
+
/* not supported here */
|
|
89
|
+
} finally {
|
|
90
|
+
if (fd !== null) fs.closeSync(fd);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Point the command somewhere else in one step: there is no moment without a command. */
|
|
95
|
+
function setLink(link, target) {
|
|
96
|
+
const tmp = `${link}.kq-${crypto.randomBytes(6).toString('hex')}`;
|
|
97
|
+
try {
|
|
98
|
+
fs.symlinkSync(target, tmp);
|
|
99
|
+
fs.renameSync(tmp, link);
|
|
100
|
+
} finally {
|
|
101
|
+
fs.rmSync(tmp, { force: true });
|
|
102
|
+
}
|
|
103
|
+
syncPath(path.dirname(link));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function linkTargetOf(link) {
|
|
107
|
+
try {
|
|
108
|
+
return path.resolve(path.dirname(link), fs.readlinkSync(link));
|
|
109
|
+
} catch {
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Temporary links of a setLink() that was killed before its rename. */
|
|
115
|
+
function removeLinkLeftovers(p) {
|
|
116
|
+
const dir = path.dirname(p.link);
|
|
117
|
+
const prefix = `${path.basename(p.link)}.kq-`;
|
|
118
|
+
for (const name of fs.readdirSync(dir)) {
|
|
119
|
+
const file = path.join(dir, name);
|
|
120
|
+
if (name.startsWith(prefix) && /^[0-9a-f]{12}$/.test(name.slice(prefix.length)) && fs.lstatSync(file).isSymbolicLink()) fs.rmSync(file, { force: true });
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Does the command point to the recovery launcher? */
|
|
125
|
+
const diverted = (p) => linkTargetOf(p.link) === p.launcher;
|
|
126
|
+
|
|
127
|
+
/** Put the command back on the package, but only if it is we who moved it. */
|
|
128
|
+
function restoreLink(p) {
|
|
129
|
+
if (diverted(p)) setLink(p.link, path.relative(path.dirname(p.link), p.entry));
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function writeJournal(p, journal) {
|
|
133
|
+
state.writeJson(p.journal, journal, { sync: true });
|
|
134
|
+
syncPath(p.stateDir);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Copy the launcher out of the package that is about to move. */
|
|
138
|
+
function installLauncher(p, from = __dirname) {
|
|
139
|
+
const dir = path.dirname(p.launcher);
|
|
140
|
+
try {
|
|
141
|
+
fs.mkdirSync(dir, { mode: 0o700 });
|
|
142
|
+
} catch (err) {
|
|
143
|
+
if (err.code !== 'EEXIST') throw err;
|
|
144
|
+
}
|
|
145
|
+
if (!fs.lstatSync(dir).isDirectory()) throw new Error(`unsafe update folder: ${dir}`);
|
|
146
|
+
// the library first: the launcher is only used once both are complete
|
|
147
|
+
for (const name of [...LAUNCHER_FILES].reverse()) {
|
|
148
|
+
const target = path.join(dir, name);
|
|
149
|
+
const tmp = `${target}.${crypto.randomBytes(6).toString('hex')}.tmp`;
|
|
150
|
+
fs.writeFileSync(tmp, fs.readFileSync(path.join(from, name)), { flag: 'wx', mode: 0o700 });
|
|
151
|
+
syncPath(tmp);
|
|
152
|
+
fs.renameSync(tmp, target);
|
|
153
|
+
}
|
|
154
|
+
syncPath(dir);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Bring the installation to a consistent state. The caller holds apply.lock.
|
|
159
|
+
* @returns {{ outcome: 'none'|'committed'|'restored'|'external'|'busy'|'broken', changed: boolean }}
|
|
160
|
+
* changed: the installed folder was moved by this call
|
|
161
|
+
*/
|
|
162
|
+
function settle(p, { step = () => {} } = {}) {
|
|
163
|
+
removeLinkLeftovers(p);
|
|
164
|
+
const exists = fs.existsSync(p.journal);
|
|
165
|
+
const journal = exists ? state.readJson(p.journal) : null;
|
|
166
|
+
if (!exists) {
|
|
167
|
+
if (fs.existsSync(p.entry)) restoreLink(p);
|
|
168
|
+
return { outcome: 'none', changed: false };
|
|
169
|
+
}
|
|
170
|
+
const valid = Boolean(journal) && WORK_RE.test(String(journal.work));
|
|
171
|
+
const works = valid
|
|
172
|
+
? [journal.work]
|
|
173
|
+
: fs.readdirSync(p.stateDir).filter((n) => WORK_RE.test(n) && fs.existsSync(path.join(p.stateDir, n, 'previous')));
|
|
174
|
+
const work = works.length ? path.join(p.stateDir, works[works.length - 1]) : null;
|
|
175
|
+
const previous = work && path.join(work, 'previous');
|
|
176
|
+
const current = identity(p.root);
|
|
177
|
+
let outcome = 'restored';
|
|
178
|
+
let changed = false;
|
|
179
|
+
// While npm installs, the folder is missing or half written: moving anything now would damage its installation.
|
|
180
|
+
const ours = valid && (current === journal.oldId || current === journal.newId);
|
|
181
|
+
if (!ours && state.npmBusy(p.modulesDir)) return { outcome: 'busy', changed };
|
|
182
|
+
if (valid && journal.committed === true && current !== null) {
|
|
183
|
+
outcome = 'committed';
|
|
184
|
+
} else if (current === null) {
|
|
185
|
+
if (previous && fs.existsSync(previous)) {
|
|
186
|
+
fs.renameSync(previous, p.root);
|
|
187
|
+
changed = true;
|
|
188
|
+
} else outcome = 'broken';
|
|
189
|
+
} else if (valid && current === journal.newId && fs.existsSync(previous)) {
|
|
190
|
+
fs.renameSync(p.root, path.join(work, 'rejected'));
|
|
191
|
+
step('rejected-removed');
|
|
192
|
+
fs.renameSync(previous, p.root);
|
|
193
|
+
changed = true;
|
|
194
|
+
} else if (valid && current !== journal.oldId) {
|
|
195
|
+
outcome = 'external';
|
|
196
|
+
}
|
|
197
|
+
if (outcome === 'broken') return { outcome, changed }; // keep everything for a later attempt
|
|
198
|
+
syncPath(p.modulesDir);
|
|
199
|
+
step('settled');
|
|
200
|
+
restoreLink(p);
|
|
201
|
+
step('link-restored');
|
|
202
|
+
fs.rmSync(p.journal, { force: true });
|
|
203
|
+
syncPath(p.stateDir);
|
|
204
|
+
step('journal-removed');
|
|
205
|
+
if (work) fs.rmSync(work, { recursive: true, force: true });
|
|
206
|
+
return { outcome, changed };
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Take the lock and settle. 'busy' while an installer (or npm) is working. */
|
|
210
|
+
function recover(stateDir, opts) {
|
|
211
|
+
const p = layout(stateDir);
|
|
212
|
+
const lock = state.acquire(path.join(stateDir, 'apply.lock'));
|
|
213
|
+
if (!lock) return { outcome: 'busy', changed: false };
|
|
214
|
+
try {
|
|
215
|
+
return settle(p, opts);
|
|
216
|
+
} finally {
|
|
217
|
+
lock.release();
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** The launcher: repair, then run the CLI with the same arguments. */
|
|
222
|
+
function main(argv = process.argv.slice(2), { waitMs = 30_000 } = {}) {
|
|
223
|
+
const p = layout(path.dirname(__dirname));
|
|
224
|
+
let result = { outcome: 'busy' };
|
|
225
|
+
try {
|
|
226
|
+
const st = fs.lstatSync(p.stateDir);
|
|
227
|
+
if (!st.isDirectory() || (process.getuid && st.uid !== process.getuid())) throw new Error('the installation belongs to another user');
|
|
228
|
+
for (const end = Date.now() + waitMs; ; ) {
|
|
229
|
+
result = recover(p.stateDir);
|
|
230
|
+
if (result.outcome !== 'busy' || Date.now() >= end) break;
|
|
231
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100);
|
|
232
|
+
}
|
|
233
|
+
} catch (err) {
|
|
234
|
+
result = { outcome: 'failed', error: err.code || err.message };
|
|
235
|
+
}
|
|
236
|
+
if (result.changed) process.stderr.write('Korveniq repaired an interrupted update.\n');
|
|
237
|
+
if (result.outcome !== 'busy' && fs.existsSync(p.entry)) {
|
|
238
|
+
const run = require('child_process').spawnSync(process.execPath, [p.entry, ...argv], { stdio: 'inherit' });
|
|
239
|
+
process.exit(run.status === null ? 128 + (os.constants.signals[run.signal] || 0) : run.status);
|
|
240
|
+
}
|
|
241
|
+
process.stderr.write(
|
|
242
|
+
result.outcome === 'busy'
|
|
243
|
+
? '! Korveniq is being updated. Try again in a moment.\n'
|
|
244
|
+
: `! An update of Korveniq was interrupted and could not be repaired${result.error ? ` (${result.error})` : ''}.\n Reinstall it with:\n ${p.command}\n`,
|
|
245
|
+
);
|
|
246
|
+
process.exit(result.outcome === 'busy' ? 75 : 1);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
module.exports = { JOURNAL, layout, identity, syncPath, setLink, diverted, restoreLink, writeJournal, installLauncher, settle, recover };
|
|
250
|
+
|
|
251
|
+
if (require.main === module) main();
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* lib/update-semver.js: strict Semantic Versioning 2.0.0 parsing and ordering, for the updater only.
|
|
5
|
+
* (lib/compat.js reads the server's looser version hints; an installer must not be loose.)
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
const NUM = '(0|[1-9]\\d{0,14})';
|
|
9
|
+
const IDS = '[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*';
|
|
10
|
+
const RE = new RegExp(`^${NUM}\\.${NUM}\\.${NUM}(?:-(${IDS}))?(?:\\+(${IDS}))?$`);
|
|
11
|
+
|
|
12
|
+
/** { major, minor, patch, pre: string[] } or null for anything that is not exactly a version. */
|
|
13
|
+
function parse(value) {
|
|
14
|
+
if (typeof value !== 'string' || value.length > 128) return null;
|
|
15
|
+
const m = RE.exec(value);
|
|
16
|
+
if (!m) return null;
|
|
17
|
+
const pre = m[4] ? m[4].split('.') : [];
|
|
18
|
+
if (pre.some((id) => /^0\d+$/.test(id))) return null;
|
|
19
|
+
return { major: Number(m[1]), minor: Number(m[2]), patch: Number(m[3]), pre };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** -1, 0 or 1; null when either side is not a version. */
|
|
23
|
+
function compare(a, b) {
|
|
24
|
+
const x = parse(a);
|
|
25
|
+
const y = parse(b);
|
|
26
|
+
if (!x || !y) return null;
|
|
27
|
+
for (const k of ['major', 'minor', 'patch']) if (x[k] !== y[k]) return x[k] < y[k] ? -1 : 1;
|
|
28
|
+
// A prerelease comes before its release.
|
|
29
|
+
if (!x.pre.length || !y.pre.length) return Math.sign(y.pre.length - x.pre.length);
|
|
30
|
+
for (let i = 0; i < Math.max(x.pre.length, y.pre.length); i++) {
|
|
31
|
+
const p = x.pre[i];
|
|
32
|
+
const q = y.pre[i];
|
|
33
|
+
if (p === undefined) return -1;
|
|
34
|
+
if (q === undefined) return 1;
|
|
35
|
+
if (p === q) continue;
|
|
36
|
+
const pn = /^\d+$/.test(p);
|
|
37
|
+
const qn = /^\d+$/.test(q);
|
|
38
|
+
if (pn && qn) return Number(p) < Number(q) ? -1 : 1;
|
|
39
|
+
if (pn !== qn) return pn ? -1 : 1;
|
|
40
|
+
return p < q ? -1 : 1;
|
|
41
|
+
}
|
|
42
|
+
return 0;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** True for a plain release version (no prerelease part). */
|
|
46
|
+
function isStable(value) {
|
|
47
|
+
const v = parse(value);
|
|
48
|
+
return Boolean(v) && v.pre.length === 0;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** True only when `candidate` is a stable release strictly newer than `installed`: never a downgrade, never a prerelease. */
|
|
52
|
+
function isUpgrade(candidate, installed) {
|
|
53
|
+
return isStable(candidate) && compare(candidate, installed) === 1;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
module.exports = { parse, compare, isStable, isUpgrade };
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* lib/update-source.js
|
|
5
|
+
* -----------------------------------------------------------------------------
|
|
6
|
+
* The ONLY place the updater gets anything from the network, and the checks that decide whether to believe it.
|
|
7
|
+
*
|
|
8
|
+
* - One source: the official npm registry, hard-coded. No environment variable, option, settings file, npm
|
|
9
|
+
* configuration or server reply can change it (tests replace it in-process with _setSourceForTests).
|
|
10
|
+
* - Redirects are refused; the tarball address must be exactly the registry's address for that name and version.
|
|
11
|
+
* - A package is accepted only if its bytes match the published sha512 integrity AND npm's registry signature over
|
|
12
|
+
* "<name>@<version>:<integrity>" verifies with a public key pinned below (https://registry.npmjs.org/-/npm/v1/keys).
|
|
13
|
+
* If npm rotates its key, automatic updates stop (fail closed, reported as KEY_UNKNOWN) until a manual upgrade
|
|
14
|
+
* brings the new key. Keys are never fetched or accepted from the network (docs/auto-update.md).
|
|
15
|
+
* - No credentials are sent: only a User-Agent and Accept header. Timeouts, size limits and retries are bounded.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
const crypto = require('crypto');
|
|
19
|
+
const semver = require('./update-semver');
|
|
20
|
+
|
|
21
|
+
const PACKAGE = 'korveniq';
|
|
22
|
+
|
|
23
|
+
const OFFICIAL = Object.freeze({
|
|
24
|
+
registry: 'https://registry.npmjs.org',
|
|
25
|
+
keys: Object.freeze({
|
|
26
|
+
'SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U':
|
|
27
|
+
'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEY6Ya7W++7aUPzvMTrezH6Ycx3c+HOKYCcNGybJZSCJq/fd7Qa8uuAKtdIkUQtQiEKERhAmE5lMMJhP8OkDOa2g==',
|
|
28
|
+
}),
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
const LIMITS = Object.freeze({
|
|
32
|
+
manifestBytes: 512 * 1024,
|
|
33
|
+
tarballBytes: 50 * 1024 * 1024,
|
|
34
|
+
manifestTimeoutMs: 5_000,
|
|
35
|
+
stallTimeoutMs: 30_000,
|
|
36
|
+
downloadTimeoutMs: 5 * 60_000,
|
|
37
|
+
retries: 2,
|
|
38
|
+
retryDelayMs: 500,
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
let source = OFFICIAL;
|
|
42
|
+
let limits = LIMITS;
|
|
43
|
+
|
|
44
|
+
/** For tests only (nothing on the command line or in the environment reaches this). */
|
|
45
|
+
function _setSourceForTests(next, nextLimits) {
|
|
46
|
+
source = next || OFFICIAL;
|
|
47
|
+
limits = nextLimits ? { ...LIMITS, ...nextLimits } : LIMITS;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
class UpdateError extends Error {
|
|
51
|
+
/** code: OFFLINE TIMEOUT RATE_LIMIT HTTP MALFORMED UNTRUSTED KEY_UNKNOWN INTEGRITY TOO_LARGE INTERRUPTED ABORTED PACKAGE INSTALL BUSY UNSUPPORTED */
|
|
52
|
+
constructor(code, message, extra = {}) {
|
|
53
|
+
super(message);
|
|
54
|
+
this.name = 'UpdateError';
|
|
55
|
+
this.code = code;
|
|
56
|
+
Object.assign(this, extra);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const tarballUrl = (version) => `${source.registry}/${PACKAGE}/-/${PACKAGE}-${version}.tgz`;
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Check a registry manifest and keep only what the updater uses. Throws unless it is our package, a well-formed
|
|
64
|
+
* version, the expected tarball address, a sha512 integrity and a signature from a pinned key that verifies.
|
|
65
|
+
*/
|
|
66
|
+
function checkManifest(json) {
|
|
67
|
+
const bad = (code, message) => new UpdateError(code, message);
|
|
68
|
+
if (!json || typeof json !== 'object' || Array.isArray(json)) throw bad('MALFORMED', 'The registry reply is not a package description');
|
|
69
|
+
if (json.name !== PACKAGE) throw bad('UNTRUSTED', 'The registry reply describes a different package');
|
|
70
|
+
const { version, dist } = json;
|
|
71
|
+
if (!semver.parse(version)) throw bad('MALFORMED', 'The registry reply has no valid version');
|
|
72
|
+
if (!dist || typeof dist !== 'object') throw bad('MALFORMED', 'The registry reply has no download information');
|
|
73
|
+
if (dist.tarball !== tarballUrl(version)) throw bad('UNTRUSTED', 'The download address is not the official one for this version');
|
|
74
|
+
const integrity = dist.integrity;
|
|
75
|
+
if (typeof integrity !== 'string' || !/^sha512-[A-Za-z0-9+/]{86}==$/.test(integrity)) throw bad('UNTRUSTED', 'The package has no sha512 integrity value');
|
|
76
|
+
const signatures = (Array.isArray(dist.signatures) ? dist.signatures : [])
|
|
77
|
+
.filter((s) => s && typeof s.keyid === 'string' && typeof s.sig === 'string')
|
|
78
|
+
.slice(0, 8)
|
|
79
|
+
.map((s) => ({ keyid: s.keyid, sig: s.sig }));
|
|
80
|
+
const manifest = { name: PACKAGE, version, tarball: dist.tarball, integrity, signatures, deprecated: Boolean(json.deprecated) };
|
|
81
|
+
verifySignature(manifest);
|
|
82
|
+
return manifest;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function verifySignature({ name, version, integrity, signatures }) {
|
|
86
|
+
const signed = Buffer.from(`${name}@${version}:${integrity}`);
|
|
87
|
+
const pinned = (keyid) => Object.prototype.hasOwnProperty.call(source.keys, keyid);
|
|
88
|
+
if ((signatures || []).length && !signatures.some(({ keyid }) => pinned(keyid))) {
|
|
89
|
+
throw new UpdateError('KEY_UNKNOWN', 'The npm registry signed this release with a key this version of Korveniq does not know');
|
|
90
|
+
}
|
|
91
|
+
const ok = (signatures || []).some(({ keyid, sig }) => {
|
|
92
|
+
if (!pinned(keyid)) return false;
|
|
93
|
+
try {
|
|
94
|
+
const key = crypto.createPublicKey({ key: Buffer.from(source.keys[keyid], 'base64'), format: 'der', type: 'spki' });
|
|
95
|
+
return crypto.verify('sha256', signed, key, Buffer.from(sig, 'base64'));
|
|
96
|
+
} catch {
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
if (!ok) throw new UpdateError('UNTRUSTED', 'The npm registry signature of this package could not be verified');
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Throw unless `bytes` are exactly the package the (verified) manifest describes. */
|
|
104
|
+
function verifyBytes(bytes, manifest) {
|
|
105
|
+
const actual = `sha512-${crypto.createHash('sha512').update(bytes).digest('base64')}`;
|
|
106
|
+
if (actual !== manifest.integrity) throw new UpdateError('INTEGRITY', 'The downloaded package does not match its published checksum');
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// ---------------------------------------------------------------------------
|
|
110
|
+
// HTTP
|
|
111
|
+
// ---------------------------------------------------------------------------
|
|
112
|
+
|
|
113
|
+
function retryAfterMs(res) {
|
|
114
|
+
const raw = res.headers.get('retry-after');
|
|
115
|
+
if (!raw) return null;
|
|
116
|
+
const ms = /^\d+$/.test(raw.trim()) ? Number(raw) * 1000 : Date.parse(raw) - Date.now();
|
|
117
|
+
return Number.isFinite(ms) && ms > 0 ? ms : null;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* One GET with an overall and a no-progress timeout. Resolves with the whole body (bounded by maxBytes).
|
|
122
|
+
* onProgress(received, total) is called with total = null when the size cannot be known.
|
|
123
|
+
*/
|
|
124
|
+
async function get(url, { accept, maxBytes, timeoutMs, stallMs, signal, userAgent, onProgress }) {
|
|
125
|
+
const controller = new AbortController();
|
|
126
|
+
let why = null;
|
|
127
|
+
const abort = (reason) => {
|
|
128
|
+
why = why || reason;
|
|
129
|
+
controller.abort();
|
|
130
|
+
};
|
|
131
|
+
const overall = setTimeout(() => abort('TIMEOUT'), timeoutMs);
|
|
132
|
+
let stall = null;
|
|
133
|
+
const touch = () => {
|
|
134
|
+
clearTimeout(stall);
|
|
135
|
+
if (stallMs) stall = setTimeout(() => abort('TIMEOUT'), stallMs);
|
|
136
|
+
};
|
|
137
|
+
const onAbort = () => abort('ABORTED');
|
|
138
|
+
if (signal) {
|
|
139
|
+
if (signal.aborted) onAbort();
|
|
140
|
+
else signal.addEventListener('abort', onAbort, { once: true });
|
|
141
|
+
}
|
|
142
|
+
let started = false;
|
|
143
|
+
try {
|
|
144
|
+
touch();
|
|
145
|
+
const res = await fetch(url, { redirect: 'error', signal: controller.signal, headers: { Accept: accept, 'User-Agent': userAgent } });
|
|
146
|
+
if (res.status === 429) throw new UpdateError('RATE_LIMIT', 'The npm registry is limiting requests', { retryAfterMs: retryAfterMs(res) });
|
|
147
|
+
if (res.status !== 200) throw new UpdateError('HTTP', `The npm registry answered HTTP ${res.status}`, { status: res.status });
|
|
148
|
+
// A compressed transfer has a content-length that is not the number of bytes we will count.
|
|
149
|
+
const encoded = res.headers.get('content-encoding');
|
|
150
|
+
const length = Number(res.headers.get('content-length'));
|
|
151
|
+
const total = !encoded && Number.isSafeInteger(length) && length > 0 ? length : null;
|
|
152
|
+
if (total !== null && total > maxBytes) throw new UpdateError('TOO_LARGE', 'The registry reply is larger than allowed');
|
|
153
|
+
started = true;
|
|
154
|
+
const chunks = [];
|
|
155
|
+
let received = 0;
|
|
156
|
+
if (onProgress) onProgress(0, total);
|
|
157
|
+
for await (const chunk of res.body) {
|
|
158
|
+
touch();
|
|
159
|
+
received += chunk.length;
|
|
160
|
+
if (received > maxBytes) throw new UpdateError('TOO_LARGE', 'The registry reply is larger than allowed');
|
|
161
|
+
chunks.push(chunk);
|
|
162
|
+
if (onProgress) onProgress(received, total);
|
|
163
|
+
}
|
|
164
|
+
if (total !== null && received !== total) throw new UpdateError('INTERRUPTED', 'The download was interrupted');
|
|
165
|
+
return Buffer.concat(chunks);
|
|
166
|
+
} catch (err) {
|
|
167
|
+
if (why === 'ABORTED') throw new UpdateError('ABORTED', 'The update was cancelled');
|
|
168
|
+
if (why === 'TIMEOUT') throw new UpdateError('TIMEOUT', 'The npm registry did not answer in time');
|
|
169
|
+
if (err instanceof UpdateError) throw err;
|
|
170
|
+
if (started) throw new UpdateError('INTERRUPTED', 'The download was interrupted');
|
|
171
|
+
// Includes a refused redirect, DNS failures and being offline.
|
|
172
|
+
throw new UpdateError('OFFLINE', 'The npm registry could not be reached');
|
|
173
|
+
} finally {
|
|
174
|
+
clearTimeout(overall);
|
|
175
|
+
clearTimeout(stall);
|
|
176
|
+
if (signal) signal.removeEventListener('abort', onAbort);
|
|
177
|
+
controller.abort(); // releases the connection after an early exit
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const transient = (err) => ['OFFLINE', 'TIMEOUT', 'INTERRUPTED'].includes(err.code) || (err.code === 'HTTP' && err.status >= 500);
|
|
182
|
+
|
|
183
|
+
async function withRetries(fn, { retries, signal }) {
|
|
184
|
+
for (let attempt = 0; ; attempt++) {
|
|
185
|
+
try {
|
|
186
|
+
return await fn();
|
|
187
|
+
} catch (err) {
|
|
188
|
+
if (attempt >= retries || !transient(err) || (signal && signal.aborted)) throw err;
|
|
189
|
+
await new Promise((resolve) => setTimeout(resolve, limits.retryDelayMs * 2 ** attempt));
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** The verified manifest of the version tagged "latest". */
|
|
195
|
+
async function fetchLatest({ signal, userAgent, retries = 0, timeoutMs } = {}) {
|
|
196
|
+
const body = await withRetries(
|
|
197
|
+
() => get(`${source.registry}/${PACKAGE}/latest`, { accept: 'application/json', maxBytes: limits.manifestBytes, timeoutMs: timeoutMs || limits.manifestTimeoutMs, signal, userAgent }),
|
|
198
|
+
{ retries, signal },
|
|
199
|
+
);
|
|
200
|
+
let json;
|
|
201
|
+
try {
|
|
202
|
+
json = JSON.parse(body.toString('utf8'));
|
|
203
|
+
} catch {
|
|
204
|
+
throw new UpdateError('MALFORMED', 'The registry reply is not valid JSON');
|
|
205
|
+
}
|
|
206
|
+
return checkManifest(json);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Download the package of a verified manifest and verify its bytes. */
|
|
210
|
+
async function download(manifest, { signal, userAgent, onProgress } = {}) {
|
|
211
|
+
verifySignature(manifest);
|
|
212
|
+
if (manifest.tarball !== tarballUrl(manifest.version)) throw new UpdateError('UNTRUSTED', 'The download address is not the official one for this version');
|
|
213
|
+
const bytes = await withRetries(
|
|
214
|
+
() => get(manifest.tarball, { accept: 'application/octet-stream', maxBytes: limits.tarballBytes, timeoutMs: limits.downloadTimeoutMs, stallMs: limits.stallTimeoutMs, signal, userAgent, onProgress }),
|
|
215
|
+
{ retries: limits.retries, signal },
|
|
216
|
+
);
|
|
217
|
+
verifyBytes(bytes, manifest);
|
|
218
|
+
return bytes;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
module.exports = { PACKAGE, OFFICIAL, LIMITS, UpdateError, checkManifest, verifySignature, verifyBytes, fetchLatest, download, tarballUrl, _setSourceForTests };
|