ui/phase-24: push events, turn-ready toast, single SubscribeEvents consumer
Wires the gateway's signed SubscribeEvents stream end-to-end:
- backend: emit game.turn.ready from lobby.OnRuntimeSnapshot on every
current_turn advance, addressed to every active membership, push-only
channel, idempotency key turn-ready:<game_id>:<turn>;
- ui: single EventStream singleton replaces revocation-watcher.ts and
carries both per-event dispatch and revocation detection; toast
primitive (store + host) lives in lib/; GameStateStore gains
pendingTurn/markPendingTurn/advanceToPending and a persisted
lastViewedTurn so a return after multiple turns surfaces the same
"view now" affordance as a live push event;
- mandatory event-signature verification through ui/core
(verifyPayloadHash + verifyEvent), full-jitter exponential backoff
1s -> 30s on transient failure, signOut("revoked") on
Unauthenticated or clean end-of-stream;
- catalog and migration accept the new kind; tests cover producer
(testcontainers + capturing publisher), consumer (Vitest event
stream, toast, game-state extensions), and a Playwright e2e
delivering a signed frame to the live UI.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -6,6 +6,7 @@
|
||||
// truth; this TS copy stays small enough to read against that test.
|
||||
|
||||
const RESPONSE_DOMAIN_MARKER_V1 = "galaxy-response-v1";
|
||||
const EVENT_DOMAIN_MARKER_V1 = "galaxy-event-v1";
|
||||
|
||||
export interface ResponseSigningFields {
|
||||
protocolVersion: string;
|
||||
@@ -15,6 +16,15 @@ export interface ResponseSigningFields {
|
||||
payloadHash: Uint8Array;
|
||||
}
|
||||
|
||||
export interface EventSigningFields {
|
||||
eventType: string;
|
||||
eventId: string;
|
||||
timestampMs: bigint;
|
||||
requestId: string;
|
||||
traceId: string;
|
||||
payloadHash: Uint8Array;
|
||||
}
|
||||
|
||||
export function buildResponseSigningInput(
|
||||
fields: ResponseSigningFields,
|
||||
): Uint8Array {
|
||||
@@ -28,6 +38,24 @@ export function buildResponseSigningInput(
|
||||
return new Uint8Array(parts);
|
||||
}
|
||||
|
||||
// `buildEventSigningInput` mirrors `ui/core/canon/event.go`
|
||||
// `BuildEventSigningInput`. The Go-side parity test
|
||||
// (`gateway/authn/parity_with_ui_core_test.go`) is the source of truth;
|
||||
// this TS copy stays close enough to that test to read against it.
|
||||
export function buildEventSigningInput(
|
||||
fields: EventSigningFields,
|
||||
): Uint8Array {
|
||||
const parts: number[] = [];
|
||||
appendLengthPrefixedString(parts, EVENT_DOMAIN_MARKER_V1);
|
||||
appendLengthPrefixedString(parts, fields.eventType);
|
||||
appendLengthPrefixedString(parts, fields.eventId);
|
||||
appendBigEndianUint64(parts, fields.timestampMs);
|
||||
appendLengthPrefixedString(parts, fields.requestId);
|
||||
appendLengthPrefixedString(parts, fields.traceId);
|
||||
appendLengthPrefixedBytes(parts, fields.payloadHash);
|
||||
return new Uint8Array(parts);
|
||||
}
|
||||
|
||||
function appendLengthPrefixedString(dst: number[], value: string): void {
|
||||
const bytes = new TextEncoder().encode(value);
|
||||
appendLengthPrefixedBytes(dst, bytes);
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
// `forgeGatewayEventFrame` produces one Connect HTTP/1.1
|
||||
// server-streaming frame carrying a `GatewayEvent` signed with the
|
||||
// fixture private key. The Playwright `turn-ready.spec.ts` route
|
||||
// handler returns this body when the UI opens `SubscribeEvents` so
|
||||
// the production verification path (`core.verifyEvent`) accepts the
|
||||
// frame under the matching public key the dev server picks up via
|
||||
// `VITE_GATEWAY_RESPONSE_PUBLIC_KEY`.
|
||||
//
|
||||
// Connect HTTP/1.1 server-streaming framing per request:
|
||||
// 1 byte flag (0x00 = message)
|
||||
// 4 bytes length (big-endian, payload size)
|
||||
// N bytes payload (JSON-encoded GatewayEvent for the JSON codec)
|
||||
//
|
||||
// The route handler closes the response after one frame; the UI's
|
||||
// `events.svelte.ts` reconnect loop treats the abrupt end-of-body as
|
||||
// a transient error and backs off, which keeps the toast visible
|
||||
// long enough for the test to assert on it.
|
||||
|
||||
import { create, toJsonString } from "@bufbuild/protobuf";
|
||||
import { webcrypto } from "node:crypto";
|
||||
import { GatewayEventSchema } from "../../../src/proto/galaxy/gateway/v1/edge_gateway_pb";
|
||||
import { buildEventSigningInput } from "./canon";
|
||||
import {
|
||||
FIXTURE_PRIVATE_KEY_PKCS8_BASE64,
|
||||
decodeBase64,
|
||||
} from "./gateway-key";
|
||||
|
||||
export interface ForgedEventInput {
|
||||
eventType: string;
|
||||
eventId: string;
|
||||
timestampMs: bigint;
|
||||
requestId: string;
|
||||
traceId: 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);
|
||||
}
|
||||
|
||||
export async function forgeGatewayEventFrame(
|
||||
input: ForgedEventInput,
|
||||
): Promise<Uint8Array> {
|
||||
const payloadHash = await sha256(input.payloadBytes);
|
||||
const canonical = buildEventSigningInput({
|
||||
eventType: input.eventType,
|
||||
eventId: input.eventId,
|
||||
timestampMs: input.timestampMs,
|
||||
requestId: input.requestId,
|
||||
traceId: input.traceId,
|
||||
payloadHash,
|
||||
});
|
||||
const signatureBuf = await webcrypto.subtle.sign(
|
||||
{ name: "Ed25519" },
|
||||
await privateKey(),
|
||||
canonical,
|
||||
);
|
||||
const event = create(GatewayEventSchema, {
|
||||
eventType: input.eventType,
|
||||
eventId: input.eventId,
|
||||
timestampMs: input.timestampMs,
|
||||
payloadBytes: input.payloadBytes,
|
||||
payloadHash,
|
||||
signature: new Uint8Array(signatureBuf),
|
||||
requestId: input.requestId,
|
||||
traceId: input.traceId,
|
||||
});
|
||||
const body = new TextEncoder().encode(
|
||||
toJsonString(GatewayEventSchema, event),
|
||||
);
|
||||
const frame = new Uint8Array(5 + body.length);
|
||||
frame[0] = 0x00; // message frame
|
||||
new DataView(frame.buffer).setUint32(1, body.length, false);
|
||||
frame.set(body, 5);
|
||||
return frame;
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
// Phase 24 end-to-end coverage for the push-event path. Boots an
|
||||
// authenticated session, mocks the gateway calls the in-game shell
|
||||
// makes (`lobby.my.games.list`, `user.games.report`), and serves one
|
||||
// signed `game.turn.ready` frame on the `SubscribeEvents` stream.
|
||||
// The test asserts the toast surfaces with the new turn, the action
|
||||
// button advances the store onto the new turn, and the header
|
||||
// reflects the freshly-loaded snapshot.
|
||||
|
||||
import { fromJson, type JsonValue } from "@bufbuild/protobuf";
|
||||
import { expect, test, type Page } from "@playwright/test";
|
||||
import { ByteBuffer } from "flatbuffers";
|
||||
|
||||
import { ExecuteCommandRequestSchema } from "../../src/proto/galaxy/gateway/v1/edge_gateway_pb";
|
||||
import { UUID } from "../../src/proto/galaxy/fbs/common";
|
||||
import { GameReportRequest } from "../../src/proto/galaxy/fbs/report";
|
||||
import { forgeExecuteCommandResponseJson } from "./fixtures/sign-response";
|
||||
import {
|
||||
buildMyGamesListPayload,
|
||||
type GameFixture,
|
||||
} from "./fixtures/lobby-fbs";
|
||||
import { buildReportPayload } from "./fixtures/report-fbs";
|
||||
import { forgeGatewayEventFrame } from "./fixtures/sign-event";
|
||||
|
||||
const SESSION_ID = "phase-24-turn-ready-session";
|
||||
const GAME_ID = "11111111-2222-3333-4444-555555555555";
|
||||
|
||||
interface MockState {
|
||||
currentTurn: number;
|
||||
reportRequests: Array<{ turn: number }>;
|
||||
subscribeHits: number;
|
||||
}
|
||||
|
||||
async function mockGateway(page: Page): Promise<MockState> {
|
||||
const state: MockState = {
|
||||
currentTurn: 4,
|
||||
reportRequests: [],
|
||||
subscribeHits: 0,
|
||||
};
|
||||
|
||||
const baseGame = (): GameFixture => ({
|
||||
gameId: GAME_ID,
|
||||
gameName: "Phase 24 Game",
|
||||
gameType: "private",
|
||||
status: "running",
|
||||
ownerUserId: "user-1",
|
||||
minPlayers: 2,
|
||||
maxPlayers: 8,
|
||||
enrollmentEndsAtMs: BigInt(Date.now() + 86_400_000),
|
||||
createdAtMs: BigInt(Date.now() - 86_400_000),
|
||||
updatedAtMs: BigInt(Date.now()),
|
||||
currentTurn: state.currentTurn,
|
||||
});
|
||||
|
||||
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,
|
||||
);
|
||||
|
||||
let resultCode = "ok";
|
||||
let payload: Uint8Array;
|
||||
switch (req.messageType) {
|
||||
case "lobby.my.games.list":
|
||||
payload = buildMyGamesListPayload([baseGame()]);
|
||||
break;
|
||||
case "user.games.report": {
|
||||
const decoded = GameReportRequest.getRootAsGameReportRequest(
|
||||
new ByteBuffer(req.payloadBytes),
|
||||
);
|
||||
const turn = decoded.turn();
|
||||
state.reportRequests.push({ turn });
|
||||
payload = buildReportPayload({
|
||||
turn,
|
||||
mapWidth: 4000,
|
||||
mapHeight: 4000,
|
||||
localPlanets: [
|
||||
{ number: 1, name: "Home", x: 1000, y: 1000 },
|
||||
],
|
||||
});
|
||||
break;
|
||||
}
|
||||
default:
|
||||
resultCode = "internal_error";
|
||||
payload = new Uint8Array();
|
||||
}
|
||||
|
||||
const body = await forgeExecuteCommandResponseJson({
|
||||
requestId: req.requestId,
|
||||
timestampMs: BigInt(Date.now()),
|
||||
resultCode,
|
||||
payloadBytes: payload,
|
||||
});
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
body,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
// The first SubscribeEvents request from the root layout receives
|
||||
// one signed `game.turn.ready` frame for turn 5; subsequent
|
||||
// reconnect attempts (events.ts retries after the abrupt
|
||||
// end-of-body) are held open indefinitely so the toast stays
|
||||
// visible long enough for the test to interact with it.
|
||||
await page.route(
|
||||
"**/galaxy.gateway.v1.EdgeGateway/SubscribeEvents",
|
||||
async (route) => {
|
||||
state.subscribeHits += 1;
|
||||
if (state.subscribeHits === 1) {
|
||||
const payload = new TextEncoder().encode(
|
||||
JSON.stringify({ game_id: GAME_ID, turn: 5 }),
|
||||
);
|
||||
const frame = await forgeGatewayEventFrame({
|
||||
eventType: "game.turn.ready",
|
||||
eventId: "evt-turn-ready-1",
|
||||
timestampMs: BigInt(Date.now()),
|
||||
requestId: "req-turn-ready-1",
|
||||
traceId: "trace-turn-ready-1",
|
||||
payloadBytes: payload,
|
||||
});
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/connect+json",
|
||||
body: Buffer.from(frame),
|
||||
});
|
||||
return;
|
||||
}
|
||||
await new Promise<void>(() => {});
|
||||
},
|
||||
);
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
async function bootSession(page: Page): Promise<void> {
|
||||
await page.goto("/__debug/store");
|
||||
await expect(page.getByTestId("debug-store-ready")).toBeVisible();
|
||||
await page.waitForFunction(() => window.__galaxyDebug?.ready === true);
|
||||
await page.evaluate(() => window.__galaxyDebug!.clearSession());
|
||||
await page.evaluate(
|
||||
(id) => window.__galaxyDebug!.setDeviceSessionId(id),
|
||||
SESSION_ID,
|
||||
);
|
||||
}
|
||||
|
||||
test("signed game.turn.ready frame surfaces the toast", async ({ page }) => {
|
||||
await mockGateway(page);
|
||||
|
||||
await bootSession(page);
|
||||
await page.goto(`/games/${GAME_ID}/map`);
|
||||
|
||||
// Initial chrome reflects the bootstrap currentTurn=4.
|
||||
await expect(page.getByTestId("active-view-map")).toHaveAttribute(
|
||||
"data-status",
|
||||
"ready",
|
||||
);
|
||||
await expect(page.getByTestId("game-shell-headline")).toContainText(
|
||||
"turn 4",
|
||||
);
|
||||
|
||||
// The signed push frame is delivered to the singleton event
|
||||
// stream → the per-game layout handler marks pendingTurn=5 → the
|
||||
// toast becomes visible carrying the new turn number and the
|
||||
// `view now` action label.
|
||||
await expect(page.getByTestId("toast")).toBeVisible({ timeout: 5_000 });
|
||||
await expect(page.getByTestId("toast-message")).toContainText("5");
|
||||
await expect(page.getByTestId("toast-action")).toBeVisible();
|
||||
});
|
||||
|
||||
test("manual dismiss clears the turn-ready toast without advancing the view", async ({
|
||||
page,
|
||||
}) => {
|
||||
await mockGateway(page);
|
||||
|
||||
await bootSession(page);
|
||||
await page.goto(`/games/${GAME_ID}/map`);
|
||||
|
||||
await expect(page.getByTestId("toast")).toBeVisible({ timeout: 5_000 });
|
||||
await page.getByTestId("toast-close").click();
|
||||
await expect(page.getByTestId("toast")).toBeHidden();
|
||||
// `pendingTurn` is still set — the user simply chose not to
|
||||
// advance — so the header continues to show the older turn.
|
||||
await expect(page.getByTestId("game-shell-headline")).toContainText(
|
||||
"turn 4",
|
||||
);
|
||||
});
|
||||
Reference in New Issue
Block a user