Open History to see the last commit
1import { NodeHttpServer } from "@effect/platform-node";
2import { type ExecutionEnvironmentDescriptor, OrchestratorMcpFailure } from "@t3tools/contracts";
3import { expect, it } from "@effect/vitest";
4import * as Context from "effect/Context";
5import * as Deferred from "effect/Deferred";
6import * as Duration from "effect/Duration";
7import * as Effect from "effect/Effect";
8import * as Fiber from "effect/Fiber";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import * as Ref from "effect/Ref";
12import * as Schema from "effect/Schema";
13import * as HttpRouter from "effect/http/HttpRouter";
14import * as SqlClient from "effect/sql/SqlClient";
15import * as TestClock from "effect/testing/TestClock";
16import { Tool, Toolkit } from "effect/ai";
17import {
18 FetchHttpClient,
19 HttpClient,
20 HttpServer,
21 HttpServerRequest,
22 HttpServerResponse,
23} from "effect/http";
24
25import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
26import * as McpHttpServer from "../mcp/McpHttpServer.ts";
27import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
28import * as McpToolAccess from "../mcp/McpToolAccess.ts";
29import * as PeerLinks from "./PeerLinks.ts";
30import * as ServerSettings from "../serverSettings.ts";
31import {
32 descriptorOf,
33 layerLinkingEnvironment,
34 servePeer,
35 type ServedPeer,
36} from "./PeerLinks.testkit.ts";
37import * as PeerMcpClient from "./PeerMcpClient.ts";
38
39import { layerReaderDatabase, traceSqlRouting } from "../persistence/testkit/SqliteRouting.ts";
40
41/** What B's probe saw: the calling client and the modes it may start work with. */
42const Probe = Schema.Struct({ caller: Schema.String, modes: Schema.String });
43
44const ProbeToolkit = Toolkit.make(
45 Tool.make("probe", {
46 description: "Reports the calling client and the modes it may start work with.",
47 success: Probe,
48 failure: OrchestratorMcpFailure,
49 failureMode: "return",
50 dependencies: [McpInvocationContext.McpInvocationContext],
51 }),
52 Tool.make("refuse", {
53 description: "Always refuses.",
54 success: Probe,
55 failure: OrchestratorMcpFailure,
56 failureMode: "return",
57 }),
58);
59
60const probeHandlers = McpToolAccess.toLayer(ProbeToolkit, {
61 probe: McpToolAccess.reads(() =>
62 McpInvocationContext.McpInvocationContext.pipe(
63 Effect.map((scope) => {
64 const modes = McpInvocationContext.clientModeCeiling(scope.client);
65 return {
66 caller: scope.client?.label ?? "none",
67 modes: `${modes.runtimeMode}/${modes.interactionMode}`,
68 };
69 }),
70 ),
71 ),
72 refuse: McpToolAccess.reads(() =>
73 Effect.fail(
74 new OrchestratorMcpFailure({ code: "thread_not_found", message: "No such thread." }),
75 ),
76 ),
77});
78
79const serveB = (descriptor: ExecutionEnvironmentDescriptor) =>
80 servePeer(descriptor, McpHttpServer.toolkitRegistration(ProbeToolkit, probeHandlers));
81
82/** Environment A, which links to B. */
83const makeA = (
84 descriptor: ExecutionEnvironmentDescriptor,
85 secrets?: typeof ServerSecretStore.layer,
86) =>
87 layerLinkingEnvironment(descriptor, secrets).pipe(
88 Layer.build,
89 Effect.map((context) => ({
90 links: Context.get(context, PeerLinks.PeerLinks),
91 peer: Context.get(context, PeerMcpClient.PeerMcpClient),
92 sql: Context.get(context, SqlClient.SqlClient),
93 settings: Context.get(context, ServerSettings.ServerSettingsService),
94 })),
95 );
96
97const laptop = descriptorOf("environment-laptop", "Laptop");
98const box = descriptorOf("environment-box", "Box");
99const probe = (
100 a: Effect.Success<ReturnType<typeof makeA>>,
101 limits: PeerMcpClient.PeerCallLimits = { runtimeMode: "full-access", interactionMode: "default" },
102 tool = "probe",
103) =>
104 a.peer.call({
105 environmentId: box.environmentId,
106 tool,
107 arguments: {},
108 limits,
109 success: Probe,
110 });
111
112const linkedSessions = (b: ServedPeer) => b.linkedSessions;
113
114/** Another environment on a socket of its own, answering as `descriptor`. */
115const serveApart = (descriptor: ExecutionEnvironmentDescriptor) =>
116 Layer.build(Layer.fresh(NodeHttpServer.layerTest)).pipe(
117 Effect.flatMap((server) => serveB(descriptor).pipe(Effect.provideContext(server))),
118 );
119
120it.effect("routes peer reads to readers and sees uncommitted link updates", () =>
121 Effect.scoped(
122 Effect.gen(function* () {
123 const context = yield* layerLinkingEnvironment(
124 laptop,
125 ServerSecretStore.layer,
126 layerReaderDatabase,
127 ).pipe(Layer.build);
128 const links = Context.get(context, PeerLinks.PeerLinks);
129 const sql = Context.get(context, SqlClient.SqlClient);
130 yield* sql`
131 INSERT INTO peer_environment_links (
132 environment_id, secret_name, label, urls_json, access, linked_at, expires_at, fenced
133 ) VALUES (
134 ${box.environmentId}, 'test-secret', 'Box', '[]', 'auto',
135 '2026-01-01T00:00:00.000Z', '2026-01-02T00:00:00.000Z', 1
136 )
137 `;
138 const { queries, trace } = traceSqlRouting();
139 yield* links.list.pipe(trace);
140 expect(Option.getOrThrow(yield* links.get(box.environmentId).pipe(trace)).label).toBe("Box");
141 const reads = queries.filter(({ query }) =>
142 query.includes("SELECT * FROM peer_environment_links"),
143 );
144 expect(reads).toHaveLength(2);
145 expect(reads.map((row) => row.connection)).toEqual(["reader", "reader"]);
146 yield* sql.withTransaction(
147 Effect.gen(function* () {
148 yield* sql`UPDATE peer_environment_links SET label = 'Uncommitted box'`;
149 expect(Option.getOrThrow(yield* links.get(box.environmentId)).label).toBe(
150 "Uncommitted box",
151 );
152 expect((yield* links.list)[0]?.label).toBe("Uncommitted box");
153 }),
154 );
155 expect(yield* links.unlink(box.environmentId)).toBe(true);
156 expect(yield* links.list).toEqual([]);
157 }),
158 ),
159);
160
161it.effect("links with a pairing code, and the peer holds its agents to the limits they carry", () =>
162 Effect.scoped(
163 Effect.gen(function* () {
164 const b = yield* serveB(box);
165 const a = yield* makeA(laptop);
166
167 const refused = yield* a.links
168 .link({ url: b.url, pairingCode: "not-a-code", access: "auto" })
169 .pipe(Effect.flip);
170 expect(refused.reason).toBe("pairing_rejected");
171 expect(yield* linkedSessions(b)).toEqual([]);
172
173 const pairing = yield* b.auth.issuePairingCredential();
174 const linked = yield* a.links.link({
175 url: b.url,
176 pairingCode: pairing.credential,
177 access: "auto",
178 });
179 expect(linked).toMatchObject({
180 environmentId: box.environmentId,
181 label: "Box",
182 urls: [b.url],
183 access: "auto",
184 });
185 // B lists the link under A's name, where it can be revoked.
186 expect((yield* linkedSessions(b)).map((session) => session.client.label)).toEqual([
187 "T3 Code · Laptop",
188 ]);
189 expect(
190 (yield* a.links.list).map(({ environmentId, status }) => [environmentId, status]),
191 ).toEqual([[box.environmentId, "reachable"]]);
192
193 // The caller's limits narrow the link's access; they never widen it.
194 expect(
195 yield* probe(a, { runtimeMode: "approval-required", interactionMode: "plan" }),
196 ).toEqual({ caller: "T3 Code · Laptop", modes: "approval-required/plan" });
197 expect(yield* probe(a)).toEqual({ caller: "T3 Code · Laptop", modes: "auto/default" });
198
199 // A refusal keeps the peer's reason.
200 const notFound = yield* probe(a, undefined, "refuse").pipe(Effect.flip);
201 expect(notFound).toMatchObject({ code: "thread_not_found", message: "No such thread." });
202 }),
203 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
204);
205
206it.effect(
207 "each machine's Linked environments beta gates links, and a link waits while it is off",
208 () =>
209 Effect.scoped(
210 Effect.gen(function* () {
211 const b = yield* serveB(box);
212 const a = yield* makeA(laptop);
213 const pairing = yield* b.auth.issuePairingCredential();
214 const link = a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
215
216 yield* a.settings.updateSettings({ linkedEnvironmentsEnabled: false });
217 expect(yield* link.pipe(Effect.flip)).toMatchObject({
218 reason: "disabled",
219 message: PeerLinks.LINKED_ENVIRONMENTS_OFF,
220 });
221 expect(yield* Ref.get(b.bearers)).toEqual([]);
222
223 yield* a.settings.updateSettings({ linkedEnvironmentsEnabled: true });
224 yield* b.settings.updateSettings({ linkedEnvironmentsEnabled: false });
225 const refusedThere = yield* link.pipe(Effect.flip);
226 expect(refusedThere.reason).toBe("pairing_rejected");
227 expect(refusedThere.message).toContain("Linked environments is off on that machine");
228 expect(yield* linkedSessions(b)).toEqual([]);
229
230 yield* b.settings.updateSettings({ linkedEnvironmentsEnabled: true });
231 yield* link;
232 yield* b.settings.updateSettings({ linkedEnvironmentsEnabled: false });
233 // Not final, so a task already running there picks up again once it is back on.
234 const waiting = yield* probe(a).pipe(Effect.flip);
235 expect(waiting.code).toBe("orchestration_error");
236 expect(waiting.message).toContain("has Linked environments turned off");
237 yield* b.settings.updateSettings({ linkedEnvironmentsEnabled: true });
238 expect(yield* probe(a)).toEqual({ caller: "T3 Code · Laptop", modes: "auto/default" });
239 }),
240 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
241);
242
243it.effect("a link whose row cannot be stored keeps none of its token", () =>
244 Effect.scoped(
245 Effect.gen(function* () {
246 const b = yield* serveB(box);
247 const held = yield* Ref.make<ReadonlySet<string>>(new Set());
248 const noted = Layer.effect(
249 ServerSecretStore.ServerSecretStore,
250 Effect.map(ServerSecretStore.make, (store) =>
251 ServerSecretStore.ServerSecretStore.of({
252 ...store,
253 set: (name, value) =>
254 store
255 .set(name, value)
256 .pipe(Effect.andThen(Ref.update(held, (names) => new Set([...names, name])))),
257 remove: (name) =>
258 store
259 .remove(name)
260 .pipe(
261 Effect.andThen(
262 Ref.update(held, (names) => new Set([...names].filter((at) => at !== name))),
263 ),
264 ),
265 }),
266 ),
267 );
268 const a = yield* makeA(laptop, noted);
269 yield* a.sql`
270 CREATE TRIGGER refuse_link BEFORE INSERT ON peer_environment_links
271 BEGIN SELECT RAISE(ABORT, 'database or disk is full'); END
272 `;
273 const pairing = yield* b.auth.issuePairingCredential();
274 const failed = yield* a.links
275 .link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
276 .pipe(Effect.flip);
277 expect(failed.reason).toBe("storage");
278 expect(yield* Ref.get(held)).toEqual(new Set());
279 }),
280 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
281);
282
283it.effect("two links racing to one peer leave the stored access matching the token", () =>
284 Effect.scoped(
285 Effect.gen(function* () {
286 const b = yield* serveB(box);
287 const a = yield* makeA(laptop);
288 const [first, second] = yield* Effect.all(
289 [b.auth.issuePairingCredential(), b.auth.issuePairingCredential()],
290 { concurrency: 2 },
291 );
292 yield* Effect.all(
293 [
294 a.links.link({ url: b.url, pairingCode: first.credential, access: "read-only" }),
295 a.links.link({ url: b.url, pairingCode: second.credential, access: "full-access" }),
296 ],
297 { concurrency: 2 },
298 );
299 const [stored] = yield* a.links.list;
300 // The token sent is the one issued with the access the row records.
301 const { modes } = yield* probe(a);
302 expect(modes).toBe(
303 stored!.access === "read-only" ? "approval-required/default" : "full-access/default",
304 );
305 }),
306 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
307);
308
309/** A bare HTTP server on a socket of its own, answering with `handle`. */
310const serveRaw = <E, R>(
311 handle: (
312 request: HttpServerRequest.HttpServerRequest,
313 ) => Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>,
314) =>
315 Layer.build(Layer.fresh(NodeHttpServer.layerTest)).pipe(
316 Effect.flatMap((server) =>
317 Effect.gen(function* () {
318 yield* HttpServer.serve(Effect.flatMap(HttpServerRequest.HttpServerRequest, handle)).pipe(
319 Layer.build,
320 );
321 const address = (yield* HttpServer.HttpServer).address;
322 if (address._tag === "UnixPathAddress") return yield* Effect.die("expected a TCP address");
323 return `http://127.0.0.1:${address.port}`;
324 }).pipe(Effect.provideContext(server)),
325 ),
326 );
327
328it.effect("never follows a peer's redirect with the pairing code", () =>
329 Effect.scoped(
330 Effect.gen(function* () {
331 const b = yield* serveB(box);
332 const received = yield* Ref.make<ReadonlyArray<string>>([]);
333 const elsewhere = yield* serveRaw((request) =>
334 Ref.update(received, (seen) => [...seen, `${request.method} ${request.url}`]).pipe(
335 Effect.as(HttpServerResponse.empty({ status: 404 })),
336 ),
337 );
338 // Answers as B, then sends every linking request on to another address.
339 const front = yield* serveRaw((request) =>
340 request.url.startsWith("/.well-known/t3/environment")
341 ? HttpClient.get(`${b.url}${request.url}`).pipe(
342 Effect.flatMap((response) => response.text),
343 Effect.map((body) =>
344 HttpServerResponse.text(body, { contentType: "application/json" }),
345 ),
346 Effect.provide(FetchHttpClient.layer),
347 Effect.orDie,
348 )
349 : Effect.succeed(
350 HttpServerResponse.empty({
351 status: 307,
352 headers: { location: `${elsewhere}${request.url}` },
353 }),
354 ),
355 );
356 const a = yield* makeA(laptop);
357 const pairing = yield* b.auth.issuePairingCredential();
358 yield* a.links
359 .link({ url: front, pairingCode: pairing.credential, access: "auto" })
360 .pipe(Effect.flip);
361 expect(yield* Ref.get(received)).toEqual([]);
362 expect(yield* a.links.list).toEqual([]);
363 }),
364 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
365);
366
367it.effect("never sends a link's token to an address that stops answering as that peer", () =>
368 Effect.scoped(
369 Effect.gen(function* () {
370 const b = yield* serveB(box);
371 const a = yield* makeA(laptop);
372 const pairing = yield* b.auth.issuePairingCredential();
373 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
374 yield* probe(a);
375 expect((yield* Ref.get(b.bearers)).length).toBeGreaterThan(0);
376
377 // The address now answers as another environment, as a reused LAN address would.
378 yield* Ref.set(b.descriptor, descriptorOf("environment-impostor", "Impostor"));
379 yield* Ref.set(b.bearers, []);
380 const failed = yield* probe(a).pipe(Effect.flip);
381 expect(failed.message).toContain("Box did not answer");
382 expect(yield* Ref.get(b.bearers)).toEqual([]);
383 expect((yield* a.links.list).map((link) => link.status)).toEqual(["unreachable"]);
384 }),
385 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
386);
387
388it.effect("cancelling a descriptor probe aborts its request and leaves later resolves fresh", () =>
389 Effect.scoped(
390 Effect.gen(function* () {
391 const hold = yield* Ref.make(false);
392 const requests = yield* Ref.make(0);
393 const entered = yield* Deferred.make<void>();
394 const interrupted = yield* Deferred.make<void>();
395 const holdDescriptor = HttpRouter.middleware(
396 (httpEffect) =>
397 Effect.gen(function* () {
398 const request = yield* HttpServerRequest.HttpServerRequest;
399 if (request.url.startsWith("/.well-known/t3/environment")) {
400 yield* Ref.update(requests, (count) => count + 1);
401 if (yield* Ref.get(hold)) {
402 return yield* Deferred.succeed(entered, undefined).pipe(
403 Effect.andThen(Effect.never),
404 Effect.onInterrupt(() =>
405 Deferred.succeed(interrupted, undefined).pipe(Effect.asVoid),
406 ),
407 Effect.interruptible,
408 );
409 }
410 }
411 return yield* httpEffect;
412 }),
413 { global: true },
414 );
415 const b = yield* servePeer(
416 box,
417 Layer.merge(McpHttpServer.toolkitRegistration(ProbeToolkit, probeHandlers), holdDescriptor),
418 );
419 const a = yield* makeA(laptop);
420 const pairing = yield* b.auth.issuePairingCredential();
421 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
422 yield* Ref.set(b.bearers, []);
423 yield* Ref.set(requests, 0);
424 yield* Ref.set(hold, true);
425
426 const resolving = yield* a.links.resolve(box.environmentId).pipe(Effect.forkScoped);
427 yield* Deferred.await(entered);
428 yield* Fiber.interrupt(resolving);
429 yield* Deferred.await(interrupted);
430
431 yield* Ref.set(hold, false);
432 expect((yield* a.links.resolve(box.environmentId)).url).toBe(b.url);
433 expect(yield* Ref.get(requests)).toBe(2);
434 expect(yield* Ref.get(b.bearers)).toEqual([]);
435 }),
436 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
437);
438
439it.effect("reads one stored link without asking the peer", () =>
440 Effect.scoped(
441 Effect.gen(function* () {
442 const b = yield* serveB(box);
443 const a = yield* makeA(laptop);
444 const pairing = yield* b.auth.issuePairingCredential();
445 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
446 yield* Ref.set(b.probes, 0);
447
448 const stored = yield* a.links.get(box.environmentId);
449 expect(Option.map(stored, (link) => link.label)).toEqual(Option.some("Box"));
450 expect(Option.isNone(yield* a.links.get(laptop.environmentId))).toBe(true);
451 expect(yield* Ref.get(b.probes)).toBe(0);
452 }),
453 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
454);
455
456it.effect("a linked peer that is renamed shows its new name", () =>
457 Effect.scoped(
458 Effect.gen(function* () {
459 const b = yield* serveB(box);
460 const a = yield* makeA(laptop);
461 const pairing = yield* b.auth.issuePairingCredential();
462 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
463
464 yield* Ref.set(b.descriptor, descriptorOf(box.environmentId, "Box Mini"));
465 expect((yield* a.links.resolve(box.environmentId)).link.label).toBe("Box Mini");
466 const stored = yield* a.links.get(box.environmentId);
467 expect(Option.map(stored, (link) => link.label)).toEqual(Option.some("Box Mini"));
468
469 yield* Ref.set(b.descriptor, descriptorOf(box.environmentId, "Box Studio"));
470 expect((yield* a.links.list).map((link) => link.label)).toEqual(["Box Studio"]);
471 const storedAfterList = yield* a.links.get(box.environmentId);
472 expect(Option.map(storedAfterList, (link) => link.label)).toEqual(Option.some("Box Studio"));
473 }),
474 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
475);
476
477it.effect("tells the agent to link again once the peer revokes the link or it expires", () =>
478 Effect.scoped(
479 Effect.gen(function* () {
480 const b = yield* serveB(box);
481 const a = yield* makeA(laptop);
482 const pairing = yield* b.auth.issuePairingCredential();
483 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
484 yield* probe(a);
485
486 const [session] = yield* linkedSessions(b);
487 yield* b.auth.revokeSession(session!.sessionId);
488 const revoked = yield* probe(a).pipe(Effect.flip);
489 expect(revoked.code).toBe("capability_denied");
490 expect(revoked.message).toContain("revoked there");
491
492 yield* a.links.link({
493 url: b.url,
494 pairingCode: (yield* b.auth.issuePairingCredential()).credential,
495 access: "auto",
496 });
497 // A link made with a peer that later answers without the fence, as
498 // one made before the fence or a peer moved back to such a version.
499 yield* Ref.set(b.descriptor, descriptorOf("environment-box", "Box", { linkFence: false }));
500 yield* Ref.set(b.bearers, []);
501 const unfenced = yield* probe(a).pipe(Effect.flip);
502 expect(unfenced.code).toBe("capability_denied");
503 expect(unfenced.message).toContain("cannot keep a linked agent's limits");
504 expect(yield* Ref.get(b.bearers)).toEqual([]);
505 yield* Ref.set(b.descriptor, box);
506
507 // A link stored before links were marked: its session there is not a
508 // link's, so the peer would not fence its work even though it can.
509 yield* a.sql`UPDATE peer_environment_links SET fenced = 0`;
510 // Linking again is its only way back, as for an expired link.
511 expect((yield* a.links.list).map((link) => link.status)).toEqual(["expired"]);
512 const legacy = yield* probe(a).pipe(Effect.flip);
513 expect(legacy.code).toBe("capability_denied");
514 expect(legacy.message).toContain("Link it again");
515 expect(yield* Ref.get(b.bearers)).toEqual([]);
516 yield* a.links.link({
517 url: b.url,
518 pairingCode: (yield* b.auth.issuePairingCredential()).credential,
519 access: "auto",
520 });
521 yield* probe(a);
522
523 yield* TestClock.adjust(Duration.days(31));
524 expect((yield* a.links.list).map((link) => link.status)).toEqual(["expired"]);
525 yield* Ref.set(b.bearers, []);
526 const expired = yield* probe(a).pipe(Effect.flip);
527 expect(expired.code).toBe("capability_denied");
528 expect(expired.message).toContain("expired");
529 expect(yield* Ref.get(b.bearers)).toEqual([]);
530 }),
531 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
532);
533
534it.effect(
535 "refuses to link itself, plain http off this machine and the tailnet, or a peer that cannot hold a linked agent to its limits",
536 () =>
537 Effect.scoped(
538 Effect.gen(function* () {
539 const b = yield* serveB(
540 descriptorOf("environment-box", "Box", { mcpModeLimitHeader: false }),
541 );
542 const a = yield* makeA(laptop);
543 const pairing = yield* b.auth.issuePairingCredential();
544 const older = yield* a.links
545 .link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
546 .pipe(Effect.flip);
547 expect(older.reason).toBe("incompatible");
548 // Nor one whose link's work could reach the user's own threads there.
549 yield* Ref.set(b.descriptor, descriptorOf("environment-box", "Box", { linkFence: false }));
550 const unfenced = yield* a.links
551 .link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
552 .pipe(Effect.flip);
553 expect(unfenced.reason).toBe("incompatible");
554
555 // Plain http to a LAN address would carry the code and token in clear.
556 const lan = yield* a.links
557 .link({
558 url: "http://192.168.1.20:3773",
559 pairingCode: pairing.credential,
560 access: "auto",
561 })
562 .pipe(Effect.flip);
563 expect(lan.message).toContain("plain http");
564 const lanAlternate = yield* a.links
565 .link({
566 url: b.url,
567 alternateUrls: ["http://192.168.1.20:3773"],
568 pairingCode: pairing.credential,
569 access: "auto",
570 })
571 .pipe(Effect.flip);
572 expect(lanAlternate.message).toContain("plain http");
573
574 yield* Ref.set(b.descriptor, laptop);
575 const self = yield* a.links
576 .link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
577 .pipe(Effect.flip);
578 expect(self.reason).toBe("self");
579 // Neither attempt spent the pairing code on a session.
580 expect(yield* linkedSessions(b)).toEqual([]);
581 }),
582 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
583);
584
585it.effect(
586 "linking a picked machine skips an address that answers as another, and never signs in there",
587 () =>
588 Effect.scoped(
589 Effect.gen(function* () {
590 const impostor = yield* serveApart(descriptorOf("environment-impostor", "Impostor"));
591 const b = yield* serveB(box);
592 const a = yield* makeA(laptop);
593 const pairing = yield* b.auth.issuePairingCredential();
594 const linked = yield* a.links.link({
595 url: impostor.url,
596 alternateUrls: [b.url],
597 pairingCode: pairing.credential,
598 access: "auto",
599 expectedEnvironmentId: box.environmentId,
600 });
601 expect(linked).toMatchObject({ environmentId: box.environmentId, urls: [b.url] });
602 yield* probe(a);
603 expect(yield* linkedSessions(impostor)).toEqual([]);
604 expect(yield* Ref.get(impostor.bearers)).toEqual([]);
605 expect((yield* linkedSessions(b)).length).toBe(1);
606 }),
607 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
608);
609
610it.effect("linking a picked machine that answers nowhere names it and links nothing", () =>
611 Effect.scoped(
612 Effect.gen(function* () {
613 const impostor = yield* serveApart(descriptorOf("environment-impostor", "Impostor"));
614 const a = yield* makeA(laptop);
615 const failed = yield* a.links
616 .link({
617 url: impostor.url,
618 alternateUrls: ["http://192.168.1.20:3773"],
619 pairingCode: "unused",
620 access: "auto",
621 expectedEnvironmentId: box.environmentId,
622 expectedLabel: "Box",
623 })
624 .pipe(Effect.flip);
625 expect(failed.reason).toBe("unreachable");
626 expect(failed.message).toBe(
627 `This environment could not reach Box at ${impostor.url}, http://192.168.1.20:3773.`,
628 );
629 expect(yield* a.links.list).toEqual([]);
630 expect(yield* linkedSessions(impostor)).toEqual([]);
631
632 // Every address refused: the message says why.
633 const refused = yield* a.links
634 .link({
635 url: "http://192.168.1.20:3773",
636 pairingCode: "unused",
637 access: "auto",
638 expectedEnvironmentId: box.environmentId,
639 expectedLabel: "Box",
640 })
641 .pipe(Effect.flip);
642 expect(refused.message).toContain("could not reach Box");
643 expect(refused.message).toContain("plain http");
644 }),
645 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
646);