Skip to content
Myr

Merge build/513-web-sign-in

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by oscabriel · committed by oscabriel · parents f55adf5, 29fe82b · Browse files · 13 files+1615 added−19 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

13 files+1615 added−19 removed

  • tests:+832 added−4 removed
  • other:+783 added−15 removed

13 files+1615 added−19 removed

modified:apps/web/src/features/auth/session-slot.tsx+74 added-11 removed
added:apps/web/src/features/auth/who.ts+27 added
added:apps/web/src/routes/auth/-dev.ts+36 added
added:apps/web/src/routes/auth/$.ts+40 added
added:apps/web/src/routes/auth/callback.ts+14 added
added:apps/web/src/routes/auth/client.ts+13 added
added:apps/web/src/routes/auth/signin.ts+14 added
added:apps/web/src/routes/auth/signout.ts+14 added
added:apps/web/src/routes/auth/whoami.ts+15 added
1import { createFileRoute } from "@tanstack/react-router";2import { env } from "cloudflare:workers";34import { serverClient } from "../../server/client.ts";5import { whoamiHandler } from "../../server/session.ts";67// Who is signed in, as the platform's `status` names the session's caller,8// asked in process through `#backend` (issue 513).9export const Route = createFileRoute("/auth/whoami")({10 server: {11 handlers: {12 GET: whoamiHandler((request) => serverClient(env, request)),13 },14 },15});
modified:apps/web/src/server/backend.ts+64 added-4 removed
3 unmodified lines
4 *5 * It travels at the platform's own URL (`PUBLIC_PLATFORM_URL`), never the6 * web's: the platform names a project's and a claim's git remote from the7 * origin of the request it is handed (W3 312 #2), and a remote on the web's8 * host would lead nowhere. Method, headers and body are kept, and nothing is9 * added: the browser's session becomes a bearer token here in issue 513,10 * never before.8 * host would lead nowhere. Method and body are kept; the browser's session9 * cookie becomes the HTTP `Authorization` header, the only credential the10 * platform reads (W3 305 #2), and the browser's own cookies and any11 * `authorization` it set never leave the web (`session.ts`, issue 513).12 *13 * A session the platform no longer knows (it answers 401 to a credential14 * it cannot verify, and only then) is not a refusal of the call: the call is15 * asked again with no credential, so a public read still answers and a16 * signed-in one says `Unauthenticated`, and the answer expires the cookie.17 */18import { Effect, Option } from "effect";1920import type { Backend } from "./rpc.ts";21import {22 clearedCookie,23 credentialFrom,24 settingCookies,25 withCredential,26} from "./session.ts";2728/** `request` as the platform's own: the same path and query on its origin. */29const onPlatform = (request: Request, platformUrl: string) => {30 const { pathname, search } = new URL(request.url);3132 return new Request(new URL(`${pathname}${search}`, platformUrl), request);33};3435/** `response` as it came, also expiring the session cookie. */36const expiringSession = (response: Response) =>37 new Response(response.body, {38 headers: settingCookies(response.headers, [clearedCookie()]),39 status: response.status,40 statusText: response.statusText,41 });4243const send = (env: Env, request: Request) =>44 Effect.promise(() => env.PLATFORM.fetch(request));4546/** The request's body read whole, so the call can be asked twice; none for a GET or HEAD. */47const bodyOf = (request: Request) =>48 request.method === "GET" || request.method === "HEAD"49 ? Effect.succeed(null)50 : Effect.promise(() => request.arrayBuffer());5152export const backend: Backend = (request, env) =>22 env.PLATFORM.fetch(onPlatform(request, env.PUBLIC_PLATFORM_URL));53 Effect.runPromise(54 Effect.gen(function* () {55 const platform = onPlatform(request, env.PUBLIC_PLATFORM_URL);56 const credential = credentialFrom(request);5758 if (Option.isNone(credential)) {59 return yield* send(env, withCredential(platform, credential));60 }6162 const body = yield* bodyOf(platform);6364 const asked = (token: Option.Option<string>) =>65 withCredential(66 body === null67 ? platform68 : new Request(platform, { body, method: platform.method }),69 token70 );7172 const answer = yield* send(env, asked(credential));7374 if (answer.status !== 401) {75 return answer;76 }7778 yield* Effect.promise(() => answer.body?.cancel() ?? Promise.resolve());7980 return expiringSession(yield* send(env, asked(Option.none())));81 })82 );
added:apps/web/src/server/session.ts+472 added
1/**2 * A decider's session on the web (issue 513). The platform is the OAuth3 * authorization server (W3 316); the web is one of its public clients, and4 * signs a person in with PKCE: `/auth/signin` sends the browser to the5 * platform's `/authorize`, `/auth/callback` trades the code at the6 * platform's `/token` over `PLATFORM`, and the access token goes into one7 * HttpOnly cookie on the web's origin. The page's JavaScript never sees it,8 * no URL, log line or response body carries it, and the web holds no9 * secret: PKCE needs none, and the web's client is a Client ID Metadata10 * Document the web serves itself (`/auth/client`).11 *12 * Every forward to the platform (`backend.ts`) turns that cookie into the13 * HTTP `Authorization` header, the only credential the platform reads (W314 * 305 #2), and drops the browser's own cookies and any `authorization` it15 * set: the browser never chooses the credential.16 */17import { Brand } from "@repo/brand";18import { Client } from "@repo/protocol/contracts";19import type { Handle } from "@repo/protocol/ids";20import { Data, Effect, Option, Redacted, Schema } from "effect";21import type { Layer } from "effect";2223/**24 * The session cookie: the platform's access token. `__Host-` keeps it to25 * this exact origin over HTTPS, so no sibling host under the same site26 * (another Worker on the account's `workers.dev` subdomain) can set or27 * shadow it.28 */29export const SESSION_COOKIE = "__Host-session";3031/** The cookie a sign-in in progress waits in: its state, PKCE verifier and way back. */32const SIGN_IN_COOKIE = "__Host-sign-in";3334/** How long a sign-in in progress waits for its callback: ten minutes. */35const SIGN_IN_SECONDS = 600;3637/**38 * How much sooner than its token the session cookie expires, so a cookie39 * never carries a token the platform has just let go.40 */41const SESSION_MARGIN_SECONDS = 60;4243/** The web's own sign-in paths that this module names in what it answers. */44const AUTH_PATHS = {45 callback: "/auth/callback",46 client: "/auth/client",47 signIn: "/auth/signin",48} as const;4950/** What a route's server handler is handed, of what it uses. */51export interface Handled {52 readonly request: Request;53}5455// --- The cookie -------------------------------------------------------------5657/**58 * A platform token as the session cookie carries it: no space, quote,59 * comma, semicolon or backslash. The callback keeps only such a token and60 * `credentialFrom` reads back only such a token, so a cookie is never set61 * that no later request could be signed in with.62 */63const Token = Schema.NonEmptyString.check(Schema.isPattern(/^[^\s",;\\]+$/u));6465const isToken = Schema.is(Token);6667/** A cookie value as it was set, if it decodes. */68const decodedValue = Option.liftThrowable(decodeURIComponent);6970/** The value of the cookie `name` the request carries, if it carries one. */71const cookieValue = (request: Request, name: string) =>72 Option.fromNullishOr(request.headers.get("cookie")).pipe(73 Option.flatMap((header) =>74 Option.fromUndefinedOr(75 header76 .split(";")77 .map((part) => part.trim())78 .find((part) => part.startsWith(`${name}=`))79 )80 ),81 Option.map((pair) => pair.slice(name.length + 1)),82 Option.flatMap(decodedValue)83 );8485/** The session cookie's value: the platform token this browser signed in with. */86export const credentialFrom = (request: Request): Option.Option<string> =>87 cookieValue(request, SESSION_COOKIE).pipe(Option.filter(isToken));8889/**90 * `request` as the platform should see it: without the browser's cookies91 * and without any `authorization` the browser set, and with `Authorization:92 * Bearer <token>` when there is a session.93 */94export const withCredential = (95 request: Request,96 token: Option.Option<string>97): Request => {98 const headers = new Headers(request.headers);99100 headers.delete("authorization");101 headers.delete("cookie");102103 if (Option.isSome(token)) {104 headers.set("authorization", `Bearer ${token.value}`);105 }106107 return new Request(request, { headers });108};109110/** A cookie only this origin's HTTP requests carry, never the page's JavaScript. */111const lockedCookie = (name: string, value: string, maxAgeSeconds: number) =>112 `${name}=${encodeURIComponent(value)}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=${Math.max(0, Math.floor(maxAgeSeconds))}`;113114/** The `Set-Cookie` value that holds `token` for `maxAgeSeconds`. */115export const sessionCookie = (token: string, maxAgeSeconds: number) =>116 lockedCookie(SESSION_COOKIE, token, maxAgeSeconds);117118/** The `Set-Cookie` value that ends the session now. */119export const clearedCookie = () => lockedCookie(SESSION_COOKIE, "", 0);120121const clearedSignIn = () => lockedCookie(SIGN_IN_COOKIE, "", 0);122123/** `headers`, also setting each of `cookies` (each its own `Set-Cookie` line). */124export const settingCookies = (125 headers: HeadersInit,126 cookies: readonly string[]127) => {128 const all = new Headers(headers);129130 for (const cookie of cookies) {131 all.append("set-cookie", cookie);132 }133134 return all;135};136137// --- PKCE -------------------------------------------------------------------138139const encodeBase64Url = Schema.encodeEffect(Schema.Uint8ArrayFromBase64Url);140141/** `size` bytes from WebCrypto's `getRandomValues`, in base64url. */142const randomText = (size: number) =>143 Effect.sync(() => crypto.getRandomValues(new Uint8Array(size))).pipe(144 Effect.flatMap(encodeBase64Url),145 Effect.orDie146 );147148/** The S256 code challenge for `verifier`: `BASE64URL(SHA256(verifier))`. */149export const challengeOf = (verifier: string) =>150 Effect.promise(() =>151 crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))152 ).pipe(153 Effect.flatMap((digest) => encodeBase64Url(new Uint8Array(digest))),154 Effect.orDie155 );156157/** A fresh PKCE verifier and its challenge, and a fresh state, each 32 random bytes. */158export const pkce = Effect.gen(function* () {159 const verifier = yield* randomText(32);160161 return {162 challenge: yield* challengeOf(verifier),163 state: yield* randomText(32),164 verifier,165 };166});167168// --- Where the browser goes -------------------------------------------------169170/** The web's OAuth client id at `origin`: the URL of its metadata document. */171const clientIdOf = (origin: string) => `${origin}${AUTH_PATHS.client}`;172173/** Where the platform sends the browser back to, at `origin`. */174const redirectUriOf = (origin: string) => `${origin}${AUTH_PATHS.callback}`;175176/**177 * Where to go after signing in or out: `wanted` when it is a path on this178 * web (resolved against its origin, so `//host`, `/\host` and a full URL179 * elsewhere all fall back) and not a sign-in path itself; the front page180 * otherwise.181 */182export const returnPath = (origin: string, wanted: string | null) =>183 Option.fromNullishOr(wanted).pipe(184 Option.filter((path) => path.startsWith("/")),185 Option.flatMap((path) => Option.fromNullishOr(URL.parse(path, origin))),186 Option.filter((url) => url.origin === origin),187 Option.map(({ hash, pathname, search }) => `${pathname}${search}${hash}`),188 Option.filter((path) => !path.startsWith("/auth/")),189 Option.getOrElse(() => "/")190 );191192/** A 302 to `location` that sets `cookies` and is never cached. */193export const redirect = (location: string, cookies: readonly string[]) =>194 new Response(null, {195 headers: settingCookies(196 {197 "cache-control": "no-store",198 location,199 "referrer-policy": "no-referrer",200 },201 cookies202 ),203 status: 302,204 });205206/** A short page that says why signing in stopped, and how to start again. */207const stoppedPage = (208 status: number,209 reason: string,210 cookies: readonly string[]211) => {212 const headers = settingCookies(213 {214 "cache-control": "no-store",215 "content-type": "text/html; charset=utf-8",216 },217 cookies218 );219220 return new Response(221 `<!doctype html><meta charset="utf-8"><title>Sign-in stopped · ${Brand.name}</title><p>${reason}</p><p><a href="${AUTH_PATHS.signIn}">Sign in again</a> or go to <a href="/">the front page</a>.</p>`,222 { headers, status }223 );224};225226// --- Sign-in ----------------------------------------------------------------227228/** A sign-in in progress, as its cookie holds it. */229const PendingSignIn = Schema.Struct({230 return: Schema.String,231 state: Schema.String,232 verifier: Schema.String,233});234235const PendingCookie = Schema.StringFromBase64Url.pipe(236 Schema.decodeTo(Schema.fromJsonString(PendingSignIn))237);238239const encodePending = Schema.encodeEffect(PendingCookie);240241const decodePending = Schema.decodeOption(PendingCookie);242243/**244 * `GET /auth/signin[?return=<path>]`: to the platform's `/authorize` with a245 * fresh PKCE challenge and state; the verifier, the state and the way back246 * wait in a short-lived HttpOnly cookie for the callback.247 */248export const signInHandler =249 (env: Env) =>250 ({ request }: Handled): Promise<Response> =>251 Effect.runPromise(252 Effect.gen(function* () {253 const here = new URL(request.url);254 const { challenge, state, verifier } = yield* pkce;255256 const pending = yield* encodePending({257 return: returnPath(here.origin, here.searchParams.get("return")),258 state,259 verifier,260 }).pipe(Effect.orDie);261262 const authorize = new URL("/authorize", env.PUBLIC_PLATFORM_URL);263264 authorize.search = new URLSearchParams({265 client_id: clientIdOf(here.origin),266 code_challenge: challenge,267 code_challenge_method: "S256",268 redirect_uri: redirectUriOf(here.origin),269 response_type: "code",270 state,271 }).toString();272273 return redirect(authorize.href, [274 lockedCookie(SIGN_IN_COOKIE, pending, SIGN_IN_SECONDS),275 ]);276 })277 );278279// --- The callback -----------------------------------------------------------280281/** Signing in stopped before a session: a 400 the person reads, or a 502 when the platform could not be asked. */282class SignInStopped extends Data.TaggedError("SignInStopped")<{283 readonly reason: string;284 readonly status: 400 | 502;285}> {}286287const startAgain = new SignInStopped({288 reason:289 "This sign-in was not started in this browser, or it took longer than ten minutes.",290 status: 400,291});292293const refused = new SignInStopped({294 reason: "The platform did not complete this sign-in.",295 status: 400,296});297298const unreachablePlatform = new SignInStopped({299 reason: "The platform could not be reached to complete this sign-in.",300 status: 502,301});302303/** What the platform's `/token` answers a good code with, of what the web keeps. */304const TokenAnswer = Schema.Struct({305 access_token: Schema.RedactedFromValue(Token),306 expires_in: Schema.Int.check(Schema.isGreaterThan(0)),307 token_type: Schema.String,308});309310const decodeTokenAnswer = Schema.decodeEffect(311 Schema.fromJsonString(TokenAnswer)312);313314/** Trades `code` for an access token at the platform's `/token`, over `PLATFORM`. */315const exchange = (316 env: Env,317 input: {318 readonly code: string;319 readonly origin: string;320 readonly verifier: string;321 }322) =>323 Effect.gen(function* () {324 const response = yield* Effect.tryPromise({325 catch: () => unreachablePlatform,326 try: () =>327 env.PLATFORM.fetch(328 new Request(new URL("/token", env.PUBLIC_PLATFORM_URL), {329 body: new URLSearchParams({330 client_id: clientIdOf(input.origin),331 code: input.code,332 code_verifier: input.verifier,333 grant_type: "authorization_code",334 redirect_uri: redirectUriOf(input.origin),335 }),336 headers: {337 accept: "application/json",338 "content-type": "application/x-www-form-urlencoded",339 },340 method: "POST",341 })342 ),343 });344345 if (!response.ok) {346 return yield* refused;347 }348349 const body = yield* Effect.tryPromise({350 catch: () => refused,351 try: () => response.text(),352 });353354 const answer = yield* decodeTokenAnswer(body).pipe(355 Effect.mapError(() => refused)356 );357358 if (answer.token_type.toLowerCase() !== "bearer") {359 return yield* refused;360 }361362 return answer;363 });364365/**366 * `GET /auth/callback?code=…&state=…`: the state must be the one this367 * browser's sign-in cookie holds; then the code and its verifier go to the368 * platform's `/token`, and the token comes back only as the session cookie,369 * set to expire before the token does, on a 302 to the way back.370 */371export const callbackHandler =372 (env: Env) =>373 ({ request }: Handled): Promise<Response> =>374 Effect.runPromise(375 Effect.gen(function* () {376 const here = new URL(request.url);377378 const pending = yield* Effect.fromOption(379 Option.flatMap(cookieValue(request, SIGN_IN_COOKIE), decodePending)380 ).pipe(Effect.mapError(() => startAgain));381382 if (here.searchParams.get("state") !== pending.state) {383 return yield* startAgain;384 }385386 const code = here.searchParams.get("code") ?? "";387388 if (code === "") {389 return yield* refused;390 }391392 const answer = yield* exchange(env, {393 code,394 origin: here.origin,395 verifier: pending.verifier,396 });397398 return redirect(returnPath(here.origin, pending.return), [399 sessionCookie(400 Redacted.value(answer.access_token),401 answer.expires_in - SESSION_MARGIN_SECONDS402 ),403 clearedSignIn(),404 ]);405 }).pipe(406 Effect.catchTag("SignInStopped", ({ reason, status }) =>407 Effect.succeed(stoppedPage(status, reason, [clearedSignIn()]))408 )409 )410 );411412// --- Sign-out, who, and the client -------------------------------------------413414/** `POST` (or a plain link's `GET`) `/auth/signout`: the session cookie ends, and the browser goes home. */415export const signOutHandler = (_handled: Handled): Response =>416 redirect("/", [clearedCookie()]);417418/** `/auth/whoami`'s answer: the handle signed in, or nothing (`features/auth/who.ts` reads it). */419const whoAnswer = (420 who: { readonly handle?: Handle },421 cookies: readonly string[] = []422) =>423 Response.json(who, {424 headers: settingCookies({ "cache-control": "no-store" }, cookies),425 });426427/**428 * `GET /auth/whoami`: `{ handle }` as the platform's `status` names the429 * session's caller, or `{}`. With no session the platform is not asked. A430 * session the platform no longer knows answers `Unauthenticated` (the431 * backend asks again with no credential), so its cookie is expired here.432 */433export const whoamiHandler =434 (clientFor: (request: Request) => Layer.Layer<Client>) =>435 ({ request }: Handled): Promise<Response> =>436 Effect.runPromise(437 Option.match(credentialFrom(request), {438 onNone: () => Effect.succeed(whoAnswer({})),439 onSome: () =>440 Effect.service(Client).pipe(441 Effect.flatMap((client) => client.status({})),442 Effect.map(({ handle }) => whoAnswer({ handle })),443 Effect.catchTag("Unauthenticated", () =>444 Effect.succeed(whoAnswer({}, [clearedCookie()]))445 ),446 Effect.orElseSucceed(() => whoAnswer({})),447 Effect.provide(clientFor(request))448 ),449 })450 );451452/**453 * The web's OAuth client at `origin`, as a Client ID Metadata Document: a454 * public client (PKCE, no secret) whose id is this document's URL and whose455 * one redirect is the web's callback. The platform reads it when the456 * browser arrives at `/authorize`, so nothing is registered there.457 */458export const webClientMetadata = (origin: string) => ({459 client_id: clientIdOf(origin),460 client_name: `${Brand.name} web`,461 client_uri: origin,462 grant_types: ["authorization_code"],463 redirect_uris: [redirectUriOf(origin)],464 response_types: ["code"],465 token_endpoint_auth_method: "none",466});467468/** `GET /auth/client`: the web's Client ID Metadata Document. */469export const clientMetadataHandler = ({ request }: Handled): Response =>470 Response.json(webClientMetadata(new URL(request.url).origin), {471 headers: { "cache-control": "public, max-age=300" },472 });
modified:apps/web/test/rpc-route.test.ts+5 added-4 removed
1 unmodified line
2 * The web's `/rpc`: the route hands each request to a backend with the3 * Worker's env, and the production backend forwards it to the platform over4 * `PLATFORM`, at the platform's own URL (so the remotes the platform names,5 * read from the request's origin, are its own; W3 312 #2), keeping method,6 * headers and body and adding no credential. A server route's own calls go7 * through the same backend, in process.6 * headers and body, but never the browser's cookies (the session cookie7 * becomes a bearer there: `session.test.ts`, issue 513). A server route's8 * own calls go through the same backend, in process.9 */10import { describe, expect, it } from "@effect/vitest";11import { Client } from "@repo/protocol/contracts";12import { ProjectName } from "@repo/protocol/ids";
90 unmodified lines
103});104105describe("the production backend", () => {106 it.effect(106 "forwards to PLATFORM at the platform's URL, keeping method, headers and body",107 "forwards to PLATFORM at the platform's URL, keeping method, headers and body, but not the browser's cookies",108 () =>109 Effect.gen(function* () {110 const platform = recorder(() => new Response("from the platform"));111
8 unmodified lines
120 {121 authorization: null,122 body: LIST_ASKS,123 contentType: "application/json",123 cookie: "theme=dark",124 cookie: null,125 method: "POST",126 url: `${PLATFORM_URL}/rpc`,127 },128 ]);
91 unmodified lines
added:apps/web/test/session.test.ts+827 added
1/**2 * A decider's session on the web (issue 513). The platform's access token3 * lives only in an HttpOnly cookie on the web's origin: sign-in sends the4 * browser to the platform's `/authorize` with PKCE, the callback trades the5 * code at the platform's `/token` over `PLATFORM` and sets the cookie, and6 * every forward to the platform turns that cookie into an HTTP7 * `Authorization` header (W3 305 #2) and drops the cookie itself. The8 * browser never chooses the credential, and never sees the token.9 */10import { describe, expect, it } from "@effect/vitest";11import { Handle } from "@repo/protocol/ids";12import { untouchable } from "@repo/testkit/untouchable";13import { Effect, Option, Schema } from "effect";14import { createElement } from "react";15import { renderToStaticMarkup } from "react-dom/server";1617import { SessionView } from "../src/features/auth/session-slot.tsx";18import { devSignIn } from "../src/routes/auth/-dev.ts";19import { backend } from "../src/server/backend.ts";20import { serverClientOver } from "../src/server/client.ts";21import {22 callbackHandler,23 challengeOf,24 clearedCookie,25 clientMetadataHandler,26 credentialFrom,27 pkce,28 SESSION_COOKIE,29 sessionCookie,30 signInHandler,31 signOutHandler,32 whoamiHandler,33 withCredential,34} from "../src/server/session.ts";3536const PLATFORM_URL = "https://platform-test.example.workers.dev";3738const WEB_URL = "https://web-test.example.workers.dev";3940const LIST_ASKS =41 '[{"_tag":"Request","id":"0","tag":"listAsks","payload":{"project":"datekit"},"headers":[]}]';4243/** What the platform's `/token` answers a good code with (1.2.1's shape). */44const TOKEN_ANSWER = {45 access_token: "alice:grant1:tok-from-platform",46 expires_in: 3600,47 refresh_token: "alice:grant1:refresh-secret",48 scope: "",49 token_type: "bearer",50};5152/** What a backend or a binding was handed, read whole. */53const seenOf = (request: Request) =>54 Effect.map(55 Effect.promise(() => request.text()),56 (body) => ({57 authorization: request.headers.get("authorization"),58 body,59 cookie: request.headers.get("cookie"),60 method: request.method,61 url: request.url,62 })63 );6465/** A fetch-shaped stub that keeps each request it is handed and answers `answer`. */66const recorder = (answer: (request: Request) => Response) => {67 const handed: Request[] = [];6869 const fetch = (request: Request) => {70 handed.push(request);7172 return Promise.resolve(answer(request));73 };7475 return { fetch, seen: Effect.suspend(() => Effect.forEach(handed, seenOf)) };76};7778/** A web Worker env whose PLATFORM binding answers `fetch` and nothing else. */79const envWith = (fetch: (request: Request) => Promise<Response>): Env => ({80 PLATFORM: untouchable<Fetcher>("PLATFORM", {81 fetch: (input, init) => fetch(new Request(input, init)),82 }),83 PUBLIC_PLATFORM_URL: PLATFORM_URL,84});8586/** An env whose PLATFORM throws when touched: the handler must not reach the platform. */87const unreachable: Env = {88 PLATFORM: untouchable<Fetcher>("PLATFORM"),89 PUBLIC_PLATFORM_URL: PLATFORM_URL,90};9192const listAsksPost = (headers: Readonly<Record<string, string>> = {}) =>93 new Request(`${WEB_URL}/rpc`, {94 body: LIST_ASKS,95 headers: { "content-type": "application/json", ...headers },96 method: "POST",97 });9899const get = (path: string, headers: Readonly<Record<string, string>> = {}) =>100 new Request(`${WEB_URL}${path}`, { headers });101102/** A response's `Set-Cookie` lines, each split into its name, value and attributes. */103const cookiesOf = (response: Response) =>104 response.headers.getSetCookie().map((line) => {105 const [pair = "", ...attributes] = line106 .split(";")107 .map((part) => part.trim());108109 const at = pair.indexOf("=");110111 return {112 attributes: attributes.map((attribute) => attribute.toLowerCase()),113 name: pair.slice(0, at),114 pair,115 value: pair.slice(at + 1),116 };117 });118119/** Each cookie a response sets, by name, with whether it expires now. */120const expiriesOf = (response: Response) =>121 cookiesOf(response).map(({ attributes, name }) => [122 name,123 attributes.includes("max-age=0"),124 ]);125126/** The `Max-Age` of a cookie, in seconds. */127const maxAgeOf = (attributes: readonly string[]) =>128 Number(129 attributes.find((attribute) => attribute.startsWith("max-age="))?.slice(8)130 );131132/** The attributes a session or state cookie must carry, lowercased. */133const LOCKED_DOWN = ["httponly", "secure", "samesite=lax", "path=/"] as const;134135/** Whether a cookie carries every attribute in `LOCKED_DOWN`. */136const lockedDown = (attributes: readonly string[] = []) =>137 LOCKED_DOWN.every((attribute) => attributes.includes(attribute));138139const textOf = (response: Response) => Effect.promise(() => response.text());140141/** Named query parameters of `url`. */142const paramsOf = (url: URL, names: readonly string[]) =>143 Object.fromEntries(names.map((name) => [name, url.searchParams.get(name)]));144145/**146 * A stream that reads a whole RPC call and writes the platform's reply to147 * it: `exit` for the call's request id, echoed as the call wrote it (a148 * number or a string).149 */150const replyingWith = (exit: string) => {151 const parts: string[] = [];152153 return new TransformStream<string, string>({154 flush: (controller) => {155 const id =156 /"id":(?<id>"[^"]*"|\d+)/u.exec(parts.join(""))?.groups?.id ?? "null";157158 controller.enqueue(`[{"_tag":"Exit","requestId":${id},"exit":${exit}}]`);159 },160 transform: (chunk) => {161 parts.push(chunk);162 },163 });164};165166/** The platform's `/rpc` answer to a `status` call: `exit`. */167const statusReply = (exit: string) => (request: Request) =>168 new Response(169 (request.clone().body ?? new Blob().stream())170 .pipeThrough(new TextDecoderStream())171 .pipeThrough(replyingWith(exit))172 .pipeThrough(new TextEncoderStream()),173 { headers: { "content-type": "application/json" } }174 );175176const STATUS_OF_INES =177 '{"_tag":"Success","value":{"answers":[],"claims":[],"handle":"ines-v"}}';178179const UNAUTHENTICATED =180 '{"_tag":"Failure","cause":[{"_tag":"Fail","error":{"_tag":"Unauthenticated"}}]}';181182describe("the session cookie", () => {183 it("is read from the cookie header, among the others", () => {184 expect(185 [186 `theme=dark; ${SESSION_COOKIE}=tok123; other=1`,187 "theme=dark",188 `${SESSION_COOKIE}=`,189 `${SESSION_COOKIE}=two%20words`,190 ].map((cookie) => credentialFrom(get("/rpc", { cookie })))191 ).toStrictEqual([192 Option.some("tok123"),193 Option.none(),194 Option.none(),195 Option.none(),196 ]);197 expect(credentialFrom(get("/rpc"))).toStrictEqual(Option.none());198 });199200 it("reads back the token a session cookie was set with", () => {201 const token = "alice:grant1:tok/with+odd=chars";202 const [pair = ""] = sessionCookie(token, 60).split(";");203204 expect(credentialFrom(get("/rpc", { cookie: pair }))).toStrictEqual(205 Option.some(token)206 );207 });208209 it("is HttpOnly, Secure, SameSite=Lax, on every path, for as long as it is given", () => {210 const [cookie] = cookiesOf(211 new Response(null, { headers: { "set-cookie": sessionCookie("t", 90) } })212 );213214 expect(cookie?.name).toBe(SESSION_COOKIE);215 expect(cookie?.attributes).toStrictEqual(216 expect.arrayContaining([...LOCKED_DOWN, "max-age=90"])217 );218 });219220 it("is cleared by a cookie of the same name that expires now", () => {221 const [cookie] = cookiesOf(222 new Response(null, { headers: { "set-cookie": clearedCookie() } })223 );224225 expect(cookie?.name).toBe(SESSION_COOKIE);226 expect(cookie?.value).toBe("");227 expect(cookie?.attributes).toStrictEqual(228 expect.arrayContaining([...LOCKED_DOWN, "max-age=0"])229 );230 });231232 it("becomes the only credential a forwarded request carries", () => {233 const forwarded = withCredential(234 get("/rpc", {235 authorization: "Bearer chosen-by-the-browser",236 cookie: `${SESSION_COOKIE}=tok123`,237 }),238 Option.some("tok123")239 );240241 const anonymous = withCredential(242 get("/rpc", { authorization: "Bearer chosen-by-the-browser" }),243 Option.none()244 );245246 expect(forwarded.headers.get("authorization")).toBe("Bearer tok123");247 expect(forwarded.headers.get("cookie")).toBeNull();248 expect(anonymous.headers.get("authorization")).toBeNull();249 });250});251252describe("PKCE", () => {253 it.effect("challenges with S256 (RFC 7636 appendix B)", () =>254 Effect.gen(function* () {255 expect(256 yield* challengeOf("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk")257 ).toBe("E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM");258 })259 );260261 it.effect("draws a fresh verifier and state each time, from WebCrypto", () =>262 Effect.gen(function* () {263 const first = yield* pkce;264 const second = yield* pkce;265266 expect(first.verifier).toMatch(/^[\w-]{43,128}$/u);267 expect(first.state).toMatch(/^[\w-]{22,}$/u);268 expect(first.challenge).toBe(yield* challengeOf(first.verifier));269 expect([second.verifier, second.state]).not.toStrictEqual([270 first.verifier,271 first.state,272 ]);273 })274 );275});276277describe("the production backend", () => {278 it.effect(279 "forwards a /rpc call with the session cookie's token as a bearer, and no cookie",280 () =>281 Effect.gen(function* () {282 const platform = recorder(() => new Response("from the platform"));283284 const response = yield* Effect.promise(() =>285 backend(286 listAsksPost({ cookie: `${SESSION_COOKIE}=tok123; other=1` }),287 envWith(platform.fetch)288 )289 );290291 expect(yield* platform.seen).toStrictEqual([292 {293 authorization: "Bearer tok123",294 body: LIST_ASKS,295 cookie: null,296 method: "POST",297 url: `${PLATFORM_URL}/rpc`,298 },299 ]);300 expect(yield* textOf(response)).toBe("from the platform");301 })302 );303304 it.effect(305 "drops an authorization the browser set, and forwards a call with no cookie with no credential",306 () =>307 Effect.gen(function* () {308 const platform = recorder(() => new Response("public"));309310 yield* Effect.promise(() =>311 backend(312 listAsksPost({ authorization: "Bearer chosen-by-the-browser" }),313 envWith(platform.fetch)314 )315 );316317 expect(yield* platform.seen).toStrictEqual([318 {319 authorization: null,320 body: LIST_ASKS,321 cookie: null,322 method: "POST",323 url: `${PLATFORM_URL}/rpc`,324 },325 ]);326 })327 );328329 it.effect(330 "asks again with no credential when the platform no longer knows the token, and expires the cookie",331 () =>332 Effect.gen(function* () {333 const platform = recorder((request) =>334 request.headers.has("authorization")335 ? new Response(null, {336 headers: { "www-authenticate": 'Bearer error="invalid_token"' },337 status: 401,338 })339 : new Response("as anyone")340 );341342 const response = yield* Effect.promise(() =>343 backend(344 listAsksPost({ cookie: `${SESSION_COOKIE}=stale` }),345 envWith(platform.fetch)346 )347 );348349 const seen = yield* platform.seen;350351 expect(352 seen.map(({ authorization, body }) => [authorization, body])353 ).toStrictEqual([354 ["Bearer stale", LIST_ASKS],355 [null, LIST_ASKS],356 ]);357 expect([response.status, yield* textOf(response)]).toStrictEqual([358 200,359 "as anyone",360 ]);361 expect(expiriesOf(response)).toStrictEqual([[SESSION_COOKIE, true]]);362 })363 );364365 it.effect("carries the session on a GET too, at the platform's URL", () =>366 Effect.gen(function* () {367 const platform = recorder(() => new Response("ok"));368369 yield* Effect.promise(() =>370 backend(371 get("/releases/x?y=1", { cookie: `${SESSION_COOKIE}=tok123` }),372 envWith(platform.fetch)373 )374 );375376 expect(377 (yield* platform.seen).map(({ authorization, method, url }) => [378 method,379 url,380 authorization,381 ])382 ).toStrictEqual([383 ["GET", `${PLATFORM_URL}/releases/x?y=1`, "Bearer tok123"],384 ]);385 })386 );387});388389/** Signs in at the web and returns where the browser went and the state cookie it holds. */390const signIn = (path: string) =>391 Effect.gen(function* () {392 const response = yield* Effect.promise(() =>393 signInHandler(unreachable)({ request: get(path) })394 );395396 const location = new URL(response.headers.get("location") ?? "");397 const [state] = cookiesOf(response);398399 return { location, response, state };400 });401402/** Signs in, then comes back to the callback with `code` and the state sign-in sent, to a platform that answers `/token` with `answer`. */403const signInAndBack = (404 path: string,405 code: string,406 answer: () => Response = () => Response.json(TOKEN_ANSWER)407) =>408 Effect.gen(function* () {409 const { location, state } = yield* signIn(path);410 const platform = recorder(answer);411412 const response = yield* Effect.promise(() =>413 callbackHandler(envWith(platform.fetch))({414 request: get(415 `/auth/callback?code=${code}&state=${location.searchParams.get("state") ?? ""}`,416 { cookie: state?.pair ?? "" }417 ),418 })419 );420421 return { location, response, seen: yield* platform.seen, state };422 });423424/** Where the callback sends the browser after a sign-in asked to come back to `path`. */425const backTo = (path: string) =>426 Effect.map(427 signInAndBack(`/auth/signin?return=${encodeURIComponent(path)}`, "c0de"),428 ({ response }) => response.headers.get("location")429 );430431describe("sign-in", () => {432 it.effect(433 "sends the browser to the platform's /authorize as the web's public client, with S256",434 () =>435 Effect.gen(function* () {436 const { location, response } = yield* signIn(437 "/auth/signin?return=/today"438 );439440 expect(response.status).toBe(302);441 expect(`${location.origin}${location.pathname}`).toBe(442 `${PLATFORM_URL}/authorize`443 );444 expect(445 paramsOf(location, [446 "client_id",447 "code_challenge_method",448 "redirect_uri",449 "response_type",450 ])451 ).toStrictEqual({452 client_id: `${WEB_URL}/auth/client`,453 code_challenge_method: "S256",454 redirect_uri: `${WEB_URL}/auth/callback`,455 response_type: "code",456 });457 expect(location.searchParams.get("code_challenge")).toMatch(458 /^[\w-]{43}$/u459 );460 })461 );462463 it.effect(464 "keeps the state and verifier in a short-lived HttpOnly cookie, never in the URL",465 () =>466 Effect.gen(function* () {467 const { location, state } = yield* signIn("/auth/signin");468469 expect(location.searchParams.get("state")).toMatch(/^[\w-]{22,}$/u);470 expect(state?.name).not.toBe(SESSION_COOKIE);471 expect(lockedDown(state?.attributes)).toBeTruthy();472 expect(maxAgeOf(state?.attributes ?? [])).toBeLessThanOrEqual(600);473 expect(location.searchParams.has("code_verifier")).toBeFalsy();474 })475 );476});477478describe("the callback", () => {479 it.effect(480 "trades the code at the platform's /token over PLATFORM, with the verifier sign-in kept",481 () =>482 Effect.gen(function* () {483 const { location, seen } = yield* signInAndBack(484 "/auth/signin?return=/today",485 "c0de"486 );487488 const [exchange, ...more] = seen;489 const form = new URLSearchParams(exchange?.body);490491 expect(more).toStrictEqual([]);492 expect([493 exchange?.method,494 exchange?.url,495 exchange?.cookie,496 ]).toStrictEqual(["POST", `${PLATFORM_URL}/token`, null]);497 expect(498 Object.fromEntries(499 ["client_id", "code", "grant_type", "redirect_uri"].map((name) => [500 name,501 form.get(name),502 ])503 )504 ).toStrictEqual({505 client_id: `${WEB_URL}/auth/client`,506 code: "c0de",507 grant_type: "authorization_code",508 redirect_uri: `${WEB_URL}/auth/callback`,509 });510 expect(yield* challengeOf(form.get("code_verifier") ?? "")).toBe(511 location.searchParams.get("code_challenge")512 );513 })514 );515516 it.effect(517 "sets the token only as the HttpOnly session cookie, for no longer than the token lives, and goes back",518 () =>519 Effect.gen(function* () {520 const { response, state } = yield* signInAndBack(521 "/auth/signin?return=/today",522 "c0de"523 );524525 const cookies = cookiesOf(response);526 const session = cookies.find(({ name }) => name === SESSION_COOKIE);527 const maxAge = maxAgeOf(session?.attributes ?? []);528529 expect([530 response.status,531 response.headers.get("location"),532 ]).toStrictEqual([302, "/today"]);533 expect(534 credentialFrom(get("/rpc", { cookie: session?.pair ?? "" }))535 ).toStrictEqual(Option.some(TOKEN_ANSWER.access_token));536 expect({537 lockedDown: lockedDown(session?.attributes),538 lives: maxAge > 0 && maxAge <= TOKEN_ANSWER.expires_in,539 }).toStrictEqual({ lives: true, lockedDown: true });540 expect(expiriesOf(response)).toContainEqual([state?.name, true]);541 })542 );543544 it.effect(545 "answers with no token or refresh token in its body or its URL",546 () =>547 Effect.gen(function* () {548 const { response } = yield* signInAndBack("/auth/signin", "c0de");549550 const shown = `${yield* textOf(response)}\n${response.headers.get("location") ?? ""}`;551552 expect(shown).not.toContain("tok-from-platform");553 expect(shown).not.toContain("refresh-secret");554 expect(response.headers.getSetCookie().join("\n")).not.toContain(555 "refresh-secret"556 );557 })558 );559560 it.effect(561 "answers 400 and sets no session when the state is not the one sign-in sent",562 () =>563 Effect.gen(function* () {564 const { state } = yield* signIn("/auth/signin");565566 const response = yield* Effect.promise(() =>567 callbackHandler(unreachable)({568 request: get("/auth/callback?code=c0de&state=forged", {569 cookie: state?.pair ?? "",570 }),571 })572 );573574 expect(response.status).toBe(400);575 expect(576 cookiesOf(response).filter(({ name }) => name === SESSION_COOKIE)577 ).toStrictEqual([]);578 })579 );580581 it.effect("answers 400 when the browser holds no sign-in in progress", () =>582 Effect.gen(function* () {583 const response = yield* Effect.promise(() =>584 callbackHandler(unreachable)({585 request: get("/auth/callback?code=c0de&state=anything"),586 })587 );588589 expect(response.status).toBe(400);590 expect(591 cookiesOf(response).filter(({ name }) => name === SESSION_COOKIE)592 ).toStrictEqual([]);593 })594 );595596 it.effect(597 "answers 400 and sets no session when the platform refuses the code",598 () =>599 Effect.gen(function* () {600 const { response } = yield* signInAndBack("/auth/signin", "used", () =>601 Response.json({ error: "invalid_grant" }, { status: 400 })602 );603604 expect(response.status).toBe(400);605 expect(606 cookiesOf(response).filter(({ name }) => name === SESSION_COOKIE)607 ).toStrictEqual([]);608 })609 );610611 it.effect(612 "answers 400 and sets no session when the token is not one the session cookie can carry back",613 () =>614 Effect.gen(function* () {615 const { response } = yield* signInAndBack("/auth/signin", "c0de", () =>616 Response.json({ ...TOKEN_ANSWER, access_token: "two words" })617 );618619 expect(response.status).toBe(400);620 expect(621 cookiesOf(response).filter(({ name }) => name === SESSION_COOKIE)622 ).toStrictEqual([]);623 })624 );625626 it.effect("goes back only to a path on the web itself", () =>627 Effect.gen(function* () {628 expect(629 yield* Effect.forEach(630 [631 "/datekit/asks/a1?tab=check",632 "https://elsewhere.example/",633 "//elsewhere.example/",634 "/\\elsewhere.example/",635 "/auth/signout",636 ],637 backTo638 )639 ).toStrictEqual(["/datekit/asks/a1?tab=check", "/", "/", "/", "/"]);640 })641 );642});643644describe("sign-out", () => {645 it("goes home and expires the session cookie, by POST or by a plain link", () => {646 const answers = ["POST", "GET"].map((method) => {647 const response = signOutHandler({648 request: new Request(`${WEB_URL}/auth/signout`, {649 headers: { cookie: `${SESSION_COOKIE}=tok123` },650 method,651 }),652 });653654 return [655 response.status,656 response.headers.get("location"),657 expiriesOf(response),658 ];659 });660661 expect(answers).toStrictEqual([662 [302, "/", [[SESSION_COOKIE, true]]],663 [302, "/", [[SESSION_COOKIE, true]]],664 ]);665 });666});667668/** `/auth/whoami` with `headers`, asking the platform through the production backend in process. */669const whoami = (env: Env, headers: Readonly<Record<string, string>> = {}) =>670 Effect.promise(() =>671 whoamiHandler((request) => serverClientOver(backend)(env, request))({672 request: get("/auth/whoami", headers),673 })674 );675676describe("whoami", () => {677 it.effect(678 "answers {} without asking the platform when nobody is signed in",679 () =>680 Effect.gen(function* () {681 const response = yield* whoami(unreachable);682683 expect(response.status).toBe(200);684 expect(yield* textOf(response)).toBe("{}");685 })686 );687688 it.effect(689 "answers the handle the platform's status names for the session",690 () =>691 Effect.gen(function* () {692 const platform = recorder(statusReply(STATUS_OF_INES));693694 const response = yield* whoami(envWith(platform.fetch), {695 cookie: `${SESSION_COOKIE}=tok123`,696 });697698 expect(699 (yield* platform.seen).map(700 ({ authorization, body, cookie, url }) => ({701 authorization,702 cookie,703 path: new URL(url).pathname.replace(/\/$/u, ""),704 status: body.includes('"tag":"status"'),705 })706 )707 ).toStrictEqual([708 {709 authorization: "Bearer tok123",710 cookie: null,711 path: "/rpc",712 status: true,713 },714 ]);715 expect(response.headers.get("cache-control")).toBe("no-store");716 expect(yield* textOf(response)).toBe('{"handle":"ines-v"}');717 })718 );719720 it.effect(721 "answers {} and expires the cookie when the platform no longer knows the session",722 () =>723 Effect.gen(function* () {724 const platform = recorder((request) =>725 request.headers.has("authorization")726 ? new Response(null, { status: 401 })727 : statusReply(UNAUTHENTICATED)(request)728 );729730 const response = yield* whoami(envWith(platform.fetch), {731 cookie: `${SESSION_COOKIE}=stale`,732 });733734 expect(yield* textOf(response)).toBe("{}");735 expect(expiriesOf(response)).toStrictEqual([[SESSION_COOKIE, true]]);736 })737 );738});739740/** A JSON object, read as data. */741const decodeDocument = Schema.decodeUnknownEffect(742 Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown))743);744745describe("the web's OAuth client", () => {746 it.effect(747 "is a public Client ID Metadata Document at its own URL, redirecting only to the callback",748 () =>749 Effect.gen(function* () {750 const response = clientMetadataHandler({751 request: get("/auth/client"),752 });753754 const document = yield* decodeDocument(yield* textOf(response));755756 expect(response.headers.get("content-type")).toContain(757 "application/json"758 );759 expect(document).toStrictEqual(760 expect.objectContaining({761 client_id: `${WEB_URL}/auth/client`,762 grant_types: ["authorization_code"],763 redirect_uris: [`${WEB_URL}/auth/callback`],764 response_types: ["code"],765 token_endpoint_auth_method: "none",766 })767 );768 expect(document).toHaveProperty("client_name", expect.any(String));769 expect(document).not.toHaveProperty("client_secret");770 })771 );772});773774describe("the dev sign-in", () => {775 it("sets the session to the dev backend's token for a handle", () => {776 const response = devSignIn({777 request: get("/auth/dev?handle=ines-v&return=/today"),778 });779780 const [session] = cookiesOf(response);781782 expect([response.status, response.headers.get("location")]).toStrictEqual([783 302,784 "/today",785 ]);786 expect(lockedDown(session?.attributes)).toBeTruthy();787 expect(788 credentialFrom(get("/rpc", { cookie: session?.pair ?? "" }))789 ).toStrictEqual(Option.some("dev-ines-v"));790 });791792 it("refuses a handle that is not one, and sets nothing", () => {793 const response = devSignIn({794 request: get("/auth/dev?handle=not%20a%20handle"),795 });796797 expect(response.status).toBe(400);798 expect(response.headers.getSetCookie()).toStrictEqual([]);799 });800});801802describe("the header's session slot", () => {803 const ines = Schema.decodeSync(Handle)("ines-v");804805 it("names the person signed in, with a way to sign out", () => {806 const markup = renderToStaticMarkup(807 createElement(SessionView, { handle: Option.some(ines), here: "/today" })808 );809810 expect(markup).toContain(">ines-v<");811 expect(markup).toContain('href="/people/ines-v"');812 expect(markup).toMatch(813 /<form[^>]*action="\/auth\/signout"[^>]*method="post"/u814 );815 expect(markup).not.toContain("/auth/signin");816 });817818 it("offers sign-in, coming back to the page it was on", () => {819 const markup = renderToStaticMarkup(820 createElement(SessionView, { handle: Option.none(), here: "/today" })821 );822823 expect(markup).toContain('href="/auth/signin?return=%2Ftoday"');824 expect(markup).toContain(">Sign in<");825 expect(markup).not.toContain("/auth/signout");826 });827});