The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { Actor, customer } from "@bank/domain/Actor"; |
| 2 | import { CurrentActor } from "@bank/domain/CurrentActor.context"; |
| 3 | import { CustomerId } from "@bank/domain/Customer/Customer.id"; |
| 4 | import { SESSION_COOKIE, Session, Unauthorized } from "@bank/domain/Session.middleware"; |
| 5 | import * as Alchemy from "alchemy"; |
| 6 | import * as Clock from "effect/Clock"; |
| 7 | import * as Context from "effect/Context"; |
| 8 | import * as Effect from "effect/Effect"; |
| 9 | import * as Base64Url from "effect/encoding/Base64Url"; |
| 10 | import * as Cookies from "effect/http/Cookies"; |
| 11 | import * as Headers from "effect/http/Headers"; |
| 12 | import { HttpServerRequest } from "effect/http/HttpServerRequest"; |
| 13 | import * as HttpServerResponse from "effect/http/HttpServerResponse"; |
| 14 | import * as Layer from "effect/Layer"; |
| 15 | import * as Option from "effect/Option"; |
| 16 | import * as Redacted from "effect/Redacted"; |
| 17 | import * as Result from "effect/Result"; |
| 18 | import * as Schema from "effect/Schema"; |
| 19 | |
| 20 | /** How long a session lasts. */ |
| 21 | const SESSION_DAYS = 7; |
| 22 | |
| 23 | /** The key that signs sessions: the same for every request to this stage. */ |
| 24 | export class SessionKey extends Context.Service< |
| 25 | SessionKey, |
| 26 | Effect.Effect<Redacted.Redacted<string>> |
| 27 | >()("Bank/SessionKey") {} |
| 28 | |
| 29 | /** A random key, made once when the stage is first deployed and kept in its state. */ |
| 30 | export const SessionKeyLive = Layer.effect( |
| 31 | SessionKey, |
| 32 | Effect.gen(function* () { |
| 33 | const key = yield* Alchemy.Random("SessionKey"); |
| 34 | return yield* key.text; |
| 35 | }), |
| 36 | ); |
| 37 | |
| 38 | const hmacKey = Effect.fn(function* () { |
| 39 | const secret = Redacted.value(yield* yield* SessionKey); |
| 40 | return yield* Effect.promise(() => |
| 41 | crypto.subtle.importKey( |
| 42 | "raw", |
| 43 | new TextEncoder().encode(secret), |
| 44 | { name: "HMAC", hash: "SHA-256" }, |
| 45 | false, |
| 46 | ["sign", "verify"], |
| 47 | ), |
| 48 | ); |
| 49 | }); |
| 50 | |
| 51 | /** What a session token says: who, and until when. */ |
| 52 | const Claims = Schema.fromJsonString(Schema.Struct({ actor: Actor, expires: Schema.Number })); |
| 53 | |
| 54 | /** A session token for `actor`: its claims and their HMAC, so no one without the key can make one. */ |
| 55 | export const signSession = Effect.fn(function* (actor: Actor) { |
| 56 | const expires = (yield* Clock.currentTimeMillis) + SESSION_DAYS * 24 * 60 * 60 * 1000; |
| 57 | // Encoding our own claims can't fail. |
| 58 | const json = yield* Schema.encodeEffect(Claims)({ actor, expires }).pipe(Effect.orDie); |
| 59 | const claims = Base64Url.encode(json); |
| 60 | const key = yield* hmacKey(); |
| 61 | const mac = yield* Effect.promise(() => |
| 62 | crypto.subtle.sign("HMAC", key, new TextEncoder().encode(claims)), |
| 63 | ); |
| 64 | return `${claims}.${Base64Url.encode(new Uint8Array(mac))}`; |
| 65 | }); |
| 66 | |
| 67 | /** The actor a token was signed for, if its signature checks out and it hasn't expired. */ |
| 68 | const verifySession = Effect.fn(function* (token: string) { |
| 69 | const [claims, mac, ...rest] = token.split("."); |
| 70 | if (!claims || !mac || rest.length > 0) return Option.none<Actor>(); |
| 71 | const signature = Base64Url.decode(mac); |
| 72 | if (Result.isFailure(signature)) return Option.none<Actor>(); |
| 73 | const key = yield* hmacKey(); |
| 74 | // `verify` compares in constant time. |
| 75 | const valid = yield* Effect.promise(() => |
| 76 | crypto.subtle.verify( |
| 77 | "HMAC", |
| 78 | key, |
| 79 | new Uint8Array(signature.success), |
| 80 | new TextEncoder().encode(claims), |
| 81 | ), |
| 82 | ); |
| 83 | const json = Base64Url.decodeString(claims); |
| 84 | if (!valid || Result.isFailure(json)) return Option.none<Actor>(); |
| 85 | const decoded = yield* Schema.decodeEffect(Claims)(json.success).pipe(Effect.option); |
| 86 | const now = yield* Clock.currentTimeMillis; |
| 87 | return Option.flatMap(decoded, (c) => (c.expires > now ? Option.some(c.actor) : Option.none())); |
| 88 | }); |
| 89 | |
| 90 | /** The token a request carries: its session cookie (browsers), or `Authorization: Bearer` (scripts). */ |
| 91 | const tokenOf = (headers: Headers.Headers): Option.Option<string> => |
| 92 | Option.orElse( |
| 93 | Option.flatMap(Headers.get(headers, "cookie"), (cookie) => |
| 94 | Option.fromNullishOr(Cookies.parseHeader(cookie)[SESSION_COOKIE]), |
| 95 | ), |
| 96 | () => |
| 97 | Option.flatMap(Headers.get(headers, "authorization"), (value) => |
| 98 | value.startsWith("Bearer ") ? Option.some(value.slice("Bearer ".length)) : Option.none(), |
| 99 | ), |
| 100 | ); |
| 101 | |
| 102 | /** Who a request is from, if it carries a valid session. */ |
| 103 | export const actorOf = Effect.fn(function* (headers: Headers.Headers) { |
| 104 | const token = tokenOf(headers); |
| 105 | return Option.isNone(token) ? Option.none<Actor>() : yield* verifySession(token.value); |
| 106 | }); |
| 107 | |
| 108 | /** The {@link Session} middleware: provides the request's actor, or fails with Unauthorized. */ |
| 109 | export const SessionLive = Layer.effect( |
| 110 | Session, |
| 111 | Effect.gen(function* () { |
| 112 | const key = yield* SessionKey; |
| 113 | return (effect, { headers }) => |
| 114 | actorOf(headers).pipe( |
| 115 | Effect.provideService(SessionKey, key), |
| 116 | Effect.flatMap( |
| 117 | Option.match({ |
| 118 | onNone: () => Effect.fail(new Unauthorized()), |
| 119 | onSome: (actor) => Effect.provideService(effect, CurrentActor, actor), |
| 120 | }), |
| 121 | ), |
| 122 | ); |
| 123 | }), |
| 124 | ); |
| 125 | |
| 126 | const SignIn = Schema.Struct({ customerId: CustomerId }); |
| 127 | |
| 128 | /** |
| 129 | * `POST /api/session` signs a customer in: it sets the signed session cookie, |
| 130 | * and returns the same token for scripts to send as `Authorization: Bearer`. |
| 131 | * `DELETE` signs them out. `HttpOnly` keeps the cookie from scripts, and |
| 132 | * `SameSite=Strict` keeps it off cross-site requests, WebSocket upgrades |
| 133 | * included. Demo only: anyone may sign in as any customer. Check a password, |
| 134 | * a magic link or a provider here before signing. |
| 135 | */ |
| 136 | export const sessionRoute = Effect.gen(function* () { |
| 137 | const request = yield* HttpServerRequest; |
| 138 | const options = { httpOnly: true, secure: true, sameSite: "strict", path: "/" } as const; |
| 139 | if (request.method === "DELETE") { |
| 140 | return HttpServerResponse.empty({ status: 204 }).pipe( |
| 141 | HttpServerResponse.setCookieUnsafe(SESSION_COOKIE, "", { ...options, maxAge: 0 }), |
| 142 | ); |
| 143 | } |
| 144 | if (request.method !== "POST") return HttpServerResponse.empty({ status: 405 }); |
| 145 | const body = yield* request.json.pipe( |
| 146 | Effect.flatMap(Schema.decodeUnknownEffect(SignIn)), |
| 147 | Effect.option, |
| 148 | ); |
| 149 | if (Option.isNone(body)) |
| 150 | return HttpServerResponse.text("Expected { customerId }", { status: 400 }); |
| 151 | const token = yield* signSession(customer(body.value.customerId)); |
| 152 | return yield* HttpServerResponse.json({ token }).pipe( |
| 153 | Effect.map( |
| 154 | HttpServerResponse.setCookieUnsafe(SESSION_COOKIE, token, { |
| 155 | ...options, |
| 156 | maxAge: `${SESSION_DAYS} days`, |
| 157 | }), |
| 158 | ), |
| 159 | ); |
| 160 | }); |