@x12i/keyrox-store 0.2.6 → 0.2.8

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
@@ -1,3 +1,4 @@
1
+ import { environmentTypeOf, isProductionStage } from "@x12i/keyrox-types";
1
2
  import { appIdFromTenantResource, applicationLifecycleTime, applicationMoveKeys, verifyApplicationTrashSnapshot } from "./application-lifecycle.js";
2
3
  import { decideLongLived, effectiveActions } from "./access.js";
3
4
  import { fail } from "./errors.js";
@@ -9,7 +10,7 @@ import { bindDelegationMemory, emptyDelegation } from "./delegation-memory.js";
9
10
  import { nextSafeShareDocument, planSafeSharePush, safeShareDocumentProblem } from "./safe-share.js";
10
11
  import { planStationRegistration } from "./stations.js";
11
12
  import { asTime, asTimeOrNull, clone, isExpired } from "./time.js";
12
- const roles = new Set(["owner", "admin", "member"]);
13
+ const roles = new Set(["owner", "admin", "member", "sandbox-developer", "support", "viewer"]);
13
14
  function empty() {
14
15
  return {
15
16
  users: new Map(), orgs: new Map(), memberships: new Map(), challenges: new Map(), invites: new Map(),
@@ -61,9 +62,16 @@ function canSharePlatformSignIn(row) {
61
62
  return row.provider !== "oidc" && (row.provider !== "microsoft" || row.directoryId === "common");
62
63
  }
63
64
  function stampEnvironment(row) {
64
- return {
65
- ...row, previousKeyExpiresAt: asTimeOrNull(row.previousKeyExpiresAt), createdAt: asTime(row.createdAt), updatedAt: asTime(row.updatedAt),
65
+ const trashedAt = asTimeOrNull(row.trashedAt ?? null);
66
+ const next = {
67
+ ...row, type: environmentTypeOf(row),
68
+ previousKeyExpiresAt: asTimeOrNull(row.previousKeyExpiresAt), createdAt: asTime(row.createdAt), updatedAt: asTime(row.updatedAt),
66
69
  };
70
+ if (trashedAt)
71
+ next.trashedAt = trashedAt;
72
+ else
73
+ delete next.trashedAt;
74
+ return next;
67
75
  }
68
76
  function stampAppToken(row) {
69
77
  return { ...row, payload: clone(row.payload), revokedAt: asTimeOrNull(row.revokedAt), expiresAt: asTimeOrNull(row.expiresAt), createdAt: asTime(row.createdAt) };
@@ -71,12 +79,18 @@ function stampAppToken(row) {
71
79
  function stampMembership(membership) {
72
80
  if (!roles.has(membership.role))
73
81
  fail("conflict", "Invalid role.");
74
- return {
82
+ const applicationIds = membership.applicationIds?.map((id) => id.trim()).filter(Boolean);
83
+ const next = {
75
84
  ...membership,
76
85
  productionAccess: membership.role === "owner" || membership.productionAccess === true,
77
86
  actions: [...membership.actions],
78
87
  createdAt: asTime(membership.createdAt),
79
88
  };
89
+ if (applicationIds?.length)
90
+ next.applicationIds = applicationIds;
91
+ else
92
+ delete next.applicationIds;
93
+ return next;
80
94
  }
81
95
  function stampStation(row) {
82
96
  if (row.keyType !== "ssh-ed25519" || row.name !== row.name.toLowerCase() || row.name.length < 1 || row.name.length > 64
@@ -386,7 +400,7 @@ export function createMemoryStore() {
386
400
  if (!app)
387
401
  fail("conflict", "Application is missing.");
388
402
  if (row.orgId !== app.orgId)
389
- fail("conflict", "Environment tenant does not match the application.");
403
+ fail("conflict", "Environment Company does not match the application.");
390
404
  if (row.status !== "active" && row.status !== "disabled")
391
405
  fail("conflict", "Invalid environment status.");
392
406
  if ([...tables.environments.values()].some((item) => item.appId === row.appId && item.name === row.name))
@@ -397,10 +411,10 @@ export function createMemoryStore() {
397
411
  const app = activeApplication(row.appId);
398
412
  const environment = tables.environments.get(row.environmentId);
399
413
  if (app?.orgId !== row.orgId || environment?.appId !== row.appId || environment.orgId !== row.orgId) {
400
- fail("conflict", "Application staff access must match the tenant, application, and environment.");
414
+ fail("conflict", "Application staff access must match the Company, application, and environment.");
401
415
  }
402
416
  if (![...tables.memberships.values()].some((membership) => membership.orgId === row.orgId && membership.userId === row.userId)) {
403
- fail("conflict", "Application staff access requires tenant membership.");
417
+ fail("conflict", "Application staff access requires Company membership.");
404
418
  }
405
419
  if (typeof row.design !== "boolean" || !["none", "read", "manage"].includes(row.runtime)) {
406
420
  fail("conflict", "Invalid application staff access level.");
@@ -544,6 +558,14 @@ export function createMemoryStore() {
544
558
  }
545
559
  });
546
560
  },
561
+ async insertUser(user) {
562
+ tx(() => {
563
+ const next = stampUser(user);
564
+ if ([...tables.users.values()].some((row) => row.email.toLowerCase() === next.email.toLowerCase()))
565
+ fail("duplicate_email", "Email already exists.");
566
+ put(tables.users, next);
567
+ });
568
+ },
547
569
  async createOrg(input) {
548
570
  tx(() => {
549
571
  const nextOrg = stampOrg(input.org);
@@ -604,13 +626,14 @@ export function createMemoryStore() {
604
626
  const existing = [...tables.memberships.values()].find((row) => row.userId === input.userId && row.orgId === input.orgId);
605
627
  if (!existing)
606
628
  fail("not_found", "Member not found.");
607
- user(input.userId);
608
- if (membershipsForUser(input.userId).length < 2)
609
- fail("last_membership", "An account must belong to at least one organization.");
610
- if (existing.role === "owner" && rows(tables.memberships, (row) => row.orgId === input.orgId && row.role === "owner").length < 2) {
629
+ const account = user(input.userId);
630
+ const otherMembers = rows(tables.memberships, (row) => row.orgId === input.orgId && row.userId !== input.userId);
631
+ if (existing.role === "owner" && otherMembers.length > 0 && rows(tables.memberships, (row) => row.orgId === input.orgId && row.role === "owner").length < 2) {
611
632
  fail("last_owner", "An organization must keep an owner.");
612
633
  }
613
634
  tables.memberships.delete(existing.id);
635
+ if (account.lastOrgId === input.orgId)
636
+ account.lastOrgId = membershipsForUser(input.userId)[0]?.orgId ?? null;
614
637
  for (const access of tables.applicationStaffAccess.values()) {
615
638
  if (access.orgId === existing.orgId && access.userId === existing.userId)
616
639
  tables.applicationStaffAccess.delete(access.id);
@@ -1138,7 +1161,7 @@ export function createMemoryStore() {
1138
1161
  fail("conflict", "Creator access must target the new development environment.");
1139
1162
  }
1140
1163
  if (audit && audit.orgId !== application.orgId)
1141
- fail("conflict", "Application registration audit must match the tenant.");
1164
+ fail("conflict", "Application registration audit must match the Company.");
1142
1165
  insertApp(application);
1143
1166
  for (const environment of environments)
1144
1167
  insertAppEnvironment(environment);
@@ -1160,10 +1183,10 @@ export function createMemoryStore() {
1160
1183
  if (app?.orgId !== sourceOrgId)
1161
1184
  fail("not_found", "Application not found.");
1162
1185
  if (sourceOrgId === targetOrgId)
1163
- fail("conflict", "Choose a different tenant.");
1186
+ fail("conflict", "Choose a different Company.");
1164
1187
  org(targetOrgId);
1165
1188
  if (audit.some((event) => event.orgId !== sourceOrgId && event.orgId !== targetOrgId)) {
1166
- fail("conflict", "Application move audit must match the source or destination tenant.");
1189
+ fail("conflict", "Application move audit must match the source or destination Company.");
1167
1190
  }
1168
1191
  const stamp = applicationLifecycleTime(updatedAt, app.updatedAt);
1169
1192
  const environments = rows(tables.environments, (row) => row.appId === appId);
@@ -1172,19 +1195,19 @@ export function createMemoryStore() {
1172
1195
  const audiences = rows(tables.audiences, (row) => row.appId === appId);
1173
1196
  const audienceIds = new Set(audiences.map(({ id }) => id));
1174
1197
  if (rows(tables.audiences, (row) => row.orgId === targetOrgId).some((row) => audiences.some((audience) => audience.identifier === row.identifier))) {
1175
- fail("conflict", "The destination tenant already uses an audience identifier from this application.");
1198
+ fail("conflict", "The destination Company already uses an audience identifier from this application.");
1176
1199
  }
1177
1200
  const sourcePath = `/tenants/${sourceOrgId}/apps/${appId}`;
1178
1201
  const targetPath = `/tenants/${targetOrgId}/apps/${appId}`;
1179
1202
  const routes = rows(tables.gatewayRoutes, (row) => audienceIds.has(row.audienceId) || row.resource.replace(/\/+$/, "") === sourcePath);
1180
1203
  if (routes.some((row) => !audienceIds.has(row.audienceId) || row.resource.replace(/\/+$/, "") !== sourcePath || row.orgId !== sourceOrgId)) {
1181
- fail("conflict", "An application gateway route uses a shared tenant resource or audience. Update its scope before moving the application.");
1204
+ fail("conflict", "An application gateway route uses a shared Company resource or audience. Update its scope before moving the application.");
1182
1205
  }
1183
1206
  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.
1207
+ // The safe-share belongs to the Company's stations and agents, so it does not move: it is removed with its documents.
1185
1208
  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.
1209
+ // Customer access does not move with the application: the new Company opts in again, and no session of the old one goes on. The
1210
+ // portal address and the allowed origins name hosts of the old Company, and a link is built on the first of them, so neither stays.
1188
1211
  for (const policy of tables.delegation.customerAccess.values()) {
1189
1212
  if (!envIds.has(policy.environmentId) || !(policy.enabled || policy.portalUrl !== null || policy.allowedOrigins.length > 0))
1190
1213
  continue;
@@ -1246,8 +1269,8 @@ export function createMemoryStore() {
1246
1269
  if (app?.orgId !== orgId)
1247
1270
  fail("not_found", "Application not found.");
1248
1271
  if (audit && audit.orgId !== orgId)
1249
- fail("conflict", "Application trash audit must match the tenant.");
1250
- if (!allowProduction && [...tables.environments.values()].some((row) => row.appId === appId && row.name === "production")) {
1272
+ fail("conflict", "Application trash audit must match the Company.");
1273
+ if (!allowProduction && [...tables.environments.values()].some((row) => row.appId === appId && isProductionStage(row))) {
1251
1274
  fail("conflict", "Production access is required to move this application to Trash.");
1252
1275
  }
1253
1276
  const stamp = applicationLifecycleTime(trashedAt, app.updatedAt);
@@ -1267,7 +1290,7 @@ export function createMemoryStore() {
1267
1290
  if (expectedTrashedAt && expectedTrashedAt !== trashedAt)
1268
1291
  fail("conflict", "Trash changed. Review the application before restoring it.");
1269
1292
  if (audit && audit.orgId !== orgId)
1270
- fail("conflict", "Application restore audit must match the tenant.");
1293
+ fail("conflict", "Application restore audit must match the Company.");
1271
1294
  const restored = { ...app, updatedAt: applicationLifecycleTime(updatedAt, trashedAt) };
1272
1295
  replace(tables.applications, restored);
1273
1296
  tables.applicationTrash.delete(appId);
@@ -1280,10 +1303,10 @@ export function createMemoryStore() {
1280
1303
  return tx(() => {
1281
1304
  org(orgId);
1282
1305
  if (audit && audit.orgId !== orgId)
1283
- fail("conflict", "Application trash audit must match the tenant.");
1306
+ fail("conflict", "Application trash audit must match the Company.");
1284
1307
  const entries = listApplicationTrash(orgId);
1285
1308
  verifyApplicationTrashSnapshot(entries, confirmed);
1286
- if (!allowProduction && [...tables.environments.values()].some((row) => row.name === "production" && entries.some(({ id }) => id === row.appId))) {
1309
+ if (!allowProduction && [...tables.environments.values()].some((row) => isProductionStage(row) && entries.some(({ id }) => id === row.appId))) {
1287
1310
  fail("conflict", "Production access is required to empty this Trash.");
1288
1311
  }
1289
1312
  for (const entry of entries)
@@ -1350,7 +1373,7 @@ export function createMemoryStore() {
1350
1373
  async listEnvironments(appId, options) {
1351
1374
  if (!options?.includeTrashed && !activeApplication(appId))
1352
1375
  return [];
1353
- return rows(tables.environments, (row) => row.appId === appId)
1376
+ return rows(tables.environments, (row) => row.appId === appId && !row.trashedAt)
1354
1377
  .sort((left, right) => left.createdAt.localeCompare(right.createdAt) || left.name.localeCompare(right.name));
1355
1378
  },
1356
1379
  async saveEnvironmentJwtProfile(environmentId, appId, orgId, profile, updatedAt) {
@@ -1381,7 +1404,39 @@ export function createMemoryStore() {
1381
1404
  const next = stampEnvironment(row);
1382
1405
  if (row.jwtProfile === undefined)
1383
1406
  next.jwtProfile = current.jwtProfile;
1407
+ if (current.trashedAt)
1408
+ next.trashedAt = current.trashedAt;
1409
+ replace(tables.environments, next);
1410
+ });
1411
+ },
1412
+ async trashEnvironment({ environmentId, appId, orgId, trashedAt, audit }) {
1413
+ return tx(() => {
1414
+ const current = tables.environments.get(environmentId);
1415
+ if (!current || current.appId !== appId || current.orgId !== orgId || current.trashedAt || !activeApplication(appId))
1416
+ fail("not_found", "Environment not found.");
1417
+ const live = [...tables.environments.values()].filter((row) => row.appId === appId && !row.trashedAt);
1418
+ if (live.length < 2)
1419
+ fail("conflict", "An application must keep at least one environment.");
1420
+ const stamp = asTime(trashedAt);
1421
+ const next = stampEnvironment({ ...current, trashedAt: stamp, updatedAt: stamp });
1384
1422
  replace(tables.environments, next);
1423
+ if (audit)
1424
+ writeAudit(audit);
1425
+ return clone(next);
1426
+ });
1427
+ },
1428
+ async restoreEnvironment({ environmentId, appId, orgId, updatedAt, audit }) {
1429
+ return tx(() => {
1430
+ const current = tables.environments.get(environmentId);
1431
+ if (!current || current.appId !== appId || current.orgId !== orgId || !current.trashedAt || !activeApplication(appId))
1432
+ fail("not_found", "Environment not found in Trash.");
1433
+ const stamp = asTime(updatedAt);
1434
+ const next = stampEnvironment({ ...current, updatedAt: stamp });
1435
+ delete next.trashedAt;
1436
+ replace(tables.environments, next);
1437
+ if (audit)
1438
+ writeAudit(audit);
1439
+ return clone(next);
1385
1440
  });
1386
1441
  },
1387
1442
  async getNotificationSettings(environmentId) {
@@ -1403,7 +1458,7 @@ export function createMemoryStore() {
1403
1458
  tables.notificationSettings.set(row.environmentId, clone({ ...row, templates: { ...row.templates }, updatedAt: asTime(row.updatedAt) }));
1404
1459
  if (audit) {
1405
1460
  if (audit.orgId !== row.orgId)
1406
- fail("conflict", "Notification audit must match the tenant.");
1461
+ fail("conflict", "Notification audit must match the Company.");
1407
1462
  writeAudit(audit);
1408
1463
  }
1409
1464
  return true;
@@ -1465,7 +1520,7 @@ export function createMemoryStore() {
1465
1520
  async saveApplicationStaffAccess(row, audit) {
1466
1521
  return tx(() => {
1467
1522
  if (audit && audit.orgId !== row.orgId)
1468
- fail("conflict", "Application staff audit must match the tenant.");
1523
+ fail("conflict", "Application staff audit must match the Company.");
1469
1524
  const saved = saveStaffAccess(row);
1470
1525
  if (audit)
1471
1526
  writeAudit(audit);
@@ -1475,7 +1530,7 @@ export function createMemoryStore() {
1475
1530
  async deleteApplicationStaffAccess(orgId, appId, environmentId, userId, audit) {
1476
1531
  return tx(() => {
1477
1532
  if (audit && audit.orgId !== orgId)
1478
- fail("conflict", "Application staff audit must match the tenant.");
1533
+ fail("conflict", "Application staff audit must match the Company.");
1479
1534
  const current = [...tables.applicationStaffAccess.values()].find((row) => row.orgId === orgId && row.appId === appId && row.environmentId === environmentId && row.userId === userId);
1480
1535
  if (!current)
1481
1536
  return false;
@@ -1494,7 +1549,7 @@ export function createMemoryStore() {
1494
1549
  if (!environment || environment.appId !== row.appId)
1495
1550
  fail("conflict", "Environment is missing.");
1496
1551
  if (row.orgId !== app.orgId)
1497
- fail("conflict", "Token tenant does not match the application.");
1552
+ fail("conflict", "Token Company does not match the application.");
1498
1553
  if (row.payload.keyVersion !== environment.keyVersion)
1499
1554
  fail("conflict", "The environment key changed during token issuance.");
1500
1555
  put(tables.appTokens, stampAppToken(row));
@@ -2117,11 +2172,11 @@ export function createMemoryStore() {
2117
2172
  tx(() => {
2118
2173
  org(row.orgId);
2119
2174
  if (row.appId && activeApplication(row.appId)?.orgId !== row.orgId)
2120
- fail("conflict", "Choose an application from this tenant.");
2175
+ fail("conflict", "Choose an application from this Company.");
2121
2176
  if (row.environmentId) {
2122
2177
  const environment = tables.environments.get(row.environmentId);
2123
2178
  if (!environment || environment.orgId !== row.orgId || (row.appId && environment.appId !== row.appId))
2124
- fail("conflict", "Choose an environment from this tenant.");
2179
+ fail("conflict", "Choose an environment from this Company.");
2125
2180
  }
2126
2181
  if ([...tables.audiences.values()].some((item) => item.orgId === row.orgId && item.identifier === row.identifier))
2127
2182
  fail("duplicate", "Duplicate key.");
@@ -2153,7 +2208,7 @@ export function createMemoryStore() {
2153
2208
  if (environmentId) {
2154
2209
  const environment = tables.environments.get(environmentId);
2155
2210
  if (!environment || environment.orgId !== orgId || (current.appId && environment.appId !== current.appId))
2156
- fail("conflict", "Choose an environment from this tenant.");
2211
+ fail("conflict", "Choose an environment from this Company.");
2157
2212
  }
2158
2213
  const next = { ...current, environmentId };
2159
2214
  replace(tables.audiences, next);
@@ -2170,7 +2225,7 @@ export function createMemoryStore() {
2170
2225
  const principal = tables.principals.get(row.principalId);
2171
2226
  const role = tables.roles.get(row.roleId);
2172
2227
  if (principal?.orgId !== row.orgId || role?.orgId !== row.orgId)
2173
- fail("conflict", "Choose an app identity and role from this tenant.");
2228
+ fail("conflict", "Choose an app identity and role from this Company.");
2174
2229
  if (!principal.enabled)
2175
2230
  fail("conflict", "This app identity is disabled.");
2176
2231
  const scope = row.scope.replace(/\/+$/, "");
@@ -2198,10 +2253,10 @@ export function createMemoryStore() {
2198
2253
  org(row.orgId);
2199
2254
  const audience = tables.audiences.get(row.audienceId);
2200
2255
  if (!audience || audience.orgId !== row.orgId)
2201
- fail("conflict", "Choose an audience from this tenant.");
2256
+ fail("conflict", "Choose an audience from this Company.");
2202
2257
  const appId = appIdFromTenantResource(row.orgId, row.resource);
2203
2258
  if ((audience.appId && activeApplication(audience.appId)?.orgId !== row.orgId) || (appId && activeApplication(appId)?.orgId !== row.orgId)) {
2204
- fail("conflict", "Choose an application from this tenant.");
2259
+ fail("conflict", "Choose an application from this Company.");
2205
2260
  }
2206
2261
  put(tables.gatewayRoutes, { ...row, createdAt: asTime(row.createdAt) });
2207
2262
  });