# Mathom A reading-first Progressive Web App client for [Wallabag](https://wallabag.org), the self-hosted read-later service. Point it at your own Wallabag instance, configure once, and get a reading experience on par with Matter or Readwise Reader — offline-capable, fully customizable, no account required on our end. **Highlights:** OAuth2 against your Wallabag, offline reading + offline mutations with replay-on-reconnect, full reader customization (font, size, line height, width, theme), filter by unread/starred/archived/tag, server-side search, add articles by URL paste or Android share sheet, pull-to-refresh on mobile, install-as-app on Android & desktop. See [CLAUDE.md](./CLAUDE.md) for the full product and technical specification. ## Architecture ``` [ Your Browser ] │ │ HTTPS — static assets + service worker ▼ [ Cloudflare Pages: SvelteKit PWA ] │ │ HTTPS — JSON API calls ▼ [ Cloudflare Worker: mathom-cors (CORS proxy) ] │ │ HTTPS ▼ [ Your Wallabag instance ] ``` The PWA is fully static (no SSR). The Worker is a ~50-line CORS shim — it adds the headers Wallabag's API is missing and forwards everything else unchanged. Your Wallabag instance is the source of truth for all data and auth. --- ## Prerequisites | Tool | Version | Install | |---|---|---| | Bun | 1.x (latest stable) | `curl -fsSL https://bun.sh/install \| bash` | | Wrangler | (via bunx, no install needed) | `bunx wrangler --version` to verify | | Git | any recent | — | | Cloudflare account | free tier | [dash.cloudflare.com](https://dash.cloudflare.com) | | Wallabag instance | 2.x | [wallabag.org install docs](https://doc.wallabag.org/en/admin/installation/installation.html) | You do **not** need Node.js to work on the PWA. Wrangler (the Cloudflare Worker CLI) is Node-first but runs via `bunx` in most cases. If you hit a Wrangler issue, install Node 20.x as a fallback for Worker commands only. --- ## Quick start (local development) ### 1. Clone ```bash git clone https://github.com/YOUR_ORG/mathom.git cd mathom ``` ### 2. Install dependencies ```bash cd pwa && bun install cd ../worker && bun install ``` ### 3. Configure environment ```bash # PWA cp pwa/.env.example pwa/.env.local # Edit pwa/.env.local — uncomment PUBLIC_DEFAULT_WORKER_URL=http://localhost:8787 # This pre-fills the Worker URL during onboarding so you don't have to type it # every time. The variable is optional; if unset the production Worker is used. # Worker has no secrets; wrangler.toml is the config ``` ### 4. Run the CORS Worker locally ```bash cd worker bunx wrangler dev ``` Wrangler starts a local Worker at **`http://localhost:8787`**. Keep this terminal open — the PWA routes all Wallabag API calls through it during development. > **Heads up:** `bunx wrangler` works for most operations. If you hit a Wrangler-specific crash or hang (file watching issues are the most common), fall back to `npx wrangler dev` with a local Node 20.x install. ### 5. Run the PWA In a second terminal: ```bash cd pwa bun run dev ``` Vite starts the dev server at **`http://localhost:5173`** with hot module replacement. Changes to `.svelte` and `.ts` files reload instantly; service worker changes require a manual browser reload (see [Debugging the service worker](#debugging-the-service-worker)). ### 6. First-time setup 1. Open `http://localhost:5173` in your browser. 2. You'll be redirected to `/onboarding`. 3. Enter your Wallabag credentials: - **Wallabag URL** — e.g., `https://wallabag.example.com` - **Client ID / Client Secret** — from your Wallabag API client (see [Wallabag configuration](#wallabag-configuration)) - **Username / Password** — your Wallabag login (used once for token exchange, then discarded) - **Worker URL** — `http://localhost:8787` for local dev 4. Click **Connect**. The app exchanges your credentials for OAuth tokens, then begins syncing articles. ### 7. Verify sync After a few seconds you should see your unread articles at `http://localhost:5173/`. If you see a CORS error or empty list, check [Troubleshooting](#troubleshooting). --- ## Wallabag configuration ### Create an API client 1. Log in to your Wallabag instance. 2. Go to **`/developer`** (e.g., `https://wallabag.example.com/developer`). 3. Click **Create a new client**. 4. Give it a name (e.g., "Mathom") and leave redirect URI blank. 5. Copy the **Client ID** and **Client Secret** — you'll need these in Mathom's settings. ### Recommended server settings In your Wallabag server config (`parameters.yml` or the admin UI): - **`download_images_enabled: true`** — Wallabag re-hosts article images on your server. Strongly recommended: avoids opaque cross-origin image responses that balloon your service worker cache and may not cache at all. ### Wallabag CORS notes Wallabag's CORS support is unreliable. The OAuth endpoint (`/oauth/v2/token`) in particular does not return CORS headers on error responses, which causes the browser to see a network error instead of a 401. This is the primary reason the CORS Worker exists. See the [Wallabag issue tracker](https://github.com/wallabag/wallabag/issues) for upstream status. --- ## Architecture ### Components | Component | Responsibility | |---|---| | **SvelteKit PWA** (`pwa/`) | UI, local IndexedDB (via Dexie), sync engine, offline queue, service worker | | **CORS Worker** (`worker/`) | Adds CORS headers to Wallabag API responses; validates target URLs; rate-limits | | **Wallabag** | Article storage, tagging, auth (OAuth2 password grant) | ### Data flows **Initial auth:** 1. User enters credentials in `/onboarding`. 2. PWA POSTs to Worker → Worker proxies to `{wallabag_url}/oauth/v2/token`. 3. Tokens stored in IndexedDB settings row. Username/password discarded immediately. **Article sync:** 1. On app open: GET `/api/entries?since={last_sync_at}` (paginated), upsert into Dexie. 2. Once daily: full ID reconciliation to catch server-side deletes. 3. `last_sync_at` updated on success. **Offline mutations (archive, star, delete):** 1. User action writes to Dexie immediately (optimistic UI). 2. A `PendingMutation` is enqueued. 3. A drainer loop flushes the queue; retries with backoff on failure. 4. Workbox Background Sync fires the drainer when connectivity returns. **Image caching:** Service worker intercepts image requests with a `CacheFirst` strategy (30-day TTL, max 1000 entries). Works best with `download_images_enabled` on your Wallabag instance. ### Why the Worker exists Browsers enforce CORS. Wallabag doesn't consistently send `Access-Control-Allow-Origin` headers — especially on the OAuth endpoint and on error responses. Rather than requiring users to patch their Wallabag instance, Mathom routes all API calls through a Cloudflare Worker that adds the missing headers. The Worker does no authentication of its own and logs no request bodies. --- ## Project layout ``` mathom/ ├── pwa/ # SvelteKit PWA (Cloudflare Pages) │ ├── src/ │ │ ├── lib/ │ │ │ ├── api/ # Wallabag API client (framework-agnostic) │ │ │ ├── db/ # Dexie schema and queries │ │ │ ├── sync/ # Sync engine and mutation queue drainer │ │ │ ├── components/ # Svelte components │ │ │ └── stores/ # Svelte 5 rune-based state │ │ ├── routes/ │ │ │ ├── +layout.svelte # Root layout (theme, font, global styles) │ │ │ ├── +page.svelte # Article list (/?filter=unread|archived|starred|all) │ │ │ ├── articles/[id]/ # Reader view │ │ │ ├── settings/ # Settings + reader preferences │ │ │ ├── settings/auth/ # Re-auth flow │ │ │ ├── onboarding/ # First-time setup wizard │ │ │ ├── search/ # Server-side search │ │ │ └── share/ # Web Share Target endpoint (Android) │ │ ├── sw.ts # Workbox service worker (vite-plugin-pwa, injectManifest) │ │ └── app.html # HTML shell, includes manifest + icon links │ ├── static/ # Icons, manifest assets, robots.txt │ ├── .env.example # Environment variable template │ ├── svelte.config.js │ ├── vite.config.ts # Vite + vite-plugin-pwa config │ └── package.json ├── worker/ # Cloudflare Worker (mathom-cors) │ ├── src/index.ts # CORS proxy logic (~50 lines) │ ├── wrangler.toml # Worker config and rate limiting │ └── package.json ├── README.md ├── CLAUDE.md # Full product + technical specification └── .gitignore ``` --- ## Common development tasks ### Running tests ```bash cd pwa && bun run test ``` The API client, DB layer, and sync engine are framework-agnostic and testable without a Svelte runtime. ### Building for production ```bash # PWA cd pwa && bun run build # Output in pwa/.svelte-kit/output/ # Worker (dry run — shows what would be deployed) cd worker && bunx wrangler deploy --dry-run ``` ### Bumping the Dexie schema version When you add or change a field on any Dexie table: 1. Open `pwa/src/lib/db/schema.ts`. 2. Add a new `db.version(N)` call with the same store strings (or new ones if indexes change). 3. Chain `.upgrade(tx => { ... })` to transform existing rows. Do not skip versions — Dexie runs migrations in order on upgrade. ```ts this.version(2).stores({ entries: 'id, is_archived, is_starred, created_at, updated_at, cached_at', pendingMutations: '++id, entry_id, type, created_at', settings: 'id' }).upgrade(async (tx) => { await tx.table('settings').toCollection().modify((s) => { s.last_full_sync_at = null; }); }); ``` Failing to bump the version when the schema changes causes a runtime error for users with existing data. ### Adding a new route 1. Create `pwa/src/routes/your-route/+page.svelte` (and `+page.ts` if you need a load function). 2. SvelteKit picks it up automatically. No router config needed. 3. If the route needs data: use `+page.ts` with a `load` function (SSR is disabled; `load` runs client-side only). ### Adding a new Wallabag API call 1. Add the function to the appropriate file in `pwa/src/lib/api/`. 2. Use the existing `apiFetch` wrapper — it handles auth headers, token refresh on 401, and routing through the Worker. 3. Keep all API code framework-agnostic (no Svelte imports). ### Updating the service worker / PWA manifest - **Manifest:** edit the `manifest` object in `pwa/vite.config.ts` under `VitePWA(...)`. - **Custom SW logic:** `pwa/src/sw.ts` is the entry point — the project uses `injectManifest`, so you own the SW source. Workbox precaches the build manifest, then individual `registerRoute` calls handle runtime caching. - **Update flow:** `registerType: 'prompt'` shows users a "new version available" banner via the `` component. The SW does not call `self.skipWaiting()` automatically; updates apply when the user clicks Reload. - **Regenerating PWA icons:** edit `pwa/static/icon-source.svg`, then run `bunx --bun @vite-pwa/assets-generator --preset minimal-2023 static/icon-source.svg` from `pwa/` to regenerate all PNG variants. After any SW change, the browser won't pick it up automatically during development. See below. ### Debugging the service worker In Chrome DevTools: - **Application → Service Workers** — see registration status, force update, unregister. - **Application → Cache Storage** — inspect what Workbox has cached. - **Application → IndexedDB** — inspect Dexie tables directly. Common issue: SW not updating after a code change. Fix: 1. DevTools → Application → Service Workers → click **Unregister**. 2. Hard-reload (`Cmd+Shift+R` / `Ctrl+Shift+R`). 3. Or run `bun run dev` — Vite's dev mode bypasses the SW by default. --- ## Deployment ### Deploy the CORS Worker ```bash cd worker # First time: authenticate bunx wrangler login # Deploy bunx wrangler deploy ``` Your Worker is live at `https://mathom-cors.YOUR_ACCOUNT.workers.dev`. Copy this URL — you'll need it for the PWA's `PUBLIC_DEFAULT_WORKER_URL`. ### Deploy the PWA to Cloudflare Pages **Manual:** ```bash cd pwa bun run build bunx wrangler pages deploy build --project-name=mathom ``` **Via GitHub integration (recommended for production):** 1. In the Cloudflare dashboard: **Pages → Create a project → Connect to Git**. 2. Select your repo. 3. Build settings: - **Framework preset:** SvelteKit - **Build command:** `cd pwa && bun run build` - **Build output directory:** `pwa/build` 4. Add environment variables (see below). 5. Deploy. ### Environment variables Set these in Cloudflare Pages → Settings → Environment variables: | Variable | Value | Notes | |---|---|---| | `PUBLIC_DEFAULT_WORKER_URL` | `https://mathom-cors.YOUR_ACCOUNT.workers.dev` | URL of your deployed Worker | The Worker itself has no secrets — its `wrangler.toml` is the complete config. ### Required Cloudflare setup - **Free account** is sufficient for both Pages and Workers. - Workers: your account gets a `*.workers.dev` subdomain automatically. - Pages: one project per app; the free tier allows unlimited deploys. --- ## Trust and security ### What the Worker does - Receives a proxied request from the PWA with a `target` query parameter (the full Wallabag API URL). - Validates that the target is HTTPS, points to a public hostname (not localhost or RFC1918), and has a path starting with `/api/` or `/oauth/`. - Forwards the request method, `Authorization` header, `Content-Type` header, and body. - Returns the Wallabag response with CORS headers added. ### What the Worker does not do - **Does not log request bodies.** Auth credentials and article content are never logged. - **Does not authenticate users.** It is a CORS shim, not a security boundary. - **Does not store anything.** Stateless; no KV, no D1. ### What credentials live where | Credential | Where stored | Notes | |---|---|---| | Wallabag access token | IndexedDB (device-local) | Short-lived; refreshed automatically | | Wallabag refresh token | IndexedDB (device-local) | Persisted; cleared on logout | | OAuth client ID / secret | IndexedDB (device-local) | Same trust model as Wallabag's mobile apps | | Username / password | Nowhere (discarded after token exchange) | Never written to storage | ### Self-hosting the Worker If you don't want to trust the project-hosted Worker: 1. Clone this repo. 2. `cd worker && bunx wrangler deploy` with your own Cloudflare account. 3. Set your Worker's URL in Mathom's Settings → Advanced → Custom CORS proxy URL. The Worker source is in `worker/src/index.ts` — ~50 lines, easy to audit. --- ## Troubleshooting ### "I get CORS errors" 1. Confirm the Worker is running: `curl http://localhost:8787/` should return a response (not a connection refused). 2. Check **Worker URL** in Mathom settings — must match exactly (`http://localhost:8787` for local, no trailing slash). 3. If the error is on the OAuth endpoint specifically: this is a known Wallabag issue. The Worker handles it; if you're still seeing errors, check that your `worker_url` is set and that the Worker dev process is running. ### "Tokens stop working / I get logged out" The app attempts a token refresh on every 401. If the refresh token is also expired or revoked (Wallabag default is 14 days for refresh tokens): 1. Go to `/settings/auth`. 2. Enter your password to re-authenticate. 3. New tokens are issued and persisted. ### "Service worker not updating" 1. Chrome DevTools → Application → Service Workers → **Unregister**. 2. Hard-reload. 3. Alternatively: `bun run dev` bypasses the SW in development mode — if you're seeing stale behaviour in dev, you may have a registered SW from a previous prod build. Unregister it. ### "IndexedDB schema mismatch" / app crashes on load This happens when the Dexie schema version in code doesn't match the version in the user's browser. Fix: - **During development:** open DevTools → Application → IndexedDB → delete the `mathom` database, reload. - **In production:** bump the version in `pwa/src/lib/db/schema.ts` and write a migration. Never delete user data without explicit user action. ### `bunx wrangler` crashes or hangs Fall back to Node: ```bash # Install Node 20.x (e.g. via nvm or https://nodejs.org) npx wrangler dev # or npx wrangler deploy ``` This is a known rough edge of running Wrangler outside its supported Node runtime. --- ## Contributing ### Code style - **TypeScript:** strict mode everywhere. No `any`. - **Svelte:** Svelte 5 runes only (`$state`, `$derived`, `$effect`, `$props`). No legacy `$:` reactive declarations, no `writable` stores. - **CSS:** plain CSS with custom properties. No Tailwind, no CSS-in-JS. - **Type checking:** `bun run check` (svelte-check). Fix all errors and warnings before opening a PR. - **Tests:** `bun run test` for the PWA, `cd worker && bun run test` for the Worker. - **File naming:** `kebab-case.svelte` for components, `kebab-case.ts` for modules. ### Branch and commit conventions - Branch names: `feature/short-description`, `fix/short-description` - Commit messages: imperative mood, present tense — "add reader font controls", not "added" or "adding" - Keep commits focused; one logical change per commit ### Filing an issue Use GitHub Issues. Include: - Mathom version (or commit SHA) - Browser and OS - Wallabag version - Steps to reproduce - Expected vs actual behaviour - Console errors if applicable