@jini-ai/integrations 0.6.19 → 0.7.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 (67) hide show
  1. package/CHANGELOG.md +48 -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/dist/webhooks/signing.js +2 -1
  67. package/package.json +34 -11
@@ -0,0 +1,48 @@
1
+ import type { Clock } from '@jini-ai/core/primitives';
2
+ import type { OAuthRandomBytes } from '@jini-ai/core/contracts/oauth';
3
+ import type { ApiConnectionOAuthCapabilities } from './oauth-capabilities.js';
4
+ import type { createApiConnectionGenerationReader } from './keys.js';
5
+ import type { ApiConnectionService } from './service.js';
6
+ interface HostedSignInWait {
7
+ readonly workspaceId: string;
8
+ readonly connectionRef: string;
9
+ readonly startGeneration: number;
10
+ readonly getStatus: ApiConnectionService['getStatus'];
11
+ readonly readGeneration: ReturnType<typeof createApiConnectionGenerationReader>;
12
+ readonly signal: AbortSignal;
13
+ readonly pollIntervalMs: number;
14
+ readonly waitTimeoutMs: number;
15
+ }
16
+ /** Hosted: wait for the callback route to install a newer credential.
17
+ * Returns false on timeout/abort; status and generation reader failures propagate unchanged.
18
+ * @complexity O(t / interval) record reads, O(1) space; no additional reads beyond the existing poll.
19
+ * @overallScore 100
20
+ */
21
+ export declare function waitForHostedSignIn(required: HostedSignInWait, _optional?: Record<string, never>): Promise<boolean>;
22
+ interface SignInHandoff {
23
+ readonly authorizationUrl: string;
24
+ readonly browserBinding: string;
25
+ readonly actorId: string;
26
+ readonly expiresAt: string;
27
+ }
28
+ export interface SignInHandoffs {
29
+ issue(required: SignInHandoff, optional?: Record<string, never>): string;
30
+ take(required: {
31
+ readonly handoffId: string;
32
+ readonly actorId: string;
33
+ }, optional?: Record<string, never>): SignInHandoff | null;
34
+ }
35
+ /** Actor-bound handoffs over the existing 256-entry, 10-minute cache. No timers or background processes.
36
+ * @returns issue (opaque id) and take (consumes even on actor mismatch).
37
+ * @example const handoffs = createSignInHandoffs({ clock, randomBytesFn }); // only host code may hold it
38
+ * @complexity O(n) insertion sweep, O(1) take; O(256) bounded space.
39
+ * @overallScore 100
40
+ */
41
+ export declare function createSignInHandoffs(required: {
42
+ readonly clock: Clock;
43
+ readonly randomBytesFn: OAuthRandomBytes;
44
+ /** @agent-note Required real `@jini-ai/oauth` exports (the host's one capabilities object): `createPendingAuthorizationStore` and `generateOAuthState`. */
45
+ readonly oauth: Pick<ApiConnectionOAuthCapabilities, 'createPendingAuthorizationStore' | 'generateState'>;
46
+ }, _optional?: Record<string, never>): SignInHandoffs;
47
+ export {};
48
+ //# sourceMappingURL=hosted-sign-in.d.ts.map
@@ -0,0 +1,51 @@
1
+ /** Abortable pause owned by the watcher; clears its timer and listener on either outcome.
2
+ * @complexity O(1) time and space. @overallScore 100
3
+ */
4
+ function pause(ms, signal) {
5
+ return new Promise((resolve) => {
6
+ const timer = setTimeout(done, ms);
7
+ signal.addEventListener('abort', done, { once: true });
8
+ function done() { clearTimeout(timer); signal.removeEventListener('abort', done); resolve(); }
9
+ });
10
+ }
11
+ /** Hosted: wait for the callback route to install a newer credential.
12
+ * Returns false on timeout/abort; status and generation reader failures propagate unchanged.
13
+ * @complexity O(t / interval) record reads, O(1) space; no additional reads beyond the existing poll.
14
+ * @overallScore 100
15
+ */
16
+ export async function waitForHostedSignIn(required, _optional = {}) {
17
+ const { connectionRef, workspaceId, startGeneration, getStatus, readGeneration, signal } = required;
18
+ const deadline = Date.now() + required.waitTimeoutMs;
19
+ while (Date.now() < deadline && !signal.aborted) {
20
+ const status = await getStatus({ connectionRef, workspaceId });
21
+ if (status.status === 'connected' && (await readGeneration({ key: connectionRef })) > startGeneration)
22
+ return true;
23
+ await pause(Math.min(required.pollIntervalMs, Math.max(deadline - Date.now(), 0)), signal);
24
+ }
25
+ return false;
26
+ }
27
+ /** Actor-bound handoffs over the existing 256-entry, 10-minute cache. No timers or background processes.
28
+ * @returns issue (opaque id) and take (consumes even on actor mismatch).
29
+ * @example const handoffs = createSignInHandoffs({ clock, randomBytesFn }); // only host code may hold it
30
+ * @complexity O(n) insertion sweep, O(1) take; O(256) bounded space.
31
+ * @overallScore 100
32
+ */
33
+ export function createSignInHandoffs(required, _optional = {}) {
34
+ const pending = required.oauth.createPendingAuthorizationStore({ clock: required.clock }, {
35
+ expiry: ({ value }) => Date.parse(value.expiresAt),
36
+ });
37
+ return {
38
+ /** Stores host-only proof; entropy errors propagate before anything is issued. */
39
+ issue(input, _options = {}) {
40
+ const id = required.oauth.generateState({ randomBytesFn: required.randomBytesFn }, { stateBytes: 32 });
41
+ pending.put({ state: id, value: { ...input } });
42
+ return id;
43
+ },
44
+ /** Burns the id first; unknown, expired, used or foreign actors all return null. */
45
+ take(input, _options = {}) {
46
+ const entry = pending.consume({ state: input.handoffId });
47
+ return entry?.actorId === input.actorId ? entry : null;
48
+ },
49
+ };
50
+ }
51
+ //# sourceMappingURL=hosted-sign-in.js.map
@@ -2,17 +2,39 @@
2
2
  * @file Public entry `@jini-ai/integrations/api-connections`: plugin-declared OAuth connections
3
3
  * (sign-in, status, reconnect, staged account switch, disconnect/revoke, access tokens).
4
4
  */
5
- export { parseApiConnectionDescriptor } from './descriptor.js';
5
+ export { parseApiConnectionDescriptor, type ApiConnectionCallbackFieldRules } from './descriptor.js';
6
6
  export { createApiConnectionService, type ApiConnectionService } from './service.js';
7
7
  export { deriveApiConnectionKey, createApiConnectionGenerationReader } from './keys.js';
8
+ export { waitForHostedSignIn, createSignInHandoffs, type SignInHandoffs } from './hosted-sign-in.js';
8
9
  export { ApiConnectionError, type ApiConnectionErrorCode } from './errors.js';
9
10
  export type { ApiConnectionClientKind, ApiConnectionServiceDeps } from './deps.js';
11
+ export type { ApiConnectionOAuthCapabilities, ApiConnectionOAuthError, ApiConnectionPendingCache } from './oauth-capabilities.js';
10
12
  export type { ApiConnectionHooks, ApiConnectionRecordStore, ApiConnectionTokenStore } from './ports.js';
11
13
  export type { StartApiConnectionResult } from './authorization.js';
12
14
  export type { CompletedAuthorization } from './finish-authorization.js';
13
15
  export type { ApiConnectionStatusView } from './status.js';
14
16
  export type { ApiConnectionDisconnectResult, ApiConnectionRemoteRevocation, ApiConnectionSwitchResult } from './account-actions.js';
17
+ import { type ApiConnectionDisconnectDeps } from './account-actions.js';
18
+ export type { ApiConnectionDisconnectDeps } from './account-actions.js';
15
19
  export type { ApiConnectionAccessTokens } from './access-token.js';
20
+ export { assertSharedOAuthCompatibility, createSharedOAuthConsumer } from './shared.js';
21
+ export type { SharedOAuthConnection, SharedOAuthConsumer, SharedOAuthConsumerDeps, SharedOAuthConsumerTarget, SharedOAuthIdentity } from './shared.js';
16
22
  export type { ApiConnectionAccount, ApiConnectionAttempt, ApiConnectionBoundedField, ApiConnectionDescriptor, ApiConnectionIntent, ApiConnectionRecord, ApiConnectionRevocationFailure, ApiConnectionStagedSwitch, ApiConnectionStatus, } from './types.js';
17
23
  export { createVaultOAuthTokenStore, parseOAuthTokenVaultMeta, parseTokenPayload, buildTokenPayload, type VaultOAuthTokenStore, type VaultOAuthTokenStoreDeps, type OAuthTokenVaultPort, type ReadConnectionGeneration, type OAuthConnectionOwner, type OAuthConnectionStatus, type OAuthTokenStoreErrorCode, } from './token-store/index.js';
24
+ /** Stops an issued connection using lifecycle ports only; no sign-in client or HTTP wiring.
25
+ * @complexity Selected record/token operations plus the existing bounded provider revocation.
26
+ */
27
+ export declare function disconnectApiConnection({ deps, ...connection }: {
28
+ readonly deps: ApiConnectionDisconnectDeps;
29
+ readonly connectionRef: string;
30
+ readonly workspaceId: string;
31
+ }, _optional?: Record<string, never>): Promise<import("./account-actions.js").ApiConnectionDisconnectResult>;
32
+ export { asApiConnectionHooksModule, checkApiConnectionClientNamespace, parseApiConnectionsFile, type ApiConnectionClientConfig, type ApiConnectionDeclaration, type ApiConnectionHooksModule, } from './declarations.js';
33
+ export { ConnectionBudgetExceededError, createConnectionBudgets, HOST_BUDGET_MAXIMUM, parseConnectionBudgets, type ConnectionBudget, type ConnectionBudgetLimiter, type ConnectionBudgetLimiterProfile, type ConnectionBudgets, type ConnectionBudgetScope, type ConnectionBudgetTarget, type CreateConnectionBudgetLimiter, } from './budgets.js';
34
+ export type { ApiConnectionRuntime, DeclaredApiConnection, ApiConnectionHttpOptions, PluginHttp, ApiConnectionHostRecordStore, ApiConnectionHostStorage, ApiConnectionByoCredential, ApiConnectionByoRefusal, ApiConnectionByoCredentials, ApiConnectionSharedIssuingContext, ApiConnectionSharedStorage, ApiConnectionPreparedSignIn, ApiConnectionSharedConnections, ApiConnectionSharedFactoryInput, ApiConnectionHostPorts, } from './host-ports.js';
35
+ export { byoClientLabel, resolveByoClient, type ByoClient } from './byo-client.js';
36
+ export { createConnectionHookHttp, CONNECTION_HOOK_UNDECLARED_ORIGIN_MESSAGE } from './hook-http.js';
37
+ export type { ApiConnectionSignInAttempt, ApiConnectionCallbackKey, ApiConnectionCallbackInbox, ApiConnectionStartLoopback, ApiConnectionHostMessages, ApiConnectionRuntimeHostDeps, ApiConnectionRuntimeHostOptions, ApiConnectionSignInLink, ApiConnectionConnectMessages, } from './host-ports.js';
38
+ export { createApiConnectionHost, type ApiConnectionHost } from './host.js';
39
+ export { startApiConnectionSignIn, runApiConnectionConnect, type ApiConnectionConnectDeps, type ApiConnectionConnectStatus, type ApiConnectionSignInStart } from './connect.js';
18
40
  //# sourceMappingURL=index.d.ts.map
@@ -5,6 +5,21 @@
5
5
  export { parseApiConnectionDescriptor } from './descriptor.js';
6
6
  export { createApiConnectionService } from './service.js';
7
7
  export { deriveApiConnectionKey, createApiConnectionGenerationReader } from './keys.js';
8
+ export { waitForHostedSignIn, createSignInHandoffs } from './hosted-sign-in.js';
8
9
  export { ApiConnectionError } from './errors.js';
10
+ import { disconnectApiConnection as runDisconnect } from './account-actions.js';
11
+ export { assertSharedOAuthCompatibility, createSharedOAuthConsumer } from './shared.js';
9
12
  export { createVaultOAuthTokenStore, parseOAuthTokenVaultMeta, parseTokenPayload, buildTokenPayload, } from './token-store/index.js';
13
+ /** Stops an issued connection using lifecycle ports only; no sign-in client or HTTP wiring.
14
+ * @complexity Selected record/token operations plus the existing bounded provider revocation.
15
+ */
16
+ export function disconnectApiConnection({ deps, ...connection }, _optional = {}) {
17
+ return runDisconnect(deps, connection);
18
+ }
19
+ export { asApiConnectionHooksModule, checkApiConnectionClientNamespace, parseApiConnectionsFile, } from './declarations.js';
20
+ export { ConnectionBudgetExceededError, createConnectionBudgets, HOST_BUDGET_MAXIMUM, parseConnectionBudgets, } from './budgets.js';
21
+ export { byoClientLabel, resolveByoClient } from './byo-client.js';
22
+ export { createConnectionHookHttp, CONNECTION_HOOK_UNDECLARED_ORIGIN_MESSAGE } from './hook-http.js';
23
+ export { createApiConnectionHost } from './host.js';
24
+ export { startApiConnectionSignIn, runApiConnectionConnect } from './connect.js';
10
25
  //# sourceMappingURL=index.js.map
@@ -7,7 +7,7 @@
7
7
  * `connected` with the new account. A crash between steps leaves "reconnect required", never a
8
8
  * record that claims one account while the store serves another account's token.
9
9
  */
10
- import type { OAuthTokenSet } from '@jini-ai/oauth';
10
+ import type { OAuthTokenSet } from '@jini-ai/core/contracts/oauth';
11
11
  import type { ApiConnectionServiceDeps } from './deps.js';
12
12
  import type { ApiConnectionAccount, ApiConnectionRecord } from './types.js';
13
13
  export declare function installCredential(deps: Pick<ApiConnectionServiceDeps, 'records' | 'tokens' | 'clock' | 'descriptor'>, requiredArgs: {
@@ -0,0 +1,63 @@
1
+ /**
2
+ * @file The narrow OAuth capabilities the API-connection closure uses, injected by the host so this
3
+ * entry never imports the OAuth runtime. Every member is the OAuth package's real export (or the
4
+ * real flow operations value); nothing here is a copy or a fallback.
5
+ */
6
+ import type { Clock } from '@jini-ai/core/primitives';
7
+ import type { OAuthEmptyArgs, OAuthFlowOperations, OAuthRandomBytes } from '@jini-ai/core/contracts/oauth';
8
+ import type { ApiConnectionCallbackFieldRules } from './descriptor.js';
9
+ /** The fields of a real OAuth error this closure reads after classification. */
10
+ export interface ApiConnectionOAuthError {
11
+ readonly code: string;
12
+ readonly message: string;
13
+ readonly operatorAction: string;
14
+ }
15
+ /** The generic single-use pending cache (`createPendingAuthorizationStore`'s cache overload). */
16
+ export interface ApiConnectionPendingCache<T> {
17
+ put(requiredArgs: {
18
+ state: string;
19
+ value: T;
20
+ }): void;
21
+ consume(requiredArgs: {
22
+ state: string;
23
+ }): T | null;
24
+ }
25
+ /**
26
+ * @agent-note Fulfilled by the host from `@jini-ai/oauth`, ONE object per host composition shared by every service, attempt,
27
+ * callback and hand-off it creates: `flow` = `oauthFlowOperations`; `generateState` = `generateOAuthState`; `pendingStateBytes` =
28
+ * `PENDING_AUTHORIZATION_STATE_BYTES`; `invalidPendingState` = `invalidPendingAuthorizationState`; `secureEquals` =
29
+ * `secureEqualsForOwnerBinding`; `isOAuthError` = `isOAuthError` (real `instanceof OAuthError`, so error identity, codes and
30
+ * retryability are the package's own, never matched by message); `maxAuthorizationStateLength` = `MAX_AUTHORIZATION_STATE_LENGTH`; `callbackFieldRules` = the same rules object given to
31
+ * `parseApiConnectionDescriptor` (`MAX_CALLBACK_FIELDS`, `MAX_CALLBACK_FIELD_LENGTH`, `isCallbackFieldName`);
32
+ * `createPendingAuthorizationStore` = `createPendingAuthorizationStore`. Required: there is no default or fallback.
33
+ */
34
+ export interface ApiConnectionOAuthCapabilities {
35
+ readonly flow: Pick<OAuthFlowOperations, 'beginAuthorizationCode' | 'completeAuthorizationCode' | 'createTokenRefresher' | 'refreshAccessToken'>;
36
+ readonly generateState: (requiredArgs: {
37
+ readonly randomBytesFn: OAuthRandomBytes;
38
+ }, optionalArgs?: {
39
+ readonly stateBytes?: number;
40
+ }) => string;
41
+ readonly pendingStateBytes: number;
42
+ readonly invalidPendingState: (requiredArgs: OAuthEmptyArgs) => Error;
43
+ readonly secureEquals: (requiredArgs: {
44
+ readonly a: string;
45
+ readonly b: string;
46
+ }) => boolean;
47
+ readonly isOAuthError: (input: {
48
+ readonly value: unknown;
49
+ }) => input is {
50
+ readonly value: ApiConnectionOAuthError;
51
+ };
52
+ readonly maxAuthorizationStateLength: number;
53
+ readonly callbackFieldRules: ApiConnectionCallbackFieldRules;
54
+ readonly createPendingAuthorizationStore: <T>(deps: {
55
+ readonly clock: Clock;
56
+ }, optionalArgs: {
57
+ readonly expiry: (requiredArgs: {
58
+ value: T;
59
+ ttlMs: number;
60
+ }) => number;
61
+ }) => ApiConnectionPendingCache<T>;
62
+ }
63
+ //# sourceMappingURL=oauth-capabilities.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=oauth-capabilities.js.map
@@ -5,7 +5,7 @@
5
5
  * vault-backed token store and the metadata store; the plugin owns scope sets, identity and
6
6
  * revocation. Tests use typed in-memory fakes of these same interfaces.
7
7
  */
8
- import type { OAuthTokenSet, OAuthTokenStore } from '@jini-ai/oauth';
8
+ import type { OAuthTokenSet, OAuthTokenStore } from '@jini-ai/core/contracts/oauth';
9
9
  import type { ApiConnectionAccount, ApiConnectionAttempt, ApiConnectionRecord } from './types.js';
10
10
  /**
11
11
  * Secret storage keyed by the opaque connection key; `delete` clears local tokens on disconnect.
@@ -1,3 +1,10 @@
1
+ /**
2
+ * @file Bounds checks for values a host or plugin hands to start/complete.
3
+ *
4
+ * Exists so ids, scopes, per-start parameters and provider callback fields are validated in one
5
+ * place before any state is stored or any token endpoint is called. Callback fields follow the
6
+ * plugin's allowlist: undeclared fields are dropped, declared ones must fit their declared size.
7
+ */
1
8
  import { ApiConnectionError } from './errors.js';
2
9
  import type { ApiConnectionBoundedField } from './types.js';
3
10
  export declare function requestInvalid(detail: string): ApiConnectionError;
@@ -14,5 +21,8 @@ export interface CheckedCallback {
14
21
  readonly error?: string;
15
22
  }
16
23
  /** Bound the raw callback before anything is consumed; OAuth names are validated by the core. */
17
- export declare function checkCallbackParams(value: Readonly<Record<string, string>>): CheckedCallback;
24
+ export declare function checkCallbackParams(value: Readonly<Record<string, string>>, limits: {
25
+ readonly maxAuthorizationStateLength: number;
26
+ readonly maxCallbackFieldLength: number;
27
+ }): CheckedCallback;
18
28
  //# sourceMappingURL=request-checks.d.ts.map
@@ -5,7 +5,6 @@
5
5
  * place before any state is stored or any token endpoint is called. Callback fields follow the
6
6
  * plugin's allowlist: undeclared fields are dropped, declared ones must fit their declared size.
7
7
  */
8
- import { MAX_AUTHORIZATION_STATE_LENGTH, MAX_CALLBACK_FIELD_LENGTH } from '@jini-ai/oauth';
9
8
  import { ApiConnectionError } from './errors.js';
10
9
  const MAX_ID_LENGTH = 256;
11
10
  const MAX_SCOPES = 64;
@@ -52,10 +51,10 @@ export function checkStartParams(fields, values) {
52
51
  return pickBoundedFields(fields, values, 'start parameter');
53
52
  }
54
53
  /** Bound the raw callback before anything is consumed; OAuth names are validated by the core. */
55
- export function checkCallbackParams(value) {
54
+ export function checkCallbackParams(value, limits) {
56
55
  const entries = Object.entries(value);
57
56
  if (entries.length > MAX_CALLBACK_PARAMS
58
- || !entries.every(([, raw]) => typeof raw === 'string' && raw.length <= Math.max(MAX_CALLBACK_FIELD_LENGTH, MAX_AUTHORIZATION_STATE_LENGTH))) {
57
+ || !entries.every(([, raw]) => typeof raw === 'string' && raw.length <= Math.max(limits.maxCallbackFieldLength, limits.maxAuthorizationStateLength))) {
59
58
  throw requestInvalid('the callback carried too many or oversized fields');
60
59
  }
61
60
  const checked = {};
@@ -0,0 +1,79 @@
1
+ import type { ApiConnectionAccount, ApiConnectionStatus } from './types.js';
2
+ /** Trusted declaration to match; a consuming site's own client must never replace the issuer's. */
3
+ export interface SharedOAuthIdentity {
4
+ readonly pluginId: string;
5
+ readonly connectionId: string;
6
+ readonly tokenEndpoint: string;
7
+ readonly authorizationEndpoint?: string;
8
+ readonly issuer?: string;
9
+ readonly resource?: string;
10
+ /** Optional pin to the saved client; omit when the consumer has a different local client. */
11
+ readonly clientId?: string;
12
+ }
13
+ /** Public owner metadata. Secret issuing context and tokens never belong in this value. */
14
+ export interface SharedOAuthConnection {
15
+ readonly credentialId: string;
16
+ readonly identity: SharedOAuthIdentity & {
17
+ readonly clientId: string;
18
+ };
19
+ readonly generation: number;
20
+ readonly status: ApiConnectionStatus;
21
+ readonly account: ApiConnectionAccount | null;
22
+ readonly grantedScopes: readonly string[];
23
+ }
24
+ /** A binding uses the immutable site UUID: workspace-local is deliberately shared by sites. */
25
+ export interface SharedOAuthConsumerTarget {
26
+ readonly siteId: string;
27
+ readonly consumerId: string;
28
+ readonly identity: SharedOAuthIdentity;
29
+ readonly requiredScopes: readonly string[];
30
+ readonly expectedAccountId?: string;
31
+ }
32
+ type ConsumerIdentity = Pick<SharedOAuthConsumerTarget, 'siteId' | 'consumerId'>;
33
+ export interface SharedOAuthConsumerDeps {
34
+ readonly bindings: {
35
+ read(requiredArgs: ConsumerIdentity): Promise<{
36
+ readonly credentialId: string;
37
+ } | null>;
38
+ };
39
+ readonly grants: {
40
+ isGranted(requiredArgs: ConsumerIdentity & {
41
+ readonly credentialId: string;
42
+ }): Promise<boolean>;
43
+ };
44
+ /** Owner adapter: reuse its service/refresher per credential in this process; never cache grants. */
45
+ readonly connections: {
46
+ read(requiredArgs: {
47
+ readonly credentialId: string;
48
+ }): Promise<SharedOAuthConnection | null>;
49
+ getAccessToken(requiredArgs: {
50
+ readonly credentialId: string;
51
+ readonly expectedGeneration: number;
52
+ readonly expectedAccountId?: string;
53
+ }): Promise<string>;
54
+ };
55
+ }
56
+ /**
57
+ * Validates public owner metadata before a user-approved grant is written. It does not authorize
58
+ * consumption: every token request must still use the consumer's live binding/grant checks.
59
+ * @complexity O(g + r) for granted/requested scopes; no storage or token I/O.
60
+ */
61
+ export declare function assertSharedOAuthCompatibility({ connection, target }: {
62
+ readonly connection: SharedOAuthConnection;
63
+ readonly target: SharedOAuthConsumerTarget;
64
+ }, _optionalArgs?: Record<string, never>): void;
65
+ /**
66
+ * Creates a live shared-connection consumer. Only an absent binding returns null status; a
67
+ * selected but revoked binding always refuses, so hosts cannot silently fall back to local keys.
68
+ * @complexity Each check reads one binding, one grant and one owner record; scope checks are
69
+ * O(g + r), for granted and requested scopes. Token requests perform two checks and one owner
70
+ * token acquisition; there is no polling, vault scan, cached authorization or site secret write.
71
+ */
72
+ export declare function createSharedOAuthConsumer(deps: SharedOAuthConsumerDeps, _optionalArgs?: Record<string, never>): {
73
+ getStatus: (target: SharedOAuthConsumerTarget, _options?: Record<string, never>) => Promise<SharedOAuthConnection | null>;
74
+ assertAuthorized(target: SharedOAuthConsumerTarget, _options?: Record<string, never>): Promise<void>;
75
+ getAccessToken(target: SharedOAuthConsumerTarget, _options?: Record<string, never>): Promise<string>;
76
+ };
77
+ export type SharedOAuthConsumer = ReturnType<typeof createSharedOAuthConsumer>;
78
+ export {};
79
+ //# sourceMappingURL=shared.d.ts.map
@@ -0,0 +1,106 @@
1
+ /**
2
+ * @file Consumes an explicitly shared OAuth connection without exposing owner credentials.
3
+ * The host keeps issuing clients, refresh tokens and refreshers in its owner store. This port
4
+ * checks the selected binding and live site grant on every use, including after a refresh.
5
+ */
6
+ import { ApiConnectionError } from './errors.js';
7
+ function unavailable() {
8
+ return new ApiConnectionError({ code: 'connection-not-found',
9
+ message: 'The selected shared connection does not match this connection. Choose a compatible saved connection or connect locally.' });
10
+ }
11
+ function denied() {
12
+ return new ApiConnectionError({ code: 'access-denied',
13
+ message: 'Permission to use the selected shared connection was removed. Choose it again in the connection settings to request access.' });
14
+ }
15
+ /**
16
+ * Validates public owner metadata before a user-approved grant is written. It does not authorize
17
+ * consumption: every token request must still use the consumer's live binding/grant checks.
18
+ * @complexity O(g + r) for granted/requested scopes; no storage or token I/O.
19
+ */
20
+ export function assertSharedOAuthCompatibility({ connection, target }, _optionalArgs = {}) {
21
+ const fields = ['pluginId', 'connectionId', 'tokenEndpoint', 'authorizationEndpoint', 'issuer', 'resource'];
22
+ if (fields.some(field => connection.identity[field] !== target.identity[field]))
23
+ throw unavailable();
24
+ if (target.identity.clientId !== undefined && connection.identity.clientId !== target.identity.clientId)
25
+ throw unavailable();
26
+ const granted = new Set(connection.grantedScopes);
27
+ if (target.requiredScopes.some(scope => !granted.has(scope))) {
28
+ throw new ApiConnectionError({ code: 'scope-not-granted',
29
+ message: 'The selected shared connection does not grant the access this connection needs. Reconnect the shared account with the required permissions.' });
30
+ }
31
+ if (target.expectedAccountId !== undefined && connection.account?.accountId !== target.expectedAccountId) {
32
+ throw new ApiConnectionError({ code: 'account-changed',
33
+ message: 'The selected shared connection now uses a different account. Review the selected account in the connection settings.' });
34
+ }
35
+ }
36
+ function assertConnected(connection) {
37
+ if (connection.status === 'connected')
38
+ return;
39
+ if (connection.status === 'reconnect-required') {
40
+ throw new ApiConnectionError({ code: 'reconnect-required', message: 'The shared connection needs a new sign-in. Reconnect the shared account in the connection settings.' });
41
+ }
42
+ if (connection.status === 'revocation-pending') {
43
+ throw new ApiConnectionError({ code: 'revocation-pending', message: 'The shared connection was stopped on every site. Its owner can retry provider revocation in the shared connection settings.' });
44
+ }
45
+ throw new ApiConnectionError({ code: 'not-connected', message: 'The shared connection is disconnected. Choose a connected saved account or connect locally.' });
46
+ }
47
+ /** Copy only public fields, protecting both snapshots and status output from adapter extras. */
48
+ function publicConnection(connection) {
49
+ const identity = connection.identity;
50
+ return { credentialId: connection.credentialId, generation: connection.generation, status: connection.status,
51
+ identity: { pluginId: identity.pluginId, connectionId: identity.connectionId, tokenEndpoint: identity.tokenEndpoint,
52
+ clientId: identity.clientId, ...(identity.issuer === undefined ? {} : { issuer: identity.issuer }),
53
+ ...(identity.authorizationEndpoint === undefined ? {} : { authorizationEndpoint: identity.authorizationEndpoint }),
54
+ ...(identity.resource === undefined ? {} : { resource: identity.resource }) },
55
+ account: connection.account === null ? null : { accountId: connection.account.accountId, displayName: connection.account.displayName },
56
+ grantedScopes: [...connection.grantedScopes] };
57
+ }
58
+ /**
59
+ * Creates a live shared-connection consumer. Only an absent binding returns null status; a
60
+ * selected but revoked binding always refuses, so hosts cannot silently fall back to local keys.
61
+ * @complexity Each check reads one binding, one grant and one owner record; scope checks are
62
+ * O(g + r), for granted and requested scopes. Token requests perform two checks and one owner
63
+ * token acquisition; there is no polling, vault scan, cached authorization or site secret write.
64
+ */
65
+ export function createSharedOAuthConsumer(deps, _optionalArgs = {}) {
66
+ async function checked(target) {
67
+ const consumer = { siteId: target.siteId, consumerId: target.consumerId };
68
+ const binding = await deps.bindings.read(consumer);
69
+ if (binding === null)
70
+ return null;
71
+ if (!await deps.grants.isGranted({ ...consumer, credentialId: binding.credentialId }))
72
+ throw denied();
73
+ const connection = await deps.connections.read({ credentialId: binding.credentialId });
74
+ if (connection === null || connection.credentialId !== binding.credentialId)
75
+ throw unavailable();
76
+ assertSharedOAuthCompatibility({ connection, target });
77
+ return publicConnection(connection);
78
+ }
79
+ async function connected(target) {
80
+ const connection = await checked(target);
81
+ if (connection === null)
82
+ throw denied();
83
+ assertConnected(connection);
84
+ return connection;
85
+ }
86
+ return {
87
+ getStatus: (target, _options = {}) => checked(target),
88
+ async assertAuthorized(target, _options = {}) {
89
+ await connected(target);
90
+ },
91
+ async getAccessToken(target, _options = {}) {
92
+ const before = await connected(target);
93
+ const expectedAccountId = before.account?.accountId;
94
+ const token = await deps.connections.getAccessToken({ credentialId: before.credentialId, expectedGeneration: before.generation,
95
+ ...(expectedAccountId === undefined ? {} : { expectedAccountId }) });
96
+ const after = await connected(target);
97
+ if (after.credentialId !== before.credentialId || after.generation !== before.generation
98
+ || after.identity.clientId !== before.identity.clientId || after.account?.accountId !== expectedAccountId) {
99
+ throw new ApiConnectionError({ code: 'storage-conflict',
100
+ message: 'The shared connection changed while this request was running. Review its status and retry.' });
101
+ }
102
+ return token;
103
+ },
104
+ };
105
+ }
106
+ //# sourceMappingURL=shared.js.map
@@ -2,8 +2,8 @@
2
2
  * Exists so every read is checked the same way before a token leaves the store: the OAuth
3
3
  * discriminator, the expected connection owner and the token shape. Secrets live only in the
4
4
  * sealed payload; the plaintext metadata holds the discriminator, status and lease fields. */
5
- import type { OAuthTokenSet } from "@jini-ai/oauth";
6
- import type { VaultMeta } from "@jini-ai/platform/secrets/credential-sets";
5
+ import type { OAuthTokenSet } from "@jini-ai/core/contracts/oauth";
6
+ import type { VaultMeta } from "@jini-ai/core/contracts/vault";
7
7
  /** Who a stored token set belongs to. Every read must match all four ids exactly. */
8
8
  export interface OAuthConnectionOwner {
9
9
  readonly workspaceId: string;
@@ -1,10 +1,32 @@
1
1
  import type { Clock } from "@jini-ai/core/primitives";
2
- import type { OAuthTokenStore } from "@jini-ai/oauth";
3
- import { type SecretsVaultService, type VaultContext } from "@jini-ai/platform/secrets/credential-sets";
2
+ import type { OAuthTokenStore } from "@jini-ai/core/contracts/oauth";
3
+ import type { VaultContext, VaultIdentity, VaultMeta, VaultSummary } from "@jini-ai/core/contracts/vault";
4
4
  import type { ApiConnectionTokenStore } from "../ports.js";
5
5
  import { type OAuthConnectionOwner } from "./record.js";
6
- /** The vault operations this store uses; `SecretsVaultService` satisfies it. */
7
- export type OAuthTokenVaultPort = Pick<SecretsVaultService, "get" | "put" | "patchMeta" | "delete">;
6
+ /** The vault operations this store uses; `SecretsVaultService` satisfies it.
7
+ * @agent-note Fulfilled by the host's real secrets vault service (the same instance the record store and archive use); exactly
8
+ * these four operations, with their CAS `expectedRevision` semantics and conflict errors unchanged. */
9
+ export interface OAuthTokenVaultPort {
10
+ get(input: VaultIdentity): Promise<{
11
+ summary: VaultSummary;
12
+ payload: VaultMeta | null;
13
+ } | null>;
14
+ put(input: VaultContext & {
15
+ id?: string;
16
+ expectedRevision: number | null;
17
+ provider: string | null;
18
+ label: string;
19
+ meta: unknown;
20
+ payload?: VaultMeta | null | undefined;
21
+ }): Promise<VaultSummary>;
22
+ patchMeta(input: VaultIdentity & {
23
+ expectedRevision: number;
24
+ patch: VaultMeta;
25
+ }): Promise<VaultSummary>;
26
+ delete(input: VaultIdentity & {
27
+ expectedRevision: number;
28
+ }): Promise<boolean>;
29
+ }
8
30
  /** Current generation of a connection. The host bumps it on disconnect, switch and reconnect. */
9
31
  export type ReadConnectionGeneration = (requiredArgs: {
10
32
  readonly key: string;
@@ -16,6 +38,10 @@ export interface VaultOAuthTokenStoreDeps {
16
38
  readonly owner: OAuthConnectionOwner;
17
39
  readonly readGeneration: ReadConnectionGeneration;
18
40
  readonly clock: Clock;
41
+ /** @agent-note Required real vault-conflict classifier from the host (`error instanceof VaultError && error.code === "conflict"`
42
+ * for the vault service bound above); it decides lease-lost mapping, CAS retries and lease refusal, so it must recognise exactly
43
+ * that service's conflict error and nothing else. */
44
+ readonly isVaultConflict: (error: unknown) => boolean;
19
45
  }
20
46
  /** `OAuthTokenStore` plus install and disconnect. Refresh writes (`persist`, `markNeedsReauth`)
21
47
  * require the lease; `install` is fenced by its generation instead. */
@@ -9,7 +9,6 @@
9
9
  * A sign-in install is not a refresh, so it takes no lease: it is fenced by the generation the
10
10
  * caller moved the connection to, and never overwrites a newer generation's tokens. */
11
11
  import { randomUUID } from "node:crypto";
12
- import { VaultError } from "@jini-ai/platform/secrets/credential-sets";
13
12
  import { OAuthTokenStoreError } from "./errors.js";
14
13
  import { buildRecordMeta, buildTokenPayload, parseTokenPayload, parseTokenSet, readRecordMeta, readReplaceableGeneration } from "./record.js";
15
14
  /** A crashed holder's lease frees itself after this long; longer than any single token request. */
@@ -18,13 +17,11 @@ const LEASE_TTL_MS = 30_000;
18
17
  const LOAD_OBSERVATION_WINDOW_MS = 60_000;
19
18
  /** Disconnect and install must win over concurrent lease writes; each retry re-reads the newest revision. */
20
19
  const WRITE_ATTEMPTS = 3;
21
- function isConflict(error) {
22
- return error instanceof VaultError && error.code === "conflict";
23
- }
24
20
  /** Creates the store for one connection owner.
25
21
  * @throws OAuthTokenStoreError `configuration` when the vault scope names another workspace. */
26
22
  export function createVaultOAuthTokenStore(deps, _optionalArgs = {}) {
27
23
  const { vault, vaultScope, owner, readGeneration, clock } = deps;
24
+ const isConflict = deps.isVaultConflict;
28
25
  if (vaultScope.workspaceId !== owner.workspaceId)
29
26
  throw new OAuthTokenStoreError({ code: "configuration" });
30
27
  // Leases this instance holds, with the generation recorded at acquisition (the write fence).