Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.
feat(desktop): update from GitHub Releases on every platform
claude-opus-5-5-mediumbc114bad6c61
diff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.ymlindex c72be6c8..f0bdf3bd 100644--- a/.github/workflows/desktop-release.yml+++ b/.github/workflows/desktop-release.yml@@ -128,7 +128,6 @@ jobs:MACOS_DEVELOPER_ID_P12_BASE64: ${{ secrets.MACOS_DEVELOPER_ID_P12_BASE64 }}MACOS_DEVELOPER_ID_PASSWORD: ${{ secrets.MACOS_DEVELOPER_ID_PASSWORD }}MACOS_NOTARY_KEY_JSON: ${{ secrets.MACOS_NOTARY_KEY_JSON }}- DESKTOP_UPDATE_KEY_PEM: ${{ secrets.DESKTOP_UPDATE_KEY_PEM }}WINDOWS_SIGNING_P12_BASE64: ${{ secrets.WINDOWS_SIGNING_P12_BASE64 }}WINDOWS_SIGNING_PASSWORD: ${{ secrets.WINDOWS_SIGNING_PASSWORD }}TARGET: ${{ matrix.target }}@@ -147,10 +146,6 @@ jobs:echo "MACOS_NOTARY_KEY=$keys/notary.json" >>"$GITHUB_ENV"fifi- if [ "$TARGET" = darwin-arm64 ] && [ -n "$DESKTOP_UPDATE_KEY_PEM" ]; then- printf '%s\n' "$DESKTOP_UPDATE_KEY_PEM" >"$keys/update.pem"- echo "DESKTOP_UPDATE_KEY=$keys/update.pem" >>"$GITHUB_ENV"- fiif [ "$TARGET" = win32-x64 ] && [ -n "$WINDOWS_SIGNING_P12_BASE64" ]; thenbase64 -d <<<"$WINDOWS_SIGNING_P12_BASE64" >"$keys/authenticode.p12"printf '%s' "$WINDOWS_SIGNING_PASSWORD" >"$keys/authenticode.password"@@ -182,6 +177,22 @@ jobs:pattern: desktop-*path: releasemerge-multiple: true+ # The signed update manifest over every platform's package. Without+ # the key the release still goes out, with a warning and no manifest.+ - name: Sign the update manifest+ env:+ DESKTOP_UPDATE_KEY_PEM: ${{ secrets.DESKTOP_UPDATE_KEY_PEM }}+ shell: bash+ run: |+ set -euo pipefail+ umask 077+ if [ -n "$DESKTOP_UPDATE_KEY_PEM" ]; then+ key="$RUNNER_TEMP/update.pem"+ trap 'rm -f "$key"' EXIT+ printf '%s\n' "$DESKTOP_UPDATE_KEY_PEM" >"$key"+ export DESKTOP_UPDATE_KEY="$key"+ fi+ scripts/ci/desktop-release.sh manifest release "${{ needs.prepare.outputs.version }}"- run: scripts/ci/desktop-release.sh checksums release "${{ needs.prepare.outputs.version }}"# GITHUB_TOKEN can write only this repository; a release in another one# takes LINGER_RELEASE_TOKEN, which prepare checked.diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.mdindex 470394b2..4499d001 100644--- a/apps/desktop/AGENTS.md+++ b/apps/desktop/AGENTS.md@@ -31,7 +31,8 @@ Gateway and runs Agents. The daemon exits with the app.`out/Linger-<version>-x64.zip` on Linux after `node build.mjs` with the`win32-x64` daemon target. Needs the`wintool` image from `packaging/win/Dockerfile`. Neither is- Authenticode-signed and Windows has no self-update yet.+ Authenticode-signed. The updater runs the setup program with+ `/S /relaunch`; the portable folder only links to the release page.- `python3 packaging/linux/package.py`: build`out/Linger-<version>-linux-x64.tar.gz` (one folder with the `linger`executable) after `node build.mjs` with the `linux-x64` daemon target.diff --git a/apps/desktop/packaging/mac/package.py b/apps/desktop/packaging/mac/package.pyindex 7a9537a8..69d54fb1 100644--- a/apps/desktop/packaging/mac/package.py+++ b/apps/desktop/packaging/mac/package.py@@ -8,7 +8,7 @@ Tools: the `dmgtool` image from ./Dockerfile (hfsplus, dmg, ImageMagick) andrcodesign for the signature Apple silicon requires.python3 packaging/mac/package.py [--arch arm64 --arch x64]- [--rcodesign PATH] [--out DIR] [--update-key PEM]+ [--rcodesign PATH] [--out DIR] [--update-archive][--developer-id P12 --developer-id-password FILE [--notary-key JSON]]Without --developer-id the app gets an ad-hoc signature and macOS asks the@@ -27,13 +27,11 @@ JIT and, as it keeps the hardened runtime of its release signature, for thenative modules it loads; their manifests then record the signed bytes before a shallow signatureseals them. The desktop copies them out of the app as they are.---update-key also writes the self-update feed to <out>/update/:-Linger-<version>-<arch>.tar.gz per arch, manifest.json and manifest.json.sig,-an Ed25519 signature made with openssl. Upload the three files to the server's-install/desktop/stable/. The key file is only passed to openssl.+--update-archive also writes <out>/Linger-<version>-<arch>.app.tar.gz, the+signed app the installed app replaces itself with. The release's signed+manifest lists it (scripts/ci/desktop-release.sh manifest)."""import argparse-import base64import hashlibimport jsonimport os@@ -321,20 +319,7 @@ def update_archive(app, output):archive.add(app, arcname="Linger.app")with open(output, "rb") as source:digest = hashlib.sha256(source.read()).hexdigest()- return {"file": os.path.basename(output), "sha256": digest, "size": os.path.getsize(output)}---def write_feed(directory, version, packages, key):- manifest = os.path.join(directory, "manifest.json")- with open(manifest, "wb") as out:- out.write(json.dumps({"schema": 1, "version": version, "packages": packages},- indent=2, sort_keys=True).encode() + b"\n")- signature = subprocess.run(- ["openssl", "pkeyutl", "-sign", "-rawin", "-inkey", key, "-in", manifest],- check=True, capture_output=True).stdout- with open(manifest + ".sig", "w") as out:- out.write(base64.b64encode(signature).decode() + "\n")- print(f"{manifest} version={version} arches={','.join(sorted(packages))}")+ print(f"{output} {os.path.getsize(output)} sha256={digest}")def main():@@ -343,7 +328,8 @@ def main():parser.add_argument("--rcodesign", default=shutil.which("rcodesign") or "rcodesign")parser.add_argument("--out", default=os.path.join(DESKTOP, "out"))parser.add_argument("--cache", default=os.path.expanduser("~/.cache/linger-desktop"))- parser.add_argument("--update-key", help="Ed25519 private key (PEM) that signs the update feed")+ parser.add_argument("--update-archive", action="store_true",+ help="also write the app archive installed apps update from")parser.add_argument("--developer-id", help="Developer ID Application certificate and key (.p12)")parser.add_argument("--developer-id-password", help="file holding the .p12 password")parser.add_argument("--notary-key", help="App Store Connect API key (JSON) for notarization")@@ -363,10 +349,6 @@ def main():check_teamhub(f"darwin-{arch}")check_runtime(f"darwin-{arch}")os.makedirs(args.out, exist_ok=True)- feed = os.path.join(args.out, "update")- if args.update_key:- os.makedirs(feed, exist_ok=True)- packages = {}for arch in arches:workdir = tempfile.mkdtemp(prefix=f"linger-dmg-{arch}-")try:@@ -381,14 +363,10 @@ def main():with open(output, "rb") as dmg:digest = hashlib.sha256(dmg.read()).hexdigest()print(f"{output} {os.path.getsize(output)} sha256={digest}")- if args.update_key:- package_info = update_archive(app, os.path.join(feed, f"Linger-{version}-{arch}.tar.gz"))- packages[f"darwin-{arch}"] = package_info- print(f"{package_info['file']} {package_info['size']} sha256={package_info['sha256']}")+ if args.update_archive:+ update_archive(app, os.path.join(args.out, f"Linger-{version}-{arch}.app.tar.gz"))finally:shutil.rmtree(workdir, ignore_errors=True)- if args.update_key:- write_feed(feed, version, packages, args.update_key)if __name__ == "__main__":diff --git a/apps/desktop/packaging/win/installer.nsi b/apps/desktop/packaging/win/installer.nsiindex 1e17e72b..d120dc89 100644--- a/apps/desktop/packaging/win/installer.nsi+++ b/apps/desktop/packaging/win/installer.nsi@@ -4,6 +4,7 @@; is fixed: the uninstaller removes all of it.Unicode true!include "MUI2.nsh"+!include "FileFunc.nsh"Name "Linger"OutFile "${OUTPUT}"@@ -162,6 +163,17 @@ Section "Linger"WriteRegDWORD HKCU "${UNINSTALL_KEY}" "NoRepair" 1SectionEnd+; The app's self-update runs this setup with /S /relaunch after it quit+; (updater.ts): a silent install shows no finish page to start Linger from.+Function .onInstSuccess+ ${GetParameters} $0+ ClearErrors+ ${GetOptions} $0 "/relaunch" $1+ IfErrors done+ Exec '"$INSTDIR\Linger.exe"'+ done:+FunctionEnd+Section "Uninstall"; Settings, sign-in and logs stay in %APPDATA%\Linger, and the local; installation (%USERPROFILE%\.simplexai) with its data.diff --git a/apps/desktop/packaging/win/package.py b/apps/desktop/packaging/win/package.pyindex 2b7d2127..2b83fa07 100644--- a/apps/desktop/packaging/win/package.py+++ b/apps/desktop/packaging/win/package.py@@ -15,8 +15,9 @@ menu shortcut and an entry under Installed apps. The zip holds the samefolder for running without installing.Neither is Authenticode-signed yet, so SmartScreen asks the user to confirm-the first start. There is no self-update on Windows; a new setup program-replaces the installed version.+the first start. The desktop updater runs a newer setup program with+/S /relaunch: it stops Linger, replaces the installed version and starts it+again. The zip has no self-update.The Go daemon goes to resources/computer/. With a bundled source package, theTeamHub binaries and the Native runtime build.mjs built from it must be therediff --git a/apps/desktop/src/main/config.ts b/apps/desktop/src/main/config.tsindex 9950d192..7210c56f 100644--- a/apps/desktop/src/main/config.ts+++ b/apps/desktop/src/main/config.ts@@ -37,6 +37,10 @@ const desktopConfig = z.object({// The backup of the earlier Simplex app's data that the local server// already told about and enrolled this computer again for.legacyBackup: z.string().optional(),+ // Releases URL of the update feed, for a deployment that publishes its own+ // releases (update-manifest.ts); GitHub's simplexai-labs/linger when unset.+ // A value that is not a URL is dropped rather than resetting the file.+ updateFeedUrl: z.string().url().optional().catch(undefined),window: z.object({x: z.number().int(),diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.tsindex 7acc7627..2997e42b 100644--- a/apps/desktop/src/main/index.ts+++ b/apps/desktop/src/main/index.ts@@ -49,7 +49,8 @@ import { loginShellEnvironment, withLoginShell } from "./shell-env.js";import { StatusModule } from "./status.js";import { SystemPermissions } from "./system-permissions.js";import { TrayModule } from "./tray.js";-import { UpdaterModule, appBundleOf } from "./updater.js";+import { updateNotice } from "./tray-menu.js";+import { UpdaterModule, updateInstallFor } from "./updater.js";import { WindowManagerModule, registerAppScheme } from "./window-manager.js";import { WorkspaceGrantsModule } from "./workspace-grants.js";@@ -205,22 +206,20 @@ async function main(): Promise<void> {});// Set once the bundle was swapped, so quitting relaunches the new version.let relaunch = false;+ // Set once the setup program of an update runs; it starts the new version.+ let updating = false;const updater = new UpdaterModule({version: VERSION,platform: process.platform,arch: process.arch,- appBundle:- app.isPackaged && process.platform === "darwin"- ? appBundleOf(process.execPath)- : undefined,+ install: app.isPackaged+ ? updateInstallFor(process.platform, process.execPath, existsSync)+ : undefined,downloadDirectory: path.join(userData, "updates"),services: localServer,- announceServices: () => {+ announce: (state) => {if (!Notification.isSupported()) return;- const notice = new Notification({- title: "Update ready",- body: "Click to update Linger on this computer. It restarts in about a minute.",- });+ const notice = new Notification(updateNotice(state));notice.on("click", () => void updater.install());notice.show();},@@ -228,6 +227,11 @@ async function main(): Promise<void> {relaunch = true;app.quit();},+ quit: async () => {+ updating = true;+ app.quit();+ },+ openExternal: (url) => shell.openExternal(url),});// The app's own macOS permissions, which the daemon asks about over stdio// and the page acts on over IPC.@@ -330,7 +334,7 @@ async function main(): Promise<void> {if (quitting) return;quitting = true;event.preventDefault();- void host.stop(relaunch ? "update" : "quit").finally(() => {+ void host.stop(relaunch || updating ? "update" : "quit").finally(() => {if (relaunch) app.relaunch();app.exit(0);});diff --git a/apps/desktop/src/main/local-server.ts b/apps/desktop/src/main/local-server.tsindex 625f704a..8b9b7e91 100644--- a/apps/desktop/src/main/local-server.ts+++ b/apps/desktop/src/main/local-server.ts@@ -2082,11 +2082,6 @@ export class LocalServerModule implements Module {return answers(this.#options.fetch ?? fetch, origin);}- // Whether the window's server is the one this app runs.- serving(serverUrl: string): boolean {- return this.#origin === serverUrl;- }-// Whether this app brings a source package the running services do not// use yet.sourceUpdateAvailable(): boolean {diff --git a/apps/desktop/src/main/tray-menu.test.ts b/apps/desktop/src/main/tray-menu.test.tsindex eb163ef0..3087593e 100644--- a/apps/desktop/src/main/tray-menu.test.ts+++ b/apps/desktop/src/main/tray-menu.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { trayMenu } from "./tray-menu.js";+import { trayMenu, updateNotice } from "./tray-menu.js";describe("trayMenu", () => {it("leads with the status and ends with quit", () => {@@ -122,4 +122,42 @@ describe("trayMenu", () => {expect(items[1]).toEqual({ kind: "separator" });}});++ it("links a release this installation cannot apply itself", () => {+ const item = trayMenu({+ status: { tone: "online", label: "Online" },+ preventSleep: false,+ enrolled: true,+ update: {+ kind: "available",+ version: "0.17.0",+ url: "https://github.com/simplexai-labs/linger/releases/tag/desktop-v0.17.0",+ },+ })[1];+ expect(item).toEqual({+ kind: "action",+ action: "install-update",+ label: "Download Linger 0.17.0…",+ });+ });+});++describe("updateNotice", () => {+ it("names what clicking it does", () => {+ expect(updateNotice({ kind: "ready", version: "0.17.0" })).toEqual({+ title: "Update ready",+ body: "Linger 0.17.0 is downloaded. Click to restart Linger and update.",+ });+ expect(+ updateNotice({ kind: "available", version: "0.17.0", url: "https://x" }),+ ).toEqual({+ title: "Update available",+ body: "Linger 0.17.0 is available. Click to open its download page.",+ });+ expect(+ updateNotice({ kind: "ready", version: "0.16.7", services: true }).body,+ ).toBe(+ "Click to update Linger on this computer. It restarts in about a minute.",+ );+ });});diff --git a/apps/desktop/src/main/tray-menu.ts b/apps/desktop/src/main/tray-menu.tsindex 26c04cb6..5c5904e0 100644--- a/apps/desktop/src/main/tray-menu.ts+++ b/apps/desktop/src/main/tray-menu.ts@@ -93,6 +93,14 @@ const updateItems = (update: TrayMenuState["update"]): TrayMenuItem[] => {return update.services? [{ kind: "label", label: "Updating Linger on This Computer…" }]: [];+ case "available":+ return [+ {+ kind: "action",+ action: "install-update",+ label: `Download Linger ${update.version}…`,+ },+ ];case "failed": {const reason =update.error.length > REASON_LENGTH@@ -111,3 +119,25 @@ const updateItems = (update: TrayMenuState["update"]): TrayMenuItem[] => {return [];}};++// The notification for an update once it is ready or available; clicking it+// does what the tray's update item does.+export function updateNotice(update: UpdateState): {+ title: string;+ body: string;+} {+ if (update.kind === "available")+ return {+ title: "Update available",+ body: `Linger ${update.version} is available. Click to open its download page.`,+ };+ if (update.kind === "ready" && !update.services)+ return {+ title: "Update ready",+ body: `Linger ${update.version} is downloaded. Click to restart Linger and update.`,+ };+ return {+ title: "Update ready",+ body: "Click to update Linger on this computer. It restarts in about a minute.",+ };+}diff --git a/apps/desktop/src/main/update-manifest.test.ts b/apps/desktop/src/main/update-manifest.test.tsindex 2eaca751..e81d4e98 100644--- a/apps/desktop/src/main/update-manifest.test.ts+++ b/apps/desktop/src/main/update-manifest.test.ts@@ -3,9 +3,13 @@ import { generateKeyPairSync, sign } from "node:crypto";import { describe, expect, it } from "vitest";import {+ DEFAULT_FEED_URL,ManifestError,compareVersions,+ feedUrls,packageFor,+ packageUrl,+ releasePageUrl,verifyManifest,} from "./update-manifest.js";@@ -18,7 +22,7 @@ const keys = () => {};const manifest = {- schema: 1,+ schema: 2,version: "0.16.1",packages: {"darwin-arm64": {@@ -58,7 +62,15 @@ describe("update manifest", () => {).toThrow(ManifestError);});- it("rejects package paths outside the feed", () => {+ it("rejects the manifest of another schema", () => {+ const { privateKey, publicPem } = keys();+ const { bytes, signature } = signed({ ...manifest, schema: 1 }, privateKey);+ expect(() => verifyManifest(bytes, signature, publicPem)).toThrow(+ "Update manifest is invalid",+ );+ });++ it("rejects package paths outside the release", () => {const { privateKey, publicPem } = keys();const bad = structuredClone(manifest);bad.packages["darwin-arm64"].file = "../Linger.tar.gz";@@ -73,4 +85,37 @@ describe("update manifest", () => {expect(compareVersions("0.16.0", "0.16.0")).toBe(0);expect(compareVersions("0.15.9", "0.16.0")).toBeLessThan(0);});++ it("orders a prerelease before its release", () => {+ expect(compareVersions("0.17.0", "0.17.0-rc.1")).toBeGreaterThan(0);+ expect(compareVersions("0.17.0-rc.1", "0.16.9")).toBeGreaterThan(0);+ expect(compareVersions("0.17.0-rc.10", "0.17.0-rc.9")).toBeGreaterThan(0);+ expect(compareVersions("0.17.0-rc.1", "0.17.0-rc.1.1")).toBeLessThan(0);+ expect(compareVersions("0.17.0-alpha", "0.17.0-beta")).toBeLessThan(0);+ expect(compareVersions("0.17.0-1", "0.17.0-alpha")).toBeLessThan(0);+ expect(compareVersions("0.17.0-rc.1", "0.17.0-rc.1")).toBe(0);+ });++ it("finds the manifest in the latest release and packages in its own", () => {+ expect(feedUrls(DEFAULT_FEED_URL)).toEqual({+ manifest: new URL(+ "https://github.com/simplexai-labs/linger/releases/latest/download/manifest.json",+ ),+ signature: new URL(+ "https://github.com/simplexai-labs/linger/releases/latest/download/manifest.json.sig",+ ),+ });+ expect(+ packageUrl(+ "https://releases.example.com/linger/",+ "0.17.0",+ "Linger-0.17.0-windows-x64-setup.exe",+ ).toString(),+ ).toBe(+ "https://releases.example.com/linger/download/desktop-v0.17.0/Linger-0.17.0-windows-x64-setup.exe",+ );+ expect(releasePageUrl(DEFAULT_FEED_URL, "0.17.0")).toBe(+ "https://github.com/simplexai-labs/linger/releases/tag/desktop-v0.17.0",+ );+ });});diff --git a/apps/desktop/src/main/update-manifest.ts b/apps/desktop/src/main/update-manifest.tsindex 8ac2f9ce..d4cb16ac 100644--- a/apps/desktop/src/main/update-manifest.ts+++ b/apps/desktop/src/main/update-manifest.ts@@ -2,11 +2,14 @@ import { createPublicKey, verify } from "node:crypto";import { z } from "zod";-// The update feed lives on the deployment's own server:-// <server>/install/desktop/<channel>/manifest.json plus manifest.json.sig,-// an Ed25519 signature over the exact manifest bytes. Package files sit next-// to the manifest.-export const FEED_PATH = "install/desktop/stable/";+// The update feed has the layout of GitHub Releases: the newest stable+// release's manifest.json plus manifest.json.sig (an Ed25519 signature over+// the exact manifest bytes) at <feed>/latest/download/, and each package in+// the release of the version the signed manifest names, at+// <feed>/download/desktop-v<version>/. A prerelease never becomes the latest+// release, so it is never offered.+export const DEFAULT_FEED_URL =+ "https://github.com/simplexai-labs/linger/releases";export const MANIFEST_FILE = "manifest.json";export const SIGNATURE_FILE = "manifest.json.sig";@@ -15,10 +18,10 @@ export const UPDATE_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----MCowBQYDK2VwAyEA985QJ8UAvzK0ZLPW6YPaIkiCS2A+qPbEaZvi0aAccR4=-----END PUBLIC KEY-----`;-const VERSION = /^\d+\.\d+\.\d+$/;+const VERSION = /^\d+\.\d+\.\d+(-[0-9A-Za-z][0-9A-Za-z.-]*)?$/;const updatePackage = z.object({- // A bare file name: the package always comes from the feed directory.+ // A bare file name: the package always comes from the manifest's release.file: z.string().regex(/^[A-Za-z0-9._-]+$/),sha256: z.string().regex(/^[0-9a-f]{64}$/),size: z.number().int().positive(),@@ -26,7 +29,7 @@ const updatePackage = z.object({export type UpdatePackage = z.infer<typeof updatePackage>;const updateManifest = z.object({- schema: z.literal(1),+ schema: z.literal(2),version: z.string().regex(VERSION),// Keyed by `${platform}-${arch}`, e.g. darwin-arm64.packages: z.record(z.string(), updatePackage),@@ -35,12 +38,37 @@ export type UpdateManifest = z.infer<typeof updateManifest>;export class ManifestError extends Error {}+export interface FeedUrls {+ readonly manifest: URL;+ readonly signature: URL;+}++const releases = (feed: string): string =>+ feed.endsWith("/") ? feed : `${feed}/`;++export function feedUrls(feed: string): FeedUrls {+ const latest = new URL("latest/download/", releases(feed));+ return {+ manifest: new URL(MANIFEST_FILE, latest),+ signature: new URL(SIGNATURE_FILE, latest),+ };+}++export function packageUrl(feed: string, version: string, file: string): URL {+ return new URL(`download/desktop-v${version}/${file}`, releases(feed));+}++// The release's page, where a person downloads the package themselves.+export function releasePageUrl(feed: string, version: string): string {+ return new URL(`tag/desktop-v${version}`, releases(feed)).toString();+}+// Returns the manifest only when the signature matches the built-in key.-export const verifyManifest = (+export function verifyManifest(bytes: Buffer,signature: string,publicKey: string = UPDATE_PUBLIC_KEY,-): UpdateManifest => {+): UpdateManifest {const valid = verify(null,bytes,@@ -57,21 +85,48 @@ export const verifyManifest = (const parsed = updateManifest.safeParse(json);if (!parsed.success) throw new ManifestError("Update manifest is invalid");return parsed.data;-};+}-// Positive when a is newer than b. Both are plain x.y.z versions.-export const compareVersions = (a: string, b: string): number => {- const pa = a.split(".").map(Number);- const pb = b.split(".").map(Number);+// Positive when a is newer than b, by semantic version precedence: x.y.z+// numerically, then a prerelease (0.17.0-rc.1) before its release.+export function compareVersions(a: string, b: string): number {+ const [coreA, preA] = splitVersion(a);+ const [coreB, preB] = splitVersion(b);+ const pa = coreA.split(".").map(Number);+ const pb = coreB.split(".").map(Number);for (let i = 0; i < 3; i++) {const diff = (pa[i] ?? 0) - (pb[i] ?? 0);if (diff !== 0) return diff;}+ if (preA === undefined || preB === undefined)+ return preA === preB ? 0 : preA === undefined ? 1 : -1;+ const ia = preA.split(".");+ const ib = preB.split(".");+ for (let i = 0; i < Math.max(ia.length, ib.length); i++) {+ const x = ia[i];+ const y = ib[i];+ if (x === undefined || y === undefined) return x === undefined ? -1 : 1;+ if (x === y) continue;+ const nx = /^\d+$/.test(x);+ const ny = /^\d+$/.test(y);+ if (nx && ny) return Number(x) - Number(y);+ if (nx !== ny) return nx ? -1 : 1;+ return x < y ? -1 : 1;+ }return 0;+}++const splitVersion = (version: string): [string, string | undefined] => {+ const dash = version.indexOf("-");+ return dash < 0+ ? [version, undefined]+ : [version.slice(0, dash), version.slice(dash + 1)];};-export const packageFor = (+export function packageFor(manifest: UpdateManifest,platform: string,arch: string,-): UpdatePackage | undefined => manifest.packages[`${platform}-${arch}`];+): UpdatePackage | undefined {+ return manifest.packages[`${platform}-${arch}`];+}diff --git a/apps/desktop/src/main/updater.test.ts b/apps/desktop/src/main/updater.test.tsindex a6358a1d..f3052ce2 100644--- a/apps/desktop/src/main/updater.test.ts+++ b/apps/desktop/src/main/updater.test.ts@@ -1,25 +1,42 @@import { createHash, generateKeyPairSync, sign } from "node:crypto";+import { EventEmitter } from "node:events";import { mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";import path from "node:path";import { describe, expect, it } from "vitest";import type { ComputerDaemonModule } from "./computer-daemon.js";+import type { DesktopConfig } from "./config.js";import { stubModule, tempDirectory, testHost } from "./test-support.js";-import { type UpdaterOptions, UpdaterModule, appBundleOf } from "./updater.js";+import {+ type SpawnSetup,+ type UpdateState,+ type UpdaterOptions,+ UpdaterModule,+ appBundleOf,+ updateInstallFor,+} from "./updater.js";-const SERVER = "https://linger.example.com";+const RELEASES = "https://github.com/simplexai-labs/linger/releases";const PACKAGE = Buffer.from("new app archive");-const release = (version: string, body = PACKAGE) => {+const release = (+ version: string,+ {+ body = PACKAGE,+ target = "darwin-arm64",+ file = `Linger-${version}-macos-arm64.app.tar.gz`,+ feed = RELEASES,+ } = {},+) => {const { privateKey, publicKey } = generateKeyPairSync("ed25519");const manifest = Buffer.from(JSON.stringify({- schema: 1,+ schema: 2,version,packages: {- "darwin-arm64": {- file: `Linger-${version}-arm64.tar.gz`,+ [target]: {+ file,sha256: createHash("sha256").update(PACKAGE).digest("hex"),size: PACKAGE.length,},@@ -27,23 +44,23 @@ const release = (version: string, body = PACKAGE) => {}),);const files: Record<string, Buffer> = {- "manifest.json": manifest,- "manifest.json.sig": Buffer.from(+ [`${feed}/latest/download/manifest.json`]: manifest,+ [`${feed}/latest/download/manifest.json.sig`]: Buffer.from(sign(null, manifest, privateKey).toString("base64"),),- [`Linger-${version}-arm64.tar.gz`]: body,+ [`${feed}/download/desktop-v${version}/${file}`]: body,};const requested: string[] = [];const fetch = (async (url: URL) => {- requested.push(url.pathname);- const name = url.pathname.replace("/install/desktop/stable/", "");- const file = files[name];- return file- ? new Response(new Uint8Array(file))+ requested.push(url.toString());+ const content = files[url.toString()];+ return content+ ? new Response(new Uint8Array(content)): new Response("missing", { status: 404 });}) as unknown as typeof globalThis.fetch;return {fetch,+ files,requested,publicKey: publicKey.export({ type: "spki", format: "pem" }).toString(),};@@ -52,6 +69,7 @@ const release = (version: string, body = PACKAGE) => {const setup = async (feed: ReturnType<typeof release>,options: Partial<UpdaterOptions> = {},+ config: Partial<DesktopConfig> = {},) => {const root = tempDirectory();const applications = path.join(root, "Applications");@@ -61,6 +79,9 @@ const setup = async (const downloads = path.join(root, "updates");let running = 0;let restarts = 0;+ let quits = 0;+ const opened: string[] = [];+ const announced: UpdateState[] = [];const runtime = {...stubModule("ComputerDaemon"),running: () => running,@@ -69,11 +90,18 @@ const setup = async (version: "0.16.7",platform: "darwin",arch: "arm64",- appBundle: bundle,+ install: { kind: "app-bundle", appBundle: bundle },downloadDirectory: downloads,restart: async () => {restarts += 1;},+ quit: async () => {+ quits += 1;+ },+ openExternal: async (url) => {+ opened.push(url);+ },+ announce: (state) => announced.push(state),fetch: feed.fetch,publicKey: feed.publicKey,checkDelayMs: 60 * 60_000,@@ -85,9 +113,7 @@ const setup = async (},...options,});- const host = testHost([stubModule("Config"), runtime, updater], {- serverUrl: SERVER,- });+ const host = testHost([stubModule("Config"), runtime, updater], config);await host.start();const setRunning = (n: number) => {running = n;@@ -100,17 +126,35 @@ const setup = async (applications,downloads,setRunning,+ opened,+ announced,restarts: () => restarts,+ quits: () => quits,};};describe("UpdaterModule", () => {- it("installs a verified update once running tasks finish", async () => {+ it("installs a verified update from the latest release once running tasks finish", async () => {const feed = release("0.17.0");- const { updater, bundle, applications, setRunning, restarts, host } =- await setup(feed);+ const {+ updater,+ bundle,+ applications,+ setRunning,+ restarts,+ host,+ announced,+ } = await setup(feed);await updater.check();expect(updater.state()).toEqual({ kind: "ready", version: "0.17.0" });+ expect(feed.requested).toEqual([+ `${RELEASES}/latest/download/manifest.json`,+ `${RELEASES}/latest/download/manifest.json.sig`,+ // From the release the signed manifest names, not whatever is latest+ // by the time of the download.+ `${RELEASES}/download/desktop-v0.17.0/Linger-0.17.0-macos-arm64.app.tar.gz`,+ ]);+ expect(announced).toEqual([{ kind: "ready", version: "0.17.0" }]);expect(readFileSync(path.join(bundle, "version"), "utf8")).toBe("0.16.7");setRunning(1);@@ -133,9 +177,11 @@ describe("UpdaterModule", () => {version: "0.17.0",platform: "darwin",arch: "arm64",- appBundle: bundle,+ install: { kind: "app-bundle", appBundle: bundle },downloadDirectory: tempDirectory(),restart: async () => {},+ quit: async () => {},+ openExternal: async () => {},checkDelayMs: 60 * 60_000,});await testHost([stubModule("Config"), stubModule("ComputerDaemon"), next])@@ -155,13 +201,11 @@ describe("UpdaterModule", () => {kind: "failed",error: "Update signature does not match",});- expect(feed.requested).not.toContain(- "/install/desktop/stable/Linger-0.17.0-arm64.tar.gz",- );+ expect(feed.requested).toHaveLength(2);});it("refuses a package that does not match its checksum", async () => {- const feed = release("0.17.0", Buffer.from("new app archivX"));+ const feed = release("0.17.0", { body: Buffer.from("new app archivX") });const { updater, downloads, applications } = await setup(feed);await updater.check();expect(updater.state()).toEqual({@@ -193,53 +237,248 @@ describe("UpdaterModule", () => {await host.stop("quit");});- it("stays idle when the server has nothing newer", async () => {+ it("stays idle when the latest release is not newer", async () => {const feed = release("0.16.7");const { updater } = await setup(feed);await updater.check();expect(updater.state()).toEqual({ kind: "idle" });expect(feed.requested).toHaveLength(2);});++ it("updates a prerelease to its release", async () => {+ const feed = release("0.16.7");+ const { updater } = await setup(feed, { version: "0.16.7-rc.2" });+ await updater.check();+ expect(updater.state()).toEqual({ kind: "ready", version: "0.16.7" });+ });++ it("stays idle when the latest release has no manifest", async () => {+ const feed = release("0.17.0");+ delete feed.files[`${RELEASES}/latest/download/manifest.json.sig`];+ const { updater, announced } = await setup(feed);+ await updater.check();+ expect(updater.state()).toEqual({ kind: "idle" });+ expect(announced).toEqual([]);+ });++ it("reads the feed the config names and refuses one without https", async () => {+ const own = "https://releases.example.com/linger";+ const feed = release("0.17.0", { feed: own });+ const { updater } = await setup(feed, {}, { updateFeedUrl: own });+ await updater.check();+ expect(updater.state()).toEqual({ kind: "ready", version: "0.17.0" });+ expect(feed.requested[0]).toBe(`${own}/latest/download/manifest.json`);++ const plain = await setup(+ release("0.17.0"),+ {},+ { updateFeedUrl: "http://releases.example.com/linger" },+ );+ await plain.updater.check();+ expect(plain.updater.state()).toEqual({+ kind: "failed",+ error: "The update feed must use https",+ });+ });});-describe("UpdaterModule with services on this computer", () => {- it("updates them from the app on request instead of asking the server", async () => {+describe("UpdaterModule with the Windows setup program", () => {+ const SETUP = "Linger-0.17.0-windows-x64-setup.exe";+ const windows = async (spawn: SpawnSetup) => {+ const feed = release("0.17.0", { target: "win32-x64", file: SETUP });+ return {+ feed,+ ...(await setup(feed, {+ platform: "win32",+ arch: "x64",+ install: { kind: "windows-setup" },+ spawn,+ })),+ };+ };+ const recorder = () => {+ const calls: { file: string; args: readonly string[]; options: object }[] =+ [];+ const spawn: SpawnSetup = (file, args, options) => {+ calls.push({ file, args, options });+ const child = Object.assign(new EventEmitter(), { unref: () => {} });+ queueMicrotask(() => child.emit("spawn"));+ return child;+ };+ return { calls, spawn };+ };++ it("runs the verified setup program silently once tasks finish, then quits", async () => {+ const { calls, spawn } = recorder();+ const { updater, downloads, feed, setRunning, quits, restarts } =+ await windows(spawn);+ await updater.check();+ expect(feed.requested.at(-1)).toBe(+ `${RELEASES}/download/desktop-v0.17.0/${SETUP}`,+ );+ expect(updater.state()).toEqual({ kind: "ready", version: "0.17.0" });+ expect(readdirSync(downloads)).toEqual([SETUP]);++ setRunning(2);+ await updater.install();+ expect(updater.state()).toEqual({ kind: "waiting", version: "0.17.0" });+ expect(calls).toEqual([]);++ setRunning(0);+ await waitFor(() => quits() === 1);+ expect(calls).toEqual([+ {+ file: path.join(downloads, SETUP),+ args: ["/S", "/relaunch"],+ options: { detached: true, stdio: "ignore" },+ },+ ]);+ expect(restarts()).toBe(0);+ });++ it("does not run a setup program that changed after its download", async () => {+ const { calls, spawn } = recorder();+ const { updater, downloads, quits } = await windows(spawn);+ await updater.check();+ writeFileSync(path.join(downloads, SETUP), "something else");+ await updater.install();+ expect(updater.state()).toEqual({+ kind: "failed",+ error: "Update package does not match its checksum",+ });+ expect(calls).toEqual([]);+ expect(quits()).toBe(0);+ });++ it("stays when the setup program cannot start", async () => {+ const spawn: SpawnSetup = () => {+ const child = Object.assign(new EventEmitter(), { unref: () => {} });+ queueMicrotask(() => child.emit("error", new Error("spawn EACCES")));+ return child;+ };+ const { updater, quits } = await windows(spawn);+ await updater.check();+ await updater.install();+ expect(updater.state()).toEqual({+ kind: "failed",+ error: "Error: spawn EACCES",+ });+ expect(quits()).toBe(0);+ });+});++describe("UpdaterModule for a download", () => {+ it("links a newer release without downloading it", async () => {+ const feed = release("0.17.0", {+ target: "linux-x64",+ file: "Linger-0.17.0-linux-x64.tar.gz",+ });+ const { updater, opened, announced, downloads } = await setup(feed, {+ platform: "linux",+ arch: "x64",+ install: { kind: "download" },+ });+ await updater.check();+ const available = {+ kind: "available",+ version: "0.17.0",+ url: `${RELEASES}/tag/desktop-v0.17.0`,+ };+ expect(updater.state()).toEqual(available);+ expect(feed.requested).toHaveLength(2);+ expect(() => readdirSync(downloads)).toThrow();++ await updater.check();+ expect(announced).toEqual([available]);+ await updater.install();+ expect(opened).toEqual([available.url]);+ expect(updater.state()).toEqual(available);+ });++ it("stays idle when the release has nothing for this platform", async () => {const feed = release("0.17.0");+ const { updater } = await setup(feed, {+ platform: "linux",+ arch: "x64",+ install: { kind: "download" },+ });+ await updater.check();+ expect(updater.state()).toEqual({ kind: "idle" });+ });+});++describe("UpdaterModule with services on this computer", () => {+ it("offers the services update the app brings and still checks for a newer app", async () => {+ const feed = release("0.16.7");let available = false;let updates = 0;- let announced = 0;- const { updater, host } = await setup(feed, {+ const { updater, host, announced } = await setup(feed, {services: {- serving: (serverUrl) => serverUrl === SERVER,sourceUpdateAvailable: () => available,updateSource: async () => {updates += 1;available = false;},},- announceServices: () => {- announced += 1;- },});- await updater.check();- expect(feed.requested).toEqual([]);- expect(updater.state()).toEqual({ kind: "idle" });-available = true;host.ctx.bus.emit("local-server.changed");- expect(updater.state()).toEqual({- kind: "ready",- version: "0.16.7",- services: true,- });- expect(announced).toBe(1);- expect(updates).toBe(0);+ const services = { kind: "ready", version: "0.16.7", services: true };+ expect(updater.state()).toEqual(services);+ expect(announced).toEqual([services]);++ await updater.check();+ expect(feed.requested).toHaveLength(2);+ expect(updater.state()).toEqual(services);+ expect(announced).toHaveLength(1);await updater.install();expect(updates).toBe(1);expect(updater.state()).toEqual({ kind: "idle" });await host.stop("quit");});++ it("replaces the services update with a newer app, which brings its own", async () => {+ const feed = release("0.17.0");+ const { updater, host } = await setup(feed, {+ services: {+ sourceUpdateAvailable: () => true,+ updateSource: async () => {},+ },+ });+ expect(updater.state()).toMatchObject({ services: true });+ await updater.check();+ expect(updater.state()).toEqual({ kind: "ready", version: "0.17.0" });+ await host.stop("quit");+ });+});++describe("updateInstallFor", () => {+ it("swaps the macOS bundle, runs the Windows setup and links elsewhere", () => {+ const none = () => false;+ expect(+ updateInstallFor(+ "darwin",+ "/Applications/Linger.app/Contents/MacOS/Linger",+ none,+ ),+ ).toEqual({ kind: "app-bundle", appBundle: "/Applications/Linger.app" });+ const installed = "C:\\Users\\a\\AppData\\Local\\Programs\\Linger";+ expect(+ updateInstallFor(+ "win32",+ `${installed}\\Linger.exe`,+ (file) => file === `${installed}\\Uninstall Linger.exe`,+ ),+ ).toEqual({ kind: "windows-setup" });+ // The portable folder has no uninstaller.+ expect(updateInstallFor("win32", "D:\\Linger\\Linger.exe", none)).toEqual({+ kind: "download",+ });+ expect(updateInstallFor("linux", "/opt/linger/linger", none)).toEqual({+ kind: "download",+ });+ });});describe("appBundleOf", () => {diff --git a/apps/desktop/src/main/updater.ts b/apps/desktop/src/main/updater.tsindex 30db7077..9fd89fca 100644--- a/apps/desktop/src/main/updater.ts+++ b/apps/desktop/src/main/updater.ts@@ -1,23 +1,25 @@-import { execFile } from "node:child_process";+import { execFile, spawn as spawnProcess } from "node:child_process";import { createHash } from "node:crypto";-import { createWriteStream } from "node:fs";+import { createReadStream, createWriteStream } from "node:fs";import { mkdir, readdir, rename, rm, stat } from "node:fs/promises";import path from "node:path";-import { Readable, Transform } from "node:stream";+import { Readable } from "node:stream";import { pipeline } from "node:stream/promises";import { promisify } from "node:util";import type { ComputerDaemonModule } from "./computer-daemon.js";import type { Module, ModuleContext } from "./modules.js";import {- FEED_PATH,- MANIFEST_FILE,+ DEFAULT_FEED_URL,ManifestError,- SIGNATURE_FILE,UPDATE_PUBLIC_KEY,compareVersions,+ feedUrls,packageFor,+ packageUrl,+ releasePageUrl,verifyManifest,+ type UpdatePackage,} from "./update-manifest.js";export type UpdateState =@@ -42,27 +44,48 @@ export type UpdateState =readonly version: string;readonly services?: boolean;}+ // A newer release this installation cannot apply itself; `url` is its+ // release page.+ | {+ readonly kind: "available";+ readonly version: string;+ readonly url: string;+ }| { readonly kind: "failed"; readonly error: string };+// How this installation takes a newer release.+export type UpdateInstall =+ // macOS: the installed Linger.app, swapped for the release's app archive.+ | { readonly kind: "app-bundle"; readonly appBundle: string }+ // Windows, installed by the setup program: the release's setup program+ // runs silently over the installation and starts Linger again.+ | { readonly kind: "windows-setup" }+ // Linux and the portable Windows folder: the person downloads the release.+ | { readonly kind: "download" };+export interface UpdaterOptions {readonly version: string;readonly platform: string;readonly arch: string;- // The installed Linger.app. Without one (development, other platforms)- // the updater stays idle.- readonly appBundle: string | undefined;+ // Without one (development) the updater asks no feed.+ readonly install: UpdateInstall | undefined;// Downloads live here until they are installed.readonly downloadDirectory: string;// Stops modules, including the daemon, and relaunches the app from- // appBundle, which by then holds the new version and its daemon.+ // the app bundle, which by then holds the new version and its daemon.readonly restart: () => Promise<void>;- // The services this app runs on this computer, when it serves the window.- // Their updates come with the app, so the feed is not asked.+ // Stops modules and quits without relaunching: the setup program, already+ // running, replaces the files and starts the new version.+ readonly quit: () => Promise<void>;+ readonly openExternal: (url: string) => Promise<void>;+ // The services this app runs on this computer. Their updates come with+ // the app: a newer app brings a newer version for them.readonly services?: LocalServices;- // Tells the person once that an update for those services is ready.- readonly announceServices?: () => void;+ // Tells the person once per version that an update is ready or available.+ readonly announce?: (state: UpdateState) => void;readonly fetch?: typeof fetch;readonly extract?: (archive: string, directory: string) => Promise<void>;+ readonly spawn?: SpawnSetup;readonly publicKey?: string;readonly checkDelayMs?: number;readonly checkIntervalMs?: number;@@ -70,13 +93,25 @@ export interface UpdaterOptions {}export interface LocalServices {- // Whether the window's server is the one on this computer.- serving(serverUrl: string): boolean;// Whether this app brings a newer version than the services run.sourceUpdateAvailable(): boolean;updateSource(): Promise<void>;}+export interface SetupProcess {+ once(event: "spawn", listener: () => void): unknown;+ once(event: "error", listener: (error: Error) => void): unknown;+ unref(): void;+}+export type SpawnSetup = (+ file: string,+ args: readonly string[],+ options: { detached: true; stdio: "ignore" },+) => SetupProcess;++// installer.nsi: /S installs without pages, /relaunch starts Linger after.+export const SETUP_ARGS = ["/S", "/relaunch"] as const;+const CHECK_DELAY_MS = 60_000;const CHECK_INTERVAL_MS = 6 * 60 * 60_000;// A dropped connection should not cost a whole check interval.@@ -93,20 +128,22 @@ const untar = async (archive: string, directory: string): Promise<void> => {export class UpdateError extends Error {}-// Self-update without Squirrel: a signed manifest on the-// deployment's own server, a sha256-checked package, and a bundle swap that-// waits for running tasks. Sign-in and the computer identity live outside the-// bundle, so they carry over.+// Self-update without Squirrel: a signed manifest in the newest GitHub+// Release (or a feed with the same layout), a sha256-checked package from+// that same release, and an install that waits for running tasks. Sign-in and+// the computer identity live outside the installed app, so they carry over.export class UpdaterModule implements Module {readonly name = "Updater";readonly dependsOn = ["Config", "ComputerDaemon"];readonly #options: UpdaterOptions;#ctx: ModuleContext | undefined;#state: UpdateState = { kind: "idle" };- #staged: string | undefined;+ // The unpacked app bundle (macOS) or the downloaded setup program+ // (Windows), with the package it came from.+ #staged: { path: string; pkg: UpdatePackage } | undefined;#timer: NodeJS.Timeout | undefined;#checking: Promise<void> | undefined;- #announced = false;+ readonly #announced = new Set<string>();readonly #unsubscribe: (() => void)[] = [];constructor(options: UpdaterOptions) {@@ -121,7 +158,7 @@ export class UpdaterModule implements Module {);this.#offerServices();}- if (!this.#options.appBundle) return;+ if (!this.#options.install) return;void this.#cleanup();const schedule = (delay: number): void => {this.#timer = setTimeout(() => {@@ -148,19 +185,29 @@ export class UpdaterModule implements Module {}// Fetches and verifies the manifest, then downloads a newer package. Only- // one check runs at a time; a ready update is not checked again.+ // one check runs at a time; a downloaded update is not checked again. A+ // services update on offer is replaced by a newer app, which brings its own.check(): Promise<void> {- if (!this.#options.appBundle || this.#servedLocally())- return Promise.resolve();- if (this.#state.kind !== "idle" && this.#state.kind !== "failed")- return this.#checking ?? Promise.resolve();+ if (!this.#options.install) return Promise.resolve();+ const state = this.#state;+ const settled =+ state.kind === "idle" ||+ state.kind === "failed" ||+ state.kind === "available" ||+ (state.kind === "ready" && state.services);+ if (!settled) return this.#checking ?? Promise.resolve();this.#checking = this.#check().finally(() => (this.#checking = undefined));return this.#checking;}- // "Restart to Update". With tasks running, the restart waits for them.+ // "Restart to Update" or "Download". With tasks running, the restart+ // waits for them.async install(): Promise<void> {const state = this.#state;+ if (state.kind === "available") {+ await this.#options.openExternal(state.url);+ return;+ }if (state.kind !== "ready" && state.kind !== "waiting") return;const runtime = this.#ctx!.get<ComputerDaemonModule>("ComputerDaemon");if (runtime.running() > 0) {@@ -190,19 +237,18 @@ export class UpdaterModule implements Module {return;}this.#setState({ kind: "installing", version: state.version });+ this.#ctx!.log.info("update.installing", { version: state.version });try {- await this.#swap();+ if (this.#options.install?.kind === "windows-setup") {+ await this.#runSetup();+ await this.#options.quit();+ } else {+ await this.#swap();+ await this.#options.restart();+ }} catch (error) {this.#fail("update.install_failed", error);- return;}- this.#ctx!.log.info("update.installing", { version: state.version });- await this.#options.restart();- }-- #servedLocally(): boolean {- const serverUrl = this.#ctx?.config.get().serverUrl;- return !!serverUrl && !!this.#options.services?.serving(serverUrl);}// "Update Linger on This Computer", offered once the app@@ -218,10 +264,7 @@ export class UpdaterModule implements Module {version: this.#options.version,services: true,});- if (!this.#announced) {- this.#announced = true;- this.#options.announceServices?.();- }+ this.#announce("services");}} else if (kind === "ready" && this.#state.services) {this.#setState({ kind: "idle" });@@ -230,18 +273,24 @@ export class UpdaterModule implements Module {async #check(): Promise<void> {const ctx = this.#ctx!;- const serverUrl = ctx.config.get().serverUrl;- if (!serverUrl) return;+ const install = this.#options.install!;+ const feed = ctx.config.get().updateFeedUrl ?? DEFAULT_FEED_URL;this.#setState({ kind: "checking" });try {- const feed = new URL(- FEED_PATH,- serverUrl.endsWith("/") ? serverUrl : `${serverUrl}/`,- );+ if (new URL(feed).protocol !== "https:")+ throw new UpdateError("The update feed must use https");+ const urls = feedUrls(feed);const [bytes, signature] = await Promise.all([- this.#get(new URL(MANIFEST_FILE, feed)),- this.#get(new URL(SIGNATURE_FILE, feed)),+ this.#get(urls.manifest),+ this.#get(urls.signature),]);+ // The newest release was published without a manifest: nothing to+ // offer until one is.+ if (!bytes || !signature) {+ ctx.log.info("update.no_manifest", { feed });+ this.#settle();+ return;+ }const manifest = verifyManifest(bytes,signature.toString("utf8"),@@ -256,85 +305,124 @@ export class UpdaterModule implements Module {compareVersions(manifest.version, this.#options.version) <= 0 ||!pkg) {- this.#setState({ kind: "idle" });+ this.#settle();return;}- this.#setState({ kind: "downloading", version: manifest.version });- const archive = path.join(this.#options.downloadDirectory, pkg.file);- await this.#download(- new URL(pkg.file, feed),- archive,- pkg.sha256,- pkg.size,- );- this.#staged = await this.#extract(archive, manifest.version);- await rm(archive, { force: true });- ctx.log.info("update.ready", { version: manifest.version });- this.#setState({ kind: "ready", version: manifest.version });+ const version = manifest.version;+ if (install.kind === "download") {+ ctx.log.info("update.available", { version });+ this.#setState({+ kind: "available",+ version,+ url: releasePageUrl(feed, version),+ });+ this.#announce(version);+ return;+ }+ this.#setState({ kind: "downloading", version });+ const file = path.join(this.#options.downloadDirectory, pkg.file);+ await this.#download(packageUrl(feed, version, pkg.file), file, pkg);+ this.#staged =+ install.kind === "app-bundle"+ ? { path: await this.#extract(file, version), pkg }+ : { path: file, pkg };+ if (install.kind === "app-bundle") await rm(file, { force: true });+ ctx.log.info("update.ready", { version });+ this.#setState({ kind: "ready", version });+ this.#announce(version);} catch (error) {this.#fail("update.check_failed", error);+ this.#offerServices();}}- async #get(url: URL): Promise<Buffer> {- const response = await (this.#options.fetch ?? fetch)(url, {- redirect: "error",- });+ // Nothing newer: back to idle, or to the services update on offer.+ #settle(): void {+ this.#setState({ kind: "idle" });+ this.#offerServices();+ }++ // Follows redirects: GitHub sends release files from another host. The+ // signature and the checksums, not the host, decide what is trusted.+ // Undefined when the file does not exist.+ async #get(url: URL): Promise<Buffer | undefined> {+ const response = await (this.#options.fetch ?? fetch)(url);+ if (response.status === 404) return undefined;if (!response.ok)throw new UpdateError(`${url.pathname} returned ${response.status}`);return Buffer.from(await response.arrayBuffer());}// Streams to disk while hashing; a mismatch deletes the file.- async #download(- url: URL,- file: string,- sha256: string,- size: number,- ): Promise<void> {+ async #download(url: URL, file: string, pkg: UpdatePackage): Promise<void> {await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });- const response = await (this.#options.fetch ?? fetch)(url, {- redirect: "error",- });+ const response = await (this.#options.fetch ?? fetch)(url);if (!response.ok || !response.body)throw new UpdateError(`${url.pathname} returned ${response.status}`);- const hash = createHash("sha256");- let received = 0;- const meter = new Transform({- transform(chunk: Buffer, _encoding, done) {- received += chunk.length;- if (received > size) {- done(new UpdateError("Update package is larger than announced"));- return;- }- hash.update(chunk);- done(null, chunk);- },- });try {- await pipeline(+ await this.#verify(Readable.fromWeb(response.body as never),- meter,+ pkg,createWriteStream(file, { mode: 0o600 }),);- if (received !== size || hash.digest("hex") !== sha256)- throw new UpdateError("Update package does not match its checksum");} catch (error) {await rm(file, { force: true });throw error;}}+ async #verify(+ source: Readable,+ pkg: UpdatePackage,+ sink?: NodeJS.WritableStream,+ ): Promise<void> {+ const hash = createHash("sha256");+ let received = 0;+ async function* meter(chunks: AsyncIterable<Buffer>) {+ for await (const chunk of chunks) {+ received += chunk.length;+ if (received > pkg.size)+ throw new UpdateError("Update package is larger than announced");+ hash.update(chunk);+ yield chunk;+ }+ }+ if (sink) await pipeline(source, meter, sink);+ else for await (const _chunk of meter(source));+ if (received !== pkg.size || hash.digest("hex") !== pkg.sha256)+ throw new UpdateError("Update package does not match its checksum");+ }++ // Checks the setup program again, since it waited on disk, then starts it+ // detached so it outlives this app, which it replaces.+ async #runSetup(): Promise<void> {+ const staged = this.#staged;+ if (!staged) throw new UpdateError("No update is ready");+ await this.#verify(createReadStream(staged.path), staged.pkg);+ const child = (this.#options.spawn ?? (spawnProcess as SpawnSetup))(+ staged.path,+ SETUP_ARGS,+ { detached: true, stdio: "ignore" },+ );+ await new Promise<void>((resolve, reject) => {+ child.once("spawn", resolve);+ child.once("error", reject);+ });+ child.unref();+ this.#staged = undefined;+ }+// Unpacks next to the installed bundle so the swap is two renames on one// volume.async #extract(archive: string, version: string): Promise<string> {- const parent = path.dirname(this.#options.appBundle!);+ const appBundle = this.#appBundle();+ const parent = path.dirname(appBundle);const staged = path.join(parent, `${STAGED_PREFIX}${version}`);await rm(staged, { recursive: true, force: true });await mkdir(staged, { recursive: true });try {await (this.#options.extract ?? untar)(archive, staged);- const app = path.join(staged, path.basename(this.#options.appBundle!));+ const app = path.join(staged, path.basename(appBundle));if (!(await stat(app)).isDirectory())throw new UpdateError("Update package has no app");return app;@@ -349,8 +437,8 @@ export class UpdaterModule implements Module {// The running process keeps its open files, so the bundle can be renamed// under it. A failed second rename puts the old bundle back.async #swap(): Promise<void> {- const bundle = this.#options.appBundle!;- const staged = this.#staged;+ const bundle = this.#appBundle();+ const staged = this.#staged?.path;if (!staged) throw new UpdateError("No update is ready");const old = path.join(path.dirname(bundle), `${OLD_PREFIX}${Date.now()}`);await rename(bundle, old);@@ -364,19 +452,46 @@ export class UpdaterModule implements Module {await rm(path.dirname(staged), { recursive: true, force: true });}- // Leftovers from an earlier update: the replaced bundle and unused stages.+ #appBundle(): string {+ const install = this.#options.install;+ if (install?.kind !== "app-bundle")+ throw new UpdateError("This installation has no app bundle");+ return install.appBundle;+ }++ // Leftovers from an earlier update: downloads, the replaced bundle and+ // unused stages.async #cleanup(): Promise<void> {- const parent = path.dirname(this.#options.appBundle!);+ const leftovers: string[] = [];+ try {+ for (const name of await readdir(this.#options.downloadDirectory))+ leftovers.push(path.join(this.#options.downloadDirectory, name));+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "ENOENT")+ this.#ctx?.log.warn("update.cleanup_failed", { error: String(error) });+ }try {- for (const name of await readdir(parent)) {- if (name.startsWith(OLD_PREFIX) || name.startsWith(STAGED_PREFIX))- await rm(path.join(parent, name), { recursive: true, force: true });+ const install = this.#options.install;+ if (install?.kind === "app-bundle") {+ const parent = path.dirname(install.appBundle);+ for (const name of await readdir(parent)) {+ if (name.startsWith(OLD_PREFIX) || name.startsWith(STAGED_PREFIX))+ leftovers.push(path.join(parent, name));+ }}+ for (const leftover of leftovers)+ await rm(leftover, { recursive: true, force: true });} catch (error) {this.#ctx?.log.warn("update.cleanup_failed", { error: String(error) });}}+ #announce(key: string): void {+ if (this.#announced.has(key)) return;+ this.#announced.add(key);+ this.#options.announce?.(this.#state);+ }+#fail(event: string, error: unknown): void {const message =error instanceof UpdateError || error instanceof ManifestError@@ -394,7 +509,29 @@ export class UpdaterModule implements Module {// The bundle that contains this executable on macOS, e.g.// /Applications/Linger.app for /Applications/Linger.app/Contents/MacOS/Linger.-export const appBundleOf = (execPath: string): string | undefined => {+export function appBundleOf(execPath: string): string | undefined {const bundle = path.resolve(execPath, "../../..");return bundle.endsWith(".app") ? bundle : undefined;-};+}++// How a packaged app at execPath takes updates. A Windows installation from+// the setup program has its uninstaller beside Linger.exe (installer.nsi);+// the portable folder has none.+export function updateInstallFor(+ platform: string,+ execPath: string,+ exists: (file: string) => boolean,+): UpdateInstall {+ if (platform === "darwin") {+ const appBundle = appBundleOf(execPath);+ if (appBundle) return { kind: "app-bundle", appBundle };+ }+ if (+ platform === "win32" &&+ exists(+ path.win32.join(path.win32.dirname(execPath), "Uninstall Linger.exe"),+ )+ )+ return { kind: "windows-setup" };+ return { kind: "download" };+}diff --git a/apps/desktop/src/main/windows-installer.test.ts b/apps/desktop/src/main/windows-installer.test.tsindex f259b7e1..ee418ce7 100644--- a/apps/desktop/src/main/windows-installer.test.ts+++ b/apps/desktop/src/main/windows-installer.test.ts@@ -92,3 +92,15 @@ it("stops the services again when Retry follows a running Linger", () => {"Goto retry",);});++it("starts Linger after a silent install only when asked to relaunch", () => {+ order(+ block("Function .onInstSuccess", "FunctionEnd"),+ "${GetParameters} $0",+ '${GetOptions} $0 "/relaunch" $1',+ "IfErrors done",+ "Exec '\"$INSTDIR\\Linger.exe\"'",+ "done:",+ );+ expect(script).toContain('!include "FileFunc.nsh"');+});diff --git a/docs/desktop-release.md b/docs/desktop-release.mdindex 5cd2160d..b1a1c6c9 100644--- a/docs/desktop-release.md+++ b/docs/desktop-release.md@@ -76,7 +76,7 @@ that runs the workflow:| `MACOS_DEVELOPER_ID_P12_BASE64` | secret | no | Base64 of the Developer ID `.p12`. Without it the app is signed ad hoc. || `MACOS_DEVELOPER_ID_PASSWORD` | secret | with the `.p12` | Password of that `.p12`. || `MACOS_NOTARY_KEY_JSON` | secret | no | App Store Connect API key JSON; needs the Developer ID. |-| `DESKTOP_UPDATE_KEY_PEM` | secret | no | Ed25519 private key (PEM) for the macOS update feed. Without it no feed is built. |+| `DESKTOP_UPDATE_KEY_PEM` | secret | for auto-update | Ed25519 private key (PEM) that signs `manifest.json`. Without it the release has no manifest and installed apps are not offered it. || `WINDOWS_SIGNING_P12_BASE64` | secret | no | Base64 of an Authenticode `.p12`. Without it the setup program is unsigned. || `WINDOWS_SIGNING_PASSWORD` | secret | with the `.p12` | Password of that `.p12`. |@@ -111,20 +111,96 @@ gh release upload native-deps <archive> --repo simplexai-labs/linger## Release Files-| File | Contents |-| ---------------------------------------------- | --------------------------------------------------------------- |-| `Linger-<version>-macos-arm64.dmg` | macOS 14.0 or later, Apple silicon |-| `Linger-<version>-linux-x64.tar.gz` | Linux x64 (glibc 2.35 or newer for the bundled Native services) |-| `Linger-<version>-windows-x64-setup.exe` | Windows x64 per-user installer |-| `Linger-<version>-windows-x64-portable.zip` | Windows x64 folder to run without installing |-| `Linger-<version>-macos-arm64-update-feed.tar` | only with the update key: the macOS self-update feed |-| `SHA256SUMS.txt` | SHA-256 of every file above |+| File | Contents |+| ------------------------------------------- | --------------------------------------------------------------- |+| `Linger-<version>-macos-arm64.dmg` | macOS 14.0 or later, Apple silicon |+| `Linger-<version>-linux-x64.tar.gz` | Linux x64 (glibc 2.35 or newer for the bundled Native services) |+| `Linger-<version>-windows-x64-setup.exe` | Windows x64 per-user installer |+| `Linger-<version>-windows-x64-portable.zip` | Windows x64 folder to run without installing |+| `Linger-<version>-macos-arm64.app.tar.gz` | macOS app the updater swaps in |+| `manifest.json`, `manifest.json.sig` | only with the update key: the [auto-update](#auto-update) feed |+| `SHA256SUMS.txt` | SHA-256 of every file above |Each package bundles the source package, PostgreSQL, voice tools, TeamHub andthe Native services as described in-[Packaging Details](#packaging-details). The update feed holds-`manifest.json`, `manifest.json.sig` and the app archive; unpack it into the-server's `install/desktop/stable/`.+[Packaging Details](#packaging-details).++## Auto-update++Installed apps update from the GitHub Releases themselves+(`apps/desktop/src/main/updater.ts`). Shortly after start and then every six+hours, the app downloads+`https://github.com/simplexai-labs/linger/releases/latest/download/manifest.json`+and its `.sig`, checks the Ed25519 signature against `UPDATE_PUBLIC_KEY` in+`update-manifest.ts` and compares the manifest's version with its own+(semver; a prerelease is below its release). Only a newer version is offered,+and a release without a manifest (404) is ignored. Since a prerelease never+becomes the latest release, only stable releases reach installed apps.++`manifest.json` (schema 2) names each platform's package of the same release+with its size and SHA-256:++```json+{+ "schema": 2,+ "version": "0.16.36",+ "packages": {+ "darwin-arm64": {+ "file": "Linger-0.16.36-macos-arm64.app.tar.gz",+ "sha256": "…",+ "size": 123+ },+ "linux-x64": {+ "file": "Linger-0.16.36-linux-x64.tar.gz",+ "sha256": "…",+ "size": 123+ },+ "win32-x64": {+ "file": "Linger-0.16.36-windows-x64-setup.exe",+ "sha256": "…",+ "size": 123+ }+ }+}+```++The app downloads the package from `releases/download/desktop-v<version>/` and+checks its size and SHA-256 while downloading. What happens next depends on+how Linger was installed:++| Install | Update |+| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| macOS `Linger.app` | The archive is unpacked beside the app. "Restart to Update" waits for running tasks, swaps the bundle and relaunches. |+| Windows setup program | The setup program is downloaded. "Restart to Update" waits for running tasks, checks the file again, starts it with `/S /relaunch` and quits; the installer stops the services, replaces the app and starts it. |+| Windows portable folder | No download: the tray offers "Download Linger <version>…", which opens the release page. |+| Linux | The same as the portable folder. |++A system notification announces each new version once, and the tray shows the+state; after a failure "Try Updating Again" checks at once. Without a newer app, the tray+still offers to update the local services when they have a newer source; a+newer app replaces that offer, because it brings its own source.++`updateFeedUrl` in the desktop config (`config.json` in the app's data+folder) points the app at another releases URL with the same layout, such as+`https://github.com/<owner>/<repo>/releases`; it must be https and its+manifest must be signed by the same key.++### Signing key++The `release` job signs `manifest.json` with `DESKTOP_UPDATE_KEY_PEM`+(`desktop-release.sh manifest`) after all three packages are built, and+refuses a key whose public half is not `UPDATE_PUBLIC_KEY`, since installed+apps would reject its signature. Without the secret the job logs a warning and+publishes the release without a manifest. Make a new pair only when the key is+lost, and ship the new public key in a release first:++```sh+openssl genpkey -algorithm ed25519 -out ed25519.pem+openssl pkey -in ed25519.pem -pubout+```++Apps of 0.1.2 and older read their update feed from the connected server and+are not offered GitHub releases; install one release by hand there.## Local Build@@ -133,13 +209,16 @@ On Linux x64 with Docker, Node, pnpm, Go and Python 3:```shDESKTOP_VERSION=0.16.36-rc.1 RCODESIGN=/path/to/rcodesign \scripts/ci/desktop-release.sh build darwin-arm64+DESKTOP_UPDATE_KEY=/path/to/ed25519.pem \+ scripts/ci/desktop-release.sh manifest .linger-runtime/desktop-release/assets 0.16.36-rc.1scripts/ci/desktop-release.sh checksums .linger-runtime/desktop-release/assets 0.16.36-rc.1```With the archives already in `LINGER_NATIVE_POSTGRES_DIR` (default`~/.cache/linger-desktop`), `LINGER_NATIVE_DEPS_URL` is not needed.-`checksums` refuses a folder without the DMG, the Linux archive and the setup-program of that version.+`manifest` needs the macOS app archive, the Linux archive and the setup program+of that version; `checksums` refuses a folder without the DMG, the Linux+archive and the setup program.## Packaging Detailsdiff --git a/scripts/ci/desktop-release.sh b/scripts/ci/desktop-release.shindex 649f649f..33ac638e 100755--- a/scripts/ci/desktop-release.sh+++ b/scripts/ci/desktop-release.sh@@ -14,6 +14,8 @@ set -euo pipefail# desktop-release.sh compile <target> node build.mjs for the target (Node, pnpm, Go)# desktop-release.sh package <target> package.py for the target (Python, Docker)# desktop-release.sh build <target> fetch-native, compile and package+# desktop-release.sh manifest <dir> <version> write the signed update manifest+# (manifest.json and .sig) into <dir># desktop-release.sh checksums <dir> <version> write <dir>/SHA256SUMS.txt# desktop-release.sh gitlab-upload <dir> <version># upload <dir>'s files to a GitLab generic@@ -35,7 +37,8 @@ set -euo pipefail# Developer ID Application .p12 and a file with its# password; without them the app is signed ad hoc# MACOS_NOTARY_KEY App Store Connect API key JSON; notarizes and staples-# DESKTOP_UPDATE_KEY Ed25519 PEM file that signs the macOS update feed+# DESKTOP_UPDATE_KEY Ed25519 PEM file that signs the update manifest; without+# it the release has no manifest and offers no update# WINDOWS_SIGNING_P12, WINDOWS_SIGNING_PASSWORD_FILE# Authenticode .p12 and a file with its password for# the setup program (osslsigncode); unsigned without@@ -61,7 +64,7 @@ die() {usage() {echo "Usage: $0 version <tag> | fetch-native|compile|package|build <target>" \- "| checksums <dir> <version> | github-release <dir> <tag> <version>" \+ "| manifest|checksums <dir> <version> | github-release <dir> <tag> <version>" \"| gitlab-upload <dir> <version>" >&2exit 2}@@ -207,17 +210,11 @@ package_darwin() {elseecho "desktop-release: no Developer ID; the app gets an ad-hoc signature" >&2fi- if [[ -n "${DESKTOP_UPDATE_KEY:-}" ]]; then- args+=(--update-key "$DESKTOP_UPDATE_KEY")- else- echo "desktop-release: no DESKTOP_UPDATE_KEY; no macOS update feed" >&2- fi+ args+=(--update-archive)(cd "$desktop" && python3 packaging/mac/package.py "${args[@]}")mv "$pkg/Linger-$version-arm64.dmg" "$assets/Linger-$version-macos-arm64.dmg"- # The feed's three files go to the server's install/desktop/stable/ as they are.- if [[ -d "$pkg/update" ]]; then- tar -cf "$assets/Linger-$version-macos-arm64-update-feed.tar" -C "$pkg/update" .- fi+ # The installed app replaces itself with this archive (updater.ts).+ mv "$pkg/Linger-$version-arm64.app.tar.gz" "$assets/Linger-$version-macos-arm64.app.tar.gz"}package_linux() {@@ -271,8 +268,70 @@ cmd_build() {cmd_package "$@"}+# The package each platform's installed app updates from, keyed like+# packageFor in apps/desktop/src/main/update-manifest.ts. Linux and the+# portable Windows folder only link to the release.+update_packages='darwin-arm64:macos-arm64.app.tar.gz linux-x64:linux-x64.tar.gz win32-x64:windows-x64-setup.exe'++# manifest.json lists every platform's package with its size and sha256, and+# manifest.json.sig is its Ed25519 signature, made with DESKTOP_UPDATE_KEY.+# Installed apps read both from the latest release and download the package+# from the release of the version it names. Without the key the release goes+# out without them, and no installed app is offered it.+cmd_manifest() {+ local dir="${1:-}" version="${2:-}" entry target suffix packages=()+ [[ -d "$dir" ]] || die "manifest needs the folder holding the release files"+ [[ "$version" =~ $version_pattern ]] || die "manifest needs the release version"+ rm -f "$dir/manifest.json" "$dir/manifest.json.sig"+ if [[ -z "${DESKTOP_UPDATE_KEY:-}" ]]; then+ echo "::warning::DESKTOP_UPDATE_KEY_PEM is not set: this release has no update manifest, so installed apps will not update to $version (docs/desktop-release.md)."+ return 0+ fi+ [[ -f "$DESKTOP_UPDATE_KEY" ]] || die "DESKTOP_UPDATE_KEY names no file"+ for entry in $update_packages; do+ target="${entry%%:*}"+ suffix="${entry#*:}"+ [[ -f "$dir/Linger-$version-$suffix" ]] || die "$dir has no Linger-$version-$suffix"+ packages+=("$target" "Linger-$version-$suffix")+ done+ # The key file is read only here; the built-in public key decides whether+ # installed apps would accept the signature.+ node - "$dir" "$version" "$DESKTOP_UPDATE_KEY" "$desktop/src/main/update-manifest.ts" "${packages[@]}" <<'NODE' ||+const crypto = require("crypto");+const fs = require("fs");+const path = require("path");+const [dir, version, keyFile, source, ...pairs] = process.argv.slice(2);+const packages = {};+for (let i = 0; i < pairs.length; i += 2) {+ const bytes = fs.readFileSync(path.join(dir, pairs[i + 1]));+ packages[pairs[i]] = {+ file: pairs[i + 1],+ sha256: crypto.createHash("sha256").update(bytes).digest("hex"),+ size: bytes.length,+ };+}+const manifest = Buffer.from(+ JSON.stringify({ schema: 2, version, packages }, null, 2) + "\n",+);+const key = crypto.createPrivateKey(fs.readFileSync(keyFile));+const signature = crypto.sign(null, manifest, key);+const builtIn = /-----BEGIN PUBLIC KEY-----[\s\S]+?-----END PUBLIC KEY-----/.exec(+ fs.readFileSync(source, "utf8"),+);+if (!builtIn || !crypto.verify(null, manifest, crypto.createPublicKey(builtIn[0]), signature)) {+ console.error("desktop-release: DESKTOP_UPDATE_KEY is not the key of UPDATE_PUBLIC_KEY in update-manifest.ts; installed apps would refuse this manifest");+ process.exit(1);+}+fs.writeFileSync(path.join(dir, "manifest.json"), manifest);+fs.writeFileSync(path.join(dir, "manifest.json.sig"), signature.toString("base64") + "\n");+console.log(`desktop-release: signed manifest.json for ${version}: ${Object.keys(packages).sort().join(", ")}`);+NODE+ die "could not write the update manifest"+}+# Every release ships the three installers; SHA256SUMS.txt covers each file-# of the version, extra ones such as the portable zip and update feed included.+# of the version, extra ones such as the portable zip and the app archive+# included, and the update manifest and its signature when there are.cmd_checksums() {local dir="${1:-}" version="${2:-}" required file files=()[[ -d "$dir" ]] || die "checksums needs the folder holding the release files"@@ -282,7 +341,7 @@ cmd_checksums() {donewhile IFS= read -r file; dofiles+=("$(basename "$file")")- done < <(find "$dir" -maxdepth 1 -type f -name "Linger-$version-*" | LC_ALL=C sort)+ done < <(find "$dir" -maxdepth 1 -type f \( -name "Linger-$version-*" -o -name manifest.json -o -name manifest.json.sig \) | LC_ALL=C sort): >"$dir/SHA256SUMS.txt.part"for file in "${files[@]}"; doprintf '%s %s\n' "$(sha256_of "$dir/$file")" "$file" >>"$dir/SHA256SUMS.txt.part"@@ -367,6 +426,7 @@ case "$command" incompile) cmd_compile "$@" ;;package) cmd_package "$@" ;;build) cmd_build "$@" ;;+ manifest) cmd_manifest "$@" ;;checksums) cmd_checksums "$@" ;;gitlab-upload) cmd_gitlab_upload "$@" ;;github-release) cmd_github_release "$@" ;;diff --git a/scripts/ci/desktop-release.test.ts b/scripts/ci/desktop-release.test.tsindex 49fe2945..7861a4b9 100644--- a/scripts/ci/desktop-release.test.ts+++ b/scripts/ci/desktop-release.test.ts@@ -1,7 +1,10 @@import { spawnSync } from "node:child_process";-import { createHash } from "node:crypto";+import { createHash, generateKeyPairSync, verify } from "node:crypto";import {chmodSync,+ copyFileSync,+ existsSync,+ mkdirSync,mkdtempSync,readFileSync,rmSync,@@ -15,8 +18,8 @@ import { afterEach, describe, expect, it } from "vitest";const script = join(process.cwd(), "scripts/ci/desktop-release.sh");const temporary: string[] = [];-function run(args: string[], env: Record<string, string> = {}) {- const result = spawnSync("bash", [script, ...args], {+function run(args: string[], env: Record<string, string> = {}, file = script) {+ const result = spawnSync("bash", [file, ...args], {encoding: "utf8",env: { PATH: process.env.PATH ?? "", HOME: tmpdir(), ...env },});@@ -122,6 +125,122 @@ describe("desktop-release.sh checksums", () => {});});+describe("desktop-release.sh manifest", () => {+ const version = "0.16.33";+ const packages = {+ "darwin-arm64": `Linger-${version}-macos-arm64.app.tar.gz`,+ "linux-x64": `Linger-${version}-linux-x64.tar.gz`,+ "win32-x64": `Linger-${version}-windows-x64-setup.exe`,+ };+ const release = () => {+ const dir = folder();+ for (const name of Object.values(packages))+ writeFileSync(join(dir, name), name);+ writeFileSync(join(dir, `Linger-${version}-macos-arm64.dmg`), "dmg");+ return dir;+ };+ // A copy of the script beside an update-manifest.ts holding a throwaway+ // key's public half, so the test never needs the release key.+ const checkout = () => {+ const { privateKey, publicKey } = generateKeyPairSync("ed25519");+ const root = folder();+ mkdirSync(join(root, "scripts/ci"), { recursive: true });+ mkdirSync(join(root, "apps/desktop/src/main"), { recursive: true });+ copyFileSync(script, join(root, "scripts/ci/desktop-release.sh"));+ const publicPem = publicKey.export({ type: "spki", format: "pem" });+ writeFileSync(+ join(root, "apps/desktop/src/main/update-manifest.ts"),+ `export const UPDATE_PUBLIC_KEY = \`${publicPem.toString().trim()}\`;\n`,+ );+ const key = join(folder(), "update.pem");+ writeFileSync(+ key,+ privateKey.export({ type: "pkcs8", format: "pem" }).toString(),+ );+ return {+ script: join(root, "scripts/ci/desktop-release.sh"),+ key,+ publicKey,+ };+ };++ it("signs a manifest of every platform's package", () => {+ const dir = release();+ const repo = checkout();++ const result = run(+ ["manifest", dir, version],+ { DESKTOP_UPDATE_KEY: repo.key },+ repo.script,+ );++ expect(result.status).toBe(0);+ const bytes = readFileSync(join(dir, "manifest.json"));+ const signature = readFileSync(join(dir, "manifest.json.sig"), "utf8");+ expect(+ verify(null, bytes, repo.publicKey, Buffer.from(signature, "base64")),+ ).toBe(true);+ expect(JSON.parse(bytes.toString())).toEqual({+ schema: 2,+ version,+ packages: Object.fromEntries(+ Object.entries(packages).map(([target, file]) => [+ target,+ {+ file,+ sha256: createHash("sha256").update(file).digest("hex"),+ size: file.length,+ },+ ]),+ ),+ });++ run(["checksums", dir, version]);+ const sums = readFileSync(join(dir, "SHA256SUMS.txt"), "utf8");+ expect(sums).toContain(" manifest.json\n");+ expect(sums).toContain(" manifest.json.sig\n");+ });++ it("warns and writes nothing without the key", () => {+ const dir = release();++ const result = run(["manifest", dir, version]);++ expect(result.status).toBe(0);+ expect(result.stdout).toContain("::warning::DESKTOP_UPDATE_KEY_PEM");+ expect(existsSync(join(dir, "manifest.json"))).toBe(false);+ });++ it("refuses a key installed apps would not accept", () => {+ const dir = release();+ // The throwaway key against this checkout's UPDATE_PUBLIC_KEY.+ const other = checkout();++ const result = run(["manifest", dir, version], {+ DESKTOP_UPDATE_KEY: other.key,+ });++ expect(result.status).toBe(1);+ expect(result.stderr).toContain("UPDATE_PUBLIC_KEY");+ expect(existsSync(join(dir, "manifest.json"))).toBe(false);+ });++ it("refuses a release without a platform's package", () => {+ const dir = release();+ rmSync(join(dir, packages["darwin-arm64"]));+ const repo = checkout();++ const result = run(+ ["manifest", dir, version],+ { DESKTOP_UPDATE_KEY: repo.key },+ repo.script,+ );++ expect(result.status).toBe(1);+ expect(result.stderr).toContain(packages["darwin-arm64"]);+ });+});+describe("desktop-release.sh build", () => {it("needs a known target and a version", () => {expect(