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

onboarding.test.ts

885 lines32.6 KB

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