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..5d5e62311ec1 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"; } @@ -125,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", @@ -140,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", @@ -189,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())); } @@ -199,24 +246,21 @@ 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.", }); - 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())); } @@ -228,25 +272,19 @@ describe("mobile cloud link environment client", () => { ...validLinkResponse(), endpoint: { ...validLinkResponse().endpoint, - providerKind: "manual", + providerKind: "cloudflare_tunnel", }, }), ); }); 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.", }); - expect(fetchMock).toHaveBeenCalledTimes(3); + expect(fetchMock).toHaveBeenCalledTimes(4); }), ); @@ -266,38 +304,36 @@ 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(linkStateResponse())); + } return Promise.resolve( Response.json({ ok: true, endpointRuntimeStatus: { status: "configured" } }), ); }); vi.stubGlobal("fetch", fetchMock); - yield* withCloudServices( - linkEnvironmentToCloudWithPreference({ - clerkToken: "clerk-token", - connection: savedConnection, - liveActivitiesEnabled: false, - }), - ); + 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", - providerKind: "cloudflare_tunnel", + providerKind: "manual", }, origin: { localHttpHost: "127.0.0.1", localHttpPort: 443, }, }); - expect(bodies[2]).toMatchObject({ + expect(bodies[3]).toMatchObject({ deviceId: "device-1", notificationsEnabled: true, liveActivitiesEnabled: false, - managedTunnelsEnabled: true, + managedTunnelsEnabled: false, }); - expect(bodies[3]).toMatchObject({ + expect(bodies[4]).toMatchObject({ cloudUserId: "user_123", environmentCredential: "environment-credential", }); diff --git a/apps/mobile/src/features/cloud/linkEnvironment.ts b/apps/mobile/src/features/cloud/linkEnvironment.ts index 18e1757b4a76..4b88fcbb0aa7 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"; @@ -54,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, @@ -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,18 +215,41 @@ 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(); + // 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( @@ -255,7 +266,7 @@ export const linkEnvironmentToCloudWithPreference = Effect.fn( payload: { notificationsEnabled: true, liveActivitiesEnabled, - managedTunnelsEnabled: true, + managedTunnelsEnabled: false, }, }) .pipe( @@ -263,28 +274,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: PUBLISH_ONLY_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, @@ -293,37 +304,42 @@ export const linkEnvironmentToCloudWithPreference = Effect.fn( proof, notificationsEnabled: true, liveActivitiesEnabled, - managedTunnelsEnabled: true, + managedTunnelsEnabled: false, }, }) .pipe( Effect.mapError(decodedRelayClientError(`${relayUrl}/v1/client/environment-links failed`)), ); yield* ensureLinkedEnvironmentMatches({ - expectedEnvironmentId: input.connection.environmentId, - expectedProviderKind: MANAGED_ENDPOINT_PROVIDER_KIND, + expectedEnvironmentId: environmentId, + expectedProviderKind: PUBLISH_ONLY_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..b7524355f2e9 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,7 +382,10 @@ function ConfiguredSettingsNotificationsRouteScreen() { runtime.runPromiseExit( setLiveActivityUpdatesEnabled({ updateEnvironment: updateEnvironmentPreference, - canConfigureEnvironment: (id) => canManageConnect(id, AuthRelayConfigureScope), + linkEnvironment: linkEnvironmentWithPreference, + canConfigureEnvironment: (id) => + canManageConnect(id, AuthRelayConfigureScope) && + canManageConnect(id, AuthRelayWriteScope), canUpdateEnvironment: (id) => canManageConnect(id, AuthRelayWriteScope), enabled: true, previousEnabled: liveActivitiesPreferenceEnabled, @@ -456,7 +480,10 @@ function ConfiguredSettingsNotificationsRouteScreen() { runtime.runPromiseExit( setLiveActivityUpdatesEnabled({ updateEnvironment: updateEnvironmentPreference, - canConfigureEnvironment: (id) => canManageConnect(id, AuthRelayConfigureScope), + linkEnvironment: linkEnvironmentWithPreference, + canConfigureEnvironment: (id) => + canManageConnect(id, AuthRelayConfigureScope) && + canManageConnect(id, AuthRelayWriteScope), canUpdateEnvironment: (id) => canManageConnect(id, AuthRelayWriteScope), enabled: false, previousEnabled: liveActivitiesPreferenceEnabled, diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 7d131361b276..e75c87010d88 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -1853,13 +1853,14 @@ "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.", "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 ccba74d1722f..39a8cd4d9401 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -1853,13 +1853,14 @@ "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.", "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 98d3dfeca64c..a10de0b05a3e 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -1853,13 +1853,14 @@ "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.", "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 a9d5c2f0ba64..32698d32a911 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -1853,13 +1853,14 @@ "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.", "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 c495490af093..dbd171818bcd 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -1853,13 +1853,14 @@ "c15d8570b0ac8ae5": "環境から HTTP {status} が返されました。", "b87f2217123b4cbf": "環境のライブアクティビティ設定を更新できませんでした。", "2f18d65ea9f178da": "環境のライブアクティビティ設定を更新できませんでした: {detail}", - "024b0e4154ca9170": "クラウドにリンクできるのは、ローカルでペアリングしたベアラー接続のみです。", "52c4bcf188d1af36": "モバイルデバイスの ID を読み込めませんでした。", "473457b89661c874": "モバイルデバイスの ID を読み込めませんでした: {detail}", "01da8c5b0a52e84a": "環境リンク証明を取得できませんでした。", "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 4ce6ff4b1635..b84f6efb6800 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -1854,13 +1854,14 @@ "c15d8570b0ac8ae5": "환경에서 HTTP {status}를 반환했습니다.", "b87f2217123b4cbf": "환경의 실시간 현황 설정을 업데이트하지 못했습니다.", "2f18d65ea9f178da": "환경의 실시간 현황 설정을 업데이트하지 못했습니다: {detail}", - "024b0e4154ca9170": "로컬로 페어링된 bearer 연결만 클라우드에 연결할 수 있습니다.", "52c4bcf188d1af36": "모바일 기기 ID를 불러올 수 없습니다.", "473457b89661c874": "모바일 기기 ID를 불러올 수 없습니다: {detail}", "01da8c5b0a52e84a": "환경 연결 증명을 얻을 수 없습니다.", "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 5a5b9e8697f6..e806ac68f371 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -1853,13 +1853,14 @@ "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.", "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 66ff10c0f254..345781ca01d5 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -1877,13 +1877,14 @@ "c15d8570b0ac8ae5": "Среда вернула HTTP {status}.", "b87f2217123b4cbf": "Не удалось обновить настройку «Эфир активности» для среды.", "2f18d65ea9f178da": "Не удалось обновить настройку «Эфир активности» для среды: {detail}", - "024b0e4154ca9170": "К облаку можно привязать только локально сопряжённое bearer-подключение.", "52c4bcf188d1af36": "Не удалось загрузить ID мобильного устройства.", "473457b89661c874": "Не удалось загрузить ID мобильного устройства: {detail}", "01da8c5b0a52e84a": "Не удалось получить подтверждение привязки окружения.", "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 f1c659560e70..6f2ccdee856b 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -1853,13 +1853,14 @@ "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.", "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 5d08213434d7..e01c9bf7289f 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -1855,13 +1855,14 @@ "c15d8570b0ac8ae5": "环境返回了 HTTP {status}。", "b87f2217123b4cbf": "无法更新该环境的实时活动偏好设置。", "2f18d65ea9f178da": "无法更新该环境的实时活动偏好设置:{detail}", - "024b0e4154ca9170": "只有本地配对的 Bearer 连接才能关联到云端。", "52c4bcf188d1af36": "无法加载移动设备 ID。", "473457b89661c874": "无法加载移动设备 ID:{detail}", "01da8c5b0a52e84a": "无法获取环境关联凭证。", "20732c0363a295a8": "无法获取环境关联证明:{detail}", "78bf018d20589722": "无法配置环境中继访问。", "a5e3ff0d1a60b766": "无法配置环境的中继访问:{detail}", + "013df8bdb9ca9096": "无法开启代理活动发布。", + "7247ede5160a0154": "无法开启代理活动发布:{detail}", "7d508fe978cb0f3b": "关闭", "3ae222ec888dd171": "追踪 ID:", "be00d572b18076d8": "长按以从此设备移除", 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..5115a27e6301 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}` }, }), ), @@ -174,16 +173,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 +209,27 @@ 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 to any session 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, origin }, - { ...headers, authorization: `Bearer ${token}` }, - ); - expect(response.status).toBe(400); - expect(yield* responseJson(response)).toMatchObject({ - message: "Invalid managed endpoint origin.", - }); + const { post, exchange, linkableHere } = yield* linkProofClient; + const desktop = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN); + 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); + 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 17e3956e4411..84491a274398 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"; @@ -119,8 +118,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; }), @@ -135,8 +133,11 @@ 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) }; + // 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/server/src/cloud/linkChecks.ts b/apps/server/src/cloud/linkChecks.ts index 607e2c08f8a5..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,33 +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; -} - -export 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; - } - } -} - -export 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)); } @@ -79,37 +51,8 @@ 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 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/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..61bb205dc958 100644 --- a/apps/web/src/cloud/useT3ConnectTurnOn.ts +++ b/apps/web/src/cloud/useT3ConnectTurnOn.ts @@ -1,10 +1,10 @@ import { AuthRelayReadScope, + AuthRelayWriteScope, type EnvironmentId, managedCapabilityDenial, } from "@t3tools/contracts"; -import { isElectron } from "../env"; import { useManagedPolicy } from "../state/managedPolicy"; import { useEnvironmentCanConfigureRelay, useEnvironmentScope } from "../state/session"; import { useCloudLinkState } from "./cloudLinkState"; @@ -14,16 +14,16 @@ 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; return resolveT3ConnectTurnOn({ - desktopApp: isElectron, // Unknown while loading and on older servers, which keep today's switch in Settings. linkableHere: linkState?.linkableHere ?? true, cloudConfigured: hasCloudPublicConfig(), canReadRelay, - canWriteRelay: canConfigureRelay, + canWriteRelay: canWriteRelay && canConfigureRelay, connectDenial, }); } 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 : (