@friggframework/core 2.0.0--canary.731.ffe61d3.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.
Files changed (94) hide show
  1. package/CLAUDE.md +14 -42
  2. package/application/commands/README.md +11 -17
  3. package/application/commands/entity-commands.js +60 -18
  4. package/application/commands/integration-commands.js +0 -63
  5. package/core/CLAUDE.md +3 -1
  6. package/core/create-handler.js +3 -0
  7. package/core/index.js +6 -0
  8. package/core/invocation-deadline.js +91 -0
  9. package/core/invocation-scope.js +30 -24
  10. package/database/documentdb-encryption-service.js +33 -2
  11. package/database/documentdb-utils.js +1 -4
  12. package/database/encryption/README.md +3 -3
  13. package/database/encryption/encryption-schema-registry.js +29 -109
  14. package/database/encryption/field-encryption-service.js +16 -55
  15. package/database/encryption/prisma-encryption-extension.js +9 -6
  16. package/database/prisma.js +1 -10
  17. package/encrypt/Cryptor.js +38 -90
  18. package/errors/fetch-error.js +11 -18
  19. package/errors/index.js +2 -4
  20. package/errors/rate-limit-error.js +45 -0
  21. package/generated/prisma-mongodb/edge.js +2 -6
  22. package/generated/prisma-mongodb/index.js +2 -10
  23. package/generated/prisma-mongodb/package.json +1 -1
  24. package/generated/prisma-mongodb/schema.prisma +1 -1
  25. package/generated/prisma-mongodb/wasm.js +2 -6
  26. package/generated/prisma-postgresql/edge.js +2 -6
  27. package/generated/prisma-postgresql/index.js +2 -10
  28. package/generated/prisma-postgresql/package.json +1 -1
  29. package/generated/prisma-postgresql/schema.prisma +1 -1
  30. package/generated/prisma-postgresql/wasm.js +2 -6
  31. package/handlers/WEBHOOKS.md +0 -29
  32. package/handlers/app-definition-loader.js +2 -9
  33. package/handlers/app-handler-helpers.js +1 -12
  34. package/handlers/backend-utils.js +2 -1
  35. package/handlers/workers/integration-defined-workers.js +2 -0
  36. package/index.js +18 -2
  37. package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +13 -67
  38. package/integrations/integration-base.js +9 -52
  39. package/integrations/integration-router.js +22 -30
  40. package/integrations/repositories/integration-mapping-repository-documentdb.js +0 -50
  41. package/integrations/repositories/integration-mapping-repository-interface.js +0 -15
  42. package/integrations/repositories/integration-mapping-repository-mongo.js +0 -29
  43. package/integrations/repositories/integration-mapping-repository-postgres.js +0 -30
  44. package/integrations/repositories/integration-mapping-repository.js +0 -29
  45. package/integrations/repositories/integration-repository-documentdb.js +0 -32
  46. package/integrations/repositories/integration-repository-interface.js +0 -30
  47. package/integrations/repositories/integration-repository-mongo.js +1 -53
  48. package/integrations/repositories/integration-repository-postgres.js +0 -58
  49. package/integrations/repositories/process-repository-mongo.js +1 -1
  50. package/integrations/use-cases/create-integration.js +19 -57
  51. package/integrations/use-cases/delete-integration-for-user.js +11 -8
  52. package/integrations/use-cases/get-integration-instance.js +12 -12
  53. package/integrations/use-cases/update-integration.js +12 -12
  54. package/jest-setup.js +2 -13
  55. package/jest-teardown.js +2 -5
  56. package/jest.config.js +0 -4
  57. package/logs/serialize.js +15 -0
  58. package/modules/requester/rate-limit/index.js +4 -0
  59. package/modules/requester/rate-limit/parsers.js +245 -0
  60. package/modules/requester/rate-limit/policy.js +304 -0
  61. package/modules/requester/requester.js +187 -9
  62. package/modules/use-cases/get-entity-options-by-id.js +5 -7
  63. package/modules/use-cases/get-module.js +8 -29
  64. package/modules/use-cases/process-authorization-callback.js +27 -78
  65. package/modules/use-cases/refresh-entity-options.js +5 -7
  66. package/modules/use-cases/test-module-auth.js +5 -7
  67. package/modules/utils/map-module-dto.js +3 -5
  68. package/package.json +7 -10
  69. package/prisma-mongodb/schema.prisma +1 -1
  70. package/prisma-postgresql/schema.prisma +1 -1
  71. package/queues/queuer-util.js +5 -6
  72. package/telemetry/otel-telemetry.js +3 -76
  73. package/telemetry/telemetry-config.js +5 -16
  74. package/telemetry/telemetry-runtime.js +1 -14
  75. package/token/repositories/token-repository-documentdb.js +1 -13
  76. package/token/repositories/token-repository-mongo.js +1 -13
  77. package/token/repositories/token-repository-postgres.js +1 -13
  78. package/types/core/index.d.ts +33 -0
  79. package/types/errors/index.d.ts +47 -0
  80. package/types/module-plugin/index.d.ts +43 -0
  81. package/user/tests/doubles/test-user-repository.js +1 -1
  82. package/user/use-cases/authenticate-user.js +7 -23
  83. package/user/use-cases/get-user-from-bearer-token.js +2 -7
  84. package/database/encryption/ciphertext-format.js +0 -24
  85. package/errors/mapping-already-exists-error.js +0 -14
  86. package/generated/prisma-mongodb/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
  87. package/generated/prisma-postgresql/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
  88. package/integrations/use-cases/add-entities-to-integration.js +0 -92
  89. package/integrations/use-cases/remove-entities-from-integration.js +0 -70
  90. package/integrations/utils/assert-entity-ids-input.js +0 -42
  91. package/jest.db.config.js +0 -23
  92. package/modules/use-cases/create-entity-from-credential.js +0 -105
  93. package/modules/utils/find-module-definition.js +0 -23
  94. package/modules/utils/to-credential-id.js +0 -14
@@ -1,92 +0,0 @@
1
- const {
2
- assertEntityIdsInput,
3
- integrationNotFound,
4
- loadIntegration,
5
- } = require('../utils/assert-entity-ids-input');
6
-
7
- /**
8
- * Attaches entities to an existing integration, e.g. when a user grants
9
- * access to more accounts after the integration was created. Every entity
10
- * must exist, belong to the integration's user, and be of a module the
11
- * integration already holds (so hydration can load it). Entities that are
12
- * already attached are left as they are.
13
- * @class AddEntitiesToIntegration
14
- */
15
- class AddEntitiesToIntegration {
16
- /**
17
- * @param {Object} params
18
- * @param {import('../repositories/integration-repository-interface').IntegrationRepositoryInterface} params.integrationRepository
19
- * @param {import('../../modules/repositories/module-repository-interface').ModuleRepositoryInterface} params.moduleRepository
20
- */
21
- constructor({ integrationRepository, moduleRepository }) {
22
- this.integrationRepository = integrationRepository;
23
- this.moduleRepository = moduleRepository;
24
- }
25
-
26
- /**
27
- * @param {string} integrationId
28
- * @param {string[]} entityIds
29
- * @returns {Promise<Object>} The updated integration record.
30
- */
31
- async execute(integrationId, entityIds) {
32
- assertEntityIdsInput(integrationId, entityIds);
33
-
34
- const integration = await loadIntegration(
35
- this.integrationRepository,
36
- integrationId
37
- );
38
-
39
- const entities = await this.moduleRepository.findEntitiesByIds(
40
- entityIds
41
- );
42
- const foundIds = new Set(entities.map((e) => String(e.id)));
43
- const missing = entityIds.filter((id) => !foundIds.has(String(id)));
44
- if (missing.length > 0) {
45
- const error = new Error(
46
- `Entities not found: ${missing.join(', ')}`
47
- );
48
- error.code = 'ENTITIES_NOT_FOUND';
49
- throw error;
50
- }
51
-
52
- const foreign = entities.filter(
53
- (e) => String(e.userId) !== String(integration.userId)
54
- );
55
- if (foreign.length > 0) {
56
- const error = new Error(
57
- `Entities do not belong to the integration's user: ${foreign
58
- .map((e) => e.id)
59
- .join(', ')}`
60
- );
61
- error.code = 'ENTITY_USER_MISMATCH';
62
- throw error;
63
- }
64
-
65
- const attached = await this.moduleRepository.findEntitiesByIds(
66
- integration.entitiesIds ?? []
67
- );
68
- const heldModules = new Set(attached.map((e) => e.moduleName));
69
- const otherModules = entities.filter(
70
- (e) => !heldModules.has(e.moduleName)
71
- );
72
- if (otherModules.length > 0) {
73
- const error = new Error(
74
- `Entities belong to a module the integration does not hold: ${otherModules
75
- .map((e) => `${e.id} (${e.moduleName})`)
76
- .join(', ')}`
77
- );
78
- error.code = 'ENTITY_MODULE_MISMATCH';
79
- throw error;
80
- }
81
-
82
- const updated =
83
- await this.integrationRepository.addEntitiesToIntegration(
84
- integrationId,
85
- entityIds
86
- );
87
- if (!updated) throw integrationNotFound(integrationId);
88
- return updated;
89
- }
90
- }
91
-
92
- module.exports = { AddEntitiesToIntegration };
@@ -1,70 +0,0 @@
1
- const {
2
- assertEntityIdsInput,
3
- integrationNotFound,
4
- loadIntegration,
5
- } = require('../utils/assert-entity-ids-input');
6
-
7
- /**
8
- * Detaches entities from an integration. Entities that are not attached are
9
- * ignored, and detached entities are not deleted. Every module the
10
- * integration holds must keep at least one entity, so the integration can
11
- * still hydrate each of its modules.
12
- * @class RemoveEntitiesFromIntegration
13
- */
14
- class RemoveEntitiesFromIntegration {
15
- /**
16
- * @param {Object} params
17
- * @param {import('../repositories/integration-repository-interface').IntegrationRepositoryInterface} params.integrationRepository
18
- * @param {import('../../modules/repositories/module-repository-interface').ModuleRepositoryInterface} params.moduleRepository
19
- */
20
- constructor({ integrationRepository, moduleRepository }) {
21
- this.integrationRepository = integrationRepository;
22
- this.moduleRepository = moduleRepository;
23
- }
24
-
25
- /**
26
- * @param {string} integrationId
27
- * @param {string[]} entityIds
28
- * @returns {Promise<Object>} The updated integration record.
29
- */
30
- async execute(integrationId, entityIds) {
31
- assertEntityIdsInput(integrationId, entityIds);
32
-
33
- const integration = await loadIntegration(
34
- this.integrationRepository,
35
- integrationId
36
- );
37
-
38
- const removing = new Set(entityIds.map(String));
39
- const attached = await this.moduleRepository.findEntitiesByIds(
40
- integration.entitiesIds ?? []
41
- );
42
- const emptied = [...new Set(attached.map((e) => e.moduleName))].filter(
43
- (moduleName) =>
44
- !attached.some(
45
- (e) =>
46
- e.moduleName === moduleName &&
47
- !removing.has(String(e.id))
48
- )
49
- );
50
- if (emptied.length > 0) {
51
- const error = new Error(
52
- `Removing these entities would leave no entity for module(s): ${emptied.join(
53
- ', '
54
- )}`
55
- );
56
- error.code = 'LAST_ENTITY_OF_MODULE';
57
- throw error;
58
- }
59
-
60
- const updated =
61
- await this.integrationRepository.removeEntitiesFromIntegration(
62
- integrationId,
63
- entityIds
64
- );
65
- if (!updated) throw integrationNotFound(integrationId);
66
- return updated;
67
- }
68
- }
69
-
70
- module.exports = { RemoveEntitiesFromIntegration };
@@ -1,42 +0,0 @@
1
- /**
2
- * Throws INVALID_INTEGRATION_DATA unless an integration id and a non-empty
3
- * list of entity ids are given.
4
- * @param {string} integrationId
5
- * @param {string[]} entityIds
6
- */
7
- function assertEntityIdsInput(integrationId, entityIds) {
8
- if (!integrationId || !Array.isArray(entityIds) || entityIds.length === 0) {
9
- const error = new Error(
10
- 'integrationId and a non-empty entityIds array are required'
11
- );
12
- error.code = 'INVALID_INTEGRATION_DATA';
13
- throw error;
14
- }
15
- }
16
-
17
- function integrationNotFound(integrationId) {
18
- const error = new Error(`Integration ${integrationId} not found`);
19
- error.code = 'INTEGRATION_NOT_FOUND';
20
- return error;
21
- }
22
-
23
- /**
24
- * Loads an integration, mapping the repositories' "not found" error to
25
- * INTEGRATION_NOT_FOUND. Any other failure (connection, invalid id) is
26
- * rethrown unchanged.
27
- * @param {Object} integrationRepository
28
- * @param {string} integrationId
29
- * @returns {Promise<Object>} The integration record.
30
- */
31
- async function loadIntegration(integrationRepository, integrationId) {
32
- try {
33
- return await integrationRepository.findIntegrationById(integrationId);
34
- } catch (error) {
35
- if (/^Integration with id .* not found$/.test(error?.message)) {
36
- throw integrationNotFound(integrationId);
37
- }
38
- throw error;
39
- }
40
- }
41
-
42
- module.exports = { assertEntityIdsInput, integrationNotFound, loadIntegration };
package/jest.db.config.js DELETED
@@ -1,23 +0,0 @@
1
- /*
2
- * Database integration suites (`*.db.test.js`).
3
- *
4
- * These talk to real databases instead of mocking Prisma, so they are kept
5
- * out of the default `npm test` run and executed with `npm run test:db`.
6
- * They need generated Prisma clients (`npm run prisma:generate`) and:
7
- * - a MongoDB replica set (Prisma requires one for MongoDB writes):
8
- * FRIGG_TEST_MONGODB_URL, default
9
- * mongodb://localhost:27017/frigg?replicaSet=rs0
10
- * - PostgreSQL with the prisma-postgresql migrations applied:
11
- * FRIGG_TEST_POSTGRES_URL, default
12
- * postgresql://postgres:postgres@localhost:5432/frigg?schema=public
13
- * The repository parity suites skip themselves unless their own URLs are
14
- * set (INTEGRATION_ENTITIES_PARITY_* / QUERY_MAPPINGS_PARITY_*).
15
- */
16
- const base = require('./jest.config');
17
-
18
- module.exports = {
19
- ...base,
20
- coverageThreshold: undefined,
21
- testMatch: ['**/*.db.test.js'],
22
- testPathIgnorePatterns: ['/node_modules/'],
23
- };
@@ -1,105 +0,0 @@
1
- const Boom = require('@hapi/boom');
2
- const { Module } = require('../module');
3
-
4
- const sameId = (a, b) =>
5
- a !== undefined &&
6
- a !== null &&
7
- b !== undefined &&
8
- b !== null &&
9
- String(a) === String(b);
10
-
11
- /**
12
- * Creates (or finds) the entity for a credential the caller already holds:
13
- * the v1 `POST /api/entity`.
14
- *
15
- * The module is built with the stored credential loaded, so the API can call
16
- * the provider and a token refresh during `getEntityDetails` updates that
17
- * credential. Persistence reuses `ProcessAuthorizationCallback.findOrCreateEntity`,
18
- * the same find-or-create (and credential repointing) the authorization flow
19
- * uses, so the two paths cannot drift.
20
- */
21
- class CreateEntityFromCredential {
22
- /**
23
- * @param {Object} params
24
- * @param {import('./process-authorization-callback').ProcessAuthorizationCallback} params.processAuthorizationCallback
25
- * @param {Object} params.credentialRepository
26
- * @param {Array<Object>} params.moduleDefinitions
27
- * @param {Function} [params.createModule] - builds a Module; injectable for tests
28
- */
29
- constructor({
30
- processAuthorizationCallback,
31
- credentialRepository,
32
- moduleDefinitions,
33
- createModule,
34
- }) {
35
- this.processAuthorizationCallback = processAuthorizationCallback;
36
- this.credentialRepository = credentialRepository;
37
- this.moduleDefinitions = moduleDefinitions || [];
38
- this.createModule = createModule || ((params) => new Module(params));
39
- }
40
-
41
- /**
42
- * @param {Object} params
43
- * @param {Object} params.user - authenticated User
44
- * @param {string} params.entityType
45
- * @param {string} params.credentialId
46
- * @returns {Promise<Object>} the persisted entity
47
- */
48
- async execute({ user, entityType, credentialId }) {
49
- const userId = user?.getId?.();
50
- if (userId === undefined || userId === null) {
51
- throw Boom.unauthorized('No authenticated user');
52
- }
53
-
54
- const definition = this.moduleDefinitions.find(
55
- (def) => def && def.moduleName === entityType
56
- );
57
- if (!definition) {
58
- throw Boom.badRequest(`Unknown entity type ${entityType}`, {
59
- code: 'ENTITY_TYPE_NOT_FOUND',
60
- });
61
- }
62
-
63
- const credential =
64
- await this.credentialRepository.findCredentialById(credentialId);
65
- // A missing credential and someone else's get the same answer, so
66
- // credential ids cannot be probed.
67
- if (!credential || !sameId(credential.userId, userId)) {
68
- throw Boom.badRequest('Invalid credential ID', {
69
- code: 'INVALID_CREDENTIAL',
70
- });
71
- }
72
-
73
- // The repository returns the tokens flat; a Module reads them from
74
- // `credential.data`.
75
- const { id, userId: ownerId, externalId, authIsValid, ...data } =
76
- credential;
77
- const module = this.createModule({
78
- userId,
79
- definition,
80
- entity: {
81
- credential: { id, userId: ownerId, externalId, authIsValid, data },
82
- },
83
- });
84
-
85
- const entityDetails =
86
- await definition.requiredAuthMethods.getEntityDetails(
87
- module.api,
88
- null,
89
- null,
90
- userId
91
- );
92
- Object.assign(
93
- entityDetails.details,
94
- module.apiParamsFromEntity(module.api)
95
- );
96
-
97
- return this.processAuthorizationCallback.findOrCreateEntity(
98
- entityDetails,
99
- definition.moduleName,
100
- credential.id
101
- );
102
- }
103
- }
104
-
105
- module.exports = { CreateEntityFromCredential };
@@ -1,23 +0,0 @@
1
- /**
2
- * The API module definition a stored entity belongs to.
3
- *
4
- * Entities are persisted with `moduleName` set to the definition's
5
- * `moduleName` (see ProcessAuthorizationCallback.findOrCreateEntity). A
6
- * definition's legacy `modelName` is accepted as well, for entities written
7
- * before the two were the same.
8
- *
9
- * @param {Array<Object>} moduleDefinitions
10
- * @param {Object} entity - entity record with a `moduleName`
11
- * @returns {Object|undefined}
12
- */
13
- function findModuleDefinitionForEntity(moduleDefinitions, entity) {
14
- const entityType = entity?.moduleName;
15
- if (!entityType) return undefined;
16
- return (moduleDefinitions || []).find(
17
- (def) =>
18
- def &&
19
- (def.moduleName === entityType || def.modelName === entityType)
20
- );
21
- }
22
-
23
- module.exports = { findModuleDefinitionForEntity };
@@ -1,14 +0,0 @@
1
- /**
2
- * Resolve the credential id from an entity's or module's `credential`, which
3
- * repositories return as the decrypted credential object (or a bare id).
4
- * @param {Object|string|number|null|undefined} credential
5
- * @returns {string|null}
6
- */
7
- function toCredentialId(credential) {
8
- if (credential && typeof credential === 'object') {
9
- return credential.id?.toString() ?? null;
10
- }
11
- return credential?.toString() ?? null;
12
- }
13
-
14
- module.exports = { toCredentialId };