Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Option from "effect/Option";
5import * as Schema from "effect/Schema";
6import * as SqlClient from "effect/unstable/sql/SqlClient";
7import * as SqlSchema from "effect/unstable/sql/SqlSchema";
8
9import {
10 AuthClientMetadataDeviceType,
11 AuthEnvironmentScopes,
12 AuthSessionId,
13 ClientSurface,
14 ServerAuthSessionMethod,
15} from "@t3tools/contracts";
16
17import {
18 type AuthSessionRepositoryError,
19 PersistenceDecodeError,
20 type PersistenceErrorCorrelation,
21 PersistenceSqlError,
22} from "./Errors.ts";
23
24export const AuthSessionClientMetadataRecord = Schema.Struct({
25 label: Schema.NullOr(Schema.String),
26 ipAddress: Schema.NullOr(Schema.String),
27 userAgent: Schema.NullOr(Schema.String),
28 deviceType: AuthClientMetadataDeviceType,
29 os: Schema.NullOr(Schema.String),
30 browser: Schema.NullOr(Schema.String),
31});
32export type AuthSessionClientMetadataRecord = typeof AuthSessionClientMetadataRecord.Type;
33
34export const AuthSessionRecord = Schema.Struct({
35 sessionId: AuthSessionId,
36 subject: Schema.String,
37 scopes: AuthEnvironmentScopes,
38 method: ServerAuthSessionMethod,
39 client: AuthSessionClientMetadataRecord,
40 issuedAt: Schema.DateTimeUtcFromString,
41 expiresAt: Schema.DateTimeUtcFromString,
42 lastConnectedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
43 revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
44});
45export type AuthSessionRecord = typeof AuthSessionRecord.Type;
46
47export const CreateAuthSessionInput = Schema.Struct({
48 sessionId: AuthSessionId,
49 subject: Schema.String,
50 scopes: AuthEnvironmentScopes,
51 method: ServerAuthSessionMethod,
52 client: AuthSessionClientMetadataRecord,
53 issuedAt: Schema.DateTimeUtcFromString,
54 expiresAt: Schema.DateTimeUtcFromString,
55});
56export type CreateAuthSessionInput = typeof CreateAuthSessionInput.Type;
57
58export const CreateReplacingActiveAuthSessionInput = Schema.Struct({
59 session: CreateAuthSessionInput,
60 revokedAt: Schema.DateTimeUtcFromString,
61});
62export type CreateReplacingActiveAuthSessionInput =
63 typeof CreateReplacingActiveAuthSessionInput.Type;
64
65export const GetAuthSessionByIdInput = Schema.Struct({
66 sessionId: AuthSessionId,
67});
68export type GetAuthSessionByIdInput = typeof GetAuthSessionByIdInput.Type;
69
70export const ListActiveAuthSessionsInput = Schema.Struct({
71 now: Schema.DateTimeUtcFromString,
72 connectedSessionIds: Schema.optionalKey(Schema.Array(AuthSessionId)),
73});
74export type ListActiveAuthSessionsInput = typeof ListActiveAuthSessionsInput.Type;
75
76export const RevokeAuthSessionInput = Schema.Struct({
77 sessionId: AuthSessionId,
78 revokedAt: Schema.DateTimeUtcFromString,
79});
80export type RevokeAuthSessionInput = typeof RevokeAuthSessionInput.Type;
81
82export const RevokeOtherAuthSessionsInput = Schema.Struct({
83 currentSessionId: AuthSessionId,
84 revokedAt: Schema.DateTimeUtcFromString,
85});
86export type RevokeOtherAuthSessionsInput = typeof RevokeOtherAuthSessionsInput.Type;
87
88export const SetAuthSessionLastConnectedAtInput = Schema.Struct({
89 sessionId: AuthSessionId,
90 lastConnectedAt: Schema.DateTimeUtcFromString,
91});
92export type SetAuthSessionLastConnectedAtInput = typeof SetAuthSessionLastConnectedAtInput.Type;
93
94export const SetAuthSessionClientConnectionInput = Schema.Struct({
95 sessionId: AuthSessionId,
96 surface: Schema.NullOr(ClientSurface),
97 appVersion: Schema.NullOr(Schema.String),
98});
99export type SetAuthSessionClientConnectionInput = typeof SetAuthSessionClientConnectionInput.Type;
100
101export class AuthSessionRepository extends Context.Service<
102 AuthSessionRepository,
103 {
104 readonly create: (
105 input: CreateAuthSessionInput,
106 ) => Effect.Effect<void, AuthSessionRepositoryError>;
107 readonly createReplacingActive: (
108 input: CreateReplacingActiveAuthSessionInput,
109 ) => Effect.Effect<ReadonlyArray<AuthSessionId>, AuthSessionRepositoryError>;
110 readonly getById: (
111 input: GetAuthSessionByIdInput,
112 ) => Effect.Effect<Option.Option<AuthSessionRecord>, AuthSessionRepositoryError>;
113 readonly listActive: (
114 input: ListActiveAuthSessionsInput,
115 ) => Effect.Effect<ReadonlyArray<AuthSessionRecord>, AuthSessionRepositoryError>;
116 readonly revoke: (
117 input: RevokeAuthSessionInput,
118 ) => Effect.Effect<boolean, AuthSessionRepositoryError>;
119 readonly revokeAllExcept: (
120 input: RevokeOtherAuthSessionsInput,
121 ) => Effect.Effect<ReadonlyArray<AuthSessionId>, AuthSessionRepositoryError>;
122 readonly setLastConnectedAt: (
123 input: SetAuthSessionLastConnectedAtInput,
124 ) => Effect.Effect<void, AuthSessionRepositoryError>;
125 readonly setClientConnection: (
126 input: SetAuthSessionClientConnectionInput,
127 ) => Effect.Effect<void, AuthSessionRepositoryError>;
128 }
129>()("t3/persistence/AuthSessions/AuthSessionRepository") {}
130
131const AuthSessionDbRow = Schema.Struct({
132 sessionId: AuthSessionId,
133 subject: Schema.String,
134 scopes: Schema.fromJsonString(AuthEnvironmentScopes),
135 method: ServerAuthSessionMethod,
136 clientLabel: Schema.NullOr(Schema.String),
137 clientIpAddress: Schema.NullOr(Schema.String),
138 clientUserAgent: Schema.NullOr(Schema.String),
139 clientDeviceType: Schema.Literals(["desktop", "mobile", "tablet", "bot", "unknown"]),
140 clientOs: Schema.NullOr(Schema.String),
141 clientBrowser: Schema.NullOr(Schema.String),
142 issuedAt: Schema.DateTimeUtcFromString,
143 expiresAt: Schema.DateTimeUtcFromString,
144 lastConnectedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
145 revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
146});
147
148const AuthSessionRawDbRow = Schema.Struct({
149 sessionId: Schema.String,
150 subject: Schema.Unknown,
151 scopes: Schema.Unknown,
152 method: Schema.Unknown,
153 clientLabel: Schema.Unknown,
154 clientIpAddress: Schema.Unknown,
155 clientUserAgent: Schema.Unknown,
156 clientDeviceType: Schema.Unknown,
157 clientOs: Schema.Unknown,
158 clientBrowser: Schema.Unknown,
159 issuedAt: Schema.Unknown,
160 expiresAt: Schema.Unknown,
161 lastConnectedAt: Schema.Unknown,
162 revokedAt: Schema.Unknown,
163});
164
165const decodeAuthSessionDbRow = Schema.decodeUnknownEffect(AuthSessionDbRow);
166
167function toAuthSessionRecord(row: typeof AuthSessionDbRow.Type): AuthSessionRecord {
168 return {
169 sessionId: row.sessionId,
170 subject: row.subject,
171 scopes: row.scopes,
172 method: row.method,
173 client: {
174 label: row.clientLabel,
175 ipAddress: row.clientIpAddress,
176 userAgent: row.clientUserAgent,
177 deviceType: row.clientDeviceType,
178 os: row.clientOs,
179 browser: row.clientBrowser,
180 },
181 issuedAt: row.issuedAt,
182 expiresAt: row.expiresAt,
183 lastConnectedAt: row.lastConnectedAt,
184 revokedAt: row.revokedAt,
185 };
186}
187
188function toPersistenceSqlOrDecodeError(
189 sqlOperation: string,
190 decodeOperation: string,
191 correlation?: PersistenceErrorCorrelation,
192) {
193 return (cause: unknown): AuthSessionRepositoryError =>
194 Schema.isSchemaError(cause)
195 ? PersistenceDecodeError.fromSchemaError(decodeOperation, cause, correlation)
196 : new PersistenceSqlError({
197 operation: sqlOperation,
198 ...(correlation === undefined ? {} : { correlation }),
199 cause,
200 });
201}
202
203/** @public Service construction is part of the canonical Effect module API. */
204export const make = Effect.gen(function* () {
205 const sql = yield* SqlClient.SqlClient;
206
207 const createSessionRow = SqlSchema.void({
208 Request: CreateAuthSessionInput,
209 execute: (input) =>
210 sql`
211 INSERT INTO auth_sessions (
212 session_id,
213 subject,
214 scopes,
215 method,
216 client_label,
217 client_ip_address,
218 client_user_agent,
219 client_device_type,
220 client_os,
221 client_browser,
222 issued_at,
223 expires_at,
224 revoked_at
225 )
226 VALUES (
227 ${input.sessionId},
228 ${input.subject},
229 ${JSON.stringify(input.scopes)},
230 ${input.method},
231 ${input.client.label},
232 ${input.client.ipAddress},
233 ${input.client.userAgent},
234 ${input.client.deviceType},
235 ${input.client.os},
236 ${input.client.browser},
237 ${input.issuedAt},
238 ${input.expiresAt},
239 NULL
240 )
241 `,
242 });
243
244 const getSessionRowById = SqlSchema.findOneOption({
245 Request: GetAuthSessionByIdInput,
246 Result: AuthSessionRawDbRow,
247 execute: ({ sessionId }) =>
248 sql`
249 SELECT
250 session_id AS "sessionId",
251 subject AS "subject",
252 scopes AS "scopes",
253 method AS "method",
254 client_label AS "clientLabel",
255 client_ip_address AS "clientIpAddress",
256 client_user_agent AS "clientUserAgent",
257 client_device_type AS "clientDeviceType",
258 client_os AS "clientOs",
259 client_browser AS "clientBrowser",
260 issued_at AS "issuedAt",
261 expires_at AS "expiresAt",
262 last_connected_at AS "lastConnectedAt",
263 revoked_at AS "revokedAt"
264 FROM auth_sessions
265 WHERE session_id = ${sessionId}
266 `,
267 });
268
269 const revokeActiveSessionsForReplacement = SqlSchema.findAll({
270 Request: CreateReplacingActiveAuthSessionInput,
271 Result: Schema.Struct({ sessionId: AuthSessionId }),
272 execute: ({ session, revokedAt }) =>
273 sql`
274 UPDATE auth_sessions
275 SET revoked_at = ${revokedAt}
276 WHERE subject = ${session.subject}
277 AND method = ${session.method}
278 AND revoked_at IS NULL
279 AND expires_at > ${revokedAt}
280 RETURNING session_id AS "sessionId"
281 `,
282 });
283
284 const listActiveSessionRows = SqlSchema.findAll({
285 Request: ListActiveAuthSessionsInput,
286 Result: AuthSessionRawDbRow,
287 execute: ({ now, connectedSessionIds = [] }) =>
288 sql`
289 SELECT
290 session_id AS "sessionId",
291 subject AS "subject",
292 scopes AS "scopes",
293 method AS "method",
294 client_label AS "clientLabel",
295 client_ip_address AS "clientIpAddress",
296 client_user_agent AS "clientUserAgent",
297 client_device_type AS "clientDeviceType",
298 client_os AS "clientOs",
299 client_browser AS "clientBrowser",
300 issued_at AS "issuedAt",
301 expires_at AS "expiresAt",
302 last_connected_at AS "lastConnectedAt",
303 revoked_at AS "revokedAt"
304 FROM auth_sessions
305 WHERE revoked_at IS NULL
306 AND (expires_at > ${now} OR ${sql.in("session_id", connectedSessionIds)})
307 ORDER BY issued_at DESC, session_id DESC
308 `,
309 });
310
311 const setLastConnectedAtRow = SqlSchema.void({
312 Request: SetAuthSessionLastConnectedAtInput,
313 execute: ({ sessionId, lastConnectedAt }) =>
314 sql`
315 UPDATE auth_sessions
316 SET last_connected_at = ${lastConnectedAt}
317 WHERE session_id = ${sessionId}
318 AND revoked_at IS NULL
319 `,
320 });
321
322 // COALESCE keeps the previous value when a client reports only one field, so
323 // a partial report never nulls out data a fuller client stored earlier.
324 const setClientConnectionRow = SqlSchema.void({
325 Request: SetAuthSessionClientConnectionInput,
326 execute: ({ sessionId, surface, appVersion }) =>
327 sql`
328 UPDATE auth_sessions
329 SET client_surface = COALESCE(${surface}, client_surface),
330 client_app_version = COALESCE(${appVersion}, client_app_version)
331 WHERE session_id = ${sessionId}
332 AND revoked_at IS NULL
333 `,
334 });
335
336 const revokeSessionRows = SqlSchema.findAll({
337 Request: RevokeAuthSessionInput,
338 Result: Schema.Struct({ sessionId: AuthSessionId }),
339 execute: ({ sessionId, revokedAt }) =>
340 sql`
341 UPDATE auth_sessions
342 SET revoked_at = ${revokedAt}
343 WHERE session_id = ${sessionId}
344 AND revoked_at IS NULL
345 RETURNING session_id AS "sessionId"
346 `,
347 });
348
349 const revokeOtherSessionRows = SqlSchema.findAll({
350 Request: RevokeOtherAuthSessionsInput,
351 Result: Schema.Struct({ sessionId: AuthSessionId }),
352 execute: ({ currentSessionId, revokedAt }) =>
353 sql`
354 UPDATE auth_sessions
355 SET revoked_at = ${revokedAt}
356 WHERE session_id <> ${currentSessionId}
357 AND revoked_at IS NULL
358 RETURNING session_id AS "sessionId"
359 `,
360 });
361
362 const create: AuthSessionRepository["Service"]["create"] = (input) =>
363 createSessionRow(input).pipe(
364 Effect.mapError(
365 toPersistenceSqlOrDecodeError(
366 "AuthSessionRepository.create:query",
367 "AuthSessionRepository.create:encodeRequest",
368 { sessionId: input.sessionId },
369 ),
370 ),
371 );
372
373 const createReplacingActive: AuthSessionRepository["Service"]["createReplacingActive"] = (
374 input,
375 ) =>
376 sql
377 .withTransaction(
378 revokeActiveSessionsForReplacement(input).pipe(
379 Effect.flatMap((revokedRows) =>
380 createSessionRow(input.session).pipe(
381 Effect.as(revokedRows.map((row) => row.sessionId)),
382 ),
383 ),
384 ),
385 )
386 .pipe(
387 Effect.mapError(
388 toPersistenceSqlOrDecodeError(
389 "AuthSessionRepository.createReplacingActive:query",
390 "AuthSessionRepository.createReplacingActive:encodeRequest",
391 { sessionId: input.session.sessionId },
392 ),
393 ),
394 );
395
396 const getById: AuthSessionRepository["Service"]["getById"] = (input) =>
397 getSessionRowById(input).pipe(
398 Effect.mapError(
399 toPersistenceSqlOrDecodeError(
400 "AuthSessionRepository.getById:query",
401 "AuthSessionRepository.getById:decodeRow",
402 { sessionId: input.sessionId },
403 ),
404 ),
405 Effect.flatMap((rowOption) =>
406 Option.match(rowOption, {
407 onNone: () => Effect.succeed(Option.none()),
408 onSome: (row) =>
409 decodeAuthSessionDbRow(row).pipe(
410 Effect.mapError((cause) =>
411 PersistenceDecodeError.fromSchemaError(
412 "AuthSessionRepository.getById:decodeRow",
413 cause,
414 { sessionId: input.sessionId },
415 ),
416 ),
417 Effect.map((decodedRow) => Option.some(toAuthSessionRecord(decodedRow))),
418 ),
419 }),
420 ),
421 );
422
423 const listActive: AuthSessionRepository["Service"]["listActive"] = (input) =>
424 listActiveSessionRows(input).pipe(
425 Effect.mapError(
426 toPersistenceSqlOrDecodeError(
427 "AuthSessionRepository.listActive:query",
428 "AuthSessionRepository.listActive:decodeRows",
429 ),
430 ),
431 Effect.flatMap((rows) =>
432 Effect.forEach(rows, (row) =>
433 decodeAuthSessionDbRow(row).pipe(
434 Effect.mapError((cause) =>
435 PersistenceDecodeError.fromSchemaError(
436 "AuthSessionRepository.listActive:decodeRows",
437 cause,
438 { sessionId: row.sessionId },
439 ),
440 ),
441 Effect.map(toAuthSessionRecord),
442 ),
443 ),
444 ),
445 );
446
447 const revoke: AuthSessionRepository["Service"]["revoke"] = (input) =>
448 revokeSessionRows(input).pipe(
449 Effect.mapError(
450 toPersistenceSqlOrDecodeError(
451 "AuthSessionRepository.revoke:query",
452 "AuthSessionRepository.revoke:decodeRows",
453 { sessionId: input.sessionId },
454 ),
455 ),
456 Effect.map((rows) => rows.length > 0),
457 );
458
459 const revokeAllExcept: AuthSessionRepository["Service"]["revokeAllExcept"] = (input) =>
460 revokeOtherSessionRows(input).pipe(
461 Effect.mapError(
462 toPersistenceSqlOrDecodeError(
463 "AuthSessionRepository.revokeAllExcept:query",
464 "AuthSessionRepository.revokeAllExcept:decodeRows",
465 { currentSessionId: input.currentSessionId },
466 ),
467 ),
468 Effect.map((rows) => rows.map((row) => row.sessionId)),
469 );
470
471 const setLastConnectedAt: AuthSessionRepository["Service"]["setLastConnectedAt"] = (input) =>
472 setLastConnectedAtRow(input).pipe(
473 Effect.mapError(
474 toPersistenceSqlOrDecodeError(
475 "AuthSessionRepository.setLastConnectedAt:query",
476 "AuthSessionRepository.setLastConnectedAt:encodeRequest",
477 { sessionId: input.sessionId },
478 ),
479 ),
480 );
481
482 const setClientConnection: AuthSessionRepository["Service"]["setClientConnection"] = (input) =>
483 setClientConnectionRow(input).pipe(
484 Effect.mapError(
485 toPersistenceSqlOrDecodeError(
486 "AuthSessionRepository.setClientConnection:query",
487 "AuthSessionRepository.setClientConnection:encodeRequest",
488 { sessionId: input.sessionId },
489 ),
490 ),
491 );
492
493 return {
494 create,
495 createReplacingActive,
496 getById,
497 listActive,
498 revoke,
499 revokeAllExcept,
500 setLastConnectedAt,
501 setClientConnection,
502 } satisfies AuthSessionRepository["Service"];
503});
504
505export const layer = Layer.effect(AuthSessionRepository, make);