@friggframework/core 2.0.0--canary.691.2fd013b.0 → 2.0.0--canary.686.ba9ded3.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 -0
- package/README.md +105 -0
- package/application/commands/integration-commands.js +20 -10
- 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-utils.js +2 -0
- package/database/encryption/encryption-schema-registry.js +93 -12
- package/database/organization-where.js +18 -0
- package/database/prisma.js +4 -2
- package/database/unique-violation.js +25 -0
- 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 -3
- package/integrations/repositories/integration-repository-interface.js +17 -1
- package/integrations/repositories/integration-repository-mongo.js +60 -77
- package/integrations/repositories/integration-repository-postgres.js +62 -76
- 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 +55 -20
- 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/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 +108 -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
|
@@ -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]')) {
|
|
@@ -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 }
|
|
@@ -39,6 +39,12 @@ const CORE_ENCRYPTION_SCHEMA = {
|
|
|
39
39
|
Token: {
|
|
40
40
|
fields: ['token'],
|
|
41
41
|
},
|
|
42
|
+
|
|
43
|
+
// Multi-step authorization (Management API v2): earlier steps can collect
|
|
44
|
+
// emails, usernames or one-time codes.
|
|
45
|
+
AuthorizationSession: {
|
|
46
|
+
fields: ['stepData'],
|
|
47
|
+
},
|
|
42
48
|
};
|
|
43
49
|
|
|
44
50
|
let customSchema = {};
|
|
@@ -174,6 +180,13 @@ function loadModuleEncryptionSchemas(integrations) {
|
|
|
174
180
|
return;
|
|
175
181
|
}
|
|
176
182
|
|
|
183
|
+
// NOTE: this path does not exist ('../integrations' resolves to
|
|
184
|
+
// database/integrations), so today this function throws MODULE_NOT_FOUND,
|
|
185
|
+
// loadCustomEncryptionSchema swallows it, and module credentialFields are
|
|
186
|
+
// effectively NOT registered. Fixing it changes which fields are encrypted
|
|
187
|
+
// and needs a decrypt that tolerates plaintext, so it ships separately:
|
|
188
|
+
// branch claude/internal-mcp-03b-module-credential-encryption. Left as is
|
|
189
|
+
// here on purpose (ADR-059 must not change what gets encrypted).
|
|
177
190
|
const { getModulesDefinitionFromIntegrationClasses } = require('../integrations/utils/map-integration-dto');
|
|
178
191
|
|
|
179
192
|
const moduleDefinitions = getModulesDefinitionFromIntegrationClasses(integrations);
|
|
@@ -205,22 +218,80 @@ function loadModuleEncryptionSchemas(integrations) {
|
|
|
205
218
|
*
|
|
206
219
|
* Used by both Prisma (MongoDB/PostgreSQL) and DocumentDB encryption services.
|
|
207
220
|
*/
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
221
|
+
/**
|
|
222
|
+
* Registers encryption schemas declared by app-level extensions
|
|
223
|
+
* (`appDefinition.coreExtensions[].encryption`), e.g. the db-credentials
|
|
224
|
+
* extension's `OAuthAppCredential.clientSecret`.
|
|
225
|
+
*
|
|
226
|
+
* @param {Array<Object>} extensions - Normalized extensions (extension-loader)
|
|
227
|
+
*/
|
|
228
|
+
function loadExtensionEncryptionSchemas(extensions) {
|
|
229
|
+
if (!extensions || !Array.isArray(extensions) || extensions.length === 0) {
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
for (const ext of extensions) {
|
|
234
|
+
if (!ext.encryption || typeof ext.encryption !== 'object') {
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const schema = {};
|
|
239
|
+
for (const [modelName, config] of Object.entries(ext.encryption)) {
|
|
240
|
+
if (config && Array.isArray(config.fields) && config.fields.length > 0) {
|
|
241
|
+
schema[modelName] = { fields: config.fields };
|
|
242
|
+
}
|
|
243
|
+
}
|
|
213
244
|
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
245
|
+
if (Object.keys(schema).length > 0) {
|
|
246
|
+
logger.info(
|
|
247
|
+
`Registering encryption schema from extension "${ext.name}" for models: ${Object.keys(schema).join(', ')}`
|
|
248
|
+
);
|
|
249
|
+
// registerCustomSchema replaces the registered schema, so merge:
|
|
250
|
+
// an extension adds its models to the app's encryption.schema
|
|
251
|
+
// rather than dropping it.
|
|
252
|
+
const merged = { ...customSchema };
|
|
253
|
+
for (const [modelName, config] of Object.entries(schema)) {
|
|
254
|
+
const existing = merged[modelName]?.fields || [];
|
|
255
|
+
merged[modelName] = {
|
|
256
|
+
...merged[modelName],
|
|
257
|
+
fields: [...new Set([...existing, ...config.fields])],
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
registerCustomSchema(merged);
|
|
217
261
|
}
|
|
262
|
+
}
|
|
263
|
+
}
|
|
218
264
|
|
|
219
|
-
|
|
220
|
-
|
|
265
|
+
function readAppDefinitionForEncryption() {
|
|
266
|
+
// Lazy require to avoid circular dependency issues
|
|
267
|
+
const {
|
|
268
|
+
getPresetAppDefinition,
|
|
269
|
+
} = require('../../handlers/app-definition-loader');
|
|
270
|
+
// A definition preset with setAppDefinition() (provider-netlify's
|
|
271
|
+
// preamble) wins: on Netlify process.cwd() cannot find the backend.
|
|
272
|
+
const preset = getPresetAppDefinition();
|
|
273
|
+
if (preset) {
|
|
274
|
+
return preset;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
const path = require('node:path');
|
|
278
|
+
const { findNearestBackendPackageJson } = require('../../utils');
|
|
279
|
+
|
|
280
|
+
const backendPackagePath = findNearestBackendPackageJson();
|
|
281
|
+
if (!backendPackagePath) {
|
|
282
|
+
return null; // No backend found, skip custom schema
|
|
283
|
+
}
|
|
221
284
|
|
|
222
|
-
|
|
223
|
-
|
|
285
|
+
const backendDir = path.dirname(backendPackagePath);
|
|
286
|
+
const backendIndexPath = path.join(backendDir, 'index.js');
|
|
287
|
+
|
|
288
|
+
const backendModule = require(backendIndexPath);
|
|
289
|
+
return backendModule?.Definition || null;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function loadCustomEncryptionSchema() {
|
|
293
|
+
try {
|
|
294
|
+
const appDefinition = readAppDefinitionForEncryption();
|
|
224
295
|
|
|
225
296
|
if (!appDefinition) {
|
|
226
297
|
return; // No app definition found
|
|
@@ -240,6 +311,15 @@ function loadCustomEncryptionSchema() {
|
|
|
240
311
|
registerEncryptionOptOut(disable);
|
|
241
312
|
}
|
|
242
313
|
|
|
314
|
+
// Load app-level extension encryption schemas. Before the module
|
|
315
|
+
// schemas: loadModuleEncryptionSchemas currently throws (see the
|
|
316
|
+
// NOTE inside it) and the throw would skip anything after it.
|
|
317
|
+
const { loadExtensions } = require('../../extensions/extension-loader');
|
|
318
|
+
const extensions = loadExtensions(appDefinition);
|
|
319
|
+
if (extensions.length > 0) {
|
|
320
|
+
loadExtensionEncryptionSchemas(extensions);
|
|
321
|
+
}
|
|
322
|
+
|
|
243
323
|
// Load module-level encryption schemas from integrations
|
|
244
324
|
const integrations = appDefinition.integrations;
|
|
245
325
|
if (integrations && Array.isArray(integrations)) {
|
|
@@ -396,6 +476,7 @@ module.exports = {
|
|
|
396
476
|
registerEncryptionOptOut,
|
|
397
477
|
loadCustomEncryptionSchema,
|
|
398
478
|
loadModuleEncryptionSchemas,
|
|
479
|
+
loadExtensionEncryptionSchemas,
|
|
399
480
|
extractCredentialFieldsFromModules,
|
|
400
481
|
validateCustomSchema,
|
|
401
482
|
validateOptOut,
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Prisma `where` fragment for an `organizationId` on MongoDB (ADR-056
|
|
3
|
+
* §3.6), shared by the entity and integration adapters.
|
|
4
|
+
*
|
|
5
|
+
* Prisma on MongoDB: `null` matches only an explicit null and `isSet: false`
|
|
6
|
+
* only a missing field. A row written before the column existed is the common
|
|
7
|
+
* "no organization" case, so `null` here means both.
|
|
8
|
+
*/
|
|
9
|
+
function organizationWhere(organizationId) {
|
|
10
|
+
if (organizationId === null) {
|
|
11
|
+
return {
|
|
12
|
+
OR: [{ organizationId: null }, { organizationId: { isSet: false } }],
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
return { organizationId };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
module.exports = { organizationWhere };
|
package/database/prisma.js
CHANGED
|
@@ -67,13 +67,15 @@ const prismaClientSingleton = () => {
|
|
|
67
67
|
const paths = [
|
|
68
68
|
// Lambda layer location (when using Prisma Lambda layer)
|
|
69
69
|
`/opt/nodejs/node_modules/generated/prisma-${dbType}`,
|
|
70
|
+
// __dirname-based absolute path (Netlify functions and bundlers)
|
|
71
|
+
require('node:path').resolve(__dirname, `../generated/prisma-${dbType}`),
|
|
70
72
|
// Local development location (relative to core package)
|
|
71
73
|
`../generated/prisma-${dbType}`,
|
|
72
74
|
];
|
|
73
75
|
|
|
74
|
-
for (const
|
|
76
|
+
for (const candidate of paths) {
|
|
75
77
|
try {
|
|
76
|
-
return require(
|
|
78
|
+
return require(candidate).PrismaClient;
|
|
77
79
|
} catch (err) {
|
|
78
80
|
// Continue to next path
|
|
79
81
|
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** Mongo/DocumentDB duplicate-key error code. */
|
|
2
|
+
const DUPLICATE_KEY_CODE = 11000;
|
|
3
|
+
/** Prisma's unique-constraint error code (PostgreSQL and MongoDB). */
|
|
4
|
+
const PRISMA_UNIQUE_CODE = 'P2002';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Whether `error` is a unique-constraint violation, however the database
|
|
8
|
+
* layer raised it: a Prisma `P2002`, or a duplicate-key `11000`
|
|
9
|
+
* (`documentdb-utils` `insertOne` sets `code` on the error it throws).
|
|
10
|
+
* Matches on the code only, never on message text.
|
|
11
|
+
*
|
|
12
|
+
* @param {unknown} error
|
|
13
|
+
* @returns {boolean}
|
|
14
|
+
*/
|
|
15
|
+
function isUniqueViolation(error) {
|
|
16
|
+
return (
|
|
17
|
+
error?.code === PRISMA_UNIQUE_CODE || error?.code === DUPLICATE_KEY_CODE
|
|
18
|
+
);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
module.exports = {
|
|
22
|
+
isUniqueViolation,
|
|
23
|
+
DUPLICATE_KEY_CODE,
|
|
24
|
+
PRISMA_UNIQUE_CODE,
|
|
25
|
+
};
|
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
|
};
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bootstrap Runner
|
|
3
|
+
*
|
|
4
|
+
* Runs extension bootstrap functions in sequence.
|
|
5
|
+
* Bootstrap hooks execute AFTER database connection but BEFORE integration
|
|
6
|
+
* router creation. This is the right place for extensions to:
|
|
7
|
+
*
|
|
8
|
+
* - Load credentials from database into integration definitions
|
|
9
|
+
* - Register additional middleware or services
|
|
10
|
+
* - Perform one-time initialization
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* await runExtensionBootstraps(extensions, { prisma, appDefinition });
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Runs all extension bootstrap functions in sequence.
|
|
18
|
+
*
|
|
19
|
+
* @param {Array<Object>} extensions - Normalized extensions (from extension-loader)
|
|
20
|
+
* @param {Object} context
|
|
21
|
+
* @param {Object} context.prisma - Prisma client instance
|
|
22
|
+
* @param {Object} context.appDefinition - Full app definition
|
|
23
|
+
* @throws {Error} If any bootstrap function fails (fails fast)
|
|
24
|
+
*/
|
|
25
|
+
async function runExtensionBootstraps(extensions, context = {}) {
|
|
26
|
+
if (!extensions || extensions.length === 0) return;
|
|
27
|
+
|
|
28
|
+
const { prisma, appDefinition } = context;
|
|
29
|
+
|
|
30
|
+
for (const ext of extensions) {
|
|
31
|
+
if (!ext.bootstrap) continue;
|
|
32
|
+
|
|
33
|
+
try {
|
|
34
|
+
await ext.bootstrap(prisma, appDefinition);
|
|
35
|
+
} catch (error) {
|
|
36
|
+
throw new Error(
|
|
37
|
+
`Extension "${ext.name}" bootstrap failed: ${error.message}`
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
module.exports = { runExtensionBootstraps };
|