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

PairingGrantStore.ts

875 lines30.5 KB

1import {
2 AuthStandardClientScopes,
3 type AuthClientMetadata,
4 type AuthConnectDevice,
5 type AuthEnvironmentScope,
6 type AuthMcpClientAccess,
7 type AuthPairingLink,
8 mcpApprovalCode,
9 PAIRING_CODE_ALPHABET,
10 PAIRING_CODE_LENGTH,
11 parseMcpApprovalCode,
12 type ServerAuthBootstrapMethod,
13 connectDeviceVerificationCode,
14} from "@t3tools/contracts";
15import {
16 DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS,
17 isValidDesktopBootstrapToken,
18} from "@t3tools/shared/desktopBootstrapToken";
19import * as Context from "effect/Context";
20import * as SecureRandom from "effect/crypto/SecureRandom";
21import * as DateTime from "effect/DateTime";
22import * as Duration from "effect/Duration";
23import * as Mac from "effect/crypto/Mac";
24import * as Effect from "effect/Effect";
25import * as Layer from "effect/Layer";
26import * as Option from "effect/Option";
27import * as PubSub from "effect/PubSub";
28import * as Ref from "effect/Ref";
29import * as Schema from "effect/Schema";
30import * as Stream from "effect/Stream";
31​
32import * as ServerConfig from "../config.ts";
33import * as AuthConnectDevices from "../persistence/AuthConnectDevices.ts";
34import * as AuthPairingLinks from "../persistence/AuthPairingLinks.ts";
35​
36export interface BootstrapGrant {
37 readonly method: ServerAuthBootstrapMethod;
38 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
39 readonly subject: string;
40 readonly label?: string;
41 readonly proofKeyThumbprint?: string;
42 readonly expiresAt: DateTime.DateTime;
44​
45export class UnknownBootstrapCredentialError extends Schema.TaggedError<UnknownBootstrapCredentialError>()(
46 "UnknownBootstrapCredentialError",
47 {},
48) {
49 override get message(): string {
50 return "Unknown bootstrap credential.";
51 }
53​
54export class ExpiredBootstrapCredentialError extends Schema.TaggedError<ExpiredBootstrapCredentialError>()(
55 "ExpiredBootstrapCredentialError",
56 {},
57) {
58 override get message(): string {
59 return "Bootstrap credential expired.";
60 }
62​
63export class BootstrapCredentialProofKeyMismatchError extends Schema.TaggedError<BootstrapCredentialProofKeyMismatchError>()(
64 "BootstrapCredentialProofKeyMismatchError",
65 {},
66) {
67 override get message(): string {
68 return "Bootstrap credential proof key mismatch.";
69 }
71​
72export class UnavailableBootstrapCredentialError extends Schema.TaggedError<UnavailableBootstrapCredentialError>()(
73 "UnavailableBootstrapCredentialError",
74 {},
75) {
76 override get message(): string {
77 return "Bootstrap credential is no longer available.";
78 }
80​
81export class BootstrapCredentialScopeNotGrantedError extends Schema.TaggedError<BootstrapCredentialScopeNotGrantedError>()(
82 "BootstrapCredentialScopeNotGrantedError",
83 {},
84) {
85 override get message(): string {
86 return "The requested authentication scope was not granted.";
87 }
89​
90/** The credential is valid but its T3 Connect device key still waits for approval. */
91export class BootstrapCredentialConnectApprovalPendingError extends Schema.TaggedError<BootstrapCredentialConnectApprovalPendingError>()(
92 "BootstrapCredentialConnectApprovalPendingError",
93 {
94 pairingLinkId: Schema.String,
95 },
96) {
97 override get message(): string {
98 return "This T3 Connect device is waiting for approval.";
99 }
101​
102export const BootstrapCredentialInvalidError = Schema.Union([
103 UnknownBootstrapCredentialError,
104 ExpiredBootstrapCredentialError,
105 BootstrapCredentialProofKeyMismatchError,
106 UnavailableBootstrapCredentialError,
107 BootstrapCredentialConnectApprovalPendingError,
108]);
109export type BootstrapCredentialInvalidError = typeof BootstrapCredentialInvalidError.Type;
110​
111export class ActivePairingLinksLoadError extends Schema.TaggedError<ActivePairingLinksLoadError>()(
112 "ActivePairingLinksLoadError",
113 {
114 cause: Schema.Defect(),
115 },
116) {
117 override get message(): string {
118 return "Failed to load active pairing links.";
119 }
121​
122export class PairingLinkRevokeError extends Schema.TaggedError<PairingLinkRevokeError>()(
123 "PairingLinkRevokeError",
124 {
125 pairingLinkId: Schema.String,
126 cause: Schema.Defect(),
127 },
128) {
129 override get message(): string {
130 return `Failed to revoke pairing link '${this.pairingLinkId}'.`;
131 }
133​
134export class PairingCredentialIssueError extends Schema.TaggedError<PairingCredentialIssueError>()(
135 "PairingCredentialIssueError",
136 {
137 pairingLinkId: Schema.String,
138 subject: Schema.String,
139 label: Schema.optional(Schema.String),
140 cause: Schema.Defect(),
141 },
142) {
143 override get message(): string {
144 return `Failed to issue pairing credential '${this.pairingLinkId}' for '${this.subject}'.`;
145 }
147​
148export class PairingCredentialRandomGenerationError extends Schema.TaggedError<PairingCredentialRandomGenerationError>()(
149 "PairingCredentialRandomGenerationError",
150 {
151 operation: Schema.Literals(["generate-id", "generate-token"]),
152 cause: Schema.Defect(),
153 },
154) {
155 override get message(): string {
156 return `Failed to generate pairing credential data during '${this.operation}'.`;
157 }
159​
160export class BootstrapCredentialConsumeError extends Schema.TaggedError<BootstrapCredentialConsumeError>()(
161 "BootstrapCredentialConsumeError",
162 {
163 cause: Schema.Defect(),
164 },
165) {
166 override get message(): string {
167 return "Failed to consume bootstrap credential.";
168 }
170​
171export class BootstrapCredentialConsumeAvailableError extends Schema.TaggedError<BootstrapCredentialConsumeAvailableError>()(
172 "BootstrapCredentialConsumeAvailableError",
173 {
174 cause: Schema.Defect(),
175 },
176) {
177 override get message(): string {
178 return "Failed to atomically consume an available bootstrap credential.";
179 }
181​
182export class ConnectDevicesError extends Schema.TaggedError<ConnectDevicesError>()(
183 "ConnectDevicesError",
184 {
185 operation: Schema.Literals(["list", "trust", "revoke", "record-request"]),
186 cause: Schema.Defect(),
187 },
188) {
189 override get message(): string {
190 return `Failed to ${this.operation} T3 Connect devices.`;
191 }
193​
194export class BootstrapCredentialLookupError extends Schema.TaggedError<BootstrapCredentialLookupError>()(
195 "BootstrapCredentialLookupError",
196 {
197 cause: Schema.Defect(),
198 },
199) {
200 override get message(): string {
201 return "Failed to look up bootstrap credential state.";
202 }
204​
205export const BootstrapCredentialInternalError = Schema.Union([
206 ActivePairingLinksLoadError,
207 PairingLinkRevokeError,
208 PairingCredentialIssueError,
209 PairingCredentialRandomGenerationError,
210 BootstrapCredentialConsumeError,
211 BootstrapCredentialConsumeAvailableError,
212 BootstrapCredentialLookupError,
213 ConnectDevicesError,
214]);
215export type BootstrapCredentialInternalError = typeof BootstrapCredentialInternalError.Type;
216export const isBootstrapCredentialInternalError = Schema.is(BootstrapCredentialInternalError);
217​
218export const BootstrapCredentialError = Schema.Union([
219 BootstrapCredentialInvalidError,
220 BootstrapCredentialInternalError,
221 BootstrapCredentialScopeNotGrantedError,
222]);
223export type BootstrapCredentialError = typeof BootstrapCredentialError.Type;
224​
225export interface IssuedBootstrapCredential {
226 readonly id: string;
227 readonly credential: string;
228 readonly label?: string;
229 readonly proofKeyThumbprint?: string;
230 readonly expiresAt: DateTime.Utc;
232​
233export type BootstrapCredentialChange =
234 | {
235 readonly type: "pairingLinkUpserted";
236 readonly pairingLink: AuthPairingLink;
237 }
238 | {
239 readonly type: "pairingLinkRemoved";
240 readonly id: string;
241 }
242 | {
243 readonly type: "connectDevicesChanged";
244 };
245​
246export class PairingGrantStore extends Context.Service<
247 PairingGrantStore,
248 {
249 readonly issueOneTimeToken: (input?: {
250 readonly ttl?: Duration.Duration;
251 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
252 readonly subject?: string;
253 readonly label?: string;
254 readonly proofKeyThumbprint?: string;
255 readonly purpose?: "startup";
256 /** Issues a hidden `<LEVEL>-` code that only an agent sign-in at this level can spend. */
257 readonly mcpApproval?: AuthMcpClientAccess;
258 /** Spendable only after someone trusts `proofKeyThumbprint` as a T3 Connect device. */
259 readonly requiresConnectApproval?: boolean;
260 }) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialInternalError>;
261 /** A device's open or denied request, reused so retries keep one request and one code. */
262 readonly findPendingConnect: (
263 proofKeyThumbprint: string,
264 ) => Effect.Effect<Option.Option<IssuedBootstrapCredential>, BootstrapCredentialInternalError>;
265 /** Shows approvers what a waiting device says it is. Only its first description sticks. */
266 readonly recordConnectRequestClient: (
267 pairingLinkId: string,
268 client: AuthClientMetadata,
269 ) => Effect.Effect<void, BootstrapCredentialInternalError>;
270 /** Trusts the device key behind a waiting request. False when it is gone or not a request. */
271 readonly approveConnectRequest: (
272 pairingLinkId: string,
273 ) => Effect.Effect<boolean, BootstrapCredentialInternalError>;
274 readonly isConnectDeviceTrusted: (
275 proofKeyThumbprint: string,
276 ) => Effect.Effect<boolean, BootstrapCredentialInternalError>;
277 readonly trustConnectDevice: (
278 proofKeyThumbprint: string,
279 client: AuthClientMetadata,
280 ) => Effect.Effect<void, BootstrapCredentialInternalError>;
281 readonly listConnectDevices: () => Effect.Effect<
282 ReadonlyArray<AuthConnectDevice>,
283 BootstrapCredentialInternalError
284 >;
285 readonly revokeConnectDevice: (
286 proofKeyThumbprint: string,
287 ) => Effect.Effect<boolean, BootstrapCredentialInternalError>;
288 readonly revokeConnectDevicesExcept: (
289 keepProofKeyThumbprint: string | null,
290 ) => Effect.Effect<number, BootstrapCredentialInternalError>;
291 readonly listActive: () => Effect.Effect<
292 ReadonlyArray<AuthPairingLink>,
293 BootstrapCredentialInternalError
294 >;
295 readonly streamChanges: Stream.Stream<BootstrapCredentialChange>;
296 readonly revoke: (id: string) => Effect.Effect<boolean, BootstrapCredentialInternalError>;
297 readonly consume: (
298 credential: string,
299 input?: {
300 readonly proofKeyThumbprint?: string;
301 readonly requestedScopes?: ReadonlyArray<AuthEnvironmentScope>;
302 /** All scopes must be granted; requestedScopes only requires an overlap for OAuth. */
303 readonly requiredScopes?: ReadonlyArray<AuthEnvironmentScope>;
304 /** Also spends a code issued for an agent sign-in at this level; others refuse them. */
305 readonly mcpApproval?: AuthMcpClientAccess;
306 },
307 ) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;
308 }
309>()("t3/auth/PairingGrantStore") {}
310​
311interface StoredBootstrapGrant extends BootstrapGrant {
312 readonly remainingUses: number | "unbounded";
314​
315type ConsumeResult =
316 | {
317 readonly _tag: "error";
318 readonly reason: "not-found" | "expired" | "scope-not-granted";
319 readonly error: BootstrapCredentialError;
320 }
321 | {
322 readonly _tag: "success";
323 readonly grant: BootstrapGrant;
324 };
325​
326const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
327​
328const toPairingLink = (row: AuthPairingLinks.AuthPairingLinkRecord): AuthPairingLink => ({
329 id: row.id,
330 scopes: row.scopes,
331 subject: row.subject,
332 ...(row.label ? { label: row.label } : {}),
333 createdAt: row.createdAt,
334 expiresAt: row.expiresAt,
335 ...(row.requiresConnectApproval === 1 && row.proofKeyThumbprint
336 ? {
337 connectDeviceRequest: {
338 verificationCode: connectDeviceVerificationCode(row.proofKeyThumbprint),
339 ...(row.requestedClient ? { client: row.requestedClient } : {}),
340 },
341 }
342 : {}),
343});
344const DESKTOP_BOOTSTRAP_TTL_HOURS = Duration.hours(24);
345const DEV_STARTUP_TTL_HOURS = Duration.hours(24);
346const PAIRING_TOKEN_REJECTION_LIMIT =
347 Math.floor(256 / PAIRING_CODE_ALPHABET.length) * PAIRING_CODE_ALPHABET.length;
348​
349const PAIRING_TOKEN_PATTERN = new RegExp(
350 `^[${PAIRING_CODE_ALPHABET}]{${PAIRING_CODE_LENGTH}}$`,
351 "i",
352);
353​
354const make = Effect.gen(function* () {
355 const random = yield* SecureRandom.SecureRandom;
356 const config = yield* ServerConfig.ServerConfig;
357 const pairingLinks = yield* AuthPairingLinks.AuthPairingLinkRepository;
358 const connectDevices = yield* AuthConnectDevices.AuthConnectDeviceRepository;
359 const seededGrantsRef = yield* Ref.make(new Map<string, StoredBootstrapGrant>());
360 const changesPubSub = yield* PubSub.unbounded<BootstrapCredentialChange>();
361 const generatePairingToken = Effect.gen(function* () {
362 let credential = "";
363 while (credential.length < PAIRING_CODE_LENGTH) {
364 const bytes = yield* random
365 .randomBytes(PAIRING_CODE_LENGTH)
366 .pipe(
367 Effect.mapError(
368 (cause) =>
369 new PairingCredentialRandomGenerationError({ operation: "generate-token", cause }),
370 ),
371 );
372 for (const byte of bytes) {
373 if (byte >= PAIRING_TOKEN_REJECTION_LIMIT) {
374 continue;
375 }
376 credential += PAIRING_CODE_ALPHABET[byte % PAIRING_CODE_ALPHABET.length]!;
377 if (credential.length === PAIRING_CODE_LENGTH) {
378 return credential;
379 }
380 }
381 }
382 return credential;
383 });
384​
385 const seedGrant = (credential: string, grant: StoredBootstrapGrant) =>
386 Ref.update(seededGrantsRef, (current) => {
387 const next = new Map(current);
388 next.set(credential, grant);
389 return next;
390 });
391​
392 const emitUpsert = (pairingLink: AuthPairingLink) =>
393 PubSub.publish(changesPubSub, {
394 type: "pairingLinkUpserted",
395 pairingLink,
396 }).pipe(Effect.asVoid);
397​
398 const emitRemoved = (id: string) =>
399 PubSub.publish(changesPubSub, {
400 type: "pairingLinkRemoved",
401 id,
402 }).pipe(Effect.asVoid);
403​
404 // Accept tokens derived from the rotating desktop secret; older desktops send only a token.
405 const desktopBootstrapSecret = config.desktopBootstrapSecret;
406 const mac = yield* Mac.Mac;
407 const consumeRotatingDesktopToken = (credential: string, nowMs: number) =>
408 desktopBootstrapSecret === undefined
409 ? Effect.succeed(false)
410 : isValidDesktopBootstrapToken(desktopBootstrapSecret, credential, nowMs).pipe(
411 Effect.provideService(Mac.Mac, mac),
412 );
413​
414 if (config.desktopBootstrapToken && desktopBootstrapSecret === undefined) {
415 const now = yield* DateTime.now;
416 yield* seedGrant(config.desktopBootstrapToken, {
417 method: "desktop-bootstrap",
418 scopes: AuthStandardClientScopes,
419 subject: "desktop-bootstrap",
420 expiresAt: DateTime.add(now, {
421 milliseconds: Duration.toMillis(DESKTOP_BOOTSTRAP_TTL_HOURS),
422 }),
423 // Reloads and expired bearer sessions must be able to re-exchange the desktop seed.
424 remainingUses: "unbounded",
425 });
426 }
427​
428 const listActive: PairingGrantStore["Service"]["listActive"] = Effect.fn(
429 "PairingGrantStore.listActive",
430 )(
431 function* () {
432 const now = yield* DateTime.now;
433 const rows = yield* pairingLinks.listActive({ now });
434 // An approved request only waits for its device to come back and spend it.
435 return rows
436 .filter((row) => !(row.requiresConnectApproval === 1 && row.connectApproved === 1))
437 .map(toPairingLink);
438 },
439 Effect.mapError((cause) => new ActivePairingLinksLoadError({ cause })),
440 );
441​
442 const revoke: PairingGrantStore["Service"]["revoke"] = Effect.fn("PairingGrantStore.revoke")(
443 function* (id) {
444 const revokedAt = yield* DateTime.now;
445 const revoked = yield* pairingLinks
446 .revoke({
447 id,
448 revokedAt,
449 })
450 .pipe(Effect.mapError((cause) => new PairingLinkRevokeError({ pairingLinkId: id, cause })));
451 if (revoked) {
452 yield* emitRemoved(id);
453 }
454 return revoked;
455 },
456 );
457​
458 const issueOneTimeToken: PairingGrantStore["Service"]["issueOneTimeToken"] = Effect.fn(
459 "PairingGrantStore.issueOneTimeToken",
460 )(function* (input) {
461 const id = yield* random
462 .uuidV4()
463 .pipe(
464 Effect.mapError(
465 (cause) =>
466 new PairingCredentialRandomGenerationError({ operation: "generate-id", cause }),
467 ),
468 );
469 const token = yield* generatePairingToken;
470 const mcpApproval = input?.mcpApproval;
471 const credential = mcpApproval ? mcpApprovalCode(mcpApproval, token) : token;
472 const isDevStartupToken = config.devUrl !== undefined && input?.purpose === "startup";
473 const ttl =
474 input?.ttl ??
475 (isDevStartupToken ? DEV_STARTUP_TTL_HOURS : DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES);
476 const now = yield* DateTime.now;
477 const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });
478 const issued: IssuedBootstrapCredential = {
479 id,
480 credential,
481 ...(input?.label ? { label: input.label } : {}),
482 ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
483 expiresAt,
484 };
485 const subject = mcpApproval
486 ? `${AuthPairingLinks.MCP_APPROVAL_SUBJECT_PREFIX}${mcpApproval}`
487 : (input?.subject ?? "one-time-token");
488 yield* pairingLinks
489 .create({
490 id,
491 credential,
492 method: "one-time-token",
493 scopes: input?.scopes ?? AuthStandardClientScopes,
494 subject,
495 label: input?.label ?? null,
496 proofKeyThumbprint: input?.proofKeyThumbprint ?? null,
497 ...(input?.requiresConnectApproval ? { requiresConnectApproval: true } : {}),
498 createdAt: now,
499 expiresAt: expiresAt,
500 })
501 .pipe(
502 Effect.mapError(
503 (cause) =>
504 new PairingCredentialIssueError({
505 pairingLinkId: id,
506 subject,
507 ...(input?.label ? { label: input.label } : {}),
508 cause,
509 }),
510 ),
511 );
512 // Approval codes stay out of the pairing links and QR codes that clients show.
513 if (!mcpApproval) {
514 yield* emitUpsert({
515 id,
516 scopes: input?.scopes ?? AuthStandardClientScopes,
517 subject,
518 ...(input?.label ? { label: input.label } : {}),
519 createdAt: now,
520 expiresAt,
521 ...(input?.requiresConnectApproval && input.proofKeyThumbprint
522 ? {
523 connectDeviceRequest: {
524 verificationCode: connectDeviceVerificationCode(input.proofKeyThumbprint),
525 },
526 }
527 : {}),
528 });
529 }
530 return issued;
531 });
532​
533 const consume: PairingGrantStore["Service"]["consume"] = Effect.fn("PairingGrantStore.consume")(
534 function* (credential, input) {
535 const now = yield* DateTime.now;
536 if (yield* consumeRotatingDesktopToken(credential, now.epochMilliseconds)) {
537 return {
538 method: "desktop-bootstrap",
539 scopes: AuthStandardClientScopes,
540 subject: "desktop-bootstrap",
541 expiresAt: DateTime.add(now, {
542 milliseconds: DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS,
543 }),
544 } satisfies BootstrapGrant;
545 }
546 const seededResult: ConsumeResult = yield* Ref.modify(
547 seededGrantsRef,
548 (current): readonly [ConsumeResult, Map<string, StoredBootstrapGrant>] => {
549 const grant = current.get(credential);
550 if (!grant) {
551 return [
552 {
553 _tag: "error",
554 reason: "not-found",
555 error: new UnknownBootstrapCredentialError({}),
556 },
557 current,
558 ];
559 }
560​
561 const next = new Map(current);
562 if (DateTime.isGreaterThanOrEqualTo(now, grant.expiresAt)) {
563 next.delete(credential);
564 return [
565 {
566 _tag: "error",
567 reason: "expired",
568 error: new ExpiredBootstrapCredentialError({}),
569 },
570 next,
571 ];
572 }
573​
574 if (grant.proofKeyThumbprint && grant.proofKeyThumbprint !== input?.proofKeyThumbprint) {
575 return [
576 {
577 _tag: "error",
578 reason: "not-found",
579 error: new BootstrapCredentialProofKeyMismatchError({}),
580 },
581 next,
582 ];
583 }
584​
585 if (
586 (input?.requestedScopes !== undefined &&
587 !input.requestedScopes.some((scope) => grant.scopes.includes(scope))) ||
588 (input?.requiredScopes !== undefined &&
589 !input.requiredScopes.every((scope) => grant.scopes.includes(scope)))
590 ) {
591 return [
592 {
593 _tag: "error",
594 reason: "scope-not-granted",
595 error: new BootstrapCredentialScopeNotGrantedError({}),
596 },
597 current,
598 ];
599 }
600​
601 const remainingUses = grant.remainingUses;
602 if (typeof remainingUses === "number") {
603 if (remainingUses <= 1) {
604 next.delete(credential);
605 } else {
606 next.set(credential, {
607 ...grant,
608 remainingUses: remainingUses - 1,
609 });
610 }
611 }
612​
613 return [
614 {
615 _tag: "success",
616 grant: {
617 method: grant.method,
618 scopes: grant.scopes,
619 subject: grant.subject,
620 ...(grant.label ? { label: grant.label } : {}),
621 ...(grant.proofKeyThumbprint
622 ? { proofKeyThumbprint: grant.proofKeyThumbprint }
623 : {}),
624 expiresAt: grant.expiresAt,
625 } satisfies BootstrapGrant,
626 },
627 next,
628 ];
629 },
630 );
631​
632 if (seededResult._tag === "success") {
633 return seededResult.grant;
634 }
635 if (seededResult.reason !== "not-found") {
636 return yield* seededResult.error;
637 }
638​
639 // Only credentials in the issued pairing-code formats are case-insensitive.
640 // People type codes in groups such as XXXX-XXXX-XXXX.
641 const compactCredential = credential.replace(/[\s-]/g, "");
642 const pairingCredential = PAIRING_TOKEN_PATTERN.test(compactCredential)
643 ? compactCredential.toUpperCase()
644 : (parseMcpApprovalCode(credential)?.code ?? credential);
645​
646 // Check scopes in the UPDATE so rejected requests cannot spend one-time links.
647 const consumed = yield* pairingLinks
648 .consumeAvailable({
649 credential: pairingCredential,
650 proofKeyThumbprint: input?.proofKeyThumbprint ?? null,
651 ...(input?.requestedScopes !== undefined
652 ? { requestedScopes: input.requestedScopes }
653 : {}),
654 ...(input?.requiredScopes !== undefined ? { requiredScopes: input.requiredScopes } : {}),
655 ...(input?.mcpApproval
656 ? {
657 mcpApprovalSubject: `${AuthPairingLinks.MCP_APPROVAL_SUBJECT_PREFIX}${input.mcpApproval}`,
658 }
659 : {}),
660 consumedAt: now,
661 now,
662 })
663 .pipe(Effect.mapError((cause) => new BootstrapCredentialConsumeAvailableError({ cause })));
664​
665 if (Option.isSome(consumed)) {
666 if (!consumed.value.subject.startsWith(AuthPairingLinks.MCP_APPROVAL_SUBJECT_PREFIX)) {
667 yield* emitRemoved(consumed.value.id);
668 }
669 return {
670 method: consumed.value.method,
671 scopes: consumed.value.scopes,
672 subject: consumed.value.subject,
673 ...(consumed.value.label ? { label: consumed.value.label } : {}),
674 ...(consumed.value.proofKeyThumbprint
675 ? { proofKeyThumbprint: consumed.value.proofKeyThumbprint }
676 : {}),
677 expiresAt: consumed.value.expiresAt,
678 } satisfies BootstrapGrant;
679 }
680​
681 const matching = yield* pairingLinks
682 .getByCredential({ credential: pairingCredential })
683 .pipe(Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause })));
684 if (Option.isNone(matching)) {
685 return yield* new UnknownBootstrapCredentialError({});
686 }
687​
688 if (matching.value.revokedAt !== null) {
689 return yield* new UnavailableBootstrapCredentialError({});
690 }
691​
692 if (matching.value.consumedAt !== null) {
693 return yield* new UnknownBootstrapCredentialError({});
694 }
695​
696 if (DateTime.isGreaterThanOrEqualTo(now, matching.value.expiresAt)) {
697 return yield* new ExpiredBootstrapCredentialError({});
698 }
699​
700 if (
701 matching.value.proofKeyThumbprint !== null &&
702 matching.value.proofKeyThumbprint !== input?.proofKeyThumbprint
703 ) {
704 return yield* new BootstrapCredentialProofKeyMismatchError({});
705 }
706​
707 if (
708 (input?.requestedScopes !== undefined &&
709 !input.requestedScopes.some((scope) => matching.value.scopes.includes(scope))) ||
710 (input?.requiredScopes !== undefined &&
711 !input.requiredScopes.every((scope) => matching.value.scopes.includes(scope)))
712 ) {
713 return yield* new BootstrapCredentialScopeNotGrantedError({});
714 }
715​
716 if (matching.value.requiresConnectApproval === 1 && matching.value.connectApproved === 0) {
717 return yield* new BootstrapCredentialConnectApprovalPendingError({
718 pairingLinkId: matching.value.id,
719 });
720 }
721​
722 return yield* new UnavailableBootstrapCredentialError({});
723 },
724 );
725​
726 const emitConnectDevicesChanged = PubSub.publish(changesPubSub, {
727 type: "connectDevicesChanged",
728 }).pipe(Effect.asVoid);
729​
730 const findPendingConnect: PairingGrantStore["Service"]["findPendingConnect"] = Effect.fn(
731 "PairingGrantStore.findPendingConnect",
732 )(
733 function* (proofKeyThumbprint) {
734 const now = yield* DateTime.now;
735 const row = yield* pairingLinks.findPendingConnect({ proofKeyThumbprint, now });
736 return Option.map(row, (link): IssuedBootstrapCredential => ({
737 id: link.id,
738 credential: link.credential,
739 ...(link.label ? { label: link.label } : {}),
740 proofKeyThumbprint,
741 expiresAt: link.expiresAt,
742 }));
743 },
744 Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause })),
745 );
746​
747 const recordConnectRequestClient: PairingGrantStore["Service"]["recordConnectRequestClient"] =
748 Effect.fn("PairingGrantStore.recordConnectRequestClient")(function* (pairingLinkId, client) {
749 const recorded = yield* pairingLinks
750 .recordConnectRequestClient({ id: pairingLinkId, client })
751 .pipe(
752 Effect.mapError(
753 (cause) => new ConnectDevicesError({ operation: "record-request", cause }),
754 ),
755 );
756 if (!recorded) return;
757 const now = yield* DateTime.now;
758 const row = yield* pairingLinks
759 .getActiveById({ id: pairingLinkId, now })
760 .pipe(Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause })));
761 if (Option.isSome(row)) yield* emitUpsert(toPairingLink(row.value));
762 });
763​
764 const trustConnectDevice: PairingGrantStore["Service"]["trustConnectDevice"] = Effect.fn(
765 "PairingGrantStore.trustConnectDevice",
766 )(function* (proofKeyThumbprint, client) {
767 const approvedAt = yield* DateTime.now;
768 yield* connectDevices
769 .trust({ proofKeyThumbprint, client, approvedAt })
770 .pipe(Effect.mapError((cause) => new ConnectDevicesError({ operation: "trust", cause })));
771 yield* emitConnectDevicesChanged;
772 });
773​
774 const approveConnectRequest: PairingGrantStore["Service"]["approveConnectRequest"] = Effect.fn(
775 "PairingGrantStore.approveConnectRequest",
776 )(function* (pairingLinkId) {
777 const now = yield* DateTime.now;
778 const row = yield* pairingLinks
779 .getActiveById({ id: pairingLinkId, now })
780 .pipe(Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause })));
781 if (
782 Option.isNone(row) ||
783 row.value.requiresConnectApproval !== 1 ||
784 row.value.proofKeyThumbprint === null
785 ) {
786 return false;
787 }
788 yield* connectDevices
789 .trust({
790 proofKeyThumbprint: row.value.proofKeyThumbprint,
791 client: row.value.requestedClient,
792 approvedAt: now,
793 })
794 .pipe(Effect.mapError((cause) => new ConnectDevicesError({ operation: "trust", cause })));
795 yield* emitRemoved(pairingLinkId);
796 yield* emitConnectDevicesChanged;
797 return true;
798 });
799​
800 const isConnectDeviceTrusted: PairingGrantStore["Service"]["isConnectDeviceTrusted"] = (
801 proofKeyThumbprint,
802 ) =>
803 connectDevices
804 .isTrusted(proofKeyThumbprint)
805 .pipe(Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause })));
806​
807 const listConnectDevices: PairingGrantStore["Service"]["listConnectDevices"] = () =>
808 connectDevices.list().pipe(
809 Effect.map((rows) =>
810 rows.map((row): AuthConnectDevice => ({
811 proofKeyThumbprint: row.proofKeyThumbprint,
812 verificationCode: connectDeviceVerificationCode(row.proofKeyThumbprint),
813 ...(row.client ? { client: row.client } : {}),
814 approvedAt: row.approvedAt,
815 })),
816 ),
817 Effect.mapError((cause) => new ConnectDevicesError({ operation: "list", cause })),
818 );
819​
820 // A credential minted before revocation is still spendable; it must die with the trust,
821 // or exchanging it would trust the key again without approval.
822 const revokeUnspentLinks = Effect.fn("PairingGrantStore.revokeUnspentLinks")(function* (
823 input: Omit<AuthPairingLinks.RevokeUnspentByProofKeyInput, "revokedAt">,
824 ) {
825 const revokedAt = yield* DateTime.now;
826 const ids = yield* pairingLinks
827 .revokeUnspentByProofKey({ ...input, revokedAt })
828 .pipe(Effect.mapError((cause) => new ConnectDevicesError({ operation: "revoke", cause })));
829 yield* Effect.forEach(ids, emitRemoved, { discard: true });
830 });
831​
832 const revokeConnectDevice: PairingGrantStore["Service"]["revokeConnectDevice"] = Effect.fn(
833 "PairingGrantStore.revokeConnectDevice",
834 )(function* (proofKeyThumbprint) {
835 yield* revokeUnspentLinks({ proofKeyThumbprint, keepProofKeyThumbprint: null });
836 const removed = yield* connectDevices
837 .remove(proofKeyThumbprint)
838 .pipe(Effect.mapError((cause) => new ConnectDevicesError({ operation: "revoke", cause })));
839 if (removed) yield* emitConnectDevicesChanged;
840 return removed;
841 });
842​
843 const revokeConnectDevicesExcept: PairingGrantStore["Service"]["revokeConnectDevicesExcept"] =
844 Effect.fn("PairingGrantStore.revokeConnectDevicesExcept")(function* (keepProofKeyThumbprint) {
845 yield* revokeUnspentLinks({ proofKeyThumbprint: null, keepProofKeyThumbprint });
846 const removed = yield* connectDevices
847 .removeAllExcept(keepProofKeyThumbprint)
848 .pipe(Effect.mapError((cause) => new ConnectDevicesError({ operation: "revoke", cause })));
849 if (removed > 0) yield* emitConnectDevicesChanged;
850 return removed;
851 });
852​
853 return PairingGrantStore.of({
854 issueOneTimeToken,
855 findPendingConnect,
856 recordConnectRequestClient,
857 approveConnectRequest,
858 isConnectDeviceTrusted,
859 trustConnectDevice,
860 listConnectDevices,
861 revokeConnectDevice,
862 revokeConnectDevicesExcept,
863 listActive,
864 get streamChanges() {
865 return Stream.fromPubSub(changesPubSub);
866 },
867 revoke,
868 consume,
869 });
870});
871​
872export const layer = Layer.effect(PairingGrantStore, make).pipe(
873 Layer.provideMerge(AuthPairingLinks.layer),
874 Layer.provideMerge(AuthConnectDevices.layer),
875);