The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 07:15 UTC
fix(connect): let remote clients with relay configuration link (#38892)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Nov 18, 2026 at 21:17 UTC
6b45d90047c7592c3e5bf5624553cf0faca1cf8e
25 files changed
+357
-437
apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts
+31
-43
@@ -5,15 +5,9 @@ import * as Option from "effect/Option";
5
import * as Effect from "effect/Effect";
6
import type { EnvironmentId } from "@t3tools/contracts";
7
import { ManagedRelay } from "@t3tools/client-runtime/relay";
8
-import * as Layer from "effect/Layer";
9
-import { HttpClient } from "effect/http";
8
9
import type { SavedRemoteConnection } from "../../lib/connection";
12
-import * as MobileStorage from "../../persistence/mobile-storage";
13
-import {
14
- CloudEnvironmentLinkError,
15
- linkEnvironmentToCloudWithPreference,
16
-} from "../cloud/linkEnvironment";
10
+import { CloudEnvironmentLinkError } from "../cloud/linkEnvironment";
11
import { setLiveActivityUpdatesEnabled } from "./liveActivityPreferences";
12
import { updateAgentAwarenessRegistrationPreferences } from "./remoteRegistration";
13
@@ -33,11 +27,6 @@ vi.mock("expo-constants", () => ({
27
28
vi.mock("expo-device", () => ({}));
29
36
-vi.mock("../cloud/linkEnvironment", async (importOriginal) => ({
37
- ...(await importOriginal<typeof import("../cloud/linkEnvironment")>()),
38
- linkEnvironmentToCloudWithPreference: vi.fn(() => Effect.void),
39
-}));
40
-
30
vi.mock("./remoteRegistration", () => ({
31
updateAgentAwarenessRegistrationPreferences: vi.fn(() => Effect.void),
32
}));
@@ -52,6 +41,13 @@ const updateEnvironment = vi.fn<
41
>
42
>(() => Effect.succeed("updated"));
43
44
+const linkEnvironment = vi.fn<
45
+ (
46
+ id: EnvironmentId,
47
+ input: { readonly clerkToken: string; readonly liveActivitiesEnabled: boolean },
48
+ ) => Effect.Effect<void, CloudEnvironmentLinkError>
49
+>(() => Effect.void);
50
+
51
const connection: SavedRemoteConnection = {
52
environmentId: "env-1" as EnvironmentId,
53
environmentLabel: "Desktop",
@@ -62,25 +58,7 @@ const connection: SavedRemoteConnection = {
58
bearerToken: "local-bearer",
59
};
60
65
-const layerTest = Layer.mergeAll(
66
- Layer.succeed(ManagedRelay.ManagedRelayClient, null as never),
67
- Layer.succeed(
68
- HttpClient.HttpClient,
69
- HttpClient.make(() => Effect.die("unexpected HTTP request")),
70
- ),
71
- Layer.succeed(
72
- MobileStorage.MobileStorage,
73
- MobileStorage.MobileStorage.of({
74
- loadOrCreateAgentAwarenessDeviceId: Effect.succeed("device-1"),
75
- loadAgentAwarenessDeviceId: Effect.succeed("device-1"),
76
- loadAgentAwarenessRegistrationRecord: Effect.succeed(null),
77
- saveAgentAwarenessRegistrationRecord: () => Effect.void,
78
- clearAgentAwarenessRegistrationRecord: Effect.void,
79
- loadRecentThreadShortcuts: Effect.succeed([]),
80
- saveRecentThreadShortcuts: () => Effect.void,
81
- }),
82
- ),
83
-);
61
+const withRelayClient = Effect.provideService(ManagedRelay.ManagedRelayClient, null as never);
62
63
describe("liveActivityPreferences", () => {
64
beforeEach(() => {
@@ -97,6 +75,7 @@ describe("liveActivityPreferences", () => {
75
const exit = yield* Effect.exit(
76
setLiveActivityUpdatesEnabled({
77
updateEnvironment,
78
+ linkEnvironment,
79
enabled: false,
80
previousEnabled: true,
81
clerkToken: "clerk-token",
@@ -120,8 +99,8 @@ describe("liveActivityPreferences", () => {
99
expect(updateEnvironment).toHaveBeenCalledTimes(2);
100
expect(updateEnvironment).toHaveBeenCalledWith(connection.environmentId, false);
101
expect(updateEnvironment).toHaveBeenCalledWith(otherConnection.environmentId, false);
123
- expect(linkEnvironmentToCloudWithPreference).not.toHaveBeenCalled();
124
- }).pipe(Effect.provide(layerTest));
102
+ expect(linkEnvironment).not.toHaveBeenCalled();
103
+ }).pipe(withRelayClient);
104
});
105
106
it.effect("reports a relay preference committed before environment configuration fails", () => {
@@ -130,12 +109,13 @@ describe("liveActivityPreferences", () => {
109
relayLinkCommitted: true,
110
});
111
updateEnvironment.mockReturnValueOnce(Effect.succeed("unlinked"));
133
- vi.mocked(linkEnvironmentToCloudWithPreference).mockReturnValueOnce(Effect.fail(failure));
112
+ linkEnvironment.mockReturnValueOnce(Effect.fail(failure));
113
114
return Effect.gen(function* () {
115
const exit = yield* Effect.exit(
116
setLiveActivityUpdatesEnabled({
117
updateEnvironment,
118
+ linkEnvironment,
119
enabled: true,
120
previousEnabled: false,
121
clerkToken: "clerk-token",
@@ -156,7 +136,7 @@ describe("liveActivityPreferences", () => {
136
expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenLastCalledWith({
137
liveActivitiesEnabled: false,
138
});
159
- }).pipe(Effect.provide(layerTest));
139
+ }).pipe(withRelayClient);
140
});
141
142
it.effect("only creates missing links when the session can configure Connect", () => {
@@ -165,14 +145,21 @@ describe("liveActivityPreferences", () => {
145
...connection,
146
environmentId: "read-only" as EnvironmentId,
147
};
148
+ // Current mobile pairings authenticate with DPoP and carry no bearer token.
149
+ const dpopConnection: SavedRemoteConnection = {
150
+ ...connection,
151
+ bearerToken: null,
152
+ authenticationMethod: "dpop",
153
+ };
154
155
return Effect.gen(function* () {
156
yield* setLiveActivityUpdatesEnabled({
157
updateEnvironment,
158
+ linkEnvironment,
159
enabled: true,
160
previousEnabled: false,
161
clerkToken: "clerk-token",
175
- connections: [readOnlyConnection, connection],
162
+ connections: [readOnlyConnection, dpopConnection],
163
canUpdateEnvironment: (environmentId) => environmentId === connection.environmentId,
164
canConfigureEnvironment: (environmentId) => environmentId === connection.environmentId,
165
});
@@ -180,12 +167,11 @@ describe("liveActivityPreferences", () => {
167
expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenCalledWith({
168
liveActivitiesEnabled: true,
169
});
183
- expect(linkEnvironmentToCloudWithPreference).toHaveBeenCalledExactlyOnceWith({
170
+ expect(linkEnvironment).toHaveBeenCalledExactlyOnceWith(connection.environmentId, {
171
clerkToken: "clerk-token",
185
- connection,
172
liveActivitiesEnabled: true,
173
});
188
- }).pipe(Effect.provide(layerTest));
174
+ }).pipe(withRelayClient);
175
});
176
177
it.effect("reports older environments whose preferences could not be updated", () =>
@@ -198,6 +184,7 @@ describe("liveActivityPreferences", () => {
184
updateEnvironment.mockReturnValueOnce(Effect.succeed("unsupported"));
185
const partial = yield* setLiveActivityUpdatesEnabled({
186
updateEnvironment,
187
+ linkEnvironment,
188
enabled: false,
189
previousEnabled: true,
190
clerkToken: "clerk-token",
@@ -206,8 +193,8 @@ describe("liveActivityPreferences", () => {
193
canUpdateEnvironment: () => true,
194
});
195
expect(partial).toBe(true);
209
- expect(linkEnvironmentToCloudWithPreference).not.toHaveBeenCalled();
210
- }).pipe(Effect.provide(layerTest)),
196
+ expect(linkEnvironment).not.toHaveBeenCalled();
197
+ }).pipe(withRelayClient),
198
);
199
200
it.effect("checks current relay access after updating the device registration", () => {
@@ -221,6 +208,7 @@ describe("liveActivityPreferences", () => {
208
return Effect.gen(function* () {
209
yield* setLiveActivityUpdatesEnabled({
210
updateEnvironment,
211
+ linkEnvironment,
212
enabled: false,
213
previousEnabled: true,
214
clerkToken: "clerk-token",
@@ -229,9 +217,9 @@ describe("liveActivityPreferences", () => {
217
canUpdateEnvironment: () => canConfigureEnvironment,
218
});
219
232
- expect(linkEnvironmentToCloudWithPreference).not.toHaveBeenCalled();
220
+ expect(linkEnvironment).not.toHaveBeenCalled();
221
expect(updateEnvironment).not.toHaveBeenCalled();
222
expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenCalledTimes(1);
235
- }).pipe(Effect.provide(layerTest));
223
+ }).pipe(withRelayClient);
224
});
225
});
apps/mobile/src/features/agent-awareness/liveActivityPreferences.ts
+7
-12
@@ -4,10 +4,7 @@ import * as Schema from "effect/Schema";
4
import type { EnvironmentId } from "@t3tools/contracts";
5
6
import type { SavedRemoteConnection } from "../../lib/connection";
7
-import {
8
- linkEnvironmentToCloudWithPreference,
9
- type CloudEnvironmentLinkError,
10
-} from "../cloud/linkEnvironment";
7
+import type { CloudEnvironmentLinkError } from "../cloud/linkEnvironment";
8
import { updateAgentAwarenessRegistrationPreferences } from "./remoteRegistration";
9
10
export class LiveActivityEnvironmentUpdateError extends Schema.TaggedError<LiveActivityEnvironmentUpdateError>()(
@@ -31,6 +28,10 @@ export const setLiveActivityUpdatesEnabled = Effect.fn("setLiveActivityUpdatesEn
28
"updated" | "unlinked" | "unsupported" | "disconnected",
29
CloudEnvironmentLinkError
30
>;
31
+ readonly linkEnvironment: (
32
+ environmentId: EnvironmentId,
33
+ input: { readonly clerkToken: string; readonly liveActivitiesEnabled: boolean },
34
+ ) => Effect.Effect<void, CloudEnvironmentLinkError>;
35
readonly canUpdateEnvironment: (environmentId: EnvironmentId) => boolean;
36
readonly canConfigureEnvironment: (environmentId: EnvironmentId) => boolean;
37
}) {
@@ -43,18 +44,12 @@ export const setLiveActivityUpdatesEnabled = Effect.fn("setLiveActivityUpdatesEn
44
? yield* input.updateEnvironment(connection.environmentId, enabled)
45
: "unlinked";
46
if (result === "updated" || result === "disconnected") return result;
46
- if (
47
- !enabled ||
48
- !clerkToken ||
49
- !connection.bearerToken ||
50
- !input.canConfigureEnvironment(connection.environmentId)
51
- ) {
47
+ if (!enabled || !clerkToken || !input.canConfigureEnvironment(connection.environmentId)) {
48
return result;
49
}
50
55
- yield* linkEnvironmentToCloudWithPreference({
51
+ yield* input.linkEnvironment(connection.environmentId, {
52
clerkToken,
57
- connection,
53
liveActivitiesEnabled: enabled,
54
});
55
return "updated" as const;
apps/mobile/src/features/cloud/linkEnvironment.test.ts
+72
-36
@@ -116,6 +116,43 @@ const withCloudServices = <A, E>(
116
>,
117
) => effect.pipe(Effect.provide(layerCloudClient()));
118
119
+const linkedSupervisor = Effect.gen(function* () {
120
+ const target = new PrimaryConnectionTarget({
121
+ environmentId: savedConnection.environmentId,
122
+ label: savedConnection.environmentLabel,
123
+ httpBaseUrl: savedConnection.httpBaseUrl,
124
+ wsBaseUrl: savedConnection.wsBaseUrl,
125
+ });
126
+ return EnvironmentSupervisor.EnvironmentSupervisor.of({
127
+ target,
128
+ state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
129
+ session: yield* SubscriptionRef.make(Option.none<RpcSession>()),
130
+ prepared: yield* SubscriptionRef.make(
131
+ Option.some<PreparedConnection>({
132
+ environmentId: savedConnection.environmentId,
133
+ label: savedConnection.environmentLabel,
134
+ httpBaseUrl: savedConnection.httpBaseUrl,
135
+ socketUrl: savedConnection.wsBaseUrl,
136
+ httpAuthorization: { _tag: "Bearer", token: "local-bearer" },
137
+ target,
138
+ }),
139
+ ),
140
+ connect: Effect.void,
141
+ disconnect: Effect.void,
142
+ retryNow: Effect.void,
143
+ });
144
+});
145
+
146
+const linkPreparedEnvironment = (liveActivitiesEnabled: boolean) =>
147
+ Effect.flatMap(linkedSupervisor, (supervisor) =>
148
+ withCloudServices(
149
+ linkEnvironmentToCloudWithPreference({
150
+ clerkToken: "clerk-token",
151
+ liveActivitiesEnabled,
152
+ }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor)),
153
+ ),
154
+ );
155
+
156
function validLinkProof() {
157
return "signed-environment-link-jwt";
158
}
@@ -125,14 +162,11 @@ function validLinkResponse(environmentId = "env-1") {
162
ok: true,
163
environmentId,
164
endpoint: {
128
- httpBaseUrl: "https://managed.example.test/",
129
- wsBaseUrl: "wss://managed.example.test/ws",
130
- providerKind: "cloudflare_tunnel",
131
- },
132
- endpointRuntime: {
133
- providerKind: "cloudflare_tunnel",
134
- connectorToken: "connector-token",
165
+ httpBaseUrl: "https://desktop.example.test/",
166
+ wsBaseUrl: "wss://desktop.example.test/ws",
167
+ providerKind: "manual",
168
},
169
+ endpointRuntime: null,
170
relayIssuer: "https://relay.example.test",
171
cloudUserId: "user_123",
172
environmentCredential: "environment-credential",
@@ -140,6 +174,16 @@ function validLinkResponse(environmentId = "env-1") {
174
};
175
}
176
177
+function linkStateResponse() {
178
+ return {
179
+ linked: false,
180
+ cloudUserId: null,
181
+ relayUrl: null,
182
+ relayIssuer: null,
183
+ publishAgentActivity: true,
184
+ };
185
+}
186
+
187
function validLinkChallengeResponse() {
188
return {
189
challenge: "link-challenge",
@@ -189,6 +233,9 @@ describe("mobile cloud link environment client", () => {
233
() =>
234
Effect.gen(function* () {
235
const fetchMock = vi.fn((url: string | URL) => {
236
+ if (String(url).endsWith("/api/connect/preferences")) {
237
+ return Promise.resolve(Response.json(linkStateResponse()));
238
+ }
239
if (String(url).endsWith("/v1/client/environment-link-challenges")) {
240
return Promise.resolve(Response.json(validLinkChallengeResponse()));
241
}
@@ -199,24 +246,21 @@ describe("mobile cloud link environment client", () => {
246
});
247
vi.stubGlobal("fetch", fetchMock);
248
202
- const error = yield* withCloudServices(
203
- linkEnvironmentToCloudWithPreference({
204
- clerkToken: "clerk-token",
205
- connection: savedConnection,
206
- liveActivitiesEnabled: true,
207
- }),
208
- ).pipe(Effect.flip);
249
+ const error = yield* linkPreparedEnvironment(true).pipe(Effect.flip);
250
expect(error).toMatchObject({
251
_tag: "CloudEnvironmentLinkError",
252
message: "Relay returned credentials for a different environment.",
253
});
213
- expect(fetchMock).toHaveBeenCalledTimes(3);
254
+ expect(fetchMock).toHaveBeenCalledTimes(4);
255
}),
256
);
257
258
it.effect("rejects relay link credentials for a different managed endpoint provider", () =>
259
Effect.gen(function* () {
260
const fetchMock = vi.fn((url: string | URL) => {
261
+ if (String(url).endsWith("/api/connect/preferences")) {
262
+ return Promise.resolve(Response.json(linkStateResponse()));
263
+ }
264
if (String(url).endsWith("/v1/client/environment-link-challenges")) {
265
return Promise.resolve(Response.json(validLinkChallengeResponse()));
266
}
@@ -228,25 +272,19 @@ describe("mobile cloud link environment client", () => {
272
...validLinkResponse(),
273
endpoint: {
274
...validLinkResponse().endpoint,
231
- providerKind: "manual",
275
+ providerKind: "cloudflare_tunnel",
276
},
277
}),
278
);
279
});
280
vi.stubGlobal("fetch", fetchMock);
281
238
- const error = yield* withCloudServices(
239
- linkEnvironmentToCloudWithPreference({
240
- clerkToken: "clerk-token",
241
- connection: savedConnection,
242
- liveActivitiesEnabled: true,
243
- }),
244
- ).pipe(Effect.flip);
282
+ const error = yield* linkPreparedEnvironment(true).pipe(Effect.flip);
283
expect(error).toMatchObject({
284
_tag: "CloudEnvironmentLinkError",
285
message: "Relay returned credentials for a different endpoint provider.",
286
});
249
- expect(fetchMock).toHaveBeenCalledTimes(3);
287
+ expect(fetchMock).toHaveBeenCalledTimes(4);
288
}),
289
);
290
@@ -266,38 +304,36 @@ describe("mobile cloud link environment client", () => {
304
if (String(url).endsWith("/v1/client/environment-links")) {
305
return Promise.resolve(Response.json(validLinkResponse()));
306
}
307
+ if (String(url).endsWith("/api/connect/preferences")) {
308
+ return Promise.resolve(Response.json(linkStateResponse()));
309
+ }
310
return Promise.resolve(
311
Response.json({ ok: true, endpointRuntimeStatus: { status: "configured" } }),
312
);
313
});
314
vi.stubGlobal("fetch", fetchMock);
315
275
- yield* withCloudServices(
276
- linkEnvironmentToCloudWithPreference({
277
- clerkToken: "clerk-token",
278
- connection: savedConnection,
279
- liveActivitiesEnabled: false,
280
- }),
281
- );
316
+ yield* linkPreparedEnvironment(false);
317
283
- expect(bodies[1]).toMatchObject({
318
+ expect(bodies[0]).toEqual({ publishAgentActivity: true });
319
+ expect(bodies[2]).toMatchObject({
320
endpoint: {
321
httpBaseUrl: "https://desktop.example.test/",
322
wsBaseUrl: "wss://desktop.example.test/ws",
287
- providerKind: "cloudflare_tunnel",
323
+ providerKind: "manual",
324
},
325
origin: {
326
localHttpHost: "127.0.0.1",
327
localHttpPort: 443,
328
},
329
});
294
- expect(bodies[2]).toMatchObject({
330
+ expect(bodies[3]).toMatchObject({
331
deviceId: "device-1",
332
notificationsEnabled: true,
333
liveActivitiesEnabled: false,
298
- managedTunnelsEnabled: true,
334
+ managedTunnelsEnabled: false,
335
});
300
- expect(bodies[3]).toMatchObject({
336
+ expect(bodies[4]).toMatchObject({
337
cloudUserId: "user_123",
338
environmentCredential: "environment-credential",
339
});
apps/mobile/src/features/cloud/linkEnvironment.ts
+81
-65
@@ -2,7 +2,7 @@ import * as Effect from "effect/Effect";
2
import * as Option from "effect/Option";
3
import * as SubscriptionRef from "effect/SubscriptionRef";
4
import * as Schema from "effect/Schema";
5
-import { HttpClient, type HttpClientResponse } from "effect/http";
5
+import type { HttpClientResponse } from "effect/http";
6
import {
7
EnvironmentCloudEndpointUnavailableError,
8
EnvironmentHttpBadRequestError,
@@ -19,13 +19,11 @@ import {
19
import { EnvironmentSupervisor } from "@t3tools/client-runtime/connection";
20
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
21
import { ManagedRelay, relayRequestFailureDetail } from "@t3tools/client-runtime/relay";
22
-import { makeEnvironmentHttpApiClient } from "@t3tools/client-runtime/rpc";
22
23
import { executeConnectedEnvironmentHttpRequest } from "@t3tools/client-runtime/state/environmentHttpAuth";
24
import { msg } from "gt-react-native";
25
26
import { m } from "../../i18n/messages";
28
-import type { SavedRemoteConnection } from "../../lib/connection";
27
import * as MobileStorage from "../../persistence/mobile-storage";
28
import { resolveCloudPublicConfig } from "./publicConfig";
29
@@ -54,8 +52,8 @@ const isEnvironmentCloudApiError = Schema.is(
52
]),
53
);
54
57
-const MANAGED_ENDPOINT_PROVIDER_KIND =
58
- "cloudflare_tunnel" satisfies RelayManagedEndpointProviderKind;
55
+// Live Activities need only agent activity, so a phone never starts a tunnel on the host.
56
+const PUBLISH_ONLY_PROVIDER_KIND = "manual" satisfies RelayManagedEndpointProviderKind;
57
58
function cloudEnvironmentLinkError(
59
message: string,
@@ -163,16 +161,6 @@ function ensureLinkedEnvironmentMatches(input: {
161
return Effect.void;
162
}
163
166
-interface LinkEnvironmentToCloudInput {
167
- readonly connection: SavedRemoteConnection;
168
- readonly clerkToken: string;
169
-}
170
-
171
-type LinkEnvironmentToCloudRequirements =
172
- | HttpClient.HttpClient
173
- | ManagedRelay.ManagedRelayClient
174
- | MobileStorage.MobileStorage;
175
-
164
const decodeRelayOkResponse = Schema.decodeUnknownEffect(RelayOkResponse);
165
166
export const updateLinkedEnvironmentLiveActivityPreference = Effect.fn(
@@ -227,18 +215,41 @@ export const updateLinkedEnvironmentLiveActivityPreference = Effect.fn(
215
);
216
});
217
218
+// Linking can install the relay client and start a managed tunnel before it answers.
219
+const CLOUD_LINK_REQUEST_TIMEOUT_MS = 60_000;
220
+
221
+/** Links the supervised environment, signing its requests with this device's own credential. */
222
export const linkEnvironmentToCloudWithPreference = Effect.fn(
223
"linkEnvironment.linkEnvironmentToCloudWithPreference",
232
-)(function* (
233
- input: LinkEnvironmentToCloudInput & { readonly liveActivitiesEnabled: boolean },
234
-): Effect.fn.Return<void, CloudEnvironmentLinkError, LinkEnvironmentToCloudRequirements> {
235
- if (!input.connection.bearerToken) {
224
+)(function* (input: { readonly clerkToken: string; readonly liveActivitiesEnabled: boolean }) {
225
+ const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
226
+ const prepared = yield* SubscriptionRef.get(supervisor.prepared);
227
+ if (Option.isNone(prepared)) {
228
return yield* new CloudEnvironmentLinkError({
237
- message: m(msg("Only a locally paired bearer connection can be linked to the cloud.")),
229
+ message: m(msg("The environment is not connected.")),
230
});
231
}
240
- const localBearerToken = input.connection.bearerToken;
232
+ const { environmentId, httpBaseUrl, target } = prepared.value;
233
+ const wsBaseUrl =
234
+ target._tag === "PrimaryConnectionTarget"
235
+ ? target.wsBaseUrl
236
+ : httpBaseUrl.replace(/^http/, "ws");
237
const relayUrl = yield* requireRelayUrl();
238
+ // Publishing is a host-local setting, so enable it before committing a link a retry would skip.
239
+ yield* executeConnectedEnvironmentHttpRequest({
240
+ group: "connect",
241
+ method: "POST",
242
+ url: (urls) => urls.preferences(),
243
+ timeoutMs: CLOUD_LINK_REQUEST_TIMEOUT_MS,
244
+ request: ({ client, headers }) =>
245
+ client.preferences({ headers, payload: { publishAgentActivity: true } }),
246
+ }).pipe(
247
+ Effect.mapError(
248
+ cloudEnvironmentLinkError(m(msg("Could not turn on agent activity publishing.")), (detail) =>
249
+ m(msg("Could not turn on agent activity publishing: {detail}", { detail })),
250
+ ),
251
+ ),
252
+ );
253
const relayClient = yield* ManagedRelay.ManagedRelayClient;
254
const storage = yield* MobileStorage.MobileStorage;
255
const deviceId = yield* storage.loadOrCreateAgentAwarenessDeviceId.pipe(
@@ -255,7 +266,7 @@ export const linkEnvironmentToCloudWithPreference = Effect.fn(
266
payload: {
267
notificationsEnabled: true,
268
liveActivitiesEnabled,
258
- managedTunnelsEnabled: true,
269
+ managedTunnelsEnabled: false,
270
},
271
})
272
.pipe(
@@ -263,28 +274,28 @@ export const linkEnvironmentToCloudWithPreference = Effect.fn(
274
decodedRelayClientError(`${relayUrl}/v1/client/environment-link-challenges failed`),
275
),
276
);
266
- const environmentClient = yield* makeEnvironmentHttpApiClient(input.connection.httpBaseUrl);
267
- const proof = yield* environmentClient.connect
268
- .linkProof({
269
- headers: { authorization: `Bearer ${localBearerToken}` },
270
- payload: {
271
- challenge: challenge.challenge,
272
- relayIssuer: relayUrl,
273
- endpoint: {
274
- httpBaseUrl: input.connection.httpBaseUrl,
275
- wsBaseUrl: input.connection.wsBaseUrl,
276
- providerKind: MANAGED_ENDPOINT_PROVIDER_KIND,
277
+ const proof = yield* executeConnectedEnvironmentHttpRequest({
278
+ group: "connect",
279
+ method: "POST",
280
+ url: (urls) => urls.linkProof(),
281
+ timeoutMs: CLOUD_LINK_REQUEST_TIMEOUT_MS,
282
+ request: ({ client, headers }) =>
283
+ client.linkProof({
284
+ headers,
285
+ payload: {
286
+ challenge: challenge.challenge,
287
+ relayIssuer: relayUrl,
288
+ endpoint: { httpBaseUrl, wsBaseUrl, providerKind: PUBLISH_ONLY_PROVIDER_KIND },
289
+ origin: endpointOrigin(httpBaseUrl),
290
},
278
- origin: endpointOrigin(input.connection.httpBaseUrl),
279
- },
280
- })
281
- .pipe(
282
- Effect.mapError(
283
- cloudEnvironmentLinkError(m(msg("Could not obtain environment link proof.")), (detail) =>
284
- m(msg("Could not obtain environment link proof: {detail}", { detail })),
285
- ),
291
+ }),
292
+ }).pipe(
293
+ Effect.mapError(
294
+ cloudEnvironmentLinkError(m(msg("Could not obtain environment link proof.")), (detail) =>
295
+ m(msg("Could not obtain environment link proof: {detail}", { detail })),
296
),
287
- );
297
+ ),
298
+ );
299
const link = yield* relayClient
300
.linkEnvironment({
301
clerkToken: input.clerkToken,
@@ -293,37 +304,42 @@ export const linkEnvironmentToCloudWithPreference = Effect.fn(
304
proof,
305
notificationsEnabled: true,
306
liveActivitiesEnabled,
296
- managedTunnelsEnabled: true,
307
+ managedTunnelsEnabled: false,
308
},
309
})
310
.pipe(
311
Effect.mapError(decodedRelayClientError(`${relayUrl}/v1/client/environment-links failed`)),
312
);
313
yield* ensureLinkedEnvironmentMatches({
303
- expectedEnvironmentId: input.connection.environmentId,
304
- expectedProviderKind: MANAGED_ENDPOINT_PROVIDER_KIND,
314
+ expectedEnvironmentId: environmentId,
315
+ expectedProviderKind: PUBLISH_ONLY_PROVIDER_KIND,
316
link,
317
});
318
308
- yield* environmentClient.connect
309
- .relayConfig({
310
- headers: { authorization: `Bearer ${localBearerToken}` },
311
- payload: {
312
- relayUrl,
313
- relayIssuer: link.relayIssuer,
314
- cloudUserId: link.cloudUserId,
315
- environmentCredential: link.environmentCredential,
316
- cloudMintPublicKey: link.cloudMintPublicKey,
317
- endpointRuntime: link.endpointRuntime,
318
- },
319
- })
320
- .pipe(
321
- Effect.mapError(
322
- cloudEnvironmentLinkError(
323
- m(msg("Could not configure environment relay access.")),
324
- (detail) => m(msg("Could not configure environment relay access: {detail}", { detail })),
325
- { relayLinkCommitted: true },
326
- ),
319
+ yield* executeConnectedEnvironmentHttpRequest({
320
+ group: "connect",
321
+ method: "POST",
322
+ url: (urls) => urls.relayConfig(),
323
+ timeoutMs: CLOUD_LINK_REQUEST_TIMEOUT_MS,
324
+ request: ({ client, headers }) =>
325
+ client.relayConfig({
326
+ headers,
327
+ payload: {
328
+ relayUrl,
329
+ relayIssuer: link.relayIssuer,
330
+ cloudUserId: link.cloudUserId,
331
+ environmentCredential: link.environmentCredential,
332
+ cloudMintPublicKey: link.cloudMintPublicKey,
333
+ endpointRuntime: link.endpointRuntime,
334
+ },
335
+ }),
336
+ }).pipe(
337
+ Effect.mapError(
338
+ cloudEnvironmentLinkError(
339
+ m(msg("Could not configure environment relay access.")),
340
+ (detail) => m(msg("Could not configure environment relay access: {detail}", { detail })),
341
+ { relayLinkCommitted: true },
342
),
328
- );
343
+ ),
344
+ );
345
});
apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx
+38
-11
@@ -51,6 +51,7 @@ import {
51
import { connectionAtomRuntime } from "../../connection/runtime";
52
import {
53
CloudEnvironmentLinkError,
54
+ linkEnvironmentToCloudWithPreference,
55
updateLinkedEnvironmentLiveActivityPreference,
56
} from "../cloud/linkEnvironment";
57
import { refreshManagedRelayEnvironments } from "../cloud/managedRelayState";
@@ -70,9 +71,20 @@ const updateLiveActivityPreference = createEnvironmentCommand(connectionAtomRunt
71
execute: updateLinkedEnvironmentLiveActivityPreference,
72
});
73
74
+const linkLiveActivityEnvironment = createEnvironmentCommand(connectionAtomRuntime, {
75
+ label: "linkLiveActivityEnvironment",
76
+ execute: linkEnvironmentToCloudWithPreference,
77
+});
78
+
79
const isLiveActivityEnvironmentUpdateError = Schema.is(LiveActivityEnvironmentUpdateError);
80
const isCloudEnvironmentLinkError = Schema.is(CloudEnvironmentLinkError);
81
82
+function toCloudEnvironmentLinkError(cause: unknown, message: string) {
83
+ return isCloudEnvironmentLinkError(cause)
84
+ ? cause
85
+ : new CloudEnvironmentLinkError({ message, cause });
86
+}
87
+
88
const updateEnvironmentPreference = Effect.fn("updateEnvironmentPreference")(function* (
89
environmentId: EnvironmentId,
90
enabled: boolean,
@@ -81,15 +93,24 @@ const updateEnvironmentPreference = Effect.fn("updateEnvironmentPreference")(fun
93
updateLiveActivityPreference.run(appAtomRegistry, { environmentId, input: enabled }),
94
);
95
if (result._tag === "Success") return result.value;
84
- const cause = squashAtomCommandFailure(result);
85
- return yield* isCloudEnvironmentLinkError(cause)
86
- ? cause
87
- : new CloudEnvironmentLinkError({
88
- message: resolveMessage(
89
- msg("Could not update the environment's Live Activity preference."),
90
- ),
91
- cause,
92
- });
96
+ return yield* toCloudEnvironmentLinkError(
97
+ squashAtomCommandFailure(result),
98
+ resolveMessage(msg("Could not update the environment's Live Activity preference.")),
99
+ );
100
+});
101
+
102
+const linkEnvironmentWithPreference = Effect.fn("linkEnvironmentWithPreference")(function* (
103
+ environmentId: EnvironmentId,
104
+ input: { readonly clerkToken: string; readonly liveActivitiesEnabled: boolean },
105
+) {
106
+ const result = yield* Effect.promise(() =>
107
+ linkLiveActivityEnvironment.run(appAtomRegistry, { environmentId, input }),
108
+ );
109
+ if (result._tag === "Success") return;
110
+ return yield* toCloudEnvironmentLinkError(
111
+ squashAtomCommandFailure(result),
112
+ resolveMessage(msg("Could not configure environment relay access.")),
113
+ );
114
});
115
116
/**
@@ -361,7 +382,10 @@ function ConfiguredSettingsNotificationsRouteScreen() {
382
runtime.runPromiseExit(
383
setLiveActivityUpdatesEnabled({
384
updateEnvironment: updateEnvironmentPreference,
364
- canConfigureEnvironment: (id) => canManageConnect(id, AuthRelayConfigureScope),
385
+ linkEnvironment: linkEnvironmentWithPreference,
386
+ canConfigureEnvironment: (id) =>
387
+ canManageConnect(id, AuthRelayConfigureScope) &&
388
+ canManageConnect(id, AuthRelayWriteScope),
389
canUpdateEnvironment: (id) => canManageConnect(id, AuthRelayWriteScope),
390
enabled: true,
391
previousEnabled: liveActivitiesPreferenceEnabled,
@@ -456,7 +480,10 @@ function ConfiguredSettingsNotificationsRouteScreen() {
480
runtime.runPromiseExit(
481
setLiveActivityUpdatesEnabled({
482
updateEnvironment: updateEnvironmentPreference,
459
- canConfigureEnvironment: (id) => canManageConnect(id, AuthRelayConfigureScope),
483
+ linkEnvironment: linkEnvironmentWithPreference,
484
+ canConfigureEnvironment: (id) =>
485
+ canManageConnect(id, AuthRelayConfigureScope) &&
486
+ canManageConnect(id, AuthRelayWriteScope),
487
canUpdateEnvironment: (id) => canManageConnect(id, AuthRelayWriteScope),
488
enabled: false,
489
previousEnabled: liveActivitiesPreferenceEnabled,
apps/mobile/src/i18n/translations/de.json
+2
-1
@@ -1853,13 +1853,14 @@
1853
"c15d8570b0ac8ae5": "Die Umgebung meldete HTTP {status}.",
1854
"b87f2217123b4cbf": "Die Live-Aktivitätseinstellung der Umgebung konnte nicht geändert werden.",
1855
"2f18d65ea9f178da": "Die Live-Aktivitätseinstellung der Umgebung konnte nicht geändert werden: {detail}",
1856
- "024b0e4154ca9170": "Nur eine lokal gekoppelte Bearer-Verbindung kann mit der Cloud verknüpft werden.",
1856
"52c4bcf188d1af36": "Die ID des Mobilgeräts konnte nicht geladen werden.",
1857
"473457b89661c874": "Die ID des Mobilgeräts konnte nicht geladen werden: {detail}",
1858
"01da8c5b0a52e84a": "Der Nachweis für die Umgebungsverknüpfung konnte nicht abgerufen werden.",
1859
"20732c0363a295a8": "Verknüpfungsnachweis der Umgebung konnte nicht abgerufen werden: {detail}",
1860
"78bf018d20589722": "Der Relay-Zugriff der Umgebung konnte nicht konfiguriert werden.",
1861
"a5e3ff0d1a60b766": "Relay-Zugriff der Umgebung konnte nicht konfiguriert werden: {detail}",
1862
+ "013df8bdb9ca9096": "Die Veröffentlichung der Agentenaktivität konnte nicht aktiviert werden.",
1863
+ "7247ede5160a0154": "Die Veröffentlichung der Agentenaktivität konnte nicht aktiviert werden: {detail}",
1864
"7d508fe978cb0f3b": "Aus",
1865
"3ae222ec888dd171": "Trace-ID:",
1866
"be00d572b18076d8": "Lange drücken, um von diesem Gerät zu entfernen",
apps/mobile/src/i18n/translations/en.json
+2
-1
@@ -1853,13 +1853,14 @@
1853
"c15d8570b0ac8ae5": "Environment returned HTTP {status}.",
1854
"b87f2217123b4cbf": "Could not update the environment's Live Activity preference.",
1855
"2f18d65ea9f178da": "Could not update the environment's Live Activity preference: {detail}",
1856
- "024b0e4154ca9170": "Only a locally paired bearer connection can be linked to the cloud.",
1856
"52c4bcf188d1af36": "Could not load the mobile device id.",
1857
"473457b89661c874": "Could not load the mobile device id: {detail}",
1858
"01da8c5b0a52e84a": "Could not obtain environment link proof.",
1859
"20732c0363a295a8": "Could not obtain environment link proof: {detail}",
1860
"78bf018d20589722": "Could not configure environment relay access.",
1861
"a5e3ff0d1a60b766": "Could not configure environment relay access: {detail}",
1862
+ "013df8bdb9ca9096": "Could not turn on agent activity publishing.",
1863
+ "7247ede5160a0154": "Could not turn on agent activity publishing: {detail}",
1864
"7d508fe978cb0f3b": "Off",
1865
"3ae222ec888dd171": "Trace ID:",
1866
"be00d572b18076d8": "Long press to remove from this device",
apps/mobile/src/i18n/translations/es.json
+2
-1
@@ -1853,13 +1853,14 @@
1853
"c15d8570b0ac8ae5": "El entorno devolvió HTTP {status}.",
1854
"b87f2217123b4cbf": "No se pudo actualizar la preferencia de actividades en directo del entorno.",
1855
"2f18d65ea9f178da": "No se pudo actualizar la preferencia de actividades en directo del entorno: {detail}",
1856
- "024b0e4154ca9170": "Solo se puede vincular a la nube una conexión bearer emparejada localmente.",
1856
"52c4bcf188d1af36": "No se pudo cargar el ID del dispositivo móvil.",
1857
"473457b89661c874": "No se pudo cargar el ID del dispositivo móvil: {detail}",
1858
"01da8c5b0a52e84a": "No se pudo obtener la prueba de vinculación del entorno.",
1859
"20732c0363a295a8": "No se pudo obtener la prueba de vinculación del entorno: {detail}",
1860
"78bf018d20589722": "No se pudo configurar el acceso del entorno al relay.",
1861
"a5e3ff0d1a60b766": "No se pudo configurar el acceso del entorno al relay: {detail}",
1862
+ "013df8bdb9ca9096": "No se pudo activar la publicación de la actividad del agente.",
1863
+ "7247ede5160a0154": "No se pudo activar la publicación de la actividad del agente: {detail}",
1864
"7d508fe978cb0f3b": "Apagado",
1865
"3ae222ec888dd171": "ID de traza:",
1866
"be00d572b18076d8": "Mantén pulsado para quitarlo de este dispositivo",
apps/mobile/src/i18n/translations/fr.json
+2
-1
@@ -1853,13 +1853,14 @@
1853
"c15d8570b0ac8ae5": "L’environnement a renvoyé HTTP {status}.",
1854
"b87f2217123b4cbf": "Impossible de mettre à jour la préférence d’activités en direct de l’environnement.",
1855
"2f18d65ea9f178da": "Impossible de mettre à jour la préférence d’activités en direct de l’environnement : {detail}",
1856
- "024b0e4154ca9170": "Seule une connexion bearer appairée localement peut être associée au cloud.",
1856
"52c4bcf188d1af36": "Impossible de charger l’ID de l’appareil mobile.",
1857
"473457b89661c874": "Impossible de charger l’ID de l’appareil mobile : {detail}",
1858
"01da8c5b0a52e84a": "Impossible d’obtenir la preuve d’association de l’environnement.",
1859
"20732c0363a295a8": "Impossible d’obtenir la preuve d’association de l’environnement : {detail}",
1860
"78bf018d20589722": "Impossible de configurer l’accès relais de l’environnement.",
1861
"a5e3ff0d1a60b766": "Impossible de configurer l’accès au relais de l’environnement : {detail}",
1862
+ "013df8bdb9ca9096": "Impossible d’activer la publication de l’activité de l’agent.",
1863
+ "7247ede5160a0154": "Impossible d’activer la publication de l’activité de l’agent : {detail}",
1864
"7d508fe978cb0f3b": "Éteint",
1865
"3ae222ec888dd171": "ID de trace :",
1866
"be00d572b18076d8": "Appuyez longuement pour retirer de cet appareil",
apps/mobile/src/i18n/translations/ja.json
+2
-1
@@ -1853,13 +1853,14 @@
1853
"c15d8570b0ac8ae5": "環境から HTTP {status} が返されました。",
1854
"b87f2217123b4cbf": "環境のライブアクティビティ設定を更新できませんでした。",
1855
"2f18d65ea9f178da": "環境のライブアクティビティ設定を更新できませんでした: {detail}",
1856
- "024b0e4154ca9170": "クラウドにリンクできるのは、ローカルでペアリングしたベアラー接続のみです。",
1856
"52c4bcf188d1af36": "モバイルデバイスの ID を読み込めませんでした。",
1857
"473457b89661c874": "モバイルデバイスの ID を読み込めませんでした: {detail}",
1858
"01da8c5b0a52e84a": "環境リンク証明を取得できませんでした。",
1859
"20732c0363a295a8": "環境のリンク証明を取得できませんでした: {detail}",
1860
"78bf018d20589722": "環境のリレーアクセスを構成できませんでした。",
1861
"a5e3ff0d1a60b766": "環境のリレーアクセスを構成できませんでした: {detail}",
1862
+ "013df8bdb9ca9096": "エージェントのアクティビティの公開をオンにできませんでした。",
1863
+ "7247ede5160a0154": "エージェントのアクティビティの公開をオンにできませんでした: {detail}",
1864
"7d508fe978cb0f3b": "オフ",
1865
"3ae222ec888dd171": "トレース ID:",
1866
"be00d572b18076d8": "長押しでこのデバイスから削除",
apps/mobile/src/i18n/translations/ko.json
+2
-1
@@ -1854,13 +1854,14 @@
1854
"c15d8570b0ac8ae5": "환경에서 HTTP {status}를 반환했습니다.",
1855
"b87f2217123b4cbf": "환경의 실시간 현황 설정을 업데이트하지 못했습니다.",
1856
"2f18d65ea9f178da": "환경의 실시간 현황 설정을 업데이트하지 못했습니다: {detail}",
1857
- "024b0e4154ca9170": "로컬로 페어링된 bearer 연결만 클라우드에 연결할 수 있습니다.",
1857
"52c4bcf188d1af36": "모바일 기기 ID를 불러올 수 없습니다.",
1858
"473457b89661c874": "모바일 기기 ID를 불러올 수 없습니다: {detail}",
1859
"01da8c5b0a52e84a": "환경 연결 증명을 얻을 수 없습니다.",
1860
"20732c0363a295a8": "환경 연결 증명을 가져올 수 없습니다: {detail}",
1861
"78bf018d20589722": "환경 릴레이 액세스를 구성할 수 없습니다.",
1862
"a5e3ff0d1a60b766": "환경 릴레이 액세스를 구성할 수 없습니다: {detail}",
1863
+ "013df8bdb9ca9096": "에이전트 활동 게시를 켤 수 없습니다.",
1864
+ "7247ede5160a0154": "에이전트 활동 게시를 켤 수 없습니다: {detail}",
1865
"7d508fe978cb0f3b": "꺼짐",
1866
"3ae222ec888dd171": "추적 ID:",
1867
"be00d572b18076d8": "길게 눌러 이 기기에서 제거",
apps/mobile/src/i18n/translations/pt-BR.json
+2
-1
@@ -1853,13 +1853,14 @@
1853
"c15d8570b0ac8ae5": "O ambiente retornou HTTP {status}.",
1854
"b87f2217123b4cbf": "Não foi possível atualizar a preferência de Atividades ao Vivo do ambiente.",
1855
"2f18d65ea9f178da": "Não foi possível atualizar a preferência de Atividades ao Vivo do ambiente: {detail}",
1856
- "024b0e4154ca9170": "Só uma conexão bearer pareada localmente pode ser vinculada à nuvem.",
1856
"52c4bcf188d1af36": "Não foi possível carregar o ID do dispositivo móvel.",
1857
"473457b89661c874": "Não foi possível carregar o ID do dispositivo móvel: {detail}",
1858
"01da8c5b0a52e84a": "Não foi possível obter a prova de vínculo do ambiente.",
1859
"20732c0363a295a8": "Não foi possível obter a prova de vínculo do ambiente: {detail}",
1860
"78bf018d20589722": "Não foi possível configurar o acesso do ambiente ao relay.",
1861
"a5e3ff0d1a60b766": "Não foi possível configurar o acesso do ambiente ao relay: {detail}",
1862
+ "013df8bdb9ca9096": "Não foi possível ativar a publicação da atividade do agente.",
1863
+ "7247ede5160a0154": "Não foi possível ativar a publicação da atividade do agente: {detail}",
1864
"7d508fe978cb0f3b": "Desligado",
1865
"3ae222ec888dd171": "ID do trace:",
1866
"be00d572b18076d8": "Mantenha pressionado para remover deste dispositivo",
apps/mobile/src/i18n/translations/ru.json
+2
-1
@@ -1877,13 +1877,14 @@
1877
"c15d8570b0ac8ae5": "Среда вернула HTTP {status}.",
1878
"b87f2217123b4cbf": "Не удалось обновить настройку «Эфир активности» для среды.",
1879
"2f18d65ea9f178da": "Не удалось обновить настройку «Эфир активности» для среды: {detail}",
1880
- "024b0e4154ca9170": "К облаку можно привязать только локально сопряжённое bearer-подключение.",
1880
"52c4bcf188d1af36": "Не удалось загрузить ID мобильного устройства.",
1881
"473457b89661c874": "Не удалось загрузить ID мобильного устройства: {detail}",
1882
"01da8c5b0a52e84a": "Не удалось получить подтверждение привязки окружения.",
1883
"20732c0363a295a8": "Не удалось получить подтверждение привязки окружения: {detail}",
1884
"78bf018d20589722": "Не удалось настроить доступ окружения к relay.",
1885
"a5e3ff0d1a60b766": "Не удалось настроить доступ окружения к relay: {detail}",
1886
+ "013df8bdb9ca9096": "Не удалось включить публикацию активности агента.",
1887
+ "7247ede5160a0154": "Не удалось включить публикацию активности агента: {detail}",
1888
"7d508fe978cb0f3b": "Выкл.",
1889
"3ae222ec888dd171": "ID трассировки:",
1890
"be00d572b18076d8": "Нажмите и удерживайте, чтобы удалить с этого устройства",
apps/mobile/src/i18n/translations/sv.json
+2
-1
@@ -1853,13 +1853,14 @@
1853
"c15d8570b0ac8ae5": "Miljön returnerade HTTP {status}.",
1854
"b87f2217123b4cbf": "Det gick inte att uppdatera miljöns inställning för liveaktiviteter.",
1855
"2f18d65ea9f178da": "Det gick inte att uppdatera miljöns inställning för liveaktiviteter: {detail}",
1856
- "024b0e4154ca9170": "Bara en lokalt parkopplad bearer-anslutning kan länkas till molnet.",
1856
"52c4bcf188d1af36": "Kunde inte läsa in den mobila enhetens id.",
1857
"473457b89661c874": "Kunde inte läsa in den mobila enhetens id: {detail}",
1858
"01da8c5b0a52e84a": "Kunde inte hämta bevis för miljölänken.",
1859
"20732c0363a295a8": "Kunde inte hämta miljöns länkbevis: {detail}",
1860
"78bf018d20589722": "Kunde inte konfigurera miljöns reläåtkomst.",
1861
"a5e3ff0d1a60b766": "Kunde inte konfigurera miljöns reläåtkomst: {detail}",
1862
+ "013df8bdb9ca9096": "Det gick inte att aktivera publicering av agentaktivitet.",
1863
+ "7247ede5160a0154": "Det gick inte att aktivera publicering av agentaktivitet: {detail}",
1864
"7d508fe978cb0f3b": "Av",
1865
"3ae222ec888dd171": "Spårnings-id:",
1866
"be00d572b18076d8": "Tryck länge för att ta bort från den här enheten",
apps/mobile/src/i18n/translations/zh.json
+2
-1
@@ -1855,13 +1855,14 @@
1855
"c15d8570b0ac8ae5": "环境返回了 HTTP {status}。",
1856
"b87f2217123b4cbf": "无法更新该环境的实时活动偏好设置。",
1857
"2f18d65ea9f178da": "无法更新该环境的实时活动偏好设置:{detail}",
1858
- "024b0e4154ca9170": "只有本地配对的 Bearer 连接才能关联到云端。",
1858
"52c4bcf188d1af36": "无法加载移动设备 ID。",
1859
"473457b89661c874": "无法加载移动设备 ID:{detail}",
1860
"01da8c5b0a52e84a": "无法获取环境关联凭证。",
1861
"20732c0363a295a8": "无法获取环境关联证明:{detail}",
1862
"78bf018d20589722": "无法配置环境中继访问。",
1863
"a5e3ff0d1a60b766": "无法配置环境的中继访问:{detail}",
1864
+ "013df8bdb9ca9096": "无法开启代理活动发布。",
1865
+ "7247ede5160a0154": "无法开启代理活动发布:{detail}",
1866
"7d508fe978cb0f3b": "关闭",
1867
"3ae222ec888dd171": "追踪 ID:",
1868
"be00d572b18076d8": "长按以从此设备移除",
apps/server/src/cloud/CloudLink.lifecycle.test.ts
+12
-37
@@ -11,22 +11,11 @@ import * as PlatformError from "effect/PlatformError";
11
import * as Schema from "effect/Schema";
12
import * as Stream from "effect/Stream";
13
import * as TestClock from "effect/testing/TestClock";
14
-import {
15
- HttpClient,
16
- HttpClientResponse,
17
- HttpServer,
18
- HttpServerRequest,
19
- type HttpClientRequest,
20
-} from "effect/http";
14
+import { HttpClient, HttpClientResponse, HttpServer, type HttpClientRequest } from "effect/http";
15
import { RELAY_LINK_PROOF_TYP, signRelayJwt, verifyRelayJwt } from "@t3tools/shared/relayJwt";
16
import * as NetAddress from "effect/net/NetAddress";
17
24
-import {
25
- AuthSessionId,
26
- type AuthEnvironmentScope,
27
- EnvironmentAuthenticatedPrincipal,
28
- EnvironmentId,
29
-} from "@t3tools/contracts";
18
+import { EnvironmentId } from "@t3tools/contracts";
19
import * as EnvironmentKeys from "./environmentKeys.ts";
20
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
21
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
@@ -312,30 +301,16 @@ describe("releaseManagedTunnelOnShutdown", () => {
301
});
302
yield* TestClock.setTime((relayNow + skewSeconds) * 1_000);
303
const link = yield* CloudLink.CloudLink;
315
- const proof = yield* link
316
- .linkProof(
317
- {
318
- challenge,
319
- relayIssuer,
320
- endpoint: {
321
- httpBaseUrl: "http://127.0.0.1:3773",
322
- wsBaseUrl: "ws://127.0.0.1:3773",
323
- providerKind: "manual",
324
- },
325
- origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
326
- },
327
- HttpServerRequest.fromWeb(
328
- new Request("http://127.0.0.1:3773/api/t3-connect/link-proof"),
329
- ),
330
- )
331
- .pipe(
332
- Effect.provideService(EnvironmentAuthenticatedPrincipal, {
333
- sessionId: AuthSessionId.make("test-session"),
334
- subject: "test",
335
- method: "bearer-access-token",
336
- scopes: new Set<AuthEnvironmentScope>(),
337
- }),
338
- );
304
+ const proof = yield* link.linkProof({
305
+ challenge,
306
+ relayIssuer,
307
+ endpoint: {
308
+ httpBaseUrl: "http://127.0.0.1:3773",
309
+ wsBaseUrl: "ws://127.0.0.1:3773",
310
+ providerKind: "manual",
311
+ },
312
+ origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
313
+ });
314
const environmentKeys =
315
yield* EnvironmentKeys.getOrCreateEnvironmentKeyPairFromSecretStore(store);
316
yield* TestClock.setTime(relayNow * 1_000);
apps/server/src/cloud/CloudLink.ts
+33
-53
@@ -1,5 +1,4 @@
1
import {
2
- EnvironmentAuthenticatedPrincipal,
2
type EnvironmentCloudLinkStateResult,
3
type EnvironmentCloudPreferencesRequest,
4
type EnvironmentCloudRelayConfigResult,
@@ -55,12 +54,7 @@ import type * as PlatformError from "effect/PlatformError";
54
import * as Schedule from "effect/Schedule";
55
import * as Schema from "effect/Schema";
56
import * as Semaphore from "effect/Semaphore";
58
-import {
59
- HttpClient,
60
- HttpClientRequest,
61
- HttpClientResponse,
62
- type HttpServerRequest,
63
-} from "effect/http";
57
+import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
58
import type * as HttpClientError from "effect/http/HttpClientError";
59
import * as HttpServer from "effect/http/HttpServer";
60
@@ -111,13 +105,11 @@ import {
105
import {
106
hasBoundedCloudProofLifetime,
107
hasExactScope,
114
- hasForwardedAuthorityHeaders,
115
- isAllowedEndpointOrigin,
108
+ isLoopbackEndpointOrigin,
109
isSupportedLinkProviderKind,
110
linkProofScopes,
111
managedEndpointRuntimeConfigsMatch,
112
parseManagedEndpointLocalOrigin,
120
- requestAbsoluteUrl,
113
} from "./linkChecks.ts";
114
import { desktopUpdateRestartPending, pendingUpdateHandoffExists } from "./updateHandoff.ts";
115
@@ -416,21 +408,15 @@ type ManagedTunnelRegistration =
408
export class CloudLink extends Context.Service<
409
CloudLink,
410
{
419
- /**
420
- * Signs the proof the relay asks for to link this environment. The request
421
- * must reach this server directly. Desktop bootstrap sessions may use the
422
- * WSL IP; all other sessions must use the loopback origin they name.
423
- */
411
+ /** Signs the proof the relay asks for to link this environment, for this server's own origin. */
412
readonly linkProof: (
413
request: RelayLinkProofRequest,
426
- httpRequest: HttpServerRequest.HttpServerRequest,
414
) => Effect.Effect<
415
RelayEnvironmentLinkProof,
416
| CloudLinkOriginInvalidError
417
| CloudLinkInternalError
418
| EnvironmentAuth.ServerAuthInternalError
432
- | ManagedLimits.ManagedPolicyRefusedError,
433
- EnvironmentAuthenticatedPrincipal
419
+ | ManagedLimits.ManagedPolicyRefusedError
420
>;
421
readonly applyRelayConfig: (
422
payload: RelayEnvironmentConfigRequest,
@@ -586,21 +572,28 @@ const make = Effect.gen(function* () {
572
),
573
);
574
575
+ // The tunnel must reach this server, so the signed origin is its own loopback address, never the caller's.
576
+ const serverLoopbackOrigin = Effect.gen(function* () {
577
+ const address = httpServer.address;
578
+ if (typeof address === "string" || !("port" in address)) {
579
+ return yield* new CloudLinkInternalError({ operation: "resolve-server-origin" });
580
+ }
581
+ const { origin } = parseManagedEndpointLocalOrigin(
582
+ `http://${loopbackUrlHostForAddress(address)}:${address.port}`,
583
+ );
584
+ if (!isLoopbackEndpointOrigin(origin)) {
585
+ return yield* new CloudLinkOriginInvalidError({ origin: "local" });
586
+ }
587
+ return origin;
588
+ });
589
+
590
const makeCloudLinkProof = Effect.fn("environment.cloud.makeLinkProof")(function* (
591
request: RelayLinkProofRequest,
591
- requestUrl: string,
592
- allowNonLoopbackRequestHost = false,
592
) {
594
- if (
595
- !isSupportedLinkProviderKind(request) ||
596
- !isAllowedEndpointOrigin({
597
- origin: request.origin,
598
- requestUrl,
599
- allowNonLoopbackRequestHost,
600
- })
601
- ) {
593
+ if (!isSupportedLinkProviderKind(request)) {
594
return yield* new CloudLinkOriginInvalidError({ origin: "endpoint" });
595
}
596
+ const origin = yield* serverLoopbackOrigin;
597
const now = yield* DateTime.now;
598
const nowSeconds = Math.floor(now.epochMilliseconds / 1_000);
599
// Borrow only the relay clock; the relay still verifies and consumes the challenge.
@@ -623,7 +616,7 @@ const make = Effect.gen(function* () {
616
environmentId: descriptor.environmentId,
617
environmentPublicKey: normalizePemForSignedPayload(signingKey.publicKey),
618
endpoint: request.endpoint,
626
- origin: request.origin,
619
+ origin,
620
scopes: linkProofScopes(request),
621
} satisfies RelayEnvironmentLinkProofPayload;
622
return yield* signingKey
@@ -642,18 +635,8 @@ const make = Effect.gen(function* () {
635
});
636
637
const linkProof = Effect.fn("environment.cloud.linkProof")(
645
- function* (request: RelayLinkProofRequest, httpRequest: HttpServerRequest.HttpServerRequest) {
646
- const requestUrl = requestAbsoluteUrl(httpRequest);
647
- if (requestUrl === null || hasForwardedAuthorityHeaders(httpRequest)) {
648
- return yield* new CloudLinkOriginInvalidError({ origin: "endpoint" });
649
- }
650
- const principal = yield* EnvironmentAuthenticatedPrincipal;
651
- // WSL desktop requests use the distro IP; only the server-issued bootstrap subject qualifies.
652
- return yield* makeCloudLinkProof(
653
- request,
654
- requestUrl,
655
- principal.subject === "desktop-bootstrap",
656
- );
638
+ function* (request: RelayLinkProofRequest) {
639
+ return yield* makeCloudLinkProof(request);
640
},
641
Effect.catchIf(ServerSecretStore.isSecretStoreError, internalError("generate-link-proof")),
642
);
@@ -877,19 +860,16 @@ const make = Effect.gen(function* () {
860
},
861
schema: RelayEnvironmentLinkChallengeResponse,
862
});
880
- const proof = yield* makeCloudLinkProof(
881
- {
882
- challenge: challenge.challenge,
883
- relayIssuer: relayUrl,
884
- endpoint: {
885
- httpBaseUrl: parsedOrigin.httpBaseUrl,
886
- wsBaseUrl: parsedOrigin.wsBaseUrl,
887
- providerKind: managedTunnelsEnabled ? "cloudflare_tunnel" : "manual",
888
- },
889
- origin: parsedOrigin.origin,
863
+ const proof = yield* makeCloudLinkProof({
864
+ challenge: challenge.challenge,
865
+ relayIssuer: relayUrl,
866
+ endpoint: {
867
+ httpBaseUrl: parsedOrigin.httpBaseUrl,
868
+ wsBaseUrl: parsedOrigin.wsBaseUrl,
869
+ providerKind: managedTunnelsEnabled ? "cloudflare_tunnel" : "manual",
870
},
891
- parsedOrigin.httpBaseUrl,
892
- );
871
+ origin: parsedOrigin.origin,
872
+ });
873
const link = yield* relayClientRequest({
874
url: `${relayUrl}/v1/client/environment-links`,
875
token: token.accessToken,
apps/server/src/cloud/http.test.ts
+33
-86
@@ -43,7 +43,6 @@ import * as ServerSettings from "../serverSettings.ts";
43
44
const DESKTOP_BOOTSTRAP_TOKEN = "test-desktop-bootstrap-token";
45
const NON_LOOPBACK_ORIGIN = "http://172.24.162.233:3773";
46
-const LOOPBACK_ORIGIN = "http://127.0.0.1:3773";
46
const proofRequest: RelayLinkProofRequest = {
47
challenge: "test-challenge",
48
relayIssuer: "https://relay.example.test",
@@ -160,10 +159,10 @@ const linkProofClient = Effect.gen(function* () {
159
const payload = (yield* responseJson(response)) as { access_token: string };
160
return payload.access_token;
161
});
163
- const linkableHere = (token: string, origin = NON_LOOPBACK_ORIGIN) =>
162
+ const linkableHere = (token: string) =>
163
Effect.promise(() =>
164
handler(
166
- new Request(`${origin}/api/connect/link-state`, {
165
+ new Request(`${NON_LOOPBACK_ORIGIN}/api/connect/link-state`, {
166
headers: { authorization: `Bearer ${token}` },
167
}),
168
),
@@ -174,16 +173,27 @@ const linkProofClient = Effect.gen(function* () {
173
return { post, exchange, linkableHere };
174
});
175
177
-describe("link proof over a non-loopback desktop transport", () => {
176
+describe("link proof over a non-loopback transport", () => {
177
it.effect(
179
- "signs a loopback tunnel origin after desktop bootstrap token exchange over a non-loopback host",
178
+ "signs this server's loopback origin for a remote client allowed to configure the relay",
179
() =>
180
Effect.gen(function* () {
181
const { post, exchange } = yield* linkProofClient;
183
- const token = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN);
184
- const response = yield* post("/api/connect/link-proof", proofRequest, {
185
- authorization: `Bearer ${token}`,
186
- });
182
+ const admin = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN);
183
+ const paired = yield* post(
184
+ "/api/auth/pairing-token",
185
+ { scopes: ["relay:read", "relay:configure"] },
186
+ { authorization: `Bearer ${admin}` },
187
+ );
188
+ expect(paired.status).toBe(200);
189
+ const { credential } = (yield* responseJson(paired)) as { credential: string };
190
+ const token = yield* exchange(credential);
191
+ // The caller's origin and forwarding headers must not steer the tunnel elsewhere.
192
+ const response = yield* post(
193
+ "/api/connect/link-proof",
194
+ { ...proofRequest, origin: { localHttpHost: "172.24.162.233", localHttpPort: 5432 } },
195
+ { authorization: `Bearer ${token}`, "x-forwarded-host": "evil.example.test" },
196
+ );
197
expect(response.status).toBe(200);
198
expect(response.headers.get("cache-control")).toBe("no-store");
199
const proof = (yield* responseJson(response)) as string;
@@ -199,90 +209,27 @@ describe("link proof over a non-loopback desktop transport", () => {
209
audience: proofRequest.relayIssuer,
210
});
211
expect(verified).toMatchObject({
202
- origin: proofRequest.origin,
212
+ origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
213
endpoint: proofRequest.endpoint,
214
challenge: proofRequest.challenge,
215
});
216
}).pipe(Effect.provide(NodeCrypto.layerSignature)),
217
);
218
209
- it.effect(
210
- "does not pass desktop trust to a paired client or accept client-supplied provenance",
211
- () =>
212
- Effect.gen(function* () {
213
- const { post, exchange, linkableHere } = yield* linkProofClient;
214
- const desktop = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN);
215
- const paired = yield* post(
216
- "/api/auth/pairing-token",
217
- {
218
- scopes: ["relay:read", "relay:configure"],
219
- label: "desktop-bootstrap",
220
- subject: "desktop-bootstrap",
221
- },
222
- { authorization: `Bearer ${desktop}` },
223
- );
224
- expect(paired.status).toBe(200);
225
- const { credential } = (yield* responseJson(paired)) as { credential: string };
226
- const token = yield* exchange(credential);
227
- const headers = { authorization: `Bearer ${token}`, "x-desktop-bootstrap": "true" };
228
- const payload = {
229
- ...proofRequest,
230
- allowNonLoopbackRequestHost: true,
231
- subject: "desktop-bootstrap",
232
- };
233
- const rejected = yield* post("/api/connect/link-proof", payload, headers);
234
- expect(rejected.status).toBe(400);
235
- expect(yield* responseJson(rejected)).toMatchObject({
236
- message: "Invalid managed endpoint origin.",
237
- });
238
- const loopback = yield* post(
239
- "/api/connect/link-proof",
240
- proofRequest,
241
- headers,
242
- LOOPBACK_ORIGIN,
243
- );
244
- expect(loopback.status).toBe(200);
245
- // Clients offer Turn on only to the desktop's own session; SSH forwards look like loopback.
246
- expect(yield* linkableHere(desktop)).toBe(true);
247
- expect(yield* linkableHere(token)).toBe(false);
248
- expect(yield* linkableHere(token, LOOPBACK_ORIGIN)).toBe(false);
249
- }),
250
- );
251
-
252
- it.effect.each([
253
- {
254
- name: "non-loopback tunnel origin",
255
- origin: { localHttpHost: "172.24.162.233", localHttpPort: 3773 },
256
- headers: {},
257
- },
258
- {
259
- name: "mismatched port",
260
- origin: { localHttpHost: "127.0.0.1", localHttpPort: 3774 },
261
- headers: {},
262
- },
263
- {
264
- name: "forwarded host",
265
- origin: proofRequest.origin,
266
- headers: { "x-forwarded-host": "127.0.0.1:3773" },
267
- },
268
- {
269
- name: "forwarded protocol",
270
- origin: proofRequest.origin,
271
- headers: { "x-forwarded-proto": "http" },
272
- },
273
- ])("rejects $name even for desktop bootstrap", ({ origin, headers }) =>
219
+ it.effect("offers Turn on to any session allowed to configure the relay", () =>
220
Effect.gen(function* () {
275
- const { post, exchange } = yield* linkProofClient;
276
- const token = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN);
277
- const response = yield* post(
278
- "/api/connect/link-proof",
279
- { ...proofRequest, origin },
280
- { ...headers, authorization: `Bearer ${token}` },
281
- );
282
- expect(response.status).toBe(400);
283
- expect(yield* responseJson(response)).toMatchObject({
284
- message: "Invalid managed endpoint origin.",
285
- });
221
+ const { post, exchange, linkableHere } = yield* linkProofClient;
222
+ const desktop = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN);
223
+ const pair = (scopes: ReadonlyArray<string>) =>
224
+ post("/api/auth/pairing-token", { scopes }, { authorization: `Bearer ${desktop}` }).pipe(
225
+ Effect.flatMap(responseJson),
226
+ Effect.flatMap((paired) => exchange((paired as { credential: string }).credential)),
227
+ );
228
+ expect(yield* linkableHere(desktop)).toBe(true);
229
+ const remote = yield* pair(["relay:read", "relay:write", "relay:configure"]);
230
+ expect(yield* linkableHere(remote)).toBe(true);
231
+ expect(yield* linkableHere(yield* pair(["relay:read", "relay:write"]))).toBe(false);
232
+ expect(yield* linkableHere(yield* pair(["relay:read", "relay:configure"]))).toBe(false);
233
}),
234
);
235
apps/server/src/cloud/http.ts
+7
-6
@@ -12,7 +12,7 @@ import {
12
} from "@t3tools/contracts";
13
import * as Effect from "effect/Effect";
14
import * as HttpEffect from "effect/http/HttpEffect";
15
-import { HttpServerRequest, HttpServerResponse } from "effect/http";
15
+import { HttpServerResponse } from "effect/http";
16
import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
17
18
import { requireEnvironmentScope } from "../auth/http.ts";
@@ -20,7 +20,6 @@ import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
20
import * as ManagedLimits from "../policy/managedLimits.ts";
21
import * as CloudLink from "./CloudLink.ts";
22
import * as ConnectReachability from "./ConnectReachability.ts";
23
-import { canLinkHere } from "./linkChecks.ts";
23
import type { RelayRequestError } from "./relayResponse.ts";
24
import { traceRelayRequest } from "./traceRelayRequest.ts";
25
@@ -119,8 +118,7 @@ export const layer = HttpApiBuilder.group(
118
.handle("linkProof", ({ payload }) =>
119
Effect.gen(function* () {
120
yield* requireEnvironmentScope(AuthRelayConfigureScope);
122
- const request = yield* HttpServerRequest.HttpServerRequest;
123
- const proof = yield* toHttpError(cloudLink.linkProof(payload, request));
121
+ const proof = yield* toHttpError(cloudLink.linkProof(payload));
122
yield* appendCloudCredentialResponseHeaders;
123
return proof;
124
}),
@@ -135,8 +133,11 @@ export const layer = HttpApiBuilder.group(
133
Effect.gen(function* () {
134
const principal = yield* requireEnvironmentScope(AuthRelayReadScope);
135
const state = yield* toHttpError(cloudLink.linkState());
138
- const request = yield* HttpServerRequest.HttpServerRequest;
139
- return { ...state, linkableHere: canLinkHere(request, principal.subject) };
136
+ // Linking also writes relay preferences, so configure alone cannot finish it.
137
+ const linkableHere =
138
+ principal.scopes.has(AuthRelayConfigureScope) &&
139
+ principal.scopes.has(AuthRelayWriteScope);
140
+ return { ...state, linkableHere };
141
}),
142
)
143
.handle("checkReachability", () =>
apps/server/src/cloud/linkChecks.ts
+2
-59
@@ -4,7 +4,6 @@ import type {
4
RelayManagedEndpointOrigin,
5
RelayManagedEndpointRuntimeConfig,
6
} from "@t3tools/contracts/relay";
7
-import type { HttpServerRequest } from "effect/http";
7
8
const CLOUD_PROOF_MAX_LIFETIME_SECONDS = 5 * 60;
9
const CLOUD_PROOF_CLOCK_SKEW_SECONDS = 60;
@@ -21,33 +20,6 @@ function isLoopbackHostname(hostname: string): boolean {
20
return LOOPBACK_HOSTNAMES.has(normalizeHostname(hostname));
21
}
22
24
-function firstForwardedHeaderValue(value: string | undefined): string | undefined {
25
- const first = value?.split(",")[0]?.trim();
26
- return first && first.length > 0 ? first : undefined;
27
-}
28
-
29
-export function requestAbsoluteUrl(request: HttpServerRequest.HttpServerRequest): string | null {
30
- try {
31
- return new URL(request.originalUrl).href;
32
- } catch {
33
- const host = firstForwardedHeaderValue(request.headers.host) ?? "127.0.0.1";
34
- try {
35
- return new URL(request.originalUrl, `http://${host}`).href;
36
- } catch {
37
- return null;
38
- }
39
- }
40
-}
41
-
42
-export function hasForwardedAuthorityHeaders(
43
- request: HttpServerRequest.HttpServerRequest,
44
-): boolean {
45
- return (
46
- firstForwardedHeaderValue(request.headers["x-forwarded-host"]) !== undefined ||
47
- firstForwardedHeaderValue(request.headers["x-forwarded-proto"]) !== undefined
48
- );
49
-}
50
-
23
function endpointRequestPort(url: URL): number {
24
return Number(url.port || (url.protocol === "https:" ? 443 : 80));
25
}
@@ -79,37 +51,8 @@ export function parseManagedEndpointLocalOrigin(localOrigin: string) {
51
};
52
}
53
82
-/**
83
- * Whether clients should offer to turn on T3 Connect over this session: only the desktop app's
84
- * own bootstrap session, from any address (WSL answers on a distro IP), never through a proxy.
85
- * A loopback address alone does not count, since SSH port forwards look like loopback too.
86
- */
87
-export function canLinkHere(
88
- request: HttpServerRequest.HttpServerRequest,
89
- subject: string,
90
-): boolean {
91
- return (
92
- subject === "desktop-bootstrap" &&
93
- requestAbsoluteUrl(request) !== null &&
94
- !hasForwardedAuthorityHeaders(request)
95
- );
96
-}
97
-
98
-export function isAllowedEndpointOrigin(input: {
99
- readonly origin: RelayManagedEndpointOrigin;
100
- readonly requestUrl: string;
101
- readonly allowNonLoopbackRequestHost?: boolean;
102
-}): boolean {
103
- if (!isLoopbackHostname(input.origin.localHttpHost)) {
104
- return false;
105
- }
106
-
107
- const url = new URL(input.requestUrl);
108
- if (!input.allowNonLoopbackRequestHost && !isLoopbackHostname(url.hostname)) {
109
- return false;
110
- }
111
-
112
- return input.origin.localHttpPort === endpointRequestPort(url);
54
+export function isLoopbackEndpointOrigin(origin: RelayManagedEndpointOrigin): boolean {
55
+ return isLoopbackHostname(origin.localHttpHost);
56
}
57
58
export function isSupportedLinkProviderKind(request: RelayLinkProofRequest): boolean {
apps/web/src/cloud/t3ConnectState.ts
+1
-6
@@ -69,7 +69,6 @@ export type T3ConnectTurnOn =
69
* `linkableHere` is the environment's own answer for this session (its link state).
70
*/
71
export function resolveT3ConnectTurnOn(input: {
72
- readonly desktopApp: boolean;
72
readonly linkableHere: boolean;
73
readonly cloudConfigured: boolean;
74
readonly canReadRelay: boolean;
@@ -77,11 +76,7 @@ export function resolveT3ConnectTurnOn(input: {
76
readonly connectDenial: string | undefined;
77
}): T3ConnectTurnOn {
78
if (input.connectDenial !== undefined) return { kind: "policy", reason: input.connectDenial };
80
- return input.desktopApp &&
81
- input.linkableHere &&
82
- input.cloudConfigured &&
83
- input.canReadRelay &&
84
- input.canWriteRelay
79
+ return input.linkableHere && input.cloudConfigured && input.canReadRelay && input.canWriteRelay
80
? { kind: "here" }
81
: { kind: "on-host" };
82
}
apps/web/src/cloud/useT3ConnectTurnOn.ts
+3
-3
@@ -1,10 +1,10 @@
1
import {
2
AuthRelayReadScope,
3
+ AuthRelayWriteScope,
4
type EnvironmentId,
5
managedCapabilityDenial,
6
} from "@t3tools/contracts";
7
7
-import { isElectron } from "../env";
8
import { useManagedPolicy } from "../state/managedPolicy";
9
import { useEnvironmentCanConfigureRelay, useEnvironmentScope } from "../state/session";
10
import { useCloudLinkState } from "./cloudLinkState";
@@ -14,16 +14,16 @@ import { resolveT3ConnectTurnOn } from "./t3ConnectState";
14
/** Whether this client can turn on T3 Connect for `environmentId`, and if not, why. */
15
export function useT3ConnectTurnOn(environmentId: EnvironmentId | null) {
16
const canReadRelay = useEnvironmentScope(environmentId, AuthRelayReadScope);
17
+ const canWriteRelay = useEnvironmentScope(environmentId, AuthRelayWriteScope);
18
const canConfigureRelay = useEnvironmentCanConfigureRelay(environmentId);
19
const connectDenial = managedCapabilityDenial(useManagedPolicy(environmentId), "connect");
20
const linkState = useCloudLinkState(environmentId).data;
21
return resolveT3ConnectTurnOn({
21
- desktopApp: isElectron,
22
// Unknown while loading and on older servers, which keep today's switch in Settings.
23
linkableHere: linkState?.linkableHere ?? true,
24
cloudConfigured: hasCloudPublicConfig(),
25
canReadRelay,
26
- canWriteRelay: canConfigureRelay,
26
+ canWriteRelay: canWriteRelay && canConfigureRelay,
27
connectDenial,
28
});
29
}
apps/web/src/components/settings/SavedEnvironmentRows.tsx
+4
-5
@@ -51,7 +51,6 @@ import {
51
supportsDesktopAppUpdate,
52
} from "~/versionSkew";
53
import { hasCloudPublicConfig } from "~/cloud/publicConfig";
54
-import { isElectron } from "~/env";
54
import { useT3ConnectTurnOn } from "~/cloud/useT3ConnectTurnOn";
55
import { useCloudLinkController } from "~/cloud/useCloudLinkController";
56
import { useManagedTunnelUsage } from "~/cloud/managedRelayState";
@@ -594,8 +593,8 @@ function ConfiguredCloudLinkRow({
593
messages,
594
);
595
const turnOn = useT3ConnectTurnOn(environmentId);
597
- // Turning on links from this desktop's own backend only; turning off works from anywhere.
598
- const showSwitch = isElectron && (turnOn.kind !== "on-host" || managedTunnelActive);
596
+ // Turning on needs relay configuration permission; turning off works from anywhere.
597
+ const showSwitch = turnOn.kind !== "on-host" || managedTunnelActive;
598
const [isUpdating, setIsUpdating] = useState(false);
599
const [isUpdatingPreference, setIsUpdatingPreference] = useState(false);
600
@@ -774,12 +773,12 @@ function ConfiguredCloudLinkRow({
773
"This environment was removed from T3 Connect. Run `t3 connect link` on the host to link it again.",
774
)}
775
/>
777
- ) : isElectron ? (
776
+ ) : (
777
<SettingsRow
778
title={setting("t3-connect").title}
779
description={gt("Run `t3 connect link` on the host, then restart T3 Code there.")}
780
/>
782
- ) : null}
781
+ )}
782
{signedOut && showSwitch ? null : (
783
<SettingsRow
784
title={setting("publish-agent-activity").title}
docs/internals/t3-connect.md
+6
-3
@@ -82,9 +82,12 @@ devices working and lists them for review, including any that got in before.
82
See `issueConnectCredential` in the
83
[environment auth service](../../apps/server/src/auth/EnvironmentAuth.ts).
84
85
-Managed tunnels expose only a validated loopback HTTP origin. Link proof checks
86
-reject forwarded authority headers, and the relay resolves endpoints from its
87
-own managed allocations rather than a caller-supplied URL. Health and mint
85
+Managed tunnels expose only this server's own loopback HTTP origin. The link
86
+proof signs that origin from the server's listening address and ignores the
87
+caller's, so any client holding `relay:configure`, local or remote, can link
88
+without being able to point the tunnel at another service on the host. The
89
+relay resolves endpoints from its own managed allocations rather than a
90
+caller-supplied URL. Health and mint
91
requests must not follow redirects. These restrictions keep endpoint discovery
92
from turning into arbitrary relay egress or exposing another service on the
93
environment host.
docs/user/remote-access.md
+7
-2
@@ -495,8 +495,13 @@ page, or **Settings → T3 Connect** on mobile, and choose **Deregister**. This
495
revokes its cloud access and frees its host space even when the environment is
496
offline or has been wiped. When T3 Connect rejects a host's link, the host
497
shows that it was removed from T3 Connect. To link it again, turn on
498
-**T3 Connect** in **Settings → Sharing & access** on a desktop host, or run
499
-`t3 connect link` on a command-line host and then restart T3 Code there. A
498
+**T3 Connect** in **Settings → Sharing & access** on web or desktop, or turn on
499
+**Live Activity Updates** in **Settings → Notifications** on mobile; if it is
500
+already on, turn it off and on again. Either needs a client paired with
501
+`relay:read`, `relay:write`, and `relay:configure`. The desktop app's own session
502
+and the startup pairing link include all three; a pairing link created in
503
+**Settings → Sharing & access** needs `relay:configure` selected. You can also
504
+run `t3 connect link` on the host and then restart T3 Code there. A
505
command-line host that released its tunnel when it last stopped may link itself
506
again on its next start; run `t3 connect unlink` on that host to keep it off.
507
Removing an environment from a device's connection settings only forgets it on