@friggframework/core 2.0.0--canary.684.0da024b.0 → 2.0.0--canary.679.a2bcc2f.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 (104) hide show
  1. package/CLAUDE.md +0 -2
  2. package/README.md +0 -105
  3. package/application/commands/integration-commands.js +2 -2
  4. package/application/commands/user-commands.js +5 -17
  5. package/credential/use-cases/credential-operations-for-user.js +25 -110
  6. package/credential/use-cases/reauthorize-credential-for-user.js +8 -15
  7. package/database/documentdb-utils.js +1 -6
  8. package/generated/prisma-mongodb/edge.js +4 -15
  9. package/generated/prisma-mongodb/index-browser.js +1 -12
  10. package/generated/prisma-mongodb/index.d.ts +86 -2027
  11. package/generated/prisma-mongodb/index.js +4 -15
  12. package/generated/prisma-mongodb/package.json +1 -1
  13. package/generated/prisma-mongodb/schema.prisma +0 -47
  14. package/generated/prisma-mongodb/wasm.js +4 -15
  15. package/generated/prisma-postgresql/edge.js +4 -15
  16. package/generated/prisma-postgresql/index-browser.js +1 -12
  17. package/generated/prisma-postgresql/index.d.ts +63 -2162
  18. package/generated/prisma-postgresql/index.js +4 -15
  19. package/generated/prisma-postgresql/package.json +1 -1
  20. package/generated/prisma-postgresql/schema.prisma +0 -44
  21. package/generated/prisma-postgresql/wasm.js +4 -15
  22. package/handlers/app-definition-loader.js +1 -15
  23. package/index.js +0 -18
  24. package/integrations/integration-router.js +73 -115
  25. package/integrations/repositories/integration-repository-documentdb.js +3 -35
  26. package/integrations/repositories/integration-repository-interface.js +1 -17
  27. package/integrations/repositories/integration-repository-mongo.js +76 -59
  28. package/integrations/repositories/integration-repository-postgres.js +76 -62
  29. package/integrations/tests/doubles/test-integration-repository.js +1 -12
  30. package/integrations/use-cases/create-integration.js +20 -55
  31. package/integrations/use-cases/get-integrations-for-user.js +40 -80
  32. package/integrations/use-cases/index.js +1 -5
  33. package/integrations/use-cases/integration-operations-for-user.js +24 -55
  34. package/management-api/management-api-config.js +0 -3
  35. package/management-api/openapi/components.js +0 -40
  36. package/management-api/openapi/v2-operations.js +1 -13
  37. package/management-api/v2/dependencies.js +15 -40
  38. package/management-api/v2/dto.js +0 -20
  39. package/management-api/v2/handlers/authorization.js +0 -1
  40. package/management-api/v2/handlers/credentials.js +2 -6
  41. package/management-api/v2/handlers/entities.js +7 -10
  42. package/management-api/v2/handlers/integrations.js +3 -6
  43. package/management-api/v2/request.js +1 -32
  44. package/modules/index.js +0 -8
  45. package/modules/repositories/module-repository-documentdb.js +4 -48
  46. package/modules/repositories/module-repository-interface.js +2 -19
  47. package/modules/repositories/module-repository-mongo.js +73 -65
  48. package/modules/repositories/module-repository-postgres.js +73 -64
  49. package/modules/use-cases/entity-operations-for-user.js +13 -50
  50. package/modules/use-cases/entity-types.js +7 -31
  51. package/modules/use-cases/execute-entity-proxy-request.js +0 -15
  52. package/modules/use-cases/get-entities-for-user.js +5 -16
  53. package/modules/use-cases/get-entity-module-for-user.js +3 -23
  54. package/modules/use-cases/get-entity-options-by-id.js +3 -9
  55. package/modules/use-cases/get-module.js +3 -9
  56. package/modules/use-cases/multi-step-authorization.js +12 -39
  57. package/modules/use-cases/process-authorization-callback.js +18 -52
  58. package/modules/use-cases/refresh-entity-options.js +3 -9
  59. package/modules/use-cases/test-module-auth.js +3 -9
  60. package/package.json +5 -6
  61. package/prisma-mongodb/schema.prisma +0 -47
  62. package/prisma-postgresql/schema.prisma +0 -44
  63. package/types/index.d.ts +0 -1
  64. package/types/modules/index.d.ts +0 -87
  65. package/user/repositories/user-repository-documentdb.js +2 -27
  66. package/user/repositories/user-repository-interface.js +0 -18
  67. package/user/repositories/user-repository-mongo.js +0 -24
  68. package/user/repositories/user-repository-postgres.js +0 -18
  69. package/user/use-cases/authenticate-user.js +1 -7
  70. package/user/use-cases/get-user-from-adopter-jwt.js +124 -95
  71. package/user/use-cases/get-user-from-x-frigg-headers.js +80 -83
  72. package/user/user.js +1 -64
  73. package/database/organization-where.js +0 -18
  74. package/database/unique-violation.js +0 -25
  75. package/integrations/repositories/integration-not-found.js +0 -14
  76. package/integrations/use-cases/resolve-integration-ownership.js +0 -177
  77. package/modules/entity-scope.js +0 -15
  78. package/modules/scope-config.js +0 -192
  79. package/modules/scope-policy.js +0 -112
  80. package/modules/scope-resolution.js +0 -288
  81. package/modules/scope-visibility.js +0 -239
  82. package/modules/tests/doubles/ownership-matching.js +0 -18
  83. package/modules/use-cases/authorize-entity-for-user.js +0 -61
  84. package/modules/use-cases/create-entity-from-credential.js +0 -113
  85. package/modules/use-cases/manage-access.js +0 -21
  86. package/prisma-postgresql/migrations/20261015000000_add_organization_membership/migration.sql +0 -26
  87. package/prisma-postgresql/migrations/20261016000000_add_entity_integration_organization/migration.sql +0 -25
  88. package/types/user/index.d.ts +0 -134
  89. package/user/adopter-jwt-config.js +0 -177
  90. package/user/adopter-jwt-errors.js +0 -59
  91. package/user/adopter-token-verifier.js +0 -122
  92. package/user/app-user-helpers.js +0 -97
  93. package/user/create-user-authentication.js +0 -64
  94. package/user/membership.js +0 -51
  95. package/user/repositories/organization-membership-record.js +0 -19
  96. package/user/repositories/organization-membership-repository-documentdb.js +0 -106
  97. package/user/repositories/organization-membership-repository-factory.js +0 -42
  98. package/user/repositories/organization-membership-repository-interface.js +0 -57
  99. package/user/repositories/organization-membership-repository-mongo.js +0 -13
  100. package/user/repositories/organization-membership-repository-postgres.js +0 -29
  101. package/user/repositories/organization-membership-repository-prisma.js +0 -81
  102. package/user/tests/doubles/adopter-jwt-fixtures.js +0 -220
  103. package/user/use-cases/ensure-organization-membership.js +0 -92
  104. package/user/use-cases/find-individual-users-by-organization.js +0 -54
@@ -3,8 +3,6 @@ const { FetchError } = require('../../errors/fetch-error');
3
3
  const { getLogger } = require('../../logs');
4
4
  const { AuthorizationSession } = require('../domain/authorization-session');
5
5
  const { findDefinition, getAuthStepCount } = require('./entity-types');
6
- const { describeRecord } = require('../scope-visibility');
7
- const { DEFAULT_SCOPE_POLICY } = require('../scope-policy');
8
6
 
9
7
  const log = getLogger('frigg.api.authorize');
10
8
 
@@ -146,30 +144,21 @@ class SubmitAuthorizationStep {
146
144
  moduleDefinitions,
147
145
  getAuthorizationRequirements,
148
146
  authorizationSessionRepository,
149
- authorizeEntityForUser,
147
+ processAuthorizationCallback,
150
148
  moduleRepository,
151
149
  credentialRepository,
152
150
  createModule,
153
- scopePolicy,
154
151
  }) {
155
- this.scopePolicy = scopePolicy || DEFAULT_SCOPE_POLICY;
156
152
  this.moduleDefinitions = moduleDefinitions || [];
157
153
  this.getAuthorizationRequirements = getAuthorizationRequirements;
158
154
  this.sessions = authorizationSessionRepository;
159
- this.authorizeEntityForUser = authorizeEntityForUser;
155
+ this.processAuthorizationCallback = processAuthorizationCallback;
160
156
  this.moduleRepository = moduleRepository;
161
157
  this.credentialRepository = credentialRepository;
162
158
  this.createModule = createModule || defaultCreateModule;
163
159
  }
164
160
 
165
- /**
166
- * @param {Object} params
167
- * @param {string} [params.scope] - the scope the caller asks for, from the
168
- * deciding level's allow list (ADR-056 §3.1). Never `global`.
169
- * @param {string} [params.fixedScope] - re-authorization keeps the scope the
170
- * credential already has, whatever the config says now.
171
- */
172
- async execute({ user, entityType, data, step = 1, sessionId, credentialId = null, scope, fixedScope }) {
161
+ async execute({ user, entityType, data, step = 1, sessionId, credentialId = null }) {
173
162
  if (!data || typeof data !== 'object' || Array.isArray(data)) {
174
163
  throw Boom.badRequest('data must be an object', {
175
164
  code: 'VALIDATION_ERROR',
@@ -177,16 +166,7 @@ class SubmitAuthorizationStep {
177
166
  });
178
167
  }
179
168
  const definition = findDefinition(this.moduleDefinitions, entityType);
180
- // `userId` binds a session to the caller and is what GET /authorize
181
- // computes too. The owner of the entity this creates is decided by
182
- // scope (§3.2), not by user.primary, and is `ownership.ownerId`.
183
169
  const userId = user.getId();
184
- const ownership = this.authorizeEntityForUser.resolveOwnership({
185
- user,
186
- entityType,
187
- scope,
188
- fixedScope,
189
- });
190
170
 
191
171
  if (!isMultiStep(definition)) {
192
172
  if (step !== 1) {
@@ -194,7 +174,7 @@ class SubmitAuthorizationStep {
194
174
  code: 'INVALID_STEP',
195
175
  });
196
176
  }
197
- return this.complete({ ownership, user, entityType, params: data, credentialId });
177
+ return this.complete({ userId, entityType, params: data, credentialId });
198
178
  }
199
179
 
200
180
  const totalSteps = getAuthStepCount(definition);
@@ -225,7 +205,7 @@ class SubmitAuthorizationStep {
225
205
  );
226
206
  }
227
207
 
228
- const module = this.createModule({ userId: ownership.ownerId, definition });
208
+ const module = this.createModule({ userId, definition });
229
209
  let result;
230
210
  try {
231
211
  result = await definition.processAuthorizationStep(
@@ -244,8 +224,7 @@ class SubmitAuthorizationStep {
244
224
  session.markComplete();
245
225
  await this.sessions.update(session);
246
226
  const outcome = await this.complete({
247
- ownership,
248
- user,
227
+ userId,
249
228
  entityType,
250
229
  params: result.authData || {},
251
230
  credentialId,
@@ -282,15 +261,14 @@ class SubmitAuthorizationStep {
282
261
  };
283
262
  }
284
263
 
285
- async complete({ ownership, user, entityType, params, credentialId }) {
264
+ async complete({ userId, entityType, params, credentialId }) {
286
265
  let callback;
287
266
  try {
288
- ({ result: callback } = await this.authorizeEntityForUser.execute({
289
- user,
267
+ callback = await this.processAuthorizationCallback.execute(
268
+ userId,
290
269
  entityType,
291
- data: params,
292
- ownership,
293
- }));
270
+ params
271
+ );
294
272
  } catch (error) {
295
273
  throw toAuthorizationError(error);
296
274
  }
@@ -298,18 +276,13 @@ class SubmitAuthorizationStep {
298
276
  this.moduleRepository.findEntityById(callback.entity_id),
299
277
  this.credentialRepository.findCredentialById(callback.credential_id),
300
278
  ]);
301
- // What the new entity is to this caller (§3.4), so a client need not list again.
302
- const tenancy = entity
303
- ? describeRecord(entity, this.scopePolicy.accessContext(user), 'entity')
304
- : null;
305
279
  const outcome = {
306
280
  status: 'complete',
307
- entity: entity && tenancy ? { ...entity, tenancy } : entity,
281
+ entity,
308
282
  credential: credential && {
309
283
  ...credential,
310
284
  type: entityType,
311
285
  entityIds: entity ? [String(entity.id)] : [],
312
- ...(tenancy && { tenancy }),
313
286
  },
314
287
  };
315
288
  if (credentialId && String(callback.credential_id) !== String(credentialId)) {
@@ -1,16 +1,5 @@
1
1
  const { Module } = require('../module');
2
2
  const { ModuleConstants } = require('../ModuleConstants');
3
- const { pickExistingEntity } = require('../scope-resolution');
4
-
5
- /**
6
- * What an entity belongs to when the caller says nothing: the person's own,
7
- * outside any organization.
8
- */
9
- const DEFAULT_TENANCY = Object.freeze({
10
- scope: 'individual',
11
- organizationId: null,
12
- legacyOrgId: null,
13
- });
14
3
  const { getLogger } = require('../../logs');
15
4
 
16
5
  const log = getLogger('frigg.modules.authorization_callback');
@@ -41,17 +30,7 @@ class ProcessAuthorizationCallback {
41
30
  this.integrationRepository = integrationRepository;
42
31
  }
43
32
 
44
- /**
45
- * @param {string} userId - the OWNER of what this creates (ADR-056 §3.2): the
46
- * person for `individual`, the organization's user for `organization`.
47
- * Not necessarily the caller; callers resolve it from the scope.
48
- * @param {string} entityType
49
- * @param {Object} params - what the module's authorization needs
50
- * @param {{scope: string, organizationId: (string|null), legacyOrgId: (string|null)}} [tenancy]
51
- * the entity's scope and organization (§3.6); default: the person's own,
52
- * with no organization
53
- */
54
- async execute(userId, entityType, params, tenancy = DEFAULT_TENANCY) {
33
+ async execute(userId, entityType, params) {
55
34
  log.debug('Authorization callback started', {
56
35
  eventName: `${log.name}.started`,
57
36
  userId,
@@ -78,7 +57,10 @@ class ProcessAuthorizationCallback {
78
57
  userId,
79
58
  entityType
80
59
  );
81
- const existingEntity = pickExistingEntity(existingEntities, tenancy);
60
+ const existingEntity =
61
+ existingEntities && existingEntities.length > 0
62
+ ? existingEntities[0]
63
+ : null;
82
64
 
83
65
  if (existingEntity) {
84
66
  log.debug('Existing entity found', {
@@ -174,8 +156,7 @@ class ProcessAuthorizationCallback {
174
156
  const persistedEntity = await this.findOrCreateEntity(
175
157
  entityDetails,
176
158
  entityType,
177
- module.credential.id,
178
- tenancy
159
+ module.credential.id
179
160
  );
180
161
  log.debug('Authorization callback completed', {
181
162
  eventName: `${log.name}.completed`,
@@ -252,12 +233,7 @@ class ProcessAuthorizationCallback {
252
233
  module.credential = persisted;
253
234
  }
254
235
 
255
- async findOrCreateEntity(
256
- entityDetails,
257
- moduleName,
258
- credentialId,
259
- tenancy = DEFAULT_TENANCY
260
- ) {
236
+ async findOrCreateEntity(entityDetails, moduleName, credentialId) {
261
237
  const { identifiers, details } = entityDetails;
262
238
 
263
239
  // Support both 'user' and 'userId' field names from module definitions
@@ -271,16 +247,11 @@ class ProcessAuthorizationCallback {
271
247
  );
272
248
  }
273
249
 
274
- // The same provider account in two organizations is two entities
275
- // (ADR-056 §3.6), so the match is per organization.
276
- const existingEntity = pickExistingEntity(
277
- await this.moduleRepository.findEntities({
278
- externalId: identifiers.externalId,
279
- user: userId,
280
- moduleName: moduleName,
281
- }),
282
- tenancy
283
- );
250
+ const existingEntity = await this.moduleRepository.findEntity({
251
+ externalId: identifiers.externalId,
252
+ user: userId,
253
+ moduleName: moduleName,
254
+ });
284
255
 
285
256
  if (existingEntity) {
286
257
  // Repoint the entity's credentialId when re-auth produced a
@@ -311,17 +282,12 @@ class ProcessAuthorizationCallback {
311
282
  return existingEntity;
312
283
  }
313
284
 
314
- // `organizationId` is not part of the entity data: that carries provider
315
- // fields, and one that happens to be called organizationId is theirs.
316
- return await this.moduleRepository.createEntity(
317
- {
318
- ...identifiers,
319
- ...details,
320
- moduleName: moduleName,
321
- credential: credentialId,
322
- },
323
- { organizationId: tenancy.organizationId ?? null }
324
- );
285
+ return await this.moduleRepository.createEntity({
286
+ ...identifiers,
287
+ ...details,
288
+ moduleName: moduleName,
289
+ credential: credentialId,
290
+ });
325
291
  }
326
292
  }
327
293
 
@@ -1,5 +1,4 @@
1
1
  const { Module } = require('../module');
2
- const { DEFAULT_SCOPE_POLICY } = require('../scope-policy');
3
2
 
4
3
  class RefreshEntityOptions {
5
4
  /**
@@ -7,11 +6,9 @@ class RefreshEntityOptions {
7
6
  * @param {import('../repositories/module-repository-interface').ModuleRepositoryInterface} params.moduleRepository
8
7
  * @param {} params.moduleDefinitions
9
8
  */
10
- constructor({ moduleRepository, moduleDefinitions, scopePolicy }) {
9
+ constructor({ moduleRepository, moduleDefinitions }) {
11
10
  this.moduleRepository = moduleRepository;
12
11
  this.moduleDefinitions = moduleDefinitions;
13
- // Who may load an entity follows its scope (ADR-056 §3.6).
14
- this.scopePolicy = scopePolicy || DEFAULT_SCOPE_POLICY;
15
12
  }
16
13
 
17
14
  /**
@@ -39,7 +36,7 @@ class RefreshEntityOptions {
39
36
 
40
37
  // Validate entity ownership
41
38
  const isOwned = typeof userIdOrUser === 'object' && userIdOrUser?.ownsUserId
42
- ? this.scopePolicy.canUseEntity(userIdOrUser, entity)
39
+ ? userIdOrUser.ownsUserId(entity.userId)
43
40
  : entity.userId?.toString() === userId?.toString();
44
41
 
45
42
  if (!isOwned) {
@@ -61,11 +58,8 @@ class RefreshEntityOptions {
61
58
  );
62
59
  }
63
60
 
64
- // Built for the entity's OWNER, not the caller: a caller may use an
65
- // organization's entity, and a token refresh during this call must
66
- // update the owner's credential, not create one under the caller.
67
61
  const module = new Module({
68
- userId: entity.userId ?? userId,
62
+ userId,
69
63
  entity,
70
64
  definition: moduleDefinition,
71
65
  });
@@ -1,5 +1,4 @@
1
1
  const { Module } = require('../module');
2
- const { DEFAULT_SCOPE_POLICY } = require('../scope-policy');
3
2
 
4
3
  class TestModuleAuth {
5
4
  /**
@@ -7,11 +6,9 @@ class TestModuleAuth {
7
6
  * @param {import('../repositories/module-repository-interface').ModuleRepositoryInterface} params.moduleRepository - Repository for module data operations.
8
7
  * @param {Array<Object>} params.moduleDefinitions - Array of module definitions.
9
8
  */
10
- constructor({ moduleRepository, moduleDefinitions, scopePolicy }) {
9
+ constructor({ moduleRepository, moduleDefinitions }) {
11
10
  this.moduleRepository = moduleRepository;
12
11
  this.moduleDefinitions = moduleDefinitions;
13
- // Who may load an entity follows its scope (ADR-056 §3.6).
14
- this.scopePolicy = scopePolicy || DEFAULT_SCOPE_POLICY;
15
12
  }
16
13
 
17
14
  /**
@@ -38,7 +35,7 @@ class TestModuleAuth {
38
35
 
39
36
  // Validate entity ownership
40
37
  const isOwned = typeof userIdOrUser === 'object' && userIdOrUser?.ownsUserId
41
- ? this.scopePolicy.canUseEntity(userIdOrUser, entity)
38
+ ? userIdOrUser.ownsUserId(entity.userId)
42
39
  : entity.userId?.toString() === userId?.toString();
43
40
 
44
41
  if (!isOwned) {
@@ -60,11 +57,8 @@ class TestModuleAuth {
60
57
  );
61
58
  }
62
59
 
63
- // Built for the entity's OWNER, not the caller: a caller may use an
64
- // organization's entity, and a token refresh during this call must
65
- // update the owner's credential, not create one under the caller.
66
60
  const module = new Module({
67
- userId: entity.userId ?? userId,
61
+ userId,
68
62
  entity,
69
63
  definition: moduleDefinition,
70
64
  });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@friggframework/core",
3
3
  "prettier": "@friggframework/prettier-config",
4
- "version": "2.0.0--canary.684.0da024b.0",
4
+ "version": "2.0.0--canary.679.a2bcc2f.0",
5
5
  "dependencies": {
6
6
  "@aws-sdk/client-apigatewaymanagementapi": "^3.588.0",
7
7
  "@aws-sdk/client-kms": "^3.588.0",
@@ -28,7 +28,6 @@
28
28
  "express-async-handler": "^1.2.0",
29
29
  "form-data": "^4.0.6",
30
30
  "fs-extra": "^11.2.0",
31
- "jose": "^5.10.0",
32
31
  "lodash": "4.18.1",
33
32
  "lodash.get": "^4.4.2",
34
33
  "node-fetch": "^2.6.7",
@@ -48,9 +47,9 @@
48
47
  }
49
48
  },
50
49
  "devDependencies": {
51
- "@friggframework/eslint-config": "2.0.0--canary.684.0da024b.0",
52
- "@friggframework/prettier-config": "2.0.0--canary.684.0da024b.0",
53
- "@friggframework/test": "2.0.0--canary.684.0da024b.0",
50
+ "@friggframework/eslint-config": "2.0.0--canary.679.a2bcc2f.0",
51
+ "@friggframework/prettier-config": "2.0.0--canary.679.a2bcc2f.0",
52
+ "@friggframework/test": "2.0.0--canary.679.a2bcc2f.0",
54
53
  "@prisma/client": "^6.19.3",
55
54
  "@types/lodash": "4.17.15",
56
55
  "@typescript-eslint/eslint-plugin": "^8.0.0",
@@ -90,5 +89,5 @@
90
89
  "publishConfig": {
91
90
  "access": "public"
92
91
  },
93
- "gitHead": "0da024bd724c987e4bc839ab0c302580333466a1"
92
+ "gitHead": "a2bcc2f124b0574c0d868beff77b4da848fd7849"
94
93
  }
@@ -56,14 +56,6 @@ model User {
56
56
  integrations Integration[]
57
57
  processes Process[]
58
58
 
59
- // Organization memberships (ADR-056 §3.6). `organizationId` above is the legacy
60
- // single-org pointer: set on a person's first link, never moved afterwards, and
61
- // read as an implicit membership when no row exists for it.
62
- // As an individual: the organizations this person belongs to.
63
- memberships OrganizationMembership[] @relation("IndividualMemberships")
64
- // As an organization: the people who belong to it.
65
- orgMembers OrganizationMembership[] @relation("OrganizationMemberships")
66
-
67
59
  @@unique([username, appUserId])
68
60
  @@index([type])
69
61
  @@index([appUserId])
@@ -134,14 +126,6 @@ model Entity {
134
126
  moduleName String?
135
127
  externalId String?
136
128
 
137
- // Organization this entity was connected in (ADR-056 §3.6): the active
138
- // organization for `individual`, the owner for `organization`, null for
139
- // `global`. Null on an `individual` entity is also what every row written
140
- // before this column existed has, and what `individualAcross: 'all'` writes.
141
- // Deliberately not a relation: a deleted organization must leave its rows
142
- // invisible, not turn them into "unscoped" ones (SetNull would do that).
143
- organizationId String? @db.ObjectId
144
-
145
129
  data Json @default("{}")
146
130
 
147
131
  createdAt DateTime @default(now())
@@ -158,7 +142,6 @@ model Entity {
158
142
  associationObjects AssociationObject[]
159
143
 
160
144
  @@index([userId])
161
- @@index([userId, organizationId])
162
145
  @@index([externalId])
163
146
  @@index([moduleName])
164
147
  @@index([credentialId])
@@ -176,11 +159,6 @@ model Integration {
176
159
  user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
177
160
  status IntegrationStatus @default(IN_CREATION)
178
161
 
179
- // Organization this integration was created in (ADR-056 §3.6): the active
180
- // organization at create time. Null for rows that predate the column. Not a
181
- // relation, for the same reason as Entity.organizationId.
182
- organizationId String? @db.ObjectId
183
-
184
162
  // Configuration and version
185
163
  config Json? // Integration configuration object
186
164
  version String?
@@ -205,7 +183,6 @@ model Integration {
205
183
  processes Process[]
206
184
 
207
185
  @@index([userId])
208
- @@index([userId, organizationId])
209
186
  @@index([status])
210
187
  @@map("Integration")
211
188
  }
@@ -503,27 +480,3 @@ model AuthorizationSession {
503
480
  @@index([expiresAt])
504
481
  @@map("AuthorizationSession")
505
482
  }
506
-
507
- // ============================================================================
508
- // ORGANIZATION MEMBERSHIP (ADR-056 §3.6)
509
- // ============================================================================
510
-
511
- /// One person's membership of one organization. Unique on the pair, so adding a
512
- /// membership is an idempotent upsert. `orgRole` is the organization role the
513
- /// adopter token carried when the membership was created (MEMBER when it named none). NoAction on delete
514
- /// because MongoDB gives no referential integrity: delete a user's memberships
515
- /// before the user.
516
- model OrganizationMembership {
517
- id String @id @default(auto()) @map("_id") @db.ObjectId
518
- individualUserId String @db.ObjectId
519
- organizationUserId String @db.ObjectId
520
- orgRole String @default("MEMBER")
521
- createdAt DateTime @default(now())
522
-
523
- individualUser User @relation("IndividualMemberships", fields: [individualUserId], references: [id], onDelete: NoAction, onUpdate: NoAction)
524
- organizationUser User @relation("OrganizationMemberships", fields: [organizationUserId], references: [id], onDelete: NoAction, onUpdate: NoAction)
525
-
526
- @@unique([individualUserId, organizationUserId])
527
- @@index([organizationUserId])
528
- @@map("OrganizationMembership")
529
- }
@@ -56,14 +56,6 @@ model User {
56
56
  integrations Integration[]
57
57
  processes Process[]
58
58
 
59
- // Organization memberships (ADR-056 §3.6). `organizationId` above is the legacy
60
- // single-org pointer: set on a person's first link, never moved afterwards, and
61
- // read as an implicit membership when no row exists for it.
62
- // As an individual: the organizations this person belongs to.
63
- memberships OrganizationMembership[] @relation("IndividualMemberships")
64
- // As an organization: the people who belong to it.
65
- orgMembers OrganizationMembership[] @relation("OrganizationMemberships")
66
-
67
59
  @@unique([username, appUserId])
68
60
  @@index([type])
69
61
  @@index([appUserId])
@@ -131,14 +123,6 @@ model Entity {
131
123
  moduleName String?
132
124
  externalId String?
133
125
 
134
- // Organization this entity was connected in (ADR-056 §3.6): the active
135
- // organization for `individual`, the owner for `organization`, null for
136
- // `global`. Null on an `individual` entity is also what every row written
137
- // before this column existed has, and what `individualAcross: 'all'` writes.
138
- // Deliberately not a relation: a deleted organization must leave its rows
139
- // invisible, not turn them into "unscoped" ones (SetNull would do that).
140
- organizationId Int?
141
-
142
126
  data Json @default("{}")
143
127
 
144
128
  createdAt DateTime @default(now())
@@ -152,7 +136,6 @@ model Entity {
152
136
  associationObjects AssociationObject[]
153
137
 
154
138
  @@index([userId])
155
- @@index([userId, organizationId])
156
139
  @@index([externalId])
157
140
  @@index([moduleName])
158
141
  @@index([credentialId])
@@ -169,11 +152,6 @@ model Integration {
169
152
  user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
170
153
  status IntegrationStatus @default(IN_CREATION)
171
154
 
172
- // Organization this integration was created in (ADR-056 §3.6): the active
173
- // organization at create time. Null for rows that predate the column. Not a
174
- // relation, for the same reason as Entity.organizationId.
175
- organizationId Int?
176
-
177
155
  // Configuration and version
178
156
  config Json? // Integration configuration object
179
157
  version String?
@@ -197,7 +175,6 @@ model Integration {
197
175
  processes Process[]
198
176
 
199
177
  @@index([userId])
200
- @@index([userId, organizationId])
201
178
  @@index([status])
202
179
  }
203
180
 
@@ -483,24 +460,3 @@ model AuthorizationSession {
483
460
  @@index([userId, entityType])
484
461
  @@index([expiresAt])
485
462
  }
486
-
487
- // ============================================================================
488
- // ORGANIZATION MEMBERSHIP (ADR-056 §3.6)
489
- // ============================================================================
490
-
491
- /// One person's membership of one organization. Unique on the pair, so adding a
492
- /// membership is an idempotent upsert. `orgRole` is the organization role the
493
- /// adopter token carried when the membership was created (MEMBER when it named none).
494
- model OrganizationMembership {
495
- id Int @id @default(autoincrement())
496
- individualUserId Int
497
- organizationUserId Int
498
- orgRole String @default("MEMBER")
499
- createdAt DateTime @default(now())
500
-
501
- individualUser User @relation("IndividualMemberships", fields: [individualUserId], references: [id], onDelete: Cascade, onUpdate: NoAction)
502
- organizationUser User @relation("OrganizationMemberships", fields: [organizationUserId], references: [id], onDelete: Cascade, onUpdate: NoAction)
503
-
504
- @@unique([individualUserId, organizationUserId])
505
- @@index([organizationUserId])
506
- }
package/types/index.d.ts CHANGED
@@ -12,5 +12,4 @@
12
12
  /// <reference path="./eslint-config/index.d.ts" />
13
13
  /// <reference path="./associations/index.d.ts" />
14
14
  /// <reference path="./syncs/index.d.ts" />
15
- /// <reference path="./user/index.d.ts" />
16
15
  /// <reference path="./modules/index.d.ts" />
@@ -36,100 +36,13 @@ declare module "@friggframework/core" {
36
36
  [entityType: string]: EntityRegistration | boolean | undefined;
37
37
  }
38
38
 
39
- /**
40
- * One level's setting: a scope, or a default plus the scopes a request may
41
- * choose from (ADR-056 §3.1). `global` is never chosen by a tenant request.
42
- */
43
- export type ScopeSetting =
44
- | EntityScope
45
- | { default?: EntityScope; allow?: EntityScope[] };
46
-
47
- /**
48
- * `appDefinition.ownership` (ADR-056 §3, §3.6). Resolution order for a new
49
- * connection: request, binding, integration, entity type (`entities[name].scope`),
50
- * this `scope`, then `organization` for an organization-primary app and
51
- * `individual` otherwise.
52
- */
53
- export interface AppOwnership {
54
- scope?: ScopeSetting;
55
- /**
56
- * `'organization'` (default): an individual entity belongs to the organization
57
- * it was connected in. `'all'`: one connection per person across every
58
- * organization, stored with no `organizationId`.
59
- */
60
- individualAcross?: "organization" | "all";
61
- }
62
-
63
- /** `Definition.ownership` on an integration (ADR-056 §3.1, §3.3). */
64
- export interface IntegrationOwnership {
65
- /** Scope every binding of this integration accepts unless it sets its own. */
66
- scope?: ScopeSetting;
67
- /** `'derive'` (default): organization when every entity it uses is organization-scoped. */
68
- owner?: "derive" | "individual" | "organization";
69
- }
70
-
71
39
  export interface AppDefinition {
72
40
  integrations: any[];
73
41
  /** App-level entity type registry (ADR-059). */
74
42
  entities?: AppDefinitionEntities;
75
- /** Who owns what a person connects (ADR-056). */
76
- ownership?: AppOwnership;
77
43
  [key: string]: unknown;
78
44
  }
79
45
 
80
- /** Whose a record is and what the caller may do with it (ADR-056 §3.4). */
81
- export interface RecordTenancy {
82
- scope: Exclude<EntityScope, "global">;
83
- owner: { type: Exclude<EntityScope, "global">; id: string };
84
- /** Null for an individual entity connected outside an organization, or under `individualAcross: 'all'`. */
85
- organizationId: string | null;
86
- /** `manage`: create, reauthorize, delete. `use`: bind it, proxy through it. `view`: metadata only. */
87
- access: "manage" | "use" | "view";
88
- }
89
-
90
- /** Which scope a connection gets, and from which level of the order (ADR-056 §3.1). */
91
- export interface ResolvedScope {
92
- scope: EntityScope;
93
- /** Where `scope` came from. `request` when the request chose within the allowed list. */
94
- source: "request" | "binding" | "integration" | "entityType" | "app" | "default";
95
- /** The level that decided what a request may choose from. */
96
- decidedBy: "binding" | "integration" | "entityType" | "app" | "default";
97
- allow: EntityScope[];
98
- }
99
-
100
- /**
101
- * First match wins, each level overriding the ones below it. A request may
102
- * choose only from the deciding level's `allow`; `global` never comes from a
103
- * tenant request. Throws a Boom 400/403 for a request scope that is not allowed.
104
- */
105
- export function resolveScope(levels: {
106
- request?: EntityScope;
107
- binding?: ScopeSetting;
108
- integration?: ScopeSetting;
109
- entityType?: ScopeSetting;
110
- app?: ScopeSetting;
111
- primary?: "individual" | "organization";
112
- }): ResolvedScope;
113
-
114
- /** Every binding of every integration with its resolved scope (for tooling that wants to show the chain). */
115
- export function listBindingScopes(
116
- appDefinition: Pick<AppDefinition, "integrations" | "ownership">,
117
- entityTypeRegistry: EntityTypeRegistry,
118
- primary?: "individual" | "organization"
119
- ): Array<{
120
- integration: string;
121
- binding: string;
122
- moduleName: string | null;
123
- scope: EntityScope;
124
- source: ResolvedScope["source"];
125
- owner: "derive" | "individual" | "organization";
126
- }>;
127
-
128
- /** Invalid ownership or scope setting, thrown at app-definition load. `code` is always `OWNERSHIP_CONFIG_INVALID`. */
129
- export class OwnershipConfigError extends Error {
130
- code: "OWNERSHIP_CONFIG_INVALID";
131
- }
132
-
133
46
  /**
134
47
  * Builds the registry from `entities` plus the modules integrations bind.
135
48
  * Throws EntityRegistryError on an invalid registry.