@devries-cameron20 / t3code Mirror · read-only / commits / d520d5bb85
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 04:30 UTC

fix(web): show saved service access with Local environment off (#26464)

Co-authored-by: PR Batch Tester <agent@local.test> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: maria-rcks <maria@kuuro.net>

shivam committed Nov 5, 2026 at 07:00 UTC d520d5bb850de9c17c2bbec0f9a37593a2d78d09
25 files changed +852 -509
apps/web/src/cloud/cloudLinkState.ts new
+71
@@ -0,0 +1,71 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 +import {
3 + AuthRelayReadScope,
4 + type EnvironmentCloudLinkStateResult,
5 + type EnvironmentId,
6 +} from "@t3tools/contracts";
7 +import * as Cause from "effect/Cause";
8 +import { AsyncResult, Atom } from "effect/reactivity";
9 +
10 +import { connectionAtomRuntime } from "../connection/runtime";
11 +import { usePrimaryEnvironmentId } from "../state/environments";
12 +import { appAtomRegistry } from "../rpc/atomRegistry";
13 +import { readEnvironmentScope, useEnvironmentScope } from "../state/session";
14 +import { readCloudLinkState, type CloudLinkTarget } from "./linkEnvironment";
15 +import { hasCloudPublicConfig } from "./publicConfig";
16 +
17 +const cloudLinkStateAtom = Atom.family((environmentId: EnvironmentId) =>
18 + connectionAtomRuntime
19 + .atom(readCloudLinkState({ target: { environmentId } }))
20 + .pipe(
21 + Atom.swr({ staleTime: 5_000, revalidateOnMount: true }),
22 + Atom.setIdleTTL(5 * 60_000),
23 + Atom.withLabel(`cloud-link:${environmentId}`),
24 + ),
25 +);
26 +
27 +const EMPTY_CLOUD_LINK_STATE_ATOM = Atom.make(
28 + AsyncResult.success<EnvironmentCloudLinkStateResult | null>(null),
29 +).pipe(Atom.keepAlive, Atom.withLabel("cloud-link:null"));
30 +
31 +function refreshCloudLinkState(target: CloudLinkTarget | null): void {
32 + if (target && readEnvironmentScope(target.environmentId, AuthRelayReadScope)) {
33 + appAtomRegistry.refresh(cloudLinkStateAtom(target.environmentId));
34 + }
35 +}
36 +
37 +export function readCachedCloudLinkState(target: CloudLinkTarget) {
38 + if (!readEnvironmentScope(target.environmentId, AuthRelayReadScope)) return null;
39 + const result = appAtomRegistry.get(cloudLinkStateAtom(target.environmentId));
40 + return result._tag === "Success" ? result.value : null;
41 +}
42 +
43 +export function useCloudLinkState(environmentId: EnvironmentId | null) {
44 + const canReadRelay = useEnvironmentScope(environmentId, AuthRelayReadScope);
45 + const target: CloudLinkTarget | null = environmentId === null ? null : { environmentId };
46 + const atom =
47 + environmentId !== null && hasCloudPublicConfig() && canReadRelay
48 + ? cloudLinkStateAtom(environmentId)
49 + : EMPTY_CLOUD_LINK_STATE_ATOM;
50 + const result = useAtomValue(atom);
51 + const refresh = () => {
52 + refreshCloudLinkState(target);
53 + };
54 + let error: string | null = null;
55 + if (result._tag === "Failure") {
56 + const cause = Cause.squash(result.cause);
57 + error = cause instanceof Error ? cause.message : "Could not read T3 Connect link state.";
58 + }
59 +
60 + return {
61 + data: result._tag === "Failure" ? null : AsyncResult.getOrElse(result, () => null),
62 + error,
63 + isPending: result.waiting,
64 + refresh,
65 + target,
66 + };
67 +}
68 +
69 +export function usePrimaryCloudLinkState() {
70 + return useCloudLinkState(usePrimaryEnvironmentId());
71 +}
apps/web/src/cloud/linkEnvironment.test.ts
+93 -26
@@ -16,6 +16,7 @@ import { afterEach, beforeEach, vi } from "vite-plus/test";
16 import {
17 AVAILABLE_CONNECTION_STATE,
18 type PreparedConnection,
19 + BearerConnectionTarget,
20 PrimaryConnectionTarget,
21 EnvironmentSupervisor,
22 } from "@t3tools/client-runtime/connection";
@@ -25,15 +26,22 @@ import { ManagedRelay } from "@t3tools/client-runtime/relay";
26 import { layerRemoteHttpClient } from "@t3tools/client-runtime/rpc";
27 import { __resetDesktopPrimaryAuthForTests } from "../environments/primary/desktopAuth";
28
28 -import { readPrimaryCloudLinkState, type CloudLinkTarget } from "./linkEnvironment";
29 +import { readCloudLinkState } from "./linkEnvironment";
30
30 -const TARGET: CloudLinkTarget = {
31 +const TARGET = {
32 environmentId: "environment-1",
33 label: "Desktop",
34 httpBaseUrl: "http://127.0.0.1:3000",
35 wsBaseUrl: "ws://127.0.0.1:3000",
36 };
37
38 +const SAVED_SERVICE_TARGET = {
39 + environmentId: "saved-service",
40 + label: "Service",
41 + httpBaseUrl: "http://127.0.0.1:3773",
42 + wsBaseUrl: "ws://127.0.0.1:3773",
43 +};
44 +
45 const relayClientInstallDialog = vi.hoisted(() => ({
46 requestConfirmation: vi.fn(),
47 reportProgress: vi.fn(),
@@ -88,26 +96,73 @@ function layerRegistry(options?: {
96 inboundFrames: Effect.succeed(0),
97 closed: Effect.never,
98 };
91 - const target = new PrimaryConnectionTarget({
92 - environmentId: EnvironmentId.make(TARGET.environmentId),
93 - label: TARGET.label,
94 - httpBaseUrl: TARGET.httpBaseUrl,
95 - wsBaseUrl: TARGET.wsBaseUrl,
99 + const makeSupervisor = Effect.fn(function* (prepared: Option.Option<PreparedConnection>) {
100 + return EnvironmentSupervisor.EnvironmentSupervisor.of({
101 + target: new PrimaryConnectionTarget({
102 + environmentId: EnvironmentId.make(TARGET.environmentId),
103 + label: TARGET.label,
104 + httpBaseUrl: TARGET.httpBaseUrl,
105 + wsBaseUrl: TARGET.wsBaseUrl,
106 + }),
107 + state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
108 + session: yield* SubscriptionRef.make(Option.some(session)),
109 + prepared: yield* SubscriptionRef.make(prepared),
110 + connect: Effect.void,
111 + disconnect: Effect.void,
112 + retryNow: Effect.void,
113 + } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
114 });
97 - const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
98 - target,
99 - state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
100 - session: yield* SubscriptionRef.make(Option.some(session)),
101 - prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
102 - connect: Effect.void,
103 - disconnect: Effect.void,
104 - retryNow: Effect.void,
105 - } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
115 + const supervisors = new Map([
116 + [
117 + TARGET.environmentId,
118 + yield* makeSupervisor(
119 + Option.some({
120 + environmentId: EnvironmentId.make(TARGET.environmentId),
121 + label: TARGET.label,
122 + httpBaseUrl: TARGET.httpBaseUrl,
123 + socketUrl: `${TARGET.wsBaseUrl}/ws`,
124 + httpAuthorization: { _tag: "Bearer", token: "desktop-bearer-token" },
125 + target: new PrimaryConnectionTarget({
126 + environmentId: EnvironmentId.make(TARGET.environmentId),
127 + label: TARGET.label,
128 + httpBaseUrl: TARGET.httpBaseUrl,
129 + wsBaseUrl: TARGET.wsBaseUrl,
130 + }),
131 + }),
132 + ),
133 + ],
134 + [
135 + SAVED_SERVICE_TARGET.environmentId,
136 + yield* makeSupervisor(
137 + Option.some({
138 + environmentId: EnvironmentId.make(SAVED_SERVICE_TARGET.environmentId),
139 + label: SAVED_SERVICE_TARGET.label,
140 + httpBaseUrl: SAVED_SERVICE_TARGET.httpBaseUrl,
141 + socketUrl: `${SAVED_SERVICE_TARGET.wsBaseUrl}/ws`,
142 + httpAuthorization: { _tag: "Bearer", token: "saved-service-token" },
143 + target: new BearerConnectionTarget({
144 + environmentId: EnvironmentId.make(SAVED_SERVICE_TARGET.environmentId),
145 + label: SAVED_SERVICE_TARGET.label,
146 + connectionId: "saved-service-connection",
147 + }),
148 + }),
149 + ),
150 + ],
151 + ]);
152 + const supervisorFor = (environmentId: EnvironmentId) => supervisors.get(environmentId)!;
153 const registry = {
107 - run: <A, E, R>(_environmentId: EnvironmentId, effect: Effect.Effect<A, E, R>) =>
108 - Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
109 - runStream: <A, E, R>(_environmentId: EnvironmentId, stream: Stream.Stream<A, E, R>) =>
110 - Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
154 + run: <A, E, R>(environmentId: EnvironmentId, effect: Effect.Effect<A, E, R>) =>
155 + Effect.provideService(
156 + effect,
157 + EnvironmentSupervisor.EnvironmentSupervisor,
158 + supervisorFor(environmentId),
159 + ),
160 + runStream: <A, E, R>(environmentId: EnvironmentId, stream: Stream.Stream<A, E, R>) =>
161 + Stream.provideService(
162 + stream,
163 + EnvironmentSupervisor.EnvironmentSupervisor,
164 + supervisorFor(environmentId),
165 + ),
166 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"];
167 return EnvironmentRegistry.EnvironmentRegistry.of(registry);
168 }),
@@ -145,9 +200,9 @@ afterEach(() => {
200 });
201
202 describe("web cloud link environment client", () => {
148 - it.effect("uses desktop bearer auth for primary cloud link state", () =>
203 + it.effect("reads link state from the chosen environment with its own credentials", () =>
204 Effect.gen(function* () {
150 - const fetchMock = vi.fn().mockResolvedValue(
205 + const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) =>
206 Response.json({
207 linked: true,
208 cloudUserId: "user-1",
@@ -165,11 +220,23 @@ describe("web cloud link environment client", () => {
220 } as unknown as DesktopBridge,
221 });
222
168 - yield* withServices(readPrimaryCloudLinkState({ target: TARGET }));
223 + for (const [target, token] of [
224 + [TARGET, "desktop-bearer-token"],
225 + [SAVED_SERVICE_TARGET, "saved-service-token"],
226 + ] as const) {
227 + fetchMock.mockClear();
228 + yield* withServices(
229 + readCloudLinkState({
230 + target: { environmentId: EnvironmentId.make(target.environmentId) },
231 + }),
232 + );
233
170 - const request = new Request(fetchMock.mock.calls[0]?.[0], fetchMock.mock.calls[0]?.[1]);
171 - expect(request.credentials).not.toBe("include");
172 - expect(request.headers.get("authorization")).toBe("Bearer desktop-bearer-token");
234 + const [input, init] = fetchMock.mock.calls[0]!;
235 + const request = new Request(input, init);
236 + expect(new URL(request.url).origin).toBe(target.httpBaseUrl);
237 + expect(request.credentials).not.toBe("include");
238 + expect(request.headers.get("authorization")).toBe(`Bearer ${token}`);
239 + }
240 }),
241 );
242 });
apps/web/src/cloud/linkEnvironment.ts
+145 -71
@@ -3,7 +3,8 @@ import * as Effect from "effect/Effect";
3 import * as Option from "effect/Option";
4 import * as Schema from "effect/Schema";
5 import * as Stream from "effect/Stream";
6 -import { HttpClient } from "effect/http";
6 +import * as SubscriptionRef from "effect/SubscriptionRef";
7 +import type { HttpClient } from "effect/http";
8 import {
9 EnvironmentCloudEndpointUnavailableError,
10 type EnvironmentCloudLinkStateResult,
@@ -19,12 +20,11 @@ import {
20 type RelayEnvironmentLinkResponse,
21 type RelayManagedEndpointProviderKind,
22 } from "@t3tools/contracts/relay";
22 -import { EnvironmentRegistry } from "@t3tools/client-runtime/connection";
23 +import { EnvironmentRegistry, EnvironmentSupervisor } from "@t3tools/client-runtime/connection";
24 import { request, runStream } from "@t3tools/client-runtime/rpc";
24 -import { makeEnvironmentHttpApiClient } from "@t3tools/client-runtime/rpc";
25 import { ManagedRelay, relayRequestFailureDetail } from "@t3tools/client-runtime/relay";
26 +import { executeConnectedEnvironmentHttpRequest } from "@t3tools/client-runtime/state/environmentHttpAuth";
27
27 -import * as PrimaryEnvironmentHttpLayer from "../environments/primary/httpLayer";
28 import { resolveCloudPublicConfig } from "./publicConfig";
29 import {
30 finishRelayClientInstall,
@@ -176,62 +176,125 @@ function ensureLinkedEnvironmentMatches(input: {
176 }
177
178 export interface CloudLinkTarget {
179 - readonly environmentId: string;
180 - readonly label: string;
181 - readonly httpBaseUrl: string;
182 - readonly wsBaseUrl: string;
179 + readonly environmentId: EnvironmentId;
180 }
181
182 export type CloudLinkState = EnvironmentCloudLinkStateResult;
183
187 -export const readPrimaryCloudLinkState: (input: {
184 +// Linking can install the relay client and start a managed tunnel before it answers.
185 +const CLOUD_LINK_REQUEST_TIMEOUT_MS = 60_000;
186 +
187 +type ConnectedEnvironmentHttpRequest<A, E, R> = Parameters<
188 + typeof executeConnectedEnvironmentHttpRequest<"connect", A, E, R>
189 +>[0];
190 +
191 +/** Runs on the target environment with this client's own credentials for it. */
192 +const connectRequest = <A, E, R>(
193 + target: CloudLinkTarget,
194 + input: Omit<ConnectedEnvironmentHttpRequest<A, E, R>, "group" | "timeoutMs">,
195 + failureMessage: string,
196 +) =>
197 + Effect.flatMap(EnvironmentRegistry.EnvironmentRegistry, (registry) =>
198 + registry.run(
199 + target.environmentId,
200 + executeConnectedEnvironmentHttpRequest({
201 + ...input,
202 + group: "connect",
203 + timeoutMs: CLOUD_LINK_REQUEST_TIMEOUT_MS,
204 + }),
205 + ),
206 + ).pipe(Effect.mapError(environmentApiError(failureMessage)));
207 +
208 +const preparedEndpoint = (target: CloudLinkTarget) =>
209 + Effect.flatMap(EnvironmentRegistry.EnvironmentRegistry, (registry) =>
210 + registry.run(
211 + target.environmentId,
212 + Effect.flatMap(EnvironmentSupervisor.EnvironmentSupervisor, (supervisor) =>
213 + SubscriptionRef.get(supervisor.prepared),
214 + ),
215 + ),
216 + ).pipe(
217 + Effect.mapError(environmentApiError("Could not reach the environment.")),
218 + Effect.flatMap(
219 + Option.match({
220 + onNone: () =>
221 + Effect.fail(
222 + new CloudEnvironmentLinkError({ message: "The environment is not connected." }),
223 + ),
224 + onSome: ({ httpBaseUrl, target }) =>
225 + Effect.succeed({
226 + httpBaseUrl,
227 + wsBaseUrl:
228 + target._tag === "PrimaryConnectionTarget"
229 + ? target.wsBaseUrl
230 + : httpBaseUrl.replace(/^http/, "ws"),
231 + }),
232 + }),
233 + ),
234 + );
235 +
236 +type CloudLinkServices = EnvironmentRegistry.EnvironmentRegistry | HttpClient.HttpClient;
237 +
238 +export const readCloudLinkState: (input: {
239 readonly target: CloudLinkTarget;
189 -}) => Effect.Effect<CloudLinkState | null, CloudEnvironmentLinkError, HttpClient.HttpClient> =
190 - Effect.fn("linkEnvironment.readPrimaryCloudLinkState")(function* (input: {
240 +}) => Effect.Effect<CloudLinkState | null, CloudEnvironmentLinkError, CloudLinkServices> =
241 + Effect.fn("linkEnvironment.readCloudLinkState")(function* (input: {
242 readonly target: CloudLinkTarget;
243 }) {
193 - const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
194 - return yield* client.connect
195 - .linkState({ headers: {} })
196 - .pipe(Effect.mapError(environmentApiError("Could not read environment cloud link state.")));
197 - }, Effect.provide(PrimaryEnvironmentHttpLayer.layer));
244 + return yield* connectRequest(
245 + input.target,
246 + {
247 + method: "GET",
248 + url: (urls) => urls.linkState(),
249 + request: ({ client, headers }) => client.linkState({ headers }),
250 + },
251 + "Could not read environment cloud link state.",
252 + );
253 + });
254
199 -export const updatePrimaryCloudPreferences: (input: {
255 +export const updateCloudPreferences: (input: {
256 readonly target: CloudLinkTarget;
257 readonly publishAgentActivity: boolean;
258 readonly holdWebhooksWhileOffline?: boolean;
203 -}) => Effect.Effect<CloudLinkState, CloudEnvironmentLinkError, HttpClient.HttpClient> = Effect.fn(
204 - "linkEnvironment.updatePrimaryCloudPreferences",
259 +}) => Effect.Effect<CloudLinkState, CloudEnvironmentLinkError, CloudLinkServices> = Effect.fn(
260 + "linkEnvironment.updateCloudPreferences",
261 )(function* (input: {
262 readonly target: CloudLinkTarget;
263 readonly publishAgentActivity: boolean;
264 readonly holdWebhooksWhileOffline?: boolean;
265 }) {
210 - const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
211 - const { target: _target, ...payload } = input;
212 - return yield* client.connect
213 - .preferences({
214 - headers: {},
215 - payload,
216 - })
217 - .pipe(Effect.mapError(environmentApiError("Could not update environment cloud preferences.")));
218 -}, Effect.provide(PrimaryEnvironmentHttpLayer.layer));
266 + const { target, ...payload } = input;
267 + return yield* connectRequest(
268 + target,
269 + {
270 + method: "POST",
271 + url: (urls) => urls.preferences(),
272 + request: ({ client, headers }) => client.preferences({ headers, payload }),
273 + },
274 + "Could not update environment cloud preferences.",
275 + );
276 +});
277
220 -export const unlinkPrimaryEnvironmentFromCloud: (input: {
278 +export const unlinkEnvironmentFromCloud: (input: {
279 readonly target: CloudLinkTarget;
280 readonly clerkToken: string | null;
281 }) => Effect.Effect<
282 void,
283 CloudEnvironmentLinkError,
226 - HttpClient.HttpClient | ManagedRelay.ManagedRelayClient
227 -> = Effect.fn("linkEnvironment.unlinkPrimaryEnvironmentFromCloud")(function* (input: {
284 + CloudLinkServices | ManagedRelay.ManagedRelayClient
285 +> = Effect.fn("linkEnvironment.unlinkEnvironmentFromCloud")(function* (input: {
286 readonly target: CloudLinkTarget;
287 readonly clerkToken: string | null;
288 }) {
231 - const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
232 - yield* client.connect
233 - .unlink({ headers: {} })
234 - .pipe(Effect.mapError(environmentApiError("Could not unlink the environment from cloud.")));
289 + yield* connectRequest(
290 + input.target,
291 + {
292 + method: "POST",
293 + url: (urls) => urls.unlink(),
294 + request: ({ client, headers }) => client.unlink({ headers }),
295 + },
296 + "Could not unlink the environment from cloud.",
297 + );
298
299 const configuredRelayUrl = relayUrl();
300 if (configuredRelayUrl && input.clerkToken) {
@@ -239,7 +302,7 @@ export const unlinkPrimaryEnvironmentFromCloud: (input: {
302 yield* relayClient
303 .unlinkEnvironment({
304 clerkToken: input.clerkToken,
242 - environmentId: EnvironmentId.make(input.target.environmentId),
305 + environmentId: input.target.environmentId,
306 })
307 .pipe(
308 Effect.catch((cause) =>
@@ -249,21 +312,21 @@ export const unlinkPrimaryEnvironmentFromCloud: (input: {
312 ),
313 );
314 }
252 -}, Effect.provide(PrimaryEnvironmentHttpLayer.layer));
315 +});
316
317 export type CloudLinkMode = "managed" | "publish_only";
318
319 const PUBLISH_ONLY_PROVIDER_KIND = "manual" satisfies RelayManagedEndpointProviderKind;
320
258 -export const linkPrimaryEnvironmentToCloud: (input: {
321 +export const linkEnvironmentToCloud: (input: {
322 readonly target: CloudLinkTarget;
323 readonly clerkToken: string;
324 readonly mode?: CloudLinkMode;
325 }) => Effect.Effect<
326 void,
327 CloudEnvironmentLinkError,
265 - EnvironmentRegistry.EnvironmentRegistry | HttpClient.HttpClient | ManagedRelay.ManagedRelayClient
266 -> = Effect.fn("linkEnvironment.linkPrimaryEnvironmentToCloud")(function* (input: {
328 + CloudLinkServices | ManagedRelay.ManagedRelayClient
329 +> = Effect.fn("linkEnvironment.linkEnvironmentToCloud")(function* (input: {
330 readonly target: CloudLinkTarget;
331 readonly clerkToken: string;
332 readonly mode?: CloudLinkMode;
@@ -279,9 +342,10 @@ export const linkPrimaryEnvironmentToCloud: (input: {
342 ? MANAGED_ENDPOINT_PROVIDER_KIND
343 : PUBLISH_ONLY_PROVIDER_KIND;
344 const relayClient = yield* ManagedRelay.ManagedRelayClient;
282 - const environmentClient = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
345 + // The environment only signs a proof for the loopback origin this request reaches it on.
346 + const endpoint = yield* preparedEndpoint(input.target);
347 if (managedTunnelsEnabled) {
284 - yield* ensureRelayClientAvailable(EnvironmentId.make(input.target.environmentId));
348 + yield* ensureRelayClientAvailable(input.target.environmentId);
349 }
350
351 const challenge = yield* relayClient
@@ -300,21 +364,24 @@ export const linkPrimaryEnvironmentToCloud: (input: {
364 ),
365 ),
366 );
303 - const proof = yield* environmentClient.connect
304 - .linkProof({
305 - headers: {},
306 - payload: {
307 - challenge: challenge.challenge,
308 - relayIssuer: configuredRelayUrl,
309 - endpoint: {
310 - httpBaseUrl: input.target.httpBaseUrl,
311 - wsBaseUrl: input.target.wsBaseUrl,
312 - providerKind,
313 - },
314 - origin: endpointOrigin(input.target.httpBaseUrl),
315 - },
316 - })
317 - .pipe(Effect.mapError(environmentApiError("Could not obtain environment link proof.")));
367 + const proof = yield* connectRequest(
368 + input.target,
369 + {
370 + method: "POST",
371 + url: (urls) => urls.linkProof(),
372 + request: ({ client, headers }) =>
373 + client.linkProof({
374 + headers,
375 + payload: {
376 + challenge: challenge.challenge,
377 + relayIssuer: configuredRelayUrl,
378 + endpoint: { ...endpoint, providerKind },
379 + origin: endpointOrigin(endpoint.httpBaseUrl),
380 + },
381 + }),
382 + },
383 + "Could not obtain environment link proof.",
384 + );
385 const link = yield* relayClient
386 .linkEnvironment({
387 clerkToken: input.clerkToken,
@@ -336,17 +403,24 @@ export const linkPrimaryEnvironmentToCloud: (input: {
403 link,
404 });
405
339 - yield* environmentClient.connect
340 - .relayConfig({
341 - headers: {},
342 - payload: {
343 - relayUrl: configuredRelayUrl,
344 - relayIssuer: link.relayIssuer,
345 - cloudUserId: link.cloudUserId,
346 - environmentCredential: link.environmentCredential,
347 - cloudMintPublicKey: link.cloudMintPublicKey,
348 - endpointRuntime: link.endpointRuntime,
349 - },
350 - })
351 - .pipe(Effect.mapError(environmentApiError("Could not configure environment relay access.")));
352 -}, Effect.provide(PrimaryEnvironmentHttpLayer.layer));
406 + yield* connectRequest(
407 + input.target,
408 + {
409 + method: "POST",
410 + url: (urls) => urls.relayConfig(),
411 + request: ({ client, headers }) =>
412 + client.relayConfig({
413 + headers,
414 + payload: {
415 + relayUrl: configuredRelayUrl,
416 + relayIssuer: link.relayIssuer,
417 + cloudUserId: link.cloudUserId,
418 + environmentCredential: link.environmentCredential,
419 + cloudMintPublicKey: link.cloudMintPublicKey,
420 + endpointRuntime: link.endpointRuntime,
421 + },
422 + }),
423 + },
424 + "Could not configure environment relay access.",
425 + );
426 +});
apps/web/src/cloud/linkEnvironmentAtoms.ts
+12 -12
@@ -5,11 +5,11 @@ import {
5
6 import { connectionAtomRuntime } from "../connection/runtime";
7 import {
8 - linkPrimaryEnvironmentToCloud,
8 + linkEnvironmentToCloud,
9 type CloudLinkMode,
10 type CloudLinkTarget,
11 - unlinkPrimaryEnvironmentFromCloud,
12 - updatePrimaryCloudPreferences,
11 + unlinkEnvironmentFromCloud,
12 + updateCloudPreferences,
13 } from "./linkEnvironment";
14
15 const cloudLinkScheduler = createAtomCommandScheduler();
@@ -18,32 +18,32 @@ const cloudLinkConcurrency = {
18 key: (input: { readonly target: CloudLinkTarget }) => input.target.environmentId,
19 };
20
21 -export const linkPrimaryEnvironment = createRuntimeCommand(connectionAtomRuntime, {
22 - label: "web:cloud:link-primary-environment",
21 +export const linkEnvironment = createRuntimeCommand(connectionAtomRuntime, {
22 + label: "web:cloud:link-environment",
23 scheduler: cloudLinkScheduler,
24 concurrency: cloudLinkConcurrency,
25 execute: (input: {
26 readonly target: CloudLinkTarget;
27 readonly clerkToken: string;
28 readonly mode?: CloudLinkMode;
29 - }) => linkPrimaryEnvironmentToCloud(input),
29 + }) => linkEnvironmentToCloud(input),
30 });
31
32 -export const unlinkPrimaryEnvironment = createRuntimeCommand(connectionAtomRuntime, {
33 - label: "web:cloud:unlink-primary-environment",
32 +export const unlinkEnvironment = createRuntimeCommand(connectionAtomRuntime, {
33 + label: "web:cloud:unlink-environment",
34 scheduler: cloudLinkScheduler,
35 concurrency: cloudLinkConcurrency,
36 execute: (input: { readonly target: CloudLinkTarget; readonly clerkToken: string | null }) =>
37 - unlinkPrimaryEnvironmentFromCloud(input),
37 + unlinkEnvironmentFromCloud(input),
38 });
39
40 -export const updatePrimaryEnvironmentPreferences = createRuntimeCommand(connectionAtomRuntime, {
41 - label: "web:cloud:update-primary-environment-preferences",
40 +export const updateEnvironmentPreferences = createRuntimeCommand(connectionAtomRuntime, {
41 + label: "web:cloud:update-environment-preferences",
42 scheduler: cloudLinkScheduler,
43 concurrency: cloudLinkConcurrency,
44 execute: (input: {
45 readonly target: CloudLinkTarget;
46 readonly publishAgentActivity: boolean;
47 readonly holdWebhooksWhileOffline?: boolean;
48 - }) => updatePrimaryCloudPreferences(input),
48 + }) => updateCloudPreferences(input),
49 });
apps/web/src/cloud/primaryCloudLinkState.ts deleted
-98
@@ -1,98 +0,0 @@
1 -import { useAtomValue } from "@effect/atom-react";
2 -import {
3 - AuthRelayReadScope,
4 - EnvironmentId,
5 - type EnvironmentCloudLinkStateResult,
6 -} from "@t3tools/contracts";
7 -import * as Cause from "effect/Cause";
8 -import * as Context from "effect/Context";
9 -import * as Effect from "effect/Effect";
10 -import * as Layer from "effect/Layer";
11 -import { AsyncResult, Atom } from "effect/reactivity";
12 -import { HttpClient } from "effect/http";
13 -
14 -import { usePrimaryEnvironment } from "../state/environments";
15 -import { runtime } from "../lib/runtime";
16 -import { appAtomRegistry } from "../rpc/atomRegistry";
17 -import { readEnvironmentScope, useEnvironmentScope } from "../state/session";
18 -import { readPrimaryCloudLinkState, type CloudLinkTarget } from "./linkEnvironment";
19 -import { hasCloudPublicConfig } from "./publicConfig";
20 -
21 -const primaryCloudLinkAtomRuntime = Atom.runtime(
22 - Layer.effect(
23 - HttpClient.HttpClient,
24 - runtime.contextEffect.pipe(
25 - Effect.map((context) => Context.get(context, HttpClient.HttpClient)),
26 - ),
27 - ),
28 -);
29 -
30 -const primaryCloudLinkStateAtom = Atom.family((key: string) => {
31 - const target = JSON.parse(key) as CloudLinkTarget;
32 - return primaryCloudLinkAtomRuntime
33 - .atom(readPrimaryCloudLinkState({ target }))
34 - .pipe(
35 - Atom.swr({ staleTime: 5_000, revalidateOnMount: true }),
36 - Atom.setIdleTTL(5 * 60_000),
37 - Atom.withLabel(`primary-cloud-link:${target.environmentId}`),
38 - );
39 -});
40 -
41 -const EMPTY_PRIMARY_CLOUD_LINK_STATE_ATOM = Atom.make(
42 - AsyncResult.success<EnvironmentCloudLinkStateResult | null>(null),
43 -).pipe(Atom.keepAlive, Atom.withLabel("primary-cloud-link:null"));
44 -
45 -function targetKey(target: CloudLinkTarget): string {
46 - return JSON.stringify(target);
47 -}
48 -
49 -function refreshPrimaryCloudLinkState(target: CloudLinkTarget | null): void {
50 - if (
51 - target &&
52 - readEnvironmentScope(EnvironmentId.make(target.environmentId), AuthRelayReadScope)
53 - ) {
54 - appAtomRegistry.refresh(primaryCloudLinkStateAtom(targetKey(target)));
55 - }
56 -}
57 -
58 -export function readCachedPrimaryCloudLinkState(target: CloudLinkTarget) {
59 - if (!readEnvironmentScope(EnvironmentId.make(target.environmentId), AuthRelayReadScope))
60 - return null;
61 - const result = appAtomRegistry.get(primaryCloudLinkStateAtom(targetKey(target)));
62 - return result._tag === "Success" ? result.value : null;
63 -}
64 -
65 -export function usePrimaryCloudLinkState() {
66 - const primary = usePrimaryEnvironment();
67 - const canReadRelay = useEnvironmentScope(primary?.environmentId ?? null, AuthRelayReadScope);
68 - const target =
69 - primary?.entry.target._tag === "PrimaryConnectionTarget"
70 - ? {
71 - environmentId: primary.environmentId,
72 - label: primary.label,
73 - httpBaseUrl: primary.entry.target.httpBaseUrl,
74 - wsBaseUrl: primary.entry.target.wsBaseUrl,
75 - }
76 - : null;
77 - const atom =
78 - target && hasCloudPublicConfig() && canReadRelay
79 - ? primaryCloudLinkStateAtom(targetKey(target))
80 - : EMPTY_PRIMARY_CLOUD_LINK_STATE_ATOM;
81 - const result = useAtomValue(atom);
82 - const refresh = () => {
83 - refreshPrimaryCloudLinkState(target);
84 - };
85 - let error: string | null = null;
86 - if (result._tag === "Failure") {
87 - const cause = Cause.squash(result.cause);
88 - error = cause instanceof Error ? cause.message : "Could not read T3 Connect link state.";
89 - }
90 -
91 - return {
92 - data: result._tag === "Failure" ? null : AsyncResult.getOrElse(result, () => null),
93 - error,
94 - isPending: result.waiting,
95 - refresh,
96 - target,
97 - };
98 -}
apps/web/src/cloud/useCloudLinkController.browser.test.tsx
+10 -15
@@ -38,7 +38,7 @@ vi.mock(import("@effect/atom-react"), async (original) => ({
38 ? []
39 : [
40 [
41 - "primary",
41 + "service",
42 { environment: { endpoint: { providerKind: testState.relayProviderKind } } },
43 ],
44 ],
@@ -73,15 +73,15 @@ vi.mock(import("../state/use-atom-command"), async (original) => ({
73 }));
74 vi.mock(import("./linkEnvironmentAtoms"), async (original) => ({
75 ...(await original()),
76 - linkPrimaryEnvironment: testState.link as never,
77 - unlinkPrimaryEnvironment: testState.unlink as never,
78 - updatePrimaryEnvironmentPreferences: testState.preferences as never,
76 + linkEnvironment: testState.link as never,
77 + unlinkEnvironment: testState.unlink as never,
78 + updateEnvironmentPreferences: testState.preferences as never,
79 }));
80 -vi.mock(import("./primaryCloudLinkState"), async (original) => ({
80 +vi.mock(import("./cloudLinkState"), async (original) => ({
81 ...(await original()),
82 - readCachedPrimaryCloudLinkState: () => testState.snapshot,
83 - usePrimaryCloudLinkState: (() => ({
84 - target,
82 + readCachedCloudLinkState: () => testState.snapshot,
83 + useCloudLinkState: ((environmentId: EnvironmentId | null) => ({
84 + target: environmentId === null ? null : { environmentId },
85 data: testState.renderedSnapshot,
86 error: null,
87 isPending: false,
@@ -96,12 +96,7 @@ vi.mock(import("./publicConfig"), async (original) => ({
96 import { CloudEnvironmentLinkError } from "./linkEnvironment";
97 import { useCloudLinkController, type CloudLinkDesiredState } from "./useCloudLinkController";
98
99 -const target = {
100 - environmentId: EnvironmentId.make("primary"),
101 - label: "Primary",
102 - httpBaseUrl: "http://localhost:3773",
103 - wsBaseUrl: "ws://localhost:3773/ws",
104 -};
99 +const target = { environmentId: EnvironmentId.make("service") };
100 const linkedState: EnvironmentCloudLinkStateResult = {
101 linked: true,
102 cloudUserId: "account-1",
@@ -114,7 +109,7 @@ const linkedState: EnvironmentCloudLinkStateResult = {
109 type Controller = ReturnType<typeof useCloudLinkController>;
110
111 function ControllerProbe({ onRender }: { onRender: (controller: Controller) => void }) {
117 - const value = useCloudLinkController();
112 + const value = useCloudLinkController(target.environmentId);
113 useLayoutEffect(() => {
114 onRender(value);
115 });
apps/web/src/cloud/useCloudLinkController.ts
+31 -33
@@ -2,10 +2,10 @@ import { useAtomValue } from "@effect/atom-react";
2 import { useAuth } from "@clerk/react";
3 import { findErrorTraceId } from "@t3tools/client-runtime/errors";
4 import {
5 - EnvironmentId,
5 AuthRelayReadScope,
6 AuthRelayWriteScope,
7 type EnvironmentCloudLinkStateResult,
8 + type EnvironmentId,
9 } from "@t3tools/contracts";
10 import { ManagedRelay } from "@t3tools/client-runtime/relay";
11 import type { RelayManagedEndpointProviderKind } from "@t3tools/contracts/relay";
@@ -24,11 +24,11 @@ import { useAtomCommand } from "../state/use-atom-command";
24 import { CloudEnvironmentLinkError } from "./linkEnvironment";
25 import { refreshManagedTunnelUsage } from "./managedRelayState";
26 import {
27 - linkPrimaryEnvironment as linkPrimaryEnvironmentAtom,
28 - unlinkPrimaryEnvironment as unlinkPrimaryEnvironmentAtom,
29 - updatePrimaryEnvironmentPreferences as updatePrimaryEnvironmentPreferencesAtom,
27 + linkEnvironment as linkEnvironmentAtom,
28 + unlinkEnvironment as unlinkEnvironmentAtom,
29 + updateEnvironmentPreferences as updateEnvironmentPreferencesAtom,
30 } from "./linkEnvironmentAtoms";
31 -import { readCachedPrimaryCloudLinkState, usePrimaryCloudLinkState } from "./primaryCloudLinkState";
31 +import { readCachedCloudLinkState, useCloudLinkState } from "./cloudLinkState";
32 import { resolveRelayClerkTokenOptions } from "./publicConfig";
33
34 export interface CloudLinkDesiredState {
@@ -62,26 +62,24 @@ function tunnelLimitFromLinkFailure(cause: unknown): number | null {
62 : null;
63 }
64
65 -export function useCloudLinkController() {
65 +export function useCloudLinkController(environmentId: EnvironmentId | null) {
66 const { getToken, isSignedIn } = useAuth();
67 const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refresh, {
68 reportFailure: false,
69 });
70 - const linkPrimaryEnvironment = useAtomCommand(linkPrimaryEnvironmentAtom, {
70 + const linkEnvironment = useAtomCommand(linkEnvironmentAtom, {
71 reportFailure: false,
72 });
73 - const unlinkPrimaryEnvironment = useAtomCommand(unlinkPrimaryEnvironmentAtom, {
73 + const unlinkEnvironment = useAtomCommand(unlinkEnvironmentAtom, {
74 reportFailure: false,
75 });
76 - const updatePrimaryEnvironmentPreferences = useAtomCommand(
77 - updatePrimaryEnvironmentPreferencesAtom,
78 - { reportFailure: false },
79 - );
80 - const primaryCloudLinkState = usePrimaryCloudLinkState();
76 + const updateEnvironmentPreferences = useAtomCommand(updateEnvironmentPreferencesAtom, {
77 + reportFailure: false,
78 + });
79 + const cloudLinkState = useCloudLinkState(environmentId);
80 const relayEnvironments = useAtomValue(relayEnvironmentDiscovery.stateValueAtom).environments;
82 - const primaryEnvironmentId = primaryCloudLinkState.target?.environmentId;
83 - const relayProviderKind = primaryEnvironmentId
84 - ? relayEnvironments.get(primaryEnvironmentId)?.environment.endpoint.providerKind
81 + const relayProviderKind = environmentId
82 + ? relayEnvironments.get(environmentId)?.environment.endpoint.providerKind
83 : undefined;
84 const [operationError, setOperationError] = useState<string | null>(null);
85 const [tunnelLimit, setTunnelLimit] = useState<number | null>(null);
@@ -106,24 +104,24 @@ export function useCloudLinkController() {
104 });
105 };
106
109 - const linkData = primaryCloudLinkState.data;
107 + const linkData = cloudLinkState.data;
108 const linkRevoked = linkData?.linkRevoked ?? false;
109 const managedTunnelActive = linkData ? isManagedTunnelActive(linkData, relayProviderKind) : false;
110 const managedTunnelOutOfSync =
111 linkData !== null && !managedTunnelActive && isManagedTunnelActive(linkData, undefined);
114 - const publishAgentActivity = primaryCloudLinkState.data?.publishAgentActivity ?? false;
115 - const holdWebhooksWhileOffline = primaryCloudLinkState.data?.holdWebhooksWhileOffline ?? false;
116 - const linked = !linkRevoked && (primaryCloudLinkState.data?.linked ?? false);
112 + const publishAgentActivity = cloudLinkState.data?.publishAgentActivity ?? false;
113 + const holdWebhooksWhileOffline = cloudLinkState.data?.holdWebhooksWhileOffline ?? false;
114 + const linked = !linkRevoked && (cloudLinkState.data?.linked ?? false);
115
116 const reconcileCloudState = async (desired: CloudLinkDesiredState): Promise<boolean> => {
117 setOperationError(null);
118 setTunnelLimit(null);
121 - const target = primaryCloudLinkState.target;
119 + const target = cloudLinkState.target;
120 if (!target) {
123 - reportUpdateFailure(new Error("Local environment is not ready yet."));
121 + reportUpdateFailure(new Error("Choose an environment first."));
122 return false;
123 }
126 - const environmentId = EnvironmentId.make(target.environmentId);
124 + const environmentId = target.environmentId;
125 const canManageLink = () => {
126 if (
127 !readEnvironmentScope(environmentId, AuthRelayReadScope) ||
@@ -137,7 +135,7 @@ export function useCloudLinkController() {
135 return true;
136 };
137 const readLinkState = () => {
140 - const state = readCachedPrimaryCloudLinkState(target);
138 + const state = readCachedCloudLinkState(target);
139 if (state === null) {
140 reportUpdateFailure(new Error("Wait until the current T3 Connect settings can be read."));
141 }
@@ -152,7 +150,7 @@ export function useCloudLinkController() {
150 // A failed mutation may have partially applied, so refresh server state on every exit.
151 if (!wantsLink) {
152 // Unlink needs no relay token; failed token reads must still allow it.
155 - const unlinkResult = await unlinkPrimaryEnvironment({
153 + const unlinkResult = await unlinkEnvironment({
154 target,
155 clerkToken: tokenResult._tag === "Success" ? (tokenResult.value ?? null) : null,
156 });
@@ -161,7 +159,7 @@ export function useCloudLinkController() {
159 if (!isAtomCommandInterrupted(unlinkResult)) {
160 reportUpdateFailure(squashAtomCommandFailure(unlinkResult));
161 }
164 - primaryCloudLinkState.refresh();
162 + cloudLinkState.refresh();
163 return false;
164 }
165 } else {
@@ -182,7 +180,7 @@ export function useCloudLinkController() {
180 currentLinkState.linkRevoked === true ||
181 currentManagedTunnel !== desired.managedTunnel
182 ) {
185 - const linkResult = await linkPrimaryEnvironment({
183 + const linkResult = await linkEnvironment({
184 target,
185 clerkToken,
186 mode: desired.managedTunnel ? "managed" : "publish_only",
@@ -197,15 +195,15 @@ export function useCloudLinkController() {
195 if (limit === null) reportUpdateFailure(cause);
196 else setTunnelLimit(limit);
197 }
200 - primaryCloudLinkState.refresh();
198 + cloudLinkState.refresh();
199 return false;
200 }
201 }
202 if (!canManageLink() || readLinkState() === null) {
205 - primaryCloudLinkState.refresh();
203 + cloudLinkState.refresh();
204 return false;
205 }
208 - const prefResult = await updatePrimaryEnvironmentPreferences({
206 + const prefResult = await updateEnvironmentPreferences({
207 target,
208 publishAgentActivity: desired.publish,
209 ...(desired.holdWebhooksWhileOffline === undefined
@@ -216,12 +214,12 @@ export function useCloudLinkController() {
214 if (!isAtomCommandInterrupted(prefResult)) {
215 reportUpdateFailure(squashAtomCommandFailure(prefResult));
216 }
219 - primaryCloudLinkState.refresh();
217 + cloudLinkState.refresh();
218 return false;
219 }
220 }
221
224 - primaryCloudLinkState.refresh();
222 + cloudLinkState.refresh();
223 const refreshResult = await refreshRelayEnvironments();
224 if (refreshResult._tag === "Failure" && !isAtomCommandInterrupted(refreshResult)) {
225 reportUpdateFailure(squashAtomCommandFailure(refreshResult));
@@ -232,7 +230,7 @@ export function useCloudLinkController() {
230
231 return {
232 isSignedIn,
235 - linkState: primaryCloudLinkState,
233 + linkState: cloudLinkState,
234 linked,
235 linkRevoked,
236 managedTunnelActive,
apps/web/src/components/cloud/ConnectOnboardingDialog.tsx
+1 -1
@@ -77,7 +77,7 @@ function ConfiguredConnectOnboardingDialog() {
77 const sessionScopesKnown =
78 primaryEnvironmentId === null ? environmentsReady : primarySessionState._tag !== "Initial";
79
80 - const controller = useCloudLinkController();
80 + const controller = useCloudLinkController(primaryEnvironmentId);
81 const accountPage = useT3ConnectAccountPage();
82 const showPublishStep = canManageRelay && controller.linkState.target !== null;
83 const steps: ReadonlyArray<OnboardingStep> = showPublishStep
apps/web/src/components/settings/AuthorizedClientsSettings.browser.test.tsx new
+80
@@ -0,0 +1,80 @@
1 +import {
2 + EnvironmentId,
3 + managedCapabilityDenial,
4 + type ManagedPolicySummary,
5 +} from "@t3tools/contracts";
6 +import { describe, expect, it, vi } from "vite-plus/test";
7 +
8 +import "~/index.css";
9 +import { render } from "../../../test/render";
10 +import { AuthorizedClientsHeaderAction } from "./AuthorizedClientsSettings";
11 +
12 +const localId = EnvironmentId.make("local");
13 +const serviceId = EnvironmentId.make("service");
14 +
15 +const state = vi.hoisted(() => ({
16 + primaryEnvironmentId: null as string | null,
17 + policies: new Map<string, unknown>(),
18 +}));
19 +
20 +vi.mock(import("../../state/environments"), async (original) => ({
21 + ...(await original()),
22 + usePrimaryEnvironmentId: (() => state.primaryEnvironmentId) as never,
23 +}));
24 +vi.mock(import("../../state/entities"), async (original) => ({
25 + ...(await original()),
26 + useServerConfigs: (() =>
27 + new Map(
28 + [...state.policies].map(([environmentId, managedPolicy]) => [
29 + environmentId,
30 + { managedPolicy },
31 + ]),
32 + )) as never,
33 +}));
34 +vi.mock(import("../../state/use-atom-command"), async (original) => ({
35 + ...(await original()),
36 + useAtomCommand: (() => vi.fn()) as never,
37 +}));
38 +
39 +const remoteClientsOff: ManagedPolicySummary = {
40 + organization: "Example Corp",
41 + lockedSettings: [],
42 + limits: { clients: ["desktop"] },
43 +};
44 +
45 +function setup(policies: ReadonlyArray<readonly [EnvironmentId, ManagedPolicySummary]>) {
46 + state.primaryEnvironmentId = localId;
47 + state.policies = new Map(policies);
48 +}
49 +
50 +const renderHeader = (environmentId: EnvironmentId) =>
51 + render(
52 + <AuthorizedClientsHeaderAction
53 + environmentId={environmentId}
54 + onPairingLinkCreated={() => {}}
55 + clientSessions={null}
56 + isRevokingOtherClients={false}
57 + onRevokeOtherClients={() => {}}
58 + delegatableScopes={[]}
59 + />,
60 + );
61 +
62 +describe("AuthorizedClientsHeaderAction", () => {
63 + const denial = managedCapabilityDenial(remoteClientsOff, "remoteClients")!;
64 +
65 + it("follows the selected service's policy, not the primary's", async () => {
66 + setup([[serviceId, remoteClientsOff]]);
67 + await using screen = await renderHeader(serviceId);
68 +
69 + await expect.element(screen.getByRole("group", { name: denial })).toBeVisible();
70 + await expect.element(screen.getByRole("button", { name: "Create link" })).toBeDisabled();
71 + });
72 +
73 + it("leaves pairing open on an unmanaged service when the primary is managed", async () => {
74 + setup([[localId, remoteClientsOff]]);
75 + await using screen = await renderHeader(serviceId);
76 +
77 + await expect.element(screen.getByRole("button", { name: "Create link" })).toBeEnabled();
78 + expect(screen.getByRole("group", { name: denial }).query()).toBeNull();
79 + });
80 +});
apps/web/src/components/settings/AuthorizedClientsSettings.tsx
+32 -20
@@ -13,9 +13,12 @@ import {
13 type AuthGrantScope,
14 type AuthPairingCredentialResult,
15 type AdvertisedEndpoint,
16 + type EnvironmentId,
17 } from "@t3tools/contracts";
17 -import { settlePromise } from "@t3tools/client-runtime/state/runtime";
18 -import * as Cause from "effect/Cause";
18 +import {
19 + isAtomCommandInterrupted,
20 + squashAtomCommandFailure,
21 +} from "@t3tools/client-runtime/state/runtime";
22
23 import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
24 import { cn } from "../../lib/utils";
@@ -47,14 +50,14 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
50 import { Button } from "../ui/button";
51 import { Textarea } from "../ui/textarea";
52 import {
50 - createServerPairingCredential,
53 isLoopbackHostname,
54 type ServerClientSessionRecord,
55 type ServerPairingLinkRecord,
56 } from "~/environments/primary";
57 +import { authEnvironment } from "~/state/auth";
58 import { readEnvironmentScope } from "~/state/session";
56 -import { usePrimaryEnvironmentId } from "~/state/environments";
57 -import { usePrimaryManagedPolicy } from "~/state/managedPolicy";
59 +import { useManagedPolicy, usePrimaryManagedPolicy } from "~/state/managedPolicy";
60 +import { useAtomCommand } from "~/state/use-atom-command";
61 import { ManagedControl } from "../ManagedPolicy";
62 import { ConnectionStatusDot } from "../ConnectionStatusDot";
63 import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "./itemRows";
@@ -124,6 +127,8 @@ type PairingLinkListRowProps = {
127 pairingLink: ServerPairingLinkRecord;
128 credential: string | undefined;
129 defaultShareOpen: boolean;
130 + /** Whether this page is served by the environment the link pairs with. */
131 + servedByEnvironment: boolean;
132 endpointUrl: string | null | undefined;
133 endpoints: ReadonlyArray<AdvertisedEndpoint>;
134 defaultEndpointKey: string | null;
@@ -136,6 +141,7 @@ const PairingLinkListRow = memo(function PairingLinkListRow({
141 pairingLink,
142 credential,
143 defaultShareOpen,
144 + servedByEnvironment,
145 endpointUrl,
146 endpoints,
147 defaultEndpointKey,
@@ -191,7 +197,7 @@ const PairingLinkListRow = memo(function PairingLinkListRow({
197 endpointPairingUrl ??
198 (credential && endpointUrl != null && endpointUrl !== ""
199 ? (hostedPairingUrl ?? resolveDesktopPairingUrl(endpointUrl, credential))
194 - : isLoopbackHostname(window.location.hostname)
200 + : !servedByEnvironment || isLoopbackHostname(window.location.hostname)
201 ? null
202 : currentOriginPairingUrl);
203 const [failedCopyValue, setFailedCopyValue] = useState<string | null>(null);
@@ -567,6 +573,7 @@ const ConnectedClientListRow = memo(function ConnectedClientListRow({
573 });
574
575 type AuthorizedClientsHeaderActionProps = {
576 + environmentId: EnvironmentId;
577 onPairingLinkCreated: (result: AuthPairingCredentialResult) => void;
578 clientSessions: ReadonlyArray<ServerClientSessionRecord> | null;
579 isRevokingOtherClients: boolean;
@@ -575,14 +582,17 @@ type AuthorizedClientsHeaderActionProps = {
582 };
583
584 export const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderAction({
585 + environmentId,
586 onPairingLinkCreated,
587 clientSessions,
588 isRevokingOtherClients,
589 onRevokeOtherClients,
590 delegatableScopes,
591 }: AuthorizedClientsHeaderActionProps) {
584 - const primaryEnvironmentId = usePrimaryEnvironmentId();
585 - const pairingDenial = managedCapabilityDenial(usePrimaryManagedPolicy(), "remoteClients");
592 + const pairingDenial = managedCapabilityDenial(useManagedPolicy(environmentId), "remoteClients");
593 + const createPairingCredential = useAtomCommand(authEnvironment.createPairingCredential, {
594 + reportFailure: false,
595 + });
596 const [dialogOpen, setDialogOpen] = useState(false);
597 const [pairingLabel, setPairingLabel] = useState("");
598 const [pairingScopes, setPairingScopes] = useState<ReadonlyArray<AuthGrantScope>>([
@@ -593,27 +603,26 @@ export const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHead
603
604 const handleCreatePairingLink = async () => {
605 if (
596 - primaryEnvironmentId === null ||
606 selectedScopes.length === 0 ||
598 - !readEnvironmentScope(primaryEnvironmentId, AuthAccessWriteScope) ||
599 - !selectedScopes.every((scope) => readEnvironmentScope(primaryEnvironmentId, scope))
607 + !readEnvironmentScope(environmentId, AuthAccessWriteScope) ||
608 + !selectedScopes.every((scope) => readEnvironmentScope(environmentId, scope))
609 )
610 return;
611 setIsCreatingPairingLink(true);
603 - const settled = await settlePromise(async () => {
604 - const created = await createServerPairingCredential({
605 - label: pairingLabel,
606 - scopes: selectedScopes,
607 - });
608 - onPairingLinkCreated(created);
612 + const trimmedLabel = pairingLabel.trim();
613 + const result = await createPairingCredential({
614 + environmentId,
615 + input: { ...(trimmedLabel ? { label: trimmedLabel } : {}), scopes: selectedScopes },
616 + });
617 + if (result._tag === "Success") {
618 + onPairingLinkCreated(result.value);
619 setPairingLabel("");
620 setPairingScopes(
621 AuthStandardClientScopes.filter((scope) => delegatableScopes.includes(scope)),
622 );
623 setDialogOpen(false);
614 - });
615 - if (settled._tag === "Failure") {
616 - const error = Cause.squash(settled.cause);
624 + } else if (!isAtomCommandInterrupted(result)) {
625 + const error = squashAtomCommandFailure(result);
626 const message = error instanceof Error ? error.message : "Failed to create pairing URL.";
627 toastManager.add(
628 stackedThreadToast({
@@ -787,6 +796,7 @@ export const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHead
796 });
797
798 type PairingClientsListProps = {
799 + servedByEnvironment: boolean;
800 endpointUrl: string | null | undefined;
801 endpoints: ReadonlyArray<AdvertisedEndpoint>;
802 defaultEndpointKey: string | null;
@@ -803,6 +813,7 @@ type PairingClientsListProps = {
813 };
814
815 export const PairingClientsList = memo(function PairingClientsList({
816 + servedByEnvironment,
817 endpointUrl,
818 endpoints,
819 defaultEndpointKey,
@@ -825,6 +836,7 @@ export const PairingClientsList = memo(function PairingClientsList({
836 pairingLink={pairingLink}
837 credential={createdPairingCredentials.get(pairingLink.id)}
838 defaultShareOpen={pairingLink.id === sharedPairingLinkId}
839 + servedByEnvironment={servedByEnvironment}
840 endpointUrl={endpointUrl}
841 endpoints={endpoints}
842 defaultEndpointKey={defaultEndpointKey}
apps/web/src/components/settings/ConnectionsSettings.logic.test.ts
+58 -1
@@ -1,7 +1,8 @@
1 -import type { DesktopWslState } from "@t3tools/contracts";
1 +import { type DesktopWslState, EnvironmentId } from "@t3tools/contracts";
2 import { describe, expect, it, vi } from "vite-plus/test";
3 import {
4 applyWslEnableSelection,
5 + resolveAccessEnvironmentId,
6 resolveTailscaleServeBaseUrl,
7 selectQrEndpointOption,
8 togglePairingScopeSelection,
@@ -144,3 +145,59 @@ describe("selectQrEndpointOption", () => {
145 );
146 });
147 });
148 +
149 +describe("resolveAccessEnvironmentId", () => {
150 + const primary = EnvironmentId.make("primary");
151 + const service = EnvironmentId.make("service");
152 + const laptop = EnvironmentId.make("laptop");
153 + it.each([
154 + {
155 + label: "defaults to the primary environment",
156 + primaryEnvironmentId: primary,
157 + environments: [
158 + { environmentId: primary, connected: true },
159 + { environmentId: service, connected: true },
160 + ],
161 + selected: null,
162 + expected: primary,
163 + },
164 + {
165 + label: "falls back to a connected saved environment without a primary",
166 + primaryEnvironmentId: null,
167 + environments: [
168 + { environmentId: laptop, connected: false },
169 + { environmentId: service, connected: true },
170 + ],
171 + selected: null,
172 + expected: service,
173 + },
174 + {
175 + label: "keeps an explicit choice",
176 + primaryEnvironmentId: primary,
177 + environments: [
178 + { environmentId: primary, connected: true },
179 + { environmentId: laptop, connected: false },
180 + ],
181 + selected: laptop,
182 + expected: laptop,
183 + },
184 + {
185 + label: "drops a choice that is no longer listed",
186 + primaryEnvironmentId: null,
187 + environments: [{ environmentId: service, connected: true }],
188 + selected: laptop,
189 + expected: service,
190 + },
191 + {
192 + label: "has nothing to show without environments",
193 + primaryEnvironmentId: null,
194 + environments: [],
195 + selected: null,
196 + expected: null,
197 + },
198 + ])("$label", ({ primaryEnvironmentId, environments, selected, expected }) => {
199 + expect(resolveAccessEnvironmentId({ primaryEnvironmentId, environments, selected })).toBe(
200 + expected,
201 + );
202 + });
203 +});
apps/web/src/components/settings/ConnectionsSettings.logic.ts
+20
@@ -19,6 +19,7 @@ import {
19 type DesktopSshEnvironmentTarget,
20 type DesktopUpdateState,
21 type DesktopWslState,
22 + type EnvironmentId,
23 } from "@t3tools/contracts";
24 import {
25 getDesktopUpdateDownloadedVersion,
@@ -436,3 +437,22 @@ export function endpointShareHint(endpoint: AdvertisedEndpoint, url: string): st
437 return "Clients on this machine";
438 }
439 }
440 +
441 +/** An explicit choice while it is listed, else the primary, else a connected environment. */
442 +export function resolveAccessEnvironmentId(input: {
443 + readonly primaryEnvironmentId: EnvironmentId | null;
444 + readonly environments: ReadonlyArray<{
445 + readonly environmentId: EnvironmentId;
446 + readonly connected: boolean;
447 + }>;
448 + readonly selected: EnvironmentId | null;
449 +}): EnvironmentId | null {
450 + const isListed = (environmentId: EnvironmentId | null) =>
451 + input.environments.some((environment) => environment.environmentId === environmentId);
452 + if (isListed(input.selected)) return input.selected;
453 + if (isListed(input.primaryEnvironmentId)) return input.primaryEnvironmentId;
454 + return (
455 + (input.environments.find((environment) => environment.connected) ?? input.environments[0])
456 + ?.environmentId ?? null
457 + );
458 +}
apps/web/src/components/settings/ConnectionsSettings.tsx
+169 -71
@@ -1,7 +1,7 @@
1 import { SessionPermissions } from "./SessionPermissions";
2 import { ChevronRightIcon, EllipsisIcon } from "lucide-react";
3 import { useAtomValue } from "@effect/atom-react";
4 -import { useState } from "react";
4 +import { type ReactNode, useState } from "react";
5 import {
6 AuthAccessReadScope,
7 AuthAccessWriteScope,
@@ -30,9 +30,11 @@ import {
30 applyWslEnableSelection,
31 isWslSettingsRowVisible,
32 missingTailscaleEndpointDescription,
33 + resolveAccessEnvironmentId,
34 resolveLocalVersionStatusLabel,
35 resolveTailscaleServeBaseUrl,
36 } from "./ConnectionsSettings.logic";
37 +import { settingsScopeEnvironmentLabel } from "./settingsScopeAxis";
38 import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";
39 import { ManagedByOrganization } from "../ManagedPolicy";
40 import { LocalEnvironmentSetting } from "./LocalEnvironmentSetting";
@@ -72,13 +74,7 @@ import { stackedThreadToast, toastManager } from "../ui/toast";
74 import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
75 import { Button } from "../ui/button";
76 import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
75 -import {
76 - revokeOtherServerClientSessions,
77 - revokeServerClientSession,
78 - revokeServerPairingLink,
79 - usePrimarySessionState,
80 - type ServerClientSessionRecord,
81 -} from "~/environments/primary";
77 +import { type ServerClientSessionRecord } from "~/environments/primary";
78 import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";
79 import { useUiStateStore } from "~/uiStateStore";
80 import {
@@ -90,7 +86,11 @@ import { hasCloudPublicConfig } from "~/cloud/publicConfig";
86 import { RemoveT3ConnectEnvironmentDialog } from "../clerk/RemoveT3ConnectEnvironmentDialog";
87 import { authEnvironment } from "~/state/auth";
88 import { environmentCatalog } from "~/connection/catalog";
93 -import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
89 +import {
90 + readEnvironmentScope,
91 + useEnvironmentScope,
92 + useEnvironmentSessionState,
93 +} from "~/state/session";
94 import { useEnvironmentQuery } from "~/state/query";
95 import {
96 desktopNetworkAccessStateAtom,
@@ -100,8 +100,10 @@ import { desktopWslStateAtom, refreshDesktopWslState } from "~/state/desktopWslS
100 import { useDesktopUpdateState } from "~/state/desktopUpdate";
101 import {
102 type EnvironmentPresentation,
103 + useEnvironment,
104 useEnvironments,
105 usePrimaryEnvironment,
106 + usePrimaryEnvironmentId,
107 } from "~/state/environments";
108 import { requestConfirmDialog } from "~/confirmDialog";
109 import { useAtomCommand } from "../../state/use-atom-command";
@@ -154,8 +156,98 @@ function LocalVersionStatusLabel() {
156 );
157 }
158
157 -/** Environments lists the machines this app connects to; access covers who may reach this one. */
159 +/** Environments lists the machines this app connects to; access covers who may reach one of them. */
160 export function ConnectionsSettings({ view }: { readonly view: "environments" | "access" }) {
161 + return view === "access" ? (
162 + <AccessSettings />
163 + ) : (
164 + <ConnectionsSettingsContent view="environments" accessEnvironmentId={null} />
165 + );
166 +}
167 +
168 +function AccessSettings() {
169 + const { environments } = useEnvironments();
170 + const primaryEnvironmentId = usePrimaryEnvironmentId();
171 + const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(null);
172 + const candidates = environments.filter(
173 + (environment) =>
174 + environment.environmentId === primaryEnvironmentId ||
175 + (environment.entry.enabled && !isDesktopLocalConnectionTarget(environment.entry.target)),
176 + );
177 + const accessEnvironmentId = resolveAccessEnvironmentId({
178 + primaryEnvironmentId,
179 + environments: candidates.map((environment) => ({
180 + environmentId: environment.environmentId,
181 + connected: environment.connection.phase === "connected",
182 + })),
183 + selected: selectedEnvironmentId,
184 + });
185 + const picker =
186 + candidates.length > 1 && accessEnvironmentId !== null ? (
187 + <div className="flex min-w-0 items-center gap-1.5 px-3 text-sm text-muted-foreground sm:px-4">
188 + <span className="shrink-0">Showing access for</span>
189 + <Select
190 + value={accessEnvironmentId}
191 + onValueChange={(next) => {
192 + if (next !== null) setSelectedEnvironmentId(next);
193 + }}
194 + >
195 + <SelectTrigger size="sm" className="w-auto max-w-72" aria-label="Environment">
196 + <SelectValue>
197 + {(value: EnvironmentId) => {
198 + const environment = candidates.find(
199 + (candidate) => candidate.environmentId === value,
200 + );
201 + return environment ? settingsScopeEnvironmentLabel(environment, candidates) : null;
202 + }}
203 + </SelectValue>
204 + </SelectTrigger>
205 + <SelectPopup alignItemWithTrigger={false}>
206 + {candidates.map((environment) => (
207 + <SelectItem
208 + hideIndicator
209 + key={environment.environmentId}
210 + value={environment.environmentId}
211 + >
212 + <span className="flex min-w-0 items-center gap-2">
213 + <EnvironmentMachineIcon
214 + aria-hidden
215 + kind={resolveEnvironmentMachineKind(environment.serverConfig)}
216 + className="size-3.5 shrink-0"
217 + />
218 + <span className="min-w-0 truncate">
219 + {settingsScopeEnvironmentLabel(environment, candidates)}
220 + </span>
221 + {environment.connection.phase !== "connected" ? (
222 + <span className="shrink-0 text-xs text-muted-foreground">Offline</span>
223 + ) : null}
224 + </span>
225 + </SelectItem>
226 + ))}
227 + </SelectPopup>
228 + </Select>
229 + </div>
230 + ) : null;
231 + // Keyed so pairing credentials and pending work never carry over to another environment.
232 + return (
233 + <ConnectionsSettingsContent
234 + key={accessEnvironmentId ?? "none"}
235 + view="access"
236 + accessEnvironmentId={accessEnvironmentId}
237 + accessEnvironmentPicker={picker}
238 + />
239 + );
240 +}
241 +
242 +function ConnectionsSettingsContent({
243 + view,
244 + accessEnvironmentId,
245 + accessEnvironmentPicker = null,
246 +}: {
247 + readonly view: "environments" | "access";
248 + readonly accessEnvironmentId: EnvironmentId | null;
249 + readonly accessEnvironmentPicker?: ReactNode;
250 +}) {
251 const desktopBridge = window.desktopBridge;
252 const { environments } = useEnvironments();
253 const primaryEnvironment = usePrimaryEnvironment();
@@ -165,11 +257,15 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |
257 reportFailure: false,
258 });
259 const primaryEnvironmentId = primaryEnvironment?.environmentId ?? null;
168 - const primarySessionState = usePrimarySessionState();
169 - const currentSessionScopes = primarySessionState.data?.authenticated
170 - ? (primarySessionState.data.permissions ?? primarySessionState.data.scopes ?? null)
260 + const accessEnvironment = useEnvironment(accessEnvironmentId);
261 + // Desktop network, Tailscale, and WSL controls change the backend this app spawned.
262 + const isPrimaryAccess =
263 + accessEnvironmentId !== null && accessEnvironmentId === primaryEnvironmentId;
264 + const accessSessionState = useEnvironmentSessionState(accessEnvironmentId);
265 + const currentSessionScopes = accessSessionState.data?.authenticated
266 + ? (accessSessionState.data.permissions ?? accessSessionState.data.scopes ?? null)
267 : null;
172 - const currentAuthPolicy = desktopBridge ? null : (primarySessionState.data?.auth.policy ?? null);
268 + const currentAuthPolicy = desktopBridge ? null : (accessSessionState.data?.auth.policy ?? null);
269 const savedEnvironments = environments.filter(
270 (environment) => environment.entry.target._tag !== "PrimaryConnectionTarget",
271 );
@@ -272,9 +368,11 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |
368 DesktopServerExposureState["mode"] | null
369 >(null);
370 const primaryServerConfig = primaryEnvironment?.serverConfig ?? null;
275 - const primaryManagedPolicy = primaryServerConfig?.managedPolicy;
371 // Turning remote access off stays possible; only the way in is managed.
277 - const remoteClientsDenial = managedCapabilityDenial(primaryManagedPolicy, "remoteClients");
372 + const remoteClientsDenial = managedCapabilityDenial(
373 + primaryServerConfig?.managedPolicy,
374 + "remoteClients",
375 + );
376 const primaryVersionMismatch = resolveServerConfigVersionMismatch(primaryServerConfig);
377 const primaryServerUpdateState = useAtomValue(
378 serverEnvironment.updateStateAtom(primaryEnvironmentId),
@@ -286,21 +384,28 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |
384 const setDefaultAdvertisedEndpointKey = useUiStateStore(
385 (state) => state.setDefaultAdvertisedEndpointKey,
386 );
289 - const canReadAccess = useEnvironmentScope(primaryEnvironmentId, AuthAccessReadScope);
290 - const canWriteAccess = useEnvironmentScope(primaryEnvironmentId, AuthAccessWriteScope);
291 - const canReadRelay = useEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope);
292 - const canMaintain = useEnvironmentScope(primaryEnvironmentId, AuthEnvironmentMaintainScope);
293 - const canManageRelay = useEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope);
294 - const canManageLocalBackend = !isLocalEnvironmentDisabled() && canMaintain;
387 + const canReadAccess = useEnvironmentScope(accessEnvironmentId, AuthAccessReadScope);
388 + const canWriteAccess = useEnvironmentScope(accessEnvironmentId, AuthAccessWriteScope);
389 + const canReadRelay = useEnvironmentScope(accessEnvironmentId, AuthRelayReadScope);
390 + const canMaintain = useEnvironmentScope(accessEnvironmentId, AuthEnvironmentMaintainScope);
391 + const canManageRelay = useEnvironmentScope(accessEnvironmentId, AuthRelayWriteScope);
392 + const canManageLocalBackend = isPrimaryAccess && !isLocalEnvironmentDisabled() && canMaintain;
393 const showsAccess = view === "access";
394 const authAccessChanges = useEnvironmentQuery(
297 - showsAccess && canReadAccess && primaryEnvironmentId !== null
395 + showsAccess && canReadAccess && accessEnvironmentId !== null
396 ? authEnvironment.accessChanges({
299 - environmentId: primaryEnvironmentId,
397 + environmentId: accessEnvironmentId,
398 input: null,
399 })
400 : null,
401 );
402 + const revokePairingLink = useAtomCommand(authEnvironment.revokePairingLink, {
403 + reportFailure: false,
404 + });
405 + const revokeClient = useAtomCommand(authEnvironment.revokeClient, { reportFailure: false });
406 + const revokeOtherClients = useAtomCommand(authEnvironment.revokeOtherClients, {
407 + reportFailure: false,
408 + });
409 const desktopNetworkAccess = useEnvironmentQuery(
410 showsAccess && canManageLocalBackend && desktopBridge ? desktopNetworkAccessStateAtom : null,
411 );
@@ -468,17 +573,15 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |
573
574 const handleRevokeDesktopPairingLink = async (id: string) => {
575 if (
471 - primaryEnvironmentId === null ||
472 - !readEnvironmentScope(primaryEnvironmentId, AuthAccessWriteScope)
576 + accessEnvironmentId === null ||
577 + !readEnvironmentScope(accessEnvironmentId, AuthAccessWriteScope)
578 )
579 return;
580 setRevokingDesktopPairingLinkId(id);
581 setDesktopAccessManagementMutationError(null);
477 - const settled = await settlePromise(async () => {
478 - await revokeServerPairingLink(id);
479 - });
480 - if (settled._tag === "Failure") {
481 - const error = Cause.squash(settled.cause);
582 + const result = await revokePairingLink({ environmentId: accessEnvironmentId, input: { id } });
583 + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
584 + const error = squashAtomCommandFailure(result);
585 const message = error instanceof Error ? error.message : "Failed to revoke pairing link.";
586 setDesktopAccessManagementMutationError(message);
587 toastManager.add(
@@ -496,17 +599,15 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |
599 sessionId: ServerClientSessionRecord["sessionId"],
600 ) => {
601 if (
499 - primaryEnvironmentId === null ||
500 - !readEnvironmentScope(primaryEnvironmentId, AuthAccessWriteScope)
602 + accessEnvironmentId === null ||
603 + !readEnvironmentScope(accessEnvironmentId, AuthAccessWriteScope)
604 )
605 return;
606 setRevokingDesktopClientSessionId(sessionId);
607 setDesktopAccessManagementMutationError(null);
505 - const settled = await settlePromise(async () => {
506 - await revokeServerClientSession(sessionId);
507 - });
508 - if (settled._tag === "Failure") {
509 - const error = Cause.squash(settled.cause);
608 + const result = await revokeClient({ environmentId: accessEnvironmentId, input: { sessionId } });
609 + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
610 + const error = squashAtomCommandFailure(result);
611 const message = error instanceof Error ? error.message : "Failed to revoke client access.";
612 setDesktopAccessManagementMutationError(message);
613 toastManager.add(
@@ -522,22 +623,21 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |
623
624 const handleRevokeOtherDesktopClients = async () => {
625 if (
525 - primaryEnvironmentId === null ||
526 - !readEnvironmentScope(primaryEnvironmentId, AuthAccessWriteScope)
626 + accessEnvironmentId === null ||
627 + !readEnvironmentScope(accessEnvironmentId, AuthAccessWriteScope)
628 )
629 return;
630 setIsRevokingOtherDesktopClients(true);
631 setDesktopAccessManagementMutationError(null);
531 - const settled = await settlePromise(async () => {
532 - const revokedCount = await revokeOtherServerClientSessions();
632 + const result = await revokeOtherClients({ environmentId: accessEnvironmentId, input: null });
633 + if (result._tag === "Success") {
634 toastManager.add({
635 type: "success",
535 - title: revokedCount === 1 ? "Revoked 1 other client" : `Revoked ${revokedCount} clients`,
636 + title: result.value === 1 ? "Revoked 1 other client" : `Revoked ${result.value} clients`,
637 description: "Other paired clients will need a new pairing link before reconnecting.",
638 });
538 - });
539 - if (settled._tag === "Failure") {
540 - const error = Cause.squash(settled.cause);
639 + } else if (!isAtomCommandInterrupted(result)) {
640 + const error = squashAtomCommandFailure(result);
641 const message = error instanceof Error ? error.message : "Failed to revoke other clients.";
642 setDesktopAccessManagementMutationError(message);
643 toastManager.add(
@@ -938,6 +1038,7 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |
1038 clientSessions: typeof desktopClientSessions,
1039 ) => (
1040 <PairingClientsList
1041 + servedByEnvironment={isPrimaryAccess}
1042 endpointUrl={desktopServerExposureState?.endpointUrl}
1043 endpoints={visibleDesktopAdvertisedEndpoints}
1044 defaultEndpointKey={defaultDesktopAdvertisedEndpointKey}
@@ -1033,28 +1134,28 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |
1134 />
1135 );
1136
1137 + const accessServerConfig = accessEnvironment?.serverConfig ?? null;
1138 const primarySettings = (
1139 <>
1038 - {primaryEnvironmentId !== null ? (
1140 + {accessEnvironmentPicker}
1141 + {accessEnvironmentId !== null ? (
1142 <>
1143 <SettingsSection
1144 {...searchableSetting("connections-environment")}
1145 title={
1043 - primaryEnvironment?.label ?? (desktopBridge ? "This machine" : "Primary environment")
1146 + accessEnvironment?.label ?? (desktopBridge ? "This machine" : "Primary environment")
1147 }
1148 icon={
1149 <EnvironmentMachineIcon
1150 aria-hidden
1151 kind={
1049 - primaryServerConfig
1050 - ? resolveEnvironmentMachineKind(primaryServerConfig)
1051 - : "desktop"
1152 + accessServerConfig ? resolveEnvironmentMachineKind(accessServerConfig) : "desktop"
1153 }
1154 className="size-4"
1155 />
1156 }
1157 headerAction={
1057 - primaryEnvironmentId !== null ? (
1158 + accessEnvironmentId !== null ? (
1159 <Menu>
1160 <MenuTrigger
1161 render={
@@ -1070,17 +1171,17 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |
1171 </MenuTrigger>
1172 <MenuPopup align="end">
1173 <EnvironmentIconMenu
1073 - environmentId={primaryEnvironmentId}
1074 - serverConfig={primaryServerConfig}
1174 + environmentId={accessEnvironmentId}
1175 + serverConfig={accessServerConfig}
1176 />
1177 </MenuPopup>
1178 </Menu>
1179 ) : null
1180 }
1181 >
1081 - {primaryManagedPolicy ? (
1182 + {accessServerConfig?.managedPolicy ? (
1183 <div className="px-3 py-2 sm:px-4">
1083 - <ManagedByOrganization policy={primaryManagedPolicy} />
1184 + <ManagedByOrganization policy={accessServerConfig.managedPolicy} />
1185 </div>
1186 ) : null}
1187 {canManageLocalBackend ? (
@@ -1132,19 +1233,18 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |
1233 {renderEndpointRows()}
1234 {renderTailscaleRow()}
1235 {renderWslRow()}
1135 - {canReadRelay || canManageRelay ? (
1136 - <CloudLinkRow canReadRelay={canReadRelay} canManageRelay={canManageRelay} />
1137 - ) : null}
1236 </>
1237 ) : canManageLocalBackend ? (
1140 - <>
1141 - {renderDisabledNetworkAccessRow()}
1142 - {canReadRelay || canManageRelay ? (
1143 - <CloudLinkRow canReadRelay={canReadRelay} canManageRelay={canManageRelay} />
1144 - ) : null}
1145 - </>
1238 + renderDisabledNetworkAccessRow()
1239 ) : null}
1147 - {primaryEnvironment ? (
1240 + {canReadRelay || canManageRelay ? (
1241 + <CloudLinkRow
1242 + environmentId={accessEnvironmentId}
1243 + canReadRelay={canReadRelay}
1244 + canManageRelay={canManageRelay}
1245 + />
1246 + ) : null}
1247 + {accessEnvironment ? (
1248 <details className="group px-3 sm:px-4">
1249 <summary className="flex min-h-11 cursor-pointer list-none items-center gap-2 rounded-md text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring [&::-webkit-details-marker]:hidden">
1250 Permissions
@@ -1154,8 +1254,8 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |
1254 />
1255 </summary>
1256 <SessionPermissions
1157 - environmentId={primaryEnvironment.environmentId}
1158 - connected={primaryEnvironment.connection.phase === "connected"}
1257 + environmentId={accessEnvironment.environmentId}
1258 + connected={accessEnvironment.connection.phase === "connected"}
1259 />
1260 </details>
1261 ) : null}
@@ -1177,6 +1277,7 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |
1277 control={
1278 canWriteAccess ? (
1279 <AuthorizedClientsHeaderAction
1280 + environmentId={accessEnvironmentId}
1281 delegatableScopes={currentSessionScopes ?? []}
1282 onPairingLinkCreated={handlePairingLinkCreated}
1283 clientSessions={
@@ -1481,9 +1582,6 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |
1582 title="No environment selected"
1583 description="Connect an environment to view its settings and access."
1584 />
1484 - {canReadRelay || canManageRelay ? (
1485 - <CloudLinkRow canReadRelay={canReadRelay} canManageRelay={canManageRelay} />
1486 - ) : null}
1585 </SettingsSection>
1586 )}
1587 </>
apps/web/src/components/settings/SavedEnvironmentRows.tsx
+22 -27
@@ -55,13 +55,9 @@ import { useT3ConnectAccountPage } from "../clerk/T3ConnectAccountPages";
55 import { TunnelLimitAlert, TunnelUsageMeter } from "../cloud/TunnelUsage";
56 import { environmentCatalog } from "~/connection/catalog";
57 import { readEnvironmentScope } from "~/state/session";
58 -import {
59 - type EnvironmentPresentation,
60 - useRelayEnvironmentDiscovery,
61 - usePrimaryEnvironmentId,
62 -} from "~/state/environments";
58 +import { type EnvironmentPresentation, useRelayEnvironmentDiscovery } from "~/state/environments";
59 import { APP_VERSION } from "~/branding";
64 -import { usePrimaryManagedPolicy } from "~/state/managedPolicy";
60 +import { useManagedPolicy } from "~/state/managedPolicy";
61 import { useAtomCommand } from "../../state/use-atom-command";
62 import { serverEnvironment } from "~/state/server";
63 import {
@@ -518,11 +514,16 @@ function T3ConnectTunnelUsage({ tunnelLimit }: { readonly tunnelLimit: number |
514 );
515 }
516
521 -function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: boolean }) {
522 - const primaryEnvironmentId = usePrimaryEnvironmentId();
517 +function ConfiguredCloudLinkRow({
518 + environmentId,
519 + canManageRelay,
520 +}: {
521 + readonly environmentId: EnvironmentId;
522 + readonly canManageRelay: boolean;
523 +}) {
524 const {
525 isSignedIn,
525 - linkState: primaryCloudLinkState,
526 + linkState: cloudLinkState,
527 linkRevoked,
528 managedTunnelActive,
529 managedTunnelOutOfSync,
@@ -531,10 +532,10 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
532 operationError,
533 tunnelLimit,
534 reconcileCloudState,
534 - } = useCloudLinkController();
535 + } = useCloudLinkController(environmentId);
536 const { openAuthPrompt } = useT3ConnectAuthPrompt();
537 // The server unlinks and refuses relay changes under such a policy; unlinking stays possible.
537 - const connectDenial = managedCapabilityDenial(usePrimaryManagedPolicy(), "connect");
538 + const connectDenial = managedCapabilityDenial(useManagedPolicy(environmentId), "connect");
539 const [isUpdating, setIsUpdating] = useState(false);
540 const [isUpdatingPreference, setIsUpdatingPreference] = useState(false);
541
@@ -545,8 +546,8 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
546 const switchDisabled =
547 !canManageRelay ||
548 !isSignedIn ||
548 - primaryCloudLinkState.data === null ||
549 - primaryCloudLinkState.isPending ||
549 + cloudLinkState.data === null ||
550 + cloudLinkState.isPending ||
551 isBusy;
552 // `isSignedIn` is undefined until Clerk loads. Signed out, one row shows a
553 // sign-in button instead of its switch; the onboarding dialog that opens after
@@ -557,7 +558,7 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
558 Sign in
559 </Button>
560 );
560 - const refreshLinkState = useEffectEvent(primaryCloudLinkState.refresh);
561 + const refreshLinkState = useEffectEvent(cloudLinkState.refresh);
562 // The server rechecks reachability when the tunnel's 30 s readiness poll changes.
563 // Poll while mounted, so a failed read does not stop later ones.
564 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- 30 s interval that refreshes the cloud link reachability while mounted
@@ -565,7 +566,7 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
566 const interval = window.setInterval(() => refreshLinkState(), 30_000);
567 return () => window.clearInterval(interval);
568 }, []);
568 - const reachability = managedTunnelActive ? primaryCloudLinkState.data?.reachability : undefined;
569 + const reachability = managedTunnelActive ? cloudLinkState.data?.reachability : undefined;
570 const reachabilityStatus =
571 reachability?.status === "reachable" ? (
572 formatConnectReachable(reachability)
@@ -586,11 +587,7 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
587 ) : null;
588
589 const updateManagedTunnel = async (enabled: boolean) => {
589 - if (
590 - primaryEnvironmentId === null ||
591 - !readEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope)
592 - )
593 - return;
590 + if (!readEnvironmentScope(environmentId, AuthRelayWriteScope)) return;
591 setIsUpdating(true);
592 const ok = await reconcileCloudState({ managedTunnel: enabled, publish: publishAgentActivity });
593 if (ok) {
@@ -612,11 +609,7 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
609 };
610
611 const updatePublishAgentActivity = async (enabled: boolean) => {
615 - if (
616 - primaryEnvironmentId === null ||
617 - !readEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope)
618 - )
619 - return;
612 + if (!readEnvironmentScope(environmentId, AuthRelayWriteScope)) return;
613 setIsUpdatingPreference(true);
614 const ok = await reconcileCloudState({ managedTunnel: managedTunnelActive, publish: enabled });
615 if (ok) {
@@ -672,7 +665,7 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
665 ? "T3 Connect is out of sync. This environment is linked only to publish agent activity, so other devices cannot connect. Turn T3 Connect on to repair it."
666 : "Make this environment available to your other devices through T3 Connect."
667 }
675 - status={operationError ?? primaryCloudLinkState.error ?? reachabilityStatus}
668 + status={operationError ?? cloudLinkState.error ?? reachabilityStatus}
669 managed={managedTunnelActive ? undefined : connectDenial}
670 control={
671 signedOut ? (
@@ -742,9 +735,11 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
735 }
736
737 export function CloudLinkRow({
738 + environmentId,
739 canReadRelay,
740 canManageRelay,
741 }: {
742 + readonly environmentId: EnvironmentId;
743 readonly canReadRelay: boolean;
744 readonly canManageRelay: boolean;
745 }) {
@@ -757,7 +752,7 @@ export function CloudLinkRow({
752 />
753 );
754 }
760 - return <ConfiguredCloudLinkRow canManageRelay={canManageRelay} />;
755 + return <ConfiguredCloudLinkRow environmentId={environmentId} canManageRelay={canManageRelay} />;
756 }
757
758 function EmptyRemoteEnvironments({ cloudEnabled = true }: { readonly cloudEnabled?: boolean }) {
apps/web/src/components/settings/ScheduledTasksSettings.tsx
+1 -1
@@ -48,7 +48,7 @@ import { formatRelativeTime } from "../../timestampFormat";
48 import { useEnvironmentSettings } from "../../hooks/useSettings";
49 import { getCustomModelOptionsByInstance } from "../../modelSelection";
50 import { providerInstanceEntriesFor } from "../../providerInstances";
51 -import { usePrimaryCloudLinkState } from "../../cloud/primaryCloudLinkState";
51 +import { usePrimaryCloudLinkState } from "../../cloud/cloudLinkState";
52 import { requestConfirmDialog } from "../../confirmDialog";
53 import { webhookAddress } from "@t3tools/client-runtime/webhook-address";
54 import { Link, useNavigate } from "@tanstack/react-router";
apps/web/src/components/settings/SettingsScopeSentence.tsx
+1 -1
@@ -49,7 +49,7 @@ export const SETTINGS_DEVICE_ONLY_PATHS: ReadonlySet<string> = new Set([
49 "/settings/diffs",
50 "/settings/snap-shot",
51 "/settings/connections",
52 - // Network access and authorized clients belong to the environment serving this app.
52 + // Access picks its environment on the page itself.
53 "/settings/access",
54 "/settings/about",
55 ]);
apps/web/src/components/settings/useAvailableSettingsSearchItems.ts
+1 -1
@@ -1,6 +1,6 @@
1 import { AuthEnvironmentMaintainScope } from "@t3tools/contracts";
2
3 -import { usePrimaryCloudLinkState } from "~/cloud/primaryCloudLinkState";
3 +import { usePrimaryCloudLinkState } from "~/cloud/cloudLinkState";
4 import { hasCloudPublicConfig } from "~/cloud/publicConfig";
5 import { isElectron } from "~/env";
6 import { isLocalEnvironmentDisabled } from "~/localEnvironment";
apps/web/src/environments/primary/auth.ts
-79
@@ -2,8 +2,6 @@ import type {
2 AuthBrowserSessionResult,
3 AuthClientMetadata,
4 AuthEnvironmentScope,
5 - AuthGrantScope,
6 - AuthPairingCredentialResult,
5 ServerAuthSessionMethod,
6 AuthSessionId,
7 AuthSessionState,
@@ -347,83 +345,6 @@ export async function submitServerAuthCredential(credential: string): Promise<vo
345 stripPairingTokenFromUrl();
346 }
347
350 -export async function createServerPairingCredential(input?: {
351 - readonly label?: string;
352 - readonly scopes?: ReadonlyArray<AuthGrantScope>;
353 -}): Promise<AuthPairingCredentialResult> {
354 - const trimmedLabel = input?.label?.trim();
355 - try {
356 - return await runPrimaryHttp(
357 - PrimaryEnvironmentHttpClient.pipe(
358 - Effect.flatMap((client) =>
359 - client.auth.pairingCredential({
360 - headers: {},
361 - payload: {
362 - ...(trimmedLabel ? { label: trimmedLabel } : {}),
363 - ...(input?.scopes ? { scopes: input.scopes } : {}),
364 - },
365 - }),
366 - ),
367 - ),
368 - );
369 - } catch (error) {
370 - throw PrimaryEnvironmentRequestError.fromCause({
371 - operation: "create-pairing-credential",
372 - cause: error,
373 - });
374 - }
375 -}
376 -
377 -export async function revokeServerPairingLink(id: string): Promise<void> {
378 - try {
379 - await runPrimaryHttp(
380 - PrimaryEnvironmentHttpClient.pipe(
381 - Effect.flatMap((client) => client.auth.revokePairingLink({ headers: {}, payload: { id } })),
382 - ),
383 - );
384 - } catch (error) {
385 - throw PrimaryEnvironmentRequestError.fromCause({
386 - operation: "revoke-pairing-link",
387 - pairingLinkId: id,
388 - cause: error,
389 - });
390 - }
391 -}
392 -
393 -export async function revokeServerClientSession(sessionId: AuthSessionId): Promise<void> {
394 - try {
395 - await runPrimaryHttp(
396 - PrimaryEnvironmentHttpClient.pipe(
397 - Effect.flatMap((client) =>
398 - client.auth.revokeClient({ headers: {}, payload: { sessionId } }),
399 - ),
400 - ),
401 - );
402 - } catch (error) {
403 - throw PrimaryEnvironmentRequestError.fromCause({
404 - operation: "revoke-client-session",
405 - sessionId,
406 - cause: error,
407 - });
408 - }
409 -}
410 -
411 -export async function revokeOtherServerClientSessions(): Promise<number> {
412 - try {
413 - const result = await runPrimaryHttp(
414 - PrimaryEnvironmentHttpClient.pipe(
415 - Effect.flatMap((client) => client.auth.revokeOtherClients({ headers: {} })),
416 - ),
417 - );
418 - return result.revokedCount;
419 - } catch (error) {
420 - throw PrimaryEnvironmentRequestError.fromCause({
421 - operation: "revoke-other-client-sessions",
422 - cause: error,
423 - });
424 - }
425 -}
426 -
348 export async function resolveInitialServerAuthGateState(): Promise<ServerAuthGateState> {
349 // Preserve explicit grant replacement across the auth-gate reload triggered by token removal.
350 if (window.location.pathname.replace(/\/+$/, "") !== "/pair") {
apps/web/src/environments/primary/index.ts
-6
@@ -1,12 +1,8 @@
1 export {
2 - createServerPairingCredential,
2 peekPairingTokenFromUrl,
3 PrimaryEnvironmentPairingCredentialRejectedError,
4 PrimaryEnvironmentRequestError,
5 resolveInitialServerAuthGateState,
7 - revokeOtherServerClientSessions,
8 - revokeServerClientSession,
9 - revokeServerPairingLink,
6 stripPairingTokenFromUrl,
7 submitServerAuthCredential,
8 takePairingTokenFromUrl,
@@ -15,8 +11,6 @@ export {
11 __resetServerAuthBootstrapForTests,
12 } from "./auth";
13
18 -export { usePrimarySessionState } from "./sessionState";
19 -
14 export {
15 DesktopEnvironmentBootstrapIncompleteError,
16 PrimaryEnvironmentProtocolUnsupportedError,
apps/web/src/environments/primary/sessionState.ts deleted
-37
@@ -1,37 +0,0 @@
1 -import { useAtomValue } from "@effect/atom-react";
2 -import * as Cause from "effect/Cause";
3 -import * as Effect from "effect/Effect";
4 -import { AsyncResult, Atom } from "effect/reactivity";
5 -
6 -import { isLocalEnvironmentDisabled } from "../../localEnvironment";
7 -import { appAtomRegistry } from "../../rpc/atomRegistry";
8 -import { fetchSessionState } from "./auth";
9 -
10 -const primarySessionStateAtom = Atom.make(
11 - Effect.suspend(() =>
12 - isLocalEnvironmentDisabled() ? Effect.succeed(null) : Effect.promise(fetchSessionState),
13 - ),
14 -).pipe(
15 - Atom.swr({ staleTime: 5_000, revalidateOnMount: true }),
16 - Atom.setIdleTTL(5 * 60_000),
17 - Atom.withLabel("primary-environment:session"),
18 -);
19 -
20 -function refreshPrimarySessionState(): void {
21 - appAtomRegistry.refresh(primarySessionStateAtom);
22 -}
23 -
24 -export function usePrimarySessionState() {
25 - const result = useAtomValue(primarySessionStateAtom);
26 - let error: string | null = null;
27 - if (result._tag === "Failure") {
28 - const cause = Cause.squash(result.cause);
29 - error = cause instanceof Error ? cause.message : "Could not read environment session.";
30 - }
31 - return {
32 - data: AsyncResult.getOrElse(result, () => null),
33 - error,
34 - isPending: result.waiting,
35 - refresh: refreshPrimarySessionState,
36 - };
37 -}
apps/web/src/state/session.ts
+6 -2
@@ -92,8 +92,12 @@ export function readPreparedConnection(environmentId: EnvironmentId) {
92 }
93
94 /** data survives SWR revalidation; isPending applies only before first resolve. */
95 -export function useEnvironmentSessionState(environmentId: EnvironmentId) {
96 - const result = useAtomValue(environmentSession.sessionStateAtom(environmentId));
95 +export function useEnvironmentSessionState(environmentId: EnvironmentId | null) {
96 + const result = useAtomValue(
97 + environmentId === null
98 + ? EMPTY_SESSION_STATE_ATOM
99 + : environmentSession.sessionStateAtom(environmentId),
100 + );
101 return {
102 data: AsyncResult.getOrElse(result, () => null),
103 hasError: result._tag === "Failure",
docs/user/remote-access.md
+4
@@ -369,6 +369,10 @@ pairing links and revoke client sessions. Revoking an unused link prevents new
369 pairings; revoke a device's session to remove its existing access. Command-line
370 management is available through `t3 auth --help`.
371
372 +When the app connects to more than one environment, choose one at the top of the
373 +page. A desktop app with **Local environment** off can manage a background
374 +service on the same machine this way, including its T3 Connect link.
375 +
376 A session with an open connection stays listed after its access credential
377 expires.
378
packages/client-runtime/package.json
+4
@@ -231,6 +231,10 @@
231 "types": "./src/state/peerLinks.ts",
232 "default": "./src/state/peerLinks.ts"
233 },
234 + "./state/environmentHttpAuth": {
235 + "types": "./src/state/environmentHttpAuth.ts",
236 + "default": "./src/state/environmentHttpAuth.ts"
237 + },
238 "./state/peerPairingCode": {
239 "types": "./src/state/peerPairingCode.ts",
240 "default": "./src/state/peerPairingCode.ts"
packages/client-runtime/src/state/auth.ts
+55 -2
@@ -2,14 +2,22 @@ import type {
2 AuthAccessSnapshot,
3 AuthAccessStreamEvent,
4 AuthAccessStreamSnapshotEvent,
5 + AuthCreatePairingCredentialInput,
6 + AuthRevokeClientSessionInput,
7 + AuthRevokePairingLinkInput,
8 } from "@t3tools/contracts";
9 import { WS_METHODS } from "@t3tools/contracts";
10 +import * as Effect from "effect/Effect";
11 +import type { HttpClient } from "effect/http";
12 import * as Stream from "effect/Stream";
13 import { Atom } from "effect/reactivity";
14
15 import type { EnvironmentRegistry } from "../connection/registry.ts";
16 import { subscribe } from "../rpc/client.ts";
12 -import { createEnvironmentSubscriptionAtomFamily } from "./runtime.ts";
17 +import { executeConnectedEnvironmentHttpRequest } from "./environmentHttpAuth.ts";
18 +import { createEnvironmentCommand, createEnvironmentSubscriptionAtomFamily } from "./runtime.ts";
19 +
20 +const ACCESS_REQUEST_TIMEOUT_MS = 8_000;
21
22 export const EMPTY_AUTH_ACCESS_SNAPSHOT: AuthAccessSnapshot = {
23 pairingLinks: [],
@@ -75,10 +83,55 @@ function projectAuthAccessSnapshot(
83 return [snapshot, [projected]];
84 }
85
86 +/** Access management runs on the chosen environment with this client's own session there. */
87 export function createAuthEnvironmentAtoms<R, E>(
79 - runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
88 + runtime: Atom.AtomRuntime<EnvironmentRegistry | HttpClient.HttpClient | R, E>,
89 ) {
90 return {
91 + createPairingCredential: createEnvironmentCommand(runtime, {
92 + label: "environment-data:server:auth-create-pairing-credential",
93 + execute: (input: AuthCreatePairingCredentialInput) =>
94 + executeConnectedEnvironmentHttpRequest({
95 + group: "auth",
96 + method: "POST",
97 + url: (urls) => urls.pairingCredential(),
98 + timeoutMs: ACCESS_REQUEST_TIMEOUT_MS,
99 + request: ({ client, headers }) => client.pairingCredential({ headers, payload: input }),
100 + }),
101 + }),
102 + revokePairingLink: createEnvironmentCommand(runtime, {
103 + label: "environment-data:server:auth-revoke-pairing-link",
104 + execute: (input: AuthRevokePairingLinkInput) =>
105 + executeConnectedEnvironmentHttpRequest({
106 + group: "auth",
107 + method: "POST",
108 + url: (urls) => urls.revokePairingLink(),
109 + timeoutMs: ACCESS_REQUEST_TIMEOUT_MS,
110 + request: ({ client, headers }) => client.revokePairingLink({ headers, payload: input }),
111 + }),
112 + }),
113 + revokeClient: createEnvironmentCommand(runtime, {
114 + label: "environment-data:server:auth-revoke-client",
115 + execute: (input: AuthRevokeClientSessionInput) =>
116 + executeConnectedEnvironmentHttpRequest({
117 + group: "auth",
118 + method: "POST",
119 + url: (urls) => urls.revokeClient(),
120 + timeoutMs: ACCESS_REQUEST_TIMEOUT_MS,
121 + request: ({ client, headers }) => client.revokeClient({ headers, payload: input }),
122 + }),
123 + }),
124 + revokeOtherClients: createEnvironmentCommand(runtime, {
125 + label: "environment-data:server:auth-revoke-other-clients",
126 + execute: (_input: null) =>
127 + executeConnectedEnvironmentHttpRequest({
128 + group: "auth",
129 + method: "POST",
130 + url: (urls) => urls.revokeOtherClients(),
131 + timeoutMs: ACCESS_REQUEST_TIMEOUT_MS,
132 + request: ({ client, headers }) => client.revokeOtherClients({ headers }),
133 + }).pipe(Effect.map((result) => result.revokedCount)),
134 + }),
135 accessChanges: createEnvironmentSubscriptionAtomFamily(runtime, {
136 label: "environment-data:server:auth-access-changes",
137 subscribe: (_input: null) =>
packages/client-runtime/src/state/environmentHttpAuth.ts
+36 -5
@@ -5,12 +5,14 @@ import {
5 ORCHESTRATION_PROTOCOL_VERSION_TEXT,
6 } from "@t3tools/contracts";
7 import * as Result from "effect/Result";
8 +import * as SubscriptionRef from "effect/SubscriptionRef";
9 import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
10 import { FetchHttpClient, type HttpMethod } from "effect/http";
11
11 -import type { RemoteEnvironmentAuthorization } from "../authorization/service.ts";
12 +import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
13 import type { PreparedConnection, PreparedHttpAuthorization } from "../connection/model.ts";
13 -import type { ManagedRelayDpopSigner } from "../relay/managedRelay.ts";
14 +import * as EnvironmentSupervisor from "../connection/supervisor.ts";
15 +import * as ManagedRelay from "../relay/managedRelay.ts";
16 import {
17 executeEnvironmentHttpRequest,
18 makeEnvironmentHttpApiGroupClient,
@@ -53,7 +55,7 @@ const buildEnvironmentAuthHeaders = Effect.fn("environmentHttpAuth.buildEnvironm
55 authorization: PreparedHttpAuthorization | null,
56 method: HttpMethod.HttpMethod,
57 url: string,
56 - signer: Option.Option<ManagedRelayDpopSigner["Service"]>,
58 + signer: Option.Option<ManagedRelay.ManagedRelayDpopSigner["Service"]>,
59 ): Effect.fn.Return<EnvironmentHttpAuthHeaders, RemoteEnvironmentAuthFetchError> {
60 if (authorization === null) {
61 return {};
@@ -102,6 +104,33 @@ export const executeAuthenticatedEnvironmentHttpRequest = <
104 )
105 : executeEnvironmentRequest(input).pipe(Effect.withSpan(ENVIRONMENT_REQUEST_SPAN));
106
107 +/** Sends the request with this client's own credentials on the supervised environment. */
108 +export const executeConnectedEnvironmentHttpRequest = Effect.fn(
109 + "clientRuntime.state.executeConnectedEnvironmentHttpRequest",
110 +)(function* <Group extends Parameters<typeof makeEnvironmentHttpApiGroupClient>[1], A, E, R>(
111 + input: Omit<
112 + Parameters<typeof executeEnvironmentRequest<Group, A, E, R>>[0],
113 + "prepared" | "signer" | "remoteAuthorization"
114 + >,
115 +) {
116 + const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
117 + const prepared = yield* SubscriptionRef.get(supervisor.prepared);
118 + if (Option.isNone(prepared)) {
119 + return yield* new RemoteEnvironmentAuthFetchError({
120 + message: "The environment is not connected.",
121 + cause: supervisor.target._tag,
122 + });
123 + }
124 + return yield* executeAuthenticatedEnvironmentHttpRequest({
125 + ...input,
126 + prepared: prepared.value,
127 + signer: yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner),
128 + remoteAuthorization: yield* Effect.serviceOption(
129 + RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
130 + ),
131 + });
132 +});
133 +
134 const ENVIRONMENT_REQUEST_SPAN = "clientRuntime.state.executeAuthenticatedEnvironmentHttpRequest";
135
136 const executeEnvironmentRequest = Effect.fnUntraced(function* <
@@ -111,8 +140,10 @@ const executeEnvironmentRequest = Effect.fnUntraced(function* <
140 R,
141 >(input: {
142 readonly prepared: PreparedConnection;
114 - readonly signer: Option.Option<ManagedRelayDpopSigner["Service"]>;
115 - readonly remoteAuthorization?: Option.Option<RemoteEnvironmentAuthorization["Service"]>;
143 + readonly signer: Option.Option<ManagedRelay.ManagedRelayDpopSigner["Service"]>;
144 + readonly remoteAuthorization?: Option.Option<
145 + RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]
146 + >;
147 readonly method: HttpMethod.HttpMethod;
148 /**
149 * The URL to sign, from the group's contract URL builder. It encodes path