mindoodb 0.0.97 → 0.0.98

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.
Files changed (125) hide show
  1. package/README.md +1 -0
  2. package/dist/appendonlystores/network/ClientNetworkContentAddressedStore.d.ts +7 -0
  3. package/dist/appendonlystores/network/ClientNetworkContentAddressedStore.d.ts.map +1 -1
  4. package/dist/appendonlystores/network/ClientNetworkContentAddressedStore.js +17 -9
  5. package/dist/appendonlystores/network/ClientNetworkContentAddressedStore.js.map +1 -1
  6. package/dist/appendonlystores/network/ServerNetworkContentAddressedStore.d.ts +12 -0
  7. package/dist/appendonlystores/network/ServerNetworkContentAddressedStore.d.ts.map +1 -1
  8. package/dist/appendonlystores/network/ServerNetworkContentAddressedStore.js +19 -0
  9. package/dist/appendonlystores/network/ServerNetworkContentAddressedStore.js.map +1 -1
  10. package/dist/browser/index.mjs +70 -0
  11. package/dist/core/BaseMindooDB.d.ts +2 -0
  12. package/dist/core/BaseMindooDB.d.ts.map +1 -1
  13. package/dist/core/BaseMindooDB.js +73 -53
  14. package/dist/core/BaseMindooDB.js.map +1 -1
  15. package/dist/core/BaseMindooTenant.d.ts +33 -1
  16. package/dist/core/BaseMindooTenant.d.ts.map +1 -1
  17. package/dist/core/BaseMindooTenant.js +141 -41
  18. package/dist/core/BaseMindooTenant.js.map +1 -1
  19. package/dist/core/BaseMindooTenantDirectory.d.ts +11 -0
  20. package/dist/core/BaseMindooTenantDirectory.d.ts.map +1 -1
  21. package/dist/core/BaseMindooTenantDirectory.js +137 -92
  22. package/dist/core/BaseMindooTenantDirectory.js.map +1 -1
  23. package/dist/core/builtinDbInvariants.d.ts +26 -1
  24. package/dist/core/builtinDbInvariants.d.ts.map +1 -1
  25. package/dist/core/builtinDbInvariants.js +52 -2
  26. package/dist/core/builtinDbInvariants.js.map +1 -1
  27. package/dist/core/index.d.ts +2 -0
  28. package/dist/core/index.d.ts.map +1 -1
  29. package/dist/core/index.js +3 -0
  30. package/dist/core/index.js.map +1 -1
  31. package/dist/core/joinrequests/crypto.d.ts +110 -0
  32. package/dist/core/joinrequests/crypto.d.ts.map +1 -0
  33. package/dist/core/joinrequests/crypto.js +340 -0
  34. package/dist/core/joinrequests/crypto.js.map +1 -0
  35. package/dist/core/joinrequests/index.d.ts +4 -0
  36. package/dist/core/joinrequests/index.d.ts.map +1 -0
  37. package/dist/core/joinrequests/index.js +29 -0
  38. package/dist/core/joinrequests/index.js.map +1 -0
  39. package/dist/core/joinrequests/invitations.d.ts +257 -0
  40. package/dist/core/joinrequests/invitations.d.ts.map +1 -0
  41. package/dist/core/joinrequests/invitations.js +703 -0
  42. package/dist/core/joinrequests/invitations.js.map +1 -0
  43. package/dist/core/joinrequests/types.d.ts +208 -0
  44. package/dist/core/joinrequests/types.d.ts.map +1 -0
  45. package/dist/core/joinrequests/types.js +43 -0
  46. package/dist/core/joinrequests/types.js.map +1 -0
  47. package/dist/core/recovery/PaperRescueDevice.d.ts +92 -0
  48. package/dist/core/recovery/PaperRescueDevice.d.ts.map +1 -0
  49. package/dist/core/recovery/PaperRescueDevice.js +182 -0
  50. package/dist/core/recovery/PaperRescueDevice.js.map +1 -0
  51. package/dist/core/recovery/RecoveryContactsDocument.d.ts +91 -0
  52. package/dist/core/recovery/RecoveryContactsDocument.d.ts.map +1 -0
  53. package/dist/core/recovery/RecoveryContactsDocument.js +92 -0
  54. package/dist/core/recovery/RecoveryContactsDocument.js.map +1 -0
  55. package/dist/core/recovery/RecoveryContactsManager.d.ts +95 -0
  56. package/dist/core/recovery/RecoveryContactsManager.d.ts.map +1 -0
  57. package/dist/core/recovery/RecoveryContactsManager.js +322 -0
  58. package/dist/core/recovery/RecoveryContactsManager.js.map +1 -0
  59. package/dist/core/recovery/index.d.ts +8 -0
  60. package/dist/core/recovery/index.d.ts.map +1 -0
  61. package/dist/core/recovery/index.js +41 -0
  62. package/dist/core/recovery/index.js.map +1 -0
  63. package/dist/core/recovery/recoverWithContacts.d.ts +36 -0
  64. package/dist/core/recovery/recoverWithContacts.d.ts.map +1 -0
  65. package/dist/core/recovery/recoverWithContacts.js +103 -0
  66. package/dist/core/recovery/recoverWithContacts.js.map +1 -0
  67. package/dist/core/recovery/recoveryPackage.d.ts +72 -0
  68. package/dist/core/recovery/recoveryPackage.d.ts.map +1 -0
  69. package/dist/core/recovery/recoveryPackage.js +181 -0
  70. package/dist/core/recovery/recoveryPackage.js.map +1 -0
  71. package/dist/core/recovery/rescueDevice.d.ts +51 -0
  72. package/dist/core/recovery/rescueDevice.d.ts.map +1 -0
  73. package/dist/core/recovery/rescueDevice.js +201 -0
  74. package/dist/core/recovery/rescueDevice.js.map +1 -0
  75. package/dist/core/recovery/shamir.d.ts +30 -0
  76. package/dist/core/recovery/shamir.d.ts.map +1 -0
  77. package/dist/core/recovery/shamir.js +133 -0
  78. package/dist/core/recovery/shamir.js.map +1 -0
  79. package/dist/core/types.d.ts +64 -1
  80. package/dist/core/types.d.ts.map +1 -1
  81. package/dist/core/types.js.map +1 -1
  82. package/dist/core/userkeys/UserKeyManager.d.ts +29 -0
  83. package/dist/core/userkeys/UserKeyManager.d.ts.map +1 -1
  84. package/dist/core/userkeys/UserKeyManager.js +76 -8
  85. package/dist/core/userkeys/UserKeyManager.js.map +1 -1
  86. package/dist/core/userkeys/generationSignature.d.ts +6 -0
  87. package/dist/core/userkeys/generationSignature.d.ts.map +1 -1
  88. package/dist/core/userkeys/generationSignature.js +1 -0
  89. package/dist/core/userkeys/generationSignature.js.map +1 -1
  90. package/dist/core/userkeys/resolveUserKeyDocument.d.ts.map +1 -1
  91. package/dist/core/userkeys/resolveUserKeyDocument.js +6 -6
  92. package/dist/core/userkeys/resolveUserKeyDocument.js.map +1 -1
  93. package/dist/core/userkeys/validateUserKeyDocument.d.ts +11 -1
  94. package/dist/core/userkeys/validateUserKeyDocument.d.ts.map +1 -1
  95. package/dist/core/userkeys/validateUserKeyDocument.js +18 -5
  96. package/dist/core/userkeys/validateUserKeyDocument.js.map +1 -1
  97. package/dist/node/server/MindooDBServer.d.ts +2 -0
  98. package/dist/node/server/MindooDBServer.d.ts.map +1 -1
  99. package/dist/node/server/MindooDBServer.js +46 -0
  100. package/dist/node/server/MindooDBServer.js.map +1 -1
  101. package/dist/node/server/StoreFactory.d.ts.map +1 -1
  102. package/dist/node/server/StoreFactory.js +4 -1
  103. package/dist/node/server/StoreFactory.js.map +1 -1
  104. package/dist/node/server/server.js +2 -0
  105. package/dist/node/server/server.js.map +1 -1
  106. package/dist/server/JoinRequestService.d.ts +108 -0
  107. package/dist/server/JoinRequestService.d.ts.map +1 -0
  108. package/dist/server/JoinRequestService.js +454 -0
  109. package/dist/server/JoinRequestService.js.map +1 -0
  110. package/dist/server/TenantManager.d.ts +50 -0
  111. package/dist/server/TenantManager.d.ts.map +1 -1
  112. package/dist/server/TenantManager.js +271 -33
  113. package/dist/server/TenantManager.js.map +1 -1
  114. package/dist/server/http/MindooDBServerCore.d.ts +18 -0
  115. package/dist/server/http/MindooDBServerCore.d.ts.map +1 -1
  116. package/dist/server/http/MindooDBServerCore.js +229 -137
  117. package/dist/server/http/MindooDBServerCore.js.map +1 -1
  118. package/dist/server/serverConfig.d.ts.map +1 -1
  119. package/dist/server/serverConfig.js +17 -0
  120. package/dist/server/serverConfig.js.map +1 -1
  121. package/dist/server/types.d.ts +15 -0
  122. package/dist/server/types.d.ts.map +1 -1
  123. package/dist/server/types.js +6 -0
  124. package/dist/server/types.js.map +1 -1
  125. package/package.json +1 -1
@@ -23,17 +23,19 @@ exports.lazyContentAddressedStore = lazyContentAddressedStore;
23
23
  const AuthenticationService_1 = require("../core/appendonlystores/network/AuthenticationService");
24
24
  const ServerNetworkContentAddressedStore_1 = require("../appendonlystores/network/ServerNetworkContentAddressedStore");
25
25
  const PurgedDocRegistry_1 = require("./PurgedDocRegistry");
26
+ const types_1 = require("../core/joinrequests/types");
26
27
  const purgeDocumentHistory_1 = require("../core/appendonlystores/purgeDocumentHistory");
27
28
  const Ed25519WitnessProvider_1 = require("../core/accesscontrol/timestamp/Ed25519WitnessProvider");
28
29
  const BaseMindooTenantFactory_1 = require("../core/BaseMindooTenantFactory");
29
30
  const RSAEncryption_1 = require("../core/crypto/RSAEncryption");
30
31
  const privateKeyEncryption_1 = require("../core/crypto/privateKeyEncryption");
31
32
  const KeyBag_1 = require("../core/keys/KeyBag");
32
- const types_1 = require("../core/types");
33
+ const types_2 = require("../core/types");
33
34
  const builtinDbInvariants_1 = require("../core/builtinDbInvariants");
34
35
  const DirectoryStateNode_1 = require("../core/accesscontrol/DirectoryStateNode");
35
36
  const tier1Evaluator_1 = require("../core/accesscontrol/tier1Evaluator");
36
37
  const base64_1 = require("../core/utils/base64");
38
+ const LogLevel_1 = require("../core/logging/LogLevel");
37
39
  // ---------------------------------------------------------------------------
38
40
  // StoreFactoryAdapter
39
41
  // ---------------------------------------------------------------------------
@@ -43,8 +45,8 @@ class StoreFactoryAdapter {
43
45
  }
44
46
  createStore(dbId, _options) {
45
47
  return {
46
- docStore: this.storeFactory.getStore(dbId, types_1.StoreKind.docs),
47
- attachmentStore: this.storeFactory.getStore(dbId, types_1.StoreKind.attachments),
48
+ docStore: this.storeFactory.getStore(dbId, types_2.StoreKind.docs),
49
+ attachmentStore: this.storeFactory.getStore(dbId, types_2.StoreKind.attachments),
48
50
  };
49
51
  }
50
52
  }
@@ -427,6 +429,21 @@ const SERVER_KEYBAG_KEY = "server.keybag";
427
429
  class TenantManager {
428
430
  constructor(options) {
429
431
  this.loadedTenants = new Map();
432
+ /**
433
+ * Tenant loads in progress. Parallel first requests for one tenant share a
434
+ * single load: two loads would open two store instances on the same
435
+ * directories, and the receipt-order write lock only holds per instance.
436
+ */
437
+ this.loadingTenants = new Map();
438
+ /** Last use and running store calls per tenant (kept across unloads). */
439
+ this.tenantActivity = new Map();
440
+ /** Tracked store handles handed out per loaded tenant, so callers get stable identities. */
441
+ this.trackedStores = new WeakMap();
442
+ /**
443
+ * Token secret per tenant when no {@link TenantManagerOptions.jwtSecretForTenant}
444
+ * is configured. Kept across unloads and reloads so tokens stay valid.
445
+ */
446
+ this.tenantJwtSecrets = new Map();
430
447
  this.serverIdentity = null;
431
448
  this.trustedServers = [];
432
449
  /** Peer wiring handed down to every server store; see setPeerAccessControl. */
@@ -704,17 +721,17 @@ class TenantManager {
704
721
  this.serverPassword &&
705
722
  this.dataStore.exists(SERVER_KEYBAG_KEY)) {
706
723
  const keyBag = await this.loadServerKeyBag();
707
- keys.push(...(await keyBag.getAllKeys("doc", tenantId, types_1.PUBLIC_INFOS_KEY_ID)));
724
+ keys.push(...(await keyBag.getAllKeys("doc", tenantId, types_2.PUBLIC_INFOS_KEY_ID)));
708
725
  }
709
726
  return this.mergeUniqueKeys(keys);
710
727
  }
711
728
  async persistTenantPublicInfosKey(tenantId, key) {
712
729
  const keyBag = await this.loadServerKeyBag();
713
- const existingKeys = await keyBag.getAllKeys("doc", tenantId, types_1.PUBLIC_INFOS_KEY_ID);
730
+ const existingKeys = await keyBag.getAllKeys("doc", tenantId, types_2.PUBLIC_INFOS_KEY_ID);
714
731
  const incomingSignature = this.bytesToBase64(key);
715
732
  const alreadyStored = existingKeys.some((entry) => this.bytesToBase64(entry) === incomingSignature);
716
733
  if (!alreadyStored) {
717
- await keyBag.set("doc", tenantId, types_1.PUBLIC_INFOS_KEY_ID, key, Date.now());
734
+ await keyBag.set("doc", tenantId, types_2.PUBLIC_INFOS_KEY_ID, key, Date.now());
718
735
  await this.saveServerKeyBag(keyBag);
719
736
  }
720
737
  }
@@ -780,13 +797,170 @@ class TenantManager {
780
797
  }
781
798
  async getTenant(tenantId) {
782
799
  const normalizedId = tenantId.toLowerCase();
800
+ this.touchTenant(normalizedId);
783
801
  const cached = this.loadedTenants.get(normalizedId);
784
802
  if (cached) {
785
803
  return cached;
786
804
  }
787
- const loaded = await this.loadTenant(normalizedId);
788
- this.loadedTenants.set(normalizedId, loaded);
789
- return loaded;
805
+ const inFlight = this.loadingTenants.get(normalizedId);
806
+ if (inFlight) {
807
+ return inFlight;
808
+ }
809
+ const loading = this.loadTenant(normalizedId).then((loaded) => {
810
+ // Only cache if nobody invalidated the tenant while it was loading
811
+ // (config update, removal, reload, clearCache).
812
+ if (this.loadingTenants.get(normalizedId) === loading) {
813
+ this.loadingTenants.delete(normalizedId);
814
+ this.loadedTenants.set(normalizedId, loaded);
815
+ }
816
+ return loaded;
817
+ }, (error) => {
818
+ if (this.loadingTenants.get(normalizedId) === loading) {
819
+ this.loadingTenants.delete(normalizedId);
820
+ }
821
+ throw error;
822
+ });
823
+ this.loadingTenants.set(normalizedId, loading);
824
+ return loading;
825
+ }
826
+ /** Drop a tenant from the cache, including a load that is still running. */
827
+ forgetTenant(normalizedId) {
828
+ this.loadedTenants.delete(normalizedId);
829
+ this.loadingTenants.delete(normalizedId);
830
+ }
831
+ // =======================================================================
832
+ // Unloading idle tenants
833
+ // =======================================================================
834
+ touchTenant(normalizedId) {
835
+ let activity = this.tenantActivity.get(normalizedId);
836
+ if (!activity) {
837
+ activity = { lastUsedAt: Date.now(), inFlight: 0 };
838
+ this.tenantActivity.set(normalizedId, activity);
839
+ }
840
+ else {
841
+ activity.lastUsedAt = Date.now();
842
+ }
843
+ return activity;
844
+ }
845
+ /**
846
+ * Wrap a store of a loaded tenant so that its use counts as tenant activity
847
+ * and a running call keeps the tenant loaded. A caller that keeps the handle
848
+ * after the tenant was unloaded or reloaded is routed to the current
849
+ * instance (`reopen`), so there is never more than one live store instance
850
+ * per store directory.
851
+ */
852
+ trackStore(normalizedId, owner, cacheKey, target, reopen) {
853
+ let handles = this.trackedStores.get(owner);
854
+ if (!handles) {
855
+ handles = new Map();
856
+ this.trackedStores.set(owner, handles);
857
+ }
858
+ const existing = handles.get(cacheKey);
859
+ if (existing) {
860
+ return existing;
861
+ }
862
+ const proxy = new Proxy(target, {
863
+ get: (obj, prop) => {
864
+ const value = Reflect.get(obj, prop, obj);
865
+ if (typeof value !== "function") {
866
+ return value;
867
+ }
868
+ const fn = value;
869
+ if (prop === "getId" || prop === "getStoreKind" || prop === "constructor") {
870
+ return fn.bind(obj);
871
+ }
872
+ return (...args) => {
873
+ const activity = this.touchTenant(normalizedId);
874
+ if (this.loadedTenants.get(normalizedId) !== owner) {
875
+ // Unloaded or reloaded since this handle was handed out.
876
+ return reopen().then((fresh) => Reflect.get(fresh, prop, fresh).apply(fresh, args));
877
+ }
878
+ activity.inFlight++;
879
+ let result;
880
+ try {
881
+ result = fn.apply(obj, args);
882
+ }
883
+ catch (error) {
884
+ activity.inFlight--;
885
+ throw error;
886
+ }
887
+ if (result && typeof result.then === "function") {
888
+ return result.finally(() => {
889
+ activity.inFlight--;
890
+ activity.lastUsedAt = Date.now();
891
+ });
892
+ }
893
+ activity.inFlight--;
894
+ return result;
895
+ };
896
+ },
897
+ });
898
+ handles.set(cacheKey, proxy);
899
+ return proxy;
900
+ }
901
+ /**
902
+ * Unload every tenant that was not used for `idleMs`: its stores (with
903
+ * their in-memory metadata indexes), its directory and its caches. The next
904
+ * request loads it again. A tenant with running store calls or purges stays.
905
+ * Returns the ids of the unloaded tenants.
906
+ */
907
+ evictIdleTenants(idleMs, now = Date.now()) {
908
+ const evicted = [];
909
+ for (const [tenantId, tenant] of this.loadedTenants) {
910
+ const activity = this.tenantActivity.get(tenantId);
911
+ if (activity && (activity.inFlight > 0 || now - activity.lastUsedAt < idleMs)) {
912
+ continue;
913
+ }
914
+ if (this.hasPurgeInFlight(tenantId)) {
915
+ continue;
916
+ }
917
+ this.loadedTenants.delete(tenantId);
918
+ evicted.push(tenantId);
919
+ void tenant.mindooTenant
920
+ ?.disposeCacheManager?.()
921
+ .catch(() => undefined);
922
+ }
923
+ if (evicted.length > 0) {
924
+ console.log(`[TenantManager] Unloaded ${evicted.length} idle tenant(s): ${evicted.join(", ")} (${this.loadedTenants.size} still loaded)`);
925
+ }
926
+ return evicted;
927
+ }
928
+ /**
929
+ * Periodically unload tenants idle for `idleMs` (see {@link evictIdleTenants}).
930
+ * `idleMs <= 0` turns it off. The timer does not keep the process alive.
931
+ */
932
+ startIdleEviction(idleMs, intervalMs = Math.min(idleMs, 60000)) {
933
+ this.stopIdleEviction();
934
+ if (!(idleMs > 0)) {
935
+ return;
936
+ }
937
+ this.idleEvictionTimer = setInterval(() => {
938
+ try {
939
+ this.evictIdleTenants(idleMs);
940
+ }
941
+ catch (error) {
942
+ console.error("[TenantManager] Unloading idle tenants failed:", error);
943
+ }
944
+ }, Math.max(1000, intervalMs));
945
+ this.idleEvictionTimer.unref?.();
946
+ }
947
+ stopIdleEviction() {
948
+ if (this.idleEvictionTimer !== undefined) {
949
+ clearInterval(this.idleEvictionTimer);
950
+ this.idleEvictionTimer = undefined;
951
+ }
952
+ }
953
+ /** Number of tenants currently held in memory. */
954
+ getLoadedTenantCount() {
955
+ return this.loadedTenants.size;
956
+ }
957
+ hasPurgeInFlight(normalizedId) {
958
+ for (const key of this.purgeInFlight.keys()) {
959
+ if (key === normalizedId || key.startsWith(`${normalizedId}\u0000`)) {
960
+ return true;
961
+ }
962
+ }
963
+ return false;
790
964
  }
791
965
  tenantExists(tenantId) {
792
966
  const normalizedId = tenantId.toLowerCase();
@@ -857,7 +1031,7 @@ class TenantManager {
857
1031
  config.defaultStoreType = updates.defaultStoreType;
858
1032
  }
859
1033
  this.writeTenantConfig(normalizedId, config);
860
- this.loadedTenants.delete(normalizedId);
1034
+ this.forgetTenant(normalizedId);
861
1035
  console.log(`[TenantManager] Updated tenant config: ${normalizedId}`);
862
1036
  }
863
1037
  async removeTenant(tenantId) {
@@ -866,23 +1040,30 @@ class TenantManager {
866
1040
  if (!this.dataStore.exists(tenantKey)) {
867
1041
  throw new Error(`Tenant ${normalizedId} does not exist`);
868
1042
  }
869
- this.loadedTenants.delete(normalizedId);
1043
+ this.forgetTenant(normalizedId);
870
1044
  if (this.serverIdentity &&
871
1045
  this.serverPassword &&
872
1046
  this.dataStore.exists(SERVER_KEYBAG_KEY)) {
873
1047
  const keyBag = await this.loadServerKeyBag();
874
- await keyBag.deleteKey("doc", normalizedId, types_1.PUBLIC_INFOS_KEY_ID);
1048
+ await keyBag.deleteKey("doc", normalizedId, types_2.PUBLIC_INFOS_KEY_ID);
875
1049
  await this.saveServerKeyBag(keyBag);
876
1050
  }
877
1051
  this.dataStore.deleteTree(tenantKey);
878
1052
  await this.storeProvider.removeTenantStores?.(normalizedId);
1053
+ this.tenantJwtSecrets.delete(normalizedId);
1054
+ this.tenantActivity.delete(normalizedId);
879
1055
  console.log(`[TenantManager] Removed tenant: ${normalizedId}`);
880
1056
  }
881
1057
  // =======================================================================
882
1058
  // Server stores
883
1059
  // =======================================================================
884
1060
  async getServerStore(tenantId, dbId, storeKind) {
885
- const tenant = await this.getTenant(tenantId);
1061
+ const normalizedId = tenantId.toLowerCase();
1062
+ const tenant = await this.getTenant(normalizedId);
1063
+ const raw = await this.getRawServerStore(tenant, tenantId, dbId, storeKind);
1064
+ return this.trackStore(normalizedId, tenant, `server:${dbId}:${storeKind}`, raw, () => this.getServerStore(tenantId, dbId, storeKind));
1065
+ }
1066
+ async getRawServerStore(tenant, tenantId, dbId, storeKind) {
886
1067
  const cacheKey = `${dbId}:${storeKind}`;
887
1068
  const cached = tenant.serverStores.get(cacheKey);
888
1069
  if (cached) {
@@ -925,20 +1106,20 @@ class TenantManager {
925
1106
  : () => this.getPurgedDocRegistry(tenantId).getPurgedDocIds(dbId);
926
1107
  // Author-scoped read (§6.12). Never for the directory databases. The
927
1108
  // attachments store finds a document's creator in the docs store.
928
- const readScopeResolver = dbId === "directory" || dbId === types_1.USER_DIRECTORY_DB_ID
1109
+ const readScopeResolver = dbId === "directory" || dbId === types_2.USER_DIRECTORY_DB_ID
929
1110
  ? undefined
930
1111
  : this.buildReadScopeResolver(directory, dbId);
931
- const docCreatorResolver = storeKind === types_1.StoreKind.attachments
1112
+ const docCreatorResolver = storeKind === types_2.StoreKind.attachments
932
1113
  ? this.buildDocCreatorResolver(
933
1114
  // Lazy as well: a refused request must not create the docs store.
934
- lazyContentAddressedStore(dbId, types_1.StoreKind.docs, () => tenant.storeFactory.getStore(dbId, types_1.StoreKind.docs)))
1115
+ lazyContentAddressedStore(dbId, types_2.StoreKind.docs, () => tenant.storeFactory.getStore(dbId, types_2.StoreKind.docs)))
935
1116
  : undefined;
936
1117
  // Purge requests in personal databases (§6.11): checked on push (only in
937
1118
  // the docs store, where the request documents live).
938
- const purgeRequestValidator = storeKind === types_1.StoreKind.docs && (0, builtinDbInvariants_1.personalDatabaseOwner)(dbId)
1119
+ const purgeRequestValidator = storeKind === types_2.StoreKind.docs && (0, builtinDbInvariants_1.personalDatabaseOwner)(dbId)
939
1120
  ? this.buildPurgeRequestValidator(tenant, directory, localStore, dbId)
940
1121
  : undefined;
941
- const builtinWriteContext = dbId === types_1.USER_DIRECTORY_DB_ID
1122
+ const builtinWriteContext = dbId === types_2.USER_DIRECTORY_DB_ID
942
1123
  ? this.buildUserdirectoryWriteContext(tenant, localStore)
943
1124
  : undefined;
944
1125
  // Directory writes only by administrators at the server's clock, and
@@ -949,6 +1130,16 @@ class TenantManager {
949
1130
  isAdminAt: (signingKey, T) => this.isTenantAdminKeyAt(tenant, signingKey, T),
950
1131
  }
951
1132
  : undefined;
1133
+ // Join requests (docs/invitations.md): server-created, admin-decided.
1134
+ const joinRequestsWriteCheck = dbId === types_1.JOIN_REQUESTS_DB_ID
1135
+ ? {
1136
+ isAdminAt: (signingKey, T) => this.isTenantAdminKeyAt(tenant, signingKey, T),
1137
+ isJoinRequestServerKey: async (signingKey) => {
1138
+ const base = tenant.mindooTenant;
1139
+ return typeof base?.isJoinRequestServerKey === "function" ? base.isJoinRequestServerKey(signingKey) : false;
1140
+ },
1141
+ }
1142
+ : undefined;
952
1143
  const serverStore = new ServerNetworkContentAddressedStore_1.ServerNetworkContentAddressedStore(localStore, directory, tenant.authService, this.cryptoAdapter, undefined, {
953
1144
  timestampProvider,
954
1145
  witnessDbid: dbId,
@@ -963,10 +1154,19 @@ class TenantManager {
963
1154
  purgeRequestValidator,
964
1155
  builtinWriteContext,
965
1156
  directoryAdminCheck,
1157
+ joinRequestsWriteCheck,
966
1158
  ...this.peerAccessControl,
967
1159
  });
1160
+ // A parallel request for the same store may have finished first while
1161
+ // this one awaited above; keep a single instance per store.
1162
+ const raced = tenant.serverStores.get(cacheKey);
1163
+ if (raced) {
1164
+ return raced;
1165
+ }
968
1166
  tenant.serverStores.set(cacheKey, serverStore);
969
- console.log(`[TenantManager] Created server store for ${tenantId}/${dbId}/${storeKind}`);
1167
+ if ((0, LogLevel_1.getDefaultLogLevel)() >= LogLevel_1.LogLevel.DEBUG) {
1168
+ console.debug(`[TenantManager] Created server store for ${tenantId}/${dbId}/${storeKind}`);
1169
+ }
970
1170
  return serverStore;
971
1171
  }
972
1172
  /**
@@ -1155,8 +1355,9 @@ class TenantManager {
1155
1355
  };
1156
1356
  }
1157
1357
  async getStore(tenantId, dbId, storeKind) {
1158
- const tenant = await this.getTenant(tenantId);
1159
- return tenant.storeFactory.getStore(dbId, storeKind);
1358
+ const normalizedId = tenantId.toLowerCase();
1359
+ const tenant = await this.getTenant(normalizedId);
1360
+ return this.trackStore(normalizedId, tenant, `local:${dbId}:${storeKind}`, tenant.storeFactory.getStore(dbId, storeKind), () => this.getStore(tenantId, dbId, storeKind));
1160
1361
  }
1161
1362
  /**
1162
1363
  * Documents purged from `dbId` on this server (the persistent purge
@@ -1165,6 +1366,29 @@ class TenantManager {
1165
1366
  getPurgedDocIds(tenantId, dbId) {
1166
1367
  return this.getPurgedDocRegistry(tenantId).getPurgedDocIds(dbId);
1167
1368
  }
1369
+ /**
1370
+ * What the join-request inbox needs from this manager (docs/invitations.md).
1371
+ */
1372
+ joinRequestAccess() {
1373
+ return {
1374
+ tenantExists: (tenantId) => this.tenantExists(tenantId),
1375
+ getServerTenant: async (tenantId) => (await this.getTenant(tenantId)).mindooTenant,
1376
+ getServerSigningPublicKey: () => this.getServerPublicInfo()?.signingPublicKey ?? null,
1377
+ isTenantMemberKey: async (tenantId, signingKey) => {
1378
+ const tenant = await this.getTenant(tenantId);
1379
+ if (await this.isTenantAdminKeyAt(tenant, signingKey, Date.now()))
1380
+ return true;
1381
+ const directory = tenant.directory;
1382
+ return typeof directory.getUserBySigningPublicKey === "function"
1383
+ ? (await directory.getUserBySigningPublicKey(signingKey)) !== null
1384
+ : false;
1385
+ },
1386
+ recordPurgedDocument: (tenantId, dbId, docId) => this.getPurgedDocRegistry(tenantId).recordPurgedDoc(dbId, docId),
1387
+ dataStore: this.dataStore,
1388
+ tenantDataKey: (tenantId, name) => `${this.tenantKey(tenantId.toLowerCase())}/${name}`,
1389
+ cryptoAdapter: this.cryptoAdapter,
1390
+ };
1391
+ }
1168
1392
  /** The (lazily-loaded, cached) purge registry for a tenant. */
1169
1393
  getPurgedDocRegistry(tenantId) {
1170
1394
  const normalizedId = tenantId.toLowerCase();
@@ -1285,7 +1509,7 @@ class TenantManager {
1285
1509
  if (entry.entryType !== "doc_create") {
1286
1510
  return "a purge request can only be created, not changed or deleted";
1287
1511
  }
1288
- if (entry.decryptionKeyId !== types_1.PUBLIC_INFOS_KEY_ID) {
1512
+ if (entry.decryptionKeyId !== types_2.PUBLIC_INFOS_KEY_ID) {
1289
1513
  return "a purge request must be encrypted with $publicinfos";
1290
1514
  }
1291
1515
  if (!mindooTenant || typeof dir.evaluateDbAccessModeForSigningKey !== "function") {
@@ -1297,7 +1521,7 @@ class TenantManager {
1297
1521
  }
1298
1522
  let docIds = null;
1299
1523
  try {
1300
- docIds = (0, builtinDbInvariants_1.purgeRequestDocIdsFromCreateBytes)(await mindooTenant.decryptPayload(entry.encryptedData, types_1.PUBLIC_INFOS_KEY_ID));
1524
+ docIds = (0, builtinDbInvariants_1.purgeRequestDocIdsFromCreateBytes)(await mindooTenant.decryptPayload(entry.encryptedData, types_2.PUBLIC_INFOS_KEY_ID));
1301
1525
  }
1302
1526
  catch {
1303
1527
  docIds = null;
@@ -1343,7 +1567,7 @@ class TenantManager {
1343
1567
  const mindooTenant = tenant.mindooTenant;
1344
1568
  if (!mindooTenant)
1345
1569
  return;
1346
- const docsStore = await this.getStore(normalizedId, dbId, types_1.StoreKind.docs);
1570
+ const docsStore = await this.getStore(normalizedId, dbId, types_2.StoreKind.docs);
1347
1571
  const creates = (await docsStore.findEntries("doc_create", null, null)).filter((m) => (0, builtinDbInvariants_1.isPurgeRequestDocId)(m.docId));
1348
1572
  if (creates.length === 0)
1349
1573
  return;
@@ -1382,8 +1606,8 @@ class TenantManager {
1382
1606
  async purgeDocumentFromDatabase(tenantId, dbId, docId) {
1383
1607
  try {
1384
1608
  await (0, purgeDocumentHistory_1.purgeDocumentHistoryFromStores)({
1385
- docsStore: await this.getStore(tenantId, dbId, types_1.StoreKind.docs),
1386
- attachmentStore: await this.getStore(tenantId, dbId, types_1.StoreKind.attachments),
1609
+ docsStore: await this.getStore(tenantId, dbId, types_2.StoreKind.docs),
1610
+ attachmentStore: await this.getStore(tenantId, dbId, types_2.StoreKind.attachments),
1387
1611
  }, docId);
1388
1612
  }
1389
1613
  catch (error) {
@@ -1399,11 +1623,12 @@ class TenantManager {
1399
1623
  }
1400
1624
  async reloadTenant(tenantId) {
1401
1625
  const normalizedId = tenantId.toLowerCase();
1402
- this.loadedTenants.delete(normalizedId);
1626
+ this.forgetTenant(normalizedId);
1403
1627
  return this.getTenant(normalizedId);
1404
1628
  }
1405
1629
  clearCache() {
1406
1630
  this.loadedTenants.clear();
1631
+ this.loadingTenants.clear();
1407
1632
  console.log(`[TenantManager] Cleared tenant cache`);
1408
1633
  }
1409
1634
  // -----------------------------------------------------------------------
@@ -1444,16 +1669,18 @@ class TenantManager {
1444
1669
  innerDirectory = new SimpleMindooDirectory(config);
1445
1670
  }
1446
1671
  // Wrap with CompositeMindooDirectory so trusted servers are also recognized
1447
- const directory = new CompositeMindooDirectory(innerDirectory, this.trustedServers, config.adminUsername
1672
+ const directory = new CompositeMindooDirectory(innerDirectory, this.trustedServers,
1673
+ // Without a configured name the root key still authenticates by key, as a
1674
+ // principal named after it (like a delegated admin, §6.13): admin-only
1675
+ // databases such as `joinrequests` (docs/invitations.md) need that.
1676
+ config.adminSigningPublicKey && config.adminEncryptionPublicKey
1448
1677
  ? {
1449
- username: config.adminUsername,
1678
+ username: config.adminUsername ?? delegatedAdminPrincipal(config.adminSigningPublicKey),
1450
1679
  signingPublicKey: config.adminSigningPublicKey,
1451
1680
  encryptionPublicKey: config.adminEncryptionPublicKey,
1452
1681
  }
1453
1682
  : undefined);
1454
- const authService = new AuthenticationService_1.AuthenticationService(this.cryptoAdapter, directory, tenantId, this.jwtSecretForTenant
1455
- ? { jwtSecret: await this.jwtSecretForTenant(tenantId) }
1456
- : undefined);
1683
+ const authService = new AuthenticationService_1.AuthenticationService(this.cryptoAdapter, directory, tenantId, { jwtSecret: await this.getJwtSecret(tenantId) });
1457
1684
  console.log(`[TenantManager] Loaded tenant: ${tenantId}`);
1458
1685
  return {
1459
1686
  context,
@@ -1464,6 +1691,17 @@ class TenantManager {
1464
1691
  serverStores: new Map(),
1465
1692
  };
1466
1693
  }
1694
+ async getJwtSecret(tenantId) {
1695
+ if (this.jwtSecretForTenant) {
1696
+ return this.jwtSecretForTenant(tenantId);
1697
+ }
1698
+ let secret = this.tenantJwtSecrets.get(tenantId);
1699
+ if (!secret) {
1700
+ secret = this.cryptoAdapter.getRandomValues(new Uint8Array(32));
1701
+ this.tenantJwtSecrets.set(tenantId, secret);
1702
+ }
1703
+ return secret;
1704
+ }
1467
1705
  /**
1468
1706
  * Create a real BaseMindooTenant for directory reading using the global
1469
1707
  * server identity.
@@ -1475,7 +1713,7 @@ class TenantManager {
1475
1713
  // Create a KeyBag using the server user's encryption key
1476
1714
  const keyBag = await this.createServerKeyBag(serverUser, this.serverPassword);
1477
1715
  for (const publicInfosKey of this.mergeUniqueKeys(publicInfosKeys)) {
1478
- await keyBag.set("doc", tenantId, types_1.PUBLIC_INFOS_KEY_ID, publicInfosKey);
1716
+ await keyBag.set("doc", tenantId, types_2.PUBLIC_INFOS_KEY_ID, publicInfosKey);
1479
1717
  }
1480
1718
  // Collect trusted server signing keys for additionalTrustedKeys
1481
1719
  const openOptions = {};