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

PeerClientPairing.ts

264 lines10.4 KB

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 EnvironmentAuth.clientSessionLabel(
169 sessions.find((session) => session.sessionId === sessionId)?.client,
170 ),
171 ),
172 Effect.orElseSucceed(() => "T3 Code client"),
173 );
174​
175 /** Asks the linked environment for a pairing; `payload` says for whom. */
176 const ask = Effect.fn("PeerClientPairing.ask")(function* (
177 input: { readonly environmentId: PeerLinkClientPairingInput["environmentId"] },
178 sessionId: AuthSessionId,
179 payload: (clientLabel: string) => PeerLinkClientPairingRequest,
180 ) {
181 if (!(yield* links.enabled)) {
182 return yield* new PeerLinkError({
183 reason: "disabled",
184 message: PeerLinks.LINKED_ENVIRONMENTS_OFF,
185 });
186 }
187 const stored = yield* links.get(input.environmentId);
188 if (Option.isNone(stored)) {
189 return yield* new PeerLinkError({
190 reason: "unknown_link",
191 message: "This environment is no longer linked to that one.",
192 });
193 }
194 const { environmentId, label, urls, access, expiresAt } = stored.value;
195 if (DateTime.isLessThanOrEqualTo(expiresAt, yield* DateTime.now)) {
196 return yield* new PeerLinkError({
197 reason: "expired",
198 message: `The link to ${label} expired. Link it again with a new pairing code from ${label}.`,
199 });
200 }
201 const unsupported = (
202 reason: Extract<PeerLinkClientPairingResult, { type: "unsupported" }>["reason"],
203 name = label,
204 ): PeerLinkClientPairingResult => ({
205 type: "unsupported",
206 environmentId,
207 label: name,
208 urls,
209 reason,
210 });
211 // The linked environment refuses this too; asking would only spend a round trip.
212 if (access !== "full-access") return unsupported("link_access");
213 const resolved = yield* links.resolve(input.environmentId).pipe(Effect.option);
214 if (Option.isNone(resolved)) return unsupported("unreachable");
215 const peer = resolved.value;
216 const request = payload(yield* clientLabelOf(sessionId));
217 if (
218 peer.capabilities.linkClientPairing !== true ||
219 // One from before this would read the request as a client's and pair the client instead.
220 (request.link !== undefined && peer.capabilities.linkPairingForLink !== true)
221 ) {
222 return unsupported("version", peer.link.label);
223 }
224 const api = yield* HttpApiClient.make(ClientPairingApi, { baseUrl: peer.url }).pipe(
225 Effect.provideService(HttpClient.HttpClient, httpClient),
226 );
227 return yield* api.peerLink
228 .clientPairing({
229 headers: { authorization: `Bearer ${peer.token}` },
230 payload: request,
231 })
232 .pipe(
233 Effect.timeout(PeerLinks.probeTimeout(peer.url)),
234 Effect.map((issued): PeerLinkClientPairingResult => ({
235 type: "credential",
236 environmentId,
237 label: peer.link.label,
238 urls,
239 credential: issued.credential,
240 expiresAt: issued.expiresAt,
241 })),
242 // No cause is logged or returned: a response this version cannot read may hold the credential.
243 Effect.catchTags({
244 HttpClientError: () => Effect.succeed(unsupported("unreachable", peer.link.label)),
245 TimeoutError: () => Effect.succeed(unsupported("unreachable", peer.link.label)),
246 }),
247 Effect.orElseSucceed(() => unsupported("refused", peer.link.label)),
248 );
249 });
250​
251 const request: PeerClientPairing["Service"]["request"] = (input, client) =>
252 ask(input, client.sessionId, (clientLabel) => ({ scopes: client.scopes, clientLabel }));
253​
254 const requestForLink: PeerClientPairing["Service"]["requestForLink"] = (input, client) =>
255 ask(input, client.sessionId, (clientLabel) => ({
256 scopes: [],
257 clientLabel,
258 link: { access: input.access },
259 }));
260​
261 return PeerClientPairing.of({ request, requestForLink });
262});
263​
264export const layer = Layer.effect(PeerClientPairing, make);