@friggframework/core 2.0.0--canary.704.79d9a63.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.
- package/CLAUDE.md +28 -40
- package/README.md +105 -0
- package/application/commands/entity-commands.js +60 -18
- package/application/commands/integration-commands.js +20 -73
- package/application/commands/scheduler-commands.js +11 -7
- package/application/commands/user-commands.js +17 -5
- package/application/index.js +6 -2
- package/core/Worker.js +31 -7
- package/core/create-handler.js +9 -0
- package/credential/repositories/credential-repository-documentdb.js +34 -0
- package/credential/repositories/credential-repository-interface.js +15 -0
- package/credential/repositories/credential-repository-mongo.js +23 -0
- package/credential/repositories/credential-repository-postgres.js +28 -0
- package/credential/use-cases/credential-operations-for-user.js +202 -0
- package/credential/use-cases/reauthorize-credential-for-user.js +73 -0
- package/database/config.js +48 -24
- package/database/documentdb-encryption-service.js +9 -22
- package/database/documentdb-utils.js +2 -0
- package/database/encryption/README.md +76 -14
- package/database/encryption/documentdb-encryption-service.md +78 -1
- package/database/encryption/encryption-config.js +219 -0
- package/database/encryption/encryption-schema-registry.js +93 -12
- package/database/encryption/integration-mapping-encryption.js +1 -1
- package/database/organization-where.js +18 -0
- package/database/prisma.js +15 -38
- package/database/unique-violation.js +25 -0
- package/database/use-cases/check-encryption-health-use-case.js +43 -52
- package/errors/index.js +0 -4
- package/extensions/bootstrap-runner.js +43 -0
- package/extensions/extension-loader.js +187 -0
- package/extensions/index.js +41 -0
- package/extensions/initialize-app.js +123 -0
- package/extensions/route-mounter.js +103 -0
- package/extensions/schema-composer.js +188 -0
- package/generated/prisma-mongodb/edge.js +43 -4
- package/generated/prisma-mongodb/index-browser.js +40 -1
- package/generated/prisma-mongodb/index.d.ts +4761 -133
- package/generated/prisma-mongodb/index.js +43 -4
- package/generated/prisma-mongodb/package.json +1 -1
- package/generated/prisma-mongodb/schema.prisma +92 -0
- package/generated/prisma-mongodb/wasm.js +43 -4
- package/generated/prisma-postgresql/edge.js +43 -4
- package/generated/prisma-postgresql/index-browser.js +40 -1
- package/generated/prisma-postgresql/index.d.ts +4961 -28
- package/generated/prisma-postgresql/index.js +43 -4
- package/generated/prisma-postgresql/package.json +1 -1
- package/generated/prisma-postgresql/schema.prisma +87 -0
- package/generated/prisma-postgresql/wasm.js +43 -4
- package/handlers/WEBHOOKS.md +0 -29
- package/handlers/app-definition-loader.js +121 -19
- package/handlers/app-handler-helpers.js +25 -3
- package/handlers/backend-utils.js +31 -25
- package/handlers/middleware/admin-auth.js +14 -1
- package/handlers/routers/auth.js +46 -10
- package/handlers/routers/health.js +13 -4
- package/handlers/routers/integration-defined-routers.js +144 -92
- package/handlers/routers/integration-webhook-routers.js +102 -64
- package/handlers/workers/integration-defined-workers.js +5 -2
- package/index.js +65 -3
- package/infrastructure/scheduler/index.js +19 -6
- package/infrastructure/scheduler/netlify-scheduler-adapter.js +216 -0
- package/infrastructure/scheduler/scheduled-job-repository.js +118 -0
- package/infrastructure/scheduler/scheduler-service-factory.js +55 -7
- package/integrations/index.js +1 -0
- package/integrations/integration-base.js +0 -29
- package/integrations/integration-router.js +131 -96
- package/integrations/repositories/integration-mapping-repository-documentdb.js +0 -50
- package/integrations/repositories/integration-mapping-repository-interface.js +0 -15
- package/integrations/repositories/integration-mapping-repository-mongo.js +0 -29
- package/integrations/repositories/integration-mapping-repository-postgres.js +0 -30
- package/integrations/repositories/integration-mapping-repository.js +0 -29
- package/integrations/repositories/integration-not-found.js +14 -0
- package/integrations/repositories/integration-repository-documentdb.js +35 -35
- package/integrations/repositories/integration-repository-interface.js +17 -31
- package/integrations/repositories/integration-repository-mongo.js +60 -129
- package/integrations/repositories/integration-repository-postgres.js +62 -134
- package/integrations/repositories/process-repository-mongo.js +1 -1
- package/integrations/schedule-config.js +80 -0
- package/integrations/tests/doubles/test-integration-repository.js +12 -1
- package/integrations/use-cases/create-integration.js +72 -75
- package/integrations/use-cases/dispatch-ongoing-syncs.js +100 -0
- package/integrations/use-cases/get-integrations-for-user.js +80 -40
- package/integrations/use-cases/index.js +7 -1
- package/integrations/use-cases/integration-operations-for-user.js +256 -0
- package/integrations/use-cases/resolve-integration-ownership.js +177 -0
- package/integrations/utils/map-integration-dto.js +43 -14
- package/management-api/create-management-api-router.js +49 -0
- package/management-api/error-response.js +116 -0
- package/management-api/management-api-config.js +151 -0
- package/management-api/meta-router.js +76 -0
- package/management-api/openapi/build-openapi.js +144 -0
- package/management-api/openapi/components.js +408 -0
- package/management-api/openapi/v1-operations.js +83 -0
- package/management-api/openapi/v2-operations.js +264 -0
- package/management-api/route-registry.js +411 -0
- package/management-api/test-support/http-client.js +39 -0
- package/management-api/use-cases/get-management-api-meta.js +57 -0
- package/management-api/v1-deprecation.js +120 -0
- package/management-api/v2/create-v2-router.js +85 -0
- package/management-api/v2/dependencies.js +281 -0
- package/management-api/v2/dto.js +143 -0
- package/management-api/v2/handlers/authorization.js +94 -0
- package/management-api/v2/handlers/credentials.js +33 -0
- package/management-api/v2/handlers/entities.js +77 -0
- package/management-api/v2/handlers/integrations.js +128 -0
- package/management-api/v2/handlers/proxy.js +34 -0
- package/management-api/v2/request.js +85 -0
- package/management-api/v2/test-support/fake-dependencies.js +103 -0
- package/modules/domain/authorization-session.js +144 -0
- package/modules/entity-scope.js +15 -0
- package/modules/entity-type-registry.js +311 -0
- package/modules/index.js +14 -0
- package/modules/module-factory.js +12 -0
- package/modules/module.js +53 -2
- package/modules/proxy/proxy-errors.js +20 -0
- package/modules/proxy/proxy-path.js +179 -0
- package/modules/proxy/proxy-policy.js +248 -0
- package/modules/repositories/authorization-session-repository-documentdb.js +112 -0
- package/modules/repositories/authorization-session-repository-factory.js +31 -0
- package/modules/repositories/authorization-session-repository-interface.js +47 -0
- package/modules/repositories/authorization-session-repository-prisma.js +87 -0
- package/modules/repositories/entity-not-found.js +18 -0
- package/modules/repositories/module-repository-documentdb.js +51 -6
- package/modules/repositories/module-repository-interface.js +19 -2
- package/modules/repositories/module-repository-mongo.js +67 -74
- package/modules/repositories/module-repository-postgres.js +66 -74
- package/modules/repositories/module-repository.js +2 -1
- package/modules/requester/proxy-request.js +244 -0
- package/modules/requester/requester.js +27 -2
- package/modules/scope-config.js +192 -0
- package/modules/scope-policy.js +112 -0
- package/modules/scope-resolution.js +288 -0
- package/modules/scope-visibility.js +247 -0
- package/modules/tests/doubles/in-memory-authorization-session-repository.js +45 -0
- package/modules/tests/doubles/ownership-matching.js +18 -0
- package/modules/use-cases/authorize-entity-for-user.js +61 -0
- package/modules/use-cases/create-entity-from-credential.js +113 -0
- package/modules/use-cases/entity-operations-for-user.js +162 -0
- package/modules/use-cases/entity-types.js +139 -0
- package/modules/use-cases/execute-entity-proxy-request.js +286 -0
- package/modules/use-cases/get-authorization-requirements.js +100 -0
- package/modules/use-cases/get-entities-for-user.js +26 -13
- package/modules/use-cases/get-entity-module-for-user.js +113 -0
- package/modules/use-cases/get-entity-options-by-id.js +10 -4
- package/modules/use-cases/get-entity-options-by-type.js +1 -1
- package/modules/use-cases/get-module-instance-from-type.js +1 -1
- package/modules/use-cases/get-module.js +10 -4
- package/modules/use-cases/manage-access.js +21 -0
- package/modules/use-cases/multi-step-authorization.js +329 -0
- package/modules/use-cases/process-authorization-callback.js +53 -19
- package/modules/use-cases/refresh-entity-options.js +10 -4
- package/modules/use-cases/test-module-auth.js +10 -4
- package/modules/utils/map-module-dto.js +3 -5
- package/package.json +6 -5
- package/prisma-mongodb/schema.prisma +92 -0
- package/prisma-postgresql/migrations/20261003000000_add_authorization_session/migration.sql +28 -0
- package/prisma-postgresql/migrations/20261015000000_add_organization_membership/migration.sql +26 -0
- package/prisma-postgresql/migrations/20261016000000_add_entity_integration_organization/migration.sql +25 -0
- package/prisma-postgresql/migrations/20261017000000_add_scheduled_job/migration.sql +28 -0
- package/prisma-postgresql/schema.prisma +87 -0
- package/providers/index.js +23 -0
- package/providers/resolve-provider.js +93 -0
- package/providers/runtime-detection.js +124 -0
- package/queues/index.js +25 -0
- package/queues/providers/index.js +11 -0
- package/queues/providers/netlify-background-provider.js +150 -0
- package/queues/providers/qstash-queue-provider.js +219 -0
- package/queues/providers/sqs-queue-provider.js +70 -0
- package/queues/queue-client-interface.js +55 -0
- package/queues/queue-message-auth.js +193 -0
- package/queues/queue-provider-factory.js +101 -0
- package/queues/queue-provider.js +65 -0
- package/queues/sqs-queue-client.js +81 -0
- package/types/index.d.ts +2 -0
- package/types/modules/index.d.ts +197 -0
- package/types/user/index.d.ts +134 -0
- package/user/adopter-jwt-config.js +177 -0
- package/user/adopter-jwt-errors.js +59 -0
- package/user/adopter-token-verifier.js +122 -0
- package/user/app-user-helpers.js +97 -0
- package/user/create-user-authentication.js +64 -0
- package/user/membership.js +51 -0
- package/user/repositories/organization-membership-record.js +19 -0
- package/user/repositories/organization-membership-repository-documentdb.js +106 -0
- package/user/repositories/organization-membership-repository-factory.js +42 -0
- package/user/repositories/organization-membership-repository-interface.js +57 -0
- package/user/repositories/organization-membership-repository-mongo.js +13 -0
- package/user/repositories/organization-membership-repository-postgres.js +29 -0
- package/user/repositories/organization-membership-repository-prisma.js +81 -0
- package/user/repositories/user-repository-documentdb.js +27 -2
- package/user/repositories/user-repository-interface.js +18 -0
- package/user/repositories/user-repository-mongo.js +24 -0
- package/user/repositories/user-repository-postgres.js +18 -0
- package/user/tests/doubles/adopter-jwt-fixtures.js +220 -0
- package/user/tests/doubles/test-user-repository.js +1 -1
- package/user/use-cases/authenticate-user.js +7 -1
- package/user/use-cases/ensure-organization-membership.js +92 -0
- package/user/use-cases/find-individual-users-by-organization.js +54 -0
- package/user/use-cases/get-user-from-adopter-jwt.js +95 -124
- package/user/use-cases/get-user-from-bearer-token.js +2 -7
- package/user/use-cases/get-user-from-x-frigg-headers.js +83 -80
- package/user/user.js +64 -1
- package/errors/mapping-already-exists-error.js +0 -14
- package/integrations/use-cases/add-entities-to-integration.js +0 -92
- package/integrations/use-cases/remove-entities-from-integration.js +0 -70
- package/integrations/utils/assert-entity-ids-input.js +0 -42
- package/modules/utils/to-credential-id.js +0 -14
package/core/Worker.js
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
const { SQSClient, GetQueueUrlCommand, SendMessageCommand } = require('@aws-sdk/client-sqs');
|
|
2
1
|
const _ = require('lodash');
|
|
3
2
|
const { RequiredPropertyError } = require('../errors');
|
|
4
3
|
const { get } = require('../assertions');
|
|
@@ -6,18 +5,44 @@ const { readQueueDelivery } = require('../queues/queue-delivery');
|
|
|
6
5
|
const { runMessageScope } = require('./invocation-scope');
|
|
7
6
|
const { getLogger } = require('../logs');
|
|
8
7
|
|
|
9
|
-
const sqs = new SQSClient({ region: process.env.AWS_REGION });
|
|
10
8
|
const log = getLogger('frigg.worker');
|
|
11
9
|
|
|
10
|
+
/**
|
|
11
|
+
* Worker - queue message producer/consumer base class.
|
|
12
|
+
*
|
|
13
|
+
* Subclass and override _run(). The queue transport is behind
|
|
14
|
+
* QueueClientInterface and can be injected (friggframework/frigg#545):
|
|
15
|
+
* `new MyWorker({ queueClient })`. Unlike #545 it is not required: without
|
|
16
|
+
* one the worker uses an SqsQueueClient configured exactly as before
|
|
17
|
+
* (AWS_REGION), created on first use rather than at module load, so
|
|
18
|
+
* requiring core constructs no AWS client and a Netlify/QStash worker that
|
|
19
|
+
* only calls _run() never touches SQS.
|
|
20
|
+
*/
|
|
12
21
|
class Worker {
|
|
22
|
+
/**
|
|
23
|
+
* @param {Object} [options]
|
|
24
|
+
* @param {import('../queues/queue-client-interface').QueueClientInterface} [options.queueClient]
|
|
25
|
+
*/
|
|
26
|
+
constructor(options = {}) {
|
|
27
|
+
this._queueClient = options.queueClient || null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
_getQueueClient() {
|
|
31
|
+
if (!this._queueClient) {
|
|
32
|
+
const { SqsQueueClient } = require('../queues/sqs-queue-client');
|
|
33
|
+
this._queueClient = new SqsQueueClient({
|
|
34
|
+
clientConfig: { region: process.env.AWS_REGION },
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
return this._queueClient;
|
|
38
|
+
}
|
|
39
|
+
|
|
13
40
|
async getQueueURL(params) {
|
|
14
41
|
// Passing params in because there will be multiple QueueNames
|
|
15
42
|
// let params = {
|
|
16
43
|
// QueueName: process.env.QueueName
|
|
17
44
|
// };
|
|
18
|
-
|
|
19
|
-
const data = await sqs.send(command);
|
|
20
|
-
return data.QueueUrl;
|
|
45
|
+
return this._getQueueClient().getQueueUrl(params);
|
|
21
46
|
}
|
|
22
47
|
|
|
23
48
|
async run(params, context = {}) {
|
|
@@ -91,8 +116,7 @@ class Worker {
|
|
|
91
116
|
}
|
|
92
117
|
|
|
93
118
|
async sendAsyncSQSMessage(params) {
|
|
94
|
-
const
|
|
95
|
-
const data = await sqs.send(command);
|
|
119
|
+
const data = await this._getQueueClient().sendMessage(params);
|
|
96
120
|
return data.MessageId;
|
|
97
121
|
}
|
|
98
122
|
|
package/core/create-handler.js
CHANGED
|
@@ -81,6 +81,15 @@ const createHandler = (optionByName = {}) => {
|
|
|
81
81
|
if (shouldUseDatabase) {
|
|
82
82
|
const { connectPrisma } = require('../database/prisma');
|
|
83
83
|
await connectPrisma();
|
|
84
|
+
|
|
85
|
+
// Extension bootstraps (e.g. db-credentials swapping a
|
|
86
|
+
// module's env for its DB loader) run once per
|
|
87
|
+
// process, after the connect and before any request
|
|
88
|
+
// builds a module. AWS and Netlify both reach here.
|
|
89
|
+
const {
|
|
90
|
+
initializeApp,
|
|
91
|
+
} = require('../extensions/initialize-app');
|
|
92
|
+
await initializeApp();
|
|
84
93
|
}
|
|
85
94
|
|
|
86
95
|
// Helps reuse the database connection. Lowers response times.
|
|
@@ -186,6 +186,40 @@ class CredentialRepositoryDocumentDB extends CredentialRepositoryInterface {
|
|
|
186
186
|
return this._mapCredential(decryptedCredential);
|
|
187
187
|
}
|
|
188
188
|
|
|
189
|
+
/**
|
|
190
|
+
* All credentials owned by a user, newest first.
|
|
191
|
+
*
|
|
192
|
+
* @param {string} userId - User ID
|
|
193
|
+
* @returns {Promise<Array<Object>>} Credentials with string IDs
|
|
194
|
+
*/
|
|
195
|
+
async findCredentialsByUserId(userId) {
|
|
196
|
+
const userObjectId = toObjectId(userId);
|
|
197
|
+
if (!userObjectId) return [];
|
|
198
|
+
const docs = await findManyDrained(
|
|
199
|
+
this.prisma,
|
|
200
|
+
'Credential',
|
|
201
|
+
{ userId: userObjectId },
|
|
202
|
+
{ sort: { createdAt: -1 } }
|
|
203
|
+
);
|
|
204
|
+
const credentials = [];
|
|
205
|
+
for (const doc of docs) {
|
|
206
|
+
const decrypted = await this.encryptionService.decryptFields(
|
|
207
|
+
'Credential',
|
|
208
|
+
doc
|
|
209
|
+
);
|
|
210
|
+
credentials.push({
|
|
211
|
+
...this._mapCredential(decrypted),
|
|
212
|
+
id: fromObjectId(doc._id),
|
|
213
|
+
userId: fromObjectId(doc.userId) ?? doc.userId,
|
|
214
|
+
externalId: doc.externalId ?? null,
|
|
215
|
+
authIsValid: doc.authIsValid ?? null,
|
|
216
|
+
createdAt: doc.createdAt ?? null,
|
|
217
|
+
updatedAt: doc.updatedAt ?? null,
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
return credentials;
|
|
221
|
+
}
|
|
222
|
+
|
|
189
223
|
async updateCredential(credentialId, updates) {
|
|
190
224
|
const objectId = toObjectId(credentialId);
|
|
191
225
|
if (!objectId) return null;
|
|
@@ -80,6 +80,21 @@ class CredentialRepositoryInterface {
|
|
|
80
80
|
);
|
|
81
81
|
}
|
|
82
82
|
|
|
83
|
+
/**
|
|
84
|
+
* All credentials owned by a user, newest first.
|
|
85
|
+
*
|
|
86
|
+
* @param {string|number} userId - User ID (string from application layer)
|
|
87
|
+
* @returns {Promise<Array<Object>>} Credentials with string IDs, `createdAt`
|
|
88
|
+
* and `updatedAt`, and the (decrypted) data fields spread in, as
|
|
89
|
+
* findCredentialById returns them. Empty when the user has none.
|
|
90
|
+
* @abstract
|
|
91
|
+
*/
|
|
92
|
+
async findCredentialsByUserId(userId) {
|
|
93
|
+
throw new Error(
|
|
94
|
+
'Method findCredentialsByUserId must be implemented by subclass'
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
|
|
83
98
|
/**
|
|
84
99
|
* Update a credential by ID
|
|
85
100
|
*
|
|
@@ -188,6 +188,29 @@ class CredentialRepositoryMongo extends CredentialRepositoryInterface {
|
|
|
188
188
|
};
|
|
189
189
|
}
|
|
190
190
|
|
|
191
|
+
/**
|
|
192
|
+
* All credentials owned by a user, newest first.
|
|
193
|
+
*
|
|
194
|
+
* @param {string} userId - User ID
|
|
195
|
+
* @returns {Promise<Array<Object>>} Credentials with string IDs
|
|
196
|
+
*/
|
|
197
|
+
async findCredentialsByUserId(userId) {
|
|
198
|
+
if (!userId) return [];
|
|
199
|
+
const credentials = await this.prisma.credential.findMany({
|
|
200
|
+
where: { userId: String(userId) },
|
|
201
|
+
orderBy: { createdAt: 'desc' },
|
|
202
|
+
});
|
|
203
|
+
return credentials.map((credential) => ({
|
|
204
|
+
...(credential.data || {}),
|
|
205
|
+
id: credential.id,
|
|
206
|
+
userId: credential.userId,
|
|
207
|
+
externalId: credential.externalId,
|
|
208
|
+
authIsValid: credential.authIsValid,
|
|
209
|
+
createdAt: credential.createdAt,
|
|
210
|
+
updatedAt: credential.updatedAt,
|
|
211
|
+
}));
|
|
212
|
+
}
|
|
213
|
+
|
|
191
214
|
/**
|
|
192
215
|
* Update a credential by ID
|
|
193
216
|
* Replaces: Credential.findByIdAndUpdate(credentialId, { $set: updates })
|
|
@@ -205,6 +205,34 @@ class CredentialRepositoryPostgres extends CredentialRepositoryInterface {
|
|
|
205
205
|
};
|
|
206
206
|
}
|
|
207
207
|
|
|
208
|
+
/**
|
|
209
|
+
* All credentials owned by a user, newest first.
|
|
210
|
+
*
|
|
211
|
+
* @param {string} userId - User ID (string from application layer)
|
|
212
|
+
* @returns {Promise<Array<Object>>} Credentials with string IDs
|
|
213
|
+
*/
|
|
214
|
+
async findCredentialsByUserId(userId) {
|
|
215
|
+
let intUserId;
|
|
216
|
+
try {
|
|
217
|
+
intUserId = this._convertId(userId);
|
|
218
|
+
} catch {
|
|
219
|
+
return [];
|
|
220
|
+
}
|
|
221
|
+
const credentials = await this.prisma.credential.findMany({
|
|
222
|
+
where: { userId: intUserId },
|
|
223
|
+
orderBy: { createdAt: 'desc' },
|
|
224
|
+
});
|
|
225
|
+
return credentials.map((credential) => ({
|
|
226
|
+
...(credential.data || {}),
|
|
227
|
+
id: credential.id.toString(),
|
|
228
|
+
userId: credential.userId?.toString(),
|
|
229
|
+
externalId: credential.externalId,
|
|
230
|
+
authIsValid: credential.authIsValid,
|
|
231
|
+
createdAt: credential.createdAt,
|
|
232
|
+
updatedAt: credential.updatedAt,
|
|
233
|
+
}));
|
|
234
|
+
}
|
|
235
|
+
|
|
208
236
|
/**
|
|
209
237
|
* Update a credential by ID
|
|
210
238
|
*
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
const Boom = require('@hapi/boom');
|
|
2
|
+
const {
|
|
3
|
+
createScopePolicy,
|
|
4
|
+
describeRecord,
|
|
5
|
+
visibilityClauses,
|
|
6
|
+
matchesListFilters,
|
|
7
|
+
SCOPES,
|
|
8
|
+
} = require('../../modules/entity-scope');
|
|
9
|
+
const { assertCanManage } = require('../../modules/use-cases/manage-access');
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Management API v2 credential operations (ADR-056 §3.4, §3.6). A credential
|
|
13
|
+
* has no module name and no organization of its own:
|
|
14
|
+
*
|
|
15
|
+
* - its `type` and `entityIds` come from the entities that use it that the
|
|
16
|
+
* caller may see, so the same person's account connected in two
|
|
17
|
+
* organizations (one credential, two entities) lists in each organization
|
|
18
|
+
* with that organization's entity only;
|
|
19
|
+
* - who it belongs to is its OWNER (`credential.userId`), never the entities:
|
|
20
|
+
* a credential an individual entity and an organization entity both point at
|
|
21
|
+
* (possible only through legacy data) is described by whoever owns the
|
|
22
|
+
* credential, so the answer cannot change with the order the entities load;
|
|
23
|
+
* - a credential whose entities are all out of sight (another organization's)
|
|
24
|
+
* is a 404, and one with no entities at all (its entity was deleted) is
|
|
25
|
+
* visible to its owner only, as it was before scoping.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
const credentialIdOf = (entity) => {
|
|
29
|
+
const ref = entity.credential ?? entity.credentialId;
|
|
30
|
+
if (ref === undefined || ref === null) return null;
|
|
31
|
+
if (typeof ref === 'object') {
|
|
32
|
+
const id = ref.id ?? ref._id;
|
|
33
|
+
return id === undefined || id === null ? null : String(id);
|
|
34
|
+
}
|
|
35
|
+
return String(ref);
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
/** Adds `type` and `entityIds` from the user's entities to each credential. */
|
|
39
|
+
function withEntityUsage(credentials, entities) {
|
|
40
|
+
const usage = new Map();
|
|
41
|
+
for (const entity of entities || []) {
|
|
42
|
+
const credentialId = credentialIdOf(entity);
|
|
43
|
+
if (!credentialId) continue;
|
|
44
|
+
const entry = usage.get(credentialId) || { type: null, entityIds: [] };
|
|
45
|
+
entry.type = entry.type || entity.moduleName || null;
|
|
46
|
+
entry.entityIds.push(String(entity.id));
|
|
47
|
+
usage.set(credentialId, entry);
|
|
48
|
+
}
|
|
49
|
+
return credentials.map((credential) => {
|
|
50
|
+
const entry = usage.get(String(credential.id)) || {
|
|
51
|
+
type: null,
|
|
52
|
+
entityIds: [],
|
|
53
|
+
};
|
|
54
|
+
return { ...credential, type: entry.type, entityIds: entry.entityIds };
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* `{scope, owner, organizationId, access}` of a credential for this caller, or
|
|
60
|
+
* null when its owner is neither the caller nor the active organization. Built
|
|
61
|
+
* by `describeRecord` over the row a connection by this owner has: the
|
|
62
|
+
* organization of a visible entity, else the one a new entity would get.
|
|
63
|
+
*/
|
|
64
|
+
function credentialTenancy(credential, visibleEntities, ctx) {
|
|
65
|
+
const entityOrg = visibleEntities.find(
|
|
66
|
+
(entity) => entity.organizationId !== undefined && entity.organizationId !== null
|
|
67
|
+
)?.organizationId;
|
|
68
|
+
const organizationId =
|
|
69
|
+
entityOrg ?? (ctx.individualAcross === 'all' ? null : ctx.activeOrgId);
|
|
70
|
+
return describeRecord({ userId: credential.userId, organizationId }, ctx, 'entity');
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** The entities of `entities` the caller may see, each with its `tenancy`. */
|
|
74
|
+
function visibleOf(entities, ctx) {
|
|
75
|
+
const visible = [];
|
|
76
|
+
for (const entity of entities || []) {
|
|
77
|
+
const tenancy = describeRecord(entity, ctx, 'entity');
|
|
78
|
+
if (tenancy) visible.push({ ...entity, tenancy });
|
|
79
|
+
}
|
|
80
|
+
return visible;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* The caller's credentials with their type, the entities of them they may see
|
|
85
|
+
* and `tenancy`. Credentials with no entity at all are listed too, for the
|
|
86
|
+
* person and the active organization that own them.
|
|
87
|
+
*/
|
|
88
|
+
class ListCredentialsForUser {
|
|
89
|
+
constructor({ credentialRepository, moduleRepository, scopePolicy }) {
|
|
90
|
+
this.credentialRepository = credentialRepository;
|
|
91
|
+
this.moduleRepository = moduleRepository;
|
|
92
|
+
this.scopePolicy = scopePolicy || createScopePolicy();
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** @param {{scope?: string, owner?: string}} [filters] */
|
|
96
|
+
async execute(user, filters = {}) {
|
|
97
|
+
const ctx = this.scopePolicy.accessContext(user);
|
|
98
|
+
const owners = [...new Set([ctx.callerId, ctx.activeOrgId].filter(Boolean))];
|
|
99
|
+
const [found, perOwner, owned] = await Promise.all([
|
|
100
|
+
this.moduleRepository.findEntitiesByOwnership(visibilityClauses(ctx, 'entity')),
|
|
101
|
+
Promise.all(owners.map((id) => this.credentialRepository.findCredentialsByUserId(id))),
|
|
102
|
+
// Every entity of those owners, in any organization: only to tell a credential
|
|
103
|
+
// with no entity at all from one used elsewhere.
|
|
104
|
+
Promise.all(owners.map((id) => this.moduleRepository.findEntitiesByUserId(id))),
|
|
105
|
+
]);
|
|
106
|
+
const visible = visibleOf(found, ctx);
|
|
107
|
+
const usedAnywhere = new Set(owned.flat().map(credentialIdOf).filter(Boolean));
|
|
108
|
+
const listed = [];
|
|
109
|
+
for (const credential of perOwner.flat().filter(Boolean)) {
|
|
110
|
+
const id = String(credential.id);
|
|
111
|
+
const referencing = visible.filter((entity) => credentialIdOf(entity) === id);
|
|
112
|
+
if (referencing.length === 0 && usedAnywhere.has(id)) continue;
|
|
113
|
+
const tenancy = credentialTenancy(credential, referencing, ctx);
|
|
114
|
+
if (!tenancy || !matchesListFilters(tenancy, filters)) continue;
|
|
115
|
+
listed.push({ ...withEntityUsage([credential], referencing)[0], tenancy });
|
|
116
|
+
}
|
|
117
|
+
return listed;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** One credential the caller may see: see the header. 404 otherwise. */
|
|
122
|
+
class GetCredentialForUserV2 {
|
|
123
|
+
constructor({ credentialRepository, moduleRepository, scopePolicy }) {
|
|
124
|
+
this.credentialRepository = credentialRepository;
|
|
125
|
+
this.moduleRepository = moduleRepository;
|
|
126
|
+
this.scopePolicy = scopePolicy || createScopePolicy();
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
async execute(credentialId, user) {
|
|
130
|
+
const notFound = () =>
|
|
131
|
+
Boom.notFound(`Credential ${credentialId} not found`, {
|
|
132
|
+
code: 'CREDENTIAL_NOT_FOUND',
|
|
133
|
+
});
|
|
134
|
+
let credential = null;
|
|
135
|
+
try {
|
|
136
|
+
credential = await this.credentialRepository.findCredentialById(
|
|
137
|
+
credentialId
|
|
138
|
+
);
|
|
139
|
+
} catch (error) {
|
|
140
|
+
if (!/Invalid ID|ObjectId|Malformed/i.test(error?.message || '')) {
|
|
141
|
+
throw error;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
if (!credential) throw notFound();
|
|
145
|
+
const ctx = this.scopePolicy.accessContext(user);
|
|
146
|
+
|
|
147
|
+
const referencing =
|
|
148
|
+
(await this.moduleRepository.findEntities({ credentialId: credential.id })) || [];
|
|
149
|
+
const visible = visibleOf(referencing, ctx);
|
|
150
|
+
if (referencing.length > 0 && visible.length === 0) throw notFound();
|
|
151
|
+
const tenancy = credentialTenancy(credential, visible, ctx);
|
|
152
|
+
if (!tenancy) throw notFound();
|
|
153
|
+
return { ...withEntityUsage([credential], visible)[0], tenancy };
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Deletes a credential the caller may manage. The entities that used it stay,
|
|
159
|
+
* with their credential unset, so they show as needing re-authorization rather
|
|
160
|
+
* than disappearing from integrations.
|
|
161
|
+
*
|
|
162
|
+
* Refuses with 409 `CREDENTIAL_SHARED` while an entity the caller cannot see
|
|
163
|
+
* still uses it: one credential row serves the same provider account in every
|
|
164
|
+
* organization, and deleting it from one would break the other. The message
|
|
165
|
+
* says nothing about the other connections (not even how many): remove the
|
|
166
|
+
* entities that use it, and it goes with the last one.
|
|
167
|
+
*/
|
|
168
|
+
class DeleteCredentialForUser {
|
|
169
|
+
constructor({ credentialRepository, moduleRepository, getCredentialForUser }) {
|
|
170
|
+
this.credentialRepository = credentialRepository;
|
|
171
|
+
this.moduleRepository = moduleRepository;
|
|
172
|
+
this.getCredentialForUser = getCredentialForUser;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
async execute(credentialId, user) {
|
|
176
|
+
const credential = await this.getCredentialForUser.execute(
|
|
177
|
+
credentialId,
|
|
178
|
+
user
|
|
179
|
+
);
|
|
180
|
+
assertCanManage(credential.tenancy.access, `credential ${credential.id}`);
|
|
181
|
+
const usedBy =
|
|
182
|
+
(await this.moduleRepository.findEntities({ credentialId: credential.id })) || [];
|
|
183
|
+
if (usedBy.length > credential.entityIds.length) {
|
|
184
|
+
throw Boom.conflict(
|
|
185
|
+
`Credential ${credential.id} is still in use by other connections and cannot be deleted from here`,
|
|
186
|
+
{ code: 'CREDENTIAL_SHARED' }
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
for (const entityId of credential.entityIds) {
|
|
190
|
+
await this.moduleRepository.unsetCredential(entityId);
|
|
191
|
+
}
|
|
192
|
+
await this.credentialRepository.deleteCredentialById(credential.id);
|
|
193
|
+
return { id: String(credential.id), entityIds: credential.entityIds };
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
module.exports = {
|
|
198
|
+
ListCredentialsForUser,
|
|
199
|
+
GetCredentialForUserV2,
|
|
200
|
+
DeleteCredentialForUser,
|
|
201
|
+
withEntityUsage,
|
|
202
|
+
};
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
const Boom = require('@hapi/boom');
|
|
2
|
+
const { assertCanManage } = require('../../modules/use-cases/manage-access');
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Re-authorization of a credential the caller owns (Management API v2). It
|
|
6
|
+
* runs the same flow as /api/v2/authorize for the credential's entity type,
|
|
7
|
+
* with the session bound to the credential so it cannot be reused for
|
|
8
|
+
* anything else.
|
|
9
|
+
*/
|
|
10
|
+
async function credentialEntityType(getCredentialForUser, credentialId, user) {
|
|
11
|
+
const credential = await getCredentialForUser.execute(credentialId, user);
|
|
12
|
+
if (!credential.type) {
|
|
13
|
+
throw Boom.conflict(
|
|
14
|
+
`Credential ${credentialId} is not used by any entity, so its type is unknown; authorize a new connection instead`,
|
|
15
|
+
{ code: 'CREDENTIAL_TYPE_UNKNOWN' }
|
|
16
|
+
);
|
|
17
|
+
}
|
|
18
|
+
return {
|
|
19
|
+
entityType: credential.type,
|
|
20
|
+
credentialId: String(credential.id),
|
|
21
|
+
// A re-authorization keeps the scope the connection already has.
|
|
22
|
+
fixedScope: credential.tenancy?.scope,
|
|
23
|
+
access: credential.tenancy?.access,
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** GET /api/v2/credentials/:credentialId/reauthorize */
|
|
28
|
+
class GetCredentialReauthorization {
|
|
29
|
+
constructor({ getCredentialForUser, getAuthorizationStep }) {
|
|
30
|
+
this.getCredentialForUser = getCredentialForUser;
|
|
31
|
+
this.getAuthorizationStep = getAuthorizationStep;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async execute(credentialId, user, { step = 1, sessionId, state } = {}) {
|
|
35
|
+
const { entityType, credentialId: boundCredentialId } =
|
|
36
|
+
await credentialEntityType(this.getCredentialForUser, credentialId, user);
|
|
37
|
+
return this.getAuthorizationStep.execute({
|
|
38
|
+
user,
|
|
39
|
+
entityType,
|
|
40
|
+
credentialId: boundCredentialId,
|
|
41
|
+
step,
|
|
42
|
+
sessionId,
|
|
43
|
+
state,
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** POST /api/v2/credentials/:credentialId/reauthorize */
|
|
49
|
+
class ReauthorizeCredentialForUser {
|
|
50
|
+
constructor({ getCredentialForUser, submitAuthorizationStep }) {
|
|
51
|
+
this.getCredentialForUser = getCredentialForUser;
|
|
52
|
+
this.submitAuthorizationStep = submitAuthorizationStep;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async execute(credentialId, user, { data, step = 1, sessionId } = {}) {
|
|
56
|
+
const { access, ...binding } = await credentialEntityType(
|
|
57
|
+
this.getCredentialForUser,
|
|
58
|
+
credentialId,
|
|
59
|
+
user
|
|
60
|
+
);
|
|
61
|
+
// A credential an organization owns: the organization's admins only.
|
|
62
|
+
assertCanManage(access, `credential ${credentialId}`);
|
|
63
|
+
return this.submitAuthorizationStep.execute({
|
|
64
|
+
user,
|
|
65
|
+
...binding,
|
|
66
|
+
data,
|
|
67
|
+
step,
|
|
68
|
+
sessionId,
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
module.exports = { GetCredentialReauthorization, ReauthorizeCredentialForUser };
|
package/database/config.js
CHANGED
|
@@ -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]')) {
|
|
@@ -4,6 +4,7 @@ const {
|
|
|
4
4
|
getFieldsToEncryptOnWrite,
|
|
5
5
|
loadCustomEncryptionSchema,
|
|
6
6
|
} = require('./encryption/encryption-schema-registry');
|
|
7
|
+
const { getEncryptionConfig } = require('./encryption/encryption-config');
|
|
7
8
|
|
|
8
9
|
/**
|
|
9
10
|
* Encryption service specifically for DocumentDB repositories
|
|
@@ -41,43 +42,29 @@ class DocumentDBEncryptionService {
|
|
|
41
42
|
}
|
|
42
43
|
|
|
43
44
|
/**
|
|
44
|
-
* Initialize Cryptor with environment-based configuration
|
|
45
|
-
*
|
|
45
|
+
* Initialize Cryptor with environment-based configuration, using the
|
|
46
|
+
* same rule as the Prisma client (see encryption/encryption-config.js).
|
|
46
47
|
*
|
|
47
|
-
*
|
|
48
|
-
*
|
|
48
|
+
* Local runs skip encryption on the dev, test and local stages. A
|
|
49
|
+
* deployed runtime with no key throws instead of writing plaintext.
|
|
49
50
|
*
|
|
50
51
|
* @private
|
|
52
|
+
* @throws {EncryptionConfigurationError} deployed with no usable key
|
|
51
53
|
*/
|
|
52
54
|
_initializeCryptor() {
|
|
53
55
|
// Load custom encryption schema from app definition BEFORE checking configuration
|
|
54
56
|
// This ensures custom fields (like User.username) are registered before any encryption operations
|
|
55
57
|
loadCustomEncryptionSchema();
|
|
56
58
|
|
|
57
|
-
|
|
58
|
-
const stage = process.env.STAGE || process.env.NODE_ENV || 'development';
|
|
59
|
-
const bypassEncryption = ['dev', 'test', 'local'].includes(stage.toLowerCase());
|
|
59
|
+
const config = getEncryptionConfig();
|
|
60
60
|
|
|
61
|
-
if (
|
|
61
|
+
if (!config.enabled) {
|
|
62
62
|
this.cryptor = null;
|
|
63
63
|
this.enabled = false;
|
|
64
64
|
return;
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
-
|
|
68
|
-
const hasKMS = !!(process.env.KMS_KEY_ARN && process.env.KMS_KEY_ARN.trim() !== '');
|
|
69
|
-
const hasAES = !!(process.env.AES_KEY_ID && process.env.AES_KEY_ID.trim() !== '');
|
|
70
|
-
|
|
71
|
-
if (!hasKMS && !hasAES) {
|
|
72
|
-
console.warn('[DocumentDBEncryptionService] No encryption keys configured. Encryption disabled.');
|
|
73
|
-
this.cryptor = null;
|
|
74
|
-
this.enabled = false;
|
|
75
|
-
return;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
// KMS takes precedence over AES
|
|
79
|
-
const shouldUseAws = hasKMS;
|
|
80
|
-
this.cryptor = new Cryptor({ shouldUseAws });
|
|
67
|
+
this.cryptor = new Cryptor({ shouldUseAws: config.method === 'kms' });
|
|
81
68
|
this.enabled = true;
|
|
82
69
|
}
|
|
83
70
|
|
|
@@ -58,6 +58,8 @@ async function insertOne(client, collection, document) {
|
|
|
58
58
|
|
|
59
59
|
// Provide helpful context for common errors
|
|
60
60
|
if (error.code === 11000) {
|
|
61
|
+
// `code` lets callers recognise a lost race without parsing text
|
|
62
|
+
// (see database/unique-violation.js).
|
|
61
63
|
throw Object.assign(
|
|
62
64
|
new Error(`${errorMsg} - Duplicate key violation`),
|
|
63
65
|
{ code: 11000 }
|