Skip to content

Commit e4624b6

Browse files
committed
Merge origin/main into flakehub/darwin fixes
Both sides had re-enabled `mailbrus-desktop` and both had touched the frontend `outputHash`, so two conflicts. **flake.nix** — kept this side. Origin's comment justified re-enabling with "webkitgtk 2.52.3 was briefly broken … resolved (2.52.5+ is unbroken on both nixos-unstable and the pinned rev)". That is inaccurate on both counts: the pinned nixpkgs (567a49d, unchanged by either side) still carries webkitgtk **2.52.4**, and its condition is `broken = clangStdenv.hostPlatform.isDarwin` — unbroken on Linux, still broken on Darwin. Re-enabling the output was right, but the reason was not, and the darwin outputs `eachDefaultSystem` advertised remain unevaluatable. This side's Linux-only restriction and its explanation are kept. **nix/pkgs.nix** — neither `outputHash` was correct after the merge: origin's was computed before this side's `svelte.config.js` version pin, and this side's was computed before origin's auth-bootstrap frontend changes. Recomputed against the merged tree. Verified first that two consecutive `deno task build` runs are byte-identical, so the value is stable rather than a snapshot — origin having had to refresh this hash twice (55ccaf8, d9f4bc3) is the symptom that pin removes. Everything else auto-merged. `Cargo.lock` is identical to origin's, so origin's `cargoHash` still applies and is unchanged; origin's `buildFeatures = ["custom-protocol"]` fix for the desktop sidecar is kept as-is. Verified on the merged tree: `cargo check` and clippy clean; 94 unit tests pass; all four nix packages build; `nix flake check --no-build --all-systems` passes; e2e 180 passed / 1 skipped / 0 failed, including origin's new auth-bootstrap specs.
2 parents 1027367 + d9f4bc3 commit e4624b6

23 files changed

Lines changed: 925 additions & 56 deletions

File tree

‎Cargo.lock‎

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎e2e/harness/server.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ export interface ServerHandle {
1414
}
1515

1616
/** Reserve an ephemeral loopback port, then release it for the server to bind. */
17-
function reserveFreePort(): Promise<number> {
17+
export function reserveFreePort(): Promise<number> {
1818
return new Promise((resolve, reject) => {
1919
const srv = createServer();
2020
srv.on('error', reject);
@@ -58,11 +58,17 @@ export interface ServerOptions {
5858
config: ConfigHandle;
5959
/** When set, start the server with `--auth <token>` (enforced on `/api/*`). */
6060
auth?: string;
61+
/**
62+
* Bind a specific port instead of reserving a fresh one. Lets a test restart
63+
* the server on the same authority (e.g. to simulate a token rotation). The
64+
* server sets `SO_REUSEADDR`, so rebinding across a restart is safe.
65+
*/
66+
port?: number;
6167
}
6268

6369
/** Start a server pointed at `clone`'s `XDG_DATA_HOME` and wait until it answers. */
6470
export async function startServer(opts: ServerOptions): Promise<ServerHandle> {
65-
const port = await reserveFreePort();
71+
const port = opts.port ?? (await reserveFreePort());
6672
const baseURL = `http://127.0.0.1:${port}`;
6773

6874
const args = [

‎e2e/specs/auth-bootstrap.spec.ts‎

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
/** auth-bootstrap: browser token entry, stale-token recovery, and desktop injection. */
2+
import { test, expect } from '../harness/fixtures.ts';
3+
import { cloneCorpus, removeClone, type Clone } from '../harness/clone.ts';
4+
import { writeFixtureConfig } from '../harness/config.ts';
5+
import { indexClone } from '../harness/notmuch.ts';
6+
import { reserveFreePort, startServer, type ServerHandle } from '../harness/server.ts';
7+
8+
/** A freshly cloned, indexed server, optionally under `--auth` and on a fixed port. */
9+
async function startAuthedServer(
10+
auth?: string,
11+
port?: number
12+
): Promise<{ clone: Clone; server: ServerHandle }> {
13+
const clone = await cloneCorpus();
14+
const scope = await indexClone(clone);
15+
const config = await writeFixtureConfig(clone);
16+
const server = await startServer({ scope, clone, config, auth, port });
17+
return { clone, server };
18+
}
19+
20+
// openspec/changes/tauri-token-injection/specs/frontend-auth-bootstrap/spec.md: missing token forces the auth screen; a valid token unlocks the app
21+
test('browser bootstrap: auth screen gates the app, wrong token rejected, correct token unlocks', async ({
22+
page
23+
}) => {
24+
const token = 'e2e-bootstrap-token';
25+
let clone: Clone | undefined;
26+
let server: ServerHandle | undefined;
27+
try {
28+
({ clone, server } = await startAuthedServer(token));
29+
await page.goto(server.baseURL);
30+
31+
// No token yet → the blocking auth screen stands in for the app.
32+
await expect(page.getByTestId('auth.screen')).toBeVisible();
33+
await expect(page.getByText('Open a maildir')).toHaveCount(0);
34+
35+
// A wrong token is rejected and keeps the screen up.
36+
await page.getByTestId('auth.token-input').fill('not-the-token');
37+
await page.getByTestId('auth.submit').click();
38+
await expect(page.getByTestId('auth.error')).toBeVisible();
39+
await expect(page.getByTestId('auth.screen')).toBeVisible();
40+
41+
// The correct token unlocks the app.
42+
await page.getByTestId('auth.token-input').fill(token);
43+
await page.getByTestId('auth.submit').click();
44+
await expect(page.getByText('Open a maildir')).toBeVisible();
45+
await expect(page.getByTestId('auth.screen')).toHaveCount(0);
46+
} finally {
47+
if (server) await server.stop();
48+
await removeClone(clone);
49+
}
50+
});
51+
52+
// openspec/changes/tauri-token-injection/specs/frontend-auth-bootstrap/spec.md: a mid-session 401 clears the stored token and re-shows the auth screen
53+
test('stale token recovery: a rotated server 401s a live session back to the auth screen', async ({
54+
page
55+
}) => {
56+
const tokenA = 'e2e-token-a';
57+
const tokenB = 'e2e-token-b';
58+
// Fixed port so the "rotated" server B reuses server A's authority.
59+
const port = await reserveFreePort();
60+
let cloneA: Clone | undefined;
61+
let cloneB: Clone | undefined;
62+
let serverA: ServerHandle | undefined;
63+
let serverB: ServerHandle | undefined;
64+
try {
65+
({ clone: cloneA, server: serverA } = await startAuthedServer(tokenA, port));
66+
await page.goto(serverA.baseURL);
67+
68+
// Bootstrap with the valid token; the app renders.
69+
await page.getByTestId('auth.token-input').fill(tokenA);
70+
await page.getByTestId('auth.submit').click();
71+
await expect(page.getByText('Open a maildir')).toBeVisible();
72+
73+
// The server "rotates": stop A, bring up B on the same authority with a
74+
// new token. The browser still holds token A in memory.
75+
await serverA.stop();
76+
serverA = undefined;
77+
({ clone: cloneB, server: serverB } = await startAuthedServer(tokenB, port));
78+
79+
// A UI action issues an authed /api/* request → 401 → recovery.
80+
await page.getByTestId('accounts.curtain').getByTestId('palette.row').first().click();
81+
await expect(page.getByTestId('auth.screen')).toBeVisible();
82+
} finally {
83+
if (serverB) await serverB.stop();
84+
if (serverA) await serverA.stop();
85+
await removeClone(cloneA);
86+
await removeClone(cloneB);
87+
}
88+
});
89+
90+
// openspec/changes/tauri-token-injection/specs/frontend-auth-bootstrap/spec.md: a server without --auth never shows the auth screen
91+
test('no-auth server: the app loads directly and the auth screen is never shown', async ({ page }) => {
92+
// The default `app` fixture starts a token-less server.
93+
await page.goto('/');
94+
await expect(page.getByText('Open a maildir')).toBeVisible();
95+
await expect(page.getByTestId('auth.screen')).toHaveCount(0);
96+
});
97+
98+
// openspec/changes/tauri-token-injection/specs/desktop-auth-token/spec.md: an injected token authenticates the SPA with no auth screen
99+
test('injected token: the SPA authenticates automatically with no auth screen', async ({ page }) => {
100+
const token = 'e2e-injected-token';
101+
let clone: Clone | undefined;
102+
let server: ServerHandle | undefined;
103+
try {
104+
({ clone, server } = await startAuthedServer(token));
105+
// Mimic the desktop shell's initialization_script.
106+
await page.addInitScript((t) => {
107+
(window as unknown as { __MAILBRUS_AUTH_TOKEN__?: string }).__MAILBRUS_AUTH_TOKEN__ = t;
108+
}, token);
109+
await page.goto(server.baseURL);
110+
111+
// App loads against the --auth server ⇒ /api/* carried the bearer token.
112+
await expect(page.getByText('Open a maildir')).toBeVisible();
113+
await expect(page.getByTestId('auth.screen')).toHaveCount(0);
114+
} finally {
115+
if (server) await server.stop();
116+
await removeClone(clone);
117+
}
118+
});

‎nix/pkgs.nix‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ let
44
pname = "mailbrus";
55
version = "0.1.0";
66
src = ../.;
7-
cargoHash = "sha256-+U6FYemR14u5/C81zsPRUwfQCvRVIwulf6IoGQw5o3s=";
7+
cargoHash = "sha256-a3dV7vSmDV7WQ5WPEvZNS6+SKJhSBvUF812Q69IUWyw=";
88
cargoBuildFlags = [ "--package" "mailbrus-cli" ];
99
nativeBuildInputs = [ pkgs.pkg-config ];
1010
buildInputs = tauri-deps;
@@ -35,16 +35,21 @@ let
3535
# `version.name` is pinned in svelte.config.js instead of defaulting to
3636
# `Date.now()`, which used to change every content-hashed chunk name and made
3737
# this hash impossible to keep correct.
38-
outputHash = "sha256-CiwxuQ5HWJys1uVlNS5PekOqtXuoXd1sOvWBkaPDEdA=";
38+
outputHash = "sha256-zGFA0eTpGQRuWiI0lrOOGC88D3EzsBCzUvjg17yilvA=";
3939
};
4040

4141
mailbrus-desktop = pkgs.rustPlatform.buildRustPackage {
4242
pname = "mailbrus-desktop";
4343
version = "0.1.0";
4444
src = ../.;
4545
preferLocalBuild = true;
46-
cargoHash = "sha256-+U6FYemR14u5/C81zsPRUwfQCvRVIwulf6IoGQw5o3s=";
46+
cargoHash = "sha256-a3dV7vSmDV7WQ5WPEvZNS6+SKJhSBvUF812Q69IUWyw=";
4747
cargoBuildFlags = [ "--package" "mailbrus-desktop" ];
48+
# Tauri sets `dev = !custom-protocol`. Without this, buildRustPackage's plain
49+
# `cargo build` leaves dev=true, stripping the `#[cfg(not(dev))]` block in
50+
# src-tauri/src/lib.rs that spawns the server sidecar + injects the auth
51+
# token — the app then can't reach 127.0.0.1:1371. See src-tauri/Cargo.toml.
52+
buildFeatures = [ "custom-protocol" ];
4853
doCheck = false;
4954
nativeBuildInputs = [
5055
pkgs.pkg-config
@@ -88,7 +93,7 @@ let
8893
pname = "mailbrus-server";
8994
version = "0.1.0";
9095
src = ../.;
91-
cargoHash = "sha256-+U6FYemR14u5/C81zsPRUwfQCvRVIwulf6IoGQw5o3s=";
96+
cargoHash = "sha256-a3dV7vSmDV7WQ5WPEvZNS6+SKJhSBvUF812Q69IUWyw=";
9297
cargoBuildFlags = [ "--package" "mailbrus-server" ];
9398
cargoTestFlags = [ "--package" "mailbrus-server" ];
9499
nativeBuildInputs = [ pkgs.pkg-config ];
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
schema: spec-driven
2+
created: 2026-08-12
Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
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

Comments
 (0)