From edb07c784363a11f6370504cbb5bc34a4e1f2aae Mon Sep 17 00:00:00 2001 From: CRT Date: Sat, 10 Oct 2026 21:16:59 +0000 Subject: [PATCH] Desktop release pipeline: privacy scan of every artifact, path-free builds, macOS universal app + DMG (Developer ID + notarization or an ad-hoc -unsigned preview) with self-tests of the exact artifacts, signed latest.json, Forgejo workflow for Linux and Windows, root-owned publish step for storebound.dev --- .forgejo/workflows/desktop.yml | 114 +++++ tests/desktop-release.test.ts | 88 ++++ tests/privacy-scan.test.ts | 67 +++ tools/desktop-release.ts | 585 +++++++++++++++++++++++ tools/privacy-scan.ts | 246 ++++++++++ tools/vds/apache-storebound-desktop.conf | 25 + tools/vds/storebound-desktop-publish | 78 +++ 7 files changed, 1203 insertions(+) create mode 100644 .forgejo/workflows/desktop.yml create mode 100644 tests/desktop-release.test.ts create mode 100644 tests/privacy-scan.test.ts create mode 100644 tools/desktop-release.ts create mode 100644 tools/privacy-scan.ts create mode 100644 tools/vds/apache-storebound-desktop.conf create mode 100755 tools/vds/storebound-desktop-publish diff --git a/.forgejo/workflows/desktop.yml b/.forgejo/workflows/desktop.yml new file mode 100644 index 00000000..ae3e049d --- /dev/null +++ b/.forgejo/workflows/desktop.yml @@ -0,0 +1,114 @@ +# storebound desktop: Linux (AppImage + deb) and Windows (NSIS, per user, unsigned) installers. +# macOS is built, signed and notarized on the owner's Mac (tools/desktop-release.ts mac); the updater signing key +# never reaches a runner: the Mac signs these installers after downloading them (tools/desktop-release.ts add). +# Runner setup (act_runner on the VDS for Linux in Docker, a Windows runner later): docs/desktop-release.md. +name: desktop + +on: + workflow_dispatch: + inputs: + windows: + description: Build Windows too (needs a runner with the "windows" label) + type: boolean + default: false + push: + tags: ['desktop-v*'] + +env: + BUN_VERSION: '1.4.0' + # the path-free build keeps the target folder outside every home folder + CARGO_TARGET_DIR: /tmp/storebound-target + CARGO_TERM_COLOR: never + +jobs: + linux: + # act_runner label: ubuntu-22.04:docker://ghcr.io/catthehacker/ubuntu:act-22.04 (glibc 2.35: the AppImage and the + # deb then run on Ubuntu 22.04 and newer, Debian 12) + runs-on: ubuntu-22.04 + timeout-minutes: 90 + env: + # linuxdeploy (AppImage) runs without FUSE inside the container + APPIMAGE_EXTRACT_AND_RUN: '1' + # WebKitGTK's DMABUF renderer leaves the window blank on some GPU / VM setups; the app sets this itself at + # start (src-tauri/src/lib.rs linux_webkit_env) unless the user did; set here too for anything run in CI + WEBKIT_DISABLE_DMABUF_RENDERER: '1' + steps: + - uses: actions/checkout@v4 + - name: System packages + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev \ + librsvg2-dev libsoup-3.0-dev libjavascriptcoregtk-4.1-dev libssl-dev libxdo-dev patchelf file build-essential \ + curl unzip squashfs-tools p7zip-full xz-utils + - name: Bun and Rust + run: | + curl -fsSL https://bun.sh/install | bash -s "bun-v${BUN_VERSION}" + echo "$HOME/.bun/bin" >> "$GITHUB_PATH" + command -v rustup || curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal + echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" + - name: Install and check + run: | + bun install --frozen-lockfile + bun tools/desktop-version.ts + bun tools/build-sidecars.ts --target bun-linux-x64 + - name: Build AppImage and deb (path-free) + working-directory: apps/desktop + run: bun ../../tools/desktop-release.ts exec -- bunx tauri build --bundles appimage,deb --ci + - name: Self-test the exact artifacts + run: | + V=$(bun tools/desktop-version.ts --print) + B="$CARGO_TARGET_DIR/release/bundle" + mkdir -p out && cp "$B/appimage/storebound_${V}_amd64.AppImage" "$B/deb/storebound_${V}_amd64.deb" out/ + chmod +x out/*.AppImage + (cd /tmp && rm -rf squashfs-root && "$GITHUB_WORKSPACE/out/storebound_${V}_amd64.AppImage" --appimage-extract >/dev/null && squashfs-root/usr/bin/storebound-desktop --self-test) + rm -rf /tmp/deb && dpkg-deb -x "out/storebound_${V}_amd64.deb" /tmp/deb && /tmp/deb/usr/bin/storebound-desktop --self-test + dpkg-deb -I "out/storebound_${V}_amd64.deb" | sed -n '1,20p' + - name: Privacy scan + run: bun tools/privacy-scan.ts out/ + - name: Checksums + run: (cd out && sha256sum * | tee SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: storebound-desktop-linux + path: out/ + retention-days: 14 + + windows: + if: ${{ inputs.windows }} + # a Windows runner registered with the "windows" label (host mode): Rust (MSVC), Bun, 7-Zip + runs-on: windows + timeout-minutes: 90 + env: + CARGO_TARGET_DIR: C:\storebound-target + steps: + - uses: actions/checkout@v4 + - name: Install and check + shell: pwsh + run: | + bun install --frozen-lockfile + bun tools/desktop-version.ts + bun tools/build-sidecars.ts --target bun-windows-x64 + - name: Build NSIS installer (per user, WebView2 bootstrapper, path-free) + shell: pwsh + working-directory: apps/desktop + run: bun ../../tools/desktop-release.ts exec -- bunx tauri build --bundles nsis --ci + - name: Install per user, self-test, uninstall + shell: pwsh + run: | + $V = bun tools/desktop-version.ts --print + New-Item -ItemType Directory -Force out | Out-Null + Copy-Item "$env:CARGO_TARGET_DIR\release\bundle\nsis\storebound_${V}_x64-setup.exe" out\ + Start-Process -Wait -FilePath "out\storebound_${V}_x64-setup.exe" -ArgumentList '/S' + $exe = "$env:LOCALAPPDATA\storebound\storebound-desktop.exe" + if (-not (Test-Path $exe)) { throw "not installed per user at $exe" } + & $exe --self-test | Tee-Object -Variable st + if ($LASTEXITCODE -ne 0) { throw "self-test failed" } + Start-Process -Wait -FilePath "$env:LOCALAPPDATA\storebound\uninstall.exe" -ArgumentList '/S' + - name: Privacy scan (no .pdb, no paths) + shell: pwsh + run: bun tools/privacy-scan.ts out + - uses: actions/upload-artifact@v3 + with: + name: storebound-desktop-windows + path: out/ + retention-days: 14 diff --git a/tests/desktop-release.test.ts b/tests/desktop-release.test.ts new file mode 100644 index 00000000..4f664e74 --- /dev/null +++ b/tests/desktop-release.test.ts @@ -0,0 +1,88 @@ +// tools/desktop-release.ts and tools/desktop-version.ts: the pure parts of the desktop release pipeline. +import { describe, expect, test } from 'bun:test'; +import { cpSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { artifactName, developerIdIdentity, mergeManifest, pathFreeEnv, releaseUrl, remoteSessionReason, sumsText, uploadable } from '../tools/desktop-release'; +import { COPIES, setVersion, versions } from '../tools/desktop-version'; + +describe('desktop version authority', () => { + test('the repository has one desktop version', () => { + const { version, drift } = versions(); + expect(version).toMatch(/^\d+\.\d+\.\d+$/); + expect(drift).toEqual([]); + }); + test('drift is found and --set fixes every copy', () => { + const root = mkdtempSync(join(tmpdir(), 'sb-ver-')); + for (const c of COPIES) { mkdirSync(join(root, c.file, '..'), { recursive: true }); cpSync(join(import.meta.dir, '..', c.file), join(root, c.file)); } + const conf = join(root, 'apps/desktop/src-tauri/tauri.conf.json'); + writeFileSync(conf, readFileSync(conf, 'utf8').replace(/"version": "[^"]+"/, '"version": "9.9.9"')); + expect(versions(root).drift.map(d => d.file)).toEqual(['apps/desktop/src-tauri/tauri.conf.json']); + setVersion('0.2.0-beta.1', root); + expect(versions(root)).toEqual({ version: '0.2.0-beta.1', drift: [] }); + // only the package's own version line of Cargo.toml / Cargo.lock changes + expect(readFileSync(join(root, 'apps/desktop/src-tauri/Cargo.toml'), 'utf8')).toContain('tauri = { version = "2.12"'); + expect(() => setVersion('latest', root)).toThrow(); + }); +}); + +describe('desktop release', () => { + test('signing refuses SSH and non-GUI sessions', () => { + expect(remoteSessionReason({}, 'Aqua')).toBeNull(); + expect(remoteSessionReason({ SSH_CONNECTION: '1 2 3 4' }, 'Aqua')).toMatch(/SSH/); + expect(remoteSessionReason({ SSH_TTY: '/dev/ttys001' }, 'Aqua')).toMatch(/SSH/); + expect(remoteSessionReason({}, 'Background')).toMatch(/GUI session/); + }); + test('only a Developer ID Application identity signs a release', () => { + const out = ` 1) ${'A'.repeat(40)} "Apple Distribution: Example Studio (TEAM000001)" + 2) ${'B'.repeat(40)} "Apple Development: Example Person (TEAM000002)" + 2 valid identities found`; + expect(developerIdIdentity(out)).toBeNull(); + expect(developerIdIdentity(`${out}\n 3) ${'C'.repeat(40)} "Developer ID Application: Example Studio (TEAM000001)"`)).toBe('Developer ID Application: Example Studio (TEAM000001)'); + }); + test('artifact names say when a build is unsigned', () => { + expect(artifactName('0.1.0', 'dmg', false)).toBe('storebound_0.1.0_universal-unsigned.dmg'); + expect(artifactName('0.1.0', 'updater', true)).toBe('storebound_0.1.0_universal.app.tar.gz'); + expect(artifactName('0.1.0', 'nsis', false)).toBe('storebound_0.1.0_x64-setup-unsigned.exe'); + expect(artifactName('0.1.0', 'appimage', false)).toBe('storebound_0.1.0_amd64.AppImage'); + expect(releaseUrl('0.1.0', 'a.dmg')).toBe('https://storebound.dev/desktop/dl/0.1.0/a.dmg'); + }); + test('path-free build: home, checkout, cargo, rustup and target dir are remapped, general first', () => { + const env = pathFreeEnv('/Users/you/src/storebound', { CARGO_TARGET_DIR: '/tmp/t', RUSTFLAGS: '-Cforce-frame-pointers=yes', CFLAGS: '-O2' }, '/Users/you'); + const flags = env.CARGO_ENCODED_RUSTFLAGS!.split('\x1f'); + expect(flags).toEqual([ + '-Cforce-frame-pointers=yes', + '--remap-path-prefix=/Users/you=~', + '--remap-path-prefix=/Users/you/src/storebound=/src', + '--remap-path-prefix=/tmp/t=/target', + '--remap-path-prefix=/Users/you/.cargo=/cargo', + '--remap-path-prefix=/Users/you/.rustup=/rustup', + ]); + expect(env.CFLAGS).toStartWith('-O2 -ffile-prefix-map=/Users/you=~'); + expect(env.CXXFLAGS).toContain('-ffile-prefix-map=/Users/you/.rustup=/rustup'); + const w = pathFreeEnv('C:\\src\\storebound', { CARGO_TARGET_DIR: 'C:\\t' }, 'C:\\Users\\you', 'win32'); + const wf = w.CARGO_ENCODED_RUSTFLAGS!.split('\x1f'); + expect(wf).toContain('--remap-path-prefix=C:\\Users\\you=~'); + expect(wf).toContain('--remap-path-prefix=\\\\?\\C:\\Users\\you=~'); + expect(wf).toContain('-Clink-arg=/PDBALTPATH:%_PDB%'); + expect(w.CL).toContain('"/d1trimfile:C:\\Users\\you\\.rustup/"'); + expect(w.LINK).toBe('/PDBALTPATH:%_PDB%'); + expect(w.CFLAGS).toBeUndefined(); + }); + test('latest.json keeps the other platforms of the same version, a new version starts fresh', () => { + const mac = { platforms: { 'darwin-aarch64': { signature: 's', url: 'https://storebound.dev/desktop/dl/0.1.0/m.app.tar.gz' } } }; + const win = { platforms: { 'windows-x86_64': { signature: 'w', url: 'https://storebound.dev/desktop/dl/0.1.0/w.exe' } } }; + const one = mergeManifest(null, '0.1.0', 'first', '2026-10-11T00:00:00Z', mac); + const two = mergeManifest(one, '0.1.0', 'other notes', '2026-10-12T00:00:00Z', win); + expect(Object.keys(two.platforms)).toEqual(['darwin-aarch64', 'windows-x86_64']); + expect(two.notes).toBe('first'); + expect(two.pub_date).toBe('2026-10-12T00:00:00Z'); + expect(Object.keys(mergeManifest(two, '0.1.1', 'n', 'x', win).platforms)).toEqual(['windows-x86_64']); + }); + test('SHA256SUMS and what is uploaded', () => { + expect(sumsText([{ file: 'b', sha256: '2' }, { file: 'a', sha256: '1' }])).toBe('1 a\n2 b\n'); + expect(uploadable('storebound_0.1.0_universal-unsigned.dmg')).toBe(true); + expect(uploadable('latest.json')).toBe(true); + for (const n of ['evidence-macos-0.1.0.json', '.DS_Store', 'latest.json.part', 'a b.dmg']) expect(uploadable(n)).toBe(false); + }); +}); diff --git a/tests/privacy-scan.test.ts b/tests/privacy-scan.test.ts new file mode 100644 index 00000000..5611df52 --- /dev/null +++ b/tests/privacy-scan.test.ts @@ -0,0 +1,67 @@ +// tools/privacy-scan.ts: the release gate over every desktop artifact. Made-up terms only (the real ones live in a +// file outside the repository). +import { describe, expect, test } from 'bun:test'; +import { spawnSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { collectTerms, kindOf, mask, parseTerms, scan, scanBuffer, type Term } from '../tools/privacy-scan'; + +const T: Term[] = [{ text: 'Quillfeather', short: false }, { text: 'qz', short: true }]; +// home folders are put together at run time, so tools/scrub.ts (which forbids them in the repository) passes +const home = (root: string, name: string): string => `${root}${name}`; + +describe('privacy scan', () => { + test('terms: comments and blanks skipped, never printed in full', () => { + expect(parseTerms('# names\nQuillfeather\n\n qz \n')).toEqual(['Quillfeather', 'qz']); + expect(mask('Quillfeather')).toBe('Q***'); + const dir = mkdtempSync(join(tmpdir(), 'sb-terms-')); + writeFileSync(join(dir, 't.txt'), `Quillfeather\nCRT\n${['hi', 'crt.fyi'].join('@')}\n`); + // the release identity is never a forbidden term + expect(collectTerms(join(dir, 't.txt'), false).map(t => t.text)).toEqual(['Quillfeather']); + }); + + test('finds a term in any case, in UTF-8 and UTF-16LE', () => { + const hits = scanBuffer('bin', Buffer.concat([Buffer.from('xx QUILLFEATHER yy'), Buffer.from('built by quillFeather', 'utf16le')]), T); + expect(hits.map(h => h.encoding)).toEqual(['utf8', 'utf16le']); + expect(hits.every(h => h.what === 'term Q***')).toBe(true); + expect(scanBuffer('bin', Buffer.from('nothing to see'), T)).toEqual([]); + }); + + test('a short term counts only in a path', () => { + expect(scanBuffer('bin', Buffer.from('jazz quiz qz-mode'), T)).toEqual([]); + expect(scanBuffer('bin', Buffer.from('/opt/qz/src'), T).some(h => h.what === 'term q***')).toBe(true); + }); + + test('home folders of any account, generic ones allowed', () => { + const hits = scanBuffer('bin', Buffer.from(`${home('/Users/', 'someone')}/work /home/runner/work ${home('C:\\Users\\', 'other')}\\x /Users/you/app /home/$USER`), []); + expect(hits.map(h => h.what)).toEqual(['home folder of an account (s***)', 'home folder of an account (o***)']); + }); + + test('folders, archives and debug files', () => { + const dir = mkdtempSync(join(tmpdir(), 'sb-scan-')); + mkdirSync(join(dir, 'pkg/My.app/Contents'), { recursive: true }); + writeFileSync(join(dir, 'pkg/My.app/Contents/clean.txt'), 'all good'); + writeFileSync(join(dir, 'pkg/My.app/Contents/leak.bin'), Buffer.from(`panic at ${home('/Users/', 'quillfeather')}/src/main.rs`, 'utf8')); + mkdirSync(join(dir, 'pkg/My.app.dSYM')); + expect(spawnSync('tar', ['-czf', join(dir, 'bundle.tar.gz'), '-C', join(dir, 'pkg'), '.']).status).toBe(0); + const r = scan([join(dir, 'bundle.tar.gz')], null, false); + expect(r.errors).toEqual([]); + const shown = r.hits.map(h => `${h.file}: ${h.what}`); + expect(shown.some(s => s.startsWith('bundle.tar.gz!/') && s.includes('leak.bin') && s.includes('home folder'))).toBe(true); + expect(shown.some(s => s.includes('My.app.dSYM: debug file'))).toBe(true); + expect(r.files).toBeGreaterThanOrEqual(3); + const clean = scan([join(dir, 'pkg/My.app/Contents/clean.txt')], null, false); + expect(clean.hits).toEqual([]); + expect(scan([join(dir, 'missing.dmg')], null, false).errors).toHaveLength(1); + }); + + test('container kinds', () => { + expect(kindOf('a/storebound_0.1.0_universal.dmg', new Uint8Array())).toBe('dmg'); + expect(kindOf('storebound_0.1.0_universal.app.tar.gz', new Uint8Array())).toBe('tar'); + expect(kindOf('storebound_0.1.0_amd64.deb', new Uint8Array())).toBe('deb'); + expect(kindOf('storebound_0.1.0_amd64.AppImage', new Uint8Array())).toBe('appimage'); + expect(kindOf('storebound_0.1.0_x64-setup.exe', Buffer.from('MZ....Nullsoft Install System'))).toBe('nsis'); + expect(kindOf('storebound-desktop.exe', Buffer.from('MZ'))).toBe('file'); + }); +}); diff --git a/tools/desktop-release.ts b/tools/desktop-release.ts new file mode 100644 index 00000000..e7486999 --- /dev/null +++ b/tools/desktop-release.ts @@ -0,0 +1,585 @@ +#!/usr/bin/env bun +// Release pipeline of the storebound desktop app. Builds, signs, checks and lays out one version for +// storebound.dev/desktop/; nothing here installs anything, and publishing is a separate, explicit step. +// +// bun tools/desktop-release.ts mac [--out ] [--target-dir ] [--identity ""] +// [--no-notarize] [--notes "..."] [--allow-dirty] +// Universal (Apple silicon + Intel) app, updater bundle (.app.tar.gz) and DMG. With a "Developer ID Application" +// identity in the keychain: hardened runtime, notarization (notarytool, App Store Connect API key) and stapling. +// Without one: an ad-hoc signed build named `-unsigned`, and what the owner has to do. Must run in the owner's +// local GUI session: codesign over SSH fails (the keychain is locked there), so SSH sessions are refused. +// Then, on the exact artifacts: codesign / Gatekeeper expectations, the self-test (sidecar handshake, both CPU +// types) from the mounted DMG and from the unpacked updater bundle, the privacy scan, minisign signatures with +// the updater key (~/.storebound-keys/updater.key), SHA256SUMS, latest.json and evidence.json. +// bun tools/desktop-release.ts add --out [--code-signed] +// Adds Windows / Linux installers built by the Forgejo workflow (.forgejo/workflows/desktop.yml) to the version +// folder: privacy scan, minisign signature here (the key never goes to a runner), latest.json, SHA256SUMS. +// bun tools/desktop-release.ts publish --out --host [--channel stable|beta] [--yes] +// Checks the folder again, uploads it to the server's incoming folder (rsync) and runs the root-owned publish +// script there (tmp -> mv, latest.json last). Without --yes it only prints the plan (dry run). +// bun tools/desktop-release.ts verify --out +// The checks of publish without uploading. +// bun tools/desktop-release.ts exec -- +// Runs a build command (tauri build on a runner) with the path-free environment described at pathFreeEnv. +// +// Version: package.json "desktopVersion" (bun tools/desktop-version.ts). Docs: docs/desktop-release.md. +import { spawnSync, type SpawnSyncOptions } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'; +import { homedir, release as osRelease, tmpdir } from 'node:os'; +import { basename, join, resolve } from 'node:path'; +import { type Download, type DownloadKey, type Manifest, manifestProblems } from '../cli/lib/desktop-dist'; +import { verify as verifySig } from '../cli/lib/minisign'; +import { buildOne, OUT_DIR as SIDECAR_DIR } from './build-sidecars'; +import { versions } from './desktop-version'; +import { scan } from './privacy-scan'; + +export const ROOT = resolve(import.meta.dir, '..'); +const APP_DIR = join(ROOT, 'apps/desktop'); +const TAURI_DIR = join(APP_DIR, 'src-tauri'); +export const BASE_URL = 'https://storebound.dev/desktop'; +export const KEYS_DIR = process.env.STOREBOUND_KEYS_DIR ?? join(homedir(), '.storebound-keys'); +const PRODUCT = 'storebound'; +const APP_NAME = 'storebound.app'; +const MAIN_BIN = 'storebound-desktop'; +/** Where the server takes uploads and the root-owned script that publishes them (tools/vds/). */ +export const REMOTE_INCOMING = '/var/lib/storebound-desktop/incoming'; +export const REMOTE_PUBLISH = '/usr/local/sbin/storebound-desktop-publish'; + +// --------------------------------------------------------------------------------------------------------------------- +// Pure parts (tests/desktop-release.test.ts) + +/** Why this session cannot sign (null = a local session). codesign needs the unlocked login keychain of the GUI + * session; over SSH it stops at errSecInternalComponent. */ +export function remoteSessionReason(env: Record, managerName: string): string | null { + if (env.SSH_CONNECTION || env.SSH_CLIENT || env.SSH_TTY) return 'this is an SSH session'; + if (managerName && managerName !== 'Aqua') return `this is not the logged-in GUI session (launchctl manager: ${managerName})`; + return null; +} + +/** The first "Developer ID Application" identity of `security find-identity -v -p codesigning`. */ +export function developerIdIdentity(securityOutput: string): string | null { + const m = /^\s*\d+\)\s+[0-9A-F]{40}\s+"(Developer ID Application: [^"]+)"/m.exec(securityOutput); + return m?.[1] ?? null; +} + +/** File names of a version. Unsigned (no Developer ID / Authenticode) builds say so in the name. */ +export function artifactName(version: string, kind: 'dmg' | 'updater' | 'nsis' | 'appimage' | 'deb', codeSigned: boolean): string { + const u = codeSigned ? '' : '-unsigned'; + switch (kind) { + case 'dmg': return `${PRODUCT}_${version}_universal${u}.dmg`; + case 'updater': return `${PRODUCT}_${version}_universal${u}.app.tar.gz`; + case 'nsis': return `${PRODUCT}_${version}_x64-setup${u}.exe`; + case 'appimage': return `${PRODUCT}_${version}_amd64.AppImage`; + case 'deb': return `${PRODUCT}_${version}_amd64.deb`; + } +} + +export const releaseUrl = (version: string, file: string): string => `${BASE_URL}/dl/${version}/${file}`; + +/** + * Environment of a build whose binaries hold no build-machine path: rustc's --remap-path-prefix (and + * -ffile-prefix-map for C compiled by build scripts) turn the home folder, the checkout, CARGO_HOME, RUSTUP_HOME and + * CARGO_TARGET_DIR into ~, /src, /cargo, /rustup and /target. General roots first: rustc applies the last match. + */ +export function pathFreeEnv(root: string, env: Record, home = homedir(), platform: NodeJS.Platform = process.platform): Record { + const win = platform === 'win32'; + const sep = win ? '\\' : '/'; + const trim = (p: string) => (win ? p.replace(/[\\/]+$/, '') : p.replace(/\/+$/, '') || '/'); + const at = (...parts: string[]) => parts.join(sep); + const roots: [string | undefined, string][] = [ + [home, '~'], + [root, '/src'], + [env.CARGO_TARGET_DIR && (win ? env.CARGO_TARGET_DIR : resolve(env.CARGO_TARGET_DIR)), '/target'], + [env.CARGO_HOME ?? at(home, '.cargo'), '/cargo'], + [env.RUSTUP_HOME ?? at(home, '.rustup'), '/rustup'], + ]; + const maps: [string, string][] = []; + for (const [f, t] of roots) { + if (!f) continue; + maps.push([trim(f), t]); + // Windows hands some paths out in verbatim form (canonicalized by build scripts and cargo) + if (win && /^[A-Za-z]:/.test(f)) maps.push([`\\\\?\\${trim(f)}`, t]); + } + const SEP = '\x1f'; + const flags = env.CARGO_ENCODED_RUSTFLAGS ? env.CARGO_ENCODED_RUSTFLAGS.split(SEP) : (env.RUSTFLAGS ?? '').split(/\s+/).filter(Boolean); + const add = (fl: string) => { if (!flags.includes(fl)) flags.push(fl); }; + for (const [f, t] of maps) add(`--remap-path-prefix=${f}=${t}`); + const out: Record = {}; + if (win) { + // MSVC: the PDB is named without its folder, and cl.exe cuts the roots off __FILE__ (longest root first) + add('-Clink-arg=/PDBALTPATH:%_PDB%'); + const trims = roots.map(r => r[0]).filter((f): f is string => !!f && !f.includes('"')).map(trim).sort((a, b) => b.length - a.length).map(f => `"/d1trimfile:${f}/"`); + out.CL = [...new Set([env.CL, ...trims].filter(Boolean))].join(' '); + out.LINK = [...new Set([env.LINK, '/PDBALTPATH:%_PDB%'].filter(Boolean))].join(' '); + } else { + const prefix = maps.filter(([f]) => !/\s/.test(f)).map(([f, t]) => `-ffile-prefix-map=${f}=${t}`); + for (const n of ['CFLAGS', 'CXXFLAGS']) out[n] = [...(env[n] ?? '').split(/\s+/).filter(Boolean), ...prefix].join(' '); + } + out.CARGO_ENCODED_RUSTFLAGS = flags.join(SEP); + return out; +} + +/** latest.json of a version: an existing one of the same version keeps its other platforms. */ +export function mergeManifest(existing: Manifest | null, version: string, notes: string, now: string, + add: { platforms?: Manifest['platforms']; downloads?: Partial> }): Manifest { + const base: Manifest = existing && existing.version === version ? existing : { version, notes, pub_date: now, platforms: {}, downloads: {} }; + return { + version, + notes: base.notes || notes, + pub_date: now, + platforms: { ...base.platforms, ...add.platforms }, + downloads: { ...base.downloads, ...add.downloads }, + }; +} + +/** `sha256sum -c` format, sorted. */ +export function sumsText(entries: { file: string; sha256: string }[]): string { + return [...entries].sort((a, b) => a.file.localeCompare(b.file)).map(e => `${e.sha256} ${e.file}`).join('\n') + '\n'; +} + +/** Files of a version folder that are uploaded (evidence and temp files stay local). */ +export const uploadable = (name: string): boolean => /^[A-Za-z0-9._-]+$/.test(name) && !name.startsWith('.') && !/^evidence/.test(name) && !name.endsWith('.part'); + +// --------------------------------------------------------------------------------------------------------------------- +// Helpers with side effects + +const t0 = Date.now(); +const say = (msg: string) => console.log(`[${((Date.now() - t0) / 1000).toFixed(0).padStart(4)}s] ${msg}`); +function fail(msg: string): never { console.error(`\ndesktop-release: ${msg}`); process.exit(1); } + +function run(cmd: string[], opts: SpawnSyncOptions & { quiet?: boolean; allowFail?: boolean } = {}): { code: number; out: string; err: string } { + const r = spawnSync(cmd[0]!, cmd.slice(1), { encoding: 'utf8', maxBuffer: 256 << 20, ...opts, stdio: opts.stdio ?? ['ignore', 'pipe', 'pipe'] }); + const res = { code: r.status ?? 1, out: String(r.stdout ?? ''), err: String(r.stderr ?? '') }; + if (res.code !== 0 && !opts.allowFail) fail(`${basename(cmd[0]!)} ${cmd.slice(1, 3).join(' ')} failed (exit ${res.code})\n${res.err.trim().split('\n').slice(-15).join('\n')}`); + return res; +} + +const sha256 = (file: string) => createHash('sha256').update(readFileSync(file)).digest('hex'); +const mb = (n: number) => `${(n / 1e6).toFixed(1)} MB`; +const confPubkey = (): string => JSON.parse(readFileSync(join(TAURI_DIR, 'tauri.conf.json'), 'utf8')).plugins.updater.pubkey; + +function updaterKey(): string { + const key = process.env.STOREBOUND_UPDATER_KEY ?? join(KEYS_DIR, 'updater.key'); + if (!existsSync(key)) fail(`no updater signing key at ${key.replace(homedir(), '~')}: see docs/desktop-release.md (bunx tauri signer generate)`); + const pub = `${key}.pub`; + if (existsSync(pub) && readFileSync(pub, 'utf8').trim() !== confPubkey()) fail(`${basename(pub)} is not the public key in tauri.conf.json: the app would refuse these updates`); + return key; +} + +/** minisign signature with the updater key (tauri signer), checked right away against tauri.conf.json's key. */ +function signFile(file: string): string { + const key = updaterKey(); + rmSync(`${file}.sig`, { force: true }); + run(['bunx', 'tauri', 'signer', 'sign', '-f', key, '-p', '', file], { cwd: APP_DIR, env: { ...process.env, TAURI_SIGNING_PRIVATE_KEY_PASSWORD: '' } }); + const sig = readFileSync(`${file}.sig`, 'utf8').trim(); + const v = verifySig(readFileSync(file), sig, confPubkey()); + if (!v.ok) fail(`${basename(file)}: fresh signature does not verify (${v.reason})`); + return sig; +} + +function privacyGate(paths: string[]): { files: number; bytes: number; hits: number } { + const r = scan(paths); + for (const h of r.hits) console.error(`privacy: ${h.file} @${h.offset}${h.encoding ? ` (${h.encoding})` : ''}: ${h.what}`); + for (const e of r.errors) console.error(`privacy: could not open ${e}`); + if (r.hits.length || r.errors.length) fail(`privacy scan failed (${r.hits.length} hits, ${r.errors.length} errors): nothing may ship`); + say(`privacy scan clean: ${r.files} files, ${mb(r.bytes)}, ${r.terms} terms${r.termsFile ? '' : ' (no forbidden-terms file: only this machine\'s names)'}`); + return { files: r.files, bytes: r.bytes, hits: 0 }; +} + +function readManifest(out: string): Manifest | null { + const p = join(out, 'latest.json'); + return existsSync(p) ? JSON.parse(readFileSync(p, 'utf8')) as Manifest : null; +} + +function writeVersionFiles(out: string, manifest: Manifest): void { + const problems = manifestProblems(manifest); + if (problems.length) fail(`latest.json: ${problems.join('; ')}`); + writeFileSync(join(out, 'latest.json.part'), `${JSON.stringify(manifest, null, 2)}\n`); + renameSync(join(out, 'latest.json.part'), join(out, 'latest.json')); + const files = readdirSync(out).filter(n => uploadable(n) && n !== 'SHA256SUMS'); + writeFileSync(join(out, 'SHA256SUMS'), sumsText(files.map(file => ({ file, sha256: sha256(join(out, file)) })))); +} + +function gitState(): { commit: string; dirty: boolean } { + const commit = run(['git', 'rev-parse', 'HEAD'], { cwd: ROOT }).out.trim(); + const dirty = run(['git', 'status', '--porcelain'], { cwd: ROOT }).out.trim().length > 0; + return { commit, dirty }; +} + +function args(argv: string[]) { + const get = (n: string) => { const i = argv.indexOf(`--${n}`); return i >= 0 ? argv[i + 1] : undefined; }; + return { get, has: (n: string) => argv.includes(`--${n}`), rest: argv.filter((a, i) => !a.startsWith('--') && !(i > 0 && argv[i - 1]!.startsWith('--') && !['--allow-dirty', '--no-notarize', '--yes', '--code-signed'].includes(argv[i - 1]!))) }; +} + +// --------------------------------------------------------------------------------------------------------------------- +// mac + +interface SelfTest { arch: string; result: Record } + +function selfTest(appPath: string, label: string): SelfTest[] { + const bin = join(appPath, 'Contents/MacOS', MAIN_BIN); + const out: SelfTest[] = []; + const arches = run(['lipo', '-archs', bin]).out.trim().split(/\s+/).sort(); + const sideArches = run(['lipo', '-archs', join(appPath, 'Contents/MacOS', PRODUCT)]).out.trim().split(/\s+/).sort(); + if (arches.join(' ') !== 'arm64 x86_64' || sideArches.join(' ') !== 'arm64 x86_64') fail(`${label}: not universal (app ${arches}, sidecar ${sideArches})`); + const rosetta = run(['arch', '-x86_64', '/usr/bin/true'], { allowFail: true }).code === 0; + for (const arch of rosetta ? ['arm64', 'x86_64'] : [process.arch === 'arm64' ? 'arm64' : 'x86_64']) { + const r = run(['arch', `-${arch}`, bin, '--self-test'], { allowFail: true, timeout: 90_000 }); + if (r.code !== 0) fail(`${label}: self-test (${arch}) failed: ${r.err.trim() || r.out.trim()}`); + const result = JSON.parse(r.out.trim().split('\n').at(-1)!) as Record; + if (result.ok !== true || result.protocol !== 'storebound-desktop/1') fail(`${label}: self-test (${arch}) answered ${r.out}`); + say(`self-test ${label} (${arch}): sidecar ${result.sidecar}, ${result.methods} methods, ${result.ms} ms`); + out.push({ arch, result }); + } + if (!rosetta) say('self-test: Rosetta is not installed, x86_64 slice not run (softwareupdate --install-rosetta to cover it)'); + return out; +} + +export interface Gate { codesign: string; spctl: string; stapler: string; binaries: string[] } + +/** Signature checks of one app, inside out: every executable in Contents/MacOS (the app and the CLI sidecar), then the + * bundle. Signed: Developer ID, hardened runtime, a secure timestamp, no sandbox entitlement (Developer ID, not the + * Mac App Store), Gatekeeper accepts it as notarized and the ticket is stapled. Unsigned: ad-hoc, Gatekeeper rejects. */ +function gatekeeper(appPath: string, signed: boolean, notarized: boolean, label: string): Gate { + run(['codesign', '--verify', '--deep', '--strict', '--verbose=2', appPath]); + const binaries: string[] = []; + const macos = join(appPath, 'Contents/MacOS'); + for (const name of [...readdirSync(macos).sort(), '']) { + const target = name ? join(macos, name) : appPath; + const info = run(['codesign', '-dvv', '--verbose=4', target]).err; + const flags = /flags=0x[0-9a-f]+\(([^)]*)\)/.exec(info)?.[1] ?? ''; + const authority = /Authority=(Developer ID Application[^\n]*)/.exec(info)?.[1]; + const ents = run(['codesign', '-d', '--entitlements', '-', '--xml', target], { allowFail: true }).out; + const what = name || APP_NAME; + if (signed) { + if (!authority) fail(`${label}: ${what} is not signed with Developer ID`); + if (!/runtime/.test(flags)) fail(`${label}: ${what} has no hardened runtime`); + if (!/Timestamp=/.test(info)) fail(`${label}: ${what} has no secure timestamp`); + if (/com\.apple\.security\.app-sandbox/.test(ents)) fail(`${label}: ${what} carries the App Sandbox entitlement (Mac App Store), not for Developer ID`); + if (/get-task-allow/.test(ents)) fail(`${label}: ${what} is debuggable (get-task-allow)`); + } else if (!/Signature=adhoc/.test(info)) fail(`${label}: unsigned build should be ad-hoc signed (${what})`); + binaries.push(`${what}: ${signed ? 'Developer ID' : 'ad-hoc'}, flags ${flags || 'none'}${/Timestamp=/.test(info) ? ', timestamped' : ''}${/allow-jit/.test(ents) ? ', JIT entitlement' : ''}`); + } + const sp = run(['spctl', '-a', '-vvv', '-t', 'exec', appPath], { allowFail: true }); + const spOut = (sp.err || sp.out).trim(); + const spctl = `${sp.code === 0 ? 'accepted' : 'rejected'}: ${spOut.split('\n').slice(1, 3).join(' / ')}`; + let stapler = 'not stapled (unsigned)'; + if (notarized) { + if (sp.code !== 0 || !/source=Notarized Developer ID/.test(spOut)) fail(`${label}: Gatekeeper does not accept the app as notarized: ${spctl}`); + const st = run(['xcrun', 'stapler', 'validate', appPath], { allowFail: true }); + if (st.code !== 0) fail(`${label}: stapler validate failed: ${(st.out + st.err).trim()}`); + stapler = 'ticket stapled, validated'; + } else if (signed) { + stapler = 'signed, not notarized (--no-notarize)'; + } else if (sp.code === 0) { + fail(`${label}: Gatekeeper accepted an ad-hoc build: unexpected`); + } + const codesign = signed ? 'Developer ID Application, hardened runtime, timestamped' : 'ad-hoc'; + say(`${label}: codesign ${codesign}; spctl -t exec ${spctl}; ${stapler}`); + return { codesign, spctl, stapler, binaries }; +} + +/** notarytool / Tauri credentials: APPLE_API_KEY + APPLE_API_ISSUER + APPLE_API_KEY_PATH, or storebound's own + * ASC_KEY_ID + ASC_ISSUER_ID + ASC_P8 (path or PEM; default ~/.appstoreconnect/private_keys/AuthKey_.p8), or + * ~/.storebound-keys/notary.json {keyId, issuerId, keyPath}. Nothing of it is printed. */ +function notaryEnv(): Record | null { + const env = process.env; + const fromJson = (() => { + const f = join(KEYS_DIR, 'notary.json'); + if (!existsSync(f)) return {} as { keyId?: string; issuerId?: string; keyPath?: string }; + return JSON.parse(readFileSync(f, 'utf8')) as { keyId?: string; issuerId?: string; keyPath?: string }; + })(); + const id = env.APPLE_API_KEY ?? env.ASC_KEY_ID ?? fromJson.keyId; + const issuer = env.APPLE_API_ISSUER ?? env.ASC_ISSUER_ID ?? fromJson.issuerId; + if (!id || !issuer) return null; + let path = env.APPLE_API_KEY_PATH ?? env.ASC_P8 ?? fromJson.keyPath ?? join(homedir(), '.appstoreconnect/private_keys', `AuthKey_${id}.p8`); + if (/BEGIN PRIVATE KEY/.test(path)) { + const dir = mkdtempSync(join(tmpdir(), 'sb-notary-')); + writeFileSync(join(dir, `AuthKey_${id}.p8`), path, { mode: 0o600 }); + path = join(dir, `AuthKey_${id}.p8`); + } + path = path.replace(/^~(?=\/)/, homedir()); + if (!existsSync(path)) fail(`notarization key file not found (${basename(path)}): set ASC_P8 or APPLE_API_KEY_PATH`); + return { APPLE_API_KEY: id, APPLE_API_ISSUER: issuer, APPLE_API_KEY_PATH: path }; +} + +async function mac(argv: string[]): Promise { + const a = args(argv); + if (process.platform !== 'darwin') fail('the macOS build runs on a Mac'); + const remote = remoteSessionReason(process.env, run(['launchctl', 'managername'], { allowFail: true }).out.trim()); + if (remote) fail(`${remote}. Signing and notarization must run in the owner's logged-in macOS session (Terminal on the Mac itself): codesign over SSH fails with errSecInternalComponent.`); + const { version, drift } = versions(); + if (!version || drift.length) fail(`desktop version drift: ${drift.map(d => d.file).join(', ')} (bun tools/desktop-version.ts)`); + const git = gitState(); + if (git.dirty && !a.has('allow-dirty')) fail('the checkout has uncommitted changes: a release is built from a commit (--allow-dirty for a test build)'); + updaterKey(); + + const securityOut = run(['security', 'find-identity', '-v', '-p', 'codesigning']).out; + const identity = a.get('identity') ?? developerIdIdentity(securityOut); + if (a.get('identity') && !securityOut.includes(`"${a.get('identity')}"`)) fail(`identity not in the keychain: ${a.get('identity')}`); + const signed = !!identity; + const notary = signed && !a.has('no-notarize') ? notaryEnv() : null; + if (signed && !a.has('no-notarize') && !notary) fail('Developer ID found but no notarization key: set APPLE_API_KEY, APPLE_API_ISSUER, APPLE_API_KEY_PATH or write ~/.storebound-keys/notary.json (docs/desktop-release.md), or pass --no-notarize for a local test'); + const notarized = signed && !!notary; + say(`storebound desktop ${version} for macOS (universal), commit ${git.commit.slice(0, 10)}${git.dirty ? ' + uncommitted changes' : ''}: ${signed ? `signing as Developer ID${notarized ? ', notarized' : ' (not notarized)'}` : 'NO Developer ID Application identity in the keychain: ad-hoc signed preview, named -unsigned'}`); + + const out = resolve(a.get('out') ?? join(homedir(), '.storebound-releases', 'desktop', version)); + mkdirSync(resolve(a.get('target-dir') ?? '/tmp/storebound-desktop-target'), { recursive: true }); + const targetDir = realpathSync(resolve(a.get('target-dir') ?? '/tmp/storebound-desktop-target')); + if (targetDir.startsWith(homedir())) fail('--target-dir must be outside the home folder (build paths end up in binaries)'); + mkdirSync(out, { recursive: true }); + + // toolchain: rustup's (Homebrew's Rust has no x86_64 standard library for the universal build) + const cargoBin = join(homedir(), '.cargo/bin'); + const PATH = `${cargoBin}:${process.env.PATH}`; + const installed = run(['rustup', 'target', 'list', '--installed'], { env: { ...process.env, PATH } }).out; + for (const t of ['aarch64-apple-darwin', 'x86_64-apple-darwin']) if (!installed.includes(t)) fail(`rustup target ${t} missing: rustup target add ${t}`); + + // sidecars: both CPU types, then one universal file (Tauri looks for binaries/storebound-universal-apple-darwin) + say('sidecars: bun build --compile for darwin-arm64 and darwin-x64'); + const arm = await buildOne('bun-darwin-arm64'); + const x64 = await buildOne('bun-darwin-x64'); + const uni = join(SIDECAR_DIR, 'storebound-universal-apple-darwin'); + rmSync(uni, { force: true }); + run(['lipo', '-create', '-output', uni, arm, x64]); + run(['codesign', '--force', '--sign', '-', uni]); + for (const f of [arm, x64, uni]) { + const v = run([f, 'version'], { allowFail: true, timeout: 60_000 }); + if (f !== x64 && v.code !== 0) fail(`${basename(f)} does not run: ${v.err}`); + } + + // the app: tauri build with the path-free environment, CARGO_TARGET_DIR outside home + const env: Record = { ...process.env, PATH, CARGO_TARGET_DIR: targetDir, CI: 'true' }; + delete env.APPLE_API_KEY; delete env.APPLE_API_ISSUER; delete env.APPLE_API_KEY_PATH; delete env.APPLE_SIGNING_IDENTITY; + delete env.APPLE_CERTIFICATE; delete env.APPLE_ID; delete env.APPLE_PASSWORD; delete env.TAURI_SIGNING_PRIVATE_KEY; + Object.assign(env, pathFreeEnv(ROOT, env), notary ?? {}); + const override = { bundle: { macOS: signed ? { signingIdentity: identity, hardenedRuntime: true, entitlements: './entitlements.plist' } : { signingIdentity: '-' } } }; + const overrideFile = join(mkdtempSync(join(tmpdir(), 'sb-release-')), 'override.json'); + writeFileSync(overrideFile, JSON.stringify(override)); + say(`tauri build --target universal-apple-darwin --bundles app (target dir ${targetDir}; this takes a while)`); + const tb = spawnSync('bunx', ['tauri', 'build', '--target', 'universal-apple-darwin', '--bundles', 'app', '--ci', '--config', overrideFile], + { cwd: APP_DIR, env: env as Record, stdio: ['ignore', 'inherit', 'inherit'] }); + if (tb.status !== 0) fail(`tauri build failed (exit ${tb.status})`); + const bundleDir = join(targetDir, 'universal-apple-darwin/release/bundle/macos'); + const app = join(bundleDir, APP_NAME); + if (!existsSync(app)) fail(`no ${APP_NAME} in ${bundleDir}`); + const dsyms = readdirSync(bundleDir).filter(n => n.endsWith('.dSYM')); + if (dsyms.length) fail(`debug symbols next to the app: ${dsyms.join(', ')}`); + + const checks: Record = { app: gatekeeper(app, signed, notarized, 'built app') }; + const tests: Record = { app: selfTest(app, 'built app') }; + + // updater bundle: the app as Tauri's updater expects it (tar.gz, no macOS metadata, root-owned entries) + const updaterName = artifactName(version, 'updater', signed); + const updater = join(out, updaterName); + rmSync(updater, { force: true }); + run(['tar', '--uid', '0', '--gid', '0', '--uname', 'root', '--gname', 'wheel', '--no-mac-metadata', '-czf', updater, '-C', bundleDir, APP_NAME], { env: { ...process.env, COPYFILE_DISABLE: '1' } }); + + // DMG: the app and an Applications link, made with hdiutil only (no Finder scripting, nothing comes to the front) + const dmgName = artifactName(version, 'dmg', signed); + const dmg = join(out, dmgName); + const stage = mkdtempSync(join(tmpdir(), 'sb-dmg-')); + run(['ditto', app, join(stage, APP_NAME)]); + symlinkSync('/Applications', join(stage, 'Applications')); + rmSync(dmg, { force: true }); + say(`DMG ${dmgName}`); + run(['hdiutil', 'create', '-volname', PRODUCT, '-srcfolder', stage, '-fs', 'HFS+', '-format', 'UDZO', '-imagekey', 'zlib-level=9', '-ov', dmg]); + rmSync(stage, { recursive: true, force: true }); + if (signed) { + run(['codesign', '--force', '--sign', identity!, '--timestamp', dmg]); + if (notarized) { + say('notarytool submit (DMG), waiting for Apple'); + const n = run(['xcrun', 'notarytool', 'submit', dmg, '--key', notary!.APPLE_API_KEY_PATH!, '--key-id', notary!.APPLE_API_KEY!, '--issuer', notary!.APPLE_API_ISSUER!, '--wait', '--output-format', 'json'], { allowFail: true, timeout: 3_600_000 }); + const status = (() => { try { return (JSON.parse(n.out) as { status?: string }).status; } catch { return undefined; } })(); + if (status !== 'Accepted') fail(`notarization of the DMG: ${status ?? n.err.trim()}`); + run(['xcrun', 'stapler', 'staple', dmg]); + run(['xcrun', 'stapler', 'validate', dmg]); + } + } + + // the exact artifacts: mount the DMG and unpack the updater bundle, then self-test what is inside + const mnt = mkdtempSync(join(tmpdir(), 'sb-mnt-')); + run(['hdiutil', 'attach', '-readonly', '-nobrowse', '-noautoopen', '-mountpoint', mnt, dmg]); + try { + checks.dmgApp = gatekeeper(join(mnt, APP_NAME), signed, notarized, 'app in the DMG'); + tests.dmg = selfTest(join(mnt, APP_NAME), 'DMG'); + } finally { + run(['hdiutil', 'detach', mnt, '-force'], { allowFail: true }); + } + // the DMG itself, as Gatekeeper sees a downloaded disk image + const dsp = run(['spctl', '-a', '-vvv', '-t', 'open', '--context', 'context:primary-signature', dmg], { allowFail: true }); + const dmgSpctl = `${dsp.code === 0 ? 'accepted' : 'rejected'}: ${(dsp.err || dsp.out).trim().split('\n').slice(1, 3).join(' / ')}`; + let dmgStapler = 'not stapled (unsigned)'; + if (notarized) { + if (dsp.code !== 0 || !/Notarized Developer ID/.test(dsp.err + dsp.out)) fail(`Gatekeeper does not accept the DMG: ${dmgSpctl}`); + const st = run(['xcrun', 'stapler', 'validate', dmg], { allowFail: true }); + if (st.code !== 0) fail(`DMG: stapler validate failed: ${(st.out + st.err).trim()}`); + dmgStapler = 'ticket stapled, validated'; + } + say(`DMG: spctl -t open ${dmgSpctl}; ${dmgStapler}`); + const unpacked = mkdtempSync(join(tmpdir(), 'sb-upd-')); + run(['tar', '-xzf', updater, '-C', unpacked]); + checks.updaterApp = gatekeeper(join(unpacked, APP_NAME), signed, notarized, 'app in the updater bundle'); + tests.updater = selfTest(join(unpacked, APP_NAME), 'updater bundle'); + rmSync(unpacked, { recursive: true, force: true }); + + // privacy: the app folder, the DMG (mounted) and the updater bundle (unpacked) + const privacy = privacyGate([app, dmg, updater]); + + // signatures with the updater key, latest.json, SHA256SUMS + const updaterSig = signFile(updater); + const dmgSig = signFile(dmg); + const notes = a.get('notes') ?? `storebound desktop ${version}`; + const now = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'); + const manifest = mergeManifest(readManifest(out), version, notes, now, { + platforms: { + 'darwin-aarch64': { signature: updaterSig, url: releaseUrl(version, updaterName) }, + 'darwin-x86_64': { signature: updaterSig, url: releaseUrl(version, updaterName) }, + }, + downloads: { 'macos-universal-dmg': { file: dmgName, url: releaseUrl(version, dmgName), sha256: sha256(dmg), size: statSync(dmg).size, signature: dmgSig, codeSigned: notarized } }, + }); + writeVersionFiles(out, manifest); + + const artifacts = [dmg, updater].map(f => ({ file: basename(f), size: statSync(f).size, sha256: sha256(f) })); + const evidence = { + product: 'storebound desktop', version, platform: 'macos-universal', builtAt: now, commit: git.commit, dirty: git.dirty, + signing: signed ? { identity: 'Developer ID Application', notarized, hardenedRuntime: true } : { identity: 'ad-hoc', notarized: false, note: 'no Developer ID Application certificate in the keychain' }, + tools: { + rustc: run(['rustc', '--version'], { env: { ...process.env, PATH } }).out.trim(), bun: Bun.version, + tauri: run(['bunx', 'tauri', '--version'], { cwd: APP_DIR }).out.trim(), macos: run(['sw_vers', '-productVersion']).out.trim(), darwin: osRelease(), + }, + checks: { ...checks, dmg: { spctl: dmgSpctl, stapler: dmgStapler }, selfTest: tests, privacy }, + artifacts, + }; + writeFileSync(join(out, `evidence-macos-${version}.json`), `${JSON.stringify(evidence, null, 2)}\n`); + + console.log(`\nstorebound desktop ${version} for macOS: ${out.replace(homedir(), '~')}`); + for (const x of artifacts) console.log(` ${x.file.padEnd(48)} ${mb(x.size).padStart(9)} ${x.sha256}`); + console.log(' latest.json, SHA256SUMS, *.sig, evidence-macos-*.json (evidence stays local)'); + if (!signed) { + console.log(` +Unsigned preview (ad-hoc). To ship a signed, notarized build: + 1. The Account Holder of the Apple Developer team creates a "Developer ID Application" certificate + (developer.apple.com > Certificates > +; a CSR from Keychain Access on this Mac) and installs it here. + 2. App Store Connect API key for notarytool (Users and Access > Integrations, role Developer): + ~/.storebound-keys/notary.json {"keyId": "...", "issuerId": "...", "keyPath": "~/.storebound-keys/AuthKey_.p8"} + 3. Run this again in Terminal on the Mac (not over SSH).`); + } + console.log(`\nnext: add Windows / Linux (bun tools/desktop-release.ts add --out ${out.replace(homedir(), '~')} ), then publish (docs/desktop-release.md).`); +} + +// --------------------------------------------------------------------------------------------------------------------- +// add (Windows / Linux installers from the Forgejo workflow) + +function add(argv: string[]): void { + const a = args(argv); + const { version, drift } = versions(); + if (!version || drift.length) fail('desktop version drift (bun tools/desktop-version.ts)'); + const out = resolve(a.get('out') ?? join(homedir(), '.storebound-releases', 'desktop', version)); + const files = a.rest.slice(1); + if (!files.length) fail('usage: add --out '); + mkdirSync(out, { recursive: true }); + const codeSigned = a.has('code-signed'); + const platforms: Manifest['platforms'] = {}; + const downloads: Partial> = {}; + const added: string[] = []; + for (const f of files.map(x => resolve(x))) { + const n = basename(f); + if (!n.includes(`_${version}_`)) fail(`${n} is not version ${version}`); + const kind = /-setup\.exe$/i.test(n) ? 'nsis' : /\.AppImage$/.test(n) ? 'appimage' : /\.deb$/.test(n) ? 'deb' : null; + if (!kind) fail(`${n}: expected an NSIS setup .exe, an .AppImage or a .deb`); + const name = artifactName(version, kind, kind === 'nsis' ? codeSigned : true); + const dest = join(out, name); + copyFileSync(f, dest); + added.push(dest); + } + privacyGate(added); + for (const dest of added) { + const name = basename(dest); + const sig = signFile(dest); + const d: Download = { file: name, url: releaseUrl(version, name), sha256: sha256(dest), size: statSync(dest).size, signature: sig, codeSigned: name.endsWith('.exe') ? codeSigned : false }; + if (name.endsWith('.exe')) { downloads['windows-x86_64-nsis'] = d; platforms['windows-x86_64'] = { signature: sig, url: d.url }; } + else if (name.endsWith('.AppImage')) { downloads['linux-x86_64-appimage'] = d; platforms['linux-x86_64'] = { signature: sig, url: d.url }; } + else downloads['linux-x86_64-deb'] = d; + say(`added ${name} (${mb(d.size)})`); + } + const existing = readManifest(out); + writeVersionFiles(out, mergeManifest(existing, version, a.get('notes') ?? existing?.notes ?? `storebound desktop ${version}`, new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'), { platforms, downloads })); + say(`latest.json now has ${Object.keys(readManifest(out)!.platforms).join(', ')}`); +} + +// --------------------------------------------------------------------------------------------------------------------- +// verify / publish + +function verifyFolder(out: string): { manifest: Manifest; files: string[] } { + if (!existsSync(join(out, 'latest.json')) || !existsSync(join(out, 'SHA256SUMS'))) fail(`${out}: no latest.json / SHA256SUMS`); + const manifest = readManifest(out)!; + const problems = manifestProblems(manifest); + if (problems.length) fail(`latest.json: ${problems.join('; ')}`); + const sums = readFileSync(join(out, 'SHA256SUMS'), 'utf8').trim().split('\n').map(l => { const [h, f] = l.split(/\s+/); return { h: h!, f: f! }; }); + for (const { h, f } of sums) if (!existsSync(join(out, f)) || sha256(join(out, f)) !== h) fail(`SHA256SUMS: ${f} does not match`); + const files = readdirSync(out).filter(uploadable); + for (const f of files) if (f !== 'SHA256SUMS' && !sums.some(s => s.f === f)) fail(`${f} is not in SHA256SUMS`); + const pub = confPubkey(); + const check = (url: string, signature: string, what: string) => { + const file = url.split('/').pop()!; + if (!url.startsWith(releaseUrl(manifest.version, ''))) fail(`${what}: ${url} is not in /desktop/dl/${manifest.version}/`); + if (!files.includes(file)) fail(`${what}: ${file} is not in the folder`); + const v = verifySig(readFileSync(join(out, file)), signature, pub); + if (!v.ok) fail(`${what}: ${file}: ${v.reason}`); + }; + for (const [k, p] of Object.entries(manifest.platforms)) check(p.url, p.signature, `platforms.${k}`); + for (const [k, d] of Object.entries(manifest.downloads ?? {})) { + check(d!.url, d!.signature, `downloads.${k}`); + if (sha256(join(out, d!.file)) !== d!.sha256 || statSync(join(out, d!.file)).size !== d!.size) fail(`downloads.${k}: size or SHA-256 differ from the file`); + } + privacyGate(files.filter(f => !/\.(sig|json)$|^SHA256SUMS$/.test(f)).map(f => join(out, f))); + say(`verified ${manifest.version}: ${files.length} files, platforms ${Object.keys(manifest.platforms).join(', ')}, downloads ${Object.keys(manifest.downloads ?? {}).join(', ')}`); + return { manifest, files }; +} + +function publish(argv: string[]): void { + const a = args(argv); + const out = resolve(a.get('out') ?? fail('--out is required')); + const host = a.get('host') ?? process.env.STOREBOUND_PUBLISH_HOST ?? fail('--host (or STOREBOUND_PUBLISH_HOST) is required'); + if (!/^[A-Za-z0-9._-]+@[A-Za-z0-9.-]+$/.test(host)) fail(`--host: user@host, got ${host}`); + const channel = a.get('channel') ?? 'stable'; + if (!['stable', 'beta'].includes(channel)) fail('--channel stable or beta'); + const { manifest, files } = verifyFolder(out); + const v = manifest.version; + const unsigned = Object.values(manifest.downloads ?? {}).filter(d => !d!.codeSigned && /\.(dmg|exe)$/.test(d!.file)).map(d => d!.file); + const steps = [ + ['ssh', host, `mkdir -p ${REMOTE_INCOMING}/${v} && chmod 700 ${REMOTE_INCOMING}`], + ['rsync', '-a', '--chmod=F644,D755', '--delete', ...files.map(f => join(out, f)), `${host}:${REMOTE_INCOMING}/${v}/`], + ['ssh', host, `${REMOTE_PUBLISH} ${v} ${channel}`], + ]; + console.log(`\npublish storebound desktop ${v} to the ${channel} channel (${channel === 'stable' ? `${BASE_URL}/latest.json` : `${BASE_URL}/beta/latest.json`}):`); + for (const f of files) console.log(` ${f}`); + if (unsigned.length) console.log(` note: unsigned preview builds (${unsigned.join(', ')}); the downloads page says so.`); + console.log('\nsteps:'); + for (const s of steps) console.log(` ${s[0]} ${s.slice(1).map(x => (x.includes(' ') ? `"${x}"` : x.replace(out, ''))).join(' ')}`); + if (!a.has('yes')) { console.log('\ndry run: nothing uploaded. Every installed app on this channel offers the update once latest.json is live; run again with --yes to publish.'); return; } + for (const s of steps) { say(`${s[0]} ...`); run(s, { stdio: ['ignore', 'inherit', 'inherit'] }); } + const live = spawnSync('curl', ['-fsS', channel === 'stable' ? `${BASE_URL}/latest.json` : `${BASE_URL}/beta/latest.json`], { encoding: 'utf8' }); + if (live.status !== 0 || (JSON.parse(live.stdout) as Manifest).version !== v) fail('latest.json on storebound.dev is not the new version yet'); + say(`live: ${BASE_URL}/ serves ${v}`); +} + +if (import.meta.main) { + const argv = process.argv.slice(2); + const cmd = argv[0]; + if (cmd === 'mac') await mac(argv.slice(1)); + else if (cmd === 'add') add(argv); + else if (cmd === 'verify') verifyFolder(resolve(args(argv).get('out') ?? fail('--out '))); + else if (cmd === 'publish') publish(argv.slice(1)); + else if (cmd === 'exec') { + // `exec -- `: runs a build command with the path-free environment (the Forgejo workflow uses it) + const cmdline = argv.slice(argv.indexOf('--') + 1); + if (argv.indexOf('--') < 0 || !cmdline.length) fail('usage: exec -- '); + const r = spawnSync(cmdline[0]!, cmdline.slice(1), { stdio: 'inherit', env: { ...process.env, ...pathFreeEnv(ROOT, process.env) }, shell: process.platform === 'win32' }); + process.exit(r.status ?? 1); + } + else { console.log(readFileSync(import.meta.path, 'utf8').split('\n').filter(l => l.startsWith('//')).slice(0, 26).map(l => l.slice(3)).join('\n')); process.exit(cmd ? 2 : 0); } +} + diff --git a/tools/privacy-scan.ts b/tools/privacy-scan.ts new file mode 100644 index 00000000..c369420f --- /dev/null +++ b/tools/privacy-scan.ts @@ -0,0 +1,246 @@ +#!/usr/bin/env bun +// Release gate: nothing storebound ships may name a person, an account or a machine. Scans files, folders (an .app +// bundle) and archives (DMG, .tar.gz, .deb, .zip, AppImage, NSIS installer) for +// +// - forbidden terms: a file kept OUTSIDE every repository (STOREBOUND_FORBIDDEN_TERMS, else +// ~/.storebound-keys/forbidden-terms.txt; one term per line, # comments), plus what this machine says about its +// owner: account name, home folder, full name (macOS), host and computer names, git's global identity (unless it +// is the release identity), and the private-name rule of tools/scrub.ts; +// - home folders of any account (/Users/, /home/, C:\Users\), generic accounts excepted +// (runner, you, ...), in case a build machine other than this one made a file; +// - debug files that must not ship: .dSYM bundles, .pdb, source maps. +// +// Every file is searched as bytes in UTF-8 and UTF-16LE, ASCII case-insensitively. A term is never printed: a hit +// shows the file (inside its archive), the byte offset and the term as its first letter plus ***. A container that +// cannot be opened is an error, not a pass. +// +// bun tools/privacy-scan.ts [--terms ] [--json] exit 0 clean, 1 hits, 2 could not open +import { spawnSync } from 'node:child_process'; +import { existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs'; +import { homedir, hostname, tmpdir, userInfo } from 'node:os'; +import { basename, join, relative } from 'node:path'; +import { RULES } from './scrub'; + +export const TERMS_ENV = 'STOREBOUND_FORBIDDEN_TERMS'; +export const DEFAULT_TERMS = join(homedir(), '.storebound-keys', 'forbidden-terms.txt'); +/** The identity every release commit uses: not personal (the address is put together so scrub's email rule passes). */ +const RELEASE_IDENTITY = new Set(['crt', ['hi', 'crt.fyi'].join('@'), 'crtkafa']); +/** Account names that say nothing about a person (never added automatically, allowed after /Users/ or /home/). */ +export const GENERIC = new Set(['root', 'user', 'users', 'admin', 'administrator', 'runner', 'runneradmin', 'ubuntu', 'build', 'builder', 'ci', + 'docker', 'node', 'vagrant', 'default', 'nobody', 'home', 'dev', 'developer', 'owner', 'guest', 'test', 'app', 'work', 'shared', 'public', + 'you', 'me', 'name', 'example', 'username', 'yourname', 'travis', 'circleci', 'jenkins', 'buildkite', 'vsts', 'cloudtest', 'appveyor', + 'pi', 'ec2-user', 'azureuser', 'vscode', 'codespace', 'gitpod', 'linuxbrew', 'abuild', 'buildbot', 'mockbuild', 'pbuilder', 'portage']); + +export interface Term { text: string; short: boolean } +export interface Hit { file: string; offset: number; what: string; encoding?: string } +export interface Report { files: number; bytes: number; hits: Hit[]; errors: string[] } + +const sh = (cmd: string[]): string => { + const r = spawnSync(cmd[0]!, cmd.slice(1), { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }); + return r.status === 0 ? r.stdout.trim() : ''; +}; + +export function parseTerms(text: string): string[] { + return text.split(/\r?\n/).map(l => l.trim()).filter(l => l && !l.startsWith('#')); +} + +/** The terms of the file (if any) plus what this machine says about its owner. */ +export function collectTerms(file: string | null, auto = true): Term[] { + const seen = new Map(); + const add = (t: string, automatic: boolean) => { + const v = t.trim(); + const k = v.toLowerCase(); + if (v.length < 2 || seen.has(k) || RELEASE_IDENTITY.has(k) || (automatic && GENERIC.has(k))) return; + seen.set(k, { text: v, short: v.length <= 3 }); + }; + if (file && existsSync(file)) for (const t of parseTerms(readFileSync(file, 'utf8'))) add(t, false); + if (auto) { + let user = ''; + try { user = userInfo().username; } catch { /* no passwd entry */ } + add(user, true); + add(basename(homedir()), true); + if (homedir().length > 4) add(homedir(), true); + const host = hostname().replace(/\.local$/i, ''); + add(host, true); + if (process.platform === 'darwin') { + add(sh(['scutil', '--get', 'ComputerName']), true); + add(sh(['scutil', '--get', 'LocalHostName']), true); + const real = sh(['id', '-F']); + add(real, true); + for (const part of real.split(/\s+/)) if (part.length >= 4) add(part, true); + } + for (const k of ['user.name', 'user.email']) add(sh(['git', 'config', '--global', k]), true); + } + return [...seen.values()]; +} + +/** The private-name rule of tools/scrub.ts as a plain term (scrub keeps it in parts so no file spells it). */ +function scrubTerms(): Term[] { + const r = RULES.find(x => x.id === 'private-name'); + const src = r?.re.source ?? ''; + return /^[A-Za-z]+$/.test(src) ? [{ text: src, short: false }] : []; +} + +export const mask = (t: string): string => `${t[0]}***`; + +/** ASCII lower-casing on bytes, so one native indexOf finds every case. */ +function lowerAscii(b: Uint8Array): Buffer { + const out = Buffer.from(b); + for (let i = 0; i < out.length; i++) { const c = out[i]!; if (c >= 0x41 && c <= 0x5a) out[i] = c | 0x20; } + return out; +} + +const PATH_BEFORE = /(?:\/users\/|\/home\/|\\users\\|[\\/])$/; +const HOME_RE = /(?:\/Users\/|\/home\/|[A-Za-z]:\\Users\\)([A-Za-z0-9._-]{2,40})/g; + +/** Searches one buffer. `name` is the shown file name. */ +export function scanBuffer(name: string, data: Uint8Array, terms: Term[]): Hit[] { + const hits: Hit[] = []; + const low = lowerAscii(data); + for (const t of terms) { + for (const enc of ['utf8', 'utf16le'] as const) { + const needle = lowerAscii(Buffer.from(t.text, enc)); + let at = low.indexOf(needle); + let n = 0; + while (at >= 0 && n < 5) { + if (!t.short || PATH_BEFORE.test(low.subarray(Math.max(0, at - 8 * (enc === 'utf8' ? 1 : 2)), at).toString('latin1').replace(/\0/g, ''))) { + hits.push({ file: name, offset: at, what: `term ${mask(t.text)}`, encoding: enc }); + n++; + } + at = low.indexOf(needle, at + 1); + } + } + } + // home folders of other accounts (UTF-8 and UTF-16LE read as one latin1 string each) + const views: [string, string][] = [['utf8', Buffer.from(data).toString('latin1')]]; + if (data.length > 1) views.push(['utf16le', Buffer.from(data.buffer, data.byteOffset, data.length - (data.length % 2)).toString('utf16le')]); + for (const [enc, s] of views) { + let n = 0; + for (const m of s.matchAll(HOME_RE)) { + if (GENERIC.has(m[1]!.toLowerCase()) || /^(?:\$|%|<|\{)/.test(m[1]!)) continue; + hits.push({ file: name, offset: enc === 'utf8' ? m.index! : m.index! * 2, what: `home folder of an account (${mask(m[1]!)})`, encoding: enc }); + if (++n >= 5) break; + } + } + return hits; +} + +const FORBIDDEN_FILE = /(?:\.dSYM$|\.pdb$|\.map$)/i; + +type Kind = 'dir' | 'dmg' | 'tar' | 'deb' | 'zip' | 'appimage' | 'nsis' | 'file'; + +export function kindOf(path: string, head: Uint8Array): Kind { + const n = path.toLowerCase(); + if (n.endsWith('.dmg')) return 'dmg'; + if (n.endsWith('.deb')) return 'deb'; + if (/\.(tar\.gz|tgz|tar|tar\.xz|tar\.zst)$/.test(n)) return 'tar'; + if (n.endsWith('.zip') || n.endsWith('.nupkg')) return 'zip'; + if (n.endsWith('.appimage')) return 'appimage'; + if (n.endsWith('.exe') && Buffer.from(head).includes(Buffer.from('Nullsoft'))) return 'nsis'; + return 'file'; +} + +function which(...names: string[]): string | null { + for (const n of names) { const p = Bun.which(n); if (p) return p; } + return null; +} + +/** Unpacks a container into a temp folder; returns the folder (caller removes it) or throws. */ +function unpack(path: string, kind: Kind): { dir: string; cleanup: () => void } { + const dir = mkdtempSync(join(tmpdir(), 'sb-privacy-')); + const cleanup = () => rmSync(dir, { recursive: true, force: true }); + const run = (cmd: string[]) => { + const r = spawnSync(cmd[0]!, cmd.slice(1), { stdio: ['ignore', 'ignore', 'pipe'], encoding: 'utf8' }); + if (r.status !== 0) { cleanup(); throw new Error(`${basename(path)}: ${basename(cmd[0]!)} failed: ${(r.stderr || '').trim().split('\n').at(-1)}`); } + }; + if (kind === 'dmg') { + if (process.platform !== 'darwin') { cleanup(); throw new Error(`${basename(path)}: DMG needs macOS (hdiutil)`); } + const mnt = join(dir, 'mnt'); + run(['hdiutil', 'attach', '-readonly', '-nobrowse', '-noverify', '-noautoopen', '-mountpoint', mnt, path]); + return { dir: mnt, cleanup: () => { spawnSync('hdiutil', ['detach', mnt, '-force'], { stdio: 'ignore' }); cleanup(); } }; + } + if (kind === 'tar' || kind === 'zip' || kind === 'deb') { + // bsdtar (macOS, Windows) reads tar, zip and ar; GNU tar on Linux reads tar, the others go through ar / unzip + if (kind === 'deb' && process.platform === 'linux') { + run(['ar', 'x', '--output', dir, path]); + for (const f of readdirSync(dir)) if (/^(data|control)\.tar/.test(f)) { const sub = join(dir, f.replace(/\..*$/, '')); mkdirSync(sub, { recursive: true }); run(['tar', '-xf', join(dir, f), '-C', sub]); } + return { dir, cleanup }; + } + if (kind === 'zip' && process.platform === 'linux') { run(['unzip', '-q', path, '-d', dir]); return { dir, cleanup }; } + run(['tar', '-xf', path, '-C', dir]); + if (kind === 'deb') for (const f of readdirSync(dir)) if (/^(data|control)\.tar/.test(f)) { const sub = join(dir, f.replace(/\..*$/, '')); mkdirSync(sub, { recursive: true }); run(['tar', '-xf', join(dir, f), '-C', sub]); } + return { dir, cleanup }; + } + if (kind === 'appimage') { + const unsq = which('unsquashfs'); + const data = readFileSync(path); + const off = data.indexOf(Buffer.from('hsqs'), 0x400); + if (unsq && off > 0) { run([unsq, '-q', '-n', '-d', join(dir, 'root'), '-o', String(off), path]); return { dir: join(dir, 'root'), cleanup }; } + const z = which('7zz', '7z'); + if (z) { run([z, 'x', '-y', `-o${dir}`, path]); return { dir, cleanup }; } + cleanup(); throw new Error(`${basename(path)}: AppImage needs unsquashfs (squashfs-tools) or 7-Zip`); + } + if (kind === 'nsis') { + const z = which('7zz', '7z'); + if (!z) { cleanup(); throw new Error(`${basename(path)}: NSIS installer needs 7-Zip (7z / 7zz)`); } + run([z, 'x', '-y', `-o${dir}`, path]); + return { dir, cleanup }; + } + cleanup(); + throw new Error(`${basename(path)}: not a container`); +} + +export function scanPath(path: string, terms: Term[], shown = basename(path), report: Report = { files: 0, bytes: 0, hits: [], errors: [] }): Report { + const st = lstatSync(path); + if (FORBIDDEN_FILE.test(path)) report.hits.push({ file: shown, offset: 0, what: 'debug file that must not ship (.dSYM / .pdb / source map)' }); + if (st.isSymbolicLink()) return report; + if (st.isDirectory()) { + for (const n of readdirSync(path).sort()) scanPath(join(path, n), terms, `${shown}/${n}`, report); + return report; + } + if (!st.isFile()) return report; + const data = readFileSync(path); + report.files++; + report.bytes += data.length; + // the file's own bytes (names, uncompressed parts), then what is inside a container + report.hits.push(...scanBuffer(shown, data, terms)); + const kind = kindOf(path, data.subarray(0, 1 << 20)); + if (kind !== 'file' && kind !== 'dir') { + let u: { dir: string; cleanup: () => void } | null = null; + try { + u = unpack(path, kind); + scanPath(u.dir, terms, `${shown}!`, report); + } catch (e) { + report.errors.push((e as Error).message); + } finally { + u?.cleanup(); + } + } + return report; +} + +export function scan(paths: string[], termsFile: string | null = process.env[TERMS_ENV] ?? DEFAULT_TERMS, auto = true): Report & { terms: number; termsFile: string | null } { + const terms = [...collectTerms(termsFile, auto), ...scrubTerms()]; + const report: Report = { files: 0, bytes: 0, hits: [], errors: [] }; + for (const p of paths) { + if (!existsSync(p)) { report.errors.push(`${p}: does not exist`); continue; } + scanPath(p, terms, basename(p), report); + } + return { ...report, terms: terms.length, termsFile: termsFile && existsSync(termsFile) ? termsFile : null }; +} + +if (import.meta.main) { + const argv = process.argv.slice(2); + const ti = argv.indexOf('--terms'); + const termsFile = ti >= 0 ? argv[ti + 1] ?? null : process.env[TERMS_ENV] ?? DEFAULT_TERMS; + const paths = argv.filter((a, i) => !a.startsWith('--') && !(ti >= 0 && i === ti + 1)); + if (!paths.length) { console.error('usage: bun tools/privacy-scan.ts [--terms ] [--json]'); process.exit(2); } + const r = scan(paths, termsFile); + if (argv.includes('--json')) console.log(JSON.stringify({ ...r, termsFile: r.termsFile ? relative(homedir(), r.termsFile).replace(/^/, '~/') : null }, null, 2)); + else { + for (const h of r.hits) console.error(`privacy: ${h.file} @${h.offset}${h.encoding ? ` (${h.encoding})` : ''}: ${h.what}`); + for (const e of r.errors) console.error(`privacy: could not open ${e}`); + console.log(`privacy-scan: ${r.files} files, ${(r.bytes / 1e6).toFixed(1)} MB, ${r.terms} terms${r.termsFile ? ' (with the terms file)' : ' (no terms file: only this machine\'s names)'}, ${r.hits.length} hits, ${r.errors.length} errors`); + } + process.exit(r.hits.length ? 1 : r.errors.length ? 2 : 0); +} diff --git a/tools/vds/apache-storebound-desktop.conf b/tools/vds/apache-storebound-desktop.conf new file mode 100644 index 00000000..50caf44f --- /dev/null +++ b/tools/vds/apache-storebound-desktop.conf @@ -0,0 +1,25 @@ +# storebound desktop downloads on storebound.dev (included in the :443 vhost of /etc/apache2/sites-available/storebound.dev.conf +# as Include /etc/apache2/storebound-desktop.conf ; see docs/desktop-release.md). +# The page itself (site/desktop/index.html) comes with the site; the binaries and latest.json live outside the site's +# document root, because the site's publish rsync deletes everything that is not in the repository. +Alias /desktop/latest.json /var/www/storebound-desktop/latest.json +Alias /desktop/beta/latest.json /var/www/storebound-desktop/beta/latest.json +Alias /desktop/dl/ /var/www/storebound-desktop/dl/ + + Options -Indexes -FollowSymLinks + AllowOverride None + Require all granted + + ForceType application/octet-stream + Header set Content-Disposition "attachment" + + + + Header set Cache-Control "no-cache" + Header set Access-Control-Allow-Origin "*" + + + # a published file never changes (a new version gets a new folder) + Header set Cache-Control "public, max-age=31536000, immutable" + Header set X-Content-Type-Options "nosniff" + diff --git a/tools/vds/storebound-desktop-publish b/tools/vds/storebound-desktop-publish new file mode 100755 index 00000000..e0a3a6a0 --- /dev/null +++ b/tools/vds/storebound-desktop-publish @@ -0,0 +1,78 @@ +#!/usr/bin/env bash +# Root-owned publish step for storebound desktop releases (install as /usr/local/sbin/storebound-desktop-publish, +# root:root 755; see docs/desktop-release.md). tools/desktop-release.ts publish uploads one version folder to +# /var/lib/storebound-desktop/incoming// and then runs: storebound-desktop-publish [stable|beta] +# +# It checks the upload (regular files with plain names only, SHA256SUMS, latest.json of that version whose every URL +# points at an uploaded file of /desktop/dl//), copies the files into /var/www/storebound-desktop/dl// +# (a new version: a temp folder renamed into place; an existing version: only new files, a file already published is +# never replaced by different bytes), and only then swaps latest.json of the channel atomically (temp file + rename). +# Apache serves that folder under https://storebound.dev/desktop/ (tools/vds/apache-storebound-desktop.conf), apart +# from the site's own rsync, which deletes what is not in the repository. Nothing from the upload is executed. +set -euo pipefail +umask 022 + +VERSION="${1:-}" +CHANNEL="${2:-stable}" +INCOMING=/var/lib/storebound-desktop/incoming +ROOT=/var/www/storebound-desktop +SITE=https://storebound.dev/desktop + +die() { echo "storebound-desktop-publish: $*" >&2; exit 1; } +[[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$ ]] || die "usage: storebound-desktop-publish [stable|beta]" +[[ "$CHANNEL" == stable || "$CHANNEL" == beta ]] || die "channel: stable or beta" +IN="$INCOMING/$VERSION" +DL="$ROOT/dl/$VERSION" +[ -d "$IN" ] && [ ! -L "$IN" ] || die "nothing uploaded at $IN" + +# only regular files with plain names, nothing hidden, no folders, no links +if find "$IN" -mindepth 1 \( ! -type f -o -name '.*' \) -print | grep -q .; then die "the upload holds something other than plain files"; fi +if find "$IN" -mindepth 1 -type f -printf '%f\n' | grep -Ev '^[A-Za-z0-9][A-Za-z0-9._-]*$' | grep -q .; then die "a file name has unexpected characters"; fi +[ -f "$IN/latest.json" ] && [ -f "$IN/SHA256SUMS" ] || die "latest.json and SHA256SUMS are required" +(cd "$IN" && sha256sum --quiet --strict -c SHA256SUMS) || die "SHA256SUMS does not match the files" + +python3 - "$IN" "$VERSION" "$SITE" <<'PY' || die "latest.json does not describe this upload" +import json, os, re, sys +src, version, site = sys.argv[1], sys.argv[2], sys.argv[3] +m = json.load(open(os.path.join(src, "latest.json"))) +assert m.get("version") == version, "version" +files = set(os.listdir(src)) +listed = {l.split()[1] for l in open(os.path.join(src, "SHA256SUMS")) if l.strip()} +assert files - {"SHA256SUMS"} <= listed, "files missing from SHA256SUMS" +prefix = f"{site}/dl/{version}/" +entries = list((m.get("platforms") or {}).values()) + list((m.get("downloads") or {}).values()) +assert entries, "no platforms" +for e in entries: + url = e.get("url", "") + assert url.startswith(prefix), url + name = url[len(prefix):] + assert re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", name) and name in files, url + assert e.get("signature"), url +PY + +install -d -m 755 "$ROOT" "$ROOT/dl" "$ROOT/beta" +if [ ! -e "$DL" ]; then + TMP="$(mktemp -d "$ROOT/dl/.tmp-$VERSION.XXXXXX")" + for f in "$IN"/*; do n="$(basename "$f")"; [ "$n" = latest.json ] || install -m 644 "$f" "$TMP/$n"; done + chmod 755 "$TMP" + mv -T "$TMP" "$DL" +else + for f in "$IN"/*; do + n="$(basename "$f")" + [ "$n" = latest.json ] && continue + if [ -e "$DL/$n" ]; then + [ "$n" = SHA256SUMS ] && continue + cmp -s "$f" "$DL/$n" || die "$n is already published with other bytes: a published file is never replaced (bump the version)" + else + install -m 644 "$f" "$DL/.$n.tmp" && mv -f "$DL/.$n.tmp" "$DL/$n" + fi + done + install -m 644 "$IN/SHA256SUMS" "$DL/.SHA256SUMS.tmp" && mv -f "$DL/.SHA256SUMS.tmp" "$DL/SHA256SUMS" +fi + +# latest.json last: installed apps see the new version only once every file it names is in place +if [ "$CHANNEL" = stable ]; then LJ="$ROOT/latest.json"; URL="$SITE/latest.json"; else LJ="$ROOT/beta/latest.json"; URL="$SITE/beta/latest.json"; fi +install -m 644 "$IN/latest.json" "$LJ.tmp" +mv -f "$LJ.tmp" "$LJ" +rm -rf "$IN" +curl -fsS -o /dev/null --resolve storebound.dev:443:127.0.0.1 "$URL" && echo "storebound desktop $VERSION published ($CHANNEL): $URL"