oauth-server.ts
This file
Path
apps/cli/test/oauth-server.ts
141 lines · 4.2 KiB · TypeScript
Last changed by
Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f
History of this fileTake it
The walk stopped after 200 commits: lines older than 678c8b8 point at 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 1–141why, one step back1import { NodeHttpServer } from "@effect/platform-node";2import { Context, Effect, Layer, Ref, Schema } from "effect";3import { HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http";45export interface OAuthServerOptions {6 readonly token: string;7 readonly state?: "same" | "other";8}910interface Grant {11 readonly challenge: string;12 readonly clientId: string;13 readonly redirectUri: string;14}1516const TokenForm = Schema.Struct({17 client_id: Schema.String,18 code: Schema.String,19 code_verifier: Schema.String,20 grant_type: Schema.String,21 redirect_uri: Schema.String,22});2324/** Base64url without padding, as RFC 7636 §4.2 spells the S256 challenge. */25const base64url = (bytes: Uint8Array) =>26 btoa(String.fromCodePoint(...bytes))27 .replaceAll("+", "-")28 .replaceAll("/", "_")29 .replace(/=+$/u, "");3031const s256 = (verifier: string) =>32 Effect.map(33 Effect.promise(() =>34 crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))35 ),36 (digest) => base64url(new Uint8Array(digest))37 );3839const refused = (error: string) =>40 HttpServerResponse.jsonUnsafe({ error }, { status: 400 });4142export const oauthServer = (options: OAuthServerOptions) =>43 Effect.gen(function* () {44 const grants = yield* Ref.make<ReadonlyMap<string, Grant>>(new Map());45 const authorizations = yield* Ref.make<readonly URLSearchParams[]>([]);46 const issued = yield* Ref.make(0);4748 const authorize = (query: URLSearchParams) =>49 Effect.gen(function* () {50 yield* Ref.update(authorizations, (all) => [...all, query]);5152 const redirectUri = query.get("redirect_uri") ?? "";53 const challenge = query.get("code_challenge") ?? "";5455 if (56 query.get("response_type") !== "code" ||57 query.get("code_challenge_method") !== "S256" ||58 challenge === ""59 ) {60 return refused("invalid_request");61 }6263 const code = `code-${yield* Ref.updateAndGet(issued, (n) => n + 1)}`;6465 yield* Ref.update(grants, (all) =>66 new Map(all).set(code, {67 challenge,68 clientId: query.get("client_id") ?? "",69 redirectUri,70 })71 );7273 const back = new URL(redirectUri);7475 back.searchParams.set("code", code);76 back.searchParams.set(77 "state",78 options.state === "other"79 ? "not-the-state"80 : (query.get("state") ?? "")81 );8283 return HttpServerResponse.redirect(back.href, { status: 302 });84 });8586 const token = Effect.gen(function* () {87 const form = yield* HttpServerRequest.schemaBodyUrlParams(TokenForm);88 const grant = (yield* Ref.get(grants)).get(form.code);8990 yield* Ref.update(grants, (all) => {91 const left = new Map(all);9293 left.delete(form.code);9495 return left;96 });9798 if (99 form.grant_type !== "authorization_code" ||100 grant === undefined ||101 grant.clientId !== form.client_id ||102 grant.redirectUri !== form.redirect_uri ||103 (yield* s256(form.code_verifier)) !== grant.challenge104 ) {105 return refused("invalid_grant");106 }107108 return HttpServerResponse.jsonUnsafe({109 access_token: options.token,110 token_type: "bearer",111 });112 }).pipe(Effect.orElseSucceed(() => refused("invalid_request")));113114 const app = Effect.gen(function* () {115 const request = yield* HttpServerRequest.HttpServerRequest;116 const url = new URL(request.url, "http://localhost");117118 if (request.method === "GET" && url.pathname === "/authorize") {119 return yield* authorize(url.searchParams);120 }121122 if (request.method === "POST" && url.pathname === "/token") {123 return yield* token;124 }125126 return HttpServerResponse.empty({ status: 404 });127 });128129 const server = yield* Layer.build(130 HttpServer.serve(app).pipe(Layer.provideMerge(NodeHttpServer.layerTest))131 ).pipe(Effect.orDie);132133 const { address } = Context.get(server, HttpServer.HttpServer);134135 const origin =136 "port" in address137 ? `http://127.0.0.1:${address.port}`138 : yield* Effect.die("the test server listens on a socket, not a port");139140 return { authorizations: Ref.get(authorizations), origin };141 });