authenticate.ts
This file
Path
packages/protocol/src/authenticate.ts
67 lines · 2.0 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–17why, one step back1import { Context, Effect, Layer, Option } from "effect";23import { Audience } from "./annotations.ts";4import {5 Anonymous,6 Authenticated,7 CurrentPrincipal,8 Unauthenticated,9} from "./principal.ts";10import type { Person, Principal } from "./principal.ts";1112export const bearerToken = (authorization: string | undefined) =>13 Option.fromNullishOr(14 /^Bearer (?<token>\S+)$/iu.exec(authorization ?? "")?.groups?.token15 );1617/**Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f
lines 18–20why, one step back18 * An unknown credential, or an `authorization` header with no bearer token,19 * is refused, never taken for anyone; a failing `verify` kills the call20 * rather than run it as anyone.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 21–67why, one step back21 */22export const authenticated = <E, R>(23 verify: (credential: string) => Effect.Effect<Option.Option<Person>, E, R>24): Layer.Layer<Authenticated, never, R> =>25 Layer.effect(26 Authenticated,27 Effect.gen(function* () {28 const services = yield* Effect.context<R>();2930 const verified = (credential: string) =>31 verify(credential).pipe(Effect.orDie, Effect.provideContext(services));3233 const principalOf = (34 authorization: string | undefined,35 audience: (typeof Audience)["Service"]36 ): Effect.Effect<Option.Option<Principal>> => {37 if (authorization === undefined) {38 return audience === "public"39 ? Effect.succeedSome(Anonymous.make({}))40 : Effect.succeedNone;41 }4243 return Option.match(bearerToken(authorization), {44 onNone: () => Effect.succeedNone,45 onSome: verified,46 });47 };4849 return (effect, { headers, rpc }) =>50 Effect.gen(function* () {51 const principal = yield* principalOf(52 headers.authorization,53 Context.get(rpc.annotations, Audience)54 );5556 if (Option.isNone(principal)) {57 return yield* new Unauthenticated();58 }5960 return yield* Effect.provideService(61 effect,62 CurrentPrincipal,63 principal.value64 );65 });66 })67 );