From 11fa7b995a8a57ebc4a00b545a1596e83d191294 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 19:20:36 -0800 Subject: [PATCH 1/5] fix(connect): let remote clients with relay configuration link Mobile only linked environments over a bearer connection, which current DPoP pairings never have, and the server only signed link proofs for loopback requests or the desktop session, so no phone could link. Sign the server's own loopback origin from its listening address instead of trusting the caller's request URL or origin, leaving relay:configure as the gate. Mobile now links through the environment's authenticated request path, which covers DPoP and bearer connections alike. Co-Authored-By: Claude Opus 5.5 --- .../liveActivityPreferences.test.ts | 74 +++++------ .../liveActivityPreferences.ts | 19 +-- .../features/cloud/linkEnvironment.test.ts | 61 ++++++--- .../src/features/cloud/linkEnvironment.ts | 121 +++++++++--------- .../SettingsNotificationsRouteScreen.tsx | 41 ++++-- apps/mobile/src/i18n/translations/de.json | 1 - apps/mobile/src/i18n/translations/en.json | 1 - apps/mobile/src/i18n/translations/es.json | 1 - apps/mobile/src/i18n/translations/fr.json | 1 - apps/mobile/src/i18n/translations/ja.json | 1 - apps/mobile/src/i18n/translations/ko.json | 1 - apps/mobile/src/i18n/translations/pt-BR.json | 1 - apps/mobile/src/i18n/translations/ru.json | 1 - apps/mobile/src/i18n/translations/sv.json | 1 - apps/mobile/src/i18n/translations/zh.json | 1 - .../src/cloud/CloudLink.lifecycle.test.ts | 49 ++----- apps/server/src/cloud/CloudLink.ts | 86 +++++-------- apps/server/src/cloud/http.test.ts | 113 +++++----------- apps/server/src/cloud/http.ts | 3 +- apps/server/src/cloud/linkChecks.ts | 23 +--- docs/internals/t3-connect.md | 9 +- 21 files changed, 258 insertions(+), 351 deletions(-) diff --git a/apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts b/apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts index 6a6e08f08299..4ea1aea9989b 100644 --- a/apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts +++ b/apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts @@ -5,15 +5,9 @@ import * as Option from "effect/Option"; import * as Effect from "effect/Effect"; import type { EnvironmentId } from "@t3tools/contracts"; import { ManagedRelay } from "@t3tools/client-runtime/relay"; -import * as Layer from "effect/Layer"; -import { HttpClient } from "effect/http"; import type { SavedRemoteConnection } from "../../lib/connection"; -import * as MobileStorage from "../../persistence/mobile-storage"; -import { - CloudEnvironmentLinkError, - linkEnvironmentToCloudWithPreference, -} from "../cloud/linkEnvironment"; +import { CloudEnvironmentLinkError } from "../cloud/linkEnvironment"; import { setLiveActivityUpdatesEnabled } from "./liveActivityPreferences"; import { updateAgentAwarenessRegistrationPreferences } from "./remoteRegistration"; @@ -33,11 +27,6 @@ vi.mock("expo-constants", () => ({ vi.mock("expo-device", () => ({})); -vi.mock("../cloud/linkEnvironment", async (importOriginal) => ({ - ...(await importOriginal()), - linkEnvironmentToCloudWithPreference: vi.fn(() => Effect.void), -})); - vi.mock("./remoteRegistration", () => ({ updateAgentAwarenessRegistrationPreferences: vi.fn(() => Effect.void), })); @@ -52,6 +41,13 @@ const updateEnvironment = vi.fn< > >(() => Effect.succeed("updated")); +const linkEnvironment = vi.fn< + ( + id: EnvironmentId, + input: { readonly clerkToken: string; readonly liveActivitiesEnabled: boolean }, + ) => Effect.Effect +>(() => Effect.void); + const connection: SavedRemoteConnection = { environmentId: "env-1" as EnvironmentId, environmentLabel: "Desktop", @@ -62,25 +58,7 @@ const connection: SavedRemoteConnection = { bearerToken: "local-bearer", }; -const layerTest = Layer.mergeAll( - Layer.succeed(ManagedRelay.ManagedRelayClient, null as never), - Layer.succeed( - HttpClient.HttpClient, - HttpClient.make(() => Effect.die("unexpected HTTP request")), - ), - Layer.succeed( - MobileStorage.MobileStorage, - MobileStorage.MobileStorage.of({ - loadOrCreateAgentAwarenessDeviceId: Effect.succeed("device-1"), - loadAgentAwarenessDeviceId: Effect.succeed("device-1"), - loadAgentAwarenessRegistrationRecord: Effect.succeed(null), - saveAgentAwarenessRegistrationRecord: () => Effect.void, - clearAgentAwarenessRegistrationRecord: Effect.void, - loadRecentThreadShortcuts: Effect.succeed([]), - saveRecentThreadShortcuts: () => Effect.void, - }), - ), -); +const withRelayClient = Effect.provideService(ManagedRelay.ManagedRelayClient, null as never); describe("liveActivityPreferences", () => { beforeEach(() => { @@ -97,6 +75,7 @@ describe("liveActivityPreferences", () => { const exit = yield* Effect.exit( setLiveActivityUpdatesEnabled({ updateEnvironment, + linkEnvironment, enabled: false, previousEnabled: true, clerkToken: "clerk-token", @@ -120,8 +99,8 @@ describe("liveActivityPreferences", () => { expect(updateEnvironment).toHaveBeenCalledTimes(2); expect(updateEnvironment).toHaveBeenCalledWith(connection.environmentId, false); expect(updateEnvironment).toHaveBeenCalledWith(otherConnection.environmentId, false); - expect(linkEnvironmentToCloudWithPreference).not.toHaveBeenCalled(); - }).pipe(Effect.provide(layerTest)); + expect(linkEnvironment).not.toHaveBeenCalled(); + }).pipe(withRelayClient); }); it.effect("reports a relay preference committed before environment configuration fails", () => { @@ -130,12 +109,13 @@ describe("liveActivityPreferences", () => { relayLinkCommitted: true, }); updateEnvironment.mockReturnValueOnce(Effect.succeed("unlinked")); - vi.mocked(linkEnvironmentToCloudWithPreference).mockReturnValueOnce(Effect.fail(failure)); + linkEnvironment.mockReturnValueOnce(Effect.fail(failure)); return Effect.gen(function* () { const exit = yield* Effect.exit( setLiveActivityUpdatesEnabled({ updateEnvironment, + linkEnvironment, enabled: true, previousEnabled: false, clerkToken: "clerk-token", @@ -156,7 +136,7 @@ describe("liveActivityPreferences", () => { expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenLastCalledWith({ liveActivitiesEnabled: false, }); - }).pipe(Effect.provide(layerTest)); + }).pipe(withRelayClient); }); it.effect("only creates missing links when the session can configure Connect", () => { @@ -165,14 +145,21 @@ describe("liveActivityPreferences", () => { ...connection, environmentId: "read-only" as EnvironmentId, }; + // Current mobile pairings authenticate with DPoP and carry no bearer token. + const dpopConnection: SavedRemoteConnection = { + ...connection, + bearerToken: null, + authenticationMethod: "dpop", + }; return Effect.gen(function* () { yield* setLiveActivityUpdatesEnabled({ updateEnvironment, + linkEnvironment, enabled: true, previousEnabled: false, clerkToken: "clerk-token", - connections: [readOnlyConnection, connection], + connections: [readOnlyConnection, dpopConnection], canUpdateEnvironment: (environmentId) => environmentId === connection.environmentId, canConfigureEnvironment: (environmentId) => environmentId === connection.environmentId, }); @@ -180,12 +167,11 @@ describe("liveActivityPreferences", () => { expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenCalledWith({ liveActivitiesEnabled: true, }); - expect(linkEnvironmentToCloudWithPreference).toHaveBeenCalledExactlyOnceWith({ + expect(linkEnvironment).toHaveBeenCalledExactlyOnceWith(connection.environmentId, { clerkToken: "clerk-token", - connection, liveActivitiesEnabled: true, }); - }).pipe(Effect.provide(layerTest)); + }).pipe(withRelayClient); }); it.effect("reports older environments whose preferences could not be updated", () => @@ -198,6 +184,7 @@ describe("liveActivityPreferences", () => { updateEnvironment.mockReturnValueOnce(Effect.succeed("unsupported")); const partial = yield* setLiveActivityUpdatesEnabled({ updateEnvironment, + linkEnvironment, enabled: false, previousEnabled: true, clerkToken: "clerk-token", @@ -206,8 +193,8 @@ describe("liveActivityPreferences", () => { canUpdateEnvironment: () => true, }); expect(partial).toBe(true); - expect(linkEnvironmentToCloudWithPreference).not.toHaveBeenCalled(); - }).pipe(Effect.provide(layerTest)), + expect(linkEnvironment).not.toHaveBeenCalled(); + }).pipe(withRelayClient), ); it.effect("checks current relay access after updating the device registration", () => { @@ -221,6 +208,7 @@ describe("liveActivityPreferences", () => { return Effect.gen(function* () { yield* setLiveActivityUpdatesEnabled({ updateEnvironment, + linkEnvironment, enabled: false, previousEnabled: true, clerkToken: "clerk-token", @@ -229,9 +217,9 @@ describe("liveActivityPreferences", () => { canUpdateEnvironment: () => canConfigureEnvironment, }); - expect(linkEnvironmentToCloudWithPreference).not.toHaveBeenCalled(); + expect(linkEnvironment).not.toHaveBeenCalled(); expect(updateEnvironment).not.toHaveBeenCalled(); expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenCalledTimes(1); - }).pipe(Effect.provide(layerTest)); + }).pipe(withRelayClient); }); }); diff --git a/apps/mobile/src/features/agent-awareness/liveActivityPreferences.ts b/apps/mobile/src/features/agent-awareness/liveActivityPreferences.ts index ac403600a7c5..6ff47c294a4c 100644 --- a/apps/mobile/src/features/agent-awareness/liveActivityPreferences.ts +++ b/apps/mobile/src/features/agent-awareness/liveActivityPreferences.ts @@ -4,10 +4,7 @@ import * as Schema from "effect/Schema"; import type { EnvironmentId } from "@t3tools/contracts"; import type { SavedRemoteConnection } from "../../lib/connection"; -import { - linkEnvironmentToCloudWithPreference, - type CloudEnvironmentLinkError, -} from "../cloud/linkEnvironment"; +import type { CloudEnvironmentLinkError } from "../cloud/linkEnvironment"; import { updateAgentAwarenessRegistrationPreferences } from "./remoteRegistration"; export class LiveActivityEnvironmentUpdateError extends Schema.TaggedError()( @@ -31,6 +28,10 @@ export const setLiveActivityUpdatesEnabled = Effect.fn("setLiveActivityUpdatesEn "updated" | "unlinked" | "unsupported" | "disconnected", CloudEnvironmentLinkError >; + readonly linkEnvironment: ( + environmentId: EnvironmentId, + input: { readonly clerkToken: string; readonly liveActivitiesEnabled: boolean }, + ) => Effect.Effect; readonly canUpdateEnvironment: (environmentId: EnvironmentId) => boolean; readonly canConfigureEnvironment: (environmentId: EnvironmentId) => boolean; }) { @@ -43,18 +44,12 @@ export const setLiveActivityUpdatesEnabled = Effect.fn("setLiveActivityUpdatesEn ? yield* input.updateEnvironment(connection.environmentId, enabled) : "unlinked"; if (result === "updated" || result === "disconnected") return result; - if ( - !enabled || - !clerkToken || - !connection.bearerToken || - !input.canConfigureEnvironment(connection.environmentId) - ) { + if (!enabled || !clerkToken || !input.canConfigureEnvironment(connection.environmentId)) { return result; } - yield* linkEnvironmentToCloudWithPreference({ + yield* input.linkEnvironment(connection.environmentId, { clerkToken, - connection, liveActivitiesEnabled: enabled, }); return "updated" as const; diff --git a/apps/mobile/src/features/cloud/linkEnvironment.test.ts b/apps/mobile/src/features/cloud/linkEnvironment.test.ts index 9e8bac68cfce..b4ee04d6d1a6 100644 --- a/apps/mobile/src/features/cloud/linkEnvironment.test.ts +++ b/apps/mobile/src/features/cloud/linkEnvironment.test.ts @@ -116,6 +116,43 @@ const withCloudServices = ( >, ) => effect.pipe(Effect.provide(layerCloudClient())); +const linkedSupervisor = Effect.gen(function* () { + const target = new PrimaryConnectionTarget({ + environmentId: savedConnection.environmentId, + label: savedConnection.environmentLabel, + httpBaseUrl: savedConnection.httpBaseUrl, + wsBaseUrl: savedConnection.wsBaseUrl, + }); + return EnvironmentSupervisor.EnvironmentSupervisor.of({ + target, + state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE), + session: yield* SubscriptionRef.make(Option.none()), + prepared: yield* SubscriptionRef.make( + Option.some({ + environmentId: savedConnection.environmentId, + label: savedConnection.environmentLabel, + httpBaseUrl: savedConnection.httpBaseUrl, + socketUrl: savedConnection.wsBaseUrl, + httpAuthorization: { _tag: "Bearer", token: "local-bearer" }, + target, + }), + ), + connect: Effect.void, + disconnect: Effect.void, + retryNow: Effect.void, + }); +}); + +const linkPreparedEnvironment = (liveActivitiesEnabled: boolean) => + Effect.flatMap(linkedSupervisor, (supervisor) => + withCloudServices( + linkEnvironmentToCloudWithPreference({ + clerkToken: "clerk-token", + liveActivitiesEnabled, + }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor)), + ), + ); + function validLinkProof() { return "signed-environment-link-jwt"; } @@ -199,13 +236,7 @@ describe("mobile cloud link environment client", () => { }); vi.stubGlobal("fetch", fetchMock); - const error = yield* withCloudServices( - linkEnvironmentToCloudWithPreference({ - clerkToken: "clerk-token", - connection: savedConnection, - liveActivitiesEnabled: true, - }), - ).pipe(Effect.flip); + const error = yield* linkPreparedEnvironment(true).pipe(Effect.flip); expect(error).toMatchObject({ _tag: "CloudEnvironmentLinkError", message: "Relay returned credentials for a different environment.", @@ -235,13 +266,7 @@ describe("mobile cloud link environment client", () => { }); vi.stubGlobal("fetch", fetchMock); - const error = yield* withCloudServices( - linkEnvironmentToCloudWithPreference({ - clerkToken: "clerk-token", - connection: savedConnection, - liveActivitiesEnabled: true, - }), - ).pipe(Effect.flip); + const error = yield* linkPreparedEnvironment(true).pipe(Effect.flip); expect(error).toMatchObject({ _tag: "CloudEnvironmentLinkError", message: "Relay returned credentials for a different endpoint provider.", @@ -272,13 +297,7 @@ describe("mobile cloud link environment client", () => { }); vi.stubGlobal("fetch", fetchMock); - yield* withCloudServices( - linkEnvironmentToCloudWithPreference({ - clerkToken: "clerk-token", - connection: savedConnection, - liveActivitiesEnabled: false, - }), - ); + yield* linkPreparedEnvironment(false); expect(bodies[1]).toMatchObject({ endpoint: { diff --git a/apps/mobile/src/features/cloud/linkEnvironment.ts b/apps/mobile/src/features/cloud/linkEnvironment.ts index 18e1757b4a76..6f32d5051ebc 100644 --- a/apps/mobile/src/features/cloud/linkEnvironment.ts +++ b/apps/mobile/src/features/cloud/linkEnvironment.ts @@ -2,7 +2,7 @@ import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as SubscriptionRef from "effect/SubscriptionRef"; import * as Schema from "effect/Schema"; -import { HttpClient, type HttpClientResponse } from "effect/http"; +import type { HttpClientResponse } from "effect/http"; import { EnvironmentCloudEndpointUnavailableError, EnvironmentHttpBadRequestError, @@ -19,13 +19,11 @@ import { import { EnvironmentSupervisor } from "@t3tools/client-runtime/connection"; import { findErrorTraceId } from "@t3tools/client-runtime/errors"; import { ManagedRelay, relayRequestFailureDetail } from "@t3tools/client-runtime/relay"; -import { makeEnvironmentHttpApiClient } from "@t3tools/client-runtime/rpc"; import { executeConnectedEnvironmentHttpRequest } from "@t3tools/client-runtime/state/environmentHttpAuth"; import { msg } from "gt-react-native"; import { m } from "../../i18n/messages"; -import type { SavedRemoteConnection } from "../../lib/connection"; import * as MobileStorage from "../../persistence/mobile-storage"; import { resolveCloudPublicConfig } from "./publicConfig"; @@ -163,16 +161,6 @@ function ensureLinkedEnvironmentMatches(input: { return Effect.void; } -interface LinkEnvironmentToCloudInput { - readonly connection: SavedRemoteConnection; - readonly clerkToken: string; -} - -type LinkEnvironmentToCloudRequirements = - | HttpClient.HttpClient - | ManagedRelay.ManagedRelayClient - | MobileStorage.MobileStorage; - const decodeRelayOkResponse = Schema.decodeUnknownEffect(RelayOkResponse); export const updateLinkedEnvironmentLiveActivityPreference = Effect.fn( @@ -227,17 +215,25 @@ export const updateLinkedEnvironmentLiveActivityPreference = Effect.fn( ); }); +// Linking can install the relay client and start a managed tunnel before it answers. +const CLOUD_LINK_REQUEST_TIMEOUT_MS = 60_000; + +/** Links the supervised environment, signing its requests with this device's own credential. */ export const linkEnvironmentToCloudWithPreference = Effect.fn( "linkEnvironment.linkEnvironmentToCloudWithPreference", -)(function* ( - input: LinkEnvironmentToCloudInput & { readonly liveActivitiesEnabled: boolean }, -): Effect.fn.Return { - if (!input.connection.bearerToken) { +)(function* (input: { readonly clerkToken: string; readonly liveActivitiesEnabled: boolean }) { + const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; + const prepared = yield* SubscriptionRef.get(supervisor.prepared); + if (Option.isNone(prepared)) { return yield* new CloudEnvironmentLinkError({ - message: m(msg("Only a locally paired bearer connection can be linked to the cloud.")), + message: m(msg("The environment is not connected.")), }); } - const localBearerToken = input.connection.bearerToken; + const { environmentId, httpBaseUrl, target } = prepared.value; + const wsBaseUrl = + target._tag === "PrimaryConnectionTarget" + ? target.wsBaseUrl + : httpBaseUrl.replace(/^http/, "ws"); const relayUrl = yield* requireRelayUrl(); const relayClient = yield* ManagedRelay.ManagedRelayClient; const storage = yield* MobileStorage.MobileStorage; @@ -263,28 +259,28 @@ export const linkEnvironmentToCloudWithPreference = Effect.fn( decodedRelayClientError(`${relayUrl}/v1/client/environment-link-challenges failed`), ), ); - const environmentClient = yield* makeEnvironmentHttpApiClient(input.connection.httpBaseUrl); - const proof = yield* environmentClient.connect - .linkProof({ - headers: { authorization: `Bearer ${localBearerToken}` }, - payload: { - challenge: challenge.challenge, - relayIssuer: relayUrl, - endpoint: { - httpBaseUrl: input.connection.httpBaseUrl, - wsBaseUrl: input.connection.wsBaseUrl, - providerKind: MANAGED_ENDPOINT_PROVIDER_KIND, + const proof = yield* executeConnectedEnvironmentHttpRequest({ + group: "connect", + method: "POST", + url: (urls) => urls.linkProof(), + timeoutMs: CLOUD_LINK_REQUEST_TIMEOUT_MS, + request: ({ client, headers }) => + client.linkProof({ + headers, + payload: { + challenge: challenge.challenge, + relayIssuer: relayUrl, + endpoint: { httpBaseUrl, wsBaseUrl, providerKind: MANAGED_ENDPOINT_PROVIDER_KIND }, + origin: endpointOrigin(httpBaseUrl), }, - origin: endpointOrigin(input.connection.httpBaseUrl), - }, - }) - .pipe( - Effect.mapError( - cloudEnvironmentLinkError(m(msg("Could not obtain environment link proof.")), (detail) => - m(msg("Could not obtain environment link proof: {detail}", { detail })), - ), + }), + }).pipe( + Effect.mapError( + cloudEnvironmentLinkError(m(msg("Could not obtain environment link proof.")), (detail) => + m(msg("Could not obtain environment link proof: {detail}", { detail })), ), - ); + ), + ); const link = yield* relayClient .linkEnvironment({ clerkToken: input.clerkToken, @@ -300,30 +296,35 @@ export const linkEnvironmentToCloudWithPreference = Effect.fn( Effect.mapError(decodedRelayClientError(`${relayUrl}/v1/client/environment-links failed`)), ); yield* ensureLinkedEnvironmentMatches({ - expectedEnvironmentId: input.connection.environmentId, + expectedEnvironmentId: environmentId, expectedProviderKind: MANAGED_ENDPOINT_PROVIDER_KIND, link, }); - yield* environmentClient.connect - .relayConfig({ - headers: { authorization: `Bearer ${localBearerToken}` }, - payload: { - relayUrl, - relayIssuer: link.relayIssuer, - cloudUserId: link.cloudUserId, - environmentCredential: link.environmentCredential, - cloudMintPublicKey: link.cloudMintPublicKey, - endpointRuntime: link.endpointRuntime, - }, - }) - .pipe( - Effect.mapError( - cloudEnvironmentLinkError( - m(msg("Could not configure environment relay access.")), - (detail) => m(msg("Could not configure environment relay access: {detail}", { detail })), - { relayLinkCommitted: true }, - ), + yield* executeConnectedEnvironmentHttpRequest({ + group: "connect", + method: "POST", + url: (urls) => urls.relayConfig(), + timeoutMs: CLOUD_LINK_REQUEST_TIMEOUT_MS, + request: ({ client, headers }) => + client.relayConfig({ + headers, + payload: { + relayUrl, + relayIssuer: link.relayIssuer, + cloudUserId: link.cloudUserId, + environmentCredential: link.environmentCredential, + cloudMintPublicKey: link.cloudMintPublicKey, + endpointRuntime: link.endpointRuntime, + }, + }), + }).pipe( + Effect.mapError( + cloudEnvironmentLinkError( + m(msg("Could not configure environment relay access.")), + (detail) => m(msg("Could not configure environment relay access: {detail}", { detail })), + { relayLinkCommitted: true }, ), - ); + ), + ); }); diff --git a/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx index 969ff8c55c8a..76b918d04196 100644 --- a/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx @@ -51,6 +51,7 @@ import { import { connectionAtomRuntime } from "../../connection/runtime"; import { CloudEnvironmentLinkError, + linkEnvironmentToCloudWithPreference, updateLinkedEnvironmentLiveActivityPreference, } from "../cloud/linkEnvironment"; import { refreshManagedRelayEnvironments } from "../cloud/managedRelayState"; @@ -70,9 +71,20 @@ const updateLiveActivityPreference = createEnvironmentCommand(connectionAtomRunt execute: updateLinkedEnvironmentLiveActivityPreference, }); +const linkLiveActivityEnvironment = createEnvironmentCommand(connectionAtomRuntime, { + label: "linkLiveActivityEnvironment", + execute: linkEnvironmentToCloudWithPreference, +}); + const isLiveActivityEnvironmentUpdateError = Schema.is(LiveActivityEnvironmentUpdateError); const isCloudEnvironmentLinkError = Schema.is(CloudEnvironmentLinkError); +function toCloudEnvironmentLinkError(cause: unknown, message: string) { + return isCloudEnvironmentLinkError(cause) + ? cause + : new CloudEnvironmentLinkError({ message, cause }); +} + const updateEnvironmentPreference = Effect.fn("updateEnvironmentPreference")(function* ( environmentId: EnvironmentId, enabled: boolean, @@ -81,15 +93,24 @@ const updateEnvironmentPreference = Effect.fn("updateEnvironmentPreference")(fun updateLiveActivityPreference.run(appAtomRegistry, { environmentId, input: enabled }), ); if (result._tag === "Success") return result.value; - const cause = squashAtomCommandFailure(result); - return yield* isCloudEnvironmentLinkError(cause) - ? cause - : new CloudEnvironmentLinkError({ - message: resolveMessage( - msg("Could not update the environment's Live Activity preference."), - ), - cause, - }); + return yield* toCloudEnvironmentLinkError( + squashAtomCommandFailure(result), + resolveMessage(msg("Could not update the environment's Live Activity preference.")), + ); +}); + +const linkEnvironmentWithPreference = Effect.fn("linkEnvironmentWithPreference")(function* ( + environmentId: EnvironmentId, + input: { readonly clerkToken: string; readonly liveActivitiesEnabled: boolean }, +) { + const result = yield* Effect.promise(() => + linkLiveActivityEnvironment.run(appAtomRegistry, { environmentId, input }), + ); + if (result._tag === "Success") return; + return yield* toCloudEnvironmentLinkError( + squashAtomCommandFailure(result), + resolveMessage(msg("Could not configure environment relay access.")), + ); }); /** @@ -361,6 +382,7 @@ function ConfiguredSettingsNotificationsRouteScreen() { runtime.runPromiseExit( setLiveActivityUpdatesEnabled({ updateEnvironment: updateEnvironmentPreference, + linkEnvironment: linkEnvironmentWithPreference, canConfigureEnvironment: (id) => canManageConnect(id, AuthRelayConfigureScope), canUpdateEnvironment: (id) => canManageConnect(id, AuthRelayWriteScope), enabled: true, @@ -456,6 +478,7 @@ function ConfiguredSettingsNotificationsRouteScreen() { runtime.runPromiseExit( setLiveActivityUpdatesEnabled({ updateEnvironment: updateEnvironmentPreference, + linkEnvironment: linkEnvironmentWithPreference, canConfigureEnvironment: (id) => canManageConnect(id, AuthRelayConfigureScope), canUpdateEnvironment: (id) => canManageConnect(id, AuthRelayWriteScope), enabled: false, diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 7d131361b276..a70e4f5cf32f 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -1853,7 +1853,6 @@ "c15d8570b0ac8ae5": "Die Umgebung meldete HTTP {status}.", "b87f2217123b4cbf": "Die Live-Aktivitätseinstellung der Umgebung konnte nicht geändert werden.", "2f18d65ea9f178da": "Die Live-Aktivitätseinstellung der Umgebung konnte nicht geändert werden: {detail}", - "024b0e4154ca9170": "Nur eine lokal gekoppelte Bearer-Verbindung kann mit der Cloud verknüpft werden.", "52c4bcf188d1af36": "Die ID des Mobilgeräts konnte nicht geladen werden.", "473457b89661c874": "Die ID des Mobilgeräts konnte nicht geladen werden: {detail}", "01da8c5b0a52e84a": "Der Nachweis für die Umgebungsverknüpfung konnte nicht abgerufen werden.", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index ccba74d1722f..d3a2fd155126 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -1853,7 +1853,6 @@ "c15d8570b0ac8ae5": "Environment returned HTTP {status}.", "b87f2217123b4cbf": "Could not update the environment's Live Activity preference.", "2f18d65ea9f178da": "Could not update the environment's Live Activity preference: {detail}", - "024b0e4154ca9170": "Only a locally paired bearer connection can be linked to the cloud.", "52c4bcf188d1af36": "Could not load the mobile device id.", "473457b89661c874": "Could not load the mobile device id: {detail}", "01da8c5b0a52e84a": "Could not obtain environment link proof.", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 98d3dfeca64c..14c932dd914e 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -1853,7 +1853,6 @@ "c15d8570b0ac8ae5": "El entorno devolvió HTTP {status}.", "b87f2217123b4cbf": "No se pudo actualizar la preferencia de actividades en directo del entorno.", "2f18d65ea9f178da": "No se pudo actualizar la preferencia de actividades en directo del entorno: {detail}", - "024b0e4154ca9170": "Solo se puede vincular a la nube una conexión bearer emparejada localmente.", "52c4bcf188d1af36": "No se pudo cargar el ID del dispositivo móvil.", "473457b89661c874": "No se pudo cargar el ID del dispositivo móvil: {detail}", "01da8c5b0a52e84a": "No se pudo obtener la prueba de vinculación del entorno.", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index a9d5c2f0ba64..a1f2478142fe 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -1853,7 +1853,6 @@ "c15d8570b0ac8ae5": "L’environnement a renvoyé HTTP {status}.", "b87f2217123b4cbf": "Impossible de mettre à jour la préférence d’activités en direct de l’environnement.", "2f18d65ea9f178da": "Impossible de mettre à jour la préférence d’activités en direct de l’environnement : {detail}", - "024b0e4154ca9170": "Seule une connexion bearer appairée localement peut être associée au cloud.", "52c4bcf188d1af36": "Impossible de charger l’ID de l’appareil mobile.", "473457b89661c874": "Impossible de charger l’ID de l’appareil mobile : {detail}", "01da8c5b0a52e84a": "Impossible d’obtenir la preuve d’association de l’environnement.", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index c495490af093..092c7fa5fed5 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -1853,7 +1853,6 @@ "c15d8570b0ac8ae5": "環境から HTTP {status} が返されました。", "b87f2217123b4cbf": "環境のライブアクティビティ設定を更新できませんでした。", "2f18d65ea9f178da": "環境のライブアクティビティ設定を更新できませんでした: {detail}", - "024b0e4154ca9170": "クラウドにリンクできるのは、ローカルでペアリングしたベアラー接続のみです。", "52c4bcf188d1af36": "モバイルデバイスの ID を読み込めませんでした。", "473457b89661c874": "モバイルデバイスの ID を読み込めませんでした: {detail}", "01da8c5b0a52e84a": "環境リンク証明を取得できませんでした。", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 4ce6ff4b1635..78f6b0b84623 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -1854,7 +1854,6 @@ "c15d8570b0ac8ae5": "환경에서 HTTP {status}를 반환했습니다.", "b87f2217123b4cbf": "환경의 실시간 현황 설정을 업데이트하지 못했습니다.", "2f18d65ea9f178da": "환경의 실시간 현황 설정을 업데이트하지 못했습니다: {detail}", - "024b0e4154ca9170": "로컬로 페어링된 bearer 연결만 클라우드에 연결할 수 있습니다.", "52c4bcf188d1af36": "모바일 기기 ID를 불러올 수 없습니다.", "473457b89661c874": "모바일 기기 ID를 불러올 수 없습니다: {detail}", "01da8c5b0a52e84a": "환경 연결 증명을 얻을 수 없습니다.", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 5a5b9e8697f6..e1403df7c7cf 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -1853,7 +1853,6 @@ "c15d8570b0ac8ae5": "O ambiente retornou HTTP {status}.", "b87f2217123b4cbf": "Não foi possível atualizar a preferência de Atividades ao Vivo do ambiente.", "2f18d65ea9f178da": "Não foi possível atualizar a preferência de Atividades ao Vivo do ambiente: {detail}", - "024b0e4154ca9170": "Só uma conexão bearer pareada localmente pode ser vinculada à nuvem.", "52c4bcf188d1af36": "Não foi possível carregar o ID do dispositivo móvel.", "473457b89661c874": "Não foi possível carregar o ID do dispositivo móvel: {detail}", "01da8c5b0a52e84a": "Não foi possível obter a prova de vínculo do ambiente.", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index 66ff10c0f254..f09f852aa073 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -1877,7 +1877,6 @@ "c15d8570b0ac8ae5": "Среда вернула HTTP {status}.", "b87f2217123b4cbf": "Не удалось обновить настройку «Эфир активности» для среды.", "2f18d65ea9f178da": "Не удалось обновить настройку «Эфир активности» для среды: {detail}", - "024b0e4154ca9170": "К облаку можно привязать только локально сопряжённое bearer-подключение.", "52c4bcf188d1af36": "Не удалось загрузить ID мобильного устройства.", "473457b89661c874": "Не удалось загрузить ID мобильного устройства: {detail}", "01da8c5b0a52e84a": "Не удалось получить подтверждение привязки окружения.", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index f1c659560e70..ed66184f9ff3 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -1853,7 +1853,6 @@ "c15d8570b0ac8ae5": "Miljön returnerade HTTP {status}.", "b87f2217123b4cbf": "Det gick inte att uppdatera miljöns inställning för liveaktiviteter.", "2f18d65ea9f178da": "Det gick inte att uppdatera miljöns inställning för liveaktiviteter: {detail}", - "024b0e4154ca9170": "Bara en lokalt parkopplad bearer-anslutning kan länkas till molnet.", "52c4bcf188d1af36": "Kunde inte läsa in den mobila enhetens id.", "473457b89661c874": "Kunde inte läsa in den mobila enhetens id: {detail}", "01da8c5b0a52e84a": "Kunde inte hämta bevis för miljölänken.", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 5d08213434d7..d9cab67e8b7f 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -1855,7 +1855,6 @@ "c15d8570b0ac8ae5": "环境返回了 HTTP {status}。", "b87f2217123b4cbf": "无法更新该环境的实时活动偏好设置。", "2f18d65ea9f178da": "无法更新该环境的实时活动偏好设置:{detail}", - "024b0e4154ca9170": "只有本地配对的 Bearer 连接才能关联到云端。", "52c4bcf188d1af36": "无法加载移动设备 ID。", "473457b89661c874": "无法加载移动设备 ID:{detail}", "01da8c5b0a52e84a": "无法获取环境关联凭证。", diff --git a/apps/server/src/cloud/CloudLink.lifecycle.test.ts b/apps/server/src/cloud/CloudLink.lifecycle.test.ts index cf02ae72cdee..a79ec07df51b 100644 --- a/apps/server/src/cloud/CloudLink.lifecycle.test.ts +++ b/apps/server/src/cloud/CloudLink.lifecycle.test.ts @@ -11,22 +11,11 @@ import * as PlatformError from "effect/PlatformError"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; -import { - HttpClient, - HttpClientResponse, - HttpServer, - HttpServerRequest, - type HttpClientRequest, -} from "effect/http"; +import { HttpClient, HttpClientResponse, HttpServer, type HttpClientRequest } from "effect/http"; import { RELAY_LINK_PROOF_TYP, signRelayJwt, verifyRelayJwt } from "@t3tools/shared/relayJwt"; import * as NetAddress from "effect/net/NetAddress"; -import { - AuthSessionId, - type AuthEnvironmentScope, - EnvironmentAuthenticatedPrincipal, - EnvironmentId, -} from "@t3tools/contracts"; +import { EnvironmentId } from "@t3tools/contracts"; import * as EnvironmentKeys from "./environmentKeys.ts"; import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; @@ -312,30 +301,16 @@ describe("releaseManagedTunnelOnShutdown", () => { }); yield* TestClock.setTime((relayNow + skewSeconds) * 1_000); const link = yield* CloudLink.CloudLink; - const proof = yield* link - .linkProof( - { - challenge, - relayIssuer, - endpoint: { - httpBaseUrl: "http://127.0.0.1:3773", - wsBaseUrl: "ws://127.0.0.1:3773", - providerKind: "manual", - }, - origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, - }, - HttpServerRequest.fromWeb( - new Request("http://127.0.0.1:3773/api/t3-connect/link-proof"), - ), - ) - .pipe( - Effect.provideService(EnvironmentAuthenticatedPrincipal, { - sessionId: AuthSessionId.make("test-session"), - subject: "test", - method: "bearer-access-token", - scopes: new Set(), - }), - ); + const proof = yield* link.linkProof({ + challenge, + relayIssuer, + endpoint: { + httpBaseUrl: "http://127.0.0.1:3773", + wsBaseUrl: "ws://127.0.0.1:3773", + providerKind: "manual", + }, + origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, + }); const environmentKeys = yield* EnvironmentKeys.getOrCreateEnvironmentKeyPairFromSecretStore(store); yield* TestClock.setTime(relayNow * 1_000); diff --git a/apps/server/src/cloud/CloudLink.ts b/apps/server/src/cloud/CloudLink.ts index 7793627cdd3d..da1ccb71c0cc 100644 --- a/apps/server/src/cloud/CloudLink.ts +++ b/apps/server/src/cloud/CloudLink.ts @@ -1,5 +1,4 @@ import { - EnvironmentAuthenticatedPrincipal, type EnvironmentCloudLinkStateResult, type EnvironmentCloudPreferencesRequest, type EnvironmentCloudRelayConfigResult, @@ -55,12 +54,7 @@ import type * as PlatformError from "effect/PlatformError"; import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; -import { - HttpClient, - HttpClientRequest, - HttpClientResponse, - type HttpServerRequest, -} from "effect/http"; +import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; import type * as HttpClientError from "effect/http/HttpClientError"; import * as HttpServer from "effect/http/HttpServer"; @@ -111,13 +105,11 @@ import { import { hasBoundedCloudProofLifetime, hasExactScope, - hasForwardedAuthorityHeaders, - isAllowedEndpointOrigin, + isLoopbackEndpointOrigin, isSupportedLinkProviderKind, linkProofScopes, managedEndpointRuntimeConfigsMatch, parseManagedEndpointLocalOrigin, - requestAbsoluteUrl, } from "./linkChecks.ts"; import { desktopUpdateRestartPending, pendingUpdateHandoffExists } from "./updateHandoff.ts"; @@ -416,21 +408,15 @@ type ManagedTunnelRegistration = export class CloudLink extends Context.Service< CloudLink, { - /** - * Signs the proof the relay asks for to link this environment. The request - * must reach this server directly. Desktop bootstrap sessions may use the - * WSL IP; all other sessions must use the loopback origin they name. - */ + /** Signs the proof the relay asks for to link this environment, for this server's own origin. */ readonly linkProof: ( request: RelayLinkProofRequest, - httpRequest: HttpServerRequest.HttpServerRequest, ) => Effect.Effect< RelayEnvironmentLinkProof, | CloudLinkOriginInvalidError | CloudLinkInternalError | EnvironmentAuth.ServerAuthInternalError - | ManagedLimits.ManagedPolicyRefusedError, - EnvironmentAuthenticatedPrincipal + | ManagedLimits.ManagedPolicyRefusedError >; readonly applyRelayConfig: ( payload: RelayEnvironmentConfigRequest, @@ -586,21 +572,28 @@ const make = Effect.gen(function* () { ), ); + // The tunnel must reach this server, so the signed origin is its own loopback address, never the caller's. + const serverLoopbackOrigin = Effect.gen(function* () { + const address = httpServer.address; + if (typeof address === "string" || !("port" in address)) { + return yield* new CloudLinkInternalError({ operation: "resolve-server-origin" }); + } + const { origin } = parseManagedEndpointLocalOrigin( + `http://${loopbackUrlHostForAddress(address)}:${address.port}`, + ); + if (!isLoopbackEndpointOrigin(origin)) { + return yield* new CloudLinkOriginInvalidError({ origin: "local" }); + } + return origin; + }); + const makeCloudLinkProof = Effect.fn("environment.cloud.makeLinkProof")(function* ( request: RelayLinkProofRequest, - requestUrl: string, - allowNonLoopbackRequestHost = false, ) { - if ( - !isSupportedLinkProviderKind(request) || - !isAllowedEndpointOrigin({ - origin: request.origin, - requestUrl, - allowNonLoopbackRequestHost, - }) - ) { + if (!isSupportedLinkProviderKind(request)) { return yield* new CloudLinkOriginInvalidError({ origin: "endpoint" }); } + const origin = yield* serverLoopbackOrigin; const now = yield* DateTime.now; const nowSeconds = Math.floor(now.epochMilliseconds / 1_000); // Borrow only the relay clock; the relay still verifies and consumes the challenge. @@ -623,7 +616,7 @@ const make = Effect.gen(function* () { environmentId: descriptor.environmentId, environmentPublicKey: normalizePemForSignedPayload(signingKey.publicKey), endpoint: request.endpoint, - origin: request.origin, + origin, scopes: linkProofScopes(request), } satisfies RelayEnvironmentLinkProofPayload; return yield* signingKey @@ -642,18 +635,8 @@ const make = Effect.gen(function* () { }); const linkProof = Effect.fn("environment.cloud.linkProof")( - function* (request: RelayLinkProofRequest, httpRequest: HttpServerRequest.HttpServerRequest) { - const requestUrl = requestAbsoluteUrl(httpRequest); - if (requestUrl === null || hasForwardedAuthorityHeaders(httpRequest)) { - return yield* new CloudLinkOriginInvalidError({ origin: "endpoint" }); - } - const principal = yield* EnvironmentAuthenticatedPrincipal; - // WSL desktop requests use the distro IP; only the server-issued bootstrap subject qualifies. - return yield* makeCloudLinkProof( - request, - requestUrl, - principal.subject === "desktop-bootstrap", - ); + function* (request: RelayLinkProofRequest) { + return yield* makeCloudLinkProof(request); }, Effect.catchIf(ServerSecretStore.isSecretStoreError, internalError("generate-link-proof")), ); @@ -877,19 +860,16 @@ const make = Effect.gen(function* () { }, schema: RelayEnvironmentLinkChallengeResponse, }); - const proof = yield* makeCloudLinkProof( - { - challenge: challenge.challenge, - relayIssuer: relayUrl, - endpoint: { - httpBaseUrl: parsedOrigin.httpBaseUrl, - wsBaseUrl: parsedOrigin.wsBaseUrl, - providerKind: managedTunnelsEnabled ? "cloudflare_tunnel" : "manual", - }, - origin: parsedOrigin.origin, + const proof = yield* makeCloudLinkProof({ + challenge: challenge.challenge, + relayIssuer: relayUrl, + endpoint: { + httpBaseUrl: parsedOrigin.httpBaseUrl, + wsBaseUrl: parsedOrigin.wsBaseUrl, + providerKind: managedTunnelsEnabled ? "cloudflare_tunnel" : "manual", }, - parsedOrigin.httpBaseUrl, - ); + origin: parsedOrigin.origin, + }); const link = yield* relayClientRequest({ url: `${relayUrl}/v1/client/environment-links`, token: token.accessToken, diff --git a/apps/server/src/cloud/http.test.ts b/apps/server/src/cloud/http.test.ts index 6c549c95bdb0..6cd0737e24de 100644 --- a/apps/server/src/cloud/http.test.ts +++ b/apps/server/src/cloud/http.test.ts @@ -174,16 +174,27 @@ const linkProofClient = Effect.gen(function* () { return { post, exchange, linkableHere }; }); -describe("link proof over a non-loopback desktop transport", () => { +describe("link proof over a non-loopback transport", () => { it.effect( - "signs a loopback tunnel origin after desktop bootstrap token exchange over a non-loopback host", + "signs this server's loopback origin for a remote client allowed to configure the relay", () => Effect.gen(function* () { const { post, exchange } = yield* linkProofClient; - const token = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN); - const response = yield* post("/api/connect/link-proof", proofRequest, { - authorization: `Bearer ${token}`, - }); + const admin = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN); + const paired = yield* post( + "/api/auth/pairing-token", + { scopes: ["relay:read", "relay:configure"] }, + { authorization: `Bearer ${admin}` }, + ); + expect(paired.status).toBe(200); + const { credential } = (yield* responseJson(paired)) as { credential: string }; + const token = yield* exchange(credential); + // The caller's origin and forwarding headers must not steer the tunnel elsewhere. + const response = yield* post( + "/api/connect/link-proof", + { ...proofRequest, origin: { localHttpHost: "172.24.162.233", localHttpPort: 5432 } }, + { authorization: `Bearer ${token}`, "x-forwarded-host": "evil.example.test" }, + ); expect(response.status).toBe(200); expect(response.headers.get("cache-control")).toBe("no-store"); const proof = (yield* responseJson(response)) as string; @@ -199,90 +210,28 @@ describe("link proof over a non-loopback desktop transport", () => { audience: proofRequest.relayIssuer, }); expect(verified).toMatchObject({ - origin: proofRequest.origin, + origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, endpoint: proofRequest.endpoint, challenge: proofRequest.challenge, }); }).pipe(Effect.provide(NodeCrypto.layerSignature)), ); - it.effect( - "does not pass desktop trust to a paired client or accept client-supplied provenance", - () => - Effect.gen(function* () { - const { post, exchange, linkableHere } = yield* linkProofClient; - const desktop = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN); - const paired = yield* post( - "/api/auth/pairing-token", - { - scopes: ["relay:read", "relay:configure"], - label: "desktop-bootstrap", - subject: "desktop-bootstrap", - }, - { authorization: `Bearer ${desktop}` }, - ); - expect(paired.status).toBe(200); - const { credential } = (yield* responseJson(paired)) as { credential: string }; - const token = yield* exchange(credential); - const headers = { authorization: `Bearer ${token}`, "x-desktop-bootstrap": "true" }; - const payload = { - ...proofRequest, - allowNonLoopbackRequestHost: true, - subject: "desktop-bootstrap", - }; - const rejected = yield* post("/api/connect/link-proof", payload, headers); - expect(rejected.status).toBe(400); - expect(yield* responseJson(rejected)).toMatchObject({ - message: "Invalid managed endpoint origin.", - }); - const loopback = yield* post( - "/api/connect/link-proof", - proofRequest, - headers, - LOOPBACK_ORIGIN, - ); - expect(loopback.status).toBe(200); - // Clients offer Turn on only to the desktop's own session; SSH forwards look like loopback. - expect(yield* linkableHere(desktop)).toBe(true); - expect(yield* linkableHere(token)).toBe(false); - expect(yield* linkableHere(token, LOOPBACK_ORIGIN)).toBe(false); - }), - ); - - it.effect.each([ - { - name: "non-loopback tunnel origin", - origin: { localHttpHost: "172.24.162.233", localHttpPort: 3773 }, - headers: {}, - }, - { - name: "mismatched port", - origin: { localHttpHost: "127.0.0.1", localHttpPort: 3774 }, - headers: {}, - }, - { - name: "forwarded host", - origin: proofRequest.origin, - headers: { "x-forwarded-host": "127.0.0.1:3773" }, - }, - { - name: "forwarded protocol", - origin: proofRequest.origin, - headers: { "x-forwarded-proto": "http" }, - }, - ])("rejects $name even for desktop bootstrap", ({ origin, headers }) => + it.effect("offers Turn on only to the desktop app's own session", () => Effect.gen(function* () { - const { post, exchange } = yield* linkProofClient; - const token = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN); - const response = yield* post( - "/api/connect/link-proof", - { ...proofRequest, origin }, - { ...headers, authorization: `Bearer ${token}` }, + const { post, exchange, linkableHere } = yield* linkProofClient; + const desktop = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN); + const paired = yield* post( + "/api/auth/pairing-token", + { scopes: ["relay:read", "relay:configure"], subject: "desktop-bootstrap" }, + { authorization: `Bearer ${desktop}` }, ); - expect(response.status).toBe(400); - expect(yield* responseJson(response)).toMatchObject({ - message: "Invalid managed endpoint origin.", - }); + const { credential } = (yield* responseJson(paired)) as { credential: string }; + const token = yield* exchange(credential); + // SSH port forwards look like loopback, so a loopback address alone does not count. + expect(yield* linkableHere(desktop)).toBe(true); + expect(yield* linkableHere(token)).toBe(false); + expect(yield* linkableHere(token, LOOPBACK_ORIGIN)).toBe(false); }), ); diff --git a/apps/server/src/cloud/http.ts b/apps/server/src/cloud/http.ts index 17e3956e4411..9d664512bb01 100644 --- a/apps/server/src/cloud/http.ts +++ b/apps/server/src/cloud/http.ts @@ -119,8 +119,7 @@ export const layer = HttpApiBuilder.group( .handle("linkProof", ({ payload }) => Effect.gen(function* () { yield* requireEnvironmentScope(AuthRelayConfigureScope); - const request = yield* HttpServerRequest.HttpServerRequest; - const proof = yield* toHttpError(cloudLink.linkProof(payload, request)); + const proof = yield* toHttpError(cloudLink.linkProof(payload)); yield* appendCloudCredentialResponseHeaders; return proof; }), diff --git a/apps/server/src/cloud/linkChecks.ts b/apps/server/src/cloud/linkChecks.ts index 607e2c08f8a5..64d59d9a107d 100644 --- a/apps/server/src/cloud/linkChecks.ts +++ b/apps/server/src/cloud/linkChecks.ts @@ -26,7 +26,7 @@ function firstForwardedHeaderValue(value: string | undefined): string | undefine return first && first.length > 0 ? first : undefined; } -export function requestAbsoluteUrl(request: HttpServerRequest.HttpServerRequest): string | null { +function requestAbsoluteUrl(request: HttpServerRequest.HttpServerRequest): string | null { try { return new URL(request.originalUrl).href; } catch { @@ -39,9 +39,7 @@ export function requestAbsoluteUrl(request: HttpServerRequest.HttpServerRequest) } } -export function hasForwardedAuthorityHeaders( - request: HttpServerRequest.HttpServerRequest, -): boolean { +function hasForwardedAuthorityHeaders(request: HttpServerRequest.HttpServerRequest): boolean { return ( firstForwardedHeaderValue(request.headers["x-forwarded-host"]) !== undefined || firstForwardedHeaderValue(request.headers["x-forwarded-proto"]) !== undefined @@ -95,21 +93,8 @@ export function canLinkHere( ); } -export function isAllowedEndpointOrigin(input: { - readonly origin: RelayManagedEndpointOrigin; - readonly requestUrl: string; - readonly allowNonLoopbackRequestHost?: boolean; -}): boolean { - if (!isLoopbackHostname(input.origin.localHttpHost)) { - return false; - } - - const url = new URL(input.requestUrl); - if (!input.allowNonLoopbackRequestHost && !isLoopbackHostname(url.hostname)) { - return false; - } - - return input.origin.localHttpPort === endpointRequestPort(url); +export function isLoopbackEndpointOrigin(origin: RelayManagedEndpointOrigin): boolean { + return isLoopbackHostname(origin.localHttpHost); } export function isSupportedLinkProviderKind(request: RelayLinkProofRequest): boolean { diff --git a/docs/internals/t3-connect.md b/docs/internals/t3-connect.md index 3e1ca5e280e4..ebb5c55e9647 100644 --- a/docs/internals/t3-connect.md +++ b/docs/internals/t3-connect.md @@ -82,9 +82,12 @@ devices working and lists them for review, including any that got in before. See `issueConnectCredential` in the [environment auth service](../../apps/server/src/auth/EnvironmentAuth.ts). -Managed tunnels expose only a validated loopback HTTP origin. Link proof checks -reject forwarded authority headers, and the relay resolves endpoints from its -own managed allocations rather than a caller-supplied URL. Health and mint +Managed tunnels expose only this server's own loopback HTTP origin. The link +proof signs that origin from the server's listening address and ignores the +caller's, so any client holding `relay:configure`, local or remote, can link +without being able to point the tunnel at another service on the host. The +relay resolves endpoints from its own managed allocations rather than a +caller-supplied URL. Health and mint requests must not follow redirects. These restrictions keep endpoint discovery from turning into arbitrary relay egress or exposing another service on the environment host. From 46781ab45a43adc6f5e3b56e1235f6be9c7c5fa6 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 19:31:19 -0800 Subject: [PATCH 2/5] fix(web): offer T3 Connect Turn on to any client that can configure it Turn on showed only in the desktop app, and the server reported a link as possible only for the desktop session. The server now answers from the session's relay:configure permission, and web follows that answer on every client. Older servers keep answering desktop-only, so mixed versions stay correct. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/cloud/http.test.ts | 24 +++++------ apps/server/src/cloud/http.ts | 6 +-- apps/server/src/cloud/linkChecks.ts | 42 ------------------- apps/web/src/cloud/t3ConnectState.ts | 7 +--- apps/web/src/cloud/useT3ConnectTurnOn.ts | 2 - .../settings/SavedEnvironmentRows.tsx | 9 ++-- docs/user/remote-access.md | 5 ++- 7 files changed, 20 insertions(+), 75 deletions(-) diff --git a/apps/server/src/cloud/http.test.ts b/apps/server/src/cloud/http.test.ts index 6cd0737e24de..1cc6a38b0c32 100644 --- a/apps/server/src/cloud/http.test.ts +++ b/apps/server/src/cloud/http.test.ts @@ -43,7 +43,6 @@ import * as ServerSettings from "../serverSettings.ts"; const DESKTOP_BOOTSTRAP_TOKEN = "test-desktop-bootstrap-token"; const NON_LOOPBACK_ORIGIN = "http://172.24.162.233:3773"; -const LOOPBACK_ORIGIN = "http://127.0.0.1:3773"; const proofRequest: RelayLinkProofRequest = { challenge: "test-challenge", relayIssuer: "https://relay.example.test", @@ -160,10 +159,10 @@ const linkProofClient = Effect.gen(function* () { const payload = (yield* responseJson(response)) as { access_token: string }; return payload.access_token; }); - const linkableHere = (token: string, origin = NON_LOOPBACK_ORIGIN) => + const linkableHere = (token: string) => Effect.promise(() => handler( - new Request(`${origin}/api/connect/link-state`, { + new Request(`${NON_LOOPBACK_ORIGIN}/api/connect/link-state`, { headers: { authorization: `Bearer ${token}` }, }), ), @@ -217,21 +216,18 @@ describe("link proof over a non-loopback transport", () => { }).pipe(Effect.provide(NodeCrypto.layerSignature)), ); - it.effect("offers Turn on only to the desktop app's own session", () => + it.effect("offers Turn on to any session allowed to configure the relay", () => Effect.gen(function* () { const { post, exchange, linkableHere } = yield* linkProofClient; const desktop = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN); - const paired = yield* post( - "/api/auth/pairing-token", - { scopes: ["relay:read", "relay:configure"], subject: "desktop-bootstrap" }, - { authorization: `Bearer ${desktop}` }, - ); - const { credential } = (yield* responseJson(paired)) as { credential: string }; - const token = yield* exchange(credential); - // SSH port forwards look like loopback, so a loopback address alone does not count. + const pair = (scopes: ReadonlyArray) => + post("/api/auth/pairing-token", { scopes }, { authorization: `Bearer ${desktop}` }).pipe( + Effect.flatMap(responseJson), + Effect.flatMap((paired) => exchange((paired as { credential: string }).credential)), + ); expect(yield* linkableHere(desktop)).toBe(true); - expect(yield* linkableHere(token)).toBe(false); - expect(yield* linkableHere(token, LOOPBACK_ORIGIN)).toBe(false); + expect(yield* linkableHere(yield* pair(["relay:read", "relay:configure"]))).toBe(true); + expect(yield* linkableHere(yield* pair(["relay:read", "relay:write"]))).toBe(false); }), ); diff --git a/apps/server/src/cloud/http.ts b/apps/server/src/cloud/http.ts index 9d664512bb01..6d146ef117ac 100644 --- a/apps/server/src/cloud/http.ts +++ b/apps/server/src/cloud/http.ts @@ -12,7 +12,7 @@ import { } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as HttpEffect from "effect/http/HttpEffect"; -import { HttpServerRequest, HttpServerResponse } from "effect/http"; +import { HttpServerResponse } from "effect/http"; import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; import { requireEnvironmentScope } from "../auth/http.ts"; @@ -20,7 +20,6 @@ import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; import * as ManagedLimits from "../policy/managedLimits.ts"; import * as CloudLink from "./CloudLink.ts"; import * as ConnectReachability from "./ConnectReachability.ts"; -import { canLinkHere } from "./linkChecks.ts"; import type { RelayRequestError } from "./relayResponse.ts"; import { traceRelayRequest } from "./traceRelayRequest.ts"; @@ -134,8 +133,7 @@ export const layer = HttpApiBuilder.group( Effect.gen(function* () { const principal = yield* requireEnvironmentScope(AuthRelayReadScope); const state = yield* toHttpError(cloudLink.linkState()); - const request = yield* HttpServerRequest.HttpServerRequest; - return { ...state, linkableHere: canLinkHere(request, principal.subject) }; + return { ...state, linkableHere: principal.scopes.has(AuthRelayConfigureScope) }; }), ) .handle("checkReachability", () => diff --git a/apps/server/src/cloud/linkChecks.ts b/apps/server/src/cloud/linkChecks.ts index 64d59d9a107d..6b8f19e60a69 100644 --- a/apps/server/src/cloud/linkChecks.ts +++ b/apps/server/src/cloud/linkChecks.ts @@ -4,7 +4,6 @@ import type { RelayManagedEndpointOrigin, RelayManagedEndpointRuntimeConfig, } from "@t3tools/contracts/relay"; -import type { HttpServerRequest } from "effect/http"; const CLOUD_PROOF_MAX_LIFETIME_SECONDS = 5 * 60; const CLOUD_PROOF_CLOCK_SKEW_SECONDS = 60; @@ -21,31 +20,6 @@ function isLoopbackHostname(hostname: string): boolean { return LOOPBACK_HOSTNAMES.has(normalizeHostname(hostname)); } -function firstForwardedHeaderValue(value: string | undefined): string | undefined { - const first = value?.split(",")[0]?.trim(); - return first && first.length > 0 ? first : undefined; -} - -function requestAbsoluteUrl(request: HttpServerRequest.HttpServerRequest): string | null { - try { - return new URL(request.originalUrl).href; - } catch { - const host = firstForwardedHeaderValue(request.headers.host) ?? "127.0.0.1"; - try { - return new URL(request.originalUrl, `http://${host}`).href; - } catch { - return null; - } - } -} - -function hasForwardedAuthorityHeaders(request: HttpServerRequest.HttpServerRequest): boolean { - return ( - firstForwardedHeaderValue(request.headers["x-forwarded-host"]) !== undefined || - firstForwardedHeaderValue(request.headers["x-forwarded-proto"]) !== undefined - ); -} - function endpointRequestPort(url: URL): number { return Number(url.port || (url.protocol === "https:" ? 443 : 80)); } @@ -77,22 +51,6 @@ export function parseManagedEndpointLocalOrigin(localOrigin: string) { }; } -/** - * Whether clients should offer to turn on T3 Connect over this session: only the desktop app's - * own bootstrap session, from any address (WSL answers on a distro IP), never through a proxy. - * A loopback address alone does not count, since SSH port forwards look like loopback too. - */ -export function canLinkHere( - request: HttpServerRequest.HttpServerRequest, - subject: string, -): boolean { - return ( - subject === "desktop-bootstrap" && - requestAbsoluteUrl(request) !== null && - !hasForwardedAuthorityHeaders(request) - ); -} - export function isLoopbackEndpointOrigin(origin: RelayManagedEndpointOrigin): boolean { return isLoopbackHostname(origin.localHttpHost); } diff --git a/apps/web/src/cloud/t3ConnectState.ts b/apps/web/src/cloud/t3ConnectState.ts index ae118214df47..97e4b804b556 100644 --- a/apps/web/src/cloud/t3ConnectState.ts +++ b/apps/web/src/cloud/t3ConnectState.ts @@ -69,7 +69,6 @@ export type T3ConnectTurnOn = * `linkableHere` is the environment's own answer for this session (its link state). */ export function resolveT3ConnectTurnOn(input: { - readonly desktopApp: boolean; readonly linkableHere: boolean; readonly cloudConfigured: boolean; readonly canReadRelay: boolean; @@ -77,11 +76,7 @@ export function resolveT3ConnectTurnOn(input: { readonly connectDenial: string | undefined; }): T3ConnectTurnOn { if (input.connectDenial !== undefined) return { kind: "policy", reason: input.connectDenial }; - return input.desktopApp && - input.linkableHere && - input.cloudConfigured && - input.canReadRelay && - input.canWriteRelay + return input.linkableHere && input.cloudConfigured && input.canReadRelay && input.canWriteRelay ? { kind: "here" } : { kind: "on-host" }; } diff --git a/apps/web/src/cloud/useT3ConnectTurnOn.ts b/apps/web/src/cloud/useT3ConnectTurnOn.ts index 18ec99df23f2..15acafae851b 100644 --- a/apps/web/src/cloud/useT3ConnectTurnOn.ts +++ b/apps/web/src/cloud/useT3ConnectTurnOn.ts @@ -4,7 +4,6 @@ import { managedCapabilityDenial, } from "@t3tools/contracts"; -import { isElectron } from "../env"; import { useManagedPolicy } from "../state/managedPolicy"; import { useEnvironmentCanConfigureRelay, useEnvironmentScope } from "../state/session"; import { useCloudLinkState } from "./cloudLinkState"; @@ -18,7 +17,6 @@ export function useT3ConnectTurnOn(environmentId: EnvironmentId | null) { const connectDenial = managedCapabilityDenial(useManagedPolicy(environmentId), "connect"); const linkState = useCloudLinkState(environmentId).data; return resolveT3ConnectTurnOn({ - desktopApp: isElectron, // Unknown while loading and on older servers, which keep today's switch in Settings. linkableHere: linkState?.linkableHere ?? true, cloudConfigured: hasCloudPublicConfig(), diff --git a/apps/web/src/components/settings/SavedEnvironmentRows.tsx b/apps/web/src/components/settings/SavedEnvironmentRows.tsx index 3cd6a39e2951..fe9dd58719c7 100644 --- a/apps/web/src/components/settings/SavedEnvironmentRows.tsx +++ b/apps/web/src/components/settings/SavedEnvironmentRows.tsx @@ -51,7 +51,6 @@ import { supportsDesktopAppUpdate, } from "~/versionSkew"; import { hasCloudPublicConfig } from "~/cloud/publicConfig"; -import { isElectron } from "~/env"; import { useT3ConnectTurnOn } from "~/cloud/useT3ConnectTurnOn"; import { useCloudLinkController } from "~/cloud/useCloudLinkController"; import { useManagedTunnelUsage } from "~/cloud/managedRelayState"; @@ -594,8 +593,8 @@ function ConfiguredCloudLinkRow({ messages, ); const turnOn = useT3ConnectTurnOn(environmentId); - // Turning on links from this desktop's own backend only; turning off works from anywhere. - const showSwitch = isElectron && (turnOn.kind !== "on-host" || managedTunnelActive); + // Turning on needs relay configuration permission; turning off works from anywhere. + const showSwitch = turnOn.kind !== "on-host" || managedTunnelActive; const [isUpdating, setIsUpdating] = useState(false); const [isUpdatingPreference, setIsUpdatingPreference] = useState(false); @@ -774,12 +773,12 @@ function ConfiguredCloudLinkRow({ "This environment was removed from T3 Connect. Run `t3 connect link` on the host to link it again.", )} /> - ) : isElectron ? ( + ) : ( - ) : null} + )} {signedOut && showSwitch ? null : ( Date: Wed, 18 Nov 2026 19:48:25 -0800 Subject: [PATCH 3/5] fix(mobile): link publish-only and turn on agent activity A phone's Live Activities toggle needs only agent activity, but mobile linked with a managed tunnel, which fails on hosts without the relay client and starts a tunnel from a phone. It also left publishing off, so a linked host never sent activity. Link publish-only and enable agent activity publishing after the relay config is saved. Co-Authored-By: Claude Opus 5.5 --- .../features/cloud/linkEnvironment.test.ts | 29 +++++++++++------- .../src/features/cloud/linkEnvironment.ts | 30 +++++++++++++++---- apps/mobile/src/i18n/translations/de.json | 2 ++ apps/mobile/src/i18n/translations/en.json | 2 ++ apps/mobile/src/i18n/translations/es.json | 2 ++ apps/mobile/src/i18n/translations/fr.json | 2 ++ apps/mobile/src/i18n/translations/ja.json | 2 ++ apps/mobile/src/i18n/translations/ko.json | 2 ++ apps/mobile/src/i18n/translations/pt-BR.json | 2 ++ apps/mobile/src/i18n/translations/ru.json | 2 ++ apps/mobile/src/i18n/translations/sv.json | 2 ++ apps/mobile/src/i18n/translations/zh.json | 2 ++ 12 files changed, 63 insertions(+), 16 deletions(-) diff --git a/apps/mobile/src/features/cloud/linkEnvironment.test.ts b/apps/mobile/src/features/cloud/linkEnvironment.test.ts index b4ee04d6d1a6..15f8d78ecf07 100644 --- a/apps/mobile/src/features/cloud/linkEnvironment.test.ts +++ b/apps/mobile/src/features/cloud/linkEnvironment.test.ts @@ -162,14 +162,11 @@ function validLinkResponse(environmentId = "env-1") { ok: true, environmentId, endpoint: { - httpBaseUrl: "https://managed.example.test/", - wsBaseUrl: "wss://managed.example.test/ws", - providerKind: "cloudflare_tunnel", - }, - endpointRuntime: { - providerKind: "cloudflare_tunnel", - connectorToken: "connector-token", + httpBaseUrl: "https://desktop.example.test/", + wsBaseUrl: "wss://desktop.example.test/ws", + providerKind: "manual", }, + endpointRuntime: null, relayIssuer: "https://relay.example.test", cloudUserId: "user_123", environmentCredential: "environment-credential", @@ -259,7 +256,7 @@ describe("mobile cloud link environment client", () => { ...validLinkResponse(), endpoint: { ...validLinkResponse().endpoint, - providerKind: "manual", + providerKind: "cloudflare_tunnel", }, }), ); @@ -291,6 +288,17 @@ describe("mobile cloud link environment client", () => { if (String(url).endsWith("/v1/client/environment-links")) { return Promise.resolve(Response.json(validLinkResponse())); } + if (String(url).endsWith("/api/connect/preferences")) { + return Promise.resolve( + Response.json({ + linked: true, + cloudUserId: "user_123", + relayUrl: "https://relay.example.test", + relayIssuer: "https://relay.example.test", + publishAgentActivity: true, + }), + ); + } return Promise.resolve( Response.json({ ok: true, endpointRuntimeStatus: { status: "configured" } }), ); @@ -303,7 +311,7 @@ describe("mobile cloud link environment client", () => { endpoint: { httpBaseUrl: "https://desktop.example.test/", wsBaseUrl: "wss://desktop.example.test/ws", - providerKind: "cloudflare_tunnel", + providerKind: "manual", }, origin: { localHttpHost: "127.0.0.1", @@ -314,12 +322,13 @@ describe("mobile cloud link environment client", () => { deviceId: "device-1", notificationsEnabled: true, liveActivitiesEnabled: false, - managedTunnelsEnabled: true, + managedTunnelsEnabled: false, }); expect(bodies[3]).toMatchObject({ cloudUserId: "user_123", environmentCredential: "environment-credential", }); + expect(bodies[4]).toEqual({ publishAgentActivity: true }); }), ); }); diff --git a/apps/mobile/src/features/cloud/linkEnvironment.ts b/apps/mobile/src/features/cloud/linkEnvironment.ts index 6f32d5051ebc..2c342e6f299a 100644 --- a/apps/mobile/src/features/cloud/linkEnvironment.ts +++ b/apps/mobile/src/features/cloud/linkEnvironment.ts @@ -52,8 +52,8 @@ const isEnvironmentCloudApiError = Schema.is( ]), ); -const MANAGED_ENDPOINT_PROVIDER_KIND = - "cloudflare_tunnel" satisfies RelayManagedEndpointProviderKind; +// Live Activities need only agent activity, so a phone never starts a tunnel on the host. +const PUBLISH_ONLY_PROVIDER_KIND = "manual" satisfies RelayManagedEndpointProviderKind; function cloudEnvironmentLinkError( message: string, @@ -251,7 +251,7 @@ export const linkEnvironmentToCloudWithPreference = Effect.fn( payload: { notificationsEnabled: true, liveActivitiesEnabled, - managedTunnelsEnabled: true, + managedTunnelsEnabled: false, }, }) .pipe( @@ -270,7 +270,7 @@ export const linkEnvironmentToCloudWithPreference = Effect.fn( payload: { challenge: challenge.challenge, relayIssuer: relayUrl, - endpoint: { httpBaseUrl, wsBaseUrl, providerKind: MANAGED_ENDPOINT_PROVIDER_KIND }, + endpoint: { httpBaseUrl, wsBaseUrl, providerKind: PUBLISH_ONLY_PROVIDER_KIND }, origin: endpointOrigin(httpBaseUrl), }, }), @@ -289,7 +289,7 @@ export const linkEnvironmentToCloudWithPreference = Effect.fn( proof, notificationsEnabled: true, liveActivitiesEnabled, - managedTunnelsEnabled: true, + managedTunnelsEnabled: false, }, }) .pipe( @@ -297,7 +297,7 @@ export const linkEnvironmentToCloudWithPreference = Effect.fn( ); yield* ensureLinkedEnvironmentMatches({ expectedEnvironmentId: environmentId, - expectedProviderKind: MANAGED_ENDPOINT_PROVIDER_KIND, + expectedProviderKind: PUBLISH_ONLY_PROVIDER_KIND, link, }); @@ -327,4 +327,22 @@ export const linkEnvironmentToCloudWithPreference = Effect.fn( ), ), ); + + // Without publishing, the link exists but the host never sends the activity Live Activities show. + yield* executeConnectedEnvironmentHttpRequest({ + group: "connect", + method: "POST", + url: (urls) => urls.preferences(), + timeoutMs: CLOUD_LINK_REQUEST_TIMEOUT_MS, + request: ({ client, headers }) => + client.preferences({ headers, payload: { publishAgentActivity: true } }), + }).pipe( + Effect.mapError( + cloudEnvironmentLinkError( + m(msg("Could not turn on agent activity publishing.")), + (detail) => m(msg("Could not turn on agent activity publishing: {detail}", { detail })), + { relayLinkCommitted: true }, + ), + ), + ); }); diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index a70e4f5cf32f..e75c87010d88 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -1859,6 +1859,8 @@ "20732c0363a295a8": "Verknüpfungsnachweis der Umgebung konnte nicht abgerufen werden: {detail}", "78bf018d20589722": "Der Relay-Zugriff der Umgebung konnte nicht konfiguriert werden.", "a5e3ff0d1a60b766": "Relay-Zugriff der Umgebung konnte nicht konfiguriert werden: {detail}", + "013df8bdb9ca9096": "Die Veröffentlichung der Agentenaktivität konnte nicht aktiviert werden.", + "7247ede5160a0154": "Die Veröffentlichung der Agentenaktivität konnte nicht aktiviert werden: {detail}", "7d508fe978cb0f3b": "Aus", "3ae222ec888dd171": "Trace-ID:", "be00d572b18076d8": "Lange drücken, um von diesem Gerät zu entfernen", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index d3a2fd155126..39a8cd4d9401 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -1859,6 +1859,8 @@ "20732c0363a295a8": "Could not obtain environment link proof: {detail}", "78bf018d20589722": "Could not configure environment relay access.", "a5e3ff0d1a60b766": "Could not configure environment relay access: {detail}", + "013df8bdb9ca9096": "Could not turn on agent activity publishing.", + "7247ede5160a0154": "Could not turn on agent activity publishing: {detail}", "7d508fe978cb0f3b": "Off", "3ae222ec888dd171": "Trace ID:", "be00d572b18076d8": "Long press to remove from this device", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 14c932dd914e..a10de0b05a3e 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -1859,6 +1859,8 @@ "20732c0363a295a8": "No se pudo obtener la prueba de vinculación del entorno: {detail}", "78bf018d20589722": "No se pudo configurar el acceso del entorno al relay.", "a5e3ff0d1a60b766": "No se pudo configurar el acceso del entorno al relay: {detail}", + "013df8bdb9ca9096": "No se pudo activar la publicación de la actividad del agente.", + "7247ede5160a0154": "No se pudo activar la publicación de la actividad del agente: {detail}", "7d508fe978cb0f3b": "Apagado", "3ae222ec888dd171": "ID de traza:", "be00d572b18076d8": "Mantén pulsado para quitarlo de este dispositivo", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index a1f2478142fe..32698d32a911 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -1859,6 +1859,8 @@ "20732c0363a295a8": "Impossible d’obtenir la preuve d’association de l’environnement : {detail}", "78bf018d20589722": "Impossible de configurer l’accès relais de l’environnement.", "a5e3ff0d1a60b766": "Impossible de configurer l’accès au relais de l’environnement : {detail}", + "013df8bdb9ca9096": "Impossible d’activer la publication de l’activité de l’agent.", + "7247ede5160a0154": "Impossible d’activer la publication de l’activité de l’agent : {detail}", "7d508fe978cb0f3b": "Éteint", "3ae222ec888dd171": "ID de trace :", "be00d572b18076d8": "Appuyez longuement pour retirer de cet appareil", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 092c7fa5fed5..dbd171818bcd 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -1859,6 +1859,8 @@ "20732c0363a295a8": "環境のリンク証明を取得できませんでした: {detail}", "78bf018d20589722": "環境のリレーアクセスを構成できませんでした。", "a5e3ff0d1a60b766": "環境のリレーアクセスを構成できませんでした: {detail}", + "013df8bdb9ca9096": "エージェントのアクティビティの公開をオンにできませんでした。", + "7247ede5160a0154": "エージェントのアクティビティの公開をオンにできませんでした: {detail}", "7d508fe978cb0f3b": "オフ", "3ae222ec888dd171": "トレース ID:", "be00d572b18076d8": "長押しでこのデバイスから削除", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 78f6b0b84623..b84f6efb6800 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -1860,6 +1860,8 @@ "20732c0363a295a8": "환경 연결 증명을 가져올 수 없습니다: {detail}", "78bf018d20589722": "환경 릴레이 액세스를 구성할 수 없습니다.", "a5e3ff0d1a60b766": "환경 릴레이 액세스를 구성할 수 없습니다: {detail}", + "013df8bdb9ca9096": "에이전트 활동 게시를 켤 수 없습니다.", + "7247ede5160a0154": "에이전트 활동 게시를 켤 수 없습니다: {detail}", "7d508fe978cb0f3b": "꺼짐", "3ae222ec888dd171": "추적 ID:", "be00d572b18076d8": "길게 눌러 이 기기에서 제거", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index e1403df7c7cf..e806ac68f371 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -1859,6 +1859,8 @@ "20732c0363a295a8": "Não foi possível obter a prova de vínculo do ambiente: {detail}", "78bf018d20589722": "Não foi possível configurar o acesso do ambiente ao relay.", "a5e3ff0d1a60b766": "Não foi possível configurar o acesso do ambiente ao relay: {detail}", + "013df8bdb9ca9096": "Não foi possível ativar a publicação da atividade do agente.", + "7247ede5160a0154": "Não foi possível ativar a publicação da atividade do agente: {detail}", "7d508fe978cb0f3b": "Desligado", "3ae222ec888dd171": "ID do trace:", "be00d572b18076d8": "Mantenha pressionado para remover deste dispositivo", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index f09f852aa073..345781ca01d5 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -1883,6 +1883,8 @@ "20732c0363a295a8": "Не удалось получить подтверждение привязки окружения: {detail}", "78bf018d20589722": "Не удалось настроить доступ окружения к relay.", "a5e3ff0d1a60b766": "Не удалось настроить доступ окружения к relay: {detail}", + "013df8bdb9ca9096": "Не удалось включить публикацию активности агента.", + "7247ede5160a0154": "Не удалось включить публикацию активности агента: {detail}", "7d508fe978cb0f3b": "Выкл.", "3ae222ec888dd171": "ID трассировки:", "be00d572b18076d8": "Нажмите и удерживайте, чтобы удалить с этого устройства", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index ed66184f9ff3..6f2ccdee856b 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -1859,6 +1859,8 @@ "20732c0363a295a8": "Kunde inte hämta miljöns länkbevis: {detail}", "78bf018d20589722": "Kunde inte konfigurera miljöns reläåtkomst.", "a5e3ff0d1a60b766": "Kunde inte konfigurera miljöns reläåtkomst: {detail}", + "013df8bdb9ca9096": "Det gick inte att aktivera publicering av agentaktivitet.", + "7247ede5160a0154": "Det gick inte att aktivera publicering av agentaktivitet: {detail}", "7d508fe978cb0f3b": "Av", "3ae222ec888dd171": "Spårnings-id:", "be00d572b18076d8": "Tryck länge för att ta bort från den här enheten", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index d9cab67e8b7f..e01c9bf7289f 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -1861,6 +1861,8 @@ "20732c0363a295a8": "无法获取环境关联证明:{detail}", "78bf018d20589722": "无法配置环境中继访问。", "a5e3ff0d1a60b766": "无法配置环境的中继访问:{detail}", + "013df8bdb9ca9096": "无法开启代理活动发布。", + "7247ede5160a0154": "无法开启代理活动发布:{detail}", "7d508fe978cb0f3b": "关闭", "3ae222ec888dd171": "追踪 ID:", "be00d572b18076d8": "长按以从此设备移除", From 3e9276f6384f765854a71e9fe854bf0c766e186a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 20:49:10 -0800 Subject: [PATCH 4/5] fix(connect): finish Live Activity links that retry or lack relay write Publishing agent activity ran after the relay link committed, so a failed publish step was skipped on retry because the link already existed. Turn publishing on first; it is a host-local setting. Linking also needs relay:write, so mobile, web Turn on, and the server's linkableHere require it alongside relay:configure, and the relink docs name every permission. Co-Authored-By: Claude Opus 5.5 --- .../features/cloud/linkEnvironment.test.ts | 38 +++++++++++-------- .../src/features/cloud/linkEnvironment.ts | 33 ++++++++-------- .../SettingsNotificationsRouteScreen.tsx | 8 +++- apps/server/src/cloud/http.test.ts | 4 +- apps/server/src/cloud/http.ts | 6 ++- apps/web/src/cloud/useT3ConnectTurnOn.ts | 4 +- docs/user/remote-access.md | 8 ++-- 7 files changed, 60 insertions(+), 41 deletions(-) diff --git a/apps/mobile/src/features/cloud/linkEnvironment.test.ts b/apps/mobile/src/features/cloud/linkEnvironment.test.ts index 15f8d78ecf07..5d5e62311ec1 100644 --- a/apps/mobile/src/features/cloud/linkEnvironment.test.ts +++ b/apps/mobile/src/features/cloud/linkEnvironment.test.ts @@ -174,6 +174,16 @@ function validLinkResponse(environmentId = "env-1") { }; } +function linkStateResponse() { + return { + linked: false, + cloudUserId: null, + relayUrl: null, + relayIssuer: null, + publishAgentActivity: true, + }; +} + function validLinkChallengeResponse() { return { challenge: "link-challenge", @@ -223,6 +233,9 @@ describe("mobile cloud link environment client", () => { () => Effect.gen(function* () { const fetchMock = vi.fn((url: string | URL) => { + if (String(url).endsWith("/api/connect/preferences")) { + return Promise.resolve(Response.json(linkStateResponse())); + } if (String(url).endsWith("/v1/client/environment-link-challenges")) { return Promise.resolve(Response.json(validLinkChallengeResponse())); } @@ -238,13 +251,16 @@ describe("mobile cloud link environment client", () => { _tag: "CloudEnvironmentLinkError", message: "Relay returned credentials for a different environment.", }); - expect(fetchMock).toHaveBeenCalledTimes(3); + expect(fetchMock).toHaveBeenCalledTimes(4); }), ); it.effect("rejects relay link credentials for a different managed endpoint provider", () => Effect.gen(function* () { const fetchMock = vi.fn((url: string | URL) => { + if (String(url).endsWith("/api/connect/preferences")) { + return Promise.resolve(Response.json(linkStateResponse())); + } if (String(url).endsWith("/v1/client/environment-link-challenges")) { return Promise.resolve(Response.json(validLinkChallengeResponse())); } @@ -268,7 +284,7 @@ describe("mobile cloud link environment client", () => { _tag: "CloudEnvironmentLinkError", message: "Relay returned credentials for a different endpoint provider.", }); - expect(fetchMock).toHaveBeenCalledTimes(3); + expect(fetchMock).toHaveBeenCalledTimes(4); }), ); @@ -289,15 +305,7 @@ describe("mobile cloud link environment client", () => { return Promise.resolve(Response.json(validLinkResponse())); } if (String(url).endsWith("/api/connect/preferences")) { - return Promise.resolve( - Response.json({ - linked: true, - cloudUserId: "user_123", - relayUrl: "https://relay.example.test", - relayIssuer: "https://relay.example.test", - publishAgentActivity: true, - }), - ); + return Promise.resolve(Response.json(linkStateResponse())); } return Promise.resolve( Response.json({ ok: true, endpointRuntimeStatus: { status: "configured" } }), @@ -307,7 +315,8 @@ describe("mobile cloud link environment client", () => { yield* linkPreparedEnvironment(false); - expect(bodies[1]).toMatchObject({ + expect(bodies[0]).toEqual({ publishAgentActivity: true }); + expect(bodies[2]).toMatchObject({ endpoint: { httpBaseUrl: "https://desktop.example.test/", wsBaseUrl: "wss://desktop.example.test/ws", @@ -318,17 +327,16 @@ describe("mobile cloud link environment client", () => { localHttpPort: 443, }, }); - expect(bodies[2]).toMatchObject({ + expect(bodies[3]).toMatchObject({ deviceId: "device-1", notificationsEnabled: true, liveActivitiesEnabled: false, managedTunnelsEnabled: false, }); - expect(bodies[3]).toMatchObject({ + expect(bodies[4]).toMatchObject({ cloudUserId: "user_123", environmentCredential: "environment-credential", }); - expect(bodies[4]).toEqual({ publishAgentActivity: true }); }), ); }); diff --git a/apps/mobile/src/features/cloud/linkEnvironment.ts b/apps/mobile/src/features/cloud/linkEnvironment.ts index 2c342e6f299a..4b88fcbb0aa7 100644 --- a/apps/mobile/src/features/cloud/linkEnvironment.ts +++ b/apps/mobile/src/features/cloud/linkEnvironment.ts @@ -235,6 +235,21 @@ export const linkEnvironmentToCloudWithPreference = Effect.fn( ? target.wsBaseUrl : httpBaseUrl.replace(/^http/, "ws"); const relayUrl = yield* requireRelayUrl(); + // Publishing is a host-local setting, so enable it before committing a link a retry would skip. + yield* executeConnectedEnvironmentHttpRequest({ + group: "connect", + method: "POST", + url: (urls) => urls.preferences(), + timeoutMs: CLOUD_LINK_REQUEST_TIMEOUT_MS, + request: ({ client, headers }) => + client.preferences({ headers, payload: { publishAgentActivity: true } }), + }).pipe( + Effect.mapError( + cloudEnvironmentLinkError(m(msg("Could not turn on agent activity publishing.")), (detail) => + m(msg("Could not turn on agent activity publishing: {detail}", { detail })), + ), + ), + ); const relayClient = yield* ManagedRelay.ManagedRelayClient; const storage = yield* MobileStorage.MobileStorage; const deviceId = yield* storage.loadOrCreateAgentAwarenessDeviceId.pipe( @@ -327,22 +342,4 @@ export const linkEnvironmentToCloudWithPreference = Effect.fn( ), ), ); - - // Without publishing, the link exists but the host never sends the activity Live Activities show. - yield* executeConnectedEnvironmentHttpRequest({ - group: "connect", - method: "POST", - url: (urls) => urls.preferences(), - timeoutMs: CLOUD_LINK_REQUEST_TIMEOUT_MS, - request: ({ client, headers }) => - client.preferences({ headers, payload: { publishAgentActivity: true } }), - }).pipe( - Effect.mapError( - cloudEnvironmentLinkError( - m(msg("Could not turn on agent activity publishing.")), - (detail) => m(msg("Could not turn on agent activity publishing: {detail}", { detail })), - { relayLinkCommitted: true }, - ), - ), - ); }); diff --git a/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx index 76b918d04196..b7524355f2e9 100644 --- a/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx @@ -383,7 +383,9 @@ function ConfiguredSettingsNotificationsRouteScreen() { setLiveActivityUpdatesEnabled({ updateEnvironment: updateEnvironmentPreference, linkEnvironment: linkEnvironmentWithPreference, - canConfigureEnvironment: (id) => canManageConnect(id, AuthRelayConfigureScope), + canConfigureEnvironment: (id) => + canManageConnect(id, AuthRelayConfigureScope) && + canManageConnect(id, AuthRelayWriteScope), canUpdateEnvironment: (id) => canManageConnect(id, AuthRelayWriteScope), enabled: true, previousEnabled: liveActivitiesPreferenceEnabled, @@ -479,7 +481,9 @@ function ConfiguredSettingsNotificationsRouteScreen() { setLiveActivityUpdatesEnabled({ updateEnvironment: updateEnvironmentPreference, linkEnvironment: linkEnvironmentWithPreference, - canConfigureEnvironment: (id) => canManageConnect(id, AuthRelayConfigureScope), + canConfigureEnvironment: (id) => + canManageConnect(id, AuthRelayConfigureScope) && + canManageConnect(id, AuthRelayWriteScope), canUpdateEnvironment: (id) => canManageConnect(id, AuthRelayWriteScope), enabled: false, previousEnabled: liveActivitiesPreferenceEnabled, diff --git a/apps/server/src/cloud/http.test.ts b/apps/server/src/cloud/http.test.ts index 1cc6a38b0c32..5115a27e6301 100644 --- a/apps/server/src/cloud/http.test.ts +++ b/apps/server/src/cloud/http.test.ts @@ -226,8 +226,10 @@ describe("link proof over a non-loopback transport", () => { Effect.flatMap((paired) => exchange((paired as { credential: string }).credential)), ); expect(yield* linkableHere(desktop)).toBe(true); - expect(yield* linkableHere(yield* pair(["relay:read", "relay:configure"]))).toBe(true); + const remote = yield* pair(["relay:read", "relay:write", "relay:configure"]); + expect(yield* linkableHere(remote)).toBe(true); expect(yield* linkableHere(yield* pair(["relay:read", "relay:write"]))).toBe(false); + expect(yield* linkableHere(yield* pair(["relay:read", "relay:configure"]))).toBe(false); }), ); diff --git a/apps/server/src/cloud/http.ts b/apps/server/src/cloud/http.ts index 6d146ef117ac..84491a274398 100644 --- a/apps/server/src/cloud/http.ts +++ b/apps/server/src/cloud/http.ts @@ -133,7 +133,11 @@ export const layer = HttpApiBuilder.group( Effect.gen(function* () { const principal = yield* requireEnvironmentScope(AuthRelayReadScope); const state = yield* toHttpError(cloudLink.linkState()); - return { ...state, linkableHere: principal.scopes.has(AuthRelayConfigureScope) }; + // Linking also writes relay preferences, so configure alone cannot finish it. + const linkableHere = + principal.scopes.has(AuthRelayConfigureScope) && + principal.scopes.has(AuthRelayWriteScope); + return { ...state, linkableHere }; }), ) .handle("checkReachability", () => diff --git a/apps/web/src/cloud/useT3ConnectTurnOn.ts b/apps/web/src/cloud/useT3ConnectTurnOn.ts index 15acafae851b..61bb205dc958 100644 --- a/apps/web/src/cloud/useT3ConnectTurnOn.ts +++ b/apps/web/src/cloud/useT3ConnectTurnOn.ts @@ -1,5 +1,6 @@ import { AuthRelayReadScope, + AuthRelayWriteScope, type EnvironmentId, managedCapabilityDenial, } from "@t3tools/contracts"; @@ -13,6 +14,7 @@ import { resolveT3ConnectTurnOn } from "./t3ConnectState"; /** Whether this client can turn on T3 Connect for `environmentId`, and if not, why. */ export function useT3ConnectTurnOn(environmentId: EnvironmentId | null) { const canReadRelay = useEnvironmentScope(environmentId, AuthRelayReadScope); + const canWriteRelay = useEnvironmentScope(environmentId, AuthRelayWriteScope); const canConfigureRelay = useEnvironmentCanConfigureRelay(environmentId); const connectDenial = managedCapabilityDenial(useManagedPolicy(environmentId), "connect"); const linkState = useCloudLinkState(environmentId).data; @@ -21,7 +23,7 @@ export function useT3ConnectTurnOn(environmentId: EnvironmentId | null) { linkableHere: linkState?.linkableHere ?? true, cloudConfigured: hasCloudPublicConfig(), canReadRelay, - canWriteRelay: canConfigureRelay, + canWriteRelay: canWriteRelay && canConfigureRelay, connectDenial, }); } diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index 46e95444f277..eb67e563696e 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -495,9 +495,11 @@ page, or **Settings → T3 Connect** on mobile, and choose **Deregister**. This revokes its cloud access and frees its host space even when the environment is offline or has been wiped. When T3 Connect rejects a host's link, the host shows that it was removed from T3 Connect. To link it again, turn on -**T3 Connect** in **Settings → Sharing & access** from any client paired with -`relay:configure`, or run `t3 connect link` on the host and then restart T3 Code -there. A +**T3 Connect** in **Settings → Sharing & access** on web or desktop, or turn on +**Live Activity Updates** in **Settings → Notifications** on mobile. Either needs a +client paired with `relay:read`, `relay:write`, and `relay:configure`, which new +desktop and startup pairings include. You can also run `t3 connect link` on the +host and then restart T3 Code there. A command-line host that released its tunnel when it last stopped may link itself again on its next start; run `t3 connect unlink` on that host to keep it off. Removing an environment from a device's connection settings only forgets it on From fb23f8b7f76dfc38f672be2a6b3612aabc95d596 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Nov 2026 21:08:48 -0800 Subject: [PATCH 5/5] docs(connect): clarify which pairings can relink and the mobile toggle Co-Authored-By: Claude Opus 5.5 --- docs/user/remote-access.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index eb67e563696e..7a6731d9ebe1 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -496,10 +496,12 @@ revokes its cloud access and frees its host space even when the environment is offline or has been wiped. When T3 Connect rejects a host's link, the host shows that it was removed from T3 Connect. To link it again, turn on **T3 Connect** in **Settings → Sharing & access** on web or desktop, or turn on -**Live Activity Updates** in **Settings → Notifications** on mobile. Either needs a -client paired with `relay:read`, `relay:write`, and `relay:configure`, which new -desktop and startup pairings include. You can also run `t3 connect link` on the -host and then restart T3 Code there. A +**Live Activity Updates** in **Settings → Notifications** on mobile; if it is +already on, turn it off and on again. Either needs a client paired with +`relay:read`, `relay:write`, and `relay:configure`. The desktop app's own session +and the startup pairing link include all three; a pairing link created in +**Settings → Sharing & access** needs `relay:configure` selected. You can also +run `t3 connect link` on the host and then restart T3 Code there. A command-line host that released its tunnel when it last stopped may link itself again on its next start; run `t3 connect unlink` on that host to keep it off. Removing an environment from a device's connection settings only forgets it on