The best way to control Claude Code, Codex and more from any computer or phone

main
ts 639 lines 22.4 KB
Raw
1 import * as Context from "effect/Context";
2 import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
3 import * as Effect from "effect/Effect";
4 import * as Layer from "effect/Layer";
5 import * as Option from "effect/Option";
6 import * as Schema from "effect/Schema";
7 import * as SqlClient from "effect/sql/SqlClient";
8 import * as SqlSchema from "effect/sql/SqlSchema";
9
10 import { AuthClientMetadata, AuthEnvironmentScopes } from "@t3tools/contracts";
11
12 import {
13 type AuthPairingLinkRepositoryError,
14 PersistenceDecodeError,
15 type PersistenceErrorCorrelation,
16 PersistenceSqlError,
17 } from "./Errors.ts";
18
19 /**
20 * These subjects are reserved for one kind and level of MCP authorization.
21 * Keep peer-link subjects under the same prefix so older servers refuse them too.
22 */
23 export const MCP_APPROVAL_SUBJECT_PREFIX = "mcp-approval:";
24 export const PEER_LINK_PAIRING_SUBJECT_PREFIX = `${MCP_APPROVAL_SUBJECT_PREFIX}peer-link:`;
25
26 const SqliteFlag = Schema.Literals([0, 1]);
27
28 export const AuthPairingLinkRecord = Schema.Struct({
29 id: Schema.String,
30 credential: Schema.String,
31 method: Schema.Literals(["desktop-bootstrap", "one-time-token"]),
32 scopes: Schema.fromJsonString(AuthEnvironmentScopes),
33 subject: Schema.String,
34 label: Schema.NullOr(Schema.String),
35 proofKeyThumbprint: Schema.NullOr(Schema.String),
36 createdAt: Schema.DateTimeUtcFromString,
37 expiresAt: Schema.DateTimeUtcFromString,
38 consumedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
39 revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
40 /** Spendable only once `proofKeyThumbprint` is a trusted T3 Connect device. */
41 requiresConnectApproval: SqliteFlag,
42 connectApproved: SqliteFlag,
43 requestedClient: Schema.NullOr(Schema.fromJsonString(AuthClientMetadata)),
44 });
45 export type AuthPairingLinkRecord = typeof AuthPairingLinkRecord.Type;
46
47 export const CreateAuthPairingLinkInput = Schema.Struct({
48 id: Schema.String,
49 credential: Schema.String,
50 method: Schema.Literals(["desktop-bootstrap", "one-time-token"]),
51 scopes: AuthEnvironmentScopes,
52 subject: Schema.String,
53 label: Schema.NullOr(Schema.String),
54 proofKeyThumbprint: Schema.NullOr(Schema.String),
55 requiresConnectApproval: Schema.optionalKey(Schema.Boolean),
56 createdAt: Schema.DateTimeUtcFromString,
57 expiresAt: Schema.DateTimeUtcFromString,
58 });
59 export type CreateAuthPairingLinkInput = typeof CreateAuthPairingLinkInput.Type;
60
61 export const ConsumeAuthPairingLinkInput = Schema.Struct({
62 credential: Schema.String,
63 proofKeyThumbprint: Schema.NullOr(Schema.String),
64 requestedScopes: Schema.optionalKey(AuthEnvironmentScopes),
65 requiredScopes: Schema.optionalKey(AuthEnvironmentScopes),
66 /** Allow a purpose-bound code only when its subject matches the request. */
67 allowedSubject: Schema.optionalKey(Schema.String),
68 consumedAt: Schema.DateTimeUtcFromString,
69 now: Schema.DateTimeUtcFromString,
70 });
71 export type ConsumeAuthPairingLinkInput = typeof ConsumeAuthPairingLinkInput.Type;
72
73 export const ListActiveAuthPairingLinksInput = Schema.Struct({
74 now: Schema.DateTimeUtcFromString,
75 });
76 export type ListActiveAuthPairingLinksInput = typeof ListActiveAuthPairingLinksInput.Type;
77
78 export const RevokeAuthPairingLinkInput = Schema.Struct({
79 id: Schema.String,
80 revokedAt: Schema.DateTimeUtcFromString,
81 });
82 export type RevokeAuthPairingLinkInput = typeof RevokeAuthPairingLinkInput.Type;
83
84 export const GetAuthPairingLinkByCredentialInput = Schema.Struct({
85 credential: Schema.String,
86 });
87 export type GetAuthPairingLinkByCredentialInput = typeof GetAuthPairingLinkByCredentialInput.Type;
88
89 export const GetActiveAuthPairingLinkByIdInput = Schema.Struct({
90 id: Schema.String,
91 now: Schema.DateTimeUtcFromString,
92 });
93 export type GetActiveAuthPairingLinkByIdInput = typeof GetActiveAuthPairingLinkByIdInput.Type;
94
95 export const FindPendingConnectPairingLinkInput = Schema.Struct({
96 proofKeyThumbprint: Schema.String,
97 now: Schema.DateTimeUtcFromString,
98 });
99 export type FindPendingConnectPairingLinkInput = typeof FindPendingConnectPairingLinkInput.Type;
100
101 /**
102 * Unspent links bound to `proofKeyThumbprint`, or with `keepProofKeyThumbprint` every other bound
103 * one. `includeUnbound` adds the links no key is bound to: pairing and approval codes.
104 */
105 export const RevokeUnspentByProofKeyInput = Schema.Struct({
106 proofKeyThumbprint: Schema.NullOr(Schema.String),
107 keepProofKeyThumbprint: Schema.NullOr(Schema.String),
108 includeUnbound: Schema.Boolean,
109 revokedAt: Schema.DateTimeUtcFromString,
110 });
111 export type RevokeUnspentByProofKeyInput = typeof RevokeUnspentByProofKeyInput.Type;
112
113 export const RecordConnectRequestClientInput = Schema.Struct({
114 id: Schema.String,
115 client: Schema.fromJsonString(AuthClientMetadata),
116 });
117 export type RecordConnectRequestClientInput = typeof RecordConnectRequestClientInput.Type;
118
119 const AuthPairingLinkRawDbRow = Schema.Struct({
120 id: Schema.String,
121 credential: Schema.Unknown,
122 method: Schema.Unknown,
123 scopes: Schema.Unknown,
124 subject: Schema.Unknown,
125 label: Schema.Unknown,
126 proofKeyThumbprint: Schema.Unknown,
127 createdAt: Schema.Unknown,
128 expiresAt: Schema.Unknown,
129 consumedAt: Schema.Unknown,
130 revokedAt: Schema.Unknown,
131 requiresConnectApproval: Schema.Unknown,
132 connectApproved: Schema.Unknown,
133 requestedClient: Schema.Unknown,
134 });
135
136 const decodeAuthPairingLinkDbRow = Schema.decodeUnknownEffect(AuthPairingLinkRecord);
137
138 export class AuthPairingLinkRepository extends Context.Service<
139 AuthPairingLinkRepository,
140 {
141 readonly create: (
142 input: CreateAuthPairingLinkInput,
143 ) => Effect.Effect<void, AuthPairingLinkRepositoryError>;
144 readonly consumeAvailable: (
145 input: ConsumeAuthPairingLinkInput,
146 ) => Effect.Effect<Option.Option<AuthPairingLinkRecord>, AuthPairingLinkRepositoryError>;
147 readonly listActive: (
148 input: ListActiveAuthPairingLinksInput,
149 ) => Effect.Effect<ReadonlyArray<AuthPairingLinkRecord>, AuthPairingLinkRepositoryError>;
150 readonly revoke: (
151 input: RevokeAuthPairingLinkInput,
152 ) => Effect.Effect<boolean, AuthPairingLinkRepositoryError>;
153 readonly getByCredential: (
154 input: GetAuthPairingLinkByCredentialInput,
155 ) => Effect.Effect<Option.Option<AuthPairingLinkRecord>, AuthPairingLinkRepositoryError>;
156 readonly getActiveById: (
157 input: GetActiveAuthPairingLinkByIdInput,
158 ) => Effect.Effect<Option.Option<AuthPairingLinkRecord>, AuthPairingLinkRepositoryError>;
159 /** The device's open or denied request, so its retries do not stack up or re-prompt. */
160 readonly findPendingConnect: (
161 input: FindPendingConnectPairingLinkInput,
162 ) => Effect.Effect<Option.Option<AuthPairingLinkRecord>, AuthPairingLinkRepositoryError>;
163 /** Keeps the first description a device gave, so it cannot be swapped while someone decides. */
164 readonly recordConnectRequestClient: (
165 input: RecordConnectRequestClientInput,
166 ) => Effect.Effect<boolean, AuthPairingLinkRepositoryError>;
167 readonly revokeUnspentByProofKey: (
168 input: RevokeUnspentByProofKeyInput,
169 ) => Effect.Effect<ReadonlyArray<string>, AuthPairingLinkRepositoryError>;
170 }
171 >()("t3/persistence/AuthPairingLinks/AuthPairingLinkRepository") {}
172
173 function toPersistenceSqlOrDecodeError(
174 sqlOperation: string,
175 decodeOperation: string,
176 correlation?: PersistenceErrorCorrelation,
177 ) {
178 return (cause: unknown): AuthPairingLinkRepositoryError =>
179 Schema.isSchemaError(cause)
180 ? PersistenceDecodeError.fromSchemaError(decodeOperation, cause, correlation)
181 : new PersistenceSqlError({
182 operation: sqlOperation,
183 ...(correlation === undefined ? {} : { correlation }),
184 cause,
185 });
186 }
187
188 /** @public */
189 export const make = Effect.gen(function* () {
190 const sql = yield* SqlClient.SqlClient;
191
192 const createPairingLinkRow = SqlSchema.void({
193 Request: CreateAuthPairingLinkInput,
194 execute: (input) =>
195 sql`
196 INSERT INTO auth_pairing_links (
197 id,
198 credential,
199 method,
200 scopes,
201 subject,
202 label,
203 proof_key_thumbprint,
204 requires_connect_approval,
205 created_at,
206 expires_at,
207 consumed_at,
208 revoked_at
209 )
210 VALUES (
211 ${input.id},
212 ${input.credential},
213 ${input.method},
214 ${JSON.stringify(input.scopes)},
215 ${input.subject},
216 ${input.label},
217 ${input.proofKeyThumbprint},
218 ${input.requiresConnectApproval ? 1 : 0},
219 ${input.createdAt},
220 ${input.expiresAt},
221 NULL,
222 NULL
223 )
224 `,
225 });
226
227 const consumeAvailablePairingLinkRow = SqlSchema.findOneOption({
228 Request: ConsumeAuthPairingLinkInput,
229 Result: AuthPairingLinkRawDbRow,
230 execute: ({
231 credential,
232 proofKeyThumbprint,
233 requestedScopes,
234 requiredScopes,
235 allowedSubject,
236 consumedAt,
237 now,
238 }) =>
239 sql`
240 UPDATE auth_pairing_links
241 SET consumed_at = ${consumedAt}
242 WHERE credential = ${credential}
243 AND revoked_at IS NULL
244 AND consumed_at IS NULL
245 AND expires_at > ${now}
246 AND (
247 subject NOT LIKE ${`${MCP_APPROVAL_SUBJECT_PREFIX}%`}
248 OR subject = ${allowedSubject ?? null}
249 )
250 AND (
251 proof_key_thumbprint IS NULL
252 OR proof_key_thumbprint = ${proofKeyThumbprint}
253 )
254 AND (
255 requires_connect_approval = 0
256 OR proof_key_thumbprint IN (SELECT proof_key_thumbprint FROM auth_connect_devices)
257 )
258 AND (${requestedScopes === undefined ? 1 : 0} OR EXISTS (
259 SELECT 1
260 FROM json_each(${JSON.stringify(requestedScopes ?? [])}) AS requested
261 WHERE requested.value IN (
262 SELECT value FROM json_each(auth_pairing_links.scopes)
263 )
264 ))
265 AND NOT EXISTS (
266 SELECT 1
267 FROM json_each(${JSON.stringify(requiredScopes ?? [])}) AS required
268 WHERE required.value NOT IN (
269 SELECT value FROM json_each(auth_pairing_links.scopes)
270 )
271 )
272 RETURNING
273 id AS "id",
274 credential AS "credential",
275 method AS "method",
276 scopes AS "scopes",
277 subject AS "subject",
278 label AS "label",
279 proof_key_thumbprint AS "proofKeyThumbprint",
280 created_at AS "createdAt",
281 expires_at AS "expiresAt",
282 consumed_at AS "consumedAt",
283 revoked_at AS "revokedAt",
284 requires_connect_approval AS "requiresConnectApproval",
285 EXISTS (
286 SELECT 1 FROM auth_connect_devices
287 WHERE auth_connect_devices.proof_key_thumbprint = auth_pairing_links.proof_key_thumbprint
288 ) AS "connectApproved",
289 requested_client_json AS "requestedClient"
290 `,
291 });
292
293 const listActivePairingLinkRows = SqlSchema.findAll({
294 Request: ListActiveAuthPairingLinksInput,
295 Result: AuthPairingLinkRawDbRow,
296 execute: ({ now }) =>
297 sql`
298 SELECT
299 id AS "id",
300 credential AS "credential",
301 method AS "method",
302 scopes AS "scopes",
303 subject AS "subject",
304 label AS "label",
305 proof_key_thumbprint AS "proofKeyThumbprint",
306 created_at AS "createdAt",
307 expires_at AS "expiresAt",
308 consumed_at AS "consumedAt",
309 revoked_at AS "revokedAt",
310 requires_connect_approval AS "requiresConnectApproval",
311 EXISTS (
312 SELECT 1 FROM auth_connect_devices
313 WHERE auth_connect_devices.proof_key_thumbprint = auth_pairing_links.proof_key_thumbprint
314 ) AS "connectApproved",
315 requested_client_json AS "requestedClient"
316 FROM auth_pairing_links
317 WHERE revoked_at IS NULL
318 AND consumed_at IS NULL
319 AND expires_at > ${now}
320 ORDER BY created_at DESC, id DESC
321 `,
322 });
323
324 const revokePairingLinkRow = SqlSchema.findAll({
325 Request: RevokeAuthPairingLinkInput,
326 Result: Schema.Struct({ id: Schema.String }),
327 execute: ({ id, revokedAt }) =>
328 sql`
329 UPDATE auth_pairing_links
330 SET revoked_at = ${revokedAt},
331 -- Revoking a waiting approval request is a denial; see findPendingConnect.
332 connect_denied = requires_connect_approval
333 WHERE id = ${id}
334 AND revoked_at IS NULL
335 AND consumed_at IS NULL
336 -- An approved request is answered; denying it now would leave the device trusted.
337 AND NOT (
338 requires_connect_approval = 1
339 AND proof_key_thumbprint IN (SELECT proof_key_thumbprint FROM auth_connect_devices)
340 )
341 RETURNING id AS "id"
342 `,
343 });
344
345 const getPairingLinkRowByCredential = SqlSchema.findOneOption({
346 Request: GetAuthPairingLinkByCredentialInput,
347 Result: AuthPairingLinkRawDbRow,
348 execute: ({ credential }) =>
349 sql`
350 SELECT
351 id AS "id",
352 credential AS "credential",
353 method AS "method",
354 scopes AS "scopes",
355 subject AS "subject",
356 label AS "label",
357 proof_key_thumbprint AS "proofKeyThumbprint",
358 created_at AS "createdAt",
359 expires_at AS "expiresAt",
360 consumed_at AS "consumedAt",
361 revoked_at AS "revokedAt",
362 requires_connect_approval AS "requiresConnectApproval",
363 EXISTS (
364 SELECT 1 FROM auth_connect_devices
365 WHERE auth_connect_devices.proof_key_thumbprint = auth_pairing_links.proof_key_thumbprint
366 ) AS "connectApproved",
367 requested_client_json AS "requestedClient"
368 FROM auth_pairing_links
369 WHERE credential = ${credential}
370 `,
371 });
372
373 const selectRow = sql`
374 SELECT
375 id AS "id",
376 credential AS "credential",
377 method AS "method",
378 scopes AS "scopes",
379 subject AS "subject",
380 label AS "label",
381 proof_key_thumbprint AS "proofKeyThumbprint",
382 created_at AS "createdAt",
383 expires_at AS "expiresAt",
384 consumed_at AS "consumedAt",
385 revoked_at AS "revokedAt",
386 requires_connect_approval AS "requiresConnectApproval",
387 EXISTS (
388 SELECT 1 FROM auth_connect_devices
389 WHERE auth_connect_devices.proof_key_thumbprint = auth_pairing_links.proof_key_thumbprint
390 ) AS "connectApproved",
391 requested_client_json AS "requestedClient"
392 FROM auth_pairing_links
393 `;
394
395 const getActivePairingLinkRowById = SqlSchema.findOneOption({
396 Request: GetActiveAuthPairingLinkByIdInput,
397 Result: AuthPairingLinkRawDbRow,
398 execute: ({ id, now }) =>
399 sql`
400 ${selectRow}
401 WHERE id = ${id}
402 AND revoked_at IS NULL
403 AND consumed_at IS NULL
404 AND expires_at > ${now}
405 `,
406 });
407
408 const findPendingConnectPairingLinkRow = SqlSchema.findOneOption({
409 Request: FindPendingConnectPairingLinkInput,
410 Result: AuthPairingLinkRawDbRow,
411 execute: ({ proofKeyThumbprint, now }) =>
412 sql`
413 ${selectRow}
414 WHERE proof_key_thumbprint = ${proofKeyThumbprint}
415 AND requires_connect_approval = 1
416 -- A denied request stays the device's answer until it expires, so retries get a
417 -- dead credential back instead of prompting the approver again.
418 AND (revoked_at IS NULL OR connect_denied = 1)
419 AND consumed_at IS NULL
420 AND expires_at > ${now}
421 ORDER BY created_at DESC, id DESC
422 LIMIT 1
423 `,
424 });
425
426 const recordConnectRequestClientRow = SqlSchema.findAll({
427 Request: RecordConnectRequestClientInput,
428 Result: Schema.Struct({ id: Schema.String }),
429 execute: ({ id, client }) =>
430 sql`
431 UPDATE auth_pairing_links
432 SET requested_client_json = ${client}
433 WHERE id = ${id}
434 AND requires_connect_approval = 1
435 AND requested_client_json IS NULL
436 RETURNING id AS "id"
437 `,
438 });
439
440 const decodeOptionalRow =
441 (operation: string) => (rowOption: Option.Option<typeof AuthPairingLinkRawDbRow.Type>) =>
442 Option.match(rowOption, {
443 onNone: () => Effect.succeedNone,
444 onSome: (row) =>
445 decodeAuthPairingLinkDbRow(row).pipe(
446 Effect.mapError((cause) =>
447 PersistenceDecodeError.fromSchemaError(operation, cause, { pairingLinkId: row.id }),
448 ),
449 Effect.asSome,
450 ),
451 });
452
453 const getActiveById: AuthPairingLinkRepository["Service"]["getActiveById"] = (input) =>
454 getActivePairingLinkRowById(input).pipe(
455 NodeSqliteClient.readOnly,
456 Effect.mapError(
457 toPersistenceSqlOrDecodeError(
458 "AuthPairingLinkRepository.getActiveById:query",
459 "AuthPairingLinkRepository.getActiveById:decodeRow",
460 { pairingLinkId: input.id },
461 ),
462 ),
463 Effect.flatMap(decodeOptionalRow("AuthPairingLinkRepository.getActiveById:decodeRow")),
464 );
465
466 const findPendingConnect: AuthPairingLinkRepository["Service"]["findPendingConnect"] = (input) =>
467 findPendingConnectPairingLinkRow(input).pipe(
468 NodeSqliteClient.readOnly,
469 Effect.mapError(
470 toPersistenceSqlOrDecodeError(
471 "AuthPairingLinkRepository.findPendingConnect:query",
472 "AuthPairingLinkRepository.findPendingConnect:decodeRow",
473 ),
474 ),
475 Effect.flatMap(decodeOptionalRow("AuthPairingLinkRepository.findPendingConnect:decodeRow")),
476 );
477
478 const recordConnectRequestClient: AuthPairingLinkRepository["Service"]["recordConnectRequestClient"] =
479 (input) =>
480 recordConnectRequestClientRow(input).pipe(
481 Effect.mapError(
482 toPersistenceSqlOrDecodeError(
483 "AuthPairingLinkRepository.recordConnectRequestClient:query",
484 "AuthPairingLinkRepository.recordConnectRequestClient:encodeRequest",
485 { pairingLinkId: input.id },
486 ),
487 ),
488 Effect.map((rows) => rows.length > 0),
489 );
490
491 const revokeUnspentByProofKeyRows = SqlSchema.findAll({
492 Request: RevokeUnspentByProofKeyInput,
493 Result: Schema.Struct({ id: Schema.String }),
494 execute: ({ proofKeyThumbprint, keepProofKeyThumbprint, includeUnbound, revokedAt }) =>
495 sql`
496 -- Only T3 Connect mints bind a proof key, so bound links are that key's connect credentials.
497 UPDATE auth_pairing_links
498 SET revoked_at = ${revokedAt}
499 WHERE revoked_at IS NULL
500 AND consumed_at IS NULL
501 AND (
502 (
503 proof_key_thumbprint IS NOT NULL
504 AND (${proofKeyThumbprint} IS NULL OR proof_key_thumbprint = ${proofKeyThumbprint})
505 AND proof_key_thumbprint IS NOT ${keepProofKeyThumbprint}
506 )
507 OR (proof_key_thumbprint IS NULL AND ${includeUnbound ? 1 : 0} = 1)
508 )
509 RETURNING id AS "id"
510 `,
511 });
512
513 const revokeUnspentByProofKey: AuthPairingLinkRepository["Service"]["revokeUnspentByProofKey"] = (
514 input,
515 ) =>
516 revokeUnspentByProofKeyRows(input).pipe(
517 Effect.mapError(
518 toPersistenceSqlOrDecodeError(
519 "AuthPairingLinkRepository.revokeUnspentByProofKey:query",
520 "AuthPairingLinkRepository.revokeUnspentByProofKey:decodeRows",
521 ),
522 ),
523 Effect.map((rows) => rows.map((row) => row.id)),
524 );
525
526 const create: AuthPairingLinkRepository["Service"]["create"] = (input) =>
527 createPairingLinkRow(input).pipe(
528 Effect.mapError(
529 toPersistenceSqlOrDecodeError(
530 "AuthPairingLinkRepository.create:query",
531 "AuthPairingLinkRepository.create:encodeRequest",
532 { pairingLinkId: input.id },
533 ),
534 ),
535 );
536
537 const consumeAvailable: AuthPairingLinkRepository["Service"]["consumeAvailable"] = (input) =>
538 consumeAvailablePairingLinkRow(input).pipe(
539 Effect.mapError(
540 toPersistenceSqlOrDecodeError(
541 "AuthPairingLinkRepository.consumeAvailable:query",
542 "AuthPairingLinkRepository.consumeAvailable:decodeRow",
543 ),
544 ),
545 Effect.flatMap((rowOption) =>
546 Option.match(rowOption, {
547 onNone: () => Effect.succeedNone,
548 onSome: (row) =>
549 decodeAuthPairingLinkDbRow(row).pipe(
550 Effect.mapError((cause) =>
551 PersistenceDecodeError.fromSchemaError(
552 "AuthPairingLinkRepository.consumeAvailable:decodeRow",
553 cause,
554 { pairingLinkId: row.id },
555 ),
556 ),
557 Effect.asSome,
558 ),
559 }),
560 ),
561 );
562
563 const listActive: AuthPairingLinkRepository["Service"]["listActive"] = (input) =>
564 listActivePairingLinkRows(input).pipe(
565 NodeSqliteClient.readOnly,
566 Effect.mapError(
567 toPersistenceSqlOrDecodeError(
568 "AuthPairingLinkRepository.listActive:query",
569 "AuthPairingLinkRepository.listActive:decodeRows",
570 ),
571 ),
572 Effect.flatMap((rows) =>
573 Effect.forEach(rows, (row) =>
574 decodeAuthPairingLinkDbRow(row).pipe(
575 Effect.mapError((cause) =>
576 PersistenceDecodeError.fromSchemaError(
577 "AuthPairingLinkRepository.listActive:decodeRows",
578 cause,
579 { pairingLinkId: row.id },
580 ),
581 ),
582 ),
583 ),
584 ),
585 );
586
587 const revoke: AuthPairingLinkRepository["Service"]["revoke"] = (input) =>
588 revokePairingLinkRow(input).pipe(
589 Effect.mapError(
590 toPersistenceSqlOrDecodeError(
591 "AuthPairingLinkRepository.revoke:query",
592 "AuthPairingLinkRepository.revoke:decodeRows",
593 { pairingLinkId: input.id },
594 ),
595 ),
596 Effect.map((rows) => rows.length > 0),
597 );
598
599 const getByCredential: AuthPairingLinkRepository["Service"]["getByCredential"] = (input) =>
600 getPairingLinkRowByCredential(input).pipe(
601 NodeSqliteClient.readOnly,
602 Effect.mapError(
603 toPersistenceSqlOrDecodeError(
604 "AuthPairingLinkRepository.getByCredential:query",
605 "AuthPairingLinkRepository.getByCredential:decodeRow",
606 ),
607 ),
608 Effect.flatMap((rowOption) =>
609 Option.match(rowOption, {
610 onNone: () => Effect.succeedNone,
611 onSome: (row) =>
612 decodeAuthPairingLinkDbRow(row).pipe(
613 Effect.mapError((cause) =>
614 PersistenceDecodeError.fromSchemaError(
615 "AuthPairingLinkRepository.getByCredential:decodeRow",
616 cause,
617 { pairingLinkId: row.id },
618 ),
619 ),
620 Effect.asSome,
621 ),
622 }),
623 ),
624 );
625
626 return {
627 create,
628 consumeAvailable,
629 listActive,
630 revoke,
631 getByCredential,
632 getActiveById,
633 findPendingConnect,
634 recordConnectRequestClient,
635 revokeUnspentByProofKey,
636 } satisfies AuthPairingLinkRepository["Service"];
637 });
638
639 export const layer = Layer.effect(AuthPairingLinkRepository, make);