Open History to see the last commit
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 });
120}
121
122/** @public Service construction is part of the canonical Effect module API. */
123export const make = Effect.gen(function* () {
124 const sql = yield* SqlClient.SqlClient;
125
126 const createPairingLinkRow = SqlSchema.void({
127 Request: CreateAuthPairingLinkInput,
128 execute: (input) =>
129 sql`
130 INSERT INTO auth_pairing_links (
131 id,
132 credential,
133 method,
134 scopes,
135 subject,
136 label,
137 proof_key_thumbprint,
138 created_at,
139 expires_at,
140 consumed_at,
141 revoked_at
142 )
143 VALUES (
144 ${input.id},
145 ${input.credential},
146 ${input.method},
147 ${JSON.stringify(input.scopes)},
148 ${input.subject},
149 ${input.label},
150 ${input.proofKeyThumbprint},
151 ${input.createdAt},
152 ${input.expiresAt},
153 NULL,
154 NULL
155 )
156 `,
157 });
158
159 const consumeAvailablePairingLinkRow = SqlSchema.findOneOption({
160 Request: ConsumeAuthPairingLinkInput,
161 Result: AuthPairingLinkRawDbRow,
162 execute: ({ credential, proofKeyThumbprint, consumedAt, now }) =>
163 sql`
164 UPDATE auth_pairing_links
165 SET consumed_at = ${consumedAt}
166 WHERE credential = ${credential}
167 AND revoked_at IS NULL
168 AND consumed_at IS NULL
169 AND expires_at > ${now}
170 AND (
171 proof_key_thumbprint IS NULL
172 OR proof_key_thumbprint = ${proofKeyThumbprint}
173 )
174 RETURNING
175 id AS "id",
176 credential AS "credential",
177 method AS "method",
178 scopes AS "scopes",
179 subject AS "subject",
180 label AS "label",
181 proof_key_thumbprint AS "proofKeyThumbprint",
182 created_at AS "createdAt",
183 expires_at AS "expiresAt",
184 consumed_at AS "consumedAt",
185 revoked_at AS "revokedAt"
186 `,
187 });
188
189 const listActivePairingLinkRows = SqlSchema.findAll({
190 Request: ListActiveAuthPairingLinksInput,
191 Result: AuthPairingLinkRawDbRow,
192 execute: ({ now }) =>
193 sql`
194 SELECT
195 id AS "id",
196 credential AS "credential",
197 method AS "method",
198 scopes AS "scopes",
199 subject AS "subject",
200 label AS "label",
201 proof_key_thumbprint AS "proofKeyThumbprint",
202 created_at AS "createdAt",
203 expires_at AS "expiresAt",
204 consumed_at AS "consumedAt",
205 revoked_at AS "revokedAt"
206 FROM auth_pairing_links
207 WHERE revoked_at IS NULL
208 AND consumed_at IS NULL
209 AND expires_at > ${now}
210 ORDER BY created_at DESC, id DESC
211 `,
212 });
213
214 const revokePairingLinkRow = SqlSchema.findAll({
215 Request: RevokeAuthPairingLinkInput,
216 Result: Schema.Struct({ id: Schema.String }),
217 execute: ({ id, revokedAt }) =>
218 sql`
219 UPDATE auth_pairing_links
220 SET revoked_at = ${revokedAt}
221 WHERE id = ${id}
222 AND revoked_at IS NULL
223 AND consumed_at IS NULL
224 RETURNING id AS "id"
225 `,
226 });
227
228 const getPairingLinkRowByCredential = SqlSchema.findOneOption({
229 Request: GetAuthPairingLinkByCredentialInput,
230 Result: AuthPairingLinkRawDbRow,
231 execute: ({ credential }) =>
232 sql`
233 SELECT
234 id AS "id",
235 credential AS "credential",
236 method AS "method",
237 scopes AS "scopes",
238 subject AS "subject",
239 label AS "label",
240 proof_key_thumbprint AS "proofKeyThumbprint",
241 created_at AS "createdAt",
242 expires_at AS "expiresAt",
243 consumed_at AS "consumedAt",
244 revoked_at AS "revokedAt"
245 FROM auth_pairing_links
246 WHERE credential = ${credential}
247 `,
248 });
249
250 const create: AuthPairingLinkRepository["Service"]["create"] = (input) =>
251 createPairingLinkRow(input).pipe(
252 Effect.mapError(
253 toPersistenceSqlOrDecodeError(
254 "AuthPairingLinkRepository.create:query",
255 "AuthPairingLinkRepository.create:encodeRequest",
256 { pairingLinkId: input.id },
257 ),
258 ),
259 );
260
261 const consumeAvailable: AuthPairingLinkRepository["Service"]["consumeAvailable"] = (input) =>
262 consumeAvailablePairingLinkRow(input).pipe(
263 Effect.mapError(
264 toPersistenceSqlOrDecodeError(
265 "AuthPairingLinkRepository.consumeAvailable:query",
266 "AuthPairingLinkRepository.consumeAvailable:decodeRow",
267 ),
268 ),
269 Effect.flatMap((rowOption) =>
270 Option.match(rowOption, {
271 onNone: () => Effect.succeed(Option.none()),
272 onSome: (row) =>
273 decodeAuthPairingLinkDbRow(row).pipe(
274 Effect.mapError((cause) =>
275 PersistenceDecodeError.fromSchemaError(
276 "AuthPairingLinkRepository.consumeAvailable:decodeRow",
277 cause,
278 { pairingLinkId: row.id },
279 ),
280 ),
281 Effect.map(Option.some),
282 ),
283 }),
284 ),
285 );
286
287 const listActive: AuthPairingLinkRepository["Service"]["listActive"] = (input) =>
288 listActivePairingLinkRows(input).pipe(
289 Effect.mapError(
290 toPersistenceSqlOrDecodeError(
291 "AuthPairingLinkRepository.listActive:query",
292 "AuthPairingLinkRepository.listActive:decodeRows",
293 ),
294 ),
295 Effect.flatMap((rows) =>
296 Effect.forEach(rows, (row) =>
297 decodeAuthPairingLinkDbRow(row).pipe(
298 Effect.mapError((cause) =>
299 PersistenceDecodeError.fromSchemaError(
300 "AuthPairingLinkRepository.listActive:decodeRows",
301 cause,
302 { pairingLinkId: row.id },
303 ),
304 ),
305 ),
306 ),
307 ),
308 );
309
310 const revoke: AuthPairingLinkRepository["Service"]["revoke"] = (input) =>
311 revokePairingLinkRow(input).pipe(
312 Effect.mapError(
313 toPersistenceSqlOrDecodeError(
314 "AuthPairingLinkRepository.revoke:query",
315 "AuthPairingLinkRepository.revoke:decodeRows",
316 { pairingLinkId: input.id },
317 ),
318 ),
319 Effect.map((rows) => rows.length > 0),
320 );
321
322 const getByCredential: AuthPairingLinkRepository["Service"]["getByCredential"] = (input) =>
323 getPairingLinkRowByCredential(input).pipe(
324 Effect.mapError(
325 toPersistenceSqlOrDecodeError(
326 "AuthPairingLinkRepository.getByCredential:query",
327 "AuthPairingLinkRepository.getByCredential:decodeRow",
328 ),
329 ),
330 Effect.flatMap((rowOption) =>
331 Option.match(rowOption, {
332 onNone: () => Effect.succeed(Option.none()),
333 onSome: (row) =>
334 decodeAuthPairingLinkDbRow(row).pipe(
335 Effect.mapError((cause) =>
336 PersistenceDecodeError.fromSchemaError(
337 "AuthPairingLinkRepository.getByCredential:decodeRow",
338 cause,
339 { pairingLinkId: row.id },
340 ),
341 ),
342 Effect.map(Option.some),
343 ),
344 }),
345 ),
346 );
347
348 return {
349 create,
350 consumeAvailable,
351 listActive,
352 revoke,
353 getByCredential,
354 } satisfies AuthPairingLinkRepository["Service"];
355});
356
357export const layer = Layer.effect(AuthPairingLinkRepository, make);