Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AuthSessions.ts

529 lines17.5 KB

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