@x12i/keyrox-store 0.2.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.
@@ -1,5 +1,7 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import { directoryHasOrganizations, directoryHasWorkspaces } from "@x12i/keyrox-types";
3
+ import { existingGrantDecision, missingGrantDecision, } from "./directory-access.js";
4
+ import { invitationLifecycle, invitationPreview } from "./directory-invitation.js";
3
5
  import { fail } from "./errors.js";
4
6
  import { asTime, asTimeOrNull, clone, isExpired } from "./time.js";
5
7
  export function emptyDirectory() {
@@ -24,8 +26,22 @@ export function emptyDirectory() {
24
26
  workspaces: new Map(),
25
27
  workspaceMemberships: new Map(),
26
28
  onboardingResponses: new Map(),
29
+ accessChecks: new Map(),
27
30
  };
28
31
  }
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
+ }
29
45
  export function bindDirectoryMemory(source, users, tx, activeApplicationForEnvironment, insertNotification) {
30
46
  const rows = (map, pred = () => true) => [...map.values()].filter(pred).map((row) => clone(row));
31
47
  const save = (map, row) => { map.set(row.id, clone(row)); };
@@ -54,7 +70,8 @@ export function bindDirectoryMemory(source, users, tx, activeApplicationForEnvir
54
70
  save(catalog, row);
55
71
  }
56
72
  function saveIdentity(maps, row) {
57
- if (row.email && [...maps.identities.values()].some((item) => item.environmentId === row.environmentId && item.email?.toLowerCase() === row.email?.toLowerCase() && item.id !== row.id)) {
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())) {
58
75
  fail("duplicate_email", "Email already exists.");
59
76
  }
60
77
  const { emailProofAt, ...identity } = row;
@@ -126,7 +143,7 @@ export function bindDirectoryMemory(source, users, tx, activeApplicationForEnvir
126
143
  return null;
127
144
  const maps = source();
128
145
  const app = activeApplicationForEnvironment(row.environmentId);
129
- const workspace = maps.workspaces.get(row.invitation.workspaceId);
146
+ const workspace = maps.workspaces.get(row.invitation.workspaceId ?? "");
130
147
  const role = maps.productRoles.get(row.invitation.roleId);
131
148
  if (app?.id !== row.appId || workspace?.appId !== row.appId || workspace.environmentId !== row.environmentId ||
132
149
  workspace.status !== "active" || role?.environmentId !== row.environmentId || !directoryHasWorkspaces(app.directoryModel) ||
@@ -165,6 +182,65 @@ export function bindDirectoryMemory(source, users, tx, activeApplicationForEnvir
165
182
  delete row.pendingWorkspaceIdentityId;
166
183
  return true;
167
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
+ }
168
244
  function acceptWorkspaceInvitation(identity, at, expectedTokenHash) {
169
245
  if (!identity.emailVerifiedAt || identity.status !== "active" || identity.kind !== "user" || !identity.email)
170
246
  return false;
@@ -176,10 +252,167 @@ export function bindDirectoryMemory(source, users, tx, activeApplicationForEnvir
176
252
  const challenge = [...maps.directoryChallenges.values()].find((row) => row.tokenHash === invite.tokenHash);
177
253
  if (!challenge || challenge.purpose !== "admit" || challenge.environmentId !== invite.environmentId || challenge.email.toLowerCase() !== invite.email.toLowerCase())
178
254
  return false;
255
+ if (invite.invitation?.delivery === "link")
256
+ return false;
179
257
  if (isExpired(challenge.expiresAt, at) || (invite.pendingWorkspaceIdentityId
180
258
  ? invite.pendingWorkspaceIdentityId !== identity.id || !challenge.usedAt : Boolean(challenge.usedAt)))
181
259
  return false;
182
- return applyWorkspaceInvitation(invite, challenge, identity, at);
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 };
183
416
  }
184
417
  return {
185
418
  async countUsers() { return users(); },
@@ -266,6 +499,8 @@ export function bindDirectoryMemory(source, users, tx, activeApplicationForEnvir
266
499
  admission.email.toLowerCase() !== email || admission.usedAt || isExpired(admission.expiresAt, stamp)) {
267
500
  fail("challenge_invalid", "Waiting list invitation is no longer available.");
268
501
  }
502
+ if (invite.invitation?.delivery === "link")
503
+ fail("challenge_invalid", "Waiting list invitation is no longer available.");
269
504
  admission.usedAt = stamp;
270
505
  if (invite.invitation) {
271
506
  if (!workspaceInvitationTarget(invite))
@@ -313,6 +548,9 @@ export function bindDirectoryMemory(source, users, tx, activeApplicationForEnvir
313
548
  const row = source().hostedSsoIdentities.get(JSON.stringify([environmentId, authority, subject]));
314
549
  return row ? clone(row) : null;
315
550
  },
551
+ async listHostedSsoIdentityIds(environmentId) {
552
+ return [...new Set([...source().hostedSsoIdentities.values()].filter((row) => row.environmentId === environmentId).map((row) => row.identityId))];
553
+ },
316
554
  async saveHostedSsoIdentity(row) { return tx(() => saveHostedSsoLink(source(), row)); },
317
555
  async setDirectorySignupRole(environmentId, roleId) {
318
556
  tx(() => {
@@ -332,7 +570,8 @@ export function bindDirectoryMemory(source, users, tx, activeApplicationForEnvir
332
570
  },
333
571
  async listDirectoryIdentities(environmentId) { return rows(source().identities, (row) => row.environmentId === environmentId); },
334
572
  async findDirectoryIdentityByEmail(environmentId, email) {
335
- 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;
336
575
  },
337
576
  async saveDirectoryMembership(row) {
338
577
  tx(() => {
@@ -425,9 +664,64 @@ export function bindDirectoryMemory(source, users, tx, activeApplicationForEnvir
425
664
  .some((row) => row.workspaceId === workspaceId && row.relation === "owner" && row.id !== membershipId)) {
426
665
  fail("last_owner", "A workspace must keep an owner.");
427
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);
428
673
  workspaceMemberships.delete(membershipId);
429
674
  });
430
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
+ },
431
725
  async getDirectoryOnboardingResponse(environmentId, target, subjectId) {
432
726
  const response = source().onboardingResponses.get(JSON.stringify([environmentId, target, subjectId]));
433
727
  return response ? clone(response) : null;
@@ -458,7 +752,10 @@ export function bindDirectoryMemory(source, users, tx, activeApplicationForEnvir
458
752
  const roles = source().productRoles;
459
753
  const current = roles.get(row.id);
460
754
  const next = { ...row, catalogRoleId: current ? current.catalogRoleId ?? null : row.catalogRoleId ?? null,
461
- permissions: [...row.permissions], inherits: [...row.inherits], createdAt: asTime(row.createdAt) };
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
+ }
462
759
  assertAvailableCatalogLink(next);
463
760
  save(roles, next);
464
761
  });
@@ -540,7 +837,24 @@ export function bindDirectoryMemory(source, users, tx, activeApplicationForEnvir
540
837
  save(source().bindings, { ...row, createdAt: asTime(row.createdAt) });
541
838
  });
542
839
  },
543
- async deleteRoleBinding(id) { tx(() => remove(source().bindings, id)); },
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
+ },
544
858
  async listRoleBindings(environmentId) { return rows(source().bindings, (row) => row.environmentId === environmentId); },
545
859
  async saveFeatureDefinition(row) {
546
860
  tx(() => {
@@ -610,9 +924,15 @@ export function bindDirectoryMemory(source, users, tx, activeApplicationForEnvir
610
924
  const clash = [...maps.appWaitlist.values()].find((item) => item.environmentId === row.environmentId && item.email.toLowerCase() === row.email.toLowerCase() && item.id !== row.id);
611
925
  if (clash)
612
926
  fail("duplicate_email", "Email already exists.");
613
- if (row.invitation && !workspaceInvitationTarget(row))
927
+ if (row.invitation && !invitationIsAvailable(row))
614
928
  fail("conflict", "The invited workspace or role is unavailable.");
615
- save(maps.appWaitlist, { ...row, createdAt: asTime(row.createdAt) });
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) } : {}) });
616
936
  if (challenge) {
617
937
  if (!activeApplicationForEnvironment(row.environmentId, true))
618
938
  fail("not_found", "Application environment not found.");
@@ -630,7 +950,7 @@ export function bindDirectoryMemory(source, users, tx, activeApplicationForEnvir
630
950
  return tx(() => {
631
951
  const maps = source();
632
952
  const challenge = [...maps.directoryChallenges.values()].find((row) => row.tokenHash === tokenHash && row.environmentId === environmentId && row.purpose === "admit");
633
- const identity = challenge && [...maps.identities.values()].find((row) => row.environmentId === environmentId && row.email?.toLowerCase() === challenge.email.toLowerCase());
953
+ const identity = challenge && signInIdentity(maps.identities.values(), environmentId, challenge.email);
634
954
  const stamp = asTime(at);
635
955
  if (!identity || !acceptWorkspaceInvitation(identity, stamp, tokenHash))
636
956
  return false;
@@ -639,6 +959,113 @@ export function bindDirectoryMemory(source, users, tx, activeApplicationForEnvir
639
959
  return true;
640
960
  });
641
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 };
1067
+ });
1068
+ },
642
1069
  async listAppWaitlist(environmentId) { return rows(source().appWaitlist, (row) => row.environmentId === environmentId); },
643
1070
  async findAppWaitlist(environmentId, email) {
644
1071
  return rows(source().appWaitlist, (row) => row.environmentId === environmentId && row.email.toLowerCase() === email.toLowerCase())[0] ?? null;