@x12i/keyrox-store 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/application-lifecycle.d.ts +6 -0
- package/dist/application-lifecycle.d.ts.map +1 -0
- package/dist/application-lifecycle.js +28 -0
- package/dist/application-lifecycle.js.map +1 -0
- package/dist/directory-memory.d.ts +19 -4
- package/dist/directory-memory.d.ts.map +1 -1
- package/dist/directory-memory.js +666 -21
- package/dist/directory-memory.js.map +1 -1
- package/dist/email-code-policy.d.ts +7 -0
- package/dist/email-code-policy.d.ts.map +1 -0
- package/dist/email-code-policy.js +7 -0
- package/dist/email-code-policy.js.map +1 -0
- package/dist/errors.d.ts +1 -1
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js.map +1 -1
- package/dist/hosted-human-sessions.d.ts +47 -0
- package/dist/hosted-human-sessions.d.ts.map +1 -0
- package/dist/hosted-human-sessions.js +2 -0
- package/dist/hosted-human-sessions.js.map +1 -0
- package/dist/index.d.ts +6 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/memory.d.ts.map +1 -1
- package/dist/memory.js +1108 -85
- package/dist/memory.js.map +1 -1
- package/dist/notification-delivery.d.ts +44 -0
- package/dist/notification-delivery.d.ts.map +1 -0
- package/dist/notification-delivery.js +58 -0
- package/dist/notification-delivery.js.map +1 -0
- package/dist/notification-webhook-jobs.d.ts +43 -0
- package/dist/notification-webhook-jobs.d.ts.map +1 -0
- package/dist/notification-webhook-jobs.js +59 -0
- package/dist/notification-webhook-jobs.js.map +1 -0
- package/dist/repository.d.ts +162 -12
- package/dist/repository.d.ts.map +1 -1
- package/package.json +2 -2
package/dist/memory.js
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
|
+
import { appIdFromTenantResource, applicationLifecycleTime, applicationMoveKeys, verifyApplicationTrashSnapshot } from "./application-lifecycle.js";
|
|
1
2
|
import { decideLongLived, effectiveActions } from "./access.js";
|
|
2
3
|
import { fail } from "./errors.js";
|
|
3
|
-
import {
|
|
4
|
+
import { hostedEmailCodePolicy } from "./email-code-policy.js";
|
|
5
|
+
import { createMemoryNotificationWebhookJobs } from "./notification-webhook-jobs.js";
|
|
6
|
+
import { createMemoryNotificationDeliveries, insertMemoryNotificationDelivery } from "./notification-delivery.js";
|
|
7
|
+
import { bindDirectoryMemory, emptyDirectory, repairDirectoryStructure } from "./directory-memory.js";
|
|
4
8
|
import { asTime, asTimeOrNull, clone, isExpired } from "./time.js";
|
|
5
9
|
const roles = new Set(["owner", "admin", "member"]);
|
|
6
10
|
function empty() {
|
|
@@ -8,9 +12,14 @@ function empty() {
|
|
|
8
12
|
users: new Map(), orgs: new Map(), memberships: new Map(), challenges: new Map(), invites: new Map(),
|
|
9
13
|
sessions: new Map(), clients: new Map(), agents: new Map(), authorizations: new Map(), grants: new Map(),
|
|
10
14
|
instances: new Map(), executions: new Map(), longTokens: new Map(), refreshes: new Map(), providers: new Map(),
|
|
15
|
+
hostedHumanSessions: new Map(), hostedHumanRefreshTokens: new Map(), hostedHumanSelections: new Map(),
|
|
11
16
|
trusts: new Map(), audits: new Map(), deniedJtis: new Map(), idempotency: new Map(),
|
|
12
|
-
applications: new Map(), environments: new Map(), appTokens: new Map(),
|
|
17
|
+
applications: new Map(), applicationTrash: new Map(), applicationLogoPurge: new Set(), environments: new Map(), notificationSettings: new Map(), notificationDeliveries: new Map(), notificationWebhooks: new Map(), notificationWebhookJobs: new Map(), applicationStaffAccess: new Map(), appTokens: new Map(),
|
|
18
|
+
platformSignIn: new Map(), accountIdentities: new Map(), accountSsoLogins: new Map(), accountSsoProfiles: new Map(), accountHandoffs: new Map(),
|
|
19
|
+
cliLoginCodes: new Map(),
|
|
13
20
|
signIn: new Map(), appSignIn: new Map(), redirects: new Map(), ssoLogins: new Map(), ssoExchanges: new Map(),
|
|
21
|
+
hostedHumanClients: new Map(), hostedHumanCodes: new Map(),
|
|
22
|
+
hostedEmailCodes: new Map(), hostedSsoProfiles: new Map(), hostedSsoEmailProofs: new Map(),
|
|
14
23
|
serviceCredentials: new Map(), principals: new Map(), workloadCredentials: new Map(), audiences: new Map(),
|
|
15
24
|
roles: new Map(), assignments: new Map(), gatewayRoutes: new Map(),
|
|
16
25
|
directory: emptyDirectory(),
|
|
@@ -27,9 +36,21 @@ function stampApplication(row) {
|
|
|
27
36
|
...row, allowedScopes: [...row.allowedScopes], allowedFeatures: [...row.allowedFeatures],
|
|
28
37
|
productName: row.productName || row.title, logoUrl: row.logoUrl ?? null, accentColor: row.accentColor ?? null,
|
|
29
38
|
signupMode: row.signupMode ?? "open", allowRegistrationWithoutPersonalOrg: row.allowRegistrationWithoutPersonalOrg ?? false,
|
|
39
|
+
waitlistQuestions: row.waitlistQuestionDefinitions?.map(({ prompt }) => prompt) ?? [...(row.waitlistQuestions ?? [])],
|
|
40
|
+
waitlistQuestionDefinitions: clone(row.waitlistQuestionDefinitions ?? null),
|
|
41
|
+
waitlistQuestionLayout: row.waitlistQuestionLayout ?? "form",
|
|
42
|
+
managedSignIn: row.managedSignIn ?? true,
|
|
43
|
+
emailCodeSignIn: row.emailCodeSignIn ?? false,
|
|
44
|
+
authCopy: { ...row.authCopy },
|
|
45
|
+
directoryModel: row.directoryModel ?? "organizations",
|
|
46
|
+
directoryLabels: clone(row.directoryLabels ?? {}),
|
|
47
|
+
onboarding: clone(row.onboarding ?? {}),
|
|
30
48
|
createdAt: asTime(row.createdAt), updatedAt: asTime(row.updatedAt),
|
|
31
49
|
};
|
|
32
50
|
}
|
|
51
|
+
function canSharePlatformSignIn(row) {
|
|
52
|
+
return row.provider !== "oidc" && (row.provider !== "microsoft" || row.directoryId === "common");
|
|
53
|
+
}
|
|
33
54
|
function stampEnvironment(row) {
|
|
34
55
|
return {
|
|
35
56
|
...row, previousKeyExpiresAt: asTimeOrNull(row.previousKeyExpiresAt), createdAt: asTime(row.createdAt), updatedAt: asTime(row.updatedAt),
|
|
@@ -51,16 +72,25 @@ function stampMembership(membership) {
|
|
|
51
72
|
function auditMatches(row, query) {
|
|
52
73
|
if (row.orgId !== query.orgId)
|
|
53
74
|
return false;
|
|
75
|
+
if (query.actorUserId && row.actorUserId !== query.actorUserId)
|
|
76
|
+
return false;
|
|
54
77
|
if (query.action && row.action !== query.action)
|
|
55
78
|
return false;
|
|
56
|
-
if (query.
|
|
79
|
+
if (query.decision && row.decision !== query.decision)
|
|
57
80
|
return false;
|
|
58
|
-
if (query.
|
|
81
|
+
if (query.subject && row.actorUserId !== query.subject && row.actorServiceId !== query.subject && row.agentId !== query.subject && row.target !== query.subject)
|
|
59
82
|
return false;
|
|
83
|
+
if (query.source) {
|
|
84
|
+
const source = "source=" + query.source;
|
|
85
|
+
if (row.detail !== source && !row.detail.startsWith(source + " "))
|
|
86
|
+
return false;
|
|
87
|
+
}
|
|
60
88
|
if (query.from && row.at < query.from)
|
|
61
89
|
return false;
|
|
62
90
|
if (query.to && row.at > query.to)
|
|
63
91
|
return false;
|
|
92
|
+
if (query.before && (row.at > query.before.at || (row.at === query.before.at && row.id >= query.before.id)))
|
|
93
|
+
return false;
|
|
64
94
|
return true;
|
|
65
95
|
}
|
|
66
96
|
function takeExpiring(map, match, at) {
|
|
@@ -74,6 +104,30 @@ function takeExpiring(map, match, at) {
|
|
|
74
104
|
}
|
|
75
105
|
export function createMemoryStore() {
|
|
76
106
|
let tables = empty();
|
|
107
|
+
const activeApplication = (appId) => tables.applicationTrash.has(appId) ? undefined : tables.applications.get(appId);
|
|
108
|
+
function isHostedEnvironmentActive(appId, environmentId) {
|
|
109
|
+
const environment = tables.environments.get(environmentId);
|
|
110
|
+
return environment?.appId === appId && environment.status === "active" && activeApplication(appId)?.status === "active";
|
|
111
|
+
}
|
|
112
|
+
function validateHostedHumanSubject(row) {
|
|
113
|
+
if (tables.environments.get(row.environmentId)?.appId !== row.appId
|
|
114
|
+
|| tables.directory.identities.get(row.subjectId)?.environmentId !== row.environmentId) {
|
|
115
|
+
fail("conflict", "The hosted human session must match its application environment and directory subject.");
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
function findHostedHumanRefreshSession(tokenHash, clientId) {
|
|
119
|
+
const token = tables.hostedHumanRefreshTokens.get(tokenHash);
|
|
120
|
+
const session = token && tables.hostedHumanSessions.get(token.sessionId);
|
|
121
|
+
return session?.clientId === clientId ? session : null;
|
|
122
|
+
}
|
|
123
|
+
function findHostedSsoProfile(challengeHash, browserHash, at) {
|
|
124
|
+
return [...tables.hostedSsoProfiles.values()].find((profile) => profile.challengeHash === challengeHash && profile.browserHash === browserHash && !isExpired(profile.expiresAt, at)
|
|
125
|
+
&& activeApplication(profile.appId)?.orgId === profile.orgId);
|
|
126
|
+
}
|
|
127
|
+
function deleteHostedSsoProfile(id) {
|
|
128
|
+
tables.hostedSsoProfiles.delete(id);
|
|
129
|
+
tables.hostedSsoEmailProofs.delete(id);
|
|
130
|
+
}
|
|
77
131
|
const tx = (run) => {
|
|
78
132
|
const saved = clone(tables);
|
|
79
133
|
try {
|
|
@@ -89,6 +143,35 @@ export function createMemoryStore() {
|
|
|
89
143
|
return row ? clone(row) : null;
|
|
90
144
|
};
|
|
91
145
|
const rows = (map, pred = () => true) => [...map.values()].filter(pred).map((row) => clone(row));
|
|
146
|
+
function removeMatching(map, matches) {
|
|
147
|
+
for (const [id, row] of map)
|
|
148
|
+
if (matches(row))
|
|
149
|
+
map.delete(id);
|
|
150
|
+
}
|
|
151
|
+
function removeHostedHumanSessions(sessionIds) {
|
|
152
|
+
if (!sessionIds.size)
|
|
153
|
+
return;
|
|
154
|
+
removeMatching(tables.hostedHumanRefreshTokens, (row) => sessionIds.has(row.sessionId));
|
|
155
|
+
for (const id of sessionIds)
|
|
156
|
+
tables.hostedHumanSessions.delete(id);
|
|
157
|
+
}
|
|
158
|
+
function pruneHostedHumanCredentials(stamp) {
|
|
159
|
+
function expiredKeys(map) {
|
|
160
|
+
const expired = new Set();
|
|
161
|
+
for (const [key, row] of map) {
|
|
162
|
+
if (isExpired(row.expiresAt, stamp))
|
|
163
|
+
expired.add(key);
|
|
164
|
+
if (expired.size === 250)
|
|
165
|
+
break;
|
|
166
|
+
}
|
|
167
|
+
return expired;
|
|
168
|
+
}
|
|
169
|
+
removeHostedHumanSessions(expiredKeys(tables.hostedHumanSessions));
|
|
170
|
+
for (const key of expiredKeys(tables.hostedHumanSelections))
|
|
171
|
+
tables.hostedHumanSelections.delete(key);
|
|
172
|
+
for (const key of expiredKeys(tables.hostedHumanCodes))
|
|
173
|
+
tables.hostedHumanCodes.delete(key);
|
|
174
|
+
}
|
|
92
175
|
const put = (map, row) => {
|
|
93
176
|
if (map.has(row.id))
|
|
94
177
|
fail("duplicate", "Duplicate key.");
|
|
@@ -100,7 +183,20 @@ export function createMemoryStore() {
|
|
|
100
183
|
map.set(row.id, clone(row));
|
|
101
184
|
};
|
|
102
185
|
const user = (id) => tables.users.get(id) ?? fail("conflict", "User is missing.");
|
|
186
|
+
const writeEmailChallenge = (row) => {
|
|
187
|
+
if (row.purpose !== "verify" && row.purpose !== "reset")
|
|
188
|
+
fail("conflict", "Invalid challenge.");
|
|
189
|
+
if ([...tables.challenges.values()].some((item) => item.tokenHash === row.tokenHash))
|
|
190
|
+
fail("duplicate", "Duplicate key.");
|
|
191
|
+
put(tables.challenges, { ...row, expiresAt: asTime(row.expiresAt), usedAt: asTimeOrNull(row.usedAt), createdAt: asTime(row.createdAt) });
|
|
192
|
+
};
|
|
103
193
|
const org = (id) => tables.orgs.get(id) ?? fail("conflict", "Organization is missing.");
|
|
194
|
+
const checkPendingInvite = (row, at) => {
|
|
195
|
+
if ([...tables.invites.values()].some((candidate) => candidate.id !== row.id && candidate.orgId === row.orgId
|
|
196
|
+
&& candidate.email.toLowerCase() === row.email.toLowerCase() && !candidate.acceptedAt && !candidate.revokedAt
|
|
197
|
+
&& !isExpired(candidate.expiresAt, at)))
|
|
198
|
+
fail("invite_pending", "An open invitation already exists.");
|
|
199
|
+
};
|
|
104
200
|
const client = (id) => tables.clients.get(id) ?? fail("conflict", "Client is missing.");
|
|
105
201
|
const agent = (id) => tables.agents.get(id) ?? fail("conflict", "Agent is missing.");
|
|
106
202
|
const grantRow = (id) => tables.grants.get(id) ?? fail("conflict", "Grant is missing.");
|
|
@@ -122,7 +218,234 @@ export function createMemoryStore() {
|
|
|
122
218
|
}
|
|
123
219
|
return { grant: clone(grant), changed };
|
|
124
220
|
};
|
|
221
|
+
function deleteSession(id) {
|
|
222
|
+
const session = tables.sessions.get(id);
|
|
223
|
+
if (!session)
|
|
224
|
+
return;
|
|
225
|
+
tables.sessions.delete(id);
|
|
226
|
+
for (const [hash, code] of tables.cliLoginCodes) {
|
|
227
|
+
if (code.browserSessionHash === session.secretHash)
|
|
228
|
+
tables.cliLoginCodes.delete(hash);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
function insertAccountIdentity(row) {
|
|
232
|
+
user(row.userId);
|
|
233
|
+
const clash = [...tables.accountIdentities.values()].some((item) => item.provider === row.provider && (item.subject === row.subject || item.userId === row.userId));
|
|
234
|
+
if (clash)
|
|
235
|
+
fail("duplicate", "Duplicate key.");
|
|
236
|
+
put(tables.accountIdentities, { ...row, createdAt: asTime(row.createdAt) });
|
|
237
|
+
}
|
|
238
|
+
function writeAudit(row) {
|
|
239
|
+
if (row.orgId)
|
|
240
|
+
org(row.orgId);
|
|
241
|
+
if (row.actorUserId)
|
|
242
|
+
user(row.actorUserId);
|
|
243
|
+
if (row.agentId)
|
|
244
|
+
agent(row.agentId);
|
|
245
|
+
if (row.actorServiceId) {
|
|
246
|
+
const service = tables.serviceCredentials.get(row.actorServiceId);
|
|
247
|
+
if (!service || service.orgId !== row.orgId || row.actorUserId || row.agentId)
|
|
248
|
+
fail("conflict", "Invalid audit service actor.");
|
|
249
|
+
}
|
|
250
|
+
if (row.decision !== "allow" && row.decision !== "deny")
|
|
251
|
+
fail("conflict", "Invalid audit decision.");
|
|
252
|
+
put(tables.audits, { ...row, at: asTime(row.at) });
|
|
253
|
+
}
|
|
254
|
+
function retireLegacyAppSignIn(appId, provider) {
|
|
255
|
+
const enabled = tables.appSignIn.get(appId);
|
|
256
|
+
if (enabled?.includes(provider))
|
|
257
|
+
tables.appSignIn.set(appId, enabled.filter((item) => item !== provider));
|
|
258
|
+
}
|
|
259
|
+
function listApplicationTrash(orgId) {
|
|
260
|
+
return rows(tables.applications, (app) => app.orgId === orgId && tables.applicationTrash.has(app.id))
|
|
261
|
+
.map((app) => ({ ...app, trashedAt: tables.applicationTrash.get(app.id) }))
|
|
262
|
+
.sort((left, right) => right.trashedAt.localeCompare(left.trashedAt) || right.id.localeCompare(left.id));
|
|
263
|
+
}
|
|
264
|
+
function removeApplicationTenantAccess(orgId, appId, at) {
|
|
265
|
+
const path = `/tenants/${orgId}/apps/${appId}`;
|
|
266
|
+
removeMatching(tables.applicationStaffAccess, (row) => row.appId === appId);
|
|
267
|
+
removeMatching(tables.assignments, (row) => row.orgId === orgId && (row.scope === path || row.scope.startsWith(`${path}/`)));
|
|
268
|
+
for (const service of tables.serviceCredentials.values()) {
|
|
269
|
+
if (service.orgId !== orgId || !service.appIds.includes(appId))
|
|
270
|
+
continue;
|
|
271
|
+
const remaining = service.appIds.filter((id) => id !== appId);
|
|
272
|
+
if (remaining.length)
|
|
273
|
+
service.appIds = remaining;
|
|
274
|
+
else
|
|
275
|
+
service.revokedAt ??= at;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
function resetApplicationSignInAttempts(appId, envIds) {
|
|
279
|
+
removeMatching(tables.ssoLogins, (row) => row.appId === appId);
|
|
280
|
+
removeMatching(tables.ssoExchanges, (row) => row.appId === appId);
|
|
281
|
+
removeMatching(tables.hostedHumanCodes, (row) => row.appId === appId);
|
|
282
|
+
removeMatching(tables.hostedEmailCodes, ({ code }) => envIds.has(code.environmentId));
|
|
283
|
+
for (const profile of tables.hostedSsoProfiles.values()) {
|
|
284
|
+
if (profile.appId === appId)
|
|
285
|
+
deleteHostedSsoProfile(profile.id);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
function purgeApplication(app) {
|
|
289
|
+
const appId = app.id;
|
|
290
|
+
tables.applicationLogoPurge.add(appId);
|
|
291
|
+
const envIds = new Set(rows(tables.environments, (row) => row.appId === appId).map(({ id }) => id));
|
|
292
|
+
const audienceIds = new Set(rows(tables.audiences, (row) => row.appId === appId).map(({ id }) => id));
|
|
293
|
+
const routeResource = `/tenants/${app.orgId}/apps/${appId}`;
|
|
294
|
+
const inEnvironment = (row) => envIds.has(row.environmentId);
|
|
295
|
+
removeApplicationTenantAccess(app.orgId, appId, app.trashedAt);
|
|
296
|
+
resetApplicationSignInAttempts(appId, envIds);
|
|
297
|
+
removeMatching(tables.hostedHumanClients, (row) => row.appId === appId);
|
|
298
|
+
removeHostedHumanSessions(new Set(rows(tables.hostedHumanSessions, inEnvironment).map(({ id }) => id)));
|
|
299
|
+
removeMatching(tables.hostedHumanSelections, inEnvironment);
|
|
300
|
+
removeMatching(tables.appTokens, (row) => row.appId === appId);
|
|
301
|
+
removeMatching(tables.signIn, (row) => row.appId === appId);
|
|
302
|
+
removeMatching(tables.gatewayRoutes, (route) => audienceIds.has(route.audienceId)
|
|
303
|
+
|| (route.orgId === app.orgId && route.resource.replace(/\/+$/, "") === routeResource));
|
|
304
|
+
for (const id of audienceIds)
|
|
305
|
+
tables.audiences.delete(id);
|
|
306
|
+
tables.appSignIn.delete(appId);
|
|
307
|
+
removeMatching(tables.notificationSettings, inEnvironment);
|
|
308
|
+
removeMatching(tables.notificationWebhooks, inEnvironment);
|
|
309
|
+
removeMatching(tables.notificationWebhookJobs, inEnvironment);
|
|
310
|
+
const directory = tables.directory;
|
|
311
|
+
removeMatching(directory.identities, inEnvironment);
|
|
312
|
+
removeMatching(directory.directoryMemberships, inEnvironment);
|
|
313
|
+
removeMatching(directory.permissions, inEnvironment);
|
|
314
|
+
removeMatching(directory.productRoles, inEnvironment);
|
|
315
|
+
removeMatching(directory.groups, inEnvironment);
|
|
316
|
+
removeMatching(directory.groupMembers, inEnvironment);
|
|
317
|
+
removeMatching(directory.bindings, inEnvironment);
|
|
318
|
+
removeMatching(directory.features, inEnvironment);
|
|
319
|
+
removeMatching(directory.featureAssignments, inEnvironment);
|
|
320
|
+
removeMatching(directory.appWaitlist, inEnvironment);
|
|
321
|
+
removeMatching(directory.appWaitlist, (row) => row.appId === appId);
|
|
322
|
+
removeMatching(directory.directoryChallenges, inEnvironment);
|
|
323
|
+
removeMatching(directory.hostedSsoIdentities, inEnvironment);
|
|
324
|
+
removeMatching(directory.workspaces, inEnvironment);
|
|
325
|
+
removeMatching(directory.workspaceMemberships, inEnvironment);
|
|
326
|
+
removeMatching(directory.onboardingResponses, inEnvironment);
|
|
327
|
+
for (const id of envIds) {
|
|
328
|
+
directory.signupRoles.delete(id);
|
|
329
|
+
tables.redirects.delete(id);
|
|
330
|
+
tables.environments.delete(id);
|
|
331
|
+
}
|
|
332
|
+
tables.applicationTrash.delete(appId);
|
|
333
|
+
tables.applications.delete(appId);
|
|
334
|
+
}
|
|
335
|
+
function insertApp(row) {
|
|
336
|
+
org(row.orgId);
|
|
337
|
+
if (row.status !== "active" && row.status !== "disabled")
|
|
338
|
+
fail("conflict", "Invalid application status.");
|
|
339
|
+
put(tables.applications, stampApplication(row));
|
|
340
|
+
}
|
|
341
|
+
function insertAppEnvironment(row) {
|
|
342
|
+
const app = activeApplication(row.appId);
|
|
343
|
+
if (!app)
|
|
344
|
+
fail("conflict", "Application is missing.");
|
|
345
|
+
if (row.orgId !== app.orgId)
|
|
346
|
+
fail("conflict", "Environment tenant does not match the application.");
|
|
347
|
+
if (row.status !== "active" && row.status !== "disabled")
|
|
348
|
+
fail("conflict", "Invalid environment status.");
|
|
349
|
+
if ([...tables.environments.values()].some((item) => item.appId === row.appId && item.name === row.name))
|
|
350
|
+
fail("duplicate", "Environment already exists.");
|
|
351
|
+
put(tables.environments, stampEnvironment(row));
|
|
352
|
+
}
|
|
353
|
+
function saveStaffAccess(row) {
|
|
354
|
+
const app = activeApplication(row.appId);
|
|
355
|
+
const environment = tables.environments.get(row.environmentId);
|
|
356
|
+
if (app?.orgId !== row.orgId || environment?.appId !== row.appId || environment.orgId !== row.orgId) {
|
|
357
|
+
fail("conflict", "Application staff access must match the tenant, application, and environment.");
|
|
358
|
+
}
|
|
359
|
+
if (![...tables.memberships.values()].some((membership) => membership.orgId === row.orgId && membership.userId === row.userId)) {
|
|
360
|
+
fail("conflict", "Application staff access requires tenant membership.");
|
|
361
|
+
}
|
|
362
|
+
if (typeof row.design !== "boolean" || !["none", "read", "manage"].includes(row.runtime)) {
|
|
363
|
+
fail("conflict", "Invalid application staff access level.");
|
|
364
|
+
}
|
|
365
|
+
const current = [...tables.applicationStaffAccess.values()].find((access) => access.environmentId === row.environmentId && access.userId === row.userId);
|
|
366
|
+
const createdAt = asTime(row.createdAt);
|
|
367
|
+
const next = { ...row, id: current?.id ?? row.id, createdAt: current?.createdAt ?? createdAt, updatedAt: asTime(row.updatedAt) };
|
|
368
|
+
if (current)
|
|
369
|
+
replace(tables.applicationStaffAccess, next);
|
|
370
|
+
else
|
|
371
|
+
put(tables.applicationStaffAccess, next);
|
|
372
|
+
return clone(next);
|
|
373
|
+
}
|
|
374
|
+
function hasSsoExchangeToken(exchange) {
|
|
375
|
+
const token = tables.appTokens.get(exchange.tokenId);
|
|
376
|
+
const app = activeApplication(exchange.appId);
|
|
377
|
+
return !!token && !!app && token.orgId === app.orgId && token.appId === exchange.appId
|
|
378
|
+
&& token.environmentId === exchange.environmentId && !token.revokedAt;
|
|
379
|
+
}
|
|
125
380
|
const store = {
|
|
381
|
+
...createMemoryNotificationDeliveries(() => tables.notificationDeliveries),
|
|
382
|
+
async createHostedHumanSession(session, tokenHash, selectionTokenHash) {
|
|
383
|
+
const createdAt = asTime(session.createdAt);
|
|
384
|
+
if (selectionTokenHash !== undefined) {
|
|
385
|
+
const selection = tables.hostedHumanSelections.get(selectionTokenHash);
|
|
386
|
+
if (!selection || selection.clientId !== session.clientId || selection.appId !== session.appId
|
|
387
|
+
|| selection.environmentId !== session.environmentId || selection.subjectId !== session.subjectId
|
|
388
|
+
|| selection.createdAt > createdAt || isExpired(selection.expiresAt, createdAt))
|
|
389
|
+
return false;
|
|
390
|
+
}
|
|
391
|
+
const expiresAt = asTime(session.expiresAt);
|
|
392
|
+
const revokedAt = asTimeOrNull(session.revokedAt);
|
|
393
|
+
validateHostedHumanSubject(session);
|
|
394
|
+
if (expiresAt <= createdAt || (revokedAt && revokedAt < createdAt)
|
|
395
|
+
|| (!session.organizationId && !session.workspaceId)
|
|
396
|
+
|| (session.organizationId && tables.directory.identities.get(session.organizationId)?.environmentId !== session.environmentId)
|
|
397
|
+
|| (session.workspaceId && tables.directory.workspaces.get(session.workspaceId)?.environmentId !== session.environmentId)) {
|
|
398
|
+
fail("conflict", "Invalid hosted human session scope or lifetime.");
|
|
399
|
+
}
|
|
400
|
+
if (tables.hostedHumanRefreshTokens.has(tokenHash))
|
|
401
|
+
fail("duplicate", "Duplicate key.");
|
|
402
|
+
put(tables.hostedHumanSessions, { ...session, createdAt, expiresAt, revokedAt });
|
|
403
|
+
tables.hostedHumanRefreshTokens.set(tokenHash, { sessionId: session.id, usedAt: null });
|
|
404
|
+
if (selectionTokenHash !== undefined)
|
|
405
|
+
tables.hostedHumanSelections.delete(selectionTokenHash);
|
|
406
|
+
return true;
|
|
407
|
+
},
|
|
408
|
+
async hostedHumanSession(id) { return one(tables.hostedHumanSessions, id); },
|
|
409
|
+
async hostedHumanRefreshSession(tokenHash, clientId) { return clone(findHostedHumanRefreshSession(tokenHash, clientId)); },
|
|
410
|
+
async rotateHostedHumanRefreshToken({ tokenHash, nextTokenHash, clientId, at }) {
|
|
411
|
+
const stamp = asTime(at);
|
|
412
|
+
const session = findHostedHumanRefreshSession(tokenHash, clientId);
|
|
413
|
+
if (!session || session.revokedAt || session.createdAt > stamp || isExpired(session.expiresAt, stamp))
|
|
414
|
+
return { status: "invalid" };
|
|
415
|
+
const current = tables.hostedHumanRefreshTokens.get(tokenHash);
|
|
416
|
+
if (current.usedAt) {
|
|
417
|
+
session.revokedAt = stamp;
|
|
418
|
+
return { status: "replayed" };
|
|
419
|
+
}
|
|
420
|
+
if (tables.hostedHumanRefreshTokens.has(nextTokenHash))
|
|
421
|
+
fail("duplicate", "Duplicate key.");
|
|
422
|
+
current.usedAt = stamp;
|
|
423
|
+
tables.hostedHumanRefreshTokens.set(nextTokenHash, { sessionId: session.id, usedAt: null });
|
|
424
|
+
return { status: "rotated", session: clone(session) };
|
|
425
|
+
},
|
|
426
|
+
async revokeHostedHumanSession(id, clientId, at) {
|
|
427
|
+
const stamp = asTime(at);
|
|
428
|
+
const session = tables.hostedHumanSessions.get(id);
|
|
429
|
+
if (session?.clientId !== clientId || session.revokedAt || session.createdAt > stamp)
|
|
430
|
+
return false;
|
|
431
|
+
session.revokedAt = stamp;
|
|
432
|
+
return true;
|
|
433
|
+
},
|
|
434
|
+
async createHostedHumanSelection(selection) {
|
|
435
|
+
const createdAt = asTime(selection.createdAt);
|
|
436
|
+
const expiresAt = asTime(selection.expiresAt);
|
|
437
|
+
validateHostedHumanSubject(selection);
|
|
438
|
+
if (expiresAt <= createdAt)
|
|
439
|
+
fail("conflict", "Invalid hosted human workspace selection lifetime.");
|
|
440
|
+
if (tables.hostedHumanSelections.has(selection.tokenHash))
|
|
441
|
+
fail("duplicate", "Duplicate key.");
|
|
442
|
+
tables.hostedHumanSelections.set(selection.tokenHash, { ...selection, createdAt, expiresAt });
|
|
443
|
+
},
|
|
444
|
+
async hostedHumanSelection(tokenHash, clientId) {
|
|
445
|
+
const selection = tables.hostedHumanSelections.get(tokenHash);
|
|
446
|
+
return selection?.clientId === clientId ? clone(selection) : null;
|
|
447
|
+
},
|
|
448
|
+
async pruneHostedHumanCredentials(at) { pruneHostedHumanCredentials(asTime(at)); },
|
|
126
449
|
async signup(input) {
|
|
127
450
|
tx(() => {
|
|
128
451
|
const nextUser = stampUser(input.user);
|
|
@@ -131,6 +454,18 @@ export function createMemoryStore() {
|
|
|
131
454
|
if (nextMembership.userId !== nextUser.id || nextMembership.orgId !== nextOrg.id || nextMembership.role !== "owner") {
|
|
132
455
|
fail("conflict", "Signup requires the new organization and its owner membership.");
|
|
133
456
|
}
|
|
457
|
+
if (input.platformAdmissionTokenHash) {
|
|
458
|
+
const tokenHash = input.platformAdmissionTokenHash;
|
|
459
|
+
const email = nextUser.email.toLowerCase();
|
|
460
|
+
const invitation = [...tables.directory.platformWaitlist.values()].find((row) => row.email.toLowerCase() === email);
|
|
461
|
+
const challenge = [...tables.directory.directoryChallenges.values()].find((row) => row.tokenHash === tokenHash);
|
|
462
|
+
if (invitation?.status !== "invited" || invitation.tokenHash !== tokenHash || challenge?.purpose !== "admit" ||
|
|
463
|
+
challenge.environmentId !== "platform" || challenge.email.toLowerCase() !== email || challenge.usedAt || isExpired(challenge.expiresAt, nextUser.createdAt)) {
|
|
464
|
+
fail("challenge_invalid", "Waiting list invitation is no longer available.");
|
|
465
|
+
}
|
|
466
|
+
invitation.status = "admitted";
|
|
467
|
+
challenge.usedAt = nextUser.createdAt;
|
|
468
|
+
}
|
|
134
469
|
if ([...tables.users.values()].some((row) => row.email.toLowerCase() === nextUser.email.toLowerCase()))
|
|
135
470
|
fail("duplicate_email", "Email already exists.");
|
|
136
471
|
if ([...tables.orgs.values()].some((row) => row.slug === nextOrg.slug))
|
|
@@ -138,6 +473,18 @@ export function createMemoryStore() {
|
|
|
138
473
|
put(tables.users, nextUser);
|
|
139
474
|
put(tables.orgs, nextOrg);
|
|
140
475
|
put(tables.memberships, nextMembership);
|
|
476
|
+
if (input.accountIdentity) {
|
|
477
|
+
if (input.accountIdentity.userId !== nextUser.id)
|
|
478
|
+
fail("conflict", "The sign-in identity must belong to the new user.");
|
|
479
|
+
insertAccountIdentity(input.accountIdentity);
|
|
480
|
+
}
|
|
481
|
+
if (input.verification) {
|
|
482
|
+
const { challenge, delivery } = input.verification;
|
|
483
|
+
if (challenge.userId !== nextUser.id || challenge.purpose !== "verify")
|
|
484
|
+
fail("conflict", "The verification challenge must belong to the new user.");
|
|
485
|
+
writeEmailChallenge(challenge);
|
|
486
|
+
insertMemoryNotificationDelivery(tables.notificationDeliveries, delivery);
|
|
487
|
+
}
|
|
141
488
|
});
|
|
142
489
|
},
|
|
143
490
|
async createOrg(input) {
|
|
@@ -198,6 +545,10 @@ export function createMemoryStore() {
|
|
|
198
545
|
fail("last_owner", "An organization must keep an owner.");
|
|
199
546
|
}
|
|
200
547
|
tables.memberships.delete(existing.id);
|
|
548
|
+
for (const access of tables.applicationStaffAccess.values()) {
|
|
549
|
+
if (access.orgId === existing.orgId && access.userId === existing.userId)
|
|
550
|
+
tables.applicationStaffAccess.delete(access.id);
|
|
551
|
+
}
|
|
201
552
|
for (const grant of [...tables.grants.values()].filter((row) => row.userId === input.userId && row.orgId === input.orgId))
|
|
202
553
|
revokeGrant(grant.id, at);
|
|
203
554
|
for (const token of tables.longTokens.values()) {
|
|
@@ -209,11 +560,20 @@ export function createMemoryStore() {
|
|
|
209
560
|
async insertChallenge(row) {
|
|
210
561
|
tx(() => {
|
|
211
562
|
user(row.userId);
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
563
|
+
writeEmailChallenge(row);
|
|
564
|
+
});
|
|
565
|
+
},
|
|
566
|
+
async reserveAccountChallenge(row, cooldownSince, delivery) {
|
|
567
|
+
return tx(() => {
|
|
568
|
+
const account = tables.users.get(row.userId);
|
|
569
|
+
if (!account || account.disabledAt || (row.purpose === "verify" && account.emailVerifiedAt))
|
|
570
|
+
return false;
|
|
571
|
+
const since = asTime(cooldownSince);
|
|
572
|
+
if ([...tables.challenges.values()].some((challenge) => challenge.userId === row.userId && challenge.purpose === row.purpose && challenge.createdAt > since))
|
|
573
|
+
return false;
|
|
574
|
+
writeEmailChallenge(row);
|
|
575
|
+
insertMemoryNotificationDelivery(tables.notificationDeliveries, delivery);
|
|
576
|
+
return true;
|
|
217
577
|
});
|
|
218
578
|
},
|
|
219
579
|
async verifyEmail(tokenHash, at) {
|
|
@@ -223,7 +583,7 @@ export function createMemoryStore() {
|
|
|
223
583
|
if (!challenge || challenge.usedAt || isExpired(challenge.expiresAt, stamp))
|
|
224
584
|
fail("challenge_invalid", "Verification link is no longer valid.");
|
|
225
585
|
const account = tables.users.get(challenge.userId);
|
|
226
|
-
if (!account)
|
|
586
|
+
if (!account || account.disabledAt || account.emailVerifiedAt)
|
|
227
587
|
fail("challenge_invalid", "Verification link is no longer valid.");
|
|
228
588
|
account.emailVerifiedAt = stamp;
|
|
229
589
|
challenge.usedAt = stamp;
|
|
@@ -237,20 +597,23 @@ export function createMemoryStore() {
|
|
|
237
597
|
if (!challenge || challenge.usedAt || isExpired(challenge.expiresAt, stamp))
|
|
238
598
|
fail("challenge_invalid", "Reset link is no longer valid.");
|
|
239
599
|
const account = tables.users.get(challenge.userId);
|
|
240
|
-
if (!account)
|
|
600
|
+
if (!account || account.disabledAt)
|
|
241
601
|
fail("challenge_invalid", "Reset link is no longer valid.");
|
|
242
602
|
account.passwordHash = input.passwordHash;
|
|
243
603
|
if (!account.emailVerifiedAt)
|
|
244
604
|
account.emailVerifiedAt = stamp;
|
|
245
|
-
|
|
605
|
+
for (const pending of tables.challenges.values()) {
|
|
606
|
+
if (pending.userId === account.id && pending.purpose === "reset" && !pending.usedAt)
|
|
607
|
+
pending.usedAt = stamp;
|
|
608
|
+
}
|
|
246
609
|
for (const session of [...tables.sessions.values()]) {
|
|
247
610
|
if (session.userId === account.id)
|
|
248
|
-
|
|
611
|
+
deleteSession(session.id);
|
|
249
612
|
}
|
|
250
613
|
return clone(account);
|
|
251
614
|
});
|
|
252
615
|
},
|
|
253
|
-
async insertInvite(row) {
|
|
616
|
+
async insertInvite(row, delivery) {
|
|
254
617
|
tx(() => {
|
|
255
618
|
org(row.orgId);
|
|
256
619
|
user(row.invitedBy);
|
|
@@ -258,14 +621,55 @@ export function createMemoryStore() {
|
|
|
258
621
|
fail("conflict", "Invalid role.");
|
|
259
622
|
if ([...tables.invites.values()].some((item) => item.tokenHash === row.tokenHash))
|
|
260
623
|
fail("duplicate", "Duplicate key.");
|
|
261
|
-
|
|
624
|
+
checkPendingInvite(row, row.createdAt);
|
|
625
|
+
put(tables.invites, { ...row, actions: [...row.actions], expiresAt: asTime(row.expiresAt), acceptedAt: asTimeOrNull(row.acceptedAt), createdAt: asTime(row.createdAt), revokedAt: asTimeOrNull(row.revokedAt ?? null), lastMailRequestedAt: asTimeOrNull(row.lastMailRequestedAt ?? null) });
|
|
626
|
+
insertMemoryNotificationDelivery(tables.notificationDeliveries, delivery);
|
|
627
|
+
});
|
|
628
|
+
},
|
|
629
|
+
async listOpenInvites(orgId, limit, beforeId) {
|
|
630
|
+
const before = beforeId ? tables.invites.get(beforeId) : null;
|
|
631
|
+
if (beforeId && (!before || before.orgId !== orgId))
|
|
632
|
+
return [];
|
|
633
|
+
return rows(tables.invites, (row) => row.orgId === orgId && !row.acceptedAt && !row.revokedAt
|
|
634
|
+
&& (!before || row.createdAt < before.createdAt || (row.createdAt === before.createdAt && row.id < before.id)))
|
|
635
|
+
.sort((a, b) => b.createdAt.localeCompare(a.createdAt) || (a.id === b.id ? 0 : b.id > a.id ? 1 : -1))
|
|
636
|
+
.slice(0, limit);
|
|
637
|
+
},
|
|
638
|
+
async getOrgInvite(orgId, inviteId) {
|
|
639
|
+
const row = tables.invites.get(inviteId);
|
|
640
|
+
return row?.orgId === orgId ? clone(row) : null;
|
|
641
|
+
},
|
|
642
|
+
async rotateInvite(input) {
|
|
643
|
+
return tx(() => {
|
|
644
|
+
const row = tables.invites.get(input.inviteId);
|
|
645
|
+
if (!row || row.orgId !== input.orgId || row.acceptedAt || row.revokedAt)
|
|
646
|
+
return null;
|
|
647
|
+
if ((row.lastMailRequestedAt ?? row.createdAt) > asTime(input.cooldownSince))
|
|
648
|
+
return null;
|
|
649
|
+
checkPendingInvite(row, input.at);
|
|
650
|
+
if ([...tables.invites.values()].some((invite) => invite.tokenHash === input.tokenHash))
|
|
651
|
+
fail("duplicate", "Duplicate key.");
|
|
652
|
+
row.tokenHash = input.tokenHash;
|
|
653
|
+
row.expiresAt = asTime(input.expiresAt);
|
|
654
|
+
row.lastMailRequestedAt = asTime(input.at);
|
|
655
|
+
insertMemoryNotificationDelivery(tables.notificationDeliveries, input.delivery);
|
|
656
|
+
return clone(row);
|
|
657
|
+
});
|
|
658
|
+
},
|
|
659
|
+
async revokeInvite(orgId, inviteId, at) {
|
|
660
|
+
return tx(() => {
|
|
661
|
+
const row = tables.invites.get(inviteId);
|
|
662
|
+
if (!row || row.orgId !== orgId || row.acceptedAt || row.revokedAt)
|
|
663
|
+
return false;
|
|
664
|
+
row.revokedAt = asTime(at);
|
|
665
|
+
return true;
|
|
262
666
|
});
|
|
263
667
|
},
|
|
264
668
|
async acceptInvite(input) {
|
|
265
669
|
return tx(() => {
|
|
266
670
|
const at = asTime(input.at);
|
|
267
671
|
const invite = [...tables.invites.values()].find((row) => row.tokenHash === input.tokenHash);
|
|
268
|
-
if (!invite || invite.acceptedAt || isExpired(invite.expiresAt, at))
|
|
672
|
+
if (!invite || invite.acceptedAt || invite.revokedAt || isExpired(invite.expiresAt, at))
|
|
269
673
|
fail("invite_invalid", "Invite is no longer valid.");
|
|
270
674
|
const account = tables.users.get(input.userId);
|
|
271
675
|
if (!account)
|
|
@@ -305,7 +709,7 @@ export function createMemoryStore() {
|
|
|
305
709
|
replace(tables.sessions, { ...session, expiresAt: asTime(session.expiresAt), createdAt: asTime(session.createdAt) });
|
|
306
710
|
});
|
|
307
711
|
},
|
|
308
|
-
async deleteSession(id) { tx(() =>
|
|
712
|
+
async deleteSession(id) { tx(() => deleteSession(id)); },
|
|
309
713
|
async insertClient(row) {
|
|
310
714
|
tx(() => {
|
|
311
715
|
if (row.authMethod !== "none" && row.authMethod !== "client_secret_basic")
|
|
@@ -591,21 +995,11 @@ export function createMemoryStore() {
|
|
|
591
995
|
return rows(tables.trusts, (row) => row.issuer === issuer && row.audience === audience);
|
|
592
996
|
},
|
|
593
997
|
async insertAudit(row) {
|
|
594
|
-
tx(() =>
|
|
595
|
-
if (row.orgId)
|
|
596
|
-
org(row.orgId);
|
|
597
|
-
if (row.actorUserId)
|
|
598
|
-
user(row.actorUserId);
|
|
599
|
-
if (row.agentId)
|
|
600
|
-
agent(row.agentId);
|
|
601
|
-
if (row.decision !== "allow" && row.decision !== "deny")
|
|
602
|
-
fail("conflict", "Invalid audit decision.");
|
|
603
|
-
put(tables.audits, { ...row, at: asTime(row.at) });
|
|
604
|
-
});
|
|
998
|
+
tx(() => writeAudit(row));
|
|
605
999
|
},
|
|
606
1000
|
async listAudit(query) {
|
|
607
1001
|
return rows(tables.audits, (row) => auditMatches(row, query))
|
|
608
|
-
.sort((left, right) => right.at.localeCompare(left.at) || right.id.
|
|
1002
|
+
.sort((left, right) => right.at.localeCompare(left.at) || (right.id > left.id ? 1 : right.id < left.id ? -1 : 0))
|
|
609
1003
|
.slice(query.offset, query.offset + query.limit);
|
|
610
1004
|
},
|
|
611
1005
|
async getDeniedJti(id) { return one(tables.deniedJtis, id); },
|
|
@@ -615,63 +1009,336 @@ export function createMemoryStore() {
|
|
|
615
1009
|
async insertIdempotency(row) {
|
|
616
1010
|
tx(() => put(tables.idempotency, { ...row, createdAt: asTime(row.createdAt) }));
|
|
617
1011
|
},
|
|
618
|
-
async insertApplication(row) {
|
|
1012
|
+
async insertApplication(row) { tx(() => insertApp(row)); },
|
|
1013
|
+
async registerApplication({ application, environments, creatorAccess, audit }) {
|
|
619
1014
|
tx(() => {
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
1015
|
+
if (!environments.length || environments.some((row) => row.appId !== application.id || row.orgId !== application.orgId)) {
|
|
1016
|
+
fail("conflict", "Registration needs environments for the new application.");
|
|
1017
|
+
}
|
|
1018
|
+
if (creatorAccess && !environments.some((row) => row.name === "development" && row.id === creatorAccess.environmentId
|
|
1019
|
+
&& row.appId === creatorAccess.appId && row.orgId === creatorAccess.orgId)) {
|
|
1020
|
+
fail("conflict", "Creator access must target the new development environment.");
|
|
1021
|
+
}
|
|
1022
|
+
if (audit && audit.orgId !== application.orgId)
|
|
1023
|
+
fail("conflict", "Application registration audit must match the tenant.");
|
|
1024
|
+
insertApp(application);
|
|
1025
|
+
for (const environment of environments)
|
|
1026
|
+
insertAppEnvironment(environment);
|
|
1027
|
+
if (creatorAccess)
|
|
1028
|
+
saveStaffAccess(creatorAccess);
|
|
1029
|
+
if (audit)
|
|
1030
|
+
writeAudit(audit);
|
|
624
1031
|
});
|
|
625
1032
|
},
|
|
626
|
-
async getApplication(id) { return one(tables.applications, id); },
|
|
1033
|
+
async getApplication(id) { return activeApplication(id) ? one(tables.applications, id) : null; },
|
|
627
1034
|
async listApplications(orgId) {
|
|
628
|
-
return rows(tables.applications, (row) => row.orgId === orgId
|
|
1035
|
+
return rows(tables.applications, (row) => row.orgId === orgId && !tables.applicationTrash.has(row.id))
|
|
1036
|
+
.sort((left, right) => right.createdAt.localeCompare(left.createdAt) || right.id.localeCompare(left.id));
|
|
629
1037
|
},
|
|
1038
|
+
async listTrashedApplications(orgId) { return listApplicationTrash(orgId); },
|
|
1039
|
+
async moveApplication({ appId, sourceOrgId, targetOrgId, updatedAt, environmentKeys, audit = [] }) {
|
|
1040
|
+
return tx(() => {
|
|
1041
|
+
const app = activeApplication(appId);
|
|
1042
|
+
if (app?.orgId !== sourceOrgId)
|
|
1043
|
+
fail("not_found", "Application not found.");
|
|
1044
|
+
if (sourceOrgId === targetOrgId)
|
|
1045
|
+
fail("conflict", "Choose a different tenant.");
|
|
1046
|
+
org(targetOrgId);
|
|
1047
|
+
if (audit.some((event) => event.orgId !== sourceOrgId && event.orgId !== targetOrgId)) {
|
|
1048
|
+
fail("conflict", "Application move audit must match the source or destination tenant.");
|
|
1049
|
+
}
|
|
1050
|
+
const stamp = applicationLifecycleTime(updatedAt, app.updatedAt);
|
|
1051
|
+
const environments = rows(tables.environments, (row) => row.appId === appId);
|
|
1052
|
+
const keys = applicationMoveKeys(environments, environmentKeys);
|
|
1053
|
+
const envIds = new Set(keys.keys());
|
|
1054
|
+
const audiences = rows(tables.audiences, (row) => row.appId === appId);
|
|
1055
|
+
const audienceIds = new Set(audiences.map(({ id }) => id));
|
|
1056
|
+
if (rows(tables.audiences, (row) => row.orgId === targetOrgId).some((row) => audiences.some((audience) => audience.identifier === row.identifier))) {
|
|
1057
|
+
fail("conflict", "The destination tenant already uses an audience identifier from this application.");
|
|
1058
|
+
}
|
|
1059
|
+
const sourcePath = `/tenants/${sourceOrgId}/apps/${appId}`;
|
|
1060
|
+
const targetPath = `/tenants/${targetOrgId}/apps/${appId}`;
|
|
1061
|
+
const routes = rows(tables.gatewayRoutes, (row) => audienceIds.has(row.audienceId) || row.resource.replace(/\/+$/, "") === sourcePath);
|
|
1062
|
+
if (routes.some((row) => !audienceIds.has(row.audienceId) || row.resource.replace(/\/+$/, "") !== sourcePath || row.orgId !== sourceOrgId)) {
|
|
1063
|
+
fail("conflict", "An application gateway route uses a shared tenant resource or audience. Update its scope before moving the application.");
|
|
1064
|
+
}
|
|
1065
|
+
removeApplicationTenantAccess(sourceOrgId, appId, stamp);
|
|
1066
|
+
resetApplicationSignInAttempts(appId, envIds);
|
|
1067
|
+
for (const client of tables.hostedHumanClients.values()) {
|
|
1068
|
+
if (client.appId === appId && !client.revokedAt)
|
|
1069
|
+
replace(tables.hostedHumanClients, { ...client, revokedAt: stamp });
|
|
1070
|
+
}
|
|
1071
|
+
for (const environment of environments) {
|
|
1072
|
+
replace(tables.environments, {
|
|
1073
|
+
...environment, ...keys.get(environment.id), orgId: targetOrgId, updatedAt: stamp,
|
|
1074
|
+
previousSecretEnc: null, previousSecretHash: null, previousKeyVersion: null, previousKeyExpiresAt: null,
|
|
1075
|
+
});
|
|
1076
|
+
}
|
|
1077
|
+
for (const row of tables.appTokens.values()) {
|
|
1078
|
+
if (row.appId === appId) {
|
|
1079
|
+
row.orgId = targetOrgId;
|
|
1080
|
+
row.revokedAt ??= stamp;
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
for (const table of [tables.notificationSettings, tables.signIn, tables.directory.identities]) {
|
|
1084
|
+
for (const row of table.values())
|
|
1085
|
+
if (row.appId === appId)
|
|
1086
|
+
row.orgId = targetOrgId;
|
|
1087
|
+
}
|
|
1088
|
+
for (const row of tables.notificationWebhooks.values()) {
|
|
1089
|
+
if (row.appId === appId) {
|
|
1090
|
+
row.orgId = targetOrgId;
|
|
1091
|
+
row.enabled = false;
|
|
1092
|
+
row.updatedAt = stamp;
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
for (const row of tables.directory.productRoles.values()) {
|
|
1096
|
+
if (envIds.has(row.environmentId))
|
|
1097
|
+
row.catalogRoleId = null;
|
|
1098
|
+
}
|
|
1099
|
+
for (const audience of audiences)
|
|
1100
|
+
replace(tables.audiences, { ...audience, orgId: targetOrgId });
|
|
1101
|
+
for (const route of routes)
|
|
1102
|
+
replace(tables.gatewayRoutes, { ...route, orgId: targetOrgId, resource: targetPath });
|
|
1103
|
+
const moved = { ...app, orgId: targetOrgId, updatedAt: stamp };
|
|
1104
|
+
replace(tables.applications, moved);
|
|
1105
|
+
for (const event of audit)
|
|
1106
|
+
writeAudit(event);
|
|
1107
|
+
return clone(moved);
|
|
1108
|
+
});
|
|
1109
|
+
},
|
|
1110
|
+
async trashApplication({ appId, orgId, trashedAt, allowProduction = true, audit }) {
|
|
1111
|
+
return tx(() => {
|
|
1112
|
+
const app = activeApplication(appId);
|
|
1113
|
+
if (app?.orgId !== orgId)
|
|
1114
|
+
fail("not_found", "Application not found.");
|
|
1115
|
+
if (audit && audit.orgId !== orgId)
|
|
1116
|
+
fail("conflict", "Application trash audit must match the tenant.");
|
|
1117
|
+
if (!allowProduction && [...tables.environments.values()].some((row) => row.appId === appId && row.name === "production")) {
|
|
1118
|
+
fail("conflict", "Production access is required to move this application to Trash.");
|
|
1119
|
+
}
|
|
1120
|
+
const stamp = applicationLifecycleTime(trashedAt, app.updatedAt);
|
|
1121
|
+
replace(tables.applications, { ...app, updatedAt: stamp });
|
|
1122
|
+
tables.applicationTrash.set(appId, stamp);
|
|
1123
|
+
if (audit)
|
|
1124
|
+
writeAudit(audit);
|
|
1125
|
+
return clone({ ...app, updatedAt: stamp, trashedAt: stamp });
|
|
1126
|
+
});
|
|
1127
|
+
},
|
|
1128
|
+
async restoreApplication({ appId, orgId, updatedAt, expectedTrashedAt, audit }) {
|
|
1129
|
+
return tx(() => {
|
|
1130
|
+
const app = tables.applications.get(appId);
|
|
1131
|
+
const trashedAt = tables.applicationTrash.get(appId);
|
|
1132
|
+
if (app?.orgId !== orgId || !trashedAt)
|
|
1133
|
+
fail("not_found", "Application not found in Trash.");
|
|
1134
|
+
if (expectedTrashedAt && expectedTrashedAt !== trashedAt)
|
|
1135
|
+
fail("conflict", "Trash changed. Review the application before restoring it.");
|
|
1136
|
+
if (audit && audit.orgId !== orgId)
|
|
1137
|
+
fail("conflict", "Application restore audit must match the tenant.");
|
|
1138
|
+
const restored = { ...app, updatedAt: applicationLifecycleTime(updatedAt, trashedAt) };
|
|
1139
|
+
replace(tables.applications, restored);
|
|
1140
|
+
tables.applicationTrash.delete(appId);
|
|
1141
|
+
if (audit)
|
|
1142
|
+
writeAudit(audit);
|
|
1143
|
+
return clone(restored);
|
|
1144
|
+
});
|
|
1145
|
+
},
|
|
1146
|
+
async emptyApplicationTrash(orgId, confirmed, audit, allowProduction = true) {
|
|
1147
|
+
return tx(() => {
|
|
1148
|
+
org(orgId);
|
|
1149
|
+
if (audit && audit.orgId !== orgId)
|
|
1150
|
+
fail("conflict", "Application trash audit must match the tenant.");
|
|
1151
|
+
const entries = listApplicationTrash(orgId);
|
|
1152
|
+
verifyApplicationTrashSnapshot(entries, confirmed);
|
|
1153
|
+
if (!allowProduction && [...tables.environments.values()].some((row) => row.name === "production" && entries.some(({ id }) => id === row.appId))) {
|
|
1154
|
+
fail("conflict", "Production access is required to empty this Trash.");
|
|
1155
|
+
}
|
|
1156
|
+
for (const entry of entries)
|
|
1157
|
+
purgeApplication(entry);
|
|
1158
|
+
if (audit)
|
|
1159
|
+
writeAudit(audit);
|
|
1160
|
+
return entries.length;
|
|
1161
|
+
});
|
|
1162
|
+
},
|
|
1163
|
+
async listPurgedApplicationLogos() { return [...tables.applicationLogoPurge].sort(); },
|
|
1164
|
+
async clearPurgedApplicationLogo(appId) { tx(() => { tables.applicationLogoPurge.delete(appId); }); },
|
|
630
1165
|
async updateApplication(row) {
|
|
631
|
-
tx(() => {
|
|
632
|
-
const current =
|
|
1166
|
+
return tx(() => {
|
|
1167
|
+
const current = activeApplication(row.id);
|
|
633
1168
|
if (!current)
|
|
634
1169
|
fail("not_found", "Application not found.");
|
|
635
1170
|
if (current.orgId !== row.orgId)
|
|
636
1171
|
fail("conflict", "An application cannot change organization.");
|
|
637
1172
|
if (row.status !== "active" && row.status !== "disabled")
|
|
638
1173
|
fail("conflict", "Invalid application status.");
|
|
639
|
-
|
|
1174
|
+
const nextModel = row.directoryModel;
|
|
1175
|
+
const modelChanges = nextModel !== undefined && nextModel !== current.directoryModel;
|
|
1176
|
+
if (modelChanges) {
|
|
1177
|
+
const directory = tables.directory;
|
|
1178
|
+
const environments = new Set([...tables.environments.values()].filter((item) => item.appId === row.id).map(({ id }) => id));
|
|
1179
|
+
if (nextModel === "people-only") {
|
|
1180
|
+
if ([...directory.identities.values()].some((item) => item.appId === row.id && item.kind === "organization")
|
|
1181
|
+
|| [...directory.workspaces.values()].some((item) => item.appId === row.id)
|
|
1182
|
+
|| [...directory.directoryMemberships.values()].some((item) => environments.has(item.environmentId))
|
|
1183
|
+
|| [...directory.workspaceMemberships.values()].some((item) => environments.has(item.environmentId))
|
|
1184
|
+
|| [...directory.bindings.values()].some((item) => environments.has(item.environmentId) && (item.subjectType === "organization" || item.organizationId !== null))
|
|
1185
|
+
|| [...directory.featureAssignments.values()].some((item) => environments.has(item.environmentId) && item.targetType === "organization")) {
|
|
1186
|
+
fail("conflict", "Existing organizations, workspaces, memberships, or organization access rules prevent using people only.");
|
|
1187
|
+
}
|
|
1188
|
+
}
|
|
1189
|
+
else if ([...directory.workspaces.values()].some((workspace) => workspace.appId === row.id && (nextModel === "organizations" ? workspace.status === "active" : nextModel === "workspaces" && workspace.organizationId !== null))) {
|
|
1190
|
+
fail("conflict", "Existing workspaces are incompatible with this directory model.");
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
const repair = modelChanges && nextModel && nextModel !== "people-only"
|
|
1194
|
+
? repairDirectoryStructure(tables.directory, new Set([...tables.environments.values()].filter((item) => item.appId === row.id).map(({ id }) => id)), { id: row.id, orgId: row.orgId }, nextModel, row.updatedAt)
|
|
1195
|
+
: { organizations: 0, workspaces: 0 };
|
|
1196
|
+
const updatedAt = asTime(row.updatedAt);
|
|
1197
|
+
replace(tables.applications, stampApplication({
|
|
1198
|
+
...row, updatedAt: updatedAt < current.updatedAt ? current.updatedAt : updatedAt,
|
|
1199
|
+
managedSignIn: row.managedSignIn ?? current.managedSignIn, emailCodeSignIn: row.emailCodeSignIn ?? current.emailCodeSignIn,
|
|
1200
|
+
authCopy: row.authCopy ?? current.authCopy,
|
|
1201
|
+
directoryModel: row.directoryModel ?? current.directoryModel, directoryLabels: row.directoryLabels ?? current.directoryLabels,
|
|
1202
|
+
waitlistQuestions: row.waitlistQuestions ?? current.waitlistQuestions,
|
|
1203
|
+
waitlistQuestionDefinitions: row.waitlistQuestionDefinitions === undefined && row.waitlistQuestions === undefined
|
|
1204
|
+
? current.waitlistQuestionDefinitions : row.waitlistQuestionDefinitions,
|
|
1205
|
+
waitlistQuestionLayout: row.waitlistQuestionLayout ?? current.waitlistQuestionLayout,
|
|
1206
|
+
onboarding: { ...current.onboarding, ...row.onboarding },
|
|
1207
|
+
}));
|
|
1208
|
+
return repair;
|
|
640
1209
|
});
|
|
641
1210
|
},
|
|
642
|
-
async insertEnvironment(row) {
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
fail("conflict", "Application is missing.");
|
|
647
|
-
if (row.orgId !== app.orgId)
|
|
648
|
-
fail("conflict", "Environment tenant does not match the application.");
|
|
649
|
-
if (row.status !== "active" && row.status !== "disabled")
|
|
650
|
-
fail("conflict", "Invalid environment status.");
|
|
651
|
-
if ([...tables.environments.values()].some((item) => item.appId === row.appId && item.name === row.name))
|
|
652
|
-
fail("duplicate", "Environment already exists.");
|
|
653
|
-
put(tables.environments, stampEnvironment(row));
|
|
654
|
-
});
|
|
1211
|
+
async insertEnvironment(row) { tx(() => insertAppEnvironment(row)); },
|
|
1212
|
+
async getEnvironment(id) {
|
|
1213
|
+
const row = tables.environments.get(id);
|
|
1214
|
+
return row && activeApplication(row.appId) ? clone(row) : null;
|
|
655
1215
|
},
|
|
656
|
-
async
|
|
657
|
-
|
|
658
|
-
|
|
1216
|
+
async listEnvironments(appId, options) {
|
|
1217
|
+
if (!options?.includeTrashed && !activeApplication(appId))
|
|
1218
|
+
return [];
|
|
1219
|
+
return rows(tables.environments, (row) => row.appId === appId)
|
|
1220
|
+
.sort((left, right) => left.createdAt.localeCompare(right.createdAt) || left.name.localeCompare(right.name));
|
|
659
1221
|
},
|
|
660
1222
|
async updateEnvironment(row) {
|
|
661
1223
|
tx(() => {
|
|
662
1224
|
const current = tables.environments.get(row.id);
|
|
663
|
-
if (!current)
|
|
1225
|
+
if (!current || !activeApplication(current.appId))
|
|
664
1226
|
fail("not_found", "Environment not found.");
|
|
665
1227
|
if (current.appId !== row.appId || current.orgId !== row.orgId || current.name !== row.name)
|
|
666
1228
|
fail("conflict", "An environment cannot change application or name.");
|
|
1229
|
+
const sameKey = row.keyVersion === current.keyVersion && row.secretHash === current.secretHash;
|
|
1230
|
+
const nextKey = row.keyVersion === current.keyVersion + 1 && row.previousSecretHash === current.secretHash;
|
|
1231
|
+
if (!sameKey && !nextKey)
|
|
1232
|
+
fail("conflict", "Environment key changed.");
|
|
667
1233
|
if (row.status !== "active" && row.status !== "disabled")
|
|
668
1234
|
fail("conflict", "Invalid environment status.");
|
|
669
1235
|
replace(tables.environments, stampEnvironment(row));
|
|
670
1236
|
});
|
|
671
1237
|
},
|
|
1238
|
+
async getNotificationSettings(environmentId) {
|
|
1239
|
+
const row = tables.notificationSettings.get(environmentId);
|
|
1240
|
+
return row ? clone(row) : null;
|
|
1241
|
+
},
|
|
1242
|
+
async saveNotificationSettings(row, expectedUpdatedAt, audit) {
|
|
1243
|
+
return tx(() => {
|
|
1244
|
+
const environment = tables.environments.get(row.environmentId);
|
|
1245
|
+
if (!environment || environment.appId !== row.appId || activeApplication(row.appId)?.orgId !== row.orgId)
|
|
1246
|
+
fail("conflict", "Notification settings must match the environment.");
|
|
1247
|
+
if (row.delivery !== "keyrox" && row.delivery !== "both" && row.delivery !== "webhook")
|
|
1248
|
+
fail("conflict", "Invalid notification delivery.");
|
|
1249
|
+
const existing = tables.notificationSettings.get(row.environmentId);
|
|
1250
|
+
if (expectedUpdatedAt !== undefined && (existing?.updatedAt ?? null) !== expectedUpdatedAt)
|
|
1251
|
+
return false;
|
|
1252
|
+
if (row.delivery === "webhook" && ![...tables.notificationWebhooks.values()].some((hook) => hook.environmentId === row.environmentId && hook.enabled))
|
|
1253
|
+
fail("conflict", "webhook_required");
|
|
1254
|
+
tables.notificationSettings.set(row.environmentId, clone({ ...row, templates: { ...row.templates }, updatedAt: asTime(row.updatedAt) }));
|
|
1255
|
+
if (audit) {
|
|
1256
|
+
if (audit.orgId !== row.orgId)
|
|
1257
|
+
fail("conflict", "Notification audit must match the tenant.");
|
|
1258
|
+
writeAudit(audit);
|
|
1259
|
+
}
|
|
1260
|
+
return true;
|
|
1261
|
+
});
|
|
1262
|
+
},
|
|
1263
|
+
async listNotificationWebhooks(environmentId) {
|
|
1264
|
+
return rows(tables.notificationWebhooks, (row) => row.environmentId === environmentId)
|
|
1265
|
+
.sort((left, right) => left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id));
|
|
1266
|
+
},
|
|
1267
|
+
async insertNotificationWebhook(row) {
|
|
1268
|
+
tx(() => {
|
|
1269
|
+
const environment = tables.environments.get(row.environmentId);
|
|
1270
|
+
if (!environment || environment.appId !== row.appId || activeApplication(row.appId)?.orgId !== row.orgId)
|
|
1271
|
+
fail("conflict", "A webhook must match the environment.");
|
|
1272
|
+
if ([...tables.notificationWebhooks.values()].filter((item) => item.environmentId === row.environmentId).length >= 5)
|
|
1273
|
+
fail("conflict", "webhook_limit");
|
|
1274
|
+
put(tables.notificationWebhooks, { ...row, createdAt: asTime(row.createdAt), updatedAt: asTime(row.updatedAt) });
|
|
1275
|
+
});
|
|
1276
|
+
},
|
|
1277
|
+
async updateNotificationWebhook(row) {
|
|
1278
|
+
tx(() => {
|
|
1279
|
+
const current = tables.notificationWebhooks.get(row.id);
|
|
1280
|
+
if (!current || current.environmentId !== row.environmentId || !activeApplication(row.appId))
|
|
1281
|
+
fail("not_found", "Webhook not found.");
|
|
1282
|
+
if (current.appId !== row.appId || current.orgId !== row.orgId)
|
|
1283
|
+
fail("conflict", "A webhook cannot change application.");
|
|
1284
|
+
if (current.enabled && !row.enabled && tables.notificationSettings.get(row.environmentId)?.delivery === "webhook" &&
|
|
1285
|
+
![...tables.notificationWebhooks.values()].some((hook) => hook.environmentId === row.environmentId && hook.id !== row.id && hook.enabled))
|
|
1286
|
+
fail("conflict", "webhook_required");
|
|
1287
|
+
replace(tables.notificationWebhooks, { ...row, createdAt: asTime(current.createdAt), updatedAt: asTime(row.updatedAt) });
|
|
1288
|
+
});
|
|
1289
|
+
},
|
|
1290
|
+
async deleteNotificationWebhook(environmentId, id, orgId) {
|
|
1291
|
+
return tx(() => {
|
|
1292
|
+
const current = tables.notificationWebhooks.get(id);
|
|
1293
|
+
if (!current || current.environmentId !== environmentId || !activeApplication(current.appId) || (orgId && current.orgId !== orgId))
|
|
1294
|
+
return false;
|
|
1295
|
+
if (current.enabled && tables.notificationSettings.get(environmentId)?.delivery === "webhook" &&
|
|
1296
|
+
![...tables.notificationWebhooks.values()].some((hook) => hook.environmentId === environmentId && hook.id !== id && hook.enabled))
|
|
1297
|
+
fail("conflict", "webhook_required");
|
|
1298
|
+
tables.notificationWebhooks.delete(id);
|
|
1299
|
+
return true;
|
|
1300
|
+
});
|
|
1301
|
+
},
|
|
1302
|
+
...createMemoryNotificationWebhookJobs(() => tables.notificationWebhookJobs, (job) => {
|
|
1303
|
+
const app = activeApplication(job.appId);
|
|
1304
|
+
const environment = tables.environments.get(job.environmentId);
|
|
1305
|
+
const hook = tables.notificationWebhooks.get(job.webhookId);
|
|
1306
|
+
const mode = tables.notificationSettings.get(job.environmentId)?.delivery;
|
|
1307
|
+
return app?.orgId === job.organizationId && app.status === "active" && environment?.appId === job.appId
|
|
1308
|
+
&& environment.orgId === job.organizationId && environment.keyVersion === job.environmentKeyVersion
|
|
1309
|
+
&& environment.status === "active" && hook?.enabled === true && hook.environmentId === job.environmentId
|
|
1310
|
+
&& hook.orgId === job.organizationId && mode === (job.keyroxDelivery ? "both" : "webhook");
|
|
1311
|
+
}),
|
|
1312
|
+
async listApplicationStaffAccess(orgId, userId) {
|
|
1313
|
+
return rows(tables.applicationStaffAccess, (row) => row.orgId === orgId && !!activeApplication(row.appId) && (userId === undefined || row.userId === userId))
|
|
1314
|
+
.sort((left, right) => left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id));
|
|
1315
|
+
},
|
|
1316
|
+
async saveApplicationStaffAccess(row, audit) {
|
|
1317
|
+
return tx(() => {
|
|
1318
|
+
if (audit && audit.orgId !== row.orgId)
|
|
1319
|
+
fail("conflict", "Application staff audit must match the tenant.");
|
|
1320
|
+
const saved = saveStaffAccess(row);
|
|
1321
|
+
if (audit)
|
|
1322
|
+
writeAudit(audit);
|
|
1323
|
+
return saved;
|
|
1324
|
+
});
|
|
1325
|
+
},
|
|
1326
|
+
async deleteApplicationStaffAccess(orgId, appId, environmentId, userId, audit) {
|
|
1327
|
+
return tx(() => {
|
|
1328
|
+
if (audit && audit.orgId !== orgId)
|
|
1329
|
+
fail("conflict", "Application staff audit must match the tenant.");
|
|
1330
|
+
const current = [...tables.applicationStaffAccess.values()].find((row) => row.orgId === orgId && row.appId === appId && row.environmentId === environmentId && row.userId === userId);
|
|
1331
|
+
if (!current)
|
|
1332
|
+
return false;
|
|
1333
|
+
tables.applicationStaffAccess.delete(current.id);
|
|
1334
|
+
if (audit)
|
|
1335
|
+
writeAudit(audit);
|
|
1336
|
+
return true;
|
|
1337
|
+
});
|
|
1338
|
+
},
|
|
672
1339
|
async insertAppToken(row) {
|
|
673
1340
|
tx(() => {
|
|
674
|
-
const app =
|
|
1341
|
+
const app = activeApplication(row.appId);
|
|
675
1342
|
if (!app)
|
|
676
1343
|
fail("conflict", "Application is missing.");
|
|
677
1344
|
const environment = tables.environments.get(row.environmentId);
|
|
@@ -679,18 +1346,23 @@ export function createMemoryStore() {
|
|
|
679
1346
|
fail("conflict", "Environment is missing.");
|
|
680
1347
|
if (row.orgId !== app.orgId)
|
|
681
1348
|
fail("conflict", "Token tenant does not match the application.");
|
|
1349
|
+
if (row.payload.keyVersion !== environment.keyVersion)
|
|
1350
|
+
fail("conflict", "The environment key changed during token issuance.");
|
|
682
1351
|
put(tables.appTokens, stampAppToken(row));
|
|
683
1352
|
});
|
|
684
1353
|
},
|
|
685
|
-
async getAppToken(id) {
|
|
1354
|
+
async getAppToken(id) {
|
|
1355
|
+
const token = tables.appTokens.get(id);
|
|
1356
|
+
return token && activeApplication(token.appId) ? clone(token) : null;
|
|
1357
|
+
},
|
|
686
1358
|
async listAppTokens(filter) {
|
|
687
|
-
return rows(tables.appTokens, (row) => (!filter.appId || row.appId === filter.appId) && (!filter.environmentId || row.environmentId === filter.environmentId) && (!filter.identityId || row.ownerIdentityId === filter.identityId) && (!filter.orgId || row.orgId === filter.orgId))
|
|
1359
|
+
return rows(tables.appTokens, (row) => !!activeApplication(row.appId) && (!filter.appId || row.appId === filter.appId) && (!filter.environmentId || row.environmentId === filter.environmentId) && (!filter.identityId || row.ownerIdentityId === filter.identityId) && (!filter.orgId || row.orgId === filter.orgId))
|
|
688
1360
|
.sort((left, right) => right.createdAt.localeCompare(left.createdAt) || right.id.localeCompare(left.id));
|
|
689
1361
|
},
|
|
690
1362
|
async revokeAppToken(id, at) {
|
|
691
1363
|
return tx(() => {
|
|
692
1364
|
const row = tables.appTokens.get(id);
|
|
693
|
-
if (!row)
|
|
1365
|
+
if (!row || !activeApplication(row.appId))
|
|
694
1366
|
return null;
|
|
695
1367
|
if (!row.revokedAt)
|
|
696
1368
|
row.revokedAt = asTime(at);
|
|
@@ -702,7 +1374,7 @@ export function createMemoryStore() {
|
|
|
702
1374
|
const stamp = asTime(at);
|
|
703
1375
|
let count = 0;
|
|
704
1376
|
for (const row of tables.appTokens.values()) {
|
|
705
|
-
if (row.revokedAt)
|
|
1377
|
+
if (row.revokedAt || !activeApplication(row.appId))
|
|
706
1378
|
continue;
|
|
707
1379
|
if (filter.appId && row.appId !== filter.appId)
|
|
708
1380
|
continue;
|
|
@@ -718,44 +1390,346 @@ export function createMemoryStore() {
|
|
|
718
1390
|
return count;
|
|
719
1391
|
});
|
|
720
1392
|
},
|
|
1393
|
+
async savePlatformSignIn(row) {
|
|
1394
|
+
return tx(() => {
|
|
1395
|
+
const existing = [...tables.platformSignIn.values()].find((item) => item.provider === row.provider);
|
|
1396
|
+
const id = existing?.id ?? row.id;
|
|
1397
|
+
const updated = {
|
|
1398
|
+
...row, id, createdAt: asTime(existing?.createdAt ?? row.createdAt),
|
|
1399
|
+
managedForApps: canSharePlatformSignIn(row) && (row.managedForApps ?? existing?.managedForApps ?? false),
|
|
1400
|
+
};
|
|
1401
|
+
tables.platformSignIn.set(id, updated);
|
|
1402
|
+
return { ...updated };
|
|
1403
|
+
});
|
|
1404
|
+
},
|
|
1405
|
+
async setPlatformSignInManaged(provider, managedForApps) {
|
|
1406
|
+
return tx(() => {
|
|
1407
|
+
const current = [...tables.platformSignIn.values()].find((item) => item.provider === provider);
|
|
1408
|
+
if (!current || (managedForApps && !canSharePlatformSignIn(current)))
|
|
1409
|
+
return null;
|
|
1410
|
+
const updated = { ...current, managedForApps };
|
|
1411
|
+
tables.platformSignIn.set(current.id, updated);
|
|
1412
|
+
return { ...updated };
|
|
1413
|
+
});
|
|
1414
|
+
},
|
|
1415
|
+
async listPlatformSignIn() {
|
|
1416
|
+
return rows(tables.platformSignIn).sort((left, right) => left.provider.localeCompare(right.provider));
|
|
1417
|
+
},
|
|
1418
|
+
async deletePlatformSignIn(provider) {
|
|
1419
|
+
tx(() => { for (const row of [...tables.platformSignIn.values()])
|
|
1420
|
+
if (row.provider === provider)
|
|
1421
|
+
tables.platformSignIn.delete(row.id); });
|
|
1422
|
+
},
|
|
1423
|
+
async findAccountIdentity(provider, subject) {
|
|
1424
|
+
return rows(tables.accountIdentities, (row) => row.provider === provider && row.subject === subject)[0] ?? null;
|
|
1425
|
+
},
|
|
1426
|
+
async findUserAccountIdentity(userId, provider) {
|
|
1427
|
+
return rows(tables.accountIdentities, (row) => row.userId === userId && row.provider === provider)[0] ?? null;
|
|
1428
|
+
},
|
|
1429
|
+
async saveAccountIdentity(row) {
|
|
1430
|
+
tx(() => insertAccountIdentity(row));
|
|
1431
|
+
},
|
|
1432
|
+
async insertAccountSsoLogin(row) {
|
|
1433
|
+
tx(() => {
|
|
1434
|
+
if (row.linkUserId)
|
|
1435
|
+
user(row.linkUserId);
|
|
1436
|
+
put(tables.accountSsoLogins, { ...row, nextPath: row.nextPath ?? null, linkUserId: row.linkUserId ?? null, linkSessionHash: row.linkSessionHash ?? null, expiresAt: asTime(row.expiresAt), createdAt: asTime(row.createdAt) });
|
|
1437
|
+
});
|
|
1438
|
+
},
|
|
1439
|
+
async takeAccountSsoLogin(stateHash, at) {
|
|
1440
|
+
return tx(() => takeExpiring(tables.accountSsoLogins, (row) => row.stateHash === stateHash, at));
|
|
1441
|
+
},
|
|
1442
|
+
async insertAccountSsoProfile(row) {
|
|
1443
|
+
tx(() => {
|
|
1444
|
+
const createdAt = asTime(row.createdAt);
|
|
1445
|
+
for (const item of tables.accountSsoProfiles.values()) {
|
|
1446
|
+
if (isExpired(item.expiresAt, createdAt))
|
|
1447
|
+
tables.accountSsoProfiles.delete(item.id);
|
|
1448
|
+
else if (item.codeHash === row.codeHash)
|
|
1449
|
+
fail("duplicate", "Duplicate key.");
|
|
1450
|
+
}
|
|
1451
|
+
put(tables.accountSsoProfiles, { ...row, expiresAt: asTime(row.expiresAt), createdAt });
|
|
1452
|
+
});
|
|
1453
|
+
},
|
|
1454
|
+
async takeAccountSsoProfile(codeHash, browserHash, at) {
|
|
1455
|
+
return tx(() => takeExpiring(tables.accountSsoProfiles, (row) => row.codeHash === codeHash && row.browserHash === browserHash, at));
|
|
1456
|
+
},
|
|
1457
|
+
async insertAccountHandoff(row) { tx(() => put(tables.accountHandoffs, { ...row, expiresAt: asTime(row.expiresAt), createdAt: asTime(row.createdAt) })); },
|
|
1458
|
+
async takeAccountHandoff(codeHash, at) {
|
|
1459
|
+
return tx(() => takeExpiring(tables.accountHandoffs, (row) => row.codeHash === codeHash, at));
|
|
1460
|
+
},
|
|
1461
|
+
async insertCliLoginCode(row) {
|
|
1462
|
+
tx(() => {
|
|
1463
|
+
const createdAt = asTime(row.createdAt);
|
|
1464
|
+
const expiresAt = asTime(row.expiresAt);
|
|
1465
|
+
const session = [...tables.sessions.values()].find((item) => item.secretHash === row.browserSessionHash);
|
|
1466
|
+
if (!session || !tables.users.has(row.userId) || !tables.orgs.has(row.orgId) || isExpired(expiresAt, createdAt))
|
|
1467
|
+
fail("conflict", "Invalid CLI sign-in code.");
|
|
1468
|
+
for (const [hash, code] of tables.cliLoginCodes) {
|
|
1469
|
+
if (isExpired(code.expiresAt, createdAt))
|
|
1470
|
+
tables.cliLoginCodes.delete(hash);
|
|
1471
|
+
}
|
|
1472
|
+
if (tables.cliLoginCodes.has(row.codeHash) || [...tables.cliLoginCodes.values()].some((code) => code.requestHash === row.requestHash)) {
|
|
1473
|
+
fail("duplicate", "Duplicate CLI sign-in code.");
|
|
1474
|
+
}
|
|
1475
|
+
tables.cliLoginCodes.set(row.codeHash, { ...row, createdAt, expiresAt });
|
|
1476
|
+
});
|
|
1477
|
+
},
|
|
1478
|
+
async takeCliLoginCode(codeHash, codeChallenge, redirectUri, at) {
|
|
1479
|
+
return tx(() => {
|
|
1480
|
+
const row = tables.cliLoginCodes.get(codeHash);
|
|
1481
|
+
const timestamp = asTime(at);
|
|
1482
|
+
if (!row || row.consumedAt || row.codeChallenge !== codeChallenge || row.redirectUri !== redirectUri || isExpired(row.expiresAt, timestamp))
|
|
1483
|
+
return null;
|
|
1484
|
+
const consumed = { ...row, consumedAt: timestamp };
|
|
1485
|
+
tables.cliLoginCodes.set(codeHash, consumed);
|
|
1486
|
+
return clone(consumed);
|
|
1487
|
+
});
|
|
1488
|
+
},
|
|
721
1489
|
async saveSignInConnection(row) {
|
|
722
1490
|
tx(() => {
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
1491
|
+
const app = activeApplication(row.appId);
|
|
1492
|
+
if (!app || app.orgId !== row.orgId)
|
|
1493
|
+
fail("conflict", "Application is missing.");
|
|
1494
|
+
const existing = [...tables.signIn.values()].find((item) => item.appId === row.appId && item.provider === row.provider);
|
|
1495
|
+
tables.signIn.set(existing?.id ?? row.id, {
|
|
1496
|
+
...row, id: existing?.id ?? row.id, legacyConnectionId: existing?.legacyConnectionId, createdAt: asTime(existing?.createdAt ?? row.createdAt),
|
|
1497
|
+
});
|
|
1498
|
+
retireLegacyAppSignIn(row.appId, row.provider);
|
|
726
1499
|
});
|
|
727
1500
|
},
|
|
728
|
-
async listSignInConnections(
|
|
729
|
-
|
|
1501
|
+
async listSignInConnections(appId) {
|
|
1502
|
+
if (!activeApplication(appId))
|
|
1503
|
+
return [];
|
|
1504
|
+
return rows(tables.signIn, (row) => row.appId === appId).sort((left, right) => left.provider.localeCompare(right.provider));
|
|
730
1505
|
},
|
|
731
|
-
async
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
1506
|
+
async listOrgSignInConnections(orgId) {
|
|
1507
|
+
return rows(tables.signIn, (row) => row.orgId === orgId && !!activeApplication(row.appId))
|
|
1508
|
+
.sort((left, right) => left.provider.localeCompare(right.provider) || left.appId.localeCompare(right.appId));
|
|
1509
|
+
},
|
|
1510
|
+
async deleteSignInConnection(appId, provider, orgId) {
|
|
1511
|
+
tx(() => {
|
|
1512
|
+
const app = activeApplication(appId);
|
|
1513
|
+
if (!app || (orgId && app.orgId !== orgId))
|
|
1514
|
+
fail("not_found", "Application not found.");
|
|
1515
|
+
for (const row of tables.signIn.values())
|
|
1516
|
+
if (row.appId === appId && row.provider === provider)
|
|
1517
|
+
tables.signIn.delete(row.id);
|
|
1518
|
+
retireLegacyAppSignIn(appId, provider);
|
|
1519
|
+
});
|
|
735
1520
|
},
|
|
736
1521
|
async saveAppSignIn(appId, providers) {
|
|
737
1522
|
tx(() => {
|
|
738
|
-
if (!
|
|
1523
|
+
if (!activeApplication(appId))
|
|
739
1524
|
fail("conflict", "Application is missing.");
|
|
740
1525
|
tables.appSignIn.set(appId, [...providers]);
|
|
741
1526
|
});
|
|
742
1527
|
},
|
|
743
1528
|
async getAppSignIn(appId) { return [...(tables.appSignIn.get(appId) ?? [])]; },
|
|
744
|
-
async saveRedirects(environmentId, uris) {
|
|
1529
|
+
async saveRedirects(environmentId, uris, orgId) {
|
|
745
1530
|
tx(() => {
|
|
746
|
-
|
|
1531
|
+
const environment = tables.environments.get(environmentId);
|
|
1532
|
+
if (!environment || !activeApplication(environment.appId) || (orgId && environment.orgId !== orgId))
|
|
747
1533
|
fail("conflict", "Environment is missing.");
|
|
748
1534
|
tables.redirects.set(environmentId, [...uris]);
|
|
749
1535
|
});
|
|
750
1536
|
},
|
|
751
1537
|
async getRedirects(environmentId) { return [...(tables.redirects.get(environmentId) ?? [])]; },
|
|
752
|
-
async
|
|
1538
|
+
async insertHostedHumanClient(row) {
|
|
1539
|
+
tx(() => {
|
|
1540
|
+
if (activeApplication(row.appId)?.orgId !== row.orgId || tables.environments.get(row.environmentId)?.appId !== row.appId) {
|
|
1541
|
+
fail("not_found", "Application environment not found.");
|
|
1542
|
+
}
|
|
1543
|
+
put(tables.hostedHumanClients, { ...row, createdAt: asTime(row.createdAt), revokedAt: asTimeOrNull(row.revokedAt) });
|
|
1544
|
+
});
|
|
1545
|
+
},
|
|
1546
|
+
async getHostedHumanClient(clientId) { return clone(tables.hostedHumanClients.get(clientId) ?? null); },
|
|
1547
|
+
async listHostedHumanClients(appId, environmentId) {
|
|
1548
|
+
const orgId = activeApplication(appId)?.orgId;
|
|
1549
|
+
return rows(tables.hostedHumanClients, (row) => row.appId === appId && row.environmentId === environmentId && row.orgId === orgId);
|
|
1550
|
+
},
|
|
1551
|
+
async revokeHostedHumanClient(appId, environmentId, clientId, at) {
|
|
1552
|
+
return tx(() => {
|
|
1553
|
+
const client = tables.hostedHumanClients.get(clientId);
|
|
1554
|
+
if (!client || client.appId !== appId || client.environmentId !== environmentId || client.orgId !== activeApplication(appId)?.orgId)
|
|
1555
|
+
return false;
|
|
1556
|
+
if (!client.revokedAt)
|
|
1557
|
+
replace(tables.hostedHumanClients, { ...client, revokedAt: asTime(at) });
|
|
1558
|
+
removeMatching(tables.hostedHumanCodes, (row) => row.clientId === clientId);
|
|
1559
|
+
return true;
|
|
1560
|
+
});
|
|
1561
|
+
},
|
|
1562
|
+
async insertHostedHumanCode(row) {
|
|
1563
|
+
return tx(() => {
|
|
1564
|
+
const client = tables.hostedHumanClients.get(row.clientId);
|
|
1565
|
+
const app = activeApplication(row.appId);
|
|
1566
|
+
const environment = tables.environments.get(row.environmentId);
|
|
1567
|
+
const identity = tables.directory.identities.get(row.identityId);
|
|
1568
|
+
if (!client || client.revokedAt || client.appId !== row.appId || client.environmentId !== row.environmentId
|
|
1569
|
+
|| client.orgId !== row.orgId || client.redirectUri !== row.redirectUri || !identity || identity.appId !== row.appId
|
|
1570
|
+
|| identity.environmentId !== row.environmentId || identity.orgId !== row.orgId || identity.kind !== "user"
|
|
1571
|
+
|| identity.status !== "active" || !identity.email || !identity.emailVerifiedAt || !identity.emailProofAt
|
|
1572
|
+
|| app?.orgId !== row.orgId || app.status !== "active" || app.signupMode !== "waiting-list"
|
|
1573
|
+
|| environment?.appId !== row.appId || environment.orgId !== row.orgId || environment.status !== "active"
|
|
1574
|
+
|| !tables.redirects.get(row.environmentId)?.includes(row.redirectUri))
|
|
1575
|
+
return false;
|
|
1576
|
+
if (tables.hostedHumanCodes.has(row.codeHash))
|
|
1577
|
+
fail("duplicate", "Duplicate sign-in code.");
|
|
1578
|
+
tables.hostedHumanCodes.set(row.codeHash, { ...row, createdAt: asTime(row.createdAt), expiresAt: asTime(row.expiresAt) });
|
|
1579
|
+
return true;
|
|
1580
|
+
});
|
|
1581
|
+
},
|
|
1582
|
+
async takeHostedHumanCode(input) {
|
|
1583
|
+
return tx(() => {
|
|
1584
|
+
const row = tables.hostedHumanCodes.get(input.codeHash);
|
|
1585
|
+
if (!row || row.clientId !== input.clientId || row.appId !== input.appId || row.environmentId !== input.environmentId
|
|
1586
|
+
|| row.redirectUri !== input.redirectUri || row.codeChallenge !== input.codeChallenge || isExpired(row.expiresAt, input.at))
|
|
1587
|
+
return null;
|
|
1588
|
+
const client = tables.hostedHumanClients.get(input.clientId);
|
|
1589
|
+
const app = activeApplication(input.appId);
|
|
1590
|
+
const environment = tables.environments.get(input.environmentId);
|
|
1591
|
+
const identity = tables.directory.identities.get(row.identityId);
|
|
1592
|
+
if (!client || client.revokedAt || client.secretHash !== input.secretHash || client.orgId !== row.orgId
|
|
1593
|
+
|| app?.orgId !== row.orgId || app.status !== "active" || app.signupMode !== "waiting-list"
|
|
1594
|
+
|| environment?.appId !== row.appId || environment.orgId !== row.orgId || environment.status !== "active"
|
|
1595
|
+
|| !tables.redirects.get(row.environmentId)?.includes(row.redirectUri)
|
|
1596
|
+
|| identity?.appId !== row.appId || identity.environmentId !== row.environmentId || identity.orgId !== row.orgId
|
|
1597
|
+
|| identity.kind !== "user" || identity.status !== "active" || !identity.email || !identity.emailVerifiedAt || !identity.emailProofAt)
|
|
1598
|
+
return null;
|
|
1599
|
+
tables.hostedHumanCodes.delete(row.codeHash);
|
|
1600
|
+
return clone(row);
|
|
1601
|
+
});
|
|
1602
|
+
},
|
|
1603
|
+
async insertSsoLogin(row) {
|
|
1604
|
+
const { waitlistInApp, ...login } = row;
|
|
1605
|
+
tx(() => {
|
|
1606
|
+
if (activeApplication(row.appId)?.orgId !== row.orgId)
|
|
1607
|
+
fail("not_found", "Application not found.");
|
|
1608
|
+
put(tables.ssoLogins, {
|
|
1609
|
+
...login, connectionAuthority: row.connectionAuthority ?? null, expiresAt: asTime(row.expiresAt), createdAt: asTime(row.createdAt),
|
|
1610
|
+
...(waitlistInApp ? { waitlistInApp: true } : {}),
|
|
1611
|
+
});
|
|
1612
|
+
});
|
|
1613
|
+
},
|
|
753
1614
|
async takeSsoLogin(stateHash, at) {
|
|
754
|
-
return tx(() => takeExpiring(tables.ssoLogins, (row) => row.stateHash === stateHash, at));
|
|
1615
|
+
return tx(() => takeExpiring(tables.ssoLogins, (row) => row.stateHash === stateHash && activeApplication(row.appId)?.orgId === row.orgId, at));
|
|
1616
|
+
},
|
|
1617
|
+
async putHostedEmailCode(row) {
|
|
1618
|
+
return tx(() => {
|
|
1619
|
+
if (!isHostedEnvironmentActive(row.appId, row.environmentId))
|
|
1620
|
+
return "cooldown";
|
|
1621
|
+
const createdAt = asTime(row.createdAt);
|
|
1622
|
+
const expiresAt = asTime(row.expiresAt);
|
|
1623
|
+
if (isExpired(expiresAt, createdAt))
|
|
1624
|
+
fail("conflict", "Email code expiry must follow issuance.");
|
|
1625
|
+
const email = row.email.trim().toLowerCase();
|
|
1626
|
+
const key = JSON.stringify([row.environmentId, email]);
|
|
1627
|
+
const previous = tables.hostedEmailCodes.get(key);
|
|
1628
|
+
const now = Date.parse(createdAt);
|
|
1629
|
+
const sendHistory = previous?.sendHistory.filter((at) => now - Date.parse(at) < hostedEmailCodePolicy.sendWindowMs) ?? [];
|
|
1630
|
+
if ((previous && (previous.code.challengeHash === row.challengeHash ||
|
|
1631
|
+
now - Date.parse(previous.code.createdAt) < hostedEmailCodePolicy.resendDelayMs)) ||
|
|
1632
|
+
sendHistory.length >= hostedEmailCodePolicy.maxSends)
|
|
1633
|
+
return "cooldown";
|
|
1634
|
+
if ([...tables.hostedEmailCodes.values()].some((state) => state.code.challengeHash === row.challengeHash)) {
|
|
1635
|
+
fail("duplicate", "Duplicate hosted email challenge.");
|
|
1636
|
+
}
|
|
1637
|
+
tables.hostedEmailCodes.set(key, {
|
|
1638
|
+
code: { ...row, email, createdAt, expiresAt },
|
|
1639
|
+
sendHistory: [...sendHistory, createdAt], attemptsRemaining: hostedEmailCodePolicy.maxAttempts, consumed: false,
|
|
1640
|
+
});
|
|
1641
|
+
return "sent";
|
|
1642
|
+
});
|
|
1643
|
+
},
|
|
1644
|
+
async verifyHostedEmailCode(appId, environmentId, challengeHash, codeHash, at) {
|
|
1645
|
+
return tx(() => {
|
|
1646
|
+
if (!isHostedEnvironmentActive(appId, environmentId))
|
|
1647
|
+
return null;
|
|
1648
|
+
const stamp = asTime(at);
|
|
1649
|
+
const state = [...tables.hostedEmailCodes.values()].find(({ code }) => code.appId === appId && code.environmentId === environmentId && code.challengeHash === challengeHash);
|
|
1650
|
+
if (!state || state.consumed || state.attemptsRemaining < 1 || isExpired(state.code.expiresAt, stamp))
|
|
1651
|
+
return null;
|
|
1652
|
+
state.attemptsRemaining -= 1;
|
|
1653
|
+
if (state.code.codeHash !== codeHash)
|
|
1654
|
+
return null;
|
|
1655
|
+
state.consumed = true;
|
|
1656
|
+
return { ...state.code };
|
|
1657
|
+
});
|
|
1658
|
+
},
|
|
1659
|
+
async insertHostedSsoProfile(row) {
|
|
1660
|
+
tx(() => {
|
|
1661
|
+
const app = tables.applications.get(row.appId);
|
|
1662
|
+
const environment = tables.environments.get(row.environmentId);
|
|
1663
|
+
if (!app || app.orgId !== row.orgId || environment?.appId !== app.id)
|
|
1664
|
+
fail("conflict", "Hosted sign-in environment is missing.");
|
|
1665
|
+
if ([...tables.hostedSsoProfiles.values()].some((current) => current.challengeHash === row.challengeHash))
|
|
1666
|
+
fail("duplicate", "Duplicate hosted sign-in challenge.");
|
|
1667
|
+
const { displayName, connectionFingerprint, waitlistInApp, ...profile } = row;
|
|
1668
|
+
put(tables.hostedSsoProfiles, {
|
|
1669
|
+
...profile, expiresAt: asTime(row.expiresAt), createdAt: asTime(row.createdAt),
|
|
1670
|
+
...(displayName != null ? { displayName } : {}),
|
|
1671
|
+
...(connectionFingerprint != null ? { connectionFingerprint } : {}),
|
|
1672
|
+
...(waitlistInApp ? { waitlistInApp: true } : {}),
|
|
1673
|
+
});
|
|
1674
|
+
});
|
|
1675
|
+
},
|
|
1676
|
+
async getHostedSsoProfile(challengeHash, browserHash, at) {
|
|
1677
|
+
const row = findHostedSsoProfile(challengeHash, browserHash, asTime(at));
|
|
1678
|
+
return row ? clone(row) : null;
|
|
1679
|
+
},
|
|
1680
|
+
async takeHostedSsoProfile(challengeHash, browserHash, at) {
|
|
1681
|
+
return tx(() => {
|
|
1682
|
+
const row = findHostedSsoProfile(challengeHash, browserHash, asTime(at));
|
|
1683
|
+
if (!row)
|
|
1684
|
+
return null;
|
|
1685
|
+
deleteHostedSsoProfile(row.id);
|
|
1686
|
+
return clone(row);
|
|
1687
|
+
});
|
|
1688
|
+
},
|
|
1689
|
+
async beginHostedSsoEmail(challengeHash, browserHash, proof) {
|
|
1690
|
+
return tx(() => {
|
|
1691
|
+
const createdAt = asTime(proof.createdAt);
|
|
1692
|
+
const expiresAt = asTime(proof.expiresAt);
|
|
1693
|
+
const profile = findHostedSsoProfile(challengeHash, browserHash, createdAt);
|
|
1694
|
+
if (!profile || profile.email !== null || profile.id !== proof.identityId || profile.environmentId !== proof.environmentId ||
|
|
1695
|
+
proof.purpose !== "hosted-sso-email" || proof.usedAt !== null || isExpired(expiresAt, createdAt))
|
|
1696
|
+
return false;
|
|
1697
|
+
const previous = tables.hostedSsoEmailProofs.get(profile.id);
|
|
1698
|
+
if (previous && Date.parse(createdAt) - Date.parse(previous.createdAt) < 60_000)
|
|
1699
|
+
return false;
|
|
1700
|
+
if ([...tables.hostedSsoEmailProofs].some(([id, row]) => id !== profile.id && row.tokenHash === proof.tokenHash)) {
|
|
1701
|
+
fail("duplicate", "Duplicate hosted sign-in email proof.");
|
|
1702
|
+
}
|
|
1703
|
+
tables.hostedSsoEmailProofs.set(profile.id, { email: proof.email, tokenHash: proof.tokenHash, createdAt, expiresAt });
|
|
1704
|
+
return true;
|
|
1705
|
+
});
|
|
1706
|
+
},
|
|
1707
|
+
async takeHostedSsoEmail(challengeHash, browserHash, tokenHash, at) {
|
|
1708
|
+
return tx(() => {
|
|
1709
|
+
const stamp = asTime(at);
|
|
1710
|
+
const profile = findHostedSsoProfile(challengeHash, browserHash, stamp);
|
|
1711
|
+
if (!profile || profile.email !== null)
|
|
1712
|
+
return null;
|
|
1713
|
+
const proof = tables.hostedSsoEmailProofs.get(profile.id);
|
|
1714
|
+
if (!proof || proof.tokenHash !== tokenHash || isExpired(proof.expiresAt, stamp))
|
|
1715
|
+
return null;
|
|
1716
|
+
deleteHostedSsoProfile(profile.id);
|
|
1717
|
+
return { ...profile, email: proof.email };
|
|
1718
|
+
});
|
|
1719
|
+
},
|
|
1720
|
+
async insertSsoExchange(row) {
|
|
1721
|
+
tx(() => {
|
|
1722
|
+
if (!hasSsoExchangeToken(row))
|
|
1723
|
+
fail("conflict", "The sign-in token is unavailable.");
|
|
1724
|
+
put(tables.ssoExchanges, { ...row, expiresAt: asTime(row.expiresAt), createdAt: asTime(row.createdAt) });
|
|
1725
|
+
});
|
|
1726
|
+
},
|
|
1727
|
+
async getSsoExchange(codeHash, at) {
|
|
1728
|
+
const stamp = asTime(at);
|
|
1729
|
+
return rows(tables.ssoExchanges, (row) => row.codeHash === codeHash && hasSsoExchangeToken(row) && !isExpired(row.expiresAt, stamp))[0] ?? null;
|
|
755
1730
|
},
|
|
756
|
-
async insertSsoExchange(row) { tx(() => put(tables.ssoExchanges, { ...row, expiresAt: asTime(row.expiresAt), createdAt: asTime(row.createdAt) })); },
|
|
757
1731
|
async takeSsoExchange(codeHash, at) {
|
|
758
|
-
return tx(() => takeExpiring(tables.ssoExchanges, (row) => row.codeHash === codeHash, at));
|
|
1732
|
+
return tx(() => takeExpiring(tables.ssoExchanges, (row) => row.codeHash === codeHash && hasSsoExchangeToken(row), at));
|
|
759
1733
|
},
|
|
760
1734
|
async insertServiceCredential(row) {
|
|
761
1735
|
tx(() => {
|
|
@@ -809,14 +1783,19 @@ export function createMemoryStore() {
|
|
|
809
1783
|
async insertAudience(row) {
|
|
810
1784
|
tx(() => {
|
|
811
1785
|
org(row.orgId);
|
|
1786
|
+
if (row.appId && activeApplication(row.appId)?.orgId !== row.orgId)
|
|
1787
|
+
fail("conflict", "Choose an application from this tenant.");
|
|
812
1788
|
if ([...tables.audiences.values()].some((item) => item.orgId === row.orgId && item.identifier === row.identifier))
|
|
813
1789
|
fail("duplicate", "Duplicate key.");
|
|
814
1790
|
put(tables.audiences, { ...row, createdAt: asTime(row.createdAt) });
|
|
815
1791
|
});
|
|
816
1792
|
},
|
|
817
|
-
async listAudiences(orgId) {
|
|
1793
|
+
async listAudiences(orgId) {
|
|
1794
|
+
return rows(tables.audiences, (row) => row.orgId === orgId && (!row.appId || activeApplication(row.appId)?.orgId === orgId));
|
|
1795
|
+
},
|
|
818
1796
|
async findAudience(orgId, identifier) {
|
|
819
|
-
return rows(tables.audiences, (row) => row.orgId === orgId && row.identifier === identifier
|
|
1797
|
+
return rows(tables.audiences, (row) => row.orgId === orgId && row.identifier === identifier
|
|
1798
|
+
&& (!row.appId || activeApplication(row.appId)?.orgId === orgId))[0] ?? null;
|
|
820
1799
|
},
|
|
821
1800
|
async insertRole(row) {
|
|
822
1801
|
tx(() => { org(row.orgId); put(tables.roles, { ...row, actions: [...row.actions], createdAt: asTime(row.createdAt) }); });
|
|
@@ -825,19 +1804,42 @@ export function createMemoryStore() {
|
|
|
825
1804
|
async insertAssignment(row) {
|
|
826
1805
|
tx(() => {
|
|
827
1806
|
org(row.orgId);
|
|
828
|
-
|
|
829
|
-
|
|
1807
|
+
const principal = tables.principals.get(row.principalId);
|
|
1808
|
+
const role = tables.roles.get(row.roleId);
|
|
1809
|
+
if (principal?.orgId !== row.orgId || role?.orgId !== row.orgId)
|
|
1810
|
+
fail("conflict", "Choose an app identity and role from this tenant.");
|
|
1811
|
+
if (!principal.enabled)
|
|
1812
|
+
fail("conflict", "This app identity is disabled.");
|
|
1813
|
+
const scope = row.scope.replace(/\/+$/, "");
|
|
1814
|
+
const duplicate = [...tables.assignments.values()].some((assignment) => assignment.orgId === row.orgId && assignment.principalId === row.principalId && assignment.roleId === row.roleId
|
|
1815
|
+
&& assignment.scope.replace(/\/+$/, "") === scope);
|
|
1816
|
+
if (duplicate)
|
|
1817
|
+
fail("duplicate", "Role assignment already exists.");
|
|
830
1818
|
put(tables.assignments, { ...row, createdAt: asTime(row.createdAt) });
|
|
831
1819
|
});
|
|
832
1820
|
},
|
|
833
1821
|
async listAssignments(orgId, principalId) {
|
|
834
1822
|
return rows(tables.assignments, (row) => row.orgId === orgId && (!principalId || row.principalId === principalId));
|
|
835
1823
|
},
|
|
1824
|
+
async deleteAssignment(id, orgId, audit) {
|
|
1825
|
+
return tx(() => {
|
|
1826
|
+
if (tables.assignments.get(id)?.orgId !== orgId)
|
|
1827
|
+
return false;
|
|
1828
|
+
tables.assignments.delete(id);
|
|
1829
|
+
writeAudit(audit);
|
|
1830
|
+
return true;
|
|
1831
|
+
});
|
|
1832
|
+
},
|
|
836
1833
|
async insertGatewayRoute(row) {
|
|
837
1834
|
tx(() => {
|
|
838
1835
|
org(row.orgId);
|
|
839
|
-
|
|
840
|
-
|
|
1836
|
+
const audience = tables.audiences.get(row.audienceId);
|
|
1837
|
+
if (!audience || audience.orgId !== row.orgId)
|
|
1838
|
+
fail("conflict", "Choose an audience from this tenant.");
|
|
1839
|
+
const appId = appIdFromTenantResource(row.orgId, row.resource);
|
|
1840
|
+
if ((audience.appId && activeApplication(audience.appId)?.orgId !== row.orgId) || (appId && activeApplication(appId)?.orgId !== row.orgId)) {
|
|
1841
|
+
fail("conflict", "Choose an application from this tenant.");
|
|
1842
|
+
}
|
|
841
1843
|
put(tables.gatewayRoutes, { ...row, createdAt: asTime(row.createdAt) });
|
|
842
1844
|
});
|
|
843
1845
|
},
|
|
@@ -850,7 +1852,16 @@ export function createMemoryStore() {
|
|
|
850
1852
|
tables.gatewayRoutes.delete(id);
|
|
851
1853
|
});
|
|
852
1854
|
},
|
|
853
|
-
...bindDirectoryMemory(() => tables.directory, () => tables.users.size, tx)
|
|
1855
|
+
...bindDirectoryMemory(() => tables.directory, () => tables.users.size, tx, (environmentId, includeDisabled = false) => {
|
|
1856
|
+
const environment = tables.environments.get(environmentId);
|
|
1857
|
+
const app = environment && activeApplication(environment.appId);
|
|
1858
|
+
return app && (includeDisabled || (environment?.status === "active" && app.status === "active")) ? app : null;
|
|
1859
|
+
}, (identity, job) => {
|
|
1860
|
+
if (job && (job.environmentId !== identity.environmentId || job.organizationId !== identity.orgId ||
|
|
1861
|
+
job.environmentKeyVersion !== tables.environments.get(identity.environmentId)?.keyVersion))
|
|
1862
|
+
fail("conflict", "Notification scope changed.");
|
|
1863
|
+
insertMemoryNotificationDelivery(tables.notificationDeliveries, job);
|
|
1864
|
+
}),
|
|
854
1865
|
async ping() { },
|
|
855
1866
|
async purgeExpired(at) {
|
|
856
1867
|
tx(() => {
|
|
@@ -858,7 +1869,11 @@ export function createMemoryStore() {
|
|
|
858
1869
|
const seconds = Math.floor(Date.parse(stamp) / 1000);
|
|
859
1870
|
for (const row of [...tables.sessions.values()])
|
|
860
1871
|
if (isExpired(row.expiresAt, stamp))
|
|
861
|
-
|
|
1872
|
+
deleteSession(row.id);
|
|
1873
|
+
pruneHostedHumanCredentials(stamp);
|
|
1874
|
+
for (const [hash, row] of tables.cliLoginCodes)
|
|
1875
|
+
if (isExpired(row.expiresAt, stamp))
|
|
1876
|
+
tables.cliLoginCodes.delete(hash);
|
|
862
1877
|
for (const row of [...tables.challenges.values()])
|
|
863
1878
|
if (isExpired(row.expiresAt, stamp))
|
|
864
1879
|
tables.challenges.delete(row.id);
|
|
@@ -871,6 +1886,14 @@ export function createMemoryStore() {
|
|
|
871
1886
|
for (const row of [...tables.ssoLogins.values()])
|
|
872
1887
|
if (isExpired(row.expiresAt, stamp))
|
|
873
1888
|
tables.ssoLogins.delete(row.id);
|
|
1889
|
+
for (const [key, { code }] of tables.hostedEmailCodes) {
|
|
1890
|
+
if (isExpired(code.expiresAt, stamp) && Date.parse(stamp) - Date.parse(code.createdAt) >= hostedEmailCodePolicy.sendWindowMs) {
|
|
1891
|
+
tables.hostedEmailCodes.delete(key);
|
|
1892
|
+
}
|
|
1893
|
+
}
|
|
1894
|
+
for (const row of [...tables.hostedSsoProfiles.values()])
|
|
1895
|
+
if (isExpired(row.expiresAt, stamp))
|
|
1896
|
+
deleteHostedSsoProfile(row.id);
|
|
874
1897
|
for (const row of [...tables.ssoExchanges.values()])
|
|
875
1898
|
if (isExpired(row.expiresAt, stamp))
|
|
876
1899
|
tables.ssoExchanges.delete(row.id);
|