@friggframework/core 2.0.0--canary.657.f16d20b.0 → 2.0.0--canary.737.83b4e17.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 (102) hide show
  1. package/CLAUDE.md +48 -93
  2. package/application/commands/README.md +17 -11
  3. package/application/commands/entity-commands.js +18 -60
  4. package/application/commands/integration-commands.js +63 -0
  5. package/core/CLAUDE.md +1 -33
  6. package/core/Worker.js +11 -317
  7. package/core/create-handler.js +0 -3
  8. package/core/index.js +0 -6
  9. package/core/invocation-scope.js +24 -30
  10. package/database/documentdb-encryption-service.js +2 -33
  11. package/database/documentdb-utils.js +4 -1
  12. package/database/encryption/README.md +3 -3
  13. package/database/encryption/ciphertext-format.js +24 -0
  14. package/database/encryption/encryption-schema-registry.js +109 -29
  15. package/database/encryption/field-encryption-service.js +55 -16
  16. package/database/encryption/prisma-encryption-extension.js +6 -9
  17. package/database/prisma.js +10 -1
  18. package/encrypt/Cryptor.js +90 -38
  19. package/errors/fetch-error.js +18 -11
  20. package/errors/index.js +4 -2
  21. package/errors/mapping-already-exists-error.js +14 -0
  22. package/generated/prisma-mongodb/edge.js +6 -2
  23. package/generated/prisma-mongodb/index.js +10 -2
  24. package/generated/prisma-mongodb/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
  25. package/generated/prisma-mongodb/package.json +1 -1
  26. package/generated/prisma-mongodb/schema.prisma +1 -1
  27. package/generated/prisma-mongodb/wasm.js +6 -2
  28. package/generated/prisma-postgresql/edge.js +6 -2
  29. package/generated/prisma-postgresql/index.js +10 -2
  30. package/generated/prisma-postgresql/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
  31. package/generated/prisma-postgresql/package.json +1 -1
  32. package/generated/prisma-postgresql/schema.prisma +1 -1
  33. package/generated/prisma-postgresql/wasm.js +6 -2
  34. package/handlers/WEBHOOKS.md +29 -0
  35. package/handlers/app-definition-loader.js +9 -2
  36. package/handlers/app-handler-helpers.js +12 -1
  37. package/handlers/backend-utils.js +1 -30
  38. package/handlers/workers/integration-defined-workers.js +0 -2
  39. package/index.js +2 -18
  40. package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +67 -15
  41. package/integrations/integration-base.js +52 -9
  42. package/integrations/integration-router.js +30 -22
  43. package/integrations/repositories/integration-mapping-repository-documentdb.js +50 -0
  44. package/integrations/repositories/integration-mapping-repository-interface.js +15 -0
  45. package/integrations/repositories/integration-mapping-repository-mongo.js +29 -0
  46. package/integrations/repositories/integration-mapping-repository-postgres.js +30 -0
  47. package/integrations/repositories/integration-mapping-repository.js +29 -0
  48. package/integrations/repositories/integration-repository-documentdb.js +32 -0
  49. package/integrations/repositories/integration-repository-interface.js +30 -0
  50. package/integrations/repositories/integration-repository-mongo.js +53 -1
  51. package/integrations/repositories/integration-repository-postgres.js +58 -0
  52. package/integrations/repositories/process-repository-mongo.js +1 -1
  53. package/integrations/use-cases/add-entities-to-integration.js +92 -0
  54. package/integrations/use-cases/create-integration.js +57 -19
  55. package/integrations/use-cases/delete-integration-for-user.js +8 -11
  56. package/integrations/use-cases/get-integration-instance.js +12 -12
  57. package/integrations/use-cases/index.js +1 -5
  58. package/integrations/use-cases/remove-entities-from-integration.js +70 -0
  59. package/integrations/use-cases/update-integration.js +12 -12
  60. package/integrations/utils/assert-entity-ids-input.js +42 -0
  61. package/jest-setup.js +13 -2
  62. package/jest-teardown.js +5 -2
  63. package/jest.config.js +4 -0
  64. package/jest.db.config.js +23 -0
  65. package/logs/serialize.js +0 -15
  66. package/modules/requester/oauth-2.js +0 -7
  67. package/modules/requester/requester.js +9 -187
  68. package/modules/use-cases/create-entity-from-credential.js +105 -0
  69. package/modules/use-cases/get-entity-options-by-id.js +7 -5
  70. package/modules/use-cases/get-module.js +29 -8
  71. package/modules/use-cases/process-authorization-callback.js +78 -27
  72. package/modules/use-cases/refresh-entity-options.js +7 -5
  73. package/modules/use-cases/test-module-auth.js +7 -5
  74. package/modules/utils/find-module-definition.js +23 -0
  75. package/modules/utils/map-module-dto.js +5 -3
  76. package/modules/utils/to-credential-id.js +14 -0
  77. package/package.json +9 -8
  78. package/prisma-mongodb/schema.prisma +1 -1
  79. package/prisma-postgresql/schema.prisma +1 -1
  80. package/queues/queue-delivery.js +0 -1
  81. package/queues/queuer-util.js +10 -8
  82. package/queues/sqs-message-body.js +17 -0
  83. package/telemetry/otel-telemetry.js +76 -3
  84. package/telemetry/telemetry-config.js +16 -5
  85. package/telemetry/telemetry-runtime.js +14 -1
  86. package/token/repositories/token-repository-documentdb.js +13 -1
  87. package/token/repositories/token-repository-mongo.js +13 -1
  88. package/token/repositories/token-repository-postgres.js +13 -1
  89. package/types/core/index.d.ts +0 -52
  90. package/types/errors/index.d.ts +0 -47
  91. package/types/module-plugin/index.d.ts +0 -43
  92. package/user/tests/doubles/test-user-repository.js +1 -1
  93. package/user/use-cases/authenticate-user.js +23 -7
  94. package/user/use-cases/get-user-from-bearer-token.js +7 -2
  95. package/core/invocation-deadline.js +0 -91
  96. package/errors/rate-limit-error.js +0 -46
  97. package/integrations/use-cases/clear-rate-limit-wait.js +0 -28
  98. package/integrations/use-cases/record-rate-limit-wait.js +0 -36
  99. package/modules/requester/rate-limit/index.js +0 -4
  100. package/modules/requester/rate-limit/parsers.js +0 -245
  101. package/modules/requester/rate-limit/policy.js +0 -304
  102. package/queues/queue-deferral.js +0 -74
@@ -0,0 +1,105 @@
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,4 +1,7 @@
1
1
  const { Module } = require('../module');
2
+ const {
3
+ findModuleDefinitionForEntity,
4
+ } = require('../utils/find-module-definition');
2
5
 
3
6
  class GetEntityOptionsById {
4
7
  /**
@@ -45,11 +48,10 @@ class GetEntityOptionsById {
45
48
  }
46
49
 
47
50
  const entityType = entity.moduleName;
48
- const moduleDefinition = this.moduleDefinitions.find((def) => {
49
- const modelName =
50
- Module.getEntityModelFromDefinition(def).modelName;
51
- return entityType === modelName;
52
- });
51
+ const moduleDefinition = findModuleDefinitionForEntity(
52
+ this.moduleDefinitions,
53
+ entity
54
+ );
53
55
 
54
56
  if (!moduleDefinition) {
55
57
  throw new Error(
@@ -1,4 +1,7 @@
1
1
  const { Module } = require('../module');
2
+ const {
3
+ findModuleDefinitionForEntity,
4
+ } = require('../utils/find-module-definition');
2
5
 
3
6
  class GetModule {
4
7
  constructor({ moduleRepository, moduleDefinitions }) {
@@ -42,10 +45,10 @@ class GetModule {
42
45
  }
43
46
 
44
47
  const entityType = entity.moduleName;
45
- const moduleDefinition = this.moduleDefinitions.find((def) => {
46
- const modelName = Module.getEntityModelFromDefinition(def).modelName;
47
- return entityType === modelName;
48
- });
48
+ const moduleDefinition = findModuleDefinitionForEntity(
49
+ this.moduleDefinitions,
50
+ entity
51
+ );
49
52
 
50
53
  if (!moduleDefinition) {
51
54
  throw new Error(
@@ -59,15 +62,33 @@ class GetModule {
59
62
  definition: moduleDefinition,
60
63
  });
61
64
 
62
- // todo: this properties should be methods in the Module class
65
+ // The credential itself (tokens, API keys) never leaves the server:
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;
63
74
  return {
64
75
  id: module.entity.id,
65
76
  name: module.entity.name,
66
77
  moduleName: module.entity.moduleName,
67
- credential: module.credential,
78
+ credentialId:
79
+ credentialId === undefined || credentialId === null
80
+ ? null
81
+ : String(credentialId),
82
+ authIsValid:
83
+ typeof credential?.authIsValid === 'boolean'
84
+ ? credential.authIsValid
85
+ : null,
68
86
  externalId: module.entity.externalId,
69
- userId: module.entity.user.toString(),
70
- }
87
+ userId:
88
+ ownerId === undefined || ownerId === null
89
+ ? null
90
+ : String(ownerId),
91
+ };
71
92
  }
72
93
  }
73
94
 
@@ -1,5 +1,8 @@
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');
3
6
 
4
7
  // Statuses considered "broken" for an integration whose credentials have just
5
8
  // been successfully re-authorized. Both ERROR (system-driven auth failure) and
@@ -28,10 +31,12 @@ class ProcessAuthorizationCallback {
28
31
  }
29
32
 
30
33
  async execute(userId, entityType, params) {
31
- const hasCode = Boolean(params && params.code);
32
- console.log(
33
- `[Frigg] processAuthorizationCallback start userId=${userId} entityType=${entityType} hasCode=${hasCode}`
34
- );
34
+ log.debug('Authorization callback started', {
35
+ eventName: `${log.name}.started`,
36
+ userId,
37
+ entityType,
38
+ hasCode: Boolean(params && params.code),
39
+ });
35
40
 
36
41
  const moduleDefinition = this.moduleDefinitions.find((def) => {
37
42
  return entityType === def.moduleName;
@@ -58,9 +63,11 @@ class ProcessAuthorizationCallback {
58
63
  : null;
59
64
 
60
65
  if (existingEntity) {
61
- console.log(
62
- `[Frigg] processAuthorizationCallback found existing entity id=${existingEntity.id} credentialId=${existingEntity.credential?.id}`
63
- );
66
+ log.debug('Existing entity found', {
67
+ eventName: `${log.name}.existing_entity_found`,
68
+ entityId: existingEntity.id,
69
+ credentialId: existingEntity.credential?.id,
70
+ });
64
71
  }
65
72
 
66
73
  const module = new Module({
@@ -69,15 +76,26 @@ class ProcessAuthorizationCallback {
69
76
  definition: moduleDefinition,
70
77
  });
71
78
 
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
+
72
86
  let tokenResponse;
73
- if (module.apiClass.requesterType === ModuleConstants.authType.oauth2) {
87
+ if (authType === ModuleConstants.authType.oauth2) {
88
+ log.debug('Exchanging authorization code for token', {
89
+ eventName: `${log.name}.token_exchanging`,
90
+ });
74
91
  tokenResponse = await moduleDefinition.requiredAuthMethods.getToken(
75
92
  module.api,
76
93
  params
77
94
  );
78
- console.log(
79
- `[Frigg] processAuthorizationCallback OAuth getToken complete userId=${userId} entityType=${entityType}`
80
- );
95
+ log.debug('Token exchange completed', {
96
+ eventName: `${log.name}.token_exchanged`,
97
+ tokenKeys: Object.keys(tokenResponse || {}),
98
+ });
81
99
  // Belt-and-suspenders: persist tokens explicitly here rather than
82
100
  // relying solely on the DLGT_TOKEN_UPDATE notification chain
83
101
  // inside setTokens. The notification path remains in place but
@@ -86,6 +104,9 @@ class ProcessAuthorizationCallback {
86
104
  // OAuth flow appears to succeed.
87
105
  await this.onTokenUpdate(module, moduleDefinition, userId);
88
106
  } else {
107
+ log.debug('Setting auth params', {
108
+ eventName: `${log.name}.auth_params_setting`,
109
+ });
89
110
  tokenResponse =
90
111
  await moduleDefinition.requiredAuthMethods.setAuthParams(
91
112
  module.api,
@@ -94,15 +115,24 @@ class ProcessAuthorizationCallback {
94
115
  await this.onTokenUpdate(module, moduleDefinition, userId);
95
116
  }
96
117
 
97
- console.log(
98
- `[Frigg] processAuthorizationCallback credential persisted credentialId=${module.credential?.id} authIsValid=${module.credential?.authIsValid}`
99
- );
118
+ log.debug('Credential persisted', {
119
+ eventName: `${log.name}.credential_persisted`,
120
+ credentialId: module.credential?.id,
121
+ authIsValid: module.credential?.authIsValid,
122
+ });
100
123
 
124
+ log.debug('Testing auth', { eventName: `${log.name}.auth_testing` });
101
125
  const authRes = await module.testAuth();
102
126
  if (!authRes) {
103
127
  throw new Error('Authorization failed');
104
128
  }
129
+ log.debug('Auth test passed', {
130
+ eventName: `${log.name}.auth_test_passed`,
131
+ });
105
132
 
133
+ log.debug('Fetching entity details', {
134
+ eventName: `${log.name}.entity_details_fetching`,
135
+ });
106
136
  const entityDetails =
107
137
  await moduleDefinition.requiredAuthMethods.getEntityDetails(
108
138
  module.api,
@@ -110,17 +140,29 @@ class ProcessAuthorizationCallback {
110
140
  tokenResponse,
111
141
  userId
112
142
  );
143
+ log.debug('Entity details received', {
144
+ eventName: `${log.name}.entity_details_received`,
145
+ externalId: entityDetails.identifiers?.externalId,
146
+ });
113
147
 
114
148
  Object.assign(
115
149
  entityDetails.details,
116
150
  module.apiParamsFromEntity(module.api)
117
151
  );
118
152
 
153
+ log.debug('Finding or creating entity', {
154
+ eventName: `${log.name}.entity_resolving`,
155
+ });
119
156
  const persistedEntity = await this.findOrCreateEntity(
120
157
  entityDetails,
121
158
  entityType,
122
159
  module.credential.id
123
160
  );
161
+ log.debug('Authorization callback completed', {
162
+ eventName: `${log.name}.completed`,
163
+ entityId: persistedEntity.id,
164
+ credentialId: module.credential.id,
165
+ });
124
166
 
125
167
  // Best-effort: a hiccup here must not fail a successful re-auth whose
126
168
  // credential + entity are already persisted. Operators can recover
@@ -129,14 +171,17 @@ class ProcessAuthorizationCallback {
129
171
  const restoredCount = await this.restoreIntegrationsForEntity(
130
172
  persistedEntity.id
131
173
  );
132
- console.log(
133
- `[Frigg] processAuthorizationCallback restored ${restoredCount} integration(s) for entityId=${persistedEntity.id}`
134
- );
174
+ log.debug('Integrations restored', {
175
+ eventName: `${log.name}.integrations_restored`,
176
+ entityId: persistedEntity.id,
177
+ restoredCount,
178
+ });
135
179
  } catch (err) {
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
- );
180
+ log.error('Failed to restore integrations after re-auth', {
181
+ eventName: `${log.name}.integrations_restore_failed`,
182
+ entityId: persistedEntity.id,
183
+ error: err,
184
+ });
140
185
  }
141
186
 
142
187
  return {
@@ -155,9 +200,12 @@ class ProcessAuthorizationCallback {
155
200
  let restored = 0;
156
201
  for (const integration of integrations) {
157
202
  if (STATUSES_RESET_ON_REAUTH.includes(integration.status)) {
158
- console.log(
159
- `[Frigg] Restoring integration ${integration.id} from ${integration.status} to ENABLED after successful re-auth (entityId=${entityId})`
160
- );
203
+ log.info('Integration restored to ENABLED after re-auth', {
204
+ eventName: `${log.name}.integration_restored`,
205
+ integrationId: integration.id,
206
+ previousStatus: integration.status,
207
+ entityId,
208
+ });
161
209
  await this.integrationRepository.updateIntegrationStatus(
162
210
  integration.id,
163
211
  'ENABLED'
@@ -219,9 +267,12 @@ class ProcessAuthorizationCallback {
219
267
  credentialId &&
220
268
  String(existingCredentialId) !== String(credentialId)
221
269
  ) {
222
- console.log(
223
- `[Frigg] Repointing entity ${existingEntity.id} credentialId ${existingCredentialId} -> ${credentialId} after re-auth`
224
- );
270
+ log.info('Entity credential repointed after re-auth', {
271
+ eventName: `${log.name}.entity_credential_repointed`,
272
+ entityId: existingEntity.id,
273
+ previousCredentialId: existingCredentialId,
274
+ credentialId,
275
+ });
225
276
  const updated = await this.moduleRepository.updateEntity(
226
277
  existingEntity.id,
227
278
  { credential: credentialId }
@@ -1,4 +1,7 @@
1
1
  const { Module } = require('../module');
2
+ const {
3
+ findModuleDefinitionForEntity,
4
+ } = require('../utils/find-module-definition');
2
5
 
3
6
  class RefreshEntityOptions {
4
7
  /**
@@ -46,11 +49,10 @@ class RefreshEntityOptions {
46
49
  }
47
50
 
48
51
  const entityType = entity.moduleName;
49
- const moduleDefinition = this.moduleDefinitions.find((def) => {
50
- const modelName =
51
- Module.getEntityModelFromDefinition(def).modelName;
52
- return entityType === modelName;
53
- });
52
+ const moduleDefinition = findModuleDefinitionForEntity(
53
+ this.moduleDefinitions,
54
+ entity
55
+ );
54
56
 
55
57
  if (!moduleDefinition) {
56
58
  throw new Error(
@@ -1,4 +1,7 @@
1
1
  const { Module } = require('../module');
2
+ const {
3
+ findModuleDefinitionForEntity,
4
+ } = require('../utils/find-module-definition');
2
5
 
3
6
  class TestModuleAuth {
4
7
  /**
@@ -45,11 +48,10 @@ class TestModuleAuth {
45
48
  }
46
49
 
47
50
  const entityType = entity.moduleName;
48
- const moduleDefinition = this.moduleDefinitions.find((def) => {
49
- const modelName =
50
- Module.getEntityModelFromDefinition(def).modelName;
51
- return entityType === modelName;
52
- });
51
+ const moduleDefinition = findModuleDefinitionForEntity(
52
+ this.moduleDefinitions,
53
+ entity
54
+ );
53
55
 
54
56
  if (!moduleDefinition) {
55
57
  throw new Error(
@@ -0,0 +1,23 @@
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,3 +1,5 @@
1
+ const { toCredentialId } = require('./to-credential-id');
2
+
1
3
  /**
2
4
  * @param {import('../module').Module} moduleInstance
3
5
  * Convert a Module domain instance to a plain DTO suitable for JSON responses.
@@ -10,9 +12,9 @@ function mapModuleClassToModuleDTO(moduleInstance) {
10
12
  name: moduleInstance.name,
11
13
  userId: moduleInstance.userId,
12
14
  entity: moduleInstance.entity,
13
- credentialId: moduleInstance.credential?._id?.toString(),
14
- type: moduleInstance.getName()
15
+ credentialId: toCredentialId(moduleInstance.credential),
16
+ type: moduleInstance.getName(),
15
17
  };
16
18
  }
17
19
 
18
- module.exports = { mapModuleClassToModuleDTO };
20
+ module.exports = { mapModuleClassToModuleDTO };
@@ -0,0 +1,14 @@
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 };
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.657.f16d20b.0",
4
+ "version": "2.0.0--canary.737.83b4e17.0",
5
5
  "dependencies": {
6
6
  "@aws-sdk/client-apigatewaymanagementapi": "^3.588.0",
7
7
  "@aws-sdk/client-kms": "^3.588.0",
@@ -11,6 +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.737.83b4e17.0",
14
15
  "@hapi/boom": "^10.0.1",
15
16
  "@opentelemetry/api": "^1.9.1",
16
17
  "@opentelemetry/context-async-hooks": "^2.9.0",
@@ -20,12 +21,12 @@
20
21
  "@opentelemetry/sdk-metrics": "^2.9.0",
21
22
  "@opentelemetry/sdk-trace-base": "^2.9.0",
22
23
  "bcryptjs": "^2.4.3",
23
- "body-parser": "^1.20.5",
24
+ "body-parser": "^1.20.9",
24
25
  "bson": "^4.7.2",
25
26
  "chalk": "^4.1.2",
26
27
  "cors": "^2.8.5",
27
28
  "dotenv": "^16.4.7",
28
- "express": "^4.22.2",
29
+ "express": "^4.22.3",
29
30
  "express-async-handler": "^1.2.0",
30
31
  "form-data": "^4.0.6",
31
32
  "fs-extra": "^11.2.0",
@@ -48,13 +49,12 @@
48
49
  }
49
50
  },
50
51
  "devDependencies": {
51
- "@friggframework/eslint-config": "2.0.0--canary.657.f16d20b.0",
52
- "@friggframework/prettier-config": "2.0.0--canary.657.f16d20b.0",
53
- "@friggframework/test": "2.0.0--canary.657.f16d20b.0",
52
+ "@friggframework/eslint-config": "2.0.0--canary.737.83b4e17.0",
53
+ "@friggframework/prettier-config": "2.0.0--canary.737.83b4e17.0",
54
+ "@friggframework/test": "2.0.0--canary.737.83b4e17.0",
54
55
  "@prisma/client": "^6.19.3",
55
56
  "@types/lodash": "4.17.15",
56
57
  "@typescript-eslint/eslint-plugin": "^8.0.0",
57
- "aws-sdk-client-mock": "^4.1.0",
58
58
  "chai": "^4.3.6",
59
59
  "eslint": "^8.22.0",
60
60
  "eslint-plugin-import": "^2.29.1",
@@ -69,6 +69,7 @@
69
69
  "scripts": {
70
70
  "lint:fix": "prettier --write --loglevel error . && eslint . --fix",
71
71
  "test": "jest --passWithNoTests # TODO",
72
+ "test:db": "jest --config jest.db.config.js --runInBand",
72
73
  "prisma:generate:mongo": "npx prisma generate --schema ./prisma-mongodb/schema.prisma",
73
74
  "prisma:generate:postgres": "npx prisma generate --schema ./prisma-postgresql/schema.prisma",
74
75
  "prisma:generate": "npm run prisma:generate:mongo && npm run prisma:generate:postgres",
@@ -91,5 +92,5 @@
91
92
  "publishConfig": {
92
93
  "access": "public"
93
94
  },
94
- "gitHead": "f16d20b91d76dd1c98f7e0dc91eb4026bafba2a3"
95
+ "gitHead": "83b4e17ac7ec4481bd8143508a2a532e399fcce8"
95
96
  }
@@ -5,7 +5,7 @@
5
5
  generator client {
6
6
  provider = "prisma-client-js"
7
7
  output = "../generated/prisma-mongodb"
8
- binaryTargets = ["native", "rhel-openssl-3.0.x"] // native for local dev, rhel for Lambda deployment
8
+ binaryTargets = ["native", "rhel-openssl-3.0.x", "linux-arm64-openssl-3.0.x"] // native for local dev, rhel for x86_64 Lambda, linux-arm64 for arm64 Lambda
9
9
  // Library engine (default since Prisma 3.x): Rust query engine loads as a
10
10
  // Node-API addon inside the same process. The binary engine forks a child
11
11
  // query-engine subprocess and communicates over a local HTTP/IPC pipe with
@@ -5,7 +5,7 @@
5
5
  generator client {
6
6
  provider = "prisma-client-js"
7
7
  output = "../generated/prisma-postgresql"
8
- binaryTargets = ["native", "rhel-openssl-3.0.x"] // native for local dev, rhel for Lambda deployment
8
+ binaryTargets = ["native", "rhel-openssl-3.0.x", "linux-arm64-openssl-3.0.x"] // native for local dev, rhel for x86_64 Lambda, linux-arm64 for arm64 Lambda
9
9
  // Library engine (default since Prisma 3.x): Rust query engine loads as a
10
10
  // Node-API addon inside the same process. The binary engine forks a child
11
11
  // query-engine subprocess and communicates over a local HTTP/IPC pipe with
@@ -38,5 +38,4 @@ module.exports = {
38
38
  INTEGRATION_QUEUE_MAX_RECEIVE_COUNT,
39
39
  QUEUE_MAX_RECEIVE_COUNT_ENV,
40
40
  readQueueDelivery,
41
- toPositiveInteger,
42
41
  };
@@ -1,6 +1,7 @@
1
1
  const { v4: uuid } = require('uuid');
2
2
  const { SQSClient, SendMessageCommand, SendMessageBatchCommand } = require('@aws-sdk/client-sqs');
3
3
  const { summarizeMessageBody } = require('../logs/summarize-event');
4
+ const { toSqsMessageBody } = require('./sqs-message-body');
4
5
 
5
6
  const awsConfigOptions = () => {
6
7
  const config = {};
@@ -78,7 +79,7 @@ const inspectBatchResult = (result, queueUrl, buffer) => {
78
79
  const QueuerUtil = {
79
80
  send: async (message, queueUrl) => {
80
81
  const command = new SendMessageCommand({
81
- MessageBody: JSON.stringify(message),
82
+ MessageBody: toSqsMessageBody(message),
82
83
  QueueUrl: queueUrl,
83
84
  });
84
85
  const result = await sqs.send(command);
@@ -95,18 +96,19 @@ const QueuerUtil = {
95
96
  for (const entry of entries) {
96
97
  buffer.push({
97
98
  Id: uuid(),
98
- MessageBody: JSON.stringify(entry),
99
+ MessageBody: toSqsMessageBody(entry),
99
100
  });
100
- // Sends 10, then purges the buffer
101
+ // Sends 10, then starts a fresh buffer. Each command gets its own
102
+ // array: clearing the shared buffer in place would also empty the
103
+ // Entries of a command that was already sent.
101
104
  if (buffer.length === batchSize) {
105
+ const batch = buffer.splice(0, buffer.length);
102
106
  const command = new SendMessageBatchCommand({
103
- Entries: buffer,
107
+ Entries: batch,
104
108
  QueueUrl: queueUrl,
105
109
  });
106
110
  const result = await sqs.send(command);
107
- inspectBatchResult(result, queueUrl, buffer);
108
- // Purge the buffer
109
- buffer.splice(0, buffer.length);
111
+ inspectBatchResult(result, queueUrl, batch);
110
112
  }
111
113
  }
112
114
 
@@ -126,4 +128,4 @@ const QueuerUtil = {
126
128
  },
127
129
  };
128
130
 
129
- module.exports = { QueuerUtil, awsConfigOptions };
131
+ module.exports = { QueuerUtil };
@@ -0,0 +1,17 @@
1
+ // SQS accepts only #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] |
2
+ // [#x10000-#x10FFFF] and rejects the whole message otherwise
3
+ // (InvalidMessageContents). JSON.stringify already escapes control characters
4
+ // and lone surrogates, but leaves U+FFFE and U+FFFF raw. Those can only occur
5
+ // inside JSON strings, so a \uXXXX escape keeps the JSON valid and JSON.parse
6
+ // returns the original message exactly.
7
+ const SQS_DISALLOWED_CHARACTERS =
8
+ /[^\x09\x0A\x0D\x20-\uD7FF\uE000-\uFFFD\u{10000}-\u{10FFFF}]/gu;
9
+
10
+ const toSqsMessageBody = (message) =>
11
+ JSON.stringify(message).replace(
12
+ SQS_DISALLOWED_CHARACTERS,
13
+ (character) =>
14
+ `\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`
15
+ );
16
+
17
+ module.exports = { toSqsMessageBody };