Repository navigation
Expand file tree
/
Copy pathverify-bundle.ts
More file actions
698 lines (654 loc) · 23.2 KB
/
Copy pathverify-bundle.ts
File metadata and controls
698 lines (654 loc) · 23.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
// Checks a built installer before it is published: the notices are in it,
// every bundled GPL component has resolvable source for its exact package,
// the eSpeak NG data matches its recorded provenance, and the packaged
// eSpeak NG runs.
//
// usage: bun scripts/release/verify-bundle.ts <artifact>... [--sources <asset>]
// [--appimage-sources <asset>]
// <artifact> a .app directory, a .dmg, the updater .app.tar.gz, a .deb,
// an .rpm, an .AppImage, a Windows NSIS .exe or .msi, or a
// directory that holds the app's resources
// --sources the gpl-sources release asset of the same build (a .tar, or
// the directory it was packed from). SOURCE.txt in every
// installer must point at it. Without it, each source URL
// must answer instead.
// --appimage-sources the appimage-sources release asset of the same
// build, required when an .AppImage is verified
// --notices the THIRD-PARTY-NOTICES.txt the build generated: every
// installer must carry an identical copy
import { createHash } from "node:crypto";
import { gunzipSync, inflateRawSync } from "node:zlib";
import {
existsSync,
lstatSync,
mkdtempSync,
readdirSync,
readFileSync,
statSync,
} from "node:fs";
import { tmpdir } from "node:os";
import * as nodePath from "node:path";
import { basename, join, resolve } from "node:path";
import { checkAppImage } from "../ci/gpl/appimage";
import {
checkCoverage,
espeakDataSource,
licenseFiles,
type DataSource,
type Provenance,
} from "../ci/gpl/lib";
const root = resolve(import.meta.dir, "../..");
export class VerifyError extends Error {}
function check(ok: boolean, message: string) {
if (!ok) throw new VerifyError(message);
}
/** Directory holding espeak-ng-data inside an unpacked artifact. Symlinks
* are not followed (a DMG links /Applications). */
export function findResources(dir: string, depth = 0): string | null {
if (depth > 8 || !existsSync(dir) || !lstatSync(dir).isDirectory())
return null;
const entries = readdirSync(dir);
if (entries.includes("espeak-ng-data") && entries.includes("espeak-ng"))
return dir;
for (const entry of entries) {
const found = findResources(join(dir, entry), depth + 1);
if (found) return found;
}
return null;
}
function spawn(cmd: string[], cwd?: string) {
const result = Bun.spawnSync(cmd, { cwd, stderr: "pipe" });
check(
result.exitCode === 0,
`${cmd.join(" ")} failed: ${result.stderr.toString()}`,
);
}
/** Whether `artifact` is a macOS bundle or carries one. */
export function isMacArtifact(artifact: string): boolean {
return /\.(app|dmg|app\.tar\.gz)\/?$/.test(artifact);
}
/** The .app in an unpacked macOS artifact: `dir` itself, or a .app directly
* in it (the root of a .dmg or of the updater archive). */
export function findApp(dir: string): string | null {
if (dir.replace(/\/+$/, "").endsWith(".app")) return dir;
const apps = readdirSync(dir).filter(
(entry) =>
entry.endsWith(".app") && lstatSync(join(dir, entry)).isDirectory(),
);
return apps.length === 1 ? join(dir, apps[0]) : null;
}
/** The .app in an unpacked macOS artifact. The updater installs every
* member of its archive under the app (it strips the first path
* component), so that archive must hold the .app and nothing else. */
export function macApp(artifact: string, dir: string): string {
const app = findApp(dir);
if (!app) throw new VerifyError(`no single .app found in ${artifact}`);
if (artifact.endsWith(".app.tar.gz")) {
const roots = readdirSync(dir);
check(
roots.length === 1,
`${artifact} holds ${roots.join(", ")}: the updater archive must hold only the .app`,
);
checkSingleGzipMember(artifact);
checkUpdaterMembers(artifact, basename(app));
}
return app;
}
/** The updater archive is one gzip member and nothing after it. The
* updater (tauri-plugin-updater, flate2's GzDecoder) reads only the first
* member, while tar reads every one: with a second member the check would
* see files the installed app does not get. */
export function checkSingleGzipMember(archive: string) {
const bytes = readFileSync(archive);
const refuse = (why: string) =>
new VerifyError(`${archive} is not a single gzip member: ${why}`);
if (bytes.length < 18 || bytes[0] !== 0x1f || bytes[1] !== 0x8b)
throw refuse("no gzip header");
if (bytes[2] !== 8) throw refuse("not deflate");
// RFC 1952: the fixed header, then the optional fields its flags name.
const flags = bytes[3];
let at = 10;
if (flags & 0x04) at += 2 + bytes.readUInt16LE(at);
const skipString = () => {
const end = bytes.indexOf(0, at);
if (end < 0) throw refuse("header cut short");
at = end + 1;
};
if (flags & 0x08) skipString();
if (flags & 0x10) skipString();
if (flags & 0x02) at += 2;
let consumed: number;
try {
const result = inflateRawSync(bytes.subarray(at), {
info: true,
} as never) as unknown as { engine: { bytesWritten: number } };
consumed = result.engine.bytesWritten;
} catch (error) {
throw refuse(`does not inflate (${error})`);
}
// The 8-byte trailer (CRC-32 and size) ends the file.
const end = at + consumed + 8;
if (end !== bytes.length)
throw refuse(
end > bytes.length
? "cut short"
: `${bytes.length - end} bytes follow the first member`,
);
// zlib checks the header and trailer checksums and the size, as the
// updater's decoder does.
try {
gunzipSync(bytes);
} catch (error) {
throw refuse(`${error}`);
}
}
/** Every member of the updater archive is the .app or under it, named as
* the updater reads it: it drops the first path component, so a member
* named `./x.app/Contents` would install `x.app/Contents` inside the app. */
export function checkUpdaterMembers(archive: string, appName: string) {
const listed = Bun.spawnSync(["tar", "-tzf", resolve(archive)], {
stderr: "pipe",
stdout: "pipe",
});
check(
listed.exitCode === 0,
`tar -tzf ${archive} failed: ${listed.stderr.toString()}`,
);
const members = listed.stdout.toString().split("\n").filter(Boolean);
const stray = members.filter(
(m) => m !== appName && m !== `${appName}/` && !m.startsWith(`${appName}/`),
);
check(
members.length > 0 && stray.length === 0,
`${archive} has members outside ${appName}/: ${stray.slice(0, 3).join(", ")}`,
);
}
export type CodesignRunner = (cmd: string[]) => {
exitCode: number;
stderr: string;
};
const runCodesign: CodesignRunner = (cmd) => {
const result = Bun.spawnSync(cmd, { stderr: "pipe", stdout: "pipe" });
return { exitCode: result.exitCode ?? 1, stderr: result.stderr.toString() };
};
/** The .app's signature is valid and seals the whole bundle, nested code
* included. */
export function checkMacSignature(
app: string,
run: CodesignRunner = runCodesign,
) {
const result = run(["codesign", "--verify", "--deep", "--strict", app]);
check(
result.exitCode === 0,
`${app} is not properly signed (codesign --verify --deep --strict): ${result.stderr.trim()}`,
);
}
/** Libraries the app's executables load through @rpath, from `otool -L`. */
export function rpathLibraries(otoolOutput: string): string[] {
return otoolOutput
.split("\n")
.map((line) => line.trim().match(/^@rpath\/(\S+)/)?.[1])
.filter((name): name is string => !!name);
}
function toolOutput(cmd: string[]): string {
const result = Bun.spawnSync(cmd, { stdout: "pipe", stderr: "pipe" });
check(
result.exitCode === 0,
`${cmd.join(" ")} failed: ${result.stderr.toString()}`,
);
return result.stdout.toString();
}
/** The run paths (LC_RPATH) in `otool -l` output. */
export function rpaths(loadCommands: string): string[] {
const paths: string[] = [];
let inRpath = false;
for (const line of loadCommands.split("\n")) {
const cmd = line.match(/^\s*cmd (\S+)/);
if (cmd) inRpath = cmd[1] === "LC_RPATH";
const path = inRpath && line.match(/^\s*path (.+) \(offset \d+\)$/);
if (path) paths.push(path[1]);
}
return paths;
}
export interface MachoTools {
/** `otool -L` of a file. */
libraries: (file: string) => string;
/** `otool -l` of a file. */
loadCommands: (file: string) => string;
/** `lipo -archs` of a file. */
archs: (file: string) => string;
}
const machoTools: MachoTools = {
// Every slice of a universal binary, not only the host's.
libraries: (file) => toolOutput(["otool", "-arch", "all", "-L", file]),
loadCommands: (file) => toolOutput(["otool", "-arch", "all", "-l", file]),
archs: (file) => toolOutput(["lipo", "-archs", file]).trim(),
};
/** Every library the executables load through @rpath (the Intel build's
* ONNX Runtime) is found through one of their run paths, the way dyld
* looks for it: a missing one stops the app at launch. */
export function checkRpathLibraries(
app: string,
tools: MachoTools = machoTools,
) {
const macos = join(app, "Contents", "MacOS");
for (const exe of readdirSync(macos)) {
const file = join(macos, exe);
const libs = rpathLibraries(tools.libraries(file));
if (libs.length === 0) continue;
const paths = rpaths(tools.loadCommands(file));
const dirs = paths.map((p) =>
p.replace(/^@(executable|loader)_path/, macos),
);
const exeArchs = tools.archs(file).split(" ");
for (const lib of libs) {
const found = dirs
.map((dir) => join(dir, lib))
.find((path) => existsSync(path));
check(
!!found,
`${exe} loads @rpath/${lib}, which none of its run paths (${paths.join(", ") || "none"}) holds`,
);
// dyld refuses a library without the executable's architectures.
const libArchs = tools.archs(found!).split(" ");
const missing = exeArchs.filter((a) => !libArchs.includes(a));
check(
missing.length === 0,
`${lib} is ${libArchs.join(" ")}, but ${exe} is ${exeArchs.join(" ")}`,
);
}
}
}
/** The minimum macOS in `otool -l` output (LC_BUILD_VERSION, or
* LC_VERSION_MIN_MACOSX in older binaries). */
export function machoMinos(loadCommands: string): string | null {
// A universal binary lists every slice: the highest one counts.
let cmd = "";
let highest: string | null = null;
for (const line of loadCommands.split("\n")) {
const c = line.match(/^\s*cmd (\S+)/);
if (c) cmd = c[1];
const v =
cmd === "LC_BUILD_VERSION"
? line.match(/^\s*minos (\S+)/)
: cmd === "LC_VERSION_MIN_MACOSX"
? line.match(/^\s*version (\S+)/)
: null;
if (v && (highest === null || compareMacos(v[1], highest) > 0))
highest = v[1];
}
return highest;
}
/** Compares two macOS versions ("13", "13.4", "10.13"). */
export function compareMacos(a: string, b: string): number {
const pa = a.split(".").map(Number);
const pb = b.split(".").map(Number);
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
const d = (pa[i] ?? 0) - (pb[i] ?? 0);
if (d !== 0) return d;
}
return 0;
}
const MACHO_MAGIC = new Set([
"cffaedfe", // 64-bit, little endian
"cefaedfe", // 32-bit, little endian
"cafebabe", // universal
]);
function isMacho(file: string): boolean {
const fd = Bun.file(file);
if (fd.size < 4) return false;
const head = new Uint8Array(readFileSync(file).subarray(0, 4));
return MACHO_MAGIC.has(Buffer.from(head).toString("hex"));
}
// Sorted, so the error lists the files in the same order on every file
// system (ext4 returns directory entries in hash order).
function machoFiles(dir: string): string[] {
return readdirSync(dir)
.sort()
.flatMap((entry) => {
const path = join(dir, entry);
const stat = lstatSync(path);
if (stat.isSymbolicLink()) return [];
if (stat.isDirectory()) return machoFiles(path);
return stat.isFile() && isMacho(path) ? [path] : [];
});
}
/** No binary in the app (its executables, Contents/Frameworks, the
* espeak-ng it runs) needs a newer macOS than LSMinimumSystemVersion: one
* that does fails to load on the macOS versions in between. */
export function checkMinimumMacos(
app: string,
tools: { minimum: (app: string) => string } & Pick<
MachoTools,
"loadCommands"
> = {
minimum: (a) =>
toolOutput([
"plutil",
"-extract",
"LSMinimumSystemVersion",
"raw",
join(a, "Contents", "Info.plist"),
]).trim(),
loadCommands: machoTools.loadCommands,
},
) {
const promised = tools.minimum(app);
const problems: string[] = [];
for (const file of machoFiles(join(app, "Contents"))) {
const minos = machoMinos(tools.loadCommands(file));
if (minos === null) problems.push(`${basename(file)} has no minimum macOS`);
else if (compareMacos(minos, promised) > 0)
problems.push(`${basename(file)} needs macOS ${minos}`);
}
check(
problems.length === 0,
`${problems.join(", ")}, the app promises ${promised} (LSMinimumSystemVersion)`,
);
}
/** The tar command that extracts `archive` into `out`. On Windows it is the
* system bsdtar: the GNU tar that Git Bash puts first on PATH reads a drive
* letter as a remote host in `-f D:\\...` and mangles `-C C:\\...` when a
* native process calls it. */
export function tarExtract(
archive: string,
out: string,
gzip: boolean,
platform: NodeJS.Platform = process.platform,
systemRoot: string = process.env.SystemRoot ?? "C:\\Windows",
): string[] {
const tar =
platform === "win32"
? nodePath.win32.join(systemRoot, "System32", "tar.exe")
: "tar";
return [tar, gzip ? "-xzf" : "-xf", archive, "-C", out];
}
/** Unpacks an installer the way a recipient would get its files. */
export function unpack(artifact: string): {
dir: string;
cleanup: () => void;
} {
const none = () => {};
if (statSync(artifact).isDirectory()) return { dir: artifact, cleanup: none };
const out = mkdtempSync(join(tmpdir(), "verify-bundle-"));
const path = resolve(artifact);
if (path.endsWith(".deb")) spawn(["dpkg-deb", "-x", path, out]);
else if (path.endsWith(".rpm")) spawn(["bsdtar", "-xf", path, "-C", out]);
else if (path.endsWith(".tar") || path.endsWith(".tar.gz")) {
spawn(tarExtract(path, out, path.endsWith(".tar.gz")));
} else if (path.endsWith(".AppImage")) {
spawn(["chmod", "+x", path]);
spawn([path, "--appimage-extract"], out);
} else if (path.endsWith(".dmg")) {
spawn([
"hdiutil",
"attach",
"-nobrowse",
"-readonly",
"-mountpoint",
out,
path,
]);
return {
dir: out,
cleanup: () => spawn(["hdiutil", "detach", out, "-force"]),
};
} else if (path.endsWith(".msi")) {
// An administrative install extracts the files under their real names
// (7z would give the MSI's internal file keys).
spawn(["msiexec", "/a", path, "/qn", `TARGETDIR=${out}`]);
} else spawn(["7z", "x", "-y", `-o${out}`, path]);
return { dir: out, cleanup: none };
}
/** A release asset given as its .tar or as the directory it was packed
* from, unpacked, with the asset's file name. */
export function openAsset(path: string): { dir: string; asset: string } {
const asset = basename(path);
return { dir: unpack(path).dir, asset };
}
/** SHA256SUMS lines ("<sha256> <file>"), LF or CRLF. */
export function parseSums(text: string): Array<[string, string]> {
return text
.split(/\r?\n/)
.filter((line) => line.trim().length > 0)
.map((line) => [line.slice(0, 64), line.slice(66)]);
}
function digestOf(path: string, algo: string): string {
return createHash(algo).update(readFileSync(path)).digest("hex");
}
export interface VerifyOptions {
/** The THIRD-PARTY-NOTICES.txt the build generated: the installed copy
* must be identical. */
notices?: string;
/** The unpacked gpl-sources asset. */
sources?: string;
/** Its asset name, when `sources` is not named after it. */
sourcesAsset?: string;
/** The pinned eSpeak NG data source (overridable in tests). */
dataSource?: DataSource;
/** Checks a source URL answers (overridable in tests). */
resolvable?: (url: string) => Promise<boolean>;
/** Runs the packaged eSpeak NG (overridable in tests). */
run?: (
cmd: string[],
env: Record<string, string>,
) => { code: number; out: string };
}
async function urlAnswers(url: string): Promise<boolean> {
const response = await fetch(url, { method: "HEAD", redirect: "follow" });
return response.ok;
}
function runCommand(cmd: string[], env: Record<string, string>) {
const result = Bun.spawnSync(cmd, {
env: { ...process.env, ...env },
stderr: "pipe",
});
return { code: result.exitCode ?? 1, out: result.stdout.toString() };
}
export async function verifyResources(
resources: string,
options: VerifyOptions = {},
) {
const notices = join(resources, "THIRD-PARTY-NOTICES.txt");
check(existsSync(notices), "THIRD-PARTY-NOTICES.txt is missing");
const text = readFileSync(notices, "utf8");
for (const needle of [
"ONNX Runtime",
"MPL-2.0 crates",
"eSpeak NG data",
"Rust crates",
]) {
check(
text.includes(needle),
`THIRD-PARTY-NOTICES.txt has no ${needle} section`,
);
}
// The app's own MIT notice (Parrot and Handy) is in it, in full.
check(
text.includes(readFileSync(join(root, "LICENSE"), "utf8")),
"THIRD-PARTY-NOTICES.txt does not carry the app's LICENSE in full",
);
if (options.notices) {
check(
text === readFileSync(options.notices, "utf8"),
`THIRD-PARTY-NOTICES.txt differs from the generated ${options.notices}`,
);
}
// The eSpeak NG data is exactly what licenses/espeak-ng-data records.
const data = join(resources, "espeak-ng-data");
const sums = parseSums(
readFileSync(join(root, "licenses/espeak-ng-data/SHA256SUMS"), "utf8"),
);
for (const [sum, file] of sums) {
const path = join(data, file);
check(existsSync(path), `espeak-ng-data/${file} is missing`);
check(
digestOf(path, "sha256") === sum,
`espeak-ng-data/${file} differs from its provenance`,
);
}
const espeak = join(resources, "espeak-ng");
for (const file of ["COPYING", "SOURCE.txt", "PROVENANCE.json"]) {
check(existsSync(join(espeak, file)), `espeak-ng/${file} is missing`);
}
const provenance: Provenance = JSON.parse(
readFileSync(join(espeak, "PROVENANCE.json"), "utf8"),
);
checkCoverage(readdirSync(espeak), provenance);
// Every license text that applies, byte for byte the one in licenses/.
for (const [from, to] of licenseFiles(provenance)) {
const path = join(espeak, to);
check(existsSync(path), `espeak-ng/${to} is missing`);
check(
readFileSync(path).equals(readFileSync(join(root, "licenses", from))),
`espeak-ng/${to} differs from licenses/${from}`,
);
}
// Every source archive, the data's included, is in this build's release
// asset, which SOURCE.txt points at. Without the asset, each URL answers.
const resolvable = options.resolvable ?? urlAnswers;
const wanted = [
...provenance.components.flatMap((c) => c.sources),
options.dataSource ?? espeakDataSource(),
];
if (options.sources) {
const asset = options.sourcesAsset ?? basename(options.sources);
const sourceText = readFileSync(join(espeak, "SOURCE.txt"), "utf8");
check(
sourceText.includes(`/${asset}`),
`espeak-ng/SOURCE.txt does not point at the release asset ${asset}`,
);
for (const source of wanted) {
const path = join(options.sources, source.file);
check(existsSync(path), `${asset} has no ${source.file}`);
const [algo, expected] = source.digest.split(":");
check(
digestOf(path, algo) === expected,
`${asset}/${source.file} has the wrong ${algo}`,
);
}
} else {
for (const source of wanted) {
check(await resolvable(source.url), `${source.url} does not answer`);
}
}
// The packaged eSpeak NG runs and turns pt-BR text into phonemes.
const binary = ["espeak-ng", "espeak-ng.exe"]
.map((b) => join(espeak, b))
.find(existsSync);
check(!!binary, "the packaged espeak-ng is missing");
const run = options.run ?? runCommand;
const result = run(
[
binary!,
`--path=${resources}`,
"-q",
"-x",
"-v",
"pt-br",
"teste de leitura",
],
{
LD_LIBRARY_PATH: espeak,
},
);
check(
result.code === 0 && result.out.trim().length > 0,
"the packaged espeak-ng did not run",
);
}
export interface Args {
artifacts: string[];
sources?: string;
appimageSources?: string;
notices?: string;
}
const VALUE_FLAGS = {
"--sources": "sources",
"--appimage-sources": "appimageSources",
"--notices": "notices",
} as const;
const USAGE =
"usage: verify-bundle.ts <artifact>... [--sources <asset>] [--appimage-sources <asset>] [--notices <generated file>]";
export function parseArgs(argv: string[]): Args {
const args: Args = { artifacts: [] };
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg in VALUE_FLAGS) {
const value = argv[i + 1];
if (value === undefined || value.startsWith("--")) {
throw new VerifyError(`${arg} needs a value. ${USAGE}`);
}
args[VALUE_FLAGS[arg as keyof typeof VALUE_FLAGS]] = value;
i++;
} else if (arg.startsWith("--")) {
throw new VerifyError(`unknown option ${arg}. ${USAGE}`);
} else {
args.artifacts.push(arg);
}
}
if (args.artifacts.length === 0) throw new VerifyError(USAGE);
return args;
}
if (import.meta.main) {
const args = parseArgs(process.argv.slice(2));
if (
args.artifacts.some((a) => a.endsWith(".AppImage")) &&
!args.appimageSources
) {
throw new VerifyError(
"an .AppImage needs --appimage-sources <asset> (its libraries' sources)",
);
}
const sources = args.sources ? openAsset(args.sources) : undefined;
const appimageSources = args.appimageSources
? openAsset(args.appimageSources)
: undefined;
const offline = process.env.VERIFY_BUNDLE_OFFLINE === "1";
for (const artifact of args.artifacts) {
const { dir, cleanup } = unpack(artifact);
let failed = false;
try {
// On macOS, the signature is checked on the .app the person gets, and
// the resources are read from that same .app.
let root = dir;
if (isMacArtifact(artifact)) {
const app = macApp(artifact, dir);
checkMacSignature(app);
checkRpathLibraries(app);
checkMinimumMacos(app);
root = app;
}
const resources = findResources(root);
if (!resources)
throw new VerifyError(`no app resources found in ${artifact}`);
await verifyResources(resources, {
notices: args.notices,
sources: sources?.dir,
sourcesAsset: sources?.asset,
...(offline ? { resolvable: async () => false } : {}),
});
if (artifact.endsWith(".AppImage")) {
checkAppImage(
join(dir, "squashfs-root"),
appimageSources!.dir,
appimageSources!.asset,
);
}
} catch (error) {
failed = true;
throw error;
} finally {
// A failed detach must not hide why the artifact was refused.
try {
cleanup();
} catch (error) {
if (!failed) throw error;
console.error(`cleanup of ${artifact} failed: ${error}`);
}
}
console.log(
`${artifact}: notices, provenance, sources and espeak-ng verified${isMacArtifact(artifact) ? ", signature sealed" : ""}`,
);
}
}