Open History to see the last commit
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;
34// Also decides where credentials go: secret providers, references, and key-bearing endpoints.
35export const AuthProvidersManageScope = "providers:manage" as const;
36export const AuthEnvironmentMaintainScope = "environment:maintain" as const;
37export const AuthPreviewOperateScope = "preview:operate" as const;
38export const AuthDiagnosticsReadScope = "diagnostics:read" as const;
39export const AuthTerminalReadScope = "terminal:read" as const;
40export const AuthTerminalOperateScope = "terminal:operate" as const;
41export const AuthSourceControlWriteScope = "source-control:write" as const;
42export const AuthFilesystemReadScope = "filesystem:read" as const;
43export const AuthFilesystemWriteScope = "filesystem:write" as const;
44/** Retained for decoding existing credentials; grants no current RPC access. */
45const AuthReviewWriteScope = "review:write" as const;
46export const AuthAccessReadScope = "access:read" as const;
47export const AuthAccessWriteScope = "access:write" as const;
48export const AuthRelayReadScope = "relay:read" as const;
49export const AuthRelayWriteScope = "relay:write" as const;
50export const AuthRelayConfigureScope = "relay:configure" as const;
51export 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]);
71export type AuthEnvironmentScope = typeof AuthEnvironmentScope.Type;
72export const AuthEnvironmentScopes = Schema.Array(AuthEnvironmentScope);
73export type AuthEnvironmentScopes = typeof AuthEnvironmentScopes.Type;
74
75export const AuthGrantScope = Schema.Literals(
76 AuthEnvironmentScope.literals.filter((scope) => scope !== AuthReviewWriteScope),
77);
78export type AuthGrantScope = typeof AuthGrantScope.Type;
79export const AuthGrantScopes = Schema.Array(AuthGrantScope);
80export type AuthGrantScopes = typeof AuthGrantScopes.Type;
81
82const legacyScopes = new Set<AuthEnvironmentScope>([
83 AuthOrchestrationReadScope,
84 AuthOrchestrationOperateScope,
85 AuthTerminalOperateScope,
86 AuthReviewWriteScope,
87 AuthAccessReadScope,
88 AuthAccessWriteScope,
89 AuthRelayReadScope,
90 AuthRelayWriteScope,
91]);
92
93export function authScopeResponse(scopes: ReadonlyArray<AuthEnvironmentScope>) {
94 return { scopes: scopes.filter((scope) => legacyScopes.has(scope)), permissions: scopes };
95}
96
97const 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.
103const 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. */
116export function authScopeRequiredResponse(requiredPermission: AuthEnvironmentScope) {
117 return {
118 requiredScope:
119 requiredPermission === AuthRelayConfigureScope
120 ? AuthRelayWriteScope
121 : (legacyParents[requiredPermission] ?? requiredPermission),
122 requiredPermission,
123 };
124}
125
126export 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
133export 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
145export 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.
156export 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
175export const AuthAdministrativeClientScopes = [
176 ...AuthStandardClientScopes,
177 AuthRelayConfigureScope,
178] as const;
179
180export const AuthTokenExchangeGrantType =
181 "urn:ietf:params:oauth:grant-type:token-exchange" as const;
182export const AuthAccessTokenType = "urn:ietf:params:oauth:token-type:access_token" as const;
183export const AuthEnvironmentBootstrapTokenType =
184 "urn:t3:params:oauth:token-type:environment-bootstrap" as const;
185
186export 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});
194export type ServerAuthDescriptor = typeof ServerAuthDescriptor.Type;
195
196export const AuthBrowserSessionRequest = Schema.Struct({
197 credential: TrimmedNonEmptyString,
198});
199export type AuthBrowserSessionRequest = typeof AuthBrowserSessionRequest.Type;
200
201export const AuthBrowserSessionResult = Schema.Struct({
202 authenticated: Schema.Literal(true),
203 ...authScopeResponseFields,
204 sessionMethod: ServerAuthSessionMethod,
205 expiresAt: Schema.DateTimeUtc,
206});
207export type AuthBrowserSessionResult = typeof AuthBrowserSessionResult.Type;
208
209export const AuthClientMetadataDeviceType = Schema.Literals([
210 "desktop",
211 "mobile",
212 "tablet",
213 "bot",
214 "unknown",
215]);
216export type AuthClientMetadataDeviceType = typeof AuthClientMetadataDeviceType.Type;
217
218export 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});
229export type AuthClientPresentationMetadata = typeof AuthClientPresentationMetadata.Type;
230
231export 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());
242export type AuthTokenExchangeRequest = typeof AuthTokenExchangeRequest.Type;
243
244export 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});
251export type AuthAccessTokenResult = typeof AuthAccessTokenResult.Type;
252
253export const AuthWebSocketTicketResult = Schema.Struct({
254 ticket: Schema.RedactedFromValue(TrimmedNonEmptyString),
255 expiresAt: Schema.DateTimeUtc,
256});
257export 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 */
265export const AuthWebSocketTicketUse = Schema.Literals(["rpc", "media"]);
266export type AuthWebSocketTicketUse = typeof AuthWebSocketTicketUse.Type;
267
268export const AuthWebSocketTicketParams = Schema.Struct({ use: AuthWebSocketTicketUse });
269
270export const AuthMcpClientAccess = Schema.Literals([
271 "read-only",
272 "approval-required",
273 "auto-accept-edits",
274 "auto",
275 "full-access",
276]);
277export type AuthMcpClientAccess = typeof AuthMcpClientAccess.Type;
278
279/** The scopes an agent session gets for an access level, and a pairing code must carry. */
280export 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. */
293export const PAIRING_CODE_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
294export const PAIRING_CODE_LENGTH = 12;
295
296const 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
304const 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`. */
310export 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. */
314export 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
326export 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});
335export type AuthPairingCredentialResult = typeof AuthPairingCredentialResult.Type;
336
337const 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 */
343export 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
352export 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});
360export type AuthClientMetadata = typeof AuthClientMetadata.Type;
361
362/** A T3 Connect device waiting for someone on this environment to approve it. */
363export 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});
368export type AuthConnectDeviceRequest = typeof AuthConnectDeviceRequest.Type;
369
370export 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});
380export type AuthPairingLink = typeof AuthPairingLink.Type;
381
382/** A T3 Connect device key this environment trusts to connect without asking again. */
383export const AuthConnectDevice = Schema.Struct({
384 proofKeyThumbprint: TrimmedNonEmptyString,
385 verificationCode: TrimmedNonEmptyString,
386 client: Schema.optionalKey(AuthClientMetadata),
387 approvedAt: Schema.DateTimeUtc,
388});
389export type AuthConnectDevice = typeof AuthConnectDevice.Type;
390
391export 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});
403export type AuthClientSession = typeof AuthClientSession.Type;
404
405export 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});
411export type AuthAccessSnapshot = typeof AuthAccessSnapshot.Type;
412
413export const AuthAccessStreamSnapshotEvent = Schema.Struct({
414 version: Schema.Literal(1),
415 revision: Schema.Number,
416 type: Schema.Literal("snapshot"),
417 payload: AuthAccessSnapshot,
418});
419export type AuthAccessStreamSnapshotEvent = typeof AuthAccessStreamSnapshotEvent.Type;
420
421export const AuthAccessStreamPairingLinkUpsertedEvent = Schema.Struct({
422 version: Schema.Literal(1),
423 revision: Schema.Number,
424 type: Schema.Literal("pairingLinkUpserted"),
425 payload: AuthPairingLink,
426});
427export type AuthAccessStreamPairingLinkUpsertedEvent =
428 typeof AuthAccessStreamPairingLinkUpsertedEvent.Type;
429
430export 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});
438export type AuthAccessStreamPairingLinkRemovedEvent =
439 typeof AuthAccessStreamPairingLinkRemovedEvent.Type;
440
441export class AuthAccessStreamError extends Schema.TaggedError<AuthAccessStreamError>()(
442 "AuthAccessStreamError",
443 {
444 message: Schema.String,
445 },
446) {}
447
448export 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
457export const AuthAccessStreamClientUpsertedEvent = Schema.Struct({
458 version: Schema.Literal(1),
459 revision: Schema.Number,
460 type: Schema.Literal("clientUpserted"),
461 payload: AuthClientSession,
462});
463export type AuthAccessStreamClientUpsertedEvent = typeof AuthAccessStreamClientUpsertedEvent.Type;
464
465export 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});
473export type AuthAccessStreamClientRemovedEvent = typeof AuthAccessStreamClientRemovedEvent.Type;
474
475export const AuthAccessStreamEvent = Schema.Union([
476 AuthAccessStreamSnapshotEvent,
477 AuthAccessStreamPairingLinkUpsertedEvent,
478 AuthAccessStreamPairingLinkRemovedEvent,
479 AuthAccessStreamClientUpsertedEvent,
480 AuthAccessStreamClientRemovedEvent,
481]);
482export type AuthAccessStreamEvent = typeof AuthAccessStreamEvent.Type;
483
484export const AuthRevokePairingLinkInput = Schema.Struct({
485 id: TrimmedNonEmptyString,
486});
487export type AuthRevokePairingLinkInput = typeof AuthRevokePairingLinkInput.Type;
488
489export const AuthRevokeClientSessionInput = Schema.Struct({
490 sessionId: AuthSessionId,
491});
492export type AuthRevokeClientSessionInput = typeof AuthRevokeClientSessionInput.Type;
493
494export const AuthApproveConnectDeviceInput = Schema.Struct({
495 pairingLinkId: TrimmedNonEmptyString,
496});
497export type AuthApproveConnectDeviceInput = typeof AuthApproveConnectDeviceInput.Type;
498
499export const AuthApproveConnectDeviceResult = Schema.Struct({
500 approved: Schema.Boolean,
501});
502export type AuthApproveConnectDeviceResult = typeof AuthApproveConnectDeviceResult.Type;
503
504export const AuthRevokeConnectDeviceInput = Schema.Struct({
505 proofKeyThumbprint: TrimmedNonEmptyString,
506});
507export type AuthRevokeConnectDeviceInput = typeof AuthRevokeConnectDeviceInput.Type;
508
509export const AuthRevokeConnectDeviceResult = Schema.Struct({
510 revoked: Schema.Boolean,
511});
512export type AuthRevokeConnectDeviceResult = typeof AuthRevokeConnectDeviceResult.Type;
513
514const pairingCredentialFields = {
515 label: Schema.optionalKey(TrimmedNonEmptyString),
516 scopes: Schema.optionalKey(AuthGrantScopes),
517};
518
519export 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]);
531export type AuthCreatePairingCredentialInput = typeof AuthCreatePairingCredentialInput.Type;
532
533export 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});
541export type AuthSessionState = typeof AuthSessionState.Type;
542
543export 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});
550export type AuthMcpProtectedResourceMetadata = typeof AuthMcpProtectedResourceMetadata.Type;
551
552export const AuthMcpAuthorizationServerMetadata = Schema.Struct({
553 issuer: Schema.String,
554 authorization_endpoint: Schema.String,
555 token_endpoint: Schema.String,
556 registration_endpoint: Schema.String,
557 // Older environments do not serve one.
558 revocation_endpoint: Schema.optionalKey(Schema.String),
559 response_types_supported: Schema.Array(Schema.Literal("code")),
560 grant_types_supported: Schema.Array(Schema.Literal("authorization_code")),
561 code_challenge_methods_supported: Schema.Array(Schema.Literal("S256")),
562 token_endpoint_auth_methods_supported: Schema.Array(Schema.Literal("none")),
563 scopes_supported: Schema.Array(AuthEnvironmentScope),
564 authorization_response_iss_parameter_supported: Schema.Boolean,
565});
566export type AuthMcpAuthorizationServerMetadata = typeof AuthMcpAuthorizationServerMetadata.Type;
567
568/**
569 * The `software_id` another T3 Code environment registers with when it links
570 * to this one. Its session is then a peer link: the work it starts here stays
571 * within that link. Claiming it only ever adds limits.
572 */
573export const MCP_PEER_LINK_SOFTWARE_ID = "t3code-peer-link";
574
575export const AuthMcpClientRegistration = Schema.Struct({
576 client_name: Schema.optionalKey(Schema.String),
577 software_id: Schema.optionalKey(Schema.String),
578 redirect_uris: Schema.optionalKey(Schema.Array(Schema.String)),
579 token_endpoint_auth_method: Schema.optionalKey(Schema.String),
580});
581export type AuthMcpClientRegistration = typeof AuthMcpClientRegistration.Type;
582
583export const AuthMcpRegisteredClient = Schema.Struct({
584 client_id: Schema.String,
585 client_name: Schema.String,
586 redirect_uris: Schema.Array(Schema.String),
587 grant_types: Schema.Array(Schema.Literal("authorization_code")),
588 response_types: Schema.Array(Schema.Literal("code")),
589 token_endpoint_auth_method: Schema.Literal("none"),
590}).pipe(HttpApiSchema.status(201));
591export type AuthMcpRegisteredClient = typeof AuthMcpRegisteredClient.Type;
592
593export class AuthMcpRegistrationError extends Schema.Error<AuthMcpRegistrationError>(
594 "AuthMcpRegistrationError",
595)(
596 {
597 error: Schema.Literals(["invalid_client_metadata", "invalid_redirect_uri"]),
598 error_description: Schema.String,
599 },
600 { httpApiStatus: 400 },
601) {
602 override get message(): string {
603 return this.error_description;
604 }
605}
606
607/** Fields are optional here because the server validates them. */
608export const AuthMcpAuthorizationRequest = Schema.Struct({
609 response_type: Schema.optionalKey(Schema.String),
610 client_id: Schema.optionalKey(Schema.String),
611 redirect_uri: Schema.optionalKey(Schema.String),
612 code_challenge: Schema.optionalKey(Schema.String),
613 code_challenge_method: Schema.optionalKey(Schema.String),
614 state: Schema.optionalKey(Schema.RedactedFromValue(Schema.String)),
615 resource: Schema.optionalKey(Schema.String),
616});
617export type AuthMcpAuthorizationRequest = typeof AuthMcpAuthorizationRequest.Type;
618
619/** Server-validated request details, trusted by the client only for display. */
620export const AuthMcpApprovalDetails = Schema.Struct({
621 /** Self-declared by the client, so shown as such. */
622 clientName: Schema.String,
623 redirectHost: Schema.String,
624 environmentHost: Schema.String,
625 csrfToken: Schema.optionalKey(Schema.String),
626 /** Only scopes held by this session qualify; others need a pairing code. Absent with `csrfToken`. */
627 oneClickAccess: Schema.optionalKey(Schema.Array(AuthMcpClientAccess)),
628 /** A managed policy's runtime-mode ceiling; the page loads without the server's config. */
629 runtimeModeCeiling: Schema.optionalKey(
630 Schema.Struct({ organization: Schema.String, maxRuntimeMode: RuntimeMode }),
631 ),
632});
633export type AuthMcpApprovalDetails = typeof AuthMcpApprovalDetails.Type;
634
635export const AuthMcpApprovalRedirect = Schema.Struct({
636 redirectTo: Schema.String,
637});
638export type AuthMcpApprovalRedirect = typeof AuthMcpApprovalRedirect.Type;
639
640export const AuthMcpApprovalDecision = Schema.Union([
641 Schema.TaggedStruct("deny", {}),
642 Schema.TaggedStruct("pairing-code", {
643 access: AuthMcpClientAccess,
644 code: TrimmedNonEmptyString,
645 }),
646 Schema.TaggedStruct("browser-session", {
647 access: AuthMcpClientAccess,
648 csrfToken: Schema.String,
649 }),
650]);
651export type AuthMcpApprovalDecision = typeof AuthMcpApprovalDecision.Type;
652
653export const AuthMcpApprovalDecisionRequest = Schema.Struct({
654 authorization: AuthMcpAuthorizationRequest,
655 decision: AuthMcpApprovalDecision,
656});
657export type AuthMcpApprovalDecisionRequest = typeof AuthMcpApprovalDecisionRequest.Type;
658
659export class AuthMcpApprovalError extends Schema.TaggedError<AuthMcpApprovalError>()(
660 "AuthMcpApprovalError",
661 { message: Schema.String },
662 { httpApiStatus: 400 },
663) {}
664
665export const AuthMcpTokenRequest = Schema.Struct({
666 grant_type: Schema.optionalKey(Schema.String),
667 code: Schema.optionalKey(Schema.RedactedFromValue(Schema.String)),
668 redirect_uri: Schema.optionalKey(Schema.String),
669 client_id: Schema.optionalKey(Schema.String),
670 code_verifier: Schema.optionalKey(Schema.RedactedFromValue(Schema.String)),
671 resource: Schema.optionalKey(Schema.String),
672}).pipe(HttpApiSchema.asFormUrlEncoded());
673export type AuthMcpTokenRequest = typeof AuthMcpTokenRequest.Type;
674
675/** RFC 7009: the holder of an access token ends its session. */
676export const AuthMcpRevokeRequest = Schema.Struct({
677 token: Schema.optionalKey(Schema.RedactedFromValue(Schema.String)),
678 token_type_hint: Schema.optionalKey(Schema.String),
679}).pipe(HttpApiSchema.asFormUrlEncoded());
680export type AuthMcpRevokeRequest = typeof AuthMcpRevokeRequest.Type;
681
682export const AuthMcpTokenResult = Schema.Struct({
683 access_token: Schema.String,
684 token_type: Schema.Literal("Bearer"),
685 expires_in: Schema.Number,
686 scope: Schema.String,
687});
688export type AuthMcpTokenResult = typeof AuthMcpTokenResult.Type;
689
690export class AuthMcpTokenError extends Schema.Error<AuthMcpTokenError>("AuthMcpTokenError")(
691 {
692 error: Schema.Literals([
693 "invalid_request",
694 "invalid_client",
695 "invalid_grant",
696 "unsupported_grant_type",
697 ]),
698 error_description: Schema.String,
699 },
700 { httpApiStatus: 400 },
701) {
702 override get message(): string {
703 return this.error_description;
704 }
705}