Skip to content
Myr

session.test.ts

This file

Path

apps/web/test/session.test.ts

983 lines · 29.2 KiB · TypeScript

Last changed by

Merge redesign into mainoscabrielbefore adoptioncaedd21

History of this file

Take it

1import { describe, expect, it } from "@effect/vitest";2import { Handle } from "@repo/protocol/ids";3import { untouchable } from "@repo/testkit/untouchable";4import { Effect, Option, Schema } from "effect";5import { createElement } from "react";6import { renderToStaticMarkup } from "react-dom/server";78import { hereOf, SessionView } from "../src/features/auth/session-slot.tsx";9import { devSignIn } from "../src/routes/auth/-dev.ts";10import { backend } from "../src/server/backend.ts";11import { serverClientOver } from "../src/server/client.ts";12import {13  callbackHandler,14  challengeOf,15  clearedCookie,16  clientMetadataHandler,17  credentialFrom,18  HANDLE_COOKIE,19  pkce,20  SESSION_COOKIE,21  sessionCookie,22  signInHandler,23  signOutHandler,24  whoamiHandler,25  withCredential,26} from "../src/server/session.ts";2728const PLATFORM_URL = "https://platform-test.example.workers.dev";2930const WEB_URL = "https://web-test.example.workers.dev";3132const LIST_ASKS =33  '[{"_tag":"Request","id":"0","tag":"listAsks","payload":{"project":"datekit"},"headers":[]}]';3435/** What the platform's `/token` answers a good code with (1.2.1's shape). */36const TOKEN_ANSWER = {37  access_token: "alice:grant1:tok-from-platform",38  expires_in: 3600,39  refresh_token: "alice:grant1:refresh-secret",40  scope: "",41  token_type: "bearer",42};4344const seenOf = (request: Request) =>45  Effect.map(46    Effect.promise(() => request.text()),47    (body) => ({48      authorization: request.headers.get("authorization"),49      body,50      cookie: request.headers.get("cookie"),51      method: request.method,52      url: request.url,53    })54  );5556const recorder = (answer: (request: Request) => Response) => {57  const handed: Request[] = [];5859  const fetch = (request: Request) => {60    handed.push(request);6162    return Promise.resolve(answer(request));63  };6465  return { fetch, seen: Effect.suspend(() => Effect.forEach(handed, seenOf)) };66};6768const envWith = (fetch: (request: Request) => Promise<Response>): Env => ({69  PLATFORM: untouchable<Fetcher>("PLATFORM", {70    fetch: (input, init) => fetch(new Request(input, init)),71  }),72  PUBLIC_PLATFORM_URL: PLATFORM_URL,73});7475const unreachable: Env = {76  PLATFORM: untouchable<Fetcher>("PLATFORM"),77  PUBLIC_PLATFORM_URL: PLATFORM_URL,78};7980const listAsksPost = (headers: Readonly<Record<string, string>> = {}) =>81  new Request(`${WEB_URL}/rpc`, {82    body: LIST_ASKS,83    headers: { "content-type": "application/json", ...headers },84    method: "POST",85  });8687const get = (path: string, headers: Readonly<Record<string, string>> = {}) =>88  new Request(`${WEB_URL}${path}`, { headers });8990const cookiesOf = (response: Response) =>91  response.headers.getSetCookie().map((line) => {92    const [pair = "", ...attributes] = line93      .split(";")94      .map((part) => part.trim());9596    const at = pair.indexOf("=");9798    return {99      attributes: attributes.map((attribute) => attribute.toLowerCase()),100      name: pair.slice(0, at),101      pair,102      value: pair.slice(at + 1),103    };104  });105106const expiriesOf = (response: Response) =>107  cookiesOf(response).map(({ attributes, name }) => [108    name,109    attributes.includes("max-age=0"),110  ]);111112const maxAgeOf = (attributes: readonly string[]) =>113  Number(114    attributes.find((attribute) => attribute.startsWith("max-age="))?.slice(8)115  );116117const LOCKED_DOWN = ["httponly", "secure", "samesite=lax", "path=/"] as const;118119const lockedDown = (attributes: readonly string[] = []) =>120  LOCKED_DOWN.every((attribute) => attributes.includes(attribute));121122const textOf = (response: Response) => Effect.promise(() => response.text());123124const paramsOf = (url: URL, names: readonly string[]) =>125  Object.fromEntries(names.map((name) => [name, url.searchParams.get(name)]));126127const replyingWith = (exit: string) => {128  const parts: string[] = [];129130  return new TransformStream<string, string>({131    flush: (controller) => {132      const id =133        /"id":(?<id>"[^"]*"|\d+)/u.exec(parts.join(""))?.groups?.id ?? "null";134135      controller.enqueue(`[{"_tag":"Exit","requestId":${id},"exit":${exit}}]`);136    },137    transform: (chunk) => {138      parts.push(chunk);139    },140  });141};142143const statusReply = (exit: string) => (request: Request) =>144  new Response(145    (request.clone().body ?? new Blob().stream())146      .pipeThrough(new TextDecoderStream())147      .pipeThrough(replyingWith(exit))148      .pipeThrough(new TextEncoderStream()),149    { headers: { "content-type": "application/json" } }150  );151152const STATUS_OF_INES =153  '{"_tag":"Success","value":{"answers":[],"claims":[],"handle":"ines-v"}}';154155const UNAUTHENTICATED =156  '{"_tag":"Failure","cause":[{"_tag":"Fail","error":{"_tag":"Unauthenticated"}}]}';157158describe("the session cookie", () => {159  it("is read from the cookie header, among the others", () => {160    expect(161      [162        `theme=dark; ${SESSION_COOKIE}=tok123; other=1`,163        "theme=dark",164        `${SESSION_COOKIE}=`,165        `${SESSION_COOKIE}=two%20words`,166      ].map((cookie) => credentialFrom(get("/rpc", { cookie })))167    ).toStrictEqual([168      Option.some("tok123"),169      Option.none(),170      Option.none(),171      Option.none(),172    ]);173    expect(credentialFrom(get("/rpc"))).toStrictEqual(Option.none());174  });175176  it("reads back the token a session cookie was set with", () => {177    const token = "alice:grant1:tok/with+odd=chars";178    const [pair = ""] = sessionCookie(token, 60).split(";");179180    expect(credentialFrom(get("/rpc", { cookie: pair }))).toStrictEqual(181      Option.some(token)182    );183  });184185  it("is HttpOnly, Secure, SameSite=Lax, on every path, for as long as it is given", () => {186    const [cookie] = cookiesOf(187      new Response(null, { headers: { "set-cookie": sessionCookie("t", 90) } })188    );189190    expect(cookie?.name).toBe(SESSION_COOKIE);191    expect(cookie?.attributes).toStrictEqual(192      expect.arrayContaining([...LOCKED_DOWN, "max-age=90"])193    );194  });195196  it("is cleared by a cookie of the same name that expires now", () => {197    const [cookie] = cookiesOf(198      new Response(null, { headers: { "set-cookie": clearedCookie() } })199    );200201    expect(cookie?.name).toBe(SESSION_COOKIE);202    expect(cookie?.value).toBe("");203    expect(cookie?.attributes).toStrictEqual(204      expect.arrayContaining([...LOCKED_DOWN, "max-age=0"])205    );206  });207208  it("becomes the only credential a forwarded request carries", () => {209    const forwarded = withCredential(210      get("/rpc", {211        authorization: "Bearer chosen-by-the-browser",212        cookie: `${SESSION_COOKIE}=tok123`,213      }),214      Option.some("tok123")215    );216217    const anonymous = withCredential(218      get("/rpc", { authorization: "Bearer chosen-by-the-browser" }),219      Option.none()220    );221222    expect(forwarded.headers.get("authorization")).toBe("Bearer tok123");223    expect(forwarded.headers.get("cookie")).toBeNull();224    expect(anonymous.headers.get("authorization")).toBeNull();225  });226});227228describe("PKCE", () => {229  it.effect("challenges with S256 (RFC 7636 appendix B)", () =>230    Effect.gen(function* () {231      expect(232        yield* challengeOf("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk")233      ).toBe("E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM");234    })235  );236237  it.effect("draws a fresh verifier and state each time, from WebCrypto", () =>238    Effect.gen(function* () {239      const first = yield* pkce;240      const second = yield* pkce;241242      expect(first.verifier).toMatch(/^[\w-]{43,128}$/u);243      expect(first.state).toMatch(/^[\w-]{22,}$/u);244      expect(first.challenge).toBe(yield* challengeOf(first.verifier));245      expect([second.verifier, second.state]).not.toStrictEqual([246        first.verifier,247        first.state,248      ]);249    })250  );251});252253describe("the production backend", () => {254  it.effect(255    "forwards a /rpc call with the session cookie's token as a bearer, and no cookie",256    () =>257      Effect.gen(function* () {258        const platform = recorder(() => new Response("from the platform"));259260        const response = yield* Effect.promise(() =>261          backend(262            listAsksPost({ cookie: `${SESSION_COOKIE}=tok123; other=1` }),263            envWith(platform.fetch)264          )265        );266267        expect(yield* platform.seen).toStrictEqual([268          {269            authorization: "Bearer tok123",270            body: LIST_ASKS,271            cookie: null,272            method: "POST",273            url: `${PLATFORM_URL}/rpc`,274          },275        ]);276        expect(yield* textOf(response)).toBe("from the platform");277      })278  );279280  it.effect(281    "drops an authorization the browser set, and forwards a call with no cookie with no credential",282    () =>283      Effect.gen(function* () {284        const platform = recorder(() => new Response("public"));285286        yield* Effect.promise(() =>287          backend(288            listAsksPost({ authorization: "Bearer chosen-by-the-browser" }),289            envWith(platform.fetch)290          )291        );292293        expect(yield* platform.seen).toStrictEqual([294          {295            authorization: null,296            body: LIST_ASKS,297            cookie: null,298            method: "POST",299            url: `${PLATFORM_URL}/rpc`,300          },301        ]);302      })303  );304305  it.effect(306    "asks again with no credential when the platform no longer knows the token, and expires the cookie",307    () =>308      Effect.gen(function* () {309        const platform = recorder((request) =>310          request.headers.has("authorization")311            ? new Response(null, {312                headers: { "www-authenticate": 'Bearer error="invalid_token"' },313                status: 401,314              })315            : new Response("as anyone")316        );317318        const response = yield* Effect.promise(() =>319          backend(320            listAsksPost({ cookie: `${SESSION_COOKIE}=stale` }),321            envWith(platform.fetch)322          )323        );324325        const seen = yield* platform.seen;326327        expect(328          seen.map(({ authorization, body }) => [authorization, body])329        ).toStrictEqual([330          ["Bearer stale", LIST_ASKS],331          [null, LIST_ASKS],332        ]);333        expect([response.status, yield* textOf(response)]).toStrictEqual([334          200,335          "as anyone",336        ]);337        expect(expiriesOf(response)).toStrictEqual([338          [SESSION_COOKIE, true],339          [HANDLE_COOKIE, true],340        ]);341      })342  );343344  it.effect("carries the session on a GET too, at the platform's URL", () =>345    Effect.gen(function* () {346      const platform = recorder(() => new Response("ok"));347348      yield* Effect.promise(() =>349        backend(350          get("/releases/x?y=1", { cookie: `${SESSION_COOKIE}=tok123` }),351          envWith(platform.fetch)352        )353      );354355      expect(356        (yield* platform.seen).map(({ authorization, method, url }) => [357          method,358          url,359          authorization,360        ])361      ).toStrictEqual([362        ["GET", `${PLATFORM_URL}/releases/x?y=1`, "Bearer tok123"],363      ]);364    })365  );366});367368const signIn = (path: string) =>369  Effect.gen(function* () {370    const response = yield* Effect.promise(() =>371      signInHandler(unreachable)({ request: get(path) })372    );373374    const location = new URL(response.headers.get("location") ?? "");375    const [state] = cookiesOf(response);376377    return { location, response, state };378  });379380const clientOver = (env: Env) => (request: Request) =>381  serverClientOver(backend)(env, request);382383const unreachableCallback = callbackHandler(384  unreachable,385  clientOver(unreachable)386);387388const signInAndBack = (389  path: string,390  code: string,391  answer: () => Response = () => Response.json(TOKEN_ANSWER),392  status: (request: Request) => Response = statusReply(STATUS_OF_INES)393) =>394  Effect.gen(function* () {395    const { location, state } = yield* signIn(path);396397    const platform = recorder((request) =>398      new URL(request.url).pathname.startsWith("/rpc")399        ? status(request)400        : answer()401    );402403    const env = envWith(platform.fetch);404405    const response = yield* Effect.promise(() =>406      callbackHandler(407        env,408        clientOver(env)409      )({410        request: get(411          `/auth/callback?code=${code}&state=${location.searchParams.get("state") ?? ""}`,412          { cookie: state?.pair ?? "" }413        ),414      })415    );416417    return { location, response, seen: yield* platform.seen, state };418  });419420const backTo = (path: string) =>421  Effect.map(422    signInAndBack(`/auth/signin?return=${encodeURIComponent(path)}`, "c0de"),423    ({ response }) => response.headers.get("location")424  );425426describe("sign-in", () => {427  it.effect(428    "sends the browser to the platform's /authorize as the web's public client, with S256",429    () =>430      Effect.gen(function* () {431        const { location, response } = yield* signIn(432          "/auth/signin?return=/inbox"433        );434435        expect(response.status).toBe(302);436        expect(`${location.origin}${location.pathname}`).toBe(437          `${PLATFORM_URL}/authorize`438        );439        expect(440          paramsOf(location, [441            "client_id",442            "code_challenge_method",443            "redirect_uri",444            "response_type",445          ])446        ).toStrictEqual({447          client_id: `${WEB_URL}/auth/client`,448          code_challenge_method: "S256",449          redirect_uri: `${WEB_URL}/auth/callback`,450          response_type: "code",451        });452        expect(location.searchParams.get("code_challenge")).toMatch(453          /^[\w-]{43}$/u454        );455      })456  );457458  it.effect(459    "keeps the state and verifier in a short-lived HttpOnly cookie, never in the URL",460    () =>461      Effect.gen(function* () {462        const { location, state } = yield* signIn("/auth/signin");463464        expect(location.searchParams.get("state")).toMatch(/^[\w-]{22,}$/u);465        expect(state?.name).not.toBe(SESSION_COOKIE);466        expect(lockedDown(state?.attributes)).toBeTruthy();467        expect(maxAgeOf(state?.attributes ?? [])).toBeLessThanOrEqual(600);468        expect(location.searchParams.has("code_verifier")).toBeFalsy();469      })470  );471});472473describe("the callback", () => {474  it.effect(475    "trades the code at the platform's /token over PLATFORM, with the verifier sign-in kept",476    () =>477      Effect.gen(function* () {478        const { location, seen } = yield* signInAndBack(479          "/auth/signin?return=/inbox",480          "c0de"481        );482483        const [exchange, ...more] = seen;484        const form = new URLSearchParams(exchange?.body);485486        // Then once, with the new token, `status`: the handle it names is487        // kept beside the session, so no page asks the platform again.488        expect(489          more.map(({ authorization, body, cookie, url }) => [490            new URL(url).pathname.replace(/\/$/u, ""),491            authorization,492            cookie,493            body.includes('"tag":"status"'),494          ])495        ).toStrictEqual([496          ["/rpc", `Bearer ${TOKEN_ANSWER.access_token}`, null, true],497        ]);498        expect([499          exchange?.method,500          exchange?.url,501          exchange?.cookie,502        ]).toStrictEqual(["POST", `${PLATFORM_URL}/token`, null]);503        expect(504          Object.fromEntries(505            ["client_id", "code", "grant_type", "redirect_uri"].map((name) => [506              name,507              form.get(name),508            ])509          )510        ).toStrictEqual({511          client_id: `${WEB_URL}/auth/client`,512          code: "c0de",513          grant_type: "authorization_code",514          redirect_uri: `${WEB_URL}/auth/callback`,515        });516        expect(yield* challengeOf(form.get("code_verifier") ?? "")).toBe(517          location.searchParams.get("code_challenge")518        );519      })520  );521522  it.effect(523    "sets the token only as the HttpOnly session cookie, for no longer than the token lives, and goes back",524    () =>525      Effect.gen(function* () {526        const { response, state } = yield* signInAndBack(527          "/auth/signin?return=/inbox",528          "c0de"529        );530531        const cookies = cookiesOf(response);532        const session = cookies.find(({ name }) => name === SESSION_COOKIE);533        const maxAge = maxAgeOf(session?.attributes ?? []);534535        expect([536          response.status,537          response.headers.get("location"),538        ]).toStrictEqual([302, "/inbox"]);539        expect(540          credentialFrom(get("/rpc", { cookie: session?.pair ?? "" }))541        ).toStrictEqual(Option.some(TOKEN_ANSWER.access_token));542        expect({543          lockedDown: lockedDown(session?.attributes),544          lives: maxAge > 0 && maxAge <= TOKEN_ANSWER.expires_in,545        }).toStrictEqual({ lives: true, lockedDown: true });546        expect(expiriesOf(response)).toContainEqual([state?.name, true]);547      })548  );549550  it.effect(551    "answers with no token or refresh token in its body or its URL",552    () =>553      Effect.gen(function* () {554        const { response } = yield* signInAndBack("/auth/signin", "c0de");555556        const shown = `${yield* textOf(response)}\n${response.headers.get("location") ?? ""}`;557558        expect(shown).not.toContain("tok-from-platform");559        expect(shown).not.toContain("refresh-secret");560        expect(response.headers.getSetCookie().join("\n")).not.toContain(561          "refresh-secret"562        );563      })564  );565566  it.effect(567    "answers 400 and sets no session when the state is not the one sign-in sent",568    () =>569      Effect.gen(function* () {570        const { state } = yield* signIn("/auth/signin");571572        const response = yield* Effect.promise(() =>573          unreachableCallback({574            request: get("/auth/callback?code=c0de&state=forged", {575              cookie: state?.pair ?? "",576            }),577          })578        );579580        expect(response.status).toBe(400);581        expect(582          cookiesOf(response).filter(({ name }) => name === SESSION_COOKIE)583        ).toStrictEqual([]);584      })585  );586587  it.effect("answers 400 when the browser holds no sign-in in progress", () =>588    Effect.gen(function* () {589      const response = yield* Effect.promise(() =>590        unreachableCallback({591          request: get("/auth/callback?code=c0de&state=anything"),592        })593      );594595      expect(response.status).toBe(400);596      expect(597        cookiesOf(response).filter(({ name }) => name === SESSION_COOKIE)598      ).toStrictEqual([]);599    })600  );601602  it.effect(603    "answers 400 and sets no session when the platform refuses the code",604    () =>605      Effect.gen(function* () {606        const { response } = yield* signInAndBack("/auth/signin", "used", () =>607          Response.json({ error: "invalid_grant" }, { status: 400 })608        );609610        expect(response.status).toBe(400);611        expect(612          cookiesOf(response).filter(({ name }) => name === SESSION_COOKIE)613        ).toStrictEqual([]);614      })615  );616617  it.effect(618    "answers 400 and sets no session when the token is not one the session cookie can carry back",619    () =>620      Effect.gen(function* () {621        const { response } = yield* signInAndBack("/auth/signin", "c0de", () =>622          Response.json({ ...TOKEN_ANSWER, access_token: "two words" })623        );624625        expect(response.status).toBe(400);626        expect(627          cookiesOf(response).filter(({ name }) => name === SESSION_COOKIE)628        ).toStrictEqual([]);629      })630  );631632  it.effect("goes back only to a path on the web itself", () =>633    Effect.gen(function* () {634      expect(635        yield* Effect.forEach(636          [637            "/oscabriel/datekit/asks/a1?tab=check",638            "https://elsewhere.example/",639            "//elsewhere.example/",640            "/\\elsewhere.example/",641            "/auth/signout",642          ],643          backTo644        )645      ).toStrictEqual([646        "/oscabriel/datekit/asks/a1?tab=check",647        "/",648        "/",649        "/",650        "/",651      ]);652    })653  );654});655656describe("sign-out", () => {657  it("goes home and expires the session and handle cookies, by POST or by a plain link", () => {658    const answers = ["POST", "GET"].map((method) => {659      const response = signOutHandler({660        request: new Request(`${WEB_URL}/auth/signout`, {661          headers: { cookie: `${SESSION_COOKIE}=tok123` },662          method,663        }),664      });665666      return [667        response.status,668        response.headers.get("location"),669        expiriesOf(response),670      ];671    });672673    expect(answers).toStrictEqual([674      [675        302,676        "/",677        [678          [SESSION_COOKIE, true],679          [HANDLE_COOKIE, true],680        ],681      ],682      [683        302,684        "/",685        [686          [SESSION_COOKIE, true],687          [HANDLE_COOKIE, true],688        ],689      ],690    ]);691  });692});693694const whoami = (env: Env, headers: Readonly<Record<string, string>> = {}) =>695  Effect.promise(() =>696    whoamiHandler((request) => serverClientOver(backend)(env, request))({697      request: get("/auth/whoami", headers),698    })699  );700701describe("whoami", () => {702  it.effect(703    "answers {} without asking the platform when nobody is signed in",704    () =>705      Effect.gen(function* () {706        const response = yield* whoami(unreachable);707708        expect(response.status).toBe(200);709        expect(yield* textOf(response)).toBe("{}");710      })711  );712713  it.effect(714    "answers the handle the platform's status names for the session",715    () =>716      Effect.gen(function* () {717        const platform = recorder(statusReply(STATUS_OF_INES));718719        const response = yield* whoami(envWith(platform.fetch), {720          cookie: `${SESSION_COOKIE}=tok123`,721        });722723        expect(724          (yield* platform.seen).map(725            ({ authorization, body, cookie, url }) => ({726              authorization,727              cookie,728              path: new URL(url).pathname.replace(/\/$/u, ""),729              status: body.includes('"tag":"status"'),730            })731          )732        ).toStrictEqual([733          {734            authorization: "Bearer tok123",735            cookie: null,736            path: "/rpc",737            status: true,738          },739        ]);740        expect(response.headers.get("cache-control")).toBe("no-store");741        expect(yield* textOf(response)).toBe('{"handle":"ines-v"}');742743        // A session from before the handle was kept: asked once, then kept.744        const kept = cookiesOf(response).filter(745          ({ name }) => name === HANDLE_COOKIE746        );747748        expect(749          kept.map(({ attributes }) => lockedDown(attributes))750        ).toStrictEqual([true]);751752        const again = yield* whoami(unreachable, {753          cookie: [754            `${SESSION_COOKIE}=tok123`,755            ...kept.map(({ pair }) => pair),756          ].join("; "),757        });758759        expect(yield* textOf(again)).toBe('{"handle":"ines-v"}');760      })761  );762763  it.effect(764    "answers {} and expires both cookies when the platform no longer knows the session",765    () =>766      Effect.gen(function* () {767        const platform = recorder((request) =>768          request.headers.has("authorization")769            ? new Response(null, { status: 401 })770            : statusReply(UNAUTHENTICATED)(request)771        );772773        const response = yield* whoami(envWith(platform.fetch), {774          cookie: `${SESSION_COOKIE}=stale`,775        });776777        expect(yield* textOf(response)).toBe("{}");778        expect(expiriesOf(response)).toStrictEqual([779          [SESSION_COOKIE, true],780          [HANDLE_COOKIE, true],781        ]);782      })783  );784});785786const sentBack = (response: Response) =>787  cookiesOf(response)788    .filter(({ attributes }) => !attributes.includes("max-age=0"))789    .map(({ pair }) => pair)790    .join("; ");791792describe("the handle kept beside the session", () => {793  it.effect(794    "after a sign-in, answers whoami with no call to the platform",795    () =>796      Effect.gen(function* () {797        const { response } = yield* signInAndBack("/auth/signin", "c0de");798        const who = yield* whoami(unreachable, { cookie: sentBack(response) });799800        expect(yield* textOf(who)).toBe('{"handle":"ines-v"}');801        expect(who.headers.getSetCookie()).toStrictEqual([]);802      })803  );804805  it.effect(806    "is a __Host- cookie the page's JavaScript never reads, living as long as the session",807    () =>808      Effect.gen(function* () {809        const { response } = yield* signInAndBack("/auth/signin", "c0de");810        const cookies = cookiesOf(response);811        const session = cookies.find(({ name }) => name === SESSION_COOKIE);812        const handle = cookies.find(({ name }) => name === HANDLE_COOKIE);813814        expect({815          host: HANDLE_COOKIE.startsWith("__Host-"),816          lives: maxAgeOf(handle?.attributes ?? []),817          lockedDown: lockedDown(handle?.attributes),818          token: handle?.value.includes("tok-from-platform"),819        }).toStrictEqual({820          host: true,821          lives: maxAgeOf(session?.attributes ?? []),822          lockedDown: true,823          token: false,824        });825      })826  );827828  it.effect(829    "is not kept when the platform names no one at sign-in, and the session still starts",830    () =>831      Effect.gen(function* () {832        const { response } = yield* signInAndBack(833          "/auth/signin",834          "c0de",835          () => Response.json(TOKEN_ANSWER),836          () => new Response("down", { status: 503 })837        );838839        expect(840          cookiesOf(response)841            .map(({ name }) => name)842            .filter((name) => name !== "__Host-sign-in")843        ).toStrictEqual([SESSION_COOKIE]);844      })845  );846847  it.effect("is not believed for another session: the platform is asked", () =>848    Effect.gen(function* () {849      const { response } = yield* signInAndBack("/auth/signin", "c0de");850851      const handle = cookiesOf(response).find(852        ({ name }) => name === HANDLE_COOKIE853      );854855      const platform = recorder(statusReply(STATUS_OF_INES));856857      const who = yield* whoami(envWith(platform.fetch), {858        cookie: `${SESSION_COOKIE}=another-token; ${handle?.pair ?? ""}`,859      });860861      expect(yield* textOf(who)).toBe('{"handle":"ines-v"}');862      expect(863        (yield* platform.seen).map(({ authorization }) => authorization)864      ).toStrictEqual(["Bearer another-token"]);865    })866  );867868  it.effect("is expired, unread, once no session is left", () =>869    Effect.gen(function* () {870      const { response } = yield* signInAndBack("/auth/signin", "c0de");871872      const handle = cookiesOf(response).find(873        ({ name }) => name === HANDLE_COOKIE874      );875876      const who = yield* whoami(unreachable, { cookie: handle?.pair ?? "" });877878      expect(yield* textOf(who)).toBe("{}");879      expect(expiriesOf(who)).toStrictEqual([[HANDLE_COOKIE, true]]);880    })881  );882});883884const decodeDocument = Schema.decodeUnknownEffect(885  Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown))886);887888describe("the web's OAuth client", () => {889  it.effect(890    "is a public Client ID Metadata Document at its own URL, redirecting only to the callback",891    () =>892      Effect.gen(function* () {893        const response = clientMetadataHandler({894          request: get("/auth/client"),895        });896897        const document = yield* decodeDocument(yield* textOf(response));898899        expect(response.headers.get("content-type")).toContain(900          "application/json"901        );902        expect(document).toStrictEqual(903          expect.objectContaining({904            client_id: `${WEB_URL}/auth/client`,905            grant_types: ["authorization_code"],906            redirect_uris: [`${WEB_URL}/auth/callback`],907            response_types: ["code"],908            token_endpoint_auth_method: "none",909          })910        );911        expect(document).toHaveProperty("client_name", expect.any(String));912        expect(document).not.toHaveProperty("client_secret");913      })914  );915});916917describe("the dev sign-in", () => {918  it("sets the session to the dev backend's token for a handle", () => {919    const response = devSignIn({920      request: get("/auth/dev?handle=ines-v&return=/inbox"),921    });922923    const [session] = cookiesOf(response);924925    expect([response.status, response.headers.get("location")]).toStrictEqual([926      302,927      "/inbox",928    ]);929    expect(lockedDown(session?.attributes)).toBeTruthy();930    expect(931      credentialFrom(get("/rpc", { cookie: session?.pair ?? "" }))932    ).toStrictEqual(Option.some("dev-ines-v"));933  });934935  it("refuses a handle that is not one, and sets nothing", () => {936    const response = devSignIn({937      request: get("/auth/dev?handle=not%20a%20handle"),938    });939940    expect(response.status).toBe(400);941    expect(response.headers.getSetCookie()).toStrictEqual([]);942  });943});944945describe("the header's session slot", () => {946  const ines = Schema.decodeSync(Handle)("ines-v");947948  it("names the person signed in, with a way to sign out", () => {949    const markup = renderToStaticMarkup(950      createElement(SessionView, { handle: Option.some(ines), here: "/inbox" })951    );952953    expect(markup).toContain(">ines-v<");954    expect(markup).toContain('href="/people/ines-v"');955    expect(markup).toMatch(956      /<form[^>]*action="\/auth\/signout"[^>]*method="post"/u957    );958    expect(markup).not.toContain("/auth/signin");959  });960961  it("offers sign-in, coming back to the page it was on", () => {962    const markup = renderToStaticMarkup(963      createElement(SessionView, { handle: Option.none(), here: "/inbox" })964    );965966    expect(markup).toContain('href="/auth/signin?return=%2Finbox"');967    expect(markup).toContain(">Sign in<");968    expect(markup).not.toContain("/auth/signout");969  });970971  it("comes back to the page without its #fragment, which the server never sees, so the link it renders matches in the browser", () => {972    const location = {973      hash: "L3",974      href: "/oscabriel/datekit/blob/main/src/add.ts?plain=1#L3",975      pathname: "/oscabriel/datekit/blob/main/src/add.ts",976      searchStr: "?plain=1",977    };978979    expect(hereOf(location)).toBe(980      "/oscabriel/datekit/blob/main/src/add.ts?plain=1"981    );982  });983});