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

auth.ts

652 lines24.8 KB

1import * as Schema from "effect/Schema";
2import * as HttpApiSchema from "effect/http-api/HttpApiSchema";
3​
4import {
5 AuthSessionId,
6 ForwardCompatibleArray,
7 ClientSurface,
8 ClientWebDeployment,
9 TrimmedNonEmptyString,
10} from "./baseSchemas.ts";
11​
12/**
13 * Declares the server's overall authentication posture.
14 *
15 * This is a high-level policy label that tells clients how the environment is
16 * expected to be accessed, not a transport detail and not an exhaustive list
17 * of every accepted credential.
18 *
19 * Typical usage:
20 * - rendered in auth/pairing UI so the user understands what kind of
21 * environment they are connecting to
22 * - used by clients to decide whether silent desktop bootstrap is expected or
23 * whether an explicit pairing flow should be shown
24 *
25 * Meanings:
26 * - `desktop-managed-local`: local desktop-managed environment with narrow
27 * trusted bootstrap, intended to avoid login prompts on the same machine
28 * - `loopback-browser`: standalone local server intended for browser pairing on
29 * the same machine
30 * - `remote-reachable`: environment intended to be reached from other devices
31 * or networks, where explicit pairing/auth is expected
32 * - `unsafe-no-auth`: intentionally unauthenticated mode; this is an explicit
33 * unsafe escape hatch, not a normal deployment mode
34 */
35export const ServerAuthPolicy = Schema.Literals([
36 "desktop-managed-local",
37 "loopback-browser",
38 "remote-reachable",
39 "unsafe-no-auth",
40]);
41export type ServerAuthPolicy = typeof ServerAuthPolicy.Type;
42​
43/**
44 * A credential type that can be exchanged for a real authenticated session.
45 *
46 * Bootstrap methods are for establishing trust at the start of a connection or
47 * pairing flow. They are not the long-lived credential used for ordinary
48 * authenticated HTTP / WebSocket traffic after pairing succeeds.
49 *
50 * Current methods:
51 * - `desktop-bootstrap`: a trusted local desktop handoff, used so the desktop
52 * shell can pair the renderer without a login screen
53 * - `one-time-token`: a short-lived pairing token, suitable for manual pairing
54 * flows such as `/pair?token=...`
55 */
56export const ServerAuthBootstrapMethod = Schema.Literals(["desktop-bootstrap", "one-time-token"]);
57export type ServerAuthBootstrapMethod = typeof ServerAuthBootstrapMethod.Type;
58​
59/**
60 * A credential type accepted for steady-state authenticated requests after a
61 * client has already paired.
62 *
63 * These methods are used by the server-wide auth layer for privileged HTTP and
64 * WebSocket access. They are distinct from bootstrap methods so clients can
65 * reason clearly about "pair first, then use session auth".
66 *
67 * Current methods:
68 * - `browser-session-cookie`: cookie-backed browser session, used by the web
69 * app after bootstrap/pairing
70 * - `bearer-access-token`: scoped token suitable for non-cookie or
71 * non-browser clients
72 * - `dpop-access-token`: scoped proof-of-possession token used by managed
73 * relay connections
74 */
75export const ServerAuthSessionMethod = Schema.Literals([
76 "browser-session-cookie",
77 "bearer-access-token",
78 "dpop-access-token",
79]);
80export type ServerAuthSessionMethod = typeof ServerAuthSessionMethod.Type;
81​
82export const AuthOrchestrationReadScope = "orchestration:read" as const;
83export const AuthOrchestrationOperateScope = "orchestration:operate" as const;
84export const AuthSettingsWriteScope = "settings:write" as const;
85export const AuthProvidersManageScope = "providers:manage" as const;
86export const AuthEnvironmentMaintainScope = "environment:maintain" as const;
87export const AuthPreviewOperateScope = "preview:operate" as const;
88export const AuthDiagnosticsReadScope = "diagnostics:read" as const;
89export const AuthTerminalReadScope = "terminal:read" as const;
90export const AuthTerminalOperateScope = "terminal:operate" as const;
91export const AuthSourceControlWriteScope = "source-control:write" as const;
92export const AuthFilesystemReadScope = "filesystem:read" as const;
93export const AuthFilesystemWriteScope = "filesystem:write" as const;
94/** Retained for decoding existing credentials; grants no current RPC access. */
95const AuthReviewWriteScope = "review:write" as const;
96export const AuthAccessReadScope = "access:read" as const;
97export const AuthAccessWriteScope = "access:write" as const;
98export const AuthRelayReadScope = "relay:read" as const;
99export const AuthRelayWriteScope = "relay:write" as const;
100export const AuthEnvironmentScope = Schema.Literals([
101 AuthOrchestrationReadScope,
102 AuthOrchestrationOperateScope,
103 AuthSettingsWriteScope,
104 AuthProvidersManageScope,
105 AuthEnvironmentMaintainScope,
106 AuthPreviewOperateScope,
107 AuthDiagnosticsReadScope,
108 AuthTerminalReadScope,
109 AuthTerminalOperateScope,
110 AuthFilesystemReadScope,
111 AuthFilesystemWriteScope,
112 AuthReviewWriteScope,
113 AuthSourceControlWriteScope,
114 AuthAccessReadScope,
115 AuthAccessWriteScope,
116 AuthRelayReadScope,
117 AuthRelayWriteScope,
118]);
119export type AuthEnvironmentScope = typeof AuthEnvironmentScope.Type;
120export const AuthEnvironmentScopes = Schema.Array(AuthEnvironmentScope);
121export type AuthEnvironmentScopes = typeof AuthEnvironmentScopes.Type;
122​
123export const AuthGrantScope = Schema.Literals(
124 AuthEnvironmentScope.literals.filter((scope) => scope !== AuthReviewWriteScope),
125);
126export type AuthGrantScope = typeof AuthGrantScope.Type;
127export const AuthGrantScopes = Schema.Array(AuthGrantScope);
128export type AuthGrantScopes = typeof AuthGrantScopes.Type;
129​
130// Frozen wire vocabulary for clients released before granular permissions.
131const legacyScopes = new Set<AuthEnvironmentScope>([
132 AuthOrchestrationReadScope,
133 AuthOrchestrationOperateScope,
134 AuthTerminalOperateScope,
135 AuthReviewWriteScope,
136 AuthAccessReadScope,
137 AuthAccessWriteScope,
138 AuthRelayReadScope,
139 AuthRelayWriteScope,
140]);
141​
142/** Format public auth metadata without changing the server's authorization grant. */
143export function authScopeResponse(scopes: ReadonlyArray<AuthEnvironmentScope>) {
144 return { scopes: scopes.filter((scope) => legacyScopes.has(scope)), permissions: scopes };
146​
147const authScopeResponseFields = {
148 scopes: AuthEnvironmentScopes,
149 permissions: Schema.optionalKey(ForwardCompatibleArray(AuthEnvironmentScope)),
150};
151​
152// Only clients talking to an old server use these parent checks. Servers never
153// expand stored grants, and an explicitly empty permissions array grants nothing.
154const legacyParents: Partial<Record<AuthEnvironmentScope, AuthEnvironmentScope>> = {
155 [AuthFilesystemReadScope]: AuthOrchestrationReadScope,
156 [AuthDiagnosticsReadScope]: AuthOrchestrationReadScope,
157 [AuthSettingsWriteScope]: AuthOrchestrationOperateScope,
158 [AuthProvidersManageScope]: AuthOrchestrationOperateScope,
159 [AuthEnvironmentMaintainScope]: AuthOrchestrationOperateScope,
160 [AuthPreviewOperateScope]: AuthOrchestrationOperateScope,
161 [AuthSourceControlWriteScope]: AuthOrchestrationOperateScope,
162 [AuthFilesystemWriteScope]: AuthOrchestrationOperateScope,
163 [AuthTerminalReadScope]: AuthTerminalOperateScope,
164};
165​
166/** Keep permission denials decodable by clients with the original scope enum. */
167export function authScopeRequiredResponse(requiredPermission: AuthEnvironmentScope) {
168 return {
169 requiredScope: legacyParents[requiredPermission] ?? requiredPermission,
170 requiredPermission,
171 };
173​
174export interface SessionGrantInput {
175 readonly authenticated: boolean;
176 readonly scopes?: ReadonlyArray<AuthEnvironmentScope> | undefined;
177 readonly permissions?: ReadonlyArray<AuthEnvironmentScope> | undefined;
178 readonly auth?: { readonly serverUpdateScope?: string | undefined } | undefined;
180​
181export function sessionGrantsScope(
182 session: SessionGrantInput,
183 scope: AuthEnvironmentScope,
184): boolean {
185 if (!session.authenticated) return false;
186 if (session.permissions !== undefined) return session.permissions.includes(scope);
187 if (session.scopes?.includes(scope)) return true;
188 // Also recognize servers from the first granular-scope release.
189 if (session.auth?.serverUpdateScope !== undefined) return false;
190 const parent = legacyParents[scope];
191 return parent !== undefined && session.scopes?.includes(parent) === true;
193​
194/** Old-only grants lost the child permissions formerly implied by their broad scopes. */
195export function sessionHasLegacyPermissions(session: SessionGrantInput): boolean {
196 const permissions = session.permissions;
197 return (
198 session.authenticated &&
199 permissions !== undefined &&
200 permissions.every((scope) => legacyScopes.has(scope)) &&
201 Object.values(legacyParents).some((parent) => permissions.includes(parent))
202 );
204​
205export const AuthStandardClientScopes = [
206 AuthOrchestrationReadScope,
207 AuthOrchestrationOperateScope,
208 AuthSettingsWriteScope,
209 AuthProvidersManageScope,
210 AuthEnvironmentMaintainScope,
211 AuthPreviewOperateScope,
212 AuthDiagnosticsReadScope,
213 AuthTerminalReadScope,
214 AuthTerminalOperateScope,
215 AuthSourceControlWriteScope,
216 AuthFilesystemReadScope,
217 AuthFilesystemWriteScope,
218 AuthRelayReadScope,
219] as const;
220export const AuthAdministrativeScopes = [
221 ...AuthStandardClientScopes,
222 AuthAccessReadScope,
223 AuthAccessWriteScope,
224 AuthRelayWriteScope,
225] as const;
226​
227export const AuthTokenExchangeGrantType =
228 "urn:ietf:params:oauth:grant-type:token-exchange" as const;
229export const AuthAccessTokenType = "urn:ietf:params:oauth:token-type:access_token" as const;
230export const AuthEnvironmentBootstrapTokenType =
231 "urn:t3:params:oauth:token-type:environment-bootstrap" as const;
232​
233/**
234 * Server-advertised auth capabilities for a specific execution environment.
235 *
236 * Clients should treat this as the authoritative description of how that
237 * environment expects to be paired and how authenticated requests should be
238 * made afterward.
239 *
240 * Field meanings:
241 * - `policy`: high-level auth posture for the environment
242 * - `bootstrapMethods`: pairing/bootstrap methods the server is currently
243 * willing to accept
244 * - `sessionMethods`: authenticated request/session methods the server supports
245 * once pairing is complete
246 * - `sessionCookieName`: cookie name clients should expect when
247 * `browser-session-cookie` is in use
248 *
249 * This descriptor is intentionally capability-oriented. It lets clients choose
250 * the right UX without embedding server-specific auth logic or assuming a
251 * single access method.
252 */
253export const ServerAuthDescriptor = Schema.Struct({
254 policy: ServerAuthPolicy,
255 bootstrapMethods: Schema.Array(ServerAuthBootstrapMethod),
256 sessionMethods: Schema.Array(ServerAuthSessionMethod),
257 sessionCookieName: TrimmedNonEmptyString,
258 /** Older servers omit this and authorize self-updates with orchestration:operate. */
259 serverUpdateScope: Schema.optionalKey(Schema.Literal(AuthEnvironmentMaintainScope)),
260});
261export type ServerAuthDescriptor = typeof ServerAuthDescriptor.Type;
262​
263export const AuthBrowserSessionRequest = Schema.Struct({
264 credential: TrimmedNonEmptyString,
265});
266export type AuthBrowserSessionRequest = typeof AuthBrowserSessionRequest.Type;
267​
268export const AuthBrowserSessionResult = Schema.Struct({
269 authenticated: Schema.Literal(true),
270 ...authScopeResponseFields,
271 sessionMethod: ServerAuthSessionMethod,
272 expiresAt: Schema.DateTimeUtc,
273});
274export type AuthBrowserSessionResult = typeof AuthBrowserSessionResult.Type;
275​
276export const AuthClientMetadataDeviceType = Schema.Literals([
277 "desktop",
278 "mobile",
279 "tablet",
280 "bot",
281 "unknown",
282]);
283export type AuthClientMetadataDeviceType = typeof AuthClientMetadataDeviceType.Type;
284​
285export const AuthClientPresentationMetadata = Schema.Struct({
286 label: Schema.optionalKey(TrimmedNonEmptyString),
287 deviceType: Schema.optionalKey(AuthClientMetadataDeviceType),
288 os: Schema.optionalKey(TrimmedNonEmptyString),
289 osMajorVersion: Schema.optionalKey(Schema.Int),
290 deviceModel: Schema.optionalKey(TrimmedNonEmptyString),
291 surface: Schema.optionalKey(ClientSurface),
292 webDeployment: Schema.optionalKey(ClientWebDeployment),
293 browser: Schema.optionalKey(TrimmedNonEmptyString),
294 appVersion: Schema.optionalKey(TrimmedNonEmptyString),
295});
296export type AuthClientPresentationMetadata = typeof AuthClientPresentationMetadata.Type;
297​
298export const AuthTokenExchangeRequest = Schema.Struct({
299 grant_type: Schema.Literal(AuthTokenExchangeGrantType),
300 subject_token: TrimmedNonEmptyString,
301 subject_token_type: Schema.Literal(AuthEnvironmentBootstrapTokenType),
302 requested_token_type: Schema.Literal(AuthAccessTokenType),
303 scope: Schema.optionalKey(TrimmedNonEmptyString),
304 client_label: Schema.optionalKey(TrimmedNonEmptyString),
305 client_device_type: Schema.optionalKey(AuthClientMetadataDeviceType),
306 client_os: Schema.optionalKey(TrimmedNonEmptyString),
307}).pipe(HttpApiSchema.asFormUrlEncoded());
308export type AuthTokenExchangeRequest = typeof AuthTokenExchangeRequest.Type;
309​
310export const AuthAccessTokenResult = Schema.Struct({
311 access_token: TrimmedNonEmptyString,
312 issued_token_type: Schema.Literal(AuthAccessTokenType),
313 token_type: Schema.Literals(["Bearer", "DPoP"]),
314 expires_in: Schema.Number,
315 scope: TrimmedNonEmptyString,
316});
317export type AuthAccessTokenResult = typeof AuthAccessTokenResult.Type;
318​
319export const AuthWebSocketTicketResult = Schema.Struct({
320 ticket: TrimmedNonEmptyString,
321 expiresAt: Schema.DateTimeUtc,
322});
323export type AuthWebSocketTicketResult = typeof AuthWebSocketTicketResult.Type;
324​
325export const AuthPairingCredentialResult = Schema.Struct({
326 id: TrimmedNonEmptyString,
327 credential: TrimmedNonEmptyString,
328 label: Schema.optionalKey(TrimmedNonEmptyString),
329 expiresAt: Schema.DateTimeUtc,
330});
331export type AuthPairingCredentialResult = typeof AuthPairingCredentialResult.Type;
332​
333// Read models contain metadata only. Credentials are returned by creation alone.
334export const AuthPairingLink = Schema.Struct({
335 id: TrimmedNonEmptyString,
336 ...authScopeResponseFields,
337 subject: TrimmedNonEmptyString,
338 label: Schema.optionalKey(TrimmedNonEmptyString),
339 createdAt: Schema.DateTimeUtc,
340 expiresAt: Schema.DateTimeUtc,
341});
342export type AuthPairingLink = typeof AuthPairingLink.Type;
343​
344export const AuthClientMetadata = Schema.Struct({
345 label: Schema.optionalKey(TrimmedNonEmptyString),
346 ipAddress: Schema.optionalKey(TrimmedNonEmptyString),
347 userAgent: Schema.optionalKey(TrimmedNonEmptyString),
348 deviceType: AuthClientMetadataDeviceType,
349 os: Schema.optionalKey(TrimmedNonEmptyString),
350 browser: Schema.optionalKey(TrimmedNonEmptyString),
351});
352export type AuthClientMetadata = typeof AuthClientMetadata.Type;
353​
354export const AuthClientSession = Schema.Struct({
355 sessionId: AuthSessionId,
356 subject: TrimmedNonEmptyString,
357 ...authScopeResponseFields,
358 method: ServerAuthSessionMethod,
359 client: AuthClientMetadata,
360 issuedAt: Schema.DateTimeUtc,
361 expiresAt: Schema.DateTimeUtc,
362 lastConnectedAt: Schema.NullOr(Schema.DateTimeUtc),
363 connected: Schema.Boolean,
364 current: Schema.Boolean,
365});
366export type AuthClientSession = typeof AuthClientSession.Type;
367​
368export const AuthAccessSnapshot = Schema.Struct({
369 pairingLinks: Schema.Array(AuthPairingLink),
370 clientSessions: Schema.Array(AuthClientSession),
371});
372export type AuthAccessSnapshot = typeof AuthAccessSnapshot.Type;
373​
374export const AuthAccessStreamSnapshotEvent = Schema.Struct({
375 version: Schema.Literal(1),
376 revision: Schema.Number,
377 type: Schema.Literal("snapshot"),
378 payload: AuthAccessSnapshot,
379});
380export type AuthAccessStreamSnapshotEvent = typeof AuthAccessStreamSnapshotEvent.Type;
381​
382export const AuthAccessStreamPairingLinkUpsertedEvent = Schema.Struct({
383 version: Schema.Literal(1),
384 revision: Schema.Number,
385 type: Schema.Literal("pairingLinkUpserted"),
386 payload: AuthPairingLink,
387});
388export type AuthAccessStreamPairingLinkUpsertedEvent =
389 typeof AuthAccessStreamPairingLinkUpsertedEvent.Type;
390​
391export const AuthAccessStreamPairingLinkRemovedEvent = Schema.Struct({
392 version: Schema.Literal(1),
393 revision: Schema.Number,
394 type: Schema.Literal("pairingLinkRemoved"),
395 payload: Schema.Struct({
396 id: TrimmedNonEmptyString,
397 }),
398});
399export type AuthAccessStreamPairingLinkRemovedEvent =
400 typeof AuthAccessStreamPairingLinkRemovedEvent.Type;
401​
402export class AuthAccessStreamError extends Schema.TaggedError<AuthAccessStreamError>()(
403 "AuthAccessStreamError",
404 {
405 message: Schema.String,
406 },
407) {}
408​
409export class EnvironmentAuthorizationError extends Schema.TaggedError<EnvironmentAuthorizationError>()(
410 "EnvironmentAuthorizationError",
411 {
412 message: Schema.String,
413 requiredScope: AuthEnvironmentScope,
414 requiredPermission: Schema.optionalKey(Schema.String),
415 },
416) {}
417​
418export const AuthAccessStreamClientUpsertedEvent = Schema.Struct({
419 version: Schema.Literal(1),
420 revision: Schema.Number,
421 type: Schema.Literal("clientUpserted"),
422 payload: AuthClientSession,
423});
424export type AuthAccessStreamClientUpsertedEvent = typeof AuthAccessStreamClientUpsertedEvent.Type;
425​
426export const AuthAccessStreamClientRemovedEvent = Schema.Struct({
427 version: Schema.Literal(1),
428 revision: Schema.Number,
429 type: Schema.Literal("clientRemoved"),
430 payload: Schema.Struct({
431 sessionId: AuthSessionId,
432 }),
433});
434export type AuthAccessStreamClientRemovedEvent = typeof AuthAccessStreamClientRemovedEvent.Type;
435​
436export const AuthAccessStreamEvent = Schema.Union([
437 AuthAccessStreamSnapshotEvent,
438 AuthAccessStreamPairingLinkUpsertedEvent,
439 AuthAccessStreamPairingLinkRemovedEvent,
440 AuthAccessStreamClientUpsertedEvent,
441 AuthAccessStreamClientRemovedEvent,
442]);
443export type AuthAccessStreamEvent = typeof AuthAccessStreamEvent.Type;
444​
445export const AuthRevokePairingLinkInput = Schema.Struct({
446 id: TrimmedNonEmptyString,
447});
448export type AuthRevokePairingLinkInput = typeof AuthRevokePairingLinkInput.Type;
449​
450export const AuthRevokeClientSessionInput = Schema.Struct({
451 sessionId: AuthSessionId,
452});
453export type AuthRevokeClientSessionInput = typeof AuthRevokeClientSessionInput.Type;
454​
455export const AuthCreatePairingCredentialInput = Schema.Struct({
456 label: Schema.optionalKey(TrimmedNonEmptyString),
457 scopes: Schema.optionalKey(AuthGrantScopes),
458});
459export type AuthCreatePairingCredentialInput = typeof AuthCreatePairingCredentialInput.Type;
460​
461export const AuthSessionState = Schema.Struct({
462 authenticated: Schema.Boolean,
463 auth: ServerAuthDescriptor,
464 scopes: Schema.optionalKey(AuthEnvironmentScopes),
465 permissions: authScopeResponseFields.permissions,
466 sessionMethod: Schema.optionalKey(ServerAuthSessionMethod),
467 expiresAt: Schema.optionalKey(Schema.DateTimeUtc),
468});
469export type AuthSessionState = typeof AuthSessionState.Type;
470​
471/**
472 * What an agent signed in through MCP OAuth may do, least to most: only read,
473 * or act on threads that never run above the given runtime mode.
474 */
475export const AuthMcpClientAccess = Schema.Literals([
476 "read-only",
477 "approval-required",
478 "auto-accept-edits",
479 "auto",
480 "full-access",
481]);
482export type AuthMcpClientAccess = typeof AuthMcpClientAccess.Type;
483​
484/** RFC 9728 metadata for an environment's `/mcp` resource. */
485export const AuthMcpProtectedResourceMetadata = Schema.Struct({
486 resource: Schema.String,
487 authorization_servers: Schema.Array(Schema.String),
488 scopes_supported: Schema.Array(AuthEnvironmentScope),
489 bearer_methods_supported: Schema.Array(Schema.Literal("header")),
490 resource_name: Schema.String,
491});
492export type AuthMcpProtectedResourceMetadata = typeof AuthMcpProtectedResourceMetadata.Type;
493​
494/** RFC 8414 metadata for the authorization server MCP clients sign in through. */
495export const AuthMcpAuthorizationServerMetadata = Schema.Struct({
496 issuer: Schema.String,
497 authorization_endpoint: Schema.String,
498 token_endpoint: Schema.String,
499 registration_endpoint: Schema.String,
500 response_types_supported: Schema.Array(Schema.Literal("code")),
501 grant_types_supported: Schema.Array(Schema.Literal("authorization_code")),
502 code_challenge_methods_supported: Schema.Array(Schema.Literal("S256")),
503 token_endpoint_auth_methods_supported: Schema.Array(Schema.Literal("none")),
504 scopes_supported: Schema.Array(AuthEnvironmentScope),
505 authorization_response_iss_parameter_supported: Schema.Boolean,
506});
507export type AuthMcpAuthorizationServerMetadata = typeof AuthMcpAuthorizationServerMetadata.Type;
508​
509/** RFC 7591 client metadata. Fields the server does not use are dropped. */
510export const AuthMcpClientRegistration = Schema.Struct({
511 client_name: Schema.optionalKey(Schema.String),
512 redirect_uris: Schema.optionalKey(Schema.Array(Schema.String)),
513 token_endpoint_auth_method: Schema.optionalKey(Schema.String),
514});
515export type AuthMcpClientRegistration = typeof AuthMcpClientRegistration.Type;
516​
517export const AuthMcpRegisteredClient = Schema.Struct({
518 client_id: Schema.String,
519 client_name: Schema.String,
520 redirect_uris: Schema.Array(Schema.String),
521 grant_types: Schema.Array(Schema.Literal("authorization_code")),
522 response_types: Schema.Array(Schema.Literal("code")),
523 token_endpoint_auth_method: Schema.Literal("none"),
524}).pipe(HttpApiSchema.status(201));
525export type AuthMcpRegisteredClient = typeof AuthMcpRegisteredClient.Type;
526​
527/** RFC 7591 §3.2.2 registration error. */
528export class AuthMcpRegistrationError extends Schema.Error<AuthMcpRegistrationError>(
529 "AuthMcpRegistrationError",
530)(
531 {
532 error: Schema.Literals(["invalid_client_metadata", "invalid_redirect_uri"]),
533 error_description: Schema.String,
534 },
535 { httpApiStatus: 400 },
536) {
537 override get message(): string {
538 return this.error_description;
539 }
541​
542/**
543 * An agent's authorization request, as the approval page received it in its
544 * URL. Every field is checked by the server, so all are optional here.
545 */
546export const AuthMcpAuthorizationRequest = Schema.Struct({
547 response_type: Schema.optionalKey(Schema.String),
548 client_id: Schema.optionalKey(Schema.String),
549 redirect_uri: Schema.optionalKey(Schema.String),
550 code_challenge: Schema.optionalKey(Schema.String),
551 code_challenge_method: Schema.optionalKey(Schema.String),
552 state: Schema.optionalKey(Schema.String),
553 resource: Schema.optionalKey(Schema.String),
554});
555export type AuthMcpAuthorizationRequest = typeof AuthMcpAuthorizationRequest.Type;
556​
557/**
558 * What the approval page needs to show for an MCP OAuth sign-in. The server
559 * has already validated the request; nothing here is trusted by the client
560 * except for display.
561 */
562export const AuthMcpApprovalDetails = Schema.Struct({
563 /** Self-declared by the client, so shown as such. */
564 clientName: Schema.String,
565 /**
566 * Where the code goes: a loopback address on the browser's machine (a CLI
567 * agent), or an https host (a hosted agent).
568 */
569 redirectHost: Schema.String,
570 environmentHost: Schema.String,
571 /** Present when this browser's session may approve without a pairing code. */
572 csrfToken: Schema.optionalKey(Schema.String),
573 /**
574 * What that session may approve in one click: only access whose scopes it
575 * holds. Anything else still needs a pairing code. Absent with `csrfToken`.
576 */
577 oneClickAccess: Schema.optionalKey(Schema.Array(AuthMcpClientAccess)),
578});
579export type AuthMcpApprovalDetails = typeof AuthMcpApprovalDetails.Type;
580​
581/**
582 * Where the approval page sends the browser next: back to the agent with a
583 * code, a denial, or a protocol error the agent should receive.
584 */
585export const AuthMcpApprovalRedirect = Schema.Struct({
586 redirectTo: Schema.String,
587});
588export type AuthMcpApprovalRedirect = typeof AuthMcpApprovalRedirect.Type;
589​
590export const AuthMcpApprovalDecision = Schema.Union([
591 Schema.TaggedStruct("deny", {}),
592 Schema.TaggedStruct("pairing-code", {
593 access: AuthMcpClientAccess,
594 code: TrimmedNonEmptyString,
595 }),
596 /** One click, for a browser session that may approve (see `csrfToken`). */
597 Schema.TaggedStruct("browser-session", {
598 access: AuthMcpClientAccess,
599 csrfToken: Schema.String,
600 }),
601]);
602export type AuthMcpApprovalDecision = typeof AuthMcpApprovalDecision.Type;
603​
604export const AuthMcpApprovalDecisionRequest = Schema.Struct({
605 authorization: AuthMcpAuthorizationRequest,
606 decision: AuthMcpApprovalDecision,
607});
608export type AuthMcpApprovalDecisionRequest = typeof AuthMcpApprovalDecisionRequest.Type;
609​
610/** A problem the approval page shows the user without redirecting anywhere. */
611export class AuthMcpApprovalError extends Schema.TaggedError<AuthMcpApprovalError>()(
612 "AuthMcpApprovalError",
613 { message: Schema.String },
614 { httpApiStatus: 400 },
615) {}
616​
617/** RFC 6749 §4.1.3 token request. Every field is checked by the server. */
618export const AuthMcpTokenRequest = Schema.Struct({
619 grant_type: Schema.optionalKey(Schema.String),
620 code: Schema.optionalKey(Schema.String),
621 redirect_uri: Schema.optionalKey(Schema.String),
622 client_id: Schema.optionalKey(Schema.String),
623 code_verifier: Schema.optionalKey(Schema.String),
624 resource: Schema.optionalKey(Schema.String),
625}).pipe(HttpApiSchema.asFormUrlEncoded());
626export type AuthMcpTokenRequest = typeof AuthMcpTokenRequest.Type;
627​
628export const AuthMcpTokenResult = Schema.Struct({
629 access_token: Schema.String,
630 token_type: Schema.Literal("Bearer"),
631 expires_in: Schema.Number,
632 scope: Schema.String,
633});
634export type AuthMcpTokenResult = typeof AuthMcpTokenResult.Type;
635​
636/** RFC 6749 §5.2 token error. */
637export class AuthMcpTokenError extends Schema.Error<AuthMcpTokenError>("AuthMcpTokenError")(
638 {
639 error: Schema.Literals([
640 "invalid_request",
641 "invalid_client",
642 "invalid_grant",
643 "unsupported_grant_type",
644 ]),
645 error_description: Schema.String,
646 },
647 { httpApiStatus: 400 },
648) {
649 override get message(): string {
650 return this.error_description;
651 }