Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions apps/api/src/sessions/routes.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { SESSION_NAME_MAX_LENGTH } from "@gamemash/games/config";
import type { CreateSessionResponse } from "@gamemash/shared";
import { describe, expect, it } from "vitest";
import { buildApp } from "../app.js";
Expand All @@ -24,6 +25,49 @@ describe("POST /api/sessions", () => {
expect(body.sessionId).toMatch(/^[0-9a-f-]{36}$/);
expect(body.hostToken).toBeTruthy();
});

it("starts the setup with the session name it was given", async () => {
const app = setup();

const created = (
await app.inject({ method: "POST", url: "/api/sessions", payload: { name: " Friday team mash " } })
).json<CreateSessionResponse>();
const loaded = await app.inject({
method: "GET",
url: `/api/sessions/${created.sessionId}/setup`,
headers: { authorization: `Bearer ${created.hostToken}` },
});

expect(loaded.json().setup).toEqual({ name: "Friday team mash", games: [] });
});

it("leaves the setup empty when the name is blank", async () => {
const app = setup();

const created = (
await app.inject({ method: "POST", url: "/api/sessions", payload: { name: " " } })
).json<CreateSessionResponse>();
const loaded = await app.inject({
method: "GET",
url: `/api/sessions/${created.sessionId}/setup`,
headers: { authorization: `Bearer ${created.hostToken}` },
});

expect(loaded.json().setup).toEqual({ name: "", games: [] });
});

it.each([
["a name that is too long", { name: "x".repeat(SESSION_NAME_MAX_LENGTH + 1) }],
["hidden characters", { name: "Friday\u200Bmash" }],
["unknown fields", { name: "Friday", extra: true }],
])("rejects %s", async (_label, payload) => {
const app = setup();

const response = await app.inject({ method: "POST", url: "/api/sessions", payload });

expect(response.statusCode).toBe(400);
expect(response.json()).toEqual({ code: "bad_request" });
});
});

describe("GET /api/sessions/by-code/:code", () => {
Expand Down
15 changes: 13 additions & 2 deletions apps/api/src/sessions/routes.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { FastifyPluginAsyncTypebox } from "@fastify/type-provider-typebox";
import { CreateSessionBodySchema } from "@gamemash/games/schemas";
import { type ErrorCode, isRoomCode, normalizeRoomCode, PLAYER_NAME_MAX_LENGTH } from "@gamemash/shared";
import {
ApiErrorSchema,
Expand Down Expand Up @@ -57,9 +58,19 @@ export const sessionRoutes =
"/api/sessions",
{
config: { rateLimit: { max: limits.sessionsPerMinute, timeWindow: MINUTE_MS, keyGenerator: byClient } },
schema: { response: { 201: CreateSessionResponseSchema } },
schema: {
body: CreateSessionBodySchema,
response: { 201: CreateSessionResponseSchema, 400: ApiErrorSchema },
},
preValidation: async (request) => {
request.body ??= {};
},
},
async (request, reply) => {
const result = await sessions.createNamed(request.body.name ?? "");
if (!result.ok) return reply.code(400).send({ code: result.error });
return reply.code(201).send(result.value);
},
async (_request, reply) => reply.code(201).send(await sessions.create()),
);

app.get(
Expand Down
27 changes: 27 additions & 0 deletions apps/api/src/sessions/service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,33 @@ describe("createSessionService", () => {

await expect(service.create()).rejects.toBeInstanceOf(RoomCodesExhaustedError);
});

it("refuses a session name with hidden characters", async () => {
const service = createSessionService({ store: createMemorySessionStore() });

const result = await service.createNamed("Friday\u200Bmash");

expect(result).toEqual({ ok: false, error: "bad_request" });
});

it("still creates the session when its name cannot be saved", async () => {
const store = createMemorySessionStore();
const warnings: unknown[] = [];
const service = createSessionService({
store: {
...store,
saveSetup: async () => {
throw new Error("redis down");
},
},
log: { warn: (details: unknown) => warnings.push(details) },
});

const result = await service.createNamed("Friday team mash");

expect(result.ok).toBe(true);
expect(warnings).toHaveLength(1);
});
});

describe("sessionExpiresAt", () => {
Expand Down
25 changes: 24 additions & 1 deletion apps/api/src/sessions/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,9 +111,25 @@ export const createSessionService = ({

const touch = async (session: SessionRecord) => store.touch(session, sessionExpiresAt(session.createdAt, now()));

const create = async (): Promise<CreateSessionResponse> => {
const nameSession = async (session: SessionRecord, name: string) => {
const setup: SessionSetup = { ...emptySetup(), name };
const summary: LobbySummary = { ...EMPTY_SUMMARY, name };
try {
await store.saveSetup(
session.id,
JSON.stringify(setup),
JSON.stringify(summary),
sessionExpiresAt(session.createdAt, session.createdAt),
);
} catch (error) {
log?.warn({ sessionId: session.id, error }, "could not save the session name");
}
};

const create = async (name = ""): Promise<CreateSessionResponse> => {
const hostToken = createSecret();
const createdAt = now();
const sessionName = name.trim();
for (let attempt = 0; attempt < MAX_ROOM_CODE_ATTEMPTS; attempt += 1) {
const session: SessionRecord = {
id: createId(),
Expand All @@ -123,12 +139,18 @@ export const createSessionService = ({
createdAt,
};
if ((await store.create(session, sessionExpiresAt(createdAt, createdAt))) === "created") {
if (sessionName) await nameSession(session, sessionName);
return { sessionId: session.id, roomCode: session.roomCode, hostToken };
}
}
throw new RoomCodesExhaustedError();
};

const createNamed = async (name: string): Promise<Result<CreateSessionResponse>> => {
if (hasHiddenCharacters(name)) return fail("bad_request");
return { ok: true, value: await create(name) };
};

const join = async (sessionId: string, rawName: string): Promise<Result<JoinSessionResponse>> => {
const name = normalizePlayerName(rawName);
if (!isValidName(name)) return fail("invalid_name");
Expand Down Expand Up @@ -348,6 +370,7 @@ export const createSessionService = ({

return {
create,
createNamed,
findByRoomCode: (code: string) => store.findByRoomCode(code),
join,
authenticateHost,
Expand Down
2 changes: 1 addition & 1 deletion apps/web/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, interactive-widget=resizes-content" />
<title>GameMash</title>
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
Expand Down
7 changes: 7 additions & 0 deletions apps/web/src/features/entry/entry-layout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import type { FormEvent, ReactNode } from "react";

export type EntryLayoutProps = {
fields: ReactNode;
submit: ReactNode;
onSubmit: (event: FormEvent<HTMLFormElement>) => void;
};
61 changes: 61 additions & 0 deletions apps/web/src/features/host/HostDesktop.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import {
buttonVariants,
EntryShell,
Heading,
HowItWorksSteps,
Logo,
PhoneIcon,
Sticker,
TrustNote,
} from "@gamemash/ui";
import { Link } from "@tanstack/react-router";
import { FormattedMessage } from "react-intl";
import type { EntryLayoutProps } from "../entry/entry-layout";
import { HOST_FORM_ID, HOST_STEPS } from "./host-layout";

export const HostDesktop = ({ fields, submit, onSubmit }: EntryLayoutProps) => (
<EntryShell
logo={<Logo size="md" hasOutline={false} />}
action={
<Link to="/" className={buttonVariants({ variant: "secondary", size: "md" })}>
<PhoneIcon size={20} strokeWidth={2.2} />
<FormattedMessage id="host.joinGame" />
</Link>
}
mainClassName="flex-col items-center gap-10"
>
<section className="flex w-full max-w-[520px] flex-1 flex-col justify-center gap-[18px]">
<form
id={HOST_FORM_ID}
noValidate
onSubmit={onSubmit}
className="flex flex-col gap-3.5 rounded-tile border-3 border-ink-950 bg-paper-white p-9 shadow-brutal-xl"
>
<Sticker tone="sky" rotate={-2} className="self-start text-label">
<FormattedMessage id="host.tag" />
</Sticker>
<Heading size="display">
<FormattedMessage id="host.title" />
</Heading>
<p className="mb-2 text-lg/[1.45] text-fg-muted">
<FormattedMessage id="host.body" />
</p>
{fields}
<div className="mt-2.5 flex flex-col">{submit}</div>
</form>
<div className="flex items-center justify-between gap-4 px-1">
<TrustNote size="inline">
<FormattedMessage id="host.trust" />
</TrustNote>
<Link to="/" className="focus-ring shrink-0 text-caption font-bold underline underline-offset-3">
<FormattedMessage id="host.joinLink" />
</Link>
</div>
</section>
<HowItWorksSteps
variant="cards"
className="max-w-[880px]"
steps={HOST_STEPS.map((id) => <FormattedMessage key={id} id={id} />)}
/>
</EntryShell>
);
56 changes: 56 additions & 0 deletions apps/web/src/features/host/HostPhone.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { buttonVariants, Heading, HowItWorksSteps, Logo, PhoneShell, TrustNote, TvMock } from "@gamemash/ui";
import { Link } from "@tanstack/react-router";
import { FormattedMessage, useIntl } from "react-intl";
import type { EntryLayoutProps } from "../entry/entry-layout";
import { HOST_FORM_ID, HOST_STEPS } from "./host-layout";

const SAMPLE_ROOM_CODE = "KWPX";

export const HostPhone = ({ fields, submit, onSubmit }: EntryLayoutProps) => {
const intl = useIntl();
return (
<PhoneShell
theme="workshop"
isBottomActionSticky
contentClassName="gap-3.5 px-5 pt-[calc(env(safe-area-inset-top)+20px)]"
mainClassName="gap-3.5"
header={
<>
<Logo hasOutline={false} />
<Link
to="/"
className={buttonVariants({
variant: "secondary",
size: "sm",
className: "workshop:min-h-9 workshop:rounded-key workshop:px-3 workshop:shadow-brutal-sm",
})}
>
<FormattedMessage id="host.joinInstead" />
</Link>
</>
}
footer={
<TrustNote size="note" tone="white">
<FormattedMessage id="host.trust" />
</TrustNote>
}
bottomAction={
<>
{submit}
<p className="text-center text-sm text-fg-subtle">
<FormattedMessage id="host.laptopHint" />
</p>
</>
}
>
<Heading size="host" className="mt-1">
<FormattedMessage id="host.title" />
</Heading>
<TvMock title={intl.formatMessage({ id: "lobby.title" })} code={SAMPLE_ROOM_CODE} />
<HowItWorksSteps variant="phone" steps={HOST_STEPS.map((id) => <FormattedMessage key={id} id={id} />)} />
<form id={HOST_FORM_ID} noValidate onSubmit={onSubmit} className="mt-1 flex flex-col gap-2">
{fields}
</form>
</PhoneShell>
);
};
73 changes: 73 additions & 0 deletions apps/web/src/features/host/HostScreen.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { SESSION_NAME_MAX_LENGTH } from "@gamemash/games/config";
import { stripHiddenCharacters } from "@gamemash/shared";
import { Button, PlayIcon, TextField } from "@gamemash/ui";
import { useMutation } from "@tanstack/react-query";
import { useNavigate } from "@tanstack/react-router";
import { type FormEvent, useState } from "react";
import { FormattedMessage, useIntl } from "react-intl";
import { saveCredentials } from "../../lib/credentials";
import { toApiError, useErrorMessage } from "../../lib/errors";
import { createSession } from "../../lib/sessions";
import { DESKTOP_QUERY, useMediaQuery } from "../../lib/use-media-query";
import { HostDesktop } from "./HostDesktop";
import { HostPhone } from "./HostPhone";
import { HOST_FORM_ID } from "./host-layout";

export const HostScreen = () => {
const intl = useIntl();
const navigate = useNavigate();
const formatError = useErrorMessage();
const isDesktop = useMediaQuery(DESKTOP_QUERY);
const [name, setName] = useState("");
const create = useMutation({
mutationFn: createSession,
onSuccess: ({ sessionId, roomCode, hostToken }) => {
saveCredentials({ role: "host", sessionId, roomCode, hostToken });
void navigate({ to: "/host/$sessionId/setup", params: { sessionId } });
},
});

const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
create.mutate(name);
};

const fields = (
<>
<TextField
label={
<FormattedMessage
id="host.nameLabel"
values={{ muted: (chunks) => <span className="font-normal text-fg-subtle">{chunks}</span> }}
/>
}
placeholder={intl.formatMessage({ id: "host.namePlaceholder" })}
maxLength={SESSION_NAME_MAX_LENGTH}
value={name}
onValueChange={(value: string) => setName(stripHiddenCharacters(value))}
controlClassName="workshop:h-14 workshop:rounded-control workshop:shadow-brutal-sm"
/>
{create.isError && (
<p role="alert" className="text-body font-bold text-danger">
{formatError(toApiError(create.error))}
</p>
)}
</>
);

const submit = (
<Button
size="lg"
type="submit"
form={HOST_FORM_ID}
disabled={create.isPending}
icon={isDesktop ? <PlayIcon size={22} /> : undefined}
className="workshop:h-16 workshop:text-2xl workshop:shadow-brutal-md"
>
<FormattedMessage id={create.isPending ? "host.creating" : "host.create"} />
</Button>
);

const Layout = isDesktop ? HostDesktop : HostPhone;
return <Layout fields={fields} submit={submit} onSubmit={handleSubmit} />;
};
2 changes: 2 additions & 0 deletions apps/web/src/features/host/host-layout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const HOST_FORM_ID = "host";
export const HOST_STEPS = ["host.step1", "host.step2", "host.step3"];
Loading
Loading