@jini-ai/integrations 0.4.1 → 0.4.3

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 (146) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/api-connections/access-token.d.ts +9 -0
  3. package/dist/api-connections/access-token.js +92 -0
  4. package/dist/api-connections/account-actions.d.ts +40 -0
  5. package/dist/api-connections/account-actions.js +110 -0
  6. package/dist/api-connections/attempt-state.d.ts +28 -0
  7. package/dist/api-connections/attempt-state.js +73 -0
  8. package/dist/api-connections/authorization.d.ts +45 -0
  9. package/dist/api-connections/authorization.js +120 -0
  10. package/dist/api-connections/deps.d.ts +41 -0
  11. package/dist/api-connections/deps.js +13 -0
  12. package/dist/api-connections/descriptor.d.ts +6 -0
  13. package/dist/api-connections/descriptor.js +111 -0
  14. package/dist/api-connections/errors.d.ts +23 -0
  15. package/dist/api-connections/errors.js +24 -0
  16. package/dist/api-connections/finish-authorization.d.ts +24 -0
  17. package/dist/api-connections/finish-authorization.js +117 -0
  18. package/dist/api-connections/index.d.ts +18 -0
  19. package/dist/api-connections/index.js +10 -0
  20. package/dist/api-connections/install-credential.d.ts +19 -0
  21. package/dist/api-connections/install-credential.js +12 -0
  22. package/dist/api-connections/keys.d.ts +27 -0
  23. package/dist/api-connections/keys.js +22 -0
  24. package/dist/api-connections/ports.d.ts +73 -0
  25. package/dist/api-connections/ports.js +2 -0
  26. package/dist/api-connections/records.d.ts +27 -0
  27. package/dist/api-connections/records.js +52 -0
  28. package/dist/api-connections/request-checks.d.ts +18 -0
  29. package/dist/api-connections/request-checks.js +67 -0
  30. package/dist/api-connections/service.d.ts +25 -0
  31. package/dist/api-connections/service.js +26 -0
  32. package/dist/api-connections/status.d.ts +28 -0
  33. package/dist/api-connections/status.js +36 -0
  34. package/dist/api-connections/token-store/errors.d.ts +20 -0
  35. package/dist/api-connections/token-store/errors.js +38 -0
  36. package/dist/api-connections/token-store/index.d.ts +6 -0
  37. package/dist/api-connections/token-store/index.js +6 -0
  38. package/dist/api-connections/token-store/record.d.ts +69 -0
  39. package/dist/api-connections/token-store/record.js +97 -0
  40. package/dist/api-connections/token-store/vault-token-store.d.ts +26 -0
  41. package/dist/api-connections/token-store/vault-token-store.js +215 -0
  42. package/dist/api-connections/types.d.ts +101 -0
  43. package/dist/api-connections/types.js +9 -0
  44. package/dist/credentialed-http/auth-schemes.js +8 -4
  45. package/dist/credentialed-http/credentialed-request.js +47 -77
  46. package/dist/credentialed-http/response-redaction.d.ts +5 -0
  47. package/dist/credentialed-http/response-redaction.js +62 -0
  48. package/dist/media-providers/catalog.d.ts +3 -1
  49. package/dist/media-providers/catalog.js +3 -1
  50. package/dist/media-providers/dispatch/async-operation-store.d.ts +31 -0
  51. package/dist/media-providers/dispatch/async-operation-store.js +75 -37
  52. package/dist/media-providers/dispatch/builtin-vendors.d.ts +1 -1
  53. package/dist/media-providers/dispatch/context.js +10 -2
  54. package/dist/media-providers/dispatch/credentials.d.ts +1 -1
  55. package/dist/media-providers/dispatch/credentials.js +3 -3
  56. package/dist/media-providers/dispatch/engine.d.ts +6 -3
  57. package/dist/media-providers/dispatch/engine.js +102 -109
  58. package/dist/media-providers/dispatch/index.d.ts +4 -2
  59. package/dist/media-providers/dispatch/index.js +3 -1
  60. package/dist/media-providers/dispatch/media-provider-registry.d.ts +62 -0
  61. package/dist/media-providers/dispatch/media-provider-registry.js +141 -0
  62. package/dist/media-providers/dispatch/node.d.ts +13 -0
  63. package/dist/media-providers/dispatch/node.js +24 -0
  64. package/dist/media-providers/dispatch/openai-compatible.d.ts +1 -1
  65. package/dist/media-providers/dispatch/openai-compatible.js +90 -87
  66. package/dist/media-providers/dispatch/operation-runtime.js +116 -89
  67. package/dist/media-providers/dispatch/outbound.d.ts +8 -4
  68. package/dist/media-providers/dispatch/outbound.js +27 -26
  69. package/dist/media-providers/dispatch/providers/aihubmix.d.ts +1 -1
  70. package/dist/media-providers/dispatch/providers/aihubmix.js +61 -56
  71. package/dist/media-providers/dispatch/providers/custom-image.d.ts +1 -1
  72. package/dist/media-providers/dispatch/providers/elevenlabs.d.ts +1 -1
  73. package/dist/media-providers/dispatch/providers/fishaudio.d.ts +1 -1
  74. package/dist/media-providers/dispatch/providers/grok.d.ts +1 -1
  75. package/dist/media-providers/dispatch/providers/imagerouter-video-async.d.ts +1 -1
  76. package/dist/media-providers/dispatch/providers/imagerouter-video-async.js +53 -49
  77. package/dist/media-providers/dispatch/providers/imagerouter.d.ts +1 -1
  78. package/dist/media-providers/dispatch/providers/imagerouter.js +11 -24
  79. package/dist/media-providers/dispatch/providers/minimax.d.ts +1 -1
  80. package/dist/media-providers/dispatch/providers/nanobanana.d.ts +1 -1
  81. package/dist/media-providers/dispatch/providers/nanobanana.js +22 -30
  82. package/dist/media-providers/dispatch/providers/openai.d.ts +1 -1
  83. package/dist/media-providers/dispatch/providers/openai.js +51 -47
  84. package/dist/media-providers/dispatch/providers/openrouter.d.ts +1 -1
  85. package/dist/media-providers/dispatch/providers/openrouter.js +52 -37
  86. package/dist/media-providers/dispatch/providers/senseaudio.d.ts +1 -1
  87. package/dist/media-providers/dispatch/providers/senseaudio.js +47 -28
  88. package/dist/media-providers/dispatch/providers/volcengine.d.ts +1 -1
  89. package/dist/media-providers/dispatch/response-parsers.js +37 -21
  90. package/dist/media-providers/dispatch/sqlite-async-operation-store.d.ts +35 -1
  91. package/dist/media-providers/dispatch/sqlite-async-operation-store.js +13 -32
  92. package/dist/media-providers/dispatch/ssrf-guard.d.ts +3 -2
  93. package/dist/media-providers/dispatch/ssrf-guard.js +6 -5
  94. package/dist/media-providers/dispatch/types.d.ts +76 -2
  95. package/dist/media-providers/dispatch/vendor-adapter.d.ts +2 -43
  96. package/dist/media-providers/dispatch/vendor-adapter.js +2 -2
  97. package/dist/media-providers/dispatch/vendor-registry-core.d.ts +24 -0
  98. package/dist/media-providers/dispatch/vendor-registry-core.js +34 -0
  99. package/dist/media-providers/dispatch/vendor-registry.d.ts +10 -36
  100. package/dist/media-providers/dispatch/vendor-registry.js +14 -42
  101. package/dist/media-providers/policy.js +25 -17
  102. package/dist/media-providers/providers.d.ts +39 -0
  103. package/dist/media-providers/providers.js +50 -18
  104. package/dist/media-providers/sqlite-driver.adapter.d.ts +4 -0
  105. package/dist/media-providers/sqlite-driver.adapter.js +5 -0
  106. package/dist/media-providers/sqlite-task-store.d.ts +50 -2
  107. package/dist/media-providers/sqlite-task-store.js +20 -84
  108. package/dist/media-providers/staging.js +77 -58
  109. package/dist/media-providers/task-lifecycle.d.ts +33 -0
  110. package/dist/media-providers/task-lifecycle.js +124 -0
  111. package/dist/media-providers/task-store.js +8 -86
  112. package/dist/media-providers/ui-defaults.d.ts +10 -0
  113. package/dist/media-providers/ui-defaults.js +167 -0
  114. package/dist/media-providers/video-request.js +112 -90
  115. package/dist/webhooks/delivery.d.ts +14 -0
  116. package/dist/webhooks/delivery.js +41 -10
  117. package/dist/webhooks/index.d.ts +1 -0
  118. package/dist/webhooks/index.js +1 -0
  119. package/dist/webhooks/ports.d.ts +23 -0
  120. package/dist/webhooks/subscriptions.d.ts +1 -1
  121. package/dist/webhooks/subscriptions.js +5 -1
  122. package/dist/webhooks/worker.d.ts +83 -0
  123. package/dist/webhooks/worker.js +105 -0
  124. package/package.json +35 -7
  125. package/dist/composio/bounded-data.d.ts +0 -36
  126. package/dist/composio/bounded-data.js +0 -181
  127. package/dist/composio/catalog.d.ts +0 -147
  128. package/dist/composio/catalog.js +0 -126
  129. package/dist/composio/composio-config.d.ts +0 -42
  130. package/dist/composio/composio-config.js +0 -145
  131. package/dist/composio/composio-descriptions.d.ts +0 -16
  132. package/dist/composio/composio-descriptions.js +0 -766
  133. package/dist/composio/composio.d.ts +0 -364
  134. package/dist/composio/composio.js +0 -1902
  135. package/dist/composio/errors.d.ts +0 -15
  136. package/dist/composio/errors.js +0 -16
  137. package/dist/composio/file-lock.d.ts +0 -13
  138. package/dist/composio/file-lock.js +0 -92
  139. package/dist/composio/index.d.ts +0 -18
  140. package/dist/composio/index.js +0 -7
  141. package/dist/composio/json-schema.d.ts +0 -93
  142. package/dist/composio/json-schema.js +0 -498
  143. package/dist/composio/output-protection.d.ts +0 -32
  144. package/dist/composio/output-protection.js +0 -105
  145. package/dist/composio/service.d.ts +0 -181
  146. package/dist/composio/service.js +0 -758
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.3 — 2026-10-22
4
+
5
+ - 2026-10-22: Webhook delivery deadlines, leases and fencing; media-provider model-id collision refusal; provider contributions.
6
+
7
+ ### Minor Changes
8
+
9
+ - media-providers: vendors are one-unit provider contributions (`{ provider, models, adapters }`) on the
10
+ shared `@jini-ai/core/provider-registry` (contract `media`). `createMediaProviderRegistry()` (built-ins
11
+ are the default contribution set; plugins `contribute`, refused not thrown) implements both
12
+ `VendorAdapterLookup` and the new `MediaModelCatalog`. `createMediaDispatchEngine` takes an optional
13
+ `catalog`, so plugin models validate; omitted, behaviour is unchanged. Registry keys map `-` to `_`;
14
+ public provider ids are unchanged.
15
+
3
16
  ## 0.4.1
4
17
 
5
18
  ### Patch Changes
@@ -0,0 +1,9 @@
1
+ import type { ApiConnectionServiceDeps } from './deps.js';
2
+ import { type OwnedRecordArgs } from './records.js';
3
+ export interface ApiConnectionAccessTokens {
4
+ getAccessToken(requiredArgs: OwnedRecordArgs, optionalArgs?: {
5
+ readonly expectedAccountId?: string;
6
+ }): Promise<string>;
7
+ }
8
+ export declare function createApiConnectionAccessTokens(deps: ApiConnectionServiceDeps): ApiConnectionAccessTokens;
9
+ //# sourceMappingURL=access-token.d.ts.map
@@ -0,0 +1,92 @@
1
+ /**
2
+ * @file Serves access tokens for a connection, refreshing through the OAuth core's refresher.
3
+ *
4
+ * Exists so plugin tool and delivery code never touch refresh tokens: they ask for an access
5
+ * token by `connectionRef` immediately before an HTTP call. Only `connected` records are served,
6
+ * an optional frozen account id stops a binding from silently following an account switch (checked
7
+ * again after the token is read, so a switch landing in between cannot leak through), and a
8
+ * rejected refresh or unreadable credential moves the record to `reconnect-required`. Unreadable
9
+ * credentials are preserved, and their internal store errors become a clear reconnect instruction.
10
+ */
11
+ import { createTokenRefresher, OAuthError, refreshAccessToken } from '@jini-ai/oauth';
12
+ import { ApiConnectionError } from './errors.js';
13
+ import { loadOwnedRecord, writeRecord } from './records.js';
14
+ import { isUnreadableTokenRecord } from './token-store/errors.js';
15
+ const REFUSALS = {
16
+ 'reconnect-required': { code: 'reconnect-required', message: 'This connection needs to be reconnected. Reconnect the account in the connection settings.' },
17
+ 'revocation-pending': { code: 'revocation-pending', message: 'This connection was disconnected. Finish disconnecting or connect again.' },
18
+ disconnected: { code: 'not-connected', message: 'This connection is not connected. Connect the account first.' },
19
+ };
20
+ function assertServable(record, expectedAccountId) {
21
+ if (record.status !== 'connected')
22
+ throw new ApiConnectionError(REFUSALS[record.status]);
23
+ if (expectedAccountId !== undefined && record.account?.accountId !== expectedAccountId) {
24
+ throw new ApiConnectionError({ code: 'account-changed',
25
+ message: 'This connection now uses a different account than this task was set up with. Review the task and reassign it.' });
26
+ }
27
+ }
28
+ /**
29
+ * Status write after a terminal credential failure; only a still-connected record is downgraded.
30
+ * When a failed read names a generation, a newer sign-in is left alone. Revision CAS also
31
+ * protects changes landing after this read. Tokens are preserved; storage failures propagate.
32
+ * @complexity One record read and at most one CAS write.
33
+ */
34
+ async function markReconnectRequired(deps, key, options = {}) {
35
+ const record = await deps.records.read({ key });
36
+ if (record?.status !== 'connected')
37
+ return;
38
+ if (options.expectedGeneration !== undefined && record.generation !== options.expectedGeneration)
39
+ return;
40
+ await writeRecord(deps, record, { status: 'reconnect-required' });
41
+ }
42
+ /**
43
+ * The token store reads the live generation, so a confirmed switch, disconnect or reconnect that
44
+ * landed between the record check and the token read could hand over another credential: refuse
45
+ * unless the record still serves the same generation. A retry reads the new state consistently.
46
+ */
47
+ async function assertUnchangedSince(deps, requiredArgs) {
48
+ const current = await loadOwnedRecord(deps, requiredArgs);
49
+ assertServable(current, requiredArgs.expectedAccountId);
50
+ if (current.generation !== requiredArgs.checked.generation) {
51
+ throw new ApiConnectionError({ code: 'storage-conflict',
52
+ message: 'This connection changed while the request was running. Reload its status and try again.' });
53
+ }
54
+ }
55
+ function refreshPort(deps) {
56
+ const { tokens } = deps;
57
+ return {
58
+ load: args => tokens.load(args),
59
+ persist: args => tokens.persist(args),
60
+ async markNeedsReauth(args) {
61
+ await tokens.markNeedsReauth(args);
62
+ await markReconnectRequired(deps, args.key);
63
+ },
64
+ ...(tokens.tryAcquireRefreshLease ? { tryAcquireRefreshLease: tokens.tryAcquireRefreshLease.bind(tokens) } : {}),
65
+ ...(tokens.releaseRefreshLease ? { releaseRefreshLease: tokens.releaseRefreshLease.bind(tokens) } : {}),
66
+ refresh: ({ refreshToken }) => refreshAccessToken({ fetchFn: deps.fetchFn, guard: deps.guard, clock: deps.clock,
67
+ tokenEndpoint: deps.descriptor.tokenEndpoint, client: deps.client, refreshToken }),
68
+ };
69
+ }
70
+ export function createApiConnectionAccessTokens(deps) {
71
+ const refresher = createTokenRefresher({ clock: deps.clock, sleep: deps.sleep, port: refreshPort(deps) });
72
+ return {
73
+ async getAccessToken(requiredArgs, optionalArgs = {}) {
74
+ const { expectedAccountId } = optionalArgs;
75
+ const record = await loadOwnedRecord(deps, requiredArgs);
76
+ assertServable(record, expectedAccountId);
77
+ const accessToken = await refresher.getAccessToken({ key: record.key }).catch(async (error) => {
78
+ if (isUnreadableTokenRecord(error)) {
79
+ await markReconnectRequired(deps, record.key, { expectedGeneration: record.generation });
80
+ throw new ApiConnectionError(REFUSALS['reconnect-required'], { cause: error });
81
+ }
82
+ if (error instanceof OAuthError && error.code === 'OAUTH_INVALID_GRANT') {
83
+ throw new ApiConnectionError(REFUSALS['reconnect-required'], { cause: error });
84
+ }
85
+ throw error;
86
+ });
87
+ await assertUnchangedSince(deps, { ...requiredArgs, checked: record, expectedAccountId });
88
+ return accessToken;
89
+ },
90
+ };
91
+ }
92
+ //# sourceMappingURL=access-token.js.map
@@ -0,0 +1,40 @@
1
+ /**
2
+ * @file Account actions after sign-in: confirm or cancel a staged switch, and disconnect.
3
+ *
4
+ * Exists so the rules owners care about live in one place: a switch only takes effect on an
5
+ * explicit confirm by the actor who staged it, against the generation it was staged on; a
6
+ * disconnect stops use first, then asks the plugin to revoke remotely, clears local tokens only
7
+ * after the provider confirmed, and otherwise stays `revocation-pending` with the disabled
8
+ * credential kept for a retry. Remote success is never reported unless the hook returned.
9
+ */
10
+ import type { ApiConnectionServiceDeps } from './deps.js';
11
+ import { type OwnedRecordArgs } from './records.js';
12
+ import { type ApiConnectionStatusView } from './status.js';
13
+ /**
14
+ * `not-needed` when no credential existed locally, so nothing could be revoked. `pending` with
15
+ * status `revocation-pending` means the disabled credential is kept and disconnecting again
16
+ * retries; `pending` with status `disconnected` means the stored credential could not be read
17
+ * (for example the host changed its OAuth client), so it was removed locally and the person has
18
+ * to remove the access on the provider's account page.
19
+ */
20
+ export type ApiConnectionRemoteRevocation = 'confirmed' | 'pending' | 'not-needed';
21
+ export interface ApiConnectionDisconnectResult extends ApiConnectionStatusView {
22
+ readonly remoteRevocation: ApiConnectionRemoteRevocation;
23
+ }
24
+ /**
25
+ * A confirmed switch never revokes the previous account's grant at the provider: revoking it could
26
+ * cut off the same account connected elsewhere through the same client. Hosts say so and link the
27
+ * provider's account-access page; the local copy of its tokens is gone.
28
+ */
29
+ export type ApiConnectionSwitchResult = ApiConnectionStatusView;
30
+ export declare function confirmSwitchAccount(deps: ApiConnectionServiceDeps, requiredArgs: OwnedRecordArgs & {
31
+ readonly actorId: string;
32
+ }): Promise<ApiConnectionSwitchResult>;
33
+ /**
34
+ * Drop a staged switch, revoking its tokens because the person consented to them. When the
35
+ * provider does not confirm, the switch stays staged (still confirmable) and cancelling again retries.
36
+ */
37
+ export declare function cancelSwitchAccount(deps: ApiConnectionServiceDeps, requiredArgs: OwnedRecordArgs): Promise<ApiConnectionDisconnectResult>;
38
+ /** Disconnect and revoke the live and any staged credential; call again to retry a `pending` revocation. */
39
+ export declare function disconnectApiConnection(deps: ApiConnectionServiceDeps, requiredArgs: OwnedRecordArgs): Promise<ApiConnectionDisconnectResult>;
40
+ //# sourceMappingURL=account-actions.d.ts.map
@@ -0,0 +1,110 @@
1
+ import { ApiConnectionError } from './errors.js';
2
+ import { installCredential } from './install-credential.js';
3
+ import { isUnreadableTokenRecord } from './token-store/errors.js';
4
+ import { stagedTokenKey } from './keys.js';
5
+ import { loadOwnedRecord, writeRecord } from './records.js';
6
+ import { toStatusView } from './status.js';
7
+ /** Classifications a revoke hook may put on its error's `code`; anything else is `unclassified`. */
8
+ const HOOK_FAILURE_CODES = new Set(['provider-unreachable', 'provider-refused']);
9
+ /** Read only the hook's `code`, and only when it is a known classification: its message may echo provider bodies. */
10
+ function hookFailureOf(error) {
11
+ // A hook may throw anything, `undefined` included.
12
+ const code = error?.code;
13
+ return HOOK_FAILURE_CODES.has(code) ? code : 'unclassified';
14
+ }
15
+ function switchNotStaged() {
16
+ return new ApiConnectionError({ code: 'switch-not-staged',
17
+ message: 'There is no account switch waiting for your confirmation, or it expired. Cancel the switch and start it again.' });
18
+ }
19
+ function stagedSwitchUsable(record, actorId, nowMs) {
20
+ const staged = record.staged;
21
+ return staged !== null && staged.actorId === actorId && staged.generation === record.generation
22
+ && Date.parse(staged.expiresAt) > nowMs;
23
+ }
24
+ /**
25
+ * Revoke the credential stored under `key` through the plugin hook and delete it only when the
26
+ * hook returned. The read ignores the generation fence: a disconnect has already disabled the
27
+ * credential, and these tokens go to the revoke hook only.
28
+ */
29
+ async function revokeStoredCredential(deps, key) {
30
+ const tokens = await deps.tokens.loadForRevocation({ key }).catch((error) => {
31
+ if (isUnreadableTokenRecord(error))
32
+ return 'unreadable';
33
+ throw error;
34
+ });
35
+ // Nothing can ever revoke with an unreadable row; keeping it would block every later sign-in.
36
+ if (tokens === 'unreadable') {
37
+ await deps.tokens.delete({ key });
38
+ return { outcome: 'abandoned', failure: 'credential-unreadable' };
39
+ }
40
+ if (tokens === null)
41
+ return { outcome: 'not-needed', failure: null };
42
+ try {
43
+ await deps.hooks.revoke({ token: tokens.refreshToken ?? tokens.accessToken });
44
+ }
45
+ catch (error) {
46
+ // The hook's error may echo provider bodies; the outcome and a fixed code, not the detail, is
47
+ // what callers and the record get. The credential stays (disabled) so a retry can still revoke.
48
+ return { outcome: 'pending', failure: hookFailureOf(error) };
49
+ }
50
+ await deps.tokens.delete({ key });
51
+ return { outcome: 'confirmed', failure: null };
52
+ }
53
+ /** One outcome for several credentials: any pending (or abandoned) wins, then any confirmed. */
54
+ function combineRevocations(outcomes) {
55
+ if (outcomes.includes('pending') || outcomes.includes('abandoned'))
56
+ return 'pending';
57
+ return outcomes.includes('confirmed') ? 'confirmed' : 'not-needed';
58
+ }
59
+ /** The first failure among several credentials (the live one is revoked first), or null. */
60
+ function firstFailure(results) {
61
+ return results.find(result => result.failure !== null)?.failure ?? null;
62
+ }
63
+ export async function confirmSwitchAccount(deps, requiredArgs) {
64
+ const record = await loadOwnedRecord(deps, requiredArgs);
65
+ if (!stagedSwitchUsable(record, requiredArgs.actorId, deps.clock.nowMs()))
66
+ throw switchNotStaged();
67
+ const stagedKey = stagedTokenKey({ key: record.key });
68
+ const tokens = await deps.tokens.load({ key: stagedKey });
69
+ if (tokens === null)
70
+ throw switchNotStaged();
71
+ const staged = record.staged;
72
+ const updated = await installCredential(deps, { current: record, tokens, account: staged.account, grantedScopes: staged.grantedScopes });
73
+ await deps.tokens.delete({ key: stagedKey });
74
+ return toStatusView(updated);
75
+ }
76
+ /**
77
+ * Drop a staged switch, revoking its tokens because the person consented to them. When the
78
+ * provider does not confirm, the switch stays staged (still confirmable) and cancelling again retries.
79
+ */
80
+ export async function cancelSwitchAccount(deps, requiredArgs) {
81
+ const record = await loadOwnedRecord(deps, requiredArgs);
82
+ // Without a staged record the slot can only hold a confirmed switch's copy of the live grant
83
+ // (or a credential a pending disconnect owns): revoking it here would cut off the live account.
84
+ if (record.staged === null)
85
+ return { ...toStatusView(record), remoteRevocation: 'not-needed' };
86
+ const result = await revokeStoredCredential(deps, stagedTokenKey({ key: record.key }));
87
+ const updated = await writeRecord(deps, record, result.outcome === 'pending'
88
+ ? { revocationFailure: result.failure } : { staged: null, revocationFailure: result.failure });
89
+ return { ...toStatusView(updated), remoteRevocation: combineRevocations([result.outcome]) };
90
+ }
91
+ /** Disconnect and revoke the live and any staged credential; call again to retry a `pending` revocation. */
92
+ export async function disconnectApiConnection(deps, requiredArgs) {
93
+ const record = await loadOwnedRecord(deps, requiredArgs);
94
+ // Stop use before any network call: no token is served or refreshed once the generation moves.
95
+ const stopped = record.status === 'revocation-pending' ? record
96
+ : await writeRecord(deps, record, { status: 'revocation-pending', generation: record.generation + 1, staged: null });
97
+ const results = [
98
+ await revokeStoredCredential(deps, record.key),
99
+ await revokeStoredCredential(deps, stagedTokenKey({ key: record.key })),
100
+ ];
101
+ const outcomes = results.map(result => result.outcome);
102
+ const remoteRevocation = combineRevocations(outcomes);
103
+ const revocationFailure = firstFailure(results);
104
+ // Only a kept credential can be retried; an abandoned one leaves nothing to wait for locally.
105
+ if (outcomes.includes('pending'))
106
+ return { ...toStatusView(await writeRecord(deps, stopped, { revocationFailure })), remoteRevocation };
107
+ const cleared = await writeRecord(deps, stopped, { status: 'disconnected', account: null, grantedScopes: [], revocationFailure });
108
+ return { ...toStatusView(cleared), remoteRevocation };
109
+ }
110
+ //# sourceMappingURL=account-actions.js.map
@@ -0,0 +1,28 @@
1
+ import { type SealedAuthorizationState } from '@jini-ai/oauth';
2
+ import type { ApiConnectionServiceDeps } from './deps.js';
3
+ import type { ApiConnectionAttempt } from './types.js';
4
+ /** Long enough for consent and multi-factor prompts; abandoned attempts die quickly. */
5
+ export declare const ATTEMPT_TTL_MS: number;
6
+ /** Same strength as `state`: the binding is what a forwarded authorization URL cannot carry along. */
7
+ export declare const BROWSER_BINDING_BYTES = 32;
8
+ /**
9
+ * The stored form of a browser binding, so a leaked attempt row cannot be replayed as a cookie.
10
+ * A host bug passing a non-string hashes as '', which no 32-byte binding ever matches.
11
+ */
12
+ export declare function hashBrowserBinding(value: unknown): string;
13
+ type AttemptDraft = Omit<ApiConnectionAttempt, 'state' | 'codeVerifier' | 'redirectUri' | 'createdAt' | 'expiresAt'>;
14
+ type AttemptDeps = Pick<ApiConnectionServiceDeps, 'records' | 'clock' | 'randomBytesFn'>;
15
+ /** Seal side: store the attempt under fresh random state. */
16
+ export declare function attemptSealer(deps: AttemptDeps, requiredArgs: {
17
+ readonly draft: AttemptDraft;
18
+ }): SealedAuthorizationState;
19
+ /** Open side: consume first, then check binding, so a probe burns the state it guessed. */
20
+ export declare function attemptOpener(deps: AttemptDeps, requiredArgs: {
21
+ /** The binding the callback's browser carried; the core's `open` arguments have no slot for it. */
22
+ readonly browserBinding: string;
23
+ readonly onOpen: (requiredArgs: {
24
+ readonly attempt: ApiConnectionAttempt;
25
+ }) => void;
26
+ }): SealedAuthorizationState;
27
+ export {};
28
+ //# sourceMappingURL=attempt-state.d.ts.map
@@ -0,0 +1,73 @@
1
+ /**
2
+ * @file Adapts the record store's attempts to the OAuth core's `SealedAuthorizationState` seam.
3
+ *
4
+ * Exists so `beginAuthorizationCode`/`completeAuthorizationCode` keep owning PKCE, redirect
5
+ * allowlisting, callback errors and the token exchange, while the attempt itself is a stored,
6
+ * expiring, single-use record bound to workspace, actor, plugin connection, callback URI,
7
+ * credential generation and the browser that started it. Every redemption failure is the core's
8
+ * indistinguishable invalid-state.
9
+ */
10
+ import { createHash } from 'node:crypto';
11
+ import { invalidPendingAuthorizationState, PENDING_AUTHORIZATION_STATE_BYTES, generateOAuthState, secureEqualsForOwnerBinding } from '@jini-ai/oauth';
12
+ import { nowIso } from '@jini-ai/core/primitives';
13
+ /** Long enough for consent and multi-factor prompts; abandoned attempts die quickly. */
14
+ export const ATTEMPT_TTL_MS = 10 * 60 * 1000;
15
+ /** Same strength as `state`: the binding is what a forwarded authorization URL cannot carry along. */
16
+ export const BROWSER_BINDING_BYTES = 32;
17
+ /**
18
+ * The stored form of a browser binding, so a leaked attempt row cannot be replayed as a cookie.
19
+ * A host bug passing a non-string hashes as '', which no 32-byte binding ever matches.
20
+ */
21
+ export function hashBrowserBinding(value) {
22
+ return createHash('sha256').update(typeof value === 'string' ? value : '').digest('base64url');
23
+ }
24
+ function toPending(attempt, providerId) {
25
+ return {
26
+ state: attempt.state, ownerKey: attempt.ownerKey, providerId, codeVerifier: attempt.codeVerifier,
27
+ redirectUri: attempt.redirectUri, scopes: attempt.requestedScopes, createdAt: attempt.createdAt, expiresAt: attempt.expiresAt,
28
+ };
29
+ }
30
+ /** Each adapter serves one direction; reaching the other means the core changed its contract. */
31
+ async function refuseUnexpected() {
32
+ throw invalidPendingAuthorizationState({});
33
+ }
34
+ /** Seal side: store the attempt under fresh random state. */
35
+ export function attemptSealer(deps, requiredArgs) {
36
+ return {
37
+ async seal({ entry }) {
38
+ const createdAt = nowIso({ clock: deps.clock });
39
+ const attempt = {
40
+ ...requiredArgs.draft, codeVerifier: entry.codeVerifier, redirectUri: entry.redirectUri, createdAt,
41
+ state: generateOAuthState({ randomBytesFn: deps.randomBytesFn }, { stateBytes: PENDING_AUTHORIZATION_STATE_BYTES }),
42
+ expiresAt: new Date(Date.parse(createdAt) + ATTEMPT_TTL_MS).toISOString(),
43
+ };
44
+ await deps.records.putAttempt({ attempt });
45
+ return toPending(attempt, entry.providerId);
46
+ },
47
+ open: refuseUnexpected,
48
+ };
49
+ }
50
+ function matchesBinding(attempt, expected, nowMs) {
51
+ return Date.parse(attempt.expiresAt) > nowMs
52
+ && secureEqualsForOwnerBinding({ a: attempt.ownerKey, b: expected.ownerKey })
53
+ // The owner key alone cannot bind a hosted callback: a cookie-less callback route can only learn
54
+ // the identities from the attempt itself. The browser binding is what the redirected browser carries.
55
+ && secureEqualsForOwnerBinding({ a: attempt.browserBindingHash, b: hashBrowserBinding(expected.browserBinding) })
56
+ && attempt.redirectUri === expected.redirectUri;
57
+ }
58
+ /** Open side: consume first, then check binding, so a probe burns the state it guessed. */
59
+ export function attemptOpener(deps, requiredArgs) {
60
+ const { browserBinding } = requiredArgs;
61
+ return {
62
+ seal: refuseUnexpected,
63
+ async open({ state, ownerKey, providerId, redirectUri }) {
64
+ const attempt = await deps.records.takeAttempt({ state });
65
+ if (attempt === null || !matchesBinding(attempt, { ownerKey, redirectUri, browserBinding }, deps.clock.nowMs())) {
66
+ throw invalidPendingAuthorizationState({});
67
+ }
68
+ requiredArgs.onOpen({ attempt });
69
+ return toPending(attempt, providerId);
70
+ },
71
+ };
72
+ }
73
+ //# sourceMappingURL=attempt-state.js.map
@@ -0,0 +1,45 @@
1
+ import type { ApiConnectionServiceDeps } from './deps.js';
2
+ import { type CompletedAuthorization } from './finish-authorization.js';
3
+ import type { ApiConnectionIntent } from './types.js';
4
+ export interface StartApiConnectionResult {
5
+ /** Stable reference to this connection; the same value on every reconnect. */
6
+ readonly connectionRef: string;
7
+ readonly authorizationUrl: string;
8
+ /**
9
+ * Host-only: the callback's CSRF binding, for the host's own routing (e.g. arming a loopback
10
+ * receiver). Never hand it to plugin code or a frame; give them `attemptId` instead.
11
+ */
12
+ readonly state: string;
13
+ /** Opaque, random id of this sign-in; `complete` returns the same id (e.g. to key callback fields). */
14
+ readonly attemptId: string;
15
+ /**
16
+ * Host-only: proof that a callback arrives in the browser that started this sign-in. Hand it to
17
+ * that browser (see the README's host contract) and pass it back to `complete`; never to plugin
18
+ * code, a frame, logs or the authorization URL. Only its hash is stored.
19
+ */
20
+ readonly browserBinding: string;
21
+ readonly expiresAt: string;
22
+ }
23
+ export declare function startApiConnectionAuthorization(deps: ApiConnectionServiceDeps, requiredArgs: {
24
+ readonly workspaceId: string;
25
+ readonly actorId: string;
26
+ readonly intent: ApiConnectionIntent;
27
+ readonly scopeSetIds: readonly string[];
28
+ readonly redirectUri: string;
29
+ }, optionalArgs?: {
30
+ readonly startParams?: Readonly<Record<string, string>>;
31
+ }): Promise<StartApiConnectionResult>;
32
+ /**
33
+ * Redeem the callback. `redirectUri` is the exact callback URL this request arrived on and the
34
+ * identities are the host's authenticated session, never values read from the callback itself.
35
+ * `browserBinding` is what the callback's browser carried back (`''` when it carried none); a
36
+ * missing or different binding burns the attempt with the same `invalid-attempt`.
37
+ */
38
+ export declare function completeApiConnectionAuthorization(deps: ApiConnectionServiceDeps, requiredArgs: {
39
+ readonly workspaceId: string;
40
+ readonly actorId: string;
41
+ readonly redirectUri: string;
42
+ readonly callbackParams: Readonly<Record<string, string>>;
43
+ readonly browserBinding: string;
44
+ }): Promise<CompletedAuthorization>;
45
+ //# sourceMappingURL=authorization.d.ts.map
@@ -0,0 +1,120 @@
1
+ /**
2
+ * @file Starts and completes an API-connection sign-in (authorization code + PKCE S256).
3
+ *
4
+ * Exists to bind the OAuth core's browser grant to a plugin connection: start records an
5
+ * expiring single-use attempt bound to workspace, actor, plugin connection, requested scopes,
6
+ * callback URI, credential generation and the starting browser; complete redeems it exactly once,
7
+ * exchanges the code, and hands the token set to `finishAuthorization` for the grant, identity and
8
+ * commit checks.
9
+ */
10
+ import { beginAuthorizationCode, completeAuthorizationCode, generateOAuthState, OAuthError } from '@jini-ai/oauth';
11
+ import { ApiConnectionError, invalidAttempt } from './errors.js';
12
+ import { attemptOpener, attemptSealer, BROWSER_BINDING_BYTES, hashBrowserBinding } from './attempt-state.js';
13
+ import { finishAuthorization, loadReadableTokens } from './finish-authorization.js';
14
+ import { deriveApiConnectionKey } from './keys.js';
15
+ import { assertId, checkCallbackParams, checkScopes, checkStartParams, pickBoundedFields, requestInvalid } from './request-checks.js';
16
+ /** Same encoding as `state`, half the entropy: it names an attempt, it does not guard one. */
17
+ const ATTEMPT_ID_BYTES = 16;
18
+ function providerFor(deps) {
19
+ const { descriptor } = deps;
20
+ return {
21
+ providerId: `${descriptor.pluginId}/${descriptor.connectionId}`, label: descriptor.label,
22
+ supportedGrants: ['authorization_code'], authorizationEndpoint: descriptor.authorizationEndpoint,
23
+ tokenEndpoint: descriptor.tokenEndpoint, defaultScopes: [], usesPkce: true, clientAuth: deps.client.authMethod,
24
+ };
25
+ }
26
+ /** One canonical string per (workspace, actor, plugin connection); JSON keeps it injective. */
27
+ function ownerKeyFor(deps, requiredArgs) {
28
+ return JSON.stringify([requiredArgs.workspaceId, requiredArgs.actorId, deps.descriptor.pluginId, deps.descriptor.connectionId]);
29
+ }
30
+ function assertStartAllowed(record, intent) {
31
+ // The disabled credential is kept for a revocation retry; a new sign-in would orphan it.
32
+ if (record?.status === 'revocation-pending') {
33
+ throw new ApiConnectionError({ code: 'revocation-pending',
34
+ message: 'This connection is disconnected locally but remote revocation is still pending. Retry disconnecting first.' });
35
+ }
36
+ // A new sign-in would overwrite (switch) or orphan (connect) the staged credential without revoking it.
37
+ if (record != null && record.staged !== null) {
38
+ throw new ApiConnectionError({ code: 'switch-in-progress',
39
+ message: 'An account switch is waiting for confirmation. Confirm it or cancel it before signing in again.' });
40
+ }
41
+ if (intent === 'switch-account' && (record === null || record.account === null)) {
42
+ throw new ApiConnectionError({ code: 'not-connected', message: 'There is no connected account to switch from. Connect an account first.' });
43
+ }
44
+ }
45
+ /** A connected record whose stored tokens this host can read and that hold a refresh token. */
46
+ async function holdsRenewableCredential(deps, record) {
47
+ if (record?.status !== 'connected')
48
+ return false;
49
+ return (await loadReadableTokens(deps, { key: record.key }))?.refreshToken != null;
50
+ }
51
+ /**
52
+ * The client kind's fixed parameters, plus the descriptor's force-consent ones on a hosted start
53
+ * with nothing renewable stored for the account: a provider may issue a refresh token only on the
54
+ * first consent per account and client (e.g. the same account in a second workspace). A switch
55
+ * signs in another account, so the stored credential never counts for it.
56
+ */
57
+ async function clientKindParams(deps, record, intent) {
58
+ const fixed = deps.descriptor.authorizationParams[deps.clientKind];
59
+ if (deps.clientKind === 'public')
60
+ return fixed;
61
+ const renewable = intent === 'connect' && await holdsRenewableCredential(deps, record);
62
+ return renewable ? fixed : { ...fixed, ...deps.descriptor.forceConsentParams };
63
+ }
64
+ /** Map OAuth core failures to connection codes; the core's messages are already token-free. */
65
+ function toConnectionError(error) {
66
+ if (!(error instanceof OAuthError))
67
+ return error;
68
+ if (error.code === 'OAUTH_INVALID_STATE')
69
+ return invalidAttempt({}, { cause: error });
70
+ const code = error.code === 'OAUTH_ACCESS_DENIED' ? 'access-denied' : 'authorization-failed';
71
+ return new ApiConnectionError({ code, message: `Sign-in did not complete: ${error.message}. ${error.operatorAction}` }, { cause: error });
72
+ }
73
+ export async function startApiConnectionAuthorization(deps, requiredArgs, optionalArgs = {}) {
74
+ const { workspaceId, actorId, intent } = requiredArgs;
75
+ assertId(workspaceId, 'workspaceId');
76
+ assertId(actorId, 'actorId');
77
+ if (intent !== 'connect' && intent !== 'switch-account')
78
+ throw requestInvalid('intent');
79
+ const startParams = checkStartParams(deps.descriptor.startParams, optionalArgs.startParams ?? {});
80
+ const key = deriveApiConnectionKey({ workspaceId, pluginId: deps.descriptor.pluginId, connectionId: deps.descriptor.connectionId });
81
+ const record = await deps.records.read({ key });
82
+ assertStartAllowed(record, intent);
83
+ const requestedScopes = checkScopes(await deps.hooks.resolveScopes({ scopeSetIds: [...requiredArgs.scopeSetIds] }));
84
+ const kindParams = await clientKindParams(deps, record, intent);
85
+ const ownerKey = ownerKeyFor(deps, { workspaceId, actorId });
86
+ const attemptId = generateOAuthState({ randomBytesFn: deps.randomBytesFn }, { stateBytes: ATTEMPT_ID_BYTES });
87
+ const browserBinding = generateOAuthState({ randomBytesFn: deps.randomBytesFn }, { stateBytes: BROWSER_BINDING_BYTES });
88
+ const draft = { key, attemptId, ownerKey, browserBindingHash: hashBrowserBinding(browserBinding), workspaceId, actorId, pluginId: deps.descriptor.pluginId,
89
+ connectionId: deps.descriptor.connectionId, intent, requestedScopes, generation: record?.generation ?? 0 };
90
+ const begun = await beginAuthorizationCode({
91
+ provider: providerFor(deps), stateless: attemptSealer(deps, { draft }), randomBytesFn: deps.randomBytesFn, guard: deps.guard,
92
+ options: deps.appOptions, ownerKey, client: deps.client, redirectUri: requiredArgs.redirectUri,
93
+ }, { scopes: requestedScopes, extraAuthorizationParams: { ...kindParams, ...startParams } })
94
+ .catch((error) => { throw toConnectionError(error); });
95
+ return { connectionRef: key, authorizationUrl: begun.authorizationUrl, state: begun.state, attemptId, browserBinding,
96
+ expiresAt: begun.expiresAt };
97
+ }
98
+ /**
99
+ * Redeem the callback. `redirectUri` is the exact callback URL this request arrived on and the
100
+ * identities are the host's authenticated session, never values read from the callback itself.
101
+ * `browserBinding` is what the callback's browser carried back (`''` when it carried none); a
102
+ * missing or different binding burns the attempt with the same `invalid-attempt`.
103
+ */
104
+ export async function completeApiConnectionAuthorization(deps, requiredArgs) {
105
+ assertId(requiredArgs.workspaceId, 'workspaceId');
106
+ assertId(requiredArgs.actorId, 'actorId');
107
+ if (!URL.canParse(requiredArgs.redirectUri))
108
+ throw requestInvalid('redirectUri');
109
+ const params = checkCallbackParams(requiredArgs.callbackParams);
110
+ const callbackFields = pickBoundedFields(deps.descriptor.callbackFields, requiredArgs.callbackParams, 'callback field');
111
+ let attempt;
112
+ const tokens = await completeAuthorizationCode({
113
+ provider: providerFor(deps), stateless: attemptOpener(deps, { browserBinding: requiredArgs.browserBinding, onOpen: opened => { attempt = opened.attempt; } }),
114
+ redirectUri: new URL(requiredArgs.redirectUri).href, ownerKey: ownerKeyFor(deps, requiredArgs), client: deps.client, params,
115
+ fetchFn: deps.fetchFn, guard: deps.guard, clock: deps.clock,
116
+ }).catch((error) => { throw toConnectionError(error); });
117
+ // completeAuthorizationCode only reaches the exchange after `open` returned an attempt.
118
+ return finishAuthorization(deps, { attempt: attempt, tokens, callbackFields });
119
+ }
120
+ //# sourceMappingURL=authorization.js.map
@@ -0,0 +1,41 @@
1
+ /**
2
+ * @file The dependency bundle every API-connection operation receives.
3
+ *
4
+ * Exists so the service factory validates its wiring once and each operation module takes one
5
+ * typed object instead of re-declaring eleven ports.
6
+ */
7
+ import type { Clock } from '@jini-ai/core/primitives';
8
+ import type { OAuthAppOptions, OAuthClient, OAuthFetch, OAuthRandomBytes, OAuthSleep, OAuthUrlGuard } from '@jini-ai/oauth';
9
+ import type { ApiConnectionHooks, ApiConnectionRecordStore, ApiConnectionTokenStore } from './ports.js';
10
+ import type { ApiConnectionDescriptor } from './types.js';
11
+ export interface ApiConnectionServiceDeps {
12
+ readonly descriptor: ApiConnectionDescriptor;
13
+ /**
14
+ * How the app is registered, independent of how it authenticates: `public` for an installed app
15
+ * (PKCE, loopback callback, re-consent replaces the whole token set), `confidential` for a hosted
16
+ * server that keeps its secret. Selects the descriptor's extra parameters and refresh-token rules.
17
+ */
18
+ readonly clientKind: ApiConnectionClientKind;
19
+ /**
20
+ * Client identity and token-endpoint auth method. A public client may still send a
21
+ * provider-issued, non-confidential secret; it stays server-side and is never logged or shown.
22
+ */
23
+ readonly client: OAuthClient;
24
+ /** Application identity and the registered callback URLs an attempt may use. */
25
+ readonly appOptions: OAuthAppOptions;
26
+ readonly hooks: ApiConnectionHooks;
27
+ readonly records: ApiConnectionRecordStore;
28
+ readonly tokens: ApiConnectionTokenStore;
29
+ readonly fetchFn: OAuthFetch;
30
+ readonly guard: OAuthUrlGuard;
31
+ readonly clock: Clock;
32
+ readonly randomBytesFn: OAuthRandomBytes;
33
+ readonly sleep: OAuthSleep;
34
+ }
35
+ export type ApiConnectionClientKind = 'public' | 'confidential';
36
+ /**
37
+ * Refuse wiring whose client kind is unknown, or confidential without token-endpoint
38
+ * authentication (a client that does not authenticate is not confidential).
39
+ */
40
+ export declare function assertClientWiring(deps: Pick<ApiConnectionServiceDeps, 'client' | 'clientKind'>): void;
41
+ //# sourceMappingURL=deps.d.ts.map
@@ -0,0 +1,13 @@
1
+ import { ApiConnectionError } from './errors.js';
2
+ /**
3
+ * Refuse wiring whose client kind is unknown, or confidential without token-endpoint
4
+ * authentication (a client that does not authenticate is not confidential).
5
+ */
6
+ export function assertClientWiring(deps) {
7
+ const known = deps.clientKind === 'public' || deps.clientKind === 'confidential';
8
+ if (known && !(deps.clientKind === 'confidential' && deps.client?.authMethod === 'none'))
9
+ return;
10
+ throw new ApiConnectionError({ code: 'configuration-invalid',
11
+ message: 'The connection is wired with an invalid client kind for its client. Fix the host configuration and restart.' });
12
+ }
13
+ //# sourceMappingURL=deps.js.map
@@ -0,0 +1,6 @@
1
+ import type { ApiConnectionDescriptor } from './types.js';
2
+ /** Validate and freeze a plugin-declared connection. Throws `descriptor-invalid` naming the bad part. */
3
+ export declare function parseApiConnectionDescriptor(requiredArgs: {
4
+ readonly value: unknown;
5
+ }): ApiConnectionDescriptor;
6
+ //# sourceMappingURL=descriptor.d.ts.map