@friggframework/core 2.0.0--canary.744.e18e27f.0 → 2.0.0--canary.745.0209482d.0

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.
@@ -66,12 +66,11 @@ class IntegrationRepositoryMongo extends IntegrationRepositoryInterface {
66
66
  * @returns {Promise<Array>} Array of integration objects (possibly empty)
67
67
  */
68
68
  async findIntegrations({ type, status } = {}) {
69
- let where = {};
69
+ const where = {};
70
70
  if (type) {
71
- const ids = await this._findIdsByType(type, { status });
72
- if (ids.length === 0) return [];
73
- where = { id: { in: ids } };
74
- } else if (status) {
71
+ where.config = { path: ['type'], equals: type };
72
+ }
73
+ if (status) {
75
74
  where.status = status;
76
75
  }
77
76
 
@@ -94,28 +93,6 @@ class IntegrationRepositoryMongo extends IntegrationRepositoryInterface {
94
93
  }));
95
94
  }
96
95
 
97
- /**
98
- * Ids of the integrations whose config.type is `type`. Prisma's MongoDB
99
- * connector has no JSON path filter (a where on config.type throws), so
100
- * the filter runs as a raw query and returns the ids only.
101
- *
102
- * @param {string} type - Integration type (config.type)
103
- * @param {Object} [options]
104
- * @param {string} [options.status] - Integration status
105
- * @param {number} [options.limit] - Most ids to return
106
- * @returns {Promise<string[]>}
107
- * @private
108
- */
109
- async _findIdsByType(type, { status, limit } = {}) {
110
- const filter = { 'config.type': type };
111
- if (status) filter.status = status;
112
- const options = { projection: { _id: 1 } };
113
- if (limit) options.limit = limit;
114
-
115
- const docs = await this.prisma.integration.findRaw({ filter, options });
116
- return (docs ?? []).map(({ _id }) => String(_id?.$oid ?? _id));
117
- }
118
-
119
96
  /**
120
97
  * Find every integration in a report-shaped projection.
121
98
  *
@@ -176,13 +153,17 @@ class IntegrationRepositoryMongo extends IntegrationRepositoryInterface {
176
153
  * @returns {Promise<Object>} Integration object
177
154
  */
178
155
  async findIntegrationByName(name) {
179
- const [id] = await this._findIdsByType(name, { limit: 1 });
180
- const integration = id
181
- ? await this.prisma.integration.findUnique({
182
- where: { id },
183
- include: { entities: true },
184
- })
185
- : null;
156
+ const integration = await this.prisma.integration.findFirst({
157
+ where: {
158
+ config: {
159
+ path: ['type'],
160
+ equals: name,
161
+ },
162
+ },
163
+ include: {
164
+ entities: true,
165
+ },
166
+ });
186
167
 
187
168
  if (!integration) {
188
169
  throw new Error(`Integration with name ${name} not found`);
@@ -116,62 +116,6 @@ class OAuth2Requester extends Requester {
116
116
 
117
117
  /** @type {boolean} Whether this requester supports token refresh */
118
118
  this.isRefreshable = true;
119
-
120
- /**
121
- * @type {number} Refresh the access token before a request when it
122
- * expires within this many ms. 0 turns it off (the default). A
123
- * module opts in with `static refreshBeforeExpiryMs`; the
124
- * constructor param overrides the class value. Opt in only when the
125
- * provider's refresh token survives a refresh, and persist
126
- * `accessTokenExpire` in `apiPropertiesToPersist.credential` so a
127
- * new invocation knows the expiry.
128
- */
129
- const refreshBeforeExpiryMs =
130
- params?.refreshBeforeExpiryMs ??
131
- this.constructor.refreshBeforeExpiryMs ??
132
- 0;
133
- this.refreshBeforeExpiryMs =
134
- Number.isFinite(refreshBeforeExpiryMs) && refreshBeforeExpiryMs > 0
135
- ? refreshBeforeExpiryMs
136
- : 0;
137
- }
138
-
139
- /**
140
- * True when the module opted in (`refreshBeforeExpiryMs` > 0) and a
141
- * refresh token is held. Off for the `client_credentials` grant:
142
- * getTokenFromClientCredentials() reports any failure, a 503 too, as
143
- * invalid auth, which would disable a working credential. Without a
144
- * refresh token, the provider rejects the refresh, which would also mark
145
- * the credential invalid.
146
- *
147
- * @returns {boolean}
148
- */
149
- isProactiveRefreshEnabled() {
150
- if (!this.refreshBeforeExpiryMs) return false;
151
- if (this.grant_type === 'client_credentials') return false;
152
- return Boolean(this.refresh_token);
153
- }
154
-
155
- /**
156
- * True when proactive refresh is on and the access token expires within
157
- * `refreshBeforeExpiryMs`. `accessTokenExpire` can be a Date, or an ISO
158
- * string from the credential store. An unknown or unreadable expiry
159
- * returns false: the 401 path handles that token.
160
- *
161
- * @returns {boolean}
162
- */
163
- _isTokenExpiringSoon() {
164
- if (!this.isProactiveRefreshEnabled()) return false;
165
- if (!this.accessTokenExpire) return false;
166
- const expiresAt = new Date(this.accessTokenExpire).getTime();
167
- if (Number.isNaN(expiresAt)) return false;
168
- return expiresAt - Date.now() <= this.refreshBeforeExpiryMs;
169
- }
170
-
171
- /** True when the URL, without its query, is `tokenUri`. */
172
- _isTokenRequest(url) {
173
- if (!this.tokenUri || typeof url !== 'string') return false;
174
- return url.split('?')[0] === String(this.tokenUri).split('?')[0];
175
119
  }
176
120
 
177
121
  /**
@@ -33,11 +33,6 @@ function sanitizedCause(err) {
33
33
  }
34
34
  const MAX_AUTH_RETRIES = 3;
35
35
 
36
- // After a proactive refresh that failed, the requester waits this long
37
- // before it tries again. Without it, every request would call the token
38
- // endpoint while the endpoint is down.
39
- const PROACTIVE_REFRESH_COOLDOWN_MS = 60_000;
40
-
41
36
  // Hinted waits are bounded by time, but a provider that always answers with a
42
37
  // short Retry-After would still keep the request in a long loop.
43
38
  const MAX_HINTED_RETRIES = 10;
@@ -64,8 +59,6 @@ class Requester extends Delegate {
64
59
  // This counter increases when the tokens change. A stale 401 (the
65
60
  // token changed already) then retries and does not refresh again.
66
61
  this._authGeneration = 0;
67
- // No proactive refresh before this time. See _refreshIfExpiringSoon().
68
- this._proactiveRefreshNotBefore = 0;
69
62
  this.DLGT_INVALID_AUTH = 'INVALID_AUTH';
70
63
  this.delegateTypes.push(this.DLGT_INVALID_AUTH);
71
64
  this.agent = get(params, 'agent', null);
@@ -256,10 +249,6 @@ class Requester extends Delegate {
256
249
  encodedUrl += queryBuild.slice(0, -1);
257
250
  }
258
251
 
259
- if (attempt === 0) {
260
- await this._refreshIfExpiringSoon(url);
261
- }
262
-
263
252
  options.headers = await this.addAuthHeaders(options.headers);
264
253
 
265
254
  // A 401 that arrives after a concurrent refresh is stale. It is not
@@ -781,120 +770,6 @@ class Requester extends Delegate {
781
770
  return false;
782
771
  }
783
772
 
784
- /**
785
- * Refreshes the token before a request when _isTokenExpiringSoon()
786
- * says so. A request with a token that expired would get a 401, and
787
- * then a refresh and a retry: one failed call each time.
788
- *
789
- * A failure here does not fail the request. The request goes out with
790
- * the current token, and the 401 path stays the fallback. After a
791
- * failure, no proactive refresh runs for PROACTIVE_REFRESH_COOLDOWN_MS.
792
- * After a refresh whose new token still expires inside the window (no
793
- * `expires_in`, or a lifetime shorter than the window), the proactive
794
- * refresh is off for this instance. Without that, every request would
795
- * refresh.
796
- * Concurrent callers share one refresh through _refreshAuthOnce().
797
- *
798
- * @param {string} url - The request URL. A call to the token endpoint
799
- * itself never starts a proactive refresh.
800
- */
801
- async _refreshIfExpiringSoon(url) {
802
- if (this._isInsideRefreshFlow()) return;
803
- if (Date.now() < this._proactiveRefreshNotBefore) return;
804
- if (this._isTokenRequest(url)) return;
805
- if (!this._isTokenExpiringSoon()) return;
806
-
807
- const tokenBefore = this.access_token;
808
- let refreshed = false;
809
- try {
810
- refreshed = await this._refreshAuthOnce();
811
- } catch (error) {
812
- this.logger.warn(
813
- 'Proactive token refresh failed, sending the request with the current token',
814
- {
815
- eventName: `${this.logger.name}.proactive_refresh_failed`,
816
- statusCode: error?.statusCode,
817
- isRateLimited: Boolean(error?.isRateLimited),
818
- }
819
- );
820
- }
821
- if (refreshed) {
822
- if (this._isTokenExpiringSoon()) {
823
- // No expires_in, or a lifetime shorter than the window: the
824
- // new token always looks expiring, so a cooldown would only
825
- // space out a refresh on every request. Turn the proactive
826
- // refresh off for this instance. The 401 path stays.
827
- this.logger.warn(
828
- 'The refreshed token expires inside the proactive refresh window, proactive refresh is off for this instance',
829
- {
830
- eventName: `${this.logger.name}.proactive_refresh_window_too_long`,
831
- }
832
- );
833
- this._proactiveRefreshNotBefore = Infinity;
834
- }
835
- return;
836
- }
837
-
838
- this._proactiveRefreshNotBefore =
839
- Date.now() + PROACTIVE_REFRESH_COOLDOWN_MS;
840
- // A failed refresh can clear the token in memory before the token
841
- // request. The old token can still be valid for a few minutes.
842
- if (!this.access_token && tokenBefore) {
843
- this.access_token = tokenBefore;
844
- }
845
- }
846
-
847
- /**
848
- * Refreshes the token now, through the same path as the refresh after a
849
- * 401: one refresh at a time per instance (concurrent requests share
850
- * it), inside the refresh marker (so the refresh's own requests never
851
- * start a proactive refresh), and the auth generation advances. For
852
- * scheduled refreshers, such as the built-in `refresh-oauth-tokens`
853
- * admin script. Call refreshAuth() directly only from inside a refresh.
854
- *
855
- * @returns {Promise<boolean>} True if the instance holds a usable token.
856
- */
857
- refreshAuthNow() {
858
- return this._refreshAuthOnce();
859
- }
860
-
861
- /**
862
- * True when a scheduled refresher may refresh this instance's token
863
- * ahead of expiry. Off by default, for the same reason as
864
- * _isTokenExpiringSoon(). OAuth2Requester turns it on with
865
- * `refreshBeforeExpiryMs`.
866
- *
867
- * @returns {boolean}
868
- */
869
- isProactiveRefreshEnabled() {
870
- return false;
871
- }
872
-
873
- /**
874
- * Hook for requesters that know when their token expires. Return true
875
- * to refresh before the next request. Off by default, because a
876
- * provider with single-use refresh tokens must not spend one on a token
877
- * that still works. OAuth2Requester turns it on with
878
- * `refreshBeforeExpiryMs`.
879
- *
880
- * @returns {boolean}
881
- */
882
- _isTokenExpiringSoon() {
883
- return false;
884
- }
885
-
886
- /**
887
- * Hook: true when the URL is this requester's token endpoint. A token
888
- * request (code exchange, client credentials) must not first refresh
889
- * the old token.
890
- *
891
- * @param {string} _url
892
- * @returns {boolean}
893
- */
894
- _isTokenRequest(_url) {
895
- return false;
896
- }
897
-
898
773
  /** True while this instance runs its own refresh. */
899
774
  _isInsideRefreshFlow() {
900
775
  return refreshContext.getStore()?.requester === this;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@friggframework/core",
3
3
  "prettier": "@friggframework/prettier-config",
4
- "version": "2.0.0--canary.744.e18e27f.0",
4
+ "version": "2.0.0--canary.745.0209482d.0",
5
5
  "dependencies": {
6
6
  "@aws-sdk/client-apigatewaymanagementapi": "^3.588.0",
7
7
  "@aws-sdk/client-kms": "^3.588.0",
@@ -11,7 +11,7 @@
11
11
  "@aws-sdk/client-sqs": "^3.588.0",
12
12
  "@aws-sdk/client-ssm": "^3.588.0",
13
13
  "@aws-sdk/s3-request-presigner": "^3.588.0",
14
- "@friggframework/schemas": "2.0.0--canary.744.e18e27f.0",
14
+ "@friggframework/schemas": "2.0.0--canary.745.0209482d.0",
15
15
  "@hapi/boom": "^10.0.1",
16
16
  "@opentelemetry/api": "^1.9.1",
17
17
  "@opentelemetry/context-async-hooks": "^2.9.0",
@@ -49,9 +49,9 @@
49
49
  }
50
50
  },
51
51
  "devDependencies": {
52
- "@friggframework/eslint-config": "2.0.0--canary.744.e18e27f.0",
53
- "@friggframework/prettier-config": "2.0.0--canary.744.e18e27f.0",
54
- "@friggframework/test": "2.0.0--canary.744.e18e27f.0",
52
+ "@friggframework/eslint-config": "2.0.0--canary.745.0209482d.0",
53
+ "@friggframework/prettier-config": "2.0.0--canary.745.0209482d.0",
54
+ "@friggframework/test": "2.0.0--canary.745.0209482d.0",
55
55
  "@prisma/client": "^6.19.3",
56
56
  "@types/lodash": "4.17.15",
57
57
  "@typescript-eslint/eslint-plugin": "^8.0.0",
@@ -93,5 +93,5 @@
93
93
  "publishConfig": {
94
94
  "access": "public"
95
95
  },
96
- "gitHead": "e18e27f133f0afa7723d361b61ef8e7e80a830ef"
96
+ "gitHead": "0209482d12a8c95727025314afa125d406b56515"
97
97
  }
@@ -1,7 +1,16 @@
1
1
  declare module "@friggframework/encrypt" {
2
2
  export class Cryptor {
3
3
  constructor(params: { shouldUseAws?: boolean });
4
+ /** Encrypts as envelope v2 (AES-256-GCM, 256-bit data key). */
4
5
  encrypt(plaintext: string): Promise<string>;
6
+ /** Decrypts every envelope version this release knows (v2 and legacy v1). */
5
7
  decrypt(ciphertext: string): Promise<string>;
8
+ /**
9
+ * True when a stored value should be rewritten with encrypt(): a legacy v1
10
+ * value, or (AES mode) a v2 value under a key id other than AES_KEY_ID.
11
+ */
12
+ needsReencryption(value: unknown): boolean;
13
+ /** 'v2', or 'v1' while FRIGG_ENCRYPTION_WRITE_VERSION=v1 (upgrade deploy). */
14
+ getWriteVersion(): 'v1' | 'v2';
6
15
  }
7
16
  }
@@ -117,10 +117,6 @@ declare module "@friggframework/module-plugin" {
117
117
  _put(options: RequestOptions): Promise<any>;
118
118
  _delete(options: RequestOptions): Promise<any>;
119
119
  refreshAuth(): Promise<any>;
120
- /** Refreshes now through the shared refresh that the 401 retry uses. */
121
- refreshAuthNow(): Promise<boolean>;
122
- /** True when a scheduled refresher may refresh ahead of expiry. False by default. */
123
- isProactiveRefreshEnabled(): boolean;
124
120
  _adoptNewerCredential(): Promise<boolean>;
125
121
  }
126
122
 
@@ -207,17 +203,9 @@ declare module "@friggframework/module-plugin" {
207
203
  scope: string;
208
204
  state: any;
209
205
  username: string;
210
- /** Refresh before a request when the token expires within this many ms. 0 is off. */
211
- refreshBeforeExpiryMs: number;
212
- static refreshBeforeExpiryMs?: number;
213
206
 
214
207
  constructor(params: OAuth2RequesterConstructor);
215
208
 
216
- /** True when opted in, a refresh token is held, and the grant is not client_credentials. */
217
- isProactiveRefreshEnabled(): boolean;
218
- /** Refreshes now through the shared refresh that the 401 retry uses. */
219
- refreshAuthNow(): Promise<boolean>;
220
-
221
209
  addAuthHeaders(headers: object): Promise<object>;
222
210
  getAuthorizationUri(): string;
223
211
  getTokenFromClientCredentials(): Promise<Token>;
@@ -288,7 +276,6 @@ declare module "@friggframework/module-plugin" {
288
276
  username?: string;
289
277
  password?: string;
290
278
  state?: any;
291
- refreshBeforeExpiryMs?: number;
292
279
  };
293
280
 
294
281
  export const ModuleConstants: {