@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
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
/* eslint-disable camelcase -- JWT claim names (org_id, org_role) and reason codes are snake_case by spec */
|
|
2
|
+
const jose = require('jose');
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Key material and token signing for adopter-JWT tests. Real keys and real
|
|
6
|
+
* signatures: nothing here fakes the verifier.
|
|
7
|
+
*/
|
|
8
|
+
async function createKeys() {
|
|
9
|
+
const es = await jose.generateKeyPair('ES256');
|
|
10
|
+
const rs = await jose.generateKeyPair('RS256');
|
|
11
|
+
const attacker = await jose.generateKeyPair('ES256');
|
|
12
|
+
const publicJwks = {
|
|
13
|
+
keys: [
|
|
14
|
+
{
|
|
15
|
+
...(await jose.exportJWK(es.publicKey)),
|
|
16
|
+
kid: 'es-1',
|
|
17
|
+
alg: 'ES256',
|
|
18
|
+
use: 'sig',
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
...(await jose.exportJWK(rs.publicKey)),
|
|
22
|
+
kid: 'rs-1',
|
|
23
|
+
alg: 'RS256',
|
|
24
|
+
use: 'sig',
|
|
25
|
+
},
|
|
26
|
+
],
|
|
27
|
+
};
|
|
28
|
+
return {
|
|
29
|
+
es,
|
|
30
|
+
rs,
|
|
31
|
+
attacker,
|
|
32
|
+
publicJwks,
|
|
33
|
+
localJwks: jose.createLocalJWKSet(publicJwks),
|
|
34
|
+
hmacSecret: 'a-shared-secret-that-is-long-enough-for-hs256',
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* @param {Object} claims
|
|
40
|
+
* @param {Object} opts
|
|
41
|
+
* @param {Object|Uint8Array} opts.key - signing key
|
|
42
|
+
* @param {string} [opts.alg='ES256']
|
|
43
|
+
* @param {string} [opts.kid]
|
|
44
|
+
* @param {string|null} [opts.exp='5m'] - null omits exp
|
|
45
|
+
*/
|
|
46
|
+
async function signToken(
|
|
47
|
+
claims,
|
|
48
|
+
{ key, alg = 'ES256', kid, exp = '5m', iss, aud, nbf } = {}
|
|
49
|
+
) {
|
|
50
|
+
const jwt = new jose.SignJWT(claims)
|
|
51
|
+
.setProtectedHeader(kid ? { alg, kid } : { alg })
|
|
52
|
+
.setIssuedAt();
|
|
53
|
+
if (exp !== null) jwt.setExpirationTime(exp);
|
|
54
|
+
if (iss) jwt.setIssuer(iss);
|
|
55
|
+
if (aud) jwt.setAudience(aud);
|
|
56
|
+
if (nbf) jwt.setNotBefore(nbf);
|
|
57
|
+
return jwt.sign(key);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const b64url = (value) =>
|
|
61
|
+
Buffer.from(JSON.stringify(value)).toString('base64url');
|
|
62
|
+
|
|
63
|
+
/** An unsigned token: `alg: none`, empty signature. */
|
|
64
|
+
function unsignedToken(claims) {
|
|
65
|
+
return `${b64url({ alg: 'none', typ: 'JWT' })}.${b64url({
|
|
66
|
+
...claims,
|
|
67
|
+
exp: Math.floor(Date.now() / 1000) + 300,
|
|
68
|
+
})}.`;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Resolves each `wait()` only once `parties` callers have arrived, so a test
|
|
73
|
+
* can make concurrent requests all read before any of them writes.
|
|
74
|
+
*/
|
|
75
|
+
function createBarrier(parties) {
|
|
76
|
+
let arrived = 0;
|
|
77
|
+
let release;
|
|
78
|
+
const gate = new Promise((resolve) => {
|
|
79
|
+
release = resolve;
|
|
80
|
+
});
|
|
81
|
+
return {
|
|
82
|
+
async wait() {
|
|
83
|
+
arrived += 1;
|
|
84
|
+
if (arrived >= parties) release();
|
|
85
|
+
await gate;
|
|
86
|
+
},
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Stateful fake of the user repository, built from jest.fn so every call is
|
|
92
|
+
* observable. Individuals carry `organizationId`, as the real repositories
|
|
93
|
+
* return it. Like the database, it refuses a second individual with the same
|
|
94
|
+
* `appUserId` (a Prisma-shaped `P2002`), which is what a first-login race hits.
|
|
95
|
+
*
|
|
96
|
+
* @param {Object} [options]
|
|
97
|
+
* @param {number} [options.findBarrier] Make the first N calls to
|
|
98
|
+
* `findIndividualUserByAppUserId` wait for each other (see createBarrier).
|
|
99
|
+
*/
|
|
100
|
+
function createUserRepositoryDouble({
|
|
101
|
+
individuals = [],
|
|
102
|
+
organizations = [],
|
|
103
|
+
findBarrier = 0,
|
|
104
|
+
} = {}) {
|
|
105
|
+
const individualUsers = new Map(
|
|
106
|
+
individuals.map((u) => [u.appUserId, { ...u }])
|
|
107
|
+
);
|
|
108
|
+
const organizationUsers = new Map(
|
|
109
|
+
organizations.map((o) => [o.appOrgId, { ...o }])
|
|
110
|
+
);
|
|
111
|
+
const barrier = findBarrier > 1 ? createBarrier(findBarrier) : null;
|
|
112
|
+
let barrierCalls = 0;
|
|
113
|
+
let seq = 0;
|
|
114
|
+
|
|
115
|
+
const repo = {
|
|
116
|
+
findIndividualUserByAppUserId: jest.fn(async (appUserId) => {
|
|
117
|
+
const found = individualUsers.get(appUserId) ?? null;
|
|
118
|
+
if (barrier && barrierCalls < findBarrier) {
|
|
119
|
+
barrierCalls += 1;
|
|
120
|
+
await barrier.wait();
|
|
121
|
+
}
|
|
122
|
+
return found && { ...found };
|
|
123
|
+
}),
|
|
124
|
+
findOrganizationUserByAppOrgId: jest.fn(
|
|
125
|
+
async (appOrgId) => organizationUsers.get(appOrgId) ?? null
|
|
126
|
+
),
|
|
127
|
+
createIndividualUser: jest.fn(async (params) => {
|
|
128
|
+
if (individualUsers.has(params.appUserId)) {
|
|
129
|
+
throw Object.assign(
|
|
130
|
+
new Error('Unique constraint failed on appUserId'),
|
|
131
|
+
{ code: 'P2002' }
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
const created = {
|
|
135
|
+
id: `ind-${++seq}`,
|
|
136
|
+
organizationId: undefined,
|
|
137
|
+
...params,
|
|
138
|
+
};
|
|
139
|
+
individualUsers.set(created.appUserId, created);
|
|
140
|
+
return { ...created };
|
|
141
|
+
}),
|
|
142
|
+
createOrganizationUser: jest.fn(async (params) => {
|
|
143
|
+
const created = { id: `org-${++seq}`, ...params };
|
|
144
|
+
organizationUsers.set(created.appOrgId, created);
|
|
145
|
+
return created;
|
|
146
|
+
}),
|
|
147
|
+
findIndividualUserById: jest.fn(async (id) => {
|
|
148
|
+
for (const u of individualUsers.values()) {
|
|
149
|
+
if (u.id === id) return { ...u };
|
|
150
|
+
}
|
|
151
|
+
return null;
|
|
152
|
+
}),
|
|
153
|
+
// Like the database: sets the pointer only while it is unset.
|
|
154
|
+
linkIndividualToOrganizationIfUnset: jest.fn(
|
|
155
|
+
async (individualId, organizationId) => {
|
|
156
|
+
for (const u of individualUsers.values()) {
|
|
157
|
+
if (u.id !== individualId) continue;
|
|
158
|
+
const unset =
|
|
159
|
+
u.organizationId === undefined ||
|
|
160
|
+
u.organizationId === null ||
|
|
161
|
+
u.organizationId === '';
|
|
162
|
+
if (unset) u.organizationId = organizationId;
|
|
163
|
+
return { ...u };
|
|
164
|
+
}
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
),
|
|
168
|
+
};
|
|
169
|
+
repo.state = { individualUsers, organizationUsers };
|
|
170
|
+
return repo;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* In-memory organization membership repository: atomic, like the real ones. The
|
|
175
|
+
* pair is unique and `addMembership` is an upsert. It knows nothing of the
|
|
176
|
+
* legacy `organizationId` pointer; the domain (user/membership.js) does.
|
|
177
|
+
*/
|
|
178
|
+
function createMembershipRepositoryDouble() {
|
|
179
|
+
const { toMembership } = require('../../repositories/organization-membership-record');
|
|
180
|
+
const rows = new Map();
|
|
181
|
+
const key = (i, o) => `${i}|${o}`;
|
|
182
|
+
let seq = 0;
|
|
183
|
+
|
|
184
|
+
const repo = {
|
|
185
|
+
findMembership: jest.fn(async (individualId, organizationId) => {
|
|
186
|
+
const row = rows.get(key(individualId, organizationId));
|
|
187
|
+
return row ? toMembership(row) : null;
|
|
188
|
+
}),
|
|
189
|
+
addMembership: jest.fn(
|
|
190
|
+
async (individualId, organizationId, { orgRole } = {}) => {
|
|
191
|
+
const k = key(individualId, organizationId);
|
|
192
|
+
if (!rows.has(k)) {
|
|
193
|
+
rows.set(k, {
|
|
194
|
+
id: `mem-${++seq}`,
|
|
195
|
+
individualUserId: individualId,
|
|
196
|
+
organizationUserId: organizationId,
|
|
197
|
+
orgRole: orgRole ?? 'MEMBER',
|
|
198
|
+
createdAt: new Date(),
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
return toMembership(rows.get(k));
|
|
202
|
+
}
|
|
203
|
+
),
|
|
204
|
+
listMembershipsForOrganization: jest.fn(async (organizationId) =>
|
|
205
|
+
[...rows.values()]
|
|
206
|
+
.filter((r) => r.organizationUserId === organizationId)
|
|
207
|
+
.map(toMembership)
|
|
208
|
+
),
|
|
209
|
+
};
|
|
210
|
+
repo.rows = rows;
|
|
211
|
+
return repo;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
module.exports = {
|
|
215
|
+
createKeys,
|
|
216
|
+
signToken,
|
|
217
|
+
unsignedToken,
|
|
218
|
+
createUserRepositoryDouble,
|
|
219
|
+
createMembershipRepositoryDouble,
|
|
220
|
+
};
|
|
@@ -23,7 +23,7 @@ class TestUserRepository {
|
|
|
23
23
|
|
|
24
24
|
async createToken(userId, rawToken, minutes = 120) {
|
|
25
25
|
const token = `token-for-${userId}-for-${minutes}-mins`;
|
|
26
|
-
this.tokens.set(token, {
|
|
26
|
+
this.tokens.set(token, { user: userId, rawToken });
|
|
27
27
|
return token;
|
|
28
28
|
}
|
|
29
29
|
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
const Boom = require('@hapi/boom');
|
|
2
2
|
const { getLogger } = require('../../logs');
|
|
3
|
+
const { AUTH_SOURCES } = require('../user');
|
|
3
4
|
|
|
4
5
|
const log = getLogger('frigg.user.authentication');
|
|
5
6
|
|
|
@@ -68,10 +69,13 @@ class AuthenticateUser {
|
|
|
68
69
|
// Validate the API key (authentication)
|
|
69
70
|
await this.authenticateWithSharedSecret.execute(apiKey);
|
|
70
71
|
// Get user from x-frigg headers (authorization)
|
|
71
|
-
|
|
72
|
+
const user = await this.getUserFromXFriggHeaders.execute(
|
|
72
73
|
appUserId,
|
|
73
74
|
appOrgId
|
|
74
75
|
);
|
|
76
|
+
// The app's own backend: trusted to manage organization things.
|
|
77
|
+
user.setAuthSource(AUTH_SOURCES.SHARED_SECRET);
|
|
78
|
+
return user;
|
|
75
79
|
}
|
|
76
80
|
log.debug('No x-frigg-api-key header, skipping shared secret', {
|
|
77
81
|
eventName: `${log.name}.shared_secret_skipped`,
|
|
@@ -90,6 +94,7 @@ class AuthenticateUser {
|
|
|
90
94
|
// Detect JWT format (3 parts separated by dots)
|
|
91
95
|
if (token && token.split('.').length === 3) {
|
|
92
96
|
const user = await this.getUserFromAdopterJwt.execute(token);
|
|
97
|
+
user.setAuthSource(AUTH_SOURCES.ADOPTER_JWT);
|
|
93
98
|
// Validate x-frigg headers match JWT claims if present
|
|
94
99
|
if (appUserId || appOrgId) {
|
|
95
100
|
this.validateUserMatch(user, appUserId, appOrgId);
|
|
@@ -106,6 +111,7 @@ class AuthenticateUser {
|
|
|
106
111
|
const user = await this.getUserFromBearerToken.execute(
|
|
107
112
|
req.headers.authorization
|
|
108
113
|
);
|
|
114
|
+
user.setAuthSource(AUTH_SOURCES.BEARER_TOKEN);
|
|
109
115
|
// Validate x-frigg headers match token user if present
|
|
110
116
|
if (appUserId || appOrgId) {
|
|
111
117
|
this.validateUserMatch(user, appUserId, appOrgId);
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
const { getLogger } = require('../../logs');
|
|
2
|
+
const { isPresent, implicitMembership } = require('../membership');
|
|
3
|
+
|
|
4
|
+
const log = getLogger('frigg.user.membership');
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Makes sure a person is a member of the organization a request is acting in
|
|
8
|
+
* (ADR-056 §3.6). Shared by the adopter-token and x-frigg header paths.
|
|
9
|
+
*
|
|
10
|
+
* - Already a member (a stored row, or the legacy `organizationId` pointer
|
|
11
|
+
* read as an implicit membership): nothing is written.
|
|
12
|
+
* - Not a member: a membership is added, unless the caller asks for existing
|
|
13
|
+
* memberships only (`requireExisting`), in which case nothing is written and
|
|
14
|
+
* `membership` is null so the caller can refuse.
|
|
15
|
+
* - The legacy `organizationId` is set when the person has none (their first
|
|
16
|
+
* link) and never changed afterwards. It is a pointer for old readers, not
|
|
17
|
+
* the active organization: that is whichever organization the request names.
|
|
18
|
+
*
|
|
19
|
+
* Adding is an idempotent upsert, so two first logins racing for different
|
|
20
|
+
* organizations both succeed.
|
|
21
|
+
*
|
|
22
|
+
* @class EnsureOrganizationMembership
|
|
23
|
+
*/
|
|
24
|
+
class EnsureOrganizationMembership {
|
|
25
|
+
/**
|
|
26
|
+
* @param {Object} params
|
|
27
|
+
* @param {import('../repositories/user-repository-interface').UserRepositoryInterface} params.userRepository
|
|
28
|
+
* @param {import('../repositories/organization-membership-repository-interface').OrganizationMembershipRepositoryInterface} params.organizationMembershipRepository
|
|
29
|
+
*/
|
|
30
|
+
constructor({ userRepository, organizationMembershipRepository }) {
|
|
31
|
+
this.userRepository = userRepository;
|
|
32
|
+
this.organizationMembershipRepository = organizationMembershipRepository;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* @param {Object} params
|
|
37
|
+
* @param {Object|null} params.individual Individual user as the repository returns it.
|
|
38
|
+
* @param {Object|null} params.organization The active organization user.
|
|
39
|
+
* @param {string|null} [params.orgRole] Role to store with a new membership.
|
|
40
|
+
* @param {boolean} [params.requireExisting=false] Refuse to add.
|
|
41
|
+
* @returns {Promise<{individual: Object|null, membership: Object|null}>}
|
|
42
|
+
* `individual` may be the updated record (legacy pointer set).
|
|
43
|
+
*/
|
|
44
|
+
async execute({
|
|
45
|
+
individual,
|
|
46
|
+
organization,
|
|
47
|
+
orgRole = null,
|
|
48
|
+
requireExisting = false,
|
|
49
|
+
}) {
|
|
50
|
+
// A request that names no organization, or no person (organization-only
|
|
51
|
+
// auth), has no membership to check or add.
|
|
52
|
+
if (!individual || !organization) {
|
|
53
|
+
return { individual, membership: null };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const existing =
|
|
57
|
+
(await this.organizationMembershipRepository.findMembership(
|
|
58
|
+
individual.id,
|
|
59
|
+
organization.id
|
|
60
|
+
)) ?? implicitMembership(individual, organization.id);
|
|
61
|
+
if (existing) {
|
|
62
|
+
return { individual, membership: existing };
|
|
63
|
+
}
|
|
64
|
+
if (requireExisting) {
|
|
65
|
+
return { individual, membership: null };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const membership =
|
|
69
|
+
await this.organizationMembershipRepository.addMembership(
|
|
70
|
+
individual.id,
|
|
71
|
+
organization.id,
|
|
72
|
+
{ orgRole }
|
|
73
|
+
);
|
|
74
|
+
log.debug('Organization membership added', {
|
|
75
|
+
eventName: `${log.name}.added`,
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
// The database repeats this condition in the update itself, so a
|
|
79
|
+
// concurrent first link by another request cannot be overwritten.
|
|
80
|
+
let updated = individual;
|
|
81
|
+
if (!isPresent(individual.organizationId)) {
|
|
82
|
+
updated =
|
|
83
|
+
(await this.userRepository.linkIndividualToOrganizationIfUnset(
|
|
84
|
+
individual.id,
|
|
85
|
+
organization.id
|
|
86
|
+
)) ?? individual;
|
|
87
|
+
}
|
|
88
|
+
return { individual: updated, membership };
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
module.exports = { EnsureOrganizationMembership };
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
const { sameId } = require('../membership');
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The individual users who belong to an organization (ADR-056 §3.6): the
|
|
5
|
+
* people with a stored membership, plus those the legacy
|
|
6
|
+
* `IndividualUser.organizationId` pointer places there, each once.
|
|
7
|
+
*
|
|
8
|
+
* Both repositories stay atomic; the union is composed here. Reading only the
|
|
9
|
+
* legacy pointer would list a person in the first organization they ever
|
|
10
|
+
* joined and in no other.
|
|
11
|
+
*
|
|
12
|
+
* @class FindIndividualUsersByOrganization
|
|
13
|
+
*/
|
|
14
|
+
class FindIndividualUsersByOrganization {
|
|
15
|
+
/**
|
|
16
|
+
* @param {Object} params
|
|
17
|
+
* @param {import('../repositories/user-repository-interface').UserRepositoryInterface} params.userRepository
|
|
18
|
+
* @param {import('../repositories/organization-membership-repository-interface').OrganizationMembershipRepositoryInterface} params.organizationMembershipRepository
|
|
19
|
+
*/
|
|
20
|
+
constructor({ userRepository, organizationMembershipRepository }) {
|
|
21
|
+
this.userRepository = userRepository;
|
|
22
|
+
this.organizationMembershipRepository = organizationMembershipRepository;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* @param {string|number} organizationUserId
|
|
27
|
+
* @returns {Promise<Object[]>} Individual users, legacy-pointer people first.
|
|
28
|
+
*/
|
|
29
|
+
async execute(organizationUserId) {
|
|
30
|
+
const [legacy, memberships] = await Promise.all([
|
|
31
|
+
this.userRepository.findIndividualUsersByOrganizationId(
|
|
32
|
+
organizationUserId
|
|
33
|
+
),
|
|
34
|
+
this.organizationMembershipRepository.listMembershipsForOrganization(
|
|
35
|
+
organizationUserId
|
|
36
|
+
),
|
|
37
|
+
]);
|
|
38
|
+
|
|
39
|
+
const users = [...(legacy || [])];
|
|
40
|
+
for (const { individualUserId } of memberships) {
|
|
41
|
+
if (users.some((u) => sameId(u.id ?? u._id, individualUserId))) {
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
const individual = await this.userRepository.findIndividualUserById(
|
|
45
|
+
individualUserId
|
|
46
|
+
);
|
|
47
|
+
// A membership whose person was deleted is skipped, not an error.
|
|
48
|
+
if (individual) users.push(individual);
|
|
49
|
+
}
|
|
50
|
+
return users;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
module.exports = { FindIndividualUsersByOrganization };
|
|
@@ -1,149 +1,120 @@
|
|
|
1
|
-
const
|
|
1
|
+
const { getLogger } = require('../../logs');
|
|
2
|
+
const { fail } = require('../adopter-jwt-errors');
|
|
3
|
+
const {
|
|
4
|
+
findAppUsers,
|
|
5
|
+
createMissingAppUsers,
|
|
6
|
+
buildUser,
|
|
7
|
+
} = require('../app-user-helpers');
|
|
8
|
+
|
|
9
|
+
const log = getLogger('frigg.user.adopter_jwt');
|
|
10
|
+
|
|
11
|
+
const idFromClaim = (value) => {
|
|
12
|
+
if (typeof value === 'string' && value.trim() !== '') return value;
|
|
13
|
+
if (typeof value === 'number' && Number.isFinite(value))
|
|
14
|
+
return String(value);
|
|
15
|
+
return null;
|
|
16
|
+
};
|
|
2
17
|
|
|
3
18
|
/**
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* When implemented, this will allow adopters to use their own JWT tokens
|
|
8
|
-
* for authentication instead of Frigg's native token system.
|
|
9
|
-
*
|
|
10
|
-
* FUTURE IMPLEMENTATION REQUIREMENTS:
|
|
11
|
-
* - Validate JWT signature using jwtConfig.secret from app definition
|
|
12
|
-
* - Support configurable signing algorithms (HS256, HS384, HS512, RS256, RS384, RS512)
|
|
13
|
-
* - Extract user identifiers from JWT claims based on jwtConfig.userIdClaim and jwtConfig.orgIdClaim
|
|
14
|
-
* - Find or create user based on extracted claim values
|
|
15
|
-
* - Handle token expiration and validation errors
|
|
16
|
-
* - Support refresh tokens (optional)
|
|
17
|
-
* - Validate user ID conflicts if both individual and org IDs present in JWT
|
|
19
|
+
* Authenticates a request by a token issued by the adopter's own identity
|
|
20
|
+
* system (ADR-056 §2): verifies it, then finds or creates the individual and
|
|
21
|
+
* organization users it names.
|
|
18
22
|
*
|
|
19
|
-
*
|
|
20
|
-
* -
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
* @todo Implement JWT validation with jsonwebtoken package
|
|
26
|
-
* @todo Add unit tests for JWT parsing and claim extraction
|
|
27
|
-
* @todo Document adopter JWT integration guide in Frigg docs
|
|
28
|
-
* @todo Add support for JWT refresh tokens
|
|
29
|
-
* @todo Implement JWT public key caching for RS* algorithms
|
|
23
|
+
* The organization the token names is the request's active organization
|
|
24
|
+
* (ADR-056 §3.6). A person who is not yet a member of it becomes one; a person
|
|
25
|
+
* can belong to several, and `IndividualUser.organizationId` is never moved
|
|
26
|
+
* (see EnsureOrganizationMembership). Two first logins racing for the same new
|
|
27
|
+
* person or organization both succeed: a create that loses to a unique
|
|
28
|
+
* constraint finds the winner's row.
|
|
30
29
|
*
|
|
31
30
|
* @class GetUserFromAdopterJwt
|
|
32
31
|
*/
|
|
33
32
|
class GetUserFromAdopterJwt {
|
|
34
33
|
/**
|
|
35
|
-
*
|
|
36
|
-
* @param {
|
|
37
|
-
* @param {import('../repositories/user-repository-interface').UserRepositoryInterface} params.userRepository - Repository for user data operations.
|
|
34
|
+
* @param {Object} params
|
|
35
|
+
* @param {import('../repositories/user-repository-interface').UserRepositoryInterface} params.userRepository
|
|
38
36
|
* @param {Object} params.userConfig - The user config in the app definition.
|
|
37
|
+
* @param {import('./ensure-organization-membership').EnsureOrganizationMembership} params.ensureOrganizationMembership
|
|
38
|
+
* @param {{verify: Function, claimNames: Object}} params.tokenVerifier -
|
|
39
|
+
* from `createAdopterTokenVerifier`.
|
|
39
40
|
*/
|
|
40
|
-
constructor({
|
|
41
|
+
constructor({
|
|
42
|
+
userRepository,
|
|
43
|
+
ensureOrganizationMembership,
|
|
44
|
+
userConfig,
|
|
45
|
+
tokenVerifier,
|
|
46
|
+
}) {
|
|
41
47
|
this.userRepository = userRepository;
|
|
48
|
+
this.ensureOrganizationMembership = ensureOrganizationMembership;
|
|
42
49
|
this.userConfig = userConfig;
|
|
50
|
+
this.tokenVerifier = tokenVerifier;
|
|
43
51
|
}
|
|
44
52
|
|
|
45
53
|
/**
|
|
46
|
-
* Executes the use case.
|
|
47
54
|
* @async
|
|
48
|
-
* @param {string}
|
|
49
|
-
* @returns {Promise<import('../user').User>}
|
|
50
|
-
* @throws {Boom}
|
|
55
|
+
* @param {string} token - The JWT from the Authorization header.
|
|
56
|
+
* @returns {Promise<import('../user').User>}
|
|
57
|
+
* @throws {Boom} 401 with `data.reason` for a token the verifier refuses
|
|
58
|
+
* (including `token_missing_user_claim`).
|
|
59
|
+
* @throws {Boom} 503 `jwks_unavailable`, 500 `jwt_config_invalid` (from the verifier).
|
|
51
60
|
*/
|
|
52
|
-
async execute(
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
'Please use one of the supported authentication modes instead: ' +
|
|
57
|
-
'friggToken (native bearer token) or xFriggHeaders (backend-to-backend with x-frigg-appUserId/appOrgId headers).'
|
|
58
|
-
);
|
|
61
|
+
async execute(token) {
|
|
62
|
+
const claims = await this.tokenVerifier.verify(token);
|
|
63
|
+
const { userIdClaim, orgIdClaim, roleClaim } =
|
|
64
|
+
this.tokenVerifier.claimNames;
|
|
59
65
|
|
|
60
|
-
|
|
66
|
+
const appUserId = idFromClaim(claims[userIdClaim]);
|
|
67
|
+
if (!appUserId) throw fail('token_missing_user_claim');
|
|
61
68
|
|
|
62
|
-
const
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
throw Boom.badImplementation('JWT configuration is required when adopterJwt auth mode is enabled');
|
|
69
|
+
const rawOrgId = claims[orgIdClaim];
|
|
70
|
+
const appOrgId = idFromClaim(rawOrgId);
|
|
71
|
+
if (rawOrgId !== undefined && rawOrgId !== null && !appOrgId) {
|
|
72
|
+
throw fail('token_malformed');
|
|
67
73
|
}
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
74
|
+
const role = claims[roleClaim];
|
|
75
|
+
|
|
76
|
+
const orgRole = typeof role === 'string' && role !== '' ? role : null;
|
|
77
|
+
const { user, membership } = await this._findOrCreateUser(
|
|
78
|
+
appUserId,
|
|
79
|
+
appOrgId,
|
|
80
|
+
orgRole
|
|
81
|
+
);
|
|
82
|
+
user.setOrgRole(orgRole);
|
|
83
|
+
// What the membership row says: the role when the token carries none.
|
|
84
|
+
user.setMembershipRole(membership?.orgRole ?? null);
|
|
85
|
+
|
|
86
|
+
log.debug('Adopter token accepted', {
|
|
87
|
+
eventName: `${log.name}.accepted`,
|
|
88
|
+
hasOrganization: Boolean(user.getOrganizationUser()),
|
|
89
|
+
});
|
|
90
|
+
return user;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async _findOrCreateUser(appUserId, appOrgId, orgRole) {
|
|
94
|
+
const cfg = this.userConfig;
|
|
95
|
+
const found = await findAppUsers(this.userRepository, cfg, {
|
|
96
|
+
appUserId,
|
|
97
|
+
appOrgId,
|
|
98
|
+
});
|
|
99
|
+
const created = await createMissingAppUsers(this.userRepository, cfg, {
|
|
100
|
+
appUserId,
|
|
101
|
+
appOrgId,
|
|
102
|
+
...found,
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
// The token's organization is the active one whether or not this is
|
|
106
|
+
// the person's first time in it.
|
|
107
|
+
const { individual, membership } =
|
|
108
|
+
await this.ensureOrganizationMembership.execute({
|
|
109
|
+
individual: created.individual,
|
|
110
|
+
organization: created.organization,
|
|
111
|
+
orgRole,
|
|
73
112
|
});
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
// At least one identifier required
|
|
80
|
-
if (!appUserId && !appOrgId) {
|
|
81
|
-
throw Boom.badRequest('JWT must contain user or organization identifier claims');
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
// Find existing users
|
|
85
|
-
let individualUserData = null;
|
|
86
|
-
let organizationUserData = null;
|
|
87
|
-
|
|
88
|
-
if (appUserId) {
|
|
89
|
-
individualUserData = await this.userRepository.findIndividualUserByAppUserId(appUserId);
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
if (appOrgId) {
|
|
93
|
-
organizationUserData = await this.userRepository.findOrganizationUserByAppOrgId(appOrgId);
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
// Validate no conflicts if both IDs present
|
|
97
|
-
if (appUserId && appOrgId && individualUserData && organizationUserData) {
|
|
98
|
-
const individualOrgId = individualUserData.organizationUser?.toString();
|
|
99
|
-
const expectedOrgId = organizationUserData.id?.toString();
|
|
100
|
-
|
|
101
|
-
if (individualOrgId !== expectedOrgId) {
|
|
102
|
-
throw Boom.badRequest(
|
|
103
|
-
'User ID mismatch: JWT claims refer to different users. ' +
|
|
104
|
-
'Individual and organization IDs must belong to the same user.'
|
|
105
|
-
);
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
// Auto-create if not found
|
|
110
|
-
if (!individualUserData && !organizationUserData) {
|
|
111
|
-
if (appUserId) {
|
|
112
|
-
individualUserData = await this.userRepository.createIndividualUser({
|
|
113
|
-
appUserId,
|
|
114
|
-
username: `jwt-user-${appUserId}`,
|
|
115
|
-
email: decoded.email || `${appUserId}@jwt.local`,
|
|
116
|
-
});
|
|
117
|
-
} else {
|
|
118
|
-
organizationUserData = await this.userRepository.createOrganizationUser({
|
|
119
|
-
appOrgId,
|
|
120
|
-
});
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
return new User(
|
|
125
|
-
individualUserData,
|
|
126
|
-
organizationUserData,
|
|
127
|
-
this.userConfig.usePassword,
|
|
128
|
-
this.userConfig.primary,
|
|
129
|
-
this.userConfig.individualUserRequired,
|
|
130
|
-
this.userConfig.organizationUserRequired
|
|
131
|
-
);
|
|
132
|
-
|
|
133
|
-
} catch (error) {
|
|
134
|
-
if (error.name === 'TokenExpiredError') {
|
|
135
|
-
throw Boom.unauthorized('JWT token has expired');
|
|
136
|
-
} else if (error.name === 'JsonWebTokenError') {
|
|
137
|
-
throw Boom.unauthorized('Invalid JWT token');
|
|
138
|
-
} else if (error.isBoom) {
|
|
139
|
-
throw error;
|
|
140
|
-
}
|
|
141
|
-
throw Boom.unauthorized('JWT authentication failed');
|
|
142
|
-
}
|
|
143
|
-
*/
|
|
113
|
+
return {
|
|
114
|
+
user: buildUser(cfg, individual, created.organization),
|
|
115
|
+
membership,
|
|
116
|
+
};
|
|
144
117
|
}
|
|
145
118
|
}
|
|
146
119
|
|
|
147
120
|
module.exports = { GetUserFromAdopterJwt };
|
|
148
|
-
|
|
149
|
-
|