Open History to see the last commit
1import { AuthSessionId, type AuthClientMetadata, type AuthClientSession } from "@t3tools/contracts";
2import { Clock, DateTime, Duration, Effect, Layer, PubSub, Ref, Schema, Stream } from "effect";
3import { Option } from "effect";
4
5import { AuthSessionRepositoryLive } from "../../persistence/Layers/AuthSessions.ts";
6import { AuthSessionRepository } from "../../persistence/Services/AuthSessions.ts";
7import { ServerSecretStore } from "../Services/ServerSecretStore.ts";
8import { SESSION_COOKIE_NAME } from "../utils.ts";
9import {
10 SessionCredentialError,
11 SessionCredentialService,
12 type IssuedSession,
13 type SessionCredentialChange,
14 type SessionCredentialServiceShape,
15 type VerifiedSession,
16} from "../Services/SessionCredentialService.ts";
17import {
18 base64UrlDecodeUtf8,
19 base64UrlEncode,
20 signPayload,
21 timingSafeEqualBase64Url,
22} from "../utils.ts";
23
24const SIGNING_SECRET_NAME = "server-signing-key";
25const DEFAULT_SESSION_TTL = Duration.days(30);
26const DEFAULT_WEBSOCKET_TOKEN_TTL = Duration.minutes(5);
27
28const SessionClaims = Schema.Struct({
29 v: Schema.Literal(1),
30 kind: Schema.Literal("session"),
31 sid: AuthSessionId,
32 sub: Schema.String,
33 role: Schema.Literals(["owner", "client"]),
34 method: Schema.Literals(["browser-session-cookie", "bearer-session-token"]),
35 iat: Schema.Number,
36 exp: Schema.Number,
37});
38type SessionClaims = typeof SessionClaims.Type;
39
40const WebSocketClaims = Schema.Struct({
41 v: Schema.Literal(1),
42 kind: Schema.Literal("websocket"),
43 sid: AuthSessionId,
44 iat: Schema.Number,
45 exp: Schema.Number,
46});
47type WebSocketClaims = typeof WebSocketClaims.Type;
48
49function createDefaultClientMetadata(): AuthClientMetadata {
50 return {
51 deviceType: "unknown",
52 };
53}
54
55function toClientMetadata(record: {
56 readonly label: string | null;
57 readonly ipAddress: string | null;
58 readonly userAgent: string | null;
59 readonly deviceType: AuthClientMetadata["deviceType"];
60 readonly os: string | null;
61 readonly browser: string | null;
62}): AuthClientMetadata {
63 return {
64 ...(record.label ? { label: record.label } : {}),
65 ...(record.ipAddress ? { ipAddress: record.ipAddress } : {}),
66 ...(record.userAgent ? { userAgent: record.userAgent } : {}),
67 deviceType: record.deviceType,
68 ...(record.os ? { os: record.os } : {}),
69 ...(record.browser ? { browser: record.browser } : {}),
70 };
71}
72
73function toAuthClientSession(input: Omit<AuthClientSession, "current">): AuthClientSession {
74 return {
75 ...input,
76 current: false,
77 };
78}
79
80export const makeSessionCredentialService = Effect.gen(function* () {
81 const secretStore = yield* ServerSecretStore;
82 const authSessions = yield* AuthSessionRepository;
83 const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
84 const connectedSessionsRef = yield* Ref.make(new Map<string, number>());
85 const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
86
87 const toSessionCredentialError = (message: string) => (cause: unknown) =>
88 new SessionCredentialError({
89 message,
90 cause,
91 });
92
93 const emitUpsert = (clientSession: AuthClientSession) =>
94 PubSub.publish(changesPubSub, {
95 type: "clientUpserted",
96 clientSession,
97 }).pipe(Effect.asVoid);
98
99 const emitRemoved = (sessionId: AuthSessionId) =>
100 PubSub.publish(changesPubSub, {
101 type: "clientRemoved",
102 sessionId,
103 }).pipe(Effect.asVoid);
104
105 const loadActiveSession = (sessionId: AuthSessionId) =>
106 Effect.gen(function* () {
107 const row = yield* authSessions.getById({ sessionId });
108 if (Option.isNone(row) || row.value.revokedAt !== null) {
109 return Option.none<AuthClientSession>();
110 }
111
112 const connectedSessions = yield* Ref.get(connectedSessionsRef);
113 return Option.some(
114 toAuthClientSession({
115 sessionId: row.value.sessionId,
116 subject: row.value.subject,
117 role: row.value.role,
118 method: row.value.method,
119 client: toClientMetadata(row.value.client),
120 issuedAt: row.value.issuedAt,
121 expiresAt: row.value.expiresAt,
122 lastConnectedAt: row.value.lastConnectedAt,
123 connected: connectedSessions.has(row.value.sessionId),
124 }),
125 );
126 });
127
128 const markConnected: SessionCredentialServiceShape["markConnected"] = (sessionId) =>
129 Ref.modify(connectedSessionsRef, (current) => {
130 const next = new Map(current);
131 const wasDisconnected = !next.has(sessionId);
132 next.set(sessionId, (next.get(sessionId) ?? 0) + 1);
133 return [wasDisconnected, next] as const;
134 }).pipe(
135 Effect.flatMap((wasDisconnected) =>
136 wasDisconnected
137 ? DateTime.now.pipe(
138 Effect.flatMap((lastConnectedAt) =>
139 authSessions.setLastConnectedAt({
140 sessionId,
141 lastConnectedAt,
142 }),
143 ),
144 )
145 : Effect.void,
146 ),
147 Effect.flatMap(() => loadActiveSession(sessionId)),
148 Effect.flatMap((session) =>
149 Option.isSome(session) ? emitUpsert(session.value) : Effect.void,
150 ),
151 Effect.catchCause((cause) =>
152 Effect.logError("Failed to publish connected-session auth update.").pipe(
153 Effect.annotateLogs({
154 sessionId,
155 cause,
156 }),
157 ),
158 ),
159 );
160
161 const markDisconnected: SessionCredentialServiceShape["markDisconnected"] = (sessionId) =>
162 Ref.update(connectedSessionsRef, (current) => {
163 const next = new Map(current);
164 const remaining = (next.get(sessionId) ?? 0) - 1;
165 if (remaining > 0) {
166 next.set(sessionId, remaining);
167 } else {
168 next.delete(sessionId);
169 }
170 return next;
171 }).pipe(
172 Effect.flatMap(() => loadActiveSession(sessionId)),
173 Effect.flatMap((session) =>
174 Option.isSome(session) ? emitUpsert(session.value) : Effect.void,
175 ),
176 Effect.catchCause((cause) =>
177 Effect.logError("Failed to publish disconnected-session auth update.").pipe(
178 Effect.annotateLogs({
179 sessionId,
180 cause,
181 }),
182 ),
183 ),
184 );
185
186 const issue: SessionCredentialServiceShape["issue"] = (input) =>
187 Effect.gen(function* () {
188 const sessionId = AuthSessionId.makeUnsafe(crypto.randomUUID());
189 const issuedAt = yield* DateTime.now;
190 const expiresAt = DateTime.add(issuedAt, {
191 milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
192 });
193 const claims: SessionClaims = {
194 v: 1,
195 kind: "session",
196 sid: sessionId,
197 sub: input?.subject ?? "browser",
198 role: input?.role ?? "client",
199 method: input?.method ?? "browser-session-cookie",
200 iat: issuedAt.epochMilliseconds,
201 exp: expiresAt.epochMilliseconds,
202 };
203 const encodedPayload = base64UrlEncode(JSON.stringify(claims));
204 const signature = signPayload(encodedPayload, signingSecret);
205 const client = input?.client ?? createDefaultClientMetadata();
206 yield* authSessions.create({
207 sessionId,
208 subject: claims.sub,
209 role: claims.role,
210 method: claims.method,
211 client: {
212 label: client.label ?? null,
213 ipAddress: client.ipAddress ?? null,
214 userAgent: client.userAgent ?? null,
215 deviceType: client.deviceType,
216 os: client.os ?? null,
217 browser: client.browser ?? null,
218 },
219 issuedAt,
220 expiresAt,
221 });
222 yield* emitUpsert(
223 toAuthClientSession({
224 sessionId,
225 subject: claims.sub,
226 role: claims.role,
227 method: claims.method,
228 client,
229 issuedAt,
230 expiresAt,
231 lastConnectedAt: null,
232 connected: false,
233 }),
234 );
235
236 return {
237 sessionId,
238 token: `${encodedPayload}.${signature}`,
239 method: claims.method,
240 client,
241 expiresAt: expiresAt,
242 role: claims.role,
243 } satisfies IssuedSession;
244 }).pipe(Effect.mapError(toSessionCredentialError("Failed to issue session credential.")));
245
246 const verify: SessionCredentialServiceShape["verify"] = (token) =>
247 Effect.gen(function* () {
248 const [encodedPayload, signature] = token.split(".");
249 if (!encodedPayload || !signature) {
250 return yield* new SessionCredentialError({
251 message: "Malformed session token.",
252 });
253 }
254
255 const expectedSignature = signPayload(encodedPayload, signingSecret);
256 if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
257 return yield* new SessionCredentialError({
258 message: "Invalid session token signature.",
259 });
260 }
261
262 const claims = yield* Effect.try({
263 try: () =>
264 Schema.decodeUnknownSync(SessionClaims)(JSON.parse(base64UrlDecodeUtf8(encodedPayload))),
265 catch: (cause) =>
266 new SessionCredentialError({
267 message: "Invalid session token payload.",
268 cause,
269 }),
270 });
271
272 const now = yield* Clock.currentTimeMillis;
273 if (claims.exp <= now) {
274 return yield* new SessionCredentialError({
275 message: "Session token expired.",
276 });
277 }
278
279 const row = yield* authSessions.getById({ sessionId: claims.sid });
280 if (Option.isNone(row)) {
281 return yield* new SessionCredentialError({
282 message: "Unknown session token.",
283 });
284 }
285 if (row.value.revokedAt !== null) {
286 return yield* new SessionCredentialError({
287 message: "Session token revoked.",
288 });
289 }
290
291 return {
292 sessionId: claims.sid,
293 token,
294 method: claims.method,
295 client: toClientMetadata(row.value.client),
296 expiresAt: DateTime.makeUnsafe(claims.exp),
297 subject: claims.sub,
298 role: claims.role,
299 } satisfies VerifiedSession;
300 }).pipe(
301 Effect.mapError((cause) =>
302 cause instanceof SessionCredentialError
303 ? cause
304 : new SessionCredentialError({
305 message: "Failed to verify session credential.",
306 cause,
307 }),
308 ),
309 );
310
311 const issueWebSocketToken: SessionCredentialServiceShape["issueWebSocketToken"] = (
312 sessionId,
313 input,
314 ) =>
315 Effect.gen(function* () {
316 const issuedAt = yield* DateTime.now;
317 const expiresAt = DateTime.add(issuedAt, {
318 milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
319 });
320 const claims: WebSocketClaims = {
321 v: 1,
322 kind: "websocket",
323 sid: sessionId,
324 iat: issuedAt.epochMilliseconds,
325 exp: expiresAt.epochMilliseconds,
326 };
327 const encodedPayload = base64UrlEncode(JSON.stringify(claims));
328 const signature = signPayload(encodedPayload, signingSecret);
329 return {
330 token: `${encodedPayload}.${signature}`,
331 expiresAt,
332 };
333 }).pipe(Effect.mapError(toSessionCredentialError("Failed to issue websocket token.")));
334
335 const verifyWebSocketToken: SessionCredentialServiceShape["verifyWebSocketToken"] = (token) =>
336 Effect.gen(function* () {
337 const [encodedPayload, signature] = token.split(".");
338 if (!encodedPayload || !signature) {
339 return yield* new SessionCredentialError({
340 message: "Malformed websocket token.",
341 });
342 }
343
344 const expectedSignature = signPayload(encodedPayload, signingSecret);
345 if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
346 return yield* new SessionCredentialError({
347 message: "Invalid websocket token signature.",
348 });
349 }
350
351 const claims = yield* Effect.try({
352 try: () =>
353 Schema.decodeUnknownSync(WebSocketClaims)(
354 JSON.parse(base64UrlDecodeUtf8(encodedPayload)),
355 ),
356 catch: (cause) =>
357 new SessionCredentialError({
358 message: "Invalid websocket token payload.",
359 cause,
360 }),
361 });
362
363 const now = yield* Clock.currentTimeMillis;
364 if (claims.exp <= now) {
365 return yield* new SessionCredentialError({
366 message: "Websocket token expired.",
367 });
368 }
369
370 const row = yield* authSessions.getById({ sessionId: claims.sid });
371 if (Option.isNone(row)) {
372 return yield* new SessionCredentialError({
373 message: "Unknown websocket session.",
374 });
375 }
376 if (row.value.expiresAt.epochMilliseconds <= now) {
377 return yield* new SessionCredentialError({
378 message: "Websocket session expired.",
379 });
380 }
381 if (row.value.revokedAt !== null) {
382 return yield* new SessionCredentialError({
383 message: "Websocket session revoked.",
384 });
385 }
386
387 return {
388 sessionId: row.value.sessionId,
389 token,
390 method: row.value.method,
391 client: toClientMetadata(row.value.client),
392 expiresAt: row.value.expiresAt,
393 subject: row.value.subject,
394 role: row.value.role,
395 } satisfies VerifiedSession;
396 }).pipe(
397 Effect.mapError((cause) =>
398 cause instanceof SessionCredentialError
399 ? cause
400 : new SessionCredentialError({
401 message: "Failed to verify websocket token.",
402 cause,
403 }),
404 ),
405 );
406
407 const listActive: SessionCredentialServiceShape["listActive"] = () =>
408 Effect.gen(function* () {
409 const now = yield* DateTime.now;
410 const connectedSessions = yield* Ref.get(connectedSessionsRef);
411 const rows = yield* authSessions.listActive({ now });
412
413 return rows.map((row) =>
414 toAuthClientSession({
415 sessionId: row.sessionId,
416 subject: row.subject,
417 role: row.role,
418 method: row.method,
419 client: toClientMetadata(row.client),
420 issuedAt: row.issuedAt,
421 expiresAt: row.expiresAt,
422 lastConnectedAt: row.lastConnectedAt,
423 connected: connectedSessions.has(row.sessionId),
424 }),
425 );
426 }).pipe(Effect.mapError(toSessionCredentialError("Failed to list active sessions.")));
427
428 const revoke: SessionCredentialServiceShape["revoke"] = (sessionId) =>
429 Effect.gen(function* () {
430 const revokedAt = yield* DateTime.now;
431 const revoked = yield* authSessions.revoke({
432 sessionId,
433 revokedAt,
434 });
435 if (revoked) {
436 yield* Ref.update(connectedSessionsRef, (current) => {
437 const next = new Map(current);
438 next.delete(sessionId);
439 return next;
440 });
441 yield* emitRemoved(sessionId);
442 }
443 return revoked;
444 }).pipe(Effect.mapError(toSessionCredentialError("Failed to revoke session.")));
445
446 const revokeAllExcept: SessionCredentialServiceShape["revokeAllExcept"] = (sessionId) =>
447 Effect.gen(function* () {
448 const revokedAt = yield* DateTime.now;
449 const revokedSessionIds = yield* authSessions.revokeAllExcept({
450 currentSessionId: sessionId,
451 revokedAt,
452 });
453 if (revokedSessionIds.length > 0) {
454 yield* Ref.update(connectedSessionsRef, (current) => {
455 const next = new Map(current);
456 for (const revokedSessionId of revokedSessionIds) {
457 next.delete(revokedSessionId);
458 }
459 return next;
460 });
461 yield* Effect.forEach(
462 revokedSessionIds,
463 (revokedSessionId) => emitRemoved(revokedSessionId),
464 {
465 concurrency: "unbounded",
466 discard: true,
467 },
468 );
469 }
470 return revokedSessionIds.length;
471 }).pipe(Effect.mapError(toSessionCredentialError("Failed to revoke other sessions.")));
472
473 return {
474 cookieName: SESSION_COOKIE_NAME,
475 issue,
476 verify,
477 issueWebSocketToken,
478 verifyWebSocketToken,
479 listActive,
480 get streamChanges() {
481 return Stream.fromPubSub(changesPubSub);
482 },
483 revoke,
484 revokeAllExcept,
485 markConnected,
486 markDisconnected,
487 } satisfies SessionCredentialServiceShape;
488});
489
490export const SessionCredentialServiceLive = Layer.effect(
491 SessionCredentialService,
492 makeSessionCredentialService,
493).pipe(Layer.provideMerge(AuthSessionRepositoryLive));