korveniq 1.0.3 → 1.0.4
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 +1 -1
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* lib/update-state.js
|
|
5
|
+
* -----------------------------------------------------------------------------
|
|
6
|
+
* Which installation is running, and the files that coordinate updates of it. Loaded by bin/index.js before anything
|
|
7
|
+
* else, so it uses only Node's own modules.
|
|
8
|
+
*
|
|
9
|
+
* Supported for automatic installation: a global npm layout on macOS or Linux that the current user owns:
|
|
10
|
+
* <prefix>/lib/node_modules/korveniq with <prefix>/bin/korveniq -> it
|
|
11
|
+
* The prefix comes from where the RUNNING files are, never from `npm prefix` (a machine can have several installs).
|
|
12
|
+
*
|
|
13
|
+
* Everything an update needs lives in <prefix>/lib/node_modules/.korveniq-update (private to the user, same file
|
|
14
|
+
* system as the package, so a rename is atomic):
|
|
15
|
+
* sessions/<pid> one per running CLI process; files are only swapped when no other process is running
|
|
16
|
+
* stage.lock.<n> one download at a time
|
|
17
|
+
* apply.lock.<n> one installation at a time; a CLI that starts while it is held waits
|
|
18
|
+
* staged.json + staged-<version>.tgz a downloaded, verified package waiting for an exit
|
|
19
|
+
* failed.json the last version that could not be installed
|
|
20
|
+
* swap.json, work-*, recovery/ an installation in progress (lib/update-recover.js)
|
|
21
|
+
*
|
|
22
|
+
* This file is also copied next to the recovery launcher, so it may use only Node's own modules.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
const fs = require('fs');
|
|
26
|
+
const os = require('os');
|
|
27
|
+
const path = require('path');
|
|
28
|
+
const crypto = require('crypto');
|
|
29
|
+
const { spawnSync } = require('child_process');
|
|
30
|
+
|
|
31
|
+
const NAME = 'korveniq';
|
|
32
|
+
const STATE_DIR = `.${NAME}-update`;
|
|
33
|
+
const LOCK_MAX_AGE_MS = 10 * 60_000; // only when it cannot be told whether a process id was reused
|
|
34
|
+
const REUSE_TOLERANCE_MS = 60_000;
|
|
35
|
+
const NPM_RETIRED_RE = /^\.korveniq-[A-Za-z0-9]{8}$/; // what npm renames the old folder to while it installs
|
|
36
|
+
|
|
37
|
+
const shellQuote = (s) => (/^[A-Za-z0-9_./-]+$/.test(s) ? s : `'${s.replace(/'/g, "'\\''")}'`);
|
|
38
|
+
|
|
39
|
+
const manualCommand = (prefix) => `npm install -g ${NAME}@latest${prefix ? ` --prefix ${shellQuote(prefix)}` : ''}`;
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* @returns {{ supported: boolean, reason: string|null, message: string, kind: string, root: string,
|
|
43
|
+
* modulesDir?: string, prefix?: string, stateDir?: string, command: string }}
|
|
44
|
+
*/
|
|
45
|
+
function detect({ root = path.join(__dirname, '..'), platform = process.platform, env = process.env, uid = process.getuid ? process.getuid() : null } = {}) {
|
|
46
|
+
let real = root;
|
|
47
|
+
try {
|
|
48
|
+
real = fs.realpathSync(root);
|
|
49
|
+
} catch {
|
|
50
|
+
/* judged by its name below */
|
|
51
|
+
}
|
|
52
|
+
const parts = real.split(path.sep);
|
|
53
|
+
const no = (kind, reason, message, command = manualCommand()) => ({ supported: false, kind, reason, message, root: real, command });
|
|
54
|
+
|
|
55
|
+
if (parts.includes('_npx')) return no('npx', 'npx', 'Running through npx, which fetches packages itself.', `npx ${NAME}@latest`);
|
|
56
|
+
if (parts.includes('.pnpm') || parts.includes('pnpm')) return no('pnpm', 'pnpm', 'Installed with pnpm.', `pnpm add -g ${NAME}@latest`);
|
|
57
|
+
if (parts.includes('.volta')) return no('volta', 'volta', 'Installed with Volta.', `volta install ${NAME}@latest`);
|
|
58
|
+
if (parts.includes('yarn') || parts.includes('.yarn')) return no('yarn', 'yarn', 'Installed with Yarn.', `yarn global add ${NAME}@latest`);
|
|
59
|
+
if (parts.includes('.bun')) return no('bun', 'bun', 'Installed with Bun.', `bun add -g ${NAME}@latest`);
|
|
60
|
+
|
|
61
|
+
const modulesDir = path.dirname(real);
|
|
62
|
+
if (path.basename(real) !== NAME || path.basename(modulesDir) !== 'node_modules') {
|
|
63
|
+
return no('source', 'source', 'Running from a source folder, not an installed package.');
|
|
64
|
+
}
|
|
65
|
+
if (platform === 'win32') return no('npm-global', 'windows', 'Automatic installation is not yet supported on Windows.');
|
|
66
|
+
if (platform !== 'darwin' && platform !== 'linux') return no('npm-global', 'platform', 'Automatic installation is not supported on this system.');
|
|
67
|
+
|
|
68
|
+
const lib = path.dirname(modulesDir);
|
|
69
|
+
const prefix = path.dirname(lib);
|
|
70
|
+
const binDir = path.join(prefix, 'bin');
|
|
71
|
+
let linked = false;
|
|
72
|
+
try {
|
|
73
|
+
const target = fs.realpathSync(path.join(binDir, NAME));
|
|
74
|
+
// (the second: an interrupted update, which is about to be repaired)
|
|
75
|
+
linked = path.basename(lib) === 'lib' && (target === path.join(real, 'bin', 'index.js') || target === path.join(modulesDir, STATE_DIR, 'recovery', 'update-recover.js'));
|
|
76
|
+
} catch {
|
|
77
|
+
/* no command link */
|
|
78
|
+
}
|
|
79
|
+
if (!linked) return no('local', 'local', 'This is not a global npm installation.', `npm install ${NAME}@latest`);
|
|
80
|
+
|
|
81
|
+
const command = manualCommand(prefix);
|
|
82
|
+
// Never as root on a user's behalf (sudo korveniq).
|
|
83
|
+
if (uid === 0 && env.SUDO_USER) return no('npm-global', 'elevated', 'Running with sudo; Korveniq does not update itself with elevated rights.', command);
|
|
84
|
+
try {
|
|
85
|
+
for (const dir of [modulesDir, real, binDir]) {
|
|
86
|
+
fs.accessSync(dir, fs.constants.W_OK);
|
|
87
|
+
if (uid !== null && fs.statSync(dir).uid !== uid) throw new Error('owner');
|
|
88
|
+
}
|
|
89
|
+
} catch {
|
|
90
|
+
return no('npm-global', 'not-writable', `Your user cannot change the installation in ${prefix}. Update it the way it was installed, or reinstall Korveniq into a folder you own.`, command);
|
|
91
|
+
}
|
|
92
|
+
return { supported: true, kind: 'npm-global', reason: null, message: '', root: real, modulesDir, prefix, stateDir: path.join(modulesDir, STATE_DIR), command };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Create (if needed) and check the private state folder. Throws rather than use a link or another user's folder. */
|
|
96
|
+
function ensureStateDir(install) {
|
|
97
|
+
const dir = install.stateDir;
|
|
98
|
+
for (const d of [dir, path.join(dir, 'sessions')]) {
|
|
99
|
+
try {
|
|
100
|
+
fs.mkdirSync(d, { mode: 0o700 });
|
|
101
|
+
} catch (err) {
|
|
102
|
+
if (err.code !== 'EEXIST') throw err;
|
|
103
|
+
}
|
|
104
|
+
const st = fs.lstatSync(d);
|
|
105
|
+
if (!st.isDirectory() || (process.getuid && st.uid !== process.getuid())) throw new Error(`unsafe update folder: ${d}`);
|
|
106
|
+
if (st.mode & 0o077) fs.chmodSync(d, 0o700);
|
|
107
|
+
}
|
|
108
|
+
return dir;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function alive(pid) {
|
|
112
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
113
|
+
try {
|
|
114
|
+
process.kill(pid, 0);
|
|
115
|
+
return true;
|
|
116
|
+
} catch (err) {
|
|
117
|
+
return err.code === 'EPERM';
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Written before the last restart of the machine: whatever has that process id now, it is not the writer. */
|
|
122
|
+
const beforeBoot = (at) => at < Date.now() - os.uptime() * 1000 - REUSE_TOLERANCE_MS;
|
|
123
|
+
|
|
124
|
+
/** When process `pid` started (milliseconds since 1970), or null when that cannot be told. */
|
|
125
|
+
function startedAt(pid, platform = process.platform) {
|
|
126
|
+
try {
|
|
127
|
+
if (platform === 'linux') {
|
|
128
|
+
const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8');
|
|
129
|
+
const ticks = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[19]); // field 22, in 1/100 s
|
|
130
|
+
const boot = Number(/^btime (\d+)$/m.exec(fs.readFileSync('/proc/stat', 'utf8'))[1]);
|
|
131
|
+
return Number.isFinite(ticks) ? (boot + ticks / 100) * 1000 : null;
|
|
132
|
+
}
|
|
133
|
+
const r = spawnSync('/bin/ps', ['-o', 'etime=', '-p', String(pid)], { encoding: 'utf8', timeout: 2000 });
|
|
134
|
+
const m = /^\s*(?:(?:(\d+)-)?(\d+):)?(\d+):(\d+)\s*$/.exec(r.stdout || ''); // [[days-]hours:]minutes:seconds
|
|
135
|
+
if (!m) return null;
|
|
136
|
+
const [days, hours, minutes, seconds] = m.slice(1).map((v) => Number(v || 0));
|
|
137
|
+
return Date.now() - (((days * 24 + hours) * 60 + minutes) * 60 + seconds) * 1000;
|
|
138
|
+
} catch {
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Is the process that wrote a record at `at` still running? A live process is never judged gone by age alone; a
|
|
145
|
+
* process id that now belongs to a younger process (reused) is. Age decides only where start times are unreadable.
|
|
146
|
+
*/
|
|
147
|
+
function writerRunning(pid, at, { maxAgeMs = Infinity, started = startedAt } = {}) {
|
|
148
|
+
if (!alive(pid) || beforeBoot(at)) return false;
|
|
149
|
+
if (pid === process.pid) return true;
|
|
150
|
+
const start = started(pid);
|
|
151
|
+
if (start === null) return Date.now() - at <= maxAgeMs;
|
|
152
|
+
return start <= at + REUSE_TOLERANCE_MS;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function readJson(file) {
|
|
156
|
+
try {
|
|
157
|
+
const st = fs.lstatSync(file);
|
|
158
|
+
if (!st.isFile() || st.size > 1024 * 1024) return null;
|
|
159
|
+
const json = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
160
|
+
return json && typeof json === 'object' ? json : null;
|
|
161
|
+
} catch {
|
|
162
|
+
return null;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Atomic replace through a new file with a random name (never writes through an existing file or link). */
|
|
167
|
+
function writeJson(file, value, { sync = false } = {}) {
|
|
168
|
+
const tmp = `${file}.${crypto.randomBytes(6).toString('hex')}.tmp`;
|
|
169
|
+
try {
|
|
170
|
+
const fd = fs.openSync(tmp, 'wx', 0o600);
|
|
171
|
+
try {
|
|
172
|
+
fs.writeFileSync(fd, `${JSON.stringify(value)}\n`);
|
|
173
|
+
if (sync) fs.fsyncSync(fd);
|
|
174
|
+
} finally {
|
|
175
|
+
fs.closeSync(fd);
|
|
176
|
+
}
|
|
177
|
+
fs.renameSync(tmp, file);
|
|
178
|
+
} finally {
|
|
179
|
+
fs.rmSync(tmp, { force: true });
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// ---------------------------------------------------------------------------
|
|
184
|
+
// Locks
|
|
185
|
+
//
|
|
186
|
+
// A lock is a series of files <name>.<n>; the highest n is the lock. Taking it means creating the next number, which
|
|
187
|
+
// exactly one process can do. An abandoned lock is never removed or renamed by a contender (two of them could then
|
|
188
|
+
// both "win"): it is simply superseded by a higher number. Releasing marks the file; numbers never go backwards.
|
|
189
|
+
// ---------------------------------------------------------------------------
|
|
190
|
+
|
|
191
|
+
function generations(base) {
|
|
192
|
+
const prefix = `${path.basename(base)}.`;
|
|
193
|
+
let names;
|
|
194
|
+
try {
|
|
195
|
+
names = fs.readdirSync(path.dirname(base));
|
|
196
|
+
} catch {
|
|
197
|
+
return [];
|
|
198
|
+
}
|
|
199
|
+
return names
|
|
200
|
+
.filter((n) => n.startsWith(prefix) && /^\d+$/.test(n.slice(prefix.length)))
|
|
201
|
+
.map((n) => Number(n.slice(prefix.length)))
|
|
202
|
+
.sort((a, b) => a - b);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function liveRecord(file) {
|
|
206
|
+
const lock = readJson(file);
|
|
207
|
+
if (!lock) {
|
|
208
|
+
// Records appear complete (they are linked into place), so this one is damaged: believe it for a few seconds.
|
|
209
|
+
try {
|
|
210
|
+
return Date.now() - fs.lstatSync(file).mtimeMs < 5000 ? { pid: 0 } : null;
|
|
211
|
+
} catch {
|
|
212
|
+
return null;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
if (lock.released || !writerRunning(lock.pid, lock.at, { maxAgeMs: LOCK_MAX_AGE_MS })) return null;
|
|
216
|
+
return lock;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** The live holder of a lock, or null (free, released, or left behind by a process that is gone). */
|
|
220
|
+
function holder(base) {
|
|
221
|
+
const top = generations(base).pop();
|
|
222
|
+
return top === undefined ? null : liveRecord(`${base}.${top}`);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Take an exclusive lock. Returns { owned(), release() }, or null when someone else holds it.
|
|
227
|
+
* @param {string} base
|
|
228
|
+
*/
|
|
229
|
+
function acquire(base) {
|
|
230
|
+
const token = crypto.randomBytes(12).toString('hex');
|
|
231
|
+
for (let attempt = 0; attempt < 20; attempt++) {
|
|
232
|
+
const top = generations(base).pop() || 0;
|
|
233
|
+
if (top && liveRecord(`${base}.${top}`)) return null;
|
|
234
|
+
const mine = top + 1;
|
|
235
|
+
const file = `${base}.${mine}`;
|
|
236
|
+
const tmp = `${base}.${token}.tmp`;
|
|
237
|
+
try {
|
|
238
|
+
fs.writeFileSync(tmp, JSON.stringify({ pid: process.pid, token, at: Date.now() }), { flag: 'wx', mode: 0o600 });
|
|
239
|
+
fs.linkSync(tmp, file); // atomic, complete, and fails if the number is taken
|
|
240
|
+
} catch (err) {
|
|
241
|
+
if (err.code === 'EEXIST') continue;
|
|
242
|
+
throw err;
|
|
243
|
+
} finally {
|
|
244
|
+
fs.rmSync(tmp, { force: true });
|
|
245
|
+
}
|
|
246
|
+
// Created a number that others had already passed (and cleaned up): step back.
|
|
247
|
+
if (generations(base).pop() !== mine) {
|
|
248
|
+
fs.rmSync(file, { force: true });
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
for (const old of generations(base)) if (old < mine) fs.rmSync(`${base}.${old}`, { force: true });
|
|
252
|
+
const owned = () => generations(base).pop() === mine && (readJson(file) || {}).token === token;
|
|
253
|
+
return {
|
|
254
|
+
owned,
|
|
255
|
+
release() {
|
|
256
|
+
if (owned()) writeJson(file, { released: true });
|
|
257
|
+
},
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
return null;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Is npm in the middle of installing or removing this package? (Its renamed old folder is there, and recent.) */
|
|
264
|
+
function npmBusy(modulesDir, now = Date.now()) {
|
|
265
|
+
try {
|
|
266
|
+
return fs.readdirSync(modulesDir).some((name) => {
|
|
267
|
+
if (!NPM_RETIRED_RE.test(name)) return false;
|
|
268
|
+
const st = fs.lstatSync(path.join(modulesDir, name));
|
|
269
|
+
return now - Math.max(st.mtimeMs, st.ctimeMs) < LOCK_MAX_AGE_MS;
|
|
270
|
+
});
|
|
271
|
+
} catch {
|
|
272
|
+
return false;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** Process ids of the other CLI processes running from this installation. Leftovers of dead ones are removed. */
|
|
277
|
+
function otherSessions(install, self = process.pid) {
|
|
278
|
+
const dir = path.join(install.stateDir, 'sessions');
|
|
279
|
+
const out = [];
|
|
280
|
+
for (const name of fs.readdirSync(dir)) {
|
|
281
|
+
const pid = Number(name);
|
|
282
|
+
if (!/^\d+$/.test(name) || pid === self) continue;
|
|
283
|
+
let at = 0;
|
|
284
|
+
try {
|
|
285
|
+
at = fs.lstatSync(path.join(dir, name)).mtimeMs;
|
|
286
|
+
} catch {
|
|
287
|
+
continue;
|
|
288
|
+
}
|
|
289
|
+
if (writerRunning(pid, at)) out.push(pid);
|
|
290
|
+
else fs.rmSync(path.join(dir, name), { force: true });
|
|
291
|
+
}
|
|
292
|
+
return out;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** Record this process as running from the installation until it exits. */
|
|
296
|
+
function registerSession(install, pid = process.pid) {
|
|
297
|
+
ensureStateDir(install);
|
|
298
|
+
const file = path.join(install.stateDir, 'sessions', String(pid));
|
|
299
|
+
fs.rmSync(file, { force: true });
|
|
300
|
+
fs.writeFileSync(file, '', { flag: 'wx', mode: 0o600 });
|
|
301
|
+
return () => fs.rmSync(file, { force: true });
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** This process is about to leave and needs no more files of the installation. */
|
|
305
|
+
function endSession(install, pid = process.pid) {
|
|
306
|
+
fs.rmSync(path.join(install.stateDir, 'sessions', String(pid)), { force: true });
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Called first thing by bin/index.js: register, then (order matters) look for an installation in progress. The
|
|
311
|
+
* installer does the reverse (lock, then look for sessions), so at least one of the two always sees the other.
|
|
312
|
+
* An installation that was interrupted is repaired here too.
|
|
313
|
+
* Returns true when the installed files changed while this process was starting, so it must be started again.
|
|
314
|
+
* Never throws: coordination problems must not stop the CLI from starting.
|
|
315
|
+
*/
|
|
316
|
+
function startSession({ install = detect(), waitMs = 15_000 } = {}) {
|
|
317
|
+
if (!install.supported) return false;
|
|
318
|
+
try {
|
|
319
|
+
const remove = registerSession(install);
|
|
320
|
+
process.once('exit', () => {
|
|
321
|
+
try {
|
|
322
|
+
remove();
|
|
323
|
+
} catch {
|
|
324
|
+
/* leaving anyway */
|
|
325
|
+
}
|
|
326
|
+
});
|
|
327
|
+
const lock = path.join(install.stateDir, 'apply.lock');
|
|
328
|
+
let stale = false;
|
|
329
|
+
for (const end = Date.now() + waitMs; Date.now() < end && holder(lock); stale = true) {
|
|
330
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50);
|
|
331
|
+
}
|
|
332
|
+
if (fs.existsSync(path.join(install.stateDir, 'swap.json')) && require('./update-recover').recover(install.stateDir).changed) stale = true;
|
|
333
|
+
// The process started in our place records itself; this one, only waiting for it, must not count as a session.
|
|
334
|
+
if (stale) remove();
|
|
335
|
+
return stale;
|
|
336
|
+
} catch {
|
|
337
|
+
return false;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
module.exports = { NAME, detect, manualCommand, ensureStateDir, alive, startedAt, writerRunning, readJson, writeJson, holder, acquire, npmBusy, otherSessions, registerSession, endSession, startSession, shellQuote };
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* lib/update-tar.js
|
|
5
|
+
* -----------------------------------------------------------------------------
|
|
6
|
+
* A deliberately strict reader for npm package tarballs (gzip + ustar/pax). It accepts only regular files and
|
|
7
|
+
* folders under "package/". Links, devices, absolute or ".." paths, backslashes, duplicate names (also names that
|
|
8
|
+
* differ only in case), unknown entry types, bad checksums and oversized content are all refused. The whole archive
|
|
9
|
+
* is checked before the first byte is written, and files are created with O_EXCL into a new, empty folder.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
const fs = require('fs');
|
|
13
|
+
const path = require('path');
|
|
14
|
+
const zlib = require('zlib');
|
|
15
|
+
const { spawnSync } = require('child_process');
|
|
16
|
+
const recovery = require('./update-recover');
|
|
17
|
+
const { UpdateError } = require('./update-source');
|
|
18
|
+
|
|
19
|
+
const BLOCK = 512;
|
|
20
|
+
const MAX_UNPACKED = 100 * 1024 * 1024;
|
|
21
|
+
const MAX_FILE = 20 * 1024 * 1024;
|
|
22
|
+
const MAX_ENTRIES = 5000;
|
|
23
|
+
|
|
24
|
+
const bad = (why) => new UpdateError('PACKAGE', `The package archive is not acceptable: ${why}`);
|
|
25
|
+
|
|
26
|
+
function text(header, start, length) {
|
|
27
|
+
const field = header.subarray(start, start + length);
|
|
28
|
+
const end = field.indexOf(0);
|
|
29
|
+
return field.subarray(0, end === -1 ? length : end).toString('utf8');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function octal(header, start, length) {
|
|
33
|
+
const s = text(header, start, length).trim();
|
|
34
|
+
if (!/^[0-7]+$/.test(s)) throw bad('a damaged header');
|
|
35
|
+
return parseInt(s, 8);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The records of a pax extended header: "<length> <key>=<value>\n". */
|
|
39
|
+
function paxRecords(data) {
|
|
40
|
+
const out = {};
|
|
41
|
+
let at = 0;
|
|
42
|
+
while (at < data.length) {
|
|
43
|
+
const space = data.indexOf(0x20, at);
|
|
44
|
+
const size = space === -1 ? NaN : Number(data.subarray(at, space).toString('ascii'));
|
|
45
|
+
if (!Number.isSafeInteger(size) || size <= space - at + 1 || at + size > data.length) throw bad('a damaged extended header');
|
|
46
|
+
const record = data.subarray(space + 1, at + size - 1).toString('utf8');
|
|
47
|
+
const eq = record.indexOf('=');
|
|
48
|
+
if (eq > 0) out[record.slice(0, eq)] = record.slice(eq + 1);
|
|
49
|
+
at += size;
|
|
50
|
+
}
|
|
51
|
+
return out;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The path inside the package ("lib/x.js"; "" for the top folder), or an error. */
|
|
55
|
+
function safePath(name) {
|
|
56
|
+
const parts = name.replace(/\/+$/, '').split('/');
|
|
57
|
+
if (name.startsWith('/') || /[\\\0:]/.test(name)) throw bad('an unsafe file name');
|
|
58
|
+
if (parts[0] !== 'package') throw bad('a file outside the package folder');
|
|
59
|
+
if (parts.some((p) => p === '' || p === '.' || p === '..')) throw bad('an unsafe file name');
|
|
60
|
+
return parts.slice(1).join('/');
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Parse the whole archive: [{ path, dir, mode, data }]. */
|
|
64
|
+
function read(gzipped) {
|
|
65
|
+
let tar;
|
|
66
|
+
try {
|
|
67
|
+
tar = zlib.gunzipSync(gzipped, { maxOutputLength: MAX_UNPACKED });
|
|
68
|
+
} catch {
|
|
69
|
+
throw bad('it cannot be decompressed');
|
|
70
|
+
}
|
|
71
|
+
const entries = [];
|
|
72
|
+
const seen = new Map();
|
|
73
|
+
let pax = null;
|
|
74
|
+
let ended = false;
|
|
75
|
+
for (let at = 0; at + BLOCK <= tar.length; ) {
|
|
76
|
+
const header = tar.subarray(at, at + BLOCK);
|
|
77
|
+
at += BLOCK;
|
|
78
|
+
if (header.every((b) => b === 0)) {
|
|
79
|
+
ended = true;
|
|
80
|
+
break;
|
|
81
|
+
}
|
|
82
|
+
let sum = 0;
|
|
83
|
+
for (let i = 0; i < BLOCK; i++) sum += i >= 148 && i < 156 ? 32 : header[i];
|
|
84
|
+
if (sum !== octal(header, 148, 8)) throw bad('a header checksum is wrong');
|
|
85
|
+
const type = String.fromCharCode(header[156] || 48);
|
|
86
|
+
const size = pax && pax.size !== undefined ? Number(pax.size) : octal(header, 124, 12);
|
|
87
|
+
if (!Number.isSafeInteger(size) || size < 0 || size > MAX_FILE || at + size > tar.length) throw bad('a file is too large or cut off');
|
|
88
|
+
const data = tar.subarray(at, at + size);
|
|
89
|
+
at += Math.ceil(size / BLOCK) * BLOCK;
|
|
90
|
+
if (type === 'x') {
|
|
91
|
+
pax = paxRecords(data);
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
if (type !== '0' && type !== '5') throw bad('it contains a link or another special entry');
|
|
95
|
+
const prefix = text(header, 345, 155);
|
|
96
|
+
const name = (pax && pax.path) || (prefix ? `${prefix}/${text(header, 0, 100)}` : text(header, 0, 100));
|
|
97
|
+
pax = null;
|
|
98
|
+
const rel = safePath(name);
|
|
99
|
+
const dir = type === '5';
|
|
100
|
+
if (rel === '') {
|
|
101
|
+
if (!dir) throw bad('an unsafe file name');
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
const key = rel.normalize('NFC').toLowerCase();
|
|
105
|
+
if (seen.has(key) && !(dir && seen.get(key))) throw bad('the same file appears twice');
|
|
106
|
+
seen.set(key, dir);
|
|
107
|
+
entries.push({ path: rel, dir, mode: octal(header, 100, 8), data: dir ? null : data });
|
|
108
|
+
if (entries.length > MAX_ENTRIES) throw bad('it has too many files');
|
|
109
|
+
}
|
|
110
|
+
if (!ended || pax) throw bad('it is cut off');
|
|
111
|
+
return entries;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Ask the system to write everything to disk before an installation relies on it. One flush for the whole folder:
|
|
116
|
+
* Node's fsync() flushes the entire drive on macOS, which for hundreds of files takes many seconds. sync(2) waits
|
|
117
|
+
* for completion on Linux; on macOS it schedules the writes and the final fsync() flushes the drive (best effort).
|
|
118
|
+
*/
|
|
119
|
+
function flush(dest) {
|
|
120
|
+
spawnSync('/bin/sync', [], { stdio: 'ignore', timeout: 30_000 });
|
|
121
|
+
recovery.syncPath(dest);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Unpack into `dest`, which must not exist yet. With `sync`, the files are flushed to disk before returning. */
|
|
125
|
+
function extract(gzipped, dest, { sync = false } = {}) {
|
|
126
|
+
const entries = read(gzipped);
|
|
127
|
+
fs.mkdirSync(dest, { mode: 0o755 });
|
|
128
|
+
for (const e of entries) {
|
|
129
|
+
const target = path.join(dest, ...e.path.split('/'));
|
|
130
|
+
if (e.dir) fs.mkdirSync(target, { recursive: true });
|
|
131
|
+
else {
|
|
132
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
133
|
+
fs.writeFileSync(target, e.data, { flag: 'wx', mode: e.mode & 0o111 ? 0o755 : 0o644 });
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
if (sync) flush(dest);
|
|
137
|
+
return entries.length;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
module.exports = { read, extract };
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/** lib/update-view.js: the words and the progress bar of the updater, in the CLI's own style (lib/ui.js). */
|
|
4
|
+
|
|
5
|
+
const ui = require('./ui');
|
|
6
|
+
|
|
7
|
+
const BAR_WIDTH = 20;
|
|
8
|
+
const glyph = () => (ui.unicode ? { up: '↑', full: '█', empty: '░' } : { up: '^', full: '#', empty: '-' });
|
|
9
|
+
|
|
10
|
+
/** Whole percent of a measured download, or null when it cannot be measured. */
|
|
11
|
+
function percent(progress) {
|
|
12
|
+
if (!progress || !progress.total) return null;
|
|
13
|
+
return Math.min(100, Math.floor((progress.received / progress.total) * 100));
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function bar(pct, width = BAR_WIDTH) {
|
|
17
|
+
const g = glyph();
|
|
18
|
+
const full = Math.floor((pct / 100) * width);
|
|
19
|
+
return g.full.repeat(full) + g.empty.repeat(width - full);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const headline = (current, version) => `${ui.theme.info(glyph().up)} ${ui.theme.bold('Update available:')} v${current} ${ui.symbols.arrow} v${version}`;
|
|
23
|
+
const detail = (text) => ui.theme.dim(` ${ui.glyphs(text)}`);
|
|
24
|
+
|
|
25
|
+
/** Lines for a notice between turns. */
|
|
26
|
+
function notice(kind, { current, version, progress, followUp, install, auto }) {
|
|
27
|
+
if (kind === 'failed') return failed(null, install);
|
|
28
|
+
if (kind === 'unverifiable') {
|
|
29
|
+
return [
|
|
30
|
+
`${ui.theme.warn(ui.symbols.warning)} Korveniq cannot verify new releases automatically.`,
|
|
31
|
+
detail('npm is signing packages with a key this version does not know. Nothing was installed.'),
|
|
32
|
+
detail('To upgrade by hand:'),
|
|
33
|
+
` ${install.command}`,
|
|
34
|
+
];
|
|
35
|
+
}
|
|
36
|
+
if (kind === 'rejected') {
|
|
37
|
+
return [`${ui.theme.warn(ui.symbols.warning)} The latest release failed verification and was not installed.`, detail('Your current version remains available.')];
|
|
38
|
+
}
|
|
39
|
+
if (kind === 'staged') {
|
|
40
|
+
if (followUp) return [`${ui.theme.info(glyph().up)} Update v${version} downloaded.`, detail('It will be installed when you exit Korveniq.')];
|
|
41
|
+
return [headline(current, version), detail('Downloaded. It will be installed when you exit Korveniq.')];
|
|
42
|
+
}
|
|
43
|
+
if (kind === 'downloading') {
|
|
44
|
+
const pct = percent(progress);
|
|
45
|
+
const lines = [headline(current, version)];
|
|
46
|
+
if (pct === null) lines.push(detail('Downloading update…'));
|
|
47
|
+
else lines.push(detail(`Downloading update… ${pct}%`), ` ${ui.theme.info(bar(pct))}`);
|
|
48
|
+
lines.push(detail('It will be installed when you exit Korveniq.'));
|
|
49
|
+
return lines;
|
|
50
|
+
}
|
|
51
|
+
if (!install.supported) return [headline(current, version), detail(install.message), detail('Update with:'), ` ${install.command}`];
|
|
52
|
+
return [headline(current, version), detail(auto ? 'Automatic installation of this version failed earlier. Try:' : 'Automatic updates are off. Install it with:'), ' korveniq update'];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const installed = (version) => [`${ui.theme.success(ui.symbols.success)} Successfully updated to v${version}`, detail('The new version will be active on your next launch.')];
|
|
56
|
+
|
|
57
|
+
const WAITING = {
|
|
58
|
+
npm: 'npm is changing the installation right now.',
|
|
59
|
+
changed: 'The installation was changed by another program.',
|
|
60
|
+
};
|
|
61
|
+
const waiting = (version, reason) => [
|
|
62
|
+
`${ui.theme.info(glyph().up)} Update v${version} is downloaded.`,
|
|
63
|
+
detail(`${WAITING[reason] || 'Another Korveniq process is running.'} It will be installed at a later exit, when no other is open.`),
|
|
64
|
+
];
|
|
65
|
+
|
|
66
|
+
function failed(err, install) {
|
|
67
|
+
const lines = [
|
|
68
|
+
`${ui.theme.warn(ui.symbols.warning)} Automatic update could not be completed.`,
|
|
69
|
+
detail(err && err.broken ? err.message : 'Your current version remains available.'),
|
|
70
|
+
];
|
|
71
|
+
if (err && !err.broken) lines.push(detail(`${err.message}.`.replace(/\.\.$/, '.')));
|
|
72
|
+
if (install && install.command) lines.push(detail('To update by hand:'), ` ${install.command}`);
|
|
73
|
+
return lines;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function print(lines, stream = process.stdout) {
|
|
77
|
+
stream.write(`${lines.join('\n')}\n\n`);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Live progress for `korveniq update`. On a terminal one line is redrawn: a bar and the measured percentage, or a
|
|
82
|
+
* spinner with the amount received when the size is unknown. Elsewhere a single plain line is printed.
|
|
83
|
+
*/
|
|
84
|
+
function downloadReporter(stream = process.stdout) {
|
|
85
|
+
const live = Boolean(stream.isTTY) && !ui.isDebug() && process.env.CI === undefined;
|
|
86
|
+
let spinner = null;
|
|
87
|
+
let last = '';
|
|
88
|
+
let announced = false;
|
|
89
|
+
const clear = () => {
|
|
90
|
+
if (last) stream.write('\r\x1b[2K');
|
|
91
|
+
last = '';
|
|
92
|
+
if (spinner) spinner.stop();
|
|
93
|
+
spinner = null;
|
|
94
|
+
};
|
|
95
|
+
return {
|
|
96
|
+
update(received, total) {
|
|
97
|
+
if (!live) {
|
|
98
|
+
if (!announced) stream.write(ui.glyphs('Downloading update…\n'));
|
|
99
|
+
announced = true;
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
const pct = percent({ received, total });
|
|
103
|
+
if (pct === null) {
|
|
104
|
+
const text = `Downloading update… ${(received / 1024).toFixed(0)} KB`;
|
|
105
|
+
if (!spinner) spinner = ui.spinner(text, { stream }).start();
|
|
106
|
+
else spinner.text = text;
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
const room = ui.columns(stream) - 1;
|
|
110
|
+
let label = ui.glyphs(` Downloading update… ${pct}%`);
|
|
111
|
+
if (label.length > room) label = ` ${pct}%`; // a very narrow terminal keeps the number
|
|
112
|
+
const width = Math.min(BAR_WIDTH, room - label.length - 2);
|
|
113
|
+
const line = width >= 5 ? `${label} ${bar(pct, width)}` : label.slice(0, Math.max(1, room));
|
|
114
|
+
if (line === last) return;
|
|
115
|
+
last = line;
|
|
116
|
+
stream.write(`\r\x1b[2K${line}`);
|
|
117
|
+
},
|
|
118
|
+
done() {
|
|
119
|
+
clear();
|
|
120
|
+
},
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
module.exports = { percent, bar, notice, installed, waiting, failed, print, downloadReporter };
|