@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
@@ -0,0 +1,67 @@
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
+ */
8
+ import { MAX_AUTHORIZATION_STATE_LENGTH, MAX_CALLBACK_FIELD_LENGTH } from '@jini-ai/oauth';
9
+ import { ApiConnectionError } from './errors.js';
10
+ const MAX_ID_LENGTH = 256;
11
+ const MAX_SCOPES = 64;
12
+ /** RFC 6749 §3.3 scope-token characters, bounded. */
13
+ const SCOPE_TOKEN = /^[\x21\x23-\x5b\x5d-\x7e]{1,512}$/;
14
+ const MAX_CALLBACK_PARAMS = 64;
15
+ const OAUTH_CALLBACK_NAMES = ['state', 'code', 'error'];
16
+ export function requestInvalid(detail) {
17
+ return new ApiConnectionError({
18
+ code: 'request-invalid',
19
+ message: `The connection request is invalid (${detail}). Start connecting again from the connection settings.`,
20
+ });
21
+ }
22
+ export function assertId(value, name) {
23
+ if (typeof value !== 'string' || value === '' || value.length > MAX_ID_LENGTH)
24
+ throw requestInvalid(name);
25
+ }
26
+ /** Non-empty, de-duplicated scope list in RFC 6749 token syntax. */
27
+ export function checkScopes(value) {
28
+ if (!Array.isArray(value) || value.length === 0 || value.length > MAX_SCOPES
29
+ || !value.every(scope => typeof scope === 'string' && SCOPE_TOKEN.test(scope))) {
30
+ throw requestInvalid('the plugin resolved no valid scope set');
31
+ }
32
+ return [...new Set(value)];
33
+ }
34
+ /** Keep only allowlisted names; refuse a declared value over its limit rather than truncate it. */
35
+ export function pickBoundedFields(fields, values, where) {
36
+ const picked = {};
37
+ for (const field of fields) {
38
+ const value = values[field.name];
39
+ if (value === undefined)
40
+ continue;
41
+ if (typeof value !== 'string' || value.length > field.maxLength)
42
+ throw requestInvalid(`${where} '${field.name}' is too large`);
43
+ picked[field.name] = value;
44
+ }
45
+ return picked;
46
+ }
47
+ /** Every name a caller passes must be declared; silently ignoring one would hide a plugin bug. */
48
+ export function checkStartParams(fields, values) {
49
+ const unknown = Object.keys(values).find(name => !fields.some(field => field.name === name));
50
+ if (unknown !== undefined)
51
+ throw requestInvalid(`start parameter '${unknown}' is not declared by the plugin`);
52
+ return pickBoundedFields(fields, values, 'start parameter');
53
+ }
54
+ /** Bound the raw callback before anything is consumed; OAuth names are validated by the core. */
55
+ export function checkCallbackParams(value) {
56
+ const entries = Object.entries(value);
57
+ 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))) {
59
+ throw requestInvalid('the callback carried too many or oversized fields');
60
+ }
61
+ const checked = {};
62
+ for (const name of OAUTH_CALLBACK_NAMES)
63
+ if (typeof value[name] === 'string')
64
+ checked[name] = value[name];
65
+ return { ...checked, state: checked.state ?? '' };
66
+ }
67
+ //# sourceMappingURL=request-checks.js.map
@@ -0,0 +1,25 @@
1
+ /**
2
+ * @file Composition root: one API-connection service per plugin-declared connection.
3
+ *
4
+ * Exists so a host wires the ports once (descriptor, client identity, stores, hooks, HTTP and
5
+ * clock) and gets every connection operation with that wiring bound.
6
+ */
7
+ import { createApiConnectionAccessTokens } from './access-token.js';
8
+ import { cancelSwitchAccount, confirmSwitchAccount, disconnectApiConnection } from './account-actions.js';
9
+ import { completeApiConnectionAuthorization, startApiConnectionAuthorization } from './authorization.js';
10
+ import { type ApiConnectionServiceDeps } from './deps.js';
11
+ import { getApiConnectionStatus } from './status.js';
12
+ type Bound<F> = F extends (deps: ApiConnectionServiceDeps, ...rest: infer A) => infer R ? (...rest: A) => R : never;
13
+ export interface ApiConnectionService {
14
+ readonly start: Bound<typeof startApiConnectionAuthorization>;
15
+ readonly complete: Bound<typeof completeApiConnectionAuthorization>;
16
+ readonly confirmSwitchAccount: Bound<typeof confirmSwitchAccount>;
17
+ readonly cancelSwitchAccount: Bound<typeof cancelSwitchAccount>;
18
+ readonly disconnect: Bound<typeof disconnectApiConnection>;
19
+ readonly getStatus: Bound<typeof getApiConnectionStatus>;
20
+ readonly getAccessToken: ReturnType<typeof createApiConnectionAccessTokens>['getAccessToken'];
21
+ }
22
+ /** @throws ApiConnectionError `configuration-invalid` when the client kind contradicts the client. */
23
+ export declare function createApiConnectionService(deps: ApiConnectionServiceDeps): ApiConnectionService;
24
+ export {};
25
+ //# sourceMappingURL=service.d.ts.map
@@ -0,0 +1,26 @@
1
+ /**
2
+ * @file Composition root: one API-connection service per plugin-declared connection.
3
+ *
4
+ * Exists so a host wires the ports once (descriptor, client identity, stores, hooks, HTTP and
5
+ * clock) and gets every connection operation with that wiring bound.
6
+ */
7
+ import { createApiConnectionAccessTokens } from './access-token.js';
8
+ import { cancelSwitchAccount, confirmSwitchAccount, disconnectApiConnection } from './account-actions.js';
9
+ import { completeApiConnectionAuthorization, startApiConnectionAuthorization } from './authorization.js';
10
+ import { assertClientWiring } from './deps.js';
11
+ import { getApiConnectionStatus } from './status.js';
12
+ /** @throws ApiConnectionError `configuration-invalid` when the client kind contradicts the client. */
13
+ export function createApiConnectionService(deps) {
14
+ assertClientWiring(deps);
15
+ const accessTokens = createApiConnectionAccessTokens(deps);
16
+ return {
17
+ start: (...args) => startApiConnectionAuthorization(deps, ...args),
18
+ complete: (...args) => completeApiConnectionAuthorization(deps, ...args),
19
+ confirmSwitchAccount: (...args) => confirmSwitchAccount(deps, ...args),
20
+ cancelSwitchAccount: (...args) => cancelSwitchAccount(deps, ...args),
21
+ disconnect: (...args) => disconnectApiConnection(deps, ...args),
22
+ getStatus: (...args) => getApiConnectionStatus(deps, ...args),
23
+ getAccessToken: (...args) => accessTokens.getAccessToken(...args),
24
+ };
25
+ }
26
+ //# sourceMappingURL=service.js.map
@@ -0,0 +1,28 @@
1
+ /**
2
+ * @file The token-free status view hosts render for a connection.
3
+ *
4
+ * Exists so status, account display and granted scopes can be shown anywhere (settings pages,
5
+ * chat, logs) without any path from a status object back to a credential.
6
+ */
7
+ import type { ApiConnectionServiceDeps } from './deps.js';
8
+ import { type OwnedRecordArgs } from './records.js';
9
+ import type { ApiConnectionAccount, ApiConnectionRecord, ApiConnectionRevocationFailure, ApiConnectionStatus } from './types.js';
10
+ export interface ApiConnectionStatusView {
11
+ readonly connectionRef: string;
12
+ readonly status: ApiConnectionStatus;
13
+ readonly account: ApiConnectionAccount | null;
14
+ readonly grantedScopes: readonly string[];
15
+ /** Account of a switch-account result awaiting confirmation, if any. */
16
+ readonly pendingSwitch: ApiConnectionAccount | null;
17
+ /** Why the last revocation was not confirmed (a fixed code for operators), or null. */
18
+ readonly revocationFailure: ApiConnectionRevocationFailure | null;
19
+ }
20
+ export declare function toStatusView(record: ApiConnectionRecord): ApiConnectionStatusView;
21
+ /**
22
+ * A connection that was never created reads as disconnected, without opening credentials.
23
+ * A connected record with missing or incompatible tokens reads as reconnect-required; status
24
+ * never rewrites or deletes the stored credential. Other storage failures still propagate.
25
+ * @complexity One record read and, only for a connected record, one token-store load; no HTTP.
26
+ */
27
+ export declare function getApiConnectionStatus(deps: Pick<ApiConnectionServiceDeps, 'records' | 'descriptor' | 'tokens'>, requiredArgs: OwnedRecordArgs): Promise<ApiConnectionStatusView>;
28
+ //# sourceMappingURL=status.d.ts.map
@@ -0,0 +1,36 @@
1
+ import { connectionNotFound, isOwnedRecord } from './records.js';
2
+ import { isUnreadableTokenRecord } from './token-store/errors.js';
3
+ export function toStatusView(record) {
4
+ return {
5
+ connectionRef: record.key, status: record.status, account: record.account,
6
+ grantedScopes: record.grantedScopes, pendingSwitch: record.staged?.account ?? null,
7
+ // Rows written before the diagnostic existed have no field; they read as "none".
8
+ revocationFailure: record.revocationFailure ?? null,
9
+ };
10
+ }
11
+ /**
12
+ * A connection that was never created reads as disconnected, without opening credentials.
13
+ * A connected record with missing or incompatible tokens reads as reconnect-required; status
14
+ * never rewrites or deletes the stored credential. Other storage failures still propagate.
15
+ * @complexity One record read and, only for a connected record, one token-store load; no HTTP.
16
+ */
17
+ export async function getApiConnectionStatus(deps, requiredArgs) {
18
+ const record = await deps.records.read({ key: requiredArgs.connectionRef });
19
+ if (record === null) {
20
+ return { connectionRef: requiredArgs.connectionRef, status: 'disconnected', account: null, grantedScopes: [], pendingSwitch: null,
21
+ revocationFailure: null };
22
+ }
23
+ if (!isOwnedRecord(record, deps, requiredArgs.workspaceId))
24
+ throw connectionNotFound();
25
+ if (record.status === 'connected') {
26
+ const tokens = await deps.tokens.load({ key: record.key }).catch((error) => {
27
+ if (isUnreadableTokenRecord(error))
28
+ return null;
29
+ throw error;
30
+ });
31
+ if (tokens === null)
32
+ return toStatusView({ ...record, status: 'reconnect-required' });
33
+ }
34
+ return toStatusView(record);
35
+ }
36
+ //# sourceMappingURL=status.js.map
@@ -0,0 +1,20 @@
1
+ /** @file Typed failures of the vault-backed OAuth token store.
2
+ * Exists so callers can branch on a stable code while messages stay fixed text: no token,
3
+ * key, owner id or vault material ever reaches an error message, status or log line. */
4
+ import { IntegrationError } from "../../argument-error.js";
5
+ export type OAuthTokenStoreErrorCode = "configuration" | "lease-not-held" | "lease-lost" | "stale-generation" | "owner-mismatch" | "invalid-record" | "write-conflict";
6
+ /** Refusal raised by the token store; `cause` keeps the underlying vault error when there is one. */
7
+ export declare class OAuthTokenStoreError extends IntegrationError {
8
+ readonly code: OAuthTokenStoreErrorCode;
9
+ readonly nextAction: string;
10
+ constructor({ code }: {
11
+ code: OAuthTokenStoreErrorCode;
12
+ }, { cause }?: {
13
+ cause?: unknown;
14
+ });
15
+ }
16
+ /** True for a stored row this owner cannot open (sealed for another client id, or malformed). Only
17
+ * a new sign-in can replace such a row, so callers treat it as "no usable credential" instead of
18
+ * failing for good. Other store failures (vault outages, conflicts) are not this. */
19
+ export declare function isUnreadableTokenRecord(error: unknown): boolean;
20
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1,38 @@
1
+ /** @file Typed failures of the vault-backed OAuth token store.
2
+ * Exists so callers can branch on a stable code while messages stay fixed text: no token,
3
+ * key, owner id or vault material ever reaches an error message, status or log line. */
4
+ import { IntegrationError } from "../../argument-error.js";
5
+ const TEXT = {
6
+ configuration: { message: "OAuth token store: the vault scope does not belong to the expected workspace.",
7
+ nextAction: "Fix the host composition so the vault scope and connection owner name the same workspace." },
8
+ "lease-not-held": { message: "OAuth token store: tokens can only be written while holding this connection's refresh lease.",
9
+ nextAction: "Acquire the refresh lease, write, then release it." },
10
+ "lease-lost": { message: "OAuth token store: a newer attempt took over this connection, so this result was discarded.",
11
+ nextAction: "Retry; the newer attempt's tokens are kept." },
12
+ "stale-generation": { message: "OAuth token store: the connection was disconnected, switched or reconnected while this attempt ran, so its tokens were discarded.",
13
+ nextAction: "Retry against the current connection." },
14
+ "owner-mismatch": { message: "OAuth token store: the stored credential belongs to a different connection owner.",
15
+ nextAction: "Reconnect this connection." },
16
+ "write-conflict": { message: "OAuth token store: the connection kept changing while its credential was being written or removed.",
17
+ nextAction: "Retry the sign-in or the disconnect." },
18
+ "invalid-record": { message: "OAuth token store: the stored credential is not a valid OAuth token record.",
19
+ nextAction: "Reconnect this connection." },
20
+ };
21
+ /** Refusal raised by the token store; `cause` keeps the underlying vault error when there is one. */
22
+ export class OAuthTokenStoreError extends IntegrationError {
23
+ code;
24
+ nextAction;
25
+ constructor({ code }, { cause } = {}) {
26
+ super({ message: TEXT[code].message }, cause === undefined ? {} : { options: { cause } });
27
+ this.name = "OAuthTokenStoreError";
28
+ this.code = code;
29
+ this.nextAction = TEXT[code].nextAction;
30
+ }
31
+ }
32
+ /** True for a stored row this owner cannot open (sealed for another client id, or malformed). Only
33
+ * a new sign-in can replace such a row, so callers treat it as "no usable credential" instead of
34
+ * failing for good. Other store failures (vault outages, conflicts) are not this. */
35
+ export function isUnreadableTokenRecord(error) {
36
+ return error instanceof OAuthTokenStoreError && (error.code === "owner-mismatch" || error.code === "invalid-record");
37
+ }
38
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1,6 @@
1
+ /** @file Folder surface of the vault-backed OAuth token store; the api-connections entry re-exports
2
+ * all of it except the `OAuthTokenStoreError` class (hosts read its `code`). */
3
+ export { createVaultOAuthTokenStore, type VaultOAuthTokenStore, type VaultOAuthTokenStoreDeps, type OAuthTokenVaultPort, type ReadConnectionGeneration } from "./vault-token-store.js";
4
+ export { parseOAuthTokenVaultMeta, type OAuthConnectionOwner, type OAuthConnectionStatus } from "./record.js";
5
+ export { OAuthTokenStoreError, type OAuthTokenStoreErrorCode } from "./errors.js";
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,6 @@
1
+ /** @file Folder surface of the vault-backed OAuth token store; the api-connections entry re-exports
2
+ * all of it except the `OAuthTokenStoreError` class (hosts read its `code`). */
3
+ export { createVaultOAuthTokenStore } from "./vault-token-store.js";
4
+ export { parseOAuthTokenVaultMeta } from "./record.js";
5
+ export { OAuthTokenStoreError } from "./errors.js";
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,69 @@
1
+ /** @file Pure codec between OAuth token sets and vault rows.
2
+ * Exists so every read is checked the same way before a token leaves the store: the OAuth
3
+ * discriminator, the expected connection owner and the token shape. Secrets live only in the
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";
7
+ /** Who a stored token set belongs to. Every read must match all four ids exactly. */
8
+ export interface OAuthConnectionOwner {
9
+ readonly workspaceId: string;
10
+ readonly pluginId: string;
11
+ readonly connectionId: string;
12
+ readonly clientId: string;
13
+ }
14
+ export type OAuthConnectionStatus = "active" | "reconnect-required";
15
+ /** Plaintext (never secret) metadata. The lease fields make refresh exclusive across processes. */
16
+ export interface OAuthTokenRecordMeta {
17
+ readonly status: OAuthConnectionStatus;
18
+ readonly leaseHolder: string | null;
19
+ readonly leaseExpiresAtMs: number | null;
20
+ }
21
+ export interface OAuthTokenPayload {
22
+ readonly generation: number;
23
+ readonly tokens: OAuthTokenSet | null;
24
+ }
25
+ /** Builds the plaintext metadata written next to the sealed payload. */
26
+ export declare function buildRecordMeta({ meta }: {
27
+ meta: OAuthTokenRecordMeta;
28
+ }): VaultMeta;
29
+ /** Vault metadata parser for the kind a host stores OAuth tokens under. Register it with
30
+ * `createVaultMetaParsers({}, { parsers: { [kind]: parseOAuthTokenVaultMeta } })`; it refuses any
31
+ * extra key so metadata cannot become a side channel for secrets.
32
+ * @throws OAuthTokenStoreError `invalid-record` on any other shape. */
33
+ export declare function parseOAuthTokenVaultMeta({ meta }: {
34
+ meta: unknown;
35
+ }): VaultMeta;
36
+ /** Reads the discriminator and lease fields of a stored row. @throws `invalid-record`. */
37
+ export declare function readRecordMeta({ meta }: {
38
+ meta: unknown;
39
+ }): OAuthTokenRecordMeta;
40
+ /** Builds the sealed payload; the owner and key are sealed with the tokens so a row copied or
41
+ * re-pointed to another connection is refused on read. */
42
+ export declare function buildTokenPayload(required: {
43
+ key: string;
44
+ owner: OAuthConnectionOwner;
45
+ generation: number;
46
+ tokens: OAuthTokenSet | null;
47
+ }): VaultMeta;
48
+ /** Validates a token set before it is written or after it is read. @throws `invalid-record`. */
49
+ export declare function parseTokenSet({ value }: {
50
+ value: unknown;
51
+ }): OAuthTokenSet;
52
+ /** Opens a decrypted payload for one expected key and owner.
53
+ * @throws `owner-mismatch` when it belongs elsewhere, `invalid-record` when malformed. */
54
+ export declare function parseTokenPayload(required: {
55
+ payload: unknown;
56
+ key: string;
57
+ owner: OAuthConnectionOwner;
58
+ }): OAuthTokenPayload;
59
+ /** Generation of the row an install is about to replace, or null when its payload is malformed.
60
+ * An install may overwrite a malformed row or one sealed for another client id of the same
61
+ * key and connection (the host changed its OAuth client): refusing either would lock the
62
+ * connection out for good, since only a new sign-in can produce a readable credential.
63
+ * @throws `owner-mismatch` when the row is sealed for another key, workspace, plugin or connection. */
64
+ export declare function readReplaceableGeneration(required: {
65
+ payload: unknown;
66
+ key: string;
67
+ owner: OAuthConnectionOwner;
68
+ }): number | null;
69
+ //# sourceMappingURL=record.d.ts.map
@@ -0,0 +1,97 @@
1
+ import { OAuthTokenStoreError } from "./errors.js";
2
+ /** Marks a vault row (metadata and sealed payload) as an OAuth token record. */
3
+ const OAUTH_TOKEN_RECORD_FORMAT = "oauth-token-set";
4
+ const PAYLOAD_VERSION = 1;
5
+ const META_KEYS = ["credentialFormat", "status", "leaseHolder", "leaseExpiresAtMs"];
6
+ const OWNER_KEYS = ["workspaceId", "pluginId", "connectionId", "clientId"];
7
+ function isRecord(value) {
8
+ return value !== null && typeof value === "object" && !Array.isArray(value);
9
+ }
10
+ function invalid() {
11
+ return new OAuthTokenStoreError({ code: "invalid-record" });
12
+ }
13
+ /** Builds the plaintext metadata written next to the sealed payload. */
14
+ export function buildRecordMeta({ meta }) {
15
+ return { credentialFormat: OAUTH_TOKEN_RECORD_FORMAT, status: meta.status,
16
+ leaseHolder: meta.leaseHolder, leaseExpiresAtMs: meta.leaseExpiresAtMs };
17
+ }
18
+ /** Vault metadata parser for the kind a host stores OAuth tokens under. Register it with
19
+ * `createVaultMetaParsers({}, { parsers: { [kind]: parseOAuthTokenVaultMeta } })`; it refuses any
20
+ * extra key so metadata cannot become a side channel for secrets.
21
+ * @throws OAuthTokenStoreError `invalid-record` on any other shape. */
22
+ export function parseOAuthTokenVaultMeta({ meta }) {
23
+ if (!isRecord(meta) || Object.keys(meta).some(key => !META_KEYS.includes(key)))
24
+ throw invalid();
25
+ return buildRecordMeta({ meta: readRecordMeta({ meta }) });
26
+ }
27
+ /** Reads the discriminator and lease fields of a stored row. @throws `invalid-record`. */
28
+ export function readRecordMeta({ meta }) {
29
+ if (!isRecord(meta) || meta.credentialFormat !== OAUTH_TOKEN_RECORD_FORMAT)
30
+ throw invalid();
31
+ const { status, leaseHolder, leaseExpiresAtMs } = meta;
32
+ if (status !== "active" && status !== "reconnect-required")
33
+ throw invalid();
34
+ if (leaseHolder !== null && typeof leaseHolder !== "string")
35
+ throw invalid();
36
+ if (leaseExpiresAtMs !== null && !Number.isSafeInteger(leaseExpiresAtMs))
37
+ throw invalid();
38
+ return { status, leaseHolder, leaseExpiresAtMs: leaseExpiresAtMs };
39
+ }
40
+ /** Builds the sealed payload; the owner and key are sealed with the tokens so a row copied or
41
+ * re-pointed to another connection is refused on read. */
42
+ export function buildTokenPayload(required) {
43
+ const { key, owner, generation, tokens } = required;
44
+ return { format: OAUTH_TOKEN_RECORD_FORMAT, version: PAYLOAD_VERSION, key, generation,
45
+ owner: { workspaceId: owner.workspaceId, pluginId: owner.pluginId, connectionId: owner.connectionId, clientId: owner.clientId },
46
+ tokens: tokens === null ? null : { accessToken: tokens.accessToken, refreshToken: tokens.refreshToken,
47
+ tokenType: tokens.tokenType, scopes: [...tokens.scopes], expiresAt: tokens.expiresAt } };
48
+ }
49
+ function ownerMatches(value, owner, names = OWNER_KEYS) {
50
+ return isRecord(value) && Object.keys(value).length === OWNER_KEYS.length && names.every(name => value[name] === owner[name]);
51
+ }
52
+ function isStringList(value) {
53
+ return Array.isArray(value) && value.every(item => typeof item === "string");
54
+ }
55
+ function isNullableString(value) {
56
+ return value === null || typeof value === "string";
57
+ }
58
+ /** Validates a token set before it is written or after it is read. @throws `invalid-record`. */
59
+ export function parseTokenSet({ value }) {
60
+ if (!isRecord(value))
61
+ throw invalid();
62
+ const { accessToken, refreshToken, tokenType, scopes, expiresAt } = value;
63
+ const valid = typeof accessToken === "string" && accessToken.length > 0 && isNullableString(refreshToken) &&
64
+ typeof tokenType === "string" && isStringList(scopes) && isNullableString(expiresAt);
65
+ if (!valid)
66
+ throw invalid();
67
+ return { accessToken, refreshToken, tokenType, scopes: [...scopes], expiresAt };
68
+ }
69
+ /** Opens a decrypted payload for one expected key and owner.
70
+ * @throws `owner-mismatch` when it belongs elsewhere, `invalid-record` when malformed. */
71
+ export function parseTokenPayload(required) {
72
+ const { payload, key, owner } = required;
73
+ if (!isRecord(payload) || payload.format !== OAUTH_TOKEN_RECORD_FORMAT || payload.version !== PAYLOAD_VERSION)
74
+ throw invalid();
75
+ if (payload.key !== key || !ownerMatches(payload.owner, owner))
76
+ throw new OAuthTokenStoreError({ code: "owner-mismatch" });
77
+ if (!Number.isSafeInteger(payload.generation))
78
+ throw invalid();
79
+ return { generation: payload.generation,
80
+ tokens: payload.tokens === null ? null : parseTokenSet({ value: payload.tokens }) };
81
+ }
82
+ /** Generation of the row an install is about to replace, or null when its payload is malformed.
83
+ * An install may overwrite a malformed row or one sealed for another client id of the same
84
+ * key and connection (the host changed its OAuth client): refusing either would lock the
85
+ * connection out for good, since only a new sign-in can produce a readable credential.
86
+ * @throws `owner-mismatch` when the row is sealed for another key, workspace, plugin or connection. */
87
+ export function readReplaceableGeneration(required) {
88
+ const { payload, key, owner } = required;
89
+ if (!isRecord(payload) || payload.format !== OAUTH_TOKEN_RECORD_FORMAT || payload.version !== PAYLOAD_VERSION
90
+ || !Number.isSafeInteger(payload.generation))
91
+ return null;
92
+ if (payload.key !== key || !ownerMatches(payload.owner, owner, ["workspaceId", "pluginId", "connectionId"])) {
93
+ throw new OAuthTokenStoreError({ code: "owner-mismatch" });
94
+ }
95
+ return payload.generation;
96
+ }
97
+ //# sourceMappingURL=record.js.map
@@ -0,0 +1,26 @@
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";
4
+ import type { ApiConnectionTokenStore } from "../ports.js";
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">;
8
+ /** Current generation of a connection. The host bumps it on disconnect, switch and reconnect. */
9
+ export type ReadConnectionGeneration = (requiredArgs: {
10
+ readonly key: string;
11
+ }) => Promise<number>;
12
+ export interface VaultOAuthTokenStoreDeps {
13
+ readonly vault: OAuthTokenVaultPort;
14
+ /** Where rows live. The kind's metadata parser must be `parseOAuthTokenVaultMeta`. */
15
+ readonly vaultScope: VaultContext;
16
+ readonly owner: OAuthConnectionOwner;
17
+ readonly readGeneration: ReadConnectionGeneration;
18
+ readonly clock: Clock;
19
+ }
20
+ /** `OAuthTokenStore` plus install and disconnect. Refresh writes (`persist`, `markNeedsReauth`)
21
+ * require the lease; `install` is fenced by its generation instead. */
22
+ export type VaultOAuthTokenStore = Required<OAuthTokenStore> & Pick<ApiConnectionTokenStore, "install" | "loadForRevocation" | "delete">;
23
+ /** Creates the store for one connection owner.
24
+ * @throws OAuthTokenStoreError `configuration` when the vault scope names another workspace. */
25
+ export declare function createVaultOAuthTokenStore(deps: VaultOAuthTokenStoreDeps, _optionalArgs?: Record<string, never>): VaultOAuthTokenStore;
26
+ //# sourceMappingURL=vault-token-store.d.ts.map