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

main
ts 696 lines 26.6 KB
Raw
1 import * as Schema from "effect/Schema";
2 import * as HttpApiSchema from "effect/http-api/HttpApiSchema";
3
4 import {
5 AuthSessionId,
6 ForwardCompatibleArray,
7 ClientSurface,
8 ClientWebDeployment,
9 TrimmedNonEmptyString,
10 } from "./baseSchemas.ts";
11 import { RuntimeMode } from "./providerPolicy.ts";
12
13 export const ServerAuthPolicy = Schema.Literals([
14 "desktop-managed-local",
15 "loopback-browser",
16 "remote-reachable",
17 "unsafe-no-auth",
18 ]);
19 export type ServerAuthPolicy = typeof ServerAuthPolicy.Type;
20
21 export const ServerAuthBootstrapMethod = Schema.Literals(["desktop-bootstrap", "one-time-token"]);
22 export type ServerAuthBootstrapMethod = typeof ServerAuthBootstrapMethod.Type;
23
24 export const ServerAuthSessionMethod = Schema.Literals([
25 "browser-session-cookie",
26 "bearer-access-token",
27 "dpop-access-token",
28 ]);
29 export type ServerAuthSessionMethod = typeof ServerAuthSessionMethod.Type;
30
31 export const AuthOrchestrationReadScope = "orchestration:read" as const;
32 export const AuthOrchestrationOperateScope = "orchestration:operate" as const;
33 export const AuthSettingsWriteScope = "settings:write" as const;
34 // Also decides where credentials go: secret providers, references, and key-bearing endpoints.
35 export const AuthProvidersManageScope = "providers:manage" as const;
36 export const AuthEnvironmentMaintainScope = "environment:maintain" as const;
37 export const AuthPreviewOperateScope = "preview:operate" as const;
38 export const AuthDiagnosticsReadScope = "diagnostics:read" as const;
39 export const AuthTerminalReadScope = "terminal:read" as const;
40 export const AuthTerminalOperateScope = "terminal:operate" as const;
41 export const AuthSourceControlWriteScope = "source-control:write" as const;
42 export const AuthFilesystemReadScope = "filesystem:read" as const;
43 export const AuthFilesystemWriteScope = "filesystem:write" as const;
44 /** Retained for decoding existing credentials; grants no current RPC access. */
45 const AuthReviewWriteScope = "review:write" as const;
46 export const AuthAccessReadScope = "access:read" as const;
47 export const AuthAccessWriteScope = "access:write" as const;
48 export const AuthRelayReadScope = "relay:read" as const;
49 export const AuthRelayWriteScope = "relay:write" as const;
50 export const AuthRelayConfigureScope = "relay:configure" as const;
51 export const AuthEnvironmentScope = Schema.Literals([
52 AuthOrchestrationReadScope,
53 AuthOrchestrationOperateScope,
54 AuthSettingsWriteScope,
55 AuthProvidersManageScope,
56 AuthEnvironmentMaintainScope,
57 AuthPreviewOperateScope,
58 AuthDiagnosticsReadScope,
59 AuthTerminalReadScope,
60 AuthTerminalOperateScope,
61 AuthFilesystemReadScope,
62 AuthFilesystemWriteScope,
63 AuthReviewWriteScope,
64 AuthSourceControlWriteScope,
65 AuthAccessReadScope,
66 AuthAccessWriteScope,
67 AuthRelayReadScope,
68 AuthRelayWriteScope,
69 AuthRelayConfigureScope,
70 ]);
71 export type AuthEnvironmentScope = typeof AuthEnvironmentScope.Type;
72 export const AuthEnvironmentScopes = Schema.Array(AuthEnvironmentScope);
73 export type AuthEnvironmentScopes = typeof AuthEnvironmentScopes.Type;
74
75 export const AuthGrantScope = Schema.Literals(
76 AuthEnvironmentScope.literals.filter((scope) => scope !== AuthReviewWriteScope),
77 );
78 export type AuthGrantScope = typeof AuthGrantScope.Type;
79 export const AuthGrantScopes = Schema.Array(AuthGrantScope);
80 export type AuthGrantScopes = typeof AuthGrantScopes.Type;
81
82 const legacyScopes = new Set<AuthEnvironmentScope>([
83 AuthOrchestrationReadScope,
84 AuthOrchestrationOperateScope,
85 AuthTerminalOperateScope,
86 AuthReviewWriteScope,
87 AuthAccessReadScope,
88 AuthAccessWriteScope,
89 AuthRelayReadScope,
90 AuthRelayWriteScope,
91 ]);
92
93 export function authScopeResponse(scopes: ReadonlyArray<AuthEnvironmentScope>) {
94 return { scopes: scopes.filter((scope) => legacyScopes.has(scope)), permissions: scopes };
95 }
96
97 const authScopeResponseFields = {
98 scopes: AuthEnvironmentScopes,
99 permissions: Schema.optionalKey(ForwardCompatibleArray(AuthEnvironmentScope)),
100 };
101
102 // Client-only fallback for old servers. Servers never expand grants; empty permissions grant nothing.
103 const legacyParents: Partial<Record<AuthEnvironmentScope, AuthEnvironmentScope>> = {
104 [AuthFilesystemReadScope]: AuthOrchestrationReadScope,
105 [AuthDiagnosticsReadScope]: AuthOrchestrationReadScope,
106 [AuthSettingsWriteScope]: AuthOrchestrationOperateScope,
107 [AuthProvidersManageScope]: AuthOrchestrationOperateScope,
108 [AuthEnvironmentMaintainScope]: AuthOrchestrationOperateScope,
109 [AuthPreviewOperateScope]: AuthOrchestrationOperateScope,
110 [AuthSourceControlWriteScope]: AuthOrchestrationOperateScope,
111 [AuthFilesystemWriteScope]: AuthOrchestrationOperateScope,
112 [AuthTerminalReadScope]: AuthTerminalOperateScope,
113 };
114
115 /** Keep permission denials decodable by clients with the original scope enum. */
116 export function authScopeRequiredResponse(requiredPermission: AuthEnvironmentScope) {
117 return {
118 requiredScope:
119 requiredPermission === AuthRelayConfigureScope
120 ? AuthRelayWriteScope
121 : (legacyParents[requiredPermission] ?? requiredPermission),
122 requiredPermission,
123 };
124 }
125
126 export interface SessionGrantInput {
127 readonly authenticated: boolean;
128 readonly scopes?: ReadonlyArray<AuthEnvironmentScope> | undefined;
129 readonly permissions?: ReadonlyArray<AuthEnvironmentScope> | undefined;
130 readonly auth?: { readonly serverUpdateScope?: string | undefined } | undefined;
131 }
132
133 export function sessionGrantsScope(
134 session: SessionGrantInput,
135 scope: AuthEnvironmentScope,
136 ): boolean {
137 if (!session.authenticated) return false;
138 if (session.permissions !== undefined) return session.permissions.includes(scope);
139 if (session.scopes?.includes(scope)) return true;
140 if (session.auth?.serverUpdateScope !== undefined) return false;
141 const parent = legacyParents[scope];
142 return parent !== undefined && session.scopes?.includes(parent) === true;
143 }
144
145 export function sessionHasLegacyPermissions(session: SessionGrantInput): boolean {
146 const permissions = session.permissions;
147 return (
148 session.authenticated &&
149 permissions !== undefined &&
150 permissions.every((scope) => legacyScopes.has(scope)) &&
151 Object.values(legacyParents).some((parent) => permissions.includes(parent))
152 );
153 }
154
155 // Shell and full-access agent scopes already confer access and relay authority.
156 export const AuthStandardClientScopes = [
157 AuthOrchestrationReadScope,
158 AuthOrchestrationOperateScope,
159 AuthSettingsWriteScope,
160 AuthProvidersManageScope,
161 AuthEnvironmentMaintainScope,
162 AuthPreviewOperateScope,
163 AuthDiagnosticsReadScope,
164 AuthTerminalReadScope,
165 AuthTerminalOperateScope,
166 AuthSourceControlWriteScope,
167 AuthFilesystemReadScope,
168 AuthFilesystemWriteScope,
169 AuthRelayReadScope,
170 AuthAccessReadScope,
171 AuthAccessWriteScope,
172 AuthRelayWriteScope,
173 ] as const;
174
175 export const AuthAdministrativeClientScopes = [
176 ...AuthStandardClientScopes,
177 AuthRelayConfigureScope,
178 ] as const;
179
180 export const AuthTokenExchangeGrantType =
181 "urn:ietf:params:oauth:grant-type:token-exchange" as const;
182 export const AuthAccessTokenType = "urn:ietf:params:oauth:token-type:access_token" as const;
183 export const AuthEnvironmentBootstrapTokenType =
184 "urn:t3:params:oauth:token-type:environment-bootstrap" as const;
185
186 export const ServerAuthDescriptor = Schema.Struct({
187 policy: ServerAuthPolicy,
188 bootstrapMethods: Schema.Array(ServerAuthBootstrapMethod),
189 sessionMethods: Schema.Array(ServerAuthSessionMethod),
190 sessionCookieName: TrimmedNonEmptyString,
191 /** Older servers omit this and authorize self-updates with orchestration:operate. */
192 serverUpdateScope: Schema.optionalKey(Schema.Literal(AuthEnvironmentMaintainScope)),
193 });
194 export type ServerAuthDescriptor = typeof ServerAuthDescriptor.Type;
195
196 export const AuthBrowserSessionRequest = Schema.Struct({
197 credential: TrimmedNonEmptyString,
198 });
199 export type AuthBrowserSessionRequest = typeof AuthBrowserSessionRequest.Type;
200
201 export const AuthBrowserSessionResult = Schema.Struct({
202 authenticated: Schema.Literal(true),
203 ...authScopeResponseFields,
204 sessionMethod: ServerAuthSessionMethod,
205 expiresAt: Schema.DateTimeUtc,
206 });
207 export type AuthBrowserSessionResult = typeof AuthBrowserSessionResult.Type;
208
209 export const AuthClientMetadataDeviceType = Schema.Literals([
210 "desktop",
211 "mobile",
212 "tablet",
213 "bot",
214 "unknown",
215 ]);
216 export type AuthClientMetadataDeviceType = typeof AuthClientMetadataDeviceType.Type;
217
218 export const AuthClientPresentationMetadata = Schema.Struct({
219 label: Schema.optionalKey(TrimmedNonEmptyString),
220 deviceType: Schema.optionalKey(AuthClientMetadataDeviceType),
221 os: Schema.optionalKey(TrimmedNonEmptyString),
222 osMajorVersion: Schema.optionalKey(Schema.Int),
223 deviceModel: Schema.optionalKey(TrimmedNonEmptyString),
224 surface: Schema.optionalKey(ClientSurface),
225 webDeployment: Schema.optionalKey(ClientWebDeployment),
226 browser: Schema.optionalKey(TrimmedNonEmptyString),
227 appVersion: Schema.optionalKey(TrimmedNonEmptyString),
228 });
229 export type AuthClientPresentationMetadata = typeof AuthClientPresentationMetadata.Type;
230
231 export const AuthTokenExchangeRequest = Schema.Struct({
232 grant_type: Schema.Literal(AuthTokenExchangeGrantType),
233 subject_token: TrimmedNonEmptyString,
234 /** An access token renews its own session, with a DPoP proof from the key it is bound to. */
235 subject_token_type: Schema.Literals([AuthEnvironmentBootstrapTokenType, AuthAccessTokenType]),
236 requested_token_type: Schema.Literal(AuthAccessTokenType),
237 scope: Schema.optionalKey(TrimmedNonEmptyString),
238 client_label: Schema.optionalKey(TrimmedNonEmptyString),
239 client_device_type: Schema.optionalKey(AuthClientMetadataDeviceType),
240 client_os: Schema.optionalKey(TrimmedNonEmptyString),
241 }).pipe(HttpApiSchema.asFormUrlEncoded());
242 export type AuthTokenExchangeRequest = typeof AuthTokenExchangeRequest.Type;
243
244 export const AuthAccessTokenResult = Schema.Struct({
245 access_token: TrimmedNonEmptyString,
246 issued_token_type: Schema.Literal(AuthAccessTokenType),
247 token_type: Schema.Literals(["Bearer", "DPoP"]),
248 expires_in: Schema.Number,
249 scope: TrimmedNonEmptyString,
250 });
251 export type AuthAccessTokenResult = typeof AuthAccessTokenResult.Type;
252
253 export const AuthWebSocketTicketResult = Schema.Struct({
254 ticket: Schema.RedactedFromValue(TrimmedNonEmptyString),
255 expiresAt: Schema.DateTimeUtc,
256 });
257 export type AuthWebSocketTicketResult = typeof AuthWebSocketTicketResult.Type;
258
259 /**
260 * Media routes share a ticket across requests; RPC uses a separate ticket.
261 * Use a path segment so the DPoP mint proof covers it; `htu` excludes query parameters,
262 * which could be stripped to change the ticket's use.
263 * Older clients mint at the bare path and receive tickets valid for either use.
264 */
265 export const AuthWebSocketTicketUse = Schema.Literals(["rpc", "media"]);
266 export type AuthWebSocketTicketUse = typeof AuthWebSocketTicketUse.Type;
267
268 export const AuthWebSocketTicketParams = Schema.Struct({ use: AuthWebSocketTicketUse });
269
270 export const AuthMcpClientAccess = Schema.Literals([
271 "read-only",
272 "approval-required",
273 "auto-accept-edits",
274 "auto",
275 "full-access",
276 ]);
277 export type AuthMcpClientAccess = typeof AuthMcpClientAccess.Type;
278
279 /** The scopes an agent session gets for an access level, and a pairing code must carry. */
280 export const mcpClientScopes = (access: AuthMcpClientAccess): ReadonlyArray<AuthGrantScope> =>
281 access === "read-only"
282 ? [AuthOrchestrationReadScope]
283 : access === "full-access"
284 ? [
285 AuthOrchestrationReadScope,
286 AuthOrchestrationOperateScope,
287 AuthSettingsWriteScope,
288 AuthSourceControlWriteScope,
289 ]
290 : [AuthOrchestrationReadScope, AuthOrchestrationOperateScope];
291
292 /** The random part of a one-time pairing code: this many characters from this alphabet. */
293 export const PAIRING_CODE_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
294 export const PAIRING_CODE_LENGTH = 12;
295
296 const MCP_APPROVAL_CODE_PREFIXES = {
297 "read-only": "READ",
298 "approval-required": "SUPERVISED",
299 "auto-accept-edits": "EDITS",
300 auto: "AUTO",
301 "full-access": "FULL",
302 } as const satisfies Record<AuthMcpClientAccess, string>;
303
304 const MCP_APPROVAL_CODE_PATTERN = new RegExp(
305 `^(${Object.values(MCP_APPROVAL_CODE_PREFIXES).join("|")})-([${PAIRING_CODE_ALPHABET}]{${PAIRING_CODE_LENGTH}})$`,
306 "i",
307 );
308
309 /** A pairing code that approves one agent sign-in at `access`, such as `AUTO-Q8RZ3NWD5KTC`. */
310 export const mcpApprovalCode = (access: AuthMcpClientAccess, token: string): string =>
311 `${MCP_APPROVAL_CODE_PREFIXES[access]}-${token}`;
312
313 /** The level a code approves and the code as issued, or undefined for any other code. */
314 export function parseMcpApprovalCode(
315 code: string,
316 ): { readonly access: AuthMcpClientAccess; readonly code: string } | undefined {
317 const match = MCP_APPROVAL_CODE_PATTERN.exec(code.trim());
318 if (match === null) return undefined;
319 const prefix = match[1]!.toUpperCase();
320 const access = AuthMcpClientAccess.literals.find(
321 (level) => MCP_APPROVAL_CODE_PREFIXES[level] === prefix,
322 );
323 return access && { access, code: mcpApprovalCode(access, match[2]!.toUpperCase()) };
324 }
325
326 export const AuthPairingCredentialResult = Schema.Struct({
327 id: TrimmedNonEmptyString,
328 credential: TrimmedNonEmptyString,
329 label: Schema.optionalKey(TrimmedNonEmptyString),
330 expiresAt: Schema.DateTimeUtc,
331 purpose: Schema.optionalKey(Schema.Literal("peer-link")),
332 /** Set when the code approves one agent sign-in at this level. Older servers omit it. */
333 access: Schema.optionalKey(AuthMcpClientAccess),
334 });
335 export type AuthPairingCredentialResult = typeof AuthPairingCredentialResult.Type;
336
337 const BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
338
339 /**
340 * A short code both sides show for a T3 Connect device, read from its proof key thumbprint.
341 * The waiting device and the approver compare it so an approval lands on the device in hand.
342 */
343 export function connectDeviceVerificationCode(proofKeyThumbprint: string): string {
344 let code = "";
345 for (const character of proofKeyThumbprint.slice(0, 8)) {
346 const value = Math.max(0, BASE64URL_ALPHABET.indexOf(character));
347 code += PAIRING_CODE_ALPHABET[value % PAIRING_CODE_ALPHABET.length]!;
348 }
349 return `${code.slice(0, 4)}-${code.slice(4)}`;
350 }
351
352 export const AuthClientMetadata = Schema.Struct({
353 label: Schema.optionalKey(TrimmedNonEmptyString),
354 ipAddress: Schema.optionalKey(TrimmedNonEmptyString),
355 userAgent: Schema.optionalKey(TrimmedNonEmptyString),
356 deviceType: AuthClientMetadataDeviceType,
357 os: Schema.optionalKey(TrimmedNonEmptyString),
358 browser: Schema.optionalKey(TrimmedNonEmptyString),
359 });
360 export type AuthClientMetadata = typeof AuthClientMetadata.Type;
361
362 /** A T3 Connect device waiting for someone on this environment to approve it. */
363 export const AuthConnectDeviceRequest = Schema.Struct({
364 verificationCode: TrimmedNonEmptyString,
365 /** What the device said about itself when it first asked. Absent until it does. */
366 client: Schema.optionalKey(AuthClientMetadata),
367 });
368 export type AuthConnectDeviceRequest = typeof AuthConnectDeviceRequest.Type;
369
370 export const AuthPairingLink = Schema.Struct({
371 id: TrimmedNonEmptyString,
372 ...authScopeResponseFields,
373 subject: TrimmedNonEmptyString,
374 label: Schema.optionalKey(TrimmedNonEmptyString),
375 createdAt: Schema.DateTimeUtc,
376 expiresAt: Schema.DateTimeUtc,
377 /** Set while a T3 Connect device waits for approval. Older servers never send it. */
378 connectDeviceRequest: Schema.optionalKey(AuthConnectDeviceRequest),
379 });
380 export type AuthPairingLink = typeof AuthPairingLink.Type;
381
382 /** A T3 Connect device key this environment trusts to connect without asking again. */
383 export const AuthConnectDevice = Schema.Struct({
384 proofKeyThumbprint: TrimmedNonEmptyString,
385 verificationCode: TrimmedNonEmptyString,
386 client: Schema.optionalKey(AuthClientMetadata),
387 approvedAt: Schema.DateTimeUtc,
388 });
389 export type AuthConnectDevice = typeof AuthConnectDevice.Type;
390
391 export const AuthClientSession = Schema.Struct({
392 sessionId: AuthSessionId,
393 subject: TrimmedNonEmptyString,
394 ...authScopeResponseFields,
395 method: ServerAuthSessionMethod,
396 client: AuthClientMetadata,
397 issuedAt: Schema.DateTimeUtc,
398 expiresAt: Schema.DateTimeUtc,
399 lastConnectedAt: Schema.NullOr(Schema.DateTimeUtc),
400 connected: Schema.Boolean,
401 current: Schema.Boolean,
402 });
403 export type AuthClientSession = typeof AuthClientSession.Type;
404
405 export const AuthAccessSnapshot = Schema.Struct({
406 pairingLinks: Schema.Array(AuthPairingLink),
407 clientSessions: Schema.Array(AuthClientSession),
408 /** Older servers omit it; they have no device approval. */
409 connectDevices: Schema.optionalKey(Schema.Array(AuthConnectDevice)),
410 });
411 export type AuthAccessSnapshot = typeof AuthAccessSnapshot.Type;
412
413 export const AuthAccessStreamSnapshotEvent = Schema.Struct({
414 version: Schema.Literal(1),
415 revision: Schema.Number,
416 type: Schema.Literal("snapshot"),
417 payload: AuthAccessSnapshot,
418 });
419 export type AuthAccessStreamSnapshotEvent = typeof AuthAccessStreamSnapshotEvent.Type;
420
421 export const AuthAccessStreamPairingLinkUpsertedEvent = Schema.Struct({
422 version: Schema.Literal(1),
423 revision: Schema.Number,
424 type: Schema.Literal("pairingLinkUpserted"),
425 payload: AuthPairingLink,
426 });
427 export type AuthAccessStreamPairingLinkUpsertedEvent =
428 typeof AuthAccessStreamPairingLinkUpsertedEvent.Type;
429
430 export const AuthAccessStreamPairingLinkRemovedEvent = Schema.Struct({
431 version: Schema.Literal(1),
432 revision: Schema.Number,
433 type: Schema.Literal("pairingLinkRemoved"),
434 payload: Schema.Struct({
435 id: TrimmedNonEmptyString,
436 }),
437 });
438 export type AuthAccessStreamPairingLinkRemovedEvent =
439 typeof AuthAccessStreamPairingLinkRemovedEvent.Type;
440
441 export class AuthAccessStreamError extends Schema.TaggedError<AuthAccessStreamError>()(
442 "AuthAccessStreamError",
443 {
444 message: Schema.String,
445 },
446 ) {}
447
448 export class EnvironmentAuthorizationError extends Schema.TaggedError<EnvironmentAuthorizationError>()(
449 "EnvironmentAuthorizationError",
450 {
451 message: Schema.String,
452 requiredScope: AuthEnvironmentScope,
453 requiredPermission: Schema.optionalKey(Schema.String),
454 },
455 ) {}
456
457 export const AuthAccessStreamClientUpsertedEvent = Schema.Struct({
458 version: Schema.Literal(1),
459 revision: Schema.Number,
460 type: Schema.Literal("clientUpserted"),
461 payload: AuthClientSession,
462 });
463 export type AuthAccessStreamClientUpsertedEvent = typeof AuthAccessStreamClientUpsertedEvent.Type;
464
465 export const AuthAccessStreamClientRemovedEvent = Schema.Struct({
466 version: Schema.Literal(1),
467 revision: Schema.Number,
468 type: Schema.Literal("clientRemoved"),
469 payload: Schema.Struct({
470 sessionId: AuthSessionId,
471 }),
472 });
473 export type AuthAccessStreamClientRemovedEvent = typeof AuthAccessStreamClientRemovedEvent.Type;
474
475 export const AuthAccessStreamEvent = Schema.Union([
476 AuthAccessStreamSnapshotEvent,
477 AuthAccessStreamPairingLinkUpsertedEvent,
478 AuthAccessStreamPairingLinkRemovedEvent,
479 AuthAccessStreamClientUpsertedEvent,
480 AuthAccessStreamClientRemovedEvent,
481 ]);
482 export type AuthAccessStreamEvent = typeof AuthAccessStreamEvent.Type;
483
484 export const AuthRevokePairingLinkInput = Schema.Struct({
485 id: TrimmedNonEmptyString,
486 });
487 export type AuthRevokePairingLinkInput = typeof AuthRevokePairingLinkInput.Type;
488
489 export const AuthRevokeClientSessionInput = Schema.Struct({
490 sessionId: AuthSessionId,
491 });
492 export type AuthRevokeClientSessionInput = typeof AuthRevokeClientSessionInput.Type;
493
494 export const AuthApproveConnectDeviceInput = Schema.Struct({
495 pairingLinkId: TrimmedNonEmptyString,
496 });
497 export type AuthApproveConnectDeviceInput = typeof AuthApproveConnectDeviceInput.Type;
498
499 export const AuthApproveConnectDeviceResult = Schema.Struct({
500 approved: Schema.Boolean,
501 });
502 export type AuthApproveConnectDeviceResult = typeof AuthApproveConnectDeviceResult.Type;
503
504 export const AuthRevokeConnectDeviceInput = Schema.Struct({
505 proofKeyThumbprint: TrimmedNonEmptyString,
506 });
507 export type AuthRevokeConnectDeviceInput = typeof AuthRevokeConnectDeviceInput.Type;
508
509 export const AuthRevokeConnectDeviceResult = Schema.Struct({
510 revoked: Schema.Boolean,
511 });
512 export type AuthRevokeConnectDeviceResult = typeof AuthRevokeConnectDeviceResult.Type;
513
514 const pairingCredentialFields = {
515 label: Schema.optionalKey(TrimmedNonEmptyString),
516 scopes: Schema.optionalKey(AuthGrantScopes),
517 };
518
519 export const AuthCreatePairingCredentialInput = Schema.Union([
520 Schema.Struct({
521 ...pairingCredentialFields,
522 access: Schema.optionalKey(AuthMcpClientAccess),
523 purpose: Schema.optionalKey(Schema.Undefined),
524 }),
525 Schema.Struct({
526 ...pairingCredentialFields,
527 access: AuthMcpClientAccess,
528 purpose: Schema.Literal("peer-link"),
529 }),
530 ]);
531 export type AuthCreatePairingCredentialInput = typeof AuthCreatePairingCredentialInput.Type;
532
533 export const AuthSessionState = Schema.Struct({
534 authenticated: Schema.Boolean,
535 auth: ServerAuthDescriptor,
536 scopes: Schema.optionalKey(AuthEnvironmentScopes),
537 permissions: authScopeResponseFields.permissions,
538 sessionMethod: Schema.optionalKey(ServerAuthSessionMethod),
539 expiresAt: Schema.optionalKey(Schema.DateTimeUtc),
540 });
541 export type AuthSessionState = typeof AuthSessionState.Type;
542
543 export const AuthMcpProtectedResourceMetadata = Schema.Struct({
544 resource: Schema.String,
545 authorization_servers: Schema.Array(Schema.String),
546 scopes_supported: Schema.Array(AuthEnvironmentScope),
547 bearer_methods_supported: Schema.Array(Schema.Literal("header")),
548 resource_name: Schema.String,
549 });
550 export type AuthMcpProtectedResourceMetadata = typeof AuthMcpProtectedResourceMetadata.Type;
551
552 export const AuthMcpAuthorizationServerMetadata = Schema.Struct({
553 issuer: Schema.String,
554 authorization_endpoint: Schema.String,
555 token_endpoint: Schema.String,
556 registration_endpoint: Schema.String,
557 response_types_supported: Schema.Array(Schema.Literal("code")),
558 grant_types_supported: Schema.Array(Schema.Literal("authorization_code")),
559 code_challenge_methods_supported: Schema.Array(Schema.Literal("S256")),
560 token_endpoint_auth_methods_supported: Schema.Array(Schema.Literal("none")),
561 scopes_supported: Schema.Array(AuthEnvironmentScope),
562 authorization_response_iss_parameter_supported: Schema.Boolean,
563 });
564 export type AuthMcpAuthorizationServerMetadata = typeof AuthMcpAuthorizationServerMetadata.Type;
565
566 /**
567 * The `software_id` another T3 Code environment registers with when it links
568 * to this one. Its session is then a peer link: the work it starts here stays
569 * within that link. Claiming it only ever adds limits.
570 */
571 export const MCP_PEER_LINK_SOFTWARE_ID = "t3code-peer-link";
572
573 export const AuthMcpClientRegistration = Schema.Struct({
574 client_name: Schema.optionalKey(Schema.String),
575 software_id: Schema.optionalKey(Schema.String),
576 redirect_uris: Schema.optionalKey(Schema.Array(Schema.String)),
577 token_endpoint_auth_method: Schema.optionalKey(Schema.String),
578 });
579 export type AuthMcpClientRegistration = typeof AuthMcpClientRegistration.Type;
580
581 export const AuthMcpRegisteredClient = Schema.Struct({
582 client_id: Schema.String,
583 client_name: Schema.String,
584 redirect_uris: Schema.Array(Schema.String),
585 grant_types: Schema.Array(Schema.Literal("authorization_code")),
586 response_types: Schema.Array(Schema.Literal("code")),
587 token_endpoint_auth_method: Schema.Literal("none"),
588 }).pipe(HttpApiSchema.status(201));
589 export type AuthMcpRegisteredClient = typeof AuthMcpRegisteredClient.Type;
590
591 export class AuthMcpRegistrationError extends Schema.Error<AuthMcpRegistrationError>(
592 "AuthMcpRegistrationError",
593 )(
594 {
595 error: Schema.Literals(["invalid_client_metadata", "invalid_redirect_uri"]),
596 error_description: Schema.String,
597 },
598 { httpApiStatus: 400 },
599 ) {
600 override get message(): string {
601 return this.error_description;
602 }
603 }
604
605 /** Fields are optional here because the server validates them. */
606 export const AuthMcpAuthorizationRequest = Schema.Struct({
607 response_type: Schema.optionalKey(Schema.String),
608 client_id: Schema.optionalKey(Schema.String),
609 redirect_uri: Schema.optionalKey(Schema.String),
610 code_challenge: Schema.optionalKey(Schema.String),
611 code_challenge_method: Schema.optionalKey(Schema.String),
612 state: Schema.optionalKey(Schema.RedactedFromValue(Schema.String)),
613 resource: Schema.optionalKey(Schema.String),
614 });
615 export type AuthMcpAuthorizationRequest = typeof AuthMcpAuthorizationRequest.Type;
616
617 /** Server-validated request details, trusted by the client only for display. */
618 export const AuthMcpApprovalDetails = Schema.Struct({
619 /** Self-declared by the client, so shown as such. */
620 clientName: Schema.String,
621 redirectHost: Schema.String,
622 environmentHost: Schema.String,
623 csrfToken: Schema.optionalKey(Schema.String),
624 /** Only scopes held by this session qualify; others need a pairing code. Absent with `csrfToken`. */
625 oneClickAccess: Schema.optionalKey(Schema.Array(AuthMcpClientAccess)),
626 /** A managed policy's runtime-mode ceiling; the page loads without the server's config. */
627 runtimeModeCeiling: Schema.optionalKey(
628 Schema.Struct({ organization: Schema.String, maxRuntimeMode: RuntimeMode }),
629 ),
630 });
631 export type AuthMcpApprovalDetails = typeof AuthMcpApprovalDetails.Type;
632
633 export const AuthMcpApprovalRedirect = Schema.Struct({
634 redirectTo: Schema.String,
635 });
636 export type AuthMcpApprovalRedirect = typeof AuthMcpApprovalRedirect.Type;
637
638 export const AuthMcpApprovalDecision = Schema.Union([
639 Schema.TaggedStruct("deny", {}),
640 Schema.TaggedStruct("pairing-code", {
641 access: AuthMcpClientAccess,
642 code: TrimmedNonEmptyString,
643 }),
644 Schema.TaggedStruct("browser-session", {
645 access: AuthMcpClientAccess,
646 csrfToken: Schema.String,
647 }),
648 ]);
649 export type AuthMcpApprovalDecision = typeof AuthMcpApprovalDecision.Type;
650
651 export const AuthMcpApprovalDecisionRequest = Schema.Struct({
652 authorization: AuthMcpAuthorizationRequest,
653 decision: AuthMcpApprovalDecision,
654 });
655 export type AuthMcpApprovalDecisionRequest = typeof AuthMcpApprovalDecisionRequest.Type;
656
657 export class AuthMcpApprovalError extends Schema.TaggedError<AuthMcpApprovalError>()(
658 "AuthMcpApprovalError",
659 { message: Schema.String },
660 { httpApiStatus: 400 },
661 ) {}
662
663 export const AuthMcpTokenRequest = Schema.Struct({
664 grant_type: Schema.optionalKey(Schema.String),
665 code: Schema.optionalKey(Schema.RedactedFromValue(Schema.String)),
666 redirect_uri: Schema.optionalKey(Schema.String),
667 client_id: Schema.optionalKey(Schema.String),
668 code_verifier: Schema.optionalKey(Schema.RedactedFromValue(Schema.String)),
669 resource: Schema.optionalKey(Schema.String),
670 }).pipe(HttpApiSchema.asFormUrlEncoded());
671 export type AuthMcpTokenRequest = typeof AuthMcpTokenRequest.Type;
672
673 export const AuthMcpTokenResult = Schema.Struct({
674 access_token: Schema.String,
675 token_type: Schema.Literal("Bearer"),
676 expires_in: Schema.Number,
677 scope: Schema.String,
678 });
679 export type AuthMcpTokenResult = typeof AuthMcpTokenResult.Type;
680
681 export class AuthMcpTokenError extends Schema.Error<AuthMcpTokenError>("AuthMcpTokenError")(
682 {
683 error: Schema.Literals([
684 "invalid_request",
685 "invalid_client",
686 "invalid_grant",
687 "unsupported_grant_type",
688 ]),
689 error_description: Schema.String,
690 },
691 { httpApiStatus: 400 },
692 ) {
693 override get message(): string {
694 return this.error_description;
695 }
696 }