akanjs 3.3.0 → 3.4.0-rc.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.
Files changed (62) hide show
  1. package/common/PipelinePlanSchema.ts +31 -7
  2. package/common/index.ts +6 -0
  3. package/common/pipelinePlan.ts +31 -5
  4. package/index.ts +7 -5
  5. package/package.json +1 -1
  6. package/pipelineConfig.ts +25 -2
  7. package/service/agentLoop/agentLoop.ts +19 -12
  8. package/service/predefinedAdaptor/anthropicTools.ts +8 -2
  9. package/types/common/index.d.ts +1 -1
  10. package/types/common/pipelinePlan.d.ts +35 -6
  11. package/types/index.d.ts +7 -5
  12. package/types/pipelineConfig.d.ts +20 -3
  13. package/types/server/logging/rotatingLogWriter.d.ts +1 -1
  14. package/types/service/predefinedAdaptor/anthropicTools.d.ts +1 -0
  15. package/types/vendor/@akanjs/native/packages/cli/src/api-updates.d.ts +149 -0
  16. package/types/vendor/@akanjs/native/packages/cli/src/api.d.ts +16 -162
  17. package/types/vendor/@akanjs/native/packages/cli/src/config.d.ts +3 -2
  18. package/types/vendor/@akanjs/native/packages/cli/src/lib/api-task.d.ts +79 -0
  19. package/types/vendor/@akanjs/native/packages/cli/src/lib/prepare.d.ts +1 -1
  20. package/types/vendor/@akanjs/native/packages/cli/src/lib/publish.d.ts +17 -5
  21. package/types/vendor/@akanjs/native/packages/cli/src/lib/updates.d.ts +29 -2
  22. package/types/vendor/@akanjs/native/packages/cli/src/platforms/desktop-update.d.ts +36 -0
  23. package/types/vendor/@akanjs/native/packages/cli/src/platforms/linux-install.d.ts +15 -0
  24. package/types/vendor/@akanjs/native/packages/core/src/kernel.d.ts +16 -5
  25. package/types/vendor/@akanjs/native/packages/desktop/src/commands.d.ts +81 -0
  26. package/types/vendor/@akanjs/native/packages/desktop/src/deeplinks.d.ts +5 -1
  27. package/types/vendor/@akanjs/native/packages/desktop/src/dispatcher.d.ts +3 -0
  28. package/types/vendor/@akanjs/native/packages/desktop/src/lifecycle.d.ts +8 -1
  29. package/types/vendor/@akanjs/native/packages/desktop/src/plugin.d.ts +21 -0
  30. package/types/vendor/@akanjs/native/packages/desktop/src/server.d.ts +1 -0
  31. package/types/vendor/@akanjs/native/plugins/updates/src/desktop.d.ts +4 -4
  32. package/types/vendor/@akanjs/native/plugins/updates/src/reports.d.ts +49 -0
  33. package/types/vendor/@akanjs/native/plugins/updates/src/signer.d.ts +21 -0
  34. package/types/vendor/@akanjs/native/plugins/window/src/index.d.ts +55 -3
  35. package/vendor/@akanjs/native/native/desktop/src/lib.rs +209 -54
  36. package/vendor/@akanjs/native/packages/cli/src/api-updates.ts +332 -0
  37. package/vendor/@akanjs/native/packages/cli/src/api.ts +67 -419
  38. package/vendor/@akanjs/native/packages/cli/src/commands/build.ts +4 -1
  39. package/vendor/@akanjs/native/packages/cli/src/config.ts +3 -2
  40. package/vendor/@akanjs/native/packages/cli/src/lib/api-task.ts +223 -0
  41. package/vendor/@akanjs/native/packages/cli/src/lib/prepare.ts +2 -7
  42. package/vendor/@akanjs/native/packages/cli/src/lib/publish.ts +164 -19
  43. package/vendor/@akanjs/native/packages/cli/src/lib/updates.ts +90 -3
  44. package/vendor/@akanjs/native/packages/cli/src/platforms/desktop-update.ts +195 -43
  45. package/vendor/@akanjs/native/packages/cli/src/platforms/linux-appimage.ts +1 -1
  46. package/vendor/@akanjs/native/packages/cli/src/platforms/linux-install.ts +206 -0
  47. package/vendor/@akanjs/native/packages/cli/src/platforms/linux.ts +5 -1
  48. package/vendor/@akanjs/native/packages/core/src/kernel.ts +21 -6
  49. package/vendor/@akanjs/native/packages/core/vectors/updates.json +2 -1
  50. package/vendor/@akanjs/native/packages/desktop/src/commands.ts +380 -0
  51. package/vendor/@akanjs/native/packages/desktop/src/deeplinks.ts +20 -3
  52. package/vendor/@akanjs/native/packages/desktop/src/dispatcher.ts +28 -13
  53. package/vendor/@akanjs/native/packages/desktop/src/host.ts +6 -18
  54. package/vendor/@akanjs/native/packages/desktop/src/lifecycle.ts +8 -1
  55. package/vendor/@akanjs/native/packages/desktop/src/plugin.ts +21 -0
  56. package/vendor/@akanjs/native/packages/desktop/src/server.ts +1 -1
  57. package/vendor/@akanjs/native/plugins/updates/src/desktop.ts +90 -164
  58. package/vendor/@akanjs/native/plugins/updates/src/reports.ts +255 -0
  59. package/vendor/@akanjs/native/plugins/updates/src/signer.ts +133 -0
  60. package/vendor/@akanjs/native/plugins/window/native-plugin.json +6 -1
  61. package/vendor/@akanjs/native/plugins/window/src/desktop.ts +20 -4
  62. package/vendor/@akanjs/native/plugins/window/src/index.ts +55 -3
@@ -9,7 +9,6 @@ import {
9
9
  openSync,
10
10
  readdirSync,
11
11
  readFileSync,
12
- readSync,
13
12
  renameSync,
14
13
  rmSync,
15
14
  writeFileSync,
@@ -39,6 +38,8 @@ import {
39
38
  } from "../../../packages/desktop/src/plugin.ts";
40
39
  import { type RelaunchOptions, relaunchAfterExit } from "../../../packages/desktop/src/relaunch.ts";
41
40
  import type { UpdateCheck, UpdateState, UpdatesApi, UpdatesEvents } from "./index.ts";
41
+ import { claimedRelease, createUpdateReports, type ReportedRelease, type ReportReason } from "./reports.ts";
42
+ import { codesignProblem, runSignatureTool, type SignatureTool, signerRefusal } from "./signer.ts";
42
43
 
43
44
  export interface UpdatesConfig {
44
45
  app: string;
@@ -60,6 +61,8 @@ export interface UpdatesConfig {
60
61
  automatic?: boolean;
61
62
  /** Windows (updates.windowsSigners): SHA-1 thumbprints a release's Authenticode certificate must be one of. */
62
63
  windowsSigners?: string[];
64
+ /** updates.report.url: where what became of each release is posted (reports.ts). */
65
+ reportUrl?: string;
63
66
  }
64
67
 
65
68
  interface Entry {
@@ -130,6 +133,9 @@ interface Manifest {
130
133
  expiresAt?: number;
131
134
  }
132
135
 
136
+ /** Why a release on trial is put back, as its report says it; only `server` may pass at another try. */
137
+ type Undone = "timeout" | "relaunch" | "server";
138
+
133
139
  /** A verified manifest and, in protocol v2, the keyId of its envelope's signer. */
134
140
  interface Release {
135
141
  m: Manifest;
@@ -183,79 +189,6 @@ const tarBinary = () =>
183
189
  ? join(process.env.SystemRoot ?? "C:\\Windows", "System32", "tar.exe")
184
190
  : (["/usr/bin/tar", "/bin/tar"].find((path) => existsSync(path)) ?? "tar");
185
191
 
186
- const powershell = () =>
187
- join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
188
-
189
- /**
190
- * Whether the release's executable is signed by the installed one's signer, decided in PowerShell and printed as one
191
- * ASCII verdict line: `unsigned` (the installed one has no valid signature), `same` or `other`. With thumbprints in
192
- * AKAN_NATIVE_SIGNERS, `same` only for a valid signature by one of them, whatever signed the installed one. Constrained
193
- * Language Mode (WDAC, AppLocker) refuses .NET type literals and method calls, so the script makes none, and an error
194
- * ends it before any verdict.
195
- */
196
- const AUTHENTICODE = `$ErrorActionPreference = 'Stop'
197
- $ProgressPreference = 'SilentlyContinue'
198
- $release = Get-AuthenticodeSignature -LiteralPath $env:AKAN_NATIVE_RELEASE_EXE
199
- $pins = @("$env:AKAN_NATIVE_SIGNERS" -split ',' | Where-Object { $_ })
200
- if ($pins.Count -gt 0) {
201
- if ("$($release.Status)" -ceq 'Valid' -and $pins -contains "$($release.SignerCertificate.Thumbprint)") { 'akan-signer: same' }
202
- else { 'akan-signer: other' }
203
- } else {
204
- $own = Get-AuthenticodeSignature -LiteralPath $env:AKAN_NATIVE_INSTALLED_EXE
205
- if ("$($own.Status)" -cne 'Valid') { 'akan-signer: unsigned' }
206
- elseif ("$($release.Status)" -ceq 'Valid' -and "$($release.SignerCertificate.Subject)" -ceq "$($own.SignerCertificate.Subject)") { 'akan-signer: same' }
207
- else { 'akan-signer: other' }
208
- }`;
209
-
210
- /**
211
- * Whether an executable is unsigned, read from its PE header without PowerShell: an x64 or arm64 image (PE32+) whose
212
- * certificate table, where Authenticode embeds a signature, is empty.
213
- */
214
- function isUnsignedImage(exe: string): boolean {
215
- let fd: number | undefined;
216
- try {
217
- fd = openSync(exe, "r");
218
- const head = Buffer.alloc(4096);
219
- const size = readSync(fd, head, 0, head.length, 0);
220
- if (size < 64 || head.toString("latin1", 0, 2) !== "MZ") return false;
221
- const pe = head.readUInt32LE(0x3c);
222
- if (pe + 176 > size || head.toString("latin1", pe, pe + 4) !== "PE\0\0") return false;
223
-
224
- const optional = pe + 24;
225
- if (head.readUInt16LE(optional) !== 0x20b) return false;
226
- if (head.readUInt32LE(optional + 108) < 5) return true;
227
- return head.readUInt32LE(optional + 112 + 32) === 0 && head.readUInt32LE(optional + 112 + 36) === 0;
228
- } catch {
229
- return false;
230
- } finally {
231
- if (fd !== undefined) closeSync(fd);
232
- }
233
- }
234
-
235
- /** A signature tool's exit code and what it printed; -1 when it could not start. */
236
- async function runSignatureTool(
237
- cmd: string[],
238
- env?: Record<string, string>,
239
- ): Promise<{ code: number; output: string }> {
240
- try {
241
- const p = Bun.spawn(cmd, {
242
- stdin: "ignore",
243
- stdout: "pipe",
244
- stderr: "pipe",
245
- windowsHide: true,
246
- ...(env ? { env: { ...process.env, ...env } } : {}),
247
- });
248
- const [out, err, code] = await Promise.all([
249
- new Response(p.stdout).text(),
250
- new Response(p.stderr).text(),
251
- p.exited,
252
- ]);
253
- return { code, output: `${out}${err}` };
254
- } catch (error) {
255
- return { code: -1, output: String(error) };
256
- }
257
- }
258
-
259
192
  /** fsync of a file, or of a folder on macOS and Linux; Windows flushes only a handle opened for writing. */
260
193
  function flush(path: string, folder = false): void {
261
194
  if (folder && process.platform === "win32") return;
@@ -297,6 +230,23 @@ function appPath(mac: boolean): string | null {
297
230
 
298
231
  const resourcesOf = (app: string, mac: boolean) => (mac ? join(app, "Contents", "Resources") : join(app, "resources"));
299
232
 
233
+ function appIdOf(app: string, mac: boolean): string {
234
+ if (mac) {
235
+ const plist = join(app, "Contents", "Info.plist");
236
+ return Bun.spawnSync(["/usr/bin/plutil", "-extract", "CFBundleIdentifier", "raw", "-o", "-", plist])
237
+ .stdout.toString()
238
+ .trim();
239
+ }
240
+ try {
241
+ const boot = JSON.parse(readFileSync(join(resourcesOf(app, mac), "boot.json"), "utf8")) as {
242
+ app?: { id?: string };
243
+ };
244
+ return boot.app?.id ?? "";
245
+ } catch {
246
+ return "";
247
+ }
248
+ }
249
+
300
250
  /**
301
251
  * Windows: the version Settings > Apps shows for an app the installer put here (windows-installer.ts writes the key
302
252
  * and puts the uninstaller beside the folder). A copy of the app elsewhere leaves the installed one's entry alone.
@@ -344,7 +294,7 @@ export interface DesktopUpdatesOptions {
344
294
  autoCheckDelay?: number;
345
295
  autoCheckInterval?: number;
346
296
  /** Runs codesign (macOS) or PowerShell (Windows) on a signature; runSignatureTool by default. */
347
- signatureTool?(cmd: string[], env?: Record<string, string>): Promise<{ code: number; output: string }>;
297
+ signatureTool?: SignatureTool;
348
298
  }
349
299
 
350
300
  export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): DesktopPlugin<UpdatesApi, UpdatesEvents> {
@@ -360,9 +310,16 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
360
310
  const settleTime = options.serverSettle ?? SERVER_SETTLE;
361
311
  const autoCheckDelay = options.autoCheckDelay ?? AUTO_CHECK_DELAY;
362
312
  const autoCheckInterval = options.autoCheckInterval ?? AUTO_CHECK_INTERVAL;
363
- const signatureTool = options.signatureTool ?? runSignatureTool;
364
313
  /** The executable inside an app with the running one's name. */
365
314
  const executableIn = (app: string) => (mac ? join(app, "Contents", "MacOS", exeName) : join(app, exeName));
315
+ const signing = {
316
+ mac,
317
+ windows,
318
+ tool: options.signatureTool ?? runSignatureTool,
319
+ pins: config?.windowsSigners ?? [],
320
+ executableIn,
321
+ };
322
+ const reports = createUpdateReports({ url: config?.reportUrl, platform });
366
323
  const resources = (app: string) => resourcesOf(app, mac);
367
324
  const carries = (app: string) => existsSync(join(resources(app), "server.json"));
368
325
  let dir = "";
@@ -480,6 +437,11 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
480
437
  fail(state, bundle, limit > 1 ? `${why} (${tries} tries)` : why);
481
438
  return true;
482
439
  };
440
+ /** The error of a release refused before any of it is downloaded, which its reports name under `reason`. */
441
+ const refused = (reason: ReportReason, release: ReportedRelease, message: string) => {
442
+ reports.record("failed", release, reason);
443
+ return new AkanNativeError("INTERNAL", message);
444
+ };
483
445
  const entryOf = ({ bundle, sequence, version, tar, build, keyId }: Entry): Entry => ({
484
446
  bundle,
485
447
  sequence,
@@ -495,14 +457,15 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
495
457
  relaunch(executableIn(app), moves, recover(), start);
496
458
 
497
459
  /**
498
- * Puts .previous back, then relaunches it. A release that may pass another time (`retry`) stays downloaded as the
499
- * pending update until it had MAX_STRIKES; any other is failed.
460
+ * Puts .previous back, then relaunches it. A release whose server did not come up may pass another time: it stays
461
+ * downloaded as the pending update until it had MAX_STRIKES; any other is failed.
500
462
  */
501
- const rollBack = async (state: State, quit: (code: number) => void, why: string, retry = false): Promise<void> => {
463
+ const rollBack = async (state: State, quit: (code: number) => void, why: string, reason: Undone): Promise<void> => {
502
464
  const trial = state.trial;
503
465
  if (!trial || !installed) return;
504
466
  const app = installed;
505
- const failed = strike(state, trial.bundle, why, retry ? MAX_STRIKES : 1);
467
+ reports.record("rolledBack", trial, reason);
468
+ const failed = strike(state, trial.bundle, why, reason === "server" ? MAX_STRIKES : 1);
506
469
  const tries = failed ? "" : `, to be tried again (${state.strikes?.[trial.bundle]} of ${MAX_STRIKES})`;
507
470
  console.warn(`[akan-native] updates: ${trial.bundle} ${why}; rolling back${tries}`);
508
471
  state.trial = undefined;
@@ -619,7 +582,7 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
619
582
  "too-large": "holds a manifest larger than 1 MiB",
620
583
  signature: "has a signature that does not verify",
621
584
  }[opened.verdict];
622
- throw new AkanNativeError("INTERNAL", `the release envelope ${why}`);
585
+ throw refused("signature", claimedRelease(manifest, keyId), `the release envelope ${why}`);
623
586
  };
624
587
 
625
588
  const fetchRelease = async (c: UpdatesConfig, state: State): Promise<Release> => {
@@ -632,6 +595,7 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
632
595
  throw new AkanNativeError("INTERNAL", "invalid release manifest: not JSON");
633
596
  }
634
597
  const hex = (s: unknown) => typeof s === "string" && /^[0-9a-f]{64}$/.test(s);
598
+ const named = { ...m, keyId: signer };
635
599
  if (
636
600
  m.schema !== (v2 ? 2 : 1) ||
637
601
  m.kind !== "app" ||
@@ -641,8 +605,9 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
641
605
  m.channel !== c.channel ||
642
606
  (v2 && (m.target ?? null) !== (c.target ?? null))
643
607
  ) {
644
- throw new AkanNativeError(
645
- "INTERNAL",
608
+ throw refused(
609
+ "manifest",
610
+ named,
646
611
  "invalid release manifest: made for another app, platform, CPU, channel or target",
647
612
  );
648
613
  }
@@ -663,13 +628,14 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
663
628
  )) ||
664
629
  (m.resetSequence !== undefined && typeof m.resetSequence !== "boolean")
665
630
  ) {
666
- throw new AkanNativeError("INTERNAL", "invalid release manifest");
631
+ throw refused("manifest", named, "invalid release manifest");
667
632
  }
668
633
  const expiry = manifestExpiry(m.expiresAt, Date.now() / 1000);
669
- if (expiry === "invalid") throw new AkanNativeError("INTERNAL", "invalid release manifest: expiresAt");
634
+ if (expiry === "invalid") throw refused("manifest", named, "invalid release manifest: expiresAt");
670
635
  if (expiry === "expired")
671
- throw new AkanNativeError(
672
- "INTERNAL",
636
+ throw refused(
637
+ "manifest",
638
+ named,
673
639
  `the release manifest expired at ${m.expiresAt}: its server has to sign it again`,
674
640
  );
675
641
  return { m, signer };
@@ -696,8 +662,9 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
696
662
  });
697
663
 
698
664
  if (decision.kind !== "take" && decision.kind !== "stale")
699
- throw new AkanNativeError(
700
- "INTERNAL",
665
+ throw refused(
666
+ "manifest",
667
+ { ...m, keyId: signer },
701
668
  `invalid release manifest: key ${signer} may not revoke ${(m.revokeKeys ?? []).join(", ")}`,
702
669
  );
703
670
  return { newer: offered && decision.kind === "take", revoke: decision.revoke };
@@ -724,52 +691,9 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
724
691
  release === carries(app)
725
692
  ? null
726
693
  : `the release ${release ? "carries a server, and this app does not" : "carries no server, and this app does"}; install it instead`;
727
-
728
- const signerRefusal = async (staged: string, app: string): Promise<string | null> => {
729
- if (mac) {
730
- const shown = await signatureTool(["/usr/bin/codesign", "--display", "--verbose=2", app]);
731
- const team = shown.code === 0 ? /^TeamIdentifier=([A-Z0-9]{10})$/m.exec(shown.output)?.[1] : undefined;
732
- if (!team) return null;
733
- const requirement = `anchor apple generic and certificate leaf[subject.OU] = "${team}"`;
734
- const { code } = await signatureTool(["/usr/bin/codesign", "--verify", `-R=${requirement}`, staged]);
735
- return code === 0 ? null : `the release is not signed by team ${team}, as this app is; publish it with --sign`;
736
- }
737
- if (!windows) return null;
738
- const pins = config?.windowsSigners ?? [];
739
- const { code, output } = await signatureTool(
740
- [
741
- powershell(),
742
- "-NoProfile",
743
- "-NonInteractive",
744
- "-EncodedCommand",
745
- Buffer.from(AUTHENTICODE, "utf16le").toString("base64"),
746
- ],
747
- {
748
- AKAN_NATIVE_INSTALLED_EXE: executableIn(app),
749
- AKAN_NATIVE_RELEASE_EXE: executableIn(staged),
750
- AKAN_NATIVE_SIGNERS: pins.join(","),
751
- },
752
- );
753
- const verdict = code === 0 ? /^akan-signer: (unsigned|same|other)\r?$/m.exec(output)?.[1] : undefined;
754
- if (verdict === "same" || (verdict === "unsigned" && !pins.length)) return null;
755
- if (verdict && pins.length)
756
- return "the release is not Authenticode-signed by a certificate of updates.windowsSigners; publish it with --sign";
757
- if (verdict) return "the release is not Authenticode-signed by the signer of this app; publish it with --sign";
758
- if (pins.length)
759
- return "PowerShell could not check the release's signer against updates.windowsSigners; install the release with its installer";
760
-
761
- if (isUnsignedImage(executableIn(app))) return null;
762
- return "PowerShell could not check the release's signer against this app's; install the release with its installer";
763
- };
764
-
765
- const codesignProblem = async (staged: string): Promise<string | null> => {
766
- if (!mac) return null;
767
- const verified = await signatureTool(["/usr/bin/codesign", "--verify", "--deep", "--strict", staged]);
768
- return verified.code === 0 ? null : `codesign failed: ${verified.output.trim()}`;
769
- };
770
694
 
771
695
  const stagedRefusal = async (staged: string, app: string): Promise<string | null> =>
772
- (await codesignProblem(staged)) ?? (await signerRefusal(staged, app));
696
+ (await codesignProblem(signing, staged)) ?? (await signerRefusal(signing, staged, app));
773
697
 
774
698
  let checked: { staged: string; refusal: Promise<string | null> } | undefined;
775
699
  const recheck = (staged: string) => {
@@ -784,6 +708,7 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
784
708
  return Promise.race([refusal, late]).finally(() => clearTimeout(timer));
785
709
  };
786
710
  const dropChanged = (pending: NonNullable<State["pending"]>, why: string) => {
711
+ reports.record("failed", pending, "verify");
787
712
  rmSync(dirname(pending.staged), { recursive: true, force: true });
788
713
  const latest = readState();
789
714
  if (latest.pending?.staged === pending.staged) latest.pending = undefined;
@@ -824,23 +749,23 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
824
749
 
825
750
  const watchTrial = (ctx: DesktopContext, c: UpdatesConfig) => {
826
751
  onTrial = true;
827
- const failTrial = (why: string, retry: boolean) => {
752
+ const failTrial = (why: string, reason: Undone) => {
828
753
  if (!onTrial) return;
829
754
  onTrial = false;
830
755
  clearTimeout(timer);
831
- void rollBack(readState(), (code) => ctx.quit(code), why, retry);
756
+ void rollBack(readState(), (code) => ctx.quit(code), why, reason);
832
757
  };
833
758
  const server = ctx.server;
834
759
  serverAnswered = server ? serverVerdict(server) : Promise.resolve(null);
835
- void serverAnswered.then((why) => why !== null && failTrial(why, true));
836
- server?.onState((state) => state === "gaveUp" && failTrial("its server gave up", true));
760
+ void serverAnswered.then((why) => why !== null && failTrial(why, "server"));
761
+ server?.onState((state) => state === "gaveUp" && failTrial("its server gave up", "server"));
837
762
  ctx.onNativeEvent("pageLoad", (e) => {
838
763
  if (e.event !== "finished" || (e.window ?? 1) !== 1 || !onTrial) return;
839
764
 
840
765
  void serverAnswered.then((why) => {
841
766
  if (why !== null || !onTrial) return;
842
767
  clearTimeout(timer);
843
- timer = setTimeout(() => failTrial("did not call notifyReady() in time", false), c.readyTimeout);
768
+ timer = setTimeout(() => failTrial("did not call notifyReady() in time", "timeout"), c.readyTimeout);
844
769
  });
845
770
  });
846
771
  };
@@ -857,6 +782,7 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
857
782
  if (refusal && !refusalsTold.has(m.bundle)) {
858
783
  refusalsTold.add(m.bundle);
859
784
  console.warn(`[akan-native] updates: ${m.bundle}: ${refusal}`);
785
+ if (newer) reports.record("failed", { ...m, keyId: release.signer }, "server");
860
786
  }
861
787
  const available = !refusal && newer && !rollingBack;
862
788
  return {
@@ -872,6 +798,9 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
872
798
  const c = need();
873
799
  const app = installed as string;
874
800
  const awake = await stayAwake(ctx, "Downloading an update");
801
+
802
+ let named: ReportedRelease | undefined;
803
+ let step: ReportReason = "server";
875
804
  try {
876
805
  const release = await fetchRelease(c, readState());
877
806
  const { m } = release;
@@ -880,11 +809,13 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
880
809
  revokeKeys(c, revoke);
881
810
  const state = readState();
882
811
  if (!newer) throw new AkanNativeError("NOT_FOUND", "no newer release for this app");
812
+ named = { ...m, keyId: release.signer };
883
813
  const refusal = typeof m.server === "boolean" ? serverRefusal(m.server, app) : null;
884
814
  if (refusal) throw new AkanNativeError("NOT_ALLOWED", refusal);
885
815
  if (state.pending?.bundle === m.bundle && existsSync(state.pending.staged)) return { bundle: m.bundle };
886
816
 
887
817
  const staging = `${app}.update-${m.bundle}`;
818
+ step = "disk";
888
819
  try {
889
820
  rmSync(staging, { recursive: true, force: true });
890
821
  mkdirSync(staging, { recursive: true });
@@ -918,13 +849,17 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
918
849
  }
919
850
  }
920
851
  if (!tar) {
852
+ step = "download";
921
853
  const gz = await fetchBytes(`${releases(c)}/${archive.url}`, archive.size, ctx);
854
+ step = "verify";
922
855
  if (sha256(gz) !== archive.gzSha256)
923
856
  throw new AkanNativeError("INTERNAL", "the release archive does not match its hash");
924
857
  tar = Bun.gunzipSync(gz as Uint8Array<ArrayBuffer>);
925
858
  }
859
+ step = "verify";
926
860
  if (sha256(tar) !== archive.sha256) throw new AkanNativeError("INTERNAL", "the release does not match its hash");
927
861
 
862
+ step = "disk";
928
863
  const tarFile = join(staging, "release.tar");
929
864
  writeFileSync(tarFile, tar);
930
865
  const run = async (cmd: string[]) => {
@@ -936,40 +871,21 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
936
871
  await run([tarBinary(), "-xf", tarFile, "-C", staging]);
937
872
  rmSync(tarFile);
938
873
 
874
+ step = "verify";
939
875
  const unpacked = readdirSync(staging);
940
876
  const staged = unpacked.length === 1 ? join(staging, unpacked[0] as string) : "";
941
877
  if (!staged || !existsSync(executableIn(staged)))
942
878
  throw new AkanNativeError("INTERNAL", `the release is not one app with ${exeName}`);
943
- let id = "";
944
- if (mac) {
945
- id = Bun.spawnSync([
946
- "/usr/bin/plutil",
947
- "-extract",
948
- "CFBundleIdentifier",
949
- "raw",
950
- "-o",
951
- "-",
952
- join(staged, "Contents", "Info.plist"),
953
- ])
954
- .stdout.toString()
955
- .trim();
956
- } else {
957
- try {
958
- id =
959
- (
960
- JSON.parse(readFileSync(join(resources(staged), "boot.json"), "utf8")) as {
961
- app?: { id?: string };
962
- }
963
- ).app?.id ?? "";
964
- } catch {}
965
- }
879
+ const id = appIdOf(staged, mac);
966
880
  if (id !== c.app)
967
881
  throw new AkanNativeError("INTERNAL", `the release is ${id || "not an akan-native app"}, not ${c.app}`);
968
882
 
969
- const codesign = await codesignProblem(staged);
883
+ const codesign = await codesignProblem(signing, staged);
970
884
  if (codesign) throw new AkanNativeError("INTERNAL", codesign);
971
- const unpackedRefusal = (await signerRefusal(staged, app)) ?? serverRefusal(carries(staged), app);
885
+ const otherSigner = await signerRefusal(signing, staged, app);
886
+ const unpackedRefusal = otherSigner ?? serverRefusal(carries(staged), app);
972
887
  if (unpackedRefusal) {
888
+ step = otherSigner ? "signer" : "server";
973
889
  rmSync(staging, { recursive: true, force: true });
974
890
  const latest = readState();
975
891
  fail(latest, m.bundle, unpackedRefusal);
@@ -981,6 +897,7 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
981
897
  rmSync(staging, { recursive: true, force: true });
982
898
  throw new AkanNativeError("CANCELLED", "the channel changed during the download");
983
899
  }
900
+ step = "disk";
984
901
  flushTree(staged);
985
902
 
986
903
  mkdirSync(join(dir, "app"), { recursive: true });
@@ -998,8 +915,12 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
998
915
  staged,
999
916
  };
1000
917
  writeState(latest);
918
+ reports.record("downloaded", latest.pending);
1001
919
  checked = { staged, refusal: Promise.resolve(null) };
1002
920
  return { bundle: m.bundle };
921
+ } catch (error) {
922
+ reports.failed(error, named, step);
923
+ throw error;
1003
924
  } finally {
1004
925
  awake();
1005
926
  }
@@ -1145,6 +1066,7 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
1145
1066
  dir = join(ctx.appLocalDataDir, ctx.dev ? "akan-native-updates-debug" : "akan-native-updates");
1146
1067
  const app = installed;
1147
1068
  if (!config || !app) return;
1069
+ reports.start({ dir, dev: ctx.dev, appVersion: ctx.app.version, config: need });
1148
1070
  const automatic = config.automatic !== false && !ctx.dev;
1149
1071
  if (automatic) {
1150
1072
  ctx.onBeforeQuit(checkBeforeQuit);
@@ -1213,6 +1135,7 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
1213
1135
 
1214
1136
  if (trial.from === config.embeddedSequence) {
1215
1137
  const failed = strike(state, trial.bundle, "could not be moved into place");
1138
+ if (failed) reports.record("failed", trial, "disk");
1216
1139
  const tries = failed
1217
1140
  ? ""
1218
1141
  : `; it is tried again at the next apply (${state.strikes?.[trial.bundle]} of ${MAX_STRIKES})`;
@@ -1255,10 +1178,11 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
1255
1178
  return;
1256
1179
  }
1257
1180
  if (++trial.attempts > 1)
1258
- return rollBack(state, (code) => ctx.launch.exit(code), "was started again without notifyReady()");
1181
+ return rollBack(state, (code) => ctx.launch.exit(code), "was started again without notifyReady()", "relaunch");
1259
1182
  trial.pid = process.pid;
1260
1183
  trial.boot = boot;
1261
1184
  writeState(state);
1185
+ reports.record("applied", trial);
1262
1186
  watchTrial(ctx, config);
1263
1187
  };
1264
1188
 
@@ -1307,6 +1231,7 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
1307
1231
  state.pending = undefined;
1308
1232
  fail(state, pending.bundle, refusal);
1309
1233
  writeState(state);
1234
+ reports.record("failed", pending, "server");
1310
1235
  throw new AkanNativeError("NOT_ALLOWED", refusal);
1311
1236
  }
1312
1237
  const changed = await stagedRefusal(pending.staged, app);
@@ -1337,6 +1262,7 @@ export function createDesktopUpdates(options: DesktopUpdatesOptions = {}): Deskt
1337
1262
  state.rolledBack = undefined;
1338
1263
  if (state.strikes) delete state.strikes[entry.bundle];
1339
1264
  writeState(state);
1265
+ reports.record("confirmed", entry);
1340
1266
  try {
1341
1267
  rmSync(trial.previous, { recursive: true, force: true });
1342
1268
  } catch (error) {