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:
Ilia Denisov
2026-05-07 15:24:21 +02:00
parent 390ad3196b
commit 22b0710d04
24 changed files with 2125 additions and 48 deletions
+163
View File
@@ -0,0 +1,163 @@
// Thin wrappers around the gateway public auth REST surface used by
// the email-code login flow. The two exported functions correspond
// 1:1 to the OpenAPI operations defined in
// `backend/openapi.yaml`:
//
// POST /api/v1/public/auth/send-email-code
// POST /api/v1/public/auth/confirm-email-code
//
// Both endpoints are unauthenticated — the device session does not
// exist yet during send-code, and confirm-code is the call that
// creates one. Persisting the returned `device_session_id` is the
// caller's responsibility (see `lib/session-store.svelte.ts`).
//
// `Accept-Language` is set automatically by the browser; the gateway
// reads it for the auth-mail localisation. We do not duplicate the
// value into the optional `locale` body field.
const SEND_EMAIL_CODE_PATH = "/api/v1/public/auth/send-email-code";
const CONFIRM_EMAIL_CODE_PATH = "/api/v1/public/auth/confirm-email-code";
export interface SendEmailCodeResult {
challengeId: string;
}
export interface ConfirmEmailCodeInput {
challengeId: string;
code: string;
publicKey: Uint8Array;
timeZone: string;
}
export interface ConfirmEmailCodeResult {
deviceSessionId: string;
}
/**
* AuthError is thrown by `sendEmailCode` and `confirmEmailCode` for
* every non-2xx gateway response. `code` mirrors the stable
* machine-readable identifier from the gateway error envelope
* (`invalid_request`, `service_unavailable`, `internal_error`, ...);
* `status` is the HTTP status that produced the error.
*/
export class AuthError extends Error {
readonly code: string;
readonly status: number;
constructor(code: string, message: string, status: number) {
super(message);
this.name = "AuthError";
this.code = code;
this.status = status;
}
}
/**
* sendEmailCode issues a login challenge for `email`. The gateway
* returns the same opaque `challenge_id` shape regardless of whether
* the address belongs to a new, existing, or throttled account, so
* the caller cannot use the response to enumerate accounts.
*/
export async function sendEmailCode(
baseUrl: string,
email: string,
): Promise<SendEmailCodeResult> {
const response = await fetch(joinUrl(baseUrl, SEND_EMAIL_CODE_PATH), {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ email }),
});
if (!response.ok) {
throw await readAuthError(response);
}
const body = (await response.json()) as { challenge_id?: unknown };
if (typeof body.challenge_id !== "string" || body.challenge_id.length === 0) {
throw new AuthError(
"internal_error",
"gateway returned a malformed send-email-code response",
response.status,
);
}
return { challengeId: body.challenge_id };
}
/**
* confirmEmailCode submits the verification code and the device's
* Ed25519 public key. On success the gateway returns the new device
* session identifier; persistence of that identifier is the caller's
* responsibility.
*/
export async function confirmEmailCode(
baseUrl: string,
input: ConfirmEmailCodeInput,
): Promise<ConfirmEmailCodeResult> {
const response = await fetch(joinUrl(baseUrl, CONFIRM_EMAIL_CODE_PATH), {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
challenge_id: input.challengeId,
code: input.code,
client_public_key: encodeBase64(input.publicKey),
time_zone: input.timeZone,
}),
});
if (!response.ok) {
throw await readAuthError(response);
}
const body = (await response.json()) as { device_session_id?: unknown };
if (
typeof body.device_session_id !== "string" ||
body.device_session_id.length === 0
) {
throw new AuthError(
"internal_error",
"gateway returned a malformed confirm-email-code response",
response.status,
);
}
return { deviceSessionId: body.device_session_id };
}
async function readAuthError(response: Response): Promise<AuthError> {
let code = "";
let message = "";
try {
const body = (await response.json()) as {
error?: { code?: unknown; message?: unknown };
};
const err = body.error;
if (err && typeof err.code === "string") {
code = err.code;
}
if (err && typeof err.message === "string") {
message = err.message;
}
} catch {
// Body was not JSON or could not be parsed; fall through to
// generic defaults below.
}
if (code.length === 0) {
code = response.status >= 500 ? "internal_error" : "invalid_request";
}
if (message.length === 0) {
message =
response.status >= 500
? "service is temporarily unavailable"
: `request rejected (${response.status})`;
}
return new AuthError(code, message, response.status);
}
function joinUrl(baseUrl: string, path: string): string {
const trimmedBase = baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl;
const trimmedPath = path.startsWith("/") ? path : `/${path}`;
return `${trimmedBase}${trimmedPath}`;
}
function encodeBase64(bytes: Uint8Array): string {
let binary = "";
for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i]!);
}
return btoa(binary);
}
+47
View File
@@ -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;
}
+157
View File
@@ -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)}`;
}
+173
View File
@@ -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();
+66 -1
View File
@@ -1,5 +1,70 @@
<script lang="ts">
import { onMount } from "svelte";
import { goto } from "$app/navigation";
import { page } from "$app/state";
import { session } from "$lib/session-store.svelte";
import { startRevocationWatcher } from "$lib/revocation-watcher";
let { children } = $props();
let stopWatcher: (() => void) | null = null;
onMount(() => {
void session.init();
return () => {
if (stopWatcher !== null) {
stopWatcher();
stopWatcher = null;
}
};
});
$effect(() => {
if (session.status === "authenticated" && stopWatcher === null) {
stopWatcher = startRevocationWatcher();
} else if (session.status !== "authenticated" && stopWatcher !== null) {
stopWatcher();
stopWatcher = null;
}
const pathname = page.url.pathname;
// Debug-only routes under /__debug/* run their own bootstrap
// path against the storage primitives and must bypass the
// auth guard so Phase 6's Playwright spec can drive the
// keystore directly.
if (pathname.startsWith("/__debug/")) {
return;
}
if (session.status === "anonymous" && pathname !== "/login") {
void goto("/login", { replaceState: true });
} else if (session.status === "authenticated" && pathname === "/login") {
void goto("/lobby", { replaceState: true });
}
});
</script>
{@render children()}
{#if session.status === "loading"}
<main class="status">
<p>loading…</p>
</main>
{:else if session.status === "unsupported"}
<main class="status">
<h1>browser not supported</h1>
<p>
Galaxy requires Ed25519 in WebCrypto. The minimum supported browser
versions are listed in the
<a href="https://github.com/galaxy/galaxy/blob/main/ui/docs/storage.md"
>storage topic doc</a
>.
</p>
</main>
{:else}
{@render children()}
{/if}
<style>
.status {
padding: 2rem;
font-family: system-ui, sans-serif;
}
</style>
+7
View File
@@ -0,0 +1,7 @@
// SPA mode: every route is rendered client-side, no SSR or
// prerendering. The static adapter serves `fallback: "index.html"` and
// the layout-level session bootstrap drives the rest of the app from
// the browser only.
export const ssr = false;
export const prerender = false;
+96
View File
@@ -0,0 +1,96 @@
<script lang="ts">
import { onMount } from "svelte";
import { createEdgeGatewayClient } from "../../api/connect";
import { GalaxyClient } from "../../api/galaxy-client";
import { GATEWAY_BASE_URL, GATEWAY_RESPONSE_PUBLIC_KEY } from "$lib/env";
import { loadCore } from "../../platform/core/index";
import { session } from "$lib/session-store.svelte";
let displayName: string | null = $state(null);
let accountError: string | null = $state(null);
let accountLoading = $state(true);
async function logout(): Promise<void> {
await session.signOut("user");
}
async function sha256(payload: Uint8Array): Promise<Uint8Array> {
const digest = await crypto.subtle.digest(
"SHA-256",
payload as BufferSource,
);
return new Uint8Array(digest);
}
onMount(async () => {
if (
session.keypair === null ||
session.deviceSessionId === null ||
GATEWAY_RESPONSE_PUBLIC_KEY.length === 0
) {
accountLoading = false;
if (GATEWAY_RESPONSE_PUBLIC_KEY.length === 0) {
accountError =
"VITE_GATEWAY_RESPONSE_PUBLIC_KEY is not configured";
}
return;
}
const keypair = session.keypair;
try {
const core = await loadCore();
const client = new GalaxyClient({
core,
edge: createEdgeGatewayClient(GATEWAY_BASE_URL),
signer: (canonical) => keypair.sign(canonical),
sha256,
deviceSessionId: session.deviceSessionId,
gatewayResponsePublicKey: GATEWAY_RESPONSE_PUBLIC_KEY,
});
const payload = await client.executeCommand(
"user.account.get",
new TextEncoder().encode("{}"),
);
const decoded = JSON.parse(new TextDecoder().decode(payload)) as {
account?: { display_name?: string; user_name?: string };
};
displayName =
decoded.account?.display_name ?? decoded.account?.user_name ?? null;
} catch (err) {
accountError = err instanceof Error ? err.message : "request failed";
} finally {
accountLoading = false;
}
});
</script>
<main>
<h1>you are logged in</h1>
<p>
device session id: <code data-testid="device-session-id"
>{session.deviceSessionId ?? ""}</code
>
</p>
{#if accountLoading}
<p>loading account…</p>
{:else if displayName !== null}
<p>
hello, <span data-testid="account-display-name">{displayName}</span>!
</p>
{:else if accountError !== null}
<p role="alert" data-testid="account-error">{accountError}</p>
{/if}
<button onclick={logout} data-testid="lobby-logout">logout</button>
</main>
<style>
main {
padding: 2rem;
font-family: system-ui, sans-serif;
}
button {
font-size: 1rem;
padding: 0.5rem 1rem;
margin-top: 1rem;
}
</style>
+6
View File
@@ -0,0 +1,6 @@
// Lobby is the first authenticated screen and depends on the
// session keypair plus the WASM core loaded at runtime; SSR and
// prerendering stay disabled.
export const ssr = false;
export const prerender = false;
+237
View File
@@ -0,0 +1,237 @@
<script lang="ts">
import { goto } from "$app/navigation";
import {
AuthError,
confirmEmailCode,
sendEmailCode,
} from "../../api/auth";
import { GATEWAY_BASE_URL } from "$lib/env";
import { session } from "$lib/session-store.svelte";
type Step = "email" | "code";
let step: Step = $state("email");
let email = $state("");
let code = $state("");
let challengeId: string | null = $state(null);
let pending = $state(false);
let error: string | null = $state(null);
function describe(err: unknown): string {
if (err instanceof AuthError) {
return err.message;
}
if (err instanceof Error) {
return err.message;
}
return "request failed";
}
async function submitEmail(event: Event): Promise<void> {
event.preventDefault();
if (pending) return;
const trimmed = email.trim();
if (trimmed.length === 0) {
error = "email must not be empty";
return;
}
pending = true;
error = null;
try {
const result = await sendEmailCode(GATEWAY_BASE_URL, trimmed);
challengeId = result.challengeId;
code = "";
step = "code";
} catch (err) {
error = describe(err);
} finally {
pending = false;
}
}
async function submitCode(event: Event): Promise<void> {
event.preventDefault();
if (pending) return;
const trimmedCode = code.trim();
if (trimmedCode.length === 0) {
error = "code must not be empty";
return;
}
if (challengeId === null) {
error = "challenge expired, please request a new code";
step = "email";
return;
}
if (session.keypair === null) {
error = "device key is not ready, please reload the page";
return;
}
pending = true;
error = null;
try {
const result = await confirmEmailCode(GATEWAY_BASE_URL, {
challengeId,
code: trimmedCode,
publicKey: session.keypair.publicKey,
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
});
await session.signIn(result.deviceSessionId);
void goto("/lobby", { replaceState: true });
} catch (err) {
if (err instanceof AuthError && err.code === "invalid_request") {
challengeId = null;
code = "";
step = "email";
error = "code expired or already used, please request a new one";
} else {
error = describe(err);
}
} finally {
pending = false;
}
}
async function resend(): Promise<void> {
if (pending) return;
const trimmed = email.trim();
if (trimmed.length === 0) {
step = "email";
return;
}
pending = true;
error = null;
try {
const result = await sendEmailCode(GATEWAY_BASE_URL, trimmed);
challengeId = result.challengeId;
code = "";
} catch (err) {
error = describe(err);
} finally {
pending = false;
}
}
function changeEmail(): void {
challengeId = null;
code = "";
error = null;
step = "email";
}
</script>
<main>
<h1>sign in to Galaxy</h1>
{#if step === "email"}
<form onsubmit={submitEmail} aria-busy={pending}>
<label>
email
<input
type="email"
name="email"
autocomplete="email"
bind:value={email}
disabled={pending}
required
data-testid="login-email-input"
/>
</label>
<button
type="submit"
disabled={pending}
data-testid="login-email-submit"
>
{pending ? "sending…" : "send code"}
</button>
</form>
{:else}
<form onsubmit={submitCode} aria-busy={pending}>
<p data-testid="login-code-target">code sent to {email}</p>
<label>
code
<input
type="text"
name="code"
inputmode="numeric"
autocomplete="one-time-code"
bind:value={code}
disabled={pending}
required
data-testid="login-code-input"
/>
</label>
<button type="submit" disabled={pending} data-testid="login-code-submit">
{pending ? "verifying…" : "verify"}
</button>
<div class="secondary">
<button
type="button"
onclick={resend}
disabled={pending}
data-testid="login-resend"
>
send a new code
</button>
<button
type="button"
onclick={changeEmail}
disabled={pending}
data-testid="login-change-email"
>
change email
</button>
</div>
</form>
{/if}
{#if error !== null}
<p role="alert" data-testid="login-error">{error}</p>
{/if}
</main>
<style>
main {
padding: 2rem;
font-family: system-ui, sans-serif;
max-width: 32rem;
}
form {
display: flex;
flex-direction: column;
gap: 1rem;
margin-top: 1.5rem;
}
label {
display: flex;
flex-direction: column;
gap: 0.25rem;
font-size: 0.875rem;
}
input {
font-size: 1rem;
padding: 0.5rem;
}
button {
font-size: 1rem;
padding: 0.5rem 1rem;
}
.secondary {
display: flex;
gap: 0.5rem;
}
.secondary button {
font-size: 0.875rem;
padding: 0.25rem 0.75rem;
}
[role="alert"] {
margin-top: 1rem;
color: #b00020;
}
</style>
+6
View File
@@ -0,0 +1,6 @@
// Login depends on browser-only WebCrypto and IndexedDB through the
// session store; SSR and prerendering are disabled to keep the
// component out of the server-render pipeline.
export const ssr = false;
export const prerender = false;