phase 7: auth flow UI (email-code login + session resume + revocation)
Implements ui/PLAN.md Phase 7 end-to-end: - /login two-step form (email -> code) over the gateway public REST surface; /lobby placeholder issues the first authenticated user.account.get and renders the decoded display name. - SessionStore (Svelte 5 runes) with loading / unsupported / anonymous / authenticated states; layout-level route guard, browser-not-supported blocker, and a minimal SubscribeEvents revocation watcher that closes the active client within 1s on a clean stream end or Unauthenticated. - VITE_GATEWAY_BASE_URL + VITE_GATEWAY_RESPONSE_PUBLIC_KEY config plus AuthError taxonomy in api/auth.ts. - Vitest (auth-api, session-store, login-page) and Playwright e2e (auth-flow.spec.ts) on the four configured projects, with a fixture Ed25519 keypair forging Connect-Web JSON responses. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
// Build-time configuration for the Galaxy gateway. Both values arrive
|
||||
// through Vite `import.meta.env` and resolve to module-level constants
|
||||
// at the first import.
|
||||
//
|
||||
// `VITE_GATEWAY_BASE_URL` is the base URL of the gateway public REST
|
||||
// surface and the Connect-Web authenticated edge (same host, same
|
||||
// port; the gateway listener serves both). It defaults to the local
|
||||
// dev address used by `tools/local-ci` and the integration suite.
|
||||
//
|
||||
// `VITE_GATEWAY_RESPONSE_PUBLIC_KEY` is the gateway's response-signing
|
||||
// Ed25519 public key, encoded as standard (non-URL-safe) base64 of
|
||||
// the raw 32-byte key. Decoded once on module load and exported as
|
||||
// `Uint8Array`. The value is only consumed by [GalaxyClient] when a
|
||||
// signed unary call is dispatched; the unauthenticated routes do not
|
||||
// need it. An empty or malformed value therefore does not block app
|
||||
// boot — it surfaces only when the lobby route opens its first
|
||||
// authenticated call.
|
||||
|
||||
const RAW_BASE_URL: string =
|
||||
(import.meta.env.VITE_GATEWAY_BASE_URL as string | undefined) ??
|
||||
"http://localhost:8080";
|
||||
|
||||
const RAW_RESPONSE_PUBLIC_KEY: string =
|
||||
(import.meta.env.VITE_GATEWAY_RESPONSE_PUBLIC_KEY as string | undefined) ??
|
||||
"";
|
||||
|
||||
export const GATEWAY_BASE_URL: string = stripTrailingSlash(RAW_BASE_URL);
|
||||
|
||||
export const GATEWAY_RESPONSE_PUBLIC_KEY: Uint8Array = decodeBase64(
|
||||
RAW_RESPONSE_PUBLIC_KEY,
|
||||
);
|
||||
|
||||
function stripTrailingSlash(url: string): string {
|
||||
return url.endsWith("/") ? url.slice(0, -1) : url;
|
||||
}
|
||||
|
||||
function decodeBase64(value: string): Uint8Array {
|
||||
if (value.length === 0) {
|
||||
return new Uint8Array();
|
||||
}
|
||||
const binary = atob(value);
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let i = 0; i < binary.length; i++) {
|
||||
bytes[i] = binary.charCodeAt(i);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
// `startRevocationWatcher` opens an authenticated SubscribeEvents
|
||||
// stream against the gateway and treats any non-aborted termination
|
||||
// as a session-revocation signal: the watcher calls
|
||||
// `session.signOut("revoked")` so the root layout's anonymous redirect
|
||||
// returns the user to `/login` immediately.
|
||||
//
|
||||
// Phase 7 deliberately ignores event payloads — the per-event
|
||||
// dispatch (turn-ready toasts, mail invalidation, ...) lands in
|
||||
// Phase 24. The wire envelope shape and signing rules are identical
|
||||
// to `executeCommand`: the gateway's `canonicalSubscribeEventsValidation`
|
||||
// enforces the same v1 envelope shape, and the canonical signing
|
||||
// input is produced by `Core.signRequest`. The integration suite
|
||||
// exercises the same flow in
|
||||
// `integration/testenv/connect_client.go::SubscribeEvents` with the
|
||||
// `gateway.subscribe` literal.
|
||||
|
||||
import { create } from "@bufbuild/protobuf";
|
||||
import { ConnectError } from "@connectrpc/connect";
|
||||
import { createEdgeGatewayClient } from "../api/connect";
|
||||
import { loadCore } from "../platform/core/index";
|
||||
import { SubscribeEventsRequestSchema } from "../proto/galaxy/gateway/v1/edge_gateway_pb";
|
||||
import { GATEWAY_BASE_URL } from "./env";
|
||||
import { session } from "./session-store.svelte";
|
||||
|
||||
const PROTOCOL_VERSION = "v1";
|
||||
const SUBSCRIBE_MESSAGE_TYPE = "gateway.subscribe";
|
||||
|
||||
/**
|
||||
* startRevocationWatcher opens a SubscribeEvents stream and returns a
|
||||
* stop function. Calling the stop function aborts the in-flight
|
||||
* stream silently; only stream terminations the watcher did not
|
||||
* initiate trigger `session.signOut("revoked")`.
|
||||
*/
|
||||
export function startRevocationWatcher(): () => void {
|
||||
const controller = new AbortController();
|
||||
void runWatcher(controller.signal);
|
||||
return () => controller.abort();
|
||||
}
|
||||
|
||||
async function runWatcher(signal: AbortSignal): Promise<void> {
|
||||
if (
|
||||
session.status !== "authenticated" ||
|
||||
session.keypair === null ||
|
||||
session.deviceSessionId === null
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const keypair = session.keypair;
|
||||
const deviceSessionId = session.deviceSessionId;
|
||||
|
||||
let stream: AsyncIterable<unknown>;
|
||||
try {
|
||||
const core = await loadCore();
|
||||
const requestId =
|
||||
typeof crypto.randomUUID === "function"
|
||||
? crypto.randomUUID()
|
||||
: fallbackRequestId();
|
||||
const timestampMs = BigInt(Date.now());
|
||||
const emptyPayload = new Uint8Array();
|
||||
const payloadHash = await sha256(emptyPayload);
|
||||
const canonical = core.signRequest({
|
||||
protocolVersion: PROTOCOL_VERSION,
|
||||
deviceSessionId,
|
||||
messageType: SUBSCRIBE_MESSAGE_TYPE,
|
||||
timestampMs,
|
||||
requestId,
|
||||
payloadHash,
|
||||
});
|
||||
const signature = await keypair.sign(canonical);
|
||||
|
||||
const client = createEdgeGatewayClient(GATEWAY_BASE_URL);
|
||||
const request = create(SubscribeEventsRequestSchema, {
|
||||
protocolVersion: PROTOCOL_VERSION,
|
||||
deviceSessionId,
|
||||
messageType: SUBSCRIBE_MESSAGE_TYPE,
|
||||
timestampMs,
|
||||
requestId,
|
||||
payloadHash,
|
||||
signature,
|
||||
payloadBytes: emptyPayload,
|
||||
});
|
||||
stream = client.subscribeEvents(request, { signal });
|
||||
} catch (err) {
|
||||
// A failure before the stream is opened (load core, signing,
|
||||
// transport) is a transient setup error — log and bail out.
|
||||
// Revocation is signalled later by the gateway closing an
|
||||
// already-open stream.
|
||||
if (!signal.aborted) {
|
||||
console.info("session store: failed to open subscribe-events", err);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
for await (const _event of stream) {
|
||||
void _event;
|
||||
}
|
||||
} catch (err) {
|
||||
// Stream errors arrive on three different paths:
|
||||
// 1. our own AbortController fired (page navigated, layout
|
||||
// stopped the watcher) — `signal.aborted` is true;
|
||||
// 2. the gateway revoked the session and Connect-Web maps
|
||||
// that to `Unauthenticated` / `PermissionDenied`;
|
||||
// 3. transient network failure (Wi-Fi drop, server
|
||||
// restart) — anything else.
|
||||
//
|
||||
// Only branch 2 is a true revocation. Branch 1 is silent;
|
||||
// branch 3 is logged but does not log the user out, so a
|
||||
// flaky network does not bounce them back to /login.
|
||||
if (signal.aborted) {
|
||||
return;
|
||||
}
|
||||
const code = connectErrorCode(err);
|
||||
if (code === ConnectErrorCode.Unauthenticated) {
|
||||
await session.signOut("revoked");
|
||||
return;
|
||||
}
|
||||
console.info("session store: subscribe-events stream errored", err);
|
||||
return;
|
||||
}
|
||||
// Clean end-of-stream from the gateway is the documented
|
||||
// `session_invalidation` signal: backend closes the push stream
|
||||
// once the device session flips to revoked.
|
||||
if (!signal.aborted && session.status === "authenticated") {
|
||||
await session.signOut("revoked");
|
||||
}
|
||||
}
|
||||
|
||||
const ConnectErrorCode = {
|
||||
Canceled: 1,
|
||||
Unauthenticated: 16,
|
||||
} as const;
|
||||
|
||||
function connectErrorCode(err: unknown): number | null {
|
||||
if (err instanceof ConnectError) {
|
||||
return err.code;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function sha256(payload: Uint8Array): Promise<Uint8Array> {
|
||||
const digest = await crypto.subtle.digest(
|
||||
"SHA-256",
|
||||
payload as BufferSource,
|
||||
);
|
||||
return new Uint8Array(digest);
|
||||
}
|
||||
|
||||
function fallbackRequestId(): string {
|
||||
const buf = new Uint8Array(16);
|
||||
crypto.getRandomValues(buf);
|
||||
let hex = "";
|
||||
for (let i = 0; i < buf.length; i++) {
|
||||
hex += buf[i]!.toString(16).padStart(2, "0");
|
||||
}
|
||||
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
// `SessionStore` is the single source of truth for the device
|
||||
// session state across every authenticated UI surface. It owns the
|
||||
// lifecycle of the WebCrypto keypair (loaded or generated through
|
||||
// the `KeyStore`), the persisted `device_session_id` (read/written
|
||||
// through the `Cache`), and the high-level status that the root
|
||||
// layout uses to gate routing.
|
||||
//
|
||||
// The store runs in two stages: `init()` loads the persisted
|
||||
// keypair and session id, sanity-checks WebCrypto Ed25519 support,
|
||||
// and settles `status` into one of `unsupported`, `anonymous`, or
|
||||
// `authenticated`. Callers (the login form, the lobby) drive the
|
||||
// rest through `signIn` and `signOut`.
|
||||
//
|
||||
// `signOut("revoked")` is a separate code path because gateway-side
|
||||
// session revocation closes the SubscribeEvents stream
|
||||
// asynchronously; the watcher in `lib/revocation-watcher.ts` calls
|
||||
// it without user interaction. The post-condition is the same as
|
||||
// `signOut("user")` — keypair regenerated, session id wiped,
|
||||
// status returned to `anonymous` — so the layout's existing
|
||||
// `anonymous → /login` redirect handles both reasons uniformly.
|
||||
|
||||
import type {
|
||||
Cache,
|
||||
DeviceKeypair,
|
||||
KeyStore,
|
||||
StoreLoader,
|
||||
} from "../platform/store/index";
|
||||
import { loadStore } from "../platform/store/index";
|
||||
import {
|
||||
clearDeviceSession,
|
||||
loadDeviceSession,
|
||||
setDeviceSessionId,
|
||||
} from "../api/session";
|
||||
|
||||
export type SessionStatus =
|
||||
| "loading"
|
||||
| "unsupported"
|
||||
| "anonymous"
|
||||
| "authenticated";
|
||||
|
||||
export class SessionStore {
|
||||
status: SessionStatus = $state("loading");
|
||||
keypair: DeviceKeypair | null = $state(null);
|
||||
deviceSessionId: string | null = $state(null);
|
||||
|
||||
private initPromise: Promise<void> | null = null;
|
||||
private keyStore: KeyStore | null = null;
|
||||
private cache: Cache | null = null;
|
||||
private supportProbe: () => Promise<boolean> = defaultSupportProbe;
|
||||
private storeLoader: StoreLoader = loadStore;
|
||||
|
||||
/**
|
||||
* init loads the persisted keypair and device-session id, runs a
|
||||
* one-time WebCrypto Ed25519 sanity check, and settles `status`.
|
||||
* Calling it multiple times is safe — the first call drives the
|
||||
* actual work; subsequent calls await the same promise.
|
||||
*/
|
||||
init(): Promise<void> {
|
||||
if (this.initPromise === null) {
|
||||
this.initPromise = this.doInit();
|
||||
}
|
||||
return this.initPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* signIn persists the device-session id returned by the
|
||||
* confirm-email-code response and flips the status to
|
||||
* `authenticated`. The keypair already lives in the store from
|
||||
* `init()`.
|
||||
*/
|
||||
async signIn(deviceSessionId: string): Promise<void> {
|
||||
if (this.cache === null) {
|
||||
throw new Error("session store: signIn called before init");
|
||||
}
|
||||
await setDeviceSessionId(this.cache, deviceSessionId);
|
||||
this.deviceSessionId = deviceSessionId;
|
||||
this.status = "authenticated";
|
||||
}
|
||||
|
||||
/**
|
||||
* signOut wipes the keypair and the persisted device-session id,
|
||||
* generates a fresh keypair so the next login does not reuse the
|
||||
* revoked public key, and returns the status to `anonymous`. The
|
||||
* `reason` is recorded in console output for telemetry but does
|
||||
* not change the post-state — both user-driven logout and
|
||||
* gateway-driven revocation land the user back on `/login`.
|
||||
*/
|
||||
async signOut(reason: "user" | "revoked"): Promise<void> {
|
||||
if (this.keyStore === null || this.cache === null) {
|
||||
throw new Error("session store: signOut called before init");
|
||||
}
|
||||
await clearDeviceSession(this.keyStore, this.cache);
|
||||
const fresh = await loadDeviceSession(this.keyStore, this.cache);
|
||||
this.keypair = fresh.keypair;
|
||||
this.deviceSessionId = null;
|
||||
this.status = "anonymous";
|
||||
if (reason === "revoked") {
|
||||
console.info("session store: device session revoked by gateway");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* setSupportProbeForTests overrides the WebCrypto Ed25519 probe.
|
||||
* Production code calls the real `crypto.subtle.generateKey`; tests
|
||||
* can swap in a deterministic stub.
|
||||
*/
|
||||
setSupportProbeForTests(probe: () => Promise<boolean>): void {
|
||||
this.supportProbe = probe;
|
||||
}
|
||||
|
||||
/**
|
||||
* setStoreLoaderForTests overrides the storage adapter resolver.
|
||||
* Production code calls `loadStore()` from `platform/store`; tests
|
||||
* inject a per-test `KeyStore` + `Cache` pair backed by a unique
|
||||
* IndexedDB name so cases stay independent.
|
||||
*/
|
||||
setStoreLoaderForTests(loader: StoreLoader): void {
|
||||
this.storeLoader = loader;
|
||||
}
|
||||
|
||||
/**
|
||||
* resetForTests forgets all persisted state on the instance so a
|
||||
* subsequent `init()` runs from scratch. Production code never
|
||||
* calls this; it exists only for the Vitest harness.
|
||||
*/
|
||||
resetForTests(): void {
|
||||
this.status = "loading";
|
||||
this.keypair = null;
|
||||
this.deviceSessionId = null;
|
||||
this.initPromise = null;
|
||||
this.keyStore = null;
|
||||
this.cache = null;
|
||||
this.supportProbe = defaultSupportProbe;
|
||||
this.storeLoader = loadStore;
|
||||
}
|
||||
|
||||
private async doInit(): Promise<void> {
|
||||
const supported = await this.supportProbe();
|
||||
if (!supported) {
|
||||
this.status = "unsupported";
|
||||
return;
|
||||
}
|
||||
const { keyStore, cache } = await this.storeLoader();
|
||||
this.keyStore = keyStore;
|
||||
this.cache = cache;
|
||||
const loaded = await loadDeviceSession(keyStore, cache);
|
||||
this.keypair = loaded.keypair;
|
||||
this.deviceSessionId = loaded.deviceSessionId;
|
||||
this.status =
|
||||
loaded.deviceSessionId === null ? "anonymous" : "authenticated";
|
||||
}
|
||||
}
|
||||
|
||||
async function defaultSupportProbe(): Promise<boolean> {
|
||||
if (
|
||||
typeof globalThis.crypto !== "object" ||
|
||||
typeof globalThis.crypto.subtle !== "object"
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
await globalThis.crypto.subtle.generateKey(
|
||||
{ name: "Ed25519" } as KeyAlgorithm,
|
||||
false,
|
||||
["sign", "verify"],
|
||||
);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export const session = new SessionStore();
|
||||
Reference in New Issue
Block a user