From d87df1f137e9a1d7dd578e29115059db009b09b1 Mon Sep 17 00:00:00 2001 From: listlessbird <124798751+listlessbird@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:58:51 +0530 Subject: [PATCH] feat(kindle): the Kindle runs one Dropcap extension from this repo dropcap.sh delivers books, runs the app's commands, reports the device and uploads its log, with optional Tailscale SSH and Wi-Fi tools, under one boot job. kindle/kd and the kindle-device skill let agents check, reach and deploy to the Kindle. --- .agents/skills/kindle-device/SKILL.md | 81 +++++ .github/workflows/ci.yml | 3 + .gitignore | 8 + AGENTS.md | 5 +- README.md | 81 +++++ apps/mobile/src/features/sending/book.ts | 2 +- apps/worker/src/Api.ts | 10 +- apps/worker/src/Worker.ts | 2 +- apps/worker/test/Mailbox.test.ts | 2 +- docs/internals/kindle.md | 24 ++ kindle/dropcap/config.xml | 11 + kindle/dropcap/dropcap.sh | 83 +++++ kindle/dropcap/dropcap.test.ts | 393 +++++++++++++++++++++++ kindle/dropcap/lib/boot.sh | 53 +++ kindle/dropcap/lib/mailbox.sh | 238 ++++++++++++++ kindle/dropcap/lib/tailscale.sh | 154 +++++++++ kindle/dropcap/lib/wifi.sh | 85 +++++ kindle/dropcap/menu.json | 73 +++++ kindle/kd | 63 ++++ vite.config.ts | 2 + 20 files changed, 1363 insertions(+), 10 deletions(-) create mode 100644 .agents/skills/kindle-device/SKILL.md create mode 100644 docs/internals/kindle.md create mode 100644 kindle/dropcap/config.xml create mode 100755 kindle/dropcap/dropcap.sh create mode 100644 kindle/dropcap/dropcap.test.ts create mode 100644 kindle/dropcap/lib/boot.sh create mode 100644 kindle/dropcap/lib/mailbox.sh create mode 100644 kindle/dropcap/lib/tailscale.sh create mode 100644 kindle/dropcap/lib/wifi.sh create mode 100644 kindle/dropcap/menu.json create mode 100755 kindle/kd diff --git a/.agents/skills/kindle-device/SKILL.md b/.agents/skills/kindle-device/SKILL.md new file mode 100644 index 0000000..ec1b04c --- /dev/null +++ b/.agents/skills/kindle-device/SKILL.md @@ -0,0 +1,81 @@ +--- +name: kindle-device +description: Work on and debug the user's jailbroken Kindle that Dropcap delivers to. Use when changing anything under kindle/, deploying it, checking whether the Kindle is delivering, reporting or running commands, reading its logs, reaching it over SSH or USB, or rotating its token. +--- + +# Working on the Kindle + +Read `docs/internals/kindle.md` first. The Kindle is the user's daily reader, so deploying to it is outward-facing like deploying the Worker: do it when the task asks for it, and verify it afterwards. + +Everything on the device lives in `/mnt/us/extensions/dropcap/`: the scripts from `kindle/dropcap/`, plus device-only files that are never in git (`mailbox.url`, `mailbox.token`, `tailscale/` binaries and `state/`, `dropcap.log`, `run-once.d/`). + +## Look before you touch + +These read the Worker and never wake or change the Kindle: + +```sh +kindle/kd status # last check-in, battery, storage, firmware, book titles, queued commands +kindle/kd logs # the end of dropcap.log, uploaded on every wake +``` + +`checkedInAt` moves on every wake that reaches the Worker. If it is recent and `kd logs` shows no errors, delivery is healthy. + +## Reach it + +1. `tailscale ping -c 1 kindle`. No reply means it is asleep, or its Wi-Fi is down. Ask the user to wake it; nothing below works until then. +2. `kindle/kd ssh ''` runs as root over Tailscale SSH. There is no scp: copy with `kindle/kd ssh 'cat > /path' < file`. +3. Keep it awake while you work: `kindle/kd ssh 'lipc-set-prop com.lab126.powerd preventScreenSaver 1'`. Set it back to `0` when you are done, every time. + +Health over SSH: + +```sh +kindle/kd ssh 'D=/mnt/us/extensions/dropcap; initctl status dropcap; $D/dropcap.sh running && echo delivering; ps -o pid,ppid,args | grep -E "[d]ropcap.sh (loop|receive)|[t]ailscaled --state"; tail -20 $D/dropcap.log' +``` + +Expect `dropcap start/running`, one `dropcap.sh loop` (a child with it as parent is a pipeline in flight), one `dropcap.sh receive`, and `tailscaled`. + +Kill only a PID you read from `ps -o pid,args` or `/var/run/dropcap/*.pid`. A `pkill -f` pattern also matches your own SSH session's command line, and `ps | grep` output contains your own command too. + +## Change and deploy + +1. Edit under `kindle/dropcap/`. The device runs BusyBox 1.34 ash: no bashisms, and see the traps in the internals doc. +2. `pnpm vp test run kindle/dropcap` runs the scripts under `busybox sh` against a fake Worker, and runs ShellCheck in busybox mode. +3. `kindle/kd deploy` syntax-checks, pushes the files over SSH, and restarts delivery. Confirm with `kindle/kd ssh 'md5sum /mnt/us/extensions/dropcap/lib/*.sh'` against the repo copies, then wait for a `reportedAt` newer than the deploy. +4. A `lib/tailscale.sh` change takes effect on Tailscale's next start. Restart it by killing it and letting the boot job bring it back, which ends your session and returns SSH in about a minute: `kindle/kd ssh 'kill $(cat /var/run/dropcap/tailscaled.pid)'`. Never run `ssh-start`, or any script that stops Tailscale, from an SSH session: the session's teardown kills it partway, even under `nohup`. +5. Prove the command path with `kindle/kd rescan`, then watch `kindle/kd status` until it settles `ok`. It runs on the next wake, or within 10 minutes while the Kindle is awake. `dropcap.sh start` runs a pass immediately. + +## Changing the boot job or the layout on the device + +Anything that stops the boot job, replaces it, or moves files Tailscale needs goes in a `run-once.d` script, so it runs from the delivery loop with no SSH session to lose. Install the new supervisor before removing the old one: a Kindle with neither stays down until someone taps KUAL → Dropcap → Start or restarts it. + +## Without SSH (USB) + +When Tailscale is broken, ask the user to plug the Kindle in. It mounts at `/media/$USER/Kindle` (`udisksctl mount -b /dev/sda1` if it does not). + +- `kindle/kd deploy` notices the mount, copies the files, and queues a restart in `extensions/dropcap/run-once.d/`. +- Any `extensions/dropcap/run-once.d/*.sh` runs once on the next wake, then is renamed `.ran`. Its output lands in `dropcap.log`, which reaches `kindle/kd logs`, so you get remote execution and its results with no SSH. A script can also upload a file with `curl -sf -H @/var/run/dropcap/auth -X PUT --data-binary @file "$(cat /mnt/us/extensions/dropcap/mailbox.url)/reports/"`. +- Eject with `sync && udisksctl unmount -b /dev/sda1 && udisksctl power-off -b /dev/sda`. The Kindle is back on Wi-Fi a few minutes later. + +## When it stops delivering + +- **`checkedInAt` is stale:** wake it and check `lipc-get-prop com.lab126.wifid cmState` (should be `CONNECTED`), then the health command above. The boot job restarts a dead loop within a minute. +- **Checks in, but `device report rejected` in the log:** the Worker's `DeviceReport` schema refused a value. Compare what `report_device` sends with `apps/worker/src/Api.ts`. +- **401s:** `extensions/dropcap/mailbox.token` and `KINDLE_TOKEN` in `~/.config/kindle-mailbox/secrets.env` differ. +- **A book is missing from the library:** query the library DB; logs give false matches. `kindle/kd ssh 'sqlite3 /var/local/cc.db "select p_cdeType, p_location from Entries where p_location like \"%%\""'`. +- **Tailscale says it needs a login:** `extensions/dropcap/tailscale/needs-login` exists and the boot job leaves Tailscale alone. The user taps KUAL → Dropcap → Start Tailscale and approves the on-screen link. +- **Wi-Fi itself is broken:** the user taps KUAL → Dropcap → Wi-Fi diagnostics. It uploads `reports/wifi-diag.txt` when it can, else read `extensions/dropcap/wifi-diag.txt` over USB. + +## Rotate KINDLE_TOKEN + +Do this whenever the token shows up in a transcript or log. Never print it. + +1. Write a new random value into `~/.config/kindle-mailbox/secrets.env` without echoing it. +2. Deploy the Worker (see AGENTS.md); the plan should be `[Mailbox] update` only. +3. `sed -n 's/^KINDLE_TOKEN=//p' ~/.config/kindle-mailbox/secrets.env | tr -d '\n' | kindle/kd ssh 'cat > /mnt/us/extensions/dropcap/mailbox.token'` +4. `kindle/kd ssh /mnt/us/extensions/dropcap/dropcap.sh start` and confirm a fresh `checkedInAt`. + +## Recovery + +- **Dropcap gone after a reset:** `kindle/kd deploy` over USB, write `mailbox.url` (the Worker's https URL) and `mailbox.token` into `extensions/dropcap/`, then KUAL → Dropcap → Start on boot, and Start. +- **Tailscale binaries missing:** fetch the static `arm` (not arm64) tarball from pkgs.tailscale.com into `extensions/dropcap/tailscale/`. +- **Off the tailnet** (`tailscale/state/` lost): KUAL → Dropcap → Start Tailscale shows a login link to approve. Then disable key expiry for `kindle` in the admin console. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e414c23..115e122 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -29,6 +29,9 @@ jobs: - run: pnpm install --frozen-lockfile + # The Kindle script tests run under busybox sh with the sqlite3 CLI, like the device. + - run: sudo apt-get install -y --no-install-recommends busybox sqlite3 + - name: Format run: pnpm vp fmt --check diff --git a/.gitignore b/.gitignore index 069bff1..7db1172 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,11 @@ node_modules/ __screenshots__/ .repos/ .alchemy/ + +# Device-only files, if a copy of the Kindle's extension folder ever lands here: tokens, the Tailscale +# binaries and enrollment, run-once scripts, network credentials. +kindle/dropcap/mailbox.* +kindle/dropcap/tailscale/ +kindle/dropcap/run-once.d/ +kindle/dropcap/network.conf +kindle/dropcap/wifi-diag.txt diff --git a/AGENTS.md b/AGENTS.md index d8aebb2..f53628d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,7 +14,7 @@ These instructions are good defaults, not hard rules. My direct requests overrid 1. **Killing by pattern.** Never `pkill -f`, `pgrep | kill`, or kill a PID you found by matching a name or path. Your own agent process has this checkout's path in its argv. Kill only a PID you captured at spawn, or the owner of your port from `ss -H -ltnp` after confirming `/proc//cwd` is this checkout. 2. **Touching the real install.** The production app (`com.listlessbird.kindledrop`) is the user's daily driver. Only install, clear, or uninstall the `.dev` package. Never run `adb shell pm clear` or `adb uninstall` against the production or `.preview` package. -3. **Publishing.** `eas update`, `eas build`, `eas submit`, and anything else that reaches the Expo or Play servers is outward-facing. OTA updates land on real devices. The same goes for deploying `apps/worker`: the Kindle pulls from it on every wake. Run them only when the user asks, and name the channel or stage before you do. +3. **Publishing.** `eas update`, `eas build`, `eas submit`, and anything else that reaches the Expo or Play servers is outward-facing. OTA updates land on real devices. The same goes for deploying `apps/worker`: the Kindle pulls from it on every wake. Deploying `kindle/` to the device is outward-facing too: it is the user's daily reader. Run them only when the user asks, and name the channel or stage before you do. Alchemy needs `CLOUDFLARE_API_TOKEN` and `CLOUDFLARE_ACCOUNT_ID` in the environment, and secrets never reach argv, logs or `set -x`. ## Dev loop @@ -43,7 +43,8 @@ These instructions are good defaults, not hard rules. My direct requests overrid - `apps/mobile`: the Expo app. `src/Stack.tsx` declares every screen and its deep link path. `src/components/ui` is the UI kit, `src/features/` holds screens and feature logic, `src/state` holds atoms, `src/persistence` holds storage services, and `src/lib` holds small shared modules. - The UI kit is Android-only: Compose controls through `@expo/ui` and Tabler icons through `AppSymbol`. Its dev-only catalog (`kindledrop-dev://dev/components`) renders every component with the theme controls on top. Add a new kit component to it. - `apps/mobile/modules/kindle-core`: the EPUB to Kindle converter, a Rust crate (`rust/`) exposed as the `KindleCore` turbo module by uniffi-bindgen-react-native. The app reaches it through the `KindleCore` service in `src/lib/kindleCore.ts`. -- `apps/worker`: the Cloudflare Worker + R2 mailbox between the app and the user's Kindle, an Effect `HttpApi` deployed with Alchemy. `src/Api.ts` is the contract: the app derives its client from it, and the Kindle's `ts.sh` (in `~/projects/kindle`) speaks it with curl, so keep status codes and the text listing stable. `pnpm vp run --filter @kindle-drop/worker dev` serves it locally, and its tests boot the same stack in workerd. +- `apps/worker`: the Cloudflare Worker + R2 mailbox between the app and the user's Kindle, an Effect `HttpApi` deployed with Alchemy. `src/Api.ts` is the contract: the app derives its client from it, and the Kindle's `kindle/dropcap/dropcap.sh` speaks it with curl, so keep status codes and the text listing stable. `pnpm vp run --filter @kindle-drop/worker dev` serves it locally, and its tests boot the same stack in workerd. +- `kindle`: `dropcap/` is the KUAL extension the Kindle runs, one `dropcap.sh` entry point over `lib/` modules for delivery, optional Tailscale SSH, Wi-Fi tools and the boot job. `kindle/kd` reads the Kindle's status and logs from the Worker, opens SSH, and deploys. Use the `kindle-device` skill for any work on the device, and read `docs/internals/kindle.md` first. - `oxlint-plugin-kd`: this repo's lint rules, ported from T3 Code. - `oxlint-plugin-anti-slop`: vendored [anti-slop](https://github.com/dmmulroy/anti-slop) rules. Update it with the `install-anti-slop` skill; never overwrite it. Provenance is in its `UPSTREAM.md`. - `scripts`: repo tooling (`check-changed`, `setup-worktree`, `sync-reference-repos`). diff --git a/README.md b/README.md index efb3a09..8a37d3e 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,84 @@ # kindle-drop + +**Dropcap** sends books (`EPUB`, `AZW3`, `PDF`, `TXT`) and web articles from Android to a jailbroken stock-reader Kindle over Wi-Fi, with lock-screen covers and no Send to Kindle or USB. + +`EPUB` files and shared links convert on-device in Rust (`kindling-mobi` + Readability) to KF8 `.azw3` (`EBOK`) plus their cover thumbnail, upload to a private Cloudflare Worker + R2 mailbox (30-day retention), and land on the Kindle the next time it wakes. The app also shows battery, free storage, and the Kindle's library, and queues deletes and rescans. + +## Setup + +### 1. Deploy the mailbox + +Needs a Cloudflare account (Workers + R2), Node `>= 24.15`, and `pnpm` 10. + +Create `~/.config/kindle-mailbox/secrets.env` with two random tokens: + +```env +APP_TOKEN=<32-byte-random-token> +KINDLE_TOKEN=<32-byte-random-token> +``` + +Deploy the Worker and R2 bucket (`kindle-mailbox`): + +```bash +pnpm install +pnpm vp run --filter @kindle-drop/worker deploy +``` + +### 2. Set up the Kindle + +Needs a jailbroken Kindle on stock firmware (tested on PW3, FW `5.16.2.1.1`) with SSH or USB access. + +Copy [`kindle/dropcap/`](kindle/dropcap) to `/mnt/us/extensions/dropcap/`, then write two config files next to `dropcap.sh`: + +- `mailbox.url`: `https://.workers.dev` +- `mailbox.token`: the `KINDLE_TOKEN` from step 1 + +Enable boot persistence and start it over SSH, or from KUAL → Dropcap: + +```sh +chmod +x /mnt/us/extensions/dropcap/dropcap.sh +/mnt/us/extensions/dropcap/dropcap.sh install-boot +/mnt/us/extensions/dropcap/dropcap.sh start +``` + +On every wake (`lipc-wait-event com.lab126.powerd outOfScreenSaver,wakeupFromSuspend`), the script pulls queued items, installs `thumbnail_*_portrait.jpg` covers into `/mnt/us/system/thumbnails/` (keeping copies in `/mnt/us/amazon-cover-bug/` to guard against Amazon placeholders), moves books into `/mnt/us/documents/`, rescans the library, runs queued commands, reports status from `/var/local/cc.db`, and uploads its log. See [`apps/worker/src/Api.ts`](apps/worker/src/Api.ts) for the wire contract. + +For SSH and Taildrop, put the static `arm` Tailscale binaries (`tailscale`, `tailscaled`) in `/mnt/us/extensions/dropcap/tailscale/` and tap KUAL → Dropcap → Start Tailscale once to log in; the boot job keeps it running. KUAL → Dropcap also has Wi-Fi join and diagnostics. With SSH working, `kindle/kd` reads the Kindle's status and log from the Worker, opens a shell, and deploys changes. + +### 3. Install and pair the Android app + +Download the latest `dropcap-*.apk` from [Releases](https://github.com/listlessbird/kindle-drop/releases) (or build with `pnpm vp run --filter @kindle-drop/mobile eas:android:prod`). + +Print a pairing QR code on your computer and scan it in Dropcap: + +```bash +pnpm vp run --filter @kindle-drop/worker pair --server https://.workers.dev +``` + +## Development + +JS-only changes and CI need Node `>= 24.15` and `pnpm` 10 (UniFFI bindings are committed). Native Android builds and Rust edits also need `ANDROID_HOME`, `cargo`, `cargo-ndk`, and the `aarch64-linux-android` + `x86_64-linux-android` targets. + +```bash +# Local Worker +APP_TOKEN=dev-app KINDLE_TOKEN=dev-kindle pnpm vp run --filter @kindle-drop/worker dev + +# Android dev client (fingerprint-cached APK) + Metro +pnpm vp run mobile:install android +pnpm vp run --filter @kindle-drop/mobile dev:client + +# Pair dev client on an emulator +pnpm vp run --filter @kindle-drop/worker pair --server http://10.0.2.2:1337 --key dev-app --scheme kindledrop-dev + +# Format, lint, typecheck, and affected tests +pnpm vp run check:changed +``` + +Regenerate bindings after changing `apps/mobile/modules/kindle-core/rust` (from `apps/mobile/modules/kindle-core`): + +```bash +cargo build --release --manifest-path rust/Cargo.toml +pnpm exec ubrn generate all --config ubrn.config.yaml rust/target/release/libkindle_core.so +``` diff --git a/apps/mobile/src/features/sending/book.ts b/apps/mobile/src/features/sending/book.ts index 5562261..7d403cd 100644 --- a/apps/mobile/src/features/sending/book.ts +++ b/apps/mobile/src/features/sending/book.ts @@ -359,7 +359,7 @@ export const formatOf = (name: string, mimeType: Option.Option) => /** The shared file's name without a format's extension, the title until conversion finds one. */ export const stem = (name: string) => name.replace(EXTENSION, ""); -// What ts.sh's tab-separated listing and the Kindle's file system cannot take. +// What dropcap.sh's tab-separated listing and the Kindle's file system cannot take. const UNSAFE_IN_NAME = /[\u0000-\u001f\u007f/\\:*?"<>|]/g; /** The shared file's name, made safe for the mailbox. EPUBs keep the converter's names instead. */ diff --git a/apps/worker/src/Api.ts b/apps/worker/src/Api.ts index 845c1b2..90a9d2c 100644 --- a/apps/worker/src/Api.ts +++ b/apps/worker/src/Api.ts @@ -11,7 +11,7 @@ import * as HttpApiMiddleware from "effect/http-api/HttpApiMiddleware"; import * as HttpApiSchema from "effect/http-api/HttpApiSchema"; import * as HttpApiSecurity from "effect/http-api/HttpApiSecurity"; -// The Kindle's ts.sh parses "\t\n" listing lines and writes to disk. +// The Kindle's dropcap.sh parses "\t\n" listing lines and writes to disk. export const ItemName = Schema.String.check(Schema.isPattern(/^[^\t\n\r/]+$/)).pipe( Schema.brand("ItemName"), ); @@ -55,7 +55,7 @@ export class EitherAuth extends HttpApiMiddleware.Service()("EitherA security: { bearer: HttpApiSecurity.bearer }, }) {} -// ts.sh deletes by path, so `.` and `..` segments are refused to keep a command inside documents/. +// dropcap.sh deletes by path, so `.` and `..` segments are refused to keep a command inside documents/. export const BookPath = Schema.String.check( Schema.isPattern(/^\/mnt\/us\/documents(?:\/(?!\.\.?(?:\/|$))[^/\t\n\r]+)+$/), ).pipe(Schema.brand("BookPath")); @@ -89,7 +89,7 @@ const BookFromFields = TabSeparated.pipe( const IntFromString = Schema.FiniteFromString.check(Schema.isInt()); /** - * What ts.sh reports on every wake, as curl's default form encoding. It leaves out a value it + * What dropcap.sh reports on every wake, as curl's default form encoding. It leaves out a value it * could not read, and the Worker rejects a malformed one. */ export const DeviceReport = Schema.Struct({ @@ -136,7 +136,7 @@ export const commandId = (queuedAtMillis: number, random: number) => /** The Worker's clock when the app queued the command, in epoch milliseconds. */ export const queuedAtOfId = (id: CommandId) => Number(id.slice(0, 15)); -/** How a command ended on the Kindle. ts.sh sends it as a form, and R2 keeps it as metadata. */ +/** How a command ended on the Kindle. dropcap.sh sends it as a form, and R2 keeps it as metadata. */ export const Outcome = Schema.Union([ Schema.Struct({ outcome: Schema.Literal("ok") }), Schema.Struct({ outcome: Schema.Literal("failed"), message: Schema.String }), @@ -200,7 +200,7 @@ export class AppGroup extends HttpApiGroup.make("app") .add(HttpApiEndpoint.delete("dismiss", "/commands/:id", { params: { id: CommandId } })) .middleware(AppAuth) {} -/** The Kindle's side, driven by curl in ts.sh on every wake. */ +/** The Kindle's side, driven by curl in dropcap.sh on every wake. */ export class KindleGroup extends HttpApiGroup.make("kindle") .add(HttpApiEndpoint.get("list", "/items/", { success: Text })) .add( diff --git a/apps/worker/src/Worker.ts b/apps/worker/src/Worker.ts index 4f5f401..9ab8e22 100644 --- a/apps/worker/src/Worker.ts +++ b/apps/worker/src/Worker.ts @@ -33,7 +33,7 @@ const HttpPlatformWeb = Layer.succeed(HttpPlatform.HttpPlatform, { const encodeItemId = Schema.encodeSync(ItemId); -// ts.sh splits each listing line on tabs: the id, the verb, then the verb's argument. +// dropcap.sh splits each listing line on tabs: the id, the verb, then the verb's argument. const commandLine = Command.match({ DeleteBook: ({ path }) => `delete\t${path}`, Rescan: () => "rescan", diff --git a/apps/worker/test/Mailbox.test.ts b/apps/worker/test/Mailbox.test.ts index 07b6306..8c1bc62 100644 --- a/apps/worker/test/Mailbox.test.ts +++ b/apps/worker/test/Mailbox.test.ts @@ -42,7 +42,7 @@ const appClient = Effect.gen(function* () { }); }); -// Requests shaped like ts.sh's `curl -sf -H "Authorization: Bearer ..."` on the Kindle. +// Requests shaped like dropcap.sh's `curl -sf -H "Authorization: Bearer ..."` on the Kindle. const kindle = (method: "GET" | "PUT" | "DELETE", path: string, as = kindleToken) => Effect.gen(function* () { const { url } = yield* stack; diff --git a/docs/internals/kindle.md b/docs/internals/kindle.md new file mode 100644 index 0000000..1caf642 --- /dev/null +++ b/docs/internals/kindle.md @@ -0,0 +1,24 @@ +# The Kindle + +The Kindle is the user's daily reader: a Paperwhite 3 (armv7, BusyBox 1.34 ash, 512MB RAM) jailbroken on firmware 5.16.2.1.1 and kept on the stock reader. `kindle/dropcap/` is the one KUAL extension it runs, and the `kindle-device` skill covers working on it. + +## One extension, separate processes + +- `dropcap.sh` is the only entry point. `lib/mailbox.sh` delivers books, runs the app's commands and reports; `lib/tailscale.sh` gives SSH and Taildrop when the static Tailscale binaries are in `tailscale/`; `lib/wifi.sh` holds recovery tools; `lib/boot.sh` holds the boot job. +- Delivery and Tailscale run as separate processes with separate start and stop, so restarting one never takes down the other. Restarting Tailscale ends SSH sessions; delivery does not depend on it at all. +- One upstart job on the root filesystem runs `dropcap.sh supervise` every minute. The userstore (`/mnt/us`, where the scripts live) disappears while USB storage is mounted, so the job restarts whatever died once it returns. Modules are sourced once at startup and every process `cd /`, so nothing pins the userstore. +- Each long-running process holds a `flock` in `/var/run/dropcap/`, so a second copy exits, and "running" means "the lock is held". Long-lived children close the lock's fd so they never keep it after their parent dies. + +## Traps + +- **Never let it take an OTA update.** The jailbreak depends on 5.16.2.1.1. The OTA binaries are renamed to `/usr/bin/otaupd.bck` and `otav3.bck`; leave them that way. +- **Don't tag the Kindle in Tailscale.** Taildrop refuses tagged nodes, and SSH only allows the user's own untagged devices. +- **`tailscale/state/` is the Kindle's tailnet enrollment.** Moving it is fine; deleting it means a new login approved from the device. +- **The firmware indexes non-books as PDOC.** KUAL, Run Hotfix, `My Clippings.txt` and crash dumps all appear in `cc.db` as PDOC, so `books()` matches reader extensions and leaves those out. The app offers Delete on anything listed. +- **BusyBox differs from a laptop shell.** `kill -0 ""` succeeds, a failed `< file` redirect reports before a later `2>/dev/null` applies, and `ps` hides arguments unless asked for `ps -o pid,args`. The tests run everything under `busybox sh` and ShellCheck's busybox mode for this reason. +- **A shell defers its TERM trap until the foreground command returns.** The loop waits for wake events with a background `lipc-wait-event` and `wait`, so a stop lands at once, except during a download. +- **Process arguments are visible.** `ps -o args` shows every argument, so secrets go through files (curl reads its bearer header with `-H @file`, tailscale its auth key with `file:`), never argv. +- **TLS 1.2 only.** The Kindle's curl links OpenSSL 1.0.2, so the Worker must never require TLS 1.3. +- **Asleep means unreachable.** Wi-Fi turns off when it suspends. Keep it awake while working with `lipc-set-prop com.lab126.powerd preventScreenSaver 1`, and set it back to 0. +- **Its clock is off.** The Kindle reports a broken timezone and drifts by minutes. Trust the Worker's `checkedInAt` and `reportedAt`. +- **Covers:** books are EBOK with an ASIN so the lock screen shows them. The firmware fetches Amazon's "No image" placeholder within seconds for an EBOK book with no thumbnail, so the cover must be installed before the book, and the guard restores it if it is ever replaced. diff --git a/kindle/dropcap/config.xml b/kindle/dropcap/config.xml new file mode 100644 index 0000000..20dfee1 --- /dev/null +++ b/kindle/dropcap/config.xml @@ -0,0 +1,11 @@ + + + + Dropcap + 1.0 + dropcap + + + menu.json + + diff --git a/kindle/dropcap/dropcap.sh b/kindle/dropcap/dropcap.sh new file mode 100755 index 0000000..77060e2 --- /dev/null +++ b/kindle/dropcap/dropcap.sh @@ -0,0 +1,83 @@ +#!/bin/sh +# Dropcap for a jailbroken stock-reader Kindle: book delivery from the Dropcap mailbox, plus optional +# Tailscale SSH/Taildrop and Wi-Fi tools. Runs under busybox ash as root. +# +# Usage: dropcap.sh start|stop|running the delivery loop +# dropcap.sh ssh-start|ssh-stop|ssh-status Tailscale SSH and Taildrop (needs tailscale/ binaries) +# dropcap.sh wifi-join|wifi-diag join network.conf's network, or collect Wi-Fi diagnostics +# dropcap.sh install-boot|uninstall-boot the boot job that keeps both running +# dropcap.sh books|guard list the library, restore covers +# Subcommands are single words, so they work however KUAL passes a menu item's params. +# QUIET=1 keeps messages off the screen (the boot job sets it). +# +# Functions return non-zero on failure and callers decide what to do; nothing here uses set -e, which +# would kill a long-running loop on the first failed curl. + +ROOT=${DROPCAP_ROOT:-/mnt/us} +DIR=$ROOT/extensions/dropcap +RUN=${DROPCAP_RUN:-/var/run/dropcap} +LOG=$DIR/dropcap.log +HERE=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd) || exit 1 +SELF=$HERE/${0##*/} + +log() { + echo "[$(date '+%F %T')] $1" >> "$LOG" +} + +# Log, and show on the Kindle's screen unless QUIET. Never fails: the screen is best effort. +say() { + log "$1" + [ -n "${QUIET:-}" ] || eips 0 22 "$(printf '%-50s' "$1")" >/dev/null 2>&1 + return 0 +} + +# Take a lock, retrying for up to $1 seconds: BusyBox 1.34's flock has no -w. The rest of the +# arguments go to `flock -n`: an fd, or a file and a command to run while holding it. +lock_within() { + local tenths=$(($1 * 10)) + shift + until flock -n "$@"; do + tenths=$((tenths - 1)) + [ "$tenths" -gt 0 ] || return 1 + usleep 100000 + done +} + +usage() { + sed -n '5,10p' "$SELF" >&2 + exit 2 +} + +# Modules load once, up front: the userstore holding them vanishes while USB storage is mounted. +# shellcheck source=SCRIPTDIR/lib/mailbox.sh +. "$HERE/lib/mailbox.sh" +# shellcheck source=SCRIPTDIR/lib/tailscale.sh +. "$HERE/lib/tailscale.sh" +# shellcheck source=SCRIPTDIR/lib/wifi.sh +. "$HERE/lib/wifi.sh" +# shellcheck source=SCRIPTDIR/lib/boot.sh +. "$HERE/lib/boot.sh" + +# A working directory on the userstore would keep it busy and block USB mode. +cd / || exit 1 +mkdir -p "$RUN" || exit 1 + +case "${1:-}" in + start) start ;; + stop) stop ;; + running) running ;; + loop) loop ;; + ssh-start) ssh_start ;; + ssh-stop) ssh_stop && say "Tailscale stopped" ;; + ssh-status) ssh_status ;; + receive) receive ;; + wifi-join) wifi_join ;; + wifi-diag) wifi_diag ;; + supervise) supervise ;; + shutdown) shutdown ;; + install-boot) install_boot ;; + uninstall-boot) uninstall_boot ;; + books) books ;; + guard) guard_covers ;; + *) usage ;; +esac diff --git a/kindle/dropcap/dropcap.test.ts b/kindle/dropcap/dropcap.test.ts new file mode 100644 index 0000000..72577c8 --- /dev/null +++ b/kindle/dropcap/dropcap.test.ts @@ -0,0 +1,393 @@ +import * as NodeChildProcess from "node:child_process"; +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; +import * as NodeSqlite from "node:sqlite"; +import { afterEach, expect, it } from "vite-plus/test"; + +const here = import.meta.dirname; +const script = NodePath.join(here, "dropcap.sh"); + +const which = (name: string) => + NodeChildProcess.execFileSync("which", [name], { encoding: "utf8" }).trim(); + +const busybox = which("busybox"); +const flockPath = which("flock"); + +// Every external command the scripts use runs as a BusyBox applet, as on the Kindle. This BusyBox +// lacks flock and nohup, so those two come from the laptop. +const applets = NodeChildProcess.execFileSync(busybox, ["--list"], { encoding: "utf8" }).split( + "\n", +); + +let cleanup: (() => void) | undefined; + +const executable = (path: string, body: string) => + NodeFS.writeFileSync(path, body, { mode: 0o755 }); + +// A fake Kindle in a temp dir, with `sh` pointing at busybox so every script runs under ash. +const kindle = () => { + const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "dropcap-")); + const bin = NodePath.join(root, "bin"); + const ext = NodePath.join(root, "extensions", "dropcap"); + const run = NodePath.join(root, "run"); + const responses = NodePath.join(root, "responses"); + const key = (url: string) => NodePath.join(responses, url.replaceAll("/", "_")); + + NodeFS.mkdirSync(bin); + NodeFS.mkdirSync(NodePath.join(root, "documents")); + NodeFS.mkdirSync(ext, { recursive: true }); + NodeFS.mkdirSync(responses); + + for (const applet of [ + "sh", + "cat", + "tr", + "sed", + "grep", + "awk", + "df", + "tail", + "head", + "cmp", + "mkdir", + "mv", + "cp", + "rm", + "date", + "sleep", + "usleep", + "printf", + "timeout", + "kill", + "touch", + "dirname", + ]) { + if (applets.includes(applet)) NodeFS.symlinkSync(busybox, NodePath.join(bin, applet)); + } + + // The laptop's util-linux flock takes options the Kindle's BusyBox 1.34 flock lacks, like -w. + executable( + NodePath.join(bin, "flock"), + `#!/bin/sh\ncase "$1" in -*[!sxun]*) echo "flock: invalid option $1" >&2; exit 1 ;; esac\nexec ${flockPath} "$@"\n`, + ); + NodeFS.writeFileSync(NodePath.join(ext, "mailbox.url"), "https://mailbox.invalid\n"); + NodeFS.writeFileSync(NodePath.join(ext, "mailbox.token"), "test-token\n"); + NodeChildProcess.execFileSync("mkfifo", [NodePath.join(root, "pass")]); + + // The Worker: GETs answer with what `respond` stored, -o writes the body, every call lands in + // curl.log, and a URL given to `hold` blocks until its file exists, like a download in flight. + executable( + NodePath.join(bin, "curl"), + `#!/bin/sh +method=GET url= out= fields= +while [ $# -gt 0 ]; do + case "$1" in + -X) method=$2; shift ;; + -o) out=$2; shift ;; + --data-urlencode) fields="$fields $2"; shift ;; + https://*) url=$1 ;; + esac + shift +done +echo "$method $url$fields" >> "${root}/curl.log" +k="${responses}/$(echo "$url" | tr / _)" +if [ -f "$k.hold" ]; then + until [ -e "$(cat "$k.hold")" ]; do usleep 10000; done +fi +[ "$method" = GET ] || exit 0 +if [ -n "$out" ]; then cat "$k" > "$out" 2>/dev/null || : > "$out"; else cat "$k" 2>/dev/null; fi +exit 0 +`, + ); + // Marks the end of a loop pass on the `pass` FIFO, then blocks like the real wake wait. + executable( + NodePath.join(bin, "lipc-wait-event"), + `#!/bin/sh\necho done > "${root}/pass"\nexec sleep 600\n`, + ); + + const env = { + ...process.env, + DROPCAP_ROOT: root, + DROPCAP_RUN: run, + CCDB: NodePath.join(root, "cc.db"), + PATH: `${bin}:${process.env.PATH}`, + }; + + const dropcap = (command: string, extra: Record = {}) => + NodeChildProcess.spawnSync(NodePath.join(bin, "sh"), [script, command], { + env: { ...env, ...extra }, + }).status === 0; + + cleanup = () => { + dropcap("shutdown"); + NodeFS.rmSync(root, { recursive: true, force: true }); + }; + + return { + root, + ext, + run, + dropcap, + // GET answers with body from now on. + respond: (url: string, body: string) => NodeFS.writeFileSync(key(url), body), + // Calls to block until path exists. + hold: (url: string, path: string) => NodeFS.writeFileSync(`${key(url)}.hold`, path), + awaitPass: () => NodeFS.readFileSync(NodePath.join(root, "pass"), "utf8"), + curlLog: () => + NodeFS.readFileSync(NodePath.join(root, "curl.log"), "utf8").trimEnd().split("\n"), + installTailscale: () => { + const ts = NodePath.join(ext, "tailscale"); + + NodeFS.mkdirSync(ts); + // Serves a unix socket until TERM. `up` logs in with a non-empty auth-key file, `status` + // succeeds once logged in, and `file get` waits until tailscaled goes away. + executable( + NodePath.join(ts, "tailscaled"), + `#!/bin/sh +for a; do case "$a" in --socket=*) sock=\${a#--socket=} ;; esac; done +python3 -c 'import socket, sys, time; socket.socket(socket.AF_UNIX).bind(sys.argv[1]); time.sleep(600)' "$sock" & +child=$! +trap 'kill $child; rm -f "$sock"; exit 0' TERM +wait $child +`, + ); + executable( + NodePath.join(ts, "tailscale"), + `#!/bin/sh +for a; do case "$a" in --socket=*) sock=\${a#--socket=} ;; esac; done +shift +echo "$*" >> "${root}/tailscale.log" +case "$1" in + up) + for a; do + case "$a" in --auth-key=file:*) [ -s "\${a#--auth-key=file:}" ] && : > "${root}/logged-in" ;; esac + done + ;; + status) [ -e "${root}/logged-in" ] ;; + ip) echo 100.64.0.1 ;; + file) while [ -S "$sock" ]; do usleep 50000; done; exit 1 ;; +esac +`, + ); + + return ts; + }, + tailscaleLog: () => NodeFS.readFileSync(NodePath.join(root, "tailscale.log"), "utf8"), + }; +}; + +/** Live processes running this checkout's dropcap.sh with the given subcommand. */ +const processes = (command: string) => + NodeFS.readdirSync("/proc") + .filter((pid) => /^\d+$/.test(pid)) + .filter((pid) => { + try { + const args = NodeFS.readFileSync(`/proc/${pid}/cmdline`, "utf8").split("\0"); + + return args.includes(script) && args.includes(command); + } catch { + return false; + } + }); + +const alive = (pidFile: string) => { + try { + return NodeFS.existsSync(`/proc/${NodeFS.readFileSync(pidFile, "utf8").trim()}`); + } catch { + return false; + } +}; + +afterEach(() => { + cleanup?.(); + cleanup = undefined; +}); + +// Types match a real PW3 on 5.16.2.1.1, which indexes KUAL, hotfix runners and its own text files as PDOC. +it("reports only books in documents/", () => { + const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "dropcap-db-")); + const ccdb = NodePath.join(dir, "cc.db"); + const db = new NodeSqlite.DatabaseSync(ccdb); + + cleanup = () => NodeFS.rmSync(dir, { recursive: true, force: true }); + db.exec("create table Entries (p_location text, p_cdeType text, p_titles_0_nominal text)"); + + const insert = db.prepare("insert into Entries values (?, ?, ?)"); + + for (const row of [ + ["/mnt/us/documents/Dune.azw3", "EBOK", "Dune"], + ["/mnt/us/documents/old/Emma.azw3", "PDOC", "Emma\tAusten"], + ["/mnt/us/documents/Notes.PDF", "PDOC", "Notes"], + ["/mnt/us/documents/Meditations.txt", "PDOC", "Meditations"], + ["/mnt/us/documents/KUAL.kual", "PDOC", "KUAL"], + ["/mnt/us/documents/Run Hotfix.run_hotfix", "PDOC", "Run Hotfix"], + ["/mnt/us/documents/My Clippings.txt", "PDOC", "Your Clippings"], + ["/mnt/us/documents/KPPMainAppV2_crash_Oct_27.txt", "PDOC", "KPPMainAppV2_crash_Oct_27"], + ["/mnt/us/documents/Untyped.azw3", null, "Untyped"], + ["/mnt/us/system/Elsewhere.azw3", "EBOK", "Elsewhere"], + ]) { + insert.run(...row); + } + + db.close(); + + const books = NodeChildProcess.execFileSync(busybox, ["sh", script, "books"], { + env: { ...process.env, DROPCAP_ROOT: "/mnt/us", DROPCAP_RUN: dir, CCDB: ccdb }, + encoding: "utf8", + }); + + expect(books.trimEnd().split("\n")).toEqual([ + "/mnt/us/documents/Dune.azw3\tDune", + "/mnt/us/documents/Meditations.txt\tMeditations", + "/mnt/us/documents/Notes.PDF\tNotes", + "/mnt/us/documents/old/Emma.azw3\tEmma Austen", + ]); +}); + +// The boot job runs supervise every minute: it must start a stopped loop and leave a running one alone. +it("supervise keeps exactly one delivery loop running", () => { + const { run, dropcap } = kindle(); + + expect(dropcap("running")).toBe(false); + expect(dropcap("supervise")).toBe(true); + expect(dropcap("running")).toBe(true); + + const pid = NodeFS.readFileSync(NodePath.join(run, "loop.pid"), "utf8"); + + expect(dropcap("supervise")).toBe(true); + expect(NodeFS.readFileSync(NodePath.join(run, "loop.pid"), "utf8")).toBe(pid); + expect(processes("loop")).toHaveLength(1); +}); + +it("restarting leaves one delivery loop, and stop leaves none", () => { + const { dropcap, awaitPass } = kindle(); + + expect(dropcap("start")).toBe(true); + awaitPass(); + expect(dropcap("start")).toBe(true); + expect(dropcap("start")).toBe(true); + expect(processes("loop")).toHaveLength(1); + expect(dropcap("stop")).toBe(true); + expect(processes("loop")).toHaveLength(0); + expect(dropcap("running")).toBe(false); +}); + +// A shell only runs its TERM trap once the whole download batch returns, so stop must end the batch. +it("stopping mid-download finishes that item and skips the rest of the queue", () => { + const { root, run, dropcap, respond, hold, curlLog } = kindle(); + const worker = "https://mailbox.invalid"; + + respond(`${worker}/items/`, "001\tone.azw3\n002\ttwo.azw3\n"); + respond(`${worker}/items/001`, "one"); + respond(`${worker}/items/002`, "two"); + hold(`${worker}/items/001`, NodePath.join(run, "stopping")); + + expect(dropcap("start")).toBe(true); + expect(dropcap("stop")).toBe(true); + + expect(processes("loop")).toHaveLength(0); + expect(NodeFS.readFileSync(NodePath.join(root, "documents", "one.azw3"), "utf8")).toBe("one"); + expect(NodeFS.existsSync(NodePath.join(root, "documents", "two.azw3"))).toBe(false); + expect(curlLog()).not.toContain(`GET ${worker}/items/002`); +}); + +it("runs the app's commands, deleting only inside documents/, and settles each one", () => { + const { root, dropcap, respond, awaitPass, curlLog } = kindle(); + const docs = (path: string) => NodePath.join(root, "documents", path); + const outside = NodePath.join(root, "outside.azw3"); + + NodeFS.mkdirSync(docs("a.b/book.sdr"), { recursive: true }); + NodeFS.writeFileSync(docs("a.b/book"), ""); + NodeFS.mkdirSync(docs("a.sdr")); + NodeFS.writeFileSync(docs("Dune.azw3"), ""); + NodeFS.mkdirSync(docs("Dune.sdr")); + NodeFS.writeFileSync(outside, ""); + respond( + "https://mailbox.invalid/commands/", + [ + `001\tdelete\t${docs("a.b/book")}`, + `002\tdelete\t${docs("Dune.azw3")}`, + `003\tdelete\t${outside}`, + `004\tdelete\t${root}/documents/../outside.azw3`, + `005\trescan`, + `006\treboot`, + ].join("\n"), + ); + + expect(dropcap("start")).toBe(true); + awaitPass(); + + expect(NodeFS.existsSync(docs("a.b/book"))).toBe(false); + expect(NodeFS.existsSync(docs("a.b/book.sdr"))).toBe(false); + expect(NodeFS.existsSync(docs("a.sdr"))).toBe(true); + expect(NodeFS.existsSync(docs("Dune.azw3"))).toBe(false); + expect(NodeFS.existsSync(docs("Dune.sdr"))).toBe(false); + expect(NodeFS.existsSync(outside)).toBe(true); + expect( + curlLog() + .filter((line) => line.startsWith("PUT https://mailbox.invalid/commands/")) + .map((line) => line.replace("PUT https://mailbox.invalid/commands/", "")), + ).toEqual([ + "001 outcome=ok", + "002 outcome=ok", + `003 outcome=failed message=not in documents/: ${outside}`, + `004 outcome=failed message=refusing ${root}/documents/../outside.azw3`, + "005 outcome=ok", + "006 outcome=failed message=unknown command reboot", + ]); +}); + +it("starts Tailscale with the auth key from its file, then stops it and the receiver", () => { + const { run, dropcap, installTailscale, tailscaleLog } = kindle(); + const authKey = NodePath.join(installTailscale(), "auth.key"); + + NodeFS.writeFileSync(authKey, "tskey-test"); + + expect(dropcap("ssh-start")).toBe(true); + expect(tailscaleLog()).toContain(`up --ssh --hostname=kindle --auth-key=file:${authKey}`); + expect(NodeFS.readFileSync(authKey, "utf8")).toBe(""); + expect(alive(NodePath.join(run, "tailscaled.pid"))).toBe(true); + expect(processes("receive")).toHaveLength(1); + + expect(dropcap("ssh-stop")).toBe(true); + expect(alive(NodePath.join(run, "tailscaled.pid"))).toBe(false); + expect(processes("receive")).toHaveLength(0); +}); + +// At boot nobody can see a login link, so a missing login must park Tailscale instead of retrying. +it("a boot-time Tailscale start with no login leaves it stopped until a manual start", () => { + const { run, dropcap, installTailscale } = kindle(); + const ts = installTailscale(); + + expect(dropcap("ssh-start", { QUIET: "1" })).toBe(false); + expect(NodeFS.existsSync(NodePath.join(ts, "needs-login"))).toBe(true); + expect(alive(NodePath.join(run, "tailscaled.pid"))).toBe(false); + expect(processes("receive")).toHaveLength(0); + + expect(dropcap("supervise", { QUIET: "1" })).toBe(true); + expect(dropcap("running")).toBe(true); + expect(NodeFS.existsSync(NodePath.join(run, "tailscaled.pid"))).toBe(false); +}); + +it("passes ShellCheck as busybox sh", () => { + const files = [ + "dropcap.sh", + "lib/mailbox.sh", + "lib/tailscale.sh", + "lib/wifi.sh", + "lib/boot.sh", + "../kd", + ]; + + // Pinned and fetched on demand into the pnpm store, so the linter adds nothing to the lockfile. + const result = NodeChildProcess.spawnSync( + "pnpm", + ["dlx", "shellcheck@4.1.0", "-s", "busybox", "-x", ...files], + { cwd: here, encoding: "utf8" }, + ); + + // The npm wrapper prints a note while it downloads the binary on first use, so match findings only. + expect(result.stdout.match(/SC\d{4}.*/g) ?? []).toEqual([]); + expect(result.status).toBe(0); +}); diff --git a/kindle/dropcap/lib/boot.sh b/kindle/dropcap/lib/boot.sh new file mode 100644 index 0000000..53191d0 --- /dev/null +++ b/kindle/dropcap/lib/boot.sh @@ -0,0 +1,53 @@ +# The upstart job that keeps Dropcap (and Tailscale, when installed) running across reboots and USB +# sessions. Sourced by dropcap.sh. + +JOB=${DROPCAP_JOB:-/etc/upstart/dropcap.conf} + +# One tick of the boot job: start whatever is not running. Always succeeds, because the job's body runs +# under sh -e and a failure would end the job until wifid restarts. +supervise() { + running || start || log "supervise: delivery did not start" + if ssh_installed && [ ! -e "$NEEDS_LOGIN" ] && ! ssh_running; then + ssh_start || log "supervise: Tailscale did not start" + fi + return 0 +} + +shutdown() { + stop + ssh_installed && ssh_stop + return 0 +} + +# The job lives on the root filesystem because the userstore, and this script, vanish while USB storage +# is mounted. Its loop brings everything back within a minute of the userstore returning. +install_boot() { + mntroot rw >/dev/null 2>&1 + if ! cat > "$JOB" </dev/null 2>&1 + say "Dropcap will start on boot" +} + +uninstall_boot() { + mntroot rw >/dev/null 2>&1 + rm -f "$JOB" || { say "Could not remove $JOB"; return 1; } + mntroot ro >/dev/null 2>&1 + say "Dropcap boot start removed" +} diff --git a/kindle/dropcap/lib/mailbox.sh b/kindle/dropcap/lib/mailbox.sh new file mode 100644 index 0000000..443fa9b --- /dev/null +++ b/kindle/dropcap/lib/mailbox.sh @@ -0,0 +1,238 @@ +# Book delivery: on every wake, install queued items from the Worker, run the app's commands, report the +# device and upload the log. Sourced by dropcap.sh; the Worker contract is apps/worker/src/Api.ts. + +DOCS=$ROOT/documents +THUMBS=$ROOT/system/thumbnails +COVERS=$ROOT/amazon-cover-bug +CCDB=${CCDB:-/var/local/cc.db} +LOOP_LOCK=$RUN/loop.lock +LOOP_PID=$RUN/loop.pid +# stop creates this, and pull_once checks it between items: a shell runs its TERM trap only once the +# foreground command (here the whole download batch) returns, so a restart would otherwise wait it out. +STOPPING=$RUN/stopping +AUTH=$RUN/auth +TAB=$(printf '\t') + +# The Worker's root URL from mailbox.url. Older installs wrote it with a trailing /items. +worker_url() { + local url + url=$(tr -d '\r\n' 2>/dev/null < "$DIR/mailbox.url") || return 1 + url=${url%/} + url=${url%/items} + case "$url" in https://*) echo "$url" ;; *) return 1 ;; esac +} + +# curl against the Worker. The bearer header goes through a root-only file, so the token never +# appears in `ps` output. Usage: api +api() { + local timeout=$1 token + shift + token=$(tr -d '\r\n' 2>/dev/null < "$DIR/mailbox.token") || return 1 + [ -n "$token" ] || return 1 + (umask 077 && printf 'Authorization: Bearer %s\n' "$token" > "$AUTH") || return 1 + curl -sf --max-time "$timeout" -H "@$AUTH" "$@" +} + +# Upload the end of the log as reports/dropcap.log, so a wake can be debugged without SSH or USB. +report_log() { + local w + w=$(worker_url) || return 0 + tail -n 200 "$LOG" 2>/dev/null | api 20 -X PUT --data-binary @- "$w/reports/dropcap.log" >/dev/null +} + +# Run each run-once.d/*.sh once, renamed to .ran first. One copied in over USB runs on the next wake, +# which reaches a Kindle whose SSH is broken. Its output goes to the log, which report_log uploads. +run_once() { + local f + for f in "$DIR"/run-once.d/*.sh; do + [ -e "$f" ] || continue + mv "$f" "$f.ran" || continue + log "run-once ${f##*/}" + nohup sh "$f.ran" >> "$LOG" 2>&1 9>&- & + done +} + +rescan() { + lipc-set-prop com.lab126.scanner doFullScan 1 >> "$LOG" 2>&1 +} + +# EBOK books need their thumbnail in system/thumbnails/ for lock-screen covers, and the firmware can +# replace it with Amazon's placeholder. amazon-cover-bug/ keeps our copies; put back any that differ. +guard_covers() { + local f t + # While USB storage is mounted the userstore is gone, and mkdir would litter the root filesystem. + [ -d "$DOCS" ] || return 0 + mkdir -p "$COVERS" "$THUMBS" || return 1 + for f in "$COVERS"/thumbnail_*_portrait.jpg; do + [ -e "$f" ] || continue + t=$THUMBS/${f##*/} + cmp -s "$f" "$t" || { cp "$f" "$t" && log "restored cover ${f##*/}"; } + done +} + +# Fetch everything queued. Covers go first and are installed at once: the firmware only fetches +# Amazon's placeholder for an EBOK book that has no thumbnail yet. Fails if the Worker is unreachable. +pull_once() { + local w list got + w=$(worker_url) || return 0 + list=$(api 20 "$w/items/") || return 1 + got=$(printf '%s\n' "$list" | while IFS=$TAB read -r id name; do + [ -n "$id" ] || continue + [ -e "$STOPPING" ] && break + name=$(printf '%s' "$name" | tr '/' '_') + case "$name" in + thumbnail_*_portrait.jpg) dest=$COVERS/$name ;; + *) [ -e "$DOCS/$name" ] && name="$(date +%s) $name"; dest=$DOCS/$name ;; + esac + tmp=${dest%/*}/.$name.part + if api 300 -o "$tmp" "$w/items/$id" && mv "$tmp" "$dest"; then + case "$name" in thumbnail_*) guard_covers ;; esac + api 20 -X DELETE "$w/items/$id" >/dev/null || log "could not remove $name from the mailbox" + log "received $name" + echo "$dest" + else + rm -f "$tmp" + log "download failed: $name" + fi + done) + [ -n "$got" ] && rescan + guard_covers + return 0 +} + +is_count() { + case "$1" in '' | *[!0-9]*) return 1 ;; esac +} + +# Remove a book, its reading position (.sdr) and its covers. The Worker only queues paths inside +# documents/, and this checks again. A book that is already gone counts as deleted. +delete_book() { + local path=$1 base sdr key + case "$path" in "$DOCS"/?*) ;; *) echo "not in documents/: $path"; return 1 ;; esac + case "$path/" in */../* | */./* | *//*) echo "refusing $path"; return 1 ;; esac + base=${path##*/} + case "$base" in ?*.*) sdr=${path%.*}.sdr ;; *) sdr=$path.sdr ;; esac + key=$(sqlite3 "$CCDB" "select p_cdeKey from Entries where p_location = '$(printf '%s' "$path" | sed "s/'/''/g")'" /dev/null) + rm -f -- "$path" || return 1 + rm -rf -- "$sdr" + case "$key" in + '' | */* | *..*) ;; + *) rm -f "$COVERS/thumbnail_${key}_EBOK_portrait.jpg" "$THUMBS/thumbnail_${key}_EBOK_portrait.jpg" ;; + esac + return 0 +} + +# Run the app's queued commands, oldest first, and settle each with the Worker. A lost settle runs the +# command again on the next wake, so every verb must be safe to repeat. +run_commands() { + local w cmds scan='' id verb arg msg ok + w=$(worker_url) || return 0 + cmds=$(api 20 "$w/commands/") || return 0 + while IFS=$TAB read -r id verb arg; do + [ -n "$id" ] || continue + ok=1 + case "$verb" in + delete) msg=$(delete_book "$arg" 2>&1) || ok='' ;; + rescan) msg='' ;; + *) msg="unknown command $verb"; ok='' ;; + esac + if [ -n "$ok" ]; then + scan=1 + log "ran $verb $arg" + api 20 -X PUT --data-urlencode outcome=ok "$w/commands/$id" >/dev/null || log "could not settle $id" + else + log "failed $verb: $msg" + api 20 -X PUT --data-urlencode outcome=failed --data-urlencode "message=$msg" "$w/commands/$id" >/dev/null || + log "could not settle $id" + fi + done <\t" line per book in documents/, from the library DB. The firmware indexes KUAL, +# hotfix runners, My Clippings.txt and its *_crash_*.txt dumps as PDOC too, so books are matched by +# extension and those two .txt files are left out. A tab or newline in a title would split the line. +books() { + sqlite3 -separator "$TAB" "$CCDB" "select p_location, replace(replace(coalesce(p_titles_0_nominal, ''), char(9), ' '), char(10), ' ') from Entries where p_cdeType in ('EBOK', 'PDOC') and p_location like '$DOCS/%' and (p_location like '%.azw3' or p_location like '%.azw' or p_location like '%.mobi' or p_location like '%.kfx' or p_location like '%.pdf' or p_location like '%.epub' or p_location like '%.txt') and p_location != '$DOCS/My Clippings.txt' and p_location not like '%\_crash\_%.txt' escape '\' and instr(p_location, char(9)) = 0 and instr(p_location, char(10)) = 0 order by p_location" </dev/null 2>/dev/null +} + +# Tell the Worker the battery, free space, firmware and library for the app's Kindle screen. A value +# that can't be read is left out. Runs after run_commands, so the library already shows deletions. +report_device() { + local w v book + w=$(worker_url) || return 0 + set -- + v=$(lipc-get-prop com.lab126.powerd battLevel 2>/dev/null) && is_count "$v" && set -- "$@" --data-urlencode "battery=$v" + v=$(lipc-get-prop com.lab126.powerd isCharging 2>/dev/null) && case "$v" in 0 | 1) set -- "$@" --data-urlencode "charging=$v" ;; esac + v=$(df -kP "$ROOT" 2>/dev/null | awk 'NR == 2 { print $4 }') && is_count "$v" && set -- "$@" --data-urlencode "freeKb=$v" + v=$(df -kP "$ROOT" 2>/dev/null | awk 'NR == 2 { print $2 }') && is_count "$v" && set -- "$@" --data-urlencode "totalKb=$v" + v=$(grep -o '[0-9][0-9.]*[0-9]' /etc/prettyversion.txt 2>/dev/null | head -1) && [ -n "$v" ] && set -- "$@" --data-urlencode "firmware=$v" + while IFS= read -r book; do + [ -n "$book" ] && set -- "$@" --data-urlencode "books=$book" + done <<EOF +$(books) +EOF + api 20 -X PUT "$@" "$w/device" >/dev/null || log "device report rejected" +} + +# True while a delivery loop holds the lock. Probing takes the lock for an instant, which a starting +# loop waits out. +running() { + ! flock -n "$LOOP_LOCK" true 2>/dev/null +} + +# The delivery loop: check the mailbox on every wake (Wi-Fi needs a few seconds to come back, so retry +# for a minute), then every 10 minutes while awake. Frozen, and free, while the Kindle sleeps. The lock +# on fd 9 makes a second loop exit; long-lived children close fd 9 so they never hold it. +loop() { + local i wait_pid= + exec 9> "$LOOP_LOCK" || exit 1 + lock_within 5 9 || { log "a delivery loop is already running"; exit 0; } + rm -f "$STOPPING" + echo $$ > "$LOOP_PID" + trap '[ -n "$wait_pid" ] && kill "$wait_pid" 2>/dev/null; exit 0' TERM INT + while :; do + run_once + guard_covers + i=0 + until pull_once; do + i=$((i + 1)) + [ $i -ge 12 ] && break + sleep 5 + done + [ $i -lt 12 ] && { run_commands; report_device; report_log; } + # Exits non-zero on its own timeout too; the short sleep only guards against a failing lipc spinning. + lipc-wait-event -s 600 com.lab126.powerd outOfScreenSaver,wakeupFromSuspend >/dev/null 2>&1 9>&- & + wait_pid=$! + wait "$wait_pid" || sleep 5 + wait_pid= + done +} + +# Start the delivery loop, replacing a running one, and return once it holds the lock. +start() { + local i=0 + stop || { say "Dropcap is busy downloading, try again"; return 1; } + tail -n 500 "$LOG" > "$LOG.tmp" 2>/dev/null && mv "$LOG.tmp" "$LOG" + nohup sh "$SELF" loop >> "$LOG" 2>&1 & + until running; do + i=$((i + 1)) + [ $i -gt 50 ] && { say "Dropcap did not start, see dropcap.log"; return 1; } + usleep 100000 + done + say "Dropcap started" +} + +# Stop the delivery loop and wait for it to let go of the lock. A loop busy downloading finishes the +# current item first (curl allows it 300 seconds), so this waits up to 330. +stop() { + local pid + running || return 0 + : > "$STOPPING" + pid=$(cat "$LOOP_PID" 2>/dev/null) + is_count "$pid" && kill "$pid" 2>/dev/null + lock_within 330 "$LOOP_LOCK" true +} diff --git a/kindle/dropcap/lib/tailscale.sh b/kindle/dropcap/lib/tailscale.sh new file mode 100644 index 0000000..637a65e --- /dev/null +++ b/kindle/dropcap/lib/tailscale.sh @@ -0,0 +1,154 @@ +# Optional Tailscale for SSH and Taildrop, from the static arm binaries in tailscale/ (not in git). +# Delivery never depends on it: restarting Tailscale ends SSH sessions but leaves the loop alone. +# Sourced by dropcap.sh. + +TS_DIR=$DIR/tailscale +TS_LOG=$TS_DIR/tailscaled.log +TS_SOCK=$RUN/tailscaled.sock +TS_HOSTNAME=${DROPCAP_TS_HOSTNAME:-kindle} +TS_PID=$RUN/tailscaled.pid +SSH_LOCK=$RUN/ssh.lock +RECEIVE_LOCK=$RUN/receive.lock +RECEIVE_PID=$RUN/receive.pid +# Written when a boot-time start finds no login. The boot job then leaves Tailscale alone until a start +# from KUAL, which can show the login link, clears it. +NEEDS_LOGIN=$TS_DIR/needs-login + +# The tailscale CLI on our socket. `timeout` and `nohup` can't run a function, so they call +# "$TS_DIR/tailscale" --socket="$TS_SOCK" directly. +ts() { + "$TS_DIR/tailscale" --socket="$TS_SOCK" "$@" +} + +ssh_installed() { + [ -x "$TS_DIR/tailscaled" ] && [ -x "$TS_DIR/tailscale" ] +} + +receiving() { + ! flock -n "$RECEIVE_LOCK" true 2>/dev/null +} + +# The tailscaled we started, by its pidfile; never by name, which would match other tailscaleds. +tailscaled_pid() { + local pid + pid=$(cat "$TS_PID" 2>/dev/null) + is_count "$pid" && grep -q tailscaled "/proc/$pid/cmdline" 2>/dev/null && echo "$pid" +} + +ssh_running() { + tailscaled_pid >/dev/null && receiving +} + +ssh_stop() { + local pid i=0 + pid=$(cat "$RECEIVE_PID" 2>/dev/null) + receiving && is_count "$pid" && kill "$pid" 2>/dev/null + if pid=$(tailscaled_pid); then + kill "$pid" 2>/dev/null + while [ -d "/proc/$pid" ] && [ $i -lt 10 ]; do + sleep 1 + i=$((i + 1)) + done + [ -d "/proc/$pid" ] && kill -9 "$pid" 2>/dev/null + fi + rm -f "$TS_SOCK" "$TS_PID" +} + +# Show the approval link on screen and wait up to 5 minutes for it. Only from KUAL: the boot job is +# QUIET and nobody would see the link. +ssh_login() { + local url i=0 + nohup timeout 300 "$TS_DIR/tailscale" --socket="$TS_SOCK" up --ssh --hostname="$TS_HOSTNAME" --force-reauth \ + > "$TS_DIR/login.txt" 2>&1 7>&- & + until url=$(grep -o 'https://login.tailscale.com/[^ ]*' "$TS_DIR/login.txt" | head -1) && [ -n "$url" ]; do + i=$((i + 1)) + [ $i -gt 30 ] && { say "No login link, see tailscale/tailscaled.log"; return 1; } + sleep 1 + done + say "Open on your phone to approve:" + eips 0 24 "$url" >/dev/null 2>&1 + i=0 + until ts status >/dev/null 2>&1; do + i=$((i + 1)) + [ $i -gt 300 ] && { say "Login not approved in time, start Tailscale again"; return 1; } + sleep 1 + done + eips 0 24 "$(printf '%-50s' '')" >/dev/null 2>&1 +} + +# Start tailscaled and join the tailnet with tailscale/auth.key if present (wiped once used), else the +# saved login, else an on-screen login link. Leaves nothing running when it fails. The lock on fd 7 +# keeps a boot-job tick from restarting a start that is still in progress. +ssh_start() { + local ok + ssh_installed || { say "Tailscale is not installed in $TS_DIR"; return 1; } + exec 7> "$SSH_LOCK" || return 1 + if ! flock -n 7; then + exec 7>&- + log "Tailscale is already starting" + return 1 + fi + ssh_start_locked + ok=$? + exec 7>&- + return $ok +} + +ssh_start_locked() { + local i=0 + ssh_stop + mkdir -p "$TS_DIR/state" || return 1 + : > "$TS_LOG" + say "Starting Tailscale..." + nohup "$TS_DIR/tailscaled" --statedir="$TS_DIR/state" --socket="$TS_SOCK" -tun userspace-networking \ + >> "$TS_LOG" 2>&1 7>&- & + echo $! > "$TS_PID" + until [ -S "$TS_SOCK" ]; do + i=$((i + 1)) + [ $i -gt 30 ] && { say "tailscaled did not start, see tailscale/tailscaled.log"; ssh_stop; return 1; } + sleep 1 + done + if [ -s "$TS_DIR/auth.key" ]; then + if timeout 60 "$TS_DIR/tailscale" --socket="$TS_SOCK" up --ssh --hostname="$TS_HOSTNAME" \ + --auth-key="file:$TS_DIR/auth.key" >> "$TS_LOG" 2>&1 7>&-; then + : > "$TS_DIR/auth.key" + else + say "Auth key rejected" + fi + else + timeout 15 "$TS_DIR/tailscale" --socket="$TS_SOCK" up --ssh --hostname="$TS_HOSTNAME" >> "$TS_LOG" 2>&1 7>&- + fi + if ! ts status >/dev/null 2>&1; then + if [ -n "${QUIET:-}" ]; then + : > "$NEEDS_LOGIN" + log "Tailscale needs a login: KUAL > Dropcap > Start Tailscale (dropcap.sh ssh-start)" + ssh_stop + return 1 + fi + ssh_login || { ssh_stop; return 1; } + fi + rm -f "$NEEDS_LOGIN" + nohup sh "$SELF" receive >/dev/null 2>&1 7>&- & + say "Tailscale up: $(ts ip -4 2>/dev/null)" +} + +ssh_status() { + ssh_installed || { say "Tailscale is not installed"; return 1; } + say "$(ts status --peers=false 2>&1 | head -1)" +} + +# Taildrop receiver: move files sent to the Kindle into documents/ and rescan. The lock on fd 8 makes a +# second receiver exit. +receive() { + exec 8> "$RECEIVE_LOCK" || exit 1 + lock_within 5 8 || exit 0 + echo $$ > "$RECEIVE_PID" + while :; do + if ts file get --wait --conflict=rename "$DOCS/" >> "$TS_LOG" 2>&1 8>&-; then + log "received a Taildrop file" + rescan + else + sleep 15 8>&- + fi + done +} diff --git a/kindle/dropcap/lib/wifi.sh b/kindle/dropcap/lib/wifi.sh new file mode 100644 index 0000000..6236e06 --- /dev/null +++ b/kindle/dropcap/lib/wifi.sh @@ -0,0 +1,85 @@ +# Wi-Fi recovery tools, run from KUAL. Sourced by dropcap.sh. + +WIFI_CONF=$DIR/network.conf +WIFI_DIAG=$DIR/wifi-diag.txt + +# Save network.conf (ESSID= and PSK=, the PSK as the 64-hex key from wpa_passphrase, never the plain +# password) as a Wi-Fi profile, connect, then start Tailscale. network.conf is deleted once connected. +# Refuses while OTA updates are still possible, so going online can't wipe the jailbreak. +wifi_join() { + local essid psk i=0 + if [ -e /usr/bin/otaupd ] || [ -e /usr/bin/otav3 ]; then + say "Block OTA first: KUAL > Rename OTA Binaries" + return 1 + fi + [ -s "$WIFI_CONF" ] || { say "No network.conf in $DIR"; return 1; } + essid=$(sed -n 's/^ESSID=//p' "$WIFI_CONF" | head -1) + psk=$(sed -n 's/^PSK=//p' "$WIFI_CONF" | head -1) + [ -n "$essid" ] && [ -n "$psk" ] || { say "network.conf needs ESSID= and PSK="; return 1; } + lipc-set-prop com.lab126.cmd wirelessEnable 1 + lipc-set-prop com.lab126.wifid enable 1 + sleep 3 + printf '{essid="%s", smethod="wpa2", secured="yes", psk="%s"}\n' "$essid" "$psk" | + lipc-hash-prop com.lab126.wifid createProfile >> "$LOG" 2>&1 + lipc-set-prop com.lab126.wifid cmConnect "$essid" >> "$LOG" 2>&1 + say "Connecting to $essid..." + until [ "$(lipc-get-prop com.lab126.wifid cmState)" = CONNECTED ]; do + i=$((i + 1)) + [ $i -gt 45 ] && { say "Wi-Fi failed: $(lipc-get-prop com.lab126.wifid cmState)"; return 1; } + sleep 1 + done + rm -f "$WIFI_CONF" + say "Wi-Fi connected" + if ssh_installed; then ssh_start; fi +} + +# Dump driver, supplicant and wifid state to wifi-diag.txt (about 30s), and upload it to the Worker as +# reports/wifi-diag.txt when it is reachable. +wifi_diag() { + local p w + say "Collecting Wi-Fi diagnostics..." + { + echo "== $(date)" + echo "== props (before)" + for p in cmState currentEssid enable profileCount signalStrength scanState; do + echo "$p=$(lipc-get-prop com.lab126.wifid "$p" 2>&1)" + done + echo "wirelessEnable=$(lipc-get-prop com.lab126.cmd wirelessEnable 2>&1)" + echo "== enabling wireless + scan" + lipc-set-prop com.lab126.cmd wirelessEnable 1 2>&1 + lipc-set-prop com.lab126.wifid enable 1 2>&1 + sleep 10 + lipc-set-prop com.lab126.wifid scan "" 2>&1 + sleep 15 + echo "== props (after)" + for p in cmState currentEssid enable profileCount scanState; do + echo "$p=$(lipc-get-prop com.lab126.wifid "$p" 2>&1)" + done + echo "== scanList" + echo "" | lipc-hash-prop com.lab126.wifid scanList 2>&1 + echo "== profileData" + echo "" | lipc-hash-prop com.lab126.wifid profileData 2>&1 | sed 's/psk *= *"[^"]*"/psk="<redacted>"/' + echo "== upstart" + initctl list 2>&1 | grep -iE "wifi|wpa|net" + echo "== processes" + # shellcheck disable=SC2009 # busybox pgrep can't print arguments, and this is a diagnostic dump. + ps -o pid,args 2>&1 | grep -iE "[w]pa|[w]ifi|[d]hcp" + echo "== modules" + lsmod 2>&1 + echo "== interfaces" + ifconfig -a 2>&1 + echo "== rfkill" + cat /sys/class/rfkill/*/name /sys/class/rfkill/*/state 2>&1 + echo "== dmesg" + dmesg 2>&1 | grep -iE "ath|wlan|wifi|sdio|mmc|firmware" | tail -60 + echo "== messages" + grep -aiE "wifid|wpa_supp|wlan|ath6|wifis|cmd\[" /var/log/messages 2>&1 | tail -150 + echo "== wpa log" + tail -80 /var/log/wpa_supplicant 2>&1 + } > "$WIFI_DIAG" 2>&1 + if w=$(worker_url) && api 20 -X PUT --data-binary "@$WIFI_DIAG" "$w/reports/wifi-diag.txt" >/dev/null; then + say "Diagnostics uploaded as reports/wifi-diag.txt" + else + say "Diagnostics saved to wifi-diag.txt. Plug into the computer." + fi +} diff --git a/kindle/dropcap/menu.json b/kindle/dropcap/menu.json new file mode 100644 index 0000000..be891e1 --- /dev/null +++ b/kindle/dropcap/menu.json @@ -0,0 +1,73 @@ +{ + "items": [ + { + "name": "Dropcap", + "priority": 0, + "items": [ + { + "name": "Start", + "priority": 1, + "action": "/mnt/us/extensions/dropcap/dropcap.sh", + "params": "start", + "exitmenu": false + }, + { + "name": "Stop", + "priority": 2, + "action": "/mnt/us/extensions/dropcap/dropcap.sh", + "params": "stop", + "exitmenu": false + }, + { + "name": "Start Tailscale", + "priority": 3, + "action": "/mnt/us/extensions/dropcap/dropcap.sh", + "params": "ssh-start", + "exitmenu": false + }, + { + "name": "Tailscale status", + "priority": 4, + "action": "/mnt/us/extensions/dropcap/dropcap.sh", + "params": "ssh-status", + "exitmenu": false + }, + { + "name": "Stop Tailscale", + "priority": 5, + "action": "/mnt/us/extensions/dropcap/dropcap.sh", + "params": "ssh-stop", + "exitmenu": false + }, + { + "name": "Join Wi-Fi from network.conf", + "priority": 6, + "action": "/mnt/us/extensions/dropcap/dropcap.sh", + "params": "wifi-join", + "exitmenu": false + }, + { + "name": "Wi-Fi diagnostics", + "priority": 7, + "action": "/mnt/us/extensions/dropcap/dropcap.sh", + "params": "wifi-diag", + "exitmenu": false + }, + { + "name": "Start on boot", + "priority": 8, + "action": "/mnt/us/extensions/dropcap/dropcap.sh", + "params": "install-boot", + "exitmenu": false + }, + { + "name": "Don't start on boot", + "priority": 9, + "action": "/mnt/us/extensions/dropcap/dropcap.sh", + "params": "uninstall-boot", + "exitmenu": false + } + ] + } + ] +} diff --git a/kindle/kd b/kindle/kd new file mode 100755 index 0000000..3af62c9 --- /dev/null +++ b/kindle/kd @@ -0,0 +1,63 @@ +#!/bin/sh +# Laptop helper for the Kindle. Reads tokens from ~/.config/kindle-mailbox/secrets.env, never prints them. +# Usage: kindle/kd status the Kindle's last check-in, device report and commands, from the Worker +# kindle/kd logs the end of dropcap.log, uploaded on every wake +# kindle/kd rescan queue a rescan; proves the command path once it settles `ok` +# kindle/kd ssh [command] root shell over Tailscale SSH (the Kindle must be awake) +# kindle/kd deploy push kindle/dropcap over SSH, or over USB when the Kindle is mounted +set -eu +HERE=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd) +WORKER=${KD_WORKER:-https://kindle-mailbox.listlessbird.workers.dev} +SECRETS=$HOME/.config/kindle-mailbox/secrets.env +MOUNT=/media/$USER/Kindle +EXT=/mnt/us/extensions/dropcap +# What the repo owns. Binaries, tokens, Tailscale state and logs stay on the device. +FILES="dropcap.sh config.xml menu.json lib/mailbox.sh lib/tailscale.sh lib/wifi.sh lib/boot.sh" + +# curl the Worker as the app. The token goes to curl on stdin, so it never appears in `ps` output. +app() { + token=$(sed -n 's/^APP_TOKEN=//p' "$SECRETS") + printf 'header = "Authorization: Bearer %s"\n' "$token" | curl -sf --max-time 60 -K - "$@" +} + +kssh() { + ssh -o BatchMode=yes -o ConnectTimeout=20 root@kindle "$@" +} + +case "${1:-}" in + status) + app "$WORKER/status" | jq '{checkedInAt, device: (.device | if . then del(.books) + {books: [.books[].title]} else . end), commands}' + ;; + logs) app "$WORKER/reports/dropcap.log" ;; + rescan) app -X POST -H 'content-type: application/json' -d '{"command":{"_tag":"Rescan"}}' "$WORKER/commands" && echo ;; + ssh) + shift + kssh "$@" + ;; + deploy) + # The Kindle's shell is busybox sh. + for f in $FILES; do + case "$f" in *.sh) busybox sh -n "$HERE/dropcap/$f" ;; esac + done + if [ -d "$MOUNT/extensions" ]; then + for f in $FILES; do + mkdir -p "$MOUNT/extensions/dropcap/${f%/*}" && cp "$HERE/dropcap/$f" "$MOUNT/extensions/dropcap/$f" + done + mkdir -p "$MOUNT/extensions/dropcap/run-once.d" + echo "$EXT/dropcap.sh start" > "$MOUNT/extensions/dropcap/run-once.d/restart.sh" + sync + echo "copied over USB; Dropcap restarts on the first wake after: udisksctl unmount -b /dev/sda1 && udisksctl power-off -b /dev/sda" + else + for f in $FILES; do + kssh "mkdir -p $EXT/lib && cat > $EXT/$f.new && mv $EXT/$f.new $EXT/$f" < "$HERE/dropcap/$f" + done + kssh "chmod +x $EXT/dropcap.sh && $EXT/dropcap.sh start" + echo "pushed over SSH and restarted delivery. Tailscale picks up lib/tailscale.sh when it restarts:" + echo " kindle/kd ssh 'kill \$(cat /var/run/dropcap/tailscaled.pid)' # the boot job brings it back within a minute" + fi + ;; + *) + sed -n '3,7p' "$0" >&2 + exit 2 + ;; +esac diff --git a/vite.config.ts b/vite.config.ts index ec12baa..5b15de2 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -57,6 +57,8 @@ export default defineConfig({ extends: true, test: { name: "lint-rules", include: ["oxlint-plugin-kd/**/*.test.ts"] }, }, + // Runs the Kindle scripts under busybox sh with the sqlite3 CLI, as the device does. + { extends: true, test: { name: "kindle", include: ["kindle/**/*.test.ts"] } }, ] : undefined, },