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>
446 lines
16 KiB
TypeScript
446 lines
16 KiB
TypeScript
import { HttpError, unprocessable } from "../../../errors.js";
|
|
import { asRecord, originOf } from "./metadata.js";
|
|
import { normalizeOAuthProviderError, oauthProviderErrorMessage } from "./provider-errors.js";
|
|
import type { OAuthProviderEndpoints, OAuthTokenEndpointAuthMethod, OAuthTransport } from "./types.js";
|
|
import { oauthApplicationType } from "./client-metadata.js";
|
|
import { CLIENT_ASSERTION_TYPE } from "./client-credentials.js";
|
|
|
|
const MAX_OAUTH_DCR_CLIENT_ID_LENGTH = 4_096;
|
|
|
|
const MAX_OAUTH_DCR_CLIENT_SECRET_LENGTH = 16_384;
|
|
|
|
function invalidOAuthDcrResponse(field: string, reason: string): HttpError {
|
|
return new HttpError(
|
|
502,
|
|
"OAuth provider returned incompatible dynamic client metadata",
|
|
{
|
|
code: "oauth_dcr_response_invalid",
|
|
field,
|
|
reason,
|
|
},
|
|
);
|
|
}
|
|
|
|
function parseOAuthDcrString(
|
|
record: Record<string, unknown>,
|
|
field: "client_id" | "client_secret",
|
|
input: { required: boolean; maxLength: number },
|
|
): string | null {
|
|
const value = record[field];
|
|
if (value === undefined || value === null) {
|
|
if (input.required) throw invalidOAuthDcrResponse(field, "missing");
|
|
return null;
|
|
}
|
|
if (
|
|
typeof value !== "string" ||
|
|
value.length === 0 ||
|
|
value.length > input.maxLength
|
|
) {
|
|
throw invalidOAuthDcrResponse(field, "invalid_string");
|
|
}
|
|
if (field === "client_id" && value.trim() !== value) {
|
|
throw invalidOAuthDcrResponse(field, "invalid_string");
|
|
}
|
|
return value;
|
|
}
|
|
|
|
function assertOAuthDcrArray(
|
|
record: Record<string, unknown>,
|
|
field: "redirect_uris" | "grant_types" | "response_types",
|
|
expected: string[],
|
|
options: { allowAdditional?: boolean; allowOmitted?: boolean } = {},
|
|
) {
|
|
if (record[field] === undefined) {
|
|
if (options.allowOmitted) return;
|
|
throw invalidOAuthDcrResponse(field, "missing");
|
|
}
|
|
const value = record[field];
|
|
if (
|
|
!Array.isArray(value) ||
|
|
value.length < expected.length ||
|
|
value.length > 32 ||
|
|
value.some(
|
|
(entry) =>
|
|
typeof entry !== "string" ||
|
|
entry.length === 0 ||
|
|
entry.length > 2_048,
|
|
)
|
|
) {
|
|
throw invalidOAuthDcrResponse(field, "invalid_array");
|
|
}
|
|
const actual = new Set(value);
|
|
if (
|
|
expected.some((entry) => !actual.has(entry)) ||
|
|
(!options.allowAdditional && actual.size !== expected.length)
|
|
) {
|
|
throw invalidOAuthDcrResponse(field, "registered_value_mismatch");
|
|
}
|
|
}
|
|
|
|
function parseOAuthDcrTimestamp(
|
|
record: Record<string, unknown>,
|
|
field: string,
|
|
): number | null {
|
|
const value = record[field];
|
|
if (value === undefined || value === null) return null;
|
|
if (
|
|
typeof value !== "number" ||
|
|
!Number.isSafeInteger(value) ||
|
|
value < 0
|
|
) {
|
|
throw invalidOAuthDcrResponse(field, "invalid_timestamp");
|
|
}
|
|
return value;
|
|
}
|
|
|
|
function selectOAuthDcrTokenEndpointAuthMethod(
|
|
supported: string[] | undefined,
|
|
): OAuthTokenEndpointAuthMethod {
|
|
if (!supported?.length || supported.includes("none")) return "none";
|
|
// When a confidential client is required, preserve the provider's advertised
|
|
// ordering. Miro advertises both methods but only completes its MCP exchange
|
|
// for the first one (`client_secret_post`), while Supabase and Hugging Face
|
|
// advertise `client_secret_basic` first. Treating Basic as a global preference
|
|
// creates a valid-looking registration that fails only after user consent.
|
|
for (const method of supported) {
|
|
if (method === "client_secret_basic" || method === "client_secret_post")
|
|
return method;
|
|
}
|
|
throw unprocessable(
|
|
"OAuth provider does not support a compatible dynamic client authentication method",
|
|
{
|
|
code: "oauth_dcr_client_auth_unsupported",
|
|
supportedMethods: supported,
|
|
},
|
|
);
|
|
}
|
|
|
|
export function storedOAuthTokenEndpointAuthMethod(
|
|
oauth: Record<string, unknown>,
|
|
clientSecret: string | null | undefined,
|
|
): OAuthTokenEndpointAuthMethod {
|
|
const method = oauth.clientTokenEndpointAuthMethod;
|
|
if (
|
|
method === "none" ||
|
|
method === "client_secret_basic" ||
|
|
method === "client_secret_post"
|
|
) {
|
|
return method;
|
|
}
|
|
const advertised = Array.isArray(oauth.tokenEndpointAuthMethodsSupported)
|
|
? oauth.tokenEndpointAuthMethodsSupported.filter(
|
|
(value): value is string => typeof value === "string",
|
|
)
|
|
: [];
|
|
// Manual OAuth clients do not carry a DCR-selected method. Follow the
|
|
// authorization server's advertised preference when it offers a
|
|
// confidential-client method; Xero, for example, documents Basic auth and
|
|
// rejects an otherwise valid code when the secret is posted in the body.
|
|
if (clientSecret && advertised.includes("client_secret_basic"))
|
|
return "client_secret_basic";
|
|
if (clientSecret && advertised.includes("client_secret_post"))
|
|
return "client_secret_post";
|
|
// Existing manually configured and preconfigured clients predate the
|
|
// persisted method field and already use client_secret_post successfully.
|
|
return clientSecret ? "client_secret_post" : "none";
|
|
}
|
|
|
|
export function createOAuthClientProtocol({ fetchRemoteHttpUrl, assertOAuthEndpointUrl }: OAuthTransport) {
|
|
async function requestOAuthClientRegistration(input: { endpoints: OAuthProviderEndpoints; redirectUri: string }) {
|
|
if (!input.endpoints.registrationUrl) {
|
|
throw unprocessable(
|
|
"OAuth provider does not advertise dynamic client registration",
|
|
{
|
|
code: "oauth_dcr_not_supported",
|
|
},
|
|
);
|
|
}
|
|
if (
|
|
input.endpoints.codeChallengeMethodsSupported?.length &&
|
|
!input.endpoints.codeChallengeMethodsSupported.includes("S256")
|
|
) {
|
|
throw unprocessable(
|
|
"OAuth provider does not support the required PKCE S256 method",
|
|
{
|
|
code: "oauth_pkce_s256_required",
|
|
},
|
|
);
|
|
}
|
|
const tokenEndpointAuthMethod = selectOAuthDcrTokenEndpointAuthMethod(
|
|
input.endpoints.tokenEndpointAuthMethodsSupported,
|
|
);
|
|
|
|
const host = new URL(input.redirectUri).host;
|
|
const clientNameHost = host
|
|
.replace(/[^A-Za-z0-9-]/g, "-")
|
|
.replace(/-+/g, "-")
|
|
.replace(/^-|-$/g, "");
|
|
const requestedMetadata = {
|
|
// Some DCR servers restrict client_name to alphanumeric characters,
|
|
// hyphens and spaces. Keep the deployment host recognizable without
|
|
// sending punctuation such as dots, colons or parentheses.
|
|
client_name: `Paperclip ${clientNameHost}`,
|
|
redirect_uris: [input.redirectUri],
|
|
grant_types: [
|
|
"authorization_code",
|
|
...(!input.endpoints.grantTypesSupported?.length ||
|
|
input.endpoints.grantTypesSupported.includes("refresh_token")
|
|
? ["refresh_token"]
|
|
: []),
|
|
],
|
|
response_types: ["code"],
|
|
token_endpoint_auth_method: tokenEndpointAuthMethod,
|
|
// MCP requires an explicit `application_type`: `web` for Paperclip's
|
|
// server-side HTTPS callback, `native` for a local install's localhost
|
|
// callback, which OIDC servers refuse for web clients.
|
|
application_type: oauthApplicationType(input.redirectUri),
|
|
};
|
|
const response = await fetchRemoteHttpUrl(
|
|
assertOAuthEndpointUrl("registration", input.endpoints.registrationUrl),
|
|
{
|
|
method: "POST",
|
|
headers: { "content-type": "application/json" },
|
|
body: JSON.stringify(requestedMetadata),
|
|
},
|
|
);
|
|
const record = asRecord(
|
|
(await response.json().catch(() => ({}))) as unknown,
|
|
);
|
|
if (!response.ok) {
|
|
const providerError = normalizeOAuthProviderError(record.error);
|
|
throw new HttpError(
|
|
502,
|
|
oauthProviderErrorMessage(
|
|
providerError,
|
|
"OAuth dynamic client registration failed",
|
|
),
|
|
{
|
|
code: "oauth_dynamic_client_registration_failed",
|
|
providerError,
|
|
status: response.status,
|
|
},
|
|
);
|
|
}
|
|
const clientId = parseOAuthDcrString(record, "client_id", {
|
|
required: true,
|
|
maxLength: MAX_OAUTH_DCR_CLIENT_ID_LENGTH,
|
|
})!;
|
|
const clientSecret = parseOAuthDcrString(record, "client_secret", {
|
|
required: tokenEndpointAuthMethod !== "none",
|
|
maxLength: MAX_OAUTH_DCR_CLIENT_SECRET_LENGTH,
|
|
});
|
|
// Some authorization servers add provider-owned metadata to the registered
|
|
// client. Paperclip still uses only the exact redirect, grant and response
|
|
// types it requested, so accept bounded supersets while requiring every
|
|
// requested value to remain present. Hugging Face, for example, adds the
|
|
// device-code grant to an otherwise valid authorization-code registration.
|
|
assertOAuthDcrArray(
|
|
record,
|
|
"redirect_uris",
|
|
requestedMetadata.redirect_uris,
|
|
{ allowAdditional: true },
|
|
);
|
|
// RFC 7591 registration responses do not consistently echo every accepted
|
|
// request field. Supabase, for example, returns only the client material and
|
|
// redirect URIs. Redirect binding remains mandatory; omitted grant/response
|
|
// metadata inherits the values Paperclip requested. Additional provider-owned
|
|
// values do not widen Paperclip's behavior because they are never persisted as
|
|
// a flow choice or sent in authorization/token requests.
|
|
assertOAuthDcrArray(record, "grant_types", requestedMetadata.grant_types, {
|
|
allowAdditional: true,
|
|
allowOmitted: true,
|
|
});
|
|
assertOAuthDcrArray(
|
|
record,
|
|
"response_types",
|
|
requestedMetadata.response_types,
|
|
{
|
|
allowAdditional: true,
|
|
allowOmitted: true,
|
|
},
|
|
);
|
|
if (
|
|
record.token_endpoint_auth_method !== undefined &&
|
|
record.token_endpoint_auth_method !==
|
|
requestedMetadata.token_endpoint_auth_method
|
|
) {
|
|
throw invalidOAuthDcrResponse(
|
|
"token_endpoint_auth_method",
|
|
"registered_value_mismatch",
|
|
);
|
|
}
|
|
const clientIdIssuedAt = parseOAuthDcrTimestamp(
|
|
record,
|
|
"client_id_issued_at",
|
|
);
|
|
const returnedClientSecretExpiresAt = parseOAuthDcrTimestamp(
|
|
record,
|
|
"client_secret_expires_at",
|
|
);
|
|
// A few public-client registrars (including Mixpanel) return the RFC 7591
|
|
// `0` sentinel even though they issued no secret. It carries no credential
|
|
// lifetime in that case, so normalize it away. A positive expiry without a
|
|
// secret is still contradictory and remains a hard failure.
|
|
if (
|
|
returnedClientSecretExpiresAt !== null &&
|
|
returnedClientSecretExpiresAt > 0 &&
|
|
clientSecret === null
|
|
) {
|
|
throw invalidOAuthDcrResponse(
|
|
"client_secret_expires_at",
|
|
"client_secret_missing",
|
|
);
|
|
}
|
|
const clientSecretExpiresAt = clientSecret
|
|
? returnedClientSecretExpiresAt
|
|
: null;
|
|
return { clientId, clientSecret, tokenEndpointAuthMethod, clientIdIssuedAt, clientSecretExpiresAt };
|
|
}
|
|
|
|
async function exchangeOAuthToken(input: {
|
|
tokenUrl: string;
|
|
clientId: string;
|
|
clientSecret?: string | null;
|
|
tokenEndpointAuthMethod?: OAuthTokenEndpointAuthMethod;
|
|
grantType?: "authorization_code" | "refresh_token" | "client_credentials";
|
|
scopes?: string[];
|
|
redirectUri?: string | null;
|
|
codeVerifier?: string | null;
|
|
code?: string | null;
|
|
refreshToken?: string | null;
|
|
/** RFC 8707 resource indicator: the MCP server this token is for. */
|
|
resource?: string | null;
|
|
/**
|
|
* RFC 7523 signed client assertion (`private_key_jwt`). When present it is
|
|
* the only client authentication sent: the client is identified by the
|
|
* assertion's `sub`, so no client_id or secret goes in the request.
|
|
*/
|
|
clientAssertion?: string | null;
|
|
}) {
|
|
const body = new URLSearchParams();
|
|
if (input.grantType === "client_credentials") {
|
|
body.set("grant_type", "client_credentials");
|
|
if (input.scopes && input.scopes.length > 0)
|
|
body.set("scope", input.scopes.join(" "));
|
|
} else if (input.refreshToken) {
|
|
body.set("grant_type", "refresh_token");
|
|
body.set("refresh_token", input.refreshToken);
|
|
} else {
|
|
body.set("grant_type", "authorization_code");
|
|
body.set("code", input.code ?? "");
|
|
body.set("redirect_uri", input.redirectUri ?? "");
|
|
body.set("code_verifier", input.codeVerifier ?? "");
|
|
}
|
|
const tokenEndpointAuthMethod = input.clientAssertion
|
|
? "private_key_jwt"
|
|
: input.tokenEndpointAuthMethod ??
|
|
(input.clientSecret ? "client_secret_post" : "none");
|
|
if (input.clientAssertion) {
|
|
body.set("client_assertion_type", CLIENT_ASSERTION_TYPE);
|
|
body.set("client_assertion", input.clientAssertion);
|
|
} else if (tokenEndpointAuthMethod !== "client_secret_basic")
|
|
body.set("client_id", input.clientId);
|
|
if (tokenEndpointAuthMethod === "client_secret_post") {
|
|
if (!input.clientSecret) {
|
|
throw unprocessable(
|
|
"OAuth client secret is missing for client_secret_post authentication",
|
|
{
|
|
code: "oauth_client_secret_missing",
|
|
},
|
|
);
|
|
}
|
|
body.set("client_secret", input.clientSecret);
|
|
}
|
|
// RFC 8707: repeat the resource indicator on the token request so the
|
|
// authorization server audience-restricts the access token (and any refresh
|
|
// exchange) to this MCP server.
|
|
if (input.resource) body.set("resource", input.resource);
|
|
|
|
// The token URL can come from a connection row written before the endpoint
|
|
// gate existed, so a client secret / authorization code never leaves
|
|
// Paperclip without re-checking the transport it would leave over.
|
|
const tokenUrl = assertOAuthEndpointUrl("token", input.tokenUrl, {
|
|
// Paperclip's own callback origin, so a first-party token endpoint keeps
|
|
// working on a deployment that is itself served over plaintext HTTP.
|
|
firstPartyOrigin: originOf(input.redirectUri),
|
|
});
|
|
const headers: Record<string, string> = {
|
|
"content-type": "application/x-www-form-urlencoded",
|
|
// Some providers otherwise return a legacy form-encoded token response.
|
|
accept: "application/json",
|
|
};
|
|
if (tokenEndpointAuthMethod === "client_secret_basic") {
|
|
if (!input.clientSecret) {
|
|
throw unprocessable(
|
|
"OAuth client secret is missing for client_secret_basic authentication",
|
|
{
|
|
code: "oauth_client_secret_missing",
|
|
},
|
|
);
|
|
}
|
|
const formEncode = (value: string) =>
|
|
new URLSearchParams({ value }).toString().slice("value=".length);
|
|
headers.Authorization = `Basic ${Buffer.from(
|
|
`${formEncode(input.clientId)}:${formEncode(input.clientSecret)}`,
|
|
"utf8",
|
|
).toString("base64")}`;
|
|
}
|
|
const response = await fetchRemoteHttpUrl(tokenUrl, {
|
|
method: "POST",
|
|
headers,
|
|
body,
|
|
});
|
|
const payload = (await response.json().catch(() => ({}))) as unknown;
|
|
const record = asRecord(payload);
|
|
if (!response.ok || record.ok === false) {
|
|
const providerError = normalizeOAuthProviderError(record.error);
|
|
const message = oauthProviderErrorMessage(
|
|
providerError,
|
|
"OAuth token exchange failed",
|
|
);
|
|
if (
|
|
input.grantType === "refresh_token" &&
|
|
providerError === "invalid_grant"
|
|
) {
|
|
throw new HttpError(
|
|
422,
|
|
"OAuth authorization has expired. Reconnect this app to continue.",
|
|
{
|
|
code: "oauth_reauthorization_required",
|
|
providerError,
|
|
status: response.status,
|
|
},
|
|
);
|
|
}
|
|
throw new HttpError(502, message, {
|
|
code: "oauth_token_exchange_failed",
|
|
providerError,
|
|
status: response.status,
|
|
});
|
|
}
|
|
const accessToken =
|
|
typeof record.access_token === "string" ? record.access_token : null;
|
|
if (!accessToken)
|
|
throw new HttpError(
|
|
502,
|
|
"OAuth provider did not return an access token",
|
|
{ code: "oauth_access_token_missing" },
|
|
);
|
|
const expiresIn =
|
|
typeof record.expires_in === "number"
|
|
? record.expires_in
|
|
: Number(record.expires_in);
|
|
return {
|
|
accessToken,
|
|
refreshToken:
|
|
typeof record.refresh_token === "string" ? record.refresh_token : null,
|
|
expiresIn: Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : null,
|
|
scope: typeof record.scope === "string" ? record.scope : null,
|
|
tokenType:
|
|
typeof record.token_type === "string" ? record.token_type : "Bearer",
|
|
};
|
|
}
|
|
|
|
return { requestOAuthClientRegistration, exchangeOAuthToken };
|
|
}
|