Files
galaxy-game/ui/frontend/tests/e2e/auth-flow.spec.ts
T
Ilia Denisov 2ecdecad1e feat(ui): lobby site-style sidebar + profile screen (#47)
- Wrap lobby and profile in a shared `lobby-shell.svelte` chrome:
  page-list sidebar (Overview/Profile) and a top "Player-xxxx"
  identity strip mirroring the project site's monospace look.
- Strip the legacy `lobby.title`, device-session-id `<code>`, and
  `lobby.greeting` paragraph; the identity strip both names the user
  and opens the profile editor.
- Add a top-level `profile` AppScreen with a three-field form
  (`display_name`, `preferred_language`, `time_zone`) backed by a new
  `src/api/account.ts` wrapper around `user.account.get`,
  `user.profile.update`, and `user.settings.update`. Saving switches
  the active i18n locale in-place when the new preferred language is
  one the UI ships translations for.
- Update e2e fixture + auth-flow / lobby-flow specs to use the new
  `lobby-account-name` testid and wait for the loaded identity before
  releasing pending `SubscribeEvents` (webkit revocation race). New
  `profile-screen.spec.ts` covers navigation, edit-save, and cancel.
- Sync `ui/docs/lobby.md` and `ui/docs/navigation.md` to the new
  layout.

Closes #47
2026-05-26 22:25:40 +02:00

343 lines
12 KiB
TypeScript

// 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>/edge.v1.Gateway/<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/edge/v1/edge_gateway_pb";
import { forgeExecuteCommandResponseJson } from "./fixtures/sign-response";
import {
buildAccountResponsePayload,
buildMyApplicationsListPayload,
buildMyGamesListPayload,
buildMyInvitesListPayload,
buildPublicGamesListPayload,
} from "./fixtures/lobby-fbs";
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(
"**/edge.v1.Gateway/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,
);
let payload: Uint8Array;
switch (req.messageType) {
case "user.account.get":
payload = buildAccountResponsePayload({
userId: "user-1",
email: "pilot@example.com",
userName: "player-test",
displayName,
});
break;
case "lobby.my.games.list":
payload = buildMyGamesListPayload([]);
break;
case "lobby.public.games.list":
payload = buildPublicGamesListPayload([]);
break;
case "lobby.my.invites.list":
payload = buildMyInvitesListPayload([]);
break;
case "lobby.my.applications.list":
payload = buildMyApplicationsListPayload([]);
break;
default:
payload = new Uint8Array();
}
const responseJson = await forgeExecuteCommandResponseJson({
requestId: req.requestId,
timestampMs: BigInt(Date.now()),
resultCode: "ok",
payloadBytes: payload,
});
await route.fulfill({
status: 200,
contentType: "application/json",
body: responseJson,
});
},
);
await page.route(
"**/edge.v1.Gateway/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("/");
// The single-URL app-shell renders the login screen from in-memory
// state (anonymous session) rather than a `/login` route, so assert
// on the visible login form instead of the URL.
await expect(page.getByTestId("login-email-input")).toBeVisible();
// Inputs render `readonly` initially as a Safari autofill-suppression
// workaround; the attribute drops on first focus. Click first so the
// onfocus handler runs before fill checks editability.
await page.getByTestId("login-email-input").click();
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").click();
await page.getByTestId("login-code-input").fill("123456");
await page.getByTestId("login-code-submit").click();
// Sign-in switches the in-memory screen to the lobby; the identity
// strip rendered by `lobby-shell.svelte` is the lobby-loaded signal.
await expect(page.getByTestId("lobby-account-name")).toBeVisible();
}
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("lobby-account-name")).toContainText("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("lobby-account-name")).toBeVisible();
await page.reload();
// The restored session re-renders the lobby screen directly (no
// `/lobby` route to land on).
await expect(page.getByTestId("lobby-account-name")).toContainText(
"Pilot",
);
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);
// `lobby-account-name` becomes visible on lobby mount with the
// "loading account…" placeholder before the gateway responds.
// Wait for the loaded name to settle so the event-stream effect
// has had a chance to issue its `SubscribeEvents` request — the
// release below targets that pending stream, and an empty
// `pendingSubscribes` list defeats the test.
await expect(page.getByTestId("lobby-account-name")).toContainText(
"Pilot",
);
// 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 flips the
// in-memory session to anonymous so the dispatcher re-renders the
// login screen (the single-URL app-shell has no `/login` route to
// redirect to).
const releaseAt = Date.now();
mocks.pendingSubscribes.forEach((resolve) => resolve());
await expect(page.getByTestId("login-email-input")).toBeVisible({
timeout: 1000,
});
expect(Date.now() - releaseAt).toBeLessThan(1500);
});
test("language picker switches the form text and forwards the locale", async ({
page,
}) => {
const sendRequests: Array<{ body: Record<string, unknown> }> = [];
await page.route(
"**/api/v1/public/auth/send-email-code",
async (route) => {
const raw = route.request().postData() ?? "";
sendRequests.push({
body: JSON.parse(raw) as Record<string, unknown>,
});
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({ challenge_id: "ch-test-2" }),
});
},
);
await page.goto("/");
await expect(page.getByTestId("login-email-submit")).toHaveText(
"send code",
);
await page
.getByTestId("login-language-select")
.selectOption("ru");
await expect(page.getByTestId("login-email-submit")).toHaveText(
"отправить код",
);
await page.getByTestId("login-email-input").click();
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();
expect(sendRequests).toHaveLength(1);
expect(sendRequests[0]!.body).toEqual({
email: "pilot@example.com",
locale: "ru",
});
});
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();
// The unsupported-browser blocker replaces the screen dispatcher
// entirely, so the login form never renders.
await expect(page.getByTestId("login-email-input")).toHaveCount(0);
});
test("autofocuses each step's primary field and keeps the code out of form history", async ({
page,
}) => {
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-focus-1" }),
});
},
);
await page.goto("/");
// The e-mail field is focused on load so the user can type at once.
// Reaching the focused state also means the readonly autofill guard
// has dropped, so `fill` does not need a preceding click here.
await expect(page.getByTestId("login-email-input")).toBeFocused();
await page.getByTestId("login-email-input").fill("pilot@example.com");
await page.getByTestId("login-email-submit").click();
// Advancing to the code step moves the cursor onto the code field.
const codeInput = page.getByTestId("login-code-input");
await expect(codeInput).toBeFocused();
// `one-time-code` is what keeps browsers (notably Firefox) from
// saving the verification code to form history. Assert the attribute
// the suppression relies on; Firefox form history itself is verified
// by hand, as the e2e matrix runs Chromium and WebKit only.
await expect(codeInput).toHaveAttribute("autocomplete", "one-time-code");
});
});