@friggframework/core 2.0.0--canary.670.2873d95.0 → 2.0.0--canary.678.58db4b2.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.
Files changed (83) hide show
  1. package/CLAUDE.md +2 -0
  2. package/README.md +57 -0
  3. package/credential/repositories/credential-repository-documentdb.js +34 -0
  4. package/credential/repositories/credential-repository-interface.js +15 -0
  5. package/credential/repositories/credential-repository-mongo.js +23 -0
  6. package/credential/repositories/credential-repository-postgres.js +28 -0
  7. package/credential/use-cases/credential-operations-for-user.js +117 -0
  8. package/credential/use-cases/reauthorize-credential-for-user.js +66 -0
  9. package/database/encryption/encryption-schema-registry.js +6 -0
  10. package/generated/prisma-mongodb/edge.js +20 -4
  11. package/generated/prisma-mongodb/index-browser.js +17 -1
  12. package/generated/prisma-mongodb/index.d.ts +1543 -95
  13. package/generated/prisma-mongodb/index.js +20 -4
  14. package/generated/prisma-mongodb/package.json +1 -1
  15. package/generated/prisma-mongodb/schema.prisma +27 -0
  16. package/generated/prisma-mongodb/wasm.js +20 -4
  17. package/generated/prisma-postgresql/edge.js +20 -4
  18. package/generated/prisma-postgresql/index-browser.js +17 -1
  19. package/generated/prisma-postgresql/index.d.ts +1570 -89
  20. package/generated/prisma-postgresql/index.js +20 -4
  21. package/generated/prisma-postgresql/package.json +1 -1
  22. package/generated/prisma-postgresql/schema.prisma +26 -0
  23. package/generated/prisma-postgresql/wasm.js +20 -4
  24. package/handlers/app-definition-loader.js +9 -1
  25. package/handlers/app-handler-helpers.js +25 -3
  26. package/handlers/middleware/admin-auth.js +14 -1
  27. package/handlers/routers/auth.js +11 -3
  28. package/handlers/routers/health.js +10 -0
  29. package/integrations/integration-router.js +6 -0
  30. package/integrations/use-cases/integration-operations-for-user.js +225 -0
  31. package/management-api/create-management-api-router.js +49 -0
  32. package/management-api/error-response.js +116 -0
  33. package/management-api/management-api-config.js +82 -0
  34. package/management-api/meta-router.js +57 -0
  35. package/management-api/openapi/build-openapi.js +144 -0
  36. package/management-api/openapi/components.js +362 -0
  37. package/management-api/openapi/v1-operations.js +83 -0
  38. package/management-api/openapi/v2-operations.js +248 -0
  39. package/management-api/route-registry.js +294 -0
  40. package/management-api/test-support/http-client.js +39 -0
  41. package/management-api/use-cases/get-management-api-meta.js +57 -0
  42. package/management-api/v1-deprecation.js +120 -0
  43. package/management-api/v2/create-v2-router.js +85 -0
  44. package/management-api/v2/dependencies.js +246 -0
  45. package/management-api/v2/dto.js +123 -0
  46. package/management-api/v2/handlers/authorization.js +93 -0
  47. package/management-api/v2/handlers/credentials.js +29 -0
  48. package/management-api/v2/handlers/entities.js +74 -0
  49. package/management-api/v2/handlers/integrations.js +125 -0
  50. package/management-api/v2/handlers/proxy.js +34 -0
  51. package/management-api/v2/request.js +54 -0
  52. package/management-api/v2/test-support/fake-dependencies.js +103 -0
  53. package/modules/domain/authorization-session.js +144 -0
  54. package/modules/proxy/proxy-errors.js +20 -0
  55. package/modules/proxy/proxy-path.js +179 -0
  56. package/modules/proxy/proxy-policy.js +248 -0
  57. package/modules/repositories/authorization-session-repository-documentdb.js +112 -0
  58. package/modules/repositories/authorization-session-repository-factory.js +31 -0
  59. package/modules/repositories/authorization-session-repository-interface.js +47 -0
  60. package/modules/repositories/authorization-session-repository-prisma.js +87 -0
  61. package/modules/requester/proxy-request.js +244 -0
  62. package/modules/requester/requester.js +27 -2
  63. package/modules/tests/doubles/in-memory-authorization-session-repository.js +45 -0
  64. package/modules/use-cases/entity-operations-for-user.js +125 -0
  65. package/modules/use-cases/entity-types.js +91 -0
  66. package/modules/use-cases/execute-entity-proxy-request.js +239 -0
  67. package/modules/use-cases/get-authorization-requirements.js +100 -0
  68. package/modules/use-cases/get-entity-module-for-user.js +86 -0
  69. package/modules/use-cases/multi-step-authorization.js +302 -0
  70. package/package.json +6 -5
  71. package/prisma-mongodb/schema.prisma +27 -0
  72. package/prisma-postgresql/migrations/20261003000000_add_authorization_session/migration.sql +28 -0
  73. package/prisma-postgresql/schema.prisma +26 -0
  74. package/types/index.d.ts +1 -0
  75. package/types/user/index.d.ts +67 -0
  76. package/user/adopter-jwt-config.js +177 -0
  77. package/user/adopter-jwt-errors.js +65 -0
  78. package/user/adopter-token-verifier.js +122 -0
  79. package/user/app-user-helpers.js +73 -0
  80. package/user/tests/doubles/adopter-jwt-fixtures.js +130 -0
  81. package/user/use-cases/get-user-from-adopter-jwt.js +109 -122
  82. package/user/use-cases/get-user-from-x-frigg-headers.js +29 -51
  83. package/user/user.js +11 -0
package/CLAUDE.md CHANGED
@@ -332,12 +332,14 @@ class MyIntegration extends IntegrationBase {
332
332
  - Password-based (bcrypt hashed)
333
333
  - Token-based (Bearer tokens)
334
334
  - App-based (external app user IDs)
335
+ - Adopter JWT (`authModes.adopterJwt`, `jwtConfig`; `jose`, JWKS or HMAC; see `README.md`)
335
336
 
336
337
  **Use Cases**:
337
338
  - `login-user.js` - User authentication
338
339
  - `create-individual-user.js` - Create personal account
339
340
  - `create-organization-user.js` - Create business account
340
341
  - `get-user-from-bearer-token.js` - Token authentication
342
+ - `get-user-from-adopter-jwt.js` - Adopter JWT verification, find-or-create (ADR-056 §2); `adopter-jwt-config.js` validates `jwtConfig` at load
341
343
 
342
344
  **Repositories**:
343
345
  - `user-repository-factory.js` - Creates database-specific repositories
package/README.md CHANGED
@@ -305,6 +305,7 @@ Comprehensive user authentication and authorization system supporting both indiv
305
305
  - **Password-based**: Traditional username/password authentication
306
306
  - **Token-based**: Bearer token authentication with session management
307
307
  - **App-based**: External app user ID authentication (passwordless)
308
+ - **Adopter token (JWT)**: A token issued by your own identity system, verified by Frigg and safe to send from a browser (see below)
308
309
 
309
310
  **Usage:**
310
311
  ```javascript
@@ -352,6 +353,62 @@ console.log('Individual user:', user.getIndividualUser());
352
353
  console.log('Organization user:', user.getOrganizationUser());
353
354
  ```
354
355
 
356
+ #### Adopter token (JWT) authentication
357
+
358
+ For a multi-tenant product (ADR-056 §2), let the browser send the token your identity system
359
+ already issues. Frigg verifies the signature and claims, then finds or creates the individual
360
+ user and the organization user the token names. Unlike `sharedSecret` (`x-frigg-*` headers), a
361
+ token cannot name a user other than the one it was issued for, so it is safe in a browser.
362
+
363
+ ```javascript
364
+ // backend/index.js
365
+ const appDefinition = {
366
+ user: {
367
+ primary: 'organization',
368
+ individualUserRequired: true,
369
+ organizationUserRequired: true,
370
+ authModes: { adopterJwt: true, friggToken: false, sharedSecret: false },
371
+ jwtConfig: {
372
+ jwksUri: 'https://login.example.com/.well-known/jwks.json',
373
+ issuer: 'https://login.example.com/',
374
+ audience: 'my-frigg-api', // required with jwksUri
375
+ },
376
+ },
377
+ };
378
+ ```
379
+
380
+ The client sends `Authorization: Bearer <token>`. `x-frigg-appuserid` / `x-frigg-apporgid`, if
381
+ also sent, must match the token or the request is refused with 403. That match rule lives in
382
+ `user/use-cases/authenticate-user.js` (`validateUserMatch`), not in the token verifier. A bearer
383
+ value that is not a three-part JWT is not offered to the verifier at all; it falls through to
384
+ `friggToken` (or is a 401 when that mode is off).
385
+
386
+ | `jwtConfig` field | Default | Meaning |
387
+ |---|---|---|
388
+ | `jwksUri` | | Remote JWKS (rotating keys, one per verifier, cached by jose). Must be `https`; `http` only for `localhost`, `127.0.0.0/8` or `::1`. Set exactly one of this and `secret`. |
389
+ | `secret` | | Shared HMAC secret. Read it from an environment variable. |
390
+ | `issuer` | not checked | Required `iss`. With `jwksUri`, a startup warning is logged when it is unset. |
391
+ | `audience` | not checked with `secret`; **required with `jwksUri`** | Accepted `aud` (a string or a list). |
392
+ | `algorithms` | `['ES256','RS256']` with `jwksUri`, `['HS256']` with `secret` | Allow-list. HS* is only accepted with `secret`, never with `jwksUri`. The older single `algorithm` is a deprecated alias; setting both is an error. |
393
+ | `clockToleranceSec` | `30` | Skew allowed on `exp` and `nbf`. |
394
+ | `userIdClaim` | `sub` | App user id (required in the token). |
395
+ | `orgIdClaim` | `org_id` | App organization id (optional). |
396
+ | `roleClaim` | `org_role` | Read and exposed as `user.getOrgRole()`; not stored yet. |
397
+
398
+ Rules worth knowing:
399
+
400
+ - Tokens must carry `exp`. `alg: none` and any algorithm outside the allow-list are refused.
401
+ - Startup fails (`loadAppDefinition` throws) when `adopterJwt` is on and the config is unusable:
402
+ neither or both of `jwksUri` and `secret`, a `jwksUri` that is not https (or loopback http),
403
+ no `audience` with `jwksUri`, or an algorithm list that does not fit the key type.
404
+ - Failures are `401` with a stable `data.reason`: `token_expired`, `token_not_yet_valid`,
405
+ `token_invalid_signature`, `token_wrong_issuer`, `token_wrong_audience`,
406
+ `token_missing_user_claim`, `token_malformed`. The message never contains the token or its claims.
407
+ Any other verification failure, such as an unreachable or unresolvable JWKS, is `503`
408
+ `jwks_unavailable`, not a 401, so clients do not drop good sessions.
409
+ - A person belongs to one organization for now: a token naming a second one gets `403`
410
+ `multi_org_unsupported` and nothing is moved (ADR-056 §3.6 replaces this with memberships).
411
+
355
412
  ### 8. Lambda Utilities (`/lambda`)
356
413
 
357
414
  AWS Lambda-specific utilities and helpers.
@@ -186,6 +186,40 @@ class CredentialRepositoryDocumentDB extends CredentialRepositoryInterface {
186
186
  return this._mapCredential(decryptedCredential);
187
187
  }
188
188
 
189
+ /**
190
+ * All credentials owned by a user, newest first.
191
+ *
192
+ * @param {string} userId - User ID
193
+ * @returns {Promise<Array<Object>>} Credentials with string IDs
194
+ */
195
+ async findCredentialsByUserId(userId) {
196
+ const userObjectId = toObjectId(userId);
197
+ if (!userObjectId) return [];
198
+ const docs = await findManyDrained(
199
+ this.prisma,
200
+ 'Credential',
201
+ { userId: userObjectId },
202
+ { sort: { createdAt: -1 } }
203
+ );
204
+ const credentials = [];
205
+ for (const doc of docs) {
206
+ const decrypted = await this.encryptionService.decryptFields(
207
+ 'Credential',
208
+ doc
209
+ );
210
+ credentials.push({
211
+ ...this._mapCredential(decrypted),
212
+ id: fromObjectId(doc._id),
213
+ userId: fromObjectId(doc.userId) ?? doc.userId,
214
+ externalId: doc.externalId ?? null,
215
+ authIsValid: doc.authIsValid ?? null,
216
+ createdAt: doc.createdAt ?? null,
217
+ updatedAt: doc.updatedAt ?? null,
218
+ });
219
+ }
220
+ return credentials;
221
+ }
222
+
189
223
  async updateCredential(credentialId, updates) {
190
224
  const objectId = toObjectId(credentialId);
191
225
  if (!objectId) return null;
@@ -80,6 +80,21 @@ class CredentialRepositoryInterface {
80
80
  );
81
81
  }
82
82
 
83
+ /**
84
+ * All credentials owned by a user, newest first.
85
+ *
86
+ * @param {string|number} userId - User ID (string from application layer)
87
+ * @returns {Promise<Array<Object>>} Credentials with string IDs, `createdAt`
88
+ * and `updatedAt`, and the (decrypted) data fields spread in, as
89
+ * findCredentialById returns them. Empty when the user has none.
90
+ * @abstract
91
+ */
92
+ async findCredentialsByUserId(userId) {
93
+ throw new Error(
94
+ 'Method findCredentialsByUserId must be implemented by subclass'
95
+ );
96
+ }
97
+
83
98
  /**
84
99
  * Update a credential by ID
85
100
  *
@@ -188,6 +188,29 @@ class CredentialRepositoryMongo extends CredentialRepositoryInterface {
188
188
  };
189
189
  }
190
190
 
191
+ /**
192
+ * All credentials owned by a user, newest first.
193
+ *
194
+ * @param {string} userId - User ID
195
+ * @returns {Promise<Array<Object>>} Credentials with string IDs
196
+ */
197
+ async findCredentialsByUserId(userId) {
198
+ if (!userId) return [];
199
+ const credentials = await this.prisma.credential.findMany({
200
+ where: { userId: String(userId) },
201
+ orderBy: { createdAt: 'desc' },
202
+ });
203
+ return credentials.map((credential) => ({
204
+ ...(credential.data || {}),
205
+ id: credential.id,
206
+ userId: credential.userId,
207
+ externalId: credential.externalId,
208
+ authIsValid: credential.authIsValid,
209
+ createdAt: credential.createdAt,
210
+ updatedAt: credential.updatedAt,
211
+ }));
212
+ }
213
+
191
214
  /**
192
215
  * Update a credential by ID
193
216
  * Replaces: Credential.findByIdAndUpdate(credentialId, { $set: updates })
@@ -205,6 +205,34 @@ class CredentialRepositoryPostgres extends CredentialRepositoryInterface {
205
205
  };
206
206
  }
207
207
 
208
+ /**
209
+ * All credentials owned by a user, newest first.
210
+ *
211
+ * @param {string} userId - User ID (string from application layer)
212
+ * @returns {Promise<Array<Object>>} Credentials with string IDs
213
+ */
214
+ async findCredentialsByUserId(userId) {
215
+ let intUserId;
216
+ try {
217
+ intUserId = this._convertId(userId);
218
+ } catch {
219
+ return [];
220
+ }
221
+ const credentials = await this.prisma.credential.findMany({
222
+ where: { userId: intUserId },
223
+ orderBy: { createdAt: 'desc' },
224
+ });
225
+ return credentials.map((credential) => ({
226
+ ...(credential.data || {}),
227
+ id: credential.id.toString(),
228
+ userId: credential.userId?.toString(),
229
+ externalId: credential.externalId,
230
+ authIsValid: credential.authIsValid,
231
+ createdAt: credential.createdAt,
232
+ updatedAt: credential.updatedAt,
233
+ }));
234
+ }
235
+
208
236
  /**
209
237
  * Update a credential by ID
210
238
  *
@@ -0,0 +1,117 @@
1
+ const Boom = require('@hapi/boom');
2
+ const { userOwns } = require('../../modules/use-cases/get-entity-module-for-user');
3
+
4
+ /**
5
+ * Management API v2 credential operations. A credential has no module name
6
+ * of its own; its `type` and the entities that use it come from the
7
+ * caller's entities. A missing or foreign credential is a 404.
8
+ */
9
+
10
+ const credentialIdOf = (entity) => {
11
+ const ref = entity.credential ?? entity.credentialId;
12
+ if (ref === undefined || ref === null) return null;
13
+ if (typeof ref === 'object') {
14
+ const id = ref.id ?? ref._id;
15
+ return id === undefined || id === null ? null : String(id);
16
+ }
17
+ return String(ref);
18
+ };
19
+
20
+ /** Adds `type` and `entityIds` from the user's entities to each credential. */
21
+ function withEntityUsage(credentials, entities) {
22
+ const usage = new Map();
23
+ for (const entity of entities || []) {
24
+ const credentialId = credentialIdOf(entity);
25
+ if (!credentialId) continue;
26
+ const entry = usage.get(credentialId) || { type: null, entityIds: [] };
27
+ entry.type = entry.type || entity.moduleName || null;
28
+ entry.entityIds.push(String(entity.id));
29
+ usage.set(credentialId, entry);
30
+ }
31
+ return credentials.map((credential) => {
32
+ const entry = usage.get(String(credential.id)) || {
33
+ type: null,
34
+ entityIds: [],
35
+ };
36
+ return { ...credential, type: entry.type, entityIds: entry.entityIds };
37
+ });
38
+ }
39
+
40
+ /** The caller's credentials with their type and entity usage. */
41
+ class ListCredentialsForUser {
42
+ constructor({ credentialRepository, moduleRepository }) {
43
+ this.credentialRepository = credentialRepository;
44
+ this.moduleRepository = moduleRepository;
45
+ }
46
+
47
+ async execute(user) {
48
+ const userId = user.getId();
49
+ const [credentials, entities] = await Promise.all([
50
+ this.credentialRepository.findCredentialsByUserId(userId),
51
+ this.moduleRepository.findEntitiesByUserId(userId),
52
+ ]);
53
+ return withEntityUsage(credentials || [], entities);
54
+ }
55
+ }
56
+
57
+ /** One credential the caller owns, with its type and entity usage. */
58
+ class GetCredentialForUserV2 {
59
+ constructor({ credentialRepository, moduleRepository }) {
60
+ this.credentialRepository = credentialRepository;
61
+ this.moduleRepository = moduleRepository;
62
+ }
63
+
64
+ async execute(credentialId, user) {
65
+ let credential = null;
66
+ try {
67
+ credential = await this.credentialRepository.findCredentialById(
68
+ credentialId
69
+ );
70
+ } catch (error) {
71
+ if (!/Invalid ID|ObjectId|Malformed/i.test(error?.message || '')) {
72
+ throw error;
73
+ }
74
+ }
75
+ if (!credential || !userOwns(user, credential.userId)) {
76
+ throw Boom.notFound(`Credential ${credentialId} not found`, {
77
+ code: 'CREDENTIAL_NOT_FOUND',
78
+ });
79
+ }
80
+ const entities = await this.moduleRepository.findEntitiesByUserId(
81
+ credential.userId
82
+ );
83
+ return withEntityUsage([credential], entities)[0];
84
+ }
85
+ }
86
+
87
+ /**
88
+ * Deletes a credential the caller owns. The entities that used it stay, with
89
+ * their credential unset, so they show as needing re-authorization rather
90
+ * than disappearing from integrations.
91
+ */
92
+ class DeleteCredentialForUser {
93
+ constructor({ credentialRepository, moduleRepository, getCredentialForUser }) {
94
+ this.credentialRepository = credentialRepository;
95
+ this.moduleRepository = moduleRepository;
96
+ this.getCredentialForUser = getCredentialForUser;
97
+ }
98
+
99
+ async execute(credentialId, user) {
100
+ const credential = await this.getCredentialForUser.execute(
101
+ credentialId,
102
+ user
103
+ );
104
+ for (const entityId of credential.entityIds) {
105
+ await this.moduleRepository.unsetCredential(entityId);
106
+ }
107
+ await this.credentialRepository.deleteCredentialById(credential.id);
108
+ return { id: String(credential.id), entityIds: credential.entityIds };
109
+ }
110
+ }
111
+
112
+ module.exports = {
113
+ ListCredentialsForUser,
114
+ GetCredentialForUserV2,
115
+ DeleteCredentialForUser,
116
+ withEntityUsage,
117
+ };
@@ -0,0 +1,66 @@
1
+ const Boom = require('@hapi/boom');
2
+
3
+ /**
4
+ * Re-authorization of a credential the caller owns (Management API v2). It
5
+ * runs the same flow as /api/v2/authorize for the credential's entity type,
6
+ * with the session bound to the credential so it cannot be reused for
7
+ * anything else.
8
+ */
9
+ async function credentialEntityType(getCredentialForUser, credentialId, user) {
10
+ const credential = await getCredentialForUser.execute(credentialId, user);
11
+ if (!credential.type) {
12
+ throw Boom.conflict(
13
+ `Credential ${credentialId} is not used by any entity, so its type is unknown; authorize a new connection instead`,
14
+ { code: 'CREDENTIAL_TYPE_UNKNOWN' }
15
+ );
16
+ }
17
+ return { entityType: credential.type, credentialId: String(credential.id) };
18
+ }
19
+
20
+ /** GET /api/v2/credentials/:credentialId/reauthorize */
21
+ class GetCredentialReauthorization {
22
+ constructor({ getCredentialForUser, getAuthorizationStep }) {
23
+ this.getCredentialForUser = getCredentialForUser;
24
+ this.getAuthorizationStep = getAuthorizationStep;
25
+ }
26
+
27
+ async execute(credentialId, user, { step = 1, sessionId, state } = {}) {
28
+ const binding = await credentialEntityType(
29
+ this.getCredentialForUser,
30
+ credentialId,
31
+ user
32
+ );
33
+ return this.getAuthorizationStep.execute({
34
+ user,
35
+ ...binding,
36
+ step,
37
+ sessionId,
38
+ state,
39
+ });
40
+ }
41
+ }
42
+
43
+ /** POST /api/v2/credentials/:credentialId/reauthorize */
44
+ class ReauthorizeCredentialForUser {
45
+ constructor({ getCredentialForUser, submitAuthorizationStep }) {
46
+ this.getCredentialForUser = getCredentialForUser;
47
+ this.submitAuthorizationStep = submitAuthorizationStep;
48
+ }
49
+
50
+ async execute(credentialId, user, { data, step = 1, sessionId } = {}) {
51
+ const binding = await credentialEntityType(
52
+ this.getCredentialForUser,
53
+ credentialId,
54
+ user
55
+ );
56
+ return this.submitAuthorizationStep.execute({
57
+ user,
58
+ ...binding,
59
+ data,
60
+ step,
61
+ sessionId,
62
+ });
63
+ }
64
+ }
65
+
66
+ module.exports = { GetCredentialReauthorization, ReauthorizeCredentialForUser };
@@ -39,6 +39,12 @@ const CORE_ENCRYPTION_SCHEMA = {
39
39
  Token: {
40
40
  fields: ['token'],
41
41
  },
42
+
43
+ // Multi-step authorization (Management API v2): earlier steps can collect
44
+ // emails, usernames or one-time codes.
45
+ AuthorizationSession: {
46
+ fields: ['stepData'],
47
+ },
42
48
  };
43
49
 
44
50
  let customSchema = {};