@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 361 lines 14 KB
Raw
1 import {
2 EnvironmentId,
3 ORCHESTRATION_PROTOCOL_VERSION,
4 type DesktopSshEnvironmentTarget,
5 } from "@t3tools/contracts";
6 import { describe, expect, it } from "@effect/vitest";
7 import * as Effect from "effect/Effect";
8 import * as Layer from "effect/Layer";
9 import * as Option from "effect/Option";
10 import * as Ref from "effect/Ref";
11
12 import * as ConnectionResolver from "./resolver.ts";
13 import * as ClientCapabilities from "../platform/capabilities.ts";
14 import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
15 import {
16 BearerConnectionCredential,
17 type ConnectionCatalogEntry,
18 SshConnectionProfile,
19 type ConnectionCredential,
20 type ConnectionProfile,
21 } from "./catalog.ts";
22 import * as ConnectionCredentialStore from "./credentialStore.ts";
23 import {
24 ConnectionTransientError,
25 PrimaryConnectionTarget,
26 SshConnectionTarget,
27 type ConnectionTarget,
28 } from "./model.ts";
29 import * as ConnectionProfileStore from "./profileStore.ts";
30 import * as RpcHttp from "../rpc/http.ts";
31 import {
32 PullRequestRoutingPermissions,
33 pullRequestRoutingConnectionKey,
34 makePullRequestRoutingPermissions,
35 } from "./pullRequestRoutingPermissions.ts";
36
37 const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
38 const ENDPOINT = {
39 httpBaseUrl: "https://environment.example.test",
40 wsBaseUrl: "wss://environment.example.test",
41 };
42 const SSH_TARGET: DesktopSshEnvironmentTarget = {
43 alias: "development",
44 hostname: "development.example.test",
45 username: "developer",
46 port: 22,
47 };
48
49 function catalogEntry(
50 target: ConnectionTarget,
51 profile: Option.Option<ConnectionProfile> = Option.none(),
52 ): ConnectionCatalogEntry {
53 return { target, profile, enabled: true };
54 }
55
56 const makeDependencies = Effect.fn("TestConnectionResolver.makeDependencies")((options?: {
57 readonly profiles?: ReadonlyArray<ConnectionProfile>;
58 readonly profileStore?: ConnectionProfileStore.ConnectionProfileStore["Service"];
59 readonly credentials?: ReadonlyArray<readonly [string, ConnectionCredential]>;
60 readonly authorizeBearer?: RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]["authorizeBearer"];
61 readonly authorizeDpop?: RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]["authorizeDpop"];
62 readonly primaryBearerToken?: string;
63 readonly prepareSsh?: ClientCapabilities.SshEnvironmentGateway["Service"]["prepare"];
64 readonly descriptorProtocolVersion?: number | null | undefined;
65 }) => {
66 const profiles = new Map(
67 (options?.profiles ?? []).map((profile) => [profile.connectionId, profile]),
68 );
69 const credentials = new Map(options?.credentials ?? []);
70
71 const profileStore = ConnectionProfileStore.ConnectionProfileStore.of({
72 get: (connectionId) => Effect.succeed(Option.fromNullishOr(profiles.get(connectionId))),
73 put: (profile) => Effect.sync(() => void profiles.set(profile.connectionId, profile)),
74 remove: (connectionId) => Effect.sync(() => void profiles.delete(connectionId)),
75 });
76 const credentialStore = ConnectionCredentialStore.ConnectionCredentialStore.of({
77 get: (connectionId) => Effect.succeed(Option.fromNullishOr(credentials.get(connectionId))),
78 put: (connectionId, credential) =>
79 Effect.sync(() => void credentials.set(connectionId, credential)),
80 remove: (connectionId) => Effect.sync(() => void credentials.delete(connectionId)),
81 });
82 const remote = RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization.of({
83 authorizeBearer:
84 options?.authorizeBearer ??
85 ((input) =>
86 Effect.succeed({
87 environmentId: input.expectedEnvironmentId,
88 label: "Authorized bearer environment",
89 httpBaseUrl: input.httpBaseUrl,
90 socketUrl: "wss://authorized.example.test/ws?wsTicket=bearer",
91 httpAuthorization: {
92 _tag: "Bearer" as const,
93 token: input.bearerToken,
94 },
95 })),
96 authorizeDpop:
97 options?.authorizeDpop ??
98 ((input) =>
99 Effect.succeed({
100 environmentId: input.expectedEnvironmentId,
101 label: "Authorized relay environment",
102 httpBaseUrl: ENDPOINT.httpBaseUrl,
103 socketUrl: "wss://authorized.example.test/ws?wsTicket=dpop",
104 httpAuthorization: {
105 _tag: "Dpop" as const,
106 accessToken: "dpop-access-token",
107 expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
108 },
109 })),
110 authorizeDpopHttp: () => Effect.die("unused"),
111 authorizeDirectDpop: () => Effect.die("unused"),
112 authorizeDirectDpopHttp: () => Effect.die("unused"),
113 rememberCheckedDescriptor: () => Effect.void,
114 renewDpopBeforeExpiry: () => Effect.die("unused"),
115 });
116 const ssh = ClientCapabilities.SshEnvironmentGateway.of({
117 provision: () => Effect.die("unused"),
118 prepare:
119 options?.prepareSsh ??
120 (() =>
121 Effect.succeed({
122 bootstrap: {
123 target: SSH_TARGET,
124 httpBaseUrl: "http://127.0.0.1:4010",
125 wsBaseUrl: "ws://127.0.0.1:4010",
126 pairingToken: null,
127 },
128 bearerToken: "ssh-bearer",
129 })),
130 disconnect: () => Effect.void,
131 });
132
133 const layerDependencies = Layer.mergeAll(
134 RpcHttp.layerRemoteHttpClient((() =>
135 Promise.resolve(
136 Response.json({
137 environmentId: ENVIRONMENT_ID,
138 label: "Compatible environment",
139 platform: { os: "linux", arch: "x64" },
140 serverVersion: "0.0.0-test",
141 ...(options?.descriptorProtocolVersion === undefined
142 ? { orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION }
143 : options.descriptorProtocolVersion === null
144 ? {}
145 : { orchestrationProtocolVersion: options.descriptorProtocolVersion }),
146 capabilities: { repositoryIdentity: true },
147 }),
148 )) satisfies typeof fetch),
149 Layer.succeed(
150 ConnectionProfileStore.ConnectionProfileStore,
151 options?.profileStore ?? profileStore,
152 ),
153 Layer.succeed(ConnectionCredentialStore.ConnectionCredentialStore, credentialStore),
154 Layer.succeed(
155 ClientCapabilities.PrimaryEnvironmentAuth,
156 ClientCapabilities.PrimaryEnvironmentAuth.of({
157 bearerToken: Effect.succeed(Option.fromNullishOr(options?.primaryBearerToken)),
158 }),
159 ),
160 Layer.succeed(
161 ClientCapabilities.ClientPresentation,
162 ClientCapabilities.ClientPresentation.of({
163 metadata: { label: "Test Client", deviceType: "desktop", surface: "web" },
164 }),
165 ),
166 Layer.succeed(RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization, remote),
167 Layer.succeed(ClientCapabilities.SshEnvironmentGateway, ssh),
168 );
169
170 return Effect.succeed(ConnectionResolver.layer.pipe(Layer.provide(layerDependencies)));
171 });
172
173 describe("ConnectionResolver", () => {
174 it.effect("blocks an old host during discovery before opening orchestration RPC", () =>
175 Effect.gen(function* () {
176 const layerBroker = yield* makeDependencies({ descriptorProtocolVersion: null });
177 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(layerBroker));
178 const target = new PrimaryConnectionTarget({
179 environmentId: ENVIRONMENT_ID,
180 label: "Primary",
181 httpBaseUrl: "http://127.0.0.1:3777",
182 wsBaseUrl: "ws://127.0.0.1:3777",
183 });
184
185 const error = yield* Effect.flip(broker.prepare(catalogEntry(target)));
186
187 expect(error).toMatchObject({ reason: "unsupported" });
188 expect(error.message).toContain("Update T3 Code on Compatible environment");
189 }),
190 );
191
192 it.effect("prepares a primary environment without remote capabilities", () =>
193 Effect.gen(function* () {
194 const layerBroker = yield* makeDependencies();
195 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(layerBroker));
196 const target = new PrimaryConnectionTarget({
197 environmentId: ENVIRONMENT_ID,
198 label: "Primary",
199 httpBaseUrl: "http://127.0.0.1:3777",
200 wsBaseUrl: "ws://127.0.0.1:3777",
201 });
202
203 expect(yield* broker.prepare(catalogEntry(target))).toEqual({
204 environmentId: ENVIRONMENT_ID,
205 label: "Primary",
206 httpBaseUrl: "http://127.0.0.1:3777",
207 socketUrl:
208 "ws://127.0.0.1:3777/ws?clientSurface=web&clientDeviceType=desktop&connectionMethod=direct&orchestrationProtocol=2&clientCapabilities=settingsSecretReferences",
209 httpAuthorization: null,
210 target,
211 // The shell reads the server's build and shell flags here before the socket opens.
212 descriptor: {
213 environmentId: ENVIRONMENT_ID,
214 label: "Compatible environment",
215 platform: { os: "linux", arch: "x64" },
216 serverVersion: "0.0.0-test",
217 orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION,
218 capabilities: { repositoryIdentity: true },
219 },
220 });
221 }),
222 );
223
224 it.effect("offers the saved SSH token on each connect and saves the one it gets back", () =>
225 Effect.gen(function* () {
226 const offeredTokens = yield* Ref.make<ReadonlyArray<string | undefined>>([]);
227 const target = new SshConnectionTarget({
228 environmentId: ENVIRONMENT_ID,
229 label: "SSH",
230 connectionId: "ssh-1",
231 });
232 const profile = new SshConnectionProfile({
233 connectionId: "ssh-1",
234 environmentId: ENVIRONMENT_ID,
235 label: "SSH",
236 target: SSH_TARGET,
237 });
238 const layerBroker = yield* makeDependencies({
239 credentials: [["ssh-1", new BearerConnectionCredential({ token: "revoked-token" })]],
240 // The host accepts only the token it paired last; anything else pairs again.
241 prepareSsh: (input) =>
242 Ref.update(offeredTokens, (tokens) => [...tokens, input.bearerToken]).pipe(
243 Effect.as({
244 bootstrap: {
245 target: input.target,
246 httpBaseUrl: "http://127.0.0.1:4010",
247 wsBaseUrl: "ws://127.0.0.1:4010",
248 pairingToken: null,
249 },
250 bearerToken: "paired-token",
251 }),
252 ),
253 });
254 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(layerBroker));
255 const entry = catalogEntry(target, Option.some(profile));
256
257 const first = yield* broker.prepare(entry);
258 const second = yield* broker.prepare(entry);
259
260 expect(yield* Ref.get(offeredTokens)).toEqual(["revoked-token", "paired-token"]);
261 expect(first.httpAuthorization).toMatchObject({ token: "paired-token" });
262 expect(second.httpAuthorization).toMatchObject({ token: "paired-token" });
263 }),
264 );
265
266 it.effect.each(["unchanged", "changed", "revocation-failed"] as const)(
267 "handles %s SSH routing consent before saving or authorizing",
268 (scenario) =>
269 Effect.gen(function* () {
270 const calls: string[] = [];
271 const target = new SshConnectionTarget({
272 environmentId: ENVIRONMENT_ID,
273 label: "SSH",
274 connectionId: "ssh-1",
275 });
276 const profile = new SshConnectionProfile({
277 connectionId: target.connectionId,
278 environmentId: ENVIRONMENT_ID,
279 label: "SSH",
280 target: SSH_TARGET,
281 });
282 const entry = catalogEntry(target, Option.some(profile));
283 const preparedTarget =
284 scenario === "unchanged"
285 ? SSH_TARGET
286 : { ...SSH_TARGET, hostname: "replacement.example.test" };
287 const failure = new ConnectionTransientError({
288 reason: "remote-unavailable",
289 detail: "Could not persist routing consent.",
290 });
291 const permissions = yield* makePullRequestRoutingPermissions({
292 read: Effect.succeed([
293 {
294 environmentId: ENVIRONMENT_ID,
295 connectionKey: pullRequestRoutingConnectionKey(entry)!,
296 permission: "read-write",
297 },
298 ]),
299 write: () =>
300 Effect.sync(() => {
301 calls.push("revoke");
302 }).pipe(
303 Effect.andThen(scenario === "revocation-failed" ? Effect.fail(failure) : Effect.void),
304 ),
305 });
306 let savedProfile: ConnectionProfile = profile;
307 const layerBroker = yield* makeDependencies({
308 profileStore: {
309 get: () => Effect.sync(() => Option.some(savedProfile)),
310 put: (value) =>
311 Effect.sync(() => {
312 calls.push("profile");
313 savedProfile = value;
314 }),
315 remove: () => Effect.die("unused"),
316 },
317 prepareSsh: () =>
318 Effect.succeed({
319 bootstrap: {
320 target: preparedTarget,
321 httpBaseUrl: "http://127.0.0.1:4010",
322 wsBaseUrl: "ws://127.0.0.1:4010",
323 pairingToken: null,
324 },
325 bearerToken: "ssh-bearer",
326 }),
327 authorizeBearer: (input) =>
328 Effect.sync(() => {
329 calls.push("authorize");
330 return {
331 environmentId: input.expectedEnvironmentId,
332 label: "SSH",
333 httpBaseUrl: input.httpBaseUrl,
334 socketUrl: "ws://127.0.0.1:4010/ws?wsTicket=ssh",
335 httpAuthorization: { _tag: "Bearer" as const, token: input.bearerToken },
336 };
337 }),
338 });
339 const broker = yield* ConnectionResolver.ConnectionResolver.pipe(
340 Effect.provide(layerBroker),
341 );
342 const prepare = broker
343 .prepare(entry)
344 .pipe(Effect.provideService(PullRequestRoutingPermissions, permissions));
345 if (scenario === "revocation-failed") {
346 expect(yield* Effect.flip(prepare)).toBe(failure);
347 expect(savedProfile).toBe(profile);
348 expect(calls).toEqual(["revoke"]);
349 } else {
350 expect((yield* prepare).socketUrl).toContain("wsTicket=ssh");
351 expect(savedProfile).toMatchObject({ target: preparedTarget });
352 expect(calls).toEqual(
353 scenario === "unchanged"
354 ? ["profile", "authorize"]
355 : ["revoke", "profile", "authorize"],
356 );
357 }
358 expect(yield* permissions.get(entry)).toBe(scenario === "changed" ? "off" : "read-write");
359 }),
360 );
361 });