Skip to content

Connect and Tunnels

Wijanarko Putra Rajeb edited this page Nov 17, 2026 · 4 revisions

Connect, tunnels and pairing

Settings → Connect is how a phone or another desktop reaches this install without typing an address or a password. It has three blocks: the addresses this server answers on, the two tunnel providers, and the devices that have been paired.

Why Tailscale is the preferred route, even at home

The naive rule — use the fastest address — is wrong here, and the measurement is what makes it wrong. On a LAN, http://192.168.x.x is not a secure context:

API http://127.0.0.1 http://192.168.x.x
isSecureContext true false
crypto.subtle available undefined
navigator.mediaDevices / getUserMedia available undefined
navigator.clipboard.readText available undefined
serviceWorker available false

So on a LAN address, composer dictation is dead, copy/paste degrades to execCommand, the PWA cannot be installed, and the password crosses the Wi-Fi in cleartext. Tailscale on the same network is a direct WireGuard peer connection — no DERP relay — so it costs a fraction of a millisecond over the LAN address and restores all four.

The order is therefore a tier, not a score (src/shared/lib/connect/tier.ts):

0  tailscale    https://<node>.<tailnet>.ts.net
1  lan          http://192.168.x.x:3000
2  cloudflare   https://<host>.<domain>

A lower tier always wins while it is reachable; the round trip only breaks ties inside a tier. A same-tier switch needs a gain of more than 30 ms and more than 20%, because every switch is a page load.

Tunnels

Tailscale Serve

tailscale serve --bg --yes --https=443 http://127.0.0.1:<port>

  • Proxies only to http://127.0.0.1, so Kabmo does not need --lan for this route. The listener stays on loopback.
  • TLS terminates on this machine with a certificate the platform already trusts, so every shell accepts it with no pinning work — and Tailscale never sees the traffic.
  • --bg is what makes the share survive a reboot and a tailscale down/up.
  • Stopping uses serve --https=443 off, never reset: reset would also remove every other share the user configured by hand.
  • The macOS App Store and Standalone variants ship the CLI inside the app bundle (/Applications/Tailscale.app/Contents/MacOS/Tailscale), so a Bun.which miss is not "not installed".
  • On Linux, sudo tailscale set --operator=$USER once, or only root may share a port.

Measured failure mode: with HTTPS disabled for the tailnet, serve does not answer at all. The spawn therefore has a 15 s deadline that settles the call — a killed process whose child still holds the pipe leaves Response(proc.stdout).text() pending forever, which hung the route for the full three minutes a smoke test allowed. The card says "Tailscale did not answer within 15 seconds. HTTPS may be disabled for this tailnet" rather than "timed out".

Cloudflare Tunnel — named only

Quick tunnels are deliberately not supported:

  • they buffer Server-Sent Events (cloudflared #1449; the maintainer confirms named tunnels stream correctly and quick tunnels do not), and Kabmo has six SSE endpoints including the chat stream — every answer would arrive in one burst at the end;
  • 200 in-flight requests, then 429;
  • the hostname changes on every start;
  • no uptime guarantee.

A named tunnel needs an account and a domain, which is why it is the second route. It is also the one route where a third party reads the traffic: TLS terminates at Cloudflare's edge, so the console's password and every prompt cross their machines in plaintext. The card says so.

The config path has three sources, highest first: the path saved on the Connect page (app_settings.connect.cloudflareConfigPath), CLOUDFLARED_CONFIG, then ~/.cloudflared/config.yml. A saved path is written only after the server proves it names a runnable config (absolute, a file, a top-level tunnel: and an ingress hostname:), and the refusal is a sentence rather than a silent fallback.

--url does not override the config's ingress service. cloudflared parses the config's rules first and only falls back to the CLI origin when ingress is empty (ingress.ParseIngressFromConfigAndCLI), and Kabmo refuses a config with no ingress hostname — so --url would be ignored in every config it accepts and the tunnel would dial whatever service: names, often another port. Instead the start path writes a runtime copy in a mkdtemp directory whose first hostname rule has service: http://127.0.0.1:<port>, passes --config to that copy, and deletes it on stop or process exit. The user's file is never modified; the other rules (the http_status:404 catch-all, originRequest, credentials-file) are preserved verbatim. A config too malformed to rewrite is refused instead of started.

A malformed file otherwise degrades to "not configured" rather than throwing.

Pairing

The payload

https://<best-address>/pair#<base64url(JSON)>
{ v:1, pairingId, secret, serverId, label, expiresAt,
  candidates: [{ kind: 'tailscale'|'lan'|'cloudflare', url }] }

The payload lives in the fragment, never the query string: a fragment is not sent to the server, so the one-time secret never reaches an access log, a proxy, or a Referer. The page reads it with location.hash and posts it once.

The QR encodes the browser link, not a kabmo:// deep link. That is what makes pairing work with no native scanner: the phone's camera app opens an https URL in the browser, the page redeems the code, and the console loads authenticated.

The flow

  1. POST /api/connect/pair (session required) mints a pairing: 32 random bytes, 2-minute TTL, single use, and returns the link plus a QR matrix.
  2. The phone opens /pair#… (public). The page measures its own origin's round trip, matches location.origin against the candidates to name the route, and posts the claim.
  3. POST /api/connect/pair/claim (public — the secret is the credential) consumes the pairing, mints a per-device token, and answers with Set-Cookie: kabmo_device=…; HttpOnly; SameSite=Lax.
  4. The page redirects to /. The console is authenticated.

The secret is compared by hash and the entry is deleted before the token is minted: a claim that fails afterwards costs a new QR, which is the safe direction. A wrong secret does not consume the code, so a mistyped paste does not invalidate the one on screen.

Where pairing lives

Two surfaces, and nothing else:

Surface Job
Console → Settings → Connect generate the code, show the QR, list and revoke devices
Shell → Server settings read a code (camera or pasted link) and connect to that server

The console's login screen deliberately has no pairing control. Pairing is how a shell learns which server to talk to, and the shell's own settings screen is where that question is asked — a login screen only appears once a server is already known. A scanner there made two places answer the same question, and the one on the login screen could not help the case that matters: a first run with no server configured at all.

Scanning from the shell's own settings

Each shell's scanner is opened from Server settings next to the pairing-link field, and the code it reads lands in that field — one submit path, the same one the paste uses.

Each platform gets the cheapest correct decoder, not one answer forced onto all of them:

Shell Decoder Why
iOS, macOS AVCaptureMetadataOutput (.qr) built into the platform, no dependency, same decoder the system Camera app uses
Android, Windows, Linux the shared page: BarcodeDetector where the OS has one, jsQR otherwise the frameworks have no QR decoder; the alternatives are a ~500 KB ZXing dependency or a hand-written Camera2 state machine, and the shells ship zero runtime dependencies

ONE page, three hosts. packages/qr-scanner/page.html is the source and packages/qr-scanner/qr-scanner.html is generated from it by bun packages/qr-scanner/build.mjs, which inlines jsQR (131 KB, minified) into the page's <script id="jsqr"> block. Android copies the generated file into its assets at build time, Windows embeds it, Linux include_str!s it. The three hand-maintained copies this replaces had already drifted, and both drifts were invisible until a device was tried:

  • BarcodeDetector is not everywhere. It exists only where the OS has a barcode provider: Android WebView 83+, and Chromium on macOS/ChromeOS. WebView2 on Windows has none — Chromium hides the interface on platforms with no provider since M88 (crbug 40725008) — and WebKitGTK has none. The Windows copy had no jsQR, so its camera preview ran and never read a frame, and every uploaded image answered "No QR code was found in that image". jsQR is therefore inlined for every host, and BarcodeDetector is only the fast path.
  • The page and its host agree on names, and a mismatch is silent. Android publishes one object — addJavascriptInterface(Bridge(), "KabmoQr") — and the page reports through window.KabmoQr.result / .error; Windows and Linux use chrome.webview.postMessage and webkit.messageHandlers.kabmoQr. The page reported only to window.__kabmoQrResult, which no host ever injected, so a successful Android scan drew "Code read." and stopped there: the camera was already stopped, the Activity never heard the code, and the screen sat on that sentence until Back. QrScannerPageTest pins the page's bridge names to the name the Activity injects, pins the generated artifact to the source page, and app/build.gradle.kts declares both files as test inputs so an edit cannot be served from Gradle's cache.

A reported error does not close the scanner. The page draws the sentence and it is the only place that can; finishing the Activity on error() destroyed the reason before it could be read, and on Android it also raced the camera's own NotFoundError against an upload that was still decoding. macOS already worked this way (finish(with:) leaves the sheet open), and its status label now wraps instead of clipping the sentence at 420 points.

An image decode that hangs is abandoned. BarcodeDetector.detect() is raced against a 4-second timeout and jsQR is tried next, so a detector that never settles cannot leave the page on "Reading the image…" forever.

A picker that cannot read the file says so. iOS used to return silently when the provider could not produce a UIImage, when cgImage was nil (a CIImage-backed UIImage, which some HEIC and animated providers hand back), and when the load failed — three different failures that all looked like "nothing happened". Each now writes a sentence, and a nil cgImage falls back to CIImage(image:) instead of giving up.

The secure origin is load-bearing on every host. getUserMedia needs one, and a document loaded from file://, about:blank or with no base URI has an opaque origin that is not one — the page would report "this device does not offer a camera" on a machine with a perfectly good webcam. So:

  • Android: loadDataWithBaseURL("https://kabmo.local/", …)
  • Windows: SetVirtualHostNameToFolderMapping("kabmo.local", folder, Allow)
  • Linux: load_html(page, Some("https://kabmo.local/"))

The camera permission stays native everywhere: Android grants RESOURCE_VIDEO_CAPTURE in onPermissionRequest, iOS/macOS ask AVCaptureDevice.requestAccess, and the usage-description keys (NSCameraUsageDescription) are what the system prompt shows — a missing key is a crash, not a refusal.

A device with no camera has two ways in, and both end in the same field:

  • paste the link — the field itself;
  • use an image — a screenshot of the code, decoded on the device. The host owns the file picker (a WebView file chooser would be a second permission path for something every shell already has), and the bytes never leave the machine.
Shell Image decoder
iOS, macOS CIDetector (CIDetectorTypeQRCode) — built in, and the round trip is pinned by a test that generates a code with CIFilter.qrCodeGenerator and reads it back
Android, Windows, Linux the shared page's own decoder, handed a data: URL by the host

The QR is drawn at an integer number of pixels per module (span × max(3, floor(340 / span))). Measured: a 260 px capture of the dialog failed to decode ("no QR code found") while the same code at 4 px per module decoded every time — a fractional size makes the browser antialias every module edge, which is what a binarizer cannot read.

Why a cookie and not a bearer header

A webview cannot attach an Authorization header to its own page requests, its WebSocket upgrades, or its image loads. A cookie is the one credential the platform sends on all of them. The gate accepts the token either way — Authorization: Bearer for a script, kabmo_device for a browser.

Two credentials, two lifetimes

A paired device holds a device token; a password login holds a session cookie. They are not the same thing, and confusing them is how a paired phone starts asking for a password again.

kabmo_device omp_session_<port>
Issued by the pairing claim POST /api/auth/login
Lifetime none — only revocation ends it 12 h, or 7 days with "Remember this device"
Stored paired_devices.token_hash (SHA-256) stateless HMAC, no row
Ends when the device is revoked in Settings → Connect the TTL passes, the password changes, or POST /api/auth/revoke

So the 7-day rule is the password session's, not the device's. A paired device never needs to scan again and never needs the password: the gate accepts its token on every request, and the token has no expiry in the database.

The cookie must be persistent, and that was a bug. Without Max-Age a cookie is a SESSION cookie, which the browser drops when it closes — so a paired phone asked for a password the next morning, and the whole point of pairing is that it does not. The claim now sets Max-Age=34560000 (400 days, the longest Chrome honours); the token itself still never expires, so this is the browser's cap rather than a policy.

Verified against a live server: a jar holding ONLY kabmo_device answers 200 on /api/connect/status and the console document reports "authenticated":true.

serverId

Derived from a random key persisted in <data>/connect-identity.json (mode 0600), so it survives a restart, a port change and a LAN address change — the three things that must not invalidate a pairing. It is published on /api/health and in the pairing payload. A device pins it and refuses an address that answers with a different one, which is what stops a LAN address reassigned by DHCP from receiving the device's token.

Revocation

DELETE /api/connect/devices?id=… sets revoked_at and drops the hash from the in-memory cache, so the next request fails at the gate. Verified end to end: a token that answered 200 answers 401 immediately after the revoke, in both the bearer and the cookie form.

Last connect

The device table's Last connect column is paired_devices.last_seen_at, and the auth gate is what writes it: every request that verifies a device token calls markDeviceConnected. The write is throttled in memory to one UPDATE per device per minute, because the gate runs on every page, frame and WebSocket upgrade — without the throttle the column would cost a database write per frame. The gate awaits that single write, so the row is current by the time the request returns.

This is a report of use, not of pairing. No shell reports anything after redeeming a code, so a timestamp written only by the claim route would show the pairing date on a phone that is open right now. A route report (POST /api/connect/devices) writes the same timestamp and seeds the throttle, so the gate does not follow it with a duplicate write inside the minute.

The cell shows relative and exact time (3 h ago · 18 Nov 2026, 14:32); a device that never came back reads "Never connected". Verified: a freshly paired device showed null, and one authenticated request populated the row before the response was returned.

The shells

The browser path pairs a browser tab. Every shell has its own cookie jar — Android's CookieManager, iOS's WKWebsiteDataStore, WebKitGTK, WebView2 — so pairing in Chrome leaves the app still asking for a password.

Each shell therefore has a Pairing link field: paste the link, and the shell loads it in its own web view, which puts the device cookie in its own jar. No camera permission, no scanner, no new dependency.

  • Android: PairingLink.originOf validates, ServerConfig.write stores the origin, and MainActivity.EXTRA_PAIR_LINK carries the link to the web view.
  • iOS: PairingLink.origin(of:) and SettingsViewController.onPair do the same.

Fallback when the active address dies

A phone that paired at home and then left the network keeps the LAN address as its active row, and the load fails with nothing but an error page. The other stored addresses are probed in parallel (GET /api/health, 1.5 s timeout) and the best reachable one is loaded instead. Attempted once per failure, so two dead addresses cannot start a probe loop; the flag clears on a successful load.

The probe cannot live in the page: https → http is mixed content, and /api/health carries no CORS headers. That is why tier.ts has no TypeScript caller and the shells port it.

Rate limiting behind a tunnel

cloudflared and tailscale serve both connect from 127.0.0.1, so every client behind one shares a single socket address. Keying the login throttle on that address gave every client on the internet one shared budget: ten failures from an attacker locked the owner out for fifteen minutes.

effectiveClientAddress therefore reads x-forwarded-for only when the socket itself is loopback. A remote attacker cannot make their own socket address loopback, and a local process that can forge the header already has the machine. A direct remote connection still keys on its own socket address, which a caller cannot forge.

Verification

Claim How
Pairing end to end live server: mint → claim → cookie → 200 → revoke → 401
/pair is public and sets the cookie 200 text/html, Set-Cookie: kabmo_device=…; HttpOnly; SameSite=Lax
The page renders Chromium at 1440×900 and 390×844: QR, countdown, routes, device table, revoke
The QR is scannable qr.roundtrip.test.ts decodes the server's own matrix with the same jsQR the page uses, including the widest payload
Tailscale CLI parsing stand-in binary answering the real JSON shapes
cloudflared lifecycle stand-in binary that records its argv and the config it was handed: runtime copy names this port, --config points at the copy, the copy is gone after stop; start, reuse, stop, spawn failure
cloudflared config path cloudflared-config.test.ts: saved path wins over env, empty resets, relative/missing/hostname-less files are refused; tunnels.test.ts: the route refuses those same shapes and stops a running tunnel when the path changes
Route order tier.test.ts, RouteChoiceTest.kt, RouteChoiceTests.swift — the same cases in three languages
Rate limit rate-limit.test.ts: a LAN socket ignores the header, a loopback socket uses it

Clone this wiki locally