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

AuthPairingLinks.ts

356 lines11.4 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 { AuthEnvironmentScopes } from "@t3tools/contracts";
10​
11import {
12 type AuthPairingLinkRepositoryError,
13 PersistenceDecodeError,
14 type PersistenceErrorCorrelation,
15 PersistenceSqlError,
16} from "./Errors.ts";
17​
18export const AuthPairingLinkRecord = Schema.Struct({
19 id: Schema.String,
20 credential: Schema.String,
21 method: Schema.Literals(["desktop-bootstrap", "one-time-token"]),
22 scopes: Schema.fromJsonString(AuthEnvironmentScopes),
23 subject: Schema.String,
24 label: Schema.NullOr(Schema.String),
25 proofKeyThumbprint: Schema.NullOr(Schema.String),
26 createdAt: Schema.DateTimeUtcFromString,
27 expiresAt: Schema.DateTimeUtcFromString,
28 consumedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
29 revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
30});
31export type AuthPairingLinkRecord = typeof AuthPairingLinkRecord.Type;
32​
33export const CreateAuthPairingLinkInput = Schema.Struct({
34 id: Schema.String,
35 credential: Schema.String,
36 method: Schema.Literals(["desktop-bootstrap", "one-time-token"]),
37 scopes: AuthEnvironmentScopes,
38 subject: Schema.String,
39 label: Schema.NullOr(Schema.String),
40 proofKeyThumbprint: Schema.NullOr(Schema.String),
41 createdAt: Schema.DateTimeUtcFromString,
42 expiresAt: Schema.DateTimeUtcFromString,
43});
44export type CreateAuthPairingLinkInput = typeof CreateAuthPairingLinkInput.Type;
45​
46export const ConsumeAuthPairingLinkInput = Schema.Struct({
47 credential: Schema.String,
48 proofKeyThumbprint: Schema.NullOr(Schema.String),
49 consumedAt: Schema.DateTimeUtcFromString,
50 now: Schema.DateTimeUtcFromString,
51});
52export type ConsumeAuthPairingLinkInput = typeof ConsumeAuthPairingLinkInput.Type;
53​
54export const ListActiveAuthPairingLinksInput = Schema.Struct({
55 now: Schema.DateTimeUtcFromString,
56});
57export type ListActiveAuthPairingLinksInput = typeof ListActiveAuthPairingLinksInput.Type;
58​
59export const RevokeAuthPairingLinkInput = Schema.Struct({
60 id: Schema.String,
61 revokedAt: Schema.DateTimeUtcFromString,
62});
63export type RevokeAuthPairingLinkInput = typeof RevokeAuthPairingLinkInput.Type;
64​
65export const GetAuthPairingLinkByCredentialInput = Schema.Struct({
66 credential: Schema.String,
67});
68export type GetAuthPairingLinkByCredentialInput = typeof GetAuthPairingLinkByCredentialInput.Type;
69​
70const AuthPairingLinkRawDbRow = Schema.Struct({
71 id: Schema.String,
72 credential: Schema.Unknown,
73 method: Schema.Unknown,
74 scopes: Schema.Unknown,
75 subject: Schema.Unknown,
76 label: Schema.Unknown,
77 proofKeyThumbprint: Schema.Unknown,
78 createdAt: Schema.Unknown,
79 expiresAt: Schema.Unknown,
80 consumedAt: Schema.Unknown,
81 revokedAt: Schema.Unknown,
82});
83​
84const decodeAuthPairingLinkDbRow = Schema.decodeUnknownEffect(AuthPairingLinkRecord);
85​
86export class AuthPairingLinkRepository extends Context.Service<
87 AuthPairingLinkRepository,
88 {
89 readonly create: (
90 input: CreateAuthPairingLinkInput,
91 ) => Effect.Effect<void, AuthPairingLinkRepositoryError>;
92 readonly consumeAvailable: (
93 input: ConsumeAuthPairingLinkInput,
94 ) => Effect.Effect<Option.Option<AuthPairingLinkRecord>, AuthPairingLinkRepositoryError>;
95 readonly listActive: (
96 input: ListActiveAuthPairingLinksInput,
97 ) => Effect.Effect<ReadonlyArray<AuthPairingLinkRecord>, AuthPairingLinkRepositoryError>;
98 readonly revoke: (
99 input: RevokeAuthPairingLinkInput,
100 ) => Effect.Effect<boolean, AuthPairingLinkRepositoryError>;
101 readonly getByCredential: (
102 input: GetAuthPairingLinkByCredentialInput,
103 ) => Effect.Effect<Option.Option<AuthPairingLinkRecord>, AuthPairingLinkRepositoryError>;
104 }
105>()("t3/persistence/AuthPairingLinks/AuthPairingLinkRepository") {}
106​
107function toPersistenceSqlOrDecodeError(
108 sqlOperation: string,
109 decodeOperation: string,
110 correlation?: PersistenceErrorCorrelation,
111) {
112 return (cause: unknown): AuthPairingLinkRepositoryError =>
113 Schema.isSchemaError(cause)
114 ? PersistenceDecodeError.fromSchemaError(decodeOperation, cause, correlation)
115 : new PersistenceSqlError({
116 operation: sqlOperation,
117 ...(correlation === undefined ? {} : { correlation }),
118 cause,
119 });
121​
122export const make = Effect.gen(function* () {
123 const sql = yield* SqlClient.SqlClient;
124​
125 const createPairingLinkRow = SqlSchema.void({
126 Request: CreateAuthPairingLinkInput,
127 execute: (input) =>
128 sql`
129 INSERT INTO auth_pairing_links (
130 id,
131 credential,
132 method,
133 scopes,
134 subject,
135 label,
136 proof_key_thumbprint,
137 created_at,
138 expires_at,
139 consumed_at,
140 revoked_at
141 )
142 VALUES (
143 ${input.id},
144 ${input.credential},
145 ${input.method},
146 ${JSON.stringify(input.scopes)},
147 ${input.subject},
148 ${input.label},
149 ${input.proofKeyThumbprint},
150 ${input.createdAt},
151 ${input.expiresAt},
152 NULL,
153 NULL
154 )
155 `,
156 });
157​
158 const consumeAvailablePairingLinkRow = SqlSchema.findOneOption({
159 Request: ConsumeAuthPairingLinkInput,
160 Result: AuthPairingLinkRawDbRow,
161 execute: ({ credential, proofKeyThumbprint, consumedAt, now }) =>
162 sql`
163 UPDATE auth_pairing_links
164 SET consumed_at = ${consumedAt}
165 WHERE credential = ${credential}
166 AND revoked_at IS NULL
167 AND consumed_at IS NULL
168 AND expires_at > ${now}
169 AND (
170 proof_key_thumbprint IS NULL
171 OR proof_key_thumbprint = ${proofKeyThumbprint}
172 )
173 RETURNING
174 id AS "id",
175 credential AS "credential",
176 method AS "method",
177 scopes AS "scopes",
178 subject AS "subject",
179 label AS "label",
180 proof_key_thumbprint AS "proofKeyThumbprint",
181 created_at AS "createdAt",
182 expires_at AS "expiresAt",
183 consumed_at AS "consumedAt",
184 revoked_at AS "revokedAt"
185 `,
186 });
187​
188 const listActivePairingLinkRows = SqlSchema.findAll({
189 Request: ListActiveAuthPairingLinksInput,
190 Result: AuthPairingLinkRawDbRow,
191 execute: ({ now }) =>
192 sql`
193 SELECT
194 id AS "id",
195 credential AS "credential",
196 method AS "method",
197 scopes AS "scopes",
198 subject AS "subject",
199 label AS "label",
200 proof_key_thumbprint AS "proofKeyThumbprint",
201 created_at AS "createdAt",
202 expires_at AS "expiresAt",
203 consumed_at AS "consumedAt",
204 revoked_at AS "revokedAt"
205 FROM auth_pairing_links
206 WHERE revoked_at IS NULL
207 AND consumed_at IS NULL
208 AND expires_at > ${now}
209 ORDER BY created_at DESC, id DESC
210 `,
211 });
212​
213 const revokePairingLinkRow = SqlSchema.findAll({
214 Request: RevokeAuthPairingLinkInput,
215 Result: Schema.Struct({ id: Schema.String }),
216 execute: ({ id, revokedAt }) =>
217 sql`
218 UPDATE auth_pairing_links
219 SET revoked_at = ${revokedAt}
220 WHERE id = ${id}
221 AND revoked_at IS NULL
222 AND consumed_at IS NULL
223 RETURNING id AS "id"
224 `,
225 });
226​
227 const getPairingLinkRowByCredential = SqlSchema.findOneOption({
228 Request: GetAuthPairingLinkByCredentialInput,
229 Result: AuthPairingLinkRawDbRow,
230 execute: ({ credential }) =>
231 sql`
232 SELECT
233 id AS "id",
234 credential AS "credential",
235 method AS "method",
236 scopes AS "scopes",
237 subject AS "subject",
238 label AS "label",
239 proof_key_thumbprint AS "proofKeyThumbprint",
240 created_at AS "createdAt",
241 expires_at AS "expiresAt",
242 consumed_at AS "consumedAt",
243 revoked_at AS "revokedAt"
244 FROM auth_pairing_links
245 WHERE credential = ${credential}
246 `,
247 });
248​
249 const create: AuthPairingLinkRepository["Service"]["create"] = (input) =>
250 createPairingLinkRow(input).pipe(
251 Effect.mapError(
252 toPersistenceSqlOrDecodeError(
253 "AuthPairingLinkRepository.create:query",
254 "AuthPairingLinkRepository.create:encodeRequest",
255 { pairingLinkId: input.id },
256 ),
257 ),
258 );
259​
260 const consumeAvailable: AuthPairingLinkRepository["Service"]["consumeAvailable"] = (input) =>
261 consumeAvailablePairingLinkRow(input).pipe(
262 Effect.mapError(
263 toPersistenceSqlOrDecodeError(
264 "AuthPairingLinkRepository.consumeAvailable:query",
265 "AuthPairingLinkRepository.consumeAvailable:decodeRow",
266 ),
267 ),
268 Effect.flatMap((rowOption) =>
269 Option.match(rowOption, {
270 onNone: () => Effect.succeed(Option.none()),
271 onSome: (row) =>
272 decodeAuthPairingLinkDbRow(row).pipe(
273 Effect.mapError((cause) =>
274 PersistenceDecodeError.fromSchemaError(
275 "AuthPairingLinkRepository.consumeAvailable:decodeRow",
276 cause,
277 { pairingLinkId: row.id },
278 ),
279 ),
280 Effect.map(Option.some),
281 ),
282 }),
283 ),
284 );
285​
286 const listActive: AuthPairingLinkRepository["Service"]["listActive"] = (input) =>
287 listActivePairingLinkRows(input).pipe(
288 Effect.mapError(
289 toPersistenceSqlOrDecodeError(
290 "AuthPairingLinkRepository.listActive:query",
291 "AuthPairingLinkRepository.listActive:decodeRows",
292 ),
293 ),
294 Effect.flatMap((rows) =>
295 Effect.forEach(rows, (row) =>
296 decodeAuthPairingLinkDbRow(row).pipe(
297 Effect.mapError((cause) =>
298 PersistenceDecodeError.fromSchemaError(
299 "AuthPairingLinkRepository.listActive:decodeRows",
300 cause,
301 { pairingLinkId: row.id },
302 ),
303 ),
304 ),
305 ),
306 ),
307 );
308​
309 const revoke: AuthPairingLinkRepository["Service"]["revoke"] = (input) =>
310 revokePairingLinkRow(input).pipe(
311 Effect.mapError(
312 toPersistenceSqlOrDecodeError(
313 "AuthPairingLinkRepository.revoke:query",
314 "AuthPairingLinkRepository.revoke:decodeRows",
315 { pairingLinkId: input.id },
316 ),
317 ),
318 Effect.map((rows) => rows.length > 0),
319 );
320​
321 const getByCredential: AuthPairingLinkRepository["Service"]["getByCredential"] = (input) =>
322 getPairingLinkRowByCredential(input).pipe(
323 Effect.mapError(
324 toPersistenceSqlOrDecodeError(
325 "AuthPairingLinkRepository.getByCredential:query",
326 "AuthPairingLinkRepository.getByCredential:decodeRow",
327 ),
328 ),
329 Effect.flatMap((rowOption) =>
330 Option.match(rowOption, {
331 onNone: () => Effect.succeed(Option.none()),
332 onSome: (row) =>
333 decodeAuthPairingLinkDbRow(row).pipe(
334 Effect.mapError((cause) =>
335 PersistenceDecodeError.fromSchemaError(
336 "AuthPairingLinkRepository.getByCredential:decodeRow",
337 cause,
338 { pairingLinkId: row.id },
339 ),
340 ),
341 Effect.map(Option.some),
342 ),
343 }),
344 ),
345 );
346​
347 return {
348 create,
349 consumeAvailable,
350 listActive,
351 revoke,
352 getByCredential,
353 } satisfies AuthPairingLinkRepository["Service"];
354});
355​
356export const layer = Layer.effect(AuthPairingLinkRepository, make);