@devries-cameron20 / t3code Mirror · read-only
Fork 0

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, 06:00 UTC

main
mdx 379 lines 15 KB
Raw
1 ---
2 title: Sessions and middleware
3 description: Authenticate every request, carry who is asking into the domain, and sign browsers in with a cookie.
4 ---
5
6 Every command and read starts with a question: who is asking? Middleware answers it before the request reaches the domain, and provides the answer as a request context that `decide` and `validate` read.
7
8 This page signs sessions by hand: the Worker signs a token, and middleware checks it. To sign users in with GitHub, Google or another provider, see [Sign in with better-auth](/domain/better-auth).
9
10 ## Declare who is asking
11
12 A request context is a service that travels with the request into the domain. It has a schema, because a command carries it to wherever its aggregate runs.
13
14 ```typescript
15 // packages/domain/src/CurrentActor.context.ts
16 import * as Domain from "@alchemy.run/domain";
17 import { Actor } from "./Actor.ts";
18
19 /**
20 * Who is making the current request. `Session` provides it; commands read it
21 * in `decide` and views in `validate`. Senders without a session (policies)
22 * provide it themselves.
23 */
24 export class CurrentActor extends Domain.RequestContext<CurrentActor>()(
25 "Bank/CurrentActor",
26 Actor,
27 ) {}
28 ```
29
30 The key (`"Bank/CurrentActor"`) names the value when it travels with a request, so each request context needs its own.
31
32 ```typescript
33 // packages/domain/src/Actor.ts
34 import * as Schema from "effect/Schema";
35 import { CustomerId } from "./Customer/Customer.id.ts";
36
37 /**
38 * Who is acting. `Session` provides it as the `CurrentActor` of each
39 * request; events that need an audit trail record it as `by`.
40 */
41 export const Actor = Schema.Union([
42 Schema.TaggedStruct("Customer", { customerId: CustomerId }),
43 Schema.TaggedStruct("Agent", { agentId: Schema.String }),
44 Schema.TaggedStruct("System", { name: Schema.String }),
45 ]);
46 export type Actor = typeof Actor.Type;
47
48 export const customer = (customerId: string): Actor => ({
49 _tag: "Customer",
50 customerId: CustomerId.make(customerId),
51 });
52 export const agent = (agentId: string): Actor => ({ _tag: "Agent", agentId });
53 export const system = (name: string): Actor => ({ _tag: "System", name });
54 ```
55
56 ## Authenticate with middleware
57
58 `Session` is middleware that provides `CurrentActor`. Browsers send a session cookie; scripts and tests send an `Authorization` header.
59
60 ```typescript
61 // packages/domain/src/Session.middleware.ts
62 import * as Headers from "effect/http/Headers";
63 import * as RpcMiddleware from "effect/rpc/RpcMiddleware";
64 import * as Schema from "effect/Schema";
65 import { CurrentActor } from "./CurrentActor.context.ts";
66
67 /** The request has no session. */
68 export class Unauthorized extends Schema.TaggedError<Unauthorized>()("Unauthorized", {}) {}
69
70 /** The cookie that carries a customer's session in a browser. */
71 export const SESSION_COOKIE = "bank_session";
72
73 /**
74 * Authenticates a request, from a customer or a support agent, and provides
75 * who is making it as the {@link CurrentActor}. Authorization is up to each
76 * command's `decide` and each view's `validate`.
77 *
78 * Browsers authenticate with the session cookie, which also reaches live
79 * reads: a WebSocket upgrade carries cookies, never a header a client sets.
80 * Other clients (tests, support tooling) send `Authorization` instead.
81 */
82 export class Session extends RpcMiddleware.Service<Session, { provides: CurrentActor }>()(
83 "Bank/Session",
84 { error: Unauthorized },
85 ) {}
86
87 /** Client side, for clients that are not browsers: send this token with every call. */
88 export const sessionClient = (token: string) =>
89 RpcMiddleware.layerClient(Session, ({ request, next }) =>
90 next({ ...request, headers: Headers.set(request.headers, "authorization", `Bearer ${token}`) }),
91 );
92 ```
93
94 The Worker that serves the Api provides `SessionLive`. A client that isn't a browser adds `sessionClient` to attach its header.
95
96 ## Guard commands and views
97
98 List the middleware on each command and view that needs it. Middleware runs in order, and what it provides is what `decide` and `validate` may read.
99
100 ```typescript
101 // packages/domain/src/Account/SetNickname.command.ts
102 import * as Domain from "@alchemy.run/domain";
103 import * as Schema from "effect/Schema";
104 import { Session } from "../Session.middleware.ts";
105 import { AccountId } from "./Account.id.ts";
106 import { NotOwner } from "./NotOwner.rejection.ts";
107
108 export class NicknameSet extends Domain.Event("NicknameSet", { nickname: Schema.String }) {}
109
110 export class SetNickname extends Domain.Command("SetNickname", {
111 target: AccountId,
112 middleware: [Session],
113 input: { nickname: Schema.String },
114 events: [NicknameSet],
115 rejects: [NotOwner],
116 }) {}
117 ```
118
119 `decide` then checks the actor against the account. See [Aggregate](/domain/aggregate#decide-each-command).
120
121 ## Sign browsers in with a cookie
122
123 `sessionRoute` sets the session cookie. `HttpOnly` keeps it from scripts, and `SameSite=Strict` keeps it off requests from other sites, WebSocket upgrades included. The Worker sends `/api/session` to it.
124
125 Cookies only work when the app and the Api share an origin. The app's Worker serves the page and forwards `/api` to the bank.
126
127 ```typescript
128 // packages/web/src/worker.ts
129 interface Fetcher {
130 fetch(request: Request): Promise<Response>;
131 }
132
133 /**
134 * The app's Worker: the client build, plus `/api` forwarded to the bank over
135 * a service binding. One origin for both, so the session cookie is
136 * first-party and reaches every call and every live read's WebSocket.
137 */
138 export default {
139 fetch(request: Request, env: { readonly ASSETS: Fetcher; readonly BANK: Fetcher }) {
140 const { pathname } = new URL(request.url);
141 return pathname.startsWith("/api") ? env.BANK.fetch(request) : env.ASSETS.fetch(request);
142 },
143 };
144 ```
145
146 ```typescript
147 // alchemy.run.ts
148 import BankWorker from "@bank/server/BankWorker";
149 import * as Alchemy from "alchemy";
150 import * as Axiom from "@alchemy.run/axiom";
151 import * as Cloudflare from "@alchemy.run/cloudflare";
152 import * as Stripe from "@alchemy.run/stripe";
153 import * as Effect from "effect/Effect";
154 import * as Layer from "effect/Layer";
155
156 export default Alchemy.Stack(
157 "CloudflareDomainExample",
158 {
159 providers: Layer.mergeAll(Cloudflare.providers(), Stripe.providers(), Axiom.providers()),
160 state: Alchemy.localState(),
161 },
162 Effect.gen(function* () {
163 const bank = yield* BankWorker;
164 // The foldkit app, built with Vite. Its Worker serves the build and
165 // forwards /api to the bank, so the app and the Api share one origin.
166 const app = yield* Cloudflare.Website.Foldkit("BankApp", {
167 rootDir: "packages/web",
168 main: "src/worker.ts",
169 env: { BANK: bank },
170 assets: { runWorkerFirst: ["/api", "/api/*"] },
171 });
172 return { url: bank.url.as<string>(), app: app.url.as<string>() };
173 }),
174 );
175 ```
176
177 `env: { BANK: bank }` gives the app's Worker a binding to the bank, and `runWorkerFirst` sends `/api` through it.
178
179 ## Sign the session
180
181 ```typescript
182 // packages/server/src/Session.ts
183 import { Actor, customer } from "@bank/domain/Actor";
184 import { CurrentActor } from "@bank/domain/CurrentActor.context";
185 import { CustomerId } from "@bank/domain/Customer/Customer.id";
186 import { SESSION_COOKIE, Session, Unauthorized } from "@bank/domain/Session.middleware";
187 import * as Alchemy from "alchemy";
188 import * as Clock from "effect/Clock";
189 import * as Context from "effect/Context";
190 import * as Effect from "effect/Effect";
191 import * as Base64Url from "effect/encoding/Base64Url";
192 import * as Cookies from "effect/http/Cookies";
193 import * as Headers from "effect/http/Headers";
194 import { HttpServerRequest } from "effect/http/HttpServerRequest";
195 import * as HttpServerResponse from "effect/http/HttpServerResponse";
196 import * as Layer from "effect/Layer";
197 import * as Option from "effect/Option";
198 import * as Redacted from "effect/Redacted";
199 import * as Result from "effect/Result";
200 import * as Schema from "effect/Schema";
201
202 /** How long a session lasts. */
203 const SESSION_DAYS = 7;
204
205 /** The key that signs sessions: the same for every request to this stage. */
206 export class SessionKey extends Context.Service<
207 SessionKey,
208 Effect.Effect<Redacted.Redacted<string>>
209 >()("Bank/SessionKey") {}
210
211 /** A random key, made once when the stage is first deployed and kept in its state. */
212 export const SessionKeyLive = Layer.effect(
213 SessionKey,
214 Effect.gen(function* () {
215 const key = yield* Alchemy.Random("SessionKey");
216 return yield* key.text;
217 }),
218 );
219
220 const hmacKey = Effect.fn(function* () {
221 const secret = Redacted.value(yield* yield* SessionKey);
222 return yield* Effect.promise(() =>
223 crypto.subtle.importKey(
224 "raw",
225 new TextEncoder().encode(secret),
226 { name: "HMAC", hash: "SHA-256" },
227 false,
228 ["sign", "verify"],
229 ),
230 );
231 });
232
233 /** What a session token says: who, and until when. */
234 const Claims = Schema.fromJsonString(Schema.Struct({ actor: Actor, expires: Schema.Number }));
235
236 /** A session token for `actor`: its claims and their HMAC, so no one without the key can make one. */
237 export const signSession = Effect.fn(function* (actor: Actor) {
238 const expires = (yield* Clock.currentTimeMillis) + SESSION_DAYS * 24 * 60 * 60 * 1000;
239 // Encoding our own claims can't fail.
240 const json = yield* Schema.encodeEffect(Claims)({ actor, expires }).pipe(Effect.orDie);
241 const claims = Base64Url.encode(json);
242 const key = yield* hmacKey();
243 const mac = yield* Effect.promise(() =>
244 crypto.subtle.sign("HMAC", key, new TextEncoder().encode(claims)),
245 );
246 return `${claims}.${Base64Url.encode(new Uint8Array(mac))}`;
247 });
248
249 /** The actor a token was signed for, if its signature checks out and it hasn't expired. */
250 const verifySession = Effect.fn(function* (token: string) {
251 const [claims, mac, ...rest] = token.split(".");
252 if (!claims || !mac || rest.length > 0) return Option.none<Actor>();
253 const signature = Base64Url.decode(mac);
254 if (Result.isFailure(signature)) return Option.none<Actor>();
255 const key = yield* hmacKey();
256 // `verify` compares in constant time.
257 const valid = yield* Effect.promise(() =>
258 crypto.subtle.verify(
259 "HMAC",
260 key,
261 new Uint8Array(signature.success),
262 new TextEncoder().encode(claims),
263 ),
264 );
265 const json = Base64Url.decodeString(claims);
266 if (!valid || Result.isFailure(json)) return Option.none<Actor>();
267 const decoded = yield* Schema.decodeEffect(Claims)(json.success).pipe(Effect.option);
268 const now = yield* Clock.currentTimeMillis;
269 return Option.flatMap(decoded, (c) => (c.expires > now ? Option.some(c.actor) : Option.none()));
270 });
271
272 /** The token a request carries: its session cookie (browsers), or `Authorization: Bearer` (scripts). */
273 const tokenOf = (headers: Headers.Headers): Option.Option<string> =>
274 Option.orElse(
275 Option.flatMap(Headers.get(headers, "cookie"), (cookie) =>
276 Option.fromNullishOr(Cookies.parseHeader(cookie)[SESSION_COOKIE]),
277 ),
278 () =>
279 Option.flatMap(Headers.get(headers, "authorization"), (value) =>
280 value.startsWith("Bearer ") ? Option.some(value.slice("Bearer ".length)) : Option.none(),
281 ),
282 );
283
284 /** Who a request is from, if it carries a valid session. */
285 export const actorOf = Effect.fn(function* (headers: Headers.Headers) {
286 const token = tokenOf(headers);
287 return Option.isNone(token) ? Option.none<Actor>() : yield* verifySession(token.value);
288 });
289
290 /** The {@link Session} middleware: provides the request's actor, or fails with Unauthorized. */
291 export const SessionLive = Layer.effect(
292 Session,
293 Effect.gen(function* () {
294 const key = yield* SessionKey;
295 return (effect, { headers }) =>
296 actorOf(headers).pipe(
297 Effect.provideService(SessionKey, key),
298 Effect.flatMap(
299 Option.match({
300 onNone: () => Effect.fail(new Unauthorized()),
301 onSome: (actor) => Effect.provideService(effect, CurrentActor, actor),
302 }),
303 ),
304 );
305 }),
306 );
307
308 const SignIn = Schema.Struct({ customerId: CustomerId });
309
310 /**
311 * `POST /api/session` signs a customer in: it sets the signed session cookie,
312 * and returns the same token for scripts to send as `Authorization: Bearer`.
313 * `DELETE` signs them out. `HttpOnly` keeps the cookie from scripts, and
314 * `SameSite=Strict` keeps it off cross-site requests, WebSocket upgrades
315 * included. Demo only: anyone may sign in as any customer. Check a password,
316 * a magic link or a provider here before signing.
317 */
318 export const sessionRoute = Effect.gen(function* () {
319 const request = yield* HttpServerRequest;
320 const options = { httpOnly: true, secure: true, sameSite: "strict", path: "/" } as const;
321 if (request.method === "DELETE") {
322 return HttpServerResponse.empty({ status: 204 }).pipe(
323 HttpServerResponse.setCookieUnsafe(SESSION_COOKIE, "", { ...options, maxAge: 0 }),
324 );
325 }
326 if (request.method !== "POST") return HttpServerResponse.empty({ status: 405 });
327 const body = yield* request.json.pipe(
328 Effect.flatMap(Schema.decodeUnknownEffect(SignIn)),
329 Effect.option,
330 );
331 if (Option.isNone(body))
332 return HttpServerResponse.text("Expected { customerId }", { status: 400 });
333 const token = yield* signSession(customer(body.value.customerId));
334 return yield* HttpServerResponse.json({ token }).pipe(
335 Effect.map(
336 HttpServerResponse.setCookieUnsafe(SESSION_COOKIE, token, {
337 ...options,
338 maxAge: `${SESSION_DAYS} days`,
339 }),
340 ),
341 );
342 });
343 ```
344
345 A session token is who is signed in and until when, plus an HMAC of both made with the Worker's key. No one without the key can make one, and editing a token breaks its signature. `crypto.subtle.verify` checks it in constant time.
346
347 `SessionKeyLive` makes the key with `Alchemy.Random`: a random secret created on the first deploy, kept in the stage's state and bound to the Worker. Every request to the stage checks against the same key.
348
349 `sessionRoute` signs the token at sign-in and sets it as the cookie. It returns the same token for scripts to send as `Authorization: Bearer`. Here anyone may sign in as any customer: put your own check, such as a password or a magic link, before `signSession`.
350
351 ## Keep tokens out of URLs
352
353 A browser can't set headers on a WebSocket, and a URL ends up in logs. A live read authenticates with what its WebSocket upgrade carries: in a browser, the session cookie. Scripts and tests send `Authorization`, which they can set on their WebSockets too. See [Testing an Api](/domain/testing-apis#test-a-deployment).
354
355 ## Ask for a second factor
356
357 Add middleware for anything that needs more than a session. `WithdrawMoney` lists `[Session, MfaChallenge]`, so a withdrawal needs both.
358
359 ```typescript
360 // packages/domain/src/MfaChallenge.middleware.ts
361 import * as RpcMiddleware from "effect/rpc/RpcMiddleware";
362 import * as Schema from "effect/Schema";
363
364 /** The request lacks a valid second factor. */
365 export class MfaRequired extends Schema.TaggedError<MfaRequired>()("MfaRequired", {}) {}
366
367 /** Requires a second factor for sensitive operations. */
368 export class MfaChallenge extends RpcMiddleware.Service<MfaChallenge>()("Bank/MfaChallenge", {
369 error: MfaRequired,
370 }) {}
371 ```
372
373 ## Act without a session
374
375 A policy has no request, so it provides `CurrentActor` itself before sending a command that needs one, usually as the system. See [Policy](/domain/policy#react-to-a-view).
376
377 :::note
378 Guard reads with [Views as security boundaries](/domain/view-security).
379 :::