@friggframework/core 2.0.0--canary.686.df38e8e.0 → 2.0.0--canary.710.9045bbc.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 (217) hide show
  1. package/CHANGELOG.md +0 -16
  2. package/CLAUDE.md +41 -29
  3. package/README.md +0 -105
  4. package/application/commands/README.md +17 -11
  5. package/application/commands/entity-commands.js +18 -60
  6. package/application/commands/integration-commands.js +73 -20
  7. package/application/commands/scheduler-commands.js +7 -11
  8. package/application/commands/user-commands.js +5 -17
  9. package/application/index.js +2 -6
  10. package/core/Worker.js +7 -31
  11. package/core/create-handler.js +0 -9
  12. package/credential/repositories/credential-repository-documentdb.js +0 -34
  13. package/credential/repositories/credential-repository-interface.js +0 -15
  14. package/credential/repositories/credential-repository-mongo.js +0 -23
  15. package/credential/repositories/credential-repository-postgres.js +0 -28
  16. package/database/config.js +24 -48
  17. package/database/documentdb-encryption-service.js +22 -9
  18. package/database/documentdb-utils.js +0 -2
  19. package/database/encryption/README.md +17 -81
  20. package/database/encryption/documentdb-encryption-service.md +1 -78
  21. package/database/encryption/encryption-schema-registry.js +46 -123
  22. package/database/encryption/field-encryption-service.js +5 -69
  23. package/database/encryption/integration-mapping-encryption.js +1 -1
  24. package/database/prisma.js +38 -15
  25. package/database/use-cases/check-encryption-health-use-case.js +52 -43
  26. package/errors/index.js +4 -0
  27. package/errors/mapping-already-exists-error.js +14 -0
  28. package/generated/prisma-mongodb/edge.js +4 -43
  29. package/generated/prisma-mongodb/index-browser.js +1 -40
  30. package/generated/prisma-mongodb/index.d.ts +111 -4739
  31. package/generated/prisma-mongodb/index.js +4 -43
  32. package/generated/prisma-mongodb/package.json +1 -1
  33. package/generated/prisma-mongodb/schema.prisma +0 -92
  34. package/generated/prisma-mongodb/wasm.js +4 -43
  35. package/generated/prisma-postgresql/edge.js +4 -43
  36. package/generated/prisma-postgresql/index-browser.js +1 -40
  37. package/generated/prisma-postgresql/index.d.ts +33 -4966
  38. package/generated/prisma-postgresql/index.js +4 -43
  39. package/generated/prisma-postgresql/package.json +1 -1
  40. package/generated/prisma-postgresql/schema.prisma +0 -87
  41. package/generated/prisma-postgresql/wasm.js +4 -43
  42. package/handlers/WEBHOOKS.md +29 -0
  43. package/handlers/app-definition-loader.js +19 -121
  44. package/handlers/app-handler-helpers.js +3 -25
  45. package/handlers/backend-utils.js +25 -31
  46. package/handlers/middleware/admin-auth.js +1 -14
  47. package/handlers/routers/auth.js +10 -46
  48. package/handlers/routers/health.js +4 -13
  49. package/handlers/routers/integration-defined-routers.js +92 -144
  50. package/handlers/routers/integration-webhook-routers.js +64 -102
  51. package/handlers/workers/integration-defined-workers.js +2 -5
  52. package/index.js +3 -65
  53. package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +67 -13
  54. package/infrastructure/scheduler/index.js +6 -19
  55. package/infrastructure/scheduler/scheduler-service-factory.js +7 -55
  56. package/integrations/index.js +0 -1
  57. package/integrations/integration-base.js +29 -0
  58. package/integrations/integration-router.js +96 -131
  59. package/integrations/repositories/integration-mapping-repository-documentdb.js +50 -0
  60. package/integrations/repositories/integration-mapping-repository-interface.js +15 -0
  61. package/integrations/repositories/integration-mapping-repository-mongo.js +29 -0
  62. package/integrations/repositories/integration-mapping-repository-postgres.js +30 -0
  63. package/integrations/repositories/integration-mapping-repository.js +29 -0
  64. package/integrations/repositories/integration-repository-documentdb.js +35 -35
  65. package/integrations/repositories/integration-repository-interface.js +31 -17
  66. package/integrations/repositories/integration-repository-mongo.js +129 -60
  67. package/integrations/repositories/integration-repository-postgres.js +134 -62
  68. package/integrations/repositories/process-repository-mongo.js +1 -1
  69. package/integrations/tests/doubles/test-integration-repository.js +1 -12
  70. package/integrations/use-cases/add-entities-to-integration.js +92 -0
  71. package/integrations/use-cases/create-integration.js +75 -72
  72. package/integrations/use-cases/get-integrations-for-user.js +40 -80
  73. package/integrations/use-cases/index.js +1 -7
  74. package/integrations/use-cases/remove-entities-from-integration.js +70 -0
  75. package/integrations/utils/assert-entity-ids-input.js +42 -0
  76. package/integrations/utils/map-integration-dto.js +14 -43
  77. package/jest-setup.js +13 -2
  78. package/jest-teardown.js +5 -2
  79. package/jest.config.js +4 -0
  80. package/jest.db.config.js +23 -0
  81. package/modules/index.js +0 -14
  82. package/modules/module-factory.js +0 -12
  83. package/modules/module.js +2 -53
  84. package/modules/repositories/module-repository-documentdb.js +6 -51
  85. package/modules/repositories/module-repository-interface.js +2 -19
  86. package/modules/repositories/module-repository-mongo.js +74 -67
  87. package/modules/repositories/module-repository-postgres.js +74 -66
  88. package/modules/repositories/module-repository.js +1 -2
  89. package/modules/requester/requester.js +2 -27
  90. package/modules/use-cases/get-entities-for-user.js +13 -26
  91. package/modules/use-cases/get-entity-options-by-id.js +4 -10
  92. package/modules/use-cases/get-entity-options-by-type.js +1 -1
  93. package/modules/use-cases/get-module-instance-from-type.js +1 -1
  94. package/modules/use-cases/get-module.js +4 -10
  95. package/modules/use-cases/process-authorization-callback.js +19 -53
  96. package/modules/use-cases/refresh-entity-options.js +4 -10
  97. package/modules/use-cases/test-module-auth.js +4 -10
  98. package/modules/utils/map-module-dto.js +5 -3
  99. package/modules/utils/to-credential-id.js +14 -0
  100. package/package.json +7 -6
  101. package/prisma-mongodb/schema.prisma +0 -92
  102. package/prisma-postgresql/schema.prisma +0 -87
  103. package/queues/index.js +0 -25
  104. package/queues/queuer-util.js +6 -5
  105. package/types/index.d.ts +0 -2
  106. package/user/repositories/user-repository-documentdb.js +2 -27
  107. package/user/repositories/user-repository-interface.js +0 -18
  108. package/user/repositories/user-repository-mongo.js +0 -24
  109. package/user/repositories/user-repository-postgres.js +0 -18
  110. package/user/tests/doubles/test-user-repository.js +1 -1
  111. package/user/use-cases/authenticate-user.js +1 -7
  112. package/user/use-cases/get-user-from-adopter-jwt.js +124 -95
  113. package/user/use-cases/get-user-from-bearer-token.js +7 -2
  114. package/user/use-cases/get-user-from-x-frigg-headers.js +80 -83
  115. package/user/user.js +1 -64
  116. package/credential/use-cases/credential-operations-for-user.js +0 -202
  117. package/credential/use-cases/reauthorize-credential-for-user.js +0 -73
  118. package/database/encryption/encryption-config.js +0 -219
  119. package/database/encryption/test-support/fake-ciphertext.js +0 -15
  120. package/database/organization-where.js +0 -18
  121. package/database/unique-violation.js +0 -25
  122. package/extensions/bootstrap-runner.js +0 -43
  123. package/extensions/extension-loader.js +0 -187
  124. package/extensions/index.js +0 -41
  125. package/extensions/initialize-app.js +0 -123
  126. package/extensions/route-mounter.js +0 -103
  127. package/extensions/schema-composer.js +0 -188
  128. package/infrastructure/scheduler/netlify-scheduler-adapter.js +0 -220
  129. package/infrastructure/scheduler/scheduled-job-repository.js +0 -118
  130. package/integrations/repositories/integration-not-found.js +0 -14
  131. package/integrations/schedule-config.js +0 -80
  132. package/integrations/use-cases/dispatch-ongoing-syncs.js +0 -100
  133. package/integrations/use-cases/integration-operations-for-user.js +0 -256
  134. package/integrations/use-cases/resolve-integration-ownership.js +0 -177
  135. package/management-api/create-management-api-router.js +0 -49
  136. package/management-api/error-response.js +0 -116
  137. package/management-api/management-api-config.js +0 -151
  138. package/management-api/meta-router.js +0 -76
  139. package/management-api/openapi/build-openapi.js +0 -144
  140. package/management-api/openapi/components.js +0 -408
  141. package/management-api/openapi/v1-operations.js +0 -83
  142. package/management-api/openapi/v2-operations.js +0 -264
  143. package/management-api/route-registry.js +0 -411
  144. package/management-api/test-support/http-client.js +0 -39
  145. package/management-api/use-cases/get-management-api-meta.js +0 -57
  146. package/management-api/v1-deprecation.js +0 -120
  147. package/management-api/v2/create-v2-router.js +0 -85
  148. package/management-api/v2/dependencies.js +0 -281
  149. package/management-api/v2/dto.js +0 -143
  150. package/management-api/v2/handlers/authorization.js +0 -94
  151. package/management-api/v2/handlers/credentials.js +0 -33
  152. package/management-api/v2/handlers/entities.js +0 -77
  153. package/management-api/v2/handlers/integrations.js +0 -128
  154. package/management-api/v2/handlers/proxy.js +0 -34
  155. package/management-api/v2/request.js +0 -85
  156. package/management-api/v2/test-support/fake-dependencies.js +0 -103
  157. package/modules/domain/authorization-session.js +0 -144
  158. package/modules/entity-scope.js +0 -15
  159. package/modules/entity-type-registry.js +0 -311
  160. package/modules/proxy/proxy-errors.js +0 -20
  161. package/modules/proxy/proxy-path.js +0 -179
  162. package/modules/proxy/proxy-policy.js +0 -248
  163. package/modules/repositories/authorization-session-repository-documentdb.js +0 -112
  164. package/modules/repositories/authorization-session-repository-factory.js +0 -31
  165. package/modules/repositories/authorization-session-repository-interface.js +0 -47
  166. package/modules/repositories/authorization-session-repository-prisma.js +0 -87
  167. package/modules/repositories/entity-not-found.js +0 -18
  168. package/modules/requester/proxy-request.js +0 -244
  169. package/modules/scope-config.js +0 -192
  170. package/modules/scope-policy.js +0 -112
  171. package/modules/scope-resolution.js +0 -288
  172. package/modules/scope-visibility.js +0 -247
  173. package/modules/tests/doubles/in-memory-authorization-session-repository.js +0 -45
  174. package/modules/tests/doubles/ownership-matching.js +0 -18
  175. package/modules/use-cases/authorize-entity-for-user.js +0 -61
  176. package/modules/use-cases/create-entity-from-credential.js +0 -113
  177. package/modules/use-cases/entity-operations-for-user.js +0 -162
  178. package/modules/use-cases/entity-types.js +0 -139
  179. package/modules/use-cases/execute-entity-proxy-request.js +0 -286
  180. package/modules/use-cases/get-authorization-requirements.js +0 -100
  181. package/modules/use-cases/get-entity-module-for-user.js +0 -113
  182. package/modules/use-cases/manage-access.js +0 -21
  183. package/modules/use-cases/multi-step-authorization.js +0 -329
  184. package/prisma-postgresql/migrations/20261003000000_add_authorization_session/migration.sql +0 -28
  185. package/prisma-postgresql/migrations/20261015000000_add_organization_membership/migration.sql +0 -26
  186. package/prisma-postgresql/migrations/20261016000000_add_entity_integration_organization/migration.sql +0 -25
  187. package/prisma-postgresql/migrations/20261017000000_add_scheduled_job/migration.sql +0 -28
  188. package/providers/index.js +0 -23
  189. package/providers/resolve-provider.js +0 -93
  190. package/providers/runtime-detection.js +0 -124
  191. package/queues/providers/index.js +0 -11
  192. package/queues/providers/netlify-background-provider.js +0 -187
  193. package/queues/providers/qstash-queue-provider.js +0 -219
  194. package/queues/providers/sqs-queue-provider.js +0 -70
  195. package/queues/queue-client-interface.js +0 -55
  196. package/queues/queue-message-auth.js +0 -193
  197. package/queues/queue-provider-factory.js +0 -101
  198. package/queues/queue-provider.js +0 -65
  199. package/queues/sqs-queue-client.js +0 -81
  200. package/types/modules/index.d.ts +0 -197
  201. package/types/user/index.d.ts +0 -134
  202. package/user/adopter-jwt-config.js +0 -177
  203. package/user/adopter-jwt-errors.js +0 -59
  204. package/user/adopter-token-verifier.js +0 -122
  205. package/user/app-user-helpers.js +0 -97
  206. package/user/create-user-authentication.js +0 -64
  207. package/user/membership.js +0 -51
  208. package/user/repositories/organization-membership-record.js +0 -19
  209. package/user/repositories/organization-membership-repository-documentdb.js +0 -106
  210. package/user/repositories/organization-membership-repository-factory.js +0 -42
  211. package/user/repositories/organization-membership-repository-interface.js +0 -57
  212. package/user/repositories/organization-membership-repository-mongo.js +0 -13
  213. package/user/repositories/organization-membership-repository-postgres.js +0 -29
  214. package/user/repositories/organization-membership-repository-prisma.js +0 -81
  215. package/user/tests/doubles/adopter-jwt-fixtures.js +0 -220
  216. package/user/use-cases/ensure-organization-membership.js +0 -92
  217. package/user/use-cases/find-individual-users-by-organization.js +0 -54
@@ -1,219 +0,0 @@
1
- /**
2
- * Field-level encryption configuration: decides whether sensitive fields are
3
- * encrypted, and with which key, from the process environment.
4
- *
5
- * The rule fails closed:
6
- *
7
- * - **Deployed** (running in AWS Lambda, and not under
8
- * serverless-offline, `serverless invoke local` or Jest): the stage name is
9
- * ignored. A configured key (KMS_KEY_ARN, or AES_KEY_ID with AES_KEY) turns
10
- * encryption on. With no key, the configuration is an error and the Prisma
11
- * client refuses to start, unless FRIGG_ENCRYPTION_DISABLED=true opts out
12
- * explicitly.
13
- * - **Local** (`frigg start`, tests, scripts on a laptop): the stages dev,
14
- * test and local skip encryption. Any other stage encrypts when a key is
15
- * configured and stays plaintext, with a warning, when none is.
16
- *
17
- * Every module that encrypts or reports on encryption reads this one rule.
18
- */
19
-
20
- const { logger } = require('./logger');
21
- const {
22
- isDeployedRuntime: isDeployedProviderRuntime,
23
- } = require('../../providers/runtime-detection');
24
-
25
- const LOCAL_BYPASS_STAGES = ['dev', 'test', 'local'];
26
- const OPT_OUT_VAR = 'FRIGG_ENCRYPTION_DISABLED';
27
-
28
- class EncryptionConfigurationError extends Error {
29
- constructor(message) {
30
- super(message);
31
- this.name = 'EncryptionConfigurationError';
32
- }
33
- }
34
-
35
- function isSet(value) {
36
- return typeof value === 'string' && value.trim() !== '';
37
- }
38
-
39
- function isTrue(value) {
40
- if (typeof value !== 'string') return false;
41
- const normalized = value.trim().toLowerCase();
42
- return normalized === 'true' || normalized === '1';
43
- }
44
-
45
- /**
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.
52
- *
53
- * @param {Object} [env=process.env]
54
- * @returns {boolean}
55
- */
56
- function isDeployedRuntime(env = process.env) {
57
- return isDeployedProviderRuntime(env);
58
- }
59
-
60
- function missingKeyMessage(stage) {
61
- return (
62
- `[Frigg] No field-level encryption key is configured for stage "${stage}". ` +
63
- 'A deployed Frigg app will not write credentials and other sensitive fields in plaintext. ' +
64
- "Fix: set encryption: { fieldLevelEncryptionMethod: 'kms' } in the app definition and redeploy " +
65
- '(Frigg creates or discovers a KMS key and sets KMS_KEY_ARN), ' +
66
- 'or provide AES_KEY_ID and AES_KEY (32 characters) in the Lambda environment. ' +
67
- `To run this stage without encryption on purpose, set ${OPT_OUT_VAR}=true ` +
68
- "(or encryption: { fieldLevelEncryptionMethod: 'none' } in the app definition)."
69
- );
70
- }
71
-
72
- function incompleteAesMessage(stage) {
73
- return (
74
- `[Frigg] AES_KEY_ID is set but AES_KEY is not (stage "${stage}"). ` +
75
- 'Provide AES_KEY (32 characters) alongside AES_KEY_ID, ' +
76
- "or use KMS with encryption: { fieldLevelEncryptionMethod: 'kms' }."
77
- );
78
- }
79
-
80
- /**
81
- * Resolves the encryption configuration without side effects.
82
- *
83
- * @param {Object} [env=process.env]
84
- * @returns {{
85
- * enabled: boolean,
86
- * method: 'kms'|'aes'|undefined,
87
- * mode: 'kms'|'aes'|'none',
88
- * runtime: 'deployed'|'local',
89
- * stage: string,
90
- * bypassed: boolean,
91
- * optedOut: boolean,
92
- * optOutIgnored: boolean,
93
- * hasKMS: boolean,
94
- * hasAES: boolean,
95
- * error: string|null,
96
- * }} `error` is set when a deployed runtime has no usable key.
97
- */
98
- function resolveEncryptionConfig(env = process.env) {
99
- const stage = env.STAGE || env.NODE_ENV || 'development';
100
- const runtime = isDeployedRuntime(env) ? 'deployed' : 'local';
101
- const hasKMS = isSet(env.KMS_KEY_ARN);
102
- const hasAES = isSet(env.AES_KEY_ID);
103
- const optOutRequested = isTrue(env[OPT_OUT_VAR]);
104
-
105
- const base = {
106
- enabled: false,
107
- method: undefined,
108
- mode: 'none',
109
- runtime,
110
- stage,
111
- bypassed: false,
112
- optedOut: false,
113
- optOutIgnored: false,
114
- hasKMS,
115
- hasAES,
116
- error: null,
117
- };
118
-
119
- if (runtime === 'local') {
120
- if (LOCAL_BYPASS_STAGES.includes(String(stage).toLowerCase())) {
121
- return { ...base, bypassed: true };
122
- }
123
- if (hasKMS || hasAES) {
124
- const method = hasKMS ? 'kms' : 'aes';
125
- return { ...base, enabled: true, method, mode: method };
126
- }
127
- return base;
128
- }
129
-
130
- const hasCompleteAES = hasAES && isSet(env.AES_KEY);
131
- if (hasKMS || hasCompleteAES) {
132
- const method = hasKMS ? 'kms' : 'aes';
133
- return {
134
- ...base,
135
- enabled: true,
136
- method,
137
- mode: method,
138
- optOutIgnored: optOutRequested,
139
- };
140
- }
141
-
142
- if (optOutRequested) {
143
- return { ...base, optedOut: true };
144
- }
145
-
146
- return {
147
- ...base,
148
- error: hasAES ? incompleteAesMessage(stage) : missingKeyMessage(stage),
149
- };
150
- }
151
-
152
- const warned = new Set();
153
-
154
- function warnOnce(key, message) {
155
- if (warned.has(key)) return;
156
- warned.add(key);
157
- logger.warn(message);
158
- }
159
-
160
- /**
161
- * Resolves the encryption configuration for use: throws when a deployed
162
- * runtime has no usable key, and warns once per process (once per Lambda
163
- * cold start) when encryption is explicitly disabled.
164
- *
165
- * @param {Object} [env=process.env]
166
- * @returns {ReturnType<typeof resolveEncryptionConfig>}
167
- * @throws {EncryptionConfigurationError}
168
- */
169
- function getEncryptionConfig(env = process.env) {
170
- const config = resolveEncryptionConfig(env);
171
-
172
- if (config.error) {
173
- throw new EncryptionConfigurationError(config.error);
174
- }
175
-
176
- if (config.optedOut) {
177
- warnOnce(
178
- 'opted-out',
179
- `[Frigg] ${OPT_OUT_VAR}=true: field-level encryption is OFF for stage "${config.stage}". ` +
180
- 'Credentials and other sensitive fields are stored in PLAINTEXT. ' +
181
- `Remove ${OPT_OUT_VAR} and configure a key (fieldLevelEncryptionMethod: 'kms') to encrypt them.`
182
- );
183
- }
184
-
185
- if (config.optOutIgnored) {
186
- warnOnce(
187
- 'opt-out-ignored',
188
- `[Frigg] ${OPT_OUT_VAR}=true is ignored because an encryption key is configured; ` +
189
- `fields are encrypted with ${config.method.toUpperCase()}. ` +
190
- 'Turning encryption off while a key is present would leave encrypted data unreadable.'
191
- );
192
- }
193
-
194
- if (config.runtime === 'local' && !config.enabled && !config.bypassed) {
195
- warnOnce(
196
- 'local-no-keys',
197
- `No encryption keys configured (KMS_KEY_ARN or AES_KEY_ID) for local stage "${config.stage}". ` +
198
- 'Field-level encryption disabled for this local run. ' +
199
- 'A deployed stage without a key refuses to start.'
200
- );
201
- }
202
-
203
- return config;
204
- }
205
-
206
- /** Test helper: let the once-per-process warnings fire again. */
207
- function resetEncryptionConfigWarnings() {
208
- warned.clear();
209
- }
210
-
211
- module.exports = {
212
- EncryptionConfigurationError,
213
- LOCAL_BYPASS_STAGES,
214
- OPT_OUT_VAR,
215
- getEncryptionConfig,
216
- isDeployedRuntime,
217
- resetEncryptionConfigWarnings,
218
- resolveEncryptionConfig,
219
- };
@@ -1,15 +0,0 @@
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 };
@@ -1,18 +0,0 @@
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 };
@@ -1,25 +0,0 @@
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
- };
@@ -1,43 +0,0 @@
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 };
@@ -1,187 +0,0 @@
1
- /**
2
- * Extension Loader
3
- *
4
- * Validates and normalizes the core extensions of the app definition
5
- * (`appDefinition.coreExtensions`, an array). Core extensions add custom
6
- * Prisma models, encryption schemas, admin routes and bootstrap logic to a
7
- * Frigg app. The key is `coreExtensions`, not `extensions`: ADR-017 keeps
8
- * `appDefinition.extensions` for its keyed object form.
9
- *
10
- * @example
11
- * const extensions = loadExtensions(appDefinition);
12
- * // extensions is a normalized array, safe to iterate
13
- */
14
-
15
- const path = require('path');
16
- const {
17
- coreExtensionRoutePathError,
18
- } = require('../management-api/route-registry');
19
-
20
- /**
21
- * Validates a single extension definition.
22
- * @param {Object} ext - Raw extension config from app definition
23
- * @param {number} index - Position in the coreExtensions array (for error messages)
24
- * @returns {{valid: boolean, errors: string[]}}
25
- */
26
- function validateExtension(ext, index) {
27
- const prefix = `coreExtensions[${index}]`;
28
- const errors = [];
29
-
30
- if (!ext || typeof ext !== 'object') {
31
- errors.push(`${prefix}: must be an object`);
32
- return { valid: false, errors };
33
- }
34
-
35
- if (!ext.name || typeof ext.name !== 'string') {
36
- errors.push(`${prefix}.name: required string`);
37
- }
38
-
39
- // schema is optional — path to a .prisma file
40
- if (ext.schema !== undefined) {
41
- if (typeof ext.schema !== 'string') {
42
- errors.push(`${prefix}.schema: must be a string (path to .prisma file)`);
43
- } else if (!ext.schema.endsWith('.prisma')) {
44
- errors.push(`${prefix}.schema: must end with .prisma`);
45
- }
46
- }
47
-
48
- // encryption is optional — object with model names → { fields: [...] }
49
- if (ext.encryption !== undefined) {
50
- if (!ext.encryption || typeof ext.encryption !== 'object') {
51
- errors.push(`${prefix}.encryption: must be an object`);
52
- } else {
53
- for (const [model, config] of Object.entries(ext.encryption)) {
54
- if (!config || !Array.isArray(config.fields)) {
55
- errors.push(
56
- `${prefix}.encryption.${model}: must have a "fields" array`
57
- );
58
- }
59
- }
60
- }
61
- }
62
-
63
- // routes is optional — { path, handler }
64
- if (ext.routes !== undefined) {
65
- if (!ext.routes || typeof ext.routes !== 'object') {
66
- errors.push(`${prefix}.routes: must be an object with { path, handler }`);
67
- } else {
68
- if (!ext.routes.path || typeof ext.routes.path !== 'string') {
69
- errors.push(`${prefix}.routes.path: required string`);
70
- } else {
71
- const pathError = coreExtensionRoutePathError(ext.routes.path);
72
- if (pathError) {
73
- errors.push(`${prefix}.routes.path: ${pathError}`);
74
- }
75
- }
76
- if (!ext.routes.handler) {
77
- errors.push(`${prefix}.routes.handler: required (function or module path)`);
78
- }
79
- }
80
- }
81
-
82
- // bootstrap is optional — function or module path
83
- if (ext.bootstrap !== undefined) {
84
- if (typeof ext.bootstrap !== 'function' && typeof ext.bootstrap !== 'string') {
85
- errors.push(
86
- `${prefix}.bootstrap: must be a function or a string (module path)`
87
- );
88
- }
89
- }
90
-
91
- return { valid: errors.length === 0, errors };
92
- }
93
-
94
- /**
95
- * Loads and validates extensions from the app definition.
96
- *
97
- * @param {Object} appDefinition - The full app definition
98
- * @returns {Array<Object>} Normalized extensions array (empty if none)
99
- * @throws {Error} If any extension fails validation
100
- */
101
- function loadExtensions(appDefinition) {
102
- if (!appDefinition) return [];
103
-
104
- // The array this loader reads used to be `appDefinition.extensions`;
105
- // that key now belongs to ADR-017's keyed object. An array there is the
106
- // old spelling: stop at load rather than silently dropping the extensions.
107
- if (Array.isArray(appDefinition.extensions)) {
108
- throw new Error(
109
- 'appDefinition.extensions (array) was renamed to appDefinition.coreExtensions; ' +
110
- 'move the array to coreExtensions'
111
- );
112
- }
113
-
114
- const raw = appDefinition.coreExtensions;
115
- if (!raw) return [];
116
-
117
- if (!Array.isArray(raw)) {
118
- throw new Error('appDefinition.coreExtensions must be an array');
119
- }
120
-
121
- if (raw.length === 0) return [];
122
-
123
- const allErrors = [];
124
-
125
- const normalized = raw.map((ext, index) => {
126
- const { valid, errors } = validateExtension(ext, index);
127
- if (!valid) {
128
- allErrors.push(...errors);
129
- return null;
130
- }
131
-
132
- // Normalize bootstrap — resolve string paths to functions
133
- let bootstrapFn = null;
134
- if (typeof ext.bootstrap === 'function') {
135
- bootstrapFn = ext.bootstrap;
136
- } else if (typeof ext.bootstrap === 'string') {
137
- bootstrapFn = require(ext.bootstrap);
138
- }
139
-
140
- // Normalize route handler — resolve string paths to functions
141
- let routeHandler = null;
142
- if (ext.routes) {
143
- if (typeof ext.routes.handler === 'function') {
144
- routeHandler = ext.routes.handler;
145
- } else if (typeof ext.routes.handler === 'string') {
146
- routeHandler = require(ext.routes.handler);
147
- } else {
148
- routeHandler = ext.routes.handler;
149
- }
150
- }
151
-
152
- return {
153
- name: ext.name,
154
- schema: ext.schema || null,
155
- encryption: ext.encryption || null,
156
- routes: ext.routes
157
- ? { path: ext.routes.path, handler: routeHandler }
158
- : null,
159
- bootstrap: bootstrapFn,
160
- };
161
- });
162
-
163
- if (allErrors.length > 0) {
164
- throw new Error(
165
- `Invalid extension configuration:\n- ${allErrors.join('\n- ')}`
166
- );
167
- }
168
-
169
- return normalized.filter(Boolean);
170
- }
171
-
172
- /**
173
- * Get extension schema file paths from loaded extensions.
174
- * @param {Array<Object>} extensions - Normalized extensions
175
- * @returns {string[]} Array of absolute paths to .prisma schema files
176
- */
177
- function getExtensionSchemaPaths(extensions) {
178
- return extensions
179
- .filter((ext) => ext.schema)
180
- .map((ext) => ext.schema);
181
- }
182
-
183
- module.exports = {
184
- loadExtensions,
185
- validateExtension,
186
- getExtensionSchemaPaths,
187
- };
@@ -1,41 +0,0 @@
1
- /**
2
- * Frigg Extension System
3
- *
4
- * Extensions allow integration developers to extend Frigg Core with:
5
- * - Custom Prisma models (schema composition)
6
- * - Encrypted fields (encryption registry merge)
7
- * - Admin API routes (route mounting)
8
- * - Bootstrap lifecycle hooks (credential loading, etc.)
9
- *
10
- * @module @friggframework/core/extensions
11
- */
12
-
13
- const { loadExtensions, validateExtension, getExtensionSchemaPaths } = require('./extension-loader');
14
- const { composeSchemas, extractModelBlocks, getSchemaFilePaths } = require('./schema-composer');
15
- const {
16
- mountExtensionRoutes,
17
- createExtensionRoutesRouter,
18
- } = require('./route-mounter');
19
- const { runExtensionBootstraps } = require('./bootstrap-runner');
20
- const { initializeApp, resetInitialization } = require('./initialize-app');
21
-
22
- module.exports = {
23
- // Extension loading & validation
24
- loadExtensions,
25
- validateExtension,
26
- getExtensionSchemaPaths,
27
-
28
- // Schema composition
29
- composeSchemas,
30
- extractModelBlocks,
31
- getSchemaFilePaths,
32
-
33
- // Route mounting
34
- mountExtensionRoutes,
35
- createExtensionRoutesRouter,
36
-
37
- // Bootstrap lifecycle
38
- runExtensionBootstraps,
39
- initializeApp,
40
- resetInitialization,
41
- };
@@ -1,123 +0,0 @@
1
- /**
2
- * Application Initialization with Extension Lifecycle
3
- *
4
- * Provides an async initialization function that runs extension bootstraps
5
- * after database connection but before router creation. This is the integration
6
- * point for providers (Lambda, Netlify) to hook into the extension lifecycle.
7
- *
8
- * Call `initializeApp()` during the async startup phase of your handler/function.
9
- * It is safe to call multiple times — subsequent calls are no-ops.
10
- *
11
- * @example
12
- * const { initializeApp } = require('@friggframework/core/extensions/initialize-app');
13
- *
14
- * // In a Lambda handler or Netlify function:
15
- * await initializeApp();
16
- * // Now extensions are bootstrapped and router can be created
17
- */
18
-
19
- const { loadExtensions } = require('./extension-loader');
20
- const { runExtensionBootstraps } = require('./bootstrap-runner');
21
-
22
- let _initialized = false;
23
- let _initPromise = null;
24
-
25
- /**
26
- * Initializes extensions by running bootstrap hooks.
27
- *
28
- * This function:
29
- * 1. Loads the app definition
30
- * 2. Loads and validates extensions
31
- * 3. Runs extension bootstrap hooks in sequence
32
- *
33
- * Bootstrap hooks receive (prisma, appDefinition) and can:
34
- * - Load credentials from database into integration Definition.env
35
- * - Register services or middleware
36
- * - Perform any one-time async initialization
37
- *
38
- * @param {Object} [options]
39
- * @param {Object} [options.appDefinition] - Override app definition (skips loadAppDefinition)
40
- * @param {Object} [options.prisma] - Override Prisma client instance
41
- * @param {boolean} [options.force=false] - Force re-initialization
42
- * @returns {Promise<{extensions: Array}>} The loaded extensions
43
- */
44
- async function initializeApp(options = {}) {
45
- const { force = false } = options;
46
-
47
- // Return cached promise if already initializing (prevent race conditions)
48
- if (_initPromise && !force) {
49
- return _initPromise;
50
- }
51
-
52
- if (_initialized && !force) {
53
- return { extensions: [] };
54
- }
55
-
56
- _initPromise = _doInitialize(options);
57
-
58
- try {
59
- const result = await _initPromise;
60
- _initialized = true;
61
- return result;
62
- } catch (error) {
63
- _initPromise = null;
64
- throw error;
65
- }
66
- }
67
-
68
- async function _doInitialize(options = {}) {
69
- let { appDefinition, prisma } = options;
70
-
71
- // Load app definition if not provided
72
- if (!appDefinition) {
73
- try {
74
- const { loadAppDefinition } = require('../handlers/app-definition-loader');
75
- const loaded = loadAppDefinition();
76
- appDefinition = loaded.appDefinition;
77
- } catch {
78
- // No app definition available — skip extension bootstrap
79
- return { extensions: [] };
80
- }
81
- }
82
-
83
- if (!appDefinition) {
84
- return { extensions: [] };
85
- }
86
-
87
- // Load extensions
88
- const extensions = loadExtensions(appDefinition);
89
-
90
- if (extensions.length === 0) {
91
- return { extensions };
92
- }
93
-
94
- // Get Prisma client if not provided
95
- if (!prisma) {
96
- try {
97
- const db = require('../database/prisma');
98
- prisma = db.prisma;
99
- } catch {
100
- // Prisma not available — skip bootstrap
101
- console.warn('Prisma client not available, skipping extension bootstraps');
102
- return { extensions };
103
- }
104
- }
105
-
106
- // Run bootstrap hooks
107
- await runExtensionBootstraps(extensions, { prisma, appDefinition });
108
-
109
- return { extensions };
110
- }
111
-
112
- /**
113
- * Reset initialization state (for testing).
114
- */
115
- function resetInitialization() {
116
- _initialized = false;
117
- _initPromise = null;
118
- }
119
-
120
- module.exports = {
121
- initializeApp,
122
- resetInitialization,
123
- };