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

AuthSessions.ts

504 lines16.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/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 };
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 });
202​
203export const make = Effect.gen(function* () {
204 const sql = yield* SqlClient.SqlClient;
205​
206 const createSessionRow = SqlSchema.void({
207 Request: CreateAuthSessionInput,
208 execute: (input) =>
209 sql`
210 INSERT INTO auth_sessions (
211 session_id,
212 subject,
213 scopes,
214 method,
215 client_label,
216 client_ip_address,
217 client_user_agent,
218 client_device_type,
219 client_os,
220 client_browser,
221 issued_at,
222 expires_at,
223 revoked_at
224 )
225 VALUES (
226 ${input.sessionId},
227 ${input.subject},
228 ${JSON.stringify(input.scopes)},
229 ${input.method},
230 ${input.client.label},
231 ${input.client.ipAddress},
232 ${input.client.userAgent},
233 ${input.client.deviceType},
234 ${input.client.os},
235 ${input.client.browser},
236 ${input.issuedAt},
237 ${input.expiresAt},
238 NULL
239 )
240 `,
241 });
242​
243 const getSessionRowById = SqlSchema.findOneOption({
244 Request: GetAuthSessionByIdInput,
245 Result: AuthSessionRawDbRow,
246 execute: ({ sessionId }) =>
247 sql`
248 SELECT
249 session_id AS "sessionId",
250 subject AS "subject",
251 scopes AS "scopes",
252 method AS "method",
253 client_label AS "clientLabel",
254 client_ip_address AS "clientIpAddress",
255 client_user_agent AS "clientUserAgent",
256 client_device_type AS "clientDeviceType",
257 client_os AS "clientOs",
258 client_browser AS "clientBrowser",
259 issued_at AS "issuedAt",
260 expires_at AS "expiresAt",
261 last_connected_at AS "lastConnectedAt",
262 revoked_at AS "revokedAt"
263 FROM auth_sessions
264 WHERE session_id = ${sessionId}
265 `,
266 });
267​
268 const revokeActiveSessionsForReplacement = SqlSchema.findAll({
269 Request: CreateReplacingActiveAuthSessionInput,
270 Result: Schema.Struct({ sessionId: AuthSessionId }),
271 execute: ({ session, revokedAt }) =>
272 sql`
273 UPDATE auth_sessions
274 SET revoked_at = ${revokedAt}
275 WHERE subject = ${session.subject}
276 AND method = ${session.method}
277 AND revoked_at IS NULL
278 AND expires_at > ${revokedAt}
279 RETURNING session_id AS "sessionId"
280 `,
281 });
282​
283 const listActiveSessionRows = SqlSchema.findAll({
284 Request: ListActiveAuthSessionsInput,
285 Result: AuthSessionRawDbRow,
286 execute: ({ now, connectedSessionIds = [] }) =>
287 sql`
288 SELECT
289 session_id AS "sessionId",
290 subject AS "subject",
291 scopes AS "scopes",
292 method AS "method",
293 client_label AS "clientLabel",
294 client_ip_address AS "clientIpAddress",
295 client_user_agent AS "clientUserAgent",
296 client_device_type AS "clientDeviceType",
297 client_os AS "clientOs",
298 client_browser AS "clientBrowser",
299 issued_at AS "issuedAt",
300 expires_at AS "expiresAt",
301 last_connected_at AS "lastConnectedAt",
302 revoked_at AS "revokedAt"
303 FROM auth_sessions
304 WHERE revoked_at IS NULL
305 AND (expires_at > ${now} OR ${sql.in("session_id", connectedSessionIds)})
306 ORDER BY issued_at DESC, session_id DESC
307 `,
308 });
309​
310 const setLastConnectedAtRow = SqlSchema.void({
311 Request: SetAuthSessionLastConnectedAtInput,
312 execute: ({ sessionId, lastConnectedAt }) =>
313 sql`
314 UPDATE auth_sessions
315 SET last_connected_at = ${lastConnectedAt}
316 WHERE session_id = ${sessionId}
317 AND revoked_at IS NULL
318 `,
319 });
320​
321 // COALESCE keeps the previous value when a client reports only one field, so
322 // a partial report never nulls out data a fuller client stored earlier.
323 const setClientConnectionRow = SqlSchema.void({
324 Request: SetAuthSessionClientConnectionInput,
325 execute: ({ sessionId, surface, appVersion }) =>
326 sql`
327 UPDATE auth_sessions
328 SET client_surface = COALESCE(${surface}, client_surface),
329 client_app_version = COALESCE(${appVersion}, client_app_version)
330 WHERE session_id = ${sessionId}
331 AND revoked_at IS NULL
332 `,
333 });
334​
335 const revokeSessionRows = SqlSchema.findAll({
336 Request: RevokeAuthSessionInput,
337 Result: Schema.Struct({ sessionId: AuthSessionId }),
338 execute: ({ sessionId, revokedAt }) =>
339 sql`
340 UPDATE auth_sessions
341 SET revoked_at = ${revokedAt}
342 WHERE session_id = ${sessionId}
343 AND revoked_at IS NULL
344 RETURNING session_id AS "sessionId"
345 `,
346 });
347​
348 const revokeOtherSessionRows = SqlSchema.findAll({
349 Request: RevokeOtherAuthSessionsInput,
350 Result: Schema.Struct({ sessionId: AuthSessionId }),
351 execute: ({ currentSessionId, revokedAt }) =>
352 sql`
353 UPDATE auth_sessions
354 SET revoked_at = ${revokedAt}
355 WHERE session_id <> ${currentSessionId}
356 AND revoked_at IS NULL
357 RETURNING session_id AS "sessionId"
358 `,
359 });
360​
361 const create: AuthSessionRepository["Service"]["create"] = (input) =>
362 createSessionRow(input).pipe(
363 Effect.mapError(
364 toPersistenceSqlOrDecodeError(
365 "AuthSessionRepository.create:query",
366 "AuthSessionRepository.create:encodeRequest",
367 { sessionId: input.sessionId },
368 ),
369 ),
370 );
371​
372 const createReplacingActive: AuthSessionRepository["Service"]["createReplacingActive"] = (
373 input,
374 ) =>
375 sql
376 .withTransaction(
377 revokeActiveSessionsForReplacement(input).pipe(
378 Effect.flatMap((revokedRows) =>
379 createSessionRow(input.session).pipe(
380 Effect.as(revokedRows.map((row) => row.sessionId)),
381 ),
382 ),
383 ),
384 )
385 .pipe(
386 Effect.mapError(
387 toPersistenceSqlOrDecodeError(
388 "AuthSessionRepository.createReplacingActive:query",
389 "AuthSessionRepository.createReplacingActive:encodeRequest",
390 { sessionId: input.session.sessionId },
391 ),
392 ),
393 );
394​
395 const getById: AuthSessionRepository["Service"]["getById"] = (input) =>
396 getSessionRowById(input).pipe(
397 Effect.mapError(
398 toPersistenceSqlOrDecodeError(
399 "AuthSessionRepository.getById:query",
400 "AuthSessionRepository.getById:decodeRow",
401 { sessionId: input.sessionId },
402 ),
403 ),
404 Effect.flatMap((rowOption) =>
405 Option.match(rowOption, {
406 onNone: () => Effect.succeed(Option.none()),
407 onSome: (row) =>
408 decodeAuthSessionDbRow(row).pipe(
409 Effect.mapError((cause) =>
410 PersistenceDecodeError.fromSchemaError(
411 "AuthSessionRepository.getById:decodeRow",
412 cause,
413 { sessionId: input.sessionId },
414 ),
415 ),
416 Effect.map((decodedRow) => Option.some(toAuthSessionRecord(decodedRow))),
417 ),
418 }),
419 ),
420 );
421​
422 const listActive: AuthSessionRepository["Service"]["listActive"] = (input) =>
423 listActiveSessionRows(input).pipe(
424 Effect.mapError(
425 toPersistenceSqlOrDecodeError(
426 "AuthSessionRepository.listActive:query",
427 "AuthSessionRepository.listActive:decodeRows",
428 ),
429 ),
430 Effect.flatMap((rows) =>
431 Effect.forEach(rows, (row) =>
432 decodeAuthSessionDbRow(row).pipe(
433 Effect.mapError((cause) =>
434 PersistenceDecodeError.fromSchemaError(
435 "AuthSessionRepository.listActive:decodeRows",
436 cause,
437 { sessionId: row.sessionId },
438 ),
439 ),
440 Effect.map(toAuthSessionRecord),
441 ),
442 ),
443 ),
444 );
445​
446 const revoke: AuthSessionRepository["Service"]["revoke"] = (input) =>
447 revokeSessionRows(input).pipe(
448 Effect.mapError(
449 toPersistenceSqlOrDecodeError(
450 "AuthSessionRepository.revoke:query",
451 "AuthSessionRepository.revoke:decodeRows",
452 { sessionId: input.sessionId },
453 ),
454 ),
455 Effect.map((rows) => rows.length > 0),
456 );
457​
458 const revokeAllExcept: AuthSessionRepository["Service"]["revokeAllExcept"] = (input) =>
459 revokeOtherSessionRows(input).pipe(
460 Effect.mapError(
461 toPersistenceSqlOrDecodeError(
462 "AuthSessionRepository.revokeAllExcept:query",
463 "AuthSessionRepository.revokeAllExcept:decodeRows",
464 { currentSessionId: input.currentSessionId },
465 ),
466 ),
467 Effect.map((rows) => rows.map((row) => row.sessionId)),
468 );
469​
470 const setLastConnectedAt: AuthSessionRepository["Service"]["setLastConnectedAt"] = (input) =>
471 setLastConnectedAtRow(input).pipe(
472 Effect.mapError(
473 toPersistenceSqlOrDecodeError(
474 "AuthSessionRepository.setLastConnectedAt:query",
475 "AuthSessionRepository.setLastConnectedAt:encodeRequest",
476 { sessionId: input.sessionId },
477 ),
478 ),
479 );
480​
481 const setClientConnection: AuthSessionRepository["Service"]["setClientConnection"] = (input) =>
482 setClientConnectionRow(input).pipe(
483 Effect.mapError(
484 toPersistenceSqlOrDecodeError(
485 "AuthSessionRepository.setClientConnection:query",
486 "AuthSessionRepository.setClientConnection:encodeRequest",
487 { sessionId: input.sessionId },
488 ),
489 ),
490 );
491​
492 return {
493 create,
494 createReplacingActive,
495 getById,
496 listActive,
497 revoke,
498 revokeAllExcept,
499 setLastConnectedAt,
500 setClientConnection,
501 } satisfies AuthSessionRepository["Service"];
502});
503​
504export const layer = Layer.effect(AuthSessionRepository, make);