Files
photoreport/apps/api/src/desktop/updates.ts
spark 3860e2e1e0
ci / rust (push) Successful in 7m47s
ci / typescript (push) Successful in 10m44s
Desktop updates never fail in silence: the page asks the server and offers the installer
The 0.3.5 app showed no update banner: the shell's own check gave no answer and the error was swallowed.
Now the error is shown, and the page also asks the update endpoint itself (installed version from the app)
and, when the shell cannot update itself, offers the release's full installer (.dmg). The API names it in
the update answer (`installer`, ignored by Tauri).

Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-13 19:36:12 +01:00

174 lines
7.5 KiB
TypeScript

import { Readable } from "node:stream";
import type { FastifyInstance } from "fastify";
import { z } from "zod";
/**
* Updates of the desktop shell (apps/desktop, `updater.rs`). Releases are Gitea releases tagged `desktop-vX.Y.Z`;
* each build job attaches its installer, the installer's signature and an `update-<target>-<arch>.json` manifest
* (`infra/desktop/update-manifest.mjs`). The repository is private, so the API reads releases with a read-only
* token and hands the installer through: the desktop app never needs a Gitea account.
*/
export interface DesktopReleaseConfig {
/** Gitea API base of the repository, e.g. https://git.bitreport.pt/api/v1/repos/BitReport.pt/photoreport */
api: string;
token: string;
}
interface GiteaAsset {
id: number;
name: string;
browser_download_url: string;
}
interface GiteaRelease {
id: number;
tag_name: string;
draft: boolean;
prerelease: boolean;
body: string | null;
published_at: string | null;
assets: GiteaAsset[];
}
/** What a build job writes next to its installer. */
const Manifest = z.object({
version: z.string(),
file: z.string().min(1),
signature: z.string().min(10),
notes: z.string().optional(),
pub_date: z.string().optional(),
});
const CACHE_MS = 5 * 60_000;
/** 1.10.0 > 1.9.3; a pre-release suffix sorts before its release. */
export function newer(candidate: string, current: string): boolean {
const parse = (v: string) => {
const [core, pre] = v.replace(/^v/, "").split("-", 2);
return { nums: (core ?? "").split(".").map((n) => Number.parseInt(n, 10) || 0), pre: pre ?? null };
};
const a = parse(candidate);
const b = parse(current);
for (let i = 0; i < 3; i++) {
const d = (a.nums[i] ?? 0) - (b.nums[i] ?? 0);
if (d !== 0) return d > 0;
}
if (a.pre === b.pre) return false;
if (a.pre === null) return true;
if (b.pre === null) return false;
return a.pre > b.pre;
}
/** The full installer a person downloads and opens, per platform. */
const INSTALLER: Record<string, RegExp> = { darwin: /\.dmg$/, windows: /\.msi$|-setup\.exe$/, linux: /\.AppImage$/ };
export class DesktopReleases {
private cache: { at: number; releases: GiteaRelease[] } | null = null;
constructor(
private readonly config: DesktopReleaseConfig,
private readonly fetchImpl: typeof fetch = fetch,
) {}
private headers() {
return { authorization: `token ${this.config.token}`, accept: "application/json" };
}
/** Published `desktop-v*` releases, newest first. */
async releases(): Promise<GiteaRelease[]> {
if (this.cache && Date.now() - this.cache.at < CACHE_MS) return this.cache.releases;
const res = await this.fetchImpl(`${this.config.api.replace(/\/$/, "")}/releases?limit=50`, { headers: this.headers() });
if (!res.ok) throw new Error(`gitea releases: ${res.status}`);
const all = ((await res.json()) as GiteaRelease[]).filter((r) => !r.draft && !r.prerelease && r.tag_name.startsWith("desktop-v"));
all.sort((x, y) => (newer(x.tag_name.slice(9), y.tag_name.slice(9)) ? -1 : 1));
this.cache = { at: Date.now(), releases: all };
return all;
}
/** The newest release that has this platform's update (a newer one may still be building, or wait for its Mac). */
private async forPlatform(target: string, arch: string): Promise<{ release: GiteaRelease; manifest: GiteaAsset } | null> {
// Universal macOS builds serve both Apple chips.
const names = [`update-${target}-${arch}.json`, ...(target === "darwin" ? ["update-darwin-universal.json"] : [])];
for (const release of await this.releases()) {
const manifest = names.map((n) => release.assets.find((a) => a.name === n)).find(Boolean);
if (manifest) return { release, manifest };
}
return null;
}
private async download(asset: GiteaAsset): Promise<Response> {
const res = await this.fetchImpl(asset.browser_download_url, { headers: { authorization: `token ${this.config.token}` } });
if (!res.ok) throw new Error(`gitea asset ${asset.name}: ${res.status}`);
return res;
}
/**
* Tauri's dynamic update answer for one platform, or null when there is nothing newer. `installer` (ignored by
* Tauri) is the full installer of the same release: the app offers it when it cannot update itself.
*/
async updateFor(
target: string,
arch: string,
current: string,
): Promise<{ version: string; notes: string; pub_date?: string; url: string; signature: string; installer?: string } | null> {
const found = await this.forPlatform(target, arch);
if (!found) return null;
const { release } = found;
const manifest = Manifest.parse(await (await this.download(found.manifest)).json());
if (!newer(manifest.version, current)) return null;
if (!release.assets.some((a) => a.name === manifest.file)) return null;
const installer = release.assets.find((a) => INSTALLER[target]?.test(a.name));
return {
version: manifest.version,
notes: manifest.notes ?? release.body ?? "",
...(manifest.pub_date ?? release.published_at ? { pub_date: (manifest.pub_date ?? release.published_at)! } : {}),
url: `/v1/desktop/download/${release.id}/${encodeURIComponent(manifest.file)}`,
signature: manifest.signature,
...(installer ? { installer: `/v1/desktop/download/${release.id}/${encodeURIComponent(installer.name)}` } : {}),
};
}
/** The installer itself, streamed from a desktop release. */
async file(releaseId: number, name: string): Promise<{ body: Readable; size: string | null } | null> {
const release = (await this.releases()).find((r) => r.id === releaseId);
if (!release) return null;
const asset = release.assets.find((a) => a.name === name);
if (!asset || /\.json$/.test(name)) return null;
const res = await this.download(asset);
if (!res.body) return null;
return { body: Readable.fromWeb(res.body as never), size: res.headers.get("content-length") };
}
}
const Platform = z.object({
target: z.enum(["darwin", "windows", "linux"]),
arch: z.enum(["x86_64", "aarch64", "i686", "armv7"]),
version: z.string().regex(/^\d+\.\d+\.\d+([-.+][\w.-]+)?$/),
});
export async function registerDesktopRoutes(app: FastifyInstance, deps: { releases: DesktopReleases | undefined; publicApiUrl: string }) {
const { releases } = deps;
app.get("/v1/desktop/update/:target/:arch/:version", { config: { rateLimit: { max: 60, timeWindow: "1 minute" } } }, async (req, reply) => {
const { target, arch, version } = Platform.parse(req.params);
if (!releases) return reply.code(204).send();
try {
const update = await releases.updateFor(target, arch, version);
if (!update) return reply.code(204).send();
const base = deps.publicApiUrl.replace(/\/$/, "");
return { ...update, url: `${base}${update.url}`, ...(update.installer ? { installer: `${base}${update.installer}` } : {}) };
} catch (err) {
req.log.warn({ err }, "desktop update check failed");
return reply.code(204).send();
}
});
app.get("/v1/desktop/download/:releaseId/:name", async (req, reply) => {
const { releaseId, name } = z.object({ releaseId: z.coerce.number().int().positive(), name: z.string().min(1).max(200) }).parse(req.params);
const file = releases ? await releases.file(releaseId, name) : null;
if (!file) return reply.code(404).send({ error: "not_found" });
if (file.size) reply.header("content-length", file.size);
return reply.header("content-type", "application/octet-stream").header("content-disposition", `attachment; filename="${name.replace(/[^\w.-]+/g, "_")}"`).send(file.body);
});
}