@aloma.io/integration-sdk 3.8.67 → 3.8.68
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/README.md +60 -0
- package/build/testing/fake-aloma.d.mts +87 -0
- package/build/testing/fake-aloma.mjs +248 -0
- package/build/testing/harness.d.mts +51 -0
- package/build/testing/harness.mjs +139 -0
- package/build/testing/index.d.mts +15 -0
- package/build/testing/index.mjs +13 -0
- package/build/testing/keys.d.mts +9 -0
- package/build/testing/keys.mjs +15 -0
- package/build/testing/network-guard.d.mts +3 -0
- package/build/testing/network-guard.mjs +49 -0
- package/build/testing/runtime-connector.d.mts +11 -0
- package/build/testing/runtime-connector.mjs +38 -0
- package/build/testing/vendor-mock.d.mts +59 -0
- package/build/testing/vendor-mock.mjs +121 -0
- package/package.json +7 -3
- package/src/testing/fake-aloma.mts +306 -0
- package/src/testing/harness.mts +172 -0
- package/src/testing/index.mts +15 -0
- package/src/testing/keys.mts +19 -0
- package/src/testing/network-guard.mts +57 -0
- package/src/testing/runtime-connector.mts +50 -0
- package/src/testing/vendor-mock.mts +166 -0
- package/test/MUTATION-entry.md +21 -0
- package/test/MUTATION.md +43 -0
- package/test/harness-connector-smoke.test.mjs +72 -0
- package/test/harness.test.mjs +375 -0
- package/test/openapi-to-connector.test.mts +25 -7
- package/test/scenarios.test.mts +15 -7
- package/tools/mutation-run-entry.mjs +52 -0
- package/tools/mutation-run.mjs +120 -0
- package/tools/run-tests.mjs +64 -0
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import net from 'node:net';
|
|
2
|
+
/**
|
|
3
|
+
* Test-only network guard.
|
|
4
|
+
*
|
|
5
|
+
* While installed, any TCP connection to a host that is not loopback throws
|
|
6
|
+
* immediately. fetch (undici), http, https, ws and axios all end up in
|
|
7
|
+
* net.Socket.prototype.connect, so this is the safety net behind the vendor mock:
|
|
8
|
+
* even code that bypasses global fetch cannot reach the network from a test.
|
|
9
|
+
*/
|
|
10
|
+
const LOOPBACK = new Set(['127.0.0.1', 'localhost', '::1', '[::1]']);
|
|
11
|
+
let original;
|
|
12
|
+
let installs = 0;
|
|
13
|
+
export const blocked = [];
|
|
14
|
+
const targetOf = (args) => {
|
|
15
|
+
// net.connect hands over a normalized [options, callback] array
|
|
16
|
+
const first = Array.isArray(args[0]) ? args[0][0] : args[0];
|
|
17
|
+
if (first && typeof first === 'object' && !Array.isArray(first)) {
|
|
18
|
+
if (first.path)
|
|
19
|
+
return { host: String(first.path), local: true };
|
|
20
|
+
return { host: String(first.host ?? 'localhost'), local: false };
|
|
21
|
+
}
|
|
22
|
+
if (typeof first === 'number' || (typeof first === 'string' && !Number.isNaN(Number(first)))) {
|
|
23
|
+
return { host: typeof args[1] === 'string' ? args[1] : 'localhost', local: false };
|
|
24
|
+
}
|
|
25
|
+
// unix socket path
|
|
26
|
+
return { host: String(first), local: true };
|
|
27
|
+
};
|
|
28
|
+
export const installNetworkGuard = () => {
|
|
29
|
+
if (installs++ > 0)
|
|
30
|
+
return;
|
|
31
|
+
original = net.Socket.prototype.connect;
|
|
32
|
+
net.Socket.prototype.connect = function (...args) {
|
|
33
|
+
const { host, local } = targetOf(args);
|
|
34
|
+
if (!local && !LOOPBACK.has(host)) {
|
|
35
|
+
const message = `NETWORK BLOCKED by connector test harness: connection to ${host} is not allowed in tests`;
|
|
36
|
+
blocked.push(host);
|
|
37
|
+
throw new Error(message);
|
|
38
|
+
}
|
|
39
|
+
return original.apply(this, args);
|
|
40
|
+
};
|
|
41
|
+
};
|
|
42
|
+
export const uninstallNetworkGuard = () => {
|
|
43
|
+
if (installs === 0)
|
|
44
|
+
return;
|
|
45
|
+
if (--installs > 0)
|
|
46
|
+
return;
|
|
47
|
+
net.Socket.prototype.connect = original;
|
|
48
|
+
original = undefined;
|
|
49
|
+
};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type RuntimeContext from '../builder/runtime-context.mjs';
|
|
2
|
+
import { Connector } from '../internal/connector/index.mjs';
|
|
3
|
+
/**
|
|
4
|
+
* Turn what a connector repo builds (`await new Builder()...build()` gives a RuntimeContext) into a configured
|
|
5
|
+
* `Connector` that the ConnectorHarness can run, without calling `connector.run()` (which starts a metrics
|
|
6
|
+
* server on a fixed port and installs process signal handlers).
|
|
7
|
+
*
|
|
8
|
+
* This repeats the wiring of RuntimeContext.start(): methods become resolvers, config/oauth/endpoint are applied,
|
|
9
|
+
* main() starts the controller and sends a health check. If RuntimeContext.start() changes, change this too.
|
|
10
|
+
*/
|
|
11
|
+
export declare const connectorFromRuntimeContext: (context: RuntimeContext) => Connector;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { AbstractController } from '../controller/index.mjs';
|
|
2
|
+
import { buildResolvers } from '../builder/runtime-context.mjs';
|
|
3
|
+
import { Connector } from '../internal/connector/index.mjs';
|
|
4
|
+
/**
|
|
5
|
+
* Turn what a connector repo builds (`await new Builder()...build()` gives a RuntimeContext) into a configured
|
|
6
|
+
* `Connector` that the ConnectorHarness can run, without calling `connector.run()` (which starts a metrics
|
|
7
|
+
* server on a fixed port and installs process signal handlers).
|
|
8
|
+
*
|
|
9
|
+
* This repeats the wiring of RuntimeContext.start(): methods become resolvers, config/oauth/endpoint are applied,
|
|
10
|
+
* main() starts the controller and sends a health check. If RuntimeContext.start() changes, change this too.
|
|
11
|
+
*/
|
|
12
|
+
export const connectorFromRuntimeContext = (context) => {
|
|
13
|
+
const { controller, data } = context;
|
|
14
|
+
if (!(controller instanceof AbstractController)) {
|
|
15
|
+
throw new Error('the controller needs to extend AbstractController');
|
|
16
|
+
}
|
|
17
|
+
const connector = new Connector({
|
|
18
|
+
id: data.id,
|
|
19
|
+
version: data.version,
|
|
20
|
+
name: `${data.id}/${data.version}`,
|
|
21
|
+
icon: undefined,
|
|
22
|
+
});
|
|
23
|
+
const configuration = connector.configure().config(data.config || {});
|
|
24
|
+
const methods = [...data.methods, '__autocomplete', '__endpoint', '__default'];
|
|
25
|
+
configuration.types(data.types).resolvers(buildResolvers(methods, controller));
|
|
26
|
+
if (data.options?.endpoint?.enabled) {
|
|
27
|
+
configuration.endpoint((arg) => controller.__endpoint(arg), data.options?.endpoint?.required);
|
|
28
|
+
}
|
|
29
|
+
if (data.auth?.oauth) {
|
|
30
|
+
configuration.oauth(data.auth?.oauth);
|
|
31
|
+
}
|
|
32
|
+
configuration.main(async ({ newTask, updateTask, config, oauth, getClient, getBlob, getBlobContent, createBlob, healthCheck }) => {
|
|
33
|
+
await controller._doStop();
|
|
34
|
+
await controller._doStart(config, oauth, newTask, updateTask, getClient, getBlob, getBlobContent, createBlob);
|
|
35
|
+
await healthCheck(controller);
|
|
36
|
+
});
|
|
37
|
+
return connector;
|
|
38
|
+
};
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/// <reference types="node" resolution-mode="require"/>
|
|
2
|
+
export type VendorRequest = {
|
|
3
|
+
method: string;
|
|
4
|
+
url: string;
|
|
5
|
+
/** the url exactly as the connector passed it to fetch */
|
|
6
|
+
rawUrl: string;
|
|
7
|
+
headers: Record<string, string>;
|
|
8
|
+
body?: string;
|
|
9
|
+
};
|
|
10
|
+
export type VendorResponse = {
|
|
11
|
+
status?: number;
|
|
12
|
+
headers?: Record<string, string>;
|
|
13
|
+
/** sent as JSON with a json content-type */
|
|
14
|
+
json?: unknown;
|
|
15
|
+
/** sent as is */
|
|
16
|
+
text?: string;
|
|
17
|
+
};
|
|
18
|
+
export type VendorResponder = VendorResponse | ((request: VendorRequest) => VendorResponse | Promise<VendorResponse>);
|
|
19
|
+
export type UrlMatcher = string | RegExp | ((url: string) => boolean);
|
|
20
|
+
/**
|
|
21
|
+
* Mock for the HTTP calls a connector makes to its vendor API.
|
|
22
|
+
*
|
|
23
|
+
* - intercepts global fetch (what the SDK Fetcher and OAuth code use)
|
|
24
|
+
* - answers from routes you register with on()/get()/post()...
|
|
25
|
+
* - any request without a route is recorded in `unmocked` and rejected,
|
|
26
|
+
* verify() then fails the test even if the connector swallowed the error
|
|
27
|
+
* - also installs the network guard, so nothing can reach a non-loopback host
|
|
28
|
+
*/
|
|
29
|
+
export declare class VendorMock {
|
|
30
|
+
readonly requests: VendorRequest[];
|
|
31
|
+
readonly unmocked: VendorRequest[];
|
|
32
|
+
private routes;
|
|
33
|
+
private originalFetch?;
|
|
34
|
+
private passthrough;
|
|
35
|
+
/** urls for which the real fetch is used (the fake ALOMA endpoint); everything else is mocked */
|
|
36
|
+
allowPassthrough(fn: (url: URL) => boolean): this;
|
|
37
|
+
on(method: string, matcher: UrlMatcher, respond: VendorResponder, options?: {
|
|
38
|
+
times?: number;
|
|
39
|
+
}): this;
|
|
40
|
+
get(matcher: UrlMatcher, respond: VendorResponder, options?: {
|
|
41
|
+
times?: number;
|
|
42
|
+
}): this;
|
|
43
|
+
post(matcher: UrlMatcher, respond: VendorResponder, options?: {
|
|
44
|
+
times?: number;
|
|
45
|
+
}): this;
|
|
46
|
+
put(matcher: UrlMatcher, respond: VendorResponder, options?: {
|
|
47
|
+
times?: number;
|
|
48
|
+
}): this;
|
|
49
|
+
delete(matcher: UrlMatcher, respond: VendorResponder, options?: {
|
|
50
|
+
times?: number;
|
|
51
|
+
}): this;
|
|
52
|
+
install(): this;
|
|
53
|
+
uninstall(): void;
|
|
54
|
+
/** throws if the connector made a request that had no mock, even if it caught the error */
|
|
55
|
+
verify(): void;
|
|
56
|
+
/** throws if a registered route was never used */
|
|
57
|
+
verifyAllRoutesUsed(): void;
|
|
58
|
+
private handle;
|
|
59
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { installNetworkGuard, uninstallNetworkGuard } from './network-guard.mjs';
|
|
2
|
+
// "https:/host/x" (one slash, which the SDK Fetcher produces) and "https://host/x" are the same URL to fetch
|
|
3
|
+
const canonical = (url) => {
|
|
4
|
+
try {
|
|
5
|
+
return new URL(url).href;
|
|
6
|
+
}
|
|
7
|
+
catch (e) {
|
|
8
|
+
return url;
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
const matches = (matcher, url) => {
|
|
12
|
+
if (typeof matcher === 'string')
|
|
13
|
+
return canonical(matcher) === url;
|
|
14
|
+
if (matcher instanceof RegExp)
|
|
15
|
+
return matcher.test(url);
|
|
16
|
+
return matcher(url);
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Mock for the HTTP calls a connector makes to its vendor API.
|
|
20
|
+
*
|
|
21
|
+
* - intercepts global fetch (what the SDK Fetcher and OAuth code use)
|
|
22
|
+
* - answers from routes you register with on()/get()/post()...
|
|
23
|
+
* - any request without a route is recorded in `unmocked` and rejected,
|
|
24
|
+
* verify() then fails the test even if the connector swallowed the error
|
|
25
|
+
* - also installs the network guard, so nothing can reach a non-loopback host
|
|
26
|
+
*/
|
|
27
|
+
export class VendorMock {
|
|
28
|
+
requests = [];
|
|
29
|
+
unmocked = [];
|
|
30
|
+
routes = [];
|
|
31
|
+
originalFetch;
|
|
32
|
+
passthrough = () => false;
|
|
33
|
+
/** urls for which the real fetch is used (the fake ALOMA endpoint); everything else is mocked */
|
|
34
|
+
allowPassthrough(fn) {
|
|
35
|
+
this.passthrough = fn;
|
|
36
|
+
return this;
|
|
37
|
+
}
|
|
38
|
+
on(method, matcher, respond, options = {}) {
|
|
39
|
+
this.routes.push({ method: method.toUpperCase(), matcher, respond, times: options.times ?? Infinity, used: 0 });
|
|
40
|
+
return this;
|
|
41
|
+
}
|
|
42
|
+
get(matcher, respond, options) {
|
|
43
|
+
return this.on('GET', matcher, respond, options);
|
|
44
|
+
}
|
|
45
|
+
post(matcher, respond, options) {
|
|
46
|
+
return this.on('POST', matcher, respond, options);
|
|
47
|
+
}
|
|
48
|
+
put(matcher, respond, options) {
|
|
49
|
+
return this.on('PUT', matcher, respond, options);
|
|
50
|
+
}
|
|
51
|
+
delete(matcher, respond, options) {
|
|
52
|
+
return this.on('DELETE', matcher, respond, options);
|
|
53
|
+
}
|
|
54
|
+
install() {
|
|
55
|
+
if (this.originalFetch)
|
|
56
|
+
return this;
|
|
57
|
+
installNetworkGuard();
|
|
58
|
+
this.originalFetch = globalThis.fetch;
|
|
59
|
+
globalThis.fetch = ((input, init) => this.handle(input, init));
|
|
60
|
+
return this;
|
|
61
|
+
}
|
|
62
|
+
uninstall() {
|
|
63
|
+
if (!this.originalFetch)
|
|
64
|
+
return;
|
|
65
|
+
globalThis.fetch = this.originalFetch;
|
|
66
|
+
this.originalFetch = undefined;
|
|
67
|
+
uninstallNetworkGuard();
|
|
68
|
+
}
|
|
69
|
+
/** throws if the connector made a request that had no mock, even if it caught the error */
|
|
70
|
+
verify() {
|
|
71
|
+
if (this.unmocked.length) {
|
|
72
|
+
const list = this.unmocked.map((r) => `${r.method} ${r.url}`).join('\n ');
|
|
73
|
+
throw new Error(`UNMOCKED vendor requests were made (no network is allowed in tests):\n ${list}`);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
/** throws if a registered route was never used */
|
|
77
|
+
verifyAllRoutesUsed() {
|
|
78
|
+
const unused = this.routes.filter((r) => r.used === 0);
|
|
79
|
+
if (unused.length) {
|
|
80
|
+
throw new Error(`mocked routes never called: ${unused.map((r) => `${r.method} ${String(r.matcher)}`).join(', ')}`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
async handle(input, init = {}) {
|
|
84
|
+
const rawUrl = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
|
|
85
|
+
const url = canonical(rawUrl);
|
|
86
|
+
const method = String(init.method || (typeof input === 'object' && input.method) || 'GET').toUpperCase();
|
|
87
|
+
const headers = {};
|
|
88
|
+
new Headers(init.headers || (typeof input === 'object' && input.headers) || {}).forEach((value, key) => {
|
|
89
|
+
headers[key] = value;
|
|
90
|
+
});
|
|
91
|
+
const request = { method, url, rawUrl, headers };
|
|
92
|
+
if (init.body != null)
|
|
93
|
+
request.body = typeof init.body === 'string' ? init.body : String(init.body);
|
|
94
|
+
const route = this.routes.find((r) => r.method === method && r.used < r.times && matches(r.matcher, url));
|
|
95
|
+
if (route) {
|
|
96
|
+
route.used++;
|
|
97
|
+
this.requests.push(request);
|
|
98
|
+
const spec = typeof route.respond === 'function' ? await route.respond(request) : route.respond;
|
|
99
|
+
const responseHeaders = { ...spec.headers };
|
|
100
|
+
let body = null;
|
|
101
|
+
if (spec.json !== undefined) {
|
|
102
|
+
body = JSON.stringify(spec.json);
|
|
103
|
+
responseHeaders['content-type'] ||= 'application/json';
|
|
104
|
+
}
|
|
105
|
+
else if (spec.text !== undefined) {
|
|
106
|
+
body = spec.text;
|
|
107
|
+
}
|
|
108
|
+
const status = spec.status ?? 200;
|
|
109
|
+
return new Response([204, 205, 304].includes(status) ? null : body, { status, headers: responseHeaders });
|
|
110
|
+
}
|
|
111
|
+
if (this.originalFetch && this.passthrough(new URL(url))) {
|
|
112
|
+
return this.originalFetch(input, init);
|
|
113
|
+
}
|
|
114
|
+
this.unmocked.push(request);
|
|
115
|
+
// status 400 makes the SDK Fetcher give up at once instead of retrying for seconds
|
|
116
|
+
const error = new Error(`UNMOCKED vendor request: ${method} ${url} (add a route with vendor.on(...))`);
|
|
117
|
+
error.status = 400;
|
|
118
|
+
error.alomaHarnessUnmocked = true;
|
|
119
|
+
throw error;
|
|
120
|
+
}
|
|
121
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aloma.io/integration-sdk",
|
|
3
|
-
"version": "3.8.
|
|
3
|
+
"version": "3.8.68",
|
|
4
4
|
"description": "",
|
|
5
5
|
"author": "aloma.io",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -11,7 +11,9 @@
|
|
|
11
11
|
"scripts": {
|
|
12
12
|
"dev": "./node_modules/typescript/bin/tsc --watch",
|
|
13
13
|
"build": "./node_modules/typescript/bin/tsc",
|
|
14
|
-
"test": "
|
|
14
|
+
"test": "node tools/run-tests.mjs",
|
|
15
|
+
"test:harness": "./node_modules/mocha/bin/_mocha --exit \"test/harness*.test.mjs\"",
|
|
16
|
+
"test:mutation": "node tools/mutation-run.mjs",
|
|
15
17
|
"test:scenarios": "node test/verify-scenarios.mjs",
|
|
16
18
|
"test:all": "npm run test:scenarios",
|
|
17
19
|
"format": "yarn prettier --write src/",
|
|
@@ -55,7 +57,9 @@
|
|
|
55
57
|
"ts-node": "^10.9.2"
|
|
56
58
|
},
|
|
57
59
|
"resolutions": {
|
|
58
|
-
"path-to-regexp": "0.1.13"
|
|
60
|
+
"path-to-regexp": "0.1.13",
|
|
61
|
+
"qs": ">=6.15.2",
|
|
62
|
+
"serialize-javascript": ">=7.0.5"
|
|
59
63
|
},
|
|
60
64
|
"repository": {
|
|
61
65
|
"type": "git",
|
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
import {randomUUID} from 'node:crypto';
|
|
2
|
+
import http from 'node:http';
|
|
3
|
+
import type {AddressInfo} from 'node:net';
|
|
4
|
+
import * as jose from 'jose';
|
|
5
|
+
import {WebSocket, WebSocketServer} from 'ws';
|
|
6
|
+
|
|
7
|
+
type Packet = {id?: string; m?: string; c?: string; a?: any; e?: any};
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* A fake ALOMA endpoint that speaks the connector protocol, in-process on a loopback port.
|
|
11
|
+
*
|
|
12
|
+
* Protocol (taken from src/internal/websocket and src/internal/dispatcher):
|
|
13
|
+
* 1. POST {url}connect with `Authorization: Connector <token>`. 401 means "register first", 200 + json means connected.
|
|
14
|
+
* 2. POST {url}register with `Authorization: Connector <registrationToken>` and
|
|
15
|
+
* {name, version, id, publicKey, schema:{configSchema, introspect}, icon}; answer 200 {key: <token>}.
|
|
16
|
+
* 3. The connector opens a websocket at wsUrl (subprotocol "connector", same Authorization header).
|
|
17
|
+
* 4. Both sides exchange text frames {p: [packet, ...]}; a packet is {id, m: method, c: callback key, a: args}.
|
|
18
|
+
* 5. ALOMA sends connector.set-config {secrets} (no reply), then connector.query {query, variables} with a
|
|
19
|
+
* callback key; the connector answers {c: key, a: result} or {c: key, a: {error}}.
|
|
20
|
+
*
|
|
21
|
+
* Anything that does not look like the real protocol is recorded in `protocolErrors`.
|
|
22
|
+
*/
|
|
23
|
+
export class FakeAloma {
|
|
24
|
+
readonly registrationToken = `fake-registration-${randomUUID()}`;
|
|
25
|
+
readonly sessionToken = `fake-session-${randomUUID()}`;
|
|
26
|
+
|
|
27
|
+
/** bodies of POST /register */
|
|
28
|
+
readonly registrations: any[] = [];
|
|
29
|
+
/** headers of POST /connect */
|
|
30
|
+
readonly connects: Array<{authorized: boolean; headers: http.IncomingHttpHeaders}> = [];
|
|
31
|
+
/** every packet the connector sent over the websocket, in order */
|
|
32
|
+
readonly received: Packet[] = [];
|
|
33
|
+
readonly protocolErrors: string[] = [];
|
|
34
|
+
|
|
35
|
+
private server!: http.Server;
|
|
36
|
+
private wss!: WebSocketServer;
|
|
37
|
+
private socket?: WebSocket;
|
|
38
|
+
private pending = new Map<string, (args: any) => void>();
|
|
39
|
+
private handlers = new Map<string, (args: any) => any | Promise<any>>();
|
|
40
|
+
private waiters: Array<() => void> = [];
|
|
41
|
+
private port = 0;
|
|
42
|
+
private id = '';
|
|
43
|
+
private version = '';
|
|
44
|
+
|
|
45
|
+
static async start(): Promise<FakeAloma> {
|
|
46
|
+
const fake = new FakeAloma();
|
|
47
|
+
await fake.listen();
|
|
48
|
+
|
|
49
|
+
return fake;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** value for the connector's endpoint setting (env.DEVICE_ENDPOINT) */
|
|
53
|
+
get url() {
|
|
54
|
+
return `http://127.0.0.1:${this.port}/`;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** value for the connector's websocket setting (env.WEBSOCKET_ENDPOINT) */
|
|
58
|
+
get wsUrl() {
|
|
59
|
+
return `ws://127.0.0.1:${this.port}/transport/`;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
get connected() {
|
|
63
|
+
return this.socket?.readyState === WebSocket.OPEN;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
get registration() {
|
|
67
|
+
return this.registrations[this.registrations.length - 1];
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
private async listen() {
|
|
71
|
+
this.server = http.createServer((req, res) => {
|
|
72
|
+
this.onHttp(req, res).catch((e) => {
|
|
73
|
+
this.protocolErrors.push(`http handler failed: ${e}`);
|
|
74
|
+
res.writeHead(500).end();
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
this.wss = new WebSocketServer({
|
|
79
|
+
noServer: true,
|
|
80
|
+
handleProtocols: (protocols) => (protocols.has('connector') ? 'connector' : false),
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
this.server.on('upgrade', (req, socket, head) => {
|
|
84
|
+
const problems: string[] = [];
|
|
85
|
+
if (req.headers.authorization !== `Connector ${this.sessionToken}`) problems.push('bad or missing Authorization on websocket');
|
|
86
|
+
if (!String(req.headers['sec-websocket-protocol'] || '').split(/,\s*/).includes('connector')) {
|
|
87
|
+
problems.push('websocket subprotocol "connector" not requested');
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
if (problems.length) {
|
|
91
|
+
this.protocolErrors.push(...problems);
|
|
92
|
+
socket.write('HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n');
|
|
93
|
+
socket.destroy();
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
this.wss.handleUpgrade(req, socket, head, (ws) => this.onSocket(ws));
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
await new Promise<void>((resolve) => this.server.listen(0, '127.0.0.1', () => resolve()));
|
|
101
|
+
this.port = (this.server.address() as AddressInfo).port;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
private async readJson(req: http.IncomingMessage) {
|
|
105
|
+
let text = '';
|
|
106
|
+
for await (const chunk of req) text += chunk;
|
|
107
|
+
|
|
108
|
+
return text ? JSON.parse(text) : {};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
private async onHttp(req: http.IncomingMessage, res: http.ServerResponse) {
|
|
112
|
+
const send = (status: number, body?: unknown) => {
|
|
113
|
+
res.writeHead(status, {'Content-Type': 'application/json'});
|
|
114
|
+
res.end(body === undefined ? '' : JSON.stringify(body));
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
const body = await this.readJson(req);
|
|
118
|
+
const auth = req.headers.authorization;
|
|
119
|
+
|
|
120
|
+
if (req.method === 'POST' && req.url === '/connect') {
|
|
121
|
+
const authorized = auth === `Connector ${this.sessionToken}`;
|
|
122
|
+
this.connects.push({authorized, headers: req.headers});
|
|
123
|
+
|
|
124
|
+
return authorized ? send(200, {}) : send(401);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
if (req.method === 'POST' && req.url === '/register') {
|
|
128
|
+
if (auth !== `Connector ${this.registrationToken}`) {
|
|
129
|
+
this.protocolErrors.push('register called with a wrong registration token');
|
|
130
|
+
return send(401);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const missing = ['name', 'version', 'id', 'publicKey', 'schema'].filter((key) => body[key] == null);
|
|
134
|
+
if (missing.length) this.protocolErrors.push(`register body is missing: ${missing.join(', ')}`);
|
|
135
|
+
|
|
136
|
+
this.id = body.id;
|
|
137
|
+
this.version = body.version;
|
|
138
|
+
if (req.headers['user-agent'] !== `${body.id}/${body.version}`) {
|
|
139
|
+
this.protocolErrors.push(`register User-Agent should be id/version, got ${req.headers['user-agent']}`);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
this.registrations.push(body);
|
|
143
|
+
|
|
144
|
+
return send(200, {key: this.sessionToken});
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
if (req.method === 'POST' && req.url === '/disconnect') return send(200, {});
|
|
148
|
+
|
|
149
|
+
this.protocolErrors.push(`unexpected request ${req.method} ${req.url}`);
|
|
150
|
+
send(404);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
private onSocket(ws: WebSocket) {
|
|
154
|
+
this.socket = ws;
|
|
155
|
+
|
|
156
|
+
ws.on('message', (raw) => {
|
|
157
|
+
const frame = JSON.parse(raw.toString());
|
|
158
|
+
const packets: Packet[] = frame.p;
|
|
159
|
+
|
|
160
|
+
if (!Array.isArray(packets)) {
|
|
161
|
+
this.protocolErrors.push('frame without a "p" array');
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
packets.forEach((packet) => this.onPacket(packet));
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
this.waiters.splice(0).forEach((fn) => fn());
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
private onPacket(packet: Packet) {
|
|
172
|
+
this.received.push(packet);
|
|
173
|
+
|
|
174
|
+
// an answer to something ALOMA sent
|
|
175
|
+
if (packet.c && !packet.m && this.pending.has(packet.c)) {
|
|
176
|
+
const done = this.pending.get(packet.c)!;
|
|
177
|
+
this.pending.delete(packet.c);
|
|
178
|
+
done(packet.a);
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// the connector asks ALOMA for something (blob, task, ...) and expects an answer on its callback key
|
|
183
|
+
if (packet.m && this.handlers.has(packet.m)) {
|
|
184
|
+
Promise.resolve(this.handlers.get(packet.m)!(packet.a)).then(
|
|
185
|
+
(answer) => packet.c && this.send({c: packet.c, a: answer}),
|
|
186
|
+
(e) => packet.c && this.send({c: packet.c, a: {error: String(e)}})
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** answer connector -> ALOMA requests such as connector.blob.get or connector.task.new */
|
|
192
|
+
handle(method: string, fn: (args: any) => any | Promise<any>) {
|
|
193
|
+
this.handlers.set(method, fn);
|
|
194
|
+
return this;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** resolves when the connector's websocket is open (the handshake is finished) */
|
|
198
|
+
async waitForConnection(timeoutMs = 5000) {
|
|
199
|
+
if (this.connected) return;
|
|
200
|
+
|
|
201
|
+
await new Promise<void>((resolve, reject) => {
|
|
202
|
+
const timer = setTimeout(() => {
|
|
203
|
+
reject(
|
|
204
|
+
new Error(
|
|
205
|
+
`connector did not connect within ${timeoutMs}ms. registrations=${this.registrations.length} ` +
|
|
206
|
+
`connects=${this.connects.length} protocolErrors=${JSON.stringify(this.protocolErrors)}`
|
|
207
|
+
)
|
|
208
|
+
);
|
|
209
|
+
}, timeoutMs);
|
|
210
|
+
|
|
211
|
+
this.waiters.push(() => {
|
|
212
|
+
clearTimeout(timer);
|
|
213
|
+
resolve();
|
|
214
|
+
});
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** resolves with the first packet the connector sent for `method` (e.g. connector.health.check), now or later */
|
|
219
|
+
async waitForPacket(method: string, timeoutMs = 5000): Promise<Packet> {
|
|
220
|
+
const deadline = Date.now() + timeoutMs;
|
|
221
|
+
|
|
222
|
+
for (;;) {
|
|
223
|
+
const found = this.received.find((packet) => packet.m === method);
|
|
224
|
+
if (found) return found;
|
|
225
|
+
if (Date.now() > deadline) throw new Error(`connector did not send ${method} within ${timeoutMs}ms`);
|
|
226
|
+
|
|
227
|
+
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** send one raw packet to the connector */
|
|
232
|
+
send(packet: Packet) {
|
|
233
|
+
if (!this.connected) throw new Error('connector is not connected');
|
|
234
|
+
|
|
235
|
+
this.socket!.send(JSON.stringify({p: [{id: randomUUID(), ...packet}]}));
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** send a packet with a callback key and wait for the connector's answer (its `a` field) */
|
|
239
|
+
request(method: string, args: any, timeoutMs = 5000): Promise<any> {
|
|
240
|
+
const key = `_req-${randomUUID()}`;
|
|
241
|
+
|
|
242
|
+
return new Promise((resolve, reject) => {
|
|
243
|
+
const timer = setTimeout(() => {
|
|
244
|
+
this.pending.delete(key);
|
|
245
|
+
reject(new Error(`no answer to ${method} within ${timeoutMs}ms`));
|
|
246
|
+
}, timeoutMs);
|
|
247
|
+
|
|
248
|
+
this.pending.set(key, (answer) => {
|
|
249
|
+
clearTimeout(timer);
|
|
250
|
+
resolve(answer);
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
this.send({m: method, c: key, a: args});
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** ask the connector for its schema and method list (connector.introspect) */
|
|
258
|
+
introspect() {
|
|
259
|
+
return this.request('connector.introspect', {});
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Send the configuration the way ALOMA does: every field that is not `plain` is a JWE encrypted with the
|
|
264
|
+
* public key the connector registered, audience = connector id. Resolves after the packet is sent;
|
|
265
|
+
* the ConnectorHarness waits for the connector's start.
|
|
266
|
+
*/
|
|
267
|
+
async setConfig(values: Record<string, any>) {
|
|
268
|
+
if (!this.registration) throw new Error('connector has not registered yet');
|
|
269
|
+
|
|
270
|
+
const fields = this.registration.schema?.configSchema?.fields || {};
|
|
271
|
+
const publicKey = await jose.importSPKI(Buffer.from(this.registration.publicKey, 'base64').toString(), 'RSA-OAEP-256');
|
|
272
|
+
const secrets: Record<string, any> = {};
|
|
273
|
+
|
|
274
|
+
for (const [key, value] of Object.entries(values)) {
|
|
275
|
+
if (fields[key]?.plain || key === 'endpointUrl') {
|
|
276
|
+
secrets[key] = value;
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
secrets[key] = await new jose.EncryptJWT({_data: value})
|
|
281
|
+
.setProtectedHeader({alg: 'RSA-OAEP-256', enc: 'A256GCM'})
|
|
282
|
+
.setIssuedAt()
|
|
283
|
+
.setIssuer('home.aloma.io')
|
|
284
|
+
.setAudience(this.id)
|
|
285
|
+
.encrypt(publicKey);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
this.send({m: 'connector.set-config', a: {secrets}});
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Call a connector method like ALOMA does (connector.query). Resolves with the connector's raw answer:
|
|
293
|
+
* an object result is passed through, any other value is wrapped as {[method]: value}, a failure is {error}.
|
|
294
|
+
*/
|
|
295
|
+
call(method: string | string[], variables?: any, ctx: {taskId?: string; namespace?: string; sticky?: boolean} = {}) {
|
|
296
|
+
return this.request('connector.query', {query: method, variables, ...ctx});
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
async close() {
|
|
300
|
+
this.pending.clear();
|
|
301
|
+
this.wss.clients.forEach((client) => client.terminate());
|
|
302
|
+
this.wss.close();
|
|
303
|
+
this.server.closeAllConnections?.();
|
|
304
|
+
await new Promise<void>((resolve) => this.server.close(() => resolve()));
|
|
305
|
+
}
|
|
306
|
+
}
|