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

PairingGrantStore.ts

873 lines30.4 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 const pairingCredential = PAIRING_TOKEN_PATTERN.test(credential)
641 ? credential.toUpperCase()
642 : (parseMcpApprovalCode(credential)?.code ?? credential);
643​
644 // Check scopes in the UPDATE so rejected requests cannot spend one-time links.
645 const consumed = yield* pairingLinks
646 .consumeAvailable({
647 credential: pairingCredential,
648 proofKeyThumbprint: input?.proofKeyThumbprint ?? null,
649 ...(input?.requestedScopes !== undefined
650 ? { requestedScopes: input.requestedScopes }
651 : {}),
652 ...(input?.requiredScopes !== undefined ? { requiredScopes: input.requiredScopes } : {}),
653 ...(input?.mcpApproval
654 ? {
655 mcpApprovalSubject: `${AuthPairingLinks.MCP_APPROVAL_SUBJECT_PREFIX}${input.mcpApproval}`,
656 }
657 : {}),
658 consumedAt: now,
659 now,
660 })
661 .pipe(Effect.mapError((cause) => new BootstrapCredentialConsumeAvailableError({ cause })));
662​
663 if (Option.isSome(consumed)) {
664 if (!consumed.value.subject.startsWith(AuthPairingLinks.MCP_APPROVAL_SUBJECT_PREFIX)) {
665 yield* emitRemoved(consumed.value.id);
666 }
667 return {
668 method: consumed.value.method,
669 scopes: consumed.value.scopes,
670 subject: consumed.value.subject,
671 ...(consumed.value.label ? { label: consumed.value.label } : {}),
672 ...(consumed.value.proofKeyThumbprint
673 ? { proofKeyThumbprint: consumed.value.proofKeyThumbprint }
674 : {}),
675 expiresAt: consumed.value.expiresAt,
676 } satisfies BootstrapGrant;
677 }
678​
679 const matching = yield* pairingLinks
680 .getByCredential({ credential: pairingCredential })
681 .pipe(Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause })));
682 if (Option.isNone(matching)) {
683 return yield* new UnknownBootstrapCredentialError({});
684 }
685​
686 if (matching.value.revokedAt !== null) {
687 return yield* new UnavailableBootstrapCredentialError({});
688 }
689​
690 if (matching.value.consumedAt !== null) {
691 return yield* new UnknownBootstrapCredentialError({});
692 }
693​
694 if (DateTime.isGreaterThanOrEqualTo(now, matching.value.expiresAt)) {
695 return yield* new ExpiredBootstrapCredentialError({});
696 }
697​
698 if (
699 matching.value.proofKeyThumbprint !== null &&
700 matching.value.proofKeyThumbprint !== input?.proofKeyThumbprint
701 ) {
702 return yield* new BootstrapCredentialProofKeyMismatchError({});
703 }
704​
705 if (
706 (input?.requestedScopes !== undefined &&
707 !input.requestedScopes.some((scope) => matching.value.scopes.includes(scope))) ||
708 (input?.requiredScopes !== undefined &&
709 !input.requiredScopes.every((scope) => matching.value.scopes.includes(scope)))
710 ) {
711 return yield* new BootstrapCredentialScopeNotGrantedError({});
712 }
713​
714 if (matching.value.requiresConnectApproval === 1 && matching.value.connectApproved === 0) {
715 return yield* new BootstrapCredentialConnectApprovalPendingError({
716 pairingLinkId: matching.value.id,
717 });
718 }
719​
720 return yield* new UnavailableBootstrapCredentialError({});
721 },
722 );
723​
724 const emitConnectDevicesChanged = PubSub.publish(changesPubSub, {
725 type: "connectDevicesChanged",
726 }).pipe(Effect.asVoid);
727​
728 const findPendingConnect: PairingGrantStore["Service"]["findPendingConnect"] = Effect.fn(
729 "PairingGrantStore.findPendingConnect",
730 )(
731 function* (proofKeyThumbprint) {
732 const now = yield* DateTime.now;
733 const row = yield* pairingLinks.findPendingConnect({ proofKeyThumbprint, now });
734 return Option.map(row, (link): IssuedBootstrapCredential => ({
735 id: link.id,
736 credential: link.credential,
737 ...(link.label ? { label: link.label } : {}),
738 proofKeyThumbprint,
739 expiresAt: link.expiresAt,
740 }));
741 },
742 Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause })),
743 );
744​
745 const recordConnectRequestClient: PairingGrantStore["Service"]["recordConnectRequestClient"] =
746 Effect.fn("PairingGrantStore.recordConnectRequestClient")(function* (pairingLinkId, client) {
747 const recorded = yield* pairingLinks
748 .recordConnectRequestClient({ id: pairingLinkId, client })
749 .pipe(
750 Effect.mapError(
751 (cause) => new ConnectDevicesError({ operation: "record-request", cause }),
752 ),
753 );
754 if (!recorded) return;
755 const now = yield* DateTime.now;
756 const row = yield* pairingLinks
757 .getActiveById({ id: pairingLinkId, now })
758 .pipe(Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause })));
759 if (Option.isSome(row)) yield* emitUpsert(toPairingLink(row.value));
760 });
761​
762 const trustConnectDevice: PairingGrantStore["Service"]["trustConnectDevice"] = Effect.fn(
763 "PairingGrantStore.trustConnectDevice",
764 )(function* (proofKeyThumbprint, client) {
765 const approvedAt = yield* DateTime.now;
766 yield* connectDevices
767 .trust({ proofKeyThumbprint, client, approvedAt })
768 .pipe(Effect.mapError((cause) => new ConnectDevicesError({ operation: "trust", cause })));
769 yield* emitConnectDevicesChanged;
770 });
771​
772 const approveConnectRequest: PairingGrantStore["Service"]["approveConnectRequest"] = Effect.fn(
773 "PairingGrantStore.approveConnectRequest",
774 )(function* (pairingLinkId) {
775 const now = yield* DateTime.now;
776 const row = yield* pairingLinks
777 .getActiveById({ id: pairingLinkId, now })
778 .pipe(Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause })));
779 if (
780 Option.isNone(row) ||
781 row.value.requiresConnectApproval !== 1 ||
782 row.value.proofKeyThumbprint === null
783 ) {
784 return false;
785 }
786 yield* connectDevices
787 .trust({
788 proofKeyThumbprint: row.value.proofKeyThumbprint,
789 client: row.value.requestedClient,
790 approvedAt: now,
791 })
792 .pipe(Effect.mapError((cause) => new ConnectDevicesError({ operation: "trust", cause })));
793 yield* emitRemoved(pairingLinkId);
794 yield* emitConnectDevicesChanged;
795 return true;
796 });
797​
798 const isConnectDeviceTrusted: PairingGrantStore["Service"]["isConnectDeviceTrusted"] = (
799 proofKeyThumbprint,
800 ) =>
801 connectDevices
802 .isTrusted(proofKeyThumbprint)
803 .pipe(Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause })));
804​
805 const listConnectDevices: PairingGrantStore["Service"]["listConnectDevices"] = () =>
806 connectDevices.list().pipe(
807 Effect.map((rows) =>
808 rows.map((row): AuthConnectDevice => ({
809 proofKeyThumbprint: row.proofKeyThumbprint,
810 verificationCode: connectDeviceVerificationCode(row.proofKeyThumbprint),
811 ...(row.client ? { client: row.client } : {}),
812 approvedAt: row.approvedAt,
813 })),
814 ),
815 Effect.mapError((cause) => new ConnectDevicesError({ operation: "list", cause })),
816 );
817​
818 // A credential minted before revocation is still spendable; it must die with the trust,
819 // or exchanging it would trust the key again without approval.
820 const revokeUnspentLinks = Effect.fn("PairingGrantStore.revokeUnspentLinks")(function* (
821 input: Omit<AuthPairingLinks.RevokeUnspentByProofKeyInput, "revokedAt">,
822 ) {
823 const revokedAt = yield* DateTime.now;
824 const ids = yield* pairingLinks
825 .revokeUnspentByProofKey({ ...input, revokedAt })
826 .pipe(Effect.mapError((cause) => new ConnectDevicesError({ operation: "revoke", cause })));
827 yield* Effect.forEach(ids, emitRemoved, { discard: true });
828 });
829​
830 const revokeConnectDevice: PairingGrantStore["Service"]["revokeConnectDevice"] = Effect.fn(
831 "PairingGrantStore.revokeConnectDevice",
832 )(function* (proofKeyThumbprint) {
833 yield* revokeUnspentLinks({ proofKeyThumbprint, keepProofKeyThumbprint: null });
834 const removed = yield* connectDevices
835 .remove(proofKeyThumbprint)
836 .pipe(Effect.mapError((cause) => new ConnectDevicesError({ operation: "revoke", cause })));
837 if (removed) yield* emitConnectDevicesChanged;
838 return removed;
839 });
840​
841 const revokeConnectDevicesExcept: PairingGrantStore["Service"]["revokeConnectDevicesExcept"] =
842 Effect.fn("PairingGrantStore.revokeConnectDevicesExcept")(function* (keepProofKeyThumbprint) {
843 yield* revokeUnspentLinks({ proofKeyThumbprint: null, keepProofKeyThumbprint });
844 const removed = yield* connectDevices
845 .removeAllExcept(keepProofKeyThumbprint)
846 .pipe(Effect.mapError((cause) => new ConnectDevicesError({ operation: "revoke", cause })));
847 if (removed > 0) yield* emitConnectDevicesChanged;
848 return removed;
849 });
850​
851 return PairingGrantStore.of({
852 issueOneTimeToken,
853 findPendingConnect,
854 recordConnectRequestClient,
855 approveConnectRequest,
856 isConnectDeviceTrusted,
857 trustConnectDevice,
858 listConnectDevices,
859 revokeConnectDevice,
860 revokeConnectDevicesExcept,
861 listActive,
862 get streamChanges() {
863 return Stream.fromPubSub(changesPubSub);
864 },
865 revoke,
866 consume,
867 });
868});
869​
870export const layer = Layer.effect(PairingGrantStore, make).pipe(
871 Layer.provideMerge(AuthPairingLinks.layer),
872 Layer.provideMerge(AuthConnectDevices.layer),
873);