@jskit-ai/connectors-core 0.2.27 → 0.2.29

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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - An operation marked `sideEffect: true` (one that sends a message, posts, books, charges or triggers another system) runs only when the application's `SIDE_EFFECTS` is `live`. Otherwise it is checked exactly as a real one, logged with `logSimulatedSideEffect`, and `invoke` answers `{ simulated: true }` without reaching the provider or touching the connection's `verifiedAt`. `createConnectionService` takes `sideEffects` (default `simulate`) and an optional `logger`; `createConnectorsFeature` reads the setting from `runtime.env` and logs through `runtime.logger`, which it now requires, and its options cannot override it.
5
6
  - A connection's status reads its row without a transaction or lock, and no longer creates an empty row for every person and integration whose status is viewed. `status()` calls `withConnection(slot, work, { readOnly: true })`; the SQL store reads the row with a plain get for such work, and the file store and a custom store that ignores the option still answer correctly.
6
7
  - connector_authorization_attempts declares its foreign key, connection_key to connector_connections.connection_key (`foreignKeys`), so json-rest-api 3.1.0 can skip the visibility query a system-context read makes for a record such a key guarantees exists. `jskit test --databases` checks each against an app's test database. `knexConnectionStore.test.js` proves it matches the migration on the connector test database.
7
8
  - `@jskit-ai/database-runtime` and `@jskit-ai/resource-runtime` are optional peer dependencies, as they are of assistant-runtime, instead of dependencies: an app without a database installs, composes and starts the package without them, where installing them made boot refuse it for want of a database driver. An app that uses its knex connection store (`./server/storage`) has them through its database.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/connectors-core",
3
- "version": "0.2.27",
3
+ "version": "0.2.29",
4
4
  "description": "Portable integration configuration and server-side account connection runtime.",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -15,7 +15,7 @@
15
15
  "./locales/en.json": "./locales/en.json"
16
16
  },
17
17
  "dependencies": {
18
- "@jskit-ai/resource-core": "0.1.210",
18
+ "@jskit-ai/resource-core": "0.1.212",
19
19
  "jose": "^6.1.3",
20
20
  "json-rest-schema": "^1.0.20",
21
21
  "oauth4webapi": "3.8.8",
@@ -56,10 +56,10 @@
56
56
  }
57
57
  },
58
58
  "peerDependencies": {
59
- "@jskit-ai/database-runtime": "0.1.268",
60
- "@jskit-ai/http-runtime": "0.2.19",
61
- "@jskit-ai/kernel": "0.2.19",
62
- "@jskit-ai/resource-runtime": "0.2.24"
59
+ "@jskit-ai/database-runtime": "0.1.270",
60
+ "@jskit-ai/http-runtime": "0.2.21",
61
+ "@jskit-ai/kernel": "0.2.21",
62
+ "@jskit-ai/resource-runtime": "0.2.26"
63
63
  },
64
64
  "peerDependenciesMeta": {
65
65
  "@jskit-ai/database-runtime": {
@@ -1,4 +1,5 @@
1
1
  import { defineFeature } from "@jskit-ai/kernel/server/features";
2
+ import { resolveSideEffectsMode } from "@jskit-ai/kernel/shared/support/sideEffects";
2
3
  import { createSchema } from "json-rest-schema";
3
4
  import { createConnectionService } from "./connectionService.js";
4
5
 
@@ -68,21 +69,31 @@ function createConnectorsActions({ connections }) {
68
69
  /**
69
70
  * The `connectors.core` feature. Given no `store`, it keeps connections in the `connectors.store` capability, which
70
71
  * createConnectionStoreFeature() provides on the connector tables; without that feature the app fails at startup, naming it.
71
- * @param {Omit<import("./types.js").ConnectionServiceOptions, "store"> & { store?: import("./types.js").ConnectionStore }} options
72
+ * Its operations marked `sideEffect` follow the application's SIDE_EFFECTS, never an option.
73
+ * @param {Omit<import("./types.js").ConnectionServiceOptions, "store" | "sideEffects" | "logger"> & { store?: import("./types.js").ConnectionStore }} options
72
74
  */
73
75
  function createConnectorsFeature(options) {
74
76
  return defineFeature({
75
77
  id: "connectors.core",
76
78
  domain: "connectors",
77
- requires: options.store ? {} : { store: "connectors.store" },
79
+ requires: {
80
+ env: "runtime.env",
81
+ logger: "runtime.logger",
82
+ ...(options.store ? {} : { store: "connectors.store" })
83
+ },
78
84
  hints: options.store ? {} : {
79
85
  "connectors.store": "Register createConnectionStoreFeature({ protection }) from @jskit-ai/connectors-core/server/storage " +
80
86
  "in your server providers, or pass createConnectorsFeature({ store })."
81
87
  },
82
88
  provides: { connections: "connectors.core" },
83
- /** @param {{ store?: import("./types.js").ConnectionStore }} dependencies */
84
- setup({ store = options.store }) {
85
- return { connections: createConnectionService({ ...options, store }) };
89
+ /**
90
+ * Operations marked `sideEffect` follow the application's SIDE_EFFECTS: simulated unless it is exactly `live`.
91
+ * @param {{ env: import("@jskit-ai/kernel/server/types").RuntimeEnv, logger: import("@jskit-ai/kernel/server/types").RuntimeLogger, store?: import("./types.js").ConnectionStore }} dependencies
92
+ */
93
+ setup({ env, logger, store = options.store }) {
94
+ return {
95
+ connections: createConnectionService({ ...options, store, sideEffects: resolveSideEffectsMode(env), logger })
96
+ };
86
97
  },
87
98
  actions({ connections }) {
88
99
  return createConnectorsActions({ connections });
@@ -4,7 +4,7 @@ import { createHash } from "node:crypto";
4
4
  import { registrationClientAuthentication, registrationGrantType, validateIntegrationConfiguration } from "../shared/configuration.js";
5
5
  import { createConnectionCredentials } from "./connectionCredentials.js";
6
6
  import { ConnectorError, providerError } from "./errors.js";
7
- import { connectionProvider, createProviderRequests, operationRequest, requireOperationScope, tokenResponse } from "./providerRequests.js";
7
+ import { SIMULATED_RESULT, connectionProvider, createProviderRequests, operationRequest, requireOperationScope, tokenResponse } from "./providerRequests.js";
8
8
 
9
9
  function publicConnection(connection) {
10
10
  if (!connection) return { status: "disconnected" };
@@ -59,6 +59,9 @@ function callbackMatches(connection, provider, registration) {
59
59
  * @param {"application" | "assistant"} [options.executionMode]
60
60
  * @param {typeof globalThis.fetch} [options.fetchImpl]
61
61
  * @param {() => number} [options.now]
62
+ * @param {"live" | "simulate"} [options.sideEffects] The application's SIDE_EFFECTS setting. Unless `live`, operations
63
+ * marked `sideEffect` are checked and logged, never sent, and answer `{ simulated: true }`.
64
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger | Console} [options.logger] Where simulated operations are logged.
62
65
  */
63
66
  function createConnectionService({
64
67
  configuration,
@@ -68,7 +71,9 @@ function createConnectionService({
68
71
  authorize,
69
72
  executionMode = "application",
70
73
  fetchImpl = globalThis.fetch,
71
- now = Date.now
74
+ now = Date.now,
75
+ sideEffects = "simulate",
76
+ logger = console
72
77
  }) {
73
78
  if (!["application", "assistant"].includes(executionMode)) throw new TypeError("Select application or assistant execution.");
74
79
  const config = validateIntegrationConfiguration(configuration, { providers });
@@ -90,7 +95,7 @@ function createConnectionService({
90
95
  );
91
96
  }
92
97
  const connectionCredentials = createConnectionCredentials({ config, resolveReference });
93
- const providerRequests = createProviderRequests({ fetchImpl, now, resolveReference });
98
+ const providerRequests = createProviderRequests({ fetchImpl, now, resolveReference, sideEffects, logger });
94
99
 
95
100
  async function access(context, integrationId, operation, input, checkAssistantPermission = true) {
96
101
  const integration = integrations[integrationId];
@@ -428,6 +433,8 @@ function createConnectionService({
428
433
  }
429
434
  const credentials = usesApiKey ? { ...connection, apiKey: await connectionCredentials.apiKeyFor(integration, provider) } : connection;
430
435
  const result = await providerRequests.request(provider, operation, input, credentials, signal);
436
+ // A simulated operation never reached the provider, so it proves nothing about the credential.
437
+ if (result === SIMULATED_RESULT) return { result };
431
438
  await save({ ...connection, verifiedAt: now(),
432
439
  ...(usesApiKey ? { credentialFingerprint: createHash("sha256").update(credentials.apiKey).digest("hex") } : {})
433
440
  });
@@ -1,11 +1,14 @@
1
1
  import * as oauth from "oauth4webapi";
2
2
  import { createHttpClient } from "@jskit-ai/http-runtime/client";
3
+ import { logSimulatedSideEffect } from "@jskit-ai/kernel/server/runtime/sideEffects";
3
4
  import { ConnectorError } from "./errors.js";
4
5
 
5
6
  const DEFAULT_SCOPE_SEPARATOR = " ";
6
7
  // Every OAuth token request takes this timeout; a provider's operations default to it.
7
8
  const REQUEST_TIMEOUT_MS = 15_000;
8
9
  const DEFAULT_TOKEN_REFRESH_LEEWAY_MS = 30_000;
10
+ // What a simulated side-effect operation answers in a test copy, in place of the provider's answer.
11
+ const SIMULATED_RESULT = Object.freeze({ simulated: true });
9
12
 
10
13
  /**
11
14
  * A provider as an integration's requests use it: with its runtime for the
@@ -83,8 +86,11 @@ function operationRequest(operation, input, settings, providerData) {
83
86
  * @param {typeof globalThis.fetch} dependencies.fetchImpl
84
87
  * @param {() => number} dependencies.now
85
88
  * @param {import("./types.js").ResolveReference} dependencies.resolveReference
89
+ * @param {"live" | "simulate"} [dependencies.sideEffects] Unless `live`, an operation marked `sideEffect` (one that
90
+ * sends a message, charges, books or posts) is checked and logged, never sent, and answers `{ simulated: true }`.
91
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger | Console} [dependencies.logger]
86
92
  */
87
- function createProviderRequests({ fetchImpl, now, resolveReference }) {
93
+ function createProviderRequests({ fetchImpl, now, resolveReference, sideEffects = "simulate", logger = console }) {
88
94
  const http = createHttpClient({ fetchImpl, csrf: { enabled: false }, credentials: "omit" });
89
95
 
90
96
  /**
@@ -129,6 +135,15 @@ function createProviderRequests({ fetchImpl, now, resolveReference }) {
129
135
  if (url.protocol !== "https:" || url.username || url.password || !origins.includes(url.origin)) {
130
136
  throw new ConnectorError("connector_destination_invalid", "The provider operation has an invalid destination.", { messageCode: "connectors.connection.providerOperationInvalidDestination" });
131
137
  }
138
+ // A test copy checks a side effect like a real one, then logs it in place of sending it.
139
+ if (operation.sideEffect === true && sideEffects !== "live") {
140
+ logSimulatedSideEffect(logger, {
141
+ kind: "connector operation",
142
+ summary: `the ${provider.id} ${operationId} request`,
143
+ details: { provider: provider.id, operation: operationId, input }
144
+ });
145
+ return SIMULATED_RESULT;
146
+ }
132
147
  // readable-check: allow method-probe - optional operation: apiKey.pathPrefix is an optional hook of the provider definition
133
148
  if (connection.method === "api-key" && typeof provider.apiKey.pathPrefix === "function") {
134
149
  const prefix = provider.apiKey.pathPrefix(connection.apiKey);
@@ -288,4 +303,4 @@ function createProviderRequests({ fetchImpl, now, resolveReference }) {
288
303
  });
289
304
  }
290
305
 
291
- export { connectionProvider, createProviderRequests, operationRequest, requireOperationScope, tokenResponse };
306
+ export { SIMULATED_RESULT, connectionProvider, createProviderRequests, operationRequest, requireOperationScope, tokenResponse };
@@ -93,6 +93,9 @@
93
93
  * @property {(result: any, request: ConnectorRequest) => boolean} [validateResult] Answers whether the response is what was asked.
94
94
  * @property {string} [assistantAction] The assistant action whose permission covers it; its operation id otherwise.
95
95
  * @property {string[]} [authenticationMethods] The credential modes it runs with; every mode otherwise.
96
+ * @property {boolean} [sideEffect] True for an operation that acts on the world: sends a message, charges, books or
97
+ * posts. Unless the application's SIDE_EFFECTS is `live`, it is checked and logged, never sent, and answers
98
+ * `{ simulated: true }`.
96
99
  */
97
100
 
98
101
  /**
@@ -109,7 +109,7 @@ test("connections without a store fail at startup, naming the feature to registe
109
109
  authorize: async (context) => context, resolveReference: async () => ""
110
110
  };
111
111
  // The kernel's startup error names the missing capability and adds the feature's hint.
112
- assert.throws(() => createCapabilityRuntime({ inputs: { "runtime.logger": silentLogger }, providers: [EventProvider, ActionProvider, createConnectorsFeature(options)] }), {
112
+ assert.throws(() => createCapabilityRuntime({ inputs: { "runtime.env": {}, "runtime.logger": silentLogger }, providers: [EventProvider, ActionProvider, createConnectorsFeature(options)] }), {
113
113
  message: 'Provider "connectors.core" requires missing capability "connectors.store". Register createConnectionStoreFeature({ protection }) ' +
114
114
  "from @jskit-ai/connectors-core/server/storage in your server providers, or pass createConnectorsFeature({ store })."
115
115
  });
@@ -131,7 +131,7 @@ test("the ordinary credential-free Feature action verifies without resolving ref
131
131
  return Response.json({ meta: [], data: [{ ok: 1, user: "default" }], rows: 1 });
132
132
  }
133
133
  };
134
- const runtime = createCapabilityRuntime({ inputs: { "runtime.logger": silentLogger }, providers: [
134
+ const runtime = createCapabilityRuntime({ inputs: { "runtime.env": {}, "runtime.logger": silentLogger }, providers: [
135
135
  EventProvider, ActionProvider, createConnectorsFeature(options),
136
136
  defineProvider({ id: "test.credential-free-observer", requires: { catalogue: "runtime.actions" }, setup({ catalogue }) { actions = catalogue; } })
137
137
  ] });
@@ -415,7 +415,7 @@ test("cancelling a service token exchange preserves the previous grant without r
415
415
  test("the client credentials Feature action uses the ordinary application policy and runtime", async () => {
416
416
  const { options } = serviceAccountSetup();
417
417
  let actions;
418
- const runtime = createCapabilityRuntime({ inputs: { "runtime.logger": silentLogger }, providers: [EventProvider, ActionProvider, createConnectorsFeature(options),
418
+ const runtime = createCapabilityRuntime({ inputs: { "runtime.env": {}, "runtime.logger": silentLogger }, providers: [EventProvider, ActionProvider, createConnectorsFeature(options),
419
419
  defineProvider({ id: "test.service-observer", requires: { catalogue: "runtime.actions" }, setup({ catalogue }) { actions = catalogue; } })] });
420
420
  await runtime.start();
421
421
  try {
@@ -886,7 +886,7 @@ test("configuration rejects gateway registrations before constructing a runtime"
886
886
  test("the Feature exposes ordinary JSKIT actions with application authorization", async () => {
887
887
  const { options } = setup();
888
888
  let actions;
889
- const runtime = createCapabilityRuntime({ inputs: { "runtime.logger": silentLogger }, providers: [
889
+ const runtime = createCapabilityRuntime({ inputs: { "runtime.env": {}, "runtime.logger": silentLogger }, providers: [
890
890
  EventProvider, ActionProvider, createConnectorsFeature(options),
891
891
  defineProvider({
892
892
  id: "test.observer", requires: { catalogue: "runtime.actions" },
@@ -1055,7 +1055,7 @@ test("JSON-body credentials replace supplied values, preserve input and reach th
1055
1055
  }
1056
1056
  };
1057
1057
  let actions;
1058
- const runtime = createCapabilityRuntime({ inputs: { "runtime.logger": silentLogger }, providers: [
1058
+ const runtime = createCapabilityRuntime({ inputs: { "runtime.env": {}, "runtime.logger": silentLogger }, providers: [
1059
1059
  EventProvider, ActionProvider, createConnectorsFeature(options),
1060
1060
  defineProvider({ id: "test.body-observer", requires: { catalogue: "runtime.actions" }, setup({ catalogue }) { actions = catalogue; } })
1061
1061
  ] });
@@ -1339,3 +1339,69 @@ test("missing API key preserves a verified connection until explicit disconnect"
1339
1339
  assert.deepEqual(await service.status(input), { status: "unconfigured", configurationError: "connector_binding_missing" });
1340
1340
  assert.equal(requests, 1);
1341
1341
  });
1342
+
1343
+ test("a test copy checks and logs a side-effect operation without sending it, and a live application sends it", async () => {
1344
+ const config = { schemaVersion: 1, registrations: {}, integrations: { mail: {
1345
+ provider: "resend", accountMode: "shared", scopes: [], authentication: { method: "api-key", secretRef: "env:KEY" }
1346
+ } } };
1347
+ const message = { from: "app@example.test", to: ["person@example.test"], subject: "Hello", text: "Hi", idempotencyKey: "m-1" };
1348
+ const sent = [];
1349
+ const logged = [];
1350
+ const store = memoryStore();
1351
+ const options = {
1352
+ configuration: config, providers: [resendProvider], store, authorize: async () => owner, resolveReference: async () => "fixture-key",
1353
+ logger: { info: (details, text) => logged.push({ details, text }) },
1354
+ fetchImpl: async (url) => {
1355
+ sent.push(String(url));
1356
+ return Response.json(String(url).endsWith("/emails") ? { id: "email-1" } : { object: "list", data: [], has_more: false });
1357
+ }
1358
+ };
1359
+ const input = { context: owner, integrationId: "mail" };
1360
+ const simulated = createConnectionService(options);
1361
+ await simulated.connectApiKey(input);
1362
+ assert.equal(sent.length, 1, "verification is a read and runs for real");
1363
+ assert.match(sent[0], /^https:\/\/api\.resend\.com\/domains/u);
1364
+ const verifiedAt = store.connections.values().next().value.verifiedAt;
1365
+ assert.deepEqual(await simulated.invoke({ ...input, operation: "emails.send", input: message }), { simulated: true });
1366
+ assert.equal(sent.length, 1, "nothing was sent");
1367
+ assert.equal(store.connections.values().next().value.verifiedAt, verifiedAt, "a simulation proves nothing about the key");
1368
+ assert.equal(logged.length, 1);
1369
+ assert.deepEqual(logged[0].details, { sideEffects: "simulate", kind: "connector operation", provider: "resend", operation: "emails.send", input: message });
1370
+ assert.match(logged[0].text, /^Test copy: the resend emails\.send request was simulated, not sent/u);
1371
+ // A simulated operation is checked like a real one.
1372
+ await assert.rejects(simulated.invoke({ ...input, operation: "emails.send", input: { ...message, to: [] } }), { code: "connector_input_invalid" });
1373
+
1374
+ const live = createConnectionService({ ...options, sideEffects: "live" });
1375
+ assert.deepEqual(await live.invoke({ ...input, operation: "emails.send", input: message }), { id: "email-1" });
1376
+ assert.deepEqual(sent.slice(1), ["https://api.resend.com/emails"]);
1377
+ });
1378
+
1379
+ test("the connectors feature follows the application's SIDE_EFFECTS, which its options cannot override", async () => {
1380
+ for (const [env, expected] of [[{}, 0], [{ SIDE_EFFECTS: "live" }, 1]]) {
1381
+ let connections;
1382
+ const sent = [];
1383
+ const runtime = createCapabilityRuntime({ inputs: { "runtime.env": env, "runtime.logger": silentLogger }, providers: [
1384
+ EventProvider, ActionProvider,
1385
+ createConnectorsFeature({
1386
+ configuration: { schemaVersion: 1, registrations: {}, integrations: { mail: {
1387
+ provider: "resend", accountMode: "shared", scopes: [], authentication: { method: "api-key", secretRef: "env:KEY" }
1388
+ } } },
1389
+ providers: [resendProvider], store: memoryStore(), authorize: async () => owner, resolveReference: async () => "fixture-key",
1390
+ sideEffects: "live",
1391
+ fetchImpl: async (url) => {
1392
+ sent.push(String(url));
1393
+ return Response.json(String(url).endsWith("/emails") ? { id: "email-1" } : { object: "list", data: [], has_more: false });
1394
+ }
1395
+ }),
1396
+ defineProvider({ id: "test.side-effects-observer", requires: { core: "connectors.core" }, setup({ core }) { connections = core; } })
1397
+ ] });
1398
+ await runtime.start();
1399
+ try {
1400
+ const input = { context: owner, integrationId: "mail" };
1401
+ await connections.connectApiKey(input);
1402
+ await connections.invoke({ ...input, operation: "emails.send",
1403
+ input: { from: "app@example.test", to: ["person@example.test"], subject: "Hello", text: "Hi", idempotencyKey: "m-1" } });
1404
+ assert.equal(sent.filter((url) => url.endsWith("/emails")).length, expected, JSON.stringify(env));
1405
+ } finally { await runtime.shutdown(); }
1406
+ }
1407
+ });
@@ -184,7 +184,7 @@ test("service grants honor cancellation and deadlines without replay or partial
184
184
 
185
185
  test("the service-account Feature action uses the same application policy and verified runtime", async (t) => {
186
186
  const f = await fixture(t); let actions;
187
- const runtime = createCapabilityRuntime({ inputs: { "runtime.logger": silentLogger }, providers: [EventProvider, ActionProvider, createConnectorsFeature(f.options),
187
+ const runtime = createCapabilityRuntime({ inputs: { "runtime.env": {}, "runtime.logger": silentLogger }, providers: [EventProvider, ActionProvider, createConnectorsFeature(f.options),
188
188
  defineProvider({ id: "test.service-observer", requires: { catalogue: "runtime.actions" }, setup({ catalogue }) { actions = catalogue; } })] });
189
189
  await runtime.start();
190
190
  try {