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

main
ts 275 lines 10.8 KB
Raw
1 import { NodeHttpServer } from "@effect/platform-node";
2 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3 import {
4 AuthAccessWriteScope,
5 type AuthEnvironmentScope,
6 type AuthMcpClientAccess,
7 AuthOrchestrationOperateScope,
8 AuthOrchestrationReadScope,
9 AuthRelayConfigureScope,
10 AuthStandardClientScopes,
11 AuthTerminalOperateScope,
12 type ExecutionEnvironmentDescriptor,
13 ProviderInstanceId,
14 ThreadId,
15 } from "@t3tools/contracts";
16 import { expect, it } from "@effect/vitest";
17 import * as Context from "effect/Context";
18 import * as Effect from "effect/Effect";
19 import * as Layer from "effect/Layer";
20 import * as Ref from "effect/Ref";
21 import * as FetchHttpClient from "effect/http/FetchHttpClient";
22 import * as HttpBody from "effect/http/HttpBody";
23 import * as HttpClient from "effect/http/HttpClient";
24 import * as HttpClientRequest from "effect/http/HttpClientRequest";
25 import * as TestClock from "effect/testing/TestClock";
26 import { Toolkit } from "effect/ai";
27
28 import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
29 import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
30 import * as McpHttpServer from "../mcp/McpHttpServer.ts";
31 import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
32 import * as McpToolAccess from "../mcp/McpToolAccess.ts";
33 import * as ServerSettings from "../serverSettings.ts";
34 import * as PeerClientPairing from "./PeerClientPairing.ts";
35 import * as PeerLinks from "./PeerLinks.ts";
36 import {
37 descriptorOf,
38 layerEnvironmentAuth,
39 layerLinkingEnvironment,
40 linkTo,
41 type ServedPeer,
42 servePeer,
43 } from "./PeerLinks.testkit.ts";
44
45 const laptop = descriptorOf("environment-laptop", "Laptop");
46 const box = descriptorOf("environment-box", "Box", { linkClientPairing: true });
47 const NoTools = Toolkit.make();
48
49 const serveBox = (descriptor: ExecutionEnvironmentDescriptor = box) =>
50 servePeer(
51 descriptor,
52 McpHttpServer.toolkitRegistration(NoTools, McpToolAccess.toLayer(NoTools, {})),
53 );
54
55 /** The laptop: its links, its own clients, and what answers a client asking to pair with a link. */
56 const makeLaptop = Effect.gen(function* () {
57 const linking = yield* Layer.build(layerLinkingEnvironment(laptop));
58 const authContext = yield* Layer.build(layerEnvironmentAuth("t3-peer-link-here-auth-"));
59 const auth = Context.get(authContext, EnvironmentAuth.EnvironmentAuth);
60 const pairing = yield* PeerClientPairing.layer.pipe(
61 Layer.provide(Layer.succeedContext(linking)),
62 Layer.provide(Layer.succeed(EnvironmentAuth.EnvironmentAuth, auth)),
63 Layer.provide(FetchHttpClient.layer),
64 Layer.build,
65 );
66 return {
67 links: Context.get(linking, PeerLinks.PeerLinks),
68 settings: Context.get(linking, ServerSettings.ServerSettingsService),
69 pairing: Context.get(pairing, PeerClientPairing.PeerClientPairing),
70 /** A client paired with the laptop, such as a phone. */
71 client: (scopes: ReadonlyArray<AuthEnvironmentScope>) =>
72 auth.issueSession({ scopes, label: "Phone" }),
73 };
74 });
75
76 const metadata = { deviceType: "mobile" as const };
77
78 /** Asks the box's route directly, as anything holding `bearer` could, and answers its status. */
79 const askBox = (b: ServedPeer, bearer: string | undefined, headers: Record<string, string> = {}) =>
80 HttpClient.execute(
81 HttpClientRequest.post(`${b.url}/api/peer-link/client-pairing`).pipe(
82 HttpClientRequest.setHeaders({
83 ...(bearer === undefined ? {} : { authorization: `Bearer ${bearer}` }),
84 ...headers,
85 }),
86 HttpClientRequest.setBody(
87 HttpBody.text(
88 JSON.stringify({ scopes: AuthStandardClientScopes, clientLabel: "Phone" }),
89 "application/json",
90 ),
91 ),
92 ),
93 ).pipe(
94 Effect.map((response) => response.status),
95 Effect.provide(FetchHttpClient.layer),
96 );
97
98 const linkTokenOf = (a: Effect.Success<typeof makeLaptop>) =>
99 a.links.resolve(box.environmentId).pipe(Effect.map((resolved) => resolved.token));
100
101 it.effect(
102 "a full-access link gets a client one pairing, with no more than the client holds here",
103 () =>
104 Effect.scoped(
105 Effect.gen(function* () {
106 const b = yield* serveBox();
107 const a = yield* makeLaptop;
108 yield* linkTo(a.links, b, "full-access");
109 // Holds less than a pairing code grants, and one scope no pairing code grants.
110 const held = [
111 AuthOrchestrationReadScope,
112 AuthOrchestrationOperateScope,
113 AuthAccessWriteScope,
114 AuthRelayConfigureScope,
115 ];
116 const phone = yield* a.client(held);
117
118 const result = yield* a.pairing.request({ environmentId: box.environmentId }, phone);
119 if (result.type !== "credential") return yield* Effect.die(result);
120 expect(result).toMatchObject({
121 environmentId: box.environmentId,
122 label: "Box",
123 urls: [b.url],
124 });
125 // The box's Connections says where the pairing came from, and can revoke it.
126 expect(yield* b.auth.listPairingLinks()).toMatchObject([{ label: "Phone · via Laptop" }]);
127
128 const session = yield* b.auth.exchangeBootstrapCredentialForAccessToken(
129 result.credential,
130 undefined,
131 metadata,
132 );
133 expect(new Set(session.scope.split(" "))).toEqual(
134 new Set([
135 AuthOrchestrationReadScope,
136 AuthOrchestrationOperateScope,
137 AuthAccessWriteScope,
138 ]),
139 );
140 expect(session.scope).not.toContain(AuthTerminalOperateScope);
141 const again = yield* b.auth
142 .exchangeBootstrapCredentialForAccessToken(result.credential, undefined, metadata)
143 .pipe(Effect.flip);
144 expect(again._tag).toBe("ServerAuthInvalidCredentialError");
145
146 // One the client never redeems is gone within minutes.
147 const unused = yield* a.pairing.request({ environmentId: box.environmentId }, phone);
148 if (unused.type !== "credential") return yield* Effect.die(unused);
149 yield* TestClock.adjust("3 minutes");
150 const late = yield* b.auth
151 .exchangeBootstrapCredentialForAccessToken(unused.credential, undefined, metadata)
152 .pipe(Effect.flip);
153 expect(late._tag).toBe("ServerAuthInvalidCredentialError");
154 }),
155 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
156 );
157
158 it.effect.each(["read-only", "approval-required", "auto"] as const)(
159 "a %s link cannot pair a client, even when the linking environment is bypassed",
160 (access: AuthMcpClientAccess) =>
161 Effect.scoped(
162 Effect.gen(function* () {
163 const b = yield* serveBox();
164 const a = yield* makeLaptop;
165 yield* linkTo(a.links, b, access);
166 const phone = yield* a.client(AuthStandardClientScopes);
167
168 expect(yield* a.pairing.request({ environmentId: box.environmentId }, phone)).toEqual({
169 type: "unsupported",
170 reason: "link_access",
171 environmentId: box.environmentId,
172 label: "Box",
173 urls: [b.url],
174 });
175 expect(yield* Ref.get(b.bearers)).toEqual([]);
176
177 expect(yield* askBox(b, yield* linkTokenOf(a))).toBe(403);
178 expect(yield* b.auth.listPairingLinks()).toEqual([]);
179 }),
180 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
181 );
182
183 it.effect("only a full-access link's own session reaches the box's pairing route", () =>
184 Effect.scoped(
185 Effect.gen(function* () {
186 const b = yield* serveBox();
187 const a = yield* makeLaptop;
188 yield* linkTo(a.links, b, "full-access");
189 const linkToken = yield* linkTokenOf(a);
190
191 // An outside agent approved at full access is not a link.
192 const agent = yield* b.auth.issueMcpClientSession({
193 label: "Outside agent",
194 access: "full-access",
195 peerLink: false,
196 client: { deviceType: "bot" },
197 });
198 expect(yield* askBox(b, agent.token)).toBe(403);
199
200 // An agent's thread credential, which a link-started agent holds too, is not a session.
201 const registry = yield* McpSessionRegistry.layer.pipe(
202 Layer.provide(
203 Layer.succeed(ServerEnvironment.ServerEnvironment, {
204 getEnvironmentId: Effect.succeed(box.environmentId),
205 getDescriptor: Effect.succeed(box),
206 }),
207 ),
208 Layer.provide(NodeCrypto.layer),
209 Layer.build,
210 );
211 const thread = yield* Context.get(registry, McpSessionRegistry.McpSessionRegistry).issue({
212 threadId: ThreadId.make("thread:box-link-started"),
213 providerInstanceId: ProviderInstanceId.make("codex"),
214 });
215 expect(yield* askBox(b, thread.config.authorizationHeader.slice("Bearer ".length))).toBe(401);
216
217 // The box's own administrator client pairs devices from Connections, not from here.
218 const owner = yield* b.auth.issueSession({ scopes: AuthStandardClientScopes });
219 expect(yield* askBox(b, owner.token)).toBe(401);
220 expect(yield* askBox(b, undefined)).toBe(401);
221 // A page in a browser never holds a link's token.
222 expect(yield* askBox(b, linkToken, { origin: "https://example.com" })).toBe(403);
223 expect(yield* b.auth.listPairingLinks()).toEqual([]);
224
225 expect(yield* askBox(b, linkToken)).toBe(200);
226 }),
227 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
228 );
229
230 it.effect("pairs no client while Linked environments is off on either side", () =>
231 Effect.scoped(
232 Effect.gen(function* () {
233 const b = yield* serveBox();
234 const a = yield* makeLaptop;
235 yield* linkTo(a.links, b, "full-access");
236 const phone = yield* a.client(AuthStandardClientScopes);
237 const linkToken = yield* linkTokenOf(a);
238
239 yield* b.settings.updateSettings({ linkedEnvironmentsEnabled: false });
240 expect(yield* askBox(b, linkToken)).toBe(403);
241 expect(yield* a.pairing.request({ environmentId: box.environmentId }, phone)).toMatchObject({
242 type: "unsupported",
243 reason: "refused",
244 });
245 yield* b.settings.updateSettings({ linkedEnvironmentsEnabled: true });
246
247 yield* a.settings.updateSettings({ linkedEnvironmentsEnabled: false });
248 const off = yield* a.pairing
249 .request({ environmentId: box.environmentId }, phone)
250 .pipe(Effect.flip);
251 expect(off.reason).toBe("disabled");
252 expect(yield* b.auth.listPairingLinks()).toEqual([]);
253 }),
254 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
255 );
256
257 it.effect("a linked environment from before client pairing is never asked", () =>
258 Effect.scoped(
259 Effect.gen(function* () {
260 const b = yield* serveBox(descriptorOf("environment-box", "Box"));
261 const a = yield* makeLaptop;
262 yield* linkTo(a.links, b, "full-access");
263 const phone = yield* a.client(AuthStandardClientScopes);
264
265 expect(yield* a.pairing.request({ environmentId: box.environmentId }, phone)).toEqual({
266 type: "unsupported",
267 reason: "version",
268 environmentId: box.environmentId,
269 label: "Box",
270 urls: [b.url],
271 });
272 expect(yield* Ref.get(b.bearers)).toEqual([]);
273 }),
274 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
275 );