Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/server/src/environment/ServerEnvironment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,7 @@ export const make = Effect.gen(function* () {
linkFence: true,
linkThreadStream: true,
linkClientPairing: true,
linkPairingForLink: true,
mcpApprovalCodes: true,
peerLinkPairingCodes: true,
mcpHostedApproval: true,
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/observability/RpcInstrumentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
59 changes: 58 additions & 1 deletion apps/server/src/peer/PeerClientPairing.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) =>
Expand Down Expand Up @@ -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* () {
Expand Down
186 changes: 111 additions & 75 deletions apps/server/src/peer/PeerClientPairing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -72,6 +73,14 @@ export class PeerClientPairing extends Context.Service<
readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
},
) => Effect.Effect<PeerLinkClientPairingResult, PeerLinkError>;
/**
* 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<PeerLinkClientPairingResult, PeerLinkError>;
}
>()("t3/peer/PeerClientPairing") {}

Expand Down Expand Up @@ -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) {
Expand All @@ -114,22 +140,14 @@ 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({
scopes,
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 };
});

Expand Down Expand Up @@ -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<PeerLinkClientPairingResult, { type: "unsupported" }>["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<PeerLinkClientPairingResult, { type: "unsupported" }>["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);
2 changes: 2 additions & 0 deletions apps/server/src/ws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)),
Expand Down
11 changes: 10 additions & 1 deletion apps/web/src/components/settings/EnvironmentsMap.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -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 });
Expand Down
Loading
Loading