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