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

AuthSessions.ts

417 lines13.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/unstable/sql/SqlClient";
7import * as SqlSchema from "effect/unstable/sql/SqlSchema";
8​
9import {
10 AuthClientMetadataDeviceType,
11 AuthEnvironmentScopes,
12 AuthSessionId,
13 ServerAuthSessionMethod,
14} from "@t3tools/contracts";
15​
16import {
17 type AuthSessionRepositoryError,
18 PersistenceDecodeError,
19 type PersistenceErrorCorrelation,
20 PersistenceSqlError,
21} from "./Errors.ts";
22​
23export const AuthSessionClientMetadataRecord = Schema.Struct({
24 label: Schema.NullOr(Schema.String),
25 ipAddress: Schema.NullOr(Schema.String),
26 userAgent: Schema.NullOr(Schema.String),
27 deviceType: AuthClientMetadataDeviceType,
28 os: Schema.NullOr(Schema.String),
29 browser: Schema.NullOr(Schema.String),
30});
31export type AuthSessionClientMetadataRecord = typeof AuthSessionClientMetadataRecord.Type;
32​
33export const AuthSessionRecord = Schema.Struct({
34 sessionId: AuthSessionId,
35 subject: Schema.String,
36 scopes: AuthEnvironmentScopes,
37 method: ServerAuthSessionMethod,
38 client: AuthSessionClientMetadataRecord,
39 issuedAt: Schema.DateTimeUtcFromString,
40 expiresAt: Schema.DateTimeUtcFromString,
41 lastConnectedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
42 revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
43});
44export type AuthSessionRecord = typeof AuthSessionRecord.Type;
45​
46export const CreateAuthSessionInput = Schema.Struct({
47 sessionId: AuthSessionId,
48 subject: Schema.String,
49 scopes: AuthEnvironmentScopes,
50 method: ServerAuthSessionMethod,
51 client: AuthSessionClientMetadataRecord,
52 issuedAt: Schema.DateTimeUtcFromString,
53 expiresAt: Schema.DateTimeUtcFromString,
54});
55export type CreateAuthSessionInput = typeof CreateAuthSessionInput.Type;
56​
57export const GetAuthSessionByIdInput = Schema.Struct({
58 sessionId: AuthSessionId,
59});
60export type GetAuthSessionByIdInput = typeof GetAuthSessionByIdInput.Type;
61​
62export const ListActiveAuthSessionsInput = Schema.Struct({
63 now: Schema.DateTimeUtcFromString,
64});
65export type ListActiveAuthSessionsInput = typeof ListActiveAuthSessionsInput.Type;
66​
67export const RevokeAuthSessionInput = Schema.Struct({
68 sessionId: AuthSessionId,
69 revokedAt: Schema.DateTimeUtcFromString,
70});
71export type RevokeAuthSessionInput = typeof RevokeAuthSessionInput.Type;
72​
73export const RevokeOtherAuthSessionsInput = Schema.Struct({
74 currentSessionId: AuthSessionId,
75 revokedAt: Schema.DateTimeUtcFromString,
76});
77export type RevokeOtherAuthSessionsInput = typeof RevokeOtherAuthSessionsInput.Type;
78​
79export const SetAuthSessionLastConnectedAtInput = Schema.Struct({
80 sessionId: AuthSessionId,
81 lastConnectedAt: Schema.DateTimeUtcFromString,
82});
83export type SetAuthSessionLastConnectedAtInput = typeof SetAuthSessionLastConnectedAtInput.Type;
84​
85export class AuthSessionRepository extends Context.Service<
86 AuthSessionRepository,
87 {
88 readonly create: (
89 input: CreateAuthSessionInput,
90 ) => Effect.Effect<void, AuthSessionRepositoryError>;
91 readonly getById: (
92 input: GetAuthSessionByIdInput,
93 ) => Effect.Effect<Option.Option<AuthSessionRecord>, AuthSessionRepositoryError>;
94 readonly listActive: (
95 input: ListActiveAuthSessionsInput,
96 ) => Effect.Effect<ReadonlyArray<AuthSessionRecord>, AuthSessionRepositoryError>;
97 readonly revoke: (
98 input: RevokeAuthSessionInput,
99 ) => Effect.Effect<boolean, AuthSessionRepositoryError>;
100 readonly revokeAllExcept: (
101 input: RevokeOtherAuthSessionsInput,
102 ) => Effect.Effect<ReadonlyArray<AuthSessionId>, AuthSessionRepositoryError>;
103 readonly setLastConnectedAt: (
104 input: SetAuthSessionLastConnectedAtInput,
105 ) => Effect.Effect<void, AuthSessionRepositoryError>;
106 }
107>()("t3/persistence/AuthSessions/AuthSessionRepository") {}
108​
109const AuthSessionDbRow = Schema.Struct({
110 sessionId: AuthSessionId,
111 subject: Schema.String,
112 scopes: Schema.fromJsonString(AuthEnvironmentScopes),
113 method: ServerAuthSessionMethod,
114 clientLabel: Schema.NullOr(Schema.String),
115 clientIpAddress: Schema.NullOr(Schema.String),
116 clientUserAgent: Schema.NullOr(Schema.String),
117 clientDeviceType: Schema.Literals(["desktop", "mobile", "tablet", "bot", "unknown"]),
118 clientOs: Schema.NullOr(Schema.String),
119 clientBrowser: Schema.NullOr(Schema.String),
120 issuedAt: Schema.DateTimeUtcFromString,
121 expiresAt: Schema.DateTimeUtcFromString,
122 lastConnectedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
123 revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
124});
125​
126const AuthSessionRawDbRow = Schema.Struct({
127 sessionId: Schema.String,
128 subject: Schema.Unknown,
129 scopes: Schema.Unknown,
130 method: Schema.Unknown,
131 clientLabel: Schema.Unknown,
132 clientIpAddress: Schema.Unknown,
133 clientUserAgent: Schema.Unknown,
134 clientDeviceType: Schema.Unknown,
135 clientOs: Schema.Unknown,
136 clientBrowser: Schema.Unknown,
137 issuedAt: Schema.Unknown,
138 expiresAt: Schema.Unknown,
139 lastConnectedAt: Schema.Unknown,
140 revokedAt: Schema.Unknown,
141});
142​
143const decodeAuthSessionDbRow = Schema.decodeUnknownEffect(AuthSessionDbRow);
144​
145function toAuthSessionRecord(row: typeof AuthSessionDbRow.Type): AuthSessionRecord {
146 return {
147 sessionId: row.sessionId,
148 subject: row.subject,
149 scopes: row.scopes,
150 method: row.method,
151 client: {
152 label: row.clientLabel,
153 ipAddress: row.clientIpAddress,
154 userAgent: row.clientUserAgent,
155 deviceType: row.clientDeviceType,
156 os: row.clientOs,
157 browser: row.clientBrowser,
158 },
159 issuedAt: row.issuedAt,
160 expiresAt: row.expiresAt,
161 lastConnectedAt: row.lastConnectedAt,
162 revokedAt: row.revokedAt,
163 };
165​
166function toPersistenceSqlOrDecodeError(
167 sqlOperation: string,
168 decodeOperation: string,
169 correlation?: PersistenceErrorCorrelation,
170) {
171 return (cause: unknown): AuthSessionRepositoryError =>
172 Schema.isSchemaError(cause)
173 ? PersistenceDecodeError.fromSchemaError(decodeOperation, cause, correlation)
174 : new PersistenceSqlError({
175 operation: sqlOperation,
176 ...(correlation === undefined ? {} : { correlation }),
177 cause,
178 });
180​
181export const make = Effect.gen(function* () {
182 const sql = yield* SqlClient.SqlClient;
183​
184 const createSessionRow = SqlSchema.void({
185 Request: CreateAuthSessionInput,
186 execute: (input) =>
187 sql`
188 INSERT INTO auth_sessions (
189 session_id,
190 subject,
191 scopes,
192 method,
193 client_label,
194 client_ip_address,
195 client_user_agent,
196 client_device_type,
197 client_os,
198 client_browser,
199 issued_at,
200 expires_at,
201 revoked_at
202 )
203 VALUES (
204 ${input.sessionId},
205 ${input.subject},
206 ${JSON.stringify(input.scopes)},
207 ${input.method},
208 ${input.client.label},
209 ${input.client.ipAddress},
210 ${input.client.userAgent},
211 ${input.client.deviceType},
212 ${input.client.os},
213 ${input.client.browser},
214 ${input.issuedAt},
215 ${input.expiresAt},
216 NULL
217 )
218 `,
219 });
220​
221 const getSessionRowById = SqlSchema.findOneOption({
222 Request: GetAuthSessionByIdInput,
223 Result: AuthSessionRawDbRow,
224 execute: ({ sessionId }) =>
225 sql`
226 SELECT
227 session_id AS "sessionId",
228 subject AS "subject",
229 scopes AS "scopes",
230 method AS "method",
231 client_label AS "clientLabel",
232 client_ip_address AS "clientIpAddress",
233 client_user_agent AS "clientUserAgent",
234 client_device_type AS "clientDeviceType",
235 client_os AS "clientOs",
236 client_browser AS "clientBrowser",
237 issued_at AS "issuedAt",
238 expires_at AS "expiresAt",
239 last_connected_at AS "lastConnectedAt",
240 revoked_at AS "revokedAt"
241 FROM auth_sessions
242 WHERE session_id = ${sessionId}
243 `,
244 });
245​
246 const listActiveSessionRows = SqlSchema.findAll({
247 Request: ListActiveAuthSessionsInput,
248 Result: AuthSessionRawDbRow,
249 execute: ({ now }) =>
250 sql`
251 SELECT
252 session_id AS "sessionId",
253 subject AS "subject",
254 scopes AS "scopes",
255 method AS "method",
256 client_label AS "clientLabel",
257 client_ip_address AS "clientIpAddress",
258 client_user_agent AS "clientUserAgent",
259 client_device_type AS "clientDeviceType",
260 client_os AS "clientOs",
261 client_browser AS "clientBrowser",
262 issued_at AS "issuedAt",
263 expires_at AS "expiresAt",
264 last_connected_at AS "lastConnectedAt",
265 revoked_at AS "revokedAt"
266 FROM auth_sessions
267 WHERE revoked_at IS NULL
268 AND expires_at > ${now}
269 ORDER BY issued_at DESC, session_id DESC
270 `,
271 });
272​
273 const setLastConnectedAtRow = SqlSchema.void({
274 Request: SetAuthSessionLastConnectedAtInput,
275 execute: ({ sessionId, lastConnectedAt }) =>
276 sql`
277 UPDATE auth_sessions
278 SET last_connected_at = ${lastConnectedAt}
279 WHERE session_id = ${sessionId}
280 AND revoked_at IS NULL
281 `,
282 });
283​
284 const revokeSessionRows = SqlSchema.findAll({
285 Request: RevokeAuthSessionInput,
286 Result: Schema.Struct({ sessionId: AuthSessionId }),
287 execute: ({ sessionId, revokedAt }) =>
288 sql`
289 UPDATE auth_sessions
290 SET revoked_at = ${revokedAt}
291 WHERE session_id = ${sessionId}
292 AND revoked_at IS NULL
293 RETURNING session_id AS "sessionId"
294 `,
295 });
296​
297 const revokeOtherSessionRows = SqlSchema.findAll({
298 Request: RevokeOtherAuthSessionsInput,
299 Result: Schema.Struct({ sessionId: AuthSessionId }),
300 execute: ({ currentSessionId, revokedAt }) =>
301 sql`
302 UPDATE auth_sessions
303 SET revoked_at = ${revokedAt}
304 WHERE session_id <> ${currentSessionId}
305 AND revoked_at IS NULL
306 RETURNING session_id AS "sessionId"
307 `,
308 });
309​
310 const create: AuthSessionRepository["Service"]["create"] = (input) =>
311 createSessionRow(input).pipe(
312 Effect.mapError(
313 toPersistenceSqlOrDecodeError(
314 "AuthSessionRepository.create:query",
315 "AuthSessionRepository.create:encodeRequest",
316 { sessionId: input.sessionId },
317 ),
318 ),
319 );
320​
321 const getById: AuthSessionRepository["Service"]["getById"] = (input) =>
322 getSessionRowById(input).pipe(
323 Effect.mapError(
324 toPersistenceSqlOrDecodeError(
325 "AuthSessionRepository.getById:query",
326 "AuthSessionRepository.getById:decodeRow",
327 { sessionId: input.sessionId },
328 ),
329 ),
330 Effect.flatMap((rowOption) =>
331 Option.match(rowOption, {
332 onNone: () => Effect.succeed(Option.none()),
333 onSome: (row) =>
334 decodeAuthSessionDbRow(row).pipe(
335 Effect.mapError((cause) =>
336 PersistenceDecodeError.fromSchemaError(
337 "AuthSessionRepository.getById:decodeRow",
338 cause,
339 { sessionId: input.sessionId },
340 ),
341 ),
342 Effect.map((decodedRow) => Option.some(toAuthSessionRecord(decodedRow))),
343 ),
344 }),
345 ),
346 );
347​
348 const listActive: AuthSessionRepository["Service"]["listActive"] = (input) =>
349 listActiveSessionRows(input).pipe(
350 Effect.mapError(
351 toPersistenceSqlOrDecodeError(
352 "AuthSessionRepository.listActive:query",
353 "AuthSessionRepository.listActive:decodeRows",
354 ),
355 ),
356 Effect.flatMap((rows) =>
357 Effect.forEach(rows, (row) =>
358 decodeAuthSessionDbRow(row).pipe(
359 Effect.mapError((cause) =>
360 PersistenceDecodeError.fromSchemaError(
361 "AuthSessionRepository.listActive:decodeRows",
362 cause,
363 { sessionId: row.sessionId },
364 ),
365 ),
366 Effect.map(toAuthSessionRecord),
367 ),
368 ),
369 ),
370 );
371​
372 const revoke: AuthSessionRepository["Service"]["revoke"] = (input) =>
373 revokeSessionRows(input).pipe(
374 Effect.mapError(
375 toPersistenceSqlOrDecodeError(
376 "AuthSessionRepository.revoke:query",
377 "AuthSessionRepository.revoke:decodeRows",
378 { sessionId: input.sessionId },
379 ),
380 ),
381 Effect.map((rows) => rows.length > 0),
382 );
383​
384 const revokeAllExcept: AuthSessionRepository["Service"]["revokeAllExcept"] = (input) =>
385 revokeOtherSessionRows(input).pipe(
386 Effect.mapError(
387 toPersistenceSqlOrDecodeError(
388 "AuthSessionRepository.revokeAllExcept:query",
389 "AuthSessionRepository.revokeAllExcept:decodeRows",
390 { currentSessionId: input.currentSessionId },
391 ),
392 ),
393 Effect.map((rows) => rows.map((row) => row.sessionId)),
394 );
395​
396 const setLastConnectedAt: AuthSessionRepository["Service"]["setLastConnectedAt"] = (input) =>
397 setLastConnectedAtRow(input).pipe(
398 Effect.mapError(
399 toPersistenceSqlOrDecodeError(
400 "AuthSessionRepository.setLastConnectedAt:query",
401 "AuthSessionRepository.setLastConnectedAt:encodeRequest",
402 { sessionId: input.sessionId },
403 ),
404 ),
405 );
406​
407 return {
408 create,
409 getById,
410 listActive,
411 revoke,
412 revokeAllExcept,
413 setLastConnectedAt,
414 } satisfies AuthSessionRepository["Service"];
415});
416​
417export const layer = Layer.effect(AuthSessionRepository, make);