mindoodb 0.0.96 → 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 (133) 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 +73 -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 +24 -1
  20. package/dist/core/BaseMindooTenantDirectory.d.ts.map +1 -1
  21. package/dist/core/BaseMindooTenantDirectory.js +161 -90
  22. package/dist/core/BaseMindooTenantDirectory.js.map +1 -1
  23. package/dist/core/accesscontrol/directoryProjection.d.ts +7 -1
  24. package/dist/core/accesscontrol/directoryProjection.d.ts.map +1 -1
  25. package/dist/core/accesscontrol/directoryProjection.js +24 -0
  26. package/dist/core/accesscontrol/directoryProjection.js.map +1 -1
  27. package/dist/core/accesscontrol/types.d.ts +42 -2
  28. package/dist/core/accesscontrol/types.d.ts.map +1 -1
  29. package/dist/core/accesscontrol/types.js +77 -0
  30. package/dist/core/accesscontrol/types.js.map +1 -1
  31. package/dist/core/builtinDbInvariants.d.ts +26 -1
  32. package/dist/core/builtinDbInvariants.d.ts.map +1 -1
  33. package/dist/core/builtinDbInvariants.js +52 -2
  34. package/dist/core/builtinDbInvariants.js.map +1 -1
  35. package/dist/core/index.d.ts +3 -1
  36. package/dist/core/index.d.ts.map +1 -1
  37. package/dist/core/index.js +11 -5
  38. package/dist/core/index.js.map +1 -1
  39. package/dist/core/joinrequests/crypto.d.ts +110 -0
  40. package/dist/core/joinrequests/crypto.d.ts.map +1 -0
  41. package/dist/core/joinrequests/crypto.js +340 -0
  42. package/dist/core/joinrequests/crypto.js.map +1 -0
  43. package/dist/core/joinrequests/index.d.ts +4 -0
  44. package/dist/core/joinrequests/index.d.ts.map +1 -0
  45. package/dist/core/joinrequests/index.js +29 -0
  46. package/dist/core/joinrequests/index.js.map +1 -0
  47. package/dist/core/joinrequests/invitations.d.ts +257 -0
  48. package/dist/core/joinrequests/invitations.d.ts.map +1 -0
  49. package/dist/core/joinrequests/invitations.js +703 -0
  50. package/dist/core/joinrequests/invitations.js.map +1 -0
  51. package/dist/core/joinrequests/types.d.ts +208 -0
  52. package/dist/core/joinrequests/types.d.ts.map +1 -0
  53. package/dist/core/joinrequests/types.js +43 -0
  54. package/dist/core/joinrequests/types.js.map +1 -0
  55. package/dist/core/recovery/PaperRescueDevice.d.ts +92 -0
  56. package/dist/core/recovery/PaperRescueDevice.d.ts.map +1 -0
  57. package/dist/core/recovery/PaperRescueDevice.js +182 -0
  58. package/dist/core/recovery/PaperRescueDevice.js.map +1 -0
  59. package/dist/core/recovery/RecoveryContactsDocument.d.ts +91 -0
  60. package/dist/core/recovery/RecoveryContactsDocument.d.ts.map +1 -0
  61. package/dist/core/recovery/RecoveryContactsDocument.js +92 -0
  62. package/dist/core/recovery/RecoveryContactsDocument.js.map +1 -0
  63. package/dist/core/recovery/RecoveryContactsManager.d.ts +95 -0
  64. package/dist/core/recovery/RecoveryContactsManager.d.ts.map +1 -0
  65. package/dist/core/recovery/RecoveryContactsManager.js +322 -0
  66. package/dist/core/recovery/RecoveryContactsManager.js.map +1 -0
  67. package/dist/core/recovery/index.d.ts +8 -0
  68. package/dist/core/recovery/index.d.ts.map +1 -0
  69. package/dist/core/recovery/index.js +41 -0
  70. package/dist/core/recovery/index.js.map +1 -0
  71. package/dist/core/recovery/recoverWithContacts.d.ts +36 -0
  72. package/dist/core/recovery/recoverWithContacts.d.ts.map +1 -0
  73. package/dist/core/recovery/recoverWithContacts.js +103 -0
  74. package/dist/core/recovery/recoverWithContacts.js.map +1 -0
  75. package/dist/core/recovery/recoveryPackage.d.ts +72 -0
  76. package/dist/core/recovery/recoveryPackage.d.ts.map +1 -0
  77. package/dist/core/recovery/recoveryPackage.js +181 -0
  78. package/dist/core/recovery/recoveryPackage.js.map +1 -0
  79. package/dist/core/recovery/rescueDevice.d.ts +51 -0
  80. package/dist/core/recovery/rescueDevice.d.ts.map +1 -0
  81. package/dist/core/recovery/rescueDevice.js +201 -0
  82. package/dist/core/recovery/rescueDevice.js.map +1 -0
  83. package/dist/core/recovery/shamir.d.ts +30 -0
  84. package/dist/core/recovery/shamir.d.ts.map +1 -0
  85. package/dist/core/recovery/shamir.js +133 -0
  86. package/dist/core/recovery/shamir.js.map +1 -0
  87. package/dist/core/types.d.ts +80 -2
  88. package/dist/core/types.d.ts.map +1 -1
  89. package/dist/core/types.js.map +1 -1
  90. package/dist/core/userkeys/UserKeyManager.d.ts +29 -0
  91. package/dist/core/userkeys/UserKeyManager.d.ts.map +1 -1
  92. package/dist/core/userkeys/UserKeyManager.js +76 -8
  93. package/dist/core/userkeys/UserKeyManager.js.map +1 -1
  94. package/dist/core/userkeys/generationSignature.d.ts +6 -0
  95. package/dist/core/userkeys/generationSignature.d.ts.map +1 -1
  96. package/dist/core/userkeys/generationSignature.js +1 -0
  97. package/dist/core/userkeys/generationSignature.js.map +1 -1
  98. package/dist/core/userkeys/resolveUserKeyDocument.d.ts.map +1 -1
  99. package/dist/core/userkeys/resolveUserKeyDocument.js +6 -6
  100. package/dist/core/userkeys/resolveUserKeyDocument.js.map +1 -1
  101. package/dist/core/userkeys/validateUserKeyDocument.d.ts +11 -1
  102. package/dist/core/userkeys/validateUserKeyDocument.d.ts.map +1 -1
  103. package/dist/core/userkeys/validateUserKeyDocument.js +18 -5
  104. package/dist/core/userkeys/validateUserKeyDocument.js.map +1 -1
  105. package/dist/node/server/MindooDBServer.d.ts +2 -0
  106. package/dist/node/server/MindooDBServer.d.ts.map +1 -1
  107. package/dist/node/server/MindooDBServer.js +46 -0
  108. package/dist/node/server/MindooDBServer.js.map +1 -1
  109. package/dist/node/server/StoreFactory.d.ts.map +1 -1
  110. package/dist/node/server/StoreFactory.js +4 -1
  111. package/dist/node/server/StoreFactory.js.map +1 -1
  112. package/dist/node/server/server.js +2 -0
  113. package/dist/node/server/server.js.map +1 -1
  114. package/dist/server/JoinRequestService.d.ts +108 -0
  115. package/dist/server/JoinRequestService.d.ts.map +1 -0
  116. package/dist/server/JoinRequestService.js +454 -0
  117. package/dist/server/JoinRequestService.js.map +1 -0
  118. package/dist/server/TenantManager.d.ts +50 -0
  119. package/dist/server/TenantManager.d.ts.map +1 -1
  120. package/dist/server/TenantManager.js +271 -33
  121. package/dist/server/TenantManager.js.map +1 -1
  122. package/dist/server/http/MindooDBServerCore.d.ts +18 -0
  123. package/dist/server/http/MindooDBServerCore.d.ts.map +1 -1
  124. package/dist/server/http/MindooDBServerCore.js +229 -137
  125. package/dist/server/http/MindooDBServerCore.js.map +1 -1
  126. package/dist/server/serverConfig.d.ts.map +1 -1
  127. package/dist/server/serverConfig.js +17 -0
  128. package/dist/server/serverConfig.js.map +1 -1
  129. package/dist/server/types.d.ts +15 -0
  130. package/dist/server/types.d.ts.map +1 -1
  131. package/dist/server/types.js +6 -0
  132. package/dist/server/types.js.map +1 -1
  133. package/package.json +1 -1
@@ -0,0 +1,703 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.InvitationRequestError = void 0;
4
+ exports.unlockInvitationAdmin = unlockInvitationAdmin;
5
+ exports.listInvitationAdminRecipients = listInvitationAdminRecipients;
6
+ exports.canonicalInvitationUsername = canonicalInvitationUsername;
7
+ exports.createInvitation = createInvitation;
8
+ exports.listInvitations = listInvitations;
9
+ exports.setInvitationRows = setInvitationRows;
10
+ exports.setInvitationRowStatus = setInvitationRowStatus;
11
+ exports.endInvitation = endInvitation;
12
+ exports.resealInvitationsForAdmins = resealInvitationsForAdmins;
13
+ exports.invitationLinkFragment = invitationLinkFragment;
14
+ exports.fetchInvitationForLink = fetchInvitationForLink;
15
+ exports.submitJoinRequest = submitJoinRequest;
16
+ exports.joinRequestVerificationCode = joinRequestVerificationCode;
17
+ exports.fetchJoinRequestStatus = fetchJoinRequestStatus;
18
+ exports.withdrawJoinRequest = withdrawJoinRequest;
19
+ exports.fetchJoinRequestSummary = fetchJoinRequestSummary;
20
+ exports.syncJoinRequestInbox = syncJoinRequestInbox;
21
+ exports.listJoinRequests = listJoinRequests;
22
+ exports.setJoinRequestStatus = setJoinRequestStatus;
23
+ exports.admitJoinRequests = admitJoinRequests;
24
+ exports.purgeDecidedJoinRequests = purgeDecidedJoinRequests;
25
+ const RSAEncryption_1 = require("../crypto/RSAEncryption");
26
+ const privateKeyEncryption_1 = require("../crypto/privateKeyEncryption");
27
+ const rsaOaep3072_1 = require("../crypto/rsaOaep3072");
28
+ const DirectoryStateNode_1 = require("../accesscontrol/DirectoryStateNode");
29
+ const fingerprint_1 = require("../userkeys/fingerprint");
30
+ const base64_1 = require("../utils/base64");
31
+ const joinRequestUri_1 = require("../uri/joinRequestUri");
32
+ const canonicalUsername_1 = require("../userid/canonicalUsername");
33
+ const types_1 = require("../types");
34
+ const types_2 = require("../appendonlystores/types");
35
+ const crypto_1 = require("./crypto");
36
+ const types_3 = require("./types");
37
+ /** Unlock an admin identity (as Haven stores it: a `PrivateUserId` plus its password). */
38
+ async function unlockInvitationAdmin(cryptoAdapter, identity, password) {
39
+ const subtle = cryptoAdapter.getSubtle();
40
+ const signingPkcs8 = await (0, privateKeyEncryption_1.decryptPrivateKey)(cryptoAdapter, identity.userSigningKeyPair.privateKey, password, "signing");
41
+ const signingKey = await subtle.importKey("pkcs8", signingPkcs8, { name: "Ed25519" }, false, ["sign"]);
42
+ const encryptionPkcs8 = await (0, privateKeyEncryption_1.decryptPrivateKey)(cryptoAdapter, identity.userEncryptionKeyPair.privateKey, password, "encryption");
43
+ const encryptionKey = await (0, rsaOaep3072_1.importRsaOaepPrivateKey)(cryptoAdapter, new Uint8Array(encryptionPkcs8));
44
+ return {
45
+ signingPublicKey: identity.userSigningKeyPair.publicKey,
46
+ encryptedSigningKey: identity.userSigningKeyPair.privateKey,
47
+ password,
48
+ signingKey,
49
+ encryptionPublicKey: identity.userEncryptionKeyPair.publicKey,
50
+ encryptionKey,
51
+ username: identity.username,
52
+ };
53
+ }
54
+ /** Every admin encryption key that must be able to open invitation seals: the root and active delegated admins. */
55
+ async function listInvitationAdminRecipients(tenant) {
56
+ const recipients = [
57
+ { encryptionPublicKey: tenant.getAdministrationEncryptionPublicKey() },
58
+ ];
59
+ const directory = await tenant.openDirectory();
60
+ if (typeof directory.listAdminKeys === "function") {
61
+ for (const admin of await directory.listAdminKeys()) {
62
+ if (admin.active && admin.encryptionPublicKey) {
63
+ recipients.push({ encryptionPublicKey: admin.encryptionPublicKey });
64
+ }
65
+ }
66
+ }
67
+ return recipients;
68
+ }
69
+ async function adminWriteOptions(tenant, admin) {
70
+ const pair = await tenant.resolveAdminSigningKeyPair(admin.encryptedSigningKey, admin.password);
71
+ return { signingKeyPair: pair, signingKeyPassword: admin.password };
72
+ }
73
+ /** Normalize a typed or pasted username to its canonical form (`CN=…/O=…`). */
74
+ function canonicalInvitationUsername(value) {
75
+ const trimmed = value?.trim();
76
+ if (!trimmed)
77
+ return undefined;
78
+ return (0, canonicalUsername_1.expandAbbreviatedName)(trimmed);
79
+ }
80
+ async function rowsFromInput(cryptoAdapter, kind, inputs, previous = []) {
81
+ const subtle = cryptoAdapter.getSubtle();
82
+ const byId = new Map(previous.map((row) => [row.rowId, row]));
83
+ const rows = [];
84
+ for (const input of inputs) {
85
+ const existing = input.rowId ? byId.get(input.rowId) : undefined;
86
+ const row = {
87
+ rowId: existing?.rowId ?? input.rowId ?? (0, crypto_1.newInvitationRowId)(cryptoAdapter),
88
+ ...(input.firstName?.trim() ? { firstName: input.firstName.trim() } : {}),
89
+ ...(input.lastName?.trim() ? { lastName: input.lastName.trim() } : {}),
90
+ ...(canonicalInvitationUsername(input.username) ? { username: canonicalInvitationUsername(input.username) } : {}),
91
+ ...(input.email?.trim() ? { email: input.email.trim() } : {}),
92
+ ...(input.loginType ? { loginType: input.loginType } : {}),
93
+ ...(input.loginValue?.trim() ? { loginValue: input.loginValue.trim() } : {}),
94
+ status: input.status ?? existing?.status ?? "new",
95
+ ...(existing?.joinRequestDocId ? { joinRequestDocId: existing.joinRequestDocId } : {}),
96
+ updatedAt: Date.now(),
97
+ };
98
+ if (kind === "personal") {
99
+ row.nonce = existing?.nonce ?? (0, crypto_1.newInvitationNonce)(cryptoAdapter);
100
+ row.nonceHash = existing?.nonceHash ?? (await (0, crypto_1.hashInvitationNonce)(subtle, row.nonce));
101
+ }
102
+ rows.push(row);
103
+ }
104
+ return rows;
105
+ }
106
+ async function fetchServerSigningKey(serverUrl) {
107
+ const response = await fetch(`${serverUrl.replace(/\/$/, "")}/.well-known/mindoodb-server-info`);
108
+ if (!response.ok)
109
+ throw new Error(`Server info not available (HTTP ${response.status})`);
110
+ const body = (await response.json());
111
+ if (typeof body.signingPublicKey !== "string" || !body.signingPublicKey) {
112
+ throw new Error("Server info carries no signing key");
113
+ }
114
+ return body.signingPublicKey;
115
+ }
116
+ /**
117
+ * Create an invitation in the local `directory` replica. Push the directory to
118
+ * the server afterwards; until then the server answers the link with 404.
119
+ */
120
+ async function createInvitation(tenant, admin, options) {
121
+ const cryptoAdapter = tenant.getCryptoAdapter();
122
+ const subtle = cryptoAdapter.getSubtle();
123
+ const invitationId = (0, crypto_1.newInvitationId)(cryptoAdapter);
124
+ const { publicKeyPem, privateKeyBytes } = await (0, rsaOaep3072_1.generateRsaOaep3072)(cryptoAdapter);
125
+ const rows = await rowsFromInput(cryptoAdapter, options.kind, options.rows ?? []);
126
+ const content = {
127
+ v: 1,
128
+ privateKey: (0, base64_1.bytesToBase64)(privateKeyBytes),
129
+ rows,
130
+ ...(options.label?.trim() ? { label: options.label.trim() } : {}),
131
+ };
132
+ const { blob } = await (0, crypto_1.sealForAdmins)(cryptoAdapter, (0, crypto_1.encodeJson)(content), await listInvitationAdminRecipients(tenant));
133
+ const now = Date.now();
134
+ const doc = {
135
+ form: types_3.INVITATION_FORM,
136
+ invitationId,
137
+ kind: options.kind,
138
+ publicKey: publicKeyPem,
139
+ keyFingerprint: await (0, crypto_1.invitationKeyFingerprint)(subtle, publicKeyPem),
140
+ createdAt: now,
141
+ expiresAt: options.expiresAt ?? now + types_3.DEFAULT_INVITATION_TTL_MS,
142
+ ...(typeof options.maxUses === "number" && options.maxUses > 0 ? { maxUses: Math.floor(options.maxUses) } : {}),
143
+ nonceHashes: rows.map((row) => row.nonceHash).filter((hash) => !!hash),
144
+ ended: false,
145
+ serverSigningPublicKey: options.serverSigningPublicKey ?? (await fetchServerSigningKey(options.serverUrl)),
146
+ serverUrl: options.serverUrl.replace(/\/$/, ""),
147
+ sealed: JSON.stringify(blob),
148
+ };
149
+ const directoryDb = await tenant.openDB(types_1.DIRECTORY_DB_ID, { adminOnlyDb: true });
150
+ await directoryDb.createDocument({
151
+ id: `${types_3.INVITATION_DOC_ID_PREFIX}${invitationId}`,
152
+ assumeUniqueId: true,
153
+ decryptionKeyId: types_1.PUBLIC_INFOS_KEY_ID,
154
+ initialValues: doc,
155
+ ...(await adminWriteOptions(tenant, admin)),
156
+ });
157
+ return { ...viewFromDoc(doc), label: content.label, rows, readable: true };
158
+ }
159
+ function viewFromDoc(doc) {
160
+ return {
161
+ invitationId: doc.invitationId,
162
+ kind: doc.kind,
163
+ publicKey: doc.publicKey,
164
+ keyFingerprint: doc.keyFingerprint,
165
+ createdAt: doc.createdAt,
166
+ expiresAt: doc.expiresAt,
167
+ ended: doc.ended === true,
168
+ ...(typeof doc.maxUses === "number" ? { maxUses: doc.maxUses } : {}),
169
+ ...(doc.serverUrl ? { serverUrl: doc.serverUrl } : {}),
170
+ ...(doc.serverSigningPublicKey ? { serverSigningPublicKey: doc.serverSigningPublicKey } : {}),
171
+ readable: false,
172
+ };
173
+ }
174
+ function toPlain(value) {
175
+ return JSON.parse(JSON.stringify(value));
176
+ }
177
+ async function readInvitationDocs(tenant) {
178
+ const directoryDb = await tenant.openDB(types_1.DIRECTORY_DB_ID, { adminOnlyDb: true });
179
+ await directoryDb.syncStoreChanges();
180
+ const out = [];
181
+ for (const docId of await directoryDb.getAllDocumentIds()) {
182
+ if (!docId.startsWith(types_3.INVITATION_DOC_ID_PREFIX))
183
+ continue;
184
+ try {
185
+ const data = toPlain((await directoryDb.getDocument(docId)).getData());
186
+ if (data.form !== types_3.INVITATION_FORM || typeof data.publicKey !== "string")
187
+ continue;
188
+ out.push({ db: directoryDb, docId, doc: { ...data, nonceHashes: data.nonceHashes ?? [] } });
189
+ }
190
+ catch {
191
+ // unreadable or deleted
192
+ }
193
+ }
194
+ return out;
195
+ }
196
+ async function openInvitationSeal(tenant, doc, admin) {
197
+ try {
198
+ const blob = JSON.parse(doc.sealed);
199
+ const opened = await (0, crypto_1.openAdminSeal)(tenant.getCryptoAdapter(), blob, {
200
+ encryptionPublicKey: admin.encryptionPublicKey,
201
+ encryptionPrivateKey: admin.encryptionKey,
202
+ });
203
+ if (!opened)
204
+ return null;
205
+ return { content: (0, crypto_1.decodeJson)(opened.plaintext), aesKey: opened.aesKey, blob };
206
+ }
207
+ catch {
208
+ return null;
209
+ }
210
+ }
211
+ /** All invitations of the tenant, with the sealed list where this admin can open it. Newest first. */
212
+ async function listInvitations(tenant, admin) {
213
+ const views = [];
214
+ for (const { doc } of await readInvitationDocs(tenant)) {
215
+ const view = viewFromDoc(doc);
216
+ if (admin) {
217
+ const opened = await openInvitationSeal(tenant, doc, admin);
218
+ if (opened) {
219
+ view.readable = true;
220
+ view.rows = opened.content.rows;
221
+ if (opened.content.label)
222
+ view.label = opened.content.label;
223
+ }
224
+ }
225
+ views.push(view);
226
+ }
227
+ return views.sort((a, b) => b.createdAt - a.createdAt);
228
+ }
229
+ async function changeInvitation(tenant, admin, invitationId, mutate) {
230
+ const docId = `${types_3.INVITATION_DOC_ID_PREFIX}${invitationId}`;
231
+ const entry = (await readInvitationDocs(tenant)).find((item) => item.docId === docId);
232
+ if (!entry)
233
+ throw new Error(`Invitation ${invitationId} not found`);
234
+ const opened = await openInvitationSeal(tenant, entry.doc, admin);
235
+ if (!opened)
236
+ throw new Error("This admin key cannot open the invitation; another admin has to re-seal it first");
237
+ const state = { doc: { ...entry.doc }, content: opened.content };
238
+ await mutate(state);
239
+ const cryptoAdapter = tenant.getCryptoAdapter();
240
+ const { blob } = await (0, crypto_1.sealForAdmins)(cryptoAdapter, (0, crypto_1.encodeJson)(state.content), await listInvitationAdminRecipients(tenant), { aesKey: opened.aesKey, wraps: opened.blob.wraps });
241
+ state.doc.sealed = JSON.stringify(blob);
242
+ state.doc.nonceHashes = state.content.rows.map((row) => row.nonceHash).filter((hash) => !!hash);
243
+ const mindooDoc = await entry.db.getDocument(docId);
244
+ await entry.db.changeDoc(mindooDoc, (d) => {
245
+ const data = d.getData();
246
+ data.sealed = state.doc.sealed;
247
+ data.nonceHashes = [...state.doc.nonceHashes];
248
+ data.ended = state.doc.ended === true;
249
+ data.expiresAt = state.doc.expiresAt;
250
+ if (typeof state.doc.maxUses === "number")
251
+ data.maxUses = state.doc.maxUses;
252
+ }, await adminWriteOptions(tenant, admin));
253
+ return {
254
+ ...viewFromDoc(state.doc),
255
+ rows: state.content.rows,
256
+ ...(state.content.label ? { label: state.content.label } : {}),
257
+ readable: true,
258
+ };
259
+ }
260
+ /** Replace the invitation list (new rows get a nonce on personal invitations; known rows keep theirs). */
261
+ function setInvitationRows(tenant, admin, invitationId, rows, options) {
262
+ return changeInvitation(tenant, admin, invitationId, async (state) => {
263
+ state.content.rows = await rowsFromInput(tenant.getCryptoAdapter(), state.doc.kind, rows, state.content.rows);
264
+ if (options?.label !== undefined)
265
+ state.content.label = options.label.trim() || undefined;
266
+ });
267
+ }
268
+ /** Update the status of single rows (e.g. `sent` after the link went out). */
269
+ function setInvitationRowStatus(tenant, admin, invitationId, updates) {
270
+ return changeInvitation(tenant, admin, invitationId, (state) => {
271
+ for (const update of updates) {
272
+ const row = state.content.rows.find((candidate) => candidate.rowId === update.rowId);
273
+ if (!row)
274
+ continue;
275
+ row.status = update.status;
276
+ if (update.joinRequestDocId)
277
+ row.joinRequestDocId = update.joinRequestDocId;
278
+ row.updatedAt = Date.now();
279
+ }
280
+ });
281
+ }
282
+ /** Stop accepting requests for an invitation. Requests already received stay. */
283
+ function endInvitation(tenant, admin, invitationId) {
284
+ return changeInvitation(tenant, admin, invitationId, (state) => {
285
+ state.doc.ended = true;
286
+ });
287
+ }
288
+ /**
289
+ * Add wraps for admins that were added after an invitation was sealed. Run on
290
+ * an admin device that can open the seals (Haven does it when the admin opens
291
+ * the invitation list). Returns the ids of re-sealed invitations.
292
+ */
293
+ async function resealInvitationsForAdmins(tenant, admin) {
294
+ const cryptoAdapter = tenant.getCryptoAdapter();
295
+ const subtle = cryptoAdapter.getSubtle();
296
+ const recipients = await listInvitationAdminRecipients(tenant);
297
+ const fingerprints = await Promise.all(recipients.map(async (recipient) => ({
298
+ recipient,
299
+ fp: await (0, fingerprint_1.fingerprintPublicKeyPem)(recipient.encryptionPublicKey, subtle),
300
+ })));
301
+ const resealed = [];
302
+ for (const { doc } of await readInvitationDocs(tenant)) {
303
+ let blob;
304
+ try {
305
+ blob = JSON.parse(doc.sealed);
306
+ }
307
+ catch {
308
+ continue;
309
+ }
310
+ if (fingerprints.every(({ fp }) => blob.wraps?.[fp]))
311
+ continue;
312
+ const opened = await openInvitationSeal(tenant, doc, admin);
313
+ if (!opened)
314
+ continue;
315
+ await changeInvitation(tenant, admin, doc.invitationId, () => undefined);
316
+ resealed.push(doc.invitationId);
317
+ }
318
+ return resealed;
319
+ }
320
+ /** The link fragment for one row (personal) or for the whole invitation (open). */
321
+ function invitationLinkFragment(tenantId, invitation, row, options) {
322
+ const server = options?.serverUrl ?? invitation.serverUrl;
323
+ if (!server)
324
+ throw new Error("No server URL for this invitation");
325
+ return (0, crypto_1.buildInvitationLinkFragment)({
326
+ serverUrl: server,
327
+ tenantId,
328
+ invitationId: invitation.invitationId,
329
+ ...(row?.nonce ? { nonce: row.nonce } : {}),
330
+ keyFingerprint: invitation.keyFingerprint,
331
+ ...(options?.tenantLabel ? { tenantLabel: options.tenantLabel } : {}),
332
+ });
333
+ }
334
+ // ---------------------------------------------------------------------------
335
+ // Device side
336
+ // ---------------------------------------------------------------------------
337
+ /** Error from the server's invitation endpoints, with its machine-readable code. */
338
+ class InvitationRequestError extends Error {
339
+ constructor(message, status, code) {
340
+ super(message);
341
+ this.status = status;
342
+ this.code = code;
343
+ this.name = "InvitationRequestError";
344
+ }
345
+ }
346
+ exports.InvitationRequestError = InvitationRequestError;
347
+ /**
348
+ * Read an invitation from the server and check its key against the link. A
349
+ * mismatch means the server (or someone in between) handed out another key,
350
+ * which would let it read the request: the caller must stop.
351
+ */
352
+ async function fetchInvitationForLink(cryptoAdapter, link) {
353
+ const url = `${link.serverUrl}/${encodeURIComponent(link.tenantId)}/invitations/${encodeURIComponent(link.invitationId)}`;
354
+ const response = await fetch(url);
355
+ const body = (await response.json().catch(() => ({})));
356
+ if (!response.ok) {
357
+ throw new InvitationRequestError(String(body.error ?? `HTTP ${response.status}`), response.status, body.code);
358
+ }
359
+ const info = body;
360
+ const fingerprint = await (0, crypto_1.invitationKeyFingerprint)(cryptoAdapter.getSubtle(), info.publicKey);
361
+ if (fingerprint !== link.keyFingerprint || info.keyFingerprint !== link.keyFingerprint) {
362
+ throw new InvitationRequestError("The invitation key does not match the link", 409, "key_mismatch");
363
+ }
364
+ return info;
365
+ }
366
+ /** Post a join request for an invitation link. */
367
+ async function submitJoinRequest(cryptoAdapter, options) {
368
+ const subtle = cryptoAdapter.getSubtle();
369
+ const { link } = options;
370
+ const invitation = options.invitation ?? (await fetchInvitationForLink(cryptoAdapter, link));
371
+ const request = (0, joinRequestUri_1.decodeJoinRequestUri)(options.joinRequestUri);
372
+ const hash = await (0, crypto_1.joinRequestHash)(subtle, link.tenantId, link.invitationId, request);
373
+ const inner = {
374
+ v: 1,
375
+ tenantId: link.tenantId,
376
+ invitationId: link.invitationId,
377
+ joinRequest: options.joinRequestUri,
378
+ ...(link.nonce ? { hmac: await (0, crypto_1.computeJoinRequestHmac)(subtle, link.nonce, hash) } : {}),
379
+ ...(options.message?.trim() ? { message: options.message.trim().slice(0, types_3.MAX_JOIN_REQUEST_MESSAGE_CHARS) } : {}),
380
+ createdAt: Date.now(),
381
+ };
382
+ const rsa = new RSAEncryption_1.RSAEncryption(cryptoAdapter);
383
+ const sealedRequest = await rsa.encryptToBase64((0, crypto_1.encodeJson)(inner), invitation.publicKey);
384
+ const unsigned = {
385
+ v: 1,
386
+ tenantId: link.tenantId,
387
+ invitationId: link.invitationId,
388
+ ...(link.nonce ? { nonceHash: await (0, crypto_1.hashInvitationNonce)(subtle, link.nonce) } : {}),
389
+ deviceSigningPublicKey: request.signingPublicKey,
390
+ createdAt: inner.createdAt,
391
+ sealedRequest,
392
+ };
393
+ const signature = await subtle.sign({ name: "Ed25519" }, options.deviceSigningKey, (await (0, crypto_1.joinRequestEnvelopeBytes)(subtle, unsigned)).slice());
394
+ const submission = { ...unsigned, signature: (0, base64_1.bytesToBase64)(new Uint8Array(signature)) };
395
+ const response = await fetch(`${link.serverUrl}/${encodeURIComponent(link.tenantId)}/join-requests`, {
396
+ method: "POST",
397
+ headers: { "Content-Type": "application/json" },
398
+ body: JSON.stringify(submission),
399
+ });
400
+ const body = (await response.json().catch(() => ({})));
401
+ if (!response.ok) {
402
+ throw new InvitationRequestError(String(body.error ?? `HTTP ${response.status}`), response.status, body.code);
403
+ }
404
+ return {
405
+ id: String(body.id),
406
+ expiresAt: Number(body.expiresAt),
407
+ verificationCode: (0, crypto_1.verificationCodeFromHash)(hash),
408
+ };
409
+ }
410
+ /**
411
+ * The verification code of a request, for requests sent without an
412
+ * invitation (code over the join request alone) or with an open link.
413
+ */
414
+ async function joinRequestVerificationCode(cryptoAdapter, joinRequestUri, scope) {
415
+ const request = (0, joinRequestUri_1.decodeJoinRequestUri)(joinRequestUri);
416
+ const hash = await (0, crypto_1.joinRequestHash)(cryptoAdapter.getSubtle(), scope?.tenantId ?? "", scope?.invitationId ?? "", request);
417
+ return (0, crypto_1.verificationCodeFromHash)(hash);
418
+ }
419
+ /**
420
+ * Ask the server what became of a request. `accepted` shows up once the
421
+ * server saw the admin's decision; the device learns it is in by discovery
422
+ * either way, so poll that too.
423
+ */
424
+ async function fetchJoinRequestStatus(serverUrl, tenantId, requestId) {
425
+ const response = await fetch(`${serverUrl.replace(/\/$/, "")}/${encodeURIComponent(tenantId)}/join-requests/${encodeURIComponent(requestId)}`);
426
+ const body = (await response.json().catch(() => ({})));
427
+ if (!response.ok) {
428
+ throw new InvitationRequestError(String(body.error ?? `HTTP ${response.status}`), response.status, body.code);
429
+ }
430
+ return {
431
+ status: String(body.status),
432
+ ...(typeof body.expiresAt === "number" ? { expiresAt: body.expiresAt } : {}),
433
+ };
434
+ }
435
+ /** Take a request back (signed by the device that sent it). The server purges it. */
436
+ async function withdrawJoinRequest(cryptoAdapter, options) {
437
+ const createdAt = Date.now();
438
+ const tenantId = options.tenantId.toLowerCase();
439
+ const signature = await cryptoAdapter.getSubtle().sign({ name: "Ed25519" }, options.deviceSigningKey, (0, crypto_1.joinRequestWithdrawalBytes)({ tenantId, docId: options.requestId, createdAt }).slice());
440
+ const response = await fetch(`${options.serverUrl.replace(/\/$/, "")}/${encodeURIComponent(tenantId)}/join-requests/${encodeURIComponent(options.requestId)}/withdraw`, {
441
+ method: "POST",
442
+ headers: { "Content-Type": "application/json" },
443
+ body: JSON.stringify({
444
+ deviceSigningPublicKey: options.deviceSigningPublicKey,
445
+ createdAt,
446
+ signature: (0, base64_1.bytesToBase64)(new Uint8Array(signature)),
447
+ }),
448
+ });
449
+ if (!response.ok) {
450
+ const body = (await response.json().catch(() => ({})));
451
+ throw new InvitationRequestError(String(body.error ?? `HTTP ${response.status}`), response.status, body.code);
452
+ }
453
+ }
454
+ /**
455
+ * Number of pending requests in a tenant's inbox, asked with a member
456
+ * device's key (no admin key needed). For a "N new requests" hint.
457
+ */
458
+ async function fetchJoinRequestSummary(cryptoAdapter, options) {
459
+ const createdAt = Date.now();
460
+ const tenantId = options.tenantId.toLowerCase();
461
+ const signature = await cryptoAdapter.getSubtle().sign({ name: "Ed25519" }, options.deviceSigningKey, (0, crypto_1.joinRequestSummaryBytes)({ tenantId, createdAt }).slice());
462
+ const response = await fetch(`${options.serverUrl.replace(/\/$/, "")}/${encodeURIComponent(tenantId)}/join-requests/summary`, {
463
+ method: "POST",
464
+ headers: { "Content-Type": "application/json" },
465
+ body: JSON.stringify({
466
+ deviceSigningPublicKey: options.deviceSigningPublicKey,
467
+ createdAt,
468
+ signature: (0, base64_1.bytesToBase64)(new Uint8Array(signature)),
469
+ }),
470
+ });
471
+ const body = (await response.json().catch(() => ({})));
472
+ if (!response.ok) {
473
+ throw new InvitationRequestError(String(body.error ?? `HTTP ${response.status}`), response.status, body.code);
474
+ }
475
+ return { pending: Number(body.pending) || 0 };
476
+ }
477
+ /**
478
+ * Pull (and push decisions of) the `joinrequests` database with the admin key,
479
+ * then forget local copies of requests the server already purged.
480
+ */
481
+ async function syncJoinRequestInbox(tenant, serverUrl, admin) {
482
+ const remote = await tenant.connectToServer(serverUrl, types_3.JOIN_REQUESTS_DB_ID, types_2.StoreKind.docs, {
483
+ authAs: {
484
+ signingPublicKey: admin.signingPublicKey,
485
+ signingKey: admin.signingKey,
486
+ encryptionKey: admin.encryptionKey,
487
+ },
488
+ });
489
+ const db = await tenant.openDB(types_3.JOIN_REQUESTS_DB_ID);
490
+ await db.pushChangesTo(remote);
491
+ await db.pullChangesFrom(remote);
492
+ await forgetServerPurgedRequests(tenant, db, remote);
493
+ }
494
+ async function forgetServerPurgedRequests(tenant, db, remote) {
495
+ const local = tenant.getDocStoreForDb(types_3.JOIN_REQUESTS_DB_ID);
496
+ const localIds = await local.getAllIds();
497
+ if (localIds.length === 0)
498
+ return;
499
+ const remoteIds = new Set(await remote.hasEntries(localIds));
500
+ const goneDocs = new Set();
501
+ for (const id of localIds) {
502
+ if (remoteIds.has(id))
503
+ continue;
504
+ const meta = await local.getEntryMetadata(id);
505
+ if (meta?.entryType === "doc_create" && meta.docId)
506
+ goneDocs.add(meta.docId);
507
+ }
508
+ for (const docId of goneDocs) {
509
+ await db.purgeDocumentHistory(docId);
510
+ }
511
+ }
512
+ /** Decrypt and check every request in the local inbox replica. */
513
+ async function listJoinRequests(tenant, admin, options) {
514
+ const cryptoAdapter = tenant.getCryptoAdapter();
515
+ const subtle = cryptoAdapter.getSubtle();
516
+ const now = Date.now();
517
+ const invitations = new Map();
518
+ for (const { doc } of await readInvitationDocs(tenant)) {
519
+ const opened = await openInvitationSeal(tenant, doc, admin);
520
+ invitations.set(doc.invitationId, {
521
+ doc,
522
+ content: opened?.content,
523
+ key: opened ? await (0, rsaOaep3072_1.importRsaOaepPrivateKey)(cryptoAdapter, (0, base64_1.base64ToBytes)(opened.content.privateKey)) : undefined,
524
+ });
525
+ }
526
+ const db = await tenant.openDB(types_3.JOIN_REQUESTS_DB_ID);
527
+ await db.syncStoreChanges();
528
+ const rsa = new RSAEncryption_1.RSAEncryption(cryptoAdapter);
529
+ const items = [];
530
+ for (const docId of await db.getAllDocumentIds()) {
531
+ if (!docId.startsWith(types_3.JOIN_REQUEST_DOC_ID_PREFIX))
532
+ continue;
533
+ let data;
534
+ try {
535
+ data = toPlain((await db.getDocument(docId)).getData());
536
+ }
537
+ catch {
538
+ continue;
539
+ }
540
+ if (!options?.includeDecided && (data.status !== "pending" || data.expiresAt <= now))
541
+ continue;
542
+ const item = {
543
+ docId,
544
+ status: data.status,
545
+ receivedAt: data.receivedAt,
546
+ expiresAt: data.expiresAt,
547
+ invitationId: data.invitationId,
548
+ deviceKeyFingerprint: data.deviceKeyFingerprint,
549
+ match: "invalid",
550
+ problems: [],
551
+ };
552
+ items.push(item);
553
+ const invitation = invitations.get(data.invitationId);
554
+ if (!invitation) {
555
+ item.problems.push("unknown_invitation");
556
+ continue;
557
+ }
558
+ item.kind = invitation.doc.kind;
559
+ if (invitation.content?.label)
560
+ item.invitationLabel = invitation.content.label;
561
+ if (!invitation.key || !invitation.content) {
562
+ item.problems.push("invitation_not_readable");
563
+ continue;
564
+ }
565
+ if (!(await (0, crypto_1.verifyJoinRequestEnvelope)(subtle, { v: 1, tenantId: tenant.getId(), ...data }))) {
566
+ item.problems.push("bad_device_signature");
567
+ }
568
+ let inner;
569
+ try {
570
+ inner = (0, crypto_1.decodeJson)(await rsa.decryptFromBase64(data.sealedRequest, invitation.key));
571
+ }
572
+ catch {
573
+ item.problems.push("cannot_decrypt");
574
+ continue;
575
+ }
576
+ let request;
577
+ try {
578
+ request = (0, joinRequestUri_1.decodeJoinRequestUri)(inner.joinRequest);
579
+ }
580
+ catch {
581
+ item.problems.push("bad_join_request");
582
+ continue;
583
+ }
584
+ item.joinRequestUri = inner.joinRequest;
585
+ item.request = request;
586
+ if (inner.message)
587
+ item.message = inner.message.slice(0, types_3.MAX_JOIN_REQUEST_MESSAGE_CHARS);
588
+ if (inner.tenantId !== tenant.getId() || inner.invitationId !== data.invitationId) {
589
+ item.problems.push("wrong_scope");
590
+ }
591
+ if (!(0, DirectoryStateNode_1.signingKeysEqual)((0, fingerprint_1.normalizePublicKeyPem)(request.signingPublicKey), (0, fingerprint_1.normalizePublicKeyPem)(data.deviceSigningPublicKey))) {
592
+ item.problems.push("device_key_mismatch");
593
+ }
594
+ if ((await (0, crypto_1.deviceKeyFingerprint)(subtle, request.signingPublicKey)) !== data.deviceKeyFingerprint) {
595
+ item.problems.push("device_fingerprint_mismatch");
596
+ }
597
+ const hash = await (0, crypto_1.joinRequestHash)(subtle, tenant.getId(), data.invitationId, request);
598
+ item.verificationCode = (0, crypto_1.verificationCodeFromHash)(hash);
599
+ if (invitation.doc.kind === "personal") {
600
+ const row = invitation.content.rows.find((candidate) => candidate.nonceHash && candidate.nonceHash === data.nonceHash);
601
+ if (!row || !row.nonce) {
602
+ item.problems.push("unknown_link");
603
+ }
604
+ else if (!inner.hmac || !(await (0, crypto_1.verifyJoinRequestHmac)(subtle, row.nonce, hash, inner.hmac))) {
605
+ item.problems.push("bad_link_proof");
606
+ }
607
+ else {
608
+ item.row = row;
609
+ }
610
+ }
611
+ item.username = item.row?.username ?? request.username;
612
+ item.match = item.problems.length > 0 ? "invalid" : invitation.doc.kind === "personal" ? "match" : "unverified";
613
+ }
614
+ return items.sort((a, b) => a.receivedAt - b.receivedAt);
615
+ }
616
+ async function setStatusLocal(tenant, admin, docId, status) {
617
+ const db = await tenant.openDB(types_3.JOIN_REQUESTS_DB_ID);
618
+ const doc = await db.getDocument(docId);
619
+ await db.changeDoc(doc, (d) => {
620
+ const data = d.getData();
621
+ data.status = status;
622
+ data.decidedAt = Date.now();
623
+ }, await adminWriteOptions(tenant, admin));
624
+ }
625
+ /**
626
+ * Set a request's status (`rejected`, `withdrawn`, …). Sync the inbox
627
+ * afterwards: the server purges decided requests once it sees the change,
628
+ * and the next sync forgets the local copy.
629
+ */
630
+ async function setJoinRequestStatus(tenant, admin, docId, status) {
631
+ await setStatusLocal(tenant, admin, docId, status);
632
+ }
633
+ /**
634
+ * Admit requests: grant each with `approveJoinRequest` under the list row's
635
+ * name, mark the request `accepted` and the row `admitted`. The joining
636
+ * device finds the grant by discovery once the directory reaches the server,
637
+ * so push `directory` and sync the inbox afterwards. Items with problems are
638
+ * refused here, whatever the caller passes.
639
+ */
640
+ async function admitJoinRequests(tenant, admin, items, options = {}) {
641
+ const results = [];
642
+ const rowUpdates = new Map();
643
+ for (const item of items) {
644
+ if (item.match === "invalid" || !item.joinRequestUri) {
645
+ results.push({ docId: item.docId, ok: false, error: item.problems.join(", ") || "invalid" });
646
+ continue;
647
+ }
648
+ const username = canonicalInvitationUsername(options.usernames?.[item.docId] ?? item.username);
649
+ if (!username) {
650
+ results.push({ docId: item.docId, ok: false, error: "missing_username" });
651
+ continue;
652
+ }
653
+ try {
654
+ await tenant.approveJoinRequest(item.joinRequestUri, {
655
+ adminSigningKey: admin.encryptedSigningKey,
656
+ adminPassword: admin.password,
657
+ username,
658
+ ...(options.serverUrl ? { serverUrl: options.serverUrl } : {}),
659
+ ...(admin.username ? { adminUsername: admin.username } : {}),
660
+ ...(options.sharedDocKeyIds ? { sharedDocKeyIds: options.sharedDocKeyIds } : {}),
661
+ ...(options.allowDeviceSelfGrant ? { allowDeviceSelfGrant: true } : {}),
662
+ });
663
+ await setStatusLocal(tenant, admin, item.docId, "accepted");
664
+ if (item.row) {
665
+ const list = rowUpdates.get(item.invitationId) ?? [];
666
+ list.push({ rowId: item.row.rowId, status: "admitted", joinRequestDocId: item.docId });
667
+ rowUpdates.set(item.invitationId, list);
668
+ }
669
+ results.push({ docId: item.docId, ok: true, username });
670
+ }
671
+ catch (error) {
672
+ results.push({ docId: item.docId, ok: false, username, error: error instanceof Error ? error.message : String(error) });
673
+ }
674
+ }
675
+ for (const [invitationId, updates] of rowUpdates) {
676
+ await setInvitationRowStatus(tenant, admin, invitationId, updates);
677
+ }
678
+ return results;
679
+ }
680
+ /**
681
+ * Purge local copies of decided or expired requests (the server purges its
682
+ * copy on its own). Returns the purged ids.
683
+ */
684
+ async function purgeDecidedJoinRequests(tenant) {
685
+ const db = await tenant.openDB(types_3.JOIN_REQUESTS_DB_ID);
686
+ await db.syncStoreChanges();
687
+ const now = Date.now();
688
+ const purged = [];
689
+ for (const docId of await db.getAllDocumentIds()) {
690
+ try {
691
+ const data = toPlain((await db.getDocument(docId)).getData());
692
+ if (data.status === "pending" && data.expiresAt > now)
693
+ continue;
694
+ }
695
+ catch {
696
+ // unreadable: purge
697
+ }
698
+ await db.purgeDocumentHistory(docId);
699
+ purged.push(docId);
700
+ }
701
+ return purged;
702
+ }
703
+ //# sourceMappingURL=invitations.js.map