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