@x12i/keyrox-store 0.1.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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-access.d.ts +61 -0
- package/dist/directory-access.d.ts.map +1 -0
- package/dist/directory-access.js +20 -0
- package/dist/directory-access.js.map +1 -0
- package/dist/directory-invitation.d.ts +34 -0
- package/dist/directory-invitation.d.ts.map +1 -0
- package/dist/directory-invitation.js +29 -0
- package/dist/directory-invitation.js.map +1 -0
- package/dist/directory-memory.d.ts +21 -4
- package/dist/directory-memory.d.ts.map +1 -1
- package/dist/directory-memory.js +1096 -24
- 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 +48 -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 +8 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -1
- package/dist/memory.d.ts.map +1 -1
- package/dist/memory.js +1115 -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 +188 -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,240 @@ 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
|
+
const directoryModel = activeApplication(session.appId)?.directoryModel ?? "organizations";
|
|
395
|
+
const peopleOnly = directoryModel === "people-only";
|
|
396
|
+
if (expiresAt <= createdAt || (revokedAt && revokedAt < createdAt)
|
|
397
|
+
|| (peopleOnly ? Boolean(session.organizationId || session.workspaceId) : !session.organizationId && !session.workspaceId)
|
|
398
|
+
|| (session.organizationId && tables.directory.identities.get(session.organizationId)?.environmentId !== session.environmentId)
|
|
399
|
+
|| (session.workspaceId && tables.directory.workspaces.get(session.workspaceId)?.environmentId !== session.environmentId)) {
|
|
400
|
+
fail("conflict", "Invalid hosted human session scope or lifetime.");
|
|
401
|
+
}
|
|
402
|
+
if (tables.hostedHumanRefreshTokens.has(tokenHash))
|
|
403
|
+
fail("duplicate", "Duplicate key.");
|
|
404
|
+
put(tables.hostedHumanSessions, { ...session, createdAt, expiresAt, revokedAt });
|
|
405
|
+
tables.hostedHumanRefreshTokens.set(tokenHash, { sessionId: session.id, usedAt: null });
|
|
406
|
+
if (selectionTokenHash !== undefined)
|
|
407
|
+
tables.hostedHumanSelections.delete(selectionTokenHash);
|
|
408
|
+
return true;
|
|
409
|
+
},
|
|
410
|
+
async hostedHumanSession(id) { return one(tables.hostedHumanSessions, id); },
|
|
411
|
+
async listHostedHumanSessions(environmentId, subjectId) {
|
|
412
|
+
return rows(tables.hostedHumanSessions, (row) => row.environmentId === environmentId && row.subjectId === subjectId)
|
|
413
|
+
.sort((left, right) => right.createdAt.localeCompare(left.createdAt) || right.id.localeCompare(left.id));
|
|
414
|
+
},
|
|
415
|
+
async hostedHumanRefreshSession(tokenHash, clientId) { return clone(findHostedHumanRefreshSession(tokenHash, clientId)); },
|
|
416
|
+
async rotateHostedHumanRefreshToken({ tokenHash, nextTokenHash, clientId, at }) {
|
|
417
|
+
const stamp = asTime(at);
|
|
418
|
+
const session = findHostedHumanRefreshSession(tokenHash, clientId);
|
|
419
|
+
if (!session || session.revokedAt || session.createdAt > stamp || isExpired(session.expiresAt, stamp))
|
|
420
|
+
return { status: "invalid" };
|
|
421
|
+
const current = tables.hostedHumanRefreshTokens.get(tokenHash);
|
|
422
|
+
if (current.usedAt) {
|
|
423
|
+
session.revokedAt = stamp;
|
|
424
|
+
return { status: "replayed" };
|
|
425
|
+
}
|
|
426
|
+
if (tables.hostedHumanRefreshTokens.has(nextTokenHash))
|
|
427
|
+
fail("duplicate", "Duplicate key.");
|
|
428
|
+
current.usedAt = stamp;
|
|
429
|
+
tables.hostedHumanRefreshTokens.set(nextTokenHash, { sessionId: session.id, usedAt: null });
|
|
430
|
+
return { status: "rotated", session: clone(session) };
|
|
431
|
+
},
|
|
432
|
+
async revokeHostedHumanSession(id, clientId, at) {
|
|
433
|
+
const stamp = asTime(at);
|
|
434
|
+
const session = tables.hostedHumanSessions.get(id);
|
|
435
|
+
if (session?.clientId !== clientId || session.revokedAt || session.createdAt > stamp)
|
|
436
|
+
return false;
|
|
437
|
+
session.revokedAt = stamp;
|
|
438
|
+
return true;
|
|
439
|
+
},
|
|
440
|
+
async createHostedHumanSelection(selection) {
|
|
441
|
+
const createdAt = asTime(selection.createdAt);
|
|
442
|
+
const expiresAt = asTime(selection.expiresAt);
|
|
443
|
+
validateHostedHumanSubject(selection);
|
|
444
|
+
if (expiresAt <= createdAt)
|
|
445
|
+
fail("conflict", "Invalid hosted human workspace selection lifetime.");
|
|
446
|
+
if (tables.hostedHumanSelections.has(selection.tokenHash))
|
|
447
|
+
fail("duplicate", "Duplicate key.");
|
|
448
|
+
tables.hostedHumanSelections.set(selection.tokenHash, { ...selection, createdAt, expiresAt });
|
|
449
|
+
},
|
|
450
|
+
async hostedHumanSelection(tokenHash, clientId) {
|
|
451
|
+
const selection = tables.hostedHumanSelections.get(tokenHash);
|
|
452
|
+
return selection?.clientId === clientId ? clone(selection) : null;
|
|
453
|
+
},
|
|
454
|
+
async pruneHostedHumanCredentials(at) { pruneHostedHumanCredentials(asTime(at)); },
|
|
126
455
|
async signup(input) {
|
|
127
456
|
tx(() => {
|
|
128
457
|
const nextUser = stampUser(input.user);
|
|
@@ -131,6 +460,18 @@ export function createMemoryStore() {
|
|
|
131
460
|
if (nextMembership.userId !== nextUser.id || nextMembership.orgId !== nextOrg.id || nextMembership.role !== "owner") {
|
|
132
461
|
fail("conflict", "Signup requires the new organization and its owner membership.");
|
|
133
462
|
}
|
|
463
|
+
if (input.platformAdmissionTokenHash) {
|
|
464
|
+
const tokenHash = input.platformAdmissionTokenHash;
|
|
465
|
+
const email = nextUser.email.toLowerCase();
|
|
466
|
+
const invitation = [...tables.directory.platformWaitlist.values()].find((row) => row.email.toLowerCase() === email);
|
|
467
|
+
const challenge = [...tables.directory.directoryChallenges.values()].find((row) => row.tokenHash === tokenHash);
|
|
468
|
+
if (invitation?.status !== "invited" || invitation.tokenHash !== tokenHash || challenge?.purpose !== "admit" ||
|
|
469
|
+
challenge.environmentId !== "platform" || challenge.email.toLowerCase() !== email || challenge.usedAt || isExpired(challenge.expiresAt, nextUser.createdAt)) {
|
|
470
|
+
fail("challenge_invalid", "Waiting list invitation is no longer available.");
|
|
471
|
+
}
|
|
472
|
+
invitation.status = "admitted";
|
|
473
|
+
challenge.usedAt = nextUser.createdAt;
|
|
474
|
+
}
|
|
134
475
|
if ([...tables.users.values()].some((row) => row.email.toLowerCase() === nextUser.email.toLowerCase()))
|
|
135
476
|
fail("duplicate_email", "Email already exists.");
|
|
136
477
|
if ([...tables.orgs.values()].some((row) => row.slug === nextOrg.slug))
|
|
@@ -138,6 +479,18 @@ export function createMemoryStore() {
|
|
|
138
479
|
put(tables.users, nextUser);
|
|
139
480
|
put(tables.orgs, nextOrg);
|
|
140
481
|
put(tables.memberships, nextMembership);
|
|
482
|
+
if (input.accountIdentity) {
|
|
483
|
+
if (input.accountIdentity.userId !== nextUser.id)
|
|
484
|
+
fail("conflict", "The sign-in identity must belong to the new user.");
|
|
485
|
+
insertAccountIdentity(input.accountIdentity);
|
|
486
|
+
}
|
|
487
|
+
if (input.verification) {
|
|
488
|
+
const { challenge, delivery } = input.verification;
|
|
489
|
+
if (challenge.userId !== nextUser.id || challenge.purpose !== "verify")
|
|
490
|
+
fail("conflict", "The verification challenge must belong to the new user.");
|
|
491
|
+
writeEmailChallenge(challenge);
|
|
492
|
+
insertMemoryNotificationDelivery(tables.notificationDeliveries, delivery);
|
|
493
|
+
}
|
|
141
494
|
});
|
|
142
495
|
},
|
|
143
496
|
async createOrg(input) {
|
|
@@ -198,6 +551,10 @@ export function createMemoryStore() {
|
|
|
198
551
|
fail("last_owner", "An organization must keep an owner.");
|
|
199
552
|
}
|
|
200
553
|
tables.memberships.delete(existing.id);
|
|
554
|
+
for (const access of tables.applicationStaffAccess.values()) {
|
|
555
|
+
if (access.orgId === existing.orgId && access.userId === existing.userId)
|
|
556
|
+
tables.applicationStaffAccess.delete(access.id);
|
|
557
|
+
}
|
|
201
558
|
for (const grant of [...tables.grants.values()].filter((row) => row.userId === input.userId && row.orgId === input.orgId))
|
|
202
559
|
revokeGrant(grant.id, at);
|
|
203
560
|
for (const token of tables.longTokens.values()) {
|
|
@@ -209,11 +566,20 @@ export function createMemoryStore() {
|
|
|
209
566
|
async insertChallenge(row) {
|
|
210
567
|
tx(() => {
|
|
211
568
|
user(row.userId);
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
569
|
+
writeEmailChallenge(row);
|
|
570
|
+
});
|
|
571
|
+
},
|
|
572
|
+
async reserveAccountChallenge(row, cooldownSince, delivery) {
|
|
573
|
+
return tx(() => {
|
|
574
|
+
const account = tables.users.get(row.userId);
|
|
575
|
+
if (!account || account.disabledAt || (row.purpose === "verify" && account.emailVerifiedAt))
|
|
576
|
+
return false;
|
|
577
|
+
const since = asTime(cooldownSince);
|
|
578
|
+
if ([...tables.challenges.values()].some((challenge) => challenge.userId === row.userId && challenge.purpose === row.purpose && challenge.createdAt > since))
|
|
579
|
+
return false;
|
|
580
|
+
writeEmailChallenge(row);
|
|
581
|
+
insertMemoryNotificationDelivery(tables.notificationDeliveries, delivery);
|
|
582
|
+
return true;
|
|
217
583
|
});
|
|
218
584
|
},
|
|
219
585
|
async verifyEmail(tokenHash, at) {
|
|
@@ -223,7 +589,7 @@ export function createMemoryStore() {
|
|
|
223
589
|
if (!challenge || challenge.usedAt || isExpired(challenge.expiresAt, stamp))
|
|
224
590
|
fail("challenge_invalid", "Verification link is no longer valid.");
|
|
225
591
|
const account = tables.users.get(challenge.userId);
|
|
226
|
-
if (!account)
|
|
592
|
+
if (!account || account.disabledAt || account.emailVerifiedAt)
|
|
227
593
|
fail("challenge_invalid", "Verification link is no longer valid.");
|
|
228
594
|
account.emailVerifiedAt = stamp;
|
|
229
595
|
challenge.usedAt = stamp;
|
|
@@ -237,20 +603,23 @@ export function createMemoryStore() {
|
|
|
237
603
|
if (!challenge || challenge.usedAt || isExpired(challenge.expiresAt, stamp))
|
|
238
604
|
fail("challenge_invalid", "Reset link is no longer valid.");
|
|
239
605
|
const account = tables.users.get(challenge.userId);
|
|
240
|
-
if (!account)
|
|
606
|
+
if (!account || account.disabledAt)
|
|
241
607
|
fail("challenge_invalid", "Reset link is no longer valid.");
|
|
242
608
|
account.passwordHash = input.passwordHash;
|
|
243
609
|
if (!account.emailVerifiedAt)
|
|
244
610
|
account.emailVerifiedAt = stamp;
|
|
245
|
-
|
|
611
|
+
for (const pending of tables.challenges.values()) {
|
|
612
|
+
if (pending.userId === account.id && pending.purpose === "reset" && !pending.usedAt)
|
|
613
|
+
pending.usedAt = stamp;
|
|
614
|
+
}
|
|
246
615
|
for (const session of [...tables.sessions.values()]) {
|
|
247
616
|
if (session.userId === account.id)
|
|
248
|
-
|
|
617
|
+
deleteSession(session.id);
|
|
249
618
|
}
|
|
250
619
|
return clone(account);
|
|
251
620
|
});
|
|
252
621
|
},
|
|
253
|
-
async insertInvite(row) {
|
|
622
|
+
async insertInvite(row, delivery) {
|
|
254
623
|
tx(() => {
|
|
255
624
|
org(row.orgId);
|
|
256
625
|
user(row.invitedBy);
|
|
@@ -258,14 +627,55 @@ export function createMemoryStore() {
|
|
|
258
627
|
fail("conflict", "Invalid role.");
|
|
259
628
|
if ([...tables.invites.values()].some((item) => item.tokenHash === row.tokenHash))
|
|
260
629
|
fail("duplicate", "Duplicate key.");
|
|
261
|
-
|
|
630
|
+
checkPendingInvite(row, row.createdAt);
|
|
631
|
+
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) });
|
|
632
|
+
insertMemoryNotificationDelivery(tables.notificationDeliveries, delivery);
|
|
633
|
+
});
|
|
634
|
+
},
|
|
635
|
+
async listOpenInvites(orgId, limit, beforeId) {
|
|
636
|
+
const before = beforeId ? tables.invites.get(beforeId) : null;
|
|
637
|
+
if (beforeId && (!before || before.orgId !== orgId))
|
|
638
|
+
return [];
|
|
639
|
+
return rows(tables.invites, (row) => row.orgId === orgId && !row.acceptedAt && !row.revokedAt
|
|
640
|
+
&& (!before || row.createdAt < before.createdAt || (row.createdAt === before.createdAt && row.id < before.id)))
|
|
641
|
+
.sort((a, b) => b.createdAt.localeCompare(a.createdAt) || (a.id === b.id ? 0 : b.id > a.id ? 1 : -1))
|
|
642
|
+
.slice(0, limit);
|
|
643
|
+
},
|
|
644
|
+
async getOrgInvite(orgId, inviteId) {
|
|
645
|
+
const row = tables.invites.get(inviteId);
|
|
646
|
+
return row?.orgId === orgId ? clone(row) : null;
|
|
647
|
+
},
|
|
648
|
+
async rotateInvite(input) {
|
|
649
|
+
return tx(() => {
|
|
650
|
+
const row = tables.invites.get(input.inviteId);
|
|
651
|
+
if (!row || row.orgId !== input.orgId || row.acceptedAt || row.revokedAt)
|
|
652
|
+
return null;
|
|
653
|
+
if ((row.lastMailRequestedAt ?? row.createdAt) > asTime(input.cooldownSince))
|
|
654
|
+
return null;
|
|
655
|
+
checkPendingInvite(row, input.at);
|
|
656
|
+
if ([...tables.invites.values()].some((invite) => invite.tokenHash === input.tokenHash))
|
|
657
|
+
fail("duplicate", "Duplicate key.");
|
|
658
|
+
row.tokenHash = input.tokenHash;
|
|
659
|
+
row.expiresAt = asTime(input.expiresAt);
|
|
660
|
+
row.lastMailRequestedAt = asTime(input.at);
|
|
661
|
+
insertMemoryNotificationDelivery(tables.notificationDeliveries, input.delivery);
|
|
662
|
+
return clone(row);
|
|
663
|
+
});
|
|
664
|
+
},
|
|
665
|
+
async revokeInvite(orgId, inviteId, at) {
|
|
666
|
+
return tx(() => {
|
|
667
|
+
const row = tables.invites.get(inviteId);
|
|
668
|
+
if (!row || row.orgId !== orgId || row.acceptedAt || row.revokedAt)
|
|
669
|
+
return false;
|
|
670
|
+
row.revokedAt = asTime(at);
|
|
671
|
+
return true;
|
|
262
672
|
});
|
|
263
673
|
},
|
|
264
674
|
async acceptInvite(input) {
|
|
265
675
|
return tx(() => {
|
|
266
676
|
const at = asTime(input.at);
|
|
267
677
|
const invite = [...tables.invites.values()].find((row) => row.tokenHash === input.tokenHash);
|
|
268
|
-
if (!invite || invite.acceptedAt || isExpired(invite.expiresAt, at))
|
|
678
|
+
if (!invite || invite.acceptedAt || invite.revokedAt || isExpired(invite.expiresAt, at))
|
|
269
679
|
fail("invite_invalid", "Invite is no longer valid.");
|
|
270
680
|
const account = tables.users.get(input.userId);
|
|
271
681
|
if (!account)
|
|
@@ -305,7 +715,7 @@ export function createMemoryStore() {
|
|
|
305
715
|
replace(tables.sessions, { ...session, expiresAt: asTime(session.expiresAt), createdAt: asTime(session.createdAt) });
|
|
306
716
|
});
|
|
307
717
|
},
|
|
308
|
-
async deleteSession(id) { tx(() =>
|
|
718
|
+
async deleteSession(id) { tx(() => deleteSession(id)); },
|
|
309
719
|
async insertClient(row) {
|
|
310
720
|
tx(() => {
|
|
311
721
|
if (row.authMethod !== "none" && row.authMethod !== "client_secret_basic")
|
|
@@ -591,21 +1001,11 @@ export function createMemoryStore() {
|
|
|
591
1001
|
return rows(tables.trusts, (row) => row.issuer === issuer && row.audience === audience);
|
|
592
1002
|
},
|
|
593
1003
|
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
|
-
});
|
|
1004
|
+
tx(() => writeAudit(row));
|
|
605
1005
|
},
|
|
606
1006
|
async listAudit(query) {
|
|
607
1007
|
return rows(tables.audits, (row) => auditMatches(row, query))
|
|
608
|
-
.sort((left, right) => right.at.localeCompare(left.at) || right.id.
|
|
1008
|
+
.sort((left, right) => right.at.localeCompare(left.at) || (right.id > left.id ? 1 : right.id < left.id ? -1 : 0))
|
|
609
1009
|
.slice(query.offset, query.offset + query.limit);
|
|
610
1010
|
},
|
|
611
1011
|
async getDeniedJti(id) { return one(tables.deniedJtis, id); },
|
|
@@ -615,63 +1015,336 @@ export function createMemoryStore() {
|
|
|
615
1015
|
async insertIdempotency(row) {
|
|
616
1016
|
tx(() => put(tables.idempotency, { ...row, createdAt: asTime(row.createdAt) }));
|
|
617
1017
|
},
|
|
618
|
-
async insertApplication(row) {
|
|
1018
|
+
async insertApplication(row) { tx(() => insertApp(row)); },
|
|
1019
|
+
async registerApplication({ application, environments, creatorAccess, audit }) {
|
|
619
1020
|
tx(() => {
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
1021
|
+
if (!environments.length || environments.some((row) => row.appId !== application.id || row.orgId !== application.orgId)) {
|
|
1022
|
+
fail("conflict", "Registration needs environments for the new application.");
|
|
1023
|
+
}
|
|
1024
|
+
if (creatorAccess && !environments.some((row) => row.name === "development" && row.id === creatorAccess.environmentId
|
|
1025
|
+
&& row.appId === creatorAccess.appId && row.orgId === creatorAccess.orgId)) {
|
|
1026
|
+
fail("conflict", "Creator access must target the new development environment.");
|
|
1027
|
+
}
|
|
1028
|
+
if (audit && audit.orgId !== application.orgId)
|
|
1029
|
+
fail("conflict", "Application registration audit must match the tenant.");
|
|
1030
|
+
insertApp(application);
|
|
1031
|
+
for (const environment of environments)
|
|
1032
|
+
insertAppEnvironment(environment);
|
|
1033
|
+
if (creatorAccess)
|
|
1034
|
+
saveStaffAccess(creatorAccess);
|
|
1035
|
+
if (audit)
|
|
1036
|
+
writeAudit(audit);
|
|
624
1037
|
});
|
|
625
1038
|
},
|
|
626
|
-
async getApplication(id) { return one(tables.applications, id); },
|
|
1039
|
+
async getApplication(id) { return activeApplication(id) ? one(tables.applications, id) : null; },
|
|
627
1040
|
async listApplications(orgId) {
|
|
628
|
-
return rows(tables.applications, (row) => row.orgId === orgId
|
|
1041
|
+
return rows(tables.applications, (row) => row.orgId === orgId && !tables.applicationTrash.has(row.id))
|
|
1042
|
+
.sort((left, right) => right.createdAt.localeCompare(left.createdAt) || right.id.localeCompare(left.id));
|
|
1043
|
+
},
|
|
1044
|
+
async listTrashedApplications(orgId) { return listApplicationTrash(orgId); },
|
|
1045
|
+
async moveApplication({ appId, sourceOrgId, targetOrgId, updatedAt, environmentKeys, audit = [] }) {
|
|
1046
|
+
return tx(() => {
|
|
1047
|
+
const app = activeApplication(appId);
|
|
1048
|
+
if (app?.orgId !== sourceOrgId)
|
|
1049
|
+
fail("not_found", "Application not found.");
|
|
1050
|
+
if (sourceOrgId === targetOrgId)
|
|
1051
|
+
fail("conflict", "Choose a different tenant.");
|
|
1052
|
+
org(targetOrgId);
|
|
1053
|
+
if (audit.some((event) => event.orgId !== sourceOrgId && event.orgId !== targetOrgId)) {
|
|
1054
|
+
fail("conflict", "Application move audit must match the source or destination tenant.");
|
|
1055
|
+
}
|
|
1056
|
+
const stamp = applicationLifecycleTime(updatedAt, app.updatedAt);
|
|
1057
|
+
const environments = rows(tables.environments, (row) => row.appId === appId);
|
|
1058
|
+
const keys = applicationMoveKeys(environments, environmentKeys);
|
|
1059
|
+
const envIds = new Set(keys.keys());
|
|
1060
|
+
const audiences = rows(tables.audiences, (row) => row.appId === appId);
|
|
1061
|
+
const audienceIds = new Set(audiences.map(({ id }) => id));
|
|
1062
|
+
if (rows(tables.audiences, (row) => row.orgId === targetOrgId).some((row) => audiences.some((audience) => audience.identifier === row.identifier))) {
|
|
1063
|
+
fail("conflict", "The destination tenant already uses an audience identifier from this application.");
|
|
1064
|
+
}
|
|
1065
|
+
const sourcePath = `/tenants/${sourceOrgId}/apps/${appId}`;
|
|
1066
|
+
const targetPath = `/tenants/${targetOrgId}/apps/${appId}`;
|
|
1067
|
+
const routes = rows(tables.gatewayRoutes, (row) => audienceIds.has(row.audienceId) || row.resource.replace(/\/+$/, "") === sourcePath);
|
|
1068
|
+
if (routes.some((row) => !audienceIds.has(row.audienceId) || row.resource.replace(/\/+$/, "") !== sourcePath || row.orgId !== sourceOrgId)) {
|
|
1069
|
+
fail("conflict", "An application gateway route uses a shared tenant resource or audience. Update its scope before moving the application.");
|
|
1070
|
+
}
|
|
1071
|
+
removeApplicationTenantAccess(sourceOrgId, appId, stamp);
|
|
1072
|
+
resetApplicationSignInAttempts(appId, envIds);
|
|
1073
|
+
for (const client of tables.hostedHumanClients.values()) {
|
|
1074
|
+
if (client.appId === appId && !client.revokedAt)
|
|
1075
|
+
replace(tables.hostedHumanClients, { ...client, revokedAt: stamp });
|
|
1076
|
+
}
|
|
1077
|
+
for (const environment of environments) {
|
|
1078
|
+
replace(tables.environments, {
|
|
1079
|
+
...environment, ...keys.get(environment.id), orgId: targetOrgId, updatedAt: stamp,
|
|
1080
|
+
previousSecretEnc: null, previousSecretHash: null, previousKeyVersion: null, previousKeyExpiresAt: null,
|
|
1081
|
+
});
|
|
1082
|
+
}
|
|
1083
|
+
for (const row of tables.appTokens.values()) {
|
|
1084
|
+
if (row.appId === appId) {
|
|
1085
|
+
row.orgId = targetOrgId;
|
|
1086
|
+
row.revokedAt ??= stamp;
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
for (const table of [tables.notificationSettings, tables.signIn, tables.directory.identities]) {
|
|
1090
|
+
for (const row of table.values())
|
|
1091
|
+
if (row.appId === appId)
|
|
1092
|
+
row.orgId = targetOrgId;
|
|
1093
|
+
}
|
|
1094
|
+
for (const row of tables.notificationWebhooks.values()) {
|
|
1095
|
+
if (row.appId === appId) {
|
|
1096
|
+
row.orgId = targetOrgId;
|
|
1097
|
+
row.enabled = false;
|
|
1098
|
+
row.updatedAt = stamp;
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
for (const row of tables.directory.productRoles.values()) {
|
|
1102
|
+
if (envIds.has(row.environmentId))
|
|
1103
|
+
row.catalogRoleId = null;
|
|
1104
|
+
}
|
|
1105
|
+
for (const audience of audiences)
|
|
1106
|
+
replace(tables.audiences, { ...audience, orgId: targetOrgId });
|
|
1107
|
+
for (const route of routes)
|
|
1108
|
+
replace(tables.gatewayRoutes, { ...route, orgId: targetOrgId, resource: targetPath });
|
|
1109
|
+
const moved = { ...app, orgId: targetOrgId, updatedAt: stamp };
|
|
1110
|
+
replace(tables.applications, moved);
|
|
1111
|
+
for (const event of audit)
|
|
1112
|
+
writeAudit(event);
|
|
1113
|
+
return clone(moved);
|
|
1114
|
+
});
|
|
629
1115
|
},
|
|
1116
|
+
async trashApplication({ appId, orgId, trashedAt, allowProduction = true, audit }) {
|
|
1117
|
+
return tx(() => {
|
|
1118
|
+
const app = activeApplication(appId);
|
|
1119
|
+
if (app?.orgId !== orgId)
|
|
1120
|
+
fail("not_found", "Application not found.");
|
|
1121
|
+
if (audit && audit.orgId !== orgId)
|
|
1122
|
+
fail("conflict", "Application trash audit must match the tenant.");
|
|
1123
|
+
if (!allowProduction && [...tables.environments.values()].some((row) => row.appId === appId && row.name === "production")) {
|
|
1124
|
+
fail("conflict", "Production access is required to move this application to Trash.");
|
|
1125
|
+
}
|
|
1126
|
+
const stamp = applicationLifecycleTime(trashedAt, app.updatedAt);
|
|
1127
|
+
replace(tables.applications, { ...app, updatedAt: stamp });
|
|
1128
|
+
tables.applicationTrash.set(appId, stamp);
|
|
1129
|
+
if (audit)
|
|
1130
|
+
writeAudit(audit);
|
|
1131
|
+
return clone({ ...app, updatedAt: stamp, trashedAt: stamp });
|
|
1132
|
+
});
|
|
1133
|
+
},
|
|
1134
|
+
async restoreApplication({ appId, orgId, updatedAt, expectedTrashedAt, audit }) {
|
|
1135
|
+
return tx(() => {
|
|
1136
|
+
const app = tables.applications.get(appId);
|
|
1137
|
+
const trashedAt = tables.applicationTrash.get(appId);
|
|
1138
|
+
if (app?.orgId !== orgId || !trashedAt)
|
|
1139
|
+
fail("not_found", "Application not found in Trash.");
|
|
1140
|
+
if (expectedTrashedAt && expectedTrashedAt !== trashedAt)
|
|
1141
|
+
fail("conflict", "Trash changed. Review the application before restoring it.");
|
|
1142
|
+
if (audit && audit.orgId !== orgId)
|
|
1143
|
+
fail("conflict", "Application restore audit must match the tenant.");
|
|
1144
|
+
const restored = { ...app, updatedAt: applicationLifecycleTime(updatedAt, trashedAt) };
|
|
1145
|
+
replace(tables.applications, restored);
|
|
1146
|
+
tables.applicationTrash.delete(appId);
|
|
1147
|
+
if (audit)
|
|
1148
|
+
writeAudit(audit);
|
|
1149
|
+
return clone(restored);
|
|
1150
|
+
});
|
|
1151
|
+
},
|
|
1152
|
+
async emptyApplicationTrash(orgId, confirmed, audit, allowProduction = true) {
|
|
1153
|
+
return tx(() => {
|
|
1154
|
+
org(orgId);
|
|
1155
|
+
if (audit && audit.orgId !== orgId)
|
|
1156
|
+
fail("conflict", "Application trash audit must match the tenant.");
|
|
1157
|
+
const entries = listApplicationTrash(orgId);
|
|
1158
|
+
verifyApplicationTrashSnapshot(entries, confirmed);
|
|
1159
|
+
if (!allowProduction && [...tables.environments.values()].some((row) => row.name === "production" && entries.some(({ id }) => id === row.appId))) {
|
|
1160
|
+
fail("conflict", "Production access is required to empty this Trash.");
|
|
1161
|
+
}
|
|
1162
|
+
for (const entry of entries)
|
|
1163
|
+
purgeApplication(entry);
|
|
1164
|
+
if (audit)
|
|
1165
|
+
writeAudit(audit);
|
|
1166
|
+
return entries.length;
|
|
1167
|
+
});
|
|
1168
|
+
},
|
|
1169
|
+
async listPurgedApplicationLogos() { return [...tables.applicationLogoPurge].sort(); },
|
|
1170
|
+
async clearPurgedApplicationLogo(appId) { tx(() => { tables.applicationLogoPurge.delete(appId); }); },
|
|
630
1171
|
async updateApplication(row) {
|
|
631
|
-
tx(() => {
|
|
632
|
-
const current =
|
|
1172
|
+
return tx(() => {
|
|
1173
|
+
const current = activeApplication(row.id);
|
|
633
1174
|
if (!current)
|
|
634
1175
|
fail("not_found", "Application not found.");
|
|
635
1176
|
if (current.orgId !== row.orgId)
|
|
636
1177
|
fail("conflict", "An application cannot change organization.");
|
|
637
1178
|
if (row.status !== "active" && row.status !== "disabled")
|
|
638
1179
|
fail("conflict", "Invalid application status.");
|
|
639
|
-
|
|
1180
|
+
const nextModel = row.directoryModel;
|
|
1181
|
+
const modelChanges = nextModel !== undefined && nextModel !== current.directoryModel;
|
|
1182
|
+
if (modelChanges) {
|
|
1183
|
+
const directory = tables.directory;
|
|
1184
|
+
const environments = new Set([...tables.environments.values()].filter((item) => item.appId === row.id).map(({ id }) => id));
|
|
1185
|
+
if (nextModel === "people-only") {
|
|
1186
|
+
if ([...directory.identities.values()].some((item) => item.appId === row.id && item.kind === "organization")
|
|
1187
|
+
|| [...directory.workspaces.values()].some((item) => item.appId === row.id)
|
|
1188
|
+
|| [...directory.directoryMemberships.values()].some((item) => environments.has(item.environmentId))
|
|
1189
|
+
|| [...directory.workspaceMemberships.values()].some((item) => environments.has(item.environmentId))
|
|
1190
|
+
|| [...directory.bindings.values()].some((item) => environments.has(item.environmentId) && (item.subjectType === "organization" || item.organizationId !== null))
|
|
1191
|
+
|| [...directory.featureAssignments.values()].some((item) => environments.has(item.environmentId) && item.targetType === "organization")) {
|
|
1192
|
+
fail("conflict", "Existing organizations, workspaces, memberships, or organization access rules prevent using people only.");
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
else if ([...directory.workspaces.values()].some((workspace) => workspace.appId === row.id && (nextModel === "organizations" ? workspace.status === "active" : nextModel === "workspaces" && workspace.organizationId !== null))) {
|
|
1196
|
+
fail("conflict", "Existing workspaces are incompatible with this directory model.");
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
const repair = modelChanges && nextModel && nextModel !== "people-only"
|
|
1200
|
+
? 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)
|
|
1201
|
+
: { organizations: 0, workspaces: 0 };
|
|
1202
|
+
const updatedAt = asTime(row.updatedAt);
|
|
1203
|
+
replace(tables.applications, stampApplication({
|
|
1204
|
+
...row, updatedAt: updatedAt < current.updatedAt ? current.updatedAt : updatedAt,
|
|
1205
|
+
managedSignIn: row.managedSignIn ?? current.managedSignIn, emailCodeSignIn: row.emailCodeSignIn ?? current.emailCodeSignIn,
|
|
1206
|
+
authCopy: row.authCopy ?? current.authCopy,
|
|
1207
|
+
directoryModel: row.directoryModel ?? current.directoryModel, directoryLabels: row.directoryLabels ?? current.directoryLabels,
|
|
1208
|
+
waitlistQuestions: row.waitlistQuestions ?? current.waitlistQuestions,
|
|
1209
|
+
waitlistQuestionDefinitions: row.waitlistQuestionDefinitions === undefined && row.waitlistQuestions === undefined
|
|
1210
|
+
? current.waitlistQuestionDefinitions : row.waitlistQuestionDefinitions,
|
|
1211
|
+
waitlistQuestionLayout: row.waitlistQuestionLayout ?? current.waitlistQuestionLayout,
|
|
1212
|
+
onboarding: { ...current.onboarding, ...row.onboarding },
|
|
1213
|
+
}));
|
|
1214
|
+
return repair;
|
|
640
1215
|
});
|
|
641
1216
|
},
|
|
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
|
-
});
|
|
1217
|
+
async insertEnvironment(row) { tx(() => insertAppEnvironment(row)); },
|
|
1218
|
+
async getEnvironment(id) {
|
|
1219
|
+
const row = tables.environments.get(id);
|
|
1220
|
+
return row && activeApplication(row.appId) ? clone(row) : null;
|
|
655
1221
|
},
|
|
656
|
-
async
|
|
657
|
-
|
|
658
|
-
|
|
1222
|
+
async listEnvironments(appId, options) {
|
|
1223
|
+
if (!options?.includeTrashed && !activeApplication(appId))
|
|
1224
|
+
return [];
|
|
1225
|
+
return rows(tables.environments, (row) => row.appId === appId)
|
|
1226
|
+
.sort((left, right) => left.createdAt.localeCompare(right.createdAt) || left.name.localeCompare(right.name));
|
|
659
1227
|
},
|
|
660
1228
|
async updateEnvironment(row) {
|
|
661
1229
|
tx(() => {
|
|
662
1230
|
const current = tables.environments.get(row.id);
|
|
663
|
-
if (!current)
|
|
1231
|
+
if (!current || !activeApplication(current.appId))
|
|
664
1232
|
fail("not_found", "Environment not found.");
|
|
665
1233
|
if (current.appId !== row.appId || current.orgId !== row.orgId || current.name !== row.name)
|
|
666
1234
|
fail("conflict", "An environment cannot change application or name.");
|
|
1235
|
+
const sameKey = row.keyVersion === current.keyVersion && row.secretHash === current.secretHash;
|
|
1236
|
+
const nextKey = row.keyVersion === current.keyVersion + 1 && row.previousSecretHash === current.secretHash;
|
|
1237
|
+
if (!sameKey && !nextKey)
|
|
1238
|
+
fail("conflict", "Environment key changed.");
|
|
667
1239
|
if (row.status !== "active" && row.status !== "disabled")
|
|
668
1240
|
fail("conflict", "Invalid environment status.");
|
|
669
1241
|
replace(tables.environments, stampEnvironment(row));
|
|
670
1242
|
});
|
|
671
1243
|
},
|
|
1244
|
+
async getNotificationSettings(environmentId) {
|
|
1245
|
+
const row = tables.notificationSettings.get(environmentId);
|
|
1246
|
+
return row ? clone(row) : null;
|
|
1247
|
+
},
|
|
1248
|
+
async saveNotificationSettings(row, expectedUpdatedAt, audit) {
|
|
1249
|
+
return tx(() => {
|
|
1250
|
+
const environment = tables.environments.get(row.environmentId);
|
|
1251
|
+
if (!environment || environment.appId !== row.appId || activeApplication(row.appId)?.orgId !== row.orgId)
|
|
1252
|
+
fail("conflict", "Notification settings must match the environment.");
|
|
1253
|
+
if (row.delivery !== "keyrox" && row.delivery !== "both" && row.delivery !== "webhook")
|
|
1254
|
+
fail("conflict", "Invalid notification delivery.");
|
|
1255
|
+
const existing = tables.notificationSettings.get(row.environmentId);
|
|
1256
|
+
if (expectedUpdatedAt !== undefined && (existing?.updatedAt ?? null) !== expectedUpdatedAt)
|
|
1257
|
+
return false;
|
|
1258
|
+
if (row.delivery === "webhook" && ![...tables.notificationWebhooks.values()].some((hook) => hook.environmentId === row.environmentId && hook.enabled))
|
|
1259
|
+
fail("conflict", "webhook_required");
|
|
1260
|
+
tables.notificationSettings.set(row.environmentId, clone({ ...row, templates: { ...row.templates }, updatedAt: asTime(row.updatedAt) }));
|
|
1261
|
+
if (audit) {
|
|
1262
|
+
if (audit.orgId !== row.orgId)
|
|
1263
|
+
fail("conflict", "Notification audit must match the tenant.");
|
|
1264
|
+
writeAudit(audit);
|
|
1265
|
+
}
|
|
1266
|
+
return true;
|
|
1267
|
+
});
|
|
1268
|
+
},
|
|
1269
|
+
async listNotificationWebhooks(environmentId) {
|
|
1270
|
+
return rows(tables.notificationWebhooks, (row) => row.environmentId === environmentId)
|
|
1271
|
+
.sort((left, right) => left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id));
|
|
1272
|
+
},
|
|
1273
|
+
async insertNotificationWebhook(row) {
|
|
1274
|
+
tx(() => {
|
|
1275
|
+
const environment = tables.environments.get(row.environmentId);
|
|
1276
|
+
if (!environment || environment.appId !== row.appId || activeApplication(row.appId)?.orgId !== row.orgId)
|
|
1277
|
+
fail("conflict", "A webhook must match the environment.");
|
|
1278
|
+
if ([...tables.notificationWebhooks.values()].filter((item) => item.environmentId === row.environmentId).length >= 5)
|
|
1279
|
+
fail("conflict", "webhook_limit");
|
|
1280
|
+
put(tables.notificationWebhooks, { ...row, createdAt: asTime(row.createdAt), updatedAt: asTime(row.updatedAt) });
|
|
1281
|
+
});
|
|
1282
|
+
},
|
|
1283
|
+
async updateNotificationWebhook(row) {
|
|
1284
|
+
tx(() => {
|
|
1285
|
+
const current = tables.notificationWebhooks.get(row.id);
|
|
1286
|
+
if (!current || current.environmentId !== row.environmentId || !activeApplication(row.appId))
|
|
1287
|
+
fail("not_found", "Webhook not found.");
|
|
1288
|
+
if (current.appId !== row.appId || current.orgId !== row.orgId)
|
|
1289
|
+
fail("conflict", "A webhook cannot change application.");
|
|
1290
|
+
if (current.enabled && !row.enabled && tables.notificationSettings.get(row.environmentId)?.delivery === "webhook" &&
|
|
1291
|
+
![...tables.notificationWebhooks.values()].some((hook) => hook.environmentId === row.environmentId && hook.id !== row.id && hook.enabled))
|
|
1292
|
+
fail("conflict", "webhook_required");
|
|
1293
|
+
replace(tables.notificationWebhooks, { ...row, createdAt: asTime(current.createdAt), updatedAt: asTime(row.updatedAt) });
|
|
1294
|
+
});
|
|
1295
|
+
},
|
|
1296
|
+
async deleteNotificationWebhook(environmentId, id, orgId) {
|
|
1297
|
+
return tx(() => {
|
|
1298
|
+
const current = tables.notificationWebhooks.get(id);
|
|
1299
|
+
if (!current || current.environmentId !== environmentId || !activeApplication(current.appId) || (orgId && current.orgId !== orgId))
|
|
1300
|
+
return false;
|
|
1301
|
+
if (current.enabled && tables.notificationSettings.get(environmentId)?.delivery === "webhook" &&
|
|
1302
|
+
![...tables.notificationWebhooks.values()].some((hook) => hook.environmentId === environmentId && hook.id !== id && hook.enabled))
|
|
1303
|
+
fail("conflict", "webhook_required");
|
|
1304
|
+
tables.notificationWebhooks.delete(id);
|
|
1305
|
+
return true;
|
|
1306
|
+
});
|
|
1307
|
+
},
|
|
1308
|
+
...createMemoryNotificationWebhookJobs(() => tables.notificationWebhookJobs, (job) => {
|
|
1309
|
+
const app = activeApplication(job.appId);
|
|
1310
|
+
const environment = tables.environments.get(job.environmentId);
|
|
1311
|
+
const hook = tables.notificationWebhooks.get(job.webhookId);
|
|
1312
|
+
const mode = tables.notificationSettings.get(job.environmentId)?.delivery;
|
|
1313
|
+
return app?.orgId === job.organizationId && app.status === "active" && environment?.appId === job.appId
|
|
1314
|
+
&& environment.orgId === job.organizationId && environment.keyVersion === job.environmentKeyVersion
|
|
1315
|
+
&& environment.status === "active" && hook?.enabled === true && hook.environmentId === job.environmentId
|
|
1316
|
+
&& hook.orgId === job.organizationId && mode === (job.keyroxDelivery ? "both" : "webhook");
|
|
1317
|
+
}),
|
|
1318
|
+
async listApplicationStaffAccess(orgId, userId) {
|
|
1319
|
+
return rows(tables.applicationStaffAccess, (row) => row.orgId === orgId && !!activeApplication(row.appId) && (userId === undefined || row.userId === userId))
|
|
1320
|
+
.sort((left, right) => left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id));
|
|
1321
|
+
},
|
|
1322
|
+
async saveApplicationStaffAccess(row, audit) {
|
|
1323
|
+
return tx(() => {
|
|
1324
|
+
if (audit && audit.orgId !== row.orgId)
|
|
1325
|
+
fail("conflict", "Application staff audit must match the tenant.");
|
|
1326
|
+
const saved = saveStaffAccess(row);
|
|
1327
|
+
if (audit)
|
|
1328
|
+
writeAudit(audit);
|
|
1329
|
+
return saved;
|
|
1330
|
+
});
|
|
1331
|
+
},
|
|
1332
|
+
async deleteApplicationStaffAccess(orgId, appId, environmentId, userId, audit) {
|
|
1333
|
+
return tx(() => {
|
|
1334
|
+
if (audit && audit.orgId !== orgId)
|
|
1335
|
+
fail("conflict", "Application staff audit must match the tenant.");
|
|
1336
|
+
const current = [...tables.applicationStaffAccess.values()].find((row) => row.orgId === orgId && row.appId === appId && row.environmentId === environmentId && row.userId === userId);
|
|
1337
|
+
if (!current)
|
|
1338
|
+
return false;
|
|
1339
|
+
tables.applicationStaffAccess.delete(current.id);
|
|
1340
|
+
if (audit)
|
|
1341
|
+
writeAudit(audit);
|
|
1342
|
+
return true;
|
|
1343
|
+
});
|
|
1344
|
+
},
|
|
672
1345
|
async insertAppToken(row) {
|
|
673
1346
|
tx(() => {
|
|
674
|
-
const app =
|
|
1347
|
+
const app = activeApplication(row.appId);
|
|
675
1348
|
if (!app)
|
|
676
1349
|
fail("conflict", "Application is missing.");
|
|
677
1350
|
const environment = tables.environments.get(row.environmentId);
|
|
@@ -679,18 +1352,23 @@ export function createMemoryStore() {
|
|
|
679
1352
|
fail("conflict", "Environment is missing.");
|
|
680
1353
|
if (row.orgId !== app.orgId)
|
|
681
1354
|
fail("conflict", "Token tenant does not match the application.");
|
|
1355
|
+
if (row.payload.keyVersion !== environment.keyVersion)
|
|
1356
|
+
fail("conflict", "The environment key changed during token issuance.");
|
|
682
1357
|
put(tables.appTokens, stampAppToken(row));
|
|
683
1358
|
});
|
|
684
1359
|
},
|
|
685
|
-
async getAppToken(id) {
|
|
1360
|
+
async getAppToken(id) {
|
|
1361
|
+
const token = tables.appTokens.get(id);
|
|
1362
|
+
return token && activeApplication(token.appId) ? clone(token) : null;
|
|
1363
|
+
},
|
|
686
1364
|
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))
|
|
1365
|
+
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
1366
|
.sort((left, right) => right.createdAt.localeCompare(left.createdAt) || right.id.localeCompare(left.id));
|
|
689
1367
|
},
|
|
690
1368
|
async revokeAppToken(id, at) {
|
|
691
1369
|
return tx(() => {
|
|
692
1370
|
const row = tables.appTokens.get(id);
|
|
693
|
-
if (!row)
|
|
1371
|
+
if (!row || !activeApplication(row.appId))
|
|
694
1372
|
return null;
|
|
695
1373
|
if (!row.revokedAt)
|
|
696
1374
|
row.revokedAt = asTime(at);
|
|
@@ -702,7 +1380,7 @@ export function createMemoryStore() {
|
|
|
702
1380
|
const stamp = asTime(at);
|
|
703
1381
|
let count = 0;
|
|
704
1382
|
for (const row of tables.appTokens.values()) {
|
|
705
|
-
if (row.revokedAt)
|
|
1383
|
+
if (row.revokedAt || !activeApplication(row.appId))
|
|
706
1384
|
continue;
|
|
707
1385
|
if (filter.appId && row.appId !== filter.appId)
|
|
708
1386
|
continue;
|
|
@@ -718,44 +1396,347 @@ export function createMemoryStore() {
|
|
|
718
1396
|
return count;
|
|
719
1397
|
});
|
|
720
1398
|
},
|
|
1399
|
+
async savePlatformSignIn(row) {
|
|
1400
|
+
return tx(() => {
|
|
1401
|
+
const existing = [...tables.platformSignIn.values()].find((item) => item.provider === row.provider);
|
|
1402
|
+
const id = existing?.id ?? row.id;
|
|
1403
|
+
const updated = {
|
|
1404
|
+
...row, id, createdAt: asTime(existing?.createdAt ?? row.createdAt),
|
|
1405
|
+
managedForApps: canSharePlatformSignIn(row) && (row.managedForApps ?? existing?.managedForApps ?? false),
|
|
1406
|
+
};
|
|
1407
|
+
tables.platformSignIn.set(id, updated);
|
|
1408
|
+
return { ...updated };
|
|
1409
|
+
});
|
|
1410
|
+
},
|
|
1411
|
+
async setPlatformSignInManaged(provider, managedForApps) {
|
|
1412
|
+
return tx(() => {
|
|
1413
|
+
const current = [...tables.platformSignIn.values()].find((item) => item.provider === provider);
|
|
1414
|
+
if (!current || (managedForApps && !canSharePlatformSignIn(current)))
|
|
1415
|
+
return null;
|
|
1416
|
+
const updated = { ...current, managedForApps };
|
|
1417
|
+
tables.platformSignIn.set(current.id, updated);
|
|
1418
|
+
return { ...updated };
|
|
1419
|
+
});
|
|
1420
|
+
},
|
|
1421
|
+
async listPlatformSignIn() {
|
|
1422
|
+
return rows(tables.platformSignIn).sort((left, right) => left.provider.localeCompare(right.provider));
|
|
1423
|
+
},
|
|
1424
|
+
async deletePlatformSignIn(provider) {
|
|
1425
|
+
tx(() => { for (const row of [...tables.platformSignIn.values()])
|
|
1426
|
+
if (row.provider === provider)
|
|
1427
|
+
tables.platformSignIn.delete(row.id); });
|
|
1428
|
+
},
|
|
1429
|
+
async findAccountIdentity(provider, subject) {
|
|
1430
|
+
return rows(tables.accountIdentities, (row) => row.provider === provider && row.subject === subject)[0] ?? null;
|
|
1431
|
+
},
|
|
1432
|
+
async findUserAccountIdentity(userId, provider) {
|
|
1433
|
+
return rows(tables.accountIdentities, (row) => row.userId === userId && row.provider === provider)[0] ?? null;
|
|
1434
|
+
},
|
|
1435
|
+
async saveAccountIdentity(row) {
|
|
1436
|
+
tx(() => insertAccountIdentity(row));
|
|
1437
|
+
},
|
|
1438
|
+
async insertAccountSsoLogin(row) {
|
|
1439
|
+
tx(() => {
|
|
1440
|
+
if (row.linkUserId)
|
|
1441
|
+
user(row.linkUserId);
|
|
1442
|
+
put(tables.accountSsoLogins, { ...row, nextPath: row.nextPath ?? null, linkUserId: row.linkUserId ?? null, linkSessionHash: row.linkSessionHash ?? null, expiresAt: asTime(row.expiresAt), createdAt: asTime(row.createdAt) });
|
|
1443
|
+
});
|
|
1444
|
+
},
|
|
1445
|
+
async takeAccountSsoLogin(stateHash, at) {
|
|
1446
|
+
return tx(() => takeExpiring(tables.accountSsoLogins, (row) => row.stateHash === stateHash, at));
|
|
1447
|
+
},
|
|
1448
|
+
async insertAccountSsoProfile(row) {
|
|
1449
|
+
tx(() => {
|
|
1450
|
+
const createdAt = asTime(row.createdAt);
|
|
1451
|
+
for (const item of tables.accountSsoProfiles.values()) {
|
|
1452
|
+
if (isExpired(item.expiresAt, createdAt))
|
|
1453
|
+
tables.accountSsoProfiles.delete(item.id);
|
|
1454
|
+
else if (item.codeHash === row.codeHash)
|
|
1455
|
+
fail("duplicate", "Duplicate key.");
|
|
1456
|
+
}
|
|
1457
|
+
put(tables.accountSsoProfiles, { ...row, expiresAt: asTime(row.expiresAt), createdAt });
|
|
1458
|
+
});
|
|
1459
|
+
},
|
|
1460
|
+
async takeAccountSsoProfile(codeHash, browserHash, at) {
|
|
1461
|
+
return tx(() => takeExpiring(tables.accountSsoProfiles, (row) => row.codeHash === codeHash && row.browserHash === browserHash, at));
|
|
1462
|
+
},
|
|
1463
|
+
async insertAccountHandoff(row) { tx(() => put(tables.accountHandoffs, { ...row, expiresAt: asTime(row.expiresAt), createdAt: asTime(row.createdAt) })); },
|
|
1464
|
+
async takeAccountHandoff(codeHash, at) {
|
|
1465
|
+
return tx(() => takeExpiring(tables.accountHandoffs, (row) => row.codeHash === codeHash, at));
|
|
1466
|
+
},
|
|
1467
|
+
async insertCliLoginCode(row) {
|
|
1468
|
+
tx(() => {
|
|
1469
|
+
const createdAt = asTime(row.createdAt);
|
|
1470
|
+
const expiresAt = asTime(row.expiresAt);
|
|
1471
|
+
const session = [...tables.sessions.values()].find((item) => item.secretHash === row.browserSessionHash);
|
|
1472
|
+
if (!session || !tables.users.has(row.userId) || !tables.orgs.has(row.orgId) || isExpired(expiresAt, createdAt))
|
|
1473
|
+
fail("conflict", "Invalid CLI sign-in code.");
|
|
1474
|
+
for (const [hash, code] of tables.cliLoginCodes) {
|
|
1475
|
+
if (isExpired(code.expiresAt, createdAt))
|
|
1476
|
+
tables.cliLoginCodes.delete(hash);
|
|
1477
|
+
}
|
|
1478
|
+
if (tables.cliLoginCodes.has(row.codeHash) || [...tables.cliLoginCodes.values()].some((code) => code.requestHash === row.requestHash)) {
|
|
1479
|
+
fail("duplicate", "Duplicate CLI sign-in code.");
|
|
1480
|
+
}
|
|
1481
|
+
tables.cliLoginCodes.set(row.codeHash, { ...row, createdAt, expiresAt });
|
|
1482
|
+
});
|
|
1483
|
+
},
|
|
1484
|
+
async takeCliLoginCode(codeHash, codeChallenge, redirectUri, at) {
|
|
1485
|
+
return tx(() => {
|
|
1486
|
+
const row = tables.cliLoginCodes.get(codeHash);
|
|
1487
|
+
const timestamp = asTime(at);
|
|
1488
|
+
if (!row || row.consumedAt || row.codeChallenge !== codeChallenge || row.redirectUri !== redirectUri || isExpired(row.expiresAt, timestamp))
|
|
1489
|
+
return null;
|
|
1490
|
+
const consumed = { ...row, consumedAt: timestamp };
|
|
1491
|
+
tables.cliLoginCodes.set(codeHash, consumed);
|
|
1492
|
+
return clone(consumed);
|
|
1493
|
+
});
|
|
1494
|
+
},
|
|
721
1495
|
async saveSignInConnection(row) {
|
|
722
1496
|
tx(() => {
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
1497
|
+
const app = activeApplication(row.appId);
|
|
1498
|
+
if (!app || app.orgId !== row.orgId)
|
|
1499
|
+
fail("conflict", "Application is missing.");
|
|
1500
|
+
const existing = [...tables.signIn.values()].find((item) => item.appId === row.appId && item.provider === row.provider);
|
|
1501
|
+
tables.signIn.set(existing?.id ?? row.id, {
|
|
1502
|
+
...row, id: existing?.id ?? row.id, legacyConnectionId: existing?.legacyConnectionId, createdAt: asTime(existing?.createdAt ?? row.createdAt),
|
|
1503
|
+
});
|
|
1504
|
+
retireLegacyAppSignIn(row.appId, row.provider);
|
|
726
1505
|
});
|
|
727
1506
|
},
|
|
728
|
-
async listSignInConnections(
|
|
729
|
-
|
|
1507
|
+
async listSignInConnections(appId) {
|
|
1508
|
+
if (!activeApplication(appId))
|
|
1509
|
+
return [];
|
|
1510
|
+
return rows(tables.signIn, (row) => row.appId === appId).sort((left, right) => left.provider.localeCompare(right.provider));
|
|
1511
|
+
},
|
|
1512
|
+
async listOrgSignInConnections(orgId) {
|
|
1513
|
+
return rows(tables.signIn, (row) => row.orgId === orgId && !!activeApplication(row.appId))
|
|
1514
|
+
.sort((left, right) => left.provider.localeCompare(right.provider) || left.appId.localeCompare(right.appId));
|
|
730
1515
|
},
|
|
731
|
-
async deleteSignInConnection(
|
|
732
|
-
tx(() => {
|
|
733
|
-
|
|
734
|
-
|
|
1516
|
+
async deleteSignInConnection(appId, provider, orgId) {
|
|
1517
|
+
tx(() => {
|
|
1518
|
+
const app = activeApplication(appId);
|
|
1519
|
+
if (!app || (orgId && app.orgId !== orgId))
|
|
1520
|
+
fail("not_found", "Application not found.");
|
|
1521
|
+
for (const row of tables.signIn.values())
|
|
1522
|
+
if (row.appId === appId && row.provider === provider)
|
|
1523
|
+
tables.signIn.delete(row.id);
|
|
1524
|
+
retireLegacyAppSignIn(appId, provider);
|
|
1525
|
+
});
|
|
735
1526
|
},
|
|
736
1527
|
async saveAppSignIn(appId, providers) {
|
|
737
1528
|
tx(() => {
|
|
738
|
-
if (!
|
|
1529
|
+
if (!activeApplication(appId))
|
|
739
1530
|
fail("conflict", "Application is missing.");
|
|
740
1531
|
tables.appSignIn.set(appId, [...providers]);
|
|
741
1532
|
});
|
|
742
1533
|
},
|
|
743
1534
|
async getAppSignIn(appId) { return [...(tables.appSignIn.get(appId) ?? [])]; },
|
|
744
|
-
async saveRedirects(environmentId, uris) {
|
|
1535
|
+
async saveRedirects(environmentId, uris, orgId) {
|
|
745
1536
|
tx(() => {
|
|
746
|
-
|
|
1537
|
+
const environment = tables.environments.get(environmentId);
|
|
1538
|
+
if (!environment || !activeApplication(environment.appId) || (orgId && environment.orgId !== orgId))
|
|
747
1539
|
fail("conflict", "Environment is missing.");
|
|
748
1540
|
tables.redirects.set(environmentId, [...uris]);
|
|
749
1541
|
});
|
|
750
1542
|
},
|
|
751
1543
|
async getRedirects(environmentId) { return [...(tables.redirects.get(environmentId) ?? [])]; },
|
|
752
|
-
async
|
|
1544
|
+
async insertHostedHumanClient(row) {
|
|
1545
|
+
tx(() => {
|
|
1546
|
+
if (activeApplication(row.appId)?.orgId !== row.orgId || tables.environments.get(row.environmentId)?.appId !== row.appId) {
|
|
1547
|
+
fail("not_found", "Application environment not found.");
|
|
1548
|
+
}
|
|
1549
|
+
put(tables.hostedHumanClients, { ...row, createdAt: asTime(row.createdAt), revokedAt: asTimeOrNull(row.revokedAt) });
|
|
1550
|
+
});
|
|
1551
|
+
},
|
|
1552
|
+
async getHostedHumanClient(clientId) { return clone(tables.hostedHumanClients.get(clientId) ?? null); },
|
|
1553
|
+
async listHostedHumanClients(appId, environmentId) {
|
|
1554
|
+
const orgId = activeApplication(appId)?.orgId;
|
|
1555
|
+
return rows(tables.hostedHumanClients, (row) => row.appId === appId && row.environmentId === environmentId && row.orgId === orgId);
|
|
1556
|
+
},
|
|
1557
|
+
async revokeHostedHumanClient(appId, environmentId, clientId, at) {
|
|
1558
|
+
return tx(() => {
|
|
1559
|
+
const client = tables.hostedHumanClients.get(clientId);
|
|
1560
|
+
if (!client || client.appId !== appId || client.environmentId !== environmentId || client.orgId !== activeApplication(appId)?.orgId)
|
|
1561
|
+
return false;
|
|
1562
|
+
if (!client.revokedAt)
|
|
1563
|
+
replace(tables.hostedHumanClients, { ...client, revokedAt: asTime(at) });
|
|
1564
|
+
removeMatching(tables.hostedHumanCodes, (row) => row.clientId === clientId);
|
|
1565
|
+
return true;
|
|
1566
|
+
});
|
|
1567
|
+
},
|
|
1568
|
+
async insertHostedHumanCode(row) {
|
|
1569
|
+
return tx(() => {
|
|
1570
|
+
const client = tables.hostedHumanClients.get(row.clientId);
|
|
1571
|
+
const app = activeApplication(row.appId);
|
|
1572
|
+
const environment = tables.environments.get(row.environmentId);
|
|
1573
|
+
const identity = tables.directory.identities.get(row.identityId);
|
|
1574
|
+
if (!client || client.revokedAt || client.appId !== row.appId || client.environmentId !== row.environmentId
|
|
1575
|
+
|| client.orgId !== row.orgId || client.redirectUri !== row.redirectUri || !identity || identity.appId !== row.appId
|
|
1576
|
+
|| identity.environmentId !== row.environmentId || identity.orgId !== row.orgId || identity.kind !== "user"
|
|
1577
|
+
|| identity.status !== "active" || !identity.email || !identity.emailVerifiedAt || !identity.emailProofAt
|
|
1578
|
+
|| app?.orgId !== row.orgId || app.status !== "active" || app.signupMode !== "waiting-list"
|
|
1579
|
+
|| environment?.appId !== row.appId || environment.orgId !== row.orgId || environment.status !== "active"
|
|
1580
|
+
|| !tables.redirects.get(row.environmentId)?.includes(row.redirectUri))
|
|
1581
|
+
return false;
|
|
1582
|
+
if (tables.hostedHumanCodes.has(row.codeHash))
|
|
1583
|
+
fail("duplicate", "Duplicate sign-in code.");
|
|
1584
|
+
tables.hostedHumanCodes.set(row.codeHash, { ...row, createdAt: asTime(row.createdAt), expiresAt: asTime(row.expiresAt) });
|
|
1585
|
+
return true;
|
|
1586
|
+
});
|
|
1587
|
+
},
|
|
1588
|
+
async takeHostedHumanCode(input) {
|
|
1589
|
+
return tx(() => {
|
|
1590
|
+
const row = tables.hostedHumanCodes.get(input.codeHash);
|
|
1591
|
+
if (!row || row.clientId !== input.clientId || row.appId !== input.appId || row.environmentId !== input.environmentId
|
|
1592
|
+
|| row.redirectUri !== input.redirectUri || row.codeChallenge !== input.codeChallenge || isExpired(row.expiresAt, input.at))
|
|
1593
|
+
return null;
|
|
1594
|
+
const client = tables.hostedHumanClients.get(input.clientId);
|
|
1595
|
+
const app = activeApplication(input.appId);
|
|
1596
|
+
const environment = tables.environments.get(input.environmentId);
|
|
1597
|
+
const identity = tables.directory.identities.get(row.identityId);
|
|
1598
|
+
if (!client || client.revokedAt || client.secretHash !== input.secretHash || client.orgId !== row.orgId
|
|
1599
|
+
|| app?.orgId !== row.orgId || app.status !== "active" || app.signupMode !== "waiting-list"
|
|
1600
|
+
|| environment?.appId !== row.appId || environment.orgId !== row.orgId || environment.status !== "active"
|
|
1601
|
+
|| !tables.redirects.get(row.environmentId)?.includes(row.redirectUri)
|
|
1602
|
+
|| identity?.appId !== row.appId || identity.environmentId !== row.environmentId || identity.orgId !== row.orgId
|
|
1603
|
+
|| identity.kind !== "user" || identity.status !== "active" || !identity.email || !identity.emailVerifiedAt || !identity.emailProofAt)
|
|
1604
|
+
return null;
|
|
1605
|
+
tables.hostedHumanCodes.delete(row.codeHash);
|
|
1606
|
+
return clone(row);
|
|
1607
|
+
});
|
|
1608
|
+
},
|
|
1609
|
+
async insertSsoLogin(row) {
|
|
1610
|
+
const { waitlistInApp, ...login } = row;
|
|
1611
|
+
tx(() => {
|
|
1612
|
+
if (activeApplication(row.appId)?.orgId !== row.orgId)
|
|
1613
|
+
fail("not_found", "Application not found.");
|
|
1614
|
+
put(tables.ssoLogins, {
|
|
1615
|
+
...login, connectionAuthority: row.connectionAuthority ?? null, expiresAt: asTime(row.expiresAt), createdAt: asTime(row.createdAt),
|
|
1616
|
+
...(waitlistInApp ? { waitlistInApp: true } : {}),
|
|
1617
|
+
...(row.invitationTokenHash ? { invitationTokenHash: row.invitationTokenHash } : {}),
|
|
1618
|
+
});
|
|
1619
|
+
});
|
|
1620
|
+
},
|
|
753
1621
|
async takeSsoLogin(stateHash, at) {
|
|
754
|
-
return tx(() => takeExpiring(tables.ssoLogins, (row) => row.stateHash === stateHash, at));
|
|
1622
|
+
return tx(() => takeExpiring(tables.ssoLogins, (row) => row.stateHash === stateHash && activeApplication(row.appId)?.orgId === row.orgId, at));
|
|
1623
|
+
},
|
|
1624
|
+
async putHostedEmailCode(row) {
|
|
1625
|
+
return tx(() => {
|
|
1626
|
+
if (!isHostedEnvironmentActive(row.appId, row.environmentId))
|
|
1627
|
+
return "cooldown";
|
|
1628
|
+
const createdAt = asTime(row.createdAt);
|
|
1629
|
+
const expiresAt = asTime(row.expiresAt);
|
|
1630
|
+
if (isExpired(expiresAt, createdAt))
|
|
1631
|
+
fail("conflict", "Email code expiry must follow issuance.");
|
|
1632
|
+
const email = row.email.trim().toLowerCase();
|
|
1633
|
+
const key = JSON.stringify([row.environmentId, email]);
|
|
1634
|
+
const previous = tables.hostedEmailCodes.get(key);
|
|
1635
|
+
const now = Date.parse(createdAt);
|
|
1636
|
+
const sendHistory = previous?.sendHistory.filter((at) => now - Date.parse(at) < hostedEmailCodePolicy.sendWindowMs) ?? [];
|
|
1637
|
+
if ((previous && (previous.code.challengeHash === row.challengeHash ||
|
|
1638
|
+
now - Date.parse(previous.code.createdAt) < hostedEmailCodePolicy.resendDelayMs)) ||
|
|
1639
|
+
sendHistory.length >= hostedEmailCodePolicy.maxSends)
|
|
1640
|
+
return "cooldown";
|
|
1641
|
+
if ([...tables.hostedEmailCodes.values()].some((state) => state.code.challengeHash === row.challengeHash)) {
|
|
1642
|
+
fail("duplicate", "Duplicate hosted email challenge.");
|
|
1643
|
+
}
|
|
1644
|
+
tables.hostedEmailCodes.set(key, {
|
|
1645
|
+
code: { ...row, email, createdAt, expiresAt },
|
|
1646
|
+
sendHistory: [...sendHistory, createdAt], attemptsRemaining: hostedEmailCodePolicy.maxAttempts, consumed: false,
|
|
1647
|
+
});
|
|
1648
|
+
return "sent";
|
|
1649
|
+
});
|
|
1650
|
+
},
|
|
1651
|
+
async verifyHostedEmailCode(appId, environmentId, challengeHash, codeHash, at) {
|
|
1652
|
+
return tx(() => {
|
|
1653
|
+
if (!isHostedEnvironmentActive(appId, environmentId))
|
|
1654
|
+
return null;
|
|
1655
|
+
const stamp = asTime(at);
|
|
1656
|
+
const state = [...tables.hostedEmailCodes.values()].find(({ code }) => code.appId === appId && code.environmentId === environmentId && code.challengeHash === challengeHash);
|
|
1657
|
+
if (!state || state.consumed || state.attemptsRemaining < 1 || isExpired(state.code.expiresAt, stamp))
|
|
1658
|
+
return null;
|
|
1659
|
+
state.attemptsRemaining -= 1;
|
|
1660
|
+
if (state.code.codeHash !== codeHash)
|
|
1661
|
+
return null;
|
|
1662
|
+
state.consumed = true;
|
|
1663
|
+
return { ...state.code };
|
|
1664
|
+
});
|
|
1665
|
+
},
|
|
1666
|
+
async insertHostedSsoProfile(row) {
|
|
1667
|
+
tx(() => {
|
|
1668
|
+
const app = tables.applications.get(row.appId);
|
|
1669
|
+
const environment = tables.environments.get(row.environmentId);
|
|
1670
|
+
if (!app || app.orgId !== row.orgId || environment?.appId !== app.id)
|
|
1671
|
+
fail("conflict", "Hosted sign-in environment is missing.");
|
|
1672
|
+
if ([...tables.hostedSsoProfiles.values()].some((current) => current.challengeHash === row.challengeHash))
|
|
1673
|
+
fail("duplicate", "Duplicate hosted sign-in challenge.");
|
|
1674
|
+
const { displayName, connectionFingerprint, waitlistInApp, ...profile } = row;
|
|
1675
|
+
put(tables.hostedSsoProfiles, {
|
|
1676
|
+
...profile, expiresAt: asTime(row.expiresAt), createdAt: asTime(row.createdAt),
|
|
1677
|
+
...(displayName != null ? { displayName } : {}),
|
|
1678
|
+
...(connectionFingerprint != null ? { connectionFingerprint } : {}),
|
|
1679
|
+
...(waitlistInApp ? { waitlistInApp: true } : {}),
|
|
1680
|
+
});
|
|
1681
|
+
});
|
|
1682
|
+
},
|
|
1683
|
+
async getHostedSsoProfile(challengeHash, browserHash, at) {
|
|
1684
|
+
const row = findHostedSsoProfile(challengeHash, browserHash, asTime(at));
|
|
1685
|
+
return row ? clone(row) : null;
|
|
1686
|
+
},
|
|
1687
|
+
async takeHostedSsoProfile(challengeHash, browserHash, at) {
|
|
1688
|
+
return tx(() => {
|
|
1689
|
+
const row = findHostedSsoProfile(challengeHash, browserHash, asTime(at));
|
|
1690
|
+
if (!row)
|
|
1691
|
+
return null;
|
|
1692
|
+
deleteHostedSsoProfile(row.id);
|
|
1693
|
+
return clone(row);
|
|
1694
|
+
});
|
|
1695
|
+
},
|
|
1696
|
+
async beginHostedSsoEmail(challengeHash, browserHash, proof) {
|
|
1697
|
+
return tx(() => {
|
|
1698
|
+
const createdAt = asTime(proof.createdAt);
|
|
1699
|
+
const expiresAt = asTime(proof.expiresAt);
|
|
1700
|
+
const profile = findHostedSsoProfile(challengeHash, browserHash, createdAt);
|
|
1701
|
+
if (!profile || profile.email !== null || profile.id !== proof.identityId || profile.environmentId !== proof.environmentId ||
|
|
1702
|
+
proof.purpose !== "hosted-sso-email" || proof.usedAt !== null || isExpired(expiresAt, createdAt))
|
|
1703
|
+
return false;
|
|
1704
|
+
const previous = tables.hostedSsoEmailProofs.get(profile.id);
|
|
1705
|
+
if (previous && Date.parse(createdAt) - Date.parse(previous.createdAt) < 60_000)
|
|
1706
|
+
return false;
|
|
1707
|
+
if ([...tables.hostedSsoEmailProofs].some(([id, row]) => id !== profile.id && row.tokenHash === proof.tokenHash)) {
|
|
1708
|
+
fail("duplicate", "Duplicate hosted sign-in email proof.");
|
|
1709
|
+
}
|
|
1710
|
+
tables.hostedSsoEmailProofs.set(profile.id, { email: proof.email, tokenHash: proof.tokenHash, createdAt, expiresAt });
|
|
1711
|
+
return true;
|
|
1712
|
+
});
|
|
1713
|
+
},
|
|
1714
|
+
async takeHostedSsoEmail(challengeHash, browserHash, tokenHash, at) {
|
|
1715
|
+
return tx(() => {
|
|
1716
|
+
const stamp = asTime(at);
|
|
1717
|
+
const profile = findHostedSsoProfile(challengeHash, browserHash, stamp);
|
|
1718
|
+
if (!profile || profile.email !== null)
|
|
1719
|
+
return null;
|
|
1720
|
+
const proof = tables.hostedSsoEmailProofs.get(profile.id);
|
|
1721
|
+
if (!proof || proof.tokenHash !== tokenHash || isExpired(proof.expiresAt, stamp))
|
|
1722
|
+
return null;
|
|
1723
|
+
deleteHostedSsoProfile(profile.id);
|
|
1724
|
+
return { ...profile, email: proof.email };
|
|
1725
|
+
});
|
|
1726
|
+
},
|
|
1727
|
+
async insertSsoExchange(row) {
|
|
1728
|
+
tx(() => {
|
|
1729
|
+
if (!hasSsoExchangeToken(row))
|
|
1730
|
+
fail("conflict", "The sign-in token is unavailable.");
|
|
1731
|
+
put(tables.ssoExchanges, { ...row, expiresAt: asTime(row.expiresAt), createdAt: asTime(row.createdAt) });
|
|
1732
|
+
});
|
|
1733
|
+
},
|
|
1734
|
+
async getSsoExchange(codeHash, at) {
|
|
1735
|
+
const stamp = asTime(at);
|
|
1736
|
+
return rows(tables.ssoExchanges, (row) => row.codeHash === codeHash && hasSsoExchangeToken(row) && !isExpired(row.expiresAt, stamp))[0] ?? null;
|
|
755
1737
|
},
|
|
756
|
-
async insertSsoExchange(row) { tx(() => put(tables.ssoExchanges, { ...row, expiresAt: asTime(row.expiresAt), createdAt: asTime(row.createdAt) })); },
|
|
757
1738
|
async takeSsoExchange(codeHash, at) {
|
|
758
|
-
return tx(() => takeExpiring(tables.ssoExchanges, (row) => row.codeHash === codeHash, at));
|
|
1739
|
+
return tx(() => takeExpiring(tables.ssoExchanges, (row) => row.codeHash === codeHash && hasSsoExchangeToken(row), at));
|
|
759
1740
|
},
|
|
760
1741
|
async insertServiceCredential(row) {
|
|
761
1742
|
tx(() => {
|
|
@@ -809,14 +1790,19 @@ export function createMemoryStore() {
|
|
|
809
1790
|
async insertAudience(row) {
|
|
810
1791
|
tx(() => {
|
|
811
1792
|
org(row.orgId);
|
|
1793
|
+
if (row.appId && activeApplication(row.appId)?.orgId !== row.orgId)
|
|
1794
|
+
fail("conflict", "Choose an application from this tenant.");
|
|
812
1795
|
if ([...tables.audiences.values()].some((item) => item.orgId === row.orgId && item.identifier === row.identifier))
|
|
813
1796
|
fail("duplicate", "Duplicate key.");
|
|
814
1797
|
put(tables.audiences, { ...row, createdAt: asTime(row.createdAt) });
|
|
815
1798
|
});
|
|
816
1799
|
},
|
|
817
|
-
async listAudiences(orgId) {
|
|
1800
|
+
async listAudiences(orgId) {
|
|
1801
|
+
return rows(tables.audiences, (row) => row.orgId === orgId && (!row.appId || activeApplication(row.appId)?.orgId === orgId));
|
|
1802
|
+
},
|
|
818
1803
|
async findAudience(orgId, identifier) {
|
|
819
|
-
return rows(tables.audiences, (row) => row.orgId === orgId && row.identifier === identifier
|
|
1804
|
+
return rows(tables.audiences, (row) => row.orgId === orgId && row.identifier === identifier
|
|
1805
|
+
&& (!row.appId || activeApplication(row.appId)?.orgId === orgId))[0] ?? null;
|
|
820
1806
|
},
|
|
821
1807
|
async insertRole(row) {
|
|
822
1808
|
tx(() => { org(row.orgId); put(tables.roles, { ...row, actions: [...row.actions], createdAt: asTime(row.createdAt) }); });
|
|
@@ -825,19 +1811,42 @@ export function createMemoryStore() {
|
|
|
825
1811
|
async insertAssignment(row) {
|
|
826
1812
|
tx(() => {
|
|
827
1813
|
org(row.orgId);
|
|
828
|
-
|
|
829
|
-
|
|
1814
|
+
const principal = tables.principals.get(row.principalId);
|
|
1815
|
+
const role = tables.roles.get(row.roleId);
|
|
1816
|
+
if (principal?.orgId !== row.orgId || role?.orgId !== row.orgId)
|
|
1817
|
+
fail("conflict", "Choose an app identity and role from this tenant.");
|
|
1818
|
+
if (!principal.enabled)
|
|
1819
|
+
fail("conflict", "This app identity is disabled.");
|
|
1820
|
+
const scope = row.scope.replace(/\/+$/, "");
|
|
1821
|
+
const duplicate = [...tables.assignments.values()].some((assignment) => assignment.orgId === row.orgId && assignment.principalId === row.principalId && assignment.roleId === row.roleId
|
|
1822
|
+
&& assignment.scope.replace(/\/+$/, "") === scope);
|
|
1823
|
+
if (duplicate)
|
|
1824
|
+
fail("duplicate", "Role assignment already exists.");
|
|
830
1825
|
put(tables.assignments, { ...row, createdAt: asTime(row.createdAt) });
|
|
831
1826
|
});
|
|
832
1827
|
},
|
|
833
1828
|
async listAssignments(orgId, principalId) {
|
|
834
1829
|
return rows(tables.assignments, (row) => row.orgId === orgId && (!principalId || row.principalId === principalId));
|
|
835
1830
|
},
|
|
1831
|
+
async deleteAssignment(id, orgId, audit) {
|
|
1832
|
+
return tx(() => {
|
|
1833
|
+
if (tables.assignments.get(id)?.orgId !== orgId)
|
|
1834
|
+
return false;
|
|
1835
|
+
tables.assignments.delete(id);
|
|
1836
|
+
writeAudit(audit);
|
|
1837
|
+
return true;
|
|
1838
|
+
});
|
|
1839
|
+
},
|
|
836
1840
|
async insertGatewayRoute(row) {
|
|
837
1841
|
tx(() => {
|
|
838
1842
|
org(row.orgId);
|
|
839
|
-
|
|
840
|
-
|
|
1843
|
+
const audience = tables.audiences.get(row.audienceId);
|
|
1844
|
+
if (!audience || audience.orgId !== row.orgId)
|
|
1845
|
+
fail("conflict", "Choose an audience from this tenant.");
|
|
1846
|
+
const appId = appIdFromTenantResource(row.orgId, row.resource);
|
|
1847
|
+
if ((audience.appId && activeApplication(audience.appId)?.orgId !== row.orgId) || (appId && activeApplication(appId)?.orgId !== row.orgId)) {
|
|
1848
|
+
fail("conflict", "Choose an application from this tenant.");
|
|
1849
|
+
}
|
|
841
1850
|
put(tables.gatewayRoutes, { ...row, createdAt: asTime(row.createdAt) });
|
|
842
1851
|
});
|
|
843
1852
|
},
|
|
@@ -850,7 +1859,16 @@ export function createMemoryStore() {
|
|
|
850
1859
|
tables.gatewayRoutes.delete(id);
|
|
851
1860
|
});
|
|
852
1861
|
},
|
|
853
|
-
...bindDirectoryMemory(() => tables.directory, () => tables.users.size, tx)
|
|
1862
|
+
...bindDirectoryMemory(() => tables.directory, () => tables.users.size, tx, (environmentId, includeDisabled = false) => {
|
|
1863
|
+
const environment = tables.environments.get(environmentId);
|
|
1864
|
+
const app = environment && activeApplication(environment.appId);
|
|
1865
|
+
return app && (includeDisabled || (environment?.status === "active" && app.status === "active")) ? app : null;
|
|
1866
|
+
}, (identity, job) => {
|
|
1867
|
+
if (job && (job.environmentId !== identity.environmentId || job.organizationId !== identity.orgId ||
|
|
1868
|
+
job.environmentKeyVersion !== tables.environments.get(identity.environmentId)?.keyVersion))
|
|
1869
|
+
fail("conflict", "Notification scope changed.");
|
|
1870
|
+
insertMemoryNotificationDelivery(tables.notificationDeliveries, job);
|
|
1871
|
+
}),
|
|
854
1872
|
async ping() { },
|
|
855
1873
|
async purgeExpired(at) {
|
|
856
1874
|
tx(() => {
|
|
@@ -858,7 +1876,11 @@ export function createMemoryStore() {
|
|
|
858
1876
|
const seconds = Math.floor(Date.parse(stamp) / 1000);
|
|
859
1877
|
for (const row of [...tables.sessions.values()])
|
|
860
1878
|
if (isExpired(row.expiresAt, stamp))
|
|
861
|
-
|
|
1879
|
+
deleteSession(row.id);
|
|
1880
|
+
pruneHostedHumanCredentials(stamp);
|
|
1881
|
+
for (const [hash, row] of tables.cliLoginCodes)
|
|
1882
|
+
if (isExpired(row.expiresAt, stamp))
|
|
1883
|
+
tables.cliLoginCodes.delete(hash);
|
|
862
1884
|
for (const row of [...tables.challenges.values()])
|
|
863
1885
|
if (isExpired(row.expiresAt, stamp))
|
|
864
1886
|
tables.challenges.delete(row.id);
|
|
@@ -871,6 +1893,14 @@ export function createMemoryStore() {
|
|
|
871
1893
|
for (const row of [...tables.ssoLogins.values()])
|
|
872
1894
|
if (isExpired(row.expiresAt, stamp))
|
|
873
1895
|
tables.ssoLogins.delete(row.id);
|
|
1896
|
+
for (const [key, { code }] of tables.hostedEmailCodes) {
|
|
1897
|
+
if (isExpired(code.expiresAt, stamp) && Date.parse(stamp) - Date.parse(code.createdAt) >= hostedEmailCodePolicy.sendWindowMs) {
|
|
1898
|
+
tables.hostedEmailCodes.delete(key);
|
|
1899
|
+
}
|
|
1900
|
+
}
|
|
1901
|
+
for (const row of [...tables.hostedSsoProfiles.values()])
|
|
1902
|
+
if (isExpired(row.expiresAt, stamp))
|
|
1903
|
+
deleteHostedSsoProfile(row.id);
|
|
874
1904
|
for (const row of [...tables.ssoExchanges.values()])
|
|
875
1905
|
if (isExpired(row.expiresAt, stamp))
|
|
876
1906
|
tables.ssoExchanges.delete(row.id);
|