@x12i/keyrox-store 0.2.5 → 0.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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,9 +23,11 @@ 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) {
@@ -73,6 +78,27 @@ function stampMembership(membership) {
73
78
  createdAt: asTime(membership.createdAt),
74
79
  };
75
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
+ }
76
102
  function auditMatches(row, query) {
77
103
  if (row.orgId !== query.orgId)
78
104
  return false;
@@ -152,6 +178,11 @@ export function createMemoryStore() {
152
178
  if (matches(row))
153
179
  map.delete(id);
154
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
+ }
155
186
  function removeHostedHumanSessions(sessionIds) {
156
187
  if (!sessionIds.size)
157
188
  return;
@@ -265,6 +296,10 @@ export function createMemoryStore() {
265
296
  .map((app) => ({ ...app, trashedAt: tables.applicationTrash.get(app.id) }))
266
297
  .sort((left, right) => right.trashedAt.localeCompare(left.trashedAt) || right.id.localeCompare(left.id));
267
298
  }
299
+ function dropSafeShare(appId) {
300
+ tables.safeShares.delete(appId);
301
+ removeMatching(tables.safeShareDocuments, (row) => row.appId === appId);
302
+ }
268
303
  function removeApplicationTenantAccess(orgId, appId, at) {
269
304
  const path = `/tenants/${orgId}/apps/${appId}`;
270
305
  removeMatching(tables.applicationStaffAccess, (row) => row.appId === appId);
@@ -297,6 +332,7 @@ export function createMemoryStore() {
297
332
  const routeResource = `/tenants/${app.orgId}/apps/${appId}`;
298
333
  const inEnvironment = (row) => envIds.has(row.environmentId);
299
334
  removeApplicationTenantAccess(app.orgId, appId, app.trashedAt);
335
+ dropSafeShare(appId);
300
336
  resetApplicationSignInAttempts(appId, envIds);
301
337
  removeMatching(tables.hostedHumanClients, (row) => row.appId === appId);
302
338
  removeHostedHumanSessions(new Set(rows(tables.hostedHumanSessions, inEnvironment).map(({ id }) => id)));
@@ -311,6 +347,9 @@ export function createMemoryStore() {
311
347
  removeMatching(tables.notificationSettings, inEnvironment);
312
348
  removeMatching(tables.notificationWebhooks, inEnvironment);
313
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);
314
353
  const directory = tables.directory;
315
354
  removeMatching(directory.identities, inEnvironment);
316
355
  removeMatching(directory.directoryMemberships, inEnvironment);
@@ -522,8 +561,14 @@ export function createMemoryStore() {
522
561
  async findUserByEmail(email) {
523
562
  return rows(tables.users, (row) => row.email.toLowerCase() === email.toLowerCase())[0] ?? null;
524
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
+ },
525
567
  async updateUser(next) { tx(() => replace(tables.users, stampUser(next))); },
526
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
+ },
527
572
  async findOrgBySlug(slug) { return rows(tables.orgs, (row) => row.slug === slug)[0] ?? null; },
528
573
  async findOrgBySuiteAccountId(suiteAccountId) {
529
574
  return rows(tables.orgs, (row) => row.suiteAccountId === suiteAccountId)[0] ?? null;
@@ -584,6 +629,21 @@ export function createMemoryStore() {
584
629
  writeEmailChallenge(row);
585
630
  });
586
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
+ },
587
647
  async reserveAccountChallenge(row, cooldownSince, delivery) {
588
648
  return tx(() => {
589
649
  const account = tables.users.get(row.userId);
@@ -597,6 +657,13 @@ export function createMemoryStore() {
597
657
  return true;
598
658
  });
599
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
+ },
600
667
  async verifyEmail(tokenHash, at) {
601
668
  return tx(() => {
602
669
  const stamp = asTime(at);
@@ -698,7 +765,8 @@ export function createMemoryStore() {
698
765
  fail("duplicate", "Duplicate key.");
699
766
  row.tokenHash = input.tokenHash;
700
767
  row.expiresAt = asTime(input.expiresAt);
701
- row.lastMailRequestedAt = asTime(input.at);
768
+ if (input.delivery || input.mailRequested)
769
+ row.lastMailRequestedAt = asTime(input.at);
702
770
  insertMemoryNotificationDelivery(tables.notificationDeliveries, input.delivery);
703
771
  return clone(row);
704
772
  });
@@ -712,6 +780,9 @@ export function createMemoryStore() {
712
780
  return true;
713
781
  });
714
782
  },
783
+ async findInviteByToken(tokenHash) {
784
+ return rows(tables.invites, (row) => row.tokenHash === tokenHash)[0] ?? null;
785
+ },
715
786
  async acceptInvite(input) {
716
787
  return tx(() => {
717
788
  const at = asTime(input.at);
@@ -1110,6 +1181,21 @@ export function createMemoryStore() {
1110
1181
  fail("conflict", "An application gateway route uses a shared tenant resource or audience. Update its scope before moving the application.");
1111
1182
  }
1112
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;
1113
1199
  resetApplicationSignInAttempts(appId, envIds);
1114
1200
  for (const client of tables.hostedHumanClients.values()) {
1115
1201
  if (client.appId === appId && !client.revokedAt)
@@ -1819,6 +1905,189 @@ export function createMemoryStore() {
1819
1905
  return clone(row);
1820
1906
  });
1821
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
+ },
1822
2091
  async insertPrincipal(row) {
1823
2092
  tx(() => {
1824
2093
  org(row.orgId);
@@ -1956,6 +2225,7 @@ export function createMemoryStore() {
1956
2225
  fail("conflict", "Notification scope changed.");
1957
2226
  insertMemoryNotificationDelivery(tables.notificationDeliveries, job);
1958
2227
  }),
2228
+ ...bindDelegationMemory(() => tables.delegation, () => tables.directory, (environmentId) => tables.environments.get(environmentId), tx, (row, challenge) => store.saveAppWaitlist(row, challenge)),
1959
2229
  async ping() { },
1960
2230
  async purgeExpired(at) {
1961
2231
  tx(() => {
@@ -1991,6 +2261,7 @@ export function createMemoryStore() {
1991
2261
  for (const row of [...tables.ssoExchanges.values()])
1992
2262
  if (isExpired(row.expiresAt, stamp))
1993
2263
  tables.ssoExchanges.delete(row.id);
2264
+ dropExpiredNonces(stamp);
1994
2265
  });
1995
2266
  },
1996
2267
  };