From cec8b349e5e21e082cdf6e03c470bfaa55565a15 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Fri, 20 Nov 2026 13:28:54 -0800 Subject: [PATCH 1/3] feat: link a machine through another one that already links to it A machine this client is not connected to could only be linked with a pairing code fetched from it by hand. When another environment holds a full-access link to it, that environment now gets the code: a person with access management on it asks, the linked machine mints an ordinary link pairing code, and the new link is made with the access they pick. Co-Authored-By: Claude Fable 5.2 --- .../src/environment/ServerEnvironment.ts | 1 + .../src/observability/RpcInstrumentation.ts | 1 + .../server/src/peer/PeerClientPairing.test.ts | 59 +++++- apps/server/src/peer/PeerClientPairing.ts | 186 +++++++++++------- apps/server/src/ws.ts | 2 + .../components/settings/EnvironmentsMap.tsx | 11 +- .../settings/LinkedEnvironmentsSettings.tsx | 119 ++++++++--- .../settings/environmentsMap.logic.test.ts | 26 +++ .../settings/environmentsMap.logic.ts | 47 ++++- apps/web/src/i18n/translations/de.json | 19 +- apps/web/src/i18n/translations/en.json | 19 +- apps/web/src/i18n/translations/es.json | 19 +- apps/web/src/i18n/translations/fr.json | 19 +- apps/web/src/i18n/translations/ja.json | 19 +- apps/web/src/i18n/translations/ko.json | 19 +- apps/web/src/i18n/translations/pt-BR.json | 19 +- apps/web/src/i18n/translations/ru.json | 19 +- apps/web/src/i18n/translations/sv.json | 19 +- apps/web/src/i18n/translations/zh.json | 19 +- docs/user/remote-access.md | 7 + .../client-runtime/src/state/peerLinks.ts | 5 + .../contracts/src/clientRpcPermissions.ts | 1 + packages/contracts/src/environment.ts | 2 + packages/contracts/src/peerLink.ts | 16 ++ packages/contracts/src/rpc.ts | 9 + 25 files changed, 499 insertions(+), 183 deletions(-) diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index 2208e70b983e3..b29f9c874f123 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -299,6 +299,7 @@ export const make = Effect.gen(function* () { linkFence: true, linkThreadStream: true, linkClientPairing: true, + linkPairingForLink: true, mcpApprovalCodes: true, peerLinkPairingCodes: true, mcpHostedApproval: true, diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index 96351b39b6315..8ee73918171c6 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -74,6 +74,7 @@ const RPC_AGGREGATES = { [WS_METHODS.peerLinksThreadHistoryPage]: "peerLinks", [WS_METHODS.peerLinksThreadItem]: "peerLinks", [WS_METHODS.peerLinksPairClient]: "peerLinks", + [WS_METHODS.peerLinksPairLink]: "peerLinks", [WS_METHODS.serverGetSettings]: "server", [WS_METHODS.serverUpdateSettings]: "server", [WS_METHODS.serverSearchAcpRegistry]: "server", diff --git a/apps/server/src/peer/PeerClientPairing.test.ts b/apps/server/src/peer/PeerClientPairing.test.ts index a9bd0f63454d7..17a5df1cb75ff 100644 --- a/apps/server/src/peer/PeerClientPairing.test.ts +++ b/apps/server/src/peer/PeerClientPairing.test.ts @@ -43,7 +43,10 @@ import { } from "./PeerLinks.testkit.ts"; const laptop = descriptorOf("environment-laptop", "Laptop"); -const box = descriptorOf("environment-box", "Box", { linkClientPairing: true }); +const box = descriptorOf("environment-box", "Box", { + linkClientPairing: true, + linkPairingForLink: true, +}); const NoTools = Toolkit.make(); const serveBox = (descriptor: ExecutionEnvironmentDescriptor = box) => @@ -254,6 +257,60 @@ it.effect("pairs no client while Linked environments is off on either side", () ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); +it.effect("a full-access link gets a pairing code that links another environment to the box", () => + Effect.scoped( + Effect.gen(function* () { + const b = yield* serveBox(); + const a = yield* makeLaptop; + yield* linkTo(a.links, b, "full-access"); + const phone = yield* a.client([AuthAccessWriteScope]); + + const result = yield* a.pairing.requestForLink( + { environmentId: box.environmentId, access: "approval-required" }, + phone, + ); + if (result.type !== "credential") return yield* Effect.die(result); + expect(result).toMatchObject({ environmentId: box.environmentId, urls: [b.url] }); + + // A third environment links with it, at the access the code was minted for. + const desk = yield* Layer.build( + layerLinkingEnvironment(descriptorOf("environment-desk", "Desk")), + ); + const linked = yield* Context.get(desk, PeerLinks.PeerLinks).link({ + url: b.url, + pairingCode: result.credential, + access: "approval-required", + }); + expect(linked).toMatchObject({ + environmentId: box.environmentId, + access: "approval-required", + }); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + +it.effect("a linked environment from before link pairing is never asked for one", () => + Effect.scoped( + Effect.gen(function* () { + const b = yield* serveBox( + descriptorOf("environment-box", "Box", { linkClientPairing: true }), + ); + const a = yield* makeLaptop; + yield* linkTo(a.links, b, "full-access"); + const phone = yield* a.client([AuthAccessWriteScope]); + + // It would read the request as a client's and hand back a client pairing. + expect( + yield* a.pairing.requestForLink( + { environmentId: box.environmentId, access: "auto" }, + phone, + ), + ).toMatchObject({ type: "unsupported", reason: "version" }); + expect(yield* Ref.get(b.bearers)).toEqual([]); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + it.effect("a linked environment from before client pairing is never asked", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/peer/PeerClientPairing.ts b/apps/server/src/peer/PeerClientPairing.ts index 045b369cfe2f4..da10e3d78d157 100644 --- a/apps/server/src/peer/PeerClientPairing.ts +++ b/apps/server/src/peer/PeerClientPairing.ts @@ -8,6 +8,7 @@ import { type PeerLinkClientPairingRequest, type PeerLinkClientPairingResult, PeerLinkError, + type PeerLinkLinkPairingInput, } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; @@ -72,6 +73,14 @@ export class PeerClientPairing extends Context.Service< readonly scopes: ReadonlyArray; }, ) => Effect.Effect; + /** + * Gets a pairing code from an environment this one links to, for the client to link another + * environment there with. The client made the request, so it is named beside the code. + */ + readonly requestForLink: ( + input: PeerLinkLinkPairingInput, + client: { readonly sessionId: AuthSessionId }, + ) => Effect.Effect; } >()("t3/peer/PeerClientPairing") {} @@ -106,6 +115,23 @@ const makeIssuer = Effect.gen(function* () { message: "Only a full-access link may pair a client here.", }); } + const via = caller.label.startsWith(PeerLinks.LINK_CLIENT_NAME_PREFIX) + ? caller.label.slice(PeerLinks.LINK_CLIENT_NAME_PREFIX.length) + : caller.label; + const refusedByPolicy = (error: { readonly message: string }) => + Effect.fail(new PeerClientPairingRefused({ reason: "policy", message: error.message })); + if (request.link !== undefined) { + // A link pairing code, as this machine's own Sharing & access would mint: the full-access + // caller could mint it by running the CLI here, so no access level is more than it holds. + const issued = yield* auth + .issuePairingCredential({ + access: request.link.access, + purpose: "peer-link", + label: `Link · via ${via}`, + }) + .pipe(Effect.catchTags({ ManagedPolicyRefusedError: refusedByPolicy })); + return { credential: issued.credential, expiresAt: issued.expiresAt }; + } // Never more than the client holds where it asked, nor more than a pairing code grants. const scopes = AuthStandardClientScopes.filter((scope) => request.scopes.includes(scope)); if (scopes.length === 0) { @@ -114,9 +140,6 @@ const makeIssuer = Effect.gen(function* () { message: "The client holds no access a pairing could carry.", }); } - const via = caller.label.startsWith(PeerLinks.LINK_CLIENT_NAME_PREFIX) - ? caller.label.slice(PeerLinks.LINK_CLIENT_NAME_PREFIX.length) - : caller.label; const clientLabel = Array.from(request.clientLabel).slice(0, CLIENT_LABEL_MAX_LENGTH).join(""); const issued = yield* auth .createPairingLink({ @@ -124,12 +147,7 @@ const makeIssuer = Effect.gen(function* () { ttl: CLIENT_PAIRING_TTL, label: `${clientLabel} · via ${via}`, }) - .pipe( - Effect.catchTags({ - ManagedPolicyRefusedError: (error) => - Effect.fail(new PeerClientPairingRefused({ reason: "policy", message: error.message })), - }), - ); + .pipe(Effect.catchTags({ ManagedPolicyRefusedError: refusedByPolicy })); return { credential: issued.credential, expiresAt: issued.expiresAt }; }); @@ -157,75 +175,93 @@ const make = Effect.gen(function* () { Effect.orElseSucceed(() => "T3 Code client"), ); - const request: PeerClientPairing["Service"]["request"] = Effect.fn("PeerClientPairing.request")( - function* (input, client) { - if (!(yield* links.enabled)) { - return yield* new PeerLinkError({ - reason: "disabled", - message: PeerLinks.LINKED_ENVIRONMENTS_OFF, - }); - } - const stored = yield* links.get(input.environmentId); - if (Option.isNone(stored)) { - return yield* new PeerLinkError({ - reason: "unknown_link", - message: "This environment is no longer linked to that one.", - }); - } - const { environmentId, label, urls, access, expiresAt } = stored.value; - if (DateTime.isLessThanOrEqualTo(expiresAt, yield* DateTime.now)) { - return yield* new PeerLinkError({ - reason: "expired", - message: `The link to ${label} expired. Link it again with a new pairing code from ${label}.`, - }); - } - const unsupported = ( - reason: Extract["reason"], - name = label, - ): PeerLinkClientPairingResult => ({ - type: "unsupported", - environmentId, - label: name, - urls, - reason, + /** Asks the linked environment for a pairing; `payload` says for whom. */ + const ask = Effect.fn("PeerClientPairing.ask")(function* ( + input: { readonly environmentId: PeerLinkClientPairingInput["environmentId"] }, + sessionId: AuthSessionId, + payload: (clientLabel: string) => PeerLinkClientPairingRequest, + ) { + if (!(yield* links.enabled)) { + return yield* new PeerLinkError({ + reason: "disabled", + message: PeerLinks.LINKED_ENVIRONMENTS_OFF, + }); + } + const stored = yield* links.get(input.environmentId); + if (Option.isNone(stored)) { + return yield* new PeerLinkError({ + reason: "unknown_link", + message: "This environment is no longer linked to that one.", }); - // The linked environment refuses this too; asking would only spend a round trip. - if (access !== "full-access") return unsupported("link_access"); - const resolved = yield* links.resolve(input.environmentId).pipe(Effect.option); - if (Option.isNone(resolved)) return unsupported("unreachable"); - const peer = resolved.value; - if (peer.capabilities.linkClientPairing !== true) { - return unsupported("version", peer.link.label); - } - const api = yield* HttpApiClient.make(ClientPairingApi, { baseUrl: peer.url }).pipe( - Effect.provideService(HttpClient.HttpClient, httpClient), + } + const { environmentId, label, urls, access, expiresAt } = stored.value; + if (DateTime.isLessThanOrEqualTo(expiresAt, yield* DateTime.now)) { + return yield* new PeerLinkError({ + reason: "expired", + message: `The link to ${label} expired. Link it again with a new pairing code from ${label}.`, + }); + } + const unsupported = ( + reason: Extract["reason"], + name = label, + ): PeerLinkClientPairingResult => ({ + type: "unsupported", + environmentId, + label: name, + urls, + reason, + }); + // The linked environment refuses this too; asking would only spend a round trip. + if (access !== "full-access") return unsupported("link_access"); + const resolved = yield* links.resolve(input.environmentId).pipe(Effect.option); + if (Option.isNone(resolved)) return unsupported("unreachable"); + const peer = resolved.value; + const request = payload(yield* clientLabelOf(sessionId)); + if ( + peer.capabilities.linkClientPairing !== true || + // One from before this would read the request as a client's and pair the client instead. + (request.link !== undefined && peer.capabilities.linkPairingForLink !== true) + ) { + return unsupported("version", peer.link.label); + } + const api = yield* HttpApiClient.make(ClientPairingApi, { baseUrl: peer.url }).pipe( + Effect.provideService(HttpClient.HttpClient, httpClient), + ); + return yield* api.peerLink + .clientPairing({ + headers: { authorization: `Bearer ${peer.token}` }, + payload: request, + }) + .pipe( + Effect.timeout(PeerLinks.probeTimeout(peer.url)), + Effect.map((issued): PeerLinkClientPairingResult => ({ + type: "credential", + environmentId, + label: peer.link.label, + urls, + credential: issued.credential, + expiresAt: issued.expiresAt, + })), + // No cause is logged or returned: a response this version cannot read may hold the credential. + Effect.catchTags({ + HttpClientError: () => Effect.succeed(unsupported("unreachable", peer.link.label)), + TimeoutError: () => Effect.succeed(unsupported("unreachable", peer.link.label)), + }), + Effect.orElseSucceed(() => unsupported("refused", peer.link.label)), ); - return yield* api.peerLink - .clientPairing({ - headers: { authorization: `Bearer ${peer.token}` }, - payload: { scopes: client.scopes, clientLabel: yield* clientLabelOf(client.sessionId) }, - }) - .pipe( - Effect.timeout(PeerLinks.probeTimeout(peer.url)), - Effect.map((issued): PeerLinkClientPairingResult => ({ - type: "credential", - environmentId, - label: peer.link.label, - urls, - credential: issued.credential, - expiresAt: issued.expiresAt, - })), - // No cause is logged or returned: a response this version cannot read may hold the credential. - Effect.catchTags({ - HttpClientError: () => Effect.succeed(unsupported("unreachable", peer.link.label)), - TimeoutError: () => Effect.succeed(unsupported("unreachable", peer.link.label)), - }), - Effect.orElseSucceed(() => unsupported("refused", peer.link.label)), - ); - }, - ); + }); + + const request: PeerClientPairing["Service"]["request"] = (input, client) => + ask(input, client.sessionId, (clientLabel) => ({ scopes: client.scopes, clientLabel })); + + const requestForLink: PeerClientPairing["Service"]["requestForLink"] = (input, client) => + ask(input, client.sessionId, (clientLabel) => ({ + scopes: [], + clientLabel, + link: { access: input.access }, + })); - return PeerClientPairing.of({ request }); + return PeerClientPairing.of({ request, requestForLink }); }); export const layer = Layer.effect(PeerClientPairing, make); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 3747e013a0193..0eaf6e8b8b926 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -2724,6 +2724,8 @@ export const layerWsRpc = ( ), [WS_METHODS.peerLinksPairClient]: (input) => peerClientPairing.request(input, currentSession), + [WS_METHODS.peerLinksPairLink]: (input) => + peerClientPairing.requestForLink(input, currentSession), [WS_METHODS.peerLinksAnswerRequest]: (input) => Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe( Effect.andThen(peerLinkRequests.answer(input)), diff --git a/apps/web/src/components/settings/EnvironmentsMap.tsx b/apps/web/src/components/settings/EnvironmentsMap.tsx index 172e2ef917093..befa3c5e19b68 100644 --- a/apps/web/src/components/settings/EnvironmentsMap.tsx +++ b/apps/web/src/components/settings/EnvironmentsMap.tsx @@ -461,7 +461,11 @@ export function EnvironmentsMap( ? { choice: null } : offer.target.kind === "machine" ? { choice: offer.target.environmentId } - : { choice: ANOTHER_ADDRESS, address: offer.target.address ?? "" }, + : { + choice: ANOTHER_ADDRESS, + address: offer.target.address ?? "", + ...(offer.target.through ? { through: offer.target.through } : {}), + }, })); }; /** One link from `sourceId` to `targetId`, whatever is selected. */ @@ -1299,6 +1303,11 @@ function actionText(action: FleetLinkAction | null, target: string, gt: GT): str ? gt("Renew link to {target}", { target }) : gt("Link to {target}", { target }); } + if (offer.path === "through-link") { + return offer.renews + ? gt("Renew link to {target}", { target }) + : gt("Link to {target}", { target }); + } return offer.renews ? gt("Renew link to {target} with a pairing code", { target }) : gt("Link to {target} with a pairing code", { target }); diff --git a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx index 1baefa99a469a..b6a0a02d89c0c 100644 --- a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx +++ b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx @@ -219,6 +219,15 @@ export interface LinkEnvironmentPrefill { /** The machine to link to, by environment id, or `ANOTHER_ADDRESS` with `address`. */ readonly choice: string | null; readonly address?: string; + /** + * With `address`: the machine there, and one of this app's that links to it at full access and + * so can get the pairing code from it. + */ + readonly through?: { + readonly viaEnvironmentId: EnvironmentId; + readonly environmentId: EnvironmentId; + readonly label: string; + }; } /** @@ -262,8 +271,26 @@ export function LinkEnvironmentDialog({ reportFailure: false, reportDefect: false, }); + const pairThrough = useAtomCommand(peerLinkEnvironment.pairLink, { + label: "pair link through a linked environment", + // The answer is a credential; keep it out of the console. + reportFailure: false, + reportDefect: false, + }); + const via = useEnvironment(prefill?.through?.viaEnvironmentId ?? null); + // Set once the linked machine would not give a code, so the dialog asks for one instead. + const [throughFailed, setThroughFailed] = useState(false); const [alsoLinkBack, setAlsoLinkBack] = useState(false); const selected = choice ?? (machines.length === 0 ? ANOTHER_ADDRESS : null); + // Only for the machine the dialog opened for: another choice or address is another machine. + const through = + prefill?.through !== undefined && + via !== null && + !throughFailed && + selected === ANOTHER_ADDRESS && + address === (prefill.address ?? "") + ? prefill.through + : null; const machine = machines.find((candidate) => candidate.environmentId === selected) ?? null; const targetId = machine?.environmentId ?? null; const connected = usePreparedConnection(targetId); @@ -282,9 +309,10 @@ export function LinkEnvironmentDialog({ const linkBack = useLinkBackOffers(environmentId, targetId === null ? [] : [targetId], open); const backOffer = linkBack.offerFor(targetId); const ready = - selected !== null && - (!needsAddress || address.trim().length > 0) && - (canMint || pairingCode.trim().length > 0); + through !== null || + (selected !== null && + (!needsAddress || address.trim().length > 0) && + (canMint || pairingCode.trim().length > 0)); const handleOpenChange = (next: boolean) => { setOpen(next); if (!next) { @@ -293,9 +321,39 @@ export function LinkEnvironmentDialog({ setPairingCode(""); setAccess("approval-required"); setMintFailed(new Set()); + setThroughFailed(false); setAlsoLinkBack(false); } }; + // Settles to what to link with, or null after reporting why the linked machine gave no code. + const resolveThrough = async (target: NonNullable) => { + const asked = await pairThrough({ + environmentId: target.viaEnvironmentId, + input: { environmentId: target.environmentId, access }, + }); + if (asked._tag === "Success" && asked.value.type === "credential") { + const [url, ...alternateUrls] = asked.value.urls; + if (url !== undefined) { + return { + url, + ...(alternateUrls.length > 0 ? { alternateUrls } : {}), + expectedEnvironmentId: asked.value.environmentId, + expectedLabel: asked.value.label, + pairingCode: asked.value.credential, + }; + } + } + if (asked._tag === "Failure" && isAtomCommandInterrupted(asked)) return null; + setThroughFailed(true); + failureToast( + gt("{via} could not get a pairing code from {target}", { + via: via?.label ?? "", + target: target.label, + }), + gt("Enter its address and a pairing code from it instead."), + ); + return null; + }; // Settles to the code to link with, or null after reporting why there is none. const resolvePairingCode = async () => { if (!canMint || targetId === null) return pairingCode.trim(); @@ -314,23 +372,28 @@ export function LinkEnvironmentDialog({ if (inFlight.current || !ready || url === undefined) return; inFlight.current = true; setBusy(true); - const code = await resolvePairingCode(); + const throughInput = through === null ? null : await resolveThrough(through); + const code = through === null ? await resolvePairingCode() : null; const result = - code === null - ? null - : await link({ - environmentId, - input: { - url, - ...(alternateUrls.length > 0 ? { alternateUrls } : {}), - // A typed address links alone: only this app's own addresses name a machine. - ...(machine === null || needsAddress - ? {} - : { expectedEnvironmentId: machine.environmentId, expectedLabel: machine.label }), - pairingCode: code, - access, - }, - }); + through !== null + ? throughInput === null + ? null + : await link({ environmentId, input: { ...throughInput, access } }) + : code === null + ? null + : await link({ + environmentId, + input: { + url, + ...(alternateUrls.length > 0 ? { alternateUrls } : {}), + // A typed address links alone: only this app's own addresses name a machine. + ...(machine === null || needsAddress + ? {} + : { expectedEnvironmentId: machine.environmentId, expectedLabel: machine.label }), + pairingCode: code, + access, + }, + }); // The link back is its own link, made on the other machine: it never undoes this one. const back = result?._tag === "Success" && @@ -389,6 +452,8 @@ export function LinkEnvironmentDialog({ {source === null ? ( Link an environment + ) : through !== null ? ( + gt("Link {source} to {target}", { source: source.label, target: through.label }) ) : machine === null ? ( gt("Link {label} to another machine", { label: source.label }) ) : ( @@ -429,7 +494,15 @@ export function LinkEnvironmentDialog({ Already linked. Linking again renews it with the access you pick.

) : null} - {needsAddress ? ( + {through !== null ? ( +

+ {gt( + "{via} links to {target} at full access, so it gets the pairing code. No code to paste.", + { via: via?.label ?? "", target: through.label }, + )} +

+ ) : null} + {needsAddress && through === null ? ( ) : null} - {needsAddress && address.trim() ? : null} - {selected === null || canMint ? null : ( + {needsAddress && through === null && address.trim() ? ( + + ) : null} + {selected === null || canMint || through !== null ? null : (