maos: add web installer factory-image prep (prepare-factory.sh, sparse_split.py, docs)
- Commit
fcc704a2e2424a5af52a232f36406ac7331d3a32- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-09 15:16 UTC (3 months ago)
- Parents
f87045e
Diff
README.md
diff --git a/README.md b/README.mdindex 259ff18..aa08f8d 100644--- a/README.md+++ b/README.md@@ -37,6 +37,7 @@ prebuilts/ # release APKs (git-ignored; populated by scripts/collect-apks.sh # copies Modern-Apps release APKs into prebuilts/ keys/generate-keys.sh # generates the OS key set (offline; never committed) ota/ # build-ota.sh + publish-ota.sh (+ README)+installer/ # prepare-factory.sh + sparse_split.py for the web installer updater/ # how to point the Updater at ota.ma.vayunmathur.com docs/BUILD_RUNBOOK.md # end-to-end Linux build/sign/OTA/publish local_manifest.xml # adds this repo to the GrapheneOS tree@@ -95,3 +96,12 @@ server proxy, since the payloads are multi-GB. Build/publish scripts are in [`ota/`](ota/README.md); pointing the Updater at the server is covered in [`updater/`](updater/README.md). Full design rationale is in `GRAPHENEOS_FORK_PLAN.md` (Modern-Apps repo).++## Web installer++`https://ma.vayunmathur.com/os/install` is a browser-based WebUSB flasher (like+GrapheneOS's `/install/web`) — flash MAOS to a Pixel with no command-line tools. The static+front-end lives in the `location_share_server` repo (`os_installer/`); the build-host side+(turning a factory image into the manifest + images it flashes, and uploading to R2) is in+[`installer/`](installer/README.md). Requires a Chromium desktop browser and an R2 CORS+policy allowing `https://ma.vayunmathur.com`.
installer/README.md
diff --git a/installer/README.md b/installer/README.mdnew file mode 100644index 0000000..be995bd--- /dev/null+++ b/installer/README.md@@ -0,0 +1,110 @@+# MAOS web installer++A browser-based flasher at **`https://ma.vayunmathur.com/os/install`**, in the style of+GrapheneOS's `/install/web`. It talks fastboot to a connected Pixel over **WebUSB** and+flashes the MAOS factory image — no `adb`/`fastboot` tools or command line needed.++## Pieces++| Where | What |+| --- | --- |+| `location_share_server/os_installer/` | The static front-end: `install.html`, `install.css`, `installer.js` (wizard), `fastboot.js` (WebUSB fastboot client). Served at `/os/install` on `ma.vayunmathur.com`. |+| `MAOS/installer/prepare-factory.sh` | Build-host script: turns a factory image into a `manifest.json` + per-partition images (splitting oversized ones into sparse chunks) and uploads them to R2. |+| `MAOS/installer/sparse_split.py` | Splits a raw image into multiple Android sparse images, each under the device's max-download-size. |+| R2 (`ota.ma.vayunmathur.com/factory/<device>/…`) | Hosts the manifest + images; the browser streams them directly. |++## Flow++```+factory image ──prepare-factory.sh──▶ manifest.json + images ──▶ R2 (factory/<device>/latest/)+ │+ ma.vayunmathur.com/os/install ◀── static app served by server │+ │ (WebUSB fastboot) │+ ▼ ▼+ Pixel in bootloader mode ◀────────── streams images from R2 ──────+```++The installer reads `factory/<device>/latest/manifest.json`, then for each step does+`flash` / `erase` / `reboot-bootloader` / `reboot` over WebUSB, streaming each referenced+image straight from R2.++## Publishing a build for the installer++```bash+# On the Linux build host, after producing a factory image (runbook step 8):+export R2_ACCESS_KEY_ID=... R2_SECRET_ACCESS_KEY=... R2_ACCOUNT_ID=...+installer/prepare-factory.sh -d shusky -b "$BUILD" -f <device>-factory-*.zip+```++This uploads to both `factory/<device>/<build>/` and `factory/<device>/latest/` (the+installer defaults to `latest`).++### The flash plan (READ THIS)++The exact partitions/slots/order for a real install are defined by the factory image's own+`flash-all.sh` and are device/release specific. `prepare-factory.sh` without `-P` generates+a **best-effort** plan and prints a warning — treat it as a scaffold, not a guarantee. For a+real release, pass an explicit plan mirroring that device's `flash-all`:++```bash+installer/prepare-factory.sh -d shusky -b "$BUILD" -f factory.zip -P plan.json+```++`plan.json` is a JSON array of steps, e.g.:++```json+[+ {"action":"flash","partition":"bootloader","image":"bootloader-shusky-*.img"},+ {"action":"reboot-bootloader"},+ {"action":"flash","partition":"radio","image":"radio-shusky-*.img"},+ {"action":"reboot-bootloader"},+ {"action":"flash","partition":"boot","image":"boot.img"},+ {"action":"flash","partition":"init_boot","image":"init_boot.img"},+ {"action":"flash","partition":"dtbo","image":"dtbo.img"},+ {"action":"flash","partition":"vendor_boot","image":"vendor_boot.img"},+ {"action":"flash","partition":"vbmeta","image":"vbmeta.img"},+ {"action":"flash","partition":"super","image":"super.img"},+ {"action":"erase","partition":"userdata"},+ {"action":"reboot"}+]+```++`image` names an entry from the factory image (top-level or inside `image-*.zip`). Any image+over `-m` bytes (default 100 MiB, e.g. `super`) is auto-split into sparse chunks and expanded+into multiple flash steps to the same partition.++Supported step actions: `flash`, `erase`, `reboot-bootloader`, `reboot`, `set-active`.++## Required: R2 CORS++The installer page is served from `ma.vayunmathur.com` but fetches the manifest + images+from `ota.ma.vayunmathur.com` (R2) — a cross-origin request. **The R2 bucket must send CORS+headers allowing `https://ma.vayunmathur.com`**, or the browser blocks the downloads. In the+R2 bucket settings, add a CORS policy like:++```json+[+ {+ "AllowedOrigins": ["https://ma.vayunmathur.com"],+ "AllowedMethods": ["GET"],+ "AllowedHeaders": ["range"],+ "ExposeHeaders": ["content-length", "content-range", "accept-ranges"],+ "MaxAgeSeconds": 3600+ }+]+```++## Browser support & safety++- **Chromium desktop only** (Chrome/Edge). WebUSB isn't in Firefox/Safari.+- Everything runs locally: images download from R2 to the browser and go to the device over+ USB. Nothing is uploaded.+- Re-locking the bootloader is offered only after a successful flash — locking over a bad+ image can hard-brick the device.++## Status / caveats++The fastboot client and prep scripts are authored against the documented fastboot + sparse+formats but have **not been validated end-to-end on a device** (that needs real hardware and+a real MAOS factory image). Expect to iterate on the per-device flash plan and, if a device's+`super` handling differs, on the sparse splitting. See the inline "verify on device" notes.
installer/__pycache__/sparse_split.cpython-312.pyc
diff --git a/installer/__pycache__/sparse_split.cpython-312.pyc b/installer/__pycache__/sparse_split.cpython-312.pycnew file mode 100644index 0000000..8e06b44Binary files /dev/null and b/installer/__pycache__/sparse_split.cpython-312.pyc differ
installer/prepare-factory.sh
diff --git a/installer/prepare-factory.sh b/installer/prepare-factory.shnew file mode 100755index 0000000..2f53018--- /dev/null+++ b/installer/prepare-factory.sh@@ -0,0 +1,187 @@+#!/usr/bin/env bash+#+# prepare-factory.sh — turn a MAOS factory image into what the web installer consumes:+# a manifest.json flash plan plus per-partition images (splitting any image larger than+# the device's max-download-size into sparse chunks), uploaded to R2.+#+# The web installer (ma.vayunmathur.com/os/install) fetches+# https://ota.ma.vayunmathur.com/factory/<device>/latest/manifest.json+# and flashes each step, streaming the referenced images from the same directory.+#+# ── IMPORTANT ──────────────────────────────────────────────────────────────────────────+# The exact flash sequence (which partitions, slots, and order) is device/release specific+# and is authoritatively defined by the factory image's own flash-all.sh. The auto-generated+# plan here is a BEST-EFFORT scaffold. For a real release, pass an explicit plan with -P+# (a JSON array of steps) that mirrors that device's flash-all, and validate on a device+# before publishing. See installer/README.md.+# ─────────────────────────────────────────────────────────────────────────────────────────+#+# Usage:+# installer/prepare-factory.sh -d shusky -b 2026080900 -f <factory-image.zip> \+# [-P plan.json] [-m 104857600] [-O out/maos-factory] [-B maos-ota] [--no-upload]+#+# R2 upload reuses the same env as ota/publish-ota.sh:+# R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, and R2_ACCOUNT_ID (or R2_ENDPOINT).+#+set -euo pipefail++HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+DEVICE="" ; BUILD="" ; FACTORY="" ; PLAN="" ; MAXB=$((100 * 1024 * 1024))+OUTDIR="out/maos-factory" ; BUCKET="${R2_BUCKET:-maos-ota}" ; UPLOAD=1++usage() { sed -n '2,30p' "$0" >&2; exit 2; }++while [[ $# -gt 0 ]]; do+ case "$1" in+ -d) DEVICE="$2"; shift 2 ;;+ -b) BUILD="$2"; shift 2 ;;+ -f) FACTORY="$2"; shift 2 ;;+ -P) PLAN="$2"; shift 2 ;;+ -m) MAXB="$2"; shift 2 ;;+ -O) OUTDIR="$2"; shift 2 ;;+ -B) BUCKET="$2"; shift 2 ;;+ --no-upload) UPLOAD=0; shift ;;+ -h|--help) usage ;;+ *) echo "unknown arg: $1" >&2; usage ;;+ esac+done++[[ -n "$DEVICE" && -n "$BUILD" && -n "$FACTORY" ]] || usage+[[ -f "$FACTORY" ]] || { echo "factory image not found: $FACTORY" >&2; exit 1; }+command -v python3 >/dev/null || { echo "python3 required (for sparse_split.py)" >&2; exit 1; }++WORK="$(mktemp -d)"+trap 'rm -rf "$WORK"' EXIT+STAGE="$OUTDIR/$DEVICE/$BUILD"+mkdir -p "$STAGE"++echo ">> unpacking factory image"+unzip -q -o "$FACTORY" -d "$WORK"+# Pixel factory images nest the partition images inside image-<device>-<build>.zip.+INNER="$(find "$WORK" -name 'image-*.zip' | head -1 || true)"+if [[ -n "$INNER" ]]; then+ unzip -q -o "$INNER" -d "$WORK/inner"+fi++# Collect a partition -> image-file map. Each *.img's partition is its basename sans .img.+declare -A IMG+add_img() { # add_img <path>+ local p; p="$(basename "$1")"; p="${p%.img}"+ # Normalize bootloader-/radio-<...> to bare partition names.+ case "$p" in+ bootloader-*) p="bootloader" ;;+ radio-*) p="radio" ;;+ esac+ IMG["$p"]="$1"+}+for f in "$WORK"/*.img "$WORK"/inner/*.img; do [[ -e "$f" ]] && add_img "$f"; done++# Stage an image for a partition, splitting into sparse chunks if it exceeds MAXB.+# Emits one or more manifest flash-step JSON objects on stdout.+stage_flash() { # stage_flash <partition> <src-image>+ local part="$1" src="$2" sz base steps=""+ sz="$(stat -c '%s' "$src")"+ base="$(basename "$src")"+ if (( sz <= MAXB )); then+ cp "$src" "$STAGE/$base"+ printf '{"action":"flash","partition":"%s","image":"%s"}' "$part" "$base"+ else+ echo " splitting $base ($sz bytes) into sparse chunks <= $MAXB" >&2+ local prefix="$STAGE/${part}"+ # sparse_split prints each output path (one per line).+ local first=1+ while IFS= read -r chunk; do+ [[ $first -eq 1 ]] || steps+=","+ first=0+ steps+=$(printf '{"action":"flash","partition":"%s","image":"%s"}' \+ "$part" "$(basename "$chunk")")+ done < <(python3 "$HERE/sparse_split.py" "$src" "$prefix" --max-bytes "$MAXB")+ printf '%s' "$steps"+ fi+}++echo ">> building flash plan"+STEPS_JSON=""+append() { [[ -z "$STEPS_JSON" ]] || STEPS_JSON+=","; STEPS_JSON+="$1"; }++if [[ -n "$PLAN" ]]; then+ # Explicit plan: array of steps. `flash` steps name a partition + an image key that+ # must exist in IMG (or a literal file under the factory dir). We still split big ones.+ [[ -f "$PLAN" ]] || { echo "plan not found: $PLAN" >&2; exit 1; }+ command -v jq >/dev/null || { echo "jq required to use -P plan.json" >&2; exit 1; }+ while IFS= read -r line; do+ action="$(jq -r '.action' <<<"$line")"+ case "$action" in+ flash)+ part="$(jq -r '.partition' <<<"$line")"+ key="$(jq -r '.image' <<<"$line")"+ src="${IMG[$key]:-$WORK/$key}"+ [[ -e "$src" ]] || src="$WORK/inner/$key"+ [[ -e "$src" ]] || { echo "plan references missing image: $key" >&2; exit 1; }+ append "$(stage_flash "$part" "$src")"+ ;;+ *) append "$line" ;;+ esac+ done < <(jq -c '.[]' "$PLAN")+else+ echo " WARNING: no -P plan.json given; generating a best-effort plan. VERIFY against" >&2+ echo " the device's real flash-all before trusting this for a release." >&2+ [[ -n "${IMG[bootloader]:-}" ]] && { append "$(stage_flash bootloader "${IMG[bootloader]}")"; append '{"action":"reboot-bootloader"}'; }+ [[ -n "${IMG[radio]:-}" ]] && { append "$(stage_flash radio "${IMG[radio]}")"; append '{"action":"reboot-bootloader"}'; }+ for part in "${!IMG[@]}"; do+ case "$part" in bootloader|radio) continue ;; esac+ append "$(stage_flash "$part" "${IMG[$part]}")"+ done+ append '{"action":"erase","partition":"userdata"}'+ append '{"action":"reboot"}'+fi++MANIFEST="$STAGE/manifest.json"+cat > "$MANIFEST" <<EOF+{+ "device": "$DEVICE",+ "build": "$BUILD",+ "steps": [ $STEPS_JSON ]+}+EOF+echo ">> manifest: $MANIFEST"+echo " $(find "$STAGE" -type f | wc -l) file(s) staged in $STAGE"++if [[ "$UPLOAD" -eq 0 ]]; then+ echo ">> --no-upload set; skipping R2 upload"+ exit 0+fi++# ---- Upload to R2 (mirrors ota/publish-ota.sh) ----+command -v aws >/dev/null || { echo "aws CLI (v2) required to upload" >&2; exit 1; }+: "${R2_ACCESS_KEY_ID:?set R2_ACCESS_KEY_ID}"+: "${R2_SECRET_ACCESS_KEY:?set R2_SECRET_ACCESS_KEY}"+ENDPOINT="${R2_ENDPOINT:-}"+if [[ -z "$ENDPOINT" ]]; then+ : "${R2_ACCOUNT_ID:?set R2_ACCOUNT_ID or R2_ENDPOINT}"+ ENDPOINT="https://${R2_ACCOUNT_ID}.r2.cloudflarestorage.com"+fi+export AWS_ACCESS_KEY_ID="$R2_ACCESS_KEY_ID" AWS_SECRET_ACCESS_KEY="$R2_SECRET_ACCESS_KEY"+export AWS_DEFAULT_REGION="auto"+export AWS_REQUEST_CHECKSUM_CALCULATION="when_required"+export AWS_RESPONSE_CHECKSUM_VALIDATION="when_required"+s3() { aws s3 --endpoint-url "$ENDPOINT" "$@"; }++# Images first (immutable), manifest last (uncacheable) so the installer never sees a+# manifest pointing at a not-yet-uploaded image. Upload to the versioned path, then mirror+# to /latest/ which the installer reads by default.+for dest in "factory/$DEVICE/$BUILD" "factory/$DEVICE/latest"; do+ echo ">> uploading images -> s3://$BUCKET/$dest/"+ for img in "$STAGE"/*.img "$STAGE"/*.simg; do+ [[ -e "$img" ]] || continue+ s3 cp "$img" "s3://$BUCKET/$dest/$(basename "$img")" \+ --content-type "application/octet-stream" \+ --cache-control "public, max-age=31536000, immutable" --only-show-errors+ done+ echo ">> uploading manifest -> s3://$BUCKET/$dest/manifest.json"+ s3 cp "$MANIFEST" "s3://$BUCKET/$dest/manifest.json" \+ --content-type "application/json" \+ --cache-control "no-store, must-revalidate" --only-show-errors+done++echo ">> done. Installer will read https://ota.ma.vayunmathur.com/factory/$DEVICE/latest/manifest.json"
installer/sparse_split.py
diff --git a/installer/sparse_split.py b/installer/sparse_split.pynew file mode 100755index 0000000..e45e9d4--- /dev/null+++ b/installer/sparse_split.py@@ -0,0 +1,124 @@+#!/usr/bin/env python3+"""+sparse_split.py — split a raw partition image into multiple Android *sparse* images,+each small enough for one fastboot `download` (i.e. under the device's max-download-size).++Why: partitions like `super` are multiple GB, but a device only accepts max-download-size+bytes per download (often a few hundred MB). fastboot normally re-chunks large images into+several sparse files and flashes each to the same partition; the MAOS web installer flashes+pre-split chunks instead of implementing sparse in the browser. Each output file is a full+sparse image for the WHOLE partition, but contains real data only for its slice and marks+the rest DONT_CARE, so flashing them in order reconstructs the partition.++Sparse format ref: AOSP system/core/libsparse (sparse_format.h).++USAGE:+ sparse_split.py <raw-image> <out-prefix> [--max-bytes N] [--block-size 4096]++Emits <out-prefix>.0.simg, <out-prefix>.1.simg, ... and prints each filename on stdout.++NOTE: authored against the documented format; validate a real flash on a device before+relying on it.+"""+import argparse+import os+import struct+import sys++SPARSE_MAGIC = 0xED26FF3A+CHUNK_RAW = 0xCAC1+CHUNK_FILL = 0xCAC2+CHUNK_DONT_CARE = 0xCAC3++FILE_HDR_SZ = 28+CHUNK_HDR_SZ = 12+++def write_header(f, block_size, total_blocks, total_chunks):+ f.write(+ struct.pack(+ "<IHHHHIIII",+ SPARSE_MAGIC,+ 1, # major+ 0, # minor+ FILE_HDR_SZ,+ CHUNK_HDR_SZ,+ block_size,+ total_blocks,+ total_chunks,+ 0, # image checksum (unused)+ )+ )+++def write_dont_care(f, blocks):+ f.write(struct.pack("<HHII", CHUNK_DONT_CARE, 0, blocks, CHUNK_HDR_SZ))+++def write_raw(f, data, block_size):+ assert len(data) % block_size == 0+ blocks = len(data) // block_size+ f.write(struct.pack("<HHII", CHUNK_RAW, 0, blocks, CHUNK_HDR_SZ + len(data)))+ f.write(data)+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("raw")+ ap.add_argument("out_prefix")+ ap.add_argument("--max-bytes", type=int, default=100 * 1024 * 1024,+ help="max real data bytes per output file (default 100 MiB)")+ ap.add_argument("--block-size", type=int, default=4096)+ args = ap.parse_args()++ bs = args.block_size+ size = os.path.getsize(args.raw)+ total_blocks = (size + bs - 1) // bs+ # Real-data blocks per output file (keep each file's payload under --max-bytes).+ blocks_per_file = max(1, args.max_bytes // bs)++ outputs = []+ with open(args.raw, "rb") as src:+ idx = 0+ start = 0 # starting block for this output file+ while start < total_blocks:+ end = min(start + blocks_per_file, total_blocks)+ out_path = f"{args.out_prefix}.{idx}.simg"+ with open(out_path, "wb") as out:+ # chunks: [DONT_CARE prefix?] [RAW slice] [DONT_CARE suffix?]+ chunks = 0+ chunks += 1 if start > 0 else 0+ chunks += 1 # the RAW slice+ chunks += 1 if end < total_blocks else 0+ write_header(out, bs, total_blocks, chunks)++ if start > 0:+ write_dont_care(out, start)++ src.seek(start * bs)+ to_read = (end - start) * bs+ data = src.read(min(to_read, size - start * bs))+ # Zero-pad the final block if the image isn't block-aligned.+ if len(data) % bs != 0:+ data += b"\x00" * (bs - (len(data) % bs))+ # If this slice runs past EOF (last file), pad remaining blocks with zeros.+ expected = (end - start) * bs+ if len(data) < expected:+ data += b"\x00" * (expected - len(data))+ write_raw(out, data, bs)++ if end < total_blocks:+ write_dont_care(out, total_blocks - end)++ outputs.append(out_path)+ print(out_path)+ idx += 1+ start = end++ if not outputs:+ print("no output produced", file=sys.stderr)+ sys.exit(1)+++if __name__ == "__main__":+ main()