@jskit-ai/connectors-core 0.2.38 → 0.2.40

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
+ - **Breaking:** `createConnectionService` takes `appEnv` (the application's `APP_ENV`, `appEnvironment(env)`) in place of `sideEffects`, and requires it: anything but the four environments throws `Supply appEnv, the application's APP_ENV: appEnvironment(env).` Only production sends an operation marked `sideEffect`; elsewhere it is checked, logged (`Staging: the resend emails.send request was logged, not sent: only production acts for real.`) and answered `{ simulated: true }`. `createConnectorsFeature` reads `APP_ENV` from `runtime.env` itself.
5
6
  - 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.
6
7
  - 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.
7
8
  - 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.
package/README.md CHANGED
@@ -116,7 +116,9 @@ const connections = createConnectionService({
116
116
  providers: [googleCalendarProvider],
117
117
  store,
118
118
  resolveReference: createEnvironmentReferenceResolver(process.env),
119
- authorize: applicationConnectionPolicy
119
+ authorize: applicationConnectionPolicy,
120
+ // The application's APP_ENV, appEnvironment(process.env): only production sends side-effect operations.
121
+ appEnv: appEnvironment(process.env)
120
122
  });
121
123
  ```
122
124
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/connectors-core",
3
- "version": "0.2.38",
3
+ "version": "0.2.40",
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.217",
18
+ "@jskit-ai/resource-core": "0.1.218",
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.275",
60
- "@jskit-ai/http-runtime": "0.2.26",
61
- "@jskit-ai/kernel": "0.2.26",
62
- "@jskit-ai/resource-runtime": "0.2.35"
59
+ "@jskit-ai/database-runtime": "0.1.276",
60
+ "@jskit-ai/http-runtime": "0.2.27",
61
+ "@jskit-ai/kernel": "0.2.27",
62
+ "@jskit-ai/resource-runtime": "0.2.37"
63
63
  },
64
64
  "peerDependenciesMeta": {
65
65
  "@jskit-ai/database-runtime": {
@@ -1,5 +1,5 @@
1
1
  import { defineFeature } from "@jskit-ai/kernel/server/features";
2
- import { resolveSideEffectsMode } from "@jskit-ai/kernel/shared/support/sideEffects";
2
+ import { appEnvironment } from "@jskit-ai/kernel/shared/support/appEnvironment";
3
3
  import { createSchema } from "json-rest-schema";
4
4
  import { createConnectionService } from "./connectionService.js";
5
5
 
@@ -69,8 +69,8 @@ function createConnectorsActions({ connections }) {
69
69
  /**
70
70
  * The `connectors.core` feature. Given no `store`, it keeps connections in the `connectors.store` capability, which
71
71
  * createConnectionStoreFeature() provides on the connector tables; without that feature the app fails at startup, naming it.
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
+ * Its operations marked `sideEffect` follow the application's APP_ENV, never an option: only production sends them.
73
+ * @param {Omit<import("./types.js").ConnectionServiceOptions, "store" | "appEnv" | "logger"> & { store?: import("./types.js").ConnectionStore }} options
74
74
  */
75
75
  function createConnectorsFeature(options) {
76
76
  return defineFeature({
@@ -87,12 +87,12 @@ function createConnectorsFeature(options) {
87
87
  },
88
88
  provides: { connections: "connectors.core" },
89
89
  /**
90
- * Operations marked `sideEffect` follow the application's SIDE_EFFECTS: simulated unless it is exactly `live`.
90
+ * Operations marked `sideEffect` follow the application's APP_ENV: logged, not sent, outside production.
91
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
92
  */
93
93
  setup({ env, logger, store = options.store }) {
94
94
  return {
95
- connections: createConnectionService({ ...options, store, sideEffects: resolveSideEffectsMode(env), logger })
95
+ connections: createConnectionService({ ...options, store, appEnv: appEnvironment(env), logger })
96
96
  };
97
97
  },
98
98
  actions({ connections }) {
@@ -1,6 +1,7 @@
1
1
  import * as oauth from "oauth4webapi";
2
2
  import { isDeepStrictEqual } from "node:util";
3
3
  import { createHash } from "node:crypto";
4
+ import { APP_ENVIRONMENTS } from "@jskit-ai/kernel/shared/support/appEnvironment";
4
5
  import { registrationClientAuthentication, registrationGrantType, validateIntegrationConfiguration } from "../shared/configuration.js";
5
6
  import { createConnectionCredentials } from "./connectionCredentials.js";
6
7
  import { ConnectorError, providerError } from "./errors.js";
@@ -59,9 +60,11 @@ function callbackMatches(connection, provider, registration) {
59
60
  * @param {"application" | "assistant"} [options.executionMode]
60
61
  * @param {typeof globalThis.fetch} [options.fetchImpl]
61
62
  * @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.
63
+ * @param {"development" | "test" | "staging" | "production"} options.appEnv The application's APP_ENV:
64
+ * `appEnvironment(env)`. Outside production, operations marked `sideEffect` are checked and logged, never sent,
65
+ * and answer `{ simulated: true }`.
66
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger | Console} [options.logger] Where operations logged
67
+ * instead of sent are written.
65
68
  */
66
69
  function createConnectionService({
67
70
  configuration,
@@ -72,10 +75,11 @@ function createConnectionService({
72
75
  executionMode = "application",
73
76
  fetchImpl = globalThis.fetch,
74
77
  now = Date.now,
75
- sideEffects = "simulate",
78
+ appEnv,
76
79
  logger = console
77
80
  }) {
78
81
  if (!["application", "assistant"].includes(executionMode)) throw new TypeError("Select application or assistant execution.");
82
+ if (!APP_ENVIRONMENTS.includes(appEnv)) throw new TypeError("Supply appEnv, the application's APP_ENV: appEnvironment(env).");
79
83
  const config = validateIntegrationConfiguration(configuration, { providers });
80
84
  // Each integration with its settings resolved, so the service reads them as one object.
81
85
  const integrations = Object.fromEntries(Object.entries(config.integrations)
@@ -95,7 +99,7 @@ function createConnectionService({
95
99
  );
96
100
  }
97
101
  const connectionCredentials = createConnectionCredentials({ config, resolveReference });
98
- const providerRequests = createProviderRequests({ fetchImpl, now, resolveReference, sideEffects, logger });
102
+ const providerRequests = createProviderRequests({ fetchImpl, now, resolveReference, appEnv, logger });
99
103
 
100
104
  async function access(context, integrationId, operation, input, checkAssistantPermission = true) {
101
105
  const integration = integrations[integrationId];
@@ -433,7 +437,7 @@ function createConnectionService({
433
437
  }
434
438
  const credentials = usesApiKey ? { ...connection, apiKey: await connectionCredentials.apiKeyFor(integration, provider) } : connection;
435
439
  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.
440
+ // An operation logged instead of sent never reached the provider, so it proves nothing about the credential.
437
441
  if (result === SIMULATED_RESULT) return { result };
438
442
  await save({ ...connection, verifiedAt: now(),
439
443
  ...(usesApiKey ? { credentialFingerprint: createHash("sha256").update(credentials.apiKey).digest("hex") } : {})
@@ -1,13 +1,13 @@
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
+ import { logSideEffect } from "@jskit-ai/kernel/server/runtime/appEnvironment";
4
4
  import { ConnectorError } from "./errors.js";
5
5
 
6
6
  const DEFAULT_SCOPE_SEPARATOR = " ";
7
7
  // Every OAuth token request takes this timeout; a provider's operations default to it.
8
8
  const REQUEST_TIMEOUT_MS = 15_000;
9
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.
10
+ // What a side-effect operation answers outside production, where it is logged in place of being sent.
11
11
  const SIMULATED_RESULT = Object.freeze({ simulated: true });
12
12
 
13
13
  /**
@@ -86,11 +86,12 @@ function operationRequest(operation, input, settings, providerData) {
86
86
  * @param {typeof globalThis.fetch} dependencies.fetchImpl
87
87
  * @param {() => number} dependencies.now
88
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 }`.
89
+ * @param {"development" | "test" | "staging" | "production"} dependencies.appEnv The application's APP_ENV. Outside
90
+ * production an operation marked `sideEffect` (one that sends a message, charges, books or posts) is checked and
91
+ * logged, never sent, and answers `{ simulated: true }`.
91
92
  * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger | Console} [dependencies.logger]
92
93
  */
93
- function createProviderRequests({ fetchImpl, now, resolveReference, sideEffects = "simulate", logger = console }) {
94
+ function createProviderRequests({ fetchImpl, now, resolveReference, appEnv, logger = console }) {
94
95
  const http = createHttpClient({ fetchImpl, csrf: { enabled: false }, credentials: "omit" });
95
96
 
96
97
  /**
@@ -135,9 +136,9 @@ function createProviderRequests({ fetchImpl, now, resolveReference, sideEffects
135
136
  if (url.protocol !== "https:" || url.username || url.password || !origins.includes(url.origin)) {
136
137
  throw new ConnectorError("connector_destination_invalid", "The provider operation has an invalid destination.", { messageCode: "connectors.connection.providerOperationInvalidDestination" });
137
138
  }
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, {
139
+ // Outside production a side effect is checked like a real one, then logged in place of being sent.
140
+ if (operation.sideEffect === true && appEnv !== "production") {
141
+ logSideEffect(logger, appEnv, {
141
142
  kind: "connector operation",
142
143
  summary: `the ${provider.id} ${operationId} request`,
143
144
  details: { provider: provider.id, operation: operationId, input }
@@ -94,7 +94,7 @@
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
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
97
+ * posts. Outside production (APP_ENV), it is checked and logged, never sent, and answers
98
98
  * `{ simulated: true }`.
99
99
  */
100
100
 
@@ -56,18 +56,18 @@ test("credential-free grants require verification, authorize access and invalida
56
56
  resolveReference: async () => { resolutions++; return "secret"; },
57
57
  fetchImpl: async (url, init) => { requests.push({ url, init }); return Response.json({ meta: [], data: [{ ok: 1, user: "default" }], rows: 1 }); }
58
58
  };
59
- const service = createConnectionService(options);
59
+ const service = createConnectionService({ appEnv: "test", ...options });
60
60
  const input = { context: owner, integrationId: "database" };
61
61
  await assert.rejects(service.invoke({ ...input, operation: "connection.check" }), { code: "connector_reconnect_required" });
62
62
  await assert.rejects(service.connectApiKey(input), { code: "connector_mode_unavailable" });
63
63
  await service.connectWithoutCredentials(input);
64
64
  assert.equal(resolutions, 0);
65
65
  assert.equal(new Headers(requests[0].init.headers).has("authorization"), false);
66
- const restart = createConnectionService(options);
66
+ const restart = createConnectionService({ appEnv: "test", ...options });
67
67
  assert.equal((await restart.status(input)).status, "connected");
68
68
  await restart.invoke({ ...input, operation: "connection.check" });
69
69
  await assert.rejects(restart.invoke({ ...input, context: { ...owner, subjectId: "other" }, operation: "connection.check" }), { code: "connector_reconnect_required" });
70
- const keyed = createConnectionService({ ...options, configuration: databaseConfiguration({ method: "api-key", secretRef: "env:PASSWORD" }) });
70
+ const keyed = createConnectionService({ appEnv: "test", ...options, configuration: databaseConfiguration({ method: "api-key", secretRef: "env:PASSWORD" }) });
71
71
  assert.equal((await keyed.status(input)).status, "reconnect-required");
72
72
  await assert.rejects(keyed.invoke({ ...input, operation: "connection.check" }), { code: "connector_reconnect_required" });
73
73
  await assert.rejects(keyed.connectWithoutCredentials(input), { code: "connector_mode_unavailable" });
@@ -90,6 +90,7 @@ test("result validation sees the request its operation built and rejects a misma
90
90
  const provider = { ...clickhouseProvider, operations: { ...clickhouseProvider.operations, "connection.check": { ...check,
91
91
  validateResult: (value, request) => { seen.push(request); return check.validateResult(value) && value.data[0].user === expectedUser; } } } };
92
92
  const service = createConnectionService({
93
+ appEnv: "test",
93
94
  configuration: databaseConfiguration({ method: "none" }), providers: [provider], store: memoryStore(),
94
95
  authorize: async (context) => context, resolveReference: async () => "secret",
95
96
  fetchImpl: async () => Response.json({ meta: [], data: [{ ok: 1, user: "default" }], rows: 1 })
@@ -109,11 +110,11 @@ test("connections without a store fail at startup, naming the feature to registe
109
110
  authorize: async (context) => context, resolveReference: async () => ""
110
111
  };
111
112
  // The kernel's startup error names the missing capability and adds the feature's hint.
112
- assert.throws(() => createCapabilityRuntime({ inputs: { "runtime.env": {}, "runtime.logger": silentLogger }, providers: [EventProvider, ActionProvider, createConnectorsFeature(options)] }), {
113
+ assert.throws(() => createCapabilityRuntime({ inputs: { "runtime.env": { APP_ENV: "test" }, "runtime.logger": silentLogger }, providers: [EventProvider, ActionProvider, createConnectorsFeature(options)] }), {
113
114
  message: 'Provider "connectors.core" requires missing capability "connectors.store". Register createConnectionStoreFeature({ protection }) ' +
114
115
  "from @jskit-ai/connectors-core/server/storage in your server providers, or pass createConnectorsFeature({ store })."
115
116
  });
116
- assert.throws(() => createConnectionService({ ...options, store: {} }), {
117
+ assert.throws(() => createConnectionService({ appEnv: "test", ...options, store: {} }), {
117
118
  name: "TypeError",
118
119
  message: /^Connections require a connection store with withConnection\(\): register createConnectionStoreFeature\(\{ protection \}\) from @jskit-ai\/connectors-core\/server\/storage/u
119
120
  });
@@ -131,7 +132,7 @@ test("the ordinary credential-free Feature action verifies without resolving ref
131
132
  return Response.json({ meta: [], data: [{ ok: 1, user: "default" }], rows: 1 });
132
133
  }
133
134
  };
134
- const runtime = createCapabilityRuntime({ inputs: { "runtime.env": {}, "runtime.logger": silentLogger }, providers: [
135
+ const runtime = createCapabilityRuntime({ inputs: { "runtime.env": { APP_ENV: "test" }, "runtime.logger": silentLogger }, providers: [
135
136
  EventProvider, ActionProvider, createConnectorsFeature(options),
136
137
  defineProvider({ id: "test.credential-free-observer", requires: { catalogue: "runtime.actions" }, setup({ catalogue }) { actions = catalogue; } })
137
138
  ] });
@@ -230,7 +231,7 @@ function setup({ config = configuration(), tokenScopes = `${listScope} ${eventsS
230
231
  }, { status: providerStatus });
231
232
  }
232
233
  };
233
- const service = createConnectionService(options);
234
+ const service = createConnectionService({ appEnv: "test", ...options });
234
235
  async function connect(context = owner) {
235
236
  const start = await service.beginAuthorization({ context, integrationId: "calendar" });
236
237
  const state = new URL(start.authorizationUrl).searchParams.get("state");
@@ -256,7 +257,7 @@ function serviceAccountSetup() {
256
257
  assert.equal(reference, "env:GOOGLE_SECRET", "Service accounts must not resolve a callback binding.");
257
258
  return "never-return-this-secret";
258
259
  } };
259
- return { ...fixture, options, provider, config, service: createConnectionService(options) };
260
+ return { ...fixture, options, provider, config, service: createConnectionService({ appEnv: "test", ...options }) };
260
261
  }
261
262
 
262
263
  test("client credentials are explicit, confidential, callback-free and cannot impersonate each app user", () => {
@@ -306,7 +307,7 @@ test("service account verification issues a confidential grant without browser s
306
307
  test("service account renewal is serialized, requests only its verified grant and survives a failed API read", async () => {
307
308
  const { options, requests, advance, store, provider } = serviceAccountSetup();
308
309
  const optionsWithVerification = { ...options, providers: [{ ...provider, grantedScopesFromVerification: () => [listScope] }] };
309
- const service = createConnectionService(optionsWithVerification);
310
+ const service = createConnectionService({ appEnv: "test", ...optionsWithVerification });
310
311
  const input = { context: owner, integrationId: "calendar" };
311
312
  await service.connectClientCredentials(input);
312
313
  advance(3_600_000);
@@ -317,7 +318,7 @@ test("service account renewal is serialized, requests only its verified grant an
317
318
  assert.deepEqual((await service.status(input)).grantedScopes, [listScope]);
318
319
  await assert.rejects(service.invoke({ ...input, operation: "events.list", input: { calendarId: "primary" } }), { code: "connector_scope_missing" });
319
320
  advance(3_600_000);
320
- const failing = createConnectionService({ ...optionsWithVerification, fetchImpl: async (url, init) =>
321
+ const failing = createConnectionService({ appEnv: "test", ...optionsWithVerification, fetchImpl: async (url, init) =>
321
322
  String(url).endsWith("/token") ? options.fetchImpl(url, init) : Response.json({ message: "secret" }, { status: 403 }) });
322
323
  await assert.rejects(failing.invoke({ ...input, operation: "calendars.list" }), { code: "connector_permission_denied" });
323
324
  assert.equal([...store.connections.values()][0].tokens.expiresAt, options.now() + 3_600_000);
@@ -332,13 +333,13 @@ test("changing service account scopes or OAuth flow requires an explicit reconne
332
333
  await service.connectClientCredentials(input);
333
334
  const scoped = structuredClone(config);
334
335
  scoped.integrations.calendar.scopes = [listScope];
335
- const reduced = createConnectionService({ ...options, configuration: scoped });
336
+ const reduced = createConnectionService({ appEnv: "test", ...options, configuration: scoped });
336
337
  assert.equal((await reduced.status(input)).status, "reconnect-required");
337
338
  await assert.rejects(reduced.invoke({ ...input, operation: "calendars.list" }), { code: "connector_reconnect_required" });
338
339
  const code = structuredClone(config);
339
340
  code.registrations.google.grantType = "authorization_code";
340
341
  code.registrations.google.callbackUrlRef = "env:CALLBACK";
341
- const browser = createConnectionService({ ...options, configuration: code,
342
+ const browser = createConnectionService({ appEnv: "test", ...options, configuration: code,
342
343
  resolveReference: async (ref) => ref === "env:CALLBACK" ? callback : "never-return-this-secret" });
343
344
  assert.equal((await browser.status(input)).status, "reconnect-required");
344
345
  await assert.rejects(browser.invoke({ ...input, operation: "calendars.list" }), { code: "connector_reconnect_required" });
@@ -357,7 +358,7 @@ test("revoked service account credentials invalidate the grant without exposing
357
358
  await service.connectClientCredentials(input);
358
359
  advance(3_600_000);
359
360
  let requests = 0;
360
- const broken = createConnectionService({ ...options, fetchImpl: async () => {
361
+ const broken = createConnectionService({ appEnv: "test", ...options, fetchImpl: async () => {
361
362
  requests++;
362
363
  return Response.json({ error: "invalid_client", error_description: "private-secret" }, { status: 400 });
363
364
  } });
@@ -376,15 +377,15 @@ test("unverified and malformed service grants never replace an existing connecti
376
377
  await service.connectClientCredentials(input);
377
378
  const saved = structuredClone([...store.connections.values()][0]);
378
379
  for (const response of [{ token_type: "Bearer", expires_in: 3600 }, { token_type: "mac", access_token: "private-token" }]) {
379
- const malformed = createConnectionService({ ...options, fetchImpl: async () => Response.json(response) });
380
+ const malformed = createConnectionService({ appEnv: "test", ...options, fetchImpl: async () => Response.json(response) });
380
381
  await assert.rejects(malformed.connectClientCredentials(input), { code: "connector_provider_failed" });
381
382
  assert.deepEqual([...store.connections.values()][0], saved);
382
383
  }
383
- const denied = createConnectionService({ ...options, fetchImpl: async (url, init) => String(url).endsWith("/token")
384
+ const denied = createConnectionService({ appEnv: "test", ...options, fetchImpl: async (url, init) => String(url).endsWith("/token")
384
385
  ? options.fetchImpl(url, init) : Response.json({ error: "private" }, { status: 403 }) });
385
386
  await assert.rejects(denied.connectClientCredentials(input), { code: "connector_permission_denied" });
386
387
  assert.deepEqual([...store.connections.values()][0], saved);
387
- const noAccess = createConnectionService({ ...options, authorize: async () => null, fetchImpl: async () => assert.fail("Denied owner reached provider") });
388
+ const noAccess = createConnectionService({ appEnv: "test", ...options, authorize: async () => null, fetchImpl: async () => assert.fail("Denied owner reached provider") });
388
389
  await assert.rejects(noAccess.connectClientCredentials(input), { code: "connector_access_denied" });
389
390
  });
390
391
 
@@ -396,7 +397,7 @@ test("cancelling a service token exchange preserves the previous grant without r
396
397
  let started;
397
398
  const requested = new Promise((resolve) => { started = resolve; });
398
399
  let calls = 0;
399
- const waiting = createConnectionService({ ...options, fetchImpl: async (_url, init) => {
400
+ const waiting = createConnectionService({ appEnv: "test", ...options, fetchImpl: async (_url, init) => {
400
401
  calls++;
401
402
  return new Promise((_resolve, reject) => {
402
403
  init.signal.addEventListener("abort", () => reject(init.signal.reason), { once: true });
@@ -415,7 +416,7 @@ test("cancelling a service token exchange preserves the previous grant without r
415
416
  test("the client credentials Feature action uses the ordinary application policy and runtime", async () => {
416
417
  const { options } = serviceAccountSetup();
417
418
  let actions;
418
- const runtime = createCapabilityRuntime({ inputs: { "runtime.env": {}, "runtime.logger": silentLogger }, providers: [EventProvider, ActionProvider, createConnectorsFeature(options),
419
+ const runtime = createCapabilityRuntime({ inputs: { "runtime.env": { APP_ENV: "test" }, "runtime.logger": silentLogger }, providers: [EventProvider, ActionProvider, createConnectorsFeature(options),
419
420
  defineProvider({ id: "test.service-observer", requires: { catalogue: "runtime.actions" }, setup({ catalogue }) { actions = catalogue; } })] });
420
421
  await runtime.start();
421
422
  try {
@@ -432,6 +433,7 @@ test("cancelling an HTTP operation preserves its grant and reports interruption
432
433
  const requested = new Promise((resolve) => { started = resolve; });
433
434
  let requests = 0;
434
435
  const service = createConnectionService({
436
+ appEnv: "test",
435
437
  ...options,
436
438
  fetchImpl: async (url, init) => {
437
439
  requests += 1;
@@ -455,7 +457,7 @@ test("provider verification can reduce comma-separated grants without refresh re
455
457
  const { options, advance } = setup({ tokenScopes: `${listScope}, ${eventsScope}` });
456
458
  let verified = [listScope];
457
459
  const provider = { ...googleCalendarProvider, scopeSeparator: ",", grantedScopesFromVerification: () => verified };
458
- const service = createConnectionService({ ...options, providers: [provider] });
460
+ const service = createConnectionService({ appEnv: "test", ...options, providers: [provider] });
459
461
  async function connect() {
460
462
  const start = await service.beginAuthorization({ context: owner, integrationId: "calendar" });
461
463
  const url = new URL(start.authorizationUrl);
@@ -612,7 +614,7 @@ test("OAuth attempts and verified grants stay bound to their provider settings",
612
614
  const state = new URL(start.authorizationUrl).searchParams.get("state");
613
615
  const config = configuration();
614
616
  config.integrations.calendar.settings = { resource: "another-account" };
615
- const changed = createConnectionService({ ...options, configuration: config });
617
+ const changed = createConnectionService({ appEnv: "test", ...options, configuration: config });
616
618
  await assert.rejects(changed.completeAuthorization({ context: owner, integrationId: "calendar", callbackUrl: `${callback}?code=x&state=${state}` }), { code: "connector_attempt_invalid" });
617
619
  assert.equal(requests.length, 0);
618
620
  await connect();
@@ -657,11 +659,11 @@ test("initial OAuth grants cannot activate permissions omitted from configuratio
657
659
  test("a provider's confidential non-PKCE exception is explicit and bound to the pending attempt", async () => {
658
660
  for (const initialPkce of [true, false]) {
659
661
  const { options, requests } = setup();
660
- const service = createConnectionService({ ...options, providers: [{ ...googleCalendarProvider, oauthPkce: initialPkce }] });
662
+ const service = createConnectionService({ appEnv: "test", ...options, providers: [{ ...googleCalendarProvider, oauthPkce: initialPkce }] });
661
663
  const start = await service.beginAuthorization({ context: owner, integrationId: "calendar" });
662
664
  const url = new URL(start.authorizationUrl);
663
665
  assert.equal(url.searchParams.has("code_challenge"), initialPkce);
664
- const changed = createConnectionService({ ...options, providers: [{ ...googleCalendarProvider, oauthPkce: !initialPkce }] });
666
+ const changed = createConnectionService({ appEnv: "test", ...options, providers: [{ ...googleCalendarProvider, oauthPkce: !initialPkce }] });
665
667
  await assert.rejects(changed.completeAuthorization({ context: owner, integrationId: "calendar", callbackUrl: `${callback}?code=code&state=${url.searchParams.get("state")}` }), { code: "connector_attempt_invalid" });
666
668
  assert.equal(requests.length, 0);
667
669
  }
@@ -671,7 +673,7 @@ test("a provider cannot disable PKCE for a public client", async () => {
671
673
  const { options } = setup(); const config = configuration();
672
674
  config.registrations.google.tokenEndpointAuthMethod = "none";
673
675
  delete config.registrations.google.clientSecretRef;
674
- const service = createConnectionService({ ...options, configuration: config,
676
+ const service = createConnectionService({ appEnv: "test", ...options, configuration: config,
675
677
  providers: [{ ...googleCalendarProvider, oauthPkce: false, oauthClientAuthenticationMethods: ["none"] }] });
676
678
  await assert.rejects(service.beginAuthorization({ context: owner, integrationId: "calendar" }), { code: "connector_mode_unavailable" });
677
679
  });
@@ -734,7 +736,7 @@ test("refresh cannot restore declined scopes or grant unrequested permissions wi
734
736
  const { options, connect, advance, store } = setup({ tokenScopes: listScope });
735
737
  await connect();
736
738
  advance(3_600_001);
737
- const service = createConnectionService({ ...options, fetchImpl: async (url, init) => {
739
+ const service = createConnectionService({ appEnv: "test", ...options, fetchImpl: async (url, init) => {
738
740
  if (String(url) === "https://oauth2.googleapis.com/token") return Response.json({
739
741
  token_type: "Bearer", access_token: "refreshed", refresh_token: "rotated",
740
742
  expires_in: 3600, scope: `${listScope} ${eventsScope} unexpected-admin`
@@ -761,7 +763,7 @@ test("an API failure after refresh commits rotated credentials before reporting
761
763
  const { options, connect, advance, store } = setup();
762
764
  await connect();
763
765
  advance(3_600_001);
764
- const service = createConnectionService({ ...options, fetchImpl: async (url, init) => {
766
+ const service = createConnectionService({ appEnv: "test", ...options, fetchImpl: async (url, init) => {
765
767
  if (String(url).endsWith("/token")) return options.fetchImpl(url, init);
766
768
  return Response.json({ error: "temporarily unavailable" }, { status: 503 });
767
769
  } });
@@ -773,7 +775,7 @@ test("an invalid refresh grant commits reconnect state rather than rolling it ba
773
775
  const { options, connect, advance } = setup();
774
776
  await connect();
775
777
  advance(3_600_001);
776
- const service = createConnectionService({ ...options, fetchImpl: async () => Response.json({ error: "invalid_grant" }, { status: 400 }) });
778
+ const service = createConnectionService({ appEnv: "test", ...options, fetchImpl: async () => Response.json({ error: "invalid_grant" }, { status: 400 }) });
777
779
  await assert.rejects(service.invoke({ context: owner, integrationId: "calendar", operation: "events.list" }), { code: "connector_reconnect_required" });
778
780
  assert.equal((await service.status({ context: owner, integrationId: "calendar" })).status, "reconnect-required");
779
781
  });
@@ -830,7 +832,7 @@ test("saved grants cannot override permissions removed from application source",
830
832
  await connect();
831
833
  const config = configuration();
832
834
  config.integrations.calendar.scopes = [listScope];
833
- const service = createConnectionService({ ...options, configuration: config });
835
+ const service = createConnectionService({ appEnv: "test", ...options, configuration: config });
834
836
  await assert.rejects(service.invoke({ context: owner, integrationId: "calendar", operation: "events.list" }), { code: "connector_scope_missing" });
835
837
  });
836
838
 
@@ -839,13 +841,13 @@ test("a changed client registration is immediately reported as needing reconnect
839
841
  await connect();
840
842
  const config = configuration();
841
843
  config.registrations.google.clientId = "another-client";
842
- const service = createConnectionService({ ...options, configuration: config });
844
+ const service = createConnectionService({ appEnv: "test", ...options, configuration: config });
843
845
  assert.equal((await service.status({ context: owner, integrationId: "calendar" })).status, "reconnect-required");
844
846
  });
845
847
 
846
848
  test("remote field errors cannot smuggle provider response text into application errors", async () => {
847
849
  const { options } = setup();
848
- const service = createConnectionService({ ...options, fetchImpl: async (url, init) => {
850
+ const service = createConnectionService({ appEnv: "test", ...options, fetchImpl: async (url, init) => {
849
851
  if (String(url).endsWith("/token")) return options.fetchImpl(url, init);
850
852
  return Response.json({ error: "failure", fieldErrors: { token: "never-return-this-secret" } }, { status: 422 });
851
853
  } });
@@ -860,7 +862,7 @@ test("remote field errors cannot smuggle provider response text into application
860
862
 
861
863
  test("a successful HTTP status with an unexpected payload does not verify a connection", async () => {
862
864
  const { options } = setup();
863
- const service = createConnectionService({ ...options, fetchImpl: async (url, init) => {
865
+ const service = createConnectionService({ appEnv: "test", ...options, fetchImpl: async (url, init) => {
864
866
  if (String(url).endsWith("/token")) return options.fetchImpl(url, init);
865
867
  return Response.json({ message: "not a Calendar response" });
866
868
  } });
@@ -886,7 +888,7 @@ test("configuration rejects gateway registrations before constructing a runtime"
886
888
  test("the Feature exposes ordinary JSKIT actions with application authorization", async () => {
887
889
  const { options } = setup();
888
890
  let actions;
889
- const runtime = createCapabilityRuntime({ inputs: { "runtime.env": {}, "runtime.logger": silentLogger }, providers: [
891
+ const runtime = createCapabilityRuntime({ inputs: { "runtime.env": { APP_ENV: "test" }, "runtime.logger": silentLogger }, providers: [
890
892
  EventProvider, ActionProvider, createConnectorsFeature(options),
891
893
  defineProvider({
892
894
  id: "test.observer", requires: { catalogue: "runtime.actions" },
@@ -936,6 +938,7 @@ test("query credentials are encoded, replace URL values and never escape through
936
938
  };
937
939
  const store = memoryStore();
938
940
  const service = createConnectionService({
941
+ appEnv: "test",
939
942
  configuration: { schemaVersion: 1, registrations: {}, integrations: {
940
943
  source: { provider: provider.id, accountMode: "shared", scopes: [], authentication: { method: "api-key", secretRef: "env:QUERY_KEY" } }
941
944
  } },
@@ -987,6 +990,7 @@ test("path credentials preserve the validated origin and query without leaking t
987
990
  };
988
991
  const store = memoryStore();
989
992
  const service = createConnectionService({
993
+ appEnv: "test",
990
994
  configuration: { schemaVersion: 1, registrations: {}, integrations: {
991
995
  source: { provider: provider.id, accountMode: "shared", scopes: [], authentication: { method: "api-key", secretRef: "env:PATH_KEY" } }
992
996
  } },
@@ -1055,7 +1059,7 @@ test("JSON-body credentials replace supplied values, preserve input and reach th
1055
1059
  }
1056
1060
  };
1057
1061
  let actions;
1058
- const runtime = createCapabilityRuntime({ inputs: { "runtime.env": {}, "runtime.logger": silentLogger }, providers: [
1062
+ const runtime = createCapabilityRuntime({ inputs: { "runtime.env": { APP_ENV: "test" }, "runtime.logger": silentLogger }, providers: [
1059
1063
  EventProvider, ActionProvider, createConnectorsFeature(options),
1060
1064
  defineProvider({ id: "test.body-observer", requires: { catalogue: "runtime.actions" }, setup({ catalogue }) { actions = catalogue; } })
1061
1065
  ] });
@@ -1071,7 +1075,7 @@ test("JSON-body credentials replace supplied values, preserve input and reach th
1071
1075
  assert.equal(new URL(requests[0].url).search, "");
1072
1076
  assert.equal(JSON.stringify([...store.connections]).includes(secret), false);
1073
1077
  assert.equal(JSON.stringify([...store.connections]).includes("verification-user"), false);
1074
- const service = createConnectionService(options);
1078
+ const service = createConnectionService({ appEnv: "test", ...options });
1075
1079
  const input = { context: owner, integrationId: "source", operation: "check" };
1076
1080
  for (const invalidBody of [undefined, null, [], "plain text"]) {
1077
1081
  body = invalidBody;
@@ -1115,7 +1119,7 @@ for (const [provider, response] of [
1115
1119
  return Response.json(state.response, { status: state.status });
1116
1120
  }
1117
1121
  };
1118
- return { config, options, store, requests, state, service: createConnectionService(options) };
1122
+ return { config, options, store, requests, state, service: createConnectionService({ appEnv: "test", ...options }) };
1119
1123
  }
1120
1124
 
1121
1125
  test(`${provider.id}: API key verification, rotation, isolation and disconnect`, async () => {
@@ -1152,7 +1156,7 @@ for (const [provider, response] of [
1152
1156
  await service.connectApiKey(input);
1153
1157
  const original = state.key;
1154
1158
  state.key = "unverified-replacement";
1155
- const reopened = createConnectionService(options);
1159
+ const reopened = createConnectionService({ appEnv: "test", ...options });
1156
1160
  assert.equal((await reopened.status(input)).status, "reconnect-required");
1157
1161
  assert.equal(requests.length, 1);
1158
1162
  state.status = 403;
@@ -1194,7 +1198,7 @@ for (const [provider, response] of [
1194
1198
  const input = { context: owner, integrationId: "service" };
1195
1199
  await service.connectApiKey(input);
1196
1200
  config.integrations.service.authentication.secretRef = "env:DIFFERENT_KEY";
1197
- const changed = createConnectionService(options);
1201
+ const changed = createConnectionService({ appEnv: "test", ...options });
1198
1202
  assert.equal((await changed.status(input)).status, "reconnect-required");
1199
1203
  await assert.rejects(changed.invoke({ ...input, operation: provider.checkOperation }), { code: "connector_reconnect_required" });
1200
1204
  state.status = 401;
@@ -1251,7 +1255,7 @@ test("changing client authentication invalidates OAuth attempts and stored grant
1251
1255
  config.registrations.google.tokenEndpointAuthMethod = "none";
1252
1256
  delete config.registrations.google.clientSecretRef;
1253
1257
  const provider = { ...googleCalendarProvider, oauthClientAuthenticationMethods: ["client_secret_post", "none"] };
1254
- const changed = createConnectionService({ ...options, configuration: config, providers: [provider] });
1258
+ const changed = createConnectionService({ appEnv: "test", ...options, configuration: config, providers: [provider] });
1255
1259
  const count = requests.length;
1256
1260
  assert.equal((await changed.status(input)).status, "reconnect-required");
1257
1261
  await assert.rejects(changed.invoke({ ...input, operation: googleCalendarProvider.checkOperation }), { code: "connector_reconnect_required" });
@@ -1275,6 +1279,7 @@ test("OAuth placeholders from custom resolvers never create consent attempts", a
1275
1279
  let attempts = 0;
1276
1280
  store.saveAttempt = async () => { attempts++; };
1277
1281
  const service = createConnectionService({
1282
+ appEnv: "test",
1278
1283
  configuration: configuration(), providers: [googleCalendarProvider], store,
1279
1284
  authorize: async () => owner,
1280
1285
  resolveReference: async (reference) => reference === "env:CALLBACK" ? callback : value,
@@ -1285,7 +1290,7 @@ test("OAuth placeholders from custom resolvers never create consent attempts", a
1285
1290
  }
1286
1291
  const config = configuration();
1287
1292
  config.registrations.google.clientId = "MISSING";
1288
- const service = createConnectionService({ configuration: config, providers: [googleCalendarProvider], store: memoryStore(),
1293
+ const service = createConnectionService({ appEnv: "test", configuration: config, providers: [googleCalendarProvider], store: memoryStore(),
1289
1294
  authorize: async () => owner, resolveReference: async () => { assert.fail("No binding resolution is needed."); } });
1290
1295
  await assert.rejects(service.beginAuthorization({ context: owner, integrationId: "calendar" }), { code: "connector_binding_missing" });
1291
1296
  });
@@ -1294,7 +1299,7 @@ test("API-key placeholders from custom resolvers never reach the provider", asyn
1294
1299
  const config = { schemaVersion: 1, registrations: {}, integrations: { mail: {
1295
1300
  provider: "resend", accountMode: "shared", scopes: [], authentication: { method: "api-key", secretRef: "env:KEY" }
1296
1301
  } } };
1297
- const service = createConnectionService({ configuration: config, providers: [resendProvider], store: memoryStore(),
1302
+ const service = createConnectionService({ appEnv: "test", configuration: config, providers: [resendProvider], store: memoryStore(),
1298
1303
  authorize: async () => owner, resolveReference: async () => "MISSING",
1299
1304
  fetchImpl: async () => { assert.fail("No placeholder may be sent to the provider."); } });
1300
1305
  await assert.rejects(service.connectApiKey({ context: owner, integrationId: "mail" }), { code: "connector_binding_missing" });
@@ -1306,7 +1311,7 @@ test("missing OAuth credentials keep an existing grant visible and removable wit
1306
1311
  const fixture = setup();
1307
1312
  await fixture.connect();
1308
1313
  const count = fixture.requests.length;
1309
- const service = createConnectionService({ ...fixture.options,
1314
+ const service = createConnectionService({ appEnv: "test", ...fixture.options,
1310
1315
  resolveReference: async (reference) => reference === "env:CALLBACK" ? callback : "MISSING" });
1311
1316
  const input = { context: owner, integrationId: "calendar" };
1312
1317
  assert.equal((await service.status(input)).status, "reconnect-required");
@@ -1321,6 +1326,7 @@ test("missing API key preserves a verified connection until explicit disconnect"
1321
1326
  let key = "fixture-key";
1322
1327
  let requests = 0;
1323
1328
  const service = createConnectionService({
1329
+ appEnv: "test",
1324
1330
  configuration: { schemaVersion: 1, registrations: {}, integrations: { mail: {
1325
1331
  provider: "resend", accountMode: "shared", scopes: [], authentication: { method: "api-key", secretRef: "env:KEY" }
1326
1332
  } } }, providers: [resendProvider], store: memoryStore(), authorize: async () => owner,
@@ -1340,7 +1346,7 @@ test("missing API key preserves a verified connection until explicit disconnect"
1340
1346
  assert.equal(requests, 1);
1341
1347
  });
1342
1348
 
1343
- test("a test copy checks and logs a side-effect operation without sending it, and a live application sends it", async () => {
1349
+ test("outside production a side-effect operation is checked and logged, never sent, and production sends it", async () => {
1344
1350
  const config = { schemaVersion: 1, registrations: {}, integrations: { mail: {
1345
1351
  provider: "resend", accountMode: "shared", scopes: [], authentication: { method: "api-key", secretRef: "env:KEY" }
1346
1352
  } } };
@@ -1357,27 +1363,44 @@ test("a test copy checks and logs a side-effect operation without sending it, an
1357
1363
  }
1358
1364
  };
1359
1365
  const input = { context: owner, integrationId: "mail" };
1360
- const simulated = createConnectionService(options);
1361
- await simulated.connectApiKey(input);
1366
+ await createConnectionService({ ...options, appEnv: "test" }).connectApiKey(input);
1362
1367
  assert.equal(sent.length, 1, "verification is a read and runs for real");
1363
1368
  assert.match(sent[0], /^https:\/\/api\.resend\.com\/domains/u);
1364
1369
  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" });
1370
+ for (const [appEnv, text] of [
1371
+ ["development", "Development: the resend emails.send request was logged, not sent."],
1372
+ ["test", "Test: the resend emails.send request was logged, not sent."],
1373
+ ["staging", "Staging: the resend emails.send request was logged, not sent: only production acts for real."]
1374
+ ]) {
1375
+ logged.length = 0;
1376
+ const service = createConnectionService({ ...options, appEnv });
1377
+ assert.deepEqual(await service.invoke({ ...input, operation: "emails.send", input: message }), { simulated: true }, appEnv);
1378
+ assert.equal(sent.length, 1, `${appEnv} sent nothing`);
1379
+ assert.equal(store.connections.values().next().value.verifiedAt, verifiedAt, "a logged operation proves nothing about the key");
1380
+ assert.deepEqual(logged, [{
1381
+ details: { appEnv, kind: "connector operation", provider: "resend", operation: "emails.send", input: message },
1382
+ text
1383
+ }]);
1384
+ // A logged operation is checked like a real one.
1385
+ await assert.rejects(service.invoke({ ...input, operation: "emails.send", input: { ...message, to: [] } }), { code: "connector_input_invalid" });
1386
+ }
1387
+
1388
+ const production = createConnectionService({ ...options, appEnv: "production" });
1389
+ assert.deepEqual(await production.invoke({ ...input, operation: "emails.send", input: message }), { id: "email-1" });
1376
1390
  assert.deepEqual(sent.slice(1), ["https://api.resend.com/emails"]);
1391
+ for (const appEnv of [undefined, "live", "Production"]) {
1392
+ assert.throws(() => createConnectionService({ ...options, appEnv }), {
1393
+ name: "TypeError", message: "Supply appEnv, the application's APP_ENV: appEnvironment(env)."
1394
+ });
1395
+ }
1377
1396
  });
1378
1397
 
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]]) {
1398
+ test("the connectors feature follows the application's APP_ENV, which its options cannot override", async () => {
1399
+ for (const [env, expected] of [
1400
+ [{ APP_ENV: "development" }, 0],
1401
+ [{ APP_ENV: "staging", NODE_ENV: "production" }, 0],
1402
+ [{ APP_ENV: "production", NODE_ENV: "production" }, 1]
1403
+ ]) {
1381
1404
  let connections;
1382
1405
  const sent = [];
1383
1406
  const runtime = createCapabilityRuntime({ inputs: { "runtime.env": env, "runtime.logger": silentLogger }, providers: [
@@ -1387,7 +1410,7 @@ test("the connectors feature follows the application's SIDE_EFFECTS, which its o
1387
1410
  provider: "resend", accountMode: "shared", scopes: [], authentication: { method: "api-key", secretRef: "env:KEY" }
1388
1411
  } } },
1389
1412
  providers: [resendProvider], store: memoryStore(), authorize: async () => owner, resolveReference: async () => "fixture-key",
1390
- sideEffects: "live",
1413
+ appEnv: "production",
1391
1414
  fetchImpl: async (url) => {
1392
1415
  sent.push(String(url));
1393
1416
  return Response.json(String(url).endsWith("/emails") ? { id: "email-1" } : { object: "list", data: [], has_more: false });
@@ -83,6 +83,7 @@ test("a status read takes no lock and creates no connection row", async (t) => {
83
83
  knex.on("query", record);
84
84
  t.after(() => knex.off("query", record));
85
85
  const service = createConnectionService({
86
+ appEnv: "test",
86
87
  configuration: { schemaVersion: 1, registrations: {}, integrations: { database: {
87
88
  provider: "clickhouse", accountMode: "shared", scopes: [], authentication: { method: "none" },
88
89
  settings: { httpUrl: "https://database.example:8443/" }
@@ -140,6 +140,7 @@ test("pending OAuth resumes after reopening the app store without exposing priva
140
140
  registrations: { google: { source: "own", clientId: "fixture-client", clientSecretRef: "env:SECRET", callbackUrlRef: "env:CALLBACK" } }
141
141
  };
142
142
  const makeService = (config = configuration) => createConnectionService({
143
+ appEnv: "test",
143
144
  configuration: config, providers: [googleCalendarProvider],
144
145
  store: createFileConnectionStore({ directory, protection: protection(), now: () => clock }),
145
146
  authorize: async (context) => context,
@@ -56,6 +56,7 @@ function setup({ env = { GOOGLE_REFRESH_TOKEN: "seed-token-1" } } = {}) {
56
56
  const revoked = new Set();
57
57
  let time = 1_000_000;
58
58
  const service = createConnectionService({
59
+ appEnv: "test",
59
60
  configuration: configuration(),
60
61
  providers: [googleCalendarProvider],
61
62
  store,
@@ -48,7 +48,7 @@ async function fixture(t) {
48
48
  }
49
49
  }]
50
50
  };
51
- return { state, options, directory, service: createConnectionService(options) };
51
+ return { state, options, directory, service: createConnectionService({ appEnv: "test", ...options }) };
52
52
  }
53
53
 
54
54
  test("service-account configuration requires an indirect credential, declared mode, scopes and shared ownership", async (t) => {
@@ -80,7 +80,7 @@ test("service credentials obtain a verified grant once, persist encrypted tokens
80
80
  const grant = f.state.grants[0];
81
81
  assert.equal(grant.credential, f.state.credential); assert.equal(grant.fetchImpl, f.options.fetchImpl);
82
82
  assert.deepEqual(grant.settings, { projectId: "project-1" }); assert.deepEqual(grant.scopes, ["send"]); assert.equal(grant.now, f.state.now);
83
- const restarted = createConnectionService(f.options);
83
+ const restarted = createConnectionService({ appEnv: "test", ...f.options });
84
84
  assert.deepEqual(await restarted.status(input), connected);
85
85
  await restarted.invoke({ ...input, operation: "check", input: { check: "again" } });
86
86
  assert.equal(f.state.grants.length, 1);
@@ -99,7 +99,7 @@ test("service credentials obtain a verified grant once, persist encrypted tokens
99
99
  test("expiry renews once under the file lock across independent service instances", async (t) => {
100
100
  const f = await fixture(t); await f.service.connectServiceAccount(input);
101
101
  f.state.now += 3_571_000;
102
- const second = createConnectionService({ ...f.options, store: createFileConnectionStore({ directory: f.directory,
102
+ const second = createConnectionService({ appEnv: "test", ...f.options, store: createFileConnectionStore({ directory: f.directory,
103
103
  protection: createCredentialProtection({ keys: { current: new Uint8Array(32).fill(5) }, activeKeyId: "current" }) }) });
104
104
  await Promise.all([f.service, second, f.service].map((service) => service.invoke({ ...input, operation: "check" })));
105
105
  assert.equal(f.state.grants.length, 2);
@@ -124,7 +124,7 @@ test("ownership and changed reference, project or requested scopes cannot reuse
124
124
  }
125
125
  for (const change of [{ settings: { projectId: "project-2" } }, { scopes: ["send", "read"] }, { authentication: { method: "service-account", secretRef: "env:OTHER" } }]) {
126
126
  const configuration = structuredClone(f.options.configuration); Object.assign(configuration.integrations.notifications, change);
127
- const changed = createConnectionService({ ...f.options, configuration });
127
+ const changed = createConnectionService({ appEnv: "test", ...f.options, configuration });
128
128
  assert.equal((await changed.status(input)).status, "reconnect-required");
129
129
  await assert.rejects(changed.invoke({ ...input, operation: "check" }), { code: "connector_reconnect_required" });
130
130
  }
@@ -146,7 +146,7 @@ test("renewed tokens survive a subsequent provider failure and authorization fai
146
146
  f.state.status = 429;
147
147
  await assert.rejects(f.service.invoke({ ...input, operation: "check" }), { code: "connector_rate_limited" });
148
148
  f.state.status = 200;
149
- await createConnectionService(f.options).invoke({ ...input, operation: "check" }); assert.equal(f.state.grants.length, 2);
149
+ await createConnectionService({ appEnv: "test", ...f.options }).invoke({ ...input, operation: "check" }); assert.equal(f.state.grants.length, 2);
150
150
  f.state.credential = "rotated"; f.state.failGrant = true; const before = f.state.requests.length;
151
151
  await assert.rejects(f.service.invoke({ ...input, operation: "check" }), { code: "connector_reconnect_required" });
152
152
  assert.equal(f.state.requests.length, before); assert.equal((await f.service.status(input)).status, "reconnect-required");
@@ -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.env": {}, "runtime.logger": silentLogger }, providers: [EventProvider, ActionProvider, createConnectorsFeature(f.options),
187
+ const runtime = createCapabilityRuntime({ inputs: { "runtime.env": { APP_ENV: "test" }, "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 {
@@ -42,6 +42,7 @@ async function fixture(t) {
42
42
  const tokenGrants = [];
43
43
  let time = Date.now();
44
44
  const restart = (runtimeDirectory = directory) => createConnectionService({
45
+ appEnv: "test",
45
46
  configuration, providers: [googleCalendarProvider, resendProvider, gmailProvider],
46
47
  now: () => time,
47
48
  store: createFileConnectionStore({ directory: runtimeDirectory, protection: createCredentialProtection({
@@ -109,7 +110,7 @@ try {
109
110
  }
110
111
  const configuration = JSON.parse(await readFile("integrations.json", "utf8"));
111
112
  const context = { applicationId: process.env.APP_ID, subjectId: "setup-operator" };
112
- const connections = createConnectionService({ configuration, providers: [resendProvider],
113
+ const connections = createConnectionService({ appEnv: "test", configuration, providers: [resendProvider],
113
114
  resolveReference: createEnvironmentReferenceResolver(process.env),
114
115
  store: createFileConnectionStore({ directory: path.resolve("state"), protection: createCredentialProtection({
115
116
  activeKeyId: "fixture", keys: { fixture: Buffer.from(process.env.STORE_KEY, "hex") }
@@ -6,6 +6,7 @@ import test from "node:test";
6
6
  import { createInstalledRuntime } from "@jskit-ai/kernel/server/platform";
7
7
  import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
8
8
 
9
+ const TEST_ENV = Object.freeze({ APP_ENV: "test" });
9
10
  const TABLE_RUNTIME = ["@jskit-ai/database-runtime", "@jskit-ai/resource-runtime"];
10
11
  const readManifest = async (url) => JSON.parse(await readFile(url, "utf8"));
11
12
 
@@ -40,14 +41,14 @@ test("an app without a database installs @jskit-ai/connectors-core without the t
40
41
  assert.equal(manifest.peerDependenciesMeta?.[name]?.optional, true, `${name} is an optional peer`);
41
42
  }
42
43
 
43
- const started = await createInstalledRuntime({ appRoot: await installedApp(t, [manifest]), logger: silentLogger });
44
+ const started = await createInstalledRuntime({ appRoot: await installedApp(t, [manifest]), env: TEST_ENV, logger: silentLogger });
44
45
  assert.ok(started.packageOrder.includes(manifest.name));
45
46
  assert.equal(started.packageOrder.some((name) => TABLE_RUNTIME.includes(name)), false);
46
47
 
47
48
  // Installed as a dependency, the table runtime would need a database driver the app does not have.
48
49
  const databaseRuntime = await readManifest(new URL("../../database-runtime/package.json", import.meta.url));
49
50
  await assert.rejects(
50
- createInstalledRuntime({ appRoot: await installedApp(t, [manifest, databaseRuntime]), logger: silentLogger }),
51
+ createInstalledRuntime({ appRoot: await installedApp(t, [manifest, databaseRuntime]), env: TEST_ENV, logger: silentLogger }),
51
52
  /requires capability runtime\.database\.driver, but no installed package provides it/u
52
53
  );
53
54
  });