@friggframework/core 2.0.0--canary.680.daae24e.0 → 2.0.0--canary.686.e94de4d.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 (156) hide show
  1. package/CHANGELOG.md +0 -11
  2. package/CLAUDE.md +28 -0
  3. package/README.md +105 -0
  4. package/application/commands/integration-commands.js +2 -2
  5. package/application/commands/scheduler-commands.js +11 -7
  6. package/application/commands/user-commands.js +17 -5
  7. package/core/Worker.js +31 -7
  8. package/core/create-handler.js +9 -0
  9. package/credential/use-cases/credential-operations-for-user.js +110 -25
  10. package/credential/use-cases/reauthorize-credential-for-user.js +15 -8
  11. package/database/config.js +48 -24
  12. package/database/documentdb-utils.js +6 -1
  13. package/database/encryption/README.md +0 -2
  14. package/database/encryption/encryption-config.js +10 -31
  15. package/database/encryption/encryption-schema-registry.js +99 -47
  16. package/database/encryption/field-encryption-service.js +5 -69
  17. package/database/organization-where.js +18 -0
  18. package/database/prisma.js +4 -2
  19. package/database/unique-violation.js +25 -0
  20. package/extensions/bootstrap-runner.js +43 -0
  21. package/extensions/extension-loader.js +187 -0
  22. package/extensions/index.js +41 -0
  23. package/extensions/initialize-app.js +123 -0
  24. package/extensions/route-mounter.js +103 -0
  25. package/extensions/schema-composer.js +188 -0
  26. package/generated/prisma-mongodb/edge.js +27 -4
  27. package/generated/prisma-mongodb/index-browser.js +24 -1
  28. package/generated/prisma-mongodb/index.d.ts +3227 -47
  29. package/generated/prisma-mongodb/index.js +27 -4
  30. package/generated/prisma-mongodb/package.json +1 -1
  31. package/generated/prisma-mongodb/schema.prisma +65 -0
  32. package/generated/prisma-mongodb/wasm.js +27 -4
  33. package/generated/prisma-postgresql/edge.js +27 -4
  34. package/generated/prisma-postgresql/index-browser.js +24 -1
  35. package/generated/prisma-postgresql/index.d.ts +3519 -67
  36. package/generated/prisma-postgresql/index.js +27 -4
  37. package/generated/prisma-postgresql/package.json +1 -1
  38. package/generated/prisma-postgresql/schema.prisma +61 -0
  39. package/generated/prisma-postgresql/wasm.js +27 -4
  40. package/handlers/app-definition-loader.js +103 -12
  41. package/handlers/routers/auth.js +40 -12
  42. package/handlers/routers/health.js +4 -2
  43. package/handlers/routers/integration-defined-routers.js +144 -92
  44. package/handlers/routers/integration-webhook-routers.js +102 -64
  45. package/index.js +63 -1
  46. package/infrastructure/scheduler/index.js +19 -6
  47. package/infrastructure/scheduler/netlify-scheduler-adapter.js +216 -0
  48. package/infrastructure/scheduler/scheduled-job-repository.js +118 -0
  49. package/infrastructure/scheduler/scheduler-service-factory.js +55 -7
  50. package/integrations/index.js +5 -0
  51. package/integrations/integration-router.js +115 -73
  52. package/integrations/repositories/integration-not-found.js +14 -0
  53. package/integrations/repositories/integration-repository-documentdb.js +35 -3
  54. package/integrations/repositories/integration-repository-interface.js +17 -1
  55. package/integrations/repositories/integration-repository-mongo.js +59 -76
  56. package/integrations/repositories/integration-repository-postgres.js +62 -76
  57. package/integrations/schedule-config.js +80 -0
  58. package/integrations/tests/doubles/test-integration-repository.js +12 -1
  59. package/integrations/use-cases/create-integration.js +55 -20
  60. package/integrations/use-cases/dispatch-ongoing-syncs.js +100 -0
  61. package/integrations/use-cases/get-integrations-for-user.js +80 -40
  62. package/integrations/use-cases/index.js +7 -1
  63. package/integrations/use-cases/integration-operations-for-user.js +55 -24
  64. package/integrations/use-cases/resolve-integration-ownership.js +177 -0
  65. package/integrations/utils/map-integration-dto.js +44 -1
  66. package/management-api/management-api-config.js +71 -2
  67. package/management-api/meta-router.js +21 -2
  68. package/management-api/openapi/components.js +40 -0
  69. package/management-api/openapi/v2-operations.js +16 -4
  70. package/management-api/route-registry.js +123 -6
  71. package/management-api/v2/dependencies.js +40 -15
  72. package/management-api/v2/dto.js +20 -0
  73. package/management-api/v2/handlers/authorization.js +1 -0
  74. package/management-api/v2/handlers/credentials.js +6 -2
  75. package/management-api/v2/handlers/entities.js +10 -7
  76. package/management-api/v2/handlers/integrations.js +6 -3
  77. package/management-api/v2/request.js +32 -1
  78. package/modules/entity-scope.js +15 -0
  79. package/modules/index.js +8 -0
  80. package/modules/module-factory.js +12 -0
  81. package/modules/module.js +53 -2
  82. package/modules/repositories/entity-not-found.js +18 -0
  83. package/modules/repositories/module-repository-documentdb.js +51 -6
  84. package/modules/repositories/module-repository-interface.js +19 -2
  85. package/modules/repositories/module-repository-mongo.js +67 -74
  86. package/modules/repositories/module-repository-postgres.js +66 -74
  87. package/modules/repositories/module-repository.js +2 -1
  88. package/modules/scope-config.js +192 -0
  89. package/modules/scope-policy.js +112 -0
  90. package/modules/scope-resolution.js +288 -0
  91. package/modules/scope-visibility.js +247 -0
  92. package/modules/tests/doubles/ownership-matching.js +18 -0
  93. package/modules/use-cases/authorize-entity-for-user.js +61 -0
  94. package/modules/use-cases/create-entity-from-credential.js +113 -0
  95. package/modules/use-cases/entity-operations-for-user.js +50 -13
  96. package/modules/use-cases/entity-types.js +31 -7
  97. package/modules/use-cases/execute-entity-proxy-request.js +50 -3
  98. package/modules/use-cases/get-authorization-requirements.js +2 -2
  99. package/modules/use-cases/get-entities-for-user.js +26 -13
  100. package/modules/use-cases/get-entity-module-for-user.js +34 -7
  101. package/modules/use-cases/get-entity-options-by-id.js +10 -4
  102. package/modules/use-cases/get-entity-options-by-type.js +1 -1
  103. package/modules/use-cases/get-module-instance-from-type.js +1 -1
  104. package/modules/use-cases/get-module.js +10 -4
  105. package/modules/use-cases/manage-access.js +21 -0
  106. package/modules/use-cases/multi-step-authorization.js +40 -13
  107. package/modules/use-cases/process-authorization-callback.js +53 -19
  108. package/modules/use-cases/refresh-entity-options.js +10 -4
  109. package/modules/use-cases/test-module-auth.js +10 -4
  110. package/package.json +6 -5
  111. package/prisma-mongodb/schema.prisma +65 -0
  112. package/prisma-postgresql/migrations/20261015000000_add_organization_membership/migration.sql +26 -0
  113. package/prisma-postgresql/migrations/20261016000000_add_entity_integration_organization/migration.sql +25 -0
  114. package/prisma-postgresql/migrations/20261017000000_add_scheduled_job/migration.sql +28 -0
  115. package/prisma-postgresql/schema.prisma +61 -0
  116. package/providers/index.js +23 -0
  117. package/providers/resolve-provider.js +93 -0
  118. package/providers/runtime-detection.js +124 -0
  119. package/queues/index.js +25 -0
  120. package/queues/providers/index.js +11 -0
  121. package/queues/providers/netlify-background-provider.js +150 -0
  122. package/queues/providers/qstash-queue-provider.js +219 -0
  123. package/queues/providers/sqs-queue-provider.js +70 -0
  124. package/queues/queue-client-interface.js +55 -0
  125. package/queues/queue-message-auth.js +193 -0
  126. package/queues/queue-provider-factory.js +101 -0
  127. package/queues/queue-provider.js +65 -0
  128. package/queues/sqs-queue-client.js +81 -0
  129. package/types/index.d.ts +1 -0
  130. package/types/modules/index.d.ts +139 -0
  131. package/types/user/index.d.ts +134 -0
  132. package/user/adopter-jwt-config.js +177 -0
  133. package/user/adopter-jwt-errors.js +59 -0
  134. package/user/adopter-token-verifier.js +122 -0
  135. package/user/app-user-helpers.js +97 -0
  136. package/user/create-user-authentication.js +64 -0
  137. package/user/membership.js +51 -0
  138. package/user/repositories/organization-membership-record.js +19 -0
  139. package/user/repositories/organization-membership-repository-documentdb.js +106 -0
  140. package/user/repositories/organization-membership-repository-factory.js +42 -0
  141. package/user/repositories/organization-membership-repository-interface.js +57 -0
  142. package/user/repositories/organization-membership-repository-mongo.js +13 -0
  143. package/user/repositories/organization-membership-repository-postgres.js +29 -0
  144. package/user/repositories/organization-membership-repository-prisma.js +81 -0
  145. package/user/repositories/user-repository-documentdb.js +27 -2
  146. package/user/repositories/user-repository-interface.js +18 -0
  147. package/user/repositories/user-repository-mongo.js +24 -0
  148. package/user/repositories/user-repository-postgres.js +18 -0
  149. package/user/tests/doubles/adopter-jwt-fixtures.js +220 -0
  150. package/user/use-cases/authenticate-user.js +7 -1
  151. package/user/use-cases/ensure-organization-membership.js +92 -0
  152. package/user/use-cases/find-individual-users-by-organization.js +54 -0
  153. package/user/use-cases/get-user-from-adopter-jwt.js +95 -124
  154. package/user/use-cases/get-user-from-x-frigg-headers.js +83 -80
  155. package/user/user.js +64 -1
  156. package/database/encryption/test-support/fake-ciphertext.js +0 -15
@@ -3,6 +3,39 @@
3
3
  * Manages configuration for Prisma ORM operations
4
4
  */
5
5
 
6
+ /**
7
+ * Maps an app definition's `database` block to a Prisma database type.
8
+ *
9
+ * @param {Object|undefined} database - `Definition.database`
10
+ * @param {string} where - where the definition lives, for the error message
11
+ * @returns {'mongodb'|'postgresql'|'documentdb'}
12
+ */
13
+ function databaseTypeFromConfig(database, where) {
14
+ if (!database) {
15
+ throw new Error(
16
+ '[Frigg] App definition missing database configuration. ' +
17
+ `Add database: { postgres: { enable: true } } (or mongoDB/documentDB) to ${where}`
18
+ );
19
+ }
20
+
21
+ // Determine database type from enabled database
22
+ // Priority order: postgres > mongoDB > documentDB
23
+ if (database.postgres?.enable === true) {
24
+ return 'postgresql';
25
+ }
26
+ if (database.mongoDB?.enable === true) {
27
+ return 'mongodb';
28
+ }
29
+ if (database.documentDB?.enable === true) {
30
+ return 'documentdb';
31
+ }
32
+
33
+ throw new Error(
34
+ '[Frigg] No database enabled in app definition. ' +
35
+ 'Set one of: database.postgres.enable, database.mongoDB.enable, or database.documentDB.enable to true'
36
+ );
37
+ }
38
+
6
39
  /**
7
40
  * Determines database type from environment or app definition
8
41
  *
@@ -21,6 +54,20 @@ function getDatabaseType() {
21
54
 
22
55
  // Fallback: Load app definition
23
56
  try {
57
+ // A definition preset with setAppDefinition() (provider-netlify's
58
+ // function preamble) wins: on Netlify process.cwd() is the function
59
+ // root at runtime, so discovery cannot find the backend.
60
+ const {
61
+ getPresetAppDefinition,
62
+ } = require('../handlers/app-definition-loader');
63
+ const preset = getPresetAppDefinition();
64
+ if (preset) {
65
+ return databaseTypeFromConfig(
66
+ preset.database,
67
+ 'your backend/index.js'
68
+ );
69
+ }
70
+
24
71
  const path = require('node:path');
25
72
  const fs = require('node:fs');
26
73
  const { findNearestBackendPackageJson } = require('../utils');
@@ -76,30 +123,7 @@ function getDatabaseType() {
76
123
  }
77
124
 
78
125
  database = backendModule?.Definition?.database;
79
-
80
- if (!database) {
81
- throw new Error(
82
- '[Frigg] App definition missing database configuration. ' +
83
- `Add database: { postgres: { enable: true } } (or mongoDB/documentDB) to ${backendIndexPath}`
84
- );
85
- }
86
-
87
- // Determine database type from enabled database
88
- // Priority order: postgres > mongoDB > documentDB
89
- if (database.postgres?.enable === true) {
90
- return 'postgresql';
91
- }
92
- if (database.mongoDB?.enable === true) {
93
- return 'mongodb';
94
- }
95
- if (database.documentDB?.enable === true) {
96
- return 'documentdb';
97
- }
98
-
99
- throw new Error(
100
- '[Frigg] No database enabled in app definition. ' +
101
- 'Set one of: database.postgres.enable, database.mongoDB.enable, or database.documentDB.enable to true'
102
- );
126
+ return databaseTypeFromConfig(database, backendIndexPath);
103
127
  } catch (error) {
104
128
  // Re-throw with context if it's our error
105
129
  if (error.message.includes('[Frigg]')) {
@@ -58,7 +58,12 @@ async function insertOne(client, collection, document) {
58
58
 
59
59
  // Provide helpful context for common errors
60
60
  if (error.code === 11000) {
61
- throw new Error(`${errorMsg} - Duplicate key violation`);
61
+ // `code` lets callers recognise a lost race without parsing text
62
+ // (see database/unique-violation.js).
63
+ throw Object.assign(
64
+ new Error(`${errorMsg} - Duplicate key violation`),
65
+ { code: 11000 }
66
+ );
62
67
  }
63
68
  throw new Error(errorMsg);
64
69
  }
@@ -456,8 +456,6 @@ Format: "keyId:encryptedText:encryptedKey"
456
456
  Example: "base64KeyId:iv:ciphertext:base64EncryptedDataKey"
457
457
  ```
458
458
 
459
- **Recognising ciphertext on read.** A value is decrypted only when it has exactly four colon-separated parts: base64 `keyId`, 32-hex-character `iv`, hex ciphertext, base64 `encryptedKey`. Plaintext that merely contains colons (`https://user:pw@host:443`) is left alone. A value with that shape that still fails to decrypt (a wrong, rotated or missing key) fails the read with `FieldDecryptionError` in a deployed runtime (see [When Encryption Runs](#when-encryption-runs)), so ciphertext never reaches an API module as if it were a token. Locally it is returned as stored and logged as a warning, so one bad field does not fail a whole read. A field that becomes encrypted later (for example a module's `credentialFields`) stays plaintext in existing rows until they are next written.
460
-
461
459
  **Why Envelope Encryption?**
462
460
 
463
461
  - Reduces KMS API calls (one DEK per field, cached)
@@ -18,6 +18,9 @@
18
18
  */
19
19
 
20
20
  const { logger } = require('./logger');
21
+ const {
22
+ isDeployedRuntime: isDeployedProviderRuntime,
23
+ } = require('../../providers/runtime-detection');
21
24
 
22
25
  const LOCAL_BYPASS_STAGES = ['dev', 'test', 'local'];
23
26
  const OPT_OUT_VAR = 'FRIGG_ENCRYPTION_DISABLED';
@@ -40,42 +43,18 @@ function isTrue(value) {
40
43
  }
41
44
 
42
45
  /**
43
- * True when the process runs as a deployed function, on AWS Lambda or on
44
- * another provider's platform.
45
- *
46
- * - AWS Lambda sets AWS_LAMBDA_FUNCTION_NAME, LAMBDA_TASK_ROOT and
47
- * AWS_EXECUTION_ENV (AWS_Lambda_<runtime>). Other AWS hosts (CloudShell,
48
- * CodeBuild, ECS) set AWS_EXECUTION_ENV to other values and count as local:
49
- * CLI commands run from CI must not trip the deployed-stage check.
50
- * - Other providers: FRIGG_PROVIDER names a non-AWS provider. Frigg's
51
- * generated function entry points for that provider set it (provider-netlify
52
- * sets 'netlify'), so it is present in every deployed function. Netlify
53
- * exposes SITE_ID, CONTEXT and NETLIFY at build time only, so they cannot
54
- * tell a running function from a laptop.
55
- *
56
- * A local run is never deployed: serverless-offline and `serverless invoke
57
- * local` (which set the Lambda variables themselves) mark IS_OFFLINE /
58
- * IS_LOCAL, `netlify dev` marks NETLIFY_DEV, and Jest marks JEST_WORKER_ID.
46
+ * True when the process runs as a deployed function, on AWS Lambda or on the
47
+ * active provider's platform (provider-netlify: FRIGG_PROVIDER=netlify, set by
48
+ * its generated entry points), and not under a local emulator or test runner.
49
+ * One rule for encryption and queue authentication: core/providers/
50
+ * runtime-detection asks the provider's detect(), and fails closed when a
51
+ * named non-AWS provider cannot be loaded.
59
52
  *
60
53
  * @param {Object} [env=process.env]
61
54
  * @returns {boolean}
62
55
  */
63
56
  function isDeployedRuntime(env = process.env) {
64
- const localRun =
65
- isTrue(env.IS_OFFLINE) ||
66
- isTrue(env.IS_LOCAL) ||
67
- isTrue(env.NETLIFY_DEV) ||
68
- isSet(env.JEST_WORKER_ID);
69
- if (localRun) return false;
70
-
71
- const onAwsRuntime =
72
- isSet(env.AWS_LAMBDA_FUNCTION_NAME) ||
73
- isSet(env.LAMBDA_TASK_ROOT) ||
74
- String(env.AWS_EXECUTION_ENV ?? '').startsWith('AWS_Lambda_');
75
- if (onAwsRuntime) return true;
76
-
77
- const provider = String(env.FRIGG_PROVIDER ?? '').trim().toLowerCase();
78
- return provider !== '' && provider !== 'aws';
57
+ return isDeployedProviderRuntime(env);
79
58
  }
80
59
 
81
60
  function missingKeyMessage(stage) {
@@ -10,11 +10,6 @@
10
10
 
11
11
  const { logger } = require('./logger');
12
12
  const { registerDeniedKeys } = require('../../logs/denied-keys');
13
- const {
14
- getEntityTypeRegistry,
15
- getEntityTypeDefinitions,
16
- EntityRegistryError,
17
- } = require('../../modules/entity-type-registry');
18
13
 
19
14
  /**
20
15
  * Core encryption schema (immutable - cannot be overridden by custom schemas)
@@ -171,9 +166,8 @@ function extractCredentialFieldsFromModules(moduleDefinitions) {
171
166
  * Each module can declare credentialFields to encrypt in its encryption config.
172
167
  *
173
168
  * @param {Array} integrations - Array of integration classes with modules
174
- * @param {object} [entities] - `appDefinition.entities` (ADR-059 registry)
175
169
  */
176
- function loadModuleEncryptionSchemas(integrations, entities) {
170
+ function loadModuleEncryptionSchemas(integrations) {
177
171
  if (!integrations) {
178
172
  throw new Error('integrations parameter is required');
179
173
  }
@@ -182,39 +176,34 @@ function loadModuleEncryptionSchemas(integrations, entities) {
182
176
  throw new Error('integrations must be an array');
183
177
  }
184
178
 
185
- // `entities` is the app definition's registry (ADR-059): a module an app
186
- // registers without any integration still carries credentials to encrypt.
187
- if (integrations.length === 0 && !entities) {
179
+ if (integrations.length === 0) {
188
180
  return;
189
181
  }
190
182
 
191
- const moduleDefinitions = getEntityTypeDefinitions(
192
- getEntityTypeRegistry({ integrations, entities })
193
- );
183
+ // NOTE: this path does not exist ('../integrations' resolves to
184
+ // database/integrations), so today this function throws MODULE_NOT_FOUND,
185
+ // loadCustomEncryptionSchema swallows it, and module credentialFields are
186
+ // effectively NOT registered. Fixing it changes which fields are encrypted
187
+ // and needs a decrypt that tolerates plaintext, so it ships separately:
188
+ // branch claude/internal-mcp-03b-module-credential-encryption. Left as is
189
+ // here on purpose (ADR-059 must not change what gets encrypted).
190
+ const { getModulesDefinitionFromIntegrationClasses } = require('../integrations/utils/map-integration-dto');
191
+
192
+ const moduleDefinitions = getModulesDefinitionFromIntegrationClasses(integrations);
194
193
  const credentialFields = extractCredentialFieldsFromModules(moduleDefinitions);
195
194
 
196
- // Core fields are encrypted already and a custom schema may not repeat
197
- // them. Everything the app registered itself stays: module fields are added
198
- // to the custom schema, never substituted for it (other models included).
199
- const coreFields = new Set(CORE_ENCRYPTION_SCHEMA.Credential?.fields || []);
200
- const fields = [
201
- ...new Set([
202
- ...(customSchema.Credential?.fields || []),
203
- ...credentialFields.filter((field) => !coreFields.has(field)),
204
- ]),
205
- ];
206
-
207
- if (fields.length === 0) {
195
+ if (credentialFields.length === 0) {
208
196
  return;
209
197
  }
210
198
 
211
199
  const moduleSchema = {
212
- ...customSchema,
213
- Credential: { ...customSchema.Credential, fields },
200
+ Credential: {
201
+ fields: credentialFields
202
+ }
214
203
  };
215
204
 
216
205
  logger.info(
217
- `Registering module-level encryption for ${fields.length} credential fields`
206
+ `Registering module-level encryption for ${credentialFields.length} credential fields`
218
207
  );
219
208
 
220
209
  registerCustomSchema(moduleSchema);
@@ -229,22 +218,80 @@ function loadModuleEncryptionSchemas(integrations, entities) {
229
218
  *
230
219
  * Used by both Prisma (MongoDB/PostgreSQL) and DocumentDB encryption services.
231
220
  */
232
- function loadCustomEncryptionSchema() {
233
- try {
234
- // Lazy require to avoid circular dependency issues
235
- const path = require('node:path');
236
- const { findNearestBackendPackageJson } = require('../../utils');
221
+ /**
222
+ * Registers encryption schemas declared by app-level extensions
223
+ * (`appDefinition.coreExtensions[].encryption`), e.g. the db-credentials
224
+ * extension's `OAuthAppCredential.clientSecret`.
225
+ *
226
+ * @param {Array<Object>} extensions - Normalized extensions (extension-loader)
227
+ */
228
+ function loadExtensionEncryptionSchemas(extensions) {
229
+ if (!extensions || !Array.isArray(extensions) || extensions.length === 0) {
230
+ return;
231
+ }
232
+
233
+ for (const ext of extensions) {
234
+ if (!ext.encryption || typeof ext.encryption !== 'object') {
235
+ continue;
236
+ }
237
+
238
+ const schema = {};
239
+ for (const [modelName, config] of Object.entries(ext.encryption)) {
240
+ if (config && Array.isArray(config.fields) && config.fields.length > 0) {
241
+ schema[modelName] = { fields: config.fields };
242
+ }
243
+ }
237
244
 
238
- const backendPackagePath = findNearestBackendPackageJson();
239
- if (!backendPackagePath) {
240
- return; // No backend found, skip custom schema
245
+ if (Object.keys(schema).length > 0) {
246
+ logger.info(
247
+ `Registering encryption schema from extension "${ext.name}" for models: ${Object.keys(schema).join(', ')}`
248
+ );
249
+ // registerCustomSchema replaces the registered schema, so merge:
250
+ // an extension adds its models to the app's encryption.schema
251
+ // rather than dropping it.
252
+ const merged = { ...customSchema };
253
+ for (const [modelName, config] of Object.entries(schema)) {
254
+ const existing = merged[modelName]?.fields || [];
255
+ merged[modelName] = {
256
+ ...merged[modelName],
257
+ fields: [...new Set([...existing, ...config.fields])],
258
+ };
259
+ }
260
+ registerCustomSchema(merged);
241
261
  }
262
+ }
263
+ }
264
+
265
+ function readAppDefinitionForEncryption() {
266
+ // Lazy require to avoid circular dependency issues
267
+ const {
268
+ getPresetAppDefinition,
269
+ } = require('../../handlers/app-definition-loader');
270
+ // A definition preset with setAppDefinition() (provider-netlify's
271
+ // preamble) wins: on Netlify process.cwd() cannot find the backend.
272
+ const preset = getPresetAppDefinition();
273
+ if (preset) {
274
+ return preset;
275
+ }
276
+
277
+ const path = require('node:path');
278
+ const { findNearestBackendPackageJson } = require('../../utils');
279
+
280
+ const backendPackagePath = findNearestBackendPackageJson();
281
+ if (!backendPackagePath) {
282
+ return null; // No backend found, skip custom schema
283
+ }
284
+
285
+ const backendDir = path.dirname(backendPackagePath);
286
+ const backendIndexPath = path.join(backendDir, 'index.js');
242
287
 
243
- const backendDir = path.dirname(backendPackagePath);
244
- const backendIndexPath = path.join(backendDir, 'index.js');
288
+ const backendModule = require(backendIndexPath);
289
+ return backendModule?.Definition || null;
290
+ }
245
291
 
246
- const backendModule = require(backendIndexPath);
247
- const appDefinition = backendModule?.Definition;
292
+ function loadCustomEncryptionSchema() {
293
+ try {
294
+ const appDefinition = readAppDefinitionForEncryption();
248
295
 
249
296
  if (!appDefinition) {
250
297
  return; // No app definition found
@@ -264,17 +311,21 @@ function loadCustomEncryptionSchema() {
264
311
  registerEncryptionOptOut(disable);
265
312
  }
266
313
 
314
+ // Load app-level extension encryption schemas. Before the module
315
+ // schemas: loadModuleEncryptionSchemas currently throws (see the
316
+ // NOTE inside it) and the throw would skip anything after it.
317
+ const { loadExtensions } = require('../../extensions/extension-loader');
318
+ const extensions = loadExtensions(appDefinition);
319
+ if (extensions.length > 0) {
320
+ loadExtensionEncryptionSchemas(extensions);
321
+ }
322
+
267
323
  // Load module-level encryption schemas from integrations
268
324
  const integrations = appDefinition.integrations;
269
- if (Array.isArray(integrations) || appDefinition.entities) {
270
- loadModuleEncryptionSchemas(
271
- Array.isArray(integrations) ? integrations : [],
272
- appDefinition.entities
273
- );
325
+ if (integrations && Array.isArray(integrations)) {
326
+ loadModuleEncryptionSchemas(integrations);
274
327
  }
275
328
  } catch (error) {
276
- // A bad entity registry is a configuration error, not "no custom schema".
277
- if (error instanceof EntityRegistryError) throw error;
278
329
  // Silently ignore errors - custom schema is optional
279
330
  // This handles cases like:
280
331
  // - Backend package.json not found (tests, standalone usage)
@@ -425,6 +476,7 @@ module.exports = {
425
476
  registerEncryptionOptOut,
426
477
  loadCustomEncryptionSchema,
427
478
  loadModuleEncryptionSchemas,
479
+ loadExtensionEncryptionSchemas,
428
480
  extractCredentialFieldsFromModules,
429
481
  validateCustomSchema,
430
482
  validateOptOut,
@@ -4,41 +4,8 @@
4
4
  * Infrastructure layer service that orchestrates field-level encryption/decryption.
5
5
  * Handles nested JSON paths (e.g., 'data.access_token') and bulk operations.
6
6
  */
7
- const { logger } = require('./logger');
8
- const { isDeployedRuntime } = require('./encryption-config');
9
-
10
- /**
11
- * Thrown when a value that looks like ciphertext cannot be decrypted in a
12
- * deployed runtime (a wrong, rotated or missing key). Returning the stored
13
- * ciphertext would hand it to API modules as if it were a token.
14
- */
15
- class FieldDecryptionError extends Error {
16
- constructor(message, options) {
17
- super(message, options);
18
- this.name = 'FieldDecryptionError';
19
- }
20
- }
21
-
22
- // Cryptor.encrypt() returns `${keyId}:${iv}:${ciphertext}:${encryptedKey}`:
23
- // keyId and encryptedKey are base64, iv is 16 bytes of hex, ciphertext is hex.
24
- // Plaintext with three colons (`https://user:pw@host:443`, `a:b:c:d`) must not
25
- // be mistaken for it.
26
- const BASE64_PART = /^[A-Za-z0-9+/]+={0,2}$/;
27
- const IV_PART = /^[0-9a-f]{32}$/i;
28
- const CIPHERTEXT_PART = /^(?:[0-9a-f]{2})+$/i;
29
-
30
7
  class FieldEncryptionService {
31
- /**
32
- * @param {Object} params
33
- * @param {Object} params.cryptor
34
- * @param {Object} params.schema
35
- * @param {() => boolean} [params.failClosedOnDecryptError] - whether a
36
- * ciphertext-shaped value that fails to decrypt throws. Defaults to
37
- * "running deployed" (encryption-config's isDeployedRuntime), read on
38
- * each failure. Locally such a value is returned as stored, with a
39
- * warning.
40
- */
41
- constructor({ cryptor, schema, failClosedOnDecryptError }) {
8
+ constructor({ cryptor, schema }) {
42
9
  if (!cryptor) {
43
10
  throw new Error('Cryptor instance required');
44
11
  }
@@ -48,10 +15,6 @@ class FieldEncryptionService {
48
15
 
49
16
  this.cryptor = cryptor;
50
17
  this.schema = schema;
51
- this.failClosedOnDecryptError =
52
- typeof failClosedOnDecryptError === 'function'
53
- ? failClosedOnDecryptError
54
- : () => isDeployedRuntime();
55
18
  }
56
19
 
57
20
  /**
@@ -134,33 +97,12 @@ class FieldEncryptionService {
134
97
  const decryptionPromises = fields.map(async (fieldPath) => {
135
98
  const value = this._getNestedValue(decrypted, fieldPath);
136
99
 
137
- if (!this._isEncrypted(value)) {
138
- return null;
139
- }
140
- try {
100
+ if (this._isEncrypted(value)) {
141
101
  const decryptedValue = await this.cryptor.decrypt(value);
142
102
  const deserializedValue = this._deserializeAfterDecryption(decryptedValue);
143
103
  return { fieldPath, decryptedValue: deserializedValue };
144
- } catch (error) {
145
- // Deployed: a ciphertext-shaped value under a wrong, rotated or
146
- // missing key fails the read rather than reaching an API
147
- // module as a token. Legacy plaintext never gets here: it does
148
- // not look like ciphertext (_isEncrypted).
149
- if (this.failClosedOnDecryptError()) {
150
- throw new FieldDecryptionError(
151
- `Could not decrypt ${modelName}.${fieldPath}`,
152
- { cause: error }
153
- );
154
- }
155
- // Local: a value that looks like ciphertext but is not is read
156
- // as it is stored. One such field must not fail the whole
157
- // read, findMany included.
158
- logger.warn(
159
- `Could not decrypt ${modelName}.${fieldPath}; returning the stored value`,
160
- { errorName: error?.name }
161
- );
162
- return null;
163
104
  }
105
+ return null;
164
106
  });
165
107
 
166
108
  const results = await Promise.all(decryptionPromises);
@@ -210,13 +152,7 @@ class FieldEncryptionService {
210
152
  }
211
153
 
212
154
  const parts = value.split(':');
213
- return (
214
- parts.length === 4 &&
215
- BASE64_PART.test(parts[0]) &&
216
- IV_PART.test(parts[1]) &&
217
- CIPHERTEXT_PART.test(parts[2]) &&
218
- BASE64_PART.test(parts[3])
219
- );
155
+ return parts.length >= 4;
220
156
  }
221
157
 
222
158
  _getNestedValue(obj, path) {
@@ -315,4 +251,4 @@ class FieldEncryptionService {
315
251
  }
316
252
  }
317
253
 
318
- module.exports = { FieldEncryptionService, FieldDecryptionError };
254
+ module.exports = { FieldEncryptionService };
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The Prisma `where` fragment for an `organizationId` on MongoDB (ADR-056
3
+ * §3.6), shared by the entity and integration adapters.
4
+ *
5
+ * Prisma on MongoDB: `null` matches only an explicit null and `isSet: false`
6
+ * only a missing field. A row written before the column existed is the common
7
+ * "no organization" case, so `null` here means both.
8
+ */
9
+ function organizationWhere(organizationId) {
10
+ if (organizationId === null) {
11
+ return {
12
+ OR: [{ organizationId: null }, { organizationId: { isSet: false } }],
13
+ };
14
+ }
15
+ return { organizationId };
16
+ }
17
+
18
+ module.exports = { organizationWhere };
@@ -41,13 +41,15 @@ const prismaClientSingleton = () => {
41
41
  const paths = [
42
42
  // Lambda layer location (when using Prisma Lambda layer)
43
43
  `/opt/nodejs/node_modules/generated/prisma-${dbType}`,
44
+ // __dirname-based absolute path (Netlify functions and bundlers)
45
+ require('node:path').resolve(__dirname, `../generated/prisma-${dbType}`),
44
46
  // Local development location (relative to core package)
45
47
  `../generated/prisma-${dbType}`,
46
48
  ];
47
49
 
48
- for (const path of paths) {
50
+ for (const candidate of paths) {
49
51
  try {
50
- return require(path).PrismaClient;
52
+ return require(candidate).PrismaClient;
51
53
  } catch (err) {
52
54
  // Continue to next path
53
55
  }
@@ -0,0 +1,25 @@
1
+ /** Mongo/DocumentDB duplicate-key error code. */
2
+ const DUPLICATE_KEY_CODE = 11000;
3
+ /** Prisma's unique-constraint error code (PostgreSQL and MongoDB). */
4
+ const PRISMA_UNIQUE_CODE = 'P2002';
5
+
6
+ /**
7
+ * Whether `error` is a unique-constraint violation, however the database
8
+ * layer raised it: a Prisma `P2002`, or a duplicate-key `11000`
9
+ * (`documentdb-utils` `insertOne` sets `code` on the error it throws).
10
+ * Matches on the code only, never on message text.
11
+ *
12
+ * @param {unknown} error
13
+ * @returns {boolean}
14
+ */
15
+ function isUniqueViolation(error) {
16
+ return (
17
+ error?.code === PRISMA_UNIQUE_CODE || error?.code === DUPLICATE_KEY_CODE
18
+ );
19
+ }
20
+
21
+ module.exports = {
22
+ isUniqueViolation,
23
+ DUPLICATE_KEY_CODE,
24
+ PRISMA_UNIQUE_CODE,
25
+ };
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Bootstrap Runner
3
+ *
4
+ * Runs extension bootstrap functions in sequence.
5
+ * Bootstrap hooks execute AFTER database connection but BEFORE integration
6
+ * router creation. This is the right place for extensions to:
7
+ *
8
+ * - Load credentials from database into integration definitions
9
+ * - Register additional middleware or services
10
+ * - Perform one-time initialization
11
+ *
12
+ * @example
13
+ * await runExtensionBootstraps(extensions, { prisma, appDefinition });
14
+ */
15
+
16
+ /**
17
+ * Runs all extension bootstrap functions in sequence.
18
+ *
19
+ * @param {Array<Object>} extensions - Normalized extensions (from extension-loader)
20
+ * @param {Object} context
21
+ * @param {Object} context.prisma - Prisma client instance
22
+ * @param {Object} context.appDefinition - Full app definition
23
+ * @throws {Error} If any bootstrap function fails (fails fast)
24
+ */
25
+ async function runExtensionBootstraps(extensions, context = {}) {
26
+ if (!extensions || extensions.length === 0) return;
27
+
28
+ const { prisma, appDefinition } = context;
29
+
30
+ for (const ext of extensions) {
31
+ if (!ext.bootstrap) continue;
32
+
33
+ try {
34
+ await ext.bootstrap(prisma, appDefinition);
35
+ } catch (error) {
36
+ throw new Error(
37
+ `Extension "${ext.name}" bootstrap failed: ${error.message}`
38
+ );
39
+ }
40
+ }
41
+ }
42
+
43
+ module.exports = { runExtensionBootstraps };