Skip to content

Build your personal knowledge base with Trilium Notes

ci(nix): sync the flake's Electron pin automatically

Elian Doran12475a811bb6
diff --git a/.github/workflows/dev.yml b/.github/workflows/dev.yml
index 1d246eff20..0c15281858 100644
--- a/.github/workflows/dev.yml
+++ b/.github/workflows/dev.yml
@@ -43,6 +43,9 @@ jobs:
- name: Typecheck
run: pnpm typecheck
+ - name: Run the repo-script tests
+ run: pnpm scripts:test
+
- name: Run the client-side tests
id: test-client
run: pnpm run --filter=client test --coverage
diff --git a/.github/workflows/update-nix-flake.yml b/.github/workflows/update-nix-flake.yml
new file mode 100644
index 0000000000..76754b174f
--- /dev/null
+++ b/.github/workflows/update-nix-flake.yml
@@ -0,0 +1,88 @@
+name: Update Nix flake
+
+# Keeps flake.nix in step with the rest of the repo. Today that means one thing:
+# the pinned Electron binary.
+#
+# nixpkgs lags behind the Electron releases we track, so the flake builds the exact
+# pinned version from Electron's official binary release — and refuses to evaluate
+# once the pin and apps/desktop/package.json drift apart:
+#
+# error: flake.nix pins Electron 43.2.0, but apps/desktop/package.json wants 43.3.0
+#
+# Renovate bumps the devDependency but knows nothing about the pin, so this job
+# closes the gap: it rewrites the pin and opens a PR. Triggered by the bump itself
+# rather than on a schedule — a weekly job would leave the flake unevaluatable for
+# up to a week, where this reacts within minutes of the bump landing on main.
+on:
+ push:
+ branches:
+ - main
+ paths:
+ - apps/desktop/package.json
+ workflow_dispatch:
+
+# Two bumps in quick succession would otherwise race to push the same PR branch,
+# and it is the later package.json state that is worth acting on.
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+
+permissions:
+ contents: read
+
+jobs:
+ electron-pin:
+ name: Sync the pinned Electron binary
+ runs-on: ubuntu-latest
+ permissions:
+ contents: write
+ pull-requests: write
+ steps:
+ - uses: actions/checkout@v7
+ - uses: pnpm/action-setup@v6
+ - name: Set up node & dependencies
+ uses: actions/setup-node@v7
+ with:
+ node-version: 24
+ cache: "pnpm"
+ - name: Install dependencies
+ run: pnpm install --frozen-lockfile
+ - name: Set up Nix
+ # The headers hash is a NAR hash of the unpacked tarball, so only Nix can
+ # compute it — and the verification step below needs a working builder.
+ uses: cachix/install-nix-action@v31
+ with:
+ extra_nix_config: |
+ experimental-features = nix-command flakes
+ - name: Refresh the pin
+ id: refresh
+ run: |
+ pnpm chore:update-flake-electron
+ git diff --quiet -- flake.nix && changed=false || changed=true
+ echo "changed=$changed" >> "$GITHUB_OUTPUT"
+ - name: Read the wanted Electron version
+ id: electron
+ run: echo "version=$(node -p "require('./apps/desktop/package.json').devDependencies.electron")" >> "$GITHUB_OUTPUT"
+ - name: Verify the pinned binary actually builds
+ # Fetching both derivations checks the written hashes against the real
+ # artifacts, so a bad hash fails here rather than in someone's `nix build`.
+ if: steps.refresh.outputs.changed == 'true'
+ run: nix build --no-link '.#electron' '.#electron.headers'
+ - name: Open a PR
+ if: steps.refresh.outputs.changed == 'true'
+ uses: peter-evans/create-pull-request@v8
+ with:
+ add-paths: flake.nix
+ branch: chore/update-flake-electron
+ commit-message: "build(nix): pin Electron ${{ steps.electron.outputs.version }} in the flake"
+ title: "build(nix): pin Electron ${{ steps.electron.outputs.version }} in the flake"
+ body: |
+ `apps/desktop/package.json` moved to Electron
+ ${{ steps.electron.outputs.version }}, so `flake.nix` needs the matching
+ binary pin — without it the flake refuses to evaluate.
+
+ Regenerated by `pnpm chore:update-flake-electron`: the per-platform
+ checksums come from the release's own `SHASUMS256.txt`, the headers hash
+ from `nix-prefetch-url --unpack`. CI verified them by building
+ `.#electron` and `.#electron.headers` before opening this PR.
+ labels: dependencies
diff --git a/flake.nix b/flake.nix
index de6ad84088..b5d234fad0 100644
--- a/flake.nix
+++ b/flake.nix
@@ -26,16 +26,19 @@
pkgs = import nixpkgs { inherit system; };
electronVersion = packageJsonDesktop.devDependencies.electron;
- electronFromNixpkgs = pkgs."electron_${lib.versions.major electronVersion}";
+ # `or null` because a major bump lands in apps/desktop/package.json long before
+ # nixpkgs has the matching electron_<major> attribute; without it the flake dies
+ # with an attribute error instead of falling through to the pinned binary below.
+ electronFromNixpkgs = pkgs."electron_${lib.versions.major electronVersion}" or null;
# nixpkgs lags behind the Electron version pinned in apps/desktop/package.json
# (electron_43 is still 43.1.0), and its source build cannot be bumped without
# upstream's Chromium dependency hashes. Build the exact pinned version from
# Electron's official binary release instead, reusing the nixpkgs builder.
#
- # When bumping Electron, refresh these hashes:
- # zips: curl -sL https://github.com/electron/electron/releases/download/v<version>/SHASUMS256.txt
- # headers: nix-prefetch-url --unpack https://artifacts.electronjs.org/headers/dist/v<version>/node-v<version>-headers.tar.gz
+ # Don't refresh these by hand — `pnpm chore:update-flake-electron` rewrites both
+ # bindings from the release's SHASUMS256.txt, and the update-nix-flake workflow
+ # opens a PR whenever apps/desktop/package.json moves ahead of the pin.
pinnedElectronVersion = "43.2.0";
pinnedElectronHashes = {
x86_64-linux = "f77ca6ed67bbc68702b69b56ad499bca6ae090705ade7d04f0ac545e409dec68";
@@ -50,7 +53,7 @@
) { };
electron =
- if electronFromNixpkgs.version == electronVersion then
+ if electronFromNixpkgs != null && electronFromNixpkgs.version == electronVersion then
electronFromNixpkgs
else
lib.throwIf (pinnedElectronVersion != electronVersion) ''
@@ -380,6 +383,11 @@ nodejs.python
packages.default = desktop;
+ # Not something to install — it is here so the pinned Electron binary can be
+ # built (and therefore its hashes verified) on its own, without going through
+ # a full desktop build. The update-nix-flake workflow does exactly that.
+ packages.electron = electron;
+
devShells.default = pkgs.mkShell {
buildInputs = [
nodejs
diff --git a/package.json b/package.json
index efd752f6be..6fdfa2f2a8 100644
--- a/package.json
+++ b/package.json
@@ -34,12 +34,14 @@
"chore:ci-update-nightly-version": "tsx ./scripts/update-nightly-version.ts",
"chore:generate-openapi": "tsx ./scripts/generate-openapi.ts",
"chore:update-build-info": "tsx ./scripts/update-build-info.ts",
+ "chore:update-flake-electron": "tsx ./scripts/update-flake-electron.ts",
"chore:update-version": "tsx ./scripts/update-version.ts",
"chore:wipe-node-modules": "node --experimental-strip-types ./scripts/wipe-node-modules.mts",
"docs:build": "pnpm run --filter build-docs start",
"docs:preview": "pnpm http-server site -p 9000",
"edit-docs:edit-demo": "pnpm run --filter edit-docs edit-demo",
- "test:all": "pnpm test:parallel && pnpm test:sequential",
+ "scripts:test": "vitest run --project scripts",
+ "test:all": "pnpm test:parallel && pnpm test:sequential && pnpm scripts:test",
"test:parallel": "pnpm --filter=!server --filter=!ckeditor5 --parallel test",
"test:sequential": "pnpm --filter=server --filter=ckeditor5 --sequential test",
"typecheck": "tsx scripts/filter-tsc-output.mts",
diff --git a/scripts/update-flake-electron.spec.ts b/scripts/update-flake-electron.spec.ts
new file mode 100644
index 0000000000..1b17d74c02
--- /dev/null
+++ b/scripts/update-flake-electron.spec.ts
@@ -0,0 +1,126 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ parseShasums,
+ readPinnedElectronVersion,
+ readWantedElectronVersion,
+ rewriteFlake
+} from "./update-flake-electron";
+
+/** Trimmed to the shape the script anchors on, indentation included. */
+const FLAKE = `{
+ outputs =
+ { self }:
+ let
+ pinnedElectronVersion = "43.2.0";
+ pinnedElectronHashes = {
+ x86_64-linux = "old-x64";
+ armv7l-linux = "old-armv7l";
+ aarch64-linux = "old-arm64";
+ x86_64-darwin = "old-darwin-x64";
+ aarch64-darwin = "old-darwin-arm64";
+ headers = "old-headers";
+ };
+ nodejs = pkgs.nodejs_24;
+ in
+ { };
+}
+`;
+
+const HASHES = {
+ "x86_64-linux": "x64",
+ "armv7l-linux": "armv7l",
+ "aarch64-linux": "arm64",
+ "x86_64-darwin": "darwin-x64",
+ "aarch64-darwin": "darwin-arm64",
+ "headers": "headers"
+};
+
+const desktopPackageJson = (electron: string) => JSON.stringify({ devDependencies: { electron } });
+
+describe("readWantedElectronVersion", () => {
+ it("reads an exact pin", () => {
+ expect(readWantedElectronVersion(desktopPackageJson("43.3.0"))).toBe("43.3.0");
+ });
+
+ it("rejects ranges and missing entries, which cannot be pinned to one build", () => {
+ expect(() => readWantedElectronVersion(desktopPackageJson("^43.3.0"))).toThrow(/exact/);
+ expect(() => readWantedElectronVersion(desktopPackageJson("latest"))).toThrow(/exact/);
+ expect(() => readWantedElectronVersion("{}")).toThrow(/devDependencies/);
+ });
+});
+
+describe("readPinnedElectronVersion", () => {
+ it("reads the flake's pin, and fails loudly when the binding is gone", () => {
+ expect(readPinnedElectronVersion(FLAKE)).toBe("43.2.0");
+ expect(() => readPinnedElectronVersion("{ }")).toThrow(/pinnedElectronVersion/);
+ });
+});
+
+describe("parseShasums", () => {
+ const shasums = [
+ `${"a".repeat(64)} *chromedriver-v43.3.0-linux-x64.zip`,
+ `${"1".repeat(64)} *electron-v43.3.0-linux-x64.zip`,
+ `${"2".repeat(64)} *electron-v43.3.0-linux-armv7l.zip`,
+ `${"3".repeat(64)} *electron-v43.3.0-linux-arm64.zip`,
+ `${"4".repeat(64)} *electron-v43.3.0-darwin-x64.zip`,
+ `${"5".repeat(64)} *electron-v43.3.0-darwin-arm64.zip`,
+ `${"b".repeat(64)} *electron-v43.3.0-linux-x64-symbols.zip`,
+ `${"c".repeat(64)} *electron-v43.3.0-mas-x64.zip`,
+ ""
+ ].join("\n");
+
+ it("picks the five platform zips and ignores the rest of the release", () => {
+ expect(parseShasums(shasums, "43.3.0")).toEqual({
+ "x86_64-linux": "1".repeat(64),
+ "armv7l-linux": "2".repeat(64),
+ "aarch64-linux": "3".repeat(64),
+ "x86_64-darwin": "4".repeat(64),
+ "aarch64-darwin": "5".repeat(64)
+ });
+ });
+
+ it("names the assets it could not find rather than emitting a partial set", () => {
+ expect(() => parseShasums(shasums, "43.4.0")).toThrow(/electron-v43\.4\.0-linux-x64\.zip/);
+
+ // Only the one that is genuinely absent — the four it did resolve stay unmentioned.
+ const withoutArm = shasums.replace(/^.*darwin-arm64\.zip$/m, "");
+ const onlyDarwinArm = /^(?!.*linux-x64).*darwin-arm64\.zip/s;
+ expect(() => parseShasums(withoutArm, "43.3.0")).toThrow(onlyDarwinArm);
+ });
+});
+
+describe("rewriteFlake", () => {
+ const rewritten = rewriteFlake(FLAKE, "43.3.0", HASHES);
+
+ it("replaces both bindings, keeping indentation and the surrounding expression", () => {
+ expect(rewritten).toBe(`{
+ outputs =
+ { self }:
+ let
+ pinnedElectronVersion = "43.3.0";
+ pinnedElectronHashes = {
+ x86_64-linux = "x64";
+ armv7l-linux = "armv7l";
+ aarch64-linux = "arm64";
+ x86_64-darwin = "darwin-x64";
+ aarch64-darwin = "darwin-arm64";
+ headers = "headers";
+ };
+ nodejs = pkgs.nodejs_24;
+ in
+ { };
+}
+`);
+ });
+
+ it("is stable when re-run against its own output", () => {
+ expect(rewriteFlake(rewritten, "43.3.0", HASHES)).toBe(rewritten);
+ });
+
+ it("refuses to touch a flake it no longer recognises", () => {
+ const versionOnly = `pinnedElectronVersion = "43.2.0";`;
+ expect(() => rewriteFlake(versionOnly, "43.3.0", HASHES)).toThrow(/pinnedElectronHashes/);
+ expect(() => rewriteFlake("{ }", "43.3.0", HASHES)).toThrow(/pinnedElectronVersion/);
+ });
+});
diff --git a/scripts/update-flake-electron.ts b/scripts/update-flake-electron.ts
new file mode 100644
index 0000000000..2b3abd2d51
--- /dev/null
+++ b/scripts/update-flake-electron.ts
@@ -0,0 +1,195 @@
+/**
+ * Keeps the Electron binary pinned in `flake.nix` in sync with the version
+ * `apps/desktop/package.json` depends on.
+ *
+ * nixpkgs lags behind the Electron releases Trilium tracks, so the flake builds
+ * the exact pinned version from Electron's official binary release rather than
+ * taking `pkgs.electron_<major>` (see the comment above `pinnedElectronVersion`).
+ * Every Electron bump therefore has to be mirrored into the flake, or it refuses
+ * to evaluate:
+ *
+ * error: flake.nix pins Electron 43.2.0, but apps/desktop/package.json wants 43.3.0
+ *
+ * This script is that mirroring, automated: it reads the wanted version, takes
+ * the five per-platform zip checksums from the release's own `SHASUMS256.txt`,
+ * computes the headers hash with `nix-prefetch-url`, and rewrites both
+ * `pinnedElectron*` bindings. It is a no-op when the pin already matches, so it
+ * is safe to run on a schedule.
+ *
+ * Run on demand or from the `update-nix-flake.yml` workflow, which opens a PR when
+ * the flake changes. Usage:
+ *
+ * pnpm chore:update-flake-electron
+ *
+ * Requires `nix-prefetch-url` on PATH — the headers hash is a NAR hash of the
+ * unpacked tarball, which only Nix can compute.
+ */
+
+import { execFileSync } from "node:child_process";
+import { readFileSync, writeFileSync } from "node:fs";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const SCRIPT_PATH = fileURLToPath(import.meta.url);
+const ROOT = resolve(dirname(SCRIPT_PATH), "..");
+const FLAKE_PATH = join(ROOT, "flake.nix");
+const DESKTOP_PACKAGE_JSON_PATH = join(ROOT, "apps", "desktop", "package.json");
+
+export async function main() {
+ const flake = readFileSync(FLAKE_PATH, "utf-8");
+ const wanted = readWantedElectronVersion(readFileSync(DESKTOP_PACKAGE_JSON_PATH, "utf-8"));
+ const pinned = readPinnedElectronVersion(flake);
+
+ if (wanted === pinned) {
+ console.log(`flake.nix already pins Electron ${pinned}; nothing to do.`);
+ return;
+ }
+
+ console.log(`Electron ${pinned} -> ${wanted}; refreshing the pin.`);
+ const hashes = {
+ ...parseShasums(await fetchShasums(wanted), wanted),
+ headers: prefetchHeadersHash(wanted)
+ };
+
+ writeFileSync(FLAKE_PATH, rewriteFlake(flake, wanted, hashes));
+ console.log(`Wrote ${FLAKE_PATH}`);
+ for (const [ key, hash ] of Object.entries(hashes)) {
+ console.log(` ${key} = ${hash}`);
+ }
+}
+
+/**
+ * Nix system → the tag Electron uses in its release asset names, in the order the
+ * generated `pinnedElectronHashes` block lists them. Mirrors `tags` in nixpkgs'
+ * `pkgs/development/tools/electron/binary/generic.nix`, which is the builder the
+ * flake reuses, so the set of systems here is exactly the set that builder covers.
+ */
+export const ELECTRON_PLATFORM_TAGS: Record<string, string> = {
+ "x86_64-linux": "linux-x64",
+ "armv7l-linux": "linux-armv7l",
+ "aarch64-linux": "linux-arm64",
+ "x86_64-darwin": "darwin-x64",
+ "aarch64-darwin": "darwin-arm64"
+};
+
+/** Per-platform zip checksums plus the `headers` NAR hash, keyed as the flake expects. */
+export type ElectronHashes = Record<string, string> & { headers: string };
+
+/**
+ * The flake pins one exact build, so a range (`^43.3.0`) has no single answer —
+ * refuse rather than guess at what the lockfile happens to resolve to today.
+ */
+export function readWantedElectronVersion(packageJson: string): string {
+ const version = JSON.parse(packageJson)?.devDependencies?.electron;
+ if (typeof version !== "string") {
+ throw new Error("apps/desktop/package.json has no devDependencies.electron entry.");
+ }
+ if (!/^\d+\.\d+\.\d+$/.test(version)) {
+ throw new Error(
+ `apps/desktop/package.json must pin an exact Electron version, found "${version}".`
+ );
+ }
+ return version;
+}
+
+export function readPinnedElectronVersion(flake: string): string {
+ const match = flake.match(/^\s*pinnedElectronVersion = "([^"]+)";$/m);
+ if (!match) {
+ throw new Error("Could not find the pinnedElectronVersion binding in flake.nix.");
+ }
+ return match[1];
+}
+
+async function fetchShasums(version: string): Promise<string> {
+ const url = `https://github.com/electron/electron/releases/download/v${version}/SHASUMS256.txt`;
+ const response = await fetch(url);
+ if (!response.ok) {
+ throw new Error(
+ `Failed to fetch ${url}: HTTP ${response.status}. Is Electron ${version} released?`
+ );
+ }
+ return response.text();
+}
+
+/**
+ * Pull the five zip checksums out of a release's `SHASUMS256.txt`, whose lines are
+ * `<sha256> *<asset name>`. The file also lists chromedriver, symbol and mas
+ * builds, so match asset names exactly rather than by substring.
+ */
+export function parseShasums(shasums: string, version: string): Record<string, string> {
+ const byAsset = new Map<string, string>();
+ for (const line of shasums.split("\n")) {
+ const match = line.match(/^([0-9a-f]{64}) \*(.+)$/);
+ if (match) {
+ byAsset.set(match[2].trim(), match[1]);
+ }
+ }
+
+ const hashes: Record<string, string> = {};
+ const missing: string[] = [];
+ for (const [ system, tag ] of Object.entries(ELECTRON_PLATFORM_TAGS)) {
+ const asset = `electron-v${version}-${tag}.zip`;
+ const hash = byAsset.get(asset);
+ if (hash) {
+ hashes[system] = hash;
+ } else {
+ missing.push(asset);
+ }
+ }
+ if (missing.length > 0) {
+ throw new Error(`SHASUMS256.txt for Electron ${version} is missing: ${missing.join(", ")}`);
+ }
+ return hashes;
+}
+
+/**
+ * The headers are consumed with `fetchzip`, so the flake needs the NAR hash of the
+ * *unpacked* tarball rather than its sha256 — hence shelling out to Nix.
+ */
+function prefetchHeadersHash(version: string): string {
+ const tarball = `node-v${version}-headers.tar.gz`;
+ const url = `https://artifacts.electronjs.org/headers/dist/v${version}/${tarball}`;
+ try {
+ return execFileSync("nix-prefetch-url", [ "--unpack", url ], { encoding: "utf-8" }).trim();
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") {
+ throw new Error(
+ "nix-prefetch-url is not on PATH; install Nix to refresh the headers hash."
+ );
+ }
+ throw err;
+ }
+}
+
+export function rewriteFlake(flake: string, version: string, hashes: ElectronHashes): string {
+ const versionPattern = /^([ \t]*)pinnedElectronVersion = "[^"]*";$/m;
+ const hashesPattern = /^([ \t]*)pinnedElectronHashes = \{[\s\S]*?^\1\};$/m;
+ if (!versionPattern.test(flake) || !hashesPattern.test(flake)) {
+ throw new Error(
+ "Could not find the pinnedElectronVersion/pinnedElectronHashes bindings in flake.nix."
+ );
+ }
+
+ return flake
+ .replace(
+ versionPattern,
+ (_match, indent: string) => `${indent}pinnedElectronVersion = "${version}";`
+ )
+ .replace(hashesPattern, (_match, indent: string) => renderHashesBlock(indent, hashes));
+}
+
+function renderHashesBlock(indent: string, hashes: ElectronHashes): string {
+ const inner = `${indent} `;
+ const lines = Object.keys(ELECTRON_PLATFORM_TAGS)
+ .map((system) => `${inner}${system} = "${hashes[system]}";`);
+ lines.push(`${inner}headers = "${hashes.headers}";`);
+ return `${indent}pinnedElectronHashes = {\n${lines.join("\n")}\n${indent}};`;
+}
+
+// Only when run as a script — the pure helpers above are imported by the spec.
+if (process.argv[1] === SCRIPT_PATH) {
+ main().catch((err) => {
+ console.error(err);
+ process.exit(1);
+ });
+}
diff --git a/scripts/vitest.config.ts b/scripts/vitest.config.ts
new file mode 100644
index 0000000000..cf7337dc03
--- /dev/null
+++ b/scripts/vitest.config.ts
@@ -0,0 +1,11 @@
+import { defineConfig } from "vitest/config";
+
+// The repo-root maintenance scripts are not a workspace package, so they get their
+// own project rather than a `pnpm --filter` target. Run it with `pnpm scripts:test`.
+export default defineConfig({
+ test: {
+ name: "scripts",
+ environment: "node",
+ include: [ "*.spec.ts" ]
+ }
+});
diff --git a/vitest.config.ts b/vitest.config.ts
index d95932acff..b3917098d1 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -8,6 +8,7 @@ export default defineConfig({
"apps/*/vitest.config.ts",
"apps/*/vite.config.ts",
"apps/*/vite.config.mts",
+ "scripts/vitest.config.ts",
],
},
})