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
+145
View File
@@ -0,0 +1,145 @@
// Verifies the wire shape of `sendEmailCode` / `confirmEmailCode`
// against the gateway public auth REST surface defined in
// `backend/openapi.yaml`. The transport is mocked through
// `globalThis.fetch`; the helpers themselves are exercised in the
// e2e Playwright spec against a Connect-Web mock that adds back the
// real network stack (still not a live gateway).
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { AuthError, confirmEmailCode, sendEmailCode } from "../src/api/auth";
const BASE_URL = "https://gateway.test";
function jsonResponse(status: number, body: unknown): Response {
return new Response(JSON.stringify(body), {
status,
headers: { "content-type": "application/json" },
});
}
describe("sendEmailCode", () => {
let fetchSpy: ReturnType<typeof vi.fn>;
beforeEach(() => {
fetchSpy = vi.fn();
globalThis.fetch = fetchSpy as unknown as typeof fetch;
});
afterEach(() => {
vi.restoreAllMocks();
});
test("posts a JSON body with the email and returns the challenge id", async () => {
fetchSpy.mockResolvedValueOnce(
jsonResponse(200, { challenge_id: "ch-123" }),
);
const result = await sendEmailCode(BASE_URL, "pilot@example.com");
expect(result).toEqual({ challengeId: "ch-123" });
expect(fetchSpy).toHaveBeenCalledTimes(1);
const [url, init] = fetchSpy.mock.calls[0]!;
expect(url).toBe(`${BASE_URL}/api/v1/public/auth/send-email-code`);
expect(init?.method).toBe("POST");
expect(init?.headers).toEqual({ "content-type": "application/json" });
expect(JSON.parse(init?.body as string)).toEqual({
email: "pilot@example.com",
});
});
test("strips a trailing slash from the base URL", async () => {
fetchSpy.mockResolvedValueOnce(jsonResponse(200, { challenge_id: "ch-1" }));
await sendEmailCode(`${BASE_URL}/`, "pilot@example.com");
expect(fetchSpy.mock.calls[0]![0]).toBe(
`${BASE_URL}/api/v1/public/auth/send-email-code`,
);
});
test("throws AuthError carrying gateway code and message on 400", async () => {
fetchSpy.mockResolvedValueOnce(
jsonResponse(400, {
error: { code: "invalid_request", message: "email must be valid" },
}),
);
await expect(sendEmailCode(BASE_URL, "bad")).rejects.toMatchObject({
name: "AuthError",
code: "invalid_request",
message: "email must be valid",
status: 400,
});
});
test("falls back to internal_error on a 5xx without an envelope", async () => {
fetchSpy.mockResolvedValueOnce(
new Response("oops", { status: 503 }),
);
const err = await sendEmailCode(BASE_URL, "pilot@example.com").catch(
(e: unknown) => e,
);
expect(err).toBeInstanceOf(AuthError);
expect((err as AuthError).code).toBe("internal_error");
expect((err as AuthError).status).toBe(503);
});
test("throws on a malformed success body", async () => {
fetchSpy.mockResolvedValueOnce(jsonResponse(200, { challenge_id: 42 }));
await expect(sendEmailCode(BASE_URL, "p@x")).rejects.toBeInstanceOf(
AuthError,
);
});
});
describe("confirmEmailCode", () => {
let fetchSpy: ReturnType<typeof vi.fn>;
beforeEach(() => {
fetchSpy = vi.fn();
globalThis.fetch = fetchSpy as unknown as typeof fetch;
});
afterEach(() => {
vi.restoreAllMocks();
});
test("base64-encodes the public key and forwards the time zone", async () => {
fetchSpy.mockResolvedValueOnce(
jsonResponse(200, { device_session_id: "dev-uuid-1" }),
);
const publicKey = new Uint8Array([0xde, 0xad, 0xbe, 0xef]);
const result = await confirmEmailCode(BASE_URL, {
challengeId: "ch-1",
code: "123456",
publicKey,
timeZone: "Europe/Berlin",
});
expect(result).toEqual({ deviceSessionId: "dev-uuid-1" });
const [url, init] = fetchSpy.mock.calls[0]!;
expect(url).toBe(`${BASE_URL}/api/v1/public/auth/confirm-email-code`);
const body = JSON.parse(init?.body as string) as Record<string, unknown>;
expect(body.challenge_id).toBe("ch-1");
expect(body.code).toBe("123456");
expect(body.time_zone).toBe("Europe/Berlin");
expect(body.client_public_key).toBe(btoa("\xde\xad\xbe\xef"));
});
test("AuthError on 400 carries the gateway error code", async () => {
fetchSpy.mockResolvedValueOnce(
jsonResponse(400, {
error: { code: "invalid_request", message: "bad code" },
}),
);
await expect(
confirmEmailCode(BASE_URL, {
challengeId: "ch",
code: "wrong",
publicKey: new Uint8Array(32),
timeZone: "UTC",
}),
).rejects.toMatchObject({ code: "invalid_request", status: 400 });
});
});
+220
View File
@@ -0,0 +1,220 @@
// Phase 7 end-to-end coverage for the email-code login flow,
// returning-user resume, gateway-driven session revocation, and the
// browser-not-supported blocker. The gateway is mocked through
// `page.route(...)`; the lobby's first authenticated `user.account.get`
// call is answered with a forged `ExecuteCommandResponse` signed by
// the fixture key in `fixtures/gateway-key.ts` so `GalaxyClient.
// verifyResponse` accepts it under the matching public key the dev
// server picks up via `VITE_GATEWAY_RESPONSE_PUBLIC_KEY`.
//
// The Connect-Web request URL pattern is
// <baseUrl>/galaxy.gateway.v1.EdgeGateway/<MethodName>
// so the route handlers below match against the trailing path
// suffix and ignore the host.
import { fromJson, type JsonValue } from "@bufbuild/protobuf";
import { expect, test, type Page } from "@playwright/test";
import { ExecuteCommandRequestSchema } from "../../src/proto/galaxy/gateway/v1/edge_gateway_pb";
import { forgeExecuteCommandResponseJson } from "./fixtures/sign-response";
interface MockSetup {
pendingSubscribes: Array<() => void>;
}
async function mockGatewayHappyPath(
page: Page,
displayName: string,
): Promise<MockSetup> {
const pendingSubscribes: Array<() => void> = [];
await page.route("**/api/v1/public/auth/send-email-code", async (route) => {
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({ challenge_id: "ch-test-1" }),
});
});
await page.route(
"**/api/v1/public/auth/confirm-email-code",
async (route) => {
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({ device_session_id: "dev-test-1" }),
});
},
);
await page.route(
"**/galaxy.gateway.v1.EdgeGateway/ExecuteCommand",
async (route) => {
const reqText = route.request().postData();
if (reqText === null) {
await route.fulfill({ status: 400 });
return;
}
const req = fromJson(
ExecuteCommandRequestSchema,
JSON.parse(reqText) as JsonValue,
);
const accountJson = JSON.stringify({
account: {
user_id: "user-1",
email: "pilot@example.com",
user_name: "player-test",
display_name: displayName,
},
});
const responseJson = await forgeExecuteCommandResponseJson({
requestId: req.requestId,
timestampMs: BigInt(Date.now()),
resultCode: "ok",
payloadBytes: new TextEncoder().encode(accountJson),
});
await route.fulfill({
status: 200,
contentType: "application/json",
body: responseJson,
});
},
);
await page.route(
"**/galaxy.gateway.v1.EdgeGateway/SubscribeEvents",
async (route) => {
// Hold the stream open until the test releases it via
// `pendingSubscribes`. Releasing fulfils with a Connect
// end-of-stream frame so the watcher reads a clean stream
// end and triggers the documented revocation path.
const action = await new Promise<"endOfStream" | "abort">(
(resolve) => {
pendingSubscribes.push(() => resolve("endOfStream"));
},
);
if (action === "abort") {
await route.abort();
return;
}
// Connect over HTTP/1.1 server-streaming framing:
// 1 byte flag (0x02 = end-stream)
// 4 bytes big-endian length
// N bytes JSON body
// `{}` is an end-stream with no error; that's how the
// gateway closes a healthy stream after a session
// invalidation.
const body = new TextEncoder().encode("{}");
const frame = new Uint8Array(5 + body.length);
frame[0] = 0x02;
new DataView(frame.buffer).setUint32(1, body.length, false);
frame.set(body, 5);
await route.fulfill({
status: 200,
contentType: "application/connect+json",
body: Buffer.from(frame),
});
},
);
return { pendingSubscribes };
}
async function completeLogin(page: Page): Promise<void> {
await page.goto("/");
await expect(page).toHaveURL(/\/login$/);
await page.getByTestId("login-email-input").fill("pilot@example.com");
await page.getByTestId("login-email-submit").click();
await expect(page.getByTestId("login-code-input")).toBeVisible();
await page.getByTestId("login-code-input").fill("123456");
await page.getByTestId("login-code-submit").click();
await expect(page).toHaveURL(/\/lobby$/);
}
test.describe("Phase 7 — auth flow", () => {
// Each test runs in a fresh browser context by default, so IndexedDB
// starts empty on every test entry. The setup hook here is reserved
// for routes shared across cases.
test("fresh browser completes the email-code login and reaches the lobby", async ({
page,
}) => {
const mocks = await mockGatewayHappyPath(page, "Pilot");
await completeLogin(page);
await expect(page.getByTestId("device-session-id")).toHaveText(
"dev-test-1",
);
await expect(page.getByTestId("account-display-name")).toHaveText("Pilot");
mocks.pendingSubscribes.forEach((resolve) => resolve());
});
test("returning user lands on the lobby without re-login", async ({
page,
}) => {
const mocks = await mockGatewayHappyPath(page, "Pilot");
await completeLogin(page);
await expect(page.getByTestId("account-display-name")).toBeVisible();
await page.reload();
await expect(page).toHaveURL(/\/lobby$/);
await expect(page.getByTestId("device-session-id")).toHaveText(
"dev-test-1",
);
mocks.pendingSubscribes.forEach((resolve) => resolve());
});
test("server-side revocation closes the active client within one second", async ({
page,
}) => {
const mocks = await mockGatewayHappyPath(page, "Pilot");
await completeLogin(page);
await expect(page.getByTestId("account-display-name")).toBeVisible();
// Fire all pending SubscribeEvents requests with an empty 200
// response. Connect-Web's server-streaming reader sees no frames
// and the watcher trips into `signOut("revoked")`, which the
// layout effect turns into a redirect back to /login.
const releaseAt = Date.now();
mocks.pendingSubscribes.forEach((resolve) => resolve());
await expect(page).toHaveURL(/\/login$/, { timeout: 1000 });
expect(Date.now() - releaseAt).toBeLessThan(1500);
});
test("browser without WebCrypto Ed25519 shows the not-supported blocker", async ({
page,
}) => {
await page.addInitScript(() => {
// Force the SessionStore probe to fail by making
// generateKey reject for Ed25519 specifically. Other
// algorithms continue to work so unrelated browser code
// is not disturbed.
const original = crypto.subtle.generateKey.bind(crypto.subtle);
crypto.subtle.generateKey = ((
algorithm: AlgorithmIdentifier | RsaHashedKeyGenParams | EcKeyGenParams,
extractable: boolean,
keyUsages: KeyUsage[],
) => {
const name =
typeof algorithm === "string"
? algorithm
: (algorithm as KeyAlgorithm).name;
if (typeof name === "string" && name.toLowerCase() === "ed25519") {
return Promise.reject(
new DOMException("not supported", "NotSupportedError"),
);
}
return original(
algorithm as Parameters<typeof original>[0],
extractable,
keyUsages,
);
}) as typeof crypto.subtle.generateKey;
});
await page.goto("/");
await expect(page.getByText(/browser not supported/i)).toBeVisible();
await expect(page).not.toHaveURL(/\/login$/);
});
});
+57
View File
@@ -0,0 +1,57 @@
// TypeScript port of the canonical response-signing serializer in
// `ui/core/canon/response.go` (`BuildResponseSigningInput`). Used by
// the Phase 7 Playwright spec to forge gateway responses and sign
// them with the fixture key. The Go-side parity check
// (`gateway/authn/parity_with_ui_core_test.go`) is the source of
// truth; this TS copy stays small enough to read against that test.
const RESPONSE_DOMAIN_MARKER_V1 = "galaxy-response-v1";
export interface ResponseSigningFields {
protocolVersion: string;
requestId: string;
timestampMs: bigint;
resultCode: string;
payloadHash: Uint8Array;
}
export function buildResponseSigningInput(
fields: ResponseSigningFields,
): Uint8Array {
const parts: number[] = [];
appendLengthPrefixedString(parts, RESPONSE_DOMAIN_MARKER_V1);
appendLengthPrefixedString(parts, fields.protocolVersion);
appendLengthPrefixedString(parts, fields.requestId);
appendBigEndianUint64(parts, fields.timestampMs);
appendLengthPrefixedString(parts, fields.resultCode);
appendLengthPrefixedBytes(parts, fields.payloadHash);
return new Uint8Array(parts);
}
function appendLengthPrefixedString(dst: number[], value: string): void {
const bytes = new TextEncoder().encode(value);
appendLengthPrefixedBytes(dst, bytes);
}
function appendLengthPrefixedBytes(dst: number[], value: Uint8Array): void {
appendUvarint(dst, BigInt(value.length));
for (let i = 0; i < value.length; i++) {
dst.push(value[i]!);
}
}
function appendUvarint(dst: number[], value: bigint): void {
let v = value;
while (v >= 0x80n) {
dst.push(Number(v & 0xffn) | 0x80);
v >>= 7n;
}
dst.push(Number(v & 0xffn));
}
function appendBigEndianUint64(dst: number[], value: bigint): void {
const v = value & 0xffffffffffffffffn;
for (let i = 7; i >= 0; i--) {
dst.push(Number((v >> BigInt(i * 8)) & 0xffn));
}
}
@@ -0,0 +1,17 @@
// Deterministic Ed25519 keypair used by the Phase 7 Playwright e2e
// suite to forge gateway-shaped responses inside `page.route(...)`.
// The pair was generated once with Node's WebCrypto and is checked
// in: it is purely test fixture material, not used in production
// builds, and the public half lands in the dev server via
// `VITE_GATEWAY_RESPONSE_PUBLIC_KEY` from `playwright.config.ts`.
export const FIXTURE_PUBLIC_KEY_RAW_BASE64 =
"3Jf1C+qApVeysTytS6umsvTGqNfn3oHcagJhO97Ias4=";
export const FIXTURE_PRIVATE_KEY_PKCS8_BASE64 =
"MC4CAQAwBQYDK2VwBCIEIGnpfNAYxKJivan1ww5uvidgozuz9JXQM9dcdYrSiHHt";
export function decodeBase64(value: string): Uint8Array {
const bin = Buffer.from(value, "base64");
return new Uint8Array(bin.buffer, bin.byteOffset, bin.byteLength);
}
@@ -0,0 +1,83 @@
// Helper used by `auth-flow.spec.ts` to forge a Connect-Web-shaped
// `ExecuteCommandResponse` signed with the fixture gateway response
// key. Lives next to the keypair fixture so the e2e file stays
// focused on the UI flow. Connect-Web's default transport uses
// JSON over HTTP/1.1, so the helper emits JSON bytes; the canonical
// signing input is still the binary form defined in
// `ui/core/canon/response.go`.
import { create, toJson, toJsonString } from "@bufbuild/protobuf";
import { webcrypto } from "node:crypto";
import { ExecuteCommandResponseSchema } from "../../../src/proto/galaxy/gateway/v1/edge_gateway_pb";
import {
FIXTURE_PRIVATE_KEY_PKCS8_BASE64,
decodeBase64,
} from "./gateway-key";
import { buildResponseSigningInput } from "./canon";
const PROTOCOL_VERSION = "v1";
export interface ForgedResponseInput {
requestId: string;
timestampMs: bigint;
resultCode: string;
payloadBytes: Uint8Array;
}
let cachedPrivateKey: CryptoKey | null = null;
async function privateKey(): Promise<CryptoKey> {
if (cachedPrivateKey !== null) {
return cachedPrivateKey;
}
const pkcs8 = decodeBase64(FIXTURE_PRIVATE_KEY_PKCS8_BASE64);
cachedPrivateKey = await webcrypto.subtle.importKey(
"pkcs8",
pkcs8,
{ name: "Ed25519" },
false,
["sign"],
);
return cachedPrivateKey;
}
async function sha256(payload: Uint8Array): Promise<Uint8Array> {
const digest = await webcrypto.subtle.digest("SHA-256", payload);
return new Uint8Array(digest);
}
/**
* forgeExecuteCommandResponseJson produces the JSON body of a
* gateway response that `GalaxyClient.executeCommand` will accept
* under the fixture public key, encoded the way Connect-Web's
* default JSON transport expects to receive it.
*/
export async function forgeExecuteCommandResponseJson(
input: ForgedResponseInput,
): Promise<string> {
const payloadHash = await sha256(input.payloadBytes);
const canonical = buildResponseSigningInput({
protocolVersion: PROTOCOL_VERSION,
requestId: input.requestId,
timestampMs: input.timestampMs,
resultCode: input.resultCode,
payloadHash,
});
const sig = await webcrypto.subtle.sign(
{ name: "Ed25519" },
await privateKey(),
canonical,
);
const message = create(ExecuteCommandResponseSchema, {
protocolVersion: PROTOCOL_VERSION,
requestId: input.requestId,
timestampMs: input.timestampMs,
resultCode: input.resultCode,
payloadBytes: input.payloadBytes,
payloadHash,
signature: new Uint8Array(sig),
});
return toJsonString(ExecuteCommandResponseSchema, message);
}
export { toJson };
-8
View File
@@ -1,8 +0,0 @@
import { expect, test } from "@playwright/test";
test("landing page renders the version string", async ({ page }) => {
await page.goto("/");
const footer = page.getByTestId("app-version");
await expect(footer).toBeVisible();
await expect(footer).toContainText(/version\s+\S+/);
});
+225
View File
@@ -0,0 +1,225 @@
// Login page component tests. The `auth` API and the navigation
// helper are mocked at module level; the session singleton is wired
// to a per-test `SessionStore`-backing IndexedDB so the keypair the
// form passes to `confirmEmailCode` is a genuine 32-byte Ed25519
// public key without polluting the production `dbConnection()`
// cache.
import "fake-indexeddb/auto";
import { fireEvent, render, waitFor } from "@testing-library/svelte";
import {
afterEach,
beforeEach,
describe,
expect,
test,
vi,
} from "vitest";
import type { IDBPDatabase } from "idb";
import { AuthError } from "../src/api/auth";
import { session } from "../src/lib/session-store.svelte";
import { type GalaxyDB, openGalaxyDB } from "../src/platform/store/idb";
import { IDBCache } from "../src/platform/store/idb-cache";
import { WebCryptoKeyStore } from "../src/platform/store/webcrypto-keystore";
vi.mock("$app/navigation", () => ({
goto: vi.fn(async () => {}),
}));
const sendEmailCodeSpy = vi.fn();
const confirmEmailCodeSpy = vi.fn();
vi.mock("../src/api/auth", async () => {
const actual = await vi.importActual<typeof import("../src/api/auth")>(
"../src/api/auth",
);
return {
...actual,
sendEmailCode: (...args: unknown[]) => sendEmailCodeSpy(...args),
confirmEmailCode: (...args: unknown[]) => confirmEmailCodeSpy(...args),
};
});
let db: IDBPDatabase<GalaxyDB>;
let dbName: string;
beforeEach(async () => {
dbName = `galaxy-ui-test-${crypto.randomUUID()}`;
db = await openGalaxyDB(dbName);
const store = {
keyStore: new WebCryptoKeyStore(db),
cache: new IDBCache(db),
};
session.resetForTests();
session.setStoreLoaderForTests(async () => store);
await session.init();
sendEmailCodeSpy.mockReset();
confirmEmailCodeSpy.mockReset();
});
afterEach(async () => {
sendEmailCodeSpy.mockReset();
confirmEmailCodeSpy.mockReset();
session.resetForTests();
db.close();
await new Promise<void>((resolve) => {
const req = indexedDB.deleteDatabase(dbName);
req.onsuccess = () => resolve();
req.onerror = () => resolve();
req.onblocked = () => resolve();
});
});
async function importLoginPage(): Promise<typeof import("../src/routes/login/+page.svelte")> {
return import("../src/routes/login/+page.svelte");
}
describe("login page", () => {
test("submitting the email step calls sendEmailCode and advances to step=code", async () => {
sendEmailCodeSpy.mockResolvedValueOnce({ challengeId: "ch-1" });
const Page = (await importLoginPage()).default;
const ui = render(Page);
const emailInput = ui.getByTestId("login-email-input") as HTMLInputElement;
await fireEvent.input(emailInput, {
target: { value: "pilot@example.com" },
});
await fireEvent.click(ui.getByTestId("login-email-submit"));
await waitFor(() => {
expect(sendEmailCodeSpy).toHaveBeenCalledWith(
expect.any(String),
"pilot@example.com",
);
expect(ui.getByTestId("login-code-input")).toBeInTheDocument();
});
});
test("a send-email-code error stays on the email step and surfaces the message", async () => {
sendEmailCodeSpy.mockRejectedValueOnce(
new AuthError("service_unavailable", "auth service is unavailable", 503),
);
const Page = (await importLoginPage()).default;
const ui = render(Page);
// Use a syntactically valid e-mail so JSDOM does not block form
// submission via the `type="email"` constraint; the gateway is
// expected to reject the request with `service_unavailable`
// regardless of the address shape.
await fireEvent.input(ui.getByTestId("login-email-input"), {
target: { value: "pilot@example.com" },
});
await fireEvent.click(ui.getByTestId("login-email-submit"));
await waitFor(() => {
expect(ui.getByTestId("login-error")).toHaveTextContent(
"auth service is unavailable",
);
});
expect(ui.queryByTestId("login-code-input")).toBeNull();
});
test("submitting the code step calls confirmEmailCode and signs the user in", async () => {
sendEmailCodeSpy.mockResolvedValueOnce({ challengeId: "ch-1" });
confirmEmailCodeSpy.mockResolvedValueOnce({ deviceSessionId: "dev-1" });
const Page = (await importLoginPage()).default;
const ui = render(Page);
await fireEvent.input(ui.getByTestId("login-email-input"), {
target: { value: "pilot@example.com" },
});
await fireEvent.click(ui.getByTestId("login-email-submit"));
await waitFor(() => ui.getByTestId("login-code-input"));
await fireEvent.input(ui.getByTestId("login-code-input"), {
target: { value: "123456" },
});
await fireEvent.click(ui.getByTestId("login-code-submit"));
await waitFor(() => {
expect(confirmEmailCodeSpy).toHaveBeenCalledTimes(1);
expect(session.deviceSessionId).toBe("dev-1");
expect(session.status).toBe("authenticated");
});
const args = confirmEmailCodeSpy.mock.calls[0]![1]!;
expect(args.challengeId).toBe("ch-1");
expect(args.code).toBe("123456");
expect(args.publicKey).toBeInstanceOf(Uint8Array);
expect(args.publicKey.length).toBe(32);
expect(typeof args.timeZone).toBe("string");
});
test("a confirm-email-code invalid_request bounces back to step=email with an error", async () => {
sendEmailCodeSpy.mockResolvedValueOnce({ challengeId: "ch-1" });
confirmEmailCodeSpy.mockRejectedValueOnce(
new AuthError("invalid_request", "code expired", 400),
);
const Page = (await importLoginPage()).default;
const ui = render(Page);
await fireEvent.input(ui.getByTestId("login-email-input"), {
target: { value: "pilot@example.com" },
});
await fireEvent.click(ui.getByTestId("login-email-submit"));
await waitFor(() => ui.getByTestId("login-code-input"));
await fireEvent.input(ui.getByTestId("login-code-input"), {
target: { value: "00000" },
});
await fireEvent.click(ui.getByTestId("login-code-submit"));
await waitFor(() => {
expect(ui.queryByTestId("login-code-input")).toBeNull();
expect(ui.getByTestId("login-email-input")).toBeInTheDocument();
expect(ui.getByTestId("login-error")).toHaveTextContent(
/expired|already used/i,
);
});
});
test("resend re-issues sendEmailCode and clears the code field", async () => {
sendEmailCodeSpy
.mockResolvedValueOnce({ challengeId: "ch-1" })
.mockResolvedValueOnce({ challengeId: "ch-2" });
const Page = (await importLoginPage()).default;
const ui = render(Page);
await fireEvent.input(ui.getByTestId("login-email-input"), {
target: { value: "pilot@example.com" },
});
await fireEvent.click(ui.getByTestId("login-email-submit"));
await waitFor(() => ui.getByTestId("login-code-input"));
await fireEvent.input(ui.getByTestId("login-code-input"), {
target: { value: "999999" },
});
await fireEvent.click(ui.getByTestId("login-resend"));
await waitFor(() => {
expect(sendEmailCodeSpy).toHaveBeenCalledTimes(2);
expect(
(ui.getByTestId("login-code-input") as HTMLInputElement).value,
).toBe("");
});
});
test("change-email returns to the email step", async () => {
sendEmailCodeSpy.mockResolvedValueOnce({ challengeId: "ch-1" });
const Page = (await importLoginPage()).default;
const ui = render(Page);
await fireEvent.input(ui.getByTestId("login-email-input"), {
target: { value: "pilot@example.com" },
});
await fireEvent.click(ui.getByTestId("login-email-submit"));
await waitFor(() => ui.getByTestId("login-code-input"));
await fireEvent.click(ui.getByTestId("login-change-email"));
await waitFor(() => {
expect(ui.queryByTestId("login-code-input")).toBeNull();
expect(ui.getByTestId("login-email-input")).toBeInTheDocument();
});
});
});
+129
View File
@@ -0,0 +1,129 @@
// SessionStore unit tests under JSDOM with `fake-indexeddb` and Node
// 22's WebCrypto. Each case wires a fresh `SessionStore` against a
// per-test IndexedDB name, so persistence behaviour is observable
// across cases without bleed and without touching the production
// `dbConnection()` cache.
import "fake-indexeddb/auto";
import { afterEach, beforeEach, describe, expect, test } from "vitest";
import type { IDBPDatabase } from "idb";
import { type GalaxyDB, openGalaxyDB } from "../src/platform/store/idb";
import { IDBCache } from "../src/platform/store/idb-cache";
import { WebCryptoKeyStore } from "../src/platform/store/webcrypto-keystore";
import type { Store } from "../src/platform/store/index";
import { SessionStore } from "../src/lib/session-store.svelte";
let db: IDBPDatabase<GalaxyDB>;
let dbName: string;
let store: Store;
beforeEach(async () => {
dbName = `galaxy-ui-test-${crypto.randomUUID()}`;
db = await openGalaxyDB(dbName);
store = {
keyStore: new WebCryptoKeyStore(db),
cache: new IDBCache(db),
};
});
afterEach(async () => {
db.close();
await new Promise<void>((resolve) => {
const req = indexedDB.deleteDatabase(dbName);
req.onsuccess = () => resolve();
req.onerror = () => resolve();
req.onblocked = () => resolve();
});
});
function newSessionStore(): SessionStore {
const s = new SessionStore();
s.setStoreLoaderForTests(async () => store);
return s;
}
describe("SessionStore.init", () => {
test("settles to anonymous when no device-session id is persisted", async () => {
const session = newSessionStore();
await session.init();
expect(session.status).toBe("anonymous");
expect(session.deviceSessionId).toBeNull();
expect(session.keypair).not.toBeNull();
expect(session.keypair!.publicKey.length).toBe(32);
});
test("settles to authenticated when a device-session id is persisted", async () => {
const first = newSessionStore();
await first.init();
await first.signIn("dev-1");
expect(first.status).toBe("authenticated");
// Simulate a fresh page load: a new SessionStore against the
// same IndexedDB picks up the previously persisted session.
const second = newSessionStore();
await second.init();
expect(second.status).toBe("authenticated");
expect(second.deviceSessionId).toBe("dev-1");
expect(second.keypair).not.toBeNull();
});
test("flips status to unsupported when WebCrypto Ed25519 is missing", async () => {
const session = newSessionStore();
session.setSupportProbeForTests(async () => false);
await session.init();
expect(session.status).toBe("unsupported");
expect(session.keypair).toBeNull();
});
test("init is idempotent", async () => {
const session = newSessionStore();
await Promise.all([session.init(), session.init(), session.init()]);
expect(session.status).toBe("anonymous");
});
});
describe("SessionStore.signIn / signOut", () => {
test("signIn persists the device-session id and updates status", async () => {
const session = newSessionStore();
await session.init();
await session.signIn("dev-2");
expect(session.deviceSessionId).toBe("dev-2");
expect(session.status).toBe("authenticated");
const reload = newSessionStore();
await reload.init();
expect(reload.deviceSessionId).toBe("dev-2");
});
test("signOut('user') wipes id, regenerates keypair, returns to anonymous", async () => {
const session = newSessionStore();
await session.init();
const firstPublicKey = Array.from(session.keypair!.publicKey);
await session.signIn("dev-3");
await session.signOut("user");
expect(session.deviceSessionId).toBeNull();
expect(session.status).toBe("anonymous");
expect(session.keypair).not.toBeNull();
const secondPublicKey = Array.from(session.keypair!.publicKey);
expect(secondPublicKey).not.toEqual(firstPublicKey);
});
test("signOut('revoked') has the same observable post-state as 'user'", async () => {
const session = newSessionStore();
await session.init();
await session.signIn("dev-4");
await session.signOut("revoked");
expect(session.status).toBe("anonymous");
expect(session.deviceSessionId).toBeNull();
});
test("signIn before init throws", async () => {
const local = new SessionStore();
await expect(local.signIn("x")).rejects.toThrow(/before init/);
});
test("signOut before init throws", async () => {
const local = new SessionStore();
await expect(local.signOut("user")).rejects.toThrow(/before init/);
});
});