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
23 changes: 23 additions & 0 deletions apps/server/src/auth/EnvironmentAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -635,6 +635,10 @@ export class EnvironmentAuth extends Context.Service<
readonly authenticateMcpClient: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<McpClientSession, ServerAuthCredentialError | ServerAuthInternalError>;
/** Ends the MCP client session `token` belongs to. False when it is no live MCP client token. */
readonly revokeMcpClientToken: (
token: string,
) => Effect.Effect<boolean, ServerAuthInternalError>;
readonly issueMcpClientSession: (input: {
readonly label: string;
readonly access: AuthMcpClientAccess;
Expand Down Expand Up @@ -1637,6 +1641,24 @@ export const make = Effect.gen(function* () {
);
};

const revokeMcpClientToken: EnvironmentAuth["Service"]["revokeMcpClientToken"] = Effect.fn(
"EnvironmentAuth.revokeMcpClientToken",
)(function* (token) {
const session = yield* sessions.verify(token).pipe(
Effect.asSome,
Effect.catchIf(SessionStore.isSessionCredentialInvalidError, () => Effect.succeedNone),
Effect.mapError((cause) => new ServerAuthSessionCredentialValidationError({ cause })),
);
if (
Option.isNone(session) ||
session.value.subject !== MCP_CLIENT_SUBJECT ||
session.value.method !== "bearer-access-token"
) {
return false;
}
return yield* revokeSession(session.value.sessionId);
});

const issueMcpClientSession: EnvironmentAuth["Service"]["issueMcpClientSession"] = (input) =>
sessions
.issue({
Expand Down Expand Up @@ -1719,6 +1741,7 @@ export const make = Effect.gen(function* () {
issueWebSocketTicket,
issueStartupPairingUrl,
authenticateMcpClient,
revokeMcpClientToken,
issueMcpClientSession,
consumeMcpApprovalCode,
});
Expand Down
17 changes: 17 additions & 0 deletions apps/server/src/auth/McpOAuth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,7 @@ it.effect("derives discovery metadata from the origin the client reached", () =>
authorization_endpoint: `${ORIGIN}/oauth/mcp/authorize`,
token_endpoint: `${ORIGIN}/oauth/mcp/token`,
registration_endpoint: `${ORIGIN}/oauth/mcp/register`,
revocation_endpoint: `${ORIGIN}/oauth/mcp/revoke`,
code_challenge_methods_supported: ["S256"],
});
}),
Expand Down Expand Up @@ -396,6 +397,22 @@ it.live("signs in with a pairing code and issues a token only /mcp accepts", ()
}),
);
expect(ticket.status).toBe(401);

// Revocation ends only an MCP client's own session; any other token is answered alike and kept.
const owner = yield* auth.exchangeBootstrapCredentialForAccessToken(
(yield* auth.issuePairingCredential()).credential,
undefined,
{ deviceType: "desktop" },
);
const bearer = (token: string) =>
HttpServerRequest.fromWeb(at("/api", { headers: { authorization: `Bearer ${token}` } }));
for (const other of ["not-a-token", owner.access_token]) {
expect((yield* handler(at("/oauth/mcp/revoke", form({ token: other })))).status).toBe(200);
}
yield* auth.authenticateHttpRequest(bearer(owner.access_token));
const revoked = yield* handler(at("/oauth/mcp/revoke", form({ token: token.access_token })));
expect(revoked.status).toBe(200);
yield* auth.authenticateMcpClient(bearer(token.access_token)).pipe(Effect.flip);
}),
),
);
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/auth/McpOAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ export const authorizationServerMetadata = (
authorization_endpoint: `${urls.issuer}/oauth/mcp/authorize`,
token_endpoint: `${urls.issuer}/oauth/mcp/token`,
registration_endpoint: `${urls.issuer}/oauth/mcp/register`,
revocation_endpoint: `${urls.issuer}/oauth/mcp/revoke`,
response_types_supported: ["code"],
grant_types_supported: ["authorization_code"],
code_challenge_methods_supported: ["S256"],
Expand Down
13 changes: 13 additions & 0 deletions apps/server/src/auth/mcpOAuthHttp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Redacted from "effect/Redacted";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import { HttpServerRequest, HttpServerResponse } from "effect/http";
Expand All @@ -20,6 +21,7 @@ import { DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth";
import * as CloudLink from "../cloud/CloudLink.ts";
import { agentApprovalAppUrlConfig } from "../cloud/publicConfig.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as EnvironmentAuth from "./EnvironmentAuth.ts";
import * as McpOAuth from "./McpOAuth.ts";
import { renderErrorPage } from "./mcpOAuthHtml.ts";

Expand Down Expand Up @@ -75,6 +77,7 @@ export const layer = HttpApiBuilder.group(
"mcpOAuth",
Effect.fnUntraced(function* (handlers) {
const oauth = yield* McpOAuth.McpOAuth;
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
const cloudLink = yield* CloudLink.CloudLink;
const serverEnvironment = yield* ServerEnvironment.ServerEnvironmentIdentity;
const hostedAppUrl = yield* agentApprovalAppUrlConfig.pipe(
Expand Down Expand Up @@ -205,6 +208,16 @@ export const layer = HttpApiBuilder.group(
yield* noStore;
return yield* oauth.exchangeCode({ request, urls: yield* requestUrls, token: payload });
}),
)
.handle("revoke", ({ payload }) =>
Effect.gen(function* () {
yield* noStore;
// RFC 7009 §2.2: an unknown or already revoked token gets the same 200 as a revoked one.
if (payload.token === undefined) return;
yield* environmentAuth
.revokeMcpClientToken(Redacted.value(payload.token))
.pipe(Effect.orDie);
}),
);
}),
);
14 changes: 9 additions & 5 deletions apps/server/src/cli/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -293,16 +293,20 @@ const environmentUnlinkCommand = Command.make("unlink", {
),
}).pipe(
Command.withDescription(
"Forget a linked environment here. Revoke it in that environment's Sharing & access to end its session there too.",
"Forget a linked environment here, and end its session there when that environment answers.",
),
Command.withHandler((flags) =>
runWithPeerLinks(flags, (links) =>
Effect.gen(function* () {
const removed = yield* links.unlink(EnvironmentId.make(flags.environmentId));
const { removed, endedThere } = yield* links.unlink(
EnvironmentId.make(flags.environmentId),
);
yield* Console.log(
removed
? `Forgot ${flags.environmentId}. Revoke it in that environment's Sharing & access to end its session there.\n`
: `No linked environment ${flags.environmentId}.\n`,
!removed
? `No linked environment ${flags.environmentId}.\n`
: endedThere
? `Forgot ${flags.environmentId} and ended its session there.\n`
: `Forgot ${flags.environmentId}. It did not answer, so revoke it in that environment's Sharing & access to end its session there.\n`,
);
}),
),
Expand Down
4 changes: 2 additions & 2 deletions apps/server/src/mcp/toolkits/orchestrator/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,15 +218,15 @@ const handlers = {
t3_environment_unlink: McpToolAccess.writesEnvironment(({ environmentId }) =>
Effect.gen(function* () {
const links = yield* PeerLinks.PeerLinks;
const removed = yield* links
const result = yield* links
.unlink(environmentId)
.pipe(
Effect.mapError(
(error) =>
new OrchestratorMcpFailure({ code: "orchestration_error", message: error.message }),
),
);
return { environmentId, removed };
return { environmentId, ...result };
}),
),
t3_thread_interrupt: McpToolAccess.writesThreads(
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/mcp/toolkits/orchestrator/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,7 @@ const EnvironmentLinkTool = Tool.make("t3_environment_link", {

const EnvironmentUnlinkTool = Tool.make("t3_environment_unlink", {
description:
"Forget a linked environment. That machine's Connections list its session until revoked there.",
"Forget a linked environment. Its session on that machine ends too when the machine answers.",
parameters: OrchestratorMcpEnvironmentUnlinkInput,
success: OrchestratorMcpEnvironmentUnlinkResult,
failure: OrchestratorMcpFailure,
Expand Down
16 changes: 15 additions & 1 deletion apps/server/src/peer/PeerLinks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ it.effect("routes peer reads to readers and sees uncommitted link updates", () =
expect((yield* links.list)[0]?.label).toBe("Uncommitted box");
}),
);
expect(yield* links.unlink(box.environmentId)).toBe(true);
expect(yield* links.unlink(box.environmentId)).toEqual({ removed: true, endedThere: false });
expect(yield* links.list).toEqual([]);
}),
);
Expand Down Expand Up @@ -206,6 +206,20 @@ it.effect("links with a pairing code, and the peer holds its agents to the limit
// A refusal keeps the peer's reason.
const notFound = yield* probe(a, undefined, "refuse").pipe(Effect.flip);
expect(notFound).toMatchObject({ code: "thread_not_found", message: "No such thread." });

// Unlinking ends the session on B too, instead of leaving a live credential behind.
expect(yield* a.links.unlink(box.environmentId)).toEqual({ removed: true, endedThere: true });
expect(yield* linkedSessions(b)).toEqual([]);

// An address that now answers as another environment never receives the token.
const other = yield* serveApart(descriptorOf("environment-other", "Other"));
const relink = yield* b.auth.issuePairingCredential({ access: "auto", purpose: "peer-link" });
yield* a.links.link({ url: b.url, pairingCode: relink.credential, access: "auto" });
yield* a.sql`UPDATE peer_environment_links SET urls_json = ${JSON.stringify([other.url])}`;
expect(yield* a.links.unlink(box.environmentId)).toEqual({
removed: true,
endedThere: false,
});
}),
).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
Expand Down
59 changes: 54 additions & 5 deletions apps/server/src/peer/PeerLinks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,10 @@ export class PeerLinks extends Context.Service<
readonly get: (
environmentId: EnvironmentId,
) => Effect.Effect<Option.Option<PeerLink>, PeerLinkError>;
/** Forgets the link here. The peer still lists the session until it is revoked there. */
readonly unlink: (environmentId: EnvironmentId) => Effect.Effect<boolean, PeerLinkError>;
/** Forgets the link here, then asks the peer to end the link's session. */
readonly unlink: (
environmentId: EnvironmentId,
) => Effect.Effect<{ readonly removed: boolean; readonly endedThere: boolean }, PeerLinkError>;
/** An address that answers as the linked peer, with its token, ready to call. */
readonly resolve: (
environmentId: EnvironmentId,
Expand Down Expand Up @@ -665,16 +667,63 @@ const make = Effect.gen(function* () {
),
);

/** Best effort: a peer that is gone or too old to revoke lets its session expire instead. */
const revokeAtPeer = Effect.fn("PeerLinks.revokeAtPeer")(
function* (environmentId: EnvironmentId, urlsJson: string, token: string) {
const urls = yield* decodeUrls(urlsJson);
// A race over no addresses never settles.
if (urls.length === 0) return false;
yield* Effect.raceAll(
urls.map((url) =>
// An address can change hands after linking; only the linked peer may see the token.
answersAs(url, environmentId).pipe(
Effect.flatMap(Effect.fromOption),
Effect.andThen(clientFor(url)),
Effect.flatMap((client) =>
client.mcpOAuth
.revoke({ payload: { token: Redacted.make(token) } })
.pipe(Effect.timeout(probeTimeout(url))),
),
),
),
);
return true;
},
Effect.catchCause((cause) =>
Effect.logDebug("The unlinked peer did not revoke the link's session", { cause }).pipe(
Effect.as(false),
),
),
);

const unlink: PeerLinks["Service"]["unlink"] = Effect.fn("PeerLinks.unlink")(
function* (environmentId) {
const deleted = yield* sql<{ secret_name: string }>`
const deleted = yield* sql<{ secret_name: string; urls_json: string }>`
DELETE FROM peer_environment_links WHERE environment_id = ${environmentId}
RETURNING secret_name
RETURNING secret_name, urls_json
`.pipe(Effect.catch(failStorage));
let endedThere = false;
for (const row of deleted) {
// Unreadable only skips the revocation; the secret is still removed below.
const token = yield* secrets
.get(row.secret_name)
.pipe(
Effect.catch((cause) =>
Effect.logWarning("Could not read the unlinked peer's token", { cause }).pipe(
Effect.as(Option.none()),
),
),
);
yield* secrets.remove(row.secret_name).pipe(Effect.catch(failStorage));
if (Option.isSome(token)) {
endedThere = yield* revokeAtPeer(
environmentId,
row.urls_json,
new TextDecoder().decode(token.value),
);
}
}
return deleted.length > 0;
return { removed: deleted.length > 0, endedThere };
},
);

Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/provider/agentContextBudget.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"claudeSystemAppendBytes": 6245,
"codexAdditionalContextBytes": 7639,
"mcpToolListJsonBytes": 59170
"mcpToolListJsonBytes": 59168
}
3 changes: 1 addition & 2 deletions apps/server/src/ws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2734,8 +2734,7 @@ export const layerWsRpc = (
[WS_METHODS.peerLinksNames]: (_input) =>
peerLinks.names.pipe(Effect.map((links) => ({ links }))),
[WS_METHODS.peerLinksLink]: (input) => peerLinks.link(input),
[WS_METHODS.peerLinksUnlink]: ({ environmentId }) =>
peerLinks.unlink(environmentId).pipe(Effect.map((removed) => ({ removed }))),
[WS_METHODS.peerLinksUnlink]: ({ environmentId }) => peerLinks.unlink(environmentId),
[WS_METHODS.peerLinksSubscribeThread]: (input) => peerThreadRelay.subscribe(input),
[WS_METHODS.peerLinksThreadHistoryPage]: (input) =>
Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe(
Expand Down
15 changes: 13 additions & 2 deletions apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -659,7 +659,7 @@ export function useForgetPeerLink(environmentId: EnvironmentId, link: PeerLinkSu
const forget = async () => {
const confirmed = await (requestConfirmDialog(
gt(
"Forget {label}? Agents here stop working there. Revoke \"T3 Code · …\" in {label}''s Sharing & access to end the session there too.",
"Forget {label}? Agents here stop working there, and their session on {label} ends too if it answers.",
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
{ label: link.label },
),
{ variant: "destructive" },
Expand All @@ -668,7 +668,18 @@ export function useForgetPeerLink(environmentId: EnvironmentId, link: PeerLinkSu
setBusy(true);
const result = await unlink({ environmentId, input: { environmentId: link.environmentId } });
setBusy(false);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
if (result._tag === "Success") {
if (result.value.removed && result.value.endedThere !== true) {
toastManager.add({
type: "warning",
title: gt("{label} did not answer", { label: link.label }),
description: gt(
"Revoke \"T3 Code · …\" in {label}''s Sharing & access to end the session there too.",
{ label: link.label },
),
});
}
} else if (!isAtomCommandInterrupted(result)) {
failureToast(gt("Could not forget the link"), String(squashAtomCommandFailure(result)));
}
};
Expand Down
4 changes: 3 additions & 1 deletion apps/web/src/i18n/translations/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -8928,7 +8928,9 @@
"fb71127e5746a6bc": "Unter „Freigabe & Zugriff“ dort oder mit t3 pair",
"1e3fee7084791773": "Auch {target} zurück mit {source} verknüpfen",
"ea34a190b0bd804c": "Agenten auf {target} können dann auch auf {source} arbeiten.",
"ad5ed0ce61b966eb": "{label} vergessen? Agenten von hier arbeiten dort nicht mehr. Widerrufe „T3 Code · …“ unter „Freigabe & Zugriff“ auf {label}, um die Sitzung auch dort zu beenden.",
"974f8c65e8b5f492": "{label} vergessen? Agenten hier arbeiten dort nicht mehr, und ihre Sitzung auf {label} endet ebenfalls, wenn es antwortet.",
"6cf9e3083b15614f": "{label} hat nicht geantwortet",
"34ccbdf619b83be3": "Widerrufe „T3 Code · …“ unter „Freigabe & Zugriff“ auf {label}, um die Sitzung auch dort zu beenden.",
"81c9796bf61b306a": "Verknüpfung konnte nicht vergessen werden",
"130e51beb6cf5aad": "Umgebung verknüpfen",
"122c3e355699e69d": "Agenten hier können dort dann Threads starten, ihnen Nachrichten senden und auf sie warten. Sie erscheint unter „Autorisierte Clients“ in „Freigabe & Zugriff“ dieser Umgebung und kann dort widerrufen werden.",
Expand Down
4 changes: 3 additions & 1 deletion apps/web/src/i18n/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -8936,7 +8936,9 @@
"fb71127e5746a6bc": "From Sharing & access there, or t3 pair",
"1e3fee7084791773": "Also link {target} back to {source}",
"ea34a190b0bd804c": "Agents on {target} can then work on {source} too.",
"ad5ed0ce61b966eb": "Forget {label}? Agents here stop working there. Revoke \"T3 Code · …\" in {label}''s Sharing & access to end the session there too.",
"974f8c65e8b5f492": "Forget {label}? Agents here stop working there, and their session on {label} ends too if it answers.",
"6cf9e3083b15614f": "{label} did not answer",
"34ccbdf619b83be3": "Revoke \"T3 Code · …\" in {label}''s Sharing & access to end the session there too.",
"81c9796bf61b306a": "Could not forget the link",
"130e51beb6cf5aad": "Link an environment",
"122c3e355699e69d": "Agents here can then launch, message and wait on threads there. It appears under Authorized clients in that environment's Sharing & access, where it can be revoked.",
Expand Down
4 changes: 3 additions & 1 deletion apps/web/src/i18n/translations/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -8926,7 +8926,9 @@
"fb71127e5746a6bc": "Desde Compartir y acceso allí, o t3 pair",
"1e3fee7084791773": "Vincular también {target} de vuelta a {source}",
"ea34a190b0bd804c": "Los agentes de {target} podrán trabajar también en {source}.",
"ad5ed0ce61b966eb": "¿Olvidar {label}? Los agentes de aquí dejarán de trabajar allí. Revoca \"T3 Code · …\" en Compartir y acceso de {label} para cerrar también la sesión allí.",
"974f8c65e8b5f492": "¿Olvidar {label}? Los agentes de aquí dejan de trabajar allí, y su sesión en {label} también termina si responde.",
"6cf9e3083b15614f": "{label} no respondió",
"34ccbdf619b83be3": "Revoca \"T3 Code · …\" en Compartir y acceso de {label} para cerrar también la sesión allí.",
"81c9796bf61b306a": "No se pudo olvidar el vínculo",
"130e51beb6cf5aad": "Vincular un entorno",
"122c3e355699e69d": "Así los agentes de aquí podrán iniciar hilos allí, enviarles mensajes y esperarlos. Aparece en Clientes autorizados, en Compartir y acceso de ese entorno, donde se puede revocar.",
Expand Down
4 changes: 3 additions & 1 deletion apps/web/src/i18n/translations/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -8928,7 +8928,9 @@
"fb71127e5746a6bc": "Depuis Partage et accès sur cette machine, ou t3 pair",
"1e3fee7084791773": "Associer aussi {target} en retour à {source}",
"ea34a190b0bd804c": "Les agents de {target} pourront alors aussi travailler sur {source}.",
"ad5ed0ce61b966eb": "Oublier {label} ? Les agents d’ici cessent d’y travailler. Révoquez « T3 Code · … » dans Partage et accès sur {label} pour y fermer aussi la session.",
"974f8c65e8b5f492": "Oublier {label} ? Les agents d’ici cessent d’y travailler, et leur session sur {label} prend fin aussi s’il répond.",
"6cf9e3083b15614f": "{label} n’a pas répondu",
"34ccbdf619b83be3": "Révoquez « T3 Code · … » dans Partage et accès sur {label} pour y fermer aussi la session.",
"81c9796bf61b306a": "Impossible d’oublier l’association",
"130e51beb6cf5aad": "Associer un environnement",
"122c3e355699e69d": "Les agents d’ici pourront alors lancer des fils là-bas, leur envoyer des messages et les attendre. L’association apparaît sous Clients autorisés dans Partage et accès de cet environnement, où elle peut être révoquée.",
Expand Down
Loading
Loading