@jini-ai/integrations 0.7.1 → 0.7.3-next.1

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 (121) 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 +16 -18
@@ -0,0 +1,131 @@
1
+ import { noOAuthProviderError, oauthClientOptions } from "./sign-in-provider.js";
2
+ import { CONNECT_TIMEOUT_MS } from "./sign-in-flow.js";
3
+ // ---------------------------------------------------------------------------
4
+ // Self-configuration: discovery + dynamic client registration
5
+ //
6
+ // A connection may reach `beginConnect` missing the two things every grant needs: where the
7
+ // authorization server is, and who the host is to it. Operators can configure both for a provider
8
+ // with a developer console. A growing share of hosted MCP servers have
9
+ // no console at all — they publish RFC 9728 / RFC 8414 metadata and an RFC 7591 registration endpoint
10
+ // and expect clients to self-register — and for those there is no human path to a client id, so the
11
+ // connection is unreachable without this.
12
+ //
13
+ // It runs ONLY in `beginConnect`, and what it learns is PERSISTED. The callback, poll and refresh
14
+ // paths read the persisted row, so there is one place where a connection can
15
+ // change shape rather than four. Persisting is also what keeps registration a once-per-connection
16
+ // event: an authorization server does not garbage-collect clients, so a connect that registered every
17
+ // time would leave one dead client behind per retry.
18
+ // ---------------------------------------------------------------------------
19
+ /** Whether a row still has to be told where its authorization server is. @complexity O(1). */
20
+ export function needsEndpointDiscovery(record, endpoints) {
21
+ return endpoints.tokenEndpoint === undefined && record.oauthProviderId === null;
22
+ }
23
+ /**
24
+ * Narrows a discovered authorization server into the blob shape the row stores.
25
+ *
26
+ * The `registration_endpoint` is deliberately NOT stored: nothing reads it once the client is minted,
27
+ * and a credential-adjacent URL kept for no reader is a liability rather than a convenience.
28
+ *
29
+ * @complexity O(1).
30
+ */
31
+ export function toStoredEndpoints(discovered) {
32
+ const server = discovered.server;
33
+ return {
34
+ issuer: server.issuer,
35
+ tokenEndpoint: server.tokenEndpoint,
36
+ ...(discovered.resource == null ? {} : { resource: discovered.resource }),
37
+ ...(server.authorizationEndpoint === null ? {} : { authorizationEndpoint: server.authorizationEndpoint }),
38
+ ...(server.deviceAuthorizationEndpoint === null ? {} : { deviceAuthorizationEndpoint: server.deviceAuthorizationEndpoint }),
39
+ };
40
+ }
41
+ /**
42
+ * Runs RFC 9728 / RFC 8414 discovery against the connection's own MCP endpoint.
43
+ *
44
+ * @throws {OAuthError} `OAUTH_INVALID_REQUEST` when the row has no URL to discover from — a stdio
45
+ * connection, which the store still requires to name its provider explicitly. Same message the
46
+ * non-discovering path has always used, because from the operator's side it is the same problem.
47
+ * @complexity O(1) in row size; a bounded, small number of outbound requests.
48
+ */
49
+ export async function discoverConnectionAuthorizationServer(deps, record) {
50
+ const resourceUrl = record.url;
51
+ if (resourceUrl === null) {
52
+ throw noOAuthProviderError({ ports: deps.ports, serverId: record.serverId });
53
+ }
54
+ return deps.ports.withCopy({ call: () => deps.ports.flow.discoverAuthorizationServer({ ...deps.httpPorts, resourceUrl }, { timeoutMs: 10_000, metadataPolicy: deps.ports.discoveryPolicy({ guard: deps.httpPorts.guard }) }) });
55
+ }
56
+ /** RFC 8628's grant-type identifier — how both RFC 8414's `grant_types_supported` and RFC 7591's own
57
+ * `grant_types` name the device flow. The internal grant alias is the shorter `device_code`
58
+ * (`EXTERNAL_MCP_OAUTH_GRANTS`), so this is the one place that URN gets spelled out — everywhere
59
+ * else compares against or registers the short name and translates through this constant instead of
60
+ * repeating the URN. */
61
+ const DEVICE_CODE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
62
+ /** The grant types to register for. Takes the RESOLVED grant rather than reading `record.oauthGrant`
63
+ * itself, because a row self-configuring its grant for the first time has not persisted it yet at
64
+ * the point registration runs — reading the record here would silently register for
65
+ * `authorization_code` on a connection that is actually about to become a device grant.
66
+ * `refresh_token` is always included: it is what decides whether this connection survives its first
67
+ * access-token expiry, and a server that does not support it ignores the entry. @complexity O(1). */
68
+ function registrationGrantTypes(grant) {
69
+ return grant === "device_code" ? [DEVICE_CODE_GRANT_TYPE, "refresh_token"] : ["authorization_code", "refresh_token"];
70
+ }
71
+ /**
72
+ * Resolves the sign-in method for a connection whose row names none, from what its OWN
73
+ * authorization server advertises — the same "ask the server, don't ask the operator" move as
74
+ * {@link discoverConnectionAuthorizationServer} makes for endpoints and {@link mintClientForConnection}
75
+ * makes for client identity.
76
+ *
77
+ * `authorization_code` wins whenever the server offers it: it is the redirect-based grant every
78
+ * browser-capable client uses, and it is what an operator would pick by default anyway.
79
+ * `device_code` exists specifically for the flow a browser cannot run (RFC 8628 — the human types a
80
+ * code at the provider instead of being redirected), so it is a fallback rather than a co-equal
81
+ * choice, taken only when the server names no other grant this sign-in implements.
82
+ *
83
+ * @throws {OAuthError} `OAUTH_INVALID_REQUEST` when the metadata names neither grant this sign-in
84
+ * implements — naming exactly what the server DID advertise, since an operator who only sees
85
+ * "connect failed" has no way to guess that from the failure alone.
86
+ * @complexity O(n) in the number of advertised grant types.
87
+ */
88
+ export function resolveGrantFromDiscovery({ grantTypesSupported, serverId, ports }, _optional = {}) {
89
+ if (grantTypesSupported.includes("authorization_code"))
90
+ return "authorization_code";
91
+ if (grantTypesSupported.includes(DEVICE_CODE_GRANT_TYPE))
92
+ return "device_code";
93
+ throw ports.errors.oauth({ code: "OAUTH_INVALID_REQUEST", message: ports.copy.noSupportedGrant({ serverId, offered: grantTypesSupported }), operatorAction: ports.copy.actions.chooseGrant });
94
+ }
95
+ /**
96
+ * Mints a client for a connection that has none.
97
+ *
98
+ * @param input.redirectUri - Registered as this client's only callback. A server that pins redirect
99
+ * URIs will refuse an authorization whose `redirect_uri` was not registered, so the value used at
100
+ * authorization time is the value registered here — not a re-derived one. `undefined` registers no
101
+ * callback at all, which is correct (and the only honest option) for a device-grant client.
102
+ * @param input.grant - The RESOLVED grant — see {@link registrationGrantTypes} for why this must not
103
+ * be read back off `record`.
104
+ * @throws {OAuthError} `OAUTH_INVALID_REQUEST` when the authorization server offers no registration
105
+ * endpoint, which is the point at which an operator genuinely does have to supply a client id.
106
+ * @complexity O(1) — one bounded outbound request.
107
+ */
108
+ export async function mintClientForConnection({ deps, record, discovered, input }, _optional = {}) {
109
+ const registrationEndpoint = discovered.server.registrationEndpoint;
110
+ if (registrationEndpoint === null) {
111
+ 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 });
112
+ }
113
+ return deps.ports.withCopy({ call: () => deps.ports.flow.registerOAuthClientDynamically({
114
+ ...deps.httpPorts,
115
+ options: oauthClientOptions(deps.ports, record, input.redirectUri),
116
+ registrationEndpoint,
117
+ scopes: input.scopes,
118
+ }, {
119
+ messages: deps.ports.oauthMessages,
120
+ // Empty for a device-only client: RFC 7591 requires `redirect_uris` only for a client that
121
+ // registers a redirect-based grant, and `registrationGrantTypes` below registers none for
122
+ // `device_code`. Registering a placeholder instead would mint a client pinned to a callback
123
+ // nothing serves.
124
+ // oauthClientOptions carries exactly this grant's callback, or [] for device-only clients.
125
+ grantTypes: registrationGrantTypes(input.grant),
126
+ // Read only if the server issues a secret without saying how to present it.
127
+ authMethodsSupported: discovered.server.tokenEndpointAuthMethodsSupported,
128
+ timeoutMs: CONNECT_TIMEOUT_MS,
129
+ }) });
130
+ }
131
+ //# sourceMappingURL=sign-in-discovery.js.map
@@ -0,0 +1,42 @@
1
+ import type { UUID } from "@jini-ai/core/primitives";
2
+ import type { OAuthClient, OAuthProviderDescriptor } from "@jini-ai/core/contracts/oauth";
3
+ import type { ExternalMcpConnectStart, ExternalMcpServerRecord } from "@jini-ai/core/contracts/hosted-mcp";
4
+ import type { SignInDeps, ExternalMcpOAuthServiceDeps } from "./sign-in-provider.js";
5
+ /** A human is watching. Long enough for a slow but working provider, short enough that a dead one is
6
+ * reported while the operator still has the tab open. */
7
+ export declare const CONNECT_TIMEOUT_MS = 15000;
8
+ /** Provider `error` codes that mean the client itself is refused (RFC 6749 §4.1.2.1 and §5.2), as
9
+ * opposed to the grant or the request. */
10
+ export declare const CLIENT_REJECTED_PROVIDER_CODES: readonly string[];
11
+ /** The binding key an authorization `state` is issued against. Workspace-scoped so a state minted in
12
+ * one workspace cannot be redeemed in another, and server-scoped so it cannot be redeemed against a
13
+ * different connection in the same workspace. */
14
+ export declare function ownerKeyOf(workspaceId: UUID, serverId: string): string;
15
+ /** EXTRACT-S5 H3 (moved under `exactOptionalPropertyTypes`): an absent audience is omitted instead of passed as
16
+ * `undefined`; the OAuth operations treat both the same (`input.resource === undefined`). No I/O. */
17
+ export declare function resourceOption(resource: string | undefined): {
18
+ resource?: string;
19
+ };
20
+ /** Device-code grant: start the device authorization, park it for polling, and hand the user code back. */
21
+ export declare function beginDeviceCodeConnect({ deps, record, provider, client, scopes, resource }: {
22
+ deps: ExternalMcpOAuthServiceDeps;
23
+ record: ExternalMcpServerRecord;
24
+ provider: OAuthProviderDescriptor;
25
+ client: OAuthClient;
26
+ scopes: string[];
27
+ resource: string | undefined;
28
+ }): Promise<ExternalMcpConnectStart>;
29
+ /** Thin site-key codec; Jini owns the expiring redirect payload and all binding checks.
30
+ * Stateless (no pending-store row) because the agent daemon can begin a connect that the web server
31
+ * completes in a different process; a process-local Map cannot join those two legs, and a sealed
32
+ * state needs no shared table. The exact redirect URI is bound into the state and replayed on
33
+ * exchange (RFC 6749 §4.1.3), never rebuilt from a callback Host header. Every open/expiry/binding
34
+ * failure is the same `OAUTH_INVALID_STATE`, so a guessed or tampered state is not an oracle.
35
+ * @complexity O(state bytes), bounded by Jini; one site-key seal/open, no pending-store I/O.
36
+ */
37
+ export declare function sealedRedirectState({ deps, serverId, browserBinding }: {
38
+ deps: SignInDeps;
39
+ serverId: string;
40
+ browserBinding?: string | undefined;
41
+ }, _optional?: Record<string, never>): import("@jini-ai/oauth").SealedAuthorizationState;
42
+ //# sourceMappingURL=sign-in-flow.d.ts.map
@@ -0,0 +1,50 @@
1
+ import { setOAuthStatus } from "./sign-in-status.js";
2
+ /** A human is watching. Long enough for a slow but working provider, short enough that a dead one is
3
+ * reported while the operator still has the tab open. */
4
+ export const CONNECT_TIMEOUT_MS = 15_000;
5
+ /** Provider `error` codes that mean the client itself is refused (RFC 6749 §4.1.2.1 and §5.2), as
6
+ * opposed to the grant or the request. */
7
+ export const CLIENT_REJECTED_PROVIDER_CODES = ["invalid_client", "unauthorized_client"];
8
+ /** The binding key an authorization `state` is issued against. Workspace-scoped so a state minted in
9
+ * one workspace cannot be redeemed in another, and server-scoped so it cannot be redeemed against a
10
+ * different connection in the same workspace. */
11
+ export function ownerKeyOf(workspaceId, serverId) {
12
+ return `${workspaceId}:${serverId}`;
13
+ }
14
+ /** EXTRACT-S5 H3 (moved under `exactOptionalPropertyTypes`): an absent audience is omitted instead of passed as
15
+ * `undefined`; the OAuth operations treat both the same (`input.resource === undefined`). No I/O. */
16
+ export function resourceOption(resource) {
17
+ return resource === undefined ? {} : { resource };
18
+ }
19
+ /** Device-code grant: start the device authorization, park it for polling, and hand the user code back. */
20
+ export async function beginDeviceCodeConnect({ deps, record, provider, client, scopes, resource }) {
21
+ 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 }) });
22
+ await deps.devices.put(record.serverId, authorization);
23
+ await setOAuthStatus(deps, record.serverId, "pending");
24
+ const { userCode, verificationUri, verificationUriComplete, expiresAt, intervalSeconds } = authorization;
25
+ return { kind: "device_code", userCode, verificationUri, verificationUriComplete, expiresAt, intervalSeconds };
26
+ }
27
+ /** Thin site-key codec; Jini owns the expiring redirect payload and all binding checks.
28
+ * Stateless (no pending-store row) because the agent daemon can begin a connect that the web server
29
+ * completes in a different process; a process-local Map cannot join those two legs, and a sealed
30
+ * state needs no shared table. The exact redirect URI is bound into the state and replayed on
31
+ * exchange (RFC 6749 §4.1.3), never rebuilt from a callback Host header. Every open/expiry/binding
32
+ * failure is the same `OAUTH_INVALID_STATE`, so a guessed or tampered state is not an oracle.
33
+ * @complexity O(state bytes), bounded by Jini; one site-key seal/open, no pending-store I/O.
34
+ */
35
+ export function sealedRedirectState({ deps, serverId, browserBinding }, _optional = {}) {
36
+ // The HTTP callback always supplies browser proof. Unbound pre-upgrade links cannot decrypt
37
+ // there; persisted grants use their existing vault AAD and remain usable across reconnects.
38
+ const parts = browserBinding === undefined ? [deps.workspaceId, serverId] : [deps.workspaceId, serverId, browserBinding];
39
+ const aad = deps.ports.aad.format({ kind: "oauth-redirect-state", version: "v1", parts: [JSON.stringify(parts)] });
40
+ return deps.ports.flow.createSealedAuthorizationState({ clock: deps.clock, workspaceId: deps.workspaceId, serverId, codec: {
41
+ async seal({ plaintext }, _options = {}) {
42
+ const sealed = await deps.sealer.seal({ plaintext, key: await deps.keyring.activeKey({}), aad });
43
+ return Buffer.from(JSON.stringify(sealed), "utf8").toString("base64url");
44
+ },
45
+ async open({ state }, _options = {}) {
46
+ return deps.sealer.open({ sealed: JSON.parse(Buffer.from(state, "base64url").toString("utf8")) }, { aad });
47
+ },
48
+ } });
49
+ }
50
+ //# sourceMappingURL=sign-in-flow.js.map
@@ -0,0 +1,103 @@
1
+ import type { OAuthAppOptions, OAuthClient, OAuthProviderDescriptor, OAuthProviderRegistry } from "@jini-ai/core/contracts/oauth";
2
+ import type { ExternalMcpServerRecord } from "@jini-ai/core/contracts/hosted-mcp";
3
+ import type { ExternalMcpOAuthDeps as HostedMcpOAuthDeps, HostedMcpSignInPorts } from "./contracts.js";
4
+ import type { SharedExternalMcpOwner } from "./shared-sign-in.js";
5
+ /** {@link ExternalMcpOAuthDeps} as the service holds them: `providers` defaulted once at construction,
6
+ * so nothing downstream builds a second registry. */
7
+ /** The sign-in's whole input: the canonical deps plus the host's {@link HostedMcpSignInPorts}. */
8
+ export type SignInDeps = HostedMcpOAuthDeps<SharedExternalMcpOwner> & {
9
+ readonly ports: HostedMcpSignInPorts;
10
+ };
11
+ export type ExternalMcpOAuthServiceDeps = SignInDeps & {
12
+ readonly providers: OAuthProviderRegistry;
13
+ };
14
+ /** Stable registration identity; callback URLs come only from the host's trusted origin policy.
15
+ * Device-only clients deliberately register no redirect URI (RFC 7591).
16
+ */
17
+ export declare function oauthClientOptions(ports: HostedMcpSignInPorts, record: ExternalMcpServerRecord, redirectUri: string | undefined): OAuthAppOptions;
18
+ /** Loads an OAuth-authenticated row, or explains why it cannot be used.
19
+ * @throws {ExternalMcpValidationError} */
20
+ export declare function requireOAuthRecord(deps: SignInDeps, serverId: string): Promise<ExternalMcpServerRecord>;
21
+ /** The refusal for a row that names no provider and no token endpoint. One builder for both places
22
+ * that reach it — provider resolution and self-configuration on a row with no URL to discover from —
23
+ * because from the operator's side it is the same problem with the same fix. */
24
+ export declare function noOAuthProviderError(required: {
25
+ readonly ports: HostedMcpSignInPorts;
26
+ readonly serverId: string;
27
+ }): Error;
28
+ /** The endpoint trio an operator may type onto a connection, as stored. Absent members mean "this
29
+ * connection names a registered provider for that part instead", or — on a remote connection — that
30
+ * discovery has not run yet. */
31
+ export interface StoredOAuthEndpoints {
32
+ issuer?: string;
33
+ authorizationEndpoint?: string;
34
+ tokenEndpoint?: string;
35
+ deviceAuthorizationEndpoint?: string;
36
+ /** RFC 8707 audience advertised by the protected server; legacy rows omit it. */
37
+ resource?: string | undefined;
38
+ /**
39
+ * How the token endpoint expects this client to authenticate.
40
+ *
41
+ * Only ever written by dynamic client registration, and only when the authorization server
42
+ * volunteered a `client_secret` and asked for a secret-bearing method despite being asked for a
43
+ * public client. It is stored because {@link buildConnectionOwnedProvider} rebuilds the descriptor
44
+ * from this blob on every later call — a refresh six weeks from now has nothing else to read it
45
+ * from, and a client that keeps authenticating as `none` at a server that issued it a secret gets
46
+ * `invalid_client` on every token request.
47
+ */
48
+ clientAuth?: string;
49
+ /**
50
+ * The client id dynamic registration minted for this row. It marks the row's client as the host's own,
51
+ * which the host may replace; a client id an operator typed never matches it and is never replaced.
52
+ * Compared against the row's live `oauthClientId` rather than trusted as a flag, so an operator
53
+ * who later types a client id over a minted one keeps theirs.
54
+ */
55
+ dynamicClientId?: string;
56
+ /** The callback URL {@link dynamicClientId} was registered with. A server that pins redirect URIs
57
+ * rejects any other, and the desktop app's port changes on every restart. */
58
+ registeredRedirectUri?: string;
59
+ }
60
+ /** Reads the stored endpoints column, tolerating a null or corrupt value as "none typed". */
61
+ export declare function readStoredEndpoints(record: ExternalMcpServerRecord): StoredOAuthEndpoints;
62
+ /** The scopes column, tolerating a null or corrupt value as "none requested". @complexity O(n). */
63
+ export declare function readStoredScopes(record: ExternalMcpServerRecord): string[];
64
+ /**
65
+ * Resolves the provider descriptor for a row: a registered id, or the operator's own endpoints.
66
+ *
67
+ * Both paths end at the same validated {@link OAuthProviderDescriptor}, which is what keeps every
68
+ * flow in `@jini-ai/oauth` provider-agnostic. `buildOperatorOAuthProvider` derives the supported grants
69
+ * from which endpoints are present, so a row cannot claim a grant it has no endpoint for.
70
+ *
71
+ * @throws {OAuthError} `OAUTH_INVALID_REQUEST` when the row names neither, or
72
+ * `OAUTH_UNSAFE_ENDPOINT` when a typed endpoint fails the outbound-safety check.
73
+ * @complexity O(1).
74
+ */
75
+ export declare function resolveProviderDescriptor(deps: ExternalMcpOAuthServiceDeps, record: ExternalMcpServerRecord): OAuthProviderDescriptor;
76
+ /** Builds the client identity for one row, unsealing the client secret only when there is one.
77
+ * @throws {OAuthError} When the row carries no client id — a state `saveExternalMcpServer` refuses
78
+ * to create, so reaching it means the row was written by something else. */
79
+ export declare function resolveClient(deps: SignInDeps, record: ExternalMcpServerRecord, provider: OAuthProviderDescriptor): Promise<OAuthClient>;
80
+ /**
81
+ * Whether the row's client is one the host minted by dynamic registration, and so the host's to replace.
82
+ *
83
+ * A row written before {@link StoredOAuthEndpoints.dynamicClientId} existed carries no such mark.
84
+ * For those, a stored `clientAuth` stands in for it: that member is only ever written by dynamic
85
+ * registration. A pre-mark self-registered PUBLIC client (no secret, so no `clientAuth`) is not
86
+ * recognized, and keeps the old reuse-forever behavior until an operator clears it.
87
+ * @complexity O(1).
88
+ */
89
+ export declare function isSelfRegisteredClient(record: ExternalMcpServerRecord, endpoints: StoredOAuthEndpoints): boolean;
90
+ /**
91
+ * Whether a self-registered client must be replaced before this connect: it was registered for a
92
+ * different callback URL than this redirect-based connect will send (or, on a pre-mark row, for an
93
+ * unknown one). A device-grant connect sends no callback, so it never makes a client stale.
94
+ * @complexity O(1).
95
+ */
96
+ export declare function isStaleSelfRegisteredClient({ record, endpoints, redirectUri }: {
97
+ record: ExternalMcpServerRecord;
98
+ endpoints: StoredOAuthEndpoints;
99
+ redirectUri: string | undefined;
100
+ }, _optional?: {}): boolean;
101
+ /** The endpoints blob minus everything that describes a self-registered client. @complexity O(1). */
102
+ export declare function withoutSelfRegisteredClient(endpoints: StoredOAuthEndpoints): StoredOAuthEndpoints;
103
+ //# sourceMappingURL=sign-in-provider.d.ts.map
@@ -0,0 +1,142 @@
1
+ /** Stable registration identity; callback URLs come only from the host's trusted origin policy.
2
+ * Device-only clients deliberately register no redirect URI (RFC 7591).
3
+ */
4
+ export function oauthClientOptions(ports, record, redirectUri) {
5
+ return { clientDisplayName: ports.registrationIdentity.clientName(record), softwareId: ports.registrationIdentity.softwareId,
6
+ redirectUris: redirectUri === undefined ? [] : [redirectUri] };
7
+ }
8
+ /** Loads an OAuth-authenticated row, or explains why it cannot be used.
9
+ * @throws {ExternalMcpValidationError} */
10
+ export async function requireOAuthRecord(deps, serverId) {
11
+ const record = await deps.repo.findByServerId({ workspaceId: deps.workspaceId, serverId });
12
+ if (!record) {
13
+ throw deps.ports.errors.validation(`no external MCP server is configured as '${serverId}'`, "id");
14
+ }
15
+ if (deps.ports.projections.authMode(record) !== "oauth") {
16
+ throw deps.ports.errors.validation(`external MCP server '${serverId}' is not configured to use OAuth`, "authMode");
17
+ }
18
+ return record;
19
+ }
20
+ /** The refusal for a row that names no provider and no token endpoint. One builder for both places
21
+ * that reach it — provider resolution and self-configuration on a row with no URL to discover from —
22
+ * because from the operator's side it is the same problem with the same fix. */
23
+ export function noOAuthProviderError(required) {
24
+ 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, });
25
+ }
26
+ /** Reads the stored endpoints column, tolerating a null or corrupt value as "none typed". */
27
+ export function readStoredEndpoints(record) {
28
+ try {
29
+ const parsed = JSON.parse(record.oauthEndpointsJson ?? "{}");
30
+ return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
31
+ }
32
+ catch {
33
+ return {};
34
+ }
35
+ }
36
+ /** Builds a descriptor from the endpoints an operator typed on this connection.
37
+ * @throws {OAuthError} When they do not form a usable provider. */
38
+ function buildConnectionOwnedProvider(deps, record, endpoints) {
39
+ const clientAuth = readStoredClientAuth(endpoints);
40
+ return deps.ports.flow.buildOperatorOAuthProvider({
41
+ guard: deps.httpPorts.guard,
42
+ providerId: record.oauthProviderId ?? `connection-${record.serverId}`,
43
+ label: record.label ?? record.serverId,
44
+ tokenEndpoint: endpoints.tokenEndpoint,
45
+ }, {
46
+ ...(endpoints.authorizationEndpoint === undefined ? {} : { authorizationEndpoint: endpoints.authorizationEndpoint }),
47
+ ...(endpoints.deviceAuthorizationEndpoint === undefined ? {} : { deviceAuthorizationEndpoint: endpoints.deviceAuthorizationEndpoint }),
48
+ scopes: readStoredScopes(record),
49
+ ...(clientAuth === null ? {} : { clientAuth }),
50
+ });
51
+ }
52
+ /** The three RFC 6749 §2.3 methods `token-endpoint.ts` can actually perform. A stored value outside
53
+ * this set is treated as absent rather than trusted — the blob is plaintext on the row. */
54
+ const STORED_CLIENT_AUTH_METHODS = ["none", "client_secret_post", "client_secret_basic"];
55
+ /** @complexity O(1). */
56
+ function readStoredClientAuth(endpoints) {
57
+ const stored = endpoints.clientAuth;
58
+ return stored !== undefined && STORED_CLIENT_AUTH_METHODS.includes(stored) ? stored : null;
59
+ }
60
+ /** The scopes column, tolerating a null or corrupt value as "none requested". @complexity O(n). */
61
+ export function readStoredScopes(record) {
62
+ try {
63
+ const parsed = JSON.parse(record.oauthScopesJson ?? "[]");
64
+ return Array.isArray(parsed) ? parsed.filter((scope) => typeof scope === "string") : [];
65
+ }
66
+ catch {
67
+ return [];
68
+ }
69
+ }
70
+ /**
71
+ * Resolves the provider descriptor for a row: a registered id, or the operator's own endpoints.
72
+ *
73
+ * Both paths end at the same validated {@link OAuthProviderDescriptor}, which is what keeps every
74
+ * flow in `@jini-ai/oauth` provider-agnostic. `buildOperatorOAuthProvider` derives the supported grants
75
+ * from which endpoints are present, so a row cannot claim a grant it has no endpoint for.
76
+ *
77
+ * @throws {OAuthError} `OAUTH_INVALID_REQUEST` when the row names neither, or
78
+ * `OAUTH_UNSAFE_ENDPOINT` when a typed endpoint fails the outbound-safety check.
79
+ * @complexity O(1).
80
+ */
81
+ export function resolveProviderDescriptor(deps, record) {
82
+ const endpoints = readStoredEndpoints(record);
83
+ if (endpoints.tokenEndpoint !== undefined) {
84
+ return buildConnectionOwnedProvider(deps, record, { ...endpoints, tokenEndpoint: endpoints.tokenEndpoint });
85
+ }
86
+ if (record.oauthProviderId === null) {
87
+ throw noOAuthProviderError({ ports: deps.ports, serverId: record.serverId });
88
+ }
89
+ if (deps.lookupProvider)
90
+ return deps.lookupProvider(record.oauthProviderId);
91
+ return deps.providers.get({ providerId: record.oauthProviderId });
92
+ }
93
+ /** Builds the client identity for one row, unsealing the client secret only when there is one.
94
+ * @throws {OAuthError} When the row carries no client id — a state `saveExternalMcpServer` refuses
95
+ * to create, so reaching it means the row was written by something else. */
96
+ export async function resolveClient(deps, record, provider) {
97
+ if (record.oauthClientId === null) {
98
+ 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, });
99
+ }
100
+ const payload = await deps.ports.store.openPayload(deps.sealer, record);
101
+ return {
102
+ clientId: record.oauthClientId,
103
+ ...(payload.clientSecret === undefined ? {} : { clientSecret: payload.clientSecret }),
104
+ authMethod: provider.clientAuth,
105
+ };
106
+ }
107
+ /**
108
+ * Whether the row's client is one the host minted by dynamic registration, and so the host's to replace.
109
+ *
110
+ * A row written before {@link StoredOAuthEndpoints.dynamicClientId} existed carries no such mark.
111
+ * For those, a stored `clientAuth` stands in for it: that member is only ever written by dynamic
112
+ * registration. A pre-mark self-registered PUBLIC client (no secret, so no `clientAuth`) is not
113
+ * recognized, and keeps the old reuse-forever behavior until an operator clears it.
114
+ * @complexity O(1).
115
+ */
116
+ export function isSelfRegisteredClient(record, endpoints) {
117
+ if (record.oauthClientId === null)
118
+ return false;
119
+ if (endpoints.dynamicClientId !== undefined)
120
+ return endpoints.dynamicClientId === record.oauthClientId;
121
+ return endpoints.clientAuth !== undefined;
122
+ }
123
+ /**
124
+ * Whether a self-registered client must be replaced before this connect: it was registered for a
125
+ * different callback URL than this redirect-based connect will send (or, on a pre-mark row, for an
126
+ * unknown one). A device-grant connect sends no callback, so it never makes a client stale.
127
+ * @complexity O(1).
128
+ */
129
+ export function isStaleSelfRegisteredClient({ record, endpoints, redirectUri }, _optional = {}) {
130
+ if (redirectUri === undefined || record.oauthGrant === "device_code")
131
+ return false;
132
+ return isSelfRegisteredClient(record, endpoints) && endpoints.registeredRedirectUri !== redirectUri;
133
+ }
134
+ /** The endpoints blob minus everything that describes a self-registered client. @complexity O(1). */
135
+ export function withoutSelfRegisteredClient(endpoints) {
136
+ const next = { ...endpoints };
137
+ delete next.clientAuth;
138
+ delete next.dynamicClientId;
139
+ delete next.registeredRedirectUri;
140
+ return next;
141
+ }
142
+ //# sourceMappingURL=sign-in-provider.js.map
@@ -0,0 +1,19 @@
1
+ import type { OAuthTokenSet } from "@jini-ai/core/contracts/oauth";
2
+ import type { ExternalMcpOAuthStatus, ExternalMcpServerRecord } from "@jini-ai/core/contracts/hosted-mcp";
3
+ import { type SignInDeps } from "./sign-in-provider.js";
4
+ /** Writes a token set into the row: sealed blob (preserving the client secret) plus the PLAINTEXT
5
+ * status and expiry beside it. One place, so the plaintext metadata cannot drift from the blob.
6
+ * @complexity O(1) — one unseal, one seal, one runtime write. */
7
+ export declare function persistTokens(deps: SignInDeps, record: ExternalMcpServerRecord, tokens: OAuthTokenSet): Promise<void>;
8
+ /** {@link setOAuthStatus}'s options. `forgetSelfRegisteredClient` also drops a client the host minted by
9
+ * dynamic registration — its id and its sealed secret — so the next connect registers afresh. It
10
+ * leaves an operator-typed client alone (see {@link isSelfRegisteredClient}). */
11
+ interface SetOAuthStatusOptions {
12
+ readonly clearToken?: boolean;
13
+ readonly forgetSelfRegisteredClient?: boolean;
14
+ }
15
+ /** Moves a row into a terminal or reset OAuth state without touching anything else on it. See
16
+ * {@link resolveClearedTokenPatch} for the `clearToken` decision tree. */
17
+ export declare function setOAuthStatus(deps: SignInDeps, serverId: string, status: ExternalMcpOAuthStatus, options?: SetOAuthStatusOptions): Promise<void>;
18
+ export {};
19
+ //# sourceMappingURL=sign-in-status.d.ts.map
@@ -0,0 +1,143 @@
1
+ import { nowIso as readNowIso } from "@jini-ai/core/primitives";
2
+ import { runtimePatchOf, updateRowOnce, writeOAuthRuntime } from "./oauth-row-writes.js";
3
+ import { readStoredEndpoints, isSelfRegisteredClient, withoutSelfRegisteredClient } from "./sign-in-provider.js";
4
+ /**
5
+ * Attempts `setOAuthStatus`'s clear-token re-seal is given before it gives up.
6
+ *
7
+ * Small and fixed, no backoff: a keyring write that fails because its active key briefly could not
8
+ * be resolved usually succeeds on the very next try, so this exists to smooth over that blip rather
9
+ * than to ride out a sustained outage — a re-seal still failing after this many immediate retries is
10
+ * treated as a real, reportable failure, not something to keep retrying indefinitely.
11
+ */
12
+ const CLEAR_TOKEN_RESEAL_ATTEMPTS = 3;
13
+ /** Writes a token set into the row: sealed blob (preserving the client secret) plus the PLAINTEXT
14
+ * status and expiry beside it. One place, so the plaintext metadata cannot drift from the blob.
15
+ * @complexity O(1) — one unseal, one seal, one runtime write. */
16
+ export async function persistTokens(deps, record, tokens) {
17
+ const existing = await deps.ports.store.openPayload(deps.sealer, record);
18
+ const { sealedOAuth, oauthAadVersion } = await deps.ports.store.sealPayload(deps, record, {
19
+ // Read-modify-write: sealing `{ tokens }` alone would silently delete the operator's client
20
+ // secret, and the next refresh would fail with a message about the provider rather than about us.
21
+ ...(existing.clientSecret === undefined ? {} : { clientSecret: existing.clientSecret }),
22
+ tokens: {
23
+ accessToken: tokens.accessToken,
24
+ refreshToken: tokens.refreshToken,
25
+ tokenType: tokens.tokenType,
26
+ scopes: [...tokens.scopes],
27
+ expiresAt: tokens.expiresAt,
28
+ },
29
+ });
30
+ // Runtime write: only the token columns, fenced on the credential read above (see oauth-row-writes.ts).
31
+ // `oauthAadVersion` is carried from the seal, never from `record` — it holds the row's OLD version.
32
+ await writeOAuthRuntime({ repo: deps.repo, ports: deps.ports, record, patch: { oauthStatus: "connected",
33
+ oauthExpiresAt: tokens.expiresAt, oauthRefreshLeaseUntil: null, sealedOAuth, oauthAadVersion, updatedAt: readNowIso({ clock: deps.clock }) } });
34
+ }
35
+ /**
36
+ * Resolves {@link setOAuthStatus}'s token-clear patch. Split out purely to keep that function's
37
+ * complexity under the shop ceiling — behavior is unchanged.
38
+ *
39
+ * Read-modify-write, the same rule `persistTokens` follows: `sealedOAuth` holds
40
+ * `{ clientSecret?, tokens? }` TOGETHER, so nulling it wholesale on a token clear would delete an
41
+ * operator's client secret along with the dead token. For a dynamically-registered (RFC 7591)
42
+ * client the operator never saw that secret, so losing it here means the row can never be
43
+ * re-authorized — only deleted and recreated.
44
+ *
45
+ * The open and the re-seal below are kept in SEPARATE try/catches on purpose, even though both can
46
+ * throw the same `ExternalMcpSecretStoreUnconfiguredError`
47
+ * (`openExternalMcpOAuthPayload`/`sealExternalMcpOAuthPayload`'s own `@throws`): they mean different
48
+ * things about whether the secret is actually lost. If OPEN fails, the blob could not be decrypted
49
+ * at all — a rotated site key or a corrupt row — so whatever it held is already unrecoverable, and
50
+ * falling back to the pre-existing wholesale-null behavior loses nothing that was not lost already
51
+ * (this is what keeps `markNeedsReauth`, `disconnect()`, and the device-poll terminal path from
52
+ * wedging on a blob that is already dead). If OPEN succeeds but the RE-SEAL fails, the secret was
53
+ * just read successfully — it is NOT lost, only the write-back (a transient keyring/active-key
54
+ * problem, say) failed, so it is retried a few times — bounded, no backoff — before giving up.
55
+ * Wholesale-nulling would destroy a secret this call proves is still recoverable, so it is never the
56
+ * outcome here; but silently leaving `sealedOAuth` untouched and reporting success would leave the
57
+ * row's `oauthStatus` claiming a state (e.g. `disconnected`) the stored blob does not actually match,
58
+ * with nothing to say so. So once the retry budget is exhausted, this rethrows instead: each of this
59
+ * function's callers already has a place that reacts to `ExternalMcpSecretStoreUnconfiguredError`
60
+ * without inventing a new one — `disconnect()`'s admin route already maps it to a 503
61
+ * `SECRET_STORE_UNCONFIGURED`, `reportAuthFailure` already carries an unexpected `setOAuthStatus`
62
+ * failure as `cause` on its terminal error, and `markNeedsReauth`'s two call sites in
63
+ * `packages/oauth/src/refresh.ts`'s `performRefresh` treat this write as best-effort the same way — its failure
64
+ * is carried as `cause` on the `OAUTH_INVALID_GRANT` error they throw next, never left to propagate
65
+ * in that error's place. (An earlier version of this comment claimed that path "already folds" a
66
+ * write failure into the boot report; it did not — the failure escaped unguarded and displaced the
67
+ * reauth signal every downstream caller branches on. Both call sites now guard it explicitly.) Any
68
+ * OTHER error (a genuine bug, not an unopenable or unsealable blob) still propagates from either
69
+ * step — this is a documented, targeted degrade, not a blanket swallow.
70
+ *
71
+ * @throws {ExternalMcpSecretStoreUnconfiguredError} If the re-seal never recovers within
72
+ * {@link CLEAR_TOKEN_RESEAL_ATTEMPTS} attempts.
73
+ */
74
+ async function resolveClearedTokenPatch(deps, record, options) {
75
+ if (options.clearToken !== true)
76
+ return {};
77
+ const opened = await openExistingOAuthPayloadForClear(deps, record);
78
+ if ("wholesale" in opened)
79
+ return { sealedOAuth: null, oauthExpiresAt: null };
80
+ const kept = options.dropClientSecret ? undefined : opened.existing.clientSecret;
81
+ const clientSecret = kept === undefined ? {} : { clientSecret: kept };
82
+ return resealClearedOAuthToken(deps, record, clientSecret);
83
+ }
84
+ /** {@link resolveClearedTokenPatch}'s OPEN step — reads the existing payload, or signals the
85
+ * wholesale-null fallback when the blob cannot be opened at all (see that function's doc for why
86
+ * this branch is safe). Split out purely to keep that function's cognitive complexity under the
87
+ * shop ceiling. */
88
+ async function openExistingOAuthPayloadForClear(deps, record) {
89
+ try {
90
+ return { existing: await deps.ports.store.openPayload(deps.sealer, record) };
91
+ }
92
+ catch (error) {
93
+ if (!deps.ports.errors.isUnconfigured(error))
94
+ throw error;
95
+ return { wholesale: true };
96
+ }
97
+ }
98
+ /** {@link resolveClearedTokenPatch}'s RE-SEAL step — retries a bounded number of times before giving
99
+ * up (see that function's doc for why). Split out purely to keep that function's cognitive
100
+ * complexity under the shop ceiling.
101
+ * @throws {ExternalMcpSecretStoreUnconfiguredError} If the re-seal never recovers within
102
+ * {@link CLEAR_TOKEN_RESEAL_ATTEMPTS} attempts. */
103
+ async function resealClearedOAuthToken(deps, record, clientSecret) {
104
+ for (let attempt = 1;; attempt += 1) {
105
+ try {
106
+ const cleared = await deps.ports.store.sealPayload(deps, record, clientSecret);
107
+ return { sealedOAuth: cleared.sealedOAuth, oauthExpiresAt: null, oauthAadVersion: cleared.oauthAadVersion };
108
+ }
109
+ catch (error) {
110
+ if (!deps.ports.errors.isUnconfigured(error))
111
+ throw error;
112
+ if (attempt >= CLEAR_TOKEN_RESEAL_ATTEMPTS)
113
+ throw error;
114
+ }
115
+ }
116
+ }
117
+ /** Moves a row into a terminal or reset OAuth state without touching anything else on it. See
118
+ * {@link resolveClearedTokenPatch} for the `clearToken` decision tree. */
119
+ export async function setOAuthStatus(deps, serverId, status, options = {}) {
120
+ const key = { workspaceId: deps.workspaceId, serverId };
121
+ const record = await deps.repo.findByServerId(key);
122
+ if (!record)
123
+ return;
124
+ const forgetClient = options.forgetSelfRegisteredClient === true && isSelfRegisteredClient(record, readStoredEndpoints(record));
125
+ const nextRow = async (current) => {
126
+ // The secret is only ever dropped together with the token (`clearToken`), never on its own.
127
+ const clearedTokenPatch = await resolveClearedTokenPatch(deps, current, { ...options, dropClientSecret: forgetClient });
128
+ return {
129
+ ...current,
130
+ oauthStatus: status,
131
+ ...clearedTokenPatch,
132
+ ...(forgetClient ? { oauthClientId: null, oauthEndpointsJson: JSON.stringify(withoutSelfRegisteredClient(readStoredEndpoints(current))) } : {}),
133
+ oauthRefreshLeaseUntil: null,
134
+ updatedAt: readNowIso({ clock: deps.clock }),
135
+ };
136
+ };
137
+ // Forgetting the client is an edit (version-compared, M4); every other state change is a runtime write (S1).
138
+ if (forgetClient)
139
+ await updateRowOnce({ repo: deps.repo, key, build: nextRow });
140
+ else
141
+ await writeOAuthRuntime({ repo: deps.repo, ports: deps.ports, record, patch: runtimePatchOf(await nextRow(record)) });
142
+ }
143
+ //# sourceMappingURL=sign-in-status.js.map