diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index b877dbd..2324eb8 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -7,25 +7,27 @@ Electron desktop app (by IronFlock) for flashing IronFlockOS onto IoT devices. T ```bash npm run dev # Development mode with HMR (electron-vite) npm run dev:debug # Dev mode with --inspect for the main process -npm run build # Typecheck + electron-vite build +npm run build # Typecheck + electron-vite build + the command-line tool +npm run build:cli # The command-line tool only: out/cli/flockflasher.cjs (vite.cli.config.ts) npm run typecheck # tsc for main/preload (tsconfig.node.json) + vue-tsc for renderer (tsconfig.web.json) npm test # Vitest unit tests (test/*.test.ts) — pure logic in src/main/security + utils npm run test:watch # Vitest watch mode npm run lint # ESLint 9 flat config (eslint.config.mjs) with --fix npm run format # Prettier (owns formatting; eslint uses flat/essential + skip-formatting) +just cli ARGS # Build the command-line tool and run it (images, drives; flash needs sudo node out/cli/flockflasher.cjs) just package # This OS's installer into dist/ (just natives + build + installer), never publishes just release-patch # Release PR (-minor/-major); its merge builds, publishes and tags in CI just merge [TITLE] # No-release PR ``` -Vitest covers only the pure, Electron-free modules (validation, sudo-arg building, sha256, progress math, the signed catalog and its loader, variant choice, the FLOCKOS partition choice and its per-OS commands through fake runners); elevated flashing and drive I/O are covered by manual per-OS smoke tests. VS Code users can use the "Debug All" compound launch config (main + renderer debugging). Dev/CI Node is pinned by `.nvmrc` + `engines` to Node 22 (`nvm use`). +Vitest covers only the pure, Electron-free modules (validation, sudo-arg building, sha256, progress math, the signed catalog and its loader, variant choice, the IRONFLOCKOS partition choice and its per-OS commands through fake runners); elevated flashing and drive I/O are covered by manual per-OS smoke tests. VS Code users can use the "Debug All" compound launch config (main + renderer debugging). Dev/CI Node is pinned by `.nvmrc` + `engines` to Node 22 (`nvm use`). **Native build requirement (macOS):** `drivelist` and `mountutils` compile from source (no arm64 prebuilds), so `npm install` needs working Command Line Tools **with the C++ stdlib headers in the toolchain path**. On very new macOS/Xcode a stale CLT can miss them (`fatal error: 'functional'/'cstdlib' file not found`); fix with `sudo rm -rf /Library/Developer/CommandLineTools && sudo xcode-select --install` (or install full Xcode). **Linux (GCC):** with node-gyp's `V8_DEPRECATION_WARNINGS`, Electron 43's `v8-primitive.h` puts `[[deprecated]]` before a GNU visibility attribute, which GCC rejects (`expected identifier before '__attribute__'`); `prepare-natives.js` undefines the warning macros via `CPPFLAGS` for `install-app-deps` on Linux. `usb` needs `libudev-dev` there. Natives are (re)built by `postinstall` → `scripts/prepare-natives.js` (`fetch-node.js` → `electron-builder install-app-deps` → `rebuild-flash-natives.js`). With `CI` set, postinstall skips these packaging steps (the CI gate needs none of them); the release build runs them itself with `just natives`. ## Critical Constraints - **Electron 43 + etcher-sdk 10.** The old Electron-19 pin (etcher-sdk broke on Electron 20+, balena-io/etcher#4087) is lifted: etcher-sdk 10 + Electron 37+ is what balena Etcher itself ships, and etcher-sdk runs only in the spawned Node subprocess, never the renderer. When bumping Electron, change **both** `package.json` `electron` and `electron-builder.yml` `electronVersion`, then rebuild natives. Note Electron removed `File.path` — the renderer resolves dropped-file paths via `webUtils.getPathForFile` exposed through the preload (`window.api.getPathForFile`). - Flashing requires root/admin. On macOS/Linux the app spawns `sudo` subprocesses; on Windows the whole app runs elevated (`requestedExecutionLevel: requireAdministrator`). -- `~/.Reflasher` is the app's config/cache directory (downloaded OS images, agent binary, `flockos-manifest.json`: the last verified IronFlockOS catalog). -- Boards come from the signed IronFlockOS catalog `https://instance-registry.ironflock.com/dl/flockos/manifest.json` only (README "Board catalog"). Images and binaries are fetched from `https://instance-registry.ironflock.com`. +- `~/.Reflasher` is the app's config/cache directory (downloaded OS images, agent binary, `ironflockos-manifest.json`: the last verified IronFlockOS catalog). +- Boards come from the signed IronFlockOS catalog `https://instance-registry.ironflock.com/dl/ironflockos/manifest.json` only (README "Board catalog"). Images and binaries are fetched from `https://instance-registry.ironflock.com`. ## Architecture @@ -43,7 +45,7 @@ The `RPC` enum in `src/types/index.ts` is the single registry of invoke channel The main process runs as **root**, and `.flock` files plus board metadata are **untrusted input**. Two rules hold the line: - **Never interpolate untrusted data into a shell string or into elevated-script source.** All privileged commands go through argv: `elevatedSpawn(cmd, argsArray)` / `spawnAsync` (no shell, no `command.split(' ')`) in `permissions.ts`. The two elevated Node scripts are FIXED constants in `security/elevated-scripts.ts` that read their inputs from `process.argv`; `elevatedNodeChildProcess(code, scriptArgs)` passes data as argv. There is a test (`test/elevated-scripts.test.ts`) asserting these scripts contain no `${…}`. - **Validate at the boundary.** `security/validation.ts` (`assertValidDevicePath`, `assertValidFlockConfig`, `isSafePathSegment`) is enforced in every privileged `ipcHandlers.ts` handler and again at config ingestion in `flash.ts`. `ipcHandlers` also cross-checks the flash target against `listDrives()` so the renderer can't aim a write at a system disk. `RPC.ReadFile` is scoped to `.flock` reads only. -- The IronFlockOS catalog is verified before anything in it is used: `security/catalog.ts` opens the device-agent's envelope (at most 64 KiB, Ed25519 over `flockos-manifest:v1`, `flockos/manifest.json`, the payload's SHA-256) against the compiled-in `FLOCKOS_CATALOG_PUBLIC_KEYS`, validates the payload (schema 1, https downloads, single-segment `.img.gz` files, boards matching their release) and refuses a catalog older than the one accepted last. Images of an unknown `variant`/`kernel`/`architecture` are skipped (logged) and boards left without images hidden, for forward compatibility. A refused catalog means an error in the UI and no boards (or, after a failed refresh, the boards verified before), never unverified data; only an unreachable catalog falls back to the verified cache (`api/catalogs.ts`). `CatalogStore.refresh` reloads it when the board list is shown, at most every 5 minutes (`force` for Retry), single-flight. The image to flash is looked up by its `imageKey` (`@`) in the main process's verified catalog (`CatalogStore.resolve`), so its URL and digest never come from the renderer or the `.flock`. `security/validation.ts` `assertFlashRequest` (in the flash IPC handler and again in `flashDevice`) accepts only a device file plus such a key — no local image path or URL. +- The IronFlockOS catalog is verified before anything in it is used: `security/catalog.ts` opens the device-agent's envelope (at most 64 KiB, Ed25519 over `ironflockos-manifest:v1`, `ironflockos/manifest.json`, the payload's SHA-256) against the compiled-in `IRONFLOCKOS_CATALOG_PUBLIC_KEYS`, validates the payload (schema 1, https downloads, single-segment `.img.gz` files, boards matching their release) and refuses a catalog older than the one accepted last. Images of an unknown `variant`/`kernel`/`architecture` are skipped (logged) and boards left without images hidden, for forward compatibility. A refused catalog means an error in the UI and no boards (or, after a failed refresh, the boards verified before), never unverified data; only an unreachable catalog falls back to the verified cache (`api/catalogs.ts`). `CatalogStore.refresh` reloads it when the board list is shown, at most every 5 minutes (`force` for Retry), single-flight. The image to flash is looked up by its `imageKey` (`@`) in the main process's verified catalog (`CatalogStore.resolve`), so its URL and digest never come from the renderer or the `.flock`. `security/validation.ts` `assertFlashRequest` (in the flash IPC handler and again in `flashDevice`) accepts only a device file plus such a key — no local image path or URL. - Downloaded artifacts are verified: `security/integrity.ts` (`verifyFileSha256`) is wired into the image download — `flash.ts` checks `ImageInfo.sha256` against the **compressed `.gz` download** (the registry publishes the digest of the compressed artifact, matching `ImageInfo.size` = the `.gz` content-length) before decompressing; `downloadFile` (`utils/index.ts`) checks HTTP status, verifies byte count, and writes to a `.part` temp then atomically renames. - Renderer runs with `nodeIntegration:false` + `contextIsolation:true`; navigation is confined to the app origin (`will-navigate`/`will-redirect` in `index.ts`). `sandbox:true` is still pending (needs a self-contained preload) — see the Electron upgrade note below. @@ -58,7 +60,10 @@ The main process runs as **root**, and `.flock` files plus board metadata are ** ### Flash pipeline for `.flock` items (`flashDevice` in `flash.ts`) 1. The config file is JSON; the renderer matches a board (`matchBoard`: the file's board model, or the one board of its `architecture`; else the user chooses) and its default variant (`defaultImage`: `base` with the `std` kernel); the user may pick another hardware, variant (`variantImages`: `base`, `base` rt, `nvidia`; never the installer) and, when the board's installer stick carries the variant (`installerFor`, its `payloads`), how to install (`installerKey`). The main process resolves the keys against its verified catalog (`CatalogStore.plan`, which refuses a payload the stick does not carry). 2. The `.img.gz` is downloaded to `~/.Reflasher`, its size and SHA-256 are checked against the catalog, and it is gunzipped there (`boards.ts` / `ImageManager`); skipped if cached. -3. After the write, the config file goes onto the FAT partition labelled `FLOCKOS`, else the first FAT partition (`utils/config-partition.ts`: `lsblk`/`udisksctl` on Linux, `diskutil` on macOS, PowerShell Storage cmdlets and `diskpart` on Windows; mounted if needed, synced, unmounted again). The device gets `.flock` only; IronFlockOS enroll removes it after use. An installer stick also gets `installer.conf` (`payload=`). +3. After the write, the config file goes onto the FAT partition labelled `IRONFLOCKOS`, else the first FAT partition (`utils/config-partition.ts`: `lsblk`/`udisksctl` on Linux, `diskutil` on macOS, PowerShell Storage cmdlets and `diskpart` on Windows; mounted if needed, synced, unmounted again). The device gets `.flock` only; IronFlockOS enroll removes it after use. An installer stick also gets `installer.conf` (`payload=`). The writing of these files is `utils/device-files.ts`, shared with the command-line tool. + +### Command-line tool (`src/cli/`, README "Command line") +`flockflasher images|drives|flash`, built by `vite.cli.config.ts` into one CommonJS file for Node 18+ that requires Node's own modules only, so `src/cli/` and what it imports must stay free of Electron, `@electron-toolkit/*` and npm dependencies (`src/main/utils/index.ts` and `permissions.ts` import Electron: never import them from the CLI's modules). It shares the signed catalog (`security/catalog.ts`, `api/catalogs.ts`), the download (`utils/download.ts`), the image checks, the image choice (`shared/images.ts`) and the IRONFLOCKOS files (`utils/device-files.ts`, `config-partition.ts`) with the app, and writes without etcher-sdk (`cli/write.ts`: gunzip into 4 MiB blocks, `/dev/rdiskN` on macOS, `O_EXCL` on Linux, read back and compared). `cli/disks.ts` decides which disks it may write (lsblk on Linux, `diskutil -plist` on macOS); Linux and macOS only. ### Device test mode (`agent.ts`) `AgentManager` downloads the `device-agent` binary from the instance registry (verified against its published SHA-256 checksum) into `~/.Reflasher/agent` and can run a "virtual device" locally against a `.flock` config. Requires a running Docker daemon (`hasDocker()`); streams agent logs/state to the renderer. diff --git a/Justfile b/Justfile index 931b378..6b73a73 100644 --- a/Justfile +++ b/Justfile @@ -37,6 +37,12 @@ build: preview: build npm run start +# The command-line tool into out/cli/flockflasher.cjs, then run it with ARGS +# (README, "Command line"); writing a disk needs sudo: sudo node out/cli/flockflasher.cjs flash ... +cli *ARGS: + npm run build:cli --silent + node out/cli/flockflasher.cjs {{ARGS}} + # ----------------------------------------------------------------------------- # Package: the installer of the CURRENT OS in dist/, never published. The # release workflow runs the same recipes on one runner per OS (see diff --git a/README.md b/README.md index d11c11c..1fcc4be 100644 --- a/README.md +++ b/README.md @@ -60,19 +60,19 @@ drop, file association) are device files only. ### The signed IronFlockOS catalog -`https://instance-registry.ironflock.com/dl/flockos/manifest.json`, published by every IronFlockOS -release ([IronFlockOS ADR-0009](https://github.com/IronFlock/ironflockos/blob/main/docs/adr/0009-phase-2-decisions-hostname-channels-firmware.md), +`https://instance-registry.ironflock.com/dl/ironflockos/manifest.json`, published by every +IronFlockOS release ([IronFlockOS ADR-0009](https://github.com/IronFlock/ironflockos/blob/main/docs/adr/0009-phase-2-decisions-hostname-channels-firmware.md), [schema](https://github.com/IronFlock/ironflockos/blob/main/docs/manifest.schema.json)). It is the device-agent's envelope, `{"payload": "", "signature": ""}`, at most 64 KiB, signed over the lines `flockos-manifest:v1`, -`flockos/manifest.json` and the payload's SHA-256 (lowercase hex), joined by `\n` without a +64-byte Ed25519 signature>"}`, at most 64 KiB, signed over the lines `ironflockos-manifest:v1`, +`ironflockos/manifest.json` and the payload's SHA-256 (lowercase hex), joined by `\n` without a trailing newline. `src/main/security/catalog.ts` verifies it with Node's `crypto`: -- The trusted keys are compiled in as `FLOCKOS_CATALOG_PUBLIC_KEYS` (the Cloud KMS key - `ironflock-release/flockos-catalog`, version 1, key id `f5e1308e`; - [PEM form](https://github.com/IronFlock/ironflockos/blob/main/pki/flockos-catalog.pub)). To rotate, - release a FlockFlasher that lists both keys before IronFlockOS signs with the new one, and drop the - old line in a later release. +- The trusted keys are compiled in as `IRONFLOCKOS_CATALOG_PUBLIC_KEYS` (the Cloud KMS key + `ironflock-release/ironflockos-catalog`, version 1, key id `036ef3bd`; + [PEM form](https://github.com/IronFlock/ironflockos/blob/main/pki/ironflockos-catalog.pub)). + To rotate, release a FlockFlasher that lists both keys before IronFlockOS signs with the new + one, and drop the old line in a later release. - A catalog that is unsigned, tampered with, signed by another key, larger than 64 KiB, not JSON, of another `schema`, malformed, internally inconsistent (a board's image differs from its release) or issued before the one accepted last is refused: the app shows the error and offers @@ -85,9 +85,9 @@ trailing newline. `src/main/security/catalog.ts` verifies it with Node's `crypto opening the board list), at most every 5 minutes, and at once with Retry after an error, so a release published while the app is open appears without a restart. Idle devices keep their board and variant on the new release. -- The last verified catalog is kept in `~/.Reflasher/flockos-manifest.json`. It is used only when - the catalog cannot be reached (network or HTTP error), with a notice. The rollback check is - against the newer of it and the catalog in use. +- The last verified catalog is kept in `~/.Reflasher/ironflockos-manifest.json`. It is used only + when the catalog cannot be reached (network or HTTP error), with a notice. The rollback check + is against the newer of it and the catalog in use. The `boards` of the catalog show the production release. The menus of a device: @@ -109,14 +109,14 @@ stick's payloads in the verified catalog (`CatalogStore.plan`) before it writes ### The device file on the flashed drive After writing a `.flock` item, FlockFlasher puts the device file onto the FAT partition labelled -`FLOCKOS` (every IronFlockOS image has one, the installer stick included), or, as a fallback, onto the +`IRONFLOCKOS` (every IronFlockOS image has one, the installer stick included), or, as a fallback, onto the first FAT partition. It finds the partition by label and file system, not by order (`src/main/utils/config-partition.ts`), and mounts it if the OS did not: - Linux: `lsblk` (through sudo when the udev database has no file systems yet), `udisksctl mount`, else `mount -t vfat` through sudo into a temporary directory. - macOS: `diskutil list` and `diskutil info`, `diskutil mount` (through sudo if needed). macOS does - not mount an EFI system partition by itself, and `FLOCKOS` is the EFI system partition on + not mount an EFI system partition by itself, and `IRONFLOCKOS` is the EFI system partition on `amd64-efi` and `arm64-efi`. - Windows: PowerShell's Storage cmdlets list the partitions; a partition without a drive letter gets one from `Add-PartitionAccessPath`, or from `diskpart` for an EFI system partition. @@ -128,6 +128,39 @@ An installer stick also gets `installer.conf` with the one line `payload= or by-id: + --installer-confirm yes|no ask on the PC's console before writing + --installer-after poweroff|reboot + --installer-allow-usb yes|no also install to USB disks + --wifi-ssid SSID the WiFi the device connects to (else the .flock's) + --wifi-password PW + --image-file FILE a downloaded .img.gz to write instead of downloading + it; it must be the catalog's (same size and SHA-256) + --cache-dir DIR where downloads are kept (default ~/.Reflasher) + --no-verify do not read the disk back after writing + -y, --yes do not ask before erasing the disk + +Every image comes from the signed catalog at +https://instance-registry.ironflock.com/dl/ironflockos/manifest.json and is checked +against its size and SHA-256 before it is written. Writing a disk needs root +(sudo) on Linux and macOS.` + +export class UsageError extends Error { + constructor(message: string) { + super(message) + this.name = 'UsageError' + } +} + +export type FlashOptions = { + flock: string + device: string + image?: string + installer?: InstallerOptions + wifiSsid?: string + wifiPassword?: string + imageFile?: string + cacheDir?: string + verify: boolean + yes: boolean +} + +export type Command = + | { command: 'help' } + | { command: 'version' } + | { command: 'images'; json: boolean } + | { command: 'drives'; all: boolean; json: boolean } + | ({ command: 'flash' } & FlashOptions) + +const yesNo = (value: string | undefined, option: string): boolean | undefined => { + if (value === undefined) return undefined + if (value === 'yes') return true + if (value === 'no') return false + throw new UsageError(`--${option} must be yes or no`) +} + +const OPTIONS = { + json: { type: 'boolean' }, + all: { type: 'boolean' }, + flock: { type: 'string', short: 'c' }, + device: { type: 'string', short: 'd' }, + image: { type: 'string', short: 'i' }, + installer: { type: 'boolean' }, + 'installer-disk': { type: 'string' }, + 'installer-confirm': { type: 'string' }, + 'installer-after': { type: 'string' }, + 'installer-allow-usb': { type: 'string' }, + 'wifi-ssid': { type: 'string' }, + 'wifi-password': { type: 'string' }, + 'image-file': { type: 'string' }, + 'cache-dir': { type: 'string' }, + 'no-verify': { type: 'boolean' }, + yes: { type: 'boolean', short: 'y' }, + help: { type: 'boolean', short: 'h' }, + version: { type: 'boolean' } +} as const + +// The options each command takes, besides --help. +const ACCEPTS: Record = { + images: ['json'], + drives: ['all', 'json'], + flash: [ + 'flock', + 'device', + 'image', + 'installer', + 'installer-disk', + 'installer-confirm', + 'installer-after', + 'installer-allow-usb', + 'wifi-ssid', + 'wifi-password', + 'image-file', + 'cache-dir', + 'no-verify', + 'yes' + ] +} + +const parse = (argv: string[]) => { + try { + return parseArgs({ args: argv, options: OPTIONS, allowPositionals: true, strict: true }) + } catch (error) { + throw new UsageError((error as Error).message) + } +} + +export const parseCommandLine = (argv: string[]): Command => { + const { values, positionals } = parse(argv) + if (values.version) return { command: 'version' } + const [command, ...rest] = positionals + if (values.help || command === undefined || command === 'help') return { command: 'help' } + if (command === 'version') return { command: 'version' } + if (!(command in ACCEPTS)) throw new UsageError(`Unknown command ${command}`) + if (rest.length > 0) throw new UsageError(`Unexpected argument ${rest[0]}`) + for (const name of Object.keys(values)) { + if (name !== 'help' && !ACCEPTS[command].includes(name)) { + throw new UsageError(`${command} takes no --${name}`) + } + } + + if (command === 'images') return { command, json: values.json === true } + if (command === 'drives') return { command, all: values.all === true, json: values.json === true } + + if (!values.flock) throw new UsageError('flash needs --flock FILE, the device file') + if (!values.device) throw new UsageError('flash needs --device DISK, the disk to write') + + const installerValues = [ + values['installer-disk'], + values['installer-confirm'], + values['installer-after'], + values['installer-allow-usb'] + ] + if (!values.installer && installerValues.some((v) => v !== undefined)) { + throw new UsageError('The --installer-* options need --installer') + } + let installer: InstallerOptions | undefined + if (values.installer) { + const after = values['installer-after'] + if (after !== undefined && after !== 'poweroff' && after !== 'reboot') { + throw new UsageError('--installer-after must be poweroff or reboot') + } + installer = { + disk: values['installer-disk'], + confirm: yesNo(values['installer-confirm'], 'installer-confirm'), + after, + allowUsb: yesNo(values['installer-allow-usb'], 'installer-allow-usb') + } + } + if (values['wifi-password'] !== undefined && values['wifi-ssid'] === undefined) { + throw new UsageError('--wifi-password needs --wifi-ssid') + } + + return { + command: 'flash', + flock: values.flock, + device: values.device, + image: values.image, + installer, + wifiSsid: values['wifi-ssid'], + wifiPassword: values['wifi-password'], + imageFile: values['image-file'], + cacheDir: values['cache-dir'], + verify: values['no-verify'] !== true, + yes: values.yes === true + } +} diff --git a/src/cli/disks.ts b/src/cli/disks.ts new file mode 100644 index 0000000..98f9198 --- /dev/null +++ b/src/cli/disks.ts @@ -0,0 +1,278 @@ +import type { CommandRunner } from '../main/utils/config-partition' +import { parsePlist, PlistValue } from './plist' + +// The disks `flockflasher` may write, and the checks before it writes one: +// a whole disk, writable, not the disk of the running system, not held by +// LVM, RAID or dm-crypt, and (macOS) not an internal disk of the Mac. Linux +// reads lsblk, macOS diskutil. The parsers are pure, so they are unit-tested. + +export type Disk = { + // /dev/sdb, /dev/disk4 + device: string + // what is written: /dev/sdb, /dev/rdisk4 (macOS's raw device, unbuffered) + rawDevice: string + size: number + model: string + transport: string + removable: boolean + // Linux: the mounted file systems of the disk, unmounted before writing + mounted: { device: string; mountpoint: string }[] + // why the disk is never written, if it is not + refusal?: string +} + +export type DiskDeps = { platform: NodeJS.Platform; run: CommandRunner } + +export const SUPPORTED_PLATFORMS: NodeJS.Platform[] = ['linux', 'darwin'] + +export const assertSupportedPlatform = (platform: NodeJS.Platform): void => { + if (!SUPPORTED_PLATFORMS.includes(platform)) { + throw new Error( + `flockflasher writes disks on Linux and macOS; on ${platform} use the FlockFlasher app` + ) + } +} + +// ------------------------------------------------------------------ linux -- + +// Mount points of the running system (installed or live): a disk with one of +// them is never written. +const SYSTEM_MOUNTS = new Set([ + '/', + '/boot', + '/usr', + '/var', + '/home', + '/etc', + '/opt', + '/srv', + '/data', + '[SWAP]', + '/cdrom', + '/run/live/medium', + '/run/initramfs/live', + '/lib/live/mount/medium' +]) +const isSystemMount = (mountpoint: string) => + SYSTEM_MOUNTS.has(mountpoint) || mountpoint.startsWith('/boot/') + +export const LSBLK_ARGS = [ + '--json', + '--bytes', + '--paths', + '--output', + 'NAME,PKNAME,TYPE,SIZE,RM,RO,TRAN,MODEL,MOUNTPOINT' +] + +// lsblk prints booleans as true/false or "1"/"0", sizes as numbers or strings, +// depending on its version. +const flag = (value: unknown) => value === true || value === 1 || value === '1' +const number = (value: unknown) => (typeof value === 'number' ? value : Number(value) || 0) +const text = (value: unknown) => (typeof value === 'string' ? value.trim() : '') + +type LsblkNode = { + name?: unknown + pkname?: unknown + type?: unknown + size?: unknown + rm?: unknown + ro?: unknown + tran?: unknown + model?: unknown + mountpoint?: unknown + children?: unknown +} + +const children = (node: LsblkNode): LsblkNode[] => + Array.isArray(node.children) ? (node.children as LsblkNode[]) : [] + +const linuxDisk = (node: LsblkNode): Disk => { + const device = text(node.name) + const mounted: Disk['mounted'] = [] + let system: string | undefined + let holder: string | undefined + const visit = (current: LsblkNode, depth: number) => { + const mountpoint = text(current.mountpoint) + if (mountpoint !== '') { + if (isSystemMount(mountpoint)) system ??= mountpoint + else mounted.push({ device: text(current.name), mountpoint }) + } + if (depth > 0 && text(current.type) !== 'part') { + holder ??= `${text(current.type)} ${text(current.name)}` + } + for (const child of children(current)) visit(child, depth + 1) + } + visit(node, 0) + + let refusal: string | undefined + if (system) refusal = `holds ${system} of the running system` + else if (holder) refusal = `is in use by ${holder}: release it first` + else if (flag(node.ro)) refusal = 'is read-only' + else if (number(node.size) === 0) refusal = 'has no medium' + + return { + device, + rawDevice: device, + size: number(node.size), + model: text(node.model), + transport: text(node.tran), + removable: flag(node.rm), + mounted, + refusal + } +} + +const lsblkNodes = (stdout: string): LsblkNode[] => { + const doc = JSON.parse(stdout) + return Array.isArray(doc?.blockdevices) ? doc.blockdevices : [] +} + +// The disks of `lsblk` without a device: physical disks only (no loop +// devices, no zram, no optical drives). +export const parseLinuxDisks = (stdout: string): Disk[] => + lsblkNodes(stdout) + .filter((node) => text(node.type) === 'disk' && !/^\/dev\/zram\d+$/.test(text(node.name))) + .map(linuxDisk) + +// The disk of `lsblk DEVICE`: a whole disk (or a loop device, named on purpose). +export const parseLinuxDisk = (stdout: string, device: string): Disk => { + const [node] = lsblkNodes(stdout) + if (!node) throw new Error(`${device} is not a block device`) + const type = text(node.type) + if (type === 'part') { + const parent = text(node.pkname) + throw new Error(`${device} is a partition: pass the whole disk${parent ? ` (${parent})` : ''}`) + } + if (type !== 'disk' && type !== 'loop') throw new Error(`${device} is a ${type}, not a disk`) + return linuxDisk(node) +} + +// ------------------------------------------------------------------ macOS -- + +type Dict = { [key: string]: PlistValue } +const asDict = (value: PlistValue): Dict => + value && typeof value === 'object' && !Array.isArray(value) ? value : {} + +// disk4, rdisk4, /dev/disk4 and /dev/rdisk4 all name disk4. +export const darwinDiskId = (device: string): string => { + const id = device.replace(/^(\/dev\/)?r?(?=disk\d)/, '') + if (!/^disk\d+(s\d+)*$/.test(id)) throw new Error(`${device} is not a macOS disk (/dev/diskN)`) + return id +} + +// A disk from its `diskutil info -plist`; systemDisks are the whole disks the +// running system lives on (the APFS container and its physical stores). +export const darwinDisk = (info: Dict, systemDisks: Set): Disk => { + const id = text(info.DeviceIdentifier) + const parent = text(info.ParentWholeDisk) + let refusal: string | undefined + if (info.WholeDisk !== true) refusal = `is a partition: pass the whole disk (/dev/${parent})` + else if (Array.isArray(info.APFSPhysicalStores)) refusal = 'is an APFS container, not a disk' + else if (systemDisks.has(id)) refusal = 'holds the running system' + // The built-in SD card reader is internal too, but its medium is removable + // (so is an attached disk image's). + else if (info.Internal === true && info.RemovableMedia !== true) + refusal = 'is an internal disk of this Mac' + else if (info.WritableMedia === false) refusal = 'is read-only' + return { + device: `/dev/${id}`, + rawDevice: `/dev/r${id}`, + size: number(info.Size ?? info.TotalSize), + model: text(info.MediaName) || text(info.IORegistryEntryName), + transport: text(info.BusProtocol), + removable: info.RemovableMedia === true || info.Ejectable === true, + mounted: [], + refusal + } +} + +const darwinInfo = async (run: CommandRunner, target: string): Promise => + asDict(parsePlist((await run('diskutil', ['info', '-plist', target])).stdout)) + +// The whole disks of the volume mounted at /: its APFS container and the +// container's physical stores. +const darwinSystemDisks = async (run: CommandRunner): Promise> => { + const disks = new Set() + const root = await darwinInfo(run, '/') + const container = text(root.ParentWholeDisk) + if (container) disks.add(container) + const stores = container ? (await darwinInfo(run, container)).APFSPhysicalStores : undefined + for (const store of Array.isArray(stores) ? stores : []) { + const id = text(asDict(store).APFSPhysicalStore) + if (!id) continue + const whole = text((await darwinInfo(run, id)).ParentWholeDisk) + if (whole) disks.add(whole) + } + return disks +} + +// ----------------------------------------------------------------- common -- + +export const inspectDisk = async (device: string, deps: DiskDeps): Promise => { + assertSupportedPlatform(deps.platform) + if (deps.platform === 'linux') { + if (!/^\/dev\/[A-Za-z0-9/._:-]+$/.test(device)) { + throw new Error(`${device} is not a disk (/dev/...)`) + } + return parseLinuxDisk((await deps.run('lsblk', [...LSBLK_ARGS, device])).stdout, device) + } + const id = darwinDiskId(device) + return darwinDisk(await darwinInfo(deps.run, id), await darwinSystemDisks(deps.run)) +} + +export const listDisks = async (deps: DiskDeps): Promise => { + assertSupportedPlatform(deps.platform) + if (deps.platform === 'linux') { + return parseLinuxDisks((await deps.run('lsblk', LSBLK_ARGS)).stdout) + } + const list = asDict(parsePlist((await deps.run('diskutil', ['list', '-plist'])).stdout)) + const ids = Array.isArray(list.WholeDisks) ? list.WholeDisks.map(text).filter(Boolean) : [] + const systemDisks = await darwinSystemDisks(deps.run) + const disks: Disk[] = [] + for (const id of ids) disks.push(darwinDisk(await darwinInfo(deps.run, id), systemDisks)) + return disks +} + +// Unmounts what the disk has mounted; a file system that will not unmount +// stops the flash before anything is written. +export const unmountDisk = async (disk: Disk, deps: DiskDeps): Promise => { + if (deps.platform === 'darwin') { + await deps.run('diskutil', ['unmountDisk', disk.device]) + return + } + for (const { device, mountpoint } of disk.mounted) { + try { + await deps.run('umount', [device]) + } catch (error) { + throw new Error(`Cannot unmount ${mountpoint} (${device}): ${(error as Error).message}`) + } + } +} + +// Drops the kernel's cached blocks of the disk (Linux), so that reading it +// back reads the disk. macOS reads the raw device, which has no cache. +export const flushDiskCache = async (disk: Disk, deps: DiskDeps): Promise => { + if (deps.platform !== 'linux') return true + try { + await deps.run('blockdev', ['--flushbufs', disk.device]) + return true + } catch { + return false + } +} + +const UNITS = ['B', 'KB', 'MB', 'GB', 'TB'] + +// Decimal units, as disks are sold. +export const humanSize = (bytes: number): string => { + let value = bytes + let unit = 0 + while (value >= 1000 && unit < UNITS.length - 1) { + value /= 1000 + unit++ + } + return `${unit === 0 ? value : value.toFixed(1)} ${UNITS[unit]}` +} + +export const describeDisk = (disk: Disk): string => + [disk.device, humanSize(disk.size), disk.transport, disk.model].filter(Boolean).join(' ') diff --git a/src/cli/image.ts b/src/cli/image.ts new file mode 100644 index 0000000..805a98f --- /dev/null +++ b/src/cli/image.ts @@ -0,0 +1,70 @@ +import { mkdir, stat, unlink } from 'node:fs/promises' +import path from 'node:path' +import type { ImageInfo } from '../types' +import { sha256File } from '../main/security/integrity' +import { downloadFile } from '../main/utils/download' + +// The .img.gz of a catalog image, checked against the catalog's size and +// SHA-256 every time it is used: a file the user names (--image-file), else +// the cached download, else a new download into the cache. + +export type ImageSource = { path: string; from: 'file' | 'cache' | 'download' } + +const matches = async (file: string, image: ImageInfo): Promise => { + const info = await stat(file) + if (!info.isFile()) return `${file} is not a file` + if (info.size !== image.size) { + return `${file} is ${info.size} bytes; the catalog's ${image.file} is ${image.size}` + } + const sha256 = await sha256File(file) + if (sha256 !== image.sha256) { + return `${file} has the SHA-256 ${sha256}; the catalog's ${image.file} has ${image.sha256}` + } + return undefined +} + +export const verifiedImage = async ( + image: ImageInfo, + opts: { + cacheDir: string + imageFile?: string + onChecking?: (file: string) => void + onDownload?: (done: number, total: number) => void + download?: typeof downloadFile + } +): Promise => { + if (opts.imageFile !== undefined) { + opts.onChecking?.(opts.imageFile) + const mismatch = await matches(opts.imageFile, image) + if (mismatch) throw new Error(`${mismatch}: it is not the image of the signed catalog`) + return { path: opts.imageFile, from: 'file' } + } + + // image.file comes from the verified catalog and is a single path segment + // (isSafePathSegment in security/catalog.ts). + // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal + const cached = path.join(opts.cacheDir, image.file) + const present = await stat(cached).then( + () => true, + () => false + ) + if (present) { + opts.onChecking?.(cached) + if ((await matches(cached, image)) === undefined) return { path: cached, from: 'cache' } + await unlink(cached) + } + + await mkdir(opts.cacheDir, { recursive: true }) + await (opts.download ?? downloadFile)( + image.download, + cached, + (progress) => opts.onDownload?.(progress.bytesWritten ?? 0, image.size), + { expectedSha256: image.sha256 } + ) + const mismatch = await matches(cached, image) + if (mismatch) { + await unlink(cached).catch(() => undefined) + throw new Error(mismatch) + } + return { path: cached, from: 'download' } +} diff --git a/src/cli/index.ts b/src/cli/index.ts new file mode 100644 index 0000000..2884c39 --- /dev/null +++ b/src/cli/index.ts @@ -0,0 +1,356 @@ +import { execFile } from 'node:child_process' +import { homedir } from 'node:os' +import path from 'node:path' +import { createInterface } from 'node:readline/promises' +import type { IronFlockOSCatalog } from '../main/security/catalog' +import { IRONFLOCKOS_CATALOG_PUBLIC_KEYS, parsePublicKeys } from '../main/security/catalog' +import { loadIronFlockOSCatalog } from '../main/api/catalogs' +import { CommandRunner, INSTALLER_CONF_FILE, installerConf } from '../main/utils/config-partition' +import { DeviceFile, writeDeviceFiles } from '../main/utils/device-files' +import { sortImages } from '../shared/images' +import type { ImageInfo } from '../types' +import { Command, FlashOptions, USAGE, UsageError, parseCommandLine } from './args' +import { + Disk, + DiskDeps, + assertSupportedPlatform, + describeDisk, + flushDiskCache, + humanSize, + inspectDisk, + listDisks, + unmountDisk +} from './disks' +import { verifiedImage } from './image' +import { choosePlan, readDeviceFile } from './plan' +import { writeImage } from './write' + +// flockflasher, the command-line tool: FlockFlasher's catalog, image checks +// and device-file handling without the app (README, "Command line"). Messages +// and progress go to stderr, tables and JSON to stdout. + +declare const __FLOCKFLASHER_VERSION__: string +export const VERSION = + typeof __FLOCKFLASHER_VERSION__ === 'string' ? __FLOCKFLASHER_VERSION__ : 'dev' + +// FlockFlasher's cache (REFLASHER_CONFIG_PATH in api/boards.ts): the verified +// catalog and the downloads. +const DEFAULT_CACHE_DIR = path.join(homedir(), '.Reflasher') + +const out = (line = '') => process.stdout.write(`${line}\n`) +const say = (line = '') => process.stderr.write(`${line}\n`) + +// Commands run without a shell, from an argv array. +export const run: CommandRunner = (command, args) => + new Promise((resolve, reject) => { + execFile( + command, + args, + { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 }, + (error, stdout, stderr) => { + if (error) { + const detail = (stderr || error.message).trim() + reject(new Error(`${command} ${args[0] ?? ''} failed: ${detail}`)) + } else { + resolve({ stdout }) + } + } + ) + }) + +// A progress line that rewrites itself on a terminal and prints every 10% +// otherwise (a log file, CI). +const progressLine = (label: string) => { + const tty = process.stderr.isTTY === true + let shown = -1 + return { + update(done: number, total: number) { + const percent = total > 0 ? Math.min(100, Math.floor((done * 100) / total)) : 0 + if (tty) { + if (percent !== shown) { + process.stderr.write( + `\r${label} ${percent}% (${humanSize(done)} of ${humanSize(total)}) ` + ) + shown = percent + } + } else { + const step = percent - (percent % 10) + if (step > shown) { + say(`${label} ${step}%`) + shown = step + } + } + }, + end() { + if (tty && shown >= 0) process.stderr.write('\n') + shown = -1 + } + } +} + +const loadCatalog = async (cacheDir: string): Promise => { + const { catalog, fromCache } = await loadIronFlockOSCatalog({ + cacheDir, + keys: parsePublicKeys(IRONFLOCKOS_CATALOG_PUBLIC_KEYS) + }) + say( + `IronFlockOS catalog of ${catalog.issuedAt}, signed with key ${catalog.keyId}` + + (fromCache ? ' (the copy verified before: the download server did not answer)' : '') + ) + return catalog +} + +// ----------------------------------------------------------------- images -- + +type ImageRow = ImageInfo & { hardware: string[] } + +const catalogImages = (catalog: IronFlockOSCatalog): ImageRow[] => { + const rows = new Map() + for (const board of catalog.boards) { + for (const image of sortImages(board.latestImages)) { + const row = rows.get(image.image_id) ?? { ...image, hardware: [] } + row.hardware.push(board.modelname) + rows.set(image.image_id, row) + } + } + return [...rows.values()] +} + +const table = (rows: string[][]) => { + const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length))) + for (const row of rows) + out( + row + .map((cell, i) => cell.padEnd(widths[i])) + .join(' ') + .trimEnd() + ) +} + +const images = async (json: boolean) => { + const catalog = await loadCatalog(DEFAULT_CACHE_DIR) + const rows = catalogImages(catalog) + if (json) { + out( + JSON.stringify( + { production: catalog.production, issued_at: catalog.issuedAt, images: rows }, + null, + 2 + ) + ) + return + } + table([ + ['IMAGE', 'VERSION', 'DOWNLOAD', 'HARDWARE'], + ...rows.map((image) => [ + image.image_id, + image.version, + humanSize(image.size), + image.hardware.join(', ') + + (image.variant === 'installer' + ? ` (installer stick for ${(image.payloads ?? []).join(', ')})` + : '') + ]) + ]) +} + +// ----------------------------------------------------------------- drives -- + +const drives = async (all: boolean, json: boolean, deps: DiskDeps) => { + const disks = (await listDisks(deps)).filter((disk) => all || !disk.refusal) + if (json) { + out(JSON.stringify(disks, null, 2)) + return + } + if (disks.length === 0) { + say('No disk to write: insert an SD card or a USB stick (--all lists every disk)') + return + } + table([ + ['DEVICE', 'SIZE', 'BUS', 'MODEL', ...(all ? ['WRITABLE'] : [])], + ...disks.map((disk) => [ + disk.device, + humanSize(disk.size), + disk.transport || '-', + disk.model || '-', + ...(all ? [disk.refusal ? `no: ${disk.refusal}` : 'yes'] : []) + ]) + ]) +} + +// ------------------------------------------------------------------ flash -- + +const confirmErase = async (disk: Disk) => { + if (!process.stdin.isTTY) { + throw new Error(`No terminal to ask on: pass --yes to erase ${disk.device}`) + } + const prompt = createInterface({ input: process.stdin, output: process.stderr }) + try { + const answer = await prompt.question( + `Everything on ${disk.device} is erased. Type yes to write it: ` + ) + if (answer.trim() !== 'yes') throw new Error('Stopped: nothing was written') + } finally { + prompt.close() + } +} + +const sameDisk = (a: Disk, b: Disk) => a.size === b.size && a.model === b.model + +export const flash = async (options: FlashOptions, deps: DiskDeps) => { + assertSupportedPlatform(deps.platform) + const cacheDir = options.cacheDir ?? DEFAULT_CACHE_DIR + + const flock = await readDeviceFile( + options.flock, + options.wifiSsid === undefined + ? undefined + : { ssid: options.wifiSsid, password: options.wifiPassword } + ) + const catalog = await loadCatalog(cacheDir) + const plan = choosePlan(catalog.boards, flock.config, { + image: options.image, + installer: options.installer !== undefined + }) + for (const warning of plan.warnings) say(`Warning: ${warning}`) + const files: DeviceFile[] = [{ name: flock.name, data: flock.data }] + if (plan.payload) { + files.push({ + name: INSTALLER_CONF_FILE, + data: Buffer.from(installerConf(plan.payload.image_id, options.installer)) + }) + } + + const disk = await inspectDisk(options.device, deps) + if (disk.refusal) throw new Error(`${disk.device} ${disk.refusal}: nothing was written`) + + say(`Device file: ${flock.name} (${String(flock.config.name)})`) + if (plan.payload) { + say(`Image: ${plan.write.image_id} ${plan.write.version}, the installer stick`) + say(`It installs: ${plan.payload.image_id} on ${plan.board.modelname}`) + } else { + say(`Image: ${plan.write.image_id} ${plan.write.version} (${plan.board.modelname})`) + } + if (options.wifiSsid !== undefined) say(`WiFi: ${options.wifiSsid}`) + say(`Disk: ${describeDisk(disk)}`) + if (!options.yes) await confirmErase(disk) + + const download = progressLine('Downloading') + const source = await verifiedImage(plan.write, { + cacheDir, + imageFile: options.imageFile, + onChecking: (file) => say(`Checking ${file} against the catalog`), + onDownload: (done, total) => download.update(done, total) + }) + download.end() + if (source.from === 'download') say(`Downloaded and checked ${plan.write.file}`) + + // The disk may have been swapped while the image was prepared. + const target = await inspectDisk(options.device, deps) + if (target.refusal || !sameDisk(disk, target)) { + throw new Error(`${disk.device} changed while the image was prepared: nothing was written`) + } + await unmountDisk(target, deps) + + const writing = progressLine('Writing') + const verifying = progressLine('Checking') + let phase: 'writing' | 'verifying' = 'writing' + let result + try { + result = await writeImage({ + source: source.path, + sourceBytes: plan.write.size, + target: target.rawDevice, + verify: options.verify, + onProgress: (progress) => { + if (progress.phase !== phase) { + writing.end() + phase = progress.phase + } + ;(progress.phase === 'writing' ? writing : verifying).update(progress.done, progress.total) + }, + beforeVerify: () => flushDiskCache(target, deps), + onWarning: (message) => say(`Warning: ${message}`) + }) + } catch (error: any) { + if (error?.code === 'EACCES' || error?.code === 'EPERM') { + throw new Error(`No permission to write ${target.rawDevice}: run flockflasher with sudo`) + } + if (error?.code === 'EBUSY') { + throw new Error(`${target.device} is in use (mounted or opened by another program)`) + } + throw error + } finally { + writing.end() + verifying.end() + } + say( + `Wrote ${humanSize(result.bytes)} to ${target.device}` + + (result.verified ? ' and read it back: it matches' : ' (not read back)') + ) + + await writeDeviceFiles(deps.platform, target.device, files, { + run: deps.run, + runElevated: deps.run, + uid: process.getuid?.(), + gid: process.getgid?.() + }) + say(`Wrote ${files.map((f) => f.name).join(' and ')} to its IRONFLOCKOS partition`) + + if (plan.payload) { + const installer = options.installer ?? {} + say( + `Done. Boot the PC from the stick: the installer writes ${plan.payload.image_id} to ` + + `${installer.disk && installer.disk !== 'largest' ? installer.disk : 'its largest internal disk'}` + + (installer.confirm === false ? ' without asking.' : ' once you confirm on its console.') + ) + } else { + say( + `Done. Start the device from ${target.device}: it enrolls with ${flock.name} on its first boot.` + ) + } +} + +// ------------------------------------------------------------------- main -- + +export const main = async (argv: string[], deps?: Partial): Promise => { + // Logs of the shared modules go to stderr with the messages. + console.log = console.error + console.info = console.error + + let command: Command + try { + command = parseCommandLine(argv) + } catch (error) { + if (!(error instanceof UsageError)) throw error + say(`flockflasher: ${error.message}`) + say('flockflasher help shows the usage.') + return 2 + } + + const diskDeps: DiskDeps = { platform: process.platform, run, ...deps } + try { + switch (command.command) { + case 'help': + out(USAGE) + break + case 'version': + out(`flockflasher ${VERSION}`) + break + case 'images': + await images(command.json) + break + case 'drives': + assertSupportedPlatform(diskDeps.platform) + await drives(command.all, command.json, diskDeps) + break + case 'flash': + await flash(command, diskDeps) + break + } + return 0 + } catch (error) { + say(`flockflasher: ${(error as Error)?.message ?? error}`) + return 1 + } +} diff --git a/src/cli/main.ts b/src/cli/main.ts new file mode 100644 index 0000000..3739879 --- /dev/null +++ b/src/cli/main.ts @@ -0,0 +1,12 @@ +import { main } from './index' + +// The entry of out/cli/flockflasher.cjs (vite.cli.config.ts). +main(process.argv.slice(2)).then( + (code) => { + process.exitCode = code + }, + (error) => { + process.stderr.write(`flockflasher: ${error?.stack ?? error}\n`) + process.exitCode = 1 + } +) diff --git a/src/cli/plan.ts b/src/cli/plan.ts new file mode 100644 index 0000000..b8fb8de --- /dev/null +++ b/src/cli/plan.ts @@ -0,0 +1,125 @@ +import { readFile, stat } from 'node:fs/promises' +import type { ImageInfo, SupportedBoard } from '../types' +import { assertValidFlockConfig } from '../main/security/validation' +import { assertInstallerCarries, FlashPlan } from '../main/api/catalogs' +import { configFileName } from '../main/utils/config-partition' +import { + defaultImage, + imageKey, + installerFor, + isConfigFileName, + matchBoard +} from '../shared/images' + +// What `flockflasher flash` writes: the device file and the catalog image, +// chosen the way FlockFlasher chooses them. Pure apart from reading the file. + +// FlockFlasher reads device files up to this size (ipcHandlers.ts). +const MAX_FLOCK_BYTES = 5 * 1024 * 1024 + +export type FlockFile = { + // the file's name on the IRONFLOCKOS partition + name: string + data: Buffer + config: Record +} + +// Reads and checks a device file. With a WiFi network, the copy for the +// device carries it (as FlockFlasher's WiFi fields do); the file itself is not +// changed. +export const readDeviceFile = async ( + file: string, + wifi?: { ssid?: string; password?: string } +): Promise => { + if (!isConfigFileName(file)) throw new Error(`${file} is not a device file (.flock)`) + const info = await stat(file) + if (!info.isFile()) throw new Error(`${file} is not a file`) + if (info.size > MAX_FLOCK_BYTES) throw new Error(`${file} is too large for a device file`) + const original = await readFile(file) + let config: unknown + try { + config = JSON.parse(original.toString('utf8')) + } catch { + throw new Error(`${file} is not a device file: it is not JSON`) + } + if (!config || typeof config !== 'object' || Array.isArray(config)) { + throw new Error(`${file} is not a device file`) + } + assertValidFlockConfig(config) + const record = config as Record + if (wifi?.ssid === undefined) + return { name: configFileName(file), data: original, config: record } + const changed = { ...record, wlanssid: wifi.ssid, password: wifi.password ?? '' } + return { name: configFileName(file), data: Buffer.from(JSON.stringify(changed)), config: changed } +} + +export type Choice = FlashPlan & { board: SupportedBoard; warnings: string[] } + +const allImages = (boards: SupportedBoard[]) => boards.flatMap((b) => b.latestImages) + +// --image takes an image id, with or without its ironflockos- prefix. +export const normalizeImageId = (id: string): string => + id.startsWith('ironflockos-') ? id : `ironflockos-${id}` + +// The image to write: --image, else the default variant of the board the +// device file asks for; with --installer, the board's installer stick that +// carries it. +export const choosePlan = ( + boards: SupportedBoard[], + config: Record, + options: { image?: string; installer: boolean } +): Choice => { + const warnings: string[] = [] + let board: SupportedBoard | undefined + let image: ImageInfo | undefined + + if (options.image !== undefined) { + const id = normalizeImageId(options.image) + board = boards.find((b) => b.latestImages.some((i) => i.image_id === id)) + image = board?.latestImages.find((i) => i.image_id === id) + if (!board || !image) { + const known = [...new Set(allImages(boards).map((i) => i.image_id))].join(', ') + throw new Error(`${id} is not an image of the catalog (it has ${known})`) + } + if (image.variant === 'installer') { + const carried = (image.payloads ?? []).join(', ') + throw new Error( + `${id} is the installer stick: choose the image it installs with --image and add --installer (it carries ${carried})` + ) + } + } else { + board = matchBoard(boards, config as Parameters[1]) + if (!board) { + const architecture = typeof config.architecture === 'string' ? config.architecture : 'none' + throw new Error( + `The device file does not tell which hardware it is for (architecture ${architecture}): choose the image with --image (flockflasher images lists them)` + ) + } + image = defaultImage(board.latestImages) + if (!image) throw new Error(`The catalog has no image for ${board.modelname}`) + } + + const architecture = config.architecture + if ( + typeof architecture === 'string' && + architecture !== '' && + architecture !== board.architecture + ) { + warnings.push( + `The device file is for ${architecture}, the image for ${board.architecture}: the device would not run its apps` + ) + } + + if (!options.installer) return { board, write: image, warnings } + const installer = installerFor(board, imageKey(image)) + if (!installer) { + const sticks = board.latestImages.filter((i) => i.variant === 'installer') + throw new Error( + sticks.length === 0 + ? `${board.modelname} has no installer stick: write the image to the device's disk instead` + : `The installer stick of ${board.modelname} does not carry ${image.image_id} (it carries ${(sticks[0].payloads ?? []).join(', ')})` + ) + } + assertInstallerCarries(installer, image) + return { board, write: installer, payload: image, warnings } +} diff --git a/src/cli/plist.ts b/src/cli/plist.ts new file mode 100644 index 0000000..966c918 --- /dev/null +++ b/src/cli/plist.ts @@ -0,0 +1,101 @@ +// A reader for the XML property lists `diskutil -plist` prints: dict, array, +// string, integer, real, true, false, date and data (as its base64 text). +// Pure, so it is unit-tested. + +export type PlistValue = string | number | boolean | PlistValue[] | { [key: string]: PlistValue } + +const ENTITIES: Record = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" } + +const unescape = (text: string): string => + text.replace(/&(amp|lt|gt|quot|apos|#\d+|#x[0-9a-fA-F]+);/g, (_, name: string) => { + if (name.startsWith('#x')) return String.fromCodePoint(parseInt(name.slice(2), 16)) + if (name.startsWith('#')) return String.fromCodePoint(parseInt(name.slice(1), 10)) + return ENTITIES[name] + }) + +type Token = { tag: string; kind: 'open' | 'close' | 'empty'; text?: string } + +const tokenize = (xml: string): Token[] => { + const tokens: Token[] = [] + // text pairs of scalars, and the open/close of containers. + const pattern = /<(\/?)([A-Za-z]+)(?:\s[^>]*?)?\s*(\/?)>|([^<]+)/g + let match: RegExpExecArray | null + while ((match = pattern.exec(xml)) !== null) { + if (match[4] !== undefined) { + const last = tokens[tokens.length - 1] + if (last && last.kind === 'open') last.text = (last.text ?? '') + match[4] + continue + } + const kind = match[1] ? 'close' : match[3] ? 'empty' : 'open' + tokens.push({ tag: match[2], kind }) + } + return tokens +} + +export const parsePlist = (xml: string): PlistValue => { + // Drop the prolog, the doctype and comments. + const body = xml + .replace(/<\?[^>]*\?>/g, '') + .replace(/]*>/gi, '') + .replace(//g, '') + const tokens = tokenize(body) + let at = 0 + + const fail = (message: string): never => { + throw new Error(`Not a property list: ${message}`) + } + + const value = (): PlistValue => { + const token = tokens[at++] ?? fail('it ends early') + if (token.kind === 'close') fail(`unexpected `) + const { tag } = token + if (token.kind === 'empty') { + if (tag === 'true') return true + if (tag === 'false') return false + if (tag === 'dict') return {} + if (tag === 'array') return [] + if (tag === 'string' || tag === 'data' || tag === 'date') return '' + return fail(`<${tag}/>`) + } + if (tag === 'dict') { + const dict: { [key: string]: PlistValue } = {} + while (tokens[at] && !(tokens[at].kind === 'close' && tokens[at].tag === 'dict')) { + const key = tokens[at++] + if (key.tag !== 'key') fail(`<${key.tag}> where a key belongs`) + if (key.kind === 'open') close('key') + dict[unescape((key.text ?? '').trim())] = value() + } + close('dict') + return dict + } + if (tag === 'array') { + const array: PlistValue[] = [] + while (tokens[at] && !(tokens[at].kind === 'close' && tokens[at].tag === 'array')) { + array.push(value()) + } + close('array') + return array + } + close(tag) + const text = token.text ?? '' + if (tag === 'string' || tag === 'date') return unescape(text) + if (tag === 'data') return text.replace(/\s+/g, '') + if (tag === 'integer' || tag === 'real') { + const number = Number(text.trim()) + return Number.isFinite(number) ? number : fail(`<${tag}>${text}`) + } + if (tag === 'plist') return fail('nested ') + return fail(`<${tag}>`) + } + + const close = (tag: string) => { + const token = tokens[at++] + if (!token || token.kind !== 'close' || token.tag !== tag) fail(` missing`) + } + + const root = tokens[at++] + if (!root || root.tag !== 'plist' || root.kind !== 'open') fail('no ') + const result = value() + close('plist') + return result +} diff --git a/src/cli/write.ts b/src/cli/write.ts new file mode 100644 index 0000000..1dc6165 --- /dev/null +++ b/src/cli/write.ts @@ -0,0 +1,156 @@ +import { createHash } from 'node:crypto' +import { constants, createReadStream } from 'node:fs' +import { open, stat } from 'node:fs/promises' +import { pipeline } from 'node:stream' +import { createGunzip } from 'node:zlib' + +// Writes a verified .img.gz to a disk without a temporary copy: decompressed +// as it is read, in whole blocks (macOS's raw devices take whole sectors +// only), synced to the disk as it goes, then read back and compared. Plain +// Node, no native modules: it writes any path (the tests write a file). + +export const BLOCK_BYTES = 4 * 1024 * 1024 +const SECTOR_BYTES = 512 +// Synced every this many bytes, so the progress is the disk's, not the cache's. +const SYNC_BYTES = 64 * 1024 * 1024 + +export type WriteProgress = { + phase: 'writing' | 'verifying' + // writing: compressed bytes read of `total` (the .img.gz); verifying: disk + // bytes read of `total` (the image) + done: number + total: number +} + +export type WriteResult = { bytes: number; sha256: string; verified: boolean } + +// The decompressed image in BLOCK_BYTES pieces; the last one is padded with +// zeros to a whole sector. +export async function* imageBlocks( + source: string, + onRead?: (compressedBytes: number) => void +): AsyncGenerator { + const input = createReadStream(source, { highWaterMark: 1024 * 1024 }) + let read = 0 + input.on('data', (chunk) => { + read += chunk.length + onRead?.(read) + }) + // pipeline destroys every stream on an error, so a broken file or a corrupt + // gzip ends the loop below with that error. + const output = pipeline(input, createGunzip(), () => undefined) + let block = Buffer.allocUnsafe(BLOCK_BYTES) + let filled = 0 + for await (const chunk of output as AsyncIterable) { + let offset = 0 + while (offset < chunk.length) { + const take = Math.min(chunk.length - offset, BLOCK_BYTES - filled) + chunk.copy(block, filled, offset, offset + take) + filled += take + offset += take + if (filled === BLOCK_BYTES) { + yield block + block = Buffer.allocUnsafe(BLOCK_BYTES) + filled = 0 + } + } + } + if (filled > 0) { + const padded = Math.ceil(filled / SECTOR_BYTES) * SECTOR_BYTES + block.fill(0, filled, padded) + yield block.subarray(0, padded) + } +} + +// Linux: O_EXCL on a block device fails (EBUSY) while it, or a partition of +// it, is mounted or otherwise in use, and keeps it so while it is open. +const openFlags = async (target: string): Promise => { + const info = await stat(target) + const exclusive = process.platform === 'linux' && info.isBlockDevice() ? constants.O_EXCL : 0 + return constants.O_WRONLY | exclusive +} + +export const writeImage = async (opts: { + // the .img.gz, already checked against the catalog + source: string + sourceBytes: number + // the raw device (or a file) + target: string + verify: boolean + onProgress?: (progress: WriteProgress) => void + // drops cached blocks before the read-back; false when it could not + beforeVerify?: () => Promise + onWarning?: (message: string) => void +}): Promise => { + const hash = createHash('sha256') + let bytes = 0 + const handle = await open(opts.target, await openFlags(opts.target)) + try { + let sinceSync = 0 + for await (const block of imageBlocks(opts.source, (done) => + opts.onProgress?.({ phase: 'writing', done, total: opts.sourceBytes }) + )) { + let offset = 0 + while (offset < block.length) { + const { bytesWritten } = await handle.write(block, offset, block.length - offset, bytes) + if (bytesWritten === 0) throw new Error(`${opts.target} took no more bytes at ${bytes}`) + offset += bytesWritten + bytes += bytesWritten + } + hash.update(block) + sinceSync += block.length + if (sinceSync >= SYNC_BYTES) { + await handle.datasync() + sinceSync = 0 + } + } + await handle.sync() + } catch (error: any) { + if (error?.code === 'ENOSPC' || error?.code === 'EIO') { + throw new Error( + `${opts.target} is too small for the image or failed (${error.code} after ${bytes} bytes)` + ) + } + throw error + } finally { + await handle.close() + } + const sha256 = hash.digest('hex') + + if (!opts.verify) return { bytes, sha256, verified: false } + if (opts.beforeVerify && !(await opts.beforeVerify())) { + opts.onWarning?.('Could not drop the disk cache: the check may read the cache, not the disk') + } + const actual = await readBack(opts.target, bytes, (done) => + opts.onProgress?.({ phase: 'verifying', done, total: bytes }) + ) + if (actual !== sha256) { + throw new Error(`${opts.target} does not read back what was written: the disk may be faulty`) + } + return { bytes, sha256, verified: true } +} + +// The SHA-256 of the first `length` bytes of a disk (or file). +export const readBack = async ( + target: string, + length: number, + onProgress?: (done: number) => void +): Promise => { + const hash = createHash('sha256') + const handle = await open(target, constants.O_RDONLY) + try { + const buffer = Buffer.allocUnsafe(BLOCK_BYTES) + let position = 0 + while (position < length) { + const want = Math.min(BLOCK_BYTES, length - position) + const { bytesRead } = await handle.read(buffer, 0, want, position) + if (bytesRead === 0) throw new Error(`${target} ended at ${position} of ${length} bytes`) + hash.update(buffer.subarray(0, bytesRead)) + position += bytesRead + onProgress?.(position) + } + } finally { + await handle.close() + } + return hash.digest('hex') +} diff --git a/src/main/api/catalogs.ts b/src/main/api/catalogs.ts index 535b7dd..5d31983 100644 --- a/src/main/api/catalogs.ts +++ b/src/main/api/catalogs.ts @@ -3,9 +3,9 @@ import path from 'node:path' import type { BoardCatalogs, ImageInfo } from '../../types' import { CatalogError, - FLOCKOS_CATALOG_PUBLIC_KEYS, - FLOCKOS_MANIFEST_URL, - FlockOSCatalog, + IRONFLOCKOS_CATALOG_PUBLIC_KEYS, + IRONFLOCKOS_MANIFEST_URL, + IronFlockOSCatalog, MAX_ENVELOPE_BYTES, TrustedKey, assertNotOlder, @@ -22,7 +22,7 @@ import { imageKey } from '../../shared/images' // The verified envelope of the catalog last accepted: used when the network is // unreachable, and the reference for the rollback check. -export const FLOCKOS_CATALOG_CACHE_FILE = 'flockos-manifest.json' +export const IRONFLOCKOS_CATALOG_CACHE_FILE = 'ironflockos-manifest.json' // A failure to reach the catalog, as opposed to a catalog that was reached and // refused. Only the former falls back to the verified cache. @@ -79,23 +79,23 @@ export const fetchCapped = async ( return Buffer.concat(chunks) } -export type FlockOSCatalogResult = { catalog: FlockOSCatalog; fromCache: boolean } +export type IronFlockOSCatalogResult = { catalog: IronFlockOSCatalog; fromCache: boolean } // Fetches, verifies and caches the IronFlockOS catalog. A document that is reached // but does not verify (unsigned, tampered, wrong key, oversize, not JSON, an // invalid payload, older than the one accepted last) is refused with a // CatalogError and never replaced by the cache; only an unreachable catalog // falls back to the verified cache. `accepted` is the catalog in use, if any. -export const loadFlockOSCatalog = async (opts: { +export const loadIronFlockOSCatalog = async (opts: { cacheDir: string keys: TrustedKey[] url?: string fetchFn?: typeof fetch - accepted?: FlockOSCatalog -}): Promise => { - const cachePath = path.join(opts.cacheDir, FLOCKOS_CATALOG_CACHE_FILE) + accepted?: IronFlockOSCatalog +}): Promise => { + const cachePath = path.join(opts.cacheDir, IRONFLOCKOS_CATALOG_CACHE_FILE) - let cached: FlockOSCatalog | undefined + let cached: IronFlockOSCatalog | undefined try { cached = openCatalog(await readFile(cachePath), opts.keys) } catch { @@ -109,7 +109,7 @@ export const loadFlockOSCatalog = async (opts: { let data: Buffer try { - data = await fetchCapped(opts.url ?? FLOCKOS_MANIFEST_URL, MAX_ENVELOPE_BYTES, opts.fetchFn) + data = await fetchCapped(opts.url ?? IRONFLOCKOS_MANIFEST_URL, MAX_ENVELOPE_BYTES, opts.fetchFn) } catch (error) { if (error instanceof CatalogUnreachableError && accepted) { console.warn(`${error.message}; using the catalog issued at ${accepted.issuedAt}`) @@ -162,7 +162,7 @@ export class CatalogStore { private keys: TrustedKey[] | undefined private keysError: CatalogError | undefined // the last verified catalog, kept when a later refresh fails - private flockos: FlockOSCatalog | undefined + private ironflockos: IronFlockOSCatalog | undefined private inFlight: Promise | undefined private lastAttemptAt: number | undefined private lastResult: BoardCatalogs | undefined @@ -179,7 +179,7 @@ export class CatalogStore { ) { this.now = opts.now ?? Date.now try { - this.keys = parsePublicKeys(opts.keyList ?? FLOCKOS_CATALOG_PUBLIC_KEYS) + this.keys = parsePublicKeys(opts.keyList ?? IRONFLOCKOS_CATALOG_PUBLIC_KEYS) } catch (error) { this.keysError = error as CatalogError } @@ -213,21 +213,21 @@ export class CatalogStore { private async doLoad(): Promise { try { if (!this.keys) throw this.keysError - const { catalog, fromCache } = await loadFlockOSCatalog({ + const { catalog, fromCache } = await loadIronFlockOSCatalog({ cacheDir: this.opts.cacheDir, keys: this.keys, url: this.opts.url, fetchFn: this.opts.fetchFn, - accepted: this.flockos + accepted: this.ironflockos }) - this.flockos = catalog + this.ironflockos = catalog console.log( `IronFlockOS catalog issued at ${catalog.issuedAt}, production ${catalog.production}, key ${catalog.keyId}` ) return { // in the catalog's order (amd64-efi first) boards: catalog.boards, - flockos: { + ironflockos: { ok: true, production: catalog.production, issuedAt: catalog.issuedAt, @@ -239,10 +239,10 @@ export class CatalogStore { const message = (error as Error)?.message ?? String(error) console.error(`IronFlockOS catalog refused (${code}): ${message}`) // A failed refresh keeps the boards verified before, with the error. - const kept = this.flockos + const kept = this.ironflockos return { boards: kept?.boards ?? [], - flockos: { + ironflockos: { ok: false, code, error: message, @@ -259,13 +259,13 @@ export class CatalogStore { throw new Error('No image chosen: choose a board and an OS image') } // Not loaded yet, or never verified: try once more. - if (!this.flockos) await this.load() - if (!this.flockos) { + if (!this.ironflockos) await this.load() + if (!this.ironflockos) { throw new Error( 'The IronFlockOS catalog is not available (it did not verify or could not be fetched)' ) } - const image = this.flockos.boards + const image = this.ironflockos.boards .flatMap((b) => b.latestImages) .find((i) => imageKey(i) === key) if (!image) throw new Error(`${key} is not in the signed IronFlockOS catalog`) diff --git a/src/main/api/flash.ts b/src/main/api/flash.ts index 2198f32..143fed1 100644 --- a/src/main/api/flash.ts +++ b/src/main/api/flash.ts @@ -5,18 +5,17 @@ import { elevatedNodeChildProcess, elevatedSpawn, spawnAsync } from './permissio import { FLASH_SCRIPT } from '../security/elevated-scripts' import { assertFlashRequest } from '../security/validation' import { verifyFileSha256 } from '../security/integrity' -import { mkdtemp, open, readFile, rename, rm, stat, unlink, writeFile } from 'fs/promises' +import { readFile, rename, stat, unlink, writeFile } from 'fs/promises' import ImageManager, { REFLASHER_CONFIG_PATH } from './boards' import { CatalogStore } from './catalogs' import { CommandRunner, INSTALLER_CONF_FILE, configFileName, - installerConf, - mountConfigPartition + installerConf } from '../utils/config-partition' +import { DeviceFile, writeDeviceFiles } from '../utils/device-files' import { cachedImageName } from '../../shared/images' -import os from 'os' import path from 'path' import { Drive } from 'drivelist' @@ -39,68 +38,19 @@ const asRunner = const run = asRunner(spawnAsync) const runElevated = asRunner(elevatedSpawn) -const writeFileDurably = async (target: string, data: Buffer) => { - const handle = await open(target, 'w') - try { - await handle.writeFile(data) - await handle.sync() - } finally { - await handle.close() - } -} - -// Writes the device file onto the flashed drive: the FAT partition labelled -// FLOCKOS, else the first FAT partition, found by label and file system rather -// than by order, and mounted for the purpose if the OS did not mount it (macOS -// and Windows mount no EFI system partition by themselves). On an installer -// stick, installer.conf names the image it installs (`payload`). +// Writes the device file onto the flashed drive (utils/device-files.ts). On an +// installer stick, installer.conf names the image it installs (`payload`). const writeDeviceConfig = async (drive: Drive, configPath: string, payload?: string) => { - const files: [string, Buffer][] = [[configFileName(configPath), await readFile(configPath)]] - if (payload) files.push([INSTALLER_CONF_FILE, Buffer.from(installerConf(payload))]) - const mounted = await mountConfigPartition(process.platform, drive.device, { + const files: DeviceFile[] = [ + { name: configFileName(configPath), data: await readFile(configPath) } + ] + if (payload) files.push({ name: INSTALLER_CONF_FILE, data: Buffer.from(installerConf(payload)) }) + await writeDeviceFiles(process.platform, drive.device, files, { run, runElevated, - makeTempDir: () => mkdtemp(path.join(os.tmpdir(), 'flockflasher-')), - removeDir: (dir) => rm(dir, { recursive: true, force: true }), - writeTempFile: async (content) => { - const file = path.join(await mkdtemp(path.join(os.tmpdir(), 'flockflasher-')), 'assign.txt') - await writeFile(file, content) - return file - }, - // the temp file sits in a directory of its own - removeFile: (file) => rm(path.dirname(file), { recursive: true, force: true }), uid: process.getuid?.(), gid: process.getgid?.() }) - console.log( - `Writing the device file to ${mounted.partition.id} (${mounted.reason}) at ${mounted.mountpoint}` - ) - try { - for (const [name, data] of files) { - // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- name is installer.conf or configFileName(), which has no separators and no leading/trailing dots - const target = path.join(mounted.mountpoint, name) - try { - await writeFileDurably(target, data) - } catch (error: any) { - // A volume that only mounted through sudo (macOS) belongs to root. - if (process.platform === 'win32' || (error?.code !== 'EACCES' && error?.code !== 'EPERM')) { - throw error - } - // A temp copy, so that cp copies only data FlockFlasher made. - const dir = await mkdtemp(path.join(os.tmpdir(), 'flockflasher-')) - try { - await writeFile(path.join(dir, name), data) - await runElevated('cp', [path.join(dir, name), target]) - } finally { - await rm(dir, { recursive: true, force: true }) - } - } - } - } finally { - await mounted - .release() - .catch((error) => console.warn('Could not release the partition:', error)) - } } // Downloads (or finds in the cache) a catalog image and returns the path of the @@ -189,7 +139,7 @@ export const flashDevice = async ( // Copy the file over when the flashing process has exited without an error code if (code === 0 && signal === null) { try { - // Every IronFlockOS image is a raw image with a FLOCKOS partition + // Every IronFlockOS image is a raw image with an IRONFLOCKOS partition // (the catalog accepts osvariant "image" only). await writeDeviceConfig(flashItem.drive!, configPath, payload) diff --git a/src/main/security/catalog.ts b/src/main/security/catalog.ts index 69c340d..a0a77e7 100644 --- a/src/main/security/catalog.ts +++ b/src/main/security/catalog.ts @@ -2,7 +2,7 @@ import { KeyObject, createHash, createPublicKey, verify } from 'node:crypto' import type { ImageInfo, ImageKernel, ImageVariant, SupportedBoard } from '../../types' import { isHttpsUrl, isSafePathSegment } from './validation' -// The signed IronFlockOS catalog, dl/flockos/manifest.json (IronFlockOS ADR-0009, +// The signed IronFlockOS catalog, dl/ironflockos/manifest.json (IronFlockOS ADR-0009, // docs/manifest.schema.json in IronFlock/ironflockos). It is published as the // device-agent's envelope (device-agent src/updatesig): // @@ -11,30 +11,30 @@ import { isHttpsUrl, isSafePathSegment } from './validation' // // at most 64 KiB, the signature over the ASCII lines // -// flockos-manifest:v1 -// flockos/manifest.json +// ironflockos-manifest:v1 +// ironflockos/manifest.json // // // joined by "\n", no trailing newline. Nothing in an envelope that does not // verify is ever used. Electron-free, so it is unit-tested. -export const FLOCKOS_MANIFEST_URL = - 'https://instance-registry.ironflock.com/dl/flockos/manifest.json' -export const CATALOG_CONTEXT = 'flockos-manifest:v1' -export const CATALOG_SUBJECT = 'flockos/manifest.json' +export const IRONFLOCKOS_MANIFEST_URL = + 'https://instance-registry.ironflock.com/dl/ironflockos/manifest.json' +export const CATALOG_CONTEXT = 'ironflockos-manifest:v1' +export const CATALOG_SUBJECT = 'ironflockos/manifest.json' export const MAX_ENVELOPE_BYTES = 64 * 1024 // The keys the catalog may be signed with, in the device-agent's format -// (FLOCKOS_CATALOG_PUBLIC_KEYS in device-agent src/osupdate/catalog.go): one +// (IRONFLOCKOS_CATALOG_PUBLIC_KEYS in device-agent src/osupdate/catalog.go): one // standard base64 raw 32-byte Ed25519 key per line, "#" starts a comment. // -// The line below is the Cloud KMS key ironflock-release/flockos-catalog, -// version 1 (IronFlockOS WP-2.6; pki/flockos-catalog.pub in IronFlock/ironflockos is -// its PEM form). Rotation: a FlockFlasher release that lists both the old and -// the new key ships before IronFlockOS signs with the new one; the old line goes -// in a later release. -export const FLOCKOS_CATALOG_PUBLIC_KEYS = ` -wFLa1T7iHYi20X8JVu/O6JUzBGmW2+tjo7QVMuxsmQg= # key f5e1308e, Cloud KMS ironflock-release/flockos-catalog v1 +// The line below is the Cloud KMS key ironflock-release/ironflockos-catalog, +// version 1 (pki/ironflockos-catalog.pub in IronFlock/ironflockos is its PEM +// form). Rotation: a FlockFlasher release that lists both the old and the new +// key ships before IronFlockOS signs with the new one; the old line goes in a +// later release. +export const IRONFLOCKOS_CATALOG_PUBLIC_KEYS = ` ++OG0Ylau0tkCKEDT+WGc9RYHOa9VCSxiOGBBTp7IEQc= # key 036ef3bd, Cloud KMS ironflock-release/ironflockos-catalog v1 ` export type CatalogErrorCode = @@ -156,7 +156,7 @@ export const openEnvelope = ( // ---------------------------------------------------------------- payload -- -export type FlockOSCatalog = { +export type IronFlockOSCatalog = { keyId: string issuedAt: string issuedAtMs: number @@ -168,7 +168,7 @@ export type FlockOSCatalog = { const VERSION = /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z.-]+)?$/ const TIME = /^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$/ const SHA256_HEX = /^[0-9a-f]{64}$/ -const IMAGE_ID = /^flockos-[a-z0-9]+(-[a-z0-9]+)*$/ +const IMAGE_ID = /^ironflockos-[a-z0-9]+(-[a-z0-9]+)*$/ // schema 1: -.img.gz const IMAGE_FILE = /\.img\.gz$/ const VARIANTS: readonly string[] = ['base', 'nvidia', 'installer'] @@ -230,7 +230,7 @@ const parsePayloads = ( target: string, images: Map ): string[] => { - const list = raw === undefined ? [`flockos-${target}-base`] : raw + const list = raw === undefined ? [`ironflockos-${target}-base`] : raw if (!Array.isArray(list) || list.some((id) => typeof id !== 'string')) { throw invalid(`${label}.payloads is not a list of image ids`) } @@ -416,7 +416,7 @@ const parseBoard = ( // board left without images is hidden); fields it uses must be well-formed, // and a known board image must match its release, or the whole catalog is // refused. -export const parseCatalogPayload = (payload: Buffer): Omit => { +export const parseCatalogPayload = (payload: Buffer): Omit => { let doc: unknown try { doc = JSON.parse(payload.toString('utf8')) @@ -454,7 +454,7 @@ export const parseCatalogPayload = (payload: Buffer): Omit { +export const openCatalog = (data: Buffer, keys: TrustedKey[]): IronFlockOSCatalog => { const { payload, keyId } = openEnvelope(data, keys) return { keyId, ...parseCatalogPayload(payload) } } @@ -462,8 +462,8 @@ export const openCatalog = (data: Buffer, keys: TrustedKey[]): FlockOSCatalog => // A reader refuses a catalog older than the one it last accepted (ADR-0009), // so a mirror cannot roll the flasher back to an older signed release. export const assertNotOlder = ( - next: FlockOSCatalog, - accepted: FlockOSCatalog | undefined + next: IronFlockOSCatalog, + accepted: IronFlockOSCatalog | undefined ): void => { if (accepted && next.issuedAtMs < accepted.issuedAtMs) { throw new CatalogError( diff --git a/src/main/security/validation.ts b/src/main/security/validation.ts index 8f29c23..d032b1d 100644 --- a/src/main/security/validation.ts +++ b/src/main/security/validation.ts @@ -104,7 +104,7 @@ export const assertValidFlockConfig = (config: MinimalConfig): void => { // @ (imageKey in src/shared/images.ts): the only way a flash // request names its image. const IMAGE_KEY = - /^flockos-[a-z0-9]+(-[a-z0-9]+)*@(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z.-]+)?$/ + /^ironflockos-[a-z0-9]+(-[a-z0-9]+)*@(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z.-]+)?$/ export const isImageKey = (value: unknown): value is string => typeof value === 'string' && value.length <= 256 && IMAGE_KEY.test(value) diff --git a/src/main/utils/config-partition.ts b/src/main/utils/config-partition.ts index 0812a3d..ef4ad49 100644 --- a/src/main/utils/config-partition.ts +++ b/src/main/utils/config-partition.ts @@ -1,10 +1,10 @@ // Finds and mounts the partition a device file goes to after flashing: the FAT -// partition labelled FLOCKOS (every IronFlockOS image has one, the installer stick +// partition labelled IRONFLOCKOS (every IronFlockOS image has one, the installer stick // included), else, as a fallback, the first FAT partition. The partition order // is never relied on. Commands run through injected runners (argv, no shell), // so the logic is unit-tested without disks or Electron. -export const FLOCKOS_LABEL = 'FLOCKOS' +export const IRONFLOCKOS_LABEL = 'IRONFLOCKOS' export type PartitionInfo = { // linux: /dev/sdb1; darwin: disk4s1; win32: the partition number @@ -58,13 +58,13 @@ export const isFatPartitionType = (partType: string | undefined): boolean => { const hasFat = (p: PartitionInfo) => isFatFilesystem(p.fsType) || (!p.fsType && isFatPartitionType(p.partType)) -// FLOCKOS by FAT label first, then the first FAT file system, then (when the +// IRONFLOCKOS by FAT label first, then the first FAT file system, then (when the // OS could not tell the file system, as Windows for an EFI system partition // without a drive letter) the first partition of a FAT partition type. export const chooseConfigPartition = (partitions: PartitionInfo[]): PartitionChoice | undefined => { const ordered = partitions.slice().sort((a, b) => a.index - b.index) const labelled = ordered.find( - (p) => (p.label ?? '').trim().toUpperCase() === FLOCKOS_LABEL && hasFat(p) + (p) => (p.label ?? '').trim().toUpperCase() === IRONFLOCKOS_LABEL && hasFat(p) ) if (labelled) return { partition: labelled, reason: 'label' } const fat = ordered.find((p) => isFatFilesystem(p.fsType)) @@ -88,17 +88,50 @@ export const configFileName = (sourcePath: string): string => { return `${stem}.flock` } -// installer.conf on an installer stick's FLOCKOS partition (KEY=value, read by -// the IronFlockOS installer): only `payload`, the id of the image to install; every -// other key keeps its default (confirm=yes: the installer asks on the console -// before it writes). +// installer.conf on an installer stick's IRONFLOCKOS partition (KEY=value, read by +// the IronFlockOS installer, profiles/installer/overlay/usr/lib/ironflockos/ +// installer-lib.sh in IronFlock/ironflockos): `payload`, the id of the image to +// install, and the keys set in `options`; every other key keeps the installer's +// default (confirm=yes: the installer asks on the console before it writes). +// FlockFlasher writes `payload` only; the command-line tool may set the others. export const INSTALLER_CONF_FILE = 'installer.conf' -export const installerConf = (payload: string): string => { - if (!/^flockos-[a-z0-9]+(-[a-z0-9]+)*$/.test(payload)) { +export type InstallerOptions = { + // largest | /dev/ | by-id: (default largest) + disk?: string + // ask on the console before writing (default true) + confirm?: boolean + // default poweroff + after?: 'poweroff' | 'reboot' + // also offer USB disks as targets (default false) + allowUsb?: boolean +} + +// The values the installer accepts (installer_conf in installer-lib.sh). +const INSTALLER_DISK = /^(largest|\/dev\/[a-zA-Z0-9]+|by-id:[A-Za-z0-9_.:-]+)$/ + +export const installerConf = (payload: string, options: InstallerOptions = {}): string => { + if (!/^ironflockos-[a-z0-9]+(-[a-z0-9]+)*$/.test(payload)) { throw new Error(`Not an IronFlockOS image id: ${payload}`) } - return `payload=${payload}\n` + const lines = [`payload=${payload}`] + if (options.disk !== undefined) { + if (!INSTALLER_DISK.test(options.disk)) { + throw new Error( + `The installer's disk must be largest, /dev/ or by-id:, not ${options.disk}` + ) + } + lines.push(`disk=${options.disk}`) + } + if (options.confirm !== undefined) lines.push(`confirm=${options.confirm ? 'yes' : 'no'}`) + if (options.after !== undefined) { + if (options.after !== 'poweroff' && options.after !== 'reboot') { + throw new Error(`The installer's after must be poweroff or reboot, not ${options.after}`) + } + lines.push(`after=${options.after}`) + } + if (options.allowUsb !== undefined) lines.push(`allow-usb=${options.allowUsb ? 'yes' : 'no'}`) + return lines.join('\n') + '\n' } // ----------------------------------------------------------------- parsers -- @@ -268,7 +301,7 @@ const waitForChoice = async ( } const found = seen.map((p) => `${p.id} ${p.fsType ?? '?'} ${p.label ?? ''}`.trim()).join(', ') throw new Error( - `No ${FLOCKOS_LABEL} or FAT partition found on ${device}` + + `No ${IRONFLOCKOS_LABEL} or FAT partition found on ${device}` + (found ? ` (partitions: ${found})` : '') + (lastError ? `: ${(lastError as Error)?.message ?? lastError}` : '') ) @@ -350,7 +383,7 @@ const mountDarwin = async (device: string, deps: MountDeps): Promise mkdtemp(path.join(os.tmpdir(), 'flockflasher-')) + +const writeFileDurably = async (target: string, data: Buffer) => { + const handle = await open(target, 'w') + try { + await handle.writeFile(data) + await handle.sync() + } finally { + await handle.close() + } +} + +export const writeDeviceFiles = async ( + platform: NodeJS.Platform, + device: string, + files: DeviceFile[], + deps: DeviceFileDeps +): Promise => { + for (const { name } of files) { + if (!isSafePathSegment(name)) { + throw new Error(`Not a file name for the IRONFLOCKOS partition: ${name}`) + } + } + const mounted = await mountConfigPartition(platform, device, { + run: deps.run, + runElevated: deps.runElevated, + makeTempDir: tempDir, + removeDir: (dir) => rm(dir, { recursive: true, force: true }), + writeTempFile: async (content) => { + const file = path.join(await tempDir(), 'assign.txt') + await writeFile(file, content) + return file + }, + // the temp file sits in a directory of its own + removeFile: (file) => rm(path.dirname(file), { recursive: true, force: true }), + uid: deps.uid, + gid: deps.gid + }) + console.log( + `Writing the device file to ${mounted.partition.id} (${mounted.reason}) at ${mounted.mountpoint}` + ) + try { + for (const { name, data } of files) { + // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- name is a single safe path segment (checked above) + const target = path.join(mounted.mountpoint, name) + try { + await writeFileDurably(target, data) + } catch (error: any) { + // A volume that only mounted through sudo (macOS) belongs to root. + if (platform === 'win32' || (error?.code !== 'EACCES' && error?.code !== 'EPERM')) { + throw error + } + // A temp copy, so that cp copies only data FlockFlasher made. + const dir = await tempDir() + try { + await writeFile(path.join(dir, name), data) + await deps.runElevated('cp', [path.join(dir, name), target]) + } finally { + await rm(dir, { recursive: true, force: true }) + } + } + } + } finally { + await mounted + .release() + .catch((error) => console.warn('Could not release the partition:', error)) + } +} diff --git a/src/main/utils/download.ts b/src/main/utils/download.ts new file mode 100644 index 0000000..c4d1d09 --- /dev/null +++ b/src/main/utils/download.ts @@ -0,0 +1,134 @@ +import { createWriteStream } from 'fs' +import fs from 'fs/promises' +import https from 'https' +import { Progress } from '../../types' +import { calculateSpeed, calculateETA } from './progress' +import { verifyFileSha256 } from '../security/integrity' + +// HTTPS downloads. Electron-free, so the command-line tool (src/cli) shares it. + +export const getRemoteFileSize = (url: string): Promise => { + return new Promise((res, rej) => { + const request = https.request(url, { method: 'HEAD' }, (result) => { + result.on('error', rej) + result.resume() // drain any body so the socket can close + result.on('end', () => { + const status = result.statusCode ?? 0 + // Follow one redirect for the HEAD probe (the GET follows them too). + if (status >= 300 && status < 400 && result.headers.location) { + const next = new URL(result.headers.location, url).toString() + return getRemoteFileSize(next).then(res, rej) + } + if (status < 200 || status >= 300) return rej(new Error(`HEAD failed: HTTP ${status}`)) + res(parseInt(result.headers['content-length'] ?? '0', 10) || 0) + }) + }) + + request.on('error', rej) // the request itself had no error handler before + request.end() + }) +} + +type DownloadOptions = { + mode?: number | undefined + // Verify the downloaded bytes against this SHA-256 hex digest before committing. + expectedSha256?: string +} + +// Download over HTTPS to a temporary `.part` file, then atomically rename into +// place. Rejects on non-2xx status, on network/stream errors, on a truncated +// transfer (bytes != content-length), and on a SHA-256 mismatch — and never leaves +// a partial file at the final path. Redirects are followed (bounded). +export const downloadFile = async ( + url: string, + destPath: string, + progress?: (progress: Partial) => void, + options?: DownloadOptions +): Promise => { + const tempPath = `${destPath}.part` + const writeStream = createWriteStream(tempPath, { mode: options?.mode }) + + let written = 0 + const startTime = Date.now() + + if (progress) { + progress({ averageSpeed: 0, eta: 0, percentage: 0, speed: 0, bytesWritten: 0 }) + } + + const size = await getRemoteFileSize(url).catch(() => 0) + + const cleanupPartial = async () => { + writeStream.destroy() + await fs.unlink(tempPath).catch(() => undefined) + } + + await new Promise((resolve, reject) => { + const fail = (err: unknown) => { + cleanupPartial().finally(() => reject(err)) + } + + const request = (currentUrl: string, redirectsLeft: number) => { + https + .get(currentUrl, (res) => { + const status = res.statusCode ?? 0 + + // Follow redirects to a bounded depth. + if (status >= 300 && status < 400 && res.headers.location) { + res.resume() // drain + if (redirectsLeft <= 0) return fail(new Error('Too many redirects')) + const next = new URL(res.headers.location, currentUrl).toString() + return request(next, redirectsLeft - 1) + } + + if (status < 200 || status >= 300) { + res.resume() + return fail(new Error(`Download failed: HTTP ${status} for ${currentUrl}`)) + } + + res.on('error', fail) + + res.on('data', (buf) => { + const ok = writeStream.write(buf, (err) => { + if (err) fail(err) + }) + written += buf.length + if (progress) { + const elapsedTime = (Date.now() - startTime) / 1000 + const { speed, averageSpeed } = calculateSpeed(written, elapsedTime) + const eta = calculateETA(written, speed, size) + const percentage = size > 0 ? (written / size) * 100 : 0 + progress({ percentage, averageSpeed, eta, speed, bytesWritten: written }) + } + if (!ok) res.pause() + }) + + writeStream.on('drain', () => res.resume()) + + res.on('end', () => { + writeStream.end(() => resolve()) + }) + }) + .on('error', fail) + } + + writeStream.on('error', fail) + request(url, 5) + }) + + // Detect truncated downloads when the server told us the size. + if (size > 0 && written !== size) { + await cleanupPartial() + throw new Error(`Incomplete download: expected ${size} bytes, got ${written}`) + } + + if (options?.expectedSha256) { + try { + await verifyFileSha256(tempPath, options.expectedSha256) + } catch (err) { + await cleanupPartial() + throw err + } + } + + await fs.rename(tempPath, destPath) +} diff --git a/src/main/utils/index.ts b/src/main/utils/index.ts index fbb9a63..9c525db 100644 --- a/src/main/utils/index.ts +++ b/src/main/utils/index.ts @@ -1,38 +1,13 @@ -import { createWriteStream } from 'fs' import fs from 'fs/promises' -import https from 'https' -import { Progress } from '../../types' import { is } from '@electron-toolkit/utils' import { app } from 'electron' import path from 'path' import { APPIMAGE_MOUNT_POINT, elevatedSpawn } from '../api/permissions' -import { calculateSpeed, calculateETA } from './progress' -import { verifyFileSha256 } from '../security/integrity' // Pure progress math lives in ./progress so it can be unit-tested without Electron. export { calculateSpeed, calculateETA } from './progress' - -export const getRemoteFileSize = (url: string): Promise => { - return new Promise((res, rej) => { - const request = https.request(url, { method: 'HEAD' }, (result) => { - result.on('error', rej) - result.resume() // drain any body so the socket can close - result.on('end', () => { - const status = result.statusCode ?? 0 - // Follow one redirect for the HEAD probe (the GET follows them too). - if (status >= 300 && status < 400 && result.headers.location) { - const next = new URL(result.headers.location, url).toString() - return getRemoteFileSize(next).then(res, rej) - } - if (status < 200 || status >= 300) return rej(new Error(`HEAD failed: HTTP ${status}`)) - res(parseInt(result.headers['content-length'] ?? '0', 10) || 0) - }) - }) - - request.on('error', rej) // the request itself had no error handler before - request.end() - }) -} +// The downloads live in ./download, which the command-line tool shares. +export { downloadFile, getRemoteFileSize } from './download' export const getNodeModulesResourcePath = (moduleName: string, opts?: { unpacked?: boolean }) => { // The elevated subprocess runs a temp script whose module loader does NOT walk up @@ -96,107 +71,3 @@ export const fileExists = async (filePath: string) => { export const killProcessDarwin = (signal: number, pid: number) => { return elevatedSpawn('kill', [`-${signal}`, String(pid)]) } - -type DownloadOptions = { - mode?: number | undefined - // Verify the downloaded bytes against this SHA-256 hex digest before committing. - expectedSha256?: string -} - -// Download over HTTPS to a temporary `.part` file, then atomically rename into -// place. Rejects on non-2xx status, on network/stream errors, on a truncated -// transfer (bytes != content-length), and on a SHA-256 mismatch — and never leaves -// a partial file at the final path. Redirects are followed (bounded). -export const downloadFile = async ( - url: string, - destPath: string, - progress?: (progress: Partial) => void, - options?: DownloadOptions -): Promise => { - const tempPath = `${destPath}.part` - const writeStream = createWriteStream(tempPath, { mode: options?.mode }) - - let written = 0 - const startTime = Date.now() - - if (progress) { - progress({ averageSpeed: 0, eta: 0, percentage: 0, speed: 0, bytesWritten: 0 }) - } - - const size = await getRemoteFileSize(url).catch(() => 0) - - const cleanupPartial = async () => { - writeStream.destroy() - await fs.unlink(tempPath).catch(() => undefined) - } - - await new Promise((resolve, reject) => { - const fail = (err: unknown) => { - cleanupPartial().finally(() => reject(err)) - } - - const request = (currentUrl: string, redirectsLeft: number) => { - https - .get(currentUrl, (res) => { - const status = res.statusCode ?? 0 - - // Follow redirects to a bounded depth. - if (status >= 300 && status < 400 && res.headers.location) { - res.resume() // drain - if (redirectsLeft <= 0) return fail(new Error('Too many redirects')) - const next = new URL(res.headers.location, currentUrl).toString() - return request(next, redirectsLeft - 1) - } - - if (status < 200 || status >= 300) { - res.resume() - return fail(new Error(`Download failed: HTTP ${status} for ${currentUrl}`)) - } - - res.on('error', fail) - - res.on('data', (buf) => { - const ok = writeStream.write(buf, (err) => { - if (err) fail(err) - }) - written += buf.length - if (progress) { - const elapsedTime = (Date.now() - startTime) / 1000 - const { speed, averageSpeed } = calculateSpeed(written, elapsedTime) - const eta = calculateETA(written, speed, size) - const percentage = size > 0 ? (written / size) * 100 : 0 - progress({ percentage, averageSpeed, eta, speed, bytesWritten: written }) - } - if (!ok) res.pause() - }) - - writeStream.on('drain', () => res.resume()) - - res.on('end', () => { - writeStream.end(() => resolve()) - }) - }) - .on('error', fail) - } - - writeStream.on('error', fail) - request(url, 5) - }) - - // Detect truncated downloads when the server told us the size. - if (size > 0 && written !== size) { - await cleanupPartial() - throw new Error(`Incomplete download: expected ${size} bytes, got ${written}`) - } - - if (options?.expectedSha256) { - try { - await verifyFileSha256(tempPath, options.expectedSha256) - } catch (err) { - await cleanupPartial() - throw err - } - } - - await fs.rename(tempPath, destPath) -} diff --git a/src/renderer/src/components/Devices.vue b/src/renderer/src/components/Devices.vue index d015916..1f872f0 100644 --- a/src/renderer/src/components/Devices.vue +++ b/src/renderer/src/components/Devices.vue @@ -30,7 +30,7 @@ const agentStore = useAgentStore() const { downloadState } = storeToRefs(agentStore) const { drives } = storeToRefs(drivesStore) -const { boards, flockos } = storeToRefs(boardStore) +const { boards, ironflockos } = storeToRefs(boardStore) const { t } = useI18n() // Menu 1: the hardware only. @@ -119,17 +119,17 @@ watch(drives, (updatedDl) => {