@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 137 lines 5.53 KB
Raw
1 /**
2 * The hosted app's side of an agent sign-in on a T3 Connect environment: it reads the request
3 * and sends the decision with the owner's own Connect session there, so no code is needed.
4 */
5 import { msg } from "gt-i18n";
6 import { type MarkedText, markedTextEnglish } from "../errors/translatable.ts";
7 import type {
8 AuthMcpApprovalDecisionRequest,
9 AuthMcpApprovalDetails,
10 AuthMcpAuthorizationRequest,
11 EnvironmentId,
12 } from "@t3tools/contracts";
13 import * as Effect from "effect/Effect";
14 import * as Option from "effect/Option";
15 import type * as HttpClient from "effect/http/HttpClient";
16 import type { Atom } from "effect/reactivity";
17 import * as Schema from "effect/Schema";
18
19 import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
20 import { RelayConnectionTarget } from "../connection/model.ts";
21 import * as ManagedRelay from "../relay/managedRelay.ts";
22 import { executeAuthenticatedEnvironmentHttpRequest } from "./environmentHttpAuth.ts";
23 import { createRuntimeCommand } from "./runtime.ts";
24
25 const REQUEST_TIMEOUT_MS = 10_000;
26
27 /** The environment cannot be reached through T3 Connect with this account. */
28 export class ConnectMcpApprovalUnavailableError extends Schema.TaggedError<ConnectMcpApprovalUnavailableError>()(
29 "ConnectMcpApprovalUnavailableError",
30 { cause: Schema.Defect() },
31 ) {
32 override get message(): string {
33 return markedTextEnglish(this.i18nMessage);
34 }
35
36 get i18nMessage(): MarkedText {
37 return [msg("Could not reach that environment through T3 Connect with this account.")];
38 }
39 }
40
41 export type ConnectMcpApprovalAnswer =
42 | { readonly kind: "details"; readonly details: AuthMcpApprovalDetails }
43 | { readonly kind: "redirect"; readonly url: string }
44 /** The environment refused the request, with a message for the user. */
45 | { readonly kind: "refused"; readonly message: string };
46
47 export type ConnectMcpApprovalCall =
48 | { readonly kind: "approval"; readonly payload: AuthMcpAuthorizationRequest }
49 | { readonly kind: "decision"; readonly payload: AuthMcpApprovalDecisionRequest };
50
51 const answerFrom = (
52 value: AuthMcpApprovalDetails | { readonly redirectTo: string },
53 ): ConnectMcpApprovalAnswer =>
54 "redirectTo" in value
55 ? { kind: "redirect", url: value.redirectTo }
56 : { kind: "details", details: value };
57
58 const refused = (error: { readonly message: string }) =>
59 Effect.succeed<ConnectMcpApprovalAnswer>({ kind: "refused", message: error.message });
60
61 /**
62 * Sends one approval call to `environmentId` with this account's T3 Connect session. Its
63 * address comes from the relay, which only grants access to the environment's owner.
64 */
65 const callConnectMcpApproval = Effect.fn("clientRuntime.state.connectMcpApproval")(
66 function* (input: {
67 readonly environmentId: EnvironmentId;
68 readonly call: ConnectMcpApprovalCall;
69 }) {
70 const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
71 const authorized = yield* remote.authorizeDpopHttp({
72 expectedEnvironmentId: input.environmentId,
73 });
74 const common = {
75 prepared: {
76 environmentId: input.environmentId,
77 httpBaseUrl: authorized.httpBaseUrl,
78 httpAuthorization: authorized.httpAuthorization,
79 target: new RelayConnectionTarget({
80 environmentId: input.environmentId,
81 label: authorized.label,
82 }),
83 },
84 signer: yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner),
85 // A token for an unsaved environment is not cached, so reuse this one until it is rejected.
86 remoteAuthorization: Option.some(
87 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization.of({
88 ...remote,
89 // Untraced: the relay authorization it may call owns the span.
90 authorizeDpopHttp: Effect.fnUntraced(function* (request) {
91 if (request.rejectedAccessToken === undefined) return authorized;
92 return yield* remote.authorizeDpopHttp(request);
93 }),
94 }),
95 ),
96 group: "mcpOAuth",
97 method: "POST",
98 timeoutMs: REQUEST_TIMEOUT_MS,
99 } as const;
100 const { call } = input;
101 const answer =
102 call.kind === "approval"
103 ? yield* executeAuthenticatedEnvironmentHttpRequest({
104 ...common,
105 url: (urls) => urls.approval(),
106 request: ({ client, headers }) =>
107 client
108 .approval({ headers, payload: call.payload })
109 .pipe(Effect.map(answerFrom), Effect.catchTags({ AuthMcpApprovalError: refused })),
110 // The owner's session can always approve; no CSRF token means a stale credential.
111 isUnauthorizedResponse: (answer) =>
112 answer.kind === "details" && answer.details.csrfToken === undefined,
113 })
114 : yield* executeAuthenticatedEnvironmentHttpRequest({
115 ...common,
116 url: (urls) => urls.decision(),
117 request: ({ client, headers }) =>
118 client
119 .decision({ headers, payload: call.payload })
120 .pipe(Effect.map(answerFrom), Effect.catchTags({ AuthMcpApprovalError: refused })),
121 });
122 return { answer, environmentUrl: authorized.httpBaseUrl, environmentLabel: authorized.label };
123 },
124 Effect.mapError((cause) => new ConnectMcpApprovalUnavailableError({ cause })),
125 );
126
127 export function createConnectMcpApprovalCommand<R, E>(
128 runtime: Atom.AtomRuntime<
129 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization | HttpClient.HttpClient | R,
130 E
131 >,
132 ) {
133 return createRuntimeCommand(runtime, {
134 label: "environment-data:connect-mcp-approval",
135 execute: callConnectMcpApproval,
136 });
137 }