From 51ef1c250b0180b656f7db785199a9a0c57b9a74 Mon Sep 17 00:00:00 2001 From: yuez Date: Fri, 23 Oct 2026 08:34:48 +0800 Subject: [PATCH] feat(web): consume the :PiWeb login handoff before the first route The daemon hands the browser `http://127.0.0.1:/#t=`. The token is read once, stored through the connection store (so the `pi2-connection` marker is set too and a fresh browser does not bounce to /connect), and stripped from the address bar and history while the query string survives. --- web/src/lib/handoff.ts | 65 +++++++++++++++++++++++ web/src/main.tsx | 10 ++++ web/tests/handoff.test.ts | 109 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 184 insertions(+) create mode 100644 web/src/lib/handoff.ts create mode 100644 web/tests/handoff.test.ts diff --git a/web/src/lib/handoff.ts b/web/src/lib/handoff.ts new file mode 100644 index 0000000..0d5c89c --- /dev/null +++ b/web/src/lib/handoff.ts @@ -0,0 +1,65 @@ +/** + * One-time login handoff for `:PiWeb`. + * + * The daemon opens `http://:/#t=` (or `#token=`). + * The token is read once, stored through the existing device-token helper and + * removed from the address bar/history before the router resolves its first + * route. Anything that is not a valid handoff is left untouched, so a bad + * link stays visibly broken instead of silently landing on `/connect`. + */ + +/** Fragment forms the daemon may hand off: `#t=` and `#token=`. */ +export const HANDOFF_HASH_PATTERN = /^(?:t|token)=(.+)$/; + +/** Device tokens are base64url-ish and at least 20 characters long. */ +export const HANDOFF_TOKEN_PATTERN = /^[A-Za-z0-9_-]{20,}$/; + +export interface HandoffLocation { + readonly hash: string; + readonly pathname: string; + readonly search: string; +} + +export interface HandoffHistory { + replaceState(data: unknown, unused: string, url?: string | URL | null): void; +} + +export type HandoffTokenSink = (token: string | null) => void; + +/** + * Extract a valid handoff token from a location hash. Returns `null` for any + * other fragment, including malformed percent-encoding. + */ +export function readHandoff(hash: string): string | null { + if (!hash) return null; + const fragment = hash.startsWith("#") ? hash.slice(1) : hash; + const match = HANDOFF_HASH_PATTERN.exec(fragment); + const encoded = match?.[1]; + if (!encoded) return null; + + let token: string; + try { + token = decodeURIComponent(encoded); + } catch { + return null; + } + return HANDOFF_TOKEN_PATTERN.test(token) ? token : null; +} + +/** + * Store a handoff token and strip the fragment while keeping the path and + * query string. No-ops (and never writes history) when the hash is not a + * valid handoff. + */ +export function consumeHandoff( + location: HandoffLocation, + history: HandoffHistory, + setToken: HandoffTokenSink, +): string | null { + const token = readHandoff(location.hash); + if (!token) return null; + + setToken(token); + history.replaceState(null, "", location.pathname + location.search); + return token; +} diff --git a/web/src/main.tsx b/web/src/main.tsx index 2d16e57..b36a544 100644 --- a/web/src/main.tsx +++ b/web/src/main.tsx @@ -8,7 +8,9 @@ import "@/styles/app.css"; import "@/lib/i18n"; import { Toaster } from "@/components/ui/toast"; +import { consumeHandoff } from "@/lib/handoff"; import { router } from "@/router"; +import { useConnectionStore } from "@/stores/connection"; const queryClient = new QueryClient({ defaultOptions: { @@ -39,6 +41,14 @@ function App() { ); } +// `:PiWeb` hands the device token over in the fragment. Consume it before the +// router resolves its first route, and go through the connection store (not +// `setDeviceToken`) so the `pi2-connection` marker the guards read is set too: +// otherwise a fresh browser would still bounce to `/connect` on its first load. +consumeHandoff(window.location, window.history, (token) => { + useConnectionStore.getState().connect({ token, endpoint: window.location.origin }); +}); + const container = document.getElementById("root"); if (!container) throw new Error("Missing #root element"); createRoot(container).render(); diff --git a/web/tests/handoff.test.ts b/web/tests/handoff.test.ts new file mode 100644 index 0000000..442c3b0 --- /dev/null +++ b/web/tests/handoff.test.ts @@ -0,0 +1,109 @@ +import { describe, expect, it, vi } from "vitest"; + +import { setDeviceToken, TOKEN_STORAGE_KEY } from "@/lib/api"; +import { consumeHandoff, readHandoff } from "@/lib/handoff"; + +/** 23 characters, valid base64url alphabet. */ +const TOKEN = "AbC-dEf_GhI-jKl_MnO-123"; +const ENCODED_TOKEN = "AbC%2DdEf_GhI%2DjKl_MnO%2D123"; + +function locationWith(hash: string, pathname = "/workspaces", search = "") { + return { hash, pathname, search }; +} + +function historySpy() { + return { replaceState: vi.fn() }; +} + +describe("readHandoff", () => { + it("accepts the short `#t=` form", () => { + expect(readHandoff(`#t=${TOKEN}`)).toBe(TOKEN); + }); + + it("accepts the long `#token=` form", () => { + expect(readHandoff(`#token=${TOKEN}`)).toBe(TOKEN); + }); + + it("decodes URL-encoded token characters", () => { + expect(readHandoff(`#t=${ENCODED_TOKEN}`)).toBe(TOKEN); + expect(readHandoff(`#token=${encodeURIComponent("a".repeat(20))}`)).toBe("a".repeat(20)); + }); + + it("rejects anything that is not a valid handoff", () => { + for (const hash of [ + "", + "#", + "#t=", + "#t=tooshort", + `#t=${"a".repeat(19)}`, + "#token=tooshort", + `#x=${TOKEN}`, + `#t=${TOKEN}!`, + `#t=${TOKEN}&next=/workspaces`, + `#token=${encodeURIComponent(`Bearer ${TOKEN}`)}`, + "#t=%E0%A4%A", + "#pair/ABCD1234", + ]) { + expect(readHandoff(hash), hash).toBeNull(); + } + expect(readHandoff(`#t=${"a".repeat(20)}`)).toBe("a".repeat(20)); + }); +}); + +describe("consumeHandoff", () => { + it("stores the token and strips the hash exactly once", () => { + const history = historySpy(); + const setToken = vi.fn(); + + expect(consumeHandoff(locationWith(`#t=${TOKEN}`), history, setToken)).toBe(TOKEN); + expect(setToken).toHaveBeenCalledExactlyOnceWith(TOKEN); + expect(history.replaceState).toHaveBeenCalledTimes(1); + expect(history.replaceState).toHaveBeenCalledWith(null, "", "/workspaces"); + }); + + it("keeps the query string when stripping the hash", () => { + const history = historySpy(); + + consumeHandoff( + locationWith(`#token=${TOKEN}`, "/workspace/ws-1", "?next=%2Fchat%2F01a1&tab=todo"), + history, + vi.fn(), + ); + expect(history.replaceState).toHaveBeenCalledWith( + null, + "", + "/workspace/ws-1?next=%2Fchat%2F01a1&tab=todo", + ); + }); + + it("no-ops without a handoff hash (no history write, no token write)", () => { + for (const hash of ["", "#", "#t=tooshort", "#/pair/ABCD1234"]) { + const history = historySpy(); + const setToken = vi.fn(); + expect(consumeHandoff(locationWith(hash, "/workspaces", "?tab=devices"), history, setToken)).toBeNull(); + expect(history.replaceState, hash).not.toHaveBeenCalled(); + expect(setToken, hash).not.toHaveBeenCalled(); + } + }); + + it("works against the real location/history and the shared token storage", () => { + window.history.replaceState(null, "", `/workspaces?tab=devices#t=${TOKEN}`); + const replaceState = vi.spyOn(window.history, "replaceState"); + + expect(consumeHandoff(window.location, window.history, setDeviceToken)).toBe(TOKEN); + + expect(localStorage.getItem(TOKEN_STORAGE_KEY)).toBe(`Bearer ${TOKEN}`); + expect(window.location.hash).toBe(""); + expect(`${window.location.pathname}${window.location.search}`).toBe("/workspaces?tab=devices"); + expect(replaceState).toHaveBeenCalledTimes(1); + }); + + it("leaves a broken link visibly broken", () => { + window.history.replaceState(null, "", "/workspaces#t=tooshort"); + const setToken = vi.fn(); + + expect(consumeHandoff(window.location, window.history, setToken)).toBeNull(); + expect(setToken).not.toHaveBeenCalled(); + expect(window.location.hash).toBe("#t=tooshort"); + }); +});