Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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` (`<image_id>@<version>`) 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` (`<image_id>@<version>`) 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.

Expand All @@ -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 `<name>.flock` only; IronFlockOS enroll removes it after use. An installer stick also gets `installer.conf` (`payload=<image id>`).
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 `<name>.flock` only; IronFlockOS enroll removes it after use. An installer stick also gets `installer.conf` (`payload=<image id>`). 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.
Expand Down
6 changes: 6 additions & 0 deletions Justfile
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
61 changes: 47 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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": "<base64 of the payload JSON>", "signature": "<base64 of a
64-byte Ed25519 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
Expand All @@ -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:

Expand All @@ -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.
Expand All @@ -128,6 +128,39 @@ An installer stick also gets `installer.conf` with the one line `payload=<image
variant); every other key keeps the installer's default (`confirm=yes`: it asks on the console
before it writes).

## Command line

`flockflasher` installs IronFlockOS without the app, for scripts, servers and machines without a
desktop. It is one JavaScript file for Node 18 or later (`out/cli/flockflasher.cjs`, built by
`npm run build:cli` or `just cli`) with nothing but Node's own modules, so it runs wherever it is
copied. It writes disks on Linux and macOS; on Windows only `images` works.

```sh
node flockflasher.cjs images # the images of the signed catalog
node flockflasher.cjs drives # the disks it can write (--all: every disk, and why not)
sudo node flockflasher.cjs flash --flock kitchen-pi.flock --device /dev/sdb --image rpi-arm64-base
```

`flash` takes the image of the `.flock`'s hardware when its architecture has only one (amd64:
the PC), else the one `--image` names. `--installer` writes the installer stick that installs
that image instead, and `--installer-disk`, `--installer-confirm`, `--installer-after` and
`--installer-allow-usb` set the other keys of `installer.conf` (an unattended install:
`--installer-confirm no`). `--wifi-ssid` and `--wifi-password` put a WiFi network into the copy of
the `.flock` on the disk, as the app's WiFi fields do. It asks before it erases the disk, unless
`--yes`. `flockflasher help` lists every option.

It shares the app's code for what must not differ: the signed catalog (`src/main/security/catalog.ts`,
`src/main/api/catalogs.ts`, the same cache in `~/.Reflasher`), the image's size and SHA-256, and
the device file on the `IRONFLOCKOS` partition (`src/main/utils/device-files.ts`). It writes without
etcher-sdk, so it needs no native modules (`src/cli/write.ts`): the `.img.gz` is decompressed as
it is read, written in 4 MiB blocks (to `/dev/rdiskN` on macOS) and synced, then read back and
compared (`--no-verify` skips that). Before it writes, it checks the disk (`src/cli/disks.ts`): a
whole disk, writable, not the disk of the running system (`/`, `/boot`, swap, a live system's
medium), not held by LVM, RAID or dm-crypt, and on macOS not an internal disk unless its medium is
removable (the built-in SD card reader). It unmounts what the disk has mounted; on Linux it opens
the disk with `O_EXCL`, which fails while anything still uses it. `--image-file` writes a
downloaded `.img.gz` instead of downloading it, if it is the catalog's (same size and SHA-256).

## EtcherSDK

FlockFlasher uses the etcher-sdk to flash and mount drives.
Expand Down
Loading
Loading