@jini-ai/integrations 0.7.2 → 0.7.3-next.2

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.
Files changed (143) hide show
  1. package/CHANGELOG.md +2 -2
  2. package/README.md +1 -0
  3. package/dist/api-connections/access-token.js +4 -4
  4. package/dist/api-connections/account-actions.d.ts +10 -4
  5. package/dist/api-connections/account-actions.js +13 -13
  6. package/dist/api-connections/attempt-state.d.ts +11 -5
  7. package/dist/api-connections/attempt-state.js +4 -4
  8. package/dist/api-connections/authorization.d.ts +7 -3
  9. package/dist/api-connections/authorization.js +18 -18
  10. package/dist/api-connections/finish-authorization.d.ts +8 -4
  11. package/dist/api-connections/finish-authorization.js +9 -9
  12. package/dist/api-connections/host.d.ts +30 -32
  13. package/dist/api-connections/host.js +232 -205
  14. package/dist/api-connections/hosted-mcp/contracts.d.ts +1 -1
  15. package/dist/api-connections/hosted-mcp/oauth-row-writes.d.ts +50 -0
  16. package/dist/api-connections/hosted-mcp/oauth-row-writes.js +38 -0
  17. package/dist/api-connections/hosted-mcp/shared-sign-in.d.ts +40 -40
  18. package/dist/api-connections/hosted-mcp/shared-sign-in.js +98 -22
  19. package/dist/api-connections/hosted-mcp/sign-in-configuration.d.ts +29 -0
  20. package/dist/api-connections/hosted-mcp/sign-in-configuration.js +127 -0
  21. package/dist/api-connections/hosted-mcp/sign-in-discovery.d.ts +72 -0
  22. package/dist/api-connections/hosted-mcp/sign-in-discovery.js +131 -0
  23. package/dist/api-connections/hosted-mcp/sign-in-flow.d.ts +42 -0
  24. package/dist/api-connections/hosted-mcp/sign-in-flow.js +50 -0
  25. package/dist/api-connections/hosted-mcp/sign-in-provider.d.ts +103 -0
  26. package/dist/api-connections/hosted-mcp/sign-in-provider.js +142 -0
  27. package/dist/api-connections/hosted-mcp/sign-in-status.d.ts +19 -0
  28. package/dist/api-connections/hosted-mcp/sign-in-status.js +143 -0
  29. package/dist/api-connections/hosted-mcp/sign-in.d.ts +2 -9
  30. package/dist/api-connections/hosted-mcp/sign-in.js +219 -770
  31. package/dist/api-connections/index.js +1 -1
  32. package/dist/api-connections/install-credential.d.ts +4 -2
  33. package/dist/api-connections/install-credential.js +7 -7
  34. package/dist/api-connections/records.d.ts +17 -5
  35. package/dist/api-connections/records.js +5 -5
  36. package/dist/api-connections/request-checks.d.ts +29 -9
  37. package/dist/api-connections/request-checks.js +13 -13
  38. package/dist/api-connections/service.d.ts +1 -1
  39. package/dist/api-connections/service.js +6 -6
  40. package/dist/api-connections/status.d.ts +3 -1
  41. package/dist/api-connections/status.js +3 -3
  42. package/dist/api-connections/token-store/errors.d.ts +3 -1
  43. package/dist/api-connections/token-store/errors.js +1 -1
  44. package/dist/api-connections/token-store/vault-token-store.js +186 -173
  45. package/dist/args.d.ts +4 -1
  46. package/dist/args.js +1 -1
  47. package/dist/credentialed-http/credentialed-request.d.ts +5 -5
  48. package/dist/credentialed-http/credentialed-request.js +8 -8
  49. package/dist/credentialed-http/response-redaction.d.ts +18 -4
  50. package/dist/credentialed-http/response-redaction.js +7 -7
  51. package/dist/credentialed-http/sets/vault-repo.js +5 -1
  52. package/dist/credentialed-http/tools/credential-copy-tool.js +20 -15
  53. package/dist/credentialed-http/tools/tool-registrations.js +272 -249
  54. package/dist/media-providers/catalog.d.ts +1 -0
  55. package/dist/media-providers/catalog.js +1 -0
  56. package/dist/media-providers/dispatch/async-operation-store.d.ts +6 -4
  57. package/dist/media-providers/dispatch/async-operation-store.js +100 -88
  58. package/dist/media-providers/dispatch/context.js +1 -1
  59. package/dist/media-providers/dispatch/engine.d.ts +5 -1
  60. package/dist/media-providers/dispatch/engine.js +2 -2
  61. package/dist/media-providers/dispatch/index.d.ts +1 -1
  62. package/dist/media-providers/dispatch/index.js +1 -1
  63. package/dist/media-providers/dispatch/node.d.ts +1 -1
  64. package/dist/media-providers/dispatch/node.js +1 -1
  65. package/dist/media-providers/dispatch/openai-compatible.d.ts +50 -11
  66. package/dist/media-providers/dispatch/openai-compatible.js +21 -17
  67. package/dist/media-providers/dispatch/operation-runtime.js +18 -18
  68. package/dist/media-providers/dispatch/outbound.d.ts +2 -2
  69. package/dist/media-providers/dispatch/outbound.js +1 -1
  70. package/dist/media-providers/dispatch/polling-adapter.d.ts +1 -1
  71. package/dist/media-providers/dispatch/providers/aihubmix-shared.d.ts +20 -6
  72. package/dist/media-providers/dispatch/providers/aihubmix-shared.js +8 -8
  73. package/dist/media-providers/dispatch/providers/aihubmix.js +12 -12
  74. package/dist/media-providers/dispatch/providers/custom-image.js +4 -4
  75. package/dist/media-providers/dispatch/providers/fishaudio.js +2 -9
  76. package/dist/media-providers/dispatch/providers/grok.js +5 -19
  77. package/dist/media-providers/dispatch/providers/imagerouter-video-async.js +22 -20
  78. package/dist/media-providers/dispatch/providers/imagerouter.js +7 -21
  79. package/dist/media-providers/dispatch/providers/minimax.js +2 -9
  80. package/dist/media-providers/dispatch/providers/nanobanana.js +2 -2
  81. package/dist/media-providers/dispatch/providers/openai.js +6 -6
  82. package/dist/media-providers/dispatch/providers/openrouter.js +4 -4
  83. package/dist/media-providers/dispatch/providers/senseaudio.js +5 -19
  84. package/dist/media-providers/dispatch/providers/volcengine.js +5 -12
  85. package/dist/media-providers/dispatch/response-parsers.js +3 -3
  86. package/dist/media-providers/dispatch/sqlite-async-operation-store.d.ts +1 -1
  87. package/dist/media-providers/dispatch/sqlite-async-operation-store.js +31 -5
  88. package/dist/media-providers/dispatch/ssrf-guard.js +5 -12
  89. package/dist/media-providers/dispatch/stub.js +2 -2
  90. package/dist/media-providers/dispatch/vendor-adapter.js +2 -2
  91. package/dist/media-providers/image-model-ids.d.ts +36 -0
  92. package/dist/media-providers/image-model-ids.js +24 -0
  93. package/dist/media-providers/sqlite-driver.adapter.d.ts +1 -1
  94. package/dist/media-providers/sqlite-task-store.d.ts +2 -2
  95. package/dist/media-providers/sqlite-task-store.js +31 -4
  96. package/dist/media-providers/task-lifecycle.d.ts +17 -4
  97. package/dist/media-providers/task-lifecycle.js +4 -4
  98. package/dist/media-providers/task-store.js +28 -24
  99. package/dist/media-providers/ui-defaults.d.ts +7 -0
  100. package/dist/media-providers/ui-defaults.js +11 -17
  101. package/dist/saved-requests/types.d.ts +1 -1
  102. package/dist/webhooks/delivery.js +31 -27
  103. package/dist/webhooks/ports.d.ts +4 -1
  104. package/dist/webhooks/subscriptions.d.ts +7 -2
  105. package/dist/webhooks/subscriptions.js +30 -37
  106. package/dist/webhooks/tools/agent-tools.d.ts +82 -0
  107. package/dist/webhooks/tools/agent-tools.js +120 -0
  108. package/dist/webhooks/tools/index.d.ts +7 -0
  109. package/dist/webhooks/tools/index.js +5 -0
  110. package/dist/webhooks/tools/tool-handlers.d.ts +22 -0
  111. package/dist/webhooks/tools/tool-handlers.js +154 -0
  112. package/dist/webhooks/tools/tool-handlers.types.d.ts +64 -0
  113. package/dist/webhooks/tools/tool-handlers.types.js +2 -0
  114. package/dist/webhooks/tools/tool-registrations.d.ts +35 -0
  115. package/dist/webhooks/tools/tool-registrations.js +95 -0
  116. package/dist/webhooks/tools/tool-views.d.ts +62 -0
  117. package/dist/webhooks/tools/tool-views.js +50 -0
  118. package/dist/webhooks/types.d.ts +2 -0
  119. package/dist/webhooks/worker.d.ts +7 -4
  120. package/dist/webhooks/worker.js +22 -20
  121. package/package.json +17 -19
  122. package/dist/composio/bounded-data.d.ts +0 -36
  123. package/dist/composio/bounded-data.js +0 -181
  124. package/dist/composio/catalog.d.ts +0 -147
  125. package/dist/composio/catalog.js +0 -126
  126. package/dist/composio/composio-config.d.ts +0 -42
  127. package/dist/composio/composio-config.js +0 -145
  128. package/dist/composio/composio-descriptions.d.ts +0 -16
  129. package/dist/composio/composio-descriptions.js +0 -766
  130. package/dist/composio/composio.d.ts +0 -364
  131. package/dist/composio/composio.js +0 -1902
  132. package/dist/composio/errors.d.ts +0 -15
  133. package/dist/composio/errors.js +0 -16
  134. package/dist/composio/file-lock.d.ts +0 -13
  135. package/dist/composio/file-lock.js +0 -92
  136. package/dist/composio/index.d.ts +0 -18
  137. package/dist/composio/index.js +0 -7
  138. package/dist/composio/json-schema.d.ts +0 -93
  139. package/dist/composio/json-schema.js +0 -498
  140. package/dist/composio/output-protection.d.ts +0 -32
  141. package/dist/composio/output-protection.js +0 -105
  142. package/dist/composio/service.d.ts +0 -181
  143. package/dist/composio/service.js +0 -758
@@ -1,6 +1,10 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import { nowIso as readNowIso } from "@jini-ai/core/primitives";
3
3
  import { createSharedExternalMcpOAuth } from "./shared-sign-in.js";
4
+ import { oauthClientOptions, requireOAuthRecord, readStoredEndpoints, readStoredScopes, resolveProviderDescriptor, resolveClient } from "./sign-in-provider.js";
5
+ import { selfConfigureConnection } from "./sign-in-configuration.js";
6
+ import { persistTokens, setOAuthStatus } from "./sign-in-status.js";
7
+ import { CONNECT_TIMEOUT_MS, CLIENT_REJECTED_PROVIDER_CODES, ownerKeyOf, resourceOption, beginDeviceCodeConnect, sealedRedirectState } from "./sign-in-flow.js";
4
8
  /**
5
9
  * @file Connects `@jini-ai/oauth`'s generic client to one external-MCP connection row.
6
10
  *
@@ -21,9 +25,6 @@ import { createSharedExternalMcpOAuth } from "./shared-sign-in.js";
21
25
  * have been lost AFTER the provider redeemed it, so an automatic retry can burn a code that
22
26
  * actually worked. The operator retries with one click; the machine does not retry at all.
23
27
  */
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
  /**
28
29
  * How long a process may hold the cross-process refresh lease.
29
30
  *
@@ -32,15 +33,6 @@ const CONNECT_TIMEOUT_MS = 15_000;
32
33
  * within a minute rather than until the next restart.
33
34
  */
34
35
  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
36
  /** Bounded by the per-workspace server cap, so no explicit eviction policy is needed beyond
45
37
  * overwriting a connection's own previous attempt. */
46
38
  export function createDeviceAuthorizationStore() {
@@ -57,13 +49,6 @@ export function createDeviceAuthorizationStore() {
57
49
  },
58
50
  };
59
51
  }
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
52
  /** Calls {@link ExternalMcpOAuthDeps.onConnected}, keeping its failure out of the sign-in's result. */
68
53
  async function notifyConnected(deps, serverId) {
69
54
  if (!deps.onConnected)
@@ -75,560 +60,8 @@ async function notifyConnected(deps, serverId) {
75
60
  deps.ports.log.postConnectFailed({ serverId, error });
76
61
  }
77
62
  }
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({
63
+ function createConnectionTokenRefresher(deps) {
64
+ return deps.ports.flow.createTokenRefresher({
632
65
  clock: deps.clock,
633
66
  sleep: ({ ms }) => new Promise((resolve) => setTimeout(resolve, ms)),
634
67
  port: {
@@ -674,216 +107,232 @@ export function createHostedMcpSignInService(required, _optional = {}) {
674
107
  },
675
108
  },
676
109
  });
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 });
110
+ }
111
+ function createSharedConnectionService(deps) {
112
+ return deps.shared ? createSharedExternalMcpOAuth({ deps, shared: deps.shared, ports: deps.ports, resolveProvider: record => resolveProviderDescriptor(deps, record), configure: async (input) => {
113
+ const record = await selfConfigureConnection({ deps, record: await requireOAuthRecord(deps, input.serverId), redirectUri: input.redirectUri, options: { configurationOnly: true } });
679
114
  const provider = resolveProviderDescriptor(deps, record);
680
115
  const endpoints = readStoredEndpoints(record);
681
116
  return { record, provider, client: await resolveClient(deps, record, provider), scopes: readStoredScopes(record),
682
117
  resource: endpoints.resource ?? record.url ?? undefined, issuer: endpoints.issuer };
683
118
  } }) : 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);
119
+ }
120
+ async function beginConnectionAuthorization({ deps, shared }, input) {
121
+ if (input.destination === 'shared' && !shared)
122
+ throw deps.ports.errors.validation(deps.ports.copy.sharedLocalOnly, 'destination');
123
+ if (shared && (input.destination === 'shared' || await shared.hasBinding(input)))
124
+ return shared.beginConnect(input);
125
+ // Self-configuration first: a row that names no endpoints or no client id gets them here, once,
126
+ // and every step below then reads an ordinary fully-specified connection.
127
+ const record = await selfConfigureConnection({ deps, record: await requireOAuthRecord(deps, input.serverId), redirectUri: input.redirectUri });
128
+ const provider = resolveProviderDescriptor(deps, record);
129
+ const client = await resolveClient(deps, record, provider);
130
+ const scopes = readStoredScopes(record);
131
+ // Keep the advertised audience across grants; the MCP URL need not be the resource id.
132
+ const resource = readStoredEndpoints(record).resource;
133
+ if (record.oauthGrant === "device_code")
134
+ return beginDeviceCodeConnect({ deps, record, provider, client, scopes, resource });
135
+ // Every path below this line is redirect-based, so the requirement is real rather than
136
+ // defensive — and it is stated where it can name both the grant and the fix, instead of being
137
+ // a blanket precondition a caller had to satisfy before it knew which grant it had.
138
+ const redirectUri = input.redirectUri;
139
+ if (redirectUri === undefined) {
140
+ throw deps.ports.errors.validation(deps.ports.copy.noPublicOrigin({ serverId: record.serverId }), "redirectUri");
141
+ }
142
+ // The authenticated GET sets the shared browser-binding cookie before revealing a provider
143
+ // URL. This also works when the daemon prepared the connection in another process.
144
+ if (input.delivery === 'hosted') {
145
+ await setOAuthStatus(deps, record.serverId, 'pending');
146
+ return {
147
+ kind: 'redirect_required',
148
+ authorizationUrl: deps.ports.signInLink({ callbackUrl: redirectUri, workspaceId: deps.workspaceId, serverId: record.serverId }),
149
+ expiresAt: new Date(deps.clock.nowMs() + 600_000).toISOString(),
150
+ };
151
+ }
152
+ 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,
153
+ randomBytesFn: ({ byteLength }) => randomBytes(byteLength),
154
+ options: oauthClientOptions(deps.ports, record, redirectUri),
155
+ ownerKey: ownerKeyOf(deps.workspaceId, record.serverId),
156
+ client,
157
+ redirectUri,
158
+ }, {
159
+ scopes,
160
+ ...resourceOption(resource),
161
+ messages: deps.ports.oauthMessages,
162
+ }) });
163
+ await setOAuthStatus(deps, record.serverId, "pending");
164
+ return { kind: "redirect_required", authorizationUrl: started.authorizationUrl, expiresAt: started.expiresAt };
165
+ }
166
+ async function completeConnectionAuthorization({ deps, shared }, input, _options = {}) {
167
+ if (shared && await shared.hasBinding(input)) {
168
+ await shared.completeAuthorizationCallback(input);
169
+ await notifyConnected(deps, input.serverId);
170
+ return;
171
+ }
172
+ const record = await requireOAuthRecord(deps, input.serverId);
173
+ const provider = resolveProviderDescriptor(deps, record);
174
+ const client = await resolveClient(deps, record, provider);
175
+ let tokens;
176
+ try {
177
+ 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,
178
+ redirectUri: input.redirectUri,
179
+ ownerKey: ownerKeyOf(deps.workspaceId, record.serverId),
180
+ client,
181
+ params: input.params,
182
+ }, {
183
+ timeoutMs: CONNECT_TIMEOUT_MS,
184
+ }) });
185
+ }
186
+ catch (error) {
187
+ // A provider that refuses the CLIENT (revoked, or never known) will refuse it on every retry,
188
+ // so a self-registered one is dropped and the next connect mints a fresh one. The provider's
189
+ // error still reaches the caller.
190
+ if (deps.ports.errors.isOAuthError(error) && CLIENT_REJECTED_PROVIDER_CODES.includes(error.providerErrorCode ?? "")) {
191
+ await setOAuthStatus(deps, record.serverId, "disconnected", { clearToken: true, forgetSelfRegisteredClient: true });
192
+ }
193
+ throw error;
194
+ }
195
+ // Re-read rather than reusing `record`: `beginConnect` wrote `pending` to it, and persisting a
196
+ // stale copy would resurrect the pre-connect row wholesale.
197
+ await persistTokens(deps, await requireOAuthRecord(deps, input.serverId), tokens);
198
+ await notifyConnected(deps, input.serverId);
199
+ }
200
+ async function pollConnectionAuthorization({ deps, shared }, input) {
201
+ if (shared && await shared.hasBinding(input)) {
202
+ const result = await shared.pollDeviceAuthorization(input);
203
+ if (result.status === "connected")
775
204
  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);
205
+ return result;
206
+ }
207
+ const record = await requireOAuthRecord(deps, input.serverId);
208
+ const authorization = await deps.devices.get(input.serverId);
209
+ if (!authorization) {
210
+ 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, });
211
+ }
212
+ const provider = resolveProviderDescriptor(deps, record);
213
+ const client = await resolveClient(deps, record, provider);
214
+ try {
215
+ const tokens = await deps.ports.withCopy({ call: () => deps.ports.flow.pollDeviceAuthorizationOnce({ ...deps.httpPorts, provider, clock: deps.clock,
216
+ client,
217
+ deviceCode: authorization.deviceCode,
218
+ expiresAt: authorization.expiresAt,
219
+ }, {
220
+ // The token request names the same audience the device start asked for (RFC 8707).
221
+ ...resourceOption(readStoredEndpoints(record).resource),
222
+ timeoutMs: CONNECT_TIMEOUT_MS,
223
+ }) });
224
+ await deps.devices.delete(input.serverId);
225
+ await persistTokens(deps, record, tokens);
226
+ await notifyConnected(deps, input.serverId);
227
+ return { status: "connected" };
228
+ }
229
+ catch (error) {
230
+ // The ONLY retryable branch in this whole module — RFC 8628 §3.5 requires the client to keep
231
+ // polling on these two, and only these two.
232
+ if (deps.ports.errors.isOAuthError(error) && error.retryable) {
233
+ return { status: "pending", retryAfterSeconds: error.retryAfterSeconds ?? authorization.intervalSeconds };
234
+ }
235
+ await deps.devices.delete(input.serverId);
236
+ await setOAuthStatus(deps, input.serverId, "disconnected");
237
+ throw error;
238
+ }
239
+ }
240
+ async function disconnectConnection({ deps, shared }, input) {
241
+ if (shared && await shared.hasBinding(input)) {
242
+ await shared.disconnect(input);
243
+ return;
244
+ }
245
+ await deps.devices.delete(input.serverId);
246
+ // A self-registered client goes too, so a reconnect is a clean one: a client the vendor has
247
+ // since dropped would otherwise be reused forever. An operator-typed client is kept.
248
+ await setOAuthStatus(deps, input.serverId, "disconnected", { clearToken: true, forgetSelfRegisteredClient: true });
249
+ }
250
+ async function reportConnectionAuthFailure({ deps, shared }, serverId, error) {
251
+ if (shared && await shared.hasBinding({ serverId })) {
252
+ await shared.markNeedsReauth({ serverId });
253
+ throw deps.ports.errors.reauthRequired({ serverId, cause: error });
254
+ }
255
+ const record = await deps.repo.findByServerId({ workspaceId: deps.workspaceId, serverId });
256
+ // A preset connection, a `static_env` row, or one already deleted has no reauth state this
257
+ // service owns — see `createExternalMcpConnectionGate`'s identical passthrough.
258
+ if (!record || deps.ports.projections.authMode(record) !== "oauth")
259
+ throw error;
260
+ // The state write is BEST EFFORT; the terminal error below is the guarantee. `setOAuthStatus`
261
+ // can still fail here — a row write that rejects, or a blob `openExternalMcpOAuthPayload`
262
+ // refuses for a reason that is NOT `ExternalMcpSecretStoreUnconfiguredError` (a payload written
263
+ // at a newer schema version, which `hydrateExternalMcpOAuthPayload` throws deliberately outside
264
+ // its own catch). Letting that escape would hand the caller an incidental error in place of the
265
+ // terminal one, and every consumer branches on the CLASS: the connection gate would not engage,
266
+ // the in-chat `external_mcp_reauth_prompt` surface would never render, and the "do not retry"
267
+ // sentence a model needs in order to stop hammering a dead connection would be gone — the
268
+ // failure mode that surface exists for. So the write's failure is carried out as `cause`
269
+ // instead of thrown in its place: nothing is silently swallowed, and nothing displaces the
270
+ // signal. A row left un-updated is recoverable on the next call; a lost signal is not.
271
+ let statusWriteFailure;
272
+ // Idempotent: a call that arrives after `tokenResolver` already discovered the same dead
273
+ // grant must not re-clear an already-cleared token or bump `updatedAt` needlessly.
274
+ if (deps.ports.projections.oauthStatus(record) !== "needs_reauth") {
275
+ try {
276
+ await setOAuthStatus(deps, serverId, "needs_reauth", { clearToken: true });
277
+ }
278
+ catch (writeError) {
279
+ statusWriteFailure = writeError;
280
+ }
281
+ }
282
+ throw deps.ports.errors.reauthRequired({
283
+ serverId,
284
+ label: record.label,
285
+ ...(statusWriteFailure === undefined ? {} : { cause: statusWriteFailure }),
286
+ });
287
+ }
288
+ function createConnectionTokenResolver({ deps, shared }, refresher) {
289
+ return {
290
+ ...(shared ? { resolveSharedAccessToken: shared.getAccessToken } : {}),
291
+ async resolveAccessToken({ serverId }) {
292
+ const sharedToken = await shared?.getAccessToken({ serverId });
293
+ if (sharedToken !== undefined)
294
+ return sharedToken;
791
295
  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" };
296
+ return await refresher.getAccessToken({ key: serverId });
805
297
  }
806
298
  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 };
299
+ // Whatever the refresher's own taxonomy says, the caller here is about to hand a message to
300
+ // a model, so a `needs_reauth` outcome is translated into the one non-retryable sentence
301
+ // that makes it stop. Anything else (a provider outage) keeps its own error, because it is
302
+ // NOT a durable state and must not be reported as one.
303
+ if (deps.ports.errors.isOAuthError(error) && error.code === "OAUTH_INVALID_GRANT") {
304
+ const record = await deps.repo.findByServerId({ workspaceId: deps.workspaceId, serverId });
305
+ throw deps.ports.errors.reauthRequired({ serverId, label: record?.label ?? null });
811
306
  }
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
307
  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
308
  }
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
309
  },
887
310
  };
888
311
  }
312
+ /**
313
+ * Builds the OAuth service for one workspace.
314
+ *
315
+ * @returns The service plus its `tokenResolver`, which `readEnabledExternalMcpConfigs` takes.
316
+ * @complexity Construction is O(1) and performs no I/O.
317
+ * @tradeoffs The assistant daemon can start a redirect that the web server completes: encrypted
318
+ * state carries the verifier and connection binding across that split using the same site key.
319
+ * No pending row or shared process memory is needed. The provider's single-use code and the
320
+ * state's expiry prevent replay. Device authorization still uses the injected durable store;
321
+ * its in-memory adapter is only suitable when begin and poll run in the same process.
322
+ */
323
+ export function createHostedMcpSignInService(required, _optional = {}) {
324
+ const deps = { ...required, providers: required.providers ?? required.ports.flow.createOAuthProviderRegistry({ guard: required.httpPorts.guard }) };
325
+ const refresher = createConnectionTokenRefresher(deps);
326
+ const shared = createSharedConnectionService(deps);
327
+ const context = { deps, shared };
328
+ return {
329
+ ...(shared ? { assertSharedAuthorized: shared.assertAuthorized, useSharedConnection: shared.useSaved, useLocalConnection: shared.useLocal, listSharedConnections: shared.list } : {}),
330
+ beginConnect: beginConnectionAuthorization.bind(null, context),
331
+ completeAuthorizationCallback: completeConnectionAuthorization.bind(null, context),
332
+ pollDeviceAuthorization: pollConnectionAuthorization.bind(null, context),
333
+ disconnect: disconnectConnection.bind(null, context),
334
+ reportAuthFailure: reportConnectionAuthFailure.bind(null, context),
335
+ tokenResolver: createConnectionTokenResolver(context, refresher),
336
+ };
337
+ }
889
338
  //# sourceMappingURL=sign-in.js.map