@x12i/keyrox-store 0.1.0 → 0.2.1

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 (45) hide show
  1. package/dist/application-lifecycle.d.ts +6 -0
  2. package/dist/application-lifecycle.d.ts.map +1 -0
  3. package/dist/application-lifecycle.js +28 -0
  4. package/dist/application-lifecycle.js.map +1 -0
  5. package/dist/directory-access.d.ts +61 -0
  6. package/dist/directory-access.d.ts.map +1 -0
  7. package/dist/directory-access.js +20 -0
  8. package/dist/directory-access.js.map +1 -0
  9. package/dist/directory-invitation.d.ts +34 -0
  10. package/dist/directory-invitation.d.ts.map +1 -0
  11. package/dist/directory-invitation.js +29 -0
  12. package/dist/directory-invitation.js.map +1 -0
  13. package/dist/directory-memory.d.ts +21 -4
  14. package/dist/directory-memory.d.ts.map +1 -1
  15. package/dist/directory-memory.js +1096 -24
  16. package/dist/directory-memory.js.map +1 -1
  17. package/dist/email-code-policy.d.ts +7 -0
  18. package/dist/email-code-policy.d.ts.map +1 -0
  19. package/dist/email-code-policy.js +7 -0
  20. package/dist/email-code-policy.js.map +1 -0
  21. package/dist/errors.d.ts +1 -1
  22. package/dist/errors.d.ts.map +1 -1
  23. package/dist/errors.js.map +1 -1
  24. package/dist/hosted-human-sessions.d.ts +48 -0
  25. package/dist/hosted-human-sessions.d.ts.map +1 -0
  26. package/dist/hosted-human-sessions.js +2 -0
  27. package/dist/hosted-human-sessions.js.map +1 -0
  28. package/dist/index.d.ts +8 -1
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +5 -0
  31. package/dist/index.js.map +1 -1
  32. package/dist/memory.d.ts.map +1 -1
  33. package/dist/memory.js +1115 -85
  34. package/dist/memory.js.map +1 -1
  35. package/dist/notification-delivery.d.ts +44 -0
  36. package/dist/notification-delivery.d.ts.map +1 -0
  37. package/dist/notification-delivery.js +58 -0
  38. package/dist/notification-delivery.js.map +1 -0
  39. package/dist/notification-webhook-jobs.d.ts +43 -0
  40. package/dist/notification-webhook-jobs.d.ts.map +1 -0
  41. package/dist/notification-webhook-jobs.js +59 -0
  42. package/dist/notification-webhook-jobs.js.map +1 -0
  43. package/dist/repository.d.ts +188 -12
  44. package/dist/repository.d.ts.map +1 -1
  45. package/package.json +2 -2
@@ -1,3 +1,7 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { directoryHasOrganizations, directoryHasWorkspaces } from "@x12i/keyrox-types";
3
+ import { existingGrantDecision, missingGrantDecision, } from "./directory-access.js";
4
+ import { invitationLifecycle, invitationPreview } from "./directory-invitation.js";
1
5
  import { fail } from "./errors.js";
2
6
  import { asTime, asTimeOrNull, clone, isExpired } from "./time.js";
3
7
  export function emptyDirectory() {
@@ -8,22 +12,408 @@ export function emptyDirectory() {
8
12
  directoryMemberships: new Map(),
9
13
  permissions: new Map(),
10
14
  productRoles: new Map(),
15
+ tenantProductRoles: new Map(),
16
+ signupRoles: new Map(),
11
17
  groups: new Map(),
12
18
  groupMembers: new Map(),
13
19
  bindings: new Map(),
14
20
  features: new Map(),
15
21
  featureAssignments: new Map(),
16
22
  appWaitlist: new Map(),
23
+ waitlistConfirmations: new Map(),
17
24
  directoryChallenges: new Map(),
25
+ hostedSsoIdentities: new Map(),
26
+ workspaces: new Map(),
27
+ workspaceMemberships: new Map(),
28
+ onboardingResponses: new Map(),
29
+ accessChecks: new Map(),
18
30
  };
19
31
  }
20
- export function bindDirectoryMemory(source, users, tx) {
32
+ function signInRank(kind) {
33
+ if (kind === "user")
34
+ return 0;
35
+ if (kind === "account")
36
+ return 1;
37
+ return 2;
38
+ }
39
+ function signInIdentity(identities, environmentId, email) {
40
+ const address = email.toLowerCase();
41
+ return [...identities]
42
+ .filter((row) => row.environmentId === environmentId && row.kind !== "organization" && row.email?.toLowerCase() === address)
43
+ .sort((left, right) => signInRank(left.kind) - signInRank(right.kind) || left.id.localeCompare(right.id))[0] ?? null;
44
+ }
45
+ export function bindDirectoryMemory(source, users, tx, activeApplicationForEnvironment, insertNotification) {
21
46
  const rows = (map, pred = () => true) => [...map.values()].filter(pred).map((row) => clone(row));
22
47
  const save = (map, row) => { map.set(row.id, clone(row)); };
23
48
  const remove = (map, id) => {
24
49
  if (!map.delete(id))
25
50
  fail("not_found", "Record not found.");
26
51
  };
52
+ function assertAvailableCatalogLink(role) {
53
+ if (!role.catalogRoleId)
54
+ return;
55
+ const maps = source();
56
+ const catalog = maps.tenantProductRoles.get(role.catalogRoleId);
57
+ if (!catalog || catalog.orgId !== activeApplicationForEnvironment(role.environmentId, true)?.orgId) {
58
+ fail("conflict", "Catalog role must belong to the application tenant.");
59
+ }
60
+ const existing = [...maps.productRoles.values()].some((item) => item.id !== role.id
61
+ && item.environmentId === role.environmentId && item.catalogRoleId === role.catalogRoleId);
62
+ if (existing)
63
+ fail("duplicate", "The catalog role already has a link in this environment.");
64
+ }
65
+ function saveTenantRole(row) {
66
+ const catalog = source().tenantProductRoles;
67
+ if ([...catalog.values()].some((item) => item.id !== row.id && item.orgId === row.orgId && item.name.toLowerCase() === row.name.toLowerCase())) {
68
+ fail("duplicate", "A catalog role already uses this name.");
69
+ }
70
+ save(catalog, row);
71
+ }
72
+ function saveIdentity(maps, row) {
73
+ if (row.email && row.kind !== "organization" && [...maps.identities.values()].some((item) => item.id !== row.id && item.kind !== "organization" && item.environmentId === row.environmentId
74
+ && item.email?.toLowerCase() === row.email?.toLowerCase())) {
75
+ fail("duplicate_email", "Email already exists.");
76
+ }
77
+ const { emailProofAt, ...identity } = row;
78
+ save(maps.identities, { ...identity, metadata: clone(row.metadata), emailVerifiedAt: asTimeOrNull(row.emailVerifiedAt),
79
+ ...(emailProofAt && { emailProofAt: asTime(emailProofAt) }), createdAt: asTime(row.createdAt), updatedAt: asTime(row.updatedAt) });
80
+ }
81
+ function recordEmailProof(identity, stamp) {
82
+ identity.emailVerifiedAt ??= stamp;
83
+ if (identity.kind === "user" && (!identity.emailProofAt || identity.emailProofAt < stamp))
84
+ identity.emailProofAt = stamp;
85
+ if (identity.updatedAt < stamp)
86
+ identity.updatedAt = stamp;
87
+ }
88
+ function addChallenge(maps, row) {
89
+ if (maps.directoryChallenges.has(row.id) || [...maps.directoryChallenges.values()].some((item) => item.tokenHash === row.tokenHash))
90
+ fail("duplicate", "Duplicate key.");
91
+ save(maps.directoryChallenges, { ...row, expiresAt: asTime(row.expiresAt), usedAt: asTimeOrNull(row.usedAt), createdAt: asTime(row.createdAt) });
92
+ }
93
+ function saveHostedSsoLink(maps, row) {
94
+ const identity = maps.identities.get(row.identityId);
95
+ if (identity?.environmentId !== row.environmentId || identity.kind !== "user")
96
+ fail("conflict", "Hosted sign-in identity is missing.");
97
+ const key = JSON.stringify([row.environmentId, row.authority, row.subject]);
98
+ const existing = maps.hostedSsoIdentities.get(key);
99
+ if (existing)
100
+ return existing.identityId === row.identityId;
101
+ maps.hostedSsoIdentities.set(key, clone(row));
102
+ return true;
103
+ }
104
+ function assertWorkspaceScope(workspace) {
105
+ const app = activeApplicationForEnvironment(workspace.environmentId);
106
+ const model = app?.directoryModel ?? "organizations";
107
+ if (!app || app.id !== workspace.appId || !directoryHasWorkspaces(model) ||
108
+ (model === "organizations-and-workspaces") !== (workspace.organizationId !== null)) {
109
+ fail("conflict", "This workspace is incompatible with the application directory model.");
110
+ }
111
+ if (workspace.organizationId) {
112
+ const organization = source().identities.get(workspace.organizationId);
113
+ if (organization?.kind !== "organization" || organization.status !== "active" ||
114
+ organization.appId !== workspace.appId || organization.environmentId !== workspace.environmentId) {
115
+ fail("conflict", "The workspace organization is unavailable in this environment.");
116
+ }
117
+ }
118
+ }
119
+ function requireOrganizationScope(environmentId) {
120
+ if (activeApplicationForEnvironment(environmentId, true)?.directoryModel === "people-only") {
121
+ fail("conflict", "Organizations are unavailable for this application.");
122
+ }
123
+ }
124
+ function addWorkspaceMember(workspace, row) {
125
+ const maps = source();
126
+ const identity = maps.identities.get(row.identityId);
127
+ if (row.workspaceId !== workspace.id || row.environmentId !== workspace.environmentId || identity?.kind === "organization" ||
128
+ identity?.status !== "active" || identity.environmentId !== workspace.environmentId || identity.appId !== workspace.appId) {
129
+ fail("conflict", "The workspace member is unavailable in this environment.");
130
+ }
131
+ if (workspace.organizationId && ![...maps.directoryMemberships.values()].some((member) => member.environmentId === row.environmentId && member.identityId === row.identityId && member.organizationId === workspace.organizationId)) {
132
+ fail("conflict", "The workspace member must belong to its organization.");
133
+ }
134
+ if (maps.workspaceMemberships.has(row.id) || [...maps.workspaceMemberships.values()]
135
+ .some((item) => item.workspaceId === row.workspaceId && item.identityId === row.identityId))
136
+ fail("duplicate", "Duplicate workspace membership.");
137
+ if (row.relation !== "owner" && row.relation !== "member")
138
+ fail("conflict", "Invalid workspace membership relation.");
139
+ save(maps.workspaceMemberships, { ...row, createdAt: asTime(row.createdAt) });
140
+ }
141
+ function workspaceInvitationTarget(row) {
142
+ if (!row.invitation)
143
+ return null;
144
+ const maps = source();
145
+ const app = activeApplicationForEnvironment(row.environmentId);
146
+ const workspace = maps.workspaces.get(row.invitation.workspaceId ?? "");
147
+ const role = maps.productRoles.get(row.invitation.roleId);
148
+ if (app?.id !== row.appId || workspace?.appId !== row.appId || workspace.environmentId !== row.environmentId ||
149
+ workspace.status !== "active" || role?.environmentId !== row.environmentId || !directoryHasWorkspaces(app.directoryModel) ||
150
+ (app.directoryModel === "organizations-and-workspaces") !== (workspace.organizationId !== null))
151
+ return null;
152
+ if (workspace.organizationId) {
153
+ const parent = maps.identities.get(workspace.organizationId);
154
+ if (parent?.kind !== "organization" || parent.status !== "active" || parent.environmentId !== row.environmentId)
155
+ return null;
156
+ }
157
+ return { workspace, role };
158
+ }
159
+ function applyWorkspaceInvitation(row, challenge, identity, at) {
160
+ const target = workspaceInvitationTarget(row);
161
+ if (!target)
162
+ return false;
163
+ const maps = source();
164
+ const { workspace, role } = target;
165
+ const parent = workspace.organizationId;
166
+ if (parent && ![...maps.directoryMemberships.values()].some((member) => member.organizationId === parent && member.identityId === identity.id)) {
167
+ save(maps.directoryMemberships, {
168
+ id: `dms_${challenge.id}`, environmentId: row.environmentId, identityId: identity.id, organizationId: parent,
169
+ relation: "member", createdAt: at,
170
+ });
171
+ }
172
+ const existing = [...maps.workspaceMemberships.values()].find((member) => member.workspaceId === workspace.id && member.identityId === identity.id);
173
+ if (existing)
174
+ existing.roleId = role.id;
175
+ else
176
+ addWorkspaceMember(workspace, {
177
+ id: `wsm_${challenge.id}`, environmentId: row.environmentId, workspaceId: workspace.id, identityId: identity.id,
178
+ roleId: role.id, relation: "member", createdAt: at,
179
+ });
180
+ challenge.usedAt ??= at;
181
+ row.status = "admitted";
182
+ delete row.pendingWorkspaceIdentityId;
183
+ return true;
184
+ }
185
+ function invitationIsAvailable(row) {
186
+ if (!row.invitation?.roleId)
187
+ return false;
188
+ const app = activeApplicationForEnvironment(row.environmentId);
189
+ const role = source().productRoles.get(row.invitation.roleId);
190
+ if (app?.id !== row.appId || role?.environmentId !== row.environmentId)
191
+ return false;
192
+ const model = app.directoryModel ?? "organizations";
193
+ if (row.invitation.workspaceId)
194
+ return !row.invitation.organizationId && Boolean(workspaceInvitationTarget(row));
195
+ if (model === "people-only")
196
+ return !row.invitation.organizationId;
197
+ if (model !== "organizations" || !row.invitation.organizationId)
198
+ return false;
199
+ const organization = source().identities.get(row.invitation.organizationId);
200
+ return organization?.kind === "organization" && organization.status === "active" && organization.appId === row.appId && organization.environmentId === row.environmentId;
201
+ }
202
+ function invitationGrantRequest(row, identityId, at, ids) {
203
+ const ownerRole = [...source().productRoles.values()].find((role) => role.environmentId === row.environmentId && role.ownerAccess);
204
+ const invitation = row.invitation;
205
+ return {
206
+ appId: row.appId, environmentId: row.environmentId, identityId, roleId: invitation.roleId,
207
+ ...(invitation.workspaceId ? { workspaceId: invitation.workspaceId } : {}),
208
+ ...(!invitation.workspaceId && invitation.organizationId ? { organizationId: invitation.organizationId } : {}),
209
+ ownerRoleId: ownerRole?.id ?? null, at,
210
+ newMembershipId: ids.membershipId, newBindingId: ids.bindingId, newOrganizationMembershipId: ids.organizationMembershipId,
211
+ };
212
+ }
213
+ function applyStoredInvitation(row, challenge, identity, at) {
214
+ if (!row.invitation || row.invitation.delivery === "link")
215
+ return false;
216
+ if (row.invitation.workspaceId)
217
+ return applyWorkspaceInvitation(row, challenge, identity, at);
218
+ if (!invitationIsAvailable(row))
219
+ return false;
220
+ const saved = applyBindingGrant(invitationGrantRequest(row, identity.id, at, {
221
+ membershipId: `wsm_${challenge.id}`, bindingId: `rbd_${challenge.id}`, organizationMembershipId: `dms_${challenge.id}`,
222
+ }));
223
+ if (!saved.roleId)
224
+ return false;
225
+ challenge.usedAt ??= at;
226
+ row.status = "admitted";
227
+ delete row.pendingWorkspaceIdentityId;
228
+ return true;
229
+ }
230
+ function savedInvitationGrant(row, identityId) {
231
+ const invitation = row.invitation;
232
+ if (!invitation)
233
+ return { membershipId: null, bindingId: null, roleId: "" };
234
+ if (invitation.workspaceId) {
235
+ const membership = [...source().workspaceMemberships.values()].find((item) => item.workspaceId === invitation.workspaceId && item.identityId === identityId);
236
+ return { membershipId: membership?.id ?? null, bindingId: null, roleId: membership?.roleId ?? invitation.roleId };
237
+ }
238
+ const organizationId = invitation.organizationId ?? null;
239
+ const binding = [...source().bindings.values()].filter((item) => item.environmentId === row.environmentId && item.subjectType === "identity"
240
+ && item.subjectId === identityId && (item.organizationId ?? null) === organizationId && item.resource === null)
241
+ .sort((left, right) => left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id))[0];
242
+ return { membershipId: null, bindingId: binding?.id ?? null, roleId: binding?.roleId ?? invitation.roleId };
243
+ }
244
+ function acceptWorkspaceInvitation(identity, at, expectedTokenHash) {
245
+ if (!identity.emailVerifiedAt || identity.status !== "active" || identity.kind !== "user" || !identity.email)
246
+ return false;
247
+ const maps = source();
248
+ const invite = [...maps.appWaitlist.values()].find((row) => row.appId === identity.appId && row.environmentId === identity.environmentId &&
249
+ row.email.toLowerCase() === identity.email.toLowerCase() && row.status === "invited" && Boolean(row.invitation));
250
+ if (!invite || (expectedTokenHash && (invite.tokenHash !== expectedTokenHash || invite.pendingWorkspaceIdentityId)))
251
+ return false;
252
+ const challenge = [...maps.directoryChallenges.values()].find((row) => row.tokenHash === invite.tokenHash);
253
+ if (!challenge || challenge.purpose !== "admit" || challenge.environmentId !== invite.environmentId || challenge.email.toLowerCase() !== invite.email.toLowerCase())
254
+ return false;
255
+ if (invite.invitation?.delivery === "link")
256
+ return false;
257
+ if (isExpired(challenge.expiresAt, at) || (invite.pendingWorkspaceIdentityId
258
+ ? invite.pendingWorkspaceIdentityId !== identity.id || !challenge.usedAt : Boolean(challenge.usedAt)))
259
+ return false;
260
+ return applyStoredInvitation(invite, challenge, identity, at);
261
+ }
262
+ function clearAccessChecks(environmentId, identityId, workspaceId, organizationId) {
263
+ const checks = source().accessChecks;
264
+ for (const check of [...checks.values()]) {
265
+ const sameWorkspace = workspaceId !== null && check.workspaceId === workspaceId;
266
+ const samePersonScope = workspaceId === null && check.workspaceId === null && check.organizationId === organizationId;
267
+ if (check.environmentId === environmentId && check.identityId === identityId && (sameWorkspace || samePersonScope))
268
+ checks.delete(check.id);
269
+ }
270
+ }
271
+ function requireGrantPerson(request) {
272
+ const identity = source().identities.get(request.identityId);
273
+ if (!identity || identity.environmentId !== request.environmentId || identity.appId !== request.appId) {
274
+ fail("not_found", "That person is not in this environment.");
275
+ }
276
+ if (identity.kind !== "user" && identity.kind !== "account")
277
+ fail("conflict", "Choose a verified person.");
278
+ if (identity.status !== "active")
279
+ fail("conflict", "This account is disabled.");
280
+ return identity;
281
+ }
282
+ function ensureOrganizationMember(request, organizationId, relation, compareRelation) {
283
+ const maps = source();
284
+ const organization = maps.identities.get(organizationId);
285
+ if (organization?.kind !== "organization" || organization.status !== "active" || organization.environmentId !== request.environmentId || organization.appId !== request.appId) {
286
+ fail("conflict", "Choose an active organization in this environment.");
287
+ }
288
+ requireOrganizationScope(request.environmentId);
289
+ const existing = [...maps.directoryMemberships.values()].find((member) => member.environmentId === request.environmentId && member.identityId === request.identityId && member.organizationId === organizationId);
290
+ const desired = relation ?? existing?.relation ?? "member";
291
+ if (compareRelation && request.expected?.relation && existing?.relation !== request.expected.relation && existing?.relation !== desired && request.expected.relation !== desired) {
292
+ fail("grant_changed", "The saved directory role changed.");
293
+ }
294
+ if (!existing) {
295
+ if (compareRelation && request.expected?.relation && request.expected.relation !== desired)
296
+ fail("grant_changed", "The saved directory role changed.");
297
+ save(maps.directoryMemberships, {
298
+ id: request.newOrganizationMembershipId, environmentId: request.environmentId, identityId: request.identityId,
299
+ organizationId, relation: desired, createdAt: asTime(request.at),
300
+ });
301
+ return { relation: desired, changed: true };
302
+ }
303
+ if (existing.relation === desired)
304
+ return { relation: existing.relation, changed: false };
305
+ if (existing.relation === "owner" && ![...maps.directoryMemberships.values()].some((member) => member.organizationId === organizationId && member.relation === "owner" && member.id !== existing.id)) {
306
+ fail("last_owner", "An organization must keep an owner.");
307
+ }
308
+ existing.relation = desired;
309
+ return { relation: desired, changed: true };
310
+ }
311
+ function applyWorkspaceGrant(request) {
312
+ const maps = source();
313
+ const workspace = maps.workspaces.get(request.workspaceId ?? "");
314
+ if (!workspace || workspace.environmentId !== request.environmentId || workspace.appId !== request.appId)
315
+ fail("not_found", "Workspace not found.");
316
+ if (workspace.status !== "active")
317
+ fail("conflict", "This workspace is disabled.");
318
+ assertWorkspaceScope(workspace);
319
+ requireGrantPerson(request);
320
+ if (workspace.organizationId)
321
+ ensureOrganizationMember(request, workspace.organizationId, undefined, false);
322
+ const membership = request.membershipId
323
+ ? maps.workspaceMemberships.get(request.membershipId)
324
+ : [...maps.workspaceMemberships.values()].find((item) => item.workspaceId === workspace.id && item.identityId === request.identityId);
325
+ if (request.membershipId && (membership?.environmentId !== request.environmentId || membership.workspaceId !== workspace.id)) {
326
+ fail("not_found", "Workspace membership not found.");
327
+ }
328
+ if (membership && membership.identityId !== request.identityId)
329
+ fail("conflict", "That membership belongs to a different person.");
330
+ if (!membership) {
331
+ if (missingGrantDecision(request.expected) === "conflict")
332
+ fail("grant_changed", "The saved role changed.");
333
+ const relation = request.relation ?? "member";
334
+ if (request.expected?.relation && request.expected.relation !== relation)
335
+ fail("grant_changed", "The saved directory role changed.");
336
+ const created = {
337
+ id: request.newMembershipId, environmentId: request.environmentId, workspaceId: workspace.id, identityId: request.identityId,
338
+ relation, createdAt: asTime(request.at), ...(request.roleId ? { roleId: request.roleId } : {}),
339
+ };
340
+ addWorkspaceMember(workspace, created);
341
+ return { outcome: "created", membership: clone(maps.workspaceMemberships.get(created.id)), binding: null, relation, previousRoleId: null, roleId: request.roleId ?? null };
342
+ }
343
+ const decision = existingGrantDecision({ roleId: membership.roleId ?? null, relation: membership.relation }, { roleId: request.roleId, relation: request.relation }, request.expected);
344
+ if (decision === "conflict")
345
+ fail("grant_changed", "The saved role changed.");
346
+ const desiredRole = request.roleId === undefined ? membership.roleId ?? null : request.roleId;
347
+ const desiredRelation = request.relation ?? membership.relation;
348
+ if (decision === "unchanged") {
349
+ return { outcome: "unchanged", membership: clone(membership), binding: null, relation: membership.relation, previousRoleId: membership.roleId ?? null, roleId: membership.roleId ?? null };
350
+ }
351
+ if (membership.relation === "owner" && desiredRelation === "member" && ![...maps.workspaceMemberships.values()].some((row) => row.workspaceId === workspace.id && row.relation === "owner" && row.id !== membership.id)) {
352
+ fail("last_owner", "A workspace must keep an owner.");
353
+ }
354
+ if (request.ownerRoleId && (membership.roleId ?? null) === request.ownerRoleId && desiredRole !== request.ownerRoleId &&
355
+ ![...maps.workspaceMemberships.values()].some((row) => row.workspaceId === workspace.id && row.roleId === request.ownerRoleId && row.id !== membership.id)) {
356
+ fail("last_owner_access", "Assign owner access to another person in this scope first.");
357
+ }
358
+ const previousRoleId = membership.roleId ?? null;
359
+ membership.relation = desiredRelation;
360
+ if (desiredRole)
361
+ membership.roleId = desiredRole;
362
+ else
363
+ delete membership.roleId;
364
+ if (previousRoleId !== desiredRole)
365
+ clearAccessChecks(request.environmentId, request.identityId, workspace.id, null);
366
+ return { outcome: "updated", membership: clone(membership), binding: null, relation: desiredRelation, previousRoleId, roleId: desiredRole };
367
+ }
368
+ function applyBindingGrant(request) {
369
+ const maps = source();
370
+ const organizationId = request.organizationId ?? null;
371
+ requireGrantPerson(request);
372
+ const relation = organizationId ? ensureOrganizationMember(request, organizationId, request.relation, true) : { relation: null, changed: false };
373
+ const matches = [...maps.bindings.values()].filter((binding) => binding.environmentId === request.environmentId
374
+ && binding.subjectType === "identity" && binding.subjectId === request.identityId
375
+ && (binding.organizationId ?? null) === organizationId && binding.resource === null);
376
+ const binding = request.bindingId
377
+ ? maps.bindings.get(request.bindingId)
378
+ : matches.sort((left, right) => left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id))[0];
379
+ if (request.bindingId && (!binding || binding.environmentId !== request.environmentId || binding.subjectType !== "identity" || binding.subjectId !== request.identityId
380
+ || (binding.organizationId ?? null) !== organizationId || binding.resource !== null)) {
381
+ fail("not_found", "Role binding not found.");
382
+ }
383
+ if (!binding) {
384
+ if (!request.roleId) {
385
+ return { outcome: relation.changed ? "created" : "unchanged", membership: null, binding: null, relation: relation.relation, previousRoleId: null, roleId: null };
386
+ }
387
+ if (missingGrantDecision(request.expected) === "conflict")
388
+ fail("grant_changed", "The saved role changed.");
389
+ if (organizationId)
390
+ requireOrganizationScope(request.environmentId);
391
+ const created = {
392
+ id: request.newBindingId, environmentId: request.environmentId, roleId: request.roleId, subjectType: "identity",
393
+ subjectId: request.identityId, organizationId, resource: null, createdAt: asTime(request.at),
394
+ };
395
+ save(maps.bindings, created);
396
+ return { outcome: "created", membership: null, binding: clone(created), relation: relation.relation, previousRoleId: null, roleId: request.roleId };
397
+ }
398
+ const decision = existingGrantDecision({ roleId: binding.roleId, relation: relation.relation ?? "member" }, { roleId: request.roleId }, request.expected && { roleId: request.expected.roleId });
399
+ if (decision === "conflict")
400
+ fail("grant_changed", "The saved role changed.");
401
+ const desiredRole = request.roleId ?? binding.roleId;
402
+ if (decision === "unchanged" && !relation.changed) {
403
+ return { outcome: "unchanged", membership: null, binding: clone(binding), relation: relation.relation, previousRoleId: binding.roleId, roleId: binding.roleId };
404
+ }
405
+ if (request.ownerRoleId && binding.roleId === request.ownerRoleId && desiredRole !== request.ownerRoleId && !matches.some((item) => item.id !== binding.id && item.roleId === request.ownerRoleId)) {
406
+ fail("last_owner_access", "Assign owner access to another person in this scope first.");
407
+ }
408
+ const previousRoleId = binding.roleId;
409
+ binding.roleId = desiredRole;
410
+ for (const extra of matches)
411
+ if (extra.id !== binding.id)
412
+ maps.bindings.delete(extra.id);
413
+ if (previousRoleId !== desiredRole)
414
+ clearAccessChecks(request.environmentId, request.identityId, null, organizationId);
415
+ return { outcome: "updated", membership: null, binding: clone(binding), relation: relation.relation, previousRoleId, roleId: desiredRole };
416
+ }
27
417
  return {
28
418
  async countUsers() { return users(); },
29
419
  async getPlatformSignup() { return clone(source().settings); },
@@ -35,7 +425,17 @@ export function bindDirectoryMemory(source, users, tx) {
35
425
  settings.operators = [...row.operators];
36
426
  });
37
427
  },
38
- async savePlatformWaitlist(row) {
428
+ async insertPlatformWaitlist(row) {
429
+ return tx(() => {
430
+ const { platformWaitlist, waitlistConfirmations } = source();
431
+ if ([...platformWaitlist.values()].some((item) => item.email.toLowerCase() === row.email.toLowerCase()))
432
+ return false;
433
+ save(platformWaitlist, { ...row, createdAt: asTime(row.createdAt) });
434
+ waitlistConfirmations.set(`platform:${row.id}`, { claimedAt: null });
435
+ return true;
436
+ });
437
+ },
438
+ async savePlatformWaitlist(row, challenge) {
39
439
  tx(() => {
40
440
  const maps = source();
41
441
  const email = row.email.toLowerCase();
@@ -43,6 +443,8 @@ export function bindDirectoryMemory(source, users, tx) {
43
443
  if (clash)
44
444
  fail("duplicate_email", "Email already exists.");
45
445
  save(maps.platformWaitlist, { ...row, createdAt: asTime(row.createdAt) });
446
+ if (challenge)
447
+ addChallenge(maps, challenge);
46
448
  });
47
449
  },
48
450
  async listPlatformWaitlist() { return rows(source().platformWaitlist); },
@@ -52,12 +454,114 @@ export function bindDirectoryMemory(source, users, tx) {
52
454
  async saveDirectoryIdentity(row) {
53
455
  tx(() => {
54
456
  const maps = source();
55
- if (row.email) {
56
- const clash = [...maps.identities.values()].find((item) => item.environmentId === row.environmentId && item.email?.toLowerCase() === row.email?.toLowerCase() && item.id !== row.id);
57
- if (clash)
58
- fail("duplicate_email", "Email already exists.");
457
+ const app = activeApplicationForEnvironment(row.environmentId, true);
458
+ if (app?.id !== row.appId || app.orgId !== row.orgId)
459
+ fail("conflict", "Identity must match its application environment and tenant.");
460
+ if (row.kind === "organization") {
461
+ requireOrganizationScope(row.environmentId);
462
+ if (!maps.identities.has(row.id) && !directoryHasOrganizations(activeApplicationForEnvironment(row.environmentId, true)?.directoryModel)) {
463
+ fail("conflict", "New organizations are unavailable for this application.");
464
+ }
465
+ }
466
+ const previous = maps.identities.get(row.id);
467
+ const proof = previous?.email?.toLowerCase() === row.email?.toLowerCase() && row.kind === "user" ? previous?.emailProofAt : null;
468
+ saveIdentity(maps, {
469
+ ...row, emailProofAt: previous ? proof : row.emailProofAt,
470
+ emailVerifiedAt: row.emailVerifiedAt ?? (proof ? previous.emailVerifiedAt : null),
471
+ });
472
+ });
473
+ },
474
+ async proveDirectoryEmail(identityId, environmentId, email, at) {
475
+ return tx(() => {
476
+ const identity = source().identities.get(identityId);
477
+ const app = activeApplicationForEnvironment(environmentId);
478
+ if (!identity || !app || identity.environmentId !== environmentId || identity.appId !== app.id || identity.orgId !== app.orgId
479
+ || identity.kind !== "user" || identity.status !== "active" || identity.email?.toLowerCase() !== email.toLowerCase())
480
+ return null;
481
+ recordEmailProof(identity, asTime(at));
482
+ return clone(identity);
483
+ });
484
+ },
485
+ async signupDirectoryPerson({ identity, organization, membership, bindingId, challenge, allowOrganizationless, admissionTokenHash, hostedSsoLink, notificationDelivery }) {
486
+ return tx(() => {
487
+ const maps = source();
488
+ const app = activeApplicationForEnvironment(identity.environmentId, true);
489
+ if (app?.id !== identity.appId || app.orgId !== identity.orgId)
490
+ fail("conflict", "Identity must match its application environment and tenant.");
491
+ let workspaceInvite;
492
+ if (admissionTokenHash) {
493
+ const stamp = asTime(identity.createdAt);
494
+ const email = identity.email?.toLowerCase();
495
+ const invite = [...maps.appWaitlist.values()].find((row) => row.appId === identity.appId &&
496
+ row.environmentId === identity.environmentId && row.email.toLowerCase() === email && row.status === "invited" && row.tokenHash === admissionTokenHash);
497
+ const admission = [...maps.directoryChallenges.values()].find((row) => row.tokenHash === admissionTokenHash);
498
+ if (!invite || !admission || admission.purpose !== "admit" || admission.environmentId !== identity.environmentId ||
499
+ admission.email.toLowerCase() !== email || admission.usedAt || isExpired(admission.expiresAt, stamp)) {
500
+ fail("challenge_invalid", "Waiting list invitation is no longer available.");
501
+ }
502
+ if (invite.invitation?.delivery === "link")
503
+ fail("challenge_invalid", "Waiting list invitation is no longer available.");
504
+ admission.usedAt = stamp;
505
+ if (invite.invitation) {
506
+ if (!workspaceInvitationTarget(invite))
507
+ fail("challenge_invalid", "The invited workspace or role is no longer available.");
508
+ workspaceInvite = { invite, admission };
509
+ invite.pendingWorkspaceIdentityId = identity.id;
510
+ }
511
+ else
512
+ invite.status = "admitted";
513
+ }
514
+ const roleId = workspaceInvite ? undefined : maps.signupRoles.get(identity.environmentId);
515
+ const role = roleId ? maps.productRoles.get(roleId) : undefined;
516
+ const model = activeApplicationForEnvironment(identity.environmentId, true)?.directoryModel;
517
+ const organizationCreated = !workspaceInvite && directoryHasOrganizations(model) && (!allowOrganizationless || role?.allowsOrganizationlessSignup !== true);
518
+ if (maps.identities.has(identity.id) || (organizationCreated && (maps.identities.has(organization.id) || maps.directoryMemberships.has(membership.id))))
519
+ fail("duplicate", "Duplicate key.");
520
+ saveIdentity(maps, identity);
521
+ if (workspaceInvite && identity.emailVerifiedAt && !applyWorkspaceInvitation(workspaceInvite.invite, workspaceInvite.admission, identity, asTime(identity.createdAt))) {
522
+ fail("challenge_invalid", "The invited workspace or role is no longer available.");
523
+ }
524
+ if (hostedSsoLink && (hostedSsoLink.identityId !== identity.id || hostedSsoLink.environmentId !== identity.environmentId ||
525
+ !saveHostedSsoLink(maps, hostedSsoLink))) {
526
+ fail("conflict", "This provider account is linked to another profile.");
527
+ }
528
+ if (organizationCreated) {
529
+ saveIdentity(maps, organization);
530
+ save(maps.directoryMemberships, { ...membership, createdAt: asTime(membership.createdAt) });
531
+ }
532
+ if (challenge)
533
+ addChallenge(maps, challenge);
534
+ if (roleId) {
535
+ if (maps.bindings.has(bindingId))
536
+ fail("duplicate", "Duplicate key.");
537
+ save(maps.bindings, {
538
+ id: bindingId, environmentId: identity.environmentId, roleId, subjectType: "identity",
539
+ subjectId: identity.id, organizationId: null, resource: null, createdAt: asTime(identity.createdAt),
540
+ });
541
+ }
542
+ insertNotification(identity, notificationDelivery);
543
+ return { organizationCreated };
544
+ });
545
+ },
546
+ async getDirectorySignupRole(environmentId) { return source().signupRoles.get(environmentId) ?? null; },
547
+ async findHostedSsoIdentity(environmentId, authority, subject) {
548
+ const row = source().hostedSsoIdentities.get(JSON.stringify([environmentId, authority, subject]));
549
+ return row ? clone(row) : null;
550
+ },
551
+ async listHostedSsoIdentityIds(environmentId) {
552
+ return [...new Set([...source().hostedSsoIdentities.values()].filter((row) => row.environmentId === environmentId).map((row) => row.identityId))];
553
+ },
554
+ async saveHostedSsoIdentity(row) { return tx(() => saveHostedSsoLink(source(), row)); },
555
+ async setDirectorySignupRole(environmentId, roleId) {
556
+ tx(() => {
557
+ const maps = source();
558
+ if (roleId === null)
559
+ maps.signupRoles.delete(environmentId);
560
+ else {
561
+ if (maps.productRoles.get(roleId)?.environmentId !== environmentId)
562
+ fail("not_found", "The role is unavailable in this environment.");
563
+ maps.signupRoles.set(environmentId, roleId);
59
564
  }
60
- save(maps.identities, { ...row, metadata: clone(row.metadata), emailVerifiedAt: asTimeOrNull(row.emailVerifiedAt), createdAt: asTime(row.createdAt), updatedAt: asTime(row.updatedAt) });
61
565
  });
62
566
  },
63
567
  async getDirectoryIdentity(id) {
@@ -66,10 +570,12 @@ export function bindDirectoryMemory(source, users, tx) {
66
570
  },
67
571
  async listDirectoryIdentities(environmentId) { return rows(source().identities, (row) => row.environmentId === environmentId); },
68
572
  async findDirectoryIdentityByEmail(environmentId, email) {
69
- return rows(source().identities, (row) => row.environmentId === environmentId && row.email?.toLowerCase() === email.toLowerCase())[0] ?? null;
573
+ const identity = signInIdentity(source().identities.values(), environmentId, email);
574
+ return identity ? clone(identity) : null;
70
575
  },
71
576
  async saveDirectoryMembership(row) {
72
577
  tx(() => {
578
+ requireOrganizationScope(row.environmentId);
73
579
  const maps = source();
74
580
  const clash = [...maps.directoryMemberships.values()].find((item) => item.identityId === row.identityId && item.organizationId === row.organizationId && item.id !== row.id);
75
581
  if (clash)
@@ -77,8 +583,159 @@ export function bindDirectoryMemory(source, users, tx) {
77
583
  save(maps.directoryMemberships, { ...row, createdAt: asTime(row.createdAt) });
78
584
  });
79
585
  },
80
- async deleteDirectoryMembership(id) { tx(() => remove(source().directoryMemberships, id)); },
586
+ async deleteDirectoryMembership(id) {
587
+ tx(() => {
588
+ const memberships = source().directoryMemberships;
589
+ const membership = memberships.get(id);
590
+ if (!membership)
591
+ fail("not_found", "Membership not found.");
592
+ if (membership.relation === "owner" && ![...memberships.values()].some((item) => item.id !== id && item.environmentId === membership.environmentId && item.organizationId === membership.organizationId && item.relation === "owner")) {
593
+ fail("last_owner", "An organization must keep an owner.");
594
+ }
595
+ memberships.delete(id);
596
+ });
597
+ },
81
598
  async listDirectoryMemberships(environmentId) { return rows(source().directoryMemberships, (row) => row.environmentId === environmentId); },
599
+ async createDirectoryWorkspace(workspace, owner, organizationMembership) {
600
+ tx(() => {
601
+ const maps = source();
602
+ if (organizationMembership) {
603
+ requireOrganizationScope(organizationMembership.environmentId);
604
+ const clash = [...maps.directoryMemberships.values()].find((item) => item.id !== organizationMembership.id
605
+ && item.identityId === organizationMembership.identityId && item.organizationId === organizationMembership.organizationId);
606
+ if (clash)
607
+ fail("duplicate", "Duplicate key.");
608
+ save(maps.directoryMemberships, { ...organizationMembership, createdAt: asTime(organizationMembership.createdAt) });
609
+ }
610
+ assertWorkspaceScope(workspace);
611
+ if (maps.workspaces.has(workspace.id))
612
+ fail("duplicate", "Duplicate workspace.");
613
+ if (owner.relation !== "owner" || !workspace.name.trim() ||
614
+ (workspace.status !== "active" && workspace.status !== "disabled"))
615
+ fail("conflict", "Invalid workspace or owner.");
616
+ save(maps.workspaces, { ...workspace, createdAt: asTime(workspace.createdAt), updatedAt: asTime(workspace.updatedAt) });
617
+ addWorkspaceMember(workspace, owner);
618
+ });
619
+ },
620
+ async getDirectoryWorkspace(environmentId, id) {
621
+ const workspace = source().workspaces.get(id);
622
+ return workspace?.environmentId === environmentId ? clone(workspace) : null;
623
+ },
624
+ async listDirectoryWorkspaces(environmentId) {
625
+ return rows(source().workspaces, (workspace) => workspace.environmentId === environmentId)
626
+ .sort((left, right) => left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id));
627
+ },
628
+ async updateDirectoryWorkspace(environmentId, id, patch) {
629
+ return tx(() => {
630
+ const maps = source();
631
+ const workspace = maps.workspaces.get(id);
632
+ if (workspace?.environmentId !== environmentId)
633
+ return null;
634
+ const name = patch.name ?? workspace.name;
635
+ const status = patch.status ?? workspace.status;
636
+ if (!name.trim() || (status !== "active" && status !== "disabled"))
637
+ fail("conflict", "Invalid workspace name or status.");
638
+ if (patch.status === "active")
639
+ assertWorkspaceScope(workspace);
640
+ const updated = { ...workspace, name, status, updatedAt: asTime(patch.updatedAt) };
641
+ save(maps.workspaces, updated);
642
+ return updated;
643
+ });
644
+ },
645
+ async addDirectoryWorkspaceMembership(row) {
646
+ tx(() => {
647
+ const workspace = source().workspaces.get(row.workspaceId);
648
+ if (workspace?.environmentId !== row.environmentId || workspace.status !== "active")
649
+ fail("not_found", "Workspace not found.");
650
+ assertWorkspaceScope(workspace);
651
+ addWorkspaceMember(workspace, row);
652
+ });
653
+ },
654
+ async listDirectoryWorkspaceMemberships(environmentId) {
655
+ return rows(source().workspaceMemberships, (row) => row.environmentId === environmentId);
656
+ },
657
+ async removeDirectoryWorkspaceMembership(environmentId, workspaceId, membershipId) {
658
+ tx(() => {
659
+ const { workspaceMemberships } = source();
660
+ const membership = workspaceMemberships.get(membershipId);
661
+ if (membership?.environmentId !== environmentId || membership.workspaceId !== workspaceId)
662
+ fail("not_found", "Workspace membership not found.");
663
+ if (membership.relation === "owner" && ![...workspaceMemberships.values()]
664
+ .some((row) => row.workspaceId === workspaceId && row.relation === "owner" && row.id !== membershipId)) {
665
+ fail("last_owner", "A workspace must keep an owner.");
666
+ }
667
+ const ownerRole = [...source().productRoles.values()].find((role) => role.environmentId === environmentId && role.ownerAccess);
668
+ if (membership.roleId && ownerRole && membership.roleId === ownerRole.id && ![...workspaceMemberships.values()]
669
+ .some((row) => row.workspaceId === workspaceId && row.id !== membershipId && row.roleId === ownerRole.id)) {
670
+ fail("last_owner_access", "Assign owner access to another person in this scope first.");
671
+ }
672
+ clearAccessChecks(environmentId, membership.identityId, workspaceId, null);
673
+ workspaceMemberships.delete(membershipId);
674
+ });
675
+ },
676
+ async applyDirectoryAccess(request) {
677
+ return tx(() => request.workspaceId ? applyWorkspaceGrant(request) : applyBindingGrant(request));
678
+ },
679
+ async clearDirectoryProductRole(input) {
680
+ return tx(() => {
681
+ const maps = source();
682
+ if (input.membershipId) {
683
+ const membership = maps.workspaceMemberships.get(input.membershipId);
684
+ if (!membership || membership.environmentId !== input.environmentId)
685
+ fail("not_found", "Workspace membership not found.");
686
+ const previousRoleId = membership.roleId ?? null;
687
+ if (previousRoleId && previousRoleId === input.ownerRoleId && ![...maps.workspaceMemberships.values()].some((row) => row.workspaceId === membership.workspaceId && row.id !== membership.id && row.roleId === input.ownerRoleId)) {
688
+ fail("last_owner_access", "Assign owner access to another person in this scope first.");
689
+ }
690
+ if (!previousRoleId)
691
+ return { cleared: false, previousRoleId: null, identityId: membership.identityId, workspaceId: membership.workspaceId, organizationId: null };
692
+ delete membership.roleId;
693
+ clearAccessChecks(input.environmentId, membership.identityId, membership.workspaceId, null);
694
+ return { cleared: true, previousRoleId, identityId: membership.identityId, workspaceId: membership.workspaceId, organizationId: null };
695
+ }
696
+ const binding = input.bindingId ? maps.bindings.get(input.bindingId) : undefined;
697
+ if (!binding || binding.environmentId !== input.environmentId)
698
+ fail("not_found", "Role binding not found.");
699
+ if (binding.roleId === input.ownerRoleId && ![...maps.bindings.values()].some((item) => item.id !== binding.id && item.environmentId === binding.environmentId
700
+ && item.subjectType === "identity" && (item.organizationId ?? null) === (binding.organizationId ?? null) && item.resource === null && item.roleId === input.ownerRoleId)) {
701
+ fail("last_owner_access", "Assign owner access to another person in this scope first.");
702
+ }
703
+ maps.bindings.delete(binding.id);
704
+ clearAccessChecks(binding.environmentId, binding.subjectId, null, binding.organizationId ?? null);
705
+ return { cleared: true, previousRoleId: binding.roleId, identityId: binding.subjectId, workspaceId: null, organizationId: binding.organizationId ?? null };
706
+ });
707
+ },
708
+ async saveDirectoryAccessCheck(row) {
709
+ tx(() => {
710
+ const maps = source();
711
+ const identity = maps.identities.get(row.identityId);
712
+ if (identity?.environmentId !== row.environmentId)
713
+ fail("not_found", "That person is not in this environment.");
714
+ for (const check of [...maps.accessChecks.values()]) {
715
+ if (check.environmentId === row.environmentId && check.identityId === row.identityId
716
+ && check.workspaceId === row.workspaceId && check.organizationId === row.organizationId)
717
+ maps.accessChecks.delete(check.id);
718
+ }
719
+ save(maps.accessChecks, { ...row, createdAt: asTime(row.createdAt) });
720
+ });
721
+ },
722
+ async listDirectoryAccessChecks(environmentId, identityId) {
723
+ return rows(source().accessChecks, (row) => row.environmentId === environmentId && row.identityId === identityId);
724
+ },
725
+ async getDirectoryOnboardingResponse(environmentId, target, subjectId) {
726
+ const response = source().onboardingResponses.get(JSON.stringify([environmentId, target, subjectId]));
727
+ return response ? clone(response) : null;
728
+ },
729
+ async saveDirectoryOnboardingResponse(row) {
730
+ tx(() => {
731
+ const maps = source();
732
+ const subject = row.target === "workspace" ? maps.workspaces.get(row.subjectId) : maps.identities.get(row.subjectId);
733
+ if (subject?.environmentId !== row.environmentId || (row.target !== "workspace" && (!("kind" in subject) || subject.kind !== row.target))) {
734
+ fail("not_found", "Onboarding subject not found.");
735
+ }
736
+ maps.onboardingResponses.set(JSON.stringify([row.environmentId, row.target, row.subjectId]), clone({ ...row, updatedAt: asTime(row.updatedAt) }));
737
+ });
738
+ },
82
739
  async saveProductPermission(row) {
83
740
  tx(() => {
84
741
  const maps = source();
@@ -91,10 +748,74 @@ export function bindDirectoryMemory(source, users, tx) {
91
748
  async deleteProductPermission(id) { tx(() => remove(source().permissions, id)); },
92
749
  async listProductPermissions(environmentId) { return rows(source().permissions, (row) => row.environmentId === environmentId); },
93
750
  async saveProductRole(row) {
94
- tx(() => save(source().productRoles, { ...row, permissions: [...row.permissions], inherits: [...row.inherits], createdAt: asTime(row.createdAt) }));
751
+ tx(() => {
752
+ const roles = source().productRoles;
753
+ const current = roles.get(row.id);
754
+ const next = { ...row, catalogRoleId: current ? current.catalogRoleId ?? null : row.catalogRoleId ?? null,
755
+ permissions: [...row.permissions], inherits: [...row.inherits], ownerAccess: row.ownerAccess === true, createdAt: asTime(row.createdAt) };
756
+ if (next.ownerAccess && [...roles.values()].some((role) => role.environmentId === next.environmentId && role.id !== next.id && role.ownerAccess)) {
757
+ fail("conflict", "This environment already has an owner access role.");
758
+ }
759
+ assertAvailableCatalogLink(next);
760
+ save(roles, next);
761
+ });
762
+ },
763
+ async deleteProductRole(id) {
764
+ tx(() => {
765
+ const maps = source();
766
+ const role = maps.productRoles.get(id);
767
+ if (role && maps.signupRoles.get(role.environmentId) === id)
768
+ maps.signupRoles.delete(role.environmentId);
769
+ remove(maps.productRoles, id);
770
+ for (const membership of maps.workspaceMemberships.values()) {
771
+ if (membership.roleId === id)
772
+ delete membership.roleId;
773
+ }
774
+ for (const link of maps.featureAssignments.values()) {
775
+ if (link.targetType === "role" && link.targetId === id)
776
+ maps.featureAssignments.delete(link.id);
777
+ }
778
+ });
95
779
  },
96
- async deleteProductRole(id) { tx(() => remove(source().productRoles, id)); },
97
780
  async listProductRoles(environmentId) { return rows(source().productRoles, (row) => row.environmentId === environmentId); },
781
+ async insertTenantProductRole(row) {
782
+ tx(() => saveTenantRole({ ...row, createdAt: asTime(row.createdAt) }));
783
+ },
784
+ async listTenantProductRoles(orgId) { return rows(source().tenantProductRoles, (row) => row.orgId === orgId); },
785
+ async updateTenantProductRole(orgId, id, name, description) {
786
+ return tx(() => {
787
+ const current = source().tenantProductRoles.get(id);
788
+ if (!current || current.orgId !== orgId)
789
+ fail("not_found", "Catalog role not found.");
790
+ const updated = { ...current, name, description };
791
+ saveTenantRole(updated);
792
+ return clone(updated);
793
+ });
794
+ },
795
+ async deleteTenantProductRole(orgId, id) {
796
+ tx(() => {
797
+ const maps = source();
798
+ if (maps.tenantProductRoles.get(id)?.orgId !== orgId)
799
+ fail("not_found", "Catalog role not found.");
800
+ if ([...maps.productRoles.values()].some((item) => item.catalogRoleId === id))
801
+ fail("conflict", "This catalog role is still linked.");
802
+ remove(maps.tenantProductRoles, id);
803
+ });
804
+ },
805
+ async setProductRoleCatalogLink(environmentId, roleId, catalogRoleId, expectedCatalogRoleId) {
806
+ return tx(() => {
807
+ const roles = source().productRoles;
808
+ const current = roles.get(roleId);
809
+ if (!current || current.environmentId !== environmentId)
810
+ fail("not_found", "Role not found.");
811
+ if ((current.catalogRoleId ?? null) !== expectedCatalogRoleId)
812
+ fail("conflict", "The role link changed.");
813
+ const next = { ...current, catalogRoleId };
814
+ assertAvailableCatalogLink(next);
815
+ save(roles, next);
816
+ return clone(next);
817
+ });
818
+ },
98
819
  async saveDirectoryGroup(row) { tx(() => save(source().groups, { ...row, createdAt: asTime(row.createdAt) })); },
99
820
  async deleteDirectoryGroup(id) { tx(() => remove(source().groups, id)); },
100
821
  async listDirectoryGroups(environmentId) { return rows(source().groups, (row) => row.environmentId === environmentId); },
@@ -109,8 +830,31 @@ export function bindDirectoryMemory(source, users, tx) {
109
830
  },
110
831
  async deleteGroupMember(id) { tx(() => remove(source().groupMembers, id)); },
111
832
  async listGroupMembers(environmentId) { return rows(source().groupMembers, (row) => row.environmentId === environmentId); },
112
- async saveRoleBinding(row) { tx(() => save(source().bindings, { ...row, createdAt: asTime(row.createdAt) })); },
113
- async deleteRoleBinding(id) { tx(() => remove(source().bindings, id)); },
833
+ async saveRoleBinding(row) {
834
+ tx(() => {
835
+ if (row.subjectType === "organization" || row.organizationId !== null)
836
+ requireOrganizationScope(row.environmentId);
837
+ save(source().bindings, { ...row, createdAt: asTime(row.createdAt) });
838
+ });
839
+ },
840
+ async deleteRoleBinding(id) {
841
+ tx(() => {
842
+ const maps = source();
843
+ const binding = maps.bindings.get(id);
844
+ if (!binding)
845
+ fail("not_found", "Record not found.");
846
+ const ownerRole = [...maps.productRoles.values()].find((role) => role.environmentId === binding.environmentId && role.ownerAccess);
847
+ if (ownerRole && binding.roleId === ownerRole.id && binding.subjectType === "identity" && binding.resource === null
848
+ && ![...maps.bindings.values()].some((item) => item.id !== binding.id && item.environmentId === binding.environmentId
849
+ && item.subjectType === "identity" && (item.organizationId ?? null) === (binding.organizationId ?? null)
850
+ && item.resource === null && item.roleId === ownerRole.id)) {
851
+ fail("last_owner_access", "Assign owner access to another person in this scope first.");
852
+ }
853
+ if (binding.subjectType === "identity")
854
+ clearAccessChecks(binding.environmentId, binding.subjectId, null, binding.organizationId);
855
+ maps.bindings.delete(id);
856
+ });
857
+ },
114
858
  async listRoleBindings(environmentId) { return rows(source().bindings, (row) => row.environmentId === environmentId); },
115
859
  async saveFeatureDefinition(row) {
116
860
  tx(() => {
@@ -118,46 +862,374 @@ export function bindDirectoryMemory(source, users, tx) {
118
862
  const clash = [...maps.features.values()].find((item) => item.environmentId === row.environmentId && item.key === row.key && item.id !== row.id);
119
863
  if (clash)
120
864
  fail("duplicate", "Duplicate key.");
121
- save(maps.features, { ...row, config: clone(row.config), createdAt: asTime(row.createdAt) });
865
+ const kind = row.kind ?? maps.features.get(row.id)?.kind ?? "feature";
866
+ save(maps.features, { ...row, kind, config: clone(row.config), createdAt: asTime(row.createdAt) });
867
+ });
868
+ },
869
+ async updateFeatureDefinition(environmentId, id, changes) {
870
+ return tx(() => {
871
+ const features = source().features;
872
+ const current = features.get(id);
873
+ if (!current || current.environmentId !== environmentId)
874
+ fail("not_found", "Feature definition not found.");
875
+ const updated = { ...current, enabled: changes.enabled ?? current.enabled, config: changes.config ?? current.config };
876
+ save(features, updated);
877
+ return clone(updated);
878
+ });
879
+ },
880
+ async deleteFeatureDefinition(id) {
881
+ tx(() => {
882
+ const maps = source();
883
+ remove(maps.features, id);
884
+ for (const link of maps.featureAssignments.values()) {
885
+ if (link.featureId === id)
886
+ maps.featureAssignments.delete(link.id);
887
+ }
122
888
  });
123
889
  },
124
- async deleteFeatureDefinition(id) { tx(() => remove(source().features, id)); },
125
890
  async listFeatureDefinitions(environmentId) { return rows(source().features, (row) => row.environmentId === environmentId); },
126
- async saveFeatureAssignment(row) { tx(() => save(source().featureAssignments, { ...row, config: clone(row.config), createdAt: asTime(row.createdAt) })); },
891
+ async saveFeatureAssignment(row) {
892
+ tx(() => {
893
+ if (row.targetType === "organization")
894
+ requireOrganizationScope(row.environmentId);
895
+ const maps = source();
896
+ if (maps.features.get(row.featureId)?.environmentId !== row.environmentId)
897
+ fail("conflict", "Feature definition not found in this environment.");
898
+ if (row.targetType === "role") {
899
+ if (!row.targetId || maps.productRoles.get(row.targetId)?.environmentId !== row.environmentId)
900
+ fail("conflict", "Role not found in this environment.");
901
+ const duplicate = [...maps.featureAssignments.values()].some((item) => item.id !== row.id && item.targetType === "role"
902
+ && item.featureId === row.featureId && item.targetId === row.targetId);
903
+ if (duplicate)
904
+ fail("duplicate", "This definition is already linked to the role.");
905
+ }
906
+ save(maps.featureAssignments, { ...row, config: clone(row.config), createdAt: asTime(row.createdAt) });
907
+ });
908
+ },
127
909
  async deleteFeatureAssignment(id) { tx(() => remove(source().featureAssignments, id)); },
128
910
  async listFeatureAssignments(environmentId) { return rows(source().featureAssignments, (row) => row.environmentId === environmentId); },
129
- async saveAppWaitlist(row) {
911
+ async insertAppWaitlist(row) {
912
+ return tx(() => {
913
+ const list = source().appWaitlist;
914
+ if ([...list.values()].some((item) => item.environmentId === row.environmentId && item.email.toLowerCase() === row.email.toLowerCase()))
915
+ return false;
916
+ save(list, { ...row, createdAt: asTime(row.createdAt) });
917
+ source().waitlistConfirmations.set(`app:${row.id}`, { claimedAt: null });
918
+ return true;
919
+ });
920
+ },
921
+ async saveAppWaitlist(row, challenge) {
130
922
  tx(() => {
131
923
  const maps = source();
132
924
  const clash = [...maps.appWaitlist.values()].find((item) => item.environmentId === row.environmentId && item.email.toLowerCase() === row.email.toLowerCase() && item.id !== row.id);
133
925
  if (clash)
134
926
  fail("duplicate_email", "Email already exists.");
135
- save(maps.appWaitlist, { ...row, createdAt: asTime(row.createdAt) });
927
+ if (row.invitation && !invitationIsAvailable(row))
928
+ fail("conflict", "The invited workspace or role is unavailable.");
929
+ const previous = maps.appWaitlist.get(row.id);
930
+ if (challenge && previous?.tokenHash && previous.tokenHash !== challenge.tokenHash) {
931
+ const previousChallenge = [...maps.directoryChallenges.values()].find((item) => item.environmentId === row.environmentId && item.tokenHash === previous.tokenHash);
932
+ if (previousChallenge && !previousChallenge.usedAt)
933
+ previousChallenge.usedAt = asTime(challenge.createdAt);
934
+ }
935
+ save(maps.appWaitlist, { ...row, createdAt: asTime(row.createdAt), ...(row.auditId ? { auditId: row.auditId } : {}), ...(row.revokedAt ? { revokedAt: asTime(row.revokedAt) } : {}) });
936
+ if (challenge) {
937
+ if (!activeApplicationForEnvironment(row.environmentId, true))
938
+ fail("not_found", "Application environment not found.");
939
+ addChallenge(maps, challenge);
940
+ }
941
+ });
942
+ },
943
+ async acceptDirectoryWorkspaceInvitation(identityId, at) {
944
+ return tx(() => {
945
+ const identity = source().identities.get(identityId);
946
+ return identity ? acceptWorkspaceInvitation(identity, asTime(at)) : false;
947
+ });
948
+ },
949
+ async acceptDirectoryWorkspaceInvitationByToken(environmentId, tokenHash, at) {
950
+ return tx(() => {
951
+ const maps = source();
952
+ const challenge = [...maps.directoryChallenges.values()].find((row) => row.tokenHash === tokenHash && row.environmentId === environmentId && row.purpose === "admit");
953
+ const identity = challenge && signInIdentity(maps.identities.values(), environmentId, challenge.email);
954
+ const stamp = asTime(at);
955
+ if (!identity || !acceptWorkspaceInvitation(identity, stamp, tokenHash))
956
+ return false;
957
+ identity.emailProofAt = stamp;
958
+ identity.updatedAt = stamp;
959
+ return true;
960
+ });
961
+ },
962
+ async completeDirectoryPasswordSetup(environmentId, tokenHash, passwordHash, at) {
963
+ return tx(() => {
964
+ const maps = source();
965
+ const stamp = asTime(at);
966
+ const challenge = [...maps.directoryChallenges.values()].find((row) => row.tokenHash === tokenHash && row.environmentId === environmentId && row.purpose === "admit");
967
+ if (!challenge || challenge.usedAt || isExpired(challenge.expiresAt, stamp))
968
+ return false;
969
+ const identity = signInIdentity(maps.identities.values(), environmentId, challenge.email);
970
+ if (!identity || identity.status !== "active" || (identity.kind !== "user" && identity.kind !== "account") || identity.passwordHash)
971
+ return false;
972
+ const invite = [...maps.appWaitlist.values()].find((row) => row.environmentId === environmentId && row.email.toLowerCase() === challenge.email.toLowerCase()
973
+ && row.status === "invited");
974
+ if (invite && invite.tokenHash !== tokenHash)
975
+ return false;
976
+ if (invite?.invitation?.delivery === "link")
977
+ return false;
978
+ if (invite?.invitation && !invitationIsAvailable(invite))
979
+ return false;
980
+ identity.passwordHash = passwordHash;
981
+ identity.emailVerifiedAt = identity.emailVerifiedAt ?? stamp;
982
+ identity.emailProofAt = stamp;
983
+ identity.updatedAt = stamp;
984
+ if (invite?.invitation) {
985
+ if (!applyStoredInvitation(invite, challenge, identity, stamp))
986
+ fail("conflict", "The invitation could not be applied.");
987
+ return true;
988
+ }
989
+ challenge.usedAt = stamp;
990
+ if (invite)
991
+ invite.status = "admitted";
992
+ return true;
993
+ });
994
+ },
995
+ async readDirectoryInvitation(environmentId, tokenHash, at) {
996
+ const invite = [...source().appWaitlist.values()].find((row) => row.environmentId === environmentId && row.tokenHash === tokenHash);
997
+ if (!invite)
998
+ return null;
999
+ const challenge = [...source().directoryChallenges.values()].find((row) => row.environmentId === environmentId && row.tokenHash === tokenHash && row.purpose === "admit") ?? null;
1000
+ return invitationPreview(invite, challenge, asTime(at));
1001
+ },
1002
+ async listDirectoryInvitations(environmentId, at) {
1003
+ const stamp = asTime(at);
1004
+ return [...source().appWaitlist.values()].flatMap((row) => {
1005
+ if (row.environmentId !== environmentId || (!row.invitation && row.status !== "revoked"))
1006
+ return [];
1007
+ const challenge = row.tokenHash ? [...source().directoryChallenges.values()].find((item) => item.environmentId === environmentId && item.tokenHash === row.tokenHash && item.purpose === "admit") ?? null : null;
1008
+ const preview = invitationPreview(row, challenge, stamp);
1009
+ return preview ? [preview] : [];
1010
+ });
1011
+ },
1012
+ async setDirectoryInvitationAudit(environmentId, id, auditId) {
1013
+ tx(() => {
1014
+ const row = source().appWaitlist.get(id);
1015
+ if (!row || row.environmentId !== environmentId)
1016
+ fail("not_found", "Invitation not found.");
1017
+ row.auditId = auditId;
1018
+ });
1019
+ },
1020
+ async revokeDirectoryInvitation(environmentId, id, at) {
1021
+ return tx(() => {
1022
+ const invite = source().appWaitlist.get(id);
1023
+ if (!invite || invite.environmentId !== environmentId)
1024
+ return "missing";
1025
+ const challenge = invite.tokenHash ? [...source().directoryChallenges.values()].find((item) => item.environmentId === environmentId && item.tokenHash === invite.tokenHash && item.purpose === "admit") ?? null : null;
1026
+ if (invitationLifecycle(invite.status, challenge, asTime(at)) !== "pending")
1027
+ return "closed";
1028
+ invite.status = "revoked";
1029
+ invite.revokedAt = asTime(at);
1030
+ if (challenge && !challenge.usedAt)
1031
+ challenge.usedAt = invite.revokedAt;
1032
+ return "revoked";
1033
+ });
1034
+ },
1035
+ async redeemDirectoryInvitation(input) {
1036
+ return tx(() => {
1037
+ const maps = source();
1038
+ const stamp = asTime(input.at);
1039
+ const challenge = [...maps.directoryChallenges.values()].find((row) => row.environmentId === input.environmentId && row.tokenHash === input.tokenHash && row.purpose === "admit");
1040
+ const invite = [...maps.appWaitlist.values()].find((row) => row.environmentId === input.environmentId && row.tokenHash === input.tokenHash);
1041
+ if (!invite?.invitation || invite.invitation.delivery !== "link" || !challenge)
1042
+ return { outcome: "unavailable" };
1043
+ const identity = maps.identities.get(input.identityId);
1044
+ if (!identity || identity.environmentId !== input.environmentId || identity.appId !== invite.appId || identity.status !== "active")
1045
+ return { outcome: "unavailable" };
1046
+ if ((identity.kind !== "user" && identity.kind !== "account") || !identity.email
1047
+ || identity.email.toLowerCase() !== invite.email.toLowerCase() || identity.email.toLowerCase() !== challenge.email.toLowerCase()) {
1048
+ return { outcome: "recipient" };
1049
+ }
1050
+ const status = invitationLifecycle(invite.status, challenge, stamp);
1051
+ if (status === "accepted") {
1052
+ const current = savedInvitationGrant(invite, identity.id);
1053
+ return { outcome: "existing", identityId: identity.id, roleId: current.roleId, membershipId: current.membershipId, bindingId: current.bindingId };
1054
+ }
1055
+ if (status !== "pending" || !invitationIsAvailable(invite))
1056
+ return { outcome: "unavailable" };
1057
+ if (!identity.emailVerifiedAt && !identity.emailProofAt)
1058
+ return { outcome: "unverified" };
1059
+ const ids = { membershipId: input.newMembershipId, bindingId: input.newBindingId, organizationMembershipId: input.newOrganizationMembershipId };
1060
+ const saved = invite.invitation.workspaceId
1061
+ ? applyWorkspaceGrant(invitationGrantRequest(invite, identity.id, stamp, ids))
1062
+ : applyBindingGrant(invitationGrantRequest(invite, identity.id, stamp, ids));
1063
+ challenge.usedAt = stamp;
1064
+ invite.status = "admitted";
1065
+ delete invite.pendingWorkspaceIdentityId;
1066
+ return { outcome: "applied", identityId: identity.id, roleId: saved.roleId ?? invite.invitation.roleId, membershipId: saved.membership?.id ?? null, bindingId: saved.binding?.id ?? null };
136
1067
  });
137
1068
  },
138
1069
  async listAppWaitlist(environmentId) { return rows(source().appWaitlist, (row) => row.environmentId === environmentId); },
139
1070
  async findAppWaitlist(environmentId, email) {
140
1071
  return rows(source().appWaitlist, (row) => row.environmentId === environmentId && row.email.toLowerCase() === email.toLowerCase())[0] ?? null;
141
1072
  },
142
- async insertDirectoryChallenge(row) {
1073
+ async claimWaitlistConfirmation(list, entryId, at, staleAt) {
1074
+ return tx(() => {
1075
+ const maps = source();
1076
+ const row = (list === "app" ? maps.appWaitlist : maps.platformWaitlist).get(entryId);
1077
+ const key = `${list}:${entryId}`;
1078
+ const pending = maps.waitlistConfirmations.get(key);
1079
+ if (row?.status !== "waiting" || !pending || (pending.claimedAt !== null && pending.claimedAt > asTime(staleAt)))
1080
+ return false;
1081
+ maps.waitlistConfirmations.set(key, { claimedAt: asTime(at) });
1082
+ return true;
1083
+ });
1084
+ },
1085
+ async finishWaitlistConfirmation(list, entryId, claimedAt, accepted) {
1086
+ tx(() => {
1087
+ const pending = source().waitlistConfirmations;
1088
+ const key = `${list}:${entryId}`;
1089
+ if (pending.get(key)?.claimedAt !== asTime(claimedAt))
1090
+ return;
1091
+ if (accepted)
1092
+ pending.delete(key);
1093
+ else
1094
+ pending.set(key, { claimedAt: null });
1095
+ });
1096
+ },
1097
+ async insertDirectoryChallenge(row, delivery) {
143
1098
  tx(() => {
1099
+ if (row.environmentId !== "platform" && !activeApplicationForEnvironment(row.environmentId, true)) {
1100
+ fail("not_found", "Application environment not found.");
1101
+ }
144
1102
  const maps = source();
145
- if ([...maps.directoryChallenges.values()].some((item) => item.tokenHash === row.tokenHash))
146
- fail("duplicate", "Duplicate key.");
147
- save(maps.directoryChallenges, { ...row, expiresAt: asTime(row.expiresAt), usedAt: asTimeOrNull(row.usedAt), createdAt: asTime(row.createdAt) });
1103
+ addChallenge(maps, row);
1104
+ if (delivery) {
1105
+ const identity = maps.identities.get(row.identityId);
1106
+ if (!identity || identity.environmentId !== row.environmentId)
1107
+ fail("conflict", "Notification scope changed.");
1108
+ insertNotification(identity, delivery);
1109
+ }
148
1110
  });
149
1111
  },
150
- async takeDirectoryChallenge(tokenHash, at) {
1112
+ async insertDirectoryChallengeWithCooldown(row, after, delivery) {
1113
+ return tx(() => {
1114
+ const maps = source();
1115
+ if (!activeApplicationForEnvironment(row.environmentId))
1116
+ return false;
1117
+ const identity = maps.identities.get(row.identityId);
1118
+ if (identity?.status !== "active" || identity.environmentId !== row.environmentId || identity.email !== row.email)
1119
+ return false;
1120
+ const cutoff = asTime(after);
1121
+ const recent = [...maps.directoryChallenges.values()].some((item) => item.environmentId === row.environmentId && item.identityId === row.identityId && item.purpose === row.purpose && item.createdAt > cutoff);
1122
+ if (recent)
1123
+ return false;
1124
+ addChallenge(maps, row);
1125
+ insertNotification(identity, delivery);
1126
+ return true;
1127
+ });
1128
+ },
1129
+ async takeDirectoryChallenge(tokenHash, at, scope) {
151
1130
  return tx(() => {
152
1131
  const maps = source();
153
1132
  const stamp = asTime(at);
154
1133
  const row = [...maps.directoryChallenges.values()].find((item) => item.tokenHash === tokenHash);
155
- if (!row || row.usedAt || isExpired(row.expiresAt, stamp))
1134
+ if (!row || row.usedAt || isExpired(row.expiresAt, stamp)
1135
+ || (scope?.environmentId && row.environmentId !== scope.environmentId) || (scope?.purpose && row.purpose !== scope.purpose))
1136
+ return null;
1137
+ if (row.environmentId !== "platform" && !activeApplicationForEnvironment(row.environmentId, true))
156
1138
  return null;
157
1139
  row.usedAt = stamp;
158
1140
  return clone(row);
159
1141
  });
160
1142
  },
1143
+ async verifyDirectoryEmail(tokenHash, at, environmentId) {
1144
+ return tx(() => {
1145
+ const maps = source();
1146
+ const stamp = asTime(at);
1147
+ const row = [...maps.directoryChallenges.values()].find((item) => item.tokenHash === tokenHash);
1148
+ if (!row || row.purpose !== "verify" || row.usedAt || isExpired(row.expiresAt, stamp) || (environmentId && row.environmentId !== environmentId))
1149
+ return null;
1150
+ const identity = maps.identities.get(row.identityId);
1151
+ if (!identity || !activeApplicationForEnvironment(row.environmentId, true) || identity.environmentId !== row.environmentId || identity.email?.toLowerCase() !== row.email.toLowerCase() || identity.status !== "active")
1152
+ return null;
1153
+ row.usedAt = stamp;
1154
+ recordEmailProof(identity, stamp);
1155
+ acceptWorkspaceInvitation(identity, stamp);
1156
+ return clone(identity);
1157
+ });
1158
+ },
161
1159
  };
162
1160
  }
1161
+ function directoryRecordId(prefix) {
1162
+ return `${prefix}_${randomBytes(16).toString("base64url")}`;
1163
+ }
1164
+ export function repairDirectoryStructure(maps, environmentIds, app, model, at) {
1165
+ const stamp = asTime(at);
1166
+ const hasOrganizations = directoryHasOrganizations(model);
1167
+ const hasWorkspaces = directoryHasWorkspaces(model);
1168
+ const repair = { organizations: 0, workspaces: 0 };
1169
+ const environments = [...environmentIds].sort();
1170
+ for (const environmentId of environments) {
1171
+ const people = [...maps.identities.values()].filter((identity) => identity.appId === app.id && identity.environmentId === environmentId
1172
+ && (identity.kind === "user" || identity.kind === "account"))
1173
+ .sort((left, right) => left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id));
1174
+ if (hasOrganizations) {
1175
+ for (const person of people) {
1176
+ if ([...maps.directoryMemberships.values()].some((item) => item.environmentId === environmentId && item.identityId === person.id))
1177
+ continue;
1178
+ const organizationId = directoryRecordId("idn");
1179
+ const membershipId = directoryRecordId("dms");
1180
+ maps.identities.set(organizationId, {
1181
+ id: organizationId, appId: app.id, environmentId, orgId: app.orgId, kind: "organization", email: null, passwordHash: null,
1182
+ displayName: person.displayName, status: "active", emailVerifiedAt: null, metadata: {}, createdAt: stamp, updatedAt: stamp,
1183
+ });
1184
+ maps.directoryMemberships.set(membershipId, {
1185
+ id: membershipId, environmentId, identityId: person.id, organizationId, relation: "owner", createdAt: stamp,
1186
+ });
1187
+ repair.organizations += 1;
1188
+ }
1189
+ if (model === "organizations-and-workspaces") {
1190
+ const orphans = [...maps.workspaces.values()].filter((workspace) => workspace.appId === app.id && workspace.environmentId === environmentId
1191
+ && workspace.organizationId === null)
1192
+ .sort((left, right) => left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id));
1193
+ for (const workspace of orphans) {
1194
+ const organizationId = directoryRecordId("idn");
1195
+ maps.identities.set(organizationId, {
1196
+ id: organizationId, appId: app.id, environmentId, orgId: app.orgId, kind: "organization", email: null, passwordHash: null,
1197
+ displayName: workspace.name, status: "active", emailVerifiedAt: null, metadata: {}, createdAt: stamp, updatedAt: stamp,
1198
+ });
1199
+ for (const owner of [...maps.workspaceMemberships.values()].filter((item) => item.workspaceId === workspace.id && item.relation === "owner")) {
1200
+ if ([...maps.directoryMemberships.values()].some((item) => item.environmentId === environmentId && item.identityId === owner.identityId && item.organizationId === organizationId))
1201
+ continue;
1202
+ const membershipId = directoryRecordId("dms");
1203
+ maps.directoryMemberships.set(membershipId, {
1204
+ id: membershipId, environmentId, identityId: owner.identityId, organizationId, relation: "member", createdAt: stamp,
1205
+ });
1206
+ }
1207
+ maps.workspaces.set(workspace.id, { ...workspace, organizationId, updatedAt: stamp });
1208
+ repair.organizations += 1;
1209
+ }
1210
+ }
1211
+ }
1212
+ if (!hasWorkspaces)
1213
+ continue;
1214
+ for (const person of people) {
1215
+ if ([...maps.workspaceMemberships.values()].some((item) => item.environmentId === environmentId && item.identityId === person.id))
1216
+ continue;
1217
+ const parent = hasOrganizations ? [...maps.directoryMemberships.values()].filter((item) => item.environmentId === environmentId && item.identityId === person.id)
1218
+ .sort((left, right) => left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id))[0] : undefined;
1219
+ if (hasOrganizations && !parent)
1220
+ continue;
1221
+ const workspaceId = directoryRecordId("wsp");
1222
+ maps.workspaces.set(workspaceId, {
1223
+ id: workspaceId, appId: app.id, environmentId, organizationId: parent?.organizationId ?? null, name: person.displayName,
1224
+ status: "active", createdAt: stamp, updatedAt: stamp,
1225
+ });
1226
+ const membershipId = directoryRecordId("wsm");
1227
+ maps.workspaceMemberships.set(membershipId, {
1228
+ id: membershipId, environmentId, workspaceId, identityId: person.id, relation: "owner", createdAt: stamp,
1229
+ });
1230
+ repair.workspaces += 1;
1231
+ }
1232
+ }
1233
+ return repair;
1234
+ }
163
1235
  //# sourceMappingURL=directory-memory.js.map