@cocreate/api 2.1.2 → 2.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,10 @@
1
+ ## [2.1.3](https://github.com/CoCreateJS/api/compare/v2.1.2...v2.1.3) (2026-11-17)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * align API dispatch with shared server routing ([c07b054](https://github.com/CoCreateJS/api/commit/c07b05490e009f0fa395fd06b4166a230ff4c2dc))
7
+
1
8
  ## [2.1.2](https://github.com/CoCreateJS/api/compare/v2.1.1...v2.1.2) (2026-11-07)
2
9
 
3
10
 
package/README.md CHANGED
@@ -33,7 +33,7 @@ For complete API references, integration guides, webhook configuration, and usag
33
33
  * **Abstract Syntax Tree (AST) Micro-Operators:** Evaluates functional configuration contexts inline, supporting expressive syntax tags (like `$data`, `$event`, `$actions`, and `$request`) along with custom business logic operators.
34
34
  * **Declarative Client Interface:** Configures complete request and response cycles using HTML5 attributes, assembling payloads from form fields and mapping results back into the document without provider-specific code.
35
35
  * **Tenant Environmental Isolation Firewall:** Guarantees cryptographic data partitioning by intercepting execution matrices and forcefully injecting bound `organization_id` and verified `host` values into core operations.
36
- * **Real-Time WebSocket Integration Matrix:** Seamlessly hooks into live server networks (`wsManager`), listening for incoming `api` and `endpoint` actions and streaming real-time operational state payloads directly back to the client.
36
+ * **Real-Time WebSocket Integration Matrix:** Seamlessly hooks into live server networks (`socket`), listening for incoming `api` and `endpoint` actions and streaming real-time operational state payloads directly back to the client.
37
37
  * **Dual Outbound Execution Vectors:** Wire-speeds native, pre-constructed HTTP payloads instantly, or dynamically builds custom multi-step outbound integrations by resolving runtime metadata against persistence layers.
38
38
  * **Cryptographic Signatures & JWT Orchestration:** Features native, low-latency hooks to generate JSON Web Tokens (`$jwt`) using HMAC-SHA256, alongside timing-attack-safe webhook signature verification (`verifySignature`).
39
39
  * **Sealed AST Runtime Sandbox:** Features a hardened utility matrix containing sandboxed global objects (`JSON`, `Array`, `Math`) and helper methods (like Base64 encoding/decoding and URL encoders), safely wrapping calculations outside the global scope.
@@ -290,7 +290,7 @@ const result = await apiGateway.executeApi(payload);
290
290
 
291
291
  ## How it Works
292
292
 
293
- 1. **Bootstrap & Event Binding:** During `init()`, the module hooks directly into the server's WebSocket framework (`wsManager`), capturing incoming `api` and `endpoint` event signals to route them to the execution handler.
293
+ 1. **Bootstrap & Event Binding:** During `init()`, the module hooks directly into the server's WebSocket framework (`socket`), capturing incoming `api` and `endpoint` event signals to route them to the execution handler.
294
294
  2. **Context and Firewall Initialization:** For every outbound execution, the engine evaluates the parameters against a parent context firewall. Security profiles match inbound connections against verified socket bounds, locking `organization_id` and `host` configurations.
295
295
  3. **Macro Configuration Resolving:** The engine sends queries through the CRUD synchronization layer to match configuration files against stored endpoints or active integration details inside the database collection.
296
296
  4. **AST Matrix Processing:** The router recursively scans headers, parameters, and bodies via `processOperators()`. Found strings matching active variables (such as `$` prefixes) are securely compiled in the isolated `NativeSandbox` environment.
@@ -323,7 +323,7 @@ The API engine creates an execution context for every request.
323
323
  | `actions` | `Array` | Results accumulated from previous workflow steps. |
324
324
  | `organization_id` | `String` | Tenant identifier. |
325
325
  | `host` | `String` | Verified tenant host used for isolation. |
326
- | `crud` / `wsManager` | `Object` | References to the CRUD layer and WebSocket manager. |
326
+ | `crud` / `socket` | `Object` | References to the CRUD layer and WebSocket manager. |
327
327
 
328
328
  ---
329
329
 
@@ -334,7 +334,7 @@ The API engine creates an execution context for every request.
334
334
 
335
335
  ### Context Sandboxing
336
336
 
337
- Internal services such as `crud` and `wsManager` intercept execution arguments and automatically enforce the authenticated tenant context. Even if a malicious configuration attempts to override tenant information, the runtime replaces it with the verified execution context.
337
+ Internal services such as `crud` and `socket` intercept execution arguments and automatically enforce the authenticated tenant context. Even if a malicious configuration attempts to override tenant information, the runtime replaces it with the verified execution context.
338
338
 
339
339
  ### Timing-Safe Signature Verification
340
340
 
@@ -362,6 +362,6 @@ This software is dual-licensed under the GNU Affero General Public License versi
362
362
  - **Commercial Use:** Commercial users must obtain a commercial license. Commercial licenses are available when signing up for an API key through the CoCreate platform.
363
363
  ## HTTP entrance
364
364
 
365
- The initialized API service exposes `http(req, res)` alongside `webhook(req, res)`. The module accepts POST JSON bodies up to 1 MiB, resolves organization scope from the hostname, and authorizes through `server.authorize.request` before execution. Bearer API keys and the envelope `apikey` field are supported; conflicting keys are rejected. Missing permission or authorization service returns 403. Caller scope and socket/user identity are excluded, and execution uses the sanitized envelope without the transport key.
365
+ Inbound API payloads use the central Cluster HTTP transport, which resolves organization scope and authorizes before calling `server.api.send`. The API service retains `webhook(req, res)` for its dedicated inbound webhook contract.
366
366
 
367
367
  `send()` remains the execution API used by trusted internal calls and socket dispatch, where socket authorization already occurs. The existing webhook AST owns provider signature verification.
package/docs/form.html CHANGED
@@ -106,14 +106,14 @@
106
106
  <pre><code class="language-javascript">
107
107
  var utils= require('../utils');
108
108
  class CoCreateStripe {
109
- constructor(wsManager) {
109
+ constructor(socket) {
110
110
  this.module_id="stripe";
111
111
  ....
112
112
  }
113
113
  init() {
114
- if (this.wsManager) {
114
+ if (this.socket) {
115
115
  //. endpoint = module_name (ex: stripe)
116
- this.wsManager.on(this.module_id, (socket, data) = this.sendStripe(socket, data));
116
+ this.socket.on(this.module_id, (socket, data) = this.sendStripe(socket, data));
117
117
  }
118
118
  }
119
119
  async sendStripe(socket, data) {
@@ -121,7 +121,7 @@
121
121
  switch (type) {
122
122
  case 'CreateCustomer': //. action name
123
123
  ... Get result by processing
124
- utils.send_response(this.wsManager, socket, {"type":type,"response":result}, this.module_id)
124
+ utils.send_response(this.socket, socket, {"type":type,"response":result}, this.module_id)
125
125
  break;
126
126
  ....
127
127
  }
@@ -144,7 +144,7 @@
144
144
  <h4>(2). Endpoint and moudle_id is same</h4>
145
145
  <h4>(3). Send response</h4>
146
146
  <pre><code class="language-javascript">
147
- utils.send_response(that.wsManager, socket, {"type":action_name,"response":result}, moudle_id)
147
+ utils.send_response(that.socket, socket, {"type":action_name,"response":result}, moudle_id)
148
148
  </code></pre>
149
149
  <h4>(4). Request data structure </h4>
150
150
  <pre><code class="language-javascript">{
package/docs/server.html CHANGED
@@ -104,14 +104,14 @@
104
104
  <pre><code class="language-javascript">
105
105
  var utils= require('../utils');
106
106
  class CoCreateStripe {
107
- constructor(wsManager) {
107
+ constructor(socket) {
108
108
  this.module_id="stripe";
109
109
  ....
110
110
  }
111
111
  init() {
112
- if (this.wsManager) {
112
+ if (this.socket) {
113
113
  //. endpoint = module_name (ex: stripe)
114
- this.wsManager.on(this.module_id, (socket, data) =&gt this.sendStripe(socket, data));
114
+ this.socket.on(this.module_id, (socket, data) =&gt this.sendStripe(socket, data));
115
115
  }
116
116
  }
117
117
  async sendStripe(socket, data) {
@@ -125,7 +125,7 @@
125
125
 
126
126
  CreateCustomer(socket, type, param1) {
127
127
  ... Get result by processing
128
- utils.send_response(this.wsManager, socket, {"type":type,"response":result}, this.module_id)
128
+ utils.send_response(this.socket, socket, {"type":type,"response":result}, this.module_id)
129
129
  }
130
130
  }//end Class
131
131
  module.exports = CoCreateStripe;
@@ -145,7 +145,7 @@
145
145
  <h4>(2). Endpoint and moudle_id is same</h4>
146
146
  <h4>(3). Send response</h4>
147
147
  <pre><code class="language-javascript">
148
- utils.send_response(that.wsManager, socket, {"type":action_name,"response":result}, moudle_id)
148
+ utils.send_response(that.socket, socket, {"type":action_name,"response":result}, moudle_id)
149
149
  </code></pre>
150
150
  <h4>(4). Request data structure </h4>
151
151
  <pre><code class="language-javascript">{
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cocreate/api",
3
- "version": "2.1.2",
3
+ "version": "2.1.3",
4
4
  "description": "A secure, multi-tenant API execution gateway and proxy layer that dynamically resolves endpoint actions, processes AST micro-operators, handles webhooks, and manages third-party integrations with strict tenant environment isolation.",
5
5
  "keywords": [
6
6
  "api-orchestration",
@@ -51,12 +51,14 @@
51
51
  }
52
52
  },
53
53
  "dependencies": {
54
+ "@cocreate/ast": "^1.0.0",
54
55
  "@cocreate/actions": "^2.0.1",
55
56
  "@cocreate/crud": "^0.0.0-stage",
56
57
  "@cocreate/element-prototype": "^2.0.1",
57
58
  "@cocreate/render": "^2.0.1",
58
59
  "@cocreate/utils": "^2.0.2",
59
- "@cocreate/socket": "^3.0.0"
60
+ "@cocreate/socket": "^3.0.0",
61
+ "@cocreate/kms": "^1.1.0"
60
62
  },
61
63
  "devDependencies": {
62
64
  "@cocreate/webpack": "^2.0.1"
package/src/server.js CHANGED
@@ -21,11 +21,11 @@
21
21
  */
22
22
 
23
23
  import { URL } from 'node:url';
24
+ import { astAsync } from '@cocreate/ast/server';
25
+ import { kms } from '@cocreate/kms/server';
24
26
  import {
25
27
  objectToSearchParams,
26
- searchParamsToObject,
27
- astAsync,
28
- security
28
+ searchParamsToObject
29
29
  } from '@cocreate/utils';
30
30
 
31
31
  let server = null;
@@ -38,7 +38,6 @@ function sendToServer(data) {
38
38
 
39
39
  const API = {
40
40
  send,
41
- http,
42
41
  webhook,
43
42
  getApiConfig
44
43
  };
@@ -63,7 +62,7 @@ export async function init(Server) {
63
62
  /**
64
63
  * Creates a Proxy firewall wrapper to automatically inject multi-tenant scope parameters (`organization_id` and `host`) into target method invocations.
65
64
  *
66
- * @param {Object} target - Target service instance to proxy (e.g., crud or wsManager).
65
+ * @param {Object} target - Target service instance to proxy.
67
66
  * @param {string} orgId - Multi-tenant organization identifier.
68
67
  * @param {string} host - Host domain identifier.
69
68
  * @returns {Proxy|undefined} Proxied target service with auto-injected tenant parameters, or undefined if target is falsy.
@@ -100,7 +99,7 @@ function createTenantProxy(target, orgId, host) {
100
99
  * @param {Object} [context.request] - Incoming HTTP request object.
101
100
  * @param {Object} [context.response] - Outgoing HTTP response object.
102
101
  * @param {Object} [context.crud] - Database service interface instance.
103
- * @param {Object} [context.wsManager] - WebSocket manager instance.
102
+ * @param {Object} [context.socket] - Socket service proxy.
104
103
  * @param {string} [context.key] - Provider key/credential string.
105
104
  * @param {Object} [context.config] - Full provider API configuration object.
106
105
  * @param {string} context.organization_id - Target multi-tenant organization ID.
@@ -112,7 +111,7 @@ function createTenantProxy(target, orgId, host) {
112
111
  function createSandbox(context) {
113
112
  const isPlatformOrg = server?.organization_id && (context.organization_id === server.organization_id);
114
113
  const secureCrud = createTenantProxy(context.crud, context.organization_id, context.host);
115
- const secureWs = createTenantProxy({ send: payload => server.send(payload) }, context.organization_id, context.host);
114
+ const secureSocket = createTenantProxy({ send: payload => server.send(payload) }, context.organization_id, context.host);
116
115
 
117
116
  const sandbox = {
118
117
  // Provider fields are configuration variables. For example, a
@@ -131,9 +130,8 @@ function createSandbox(context) {
131
130
  Buffer,
132
131
 
133
132
  crud: secureCrud,
134
- socket: secureWs,
135
- wsManager: secureWs,
136
- security,
133
+ socket: secureSocket,
134
+ kms,
137
135
 
138
136
  key: context.key,
139
137
  config: context.config,
@@ -163,8 +161,7 @@ function createSandbox(context) {
163
161
  $header: sandbox.header,
164
162
  $crud: sandbox.crud,
165
163
  $socket: sandbox.socket,
166
- $wsManager: sandbox.wsManager,
167
- $security: sandbox.security,
164
+ $kms: sandbox.kms,
168
165
  $config: sandbox.config,
169
166
  $api: sandbox.api
170
167
  });
@@ -199,7 +196,7 @@ function createSandbox(context) {
199
196
  */
200
197
  export async function send(data, parentContext = null) {
201
198
  try {
202
- const wsManager = server?.wsManager;
199
+ const socket = server?.socket;
203
200
  const orgId = parentContext?.organization_id || data.organization_id;
204
201
  const host = parentContext?.host || data.host;
205
202
 
@@ -252,7 +249,7 @@ export async function send(data, parentContext = null) {
252
249
  organization_id: orgId,
253
250
  host,
254
251
  crud: parentContext?.crud || crud,
255
- wsManager: parentContext?.wsManager || wsManager,
252
+ socket: parentContext?.socket || socket,
256
253
  key: apiConfig.key,
257
254
  config: apiConfig
258
255
  };
@@ -348,7 +345,6 @@ export async function send(data, parentContext = null) {
348
345
  sendToServer(data);
349
346
  return data;
350
347
  } catch (error) {
351
- const wsManager = server?.wsManager;
352
348
  if (!Array.isArray(data.error)) {
353
349
  data.error = data.error ? [data.error] : [];
354
350
  }
@@ -364,85 +360,6 @@ export async function send(data, parentContext = null) {
364
360
  }
365
361
  }
366
362
 
367
- /**
368
- * Handles inbound API HTTP requests, resolves host scope and authorizes before execution.
369
- * @param {object} req - Native HTTP request.
370
- * @param {object} res - Native HTTP response.
371
- * @param {object} [parsedInput] - Body already read by the manager HTTP entrance.
372
- * @param {Function} [execute] - Trusted dispatcher invoked only after request authorization.
373
- * @returns {Promise<object|undefined>} Successful execution result, otherwise undefined.
374
- * @public
375
- * @environment server
376
- */
377
- export async function http(req, res, parsedInput, execute = request => server.api.send(request)) {
378
- const reply = (status, body) => {
379
- res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
380
- res.end(JSON.stringify(body));
381
- };
382
- if (req.method !== 'POST') {
383
- res.setHeader('Allow', 'POST');
384
- return reply(405, { error: 'Use POST for this operation.' });
385
- }
386
- if (req.headers['content-type']?.split(';')[0].trim().toLowerCase() !== 'application/json') {
387
- return reply(415, { error: 'An application/json body is required.' });
388
- }
389
- let input = parsedInput;
390
- try {
391
- if (input === undefined) {
392
- const chunks = [];
393
- let size = 0;
394
- for await (const chunk of req) {
395
- const buffer = Buffer.from(chunk);
396
- size += buffer.length;
397
- if (size > 1024 * 1024) return reply(413, { error: 'Request body exceeds 1 MiB.' });
398
- chunks.push(buffer);
399
- }
400
- input = JSON.parse(Buffer.concat(chunks).toString('utf8'));
401
- }
402
- if (!input || typeof input !== 'object' || Array.isArray(input)) throw new Error();
403
- } catch {
404
- return reply(400, { error: 'A JSON object is required.' });
405
- }
406
-
407
- const bearer = req.headers.authorization?.match(/^Bearer\s+(\S+)$/i)?.[1];
408
- const apikey = bearer || input.apikey;
409
- if ((apikey !== undefined && (typeof apikey !== 'string' || !apikey.trim())) ||
410
- (bearer && input.apikey !== undefined && input.apikey !== bearer)) {
411
- return reply(401, { error: 'A valid API key is required.' });
412
- }
413
-
414
- try {
415
- const host = new URL(`https://${req.headers.host}`).hostname;
416
- const organization = await server.crud.getOrganization({ host });
417
- if (!organization?._id || organization.error) return reply(404, { error: 'Organization not found.' });
418
- if (typeof input.api !== 'string' || !input.api.trim() ||
419
- typeof input.endpoint !== 'string' || !input.endpoint.trim() ||
420
- typeof input.method !== 'string' || !input.method.trim()) {
421
- return reply(400, { error: 'api, endpoint and method are required.' });
422
- }
423
- const envelope = pickHttpFields(input, ['api', 'endpoint', 'method', 'data', 'region', 'headers', 'searchParams', 'timeout']);
424
- // Scope and identity are server-resolved, never supplied by the caller.
425
- Object.assign(envelope, { organization_id: organization._id, host, apikey });
426
- const request = await server.authorize?.request(envelope);
427
- if (!request) return reply(403, { error: 'Operation is not authorized.' });
428
- const result = await execute(request);
429
- const failed = result?.success === false || hasHttpErrors(result?.error);
430
- reply(failed ? 400 : 200, result);
431
- return failed ? undefined : result;
432
- } catch (error) {
433
- if (error.code === 'AUTHORIZATION_DENIED') return reply(403, { error: error.message });
434
- return reply(500, { error: 'Unable to process the operation.' });
435
- }
436
- }
437
-
438
- function hasHttpErrors(error) {
439
- return Array.isArray(error) ? error.length > 0 : Boolean(error);
440
- }
441
-
442
- function pickHttpFields(input, fields) {
443
- return Object.fromEntries(fields.filter(field => Object.hasOwn(input, field)).map(field => [field, input[field]]));
444
- }
445
-
446
363
  /**
447
364
  * Processes incoming HTTP webhook requests, verifies HMAC/JWT security signatures, and executes pipelines.
448
365
  *
@@ -455,7 +372,7 @@ function pickHttpFields(input, fields) {
455
372
  */
456
373
  export async function webhook(req, res) {
457
374
  try {
458
- const wsManager = server?.wsManager;
375
+ const socket = server?.socket;
459
376
  const urlObject = new URL(`http://${req.headers.host}${req.url}`);
460
377
  const hostname = urlObject.hostname;
461
378
 
@@ -511,7 +428,7 @@ export async function webhook(req, res) {
511
428
  organization,
512
429
  organization_id: organization._id,
513
430
  crud,
514
- wsManager,
431
+ socket,
515
432
  key: apiConfig.key,
516
433
  config: apiConfig
517
434
  };
@@ -8,14 +8,15 @@ const { URL } = require('node:url');
8
8
  const source = fs.readFileSync(require.resolve('../src/server.js'), 'utf8')
9
9
  .replace(/^import \{ URL \} from 'node:url';$/m, '')
10
10
  .replace(/import \{[\s\S]*?\} from '@cocreate\/utils';/, '')
11
+ .replace(/^import \{ astAsync \} from '@cocreate\/ast\/server';$/m, '')
11
12
  .replace(/export async function/g, 'async function')
12
13
  .replace(/export default \{[\s\S]*?\};/, '');
13
14
  const dependencies = Promise.all([
14
- import('../../CoCreate-utils/src/modules/ast/index.js'),
15
+ import('../../ast/src/server.js'),
15
16
  import('../../CoCreate-utils/src/modules/objectToSearchParams.js'),
16
17
  import('../../CoCreate-utils/src/modules/searchParamsToObject.js'),
17
- import('../../../CoCreate-app/src/apps/endpoints/config/data.js'),
18
- import('../../../CoCreate-app/src/apps/servers/configs/config/autoscaler.js')
18
+ import('../../../app/src/apps/endpoints/config/data.js'),
19
+ import('../../../app/src/apps/configs/config/autoscaler.js')
19
20
  ]);
20
21
 
21
22
  async function setup({ index = 0, storage, storageError } = {}) {
@@ -29,7 +30,7 @@ async function setup({ index = 0, storage, storageError } = {}) {
29
30
  const context = vm.createContext({
30
31
  Buffer, URL, AbortController, setTimeout, clearTimeout,
31
32
  console: { log() {}, warn() {}, error() {} },
32
- objectToSearchParams, searchParamsToObject, astAsync, security: {},
33
+ objectToSearchParams, searchParamsToObject, astAsync, kms: {},
33
34
  fetch: async (url, options) => {
34
35
  const body = options.body?.startsWith('{')
35
36
  ? JSON.parse(options.body)
@@ -79,7 +80,7 @@ async function setup({ index = 0, storage, storageError } = {}) {
79
80
  setStorage(value) { currentStorage = value; },
80
81
  async run(data = {}) {
81
82
  const original = {
82
- storage: 'storage-id', region: 'example', vmType: 'small', vmId: 'server-example',
83
+ storage: 'storage-id', region: 'example', type: 'small', id: 'server-example',
83
84
  cluster_id: 'cluster-id', host: 'example.com', binaryUrl: 'https://example.com/runtime.tar.gz',
84
85
  environment: 'server_id=server-id\ncluster_id=cluster-id',
85
86
  startupScript: startup.default.object[0].config.startupScript,
@@ -184,7 +185,7 @@ test('storage read errors and malformed records stop the endpoint pipeline', asy
184
185
 
185
186
 
186
187
  test('storage lookup requests MongoDB-compatible provider template exclusions', async () => {
187
- const template = fs.readFileSync(new URL('../../../CoCreate-app/src/apps/apis/components/fields.html', 'file://' + __filename), 'utf8');
188
+ const template = fs.readFileSync(new URL('../../../app/src/apps/apis/components/fields.html', 'file://' + __filename), 'utf8');
188
189
  const excluded = template.match(/render-exclude="([^"]+)"/)[1].split(',').map(key => key.trim())
189
190
  .filter(key => !['name', 'provider', '_id'].includes(key) && !key.startsWith('$'));
190
191
  const fixture = await setup({ storage: record });
@@ -6,7 +6,7 @@ test('API responses and errors enter server.send instead of raw socket delivery'
6
6
  const sent = [];
7
7
  await init({ organization_id: 'platform', crud: {},
8
8
  send: data => { sent.push(data); return data; },
9
- wsManager: { send() { assert.fail('API must use server.send'); } } });
9
+ socket: { send() { assert.fail('API must use server.send'); } } });
10
10
  t.mock.method(globalThis, 'fetch', async () => new Response('{"ok":true}', { headers: { 'content-type': 'application/json' } }));
11
11
  const data = { method: 'get', url: 'https://example.test', organization_id: 'tenant',
12
12
  socketId: 'trusted-socket', clientId: 'trusted-client', host: 'tenant.test',
@@ -31,7 +31,7 @@ test('API AST socket operators retain tenant scope while entering server.send',
31
31
  ? [{ _id: 'provider', url: 'https://example.test' }]
32
32
  : [{ resolved: true, data: { '$socket.send': { method: 'notification', organization_id: 'forged', host: 'forged' } } }] }) },
33
33
  send: data => { sent.push({ ...data }); return data; },
34
- wsManager: { send() { assert.fail('AST must use server.send'); } } });
34
+ socket: { send() { assert.fail('AST must use server.send'); } } });
35
35
  const data = { method: 'post', api: 'provider', endpoint: 'notify', organization_id: 'tenant',
36
36
  socketId: 'trusted-socket', clientId: 'trusted-client', host: 'tenant.test',
37
37
  socket: { organization_id: 'forged-org', host: 'forged.test' } };