@friggframework/core 2.0.0--canary.680.daae24e.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/CHANGELOG.md +0 -11
- package/CLAUDE.md +28 -0
- package/README.md +105 -0
- package/application/commands/integration-commands.js +2 -2
- package/application/commands/scheduler-commands.js +11 -7
- package/application/commands/user-commands.js +17 -5
- package/core/Worker.js +31 -7
- package/core/create-handler.js +9 -0
- package/credential/use-cases/credential-operations-for-user.js +110 -25
- package/credential/use-cases/reauthorize-credential-for-user.js +15 -8
- package/database/config.js +48 -24
- package/database/documentdb-utils.js +6 -1
- package/database/encryption/README.md +0 -2
- package/database/encryption/encryption-config.js +10 -31
- package/database/encryption/encryption-schema-registry.js +99 -47
- package/database/encryption/field-encryption-service.js +5 -69
- 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 +27 -4
- package/generated/prisma-mongodb/index-browser.js +24 -1
- package/generated/prisma-mongodb/index.d.ts +3227 -47
- package/generated/prisma-mongodb/index.js +27 -4
- package/generated/prisma-mongodb/package.json +1 -1
- package/generated/prisma-mongodb/schema.prisma +65 -0
- package/generated/prisma-mongodb/wasm.js +27 -4
- package/generated/prisma-postgresql/edge.js +27 -4
- package/generated/prisma-postgresql/index-browser.js +24 -1
- package/generated/prisma-postgresql/index.d.ts +3519 -67
- package/generated/prisma-postgresql/index.js +27 -4
- package/generated/prisma-postgresql/package.json +1 -1
- package/generated/prisma-postgresql/schema.prisma +61 -0
- package/generated/prisma-postgresql/wasm.js +27 -4
- package/handlers/app-definition-loader.js +103 -12
- package/handlers/routers/auth.js +40 -12
- package/handlers/routers/health.js +4 -2
- package/handlers/routers/integration-defined-routers.js +144 -92
- package/handlers/routers/integration-webhook-routers.js +102 -64
- package/index.js +63 -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 +5 -0
- package/integrations/integration-router.js +115 -73
- 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 +55 -24
- package/integrations/use-cases/resolve-integration-ownership.js +177 -0
- package/integrations/utils/map-integration-dto.js +44 -1
- package/management-api/management-api-config.js +71 -2
- package/management-api/meta-router.js +21 -2
- package/management-api/openapi/components.js +40 -0
- package/management-api/openapi/v2-operations.js +16 -4
- package/management-api/route-registry.js +123 -6
- package/management-api/v2/dependencies.js +40 -15
- package/management-api/v2/dto.js +20 -0
- package/management-api/v2/handlers/authorization.js +1 -0
- package/management-api/v2/handlers/credentials.js +6 -2
- package/management-api/v2/handlers/entities.js +10 -7
- package/management-api/v2/handlers/integrations.js +6 -3
- package/management-api/v2/request.js +32 -1
- package/modules/entity-scope.js +15 -0
- package/modules/index.js +8 -0
- package/modules/module-factory.js +12 -0
- package/modules/module.js +53 -2
- 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/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/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 +50 -13
- package/modules/use-cases/entity-types.js +31 -7
- package/modules/use-cases/execute-entity-proxy-request.js +50 -3
- package/modules/use-cases/get-authorization-requirements.js +2 -2
- package/modules/use-cases/get-entities-for-user.js +26 -13
- package/modules/use-cases/get-entity-module-for-user.js +34 -7
- 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 +40 -13
- 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 +65 -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 +61 -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 +1 -0
- package/types/modules/index.d.ts +139 -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/database/encryption/test-support/fake-ciphertext.js +0 -15
|
@@ -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
|
-
|
|
@@ -1,10 +1,38 @@
|
|
|
1
1
|
const Boom = require('@hapi/boom');
|
|
2
|
-
const {
|
|
2
|
+
const {
|
|
3
|
+
findAppUsers,
|
|
4
|
+
createMissingAppUsers,
|
|
5
|
+
buildUser,
|
|
6
|
+
wantsIndividual,
|
|
7
|
+
} = require('../app-user-helpers');
|
|
8
|
+
const { getLogger } = require('../../logs');
|
|
9
|
+
|
|
10
|
+
const log = getLogger('frigg.user.x_frigg_headers');
|
|
11
|
+
|
|
12
|
+
const NOT_A_MEMBER_MESSAGE =
|
|
13
|
+
'Not a member: the user identified by x-frigg-appUserId is not a member of the ' +
|
|
14
|
+
'organization identified by x-frigg-appOrgId, and strict membership does not ' +
|
|
15
|
+
'allow these headers to add them.';
|
|
3
16
|
|
|
4
17
|
/**
|
|
5
18
|
* Use case for retrieving or creating a user from x-frigg header identifiers.
|
|
6
19
|
* Supports backend-to-backend API communication using application user IDs.
|
|
7
20
|
*
|
|
21
|
+
* `x-frigg-appOrgId` names the request's active organization (ADR-056 §3.6).
|
|
22
|
+
* A person the organization does not know yet is added to it as a member; the
|
|
23
|
+
* person is never moved out of another organization, and
|
|
24
|
+
* `IndividualUser.organizationId` is set only on a first link.
|
|
25
|
+
*
|
|
26
|
+
* With `user.strictMembership: true` the headers cannot make anyone a member of
|
|
27
|
+
* an organization that already existed: a person who is not already a member
|
|
28
|
+
* (a brand-new `appUserId` included) is refused with 400. The one thing strict
|
|
29
|
+
* mode still allows is naming an organization this request creates, so a first
|
|
30
|
+
* login can bootstrap its own organization. Apps that run strict add people to
|
|
31
|
+
* existing organizations themselves, through the membership repository.
|
|
32
|
+
*
|
|
33
|
+
* `strictUserValidation` is a deprecated alias for `strictMembership`; its
|
|
34
|
+
* meaning changed (it used to reject a mismatched individual/organization pair).
|
|
35
|
+
*
|
|
8
36
|
* @class GetUserFromXFriggHeaders
|
|
9
37
|
*/
|
|
10
38
|
class GetUserFromXFriggHeaders {
|
|
@@ -12,11 +40,22 @@ class GetUserFromXFriggHeaders {
|
|
|
12
40
|
* Creates a new GetUserFromXFriggHeaders instance.
|
|
13
41
|
* @param {Object} params - Configuration parameters.
|
|
14
42
|
* @param {import('../repositories/user-repository-interface').UserRepositoryInterface} params.userRepository - Repository for user data operations.
|
|
43
|
+
* @param {import('./ensure-organization-membership').EnsureOrganizationMembership} params.ensureOrganizationMembership
|
|
15
44
|
* @param {Object} params.userConfig - The user config in the app definition.
|
|
16
45
|
*/
|
|
17
|
-
constructor({ userRepository, userConfig }) {
|
|
46
|
+
constructor({ userRepository, ensureOrganizationMembership, userConfig }) {
|
|
18
47
|
this.userRepository = userRepository;
|
|
48
|
+
this.ensureOrganizationMembership = ensureOrganizationMembership;
|
|
19
49
|
this.userConfig = userConfig;
|
|
50
|
+
|
|
51
|
+
const { strictMembership, strictUserValidation } = userConfig ?? {};
|
|
52
|
+
if (strictUserValidation !== undefined && strictMembership === undefined) {
|
|
53
|
+
log.warn(
|
|
54
|
+
'user.strictUserValidation is deprecated and now means strictMembership; rename it',
|
|
55
|
+
{ eventName: `${log.name}.strict_user_validation_deprecated` }
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
this.strict = Boolean(strictMembership ?? strictUserValidation);
|
|
20
59
|
}
|
|
21
60
|
|
|
22
61
|
/**
|
|
@@ -25,7 +64,7 @@ class GetUserFromXFriggHeaders {
|
|
|
25
64
|
* @param {string} [appUserId] - The app user ID from x-frigg-appUserId header.
|
|
26
65
|
* @param {string} [appOrgId] - The app organization ID from x-frigg-appOrgId header.
|
|
27
66
|
* @returns {Promise<import('../user').User>} The authenticated user object.
|
|
28
|
-
* @throws {Boom} 400 Bad Request if neither ID is provided or if
|
|
67
|
+
* @throws {Boom} 400 Bad Request if neither ID is provided or, in strict mode, if the person is not already a member of the existing organization named.
|
|
29
68
|
*/
|
|
30
69
|
async execute(appUserId, appOrgId) {
|
|
31
70
|
// At least one header must be provided
|
|
@@ -36,96 +75,60 @@ class GetUserFromXFriggHeaders {
|
|
|
36
75
|
}
|
|
37
76
|
|
|
38
77
|
// Find users by both IDs if both are provided
|
|
39
|
-
let individualUserData =
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
await this.userRepository.findIndividualUserByAppUserId(
|
|
45
|
-
appUserId
|
|
46
|
-
);
|
|
47
|
-
}
|
|
78
|
+
let { individual: individualUserData, organization: organizationUserData } =
|
|
79
|
+
await findAppUsers(this.userRepository, this.userConfig, {
|
|
80
|
+
appUserId,
|
|
81
|
+
appOrgId,
|
|
82
|
+
});
|
|
48
83
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
);
|
|
54
|
-
}
|
|
84
|
+
// Strict mode refuses to make anyone a member of an organization that
|
|
85
|
+
// existed before this request. Only an organization created below is
|
|
86
|
+
// exempt, since it has no members to disagree with.
|
|
87
|
+
const refuseNewMembers = this.strict && Boolean(organizationUserData);
|
|
55
88
|
|
|
56
|
-
//
|
|
89
|
+
// A person who does not exist yet cannot already be a member, so refuse
|
|
90
|
+
// now, before anything is persisted: refusing after creating them would
|
|
91
|
+
// leave an orphan individual behind on every refused request.
|
|
57
92
|
if (
|
|
93
|
+
refuseNewMembers &&
|
|
58
94
|
appUserId &&
|
|
59
|
-
|
|
60
|
-
individualUserData
|
|
61
|
-
organizationUserData
|
|
95
|
+
wantsIndividual(this.userConfig) &&
|
|
96
|
+
!individualUserData
|
|
62
97
|
) {
|
|
63
|
-
|
|
64
|
-
const individualOrgId =
|
|
65
|
-
individualUserData.organizationUser?.toString();
|
|
66
|
-
const expectedOrgId = organizationUserData.id?.toString();
|
|
67
|
-
|
|
68
|
-
if (individualOrgId !== expectedOrgId) {
|
|
69
|
-
// Default behavior: Auto-link disconnected users
|
|
70
|
-
// Opt-in strict mode: Throw error on mismatch
|
|
71
|
-
if (this.userConfig.strictUserValidation) {
|
|
72
|
-
throw Boom.badRequest(
|
|
73
|
-
'User ID mismatch: x-frigg-appUserId and x-frigg-appOrgId refer to different users. ' +
|
|
74
|
-
'Provide only one identifier or ensure they belong to the same user.'
|
|
75
|
-
);
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
// Auto-link the users
|
|
79
|
-
individualUserData = await this.userRepository.linkIndividualToOrganization(
|
|
80
|
-
individualUserData.id,
|
|
81
|
-
organizationUserData.id
|
|
82
|
-
);
|
|
83
|
-
}
|
|
98
|
+
throw Boom.badRequest(NOT_A_MEMBER_MESSAGE);
|
|
84
99
|
}
|
|
85
100
|
|
|
86
101
|
// Auto-create users independently if they don't exist and are required
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
username: `app-user-${appUserId}`,
|
|
96
|
-
email: `${appUserId}@app.local`,
|
|
97
|
-
});
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
if (
|
|
101
|
-
!organizationUserData &&
|
|
102
|
-
appOrgId &&
|
|
103
|
-
this.userConfig.organizationUserRequired
|
|
104
|
-
) {
|
|
105
|
-
organizationUserData =
|
|
106
|
-
await this.userRepository.createOrganizationUser({
|
|
107
|
-
appOrgId,
|
|
108
|
-
});
|
|
109
|
-
|
|
110
|
-
// Link individual user to newly created org user if individual exists
|
|
111
|
-
if (individualUserData && organizationUserData) {
|
|
112
|
-
individualUserData = await this.userRepository.linkIndividualToOrganization(
|
|
113
|
-
individualUserData.id,
|
|
114
|
-
organizationUserData.id
|
|
115
|
-
);
|
|
102
|
+
const created = await createMissingAppUsers(
|
|
103
|
+
this.userRepository,
|
|
104
|
+
this.userConfig,
|
|
105
|
+
{
|
|
106
|
+
appUserId,
|
|
107
|
+
appOrgId,
|
|
108
|
+
individual: individualUserData,
|
|
109
|
+
organization: organizationUserData,
|
|
116
110
|
}
|
|
111
|
+
);
|
|
112
|
+
individualUserData = created.individual;
|
|
113
|
+
organizationUserData = created.organization;
|
|
114
|
+
|
|
115
|
+
// The organization named by the header is the active one: join it
|
|
116
|
+
// rather than re-linking the person's single organizationId.
|
|
117
|
+
const ensured = await this.ensureOrganizationMembership.execute({
|
|
118
|
+
individual: individualUserData,
|
|
119
|
+
organization: organizationUserData,
|
|
120
|
+
requireExisting: refuseNewMembers,
|
|
121
|
+
});
|
|
122
|
+
if (refuseNewMembers && individualUserData && !ensured.membership) {
|
|
123
|
+
throw Boom.badRequest(NOT_A_MEMBER_MESSAGE);
|
|
117
124
|
}
|
|
125
|
+
individualUserData = ensured.individual;
|
|
118
126
|
|
|
119
|
-
|
|
127
|
+
return buildUser(
|
|
128
|
+
this.userConfig,
|
|
120
129
|
individualUserData,
|
|
121
|
-
organizationUserData
|
|
122
|
-
this.userConfig.usePassword,
|
|
123
|
-
this.userConfig.primary,
|
|
124
|
-
this.userConfig.individualUserRequired,
|
|
125
|
-
this.userConfig.organizationUserRequired
|
|
130
|
+
organizationUserData
|
|
126
131
|
);
|
|
127
|
-
|
|
128
|
-
return user;
|
|
129
132
|
}
|
|
130
133
|
}
|
|
131
134
|
|