diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 284d8e3a18f11..ea4d84ea0a3b3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -71,6 +71,9 @@ jobs: - name: Verify preload bundle output run: node apps/desktop/scripts/verify-preload-bundle.mjs + - name: Verify Connect pairing endpoint in the built server + run: node scripts/connect-pairing-smoke.ts apps/server/dist + # Everything except `t3` (apps/server). `--parallel` drops the package # dependency ordering that `vp run` applies by default: these `test` tasks # declare no `dependsOn` and resolve workspace deps from source, so ordering diff --git a/apps/server/src/auth/EnvironmentAuth.ts b/apps/server/src/auth/EnvironmentAuth.ts index d10f2f4cf4ab0..a7dafb381bd31 100644 --- a/apps/server/src/auth/EnvironmentAuth.ts +++ b/apps/server/src/auth/EnvironmentAuth.ts @@ -2,6 +2,7 @@ import { AuthAccessTokenType, AuthAccessWriteScope, AuthAdministrativeScopes, + mcpClientScopes, AuthStandardClientScopes, type AuthAccessTokenResult, type AuthBrowserSessionResult, @@ -982,10 +983,16 @@ export const make = Effect.gen(function* () { const issuePairingCredential: EnvironmentAuth["Service"]["issuePairingCredential"] = (input) => issuePairingCredentialForSubject({ - scopes: input?.scopes ?? AuthStandardClientScopes, + scopes: + input?.scopes ?? (input?.access ? mcpClientScopes(input.access) : AuthStandardClientScopes), subject: "one-time-token", ...(input?.label ? { label: input.label } : {}), - }).pipe(Effect.withSpan("EnvironmentAuth.issuePairingCredential")); + }).pipe( + Effect.map((issued) => + input?.access === undefined ? issued : { ...issued, access: input.access }, + ), + Effect.withSpan("EnvironmentAuth.issuePairingCredential"), + ); const issueStartupPairingCredential: EnvironmentAuth["Service"]["issueStartupPairingCredential"] = () => { diff --git a/apps/server/src/auth/http.ts b/apps/server/src/auth/http.ts index 0f927580367dd..b96b743829dde 100644 --- a/apps/server/src/auth/http.ts +++ b/apps/server/src/auth/http.ts @@ -2,6 +2,7 @@ import { AuthAccessReadScope, AuthAccessWriteScope, AuthStandardClientScopes, + mcpClientScopes, AuthOrchestrationOperateScope, AuthOrchestrationReadScope, AuthRelayReadScope, @@ -403,7 +404,11 @@ export const authHttpApiLayer = HttpApiBuilder.group( function* (args) { yield* annotateEnvironmentRequest(args.endpoint.name); const session = yield* requireEnvironmentScope(AuthAccessWriteScope); - const delegatedScopes = args.payload.scopes ?? AuthStandardClientScopes; + const delegatedScopes = + args.payload.scopes ?? + (args.payload.access + ? mcpClientScopes(args.payload.access) + : AuthStandardClientScopes); if ( delegatedScopes.length === 0 || new Set(delegatedScopes).size !== delegatedScopes.length @@ -415,7 +420,10 @@ export const authHttpApiLayer = HttpApiBuilder.group( return yield* failEnvironmentScopeRequired(delegatedScope); } } - return yield* serverAuth.issuePairingCredential(args.payload); + return yield* serverAuth.issuePairingCredential({ + ...args.payload, + scopes: delegatedScopes, + }); }, Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) => failEnvironmentInternal("pairing_credential_issuance_failed", error), diff --git a/apps/server/src/auth/mcpPairingHttp.test.ts b/apps/server/src/auth/mcpPairingHttp.test.ts new file mode 100644 index 0000000000000..8d23c01da02de --- /dev/null +++ b/apps/server/src/auth/mcpPairingHttp.test.ts @@ -0,0 +1,203 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { + CONNECT_PAIRING_DISCOVERY_PATH, + EnvironmentHttpApi, + MCP_PAIRING_AUTHORIZE_PATH, + MCP_PAIRING_REGISTER_PATH, + MCP_PAIRING_SCOPES, + MCP_PAIRING_TOKEN_PATH, + MCP_PEER_LINK_SOFTWARE_ID, +} from "@t3tools/contracts"; +import { expect, it } from "@effect/vitest"; +import * as Context from "effect/Context"; +import * as Crypto from "effect/Crypto"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Redacted from "effect/Redacted"; +import * as Schema from "effect/Schema"; +import * as Etag from "effect/unstable/http/Etag"; +import * as HttpPlatform from "effect/unstable/http/HttpPlatform"; +import * as HttpApi from "effect/unstable/httpapi/HttpApi"; +import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder"; +import * as HttpRouter from "effect/unstable/http/HttpRouter"; + +import * as ServerConfig from "../config.ts"; +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts"; +import * as EnvironmentAuth from "./EnvironmentAuth.ts"; +import { authHttpApiLayer, environmentAuthenticatedAuthLayer } from "./http.ts"; +import { mcpPairingHttpApiLayer } from "./mcpPairingHttp.ts"; +import * as ServerSecretStore from "./ServerSecretStore.ts"; + +const DEV_TOKEN = "reusable-dev-auth-token-that-is-long-enough"; + +class PairingTestApi extends HttpApi.make("environment") + .add(EnvironmentHttpApi.groups.auth) + .add(EnvironmentHttpApi.groups.mcpOAuth) {} + +const configLayer = Layer.effect( + ServerConfig.ServerConfig, + Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + return { + ...config, + mode: "web", + devUrl: new URL("http://127.0.0.1:5173"), + devAuthToken: Redacted.make(DEV_TOKEN), + } satisfies ServerConfig.ServerConfig["Service"]; + }), +).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-pairing-test-" }))); + +const environmentAuthLayer = EnvironmentAuth.layer.pipe( + Layer.provide(SqlitePersistenceMemory), + Layer.provide(ServerSecretStore.layer), + Layer.provide(ServerEnvironment.identityLayer), + Layer.provide(configLayer), +); + +const routesLayer = HttpApiBuilder.layer(PairingTestApi).pipe( + Layer.provide(authHttpApiLayer), + Layer.provide(mcpPairingHttpApiLayer), + Layer.provide(environmentAuthenticatedAuthLayer), + Layer.provideMerge(environmentAuthLayer), + Layer.provide(configLayer), + Layer.provideMerge( + HttpPlatform.layer.pipe( + Layer.provideMerge(NodeServices.layer), + Layer.provideMerge(Etag.layerWeak), + ), + ), + Layer.provide(NodeServices.layer), +); + +const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); + +it.effect("serves Connect pairing discovery and exchanges a pairing code", () => + Effect.gen(function* () { + const crypto = yield* Crypto.Crypto; + const unusedSecretStore = ServerSecretStore.ServerSecretStore.of({ + get: () => Effect.succeed(Option.none()), + set: () => Effect.void, + create: () => Effect.void, + getOrCreateRandom: () => Effect.die("Not used by these routes."), + remove: () => Effect.void, + }); + const requestContext = Context.make(Crypto.Crypto, crypto).pipe( + Context.add(ServerSecretStore.ServerSecretStore, unusedSecretStore), + ); + + return yield* Effect.acquireUseRelease( + Effect.sync(() => HttpRouter.toWebHandler(routesLayer, { disableLogger: true })), + (environment) => + Effect.tryPromise(async () => { + const discovery = await environment.handler( + new Request(`http://127.0.0.1${CONNECT_PAIRING_DISCOVERY_PATH}`), + requestContext, + ); + expect(discovery.status).toBe(200); + const metadata = (await discovery.json()) as { + readonly authorization_endpoint: string; + readonly token_endpoint: string; + readonly scopes_supported: ReadonlyArray; + }; + const origin = new URL(metadata.authorization_endpoint).origin; + expect(metadata.authorization_endpoint).toBe(`${origin}${MCP_PAIRING_AUTHORIZE_PATH}`); + expect(metadata.token_endpoint).toBe(`${origin}${MCP_PAIRING_TOKEN_PATH}`); + expect(metadata.scopes_supported).toEqual([...MCP_PAIRING_SCOPES]); + + const authorize = await environment.handler( + new Request(`http://127.0.0.1${MCP_PAIRING_AUTHORIZE_PATH}`), + requestContext, + ); + expect(authorize.status).toBe(200); + expect(await authorize.json()).toMatchObject({ + pairing: "code", + peer_software_id: MCP_PEER_LINK_SOFTWARE_ID, + }); + + const registered = await environment.handler( + new Request(`http://127.0.0.1${MCP_PAIRING_REGISTER_PATH}`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: encodeJson({ software_id: MCP_PEER_LINK_SOFTWARE_ID, client_name: "Air" }), + }), + requestContext, + ); + expect(registered.status).toBe(200); + expect(await registered.json()).toMatchObject({ + client_id: MCP_PEER_LINK_SOFTWARE_ID, + token_endpoint_auth_method: "none", + }); + + const devSession = await environment.handler( + new Request("http://127.0.0.1/api/auth/browser-session", { + method: "POST", + headers: { "content-type": "application/json" }, + body: encodeJson({ credential: DEV_TOKEN }), + }), + requestContext, + ); + expect(devSession.status).toBe(200); + const devCookie = + devSession.headers + .getSetCookie() + .find((cookie) => cookie.startsWith("t3_dev_session_")) + ?.split(";", 1)[0] ?? ""; + expect(devCookie).not.toBe(""); + + const pairing = await environment.handler( + new Request("http://127.0.0.1/api/auth/pairing-token", { + method: "POST", + headers: { "content-type": "application/json", cookie: devCookie }, + body: encodeJson({ access: "auto", label: "kara3" }), + }), + requestContext, + ); + expect(pairing.status).toBe(200); + const issued = (await pairing.json()) as { + readonly credential: string; + readonly access?: string; + }; + expect(issued.access).toBe("auto"); + + const token = await environment.handler( + new Request(`http://127.0.0.1${MCP_PAIRING_TOKEN_PATH}`, { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ + grant_type: "authorization_code", + code: issued.credential, + access: "auto", + }), + }), + requestContext, + ); + expect(token.status).toBe(200); + const exchanged = (await token.json()) as { + readonly scope: string; + readonly token_type: string; + }; + expect(exchanged.token_type).toBe("Bearer"); + expect(exchanged.scope.split(" ")).toEqual([ + "orchestration:read", + "orchestration:operate", + ]); + + const rejected = await environment.handler( + new Request(`http://127.0.0.1${MCP_PAIRING_TOKEN_PATH}`, { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ + grant_type: "authorization_code", + code: "not-a-pairing-code", + }), + }), + requestContext, + ); + expect(rejected.status).toBe(401); + }), + (environment) => Effect.promise(() => environment.dispose()), + ); + }).pipe(Effect.provide(NodeServices.layer)), +); diff --git a/apps/server/src/auth/mcpPairingHttp.ts b/apps/server/src/auth/mcpPairingHttp.ts new file mode 100644 index 0000000000000..0e1c2a2b39ba1 --- /dev/null +++ b/apps/server/src/auth/mcpPairingHttp.ts @@ -0,0 +1,190 @@ +import { + type AuthMcpAuthorizationServerMetadata, + type AuthMcpAuthorizeResult, + type AuthMcpClientRegistration, + type AuthMcpProtectedResourceMetadata, + type AuthMcpRegisteredClient, + EnvironmentHttpApi, + MCP_PAIRING_AUTHORIZE_PATH, + MCP_PAIRING_REGISTER_PATH, + MCP_PAIRING_SCOPES, + MCP_PAIRING_TOKEN_PATH, + MCP_PEER_LINK_SOFTWARE_ID, + mcpClientScopes, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http"; +import * as HttpEffect from "effect/unstable/http/HttpEffect"; +import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder"; + +import * as EnvironmentAuth from "./EnvironmentAuth.ts"; +import { + annotateEnvironmentRequest, + failEnvironmentAuthInvalid, + failEnvironmentInternal, + failEnvironmentInvalidRequest, +} from "./http.ts"; +import { deriveAuthClientMetadata } from "./utils.ts"; + +const DEFAULT_MCP_CLIENT_ID = "t3-mcp-client"; +const DEFAULT_MCP_CLIENT_NAME = "MCP client"; +const SOFTWARE_ID_PATTERN = /^[A-Za-z0-9._-]{1,100}$/; + +export interface McpPairingUrls { + readonly issuer: string; + readonly resource: string; + readonly authorization_endpoint: string; + readonly token_endpoint: string; + readonly registration_endpoint: string; +} + +export function mcpPairingUrls(origin: string): McpPairingUrls { + return { + issuer: origin, + resource: `${origin}/mcp`, + authorization_endpoint: `${origin}${MCP_PAIRING_AUTHORIZE_PATH}`, + token_endpoint: `${origin}${MCP_PAIRING_TOKEN_PATH}`, + registration_endpoint: `${origin}${MCP_PAIRING_REGISTER_PATH}`, + }; +} + +export function protectedResourceMetadata(urls: McpPairingUrls): AuthMcpProtectedResourceMetadata { + return { + resource: urls.resource, + authorization_servers: [urls.issuer], + scopes_supported: MCP_PAIRING_SCOPES, + bearer_methods_supported: ["header"], + resource_name: "T3 Code", + }; +} + +export function authorizationServerMetadata( + urls: McpPairingUrls, +): AuthMcpAuthorizationServerMetadata { + return { + issuer: urls.issuer, + authorization_endpoint: urls.authorization_endpoint, + token_endpoint: urls.token_endpoint, + registration_endpoint: urls.registration_endpoint, + response_types_supported: ["code"], + grant_types_supported: ["authorization_code"], + code_challenge_methods_supported: ["S256"], + token_endpoint_auth_methods_supported: ["none"], + scopes_supported: MCP_PAIRING_SCOPES, + authorization_response_iss_parameter_supported: true, + }; +} + +export function authorizeResult(urls: McpPairingUrls): AuthMcpAuthorizeResult { + return { + pairing: "code", + token_endpoint: urls.token_endpoint, + scopes_supported: MCP_PAIRING_SCOPES, + peer_software_id: MCP_PEER_LINK_SOFTWARE_ID, + }; +} + +export function registerMcpClient( + registration: AuthMcpClientRegistration, +): AuthMcpRegisteredClient | undefined { + const softwareId = registration.software_id?.trim(); + if (softwareId !== undefined && softwareId.length > 0 && !SOFTWARE_ID_PATTERN.test(softwareId)) { + return undefined; + } + const clientName = registration.client_name?.trim(); + return { + client_id: softwareId && softwareId.length > 0 ? softwareId : DEFAULT_MCP_CLIENT_ID, + client_name: + clientName && clientName.length > 0 ? clientName.slice(0, 100) : DEFAULT_MCP_CLIENT_NAME, + token_endpoint_auth_method: "none", + }; +} + +const requestOrigin = Effect.map(HttpServerRequest.HttpServerRequest, (request) => { + const url = HttpServerRequest.toURL(request); + return Option.isSome(url) ? url.value.origin : "http://127.0.0.1"; +}); + +export const mcpPairingHttpApiLayer = HttpApiBuilder.group( + EnvironmentHttpApi, + "mcpOAuth", + Effect.fnUntraced(function* (handlers) { + const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; + + return handlers + .handle( + "protectedResource", + Effect.fn("environment.mcp.protectedResource")(function* (args) { + yield* annotateEnvironmentRequest(args.endpoint.name); + return protectedResourceMetadata(mcpPairingUrls(yield* requestOrigin)); + }), + ) + .handle( + "mcpProtectedResource", + Effect.fn("environment.mcp.mcpProtectedResource")(function* (args) { + yield* annotateEnvironmentRequest(args.endpoint.name); + return protectedResourceMetadata(mcpPairingUrls(yield* requestOrigin)); + }), + ) + .handle( + "authorizationServer", + Effect.fn("environment.mcp.authorizationServer")(function* (args) { + yield* annotateEnvironmentRequest(args.endpoint.name); + return authorizationServerMetadata(mcpPairingUrls(yield* requestOrigin)); + }), + ) + .handle( + "authorize", + Effect.fn("environment.mcp.authorize")(function* (args) { + yield* annotateEnvironmentRequest(args.endpoint.name); + return authorizeResult(mcpPairingUrls(yield* requestOrigin)); + }), + ) + .handle( + "register", + Effect.fn("environment.mcp.register")(function* (args) { + yield* annotateEnvironmentRequest(args.endpoint.name); + const registered = registerMcpClient(args.payload); + if (!registered) { + return yield* failEnvironmentInvalidRequest("invalid_command"); + } + return registered; + }), + ) + .handle( + "token", + Effect.fn("environment.mcp.token")( + function* (args) { + yield* annotateEnvironmentRequest(args.endpoint.name); + const request = yield* HttpServerRequest.HttpServerRequest; + yield* HttpEffect.appendPreResponseHandler((_httpRequest, response) => + Effect.succeed( + HttpServerResponse.setHeaders(response, { + "cache-control": "no-store", + pragma: "no-cache", + }), + ), + ); + return yield* serverAuth.exchangeBootstrapCredentialForAccessToken( + args.payload.code, + mcpClientScopes(args.payload.access ?? "auto"), + deriveAuthClientMetadata({ request }), + ); + }, + Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) => + failEnvironmentAuthInvalid( + EnvironmentAuth.serverAuthCredentialReason(error), + EnvironmentAuth.serverAuthDpopFailureReason(error), + ), + ), + Effect.catchIf(EnvironmentAuth.isServerAuthInvalidRequestError, (error) => + failEnvironmentInvalidRequest(EnvironmentAuth.serverAuthInvalidRequestReason(error)), + ), + Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) => + failEnvironmentInternal("access_token_issuance_failed", error), + ), + ), + ); + }), +); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 7f3165d7c96ca..f6dc23c40570b 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -125,6 +125,7 @@ import * as ServerEnvironment from "./environment/ServerEnvironment.ts"; import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts"; import { makeLaunchPreflightWarningReporter } from "./environment/launchPreflightReporter.ts"; import { authHttpApiLayer, environmentAuthenticatedAuthLayer } from "./auth/http.ts"; +import { mcpPairingHttpApiLayer } from "./auth/mcpPairingHttp.ts"; import * as ServerSecretStore from "./auth/ServerSecretStore.ts"; import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts"; import { @@ -645,6 +646,7 @@ export const makeRoutesLayer = Layer.mergeAll( Layer.mergeAll( HttpApiBuilder.layer(EnvironmentHttpApi).pipe( Layer.provide(authHttpApiLayer), + Layer.provide(mcpPairingHttpApiLayer), Layer.provide(connectHttpApiLayer), Layer.provide(orchestrationHttpApiLayer), Layer.provide(pullRequestHttpApiLayer), diff --git a/docs/operations/fork-release.md b/docs/operations/fork-release.md index 1350a89aa0df6..7c9ca07e3403a 100644 --- a/docs/operations/fork-release.md +++ b/docs/operations/fork-release.md @@ -353,6 +353,40 @@ The fork release attaches `linux-x64` and `win32-x64` self-contained archives. Other platform keys are rejected clearly by the installers and `t3 update` rather than producing a predictable missing-asset error. +## Installing the Connect fix on an Apple Silicon Mac + +The fork diverged from upstream before T3 0.1.8 added MCP pairing scopes, so a +build from that base cannot advertise `/.well-known/oauth-authorization-server` +or exchange a pairing code for `orchestration:read` and `orchestration:operate`. +Another machine, including the MacBook Air signed in as `kara3`, cannot link +and drive this environment until it runs a fork build that includes that +endpoint. + +This fork does not follow upstream's update channel. Do not install a +`pingdotgg/t3code` release, the Homebrew cask, or `t3 update` from `t3.codes`. +Desktop in-app update is not on: releases do not attach `latest.yml` or +`latest-mac.yml`, and an unsigned macOS build cannot apply a Squirrel.Mac +update. Install by downloading the artifact. + +1. After this change is on `main`, run **Fork release** with `include_macos_arm64` + set. The default release builds the Intel DMG only. The Air is Apple Silicon + and needs the arm64 artifact. That build is reported untested. +2. Download `T3-Code--arm64.dmg` from the `nullStack65/t3code` GitHub + Release for that version. Check it against `SHA256SUMS` on the same release. +3. Open the DMG and copy T3 Code into Applications. The build is unsigned unless + Apple signing secrets were present, so the first launch needs Gatekeeper's + Open action (right-click the app, choose Open). +4. Install over the existing app. The `appId` and user-data path are unchanged, + so projects, credentials, and pairings already on the Air stay in place. +5. On the host that should be driven, open **Settings → Connections**, sign in, + and enable **T3 Connect**. On the Air, sign in to the same account and choose + that environment. A one-time code from **Settings → Connections** on the host + can also be redeemed at `/pair` or exchanged at `/oauth/mcp/token`. The host's + `/.well-known/oauth-authorization-server` document lists the MCP pairing scopes. + +Later installs are the same download. There is no automatic update feed to +subscribe the Air to. + ## Signing and updates Three distinct support levels: diff --git a/packages/contracts/src/auth.ts b/packages/contracts/src/auth.ts index b2ce4e591f842..0664f92c7ad3e 100644 --- a/packages/contracts/src/auth.ts +++ b/packages/contracts/src/auth.ts @@ -114,6 +114,99 @@ export const AuthAdministrativeScopes = [ AuthRelayWriteScope, ] as const; +/** + * Access a pairing code grants an MCP client, including another T3 environment + * that links here. `full-access` is this fork's standard client set. + */ +export const AuthMcpClientAccess = Schema.Literals([ + "read-only", + "approval-required", + "auto-accept-edits", + "auto", + "full-access", +]); +export type AuthMcpClientAccess = typeof AuthMcpClientAccess.Type; + +export const MCP_PEER_LINK_SOFTWARE_ID = "t3code-peer-link"; +export const CONNECT_PAIRING_DISCOVERY_PATH = "/.well-known/oauth-authorization-server"; +export const MCP_PAIRING_TOKEN_PATH = "/oauth/mcp/token"; +export const MCP_PAIRING_AUTHORIZE_PATH = "/oauth/mcp/authorize"; +export const MCP_PAIRING_REGISTER_PATH = "/oauth/mcp/register"; +export const MCP_PROTECTED_RESOURCE_PATH = "/.well-known/oauth-protected-resource"; +export const MCP_PROTECTED_RESOURCE_MCP_PATH = "/.well-known/oauth-protected-resource/mcp"; + +/** Scopes advertised for Connect pairing. Every `mcpClientScopes` result is a subset. */ +export const MCP_PAIRING_SCOPES = AuthStandardClientScopes; + +export function mcpClientScopes(access: AuthMcpClientAccess): ReadonlyArray { + switch (access) { + case "read-only": + return [AuthOrchestrationReadScope]; + case "approval-required": + case "auto-accept-edits": + case "auto": + return [AuthOrchestrationReadScope, AuthOrchestrationOperateScope]; + case "full-access": + return MCP_PAIRING_SCOPES; + default: { + const unreachable: never = access; + return unreachable; + } + } +} + +export const AuthMcpProtectedResourceMetadata = Schema.Struct({ + resource: Schema.String, + authorization_servers: Schema.Array(Schema.String), + scopes_supported: Schema.Array(AuthEnvironmentScope), + bearer_methods_supported: Schema.Array(Schema.Literal("header")), + resource_name: Schema.String, +}); +export type AuthMcpProtectedResourceMetadata = typeof AuthMcpProtectedResourceMetadata.Type; + +export const AuthMcpAuthorizationServerMetadata = Schema.Struct({ + issuer: Schema.String, + authorization_endpoint: Schema.String, + token_endpoint: Schema.String, + registration_endpoint: Schema.String, + response_types_supported: Schema.Array(Schema.Literal("code")), + grant_types_supported: Schema.Array(Schema.Literal("authorization_code")), + code_challenge_methods_supported: Schema.Array(Schema.Literal("S256")), + token_endpoint_auth_methods_supported: Schema.Array(Schema.Literal("none")), + scopes_supported: Schema.Array(AuthEnvironmentScope), + authorization_response_iss_parameter_supported: Schema.Boolean, +}); +export type AuthMcpAuthorizationServerMetadata = typeof AuthMcpAuthorizationServerMetadata.Type; + +export const AuthMcpAuthorizeResult = Schema.Struct({ + pairing: Schema.Literal("code"), + token_endpoint: Schema.String, + scopes_supported: Schema.Array(AuthEnvironmentScope), + peer_software_id: Schema.Literal(MCP_PEER_LINK_SOFTWARE_ID), +}); +export type AuthMcpAuthorizeResult = typeof AuthMcpAuthorizeResult.Type; + +export const AuthMcpClientRegistration = Schema.Struct({ + client_name: Schema.optionalKey(Schema.String), + software_id: Schema.optionalKey(Schema.String), + redirect_uris: Schema.optionalKey(Schema.Array(Schema.String)), +}); +export type AuthMcpClientRegistration = typeof AuthMcpClientRegistration.Type; + +export const AuthMcpRegisteredClient = Schema.Struct({ + client_id: Schema.String, + client_name: Schema.String, + token_endpoint_auth_method: Schema.Literal("none"), +}); +export type AuthMcpRegisteredClient = typeof AuthMcpRegisteredClient.Type; + +export const AuthMcpPairingTokenRequest = Schema.Struct({ + grant_type: Schema.Literal("authorization_code"), + code: TrimmedNonEmptyString, + access: Schema.optionalKey(AuthMcpClientAccess), +}).pipe(HttpApiSchema.asFormUrlEncoded()); +export type AuthMcpPairingTokenRequest = typeof AuthMcpPairingTokenRequest.Type; + export const AuthTokenExchangeGrantType = "urn:ietf:params:oauth:grant-type:token-exchange" as const; export const AuthAccessTokenType = "urn:ietf:params:oauth:token-type:access_token" as const; @@ -215,6 +308,8 @@ export const AuthPairingCredentialResult = Schema.Struct({ credential: TrimmedNonEmptyString, label: Schema.optionalKey(TrimmedNonEmptyString), expiresAt: Schema.DateTimeUtc, + /** Set when the code was minted for an MCP client at this access level. */ + access: Schema.optionalKey(AuthMcpClientAccess), }); export type AuthPairingCredentialResult = typeof AuthPairingCredentialResult.Type; @@ -342,6 +437,8 @@ export type AuthRevokeClientSessionInput = typeof AuthRevokeClientSessionInput.T export const AuthCreatePairingCredentialInput = Schema.Struct({ label: Schema.optionalKey(TrimmedNonEmptyString), scopes: Schema.optionalKey(AuthEnvironmentScopes), + /** When `scopes` is omitted, the code carries `mcpClientScopes(access)`. */ + access: Schema.optionalKey(AuthMcpClientAccess), }); export type AuthCreatePairingCredentialInput = typeof AuthCreatePairingCredentialInput.Type; diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.ts index ae63a405fa989..c8b3cdeec76a4 100644 --- a/packages/contracts/src/environmentHttp.ts +++ b/packages/contracts/src/environmentHttp.ts @@ -14,6 +14,12 @@ import { AuthBrowserSessionResult, AuthClientSession, AuthCreatePairingCredentialInput, + AuthMcpAuthorizationServerMetadata, + AuthMcpAuthorizeResult, + AuthMcpClientRegistration, + AuthMcpPairingTokenRequest, + AuthMcpProtectedResourceMetadata, + AuthMcpRegisteredClient, AuthPairingCredentialResult, AuthPairingLink, AuthRevokeClientSessionInput, @@ -22,6 +28,12 @@ import { AuthTokenExchangeRequest, AuthSessionState, AuthWebSocketTicketResult, + CONNECT_PAIRING_DISCOVERY_PATH, + MCP_PAIRING_AUTHORIZE_PATH, + MCP_PAIRING_REGISTER_PATH, + MCP_PAIRING_TOKEN_PATH, + MCP_PROTECTED_RESOURCE_MCP_PATH, + MCP_PROTECTED_RESOURCE_PATH, ServerAuthSessionMethod, } from "./auth.ts"; import { @@ -554,6 +566,50 @@ class EnvironmentPullRequestsHttpApi extends HttpApiGroup.make("pullRequests").a }).middleware(EnvironmentAuthenticatedAuth), ) {} +/** + * MCP clients and linked environments discover Connect pairing here. + * `authorizationServer` lists the scopes a pairing code must carry. + */ +class EnvironmentMcpOAuthHttpApi extends HttpApiGroup.make("mcpOAuth") + .add( + HttpApiEndpoint.get("protectedResource", MCP_PROTECTED_RESOURCE_PATH, { + success: AuthMcpProtectedResourceMetadata, + }), + ) + .add( + HttpApiEndpoint.get("mcpProtectedResource", MCP_PROTECTED_RESOURCE_MCP_PATH, { + success: AuthMcpProtectedResourceMetadata, + }), + ) + .add( + HttpApiEndpoint.get("authorizationServer", CONNECT_PAIRING_DISCOVERY_PATH, { + success: AuthMcpAuthorizationServerMetadata, + }), + ) + .add( + HttpApiEndpoint.get("authorize", MCP_PAIRING_AUTHORIZE_PATH, { + success: AuthMcpAuthorizeResult, + }), + ) + .add( + HttpApiEndpoint.post("register", MCP_PAIRING_REGISTER_PATH, { + payload: AuthMcpClientRegistration, + success: AuthMcpRegisteredClient, + error: [EnvironmentRequestInvalidError], + }), + ) + .add( + HttpApiEndpoint.post("token", MCP_PAIRING_TOKEN_PATH, { + payload: AuthMcpPairingTokenRequest, + success: AuthAccessTokenResult, + error: [ + EnvironmentAuthInvalidError, + EnvironmentRequestInvalidError, + EnvironmentInternalError, + ], + }), + ) {} + class EnvironmentConnectHttpApi extends HttpApiGroup.make("connect") .add( HttpApiEndpoint.post("linkProof", "/api/connect/link-proof", { @@ -620,4 +676,5 @@ export class EnvironmentHttpApi extends HttpApi.make("environment") .add(EnvironmentAuthHttpApi) .add(EnvironmentOrchestrationHttpApi) .add(EnvironmentPullRequestsHttpApi) - .add(EnvironmentConnectHttpApi) {} + .add(EnvironmentConnectHttpApi) + .add(EnvironmentMcpOAuthHttpApi) {} diff --git a/packages/contracts/src/mcpPairing.test.ts b/packages/contracts/src/mcpPairing.test.ts new file mode 100644 index 0000000000000..98bf07418f047 --- /dev/null +++ b/packages/contracts/src/mcpPairing.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { AuthMcpClientAccess, MCP_PAIRING_SCOPES, mcpClientScopes } from "./auth.ts"; + +describe("MCP pairing scopes", () => { + it("grants a linked environment the scopes it needs to drive this one", () => { + expect(mcpClientScopes("read-only")).toEqual(["orchestration:read"]); + expect(mcpClientScopes("auto")).toEqual(["orchestration:read", "orchestration:operate"]); + expect(mcpClientScopes("approval-required")).toEqual(mcpClientScopes("auto")); + expect(mcpClientScopes("auto-accept-edits")).toEqual(mcpClientScopes("auto")); + expect(mcpClientScopes("full-access")).toEqual([...MCP_PAIRING_SCOPES]); + for (const access of AuthMcpClientAccess.literals) { + for (const scope of mcpClientScopes(access)) { + expect(MCP_PAIRING_SCOPES).toContain(scope); + } + } + }); +}); diff --git a/scripts/connect-pairing-smoke.ts b/scripts/connect-pairing-smoke.ts new file mode 100644 index 0000000000000..00fdeacfb4611 --- /dev/null +++ b/scripts/connect-pairing-smoke.ts @@ -0,0 +1,30 @@ +// @effect-diagnostics nodeBuiltinImport:off - The smoke check reads a built bundle from disk. +// @effect-diagnostics globalConsole:off - This is a one-shot CLI, not an Effect program. +import * as NodePath from "node:path"; +import * as NodeURL from "node:url"; + +import { + bundleContainsConnectPairingEndpoint, + CONNECT_PAIRING_DISCOVERY_PATH, +} from "./lib/connect-pairing-bundle.ts"; + +const repoRoot = NodePath.resolve(NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)), ".."); +const roots = process.argv.slice(2); +const targets = roots.length > 0 ? roots : [NodePath.join(repoRoot, "apps/server/dist")]; + +let missing = false; +for (const root of targets) { + const resolved = NodePath.resolve(root); + if (!bundleContainsConnectPairingEndpoint(resolved)) { + missing = true; + console.error( + `Connect pairing endpoint ${CONNECT_PAIRING_DISCOVERY_PATH} is missing from ${resolved}`, + ); + } else { + console.log(`Connect pairing endpoint is present in ${resolved}`); + } +} + +if (missing) { + process.exit(1); +} diff --git a/scripts/lib/connect-pairing-bundle.test.ts b/scripts/lib/connect-pairing-bundle.test.ts new file mode 100644 index 0000000000000..d066ed5ff87c4 --- /dev/null +++ b/scripts/lib/connect-pairing-bundle.test.ts @@ -0,0 +1,44 @@ +// @effect-diagnostics nodeBuiltinImport:off - The smoke check reads a built bundle from disk. +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; +import { afterEach, describe, expect, it } from "vite-plus/test"; + +import { + bundleContainsConnectPairingEndpoint, + CONNECT_PAIRING_DISCOVERY_PATH, +} from "./connect-pairing-bundle.ts"; + +const temporaryDirectories: string[] = []; + +afterEach(() => { + for (const directory of temporaryDirectories.splice(0)) { + NodeFS.rmSync(directory, { recursive: true, force: true }); + } +}); + +function makeBundle(files: Readonly>): string { + const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-connect-pairing-")); + temporaryDirectories.push(directory); + for (const [name, contents] of Object.entries(files)) { + const file = NodePath.join(directory, name); + NodeFS.mkdirSync(NodePath.dirname(file), { recursive: true }); + NodeFS.writeFileSync(file, contents); + } + return directory; +} + +describe("Connect pairing bundle smoke", () => { + it("finds the discovery endpoint in a built bundle and rejects a bundle without it", () => { + const present = makeBundle({ + "dist/bin.mjs": `const path = ${JSON.stringify(CONNECT_PAIRING_DISCOVERY_PATH)};`, + }); + const absent = makeBundle({ + "dist/bin.mjs": 'const path = "/.well-known/t3/environment";', + }); + + expect(bundleContainsConnectPairingEndpoint(present)).toBe(true); + expect(bundleContainsConnectPairingEndpoint(absent)).toBe(false); + expect(bundleContainsConnectPairingEndpoint(NodePath.join(absent, "missing"))).toBe(false); + }); +}); diff --git a/scripts/lib/connect-pairing-bundle.ts b/scripts/lib/connect-pairing-bundle.ts new file mode 100644 index 0000000000000..2f461805f5cf5 --- /dev/null +++ b/scripts/lib/connect-pairing-bundle.ts @@ -0,0 +1,26 @@ +// @effect-diagnostics nodeBuiltinImport:off - The smoke check reads a built bundle from disk. +import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; + +/** Keep aligned with `CONNECT_PAIRING_DISCOVERY_PATH` in packages/contracts. */ +export const CONNECT_PAIRING_DISCOVERY_PATH = "/.well-known/oauth-authorization-server"; + +const TEXT_EXTENSIONS = new Set([".js", ".mjs", ".cjs", ".html", ".json"]); + +export function bundleContainsConnectPairingEndpoint(root: string): boolean { + return collectText(root).some((text) => text.includes(CONNECT_PAIRING_DISCOVERY_PATH)); +} + +function collectText(root: string): ReadonlyArray { + const stats = NodeFS.statSync(root, { throwIfNoEntry: false }); + if (!stats) return []; + if (stats.isFile()) { + return TEXT_EXTENSIONS.has(NodePath.extname(root)) ? [NodeFS.readFileSync(root, "utf8")] : []; + } + const texts: string[] = []; + for (const entry of NodeFS.readdirSync(root, { withFileTypes: true })) { + if (entry.name === "node_modules") continue; + texts.push(...collectText(NodePath.join(root, entry.name))); + } + return texts; +}