pages.test.ts
This file
Path
apps/platform/test/pages.test.ts
654 lines · 18.9 KiB · TypeScript
Last changed by
Merge redesign into mainoscabrielbefore adoptioncaedd21
History of this fileTake it
1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { FrontPageMemory } from "@repo/project/front-page/memory";4import { Projects } from "@repo/project/projects";5import { ProjectName } from "@repo/protocol/ids";6import { UnknownProject } from "@repo/protocol/refusal";7import { Effect, Layer, Option } from "effect";89import {10 ACCOUNT_PATHS,11 addEmailPage,12 codePage,13 problemPage,14 profilePage,15 resetPage,16 signInPage,17 signUpPage,18} from "../src/auth/pages.ts";19import type { Asker, PendingForm } from "../src/auth/pages.ts";20import { homeResponse } from "../src/home.ts";21import { HostInfo } from "../src/host-info.ts";2223const claude: Asker = {24 clientDomain: "claude.ai",25 clientName: "Claude",26 redirectHost: "claude.ai",27 redirectIsLoopback: false,28};2930const local: Asker = {31 clientName: "A CLI",32 redirectHost: "127.0.0.1:53682",33 redirectIsLoopback: true,34};3536const form: PendingForm = { csrf: "csrf-token", request: "sealed-request" };3738const home = Effect.gen(function* () {39 const response = yield* homeResponse(40 new Request("https://platform.example/", {41 headers: { accept: "text/html" },42 })43 );4445 return yield* Effect.promise(() => response.text());46}).pipe(47 Effect.provide(48 Layer.mergeAll(49 FrontPageMemory.layer({50 credits: [],51 entries: [],52 projects: [53 {54 openAsks: 2,55 posture: "open",56 project: ProjectName.make("alice/datekit"),57 },58 ],59 }),60 Layer.succeed(61 Projects,62 Projects.of({63 create: () => Effect.die("the home page makes no project"),64 get: (project) => Effect.fail(new UnknownProject({ project })),65 })66 ),67 Layer.succeed(68 HostInfo,69 HostInfo.of({70 draftModel: "@cf/test/drafter",71 webUrl: Option.some("https://web.example"),72 })73 )74 )75 )76);7778const PAGES = {79 "Google's profile page": profilePage(80 local,81 form,82 "/authorize?x=1",83 { displayName: "Carol Example", handle: "carol" },84 "That handle is taken. Choose another, or sign in."85 ),86 "adding an email": addEmailPage(87 claude,88 form,89 "/authorize?x=1",90 "alice@mail.example",91 "Another account already uses that email. Add a different one."92 ),93 "entering a code": codePage(94 claude,95 form,96 {97 action: ACCOUNT_PATHS.signUpVerify,98 intro: "We mailed a code to alice@mail.example.",99 newPassword: false,100 startOverHref: "/authorize?x=1",101 },102 "That code is wrong or has expired."103 ),104 "resetting a password": resetPage(105 local,106 form,107 "/authorize?x=1",108 "alice@mail.example"109 ),110 "setting a new password by code": codePage(local, form, {111 action: ACCOUNT_PATHS.resetVerify,112 intro: "If an account uses alice@mail.example, we mailed it a code.",113 newPassword: true,114 startOverHref: "/authorize?x=1",115 }),116 "sign-in": signInPage(117 claude,118 form,119 { google: true },120 "The email, handle or password is wrong."121 ),122 "sign-up": signUpPage(123 local,124 form,125 "/authorize?x=1",126 { displayName: "Alice", email: "alice@mail.example", handle: "alice" },127 "A password is 12 to 256 characters."128 ),129 "the problem page": problemPage(130 "This sign-in page expired or was not opened here. Start signing in again from your app."131 ),132} as const;133134const FORMS = new Set(135 Object.keys(PAGES).filter((name) => name !== "the problem page")136);137138interface Rule {139 readonly selectors: readonly string[];140 readonly declarations: ReadonlyMap<string, string>;141 readonly dark: boolean;142}143144const styleOf = (html: string) => {145 const styles = [...html.matchAll(/<style>(?<css>.*?)<\/style>/gsu)];146147 expect(styles).toHaveLength(1);148149 return styles[0]?.groups?.css ?? "";150};151152const DEPTH: ReadonlyMap<string, number> = new Map([153 ["{", 1],154 ["}", -1],155]);156157const DARK = /^@media\s*\(\s*prefers-color-scheme\s*:\s*dark\s*\)$/u;158159const rulesOf = (css: string, dark = false): readonly Rule[] => {160 const rules: Rule[] = [];161 const text = css.replaceAll(/\/\*.*?\*\//gsu, "");162 let at = 0;163164 while (at < text.length) {165 const open = text.indexOf("{", at);166167 if (open === -1) {168 break;169 }170171 const head = text.slice(at, open).trim();172 let depth = 1;173 let close = open + 1;174175 while (depth > 0 && close < text.length) {176 depth += DEPTH.get(text[close] ?? "") ?? 0;177 close += 1;178 }179180 const body = text.slice(open + 1, close - 1);181182 if (head.startsWith("@media")) {183 rules.push(...(DARK.test(head) ? rulesOf(body, true) : []));184 } else {185 rules.push({186 dark,187 declarations: new Map(188 body189 .split(";")190 .map((declaration) => declaration.split(":"))191 .filter((parts) => parts.length >= 2)192 .map(([name = "", ...value]) => [193 name.trim(),194 value.join(":").trim(),195 ])196 ),197 selectors: head.split(",").map((selector) => selector.trim()),198 });199 }200201 at = close;202 }203204 return rules;205};206207type Scheme = "dark" | "light";208209interface Resolved {210 readonly value: string | undefined;211 readonly fromDark: boolean;212}213214const resolve = (215 rules: readonly Rule[],216 scheme: Scheme,217 selector: string,218 property: string219): Resolved => {220 const applying = rules.filter(221 (rule) =>222 (scheme === "dark" || !rule.dark) &&223 rule.selectors.includes(selector) &&224 rule.declarations.has(property)225 );226227 const rule = applying.at(-1);228 const value = rule?.declarations.get(property);229230 const variable = /^var\((?<name>--[\w-]+)\)$/u.exec(value ?? "")?.groups231 ?.name;232233 if (variable === undefined) {234 return { fromDark: rule?.dark ?? false, value };235 }236237 const inner = resolve(rules, scheme, ":root", variable);238239 return {240 fromDark: (rule?.dark ?? false) || inner.fromDark,241 value: inner.value,242 };243};244245const channelsOf = (hex: string) => {246 const digits = /^#(?<body>[\da-f]{3}|[\da-f]{6})$/iu.exec(hex)?.groups?.body;247248 expect(digits, `${hex} is a literal hex colour`).toBeDefined();249250 const full =251 digits?.length === 3252 ? digits.replaceAll(/(?<digit>.)/gu, "$<digit>$<digit>")253 : (digits ?? "000000");254255 return [0, 2, 4].map((start) =>256 Number.parseInt(full.slice(start, start + 2), 16)257 );258};259260const linearOf = (hex: string) =>261 channelsOf(hex).map((channel) => {262 const unit = channel / 255;263264 return unit <= 0.04045 ? unit / 12.92 : ((unit + 0.055) / 1.055) ** 2.4;265 });266267const luminanceOf = (hex: string) => {268 const [r = 0, g = 0, b = 0] = linearOf(hex);269270 return 0.2126 * r + 0.7152 * g + 0.0722 * b;271};272273// OKLCH's chroma and hue, by Björn Ottosson's published matrices.274const chromaAndHueOf = (hex: string) => {275 const [r = 0, g = 0, b = 0] = linearOf(hex);276 const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);277 const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);278 const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);279 const a = 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s;280 const bee = 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s;281282 return {283 chroma: Math.hypot(a, bee),284 hue: ((Math.atan2(bee, a) * 180) / Math.PI + 360) % 360,285 };286};287288const contrast = (one: string, other: string) => {289 const [light, dark] = [luminanceOf(one), luminanceOf(other)].toSorted(290 (a, b) => b - a291 );292293 return ((light ?? 0) + 0.05) / ((dark ?? 0) + 0.05);294};295296const colour = (297 rules: readonly Rule[],298 scheme: Scheme,299 selector: string,300 property: string301) => {302 const { value } = resolve(rules, scheme, selector, property);303304 expect(value, `${selector} sets ${property} in ${scheme}`).toBeDefined();305306 return value ?? "";307};308309const holdsTheFloors = (310 rules: readonly Rule[],311 scheme: Scheme,312 hasForm: boolean,313 ground = "body"314) => {315 const paper = colour(rules, scheme, ground, "background-color");316317 const at = (selector: string, property = "color") =>318 contrast(colour(rules, scheme, selector, property), paper);319320 expect(at("body"), "body text").toBeGreaterThanOrEqual(4.5);321 expect(at("a"), "links").toBeGreaterThanOrEqual(4.5);322 expect(at(".error"), "an error").toBeGreaterThanOrEqual(4.5);323 expect(at(".muted"), "muted text").toBeGreaterThanOrEqual(4.5);324 expect(at(".warn"), "the warning's word").toBeGreaterThanOrEqual(4.5);325326 if (hasForm) {327 expect(at("input", "border-color"), "input borders").toBeGreaterThanOrEqual(328 3329 );330 expect(331 contrast(332 colour(rules, scheme, "input", "color"),333 colour(rules, scheme, "input", "background-color")334 ),335 "input text"336 ).toBeGreaterThanOrEqual(4.5);337 expect(338 contrast(339 colour(rules, scheme, "button", "color"),340 colour(rules, scheme, "button", "background-color")341 ),342 "the primary button"343 ).toBeGreaterThanOrEqual(4.5);344 }345};346347describe("the platform's own pages", () => {348 const each = [349 ...Object.entries(PAGES).map(([name, html]) => ({350 card: true,351 form: FORMS.has(name),352 html: Effect.succeed(html),353 name,354 })),355 { card: false, form: false, html: home, name: "the platform's /" },356 ];357358 describe.each(each)("$name", (page) => {359 it.effect("loads nothing: no script, stylesheet, font or image", () =>360 Effect.gen(function* () {361 expect(yield* page.html).not.toMatch(362 /<script|<link|<img|src=|url\(|@import|@font-face/u363 );364 })365 );366367 it.effect("follows the system's scheme and colours its links in both", () =>368 Effect.gen(function* () {369 const rules = rulesOf(styleOf(yield* page.html));370371 expect(resolve(rules, "light", ":root", "color-scheme").value).toBe(372 "light dark"373 );374 expect(resolve(rules, "dark", "a", "color").fromDark).toBeTruthy();375 expect(376 resolve(rules, "dark", "body", "background-color").fromDark377 ).toBeTruthy();378 })379 );380381 it.effect("holds every contrast floor in the light and dark schemes", () =>382 Effect.gen(function* () {383 const rules = rulesOf(styleOf(yield* page.html));384385 for (const ground of page.card ? ["body", ".card"] : ["body"]) {386 holdsTheFloors(rules, "light", page.form, ground);387 holdsTheFloors(rules, "dark", page.form, ground);388 }389 })390 );391392 it.effect("lets the keyboard reach a block that scrolls sideways", () =>393 Effect.gen(function* () {394 const html = yield* page.html;395396 expect(html.match(/<pre\b[^>]*>/gu) ?? []).toStrictEqual(397 (html.match(/<pre\b[^>]*>/gu) ?? []).map(() => '<pre tabindex="0">')398 );399 })400 );401402 it.effect("reads at 16 px, inputs too", () =>403 Effect.gen(function* () {404 const rules = rulesOf(styleOf(yield* page.html));405406 expect(resolve(rules, "light", "body", "font-size").value).toBe("16px");407 expect(resolve(rules, "light", "input", "font-size").value).toBe(408 "16px"409 );410 })411 );412 });413});414415const SIGN_IN_PAGES = Object.entries(PAGES).map(([name, html]) => ({416 html,417 name,418}));419420const EDGES = /^(?:border-(?:top|right|bottom|left)|box-shadow|outline)/u;421422describe.each(SIGN_IN_PAGES)("$name, in the focus look", ({ html }) => {423 it("shows the wordmark as text, then one card, and no navigation", () => {424 const wordmark = html.indexOf(`<p class="wordmark">${Brand.name}</p>`);425 const card = html.indexOf('class="card"');426427 expect(wordmark).toBeGreaterThan(html.indexOf("<body"));428 expect(card).toBeGreaterThan(wordmark);429 expect(html.indexOf("<h1")).toBeGreaterThan(card);430 expect(html.match(/class="card"/gu)).toHaveLength(1);431 expect(html).not.toMatch(/<nav\b|<svg[^>]*class="mark"/u);432 });433434 it("sets the web's faces and paper", () => {435 const rules = rulesOf(styleOf(html));436437 expect(resolve(rules, "light", "body", "font-family").value).toMatch(438 /^"IBM Plex Sans",/u439 );440 expect(resolve(rules, "light", "code", "font-family").value).toMatch(441 /^"IBM Plex Mono",/u442 );443 expect(colour(rules, "light", "body", "background-color")).toBe("#f8f7f4");444 expect(colour(rules, "dark", "body", "background-color")).toBe("#0a0a0a");445 });446447 it("draws every colour as a hex, and none orange, brown or amber", () => {448 const css = styleOf(html);449450 const warm = [...css.matchAll(/#(?<digits>[\da-f]{6})/giu)].flatMap(451 (found) => {452 const hex = `#${found.groups?.digits ?? ""}`;453 const { chroma, hue } = chromaAndHueOf(hex);454455 return chroma > 0.02 && hue >= 40 && hue <= 100 ? [hex] : [];456 }457 );458459 expect(css).not.toMatch(/\b(?:rgba?|hsla?|oklch|oklab|lab|lch)\(/u);460 expect(warm).toStrictEqual([]);461 });462463 it("keeps the card a plain bordered surface, with nothing on an edge", () => {464 const rules = rulesOf(styleOf(html));465466 const card = rules.filter((rule) => rule.selectors.includes(".card"));467468 expect(card.flatMap((rule) => [...rule.declarations.keys()])).toContain(469 "border"470 );471 expect(472 card.flatMap((rule) =>473 [...rule.declarations.keys()].filter((name) => EDGES.test(name))474 )475 ).toStrictEqual([]);476 expect(477 rules478 .flatMap((rule) => rule.selectors)479 .filter((at) => /::?(?:before|after)/u.test(at))480 ).toStrictEqual([]);481 });482});483484const consentOf = (html: string) =>485 /<section class="consent"[^>]*>(?<body>.*?)<\/section>/su.exec(html)?.groups486 ?.body ?? "";487488const consentLabelOf = (html: string) =>489 /<section class="consent" aria-label="(?<label>[^"]*)">/u.exec(html)?.groups490 ?.label;491492const mayListOf = (html: string) =>493 /<ul class="may">.*?<\/ul>/su.exec(consentOf(html))?.[0];494495describe("the sign-in page, as an MCP client's consent", () => {496 it("names the client and lists what it may do as you", () => {497 const consent = consentOf(PAGES["sign-in"]);498499 expect(consent).toContain(500 "<strong>Claude</strong> (published by claude.ai)"501 );502 expect(consent.match(/<li>/gu)).toHaveLength(4);503 expect(consent).toContain("<li>Claim, release and answer asks");504 expect(consent).toContain("It never sees your password.");505 expect(consent).toContain(506 "finish answers, land changes, vouch for or denounce people"507 );508 });509510 it("lists the same on the sign-up page, where a newcomer allows it", () => {511 expect(mayListOf(PAGES["sign-up"])).toBeDefined();512 expect(mayListOf(PAGES["sign-up"])).toBe(mayListOf(PAGES["sign-in"]));513 });514515 it("names the consent region for what it says", () => {516 expect(consentLabelOf(PAGES["sign-in"])).toBe(517 "Who asks and what it may do"518 );519 expect(consentLabelOf(PAGES["sign-up"])).toBe(520 "Who asks and what it may do"521 );522 expect(consentLabelOf(PAGES["adding an email"])).toBe("Who asks");523 expect(mayListOf(PAGES["adding an email"])).toBeUndefined();524 });525526 it("escapes every value a client supplies, on every page that names it", () => {527 const hostile: Asker = {528 clientDomain: `"><img src=x>`,529 clientName: `<script>alert("x")</script>`,530 redirectHost: "evil.example<b>",531 redirectIsLoopback: true,532 };533534 const named = [535 signUpPage(hostile, form, "/authorize", {}),536 profilePage(hostile, form, "/authorize", {}),537 addEmailPage(hostile, form, "/authorize"),538 resetPage(hostile, form, "/authorize"),539 codePage(hostile, form, {540 action: ACCOUNT_PATHS.signUpVerify,541 intro: "We mailed a code.",542 newPassword: false,543 startOverHref: "/authorize",544 }),545 ];546547 for (const html of named) {548 expect(html).not.toMatch(/<script|<img|<b>/u);549 expect(html).toContain(550 "<script>alert("x")</script>"551 );552 }553 });554555 it("says who asks and where access goes before Google and the form", () => {556 const html = PAGES["sign-in"];557 const asks = html.indexOf("asks to act as you");558 const goes = html.indexOf("Access goes to");559 const google = html.indexOf("Continue with Google");560 const formAt = html.indexOf("<form");561562 expect(asks).toBeGreaterThan(html.indexOf("<h1"));563 expect(goes).toBeGreaterThan(asks);564 expect(google).toBeGreaterThan(goes);565 expect(formAt).toBeGreaterThan(google);566 expect(html.indexOf("New here?")).toBeGreaterThan(formAt);567 });568569 it("puts the loopback warning in the consent, as a word, before the form", () => {570 const html = signInPage(local, form, { google: false });571 const warning = html.indexOf("Warning");572573 expect(warning).toBeGreaterThan(html.indexOf("Access goes to"));574 expect(warning).toBeLessThan(html.indexOf("<form"));575 expect(html).toContain(576 "This sends access to an app on your computer. Continue only if you just started signing in from it."577 );578 expect(signInPage(claude, form, { google: false })).not.toContain(579 "Warning"580 );581 });582583 it("escapes every value a client supplies", () => {584 const html = signInPage(585 {586 clientDomain: `"><img src=x>`,587 clientName: `<script>alert("x")</script>`,588 redirectHost: "evil.example<b>",589 redirectIsLoopback: false,590 },591 { csrf: `"><script>`, request: `a"b` },592 { google: true }593 );594595 expect(html).not.toContain("<script>");596 expect(html).not.toContain("<img");597 expect(html).not.toContain("<b>");598 expect(html).toContain("<script>alert("x")</script>");599 expect(html).toContain("evil.example<b>");600 });601602 it("draws an error in the refusal's colour, and the problem page's in ink", () => {603 expect(PAGES["sign-in"]).toMatch(604 /<p class="error" role="alert">The email, handle or password is wrong\.<\/p>/u605 );606 expect(PAGES["the problem page"]).not.toContain('class="error"');607 expect(PAGES["the problem page"]).toMatch(/<a href="\/">/u);608 });609});610611describe("a sign-in form shown again", () => {612 it("escapes every value the person typed", () => {613 const typed = `"><script>alert(1)</script>`;614615 const pages = [616 signUpPage(local, form, "/authorize", {617 displayName: typed,618 email: typed,619 handle: typed,620 }),621 profilePage(local, form, "/authorize", {622 displayName: typed,623 handle: typed,624 }),625 addEmailPage(local, form, "/authorize", typed),626 resetPage(local, form, "/authorize", typed),627 ];628629 for (const html of pages) {630 expect(html).not.toContain("<script>");631 expect(html).toContain(632 `value=""><script>alert(1)</script>"`633 );634 }635 });636637 it("never fills in a password", () => {638 expect(639 signUpPage(local, form, "/authorize", { email: "alice@mail.example" })640 ).toMatch(/<input type="password" name="password" [^>]*required>/u);641 });642});643644describe("the sign-in page's ways out", () => {645 it("links to resetting a password and to signing up, carrying the sealed request", () => {646 const html = signInPage(claude, form, { google: false });647648 expect(html).toContain(649 `href="${ACCOUNT_PATHS.reset}?request=sealed-request"`650 );651 expect(html).toContain('href="/signup?request=sealed-request"');652 expect(html).toContain("Email or handle");653 });654});