@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,143 @@
1
+ import { ApiConnectionError } from './errors.js';
2
+ import { createApiConnectionGenerationReader, deriveApiConnectionKey } from './keys.js';
3
+ import { waitForHostedSignIn } from './hosted-sign-in.js';
4
+ import { ToolInputError } from "@jini-ai/core";
5
+ /** API-connection refusals carry safe, actionable messages; surface them as caller-facing input errors. */
6
+ function asToolError({ error, messages }) {
7
+ if (error instanceof ApiConnectionError)
8
+ throw new ToolInputError({ message: messages.toolError({ message: error.message }) });
9
+ throw error;
10
+ }
11
+ /**
12
+ * Starts one sign-in for a declared connection: the generic start with the caller's declared start
13
+ * parameters (Jini refuses undeclared ones), on the runtime's redirect. Desktop arms Jini's
14
+ * 127.0.0.1 loopback receiver first (it closes on its callback, `timeoutMs` or `signal`) and
15
+ * redeems the callback itself, returning the plugin's declared callback fields with the result.
16
+ * Shared by `agent_plugin_connect` and the admin-surface connection port.
17
+ * @complexity One start; desktop adds one loopback listener and, later, one exchange.
18
+ */
19
+ export async function startApiConnectionSignIn(required, optional = {}) {
20
+ if (required.host.runtime === "desktop")
21
+ return startDesktopSignIn(required, optional);
22
+ if (required.destination === "shared")
23
+ throw new ApiConnectionError({ code: 'connection-not-found', message: required.messages.sharedUnavailable });
24
+ const { host, connection, actorId, intent, scopeSetIds } = required;
25
+ // The service first: its setup refusals (no client configured) come before the callback address's.
26
+ const service = host.serviceFor({ connection });
27
+ const callbackUrl = host.hostedCallbackUrl({ connection });
28
+ const start = await service.start({ workspaceId: host.workspaceId, actorId, intent, scopeSetIds, redirectUri: callbackUrl }, startOptionsOf(optional));
29
+ // Hosted hands out the host's own link (`browser-binding.ts`): opening it as this admin sets the
30
+ // browser binding, then redirects to the provider. The provider URL and the binding stay here.
31
+ const { authorizationUrl, browserBinding, expiresAt } = start;
32
+ const handoffId = host.signInHandoffs.issue({ authorizationUrl, browserBinding, actorId, expiresAt });
33
+ return { authorizationUrl: required.signInLink({ callbackUrl, workspaceId: host.workspaceId, handoffId }), attemptId: start.attemptId, expiresAt };
34
+ }
35
+ const startOptionsOf = (optional) => (optional.startParams === undefined ? {} : { startParams: optional.startParams });
36
+ /** Per host (one per workspace), the listener of each connection's pending desktop sign-in. */
37
+ const pendingDesktopSignIns = new WeakMap();
38
+ /**
39
+ * One pending desktop sign-in per connection (cancel-previous): a new one closes the previous
40
+ * listener, so repeated clicks never stack 127.0.0.1 listeners that each wait out their timeout.
41
+ * The previous attempt could not complete anyway once a newer one started.
42
+ * @returns Frees the slot, only while it still holds this listener. @complexity O(1).
43
+ */
44
+ function claimLoopbackSlot(host, connection, listening) {
45
+ const slots = pendingDesktopSignIns.get(host) ?? new Map();
46
+ pendingDesktopSignIns.set(host, slots);
47
+ const key = deriveApiConnectionKey({ workspaceId: host.workspaceId, pluginId: connection.pluginId, connectionId: connection.descriptor.connectionId });
48
+ slots.get(key)?.abort();
49
+ slots.set(key, listening);
50
+ return () => { if (slots.get(key) === listening)
51
+ slots.delete(key); };
52
+ }
53
+ async function startDesktopSignIn(required, optional) {
54
+ const { host, connection, actorId, intent, scopeSetIds } = required;
55
+ const listening = new AbortController();
56
+ const stop = () => listening.abort();
57
+ const free = claimLoopbackSlot(host, connection, listening);
58
+ const release = () => { free(); optional.signal?.removeEventListener("abort", stop); };
59
+ optional.signal?.addEventListener("abort", stop, { once: true });
60
+ try {
61
+ const receiver = await host.startLoopback({}, {
62
+ callbackFields: connection.descriptor.callbackFields.map((field) => field.name), signal: listening.signal,
63
+ ...(optional.timeoutMs === undefined ? {} : { timeoutMs: optional.timeoutMs }),
64
+ });
65
+ const target = await host.prepareSignIn({ connection, actorId, destination: required.destination, redirectUri: receiver.redirectUri });
66
+ const service = target.service;
67
+ const start = await service.start({ workspaceId: target.workspaceId, actorId, intent, scopeSetIds, redirectUri: receiver.redirectUri }, startOptionsOf(optional));
68
+ // `state` and `browserBinding` stay here: the receiver that gets the callback is this process,
69
+ // so both go straight back to `complete`, never into the result.
70
+ const { state, browserBinding } = start;
71
+ const completion = receiver.receive({ expectedState: state }).then((callback) => service.complete({ workspaceId: target.workspaceId, actorId, redirectUri: receiver.redirectUri, callbackParams: { ...callback.fields, state, code: callback.code }, browserBinding }).then(async (done) => { await target.onCompleted(); return done; }), () => null).finally(release);
72
+ return { authorizationUrl: start.authorizationUrl, attemptId: start.attemptId, expiresAt: start.expiresAt, completion };
73
+ }
74
+ catch (error) {
75
+ // Nothing will arm the listener now: close it instead of leaving it to its timeout.
76
+ stop();
77
+ release();
78
+ throw error;
79
+ }
80
+ }
81
+ async function connectHosted(run, scopeSetIds) {
82
+ const { host } = run.deps;
83
+ const connectionRef = deriveApiConnectionKey({ workspaceId: host.workspaceId, pluginId: run.connection.pluginId, connectionId: run.connection.descriptor.connectionId });
84
+ const readGeneration = createApiConnectionGenerationReader({ records: host.records });
85
+ const startGeneration = await readGeneration({ key: connectionRef });
86
+ const start = await startApiConnectionSignIn({ host, connection: run.connection, actorId: run.actorId, intent: "connect", scopeSetIds, signInLink: run.signInLink, messages: run.messages }).catch((error) => asToolError({ error, messages: run.messages }));
87
+ // Built only after the start: building it first threw its setup refusals (no callback origin, no
88
+ // client secret) raw, past the `ToolInputError` mapping above.
89
+ const service = host.serviceFor({ connection: run.connection });
90
+ // Hosted cards get the same-origin path; desktop keeps the provider URL for the system browser.
91
+ await run.showSignIn({ signInUrl: new URL(start.authorizationUrl).pathname });
92
+ return waitForHostedSignIn({
93
+ workspaceId: host.workspaceId, connectionRef, startGeneration, getStatus: service.getStatus, readGeneration,
94
+ signal: run.signal, pollIntervalMs: run.pollIntervalMs, waitTimeoutMs: run.waitTimeoutMs,
95
+ });
96
+ }
97
+ /**
98
+ * Desktop: loopback receiver, consent in the system browser, completion here. The listener always
99
+ * closes: this call's own controller also closes it when the card cannot be shown or the run ends,
100
+ * not only on `run.signal`, so a failed card never leaves a 127.0.0.1 listener up for its timeout.
101
+ */
102
+ async function connectDesktop(run, scopeSetIds) {
103
+ const { host } = run.deps;
104
+ const listening = new AbortController();
105
+ const stop = () => listening.abort();
106
+ run.signal.addEventListener("abort", stop, { once: true });
107
+ try {
108
+ // `runApiConnectionConnect` takes this path only for a desktop host, so the desktop start is
109
+ // called directly and its completion is always present (no "no completion" case to handle).
110
+ const start = await startDesktopSignIn({ host, connection: run.connection, actorId: run.actorId, intent: "connect", scopeSetIds, destination: run.destination, signInLink: run.signInLink, messages: run.messages }, {
111
+ timeoutMs: run.waitTimeoutMs, signal: listening.signal,
112
+ }).catch((error) => asToolError({ error, messages: run.messages }));
113
+ await run.showSignIn({ signInUrl: start.authorizationUrl });
114
+ return (await start.completion.catch((error) => asToolError({ error, messages: run.messages }))) !== null;
115
+ }
116
+ finally {
117
+ run.signal.removeEventListener("abort", stop);
118
+ stop();
119
+ }
120
+ }
121
+ /**
122
+ * Connects one declared API connection. Already connected with every scope it would request:
123
+ * returns `connected` with no sign-in, like the MCP branch does for a connected server.
124
+ * @throws {ToolInputError} The connection refused to start or complete (safe message, next step).
125
+ * @complexity One status read, one sign-in round trip bounded by `waitTimeoutMs`.
126
+ */
127
+ export async function runApiConnectionConnect(required, _optional = {}) {
128
+ const { host } = required.deps;
129
+ const { connection } = required;
130
+ // Chat connects the plugin's base scopes; products add theirs from the plugin's own panel.
131
+ const scopeSetIds = [];
132
+ const status = await host.statusOf({ connection, local: required.destination === "site" });
133
+ const { connectionRef } = status;
134
+ const wanted = await host.requestedScopes({ connection, scopeSetIds });
135
+ if (required.destination !== "shared" && status.status === "connected" && wanted.every((scope) => status.grantedScopes.includes(scope))) {
136
+ if (required.destination === "site")
137
+ await host.sharedOAuth?.selectLocal(connection);
138
+ return { status: "connected", connectionRef };
139
+ }
140
+ const connected = host.runtime === "desktop" ? await connectDesktop(required, scopeSetIds) : await connectHosted(required, scopeSetIds);
141
+ return { status: connected ? "connected" : "waiting-for-sign-in", connectionRef };
142
+ }
143
+ //# sourceMappingURL=connect.js.map
@@ -0,0 +1,68 @@
1
+ import type { ApiConnectionHooks } from './ports.js';
2
+ import { type ConnectionBudget } from './budgets.js';
3
+ /** Where a runtime's client id (and, for the hosted web client, its secret) is configured. */
4
+ export interface ApiConnectionClientConfig {
5
+ readonly clientIdEnv: string;
6
+ readonly clientSecretEnv?: string;
7
+ /** Hosted only: the site origins the shared client has registered callbacks for, added to the host's
8
+ * configured list (`API_CONNECTION_CALLBACK_ORIGINS_ENV`). Neither: hosted sign-in is refused. */
9
+ readonly redirectOrigins?: readonly string[];
10
+ }
11
+ /** One `connections[]` entry before the plugin id is known. */
12
+ export interface ApiConnectionDeclaration {
13
+ readonly id: string;
14
+ readonly module: string;
15
+ readonly clients: {
16
+ readonly web?: ApiConnectionClientConfig;
17
+ readonly desktop?: ApiConnectionClientConfig;
18
+ };
19
+ /** Clamped per-minute budgets the host charges on every token read; always includes an instance budget. */
20
+ readonly budgets: readonly ConnectionBudget[];
21
+ /** The scope-set ids (opaque product-module ids) the plugin offers, so status can report which are granted. */
22
+ readonly scopeSets: readonly string[];
23
+ /** The https origins the plugin's API calls with this connection reach (form delivery's host allowlist). */
24
+ readonly apiOrigins: readonly string[];
25
+ /** True when a workspace admin may sign in with their own OAuth client instead of the host's (`byo-client.ts`). */
26
+ readonly byoClient: boolean;
27
+ /** Passed to `parseApiConnectionDescriptor` with the plugin id at load time. */
28
+ readonly descriptor: Readonly<Record<string, unknown>>;
29
+ }
30
+ /** What the hooks module default-exports: hooks built over the host's guarded HTTP capability. */
31
+ export interface ApiConnectionHooksModule {
32
+ readonly createHooks: (required: {
33
+ readonly http: unknown;
34
+ }, optional?: Record<string, never>) => ApiConnectionHooks;
35
+ }
36
+ type ParseResult = {
37
+ readonly ok: true;
38
+ readonly descriptors: readonly ApiConnectionDeclaration[];
39
+ } | {
40
+ readonly ok: false;
41
+ readonly reason: string;
42
+ };
43
+ /**
44
+ * Parses a plugin's API-connections file. Pure; unknown keys go to the descriptor parser.
45
+ * `clientNamespace` is the host's client-setting prefix (for example `ACME_`); Jini ships no default.
46
+ * @throws TypeError when `clientNamespace` is malformed (host misconfiguration).
47
+ * @complexity O(c).
48
+ */
49
+ export declare function parseApiConnectionsFile(required: {
50
+ readonly raw: string;
51
+ readonly clientNamespace: string;
52
+ }, _optional?: Record<string, never>): ParseResult;
53
+ /** The hooks module contract: the module itself, or why it is refused. @complexity O(1). */
54
+ export declare function asApiConnectionHooksModule(required: {
55
+ readonly exported: unknown;
56
+ }, _optional?: Record<string, never>): ApiConnectionHooksModule | string;
57
+ /** Refuse another plugin's client config before reading environment or constructing a service.
58
+ * Full ids distinguish plugins sharing a prefix; dots and hyphens have distinct encodings to avoid
59
+ * namespace collisions ("acme.office" vs "acme-office"). O(c) over at most two runtime clients.
60
+ * @throws Error naming the plugin's namespace when a client setting lies outside it.
61
+ */
62
+ export declare function checkApiConnectionClientNamespace(required: {
63
+ readonly pluginId: string;
64
+ readonly clients: ApiConnectionDeclaration['clients'];
65
+ readonly clientNamespace: string;
66
+ }, _optional?: Record<string, never>): void;
67
+ export {};
68
+ //# sourceMappingURL=declarations.d.ts.map
@@ -0,0 +1,178 @@
1
+ import path from 'node:path';
2
+ import { parseConnectionBudgets } from './budgets.js';
3
+ /**
4
+ * @file Pure rules for a plugin's API-connections contribution file: the declaration parser, the
5
+ * hooks module contract and the client-setting namespace check. Loading stays with the host, which
6
+ * runs hooks through its one executable gate and accepts the descriptor only through
7
+ * `parseApiConnectionDescriptor`.
8
+ *
9
+ * Client config is only ever NAMED by the plugin: names must sit in the host's `clientNamespace`
10
+ * (a required host input; there is no default) and, at load, in the full plugin-id namespace, so a
11
+ * plugin can point at its own `…_CLIENT_ID` / `…_CLIENT_SECRET` and never at another secret of the
12
+ * host. Request budgets (`budgets`) are clamped to the host's maxima by `budgets.ts` and never reach
13
+ * the descriptor; nor do `scopeSets`, `apiOrigins` and `byoClient`, which only the host reads.
14
+ */
15
+ /** The setting-name part after the host's namespace. */
16
+ const CLIENT_ENV_REST_PATTERN = /^[A-Z0-9_]{1,80}_CLIENT_(ID|SECRET)$/;
17
+ /** A host's client-setting namespace: upper-case, ending in `_` (for example `ACME_`). */
18
+ const CLIENT_NAMESPACE_PATTERN = /^[A-Z][A-Z0-9_]{0,31}_$/;
19
+ const ID_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
20
+ const MAX_CONNECTIONS = 8;
21
+ const MAX_ORIGINS = 32;
22
+ const MAX_API_ORIGINS = 8;
23
+ const MAX_SCOPE_SETS = 16;
24
+ /** The scope-set id shape Jini's admin-surface port accepts. */
25
+ const SCOPE_SET_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
26
+ function isObject(value) {
27
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
28
+ }
29
+ function isOrigin(value) {
30
+ return typeof value === 'string' && URL.canParse(value) && new URL(value).origin === value;
31
+ }
32
+ function isEnvName(value, suffix, namespace) {
33
+ return typeof value === 'string' && value.startsWith(namespace) && CLIENT_ENV_REST_PATTERN.test(value.slice(namespace.length)) && value.endsWith(suffix);
34
+ }
35
+ function isOriginList(value) {
36
+ return Array.isArray(value) && value.length <= MAX_ORIGINS && value.every(isOrigin);
37
+ }
38
+ /** Both runtime clients, or why one is invalid. @complexity O(o) origins. */
39
+ function parseClients(clients, at, namespace) {
40
+ const web = parseClient(clients.web, `${at}.clients.web`, namespace);
41
+ const desktop = parseClient(clients.desktop, `${at}.clients.desktop`, namespace);
42
+ if (typeof web === 'string')
43
+ return web;
44
+ if (typeof desktop === 'string')
45
+ return desktop;
46
+ return { ...(web ? { web } : {}), ...(desktop ? { desktop } : {}) };
47
+ }
48
+ /** One client config, or why it is invalid. @complexity O(o) origins. */
49
+ // complexity-debt: four optional fields, each validated in place; splitting further only moves the branches.
50
+ function parseClient(value, at, namespace) {
51
+ if (value === undefined)
52
+ return undefined;
53
+ if (!isObject(value))
54
+ return `${at} must be an object`;
55
+ const { clientIdEnv, clientSecretEnv, redirectOrigins } = value;
56
+ if (!isEnvName(clientIdEnv, '_ID', namespace))
57
+ return `${at}.clientIdEnv must name a ${namespace}…_CLIENT_ID setting`;
58
+ if (clientSecretEnv !== undefined && !isEnvName(clientSecretEnv, '_SECRET', namespace))
59
+ return `${at}.clientSecretEnv must name a ${namespace}…_CLIENT_SECRET setting`;
60
+ if (redirectOrigins !== undefined && !isOriginList(redirectOrigins))
61
+ return `${at}.redirectOrigins must be a list of origins`;
62
+ return { clientIdEnv, ...(clientSecretEnv === undefined ? {} : { clientSecretEnv }), ...(redirectOrigins === undefined ? {} : { redirectOrigins }) };
63
+ }
64
+ function isHttpsOrigin(value) {
65
+ return isOrigin(value) && new URL(value).protocol === 'https:';
66
+ }
67
+ function isBoundedList(value, max, isItem) {
68
+ return Array.isArray(value) && value.length <= max && value.every(isItem);
69
+ }
70
+ const isScopeSetId = (id) => typeof id === 'string' && SCOPE_SET_ID_PATTERN.test(id);
71
+ /** Optional host-read fields, each bounded; absent lists are empty and an absent `byoClient` is false. @complexity O(n) entries. */
72
+ function parseHostLists(scopeSets, apiOrigins, byoClient, at) {
73
+ const sets = scopeSets ?? [];
74
+ const origins = apiOrigins ?? [];
75
+ if (!isBoundedList(sets, MAX_SCOPE_SETS, isScopeSetId))
76
+ return `${at}.scopeSets must be at most ${MAX_SCOPE_SETS} short ids`;
77
+ if (!isBoundedList(origins, MAX_API_ORIGINS, isHttpsOrigin))
78
+ return `${at}.apiOrigins must be at most ${MAX_API_ORIGINS} https:// origins`;
79
+ if (byoClient !== undefined && typeof byoClient !== 'boolean')
80
+ return `${at}.byoClient must be true or false`;
81
+ return { scopeSets: [...sets], apiOrigins: [...origins], byoClient: byoClient === true };
82
+ }
83
+ function idOrModuleProblem(id, module, at) {
84
+ if (typeof id !== 'string' || id.length > 64 || !ID_PATTERN.test(id))
85
+ return `${at}.id must be a lowercase hyphenated id`;
86
+ if (typeof module !== 'string' || !module.endsWith('.mjs') || path.posix.isAbsolute(module))
87
+ return `${at}.module must be a relative path ending in .mjs`;
88
+ return undefined;
89
+ }
90
+ /**
91
+ * One declaration, or why it is invalid. Either client may name a secret setting: the desktop
92
+ * (installed-app) client stays public even then, because some providers issue installed apps a
93
+ * secret that is not confidential; the host still keeps it in config only, never in output or logs.
94
+ * @complexity O(1).
95
+ */
96
+ function parseDeclaration(entry, at, namespace) {
97
+ if (!isObject(entry))
98
+ return `${at} must be an object`;
99
+ const { id, module, clients, budgets: declaredBudgets, scopeSets, apiOrigins, byoClient, ...descriptor } = entry;
100
+ const invalid = idOrModuleProblem(id, module, at);
101
+ if (invalid)
102
+ return invalid;
103
+ if (!isObject(clients))
104
+ return `${at}.clients must be an object`;
105
+ const runtimeClients = parseClients(clients, at, namespace);
106
+ if (typeof runtimeClients === 'string')
107
+ return runtimeClients;
108
+ const budgets = parseConnectionBudgets({ value: declaredBudgets, at: `${at}.budgets` });
109
+ if (typeof budgets === 'string')
110
+ return budgets;
111
+ const lists = parseHostLists(scopeSets, apiOrigins, byoClient, at);
112
+ if (typeof lists === 'string')
113
+ return lists;
114
+ // idOrModuleProblem returned undefined, so both are checked strings.
115
+ return { id: id, module: module, clients: runtimeClients, budgets, ...lists, descriptor };
116
+ }
117
+ const INVALID_JSON = Symbol('invalid-json');
118
+ function parseJson(raw) {
119
+ try {
120
+ return JSON.parse(raw);
121
+ }
122
+ catch {
123
+ return INVALID_JSON;
124
+ }
125
+ }
126
+ /** A host misconfiguration, not plugin data: refuse it loudly rather than accept every setting name. */
127
+ function checkedNamespace(clientNamespace) {
128
+ if (!CLIENT_NAMESPACE_PATTERN.test(clientNamespace))
129
+ throw new TypeError('clientNamespace must be upper-case letters, digits and underscores, ending in "_".');
130
+ return clientNamespace;
131
+ }
132
+ /**
133
+ * Parses a plugin's API-connections file. Pure; unknown keys go to the descriptor parser.
134
+ * `clientNamespace` is the host's client-setting prefix (for example `ACME_`); Jini ships no default.
135
+ * @throws TypeError when `clientNamespace` is malformed (host misconfiguration).
136
+ * @complexity O(c).
137
+ */
138
+ // complexity-debt: top-level shape checks plus the per-entry loop and duplicate check.
139
+ export function parseApiConnectionsFile(required, _optional = {}) {
140
+ const namespace = checkedNamespace(required.clientNamespace);
141
+ const value = parseJson(required.raw);
142
+ if (value === INVALID_JSON)
143
+ return { ok: false, reason: 'not valid JSON' };
144
+ if (!isObject(value) || value.schemaVersion !== 1)
145
+ return { ok: false, reason: 'schemaVersion must be 1' };
146
+ if (!Array.isArray(value.connections) || value.connections.length > MAX_CONNECTIONS)
147
+ return { ok: false, reason: `connections must be an array of at most ${MAX_CONNECTIONS}` };
148
+ const descriptors = [];
149
+ for (const [index, entry] of value.connections.entries()) {
150
+ const result = parseDeclaration(entry, `connections[${index}]`, namespace);
151
+ if (typeof result === 'string')
152
+ return { ok: false, reason: result };
153
+ if (descriptors.some((seen) => seen.id === result.id))
154
+ return { ok: false, reason: `connections[${index}].id '${result.id}' is declared twice` };
155
+ descriptors.push(result);
156
+ }
157
+ return { ok: true, descriptors };
158
+ }
159
+ /** The hooks module contract: the module itself, or why it is refused. @complexity O(1). */
160
+ export function asApiConnectionHooksModule(required, _optional = {}) {
161
+ const { exported } = required;
162
+ return isObject(exported) && typeof exported.createHooks === 'function' ? exported : 'its module has no createHooks() function';
163
+ }
164
+ /** Refuse another plugin's client config before reading environment or constructing a service.
165
+ * Full ids distinguish plugins sharing a prefix; dots and hyphens have distinct encodings to avoid
166
+ * namespace collisions ("acme.office" vs "acme-office"). O(c) over at most two runtime clients.
167
+ * @throws Error naming the plugin's namespace when a client setting lies outside it.
168
+ */
169
+ export function checkApiConnectionClientNamespace(required, _optional = {}) {
170
+ const namespace = `${checkedNamespace(required.clientNamespace)}${required.pluginId.toUpperCase().replaceAll('.', '__').replaceAll('-', '_')}_`;
171
+ for (const [runtime, client] of Object.entries(required.clients)) {
172
+ const prefix = `${namespace}OAUTH_${runtime.toUpperCase()}_CLIENT_`;
173
+ if (client && (client.clientIdEnv !== `${prefix}ID` || (client.clientSecretEnv !== undefined && client.clientSecretEnv !== `${prefix}SECRET`))) {
174
+ throw new Error(`Client settings must belong to this plugin's ${namespace} namespace.`);
175
+ }
176
+ }
177
+ }
178
+ //# sourceMappingURL=declarations.js.map
@@ -5,7 +5,8 @@
5
5
  * typed object instead of re-declaring eleven ports.
6
6
  */
7
7
  import type { Clock } from '@jini-ai/core/primitives';
8
- import type { OAuthAppOptions, OAuthClient, OAuthFetch, OAuthRandomBytes, OAuthSleep, OAuthUrlGuard } from '@jini-ai/oauth';
8
+ import type { OAuthAppOptions, OAuthClient, OAuthFetch, OAuthRandomBytes, OAuthSleep, OAuthUrlGuard } from '@jini-ai/core/contracts/oauth';
9
+ import type { ApiConnectionOAuthCapabilities } from './oauth-capabilities.js';
9
10
  import type { ApiConnectionHooks, ApiConnectionRecordStore, ApiConnectionTokenStore } from './ports.js';
10
11
  import type { ApiConnectionDescriptor } from './types.js';
11
12
  export interface ApiConnectionServiceDeps {
@@ -31,6 +32,8 @@ export interface ApiConnectionServiceDeps {
31
32
  readonly clock: Clock;
32
33
  readonly randomBytesFn: OAuthRandomBytes;
33
34
  readonly sleep: OAuthSleep;
35
+ /** @agent-note Required; the host's ONE `ApiConnectionOAuthCapabilities` object (real `@jini-ai/oauth` exports), the same instance for every service it creates. */
36
+ readonly oauth: ApiConnectionOAuthCapabilities;
34
37
  }
35
38
  export type ApiConnectionClientKind = 'public' | 'confidential';
36
39
  /**
@@ -1,6 +1,21 @@
1
1
  import type { ApiConnectionDescriptor } from './types.js';
2
+ interface FieldRules {
3
+ readonly maxFields: number;
4
+ readonly maxLength: number;
5
+ readonly acceptsName: (name: string) => boolean;
6
+ }
7
+ /**
8
+ * The loopback receiver's callback-field limits and name rule.
9
+ * @agent-note Required host input bound from the real `@jini-ai/oauth` exports (`maxFields` = `MAX_CALLBACK_FIELDS`, `maxLength` =
10
+ * `MAX_CALLBACK_FIELD_LENGTH`, `acceptsName` = `isCallbackFieldName`); one source of truth, never copied or defaulted here.
11
+ */
12
+ export type ApiConnectionCallbackFieldRules = FieldRules;
2
13
  /** Validate and freeze a plugin-declared connection. Throws `descriptor-invalid` naming the bad part. */
3
14
  export declare function parseApiConnectionDescriptor(requiredArgs: {
4
15
  readonly value: unknown;
16
+ /** The loopback receiver's own limits and name rule (one source of truth in the OAuth core), so a
17
+ * declaration accepted here never fails only on desktop. */
18
+ readonly callbackFieldRules: ApiConnectionCallbackFieldRules;
5
19
  }): ApiConnectionDescriptor;
20
+ export {};
6
21
  //# sourceMappingURL=descriptor.d.ts.map
@@ -5,7 +5,6 @@
5
5
  * field limit is checked once here so the flow code can trust the shape. Endpoint safety (scheme,
6
6
  * private hosts, DNS) is still enforced at use by the injected OAuth URL guard.
7
7
  */
8
- import { isCallbackFieldName, MAX_CALLBACK_FIELD_LENGTH, MAX_CALLBACK_FIELDS } from '@jini-ai/oauth';
9
8
  import { ApiConnectionError } from './errors.js';
10
9
  const ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
11
10
  const PARAM_NAME_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
@@ -15,9 +14,6 @@ const MAX_PARAMS = 16;
15
14
  const MAX_PARAM_VALUE_LENGTH = 512;
16
15
  /** Start values ride in the authorization URL; 8 KiB stays within common server request-line limits. */
17
16
  const START_PARAM_RULES = { maxFields: 8, maxLength: 8192, acceptsName: () => true };
18
- /** The loopback receiver's own limits and name rule (one source of truth in the OAuth core), so a
19
- * declaration accepted here never fails only on desktop. */
20
- const CALLBACK_FIELD_RULES = { maxFields: MAX_CALLBACK_FIELDS, maxLength: MAX_CALLBACK_FIELD_LENGTH, acceptsName: isCallbackFieldName };
21
17
  /** Names the OAuth core sets itself or reads from the callback; a plugin may not shadow them. */
22
18
  const RESERVED_NAMES = new Set([
23
19
  'resource', 'response_type', 'client_id', 'redirect_uri', 'scope', 'state', 'code',
@@ -105,7 +101,7 @@ export function parseApiConnectionDescriptor(requiredArgs) {
105
101
  }),
106
102
  forceConsentParams: readParams(source.forceConsentParams, 'forceConsentParams'),
107
103
  startParams: readFields(source.startParams, 'startParams', START_PARAM_RULES),
108
- callbackFields: readFields(source.callbackFields, 'callbackFields', CALLBACK_FIELD_RULES),
104
+ callbackFields: readFields(source.callbackFields, 'callbackFields', requiredArgs.callbackFieldRules),
109
105
  });
110
106
  }
111
107
  //# sourceMappingURL=descriptor.js.map
@@ -1,4 +1,4 @@
1
- import type { OAuthTokenSet } from '@jini-ai/oauth';
1
+ import type { OAuthTokenSet } from '@jini-ai/core/contracts/oauth';
2
2
  import type { ApiConnectionServiceDeps } from './deps.js';
3
3
  import type { ApiConnectionAccount, ApiConnectionAttempt } from './types.js';
4
4
  export interface CompletedAuthorization {
@@ -0,0 +1,20 @@
1
+ import type { DeclaredApiConnection, PluginHttp } from "./host-ports.js";
2
+ /**
3
+ * @file The HTTP a connection's hooks module (account identity, revocation, scope sets) receives:
4
+ * the host's guarded plugin HTTP, limited to the origins that connection declares (`apiOrigins`)
5
+ * plus its token endpoint's origin (where providers serve revocation). Hooks see fresh access and
6
+ * refresh tokens during sign-in and disconnect, so unscoped public https would let a hook carry
7
+ * one to any host; this keeps them on the provider the plugin declared.
8
+ */
9
+ export declare const CONNECTION_HOOK_UNDECLARED_ORIGIN_MESSAGE = "A plugin's sign-in code may only call its connection's declared API addresses and its token endpoint. Report this to the plugin author.";
10
+ /**
11
+ * Wraps `http` so only the connection's declared origins are reachable. The origin is compared
12
+ * exactly (scheme, host and port), so a look-alike host, plaintext or another port is refused
13
+ * before anything is sent; an unparsable URL gets the same refusal.
14
+ * @complexity O(o) declared origins per fetch, then the wrapped fetch.
15
+ */
16
+ export declare function createConnectionHookHttp(required: {
17
+ readonly http: PluginHttp;
18
+ readonly connection: Pick<DeclaredApiConnection, "apiOrigins" | "descriptor">;
19
+ }, _optional?: Record<string, never>): PluginHttp;
20
+ //# sourceMappingURL=hook-http.d.ts.map
@@ -0,0 +1,27 @@
1
+ /**
2
+ * @file The HTTP a connection's hooks module (account identity, revocation, scope sets) receives:
3
+ * the host's guarded plugin HTTP, limited to the origins that connection declares (`apiOrigins`)
4
+ * plus its token endpoint's origin (where providers serve revocation). Hooks see fresh access and
5
+ * refresh tokens during sign-in and disconnect, so unscoped public https would let a hook carry
6
+ * one to any host; this keeps them on the provider the plugin declared.
7
+ */
8
+ export const CONNECTION_HOOK_UNDECLARED_ORIGIN_MESSAGE = "A plugin's sign-in code may only call its connection's declared API addresses and its token endpoint. Report this to the plugin author.";
9
+ /**
10
+ * Wraps `http` so only the connection's declared origins are reachable. The origin is compared
11
+ * exactly (scheme, host and port), so a look-alike host, plaintext or another port is refused
12
+ * before anything is sent; an unparsable URL gets the same refusal.
13
+ * @complexity O(o) declared origins per fetch, then the wrapped fetch.
14
+ */
15
+ export function createConnectionHookHttp(required, _optional = {}) {
16
+ const { http, connection } = required;
17
+ const allowed = new Set([...connection.apiOrigins, new URL(connection.descriptor.tokenEndpoint).origin]);
18
+ return {
19
+ async fetch(target, options) {
20
+ const origin = URL.parse(target.url)?.origin;
21
+ if (origin === undefined || !allowed.has(origin))
22
+ throw new Error(CONNECTION_HOOK_UNDECLARED_ORIGIN_MESSAGE);
23
+ return http.fetch(target, options);
24
+ },
25
+ };
26
+ }
27
+ //# sourceMappingURL=hook-http.js.map