@devries-cameron20 / t3code Mirror · read-only / commits / 003ccd336d
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 22, 13:15 UTC

fix(client-runtime): pairing links can no longer add routes to a saved environment (#26178)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 27, 2026 at 23:14 UTC 003ccd336dc8c2b9a0cbe62cfc358075e86db28c
5 files changed +206 -83
docs/user/remote-access.md
+4 -3
@@ -79,9 +79,10 @@ URL, SSH, or T3 Connect. Tailscale shares its `100.64.0.0/10` address range with
79 other VPNs such as Cloudflare WARP, so an address in that range shows as VPN
80 unless the machine confirms it is on Tailscale. To add a route, choose **Add
81 route** in the machine's route list, or next to it in the T3 Connect list.
82 -Pairing the same machine again over another address also adds a route instead
83 -of a second machine. A new route is placed by speed, in that order, and you can
84 -reorder routes at any time.
82 +A pairing link for a saved machine is refused when it comes from an address
83 +that machine does not have yet; add that address with **Add route** instead.
84 +Pairing again over an address the machine already has still works. A new route
85 +is placed by speed, in that order, and you can reorder routes at any time.
86
87 While connected through T3 Connect or a paired address, T3 Code also learns the
88 machine's current LAN and Tailscale addresses and adds them as routes, so
packages/client-runtime/src/connection/onboarding.test.ts
+143 -64
@@ -6,6 +6,7 @@ import {
6 } from "@t3tools/contracts";
7 import { 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";
@@ -37,6 +38,7 @@ import {
38 } from "./onboarding.ts";
39 import * as EnvironmentRegistry from "./registry.ts";
40 import * as ConnectionProfileStore from "./profileStore.ts";
41 +import { connectionRoutes, routeHttpBaseUrl } from "./routes.ts";
42 import * as ConnectionWakeups from "./wakeups.ts";
43
44 const layerClientPresentation = Layer.succeed(
@@ -58,6 +60,7 @@ function layerPairingHttp(
60 readonly protocolVersion?: number;
61 readonly selfUpdate?: boolean;
62 readonly grantScopes?: ReadonlyArray<AuthEnvironmentScope>;
63 + readonly exchangeGate?: { readonly reached: () => void; readonly release: Promise<void> };
64 },
65 ) {
66 const grantScopes = options?.grantScopes ?? AuthStandardClientScopes;
@@ -121,15 +124,17 @@ function layerPairingHttp(
124 ),
125 );
126 }
124 - return Promise.resolve(
125 - Response.json({
126 - access_token: "bearer-token",
127 - issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
128 - token_type: "Bearer",
129 - expires_in: 3600,
130 - scope: sessionScopes.join(" "),
131 - }),
132 - );
127 + const granted = Response.json({
128 + access_token: "bearer-token",
129 + issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
130 + token_type: "Bearer",
131 + expires_in: 3600,
132 + scope: sessionScopes.join(" "),
133 + });
134 + const gate = options?.exchangeGate;
135 + if (gate === undefined) return Promise.resolve(granted);
136 + gate.reached();
137 + return gate.release.then(() => granted);
138 }
139
140 if (url.endsWith("/api/auth/session")) {
@@ -154,10 +159,13 @@ function layerPairingHttp(
159 return RpcHttp.layerRemoteHttpClient(fetchFn);
160 }
161
157 -function layerPairingOnboarding(options?: Parameters<typeof layerPairingHttp>[1]) {
162 +function layerPairingOnboarding(
163 + options?: Parameters<typeof layerPairingHttp>[1],
164 + calls: Array<{ readonly url: string; readonly init: RequestInit }> = [],
165 +) {
166 const dependencies = Layer.mergeAll(
167 layerClientPresentation,
160 - layerPairingHttp([], options),
168 + layerPairingHttp(calls, options),
169 Layer.mock(Persistence.ConnectionTargetStore)({
170 list: Effect.succeed([]),
171 listDisabled: Effect.succeed([]),
@@ -168,7 +176,10 @@ function layerPairingOnboarding(options?: Parameters<typeof layerPairingHttp>[1]
176 }),
177 Layer.mock(Persistence.EnvironmentCacheStore)({}),
178 Layer.mock(ConnectionProfileStore.ConnectionProfileStore)({}),
171 - Layer.mock(ConnectionCredentialStore.ConnectionCredentialStore)({}),
179 + Layer.mock(ConnectionCredentialStore.ConnectionCredentialStore)({
180 + get: () => Effect.succeedNone,
181 + put: () => Effect.void,
182 + }),
183 Layer.mock(ClientCapabilities.SshEnvironmentGateway)({}),
184 Layer.succeed(
185 Connectivity.Connectivity,
@@ -230,7 +241,7 @@ describe("connection onboarding", () => {
241 const registration = yield* preparePairingRegistration({
242 host: "remote.example.test",
243 pairingCode: "pairing-token",
233 - }).pipe(Effect.provide(Layer.mergeAll(layerClientPresentation, layerPairingHttp(calls))));
244 + }).pipe(Effect.provide(layerPairingOnboarding(undefined, calls)));
245
246 expect(registration).toMatchObject({
247 _tag: "BearerConnectionRegistration",
@@ -294,6 +305,72 @@ describe("connection onboarding", () => {
305 }).pipe(Effect.provide(layerPairingOnboarding())),
306 );
307
308 + it.effect("refuses a pairing link that claims a saved environment from a new address", () => {
309 + const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
310 + return Effect.gen(function* () {
311 + const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
312 + const onboarding = yield* Onboarding.ConnectionOnboarding;
313 + const before = yield* registerSwitchedOffEnvironment;
314 +
315 + const error = yield* onboarding
316 + .registerPairing({ host: "attacker.example.test", pairingCode: "pairing-token" })
317 + .pipe(Effect.flip);
318 +
319 + expect(error).toMatchObject({ _tag: "ConnectionBlockedError", reason: "configuration" });
320 + expect(yield* SubscriptionRef.get(registry.entries)).toEqual(before);
321 + expect(calls.map((call) => call.url)).toEqual([
322 + "https://attacker.example.test/.well-known/t3/environment",
323 + ]);
324 + }).pipe(Effect.provide(layerPairingOnboarding(undefined, calls)));
325 + });
326 +
327 + it.effect("refuses a new address when the environment is saved during the exchange", () => {
328 + let reached!: () => void;
329 + let release!: () => void;
330 + const exchangeReached = new Promise<void>((resolve) => (reached = resolve));
331 + const exchangeGate = {
332 + reached: () => reached(),
333 + release: new Promise<void>((resolve) => (release = resolve)),
334 + };
335 + return Effect.gen(function* () {
336 + const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
337 + const onboarding = yield* Onboarding.ConnectionOnboarding;
338 + const pairing = yield* onboarding
339 + .registerPairing({ host: "attacker.example.test", pairingCode: "pairing-token" })
340 + .pipe(Effect.result, Effect.forkChild);
341 + yield* Effect.promise(() => exchangeReached);
342 + const before = yield* registerSwitchedOffEnvironment;
343 + release();
344 +
345 + const outcome = yield* Fiber.join(pairing);
346 +
347 + expect(outcome).toMatchObject({
348 + _tag: "Failure",
349 + failure: { _tag: "ConnectionBlockedError", reason: "configuration" },
350 + });
351 + expect(yield* SubscriptionRef.get(registry.entries)).toEqual(before);
352 + }).pipe(Effect.provide(layerPairingOnboarding({ exchangeGate })));
353 + });
354 +
355 + it.effect("adds a new address as a route when pairing targets that environment", () =>
356 + Effect.gen(function* () {
357 + const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
358 + const onboarding = yield* Onboarding.ConnectionOnboarding;
359 + yield* registerSwitchedOffEnvironment;
360 +
361 + yield* onboarding.registerPairing({
362 + host: "lan.example.test",
363 + pairingCode: "pairing-token",
364 + expectedEnvironmentId: PAIRED_ENVIRONMENT_ID,
365 + });
366 +
367 + const entry = (yield* SubscriptionRef.get(registry.entries)).get(PAIRED_ENVIRONMENT_ID);
368 + expect(entry === undefined ? [] : connectionRoutes(entry).map(routeHttpBaseUrl)).toEqual(
369 + expect.arrayContaining(["https://remote.example.test/", "https://lan.example.test/"]),
370 + );
371 + }).pipe(Effect.provide(layerPairingOnboarding())),
372 + );
373 +
374 it.effect(
375 "re-pairs an outdated self-updatable environment so its connection can be rechecked",
376 () =>
@@ -334,34 +411,55 @@ describe("connection onboarding", () => {
411 ),
412 );
413
337 - it.effect("leaves a platform-managed environment untouched when its id is paired", () =>
338 - Effect.gen(function* () {
339 - const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
340 - const onboarding = yield* Onboarding.ConnectionOnboarding;
341 - yield* registry.reconcilePlatform([
342 - new PrimaryConnectionRegistration({
343 - target: new PrimaryConnectionTarget({
344 - environmentId: PAIRED_ENVIRONMENT_ID,
345 - label: "Host environment",
346 - httpBaseUrl: "http://127.0.0.1:3773",
347 - wsBaseUrl: "ws://127.0.0.1:3773",
348 - }),
414 + it.effect.each([
415 + {
416 + kind: "primary",
417 + registration: new PrimaryConnectionRegistration({
418 + target: new PrimaryConnectionTarget({
419 + environmentId: PAIRED_ENVIRONMENT_ID,
420 + label: "Host environment",
421 + httpBaseUrl: "http://127.0.0.1:3773",
422 + wsBaseUrl: "ws://127.0.0.1:3773",
423 }),
350 - ]);
351 - yield* registry.setCompatibility(PAIRED_ENVIRONMENT_ID, UNSUPPORTED_ERROR);
352 - const before = yield* SubscriptionRef.get(registry.entries);
353 - expect(before.get(PAIRED_ENVIRONMENT_ID)).toMatchObject({
354 - enabled: true,
355 - unsupportedReason: UNSUPPORTED_ERROR.message,
356 - });
424 + }),
425 + },
426 + {
427 + kind: "bearer",
428 + registration: new BearerConnectionRegistration({
429 + target: new BearerConnectionTarget({
430 + environmentId: PAIRED_ENVIRONMENT_ID,
431 + connectionId: "platform:wsl",
432 + label: "WSL",
433 + }),
434 + profile: new BearerConnectionProfile({
435 + ...PAIRED_PROFILE,
436 + connectionId: "platform:wsl",
437 + label: "WSL",
438 + httpBaseUrl: "http://127.0.0.1:4000",
439 + wsBaseUrl: "ws://127.0.0.1:4000",
440 + }),
441 + credential: new BearerConnectionCredential({ token: "platform-token" }),
442 + }),
443 + },
444 + ] as const)(
445 + "leaves a platform-managed $kind environment untouched when its id is paired",
446 + ({ registration }) =>
447 + Effect.gen(function* () {
448 + const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
449 + const onboarding = yield* Onboarding.ConnectionOnboarding;
450 + yield* registry.reconcilePlatform([registration]);
451 + yield* registry.setCompatibility(PAIRED_ENVIRONMENT_ID, UNSUPPORTED_ERROR);
452 + const before = yield* SubscriptionRef.get(registry.entries);
453 + expect(before.get(PAIRED_ENVIRONMENT_ID)).toMatchObject({
454 + enabled: true,
455 + unsupportedReason: UNSUPPORTED_ERROR.message,
456 + });
457
358 - const environmentId = yield* onboarding.registerPairing(PAIRING_INPUT);
458 + const environmentId = yield* onboarding.registerPairing(PAIRING_INPUT);
459
360 - expect(environmentId).toBe(PAIRED_ENVIRONMENT_ID);
361 - const after = yield* SubscriptionRef.get(registry.entries);
362 - expect(after).toEqual(before);
363 - expect(after.get(PAIRED_ENVIRONMENT_ID)?.unsupportedReason).toBe(UNSUPPORTED_ERROR.message);
364 - }).pipe(Effect.provide(layerPairingOnboarding())),
460 + expect(environmentId).toBe(PAIRED_ENVIRONMENT_ID);
461 + expect(yield* SubscriptionRef.get(registry.entries)).toEqual(before);
462 + }).pipe(Effect.provide(layerPairingOnboarding())),
463 );
464
465 it.effect("leaves a switched-off environment unchanged when the pairing exchange fails", () =>
@@ -392,10 +490,7 @@ describe("connection onboarding", () => {
490 pairingCode: "pairing-token",
491 }).pipe(
492 Effect.provide(
395 - Layer.mergeAll(
396 - layerClientPresentation,
397 - layerPairingHttp(calls, { protocolVersion: ORCHESTRATION_PROTOCOL_VERSION + 1 }),
398 - ),
493 + layerPairingOnboarding({ protocolVersion: ORCHESTRATION_PROTOCOL_VERSION + 1 }, calls),
494 ),
495 Effect.flip,
496 );
@@ -410,21 +505,19 @@ describe("connection onboarding", () => {
505 { label: "default", scopes: AuthStandardClientScopes },
506 ] as const)("preserves the $label grant when pairing a remote environment", ({ scopes }) =>
507 Effect.gen(function* () {
413 - const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
414 - const httpLayer = layerPairingHttp(calls, { grantScopes: scopes });
508 const registration = yield* preparePairingRegistration({
509 host: "remote.example.test",
510 pairingCode: "pairing-token",
418 - }).pipe(Effect.provide(Layer.mergeAll(layerClientPresentation, httpLayer)));
511 + });
512
513 const session = yield* fetchRemoteSessionState({
514 httpBaseUrl: registration.profile.httpBaseUrl,
515 bearerToken: registration.credential.token,
423 - }).pipe(Effect.provide(httpLayer));
516 + });
517
518 expect(session.authenticated).toBe(true);
519 expect(session.scopes).toEqual(scopes);
427 - }),
520 + }).pipe(Effect.provide(layerPairingOnboarding({ grantScopes: scopes }))),
521 );
522
523 it.effect("refuses to add a route that reaches a different machine, keeping the code", () =>
@@ -434,10 +527,7 @@ describe("connection onboarding", () => {
527 host: "remote.example.test",
528 pairingCode: "pairing-token",
529 expectedEnvironmentId: EnvironmentId.make("some-other-machine"),
437 - }).pipe(
438 - Effect.provide(Layer.mergeAll(layerClientPresentation, layerPairingHttp(calls))),
439 - Effect.flip,
440 - );
530 + }).pipe(Effect.provide(layerPairingOnboarding(undefined, calls)), Effect.flip);
531 expect(error).toMatchObject({ reason: "configuration" });
532 expect(error.message).toContain("different machine");
533 expect(calls.map((call) => call.url)).toEqual([
@@ -454,10 +544,7 @@ describe("connection onboarding", () => {
544 pairingCode: "pairing-token",
545 }).pipe(
546 Effect.provide(
457 - Layer.mergeAll(
458 - layerClientPresentation,
459 - layerPairingHttp(calls, { protocolVersion: ORCHESTRATION_PROTOCOL_VERSION - 1 }),
460 - ),
547 + layerPairingOnboarding({ protocolVersion: ORCHESTRATION_PROTOCOL_VERSION - 1 }, calls),
548 ),
549 Effect.flip,
550 );
@@ -476,15 +563,7 @@ describe("connection onboarding", () => {
563 yield* preparePairingRegistration({
564 host: "remote.example.test",
565 pairingCode: "pairing-token",
479 - }).pipe(
480 - Effect.provide(
481 - Layer.mergeAll(
482 - layerClientPresentation,
483 - layerPairingHttp(calls, { failDescriptor: true }),
484 - ),
485 - ),
486 - Effect.flip,
487 - );
566 + }).pipe(Effect.provide(layerPairingOnboarding({ failDescriptor: true }, calls)), Effect.flip);
567
568 expect(calls.map((call) => call.url)).toEqual([
569 "https://remote.example.test/.well-known/t3/environment",
packages/client-runtime/src/connection/onboarding.ts
+24 -13
@@ -113,19 +113,8 @@ export const preparePairingRegistration = Effect.fn(
113 ) {
114 return yield* differentMachineError(descriptor.label);
115 }
116 - const compatibilityError = orchestrationProtocolCompatibilityError(descriptor);
117 - // An outdated server is still saved so it can be updated from this client.
118 - if (compatibilityError !== null && compatibilityError.serverUpdateRequired !== true) {
119 - return yield* compatibilityError;
120 - }
121 - const access = yield* bootstrapRemoteBearerSession({
122 - httpBaseUrl: target.httpBaseUrl,
123 - credential: target.credential,
124 - clientMetadata: presentation.metadata,
125 - }).pipe(Effect.mapError(mapRemoteEnvironmentError));
116 const connectionId = bearerConnectionId(descriptor.environmentId, target.httpBaseUrl);
127 -
128 - return new BearerConnectionRegistration({
117 + const route = {
118 target: new BearerConnectionTarget({
119 environmentId: descriptor.environmentId,
120 label: descriptor.label,
@@ -138,6 +127,25 @@ export const preparePairingRegistration = Effect.fn(
127 httpBaseUrl: target.httpBaseUrl,
128 wsBaseUrl: target.wsBaseUrl,
129 }),
130 + };
131 + // The registry checks again under its lease; this early check keeps a refused code unspent.
132 + if (input.expectedEnvironmentId === undefined) {
133 + const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
134 + yield* registry.assertKnownAddress({ ...route, profile: Option.some(route.profile) });
135 + }
136 + const compatibilityError = orchestrationProtocolCompatibilityError(descriptor);
137 + // An outdated server is still saved so it can be updated from this client.
138 + if (compatibilityError !== null && compatibilityError.serverUpdateRequired !== true) {
139 + return yield* compatibilityError;
140 + }
141 + const access = yield* bootstrapRemoteBearerSession({
142 + httpBaseUrl: target.httpBaseUrl,
143 + credential: target.credential,
144 + clientMetadata: presentation.metadata,
145 + }).pipe(Effect.mapError(mapRemoteEnvironmentError));
146 +
147 + return new BearerConnectionRegistration({
148 + ...route,
149 credential: new BearerConnectionCredential({
150 token: access.access_token,
151 }),
@@ -149,7 +157,10 @@ const registerPairingConnection = Effect.fn(
157 )(function* (input: PairingConnectionInput) {
158 const registration = yield* preparePairingRegistration(input);
159 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
152 - if (!(yield* registry.register(registration))) return registration.target.environmentId;
160 + const knownAddressOnly = input.expectedEnvironmentId === undefined;
161 + if (!(yield* registry.register(registration, { knownAddressOnly }))) {
162 + return registration.target.environmentId;
163 + }
164 yield* registry.setCompatibility(registration.target.environmentId, null);
165 yield* registry
166 .setEnabled(registration.target.environmentId, true)
packages/client-runtime/src/connection/registry.ts
+34 -3
@@ -101,11 +101,20 @@ export class EnvironmentRegistry extends Context.Service<
101 readonly start: Effect.Effect<void>;
102 /**
103 * Succeeds with `false` and changes nothing when the environment is
104 - * platform-managed, since the host owns that entry.
104 + * platform-managed, since the host owns that entry. With `knownAddressOnly`, it fails like
105 + * `assertKnownAddress`, checked under the environment's lease.
106 */
107 readonly register: (
108 registration: ConnectionRegistration,
108 - ) => Effect.Effect<boolean, Persistence.ConnectionPersistenceError>;
109 + options?: { readonly knownAddressOnly?: boolean },
110 + ) => Effect.Effect<boolean, Persistence.ConnectionPersistenceError | ConnectionBlockedError>;
111 + /**
112 + * Fails when the route would add a new address to a saved user environment. Pairing that does
113 + * not target an environment checks this, because the server reports its own environment id.
114 + */
115 + readonly assertKnownAddress: (
116 + route: ConnectionRoute,
117 + ) => Effect.Effect<void, ConnectionBlockedError>;
118 readonly reconcilePlatform: (
119 registrations: ReadonlyArray<PlatformConnectionRegistration>,
120 ) => Effect.Effect<void>;
@@ -532,21 +541,42 @@ export const make = Effect.gen(function* () {
541 return { entry: rest, addressesChanged: true };
542 };
543
544 + const assertKnownAddress = Effect.fn("EnvironmentRegistry.assertKnownAddress")(function* (
545 + route: ConnectionRoute,
546 + ) {
547 + const environmentId = route.target.environmentId;
548 + if ((yield* Ref.get(platformEnvironmentIds)).has(environmentId)) return;
549 + const saved = (yield* SubscriptionRef.get(entries)).get(environmentId);
550 + if (
551 + saved !== undefined &&
552 + findRouteToSameAddress(connectionRoutes(saved), route) === undefined
553 + ) {
554 + return yield* new ConnectionBlockedError({
555 + reason: "configuration",
556 + detail: `That address claims to be ${saved.target.label}, which is already saved. Add it as a route from that environment's settings instead.`,
557 + });
558 + }
559 + });
560 +
561 const register = Effect.fn("EnvironmentRegistry.register")(function* (
562 registration: ConnectionRegistration,
563 + options?: { readonly knownAddressOnly?: boolean },
564 ) {
565 const registered = connectionRegistrationCatalogEntry(registration);
566 const environmentId = registered.target.environmentId;
567 + const route: ConnectionRoute = { target: registered.target, profile: registered.profile };
568 return yield* withLeaseLock(
569 environmentId,
570 Effect.gen(function* () {
571 if ((yield* Ref.get(platformEnvironmentIds)).has(environmentId)) {
572 return false;
573 }
574 + if (options?.knownAddressOnly === true) {
575 + yield* assertKnownAddress(route);
576 + }
577 const previous = (yield* SubscriptionRef.get(entries)).get(environmentId);
578 let entry = registered;
579 if (previous !== undefined) {
549 - const route: ConnectionRoute = { target: registered.target, profile: registered.profile };
580 const existing = connectionRoutes(previous);
581 const sameAddress = findRouteToSameAddress(existing, route);
582 const routes = existing.filter(
@@ -1132,6 +1162,7 @@ export const make = Effect.gen(function* () {
1162 networkStatus,
1163 start,
1164 register,
1165 + assertKnownAddress,
1166 reconcilePlatform,
1167 remove,
1168 removeRoute,
packages/client-runtime/src/state/threads-atoms.test.ts
+1
@@ -128,6 +128,7 @@ const makeHarness = Effect.fn("TestThreadAtoms.makeHarness")(function* (options?
128 networkStatus: yield* SubscriptionRef.make<NetworkStatus>("online"),
129 start: Effect.void,
130 register: () => Effect.die("Unexpected environment registration"),
131 + assertKnownAddress: () => Effect.die("Unexpected address check"),
132 reconcilePlatform: () => Effect.die("Unexpected environment reconciliation"),
133 remove: () => Effect.die("Unexpected environment removal"),
134 removeRoute: () => Effect.die("Unexpected route removal"),