@aloma.io/integration-sdk 3.8.69 → 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 (117) 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 +22 -1
  4. package/build/internal/fetcher/fetcher.mjs +99 -14
  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/build/openapi-to-connector.mjs +5 -2
  11. package/package.json +9 -4
  12. package/.prettierrc.cjs +0 -8
  13. package/MULTI_RESOURCE_GUIDE.md +0 -220
  14. package/OPENAPI_TO_CONNECTOR.md +0 -346
  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 -166
  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 -1644
  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/fixtures/transform/basic/expected.json +0 -9
  67. package/test/fixtures/transform/basic/src/controller/abstract.mts +0 -5
  68. package/test/fixtures/transform/basic/src/controller/index.mts +0 -30
  69. package/test/fixtures/transform/basic/tsconfig.json +0 -1
  70. package/test/fixtures/transform/interface-param/src/controller/abstract.mts +0 -5
  71. package/test/fixtures/transform/interface-param/src/controller/index.mts +0 -12
  72. package/test/fixtures/transform/interface-param/tsconfig.json +0 -1
  73. package/test/fixtures/transform/overloads/expected.json +0 -6
  74. package/test/fixtures/transform/overloads/src/controller/abstract.mts +0 -5
  75. package/test/fixtures/transform/overloads/src/controller/index.mts +0 -11
  76. package/test/fixtures/transform/overloads/tsconfig.json +0 -1
  77. package/test/fixtures/transform/tdd-stub/expected.json +0 -8
  78. package/test/fixtures/transform/tdd-stub/src/controller/abstract.mts +0 -6
  79. package/test/fixtures/transform/tdd-stub/src/controller/index.mts +0 -204
  80. package/test/fixtures/transform/tdd-stub/tsconfig.json +0 -1
  81. package/test/fixtures/transform/two-exports/src/controller/abstract.mts +0 -5
  82. package/test/fixtures/transform/two-exports/src/controller/index.mts +0 -9
  83. package/test/fixtures/transform/two-exports/tsconfig.json +0 -1
  84. package/test/fixtures/transform/type-error/src/controller/abstract.mts +0 -5
  85. package/test/fixtures/transform/type-error/src/controller/index.mts +0 -7
  86. package/test/fixtures/transform/type-error/tsconfig.json +0 -1
  87. package/test/fixtures/transform/typed/expected.json +0 -8
  88. package/test/fixtures/transform/typed/src/controller/abstract.mts +0 -5
  89. package/test/fixtures/transform/typed/src/controller/index.mts +0 -13
  90. package/test/fixtures/transform/typed/tsconfig.json +0 -1
  91. package/test/fixtures/transform/visibility/expected.json +0 -9
  92. package/test/fixtures/transform/visibility/src/controller/abstract.mts +0 -5
  93. package/test/fixtures/transform/visibility/src/controller/index.mts +0 -19
  94. package/test/fixtures/transform/visibility/tsconfig.json +0 -1
  95. package/test/harness-connector-smoke.test.mjs +0 -72
  96. package/test/harness.test.mjs +0 -375
  97. package/test/nested-resolver.test.mjs +0 -184
  98. package/test/openapi-generator-bugs.test.mjs +0 -248
  99. package/test/openapi-identifier-sanitise.test.mjs +0 -69
  100. package/test/openapi-nested-paths.test.mjs +0 -100
  101. package/test/openapi-to-connector.test.mts +0 -225
  102. package/test/openapi-ts-compilation.test.mjs +0 -178
  103. package/test/scenarios/README.md +0 -148
  104. package/test/scenarios/complex/expected/controller.mts +0 -271
  105. package/test/scenarios/complex/expected/orders-resource.mts +0 -262
  106. package/test/scenarios/complex/expected/products-resource.mts +0 -237
  107. package/test/scenarios/complex/specs/orders.json +0 -362
  108. package/test/scenarios/complex/specs/products.json +0 -308
  109. package/test/scenarios/simple/expected-controller.mts +0 -60
  110. package/test/scenarios/simple/simple-api.json +0 -39
  111. package/test/scenarios.test.mts +0 -294
  112. package/test/transform.test.mjs +0 -68
  113. package/test/verify-scenarios.mjs +0 -298
  114. package/tools/mutation-run-entry.mjs +0 -52
  115. package/tools/mutation-run.mjs +0 -120
  116. package/tools/run-tests.mjs +0 -64
  117. package/tsconfig.json +0 -27
package/README.md CHANGED
@@ -162,9 +162,22 @@ Not covered: the Prometheus metrics server (fixed port 4050), process signal han
162
162
  environment variables and OAuth flows against a real provider. `connectorFromRuntimeContext` repeats the wiring of
163
163
  `RuntimeContext.start()`, so keep the two in step.
164
164
 
165
- SDK maintainers: `yarn test:harness` runs the harness tests (CI runs it on Node 18, 20, 22 and 24). `yarn test:mutation`
165
+ SDK maintainers: `yarn test:harness` runs the harness tests (CI runs it on Node 22, 24 and 26). `yarn test:mutation`
166
166
  applies 30+ deliberate bugs to the harness and the SDK handshake, dispatch and result paths and checks the tests
167
- catch each one; the result is recorded in `test/MUTATION.md`.
167
+ catch each one; the result table is printed to the log.
168
+
169
+ ## 🔁 Fetcher retries
170
+
171
+ `fetcher.fetch(url, options)` tries a request up to `retry` times in total (default 5).
172
+
173
+ - A 429 counts against the limit like any other retried failure. The wait before a retry is the vendor's `Retry-After`
174
+ header (seconds or an HTTP date) when present, at most 60 s; otherwise 10 s after a 429 and 500 ms after other failures.
175
+ - GET, HEAD, OPTIONS, PUT and DELETE are retried after a 5xx, a timeout or a network error. POST and PATCH are retried
176
+ only when the request sets `retryUnsafe: true`, for example `fetcher.fetch('/orders', {method: 'POST', body, retryUnsafe: true})`;
177
+ use it when the vendor treats a repeated request as the same request (an idempotency key, for instance).
178
+ - 4xx answers other than 408 and 429 are thrown at once (the OAuth client also retries a 401 with a refreshed token).
179
+ - A 200 answer whose body is not valid JSON is thrown as a `ResponseParseError` with the `status` and the first 200
180
+ characters of the body. Pass `text: true` to read a body as text.
168
181
 
169
182
  ## 📚 Documentation
170
183
 
@@ -1,4 +1,14 @@
1
1
  import { OAuth } from '../../../fetcher/oauth-fetcher.mjs';
2
+ // the "error" member of a token endpoint answer, when it is a plain code such as invalid_grant
3
+ const oauthErrorCode = (text) => {
4
+ try {
5
+ const code = JSON.parse(text)?.error;
6
+ return typeof code === 'string' && /^[A-Za-z0-9_.-]{1,64}$/.test(code) ? code : undefined;
7
+ }
8
+ catch {
9
+ return undefined;
10
+ }
11
+ };
2
12
  export const makeOAuth = async ({ config, transport, decrypted, dispatcher, }) => {
3
13
  const saveOAuthResult = async (what) => {
4
14
  const jwe = await config.validateKeys('RSA-OAEP-256');
@@ -44,16 +54,27 @@ export const makeOAuth = async ({ config, transport, decrypted, dispatcher, }) =
44
54
  const status = await response.status;
45
55
  const text = await response.text();
46
56
  if (status === 200) {
47
- return JSON.parse(text);
48
- }
49
- else {
50
- throw new Error('could not get refresh token ' + status + ' ' + text);
57
+ try {
58
+ return JSON.parse(text);
59
+ }
60
+ catch {
61
+ throw new Error('could not get refresh token ' + status + ' (answer is not JSON)');
62
+ }
51
63
  }
64
+ // only the status and the OAuth error code are kept; the body may repeat what was sent
65
+ const code = oauthErrorCode(text);
66
+ const message = 'could not get refresh token ' + status + (code ? ' ' + code : '');
67
+ const error = new Error(message);
68
+ // a refusal from the token endpoint is final: the same request would be refused again
69
+ if (status >= 400 && status < 500)
70
+ error.noRetry = true;
71
+ console.log(message);
72
+ throw error;
52
73
  };
53
74
  const theOAuth = dispatcher._oauth ? new OAuth(decrypted.oauthResult, saveOAuthResult, getRefreshToken) : null;
54
75
  if (theOAuth) {
55
76
  clearInterval(dispatcher._refreshOAuthToken);
56
- if (!(dispatcher._oauth.noPeriodicTokenRefresh === false)) {
77
+ if (dispatcher._oauth.noPeriodicTokenRefresh !== true) {
57
78
  dispatcher._refreshOAuthToken = setInterval(async () => {
58
79
  try {
59
80
  console.log('refreshing oauth token');
@@ -62,7 +83,7 @@ export const makeOAuth = async ({ config, transport, decrypted, dispatcher, }) =
62
83
  catch (e) {
63
84
  console.log('periodic refresh', e);
64
85
  }
65
- }, dispatcher._oauth.tokenRefreshPeriod || 4 * 60 * 60 * 15000);
86
+ }, dispatcher._oauth.tokenRefreshPeriod || 4 * 60 * 60 * 1000);
66
87
  }
67
88
  }
68
89
  return theOAuth;
@@ -1,4 +1,5 @@
1
1
  /// <reference types="node" resolution-mode="require"/>
2
+ /// <reference types="node" resolution-mode="require"/>
2
3
  /**
3
4
  * http request fetcher
4
5
  */
@@ -17,7 +18,15 @@ export default class Fetcher {
17
18
  });
18
19
  getToken(force: boolean): Promise<string>;
19
20
  protected customize(options?: {}, args?: {}): Promise<void>;
20
- protected onError(e: any, url: string, options: any, retries: number, args: any, rateLimit?: any): Promise<unknown>;
21
+ /**
22
+ * whether a failed attempt is tried again: 429 and 408 always (the vendor did not process the request);
23
+ * other 4xx never; a 5xx, a timeout or a network error for GET, HEAD, OPTIONS, PUT and DELETE, and for other
24
+ * methods only when the request sets retryUnsafe
25
+ */
26
+ protected retryable(e: any, options: any): boolean;
27
+ /** ms to wait before the next attempt: the vendor's Retry-After, else 10 s for a 429, else 500 ms */
28
+ protected waitBefore(e: any): number;
29
+ protected onError(e: any, url: string, options: any, retries: number, args: any, wait?: number): Promise<unknown>;
21
30
  /**
22
31
  * fetch data from a url
23
32
  * @param url url to fetch
@@ -41,5 +50,17 @@ export default class Fetcher {
41
50
  * request body like "hello world" or {hello: "world"}
42
51
  */
43
52
  body?: any;
53
+ /**
54
+ * query parameters like {limit: 10, properties: ["a", "b"]}, appended to the url;
55
+ * undefined and null are skipped, arrays become repeated keys, objects are refused
56
+ */
57
+ params?: {
58
+ [key: string]: any;
59
+ } | URLSearchParams;
60
+ /**
61
+ * retry a POST or PATCH (or any other method that is not GET, HEAD, OPTIONS, PUT or DELETE) after a 5xx,
62
+ * a timeout or a network error; off by default, because the vendor may already have processed the request
63
+ */
64
+ retryUnsafe?: boolean;
44
65
  }, retries?: number, args?: any): Promise<any>;
45
66
  }
@@ -1,4 +1,68 @@
1
1
  import { unwrap } from '../util/index.mjs';
2
+ class ParamsError extends Error {
3
+ }
4
+ /**
5
+ * build a query string from request params: undefined and null are skipped, arrays become repeated keys,
6
+ * objects are refused; values are encoded by URLSearchParams
7
+ */
8
+ const toQuery = (params) => {
9
+ if (params == null)
10
+ return '';
11
+ if (params instanceof URLSearchParams)
12
+ return params.toString();
13
+ if (typeof params !== 'object' || Array.isArray(params))
14
+ throw new ParamsError('params must be an object');
15
+ const query = new URLSearchParams();
16
+ const add = (key, value) => {
17
+ if (value == null)
18
+ return;
19
+ if (typeof value === 'object') {
20
+ throw new ParamsError(`params.${key} is an object; only strings, numbers, booleans and arrays of them are sent`);
21
+ }
22
+ query.append(key, String(value));
23
+ };
24
+ for (const [key, value] of Object.entries(params)) {
25
+ if (Array.isArray(value))
26
+ value.forEach((item) => add(key, item));
27
+ else
28
+ add(key, value);
29
+ }
30
+ return query.toString();
31
+ };
32
+ const withQuery = (url, query) => {
33
+ if (!query)
34
+ return url;
35
+ const hash = url.indexOf('#');
36
+ const base = hash < 0 ? url : url.slice(0, hash);
37
+ const sep = !base.includes('?') ? '?' : /[?&]$/.test(base) ? '' : '&';
38
+ return base + sep + query + (hash < 0 ? '' : url.slice(hash));
39
+ };
40
+ const REQUEST_TIMEOUT_MAX = 30 * 60 * 1000;
41
+ const RETRY_AFTER_MAX = 60 * 1000;
42
+ const RATE_LIMIT_WAIT = 10000;
43
+ const RETRY_WAIT = 500;
44
+ // methods that may be sent again after a 5xx, a timeout or a network error without the caller opting in
45
+ const REPEATABLE_METHODS = ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE'];
46
+ /**
47
+ * the wait in ms asked for by a Retry-After header (seconds or an HTTP date), capped at 60 s;
48
+ * undefined when the header is absent or not usable
49
+ */
50
+ const retryAfterMs = (value) => {
51
+ const text = value?.trim();
52
+ if (!text)
53
+ return undefined;
54
+ let ms;
55
+ if (/^\d+$/.test(text)) {
56
+ ms = Number(text) * 1000;
57
+ }
58
+ else if (/[a-z]/i.test(text) && !Number.isNaN(Date.parse(text))) {
59
+ ms = Math.max(0, Date.parse(text) - Date.now());
60
+ }
61
+ else {
62
+ return undefined;
63
+ }
64
+ return Math.min(ms, RETRY_AFTER_MAX);
65
+ };
2
66
  /**
3
67
  * http request fetcher
4
68
  */
@@ -21,7 +85,26 @@ export default class Fetcher {
21
85
  if (this.customize0)
22
86
  await this.customize0(options, args);
23
87
  }
24
- async onError(e, url, options, retries, args, rateLimit) {
88
+ /**
89
+ * whether a failed attempt is tried again: 429 and 408 always (the vendor did not process the request);
90
+ * other 4xx never; a 5xx, a timeout or a network error for GET, HEAD, OPTIONS, PUT and DELETE, and for other
91
+ * methods only when the request sets retryUnsafe
92
+ */
93
+ retryable(e, options) {
94
+ if (e.status === 429 || e.status === 408)
95
+ return true;
96
+ if (e.status != null && e.status < 500)
97
+ return false;
98
+ const method = String(options?.method || 'GET').toUpperCase();
99
+ return REPEATABLE_METHODS.includes(method) || options?.retryUnsafe === true;
100
+ }
101
+ /** ms to wait before the next attempt: the vendor's Retry-After, else 10 s for a 429, else 500 ms */
102
+ waitBefore(e) {
103
+ if (e.retryAfter != null)
104
+ return e.retryAfter;
105
+ return e.status === 429 ? RATE_LIMIT_WAIT : RETRY_WAIT;
106
+ }
107
+ async onError(e, url, options, retries, args, wait = RETRY_WAIT) {
25
108
  var local = this;
26
109
  return new Promise((resolve, reject) => {
27
110
  setTimeout(async () => {
@@ -31,7 +114,7 @@ export default class Fetcher {
31
114
  catch (e) {
32
115
  reject(e);
33
116
  }
34
- }, rateLimit ? 10000 : 500);
117
+ }, wait);
35
118
  });
36
119
  }
37
120
  /**
@@ -55,6 +138,8 @@ export default class Fetcher {
55
138
  url = options0.url;
56
139
  delete options0.url;
57
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));
58
143
  if (!options0?.headers || !options0?.headers?.Accept) {
59
144
  options0.headers = {
60
145
  ...options0.headers,
@@ -74,8 +159,9 @@ export default class Fetcher {
74
159
  options0.body = JSON.stringify(options0.body);
75
160
  }
76
161
  const timeout = Math.min(options0?.timeout || 30 * 60 * 1000, 30 * 60 * 1000);
77
- const ret = await fetch(theURL, {
78
- ...options0,
162
+ const { params, ...init } = options0;
163
+ const ret = await fetch(fullURL, {
164
+ ...init,
79
165
  signal: AbortSignal.timeout(timeout),
80
166
  });
81
167
  const status = await ret.status;
@@ -83,6 +169,7 @@ export default class Fetcher {
83
169
  const text = await ret.text();
84
170
  const e = new Error(status + ' ' + text);
85
171
  e.status = status;
172
+ e.retryAfter = retryAfterMs(ret.headers.get('retry-after'));
86
173
  throw e;
87
174
  }
88
175
  if (local.onResponse) {
@@ -91,22 +178,20 @@ export default class Fetcher {
91
178
  if (status === 204) {
92
179
  return { ok: true };
93
180
  }
94
- return unwrap(ret, options0);
181
+ return await unwrap(ret, options0);
95
182
  }
96
183
  catch (e) {
97
- // too many requests
98
- if (e.status === 429) {
99
- return local.onError(e, url, options0, retries, args, true);
100
- }
101
- // bad request
102
- if (e.status === 400 || e.status === 422) {
184
+ if (e instanceof ParamsError)
185
+ throw e;
186
+ // client errors other than 408 and 429, and unsafe methods without retryUnsafe
187
+ if (!local.retryable(e, options0))
103
188
  throw e;
104
- }
105
189
  --retries;
106
- console.log(theURL, e);
190
+ // without the query string: its values may hold ids or emails
191
+ console.log(theURL.split('?')[0], e);
107
192
  if (retries <= 0)
108
193
  throw e;
109
- return local.onError(e, url, options0, retries, args);
194
+ return local.onError(e, url, options0, retries, args, local.waitBefore(e));
110
195
  }
111
196
  }
112
197
  }
@@ -12,8 +12,14 @@ declare class OAuthFetcher extends Fetcher {
12
12
  customize: any;
13
13
  });
14
14
  __healthCheck(): Promise<void>;
15
- getToken(force: any): Promise<any>;
16
- onError(e: any, url: any, options: any, retries: any, args: any, rateLimit: any): Promise<unknown>;
15
+ /**
16
+ * the access token for a call
17
+ * @param force refresh the token even if one is stored
18
+ * @param staleToken the token the failed attempt was sent with; when another call has refreshed since, that token is used
19
+ */
20
+ getToken(force: any, staleToken?: string): Promise<any>;
21
+ protected retryable(e: any, options: any): boolean;
22
+ onError(e: any, url: any, options: any, retries: any, args: any, wait?: number): Promise<unknown>;
17
23
  periodicRefresh(): Promise<void>;
18
24
  customize(options: any, args?: any): Promise<void>;
19
25
  }
@@ -22,11 +28,18 @@ export declare class OAuth {
22
28
  saveOAuthResult: any;
23
29
  obtainViaRefreshToken: any;
24
30
  clients: any[];
31
+ private refreshing;
25
32
  constructor(data: any, saveOAuthResult: any, getRefreshToken: any);
26
33
  data(): any;
27
34
  accessToken(): any;
28
35
  refreshToken(): any;
29
36
  update(accessToken: any, refreshToken: any): Promise<void>;
37
+ /**
38
+ * exchange the refresh token for a new access token and store it; calls that arrive while an exchange is
39
+ * running share it
40
+ */
41
+ refreshAccessToken(): Promise<string>;
42
+ private exchange;
30
43
  periodicRefresh(): Promise<void>;
31
44
  invalidate(err: any): Promise<void>;
32
45
  getClient(arg?: any): OAuthFetcher;
@@ -12,45 +12,41 @@ class OAuthFetcher extends Fetcher {
12
12
  if (this.used && !this.oauth.accessToken())
13
13
  throw new Error('no access token');
14
14
  }
15
- async getToken(force) {
15
+ /**
16
+ * the access token for a call
17
+ * @param force refresh the token even if one is stored
18
+ * @param staleToken the token the failed attempt was sent with; when another call has refreshed since, that token is used
19
+ */
20
+ async getToken(force, staleToken) {
16
21
  var local = this, oauth = local.oauth;
17
22
  this.used = true;
18
23
  if (local._getToken)
19
24
  return local._getToken(force);
20
- if (!force && oauth.accessToken())
21
- return oauth.accessToken();
22
- const refreshToken = oauth.refreshToken();
23
- try {
24
- if (!refreshToken) {
25
- throw new Error('have no access_token and no refresh_token');
26
- }
27
- const ret = await oauth.obtainViaRefreshToken(oauth.refreshToken());
28
- if (ret.access_token) {
29
- oauth.update(ret.access_token, ret.refresh_token);
30
- return ret.access_token;
31
- }
32
- else {
33
- throw new Error('could not obtain access token via refresh token');
34
- }
35
- }
36
- catch (e) {
37
- oauth.invalidate(e);
38
- throw e;
39
- }
25
+ const current = oauth.accessToken();
26
+ if (current && (!force || (staleToken && current !== staleToken)))
27
+ return current;
28
+ return oauth.refreshAccessToken();
40
29
  }
41
- async onError(e, url, options, retries, args, rateLimit) {
30
+ // a 401 is retried with a refreshed token; an error that ends the refresh is not retried
31
+ retryable(e, options) {
32
+ if (e?.noRetry)
33
+ return false;
34
+ return e.status === 401 || super.retryable(e, options);
35
+ }
36
+ async onError(e, url, options, retries, args, wait = 500) {
42
37
  var local = this;
43
38
  return new Promise((resolve, reject) => {
44
39
  setTimeout(async () => {
45
40
  try {
46
41
  resolve(await local.fetch(url, options, retries, {
47
42
  forceTokenRefresh: e.status === 401,
43
+ staleToken: `${options?.headers?.Authorization || ''}`.replace(/^Bearer /, '') || undefined,
48
44
  }));
49
45
  }
50
46
  catch (e) {
51
47
  reject(e);
52
48
  }
53
- }, rateLimit ? 10000 : 500);
49
+ }, wait);
54
50
  });
55
51
  }
56
52
  async periodicRefresh() {
@@ -65,7 +61,7 @@ class OAuthFetcher extends Fetcher {
65
61
  const local = this;
66
62
  if (this.customize0)
67
63
  await this.customize0(options, args);
68
- const token = await local.getToken(args.forceTokenRefresh);
64
+ const token = await local.getToken(args.forceTokenRefresh, args.staleToken);
69
65
  options.headers = {
70
66
  ...options.headers,
71
67
  Authorization: `Bearer ${token}`,
@@ -77,6 +73,7 @@ export class OAuth {
77
73
  saveOAuthResult;
78
74
  obtainViaRefreshToken;
79
75
  clients;
76
+ refreshing = null;
80
77
  constructor(data, saveOAuthResult, getRefreshToken) {
81
78
  this._data = data || {};
82
79
  this.saveOAuthResult = saveOAuthResult;
@@ -99,13 +96,61 @@ export class OAuth {
99
96
  }
100
97
  await this.saveOAuthResult(this._data);
101
98
  }
99
+ /**
100
+ * exchange the refresh token for a new access token and store it; calls that arrive while an exchange is
101
+ * running share it
102
+ */
103
+ refreshAccessToken() {
104
+ return (this.refreshing ||= this.exchange().finally(() => {
105
+ this.refreshing = null;
106
+ }));
107
+ }
108
+ async exchange() {
109
+ const before = this.accessToken();
110
+ try {
111
+ const refreshToken = this.refreshToken();
112
+ if (!refreshToken) {
113
+ throw new Error('have no access_token and no refresh_token');
114
+ }
115
+ const ret = await this.obtainViaRefreshToken(refreshToken);
116
+ if (!ret.access_token) {
117
+ throw new Error('could not obtain access token via refresh token');
118
+ }
119
+ try {
120
+ await this.update(ret.access_token, ret.refresh_token);
121
+ }
122
+ catch (e) {
123
+ // the stored token is not repeated by a retry
124
+ if (e && typeof e === 'object')
125
+ e.noRetry = true;
126
+ throw e;
127
+ }
128
+ return ret.access_token;
129
+ }
130
+ catch (e) {
131
+ // a client error from the token endpoint ends the call; the same refresh token would be refused again
132
+ if (e?.status >= 400 && e.status < 500)
133
+ e.noRetry = true;
134
+ // a token that was stored while this exchange ran stays valid
135
+ if (this.accessToken() === before)
136
+ await this.invalidate(e);
137
+ throw e;
138
+ }
139
+ }
102
140
  async periodicRefresh() {
103
141
  const clients = this.clients;
104
142
  console.log('refreshing oauth clients', clients.length);
105
- for (let i = 0; i < clients.length; ++i) {
106
- const client = clients[0];
107
- await client.periodicRefresh();
143
+ let failure;
144
+ for (const client of clients) {
145
+ try {
146
+ await client.periodicRefresh();
147
+ }
148
+ catch (e) {
149
+ failure ||= e;
150
+ }
108
151
  }
152
+ if (failure)
153
+ throw failure;
109
154
  }
110
155
  async invalidate(err) {
111
156
  this._data.access_token = null;
@@ -1,5 +1,13 @@
1
1
  export declare const handlePacketError: (packet: any, e: any, transport: any) => void;
2
2
  export declare const reply: (arg: any, packet: any, transport: any) => void;
3
3
  export declare const unwrap0: (ret: any, body: any, options: any) => any;
4
+ /**
5
+ * a response whose body should be JSON but is not; carries the response status and at most the first 200 characters
6
+ * of the body
7
+ */
8
+ export declare class ResponseParseError extends Error {
9
+ status: number;
10
+ constructor(status: number, text: string);
11
+ }
4
12
  export declare const unwrap: (ret: any, options: any) => Promise<any>;
5
13
  export declare const notEmpty: (what: any, name: any) => any;
@@ -20,6 +20,18 @@ export const unwrap0 = (ret, body, options) => {
20
20
  return body;
21
21
  }
22
22
  };
23
+ /**
24
+ * a response whose body should be JSON but is not; carries the response status and at most the first 200 characters
25
+ * of the body
26
+ */
27
+ export class ResponseParseError extends Error {
28
+ status;
29
+ constructor(status, text) {
30
+ super(`invalid JSON in ${status} response: ${text.slice(0, 200)}`);
31
+ this.name = 'ResponseParseError';
32
+ this.status = status;
33
+ }
34
+ }
23
35
  export const unwrap = async (ret, options) => {
24
36
  if (options?.text)
25
37
  return unwrap0(ret, await ret.text(), options);
@@ -35,7 +47,7 @@ export const unwrap = async (ret, options) => {
35
47
  return unwrap0(ret, JSON.parse(text), options);
36
48
  }
37
49
  catch (e) {
38
- throw e + ' ' + text;
50
+ throw new ResponseParseError(ret.status, text);
39
51
  }
40
52
  };
41
53
  export const notEmpty = (what, name) => {
@@ -31,7 +31,7 @@ class JWE {
31
31
  };
32
32
  }
33
33
  async importBase64Pair({ publicKey, privateKey, algorithm }) {
34
- this.importPair({
34
+ await this.importPair({
35
35
  publicKey: Buffer.from(publicKey, 'base64').toString(),
36
36
  privateKey: Buffer.from(privateKey, 'base64').toString(),
37
37
  algorithm,
@@ -51,6 +51,8 @@ class JWE {
51
51
  const { payload, protectedHeader } = await jose.jwtDecrypt(what, this.pair.privateKey, {
52
52
  issuer: this.issuer,
53
53
  audience,
54
+ keyManagementAlgorithms: ['RSA-OAEP-256'],
55
+ contentEncryptionAlgorithms: ['A256GCM'],
54
56
  });
55
57
  return payload._data;
56
58
  }
@@ -97,10 +97,13 @@ export class OpenAPIToConnector {
97
97
  const validationResult = OpenAPISchema.safeParse(parsed);
98
98
  if (!validationResult.success) {
99
99
  // Check if the errors are just about missing 'type' fields in schemas
100
- const criticalErrors = validationResult.error.errors.filter((err) => {
100
+ // zod 4 reports .issues (zod 3's .errors is gone), and a missing field is an invalid_type issue whose message no
101
+ // longer reads 'Required'
102
+ const isMissing = (err) => err.message.includes('Required') || (err.code === 'invalid_type' && /received undefined/.test(err.message));
103
+ const criticalErrors = validationResult.error.issues.filter((err) => {
101
104
  const path = err.path.join('.');
102
105
  // Allow missing 'type' in schema definitions as many OpenAPI specs don't include it
103
- return !path.includes('components.schemas') || !err.message.includes('Required');
106
+ return !path.includes('components.schemas') || !isMissing(err);
104
107
  });
105
108
  if (criticalErrors.length > 0) {
106
109
  const errors = criticalErrors.map((err) => `${err.path.join('.')}: ${err.message}`).join(', ');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aloma.io/integration-sdk",
3
- "version": "3.8.69",
3
+ "version": "3.8.71",
4
4
  "description": "",
5
5
  "author": "aloma.io",
6
6
  "license": "Apache-2.0",
@@ -12,13 +12,18 @@
12
12
  "dev": "./node_modules/typescript/bin/tsc --watch",
13
13
  "build": "./node_modules/typescript/bin/tsc",
14
14
  "test": "node tools/run-tests.mjs",
15
- "test:harness": "./node_modules/mocha/bin/_mocha --exit \"test/harness*.test.mjs\"",
15
+ "test:harness": "./node_modules/mocha/bin/mocha.js --exit \"test/harness*.test.mjs\"",
16
16
  "test:mutation": "node tools/mutation-run.mjs",
17
17
  "test:scenarios": "node test/verify-scenarios.mjs",
18
18
  "test:all": "npm run test:scenarios",
19
19
  "format": "yarn prettier --write src/",
20
20
  "openapi-to-connector": "node ./build/openapi-to-connector.mjs"
21
21
  },
22
+ "files": [
23
+ "build/",
24
+ "template/",
25
+ "README.md"
26
+ ],
22
27
  "main": "./build/index.js",
23
28
  "exports": {
24
29
  ".": {
@@ -42,7 +47,7 @@
42
47
  "prom-client": "^15",
43
48
  "typescript": "^5",
44
49
  "ws": "^8",
45
- "zod": "^3"
50
+ "zod": "^4"
46
51
  },
47
52
  "optionalDependencies": {
48
53
  "bufferutil": "^4",
@@ -52,7 +57,7 @@
52
57
  "@types/js-yaml": "^4.0.9",
53
58
  "@types/mocha": "^10.0.6",
54
59
  "chai": "^4.3.10",
55
- "mocha": "^10",
60
+ "mocha": "12.0.3",
56
61
  "prettier": "^3",
57
62
  "ts-node": "^10.9.2"
58
63
  },
package/.prettierrc.cjs DELETED
@@ -1,8 +0,0 @@
1
- module.exports = {
2
- bracketSpacing: false,
3
- bracketSameLine: false,
4
- singleQuote: true,
5
- arrowParens: 'always', //x => x
6
- trailingComma: 'es5',
7
- printWidth: 120,
8
- };