@friggframework/core 2.0.0--canary.688.87a9bf3.0 → 2.0.0--canary.690.d043f23.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/entity-commands.js +60 -18
- 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 +167 -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 +118 -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 +11 -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 +63 -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/tests/doubles/test-integration-repository.js +12 -1
- package/integrations/use-cases/create-integration.js +55 -20
- package/integrations/use-cases/get-integrations-for-user.js +80 -40
- package/integrations/use-cases/index.js +5 -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 +57 -0
- package/management-api/openapi/build-openapi.js +144 -0
- package/management-api/openapi/components.js +414 -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 +294 -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-bases.js +169 -0
- package/modules/proxy/proxy-errors.js +31 -0
- package/modules/proxy/proxy-path.js +183 -0
- package/modules/proxy/proxy-policy.js +265 -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 +245 -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 +331 -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 +13 -0
- package/providers/resolve-provider.js +93 -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 +199 -0
- package/queues/providers/sqs-queue-provider.js +70 -0
- package/queues/queue-client-interface.js +55 -0
- package/queues/queue-message-auth.js +187 -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 +214 -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
- package/errors/mapping-already-exists-error.js +0 -14
- package/modules/utils/to-credential-id.js +0 -14
|
@@ -4,7 +4,7 @@ const {
|
|
|
4
4
|
toObjectId,
|
|
5
5
|
fromObjectId,
|
|
6
6
|
findOne,
|
|
7
|
-
|
|
7
|
+
findManyDrained,
|
|
8
8
|
insertOne,
|
|
9
9
|
updateOne,
|
|
10
10
|
deleteOne,
|
|
@@ -72,7 +72,9 @@ class UserRepositoryDocumentDB extends UserRepositoryInterface {
|
|
|
72
72
|
}
|
|
73
73
|
|
|
74
74
|
async findIndividualUsersByOrganizationId(organizationUserId) {
|
|
75
|
-
|
|
75
|
+
// Drained: findMany returns only the first cursor batch, which would
|
|
76
|
+
// drop people from a large organization.
|
|
77
|
+
const docs = await findManyDrained(this.prisma, 'User', {
|
|
76
78
|
organizationId: toObjectId(organizationUserId),
|
|
77
79
|
type: 'INDIVIDUAL',
|
|
78
80
|
});
|
|
@@ -421,6 +423,29 @@ class UserRepositoryDocumentDB extends UserRepositoryInterface {
|
|
|
421
423
|
);
|
|
422
424
|
return this._mapUser(decrypted);
|
|
423
425
|
}
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* Set the legacy organizationId only if it is still null or absent (see the
|
|
429
|
+
* interface): the filter carries the condition, so it is one atomic update.
|
|
430
|
+
* @param {string} individualUserId
|
|
431
|
+
* @param {string} organizationUserId
|
|
432
|
+
* @returns {Promise<Object|null>} The individual user as stored afterwards
|
|
433
|
+
*/
|
|
434
|
+
async linkIndividualToOrganizationIfUnset(individualUserId, organizationUserId) {
|
|
435
|
+
await updateOne(
|
|
436
|
+
this.prisma,
|
|
437
|
+
'User',
|
|
438
|
+
{
|
|
439
|
+
_id: toObjectId(individualUserId),
|
|
440
|
+
type: 'INDIVIDUAL',
|
|
441
|
+
// Raw MongoDB query (not Prisma): `{ field: null }` matches both a
|
|
442
|
+
// null value and a missing field, so no `$exists` branch is needed.
|
|
443
|
+
organizationId: null,
|
|
444
|
+
},
|
|
445
|
+
{ $set: { organizationId: toObjectId(organizationUserId) } }
|
|
446
|
+
);
|
|
447
|
+
return this.findIndividualUserById(individualUserId);
|
|
448
|
+
}
|
|
424
449
|
}
|
|
425
450
|
|
|
426
451
|
module.exports = { UserRepositoryDocumentDB };
|
|
@@ -209,6 +209,24 @@ class UserRepositoryInterface {
|
|
|
209
209
|
'Method linkIndividualToOrganization must be implemented by subclass'
|
|
210
210
|
);
|
|
211
211
|
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Set an individual user's legacy `organizationId` pointer only if it is
|
|
215
|
+
* not set yet (their first link), decided by the database in the same
|
|
216
|
+
* statement so two concurrent first logins cannot overwrite each other.
|
|
217
|
+
* Never changes an existing pointer (ADR-056 §3.6).
|
|
218
|
+
*
|
|
219
|
+
* @param {string|number} individualUserId - Individual user ID
|
|
220
|
+
* @param {string|number} organizationUserId - Organization user ID
|
|
221
|
+
* @returns {Promise<Object|null>} The individual user as stored afterwards
|
|
222
|
+
* (null if there is no such individual)
|
|
223
|
+
* @abstract
|
|
224
|
+
*/
|
|
225
|
+
async linkIndividualToOrganizationIfUnset(individualUserId, organizationUserId) {
|
|
226
|
+
throw new Error(
|
|
227
|
+
'Method linkIndividualToOrganizationIfUnset must be implemented by subclass'
|
|
228
|
+
);
|
|
229
|
+
}
|
|
212
230
|
}
|
|
213
231
|
|
|
214
232
|
module.exports = { UserRepositoryInterface };
|
|
@@ -318,6 +318,30 @@ class UserRepositoryMongo extends UserRepositoryInterface {
|
|
|
318
318
|
},
|
|
319
319
|
});
|
|
320
320
|
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Set the legacy organizationId only if it is still null (see the interface).
|
|
324
|
+
* @param {string} individualUserId
|
|
325
|
+
* @param {string} organizationUserId
|
|
326
|
+
* @returns {Promise<Object|null>} The individual user as stored afterwards
|
|
327
|
+
*/
|
|
328
|
+
async linkIndividualToOrganizationIfUnset(individualUserId, organizationUserId) {
|
|
329
|
+
await this.prisma.user.updateMany({
|
|
330
|
+
where: {
|
|
331
|
+
id: individualUserId,
|
|
332
|
+
type: 'INDIVIDUAL',
|
|
333
|
+
// Prisma on MongoDB: `null` matches only an explicit null, and
|
|
334
|
+
// `isSet: false` only a missing field. An individual created
|
|
335
|
+
// without the field is the common case, so match both.
|
|
336
|
+
OR: [
|
|
337
|
+
{ organizationId: null },
|
|
338
|
+
{ organizationId: { isSet: false } },
|
|
339
|
+
],
|
|
340
|
+
},
|
|
341
|
+
data: { organizationId: organizationUserId },
|
|
342
|
+
});
|
|
343
|
+
return this.findIndividualUserById(individualUserId);
|
|
344
|
+
}
|
|
321
345
|
}
|
|
322
346
|
|
|
323
347
|
module.exports = { UserRepositoryMongo };
|
|
@@ -372,6 +372,24 @@ class UserRepositoryPostgres extends UserRepositoryInterface {
|
|
|
372
372
|
});
|
|
373
373
|
return this._convertUserIds(user);
|
|
374
374
|
}
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* Set the legacy organizationId only if it is still null (see the interface).
|
|
378
|
+
* @param {string} individualUserId - Individual user ID (string from application layer)
|
|
379
|
+
* @param {string} organizationUserId - Organization user ID (string from application layer)
|
|
380
|
+
* @returns {Promise<Object|null>} The individual user as stored afterwards, with string IDs
|
|
381
|
+
*/
|
|
382
|
+
async linkIndividualToOrganizationIfUnset(individualUserId, organizationUserId) {
|
|
383
|
+
await this.prisma.user.updateMany({
|
|
384
|
+
where: {
|
|
385
|
+
id: this._convertId(individualUserId),
|
|
386
|
+
type: 'INDIVIDUAL',
|
|
387
|
+
organizationId: null,
|
|
388
|
+
},
|
|
389
|
+
data: { organizationId: this._convertId(organizationUserId) },
|
|
390
|
+
});
|
|
391
|
+
return this.findIndividualUserById(individualUserId);
|
|
392
|
+
}
|
|
375
393
|
}
|
|
376
394
|
|
|
377
395
|
module.exports = { UserRepositoryPostgres };
|
|
@@ -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
|
+
};
|
|
@@ -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 };
|