@friggframework/core 2.0.0--canary.730.f2ba24a.0 → 2.0.0--canary.656.6eb85ab.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.
- package/CLAUDE.md +14 -42
- package/application/commands/README.md +11 -17
- package/application/commands/entity-commands.js +60 -18
- package/application/commands/integration-commands.js +0 -63
- package/core/CLAUDE.md +3 -1
- package/core/create-handler.js +3 -0
- package/core/index.js +6 -0
- package/core/invocation-deadline.js +91 -0
- package/core/invocation-scope.js +30 -24
- package/database/documentdb-encryption-service.js +33 -2
- package/database/documentdb-utils.js +1 -4
- package/database/encryption/README.md +3 -3
- package/database/encryption/encryption-schema-registry.js +29 -109
- package/database/encryption/field-encryption-service.js +16 -55
- package/database/encryption/prisma-encryption-extension.js +9 -6
- package/database/prisma.js +1 -10
- package/encrypt/Cryptor.js +38 -90
- package/errors/fetch-error.js +11 -18
- package/errors/index.js +2 -4
- package/errors/rate-limit-error.js +45 -0
- package/handlers/WEBHOOKS.md +0 -29
- package/handlers/app-definition-loader.js +2 -9
- package/handlers/app-handler-helpers.js +1 -12
- package/handlers/backend-utils.js +2 -1
- package/handlers/workers/integration-defined-workers.js +2 -0
- package/index.js +18 -2
- package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +13 -67
- package/integrations/integration-base.js +9 -52
- package/integrations/integration-router.js +22 -30
- package/integrations/repositories/integration-mapping-repository-documentdb.js +0 -50
- package/integrations/repositories/integration-mapping-repository-interface.js +0 -15
- package/integrations/repositories/integration-mapping-repository-mongo.js +0 -29
- package/integrations/repositories/integration-mapping-repository-postgres.js +0 -30
- package/integrations/repositories/integration-mapping-repository.js +0 -29
- package/integrations/repositories/integration-repository-documentdb.js +0 -32
- package/integrations/repositories/integration-repository-interface.js +0 -30
- package/integrations/repositories/integration-repository-mongo.js +1 -53
- package/integrations/repositories/integration-repository-postgres.js +0 -58
- package/integrations/repositories/process-repository-mongo.js +1 -1
- package/integrations/use-cases/create-integration.js +19 -57
- package/integrations/use-cases/delete-integration-for-user.js +11 -8
- package/integrations/use-cases/get-integration-instance.js +12 -12
- package/integrations/use-cases/update-integration.js +12 -12
- package/jest-setup.js +2 -13
- package/jest-teardown.js +2 -5
- package/jest.config.js +0 -4
- package/logs/serialize.js +15 -0
- package/modules/requester/rate-limit/index.js +4 -0
- package/modules/requester/rate-limit/parsers.js +245 -0
- package/modules/requester/rate-limit/policy.js +304 -0
- package/modules/requester/requester.js +187 -9
- package/modules/use-cases/get-entity-options-by-id.js +5 -7
- package/modules/use-cases/get-module.js +8 -29
- package/modules/use-cases/process-authorization-callback.js +27 -78
- package/modules/use-cases/refresh-entity-options.js +5 -7
- package/modules/use-cases/test-module-auth.js +5 -7
- package/modules/utils/map-module-dto.js +3 -5
- package/package.json +7 -10
- package/queues/queuer-util.js +5 -6
- package/token/repositories/token-repository-documentdb.js +1 -13
- package/token/repositories/token-repository-mongo.js +1 -13
- package/token/repositories/token-repository-postgres.js +1 -13
- package/types/core/index.d.ts +33 -0
- package/types/errors/index.d.ts +47 -0
- package/types/module-plugin/index.d.ts +43 -0
- package/user/tests/doubles/test-user-repository.js +1 -1
- package/user/use-cases/authenticate-user.js +7 -23
- package/user/use-cases/get-user-from-bearer-token.js +2 -7
- package/database/encryption/ciphertext-format.js +0 -24
- package/errors/mapping-already-exists-error.js +0 -14
- package/integrations/use-cases/add-entities-to-integration.js +0 -92
- package/integrations/use-cases/remove-entities-from-integration.js +0 -70
- package/integrations/utils/assert-entity-ids-input.js +0 -42
- package/jest.db.config.js +0 -23
- package/modules/use-cases/create-entity-from-credential.js +0 -105
- package/modules/utils/find-module-definition.js +0 -23
- package/modules/utils/to-credential-id.js +0 -14
|
@@ -1,13 +1,24 @@
|
|
|
1
1
|
const fetch = require('node-fetch');
|
|
2
2
|
const { AsyncLocalStorage } = require('async_hooks');
|
|
3
3
|
const { Delegate } = require('../../core');
|
|
4
|
-
const {
|
|
4
|
+
const {
|
|
5
|
+
invocationMaxInProcessWaitMs,
|
|
6
|
+
remainingInvocationMs,
|
|
7
|
+
} = require('../../core/invocation-deadline');
|
|
8
|
+
const { FetchError, RateLimitError } = require('../../errors');
|
|
5
9
|
const { get } = require('../../assertions');
|
|
6
10
|
const { getTelemetry } = require('../../telemetry/telemetry-runtime');
|
|
7
11
|
const { getLogger } = require('../../logs');
|
|
8
12
|
const { redactUrl } = require('../../logs/redact');
|
|
9
13
|
const { toSanitizedSurrogate } = require('../../logs/serialize');
|
|
10
14
|
const { getLoggerScope } = require('../../logs/context');
|
|
15
|
+
const {
|
|
16
|
+
computeScopeKey,
|
|
17
|
+
computeWaitMs,
|
|
18
|
+
inProcessBudgetMs,
|
|
19
|
+
readRateLimitPolicy,
|
|
20
|
+
resolveRateLimitHint,
|
|
21
|
+
} = require('./rate-limit');
|
|
11
22
|
|
|
12
23
|
const DEFAULT_REQUEST_TIMEOUT_MS = 60_000;
|
|
13
24
|
|
|
@@ -22,6 +33,10 @@ function sanitizedCause(err) {
|
|
|
22
33
|
}
|
|
23
34
|
const MAX_AUTH_RETRIES = 3;
|
|
24
35
|
|
|
36
|
+
// Hinted waits are bounded by time, but a provider that always answers with a
|
|
37
|
+
// short Retry-After would still keep the request in a long loop.
|
|
38
|
+
const MAX_HINTED_RETRIES = 10;
|
|
39
|
+
|
|
25
40
|
// This context marks the async call chain that holds the refresh slot, and
|
|
26
41
|
// names the requester that holds it. Token requests re-enter _rawRequest
|
|
27
42
|
// through this._post. A 401 from inside that chain must fail fast: if it
|
|
@@ -34,6 +49,8 @@ class Requester extends Delegate {
|
|
|
34
49
|
constructor(params) {
|
|
35
50
|
super(params);
|
|
36
51
|
this.backOff = get(params, 'backOff', [1, 3, 10, 30, 60, 180]);
|
|
52
|
+
this._rateLimitPolicy = readRateLimitPolicy(this.constructor);
|
|
53
|
+
this._random = params?.random ?? Math.random;
|
|
37
54
|
this.isRefreshable = false;
|
|
38
55
|
this.refreshCount = 0;
|
|
39
56
|
this.authGraceRetryCount = 0;
|
|
@@ -211,9 +228,16 @@ class Requester extends Delegate {
|
|
|
211
228
|
* @param {Object} options - Fetch options, as built by `_request`.
|
|
212
229
|
* @param {number} attempt - 0-based count of retries already made for
|
|
213
230
|
* this call. Indexes `this.backOff` for the next delay and is passed
|
|
214
|
-
* back in on each recursive retry.
|
|
231
|
+
* back in on each recursive retry. A hinted retry leaves it unchanged.
|
|
232
|
+
* @param {{ waitedMs: number, retries: number }} hinted - The time slept
|
|
233
|
+
* and the retries made for rate-limit hints, for the whole call.
|
|
215
234
|
*/
|
|
216
|
-
async _rawRequest(
|
|
235
|
+
async _rawRequest(
|
|
236
|
+
url,
|
|
237
|
+
options,
|
|
238
|
+
attempt = 0,
|
|
239
|
+
hinted = { waitedMs: 0, retries: 0 }
|
|
240
|
+
) {
|
|
217
241
|
let encodedUrl = encodeURI(url);
|
|
218
242
|
if (options.query) {
|
|
219
243
|
let queryBuild = '?';
|
|
@@ -279,7 +303,7 @@ class Requester extends Delegate {
|
|
|
279
303
|
clearRequestTimer();
|
|
280
304
|
const delay = this.backOff[attempt] * 1000;
|
|
281
305
|
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
282
|
-
return this._rawRequest(url, options, attempt + 1);
|
|
306
|
+
return this._rawRequest(url, options, attempt + 1, hinted);
|
|
283
307
|
}
|
|
284
308
|
const fetchError = await FetchError.create({
|
|
285
309
|
resource: encodedUrl,
|
|
@@ -298,15 +322,41 @@ class Requester extends Delegate {
|
|
|
298
322
|
|
|
299
323
|
const { status } = response;
|
|
300
324
|
|
|
325
|
+
const throttle = await this._detectThrottle(
|
|
326
|
+
response,
|
|
327
|
+
status,
|
|
328
|
+
attempt
|
|
329
|
+
);
|
|
330
|
+
const hintedDelayMs = await this._hintedRetryDelayMs({
|
|
331
|
+
throttle,
|
|
332
|
+
status,
|
|
333
|
+
attempt,
|
|
334
|
+
hinted,
|
|
335
|
+
encodedUrl,
|
|
336
|
+
options,
|
|
337
|
+
response,
|
|
338
|
+
timeoutMs,
|
|
339
|
+
});
|
|
340
|
+
if (hintedDelayMs !== null) {
|
|
341
|
+
clearRequestTimer();
|
|
342
|
+
await new Promise((resolve) =>
|
|
343
|
+
setTimeout(resolve, hintedDelayMs)
|
|
344
|
+
);
|
|
345
|
+
return this._rawRequest(url, options, attempt, {
|
|
346
|
+
waitedMs: hinted.waitedMs + hintedDelayMs,
|
|
347
|
+
retries: hinted.retries + 1,
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
|
|
301
351
|
// If the status is retriable and there are back off requests left, retry the request
|
|
302
352
|
if (
|
|
303
|
-
(
|
|
353
|
+
(throttle?.throttled || status >= 500) &&
|
|
304
354
|
attempt < this.backOff.length
|
|
305
355
|
) {
|
|
306
356
|
clearRequestTimer();
|
|
307
357
|
const delay = this.backOff[attempt] * 1000;
|
|
308
358
|
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
309
|
-
return this._rawRequest(url, options, attempt + 1);
|
|
359
|
+
return this._rawRequest(url, options, attempt + 1, hinted);
|
|
310
360
|
}
|
|
311
361
|
|
|
312
362
|
if (status === 401) {
|
|
@@ -327,7 +377,7 @@ class Requester extends Delegate {
|
|
|
327
377
|
// This request did not try the current token. Retry with
|
|
328
378
|
// it. Do not spend one more provider-side rotation.
|
|
329
379
|
clearRequestTimer();
|
|
330
|
-
return this._rawRequest(url, options, attempt + 1);
|
|
380
|
+
return this._rawRequest(url, options, attempt + 1, hinted);
|
|
331
381
|
}
|
|
332
382
|
|
|
333
383
|
if (!this.isRefreshable) {
|
|
@@ -344,7 +394,12 @@ class Requester extends Delegate {
|
|
|
344
394
|
await new Promise((resolve) =>
|
|
345
395
|
setTimeout(resolve, delay)
|
|
346
396
|
);
|
|
347
|
-
return this._rawRequest(
|
|
397
|
+
return this._rawRequest(
|
|
398
|
+
url,
|
|
399
|
+
options,
|
|
400
|
+
attempt + 1,
|
|
401
|
+
hinted
|
|
402
|
+
);
|
|
348
403
|
}
|
|
349
404
|
|
|
350
405
|
throw await this._invalidateAuth(
|
|
@@ -377,7 +432,7 @@ class Requester extends Delegate {
|
|
|
377
432
|
const refreshSucceeded = await this._refreshAuthOnce();
|
|
378
433
|
if (refreshSucceeded) {
|
|
379
434
|
clearRequestTimer();
|
|
380
|
-
return this._rawRequest(url, options, attempt + 1);
|
|
435
|
+
return this._rawRequest(url, options, attempt + 1, hinted);
|
|
381
436
|
}
|
|
382
437
|
|
|
383
438
|
throw await this._invalidateAuth(encodedUrl, options, response);
|
|
@@ -392,6 +447,7 @@ class Requester extends Delegate {
|
|
|
392
447
|
resource: encodedUrl,
|
|
393
448
|
init: options,
|
|
394
449
|
response,
|
|
450
|
+
responseBody: throttle?.responseBody,
|
|
395
451
|
});
|
|
396
452
|
throw this._maybeFlagTimeoutDuringBodyRead(
|
|
397
453
|
fetchError,
|
|
@@ -421,6 +477,128 @@ class Requester extends Delegate {
|
|
|
421
477
|
}
|
|
422
478
|
}
|
|
423
479
|
|
|
480
|
+
async _hintedRetryDelayMs({
|
|
481
|
+
throttle,
|
|
482
|
+
status,
|
|
483
|
+
attempt,
|
|
484
|
+
hinted,
|
|
485
|
+
encodedUrl,
|
|
486
|
+
options,
|
|
487
|
+
response,
|
|
488
|
+
timeoutMs,
|
|
489
|
+
}) {
|
|
490
|
+
if (!throttle?.throttled || throttle.hint.source === 'backoff') {
|
|
491
|
+
return null;
|
|
492
|
+
}
|
|
493
|
+
const { hint } = throttle;
|
|
494
|
+
const untimed = hint.waitMs === undefined;
|
|
495
|
+
const mayWait =
|
|
496
|
+
this.backOff.length > 0 && hinted.retries < MAX_HINTED_RETRIES;
|
|
497
|
+
const budgetMs = mayWait
|
|
498
|
+
? inProcessBudgetMs({
|
|
499
|
+
maxInProcessWaitMs: invocationMaxInProcessWaitMs(),
|
|
500
|
+
requestTimeoutMs: this.requestTimeoutMs,
|
|
501
|
+
remainingMs: remainingInvocationMs(),
|
|
502
|
+
waitedMs: hinted.waitedMs,
|
|
503
|
+
})
|
|
504
|
+
: 0;
|
|
505
|
+
const { waitMs, fits } = untimed
|
|
506
|
+
? { waitMs: undefined, fits: false }
|
|
507
|
+
: computeWaitMs({
|
|
508
|
+
hint,
|
|
509
|
+
policy: this._rateLimitPolicy,
|
|
510
|
+
budgetMs,
|
|
511
|
+
random: this._random,
|
|
512
|
+
});
|
|
513
|
+
if (fits) {
|
|
514
|
+
this._logRateLimited({
|
|
515
|
+
status,
|
|
516
|
+
hint,
|
|
517
|
+
waitMs,
|
|
518
|
+
attempt,
|
|
519
|
+
waitedMs: hinted.waitedMs,
|
|
520
|
+
});
|
|
521
|
+
return waitMs;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
this._logRequestFailed(encodedUrl, options, status);
|
|
525
|
+
const rateLimitError = await RateLimitError.create({
|
|
526
|
+
resource: encodedUrl,
|
|
527
|
+
init: options,
|
|
528
|
+
response,
|
|
529
|
+
responseBody: throttle.responseBody,
|
|
530
|
+
hint,
|
|
531
|
+
waitMs,
|
|
532
|
+
module: this._telemetryModuleLabel(),
|
|
533
|
+
scopeKey: computeScopeKey(this._rateLimitPolicy, this),
|
|
534
|
+
});
|
|
535
|
+
throw this._maybeFlagTimeoutDuringBodyRead(rateLimitError, timeoutMs);
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
async _detectThrottle(response, status, attempt) {
|
|
539
|
+
const policy = this._rateLimitPolicy;
|
|
540
|
+
const canClassify =
|
|
541
|
+
typeof policy?.classify === 'function' &&
|
|
542
|
+
status >= 400 &&
|
|
543
|
+
status !== 401;
|
|
544
|
+
if (status !== 429 && !canClassify) return null;
|
|
545
|
+
|
|
546
|
+
let responseBody;
|
|
547
|
+
let body;
|
|
548
|
+
if (canClassify) {
|
|
549
|
+
({ text: responseBody, json: body } =
|
|
550
|
+
await this._readBodyForClassify(response));
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
const hint = resolveRateLimitHint(
|
|
554
|
+
policy,
|
|
555
|
+
{ status, headers: response.headers, body },
|
|
556
|
+
{
|
|
557
|
+
attempt,
|
|
558
|
+
backOff: this.backOff,
|
|
559
|
+
now: Date.now(),
|
|
560
|
+
onClassifyError: (error) =>
|
|
561
|
+
this._logClassifyFailed(status, error),
|
|
562
|
+
}
|
|
563
|
+
);
|
|
564
|
+
return { throttled: Boolean(hint), hint, responseBody };
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
async _readBodyForClassify(response) {
|
|
568
|
+
if (response.bodyUsed || typeof response.text !== 'function') {
|
|
569
|
+
return {};
|
|
570
|
+
}
|
|
571
|
+
const text = await response.text();
|
|
572
|
+
try {
|
|
573
|
+
return { text, json: JSON.parse(text) };
|
|
574
|
+
} catch {
|
|
575
|
+
return { text };
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
_logRateLimited({ status, hint, waitMs, attempt, waitedMs }) {
|
|
580
|
+
const logger = this.logger;
|
|
581
|
+
logger.trace('Rate limited', {
|
|
582
|
+
eventName: `${logger.name}.rate_limited`,
|
|
583
|
+
statusCode: status,
|
|
584
|
+
waitMs,
|
|
585
|
+
retryAt: new Date(Date.now() + waitMs).toISOString(),
|
|
586
|
+
reason: hint.reason,
|
|
587
|
+
hintSource: hint.source,
|
|
588
|
+
attempt,
|
|
589
|
+
waitedMs,
|
|
590
|
+
});
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
_logClassifyFailed(status, error) {
|
|
594
|
+
const logger = this.logger;
|
|
595
|
+
logger.warn('Rate limit classifier failed', {
|
|
596
|
+
eventName: `${logger.name}.rate_limit_classify_failed`,
|
|
597
|
+
statusCode: status,
|
|
598
|
+
error,
|
|
599
|
+
});
|
|
600
|
+
}
|
|
601
|
+
|
|
424
602
|
_logRequestFailed(encodedUrl, options, status) {
|
|
425
603
|
const logger = this.logger;
|
|
426
604
|
if (!logger.isLevelEnabled('DEBUG')) return;
|
|
@@ -1,7 +1,4 @@
|
|
|
1
1
|
const { Module } = require('../module');
|
|
2
|
-
const {
|
|
3
|
-
findModuleDefinitionForEntity,
|
|
4
|
-
} = require('../utils/find-module-definition');
|
|
5
2
|
|
|
6
3
|
class GetEntityOptionsById {
|
|
7
4
|
/**
|
|
@@ -48,10 +45,11 @@ class GetEntityOptionsById {
|
|
|
48
45
|
}
|
|
49
46
|
|
|
50
47
|
const entityType = entity.moduleName;
|
|
51
|
-
const moduleDefinition =
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
48
|
+
const moduleDefinition = this.moduleDefinitions.find((def) => {
|
|
49
|
+
const modelName =
|
|
50
|
+
Module.getEntityModelFromDefinition(def).modelName;
|
|
51
|
+
return entityType === modelName;
|
|
52
|
+
});
|
|
55
53
|
|
|
56
54
|
if (!moduleDefinition) {
|
|
57
55
|
throw new Error(
|
|
@@ -1,7 +1,4 @@
|
|
|
1
1
|
const { Module } = require('../module');
|
|
2
|
-
const {
|
|
3
|
-
findModuleDefinitionForEntity,
|
|
4
|
-
} = require('../utils/find-module-definition');
|
|
5
2
|
|
|
6
3
|
class GetModule {
|
|
7
4
|
constructor({ moduleRepository, moduleDefinitions }) {
|
|
@@ -45,10 +42,10 @@ class GetModule {
|
|
|
45
42
|
}
|
|
46
43
|
|
|
47
44
|
const entityType = entity.moduleName;
|
|
48
|
-
const moduleDefinition =
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
);
|
|
45
|
+
const moduleDefinition = this.moduleDefinitions.find((def) => {
|
|
46
|
+
const modelName = Module.getEntityModelFromDefinition(def).modelName;
|
|
47
|
+
return entityType === modelName;
|
|
48
|
+
});
|
|
52
49
|
|
|
53
50
|
if (!moduleDefinition) {
|
|
54
51
|
throw new Error(
|
|
@@ -62,33 +59,15 @@ class GetModule {
|
|
|
62
59
|
definition: moduleDefinition,
|
|
63
60
|
});
|
|
64
61
|
|
|
65
|
-
//
|
|
66
|
-
// the response names it and says whether it still works, as the v2
|
|
67
|
-
// entity DTO does.
|
|
68
|
-
const credential = module.credential;
|
|
69
|
-
const credentialId =
|
|
70
|
-
credential && typeof credential === 'object'
|
|
71
|
-
? credential.id
|
|
72
|
-
: credential;
|
|
73
|
-
const ownerId = module.entity.userId ?? module.entity.user;
|
|
62
|
+
// todo: this properties should be methods in the Module class
|
|
74
63
|
return {
|
|
75
64
|
id: module.entity.id,
|
|
76
65
|
name: module.entity.name,
|
|
77
66
|
moduleName: module.entity.moduleName,
|
|
78
|
-
|
|
79
|
-
credentialId === undefined || credentialId === null
|
|
80
|
-
? null
|
|
81
|
-
: String(credentialId),
|
|
82
|
-
authIsValid:
|
|
83
|
-
typeof credential?.authIsValid === 'boolean'
|
|
84
|
-
? credential.authIsValid
|
|
85
|
-
: null,
|
|
67
|
+
credential: module.credential,
|
|
86
68
|
externalId: module.entity.externalId,
|
|
87
|
-
userId:
|
|
88
|
-
|
|
89
|
-
? null
|
|
90
|
-
: String(ownerId),
|
|
91
|
-
};
|
|
69
|
+
userId: module.entity.user.toString(),
|
|
70
|
+
}
|
|
92
71
|
}
|
|
93
72
|
}
|
|
94
73
|
|
|
@@ -1,8 +1,5 @@
|
|
|
1
1
|
const { Module } = require('../module');
|
|
2
2
|
const { ModuleConstants } = require('../ModuleConstants');
|
|
3
|
-
const { getLogger } = require('../../logs');
|
|
4
|
-
|
|
5
|
-
const log = getLogger('frigg.modules.authorization_callback');
|
|
6
3
|
|
|
7
4
|
// Statuses considered "broken" for an integration whose credentials have just
|
|
8
5
|
// been successfully re-authorized. Both ERROR (system-driven auth failure) and
|
|
@@ -31,12 +28,10 @@ class ProcessAuthorizationCallback {
|
|
|
31
28
|
}
|
|
32
29
|
|
|
33
30
|
async execute(userId, entityType, params) {
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
userId
|
|
37
|
-
|
|
38
|
-
hasCode: Boolean(params && params.code),
|
|
39
|
-
});
|
|
31
|
+
const hasCode = Boolean(params && params.code);
|
|
32
|
+
console.log(
|
|
33
|
+
`[Frigg] processAuthorizationCallback start userId=${userId} entityType=${entityType} hasCode=${hasCode}`
|
|
34
|
+
);
|
|
40
35
|
|
|
41
36
|
const moduleDefinition = this.moduleDefinitions.find((def) => {
|
|
42
37
|
return entityType === def.moduleName;
|
|
@@ -63,11 +58,9 @@ class ProcessAuthorizationCallback {
|
|
|
63
58
|
: null;
|
|
64
59
|
|
|
65
60
|
if (existingEntity) {
|
|
66
|
-
log
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
credentialId: existingEntity.credential?.id,
|
|
70
|
-
});
|
|
61
|
+
console.log(
|
|
62
|
+
`[Frigg] processAuthorizationCallback found existing entity id=${existingEntity.id} credentialId=${existingEntity.credential?.id}`
|
|
63
|
+
);
|
|
71
64
|
}
|
|
72
65
|
|
|
73
66
|
const module = new Module({
|
|
@@ -76,26 +69,15 @@ class ProcessAuthorizationCallback {
|
|
|
76
69
|
definition: moduleDefinition,
|
|
77
70
|
});
|
|
78
71
|
|
|
79
|
-
const authType = module.apiClass.requesterType;
|
|
80
|
-
log.debug('Module created', {
|
|
81
|
-
eventName: `${log.name}.module_created`,
|
|
82
|
-
moduleName: module.getName(),
|
|
83
|
-
authType,
|
|
84
|
-
});
|
|
85
|
-
|
|
86
72
|
let tokenResponse;
|
|
87
|
-
if (
|
|
88
|
-
log.debug('Exchanging authorization code for token', {
|
|
89
|
-
eventName: `${log.name}.token_exchanging`,
|
|
90
|
-
});
|
|
73
|
+
if (module.apiClass.requesterType === ModuleConstants.authType.oauth2) {
|
|
91
74
|
tokenResponse = await moduleDefinition.requiredAuthMethods.getToken(
|
|
92
75
|
module.api,
|
|
93
76
|
params
|
|
94
77
|
);
|
|
95
|
-
log
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
});
|
|
78
|
+
console.log(
|
|
79
|
+
`[Frigg] processAuthorizationCallback OAuth getToken complete userId=${userId} entityType=${entityType}`
|
|
80
|
+
);
|
|
99
81
|
// Belt-and-suspenders: persist tokens explicitly here rather than
|
|
100
82
|
// relying solely on the DLGT_TOKEN_UPDATE notification chain
|
|
101
83
|
// inside setTokens. The notification path remains in place but
|
|
@@ -104,9 +86,6 @@ class ProcessAuthorizationCallback {
|
|
|
104
86
|
// OAuth flow appears to succeed.
|
|
105
87
|
await this.onTokenUpdate(module, moduleDefinition, userId);
|
|
106
88
|
} else {
|
|
107
|
-
log.debug('Setting auth params', {
|
|
108
|
-
eventName: `${log.name}.auth_params_setting`,
|
|
109
|
-
});
|
|
110
89
|
tokenResponse =
|
|
111
90
|
await moduleDefinition.requiredAuthMethods.setAuthParams(
|
|
112
91
|
module.api,
|
|
@@ -115,24 +94,15 @@ class ProcessAuthorizationCallback {
|
|
|
115
94
|
await this.onTokenUpdate(module, moduleDefinition, userId);
|
|
116
95
|
}
|
|
117
96
|
|
|
118
|
-
log
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
authIsValid: module.credential?.authIsValid,
|
|
122
|
-
});
|
|
97
|
+
console.log(
|
|
98
|
+
`[Frigg] processAuthorizationCallback credential persisted credentialId=${module.credential?.id} authIsValid=${module.credential?.authIsValid}`
|
|
99
|
+
);
|
|
123
100
|
|
|
124
|
-
log.debug('Testing auth', { eventName: `${log.name}.auth_testing` });
|
|
125
101
|
const authRes = await module.testAuth();
|
|
126
102
|
if (!authRes) {
|
|
127
103
|
throw new Error('Authorization failed');
|
|
128
104
|
}
|
|
129
|
-
log.debug('Auth test passed', {
|
|
130
|
-
eventName: `${log.name}.auth_test_passed`,
|
|
131
|
-
});
|
|
132
105
|
|
|
133
|
-
log.debug('Fetching entity details', {
|
|
134
|
-
eventName: `${log.name}.entity_details_fetching`,
|
|
135
|
-
});
|
|
136
106
|
const entityDetails =
|
|
137
107
|
await moduleDefinition.requiredAuthMethods.getEntityDetails(
|
|
138
108
|
module.api,
|
|
@@ -140,29 +110,17 @@ class ProcessAuthorizationCallback {
|
|
|
140
110
|
tokenResponse,
|
|
141
111
|
userId
|
|
142
112
|
);
|
|
143
|
-
log.debug('Entity details received', {
|
|
144
|
-
eventName: `${log.name}.entity_details_received`,
|
|
145
|
-
externalId: entityDetails.identifiers?.externalId,
|
|
146
|
-
});
|
|
147
113
|
|
|
148
114
|
Object.assign(
|
|
149
115
|
entityDetails.details,
|
|
150
116
|
module.apiParamsFromEntity(module.api)
|
|
151
117
|
);
|
|
152
118
|
|
|
153
|
-
log.debug('Finding or creating entity', {
|
|
154
|
-
eventName: `${log.name}.entity_resolving`,
|
|
155
|
-
});
|
|
156
119
|
const persistedEntity = await this.findOrCreateEntity(
|
|
157
120
|
entityDetails,
|
|
158
121
|
entityType,
|
|
159
122
|
module.credential.id
|
|
160
123
|
);
|
|
161
|
-
log.debug('Authorization callback completed', {
|
|
162
|
-
eventName: `${log.name}.completed`,
|
|
163
|
-
entityId: persistedEntity.id,
|
|
164
|
-
credentialId: module.credential.id,
|
|
165
|
-
});
|
|
166
124
|
|
|
167
125
|
// Best-effort: a hiccup here must not fail a successful re-auth whose
|
|
168
126
|
// credential + entity are already persisted. Operators can recover
|
|
@@ -171,17 +129,14 @@ class ProcessAuthorizationCallback {
|
|
|
171
129
|
const restoredCount = await this.restoreIntegrationsForEntity(
|
|
172
130
|
persistedEntity.id
|
|
173
131
|
);
|
|
174
|
-
log
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
restoredCount,
|
|
178
|
-
});
|
|
132
|
+
console.log(
|
|
133
|
+
`[Frigg] processAuthorizationCallback restored ${restoredCount} integration(s) for entityId=${persistedEntity.id}`
|
|
134
|
+
);
|
|
179
135
|
} catch (err) {
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
});
|
|
136
|
+
console.error(
|
|
137
|
+
`[Frigg] Failed to restore integrations for entity ${persistedEntity.id} after successful re-auth — manual intervention may be needed`,
|
|
138
|
+
err
|
|
139
|
+
);
|
|
185
140
|
}
|
|
186
141
|
|
|
187
142
|
return {
|
|
@@ -200,12 +155,9 @@ class ProcessAuthorizationCallback {
|
|
|
200
155
|
let restored = 0;
|
|
201
156
|
for (const integration of integrations) {
|
|
202
157
|
if (STATUSES_RESET_ON_REAUTH.includes(integration.status)) {
|
|
203
|
-
log
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
previousStatus: integration.status,
|
|
207
|
-
entityId,
|
|
208
|
-
});
|
|
158
|
+
console.log(
|
|
159
|
+
`[Frigg] Restoring integration ${integration.id} from ${integration.status} to ENABLED after successful re-auth (entityId=${entityId})`
|
|
160
|
+
);
|
|
209
161
|
await this.integrationRepository.updateIntegrationStatus(
|
|
210
162
|
integration.id,
|
|
211
163
|
'ENABLED'
|
|
@@ -267,12 +219,9 @@ class ProcessAuthorizationCallback {
|
|
|
267
219
|
credentialId &&
|
|
268
220
|
String(existingCredentialId) !== String(credentialId)
|
|
269
221
|
) {
|
|
270
|
-
log
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
previousCredentialId: existingCredentialId,
|
|
274
|
-
credentialId,
|
|
275
|
-
});
|
|
222
|
+
console.log(
|
|
223
|
+
`[Frigg] Repointing entity ${existingEntity.id} credentialId ${existingCredentialId} -> ${credentialId} after re-auth`
|
|
224
|
+
);
|
|
276
225
|
const updated = await this.moduleRepository.updateEntity(
|
|
277
226
|
existingEntity.id,
|
|
278
227
|
{ credential: credentialId }
|
|
@@ -1,7 +1,4 @@
|
|
|
1
1
|
const { Module } = require('../module');
|
|
2
|
-
const {
|
|
3
|
-
findModuleDefinitionForEntity,
|
|
4
|
-
} = require('../utils/find-module-definition');
|
|
5
2
|
|
|
6
3
|
class RefreshEntityOptions {
|
|
7
4
|
/**
|
|
@@ -49,10 +46,11 @@ class RefreshEntityOptions {
|
|
|
49
46
|
}
|
|
50
47
|
|
|
51
48
|
const entityType = entity.moduleName;
|
|
52
|
-
const moduleDefinition =
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
49
|
+
const moduleDefinition = this.moduleDefinitions.find((def) => {
|
|
50
|
+
const modelName =
|
|
51
|
+
Module.getEntityModelFromDefinition(def).modelName;
|
|
52
|
+
return entityType === modelName;
|
|
53
|
+
});
|
|
56
54
|
|
|
57
55
|
if (!moduleDefinition) {
|
|
58
56
|
throw new Error(
|
|
@@ -1,7 +1,4 @@
|
|
|
1
1
|
const { Module } = require('../module');
|
|
2
|
-
const {
|
|
3
|
-
findModuleDefinitionForEntity,
|
|
4
|
-
} = require('../utils/find-module-definition');
|
|
5
2
|
|
|
6
3
|
class TestModuleAuth {
|
|
7
4
|
/**
|
|
@@ -48,10 +45,11 @@ class TestModuleAuth {
|
|
|
48
45
|
}
|
|
49
46
|
|
|
50
47
|
const entityType = entity.moduleName;
|
|
51
|
-
const moduleDefinition =
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
48
|
+
const moduleDefinition = this.moduleDefinitions.find((def) => {
|
|
49
|
+
const modelName =
|
|
50
|
+
Module.getEntityModelFromDefinition(def).modelName;
|
|
51
|
+
return entityType === modelName;
|
|
52
|
+
});
|
|
55
53
|
|
|
56
54
|
if (!moduleDefinition) {
|
|
57
55
|
throw new Error(
|
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
const { toCredentialId } = require('./to-credential-id');
|
|
2
|
-
|
|
3
1
|
/**
|
|
4
2
|
* @param {import('../module').Module} moduleInstance
|
|
5
3
|
* Convert a Module domain instance to a plain DTO suitable for JSON responses.
|
|
@@ -12,9 +10,9 @@ function mapModuleClassToModuleDTO(moduleInstance) {
|
|
|
12
10
|
name: moduleInstance.name,
|
|
13
11
|
userId: moduleInstance.userId,
|
|
14
12
|
entity: moduleInstance.entity,
|
|
15
|
-
credentialId:
|
|
16
|
-
type: moduleInstance.getName()
|
|
13
|
+
credentialId: moduleInstance.credential?._id?.toString(),
|
|
14
|
+
type: moduleInstance.getName()
|
|
17
15
|
};
|
|
18
16
|
}
|
|
19
17
|
|
|
20
|
-
module.exports = { mapModuleClassToModuleDTO };
|
|
18
|
+
module.exports = { mapModuleClassToModuleDTO };
|