@friggframework/core 2.0.0--canary.663.8de669c.0 → 2.0.0--canary.686.821f8a3.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/CHANGELOG.md +11 -0
- 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 +6 -1
- package/database/encryption/README.md +2 -0
- package/database/encryption/encryption-config.js +10 -31
- package/database/encryption/encryption-schema-registry.js +121 -24
- package/database/encryption/field-encryption-service.js +69 -5
- package/database/encryption/test-support/fake-ciphertext.js +15 -0
- package/database/organization-where.js +18 -0
- package/database/prisma.js +4 -2
- package/database/unique-violation.js +25 -0
- 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/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 -1
- 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-router.js +131 -96
- 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 +59 -76
- package/integrations/repositories/integration-repository-postgres.js +62 -76
- 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 +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/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-x-frigg-headers.js +83 -80
- package/user/user.js +64 -1
|
@@ -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,7 +58,12 @@ async function insertOne(client, collection, document) {
|
|
|
58
58
|
|
|
59
59
|
// Provide helpful context for common errors
|
|
60
60
|
if (error.code === 11000) {
|
|
61
|
-
|
|
61
|
+
// `code` lets callers recognise a lost race without parsing text
|
|
62
|
+
// (see database/unique-violation.js).
|
|
63
|
+
throw Object.assign(
|
|
64
|
+
new Error(`${errorMsg} - Duplicate key violation`),
|
|
65
|
+
{ code: 11000 }
|
|
66
|
+
);
|
|
62
67
|
}
|
|
63
68
|
throw new Error(errorMsg);
|
|
64
69
|
}
|
|
@@ -456,6 +456,8 @@ Format: "keyId:encryptedText:encryptedKey"
|
|
|
456
456
|
Example: "base64KeyId:iv:ciphertext:base64EncryptedDataKey"
|
|
457
457
|
```
|
|
458
458
|
|
|
459
|
+
**Recognising ciphertext on read.** A value is decrypted only when it has exactly four colon-separated parts: base64 `keyId`, 32-hex-character `iv`, hex ciphertext, base64 `encryptedKey`. Plaintext that merely contains colons (`https://user:pw@host:443`) is left alone. A value with that shape that still fails to decrypt (a wrong, rotated or missing key) fails the read with `FieldDecryptionError` in a deployed runtime (see [When Encryption Runs](#when-encryption-runs)), so ciphertext never reaches an API module as if it were a token. Locally it is returned as stored and logged as a warning, so one bad field does not fail a whole read. A field that becomes encrypted later (for example a module's `credentialFields`) stays plaintext in existing rows until they are next written.
|
|
460
|
+
|
|
459
461
|
**Why Envelope Encryption?**
|
|
460
462
|
|
|
461
463
|
- Reduces KMS API calls (one DEK per field, cached)
|
|
@@ -18,6 +18,9 @@
|
|
|
18
18
|
*/
|
|
19
19
|
|
|
20
20
|
const { logger } = require('./logger');
|
|
21
|
+
const {
|
|
22
|
+
isDeployedRuntime: isDeployedProviderRuntime,
|
|
23
|
+
} = require('../../providers/runtime-detection');
|
|
21
24
|
|
|
22
25
|
const LOCAL_BYPASS_STAGES = ['dev', 'test', 'local'];
|
|
23
26
|
const OPT_OUT_VAR = 'FRIGG_ENCRYPTION_DISABLED';
|
|
@@ -40,42 +43,18 @@ function isTrue(value) {
|
|
|
40
43
|
}
|
|
41
44
|
|
|
42
45
|
/**
|
|
43
|
-
* True when the process runs as a deployed function, on AWS Lambda or on
|
|
44
|
-
*
|
|
45
|
-
*
|
|
46
|
-
*
|
|
47
|
-
*
|
|
48
|
-
*
|
|
49
|
-
* CLI commands run from CI must not trip the deployed-stage check.
|
|
50
|
-
* - Other providers: FRIGG_PROVIDER names a non-AWS provider. Frigg's
|
|
51
|
-
* generated function entry points for that provider set it (provider-netlify
|
|
52
|
-
* sets 'netlify'), so it is present in every deployed function. Netlify
|
|
53
|
-
* exposes SITE_ID, CONTEXT and NETLIFY at build time only, so they cannot
|
|
54
|
-
* tell a running function from a laptop.
|
|
55
|
-
*
|
|
56
|
-
* A local run is never deployed: serverless-offline and `serverless invoke
|
|
57
|
-
* local` (which set the Lambda variables themselves) mark IS_OFFLINE /
|
|
58
|
-
* IS_LOCAL, `netlify dev` marks NETLIFY_DEV, and Jest marks JEST_WORKER_ID.
|
|
46
|
+
* True when the process runs as a deployed function, on AWS Lambda or on the
|
|
47
|
+
* active provider's platform (provider-netlify: FRIGG_PROVIDER=netlify, set by
|
|
48
|
+
* its generated entry points), and not under a local emulator or test runner.
|
|
49
|
+
* One rule for encryption and queue authentication: core/providers/
|
|
50
|
+
* runtime-detection asks the provider's detect(), and fails closed when a
|
|
51
|
+
* named non-AWS provider cannot be loaded.
|
|
59
52
|
*
|
|
60
53
|
* @param {Object} [env=process.env]
|
|
61
54
|
* @returns {boolean}
|
|
62
55
|
*/
|
|
63
56
|
function isDeployedRuntime(env = process.env) {
|
|
64
|
-
|
|
65
|
-
isTrue(env.IS_OFFLINE) ||
|
|
66
|
-
isTrue(env.IS_LOCAL) ||
|
|
67
|
-
isTrue(env.NETLIFY_DEV) ||
|
|
68
|
-
isSet(env.JEST_WORKER_ID);
|
|
69
|
-
if (localRun) return false;
|
|
70
|
-
|
|
71
|
-
const onAwsRuntime =
|
|
72
|
-
isSet(env.AWS_LAMBDA_FUNCTION_NAME) ||
|
|
73
|
-
isSet(env.LAMBDA_TASK_ROOT) ||
|
|
74
|
-
String(env.AWS_EXECUTION_ENV ?? '').startsWith('AWS_Lambda_');
|
|
75
|
-
if (onAwsRuntime) return true;
|
|
76
|
-
|
|
77
|
-
const provider = String(env.FRIGG_PROVIDER ?? '').trim().toLowerCase();
|
|
78
|
-
return provider !== '' && provider !== 'aws';
|
|
57
|
+
return isDeployedProviderRuntime(env);
|
|
79
58
|
}
|
|
80
59
|
|
|
81
60
|
function missingKeyMessage(stage) {
|
|
@@ -10,6 +10,11 @@
|
|
|
10
10
|
|
|
11
11
|
const { logger } = require('./logger');
|
|
12
12
|
const { registerDeniedKeys } = require('../../logs/denied-keys');
|
|
13
|
+
const {
|
|
14
|
+
getEntityTypeRegistry,
|
|
15
|
+
getEntityTypeDefinitions,
|
|
16
|
+
EntityRegistryError,
|
|
17
|
+
} = require('../../modules/entity-type-registry');
|
|
13
18
|
|
|
14
19
|
/**
|
|
15
20
|
* Core encryption schema (immutable - cannot be overridden by custom schemas)
|
|
@@ -39,6 +44,12 @@ const CORE_ENCRYPTION_SCHEMA = {
|
|
|
39
44
|
Token: {
|
|
40
45
|
fields: ['token'],
|
|
41
46
|
},
|
|
47
|
+
|
|
48
|
+
// Multi-step authorization (Management API v2): earlier steps can collect
|
|
49
|
+
// emails, usernames or one-time codes.
|
|
50
|
+
AuthorizationSession: {
|
|
51
|
+
fields: ['stepData'],
|
|
52
|
+
},
|
|
42
53
|
};
|
|
43
54
|
|
|
44
55
|
let customSchema = {};
|
|
@@ -160,8 +171,9 @@ function extractCredentialFieldsFromModules(moduleDefinitions) {
|
|
|
160
171
|
* Each module can declare credentialFields to encrypt in its encryption config.
|
|
161
172
|
*
|
|
162
173
|
* @param {Array} integrations - Array of integration classes with modules
|
|
174
|
+
* @param {object} [entities] - `appDefinition.entities` (ADR-059 registry)
|
|
163
175
|
*/
|
|
164
|
-
function loadModuleEncryptionSchemas(integrations) {
|
|
176
|
+
function loadModuleEncryptionSchemas(integrations, entities) {
|
|
165
177
|
if (!integrations) {
|
|
166
178
|
throw new Error('integrations parameter is required');
|
|
167
179
|
}
|
|
@@ -170,27 +182,39 @@ function loadModuleEncryptionSchemas(integrations) {
|
|
|
170
182
|
throw new Error('integrations must be an array');
|
|
171
183
|
}
|
|
172
184
|
|
|
173
|
-
|
|
185
|
+
// `entities` is the app definition's registry (ADR-059): a module an app
|
|
186
|
+
// registers without any integration still carries credentials to encrypt.
|
|
187
|
+
if (integrations.length === 0 && !entities) {
|
|
174
188
|
return;
|
|
175
189
|
}
|
|
176
190
|
|
|
177
|
-
const
|
|
178
|
-
|
|
179
|
-
|
|
191
|
+
const moduleDefinitions = getEntityTypeDefinitions(
|
|
192
|
+
getEntityTypeRegistry({ integrations, entities })
|
|
193
|
+
);
|
|
180
194
|
const credentialFields = extractCredentialFieldsFromModules(moduleDefinitions);
|
|
181
195
|
|
|
182
|
-
|
|
196
|
+
// Core fields are encrypted already and a custom schema may not repeat
|
|
197
|
+
// them. Everything the app registered itself stays: module fields are added
|
|
198
|
+
// to the custom schema, never substituted for it (other models included).
|
|
199
|
+
const coreFields = new Set(CORE_ENCRYPTION_SCHEMA.Credential?.fields || []);
|
|
200
|
+
const fields = [
|
|
201
|
+
...new Set([
|
|
202
|
+
...(customSchema.Credential?.fields || []),
|
|
203
|
+
...credentialFields.filter((field) => !coreFields.has(field)),
|
|
204
|
+
]),
|
|
205
|
+
];
|
|
206
|
+
|
|
207
|
+
if (fields.length === 0) {
|
|
183
208
|
return;
|
|
184
209
|
}
|
|
185
210
|
|
|
186
211
|
const moduleSchema = {
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
}
|
|
212
|
+
...customSchema,
|
|
213
|
+
Credential: { ...customSchema.Credential, fields },
|
|
190
214
|
};
|
|
191
215
|
|
|
192
216
|
logger.info(
|
|
193
|
-
`Registering module-level encryption for ${
|
|
217
|
+
`Registering module-level encryption for ${fields.length} credential fields`
|
|
194
218
|
);
|
|
195
219
|
|
|
196
220
|
registerCustomSchema(moduleSchema);
|
|
@@ -205,22 +229,80 @@ function loadModuleEncryptionSchemas(integrations) {
|
|
|
205
229
|
*
|
|
206
230
|
* Used by both Prisma (MongoDB/PostgreSQL) and DocumentDB encryption services.
|
|
207
231
|
*/
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
232
|
+
/**
|
|
233
|
+
* Registers encryption schemas declared by app-level extensions
|
|
234
|
+
* (`appDefinition.coreExtensions[].encryption`), e.g. the db-credentials
|
|
235
|
+
* extension's `OAuthAppCredential.clientSecret`.
|
|
236
|
+
*
|
|
237
|
+
* @param {Array<Object>} extensions - Normalized extensions (extension-loader)
|
|
238
|
+
*/
|
|
239
|
+
function loadExtensionEncryptionSchemas(extensions) {
|
|
240
|
+
if (!extensions || !Array.isArray(extensions) || extensions.length === 0) {
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
for (const ext of extensions) {
|
|
245
|
+
if (!ext.encryption || typeof ext.encryption !== 'object') {
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
const schema = {};
|
|
250
|
+
for (const [modelName, config] of Object.entries(ext.encryption)) {
|
|
251
|
+
if (config && Array.isArray(config.fields) && config.fields.length > 0) {
|
|
252
|
+
schema[modelName] = { fields: config.fields };
|
|
253
|
+
}
|
|
254
|
+
}
|
|
213
255
|
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
256
|
+
if (Object.keys(schema).length > 0) {
|
|
257
|
+
logger.info(
|
|
258
|
+
`Registering encryption schema from extension "${ext.name}" for models: ${Object.keys(schema).join(', ')}`
|
|
259
|
+
);
|
|
260
|
+
// registerCustomSchema replaces the registered schema, so merge:
|
|
261
|
+
// an extension adds its models to the app's encryption.schema
|
|
262
|
+
// rather than dropping it.
|
|
263
|
+
const merged = { ...customSchema };
|
|
264
|
+
for (const [modelName, config] of Object.entries(schema)) {
|
|
265
|
+
const existing = merged[modelName]?.fields || [];
|
|
266
|
+
merged[modelName] = {
|
|
267
|
+
...merged[modelName],
|
|
268
|
+
fields: [...new Set([...existing, ...config.fields])],
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
registerCustomSchema(merged);
|
|
217
272
|
}
|
|
273
|
+
}
|
|
274
|
+
}
|
|
218
275
|
|
|
219
|
-
|
|
220
|
-
|
|
276
|
+
function readAppDefinitionForEncryption() {
|
|
277
|
+
// Lazy require to avoid circular dependency issues
|
|
278
|
+
const {
|
|
279
|
+
getPresetAppDefinition,
|
|
280
|
+
} = require('../../handlers/app-definition-loader');
|
|
281
|
+
// A definition preset with setAppDefinition() (provider-netlify's
|
|
282
|
+
// preamble) wins: on Netlify process.cwd() cannot find the backend.
|
|
283
|
+
const preset = getPresetAppDefinition();
|
|
284
|
+
if (preset) {
|
|
285
|
+
return preset;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
const path = require('node:path');
|
|
289
|
+
const { findNearestBackendPackageJson } = require('../../utils');
|
|
290
|
+
|
|
291
|
+
const backendPackagePath = findNearestBackendPackageJson();
|
|
292
|
+
if (!backendPackagePath) {
|
|
293
|
+
return null; // No backend found, skip custom schema
|
|
294
|
+
}
|
|
221
295
|
|
|
222
|
-
|
|
223
|
-
|
|
296
|
+
const backendDir = path.dirname(backendPackagePath);
|
|
297
|
+
const backendIndexPath = path.join(backendDir, 'index.js');
|
|
298
|
+
|
|
299
|
+
const backendModule = require(backendIndexPath);
|
|
300
|
+
return backendModule?.Definition || null;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function loadCustomEncryptionSchema() {
|
|
304
|
+
try {
|
|
305
|
+
const appDefinition = readAppDefinitionForEncryption();
|
|
224
306
|
|
|
225
307
|
if (!appDefinition) {
|
|
226
308
|
return; // No app definition found
|
|
@@ -240,12 +322,26 @@ function loadCustomEncryptionSchema() {
|
|
|
240
322
|
registerEncryptionOptOut(disable);
|
|
241
323
|
}
|
|
242
324
|
|
|
325
|
+
// Load app-level extension encryption schemas. Before the module
|
|
326
|
+
// schemas: loadModuleEncryptionSchemas currently throws (see the
|
|
327
|
+
// NOTE inside it) and the throw would skip anything after it.
|
|
328
|
+
const { loadExtensions } = require('../../extensions/extension-loader');
|
|
329
|
+
const extensions = loadExtensions(appDefinition);
|
|
330
|
+
if (extensions.length > 0) {
|
|
331
|
+
loadExtensionEncryptionSchemas(extensions);
|
|
332
|
+
}
|
|
333
|
+
|
|
243
334
|
// Load module-level encryption schemas from integrations
|
|
244
335
|
const integrations = appDefinition.integrations;
|
|
245
|
-
if (
|
|
246
|
-
loadModuleEncryptionSchemas(
|
|
336
|
+
if (Array.isArray(integrations) || appDefinition.entities) {
|
|
337
|
+
loadModuleEncryptionSchemas(
|
|
338
|
+
Array.isArray(integrations) ? integrations : [],
|
|
339
|
+
appDefinition.entities
|
|
340
|
+
);
|
|
247
341
|
}
|
|
248
342
|
} catch (error) {
|
|
343
|
+
// A bad entity registry is a configuration error, not "no custom schema".
|
|
344
|
+
if (error instanceof EntityRegistryError) throw error;
|
|
249
345
|
// Silently ignore errors - custom schema is optional
|
|
250
346
|
// This handles cases like:
|
|
251
347
|
// - Backend package.json not found (tests, standalone usage)
|
|
@@ -396,6 +492,7 @@ module.exports = {
|
|
|
396
492
|
registerEncryptionOptOut,
|
|
397
493
|
loadCustomEncryptionSchema,
|
|
398
494
|
loadModuleEncryptionSchemas,
|
|
495
|
+
loadExtensionEncryptionSchemas,
|
|
399
496
|
extractCredentialFieldsFromModules,
|
|
400
497
|
validateCustomSchema,
|
|
401
498
|
validateOptOut,
|