@x12i/keyrox-store 0.0.0-stage → 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/access.d.ts +22 -0
- package/dist/access.d.ts.map +1 -0
- package/dist/access.js +28 -0
- package/dist/access.js.map +1 -0
- 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 +38 -0
- package/dist/directory-memory.d.ts.map +1 -0
- package/dist/directory-memory.js +808 -0
- package/dist/directory-memory.js.map +1 -0
- 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 +7 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +12 -0
- package/dist/errors.js.map +1 -0
- 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 +11 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -0
- package/dist/memory.d.ts +3 -0
- package/dist/memory.d.ts.map +1 -0
- package/dist/memory.js +1905 -0
- package/dist/memory.js.map +1 -0
- 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 +386 -0
- package/dist/repository.d.ts.map +1 -0
- package/dist/repository.js +2 -0
- package/dist/repository.js.map +1 -0
- package/dist/time.d.ts +5 -0
- package/dist/time.d.ts.map +1 -0
- package/dist/time.js +17 -0
- package/dist/time.js.map +1 -0
- package/package.json +32 -4
- package/README.md +0 -3
package/dist/memory.js
ADDED
|
@@ -0,0 +1,1905 @@
|
|
|
1
|
+
import { appIdFromTenantResource, applicationLifecycleTime, applicationMoveKeys, verifyApplicationTrashSnapshot } from "./application-lifecycle.js";
|
|
2
|
+
import { decideLongLived, effectiveActions } from "./access.js";
|
|
3
|
+
import { fail } from "./errors.js";
|
|
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";
|
|
8
|
+
import { asTime, asTimeOrNull, clone, isExpired } from "./time.js";
|
|
9
|
+
const roles = new Set(["owner", "admin", "member"]);
|
|
10
|
+
function empty() {
|
|
11
|
+
return {
|
|
12
|
+
users: new Map(), orgs: new Map(), memberships: new Map(), challenges: new Map(), invites: new Map(),
|
|
13
|
+
sessions: new Map(), clients: new Map(), agents: new Map(), authorizations: new Map(), grants: new Map(),
|
|
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(),
|
|
16
|
+
trusts: new Map(), audits: new Map(), deniedJtis: new Map(), idempotency: 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(),
|
|
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(),
|
|
23
|
+
serviceCredentials: new Map(), principals: new Map(), workloadCredentials: new Map(), audiences: new Map(),
|
|
24
|
+
roles: new Map(), assignments: new Map(), gatewayRoutes: new Map(),
|
|
25
|
+
directory: emptyDirectory(),
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
function stampUser(user) {
|
|
29
|
+
return { ...user, lastOrgId: user.lastOrgId ?? null, emailVerifiedAt: asTimeOrNull(user.emailVerifiedAt), disabledAt: asTimeOrNull(user.disabledAt), createdAt: asTime(user.createdAt) };
|
|
30
|
+
}
|
|
31
|
+
function stampOrg(org) {
|
|
32
|
+
return { ...org, logoUrl: org.logoUrl ?? null, policy: { ...org.policy }, createdAt: asTime(org.createdAt) };
|
|
33
|
+
}
|
|
34
|
+
function stampApplication(row) {
|
|
35
|
+
return {
|
|
36
|
+
...row, allowedScopes: [...row.allowedScopes], allowedFeatures: [...row.allowedFeatures],
|
|
37
|
+
productName: row.productName || row.title, logoUrl: row.logoUrl ?? null, accentColor: row.accentColor ?? null,
|
|
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 ?? {}),
|
|
48
|
+
createdAt: asTime(row.createdAt), updatedAt: asTime(row.updatedAt),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
function canSharePlatformSignIn(row) {
|
|
52
|
+
return row.provider !== "oidc" && (row.provider !== "microsoft" || row.directoryId === "common");
|
|
53
|
+
}
|
|
54
|
+
function stampEnvironment(row) {
|
|
55
|
+
return {
|
|
56
|
+
...row, previousKeyExpiresAt: asTimeOrNull(row.previousKeyExpiresAt), createdAt: asTime(row.createdAt), updatedAt: asTime(row.updatedAt),
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
function stampAppToken(row) {
|
|
60
|
+
return { ...row, payload: clone(row.payload), revokedAt: asTimeOrNull(row.revokedAt), expiresAt: asTimeOrNull(row.expiresAt), createdAt: asTime(row.createdAt) };
|
|
61
|
+
}
|
|
62
|
+
function stampMembership(membership) {
|
|
63
|
+
if (!roles.has(membership.role))
|
|
64
|
+
fail("conflict", "Invalid role.");
|
|
65
|
+
return {
|
|
66
|
+
...membership,
|
|
67
|
+
productionAccess: membership.role === "owner" || membership.productionAccess === true,
|
|
68
|
+
actions: [...membership.actions],
|
|
69
|
+
createdAt: asTime(membership.createdAt),
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
function auditMatches(row, query) {
|
|
73
|
+
if (row.orgId !== query.orgId)
|
|
74
|
+
return false;
|
|
75
|
+
if (query.actorUserId && row.actorUserId !== query.actorUserId)
|
|
76
|
+
return false;
|
|
77
|
+
if (query.action && row.action !== query.action)
|
|
78
|
+
return false;
|
|
79
|
+
if (query.decision && row.decision !== query.decision)
|
|
80
|
+
return false;
|
|
81
|
+
if (query.subject && row.actorUserId !== query.subject && row.actorServiceId !== query.subject && row.agentId !== query.subject && row.target !== query.subject)
|
|
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
|
+
}
|
|
88
|
+
if (query.from && row.at < query.from)
|
|
89
|
+
return false;
|
|
90
|
+
if (query.to && row.at > query.to)
|
|
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;
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
96
|
+
function takeExpiring(map, match, at) {
|
|
97
|
+
const row = [...map.values()].find(match);
|
|
98
|
+
if (!row)
|
|
99
|
+
return null;
|
|
100
|
+
map.delete(row.id);
|
|
101
|
+
if (isExpired(row.expiresAt, asTime(at)))
|
|
102
|
+
return null;
|
|
103
|
+
return clone(row);
|
|
104
|
+
}
|
|
105
|
+
export function createMemoryStore() {
|
|
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
|
+
}
|
|
131
|
+
const tx = (run) => {
|
|
132
|
+
const saved = clone(tables);
|
|
133
|
+
try {
|
|
134
|
+
return run();
|
|
135
|
+
}
|
|
136
|
+
catch (error) {
|
|
137
|
+
tables = saved;
|
|
138
|
+
throw error;
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
const one = (map, id) => {
|
|
142
|
+
const row = map.get(id);
|
|
143
|
+
return row ? clone(row) : null;
|
|
144
|
+
};
|
|
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
|
+
}
|
|
175
|
+
const put = (map, row) => {
|
|
176
|
+
if (map.has(row.id))
|
|
177
|
+
fail("duplicate", "Duplicate key.");
|
|
178
|
+
map.set(row.id, clone(row));
|
|
179
|
+
};
|
|
180
|
+
const replace = (map, row) => {
|
|
181
|
+
if (!map.has(row.id))
|
|
182
|
+
fail("not_found", "Record not found.");
|
|
183
|
+
map.set(row.id, clone(row));
|
|
184
|
+
};
|
|
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
|
+
};
|
|
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
|
+
};
|
|
200
|
+
const client = (id) => tables.clients.get(id) ?? fail("conflict", "Client is missing.");
|
|
201
|
+
const agent = (id) => tables.agents.get(id) ?? fail("conflict", "Agent is missing.");
|
|
202
|
+
const grantRow = (id) => tables.grants.get(id) ?? fail("conflict", "Grant is missing.");
|
|
203
|
+
const membershipsForUser = (userId) => rows(tables.memberships, (row) => row.userId === userId);
|
|
204
|
+
const revokeGrant = (id, at) => {
|
|
205
|
+
const grant = tables.grants.get(id);
|
|
206
|
+
if (!grant)
|
|
207
|
+
return null;
|
|
208
|
+
const changed = grant.revokedAt === null;
|
|
209
|
+
if (changed)
|
|
210
|
+
grant.revokedAt = asTime(at);
|
|
211
|
+
for (const token of tables.longTokens.values()) {
|
|
212
|
+
if (token.grantId === id && token.revokedAt === null)
|
|
213
|
+
token.revokedAt = grant.revokedAt;
|
|
214
|
+
}
|
|
215
|
+
for (const refresh of tables.refreshes.values()) {
|
|
216
|
+
if (refresh.grantId === id && refresh.revokedAt === null)
|
|
217
|
+
refresh.revokedAt = grant.revokedAt;
|
|
218
|
+
}
|
|
219
|
+
return { grant: clone(grant), changed };
|
|
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
|
+
}
|
|
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)); },
|
|
449
|
+
async signup(input) {
|
|
450
|
+
tx(() => {
|
|
451
|
+
const nextUser = stampUser(input.user);
|
|
452
|
+
const nextOrg = stampOrg(input.org);
|
|
453
|
+
const nextMembership = stampMembership(input.membership);
|
|
454
|
+
if (nextMembership.userId !== nextUser.id || nextMembership.orgId !== nextOrg.id || nextMembership.role !== "owner") {
|
|
455
|
+
fail("conflict", "Signup requires the new organization and its owner membership.");
|
|
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
|
+
}
|
|
469
|
+
if ([...tables.users.values()].some((row) => row.email.toLowerCase() === nextUser.email.toLowerCase()))
|
|
470
|
+
fail("duplicate_email", "Email already exists.");
|
|
471
|
+
if ([...tables.orgs.values()].some((row) => row.slug === nextOrg.slug))
|
|
472
|
+
fail("duplicate_slug", "Slug already exists.");
|
|
473
|
+
put(tables.users, nextUser);
|
|
474
|
+
put(tables.orgs, nextOrg);
|
|
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
|
+
}
|
|
488
|
+
});
|
|
489
|
+
},
|
|
490
|
+
async createOrg(input) {
|
|
491
|
+
tx(() => {
|
|
492
|
+
const nextOrg = stampOrg(input.org);
|
|
493
|
+
const nextMembership = stampMembership(input.membership);
|
|
494
|
+
if (nextMembership.orgId !== nextOrg.id || nextMembership.role !== "owner")
|
|
495
|
+
fail("conflict", "A new organization needs an owner membership.");
|
|
496
|
+
user(nextMembership.userId);
|
|
497
|
+
if ([...tables.orgs.values()].some((row) => row.slug === nextOrg.slug))
|
|
498
|
+
fail("duplicate_slug", "Slug already exists.");
|
|
499
|
+
put(tables.orgs, nextOrg);
|
|
500
|
+
put(tables.memberships, nextMembership);
|
|
501
|
+
});
|
|
502
|
+
},
|
|
503
|
+
async getUser(id) { return one(tables.users, id); },
|
|
504
|
+
async findUserByEmail(email) {
|
|
505
|
+
return rows(tables.users, (row) => row.email.toLowerCase() === email.toLowerCase())[0] ?? null;
|
|
506
|
+
},
|
|
507
|
+
async updateUser(next) { tx(() => replace(tables.users, stampUser(next))); },
|
|
508
|
+
async getOrg(id) { return one(tables.orgs, id); },
|
|
509
|
+
async findOrgBySlug(slug) { return rows(tables.orgs, (row) => row.slug === slug)[0] ?? null; },
|
|
510
|
+
async updateOrg(next) {
|
|
511
|
+
tx(() => {
|
|
512
|
+
org(next.id);
|
|
513
|
+
replace(tables.orgs, stampOrg(next));
|
|
514
|
+
});
|
|
515
|
+
},
|
|
516
|
+
async findMembership(userId, orgId) {
|
|
517
|
+
return rows(tables.memberships, (row) => row.userId === userId && row.orgId === orgId)[0] ?? null;
|
|
518
|
+
},
|
|
519
|
+
async listMembershipsByUser(userId) { return membershipsForUser(userId); },
|
|
520
|
+
async listMembershipsByOrg(orgId) { return rows(tables.memberships, (row) => row.orgId === orgId); },
|
|
521
|
+
async saveMembership(membership) {
|
|
522
|
+
tx(() => {
|
|
523
|
+
const next = stampMembership(membership);
|
|
524
|
+
const existing = tables.memberships.get(next.id);
|
|
525
|
+
if (!existing || existing.orgId !== next.orgId || existing.userId !== next.userId)
|
|
526
|
+
fail("not_found", "Member not found.");
|
|
527
|
+
if (existing.role === "owner" && next.role !== "owner") {
|
|
528
|
+
const owners = rows(tables.memberships, (row) => row.orgId === existing.orgId && row.role === "owner");
|
|
529
|
+
if (owners.length < 2)
|
|
530
|
+
fail("last_owner", "An organization must keep an owner.");
|
|
531
|
+
}
|
|
532
|
+
replace(tables.memberships, next);
|
|
533
|
+
});
|
|
534
|
+
},
|
|
535
|
+
async removeMembership(input) {
|
|
536
|
+
tx(() => {
|
|
537
|
+
const at = asTime(input.at);
|
|
538
|
+
const existing = [...tables.memberships.values()].find((row) => row.userId === input.userId && row.orgId === input.orgId);
|
|
539
|
+
if (!existing)
|
|
540
|
+
fail("not_found", "Member not found.");
|
|
541
|
+
user(input.userId);
|
|
542
|
+
if (membershipsForUser(input.userId).length < 2)
|
|
543
|
+
fail("last_membership", "An account must belong to at least one organization.");
|
|
544
|
+
if (existing.role === "owner" && rows(tables.memberships, (row) => row.orgId === input.orgId && row.role === "owner").length < 2) {
|
|
545
|
+
fail("last_owner", "An organization must keep an owner.");
|
|
546
|
+
}
|
|
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
|
+
}
|
|
552
|
+
for (const grant of [...tables.grants.values()].filter((row) => row.userId === input.userId && row.orgId === input.orgId))
|
|
553
|
+
revokeGrant(grant.id, at);
|
|
554
|
+
for (const token of tables.longTokens.values()) {
|
|
555
|
+
if (token.userId === input.userId && token.orgId === input.orgId && token.revokedAt === null)
|
|
556
|
+
token.revokedAt = at;
|
|
557
|
+
}
|
|
558
|
+
});
|
|
559
|
+
},
|
|
560
|
+
async insertChallenge(row) {
|
|
561
|
+
tx(() => {
|
|
562
|
+
user(row.userId);
|
|
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;
|
|
577
|
+
});
|
|
578
|
+
},
|
|
579
|
+
async verifyEmail(tokenHash, at) {
|
|
580
|
+
return tx(() => {
|
|
581
|
+
const stamp = asTime(at);
|
|
582
|
+
const challenge = [...tables.challenges.values()].find((row) => row.tokenHash === tokenHash && row.purpose === "verify");
|
|
583
|
+
if (!challenge || challenge.usedAt || isExpired(challenge.expiresAt, stamp))
|
|
584
|
+
fail("challenge_invalid", "Verification link is no longer valid.");
|
|
585
|
+
const account = tables.users.get(challenge.userId);
|
|
586
|
+
if (!account || account.disabledAt || account.emailVerifiedAt)
|
|
587
|
+
fail("challenge_invalid", "Verification link is no longer valid.");
|
|
588
|
+
account.emailVerifiedAt = stamp;
|
|
589
|
+
challenge.usedAt = stamp;
|
|
590
|
+
return clone(account);
|
|
591
|
+
});
|
|
592
|
+
},
|
|
593
|
+
async resetPassword(input) {
|
|
594
|
+
return tx(() => {
|
|
595
|
+
const stamp = asTime(input.at);
|
|
596
|
+
const challenge = [...tables.challenges.values()].find((row) => row.tokenHash === input.tokenHash && row.purpose === "reset");
|
|
597
|
+
if (!challenge || challenge.usedAt || isExpired(challenge.expiresAt, stamp))
|
|
598
|
+
fail("challenge_invalid", "Reset link is no longer valid.");
|
|
599
|
+
const account = tables.users.get(challenge.userId);
|
|
600
|
+
if (!account || account.disabledAt)
|
|
601
|
+
fail("challenge_invalid", "Reset link is no longer valid.");
|
|
602
|
+
account.passwordHash = input.passwordHash;
|
|
603
|
+
if (!account.emailVerifiedAt)
|
|
604
|
+
account.emailVerifiedAt = stamp;
|
|
605
|
+
for (const pending of tables.challenges.values()) {
|
|
606
|
+
if (pending.userId === account.id && pending.purpose === "reset" && !pending.usedAt)
|
|
607
|
+
pending.usedAt = stamp;
|
|
608
|
+
}
|
|
609
|
+
for (const session of [...tables.sessions.values()]) {
|
|
610
|
+
if (session.userId === account.id)
|
|
611
|
+
deleteSession(session.id);
|
|
612
|
+
}
|
|
613
|
+
return clone(account);
|
|
614
|
+
});
|
|
615
|
+
},
|
|
616
|
+
async insertInvite(row, delivery) {
|
|
617
|
+
tx(() => {
|
|
618
|
+
org(row.orgId);
|
|
619
|
+
user(row.invitedBy);
|
|
620
|
+
if (!roles.has(row.role))
|
|
621
|
+
fail("conflict", "Invalid role.");
|
|
622
|
+
if ([...tables.invites.values()].some((item) => item.tokenHash === row.tokenHash))
|
|
623
|
+
fail("duplicate", "Duplicate key.");
|
|
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;
|
|
666
|
+
});
|
|
667
|
+
},
|
|
668
|
+
async acceptInvite(input) {
|
|
669
|
+
return tx(() => {
|
|
670
|
+
const at = asTime(input.at);
|
|
671
|
+
const invite = [...tables.invites.values()].find((row) => row.tokenHash === input.tokenHash);
|
|
672
|
+
if (!invite || invite.acceptedAt || invite.revokedAt || isExpired(invite.expiresAt, at))
|
|
673
|
+
fail("invite_invalid", "Invite is no longer valid.");
|
|
674
|
+
const account = tables.users.get(input.userId);
|
|
675
|
+
if (!account)
|
|
676
|
+
fail("not_found", "User not found.");
|
|
677
|
+
if (invite.email.toLowerCase() !== input.email.toLowerCase() || invite.email.toLowerCase() !== account.email.toLowerCase()) {
|
|
678
|
+
fail("invite_email", "Invite email does not match the account.");
|
|
679
|
+
}
|
|
680
|
+
org(invite.orgId);
|
|
681
|
+
const existing = [...tables.memberships.values()].find((row) => row.userId === account.id && row.orgId === invite.orgId);
|
|
682
|
+
if (!existing) {
|
|
683
|
+
put(tables.memberships, stampMembership({
|
|
684
|
+
id: input.membershipId, orgId: invite.orgId, userId: account.id, role: invite.role, actions: [...invite.actions],
|
|
685
|
+
productionAccess: invite.productionAccess === true, createdAt: at,
|
|
686
|
+
}));
|
|
687
|
+
}
|
|
688
|
+
invite.acceptedAt = at;
|
|
689
|
+
return clone(invite);
|
|
690
|
+
});
|
|
691
|
+
},
|
|
692
|
+
async insertSession(row) {
|
|
693
|
+
tx(() => {
|
|
694
|
+
user(row.userId);
|
|
695
|
+
org(row.orgId);
|
|
696
|
+
if ([...tables.sessions.values()].some((item) => item.secretHash === row.secretHash))
|
|
697
|
+
fail("duplicate", "Duplicate key.");
|
|
698
|
+
put(tables.sessions, { ...row, expiresAt: asTime(row.expiresAt), createdAt: asTime(row.createdAt) });
|
|
699
|
+
});
|
|
700
|
+
},
|
|
701
|
+
async findSessionByHash(secretHash) { return rows(tables.sessions, (row) => row.secretHash === secretHash)[0] ?? null; },
|
|
702
|
+
async updateSession(session) {
|
|
703
|
+
tx(() => {
|
|
704
|
+
const existing = tables.sessions.get(session.id);
|
|
705
|
+
if (!existing)
|
|
706
|
+
fail("not_found", "Session not found.");
|
|
707
|
+
user(session.userId);
|
|
708
|
+
org(session.orgId);
|
|
709
|
+
replace(tables.sessions, { ...session, expiresAt: asTime(session.expiresAt), createdAt: asTime(session.createdAt) });
|
|
710
|
+
});
|
|
711
|
+
},
|
|
712
|
+
async deleteSession(id) { tx(() => deleteSession(id)); },
|
|
713
|
+
async insertClient(row) {
|
|
714
|
+
tx(() => {
|
|
715
|
+
if (row.authMethod !== "none" && row.authMethod !== "client_secret_basic")
|
|
716
|
+
fail("conflict", "Invalid client.");
|
|
717
|
+
put(tables.clients, { ...row, redirectUris: [...row.redirectUris], createdAt: asTime(row.createdAt) });
|
|
718
|
+
});
|
|
719
|
+
},
|
|
720
|
+
async getClient(id) { return one(tables.clients, id); },
|
|
721
|
+
async insertAgent(row) {
|
|
722
|
+
tx(() => {
|
|
723
|
+
client(row.clientId);
|
|
724
|
+
user(row.ownerUserId);
|
|
725
|
+
org(row.orgId);
|
|
726
|
+
if ([...tables.agents.values()].some((item) => item.clientId === row.clientId && item.ownerUserId === row.ownerUserId && item.orgId === row.orgId)) {
|
|
727
|
+
fail("duplicate", "Duplicate key.");
|
|
728
|
+
}
|
|
729
|
+
put(tables.agents, { ...row, suspendedAt: asTimeOrNull(row.suspendedAt), createdAt: asTime(row.createdAt) });
|
|
730
|
+
});
|
|
731
|
+
},
|
|
732
|
+
async getAgent(id) { return one(tables.agents, id); },
|
|
733
|
+
async findAgentByClientOwner(clientId, ownerUserId, orgId) {
|
|
734
|
+
return rows(tables.agents, (row) => row.clientId === clientId && row.ownerUserId === ownerUserId && row.orgId === orgId)[0] ?? null;
|
|
735
|
+
},
|
|
736
|
+
async listAgentsByOrg(orgId) { return rows(tables.agents, (row) => row.orgId === orgId); },
|
|
737
|
+
async suspendAgent(id, at) {
|
|
738
|
+
return tx(() => {
|
|
739
|
+
const stamp = asTime(at);
|
|
740
|
+
const existing = tables.agents.get(id);
|
|
741
|
+
if (!existing)
|
|
742
|
+
return null;
|
|
743
|
+
existing.suspendedAt = stamp;
|
|
744
|
+
const revoked = [...tables.grants.values()]
|
|
745
|
+
.filter((row) => row.agentId === id)
|
|
746
|
+
.map((row) => revokeGrant(row.id, stamp))
|
|
747
|
+
.filter((row) => row !== null && row.changed)
|
|
748
|
+
.map((row) => row.grant);
|
|
749
|
+
return { agent: clone(existing), revoked };
|
|
750
|
+
});
|
|
751
|
+
},
|
|
752
|
+
async insertAuthorization(row) {
|
|
753
|
+
tx(() => {
|
|
754
|
+
client(row.clientId);
|
|
755
|
+
if (row.orgId)
|
|
756
|
+
org(row.orgId);
|
|
757
|
+
if (row.userId)
|
|
758
|
+
user(row.userId);
|
|
759
|
+
if (row.agentId)
|
|
760
|
+
agent(row.agentId);
|
|
761
|
+
if (row.grantId)
|
|
762
|
+
grantRow(row.grantId);
|
|
763
|
+
put(tables.authorizations, {
|
|
764
|
+
...row, actions: [...row.actions], resources: [...row.resources], lastPollAt: asTimeOrNull(row.lastPollAt),
|
|
765
|
+
expiresAt: asTime(row.expiresAt), createdAt: asTime(row.createdAt),
|
|
766
|
+
});
|
|
767
|
+
});
|
|
768
|
+
},
|
|
769
|
+
async getAuthorization(id) { return one(tables.authorizations, id); },
|
|
770
|
+
async findAuthorization(filter) {
|
|
771
|
+
return rows(tables.authorizations, (row) => (filter.codeHash === undefined || row.codeHash === filter.codeHash)
|
|
772
|
+
&& (filter.deviceCodeHash === undefined || row.deviceCodeHash === filter.deviceCodeHash)
|
|
773
|
+
&& (filter.userCodeHash === undefined || row.userCodeHash === filter.userCodeHash))[0] ?? null;
|
|
774
|
+
},
|
|
775
|
+
async updateAuthorization(row) {
|
|
776
|
+
tx(() => {
|
|
777
|
+
if (!tables.authorizations.has(row.id))
|
|
778
|
+
fail("not_found", "Authorization not found.");
|
|
779
|
+
client(row.clientId);
|
|
780
|
+
if (row.orgId)
|
|
781
|
+
org(row.orgId);
|
|
782
|
+
if (row.userId)
|
|
783
|
+
user(row.userId);
|
|
784
|
+
if (row.agentId)
|
|
785
|
+
agent(row.agentId);
|
|
786
|
+
if (row.grantId)
|
|
787
|
+
grantRow(row.grantId);
|
|
788
|
+
replace(tables.authorizations, {
|
|
789
|
+
...row, actions: [...row.actions], resources: [...row.resources], lastPollAt: asTimeOrNull(row.lastPollAt),
|
|
790
|
+
expiresAt: asTime(row.expiresAt), createdAt: asTime(row.createdAt),
|
|
791
|
+
});
|
|
792
|
+
});
|
|
793
|
+
},
|
|
794
|
+
async listAuthorizationsByStatus(status) { return rows(tables.authorizations, (row) => row.status === status); },
|
|
795
|
+
async insertGrant(row) {
|
|
796
|
+
tx(() => {
|
|
797
|
+
user(row.userId);
|
|
798
|
+
org(row.orgId);
|
|
799
|
+
client(row.clientId);
|
|
800
|
+
agent(row.agentId);
|
|
801
|
+
if (!tables.authorizations.has(row.approvalRequestId))
|
|
802
|
+
fail("conflict", "Authorization request is missing.");
|
|
803
|
+
put(tables.grants, {
|
|
804
|
+
...row, actions: [...row.actions], resources: [...row.resources], createdAt: asTime(row.createdAt),
|
|
805
|
+
expiresAt: asTime(row.expiresAt), revokedAt: asTimeOrNull(row.revokedAt),
|
|
806
|
+
});
|
|
807
|
+
});
|
|
808
|
+
},
|
|
809
|
+
async getGrant(id) { return one(tables.grants, id); },
|
|
810
|
+
async updateGrant(row) {
|
|
811
|
+
tx(() => {
|
|
812
|
+
if (!tables.grants.has(row.id))
|
|
813
|
+
fail("not_found", "Grant not found.");
|
|
814
|
+
user(row.userId);
|
|
815
|
+
org(row.orgId);
|
|
816
|
+
replace(tables.grants, {
|
|
817
|
+
...row, actions: [...row.actions], resources: [...row.resources], createdAt: asTime(row.createdAt),
|
|
818
|
+
expiresAt: asTime(row.expiresAt), revokedAt: asTimeOrNull(row.revokedAt),
|
|
819
|
+
});
|
|
820
|
+
});
|
|
821
|
+
},
|
|
822
|
+
async listGrants(filter) {
|
|
823
|
+
return rows(tables.grants, (row) => (filter.orgId === undefined || row.orgId === filter.orgId)
|
|
824
|
+
&& (filter.userId === undefined || row.userId === filter.userId)
|
|
825
|
+
&& (filter.agentId === undefined || row.agentId === filter.agentId));
|
|
826
|
+
},
|
|
827
|
+
async revokeGrant(id, at) { return tx(() => revokeGrant(id, at)); },
|
|
828
|
+
async insertLongToken(row) {
|
|
829
|
+
tx(() => {
|
|
830
|
+
user(row.userId);
|
|
831
|
+
org(row.orgId);
|
|
832
|
+
if (row.grantId)
|
|
833
|
+
grantRow(row.grantId);
|
|
834
|
+
if (row.agentId)
|
|
835
|
+
agent(row.agentId);
|
|
836
|
+
if (row.kind !== "personal" && row.kind !== "agent")
|
|
837
|
+
fail("conflict", "Invalid token.");
|
|
838
|
+
if ([...tables.longTokens.values()].some((item) => item.hash === row.hash))
|
|
839
|
+
fail("duplicate", "Duplicate key.");
|
|
840
|
+
put(tables.longTokens, {
|
|
841
|
+
...row, actions: [...row.actions], resources: [...row.resources], expiresAt: asTimeOrNull(row.expiresAt),
|
|
842
|
+
revokedAt: asTimeOrNull(row.revokedAt), createdAt: asTime(row.createdAt), lastUsedAt: asTimeOrNull(row.lastUsedAt),
|
|
843
|
+
});
|
|
844
|
+
});
|
|
845
|
+
},
|
|
846
|
+
async getLongToken(id) { return one(tables.longTokens, id); },
|
|
847
|
+
async findLongTokenByHash(hash) { return rows(tables.longTokens, (row) => row.hash === hash)[0] ?? null; },
|
|
848
|
+
async updateLongToken(row) {
|
|
849
|
+
tx(() => {
|
|
850
|
+
if (!tables.longTokens.has(row.id))
|
|
851
|
+
fail("not_found", "Token not found.");
|
|
852
|
+
replace(tables.longTokens, {
|
|
853
|
+
...row, actions: [...row.actions], resources: [...row.resources], expiresAt: asTimeOrNull(row.expiresAt),
|
|
854
|
+
revokedAt: asTimeOrNull(row.revokedAt), createdAt: asTime(row.createdAt), lastUsedAt: asTimeOrNull(row.lastUsedAt),
|
|
855
|
+
});
|
|
856
|
+
});
|
|
857
|
+
},
|
|
858
|
+
async listLongTokens(filter) {
|
|
859
|
+
return rows(tables.longTokens, (row) => (filter.orgId === undefined || row.orgId === filter.orgId)
|
|
860
|
+
&& (filter.userId === undefined || row.userId === filter.userId)
|
|
861
|
+
&& (filter.grantId === undefined || row.grantId === filter.grantId));
|
|
862
|
+
},
|
|
863
|
+
async revokeLongToken(id, at) {
|
|
864
|
+
return tx(() => {
|
|
865
|
+
const token = tables.longTokens.get(id);
|
|
866
|
+
if (!token)
|
|
867
|
+
return null;
|
|
868
|
+
const stamp = asTime(at);
|
|
869
|
+
const already = token.revokedAt !== null;
|
|
870
|
+
if (!already)
|
|
871
|
+
token.revokedAt = stamp;
|
|
872
|
+
const revocation = token.grantId && !already ? revokeGrant(token.grantId, stamp) : null;
|
|
873
|
+
return { token: clone(token), grant: revocation?.grant ?? null, grantChanged: revocation?.changed ?? false };
|
|
874
|
+
});
|
|
875
|
+
},
|
|
876
|
+
async longLivedAccess(hash, at) {
|
|
877
|
+
const stamp = asTime(at);
|
|
878
|
+
const token = rows(tables.longTokens, (row) => row.hash === hash)[0] ?? null;
|
|
879
|
+
return decideLongLived({
|
|
880
|
+
token,
|
|
881
|
+
user: token ? one(tables.users, token.userId) : null,
|
|
882
|
+
membership: token ? rows(tables.memberships, (row) => row.userId === token.userId && row.orgId === token.orgId)[0] ?? null : null,
|
|
883
|
+
grant: token?.grantId ? one(tables.grants, token.grantId) : null,
|
|
884
|
+
agent: token?.agentId ? one(tables.agents, token.agentId) : null,
|
|
885
|
+
at: stamp,
|
|
886
|
+
});
|
|
887
|
+
},
|
|
888
|
+
async insertRefresh(row) {
|
|
889
|
+
tx(() => {
|
|
890
|
+
user(row.userId);
|
|
891
|
+
org(row.orgId);
|
|
892
|
+
client(row.clientId);
|
|
893
|
+
if (row.grantId)
|
|
894
|
+
grantRow(row.grantId);
|
|
895
|
+
if (row.agentId)
|
|
896
|
+
agent(row.agentId);
|
|
897
|
+
if ([...tables.refreshes.values()].some((item) => item.hash === row.hash))
|
|
898
|
+
fail("duplicate", "Duplicate key.");
|
|
899
|
+
put(tables.refreshes, {
|
|
900
|
+
...row, actions: [...row.actions], resources: [...row.resources], expiresAt: asTime(row.expiresAt),
|
|
901
|
+
rotatedAt: asTimeOrNull(row.rotatedAt), revokedAt: asTimeOrNull(row.revokedAt), createdAt: asTime(row.createdAt),
|
|
902
|
+
});
|
|
903
|
+
});
|
|
904
|
+
},
|
|
905
|
+
async findRefreshByHash(hash) { return rows(tables.refreshes, (row) => row.hash === hash)[0] ?? null; },
|
|
906
|
+
async rotateRefresh(input) {
|
|
907
|
+
return tx(() => {
|
|
908
|
+
const at = asTime(input.at);
|
|
909
|
+
const current = [...tables.refreshes.values()].find((row) => row.hash === input.hash);
|
|
910
|
+
if (!current || current.clientId !== input.clientId)
|
|
911
|
+
return { status: "missing" };
|
|
912
|
+
if (current.rotatedAt || current.revokedAt) {
|
|
913
|
+
for (const refresh of tables.refreshes.values()) {
|
|
914
|
+
if (refresh.familyId === current.familyId && refresh.revokedAt === null)
|
|
915
|
+
refresh.revokedAt = at;
|
|
916
|
+
}
|
|
917
|
+
const revocation = current.grantId ? revokeGrant(current.grantId, at) : null;
|
|
918
|
+
return { status: "reuse", grant: revocation?.grant ?? null, grantChanged: revocation?.changed ?? false };
|
|
919
|
+
}
|
|
920
|
+
if (isExpired(current.expiresAt, at))
|
|
921
|
+
return { status: "expired" };
|
|
922
|
+
const account = tables.users.get(current.userId);
|
|
923
|
+
if (!account || account.disabledAt)
|
|
924
|
+
return { status: "inactive", reason: "user" };
|
|
925
|
+
const membership = [...tables.memberships.values()].find((row) => row.userId === current.userId && row.orgId === current.orgId) ?? null;
|
|
926
|
+
if (!membership)
|
|
927
|
+
return { status: "inactive", reason: "membership" };
|
|
928
|
+
const grant = current.grantId ? tables.grants.get(current.grantId) ?? null : null;
|
|
929
|
+
if (current.grantId && (!grant || grant.revokedAt || isExpired(grant.expiresAt, at)))
|
|
930
|
+
return { status: "inactive", reason: "grant" };
|
|
931
|
+
const actions = effectiveActions(membership, current.actions, grant);
|
|
932
|
+
if (!actions.length)
|
|
933
|
+
return { status: "inactive", reason: "actions" };
|
|
934
|
+
if (input.next.hash === current.hash || tables.refreshes.has(input.next.id) || [...tables.refreshes.values()].some((row) => row.hash === input.next.hash)) {
|
|
935
|
+
fail("duplicate", "Duplicate key.");
|
|
936
|
+
}
|
|
937
|
+
current.rotatedAt = at;
|
|
938
|
+
const next = {
|
|
939
|
+
id: input.next.id, hash: input.next.hash, familyId: current.familyId, grantId: current.grantId, clientId: current.clientId,
|
|
940
|
+
userId: current.userId, orgId: current.orgId, audience: current.audience, actions, resources: [...current.resources],
|
|
941
|
+
agentId: current.agentId, expiresAt: asTime(input.next.expiresAt), rotatedAt: null, revokedAt: null, createdAt: asTime(input.next.createdAt),
|
|
942
|
+
};
|
|
943
|
+
put(tables.refreshes, next);
|
|
944
|
+
return { status: "rotated", token: clone(next), actions: [...actions], grant: grant ? clone(grant) : null };
|
|
945
|
+
});
|
|
946
|
+
},
|
|
947
|
+
async revokeRefreshFamily(hash, at) {
|
|
948
|
+
tx(() => {
|
|
949
|
+
const stamp = asTime(at);
|
|
950
|
+
const current = [...tables.refreshes.values()].find((row) => row.hash === hash);
|
|
951
|
+
if (!current)
|
|
952
|
+
return;
|
|
953
|
+
for (const refresh of tables.refreshes.values()) {
|
|
954
|
+
if (refresh.familyId === current.familyId && refresh.revokedAt === null)
|
|
955
|
+
refresh.revokedAt = stamp;
|
|
956
|
+
}
|
|
957
|
+
});
|
|
958
|
+
},
|
|
959
|
+
async insertInstance(row) {
|
|
960
|
+
tx(() => {
|
|
961
|
+
agent(row.agentId);
|
|
962
|
+
grantRow(row.grantId);
|
|
963
|
+
put(tables.instances, { ...row, createdAt: asTime(row.createdAt), lastSeenAt: asTime(row.lastSeenAt) });
|
|
964
|
+
});
|
|
965
|
+
},
|
|
966
|
+
async insertExecution(row) {
|
|
967
|
+
tx(() => {
|
|
968
|
+
agent(row.agentId);
|
|
969
|
+
if (row.instanceId && !tables.instances.has(row.instanceId))
|
|
970
|
+
fail("conflict", "Instance is missing.");
|
|
971
|
+
if (row.grantId && !tables.grants.has(row.grantId))
|
|
972
|
+
fail("conflict", "Grant is missing.");
|
|
973
|
+
put(tables.executions, { ...row, createdAt: asTime(row.createdAt) });
|
|
974
|
+
});
|
|
975
|
+
},
|
|
976
|
+
async insertProvider(row) {
|
|
977
|
+
tx(() => {
|
|
978
|
+
user(row.userId);
|
|
979
|
+
org(row.orgId);
|
|
980
|
+
put(tables.providers, { ...row, scopes: [...row.scopes], revokedAt: asTimeOrNull(row.revokedAt), createdAt: asTime(row.createdAt) });
|
|
981
|
+
});
|
|
982
|
+
},
|
|
983
|
+
async getProvider(id) { return one(tables.providers, id); },
|
|
984
|
+
async listProviders(orgId, userId) {
|
|
985
|
+
return rows(tables.providers, (row) => row.orgId === orgId && row.userId === userId);
|
|
986
|
+
},
|
|
987
|
+
async insertTrust(row) {
|
|
988
|
+
tx(() => {
|
|
989
|
+
org(row.orgId);
|
|
990
|
+
put(tables.trusts, { ...row, actions: [...row.actions], jwks: clone(row.jwks), disabledAt: asTimeOrNull(row.disabledAt), createdAt: asTime(row.createdAt) });
|
|
991
|
+
});
|
|
992
|
+
},
|
|
993
|
+
async getTrust(id) { return one(tables.trusts, id); },
|
|
994
|
+
async listTrusts(issuer, audience) {
|
|
995
|
+
return rows(tables.trusts, (row) => row.issuer === issuer && row.audience === audience);
|
|
996
|
+
},
|
|
997
|
+
async insertAudit(row) {
|
|
998
|
+
tx(() => writeAudit(row));
|
|
999
|
+
},
|
|
1000
|
+
async listAudit(query) {
|
|
1001
|
+
return rows(tables.audits, (row) => auditMatches(row, query))
|
|
1002
|
+
.sort((left, right) => right.at.localeCompare(left.at) || (right.id > left.id ? 1 : right.id < left.id ? -1 : 0))
|
|
1003
|
+
.slice(query.offset, query.offset + query.limit);
|
|
1004
|
+
},
|
|
1005
|
+
async getDeniedJti(id) { return one(tables.deniedJtis, id); },
|
|
1006
|
+
async denyJti(row) { tx(() => { if (!tables.deniedJtis.has(row.id))
|
|
1007
|
+
tables.deniedJtis.set(row.id, { ...row }); }); },
|
|
1008
|
+
async getIdempotency(id) { return one(tables.idempotency, id); },
|
|
1009
|
+
async insertIdempotency(row) {
|
|
1010
|
+
tx(() => put(tables.idempotency, { ...row, createdAt: asTime(row.createdAt) }));
|
|
1011
|
+
},
|
|
1012
|
+
async insertApplication(row) { tx(() => insertApp(row)); },
|
|
1013
|
+
async registerApplication({ application, environments, creatorAccess, audit }) {
|
|
1014
|
+
tx(() => {
|
|
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);
|
|
1031
|
+
});
|
|
1032
|
+
},
|
|
1033
|
+
async getApplication(id) { return activeApplication(id) ? one(tables.applications, id) : null; },
|
|
1034
|
+
async listApplications(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));
|
|
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); }); },
|
|
1165
|
+
async updateApplication(row) {
|
|
1166
|
+
return tx(() => {
|
|
1167
|
+
const current = activeApplication(row.id);
|
|
1168
|
+
if (!current)
|
|
1169
|
+
fail("not_found", "Application not found.");
|
|
1170
|
+
if (current.orgId !== row.orgId)
|
|
1171
|
+
fail("conflict", "An application cannot change organization.");
|
|
1172
|
+
if (row.status !== "active" && row.status !== "disabled")
|
|
1173
|
+
fail("conflict", "Invalid application status.");
|
|
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;
|
|
1209
|
+
});
|
|
1210
|
+
},
|
|
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;
|
|
1215
|
+
},
|
|
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));
|
|
1221
|
+
},
|
|
1222
|
+
async updateEnvironment(row) {
|
|
1223
|
+
tx(() => {
|
|
1224
|
+
const current = tables.environments.get(row.id);
|
|
1225
|
+
if (!current || !activeApplication(current.appId))
|
|
1226
|
+
fail("not_found", "Environment not found.");
|
|
1227
|
+
if (current.appId !== row.appId || current.orgId !== row.orgId || current.name !== row.name)
|
|
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.");
|
|
1233
|
+
if (row.status !== "active" && row.status !== "disabled")
|
|
1234
|
+
fail("conflict", "Invalid environment status.");
|
|
1235
|
+
replace(tables.environments, stampEnvironment(row));
|
|
1236
|
+
});
|
|
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
|
+
},
|
|
1339
|
+
async insertAppToken(row) {
|
|
1340
|
+
tx(() => {
|
|
1341
|
+
const app = activeApplication(row.appId);
|
|
1342
|
+
if (!app)
|
|
1343
|
+
fail("conflict", "Application is missing.");
|
|
1344
|
+
const environment = tables.environments.get(row.environmentId);
|
|
1345
|
+
if (!environment || environment.appId !== row.appId)
|
|
1346
|
+
fail("conflict", "Environment is missing.");
|
|
1347
|
+
if (row.orgId !== app.orgId)
|
|
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.");
|
|
1351
|
+
put(tables.appTokens, stampAppToken(row));
|
|
1352
|
+
});
|
|
1353
|
+
},
|
|
1354
|
+
async getAppToken(id) {
|
|
1355
|
+
const token = tables.appTokens.get(id);
|
|
1356
|
+
return token && activeApplication(token.appId) ? clone(token) : null;
|
|
1357
|
+
},
|
|
1358
|
+
async listAppTokens(filter) {
|
|
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))
|
|
1360
|
+
.sort((left, right) => right.createdAt.localeCompare(left.createdAt) || right.id.localeCompare(left.id));
|
|
1361
|
+
},
|
|
1362
|
+
async revokeAppToken(id, at) {
|
|
1363
|
+
return tx(() => {
|
|
1364
|
+
const row = tables.appTokens.get(id);
|
|
1365
|
+
if (!row || !activeApplication(row.appId))
|
|
1366
|
+
return null;
|
|
1367
|
+
if (!row.revokedAt)
|
|
1368
|
+
row.revokedAt = asTime(at);
|
|
1369
|
+
return clone(row);
|
|
1370
|
+
});
|
|
1371
|
+
},
|
|
1372
|
+
async revokeAppTokens(filter, at) {
|
|
1373
|
+
return tx(() => {
|
|
1374
|
+
const stamp = asTime(at);
|
|
1375
|
+
let count = 0;
|
|
1376
|
+
for (const row of tables.appTokens.values()) {
|
|
1377
|
+
if (row.revokedAt || !activeApplication(row.appId))
|
|
1378
|
+
continue;
|
|
1379
|
+
if (filter.appId && row.appId !== filter.appId)
|
|
1380
|
+
continue;
|
|
1381
|
+
if (filter.environmentId && row.environmentId !== filter.environmentId)
|
|
1382
|
+
continue;
|
|
1383
|
+
if (filter.identityId && row.ownerIdentityId !== filter.identityId)
|
|
1384
|
+
continue;
|
|
1385
|
+
if (filter.orgId && row.orgId !== filter.orgId)
|
|
1386
|
+
continue;
|
|
1387
|
+
row.revokedAt = stamp;
|
|
1388
|
+
count += 1;
|
|
1389
|
+
}
|
|
1390
|
+
return count;
|
|
1391
|
+
});
|
|
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
|
+
},
|
|
1489
|
+
async saveSignInConnection(row) {
|
|
1490
|
+
tx(() => {
|
|
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);
|
|
1499
|
+
});
|
|
1500
|
+
},
|
|
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));
|
|
1505
|
+
},
|
|
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
|
+
});
|
|
1520
|
+
},
|
|
1521
|
+
async saveAppSignIn(appId, providers) {
|
|
1522
|
+
tx(() => {
|
|
1523
|
+
if (!activeApplication(appId))
|
|
1524
|
+
fail("conflict", "Application is missing.");
|
|
1525
|
+
tables.appSignIn.set(appId, [...providers]);
|
|
1526
|
+
});
|
|
1527
|
+
},
|
|
1528
|
+
async getAppSignIn(appId) { return [...(tables.appSignIn.get(appId) ?? [])]; },
|
|
1529
|
+
async saveRedirects(environmentId, uris, orgId) {
|
|
1530
|
+
tx(() => {
|
|
1531
|
+
const environment = tables.environments.get(environmentId);
|
|
1532
|
+
if (!environment || !activeApplication(environment.appId) || (orgId && environment.orgId !== orgId))
|
|
1533
|
+
fail("conflict", "Environment is missing.");
|
|
1534
|
+
tables.redirects.set(environmentId, [...uris]);
|
|
1535
|
+
});
|
|
1536
|
+
},
|
|
1537
|
+
async getRedirects(environmentId) { return [...(tables.redirects.get(environmentId) ?? [])]; },
|
|
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
|
+
},
|
|
1614
|
+
async takeSsoLogin(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;
|
|
1730
|
+
},
|
|
1731
|
+
async takeSsoExchange(codeHash, at) {
|
|
1732
|
+
return tx(() => takeExpiring(tables.ssoExchanges, (row) => row.codeHash === codeHash && hasSsoExchangeToken(row), at));
|
|
1733
|
+
},
|
|
1734
|
+
async insertServiceCredential(row) {
|
|
1735
|
+
tx(() => {
|
|
1736
|
+
org(row.orgId);
|
|
1737
|
+
if ([...tables.serviceCredentials.values()].some((item) => item.secretHash === row.secretHash))
|
|
1738
|
+
fail("duplicate", "Duplicate key.");
|
|
1739
|
+
put(tables.serviceCredentials, { ...row, appIds: [...row.appIds], permissions: [...row.permissions], revokedAt: asTimeOrNull(row.revokedAt), createdAt: asTime(row.createdAt) });
|
|
1740
|
+
});
|
|
1741
|
+
},
|
|
1742
|
+
async listServiceCredentials(orgId) {
|
|
1743
|
+
return rows(tables.serviceCredentials, (row) => row.orgId === orgId).sort((left, right) => right.createdAt.localeCompare(left.createdAt));
|
|
1744
|
+
},
|
|
1745
|
+
async findServiceCredentialByHash(hash) {
|
|
1746
|
+
return rows(tables.serviceCredentials, (row) => row.secretHash === hash)[0] ?? null;
|
|
1747
|
+
},
|
|
1748
|
+
async revokeServiceCredential(id, at) {
|
|
1749
|
+
return tx(() => {
|
|
1750
|
+
const row = tables.serviceCredentials.get(id);
|
|
1751
|
+
if (!row)
|
|
1752
|
+
return null;
|
|
1753
|
+
if (!row.revokedAt)
|
|
1754
|
+
row.revokedAt = asTime(at);
|
|
1755
|
+
return clone(row);
|
|
1756
|
+
});
|
|
1757
|
+
},
|
|
1758
|
+
async insertPrincipal(row) {
|
|
1759
|
+
tx(() => {
|
|
1760
|
+
org(row.orgId);
|
|
1761
|
+
if ([...tables.principals.values()].some((item) => item.clientId === row.clientId))
|
|
1762
|
+
fail("duplicate", "Duplicate key.");
|
|
1763
|
+
put(tables.principals, { ...row, createdAt: asTime(row.createdAt) });
|
|
1764
|
+
});
|
|
1765
|
+
},
|
|
1766
|
+
async listPrincipals(orgId) {
|
|
1767
|
+
return rows(tables.principals, (row) => row.orgId === orgId).sort((left, right) => right.createdAt.localeCompare(left.createdAt));
|
|
1768
|
+
},
|
|
1769
|
+
async findPrincipalByClientId(clientId) {
|
|
1770
|
+
return rows(tables.principals, (row) => row.clientId === clientId)[0] ?? null;
|
|
1771
|
+
},
|
|
1772
|
+
async insertWorkloadCredential(row) {
|
|
1773
|
+
tx(() => {
|
|
1774
|
+
const principal = tables.principals.get(row.principalId);
|
|
1775
|
+
if (!principal || principal.orgId !== row.orgId)
|
|
1776
|
+
fail("conflict", "Workload principal is missing.");
|
|
1777
|
+
put(tables.workloadCredentials, { ...row, jwks: clone(row.jwks), createdAt: asTime(row.createdAt) });
|
|
1778
|
+
});
|
|
1779
|
+
},
|
|
1780
|
+
async listWorkloadCredentials(principalId) {
|
|
1781
|
+
return rows(tables.workloadCredentials, (row) => row.principalId === principalId);
|
|
1782
|
+
},
|
|
1783
|
+
async insertAudience(row) {
|
|
1784
|
+
tx(() => {
|
|
1785
|
+
org(row.orgId);
|
|
1786
|
+
if (row.appId && activeApplication(row.appId)?.orgId !== row.orgId)
|
|
1787
|
+
fail("conflict", "Choose an application from this tenant.");
|
|
1788
|
+
if ([...tables.audiences.values()].some((item) => item.orgId === row.orgId && item.identifier === row.identifier))
|
|
1789
|
+
fail("duplicate", "Duplicate key.");
|
|
1790
|
+
put(tables.audiences, { ...row, createdAt: asTime(row.createdAt) });
|
|
1791
|
+
});
|
|
1792
|
+
},
|
|
1793
|
+
async listAudiences(orgId) {
|
|
1794
|
+
return rows(tables.audiences, (row) => row.orgId === orgId && (!row.appId || activeApplication(row.appId)?.orgId === orgId));
|
|
1795
|
+
},
|
|
1796
|
+
async findAudience(orgId, identifier) {
|
|
1797
|
+
return rows(tables.audiences, (row) => row.orgId === orgId && row.identifier === identifier
|
|
1798
|
+
&& (!row.appId || activeApplication(row.appId)?.orgId === orgId))[0] ?? null;
|
|
1799
|
+
},
|
|
1800
|
+
async insertRole(row) {
|
|
1801
|
+
tx(() => { org(row.orgId); put(tables.roles, { ...row, actions: [...row.actions], createdAt: asTime(row.createdAt) }); });
|
|
1802
|
+
},
|
|
1803
|
+
async listRoles(orgId) { return rows(tables.roles, (row) => row.orgId === orgId); },
|
|
1804
|
+
async insertAssignment(row) {
|
|
1805
|
+
tx(() => {
|
|
1806
|
+
org(row.orgId);
|
|
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.");
|
|
1818
|
+
put(tables.assignments, { ...row, createdAt: asTime(row.createdAt) });
|
|
1819
|
+
});
|
|
1820
|
+
},
|
|
1821
|
+
async listAssignments(orgId, principalId) {
|
|
1822
|
+
return rows(tables.assignments, (row) => row.orgId === orgId && (!principalId || row.principalId === principalId));
|
|
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
|
+
},
|
|
1833
|
+
async insertGatewayRoute(row) {
|
|
1834
|
+
tx(() => {
|
|
1835
|
+
org(row.orgId);
|
|
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
|
+
}
|
|
1843
|
+
put(tables.gatewayRoutes, { ...row, createdAt: asTime(row.createdAt) });
|
|
1844
|
+
});
|
|
1845
|
+
},
|
|
1846
|
+
async listGatewayRoutes(orgId) { return rows(tables.gatewayRoutes, (row) => !orgId || row.orgId === orgId); },
|
|
1847
|
+
async deleteGatewayRoute(id, orgId) {
|
|
1848
|
+
tx(() => {
|
|
1849
|
+
const row = tables.gatewayRoutes.get(id);
|
|
1850
|
+
if (!row || row.orgId !== orgId)
|
|
1851
|
+
fail("not_found", "Route not found.");
|
|
1852
|
+
tables.gatewayRoutes.delete(id);
|
|
1853
|
+
});
|
|
1854
|
+
},
|
|
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
|
+
}),
|
|
1865
|
+
async ping() { },
|
|
1866
|
+
async purgeExpired(at) {
|
|
1867
|
+
tx(() => {
|
|
1868
|
+
const stamp = asTime(at);
|
|
1869
|
+
const seconds = Math.floor(Date.parse(stamp) / 1000);
|
|
1870
|
+
for (const row of [...tables.sessions.values()])
|
|
1871
|
+
if (isExpired(row.expiresAt, stamp))
|
|
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);
|
|
1877
|
+
for (const row of [...tables.challenges.values()])
|
|
1878
|
+
if (isExpired(row.expiresAt, stamp))
|
|
1879
|
+
tables.challenges.delete(row.id);
|
|
1880
|
+
for (const row of [...tables.authorizations.values()])
|
|
1881
|
+
if (isExpired(row.expiresAt, stamp))
|
|
1882
|
+
tables.authorizations.delete(row.id);
|
|
1883
|
+
for (const row of [...tables.deniedJtis.values()])
|
|
1884
|
+
if (row.exp <= seconds)
|
|
1885
|
+
tables.deniedJtis.delete(row.id);
|
|
1886
|
+
for (const row of [...tables.ssoLogins.values()])
|
|
1887
|
+
if (isExpired(row.expiresAt, stamp))
|
|
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);
|
|
1897
|
+
for (const row of [...tables.ssoExchanges.values()])
|
|
1898
|
+
if (isExpired(row.expiresAt, stamp))
|
|
1899
|
+
tables.ssoExchanges.delete(row.id);
|
|
1900
|
+
});
|
|
1901
|
+
},
|
|
1902
|
+
};
|
|
1903
|
+
return store;
|
|
1904
|
+
}
|
|
1905
|
+
//# sourceMappingURL=memory.js.map
|