session.ts
This file
Path
apps/web/src/server/session.ts
458 lines · 13.7 KiB · TypeScript
Last changed by
Merge build/comments-web-rest into mainoscabrielbefore adoption0eb1248
History of this fileTake it
The walk stopped after 200 commits: lines older than 678c8b8 point at it.
Merge build/comments-web-rest into mainoscabrielbefore adoption0eb1248
lines 1–3why, one step back1// The access token lives only in an HttpOnly cookie: no URL, log line or response body carries it, and the web2// holds no secret (PKCE, and a Client ID Metadata Document it serves itself). The handle cookie beside it only3// shapes what a page shows; every call carries the token, and the platform decides who the caller is.Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 4–5why, one step back4import { Brand } from "@repo/brand";5import { Client } from "@repo/protocol/contracts";Merge build/1213-platform-performance-and-agent-surfacesoscabrielbefore adoption1d75a0d
line 6why, one step back6import { Handle as HandleSchema } from "@repo/protocol/ids";Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 7–10why, one step back7import type { Handle } from "@repo/protocol/ids";8import { Data, Effect, Option, Redacted, Schema } from "effect";9import type { Layer } from "effect";10Merge build/comments-web-rest into mainoscabrielbefore adoption0eb1248
line 11why, one step back11// `__Host-` keeps it to this exact origin over HTTPS, so no sibling host on the same `workers.dev` subdomain can set or shadow it.Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 12–13why, one step back12export const SESSION_COOKIE = "__Host-session";13Merge build/1213-platform-performance-and-agent-surfacesoscabrielbefore adoption1d75a0d
lines 14–15why, one step back14export const HANDLE_COOKIE = "__Host-handle";15Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 16–35why, one step back16const SIGN_IN_COOKIE = "__Host-sign-in";1718const SIGN_IN_SECONDS = 600;1920/**21 * How much sooner than its token the session cookie expires, so a cookie22 * never carries a token the platform has just let go.23 */24const SESSION_MARGIN_SECONDS = 60;2526const AUTH_PATHS = {27 callback: "/auth/callback",28 client: "/auth/client",29 signIn: "/auth/signin",30} as const;3132export interface Handled {33 readonly request: Request;34}35Merge build/comments-web-rest into mainoscabrielbefore adoption0eb1248
line 36why, one step back36// Only such a token is kept and read back, so a cookie is never set that no later request could sign in with.Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 37–83why, one step back37const Token = Schema.NonEmptyString.check(Schema.isPattern(/^[^\s",;\\]+$/u));3839const isToken = Schema.is(Token);4041const decodedValue = Option.liftThrowable(decodeURIComponent);4243const cookieValue = (request: Request, name: string) =>44 Option.fromNullishOr(request.headers.get("cookie")).pipe(45 Option.flatMap((header) =>46 Option.fromUndefinedOr(47 header48 .split(";")49 .map((part) => part.trim())50 .find((part) => part.startsWith(`${name}=`))51 )52 ),53 Option.map((pair) => pair.slice(name.length + 1)),54 Option.flatMap(decodedValue)55 );5657export const credentialFrom = (request: Request): Option.Option<string> =>58 cookieValue(request, SESSION_COOKIE).pipe(Option.filter(isToken));5960export const withCredential = (61 request: Request,62 token: Option.Option<string>63): Request => {64 const headers = new Headers(request.headers);6566 headers.delete("authorization");67 headers.delete("cookie");6869 if (Option.isSome(token)) {70 headers.set("authorization", `Bearer ${token.value}`);71 }7273 return new Request(request, { headers });74};7576const lockedCookie = (name: string, value: string, maxAgeSeconds: number) =>77 `${name}=${encodeURIComponent(value)}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=${Math.max(0, Math.floor(maxAgeSeconds))}`;7879export const sessionCookie = (token: string, maxAgeSeconds: number) =>80 lockedCookie(SESSION_COOKIE, token, maxAgeSeconds);8182export const clearedCookie = () => lockedCookie(SESSION_COOKIE, "", 0);83Merge build/1213-platform-performance-and-agent-surfacesoscabrielbefore adoption1d75a0d
lines 84–88why, one step back84export const clearedCookies = () => [85 clearedCookie(),86 lockedCookie(HANDLE_COOKIE, "", 0),87];88Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 89–129why, one step back89const clearedSignIn = () => lockedCookie(SIGN_IN_COOKIE, "", 0);9091export const settingCookies = (92 headers: HeadersInit,93 cookies: readonly string[]94) => {95 const all = new Headers(headers);9697 for (const cookie of cookies) {98 all.append("set-cookie", cookie);99 }100101 return all;102};103104const encodeBase64Url = Schema.encodeEffect(Schema.Uint8ArrayFromBase64Url);105106const randomText = (size: number) =>107 Effect.sync(() => crypto.getRandomValues(new Uint8Array(size))).pipe(108 Effect.flatMap(encodeBase64Url),109 Effect.orDie110 );111112export const challengeOf = (verifier: string) =>113 Effect.promise(() =>114 crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))115 ).pipe(116 Effect.flatMap((digest) => encodeBase64Url(new Uint8Array(digest))),117 Effect.orDie118 );119120export const pkce = Effect.gen(function* () {121 const verifier = yield* randomText(32);122123 return {124 challenge: yield* challengeOf(verifier),125 state: yield* randomText(32),126 verifier,127 };128});129Merge build/1213-platform-performance-and-agent-surfacesoscabrielbefore adoption1d75a0d
lines 130–139why, one step back130const HANDLE_LEARNED_SECONDS = 24 * 60 * 60;131132const fingerprintOf = (token: string) =>133 Effect.promise(() =>134 crypto.subtle.digest("SHA-256", new TextEncoder().encode(token))135 ).pipe(136 Effect.flatMap((digest) => encodeBase64Url(new Uint8Array(digest))),137 Effect.orDie138 );139Merge build/comments-web-rest into mainoscabrielbefore adoption0eb1248
line 140why, one step back140// `<fingerprint>.<handle>`: a fingerprint is base64url, which has no `.`.Merge build/1213-platform-performance-and-agent-surfacesoscabrielbefore adoption1d75a0d
lines 141–175why, one step back141const handleCookie = (token: string, handle: Handle, maxAgeSeconds: number) =>142 Effect.map(fingerprintOf(token), (fingerprint) =>143 lockedCookie(HANDLE_COOKIE, `${fingerprint}.${handle}`, maxAgeSeconds)144 );145146const decodeHandle = Schema.decodeUnknownOption(HandleSchema);147148const keptHandle = (request: Request, token: string) =>149 Effect.map(fingerprintOf(token), (fingerprint) =>150 Option.flatMap(cookieValue(request, HANDLE_COOKIE), (value) => {151 const at = value.indexOf(".");152153 return at > 0 && value.slice(0, at) === fingerprint154 ? decodeHandle(value.slice(at + 1))155 : Option.none();156 })157 );158159const handleOf = (160 clientFor: (request: Request) => Layer.Layer<Client>,161 origin: string,162 token: string163) =>164 Effect.service(Client).pipe(165 Effect.flatMap((client) => client.status({})),166 Effect.map(({ handle }) => handle),167 Effect.provide(168 clientFor(169 new Request(`${origin}/auth/whoami`, {170 headers: { cookie: `${SESSION_COOKIE}=${encodeURIComponent(token)}` },171 })172 )173 )174 );175Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 176–179why, one step back176const clientIdOf = (origin: string) => `${origin}${AUTH_PATHS.client}`;177178const redirectUriOf = (origin: string) => `${origin}${AUTH_PATHS.callback}`;179Merge build/comments-web-rest into mainoscabrielbefore adoption0eb1248
line 180why, one step back180// Resolved against the origin, so `//host`, `/\host` and a full URL elsewhere all fall back to the front page.Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 181–217why, one step back181export const returnPath = (origin: string, wanted: string | null) =>182 Option.fromNullishOr(wanted).pipe(183 Option.filter((path) => path.startsWith("/")),184 Option.flatMap((path) => Option.fromNullishOr(URL.parse(path, origin))),185 Option.filter((url) => url.origin === origin),186 Option.map(({ hash, pathname, search }) => `${pathname}${search}${hash}`),187 Option.filter((path) => !path.startsWith("/auth/")),188 Option.getOrElse(() => "/")189 );190191export const redirect = (location: string, cookies: readonly string[]) =>192 new Response(null, {193 headers: settingCookies(194 {195 "cache-control": "no-store",196 location,197 "referrer-policy": "no-referrer",198 },199 cookies200 ),201 status: 302,202 });203204const stoppedPage = (205 status: number,206 reason: string,207 cookies: readonly string[]208) => {209 const headers = settingCookies(210 {211 "cache-control": "no-store",212 "content-type": "text/html; charset=utf-8",213 },214 cookies215 );216217 return new Response(Merge build/1300-w13-foundation into mainoscabrielbefore adoption0e29c37
line 218why, one step back218 `<!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="/asks">the open asks</a>.</p>`,Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 219–349why, one step back219 { headers, status }220 );221};222223const PendingSignIn = Schema.Struct({224 return: Schema.String,225 state: Schema.String,226 verifier: Schema.String,227});228229const PendingCookie = Schema.StringFromBase64Url.pipe(230 Schema.decodeTo(Schema.fromJsonString(PendingSignIn))231);232233const encodePending = Schema.encodeEffect(PendingCookie);234235const decodePending = Schema.decodeOption(PendingCookie);236237export const signInHandler =238 (env: Env) =>239 ({ request }: Handled): Promise<Response> =>240 Effect.runPromise(241 Effect.gen(function* () {242 const here = new URL(request.url);243 const { challenge, state, verifier } = yield* pkce;244245 const pending = yield* encodePending({246 return: returnPath(here.origin, here.searchParams.get("return")),247 state,248 verifier,249 }).pipe(Effect.orDie);250251 const authorize = new URL("/authorize", env.PUBLIC_PLATFORM_URL);252253 authorize.search = new URLSearchParams({254 client_id: clientIdOf(here.origin),255 code_challenge: challenge,256 code_challenge_method: "S256",257 redirect_uri: redirectUriOf(here.origin),258 response_type: "code",259 state,260 }).toString();261262 return redirect(authorize.href, [263 lockedCookie(SIGN_IN_COOKIE, pending, SIGN_IN_SECONDS),264 ]);265 })266 );267268class SignInStopped extends Data.TaggedError("SignInStopped")<{269 readonly reason: string;270 readonly status: 400 | 502;271}> {}272273const startAgain = new SignInStopped({274 reason:275 "This sign-in was not started in this browser, or it took longer than ten minutes.",276 status: 400,277});278279const refused = new SignInStopped({280 reason: "The platform did not complete this sign-in.",281 status: 400,282});283284const unreachablePlatform = new SignInStopped({285 reason: "The platform could not be reached to complete this sign-in.",286 status: 502,287});288289const TokenAnswer = Schema.Struct({290 access_token: Schema.RedactedFromValue(Token),291 expires_in: Schema.Int.check(Schema.isGreaterThan(0)),292 token_type: Schema.String,293});294295const decodeTokenAnswer = Schema.decodeEffect(296 Schema.fromJsonString(TokenAnswer)297);298299const exchange = (300 env: Env,301 input: {302 readonly code: string;303 readonly origin: string;304 readonly verifier: string;305 }306) =>307 Effect.gen(function* () {308 const response = yield* Effect.tryPromise({309 catch: () => unreachablePlatform,310 try: () =>311 env.PLATFORM.fetch(312 new Request(new URL("/token", env.PUBLIC_PLATFORM_URL), {313 body: new URLSearchParams({314 client_id: clientIdOf(input.origin),315 code: input.code,316 code_verifier: input.verifier,317 grant_type: "authorization_code",318 redirect_uri: redirectUriOf(input.origin),319 }),320 headers: {321 accept: "application/json",322 "content-type": "application/x-www-form-urlencoded",323 },324 method: "POST",325 })326 ),327 });328329 if (!response.ok) {330 return yield* refused;331 }332333 const body = yield* Effect.tryPromise({334 catch: () => refused,335 try: () => response.text(),336 });337338 const answer = yield* decodeTokenAnswer(body).pipe(339 Effect.mapError(() => refused)340 );341342 if (answer.token_type.toLowerCase() !== "bearer") {343 return yield* refused;344 }345346 return answer;347 });348349export const callbackHandler =Merge build/1213-platform-performance-and-agent-surfacesoscabrielbefore adoption1d75a0d
line 350why, one step back350 (env: Env, clientFor: (request: Request) => Layer.Layer<Client>) =>Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 351–375why, one step back351 ({ request }: Handled): Promise<Response> =>352 Effect.runPromise(353 Effect.gen(function* () {354 const here = new URL(request.url);355356 const pending = yield* Effect.fromOption(357 Option.flatMap(cookieValue(request, SIGN_IN_COOKIE), decodePending)358 ).pipe(Effect.mapError(() => startAgain));359360 if (here.searchParams.get("state") !== pending.state) {361 return yield* startAgain;362 }363364 const code = here.searchParams.get("code") ?? "";365366 if (code === "") {367 return yield* refused;368 }369370 const answer = yield* exchange(env, {371 code,372 origin: here.origin,373 verifier: pending.verifier,374 });375Merge build/1213-platform-performance-and-agent-surfacesoscabrielbefore adoption1d75a0d
lines 376–385why, one step back376 const token = Redacted.value(answer.access_token);377 const lives = answer.expires_in - SESSION_MARGIN_SECONDS;378379 // Signing in never waits on this: whatever stops it keeps no handle.380 const handle = yield* handleOf(clientFor, here.origin, token).pipe(381 Effect.flatMap((named) => handleCookie(token, named, lives)),382 Effect.map(Option.some),383 Effect.catchCause(() => Effect.succeedNone)384 );385Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
line 386why, one step back386 return redirect(returnPath(here.origin, pending.return), [Merge build/1213-platform-performance-and-agent-surfacesoscabrielbefore adoption1d75a0d
lines 387–388why, one step back387 sessionCookie(token, lives),388 ...Option.toArray(handle),Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 389–398why, one step back389 clearedSignIn(),390 ]);391 }).pipe(392 Effect.catchTag("SignInStopped", ({ reason, status }) =>393 Effect.succeed(stoppedPage(status, reason, [clearedSignIn()]))394 )395 )396 );397398export const signOutHandler = (_handled: Handled): Response =>Merge build/1213-platform-performance-and-agent-surfacesoscabrielbefore adoption1d75a0d
line 399why, one step back399 redirect("/", clearedCookies());Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 400–413why, one step back400401const whoAnswer = (402 who: { readonly handle?: Handle },403 cookies: readonly string[] = []404) =>405 Response.json(who, {406 headers: settingCookies({ "cache-control": "no-store" }, cookies),407 });408409export const whoamiHandler =410 (clientFor: (request: Request) => Layer.Layer<Client>) =>411 ({ request }: Handled): Promise<Response> =>412 Effect.runPromise(413 Option.match(credentialFrom(request), {Merge build/1213-platform-performance-and-agent-surfacesoscabrielbefore adoption1d75a0d
lines 414–440why, one step back414 onNone: () =>415 Effect.succeed(416 whoAnswer(417 {},418 Option.isSome(cookieValue(request, HANDLE_COOKIE))419 ? [lockedCookie(HANDLE_COOKIE, "", 0)]420 : []421 )422 ),423 onSome: (token) =>424 Effect.flatMap(keptHandle(request, token), (kept) =>425 Option.match(kept, {426 onNone: () =>427 handleOf(clientFor, new URL(request.url).origin, token).pipe(428 Effect.flatMap((handle) =>429 Effect.map(430 handleCookie(token, handle, HANDLE_LEARNED_SECONDS),431 (cookie) => whoAnswer({ handle }, [cookie])432 )433 ),434 Effect.catchTag("Unauthenticated", () =>435 Effect.succeed(whoAnswer({}, clearedCookies()))436 ),437 Effect.orElseSucceed(() => whoAnswer({}))438 ),439 onSome: (handle) => Effect.succeed(whoAnswer({ handle })),440 })Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 441–458why, one step back441 ),442 })443 );444445export const webClientMetadata = (origin: string) => ({446 client_id: clientIdOf(origin),447 client_name: `${Brand.name} web`,448 client_uri: origin,449 grant_types: ["authorization_code"],450 redirect_uris: [redirectUriOf(origin)],451 response_types: ["code"],452 token_endpoint_auth_method: "none",453});454455export const clientMetadataHandler = ({ request }: Handled): Response =>456 Response.json(webClientMetadata(new URL(request.url).origin), {457 headers: { "cache-control": "public, max-age=300" },458 });