@friggframework/core 2.0.0--canary.704.79d9a63.0 → 2.0.0--canary.680.daae24e.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 (117) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/CLAUDE.md +0 -40
  3. package/application/commands/entity-commands.js +60 -18
  4. package/application/commands/integration-commands.js +18 -71
  5. package/application/index.js +6 -2
  6. package/credential/repositories/credential-repository-documentdb.js +34 -0
  7. package/credential/repositories/credential-repository-interface.js +15 -0
  8. package/credential/repositories/credential-repository-mongo.js +23 -0
  9. package/credential/repositories/credential-repository-postgres.js +28 -0
  10. package/credential/use-cases/credential-operations-for-user.js +117 -0
  11. package/credential/use-cases/reauthorize-credential-for-user.js +66 -0
  12. package/database/documentdb-encryption-service.js +9 -22
  13. package/database/documentdb-utils.js +1 -4
  14. package/database/encryption/README.md +78 -14
  15. package/database/encryption/documentdb-encryption-service.md +78 -1
  16. package/database/encryption/encryption-config.js +240 -0
  17. package/database/encryption/encryption-schema-registry.js +41 -12
  18. package/database/encryption/field-encryption-service.js +69 -5
  19. package/database/encryption/integration-mapping-encryption.js +1 -1
  20. package/database/encryption/test-support/fake-ciphertext.js +15 -0
  21. package/database/prisma.js +11 -36
  22. package/database/use-cases/check-encryption-health-use-case.js +43 -52
  23. package/errors/index.js +0 -4
  24. package/generated/prisma-mongodb/edge.js +20 -4
  25. package/generated/prisma-mongodb/index-browser.js +17 -1
  26. package/generated/prisma-mongodb/index.d.ts +1543 -95
  27. package/generated/prisma-mongodb/index.js +20 -4
  28. package/generated/prisma-mongodb/package.json +1 -1
  29. package/generated/prisma-mongodb/schema.prisma +27 -0
  30. package/generated/prisma-mongodb/wasm.js +20 -4
  31. package/generated/prisma-postgresql/edge.js +20 -4
  32. package/generated/prisma-postgresql/index-browser.js +17 -1
  33. package/generated/prisma-postgresql/index.d.ts +1570 -89
  34. package/generated/prisma-postgresql/index.js +20 -4
  35. package/generated/prisma-postgresql/package.json +1 -1
  36. package/generated/prisma-postgresql/schema.prisma +26 -0
  37. package/generated/prisma-postgresql/wasm.js +20 -4
  38. package/handlers/WEBHOOKS.md +0 -29
  39. package/handlers/app-definition-loader.js +19 -8
  40. package/handlers/app-handler-helpers.js +25 -3
  41. package/handlers/backend-utils.js +31 -25
  42. package/handlers/middleware/admin-auth.js +14 -1
  43. package/handlers/routers/auth.js +11 -3
  44. package/handlers/routers/health.js +11 -4
  45. package/handlers/workers/integration-defined-workers.js +5 -2
  46. package/index.js +4 -4
  47. package/integrations/index.js +0 -4
  48. package/integrations/integration-base.js +0 -29
  49. package/integrations/integration-router.js +16 -23
  50. package/integrations/repositories/integration-mapping-repository-documentdb.js +0 -50
  51. package/integrations/repositories/integration-mapping-repository-interface.js +0 -15
  52. package/integrations/repositories/integration-mapping-repository-mongo.js +0 -29
  53. package/integrations/repositories/integration-mapping-repository-postgres.js +0 -30
  54. package/integrations/repositories/integration-mapping-repository.js +0 -29
  55. package/integrations/repositories/integration-repository-documentdb.js +0 -32
  56. package/integrations/repositories/integration-repository-interface.js +0 -30
  57. package/integrations/repositories/integration-repository-mongo.js +1 -53
  58. package/integrations/repositories/integration-repository-postgres.js +0 -58
  59. package/integrations/repositories/process-repository-mongo.js +1 -1
  60. package/integrations/use-cases/create-integration.js +19 -57
  61. package/integrations/use-cases/integration-operations-for-user.js +225 -0
  62. package/integrations/utils/map-integration-dto.js +1 -15
  63. package/management-api/create-management-api-router.js +49 -0
  64. package/management-api/error-response.js +116 -0
  65. package/management-api/management-api-config.js +82 -0
  66. package/management-api/meta-router.js +57 -0
  67. package/management-api/openapi/build-openapi.js +144 -0
  68. package/management-api/openapi/components.js +368 -0
  69. package/management-api/openapi/v1-operations.js +83 -0
  70. package/management-api/openapi/v2-operations.js +252 -0
  71. package/management-api/route-registry.js +294 -0
  72. package/management-api/test-support/http-client.js +39 -0
  73. package/management-api/use-cases/get-management-api-meta.js +57 -0
  74. package/management-api/v1-deprecation.js +120 -0
  75. package/management-api/v2/create-v2-router.js +85 -0
  76. package/management-api/v2/dependencies.js +256 -0
  77. package/management-api/v2/dto.js +123 -0
  78. package/management-api/v2/handlers/authorization.js +93 -0
  79. package/management-api/v2/handlers/credentials.js +29 -0
  80. package/management-api/v2/handlers/entities.js +74 -0
  81. package/management-api/v2/handlers/integrations.js +125 -0
  82. package/management-api/v2/handlers/proxy.js +34 -0
  83. package/management-api/v2/request.js +54 -0
  84. package/management-api/v2/test-support/fake-dependencies.js +103 -0
  85. package/modules/domain/authorization-session.js +144 -0
  86. package/modules/entity-type-registry.js +311 -0
  87. package/modules/index.js +6 -0
  88. package/modules/proxy/proxy-errors.js +20 -0
  89. package/modules/proxy/proxy-path.js +179 -0
  90. package/modules/proxy/proxy-policy.js +248 -0
  91. package/modules/repositories/authorization-session-repository-documentdb.js +112 -0
  92. package/modules/repositories/authorization-session-repository-factory.js +31 -0
  93. package/modules/repositories/authorization-session-repository-interface.js +47 -0
  94. package/modules/repositories/authorization-session-repository-prisma.js +87 -0
  95. package/modules/requester/proxy-request.js +244 -0
  96. package/modules/requester/requester.js +27 -2
  97. package/modules/tests/doubles/in-memory-authorization-session-repository.js +45 -0
  98. package/modules/use-cases/entity-operations-for-user.js +125 -0
  99. package/modules/use-cases/entity-types.js +115 -0
  100. package/modules/use-cases/execute-entity-proxy-request.js +239 -0
  101. package/modules/use-cases/get-authorization-requirements.js +100 -0
  102. package/modules/use-cases/get-entity-module-for-user.js +86 -0
  103. package/modules/use-cases/multi-step-authorization.js +302 -0
  104. package/modules/utils/map-module-dto.js +3 -5
  105. package/package.json +5 -5
  106. package/prisma-mongodb/schema.prisma +27 -0
  107. package/prisma-postgresql/migrations/20261003000000_add_authorization_session/migration.sql +28 -0
  108. package/prisma-postgresql/schema.prisma +26 -0
  109. package/types/index.d.ts +1 -0
  110. package/types/modules/index.d.ts +58 -0
  111. package/user/tests/doubles/test-user-repository.js +1 -1
  112. package/user/use-cases/get-user-from-bearer-token.js +2 -7
  113. package/errors/mapping-already-exists-error.js +0 -14
  114. package/integrations/use-cases/add-entities-to-integration.js +0 -92
  115. package/integrations/use-cases/remove-entities-from-integration.js +0 -70
  116. package/integrations/utils/assert-entity-ids-input.js +0 -42
  117. package/modules/utils/to-credential-id.js +0 -14
@@ -4,8 +4,41 @@
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
+
7
30
  class FieldEncryptionService {
8
- constructor({ cryptor, schema }) {
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 }) {
9
42
  if (!cryptor) {
10
43
  throw new Error('Cryptor instance required');
11
44
  }
@@ -15,6 +48,10 @@ class FieldEncryptionService {
15
48
 
16
49
  this.cryptor = cryptor;
17
50
  this.schema = schema;
51
+ this.failClosedOnDecryptError =
52
+ typeof failClosedOnDecryptError === 'function'
53
+ ? failClosedOnDecryptError
54
+ : () => isDeployedRuntime();
18
55
  }
19
56
 
20
57
  /**
@@ -97,12 +134,33 @@ class FieldEncryptionService {
97
134
  const decryptionPromises = fields.map(async (fieldPath) => {
98
135
  const value = this._getNestedValue(decrypted, fieldPath);
99
136
 
100
- if (this._isEncrypted(value)) {
137
+ if (!this._isEncrypted(value)) {
138
+ return null;
139
+ }
140
+ try {
101
141
  const decryptedValue = await this.cryptor.decrypt(value);
102
142
  const deserializedValue = this._deserializeAfterDecryption(decryptedValue);
103
143
  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;
104
163
  }
105
- return null;
106
164
  });
107
165
 
108
166
  const results = await Promise.all(decryptionPromises);
@@ -152,7 +210,13 @@ class FieldEncryptionService {
152
210
  }
153
211
 
154
212
  const parts = value.split(':');
155
- return parts.length >= 4;
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
+ );
156
220
  }
157
221
 
158
222
  _getNestedValue(obj, path) {
@@ -251,4 +315,4 @@ class FieldEncryptionService {
251
315
  }
252
316
  }
253
317
 
254
- module.exports = { FieldEncryptionService };
318
+ module.exports = { FieldEncryptionService, FieldDecryptionError };
@@ -1,4 +1,4 @@
1
- const { getEncryptionConfig } = require('../prisma');
1
+ const { getEncryptionConfig } = require('./encryption-config');
2
2
  const { Cryptor } = require('../../encrypt/Cryptor');
3
3
  const {
4
4
  getFieldsToDecryptOnRead,
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Test double for Cryptor output. Same shape as the real thing
3
+ * (`keyId:iv:ciphertext:encryptedKey`: base64, 16-byte hex, hex, base64) so
4
+ * FieldEncryptionService._isEncrypted accepts it, with the plaintext
5
+ * recoverable for the fake decrypt.
6
+ */
7
+ const fakeCiphertext = (plain) =>
8
+ `a2V5SWQ=:${'0'.repeat(32)}:${Buffer.from(String(plain)).toString(
9
+ 'hex'
10
+ )}:ZW5jS2V5`;
11
+
12
+ const fakePlaintext = (ciphertext) =>
13
+ Buffer.from(String(ciphertext).split(':')[2], 'hex').toString();
14
+
15
+ module.exports = { fakeCiphertext, fakePlaintext };
@@ -4,6 +4,7 @@ const {
4
4
  const { loadCustomEncryptionSchema } = require('./encryption/encryption-schema-registry');
5
5
  const { logger } = require('./encryption/logger');
6
6
  const { Cryptor } = require('../encrypt/Cryptor');
7
+ const { getEncryptionConfig } = require('./encryption/encryption-config');
7
8
  const config = require('./config');
8
9
 
9
10
  /**
@@ -32,33 +33,6 @@ function ensureMongoDbUrl() {
32
33
  );
33
34
  }
34
35
 
35
- function getEncryptionConfig() {
36
- const STAGE = process.env.STAGE || process.env.NODE_ENV || 'development';
37
- const shouldBypassEncryption = ['dev', 'test', 'local'].includes(STAGE);
38
-
39
- if (shouldBypassEncryption) {
40
- return { enabled: false };
41
- }
42
-
43
- const hasKMS =
44
- process.env.KMS_KEY_ARN && process.env.KMS_KEY_ARN.trim() !== '';
45
- const hasAES =
46
- process.env.AES_KEY_ID && process.env.AES_KEY_ID.trim() !== '';
47
-
48
- if (!hasKMS && !hasAES) {
49
- logger.warn(
50
- 'No encryption keys configured (KMS_KEY_ARN or AES_KEY_ID). ' +
51
- 'Field-level encryption disabled. Set STAGE=production and configure keys to enable.'
52
- );
53
- return { enabled: false };
54
- }
55
-
56
- return {
57
- enabled: true,
58
- method: hasKMS ? 'kms' : 'aes',
59
- };
60
- }
61
-
62
36
  const prismaClientSingleton = () => {
63
37
  let PrismaClient;
64
38
 
@@ -103,9 +77,13 @@ const prismaClientSingleton = () => {
103
77
  errorFormat: 'pretty',
104
78
  });
105
79
 
80
+ // Throws when a deployed runtime has no encryption key: the app must not
81
+ // start and write sensitive fields in plaintext.
106
82
  const encryptionConfig = getEncryptionConfig();
107
83
 
108
84
  if (encryptionConfig.enabled) {
85
+ // Fail closed: if the extension cannot be installed, do not hand out
86
+ // a client that would write plaintext.
109
87
  try {
110
88
  // Load custom encryption schema from appDefinition before creating extension
111
89
  loadCustomEncryptionSchema();
@@ -120,17 +98,14 @@ const prismaClientSingleton = () => {
120
98
  enabled: true,
121
99
  })
122
100
  );
123
-
124
- logger.info(
125
- `Field-level encryption enabled using ${encryptionConfig.method.toUpperCase()}`
126
- );
127
101
  } catch (error) {
128
- logger.error(
129
- 'Failed to initialize encryption extension:',
130
- error
131
- );
132
- logger.warn('Continuing without encryption...');
102
+ logger.error('Failed to initialize encryption extension:', error);
103
+ throw error;
133
104
  }
105
+
106
+ logger.info(
107
+ `Field-level encryption enabled using ${encryptionConfig.method.toUpperCase()}`
108
+ );
134
109
  } else {
135
110
  logger.info('Field-level encryption disabled');
136
111
  }
@@ -1,3 +1,12 @@
1
+ const {
2
+ resolveEncryptionConfig,
3
+ OPT_OUT_VAR,
4
+ } = require('../encryption/encryption-config');
5
+
6
+ /**
7
+ * Reports whether field-level encryption is on and working, using the same
8
+ * rule the Prisma client applies at startup (encryption/encryption-config.js).
9
+ */
1
10
  class CheckEncryptionHealthUseCase {
2
11
  constructor({ testEncryptionUseCase }) {
3
12
  this.testEncryptionUseCase = testEncryptionUseCase;
@@ -5,78 +14,60 @@ class CheckEncryptionHealthUseCase {
5
14
 
6
15
  async execute() {
7
16
  const config = this._getEncryptionConfiguration();
17
+ const summary = {
18
+ mode: config.mode,
19
+ bypassed: config.bypassed,
20
+ optedOut: config.optedOut,
21
+ runtime: config.runtime,
22
+ stage: config.stage,
23
+ debug: {
24
+ hasKMS: config.hasKMS,
25
+ hasAES: config.hasAES,
26
+ },
27
+ };
8
28
 
9
- if (config.isBypassed || config.mode === 'none') {
10
- const testResult = config.isBypassed
11
- ? 'Encryption bypassed for this stage'
12
- : 'No encryption keys configured';
29
+ if (config.error) {
30
+ return {
31
+ status: 'unhealthy',
32
+ ...summary,
33
+ testResult: config.error,
34
+ encryptionWorks: false,
35
+ };
36
+ }
13
37
 
38
+ if (!config.enabled) {
14
39
  return {
15
40
  status: 'disabled',
16
- mode: config.mode,
17
- bypassed: config.isBypassed,
18
- stage: config.stage,
19
- testResult,
41
+ ...summary,
42
+ testResult: this._disabledReason(config),
20
43
  encryptionWorks: false,
21
- debug: {
22
- hasKMS: config.hasKMS,
23
- hasAES: config.hasAES,
24
- },
25
44
  };
26
45
  }
27
46
 
28
47
  try {
29
48
  const testResults = await this.testEncryptionUseCase.execute();
30
-
31
- return {
32
- ...testResults,
33
- mode: config.mode,
34
- bypassed: config.isBypassed,
35
- stage: config.stage,
36
- debug: {
37
- hasKMS: config.hasKMS,
38
- hasAES: config.hasAES,
39
- },
40
- };
49
+ return { ...testResults, ...summary };
41
50
  } catch (error) {
42
51
  return {
43
52
  status: 'unhealthy',
44
- mode: config.mode,
45
- bypassed: config.isBypassed,
46
- stage: config.stage,
53
+ ...summary,
47
54
  testResult: `Encryption test failed: ${error.message}`,
48
55
  encryptionWorks: false,
49
- debug: {
50
- hasKMS: config.hasKMS,
51
- hasAES: config.hasAES,
52
- },
53
56
  };
54
57
  }
55
58
  }
56
59
 
57
- _getEncryptionConfiguration() {
58
- const { STAGE, BYPASS_ENCRYPTION_STAGE, KMS_KEY_ARN, AES_KEY_ID } =
59
- process.env;
60
-
61
- const defaultBypassStages = ['dev', 'test', 'local'];
62
- const useEnv = BYPASS_ENCRYPTION_STAGE !== undefined;
63
- const bypassStages = useEnv
64
- ? BYPASS_ENCRYPTION_STAGE.split(',').map((s) => s.trim())
65
- : defaultBypassStages;
66
-
67
- const isBypassed = bypassStages.includes(STAGE);
68
- const hasAES = AES_KEY_ID && AES_KEY_ID.trim() !== '';
69
- const hasKMS = KMS_KEY_ARN && KMS_KEY_ARN.trim() !== '';
70
- // Prefer KMS over AES when both are configured (KMS is more secure)
71
- const mode = hasKMS ? 'kms' : hasAES ? 'aes' : 'none';
60
+ _disabledReason(config) {
61
+ if (config.bypassed) return 'Encryption bypassed for this stage';
62
+ if (config.optedOut) {
63
+ return `Encryption explicitly disabled (${OPT_OUT_VAR}=true); sensitive fields are stored in plaintext`;
64
+ }
65
+ return 'No encryption keys configured';
66
+ }
72
67
 
73
- return {
74
- stage: STAGE || null,
75
- isBypassed,
76
- hasAES,
77
- hasKMS,
78
- mode,
79
- };
68
+ _getEncryptionConfiguration() {
69
+ const config = resolveEncryptionConfig(process.env);
70
+ return { ...config, stage: process.env.STAGE || null };
80
71
  }
81
72
  }
82
73
 
package/errors/index.js CHANGED
@@ -6,9 +6,6 @@ const {
6
6
  ParameterTypeError,
7
7
  } = require('./validation-errors');
8
8
  const { ClientSafeError } = require('./client-safe-error');
9
- const {
10
- MappingAlreadyExistsError,
11
- } = require('./mapping-already-exists-error');
12
9
 
13
10
  module.exports = {
14
11
  BaseError,
@@ -17,5 +14,4 @@ module.exports = {
17
14
  RequiredPropertyError,
18
15
  ParameterTypeError,
19
16
  ClientSafeError,
20
- MappingAlreadyExistsError,
21
17
  };