@x12i/keyrox-store 0.2.4 → 0.2.6

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/memory.js CHANGED
@@ -5,6 +5,9 @@ import { hostedEmailCodePolicy } from "./email-code-policy.js";
5
5
  import { createMemoryNotificationWebhookJobs } from "./notification-webhook-jobs.js";
6
6
  import { createMemoryNotificationDeliveries, insertMemoryNotificationDelivery } from "./notification-delivery.js";
7
7
  import { bindDirectoryMemory, emptyDirectory, repairDirectoryStructure } from "./directory-memory.js";
8
+ import { bindDelegationMemory, emptyDelegation } from "./delegation-memory.js";
9
+ import { nextSafeShareDocument, planSafeSharePush, safeShareDocumentProblem } from "./safe-share.js";
10
+ import { planStationRegistration } from "./stations.js";
8
11
  import { asTime, asTimeOrNull, clone, isExpired } from "./time.js";
9
12
  const roles = new Set(["owner", "admin", "member"]);
10
13
  function empty() {
@@ -20,16 +23,21 @@ function empty() {
20
23
  signIn: new Map(), appSignIn: new Map(), redirects: new Map(), ssoLogins: new Map(), ssoExchanges: new Map(),
21
24
  hostedHumanClients: new Map(), hostedHumanCodes: new Map(),
22
25
  hostedEmailCodes: new Map(), hostedSsoProfiles: new Map(), hostedSsoEmailProofs: new Map(),
23
- serviceCredentials: new Map(), principals: new Map(), workloadCredentials: new Map(), audiences: new Map(),
26
+ serviceCredentials: new Map(), stationRegistrations: new Map(), stations: new Map(), requestNonces: new Map(), safeShares: new Map(), safeShareDocuments: new Map(),
27
+ principals: new Map(), workloadCredentials: new Map(), audiences: new Map(),
24
28
  roles: new Map(), assignments: new Map(), gatewayRoutes: new Map(),
25
29
  directory: emptyDirectory(),
30
+ delegation: emptyDelegation(),
26
31
  };
27
32
  }
28
33
  function stampUser(user) {
29
34
  return { ...user, lastOrgId: user.lastOrgId ?? null, emailVerifiedAt: asTimeOrNull(user.emailVerifiedAt), disabledAt: asTimeOrNull(user.disabledAt), createdAt: asTime(user.createdAt) };
30
35
  }
31
36
  function stampOrg(org) {
32
- return { ...org, logoUrl: org.logoUrl ?? null, policy: { ...org.policy }, createdAt: asTime(org.createdAt) };
37
+ return {
38
+ ...org, logoUrl: org.logoUrl ?? null, policy: { ...org.policy }, createdAt: asTime(org.createdAt),
39
+ suiteAccountId: org.suiteAccountId ?? null, suiteAccountVersion: org.suiteAccountVersion ?? 0,
40
+ };
33
41
  }
34
42
  function stampApplication(row) {
35
43
  return {
@@ -41,6 +49,7 @@ function stampApplication(row) {
41
49
  waitlistQuestionLayout: row.waitlistQuestionLayout ?? "form",
42
50
  managedSignIn: row.managedSignIn ?? true,
43
51
  emailCodeSignIn: row.emailCodeSignIn ?? false,
52
+ authixMode: row.authixMode === true,
44
53
  authCopy: { ...row.authCopy },
45
54
  directoryModel: row.directoryModel ?? "organizations",
46
55
  directoryLabels: clone(row.directoryLabels ?? {}),
@@ -69,6 +78,27 @@ function stampMembership(membership) {
69
78
  createdAt: asTime(membership.createdAt),
70
79
  };
71
80
  }
81
+ function stampStation(row) {
82
+ if (row.keyType !== "ssh-ed25519" || row.name !== row.name.toLowerCase() || row.name.length < 1 || row.name.length > 64
83
+ || (row.removedAt === null) !== (row.removedReason === null))
84
+ fail("conflict", "Invalid station.");
85
+ return { ...row, registeredAt: asTime(row.registeredAt), lastSeenAt: asTime(row.lastSeenAt), removedAt: asTimeOrNull(row.removedAt) };
86
+ }
87
+ function stampStationRegistration(row) {
88
+ const secret = row.secretHash !== null && row.secretEnc !== null;
89
+ if (!Number.isInteger(row.generation) || row.generation < 0 || row.enabled !== secret || (row.secretHash === null) !== (row.secretEnc === null)) {
90
+ fail("conflict", "Invalid station registration.");
91
+ }
92
+ return { ...row, enabledAt: asTimeOrNull(row.enabledAt), updatedAt: asTime(row.updatedAt) };
93
+ }
94
+ const nonceKey = (row) => `${row.fingerprint}\n${row.nonce}`;
95
+ const documentKey = (appId, name) => `${appId}\n${name}`;
96
+ function summaryOf(row) {
97
+ return {
98
+ appId: row.appId, name: row.name, kind: row.kind, version: row.version, bytes: row.bytes, sha256: row.sha256,
99
+ pushedBy: { ...row.pushedBy }, pushedAt: row.pushedAt, hasPrevious: row.previous !== null,
100
+ };
101
+ }
72
102
  function auditMatches(row, query) {
73
103
  if (row.orgId !== query.orgId)
74
104
  return false;
@@ -148,6 +178,11 @@ export function createMemoryStore() {
148
178
  if (matches(row))
149
179
  map.delete(id);
150
180
  }
181
+ function dropExpiredNonces(stamp) {
182
+ for (const [key, row] of tables.requestNonces)
183
+ if (isExpired(row.expiresAt, stamp))
184
+ tables.requestNonces.delete(key);
185
+ }
151
186
  function removeHostedHumanSessions(sessionIds) {
152
187
  if (!sessionIds.size)
153
188
  return;
@@ -261,6 +296,10 @@ export function createMemoryStore() {
261
296
  .map((app) => ({ ...app, trashedAt: tables.applicationTrash.get(app.id) }))
262
297
  .sort((left, right) => right.trashedAt.localeCompare(left.trashedAt) || right.id.localeCompare(left.id));
263
298
  }
299
+ function dropSafeShare(appId) {
300
+ tables.safeShares.delete(appId);
301
+ removeMatching(tables.safeShareDocuments, (row) => row.appId === appId);
302
+ }
264
303
  function removeApplicationTenantAccess(orgId, appId, at) {
265
304
  const path = `/tenants/${orgId}/apps/${appId}`;
266
305
  removeMatching(tables.applicationStaffAccess, (row) => row.appId === appId);
@@ -293,6 +332,7 @@ export function createMemoryStore() {
293
332
  const routeResource = `/tenants/${app.orgId}/apps/${appId}`;
294
333
  const inEnvironment = (row) => envIds.has(row.environmentId);
295
334
  removeApplicationTenantAccess(app.orgId, appId, app.trashedAt);
335
+ dropSafeShare(appId);
296
336
  resetApplicationSignInAttempts(appId, envIds);
297
337
  removeMatching(tables.hostedHumanClients, (row) => row.appId === appId);
298
338
  removeHostedHumanSessions(new Set(rows(tables.hostedHumanSessions, inEnvironment).map(({ id }) => id)));
@@ -307,6 +347,9 @@ export function createMemoryStore() {
307
347
  removeMatching(tables.notificationSettings, inEnvironment);
308
348
  removeMatching(tables.notificationWebhooks, inEnvironment);
309
349
  removeMatching(tables.notificationWebhookJobs, inEnvironment);
350
+ removeMatching(tables.delegation.customerAccess, inEnvironment);
351
+ removeMatching(tables.delegation.delegations, (row) => row.appId === appId);
352
+ removeMatching(tables.delegation.delegateSends, inEnvironment);
310
353
  const directory = tables.directory;
311
354
  removeMatching(directory.identities, inEnvironment);
312
355
  removeMatching(directory.directoryMemberships, inEnvironment);
@@ -518,9 +561,18 @@ export function createMemoryStore() {
518
561
  async findUserByEmail(email) {
519
562
  return rows(tables.users, (row) => row.email.toLowerCase() === email.toLowerCase())[0] ?? null;
520
563
  },
564
+ async listUsers() {
565
+ return [...tables.users.values()].sort((left, right) => left.email.localeCompare(right.email) || left.id.localeCompare(right.id)).map(clone);
566
+ },
521
567
  async updateUser(next) { tx(() => replace(tables.users, stampUser(next))); },
522
568
  async getOrg(id) { return one(tables.orgs, id); },
569
+ async listOrgs() {
570
+ return [...tables.orgs.values()].sort((left, right) => left.name.localeCompare(right.name) || left.id.localeCompare(right.id)).map(clone);
571
+ },
523
572
  async findOrgBySlug(slug) { return rows(tables.orgs, (row) => row.slug === slug)[0] ?? null; },
573
+ async findOrgBySuiteAccountId(suiteAccountId) {
574
+ return rows(tables.orgs, (row) => row.suiteAccountId === suiteAccountId)[0] ?? null;
575
+ },
524
576
  async updateOrg(next) {
525
577
  tx(() => {
526
578
  org(next.id);
@@ -577,6 +629,21 @@ export function createMemoryStore() {
577
629
  writeEmailChallenge(row);
578
630
  });
579
631
  },
632
+ async replaceAccountResetChallenge(row) {
633
+ tx(() => {
634
+ if (row.purpose !== "reset")
635
+ fail("conflict", "Reset challenge is required.");
636
+ const account = tables.users.get(row.userId);
637
+ if (!account || account.disabledAt)
638
+ fail("not_found", "User not found.");
639
+ const stamp = asTime(row.createdAt);
640
+ for (const challenge of tables.challenges.values()) {
641
+ if (challenge.userId === row.userId && challenge.purpose === "reset" && !challenge.usedAt)
642
+ challenge.usedAt = stamp;
643
+ }
644
+ writeEmailChallenge(row);
645
+ });
646
+ },
580
647
  async reserveAccountChallenge(row, cooldownSince, delivery) {
581
648
  return tx(() => {
582
649
  const account = tables.users.get(row.userId);
@@ -590,6 +657,13 @@ export function createMemoryStore() {
590
657
  return true;
591
658
  });
592
659
  },
660
+ async releaseAccountChallenge(id) {
661
+ tx(() => {
662
+ const row = tables.challenges.get(id);
663
+ if (row && !row.usedAt)
664
+ tables.challenges.delete(id);
665
+ });
666
+ },
593
667
  async verifyEmail(tokenHash, at) {
594
668
  return tx(() => {
595
669
  const stamp = asTime(at);
@@ -691,7 +765,8 @@ export function createMemoryStore() {
691
765
  fail("duplicate", "Duplicate key.");
692
766
  row.tokenHash = input.tokenHash;
693
767
  row.expiresAt = asTime(input.expiresAt);
694
- row.lastMailRequestedAt = asTime(input.at);
768
+ if (input.delivery || input.mailRequested)
769
+ row.lastMailRequestedAt = asTime(input.at);
695
770
  insertMemoryNotificationDelivery(tables.notificationDeliveries, input.delivery);
696
771
  return clone(row);
697
772
  });
@@ -705,6 +780,9 @@ export function createMemoryStore() {
705
780
  return true;
706
781
  });
707
782
  },
783
+ async findInviteByToken(tokenHash) {
784
+ return rows(tables.invites, (row) => row.tokenHash === tokenHash)[0] ?? null;
785
+ },
708
786
  async acceptInvite(input) {
709
787
  return tx(() => {
710
788
  const at = asTime(input.at);
@@ -1103,6 +1181,21 @@ export function createMemoryStore() {
1103
1181
  fail("conflict", "An application gateway route uses a shared tenant resource or audience. Update its scope before moving the application.");
1104
1182
  }
1105
1183
  removeApplicationTenantAccess(sourceOrgId, appId, stamp);
1184
+ // The safe-share belongs to the Team's stations and agents, so it does not move: it is removed with its documents.
1185
+ dropSafeShare(appId);
1186
+ // Customer access does not move with the application: the new Team opts in again, and no session of the old one goes on. The
1187
+ // portal address and the allowed origins name hosts of the old Team, and a link is built on the first of them, so neither stays.
1188
+ for (const policy of tables.delegation.customerAccess.values()) {
1189
+ if (!envIds.has(policy.environmentId) || !(policy.enabled || policy.portalUrl !== null || policy.allowedOrigins.length > 0))
1190
+ continue;
1191
+ policy.enabled = false;
1192
+ policy.portalUrl = null;
1193
+ policy.allowedOrigins = [];
1194
+ policy.updatedAt = stamp;
1195
+ }
1196
+ for (const delegation of tables.delegation.delegations.values())
1197
+ if (delegation.appId === appId)
1198
+ delegation.endedAt ??= stamp;
1106
1199
  resetApplicationSignInAttempts(appId, envIds);
1107
1200
  for (const client of tables.hostedHumanClients.values()) {
1108
1201
  if (client.appId === appId && !client.revokedAt)
@@ -1237,6 +1330,7 @@ export function createMemoryStore() {
1237
1330
  replace(tables.applications, stampApplication({
1238
1331
  ...row, updatedAt: updatedAt < current.updatedAt ? current.updatedAt : updatedAt,
1239
1332
  managedSignIn: row.managedSignIn ?? current.managedSignIn, emailCodeSignIn: row.emailCodeSignIn ?? current.emailCodeSignIn,
1333
+ authixMode: row.authixMode ?? current.authixMode,
1240
1334
  authCopy: row.authCopy ?? current.authCopy,
1241
1335
  directoryModel: row.directoryModel ?? current.directoryModel, directoryLabels: row.directoryLabels ?? current.directoryLabels,
1242
1336
  waitlistQuestions: row.waitlistQuestions ?? current.waitlistQuestions,
@@ -1811,6 +1905,189 @@ export function createMemoryStore() {
1811
1905
  return clone(row);
1812
1906
  });
1813
1907
  },
1908
+ async getStationRegistration(orgId) {
1909
+ return one(tables.stationRegistrations, orgId);
1910
+ },
1911
+ async saveStationRegistration(change) {
1912
+ return tx(() => {
1913
+ const next = stampStationRegistration(change.registration);
1914
+ org(next.orgId);
1915
+ const current = tables.stationRegistrations.get(next.orgId);
1916
+ if ((current?.enabled ?? false) !== change.expected.enabled || (current?.generation ?? 0) !== change.expected.generation)
1917
+ return { saved: false, removed: 0 };
1918
+ tables.stationRegistrations.set(next.orgId, clone(next));
1919
+ let removed = 0;
1920
+ if (change.removeOlder) {
1921
+ const at = asTime(change.removeOlder.at);
1922
+ for (const station of tables.stations.values()) {
1923
+ if (station.orgId !== next.orgId || station.removedAt !== null || station.generation >= next.generation)
1924
+ continue;
1925
+ station.removedAt = at;
1926
+ station.removedBy = change.removeOlder.removedBy;
1927
+ station.removedReason = "secret-regenerated";
1928
+ removed += 1;
1929
+ }
1930
+ }
1931
+ return { saved: true, removed };
1932
+ });
1933
+ },
1934
+ async listStations(orgId) {
1935
+ return rows(tables.stations, (row) => row.orgId === orgId && row.removedAt === null)
1936
+ .sort((left, right) => right.registeredAt.localeCompare(left.registeredAt) || right.id.localeCompare(left.id));
1937
+ },
1938
+ async getStation(orgId, id) {
1939
+ const row = tables.stations.get(id);
1940
+ return row?.orgId === orgId ? clone(row) : null;
1941
+ },
1942
+ async findStationByFingerprint(orgId, fingerprint) {
1943
+ return rows(tables.stations, (row) => row.orgId === orgId && row.fingerprint === fingerprint)[0] ?? null;
1944
+ },
1945
+ async registerStation(input) {
1946
+ return tx(() => {
1947
+ const wanted = { ...stampStation(input.station), removedAt: null, removedBy: null, removedReason: null };
1948
+ org(wanted.orgId);
1949
+ // The settings are read again here, inside the write: a secret that was replaced or switched off after the caller
1950
+ // checked it must not register anyone. Nothing has been written yet, so a refusal leaves nothing behind.
1951
+ const settings = tables.stationRegistrations.get(wanted.orgId);
1952
+ if (!settings?.enabled || settings.generation !== input.expected.generation) {
1953
+ return { status: "registration_changed", enabled: settings?.enabled === true };
1954
+ }
1955
+ const stamp = asTime(input.at);
1956
+ dropExpiredNonces(stamp);
1957
+ const nonce = { ...input.nonce, expiresAt: asTime(input.nonce.expiresAt) };
1958
+ if (tables.requestNonces.has(nonceKey(nonce)))
1959
+ return { status: "replayed" };
1960
+ const existing = [...tables.stations.values()].find((row) => row.orgId === wanted.orgId && row.fingerprint === wanted.fingerprint) ?? null;
1961
+ const active = [...tables.stations.values()].filter((row) => row.orgId === wanted.orgId && row.removedAt === null);
1962
+ const plan = planStationRegistration({
1963
+ existing: existing && clone(existing),
1964
+ nameTaken: active.some((row) => row.name === wanted.name && row.id !== existing?.id),
1965
+ activeCount: active.length,
1966
+ maxActive: input.maxActive,
1967
+ });
1968
+ if (plan.action === "key_removed" || plan.action === "name_taken" || plan.action === "limit")
1969
+ return { status: plan.action };
1970
+ tables.requestNonces.set(nonceKey(nonce), clone(nonce));
1971
+ if (plan.action === "create") {
1972
+ put(tables.stations, wanted);
1973
+ return { status: "created", station: clone(wanted) };
1974
+ }
1975
+ const row = existing;
1976
+ row.name = wanted.name;
1977
+ row.generation = wanted.generation;
1978
+ row.lastSeenAt = stamp;
1979
+ if (plan.action === "reactivate") {
1980
+ row.registeredAt = wanted.registeredAt;
1981
+ row.removedAt = null;
1982
+ row.removedBy = null;
1983
+ row.removedReason = null;
1984
+ }
1985
+ return { status: plan.action === "update" ? "updated" : "created", station: clone(row) };
1986
+ });
1987
+ },
1988
+ async removeStation(input) {
1989
+ return tx(() => {
1990
+ const row = tables.stations.get(input.id);
1991
+ if (!row || row.orgId !== input.orgId || row.removedAt !== null)
1992
+ return null;
1993
+ row.removedAt = asTime(input.at);
1994
+ row.removedBy = input.removedBy;
1995
+ row.removedReason = "removed";
1996
+ return clone(row);
1997
+ });
1998
+ },
1999
+ async touchStation(orgId, id, at, minIntervalMs) {
2000
+ tx(() => {
2001
+ const row = tables.stations.get(id);
2002
+ if (!row || row.orgId !== orgId || row.removedAt !== null)
2003
+ return;
2004
+ const stamp = asTime(at);
2005
+ if (Date.parse(stamp) - Date.parse(row.lastSeenAt) >= minIntervalMs)
2006
+ row.lastSeenAt = stamp;
2007
+ });
2008
+ },
2009
+ async takeRequestNonce(nonce, at) {
2010
+ return tx(() => {
2011
+ dropExpiredNonces(asTime(at));
2012
+ const key = nonceKey(nonce);
2013
+ if (tables.requestNonces.has(key))
2014
+ return false;
2015
+ tables.requestNonces.set(key, { ...nonce, expiresAt: asTime(nonce.expiresAt) });
2016
+ return true;
2017
+ });
2018
+ },
2019
+ async listStationsByIds(orgId, ids) {
2020
+ const wanted = new Set(ids);
2021
+ return rows(tables.stations, (row) => row.orgId === orgId && wanted.has(row.id));
2022
+ },
2023
+ async getSafeShare(appId) {
2024
+ return one(tables.safeShares, appId);
2025
+ },
2026
+ async defineSafeShare(input) {
2027
+ return tx(() => {
2028
+ const app = activeApplication(input.appId);
2029
+ if (!app || app.orgId !== input.orgId)
2030
+ return { status: "not_found" };
2031
+ const current = tables.safeShares.get(input.appId);
2032
+ if (current?.active)
2033
+ return { status: "already", share: clone(current) };
2034
+ const share = { appId: input.appId, orgId: input.orgId, definedAt: asTime(input.at), definedBy: input.definedBy, active: true };
2035
+ tables.safeShares.set(input.appId, share);
2036
+ const restored = [...tables.safeShareDocuments.values()].filter((row) => row.appId === input.appId).length;
2037
+ return { status: "defined", share: clone(share), restored };
2038
+ });
2039
+ },
2040
+ async removeSafeShare(input) {
2041
+ return tx(() => {
2042
+ const app = activeApplication(input.appId);
2043
+ const current = tables.safeShares.get(input.appId);
2044
+ if (!app || app.orgId !== input.orgId || !current?.active)
2045
+ return null;
2046
+ current.active = false;
2047
+ return clone(current);
2048
+ });
2049
+ },
2050
+ async listSafeShareDocuments(appId) {
2051
+ return [...tables.safeShareDocuments.values()].filter((row) => row.appId === appId)
2052
+ .map(summaryOf).sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));
2053
+ },
2054
+ async getSafeShareDocuments(appId, names) {
2055
+ const found = [];
2056
+ for (const name of new Set(names)) {
2057
+ const row = tables.safeShareDocuments.get(documentKey(appId, name));
2058
+ if (row)
2059
+ found.push(clone(row));
2060
+ }
2061
+ return found.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));
2062
+ },
2063
+ async pushSafeShareDocument(input) {
2064
+ return tx(() => {
2065
+ const problem = safeShareDocumentProblem(input);
2066
+ if (problem)
2067
+ fail("conflict", problem);
2068
+ const stamp = asTime(input.pushedAt);
2069
+ dropExpiredNonces(stamp);
2070
+ const app = activeApplication(input.appId);
2071
+ const share = tables.safeShares.get(input.appId);
2072
+ const key = documentKey(input.appId, input.name);
2073
+ const existing = tables.safeShareDocuments.get(key) ?? null;
2074
+ const nonce = input.nonce ? { ...input.nonce, expiresAt: asTime(input.nonce.expiresAt) } : null;
2075
+ const plan = planSafeSharePush({
2076
+ active: app?.orgId === input.orgId && share?.active === true,
2077
+ replayed: nonce !== null && tables.requestNonces.has(nonceKey(nonce)),
2078
+ exists: existing !== null,
2079
+ documentCount: [...tables.safeShareDocuments.values()].filter((row) => row.appId === input.appId).length,
2080
+ maxDocuments: input.maxDocuments,
2081
+ });
2082
+ if (plan.action !== "write")
2083
+ return { status: plan.action };
2084
+ if (nonce)
2085
+ tables.requestNonces.set(nonceKey(nonce), clone(nonce));
2086
+ const document = nextSafeShareDocument(existing && clone(existing), { ...input, pushedAt: stamp });
2087
+ tables.safeShareDocuments.set(key, document);
2088
+ return { status: "pushed", document: clone(document) };
2089
+ });
2090
+ },
1814
2091
  async insertPrincipal(row) {
1815
2092
  tx(() => {
1816
2093
  org(row.orgId);
@@ -1948,6 +2225,7 @@ export function createMemoryStore() {
1948
2225
  fail("conflict", "Notification scope changed.");
1949
2226
  insertMemoryNotificationDelivery(tables.notificationDeliveries, job);
1950
2227
  }),
2228
+ ...bindDelegationMemory(() => tables.delegation, () => tables.directory, (environmentId) => tables.environments.get(environmentId), tx, (row, challenge) => store.saveAppWaitlist(row, challenge)),
1951
2229
  async ping() { },
1952
2230
  async purgeExpired(at) {
1953
2231
  tx(() => {
@@ -1983,6 +2261,7 @@ export function createMemoryStore() {
1983
2261
  for (const row of [...tables.ssoExchanges.values()])
1984
2262
  if (isExpired(row.expiresAt, stamp))
1985
2263
  tables.ssoExchanges.delete(row.id);
2264
+ dropExpiredNonces(stamp);
1986
2265
  });
1987
2266
  },
1988
2267
  };