Open History to see the last commit
1import {
2 AuthSessionId,
3 AuthStandardClientScopes,
4 AuthEnvironmentScopes,
5 type AuthClientMetadata,
6 type AuthClientSession,
7 type AuthEnvironmentScope,
8 type ServerAuthSessionMethod,
9} from "@t3tools/contracts";
10import * as Clock from "effect/Clock";
11import * as Context from "effect/Context";
12import * as Crypto from "effect/Crypto";
13import * as Data from "effect/Data";
14import * as DateTime from "effect/DateTime";
15import * as Duration from "effect/Duration";
16import * as Effect from "effect/Effect";
17import * as Layer from "effect/Layer";
18import * as PubSub from "effect/PubSub";
19import * as Ref from "effect/Ref";
20import * as Schema from "effect/Schema";
21import * as Stream from "effect/Stream";
22import * as Option from "effect/Option";
23
24import { ServerConfig } from "../config.ts";
25import { AuthSessionRepositoryLive } from "../persistence/Layers/AuthSessions.ts";
26import { AuthSessionRepository } from "../persistence/Services/AuthSessions.ts";
27import * as ServerSecretStore from "./ServerSecretStore.ts";
28import {
29 base64UrlDecodeUtf8,
30 base64UrlEncode,
31 resolveSessionCookieName,
32 signPayload,
33 timingSafeEqualBase64Url,
34} from "./utils.ts";
35
36export interface IssuedSession {
37 readonly sessionId: AuthSessionId;
38 readonly token: string;
39 readonly method: ServerAuthSessionMethod;
40 readonly client: AuthClientMetadata;
41 readonly expiresAt: DateTime.DateTime;
42 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
43 readonly proofKeyThumbprint?: string;
44}
45
46export interface VerifiedSession {
47 readonly sessionId: AuthSessionId;
48 readonly token: string;
49 readonly method: ServerAuthSessionMethod;
50 readonly client: AuthClientMetadata;
51 readonly expiresAt?: DateTime.DateTime;
52 readonly subject: string;
53 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
54 readonly proofKeyThumbprint?: string;
55}
56
57export type SessionCredentialChange =
58 | {
59 readonly type: "clientUpserted";
60 readonly clientSession: AuthClientSession;
61 }
62 | {
63 readonly type: "clientRemoved";
64 readonly sessionId: AuthSessionId;
65 };
66
67export class SessionCredentialInvalidError extends Data.TaggedError(
68 "SessionCredentialInvalidError",
69)<{
70 readonly message: string;
71 readonly cause?: unknown;
72}> {}
73
74export class SessionCredentialInternalError extends Data.TaggedError(
75 "SessionCredentialInternalError",
76)<{
77 readonly message: string;
78 readonly cause?: unknown;
79}> {}
80
81export type SessionCredentialError = SessionCredentialInvalidError | SessionCredentialInternalError;
82
83export interface SessionStoreShape {
84 readonly cookieName: string;
85 readonly issue: (input?: {
86 readonly ttl?: Duration.Duration;
87 readonly subject?: string;
88 readonly method?: ServerAuthSessionMethod;
89 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
90 readonly client?: AuthClientMetadata;
91 readonly proofKeyThumbprint?: string;
92 }) => Effect.Effect<IssuedSession, SessionCredentialInternalError>;
93 readonly verify: (token: string) => Effect.Effect<VerifiedSession, SessionCredentialError>;
94 readonly issueWebSocketToken: (
95 sessionId: AuthSessionId,
96 input?: {
97 readonly ttl?: Duration.Duration;
98 },
99 ) => Effect.Effect<
100 {
101 readonly token: string;
102 readonly expiresAt: DateTime.DateTime;
103 },
104 SessionCredentialInternalError
105 >;
106 readonly verifyWebSocketToken: (
107 token: string,
108 ) => Effect.Effect<VerifiedSession, SessionCredentialError>;
109 readonly listActive: () => Effect.Effect<
110 ReadonlyArray<AuthClientSession>,
111 SessionCredentialInternalError
112 >;
113 readonly streamChanges: Stream.Stream<SessionCredentialChange>;
114 readonly revoke: (
115 sessionId: AuthSessionId,
116 ) => Effect.Effect<boolean, SessionCredentialInternalError>;
117 readonly revokeAllExcept: (
118 sessionId: AuthSessionId,
119 ) => Effect.Effect<number, SessionCredentialInternalError>;
120 readonly markConnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
121 readonly markDisconnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
122}
123
124export class SessionStore extends Context.Service<SessionStore, SessionStoreShape>()(
125 "t3/auth/SessionStore",
126) {}
127
128const SIGNING_SECRET_NAME = "server-signing-key";
129const DEFAULT_SESSION_TTL = Duration.days(30);
130const DEFAULT_WEBSOCKET_TOKEN_TTL = Duration.minutes(5);
131
132const SessionClaims = Schema.Struct({
133 v: Schema.Literal(1),
134 kind: Schema.Literal("session"),
135 sid: AuthSessionId,
136 sub: Schema.String,
137 scopes: AuthEnvironmentScopes,
138 method: Schema.Literals(["browser-session-cookie", "bearer-access-token", "dpop-access-token"]),
139 jkt: Schema.optionalKey(Schema.String),
140 iat: Schema.Number,
141 exp: Schema.Number,
142});
143type SessionClaims = typeof SessionClaims.Type;
144
145const WebSocketClaims = Schema.Struct({
146 v: Schema.Literal(1),
147 kind: Schema.Literal("websocket"),
148 sid: AuthSessionId,
149 iat: Schema.Number,
150 exp: Schema.Number,
151});
152type WebSocketClaims = typeof WebSocketClaims.Type;
153
154const decodeSessionClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(SessionClaims));
155const decodeWebSocketClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(WebSocketClaims));
156
157function createDefaultClientMetadata(): AuthClientMetadata {
158 return {
159 deviceType: "unknown",
160 };
161}
162
163function toClientMetadata(record: {
164 readonly label: string | null;
165 readonly ipAddress: string | null;
166 readonly userAgent: string | null;
167 readonly deviceType: AuthClientMetadata["deviceType"];
168 readonly os: string | null;
169 readonly browser: string | null;
170}): AuthClientMetadata {
171 return {
172 ...(record.label ? { label: record.label } : {}),
173 ...(record.ipAddress ? { ipAddress: record.ipAddress } : {}),
174 ...(record.userAgent ? { userAgent: record.userAgent } : {}),
175 deviceType: record.deviceType,
176 ...(record.os ? { os: record.os } : {}),
177 ...(record.browser ? { browser: record.browser } : {}),
178 };
179}
180
181function toAuthClientSession(input: Omit<AuthClientSession, "current">): AuthClientSession {
182 return {
183 ...input,
184 current: false,
185 };
186}
187
188const toSessionCredentialInternalError = (message: string) => (cause: unknown) =>
189 new SessionCredentialInternalError({
190 message,
191 cause,
192 });
193
194export const make = Effect.fn("makeSessionStore")(function* () {
195 const crypto = yield* Crypto.Crypto;
196 const serverConfig = yield* ServerConfig;
197 const secretStore = yield* ServerSecretStore.ServerSecretStore;
198 const authSessions = yield* AuthSessionRepository;
199 const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
200 const connectedSessionsRef = yield* Ref.make(new Map<string, number>());
201 const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
202 const cookieName = resolveSessionCookieName({
203 mode: serverConfig.mode,
204 port: serverConfig.port,
205 });
206
207 const emitUpsert = (clientSession: AuthClientSession) =>
208 PubSub.publish(changesPubSub, {
209 type: "clientUpserted",
210 clientSession,
211 }).pipe(Effect.asVoid);
212
213 const emitRemoved = (sessionId: AuthSessionId) =>
214 PubSub.publish(changesPubSub, {
215 type: "clientRemoved",
216 sessionId,
217 }).pipe(Effect.asVoid);
218
219 const loadActiveSession = (sessionId: AuthSessionId) =>
220 Effect.gen(function* () {
221 const row = yield* authSessions.getById({ sessionId });
222 if (Option.isNone(row) || row.value.revokedAt !== null) {
223 return Option.none<AuthClientSession>();
224 }
225
226 const connectedSessions = yield* Ref.get(connectedSessionsRef);
227 return Option.some(
228 toAuthClientSession({
229 sessionId: row.value.sessionId,
230 subject: row.value.subject,
231 scopes: row.value.scopes,
232 method: row.value.method,
233 client: toClientMetadata(row.value.client),
234 issuedAt: row.value.issuedAt,
235 expiresAt: row.value.expiresAt,
236 lastConnectedAt: row.value.lastConnectedAt,
237 connected: connectedSessions.has(row.value.sessionId),
238 }),
239 );
240 });
241
242 const markConnected: SessionStoreShape["markConnected"] = (sessionId) =>
243 Ref.modify(connectedSessionsRef, (current) => {
244 const next = new Map(current);
245 const wasDisconnected = !next.has(sessionId);
246 next.set(sessionId, (next.get(sessionId) ?? 0) + 1);
247 return [wasDisconnected, next] as const;
248 }).pipe(
249 Effect.flatMap((wasDisconnected) =>
250 wasDisconnected
251 ? DateTime.now.pipe(
252 Effect.flatMap((lastConnectedAt) =>
253 authSessions.setLastConnectedAt({
254 sessionId,
255 lastConnectedAt,
256 }),
257 ),
258 )
259 : Effect.void,
260 ),
261 Effect.flatMap(() => loadActiveSession(sessionId)),
262 Effect.flatMap((session) =>
263 Option.isSome(session) ? emitUpsert(session.value) : Effect.void,
264 ),
265 Effect.catchCause((cause) =>
266 Effect.logError("Failed to publish connected-session auth update.").pipe(
267 Effect.annotateLogs({
268 sessionId,
269 cause,
270 }),
271 ),
272 ),
273 Effect.withSpan("SessionStore.markConnected"),
274 );
275
276 const markDisconnected: SessionStoreShape["markDisconnected"] = (sessionId) =>
277 Ref.update(connectedSessionsRef, (current) => {
278 const next = new Map(current);
279 const remaining = (next.get(sessionId) ?? 0) - 1;
280 if (remaining > 0) {
281 next.set(sessionId, remaining);
282 } else {
283 next.delete(sessionId);
284 }
285 return next;
286 }).pipe(
287 Effect.flatMap(() => loadActiveSession(sessionId)),
288 Effect.flatMap((session) =>
289 Option.isSome(session) ? emitUpsert(session.value) : Effect.void,
290 ),
291 Effect.catchCause((cause) =>
292 Effect.logError("Failed to publish disconnected-session auth update.").pipe(
293 Effect.annotateLogs({
294 sessionId,
295 cause,
296 }),
297 ),
298 ),
299 Effect.withSpan("SessionStore.markDisconnected"),
300 );
301
302 const encodeClaims = Schema.encodeEffect(Schema.fromJsonString(SessionClaims));
303 const issue: SessionStoreShape["issue"] = Effect.fn("SessionStore.issue")(
304 function* (input) {
305 const sessionId = AuthSessionId.make(yield* crypto.randomUUIDv4);
306 const issuedAt = yield* DateTime.now;
307 const expiresAt = DateTime.add(issuedAt, {
308 milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
309 });
310 const claims: SessionClaims = {
311 v: 1,
312 kind: "session",
313 sid: sessionId,
314 sub: input?.subject ?? "browser",
315 scopes: input?.scopes ?? AuthStandardClientScopes,
316 method: input?.method ?? "browser-session-cookie",
317 ...(input?.proofKeyThumbprint ? { jkt: input.proofKeyThumbprint } : {}),
318 iat: issuedAt.epochMilliseconds,
319 exp: expiresAt.epochMilliseconds,
320 };
321
322 const encodedPayload = yield* encodeClaims(claims).pipe(
323 Effect.map(base64UrlEncode),
324 Effect.mapError(
325 (cause) =>
326 new SessionCredentialInternalError({ message: "Failed to encode claims", cause }),
327 ),
328 );
329 const signature = signPayload(encodedPayload, signingSecret);
330 const client = input?.client ?? createDefaultClientMetadata();
331 yield* authSessions.create({
332 sessionId,
333 subject: claims.sub,
334 scopes: claims.scopes,
335 method: claims.method,
336 client: {
337 label: client.label ?? null,
338 ipAddress: client.ipAddress ?? null,
339 userAgent: client.userAgent ?? null,
340 deviceType: client.deviceType,
341 os: client.os ?? null,
342 browser: client.browser ?? null,
343 },
344 issuedAt,
345 expiresAt,
346 });
347 yield* emitUpsert(
348 toAuthClientSession({
349 sessionId,
350 subject: claims.sub,
351 scopes: claims.scopes,
352 method: claims.method,
353 client,
354 issuedAt,
355 expiresAt,
356 lastConnectedAt: null,
357 connected: false,
358 }),
359 );
360
361 return {
362 sessionId,
363 token: `${encodedPayload}.${signature}`,
364 method: claims.method,
365 client,
366 expiresAt: expiresAt,
367 scopes: claims.scopes,
368 ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
369 } satisfies IssuedSession;
370 },
371 Effect.mapError(toSessionCredentialInternalError("Failed to issue session credential.")),
372 );
373
374 const verify: SessionStoreShape["verify"] = Effect.fn("SessionStore.verify")(
375 function* (token) {
376 const [encodedPayload, signature] = token.split(".");
377 if (!encodedPayload || !signature) {
378 return yield* new SessionCredentialInvalidError({
379 message: "Malformed session token.",
380 });
381 }
382
383 const expectedSignature = signPayload(encodedPayload, signingSecret);
384 if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
385 return yield* new SessionCredentialInvalidError({
386 message: "Invalid session token signature.",
387 });
388 }
389
390 const claims = yield* decodeSessionClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
391 Effect.mapError(
392 (cause) =>
393 new SessionCredentialInvalidError({
394 message: "Invalid session token payload.",
395 cause,
396 }),
397 ),
398 );
399
400 const now = yield* Clock.currentTimeMillis;
401 if (claims.exp <= now) {
402 return yield* new SessionCredentialInvalidError({
403 message: "Session token expired.",
404 });
405 }
406
407 const row = yield* authSessions.getById({ sessionId: claims.sid });
408 if (Option.isNone(row)) {
409 return yield* new SessionCredentialInvalidError({
410 message: "Unknown session token.",
411 });
412 }
413 if (row.value.revokedAt !== null) {
414 return yield* new SessionCredentialInvalidError({
415 message: "Session token revoked.",
416 });
417 }
418
419 const expiresAt = DateTime.make(claims.exp);
420 if (Option.isNone(expiresAt)) {
421 return yield* new SessionCredentialInvalidError({
422 message: "Invalid `exp` claim",
423 });
424 }
425
426 return {
427 sessionId: claims.sid,
428 token,
429 method: claims.method,
430 client: toClientMetadata(row.value.client),
431 expiresAt: expiresAt.value,
432 subject: claims.sub,
433 scopes: claims.scopes,
434 ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
435 } satisfies VerifiedSession;
436 },
437 Effect.mapError((cause) =>
438 cause._tag === "SessionCredentialInvalidError"
439 ? cause
440 : new SessionCredentialInternalError({
441 message: "Failed to verify session credential.",
442 cause,
443 }),
444 ),
445 );
446
447 const encodeWsClaims = Schema.encodeEffect(Schema.fromJsonString(WebSocketClaims));
448 const issueWebSocketToken: SessionStoreShape["issueWebSocketToken"] = Effect.fn(
449 "SessionStore.issueWebSocketToken",
450 )(
451 function* (sessionId, input) {
452 const issuedAt = yield* DateTime.now;
453 const expiresAt = DateTime.add(issuedAt, {
454 milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
455 });
456 const claims: WebSocketClaims = {
457 v: 1,
458 kind: "websocket",
459 sid: sessionId,
460 iat: issuedAt.epochMilliseconds,
461 exp: expiresAt.epochMilliseconds,
462 };
463 const encodedPayload = yield* encodeWsClaims(claims).pipe(
464 Effect.map(base64UrlEncode),
465 Effect.mapError(
466 (cause) =>
467 new SessionCredentialInternalError({ message: "Failed to encode claims", cause }),
468 ),
469 );
470 const signature = signPayload(encodedPayload, signingSecret);
471 return {
472 token: `${encodedPayload}.${signature}`,
473 expiresAt,
474 };
475 },
476 Effect.mapError(toSessionCredentialInternalError("Failed to issue websocket token.")),
477 );
478
479 const verifyWebSocketToken: SessionStoreShape["verifyWebSocketToken"] = Effect.fn(
480 "SessionStore.verifyWebSocketToken",
481 )(
482 function* (token) {
483 const [encodedPayload, signature] = token.split(".");
484 if (!encodedPayload || !signature) {
485 return yield* new SessionCredentialInvalidError({
486 message: "Malformed websocket token.",
487 });
488 }
489
490 const expectedSignature = signPayload(encodedPayload, signingSecret);
491 if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
492 return yield* new SessionCredentialInvalidError({
493 message: "Invalid websocket token signature.",
494 });
495 }
496
497 const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
498 Effect.mapError(
499 (cause) =>
500 new SessionCredentialInvalidError({
501 message: "Invalid websocket token payload.",
502 cause,
503 }),
504 ),
505 );
506
507 const now = yield* Clock.currentTimeMillis;
508 if (claims.exp <= now) {
509 return yield* new SessionCredentialInvalidError({
510 message: "Websocket token expired.",
511 });
512 }
513
514 const row = yield* authSessions.getById({ sessionId: claims.sid });
515 if (Option.isNone(row)) {
516 return yield* new SessionCredentialInvalidError({
517 message: "Unknown websocket session.",
518 });
519 }
520 if (row.value.expiresAt.epochMilliseconds <= now) {
521 return yield* new SessionCredentialInvalidError({
522 message: "Websocket session expired.",
523 });
524 }
525 if (row.value.revokedAt !== null) {
526 return yield* new SessionCredentialInvalidError({
527 message: "Websocket session revoked.",
528 });
529 }
530
531 return {
532 sessionId: row.value.sessionId,
533 token,
534 method: row.value.method,
535 client: toClientMetadata(row.value.client),
536 expiresAt: row.value.expiresAt,
537 subject: row.value.subject,
538 scopes: row.value.scopes,
539 } satisfies VerifiedSession;
540 },
541 Effect.mapError((cause) =>
542 cause._tag === "SessionCredentialInvalidError"
543 ? cause
544 : new SessionCredentialInternalError({
545 message: "Failed to verify websocket token.",
546 cause,
547 }),
548 ),
549 );
550
551 const listActive: SessionStoreShape["listActive"] = Effect.fn("SessionStore.listActive")(
552 function* () {
553 const now = yield* DateTime.now;
554 const connectedSessions = yield* Ref.get(connectedSessionsRef);
555 const rows = yield* authSessions.listActive({ now });
556
557 return rows.map((row) =>
558 toAuthClientSession({
559 sessionId: row.sessionId,
560 subject: row.subject,
561 scopes: row.scopes,
562 method: row.method,
563 client: toClientMetadata(row.client),
564 issuedAt: row.issuedAt,
565 expiresAt: row.expiresAt,
566 lastConnectedAt: row.lastConnectedAt,
567 connected: connectedSessions.has(row.sessionId),
568 }),
569 );
570 },
571 Effect.mapError(toSessionCredentialInternalError("Failed to list active sessions.")),
572 );
573
574 const revoke: SessionStoreShape["revoke"] = Effect.fn("SessionStore.revoke")(
575 function* (sessionId) {
576 const revokedAt = yield* DateTime.now;
577 const revoked = yield* authSessions.revoke({
578 sessionId,
579 revokedAt,
580 });
581 if (revoked) {
582 yield* Ref.update(connectedSessionsRef, (current) => {
583 const next = new Map(current);
584 next.delete(sessionId);
585 return next;
586 });
587 yield* emitRemoved(sessionId);
588 }
589 return revoked;
590 },
591 Effect.mapError(toSessionCredentialInternalError("Failed to revoke session.")),
592 );
593
594 const revokeAllExcept: SessionStoreShape["revokeAllExcept"] = Effect.fn(
595 "SessionStore.revokeAllExcept",
596 )(
597 function* (sessionId) {
598 const revokedAt = yield* DateTime.now;
599 const revokedSessionIds = yield* authSessions.revokeAllExcept({
600 currentSessionId: sessionId,
601 revokedAt,
602 });
603 if (revokedSessionIds.length > 0) {
604 yield* Ref.update(connectedSessionsRef, (current) => {
605 const next = new Map(current);
606 for (const revokedSessionId of revokedSessionIds) {
607 next.delete(revokedSessionId);
608 }
609 return next;
610 });
611 yield* Effect.forEach(
612 revokedSessionIds,
613 (revokedSessionId) => emitRemoved(revokedSessionId),
614 {
615 concurrency: "unbounded",
616 discard: true,
617 },
618 );
619 }
620 return revokedSessionIds.length;
621 },
622 Effect.mapError(toSessionCredentialInternalError("Failed to revoke other sessions.")),
623 );
624
625 return {
626 cookieName,
627 issue,
628 verify,
629 issueWebSocketToken,
630 verifyWebSocketToken,
631 listActive,
632 get streamChanges() {
633 return Stream.fromPubSub(changesPubSub);
634 },
635 revoke,
636 revokeAllExcept,
637 markConnected,
638 markDisconnected,
639 } satisfies SessionStoreShape;
640});
641
642export const layer = Layer.effect(SessionStore, make()).pipe(
643 Layer.provideMerge(AuthSessionRepositoryLive),
644);