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

auth.ts

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