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 createIfAbsent: (
111 input: CreateAuthSessionInput,
112 ) => Effect.Effect<void, AuthSessionRepositoryError>;
113 readonly getById: (
114 input: GetAuthSessionByIdInput,
115 ) => Effect.Effect<Option.Option<AuthSessionRecord>, AuthSessionRepositoryError>;
116 readonly listActive: (
117 input: ListActiveAuthSessionsInput,
118 ) => Effect.Effect<ReadonlyArray<AuthSessionRecord>, AuthSessionRepositoryError>;
119 readonly revoke: (
120 input: RevokeAuthSessionInput,
121 ) => Effect.Effect<boolean, AuthSessionRepositoryError>;
122 readonly revokeAllExcept: (
123 input: RevokeOtherAuthSessionsInput,
124 ) => Effect.Effect<ReadonlyArray<AuthSessionId>, AuthSessionRepositoryError>;
125 readonly setLastConnectedAt: (
126 input: SetAuthSessionLastConnectedAtInput,
127 ) => Effect.Effect<void, AuthSessionRepositoryError>;
128 readonly setClientConnection: (
129 input: SetAuthSessionClientConnectionInput,
130 ) => Effect.Effect<void, AuthSessionRepositoryError>;
131 }
132>()("t3/persistence/AuthSessions/AuthSessionRepository") {}
133
134const AuthSessionDbRow = Schema.Struct({
135 sessionId: AuthSessionId,
136 subject: Schema.String,
137 scopes: Schema.fromJsonString(AuthEnvironmentScopes),
138 method: ServerAuthSessionMethod,
139 clientLabel: Schema.NullOr(Schema.String),
140 clientIpAddress: Schema.NullOr(Schema.String),
141 clientUserAgent: Schema.NullOr(Schema.String),
142 clientDeviceType: Schema.Literals(["desktop", "mobile", "tablet", "bot", "unknown"]),
143 clientOs: Schema.NullOr(Schema.String),
144 clientBrowser: Schema.NullOr(Schema.String),
145 issuedAt: Schema.DateTimeUtcFromString,
146 expiresAt: Schema.DateTimeUtcFromString,
147 lastConnectedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
148 revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
149});
150
151const AuthSessionRawDbRow = Schema.Struct({
152 sessionId: Schema.String,
153 subject: Schema.Unknown,
154 scopes: Schema.Unknown,
155 method: Schema.Unknown,
156 clientLabel: Schema.Unknown,
157 clientIpAddress: Schema.Unknown,
158 clientUserAgent: Schema.Unknown,
159 clientDeviceType: Schema.Unknown,
160 clientOs: Schema.Unknown,
161 clientBrowser: Schema.Unknown,
162 issuedAt: Schema.Unknown,
163 expiresAt: Schema.Unknown,
164 lastConnectedAt: Schema.Unknown,
165 revokedAt: Schema.Unknown,
166});
167
168const decodeAuthSessionDbRow = Schema.decodeUnknownEffect(AuthSessionDbRow);
169
170function toAuthSessionRecord(row: typeof AuthSessionDbRow.Type): AuthSessionRecord {
171 return {
172 sessionId: row.sessionId,
173 subject: row.subject,
174 scopes: row.scopes,
175 method: row.method,
176 client: {
177 label: row.clientLabel,
178 ipAddress: row.clientIpAddress,
179 userAgent: row.clientUserAgent,
180 deviceType: row.clientDeviceType,
181 os: row.clientOs,
182 browser: row.clientBrowser,
183 },
184 issuedAt: row.issuedAt,
185 expiresAt: row.expiresAt,
186 lastConnectedAt: row.lastConnectedAt,
187 revokedAt: row.revokedAt,
188 };
189}
190
191function toPersistenceSqlOrDecodeError(
192 sqlOperation: string,
193 decodeOperation: string,
194 correlation?: PersistenceErrorCorrelation,
195) {
196 return (cause: unknown): AuthSessionRepositoryError =>
197 Schema.isSchemaError(cause)
198 ? PersistenceDecodeError.fromSchemaError(decodeOperation, cause, correlation)
199 : new PersistenceSqlError({
200 operation: sqlOperation,
201 ...(correlation === undefined ? {} : { correlation }),
202 cause,
203 });
204}
205
206/** @public Service construction is part of the canonical Effect module API. */
207export const make = Effect.gen(function* () {
208 const sql = yield* SqlClient.SqlClient;
209
210 const insertSessionRow = (ignoreExisting: boolean) =>
211 SqlSchema.void({
212 Request: CreateAuthSessionInput,
213 execute: (input) =>
214 sql`
215 INSERT INTO auth_sessions (
216 session_id,
217 subject,
218 scopes,
219 method,
220 client_label,
221 client_ip_address,
222 client_user_agent,
223 client_device_type,
224 client_os,
225 client_browser,
226 issued_at,
227 expires_at,
228 revoked_at
229 )
230 VALUES (
231 ${input.sessionId},
232 ${input.subject},
233 ${JSON.stringify(input.scopes)},
234 ${input.method},
235 ${input.client.label},
236 ${input.client.ipAddress},
237 ${input.client.userAgent},
238 ${input.client.deviceType},
239 ${input.client.os},
240 ${input.client.browser},
241 ${input.issuedAt},
242 ${input.expiresAt},
243 NULL
244 )
245 ${ignoreExisting ? sql`ON CONFLICT(session_id) DO NOTHING` : sql``}
246 `,
247 });
248 const createSessionRow = insertSessionRow(false);
249 const createSessionRowIfAbsent = insertSessionRow(true);
250
251 const getSessionRowById = SqlSchema.findOneOption({
252 Request: GetAuthSessionByIdInput,
253 Result: AuthSessionRawDbRow,
254 execute: ({ sessionId }) =>
255 sql`
256 SELECT
257 session_id AS "sessionId",
258 subject AS "subject",
259 scopes AS "scopes",
260 method AS "method",
261 client_label AS "clientLabel",
262 client_ip_address AS "clientIpAddress",
263 client_user_agent AS "clientUserAgent",
264 client_device_type AS "clientDeviceType",
265 client_os AS "clientOs",
266 client_browser AS "clientBrowser",
267 issued_at AS "issuedAt",
268 expires_at AS "expiresAt",
269 last_connected_at AS "lastConnectedAt",
270 revoked_at AS "revokedAt"
271 FROM auth_sessions
272 WHERE session_id = ${sessionId}
273 `,
274 });
275
276 const revokeActiveSessionsForReplacement = SqlSchema.findAll({
277 Request: CreateReplacingActiveAuthSessionInput,
278 Result: Schema.Struct({ sessionId: AuthSessionId }),
279 execute: ({ session, revokedAt }) =>
280 sql`
281 UPDATE auth_sessions
282 SET revoked_at = ${revokedAt}
283 WHERE subject = ${session.subject}
284 AND method = ${session.method}
285 AND revoked_at IS NULL
286 AND expires_at > ${revokedAt}
287 RETURNING session_id AS "sessionId"
288 `,
289 });
290
291 const listActiveSessionRows = SqlSchema.findAll({
292 Request: ListActiveAuthSessionsInput,
293 Result: AuthSessionRawDbRow,
294 execute: ({ now, connectedSessionIds = [] }) =>
295 sql`
296 SELECT
297 session_id AS "sessionId",
298 subject AS "subject",
299 scopes AS "scopes",
300 method AS "method",
301 client_label AS "clientLabel",
302 client_ip_address AS "clientIpAddress",
303 client_user_agent AS "clientUserAgent",
304 client_device_type AS "clientDeviceType",
305 client_os AS "clientOs",
306 client_browser AS "clientBrowser",
307 issued_at AS "issuedAt",
308 expires_at AS "expiresAt",
309 last_connected_at AS "lastConnectedAt",
310 revoked_at AS "revokedAt"
311 FROM auth_sessions
312 WHERE revoked_at IS NULL
313 AND (expires_at > ${now} OR ${sql.in("session_id", connectedSessionIds)})
314 ORDER BY issued_at DESC, session_id DESC
315 `,
316 });
317
318 const setLastConnectedAtRow = SqlSchema.void({
319 Request: SetAuthSessionLastConnectedAtInput,
320 execute: ({ sessionId, lastConnectedAt }) =>
321 sql`
322 UPDATE auth_sessions
323 SET last_connected_at = ${lastConnectedAt}
324 WHERE session_id = ${sessionId}
325 AND revoked_at IS NULL
326 `,
327 });
328
329 // COALESCE keeps the previous value when a client reports only one field, so
330 // a partial report never nulls out data a fuller client stored earlier.
331 const setClientConnectionRow = SqlSchema.void({
332 Request: SetAuthSessionClientConnectionInput,
333 execute: ({ sessionId, surface, appVersion }) =>
334 sql`
335 UPDATE auth_sessions
336 SET client_surface = COALESCE(${surface}, client_surface),
337 client_app_version = COALESCE(${appVersion}, client_app_version)
338 WHERE session_id = ${sessionId}
339 AND revoked_at IS NULL
340 `,
341 });
342
343 const revokeSessionRows = SqlSchema.findAll({
344 Request: RevokeAuthSessionInput,
345 Result: Schema.Struct({ sessionId: AuthSessionId }),
346 execute: ({ sessionId, revokedAt }) =>
347 sql`
348 UPDATE auth_sessions
349 SET revoked_at = ${revokedAt}
350 WHERE session_id = ${sessionId}
351 AND revoked_at IS NULL
352 RETURNING session_id AS "sessionId"
353 `,
354 });
355
356 const revokeOtherSessionRows = SqlSchema.findAll({
357 Request: RevokeOtherAuthSessionsInput,
358 Result: Schema.Struct({ sessionId: AuthSessionId }),
359 execute: ({ currentSessionId, revokedAt }) =>
360 sql`
361 UPDATE auth_sessions
362 SET revoked_at = ${revokedAt}
363 WHERE session_id <> ${currentSessionId}
364 AND revoked_at IS NULL
365 RETURNING session_id AS "sessionId"
366 `,
367 });
368
369 const create: AuthSessionRepository["Service"]["create"] = (input) =>
370 createSessionRow(input).pipe(
371 Effect.mapError(
372 toPersistenceSqlOrDecodeError(
373 "AuthSessionRepository.create:query",
374 "AuthSessionRepository.create:encodeRequest",
375 { sessionId: input.sessionId },
376 ),
377 ),
378 );
379
380 const createReplacingActive: AuthSessionRepository["Service"]["createReplacingActive"] = (
381 input,
382 ) =>
383 sql
384 .withTransaction(
385 revokeActiveSessionsForReplacement(input).pipe(
386 Effect.flatMap((revokedRows) =>
387 createSessionRow(input.session).pipe(
388 Effect.as(revokedRows.map((row) => row.sessionId)),
389 ),
390 ),
391 ),
392 )
393 .pipe(
394 Effect.mapError(
395 toPersistenceSqlOrDecodeError(
396 "AuthSessionRepository.createReplacingActive:query",
397 "AuthSessionRepository.createReplacingActive:encodeRequest",
398 { sessionId: input.session.sessionId },
399 ),
400 ),
401 );
402
403 const createIfAbsent: AuthSessionRepository["Service"]["createIfAbsent"] = (input) =>
404 createSessionRowIfAbsent(input).pipe(
405 Effect.mapError(
406 toPersistenceSqlOrDecodeError(
407 "AuthSessionRepository.createIfAbsent:query",
408 "AuthSessionRepository.createIfAbsent:encodeRequest",
409 { sessionId: input.sessionId },
410 ),
411 ),
412 );
413
414 const getById: AuthSessionRepository["Service"]["getById"] = (input) =>
415 getSessionRowById(input).pipe(
416 Effect.mapError(
417 toPersistenceSqlOrDecodeError(
418 "AuthSessionRepository.getById:query",
419 "AuthSessionRepository.getById:decodeRow",
420 { sessionId: input.sessionId },
421 ),
422 ),
423 Effect.flatMap((rowOption) =>
424 Option.match(rowOption, {
425 onNone: () => Effect.succeed(Option.none()),
426 onSome: (row) =>
427 decodeAuthSessionDbRow(row).pipe(
428 Effect.mapError((cause) =>
429 PersistenceDecodeError.fromSchemaError(
430 "AuthSessionRepository.getById:decodeRow",
431 cause,
432 { sessionId: input.sessionId },
433 ),
434 ),
435 Effect.map((decodedRow) => Option.some(toAuthSessionRecord(decodedRow))),
436 ),
437 }),
438 ),
439 );
440
441 const listActive: AuthSessionRepository["Service"]["listActive"] = (input) =>
442 listActiveSessionRows(input).pipe(
443 Effect.mapError(
444 toPersistenceSqlOrDecodeError(
445 "AuthSessionRepository.listActive:query",
446 "AuthSessionRepository.listActive:decodeRows",
447 ),
448 ),
449 Effect.flatMap((rows) =>
450 Effect.forEach(rows, (row) =>
451 decodeAuthSessionDbRow(row).pipe(
452 Effect.mapError((cause) =>
453 PersistenceDecodeError.fromSchemaError(
454 "AuthSessionRepository.listActive:decodeRows",
455 cause,
456 { sessionId: row.sessionId },
457 ),
458 ),
459 Effect.map(toAuthSessionRecord),
460 ),
461 ),
462 ),
463 );
464
465 const revoke: AuthSessionRepository["Service"]["revoke"] = (input) =>
466 revokeSessionRows(input).pipe(
467 Effect.mapError(
468 toPersistenceSqlOrDecodeError(
469 "AuthSessionRepository.revoke:query",
470 "AuthSessionRepository.revoke:decodeRows",
471 { sessionId: input.sessionId },
472 ),
473 ),
474 Effect.map((rows) => rows.length > 0),
475 );
476
477 const revokeAllExcept: AuthSessionRepository["Service"]["revokeAllExcept"] = (input) =>
478 revokeOtherSessionRows(input).pipe(
479 Effect.mapError(
480 toPersistenceSqlOrDecodeError(
481 "AuthSessionRepository.revokeAllExcept:query",
482 "AuthSessionRepository.revokeAllExcept:decodeRows",
483 { currentSessionId: input.currentSessionId },
484 ),
485 ),
486 Effect.map((rows) => rows.map((row) => row.sessionId)),
487 );
488
489 const setLastConnectedAt: AuthSessionRepository["Service"]["setLastConnectedAt"] = (input) =>
490 setLastConnectedAtRow(input).pipe(
491 Effect.mapError(
492 toPersistenceSqlOrDecodeError(
493 "AuthSessionRepository.setLastConnectedAt:query",
494 "AuthSessionRepository.setLastConnectedAt:encodeRequest",
495 { sessionId: input.sessionId },
496 ),
497 ),
498 );
499
500 const setClientConnection: AuthSessionRepository["Service"]["setClientConnection"] = (input) =>
501 setClientConnectionRow(input).pipe(
502 Effect.mapError(
503 toPersistenceSqlOrDecodeError(
504 "AuthSessionRepository.setClientConnection:query",
505 "AuthSessionRepository.setClientConnection:encodeRequest",
506 { sessionId: input.sessionId },
507 ),
508 ),
509 );
510
511 return {
512 create,
513 createReplacingActive,
514 createIfAbsent,
515 getById,
516 listActive,
517 revoke,
518 revokeAllExcept,
519 setLastConnectedAt,
520 setClientConnection,
521 } satisfies AuthSessionRepository["Service"];
522});
523
524export const layer = Layer.effect(AuthSessionRepository, make);