@aloma.io/integration-sdk 3.8.70 → 3.8.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/README.md +15 -2
  2. package/build/internal/connector/server/on-connect/make-oauth.mjs +27 -6
  3. package/build/internal/fetcher/fetcher.d.mts +14 -1
  4. package/build/internal/fetcher/fetcher.mjs +52 -11
  5. package/build/internal/fetcher/oauth-fetcher.d.mts +15 -2
  6. package/build/internal/fetcher/oauth-fetcher.mjs +72 -27
  7. package/build/internal/util/index.d.mts +8 -0
  8. package/build/internal/util/index.mjs +13 -1
  9. package/build/internal/util/jwe/index.mjs +3 -1
  10. package/package.json +8 -3
  11. package/.prettierrc.cjs +0 -8
  12. package/FINDINGS-PLAT-47.md +0 -253
  13. package/MULTI_RESOURCE_GUIDE.md +0 -220
  14. package/OPENAPI_TO_CONNECTOR.md +0 -349
  15. package/examples/hello-world/package.json +0 -25
  16. package/examples/hello-world/src/controller/index.mts +0 -12
  17. package/examples/hello-world/src/index.mts +0 -6
  18. package/examples/hello-world/tsconfig.json +0 -27
  19. package/examples/sample-api.json +0 -325
  20. package/examples/sample-api.yaml +0 -222
  21. package/examples/simple-api.json +0 -39
  22. package/index.js +0 -4
  23. package/src/builder/index.mts +0 -274
  24. package/src/builder/runtime-context.mts +0 -129
  25. package/src/cli.mts +0 -533
  26. package/src/controller/index.mts +0 -278
  27. package/src/index.mts +0 -2
  28. package/src/internal/connector/config.mts +0 -59
  29. package/src/internal/connector/index.mts +0 -53
  30. package/src/internal/connector/metrics.mts +0 -34
  31. package/src/internal/connector/server/index.mts +0 -51
  32. package/src/internal/connector/server/on-connect/decrypt-config.mts +0 -27
  33. package/src/internal/connector/server/on-connect/finish-oauth.mts +0 -109
  34. package/src/internal/connector/server/on-connect/index.mts +0 -162
  35. package/src/internal/connector/server/on-connect/make-oauth.mts +0 -97
  36. package/src/internal/connector/server/on-connect/start-oauth.mts +0 -24
  37. package/src/internal/connector/server/on-message.mts +0 -13
  38. package/src/internal/dispatcher/index.mts +0 -231
  39. package/src/internal/fetcher/fetcher.mts +0 -215
  40. package/src/internal/fetcher/oauth-fetcher.mts +0 -153
  41. package/src/internal/index.mts +0 -3
  42. package/src/internal/util/index.mts +0 -52
  43. package/src/internal/util/jwe/cli.mts +0 -12
  44. package/src/internal/util/jwe/index.mts +0 -72
  45. package/src/internal/websocket/config.mjs +0 -109
  46. package/src/internal/websocket/connection/constants.mjs +0 -25
  47. package/src/internal/websocket/connection/index.mjs +0 -71
  48. package/src/internal/websocket/connection/registration.mjs +0 -42
  49. package/src/internal/websocket/index.mjs +0 -46
  50. package/src/internal/websocket/transport/durable.mjs +0 -71
  51. package/src/internal/websocket/transport/index.mjs +0 -194
  52. package/src/internal/websocket/transport/packet.mjs +0 -54
  53. package/src/internal/websocket/transport/processor.mjs +0 -66
  54. package/src/openapi-to-connector.mts +0 -1648
  55. package/src/testing/fake-aloma.mts +0 -306
  56. package/src/testing/harness.mts +0 -172
  57. package/src/testing/index.mts +0 -15
  58. package/src/testing/keys.mts +0 -19
  59. package/src/testing/network-guard.mts +0 -57
  60. package/src/testing/runtime-connector.mts +0 -50
  61. package/src/testing/vendor-mock.mts +0 -166
  62. package/src/transform/index.mts +0 -544
  63. package/test/MUTATION-entry.md +0 -21
  64. package/test/MUTATION.md +0 -43
  65. package/test/dispatcher-ctx-forwarding.test.mjs +0 -161
  66. package/test/fetcher-query-params.test.mjs +0 -294
  67. package/test/fixtures/transform/basic/expected.json +0 -9
  68. package/test/fixtures/transform/basic/src/controller/abstract.mts +0 -5
  69. package/test/fixtures/transform/basic/src/controller/index.mts +0 -30
  70. package/test/fixtures/transform/basic/tsconfig.json +0 -1
  71. package/test/fixtures/transform/interface-param/src/controller/abstract.mts +0 -5
  72. package/test/fixtures/transform/interface-param/src/controller/index.mts +0 -12
  73. package/test/fixtures/transform/interface-param/tsconfig.json +0 -1
  74. package/test/fixtures/transform/overloads/expected.json +0 -6
  75. package/test/fixtures/transform/overloads/src/controller/abstract.mts +0 -5
  76. package/test/fixtures/transform/overloads/src/controller/index.mts +0 -11
  77. package/test/fixtures/transform/overloads/tsconfig.json +0 -1
  78. package/test/fixtures/transform/tdd-stub/expected.json +0 -8
  79. package/test/fixtures/transform/tdd-stub/src/controller/abstract.mts +0 -6
  80. package/test/fixtures/transform/tdd-stub/src/controller/index.mts +0 -204
  81. package/test/fixtures/transform/tdd-stub/tsconfig.json +0 -1
  82. package/test/fixtures/transform/two-exports/src/controller/abstract.mts +0 -5
  83. package/test/fixtures/transform/two-exports/src/controller/index.mts +0 -9
  84. package/test/fixtures/transform/two-exports/tsconfig.json +0 -1
  85. package/test/fixtures/transform/type-error/src/controller/abstract.mts +0 -5
  86. package/test/fixtures/transform/type-error/src/controller/index.mts +0 -7
  87. package/test/fixtures/transform/type-error/tsconfig.json +0 -1
  88. package/test/fixtures/transform/typed/expected.json +0 -8
  89. package/test/fixtures/transform/typed/src/controller/abstract.mts +0 -5
  90. package/test/fixtures/transform/typed/src/controller/index.mts +0 -13
  91. package/test/fixtures/transform/typed/tsconfig.json +0 -1
  92. package/test/fixtures/transform/visibility/expected.json +0 -9
  93. package/test/fixtures/transform/visibility/src/controller/abstract.mts +0 -5
  94. package/test/fixtures/transform/visibility/src/controller/index.mts +0 -19
  95. package/test/fixtures/transform/visibility/tsconfig.json +0 -1
  96. package/test/harness-connector-smoke.test.mjs +0 -72
  97. package/test/harness.test.mjs +0 -375
  98. package/test/nested-resolver.test.mjs +0 -184
  99. package/test/openapi-generator-bugs.test.mjs +0 -248
  100. package/test/openapi-identifier-sanitise.test.mjs +0 -69
  101. package/test/openapi-nested-paths.test.mjs +0 -100
  102. package/test/openapi-to-connector.test.mts +0 -232
  103. package/test/openapi-ts-compilation.test.mjs +0 -178
  104. package/test/scenarios/README.md +0 -148
  105. package/test/scenarios/complex/expected/controller.mts +0 -271
  106. package/test/scenarios/complex/expected/orders-resource.mts +0 -262
  107. package/test/scenarios/complex/expected/products-resource.mts +0 -237
  108. package/test/scenarios/complex/specs/orders.json +0 -362
  109. package/test/scenarios/complex/specs/products.json +0 -308
  110. package/test/scenarios/simple/expected-controller.mts +0 -60
  111. package/test/scenarios/simple/simple-api.json +0 -39
  112. package/test/scenarios.test.mts +0 -294
  113. package/test/transform.test.mjs +0 -68
  114. package/test/verify-scenarios.mjs +0 -298
  115. package/tools/mutation-run-entry.mjs +0 -52
  116. package/tools/mutation-run.mjs +0 -138
  117. package/tools/run-tests.mjs +0 -64
  118. package/tsconfig.json +0 -27
@@ -1,215 +0,0 @@
1
- import {unwrap} from '../util/index.mjs';
2
-
3
- class ParamsError extends Error {}
4
-
5
- /**
6
- * build a query string from request params: undefined and null are skipped, arrays become repeated keys,
7
- * objects are refused; values are encoded by URLSearchParams
8
- */
9
- const toQuery = (params: any): string => {
10
- if (params == null) return '';
11
- if (params instanceof URLSearchParams) return params.toString();
12
- if (typeof params !== 'object' || Array.isArray(params)) throw new ParamsError('params must be an object');
13
-
14
- const query = new URLSearchParams();
15
- const add = (key: string, value: any) => {
16
- if (value == null) return;
17
- if (typeof value === 'object') {
18
- throw new ParamsError(`params.${key} is an object; only strings, numbers, booleans and arrays of them are sent`);
19
- }
20
- query.append(key, String(value));
21
- };
22
-
23
- for (const [key, value] of Object.entries(params)) {
24
- if (Array.isArray(value)) value.forEach((item) => add(key, item));
25
- else add(key, value);
26
- }
27
-
28
- return query.toString();
29
- };
30
-
31
- const withQuery = (url: string, query: string): string => {
32
- if (!query) return url;
33
-
34
- const hash = url.indexOf('#');
35
- const base = hash < 0 ? url : url.slice(0, hash);
36
- const sep = !base.includes('?') ? '?' : /[?&]$/.test(base) ? '' : '&';
37
-
38
- return base + sep + query + (hash < 0 ? '' : url.slice(hash));
39
- };
40
-
41
- /**
42
- * http request fetcher
43
- */
44
- export default class Fetcher {
45
- protected retry: number;
46
- protected baseUrl: any;
47
- protected onResponse: any;
48
- protected customize0: any;
49
- constructor({
50
- retry = 5,
51
- baseUrl,
52
- onResponse,
53
- customize,
54
- }: {
55
- retry?: number;
56
- baseUrl?: string;
57
- onResponse?: (response: Response) => void;
58
- customize?: (request: {[key: string]: any}) => void;
59
- } = {}) {
60
- this.retry = retry;
61
- this.baseUrl = baseUrl;
62
- this.onResponse = onResponse;
63
- if (customize) this.customize0 = customize;
64
- }
65
-
66
- async getToken(force: boolean): Promise<string> {
67
- throw new Error('not implemented');
68
- }
69
-
70
- protected async customize(options = {}, args = {}) {
71
- if (this.customize0) await this.customize0(options, args);
72
- }
73
-
74
- protected async onError(e: any, url: string, options: any, retries: number, args: any, rateLimit?) {
75
- var local = this;
76
-
77
- return new Promise((resolve, reject) => {
78
- setTimeout(
79
- async () => {
80
- try {
81
- resolve(await local.fetch(url, options, retries, args));
82
- } catch (e) {
83
- reject(e);
84
- }
85
- },
86
- rateLimit ? 10000 : 500
87
- );
88
- });
89
- }
90
-
91
- /**
92
- * fetch data from a url
93
- * @param url url to fetch
94
- * @param options request options
95
- * @param retries retries left for the request
96
- * @param args optional args for customize()
97
- * @returns
98
- */
99
- async fetch(
100
- url: string,
101
- options?: {
102
- /**
103
- * request method like GET, POST, PUT, DELETE
104
- */
105
- method?: string;
106
- /**
107
- * request headers like Accept, Content-type
108
- */
109
- headers?: {[key: string]: any};
110
- /**
111
- * request body like "hello world" or {hello: "world"}
112
- */
113
- body?: any;
114
- /**
115
- * query parameters like {limit: 10, properties: ["a", "b"]}, appended to the url;
116
- * undefined and null are skipped, arrays become repeated keys, objects are refused
117
- */
118
- params?: {[key: string]: any} | URLSearchParams;
119
- },
120
- retries?: number,
121
- args: any = {}
122
- ) {
123
- var local = this,
124
- baseUrl = local.baseUrl;
125
- options ||= {};
126
-
127
- const options0: any = {...options};
128
-
129
- if (retries == null) retries = local.retry;
130
-
131
- let theURL = !baseUrl ? url : `${baseUrl?.endsWith('/') ? baseUrl : baseUrl + '/'}${url}`.replace(/\/\/+/gi, '/');
132
-
133
- try {
134
- options0.url = url;
135
- await local.customize(options0, args);
136
-
137
- url = options0.url;
138
- delete options0.url;
139
-
140
- theURL = !baseUrl ? url : `${baseUrl?.endsWith('/') ? baseUrl : baseUrl + '/'}${url}`.replace(/\/\/+/gi, '/');
141
- // after the slash collapse, so encoded values are not altered; options0 keeps params for retries
142
- const fullURL = withQuery(theURL, toQuery(options0.params));
143
-
144
- if (!options0?.headers || !options0?.headers?.Accept) {
145
- options0.headers = {
146
- ...options0.headers,
147
- Accept: 'application/json',
148
- };
149
- }
150
-
151
- if ((!options0?.headers || !options0?.headers?.['Content-type']) && !(options0?.body instanceof FormData)) {
152
- options0.headers = {
153
- ...options0.headers,
154
- 'Content-type': 'application/json',
155
- };
156
- }
157
-
158
- if (
159
- !(options0?.method === 'GET' || options0?.method === 'HEAD') &&
160
- options0?.body &&
161
- !(typeof options0.body === 'string') &&
162
- options0?.headers?.['Content-type'] === 'application/json'
163
- ) {
164
- options0.body = JSON.stringify(options0.body);
165
- }
166
-
167
- const timeout = Math.min(options0?.timeout || 30 * 60 * 1000, 30 * 60 * 1000);
168
- const {params, ...init} = options0;
169
- const ret = await fetch(fullURL, {
170
- ...init,
171
- signal: AbortSignal.timeout(timeout),
172
- });
173
- const status = await ret.status;
174
-
175
- if (status > 399) {
176
- const text = await ret.text();
177
- const e: any = new Error(status + ' ' + text);
178
-
179
- e.status = status;
180
- throw e;
181
- }
182
-
183
- if (local.onResponse) {
184
- await local.onResponse(ret);
185
- }
186
-
187
- if (status === 204) {
188
- return {ok: true};
189
- }
190
-
191
- return unwrap(ret, options0);
192
- } catch (e: any) {
193
- if (e instanceof ParamsError) throw e;
194
-
195
- // too many requests
196
- if (e.status === 429) {
197
- return local.onError(e, url, options0, retries, args, true);
198
- }
199
-
200
- // bad request
201
- if (e.status === 400 || e.status === 422) {
202
- throw e;
203
- }
204
-
205
- --retries;
206
-
207
- // without the query string: its values may hold ids or emails
208
- console.log(theURL.split('?')[0], e);
209
-
210
- if (retries <= 0) throw e;
211
-
212
- return local.onError(e, url, options0, retries, args);
213
- }
214
- }
215
- }
@@ -1,153 +0,0 @@
1
- import Fetcher from './fetcher.mjs';
2
-
3
- class OAuthFetcher extends Fetcher {
4
- oauth: any;
5
- _getToken: any;
6
- used: boolean = false;
7
- constructor({oauth, retry = 5, getToken, baseUrl, onResponse, customize}) {
8
- super({retry, baseUrl, onResponse, customize});
9
-
10
- this.oauth = oauth;
11
- this._getToken = getToken;
12
- }
13
-
14
- async __healthCheck() {
15
- if (this.used && !this.oauth.accessToken()) throw new Error('no access token');
16
- }
17
-
18
- async getToken(force) {
19
- var local = this,
20
- oauth = local.oauth;
21
-
22
- this.used = true;
23
-
24
- if (local._getToken) return local._getToken(force);
25
-
26
- if (!force && oauth.accessToken()) return oauth.accessToken();
27
-
28
- const refreshToken = oauth.refreshToken();
29
-
30
- try {
31
- if (!refreshToken) {
32
- throw new Error('have no access_token and no refresh_token');
33
- }
34
-
35
- const ret = await oauth.obtainViaRefreshToken(oauth.refreshToken());
36
-
37
- if (ret.access_token) {
38
- oauth.update(ret.access_token, ret.refresh_token);
39
-
40
- return ret.access_token;
41
- } else {
42
- throw new Error('could not obtain access token via refresh token');
43
- }
44
- } catch (e) {
45
- oauth.invalidate(e);
46
-
47
- throw e;
48
- }
49
- }
50
-
51
- async onError(e, url, options, retries, args, rateLimit) {
52
- var local = this;
53
-
54
- return new Promise((resolve, reject) => {
55
- setTimeout(
56
- async () => {
57
- try {
58
- resolve(
59
- await local.fetch(url, options, retries, {
60
- forceTokenRefresh: e.status === 401,
61
- })
62
- );
63
- } catch (e) {
64
- reject(e);
65
- }
66
- },
67
- rateLimit ? 10000 : 500
68
- );
69
- });
70
- }
71
-
72
- async periodicRefresh() {
73
- const local = this,
74
- oauth = local.oauth;
75
-
76
- console.log('refreshing oauth token, have token', !!oauth.refreshToken());
77
- if (!oauth.refreshToken()) return;
78
-
79
- await local.getToken(true);
80
-
81
- console.log('refreshed oauth token');
82
- }
83
-
84
- async customize(options: any, args: any = {}) {
85
- const local = this;
86
-
87
- if (this.customize0) await this.customize0(options, args);
88
-
89
- const token = await local.getToken(args.forceTokenRefresh);
90
-
91
- options.headers = {
92
- ...options.headers,
93
- Authorization: `Bearer ${token}`,
94
- };
95
- }
96
- }
97
-
98
- export class OAuth {
99
- _data: any;
100
- saveOAuthResult: any;
101
- obtainViaRefreshToken: any;
102
- clients: any[];
103
- constructor(data, saveOAuthResult, getRefreshToken) {
104
- this._data = data || {};
105
- this.saveOAuthResult = saveOAuthResult;
106
- this.obtainViaRefreshToken = getRefreshToken;
107
- this.clients = [];
108
- }
109
-
110
- data() {
111
- return this._data;
112
- }
113
-
114
- accessToken() {
115
- return this._data.access_token;
116
- }
117
-
118
- refreshToken() {
119
- return this._data.refresh_token;
120
- }
121
-
122
- async update(accessToken, refreshToken) {
123
- this._data.access_token = accessToken;
124
-
125
- if (refreshToken) {
126
- this._data.refresh_token = refreshToken;
127
- }
128
-
129
- await this.saveOAuthResult(this._data);
130
- }
131
-
132
- async periodicRefresh() {
133
- const clients = this.clients;
134
-
135
- console.log('refreshing oauth clients', clients.length);
136
-
137
- for (let i = 0; i < clients.length; ++i) {
138
- const client = clients[0];
139
-
140
- await client.periodicRefresh();
141
- }
142
- }
143
-
144
- async invalidate(err) {
145
- this._data.access_token = null;
146
- }
147
-
148
- getClient(arg: any = {}) {
149
- const client = new OAuthFetcher({...arg, oauth: this});
150
- this.clients.push(client);
151
- return client;
152
- }
153
- }
@@ -1,3 +0,0 @@
1
- import {Connector} from './connector/index.mjs';
2
-
3
- export {Connector};
@@ -1,52 +0,0 @@
1
- export const handlePacketError = (packet, e, transport) => {
2
- if (!packet.cb()) {
3
- console.dir({msg: 'packet error', e, packet}, {depth: null});
4
- return;
5
- }
6
-
7
- transport.send(transport.newPacket({c: packet.cb(), a: {error: '' + e}}));
8
- };
9
-
10
- export const reply = (arg, packet, transport) => {
11
- if (!packet.cb()) {
12
- console.dir({msg: 'cannot reply to packet without cb', arg, packet}, {depth: null});
13
- return;
14
- }
15
-
16
- transport.send(transport.newPacket({c: packet.cb(), a: {...arg}}));
17
- };
18
-
19
- export const unwrap0 = (ret, body, options) => {
20
- if (options?.bodyOnly === false) {
21
- return {status: ret.status, headers: ret.headers, body};
22
- } else {
23
- return body;
24
- }
25
- };
26
-
27
- export const unwrap = async (ret, options) => {
28
- if (options?.text) return unwrap0(ret, await ret.text(), options);
29
- if (options?.base64) {
30
- const base64 = Buffer.from(await ret.arrayBuffer()).toString('base64');
31
-
32
- return unwrap0(ret, base64, options);
33
- }
34
-
35
- if (options?.skipResponseBody) {
36
- return {status: ret.status, headers: ret.headers};
37
- }
38
-
39
- const text = await ret.text();
40
-
41
- try {
42
- return unwrap0(ret, JSON.parse(text), options);
43
- } catch (e) {
44
- throw e + ' ' + text;
45
- }
46
- };
47
-
48
- export const notEmpty = (what, name) => {
49
- if (!what?.trim()) throw new Error(`${name} cannot be empty`);
50
-
51
- return what;
52
- };
@@ -1,12 +0,0 @@
1
- import JWE from './index.mjs';
2
-
3
- const main = async () => {
4
- const jwe = new JWE({});
5
- await jwe.newPair();
6
-
7
- console.log('PRIVATE_KEY=' + (await jwe.exportPrivateAsBase64()));
8
- console.log('PUBLIC_KEY=' + (await jwe.exportPublicAsBase64()));
9
- };
10
-
11
- setTimeout(() => null, 100);
12
- main();
@@ -1,72 +0,0 @@
1
- import * as jose from 'jose';
2
-
3
- class JWE {
4
- issuer: string;
5
- algorithm: string;
6
- pair?: jose.GenerateKeyPairResult<jose.KeyLike>;
7
- constructor({algorithm = 'PS256'}) {
8
- this.issuer = 'home.aloma.io';
9
- this.algorithm = algorithm;
10
- }
11
-
12
- async newPair() {
13
- this.pair = await jose.generateKeyPair(this.algorithm);
14
- }
15
-
16
- async exportPair() {
17
- return {
18
- publicKey: await jose.exportSPKI(this.pair!.publicKey),
19
- privateKey: await jose.exportPKCS8(this.pair!.privateKey),
20
- };
21
- }
22
-
23
- async exportPrivateAsBase64() {
24
- const pair = await this.exportPair();
25
-
26
- return Buffer.from(pair.privateKey).toString('base64');
27
- }
28
-
29
- async exportPublicAsBase64() {
30
- const pair = await this.exportPair();
31
-
32
- return Buffer.from(pair.publicKey).toString('base64');
33
- }
34
-
35
- async importPair({publicKey, privateKey, algorithm}) {
36
- this.pair = {
37
- publicKey: await jose.importSPKI(publicKey, algorithm),
38
- privateKey: await jose.importPKCS8(privateKey, algorithm),
39
- };
40
- }
41
-
42
- async importBase64Pair({publicKey, privateKey, algorithm}) {
43
- this.importPair({
44
- publicKey: Buffer.from(publicKey, 'base64').toString(),
45
- privateKey: Buffer.from(privateKey, 'base64').toString(),
46
- algorithm,
47
- });
48
- }
49
-
50
- async encrypt(what, expiration = '7d', audience, algorithm = 'RSA-OAEP-256') {
51
- const item = new jose.EncryptJWT({_data: {...what}})
52
- .setProtectedHeader({alg: algorithm, enc: 'A256GCM'})
53
- .setIssuedAt()
54
- .setIssuer(this.issuer)
55
- .setAudience(audience);
56
-
57
- if (expiration && expiration !== 'none') item.setExpirationTime(expiration);
58
-
59
- return await item.encrypt(this.pair!.publicKey);
60
- }
61
-
62
- async decrypt(what, audience) {
63
- const {payload, protectedHeader} = await jose.jwtDecrypt(what, this.pair!.privateKey, {
64
- issuer: this.issuer,
65
- audience,
66
- });
67
-
68
- return payload._data;
69
- }
70
- }
71
-
72
- export default JWE;
@@ -1,109 +0,0 @@
1
- import C from './connection/constants.mjs';
2
- import JWE from '../util/jwe/index.mjs';
3
-
4
- class Config {
5
- constructor({
6
- registrationToken,
7
- version,
8
- name,
9
- id,
10
- endpoint,
11
- wsEndpoint,
12
- privateKey,
13
- publicKey,
14
- introspect,
15
- configSchema,
16
- icon,
17
- }) {
18
- this._token = null;
19
- this._registrationToken = registrationToken;
20
- this._version = version;
21
- this._name = name;
22
- this._endpoint = endpoint;
23
- this._wsEndpoint = wsEndpoint;
24
- this._id = id;
25
- this._data = {};
26
- this._privateKey = privateKey;
27
- this._publicKey = publicKey;
28
- this._jwe = new JWE({});
29
- this._introspect = introspect;
30
- this._configSchema = configSchema;
31
- this._icon = icon;
32
-
33
- if (!registrationToken) throw new Error('empty registration token (set env.REGISTRATION_TOKEN)');
34
- if (!endpoint) throw new Error('empty endpoint (set env.DEVICE_ENDPOINT)');
35
- if (!wsEndpoint) throw new Error('empty registration token (set env.WEBSOCKET_ENDPOINT)');
36
-
37
- if (!this._id || !this._version) throw new Error('need connector id and version');
38
- }
39
-
40
- async validateKeys(algorithm) {
41
- if (!this._privateKey || !this._publicKey) throw new Error('need private and public key');
42
-
43
- await this._jwe.importBase64Pair({
44
- publicKey: this._publicKey,
45
- privateKey: this._privateKey,
46
- algorithm,
47
- });
48
-
49
- return this._jwe;
50
- }
51
-
52
- data(what) {
53
- if (what) {
54
- this._data = what;
55
- }
56
-
57
- return this._data;
58
- }
59
-
60
- introspect() {
61
- return this._introspect();
62
- }
63
-
64
- configSchema() {
65
- return this._configSchema();
66
- }
67
-
68
- publicKey() {
69
- return this._publicKey;
70
- }
71
-
72
- id() {
73
- return this._id;
74
- }
75
-
76
- version() {
77
- return this._version;
78
- }
79
-
80
- name() {
81
- return this._name;
82
- }
83
-
84
- url() {
85
- return this._endpoint;
86
- }
87
-
88
- wsUrl() {
89
- return this._wsEndpoint;
90
- }
91
-
92
- registrationToken() {
93
- return this._registrationToken;
94
- }
95
-
96
- token() {
97
- return this._token;
98
- }
99
-
100
- icon() {
101
- return this._icon;
102
- }
103
-
104
- setToken(what) {
105
- this._token = what;
106
- }
107
- }
108
-
109
- export {Config};
@@ -1,25 +0,0 @@
1
- const AUTHORIZATION = 'Authorization';
2
-
3
- export default {
4
- augmentRequest: (what, config) => {
5
- what.headers = {
6
- ...what.headers,
7
- 'User-Agent': config.id() + '/' + config.version(),
8
- };
9
-
10
- what.headers[AUTHORIZATION] = `Connector ${config.token()}`;
11
-
12
- return what;
13
- },
14
-
15
- augmentRegistration: (what, config) => {
16
- what.headers = {
17
- ...what.headers,
18
- 'User-Agent': config.id() + '/' + config.version(),
19
- };
20
-
21
- what.headers[AUTHORIZATION] = `Connector ${config.registrationToken()}`;
22
-
23
- return what;
24
- },
25
- };
@@ -1,71 +0,0 @@
1
- import {Registration} from './registration.mjs';
2
- import C from './constants.mjs';
3
-
4
- class Connection {
5
- constructor({config, onStart}) {
6
- this.config = config;
7
- this.onStart = onStart;
8
- }
9
-
10
- async start() {
11
- var local = this,
12
- config = local.config;
13
-
14
- try {
15
- const response = await fetch(
16
- config.url() + 'connect',
17
- C.augmentRequest(
18
- {
19
- method: 'POST',
20
- body: JSON.stringify({}),
21
- headers: {'Content-Type': 'application/json'},
22
- signal: AbortSignal.timeout(60 * 1000),
23
- },
24
- config
25
- )
26
- );
27
-
28
- if (response.status === 401) {
29
- config.setToken(await new Registration(local.config).run());
30
-
31
- return await local.start();
32
- } else if (response.status === 200) {
33
- config.data(await response.json());
34
-
35
- await local.onStart(() => local.onDisconnect());
36
- } else {
37
- setTimeout(() => local.start(), 5000);
38
- }
39
- } catch (e) {
40
- console.log(e);
41
- setTimeout(() => local.start(), 5000);
42
- }
43
- }
44
-
45
- onDisconnect() {
46
- var local = this;
47
-
48
- setTimeout(() => local.start(), 5000);
49
- }
50
-
51
- async close() {
52
- try {
53
- await fetch(
54
- this.config.url() + 'disconnect',
55
- C.augmentRequest(
56
- {
57
- method: 'POST',
58
- body: JSON.stringify({}),
59
- headers: {'Content-Type': 'application/json'},
60
- signal: AbortSignal.timeout(60 * 1000),
61
- },
62
- this.config
63
- )
64
- );
65
- } catch (e) {
66
- // blank
67
- }
68
- }
69
- }
70
-
71
- export {Connection};