The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 03:37 UTC
| 1 | import { |
| 2 | AuthAdministrativeClientScopes, |
| 3 | AuthStandardClientScopes, |
| 4 | type AuthClientMetadata, |
| 5 | type AuthConnectDevice, |
| 6 | type AuthEnvironmentScope, |
| 7 | type AuthMcpClientAccess, |
| 8 | type AuthPairingLink, |
| 9 | mcpApprovalCode, |
| 10 | PAIRING_CODE_ALPHABET, |
| 11 | PAIRING_CODE_LENGTH, |
| 12 | parseMcpApprovalCode, |
| 13 | type ServerAuthBootstrapMethod, |
| 14 | connectDeviceVerificationCode, |
| 15 | } from "@t3tools/contracts"; |
| 16 | import { |
| 17 | DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS, |
| 18 | isValidDesktopBootstrapToken, |
| 19 | } from "@t3tools/shared/desktopBootstrapToken"; |
| 20 | import * as Context from "effect/Context"; |
| 21 | import * as SecureRandom from "effect/crypto/SecureRandom"; |
| 22 | import * as DateTime from "effect/DateTime"; |
| 23 | import * as Duration from "effect/Duration"; |
| 24 | import * as Mac from "effect/crypto/Mac"; |
| 25 | import * as Effect from "effect/Effect"; |
| 26 | import * as Layer from "effect/Layer"; |
| 27 | import * as Option from "effect/Option"; |
| 28 | import * as PubSub from "effect/PubSub"; |
| 29 | import * as Ref from "effect/Ref"; |
| 30 | import * as Schema from "effect/Schema"; |
| 31 | import * as Stream from "effect/Stream"; |
| 32 | |
| 33 | import * as ServerConfig from "../config.ts"; |
| 34 | import * as AuthConnectDevices from "../persistence/AuthConnectDevices.ts"; |
| 35 | import * as AuthPairingLinks from "../persistence/AuthPairingLinks.ts"; |
| 36 | |
| 37 | export interface BootstrapGrant { |
| 38 | readonly method: ServerAuthBootstrapMethod; |
| 39 | readonly scopes: ReadonlyArray<AuthEnvironmentScope>; |
| 40 | readonly subject: string; |
| 41 | readonly label?: string; |
| 42 | readonly proofKeyThumbprint?: string; |
| 43 | readonly expiresAt: DateTime.DateTime; |
| 44 | } |
| 45 | |
| 46 | export class UnknownBootstrapCredentialError extends Schema.TaggedError<UnknownBootstrapCredentialError>()( |
| 47 | "UnknownBootstrapCredentialError", |
| 48 | {}, |
| 49 | ) { |
| 50 | override get message(): string { |
| 51 | return "Unknown bootstrap credential."; |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | export class ExpiredBootstrapCredentialError extends Schema.TaggedError<ExpiredBootstrapCredentialError>()( |
| 56 | "ExpiredBootstrapCredentialError", |
| 57 | {}, |
| 58 | ) { |
| 59 | override get message(): string { |
| 60 | return "Bootstrap credential expired."; |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | export class BootstrapCredentialProofKeyMismatchError extends Schema.TaggedError<BootstrapCredentialProofKeyMismatchError>()( |
| 65 | "BootstrapCredentialProofKeyMismatchError", |
| 66 | {}, |
| 67 | ) { |
| 68 | override get message(): string { |
| 69 | return "Bootstrap credential proof key mismatch."; |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | export class UnavailableBootstrapCredentialError extends Schema.TaggedError<UnavailableBootstrapCredentialError>()( |
| 74 | "UnavailableBootstrapCredentialError", |
| 75 | {}, |
| 76 | ) { |
| 77 | override get message(): string { |
| 78 | return "Bootstrap credential is no longer available."; |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | export class BootstrapCredentialScopeNotGrantedError extends Schema.TaggedError<BootstrapCredentialScopeNotGrantedError>()( |
| 83 | "BootstrapCredentialScopeNotGrantedError", |
| 84 | {}, |
| 85 | ) { |
| 86 | override get message(): string { |
| 87 | return "The requested authentication scope was not granted."; |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | /** The credential is valid but its T3 Connect device key still waits for approval. */ |
| 92 | export class BootstrapCredentialConnectApprovalPendingError extends Schema.TaggedError<BootstrapCredentialConnectApprovalPendingError>()( |
| 93 | "BootstrapCredentialConnectApprovalPendingError", |
| 94 | { |
| 95 | pairingLinkId: Schema.String, |
| 96 | }, |
| 97 | ) { |
| 98 | override get message(): string { |
| 99 | return "This T3 Connect device is waiting for approval."; |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | export const BootstrapCredentialInvalidError = Schema.Union([ |
| 104 | UnknownBootstrapCredentialError, |
| 105 | ExpiredBootstrapCredentialError, |
| 106 | BootstrapCredentialProofKeyMismatchError, |
| 107 | UnavailableBootstrapCredentialError, |
| 108 | BootstrapCredentialConnectApprovalPendingError, |
| 109 | ]); |
| 110 | export type BootstrapCredentialInvalidError = typeof BootstrapCredentialInvalidError.Type; |
| 111 | |
| 112 | export class ActivePairingLinksLoadError extends Schema.TaggedError<ActivePairingLinksLoadError>()( |
| 113 | "ActivePairingLinksLoadError", |
| 114 | { |
| 115 | cause: Schema.Defect(), |
| 116 | }, |
| 117 | ) { |
| 118 | override get message(): string { |
| 119 | return "Failed to load active pairing links."; |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | export class PairingLinkRevokeError extends Schema.TaggedError<PairingLinkRevokeError>()( |
| 124 | "PairingLinkRevokeError", |
| 125 | { |
| 126 | pairingLinkId: Schema.String, |
| 127 | cause: Schema.Defect(), |
| 128 | }, |
| 129 | ) { |
| 130 | override get message(): string { |
| 131 | return `Failed to revoke pairing link '${this.pairingLinkId}'.`; |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | export class PairingCredentialIssueError extends Schema.TaggedError<PairingCredentialIssueError>()( |
| 136 | "PairingCredentialIssueError", |
| 137 | { |
| 138 | pairingLinkId: Schema.String, |
| 139 | subject: Schema.String, |
| 140 | label: Schema.optional(Schema.String), |
| 141 | cause: Schema.Defect(), |
| 142 | }, |
| 143 | ) { |
| 144 | override get message(): string { |
| 145 | return `Failed to issue pairing credential '${this.pairingLinkId}' for '${this.subject}'.`; |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | export class PairingCredentialRandomGenerationError extends Schema.TaggedError<PairingCredentialRandomGenerationError>()( |
| 150 | "PairingCredentialRandomGenerationError", |
| 151 | { |
| 152 | operation: Schema.Literals(["generate-id", "generate-token"]), |
| 153 | cause: Schema.Defect(), |
| 154 | }, |
| 155 | ) { |
| 156 | override get message(): string { |
| 157 | return `Failed to generate pairing credential data during '${this.operation}'.`; |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | export class BootstrapCredentialConsumeError extends Schema.TaggedError<BootstrapCredentialConsumeError>()( |
| 162 | "BootstrapCredentialConsumeError", |
| 163 | { |
| 164 | cause: Schema.Defect(), |
| 165 | }, |
| 166 | ) { |
| 167 | override get message(): string { |
| 168 | return "Failed to consume bootstrap credential."; |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | export class BootstrapCredentialConsumeAvailableError extends Schema.TaggedError<BootstrapCredentialConsumeAvailableError>()( |
| 173 | "BootstrapCredentialConsumeAvailableError", |
| 174 | { |
| 175 | cause: Schema.Defect(), |
| 176 | }, |
| 177 | ) { |
| 178 | override get message(): string { |
| 179 | return "Failed to atomically consume an available bootstrap credential."; |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | export class ConnectDevicesError extends Schema.TaggedError<ConnectDevicesError>()( |
| 184 | "ConnectDevicesError", |
| 185 | { |
| 186 | operation: Schema.Literals(["list", "trust", "revoke", "record-request"]), |
| 187 | cause: Schema.Defect(), |
| 188 | }, |
| 189 | ) { |
| 190 | override get message(): string { |
| 191 | return `Failed to ${this.operation} T3 Connect devices.`; |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | export class BootstrapCredentialLookupError extends Schema.TaggedError<BootstrapCredentialLookupError>()( |
| 196 | "BootstrapCredentialLookupError", |
| 197 | { |
| 198 | cause: Schema.Defect(), |
| 199 | }, |
| 200 | ) { |
| 201 | override get message(): string { |
| 202 | return "Failed to look up bootstrap credential state."; |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | export const BootstrapCredentialInternalError = Schema.Union([ |
| 207 | ActivePairingLinksLoadError, |
| 208 | PairingLinkRevokeError, |
| 209 | PairingCredentialIssueError, |
| 210 | PairingCredentialRandomGenerationError, |
| 211 | BootstrapCredentialConsumeError, |
| 212 | BootstrapCredentialConsumeAvailableError, |
| 213 | BootstrapCredentialLookupError, |
| 214 | ConnectDevicesError, |
| 215 | ]); |
| 216 | export type BootstrapCredentialInternalError = typeof BootstrapCredentialInternalError.Type; |
| 217 | export const isBootstrapCredentialInternalError = Schema.is(BootstrapCredentialInternalError); |
| 218 | |
| 219 | export const BootstrapCredentialError = Schema.Union([ |
| 220 | BootstrapCredentialInvalidError, |
| 221 | BootstrapCredentialInternalError, |
| 222 | BootstrapCredentialScopeNotGrantedError, |
| 223 | ]); |
| 224 | export type BootstrapCredentialError = typeof BootstrapCredentialError.Type; |
| 225 | |
| 226 | export interface IssuedBootstrapCredential { |
| 227 | readonly id: string; |
| 228 | readonly credential: string; |
| 229 | readonly label?: string; |
| 230 | readonly proofKeyThumbprint?: string; |
| 231 | readonly expiresAt: DateTime.Utc; |
| 232 | } |
| 233 | |
| 234 | export type BootstrapCredentialChange = |
| 235 | | { |
| 236 | readonly type: "pairingLinkUpserted"; |
| 237 | readonly pairingLink: AuthPairingLink; |
| 238 | } |
| 239 | | { |
| 240 | readonly type: "pairingLinkRemoved"; |
| 241 | readonly id: string; |
| 242 | } |
| 243 | | { |
| 244 | readonly type: "connectDevicesChanged"; |
| 245 | }; |
| 246 | |
| 247 | export class PairingGrantStore extends Context.Service< |
| 248 | PairingGrantStore, |
| 249 | { |
| 250 | readonly issueOneTimeToken: (input?: { |
| 251 | readonly ttl?: Duration.Duration; |
| 252 | readonly scopes?: ReadonlyArray<AuthEnvironmentScope>; |
| 253 | readonly subject?: string; |
| 254 | readonly label?: string; |
| 255 | readonly proofKeyThumbprint?: string; |
| 256 | readonly purpose?: "startup"; |
| 257 | /** Issues a hidden `<LEVEL>-` code that only an agent sign-in at this level can spend. */ |
| 258 | readonly mcpApproval?: AuthMcpClientAccess; |
| 259 | /** Spendable only after someone trusts `proofKeyThumbprint` as a T3 Connect device. */ |
| 260 | readonly requiresConnectApproval?: boolean; |
| 261 | }) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialInternalError>; |
| 262 | /** A device's open or denied request, reused so retries keep one request and one code. */ |
| 263 | readonly findPendingConnect: ( |
| 264 | proofKeyThumbprint: string, |
| 265 | ) => Effect.Effect<Option.Option<IssuedBootstrapCredential>, BootstrapCredentialInternalError>; |
| 266 | /** Shows approvers what a waiting device says it is. Only its first description sticks. */ |
| 267 | readonly recordConnectRequestClient: ( |
| 268 | pairingLinkId: string, |
| 269 | client: AuthClientMetadata, |
| 270 | ) => Effect.Effect<void, BootstrapCredentialInternalError>; |
| 271 | /** Trusts the device key behind a waiting request. False when it is gone or not a request. */ |
| 272 | readonly approveConnectRequest: ( |
| 273 | pairingLinkId: string, |
| 274 | ) => Effect.Effect<boolean, BootstrapCredentialInternalError>; |
| 275 | readonly isConnectDeviceTrusted: ( |
| 276 | proofKeyThumbprint: string, |
| 277 | ) => Effect.Effect<boolean, BootstrapCredentialInternalError>; |
| 278 | readonly trustConnectDevice: ( |
| 279 | proofKeyThumbprint: string, |
| 280 | client: AuthClientMetadata, |
| 281 | ) => Effect.Effect<void, BootstrapCredentialInternalError>; |
| 282 | readonly listConnectDevices: () => Effect.Effect< |
| 283 | ReadonlyArray<AuthConnectDevice>, |
| 284 | BootstrapCredentialInternalError |
| 285 | >; |
| 286 | readonly revokeConnectDevice: ( |
| 287 | proofKeyThumbprint: string, |
| 288 | ) => Effect.Effect<boolean, BootstrapCredentialInternalError>; |
| 289 | readonly revokeConnectDevicesExcept: ( |
| 290 | keepProofKeyThumbprint: string | null, |
| 291 | ) => Effect.Effect<number, BootstrapCredentialInternalError>; |
| 292 | readonly listActive: () => Effect.Effect< |
| 293 | ReadonlyArray<AuthPairingLink>, |
| 294 | BootstrapCredentialInternalError |
| 295 | >; |
| 296 | readonly streamChanges: Stream.Stream<BootstrapCredentialChange>; |
| 297 | readonly revoke: (id: string) => Effect.Effect<boolean, BootstrapCredentialInternalError>; |
| 298 | readonly consume: ( |
| 299 | credential: string, |
| 300 | input?: { |
| 301 | readonly proofKeyThumbprint?: string; |
| 302 | readonly requestedScopes?: ReadonlyArray<AuthEnvironmentScope>; |
| 303 | /** All scopes must be granted; requestedScopes only requires an overlap for OAuth. */ |
| 304 | readonly requiredScopes?: ReadonlyArray<AuthEnvironmentScope>; |
| 305 | readonly allowedSubject?: string; |
| 306 | }, |
| 307 | ) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>; |
| 308 | } |
| 309 | >()("t3/auth/PairingGrantStore") {} |
| 310 | |
| 311 | interface StoredBootstrapGrant extends BootstrapGrant { |
| 312 | readonly remainingUses: number | "unbounded"; |
| 313 | } |
| 314 | |
| 315 | type 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 | |
| 326 | const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5); |
| 327 | |
| 328 | const 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 | }); |
| 344 | const DESKTOP_BOOTSTRAP_TTL_HOURS = Duration.hours(24); |
| 345 | const DEV_STARTUP_TTL_HOURS = Duration.hours(24); |
| 346 | const PAIRING_TOKEN_REJECTION_LIMIT = |
| 347 | Math.floor(256 / PAIRING_CODE_ALPHABET.length) * PAIRING_CODE_ALPHABET.length; |
| 348 | |
| 349 | const PAIRING_TOKEN_PATTERN = new RegExp( |
| 350 | `^[${PAIRING_CODE_ALPHABET}]{${PAIRING_CODE_LENGTH}}$`, |
| 351 | "i", |
| 352 | ); |
| 353 | |
| 354 | const 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: AuthAdministrativeClientScopes, |
| 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 | // Purpose-bound codes stay out of the pairing links and QR codes that clients show. |
| 513 | if (!subject.startsWith(AuthPairingLinks.MCP_APPROVAL_SUBJECT_PREFIX)) { |
| 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: AuthAdministrativeClientScopes, |
| 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?.allowedSubject ? { allowedSubject: input.allowedSubject } : {}), |
| 656 | consumedAt: now, |
| 657 | now, |
| 658 | }) |
| 659 | .pipe(Effect.mapError((cause) => new BootstrapCredentialConsumeAvailableError({ cause }))); |
| 660 | |
| 661 | if (Option.isSome(consumed)) { |
| 662 | if (!consumed.value.subject.startsWith(AuthPairingLinks.MCP_APPROVAL_SUBJECT_PREFIX)) { |
| 663 | yield* emitRemoved(consumed.value.id); |
| 664 | } |
| 665 | return { |
| 666 | method: consumed.value.method, |
| 667 | scopes: consumed.value.scopes, |
| 668 | subject: consumed.value.subject, |
| 669 | ...(consumed.value.label ? { label: consumed.value.label } : {}), |
| 670 | ...(consumed.value.proofKeyThumbprint |
| 671 | ? { proofKeyThumbprint: consumed.value.proofKeyThumbprint } |
| 672 | : {}), |
| 673 | expiresAt: consumed.value.expiresAt, |
| 674 | } satisfies BootstrapGrant; |
| 675 | } |
| 676 | |
| 677 | const matching = yield* pairingLinks |
| 678 | .getByCredential({ credential: pairingCredential }) |
| 679 | .pipe(Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause }))); |
| 680 | if (Option.isNone(matching)) { |
| 681 | return yield* new UnknownBootstrapCredentialError({}); |
| 682 | } |
| 683 | |
| 684 | if (matching.value.revokedAt !== null) { |
| 685 | return yield* new UnavailableBootstrapCredentialError({}); |
| 686 | } |
| 687 | |
| 688 | if (matching.value.consumedAt !== null) { |
| 689 | return yield* new UnknownBootstrapCredentialError({}); |
| 690 | } |
| 691 | |
| 692 | if (DateTime.isGreaterThanOrEqualTo(now, matching.value.expiresAt)) { |
| 693 | return yield* new ExpiredBootstrapCredentialError({}); |
| 694 | } |
| 695 | |
| 696 | if ( |
| 697 | matching.value.proofKeyThumbprint !== null && |
| 698 | matching.value.proofKeyThumbprint !== input?.proofKeyThumbprint |
| 699 | ) { |
| 700 | return yield* new BootstrapCredentialProofKeyMismatchError({}); |
| 701 | } |
| 702 | |
| 703 | if ( |
| 704 | (input?.requestedScopes !== undefined && |
| 705 | !input.requestedScopes.some((scope) => matching.value.scopes.includes(scope))) || |
| 706 | (input?.requiredScopes !== undefined && |
| 707 | !input.requiredScopes.every((scope) => matching.value.scopes.includes(scope))) |
| 708 | ) { |
| 709 | return yield* new BootstrapCredentialScopeNotGrantedError({}); |
| 710 | } |
| 711 | |
| 712 | if (matching.value.requiresConnectApproval === 1 && matching.value.connectApproved === 0) { |
| 713 | return yield* new BootstrapCredentialConnectApprovalPendingError({ |
| 714 | pairingLinkId: matching.value.id, |
| 715 | }); |
| 716 | } |
| 717 | |
| 718 | return yield* new UnavailableBootstrapCredentialError({}); |
| 719 | }, |
| 720 | ); |
| 721 | |
| 722 | const emitConnectDevicesChanged = PubSub.publish(changesPubSub, { |
| 723 | type: "connectDevicesChanged", |
| 724 | }).pipe(Effect.asVoid); |
| 725 | |
| 726 | const findPendingConnect: PairingGrantStore["Service"]["findPendingConnect"] = Effect.fn( |
| 727 | "PairingGrantStore.findPendingConnect", |
| 728 | )( |
| 729 | function* (proofKeyThumbprint) { |
| 730 | const now = yield* DateTime.now; |
| 731 | const row = yield* pairingLinks.findPendingConnect({ proofKeyThumbprint, now }); |
| 732 | return Option.map(row, (link): IssuedBootstrapCredential => ({ |
| 733 | id: link.id, |
| 734 | credential: link.credential, |
| 735 | ...(link.label ? { label: link.label } : {}), |
| 736 | proofKeyThumbprint, |
| 737 | expiresAt: link.expiresAt, |
| 738 | })); |
| 739 | }, |
| 740 | Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause })), |
| 741 | ); |
| 742 | |
| 743 | const recordConnectRequestClient: PairingGrantStore["Service"]["recordConnectRequestClient"] = |
| 744 | Effect.fn("PairingGrantStore.recordConnectRequestClient")(function* (pairingLinkId, client) { |
| 745 | const recorded = yield* pairingLinks |
| 746 | .recordConnectRequestClient({ id: pairingLinkId, client }) |
| 747 | .pipe( |
| 748 | Effect.mapError( |
| 749 | (cause) => new ConnectDevicesError({ operation: "record-request", cause }), |
| 750 | ), |
| 751 | ); |
| 752 | if (!recorded) return; |
| 753 | const now = yield* DateTime.now; |
| 754 | const row = yield* pairingLinks |
| 755 | .getActiveById({ id: pairingLinkId, now }) |
| 756 | .pipe(Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause }))); |
| 757 | if (Option.isSome(row)) yield* emitUpsert(toPairingLink(row.value)); |
| 758 | }); |
| 759 | |
| 760 | const trustConnectDevice: PairingGrantStore["Service"]["trustConnectDevice"] = Effect.fn( |
| 761 | "PairingGrantStore.trustConnectDevice", |
| 762 | )(function* (proofKeyThumbprint, client) { |
| 763 | const approvedAt = yield* DateTime.now; |
| 764 | yield* connectDevices |
| 765 | .trust({ proofKeyThumbprint, client, approvedAt }) |
| 766 | .pipe(Effect.mapError((cause) => new ConnectDevicesError({ operation: "trust", cause }))); |
| 767 | yield* emitConnectDevicesChanged; |
| 768 | }); |
| 769 | |
| 770 | const approveConnectRequest: PairingGrantStore["Service"]["approveConnectRequest"] = Effect.fn( |
| 771 | "PairingGrantStore.approveConnectRequest", |
| 772 | )(function* (pairingLinkId) { |
| 773 | const now = yield* DateTime.now; |
| 774 | const row = yield* pairingLinks |
| 775 | .getActiveById({ id: pairingLinkId, now }) |
| 776 | .pipe(Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause }))); |
| 777 | if ( |
| 778 | Option.isNone(row) || |
| 779 | row.value.requiresConnectApproval !== 1 || |
| 780 | row.value.proofKeyThumbprint === null |
| 781 | ) { |
| 782 | return false; |
| 783 | } |
| 784 | yield* connectDevices |
| 785 | .trust({ |
| 786 | proofKeyThumbprint: row.value.proofKeyThumbprint, |
| 787 | client: row.value.requestedClient, |
| 788 | approvedAt: now, |
| 789 | }) |
| 790 | .pipe(Effect.mapError((cause) => new ConnectDevicesError({ operation: "trust", cause }))); |
| 791 | yield* emitRemoved(pairingLinkId); |
| 792 | yield* emitConnectDevicesChanged; |
| 793 | return true; |
| 794 | }); |
| 795 | |
| 796 | const isConnectDeviceTrusted: PairingGrantStore["Service"]["isConnectDeviceTrusted"] = ( |
| 797 | proofKeyThumbprint, |
| 798 | ) => |
| 799 | connectDevices |
| 800 | .isTrusted(proofKeyThumbprint) |
| 801 | .pipe(Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause }))); |
| 802 | |
| 803 | const listConnectDevices: PairingGrantStore["Service"]["listConnectDevices"] = () => |
| 804 | connectDevices.list().pipe( |
| 805 | Effect.map((rows) => |
| 806 | rows.map((row): AuthConnectDevice => ({ |
| 807 | proofKeyThumbprint: row.proofKeyThumbprint, |
| 808 | verificationCode: connectDeviceVerificationCode(row.proofKeyThumbprint), |
| 809 | ...(row.client ? { client: row.client } : {}), |
| 810 | approvedAt: row.approvedAt, |
| 811 | })), |
| 812 | ), |
| 813 | Effect.mapError((cause) => new ConnectDevicesError({ operation: "list", cause })), |
| 814 | ); |
| 815 | |
| 816 | // A credential minted before revocation is still spendable; it must die with the trust, |
| 817 | // or exchanging it would trust the key again without approval. |
| 818 | const revokeUnspentLinks = Effect.fn("PairingGrantStore.revokeUnspentLinks")(function* ( |
| 819 | input: Omit<AuthPairingLinks.RevokeUnspentByProofKeyInput, "revokedAt">, |
| 820 | ) { |
| 821 | const revokedAt = yield* DateTime.now; |
| 822 | const ids = yield* pairingLinks |
| 823 | .revokeUnspentByProofKey({ ...input, revokedAt }) |
| 824 | .pipe(Effect.mapError((cause) => new ConnectDevicesError({ operation: "revoke", cause }))); |
| 825 | yield* Effect.forEach(ids, emitRemoved, { discard: true }); |
| 826 | }); |
| 827 | |
| 828 | const revokeConnectDevice: PairingGrantStore["Service"]["revokeConnectDevice"] = Effect.fn( |
| 829 | "PairingGrantStore.revokeConnectDevice", |
| 830 | )(function* (proofKeyThumbprint) { |
| 831 | yield* revokeUnspentLinks({ |
| 832 | proofKeyThumbprint, |
| 833 | keepProofKeyThumbprint: null, |
| 834 | includeUnbound: false, |
| 835 | }); |
| 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 | // "Revoke all others" promises every other way in is gone, so unspent codes go too. |
| 846 | yield* revokeUnspentLinks({ |
| 847 | proofKeyThumbprint: null, |
| 848 | keepProofKeyThumbprint, |
| 849 | includeUnbound: true, |
| 850 | }); |
| 851 | const removed = yield* connectDevices |
| 852 | .removeAllExcept(keepProofKeyThumbprint) |
| 853 | .pipe(Effect.mapError((cause) => new ConnectDevicesError({ operation: "revoke", cause }))); |
| 854 | if (removed > 0) yield* emitConnectDevicesChanged; |
| 855 | return removed; |
| 856 | }); |
| 857 | |
| 858 | return PairingGrantStore.of({ |
| 859 | issueOneTimeToken, |
| 860 | findPendingConnect, |
| 861 | recordConnectRequestClient, |
| 862 | approveConnectRequest, |
| 863 | isConnectDeviceTrusted, |
| 864 | trustConnectDevice, |
| 865 | listConnectDevices, |
| 866 | revokeConnectDevice, |
| 867 | revokeConnectDevicesExcept, |
| 868 | listActive, |
| 869 | get streamChanges() { |
| 870 | return Stream.fromPubSub(changesPubSub); |
| 871 | }, |
| 872 | revoke, |
| 873 | consume, |
| 874 | }); |
| 875 | }); |
| 876 | |
| 877 | export const layer = Layer.effect(PairingGrantStore, make).pipe( |
| 878 | Layer.provideMerge(AuthPairingLinks.layer), |
| 879 | Layer.provideMerge(AuthConnectDevices.layer), |
| 880 | ); |