TypeScript
fix(client-runtime): pairing links can no longer add routes to a saved environment (#26178)
Julius Marminge003ccd336dc8
diff --git a/docs/user/remote-access.md b/docs/user/remote-access.mdindex d1bfe3710d2..835476864a1 100644--- a/docs/user/remote-access.md+++ b/docs/user/remote-access.md@@ -79,9 +79,10 @@ URL, SSH, or T3 Connect. Tailscale shares its `100.64.0.0/10` address range withother VPNs such as Cloudflare WARP, so an address in that range shows as VPNunless the machine confirms it is on Tailscale. To add a route, choose **Addroute** in the machine's route list, or next to it in the T3 Connect list.-Pairing the same machine again over another address also adds a route instead-of a second machine. A new route is placed by speed, in that order, and you can-reorder routes at any time.+A pairing link for a saved machine is refused when it comes from an address+that machine does not have yet; add that address with **Add route** instead.+Pairing again over an address the machine already has still works. A new route+is placed by speed, in that order, and you can reorder routes at any time.While connected through T3 Connect or a paired address, T3 Code also learns themachine's current LAN and Tailscale addresses and adds them as routes, sodiff --git a/packages/client-runtime/src/connection/onboarding.test.ts b/packages/client-runtime/src/connection/onboarding.test.tsindex 59d28bc25ff..2131507e547 100644--- a/packages/client-runtime/src/connection/onboarding.test.ts+++ b/packages/client-runtime/src/connection/onboarding.test.ts@@ -6,6 +6,7 @@ import {} from "@t3tools/contracts";import { describe, expect, it } from "@effect/vitest";import * as Effect from "effect/Effect";+import * as Fiber from "effect/Fiber";import * as Layer from "effect/Layer";import * as Option from "effect/Option";import * as Stream from "effect/Stream";@@ -37,6 +38,7 @@ import {} from "./onboarding.ts";import * as EnvironmentRegistry from "./registry.ts";import * as ConnectionProfileStore from "./profileStore.ts";+import { connectionRoutes, routeHttpBaseUrl } from "./routes.ts";import * as ConnectionWakeups from "./wakeups.ts";const layerClientPresentation = Layer.succeed(@@ -58,6 +60,7 @@ function layerPairingHttp(readonly protocolVersion?: number;readonly selfUpdate?: boolean;readonly grantScopes?: ReadonlyArray<AuthEnvironmentScope>;+ readonly exchangeGate?: { readonly reached: () => void; readonly release: Promise<void> };},) {const grantScopes = options?.grantScopes ?? AuthStandardClientScopes;@@ -121,15 +124,17 @@ function layerPairingHttp(),);}- return Promise.resolve(- Response.json({- access_token: "bearer-token",- issued_token_type: "urn:ietf:params:oauth:token-type:access_token",- token_type: "Bearer",- expires_in: 3600,- scope: sessionScopes.join(" "),- }),- );+ const granted = Response.json({+ access_token: "bearer-token",+ issued_token_type: "urn:ietf:params:oauth:token-type:access_token",+ token_type: "Bearer",+ expires_in: 3600,+ scope: sessionScopes.join(" "),+ });+ const gate = options?.exchangeGate;+ if (gate === undefined) return Promise.resolve(granted);+ gate.reached();+ return gate.release.then(() => granted);}if (url.endsWith("/api/auth/session")) {@@ -154,10 +159,13 @@ function layerPairingHttp(return RpcHttp.layerRemoteHttpClient(fetchFn);}-function layerPairingOnboarding(options?: Parameters<typeof layerPairingHttp>[1]) {+function layerPairingOnboarding(+ options?: Parameters<typeof layerPairingHttp>[1],+ calls: Array<{ readonly url: string; readonly init: RequestInit }> = [],+) {const dependencies = Layer.mergeAll(layerClientPresentation,- layerPairingHttp([], options),+ layerPairingHttp(calls, options),Layer.mock(Persistence.ConnectionTargetStore)({list: Effect.succeed([]),listDisabled: Effect.succeed([]),@@ -168,7 +176,10 @@ function layerPairingOnboarding(options?: Parameters<typeof layerPairingHttp>[1]}),Layer.mock(Persistence.EnvironmentCacheStore)({}),Layer.mock(ConnectionProfileStore.ConnectionProfileStore)({}),- Layer.mock(ConnectionCredentialStore.ConnectionCredentialStore)({}),+ Layer.mock(ConnectionCredentialStore.ConnectionCredentialStore)({+ get: () => Effect.succeedNone,+ put: () => Effect.void,+ }),Layer.mock(ClientCapabilities.SshEnvironmentGateway)({}),Layer.succeed(Connectivity.Connectivity,@@ -230,7 +241,7 @@ describe("connection onboarding", () => {const registration = yield* preparePairingRegistration({host: "remote.example.test",pairingCode: "pairing-token",- }).pipe(Effect.provide(Layer.mergeAll(layerClientPresentation, layerPairingHttp(calls))));+ }).pipe(Effect.provide(layerPairingOnboarding(undefined, calls)));expect(registration).toMatchObject({_tag: "BearerConnectionRegistration",@@ -294,6 +305,72 @@ describe("connection onboarding", () => {}).pipe(Effect.provide(layerPairingOnboarding())),);+ it.effect("refuses a pairing link that claims a saved environment from a new address", () => {+ const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];+ return Effect.gen(function* () {+ const registry = yield* EnvironmentRegistry.EnvironmentRegistry;+ const onboarding = yield* Onboarding.ConnectionOnboarding;+ const before = yield* registerSwitchedOffEnvironment;++ const error = yield* onboarding+ .registerPairing({ host: "attacker.example.test", pairingCode: "pairing-token" })+ .pipe(Effect.flip);++ expect(error).toMatchObject({ _tag: "ConnectionBlockedError", reason: "configuration" });+ expect(yield* SubscriptionRef.get(registry.entries)).toEqual(before);+ expect(calls.map((call) => call.url)).toEqual([+ "https://attacker.example.test/.well-known/t3/environment",+ ]);+ }).pipe(Effect.provide(layerPairingOnboarding(undefined, calls)));+ });++ it.effect("refuses a new address when the environment is saved during the exchange", () => {+ let reached!: () => void;+ let release!: () => void;+ const exchangeReached = new Promise<void>((resolve) => (reached = resolve));+ const exchangeGate = {+ reached: () => reached(),+ release: new Promise<void>((resolve) => (release = resolve)),+ };+ return Effect.gen(function* () {+ const registry = yield* EnvironmentRegistry.EnvironmentRegistry;+ const onboarding = yield* Onboarding.ConnectionOnboarding;+ const pairing = yield* onboarding+ .registerPairing({ host: "attacker.example.test", pairingCode: "pairing-token" })+ .pipe(Effect.result, Effect.forkChild);+ yield* Effect.promise(() => exchangeReached);+ const before = yield* registerSwitchedOffEnvironment;+ release();++ const outcome = yield* Fiber.join(pairing);++ expect(outcome).toMatchObject({+ _tag: "Failure",+ failure: { _tag: "ConnectionBlockedError", reason: "configuration" },+ });+ expect(yield* SubscriptionRef.get(registry.entries)).toEqual(before);+ }).pipe(Effect.provide(layerPairingOnboarding({ exchangeGate })));+ });++ it.effect("adds a new address as a route when pairing targets that environment", () =>+ Effect.gen(function* () {+ const registry = yield* EnvironmentRegistry.EnvironmentRegistry;+ const onboarding = yield* Onboarding.ConnectionOnboarding;+ yield* registerSwitchedOffEnvironment;++ yield* onboarding.registerPairing({+ host: "lan.example.test",+ pairingCode: "pairing-token",+ expectedEnvironmentId: PAIRED_ENVIRONMENT_ID,+ });++ const entry = (yield* SubscriptionRef.get(registry.entries)).get(PAIRED_ENVIRONMENT_ID);+ expect(entry === undefined ? [] : connectionRoutes(entry).map(routeHttpBaseUrl)).toEqual(+ expect.arrayContaining(["https://remote.example.test/", "https://lan.example.test/"]),+ );+ }).pipe(Effect.provide(layerPairingOnboarding())),+ );+it.effect("re-pairs an outdated self-updatable environment so its connection can be rechecked",() =>@@ -334,34 +411,55 @@ describe("connection onboarding", () => {),);- it.effect("leaves a platform-managed environment untouched when its id is paired", () =>- Effect.gen(function* () {- const registry = yield* EnvironmentRegistry.EnvironmentRegistry;- const onboarding = yield* Onboarding.ConnectionOnboarding;- yield* registry.reconcilePlatform([- new PrimaryConnectionRegistration({- target: new PrimaryConnectionTarget({- environmentId: PAIRED_ENVIRONMENT_ID,- label: "Host environment",- httpBaseUrl: "http://127.0.0.1:3773",- wsBaseUrl: "ws://127.0.0.1:3773",- }),+ it.effect.each([+ {+ kind: "primary",+ registration: new PrimaryConnectionRegistration({+ target: new PrimaryConnectionTarget({+ environmentId: PAIRED_ENVIRONMENT_ID,+ label: "Host environment",+ httpBaseUrl: "http://127.0.0.1:3773",+ wsBaseUrl: "ws://127.0.0.1:3773",}),- ]);- yield* registry.setCompatibility(PAIRED_ENVIRONMENT_ID, UNSUPPORTED_ERROR);- const before = yield* SubscriptionRef.get(registry.entries);- expect(before.get(PAIRED_ENVIRONMENT_ID)).toMatchObject({- enabled: true,- unsupportedReason: UNSUPPORTED_ERROR.message,- });+ }),+ },+ {+ kind: "bearer",+ registration: new BearerConnectionRegistration({+ target: new BearerConnectionTarget({+ environmentId: PAIRED_ENVIRONMENT_ID,+ connectionId: "platform:wsl",+ label: "WSL",+ }),+ profile: new BearerConnectionProfile({+ ...PAIRED_PROFILE,+ connectionId: "platform:wsl",+ label: "WSL",+ httpBaseUrl: "http://127.0.0.1:4000",+ wsBaseUrl: "ws://127.0.0.1:4000",+ }),+ credential: new BearerConnectionCredential({ token: "platform-token" }),+ }),+ },+ ] as const)(+ "leaves a platform-managed $kind environment untouched when its id is paired",+ ({ registration }) =>+ Effect.gen(function* () {+ const registry = yield* EnvironmentRegistry.EnvironmentRegistry;+ const onboarding = yield* Onboarding.ConnectionOnboarding;+ yield* registry.reconcilePlatform([registration]);+ yield* registry.setCompatibility(PAIRED_ENVIRONMENT_ID, UNSUPPORTED_ERROR);+ const before = yield* SubscriptionRef.get(registry.entries);+ expect(before.get(PAIRED_ENVIRONMENT_ID)).toMatchObject({+ enabled: true,+ unsupportedReason: UNSUPPORTED_ERROR.message,+ });- const environmentId = yield* onboarding.registerPairing(PAIRING_INPUT);+ const environmentId = yield* onboarding.registerPairing(PAIRING_INPUT);- expect(environmentId).toBe(PAIRED_ENVIRONMENT_ID);- const after = yield* SubscriptionRef.get(registry.entries);- expect(after).toEqual(before);- expect(after.get(PAIRED_ENVIRONMENT_ID)?.unsupportedReason).toBe(UNSUPPORTED_ERROR.message);- }).pipe(Effect.provide(layerPairingOnboarding())),+ expect(environmentId).toBe(PAIRED_ENVIRONMENT_ID);+ expect(yield* SubscriptionRef.get(registry.entries)).toEqual(before);+ }).pipe(Effect.provide(layerPairingOnboarding())),);it.effect("leaves a switched-off environment unchanged when the pairing exchange fails", () =>@@ -392,10 +490,7 @@ describe("connection onboarding", () => {pairingCode: "pairing-token",}).pipe(Effect.provide(- Layer.mergeAll(- layerClientPresentation,- layerPairingHttp(calls, { protocolVersion: ORCHESTRATION_PROTOCOL_VERSION + 1 }),- ),+ layerPairingOnboarding({ protocolVersion: ORCHESTRATION_PROTOCOL_VERSION + 1 }, calls),),Effect.flip,);@@ -410,21 +505,19 @@ describe("connection onboarding", () => {{ label: "default", scopes: AuthStandardClientScopes },] as const)("preserves the $label grant when pairing a remote environment", ({ scopes }) =>Effect.gen(function* () {- const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];- const httpLayer = layerPairingHttp(calls, { grantScopes: scopes });const registration = yield* preparePairingRegistration({host: "remote.example.test",pairingCode: "pairing-token",- }).pipe(Effect.provide(Layer.mergeAll(layerClientPresentation, httpLayer)));+ });const session = yield* fetchRemoteSessionState({httpBaseUrl: registration.profile.httpBaseUrl,bearerToken: registration.credential.token,- }).pipe(Effect.provide(httpLayer));+ });expect(session.authenticated).toBe(true);expect(session.scopes).toEqual(scopes);- }),+ }).pipe(Effect.provide(layerPairingOnboarding({ grantScopes: scopes }))),);it.effect("refuses to add a route that reaches a different machine, keeping the code", () =>@@ -434,10 +527,7 @@ describe("connection onboarding", () => {host: "remote.example.test",pairingCode: "pairing-token",expectedEnvironmentId: EnvironmentId.make("some-other-machine"),- }).pipe(- Effect.provide(Layer.mergeAll(layerClientPresentation, layerPairingHttp(calls))),- Effect.flip,- );+ }).pipe(Effect.provide(layerPairingOnboarding(undefined, calls)), Effect.flip);expect(error).toMatchObject({ reason: "configuration" });expect(error.message).toContain("different machine");expect(calls.map((call) => call.url)).toEqual([@@ -454,10 +544,7 @@ describe("connection onboarding", () => {pairingCode: "pairing-token",}).pipe(Effect.provide(- Layer.mergeAll(- layerClientPresentation,- layerPairingHttp(calls, { protocolVersion: ORCHESTRATION_PROTOCOL_VERSION - 1 }),- ),+ layerPairingOnboarding({ protocolVersion: ORCHESTRATION_PROTOCOL_VERSION - 1 }, calls),),Effect.flip,);@@ -476,15 +563,7 @@ describe("connection onboarding", () => {yield* preparePairingRegistration({host: "remote.example.test",pairingCode: "pairing-token",- }).pipe(- Effect.provide(- Layer.mergeAll(- layerClientPresentation,- layerPairingHttp(calls, { failDescriptor: true }),- ),- ),- Effect.flip,- );+ }).pipe(Effect.provide(layerPairingOnboarding({ failDescriptor: true }, calls)), Effect.flip);expect(calls.map((call) => call.url)).toEqual(["https://remote.example.test/.well-known/t3/environment",diff --git a/packages/client-runtime/src/connection/onboarding.ts b/packages/client-runtime/src/connection/onboarding.tsindex 66f14f2eca6..48e8b614c67 100644--- a/packages/client-runtime/src/connection/onboarding.ts+++ b/packages/client-runtime/src/connection/onboarding.ts@@ -113,19 +113,8 @@ export const preparePairingRegistration = Effect.fn() {return yield* differentMachineError(descriptor.label);}- const compatibilityError = orchestrationProtocolCompatibilityError(descriptor);- // An outdated server is still saved so it can be updated from this client.- if (compatibilityError !== null && compatibilityError.serverUpdateRequired !== true) {- return yield* compatibilityError;- }- const access = yield* bootstrapRemoteBearerSession({- httpBaseUrl: target.httpBaseUrl,- credential: target.credential,- clientMetadata: presentation.metadata,- }).pipe(Effect.mapError(mapRemoteEnvironmentError));const connectionId = bearerConnectionId(descriptor.environmentId, target.httpBaseUrl);-- return new BearerConnectionRegistration({+ const route = {target: new BearerConnectionTarget({environmentId: descriptor.environmentId,label: descriptor.label,@@ -138,6 +127,25 @@ export const preparePairingRegistration = Effect.fn(httpBaseUrl: target.httpBaseUrl,wsBaseUrl: target.wsBaseUrl,}),+ };+ // The registry checks again under its lease; this early check keeps a refused code unspent.+ if (input.expectedEnvironmentId === undefined) {+ const registry = yield* EnvironmentRegistry.EnvironmentRegistry;+ yield* registry.assertKnownAddress({ ...route, profile: Option.some(route.profile) });+ }+ const compatibilityError = orchestrationProtocolCompatibilityError(descriptor);+ // An outdated server is still saved so it can be updated from this client.+ if (compatibilityError !== null && compatibilityError.serverUpdateRequired !== true) {+ return yield* compatibilityError;+ }+ const access = yield* bootstrapRemoteBearerSession({+ httpBaseUrl: target.httpBaseUrl,+ credential: target.credential,+ clientMetadata: presentation.metadata,+ }).pipe(Effect.mapError(mapRemoteEnvironmentError));++ return new BearerConnectionRegistration({+ ...route,credential: new BearerConnectionCredential({token: access.access_token,}),@@ -149,7 +157,10 @@ const registerPairingConnection = Effect.fn()(function* (input: PairingConnectionInput) {const registration = yield* preparePairingRegistration(input);const registry = yield* EnvironmentRegistry.EnvironmentRegistry;- if (!(yield* registry.register(registration))) return registration.target.environmentId;+ const knownAddressOnly = input.expectedEnvironmentId === undefined;+ if (!(yield* registry.register(registration, { knownAddressOnly }))) {+ return registration.target.environmentId;+ }yield* registry.setCompatibility(registration.target.environmentId, null);yield* registry.setEnabled(registration.target.environmentId, true)diff --git a/packages/client-runtime/src/connection/registry.ts b/packages/client-runtime/src/connection/registry.tsindex 1db7eb22749..4d4a06fccc1 100644--- a/packages/client-runtime/src/connection/registry.ts+++ b/packages/client-runtime/src/connection/registry.ts@@ -101,11 +101,20 @@ export class EnvironmentRegistry extends Context.Service<readonly start: Effect.Effect<void>;/*** Succeeds with `false` and changes nothing when the environment is- * platform-managed, since the host owns that entry.+ * platform-managed, since the host owns that entry. With `knownAddressOnly`, it fails like+ * `assertKnownAddress`, checked under the environment's lease.*/readonly register: (registration: ConnectionRegistration,- ) => Effect.Effect<boolean, Persistence.ConnectionPersistenceError>;+ options?: { readonly knownAddressOnly?: boolean },+ ) => Effect.Effect<boolean, Persistence.ConnectionPersistenceError | ConnectionBlockedError>;+ /**+ * Fails when the route would add a new address to a saved user environment. Pairing that does+ * not target an environment checks this, because the server reports its own environment id.+ */+ readonly assertKnownAddress: (+ route: ConnectionRoute,+ ) => Effect.Effect<void, ConnectionBlockedError>;readonly reconcilePlatform: (registrations: ReadonlyArray<PlatformConnectionRegistration>,) => Effect.Effect<void>;@@ -532,21 +541,42 @@ export const make = Effect.gen(function* () {return { entry: rest, addressesChanged: true };};+ const assertKnownAddress = Effect.fn("EnvironmentRegistry.assertKnownAddress")(function* (+ route: ConnectionRoute,+ ) {+ const environmentId = route.target.environmentId;+ if ((yield* Ref.get(platformEnvironmentIds)).has(environmentId)) return;+ const saved = (yield* SubscriptionRef.get(entries)).get(environmentId);+ if (+ saved !== undefined &&+ findRouteToSameAddress(connectionRoutes(saved), route) === undefined+ ) {+ return yield* new ConnectionBlockedError({+ reason: "configuration",+ detail: `That address claims to be ${saved.target.label}, which is already saved. Add it as a route from that environment's settings instead.`,+ });+ }+ });+const register = Effect.fn("EnvironmentRegistry.register")(function* (registration: ConnectionRegistration,+ options?: { readonly knownAddressOnly?: boolean },) {const registered = connectionRegistrationCatalogEntry(registration);const environmentId = registered.target.environmentId;+ const route: ConnectionRoute = { target: registered.target, profile: registered.profile };return yield* withLeaseLock(environmentId,Effect.gen(function* () {if ((yield* Ref.get(platformEnvironmentIds)).has(environmentId)) {return false;}+ if (options?.knownAddressOnly === true) {+ yield* assertKnownAddress(route);+ }const previous = (yield* SubscriptionRef.get(entries)).get(environmentId);let entry = registered;if (previous !== undefined) {- const route: ConnectionRoute = { target: registered.target, profile: registered.profile };const existing = connectionRoutes(previous);const sameAddress = findRouteToSameAddress(existing, route);const routes = existing.filter(@@ -1132,6 +1162,7 @@ export const make = Effect.gen(function* () {networkStatus,start,register,+ assertKnownAddress,reconcilePlatform,remove,removeRoute,diff --git a/packages/client-runtime/src/state/threads-atoms.test.ts b/packages/client-runtime/src/state/threads-atoms.test.tsindex 32cf8fec499..23263d43244 100644--- a/packages/client-runtime/src/state/threads-atoms.test.ts+++ b/packages/client-runtime/src/state/threads-atoms.test.ts@@ -128,6 +128,7 @@ const makeHarness = Effect.fn("TestThreadAtoms.makeHarness")(function* (options?networkStatus: yield* SubscriptionRef.make<NetworkStatus>("online"),start: Effect.void,register: () => Effect.die("Unexpected environment registration"),+ assertKnownAddress: () => Effect.die("Unexpected address check"),reconcilePlatform: () => Effect.die("Unexpected environment reconciliation"),remove: () => Effect.die("Unexpected environment removal"),removeRoute: () => Effect.die("Unexpected route removal"),