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

AuthSessions.ts

527 lines17.3 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 const setClientConnectionRow = SqlSchema.void({
335 Request: SetAuthSessionClientConnectionInput,
336 execute: ({ sessionId, surface, appVersion }) =>
337 sql`
338 UPDATE auth_sessions
339 SET client_surface = COALESCE(${surface}, client_surface),
340 client_app_version = COALESCE(${appVersion}, client_app_version)
341 WHERE session_id = ${sessionId}
342 AND revoked_at IS NULL
343 `,
344 });
345​
346 const revokeSessionRows = SqlSchema.findAll({
347 Request: RevokeAuthSessionInput,
348 Result: Schema.Struct({ sessionId: AuthSessionId }),
349 execute: ({ sessionId, revokedAt }) =>
350 sql`
351 UPDATE auth_sessions
352 SET revoked_at = ${revokedAt}
353 WHERE session_id = ${sessionId}
354 AND revoked_at IS NULL
355 RETURNING session_id AS "sessionId"
356 `,
357 });
358​
359 const revokeOtherSessionRows = SqlSchema.findAll({
360 Request: RevokeOtherAuthSessionsInput,
361 Result: Schema.Struct({ sessionId: AuthSessionId }),
362 execute: ({ currentSessionId, revokedAt }) =>
363 sql`
364 UPDATE auth_sessions
365 SET revoked_at = ${revokedAt}
366 WHERE session_id <> ${currentSessionId}
367 AND revoked_at IS NULL
368 RETURNING session_id AS "sessionId"
369 `,
370 });
371​
372 const create: AuthSessionRepository["Service"]["create"] = (input) =>
373 createSessionRow(input).pipe(
374 Effect.mapError(
375 toPersistenceSqlOrDecodeError(
376 "AuthSessionRepository.create:query",
377 "AuthSessionRepository.create:encodeRequest",
378 { sessionId: input.sessionId },
379 ),
380 ),
381 );
382​
383 const createReplacingActive: AuthSessionRepository["Service"]["createReplacingActive"] = (
384 input,
385 ) =>
386 sql
387 .withTransaction(
388 revokeActiveSessionsForReplacement(input).pipe(
389 Effect.flatMap((revokedRows) =>
390 createSessionRow(input.session).pipe(
391 Effect.as(revokedRows.map((row) => row.sessionId)),
392 ),
393 ),
394 ),
395 )
396 .pipe(
397 Effect.mapError(
398 toPersistenceSqlOrDecodeError(
399 "AuthSessionRepository.createReplacingActive:query",
400 "AuthSessionRepository.createReplacingActive:encodeRequest",
401 { sessionId: input.session.sessionId },
402 ),
403 ),
404 );
405​
406 const createIfAbsent: AuthSessionRepository["Service"]["createIfAbsent"] = (input) =>
407 createSessionRowIfAbsent(input).pipe(
408 Effect.mapError(
409 toPersistenceSqlOrDecodeError(
410 "AuthSessionRepository.createIfAbsent:query",
411 "AuthSessionRepository.createIfAbsent:encodeRequest",
412 { sessionId: input.sessionId },
413 ),
414 ),
415 );
416​
417 const getById: AuthSessionRepository["Service"]["getById"] = (input) =>
418 getSessionRowById(input).pipe(
419 Effect.mapError(
420 toPersistenceSqlOrDecodeError(
421 "AuthSessionRepository.getById:query",
422 "AuthSessionRepository.getById:decodeRow",
423 { sessionId: input.sessionId },
424 ),
425 ),
426 Effect.flatMap((rowOption) =>
427 Option.match(rowOption, {
428 onNone: () => Effect.succeedNone,
429 onSome: (row) =>
430 decodeAuthSessionDbRow(row).pipe(
431 Effect.mapError((cause) =>
432 PersistenceDecodeError.fromSchemaError(
433 "AuthSessionRepository.getById:decodeRow",
434 cause,
435 { sessionId: input.sessionId },
436 ),
437 ),
438 Effect.map((decodedRow) => Option.some(toAuthSessionRecord(decodedRow))),
439 ),
440 }),
441 ),
442 );
443​
444 const listActive: AuthSessionRepository["Service"]["listActive"] = (input) =>
445 listActiveSessionRows(input).pipe(
446 Effect.mapError(
447 toPersistenceSqlOrDecodeError(
448 "AuthSessionRepository.listActive:query",
449 "AuthSessionRepository.listActive:decodeRows",
450 ),
451 ),
452 Effect.flatMap((rows) =>
453 Effect.forEach(rows, (row) =>
454 decodeAuthSessionDbRow(row).pipe(
455 Effect.mapError((cause) =>
456 PersistenceDecodeError.fromSchemaError(
457 "AuthSessionRepository.listActive:decodeRows",
458 cause,
459 { sessionId: row.sessionId },
460 ),
461 ),
462 Effect.map(toAuthSessionRecord),
463 ),
464 ),
465 ),
466 );
467​
468 const revoke: AuthSessionRepository["Service"]["revoke"] = (input) =>
469 revokeSessionRows(input).pipe(
470 Effect.mapError(
471 toPersistenceSqlOrDecodeError(
472 "AuthSessionRepository.revoke:query",
473 "AuthSessionRepository.revoke:decodeRows",
474 { sessionId: input.sessionId },
475 ),
476 ),
477 Effect.map((rows) => rows.length > 0),
478 );
479​
480 const revokeAllExcept: AuthSessionRepository["Service"]["revokeAllExcept"] = (input) =>
481 revokeOtherSessionRows(input).pipe(
482 Effect.mapError(
483 toPersistenceSqlOrDecodeError(
484 "AuthSessionRepository.revokeAllExcept:query",
485 "AuthSessionRepository.revokeAllExcept:decodeRows",
486 { currentSessionId: input.currentSessionId },
487 ),
488 ),
489 Effect.map((rows) => rows.map((row) => row.sessionId)),
490 );
491​
492 const setLastConnectedAt: AuthSessionRepository["Service"]["setLastConnectedAt"] = (input) =>
493 setLastConnectedAtRow(input).pipe(
494 Effect.mapError(
495 toPersistenceSqlOrDecodeError(
496 "AuthSessionRepository.setLastConnectedAt:query",
497 "AuthSessionRepository.setLastConnectedAt:encodeRequest",
498 { sessionId: input.sessionId },
499 ),
500 ),
501 );
502​
503 const setClientConnection: AuthSessionRepository["Service"]["setClientConnection"] = (input) =>
504 setClientConnectionRow(input).pipe(
505 Effect.mapError(
506 toPersistenceSqlOrDecodeError(
507 "AuthSessionRepository.setClientConnection:query",
508 "AuthSessionRepository.setClientConnection:encodeRequest",
509 { sessionId: input.sessionId },
510 ),
511 ),
512 );
513​
514 return {
515 create,
516 createReplacingActive,
517 createIfAbsent,
518 getById,
519 listActive,
520 revoke,
521 revokeAllExcept,
522 setLastConnectedAt,
523 setClientConnection,
524 } satisfies AuthSessionRepository["Service"];
525});
526​
527export const layer = Layer.effect(AuthSessionRepository, make);