upgradr 0.4.1 → 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 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
@@ -79,6 +79,7 @@ export function createUpdater(config) {
79
79
  latestVersion: info.latestVersion,
80
80
  binaryName: cfg.binaryName,
81
81
  assetName: cfg.assetName,
82
+ verify: cfg.verify,
82
83
  fetchImpl: cfg.fetchImpl,
83
84
  onProgress: cfg.onProgress,
84
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,6 +3,7 @@ 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);
7
8
  /** Max number of trailing output lines kept in an error message. */
8
9
  const OUTPUT_TAIL_LINES = 10;
@@ -76,6 +77,7 @@ export async function upgradeWithPackageManager(command, args) {
76
77
  /**
77
78
  * Download the release binary for `latestVersion` and swap it into place at
78
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.
79
81
  */
80
82
  export async function upgradeFromBinary(opts) {
81
83
  const doFetch = opts.fetchImpl ?? fetch;
@@ -84,20 +86,29 @@ export async function upgradeFromBinary(opts) {
84
86
  binaryName: opts.binaryName,
85
87
  assetName: opts.assetName,
86
88
  });
87
- const tag = `v${opts.latestVersion}`;
88
- const url = `https://github.com/${opts.repo}/releases/download/${tag}/${artifact}`;
89
+ const releaseUrl = `https://github.com/${opts.repo}/releases/download/v${opts.latestVersion}`;
89
90
  const tmpPath = join(tmpdir(), `${opts.binaryName}-upgrade-${Date.now()}`);
90
91
  const targetPath = process.execPath;
91
92
  try {
92
- const res = await doFetch(url);
93
+ const res = await doFetch(`${releaseUrl}/${artifact}`);
93
94
  if (!res.ok) {
94
95
  return {
95
96
  success: false,
96
97
  error: `Failed to download binary: HTTP ${res.status}`,
97
98
  };
98
99
  }
99
- const bytes = await res.arrayBuffer();
100
- await writeFile(tmpPath, Buffer.from(bytes));
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);
101
112
  await chmod(tmpPath, 0o755);
102
113
  // Try to move into place (mv handles cross-filesystem moves).
103
114
  const mv = await run("mv", [tmpPath, targetPath]);
@@ -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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "upgradr",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
4
4
  "description": "Self-update for Bun & Node CLIs: check npm for a newer release, then upgrade in place via npm/bun or a GitHub release binary.",
5
5
  "type": "module",
6
6
  "license": "MIT",
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 {
@@ -178,6 +179,7 @@ export function createUpdater(config: UpdaterConfig): Updater {
178
179
  latestVersion: info.latestVersion,
179
180
  binaryName: cfg.binaryName,
180
181
  assetName: cfg.assetName,
182
+ verify: cfg.verify,
181
183
  fetchImpl: cfg.fetchImpl,
182
184
  onProgress: cfg.onProgress,
183
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
 
@@ -114,12 +115,14 @@ export async function upgradeWithPackageManager(
114
115
  /**
115
116
  * Download the release binary for `latestVersion` and swap it into place at
116
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.
117
119
  */
118
120
  export async function upgradeFromBinary(opts: {
119
121
  repo: string;
120
122
  latestVersion: string;
121
123
  binaryName: string;
122
124
  assetName?: (target: AssetTarget) => string;
125
+ verify?: VerifyConfig;
123
126
  fetchImpl?: FetchLike;
124
127
  onProgress?: (message: string) => void;
125
128
  }): Promise<InstallOutcome> {
@@ -130,14 +133,13 @@ export async function upgradeFromBinary(opts: {
130
133
  binaryName: opts.binaryName,
131
134
  assetName: opts.assetName,
132
135
  });
133
- const tag = `v${opts.latestVersion}`;
134
- const url = `https://github.com/${opts.repo}/releases/download/${tag}/${artifact}`;
136
+ const releaseUrl = `https://github.com/${opts.repo}/releases/download/v${opts.latestVersion}`;
135
137
 
136
138
  const tmpPath = join(tmpdir(), `${opts.binaryName}-upgrade-${Date.now()}`);
137
139
  const targetPath = process.execPath;
138
140
 
139
141
  try {
140
- const res = await doFetch(url);
142
+ const res = await doFetch(`${releaseUrl}/${artifact}`);
141
143
  if (!res.ok) {
142
144
  return {
143
145
  success: false,
@@ -145,8 +147,17 @@ export async function upgradeFromBinary(opts: {
145
147
  };
146
148
  }
147
149
 
148
- const bytes = await res.arrayBuffer();
149
- await writeFile(tmpPath, Buffer.from(bytes));
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);
150
161
 
151
162
  await chmod(tmpPath, 0o755);
152
163
 
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
+ }