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
81 changes: 81 additions & 0 deletions .agents/skills/kindle-device/SKILL.md
Original file line number Diff line number Diff line change
@@ -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 '<command>'` 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/<name>"`.
- 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 \"%<name>%\""'`.
- **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.
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
8 changes: 8 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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
5 changes: 3 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<pid>/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

Expand Down Expand Up @@ -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/<feature>` 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`).
Expand Down
81 changes: 81 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,84 @@
<img src="apps/mobile/assets/icon-production.png" width="64" height="64" alt="">

# 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://<your-worker>.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://<your-worker>.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
```
2 changes: 1 addition & 1 deletion apps/mobile/src/features/sending/book.ts
Original file line number Diff line number Diff line change
Expand Up @@ -359,7 +359,7 @@ export const formatOf = (name: string, mimeType: Option.Option<string>) =>
/** 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. */
Expand Down
10 changes: 5 additions & 5 deletions apps/worker/src/Api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 "<id>\t<name>\n" listing lines and writes <name> to disk.
// The Kindle's dropcap.sh parses "<id>\t<name>\n" listing lines and writes <name> to disk.
export const ItemName = Schema.String.check(Schema.isPattern(/^[^\t\n\r/]+$/)).pipe(
Schema.brand("ItemName"),
);
Expand Down Expand Up @@ -55,7 +55,7 @@ export class EitherAuth extends HttpApiMiddleware.Service<EitherAuth>()("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"));
Expand Down Expand Up @@ -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({
Expand Down Expand Up @@ -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 }),
Expand Down Expand Up @@ -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(
Expand Down
2 changes: 1 addition & 1 deletion apps/worker/src/Worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
2 changes: 1 addition & 1 deletion apps/worker/test/Mailbox.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Loading
Loading