@jini-ai/integrations 0.6.17 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +42 -1
- package/dist/api-connections/access-token.js +4 -14
- package/dist/api-connections/account-actions.d.ts +6 -1
- package/dist/api-connections/attempt-state.d.ts +2 -2
- package/dist/api-connections/attempt-state.js +10 -11
- package/dist/api-connections/authorization.js +13 -20
- package/dist/api-connections/budgets.d.ts +91 -0
- package/dist/api-connections/budgets.js +87 -0
- package/dist/api-connections/byo-client.d.ts +38 -0
- package/dist/api-connections/byo-client.js +28 -0
- package/dist/api-connections/connect.d.ts +87 -0
- package/dist/api-connections/connect.js +143 -0
- package/dist/api-connections/declarations.d.ts +68 -0
- package/dist/api-connections/declarations.js +178 -0
- package/dist/api-connections/deps.d.ts +4 -1
- package/dist/api-connections/descriptor.d.ts +15 -0
- package/dist/api-connections/descriptor.js +1 -5
- package/dist/api-connections/finish-authorization.d.ts +1 -1
- package/dist/api-connections/hook-http.d.ts +20 -0
- package/dist/api-connections/hook-http.js +27 -0
- package/dist/api-connections/host-ports.d.ts +244 -0
- package/dist/api-connections/host-ports.js +2 -0
- package/dist/api-connections/host.d.ts +81 -0
- package/dist/api-connections/host.js +320 -0
- package/dist/api-connections/hosted-mcp/contracts.d.ts +291 -0
- package/dist/api-connections/hosted-mcp/contracts.js +2 -0
- package/dist/api-connections/hosted-mcp/index.d.ts +5 -0
- package/dist/api-connections/hosted-mcp/index.js +3 -0
- package/dist/api-connections/hosted-mcp/shared-sign-in.d.ts +167 -0
- package/dist/api-connections/hosted-mcp/shared-sign-in.js +293 -0
- package/dist/api-connections/hosted-mcp/sign-in.d.ts +25 -0
- package/dist/api-connections/hosted-mcp/sign-in.js +889 -0
- package/dist/api-connections/hosted-sign-in.d.ts +48 -0
- package/dist/api-connections/hosted-sign-in.js +51 -0
- package/dist/api-connections/index.d.ts +23 -1
- package/dist/api-connections/index.js +15 -0
- package/dist/api-connections/install-credential.d.ts +1 -1
- package/dist/api-connections/oauth-capabilities.d.ts +63 -0
- package/dist/api-connections/oauth-capabilities.js +2 -0
- package/dist/api-connections/ports.d.ts +1 -1
- package/dist/api-connections/request-checks.d.ts +11 -1
- package/dist/api-connections/request-checks.js +2 -3
- package/dist/api-connections/shared.d.ts +79 -0
- package/dist/api-connections/shared.js +106 -0
- package/dist/api-connections/token-store/record.d.ts +2 -2
- package/dist/api-connections/token-store/vault-token-store.d.ts +30 -4
- package/dist/api-connections/token-store/vault-token-store.js +1 -4
- package/dist/credentialed-http/sets/host.d.ts +146 -0
- package/dist/credentialed-http/sets/host.js +2 -0
- package/dist/credentialed-http/sets/index.d.ts +24 -0
- package/dist/credentialed-http/sets/index.js +24 -0
- package/dist/credentialed-http/sets/store.d.ts +193 -0
- package/dist/credentialed-http/sets/store.js +489 -0
- package/dist/credentialed-http/sets/vault-repo.d.ts +81 -0
- package/dist/credentialed-http/sets/vault-repo.js +147 -0
- package/dist/credentialed-http/tools/credential-copy-tool.d.ts +34 -0
- package/dist/credentialed-http/tools/credential-copy-tool.js +132 -0
- package/dist/credentialed-http/tools/credential-tool-host.d.ts +152 -0
- package/dist/credentialed-http/tools/credential-tool-host.js +2 -0
- package/dist/credentialed-http/tools/credential-tool-operations.d.ts +370 -0
- package/dist/credentialed-http/tools/credential-tool-operations.js +2 -0
- package/dist/credentialed-http/tools/index.d.ts +7 -0
- package/dist/credentialed-http/tools/index.js +4 -0
- package/dist/credentialed-http/tools/tool-registrations.d.ts +55 -0
- package/dist/credentialed-http/tools/tool-registrations.js +729 -0
- package/package.json +34 -11
|
@@ -0,0 +1,889 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { nowIso as readNowIso } from "@jini-ai/core/primitives";
|
|
3
|
+
import { createSharedExternalMcpOAuth } from "./shared-sign-in.js";
|
|
4
|
+
/**
|
|
5
|
+
* @file Connects `@jini-ai/oauth`'s generic client to one external-MCP connection row.
|
|
6
|
+
*
|
|
7
|
+
* This is the ONLY module that knows both halves. `@jini-ai/oauth` knows nothing about MCP;
|
|
8
|
+
* the hosted store knows nothing about token endpoints; this file owns the join and nothing
|
|
9
|
+
* else. The host owns HTTP routes and binds federation separately.
|
|
10
|
+
*
|
|
11
|
+
* Callback routes reuse the connectors' public mount, XSS-safe page, origin-checked popup bridge,
|
|
12
|
+
* focus-regain fallback and per-IP limiters. Authorization grants, PKCE, exchange, refresh and
|
|
13
|
+
* expiry are owned by `@jini-ai/oauth` behind provider-agnostic descriptors.
|
|
14
|
+
*
|
|
15
|
+
* ## Connect-time failures are loud, fast and never retried
|
|
16
|
+
*
|
|
17
|
+
* A connect attempt is a FOREGROUND action with a human watching a spinner — the exact opposite of
|
|
18
|
+
* boot-time federation, which fails open precisely because nobody
|
|
19
|
+
* asked for that server at that moment. So every call here is bounded by a timeout and reports a
|
|
20
|
+
* specific failure; nothing loops. An authorization code is single-use and the first response may
|
|
21
|
+
* have been lost AFTER the provider redeemed it, so an automatic retry can burn a code that
|
|
22
|
+
* actually worked. The operator retries with one click; the machine does not retry at all.
|
|
23
|
+
*/
|
|
24
|
+
/** A human is watching. Long enough for a slow but working provider, short enough that a dead one is
|
|
25
|
+
* reported while the operator still has the tab open. */
|
|
26
|
+
const CONNECT_TIMEOUT_MS = 15_000;
|
|
27
|
+
/**
|
|
28
|
+
* How long a process may hold the cross-process refresh lease.
|
|
29
|
+
*
|
|
30
|
+
* Comfortably longer than {@link CONNECT_TIMEOUT_MS} so a legitimate in-flight refresh is never
|
|
31
|
+
* treated as abandoned, and short enough that a process killed mid-refresh frees the connection
|
|
32
|
+
* within a minute rather than until the next restart.
|
|
33
|
+
*/
|
|
34
|
+
const REFRESH_LEASE_MS = 45_000;
|
|
35
|
+
/**
|
|
36
|
+
* Attempts `setOAuthStatus`'s clear-token re-seal is given before it gives up.
|
|
37
|
+
*
|
|
38
|
+
* Small and fixed, no backoff: a keyring write that fails because its active key briefly could not
|
|
39
|
+
* be resolved usually succeeds on the very next try, so this exists to smooth over that blip rather
|
|
40
|
+
* than to ride out a sustained outage — a re-seal still failing after this many immediate retries is
|
|
41
|
+
* treated as a real, reportable failure, not something to keep retrying indefinitely.
|
|
42
|
+
*/
|
|
43
|
+
const CLEAR_TOKEN_RESEAL_ATTEMPTS = 3;
|
|
44
|
+
/** Bounded by the per-workspace server cap, so no explicit eviction policy is needed beyond
|
|
45
|
+
* overwriting a connection's own previous attempt. */
|
|
46
|
+
export function createDeviceAuthorizationStore() {
|
|
47
|
+
const byServerId = new Map();
|
|
48
|
+
return {
|
|
49
|
+
async put(serverId, authorization) {
|
|
50
|
+
byServerId.set(serverId, authorization);
|
|
51
|
+
},
|
|
52
|
+
async get(serverId) {
|
|
53
|
+
return byServerId.get(serverId);
|
|
54
|
+
},
|
|
55
|
+
async delete(serverId) {
|
|
56
|
+
byServerId.delete(serverId);
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
/** Stable registration identity; callback URLs come only from the host's trusted origin policy.
|
|
61
|
+
* Device-only clients deliberately register no redirect URI (RFC 7591).
|
|
62
|
+
*/
|
|
63
|
+
function oauthClientOptions(ports, record, redirectUri) {
|
|
64
|
+
return { clientDisplayName: ports.registrationIdentity.clientName(record), softwareId: ports.registrationIdentity.softwareId,
|
|
65
|
+
redirectUris: redirectUri === undefined ? [] : [redirectUri] };
|
|
66
|
+
}
|
|
67
|
+
/** Calls {@link ExternalMcpOAuthDeps.onConnected}, keeping its failure out of the sign-in's result. */
|
|
68
|
+
async function notifyConnected(deps, serverId) {
|
|
69
|
+
if (!deps.onConnected)
|
|
70
|
+
return;
|
|
71
|
+
try {
|
|
72
|
+
await deps.onConnected(serverId);
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
deps.ports.log.postConnectFailed({ serverId, error });
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/** Loads an OAuth-authenticated row, or explains why it cannot be used.
|
|
79
|
+
* @throws {ExternalMcpValidationError} */
|
|
80
|
+
async function requireOAuthRecord(deps, serverId) {
|
|
81
|
+
const record = await deps.repo.findByServerId({ workspaceId: deps.workspaceId, serverId });
|
|
82
|
+
if (!record) {
|
|
83
|
+
throw deps.ports.errors.validation(`no external MCP server is configured as '${serverId}'`, "id");
|
|
84
|
+
}
|
|
85
|
+
if (deps.ports.projections.authMode(record) !== "oauth") {
|
|
86
|
+
throw deps.ports.errors.validation(`external MCP server '${serverId}' is not configured to use OAuth`, "authMode");
|
|
87
|
+
}
|
|
88
|
+
return record;
|
|
89
|
+
}
|
|
90
|
+
/** The refusal for a row that names no provider and no token endpoint. One builder for both places
|
|
91
|
+
* that reach it — provider resolution and self-configuration on a row with no URL to discover from —
|
|
92
|
+
* because from the operator's side it is the same problem with the same fix. */
|
|
93
|
+
function noOAuthProviderError(required) {
|
|
94
|
+
return required.ports.errors.oauth({ code: "OAUTH_INVALID_REQUEST", message: `external MCP server '${required.serverId}' names no OAuth provider and defines no token endpoint`, operatorAction: required.ports.copy.actions.noProvider, });
|
|
95
|
+
}
|
|
96
|
+
/** Reads the stored endpoints column, tolerating a null or corrupt value as "none typed". */
|
|
97
|
+
function readStoredEndpoints(record) {
|
|
98
|
+
try {
|
|
99
|
+
const parsed = JSON.parse(record.oauthEndpointsJson ?? "{}");
|
|
100
|
+
return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
return {};
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
/** Builds a descriptor from the endpoints an operator typed on this connection.
|
|
107
|
+
* @throws {OAuthError} When they do not form a usable provider. */
|
|
108
|
+
function buildConnectionOwnedProvider(deps, record, endpoints) {
|
|
109
|
+
const clientAuth = readStoredClientAuth(endpoints);
|
|
110
|
+
return deps.ports.flow.buildOperatorOAuthProvider({
|
|
111
|
+
guard: deps.httpPorts.guard,
|
|
112
|
+
providerId: record.oauthProviderId ?? `connection-${record.serverId}`,
|
|
113
|
+
label: record.label ?? record.serverId,
|
|
114
|
+
tokenEndpoint: endpoints.tokenEndpoint,
|
|
115
|
+
}, {
|
|
116
|
+
...(endpoints.authorizationEndpoint === undefined ? {} : { authorizationEndpoint: endpoints.authorizationEndpoint }),
|
|
117
|
+
...(endpoints.deviceAuthorizationEndpoint === undefined ? {} : { deviceAuthorizationEndpoint: endpoints.deviceAuthorizationEndpoint }),
|
|
118
|
+
scopes: readStoredScopes(record),
|
|
119
|
+
...(clientAuth === null ? {} : { clientAuth }),
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
/** The three RFC 6749 §2.3 methods `token-endpoint.ts` can actually perform. A stored value outside
|
|
123
|
+
* this set is treated as absent rather than trusted — the blob is plaintext on the row. */
|
|
124
|
+
const STORED_CLIENT_AUTH_METHODS = ["none", "client_secret_post", "client_secret_basic"];
|
|
125
|
+
/** @complexity O(1). */
|
|
126
|
+
function readStoredClientAuth(endpoints) {
|
|
127
|
+
const stored = endpoints.clientAuth;
|
|
128
|
+
return stored !== undefined && STORED_CLIENT_AUTH_METHODS.includes(stored) ? stored : null;
|
|
129
|
+
}
|
|
130
|
+
/** The scopes column, tolerating a null or corrupt value as "none requested". @complexity O(n). */
|
|
131
|
+
function readStoredScopes(record) {
|
|
132
|
+
try {
|
|
133
|
+
const parsed = JSON.parse(record.oauthScopesJson ?? "[]");
|
|
134
|
+
return Array.isArray(parsed) ? parsed.filter((scope) => typeof scope === "string") : [];
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
return [];
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Resolves the provider descriptor for a row: a registered id, or the operator's own endpoints.
|
|
142
|
+
*
|
|
143
|
+
* Both paths end at the same validated {@link OAuthProviderDescriptor}, which is what keeps every
|
|
144
|
+
* flow in `@jini-ai/oauth` provider-agnostic. `buildOperatorOAuthProvider` derives the supported grants
|
|
145
|
+
* from which endpoints are present, so a row cannot claim a grant it has no endpoint for.
|
|
146
|
+
*
|
|
147
|
+
* @throws {OAuthError} `OAUTH_INVALID_REQUEST` when the row names neither, or
|
|
148
|
+
* `OAUTH_UNSAFE_ENDPOINT` when a typed endpoint fails the outbound-safety check.
|
|
149
|
+
* @complexity O(1).
|
|
150
|
+
*/
|
|
151
|
+
function resolveProviderDescriptor(deps, record) {
|
|
152
|
+
const endpoints = readStoredEndpoints(record);
|
|
153
|
+
if (endpoints.tokenEndpoint !== undefined) {
|
|
154
|
+
return buildConnectionOwnedProvider(deps, record, { ...endpoints, tokenEndpoint: endpoints.tokenEndpoint });
|
|
155
|
+
}
|
|
156
|
+
if (record.oauthProviderId === null) {
|
|
157
|
+
throw noOAuthProviderError({ ports: deps.ports, serverId: record.serverId });
|
|
158
|
+
}
|
|
159
|
+
if (deps.lookupProvider)
|
|
160
|
+
return deps.lookupProvider(record.oauthProviderId);
|
|
161
|
+
return deps.providers.get({ providerId: record.oauthProviderId });
|
|
162
|
+
}
|
|
163
|
+
/** Builds the client identity for one row, unsealing the client secret only when there is one.
|
|
164
|
+
* @throws {OAuthError} When the row carries no client id — a state `saveExternalMcpServer` refuses
|
|
165
|
+
* to create, so reaching it means the row was written by something else. */
|
|
166
|
+
async function resolveClient(deps, record, provider) {
|
|
167
|
+
if (record.oauthClientId === null) {
|
|
168
|
+
throw deps.ports.errors.oauth({ code: "OAUTH_INVALID_REQUEST", message: `external MCP server '${record.serverId}' has no OAuth client id`, operatorAction: deps.ports.copy.actions.noClientId, });
|
|
169
|
+
}
|
|
170
|
+
const payload = await deps.ports.store.openPayload(deps.sealer, record);
|
|
171
|
+
return {
|
|
172
|
+
clientId: record.oauthClientId,
|
|
173
|
+
...(payload.clientSecret === undefined ? {} : { clientSecret: payload.clientSecret }),
|
|
174
|
+
authMethod: provider.clientAuth,
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
// ---------------------------------------------------------------------------
|
|
178
|
+
// Self-configuration: discovery + dynamic client registration
|
|
179
|
+
//
|
|
180
|
+
// A connection may reach `beginConnect` missing the two things every grant needs: where the
|
|
181
|
+
// authorization server is, and who the host is to it. Operators can configure both for a provider
|
|
182
|
+
// with a developer console. A growing share of hosted MCP servers have
|
|
183
|
+
// no console at all — they publish RFC 9728 / RFC 8414 metadata and an RFC 7591 registration endpoint
|
|
184
|
+
// and expect clients to self-register — and for those there is no human path to a client id, so the
|
|
185
|
+
// connection is unreachable without this.
|
|
186
|
+
//
|
|
187
|
+
// It runs ONLY in `beginConnect`, and what it learns is PERSISTED. The callback, poll and refresh
|
|
188
|
+
// paths read the persisted row, so there is one place where a connection can
|
|
189
|
+
// change shape rather than four. Persisting is also what keeps registration a once-per-connection
|
|
190
|
+
// event: an authorization server does not garbage-collect clients, so a connect that registered every
|
|
191
|
+
// time would leave one dead client behind per retry.
|
|
192
|
+
// ---------------------------------------------------------------------------
|
|
193
|
+
/** Whether a row still has to be told where its authorization server is. @complexity O(1). */
|
|
194
|
+
function needsEndpointDiscovery(record, endpoints) {
|
|
195
|
+
return endpoints.tokenEndpoint === undefined && record.oauthProviderId === null;
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Narrows a discovered authorization server into the blob shape the row stores.
|
|
199
|
+
*
|
|
200
|
+
* The `registration_endpoint` is deliberately NOT stored: nothing reads it once the client is minted,
|
|
201
|
+
* and a credential-adjacent URL kept for no reader is a liability rather than a convenience.
|
|
202
|
+
*
|
|
203
|
+
* @complexity O(1).
|
|
204
|
+
*/
|
|
205
|
+
function toStoredEndpoints(discovered) {
|
|
206
|
+
const server = discovered.server;
|
|
207
|
+
return {
|
|
208
|
+
issuer: server.issuer,
|
|
209
|
+
tokenEndpoint: server.tokenEndpoint,
|
|
210
|
+
...(discovered.resource == null ? {} : { resource: discovered.resource }),
|
|
211
|
+
...(server.authorizationEndpoint === null ? {} : { authorizationEndpoint: server.authorizationEndpoint }),
|
|
212
|
+
...(server.deviceAuthorizationEndpoint === null ? {} : { deviceAuthorizationEndpoint: server.deviceAuthorizationEndpoint }),
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Runs RFC 9728 / RFC 8414 discovery against the connection's own MCP endpoint.
|
|
217
|
+
*
|
|
218
|
+
* @throws {OAuthError} `OAUTH_INVALID_REQUEST` when the row has no URL to discover from — a stdio
|
|
219
|
+
* connection, which the store still requires to name its provider explicitly. Same message the
|
|
220
|
+
* non-discovering path has always used, because from the operator's side it is the same problem.
|
|
221
|
+
* @complexity O(1) in row size; a bounded, small number of outbound requests.
|
|
222
|
+
*/
|
|
223
|
+
async function discoverConnectionAuthorizationServer(deps, record) {
|
|
224
|
+
const resourceUrl = record.url;
|
|
225
|
+
if (resourceUrl === null) {
|
|
226
|
+
throw noOAuthProviderError({ ports: deps.ports, serverId: record.serverId });
|
|
227
|
+
}
|
|
228
|
+
return deps.ports.withCopy({ call: () => deps.ports.flow.discoverAuthorizationServer({ ...deps.httpPorts, resourceUrl }, { timeoutMs: 10_000, metadataPolicy: deps.ports.discoveryPolicy({ guard: deps.httpPorts.guard }) }) });
|
|
229
|
+
}
|
|
230
|
+
/** RFC 8628's grant-type identifier — how both RFC 8414's `grant_types_supported` and RFC 7591's own
|
|
231
|
+
* `grant_types` name the device flow. The internal grant alias is the shorter `device_code`
|
|
232
|
+
* (`EXTERNAL_MCP_OAUTH_GRANTS`), so this is the one place that URN gets spelled out — everywhere
|
|
233
|
+
* else compares against or registers the short name and translates through this constant instead of
|
|
234
|
+
* repeating the URN. */
|
|
235
|
+
const DEVICE_CODE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
|
|
236
|
+
/** The grant types to register for. Takes the RESOLVED grant rather than reading `record.oauthGrant`
|
|
237
|
+
* itself, because a row self-configuring its grant for the first time has not persisted it yet at
|
|
238
|
+
* the point registration runs — reading the record here would silently register for
|
|
239
|
+
* `authorization_code` on a connection that is actually about to become a device grant.
|
|
240
|
+
* `refresh_token` is always included: it is what decides whether this connection survives its first
|
|
241
|
+
* access-token expiry, and a server that does not support it ignores the entry. @complexity O(1). */
|
|
242
|
+
function registrationGrantTypes(grant) {
|
|
243
|
+
return grant === "device_code" ? [DEVICE_CODE_GRANT_TYPE, "refresh_token"] : ["authorization_code", "refresh_token"];
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Resolves the sign-in method for a connection whose row names none, from what its OWN
|
|
247
|
+
* authorization server advertises — the same "ask the server, don't ask the operator" move as
|
|
248
|
+
* {@link discoverConnectionAuthorizationServer} makes for endpoints and {@link mintClientForConnection}
|
|
249
|
+
* makes for client identity.
|
|
250
|
+
*
|
|
251
|
+
* `authorization_code` wins whenever the server offers it: it is the redirect-based grant every
|
|
252
|
+
* browser-capable client uses, and it is what an operator would pick by default anyway.
|
|
253
|
+
* `device_code` exists specifically for the flow a browser cannot run (RFC 8628 — the human types a
|
|
254
|
+
* code at the provider instead of being redirected), so it is a fallback rather than a co-equal
|
|
255
|
+
* choice, taken only when the server names no other grant this sign-in implements.
|
|
256
|
+
*
|
|
257
|
+
* @throws {OAuthError} `OAUTH_INVALID_REQUEST` when the metadata names neither grant this sign-in
|
|
258
|
+
* implements — naming exactly what the server DID advertise, since an operator who only sees
|
|
259
|
+
* "connect failed" has no way to guess that from the failure alone.
|
|
260
|
+
* @complexity O(n) in the number of advertised grant types.
|
|
261
|
+
*/
|
|
262
|
+
function resolveGrantFromDiscovery(grantTypesSupported, serverId, ports) {
|
|
263
|
+
if (grantTypesSupported.includes("authorization_code"))
|
|
264
|
+
return "authorization_code";
|
|
265
|
+
if (grantTypesSupported.includes(DEVICE_CODE_GRANT_TYPE))
|
|
266
|
+
return "device_code";
|
|
267
|
+
throw ports.errors.oauth({ code: "OAUTH_INVALID_REQUEST", message: ports.copy.noSupportedGrant({ serverId, offered: grantTypesSupported }), operatorAction: ports.copy.actions.chooseGrant });
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* Mints a client for a connection that has none.
|
|
271
|
+
*
|
|
272
|
+
* @param input.redirectUri - Registered as this client's only callback. A server that pins redirect
|
|
273
|
+
* URIs will refuse an authorization whose `redirect_uri` was not registered, so the value used at
|
|
274
|
+
* authorization time is the value registered here — not a re-derived one. `undefined` registers no
|
|
275
|
+
* callback at all, which is correct (and the only honest option) for a device-grant client.
|
|
276
|
+
* @param input.grant - The RESOLVED grant — see {@link registrationGrantTypes} for why this must not
|
|
277
|
+
* be read back off `record`.
|
|
278
|
+
* @throws {OAuthError} `OAUTH_INVALID_REQUEST` when the authorization server offers no registration
|
|
279
|
+
* endpoint, which is the point at which an operator genuinely does have to supply a client id.
|
|
280
|
+
* @complexity O(1) — one bounded outbound request.
|
|
281
|
+
*/
|
|
282
|
+
async function mintClientForConnection(deps, record, discovered, input) {
|
|
283
|
+
const registrationEndpoint = discovered.server.registrationEndpoint;
|
|
284
|
+
if (registrationEndpoint === null) {
|
|
285
|
+
throw deps.ports.errors.oauth({ code: "OAUTH_INVALID_REQUEST", message: `external MCP server '${record.serverId}' has no OAuth client id and its authorization server offers no dynamic client registration`, operatorAction: deps.ports.copy.actions.noRegistration });
|
|
286
|
+
}
|
|
287
|
+
return deps.ports.withCopy({ call: () => deps.ports.flow.registerOAuthClientDynamically({
|
|
288
|
+
...deps.httpPorts,
|
|
289
|
+
options: oauthClientOptions(deps.ports, record, input.redirectUri),
|
|
290
|
+
registrationEndpoint,
|
|
291
|
+
scopes: input.scopes,
|
|
292
|
+
}, {
|
|
293
|
+
messages: deps.ports.oauthMessages,
|
|
294
|
+
// Empty for a device-only client: RFC 7591 requires `redirect_uris` only for a client that
|
|
295
|
+
// registers a redirect-based grant, and `registrationGrantTypes` below registers none for
|
|
296
|
+
// `device_code`. Registering a placeholder instead would mint a client pinned to a callback
|
|
297
|
+
// nothing serves.
|
|
298
|
+
// oauthClientOptions carries exactly this grant's callback, or [] for device-only clients.
|
|
299
|
+
grantTypes: registrationGrantTypes(input.grant),
|
|
300
|
+
// Read only if the server issues a secret without saying how to present it.
|
|
301
|
+
authMethodsSupported: discovered.server.tokenEndpointAuthMethodsSupported,
|
|
302
|
+
timeoutMs: CONNECT_TIMEOUT_MS,
|
|
303
|
+
}) });
|
|
304
|
+
}
|
|
305
|
+
/** Writes one connect's self-configuration onto the row, preserving anything already sealed beside it.
|
|
306
|
+
*
|
|
307
|
+
* Read-modify-write for the same reason {@link persistTokens} is: sealing `{ clientSecret }` alone
|
|
308
|
+
* would delete a token the connection is still holding.
|
|
309
|
+
* @complexity O(1) — one unseal, one seal, one upsert. */
|
|
310
|
+
async function persistSelfConfiguration(deps, record, identity, options = {}) {
|
|
311
|
+
const existing = await deps.ports.store.openPayload(deps.sealer, record);
|
|
312
|
+
const clientSecret = identity.clientSecret === undefined ? existing.clientSecret : (identity.clientSecret ?? undefined);
|
|
313
|
+
const { sealedOAuth, oauthAadVersion } = await deps.ports.store.sealPayload(deps, record, {
|
|
314
|
+
...(clientSecret === undefined ? {} : { clientSecret }),
|
|
315
|
+
...(existing.tokens === undefined ? {} : { tokens: existing.tokens }),
|
|
316
|
+
});
|
|
317
|
+
const next = {
|
|
318
|
+
...record,
|
|
319
|
+
oauthGrant: identity.grant,
|
|
320
|
+
oauthClientId: identity.clientId,
|
|
321
|
+
oauthEndpointsJson: JSON.stringify(identity.endpoints),
|
|
322
|
+
oauthScopesJson: JSON.stringify(identity.scopes),
|
|
323
|
+
sealedOAuth,
|
|
324
|
+
// Carried from the seal, never from `...record` — the spread holds the row's OLD version.
|
|
325
|
+
oauthAadVersion,
|
|
326
|
+
updatedAt: readNowIso({ clock: deps.clock }),
|
|
327
|
+
};
|
|
328
|
+
if (!options.configurationOnly)
|
|
329
|
+
await deps.repo.upsert(next);
|
|
330
|
+
return next;
|
|
331
|
+
}
|
|
332
|
+
/**
|
|
333
|
+
* Fills in whatever a connection is missing, persists it, and returns the row as it now stands.
|
|
334
|
+
*
|
|
335
|
+
* A no-op — and, importantly, ZERO outbound requests — for a connection that already names its
|
|
336
|
+
* endpoints, its grant AND its client id. That is what keeps every existing connection behaving
|
|
337
|
+
* exactly as it did: self-configuration is reached only by a row that could not have connected at
|
|
338
|
+
* all before, or that named everything except which grant to use.
|
|
339
|
+
*
|
|
340
|
+
* Nothing is written until every step has succeeded, so a failed registration leaves the row exactly
|
|
341
|
+
* as it was and the operator's retry is a clean retry rather than one over half-written state.
|
|
342
|
+
*
|
|
343
|
+
* @param redirectUri - The absolute callback URL this connect will use, registered verbatim.
|
|
344
|
+
* @returns The row, self-configured if it needed to be.
|
|
345
|
+
* @throws {OAuthError} From discovery, grant resolution, or registration; every one is terminal and
|
|
346
|
+
* nothing is retried.
|
|
347
|
+
* @complexity O(1) in row size; a bounded, small number of outbound requests, and none at all on the
|
|
348
|
+
* already-configured path.
|
|
349
|
+
*/
|
|
350
|
+
async function selfConfigureConnection(deps, record, redirectUri, options = {}) {
|
|
351
|
+
const stored = readStoredEndpoints(record);
|
|
352
|
+
const mustDiscover = needsEndpointDiscovery(record, stored);
|
|
353
|
+
const mustResolveGrant = record.oauthGrant === null;
|
|
354
|
+
const keepClient = record.oauthClientId !== null && !isStaleSelfRegisteredClient(record, stored, redirectUri);
|
|
355
|
+
if (!mustDiscover && !mustResolveGrant && keepClient)
|
|
356
|
+
return record;
|
|
357
|
+
const discovered = await discoverConnectionAuthorizationServer(deps, record);
|
|
358
|
+
const discoveredEndpoints = toStoredEndpoints(discovered);
|
|
359
|
+
// Endpoints the operator typed win; discovery only fills the ones left blank (a typed token
|
|
360
|
+
// endpoint alone has no authorization endpoint to redirect to).
|
|
361
|
+
const endpoints = mustDiscover ? discoveredEndpoints : { ...discoveredEndpoints, ...stored, resource: discoveredEndpoints.resource ?? stored.resource };
|
|
362
|
+
const grant = selfConfiguredGrant({ record, discovered, ports: deps.ports });
|
|
363
|
+
const scopes = selfConfiguredScopes({ record, discovered });
|
|
364
|
+
// Narrowed on the field rather than on `mustRegister`, so there is no fallback that could write an
|
|
365
|
+
// empty client id if the two ever disagreed.
|
|
366
|
+
if (keepClient && record.oauthClientId !== null) {
|
|
367
|
+
return persistSelfConfiguration(deps, record, { endpoints, scopes, grant, clientId: record.oauthClientId, clientSecret: undefined }, options);
|
|
368
|
+
}
|
|
369
|
+
const minted = await mintClientForConnection(deps, record, discovered, { redirectUri, scopes, grant });
|
|
370
|
+
return persistSelfConfiguration(deps, record, {
|
|
371
|
+
endpoints: withMintedClient({ endpoints, minted, redirectUri }),
|
|
372
|
+
scopes,
|
|
373
|
+
grant,
|
|
374
|
+
clientId: minted.clientId,
|
|
375
|
+
clientSecret: minted.clientSecret,
|
|
376
|
+
}, options);
|
|
377
|
+
}
|
|
378
|
+
/**
|
|
379
|
+
* The grant a self-configuring connect uses. Resolved from the SAME discovery call that found the
|
|
380
|
+
* endpoints, on the same terms as those and the client id: an operator-named grant always wins, and
|
|
381
|
+
* only a row that left it blank asks the server what it actually supports rather than have
|
|
382
|
+
* `beginConnect` guess. The cast is safe: every non-null `oauthGrant` on a row was either validated by
|
|
383
|
+
* `assertOAuthGrant` at save time or written by a PRIOR call to this same resolver, so it is always one
|
|
384
|
+
* of `EXTERNAL_MCP_OAUTH_GRANTS` even though the column's declared type is a bare `string | null`.
|
|
385
|
+
* @throws {OAuthError} From {@link resolveGrantFromDiscovery}.
|
|
386
|
+
* @complexity O(n) in the number of advertised grant types.
|
|
387
|
+
*/
|
|
388
|
+
function selfConfiguredGrant(required) {
|
|
389
|
+
const { record, discovered } = required;
|
|
390
|
+
return record.oauthGrant === null ? resolveGrantFromDiscovery(discovered.server.grantTypesSupported, record.serverId, required.ports) : record.oauthGrant;
|
|
391
|
+
}
|
|
392
|
+
/**
|
|
393
|
+
* The scopes a self-configuring connect requests. Scopes the operator named win; an empty list adopts
|
|
394
|
+
* what the resource itself asks for, because a resource that advertises `offline_access` is naming
|
|
395
|
+
* the scope that decides whether this connection can ever refresh.
|
|
396
|
+
* @complexity O(n) in the number of scopes.
|
|
397
|
+
*/
|
|
398
|
+
function selfConfiguredScopes(required) {
|
|
399
|
+
const operatorScopes = readStoredScopes(required.record);
|
|
400
|
+
return operatorScopes.length > 0 ? operatorScopes : [...required.discovered.resourceScopes];
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* The endpoints blob for a freshly minted client: any previous self-registered client's marks
|
|
404
|
+
* dropped, then this client's own — its id, the callback it was registered with (none for a
|
|
405
|
+
* device-grant connect), and `clientAuth` only when the server issued a secret.
|
|
406
|
+
* @complexity O(1).
|
|
407
|
+
*/
|
|
408
|
+
function withMintedClient(required) {
|
|
409
|
+
const { endpoints, minted, redirectUri } = required;
|
|
410
|
+
return {
|
|
411
|
+
...withoutSelfRegisteredClient(endpoints),
|
|
412
|
+
...(minted.clientSecret === null ? {} : { clientAuth: minted.tokenEndpointAuthMethod }),
|
|
413
|
+
dynamicClientId: minted.clientId,
|
|
414
|
+
...(redirectUri === undefined ? {} : { registeredRedirectUri: redirectUri }),
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
/**
|
|
418
|
+
* Whether the row's client is one the host minted by dynamic registration, and so the host's to replace.
|
|
419
|
+
*
|
|
420
|
+
* A row written before {@link StoredOAuthEndpoints.dynamicClientId} existed carries no such mark.
|
|
421
|
+
* For those, a stored `clientAuth` stands in for it: that member is only ever written by dynamic
|
|
422
|
+
* registration. A pre-mark self-registered PUBLIC client (no secret, so no `clientAuth`) is not
|
|
423
|
+
* recognized, and keeps the old reuse-forever behavior until an operator clears it.
|
|
424
|
+
* @complexity O(1).
|
|
425
|
+
*/
|
|
426
|
+
function isSelfRegisteredClient(record, endpoints) {
|
|
427
|
+
if (record.oauthClientId === null)
|
|
428
|
+
return false;
|
|
429
|
+
if (endpoints.dynamicClientId !== undefined)
|
|
430
|
+
return endpoints.dynamicClientId === record.oauthClientId;
|
|
431
|
+
return endpoints.clientAuth !== undefined;
|
|
432
|
+
}
|
|
433
|
+
/**
|
|
434
|
+
* Whether a self-registered client must be replaced before this connect: it was registered for a
|
|
435
|
+
* different callback URL than this redirect-based connect will send (or, on a pre-mark row, for an
|
|
436
|
+
* unknown one). A device-grant connect sends no callback, so it never makes a client stale.
|
|
437
|
+
* @complexity O(1).
|
|
438
|
+
*/
|
|
439
|
+
function isStaleSelfRegisteredClient(record, endpoints, redirectUri) {
|
|
440
|
+
if (redirectUri === undefined || record.oauthGrant === "device_code")
|
|
441
|
+
return false;
|
|
442
|
+
return isSelfRegisteredClient(record, endpoints) && endpoints.registeredRedirectUri !== redirectUri;
|
|
443
|
+
}
|
|
444
|
+
/** The endpoints blob minus everything that describes a self-registered client. @complexity O(1). */
|
|
445
|
+
function withoutSelfRegisteredClient(endpoints) {
|
|
446
|
+
const next = { ...endpoints };
|
|
447
|
+
delete next.clientAuth;
|
|
448
|
+
delete next.dynamicClientId;
|
|
449
|
+
delete next.registeredRedirectUri;
|
|
450
|
+
return next;
|
|
451
|
+
}
|
|
452
|
+
/** Provider `error` codes that mean the client itself is refused (RFC 6749 §4.1.2.1 and §5.2), as
|
|
453
|
+
* opposed to the grant or the request. */
|
|
454
|
+
const CLIENT_REJECTED_PROVIDER_CODES = ["invalid_client", "unauthorized_client"];
|
|
455
|
+
/** The binding key an authorization `state` is issued against. Workspace-scoped so a state minted in
|
|
456
|
+
* one workspace cannot be redeemed in another, and server-scoped so it cannot be redeemed against a
|
|
457
|
+
* different connection in the same workspace. */
|
|
458
|
+
function ownerKeyOf(workspaceId, serverId) {
|
|
459
|
+
return `${workspaceId}:${serverId}`;
|
|
460
|
+
}
|
|
461
|
+
/** EXTRACT-S5 H3 (moved under `exactOptionalPropertyTypes`): an absent audience is omitted instead of passed as
|
|
462
|
+
* `undefined`; the OAuth operations treat both the same (`input.resource === undefined`). No I/O. */
|
|
463
|
+
function resourceOption(resource) {
|
|
464
|
+
return resource === undefined ? {} : { resource };
|
|
465
|
+
}
|
|
466
|
+
/** Thin site-key codec; Jini owns the expiring redirect payload and all binding checks.
|
|
467
|
+
* Stateless (no pending-store row) because the agent daemon can begin a connect that the web server
|
|
468
|
+
* completes in a different process; a process-local Map cannot join those two legs, and a sealed
|
|
469
|
+
* state needs no shared table. The exact redirect URI is bound into the state and replayed on
|
|
470
|
+
* exchange (RFC 6749 §4.1.3), never rebuilt from a callback Host header. Every open/expiry/binding
|
|
471
|
+
* failure is the same `OAUTH_INVALID_STATE`, so a guessed or tampered state is not an oracle.
|
|
472
|
+
* @complexity O(state bytes), bounded by Jini; one site-key seal/open, no pending-store I/O.
|
|
473
|
+
*/
|
|
474
|
+
function sealedRedirectState({ deps, serverId, browserBinding }, _optional = {}) {
|
|
475
|
+
// The HTTP callback always supplies browser proof. Unbound pre-upgrade links cannot decrypt
|
|
476
|
+
// there; persisted grants use their existing vault AAD and remain usable across reconnects.
|
|
477
|
+
const parts = browserBinding === undefined ? [deps.workspaceId, serverId] : [deps.workspaceId, serverId, browserBinding];
|
|
478
|
+
const aad = deps.ports.aad.format({ kind: "oauth-redirect-state", version: "v1", parts: [JSON.stringify(parts)] });
|
|
479
|
+
return deps.ports.flow.createSealedAuthorizationState({ clock: deps.clock, workspaceId: deps.workspaceId, serverId, codec: {
|
|
480
|
+
async seal({ plaintext }, _options = {}) {
|
|
481
|
+
const sealed = await deps.sealer.seal({ plaintext, key: await deps.keyring.activeKey({}), aad });
|
|
482
|
+
return Buffer.from(JSON.stringify(sealed), "utf8").toString("base64url");
|
|
483
|
+
},
|
|
484
|
+
async open({ state }, _options = {}) {
|
|
485
|
+
return deps.sealer.open({ sealed: JSON.parse(Buffer.from(state, "base64url").toString("utf8")) }, { aad });
|
|
486
|
+
},
|
|
487
|
+
} });
|
|
488
|
+
}
|
|
489
|
+
/** Writes a token set into the row: sealed blob (preserving the client secret) plus the PLAINTEXT
|
|
490
|
+
* status and expiry beside it. One place, so the plaintext metadata cannot drift from the blob.
|
|
491
|
+
* @complexity O(1) — one unseal, one seal, one upsert. */
|
|
492
|
+
async function persistTokens(deps, record, tokens) {
|
|
493
|
+
const existing = await deps.ports.store.openPayload(deps.sealer, record);
|
|
494
|
+
const { sealedOAuth, oauthAadVersion } = await deps.ports.store.sealPayload(deps, record, {
|
|
495
|
+
// Read-modify-write: sealing `{ tokens }` alone would silently delete the operator's client
|
|
496
|
+
// secret, and the next refresh would fail with a message about the provider rather than about us.
|
|
497
|
+
...(existing.clientSecret === undefined ? {} : { clientSecret: existing.clientSecret }),
|
|
498
|
+
tokens: {
|
|
499
|
+
accessToken: tokens.accessToken,
|
|
500
|
+
refreshToken: tokens.refreshToken,
|
|
501
|
+
tokenType: tokens.tokenType,
|
|
502
|
+
scopes: [...tokens.scopes],
|
|
503
|
+
expiresAt: tokens.expiresAt,
|
|
504
|
+
},
|
|
505
|
+
});
|
|
506
|
+
await deps.repo.upsert({
|
|
507
|
+
...record,
|
|
508
|
+
oauthStatus: "connected",
|
|
509
|
+
oauthExpiresAt: tokens.expiresAt,
|
|
510
|
+
oauthRefreshLeaseUntil: null,
|
|
511
|
+
sealedOAuth,
|
|
512
|
+
// Carried from the seal, never from `...record` — the spread holds the row's OLD version.
|
|
513
|
+
oauthAadVersion,
|
|
514
|
+
updatedAt: readNowIso({ clock: deps.clock }),
|
|
515
|
+
});
|
|
516
|
+
}
|
|
517
|
+
/**
|
|
518
|
+
* Resolves {@link setOAuthStatus}'s token-clear patch. Split out purely to keep that function's
|
|
519
|
+
* complexity under the shop ceiling — behavior is unchanged.
|
|
520
|
+
*
|
|
521
|
+
* Read-modify-write, the same rule `persistTokens` follows: `sealedOAuth` holds
|
|
522
|
+
* `{ clientSecret?, tokens? }` TOGETHER, so nulling it wholesale on a token clear would delete an
|
|
523
|
+
* operator's client secret along with the dead token. For a dynamically-registered (RFC 7591)
|
|
524
|
+
* client the operator never saw that secret, so losing it here means the row can never be
|
|
525
|
+
* re-authorized — only deleted and recreated.
|
|
526
|
+
*
|
|
527
|
+
* The open and the re-seal below are kept in SEPARATE try/catches on purpose, even though both can
|
|
528
|
+
* throw the same `ExternalMcpSecretStoreUnconfiguredError`
|
|
529
|
+
* (`openExternalMcpOAuthPayload`/`sealExternalMcpOAuthPayload`'s own `@throws`): they mean different
|
|
530
|
+
* things about whether the secret is actually lost. If OPEN fails, the blob could not be decrypted
|
|
531
|
+
* at all — a rotated site key or a corrupt row — so whatever it held is already unrecoverable, and
|
|
532
|
+
* falling back to the pre-existing wholesale-null behavior loses nothing that was not lost already
|
|
533
|
+
* (this is what keeps `markNeedsReauth`, `disconnect()`, and the device-poll terminal path from
|
|
534
|
+
* wedging on a blob that is already dead). If OPEN succeeds but the RE-SEAL fails, the secret was
|
|
535
|
+
* just read successfully — it is NOT lost, only the write-back (a transient keyring/active-key
|
|
536
|
+
* problem, say) failed, so it is retried a few times — bounded, no backoff — before giving up.
|
|
537
|
+
* Wholesale-nulling would destroy a secret this call proves is still recoverable, so it is never the
|
|
538
|
+
* outcome here; but silently leaving `sealedOAuth` untouched and reporting success would leave the
|
|
539
|
+
* row's `oauthStatus` claiming a state (e.g. `disconnected`) the stored blob does not actually match,
|
|
540
|
+
* with nothing to say so. So once the retry budget is exhausted, this rethrows instead: each of this
|
|
541
|
+
* function's callers already has a place that reacts to `ExternalMcpSecretStoreUnconfiguredError`
|
|
542
|
+
* without inventing a new one — `disconnect()`'s admin route already maps it to a 503
|
|
543
|
+
* `SECRET_STORE_UNCONFIGURED`, `reportAuthFailure` already carries an unexpected `setOAuthStatus`
|
|
544
|
+
* failure as `cause` on its terminal error, and `markNeedsReauth`'s two call sites in
|
|
545
|
+
* `token-refresh.ts`'s `performRefresh` treat this write as best-effort the same way — its failure
|
|
546
|
+
* is carried as `cause` on the `OAUTH_INVALID_GRANT` error they throw next, never left to propagate
|
|
547
|
+
* in that error's place. (An earlier version of this comment claimed that path "already folds" a
|
|
548
|
+
* write failure into the boot report; it did not — the failure escaped unguarded and displaced the
|
|
549
|
+
* reauth signal every downstream caller branches on. Both call sites now guard it explicitly.) Any
|
|
550
|
+
* OTHER error (a genuine bug, not an unopenable or unsealable blob) still propagates from either
|
|
551
|
+
* step — this is a documented, targeted degrade, not a blanket swallow.
|
|
552
|
+
*
|
|
553
|
+
* @throws {ExternalMcpSecretStoreUnconfiguredError} If the re-seal never recovers within
|
|
554
|
+
* {@link CLEAR_TOKEN_RESEAL_ATTEMPTS} attempts.
|
|
555
|
+
*/
|
|
556
|
+
async function resolveClearedTokenPatch(deps, record, options) {
|
|
557
|
+
if (options.clearToken !== true)
|
|
558
|
+
return {};
|
|
559
|
+
const opened = await openExistingOAuthPayloadForClear(deps, record);
|
|
560
|
+
if ("wholesale" in opened)
|
|
561
|
+
return { sealedOAuth: null, oauthExpiresAt: null };
|
|
562
|
+
const kept = options.dropClientSecret ? undefined : opened.existing.clientSecret;
|
|
563
|
+
const clientSecret = kept === undefined ? {} : { clientSecret: kept };
|
|
564
|
+
return resealClearedOAuthToken(deps, record, clientSecret);
|
|
565
|
+
}
|
|
566
|
+
/** {@link resolveClearedTokenPatch}'s OPEN step — reads the existing payload, or signals the
|
|
567
|
+
* wholesale-null fallback when the blob cannot be opened at all (see that function's doc for why
|
|
568
|
+
* this branch is safe). Split out purely to keep that function's cognitive complexity under the
|
|
569
|
+
* shop ceiling. */
|
|
570
|
+
async function openExistingOAuthPayloadForClear(deps, record) {
|
|
571
|
+
try {
|
|
572
|
+
return { existing: await deps.ports.store.openPayload(deps.sealer, record) };
|
|
573
|
+
}
|
|
574
|
+
catch (error) {
|
|
575
|
+
if (!deps.ports.errors.isUnconfigured(error))
|
|
576
|
+
throw error;
|
|
577
|
+
return { wholesale: true };
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
/** {@link resolveClearedTokenPatch}'s RE-SEAL step — retries a bounded number of times before giving
|
|
581
|
+
* up (see that function's doc for why). Split out purely to keep that function's cognitive
|
|
582
|
+
* complexity under the shop ceiling.
|
|
583
|
+
* @throws {ExternalMcpSecretStoreUnconfiguredError} If the re-seal never recovers within
|
|
584
|
+
* {@link CLEAR_TOKEN_RESEAL_ATTEMPTS} attempts. */
|
|
585
|
+
async function resealClearedOAuthToken(deps, record, clientSecret) {
|
|
586
|
+
for (let attempt = 1;; attempt += 1) {
|
|
587
|
+
try {
|
|
588
|
+
const cleared = await deps.ports.store.sealPayload(deps, record, clientSecret);
|
|
589
|
+
return { sealedOAuth: cleared.sealedOAuth, oauthExpiresAt: null, oauthAadVersion: cleared.oauthAadVersion };
|
|
590
|
+
}
|
|
591
|
+
catch (error) {
|
|
592
|
+
if (!deps.ports.errors.isUnconfigured(error))
|
|
593
|
+
throw error;
|
|
594
|
+
if (attempt >= CLEAR_TOKEN_RESEAL_ATTEMPTS)
|
|
595
|
+
throw error;
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
/** Moves a row into a terminal or reset OAuth state without touching anything else on it. See
|
|
600
|
+
* {@link resolveClearedTokenPatch} for the `clearToken` decision tree. */
|
|
601
|
+
async function setOAuthStatus(deps, serverId, status, options = {}) {
|
|
602
|
+
const record = await deps.repo.findByServerId({ workspaceId: deps.workspaceId, serverId });
|
|
603
|
+
if (!record)
|
|
604
|
+
return;
|
|
605
|
+
const endpoints = readStoredEndpoints(record);
|
|
606
|
+
const forgetClient = options.forgetSelfRegisteredClient === true && isSelfRegisteredClient(record, endpoints);
|
|
607
|
+
// The secret is only ever dropped together with the token (`clearToken`), never on its own.
|
|
608
|
+
const clearedTokenPatch = await resolveClearedTokenPatch(deps, record, { ...options, dropClientSecret: forgetClient });
|
|
609
|
+
await deps.repo.upsert({
|
|
610
|
+
...record,
|
|
611
|
+
oauthStatus: status,
|
|
612
|
+
...clearedTokenPatch,
|
|
613
|
+
...(forgetClient ? { oauthClientId: null, oauthEndpointsJson: JSON.stringify(withoutSelfRegisteredClient(endpoints)) } : {}),
|
|
614
|
+
oauthRefreshLeaseUntil: null,
|
|
615
|
+
updatedAt: readNowIso({ clock: deps.clock }),
|
|
616
|
+
});
|
|
617
|
+
}
|
|
618
|
+
/**
|
|
619
|
+
* Builds the OAuth service for one workspace.
|
|
620
|
+
*
|
|
621
|
+
* @returns The service plus its `tokenResolver`, which `readEnabledExternalMcpConfigs` takes.
|
|
622
|
+
* @complexity Construction is O(1) and performs no I/O.
|
|
623
|
+
* @tradeoffs The assistant daemon can start a redirect that the web server completes: encrypted
|
|
624
|
+
* state carries the verifier and connection binding across that split using the same site key.
|
|
625
|
+
* No pending row or shared process memory is needed. The provider's single-use code and the
|
|
626
|
+
* state's expiry prevent replay. Device authorization still uses the injected durable store;
|
|
627
|
+
* its in-memory adapter is only suitable when begin and poll run in the same process.
|
|
628
|
+
*/
|
|
629
|
+
export function createHostedMcpSignInService(required, _optional = {}) {
|
|
630
|
+
const deps = { ...required, providers: required.providers ?? required.ports.flow.createOAuthProviderRegistry({ guard: required.httpPorts.guard }) };
|
|
631
|
+
const refresher = deps.ports.flow.createTokenRefresher({
|
|
632
|
+
clock: deps.clock,
|
|
633
|
+
sleep: ({ ms }) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
634
|
+
port: {
|
|
635
|
+
async load({ key: serverId }) {
|
|
636
|
+
const record = await deps.repo.findByServerId({ workspaceId: deps.workspaceId, serverId });
|
|
637
|
+
if (!record)
|
|
638
|
+
return null;
|
|
639
|
+
// A row already parked in `needs_reauth` must not be probed again on every tool call: the
|
|
640
|
+
// state is durable and only a human clears it.
|
|
641
|
+
if (deps.ports.projections.oauthStatus(record) === "needs_reauth")
|
|
642
|
+
return null;
|
|
643
|
+
const payload = await deps.ports.store.openPayload(deps.sealer, record);
|
|
644
|
+
return payload.tokens === undefined
|
|
645
|
+
? null
|
|
646
|
+
: { ...payload.tokens, scopes: [...payload.tokens.scopes] };
|
|
647
|
+
},
|
|
648
|
+
async refresh({ key: serverId, refreshToken }) {
|
|
649
|
+
const record = await requireOAuthRecord(deps, serverId);
|
|
650
|
+
const provider = resolveProviderDescriptor(deps, record);
|
|
651
|
+
return deps.ports.withCopy({ call: async () => deps.ports.flow.refreshAccessToken({ ...deps.httpPorts, clock: deps.clock, tokenEndpoint: provider.tokenEndpoint,
|
|
652
|
+
client: await resolveClient(deps, record, provider), refreshToken }, { scopes: readStoredScopes(record), ...resourceOption(readStoredEndpoints(record).resource), timeoutMs: CONNECT_TIMEOUT_MS }) });
|
|
653
|
+
},
|
|
654
|
+
async persist({ key: serverId, tokens }) {
|
|
655
|
+
const record = await requireOAuthRecord(deps, serverId);
|
|
656
|
+
await persistTokens(deps, record, tokens);
|
|
657
|
+
},
|
|
658
|
+
async markNeedsReauth({ key: serverId }) {
|
|
659
|
+
// The token is CLEARED, not kept: it is known dead, and a dead credential sitting in the
|
|
660
|
+
// row is one accidental read away from being sent to a provider that will reject it.
|
|
661
|
+
await setOAuthStatus(deps, serverId, "needs_reauth", { clearToken: true });
|
|
662
|
+
},
|
|
663
|
+
async tryAcquireRefreshLease({ key: serverId }) {
|
|
664
|
+
const nowIso = readNowIso({ clock: deps.clock });
|
|
665
|
+
return deps.repo.tryClaimOAuthRefreshLease({
|
|
666
|
+
workspaceId: deps.workspaceId,
|
|
667
|
+
serverId,
|
|
668
|
+
nowIso,
|
|
669
|
+
leaseUntil: new Date(Date.parse(nowIso) + REFRESH_LEASE_MS).toISOString(),
|
|
670
|
+
});
|
|
671
|
+
},
|
|
672
|
+
async releaseRefreshLease({ key: serverId }) {
|
|
673
|
+
await deps.repo.releaseOAuthRefreshLease({ workspaceId: deps.workspaceId, serverId });
|
|
674
|
+
},
|
|
675
|
+
},
|
|
676
|
+
});
|
|
677
|
+
const shared = deps.shared ? createSharedExternalMcpOAuth({ deps, shared: deps.shared, ports: deps.ports, resolveProvider: record => resolveProviderDescriptor(deps, record), configure: async (input) => {
|
|
678
|
+
const record = await selfConfigureConnection(deps, await requireOAuthRecord(deps, input.serverId), input.redirectUri, { configurationOnly: true });
|
|
679
|
+
const provider = resolveProviderDescriptor(deps, record);
|
|
680
|
+
const endpoints = readStoredEndpoints(record);
|
|
681
|
+
return { record, provider, client: await resolveClient(deps, record, provider), scopes: readStoredScopes(record),
|
|
682
|
+
resource: endpoints.resource ?? record.url ?? undefined, issuer: endpoints.issuer };
|
|
683
|
+
} }) : undefined;
|
|
684
|
+
return {
|
|
685
|
+
...(shared ? { assertSharedAuthorized: shared.assertAuthorized, useSharedConnection: shared.useSaved, useLocalConnection: shared.useLocal, listSharedConnections: shared.list } : {}),
|
|
686
|
+
async beginConnect(input) {
|
|
687
|
+
if (input.destination === 'shared' && !shared)
|
|
688
|
+
throw deps.ports.errors.validation(deps.ports.copy.sharedLocalOnly, 'destination');
|
|
689
|
+
if (shared && (input.destination === 'shared' || await shared.hasBinding(input)))
|
|
690
|
+
return shared.beginConnect(input);
|
|
691
|
+
// Self-configuration first: a row that names no endpoints or no client id gets them here, once,
|
|
692
|
+
// and every step below then reads an ordinary fully-specified connection.
|
|
693
|
+
const record = await selfConfigureConnection(deps, await requireOAuthRecord(deps, input.serverId), input.redirectUri);
|
|
694
|
+
const provider = resolveProviderDescriptor(deps, record);
|
|
695
|
+
const client = await resolveClient(deps, record, provider);
|
|
696
|
+
const scopes = readStoredScopes(record);
|
|
697
|
+
// Keep the advertised audience across grants; the MCP URL need not be the resource id.
|
|
698
|
+
const resource = readStoredEndpoints(record).resource;
|
|
699
|
+
if (record.oauthGrant === "device_code") {
|
|
700
|
+
const authorization = await deps.ports.withCopy({ call: () => deps.ports.flow.beginDeviceAuthorization({ ...deps.httpPorts, provider, clock: deps.clock, client }, { scopes, ...resourceOption(resource), timeoutMs: CONNECT_TIMEOUT_MS }) });
|
|
701
|
+
await deps.devices.put(record.serverId, authorization);
|
|
702
|
+
await setOAuthStatus(deps, record.serverId, "pending");
|
|
703
|
+
return {
|
|
704
|
+
kind: "device_code",
|
|
705
|
+
userCode: authorization.userCode,
|
|
706
|
+
verificationUri: authorization.verificationUri,
|
|
707
|
+
verificationUriComplete: authorization.verificationUriComplete,
|
|
708
|
+
expiresAt: authorization.expiresAt,
|
|
709
|
+
intervalSeconds: authorization.intervalSeconds,
|
|
710
|
+
};
|
|
711
|
+
}
|
|
712
|
+
// Every path below this line is redirect-based, so the requirement is real rather than
|
|
713
|
+
// defensive — and it is stated where it can name both the grant and the fix, instead of being
|
|
714
|
+
// a blanket precondition a caller had to satisfy before it knew which grant it had.
|
|
715
|
+
const redirectUri = input.redirectUri;
|
|
716
|
+
if (redirectUri === undefined) {
|
|
717
|
+
throw deps.ports.errors.validation(deps.ports.copy.noPublicOrigin({ serverId: record.serverId }), "redirectUri");
|
|
718
|
+
}
|
|
719
|
+
// The authenticated GET sets the shared browser-binding cookie before revealing a provider
|
|
720
|
+
// URL. This also works when the daemon prepared the connection in another process.
|
|
721
|
+
if (input.delivery === 'hosted') {
|
|
722
|
+
await setOAuthStatus(deps, record.serverId, 'pending');
|
|
723
|
+
return {
|
|
724
|
+
kind: 'redirect_required',
|
|
725
|
+
authorizationUrl: deps.ports.signInLink({ callbackUrl: redirectUri, workspaceId: deps.workspaceId, serverId: record.serverId }),
|
|
726
|
+
expiresAt: new Date(deps.clock.nowMs() + 600_000).toISOString(),
|
|
727
|
+
};
|
|
728
|
+
}
|
|
729
|
+
const started = await deps.ports.withCopy({ call: () => deps.ports.flow.beginAuthorizationCode({ provider, stateless: sealedRedirectState({ deps, serverId: record.serverId, browserBinding: input.browserBinding }), guard: deps.httpPorts.guard,
|
|
730
|
+
randomBytesFn: ({ byteLength }) => randomBytes(byteLength),
|
|
731
|
+
options: oauthClientOptions(deps.ports, record, redirectUri),
|
|
732
|
+
ownerKey: ownerKeyOf(deps.workspaceId, record.serverId),
|
|
733
|
+
client,
|
|
734
|
+
redirectUri,
|
|
735
|
+
}, {
|
|
736
|
+
scopes,
|
|
737
|
+
...resourceOption(resource),
|
|
738
|
+
messages: deps.ports.oauthMessages,
|
|
739
|
+
}) });
|
|
740
|
+
await setOAuthStatus(deps, record.serverId, "pending");
|
|
741
|
+
return { kind: "redirect_required", authorizationUrl: started.authorizationUrl, expiresAt: started.expiresAt };
|
|
742
|
+
},
|
|
743
|
+
async completeAuthorizationCallback(input, _options = {}) {
|
|
744
|
+
if (shared && await shared.hasBinding(input)) {
|
|
745
|
+
await shared.completeAuthorizationCallback(input);
|
|
746
|
+
await notifyConnected(deps, input.serverId);
|
|
747
|
+
return;
|
|
748
|
+
}
|
|
749
|
+
const record = await requireOAuthRecord(deps, input.serverId);
|
|
750
|
+
const provider = resolveProviderDescriptor(deps, record);
|
|
751
|
+
const client = await resolveClient(deps, record, provider);
|
|
752
|
+
let tokens;
|
|
753
|
+
try {
|
|
754
|
+
tokens = await deps.ports.withCopy({ call: () => deps.ports.flow.completeAuthorizationCode({ ...deps.httpPorts, provider, stateless: sealedRedirectState({ deps, serverId: record.serverId, browserBinding: input.browserBinding }), clock: deps.clock,
|
|
755
|
+
redirectUri: input.redirectUri,
|
|
756
|
+
ownerKey: ownerKeyOf(deps.workspaceId, record.serverId),
|
|
757
|
+
client,
|
|
758
|
+
params: input.params,
|
|
759
|
+
}, {
|
|
760
|
+
timeoutMs: CONNECT_TIMEOUT_MS,
|
|
761
|
+
}) });
|
|
762
|
+
}
|
|
763
|
+
catch (error) {
|
|
764
|
+
// A provider that refuses the CLIENT (revoked, or never known) will refuse it on every retry,
|
|
765
|
+
// so a self-registered one is dropped and the next connect mints a fresh one. The provider's
|
|
766
|
+
// error still reaches the caller.
|
|
767
|
+
if (deps.ports.errors.isOAuthError(error) && CLIENT_REJECTED_PROVIDER_CODES.includes(error.providerErrorCode ?? "")) {
|
|
768
|
+
await setOAuthStatus(deps, record.serverId, "disconnected", { clearToken: true, forgetSelfRegisteredClient: true });
|
|
769
|
+
}
|
|
770
|
+
throw error;
|
|
771
|
+
}
|
|
772
|
+
// Re-read rather than reusing `record`: `beginConnect` wrote `pending` to it, and persisting a
|
|
773
|
+
// stale copy would resurrect the pre-connect row wholesale.
|
|
774
|
+
await persistTokens(deps, await requireOAuthRecord(deps, input.serverId), tokens);
|
|
775
|
+
await notifyConnected(deps, input.serverId);
|
|
776
|
+
},
|
|
777
|
+
async pollDeviceAuthorization(input) {
|
|
778
|
+
if (shared && await shared.hasBinding(input)) {
|
|
779
|
+
const result = await shared.pollDeviceAuthorization(input);
|
|
780
|
+
if (result.status === "connected")
|
|
781
|
+
await notifyConnected(deps, input.serverId);
|
|
782
|
+
return result;
|
|
783
|
+
}
|
|
784
|
+
const record = await requireOAuthRecord(deps, input.serverId);
|
|
785
|
+
const authorization = await deps.devices.get(input.serverId);
|
|
786
|
+
if (!authorization) {
|
|
787
|
+
throw deps.ports.errors.oauth({ code: "OAUTH_INVALID_STATE", message: `no device authorization is in progress for '${input.serverId}'`, operatorAction: deps.ports.copy.actions.restartDevice, });
|
|
788
|
+
}
|
|
789
|
+
const provider = resolveProviderDescriptor(deps, record);
|
|
790
|
+
const client = await resolveClient(deps, record, provider);
|
|
791
|
+
try {
|
|
792
|
+
const tokens = await deps.ports.withCopy({ call: () => deps.ports.flow.pollDeviceAuthorizationOnce({ ...deps.httpPorts, provider, clock: deps.clock,
|
|
793
|
+
client,
|
|
794
|
+
deviceCode: authorization.deviceCode,
|
|
795
|
+
expiresAt: authorization.expiresAt,
|
|
796
|
+
}, {
|
|
797
|
+
// The token request names the same audience the device start asked for (RFC 8707).
|
|
798
|
+
...resourceOption(readStoredEndpoints(record).resource),
|
|
799
|
+
timeoutMs: CONNECT_TIMEOUT_MS,
|
|
800
|
+
}) });
|
|
801
|
+
await deps.devices.delete(input.serverId);
|
|
802
|
+
await persistTokens(deps, record, tokens);
|
|
803
|
+
await notifyConnected(deps, input.serverId);
|
|
804
|
+
return { status: "connected" };
|
|
805
|
+
}
|
|
806
|
+
catch (error) {
|
|
807
|
+
// The ONLY retryable branch in this whole module — RFC 8628 §3.5 requires the client to keep
|
|
808
|
+
// polling on these two, and only these two.
|
|
809
|
+
if (deps.ports.errors.isOAuthError(error) && error.retryable) {
|
|
810
|
+
return { status: "pending", retryAfterSeconds: error.retryAfterSeconds ?? authorization.intervalSeconds };
|
|
811
|
+
}
|
|
812
|
+
await deps.devices.delete(input.serverId);
|
|
813
|
+
await setOAuthStatus(deps, input.serverId, "disconnected");
|
|
814
|
+
throw error;
|
|
815
|
+
}
|
|
816
|
+
},
|
|
817
|
+
async disconnect(input) {
|
|
818
|
+
if (shared && await shared.hasBinding(input)) {
|
|
819
|
+
await shared.disconnect(input);
|
|
820
|
+
return;
|
|
821
|
+
}
|
|
822
|
+
await deps.devices.delete(input.serverId);
|
|
823
|
+
// A self-registered client goes too, so a reconnect is a clean one: a client the vendor has
|
|
824
|
+
// since dropped would otherwise be reused forever. An operator-typed client is kept.
|
|
825
|
+
await setOAuthStatus(deps, input.serverId, "disconnected", { clearToken: true, forgetSelfRegisteredClient: true });
|
|
826
|
+
},
|
|
827
|
+
async reportAuthFailure(serverId, error) {
|
|
828
|
+
if (shared && await shared.hasBinding({ serverId })) {
|
|
829
|
+
await shared.markNeedsReauth({ serverId });
|
|
830
|
+
throw deps.ports.errors.reauthRequired({ serverId, cause: error });
|
|
831
|
+
}
|
|
832
|
+
const record = await deps.repo.findByServerId({ workspaceId: deps.workspaceId, serverId });
|
|
833
|
+
// A preset connection, a `static_env` row, or one already deleted has no reauth state this
|
|
834
|
+
// service owns — see `createExternalMcpConnectionGate`'s identical passthrough.
|
|
835
|
+
if (!record || deps.ports.projections.authMode(record) !== "oauth")
|
|
836
|
+
throw error;
|
|
837
|
+
// The state write is BEST EFFORT; the terminal error below is the guarantee. `setOAuthStatus`
|
|
838
|
+
// can still fail here — a row write that rejects, or a blob `openExternalMcpOAuthPayload`
|
|
839
|
+
// refuses for a reason that is NOT `ExternalMcpSecretStoreUnconfiguredError` (a payload written
|
|
840
|
+
// at a newer schema version, which `hydrateExternalMcpOAuthPayload` throws deliberately outside
|
|
841
|
+
// its own catch). Letting that escape would hand the caller an incidental error in place of the
|
|
842
|
+
// terminal one, and every consumer branches on the CLASS: the connection gate would not engage,
|
|
843
|
+
// the in-chat `external_mcp_reauth_prompt` surface would never render, and the "do not retry"
|
|
844
|
+
// sentence a model needs in order to stop hammering a dead connection would be gone — the
|
|
845
|
+
// failure mode that surface exists for. So the write's failure is carried out as `cause`
|
|
846
|
+
// instead of thrown in its place: nothing is silently swallowed, and nothing displaces the
|
|
847
|
+
// signal. A row left un-updated is recoverable on the next call; a lost signal is not.
|
|
848
|
+
let statusWriteFailure;
|
|
849
|
+
// Idempotent: a call that arrives after `tokenResolver` already discovered the same dead
|
|
850
|
+
// grant must not re-clear an already-cleared token or bump `updatedAt` needlessly.
|
|
851
|
+
if (deps.ports.projections.oauthStatus(record) !== "needs_reauth") {
|
|
852
|
+
try {
|
|
853
|
+
await setOAuthStatus(deps, serverId, "needs_reauth", { clearToken: true });
|
|
854
|
+
}
|
|
855
|
+
catch (writeError) {
|
|
856
|
+
statusWriteFailure = writeError;
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
throw deps.ports.errors.reauthRequired({
|
|
860
|
+
serverId,
|
|
861
|
+
label: record.label,
|
|
862
|
+
...(statusWriteFailure === undefined ? {} : { cause: statusWriteFailure }),
|
|
863
|
+
});
|
|
864
|
+
},
|
|
865
|
+
tokenResolver: {
|
|
866
|
+
...(shared ? { resolveSharedAccessToken: shared.getAccessToken } : {}),
|
|
867
|
+
async resolveAccessToken({ serverId }) {
|
|
868
|
+
const sharedToken = await shared?.getAccessToken({ serverId });
|
|
869
|
+
if (sharedToken !== undefined)
|
|
870
|
+
return sharedToken;
|
|
871
|
+
try {
|
|
872
|
+
return await refresher.getAccessToken({ key: serverId });
|
|
873
|
+
}
|
|
874
|
+
catch (error) {
|
|
875
|
+
// Whatever the refresher's own taxonomy says, the caller here is about to hand a message to
|
|
876
|
+
// a model, so a `needs_reauth` outcome is translated into the one non-retryable sentence
|
|
877
|
+
// that makes it stop. Anything else (a provider outage) keeps its own error, because it is
|
|
878
|
+
// NOT a durable state and must not be reported as one.
|
|
879
|
+
if (deps.ports.errors.isOAuthError(error) && error.code === "OAUTH_INVALID_GRANT") {
|
|
880
|
+
const record = await deps.repo.findByServerId({ workspaceId: deps.workspaceId, serverId });
|
|
881
|
+
throw deps.ports.errors.reauthRequired({ serverId, label: record?.label ?? null });
|
|
882
|
+
}
|
|
883
|
+
throw error;
|
|
884
|
+
}
|
|
885
|
+
},
|
|
886
|
+
},
|
|
887
|
+
};
|
|
888
|
+
}
|
|
889
|
+
//# sourceMappingURL=sign-in.js.map
|