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
Provenance
- Commit
f736a1e- Tree
00ff958- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
f55adf5- Parent 2
29fe82b
13 files changed+1615 added−19 removed
modified:apps/web/src/features/auth/session-slot.tsx+74 added-11 removed
12342345678967891011121310111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576/** * The header's session slot. A placeholder from issue 511: a link to sign * in. Issue 513 owns this file and replaces it with the signed-in handle and * sign-out, or this link. * The header's session slot (issue 513): who is signed in, with sign-out, * or a link to sign in that comes back to this page. Signing in is only * for deciders (PRODUCT.md), so the slot stays one quiet line: the handle * in ink, the action in the nav's muted text. * * `SessionView` draws it from props; `SessionSlot` (no props: the root * route renders it, issue 511) wires it to `whoAtom` and the location. */export const SessionSlot = () => ( <a className="decoration-rule font-medium underline hover:decoration-current" href="/auth/signin" > Sign in </a>);import { useAtomValue } from "@effect/atom-react";import type { Handle } from "@repo/protocol/ids";import { useLocation } from "@tanstack/react-router";import { Option } from "effect";import { AsyncResult } from "effect/reactivity";
import { HandleLink } from "../shared/handle.tsx";import { whoAtom } from "./who.ts";
/** Sign-in, coming back to `here` afterwards. */const signInHref = (here: string) => `/auth/signin?${new URLSearchParams({ return: here }).toString()}`;
/** The nav's own action style: muted text, ink on hover. */const ACTION = "text-muted-foreground hover:text-foreground cursor-pointer text-sm no-underline transition-colors duration-150";
export const SessionView = ({ handle, here,}: { readonly handle: Option.Option<Handle>; readonly here: string;}) => Option.match(handle, { onNone: () => ( <a className={ACTION} href={signInHref(here)}> Sign in </a> ), onSome: (signedIn) => ( <div className="flex items-center gap-3"> <p className="flex min-w-0 items-baseline gap-1"> <span className="text-muted-foreground sr-only shrink-0 sm:not-sr-only"> Signed in as </span> {/* The header's row never shrinks below its content, so a long handle is capped (a quarter of a phone's width) for `truncate` to take hold and keep "Sign out" on screen; its title is whole. */} <span className="max-w-[25vw] min-w-0 truncate sm:max-w-xs" title={signedIn} > <HandleLink handle={signedIn} /> </span> </p> <span aria-hidden className="bg-rule h-4 w-px" /> <form action="/auth/signout" className="flex" method="post"> <button className={ACTION} type="submit"> Sign out </button> </form> </div> ), });
export const SessionSlot = () => { const here = useLocation({ select: (location) => location.href }); const who = useAtomValue(whoAtom);
return ( <SessionView handle={AsyncResult.isSuccess(who) ? who.value : Option.none()} here={here} /> );};added:apps/web/src/features/auth/who.ts+27 added
123456789101112131415161718192021222324252627/** * Who is signed in, as the browser learns it: the web's own `/auth/whoami` * (a same-origin server route that asks the platform with the session * cookie the page's JavaScript cannot read). It runs in the browser only: * on the server the slot renders as signed out, the page's first paint, and * the browser fills it in. * * Not a contract, so not an atom over `ContractsClient` (`src/surfaces.ts`): * the session is the web's, not the platform's. */import { Handle } from "@repo/protocol/ids";import { Effect, Option, Schema } from "effect";import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http";import { Atom } from "effect/reactivity";
/** `/auth/whoami`'s answer: the handle signed in, or nothing. */const Who = Schema.Struct({ handle: Schema.optionalKey(Handle) });
/** The handle signed in in this browser, once known; signed out on the server and on any failure. */export const whoAtom = Atom.make( HttpClient.get("/auth/whoami").pipe( Effect.flatMap(HttpClientResponse.schemaBodyJson(Who)), Effect.map(({ handle }) => Option.fromUndefinedOr(handle)), Effect.orElseSucceed(() => Option.none<Handle>()), Effect.provide(FetchHttpClient.layer) )).pipe(Atom.withServerValueInitial);added:apps/web/src/routes/auth/-dev.ts+36 added
123456789101112131415161718192021222324252627282930313233343536/** * The dev sign-in, for `vite dev` and tests only: `GET /auth/dev?handle=<h>` * sets the session cookie to `dev-<h>`, the token the dev backend (`#backend` * under the `development` condition, issue 502) knows as that fictional * person, so Today and decide can be tried with no platform. * * The leading `-` keeps this module out of the route tree; `$.ts` reaches * it through an `import()` that only a development build keeps, so the * production bundle carries none of it (W5 505's production-bundle test). */import { Handle } from "@repo/protocol/ids";import { Option, Schema } from "effect";
import type { Handled } from "../../server/session.ts";import { redirect, returnPath, sessionCookie } from "../../server/session.ts";
/** How long a dev session lasts: a working day. */const DEV_SESSION_SECONDS = 8 * 60 * 60;
const decodeHandle = Schema.decodeUnknownOption(Handle);
export const devSignIn = ({ request }: Handled): Response => { const here = new URL(request.url);
return Option.match(decodeHandle(here.searchParams.get("handle")), { onNone: () => new Response("Give a handle: /auth/dev?handle=<handle>", { headers: { "cache-control": "no-store" }, status: 400, }), onSome: (handle) => redirect(returnPath(here.origin, here.searchParams.get("return")), [ sessionCookie(`dev-${handle}`, DEV_SESSION_SECONDS), ]), });};added:apps/web/src/routes/auth/$.ts+40 added
12345678910111213141516171819202122232425262728293031323334353637383940import { createFileRoute } from "@tanstack/react-router";import { Effect } from "effect";
import type { Handled } from "../../server/session.ts";
/** * Any other `/auth/<name>`. A development build serves the dev sign-in * (`-dev.ts`) at `dev`; Vite writes `import.meta.env.DEV` as `false` in a * production build, so the `import()` below is dead code there and the dev * module never enters the bundle (W5 505's production-bundle test). It is * reached this way, not as a route of its own, so the route tree names no * dev path. */const devRoute = import.meta.env.DEV ? () => Effect.promise(() => import("./-dev.ts")) : undefined;
const notFound = () => new Response("Not found.", { headers: { "cache-control": "no-store" }, status: 404, });
const elsewhere = ({ params, request,}: Handled & { readonly params: { readonly _splat?: string } }) => params._splat === "dev" && devRoute !== undefined ? Effect.runPromise( Effect.map(devRoute(), ({ devSignIn }) => devSignIn({ request })) ) : notFound();
export const Route = createFileRoute("/auth/$")({ server: { handlers: { GET: elsewhere, }, },});added:apps/web/src/routes/auth/callback.ts+14 added
1234567891011121314import { createFileRoute } from "@tanstack/react-router";import { env } from "cloudflare:workers";
import { callbackHandler } from "../../server/session.ts";
// The platform sends the browser back here with a code, which becomes the// session cookie (issue 513; src/server/session.ts).export const Route = createFileRoute("/auth/callback")({ server: { handlers: { GET: callbackHandler(env), }, },});added:apps/web/src/routes/auth/client.ts+13 added
12345678910111213import { createFileRoute } from "@tanstack/react-router";
import { clientMetadataHandler } from "../../server/session.ts";
// The web's OAuth client, as a Client ID Metadata Document: its URL is the// client id the platform's /authorize reads (issue 513).export const Route = createFileRoute("/auth/client")({ server: { handlers: { GET: clientMetadataHandler, }, },});added:apps/web/src/routes/auth/signin.ts+14 added
1234567891011121314import { createFileRoute } from "@tanstack/react-router";import { env } from "cloudflare:workers";
import { signInHandler } from "../../server/session.ts";
// Sign-in starts here: to the platform's /authorize with PKCE (issue 513;// src/server/session.ts).export const Route = createFileRoute("/auth/signin")({ server: { handlers: { GET: signInHandler(env), }, },});added:apps/web/src/routes/auth/signout.ts+14 added
1234567891011121314import { createFileRoute } from "@tanstack/react-router";
import { signOutHandler } from "../../server/session.ts";
// Sign-out ends the session cookie: the header's form posts here, and a// plain link works too (issue 513).export const Route = createFileRoute("/auth/signout")({ server: { handlers: { GET: signOutHandler, POST: signOutHandler, }, },});added:apps/web/src/routes/auth/whoami.ts+15 added
1+import { createFileRoute } from "@tanstack/react-router";2+import { env } from "cloudflare:workers";3+4+import { serverClient } from "../../server/client.ts";5+import { whoamiHandler } from "../../server/session.ts";6+7+// Who is signed in, as the platform's `status` names the session's caller,8+// asked in process through `#backend` (issue 513).9+export 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 lines4 *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 */18+import { Effect, Option } from "effect";19+20 import type { Backend } from "./rpc.ts";21+import {22+ clearedCookie,23+ credentialFrom,24+ settingCookies,25+ withCredential,26+} from "./session.ts";27 28 /** `request` as the platform's own: the same path and query on its origin. */29 const onPlatform = (request: Request, platformUrl: string) => {30 const { pathname, search } = new URL(request.url);31 32 return new Request(new URL(`${pathname}${search}`, platformUrl), request);33 };34 35+/** `response` as it came, also expiring the session cookie. */36+const expiringSession = (response: Response) =>37+ new Response(response.body, {38+ headers: settingCookies(response.headers, [clearedCookie()]),39+ status: response.status,40+ statusText: response.statusText,41+ });42+43+const send = (env: Env, request: Request) =>44+ Effect.promise(() => env.PLATFORM.fetch(request));45+46+/** The request's body read whole, so the call can be asked twice; none for a GET or HEAD. */47+const bodyOf = (request: Request) =>48+ request.method === "GET" || request.method === "HEAD"49+ ? Effect.succeed(null)50+ : Effect.promise(() => request.arrayBuffer());51+52 export 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);57+58+ if (Option.isNone(credential)) {59+ return yield* send(env, withCredential(platform, credential));60+ }61+62+ const body = yield* bodyOf(platform);63+64+ const asked = (token: Option.Option<string>) =>65+ withCredential(66+ body === null67+ ? platform68+ : new Request(platform, { body, method: platform.method }),69+ token70+ );71+72+ const answer = yield* send(env, asked(credential));73+74+ if (answer.status !== 401) {75+ return answer;76+ }77+78+ yield* Effect.promise(() => answer.body?.cancel() ?? Promise.resolve());79+80+ 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+ */17+import { Brand } from "@repo/brand";18+import { Client } from "@repo/protocol/contracts";19+import type { Handle } from "@repo/protocol/ids";20+import { Data, Effect, Option, Redacted, Schema } from "effect";21+import type { Layer } from "effect";22+23+/**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+ */29+export const SESSION_COOKIE = "__Host-session";30+31+/** The cookie a sign-in in progress waits in: its state, PKCE verifier and way back. */32+const SIGN_IN_COOKIE = "__Host-sign-in";33+34+/** How long a sign-in in progress waits for its callback: ten minutes. */35+const SIGN_IN_SECONDS = 600;36+37+/**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+ */41+const SESSION_MARGIN_SECONDS = 60;42+43+/** The web's own sign-in paths that this module names in what it answers. */44+const AUTH_PATHS = {45+ callback: "/auth/callback",46+ client: "/auth/client",47+ signIn: "/auth/signin",48+} as const;49+50+/** What a route's server handler is handed, of what it uses. */51+export interface Handled {52+ readonly request: Request;53+}54+55+// --- The cookie -------------------------------------------------------------56+57+/**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+ */63+const Token = Schema.NonEmptyString.check(Schema.isPattern(/^[^\s",;\\]+$/u));64+65+const isToken = Schema.is(Token);66+67+/** A cookie value as it was set, if it decodes. */68+const decodedValue = Option.liftThrowable(decodeURIComponent);69+70+/** The value of the cookie `name` the request carries, if it carries one. */71+const 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+ );84+85+/** The session cookie's value: the platform token this browser signed in with. */86+export const credentialFrom = (request: Request): Option.Option<string> =>87+ cookieValue(request, SESSION_COOKIE).pipe(Option.filter(isToken));88+89+/**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+ */94+export const withCredential = (95+ request: Request,96+ token: Option.Option<string>97+): Request => {98+ const headers = new Headers(request.headers);99+100+ headers.delete("authorization");101+ headers.delete("cookie");102+103+ if (Option.isSome(token)) {104+ headers.set("authorization", `Bearer ${token.value}`);105+ }106+107+ return new Request(request, { headers });108+};109+110+/** A cookie only this origin's HTTP requests carry, never the page's JavaScript. */111+const lockedCookie = (name: string, value: string, maxAgeSeconds: number) =>112+ `${name}=${encodeURIComponent(value)}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=${Math.max(0, Math.floor(maxAgeSeconds))}`;113+114+/** The `Set-Cookie` value that holds `token` for `maxAgeSeconds`. */115+export const sessionCookie = (token: string, maxAgeSeconds: number) =>116+ lockedCookie(SESSION_COOKIE, token, maxAgeSeconds);117+118+/** The `Set-Cookie` value that ends the session now. */119+export const clearedCookie = () => lockedCookie(SESSION_COOKIE, "", 0);120+121+const clearedSignIn = () => lockedCookie(SIGN_IN_COOKIE, "", 0);122+123+/** `headers`, also setting each of `cookies` (each its own `Set-Cookie` line). */124+export const settingCookies = (125+ headers: HeadersInit,126+ cookies: readonly string[]127+) => {128+ const all = new Headers(headers);129+130+ for (const cookie of cookies) {131+ all.append("set-cookie", cookie);132+ }133+134+ return all;135+};136+137+// --- PKCE -------------------------------------------------------------------138+139+const encodeBase64Url = Schema.encodeEffect(Schema.Uint8ArrayFromBase64Url);140+141+/** `size` bytes from WebCrypto's `getRandomValues`, in base64url. */142+const randomText = (size: number) =>143+ Effect.sync(() => crypto.getRandomValues(new Uint8Array(size))).pipe(144+ Effect.flatMap(encodeBase64Url),145+ Effect.orDie146+ );147+148+/** The S256 code challenge for `verifier`: `BASE64URL(SHA256(verifier))`. */149+export 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+ );156+157+/** A fresh PKCE verifier and its challenge, and a fresh state, each 32 random bytes. */158+export const pkce = Effect.gen(function* () {159+ const verifier = yield* randomText(32);160+161+ return {162+ challenge: yield* challengeOf(verifier),163+ state: yield* randomText(32),164+ verifier,165+ };166+});167+168+// --- Where the browser goes -------------------------------------------------169+170+/** The web's OAuth client id at `origin`: the URL of its metadata document. */171+const clientIdOf = (origin: string) => `${origin}${AUTH_PATHS.client}`;172+173+/** Where the platform sends the browser back to, at `origin`. */174+const redirectUriOf = (origin: string) => `${origin}${AUTH_PATHS.callback}`;175+176+/**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+ */182+export 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+ );191+192+/** A 302 to `location` that sets `cookies` and is never cached. */193+export 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+ });205+206+/** A short page that says why signing in stopped, and how to start again. */207+const 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+ );219+220+ 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+};225+226+// --- Sign-in ----------------------------------------------------------------227+228+/** A sign-in in progress, as its cookie holds it. */229+const PendingSignIn = Schema.Struct({230+ return: Schema.String,231+ state: Schema.String,232+ verifier: Schema.String,233+});234+235+const PendingCookie = Schema.StringFromBase64Url.pipe(236+ Schema.decodeTo(Schema.fromJsonString(PendingSignIn))237+);238+239+const encodePending = Schema.encodeEffect(PendingCookie);240+241+const decodePending = Schema.decodeOption(PendingCookie);242+243+/**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+ */248+export 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;255+256+ const pending = yield* encodePending({257+ return: returnPath(here.origin, here.searchParams.get("return")),258+ state,259+ verifier,260+ }).pipe(Effect.orDie);261+262+ const authorize = new URL("/authorize", env.PUBLIC_PLATFORM_URL);263+264+ 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();272+273+ return redirect(authorize.href, [274+ lockedCookie(SIGN_IN_COOKIE, pending, SIGN_IN_SECONDS),275+ ]);276+ })277+ );278+279+// --- The callback -----------------------------------------------------------280+281+/** Signing in stopped before a session: a 400 the person reads, or a 502 when the platform could not be asked. */282+class SignInStopped extends Data.TaggedError("SignInStopped")<{283+ readonly reason: string;284+ readonly status: 400 | 502;285+}> {}286+287+const 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+});292+293+const refused = new SignInStopped({294+ reason: "The platform did not complete this sign-in.",295+ status: 400,296+});297+298+const unreachablePlatform = new SignInStopped({299+ reason: "The platform could not be reached to complete this sign-in.",300+ status: 502,301+});302+303+/** What the platform's `/token` answers a good code with, of what the web keeps. */304+const TokenAnswer = Schema.Struct({305+ access_token: Schema.RedactedFromValue(Token),306+ expires_in: Schema.Int.check(Schema.isGreaterThan(0)),307+ token_type: Schema.String,308+});309+310+const decodeTokenAnswer = Schema.decodeEffect(311+ Schema.fromJsonString(TokenAnswer)312+);313+314+/** Trades `code` for an access token at the platform's `/token`, over `PLATFORM`. */315+const 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+ });344+345+ if (!response.ok) {346+ return yield* refused;347+ }348+349+ const body = yield* Effect.tryPromise({350+ catch: () => refused,351+ try: () => response.text(),352+ });353+354+ const answer = yield* decodeTokenAnswer(body).pipe(355+ Effect.mapError(() => refused)356+ );357+358+ if (answer.token_type.toLowerCase() !== "bearer") {359+ return yield* refused;360+ }361+362+ return answer;363+ });364+365+/**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+ */371+export const callbackHandler =372+ (env: Env) =>373+ ({ request }: Handled): Promise<Response> =>374+ Effect.runPromise(375+ Effect.gen(function* () {376+ const here = new URL(request.url);377+378+ const pending = yield* Effect.fromOption(379+ Option.flatMap(cookieValue(request, SIGN_IN_COOKIE), decodePending)380+ ).pipe(Effect.mapError(() => startAgain));381+382+ if (here.searchParams.get("state") !== pending.state) {383+ return yield* startAgain;384+ }385+386+ const code = here.searchParams.get("code") ?? "";387+388+ if (code === "") {389+ return yield* refused;390+ }391+392+ const answer = yield* exchange(env, {393+ code,394+ origin: here.origin,395+ verifier: pending.verifier,396+ });397+398+ 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+ );411+412+// --- Sign-out, who, and the client -------------------------------------------413+414+/** `POST` (or a plain link's `GET`) `/auth/signout`: the session cookie ends, and the browser goes home. */415+export const signOutHandler = (_handled: Handled): Response =>416+ redirect("/", [clearedCookie()]);417+418+/** `/auth/whoami`'s answer: the handle signed in, or nothing (`features/auth/who.ts` reads it). */419+const whoAnswer = (420+ who: { readonly handle?: Handle },421+ cookies: readonly string[] = []422+) =>423+ Response.json(who, {424+ headers: settingCookies({ "cache-control": "no-store" }, cookies),425+ });426+427+/**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+ */433+export 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+ );451+452+/**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+ */458+export 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+});467+468+/** `GET /auth/client`: the web's Client ID Metadata Document. */469+export 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 line2 * 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 */10 import { describe, expect, it } from "@effect/vitest";11 import { Client } from "@repo/protocol/contracts";12 import { ProjectName } from "@repo/protocol/ids";90 unmodified lines103 });104 105 describe("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 lines120 {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 linesadded: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+ */10+import { describe, expect, it } from "@effect/vitest";11+import { Handle } from "@repo/protocol/ids";12+import { untouchable } from "@repo/testkit/untouchable";13+import { Effect, Option, Schema } from "effect";14+import { createElement } from "react";15+import { renderToStaticMarkup } from "react-dom/server";16+17+import { SessionView } from "../src/features/auth/session-slot.tsx";18+import { devSignIn } from "../src/routes/auth/-dev.ts";19+import { backend } from "../src/server/backend.ts";20+import { serverClientOver } from "../src/server/client.ts";21+import {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";35+36+const PLATFORM_URL = "https://platform-test.example.workers.dev";37+38+const WEB_URL = "https://web-test.example.workers.dev";39+40+const LIST_ASKS =41+ '[{"_tag":"Request","id":"0","tag":"listAsks","payload":{"project":"datekit"},"headers":[]}]';42+43+/** What the platform's `/token` answers a good code with (1.2.1's shape). */44+const 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+};51+52+/** What a backend or a binding was handed, read whole. */53+const 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+ );64+65+/** A fetch-shaped stub that keeps each request it is handed and answers `answer`. */66+const recorder = (answer: (request: Request) => Response) => {67+ const handed: Request[] = [];68+69+ const fetch = (request: Request) => {70+ handed.push(request);71+72+ return Promise.resolve(answer(request));73+ };74+75+ return { fetch, seen: Effect.suspend(() => Effect.forEach(handed, seenOf)) };76+};77+78+/** A web Worker env whose PLATFORM binding answers `fetch` and nothing else. */79+const 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+});85+86+/** An env whose PLATFORM throws when touched: the handler must not reach the platform. */87+const unreachable: Env = {88+ PLATFORM: untouchable<Fetcher>("PLATFORM"),89+ PUBLIC_PLATFORM_URL: PLATFORM_URL,90+};91+92+const 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+ });98+99+const get = (path: string, headers: Readonly<Record<string, string>> = {}) =>100+ new Request(`${WEB_URL}${path}`, { headers });101+102+/** A response's `Set-Cookie` lines, each split into its name, value and attributes. */103+const cookiesOf = (response: Response) =>104+ response.headers.getSetCookie().map((line) => {105+ const [pair = "", ...attributes] = line106+ .split(";")107+ .map((part) => part.trim());108+109+ const at = pair.indexOf("=");110+111+ return {112+ attributes: attributes.map((attribute) => attribute.toLowerCase()),113+ name: pair.slice(0, at),114+ pair,115+ value: pair.slice(at + 1),116+ };117+ });118+119+/** Each cookie a response sets, by name, with whether it expires now. */120+const expiriesOf = (response: Response) =>121+ cookiesOf(response).map(({ attributes, name }) => [122+ name,123+ attributes.includes("max-age=0"),124+ ]);125+126+/** The `Max-Age` of a cookie, in seconds. */127+const maxAgeOf = (attributes: readonly string[]) =>128+ Number(129+ attributes.find((attribute) => attribute.startsWith("max-age="))?.slice(8)130+ );131+132+/** The attributes a session or state cookie must carry, lowercased. */133+const LOCKED_DOWN = ["httponly", "secure", "samesite=lax", "path=/"] as const;134+135+/** Whether a cookie carries every attribute in `LOCKED_DOWN`. */136+const lockedDown = (attributes: readonly string[] = []) =>137+ LOCKED_DOWN.every((attribute) => attributes.includes(attribute));138+139+const textOf = (response: Response) => Effect.promise(() => response.text());140+141+/** Named query parameters of `url`. */142+const paramsOf = (url: URL, names: readonly string[]) =>143+ Object.fromEntries(names.map((name) => [name, url.searchParams.get(name)]));144+145+/**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+ */150+const replyingWith = (exit: string) => {151+ const parts: string[] = [];152+153+ return new TransformStream<string, string>({154+ flush: (controller) => {155+ const id =156+ /"id":(?<id>"[^"]*"|\d+)/u.exec(parts.join(""))?.groups?.id ?? "null";157+158+ controller.enqueue(`[{"_tag":"Exit","requestId":${id},"exit":${exit}}]`);159+ },160+ transform: (chunk) => {161+ parts.push(chunk);162+ },163+ });164+};165+166+/** The platform's `/rpc` answer to a `status` call: `exit`. */167+const 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+ );175+176+const STATUS_OF_INES =177+ '{"_tag":"Success","value":{"answers":[],"claims":[],"handle":"ines-v"}}';178+179+const UNAUTHENTICATED =180+ '{"_tag":"Failure","cause":[{"_tag":"Fail","error":{"_tag":"Unauthenticated"}}]}';181+182+describe("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+ });199+200+ 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(";");203+204+ expect(credentialFrom(get("/rpc", { cookie: pair }))).toStrictEqual(205+ Option.some(token)206+ );207+ });208+209+ 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+ );213+214+ expect(cookie?.name).toBe(SESSION_COOKIE);215+ expect(cookie?.attributes).toStrictEqual(216+ expect.arrayContaining([...LOCKED_DOWN, "max-age=90"])217+ );218+ });219+220+ 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+ );224+225+ 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+ });231+232+ 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+ );240+241+ const anonymous = withCredential(242+ get("/rpc", { authorization: "Bearer chosen-by-the-browser" }),243+ Option.none()244+ );245+246+ expect(forwarded.headers.get("authorization")).toBe("Bearer tok123");247+ expect(forwarded.headers.get("cookie")).toBeNull();248+ expect(anonymous.headers.get("authorization")).toBeNull();249+ });250+});251+252+describe("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+ );260+261+ 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;265+266+ 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+});276+277+describe("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"));283+284+ const response = yield* Effect.promise(() =>285+ backend(286+ listAsksPost({ cookie: `${SESSION_COOKIE}=tok123; other=1` }),287+ envWith(platform.fetch)288+ )289+ );290+291+ 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+ );303+304+ 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"));309+310+ yield* Effect.promise(() =>311+ backend(312+ listAsksPost({ authorization: "Bearer chosen-by-the-browser" }),313+ envWith(platform.fetch)314+ )315+ );316+317+ 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+ );328+329+ 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+ );341+342+ const response = yield* Effect.promise(() =>343+ backend(344+ listAsksPost({ cookie: `${SESSION_COOKIE}=stale` }),345+ envWith(platform.fetch)346+ )347+ );348+349+ const seen = yield* platform.seen;350+351+ 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+ );364+365+ 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"));368+369+ yield* Effect.promise(() =>370+ backend(371+ get("/releases/x?y=1", { cookie: `${SESSION_COOKIE}=tok123` }),372+ envWith(platform.fetch)373+ )374+ );375+376+ 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+});388+389+/** Signs in at the web and returns where the browser went and the state cookie it holds. */390+const signIn = (path: string) =>391+ Effect.gen(function* () {392+ const response = yield* Effect.promise(() =>393+ signInHandler(unreachable)({ request: get(path) })394+ );395+396+ const location = new URL(response.headers.get("location") ?? "");397+ const [state] = cookiesOf(response);398+399+ return { location, response, state };400+ });401+402+/** Signs in, then comes back to the callback with `code` and the state sign-in sent, to a platform that answers `/token` with `answer`. */403+const 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);411+412+ 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+ );420+421+ return { location, response, seen: yield* platform.seen, state };422+ });423+424+/** Where the callback sends the browser after a sign-in asked to come back to `path`. */425+const backTo = (path: string) =>426+ Effect.map(427+ signInAndBack(`/auth/signin?return=${encodeURIComponent(path)}`, "c0de"),428+ ({ response }) => response.headers.get("location")429+ );430+431+describe("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+ );439+440+ 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+ );462+463+ 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");468+469+ 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+});477+478+describe("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+ );487+488+ const [exchange, ...more] = seen;489+ const form = new URLSearchParams(exchange?.body);490+491+ 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+ );515+516+ 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+ );524+525+ const cookies = cookiesOf(response);526+ const session = cookies.find(({ name }) => name === SESSION_COOKIE);527+ const maxAge = maxAgeOf(session?.attributes ?? []);528+529+ 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+ );543+544+ 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");549+550+ const shown = `${yield* textOf(response)}\n${response.headers.get("location") ?? ""}`;551+552+ 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+ );559+560+ 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");565+566+ const response = yield* Effect.promise(() =>567+ callbackHandler(unreachable)({568+ request: get("/auth/callback?code=c0de&state=forged", {569+ cookie: state?.pair ?? "",570+ }),571+ })572+ );573+574+ expect(response.status).toBe(400);575+ expect(576+ cookiesOf(response).filter(({ name }) => name === SESSION_COOKIE)577+ ).toStrictEqual([]);578+ })579+ );580+581+ 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+ );588+589+ expect(response.status).toBe(400);590+ expect(591+ cookiesOf(response).filter(({ name }) => name === SESSION_COOKIE)592+ ).toStrictEqual([]);593+ })594+ );595+596+ 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+ );603+604+ expect(response.status).toBe(400);605+ expect(606+ cookiesOf(response).filter(({ name }) => name === SESSION_COOKIE)607+ ).toStrictEqual([]);608+ })609+ );610+611+ 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+ );618+619+ expect(response.status).toBe(400);620+ expect(621+ cookiesOf(response).filter(({ name }) => name === SESSION_COOKIE)622+ ).toStrictEqual([]);623+ })624+ );625+626+ 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+});643+644+describe("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+ });653+654+ return [655+ response.status,656+ response.headers.get("location"),657+ expiriesOf(response),658+ ];659+ });660+661+ expect(answers).toStrictEqual([662+ [302, "/", [[SESSION_COOKIE, true]]],663+ [302, "/", [[SESSION_COOKIE, true]]],664+ ]);665+ });666+});667+668+/** `/auth/whoami` with `headers`, asking the platform through the production backend in process. */669+const 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+ );675+676+describe("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);682+683+ expect(response.status).toBe(200);684+ expect(yield* textOf(response)).toBe("{}");685+ })686+ );687+688+ 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));693+694+ const response = yield* whoami(envWith(platform.fetch), {695+ cookie: `${SESSION_COOKIE}=tok123`,696+ });697+698+ 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+ );719+720+ 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+ );729+730+ const response = yield* whoami(envWith(platform.fetch), {731+ cookie: `${SESSION_COOKIE}=stale`,732+ });733+734+ expect(yield* textOf(response)).toBe("{}");735+ expect(expiriesOf(response)).toStrictEqual([[SESSION_COOKIE, true]]);736+ })737+ );738+});739+740+/** A JSON object, read as data. */741+const decodeDocument = Schema.decodeUnknownEffect(742+ Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown))743+);744+745+describe("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+ });753+754+ const document = yield* decodeDocument(yield* textOf(response));755+756+ 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+});773+774+describe("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+ });779+780+ const [session] = cookiesOf(response);781+782+ 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+ });791+792+ 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+ });796+797+ expect(response.status).toBe(400);798+ expect(response.headers.getSetCookie()).toStrictEqual([]);799+ });800+});801+802+describe("the header's session slot", () => {803+ const ines = Schema.decodeSync(Handle)("ines-v");804+805+ 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+ );809+810+ 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+ });817+818+ 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+ );822+823+ expect(markup).toContain('href="/auth/signin?return=%2Ftoday"');824+ expect(markup).toContain(">Sign in<");825+ expect(markup).not.toContain("/auth/signout");826+ });827+});