Open History to see the last commit
1import {
2 type AuthEnvironmentScope,
3 type AuthSessionId,
4 AuthStandardClientScopes,
5 EnvironmentHttpApi,
6 type PeerLinkClientPairingCredential,
7 type PeerLinkClientPairingInput,
8 type PeerLinkClientPairingRequest,
9 type PeerLinkClientPairingResult,
10 PeerLinkError,
11 type PeerLinkLinkPairingInput,
12} from "@t3tools/contracts";
13import * as Context from "effect/Context";
14import * as DateTime from "effect/DateTime";
15import * as Duration from "effect/Duration";
16import * as Effect from "effect/Effect";
17import * as Layer from "effect/Layer";
18import * as Option from "effect/Option";
19import * as Schema from "effect/Schema";
20import * as HttpClient from "effect/http/HttpClient";
21import * as HttpApi from "effect/http-api/HttpApi";
22import * as HttpApiClient from "effect/http-api/HttpApiClient";
23
24import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
25import * as ServerSettings from "../serverSettings.ts";
26import * as PeerLinks from "./PeerLinks.ts";
27
28/** Long enough for the client to reach the linked environment and redeem it, and no longer. */
29const CLIENT_PAIRING_TTL = Duration.minutes(3);
30const CLIENT_LABEL_MAX_LENGTH = 80;
31
32const ClientPairingApi = HttpApi.make(EnvironmentHttpApi.identifier)
33 .add(EnvironmentHttpApi.groups.peerLink)
34 .annotateMerge(EnvironmentHttpApi.annotations);
35
36/** Why the linked environment will not mint a client pairing for this caller. */
37export class PeerClientPairingRefused extends Schema.TaggedError<PeerClientPairingRefused>()(
38 "PeerClientPairingRefused",
39 {
40 reason: Schema.Literals(["disabled", "not_a_full_access_link", "no_scopes", "policy"]),
41 message: Schema.String,
42 },
43) {}
44
45/**
46 * The linked side: mints a one-time pairing credential for a client of the environment that
47 * links here, when that environment asks over its link.
48 */
49export class PeerClientPairingIssuer extends Context.Service<
50 PeerClientPairingIssuer,
51 {
52 readonly issue: (
53 caller: EnvironmentAuth.McpClientSession,
54 request: PeerLinkClientPairingRequest,
55 ) => Effect.Effect<
56 PeerLinkClientPairingCredential,
57 PeerClientPairingRefused | EnvironmentAuth.ServerAuthInternalError
58 >;
59 }
60>()("t3/peer/PeerClientPairing/PeerClientPairingIssuer") {}
61
62/**
63 * The linking side: gets a client of this environment a pairing credential for an environment
64 * this one links to, so the client can connect there itself.
65 */
66export class PeerClientPairing extends Context.Service<
67 PeerClientPairing,
68 {
69 readonly request: (
70 input: PeerLinkClientPairingInput,
71 client: {
72 readonly sessionId: AuthSessionId;
73 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
74 },
75 ) => Effect.Effect<PeerLinkClientPairingResult, PeerLinkError>;
76 /**
77 * Gets a pairing code from an environment this one links to, for the client to link another
78 * environment there with. The client made the request, so it is named beside the code.
79 */
80 readonly requestForLink: (
81 input: PeerLinkLinkPairingInput,
82 client: { readonly sessionId: AuthSessionId },
83 ) => Effect.Effect<PeerLinkClientPairingResult, PeerLinkError>;
84 }
85>()("t3/peer/PeerClientPairing") {}
86
87const makeIssuer = Effect.gen(function* () {
88 const auth = yield* EnvironmentAuth.EnvironmentAuth;
89 const serverSettings = yield* ServerSettings.ServerSettingsService;
90 const maxRuntimeMode = serverSettings.managedPolicy?.limits?.maxRuntimeMode;
91 const enabled = serverSettings.getSettings.pipe(
92 Effect.map((settings) => settings.linkedEnvironmentsEnabled),
93 Effect.orElseSucceed(() => false),
94 );
95
96 const issue: PeerClientPairingIssuer["Service"]["issue"] = Effect.fn(
97 "PeerClientPairingIssuer.issue",
98 )(function* (caller, request) {
99 if (!(yield* enabled)) {
100 return yield* new PeerClientPairingRefused({
101 reason: "disabled",
102 message: PeerLinks.LINKED_ENVIRONMENTS_OFF,
103 });
104 }
105 // A full-access link's agents already run as this machine's user and could run
106 // `t3 auth pairing create` themselves, so minting here adds no power. Any lower link would
107 // gain more than it holds, and so would one an administrator's ceiling holds below full access.
108 if (
109 !caller.peerLink ||
110 caller.access !== "full-access" ||
111 (maxRuntimeMode !== undefined && maxRuntimeMode !== "full-access")
112 ) {
113 return yield* new PeerClientPairingRefused({
114 reason: "not_a_full_access_link",
115 message: "Only a full-access link may pair a client here.",
116 });
117 }
118 const via = caller.label.startsWith(PeerLinks.LINK_CLIENT_NAME_PREFIX)
119 ? caller.label.slice(PeerLinks.LINK_CLIENT_NAME_PREFIX.length)
120 : caller.label;
121 const refusedByPolicy = (error: { readonly message: string }) =>
122 Effect.fail(new PeerClientPairingRefused({ reason: "policy", message: error.message }));
123 if (request.link !== undefined) {
124 // A link pairing code, as this machine's own Sharing & access would mint: the full-access
125 // caller could mint it by running the CLI here, so no access level is more than it holds.
126 const issued = yield* auth
127 .issuePairingCredential({
128 access: request.link.access,
129 purpose: "peer-link",
130 label: `Link · via ${via}`,
131 })
132 .pipe(Effect.catchTags({ ManagedPolicyRefusedError: refusedByPolicy }));
133 return { credential: issued.credential, expiresAt: issued.expiresAt };
134 }
135 // Never more than the client holds where it asked, nor more than a pairing code grants.
136 const scopes = AuthStandardClientScopes.filter((scope) => request.scopes.includes(scope));
137 if (scopes.length === 0) {
138 return yield* new PeerClientPairingRefused({
139 reason: "no_scopes",
140 message: "The client holds no access a pairing could carry.",
141 });
142 }
143 const clientLabel = Array.from(request.clientLabel).slice(0, CLIENT_LABEL_MAX_LENGTH).join("");
144 const issued = yield* auth
145 .createPairingLink({
146 scopes,
147 ttl: CLIENT_PAIRING_TTL,
148 label: `${clientLabel} · via ${via}`,
149 })
150 .pipe(Effect.catchTags({ ManagedPolicyRefusedError: refusedByPolicy }));
151 return { credential: issued.credential, expiresAt: issued.expiresAt };
152 });
153
154 return PeerClientPairingIssuer.of({ issue });
155});
156
157export const layerIssuer = Layer.effect(PeerClientPairingIssuer, makeIssuer);
158
159const make = Effect.gen(function* () {
160 const links = yield* PeerLinks.PeerLinks;
161 const auth = yield* EnvironmentAuth.EnvironmentAuth;
162 const httpClient = yield* HttpClient.HttpClient;
163
164 /** What this environment's Connections calls the client that asked. */
165 const clientLabelOf = (sessionId: AuthSessionId) =>
166 auth.listClientSessions(sessionId).pipe(
167 Effect.map((sessions) => {
168 const client = sessions.find((session) => session.sessionId === sessionId)?.client;
169 return (
170 client?.label ??
171 ([client?.browser, client?.os].filter((part) => part !== undefined).join(" on ") ||
172 "T3 Code client")
173 );
174 }),
175 Effect.orElseSucceed(() => "T3 Code client"),
176 );
177
178 /** Asks the linked environment for a pairing; `payload` says for whom. */
179 const ask = Effect.fn("PeerClientPairing.ask")(function* (
180 input: { readonly environmentId: PeerLinkClientPairingInput["environmentId"] },
181 sessionId: AuthSessionId,
182 payload: (clientLabel: string) => PeerLinkClientPairingRequest,
183 ) {
184 if (!(yield* links.enabled)) {
185 return yield* new PeerLinkError({
186 reason: "disabled",
187 message: PeerLinks.LINKED_ENVIRONMENTS_OFF,
188 });
189 }
190 const stored = yield* links.get(input.environmentId);
191 if (Option.isNone(stored)) {
192 return yield* new PeerLinkError({
193 reason: "unknown_link",
194 message: "This environment is no longer linked to that one.",
195 });
196 }
197 const { environmentId, label, urls, access, expiresAt } = stored.value;
198 if (DateTime.isLessThanOrEqualTo(expiresAt, yield* DateTime.now)) {
199 return yield* new PeerLinkError({
200 reason: "expired",
201 message: `The link to ${label} expired. Link it again with a new pairing code from ${label}.`,
202 });
203 }
204 const unsupported = (
205 reason: Extract<PeerLinkClientPairingResult, { type: "unsupported" }>["reason"],
206 name = label,
207 ): PeerLinkClientPairingResult => ({
208 type: "unsupported",
209 environmentId,
210 label: name,
211 urls,
212 reason,
213 });
214 // The linked environment refuses this too; asking would only spend a round trip.
215 if (access !== "full-access") return unsupported("link_access");
216 const resolved = yield* links.resolve(input.environmentId).pipe(Effect.option);
217 if (Option.isNone(resolved)) return unsupported("unreachable");
218 const peer = resolved.value;
219 const request = payload(yield* clientLabelOf(sessionId));
220 if (
221 peer.capabilities.linkClientPairing !== true ||
222 // One from before this would read the request as a client's and pair the client instead.
223 (request.link !== undefined && peer.capabilities.linkPairingForLink !== true)
224 ) {
225 return unsupported("version", peer.link.label);
226 }
227 const api = yield* HttpApiClient.make(ClientPairingApi, { baseUrl: peer.url }).pipe(
228 Effect.provideService(HttpClient.HttpClient, httpClient),
229 );
230 return yield* api.peerLink
231 .clientPairing({
232 headers: { authorization: `Bearer ${peer.token}` },
233 payload: request,
234 })
235 .pipe(
236 Effect.timeout(PeerLinks.probeTimeout(peer.url)),
237 Effect.map((issued): PeerLinkClientPairingResult => ({
238 type: "credential",
239 environmentId,
240 label: peer.link.label,
241 urls,
242 credential: issued.credential,
243 expiresAt: issued.expiresAt,
244 })),
245 // No cause is logged or returned: a response this version cannot read may hold the credential.
246 Effect.catchTags({
247 HttpClientError: () => Effect.succeed(unsupported("unreachable", peer.link.label)),
248 TimeoutError: () => Effect.succeed(unsupported("unreachable", peer.link.label)),
249 }),
250 Effect.orElseSucceed(() => unsupported("refused", peer.link.label)),
251 );
252 });
253
254 const request: PeerClientPairing["Service"]["request"] = (input, client) =>
255 ask(input, client.sessionId, (clientLabel) => ({ scopes: client.scopes, clientLabel }));
256
257 const requestForLink: PeerClientPairing["Service"]["requestForLink"] = (input, client) =>
258 ask(input, client.sessionId, (clientLabel) => ({
259 scopes: [],
260 clientLabel,
261 link: { access: input.access },
262 }));
263
264 return PeerClientPairing.of({ request, requestForLink });
265});
266
267export const layer = Layer.effect(PeerClientPairing, make);