@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 750 lines 28.1 KB
Raw
1 import {
2 AuthStandardClientScopes,
3 EnvironmentId,
4 type AuthEnvironmentScope,
5 ORCHESTRATION_PROTOCOL_VERSION,
6 } from "@t3tools/contracts";
7 import { assert, describe, expect, it } from "@effect/vitest";
8 import * as Effect from "effect/Effect";
9 import * as Fiber from "effect/Fiber";
10 import * as Layer from "effect/Layer";
11 import * as Option from "effect/Option";
12 import * as Stream from "effect/Stream";
13 import * as SubscriptionRef from "effect/SubscriptionRef";
14
15 import * as RpcHttp from "../rpc/http.ts";
16 import * as ClientCapabilities from "../platform/capabilities.ts";
17 import * as ManagedRelay from "../relay/managedRelay.ts";
18 import * as Persistence from "../platform/persistence.ts";
19 import { fetchRemoteSessionState } from "../authorization/remote.ts";
20 import {
21 BearerConnectionCredential,
22 BearerConnectionProfile,
23 BearerConnectionRegistration,
24 PrimaryConnectionRegistration,
25 } from "./catalog.ts";
26 import * as Connectivity from "./connectivity.ts";
27 import * as ConnectionCredentialStore from "./credentialStore.ts";
28 import * as ConnectionDriver from "./driver.ts";
29 import {
30 BearerConnectionTarget,
31 ConnectionBlockedError,
32 PrimaryConnectionTarget,
33 } from "./model.ts";
34 import * as Onboarding from "./onboarding.ts";
35 import {
36 prepareBearerConnectionUpdate,
37 preparePairingRegistration,
38 prepareSshRegistration,
39 } from "./onboarding.ts";
40 import * as EnvironmentRegistry from "./registry.ts";
41 import * as ConnectionProfileStore from "./profileStore.ts";
42 import { connectionRoutes, routeHttpBaseUrl } from "./routes.ts";
43 import * as ConnectionWakeups from "./wakeups.ts";
44
45 const layerClientPresentation = Layer.succeed(
46 ClientCapabilities.ClientPresentation,
47 ClientCapabilities.ClientPresentation.of({
48 metadata: {
49 label: "T3 Code Test",
50 deviceType: "desktop",
51 os: "Test OS",
52 },
53 }),
54 );
55
56 function layerPairingHttp(
57 calls: Array<{ readonly url: string; readonly init: RequestInit }>,
58 options?: {
59 readonly failDescriptor?: boolean;
60 readonly failExchange?: boolean;
61 readonly protocolVersion?: number;
62 readonly selfUpdate?: boolean;
63 readonly grantScopes?: ReadonlyArray<AuthEnvironmentScope>;
64 readonly exchangeGate?: { readonly reached: () => void; readonly release: Promise<void> };
65 readonly accessTokenRenewal?: boolean;
66 },
67 ) {
68 const grantScopes = options?.grantScopes ?? AuthStandardClientScopes;
69 let sessionScopes: ReadonlyArray<string> = [];
70 const fetchFn = ((input, init = {}) => {
71 const url = String(input);
72 calls.push({ url, init });
73
74 if (url.endsWith("/.well-known/t3/environment")) {
75 if (options?.failDescriptor === true) {
76 return Promise.resolve(
77 Response.json({ message: "descriptor unavailable" }, { status: 503 }),
78 );
79 }
80 return Promise.resolve(
81 Response.json({
82 environmentId: "environment-paired",
83 label: "Paired environment",
84 platform: {
85 os: "linux",
86 arch: "x64",
87 },
88 serverVersion: "0.0.0-test",
89 orchestrationProtocolVersion: options?.protocolVersion ?? ORCHESTRATION_PROTOCOL_VERSION,
90 capabilities: {
91 repositoryIdentity: true,
92 ...(options?.selfUpdate === true ? { serverSelfUpdate: "boot-service" } : {}),
93 ...(options?.accessTokenRenewal === true ? { accessTokenRenewal: true } : {}),
94 },
95 }),
96 );
97 }
98
99 if (url.endsWith("/oauth/token")) {
100 if (options?.failExchange === true) {
101 return Promise.resolve(
102 Response.json(
103 {
104 _tag: "EnvironmentAuthInvalidError",
105 code: "auth_invalid",
106 reason: "invalid_credential",
107 traceId: "trace-pairing-test",
108 },
109 { status: 401 },
110 ),
111 );
112 }
113 const body =
114 init.body instanceof Uint8Array ? new TextDecoder().decode(init.body) : String(init.body);
115 const requestedScope = new URLSearchParams(body).get("scope");
116 sessionScopes = requestedScope === null ? grantScopes : requestedScope.split(" ");
117 if (!sessionScopes.every((scope) => grantScopes.some((granted) => granted === scope))) {
118 return Promise.resolve(
119 Response.json(
120 {
121 _tag: "EnvironmentRequestInvalidError",
122 code: "invalid_request",
123 reason: "scope_not_granted",
124 traceId: "pairing-scope-test",
125 },
126 { status: 400 },
127 ),
128 );
129 }
130 const dpop = new Headers(init.headers).has("dpop");
131 const granted = Response.json({
132 access_token: dpop ? "dpop-token" : "bearer-token",
133 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
134 token_type: dpop ? "DPoP" : "Bearer",
135 expires_in: 3600,
136 scope: sessionScopes.join(" "),
137 });
138 const gate = options?.exchangeGate;
139 if (gate === undefined) return Promise.resolve(granted);
140 gate.reached();
141 return gate.release.then(() => granted);
142 }
143
144 if (url.endsWith("/api/auth/session")) {
145 return Promise.resolve(
146 Response.json({
147 authenticated: true,
148 auth: {
149 policy: "remote-reachable",
150 bootstrapMethods: ["one-time-token"],
151 sessionMethods: ["bearer-access-token"],
152 sessionCookieName: "t3_session",
153 },
154 scopes: sessionScopes,
155 sessionMethod: "bearer-access-token",
156 }),
157 );
158 }
159
160 return Promise.reject(new Error(`Unexpected request: ${url}`));
161 }) satisfies typeof fetch;
162
163 return RpcHttp.layerRemoteHttpClient(fetchFn);
164 }
165
166 function layerPairingOnboarding(
167 options?: Parameters<typeof layerPairingHttp>[1],
168 calls: Array<{ readonly url: string; readonly init: RequestInit }> = [],
169 provision?: ClientCapabilities.SshEnvironmentGateway["Service"]["provision"],
170 ) {
171 const dependencies = Layer.mergeAll(
172 layerClientPresentation,
173 layerPairingHttp(calls, options),
174 Layer.mock(Persistence.ConnectionTargetStore)({
175 list: Effect.succeed([]),
176 listDisabled: Effect.succeed([]),
177 }),
178 Layer.mock(Persistence.ConnectionRegistrationStore)({
179 register: () => Effect.void,
180 setEnabled: () => Effect.void,
181 }),
182 Layer.mock(Persistence.EnvironmentCacheStore)({}),
183 Layer.mock(ConnectionProfileStore.ConnectionProfileStore)({}),
184 Layer.mock(ConnectionCredentialStore.ConnectionCredentialStore)({
185 get: () => Effect.succeedNone,
186 put: () => Effect.void,
187 }),
188 Layer.mock(ClientCapabilities.SshEnvironmentGateway)(provision ? { provision } : {}),
189 Layer.succeed(
190 Connectivity.Connectivity,
191 Connectivity.Connectivity.of({ status: Effect.succeed("online"), changes: Stream.never }),
192 ),
193 Layer.mock(ConnectionDriver.ConnectionDriver)({ connect: () => Effect.never }),
194 Layer.succeed(
195 ConnectionWakeups.ConnectionWakeups,
196 ConnectionWakeups.ConnectionWakeups.of({ changes: Stream.never }),
197 ),
198 );
199 return Onboarding.layer.pipe(
200 Layer.provideMerge(EnvironmentRegistry.layer.pipe(Layer.provideMerge(dependencies))),
201 );
202 }
203
204 const PAIRED_ENVIRONMENT_ID = EnvironmentId.make("environment-paired");
205 const PAIRING_INPUT = { host: "remote.example.test", pairingCode: "pairing-token" };
206 const PAIRED_PROFILE = new BearerConnectionProfile({
207 connectionId: "bearer:environment-paired:https://remote.example.test",
208 environmentId: PAIRED_ENVIRONMENT_ID,
209 label: "Paired environment",
210 httpBaseUrl: "https://remote.example.test/",
211 wsBaseUrl: "wss://remote.example.test/",
212 });
213 const UNSUPPORTED_ERROR = new ConnectionBlockedError({
214 reason: "unsupported",
215 detail: "The saved server used an incompatible orchestration protocol.",
216 });
217
218 const registerSwitchedOffEnvironment = Effect.gen(function* () {
219 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
220 const registration = new BearerConnectionRegistration({
221 target: new BearerConnectionTarget({
222 environmentId: PAIRED_ENVIRONMENT_ID,
223 connectionId: PAIRED_PROFILE.connectionId,
224 label: "Old label",
225 }),
226 profile: new BearerConnectionProfile({ ...PAIRED_PROFILE, label: "Old label" }),
227 credential: new BearerConnectionCredential({ token: "old-token" }),
228 });
229 yield* registry.register(registration);
230 yield* registry.setEnabled(PAIRED_ENVIRONMENT_ID, false);
231 yield* registry.setCompatibility(PAIRED_ENVIRONMENT_ID, UNSUPPORTED_ERROR);
232 const entries = yield* SubscriptionRef.get(registry.entries);
233 expect(entries.get(PAIRED_ENVIRONMENT_ID)).toEqual({
234 target: registration.target,
235 profile: Option.some(registration.profile),
236 enabled: false,
237 unsupportedReason: UNSUPPORTED_ERROR.message,
238 });
239 return entries;
240 });
241
242 describe("connection onboarding", () => {
243 it.effect("prepares a persisted bearer registration from pairing details", () =>
244 Effect.gen(function* () {
245 const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
246 const registration = yield* preparePairingRegistration({
247 host: "remote.example.test",
248 pairingCode: "pairing-token",
249 }).pipe(Effect.provide(layerPairingOnboarding(undefined, calls)));
250
251 expect(registration).toMatchObject({
252 _tag: "BearerConnectionRegistration",
253 target: {
254 environmentId: "environment-paired",
255 label: "Paired environment",
256 connectionId: "bearer:environment-paired:https://remote.example.test",
257 },
258 profile: {
259 environmentId: "environment-paired",
260 label: "Paired environment",
261 connectionId: "bearer:environment-paired:https://remote.example.test",
262 httpBaseUrl: "https://remote.example.test/",
263 wsBaseUrl: "wss://remote.example.test/",
264 },
265 credential: {
266 token: "bearer-token",
267 },
268 });
269 expect(calls.map((call) => call.url)).toEqual([
270 "https://remote.example.test/.well-known/t3/environment",
271 "https://remote.example.test/oauth/token",
272 ]);
273
274 const tokenRequest = calls.find((call) => call.url.endsWith("/oauth/token"));
275 const tokenBody =
276 tokenRequest?.init.body instanceof Uint8Array
277 ? new TextDecoder().decode(tokenRequest.init.body)
278 : String(tokenRequest?.init.body);
279 const tokenParams = new URLSearchParams(tokenBody);
280 expect(tokenParams.get("subject_token")).toBe("pairing-token");
281 expect(tokenParams.has("scope")).toBe(false);
282 expect(tokenParams.get("client_label")).toBe("T3 Code Test");
283 expect(tokenParams.get("client_device_type")).toBe("desktop");
284 expect(tokenParams.get("client_os")).toBe("Test OS");
285 }),
286 );
287
288 it.effect("turns a switched-off environment back on when it is paired again", () =>
289 Effect.gen(function* () {
290 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
291 const onboarding = yield* Onboarding.ConnectionOnboarding;
292 yield* registerSwitchedOffEnvironment;
293
294 const environmentId = yield* onboarding.registerPairing(PAIRING_INPUT);
295
296 expect(environmentId).toBe(PAIRED_ENVIRONMENT_ID);
297 const entries = yield* SubscriptionRef.get(registry.entries);
298 const entry = entries.get(environmentId);
299 expect(entries.size).toBe(1);
300 expect(entry?.enabled).toBe(true);
301 expect(entry?.unsupportedReason).toBeUndefined();
302 expect(entry?.profile).toEqual(Option.some(PAIRED_PROFILE));
303 expect(entry?.target).toEqual(
304 new BearerConnectionTarget({
305 environmentId,
306 connectionId: PAIRED_PROFILE.connectionId,
307 label: PAIRED_PROFILE.label,
308 }),
309 );
310 }).pipe(Effect.provide(layerPairingOnboarding())),
311 );
312
313 it.effect("refuses a pairing link that claims a saved environment from a new address", () => {
314 const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
315 return Effect.gen(function* () {
316 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
317 const onboarding = yield* Onboarding.ConnectionOnboarding;
318 const before = yield* registerSwitchedOffEnvironment;
319
320 const error = yield* onboarding
321 .registerPairing({ host: "attacker.example.test", pairingCode: "pairing-token" })
322 .pipe(Effect.flip);
323
324 expect(error).toMatchObject({ _tag: "ConnectionBlockedError", reason: "configuration" });
325 expect(yield* SubscriptionRef.get(registry.entries)).toEqual(before);
326 expect(calls.map((call) => call.url)).toEqual([
327 "https://attacker.example.test/.well-known/t3/environment",
328 ]);
329 }).pipe(Effect.provide(layerPairingOnboarding(undefined, calls)));
330 });
331
332 it.effect(
333 "refuses to add an SSH route to a saved environment during untargeted onboarding",
334 () => {
335 const target = {
336 alias: "devbox",
337 hostname: "devbox.example.test",
338 username: "developer",
339 port: 22,
340 };
341 return Effect.gen(function* () {
342 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
343 const onboarding = yield* Onboarding.ConnectionOnboarding;
344 const before = yield* registerSwitchedOffEnvironment;
345
346 const result = yield* onboarding.registerSsh({ target }).pipe(Effect.result);
347
348 expect(result).toMatchObject({
349 _tag: "Failure",
350 failure: { _tag: "ConnectionBlockedError", reason: "configuration" },
351 });
352 expect(yield* SubscriptionRef.get(registry.entries)).toEqual(before);
353 }).pipe(
354 Effect.provide(
355 layerPairingOnboarding(undefined, [], () =>
356 Effect.succeed({
357 environmentId: PAIRED_ENVIRONMENT_ID,
358 label: "Remote development box",
359 bootstrap: {
360 target,
361 httpBaseUrl: "http://127.0.0.1:3201",
362 wsBaseUrl: "ws://127.0.0.1:3201",
363 pairingToken: "pairing-token",
364 },
365 bearerToken: "bearer-token",
366 }),
367 ),
368 ),
369 );
370 },
371 );
372
373 it.effect("refuses a new address when the environment is saved during the exchange", () => {
374 let reached!: () => void;
375 let release!: () => void;
376 const exchangeReached = new Promise<void>((resolve) => (reached = resolve));
377 const exchangeGate = {
378 reached: () => reached(),
379 release: new Promise<void>((resolve) => (release = resolve)),
380 };
381 return Effect.gen(function* () {
382 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
383 const onboarding = yield* Onboarding.ConnectionOnboarding;
384 const pairing = yield* onboarding
385 .registerPairing({ host: "attacker.example.test", pairingCode: "pairing-token" })
386 .pipe(Effect.result, Effect.forkChild);
387 yield* Effect.promise(() => exchangeReached);
388 const before = yield* registerSwitchedOffEnvironment;
389 release();
390
391 const outcome = yield* Fiber.join(pairing);
392
393 expect(outcome).toMatchObject({
394 _tag: "Failure",
395 failure: { _tag: "ConnectionBlockedError", reason: "configuration" },
396 });
397 expect(yield* SubscriptionRef.get(registry.entries)).toEqual(before);
398 }).pipe(Effect.provide(layerPairingOnboarding({ exchangeGate })));
399 });
400
401 it.effect("adds a new address as a route when pairing targets that environment", () =>
402 Effect.gen(function* () {
403 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
404 const onboarding = yield* Onboarding.ConnectionOnboarding;
405 yield* registerSwitchedOffEnvironment;
406
407 yield* onboarding.registerPairing({
408 host: "lan.example.test",
409 pairingCode: "pairing-token",
410 expectedEnvironmentId: PAIRED_ENVIRONMENT_ID,
411 });
412
413 const entry = (yield* SubscriptionRef.get(registry.entries)).get(PAIRED_ENVIRONMENT_ID);
414 expect(entry === undefined ? [] : connectionRoutes(entry).map(routeHttpBaseUrl)).toEqual(
415 expect.arrayContaining(["https://remote.example.test/", "https://lan.example.test/"]),
416 );
417 }).pipe(Effect.provide(layerPairingOnboarding())),
418 );
419
420 it.effect(
421 "re-pairs an outdated self-updatable environment so its connection can be rechecked",
422 () =>
423 Effect.gen(function* () {
424 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
425 const onboarding = yield* Onboarding.ConnectionOnboarding;
426 yield* registerSwitchedOffEnvironment;
427 yield* registry.setCompatibility(
428 PAIRED_ENVIRONMENT_ID,
429 new ConnectionBlockedError({
430 reason: "unsupported",
431 detail: "The saved server needs an update.",
432 serverUpdateRequired: true,
433 }),
434 );
435 expect(
436 (yield* SubscriptionRef.get(registry.entries)).get(PAIRED_ENVIRONMENT_ID),
437 ).toMatchObject({
438 enabled: false,
439 serverUpdateRequired: true,
440 });
441
442 const environmentId = yield* onboarding.registerPairing(PAIRING_INPUT);
443
444 expect(environmentId).toBe(PAIRED_ENVIRONMENT_ID);
445 const entry = (yield* SubscriptionRef.get(registry.entries)).get(environmentId);
446 expect(entry?.enabled).toBe(true);
447 expect(entry?.unsupportedReason).toBeUndefined();
448 expect(entry?.serverUpdateRequired).toBeUndefined();
449 expect(entry?.profile).toEqual(Option.some(PAIRED_PROFILE));
450 }).pipe(
451 Effect.provide(
452 layerPairingOnboarding({
453 protocolVersion: ORCHESTRATION_PROTOCOL_VERSION - 1,
454 selfUpdate: true,
455 }),
456 ),
457 ),
458 );
459
460 it.effect.each([
461 {
462 kind: "primary",
463 registration: new PrimaryConnectionRegistration({
464 target: new PrimaryConnectionTarget({
465 environmentId: PAIRED_ENVIRONMENT_ID,
466 label: "Host environment",
467 httpBaseUrl: "http://127.0.0.1:3773",
468 wsBaseUrl: "ws://127.0.0.1:3773",
469 }),
470 }),
471 },
472 {
473 kind: "bearer",
474 registration: new BearerConnectionRegistration({
475 target: new BearerConnectionTarget({
476 environmentId: PAIRED_ENVIRONMENT_ID,
477 connectionId: "platform:wsl",
478 label: "WSL",
479 }),
480 profile: new BearerConnectionProfile({
481 ...PAIRED_PROFILE,
482 connectionId: "platform:wsl",
483 label: "WSL",
484 httpBaseUrl: "http://127.0.0.1:4000",
485 wsBaseUrl: "ws://127.0.0.1:4000",
486 }),
487 credential: new BearerConnectionCredential({ token: "platform-token" }),
488 }),
489 },
490 ] as const)(
491 "leaves a platform-managed $kind environment untouched when its id is paired",
492 ({ registration }) =>
493 Effect.gen(function* () {
494 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
495 const onboarding = yield* Onboarding.ConnectionOnboarding;
496 yield* registry.reconcilePlatform([registration]);
497 yield* registry.setCompatibility(PAIRED_ENVIRONMENT_ID, UNSUPPORTED_ERROR);
498 const before = yield* SubscriptionRef.get(registry.entries);
499 expect(before.get(PAIRED_ENVIRONMENT_ID)).toMatchObject({
500 enabled: true,
501 unsupportedReason: UNSUPPORTED_ERROR.message,
502 });
503
504 const environmentId = yield* onboarding.registerPairing(PAIRING_INPUT);
505
506 expect(environmentId).toBe(PAIRED_ENVIRONMENT_ID);
507 expect(yield* SubscriptionRef.get(registry.entries)).toEqual(before);
508 }).pipe(Effect.provide(layerPairingOnboarding())),
509 );
510
511 it.effect("leaves a switched-off environment unchanged when the pairing exchange fails", () =>
512 Effect.gen(function* () {
513 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
514 const onboarding = yield* Onboarding.ConnectionOnboarding;
515 const before = yield* registerSwitchedOffEnvironment;
516
517 const error = yield* onboarding.registerPairing(PAIRING_INPUT).pipe(Effect.flip);
518
519 expect(error).toMatchObject({
520 _tag: "ConnectionBlockedError",
521 reason: "authentication",
522 traceId: "trace-pairing-test",
523 });
524 const after = yield* SubscriptionRef.get(registry.entries);
525 expect(after).toEqual(before);
526 expect(after.get(PAIRED_ENVIRONMENT_ID)?.enabled).toBe(false);
527 expect(after.get(PAIRED_ENVIRONMENT_ID)?.unsupportedReason).toBe(UNSUPPORTED_ERROR.message);
528 }).pipe(Effect.provide(layerPairingOnboarding({ failExchange: true }))),
529 );
530
531 it.effect("rejects an incompatible server without consuming the pairing credential", () =>
532 Effect.gen(function* () {
533 const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
534 const error = yield* preparePairingRegistration({
535 host: "remote.example.test",
536 pairingCode: "pairing-token",
537 }).pipe(
538 Effect.provide(
539 layerPairingOnboarding({ protocolVersion: ORCHESTRATION_PROTOCOL_VERSION + 1 }, calls),
540 ),
541 Effect.flip,
542 );
543 expect(error).toMatchObject({ reason: "unsupported" });
544 expect(calls.map((call) => call.url)).toEqual([
545 "https://remote.example.test/.well-known/t3/environment",
546 ]);
547 }),
548 );
549 it.effect.each([
550 { label: "read-only", scopes: ["orchestration:read"] },
551 { label: "default", scopes: AuthStandardClientScopes },
552 ] as const)("preserves the $label grant when pairing a remote environment", ({ scopes }) =>
553 Effect.gen(function* () {
554 const registration = yield* preparePairingRegistration({
555 host: "remote.example.test",
556 pairingCode: "pairing-token",
557 });
558
559 assert(registration.credential._tag === "BearerConnectionCredential");
560 const session = yield* fetchRemoteSessionState({
561 httpBaseUrl: registration.profile.httpBaseUrl,
562 bearerToken: registration.credential.token,
563 });
564
565 expect(session.authenticated).toBe(true);
566 expect(session.scopes).toEqual(scopes);
567 }).pipe(Effect.provide(layerPairingOnboarding({ grantScopes: scopes }))),
568 );
569
570 it.effect.each([
571 { name: "a host that renews, with a device key", renews: true, signer: true, dpop: true },
572 { name: "a host that renews, without a device key", renews: true, signer: false, dpop: false },
573 { name: "an older host, with a device key", renews: false, signer: true, dpop: false },
574 ])("pairs with $name as DPoP: $dpop", ({ renews, signer, dpop }) =>
575 Effect.gen(function* () {
576 const registration = yield* preparePairingRegistration({
577 host: "remote.example.test",
578 pairingCode: "pairing-token",
579 });
580 expect(registration.credential).toMatchObject(
581 dpop
582 ? { _tag: "DpopConnectionCredential", accessToken: "dpop-token" }
583 : { _tag: "BearerConnectionCredential", token: "bearer-token" },
584 );
585 }).pipe(
586 Effect.provide(
587 Layer.merge(
588 layerPairingOnboarding({ accessTokenRenewal: renews }),
589 signer
590 ? Layer.succeed(
591 ManagedRelay.ManagedRelayDpopSigner,
592 ManagedRelay.ManagedRelayDpopSigner.of({
593 thumbprint: Effect.succeed("device-key"),
594 createProof: (proof) => Effect.succeed(`proof:${proof.url}`),
595 }),
596 )
597 : Layer.empty,
598 ),
599 ),
600 ),
601 );
602
603 it.effect("refuses to add a route that reaches a different machine, keeping the code", () =>
604 Effect.gen(function* () {
605 const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
606 const error = yield* preparePairingRegistration({
607 host: "remote.example.test",
608 pairingCode: "pairing-token",
609 expectedEnvironmentId: EnvironmentId.make("some-other-machine"),
610 }).pipe(Effect.provide(layerPairingOnboarding(undefined, calls)), Effect.flip);
611 expect(error).toMatchObject({ reason: "configuration" });
612 expect(error.message).toContain("different machine");
613 expect(calls.map((call) => call.url)).toEqual([
614 "https://remote.example.test/.well-known/t3/environment",
615 ]);
616 }),
617 );
618
619 it.effect("refuses an outdated server that cannot update itself", () =>
620 Effect.gen(function* () {
621 const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
622 const error = yield* preparePairingRegistration({
623 host: "remote.example.test",
624 pairingCode: "pairing-token",
625 }).pipe(
626 Effect.provide(
627 layerPairingOnboarding({ protocolVersion: ORCHESTRATION_PROTOCOL_VERSION - 1 }, calls),
628 ),
629 Effect.flip,
630 );
631 expect(error).toMatchObject({ reason: "unsupported" });
632 expect(error).not.toHaveProperty("serverUpdateRequired");
633 expect(calls.map((call) => call.url)).toEqual([
634 "https://remote.example.test/.well-known/t3/environment",
635 ]);
636 }),
637 );
638
639 it.effect("does not consume a pairing credential when descriptor discovery fails", () =>
640 Effect.gen(function* () {
641 const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
642
643 yield* preparePairingRegistration({
644 host: "remote.example.test",
645 pairingCode: "pairing-token",
646 }).pipe(Effect.provide(layerPairingOnboarding({ failDescriptor: true }, calls)), Effect.flip);
647
648 expect(calls.map((call) => call.url)).toEqual([
649 "https://remote.example.test/.well-known/t3/environment",
650 ]);
651 }),
652 );
653
654 it.effect("updates bearer metadata while preserving the credential and identity", () =>
655 Effect.gen(function* () {
656 const environmentId = EnvironmentId.make("environment-paired");
657 const registration = yield* prepareBearerConnectionUpdate({
658 input: {
659 environmentId,
660 label: " Renamed environment ",
661 httpBaseUrl: "http://100.65.180.100:3773/path",
662 },
663 entry: Option.some({
664 target: new BearerConnectionTarget({
665 environmentId,
666 label: "Old label",
667 connectionId: "bearer:environment-paired",
668 }),
669 profile: Option.some(
670 new BearerConnectionProfile({
671 connectionId: "bearer:environment-paired",
672 environmentId,
673 label: "Old label",
674 httpBaseUrl: "http://old.example.test/",
675 wsBaseUrl: "ws://old.example.test/",
676 }),
677 ),
678 enabled: true,
679 }),
680 credential: Option.some(new BearerConnectionCredential({ token: "bearer-token" })),
681 });
682
683 expect(registration).toMatchObject({
684 target: {
685 environmentId,
686 label: "Renamed environment",
687 connectionId: "bearer:environment-paired",
688 },
689 profile: {
690 environmentId,
691 label: "Renamed environment",
692 httpBaseUrl: "http://100.65.180.100:3773/",
693 wsBaseUrl: "ws://100.65.180.100:3773/",
694 },
695 credential: { token: "bearer-token" },
696 });
697 }),
698 );
699
700 it.effect("prepares an SSH registration from the provisioned platform environment", () =>
701 Effect.gen(function* () {
702 const target = {
703 alias: "devbox",
704 hostname: "devbox.example.test",
705 username: "developer",
706 port: 22,
707 };
708 const registration = yield* prepareSshRegistration({
709 target,
710 }).pipe(
711 Effect.provideService(
712 ClientCapabilities.SshEnvironmentGateway,
713 ClientCapabilities.SshEnvironmentGateway.of({
714 provision: () =>
715 Effect.succeed({
716 environmentId: EnvironmentId.make("environment-ssh"),
717 label: "Remote development box",
718 bootstrap: {
719 target,
720 httpBaseUrl: "http://127.0.0.1:3201",
721 wsBaseUrl: "ws://127.0.0.1:3201",
722 pairingToken: "pairing-token",
723 },
724 bearerToken: "bearer-token",
725 }),
726 prepare: () => Effect.die("unused"),
727 disconnect: () => Effect.die("unused"),
728 }),
729 ),
730 );
731
732 expect(registration).toMatchObject({
733 _tag: "SshConnectionRegistration",
734 target: {
735 environmentId: "environment-ssh",
736 label: "Remote development box",
737 connectionId: 'ssh:environment-ssh:["devbox","devbox.example.test","developer",22]',
738 },
739 profile: {
740 environmentId: "environment-ssh",
741 label: "Remote development box",
742 connectionId: 'ssh:environment-ssh:["devbox","devbox.example.test","developer",22]',
743 target,
744 },
745 // Saved so the first connect reuses this pairing instead of adding another.
746 credential: { token: "bearer-token" },
747 });
748 }),
749 );
750 });