@x12i/keyrox-store 0.2.5 → 0.2.7

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.
@@ -0,0 +1,19 @@
1
+ import { type AppEnvironment, type CustomerAccess, type DelegateSend, type Delegation } from "@x12i/keyrox-types";
2
+ import type { DirectoryMaps } from "./directory-memory.js";
3
+ import type { KeyroxStore } from "./repository.js";
4
+ export interface DelegationMaps {
5
+ /** Keyed by the environment id. */
6
+ customerAccess: Map<string, CustomerAccess>;
7
+ delegations: Map<string, Delegation>;
8
+ delegateSends: Map<string, DelegateSend>;
9
+ }
10
+ export declare function emptyDelegation(): DelegationMaps;
11
+ type DelegationApi = Pick<KeyroxStore, "getCustomerAccess" | "saveCustomerAccess" | "hasCustomerAccessOrigin" | "insertDelegation" | "getDelegation" | "findDelegationByCodeHash" | "findDelegationByTokenHash" | "redeemDelegation" | "endDelegation" | "endDelegationsOfEnvironment" | "pruneDelegations" | "claimDelegateSend" | "claimAppWaitlistInvitation">;
12
+ /**
13
+ * The memory store's customer access. It mirrors the SQL store, constraint for constraint: an unknown environment is a
14
+ * conflict (the foreign key), a repeated code or token hash is a duplicate (the unique indexes), and a row whose
15
+ * code, token and expiry disagree is refused (the check). Every method runs in `tx`, so a failure leaves nothing behind.
16
+ */
17
+ export declare function bindDelegationMemory(maps: () => DelegationMaps, directory: () => Pick<DirectoryMaps, "appWaitlist" | "workspaces">, environmentOf: (environmentId: string) => AppEnvironment | undefined, tx: <T>(run: () => T) => T, saveAppWaitlist: KeyroxStore["saveAppWaitlist"]): DelegationApi;
18
+ export {};
19
+ //# sourceMappingURL=delegation-memory.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"delegation-memory.d.ts","sourceRoot":"","sources":["../src/delegation-memory.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,cAAc,EAAyB,KAAK,cAAc,EAAE,KAAK,YAAY,EAAE,KAAK,UAAU,EACpG,MAAM,oBAAoB,CAAC;AAE5B,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAE3D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAGnD,MAAM,WAAW,cAAc;IAC7B,mCAAmC;IACnC,cAAc,EAAE,GAAG,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;IAC5C,WAAW,EAAE,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;IACrC,aAAa,EAAE,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;CAC1C;AAED,wBAAgB,eAAe,IAAI,cAAc,CAEhD;AAED,KAAK,aAAa,GAAG,IAAI,CAAC,WAAW,EACnC,mBAAmB,GAAG,oBAAoB,GAAG,yBAAyB,GAAG,kBAAkB,GAAG,eAAe,GAAG,0BAA0B,GAAG,2BAA2B,GACxK,kBAAkB,GAAG,eAAe,GAAG,6BAA6B,GAAG,kBAAkB,GAAG,mBAAmB,GAAG,4BAA4B,CAC/I,CAAC;AAEF;;;;GAIG;AACH,wBAAgB,oBAAoB,CAClC,IAAI,EAAE,MAAM,cAAc,EAC1B,SAAS,EAAE,MAAM,IAAI,CAAC,aAAa,EAAE,aAAa,GAAG,YAAY,CAAC,EAClE,aAAa,EAAE,CAAC,aAAa,EAAE,MAAM,KAAK,cAAc,GAAG,SAAS,EACpE,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,MAAM,CAAC,KAAK,CAAC,EAC1B,eAAe,EAAE,WAAW,CAAC,iBAAiB,CAAC,GAC9C,aAAa,CAoJf"}
@@ -0,0 +1,193 @@
1
+ import { DELEGATE_SENDS_RETENTION_MS, DELEGATE_SENDS_WINDOW_MS, DELEGATE_SESSION_MINUTES, DELEGATE_MAX_ALLOWED_ORIGINS, DELEGATE_MAX_RETURN_URLS, DELEGATION_RETENTION_MS, delegationEndsAt, } from "@x12i/keyrox-types";
2
+ import { invitationTargetsOrganization } from "./delegation.js";
3
+ import { fail } from "./errors.js";
4
+ import { asTime, asTimeOrNull, clone, isExpired } from "./time.js";
5
+ export function emptyDelegation() {
6
+ return { customerAccess: new Map(), delegations: new Map(), delegateSends: new Map() };
7
+ }
8
+ /**
9
+ * The memory store's customer access. It mirrors the SQL store, constraint for constraint: an unknown environment is a
10
+ * conflict (the foreign key), a repeated code or token hash is a duplicate (the unique indexes), and a row whose
11
+ * code, token and expiry disagree is refused (the check). Every method runs in `tx`, so a failure leaves nothing behind.
12
+ */
13
+ export function bindDelegationMemory(maps, directory, environmentOf, tx, saveAppWaitlist) {
14
+ const sessionMinutes = DELEGATE_SESSION_MINUTES;
15
+ return {
16
+ async getCustomerAccess(environmentId) {
17
+ const row = maps().customerAccess.get(environmentId);
18
+ return row ? clone(row) : null;
19
+ },
20
+ async saveCustomerAccess(row, guard) {
21
+ return tx(() => {
22
+ const environment = environmentOf(row.environmentId);
23
+ // Under a guard an environment that is gone is the same refusal as one that moved: it is not the Team's any more.
24
+ if (guard && environment?.orgId !== guard.orgId)
25
+ return false;
26
+ if (!environment)
27
+ fail("conflict", "Application environment not found.");
28
+ if (!sessionMinutes.includes(row.sessionMinutes))
29
+ fail("conflict", "Invalid session length.");
30
+ if (row.returnUrls.length > DELEGATE_MAX_RETURN_URLS)
31
+ fail("conflict", "Too many return addresses.");
32
+ if (row.allowedOrigins.length > DELEGATE_MAX_ALLOWED_ORIGINS)
33
+ fail("conflict", "Too many allowed origins.");
34
+ if (row.portalUrl !== null && row.portalUrl.length > 2000)
35
+ fail("conflict", "The portal address is too long.");
36
+ if (guard) {
37
+ // What the SQL store holds with a share lock and a conditional write: the row is still the one that was read. (That the environment is
38
+ // still the guard's Team's was judged above.)
39
+ const held = maps().customerAccess.get(row.environmentId);
40
+ if ((held?.updatedAt ?? null) !== (guard.previousUpdatedAt === null ? null : asTime(guard.previousUpdatedAt)))
41
+ return false;
42
+ }
43
+ maps().customerAccess.set(row.environmentId, {
44
+ environmentId: row.environmentId, enabled: row.enabled, operations: [...row.operations],
45
+ assignableRoleIds: [...row.assignableRoleIds], returnUrls: [...row.returnUrls], portalUrl: row.portalUrl,
46
+ allowedOrigins: [...row.allowedOrigins], sessionMinutes: row.sessionMinutes, updatedAt: asTime(row.updatedAt),
47
+ });
48
+ return true;
49
+ });
50
+ },
51
+ async hasCustomerAccessOrigin(origin) {
52
+ for (const row of maps().customerAccess.values())
53
+ if (row.enabled && row.allowedOrigins.includes(origin))
54
+ return true;
55
+ return false;
56
+ },
57
+ async insertDelegation(row) {
58
+ tx(() => {
59
+ const environment = environmentOf(row.environmentId);
60
+ if (!environment || environment.appId !== row.appId)
61
+ fail("conflict", "Application environment not found.");
62
+ if ((row.codeUsedAt === null) !== (row.tokenHash === null) || (row.tokenHash === null) !== (row.tokenExpiresAt === null)) {
63
+ fail("conflict", "A delegation holds a token exactly when its code was used.");
64
+ }
65
+ const table = maps().delegations;
66
+ if (table.has(row.id))
67
+ fail("duplicate", "Duplicate key.");
68
+ for (const other of table.values()) {
69
+ if (other.codeHash === row.codeHash || (row.tokenHash !== null && other.tokenHash === row.tokenHash))
70
+ fail("duplicate", "Duplicate key.");
71
+ }
72
+ table.set(row.id, {
73
+ ...clone(row), codeExpiresAt: asTime(row.codeExpiresAt), codeUsedAt: asTimeOrNull(row.codeUsedAt), tokenExpiresAt: asTimeOrNull(row.tokenExpiresAt),
74
+ endedAt: asTimeOrNull(row.endedAt), createdAt: asTime(row.createdAt),
75
+ });
76
+ });
77
+ },
78
+ async getDelegation(id) {
79
+ const row = maps().delegations.get(id);
80
+ return row ? clone(row) : null;
81
+ },
82
+ async findDelegationByCodeHash(codeHash) {
83
+ for (const row of maps().delegations.values())
84
+ if (row.codeHash === codeHash)
85
+ return clone(row);
86
+ return null;
87
+ },
88
+ async findDelegationByTokenHash(tokenHash) {
89
+ for (const row of maps().delegations.values())
90
+ if (row.tokenHash !== null && row.tokenHash === tokenHash)
91
+ return clone(row);
92
+ return null;
93
+ },
94
+ async redeemDelegation(input) {
95
+ return tx(() => {
96
+ const stamp = asTime(input.at);
97
+ const row = [...maps().delegations.values()].find((item) => item.codeHash === input.codeHash);
98
+ if (!row || row.codeUsedAt !== null || row.endedAt !== null || isExpired(row.codeExpiresAt, stamp))
99
+ return null;
100
+ if ([...maps().delegations.values()].some((item) => item.tokenHash === input.tokenHash))
101
+ fail("duplicate", "Duplicate key.");
102
+ row.codeUsedAt = stamp;
103
+ row.tokenHash = input.tokenHash;
104
+ row.tokenExpiresAt = asTime(input.tokenExpiresAt);
105
+ return clone(row);
106
+ });
107
+ },
108
+ async endDelegation(id, at) {
109
+ return tx(() => {
110
+ const row = maps().delegations.get(id);
111
+ if (!row || row.endedAt !== null)
112
+ return false;
113
+ row.endedAt = asTime(at);
114
+ return true;
115
+ });
116
+ },
117
+ async endDelegationsOfEnvironment(environmentId, at) {
118
+ return tx(() => {
119
+ const stamp = asTime(at);
120
+ const ended = [];
121
+ for (const row of maps().delegations.values()) {
122
+ if (row.environmentId !== environmentId || row.endedAt !== null)
123
+ continue;
124
+ // A code that was never used lives until its own expiry, a session until its token's. Anything past that is over already.
125
+ const lastsUntil = row.codeUsedAt === null ? row.codeExpiresAt : row.tokenExpiresAt;
126
+ if (lastsUntil === null || Date.parse(lastsUntil) <= Date.parse(stamp))
127
+ continue;
128
+ row.endedAt = stamp;
129
+ ended.push(row.id);
130
+ }
131
+ return ended.sort();
132
+ });
133
+ },
134
+ async pruneDelegations(at) {
135
+ return tx(() => {
136
+ const now = Date.parse(asTime(at));
137
+ const table = maps();
138
+ let delegations = 0;
139
+ let sends = 0;
140
+ for (const [id, row] of [...table.delegations]) {
141
+ if (Date.parse(delegationEndsAt(row)) + DELEGATION_RETENTION_MS <= now) {
142
+ table.delegations.delete(id);
143
+ delegations += 1;
144
+ }
145
+ }
146
+ for (const [id, row] of [...table.delegateSends]) {
147
+ if (Date.parse(row.at) + DELEGATE_SENDS_RETENTION_MS <= now) {
148
+ table.delegateSends.delete(id);
149
+ sends += 1;
150
+ }
151
+ }
152
+ return { delegations, sends };
153
+ });
154
+ },
155
+ async claimDelegateSend(input) {
156
+ return tx(() => {
157
+ if (!environmentOf(input.environmentId))
158
+ fail("conflict", "Application environment not found.");
159
+ const table = maps().delegateSends;
160
+ const stamp = asTime(input.at);
161
+ const since = Date.parse(stamp) - DELEGATE_SENDS_WINDOW_MS;
162
+ let counted = 0;
163
+ for (const row of table.values()) {
164
+ if (row.environmentId === input.environmentId && row.organizationId === input.organizationId && Date.parse(row.at) > since)
165
+ counted += 1;
166
+ }
167
+ if (counted >= input.max)
168
+ return false;
169
+ if (table.has(input.id))
170
+ fail("duplicate", "Duplicate key.");
171
+ table.set(input.id, { id: input.id, environmentId: input.environmentId, organizationId: input.organizationId, at: stamp });
172
+ return true;
173
+ });
174
+ },
175
+ // The check and the write below happen in one synchronous run: saveAppWaitlist does its work before it returns its
176
+ // promise, and nothing else can run in between.
177
+ async claimAppWaitlistInvitation(row, challenge, organizationId) {
178
+ const dir = directory();
179
+ const address = row.email.toLowerCase();
180
+ const current = [...dir.appWaitlist.values()].find((item) => item.environmentId === row.environmentId && item.email.toLowerCase() === address);
181
+ if (current) {
182
+ const workspace = current.invitation?.workspaceId ? dir.workspaces.get(current.invitation.workspaceId) : undefined;
183
+ const workspaceOrganizationId = workspace && workspace.environmentId === current.environmentId ? workspace.organizationId : null;
184
+ if (!invitationTargetsOrganization(current, organizationId, workspaceOrganizationId))
185
+ return "held";
186
+ }
187
+ const written = current ? { ...row, id: current.id, createdAt: current.createdAt, answers: clone(current.answers ?? []) } : row;
188
+ await saveAppWaitlist(written, challenge);
189
+ return "saved";
190
+ },
191
+ };
192
+ }
193
+ //# sourceMappingURL=delegation-memory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"delegation-memory.js","sourceRoot":"","sources":["../src/delegation-memory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,2BAA2B,EAAE,wBAAwB,EAAE,wBAAwB,EAAE,4BAA4B,EAAE,wBAAwB,EAAE,uBAAuB,EAChK,gBAAgB,GAEjB,M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UAAU,CAAC,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;gBACnH,MAAM,uBAAuB,GAAG,SAAS,IAAI,SAAS,CAAC,aAAa,KAAK,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,SAAS,CAAC,cAAc,CAAC,CAAC,CAAC,IAAI,CAAC;gBACjI,IAAI,CAAC,6BAA6B,CAAC,OAAO,EAAE,cAAc,EAAE,uBAAuB,CAAC;oBAAE,OAAO,MAAe,CAAC;YAC/G,CAAC;YACD,MAAM,OAAO,GAAG,OAAO,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,EAAE,EAAE,EAAE,OAAO,CAAC,EAAE,EAAE,SAAS,EAAE,OAAO,CAAC,SAAS,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,OAAO,IAAI,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC;YAChI,MAAM,eAAe,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;YAC1C,OAAO,OAAgB,CAAC;QAC1B,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,50 @@
1
+ import type { AppWaitlistEntry } from "@x12i/keyrox-types";
2
+ /**
3
+ * Customer access in the stores (the delegation of the back-office brief, section 5). The two stores share the shapes
4
+ * below and the one rule of the address claim, so they cannot disagree about who may write a waiting-list row.
5
+ */
6
+ /** The atomic step that turns a one-time code into a token. Nothing is written unless the code is live and unused. */
7
+ export interface RedeemDelegationInput {
8
+ codeHash: string;
9
+ /** The moment of the redeem. A code is live while this is before its expiry. */
10
+ at: string;
11
+ tokenHash: string;
12
+ tokenExpiresAt: string;
13
+ }
14
+ /**
15
+ * What a save of the customer-access policy must still find true at the moment it writes. The policy route reads the row,
16
+ * changes it and writes it back, and a person was judged against a Team before any of that. A write that finds either of
17
+ * these false is refused and changes nothing: another request saved first, or the application moved to another Team.
18
+ */
19
+ export interface CustomerAccessGuard {
20
+ /** The Team the person was judged against. The environment must still belong to it when the row is written. */
21
+ orgId: string;
22
+ /** The `updatedAt` of the row that was read, or null when there was none. The row must still be exactly that one. */
23
+ previousUpdatedAt: string | null;
24
+ }
25
+ /** One invitation mail to be counted against the hourly cap of an organization. */
26
+ export interface DelegateSendClaim {
27
+ id: string;
28
+ environmentId: string;
29
+ organizationId: string;
30
+ at: string;
31
+ /** How many mails the organization may send in the hour that ends at `at`. */
32
+ max: number;
33
+ }
34
+ /**
35
+ * The outcome of claiming an address for an invitation of one organization. "held" means the waiting-list row for the
36
+ * address belongs to someone else (another organization's invitation, or a waiting-list entry), so nothing was written.
37
+ */
38
+ export type WaitlistClaim = "saved" | "held";
39
+ export interface PrunedDelegations {
40
+ delegations: number;
41
+ sends: number;
42
+ }
43
+ /**
44
+ * Whether a waiting-list row is an invitation whose target lies in this organization, in any status. An organization
45
+ * target says so itself. A workspace target is resolved to the organization of the workspace, which the caller reads
46
+ * from the workspace row (null when the workspace does not exist or belongs to none). A row with no target, a
47
+ * waiting-list entry or a role-only invitation, is nobody's.
48
+ */
49
+ export declare function invitationTargetsOrganization(entry: Pick<AppWaitlistEntry, "invitation">, organizationId: string, workspaceOrganizationId: string | null): boolean;
50
+ //# sourceMappingURL=delegation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"delegation.d.ts","sourceRoot":"","sources":["../src/delegation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAE3D;;;GAGG;AAEH,sHAAsH;AACtH,MAAM,WAAW,qBAAqB;IACpC,QAAQ,EAAE,MAAM,CAAC;IACjB,gFAAgF;IAChF,EAAE,EAAE,MAAM,CAAC;IACX,SAAS,EAAE,MAAM,CAAC;IAClB,cAAc,EAAE,MAAM,CAAC;CACxB;AAED;;;;GAIG;AACH,MAAM,WAAW,mBAAmB;IAClC,+GAA+G;IAC/G,KAAK,EAAE,MAAM,CAAC;IACd,qHAAqH;IACrH,iBAAiB,EAAE,MAAM,GAAG,IAAI,CAAC;CAClC;AAED,mFAAmF;AACnF,MAAM,WAAW,iBAAiB;IAChC,EAAE,EAAE,MAAM,CAAC;IACX,aAAa,EAAE,MAAM,CAAC;IACtB,cAAc,EAAE,MAAM,CAAC;IACvB,EAAE,EAAE,MAAM,CAAC;IACX,8EAA8E;IAC9E,GAAG,EAAE,MAAM,CAAC;CACb;AAED;;;GAGG;AACH,MAAM,MAAM,aAAa,GAAG,OAAO,GAAG,MAAM,CAAC;AAE7C,MAAM,WAAW,iBAAiB;IAChC,WAAW,EAAE,MAAM,CAAC;IACpB,KAAK,EAAE,MAAM,CAAC;CACf;AAED;;;;;GAKG;AACH,wBAAgB,6BAA6B,CAAC,KAAK,EAAE,IAAI,CAAC,gBAAgB,EAAE,YAAY,CAAC,EAAE,cAAc,EAAE,MAAM,EAAE,uBAAuB,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAMlK"}
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Whether a waiting-list row is an invitation whose target lies in this organization, in any status. An organization
3
+ * target says so itself. A workspace target is resolved to the organization of the workspace, which the caller reads
4
+ * from the workspace row (null when the workspace does not exist or belongs to none). A row with no target, a
5
+ * waiting-list entry or a role-only invitation, is nobody's.
6
+ */
7
+ export function invitationTargetsOrganization(entry, organizationId, workspaceOrganizationId) {
8
+ const target = entry.invitation;
9
+ if (!target || (!target.workspaceId && !target.organizationId))
10
+ return false;
11
+ if (target.workspaceId && workspaceOrganizationId !== organizationId)
12
+ return false;
13
+ if (target.organizationId && target.organizationId !== organizationId)
14
+ return false;
15
+ return true;
16
+ }
17
+ //# sourceMappingURL=delegation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"delegation.js","sourceRoot":"","sources":["../src/delegation.ts"],"names":[],"mappings":"AAiDA;;;;;GAKG;AACH,MAAM,UAAU,6BAA6B,CAAC,KAA2C,EAAE,cAAsB,EAAE,uBAAsC;IACvJ,MAAM,MAAM,GAAG,KAAK,CAAC,UAAU,CAAC;IAChC,IAAI,CAAC,MAAM,IAAI,CAAC,CAAC,MAAM,CAAC,WAAW,IAAI,CAAC,MAAM,CAAC,cAAc,CAAC;QAAE,OAAO,KAAK,CAAC;IAC7E,IAAI,MAAM,CAAC,WAAW,IAAI,uBAAuB,KAAK,cAAc;QAAE,OAAO,KAAK,CAAC;IACnF,IAAI,MAAM,CAAC,cAAc,IAAI,MAAM,CAAC,cAAc,KAAK,cAAc;QAAE,OAAO,KAAK,CAAC;IACpF,OAAO,IAAI,CAAC;AACd,CAAC"}
@@ -29,7 +29,7 @@ export interface DirectoryMaps {
29
29
  accessChecks: Map<string, DirectoryAccessCheck>;
30
30
  userCount: () => number;
31
31
  }
32
- type DirectoryApi = Pick<KeyroxStore, "countUsers" | "getPlatformSignup" | "setPlatformSignup" | "insertPlatformWaitlist" | "savePlatformWaitlist" | "listPlatformWaitlist" | "findPlatformWaitlist" | "saveDirectoryIdentity" | "proveDirectoryEmail" | "getDirectoryIdentity" | "listDirectoryIdentities" | "findDirectoryIdentityByEmail" | "findHostedSsoIdentity" | "listHostedSsoIdentityIds" | "saveHostedSsoIdentity" | "signupDirectoryPerson" | "getDirectorySignupRole" | "setDirectorySignupRole" | "saveDirectoryMembership" | "deleteDirectoryMembership" | "listDirectoryMemberships" | "createDirectoryWorkspace" | "getDirectoryWorkspace" | "listDirectoryWorkspaces" | "updateDirectoryWorkspace" | "addDirectoryWorkspaceMembership" | "listDirectoryWorkspaceMemberships" | "removeDirectoryWorkspaceMembership" | "applyDirectoryAccess" | "clearDirectoryProductRole" | "saveDirectoryAccessCheck" | "listDirectoryAccessChecks" | "getDirectoryOnboardingResponse" | "saveDirectoryOnboardingResponse" | "saveProductPermission" | "deleteProductPermission" | "listProductPermissions" | "saveProductRole" | "deleteProductRole" | "listProductRoles" | "insertTenantProductRole" | "listTenantProductRoles" | "updateTenantProductRole" | "deleteTenantProductRole" | "setProductRoleCatalogLink" | "saveDirectoryGroup" | "deleteDirectoryGroup" | "listDirectoryGroups" | "saveGroupMember" | "deleteGroupMember" | "listGroupMembers" | "saveRoleBinding" | "deleteRoleBinding" | "listRoleBindings" | "saveFeatureDefinition" | "updateFeatureDefinition" | "deleteFeatureDefinition" | "listFeatureDefinitions" | "saveFeatureAssignment" | "deleteFeatureAssignment" | "listFeatureAssignments" | "insertAppWaitlist" | "saveAppWaitlist" | "readDirectoryInvitation" | "listDirectoryInvitations" | "setDirectoryInvitationAudit" | "revokeDirectoryInvitation" | "redeemDirectoryInvitation" | "acceptDirectoryWorkspaceInvitation" | "acceptDirectoryWorkspaceInvitationByToken" | "completeDirectoryPasswordSetup" | "prepareDirectoryPasswordChange" | "commitDirectoryPasswordChange" | "listAppWaitlist" | "findAppWaitlist" | "claimWaitlistConfirmation" | "finishWaitlistConfirmation" | "insertDirectoryChallenge" | "insertDirectoryChallengeWithCooldown" | "takeDirectoryChallenge" | "verifyDirectoryEmail">;
32
+ type DirectoryApi = Pick<KeyroxStore, "countUsers" | "getPlatformSignup" | "setPlatformSignup" | "insertPlatformWaitlist" | "savePlatformWaitlist" | "listPlatformWaitlist" | "findPlatformWaitlist" | "saveDirectoryIdentity" | "createDirectoryOrganization" | "proveDirectoryEmail" | "getDirectoryIdentity" | "listDirectoryIdentities" | "findDirectoryIdentityByEmail" | "findHostedSsoIdentity" | "listHostedSsoIdentityIds" | "saveHostedSsoIdentity" | "signupDirectoryPerson" | "getDirectorySignupRole" | "setDirectorySignupRole" | "saveDirectoryMembership" | "deleteDirectoryMembership" | "listDirectoryMemberships" | "createDirectoryWorkspace" | "getDirectoryWorkspace" | "listDirectoryWorkspaces" | "updateDirectoryWorkspace" | "addDirectoryWorkspaceMembership" | "listDirectoryWorkspaceMemberships" | "removeDirectoryWorkspaceMembership" | "applyDirectoryAccess" | "clearDirectoryProductRole" | "saveDirectoryAccessCheck" | "listDirectoryAccessChecks" | "getDirectoryOnboardingResponse" | "saveDirectoryOnboardingResponse" | "saveProductPermission" | "deleteProductPermission" | "listProductPermissions" | "saveProductRole" | "deleteProductRole" | "listProductRoles" | "insertTenantProductRole" | "listTenantProductRoles" | "updateTenantProductRole" | "deleteTenantProductRole" | "setProductRoleCatalogLink" | "saveDirectoryGroup" | "deleteDirectoryGroup" | "listDirectoryGroups" | "saveGroupMember" | "deleteGroupMember" | "listGroupMembers" | "saveRoleBinding" | "deleteRoleBinding" | "listRoleBindings" | "saveFeatureDefinition" | "updateFeatureDefinition" | "deleteFeatureDefinition" | "listFeatureDefinitions" | "saveFeatureAssignment" | "deleteFeatureAssignment" | "listFeatureAssignments" | "insertAppWaitlist" | "saveAppWaitlist" | "readDirectoryInvitation" | "listDirectoryInvitations" | "setDirectoryInvitationAudit" | "revokeDirectoryInvitation" | "redeemDirectoryInvitation" | "acceptDirectoryWorkspaceInvitation" | "acceptDirectoryWorkspaceInvitationByToken" | "completeDirectoryPasswordSetup" | "prepareDirectoryPasswordChange" | "commitDirectoryPasswordChange" | "listAppWaitlist" | "findAppWaitlist" | "claimWaitlistConfirmation" | "finishWaitlistConfirmation" | "insertDirectoryChallenge" | "insertDirectoryChallengeWithCooldown" | "releaseDirectoryChallenge" | "replaceDirectoryResetChallenge" | "takeDirectoryChallenge" | "verifyDirectoryEmail">;
33
33
  export declare function emptyDirectory(): Omit<DirectoryMaps, "userCount">;
34
34
  export declare function bindDirectoryMemory(source: () => Omit<DirectoryMaps, "userCount">, users: () => number, tx: <T>(run: () => T) => T, activeApplicationForEnvironment: (environmentId: string, includeDisabled?: boolean) => Application | null, insertNotification: (identity: DirectoryIdentity, job: DirectorySignupInput["notificationDelivery"]) => void): DirectoryApi;
35
35
  export declare function repairDirectoryStructure(maps: Omit<DirectoryMaps, "userCount">, environmentIds: ReadonlySet<string>, app: {
@@ -1 +1 @@
1
- {"version":3,"file":"directory-memory.d.ts","sourceRoot":"","sources":["../src/directory-memory.ts"],"names":[],"mappings":"AACA,OAAO,EAAqD,KAAK,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAE5G,OAAO,KAAK,EACV,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AM,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,MAAM,CAAC,KAAK,CAAC,EAC/F,+BAA+B,EAAE,CAAC,aAAa,EAAE,MAAM,EAAE,eAAe,CAAC,EAAE,OAAO,KAAK,WAAW,GAAG,IAAI,EACzG,kBAAkB,EAAE,CAAC,QAAQ,EAAE,iBAAiB,EAAE,GAAG,EAAE,oBAAoB,CAAC,sBAAsB,CAAC,KAAK,IAAI,GAC3G,YAAY,CAokCd;AAMD,wBAAgB,wBAAwB,CACtC,IAAI,EAAE,IAAI,CAAC,aAAa,EAAE,WAAW,CAAC,EAAE,cAAc,EAAE,WAAW,CAAC,MAAM,CAAC,EAAE,GAAG,EAAE;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,EAAE,KAAK,EAAE,cAAc,EAAE,EAAE,EAAE,MAAM,GACjJ,wBAAwB,CAiE1B"}
@@ -279,6 +279,9 @@ export function bindDirectoryMemory(source, users, tx, activeApplicationForEnvir
279
279
  fail("conflict", "This account is disabled.");
280
280
  return identity;
281
281
  }
282
+ function organizationHasOwner(maps, environmentId, organizationId, exceptId) {
283
+ return [...maps.directoryMemberships.values()].some((item) => item.id !== exceptId && item.environmentId === environmentId && item.organizationId === organizationId && item.relation === "owner");
284
+ }
282
285
  function ensureOrganizationMember(request, organizationId, relation, compareRelation) {
283
286
  const maps = source();
284
287
  const organization = maps.identities.get(organizationId);
@@ -294,6 +297,9 @@ export function bindDirectoryMemory(source, users, tx, activeApplicationForEnvir
294
297
  if (!existing) {
295
298
  if (compareRelation && request.expected?.relation && request.expected.relation !== desired)
296
299
  fail("grant_changed", "The saved directory role changed.");
300
+ if (desired !== "owner" && !organizationHasOwner(maps, request.environmentId, organizationId)) {
301
+ fail("last_owner", "An organization must keep an owner.");
302
+ }
297
303
  save(maps.directoryMemberships, {
298
304
  id: request.newOrganizationMembershipId, environmentId: request.environmentId, identityId: request.identityId,
299
305
  organizationId, relation: desired, createdAt: asTime(request.at),
@@ -573,6 +579,31 @@ export function bindDirectoryMemory(source, users, tx, activeApplicationForEnvir
573
579
  const identity = signInIdentity(source().identities.values(), environmentId, email);
574
580
  return identity ? clone(identity) : null;
575
581
  },
582
+ async createDirectoryOrganization(identity, owner) {
583
+ tx(() => {
584
+ const maps = source();
585
+ const app = activeApplicationForEnvironment(identity.environmentId, true);
586
+ if (app?.id !== identity.appId || app.orgId !== identity.orgId)
587
+ fail("conflict", "Identity must match its application environment and tenant.");
588
+ if (identity.kind !== "organization")
589
+ fail("conflict", "An organization is required.");
590
+ requireOrganizationScope(identity.environmentId);
591
+ if (!directoryHasOrganizations(app.directoryModel))
592
+ fail("conflict", "New organizations are unavailable for this application.");
593
+ if (maps.identities.has(identity.id) || maps.directoryMemberships.has(owner.id))
594
+ fail("duplicate", "Duplicate key.");
595
+ const person = maps.identities.get(owner.identityId);
596
+ if (!person || person.environmentId !== identity.environmentId || person.appId !== identity.appId || person.status !== "active"
597
+ || (person.kind !== "user" && person.kind !== "account")) {
598
+ fail("not_found", "Choose an active person in this environment to own the organization.");
599
+ }
600
+ if (owner.environmentId !== identity.environmentId || owner.organizationId !== identity.id || owner.relation !== "owner") {
601
+ fail("conflict", "An organization must have an owner.");
602
+ }
603
+ saveIdentity(maps, identity);
604
+ save(maps.directoryMemberships, { ...owner, createdAt: asTime(owner.createdAt) });
605
+ });
606
+ },
576
607
  async saveDirectoryMembership(row) {
577
608
  tx(() => {
578
609
  requireOrganizationScope(row.environmentId);
@@ -580,6 +611,9 @@ export function bindDirectoryMemory(source, users, tx, activeApplicationForEnvir
580
611
  const clash = [...maps.directoryMemberships.values()].find((item) => item.identityId === row.identityId && item.organizationId === row.organizationId && item.id !== row.id);
581
612
  if (clash)
582
613
  fail("duplicate", "Duplicate key.");
614
+ if (row.relation !== "owner" && !organizationHasOwner(maps, row.environmentId, row.organizationId, row.id)) {
615
+ fail("last_owner", "An organization must keep an owner.");
616
+ }
583
617
  save(maps.directoryMemberships, { ...row, createdAt: asTime(row.createdAt) });
584
618
  });
585
619
  },
@@ -605,6 +639,9 @@ export function bindDirectoryMemory(source, users, tx, activeApplicationForEnvir
605
639
  && item.identityId === organizationMembership.identityId && item.organizationId === organizationMembership.organizationId);
606
640
  if (clash)
607
641
  fail("duplicate", "Duplicate key.");
642
+ if (organizationMembership.relation !== "owner" && !organizationHasOwner(maps, organizationMembership.environmentId, organizationMembership.organizationId)) {
643
+ fail("last_owner", "An organization must keep an owner.");
644
+ }
608
645
  save(maps.directoryMemberships, { ...organizationMembership, createdAt: asTime(organizationMembership.createdAt) });
609
646
  }
610
647
  assertWorkspaceScope(workspace);
@@ -967,7 +1004,7 @@ export function bindDirectoryMemory(source, users, tx, activeApplicationForEnvir
967
1004
  if (!challenge || challenge.usedAt || isExpired(challenge.expiresAt, stamp))
968
1005
  return false;
969
1006
  const identity = signInIdentity(maps.identities.values(), environmentId, challenge.email);
970
- if (!identity || identity.status !== "active" || (identity.kind !== "user" && identity.kind !== "account") || identity.passwordHash)
1007
+ if (!identity || identity.status !== "active" || (identity.kind !== "user" && identity.kind !== "account"))
971
1008
  return false;
972
1009
  const invite = [...maps.appWaitlist.values()].find((row) => row.environmentId === environmentId && row.email.toLowerCase() === challenge.email.toLowerCase()
973
1010
  && row.status === "invited");
@@ -977,7 +1014,7 @@ export function bindDirectoryMemory(source, users, tx, activeApplicationForEnvir
977
1014
  return false;
978
1015
  if (invite?.invitation && !invitationIsAvailable(invite))
979
1016
  return false;
980
- identity.passwordHash = passwordHash;
1017
+ void passwordHash;
981
1018
  identity.emailVerifiedAt = identity.emailVerifiedAt ?? stamp;
982
1019
  identity.emailProofAt = stamp;
983
1020
  identity.updatedAt = stamp;
@@ -1154,6 +1191,34 @@ export function bindDirectoryMemory(source, users, tx, activeApplicationForEnvir
1154
1191
  return true;
1155
1192
  });
1156
1193
  },
1194
+ async releaseDirectoryChallenge(id) {
1195
+ tx(() => {
1196
+ const row = source().directoryChallenges.get(id);
1197
+ if (row && !row.usedAt)
1198
+ source().directoryChallenges.delete(id);
1199
+ });
1200
+ },
1201
+ async replaceDirectoryResetChallenge(row) {
1202
+ tx(() => {
1203
+ if (row.purpose !== "reset")
1204
+ fail("conflict", "Reset challenge is required.");
1205
+ const maps = source();
1206
+ const identity = maps.identities.get(row.identityId);
1207
+ const email = identity?.email?.toLowerCase();
1208
+ if (!identity || identity.environmentId !== row.environmentId || email !== row.email.toLowerCase()
1209
+ || (identity.kind !== "user" && identity.kind !== "account") || identity.status !== "active"
1210
+ || !activeApplicationForEnvironment(row.environmentId, true)) {
1211
+ fail("not_found", "Person not found.");
1212
+ }
1213
+ const stamp = asTime(row.createdAt);
1214
+ for (const challenge of maps.directoryChallenges.values()) {
1215
+ if (challenge.environmentId === row.environmentId && challenge.identityId === row.identityId && challenge.purpose === "reset" && !challenge.usedAt) {
1216
+ challenge.usedAt = stamp;
1217
+ }
1218
+ }
1219
+ addChallenge(maps, row);
1220
+ });
1221
+ },
1157
1222
  async takeDirectoryChallenge(tokenHash, at, scope) {
1158
1223
  return tx(() => {
1159
1224
  const maps = source();
@@ -1229,7 +1294,7 @@ export function repairDirectoryStructure(maps, environmentIds, app, model, at) {
1229
1294
  continue;
1230
1295
  const membershipId = directoryRecordId("dms");
1231
1296
  maps.directoryMemberships.set(membershipId, {
1232
- id: membershipId, environmentId, identityId: owner.identityId, organizationId, relation: "member", createdAt: stamp,
1297
+ id: membershipId, environmentId, identityId: owner.identityId, organizationId, relation: "owner", createdAt: stamp,
1233
1298
  });
1234
1299
  }
1235
1300
  maps.workspaces.set(workspace.id, { ...workspace, organizationId, updatedAt: stamp });