mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-20 18:26:40 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents use apps through connections to remote MCP servers
> - Today an organization connection must sign in as a person (browser
sign-in) or use a static key
> - Service accounts and CI-style integrations have no person who can
sign in
> - The MCP OAuth Client Credentials extension (2026-07-28) defines
machine-to-machine sign-in for this case
> - This pull request adds "Machine sign-in" for organization
connections, with a Paperclip-held signing key (recommended) or a client
secret
> - The benefit is that organizations can connect automation-owned MCP
servers safely, with credentials only in the vault and bound to one
sign-in service
## Linked Issues or Issue Description
**Subsystem affected**
Connections: remote MCP OAuth (server `tool-access/oauth`, tool gateway
token refresh) and the custom MCP server setup flow in the UI.
**Problem or motivation**
Organization-owned automation (service accounts, CI integrations) cannot
connect an MCP server that requires OAuth, because no person can
complete a browser sign-in. The MCP OAuth Client Credentials extension
(`io.modelcontextprotocol/oauth-client-credentials`) solves this with
`grant_type=client_credentials` and RFC 7523 signed client assertions.
**Proposed solution**
Add machine sign-in for organization connections only. Paperclip creates
a keypair per connection, keeps the private key in the company vault,
and shows the public key (PEM and JWK) for the admin to register. A
client secret is also supported. The sign-in service (issuer and token
endpoint) is pinned at setup. Tokens use the existing organization grant
refresh path, so caching, concurrent dedupe and 401 re-request reuse the
existing lease and single flight.
**Alternatives considered**
Reuse the deployment-wide `PAPERCLIP_TOOL_OAUTH_*` client env path that
already sent `client_credentials`. Rejected: it is not per connection,
it keeps secrets in env, and it has no issuer pin. Route machine sign-in
through `connectGalleryApp`. Rejected: its rollback deletes the draft on
a failed test, which would lose a key the admin already registered.
**Roadmap alignment**
Phase 1 of the enterprise MCP plan (no enterprise single sign-on
needed). OIDC login and enterprise-managed authorization (ID-JAG) are
later phases.
## What Changed
- `oauth/client-credentials.ts`: keypair generation (RS256, or ES256
when the service requires it), RFC 7638 key IDs, and RFC 7523 assertions
(`iss` = `sub` = client ID, `aud` = token endpoint, 60 s `exp`, unique
`jti`) with Node `crypto` only.
- `oauth/client.ts`: the token exchange accepts a signed assertion and
then sends only `client_assertion_type` and `client_assertion` (no
`client_id` or secret), as the extension specifies.
- `oauth/client-credentials-service.ts`: discovery of the sign-in
service (protected-resource metadata, then RFC 8414/OIDC metadata with
issuer check, or a token URL entered directly), issuer pinning,
vault-only key and secret handling, draft creation, test-and-activate,
and no-downtime rotation (test the new secret first; stage a new key and
switch only after the provider accepts it).
- `oauth/grant-refresh.ts` and `oauth/connection-refresh.ts`: machine
sign-in requests a new access token with the connection's own
credentials instead of needing a refresh token. It never falls back to
deployment-wide OAuth clients.
- `catalog/discovery.ts`: a rejected token on a machine sign-in
connection never re-runs discovery or rewrites the pinned endpoints.
- `mcp-http.ts` and the tool gateway: declare
`io.modelcontextprotocol/oauth-client-credentials` in client
capabilities only for connections that use it.
- Routes (with OpenAPI and activity logging): `POST
/companies/{companyId}/tools/machine-sign-in`, `GET|POST
/tool-connections/{id}/machine-sign-in[/test|/rotate|/rotate/complete]`.
Removal activity now records `machineSignIn: true`. The runner API
treats these routes as sensitive.
- Shared validators and types for machine sign-in.
- UI: "Machine sign-in" under Advanced authentication in the custom MCP
server flow (organization connections only), `MachineSignInSetup`
(choose Paperclip key or client secret, register the public key, test),
and Storybook stories for each setup state.
- Docs: `doc/connections/MCP-CLIENT-CREDENTIALS.md`, linked from
`doc/connections/README.md` and `GENERIC-REMOTE-MCP.md`.
## Verification
- `server/src/__tests__/tool-access-client-credentials.test.ts`: 16/16
pass. It uses a fake sign-in service that verifies real signatures
against registered keys, and a fake MCP server. It covers RS256 and
ES256 assertion claims and signatures, assertion-only client
authentication, the secret flow (`client_secret_basic`), discovery and
direct token URL, issuer pinning (refuses a different sign-in service
and sends it nothing), the pinned endpoint surviving a hostile
challenge, the token cache (0 token requests while live), concurrent
dedupe (5 callers on 2 service instances produce 1 token request), 401
re-request, key and secret rotation, a refused personal connection,
secret redaction in responses, rows and activity, and vault cleanup on
removal.
- Red/green: with the grant-refresh machine sign-in branch and the
discovery pin guard disabled, 5 runtime tests fail (pin, cache/dedupe,
401 re-request, both rotations). Restored: 16/16 pass. The other tests
cover new routes and services that do not exist on `master`.
- `ui/src/features/connections/MachineSignInSetup.test.tsx`: 3/3.
`ConnectionSetupFlow.architecture` and `.oauth` tests: 19/19.
- `openapi-routes.test.ts`: 51/51. `runner-api.test.ts`: 2153/2153.
`mcp-http.test.ts`: 9/9. Existing `tool-access-service.test.ts` refresh
and legacy client-credentials tests: 54/54 (filtered).
- Server package `tsc --noEmit`: clean. UI `tsc`: clean except the
pre-existing generated Storybook catalog imports.
- Not run locally (machine under heavy load): full suites, repo-wide
typecheck, browser check of the live app. CI covers breadth.
## Risks
- No migration. New config lives in `config.oauth` (`grantType:
"client_credentials"` plus `clientAuth`). Older env-configured
client-credentials connections have no `clientAuth` and keep their
original path.
- The capability declaration adds one extension key only for machine
sign-in connections. Other requests are unchanged.
- Rotation has no settings-page control yet; it is available through the
API. This is a follow-up.
- Low risk to agent boot and time to first token: a live token is read
exactly like a browser sign-in token.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with
tool use (shell, file edits, test runs).
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [ ] I will address all Greptile and reviewer comments before
requesting merge
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
189 lines
7.9 KiB
TypeScript
189 lines
7.9 KiB
TypeScript
import { createHash, createPublicKey, generateKeyPair, randomUUID, sign, type JsonWebKey, type KeyObject } from "node:crypto";
|
|
import type { toolConnections } from "@paperclipai/db";
|
|
import { asRecord, normalizeOauthScopes, oauthConfig } from "./metadata.js";
|
|
|
|
/**
|
|
* MCP OAuth Client Credentials extension (2026-07-28): machine-to-machine sign-in
|
|
* for organization-owned connections. No person signs in; Paperclip presents a
|
|
* client it was registered as, either with a signed assertion (RFC 7523,
|
|
* `private_key_jwt`, recommended) or a client secret.
|
|
*
|
|
* This module is the protocol half: key material, assertions, and how the
|
|
* connection records its pinned authorization server. Secret values never live
|
|
* here; they are read from the company vault by the caller just before a token
|
|
* request and never stored in config.
|
|
*/
|
|
export const CLIENT_ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
|
|
|
|
/** Vault paths. The private key and client secret are only ever sent to the pinned token endpoint. */
|
|
export const CLIENT_PRIVATE_KEY_PATH = "oauth.client_private_key";
|
|
export const CLIENT_PRIVATE_KEY_NEXT_PATH = "oauth.client_private_key_next";
|
|
export const CLIENT_SECRET_PATH = "oauth.client_secret";
|
|
|
|
export type ClientCredentialsAuthMethod = "private_key_jwt" | "client_secret_basic" | "client_secret_post";
|
|
export type ClientAssertionAlgorithm = "RS256" | "ES256";
|
|
|
|
/** Public half of a Paperclip-held key, safe to show and to store in config. */
|
|
export type ClientPublicKey = {
|
|
keyId: string;
|
|
algorithm: ClientAssertionAlgorithm;
|
|
publicKeyPem: string;
|
|
publicJwk: JsonWebKey;
|
|
createdAt: string;
|
|
};
|
|
|
|
export type ClientCredentialsSettings = {
|
|
clientId: string | null;
|
|
tokenUrl: string;
|
|
/** Pinned authorization-server issuer. Null when the admin entered a token URL directly. */
|
|
issuer: string | null;
|
|
scopes: string[];
|
|
resource: string | null;
|
|
authMethod: ClientCredentialsAuthMethod;
|
|
key: ClientPublicKey | null;
|
|
pendingKey: ClientPublicKey | null;
|
|
};
|
|
|
|
function isAuthMethod(value: unknown): value is ClientCredentialsAuthMethod {
|
|
return value === "private_key_jwt" || value === "client_secret_basic" || value === "client_secret_post";
|
|
}
|
|
|
|
function publicKeyFrom(value: unknown): ClientPublicKey | null {
|
|
const record = asRecord(value);
|
|
if (typeof record.keyId !== "string" || typeof record.publicKeyPem !== "string") return null;
|
|
if (record.algorithm !== "RS256" && record.algorithm !== "ES256") return null;
|
|
return {
|
|
keyId: record.keyId,
|
|
algorithm: record.algorithm,
|
|
publicKeyPem: record.publicKeyPem,
|
|
publicJwk: asRecord(record.publicJwk) as JsonWebKey,
|
|
createdAt: typeof record.createdAt === "string" ? record.createdAt : new Date(0).toISOString(),
|
|
};
|
|
}
|
|
|
|
/**
|
|
* The machine sign-in settings a connection was set up with, or null when the
|
|
* connection does not use them. Older env-configured client-credentials rows
|
|
* (no `clientAuth`) keep their original path.
|
|
*/
|
|
export function clientCredentialsSettings(
|
|
connection: Pick<typeof toolConnections.$inferSelect, "config">,
|
|
): ClientCredentialsSettings | null {
|
|
const oauth = oauthConfig(connection);
|
|
if (oauth.grantType !== "client_credentials") return null;
|
|
const clientAuth = asRecord(oauth.clientAuth);
|
|
if (!isAuthMethod(clientAuth.method) || typeof oauth.tokenUrl !== "string") return null;
|
|
return {
|
|
clientId: typeof oauth.clientId === "string" && oauth.clientId.trim() ? oauth.clientId.trim() : null,
|
|
tokenUrl: oauth.tokenUrl,
|
|
issuer: typeof oauth.issuer === "string" && oauth.issuer.trim() ? oauth.issuer.trim() : null,
|
|
scopes: normalizeOauthScopes(oauth.scopes),
|
|
resource: typeof oauth.resource === "string" && oauth.resource ? oauth.resource : null,
|
|
authMethod: clientAuth.method,
|
|
key: publicKeyFrom(clientAuth.key),
|
|
pendingKey: publicKeyFrom(clientAuth.pendingKey),
|
|
};
|
|
}
|
|
|
|
export function usesClientCredentials(connection: Pick<typeof toolConnections.$inferSelect, "config">): boolean {
|
|
return clientCredentialsSettings(connection) !== null;
|
|
}
|
|
|
|
/** Prefer RS256 (the most widely accepted); use ES256 only when the server asks for it. */
|
|
export function chooseAssertionAlgorithm(supported: string[] | undefined): ClientAssertionAlgorithm {
|
|
if (!supported?.length || supported.includes("RS256")) return "RS256";
|
|
if (supported.includes("ES256")) return "ES256";
|
|
return "RS256";
|
|
}
|
|
|
|
function base64Url(value: Buffer | string): string {
|
|
return Buffer.from(value).toString("base64url");
|
|
}
|
|
|
|
/** RFC 7638 JWK thumbprint, used as the key ID so it is stable and verifiable. */
|
|
export function jwkThumbprint(jwk: JsonWebKey): string {
|
|
const canonical = jwk.kty === "EC"
|
|
? { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y }
|
|
: { e: jwk.e, kty: jwk.kty, n: jwk.n };
|
|
return base64Url(createHash("sha256").update(JSON.stringify(canonical)).digest());
|
|
}
|
|
|
|
export function publicKeyForPrivateKey(privateKeyPem: string, algorithm: ClientAssertionAlgorithm, createdAt: Date): ClientPublicKey {
|
|
const publicKey = createPublicKey(privateKeyPem);
|
|
const exported = publicKey.export({ format: "jwk" });
|
|
const keyId = jwkThumbprint(exported);
|
|
return {
|
|
keyId,
|
|
algorithm,
|
|
publicKeyPem: publicKey.export({ format: "pem", type: "spki" }).toString(),
|
|
publicJwk: { ...exported, kid: keyId, alg: algorithm, use: "sig" },
|
|
createdAt: createdAt.toISOString(),
|
|
};
|
|
}
|
|
|
|
function generatePrivateKey(algorithm: ClientAssertionAlgorithm): Promise<KeyObject> {
|
|
return new Promise((resolve, reject) => {
|
|
const done = (error: Error | null, _publicKey: KeyObject, privateKey: KeyObject) =>
|
|
error ? reject(error) : resolve(privateKey);
|
|
if (algorithm === "ES256") generateKeyPair("ec", { namedCurve: "P-256" }, done);
|
|
else generateKeyPair("rsa", { modulusLength: 2048 }, done);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* A fresh signing key. The private half goes straight to the vault; only the
|
|
* public half is kept in config. Generated off the event loop: RSA key
|
|
* generation takes long enough to stall unrelated requests if done inline.
|
|
*/
|
|
export async function generateClientKeyPair(algorithm: ClientAssertionAlgorithm, now = new Date()): Promise<{
|
|
privateKeyPem: string;
|
|
publicKey: ClientPublicKey;
|
|
}> {
|
|
const privateKey = await generatePrivateKey(algorithm);
|
|
const privateKeyPem = privateKey.export({ format: "pem", type: "pkcs8" }).toString();
|
|
return { privateKeyPem, publicKey: publicKeyForPrivateKey(privateKeyPem, algorithm, now) };
|
|
}
|
|
|
|
/** Assertions are single-use and short-lived: a captured one is useless a minute later. */
|
|
export const CLIENT_ASSERTION_LIFETIME_SECONDS = 60;
|
|
|
|
/**
|
|
* RFC 7523 §3 client assertion: `iss` = `sub` = client ID, `aud` = the token
|
|
* endpoint it is presented to, a short `exp`, and a unique `jti`.
|
|
*/
|
|
export function signClientAssertion(input: {
|
|
privateKeyPem: string;
|
|
algorithm: ClientAssertionAlgorithm;
|
|
keyId: string;
|
|
clientId: string;
|
|
audience: string;
|
|
now?: Date;
|
|
}): string {
|
|
const issuedAt = Math.floor((input.now ?? new Date()).getTime() / 1000);
|
|
const header = { alg: input.algorithm, typ: "JWT", kid: input.keyId };
|
|
const claims = {
|
|
iss: input.clientId,
|
|
sub: input.clientId,
|
|
aud: input.audience,
|
|
iat: issuedAt,
|
|
exp: issuedAt + CLIENT_ASSERTION_LIFETIME_SECONDS,
|
|
jti: randomUUID(),
|
|
};
|
|
const signingInput = `${base64Url(JSON.stringify(header))}.${base64Url(JSON.stringify(claims))}`;
|
|
const signature = sign(
|
|
"sha256",
|
|
Buffer.from(signingInput),
|
|
input.algorithm === "ES256"
|
|
? { key: input.privateKeyPem, dsaEncoding: "ieee-p1363" }
|
|
: input.privateKeyPem,
|
|
);
|
|
return `${signingInput}.${base64Url(signature)}`;
|
|
}
|
|
|
|
/** Secret authentication method the server accepts, preferring Basic as the spec requires servers to support it. */
|
|
export function chooseSecretAuthMethod(supported: string[] | undefined): "client_secret_basic" | "client_secret_post" {
|
|
if (!supported?.length || supported.includes("client_secret_basic")) return "client_secret_basic";
|
|
if (supported.includes("client_secret_post")) return "client_secret_post";
|
|
return "client_secret_basic";
|
|
}
|