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..954c0e1c4ee3c 100644 --- a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx +++ b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx @@ -26,7 +26,12 @@ import { type ReactNode, useId, useRef, useState } from "react"; import { requestConfirmDialog } from "~/confirmDialog"; import { useEnvironment } from "~/state/environments"; import { mintPairingCodeOn } from "~/state/peerPairingCode"; -import { peerLinkEnvironment, useLinkableMachines, useLinkBackOffers } from "~/state/peerLinks"; +import { + peerLinkEnvironment, + useLinkableMachines, + useLinkBackOffers, + useLinkThroughRoutes, +} from "~/state/peerLinks"; import { useEnvironments } from "~/state/environments"; import { useEnvironmentQuery } from "~/state/query"; import { useEnvironmentScope, usePreparedConnection } from "~/state/session"; @@ -219,6 +224,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; + }; } /** @@ -243,7 +257,24 @@ export function LinkEnvironmentDialog({ const setOpen = onOpenChange; // Named in the title: from the map, nothing else on screen says which machine is linking. const source = useEnvironment(environmentId); - const machines = useLinkableMachines(environmentId, open); + const saved = useLinkableMachines(environmentId, open); + const routes = useLinkThroughRoutes(environmentId, open); + // Machines this app has no entry for are still pickable when one of its environments links + // to them at full access. + const machines = [ + ...saved, + ...[...routes.values()] + .filter((route) => saved.every((machine) => machine.environmentId !== route.environmentId)) + .map((route) => ({ + environmentId: route.environmentId, + label: route.label, + machine: "server" as const, + connected: false, + connectOnly: false, + linked: false, + urls: route.urls, + })), + ]; // Null until the user picks; with no other machines known, only an address is left. const [choice, setChoice] = useState(prefill?.choice ?? null); const [address, setAddress] = useState(prefill?.address ?? ""); @@ -262,8 +293,23 @@ 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, + }); + // Machines that would not give a code through a link, so the dialog asks for one instead. + const [throughFailed, setThroughFailed] = useState>(new Set()); 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 prefilledThrough = + prefill?.through !== undefined && + 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); @@ -279,12 +325,21 @@ export function LinkEnvironmentDialog({ Option.isSome(connected) && mayMint && !mintFailed.has(targetId); + // Minting with this client's own session there comes first: it needs no third machine. + const throughCandidate = + prefilledThrough ?? (targetId === null || canMint ? null : (routes.get(targetId) ?? null)); + const via = useEnvironment(throughCandidate?.viaEnvironmentId ?? null); + const through = + throughCandidate !== null && via !== null && !throughFailed.has(throughCandidate.environmentId) + ? throughCandidate + : null; 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 +348,39 @@ export function LinkEnvironmentDialog({ setPairingCode(""); setAccess("approval-required"); setMintFailed(new Set()); + setThroughFailed(new Set()); 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((failed) => new Set(failed).add(target.environmentId)); + 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 +399,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 +479,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 }) ) : ( @@ -412,7 +504,7 @@ export function LinkEnvironmentDialog({ void submit(); }} > - {machines.length > 0 ? ( + {machines.length > 0 && (through === null || through !== prefilledThrough) ? ( 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 : (