The best way to control Claude Code, Codex and more from any computer or phone
fix(connect): restrict relay configuration and token destinations (#37823)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Nov 18, 2026 at 20:26 UTC
a941ab544d4b30765aaf50d8447eee12630c5486
57 files changed
+1085
-173
apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts
+90
-14
@@ -1,5 +1,7 @@
1
import { beforeEach, vi } from "vite-plus/test";
2
import { describe, expect, it } from "@effect/vitest";
3
+import * as Exit from "effect/Exit";
4
+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";
@@ -40,6 +42,16 @@ vi.mock("./remoteRegistration", () => ({
42
updateAgentAwarenessRegistrationPreferences: vi.fn(() => Effect.void),
43
}));
44
45
+const updateEnvironment = vi.fn<
46
+ (
47
+ id: EnvironmentId,
48
+ enabled: boolean,
49
+ ) => Effect.Effect<
50
+ "updated" | "unlinked" | "unsupported" | "disconnected",
51
+ CloudEnvironmentLinkError
52
+ >
53
+>(() => Effect.succeed("updated"));
54
+
55
const connection: SavedRemoteConnection = {
56
environmentId: "env-1" as EnvironmentId,
57
environmentLabel: "Desktop",
@@ -75,43 +87,80 @@ describe("liveActivityPreferences", () => {
87
vi.clearAllMocks();
88
});
89
78
- it.effect("restores relay preferences when an environment update fails", () => {
79
- vi.mocked(linkEnvironmentToCloudWithPreference).mockImplementationOnce(() =>
90
+ it.effect("restores only the device preference when an environment update fails", () => {
91
+ const otherConnection = { ...connection, environmentId: "env-2" as EnvironmentId };
92
+ updateEnvironment.mockImplementationOnce(() =>
93
Effect.fail(new CloudEnvironmentLinkError({ message: "environment update failed" })),
94
);
95
96
return Effect.gen(function* () {
97
const exit = yield* Effect.exit(
98
setLiveActivityUpdatesEnabled({
99
+ updateEnvironment,
100
enabled: false,
101
previousEnabled: true,
102
clerkToken: "clerk-token",
89
- connections: [connection],
90
- canConfigureEnvironment: () => true,
103
+ connections: [connection, otherConnection],
104
+ canConfigureEnvironment: () => false,
105
+ canUpdateEnvironment: () => true,
106
}),
107
);
108
94
- expect(exit._tag).toBe("Failure");
109
+ expect(Exit.findErrorOption(exit)).toEqual(
110
+ Option.some(
111
+ expect.objectContaining({ updatedEnvironments: [otherConnection.environmentLabel] }),
112
+ ),
113
+ );
114
expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenNthCalledWith(1, {
115
liveActivitiesEnabled: false,
116
});
117
expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenNthCalledWith(2, {
118
liveActivitiesEnabled: true,
119
});
101
- expect(linkEnvironmentToCloudWithPreference).toHaveBeenNthCalledWith(1, {
102
- clerkToken: "clerk-token",
103
- connection,
120
+ expect(updateEnvironment).toHaveBeenCalledTimes(2);
121
+ expect(updateEnvironment).toHaveBeenCalledWith(connection.environmentId, false);
122
+ expect(updateEnvironment).toHaveBeenCalledWith(otherConnection.environmentId, false);
123
+ expect(linkEnvironmentToCloudWithPreference).not.toHaveBeenCalled();
124
+ }).pipe(Effect.provide(layerTest));
125
+ });
126
+
127
+ it.effect("reports a relay preference committed before environment configuration fails", () => {
128
+ const failure = new CloudEnvironmentLinkError({
129
+ message: "environment configuration failed",
130
+ relayLinkCommitted: true,
131
+ });
132
+ updateEnvironment.mockReturnValueOnce(Effect.succeed("unlinked"));
133
+ vi.mocked(linkEnvironmentToCloudWithPreference).mockReturnValueOnce(Effect.fail(failure));
134
+
135
+ return Effect.gen(function* () {
136
+ const exit = yield* Effect.exit(
137
+ setLiveActivityUpdatesEnabled({
138
+ updateEnvironment,
139
+ enabled: true,
140
+ previousEnabled: false,
141
+ clerkToken: "clerk-token",
142
+ connections: [connection],
143
+ canConfigureEnvironment: () => true,
144
+ canUpdateEnvironment: () => true,
145
+ }),
146
+ );
147
+
148
+ expect(Exit.findErrorOption(exit)).toEqual(
149
+ Option.some(
150
+ expect.objectContaining({
151
+ updatedEnvironments: [connection.environmentLabel],
152
+ cause: failure,
153
+ }),
154
+ ),
155
+ );
156
+ expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenLastCalledWith({
157
liveActivitiesEnabled: false,
158
});
106
- expect(linkEnvironmentToCloudWithPreference).toHaveBeenNthCalledWith(2, {
107
- clerkToken: "clerk-token",
108
- connection,
109
- liveActivitiesEnabled: true,
110
- });
159
}).pipe(Effect.provide(layerTest));
160
});
161
114
- it.effect("only re-links environments with relay access when enabling updates", () => {
162
+ it.effect("only creates missing links when the session can configure Connect", () => {
163
+ updateEnvironment.mockReturnValueOnce(Effect.succeed("unlinked" as const));
164
const readOnlyConnection: SavedRemoteConnection = {
165
...connection,
166
environmentId: "read-only" as EnvironmentId,
@@ -119,10 +168,12 @@ describe("liveActivityPreferences", () => {
168
169
return Effect.gen(function* () {
170
yield* setLiveActivityUpdatesEnabled({
171
+ updateEnvironment,
172
enabled: true,
173
previousEnabled: false,
174
clerkToken: "clerk-token",
175
connections: [readOnlyConnection, connection],
176
+ canUpdateEnvironment: (environmentId) => environmentId === connection.environmentId,
177
canConfigureEnvironment: (environmentId) => environmentId === connection.environmentId,
178
});
179
@@ -137,6 +188,28 @@ describe("liveActivityPreferences", () => {
188
}).pipe(Effect.provide(layerTest));
189
});
190
191
+ it.effect("reports older environments whose preferences could not be updated", () =>
192
+ Effect.gen(function* () {
193
+ const dpopConnection: SavedRemoteConnection = {
194
+ ...connection,
195
+ bearerToken: null,
196
+ authenticationMethod: "dpop",
197
+ };
198
+ updateEnvironment.mockReturnValueOnce(Effect.succeed("unsupported"));
199
+ const partial = yield* setLiveActivityUpdatesEnabled({
200
+ updateEnvironment,
201
+ enabled: false,
202
+ previousEnabled: true,
203
+ clerkToken: "clerk-token",
204
+ connections: [dpopConnection],
205
+ canConfigureEnvironment: () => false,
206
+ canUpdateEnvironment: () => true,
207
+ });
208
+ expect(partial).toBe(true);
209
+ expect(linkEnvironmentToCloudWithPreference).not.toHaveBeenCalled();
210
+ }).pipe(Effect.provide(layerTest)),
211
+ );
212
+
213
it.effect("checks current relay access after updating the device registration", () => {
214
let canConfigureEnvironment = true;
215
vi.mocked(updateAgentAwarenessRegistrationPreferences).mockImplementationOnce(() =>
@@ -147,14 +220,17 @@ describe("liveActivityPreferences", () => {
220
221
return Effect.gen(function* () {
222
yield* setLiveActivityUpdatesEnabled({
223
+ updateEnvironment,
224
enabled: false,
225
previousEnabled: true,
226
clerkToken: "clerk-token",
227
connections: [connection],
228
canConfigureEnvironment: () => canConfigureEnvironment,
229
+ canUpdateEnvironment: () => canConfigureEnvironment,
230
});
231
232
expect(linkEnvironmentToCloudWithPreference).not.toHaveBeenCalled();
233
+ expect(updateEnvironment).not.toHaveBeenCalled();
234
expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenCalledTimes(1);
235
}).pipe(Effect.provide(layerTest));
236
});
apps/mobile/src/features/agent-awareness/liveActivityPreferences.ts
+69
-38
@@ -1,34 +1,63 @@
1
import * as Effect from "effect/Effect";
2
+import * as Result from "effect/Result";
3
+import * as Schema from "effect/Schema";
4
import type { EnvironmentId } from "@t3tools/contracts";
5
6
import type { SavedRemoteConnection } from "../../lib/connection";
5
-import { linkEnvironmentToCloudWithPreference } from "../cloud/linkEnvironment";
7
+import {
8
+ linkEnvironmentToCloudWithPreference,
9
+ type CloudEnvironmentLinkError,
10
+} from "../cloud/linkEnvironment";
11
import { updateAgentAwarenessRegistrationPreferences } from "./remoteRegistration";
12
13
+export class LiveActivityEnvironmentUpdateError extends Schema.TaggedError<LiveActivityEnvironmentUpdateError>()(
14
+ "LiveActivityEnvironmentUpdateError",
15
+ {
16
+ updatedEnvironments: Schema.Array(Schema.String),
17
+ cause: Schema.Defect(),
18
+ },
19
+) {}
20
+
21
export const setLiveActivityUpdatesEnabled = Effect.fn("setLiveActivityUpdatesEnabled")(
22
function* (input: {
23
readonly enabled: boolean;
24
readonly previousEnabled: boolean;
25
readonly clerkToken: string | null;
26
readonly connections: ReadonlyArray<SavedRemoteConnection>;
27
+ readonly updateEnvironment: (
28
+ environmentId: EnvironmentId,
29
+ enabled: boolean,
30
+ ) => Effect.Effect<
31
+ "updated" | "unlinked" | "unsupported" | "disconnected",
32
+ CloudEnvironmentLinkError
33
+ >;
34
+ readonly canUpdateEnvironment: (environmentId: EnvironmentId) => boolean;
35
readonly canConfigureEnvironment: (environmentId: EnvironmentId) => boolean;
36
}) {
16
- const linkedConnections = input.connections.filter(
17
- (connection) => connection.bearerToken !== null,
18
- );
19
-
37
const updateEnvironmentPreference = Effect.fn("updateEnvironmentPreference")(function* (
38
connection: SavedRemoteConnection,
39
enabled: boolean,
23
- clerkToken: string,
40
+ clerkToken: string | null,
41
) {
25
- if (!input.canConfigureEnvironment(connection.environmentId)) return;
42
+ const result = input.canUpdateEnvironment(connection.environmentId)
43
+ ? yield* input.updateEnvironment(connection.environmentId, enabled)
44
+ : "unlinked";
45
+ if (result === "updated" || result === "disconnected") return result;
46
+ if (
47
+ !enabled ||
48
+ !clerkToken ||
49
+ !connection.bearerToken ||
50
+ !input.canConfigureEnvironment(connection.environmentId)
51
+ ) {
52
+ return result;
53
+ }
54
55
yield* linkEnvironmentToCloudWithPreference({
56
clerkToken,
57
connection,
58
liveActivitiesEnabled: enabled,
59
});
60
+ return "updated" as const;
61
});
62
63
const updateRelayPreference = Effect.fn("updateRelayPreference")(function* (enabled: boolean) {
@@ -37,44 +66,46 @@ export const setLiveActivityUpdatesEnabled = Effect.fn("setLiveActivityUpdatesEn
66
});
67
68
const clerkToken = input.clerkToken;
40
- if (!clerkToken) return;
41
-
42
- yield* Effect.forEach(
43
- linkedConnections,
44
- (connection) => updateEnvironmentPreference(connection, enabled, clerkToken),
45
- { concurrency: "unbounded" },
46
- );
47
- });
48
-
49
- const restoreRelayPreference = Effect.fn("restoreRelayPreference")(function* () {
50
- yield* updateAgentAwarenessRegistrationPreferences({
51
- liveActivitiesEnabled: input.previousEnabled,
52
- }).pipe(
53
- Effect.catchCause((cause) =>
54
- Effect.logWarning("Could not restore Live Activity device preference.", cause),
55
- ),
56
- );
57
-
58
- const clerkToken = input.clerkToken;
59
- if (!clerkToken) return;
69
+ if (!clerkToken) return false;
70
61
- yield* Effect.forEach(
62
- linkedConnections,
71
+ const results = yield* Effect.forEach(
72
+ input.connections,
73
(connection) =>
64
- updateEnvironmentPreference(connection, input.previousEnabled, clerkToken).pipe(
65
- Effect.catchCause((cause) =>
66
- Effect.logWarning(
67
- `Could not restore Live Activity preference for environment ${connection.environmentId}.`,
68
- cause,
69
- ),
70
- ),
74
+ updateEnvironmentPreference(connection, enabled, clerkToken).pipe(
75
+ Effect.result,
76
+ Effect.map((result) => ({ connection, result })),
77
),
78
{ concurrency: "unbounded" },
79
);
80
+ const failure = results.find(({ result }) => Result.isFailure(result));
81
+ if (failure && Result.isFailure(failure.result)) {
82
+ const updatedEnvironments = results.flatMap(({ connection, result }) => {
83
+ const changed = Result.isSuccess(result)
84
+ ? result.success === "updated"
85
+ : result.failure.relayLinkCommitted === true;
86
+ return changed ? [connection.environmentLabel] : [];
87
+ });
88
+ if (updatedEnvironments.length === 0) return yield* failure.result.failure;
89
+ return yield* new LiveActivityEnvironmentUpdateError({
90
+ updatedEnvironments,
91
+ cause: failure.result.failure,
92
+ });
93
+ }
94
+ return results.some(
95
+ ({ result }) => Result.isSuccess(result) && result.success === "unsupported",
96
+ );
97
});
98
76
- yield* updateRelayPreference(input.enabled).pipe(
77
- Effect.onError(() => restoreRelayPreference()),
99
+ return yield* updateRelayPreference(input.enabled).pipe(
100
+ Effect.onError(() =>
101
+ updateAgentAwarenessRegistrationPreferences({
102
+ liveActivitiesEnabled: input.previousEnabled,
103
+ }).pipe(
104
+ Effect.catchCause((cause) =>
105
+ Effect.logWarning("Could not restore Live Activity device preference.", cause),
106
+ ),
107
+ ),
108
+ ),
109
);
110
},
111
);
apps/mobile/src/features/cloud/linkEnvironment.test.ts
+40
-2
@@ -1,16 +1,27 @@
1
import { beforeEach, vi } from "vite-plus/test";
2
import { describe, expect, it } from "@effect/vitest";
3
import * as Effect from "effect/Effect";
4
+import * as Option from "effect/Option";
5
+import * as SubscriptionRef from "effect/SubscriptionRef";
6
import * as Layer from "effect/Layer";
7
import { EnvironmentId } from "@t3tools/contracts";
8
import { RelayMobileClientId } from "@t3tools/contracts/relay";
9
+import {
10
+ EnvironmentSupervisor,
11
+ AVAILABLE_CONNECTION_STATE,
12
+ PrimaryConnectionTarget,
13
+ type PreparedConnection,
14
+} from "@t3tools/client-runtime/connection";
15
import { ManagedRelay } from "@t3tools/client-runtime/relay";
8
-import { layerRemoteHttpClient } from "@t3tools/client-runtime/rpc";
16
+import { layerRemoteHttpClient, type RpcSession } from "@t3tools/client-runtime/rpc";
17
import { HttpClient } from "effect/http";
18
19
import * as MobileStorage from "../../persistence/mobile-storage";
20
13
-import { linkEnvironmentToCloudWithPreference } from "./linkEnvironment";
21
+import {
22
+ linkEnvironmentToCloudWithPreference,
23
+ updateLinkedEnvironmentLiveActivityPreference,
24
+} from "./linkEnvironment";
25
26
vi.mock("expo-constants", () => ({
27
default: {
@@ -146,6 +157,33 @@ describe("mobile cloud link environment client", () => {
157
createProofMock.mockClear();
158
});
159
160
+ it.effect("skips Live Activity updates when the environment has no prepared connection", () =>
161
+ Effect.gen(function* () {
162
+ const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
163
+ target: new PrimaryConnectionTarget({
164
+ environmentId: savedConnection.environmentId,
165
+ label: savedConnection.environmentLabel,
166
+ httpBaseUrl: savedConnection.httpBaseUrl,
167
+ wsBaseUrl: savedConnection.wsBaseUrl,
168
+ }),
169
+ state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
170
+ session: yield* SubscriptionRef.make(Option.none<RpcSession>()),
171
+ prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
172
+ connect: Effect.void,
173
+ disconnect: Effect.void,
174
+ retryNow: Effect.void,
175
+ });
176
+ const result = yield* updateLinkedEnvironmentLiveActivityPreference(true).pipe(
177
+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
178
+ Effect.provideService(
179
+ HttpClient.HttpClient,
180
+ HttpClient.make(() => Effect.die("unexpected HTTP request")),
181
+ ),
182
+ );
183
+ expect(result).toBe("disconnected");
184
+ }),
185
+ );
186
+
187
it.effect(
188
"rejects relay link credentials for a different environment before persisting relay config",
189
() =>
apps/mobile/src/features/cloud/linkEnvironment.ts
+68
-2
@@ -1,6 +1,8 @@
1
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";
3
-import { HttpClient } from "effect/http";
5
+import { HttpClient, type HttpClientResponse } from "effect/http";
6
import {
7
EnvironmentCloudEndpointUnavailableError,
8
EnvironmentHttpBadRequestError,
@@ -10,13 +12,16 @@ import {
12
EnvironmentHttpUnauthorizedError,
13
} from "@t3tools/contracts";
14
import {
15
+ RelayOkResponse,
16
type RelayEnvironmentLinkResponse as RelayEnvironmentLinkResponseType,
17
type RelayManagedEndpointProviderKind,
18
} from "@t3tools/contracts/relay";
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";
23
24
+import { executeConnectedEnvironmentHttpRequest } from "@t3tools/client-runtime/state/environmentHttpAuth";
25
import { msg } from "gt-react-native";
26
27
import { m } from "../../i18n/messages";
@@ -34,6 +39,7 @@ export class CloudEnvironmentLinkError extends Schema.TaggedError<CloudEnvironme
39
message: Schema.String,
40
cause: Schema.optional(Schema.Defect()),
41
traceId: Schema.optional(Schema.String),
42
+ relayLinkCommitted: Schema.optionalKey(Schema.Literal(true)),
43
},
44
) {}
45
@@ -51,7 +57,11 @@ const isEnvironmentCloudApiError = Schema.is(
57
const MANAGED_ENDPOINT_PROVIDER_KIND =
58
"cloudflare_tunnel" satisfies RelayManagedEndpointProviderKind;
59
54
-function cloudEnvironmentLinkError(message: string, withDetail: (detail: string) => string) {
60
+function cloudEnvironmentLinkError(
61
+ message: string,
62
+ withDetail: (detail: string) => string,
63
+ options?: { readonly relayLinkCommitted: true },
64
+) {
65
return (cause: unknown) => {
66
const environmentError = findEnvironmentCloudApiError(cause);
67
const traceId = findErrorTraceId(cause);
@@ -61,6 +71,7 @@ function cloudEnvironmentLinkError(message: string, withDetail: (detail: string)
71
return new CloudEnvironmentLinkError({
72
message: detail,
73
cause,
74
+ ...options,
75
...(traceId === null ? {} : { traceId }),
76
});
77
};
@@ -162,6 +173,60 @@ type LinkEnvironmentToCloudRequirements =
173
| ManagedRelay.ManagedRelayClient
174
| MobileStorage.MobileStorage;
175
176
+const decodeRelayOkResponse = Schema.decodeUnknownEffect(RelayOkResponse);
177
+
178
+export const updateLinkedEnvironmentLiveActivityPreference = Effect.fn(
179
+ "linkEnvironment.updateLinkedEnvironmentLiveActivityPreference",
180
+)(function* (liveActivitiesEnabled: boolean) {
181
+ const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
182
+ if (Option.isNone(yield* SubscriptionRef.get(supervisor.prepared))) {
183
+ return "disconnected" as const;
184
+ }
185
+
186
+ return yield* executeConnectedEnvironmentHttpRequest<
187
+ "connect",
188
+ HttpClientResponse.HttpClientResponse,
189
+ unknown,
190
+ never
191
+ >({
192
+ group: "connect",
193
+ method: "POST",
194
+ url: (urls) => urls.liveActivityPreference(),
195
+ timeoutMs: 8_000,
196
+ requestInit: { redirect: "error" },
197
+ isUnauthorizedResponse: (response) => response.status === 401,
198
+ request: ({ client, headers }) =>
199
+ client.liveActivityPreference({
200
+ headers,
201
+ payload: { liveActivitiesEnabled },
202
+ responseMode: "response-only",
203
+ }),
204
+ }).pipe(
205
+ Effect.flatMap((response) =>
206
+ Effect.gen(function* () {
207
+ if (response.status === 404) return "unsupported" as const;
208
+ if (response.status === 200) {
209
+ const json = yield* response.json;
210
+ const result = yield* decodeRelayOkResponse(json);
211
+ return result.ok ? ("updated" as const) : ("unlinked" as const);
212
+ }
213
+ return yield* new CloudEnvironmentLinkError({
214
+ message: m(msg("Environment returned HTTP {status}."), { status: response.status }),
215
+ });
216
+ }),
217
+ ),
218
+ Effect.mapError(
219
+ cloudEnvironmentLinkError(
220
+ m(msg("Could not update the environment's Live Activity preference.")),
221
+ (detail) =>
222
+ m(msg("Could not update the environment's Live Activity preference: {detail}"), {
223
+ detail,
224
+ }),
225
+ ),
226
+ ),
227
+ );
228
+});
229
+
230
export const linkEnvironmentToCloudWithPreference = Effect.fn(
231
"linkEnvironment.linkEnvironmentToCloudWithPreference",
232
)(function* (
@@ -257,6 +322,7 @@ export const linkEnvironmentToCloudWithPreference = Effect.fn(
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
),
327
),
328
);
apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx
+90
-12
@@ -1,8 +1,12 @@
1
import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
2
-import { useGT, useMessages } from "gt-react-native";
2
+import { msg, useGT, useMessages } from "gt-react-native";
3
import * as Dialog from "../../components/ui/Dialog";
4
import { managedCapabilityDenial } from "@t3tools/client-runtime/contract-labels";
5
-import { AuthRelayWriteScope, type EnvironmentId } from "@t3tools/contracts";
5
+import {
6
+ AuthRelayConfigureScope,
7
+ AuthRelayWriteScope,
8
+ type EnvironmentId,
9
+} from "@t3tools/contracts";
10
import { readEnvironmentScope } from "../../state/session";
11
import { appAtomRegistry } from "../../state/atom-registry";
12
import { serverEnvironment } from "../../state/server";
@@ -12,6 +16,7 @@ import { useAtomSet, useAtomValue } from "@effect/atom-react";
16
import * as Notifications from "expo-notifications";
17
import { useNavigation } from "@react-navigation/native";
18
import * as Effect from "effect/Effect";
19
+import * as Schema from "effect/Schema";
20
import { AsyncResult } from "effect/reactivity";
21
import { useRef, useState, useSyncExternalStore } from "react";
22
import { Linking, Platform } from "react-native";
@@ -20,6 +25,7 @@ import { m as resolveMessage } from "../../i18n/messages";
25
26
import { AppText as Text } from "../../components/ui/AppText";
27
import {
28
+ createEnvironmentCommand,
29
isAtomCommandInterrupted,
30
reportAtomCommandResult,
31
settleAsyncResult,
@@ -31,7 +37,10 @@ import {
37
openAndroidLiveUpdateSettings,
38
supportsAndroidLiveUpdateSettings,
39
} from "../agent-awareness/androidNotifications";
34
-import { setLiveActivityUpdatesEnabled } from "../agent-awareness/liveActivityPreferences";
40
+import {
41
+ LiveActivityEnvironmentUpdateError,
42
+ setLiveActivityUpdatesEnabled,
43
+} from "../agent-awareness/liveActivityPreferences";
44
import { requestAgentNotificationPermission } from "../agent-awareness/notificationPermissions";
45
import {
46
agentAwarenessNotificationsReady,
@@ -39,6 +48,11 @@ import {
48
refreshAgentAwarenessRegistration,
49
subscribeAgentAwarenessRegistrationStatus,
50
} from "../agent-awareness/remoteRegistration";
51
+import { connectionAtomRuntime } from "../../connection/runtime";
52
+import {
53
+ CloudEnvironmentLinkError,
54
+ updateLinkedEnvironmentLiveActivityPreference,
55
+} from "../cloud/linkEnvironment";
56
import { refreshManagedRelayEnvironments } from "../cloud/managedRelayState";
57
import { hasCloudPublicConfig, resolveRelayClerkTokenOptions } from "../cloud/publicConfig";
58
import { makePermissionStatusAtom } from "../../lib/permissionStatusAtom";
@@ -51,16 +65,46 @@ import { SettingsSwitchRow } from "./components/SettingsSwitchRow";
65
import { SettingsScreen } from "./components/SettingsScreen";
66
import { resolveAgentAwarenessPlatformPresentation } from "./SettingsRouteScreen.logic";
67
68
+const updateLiveActivityPreference = createEnvironmentCommand(connectionAtomRuntime, {
69
+ label: "updateLiveActivityPreference",
70
+ execute: updateLinkedEnvironmentLiveActivityPreference,
71
+});
72
+
73
+const isLiveActivityEnvironmentUpdateError = Schema.is(LiveActivityEnvironmentUpdateError);
74
+const isCloudEnvironmentLinkError = Schema.is(CloudEnvironmentLinkError);
75
+
76
+const updateEnvironmentPreference = Effect.fn("updateEnvironmentPreference")(function* (
77
+ environmentId: EnvironmentId,
78
+ enabled: boolean,
79
+) {
80
+ const result = yield* Effect.promise(() =>
81
+ updateLiveActivityPreference.run(appAtomRegistry, { environmentId, input: enabled }),
82
+ );
83
+ 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
+ });
93
+});
94
+
95
/**
96
* A policy that turns Connect off refuses relay links and preferences, which would fail the
97
* whole batch, so those environments are skipped like ones this session cannot configure.
98
*/
58
-function canLinkEnvironmentToConnect(environmentId: EnvironmentId) {
99
+function canManageConnect(
100
+ environmentId: EnvironmentId,
101
+ scope: typeof AuthRelayConfigureScope | typeof AuthRelayWriteScope,
102
+) {
103
const policy = appAtomRegistry.get(
104
serverEnvironment.configValueAtom(environmentId),
105
)?.managedPolicy;
106
return (
63
- readEnvironmentScope(environmentId, AuthRelayWriteScope) &&
107
+ readEnvironmentScope(environmentId, scope) &&
108
managedCapabilityDenial(policy, "connect") === undefined
109
);
110
}
@@ -316,7 +360,9 @@ function ConfiguredSettingsNotificationsRouteScreen() {
360
const updateResult = await settleAsyncResult(() =>
361
runtime.runPromiseExit(
362
setLiveActivityUpdatesEnabled({
319
- canConfigureEnvironment: canLinkEnvironmentToConnect,
363
+ updateEnvironment: updateEnvironmentPreference,
364
+ canConfigureEnvironment: (id) => canManageConnect(id, AuthRelayConfigureScope),
365
+ canUpdateEnvironment: (id) => canManageConnect(id, AuthRelayWriteScope),
366
enabled: true,
367
previousEnabled: liveActivitiesPreferenceEnabled,
368
clerkToken: tokenResult.value,
@@ -328,6 +374,7 @@ function ConfiguredSettingsNotificationsRouteScreen() {
374
setLiveActivityStatus("disabled");
375
if (!isAtomCommandInterrupted(updateResult)) {
376
const error = squashAtomCommandFailure(updateResult);
377
+ if (reportPartialEnvironmentUpdate(error)) return;
378
Dialog.alert(
379
Platform.OS === "android"
380
? gt("Ongoing activity unavailable")
@@ -344,11 +391,18 @@ function ConfiguredSettingsNotificationsRouteScreen() {
391
refreshManagedRelayEnvironments();
392
setLiveActivityStatus("enabled");
393
// Environment linking can precede device registration; only registered devices can receive Live Activities.
347
- if (getAgentAwarenessRegistrationStatus() === "registered") {
394
+ if (updateResult.value) {
395
+ Dialog.alert(
396
+ gt("Some environments need an update"),
397
+ gt(
398
+ "The device preference was saved. Update older environment servers to apply the setting there.",
399
+ ),
400
+ );
401
+ } else if (getAgentAwarenessRegistrationStatus() === "registered") {
402
Dialog.alert(
403
Platform.OS === "android" ? gt("Ongoing activity enabled") : gt("Live Activities enabled"),
404
environmentCount > 0
351
- ? gt("Agent activity updates are enabled for environments this connection can configure.")
405
+ ? gt("Agent activity updates are enabled for eligible environments.")
406
: gt(
407
"Agent activity updates are enabled. Add an environment to start receiving updates.",
408
),
@@ -401,7 +455,9 @@ function ConfiguredSettingsNotificationsRouteScreen() {
455
const updateResult = await settleAsyncResult(() =>
456
runtime.runPromiseExit(
457
setLiveActivityUpdatesEnabled({
404
- canConfigureEnvironment: canLinkEnvironmentToConnect,
458
+ updateEnvironment: updateEnvironmentPreference,
459
+ canConfigureEnvironment: (id) => canManageConnect(id, AuthRelayConfigureScope),
460
+ canUpdateEnvironment: (id) => canManageConnect(id, AuthRelayWriteScope),
461
enabled: false,
462
previousEnabled: liveActivitiesPreferenceEnabled,
463
clerkToken: token,
@@ -411,14 +467,36 @@ function ConfiguredSettingsNotificationsRouteScreen() {
467
);
468
if (updateResult._tag === "Failure") {
469
setLiveActivityStatus(isSignedIn ? "enabled" : "signed-out");
414
- reportAtomCommandResult(updateResult, {
415
- label: "live activity disable",
416
- });
470
+ if (!reportPartialEnvironmentUpdate(squashAtomCommandFailure(updateResult))) {
471
+ reportAtomCommandResult(updateResult, {
472
+ label: "live activity disable",
473
+ });
474
+ }
475
return;
476
}
477
savePreferences({ liveActivitiesEnabled: false });
478
refreshManagedRelayEnvironments();
479
setLiveActivityStatus("disabled");
480
+ if (updateResult.value) {
481
+ Dialog.alert(
482
+ gt("Some environments need an update"),
483
+ gt(
484
+ "The device preference was saved. Update older environment servers to apply the setting there.",
485
+ ),
486
+ );
487
+ }
488
+ }
489
+
490
+ function reportPartialEnvironmentUpdate(error: unknown): boolean {
491
+ if (!isLiveActivityEnvironmentUpdateError(error)) return false;
492
+ refreshManagedRelayEnvironments();
493
+ Dialog.alert(
494
+ gt("Some environments were updated"),
495
+ gt("The device setting was not saved. The new setting was applied to: {environments}.", {
496
+ environments: error.updatedEnvironments.join(", "),
497
+ }),
498
+ );
499
+ return true;
500
}
501
502
// Both writers settle their own failures, so awaiting them never throws.
apps/mobile/src/i18n/translations/de.json
+11
-2
@@ -995,7 +995,9 @@
995
"45fdf7cb16c83b75": "Relay ansehen",
996
"566b6a4f83192c13": "Die Konnektivität des verwalteten Relays prüfen.",
997
"725b0d37325acdff": "Relay verwalten",
998
- "d89418e289b38f62": "Die Konnektivität des verwalteten Tunnels ändern.",
998
+ "61c9874c98415329": "Relay-Einstellungen ändern oder T3 Connect trennen.",
999
+ "3c85ec9cc2a6d25c": "Relay konfigurieren (Admin)",
1000
+ "7f979acc0e1ee320": "T3 Connect einrichten oder ersetzen, einschließlich der vertrauenswürdigen Stelle, die Kopplungsdaten ausstellt.",
1001
"cea8105b6e4e1703": "Verbinde dich mit dieser Umgebung, um die Berechtigungen dieser Sitzung zu sehen.",
1002
"3e5da15fb9653bc6": "Diese Umgebung hat deine Sitzung nicht akzeptiert. Verbinde dich erneut, um es noch einmal zu versuchen.",
1003
"7f2181cbb5edc3f3": "Deine Berechtigungen konnten nicht überprüft werden. Wird automatisch erneut versucht.",
@@ -1848,6 +1850,9 @@
1850
"b27e256eea29c823": "Relay-URL ist nicht konfiguriert.",
1851
"bd2a0460b58f2ee0": "Das Relay hat Anmeldedaten für eine andere Umgebung zurückgegeben.",
1852
"df614296bc5e624f": "Das Relay hat Anmeldedaten für einen anderen Endpunktanbieter zurückgegeben.",
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.",
1857
"52c4bcf188d1af36": "Die ID des Mobilgeräts konnte nicht geladen werden.",
1858
"473457b89661c874": "Die ID des Mobilgeräts konnte nicht geladen werden: {detail}",
@@ -3291,14 +3296,18 @@
3296
"c5e8c33c81298771": "Aktiviere Benachrichtigungen in den Systemeinstellungen, um laufende Agentenaktivität anzuzeigen.",
3297
"92eadafb24868a2b": "Live-Aktivitäten nicht verfügbar",
3298
"06fdc3a2762b7d11": "Updates zur Agentenaktivität konnten nicht aktiviert werden.",
3299
+ "9ab5b1b388c83bd4": "Einige Umgebungen benötigen ein Update",
3300
+ "e234f4ae749208cc": "Die Geräteeinstellung wurde gespeichert. Aktualisiere ältere Umgebungsserver, um die Einstellung auch dort anzuwenden.",
3301
"de02acb5424cf89b": "Laufende Aktivität aktiviert",
3302
"ada8c7c0bd1538d9": "Live-Aktivitäten aktiviert",
3296
- "15774de43601ae0a": "Updates zur Agentenaktivität sind für Umgebungen aktiviert, die diese Verbindung konfigurieren kann.",
3303
+ "7641156da4b89c8e": "Agentenaktivitäten werden für geeignete Umgebungen angezeigt.",
3304
"f95faa78fdce049f": "Updates zur Agentenaktivität sind aktiviert. Füge eine Umgebung hinzu, um Updates zu erhalten.",
3305
"abec148ed1b71b11": "Aktivieren der Aktivitäts-Updates konnte nicht abgeschlossen werden",
3306
"0aecb0b05ccd394e": "Dieses Gerät konnte nicht bei {product} registriert werden, daher erscheinen noch keine Aktivitäts-Updates. Sie starten, sobald die Registrierung erfolgreich ist.",
3307
"79f07c54023a5bf7": "Benachrichtigungen deaktivieren",
3308
"ebf3eaee224a5372": "Öffne die Systemeinstellungen, um Benachrichtigungen für {product} zu deaktivieren.",
3309
+ "990fb243dc6a5448": "Einige Umgebungen wurden aktualisiert",
3310
+ "0a3f122ccb7757c8": "Die Geräteeinstellung wurde nicht gespeichert. Die neue Einstellung gilt für: {environments}.",
3311
"d65f9a3ee3f07eb8": "Agentenaktivität",
3312
"9ddc5a1e3ae7dc5d": "Gerätebenachrichtigungen",
3313
"3f5506ebb3736478": "Live-Updates der Agenten",
apps/mobile/src/i18n/translations/en.json
+11
-2
@@ -995,7 +995,9 @@
995
"45fdf7cb16c83b75": "View relay",
996
"566b6a4f83192c13": "Inspect managed relay connectivity.",
997
"725b0d37325acdff": "Manage relay",
998
- "d89418e289b38f62": "Change managed tunnel connectivity.",
998
+ "61c9874c98415329": "Update relay preferences or unlink T3 Connect.",
999
+ "3c85ec9cc2a6d25c": "Configure relay (admin)",
1000
+ "7f979acc0e1ee320": "Set up or replace T3 Connect, including its trusted pairing credential issuer.",
1001
"cea8105b6e4e1703": "Connect to this environment to view this session’s permissions.",
1002
"3e5da15fb9653bc6": "This environment did not accept your session. Reconnect to try again.",
1003
"7f2181cbb5edc3f3": "Could not verify your permissions. Retrying automatically.",
@@ -1848,6 +1850,9 @@
1850
"b27e256eea29c823": "Relay URL is not configured.",
1851
"bd2a0460b58f2ee0": "Relay returned credentials for a different environment.",
1852
"df614296bc5e624f": "Relay returned credentials for a different endpoint provider.",
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.",
1857
"52c4bcf188d1af36": "Could not load the mobile device id.",
1858
"473457b89661c874": "Could not load the mobile device id: {detail}",
@@ -3292,14 +3297,18 @@
3297
"c5e8c33c81298771": "Enable notifications in system Settings to show ongoing agent activity.",
3298
"92eadafb24868a2b": "Live Activities unavailable",
3299
"06fdc3a2762b7d11": "Could not enable agent activity updates.",
3300
+ "9ab5b1b388c83bd4": "Some environments need an update",
3301
+ "e234f4ae749208cc": "The device preference was saved. Update older environment servers to apply the setting there.",
3302
"de02acb5424cf89b": "Ongoing activity enabled",
3303
"ada8c7c0bd1538d9": "Live Activities enabled",
3297
- "15774de43601ae0a": "Agent activity updates are enabled for environments this connection can configure.",
3304
+ "7641156da4b89c8e": "Agent activity updates are enabled for eligible environments.",
3305
"f95faa78fdce049f": "Agent activity updates are enabled. Add an environment to start receiving updates.",
3306
"abec148ed1b71b11": "Couldn't finish enabling activity updates",
3307
"0aecb0b05ccd394e": "This device could not be registered with {product}, so activity updates won't appear yet. They'll start once registration succeeds.",
3308
"79f07c54023a5bf7": "Disable notifications",
3309
"ebf3eaee224a5372": "Open system Settings to disable notifications for {product}.",
3310
+ "990fb243dc6a5448": "Some environments were updated",
3311
+ "0a3f122ccb7757c8": "The device setting was not saved. The new setting was applied to: {environments}.",
3312
"d65f9a3ee3f07eb8": "Agent activity",
3313
"9ddc5a1e3ae7dc5d": "Device Notifications",
3314
"3f5506ebb3736478": "Agent Live Updates",
apps/mobile/src/i18n/translations/es.json
+11
-2
@@ -995,7 +995,9 @@
995
"45fdf7cb16c83b75": "Ver relay",
996
"566b6a4f83192c13": "Inspeccionar la conectividad del relay gestionado.",
997
"725b0d37325acdff": "Gestionar relay",
998
- "d89418e289b38f62": "Cambiar la conectividad del túnel gestionado.",
998
+ "61c9874c98415329": "Cambia las preferencias del relé o desvincula T3 Connect.",
999
+ "3c85ec9cc2a6d25c": "Configurar relé (administrador)",
1000
+ "7f979acc0e1ee320": "Configura o reemplaza T3 Connect, incluido el emisor de confianza de credenciales de emparejamiento.",
1001
"cea8105b6e4e1703": "Conéctate a este entorno para ver los permisos de esta sesión.",
1002
"3e5da15fb9653bc6": "Este entorno no aceptó tu sesión. Vuelve a conectar para intentarlo de nuevo.",
1003
"7f2181cbb5edc3f3": "No se pudieron verificar tus permisos. Reintentando automáticamente.",
@@ -1848,6 +1850,9 @@
1850
"b27e256eea29c823": "La URL del relay no está configurada.",
1851
"bd2a0460b58f2ee0": "El relay devolvió credenciales de otro entorno.",
1852
"df614296bc5e624f": "El relay devolvió credenciales de otro proveedor de endpoint.",
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.",
1857
"52c4bcf188d1af36": "No se pudo cargar el ID del dispositivo móvil.",
1858
"473457b89661c874": "No se pudo cargar el ID del dispositivo móvil: {detail}",
@@ -3286,14 +3291,18 @@
3291
"c5e8c33c81298771": "Activa las notificaciones en los ajustes del sistema para mostrar la actividad de agentes en curso.",
3292
"92eadafb24868a2b": "Actividades en directo no disponibles",
3293
"06fdc3a2762b7d11": "No se pudieron activar las actualizaciones de actividad de agentes.",
3294
+ "9ab5b1b388c83bd4": "Algunos entornos necesitan una actualización",
3295
+ "e234f4ae749208cc": "Se guardó la preferencia del dispositivo. Actualiza los servidores de entornos antiguos para aplicarles la preferencia.",
3296
"de02acb5424cf89b": "Actividad en curso activada",
3297
"ada8c7c0bd1538d9": "Actividades en directo activadas",
3291
- "15774de43601ae0a": "Las actualizaciones de actividad de agentes están activadas para los entornos que esta conexión puede configurar.",
3298
+ "7641156da4b89c8e": "Las actualizaciones de actividad de los agentes están habilitadas en los entornos compatibles.",
3299
"f95faa78fdce049f": "Las actualizaciones de actividad de agentes están activadas. Añade un entorno para empezar a recibirlas.",
3300
"abec148ed1b71b11": "No se pudo terminar de activar las actualizaciones de actividad",
3301
"0aecb0b05ccd394e": "No se pudo registrar este dispositivo en {product}, así que aún no aparecerán actualizaciones de actividad. Empezarán cuando el registro se complete.",
3302
"79f07c54023a5bf7": "Desactivar notificaciones",
3303
"ebf3eaee224a5372": "Abre los ajustes del sistema para desactivar las notificaciones de {product}.",
3304
+ "990fb243dc6a5448": "Se actualizaron algunos entornos",
3305
+ "0a3f122ccb7757c8": "No se guardó la configuración del dispositivo. La nueva configuración se aplicó a: {environments}.",
3306
"d65f9a3ee3f07eb8": "Actividad de agentes",
3307
"9ddc5a1e3ae7dc5d": "Notificaciones del dispositivo",
3308
"3f5506ebb3736478": "Actualizaciones en directo de agentes",
apps/mobile/src/i18n/translations/fr.json
+11
-2
@@ -995,7 +995,9 @@
995
"45fdf7cb16c83b75": "Voir le relais",
996
"566b6a4f83192c13": "Inspecter la connectivité du relais géré.",
997
"725b0d37325acdff": "Gérer le relais",
998
- "d89418e289b38f62": "Modifier la connectivité du tunnel géré.",
998
+ "61c9874c98415329": "Modifier les préférences du relais ou dissocier T3 Connect.",
999
+ "3c85ec9cc2a6d25c": "Configurer le relais (admin)",
1000
+ "7f979acc0e1ee320": "Configurer ou remplacer T3 Connect, y compris son émetteur de confiance d’identifiants d’appairage.",
1001
"cea8105b6e4e1703": "Connectez-vous à cet environnement pour voir les autorisations de cette session.",
1002
"3e5da15fb9653bc6": "Cet environnement n’a pas accepté votre session. Reconnectez-vous pour réessayer.",
1003
"7f2181cbb5edc3f3": "Impossible de vérifier vos autorisations. Nouvelle tentative automatique.",
@@ -1848,6 +1850,9 @@
1850
"b27e256eea29c823": "L’URL du relais n’est pas configurée.",
1851
"bd2a0460b58f2ee0": "Le relais a renvoyé des identifiants pour un autre environnement.",
1852
"df614296bc5e624f": "Le relais a renvoyé des identifiants pour un autre fournisseur de point de terminaison.",
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.",
1857
"52c4bcf188d1af36": "Impossible de charger l’ID de l’appareil mobile.",
1858
"473457b89661c874": "Impossible de charger l’ID de l’appareil mobile : {detail}",
@@ -3286,14 +3291,18 @@
3291
"c5e8c33c81298771": "Activez les notifications dans les Réglages du système pour afficher l’activité en cours des agents.",
3292
"92eadafb24868a2b": "Live Activities indisponibles",
3293
"06fdc3a2762b7d11": "Impossible d’activer les mises à jour de l’activité des agents.",
3294
+ "9ab5b1b388c83bd4": "Certains environnements doivent être mis à jour",
3295
+ "e234f4ae749208cc": "La préférence de l’appareil a été enregistrée. Mettez à jour les anciens serveurs d’environnement pour l’y appliquer.",
3296
"de02acb5424cf89b": "Activité en cours activée",
3297
"ada8c7c0bd1538d9": "Live Activities activées",
3291
- "15774de43601ae0a": "Les mises à jour de l’activité des agents sont activées pour les environnements que cette connexion peut configurer.",
3298
+ "7641156da4b89c8e": "Les mises à jour d’activité des agents sont activées pour les environnements compatibles.",
3299
"f95faa78fdce049f": "Les mises à jour de l’activité des agents sont activées. Ajoutez un environnement pour commencer à les recevoir.",
3300
"abec148ed1b71b11": "Impossible de terminer l’activation des mises à jour d’activité",
3301
"0aecb0b05ccd394e": "Cet appareil n’a pas pu être inscrit auprès de {product}, les mises à jour d’activité n’apparaîtront donc pas encore. Elles commenceront dès que l’inscription aura réussi.",
3302
"79f07c54023a5bf7": "Désactiver les notifications",
3303
"ebf3eaee224a5372": "Ouvrez les Réglages du système pour désactiver les notifications de {product}.",
3304
+ "990fb243dc6a5448": "Certains environnements ont été mis à jour",
3305
+ "0a3f122ccb7757c8": "Le réglage de l’appareil n’a pas été enregistré. Le nouveau réglage a été appliqué à : {environments}.",
3306
"d65f9a3ee3f07eb8": "Activité des agents",
3307
"9ddc5a1e3ae7dc5d": "Notifications de l’appareil",
3308
"3f5506ebb3736478": "Live Updates des agents",
apps/mobile/src/i18n/translations/ja.json
+11
-2
@@ -995,7 +995,9 @@
995
"45fdf7cb16c83b75": "リレーの表示",
996
"566b6a4f83192c13": "マネージドリレーの接続状態を確認します。",
997
"725b0d37325acdff": "リレーの管理",
998
- "d89418e289b38f62": "マネージドトンネルの接続を変更します。",
998
+ "61c9874c98415329": "リレー設定を更新するか、T3 Connect のリンクを解除します。",
999
+ "3c85ec9cc2a6d25c": "リレーを設定(管理者)",
1000
+ "7f979acc0e1ee320": "T3 Connect と、信頼できるペアリング認証情報の発行元を設定または変更します。",
1001
"cea8105b6e4e1703": "このセッションの権限を表示するには、この環境に接続してください。",
1002
"3e5da15fb9653bc6": "この環境はセッションを受け付けませんでした。再接続してもう一度お試しください。",
1003
"7f2181cbb5edc3f3": "権限を確認できませんでした。自動的に再試行しています。",
@@ -1848,6 +1850,9 @@
1850
"b27e256eea29c823": "リレー URL が設定されていません。",
1851
"bd2a0460b58f2ee0": "リレーが別の環境の資格情報を返しました。",
1852
"df614296bc5e624f": "リレーが別のエンドポイントプロバイダーの資格情報を返しました。",
1853
+ "c15d8570b0ac8ae5": "環境から HTTP {status} が返されました。",
1854
+ "b87f2217123b4cbf": "環境のライブアクティビティ設定を更新できませんでした。",
1855
+ "2f18d65ea9f178da": "環境のライブアクティビティ設定を更新できませんでした: {detail}",
1856
"024b0e4154ca9170": "クラウドにリンクできるのは、ローカルでペアリングしたベアラー接続のみです。",
1857
"52c4bcf188d1af36": "モバイルデバイスの ID を読み込めませんでした。",
1858
"473457b89661c874": "モバイルデバイスの ID を読み込めませんでした: {detail}",
@@ -3283,14 +3288,18 @@
3288
"c5e8c33c81298771": "進行中のエージェントのアクティビティを表示するには、システムの設定で通知を有効にしてください。",
3289
"92eadafb24868a2b": "ライブアクティビティを利用できません",
3290
"06fdc3a2762b7d11": "エージェントのアクティビティの更新を有効にできませんでした。",
3291
+ "9ab5b1b388c83bd4": "一部の環境は更新が必要です",
3292
+ "e234f4ae749208cc": "デバイスの設定を保存しました。古い環境サーバーにも設定を適用するには、サーバーを更新してください。",
3293
"de02acb5424cf89b": "進行中のアクティビティを有効にしました",
3294
"ada8c7c0bd1538d9": "ライブアクティビティを有効にしました",
3288
- "15774de43601ae0a": "この接続で設定できる環境について、エージェントのアクティビティの更新が有効になりました。",
3295
+ "7641156da4b89c8e": "対象の環境ではエージェントのアクティビティ更新が有効です。",
3296
"f95faa78fdce049f": "エージェントのアクティビティの更新が有効になりました。更新の受信を開始するには環境を追加してください。",
3297
"abec148ed1b71b11": "アクティビティの更新の有効化を完了できませんでした",
3298
"0aecb0b05ccd394e": "このデバイスを {product} に登録できなかったため、アクティビティの更新はまだ表示されません。登録が成功すると表示されるようになります。",
3299
"79f07c54023a5bf7": "通知を無効にする",
3300
"ebf3eaee224a5372": "{product} の通知を無効にするには、システムの設定を開いてください。",
3301
+ "990fb243dc6a5448": "一部の環境が更新されました",
3302
+ "0a3f122ccb7757c8": "デバイスの設定は保存されませんでした。新しい設定が適用された環境: {environments}。",
3303
"d65f9a3ee3f07eb8": "エージェントのアクティビティ",
3304
"9ddc5a1e3ae7dc5d": "デバイスの通知",
3305
"3f5506ebb3736478": "エージェントのライブアップデート",
apps/mobile/src/i18n/translations/ko.json
+11
-2
@@ -995,7 +995,9 @@
995
"45fdf7cb16c83b75": "릴레이 보기",
996
"566b6a4f83192c13": "관리형 릴레이 연결 상태를 확인합니다.",
997
"725b0d37325acdff": "릴레이 관리",
998
- "d89418e289b38f62": "관리형 터널 연결을 변경합니다.",
998
+ "61c9874c98415329": "릴레이 환경설정을 변경하거나 T3 Connect 연결을 해제합니다.",
999
+ "3c85ec9cc2a6d25c": "릴레이 구성(관리자)",
1000
+ "7f979acc0e1ee320": "T3 Connect와 신뢰할 수 있는 페어링 자격 증명 발급자를 설정하거나 교체합니다.",
1001
"cea8105b6e4e1703": "이 세션의 권한을 보려면 이 환경에 연결하세요.",
1002
"3e5da15fb9653bc6": "이 환경에서 세션을 수락하지 않았습니다. 다시 연결해 보세요.",
1003
"7f2181cbb5edc3f3": "권한을 확인할 수 없습니다. 자동으로 다시 시도합니다.",
@@ -1849,6 +1851,9 @@
1851
"b27e256eea29c823": "릴레이 URL이 구성되지 않았습니다.",
1852
"bd2a0460b58f2ee0": "릴레이가 다른 환경의 자격 증명을 반환했습니다.",
1853
"df614296bc5e624f": "릴레이가 다른 엔드포인트 제공자의 자격 증명을 반환했습니다.",
1854
+ "c15d8570b0ac8ae5": "환경에서 HTTP {status}를 반환했습니다.",
1855
+ "b87f2217123b4cbf": "환경의 실시간 현황 설정을 업데이트하지 못했습니다.",
1856
+ "2f18d65ea9f178da": "환경의 실시간 현황 설정을 업데이트하지 못했습니다: {detail}",
1857
"024b0e4154ca9170": "로컬로 페어링된 bearer 연결만 클라우드에 연결할 수 있습니다.",
1858
"52c4bcf188d1af36": "모바일 기기 ID를 불러올 수 없습니다.",
1859
"473457b89661c874": "모바일 기기 ID를 불러올 수 없습니다: {detail}",
@@ -3287,14 +3292,18 @@
3292
"c5e8c33c81298771": "진행 중인 에이전트 활동을 표시하려면 시스템 설정에서 알림을 허용하세요.",
3293
"92eadafb24868a2b": "실시간 현황을 사용할 수 없음",
3294
"06fdc3a2762b7d11": "에이전트 활동 업데이트를 사용할 수 없습니다.",
3295
+ "9ab5b1b388c83bd4": "일부 환경을 업데이트해야 합니다",
3296
+ "e234f4ae749208cc": "기기 설정이 저장되었습니다. 이전 환경 서버에도 설정을 적용하려면 해당 서버를 업데이트하세요.",
3297
"de02acb5424cf89b": "진행 중인 활동 사용",
3298
"ada8c7c0bd1538d9": "실시간 현황 사용",
3292
- "15774de43601ae0a": "이 연결로 구성할 수 있는 환경에 대해 에이전트 활동 업데이트를 사용합니다.",
3299
+ "7641156da4b89c8e": "지원되는 환경에서 에이전트 활동 업데이트가 활성화되어 있습니다.",
3300
"f95faa78fdce049f": "에이전트 활동 업데이트를 사용합니다. 업데이트를 받으려면 환경을 추가하세요.",
3301
"abec148ed1b71b11": "활동 업데이트 사용 설정을 완료할 수 없습니다",
3302
"0aecb0b05ccd394e": "이 기기를 {product}에 등록할 수 없어 아직 활동 업데이트가 표시되지 않습니다. 등록이 완료되면 시작됩니다.",
3303
"79f07c54023a5bf7": "알림 끄기",
3304
"ebf3eaee224a5372": "{product} 알림을 끄려면 시스템 설정을 여세요.",
3305
+ "990fb243dc6a5448": "일부 환경이 업데이트되었습니다",
3306
+ "0a3f122ccb7757c8": "기기 설정이 저장되지 않았습니다. 새 설정이 적용된 환경: {environments}.",
3307
"d65f9a3ee3f07eb8": "에이전트 활동",
3308
"9ddc5a1e3ae7dc5d": "기기 알림",
3309
"3f5506ebb3736478": "에이전트 실시간 업데이트",
apps/mobile/src/i18n/translations/pt-BR.json
+11
-2
@@ -995,7 +995,9 @@
995
"45fdf7cb16c83b75": "Ver relay",
996
"566b6a4f83192c13": "Inspecionar a conectividade do relay gerenciado.",
997
"725b0d37325acdff": "Gerenciar relay",
998
- "d89418e289b38f62": "Alterar a conectividade do túnel gerenciado.",
998
+ "61c9874c98415329": "Atualize as preferências do relay ou desvincule o T3 Connect.",
999
+ "3c85ec9cc2a6d25c": "Configurar relay (admin)",
1000
+ "7f979acc0e1ee320": "Configure ou substitua o T3 Connect, incluindo o emissor confiável de credenciais de pareamento.",
1001
"cea8105b6e4e1703": "Conecte-se a este ambiente para ver as permissões desta sessão.",
1002
"3e5da15fb9653bc6": "Este ambiente não aceitou sua sessão. Reconecte para tentar novamente.",
1003
"7f2181cbb5edc3f3": "Não foi possível verificar suas permissões. Tentando novamente automaticamente.",
@@ -1848,6 +1850,9 @@
1850
"b27e256eea29c823": "A URL do relay não está configurada.",
1851
"bd2a0460b58f2ee0": "O relay retornou credenciais de outro ambiente.",
1852
"df614296bc5e624f": "O relay retornou credenciais de outro provedor de endpoint.",
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.",
1857
"52c4bcf188d1af36": "Não foi possível carregar o ID do dispositivo móvel.",
1858
"473457b89661c874": "Não foi possível carregar o ID do dispositivo móvel: {detail}",
@@ -3286,14 +3291,18 @@
3291
"c5e8c33c81298771": "Ative as notificações nos Ajustes do sistema para mostrar a atividade dos agentes em andamento.",
3292
"92eadafb24868a2b": "Live Activities indisponíveis",
3293
"06fdc3a2762b7d11": "Não foi possível ativar as atualizações de atividade dos agentes.",
3294
+ "9ab5b1b388c83bd4": "Alguns ambientes precisam ser atualizados",
3295
+ "e234f4ae749208cc": "A preferência do dispositivo foi salva. Atualize os servidores de ambientes antigos para aplicar a configuração neles.",
3296
"de02acb5424cf89b": "Atividade em andamento ativada",
3297
"ada8c7c0bd1538d9": "Live Activities ativadas",
3291
- "15774de43601ae0a": "As atualizações de atividade dos agentes estão ativadas para os ambientes que esta conexão pode configurar.",
3298
+ "7641156da4b89c8e": "As atualizações de atividade dos agentes estão ativadas para os ambientes compatíveis.",
3299
"f95faa78fdce049f": "As atualizações de atividade dos agentes estão ativadas. Adicione um ambiente para começar a recebê-las.",
3300
"abec148ed1b71b11": "Não foi possível concluir a ativação das atualizações de atividade",
3301
"0aecb0b05ccd394e": "Este dispositivo não pôde ser registrado no {product}, então as atualizações de atividade ainda não vão aparecer. Elas começarão quando o registro for concluído.",
3302
"79f07c54023a5bf7": "Desativar notificações",
3303
"ebf3eaee224a5372": "Abra os Ajustes do sistema para desativar as notificações do {product}.",
3304
+ "990fb243dc6a5448": "Alguns ambientes foram atualizados",
3305
+ "0a3f122ccb7757c8": "A configuração do dispositivo não foi salva. A nova configuração foi aplicada a: {environments}.",
3306
"d65f9a3ee3f07eb8": "Atividade dos agentes",
3307
"9ddc5a1e3ae7dc5d": "Notificações do dispositivo",
3308
"3f5506ebb3736478": "Live Updates dos agentes",
apps/mobile/src/i18n/translations/ru.json
+11
-2
@@ -995,7 +995,9 @@
995
"45fdf7cb16c83b75": "Просмотр relay",
996
"566b6a4f83192c13": "Просмотр подключения через управляемый relay.",
997
"725b0d37325acdff": "Управление relay",
998
- "d89418e289b38f62": "Изменение подключения через управляемый туннель.",
998
+ "61c9874c98415329": "Изменение настроек ретранслятора или отключение T3 Connect.",
999
+ "3c85ec9cc2a6d25c": "Настройка ретранслятора (администратор)",
1000
+ "7f979acc0e1ee320": "Настройка или замена T3 Connect и доверенного издателя учётных данных для сопряжения.",
1001
"cea8105b6e4e1703": "Подключитесь к этому окружению, чтобы увидеть разрешения этого сеанса.",
1002
"3e5da15fb9653bc6": "Окружение не приняло ваш сеанс. Переподключитесь, чтобы попробовать снова.",
1003
"7f2181cbb5edc3f3": "Не удалось проверить ваши разрешения. Повторная попытка выполняется автоматически.",
@@ -1872,6 +1874,9 @@
1874
"b27e256eea29c823": "URL relay не настроен.",
1875
"bd2a0460b58f2ee0": "Relay вернул учётные данные для другого окружения.",
1876
"df614296bc5e624f": "Relay вернул учётные данные для другого провайдера эндпоинтов.",
1877
+ "c15d8570b0ac8ae5": "Среда вернула HTTP {status}.",
1878
+ "b87f2217123b4cbf": "Не удалось обновить настройку «Эфир активности» для среды.",
1879
+ "2f18d65ea9f178da": "Не удалось обновить настройку «Эфир активности» для среды: {detail}",
1880
"024b0e4154ca9170": "К облаку можно привязать только локально сопряжённое bearer-подключение.",
1881
"52c4bcf188d1af36": "Не удалось загрузить ID мобильного устройства.",
1882
"473457b89661c874": "Не удалось загрузить ID мобильного устройства: {detail}",
@@ -3340,14 +3345,18 @@
3345
"c5e8c33c81298771": "Включите уведомления в системных настройках, чтобы показывать текущую активность агентов.",
3346
"92eadafb24868a2b": "Live Activities недоступны",
3347
"06fdc3a2762b7d11": "Не удалось включить обновления активности агентов.",
3348
+ "9ab5b1b388c83bd4": "Некоторые среды требуют обновления",
3349
+ "e234f4ae749208cc": "Настройка устройства сохранена. Обновите серверы старых сред, чтобы применить настройку и там.",
3350
"de02acb5424cf89b": "Текущая активность включена",
3351
"ada8c7c0bd1538d9": "Live Activities включены",
3345
- "15774de43601ae0a": "Обновления активности агентов включены для окружений, которые может настраивать это подключение.",
3352
+ "7641156da4b89c8e": "Обновления активности агентов включены для подходящих сред.",
3353
"f95faa78fdce049f": "Обновления активности агентов включены. Добавьте окружение, чтобы начать получать обновления.",
3354
"abec148ed1b71b11": "Не удалось завершить включение обновлений активности",
3355
"0aecb0b05ccd394e": "Это устройство не удалось зарегистрировать в {product}, поэтому обновления активности пока не появятся. Они начнут приходить после успешной регистрации.",
3356
"79f07c54023a5bf7": "Отключить уведомления",
3357
"ebf3eaee224a5372": "Откройте системные настройки, чтобы отключить уведомления для {product}.",
3358
+ "990fb243dc6a5448": "Некоторые среды обновлены",
3359
+ "0a3f122ccb7757c8": "Настройка устройства не сохранена. Новая настройка применена к следующим средам: {environments}.",
3360
"d65f9a3ee3f07eb8": "Активность агентов",
3361
"9ddc5a1e3ae7dc5d": "Уведомления устройства",
3362
"3f5506ebb3736478": "Live Updates агентов",
apps/mobile/src/i18n/translations/sv.json
+11
-2
@@ -995,7 +995,9 @@
995
"45fdf7cb16c83b75": "Visa relä",
996
"566b6a4f83192c13": "Granska anslutningen för det hanterade reläet.",
997
"725b0d37325acdff": "Hantera relä",
998
- "d89418e289b38f62": "Ändra anslutningen för den hanterade tunneln.",
998
+ "61c9874c98415329": "Ändra reläinställningar eller koppla från T3 Connect.",
999
+ "3c85ec9cc2a6d25c": "Konfigurera relä (admin)",
1000
+ "7f979acc0e1ee320": "Konfigurera eller ersätt T3 Connect, inklusive dess betrodda utfärdare av parkopplingsuppgifter.",
1001
"cea8105b6e4e1703": "Anslut till den här miljön för att se den här sessionens behörigheter.",
1002
"3e5da15fb9653bc6": "Den här miljön godtog inte din session. Anslut igen för att försöka på nytt.",
1003
"7f2181cbb5edc3f3": "Kunde inte verifiera dina behörigheter. Försöker igen automatiskt.",
@@ -1848,6 +1850,9 @@
1850
"b27e256eea29c823": "Reläets URL är inte konfigurerad.",
1851
"bd2a0460b58f2ee0": "Reläet returnerade autentiseringsuppgifter för en annan miljö.",
1852
"df614296bc5e624f": "Reläet returnerade autentiseringsuppgifter för en annan slutpunktsleverantör.",
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.",
1857
"52c4bcf188d1af36": "Kunde inte läsa in den mobila enhetens id.",
1858
"473457b89661c874": "Kunde inte läsa in den mobila enhetens id: {detail}",
@@ -3292,14 +3297,18 @@
3297
"c5e8c33c81298771": "Aktivera aviseringar i systeminställningarna för att visa pågående agentaktivitet.",
3298
"92eadafb24868a2b": "Liveaktiviteter är inte tillgängliga",
3299
"06fdc3a2762b7d11": "Kunde inte aktivera uppdateringar av agentaktivitet.",
3300
+ "9ab5b1b388c83bd4": "Vissa miljöer behöver uppdateras",
3301
+ "e234f4ae749208cc": "Enhetsinställningen sparades. Uppdatera äldre miljöservrar för att tillämpa inställningen där.",
3302
"de02acb5424cf89b": "Pågående aktivitet aktiverad",
3303
"ada8c7c0bd1538d9": "Liveaktiviteter aktiverade",
3297
- "15774de43601ae0a": "Uppdateringar av agentaktivitet är aktiverade för miljöer som den här anslutningen kan konfigurera.",
3304
+ "7641156da4b89c8e": "Uppdateringar om agentaktivitet är aktiverade för miljöer som stöder dem.",
3305
"f95faa78fdce049f": "Uppdateringar av agentaktivitet är aktiverade. Lägg till en miljö för att börja ta emot uppdateringar.",
3306
"abec148ed1b71b11": "Kunde inte slutföra aktiveringen av aktivitetsuppdateringar",
3307
"0aecb0b05ccd394e": "Enheten kunde inte registreras hos {product}, så aktivitetsuppdateringar visas inte än. De startar när registreringen lyckas.",
3308
"79f07c54023a5bf7": "Inaktivera aviseringar",
3309
"ebf3eaee224a5372": "Öppna systeminställningarna för att inaktivera aviseringar för {product}.",
3310
+ "990fb243dc6a5448": "Vissa miljöer uppdaterades",
3311
+ "0a3f122ccb7757c8": "Enhetsinställningen sparades inte. Den nya inställningen tillämpades på: {environments}.",
3312
"d65f9a3ee3f07eb8": "Agentaktivitet",
3313
"9ddc5a1e3ae7dc5d": "Enhetsaviseringar",
3314
"3f5506ebb3736478": "Liveuppdateringar från agenter",
apps/mobile/src/i18n/translations/zh.json
+11
-2
@@ -995,7 +995,9 @@
995
"45fdf7cb16c83b75": "查看中继",
996
"566b6a4f83192c13": "查看托管中继的连接状态。",
997
"725b0d37325acdff": "管理中继",
998
- "d89418e289b38f62": "更改托管隧道的连接状态。",
998
+ "61c9874c98415329": "更新中继偏好设置或解除 T3 Connect 关联。",
999
+ "3c85ec9cc2a6d25c": "配置中继(管理员)",
1000
+ "7f979acc0e1ee320": "设置或替换 T3 Connect,包括其受信任的配对凭据签发方。",
1001
"cea8105b6e4e1703": "连接此环境后即可查看当前连接的权限。",
1002
"3e5da15fb9653bc6": "此环境未接受你的连接。请重新连接后重试。",
1003
"7f2181cbb5edc3f3": "无法验证你的权限。正在自动重试。",
@@ -1850,6 +1852,9 @@
1852
"b27e256eea29c823": "未配置中继 URL。",
1853
"bd2a0460b58f2ee0": "中继返回的凭据属于另一个环境。",
1854
"df614296bc5e624f": "中继返回的凭据属于另一种端点提供方。",
1855
+ "c15d8570b0ac8ae5": "环境返回了 HTTP {status}。",
1856
+ "b87f2217123b4cbf": "无法更新该环境的实时活动偏好设置。",
1857
+ "2f18d65ea9f178da": "无法更新该环境的实时活动偏好设置:{detail}",
1858
"024b0e4154ca9170": "只有本地配对的 Bearer 连接才能关联到云端。",
1859
"52c4bcf188d1af36": "无法加载移动设备 ID。",
1860
"473457b89661c874": "无法加载移动设备 ID:{detail}",
@@ -3288,14 +3293,18 @@
3293
"c5e8c33c81298771": "在系统设置中启用通知以显示进行中的智能体活动。",
3294
"92eadafb24868a2b": "实时活动不可用",
3295
"06fdc3a2762b7d11": "无法启用智能体活动更新。",
3296
+ "9ab5b1b388c83bd4": "部分环境需要更新",
3297
+ "e234f4ae749208cc": "设备偏好已保存。请更新旧版环境服务器,以在这些环境中应用此设置。",
3298
"de02acb5424cf89b": "进行中活动已启用",
3299
"ada8c7c0bd1538d9": "实时活动已启用",
3293
- "15774de43601ae0a": "已为此连接可配置的环境启用智能体活动更新。",
3300
+ "7641156da4b89c8e": "符合条件的环境已启用代理活动更新。",
3301
"f95faa78fdce049f": "智能体活动更新已启用。添加一个环境以开始接收更新。",
3302
"abec148ed1b71b11": "无法完成启用活动更新",
3303
"0aecb0b05ccd394e": "此设备无法注册到 {product},因此暂时不会显示活动更新。注册成功后即会开始显示。",
3304
"79f07c54023a5bf7": "关闭通知",
3305
"ebf3eaee224a5372": "打开系统设置以关闭 {product} 的通知。",
3306
+ "990fb243dc6a5448": "部分环境已更新",
3307
+ "0a3f122ccb7757c8": "设备设置未保存。新设置已应用于:{environments}。",
3308
"d65f9a3ee3f07eb8": "智能体活动",
3309
"9ddc5a1e3ae7dc5d": "设备通知",
3310
"3f5506ebb3736478": "智能体实时更新",
apps/server/src/auth/EnvironmentAuth.test.ts
+9
-4
@@ -2,7 +2,7 @@ import * as NodePlatformCrypto from "@effect/platform-node/NodeCrypto";
2
import * as NodeServices from "@effect/platform-node/NodeServices";
3
import {
4
authScopeResponse,
5
- AuthStandardClientScopes,
5
+ AuthAdministrativeClientScopes,
6
connectDeviceVerificationCode,
7
} from "@t3tools/contracts";
8
import { expect, it } from "@effect/vitest";
@@ -107,7 +107,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodePlatformCrypto.layer))(
107
const authenticated = yield* serverAuth.authenticateHttpRequest(request);
108
expect(devExchange.cookieName).toMatch(/^t3_dev_session_/);
109
expect(devExchange.expireNormalCookie).toBe(true);
110
- expect(devExchange.response).toMatchObject(authScopeResponse(AuthStandardClientScopes));
110
+ expect(devExchange.response).toMatchObject(
111
+ authScopeResponse(AuthAdministrativeClientScopes),
112
+ );
113
expect(authenticated.scopes).toEqual(["orchestration:read"]);
114
}).pipe(
115
Effect.provide(
@@ -265,7 +267,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodePlatformCrypto.layer))(
267
expect((yield* Effect.flip(sessions.verify(token)))._tag).toBe("SessionTokenRevokedError");
268
expect(
269
(yield* serverAuth.createBrowserSession(recovery.credential, requestMetadata)).response,
268
- ).toMatchObject({ authenticated: true, ...authScopeResponse(AuthStandardClientScopes) });
270
+ ).toMatchObject({
271
+ authenticated: true,
272
+ ...authScopeResponse(AuthAdministrativeClientScopes),
273
+ });
274
}).pipe(
275
Effect.provide(
276
layerEnvironmentAuth({
@@ -754,7 +759,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodePlatformCrypto.layer))(
759
makeCookieRequest(sessions.cookieName, exchanged.sessionToken),
760
);
761
757
- expect(verified.scopes).toEqual(AuthStandardClientScopes);
762
+ expect(verified.scopes).toEqual(AuthAdministrativeClientScopes);
763
expect(verified.subject).toBe("administrative-bootstrap");
764
}).pipe(Effect.provide(layerEnvironmentAuth())),
765
);
apps/server/src/auth/EnvironmentAuth.ts
+2
-1
@@ -3,6 +3,7 @@ import {
3
AuthAccessWriteScope,
4
AuthMcpClientAccess,
5
AuthOrchestrationOperateScope,
6
+ AuthAdministrativeClientScopes,
7
AuthStandardClientScopes,
8
type AuthAccessTokenResult,
9
type AuthBrowserSessionResult,
@@ -1398,7 +1399,7 @@ export const make = Effect.gen(function* () {
1399
() => {
1400
// Unguarded: startup already refused auth policies the managed policy leaves out.
1401
const fallback = issuePairingLink({
1401
- scopes: AuthStandardClientScopes,
1402
+ scopes: AuthAdministrativeClientScopes,
1403
subject: INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
1404
purpose: "startup",
1405
}).pipe(Effect.map(toPairingCredential));
apps/server/src/auth/PairingGrantStore.ts
+3
-2
@@ -1,4 +1,5 @@
1
import {
2
+ AuthAdministrativeClientScopes,
3
AuthStandardClientScopes,
4
type AuthClientMetadata,
5
type AuthConnectDevice,
@@ -414,7 +415,7 @@ const make = Effect.gen(function* () {
415
const now = yield* DateTime.now;
416
yield* seedGrant(config.desktopBootstrapToken, {
417
method: "desktop-bootstrap",
417
- scopes: AuthStandardClientScopes,
418
+ scopes: AuthAdministrativeClientScopes,
419
subject: "desktop-bootstrap",
420
expiresAt: DateTime.add(now, {
421
milliseconds: Duration.toMillis(DESKTOP_BOOTSTRAP_TTL_HOURS),
@@ -535,7 +536,7 @@ const make = Effect.gen(function* () {
536
if (yield* consumeRotatingDesktopToken(credential, now.epochMilliseconds)) {
537
return {
538
method: "desktop-bootstrap",
538
- scopes: AuthStandardClientScopes,
539
+ scopes: AuthAdministrativeClientScopes,
540
subject: "desktop-bootstrap",
541
expiresAt: DateTime.add(now, {
542
milliseconds: DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS,
apps/server/src/auth/SessionStore.ts
+2
-1
@@ -1,5 +1,6 @@
1
import {
2
AuthSessionId,
3
+ AuthAdministrativeClientScopes,
4
AuthStandardClientScopes,
5
AuthEnvironmentScopes,
6
type AuthClientMetadata,
@@ -575,7 +576,7 @@ const make = Effect.gen(function* () {
576
.createIfAbsent({
577
sessionId: devAuth.sessionId,
578
subject: "reusable-dev-token",
578
- scopes: AuthStandardClientScopes,
579
+ scopes: AuthAdministrativeClientScopes,
580
method: "browser-session-cookie",
581
client: {
582
label: "Reusable dev token",
apps/server/src/cloud/CloudLink.lifecycle.test.ts
+20
-2
@@ -1,6 +1,7 @@
1
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2
import * as NodeServices from "@effect/platform-node/NodeServices";
3
import { describe, expect, it } from "@effect/vitest";
4
+import * as ConfigProvider from "effect/ConfigProvider";
5
import * as Effect from "effect/Effect";
6
import * as FileSystem from "effect/FileSystem";
7
import * as Layer from "effect/Layer";
@@ -268,11 +269,14 @@ describe("releaseManagedTunnelOnShutdown", () => {
269
),
270
),
271
271
- Effect.provide(
272
+ Effect.provide([
273
ServerConfigModule.layerTest("/", { prefix: "t3-http-release-test-" }).pipe(
274
Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
275
),
275
- ),
276
+ ConfigProvider.layer(
277
+ ConfigProvider.fromEnv({ env: { T3CODE_RELAY_URL: "https://relay.example.test" } }),
278
+ ),
279
+ ]),
280
Effect.scoped,
281
);
282
@@ -400,6 +404,20 @@ describe("releaseManagedTunnelOnShutdown", () => {
404
}).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
405
});
406
407
+ it.effect("releases a tunnel only through the configured relay", () => {
408
+ const { store, values } = makeMemorySecretStore(managedLinkSecrets);
409
+ values.set(RELAY_URL_SECRET, new TextEncoder().encode("https://old-relay.example.test"));
410
+ const applyConfigCalls: Array<unknown> = [];
411
+ const requests: Array<HttpClientRequest.HttpClientRequest> = [];
412
+
413
+ return Effect.gen(function* () {
414
+ const link = yield* CloudLink.CloudLink;
415
+ expect(yield* link.releaseManagedTunnelOnShutdown()).toBe(false);
416
+ expect(applyConfigCalls).toEqual([]);
417
+ expect(requests).toEqual([]);
418
+ }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
419
+ });
420
+
421
it.effect("leaves the tunnel of a web/mobile-installed link untouched", () => {
422
const { store, values } = makeMemorySecretStore([
423
[CLOUD_ENDPOINT_RUNTIME_CONFIG, "runtime-config"],
apps/server/src/cloud/CloudLink.ts
+53
-7
@@ -38,7 +38,7 @@ import {
38
RELAY_MINT_RESPONSE_TYP,
39
verifyRelayJwt,
40
} from "@t3tools/shared/relayJwt";
41
-import { isSecureRelayUrl } from "@t3tools/shared/relayUrl";
41
+import { isSecureRelayUrl, normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";
42
import * as Context from "effect/Context";
43
import * as SecureRandom from "effect/crypto/SecureRandom";
44
import * as Signature from "effect/crypto/Signature";
@@ -46,6 +46,7 @@ import * as Jwk from "effect/jose/Jwk";
46
import * as DateTime from "effect/DateTime";
47
import * as Duration from "effect/Duration";
48
import * as Effect from "effect/Effect";
49
+import * as FetchHttpClient from "effect/http/FetchHttpClient";
50
import * as FileSystem from "effect/FileSystem";
51
import * as Layer from "effect/Layer";
52
import * as Option from "effect/Option";
@@ -251,6 +252,7 @@ const INTERNAL_OPERATION_MESSAGES = {
252
"persist-recovered-tunnel": "Could not persist the recovered managed tunnel configuration.",
253
"read-relay-config": "Could not read environment relay configuration.",
254
"remove-relay-config": "Could not remove environment relay configuration.",
255
+ "update-live-activity-preference": "Could not update T3 Connect Live Activity preferences.",
256
"update-webhook-settings": "Could not update T3 Connect webhook settings.",
257
"read-preferences": "Could not read environment cloud preferences.",
258
"persist-preferences": "Could not persist environment cloud preferences.",
@@ -455,6 +457,12 @@ export class CloudLink extends Context.Service<
457
EnvironmentCloudLinkStateResult,
458
CloudLinkNotLinkedError | CloudLinkInternalError | ManagedLimits.ManagedPolicyRefusedError
459
>;
460
+ readonly updateLiveActivityPreference: (
461
+ enabled: boolean,
462
+ ) => Effect.Effect<
463
+ RelayOkResponse,
464
+ CloudLinkInternalError | ManagedLimits.ManagedPolicyRefusedError
465
+ >;
466
readonly answerHealthRequest: (
467
request: RelayCloudEnvironmentHealthRequest,
468
) => Effect.Effect<
@@ -1232,22 +1240,27 @@ const make = Effect.gen(function* () {
1240
yield* Effect.logInfo("Keeping the managed tunnel across the update restart");
1241
return false;
1242
}
1235
- const token = yield* cliTokenManager.getExisting;
1236
- if (Option.isNone(token)) {
1243
+ const relayUrl = yield* requireRelayUrl.pipe(Effect.option);
1244
+ const installedRelayUrl = yield* secrets.get(RELAY_URL_SECRET);
1245
+ if (
1246
+ Option.isNone(relayUrl) ||
1247
+ Option.isNone(installedRelayUrl) ||
1248
+ normalizeSecureRelayUrl(bytesToString(installedRelayUrl.value)) !== relayUrl.value
1249
+ ) {
1250
return false;
1251
}
1239
- // Use the persisted relay URL; T3CODE_RELAY_URL may have changed since linking.
1240
- const relayUrl = yield* secrets.get(RELAY_URL_SECRET);
1241
- if (Option.isNone(relayUrl)) {
1252
+ const token = yield* cliTokenManager.getExisting;
1253
+ if (Option.isNone(token)) {
1254
return false;
1255
}
1256
const environmentId = yield* environment.getEnvironmentId;
1257
yield* endpointRuntime.applyConfig(null);
1258
const response = yield* HttpClientRequest.delete(
1247
- `${bytesToString(relayUrl.value)}/v1/client/environment-links/${encodeURIComponent(environmentId)}/tunnel`,
1259
+ `${relayUrl.value}/v1/client/environment-links/${encodeURIComponent(environmentId)}/tunnel`,
1260
).pipe(
1261
HttpClientRequest.bearerToken(token.value.accessToken),
1262
httpClient.execute,
1263
+ Effect.provideService(FetchHttpClient.RequestInit, { redirect: "error" }),
1264
Effect.flatMap(filterRelayResponse),
1265
Effect.flatMap(HttpClientResponse.schemaBodyJson(RelayOkResponse)),
1266
withRelayClientTracing,
@@ -1425,6 +1438,37 @@ const make = Effect.gen(function* () {
1438
Effect.catchIf(ServerSecretStore.isSecretStoreError, internalError("read-preferences")),
1439
);
1440
1441
+ const updateLiveActivityPreference = Effect.fn("environment.cloud.updateLiveActivityPreference")(
1442
+ function* (liveActivitiesEnabled: boolean) {
1443
+ return yield* endpointRuntime.withLinkStateLock(
1444
+ Effect.gen(function* () {
1445
+ const connection = yield* readRelayConnection.pipe(withSecrets);
1446
+ const cloudUserId = yield* secrets.get(CLOUD_LINKED_USER_ID);
1447
+ const revoked = yield* secrets.get(CLOUD_LINK_REVOKED);
1448
+ if (connection === null || Option.isNone(cloudUserId) || Option.isSome(revoked)) {
1449
+ return { ok: false };
1450
+ }
1451
+ const environmentId = yield* environment.getEnvironmentId;
1452
+ const client = yield* makeRelayEnvironmentClient(connection);
1453
+ return yield* client.server
1454
+ .updateLiveActivityPreference({
1455
+ params: { environmentId },
1456
+ payload: { cloudUserId: bytesToString(cloudUserId.value), liveActivitiesEnabled },
1457
+ })
1458
+ .pipe(
1459
+ Effect.provideService(FetchHttpClient.RequestInit, { redirect: "error" }),
1460
+ Effect.timeout("10 seconds"),
1461
+ Effect.catch(internalError("update-live-activity-preference")),
1462
+ );
1463
+ }),
1464
+ );
1465
+ },
1466
+ Effect.catchIf(
1467
+ ServerSecretStore.isSecretStoreError,
1468
+ internalError("update-live-activity-preference"),
1469
+ ),
1470
+ );
1471
+
1472
const answerHealthRequest = Effect.fn("environment.cloud.health")(
1473
function* (request: RelayCloudEnvironmentHealthRequest) {
1474
const cloudMintPublicKey = yield* secrets
@@ -1654,6 +1698,7 @@ const make = Effect.gen(function* () {
1698
linkState,
1699
unlink,
1700
updatePreferences: refused,
1701
+ updateLiveActivityPreference: refused,
1702
answerHealthRequest: refused,
1703
mintCredential: refused,
1704
reconcileDesiredLinkIfStillDesired: notDesired,
@@ -1670,6 +1715,7 @@ const make = Effect.gen(function* () {
1715
linkState,
1716
unlink,
1717
updatePreferences,
1718
+ updateLiveActivityPreference,
1719
answerHealthRequest,
1720
mintCredential,
1721
reconcileDesiredLinkIfStillDesired,
apps/server/src/cloud/http.test.ts
+54
-4
@@ -99,7 +99,9 @@ const layerLinkProofRoutes = HttpApiBuilder.layer(LinkProofTestApi).pipe(
99
capabilities: { repositoryIdentity: false },
100
}),
101
}),
102
- Layer.mock(ManagedEndpointRuntime.CloudManagedEndpointRuntime)({}),
102
+ Layer.mock(ManagedEndpointRuntime.CloudManagedEndpointRuntime)({
103
+ withLinkStateLock: (effect) => effect,
104
+ }),
105
Layer.mock(CliTokenManager.CloudCliTokenManager)({}),
106
Layer.mock(AgentAwarenessRelay.AgentAwarenessRelay)({}),
107
Layer.mock(HttpServer.HttpServer)({
@@ -213,7 +215,7 @@ describe("link proof over a non-loopback desktop transport", () => {
215
const paired = yield* post(
216
"/api/auth/pairing-token",
217
{
216
- scopes: ["relay:read", "relay:write"],
218
+ scopes: ["relay:read", "relay:configure"],
219
label: "desktop-bootstrap",
220
subject: "desktop-bootstrap",
221
},
@@ -284,10 +286,10 @@ describe("link proof over a non-loopback desktop transport", () => {
286
}),
287
);
288
287
- it.effect("requires relay-write scope even for desktop bootstrap", () =>
289
+ it.effect("requires relay configuration permission even for desktop bootstrap", () =>
290
Effect.gen(function* () {
291
const { post, exchange } = yield* linkProofClient;
290
- const token = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN, "relay:read");
292
+ const token = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN, "relay:write");
293
const response = yield* post("/api/connect/link-proof", proofRequest, {
294
authorization: `Bearer ${token}`,
295
});
@@ -295,6 +297,54 @@ describe("link proof over a non-loopback desktop transport", () => {
297
expect(yield* responseJson(response)).toMatchObject({
298
code: "insufficient_scope",
299
requiredScope: "relay:write",
300
+ requiredPermission: "relay:configure",
301
+ });
302
+ }),
303
+ );
304
+
305
+ it.effect("allows relay writers to set preferences without creating a link", () =>
306
+ Effect.gen(function* () {
307
+ const { post, exchange } = yield* linkProofClient;
308
+ const path = "/api/connect/live-activity-preference";
309
+ const payload = { liveActivitiesEnabled: true };
310
+ const readToken = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN, "relay:read");
311
+ const denied = yield* post(path, payload, { authorization: `Bearer ${readToken}` });
312
+ expect(denied.status).toBe(403);
313
+
314
+ const writeToken = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN, "relay:write");
315
+ const unlinked = yield* post(path, payload, { authorization: `Bearer ${writeToken}` });
316
+ expect(unlinked.status).toBe(200);
317
+ expect(yield* responseJson(unlinked)).toEqual({ ok: false });
318
+ }),
319
+ );
320
+
321
+ it.effect("requires explicit permission to configure the relay", () =>
322
+ Effect.gen(function* () {
323
+ const { post, exchange } = yield* linkProofClient;
324
+ const admin = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN);
325
+ const paired = yield* post(
326
+ "/api/auth/pairing-token",
327
+ {},
328
+ { authorization: `Bearer ${admin}` },
329
+ );
330
+ expect(paired.status).toBe(200);
331
+ const { credential } = (yield* responseJson(paired)) as { credential: string };
332
+ const token = yield* exchange(credential);
333
+ const response = yield* post(
334
+ "/api/connect/relay-config",
335
+ {
336
+ relayUrl: "https://relay.example.test",
337
+ cloudUserId: "test-link-owner",
338
+ environmentCredential: "test-environment-credential",
339
+ cloudMintPublicKey: "test-public-key",
340
+ endpointRuntime: null,
341
+ },
342
+ { authorization: `Bearer ${token}` },
343
+ );
344
+ expect(response.status).toBe(403);
345
+ expect(yield* responseJson(response)).toMatchObject({
346
+ code: "insufficient_scope",
347
+ requiredPermission: "relay:configure",
348
});
349
}),
350
);
apps/server/src/cloud/http.ts
+13
-4
@@ -1,5 +1,6 @@
1
import {
2
AuthRelayReadScope,
3
+ AuthRelayConfigureScope,
4
AuthRelayWriteScope,
5
EnvironmentCloudEndpointUnavailableError,
6
EnvironmentHttpApi,
@@ -117,7 +118,7 @@ export const layer = HttpApiBuilder.group(
118
return handlers
119
.handle("linkProof", ({ payload }) =>
120
Effect.gen(function* () {
120
- yield* requireEnvironmentScope(AuthRelayWriteScope);
121
+ yield* requireEnvironmentScope(AuthRelayConfigureScope);
122
const request = yield* HttpServerRequest.HttpServerRequest;
123
const proof = yield* toHttpError(cloudLink.linkProof(payload, request));
124
yield* appendCloudCredentialResponseHeaders;
@@ -125,9 +126,10 @@ export const layer = HttpApiBuilder.group(
126
}),
127
)
128
.handle("relayConfig", ({ payload }) =>
128
- requireEnvironmentScope(AuthRelayWriteScope).pipe(
129
- Effect.andThen(toHttpErrorOrUnavailable(cloudLink.applyRelayConfig(payload))),
130
- ),
129
+ Effect.gen(function* () {
130
+ yield* requireEnvironmentScope(AuthRelayConfigureScope);
131
+ return yield* toHttpErrorOrUnavailable(cloudLink.applyRelayConfig(payload));
132
+ }),
133
)
134
.handle("linkState", () =>
135
Effect.gen(function* () {
@@ -150,6 +152,13 @@ export const layer = HttpApiBuilder.group(
152
Effect.andThen(toHttpError(cloudLink.updatePreferences(payload))),
153
),
154
)
155
+ .handle("liveActivityPreference", ({ payload }) =>
156
+ requireEnvironmentScope(AuthRelayWriteScope).pipe(
157
+ Effect.andThen(
158
+ toHttpError(cloudLink.updateLiveActivityPreference(payload.liveActivitiesEnabled)),
159
+ ),
160
+ ),
161
+ )
162
.handle("health", ({ payload }) =>
163
toHttpError(cloudLink.answerHealthRequest(payload)).pipe(
164
Effect.tap(() => appendCloudCredentialResponseHeaders),
apps/web/src/cloud/t3ConnectState.test.ts
new
+78
@@ -0,0 +1,78 @@
1
+import type { EnvironmentCloudLinkStateResult } from "@t3tools/contracts";
2
+import { describe, expect, it } from "vite-plus/test";
3
+
4
+import { cloudChangeReplacesLink } from "./t3ConnectState";
5
+
6
+function linkState(input: {
7
+ readonly linked: boolean;
8
+ readonly tunnel: boolean;
9
+ readonly revoked?: boolean;
10
+}): EnvironmentCloudLinkStateResult {
11
+ return {
12
+ linked: input.linked,
13
+ cloudUserId: input.linked ? "user" : null,
14
+ relayUrl: input.linked ? "https://relay.example.test" : null,
15
+ relayIssuer: null,
16
+ managedTunnelActive: input.tunnel,
17
+ publishAgentActivity: input.linked,
18
+ linkRevoked: input.revoked ?? false,
19
+ };
20
+}
21
+
22
+describe("cloudChangeReplacesLink", () => {
23
+ it.each([
24
+ {
25
+ name: "linking a tunnel",
26
+ state: { linked: false, tunnel: false },
27
+ tunnel: true,
28
+ publish: false,
29
+ expected: true,
30
+ },
31
+ {
32
+ name: "linking publish-only",
33
+ state: { linked: false, tunnel: false },
34
+ tunnel: false,
35
+ publish: true,
36
+ expected: true,
37
+ },
38
+ {
39
+ name: "repairing a revoked link",
40
+ state: { linked: true, tunnel: true, revoked: true },
41
+ tunnel: true,
42
+ publish: true,
43
+ expected: true,
44
+ },
45
+ {
46
+ name: "dropping the tunnel but keeping publish",
47
+ state: { linked: true, tunnel: true },
48
+ tunnel: false,
49
+ publish: true,
50
+ expected: true,
51
+ },
52
+ {
53
+ name: "adding a tunnel to a publish-only link",
54
+ state: { linked: true, tunnel: false },
55
+ tunnel: true,
56
+ publish: true,
57
+ expected: true,
58
+ },
59
+ {
60
+ name: "unlinking",
61
+ state: { linked: true, tunnel: true },
62
+ tunnel: false,
63
+ publish: false,
64
+ expected: false,
65
+ },
66
+ {
67
+ name: "toggling publish on a tunnel link",
68
+ state: { linked: true, tunnel: true },
69
+ tunnel: true,
70
+ publish: false,
71
+ expected: false,
72
+ },
73
+ ])("$name → $expected", ({ state, tunnel, publish, expected }) => {
74
+ expect(
75
+ cloudChangeReplacesLink(linkState(state), undefined, { managedTunnel: tunnel, publish }),
76
+ ).toBe(expected);
77
+ });
78
+});
apps/web/src/cloud/t3ConnectState.ts
+17
@@ -18,6 +18,23 @@ export function isManagedTunnelActive(
18
);
19
}
20
21
+/**
22
+ * Whether reaching `desired` links or relinks the environment, which needs `relay:configure`.
23
+ * Unlinking and preference changes on the current link only need `relay:write`.
24
+ */
25
+export function cloudChangeReplacesLink(
26
+ linkState: EnvironmentCloudLinkStateResult,
27
+ relayProviderKind: RelayManagedEndpointProviderKind | undefined,
28
+ desired: { readonly managedTunnel: boolean; readonly publish: boolean },
29
+) {
30
+ return (
31
+ (desired.managedTunnel || desired.publish) &&
32
+ (!linkState.linked ||
33
+ linkState.linkRevoked === true ||
34
+ isManagedTunnelActive(linkState, relayProviderKind) !== desired.managedTunnel)
35
+ );
36
+}
37
+
38
// The URL ends up in commands people paste into a shell, so only plain DNS names pass.
39
const TUNNEL_HOSTNAME = /^[a-z0-9-]+(\.[a-z0-9-]+)+$/i;
40
apps/web/src/cloud/useCloudLinkController.browser.test.tsx
+4
-1
@@ -1,6 +1,8 @@
1
import {
2
AuthRelayReadScope,
3
AuthRelayWriteScope,
4
+ AuthAdministrativeClientScopes,
5
+ AuthRelayConfigureScope,
6
EnvironmentId,
7
type EnvironmentCloudLinkStateResult,
8
} from "@t3tools/contracts";
@@ -66,6 +68,7 @@ vi.mock(import("../state/relay"), async (original) => {
68
vi.mock(import("../state/session"), async (original) => ({
69
...(await original()),
70
readEnvironmentScope: (_environmentId, scope) => testState.scopes.has(scope),
71
+ readEnvironmentCanConfigureRelay: () => testState.scopes.has(AuthRelayConfigureScope),
72
}));
73
vi.mock(import("../state/use-atom-command"), async (original) => ({
74
...(await original()),
@@ -146,7 +149,7 @@ function expectNoMutations() {
149
}
150
151
function setup() {
149
- testState.scopes = new Set([AuthRelayReadScope, AuthRelayWriteScope]);
152
+ testState.scopes = new Set(AuthAdministrativeClientScopes);
153
testState.snapshot = linkedState;
154
testState.renderedSnapshot = linkedState;
155
testState.relayProviderKind = null;
apps/web/src/cloud/useCloudLinkController.ts
+25
-8
@@ -17,7 +17,11 @@ import { m } from "../i18n/messages";
17
import { stackedThreadToast } from "../components/ui/toastHelpers";
18
import { relayFailureReason } from "./relayFailureReason";
19
import { relayEnvironmentDiscovery } from "../state/relay";
20
-import { readEnvironmentScope } from "../state/session";
20
+import {
21
+ readEnvironmentCanConfigureRelay,
22
+ readEnvironmentScope,
23
+ useEnvironmentCanConfigureRelay,
24
+} from "../state/session";
25
import { useAtomCommand } from "../state/use-atom-command";
26
import { isCloudEnvironmentLinkError } from "./linkEnvironment";
27
import { refreshManagedTunnelUsage } from "./managedRelayState";
@@ -28,7 +32,7 @@ import {
32
} from "./linkEnvironmentAtoms";
33
import { readCachedCloudLinkState, useCloudLinkState } from "./cloudLinkState";
34
import { resolveRelayClerkTokenOptions } from "./publicConfig";
31
-import { isManagedTunnelActive } from "./t3ConnectState";
35
+import { cloudChangeReplacesLink, isManagedTunnelActive } from "./t3ConnectState";
36
37
export interface CloudLinkDesiredState {
38
readonly managedTunnel: boolean;
@@ -105,6 +109,11 @@ export function useCloudLinkController(environmentId: EnvironmentId | null) {
109
const publishAgentActivity = cloudLinkState.data?.publishAgentActivity ?? false;
110
const holdWebhooksWhileOffline = cloudLinkState.data?.holdWebhooksWhileOffline ?? false;
111
const linked = !linkRevoked && (cloudLinkState.data?.linked ?? false);
112
+ const canConfigureRelay = useEnvironmentCanConfigureRelay(environmentId);
113
+ const needsRelayConfiguration = (desired: CloudLinkDesiredState) =>
114
+ !canConfigureRelay &&
115
+ linkData !== null &&
116
+ cloudChangeReplacesLink(linkData, relayProviderKind, desired);
117
118
const reconcileCloudState = async (desired: CloudLinkDesiredState): Promise<boolean> => {
119
setOperationError(null);
@@ -181,12 +190,19 @@ export function useCloudLinkController(environmentId: EnvironmentId | null) {
190
reportUpdateFailure(new Error(m(msg("Sign in to T3 Connect before enabling this."))));
191
return false;
192
}
184
- const currentManagedTunnel = isManagedTunnelActive(currentLinkState, relayProviderKind);
185
- if (
186
- !currentLinkState.linked ||
187
- currentLinkState.linkRevoked === true ||
188
- currentManagedTunnel !== desired.managedTunnel
189
- ) {
193
+ if (cloudChangeReplacesLink(currentLinkState, relayProviderKind, desired)) {
194
+ if (!readEnvironmentCanConfigureRelay(environmentId)) {
195
+ reportUpdateFailure(
196
+ new Error(
197
+ m(
198
+ msg(
199
+ "This connection needs the relay configuration permission to configure T3 Connect.",
200
+ ),
201
+ ),
202
+ ),
203
+ );
204
+ return false;
205
+ }
206
const linkResult = await linkEnvironment({
207
target,
208
clerkToken,
@@ -246,6 +262,7 @@ export function useCloudLinkController(environmentId: EnvironmentId | null) {
262
holdWebhooksWhileOffline,
263
operationError,
264
tunnelLimit,
265
+ needsRelayConfiguration,
266
reconcileCloudState,
267
};
268
}
apps/web/src/cloud/useT3ConnectTurnOn.ts
+3
-4
@@ -1,13 +1,12 @@
1
import {
2
AuthRelayReadScope,
3
- AuthRelayWriteScope,
3
type EnvironmentId,
4
managedCapabilityDenial,
5
} from "@t3tools/contracts";
6
7
import { isElectron } from "../env";
8
import { useManagedPolicy } from "../state/managedPolicy";
10
-import { useEnvironmentScope } from "../state/session";
9
+import { useEnvironmentCanConfigureRelay, useEnvironmentScope } from "../state/session";
10
import { useCloudLinkState } from "./cloudLinkState";
11
import { hasCloudPublicConfig } from "./publicConfig";
12
import { resolveT3ConnectTurnOn } from "./t3ConnectState";
@@ -15,7 +14,7 @@ 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);
18
- const canWriteRelay = useEnvironmentScope(environmentId, AuthRelayWriteScope);
17
+ const canConfigureRelay = useEnvironmentCanConfigureRelay(environmentId);
18
const connectDenial = managedCapabilityDenial(useManagedPolicy(environmentId), "connect");
19
const linkState = useCloudLinkState(environmentId).data;
20
return resolveT3ConnectTurnOn({
@@ -24,7 +23,7 @@ export function useT3ConnectTurnOn(environmentId: EnvironmentId | null) {
23
linkableHere: linkState?.linkableHere ?? true,
24
cloudConfigured: hasCloudPublicConfig(),
25
canReadRelay,
27
- canWriteRelay,
26
+ canWriteRelay: canConfigureRelay,
27
connectDenial,
28
});
29
}
apps/web/src/components/cloud/ConnectOnboardingDialog.tsx
+25
-28
@@ -6,6 +6,7 @@ import {
6
AuthRelayReadScope,
7
AuthRelayWriteScope,
8
type AuthSessionState,
9
+ type EnvironmentId,
10
} from "@t3tools/contracts";
11
import { AsyncResult, Atom } from "effect/reactivity";
12
import { msg, T, useGT, useMessages } from "gt-react";
@@ -28,7 +29,13 @@ import {
29
usePrimaryEnvironmentId,
30
} from "~/state/environments";
31
import { usePrimaryManagedPolicy } from "~/state/managedPolicy";
31
-import { environmentSession, readEnvironmentScope, useEnvironmentScope } from "~/state/session";
32
+import {
33
+ environmentSession,
34
+ readEnvironmentCanConfigureRelay,
35
+ readEnvironmentScope,
36
+ useEnvironmentCanConfigureRelay,
37
+ useEnvironmentScope,
38
+} from "~/state/session";
39
import {
40
type T3ConnectAccountPageUrl,
41
useT3ConnectAccountPage,
@@ -52,6 +59,15 @@ type OnboardingStep = "publish" | "devices";
59
60
const EMPTY_SESSION_STATE_ATOM = Atom.make(AsyncResult.initial<AuthSessionState>());
61
62
+function canPublishOnEnvironment(id: EnvironmentId | null): boolean {
63
+ return (
64
+ id !== null &&
65
+ readEnvironmentScope(id, AuthRelayReadScope) &&
66
+ readEnvironmentScope(id, AuthRelayWriteScope) &&
67
+ readEnvironmentCanConfigureRelay(id)
68
+ );
69
+}
70
+
71
function ConfiguredConnectOnboardingDialog() {
72
// Pending Clerk sessions must not look signed out or activation would look like a new sign-in.
73
const { isLoaded, isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false });
@@ -73,12 +89,13 @@ function ConfiguredConnectOnboardingDialog() {
89
? EMPTY_SESSION_STATE_ATOM
90
: environmentSession.sessionStateAtom(primaryEnvironmentId),
91
);
76
- const canReadRelay = useEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope);
77
- const canWriteRelay = useEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope);
92
+ const canConfigureRelay = useEnvironmentCanConfigureRelay(primaryEnvironmentId);
93
// A policy that turns Connect off leaves nothing to publish; reaching other devices still works.
94
const connectAllowed =
95
managedCapabilityDenial(usePrimaryManagedPolicy(), "connect") === undefined;
81
- const canManageRelay = canReadRelay && canWriteRelay && connectAllowed;
96
+ const canReadRelay = useEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope);
97
+ const canWriteRelay = useEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope);
98
+ const canManageRelay = canReadRelay && canWriteRelay && canConfigureRelay && connectAllowed;
99
const canRequireDeviceApproval = useEnvironmentScope(primaryEnvironmentId, AuthAccessWriteScope);
100
const deviceApprovalRequired =
101
usePrimaryEnvironment()?.serverConfig?.settings.requireConnectDeviceApproval === true;
@@ -189,11 +206,7 @@ function ConfiguredConnectOnboardingDialog() {
206
setIsApplying(false);
207
if (!saved) return;
208
}
192
- if (
193
- primaryEnvironmentId === null ||
194
- !readEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope) ||
195
- !readEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope)
196
- ) {
209
+ if (!canPublishOnEnvironment(primaryEnvironmentId)) {
210
setStep("devices");
211
return;
212
}
@@ -253,13 +266,7 @@ function ConfiguredConnectOnboardingDialog() {
266
isStepDisabled={() => isApplying}
267
onStepChange={(index) => {
268
const next = steps[index];
256
- if (
257
- next === "publish" &&
258
- (primaryEnvironmentId === null ||
259
- !readEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope) ||
260
- !readEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope))
261
- )
262
- return;
269
+ if (next === "publish" && !canPublishOnEnvironment(primaryEnvironmentId)) return;
270
if (next) setStep(next);
271
}}
272
/>
@@ -280,20 +287,10 @@ function ConfiguredConnectOnboardingDialog() {
287
tunnelLimit={controller.tunnelLimit}
288
onOpenAccountPage={leaveForAccountPage}
289
onExposeEnvironmentChange={(enabled) => {
283
- if (
284
- primaryEnvironmentId !== null &&
285
- readEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope) &&
286
- readEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope)
287
- )
288
- setExposeEnvironment(enabled);
290
+ if (canPublishOnEnvironment(primaryEnvironmentId)) setExposeEnvironment(enabled);
291
}}
292
onPublishAgentActivityChange={(enabled) => {
291
- if (
292
- primaryEnvironmentId !== null &&
293
- readEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope) &&
294
- readEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope)
295
- )
296
- setPublishAgentActivity(enabled);
293
+ if (canPublishOnEnvironment(primaryEnvironmentId)) setPublishAgentActivity(enabled);
294
}}
295
/>
296
) : (
apps/web/src/components/settings/AuthorizedClientsSettings.tsx
+16
@@ -10,7 +10,9 @@ import {
10
AuthDiagnosticsReadScope,
11
AuthOrchestrationReadScope,
12
AuthFilesystemReadScope,
13
+ AuthRelayConfigureScope,
14
AuthStandardClientScopes,
15
+ AuthTerminalOperateScope,
16
AuthTerminalReadScope,
17
type AuthEnvironmentScope,
18
type AuthGrantScope,
@@ -617,6 +619,8 @@ export const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHead
619
...AuthStandardClientScopes,
620
]);
621
const selectedScopes = pairingScopes.filter((scope) => delegatableScopes.includes(scope));
622
+ const terminalSelected = selectedScopes.includes(AuthTerminalOperateScope);
623
+ const relayAdminSelected = selectedScopes.includes(AuthRelayConfigureScope);
624
const [isCreatingPairingLink, setIsCreatingPairingLink] = useState(false);
625
626
const handleCreatePairingLink = async () => {
@@ -793,6 +797,18 @@ export const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHead
797
<span className="block text-xs leading-snug text-muted-foreground">
798
{m(description)}
799
</span>
800
+ {terminalSelected && scope === AuthTerminalOperateScope ? (
801
+ <span className="block text-xs text-warning">
802
+ {gt(
803
+ "Terminal commands can read or change files within the server account’s permissions.",
804
+ )}
805
+ </span>
806
+ ) : null}
807
+ {relayAdminSelected && scope === AuthRelayConfigureScope ? (
808
+ <span className="block text-xs text-warning">
809
+ {gt("This client can change who can issue pairing credentials.")}
810
+ </span>
811
+ ) : null}
812
</span>
813
</label>
814
),
apps/web/src/components/settings/SavedEnvironmentRows.tsx
+16
-4
@@ -582,6 +582,7 @@ function ConfiguredCloudLinkRow({
582
holdWebhooksWhileOffline,
583
operationError,
584
tunnelLimit,
585
+ needsRelayConfiguration,
586
reconcileCloudState,
587
} = useCloudLinkController(environmentId);
588
const { openAuthPrompt } = useT3ConnectAuthPrompt();
@@ -608,6 +609,17 @@ function ConfiguredCloudLinkRow({
609
cloudLinkState.data === null ||
610
cloudLinkState.isPending ||
611
isBusy;
612
+ const configureReason = gt(
613
+ "This connection needs the relay configuration permission to configure T3 Connect.",
614
+ );
615
+ const tunnelNeedsConfigure = needsRelayConfiguration({
616
+ managedTunnel: !managedTunnelActive,
617
+ publish: publishAgentActivity,
618
+ });
619
+ const publishNeedsConfigure = needsRelayConfiguration({
620
+ managedTunnel: managedTunnelActive,
621
+ publish: !publishAgentActivity,
622
+ });
623
// `isSignedIn` is undefined until Clerk loads. Signed out, one row shows a
624
// sign-in button instead of its switch; the onboarding dialog that opens after
625
// a fresh sign-in offers both linking and publishing.
@@ -744,8 +756,8 @@ function ConfiguredCloudLinkRow({
756
) : (
757
<CloudLinkSwitch
758
checked={managedTunnelActive}
747
- disabled={switchDisabled}
748
- disabledReason={disabledReason}
759
+ disabled={switchDisabled || tunnelNeedsConfigure}
760
+ disabledReason={disabledReason ?? (tunnelNeedsConfigure ? configureReason : null)}
761
onCheckedChange={(enabled) => void updateManagedTunnel(enabled)}
762
/>
763
)
@@ -784,8 +796,8 @@ function ConfiguredCloudLinkRow({
796
<CloudLinkSwitch
797
ariaLabel={gt("Publish agent activity to mobile clients")}
798
checked={publishAgentActivity}
787
- disabled={switchDisabled}
788
- disabledReason={disabledReason}
799
+ disabled={switchDisabled || publishNeedsConfigure}
800
+ disabledReason={disabledReason ?? (publishNeedsConfigure ? configureReason : null)}
801
onCheckedChange={(enabled) => void updatePublishAgentActivity(enabled)}
802
/>
803
)
apps/web/src/i18n/translations/de.json
+6
-1
@@ -996,7 +996,9 @@
996
"45fdf7cb16c83b75": "Relay ansehen",
997
"566b6a4f83192c13": "Die Konnektivität des verwalteten Relays prüfen.",
998
"725b0d37325acdff": "Relay verwalten",
999
- "d89418e289b38f62": "Die Konnektivität des verwalteten Tunnels ändern.",
999
+ "61c9874c98415329": "Relay-Einstellungen ändern oder T3 Connect trennen.",
1000
+ "3c85ec9cc2a6d25c": "Relay konfigurieren (Admin)",
1001
+ "7f979acc0e1ee320": "T3 Connect einrichten oder ersetzen, einschließlich der vertrauenswürdigen Stelle, die Kopplungsdaten ausstellt.",
1002
"cea8105b6e4e1703": "Verbinde dich mit dieser Umgebung, um die Berechtigungen dieser Sitzung zu sehen.",
1003
"3e5da15fb9653bc6": "Diese Umgebung hat deine Sitzung nicht akzeptiert. Verbinde dich erneut, um es noch einmal zu versuchen.",
1004
"7f2181cbb5edc3f3": "Deine Berechtigungen konnten nicht überprüft werden. Wird automatisch erneut versucht.",
@@ -1487,6 +1489,7 @@
1489
"64b5d9920f89189c": "Warte, bis die aktuellen T3-Connect-Einstellungen gelesen werden können.",
1490
"a74f94bf4c3c6bfe": "Hier getrennt, aber T3 Connect führt sie noch. Entferne sie unter Konto.",
1491
"4ca203c6fe28afa6": "Melde dich bei T3 Connect an, bevor du dies aktivierst.",
1492
+ "895d824b027d128e": "Diese Verbindung benötigt die Berechtigung zur Relay-Konfiguration, um T3 Connect einzurichten.",
1493
"e4f274ef6c9c9a6c": "Wähle einen Ordner auf dem anderen Rechner.",
1494
"5aa50c97d1573919": "Das Klonen konnte nicht gestartet werden.",
1495
"1a31b5a1f4fe467f": "Dieser Rechner",
@@ -7379,6 +7382,8 @@
7382
"b76eda9aa9bec002": "Andere widerrufen",
7383
"04ab01b535a8e3a8": "z. B. iPad im Wohnzimmer",
7384
"274fac14d65ab9cc": "Standard",
7385
+ "e0dde491debc2517": "Terminalbefehle können Dateien im Rahmen der Berechtigungen des Serverkontos lesen oder ändern.",
7386
+ "7aa48417f0b79691": "Dieser Client kann ändern, wer Kopplungsdaten ausstellen darf.",
7387
"f8d29f698314bb6e": "Wird erstellt…",
7388
"647bd066558e1add": "Standard",
7389
"84dc0da709ddecd1": "Einrichten",
apps/web/src/i18n/translations/en.json
+6
-1
@@ -996,7 +996,9 @@
996
"45fdf7cb16c83b75": "View relay",
997
"566b6a4f83192c13": "Inspect managed relay connectivity.",
998
"725b0d37325acdff": "Manage relay",
999
- "d89418e289b38f62": "Change managed tunnel connectivity.",
999
+ "61c9874c98415329": "Update relay preferences or unlink T3 Connect.",
1000
+ "3c85ec9cc2a6d25c": "Configure relay (admin)",
1001
+ "7f979acc0e1ee320": "Set up or replace T3 Connect, including its trusted pairing credential issuer.",
1002
"cea8105b6e4e1703": "Connect to this environment to view this session’s permissions.",
1003
"3e5da15fb9653bc6": "This environment did not accept your session. Reconnect to try again.",
1004
"7f2181cbb5edc3f3": "Could not verify your permissions. Retrying automatically.",
@@ -1487,6 +1489,7 @@
1489
"64b5d9920f89189c": "Wait until the current T3 Connect settings can be read.",
1490
"a74f94bf4c3c6bfe": "Disconnected here, but T3 Connect still lists it. Remove it in Account.",
1491
"4ca203c6fe28afa6": "Sign in to T3 Connect before enabling this.",
1492
+ "895d824b027d128e": "This connection needs the relay configuration permission to configure T3 Connect.",
1493
"e4f274ef6c9c9a6c": "Choose a folder on the other machine.",
1494
"5aa50c97d1573919": "Could not start the clone.",
1495
"1a31b5a1f4fe467f": "This machine",
@@ -7387,6 +7390,8 @@
7390
"b76eda9aa9bec002": "Revoke others",
7391
"04ab01b535a8e3a8": "e.g. Living room iPad",
7392
"274fac14d65ab9cc": "Standard",
7393
+ "e0dde491debc2517": "Terminal commands can read or change files within the server account’s permissions.",
7394
+ "7aa48417f0b79691": "This client can change who can issue pairing credentials.",
7395
"f8d29f698314bb6e": "Creating…",
7396
"647bd066558e1add": "Default",
7397
"84dc0da709ddecd1": "Setup",
apps/web/src/i18n/translations/es.json
+6
-1
@@ -996,7 +996,9 @@
996
"45fdf7cb16c83b75": "Ver relay",
997
"566b6a4f83192c13": "Inspeccionar la conectividad del relay gestionado.",
998
"725b0d37325acdff": "Gestionar relay",
999
- "d89418e289b38f62": "Cambiar la conectividad del túnel gestionado.",
999
+ "61c9874c98415329": "Cambia las preferencias del relé o desvincula T3 Connect.",
1000
+ "3c85ec9cc2a6d25c": "Configurar relé (administrador)",
1001
+ "7f979acc0e1ee320": "Configura o reemplaza T3 Connect, incluido el emisor de confianza de credenciales de emparejamiento.",
1002
"cea8105b6e4e1703": "Conéctate a este entorno para ver los permisos de esta sesión.",
1003
"3e5da15fb9653bc6": "Este entorno no aceptó tu sesión. Vuelve a conectar para intentarlo de nuevo.",
1004
"7f2181cbb5edc3f3": "No se pudieron verificar tus permisos. Reintentando automáticamente.",
@@ -1487,6 +1489,7 @@
1489
"64b5d9920f89189c": "Espera hasta que se puedan leer los ajustes actuales de T3 Connect.",
1490
"a74f94bf4c3c6bfe": "Desconectado aquí, pero T3 Connect aún lo muestra. Quítalo en Cuenta.",
1491
"4ca203c6fe28afa6": "Inicia sesión en T3 Connect antes de activar esto.",
1492
+ "895d824b027d128e": "Esta conexión necesita permiso para configurar el relé antes de configurar T3 Connect.",
1493
"e4f274ef6c9c9a6c": "Elige una carpeta en la otra máquina.",
1494
"5aa50c97d1573919": "No se pudo iniciar la clonación.",
1495
"1a31b5a1f4fe467f": "Esta máquina",
@@ -7380,6 +7383,8 @@
7383
"b76eda9aa9bec002": "Revocar los demás",
7384
"04ab01b535a8e3a8": "p. ej., iPad del salón",
7385
"274fac14d65ab9cc": "Estándar",
7386
+ "e0dde491debc2517": "Los comandos de terminal pueden leer o modificar archivos según los permisos de la cuenta del servidor.",
7387
+ "7aa48417f0b79691": "Este cliente puede cambiar quién puede emitir credenciales de emparejamiento.",
7388
"f8d29f698314bb6e": "Creando…",
7389
"647bd066558e1add": "Predeterminado",
7390
"84dc0da709ddecd1": "Configurar",
apps/web/src/i18n/translations/fr.json
+6
-1
@@ -996,7 +996,9 @@
996
"45fdf7cb16c83b75": "Voir le relais",
997
"566b6a4f83192c13": "Inspecter la connectivité du relais géré.",
998
"725b0d37325acdff": "Gérer le relais",
999
- "d89418e289b38f62": "Modifier la connectivité du tunnel géré.",
999
+ "61c9874c98415329": "Modifier les préférences du relais ou dissocier T3 Connect.",
1000
+ "3c85ec9cc2a6d25c": "Configurer le relais (admin)",
1001
+ "7f979acc0e1ee320": "Configurer ou remplacer T3 Connect, y compris son émetteur de confiance d’identifiants d’appairage.",
1002
"cea8105b6e4e1703": "Connectez-vous à cet environnement pour voir les autorisations de cette session.",
1003
"3e5da15fb9653bc6": "Cet environnement n’a pas accepté votre session. Reconnectez-vous pour réessayer.",
1004
"7f2181cbb5edc3f3": "Impossible de vérifier vos autorisations. Nouvelle tentative automatique.",
@@ -1487,6 +1489,7 @@
1489
"64b5d9920f89189c": "Attendez que les paramètres T3 Connect actuels puissent être lus.",
1490
"a74f94bf4c3c6bfe": "Déconnecté ici, mais T3 Connect le liste toujours. Supprimez-le dans Compte.",
1491
"4ca203c6fe28afa6": "Connectez-vous à T3 Connect avant d’activer cette option.",
1492
+ "895d824b027d128e": "Cette connexion nécessite l’autorisation de configurer le relais pour configurer T3 Connect.",
1493
"e4f274ef6c9c9a6c": "Choisissez un dossier sur l’autre machine.",
1494
"5aa50c97d1573919": "Impossible de lancer le clonage.",
1495
"1a31b5a1f4fe467f": "Cette machine",
@@ -7381,6 +7384,8 @@
7384
"b76eda9aa9bec002": "Révoquer les autres",
7385
"04ab01b535a8e3a8": "ex. iPad du salon",
7386
"274fac14d65ab9cc": "Standard",
7387
+ "e0dde491debc2517": "Les commandes du terminal peuvent lire ou modifier des fichiers selon les autorisations du compte serveur.",
7388
+ "7aa48417f0b79691": "Ce client peut modifier les personnes autorisées à émettre des identifiants d’appairage.",
7389
"f8d29f698314bb6e": "Création…",
7390
"647bd066558e1add": "Par défaut",
7391
"84dc0da709ddecd1": "Configurer",
apps/web/src/i18n/translations/ja.json
+6
-1
@@ -996,7 +996,9 @@
996
"45fdf7cb16c83b75": "リレーの表示",
997
"566b6a4f83192c13": "マネージドリレーの接続状態を確認します。",
998
"725b0d37325acdff": "リレーの管理",
999
- "d89418e289b38f62": "マネージドトンネルの接続を変更します。",
999
+ "61c9874c98415329": "リレー設定を更新するか、T3 Connect のリンクを解除します。",
1000
+ "3c85ec9cc2a6d25c": "リレーを設定(管理者)",
1001
+ "7f979acc0e1ee320": "T3 Connect と、信頼できるペアリング認証情報の発行元を設定または変更します。",
1002
"cea8105b6e4e1703": "このセッションの権限を表示するには、この環境に接続してください。",
1003
"3e5da15fb9653bc6": "この環境はセッションを受け付けませんでした。再接続してもう一度お試しください。",
1004
"7f2181cbb5edc3f3": "権限を確認できませんでした。自動的に再試行しています。",
@@ -1487,6 +1489,7 @@
1489
"64b5d9920f89189c": "現在の T3 Connect 設定を読み取れるようになるまでお待ちください。",
1490
"a74f94bf4c3c6bfe": "ここでは切断しましたが、T3 Connect にはまだ表示されています。アカウントで削除してください。",
1491
"4ca203c6fe28afa6": "有効にする前に T3 Connect にサインインしてください。",
1492
+ "895d824b027d128e": "この接続から T3 Connect を設定するには、リレーの設定権限が必要です。",
1493
"e4f274ef6c9c9a6c": "相手のマシン上のフォルダーを選択してください。",
1494
"5aa50c97d1573919": "クローンを開始できませんでした。",
1495
"1a31b5a1f4fe467f": "このマシン",
@@ -7346,6 +7349,8 @@
7349
"b76eda9aa9bec002": "他をすべて取り消す",
7350
"04ab01b535a8e3a8": "例: リビングの iPad",
7351
"274fac14d65ab9cc": "標準",
7352
+ "e0dde491debc2517": "ターミナルのコマンドは、サーバーアカウントの権限の範囲内でファイルを読み取り、変更できます。",
7353
+ "7aa48417f0b79691": "このクライアントは、ペアリング認証情報を発行できるユーザーを変更できます。",
7354
"f8d29f698314bb6e": "作成しています…",
7355
"647bd066558e1add": "デフォルト",
7356
"84dc0da709ddecd1": "セットアップ",
apps/web/src/i18n/translations/ko.json
+6
-1
@@ -996,7 +996,9 @@
996
"45fdf7cb16c83b75": "릴레이 보기",
997
"566b6a4f83192c13": "관리형 릴레이 연결 상태를 확인합니다.",
998
"725b0d37325acdff": "릴레이 관리",
999
- "d89418e289b38f62": "관리형 터널 연결을 변경합니다.",
999
+ "61c9874c98415329": "릴레이 환경설정을 변경하거나 T3 Connect 연결을 해제합니다.",
1000
+ "3c85ec9cc2a6d25c": "릴레이 구성(관리자)",
1001
+ "7f979acc0e1ee320": "T3 Connect와 신뢰할 수 있는 페어링 자격 증명 발급자를 설정하거나 교체합니다.",
1002
"cea8105b6e4e1703": "이 세션의 권한을 보려면 이 환경에 연결하세요.",
1003
"3e5da15fb9653bc6": "이 환경에서 세션을 수락하지 않았습니다. 다시 연결해 보세요.",
1004
"7f2181cbb5edc3f3": "권한을 확인할 수 없습니다. 자동으로 다시 시도합니다.",
@@ -1487,6 +1489,7 @@
1489
"64b5d9920f89189c": "현재 T3 Connect 설정을 읽을 수 있을 때까지 기다리세요.",
1490
"a74f94bf4c3c6bfe": "여기서는 연결이 해제되었지만 T3 Connect에는 아직 표시됩니다. 계정에서 제거하세요.",
1491
"4ca203c6fe28afa6": "이 기능을 켜기 전에 T3 Connect에 로그인하세요.",
1492
+ "895d824b027d128e": "이 연결에서 T3 Connect를 설정하려면 릴레이 구성 권한이 필요합니다.",
1493
"e4f274ef6c9c9a6c": "다른 머신의 폴더를 선택하세요.",
1494
"5aa50c97d1573919": "복제를 시작할 수 없습니다.",
1495
"1a31b5a1f4fe467f": "이 머신",
@@ -7347,6 +7350,8 @@
7350
"b76eda9aa9bec002": "다른 항목 취소",
7351
"04ab01b535a8e3a8": "예: 거실 iPad",
7352
"274fac14d65ab9cc": "표준",
7353
+ "e0dde491debc2517": "터미널 명령은 서버 계정에 부여된 권한 범위에서 파일을 읽거나 변경할 수 있습니다.",
7354
+ "7aa48417f0b79691": "이 클라이언트는 페어링 자격 증명을 발급할 수 있는 주체를 변경할 수 있습니다.",
7355
"f8d29f698314bb6e": "만드는 중…",
7356
"647bd066558e1add": "기본값",
7357
"84dc0da709ddecd1": "설정",
apps/web/src/i18n/translations/pt-BR.json
+6
-1
@@ -996,7 +996,9 @@
996
"45fdf7cb16c83b75": "Ver relay",
997
"566b6a4f83192c13": "Inspecionar a conectividade do relay gerenciado.",
998
"725b0d37325acdff": "Gerenciar relay",
999
- "d89418e289b38f62": "Alterar a conectividade do túnel gerenciado.",
999
+ "61c9874c98415329": "Atualize as preferências do relay ou desvincule o T3 Connect.",
1000
+ "3c85ec9cc2a6d25c": "Configurar relay (admin)",
1001
+ "7f979acc0e1ee320": "Configure ou substitua o T3 Connect, incluindo o emissor confiável de credenciais de pareamento.",
1002
"cea8105b6e4e1703": "Conecte-se a este ambiente para ver as permissões desta sessão.",
1003
"3e5da15fb9653bc6": "Este ambiente não aceitou sua sessão. Reconecte para tentar novamente.",
1004
"7f2181cbb5edc3f3": "Não foi possível verificar suas permissões. Tentando novamente automaticamente.",
@@ -1487,6 +1489,7 @@
1489
"64b5d9920f89189c": "Aguarde até que as configurações atuais do T3 Connect possam ser lidas.",
1490
"a74f94bf4c3c6bfe": "Desconectado aqui, mas o T3 Connect ainda o lista. Remova-o em Conta.",
1491
"4ca203c6fe28afa6": "Entre no T3 Connect antes de ativar isto.",
1492
+ "895d824b027d128e": "Esta conexão precisa da permissão para configurar o relay antes de configurar o T3 Connect.",
1493
"e4f274ef6c9c9a6c": "Escolha uma pasta na outra máquina.",
1494
"5aa50c97d1573919": "Não foi possível iniciar o clone.",
1495
"1a31b5a1f4fe467f": "Esta máquina",
@@ -7380,6 +7383,8 @@
7383
"b76eda9aa9bec002": "Revogar os outros",
7384
"04ab01b535a8e3a8": "ex.: iPad da sala",
7385
"274fac14d65ab9cc": "Padrão",
7386
+ "e0dde491debc2517": "Os comandos do terminal podem ler ou alterar arquivos conforme as permissões da conta do servidor.",
7387
+ "7aa48417f0b79691": "Este cliente pode alterar quem pode emitir credenciais de pareamento.",
7388
"f8d29f698314bb6e": "Criando…",
7389
"647bd066558e1add": "Padrão",
7390
"84dc0da709ddecd1": "Configurar",
apps/web/src/i18n/translations/ru.json
+6
-1
@@ -996,7 +996,9 @@
996
"45fdf7cb16c83b75": "Просмотр relay",
997
"566b6a4f83192c13": "Просмотр подключения через управляемый relay.",
998
"725b0d37325acdff": "Управление relay",
999
- "d89418e289b38f62": "Изменение подключения через управляемый туннель.",
999
+ "61c9874c98415329": "Изменение настроек ретранслятора или отключение T3 Connect.",
1000
+ "3c85ec9cc2a6d25c": "Настройка ретранслятора (администратор)",
1001
+ "7f979acc0e1ee320": "Настройка или замена T3 Connect и доверенного издателя учётных данных для сопряжения.",
1002
"cea8105b6e4e1703": "Подключитесь к этому окружению, чтобы увидеть разрешения этого сеанса.",
1003
"3e5da15fb9653bc6": "Окружение не приняло ваш сеанс. Переподключитесь, чтобы попробовать снова.",
1004
"7f2181cbb5edc3f3": "Не удалось проверить ваши разрешения. Повторная попытка выполняется автоматически.",
@@ -1487,6 +1489,7 @@
1489
"64b5d9920f89189c": "Дождитесь, пока текущие настройки T3 Connect можно будет прочитать.",
1490
"a74f94bf4c3c6bfe": "Отключено здесь, но T3 Connect всё ещё его показывает. Удалите его в разделе «Аккаунт».",
1491
"4ca203c6fe28afa6": "Войдите в T3 Connect, прежде чем включать это.",
1492
+ "895d824b027d128e": "Для настройки T3 Connect этому подключению нужно разрешение на настройку ретранслятора.",
1493
"e4f274ef6c9c9a6c": "Выберите папку на другой машине.",
1494
"5aa50c97d1573919": "Не удалось начать клонирование.",
1495
"1a31b5a1f4fe467f": "Эта машина",
@@ -7380,6 +7383,8 @@
7383
"b76eda9aa9bec002": "Отозвать остальные",
7384
"04ab01b535a8e3a8": "например, iPad в гостиной",
7385
"274fac14d65ab9cc": "Стандартные",
7386
+ "e0dde491debc2517": "Команды терминала могут читать и изменять файлы в пределах прав учётной записи сервера.",
7387
+ "7aa48417f0b79691": "Этот клиент может изменять список тех, кто вправе выдавать учётные данные для сопряжения.",
7388
"f8d29f698314bb6e": "Создание…",
7389
"647bd066558e1add": "По умолчанию",
7390
"84dc0da709ddecd1": "Настроить",
apps/web/src/i18n/translations/sv.json
+6
-1
@@ -996,7 +996,9 @@
996
"45fdf7cb16c83b75": "Visa relä",
997
"566b6a4f83192c13": "Granska anslutningen för det hanterade reläet.",
998
"725b0d37325acdff": "Hantera relä",
999
- "d89418e289b38f62": "Ändra anslutningen för den hanterade tunneln.",
999
+ "61c9874c98415329": "Ändra reläinställningar eller koppla från T3 Connect.",
1000
+ "3c85ec9cc2a6d25c": "Konfigurera relä (admin)",
1001
+ "7f979acc0e1ee320": "Konfigurera eller ersätt T3 Connect, inklusive dess betrodda utfärdare av parkopplingsuppgifter.",
1002
"cea8105b6e4e1703": "Anslut till den här miljön för att se den här sessionens behörigheter.",
1003
"3e5da15fb9653bc6": "Den här miljön godtog inte din session. Anslut igen för att försöka på nytt.",
1004
"7f2181cbb5edc3f3": "Kunde inte verifiera dina behörigheter. Försöker igen automatiskt.",
@@ -1487,6 +1489,7 @@
1489
"64b5d9920f89189c": "Vänta tills de aktuella T3 Connect-inställningarna kan läsas.",
1490
"a74f94bf4c3c6bfe": "Frånkopplad här, men T3 Connect listar den fortfarande. Ta bort den under Konto.",
1491
"4ca203c6fe28afa6": "Logga in på T3 Connect innan du aktiverar det här.",
1492
+ "895d824b027d128e": "Den här anslutningen behöver behörighet att konfigurera reläet för att konfigurera T3 Connect.",
1493
"e4f274ef6c9c9a6c": "Välj en mapp på den andra datorn.",
1494
"5aa50c97d1573919": "Kunde inte starta kloningen.",
1495
"1a31b5a1f4fe467f": "Den här datorn",
@@ -7386,6 +7389,8 @@
7389
"b76eda9aa9bec002": "Återkalla andra",
7390
"04ab01b535a8e3a8": "t.ex. iPad i vardagsrummet",
7391
"274fac14d65ab9cc": "Standard",
7392
+ "e0dde491debc2517": "Terminalkommandon kan läsa eller ändra filer inom serverkontots behörigheter.",
7393
+ "7aa48417f0b79691": "Den här klienten kan ändra vem som får utfärda parkopplingsuppgifter.",
7394
"f8d29f698314bb6e": "Skapar…",
7395
"647bd066558e1add": "Standard",
7396
"84dc0da709ddecd1": "Konfigurera",
apps/web/src/i18n/translations/zh.json
+6
-1
@@ -996,7 +996,9 @@
996
"45fdf7cb16c83b75": "查看中继",
997
"566b6a4f83192c13": "查看托管中继的连接状态。",
998
"725b0d37325acdff": "管理中继",
999
- "d89418e289b38f62": "更改托管隧道的连接状态。",
999
+ "61c9874c98415329": "更新中继偏好设置或解除 T3 Connect 关联。",
1000
+ "3c85ec9cc2a6d25c": "配置中继(管理员)",
1001
+ "7f979acc0e1ee320": "设置或替换 T3 Connect,包括其受信任的配对凭据签发方。",
1002
"cea8105b6e4e1703": "连接此环境后即可查看当前连接的权限。",
1003
"3e5da15fb9653bc6": "此环境未接受你的连接。请重新连接后重试。",
1004
"7f2181cbb5edc3f3": "无法验证你的权限。正在自动重试。",
@@ -1487,6 +1489,7 @@
1489
"64b5d9920f89189c": "请等待当前 T3 Connect 设置可以读取。",
1490
"a74f94bf4c3c6bfe": "已在此断开,但 T3 Connect 仍列出此环境。请到账户中移除。",
1491
"4ca203c6fe28afa6": "启用前请先登录 T3 Connect。",
1492
+ "895d824b027d128e": "此连接需要中继配置权限才能设置 T3 Connect。",
1493
"e4f274ef6c9c9a6c": "请选择另一台机器上的文件夹。",
1494
"5aa50c97d1573919": "无法开始克隆。",
1495
"1a31b5a1f4fe467f": "本机",
@@ -7395,6 +7398,8 @@
7398
"b76eda9aa9bec002": "撤销其他客户端的访问权限",
7399
"04ab01b535a8e3a8": "例如:客厅的 iPad",
7400
"274fac14d65ab9cc": "标准",
7401
+ "e0dde491debc2517": "终端命令可以在服务器账户的权限范围内读取或修改文件。",
7402
+ "7aa48417f0b79691": "此客户端可以更改谁有权签发配对凭据。",
7403
"f8d29f698314bb6e": "正在创建…",
7404
"647bd066558e1add": "默认",
7405
"84dc0da709ddecd1": "设置",
apps/web/src/state/session.ts
+15
@@ -3,6 +3,7 @@ import { createEnvironmentSessionAtoms } from "@t3tools/client-runtime/state/ses
3
import {
4
type AuthEnvironmentScope,
5
type AuthSessionState,
6
+ AuthRelayConfigureScope,
7
type EnvironmentId,
8
sessionGrantsScope,
9
} from "@t3tools/contracts";
@@ -34,6 +35,20 @@ export function useEnvironmentScope(
35
);
36
}
37
38
+export function useEnvironmentCanConfigureRelay(environmentId: EnvironmentId | null): boolean {
39
+ return useAtomValue(
40
+ environmentId === null
41
+ ? EMPTY_SESSION_STATE_ATOM
42
+ : environmentSession.sessionStateAtom(environmentId),
43
+ (result) => sessionHasScope(result, AuthRelayConfigureScope),
44
+ );
45
+}
46
+
47
+export function readEnvironmentCanConfigureRelay(environmentId: EnvironmentId): boolean {
48
+ const result = appAtomRegistry.get(environmentSession.sessionStateAtom(environmentId));
49
+ return sessionHasScope(result, AuthRelayConfigureScope);
50
+}
51
+
52
export function sessionHasScope(
53
result: AsyncResult.AsyncResult<AuthSessionState, unknown>,
54
scope: AuthEnvironmentScope,
docs/user/remote-access.md
+13
-3
@@ -446,7 +446,8 @@ t3 pair --scope orchestration:read --scope relay:read
446
The selected scopes replace the default permissions. The same option works with
447
`t3 auth pairing create` and `t3 auth session issue`; each command's
448
`--help` lists the available scopes. Without `--scope`, pairing tokens and issued
449
-bearer sessions get every permission, including managing access and T3 Connect.
449
+bearer sessions get the standard client permissions, including managing access.
450
+Setting up or replacing a T3 Connect link requires the separate `relay:configure` permission.
451
A terminal or a full-access agent on the host can reach those as well, so a
452
client that should not manage access also needs to go without `terminal:operate`
453
and `orchestration:operate`.
@@ -469,8 +470,10 @@ worktree still creates that branch and worktree with `orchestration:operate`,
470
and the agent it runs can use Git however the environment allows.
471
472
Settings changes, provider management, environment maintenance, access
472
-management, and T3 Connect management can each be granted separately. New
473
-pairings without `--scope` include all of them. Existing clients keep the
473
+management, and T3 Connect preferences can each be granted separately. Setting
474
+up or replacing a T3 Connect link requires the administrative
475
+`relay:configure` permission. `relay:write` covers preferences and unlinking.
476
+New pairings without `--scope` include the standard client permissions. Existing clients keep the
477
permissions they paired with and can stay connected after an update, but newly
478
separated features may require pairing again with the permissions they need.
479
Older clients may show controls that the server denies. Create a fresh pairing
@@ -480,6 +483,13 @@ link to change a client's permissions.
483
local changes. Add `filesystem:write` to allow editing files or saving plans to
484
the workspace. These scopes control direct file access from the client.
485
486
+Some permissions also give a client indirect access. With `terminal:operate`,
487
+a client can run commands that read or change any files the server’s OS account
488
+can access, even when the pairing link omits file permissions. With
489
+`relay:configure`, a client can replace the trusted issuer of pairing
490
+credentials. Grant these permissions only to clients you trust with those
491
+capabilities.
492
+
493
To remove an environment from T3 Connect, open your account menu's **T3 Connect**
494
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
infra/relay/src/agentActivity/AgentActivityPublisher.test.ts
+1
@@ -106,6 +106,7 @@ function makeEnvironmentLinks(
106
listForUser: () => Effect.succeed([]),
107
getForUser: () => Effect.succeed(null),
108
findActiveManagedForEnvironment: () => Effect.succeed([]),
109
+ updateLiveActivityPreference: () => Effect.die("unexpected Live Activity preference update"),
110
setHoldWebhooksWhileOffline: () => Effect.void,
111
revokeForUser: () => Effect.succeed(false),
112
...overrides,
infra/relay/src/agentActivity/FcmDeliveries.test.ts
+1
@@ -171,6 +171,7 @@ function harness() {
171
),
172
listForUser: () => Effect.succeed([]),
173
findActiveManagedForEnvironment: () => Effect.succeed([]),
174
+ updateLiveActivityPreference: () => Effect.die("unexpected Live Activity preference update"),
175
setHoldWebhooksWhileOffline: () => Effect.void,
176
revokeForUser: () => Effect.succeed(false),
177
getForUser: (input) =>
infra/relay/src/agentActivity/MobileRegistrations.test.ts
+1
@@ -117,6 +117,7 @@ function makeEnvironmentLinks(
117
listForUser: () => Effect.succeed([]),
118
getForUser: () => Effect.succeed(null),
119
findActiveManagedForEnvironment: () => Effect.succeed([]),
120
+ updateLiveActivityPreference: () => Effect.die("unexpected Live Activity preference update"),
121
setHoldWebhooksWhileOffline: () => Effect.void,
122
revokeForUser: () => Effect.succeed(false),
123
...overrides,
infra/relay/src/environments/EnvironmentConnector.test.ts
+1
@@ -229,6 +229,7 @@ function makeLinks(
229
...overrides,
230
}),
231
findActiveManagedForEnvironment: () => Effect.succeed([]),
232
+ updateLiveActivityPreference: () => Effect.die("unexpected Live Activity preference update"),
233
setHoldWebhooksWhileOffline: () => Effect.void,
234
revokeForUser: () => Effect.succeed(false),
235
};
infra/relay/src/environments/EnvironmentLinker.test.ts
+2
@@ -132,6 +132,8 @@ function layerTest(input?: {
132
listForUser: () => Effect.succeed([]),
133
getForUser: () => Effect.succeed(null),
134
findActiveManagedForEnvironment: () => Effect.succeed([]),
135
+ updateLiveActivityPreference: () =>
136
+ Effect.die("unexpected Live Activity preference update"),
137
setHoldWebhooksWhileOffline: () => Effect.void,
138
revokeForUser: () => Effect.succeed(false),
139
}),
infra/relay/src/environments/EnvironmentLinks.test.ts
+89
@@ -1,6 +1,12 @@
1
+import * as NodeServices from "@effect/platform-node/NodeServices";
2
+import { PGlite } from "@electric-sql/pglite";
3
+import { drizzle } from "drizzle-orm/pglite";
4
+import * as FileSystem from "effect/FileSystem";
5
+import * as Path from "effect/Path";
6
import { describe, expect, it } from "@effect/vitest";
7
import * as Effect from "effect/Effect";
8
import * as Layer from "effect/Layer";
9
+import type { SQL } from "drizzle-orm";
10
import { PgDialect } from "drizzle-orm/pg-core";
11
12
import * as RelayDb from "../db.ts";
@@ -64,6 +70,89 @@ describe("EnvironmentLinks", () => {
70
);
71
});
72
73
+ it.effect("updates Live Activities only on the matching active link", () =>
74
+ Effect.gen(function* () {
75
+ const pg = yield* Effect.acquireRelease(
76
+ Effect.promise(() => PGlite.create()),
77
+ (client) => Effect.promise(() => client.close()),
78
+ );
79
+ const fs = yield* FileSystem.FileSystem;
80
+ const path = yield* Path.Path;
81
+ const migrationsDir = yield* path.fromFileUrl(
82
+ new URL("../../migrations/postgres/", import.meta.url),
83
+ );
84
+ for (const name of (yield* fs.readDirectory(migrationsDir)).toSorted()) {
85
+ const migration = yield* fs.readFileString(`${migrationsDir}${name}/migration.sql`);
86
+ yield* Effect.promise(() => pg.exec(migration));
87
+ }
88
+
89
+ const db = drizzle({ client: pg });
90
+ const matching = { userId: "user-1", environmentId: "env-1", environmentPublicKey: "key-1" };
91
+ const revoked = { ...matching, environmentId: "revoked-env" };
92
+ const timestamp = "2026-01-01T00:00:00.000Z";
93
+ const rows = [
94
+ matching,
95
+ { ...matching, userId: "user-2" },
96
+ { ...matching, environmentId: "env-2" },
97
+ { ...matching, userId: "user-3", environmentPublicKey: "key-2" },
98
+ { ...revoked, revokedAt: timestamp },
99
+ ];
100
+ yield* Effect.promise(() =>
101
+ db.insert(relayEnvironmentLinks).values(
102
+ rows.map((row) => ({
103
+ ...row,
104
+ endpointHttpBaseUrl: "https://environment.test",
105
+ endpointWsBaseUrl: "wss://environment.test",
106
+ endpointProviderKind: "cloudflare_tunnel",
107
+ createdAt: timestamp,
108
+ updatedAt: timestamp,
109
+ })),
110
+ ),
111
+ );
112
+ // PGlite returns promises where the production Drizzle driver returns Effects.
113
+ const effectDb = {
114
+ update: (table: typeof relayEnvironmentLinks) => ({
115
+ set: (values: Partial<typeof relayEnvironmentLinks.$inferInsert>) => ({
116
+ where: (condition: SQL | undefined) => ({
117
+ returning: (fields: { environmentId: typeof relayEnvironmentLinks.environmentId }) =>
118
+ Effect.promise(() =>
119
+ db.update(table).set(values).where(condition).returning(fields),
120
+ ),
121
+ }),
122
+ }),
123
+ }),
124
+ } as unknown as RelayDb.RelayDb["Service"];
125
+ const links = yield* Effect.service(EnvironmentLinks.EnvironmentLinks).pipe(
126
+ Effect.provide(
127
+ EnvironmentLinks.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, effectDb))),
128
+ ),
129
+ );
130
+ expect(
131
+ yield* links.updateLiveActivityPreference({ ...matching, liveActivitiesEnabled: false }),
132
+ ).toBe(true);
133
+ expect(
134
+ yield* links.updateLiveActivityPreference({
135
+ ...matching,
136
+ environmentPublicKey: "key-2",
137
+ liveActivitiesEnabled: false,
138
+ }),
139
+ ).toBe(false);
140
+ expect(
141
+ yield* links.updateLiveActivityPreference({ ...revoked, liveActivitiesEnabled: false }),
142
+ ).toBe(false);
143
+
144
+ const updated = yield* Effect.promise(() => db.select().from(relayEnvironmentLinks));
145
+ expect(
146
+ updated
147
+ .filter((row) => !row.liveActivitiesEnabled)
148
+ .map(({ userId, environmentId }) => ({
149
+ userId,
150
+ environmentId,
151
+ })),
152
+ ).toEqual([{ userId: matching.userId, environmentId: matching.environmentId }]);
153
+ }).pipe(Effect.provide(NodeServices.layer)),
154
+ );
155
+
156
it.effect("revokes only the active link owned by the requesting user", () => {
157
const updateValues: Array<Record<string, unknown>> = [];
158
const whereConditions: Array<unknown> = [];
infra/relay/src/environments/EnvironmentLinks.ts
+36
@@ -145,6 +145,12 @@ export class EnvironmentLinks extends Context.Service<
145
readonly environmentPublicKey: string;
146
readonly holdWebhooksWhileOffline: boolean;
147
}) => Effect.Effect<void, EnvironmentLinkEnvironmentLookupPersistenceError>;
148
+ readonly updateLiveActivityPreference: (input: {
149
+ readonly userId: string;
150
+ readonly environmentId: string;
151
+ readonly environmentPublicKey: string;
152
+ readonly liveActivitiesEnabled: boolean;
153
+ }) => Effect.Effect<boolean, EnvironmentLinkEnvironmentLookupPersistenceError>;
154
readonly revokeForUser: (input: {
155
readonly userId: string;
156
readonly environmentId: string;
@@ -465,6 +471,36 @@ const make = Effect.gen(function* () {
471
);
472
}),
473
474
+ updateLiveActivityPreference: Effect.fn(
475
+ "relay.environment_links.update_live_activity_preference",
476
+ )(function* (input) {
477
+ const rows = yield* db
478
+ .update(relayEnvironmentLinks)
479
+ .set({
480
+ liveActivitiesEnabled: input.liveActivitiesEnabled,
481
+ updatedAt: DateTime.formatIso(yield* DateTime.now),
482
+ })
483
+ .where(
484
+ and(
485
+ eq(relayEnvironmentLinks.userId, input.userId),
486
+ eq(relayEnvironmentLinks.environmentId, input.environmentId),
487
+ eq(relayEnvironmentLinks.environmentPublicKey, input.environmentPublicKey),
488
+ isNull(relayEnvironmentLinks.revokedAt),
489
+ ),
490
+ )
491
+ .returning({ environmentId: relayEnvironmentLinks.environmentId })
492
+ .pipe(
493
+ Effect.mapError(
494
+ (cause) =>
495
+ new EnvironmentLinkEnvironmentLookupPersistenceError({
496
+ environmentId: input.environmentId,
497
+ cause,
498
+ }),
499
+ ),
500
+ );
501
+ return rows.length > 0;
502
+ }),
503
+
504
revokeForUser: Effect.fn("relay.environment_links.revoke_for_user")(function* (input) {
505
yield* Effect.annotateCurrentSpan({
506
"relay.environment_id": input.environmentId,
infra/relay/src/hooks/HeldHooks.test.ts
+1
@@ -79,6 +79,7 @@ const withService = <A, E>(
79
link.environmentPublicKey === input.environmentPublicKey),
80
),
81
),
82
+ updateLiveActivityPreference: () => Effect.die("unexpected Live Activity preference update"),
83
setHoldWebhooksWhileOffline: () => Effect.void,
84
}),
85
Layer.mock(ManagedEndpointAllocations.ManagedEndpointAllocations, {
infra/relay/src/http/Api.test.ts
+2
@@ -538,6 +538,8 @@ function layerRelayUnlinkTest(input?: {
538
listForUser: () => Effect.die("unused listForUser"),
539
getForUser: input?.getForUser ?? (() => Effect.succeed(null)),
540
findActiveManagedForEnvironment: () => Effect.die("unused findActiveManagedForEnvironment"),
541
+ updateLiveActivityPreference: () =>
542
+ Effect.die("unexpected Live Activity preference update"),
543
setHoldWebhooksWhileOffline: () => Effect.die("unused setHoldWebhooksWhileOffline"),
544
revokeForUser: input?.revokeForUser ?? (() => Effect.succeed(false)),
545
}),
infra/relay/src/http/Api.ts
+15
@@ -1426,6 +1426,21 @@ export const layerServerApi = HttpApiBuilder.group(
1426
return payload;
1427
}, mapRelayCommonApiErrors("not_authorized")),
1428
)
1429
+ .handle(
1430
+ "updateLiveActivityPreference",
1431
+ Effect.fn("relay.api.server.updateLiveActivityPreference")(function* ({ params, payload }) {
1432
+ yield* requireOwnEnvironment(params.environmentId);
1433
+ const principal = yield* RelayEnvironmentPrincipal;
1434
+ const links = yield* EnvironmentLinks.EnvironmentLinks;
1435
+ const ok = yield* links.updateLiveActivityPreference({
1436
+ userId: payload.cloudUserId,
1437
+ environmentId: params.environmentId,
1438
+ environmentPublicKey: principal.environmentPublicKey,
1439
+ liveActivitiesEnabled: payload.liveActivitiesEnabled,
1440
+ });
1441
+ return { ok };
1442
+ }, mapRelayCommonApiErrors("not_authorized")),
1443
+ )
1444
.handle(
1445
"wakeHeldHooks",
1446
Effect.fn("relay.api.server.wakeHeldHooks")(function* ({ params }) {
packages/contracts/src/auth.ts
+11
-1
@@ -47,6 +47,7 @@ export const AuthAccessReadScope = "access:read" as const;
47
export const AuthAccessWriteScope = "access:write" as const;
48
export const AuthRelayReadScope = "relay:read" as const;
49
export const AuthRelayWriteScope = "relay:write" as const;
50
+export const AuthRelayConfigureScope = "relay:configure" as const;
51
export const AuthEnvironmentScope = Schema.Literals([
52
AuthOrchestrationReadScope,
53
AuthOrchestrationOperateScope,
@@ -65,6 +66,7 @@ export const AuthEnvironmentScope = Schema.Literals([
66
AuthAccessWriteScope,
67
AuthRelayReadScope,
68
AuthRelayWriteScope,
69
+ AuthRelayConfigureScope,
70
]);
71
export type AuthEnvironmentScope = typeof AuthEnvironmentScope.Type;
72
export const AuthEnvironmentScopes = Schema.Array(AuthEnvironmentScope);
@@ -113,7 +115,10 @@ const legacyParents: Partial<Record<AuthEnvironmentScope, AuthEnvironmentScope>>
115
/** Keep permission denials decodable by clients with the original scope enum. */
116
export function authScopeRequiredResponse(requiredPermission: AuthEnvironmentScope) {
117
return {
116
- requiredScope: legacyParents[requiredPermission] ?? requiredPermission,
118
+ requiredScope:
119
+ requiredPermission === AuthRelayConfigureScope
120
+ ? AuthRelayWriteScope
121
+ : (legacyParents[requiredPermission] ?? requiredPermission),
122
requiredPermission,
123
};
124
}
@@ -167,6 +172,11 @@ export const AuthStandardClientScopes = [
172
AuthRelayWriteScope,
173
] as const;
174
175
+export const AuthAdministrativeClientScopes = [
176
+ ...AuthStandardClientScopes,
177
+ AuthRelayConfigureScope,
178
+] as const;
179
+
180
export const AuthTokenExchangeGrantType =
181
"urn:ietf:params:oauth:grant-type:token-exchange" as const;
182
export const AuthAccessTokenType = "urn:ietf:params:oauth:token-type:access_token" as const;
packages/contracts/src/environmentHttp.ts
+8
@@ -1028,6 +1028,14 @@ class EnvironmentConnectHttpApi extends HttpApiGroup.make("connect")
1028
error: EnvironmentHttpCloudErrors,
1029
}).middleware(EnvironmentAuthenticatedAuth),
1030
)
1031
+ .add(
1032
+ HttpApiEndpoint.post("liveActivityPreference", "/api/connect/live-activity-preference", {
1033
+ headers: OptionalBearerHeaders,
1034
+ payload: Schema.Struct({ liveActivitiesEnabled: Schema.Boolean }),
1035
+ success: Schema.Struct({ ok: Schema.Boolean }),
1036
+ error: EnvironmentHttpCloudErrors,
1037
+ }).middleware(EnvironmentAuthenticatedAuth),
1038
+ )
1039
.add(
1040
HttpApiEndpoint.post("health", "/api/t3-connect/health", {
1041
payload: RelayCloudEnvironmentHealthRequest,
packages/contracts/src/relay.ts
+13
@@ -1262,6 +1262,19 @@ const RelayServerGroup = HttpApiGroup.make("server")
1262
error: RelayAuthAndInternalErrors,
1263
},
1264
).annotate(OpenApi.Summary, "Update an environment's link preferences"),
1265
+ HttpApiEndpoint.post(
1266
+ "updateLiveActivityPreference",
1267
+ "/v1/environments/:environmentId/live-activity-preference",
1268
+ {
1269
+ params: Schema.Struct({ environmentId: EnvironmentId }),
1270
+ payload: Schema.Struct({
1271
+ cloudUserId: Schema.String,
1272
+ liveActivitiesEnabled: Schema.Boolean,
1273
+ }),
1274
+ success: RelayOkResponse,
1275
+ error: RelayAuthAndInternalErrors,
1276
+ },
1277
+ ),
1278
HttpApiEndpoint.post("wakeHeldHooks", "/v1/environments/:environmentId/hooks/wake", {
1279
params: Schema.Struct({ environmentId: EnvironmentId }),
1280
success: RelayWakeHeldHooksResponse,
packages/shared/src/authScopeOptions.ts
+9
-1
@@ -11,6 +11,7 @@ import {
11
AuthPreviewOperateScope,
12
AuthProvidersManageScope,
13
AuthRelayReadScope,
14
+ AuthRelayConfigureScope,
15
AuthRelayWriteScope,
16
AuthSettingsWriteScope,
17
AuthSourceControlWriteScope,
@@ -103,7 +104,14 @@ export const AUTH_SCOPE_OPTIONS: ReadonlyArray<{
104
{
105
scope: AuthRelayWriteScope,
106
title: msg("Manage relay"),
106
- description: msg("Change managed tunnel connectivity."),
107
+ description: msg("Update relay preferences or unlink T3 Connect."),
108
+ },
109
+ {
110
+ scope: AuthRelayConfigureScope,
111
+ title: msg("Configure relay (admin)"),
112
+ description: msg(
113
+ "Set up or replace T3 Connect, including its trusted pairing credential issuer.",
114
+ ),
115
},
116
];
117