upgradr 0.4.0 → 0.5.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 +38 -0
- package/dist/config.d.ts +8 -0
- package/dist/config.js +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +4 -0
- package/dist/upgrade.d.ts +3 -0
- package/dist/upgrade.js +51 -17
- package/dist/verify.d.ts +29 -0
- package/dist/verify.js +78 -0
- package/package.json +1 -1
- package/src/config.ts +10 -0
- package/src/index.ts +5 -0
- package/src/upgrade.ts +71 -21
- package/src/verify.ts +116 -0
package/README.md
CHANGED
|
@@ -14,6 +14,7 @@ generalized so any Bun or Node CLI can drop it in.
|
|
|
14
14
|
- **Cached background notice** — a throttled "update available" line on startup, shown only in a TTY, with an env-var opt-out.
|
|
15
15
|
- **`upgrade` that always re-checks** — an explicit upgrade never trusts a stale cache.
|
|
16
16
|
- **Four install methods, auto-detected** — `npm` / `bun` global installs, a compiled release **binary** (downloaded + swapped in place, with `sudo` fallback), and `local-dev` (source checkout → no-op).
|
|
17
|
+
- **Signed release checks** — optionally verify a downloaded binary against the release's `SHA256SUMS` and its [minisign](https://jedisct1.github.io/minisign/) signature before installing it.
|
|
17
18
|
- **No framework coupling** — a `createUpdater(config)` factory returns plain async methods. Bring your own CLI (Commander, etc.). The library never writes to the console or exits the process; you own presentation.
|
|
18
19
|
|
|
19
20
|
## Install
|
|
@@ -115,6 +116,7 @@ if (!result.success && !result.performed && result.error) {
|
|
|
115
116
|
| `backgroundSkipCommands` | | `["check-update","upgrade"]` | Commands that suppress the startup notice. |
|
|
116
117
|
| `formatNotice` | | built-in | `(ctx) => string` to fully render the startup notice. |
|
|
117
118
|
| `assetName` | | — | `(target) => string` to fully override the release asset name. |
|
|
119
|
+
| `verify` | | — | `{ checksums, publicKey? }`: check a release binary before installing it. See [Verifying release binaries](#verifying-release-binaries). |
|
|
118
120
|
| `fetchImpl` | | global `fetch` | Injectable `fetch` (for testing). |
|
|
119
121
|
| `onProgress` | | no-op | Progress callback (e.g. the sudo heads-up during a binary swap). |
|
|
120
122
|
|
|
@@ -178,6 +180,42 @@ So a v1.2.3 release of `binaryName: "your-cli"` needs assets like
|
|
|
178
180
|
`your-cli-darwin-arm64`, `your-cli-linux-x64`, `your-cli-windows-x64.exe`.
|
|
179
181
|
(Ship a different scheme? Override `assetName` in the config.)
|
|
180
182
|
|
|
183
|
+
### Verifying release binaries
|
|
184
|
+
|
|
185
|
+
Without `verify`, the `binary` path installs whatever the download URL returns.
|
|
186
|
+
Set it to check each download first:
|
|
187
|
+
|
|
188
|
+
```ts
|
|
189
|
+
createUpdater({
|
|
190
|
+
// …required config…
|
|
191
|
+
verify: {
|
|
192
|
+
checksums: "SHA256SUMS", // release asset of `<sha256> <file>` lines
|
|
193
|
+
publicKey: "RWT…", // optional: the base64 line of your minisign.pub
|
|
194
|
+
},
|
|
195
|
+
});
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
The `binary` path then downloads `<checksums>` from the same release, plus
|
|
199
|
+
`<checksums>.minisig` when `publicKey` is set. It installs the binary only if
|
|
200
|
+
the [minisign](https://jedisct1.github.io/minisign/) signature on the checksum
|
|
201
|
+
file is valid for `publicKey`, and the file lists the asset's name with the
|
|
202
|
+
SHA-256 of the downloaded bytes. Otherwise `upgrade()` returns
|
|
203
|
+
`success: false` with the failed check in `error`, and the installed binary is
|
|
204
|
+
left alone.
|
|
205
|
+
|
|
206
|
+
A checksum file alone catches a corrupted download. Only the signature catches
|
|
207
|
+
a tampered one, because the checksum file comes from the same host as the
|
|
208
|
+
binary. Produce both in CI, with the secret key in a CI secret:
|
|
209
|
+
|
|
210
|
+
```sh
|
|
211
|
+
cd dist && sha256sum your-cli-* > SHA256SUMS
|
|
212
|
+
minisign -Sm SHA256SUMS -s minisign.key # writes SHA256SUMS.minisig
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
Anyone can check a release by hand with
|
|
216
|
+
`minisign -Vm SHA256SUMS -P <publicKey>`. A host that serves an older release's
|
|
217
|
+
validly signed files can still offer that older binary as the latest.
|
|
218
|
+
|
|
181
219
|
### Example release workflow
|
|
182
220
|
|
|
183
221
|
Trigger a release when `package.json`'s `version` changes on `main`: create the
|
package/dist/config.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { VerifyConfig } from "./verify.ts";
|
|
1
2
|
/** How the current binary/script was installed. */
|
|
2
3
|
export type InstallMethod = "npm" | "bun" | "binary" | "local-dev";
|
|
3
4
|
/**
|
|
@@ -62,6 +63,12 @@ export interface UpdaterConfig {
|
|
|
62
63
|
formatNotice?: (ctx: NoticeContext) => string;
|
|
63
64
|
/** Override the full release asset name for a platform. */
|
|
64
65
|
assetName?: (target: AssetTarget) => string;
|
|
66
|
+
/**
|
|
67
|
+
* Check a downloaded release binary against the release's checksum file,
|
|
68
|
+
* and that file's minisign signature, before installing it. Omit to install
|
|
69
|
+
* the download unchecked.
|
|
70
|
+
*/
|
|
71
|
+
verify?: VerifyConfig;
|
|
65
72
|
/** Injectable `fetch` (for testing). Defaults to the global `fetch`. */
|
|
66
73
|
fetchImpl?: FetchLike;
|
|
67
74
|
/** Called with human-readable progress messages (e.g. sudo prompts). Defaults to a no-op. */
|
|
@@ -82,6 +89,7 @@ export interface ResolvedConfig {
|
|
|
82
89
|
backgroundSkipCommands: string[];
|
|
83
90
|
formatNotice: ((ctx: NoticeContext) => string) | undefined;
|
|
84
91
|
assetName: ((target: AssetTarget) => string) | undefined;
|
|
92
|
+
verify: VerifyConfig | undefined;
|
|
85
93
|
fetchImpl: FetchLike;
|
|
86
94
|
onProgress: (message: string) => void;
|
|
87
95
|
}
|
package/dist/config.js
CHANGED
|
@@ -18,6 +18,7 @@ export function resolveConfig(config) {
|
|
|
18
18
|
backgroundSkipCommands: config.backgroundSkipCommands ?? DEFAULT_BACKGROUND_SKIP_COMMANDS,
|
|
19
19
|
formatNotice: config.formatNotice,
|
|
20
20
|
assetName: config.assetName,
|
|
21
|
+
verify: config.verify,
|
|
21
22
|
fetchImpl: config.fetchImpl ?? fetch,
|
|
22
23
|
onProgress: config.onProgress ?? (() => { }),
|
|
23
24
|
};
|
package/dist/index.d.ts
CHANGED
|
@@ -4,6 +4,7 @@ export { fetchChangelog, fetchLatestVersion, isNewerVersion, type UpdateCache, t
|
|
|
4
4
|
export type { AssetTarget, FetchLike, InstallMethod, NoticeContext, ResolvedConfig, UpdaterConfig, } from "./config.ts";
|
|
5
5
|
export { formatNotice } from "./notice.ts";
|
|
6
6
|
export { type InstallOutcome, platformArtifactName, } from "./upgrade.ts";
|
|
7
|
+
export type { VerifyConfig } from "./verify.ts";
|
|
7
8
|
/** The outcome of {@link Updater.upgrade}. */
|
|
8
9
|
export interface UpgradeResult {
|
|
9
10
|
/** How the running CLI was installed. */
|
package/dist/index.js
CHANGED
|
@@ -57,9 +57,12 @@ export function createUpdater(config) {
|
|
|
57
57
|
let outcome;
|
|
58
58
|
switch (method) {
|
|
59
59
|
case "bun":
|
|
60
|
+
// upgradr just confirmed this version on the registry, so skip
|
|
61
|
+
// bun's manifest cache — it can lag right after a publish.
|
|
60
62
|
outcome = await upgradeWithPackageManager("bun", [
|
|
61
63
|
"install",
|
|
62
64
|
"-g",
|
|
65
|
+
"--no-cache",
|
|
63
66
|
`${cfg.packageName}@${info.latestVersion}`,
|
|
64
67
|
]);
|
|
65
68
|
break;
|
|
@@ -76,6 +79,7 @@ export function createUpdater(config) {
|
|
|
76
79
|
latestVersion: info.latestVersion,
|
|
77
80
|
binaryName: cfg.binaryName,
|
|
78
81
|
assetName: cfg.assetName,
|
|
82
|
+
verify: cfg.verify,
|
|
79
83
|
fetchImpl: cfg.fetchImpl,
|
|
80
84
|
onProgress: cfg.onProgress,
|
|
81
85
|
});
|
package/dist/upgrade.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { AssetTarget, FetchLike } from "./config.ts";
|
|
2
|
+
import { type VerifyConfig } from "./verify.ts";
|
|
2
3
|
/** Outcome of a binary or package-manager install attempt. */
|
|
3
4
|
export interface InstallOutcome {
|
|
4
5
|
success: boolean;
|
|
@@ -19,12 +20,14 @@ export declare function upgradeWithPackageManager(command: string, args: string[
|
|
|
19
20
|
/**
|
|
20
21
|
* Download the release binary for `latestVersion` and swap it into place at
|
|
21
22
|
* `process.execPath`, falling back to `sudo mv` when a plain move is denied.
|
|
23
|
+
* With `verify`, a binary that fails its release checks is never written.
|
|
22
24
|
*/
|
|
23
25
|
export declare function upgradeFromBinary(opts: {
|
|
24
26
|
repo: string;
|
|
25
27
|
latestVersion: string;
|
|
26
28
|
binaryName: string;
|
|
27
29
|
assetName?: (target: AssetTarget) => string;
|
|
30
|
+
verify?: VerifyConfig;
|
|
28
31
|
fetchImpl?: FetchLike;
|
|
29
32
|
onProgress?: (message: string) => void;
|
|
30
33
|
}): Promise<InstallOutcome>;
|
package/dist/upgrade.js
CHANGED
|
@@ -3,21 +3,44 @@ import { chmod, unlink, writeFile } from "node:fs/promises";
|
|
|
3
3
|
import { tmpdir } from "node:os";
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
import { promisify } from "node:util";
|
|
6
|
+
import { releaseProblem } from "./verify.js";
|
|
6
7
|
const execFileAsync = promisify(execFile);
|
|
8
|
+
/** Max number of trailing output lines kept in an error message. */
|
|
9
|
+
const OUTPUT_TAIL_LINES = 10;
|
|
7
10
|
/**
|
|
8
|
-
* Run a command without throwing, returning its exit code.
|
|
9
|
-
* (Node + Bun) replacement for Bun's `$`…`.nothrow()`.
|
|
11
|
+
* Run a command without throwing, returning its exit code and output.
|
|
12
|
+
* Cross-runtime (Node + Bun) replacement for Bun's `$`…`.nothrow()`.
|
|
10
13
|
*/
|
|
11
14
|
async function run(command, args) {
|
|
12
15
|
try {
|
|
13
|
-
await execFileAsync(command, args);
|
|
14
|
-
return { exitCode: 0 };
|
|
16
|
+
const { stdout, stderr } = await execFileAsync(command, args);
|
|
17
|
+
return { exitCode: 0, stdout: String(stdout), stderr: String(stderr) };
|
|
15
18
|
}
|
|
16
19
|
catch (err) {
|
|
17
|
-
const
|
|
18
|
-
return {
|
|
20
|
+
const e = err;
|
|
21
|
+
return {
|
|
22
|
+
exitCode: typeof e.code === "number" ? e.code : 1,
|
|
23
|
+
stdout: String(e.stdout ?? ""),
|
|
24
|
+
stderr: String(e.stderr ?? ""),
|
|
25
|
+
spawnError: typeof e.code === "string" ? e.message : undefined,
|
|
26
|
+
};
|
|
19
27
|
}
|
|
20
28
|
}
|
|
29
|
+
/**
|
|
30
|
+
* Describe a failed {@link run}: the exact command, its exit code, and the
|
|
31
|
+
* tail of its stderr (or stdout when stderr is empty).
|
|
32
|
+
*/
|
|
33
|
+
function describeFailure(command, args, result) {
|
|
34
|
+
const cmd = [command, ...args].join(" ");
|
|
35
|
+
if (result.spawnError)
|
|
36
|
+
return `${cmd} failed: ${result.spawnError}`;
|
|
37
|
+
const output = (result.stderr.trim() || result.stdout.trim())
|
|
38
|
+
.split("\n")
|
|
39
|
+
.slice(-OUTPUT_TAIL_LINES)
|
|
40
|
+
.join("\n");
|
|
41
|
+
const head = `${cmd} exited with code ${result.exitCode}`;
|
|
42
|
+
return output ? `${head}:\n${output}` : head;
|
|
43
|
+
}
|
|
21
44
|
/**
|
|
22
45
|
* Build the GitHub release asset name for the current platform.
|
|
23
46
|
* Defaults to `<binaryName>-<os>-<arch>[.exe]`, or delegates to `assetName`.
|
|
@@ -49,14 +72,12 @@ export async function upgradeWithPackageManager(command, args) {
|
|
|
49
72
|
const result = await run(command, args);
|
|
50
73
|
return result.exitCode === 0
|
|
51
74
|
? { success: true }
|
|
52
|
-
: {
|
|
53
|
-
success: false,
|
|
54
|
-
error: `${command} exited with code ${result.exitCode}`,
|
|
55
|
-
};
|
|
75
|
+
: { success: false, error: describeFailure(command, args, result) };
|
|
56
76
|
}
|
|
57
77
|
/**
|
|
58
78
|
* Download the release binary for `latestVersion` and swap it into place at
|
|
59
79
|
* `process.execPath`, falling back to `sudo mv` when a plain move is denied.
|
|
80
|
+
* With `verify`, a binary that fails its release checks is never written.
|
|
60
81
|
*/
|
|
61
82
|
export async function upgradeFromBinary(opts) {
|
|
62
83
|
const doFetch = opts.fetchImpl ?? fetch;
|
|
@@ -65,31 +86,44 @@ export async function upgradeFromBinary(opts) {
|
|
|
65
86
|
binaryName: opts.binaryName,
|
|
66
87
|
assetName: opts.assetName,
|
|
67
88
|
});
|
|
68
|
-
const
|
|
69
|
-
const url = `https://github.com/${opts.repo}/releases/download/${tag}/${artifact}`;
|
|
89
|
+
const releaseUrl = `https://github.com/${opts.repo}/releases/download/v${opts.latestVersion}`;
|
|
70
90
|
const tmpPath = join(tmpdir(), `${opts.binaryName}-upgrade-${Date.now()}`);
|
|
71
91
|
const targetPath = process.execPath;
|
|
72
92
|
try {
|
|
73
|
-
const res = await doFetch(
|
|
93
|
+
const res = await doFetch(`${releaseUrl}/${artifact}`);
|
|
74
94
|
if (!res.ok) {
|
|
75
95
|
return {
|
|
76
96
|
success: false,
|
|
77
97
|
error: `Failed to download binary: HTTP ${res.status}`,
|
|
78
98
|
};
|
|
79
99
|
}
|
|
80
|
-
const bytes = await res.arrayBuffer();
|
|
81
|
-
|
|
100
|
+
const bytes = new Uint8Array(await res.arrayBuffer());
|
|
101
|
+
if (opts.verify) {
|
|
102
|
+
const problem = await releaseProblem({
|
|
103
|
+
config: opts.verify,
|
|
104
|
+
artifact,
|
|
105
|
+
binary: bytes,
|
|
106
|
+
download: (name) => doFetch(`${releaseUrl}/${name}`),
|
|
107
|
+
});
|
|
108
|
+
if (problem)
|
|
109
|
+
return { success: false, error: problem };
|
|
110
|
+
}
|
|
111
|
+
await writeFile(tmpPath, bytes);
|
|
82
112
|
await chmod(tmpPath, 0o755);
|
|
83
113
|
// Try to move into place (mv handles cross-filesystem moves).
|
|
84
114
|
const mv = await run("mv", [tmpPath, targetPath]);
|
|
85
115
|
if (mv.exitCode !== 0) {
|
|
86
116
|
// Fall back to sudo.
|
|
87
117
|
onProgress("Requires elevated permissions...");
|
|
88
|
-
const
|
|
118
|
+
const sudoArgs = ["mv", tmpPath, targetPath];
|
|
119
|
+
const sudo = await run("sudo", sudoArgs);
|
|
89
120
|
if (sudo.exitCode !== 0) {
|
|
121
|
+
await unlink(tmpPath).catch(() => { });
|
|
90
122
|
return {
|
|
91
123
|
success: false,
|
|
92
|
-
error:
|
|
124
|
+
error: `Failed to install binary. Try running with sudo.\n` +
|
|
125
|
+
`${describeFailure("mv", [tmpPath, targetPath], mv)}\n` +
|
|
126
|
+
describeFailure("sudo", sudoArgs, sudo),
|
|
93
127
|
};
|
|
94
128
|
}
|
|
95
129
|
}
|
package/dist/verify.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** Checks a downloaded release binary must pass before it is installed. */
|
|
2
|
+
export interface VerifyConfig {
|
|
3
|
+
/** Release asset listing `<sha256> <file>` lines, e.g. `"SHA256SUMS"`. */
|
|
4
|
+
checksums: string;
|
|
5
|
+
/**
|
|
6
|
+
* minisign public key: the base64 line of a `minisign.pub` file (the whole
|
|
7
|
+
* file is accepted too). When set, the checksums asset must carry a valid
|
|
8
|
+
* minisign signature, published as `<checksums>.minisig`.
|
|
9
|
+
*/
|
|
10
|
+
publicKey?: string;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Whether `minisig` (the contents of a `.minisig` file) is a valid minisign
|
|
14
|
+
* signature of `data` by `publicKey`. Accepts both the prehashed (`ED`) and
|
|
15
|
+
* legacy (`Ed`) algorithms, and checks the key ID and the global signature
|
|
16
|
+
* over the trusted comment.
|
|
17
|
+
*/
|
|
18
|
+
export declare function verifyMinisign(data: Uint8Array, minisig: string, publicKey: string): boolean;
|
|
19
|
+
/**
|
|
20
|
+
* Why `binary`, the release asset named `artifact`, fails `config`'s checks,
|
|
21
|
+
* or `undefined` when it passes. `download` fetches another asset of the same
|
|
22
|
+
* release by name.
|
|
23
|
+
*/
|
|
24
|
+
export declare function releaseProblem(opts: {
|
|
25
|
+
config: VerifyConfig;
|
|
26
|
+
artifact: string;
|
|
27
|
+
binary: Uint8Array;
|
|
28
|
+
download: (name: string) => Promise<Response>;
|
|
29
|
+
}): Promise<string | undefined>;
|
package/dist/verify.js
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { createHash, createPublicKey, verify } from "node:crypto";
|
|
2
|
+
const TRUSTED_COMMENT = "trusted comment: ";
|
|
3
|
+
const CHECKSUM_LINE_RE = /^([0-9a-f]{64})\s+\*?(.+)$/i;
|
|
4
|
+
const decode = (line) => Buffer.from(line?.trim() ?? "", "base64");
|
|
5
|
+
/**
|
|
6
|
+
* Whether `minisig` (the contents of a `.minisig` file) is a valid minisign
|
|
7
|
+
* signature of `data` by `publicKey`. Accepts both the prehashed (`ED`) and
|
|
8
|
+
* legacy (`Ed`) algorithms, and checks the key ID and the global signature
|
|
9
|
+
* over the trusted comment.
|
|
10
|
+
*/
|
|
11
|
+
export function verifyMinisign(data, minisig, publicKey) {
|
|
12
|
+
// .pub: untrusted comment, then "Ed" + key ID (8) + Ed25519 key (32).
|
|
13
|
+
const pub = decode(publicKey.trim().split("\n").at(-1));
|
|
14
|
+
// .minisig: untrusted comment, algorithm + key ID (8) + signature (64),
|
|
15
|
+
// trusted comment, then the signature over signature + trusted comment.
|
|
16
|
+
const [, sigLine, trustedLine = "", globalLine] = minisig.split(/\r?\n/);
|
|
17
|
+
const sig = decode(sigLine);
|
|
18
|
+
const global = decode(globalLine);
|
|
19
|
+
if (pub.length !== 42 ||
|
|
20
|
+
sig.length !== 74 ||
|
|
21
|
+
global.length !== 64 ||
|
|
22
|
+
pub.subarray(0, 2).toString("latin1") !== "Ed" ||
|
|
23
|
+
!sig.subarray(2, 10).equals(pub.subarray(2, 10)) ||
|
|
24
|
+
!trustedLine.startsWith(TRUSTED_COMMENT)) {
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
const algorithm = sig.subarray(0, 2).toString("latin1");
|
|
28
|
+
if (algorithm !== "ED" && algorithm !== "Ed")
|
|
29
|
+
return false;
|
|
30
|
+
const key = createPublicKey({
|
|
31
|
+
key: {
|
|
32
|
+
kty: "OKP",
|
|
33
|
+
crv: "Ed25519",
|
|
34
|
+
x: pub.subarray(10).toString("base64url"),
|
|
35
|
+
},
|
|
36
|
+
format: "jwk",
|
|
37
|
+
});
|
|
38
|
+
const signature = sig.subarray(10);
|
|
39
|
+
const message = algorithm === "ED" ? createHash("blake2b512").update(data).digest() : data;
|
|
40
|
+
const trusted = Buffer.from(trustedLine.slice(TRUSTED_COMMENT.length));
|
|
41
|
+
return (verify(null, message, key, signature) &&
|
|
42
|
+
verify(null, Buffer.concat([signature, trusted]), key, global));
|
|
43
|
+
}
|
|
44
|
+
/** The SHA-256 a checksum file lists for `name`, lowercased. */
|
|
45
|
+
function listedChecksum(checksums, name) {
|
|
46
|
+
for (const line of checksums.split(/\r?\n/)) {
|
|
47
|
+
const match = CHECKSUM_LINE_RE.exec(line.trim());
|
|
48
|
+
if (match?.[2] === name)
|
|
49
|
+
return match[1]?.toLowerCase();
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Why `binary`, the release asset named `artifact`, fails `config`'s checks,
|
|
54
|
+
* or `undefined` when it passes. `download` fetches another asset of the same
|
|
55
|
+
* release by name.
|
|
56
|
+
*/
|
|
57
|
+
export async function releaseProblem(opts) {
|
|
58
|
+
const { checksums, publicKey } = opts.config;
|
|
59
|
+
const names = publicKey ? [checksums, `${checksums}.minisig`] : [checksums];
|
|
60
|
+
const responses = await Promise.all(names.map(opts.download));
|
|
61
|
+
const failed = responses.findIndex((res) => !res.ok);
|
|
62
|
+
if (failed !== -1) {
|
|
63
|
+
return `Failed to download ${names[failed]}: HTTP ${responses[failed]?.status}`;
|
|
64
|
+
}
|
|
65
|
+
const [sums, minisig] = await Promise.all(responses.map((res) => res.arrayBuffer()));
|
|
66
|
+
const sumsBytes = new Uint8Array(sums ?? new ArrayBuffer(0));
|
|
67
|
+
if (publicKey &&
|
|
68
|
+
!verifyMinisign(sumsBytes, new TextDecoder().decode(minisig), publicKey)) {
|
|
69
|
+
return `${checksums} is not signed by the configured public key`;
|
|
70
|
+
}
|
|
71
|
+
const expected = listedChecksum(new TextDecoder().decode(sumsBytes), opts.artifact);
|
|
72
|
+
if (!expected)
|
|
73
|
+
return `${checksums} does not list ${opts.artifact}`;
|
|
74
|
+
const actual = createHash("sha256").update(opts.binary).digest("hex");
|
|
75
|
+
return actual === expected
|
|
76
|
+
? undefined
|
|
77
|
+
: `Checksum mismatch for ${opts.artifact}`;
|
|
78
|
+
}
|
package/package.json
CHANGED
package/src/config.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import type { VerifyConfig } from "./verify.ts";
|
|
2
|
+
|
|
1
3
|
/** How the current binary/script was installed. */
|
|
2
4
|
export type InstallMethod = "npm" | "bun" | "binary" | "local-dev";
|
|
3
5
|
|
|
@@ -70,6 +72,12 @@ export interface UpdaterConfig {
|
|
|
70
72
|
formatNotice?: (ctx: NoticeContext) => string;
|
|
71
73
|
/** Override the full release asset name for a platform. */
|
|
72
74
|
assetName?: (target: AssetTarget) => string;
|
|
75
|
+
/**
|
|
76
|
+
* Check a downloaded release binary against the release's checksum file,
|
|
77
|
+
* and that file's minisign signature, before installing it. Omit to install
|
|
78
|
+
* the download unchecked.
|
|
79
|
+
*/
|
|
80
|
+
verify?: VerifyConfig;
|
|
73
81
|
/** Injectable `fetch` (for testing). Defaults to the global `fetch`. */
|
|
74
82
|
fetchImpl?: FetchLike;
|
|
75
83
|
/** Called with human-readable progress messages (e.g. sudo prompts). Defaults to a no-op. */
|
|
@@ -91,6 +99,7 @@ export interface ResolvedConfig {
|
|
|
91
99
|
backgroundSkipCommands: string[];
|
|
92
100
|
formatNotice: ((ctx: NoticeContext) => string) | undefined;
|
|
93
101
|
assetName: ((target: AssetTarget) => string) | undefined;
|
|
102
|
+
verify: VerifyConfig | undefined;
|
|
94
103
|
fetchImpl: FetchLike;
|
|
95
104
|
onProgress: (message: string) => void;
|
|
96
105
|
}
|
|
@@ -117,6 +126,7 @@ export function resolveConfig(config: UpdaterConfig): ResolvedConfig {
|
|
|
117
126
|
config.backgroundSkipCommands ?? DEFAULT_BACKGROUND_SKIP_COMMANDS,
|
|
118
127
|
formatNotice: config.formatNotice,
|
|
119
128
|
assetName: config.assetName,
|
|
129
|
+
verify: config.verify,
|
|
120
130
|
fetchImpl: config.fetchImpl ?? fetch,
|
|
121
131
|
onProgress: config.onProgress ?? (() => {}),
|
|
122
132
|
};
|
package/src/index.ts
CHANGED
|
@@ -39,6 +39,7 @@ export {
|
|
|
39
39
|
type InstallOutcome,
|
|
40
40
|
platformArtifactName,
|
|
41
41
|
} from "./upgrade.ts";
|
|
42
|
+
export type { VerifyConfig } from "./verify.ts";
|
|
42
43
|
|
|
43
44
|
/** The outcome of {@link Updater.upgrade}. */
|
|
44
45
|
export interface UpgradeResult {
|
|
@@ -156,9 +157,12 @@ export function createUpdater(config: UpdaterConfig): Updater {
|
|
|
156
157
|
let outcome: InstallOutcome;
|
|
157
158
|
switch (method) {
|
|
158
159
|
case "bun":
|
|
160
|
+
// upgradr just confirmed this version on the registry, so skip
|
|
161
|
+
// bun's manifest cache — it can lag right after a publish.
|
|
159
162
|
outcome = await upgradeWithPackageManager("bun", [
|
|
160
163
|
"install",
|
|
161
164
|
"-g",
|
|
165
|
+
"--no-cache",
|
|
162
166
|
`${cfg.packageName}@${info.latestVersion}`,
|
|
163
167
|
]);
|
|
164
168
|
break;
|
|
@@ -175,6 +179,7 @@ export function createUpdater(config: UpdaterConfig): Updater {
|
|
|
175
179
|
latestVersion: info.latestVersion,
|
|
176
180
|
binaryName: cfg.binaryName,
|
|
177
181
|
assetName: cfg.assetName,
|
|
182
|
+
verify: cfg.verify,
|
|
178
183
|
fetchImpl: cfg.fetchImpl,
|
|
179
184
|
onProgress: cfg.onProgress,
|
|
180
185
|
});
|
package/src/upgrade.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { tmpdir } from "node:os";
|
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
import { promisify } from "node:util";
|
|
6
6
|
import type { AssetTarget, FetchLike } from "./config.ts";
|
|
7
|
+
import { releaseProblem, type VerifyConfig } from "./verify.ts";
|
|
7
8
|
|
|
8
9
|
const execFileAsync = promisify(execFile);
|
|
9
10
|
|
|
@@ -13,23 +14,60 @@ export interface InstallOutcome {
|
|
|
13
14
|
error?: string;
|
|
14
15
|
}
|
|
15
16
|
|
|
17
|
+
/** Max number of trailing output lines kept in an error message. */
|
|
18
|
+
const OUTPUT_TAIL_LINES = 10;
|
|
19
|
+
|
|
20
|
+
interface RunResult {
|
|
21
|
+
exitCode: number;
|
|
22
|
+
stdout: string;
|
|
23
|
+
stderr: string;
|
|
24
|
+
/** Spawn failure (e.g. ENOENT) when the command never ran. */
|
|
25
|
+
spawnError?: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
16
28
|
/**
|
|
17
|
-
* Run a command without throwing, returning its exit code.
|
|
18
|
-
* (Node + Bun) replacement for Bun's `$`…`.nothrow()`.
|
|
29
|
+
* Run a command without throwing, returning its exit code and output.
|
|
30
|
+
* Cross-runtime (Node + Bun) replacement for Bun's `$`…`.nothrow()`.
|
|
19
31
|
*/
|
|
20
|
-
async function run(
|
|
21
|
-
command: string,
|
|
22
|
-
args: string[],
|
|
23
|
-
): Promise<{ exitCode: number }> {
|
|
32
|
+
async function run(command: string, args: string[]): Promise<RunResult> {
|
|
24
33
|
try {
|
|
25
|
-
await execFileAsync(command, args);
|
|
26
|
-
return { exitCode: 0 };
|
|
34
|
+
const { stdout, stderr } = await execFileAsync(command, args);
|
|
35
|
+
return { exitCode: 0, stdout: String(stdout), stderr: String(stderr) };
|
|
27
36
|
} catch (err) {
|
|
28
|
-
const
|
|
29
|
-
|
|
37
|
+
const e = err as {
|
|
38
|
+
code?: number | string;
|
|
39
|
+
stdout?: unknown;
|
|
40
|
+
stderr?: unknown;
|
|
41
|
+
message?: string;
|
|
42
|
+
};
|
|
43
|
+
return {
|
|
44
|
+
exitCode: typeof e.code === "number" ? e.code : 1,
|
|
45
|
+
stdout: String(e.stdout ?? ""),
|
|
46
|
+
stderr: String(e.stderr ?? ""),
|
|
47
|
+
spawnError: typeof e.code === "string" ? e.message : undefined,
|
|
48
|
+
};
|
|
30
49
|
}
|
|
31
50
|
}
|
|
32
51
|
|
|
52
|
+
/**
|
|
53
|
+
* Describe a failed {@link run}: the exact command, its exit code, and the
|
|
54
|
+
* tail of its stderr (or stdout when stderr is empty).
|
|
55
|
+
*/
|
|
56
|
+
function describeFailure(
|
|
57
|
+
command: string,
|
|
58
|
+
args: string[],
|
|
59
|
+
result: RunResult,
|
|
60
|
+
): string {
|
|
61
|
+
const cmd = [command, ...args].join(" ");
|
|
62
|
+
if (result.spawnError) return `${cmd} failed: ${result.spawnError}`;
|
|
63
|
+
const output = (result.stderr.trim() || result.stdout.trim())
|
|
64
|
+
.split("\n")
|
|
65
|
+
.slice(-OUTPUT_TAIL_LINES)
|
|
66
|
+
.join("\n");
|
|
67
|
+
const head = `${cmd} exited with code ${result.exitCode}`;
|
|
68
|
+
return output ? `${head}:\n${output}` : head;
|
|
69
|
+
}
|
|
70
|
+
|
|
33
71
|
/**
|
|
34
72
|
* Build the GitHub release asset name for the current platform.
|
|
35
73
|
* Defaults to `<binaryName>-<os>-<arch>[.exe]`, or delegates to `assetName`.
|
|
@@ -71,21 +109,20 @@ export async function upgradeWithPackageManager(
|
|
|
71
109
|
const result = await run(command, args);
|
|
72
110
|
return result.exitCode === 0
|
|
73
111
|
? { success: true }
|
|
74
|
-
: {
|
|
75
|
-
success: false,
|
|
76
|
-
error: `${command} exited with code ${result.exitCode}`,
|
|
77
|
-
};
|
|
112
|
+
: { success: false, error: describeFailure(command, args, result) };
|
|
78
113
|
}
|
|
79
114
|
|
|
80
115
|
/**
|
|
81
116
|
* Download the release binary for `latestVersion` and swap it into place at
|
|
82
117
|
* `process.execPath`, falling back to `sudo mv` when a plain move is denied.
|
|
118
|
+
* With `verify`, a binary that fails its release checks is never written.
|
|
83
119
|
*/
|
|
84
120
|
export async function upgradeFromBinary(opts: {
|
|
85
121
|
repo: string;
|
|
86
122
|
latestVersion: string;
|
|
87
123
|
binaryName: string;
|
|
88
124
|
assetName?: (target: AssetTarget) => string;
|
|
125
|
+
verify?: VerifyConfig;
|
|
89
126
|
fetchImpl?: FetchLike;
|
|
90
127
|
onProgress?: (message: string) => void;
|
|
91
128
|
}): Promise<InstallOutcome> {
|
|
@@ -96,14 +133,13 @@ export async function upgradeFromBinary(opts: {
|
|
|
96
133
|
binaryName: opts.binaryName,
|
|
97
134
|
assetName: opts.assetName,
|
|
98
135
|
});
|
|
99
|
-
const
|
|
100
|
-
const url = `https://github.com/${opts.repo}/releases/download/${tag}/${artifact}`;
|
|
136
|
+
const releaseUrl = `https://github.com/${opts.repo}/releases/download/v${opts.latestVersion}`;
|
|
101
137
|
|
|
102
138
|
const tmpPath = join(tmpdir(), `${opts.binaryName}-upgrade-${Date.now()}`);
|
|
103
139
|
const targetPath = process.execPath;
|
|
104
140
|
|
|
105
141
|
try {
|
|
106
|
-
const res = await doFetch(
|
|
142
|
+
const res = await doFetch(`${releaseUrl}/${artifact}`);
|
|
107
143
|
if (!res.ok) {
|
|
108
144
|
return {
|
|
109
145
|
success: false,
|
|
@@ -111,8 +147,17 @@ export async function upgradeFromBinary(opts: {
|
|
|
111
147
|
};
|
|
112
148
|
}
|
|
113
149
|
|
|
114
|
-
const bytes = await res.arrayBuffer();
|
|
115
|
-
|
|
150
|
+
const bytes = new Uint8Array(await res.arrayBuffer());
|
|
151
|
+
if (opts.verify) {
|
|
152
|
+
const problem = await releaseProblem({
|
|
153
|
+
config: opts.verify,
|
|
154
|
+
artifact,
|
|
155
|
+
binary: bytes,
|
|
156
|
+
download: (name) => doFetch(`${releaseUrl}/${name}`),
|
|
157
|
+
});
|
|
158
|
+
if (problem) return { success: false, error: problem };
|
|
159
|
+
}
|
|
160
|
+
await writeFile(tmpPath, bytes);
|
|
116
161
|
|
|
117
162
|
await chmod(tmpPath, 0o755);
|
|
118
163
|
|
|
@@ -122,11 +167,16 @@ export async function upgradeFromBinary(opts: {
|
|
|
122
167
|
if (mv.exitCode !== 0) {
|
|
123
168
|
// Fall back to sudo.
|
|
124
169
|
onProgress("Requires elevated permissions...");
|
|
125
|
-
const
|
|
170
|
+
const sudoArgs = ["mv", tmpPath, targetPath];
|
|
171
|
+
const sudo = await run("sudo", sudoArgs);
|
|
126
172
|
if (sudo.exitCode !== 0) {
|
|
173
|
+
await unlink(tmpPath).catch(() => {});
|
|
127
174
|
return {
|
|
128
175
|
success: false,
|
|
129
|
-
error:
|
|
176
|
+
error:
|
|
177
|
+
`Failed to install binary. Try running with sudo.\n` +
|
|
178
|
+
`${describeFailure("mv", [tmpPath, targetPath], mv)}\n` +
|
|
179
|
+
describeFailure("sudo", sudoArgs, sudo),
|
|
130
180
|
};
|
|
131
181
|
}
|
|
132
182
|
}
|
package/src/verify.ts
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { createHash, createPublicKey, verify } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
/** Checks a downloaded release binary must pass before it is installed. */
|
|
4
|
+
export interface VerifyConfig {
|
|
5
|
+
/** Release asset listing `<sha256> <file>` lines, e.g. `"SHA256SUMS"`. */
|
|
6
|
+
checksums: string;
|
|
7
|
+
/**
|
|
8
|
+
* minisign public key: the base64 line of a `minisign.pub` file (the whole
|
|
9
|
+
* file is accepted too). When set, the checksums asset must carry a valid
|
|
10
|
+
* minisign signature, published as `<checksums>.minisig`.
|
|
11
|
+
*/
|
|
12
|
+
publicKey?: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const TRUSTED_COMMENT = "trusted comment: ";
|
|
16
|
+
const CHECKSUM_LINE_RE = /^([0-9a-f]{64})\s+\*?(.+)$/i;
|
|
17
|
+
|
|
18
|
+
const decode = (line: string | undefined) =>
|
|
19
|
+
Buffer.from(line?.trim() ?? "", "base64");
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Whether `minisig` (the contents of a `.minisig` file) is a valid minisign
|
|
23
|
+
* signature of `data` by `publicKey`. Accepts both the prehashed (`ED`) and
|
|
24
|
+
* legacy (`Ed`) algorithms, and checks the key ID and the global signature
|
|
25
|
+
* over the trusted comment.
|
|
26
|
+
*/
|
|
27
|
+
export function verifyMinisign(
|
|
28
|
+
data: Uint8Array,
|
|
29
|
+
minisig: string,
|
|
30
|
+
publicKey: string,
|
|
31
|
+
): boolean {
|
|
32
|
+
// .pub: untrusted comment, then "Ed" + key ID (8) + Ed25519 key (32).
|
|
33
|
+
const pub = decode(publicKey.trim().split("\n").at(-1));
|
|
34
|
+
// .minisig: untrusted comment, algorithm + key ID (8) + signature (64),
|
|
35
|
+
// trusted comment, then the signature over signature + trusted comment.
|
|
36
|
+
const [, sigLine, trustedLine = "", globalLine] = minisig.split(/\r?\n/);
|
|
37
|
+
const sig = decode(sigLine);
|
|
38
|
+
const global = decode(globalLine);
|
|
39
|
+
if (
|
|
40
|
+
pub.length !== 42 ||
|
|
41
|
+
sig.length !== 74 ||
|
|
42
|
+
global.length !== 64 ||
|
|
43
|
+
pub.subarray(0, 2).toString("latin1") !== "Ed" ||
|
|
44
|
+
!sig.subarray(2, 10).equals(pub.subarray(2, 10)) ||
|
|
45
|
+
!trustedLine.startsWith(TRUSTED_COMMENT)
|
|
46
|
+
) {
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
const algorithm = sig.subarray(0, 2).toString("latin1");
|
|
50
|
+
if (algorithm !== "ED" && algorithm !== "Ed") return false;
|
|
51
|
+
|
|
52
|
+
const key = createPublicKey({
|
|
53
|
+
key: {
|
|
54
|
+
kty: "OKP",
|
|
55
|
+
crv: "Ed25519",
|
|
56
|
+
x: pub.subarray(10).toString("base64url"),
|
|
57
|
+
},
|
|
58
|
+
format: "jwk",
|
|
59
|
+
});
|
|
60
|
+
const signature = sig.subarray(10);
|
|
61
|
+
const message =
|
|
62
|
+
algorithm === "ED" ? createHash("blake2b512").update(data).digest() : data;
|
|
63
|
+
const trusted = Buffer.from(trustedLine.slice(TRUSTED_COMMENT.length));
|
|
64
|
+
return (
|
|
65
|
+
verify(null, message, key, signature) &&
|
|
66
|
+
verify(null, Buffer.concat([signature, trusted]), key, global)
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The SHA-256 a checksum file lists for `name`, lowercased. */
|
|
71
|
+
function listedChecksum(checksums: string, name: string): string | undefined {
|
|
72
|
+
for (const line of checksums.split(/\r?\n/)) {
|
|
73
|
+
const match = CHECKSUM_LINE_RE.exec(line.trim());
|
|
74
|
+
if (match?.[2] === name) return match[1]?.toLowerCase();
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Why `binary`, the release asset named `artifact`, fails `config`'s checks,
|
|
80
|
+
* or `undefined` when it passes. `download` fetches another asset of the same
|
|
81
|
+
* release by name.
|
|
82
|
+
*/
|
|
83
|
+
export async function releaseProblem(opts: {
|
|
84
|
+
config: VerifyConfig;
|
|
85
|
+
artifact: string;
|
|
86
|
+
binary: Uint8Array;
|
|
87
|
+
download: (name: string) => Promise<Response>;
|
|
88
|
+
}): Promise<string | undefined> {
|
|
89
|
+
const { checksums, publicKey } = opts.config;
|
|
90
|
+
const names = publicKey ? [checksums, `${checksums}.minisig`] : [checksums];
|
|
91
|
+
const responses = await Promise.all(names.map(opts.download));
|
|
92
|
+
const failed = responses.findIndex((res) => !res.ok);
|
|
93
|
+
if (failed !== -1) {
|
|
94
|
+
return `Failed to download ${names[failed]}: HTTP ${responses[failed]?.status}`;
|
|
95
|
+
}
|
|
96
|
+
const [sums, minisig] = await Promise.all(
|
|
97
|
+
responses.map((res) => res.arrayBuffer()),
|
|
98
|
+
);
|
|
99
|
+
const sumsBytes = new Uint8Array(sums ?? new ArrayBuffer(0));
|
|
100
|
+
|
|
101
|
+
if (
|
|
102
|
+
publicKey &&
|
|
103
|
+
!verifyMinisign(sumsBytes, new TextDecoder().decode(minisig), publicKey)
|
|
104
|
+
) {
|
|
105
|
+
return `${checksums} is not signed by the configured public key`;
|
|
106
|
+
}
|
|
107
|
+
const expected = listedChecksum(
|
|
108
|
+
new TextDecoder().decode(sumsBytes),
|
|
109
|
+
opts.artifact,
|
|
110
|
+
);
|
|
111
|
+
if (!expected) return `${checksums} does not list ${opts.artifact}`;
|
|
112
|
+
const actual = createHash("sha256").update(opts.binary).digest("hex");
|
|
113
|
+
return actual === expected
|
|
114
|
+
? undefined
|
|
115
|
+
: `Checksum mismatch for ${opts.artifact}`;
|
|
116
|
+
}
|