@jini-ai/integrations 0.6.19 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/dist/api-connections/access-token.js +4 -14
  3. package/dist/api-connections/account-actions.d.ts +6 -1
  4. package/dist/api-connections/attempt-state.d.ts +2 -2
  5. package/dist/api-connections/attempt-state.js +10 -11
  6. package/dist/api-connections/authorization.js +13 -20
  7. package/dist/api-connections/budgets.d.ts +91 -0
  8. package/dist/api-connections/budgets.js +87 -0
  9. package/dist/api-connections/byo-client.d.ts +38 -0
  10. package/dist/api-connections/byo-client.js +28 -0
  11. package/dist/api-connections/connect.d.ts +87 -0
  12. package/dist/api-connections/connect.js +143 -0
  13. package/dist/api-connections/declarations.d.ts +68 -0
  14. package/dist/api-connections/declarations.js +178 -0
  15. package/dist/api-connections/deps.d.ts +4 -1
  16. package/dist/api-connections/descriptor.d.ts +15 -0
  17. package/dist/api-connections/descriptor.js +1 -5
  18. package/dist/api-connections/finish-authorization.d.ts +1 -1
  19. package/dist/api-connections/hook-http.d.ts +20 -0
  20. package/dist/api-connections/hook-http.js +27 -0
  21. package/dist/api-connections/host-ports.d.ts +244 -0
  22. package/dist/api-connections/host-ports.js +2 -0
  23. package/dist/api-connections/host.d.ts +81 -0
  24. package/dist/api-connections/host.js +320 -0
  25. package/dist/api-connections/hosted-mcp/contracts.d.ts +291 -0
  26. package/dist/api-connections/hosted-mcp/contracts.js +2 -0
  27. package/dist/api-connections/hosted-mcp/index.d.ts +5 -0
  28. package/dist/api-connections/hosted-mcp/index.js +3 -0
  29. package/dist/api-connections/hosted-mcp/shared-sign-in.d.ts +167 -0
  30. package/dist/api-connections/hosted-mcp/shared-sign-in.js +293 -0
  31. package/dist/api-connections/hosted-mcp/sign-in.d.ts +25 -0
  32. package/dist/api-connections/hosted-mcp/sign-in.js +889 -0
  33. package/dist/api-connections/hosted-sign-in.d.ts +48 -0
  34. package/dist/api-connections/hosted-sign-in.js +51 -0
  35. package/dist/api-connections/index.d.ts +23 -1
  36. package/dist/api-connections/index.js +15 -0
  37. package/dist/api-connections/install-credential.d.ts +1 -1
  38. package/dist/api-connections/oauth-capabilities.d.ts +63 -0
  39. package/dist/api-connections/oauth-capabilities.js +2 -0
  40. package/dist/api-connections/ports.d.ts +1 -1
  41. package/dist/api-connections/request-checks.d.ts +11 -1
  42. package/dist/api-connections/request-checks.js +2 -3
  43. package/dist/api-connections/shared.d.ts +79 -0
  44. package/dist/api-connections/shared.js +106 -0
  45. package/dist/api-connections/token-store/record.d.ts +2 -2
  46. package/dist/api-connections/token-store/vault-token-store.d.ts +30 -4
  47. package/dist/api-connections/token-store/vault-token-store.js +1 -4
  48. package/dist/credentialed-http/sets/host.d.ts +146 -0
  49. package/dist/credentialed-http/sets/host.js +2 -0
  50. package/dist/credentialed-http/sets/index.d.ts +24 -0
  51. package/dist/credentialed-http/sets/index.js +24 -0
  52. package/dist/credentialed-http/sets/store.d.ts +193 -0
  53. package/dist/credentialed-http/sets/store.js +489 -0
  54. package/dist/credentialed-http/sets/vault-repo.d.ts +81 -0
  55. package/dist/credentialed-http/sets/vault-repo.js +147 -0
  56. package/dist/credentialed-http/tools/credential-copy-tool.d.ts +34 -0
  57. package/dist/credentialed-http/tools/credential-copy-tool.js +132 -0
  58. package/dist/credentialed-http/tools/credential-tool-host.d.ts +152 -0
  59. package/dist/credentialed-http/tools/credential-tool-host.js +2 -0
  60. package/dist/credentialed-http/tools/credential-tool-operations.d.ts +370 -0
  61. package/dist/credentialed-http/tools/credential-tool-operations.js +2 -0
  62. package/dist/credentialed-http/tools/index.d.ts +7 -0
  63. package/dist/credentialed-http/tools/index.js +4 -0
  64. package/dist/credentialed-http/tools/tool-registrations.d.ts +55 -0
  65. package/dist/credentialed-http/tools/tool-registrations.js +729 -0
  66. package/package.json +34 -11
@@ -0,0 +1,244 @@
1
+ import type { Clock } from '@jini-ai/core/primitives';
2
+ import type { OAuthAppOptions, OAuthClient, OAuthHttpPorts } from '@jini-ai/core/contracts/oauth';
3
+ import type { ApiConnectionDeclaration, ApiConnectionHooksModule } from './declarations.js';
4
+ import type { ApiConnectionClientKind } from './deps.js';
5
+ import type { ApiConnectionOAuthCapabilities } from './oauth-capabilities.js';
6
+ import type { ApiConnectionError } from './errors.js';
7
+ import type { ApiConnectionRecordStore, ApiConnectionTokenStore } from './ports.js';
8
+ import type { ApiConnectionService } from './service.js';
9
+ import type { SharedOAuthConnection } from './shared.js';
10
+ import type { ApiConnectionAccount, ApiConnectionAttempt, ApiConnectionDescriptor } from './types.js';
11
+ import type { CreateConnectionBudgetLimiter } from './budgets.js';
12
+ export type ApiConnectionRuntime = 'hosted' | 'desktop';
13
+ /** The trusted projection a host loader returns; declarations and hooks remain in this domain. */
14
+ export interface DeclaredApiConnection {
15
+ readonly pluginId: string;
16
+ readonly descriptor: ApiConnectionDescriptor;
17
+ readonly clients: ApiConnectionDeclaration['clients'];
18
+ readonly budgets: ApiConnectionDeclaration['budgets'];
19
+ readonly scopeSets: ApiConnectionDeclaration['scopeSets'];
20
+ readonly apiOrigins: ApiConnectionDeclaration['apiOrigins'];
21
+ readonly byoClient: ApiConnectionDeclaration['byoClient'];
22
+ readonly module: ApiConnectionHooksModule;
23
+ }
24
+ /** Buffered request options only; the host retains URL, redirect and DNS policy enforcement. */
25
+ export interface ApiConnectionHttpOptions {
26
+ readonly method?: 'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
27
+ readonly headers?: Readonly<Record<string, string>>;
28
+ readonly body?: string;
29
+ readonly signal?: AbortSignal;
30
+ }
31
+ export interface PluginHttp {
32
+ fetch(required: {
33
+ readonly url: string;
34
+ }, optional?: ApiConnectionHttpOptions): Promise<Response>;
35
+ }
36
+ /** A non-consuming attempt lookup is needed by the host's public callback route. */
37
+ export interface ApiConnectionHostRecordStore extends ApiConnectionRecordStore {
38
+ peekAttempt(required: {
39
+ readonly state: string;
40
+ }, optional?: Record<string, never>): Promise<ApiConnectionAttempt | null>;
41
+ }
42
+ export interface ApiConnectionHostStorage {
43
+ readonly records: ApiConnectionHostRecordStore;
44
+ tokensFor(required: {
45
+ owner: {
46
+ workspaceId: string;
47
+ pluginId: string;
48
+ connectionId: string;
49
+ clientId: string;
50
+ };
51
+ }): ApiConnectionTokenStore;
52
+ }
53
+ /** Only the selected credential's client fields and allowed origins cross this boundary. */
54
+ export interface ApiConnectionByoCredential {
55
+ readonly connection: {
56
+ readonly username?: string | undefined;
57
+ readonly token: string;
58
+ };
59
+ /**
60
+ * The saved credential's allowed origins, projected only when called.
61
+ * @agent-note Deferred on purpose: `resolveByoClient` calls it after the read has resolved and
62
+ * outside the read's "unreadable" catch, so a projection failure (e.g. a malformed saved base URL)
63
+ * rejects with the host's own raw error instead of being reported as an unreadable credential.
64
+ */
65
+ readonly allowedOrigins: () => readonly string[];
66
+ }
67
+ export type ApiConnectionByoRefusal = {
68
+ connection: Pick<DeclaredApiConnection, 'descriptor'>;
69
+ label: string;
70
+ } & ({
71
+ problem: 'unreadable' | 'missing-client-id';
72
+ } | {
73
+ problem: 'wrong-origin';
74
+ tokenOrigin: string;
75
+ });
76
+ export interface ApiConnectionByoCredentials {
77
+ read(required: {
78
+ workspaceId: string;
79
+ label: string;
80
+ }): Promise<ApiConnectionByoCredential | null>;
81
+ refuse(required: ApiConnectionByoRefusal): ApiConnectionError;
82
+ }
83
+ /** Sealed owner context is projected by the host's existing shared storage, never copied or reissued. */
84
+ export interface ApiConnectionSharedIssuingContext {
85
+ readonly credentialId: string;
86
+ readonly identity: SharedOAuthConnection['identity'];
87
+ readonly client: OAuthClient;
88
+ readonly clientKind: ApiConnectionClientKind;
89
+ readonly descriptor: ApiConnectionDescriptor;
90
+ }
91
+ export interface ApiConnectionSharedStorage {
92
+ readonly records: ApiConnectionRecordStore;
93
+ readContext(required: {
94
+ credentialId: string;
95
+ }): Promise<ApiConnectionSharedIssuingContext | null>;
96
+ tokensFor(required: {
97
+ context: ApiConnectionSharedIssuingContext;
98
+ }): ApiConnectionTokenStore;
99
+ }
100
+ export interface ApiConnectionPreparedSignIn {
101
+ readonly service: ApiConnectionService;
102
+ readonly workspaceId: string;
103
+ onCompleted(): Promise<void>;
104
+ }
105
+ export interface ApiConnectionSharedConnections {
106
+ bind(required: {
107
+ keyId: string;
108
+ use: boolean;
109
+ }, optional?: Record<string, never>): Promise<void>;
110
+ hasBinding(connection: DeclaredApiConnection, optional?: Record<string, never>): Promise<boolean>;
111
+ getStatus(connection: DeclaredApiConnection, optional?: Record<string, never>): Promise<SharedOAuthConnection | null>;
112
+ readAccount(connection: DeclaredApiConnection, optional?: Record<string, never>): Promise<ApiConnectionAccount | null>;
113
+ getAccessToken(connection: DeclaredApiConnection, optional?: {
114
+ expectedAccountId?: string;
115
+ }): Promise<string>;
116
+ selectLocal(connection: DeclaredApiConnection, optional?: Record<string, never>): Promise<void>;
117
+ stopUsing(connection: DeclaredApiConnection, optional?: Record<string, never>): Promise<void>;
118
+ prepare(required: {
119
+ connection: DeclaredApiConnection;
120
+ actorId: string;
121
+ context: ApiConnectionSharedIssuingContext;
122
+ redirectUri?: string;
123
+ }, optional?: Record<string, never>): Promise<ApiConnectionPreparedSignIn>;
124
+ }
125
+ export interface ApiConnectionSharedFactoryInput {
126
+ readonly workspaceId: string;
127
+ readonly listConnections: (required: {
128
+ pluginId: string;
129
+ }) => Promise<readonly DeclaredApiConnection[]>;
130
+ readonly requestedScopes: (required: {
131
+ connection: DeclaredApiConnection;
132
+ scopeSetIds: readonly string[];
133
+ }) => Promise<readonly string[]>;
134
+ readonly createService: (required: {
135
+ connection: DeclaredApiConnection;
136
+ context: ApiConnectionSharedIssuingContext;
137
+ redirectUri?: string;
138
+ }) => ApiConnectionService;
139
+ }
140
+ /**
141
+ * What a host binds once for the API-connection runtime.
142
+ * @agent-note The host binds its one storage owner, fresh declaration loader, guarded HTTP,
143
+ * credential projection and application identity. These ports never construct a host or store.
144
+ */
145
+ export interface ApiConnectionHostPorts {
146
+ readonly apiConnectionStorage: ApiConnectionHostStorage;
147
+ readonly loadDeclaredConnections: (required: {
148
+ workspaceId: string;
149
+ }) => Promise<{
150
+ connections: readonly DeclaredApiConnection[];
151
+ refusals: readonly string[];
152
+ }>;
153
+ readonly createSharedConnections: (required: ApiConnectionSharedFactoryInput) => ApiConnectionSharedConnections;
154
+ readonly appIdentity: Pick<OAuthAppOptions, 'clientDisplayName' | 'softwareId'>;
155
+ readonly byoCredentials: ApiConnectionByoCredentials;
156
+ readonly createLimiter: CreateConnectionBudgetLimiter;
157
+ }
158
+ /** Connection attempt outcomes are projected through a local shape; the host supplies their owner. */
159
+ export interface ApiConnectionSignInAttempt {
160
+ readonly code: string;
161
+ readonly nextAction: string;
162
+ }
163
+ export interface ApiConnectionCallbackKey {
164
+ readonly workspaceId: string;
165
+ readonly pluginId: string;
166
+ readonly connectionId: string;
167
+ readonly attemptId: string;
168
+ }
169
+ export interface ApiConnectionCallbackInbox {
170
+ deposit(required: ApiConnectionCallbackKey & {
171
+ readonly fields: Readonly<Record<string, string>>;
172
+ }, optional?: Record<string, never>): void;
173
+ take(required: ApiConnectionCallbackKey, optional?: Record<string, never>): Readonly<Record<string, string>> | null;
174
+ }
175
+ export type ApiConnectionStartLoopback = (required: Record<string, never>, optional?: {
176
+ readonly callbackFields?: readonly string[];
177
+ readonly timeoutMs?: number;
178
+ readonly signal?: AbortSignal;
179
+ readonly timers?: {
180
+ after(required: {
181
+ readonly ms: number;
182
+ readonly run: () => void;
183
+ }): () => void;
184
+ };
185
+ }) => Promise<{
186
+ readonly redirectUri: string;
187
+ receive(required: {
188
+ readonly expectedState: string;
189
+ }): Promise<{
190
+ readonly code: string;
191
+ readonly fields: Readonly<Record<string, string>>;
192
+ }>;
193
+ }>;
194
+ /** Product wording and environment setting names are host inputs, including refusal punctuation. */
195
+ export interface ApiConnectionHostMessages {
196
+ readonly callbackOriginsEnv: string;
197
+ notConfigured(required: {
198
+ label: string;
199
+ runtime: ApiConnectionRuntime;
200
+ what: string;
201
+ }): string;
202
+ missingReturnAddress(required: {
203
+ label: string;
204
+ }): string;
205
+ unregisteredOrigin(required: {
206
+ label: string;
207
+ }): string;
208
+ noPublicOrigin(required: {
209
+ label: string;
210
+ }): string;
211
+ }
212
+ /** @agent-note Pass the already-built state store/inbox over the same storage used by the callback route.
213
+ * State is opaque to this domain; integrations never imports its owner's package. */
214
+ export interface ApiConnectionRuntimeHostDeps<State> extends ApiConnectionHostPorts {
215
+ readonly workspaceId: string;
216
+ readonly clock: Clock;
217
+ readonly oauthHttp: OAuthHttpPorts;
218
+ /** @agent-note Required; ONE `ApiConnectionOAuthCapabilities` object bound by the host from the real `@jini-ai/oauth` exports, shared by every service, attempt, callback and sign-in hand-off this host creates. */
219
+ readonly oauth: ApiConnectionOAuthCapabilities;
220
+ readonly pluginHttp: PluginHttp;
221
+ readonly runtime: ApiConnectionRuntime;
222
+ readonly env: Readonly<Record<string, string | undefined>>;
223
+ readonly publicOrigin: () => string | undefined;
224
+ readonly pluginState: State;
225
+ readonly callbackInbox: ApiConnectionCallbackInbox;
226
+ readonly callbackPath: string;
227
+ readonly startLoopback: ApiConnectionStartLoopback;
228
+ readonly messages: ApiConnectionHostMessages;
229
+ }
230
+ export interface ApiConnectionRuntimeHostOptions {
231
+ readonly shared?: ApiConnectionSharedStorage;
232
+ }
233
+ export type ApiConnectionSignInLink = (required: {
234
+ callbackUrl: string;
235
+ workspaceId: string;
236
+ handoffId: string;
237
+ }) => string;
238
+ export interface ApiConnectionConnectMessages {
239
+ toolError(required: {
240
+ message: string;
241
+ }): string;
242
+ readonly sharedUnavailable: string;
243
+ }
244
+ //# sourceMappingURL=host-ports.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=host-ports.js.map
@@ -0,0 +1,81 @@
1
+ import { type ApiConnectionService } from './service.js';
2
+ import type { ApiConnectionRuntimeHostDeps, ApiConnectionRuntimeHostOptions, ApiConnectionSignInAttempt, ApiConnectionRuntime, ApiConnectionHostRecordStore, DeclaredApiConnection } from './host-ports.js';
3
+ /**
4
+ * Builds the workspace host. Declarations are read fresh per call, so enabling or disabling a
5
+ * plugin takes effect without a restart (Node caches each hooks module per file URL).
6
+ * @complexity O(1) setup; each lookup is one contribution load, O(p + c).
7
+ */
8
+ export declare function createApiConnectionHost<State>(required: ApiConnectionRuntimeHostDeps<State>, optional?: ApiConnectionRuntimeHostOptions): {
9
+ sharingAvailable: boolean;
10
+ sharedOAuth: import("./host-ports.js").ApiConnectionSharedConnections | undefined;
11
+ prepareSignIn: (input: {
12
+ connection: DeclaredApiConnection;
13
+ actorId: string;
14
+ destination?: "site" | "shared" | undefined;
15
+ redirectUri?: string;
16
+ }) => Promise<import("./host-ports.js").ApiConnectionPreparedSignIn>;
17
+ workspaceId: string;
18
+ runtime: ApiConnectionRuntime;
19
+ clock: import("@jini-ai/core/primitives").Clock;
20
+ records: ApiConnectionHostRecordStore;
21
+ startLoopback: import("./host-ports.js").ApiConnectionStartLoopback;
22
+ listConnections: (input?: {
23
+ readonly pluginId?: string;
24
+ }) => Promise<readonly DeclaredApiConnection[]>;
25
+ serviceFor: (input: {
26
+ readonly connection: DeclaredApiConnection;
27
+ readonly redirectUri?: string;
28
+ }) => ApiConnectionService;
29
+ accessTokensFor: (scope: {
30
+ readonly pluginId: string;
31
+ }) => {
32
+ getAccessToken(input: {
33
+ readonly connectionRef: string;
34
+ }, options?: {
35
+ readonly expectedAccountId?: string;
36
+ }): Promise<string>;
37
+ };
38
+ toolConnections: {
39
+ readAccount(target: {
40
+ readonly workspaceId: string;
41
+ readonly pluginId: string;
42
+ readonly connectionRef: string;
43
+ }): Promise<import("./types.js").ApiConnectionAccount | null>;
44
+ getAccessToken(target: {
45
+ readonly workspaceId: string;
46
+ readonly pluginId: string;
47
+ readonly connectionRef: string;
48
+ }, options?: {
49
+ readonly expectedAccountId?: string;
50
+ }): Promise<string>;
51
+ };
52
+ apiOriginsFor: (input: {
53
+ readonly workspaceId: string;
54
+ readonly pluginId: string;
55
+ }) => Promise<readonly string[]>;
56
+ declaredFor: (input: {
57
+ readonly pluginId: string;
58
+ readonly connectionRef: string;
59
+ }) => Promise<DeclaredApiConnection | undefined>;
60
+ requestedScopes: (input: {
61
+ readonly connection: DeclaredApiConnection;
62
+ readonly scopeSetIds: readonly string[];
63
+ }) => Promise<readonly string[]>;
64
+ hostedCallbackUrl: ({ connection }: {
65
+ readonly connection: DeclaredApiConnection;
66
+ }) => string;
67
+ statusOf: ({ connection, local }: {
68
+ readonly connection: DeclaredApiConnection;
69
+ readonly local?: boolean;
70
+ }) => Promise<{
71
+ connectionRef: string;
72
+ status: import("./types.js").ApiConnectionStatus;
73
+ grantedScopes: readonly string[];
74
+ }>;
75
+ callbackInbox: import("./host-ports.js").ApiConnectionCallbackInbox;
76
+ lastSignInAttempts: Map<string, ApiConnectionSignInAttempt>;
77
+ signInHandoffs: import("./hosted-sign-in.js").SignInHandoffs;
78
+ pluginState: State;
79
+ };
80
+ export type ApiConnectionHost<State = unknown> = ReturnType<typeof createApiConnectionHost<State>>;
81
+ //# sourceMappingURL=host.d.ts.map
@@ -0,0 +1,320 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { createApiConnectionService } from './service.js';
3
+ import { createSignInHandoffs } from './hosted-sign-in.js';
4
+ import { deriveApiConnectionKey } from './keys.js';
5
+ import { ApiConnectionError } from './errors.js';
6
+ import { createConnectionBudgets } from './budgets.js';
7
+ import { resolveByoClient } from './byo-client.js';
8
+ import { createConnectionHookHttp } from "./hook-http.js";
9
+ /**
10
+ * @file Composes Jini's api-connections service (G1) with the host's vault stores (G2 + 0020) for every
11
+ * connection an active plugin declares. One host per workspace; callers ask it for a connection's
12
+ * service, its record store or a fresh access token. Nothing here names a provider.
13
+ *
14
+ * Runtime decides the client: `hosted` uses the plugin's web client (confidential: its secret is
15
+ * required) and the fixed public callback; `desktop` uses the installed-app client (public, PKCE,
16
+ * optionally with a provider-issued non-confidential secret) and a per-attempt loopback redirect.
17
+ * Tokens stay bound to the client that issued them. Every token read first spends the connection's
18
+ * declared request budgets (`budgets.ts`), counted in this host's memory. The host also owns the
19
+ * workspace's plugin settings store (`plugin-state.ts`, same vault) and the consume-once inbox where
20
+ * a completed sign-in's declared callback fields wait for the plugin's surface handler.
21
+ *
22
+ * A connection that allows it (`byoClient`) uses the workspace admin's own OAuth client when one is
23
+ * saved (`byo-client.ts`); its secret stays in this host's memory for the call and goes to the token
24
+ * endpoint only. Tokens are sealed for the client id that issued them, so after the client changes
25
+ * (BYO saved, replaced or removed) a connected record would claim "connected" with tokens nobody can
26
+ * read: every status read and token read here notices that and durably moves the record to
27
+ * `reconnect-required` (the honest state: a reconnect issues tokens for the current client).
28
+ */
29
+ /** The one refusal for a ref the calling plugin does not own here, whatever the reason. */
30
+ function notAvailable() {
31
+ return new ApiConnectionError({ code: "connection-not-found", message: "This connection is not available to this plugin here. Connect the plugin's account, then retry." });
32
+ }
33
+ /** Why a connection cannot be used on this host, in words for the person, never a secret value. */
34
+ function setupRefused(message) {
35
+ return new ApiConnectionError({ code: "descriptor-invalid", message });
36
+ }
37
+ /** A configured host setting, trimmed; undefined when the plugin names none or it is unset. @complexity O(1). */
38
+ function configured(env, name) {
39
+ return name === undefined ? undefined : env[name]?.trim() || undefined;
40
+ }
41
+ /** True when a stored token set cannot be opened by this owner (sealed for another client id, or malformed). */
42
+ function isUnreadableTokenRecord(error) {
43
+ const code = error?.code;
44
+ return error instanceof Error && error.name === "OAuthTokenStoreError" && (code === "owner-mismatch" || code === "invalid-record");
45
+ }
46
+ /** True when Jini's service already turned an unreadable token record into its generic reconnect-required refusal. */
47
+ function wrapsUnreadableTokenRecord(error) {
48
+ return error instanceof ApiConnectionError && isUnreadableTokenRecord(error.cause);
49
+ }
50
+ function clientChanged(cause) {
51
+ return new ApiConnectionError({ code: "reconnect-required", message: "This connection's sign-in client changed, so its stored sign-in can no longer be used. Reconnect the account in the connection settings." }, { cause });
52
+ }
53
+ /** The client kind a runtime signs in as: the installed app is public, the hosted site confidential. */
54
+ function clientKindFor(runtime) {
55
+ return runtime === "desktop" ? "public" : "confidential";
56
+ }
57
+ /** An admin's own client for this runtime; its secret goes to the token endpoint like the host's. @complexity O(1). */
58
+ function byoOAuthClient(byo, runtime) {
59
+ return { clientKind: clientKindFor(runtime), client: { clientId: byo.clientId, clientSecret: byo.clientSecret, authMethod: "client_secret_post" } };
60
+ }
61
+ /**
62
+ * The runtime's OAuth client and how it is registered. Desktop is the installed app (`public`): PKCE,
63
+ * and a provider-issued secret only when the provider requires one for installed apps (it is not
64
+ * confidential there, but it still stays in host config and is never shown or logged). Hosted is the
65
+ * web client (`confidential`) and must have its server-held secret.
66
+ * @complexity O(1).
67
+ */
68
+ function resolveClient(connection, runtime, env, messages) {
69
+ const config = runtime === "desktop" ? connection.clients.desktop : connection.clients.web;
70
+ const clientId = configured(env, config?.clientIdEnv);
71
+ if (!config || !clientId)
72
+ throw notConfigured(connection, runtime, "sign-in client", messages);
73
+ const clientSecret = configured(env, config.clientSecretEnv);
74
+ const clientKind = clientKindFor(runtime);
75
+ if (clientKind === "confidential" && !clientSecret)
76
+ throw notConfigured(connection, runtime, "sign-in client secret", messages);
77
+ return { clientKind, client: clientSecret ? { clientId, clientSecret, authMethod: "client_secret_post" } : { clientId, authMethod: "none" } };
78
+ }
79
+ /** Each listed entry's origin; an entry that is not a URL is dropped (it can match nothing). @complexity O(n). */
80
+ function configuredOrigins(env, setting) {
81
+ const listed = configured(env, setting)?.split(",") ?? [];
82
+ return listed.flatMap((entry) => URL.parse(entry.trim())?.origin ?? []);
83
+ }
84
+ function notConfigured(connection, runtime, what, messages) {
85
+ return setupRefused(messages.notConfigured({ label: connection.descriptor.label, runtime, what }));
86
+ }
87
+ /** Status projection shared by local records and token-free owner connection metadata. */
88
+ function connectionStatus({ connectionRef, record }) {
89
+ return { connectionRef, status: record?.status ?? "disconnected", grantedScopes: record?.grantedScopes ?? [] };
90
+ }
91
+ /**
92
+ * Builds the workspace host. Declarations are read fresh per call, so enabling or disabling a
93
+ * plugin takes effect without a restart (Node caches each hooks module per file URL).
94
+ * @complexity O(1) setup; each lookup is one contribution load, O(p + c).
95
+ */
96
+ export function createApiConnectionHost(required, optional = {}) {
97
+ const { records } = required.apiConnectionStorage;
98
+ const budgets = createConnectionBudgets({ clock: required.clock, createLimiter: required.createLimiter });
99
+ // In-process: the public callback and the admin-surface routes run in this host's process.
100
+ const callbackInbox = required.callbackInbox;
101
+ const pluginState = required.pluginState;
102
+ // In-process, by connection ref: the last desktop sign-in that failed after the browser opened, so
103
+ // the plugin's panel can say so (the loopback page is all the user saw). At most one per declared
104
+ // connection; a later success deletes it.
105
+ const lastSignInAttempts = new Map();
106
+ // Hosted sign-ins started here, waiting for their starter's browser to open the host link.
107
+ const signInHandoffs = createSignInHandoffs({ clock: required.clock, randomBytesFn: ({ byteLength }) => randomBytes(byteLength), oauth: required.oauth });
108
+ // Per host (so per workspace) and per loaded declaration object: a BYO client never travels with a
109
+ // connection object into another host, and the secret is never a field anything could serialize.
110
+ const byoClients = new WeakMap();
111
+ /** The declared connections, each with this workspace's BYO client resolved fresh. @complexity O(p + c) plus one credential open per BYO connection. */
112
+ async function listConnections(input = {}) {
113
+ const { connections } = await required.loadDeclaredConnections({ workspaceId: required.workspaceId });
114
+ const listed = input.pluginId === undefined ? connections : connections.filter((connection) => connection.pluginId === input.pluginId);
115
+ for (const connection of listed) {
116
+ const byo = await resolveByoClient({ byoCredentials: required.byoCredentials, workspaceId: required.workspaceId, connection });
117
+ if (byo)
118
+ byoClients.set(connection, byo);
119
+ }
120
+ return listed;
121
+ }
122
+ /** The connection's OAuth client here: the admin's own when saved (an unusable one refuses), else the host's. @complexity O(1). */
123
+ function clientFor(connection) {
124
+ const byo = byoClients.get(connection);
125
+ if (byo instanceof ApiConnectionError)
126
+ throw byo;
127
+ return byo ? byoOAuthClient(byo, required.runtime) : resolveClient(connection, required.runtime, required.env, required.messages);
128
+ }
129
+ function tokensFor(connection, clientId) {
130
+ const owner = { workspaceId: required.workspaceId, pluginId: connection.pluginId, connectionId: connection.descriptor.connectionId, clientId };
131
+ return required.apiConnectionStorage.tokensFor({ owner });
132
+ }
133
+ /** Durably moves a record to `reconnect-required` (revision CAS); a lost race returns what won. @complexity Two vault calls at most. */
134
+ async function markReconnectRequired(record) {
135
+ const next = { ...record, status: "reconnect-required", revision: record.revision + 1, updatedAt: new Date(required.clock.nowMs()).toISOString() };
136
+ return (await records.compareAndSet({ key: record.key, expectedRevision: record.revision, record: next })) ? next : records.read({ key: record.key });
137
+ }
138
+ /**
139
+ * True when a connected record's tokens were sealed for another client than the one this host
140
+ * would use now. A connection no longer declared, or with no usable client, is left as it is: its
141
+ * actions already refuse with their own reason.
142
+ * @complexity One contribution load and one token-row open.
143
+ */
144
+ async function tokensForAnotherClient(record) {
145
+ if (record.status !== "connected")
146
+ return false;
147
+ const connection = (await listConnections({ pluginId: record.pluginId })).find((candidate) => candidate.descriptor.connectionId === record.connectionId);
148
+ if (!connection)
149
+ return false;
150
+ let clientId;
151
+ try {
152
+ clientId = clientFor(connection).client.clientId;
153
+ }
154
+ catch {
155
+ return false;
156
+ }
157
+ return tokensFor(connection, clientId).load({ key: record.key }).then(() => false, (error) => {
158
+ if (isUnreadableTokenRecord(error))
159
+ return true;
160
+ throw error;
161
+ });
162
+ }
163
+ /** The record as it really stands: a connected record whose tokens belong to another client reads (and is stored) as reconnect-required. */
164
+ async function readHonestRecord(input) {
165
+ const record = await records.read(input);
166
+ return record && (await tokensForAnotherClient(record)) ? markReconnectRequired(record) : record;
167
+ }
168
+ const honestRecords = { ...records, read: readHonestRecord };
169
+ /** The https origins `pluginId`'s connections declare here (union); another workspace declares none. @complexity O(p + c). */
170
+ async function apiOriginsFor(input) {
171
+ if (input.workspaceId !== required.workspaceId)
172
+ return [];
173
+ return (await listConnections({ pluginId: input.pluginId })).flatMap((connection) => connection.apiOrigins);
174
+ }
175
+ /**
176
+ * The hosted callback URL. Fails closed: refused when no return address is registered at all
177
+ * (declared or configured), when this site has no public origin, or when its origin is not one of
178
+ * them, so an unregistered site gets this actionable refusal instead of the provider's error page.
179
+ */
180
+ function hostedCallbackUrl({ connection }) {
181
+ const origin = required.publicOrigin();
182
+ // A BYO web client is the admin's own registration: they registered this site's own callback.
183
+ const byo = byoClients.get(connection);
184
+ if (byo && !(byo instanceof ApiConnectionError))
185
+ return byoCallbackUrl(connection, origin);
186
+ const allowed = [...(connection.clients.web?.redirectOrigins ?? []), ...configuredOrigins(required.env, required.messages.callbackOriginsEnv)];
187
+ if (allowed.length === 0) {
188
+ throw setupRefused(required.messages.missingReturnAddress({ label: connection.descriptor.label }));
189
+ }
190
+ if (!origin || !allowed.includes(origin)) {
191
+ throw setupRefused(required.messages.unregisteredOrigin({ label: connection.descriptor.label }));
192
+ }
193
+ return `${origin}${required.callbackPath}`;
194
+ }
195
+ function byoCallbackUrl(connection, origin) {
196
+ if (!origin)
197
+ throw setupRefused(required.messages.noPublicOrigin({ label: connection.descriptor.label }));
198
+ return `${origin}${required.callbackPath}`;
199
+ }
200
+ /** The connection's hooks over HTTP limited to its declared API origins and token endpoint origin. @complexity O(1). */
201
+ function hooksFor(connection) {
202
+ return connection.module.createHooks({ http: createConnectionHookHttp({ http: required.pluginHttp, connection }) });
203
+ }
204
+ /** One connection's service. Desktop passes the loopback redirect URI its attempt listens on. @complexity O(1). */
205
+ function serviceFor(input) {
206
+ const { connection } = input;
207
+ const { client, clientKind } = clientFor(connection);
208
+ const redirectUri = input.redirectUri ?? (required.runtime === "hosted" ? hostedCallbackUrl({ connection }) : undefined);
209
+ return createApiConnectionService({
210
+ descriptor: connection.descriptor, client, clientKind,
211
+ appOptions: { ...required.appIdentity, redirectUris: redirectUri ? [redirectUri] : [] },
212
+ hooks: hooksFor(connection),
213
+ records, tokens: tokensFor(connection, client.clientId),
214
+ fetchFn: required.oauthHttp.fetchFn, guard: required.oauthHttp.guard, clock: required.clock, oauth: required.oauth,
215
+ randomBytesFn: ({ byteLength }) => randomBytes(byteLength),
216
+ sleep: ({ ms }) => new Promise((resolve) => { setTimeout(resolve, ms); }),
217
+ });
218
+ }
219
+ /** The connection `connectionRef` names, only when THIS plugin declares it in THIS workspace. @complexity O(p + c). */
220
+ async function declaredFor(input) {
221
+ return (await listConnections({ pluginId: input.pluginId })).find((candidate) => deriveApiConnectionKey({ workspaceId: required.workspaceId, pluginId: input.pluginId, connectionId: candidate.descriptor.connectionId }) === input.connectionRef);
222
+ }
223
+ /**
224
+ * The plugin host capability `connections.getAccessToken({ connectionRef })`, scoped to one plugin.
225
+ * The ref must be the key of a connection THIS plugin declares in THIS workspace; anything else is
226
+ * the same refusal, so a plugin cannot probe other plugins' or workspaces' refs. Only an access
227
+ * token ever leaves: the refresh token stays inside the vault token store.
228
+ * @complexity O(p + c) contribution load, then one token read (and at most one refresh).
229
+ */
230
+ function accessTokensFor(scope) {
231
+ return {
232
+ async getAccessToken(input, options = {}) {
233
+ const connection = await declaredFor({ pluginId: scope.pluginId, connectionRef: input.connectionRef });
234
+ if (!connection)
235
+ throw notAvailable();
236
+ await budgets.charge({ workspaceId: required.workspaceId, pluginId: scope.pluginId, connectionId: connection.descriptor.connectionId, connectionRef: input.connectionRef, budgets: connection.budgets });
237
+ if (sharedOAuth && await sharedOAuth.hasBinding(connection))
238
+ return sharedOAuth.getAccessToken(connection, options);
239
+ return serviceFor({ connection }).getAccessToken({ connectionRef: input.connectionRef, workspaceId: required.workspaceId }, options).catch(async (error) => {
240
+ if (!isUnreadableTokenRecord(error) && !wrapsUnreadableTokenRecord(error))
241
+ throw error;
242
+ const record = await records.read({ key: input.connectionRef });
243
+ if (record?.status === "connected")
244
+ await markReconnectRequired(record);
245
+ throw clientChanged(error);
246
+ });
247
+ },
248
+ };
249
+ }
250
+ /**
251
+ * The connection port executable tools and admin-surface handlers receive (one per site; each
252
+ * call names its workspace and plugin). A target in another workspace, or a ref its plugin does
253
+ * not declare here, reads as no account and is refused exactly like an unknown ref.
254
+ * @complexity As {@link accessTokensFor}; `readAccount` is one contribution load and one record read.
255
+ */
256
+ const toolConnections = {
257
+ async readAccount(target) {
258
+ if (target.workspaceId !== required.workspaceId || !(await declaredFor(target)))
259
+ return null;
260
+ if (sharedOAuth) {
261
+ const connection = await declaredFor(target);
262
+ if (connection && await sharedOAuth.hasBinding(connection)) {
263
+ return sharedOAuth.readAccount(connection);
264
+ }
265
+ }
266
+ const record = await readHonestRecord({ key: target.connectionRef });
267
+ return record?.status === "connected" && record.account ? { accountId: record.account.accountId, displayName: record.account.displayName } : null;
268
+ },
269
+ async getAccessToken(target, options = {}) {
270
+ if (target.workspaceId !== required.workspaceId)
271
+ throw notAvailable();
272
+ return accessTokensFor({ pluginId: target.pluginId }).getAccessToken({ connectionRef: target.connectionRef }, options);
273
+ },
274
+ };
275
+ /** The scopes a sign-in for these scope sets would request, via the plugin's own hook. @complexity One hook call. */
276
+ async function requestedScopes(input) {
277
+ return hooksFor(input.connection).resolveScopes({ scopeSetIds: [...input.scopeSetIds] });
278
+ }
279
+ /** Token-free status straight from the record; a connection never created reads as disconnected. @complexity One read. */
280
+ async function statusOf({ connection, local = false }) {
281
+ const key = deriveApiConnectionKey({ workspaceId: required.workspaceId, pluginId: connection.pluginId, connectionId: connection.descriptor.connectionId });
282
+ if (!local && sharedOAuth && await sharedOAuth.hasBinding(connection)) {
283
+ const shared = await sharedOAuth.getStatus(connection);
284
+ return connectionStatus({ connectionRef: key, record: shared });
285
+ }
286
+ const record = await readHonestRecord({ key });
287
+ return connectionStatus({ connectionRef: key, record });
288
+ }
289
+ const sharedOAuth = optional.shared && required.runtime === "desktop" ? required.createSharedConnections({
290
+ workspaceId: required.workspaceId, listConnections, requestedScopes,
291
+ createService: ({ connection, context, redirectUri }) => createApiConnectionService({
292
+ descriptor: context.descriptor, client: context.client, clientKind: context.clientKind,
293
+ appOptions: { ...required.appIdentity, redirectUris: redirectUri ? [redirectUri] : [] },
294
+ hooks: hooksFor(connection), records: optional.shared.records, tokens: optional.shared.tokensFor({ context }),
295
+ fetchFn: required.oauthHttp.fetchFn, guard: required.oauthHttp.guard, clock: required.clock, oauth: required.oauth,
296
+ randomBytesFn: ({ byteLength }) => randomBytes(byteLength), sleep: ({ ms }) => new Promise(resolve => { setTimeout(resolve, ms); }),
297
+ }),
298
+ }) : undefined;
299
+ async function prepareSignIn(input) {
300
+ const { connection } = input;
301
+ if (input.destination !== "shared")
302
+ return { service: serviceFor(input), workspaceId: required.workspaceId, onCompleted: async () => {
303
+ if (input.destination === "site")
304
+ await sharedOAuth?.selectLocal(connection);
305
+ } };
306
+ if (!sharedOAuth)
307
+ throw notAvailable();
308
+ const credentialId = deriveApiConnectionKey({ workspaceId: "project", pluginId: connection.pluginId, connectionId: connection.descriptor.connectionId });
309
+ const existing = await optional.shared.readContext({ credentialId });
310
+ if (existing)
311
+ return sharedOAuth.prepare({ ...input, context: existing });
312
+ const { client, clientKind } = clientFor(connection);
313
+ const context = { credentialId, client, clientKind, descriptor: connection.descriptor,
314
+ identity: { pluginId: connection.pluginId, connectionId: connection.descriptor.connectionId, tokenEndpoint: connection.descriptor.tokenEndpoint, authorizationEndpoint: connection.descriptor.authorizationEndpoint, clientId: client.clientId } };
315
+ return sharedOAuth.prepare({ ...input, context });
316
+ }
317
+ return { sharingAvailable: Boolean(sharedOAuth), sharedOAuth, prepareSignIn, workspaceId: required.workspaceId, runtime: required.runtime, clock: required.clock, records: honestRecords, startLoopback: required.startLoopback, listConnections, serviceFor, accessTokensFor,
318
+ toolConnections, apiOriginsFor, declaredFor, requestedScopes, hostedCallbackUrl, statusOf, callbackInbox, lastSignInAttempts, signInHandoffs, pluginState };
319
+ }
320
+ //# sourceMappingURL=host.js.map