@durableintel/nenya 0.0.0-stage → 1.2.1

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.
@@ -0,0 +1,579 @@
1
+ // Fetch, verify and install one release for this account, on macOS and Windows. Nothing here
2
+ // asks for an administrator: macOS gets ~/Applications/Nenya.app, Windows the per-user Squirrel
3
+ // install under %LOCALAPPDATA%. Every action goes through the injected `system` (run, launch) and
4
+ // `fetch`, so the tests stand in for the bucket, `ditto`, `open` and `Setup.exe`.
5
+ //
6
+ // The release list is read from the v2 feed root first and from the legacy root only when the v2
7
+ // list answers 404 or 403 (readFeed; spec 15, signing rotation), and every download must verify
8
+ // with one of the listed release keys.
9
+ //
10
+ // Every read from the bucket is bounded: a manifest or bundle by `limits.manifest`, an artifact
11
+ // by the size its feed declares (macOS, RELEASES.json `updateTo.size`), by Content-Length when
12
+ // the server sends one, and always by `limits.download`. A stream that runs past its bound is
13
+ // cut off, the partial file removed, and the person told in one line.
14
+ import { createWriteStream } from "node:fs";
15
+ import * as fs from "node:fs/promises";
16
+ import { join } from "node:path";
17
+ import { Readable, Transform, Writable } from "node:stream";
18
+ import { pipeline } from "node:stream/promises";
19
+ import {
20
+ feedPaths,
21
+ macZipName,
22
+ parseMacFeed,
23
+ parseWindowsReleases,
24
+ } from "./release.mjs";
25
+ import { createChecker } from "./verify.mjs";
26
+ import {
27
+ ELEVATION_UNKNOWN_LINE,
28
+ OTHER_ACCOUNT_LINE,
29
+ elevatedRunPlaces,
30
+ giveBackLines,
31
+ systemWideCopyLine,
32
+ windowsDesktopIsOtherAccount,
33
+ windowsElevated,
34
+ windowsGiveToPerson,
35
+ windowsSystemWideCopy,
36
+ } from "./windows.mjs";
37
+
38
+ // Thrown for anything the person needs to hear as one plain line (exit 1).
39
+ export class SetupError extends Error {}
40
+
41
+ export const DEFAULT_LIMITS = {
42
+ download: 512 * 1024 * 1024, // no desktop artifact comes near this
43
+ manifest: 4 * 1024 * 1024, // RELEASES, RELEASES.json, *.sigstore.json
44
+ };
45
+
46
+ const INVITE_FLAG = "--invite";
47
+
48
+ class TooLarge extends Error {}
49
+
50
+ // A Transform that passes bytes through `onChunk` and fails once more than `limit` have passed.
51
+ function bounded(limit, onChunk) {
52
+ let seen = 0;
53
+ return new Transform({
54
+ transform(chunk, _encoding, callback) {
55
+ seen += chunk.length;
56
+ if (seen > limit) {
57
+ callback(new TooLarge());
58
+ return;
59
+ }
60
+ onChunk?.(chunk);
61
+ callback(null, chunk);
62
+ },
63
+ });
64
+ }
65
+
66
+ function contentLength(response) {
67
+ const header = response.headers.get("content-length");
68
+ const length = header === null ? NaN : Number(header);
69
+ return Number.isSafeInteger(length) && length >= 0 ? length : undefined;
70
+ }
71
+
72
+ // Throws `error` after cancelling a response body nobody will read: an unconsumed body keeps the
73
+ // connection, and so the process, alive until the server closes it.
74
+ async function refuse(response, error) {
75
+ await response.body?.cancel().catch(() => {});
76
+ throw error;
77
+ }
78
+
79
+ // The answers that mean a file isn't there: 404 (the downloads host, Blob behind Front Door, a
80
+ // local copy) and 403 (Cloud Storage's answer for a missing object where listing is denied,
81
+ // scripts/release/README.md). Only for the v2 release list (readFeed) do they mean "read the legacy
82
+ // feed"; that gives nothing away, as the legacy feed is verified with the same keys.
83
+ const NOT_THERE = new Set([403, 404]);
84
+
85
+ // GET `url` as text, at most `limit` bytes. With `absent`, a 404 or 403 resolves to null (the
86
+ // caller reads elsewhere); without it a 404 is refused as "no <what> yet" and a 403 like any other
87
+ // failure.
88
+ async function getText(fetch, url, what, limit, { absent = false } = {}) {
89
+ const response = await fetch(url).catch(() => null);
90
+ if (!response) {
91
+ throw new SetupError(`Couldn't reach the Nenya downloads to read ${what}.`);
92
+ }
93
+ if (absent && NOT_THERE.has(response.status)) {
94
+ await response.body?.cancel().catch(() => {});
95
+ return null;
96
+ }
97
+ if (response.status === 404) {
98
+ await refuse(
99
+ response,
100
+ new SetupError(`The Nenya downloads have no ${what} yet.`),
101
+ );
102
+ }
103
+ if (!response.ok) {
104
+ await refuse(
105
+ response,
106
+ new SetupError(
107
+ `Couldn't read ${what} from the Nenya downloads (HTTP ${response.status}).`,
108
+ ),
109
+ );
110
+ }
111
+ const declared = contentLength(response);
112
+ if (declared !== undefined && declared > limit) {
113
+ await refuse(
114
+ response,
115
+ new SetupError(`The Nenya downloads' ${what} is larger than expected.`),
116
+ );
117
+ }
118
+ const chunks = [];
119
+ try {
120
+ await pipeline(
121
+ Readable.fromWeb(response.body),
122
+ bounded(limit),
123
+ new Writable({
124
+ write(chunk, _encoding, callback) {
125
+ chunks.push(chunk);
126
+ callback();
127
+ },
128
+ }),
129
+ );
130
+ } catch (error) {
131
+ await refuse(
132
+ response,
133
+ error instanceof TooLarge
134
+ ? new SetupError(
135
+ `The Nenya downloads' ${what} is larger than expected.`,
136
+ )
137
+ : new SetupError(`Couldn't finish reading ${what}.`),
138
+ );
139
+ }
140
+ return Buffer.concat(chunks).toString("utf8");
141
+ }
142
+
143
+ // The channel's release list for one platform and arch (spec 15, signing rotation): the v2 root's
144
+ // first, desktop/v2/<channel>/<platform>/<arch>/<manifest>; only when that answers 404 or 403 (no v2 feed
145
+ // published yet; for a local copy, the file isn't there) the legacy root's, as before the bridge.
146
+ // Anything else from the v2 root (another HTTP status, no connection, a list or download that is
147
+ // then refused) is refused, never traded for the legacy feed. Resolves to { directoryUrl, text }:
148
+ // every download is built from that directory, the root actually read.
149
+ async function readFeed({
150
+ fetch,
151
+ baseUrl,
152
+ channel,
153
+ platform,
154
+ arch,
155
+ manifest,
156
+ what,
157
+ limit,
158
+ }) {
159
+ const [v2, legacy] = feedPaths(channel, platform, arch);
160
+ for (const [path, absent] of [
161
+ [v2, true],
162
+ [legacy, false],
163
+ ]) {
164
+ const directoryUrl = `${baseUrl}/${path}`;
165
+ const text = await getText(
166
+ fetch,
167
+ `${directoryUrl}/${manifest}`,
168
+ what,
169
+ limit,
170
+ {
171
+ absent,
172
+ },
173
+ );
174
+ if (text !== null) return { directoryUrl, text };
175
+ }
176
+ }
177
+
178
+ // Downloads `name` from `directoryUrl` into `file`, checking it against the bundle beside it with
179
+ // the listed release keys (`publicKeyPems`: lib/verify.mjs createChecker; any listed key may have
180
+ // signed it). `size`, when the feed declares one, bounds the download exactly. Refuses, with the
181
+ // one line, anything that does not verify or runs past its bound; nothing unverified stays on disk.
182
+ export async function downloadVerified({
183
+ fetch,
184
+ directoryUrl,
185
+ name,
186
+ file,
187
+ publicKeyPems,
188
+ version,
189
+ size,
190
+ limits = DEFAULT_LIMITS,
191
+ }) {
192
+ // The keys are loaded (each EC P-256) before anything is fetched.
193
+ const checker = createChecker(publicKeyPems);
194
+ const url = `${directoryUrl}/${encodeURIComponent(name)}`;
195
+ const bundle = await getText(
196
+ fetch,
197
+ `${url}.sigstore.json`,
198
+ `signature for Nenya ${version}`,
199
+ limits.manifest,
200
+ );
201
+ const response = await fetch(url).catch(() => null);
202
+ if (!response) {
203
+ throw new SetupError(`Couldn't download Nenya ${version}.`);
204
+ }
205
+ if (!response.ok) {
206
+ await refuse(
207
+ response,
208
+ new SetupError(
209
+ `Couldn't download Nenya ${version} (HTTP ${response.status}).`,
210
+ ),
211
+ );
212
+ }
213
+ const tooLarge = new SetupError(
214
+ `The download of Nenya ${version} is larger than expected, so it wasn't installed.`,
215
+ );
216
+ const declared = contentLength(response);
217
+ const limit = Math.min(
218
+ limits.download,
219
+ size ?? Infinity,
220
+ declared ?? Infinity,
221
+ );
222
+ if (
223
+ (size !== undefined && size > limits.download) ||
224
+ (declared ?? 0) > limit
225
+ ) {
226
+ await refuse(response, tooLarge);
227
+ }
228
+ try {
229
+ await pipeline(
230
+ Readable.fromWeb(response.body),
231
+ bounded(limit, (chunk) => checker.update(chunk)),
232
+ createWriteStream(file),
233
+ );
234
+ } catch (error) {
235
+ await fs.rm(file, { force: true });
236
+ await refuse(
237
+ response,
238
+ error instanceof TooLarge
239
+ ? tooLarge
240
+ : new SetupError(
241
+ `The download of Nenya ${version} didn't finish, so it wasn't installed.`,
242
+ ),
243
+ );
244
+ }
245
+ const result = checker.finish(bundle);
246
+ if (!result.ok) {
247
+ await fs.rm(file, { force: true });
248
+ throw new SetupError(
249
+ `The download of Nenya ${version} doesn't match its signature, so it wasn't installed.`,
250
+ );
251
+ }
252
+ }
253
+
254
+ function inviteArgs(invite) {
255
+ return invite ? [INVITE_FLAG, invite] : [];
256
+ }
257
+
258
+ function inviteLine(invite) {
259
+ return `Your invite code is ${invite}: Nenya asks for it when you sign up.`;
260
+ }
261
+
262
+ // The executable an unpacked bundle names in Contents/Info.plist (CFBundleExecutable), if the
263
+ // bundle is complete; null otherwise. Electron Forge writes the plist as XML.
264
+ async function bundleExecutable(app) {
265
+ const plist = await fs
266
+ .readFile(join(app, "Contents", "Info.plist"), "utf8")
267
+ .catch(() => null);
268
+ const match =
269
+ plist &&
270
+ /<key>CFBundleExecutable<\/key>\s*<string>([^<]+)<\/string>/.exec(plist);
271
+ if (!match) return null;
272
+ const executable = join(app, "Contents", "MacOS", match[1]);
273
+ return (await exists(executable)) ? executable : null;
274
+ }
275
+
276
+ // The macOS app's bundle id (apps/desktop/src/main/core/installFootprint.ts BUNDLE_ID): LaunchServices names a running
277
+ // Nenya by it, and Squirrel.Mac names its ShipIt job and cache folder after it.
278
+ export const MAC_BUNDLE_ID = "com.qwntl.nenya.desktop";
279
+
280
+ /**
281
+ * BA-37: the update the installed Nenya's Squirrel.Mac prepared, discarded before this install asks that copy to quit
282
+ * and puts the new version in place. ShipIt waits for the app to terminate and then installs the prepared update over
283
+ * the bundle (apps/desktop/src/main/update.ts: the quit carries the install), older or from another channel than this
284
+ * install. Its launchd job (<bundle id>.ShipIt, submitted when the update was prepared) is removed, so nothing installs
285
+ * at the quit, and its cache folder (~/Library/Caches/<bundle id>.ShipIt: the prepared bundle and ShipIt's state) goes
286
+ * with it. (a21 deploy/client/npm/installer discardStagedUpdates, for Squirrel.Mac's own staging.) True when the
287
+ * folder is gone or never was.
288
+ */
289
+ export async function discardStagedUpdates({ home, system }) {
290
+ system.run("/bin/launchctl", ["remove", `${MAC_BUNDLE_ID}.ShipIt`], {
291
+ timeout: 15_000,
292
+ });
293
+ const cache = join(home, "Library", "Caches", `${MAC_BUNDLE_ID}.ShipIt`);
294
+ await fs.rm(cache, { recursive: true, force: true }).catch(() => {});
295
+ return !(await exists(cache));
296
+ }
297
+
298
+ /** The pid of a running Nenya (LaunchServices' record, read with lsappinfo: no Automation prompt), or null. */
299
+ export function runningMacPid(system) {
300
+ const shown = system.run(
301
+ "/usr/bin/lsappinfo",
302
+ ["info", "-only", "pid", "-app", MAC_BUNDLE_ID],
303
+ { timeout: 15_000, output: true },
304
+ );
305
+ const match = /"pid"\s*=\s*(\d+)/.exec(String(shown.stdout ?? ""));
306
+ return match ? Number(match[1]) : null;
307
+ }
308
+
309
+ /**
310
+ * BA-7: asks a running Nenya to quit (SIGTERM to that one pid, which Electron handles as Quit) and waits up to about
311
+ * 15 s. True when no Nenya is running afterwards; false when it is still open, and then nothing may be swapped.
312
+ * (a21 deploy/client/npm/installer quitRunningMac.)
313
+ */
314
+ export function quitRunningMac(system) {
315
+ const pid = runningMacPid(system);
316
+ if (pid === null) return true;
317
+ system.run("/bin/kill", ["-TERM", String(pid)], { timeout: 15_000 });
318
+ for (let attempt = 0; attempt < 30; attempt += 1) {
319
+ if (runningMacPid(system) === null) return true;
320
+ system.run("/bin/sleep", ["0.5"]);
321
+ }
322
+ return runningMacPid(system) === null;
323
+ }
324
+
325
+ // On both OSes `beforeInstall`, when given, runs once the download has verified and before
326
+ // anything is installed or started (the CLI records a local feed's environment there, so the app's
327
+ // first start already reads it); if it throws, nothing is installed.
328
+ //
329
+ // macOS: ~/Applications/Nenya.app from the Squirrel.Mac update ZIP, unpacked with the system's
330
+ // `ditto` (what Squirrel.Mac itself uses: it keeps symbolic links, modes and the code signature)
331
+ // into a staging folder beside the target, so the swap is two renames on one volume; then opened
332
+ // with `open -n`, which hands `--invite CODE` to the app as the old installer did (the app reads
333
+ // it on first launch and from a second instance).
334
+ export async function installDarwin({
335
+ fetch,
336
+ baseUrl,
337
+ channel,
338
+ arch,
339
+ home,
340
+ tmpdir,
341
+ system,
342
+ publicKeyPems,
343
+ invite,
344
+ repair,
345
+ out,
346
+ beforeInstall,
347
+ limits = DEFAULT_LIMITS,
348
+ }) {
349
+ const { directoryUrl, text: feed } = await readFeed({
350
+ fetch,
351
+ baseUrl,
352
+ channel,
353
+ platform: "darwin",
354
+ arch,
355
+ manifest: "RELEASES.json",
356
+ what: `${channel} release list for this Mac`,
357
+ limit: limits.manifest,
358
+ });
359
+ let release;
360
+ try {
361
+ release = parseMacFeed(feed);
362
+ } catch (error) {
363
+ throw new SetupError(
364
+ `The Nenya downloads' release list can't be read (${error.message}).`,
365
+ );
366
+ }
367
+ if (release.name !== macZipName(arch, release.version)) {
368
+ throw new SetupError(
369
+ `The Nenya downloads' release list names an unexpected file (${release.name}).`,
370
+ );
371
+ }
372
+
373
+ const applications = join(home, "Applications");
374
+ const target = join(applications, "Nenya.app");
375
+ const work = await fs.mkdtemp(join(tmpdir, "nenya-setup-"));
376
+ try {
377
+ const zip = join(work, release.name);
378
+ await downloadVerified({
379
+ fetch,
380
+ directoryUrl,
381
+ name: release.name,
382
+ file: zip,
383
+ publicKeyPems,
384
+ version: release.version,
385
+ size: release.size,
386
+ limits,
387
+ });
388
+ await beforeInstall?.();
389
+
390
+ await fs.mkdir(applications, { recursive: true });
391
+ const stage = await fs.mkdtemp(join(applications, ".nenya-install-"));
392
+ let keepStage = false;
393
+ try {
394
+ const unpacked = system.run("/usr/bin/ditto", ["-x", "-k", zip, stage]);
395
+ const app = join(stage, "Nenya.app");
396
+ if (unpacked.status !== 0 || !(await bundleExecutable(app))) {
397
+ throw new SetupError(
398
+ `Nenya ${release.version} couldn't be unpacked into ${applications}.`,
399
+ );
400
+ }
401
+ // BA-37, then BA-7: the update a running copy prepared goes first (its quit would install it over this one),
402
+ // then that copy quits, so the swap never happens under a running Nenya.
403
+ await discardStagedUpdates({ home, system });
404
+ if (!quitRunningMac(system)) {
405
+ throw new SetupError(
406
+ "Nenya is open on this Mac and didn't quit, so nothing was changed. This command works once Nenya is quit.",
407
+ );
408
+ }
409
+ const previous = (await exists(target))
410
+ ? join(stage, "previous.app")
411
+ : null;
412
+ if (previous) await fs.rename(target, previous);
413
+ try {
414
+ await fs.rename(app, target);
415
+ } catch {
416
+ // The copy that was there goes back before the stage is removed. If even that fails,
417
+ // the stage stays, with the previous copy inside, and the person is told where it is.
418
+ const restored = previous
419
+ ? await fs.rename(previous, target).then(
420
+ () => true,
421
+ () => false,
422
+ )
423
+ : true;
424
+ if (!restored) {
425
+ keepStage = true;
426
+ throw new SetupError(
427
+ `Nenya ${release.version} couldn't be put into ${applications}, and the copy that was there is now at ${previous} instead of ${target}.`,
428
+ );
429
+ }
430
+ throw new SetupError(
431
+ `Nenya ${release.version} couldn't be put into ${applications}.`,
432
+ );
433
+ }
434
+ } finally {
435
+ if (!keepStage) {
436
+ await fs.rm(stage, { recursive: true, force: true }).catch(() => {});
437
+ }
438
+ }
439
+ } finally {
440
+ await fs.rm(work, { recursive: true, force: true }).catch(() => {});
441
+ }
442
+
443
+ out(
444
+ `${repair ? "Reinstalled" : "Installed"} Nenya ${release.version} in ~/Applications.`,
445
+ );
446
+ const args = invite ? [target, "--args", ...inviteArgs(invite)] : [target];
447
+ const opened = system.run("/usr/bin/open", ["-n", ...args]).status === 0;
448
+ if (!opened) {
449
+ out("Nenya couldn't be opened; it's in Applications.");
450
+ if (invite) out(inviteLine(invite));
451
+ }
452
+ return 0;
453
+ }
454
+
455
+ // Windows: the Squirrel installer run silently installs under %LOCALAPPDATA%\<squirrelId> for this
456
+ // account. It doesn't always start the app (WIN2-01), so setup opens it after every install, as on
457
+ // macOS; with `--invite CODE` that start hands the code over, to the running one if Squirrel did
458
+ // start it (Squirrel passes nothing through).
459
+ // From an administrator terminal (lib/windows.mjs): elevated as another account than the desktop's,
460
+ // nothing is fetched or written (BA-40); elevated as the person, the install is still theirs, and
461
+ // what this run made in their profile is given back to them (BA-76), and anything that couldn't be is
462
+ // said. If Windows can't say whether the terminal is elevated, nothing is fetched or written. A Nenya
463
+ // installed for everyone in Program Files is named once, with why it isn't removed from there
464
+ // (NPX-BESIDE).
465
+ export async function installWin32({
466
+ fetch,
467
+ baseUrl,
468
+ channel,
469
+ arch,
470
+ home,
471
+ env,
472
+ tmpdir,
473
+ system,
474
+ publicKeyPems,
475
+ invite,
476
+ repair,
477
+ out,
478
+ beforeInstall,
479
+ limits = DEFAULT_LIMITS,
480
+ lstat,
481
+ realpath,
482
+ existsSync,
483
+ pid,
484
+ }) {
485
+ const elevated = windowsElevated({ env, system });
486
+ if (elevated === null) throw new SetupError(ELEVATION_UNKNOWN_LINE);
487
+ if (elevated && windowsDesktopIsOtherAccount({ env, system, pid })) {
488
+ throw new SetupError(OTHER_ACCOUNT_LINE);
489
+ }
490
+ const { directoryUrl, text: releases } = await readFeed({
491
+ fetch,
492
+ baseUrl,
493
+ channel,
494
+ platform: "win32",
495
+ arch,
496
+ manifest: "RELEASES",
497
+ what: `${channel} release list for this computer`,
498
+ limit: limits.manifest,
499
+ });
500
+ let release;
501
+ try {
502
+ release = parseWindowsReleases(releases);
503
+ } catch (error) {
504
+ throw new SetupError(
505
+ `The Nenya downloads' release list can't be read (${error.message}).`,
506
+ );
507
+ }
508
+
509
+ const work = await fs.mkdtemp(join(tmpdir, "nenya-setup-"));
510
+ try {
511
+ const setup = join(work, release.installer);
512
+ await downloadVerified({
513
+ fetch,
514
+ directoryUrl,
515
+ name: release.installer,
516
+ file: setup,
517
+ publicKeyPems,
518
+ version: release.version,
519
+ limits,
520
+ });
521
+ await beforeInstall?.();
522
+ const installed = system.run(setup, ["--silent"], { timeout: 900_000 });
523
+ if (installed.status !== 0) {
524
+ throw new SetupError(
525
+ `Nenya ${release.version}'s installer didn't finish.`,
526
+ );
527
+ }
528
+ } finally {
529
+ await fs.rm(work, { recursive: true, force: true }).catch(() => {});
530
+ }
531
+
532
+ const localAppData = env.LOCALAPPDATA || join(home, "AppData", "Local");
533
+ const folder = join(localAppData, release.squirrelId);
534
+ const givenBack = elevated
535
+ ? windowsGiveToPerson({
536
+ places: elevatedRunPlaces({
537
+ env,
538
+ home,
539
+ squirrelId: release.squirrelId,
540
+ }),
541
+ env,
542
+ system,
543
+ ...(lstat ? { lstat } : {}),
544
+ ...(realpath ? { realpath } : {}),
545
+ })
546
+ : null;
547
+ out(
548
+ `${repair ? "Reinstalled" : "Installed"} Nenya ${release.version} for this account.`,
549
+ );
550
+ if (givenBack) for (const line of giveBackLines(givenBack)) out(line);
551
+ const other = windowsSystemWideCopy({
552
+ env,
553
+ system,
554
+ ...(existsSync ? { exists: existsSync } : {}),
555
+ });
556
+ if (other) out(systemWideCopyLine(other));
557
+ // The app's own launcher is the one .exe beside Squirrel's Update.exe. From an administrator
558
+ // terminal it starts again as the person (apps/desktop/src/main/core/elevation.ts).
559
+ const executables = (await fs.readdir(folder).catch(() => [])).filter(
560
+ (name) =>
561
+ name.toLowerCase().endsWith(".exe") &&
562
+ name.toLowerCase() !== "update.exe",
563
+ );
564
+ const opened =
565
+ executables.length === 1 &&
566
+ (await system.launch(join(folder, executables[0]), inviteArgs(invite)));
567
+ if (!opened) {
568
+ out("Nenya couldn't be opened; it's in the Start menu.");
569
+ if (invite) out(inviteLine(invite));
570
+ }
571
+ return 0;
572
+ }
573
+
574
+ async function exists(path) {
575
+ return fs
576
+ .access(path)
577
+ .then(() => true)
578
+ .catch(() => false);
579
+ }