|
| 1 | +## Context |
| 2 | + |
| 3 | +`mailbrus-server` already enforces a bearer token on `/api/*` when launched with |
| 4 | +`--auth <token>` (`api-origin-validation` spec). The frontend already *reads* a token |
| 5 | +from `window.__MAILBRUS_AUTH_TOKEN__` or `localStorage['mailbrus.authToken']` |
| 6 | +(`src/lib/api.ts:readInitialToken`) and propagates it to localStorage, IndexedDB, and the |
| 7 | +service worker (`setAuthToken`). What is missing is **token delivery**: |
| 8 | + |
| 9 | +- The desktop shell (`src-tauri/src/lib.rs`) spawns the sidecar without `--auth` and never |
| 10 | + sets the injected global. |
| 11 | +- The browser/PWA has no UI to enter a token, so a server run with `--auth` returns `401` |
| 12 | + for every request and the app appears dead. |
| 13 | + |
| 14 | +Two entry paths need different delivery, and both need recovery when a stored token no |
| 15 | +longer matches a restarted server. |
| 16 | + |
| 17 | +Constraints: |
| 18 | +- The Tauri window loads the server's HTTP URL (`http://127.0.0.1:1371`), not the |
| 19 | + `asset:` protocol — the SPA runs against real HTTP. |
| 20 | +- Tauri capabilities key on the window **label `"main"`** (`src-tauri/capabilities/*.json`) |
| 21 | + — the label must be preserved. |
| 22 | +- `initialization_script` must be attached at webview *build* time, so the window must be |
| 23 | + constructed in Rust rather than declared statically in `tauri.conf.json`. |
| 24 | +- Several `/api` calls bypass the shared `apiFetch` wrapper (direct `fetch()` in |
| 25 | + `OnboardingWizard.svelte`, `SettingsPanel.svelte`, `mutations.ts`, `outbox.ts`, |
| 26 | + `[...path]/+page.svelte`), so `401` recovery cannot live only in `apiFetch`. |
| 27 | + |
| 28 | +## Goals / Non-Goals |
| 29 | + |
| 30 | +**Goals:** |
| 31 | +- Desktop app authenticates automatically with zero user action, and the local API is no |
| 32 | + longer reachable unauthenticated by other loopback processes. |
| 33 | +- Browser/PWA users can bootstrap a token through a blocking auth screen when the API |
| 34 | + requires one. |
| 35 | +- A stored token that a restarted server rejects is recovered gracefully (cleared + |
| 36 | + re-prompt), never a permanently-dead app. |
| 37 | + |
| 38 | +**Non-Goals:** |
| 39 | +- Rotating/expiring tokens or a `/api/auth/refresh` endpoint (rejected — see Decisions). |
| 40 | +- Any change to server-side `--auth` semantics or new server endpoints. |
| 41 | +- Multi-user auth, password login, or token storage encryption. |
| 42 | +- Changing dev mode: `cargo tauri dev` keeps starting the sidecar token-less via |
| 43 | + `beforeDevCommand`. |
| 44 | + |
| 45 | +## Decisions |
| 46 | + |
| 47 | +### D1. Desktop generates a per-launch random token and passes it to the sidecar |
| 48 | +The `#[cfg(not(dev))]` setup block generates a 256-bit token, spawns the sidecar with |
| 49 | +`--auth <token>` (added to the existing arg list), and injects the same value into the |
| 50 | +webview. Token and server process are born and die together, so they can never drift. |
| 51 | + |
| 52 | +- **RNG:** use `getrandom` (already transitively in `Cargo.lock`) to fill 32 bytes, |
| 53 | + hex-encoded to a 64-char string. *Alternative:* `uuid` v4 (122 bits, needs the `v4` |
| 54 | + feature flag). Chosen `getrandom` for higher entropy and no new feature surface. |
| 55 | +- **Escaping:** the injected value is produced with `serde_json::to_string(&token)` so it |
| 56 | + is always a valid quoted JS string literal (defensive; the hex token needs no escaping). |
| 57 | + |
| 58 | +### D2. Build the window in Rust with an initialization_script (label `"main"`) |
| 59 | +Move the window out of `tauri.conf.json`'s static `windows` array and construct it with |
| 60 | +`WebviewWindowBuilder::new(app, "main", WebviewUrl::External(url))`, replicating the |
| 61 | +current `title`/size. The builder gets `.initialization_script(&format!("window.__MAILBRUS_AUTH_TOKEN__ = {json};"))` |
| 62 | +**only in `#[cfg(not(dev))]`**. The window is built unconditionally (dev + prod); only the |
| 63 | +injection and `--auth` are prod-gated. |
| 64 | + |
| 65 | +- Init scripts run before any page script on every navigation/reload, so the global is |
| 66 | + always present and always matches the current server process. |
| 67 | +- CSP is unaffected: `initialization_script` is injected by the webview runtime, not an |
| 68 | + inline `<script>`, so `script-src` need not change. |
| 69 | +- *Alternative:* keep the config window and `eval()` the global after load — rejected as |
| 70 | + racy (page scripts may run first) and it re-injects on every reload awkwardly. |
| 71 | + |
| 72 | +### D3. Browser auth screen gated in the root layout |
| 73 | +`src/routes/+layout.svelte` gains an auth gate backed by a small store with states |
| 74 | +`checking → authed | needs-token`. On boot it probes `GET /api/maildirs` (already the |
| 75 | +server health probe and the app's first data load — no new endpoint): |
| 76 | + |
| 77 | +- `200` → `authed`, render children. |
| 78 | +- `401` with no usable token, or with a token the server rejects → `needs-token`, render a |
| 79 | + blocking `<AuthScreen>` instead of the app. |
| 80 | +- Any other status / network error → not an auth problem; fall through to normal app error |
| 81 | + handling (e.g. server still starting). |
| 82 | + |
| 83 | +`<AuthScreen>` takes a token, calls `setAuthToken(token)`, re-probes, and on `200` flips to |
| 84 | +`authed`. On desktop the injected global makes the probe succeed immediately, so the screen |
| 85 | +never appears in normal operation. |
| 86 | + |
| 87 | +### D4. Stale-token recovery centralized, not per-call |
| 88 | +Because direct `fetch()` sites bypass `apiFetch`, recovery lives in one shared helper that |
| 89 | +every `/api` response passes through (extend `apiFetch` **and** route the direct callers |
| 90 | +through the same response check). On a `401` *when a token was attached*, the helper calls |
| 91 | +`setAuthToken(null)` and flips the gate store to `needs-token`. This is the entire |
| 92 | +"refresh" story — a stable secret plus re-bootstrap, no timers. |
| 93 | + |
| 94 | +- **Browser:** returns to `<AuthScreen>`. |
| 95 | +- **Desktop:** a `401`-with-token is near-unreachable (injected token always matches the |
| 96 | + live process and takes precedence over localStorage). Treated as an error state offering |
| 97 | + a window reload (re-runs the init script); not a primary flow. |
| 98 | + |
| 99 | +### D5. Static secret, no rotation (confirmed with stakeholder) |
| 100 | +Threat model is other local processes on loopback, not credential exfiltration, so a token |
| 101 | +fixed for the server's lifetime is sufficient. Rotation/expiry would require new server |
| 102 | +endpoints, a token store, and clock handling for no security gain on a single-user local |
| 103 | +client. Rejected. |
| 104 | + |
| 105 | +## Boot / auth flow |
| 106 | + |
| 107 | +```mermaid |
| 108 | +flowchart TD |
| 109 | + Boot[SPA boot: read token<br/>injected global → localStorage] --> Probe[GET /api/maildirs] |
| 110 | + Probe -->|200| Authed[authed: render app] |
| 111 | + Probe -->|401| Screen[needs-token: AuthScreen] |
| 112 | + Probe -->|other/network| Retry[non-auth error path] |
| 113 | + Screen -->|user enters token| Set[setAuthToken + re-probe] |
| 114 | + Set -->|200| Authed |
| 115 | + Set -->|401| Screen |
| 116 | + Authed -->|later 401 with token| Clear[clear token] |
| 117 | + Clear --> Screen |
| 118 | +``` |
| 119 | + |
| 120 | +## Risks / Trade-offs |
| 121 | + |
| 122 | +- **Direct `fetch('/api/...')` sites bypass central recovery** → route all `/api` callers |
| 123 | + through the shared response check; add a task to audit the five known sites and a test |
| 124 | + that a mid-session `401` surfaces the auth screen. |
| 125 | +- **Window moved to Rust drops config-driven window props** → replicate `title`/size in the |
| 126 | + builder and keep label `"main"` so capabilities keep matching; verify the bundled app |
| 127 | + still opens one correctly-sized window. |
| 128 | +- **`Cargo.lock` changes (new `getrandom` direct dep)** → update the shared `cargoHash` in |
| 129 | + `nix/pkgs.nix` in the same commit (per `CLAUDE.md`), else fresh Nix/CI builds break. |
| 130 | +- **Desktop `401` has no user-actionable recovery** (user can't know the generated token) → |
| 131 | + acceptable because it is effectively unreachable; offer a reload and log loudly. |
| 132 | +- **Token visible in webview memory** → inherent to any bearer scheme on a local HTTP |
| 133 | + server; out of scope, matches existing posture. |
| 134 | + |
| 135 | +## Migration Plan |
| 136 | + |
| 137 | +1. Desktop: add RNG dep, generate token, add `--auth` to sidecar args, build window in Rust |
| 138 | + with init script, trim `tauri.conf.json` `windows`. Update `cargoHash`. |
| 139 | +2. Frontend: add gate store + `<AuthScreen>` in `+layout.svelte`; centralize `401` |
| 140 | + recovery; route direct `/api` callers through it. |
| 141 | +3. Tests: E2E for browser bootstrap (401 → screen → enter token → app), mid-session stale |
| 142 | + `401` recovery, and desktop auto-auth (injected global → app, no screen). |
| 143 | + |
| 144 | +Rollback: revert the desktop commit (sidecar returns to token-less) and the frontend gate; |
| 145 | +no persisted state migration is involved (the localStorage/IDB token keys already exist). |
| 146 | + |
| 147 | +## Open Questions |
| 148 | + |
| 149 | +- Should the browser auth screen offer a "continue without auth" affordance when the probe |
| 150 | + succeeds (server has no `--auth`)? Current design simply never shows the screen in that |
| 151 | + case — likely sufficient. |
0 commit comments