mindoodb 0.2.9 → 0.3.1

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 (124) hide show
  1. package/dist/appendonlystores/network/ClientNetworkContentAddressedStore.d.ts +23 -18
  2. package/dist/appendonlystores/network/ClientNetworkContentAddressedStore.d.ts.map +1 -1
  3. package/dist/appendonlystores/network/ClientNetworkContentAddressedStore.js +94 -28
  4. package/dist/appendonlystores/network/ClientNetworkContentAddressedStore.js.map +1 -1
  5. package/dist/appendonlystores/network/HttpTransport.d.ts +5 -1
  6. package/dist/appendonlystores/network/HttpTransport.d.ts.map +1 -1
  7. package/dist/appendonlystores/network/HttpTransport.js +13 -3
  8. package/dist/appendonlystores/network/HttpTransport.js.map +1 -1
  9. package/dist/appendonlystores/network/ServerNetworkContentAddressedStore.d.ts +19 -0
  10. package/dist/appendonlystores/network/ServerNetworkContentAddressedStore.d.ts.map +1 -1
  11. package/dist/appendonlystores/network/ServerNetworkContentAddressedStore.js +90 -1
  12. package/dist/appendonlystores/network/ServerNetworkContentAddressedStore.js.map +1 -1
  13. package/dist/browser/index.mjs +33 -0
  14. package/dist/core/BaseMindooTenantDirectory.d.ts +86 -1
  15. package/dist/core/BaseMindooTenantDirectory.d.ts.map +1 -1
  16. package/dist/core/BaseMindooTenantDirectory.js +353 -12
  17. package/dist/core/BaseMindooTenantDirectory.js.map +1 -1
  18. package/dist/core/accesscontrol/directoryProjection.d.ts.map +1 -1
  19. package/dist/core/accesscontrol/directoryProjection.js +1 -0
  20. package/dist/core/accesscontrol/directoryProjection.js.map +1 -1
  21. package/dist/core/accesscontrol/types.d.ts +11 -2
  22. package/dist/core/accesscontrol/types.d.ts.map +1 -1
  23. package/dist/core/accesscontrol/types.js +3 -0
  24. package/dist/core/accesscontrol/types.js.map +1 -1
  25. package/dist/core/activity/ActivityIndex.d.ts +80 -0
  26. package/dist/core/activity/ActivityIndex.d.ts.map +1 -0
  27. package/dist/core/activity/ActivityIndex.js +378 -0
  28. package/dist/core/activity/ActivityIndex.js.map +1 -0
  29. package/dist/core/activity/MemoryActivityTable.d.ts +52 -0
  30. package/dist/core/activity/MemoryActivityTable.d.ts.map +1 -0
  31. package/dist/core/activity/MemoryActivityTable.js +196 -0
  32. package/dist/core/activity/MemoryActivityTable.js.map +1 -0
  33. package/dist/core/activity/SqliteActivityTable.d.ts +41 -0
  34. package/dist/core/activity/SqliteActivityTable.d.ts.map +1 -0
  35. package/dist/core/activity/SqliteActivityTable.js +302 -0
  36. package/dist/core/activity/SqliteActivityTable.js.map +1 -0
  37. package/dist/core/activity/index.d.ts +7 -0
  38. package/dist/core/activity/index.d.ts.map +1 -0
  39. package/dist/core/activity/index.js +37 -0
  40. package/dist/core/activity/index.js.map +1 -0
  41. package/dist/core/activity/mindoodbActivitySource.d.ts +17 -0
  42. package/dist/core/activity/mindoodbActivitySource.d.ts.map +1 -0
  43. package/dist/core/activity/mindoodbActivitySource.js +44 -0
  44. package/dist/core/activity/mindoodbActivitySource.js.map +1 -0
  45. package/dist/core/activity/summaryRuleClassifier.d.ts +57 -0
  46. package/dist/core/activity/summaryRuleClassifier.d.ts.map +1 -0
  47. package/dist/core/activity/summaryRuleClassifier.js +157 -0
  48. package/dist/core/activity/summaryRuleClassifier.js.map +1 -0
  49. package/dist/core/activity/types.d.ts +221 -0
  50. package/dist/core/activity/types.d.ts.map +1 -0
  51. package/dist/core/activity/types.js +37 -0
  52. package/dist/core/activity/types.js.map +1 -0
  53. package/dist/core/appendonlystores/network/AuthenticationService.d.ts +20 -0
  54. package/dist/core/appendonlystores/network/AuthenticationService.d.ts.map +1 -1
  55. package/dist/core/appendonlystores/network/AuthenticationService.js +47 -6
  56. package/dist/core/appendonlystores/network/AuthenticationService.js.map +1 -1
  57. package/dist/core/appendonlystores/network/NetworkTransport.d.ts +6 -1
  58. package/dist/core/appendonlystores/network/NetworkTransport.d.ts.map +1 -1
  59. package/dist/core/appendonlystores/network/types.d.ts +14 -0
  60. package/dist/core/appendonlystores/network/types.d.ts.map +1 -1
  61. package/dist/core/appendonlystores/network/types.js.map +1 -1
  62. package/dist/core/builtinDbInvariants.d.ts +4 -1
  63. package/dist/core/builtinDbInvariants.d.ts.map +1 -1
  64. package/dist/core/builtinDbInvariants.js +4 -1
  65. package/dist/core/builtinDbInvariants.js.map +1 -1
  66. package/dist/core/guestAdmissions.d.ts +133 -0
  67. package/dist/core/guestAdmissions.d.ts.map +1 -0
  68. package/dist/core/guestAdmissions.js +207 -0
  69. package/dist/core/guestAdmissions.js.map +1 -0
  70. package/dist/core/guestTickets.d.ts +25 -6
  71. package/dist/core/guestTickets.d.ts.map +1 -1
  72. package/dist/core/guestTickets.js +56 -21
  73. package/dist/core/guestTickets.js.map +1 -1
  74. package/dist/core/index.d.ts +4 -0
  75. package/dist/core/index.d.ts.map +1 -1
  76. package/dist/core/index.js +23 -1
  77. package/dist/core/index.js.map +1 -1
  78. package/dist/core/live/LiveSubChannel.d.ts +91 -0
  79. package/dist/core/live/LiveSubChannel.d.ts.map +1 -0
  80. package/dist/core/live/LiveSubChannel.js +222 -0
  81. package/dist/core/live/LiveSubChannel.js.map +1 -0
  82. package/dist/core/types.d.ts +35 -1
  83. package/dist/core/types.d.ts.map +1 -1
  84. package/dist/guest/guestCall.d.ts +148 -0
  85. package/dist/guest/guestCall.d.ts.map +1 -0
  86. package/dist/guest/guestCall.js +248 -0
  87. package/dist/guest/guestCall.js.map +1 -0
  88. package/dist/guest/guestChat.d.ts +79 -0
  89. package/dist/guest/guestChat.d.ts.map +1 -0
  90. package/dist/guest/guestChat.js +297 -0
  91. package/dist/guest/guestChat.js.map +1 -0
  92. package/dist/guest/guestLink.d.ts +25 -3
  93. package/dist/guest/guestLink.d.ts.map +1 -1
  94. package/dist/guest/guestLink.js +44 -2
  95. package/dist/guest/guestLink.js.map +1 -1
  96. package/dist/guest/index.d.ts +4 -1
  97. package/dist/guest/index.d.ts.map +1 -1
  98. package/dist/guest/index.js +17 -1
  99. package/dist/guest/index.js.map +1 -1
  100. package/dist/node/server/MindooDBServer.d.ts.map +1 -1
  101. package/dist/node/server/MindooDBServer.js +1 -1
  102. package/dist/node/server/MindooDBServer.js.map +1 -1
  103. package/dist/server/GuestAdmissionService.d.ts +34 -0
  104. package/dist/server/GuestAdmissionService.d.ts.map +1 -0
  105. package/dist/server/GuestAdmissionService.js +36 -0
  106. package/dist/server/GuestAdmissionService.js.map +1 -0
  107. package/dist/server/GuestTicketService.d.ts.map +1 -1
  108. package/dist/server/GuestTicketService.js +15 -9
  109. package/dist/server/GuestTicketService.js.map +1 -1
  110. package/dist/server/SyncEventBus.d.ts +8 -0
  111. package/dist/server/SyncEventBus.d.ts.map +1 -1
  112. package/dist/server/SyncEventBus.js.map +1 -1
  113. package/dist/server/TenantManager.d.ts +24 -0
  114. package/dist/server/TenantManager.d.ts.map +1 -1
  115. package/dist/server/TenantManager.js +40 -1
  116. package/dist/server/TenantManager.js.map +1 -1
  117. package/dist/server/http/MindooDBServerCore.d.ts +5 -0
  118. package/dist/server/http/MindooDBServerCore.d.ts.map +1 -1
  119. package/dist/server/http/MindooDBServerCore.js +123 -13
  120. package/dist/server/http/MindooDBServerCore.js.map +1 -1
  121. package/dist/server/http/types.d.ts +9 -0
  122. package/dist/server/http/types.d.ts.map +1 -1
  123. package/dist/server/http/types.js.map +1 -1
  124. package/package.json +1 -1
@@ -0,0 +1,248 @@
1
+ "use strict";
2
+ /**
3
+ * Guests in calls (docs/accesscontrol.md §6.15), the guest's side.
4
+ *
5
+ * 1. The guest's page makes its own key pair ({@link createGuestCallKeys}):
6
+ * Ed25519 to sign in later, RSA-OAEP so members can seal keys for it.
7
+ * Keep the private keys non-extractable (e.g. in IndexedDB); they never
8
+ * leave the browser.
9
+ * 2. It signs in with the knock ticket from the link
10
+ * (`GuestTicketSession.signIn`, the PIN may be empty) and knocks on the
11
+ * database's lobby ({@link GuestLiveChannel}, channel `lobby`). The knock
12
+ * payload is the page's own format, sealed to the room's waiting-room key
13
+ * with {@link sealForPublicKey}; it carries the guest's public keys.
14
+ * 3. A member answers on the lobby, addressed to the guest's stream. If the
15
+ * answer admits them, the guest signs in again with its own key
16
+ * ({@link signInAdmittedGuest}) and uses the call's channel `call:<id>`.
17
+ *
18
+ * The server sees who knocks where and when, never the payloads.
19
+ */
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.GuestLiveChannel = exports.GuestCallSignInError = void 0;
22
+ exports.createGuestCallKeys = createGuestCallKeys;
23
+ exports.sealForPublicKey = sealForPublicKey;
24
+ exports.openSealedForKey = openSealedForKey;
25
+ exports.signAsGuest = signAsGuest;
26
+ exports.verifyGuestSignature = verifyGuestSignature;
27
+ exports.signInAdmittedGuest = signInAdmittedGuest;
28
+ exports.requestGuestCallToken = requestGuestCallToken;
29
+ const AuthChallenge_1 = require("../core/crypto/AuthChallenge");
30
+ const HttpTransport_1 = require("../appendonlystores/network/HttpTransport");
31
+ const LiveSubChannel_1 = require("../core/live/LiveSubChannel");
32
+ const types_1 = require("../core/types");
33
+ function toBase64(bytes) {
34
+ let binary = "";
35
+ for (let i = 0; i < bytes.length; i++)
36
+ binary += String.fromCharCode(bytes[i]);
37
+ return btoa(binary);
38
+ }
39
+ function fromBase64(value) {
40
+ const binary = atob(value);
41
+ const out = new Uint8Array(binary.length);
42
+ for (let i = 0; i < binary.length; i++)
43
+ out[i] = binary.charCodeAt(i);
44
+ return out;
45
+ }
46
+ function pem(der) {
47
+ const lines = toBase64(der).match(/.{1,64}/g) ?? [];
48
+ return `-----BEGIN PUBLIC KEY-----\n${lines.join("\n")}\n-----END PUBLIC KEY-----`;
49
+ }
50
+ function pemToDer(value) {
51
+ return fromBase64(value.replace(/-----[^-]+-----/g, "").replace(/\s+/g, ""));
52
+ }
53
+ function buffer(bytes) {
54
+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
55
+ }
56
+ /**
57
+ * Make the guest's keys. Private keys are not extractable unless asked: store
58
+ * the CryptoKey objects themselves (IndexedDB can hold them) to come back
59
+ * after a reload without knocking again.
60
+ */
61
+ async function createGuestCallKeys(cryptoAdapter, options) {
62
+ const subtle = cryptoAdapter.getSubtle();
63
+ const extractable = options?.extractable === true;
64
+ const signing = (await subtle.generateKey({ name: "Ed25519" }, extractable, ["sign", "verify"]));
65
+ const encryption = (await subtle.generateKey({ name: "RSA-OAEP", modulusLength: 3072, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" }, extractable, ["encrypt", "decrypt", "wrapKey", "unwrapKey"]));
66
+ return {
67
+ signingKey: signing.privateKey,
68
+ signingPublicKey: pem(new Uint8Array(await subtle.exportKey("spki", signing.publicKey))),
69
+ decryptionKey: encryption.privateKey,
70
+ encryptionPublicKey: pem(new Uint8Array(await subtle.exportKey("spki", encryption.publicKey))),
71
+ };
72
+ }
73
+ /** Seal `plaintext` for the holder of the RSA-OAEP private key of `publicKeyPem`. */
74
+ async function sealForPublicKey(cryptoAdapter, publicKeyPem, plaintext) {
75
+ const subtle = cryptoAdapter.getSubtle();
76
+ const publicKey = await subtle.importKey("spki", buffer(pemToDer(publicKeyPem)), { name: "RSA-OAEP", hash: "SHA-256" }, false, [
77
+ "encrypt",
78
+ ]);
79
+ const raw = cryptoAdapter.getRandomValues(new Uint8Array(32));
80
+ const iv = cryptoAdapter.getRandomValues(new Uint8Array(12));
81
+ const aes = await subtle.importKey("raw", buffer(raw), { name: "AES-GCM" }, false, ["encrypt"]);
82
+ const c = new Uint8Array(await subtle.encrypt({ name: "AES-GCM", iv: buffer(iv) }, aes, buffer(plaintext)));
83
+ const k = new Uint8Array(await subtle.encrypt({ name: "RSA-OAEP" }, publicKey, buffer(raw)));
84
+ raw.fill(0);
85
+ return { v: 1, k: toBase64(k), iv: toBase64(iv), c: toBase64(c) };
86
+ }
87
+ /** Open a {@link SealedForKey} with the RSA-OAEP private key it was sealed for. */
88
+ async function openSealedForKey(cryptoAdapter, privateKey, sealed) {
89
+ if (!sealed || sealed.v !== 1)
90
+ throw new Error("sealed message: unknown format");
91
+ const subtle = cryptoAdapter.getSubtle();
92
+ const raw = new Uint8Array(await subtle.decrypt({ name: "RSA-OAEP" }, privateKey, buffer(fromBase64(sealed.k))));
93
+ const aes = await subtle.importKey("raw", buffer(raw), { name: "AES-GCM" }, false, ["decrypt"]);
94
+ raw.fill(0);
95
+ return new Uint8Array(await subtle.decrypt({ name: "AES-GCM", iv: buffer(fromBase64(sealed.iv)) }, aes, buffer(fromBase64(sealed.c))));
96
+ }
97
+ /** Sign `bytes` with the guest's key (members check knocks against the key in them). */
98
+ async function signAsGuest(cryptoAdapter, keys, bytes) {
99
+ return new Uint8Array(await cryptoAdapter.getSubtle().sign({ name: "Ed25519" }, keys.signingKey, buffer(bytes)));
100
+ }
101
+ /** Check a signature of a guest key (SPKI PEM, Ed25519). */
102
+ async function verifyGuestSignature(cryptoAdapter, signingPublicKeyPem, bytes, signature) {
103
+ const subtle = cryptoAdapter.getSubtle();
104
+ const key = await subtle.importKey("spki", buffer(pemToDer(signingPublicKeyPem)), { name: "Ed25519" }, false, ["verify"]);
105
+ return subtle.verify({ name: "Ed25519" }, key, buffer(signature), buffer(bytes));
106
+ }
107
+ /** Thrown when the server does not (or no longer) let the guest's key in. */
108
+ class GuestCallSignInError extends Error {
109
+ constructor(message) {
110
+ super(message);
111
+ this.name = "GuestCallSignInError";
112
+ }
113
+ }
114
+ exports.GuestCallSignInError = GuestCallSignInError;
115
+ /**
116
+ * Sign in with the guest's own key once a member admitted it. The token
117
+ * opens no documents; it carries the call channels of the admission's
118
+ * database. It stops working when the admission ends.
119
+ */
120
+ async function signInAdmittedGuest(options) {
121
+ const doFetch = options.fetchImpl ?? fetch;
122
+ const base = `${options.serverUrl.replace(/\/+$/, "")}/${options.tenantId}`;
123
+ const post = async (path, body) => {
124
+ const response = await doFetch(`${base}${path}`, {
125
+ method: "POST",
126
+ headers: { "Content-Type": "application/json" },
127
+ body: JSON.stringify(body),
128
+ });
129
+ return { status: response.status, data: (await response.json().catch(() => ({}))) };
130
+ };
131
+ const challenge = await post("/auth/challenge", { signingPublicKey: options.keys.signingPublicKey });
132
+ if (challenge.status !== 200 || typeof challenge.data.challenge !== "string") {
133
+ throw new GuestCallSignInError(String(challenge.data.error ?? `challenge failed (${challenge.status})`));
134
+ }
135
+ const signature = await signAsGuest(options.cryptoAdapter, options.keys, (0, AuthChallenge_1.authChallengeSigningBytes)(challenge.data.challenge));
136
+ const auth = await post("/auth/authenticate", { challenge: challenge.data.challenge, signature: toBase64(signature) });
137
+ if (auth.data.success !== true || typeof auth.data.token !== "string") {
138
+ throw new GuestCallSignInError(String(auth.data.error ?? "sign-in failed"));
139
+ }
140
+ let admissionId = "";
141
+ try {
142
+ const payload = JSON.parse(atob(auth.data.token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/")));
143
+ admissionId = payload.guestAdmissionId ?? "";
144
+ }
145
+ catch {
146
+ // Opaque token: fine, the caller knows the admission from the member's answer.
147
+ }
148
+ return { token: auth.data.token, admissionId };
149
+ }
150
+ /**
151
+ * The live channel of one database as a guest uses it: listen on the
152
+ * sub-channels its token allows (none for a knock ticket, which hears only
153
+ * answers addressed to it) and publish there.
154
+ */
155
+ class GuestLiveChannel {
156
+ constructor(options) {
157
+ this.options = options;
158
+ this.clientId = Array.from(options.cryptoAdapter.getRandomValues(new Uint8Array(12)), (byte) => byte.toString(16).padStart(2, "0")).join("");
159
+ this.transport = new HttpTransport_1.HttpTransport({
160
+ baseUrl: `${options.serverUrl.replace(/\/+$/, "")}/${options.tenantId}`,
161
+ tenantId: options.tenantId,
162
+ dbId: options.dbId,
163
+ storeKind: types_1.StoreKind.docs,
164
+ });
165
+ }
166
+ /**
167
+ * Listen until `signal` aborts or the server ends the stream (resolves) or
168
+ * refuses it (rejects, e.g. after the admission ended). `onOpen` fires once
169
+ * the server has subscribed the stream.
170
+ */
171
+ async listen(onMessage, options) {
172
+ await this.transport.subscribeToChanges(await this.options.token(), () => undefined, {
173
+ ...(options?.signal ? { signal: options.signal } : {}),
174
+ ...(options?.onOpen ? { onOpen: options.onOpen } : {}),
175
+ live: { clientId: this.clientId, onLive: onMessage, ...(options?.channels?.length ? { channels: options.channels } : {}) },
176
+ });
177
+ }
178
+ /**
179
+ * Publish the app's bytes (already sealed by the caller) on `channel`,
180
+ * optionally to one stream. With `keys` the bytes go in a signed envelope
181
+ * (what members' Haven checks, `openLiveSubChannel`); without, they go as
182
+ * they are (tests of the transport).
183
+ */
184
+ async publish(payload, options) {
185
+ let wire = payload;
186
+ if (this.options.keys) {
187
+ const at = Date.now();
188
+ const signature = await signAsGuest(this.options.cryptoAdapter, this.options.keys, (0, LiveSubChannel_1.liveSubSigningBytes)(this.options.dbId, options.channel, at, payload));
189
+ const envelope = { v: 1, k: this.options.keys.signingPublicKey, s: toBase64(signature), at, p: toBase64(payload) };
190
+ wire = (0, LiveSubChannel_1.encodeLiveSubEnvelope)(envelope);
191
+ }
192
+ await this.transport.publishLive(await this.options.token(), toBase64(wire), this.clientId, options);
193
+ }
194
+ /**
195
+ * Open a signed message received here: checks the signature over database,
196
+ * channel, time and payload and the age. Returns the signer's key (compare
197
+ * it with the keys the member who let you in named) or null.
198
+ */
199
+ async open(event) {
200
+ if (event.dbId !== this.options.dbId || !event.channel)
201
+ return null;
202
+ const envelope = (0, LiveSubChannel_1.decodeLiveSubEnvelope)(event.payload);
203
+ if (!envelope || Math.abs(Date.now() - envelope.at) > LiveSubChannel_1.LIVE_SUB_MAX_AGE_MS)
204
+ return null;
205
+ const payload = fromBase64(envelope.p);
206
+ const ok = await verifyGuestSignature(this.options.cryptoAdapter, envelope.k, (0, LiveSubChannel_1.liveSubSigningBytes)(this.options.dbId, event.channel, envelope.at, payload), fromBase64(envelope.s)).catch(() => false);
207
+ return ok ? { signingKey: envelope.k, payload, sentAt: envelope.at } : null;
208
+ }
209
+ }
210
+ exports.GuestLiveChannel = GuestLiveChannel;
211
+ /**
212
+ * Ask the tenant's media gateway for a LiveKit token, as an admitted guest:
213
+ * a challenge, signed with the guest's own key over tenant, database and
214
+ * call (mindoo-media-gateway `/guest/*`).
215
+ */
216
+ async function requestGuestCallToken(options) {
217
+ const doFetch = options.fetchImpl ?? fetch;
218
+ const base = options.gatewayUrl.replace(/\/+$/, "");
219
+ const post = async (path, body) => {
220
+ const response = await doFetch(`${base}${path}`, {
221
+ method: "POST",
222
+ headers: { "Content-Type": "application/json" },
223
+ body: JSON.stringify(body),
224
+ });
225
+ const data = (await response.json().catch(() => ({})));
226
+ if (!response.ok)
227
+ throw new GuestCallSignInError(String(data.detail ?? `media gateway refused (${response.status})`));
228
+ return data;
229
+ };
230
+ const { challenge } = (await post("/guest/challenge", {
231
+ tenantId: options.tenantId,
232
+ signingPublicKey: options.keys.signingPublicKey,
233
+ }));
234
+ if (typeof challenge !== "string")
235
+ throw new GuestCallSignInError("media gateway: no challenge");
236
+ const text = `mindoo-media-gateway/guest-call-token/v1\n${challenge}\n${options.tenantId}\n${options.dbId}\n${options.callId}`;
237
+ const signature = await signAsGuest(options.cryptoAdapter, options.keys, new TextEncoder().encode(text));
238
+ const answer = await post("/guest/call/token", {
239
+ tenantId: options.tenantId,
240
+ databaseId: options.dbId,
241
+ callId: options.callId,
242
+ signingPublicKey: options.keys.signingPublicKey,
243
+ challenge,
244
+ signature: toBase64(signature),
245
+ });
246
+ return answer;
247
+ }
248
+ //# sourceMappingURL=guestCall.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guestCall.js","sourceRoot":"","sources":["../../src/guest/guestCall.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;GAiBG;;;AAwDH,kDAkBC;AAcD,4CAgBC;AAGD,4CAaC;AAGD,kCAEC;AAGD,oDASC;AAeD,kDAoCC;AA0GD,sDAqCC;AAxUD,gEAAyE;AAEzE,6EAA0E;AAC1E,gEAMqC;AACrC,yCAA0C;AAE1C,SAAS,QAAQ,CAAC,KAAiB;IACjC,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,KAAK,IAAI,CAAC,GAAG,CAAC,EA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AI;QACxB,MAAM,EAAE,OAAO,CAAC,MAAM;QACtB,gBAAgB,EAAE,OAAO,CAAC,IAAI,CAAC,gBAAgB;QAC/C,SAAS;QACT,SAAS,EAAE,QAAQ,CAAC,SAAS,CAAC;KAC/B,CAAC,CAAC;IACH,OAAO,MAAmC,CAAC;AAC7C,CAAC"}
@@ -0,0 +1,79 @@
1
+ /**
2
+ * A guest in a meeting's chat (docs/accesscontrol.md §6.15, "chat from
3
+ * admission"), without a tenant.
4
+ *
5
+ * A member admitted the guest's own keys with chat rights and added the
6
+ * guest's RSA key as a reader of the chat's group document, without the
7
+ * earlier history. The server serves the guest only that group document and
8
+ * the chat's documents it witnessed from the admission on, and accepts from
9
+ * the guest only creates and changes of documents under the guest's own
10
+ * prefix (which names the admission).
11
+ *
12
+ * Reading: the group document's recipient blocks hold the key series; the
13
+ * guest opens the generations wrapped to its key and decrypts the chat's
14
+ * entries (IV + AES-GCM, any generation) and replays them with Automerge.
15
+ * Writing: a document under the group's key series (`$sealed:<group>`), signed
16
+ * with the guest's key, the way BaseMindooDB builds one.
17
+ *
18
+ * Authenticity: the server checks every member's and guest's signature on
19
+ * push, and only holders of the group key produce entries that decrypt. The
20
+ * guest does not check member signatures itself (it holds no directory).
21
+ */
22
+ import type { CryptoAdapter } from "../core/crypto/CryptoAdapter";
23
+ import { type GuestCallKeys } from "./guestCall";
24
+ /** A document of the chat as the guest reads it. */
25
+ export interface GuestChatDocument {
26
+ docId: string;
27
+ /** Fields, atomic strings as plain strings. */
28
+ data: Record<string, unknown>;
29
+ /** Server time the document was created (ms). */
30
+ createdAt: number;
31
+ /** Written by this guest. */
32
+ mine: boolean;
33
+ deleted: boolean;
34
+ }
35
+ export declare class GuestChat {
36
+ private readonly options;
37
+ private readonly docsStore;
38
+ private readonly known;
39
+ private readonly docs;
40
+ /** Generations of the group's key series this guest holds, by epoch. */
41
+ private readonly generations;
42
+ private readonly aesKeys;
43
+ /** Entries no generation the guest holds opens; tried again when a new one arrives. */
44
+ private readonly unreadable;
45
+ constructor(options: {
46
+ serverUrl: string;
47
+ tenantId: string;
48
+ dbId: string;
49
+ /** The chat's group document (the admission names it). */
50
+ groupDocId: string;
51
+ /** The guest's own prefix for documents it writes (the admission names it). */
52
+ writePrefix?: string;
53
+ keys: GuestCallKeys;
54
+ /** The admitted guest's token (`signInAdmittedGuest`); called before each request. */
55
+ token: () => string | Promise<string>;
56
+ cryptoAdapter: CryptoAdapter;
57
+ });
58
+ /** Whether the guest holds a key of the chat yet (a member added it as a reader). */
59
+ get canRead(): boolean;
60
+ /** Fetch what is new and return every document the guest can read, oldest first. */
61
+ refresh(): Promise<GuestChatDocument[]>;
62
+ private ingestKeys;
63
+ private aesKey;
64
+ private decrypt;
65
+ /** Applies one entry; false when it cannot be read (yet). */
66
+ private apply;
67
+ private sign;
68
+ /** The store entry for one local Automerge change of `docId`. */
69
+ private entryFor;
70
+ private push;
71
+ /**
72
+ * Write a new document under the guest's prefix (`<writePrefix><suffix>`),
73
+ * strings as atomic values. Needs `chatWrite` and a key of the chat.
74
+ */
75
+ create(suffix: string, fields: Record<string, unknown>): Promise<string>;
76
+ /** Change fields of one of the guest's own documents. */
77
+ update(docId: string, fields: Record<string, unknown>): Promise<void>;
78
+ }
79
+ //# sourceMappingURL=guestChat.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guestChat.d.ts","sourceRoot":"","sources":["../../src/guest/guestChat.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAGH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAQlE,OAAO,EAAe,KAAK,aAAa,EAAE,MAAM,aAAa,CAAC;AAE9D,oDAAoD;AACpD,MAAM,WAAW,iBAAiB;IAChC,KAAK,EAAE,MAAM,CAAC;IACd,+CAA+C;IAC/C,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC9B,iDAAiD;IACjD,SAAS,EAAE,MAAM,CAAC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AAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;CAkB5E"}
@@ -0,0 +1,297 @@
1
+ "use strict";
2
+ /**
3
+ * A guest in a meeting's chat (docs/accesscontrol.md §6.15, "chat from
4
+ * admission"), without a tenant.
5
+ *
6
+ * A member admitted the guest's own keys with chat rights and added the
7
+ * guest's RSA key as a reader of the chat's group document, without the
8
+ * earlier history. The server serves the guest only that group document and
9
+ * the chat's documents it witnessed from the admission on, and accepts from
10
+ * the guest only creates and changes of documents under the guest's own
11
+ * prefix (which names the admission).
12
+ *
13
+ * Reading: the group document's recipient blocks hold the key series; the
14
+ * guest opens the generations wrapped to its key and decrypts the chat's
15
+ * entries (IV + AES-GCM, any generation) and replays them with Automerge.
16
+ * Writing: a document under the group's key series (`$sealed:<group>`), signed
17
+ * with the guest's key, the way BaseMindooDB builds one.
18
+ *
19
+ * Authenticity: the server checks every member's and guest's signature on
20
+ * push, and only holders of the group key produce entries that decrypt. The
21
+ * guest does not check member signatures itself (it holds no directory).
22
+ */
23
+ Object.defineProperty(exports, "__esModule", { value: true });
24
+ exports.GuestChat = void 0;
25
+ const automerge_adapter_1 = require("../core/automerge-adapter");
26
+ const EntrySignature_1 = require("../core/crypto/EntrySignature");
27
+ const types_1 = require("../core/types");
28
+ const sealedCrypto_1 = require("../core/userkeys/sealedCrypto");
29
+ const sealedTypes_1 = require("../core/userkeys/sealedTypes");
30
+ const idGeneration_1 = require("../core/utils/idGeneration");
31
+ const HttpTransport_1 = require("../appendonlystores/network/HttpTransport");
32
+ const ClientNetworkContentAddressedStore_1 = require("../appendonlystores/network/ClientNetworkContentAddressedStore");
33
+ const guestCall_1 = require("./guestCall");
34
+ const atomic = (value) => new (automerge_adapter_1.Automerge.ImmutableString)(value);
35
+ function hydrate(value) {
36
+ if (typeof value === "string")
37
+ return atomic(value);
38
+ if (Array.isArray(value))
39
+ return Array.from(value, hydrate);
40
+ if (value && typeof value === "object" && !(value instanceof Uint8Array) && !(value instanceof Date)) {
41
+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, hydrate(entry)]));
42
+ }
43
+ return value;
44
+ }
45
+ function plain(value) {
46
+ if (value === null || typeof value !== "object")
47
+ return value;
48
+ if (value instanceof Uint8Array || value instanceof Date)
49
+ return value;
50
+ const immutable = automerge_adapter_1.Automerge.ImmutableString;
51
+ if (immutable && value instanceof immutable)
52
+ return String(value);
53
+ if (Array.isArray(value))
54
+ return value.map(plain);
55
+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, plain(entry)]));
56
+ }
57
+ function sameKey(a, b) {
58
+ const body = (pem) => pem.replace(/-----[^-]+-----/g, "").replace(/\s+/g, "");
59
+ return body(a) === body(b);
60
+ }
61
+ class GuestChat {
62
+ constructor(options) {
63
+ this.options = options;
64
+ this.known = new Set();
65
+ this.docs = new Map();
66
+ /** Generations of the group's key series this guest holds, by epoch. */
67
+ this.generations = new Map();
68
+ this.aesKeys = new Map();
69
+ /** Entries no generation the guest holds opens; tried again when a new one arrives. */
70
+ this.unreadable = new Map();
71
+ const transport = new HttpTransport_1.HttpTransport({
72
+ baseUrl: `${options.serverUrl.replace(/\/+$/, "")}/${options.tenantId}`,
73
+ tenantId: options.tenantId,
74
+ dbId: options.dbId,
75
+ storeKind: types_1.StoreKind.docs,
76
+ });
77
+ this.docsStore = new ClientNetworkContentAddressedStore_1.ClientNetworkContentAddressedStore(options.dbId, types_1.StoreKind.docs, transport, options.cryptoAdapter, "$guest", options.keys.signingKey, options.keys.decryptionKey, undefined, options.keys.signingPublicKey);
78
+ this.docsStore.setExternalTokenProvider(async () => options.token());
79
+ }
80
+ /** Whether the guest holds a key of the chat yet (a member added it as a reader). */
81
+ get canRead() {
82
+ return this.generations.size > 0;
83
+ }
84
+ /** Fetch what is new and return every document the guest can read, oldest first. */
85
+ async refresh() {
86
+ const metas = await this.docsStore.findNewEntries([...this.known, ...this.unreadable.keys()]);
87
+ const generationsBefore = this.generations.size;
88
+ const entries = metas.length > 0 ? await this.docsStore.getEntries(metas.map((meta) => meta.id)) : [];
89
+ // Keys first: the group document's recipient blocks.
90
+ for (const entry of entries) {
91
+ if (entry.docId === this.options.groupDocId && entry.recipients)
92
+ await this.ingestKeys(entry.recipients);
93
+ }
94
+ // A new generation may open what could not be read before.
95
+ const retry = this.generations.size > generationsBefore ? [...this.unreadable.values()] : [];
96
+ const ordered = [...retry, ...entries].sort((a, b) => (a.receivedAt ?? a.createdAt) - (b.receivedAt ?? b.createdAt));
97
+ for (const entry of ordered) {
98
+ if (await this.apply(entry)) {
99
+ this.known.add(entry.id);
100
+ this.unreadable.delete(entry.id);
101
+ }
102
+ else {
103
+ this.unreadable.set(entry.id, entry);
104
+ }
105
+ }
106
+ return [...this.docs.entries()]
107
+ .filter(([docId, state]) => docId !== this.options.groupDocId && state.hasBase)
108
+ .map(([docId, state]) => ({
109
+ docId,
110
+ data: plain(state.doc),
111
+ createdAt: state.createdAt,
112
+ mine: sameKey(state.createdBy, this.options.keys.signingPublicKey),
113
+ deleted: state.deleted,
114
+ }))
115
+ .sort((a, b) => a.createdAt - b.createdAt);
116
+ }
117
+ async ingestKeys(recipients) {
118
+ try {
119
+ const range = await (0, sealedCrypto_1.openBundleRange)({ crypto: this.options.cryptoAdapter, recipients, privateKey: this.options.keys.decryptionKey });
120
+ for (const { epoch, key } of range)
121
+ this.generations.set(epoch, key);
122
+ }
123
+ catch {
124
+ // A block from before the guest was a reader: nothing for it.
125
+ }
126
+ }
127
+ async aesKey(epoch) {
128
+ let key = this.aesKeys.get(epoch);
129
+ if (!key) {
130
+ key = await this.options.cryptoAdapter
131
+ .getSubtle()
132
+ .importKey("raw", this.generations.get(epoch), { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
133
+ this.aesKeys.set(epoch, key);
134
+ }
135
+ return key;
136
+ }
137
+ async decrypt(payload) {
138
+ const subtle = this.options.cryptoAdapter.getSubtle();
139
+ const epochs = [...this.generations.keys()].sort((a, b) => b - a);
140
+ for (const epoch of epochs) {
141
+ try {
142
+ return new Uint8Array(await subtle.decrypt({ name: "AES-GCM", iv: payload.slice(0, 12), tagLength: 128 }, await this.aesKey(epoch), payload.slice(12)));
143
+ }
144
+ catch {
145
+ // another generation
146
+ }
147
+ }
148
+ return null;
149
+ }
150
+ /** Applies one entry; false when it cannot be read (yet). */
151
+ async apply(entry) {
152
+ if (entry.entryType === "attachment_chunk")
153
+ return true;
154
+ const state = this.docs.get(entry.docId) ??
155
+ {
156
+ doc: automerge_adapter_1.Automerge.init(),
157
+ entryByHash: new Map(),
158
+ createdAt: entry.receivedAt ?? entry.createdAt,
159
+ createdBy: entry.createdByPublicKey,
160
+ deleted: false,
161
+ applied: new Set(),
162
+ hasBase: false,
163
+ };
164
+ if (state.applied.has(entry.id))
165
+ return true;
166
+ if (entry.entryType === "doc_delete") {
167
+ state.deleted = true;
168
+ }
169
+ else if (entry.entryType === "doc_undelete") {
170
+ state.deleted = false;
171
+ }
172
+ else if (entry.entryType === "doc_create" || entry.entryType === "doc_change" || entry.entryType === "doc_snapshot") {
173
+ const bytes = await this.decrypt(entry.encryptedData);
174
+ if (!bytes)
175
+ return false;
176
+ if (entry.entryType === "doc_snapshot") {
177
+ state.doc = automerge_adapter_1.Automerge.merge(state.doc, automerge_adapter_1.Automerge.load(bytes));
178
+ }
179
+ else {
180
+ const decoded = automerge_adapter_1.Automerge.decodeChange(bytes);
181
+ if (decoded.hash)
182
+ state.entryByHash.set(decoded.hash, entry.id);
183
+ [state.doc] = automerge_adapter_1.Automerge.applyChanges(state.doc, [bytes]);
184
+ }
185
+ if (entry.entryType === "doc_create") {
186
+ state.createdAt = entry.receivedAt ?? entry.createdAt;
187
+ state.createdBy = entry.createdByPublicKey;
188
+ }
189
+ if (entry.entryType !== "doc_change")
190
+ state.hasBase = true;
191
+ }
192
+ else {
193
+ return true;
194
+ }
195
+ state.applied.add(entry.id);
196
+ this.docs.set(entry.docId, state);
197
+ return true;
198
+ }
199
+ async sign(bytes) {
200
+ return (0, guestCall_1.signAsGuest)(this.options.cryptoAdapter, this.options.keys, bytes);
201
+ }
202
+ /** The store entry for one local Automerge change of `docId`. */
203
+ async entryFor(docId, state, changeBytes, entryType) {
204
+ const crypto = this.options.cryptoAdapter;
205
+ const subtle = crypto.getSubtle();
206
+ const epoch = Math.max(...this.generations.keys());
207
+ const iv = crypto.getRandomValues(new Uint8Array(12));
208
+ const ct = new Uint8Array(await subtle.encrypt({ name: "AES-GCM", iv: iv, tagLength: 128 }, await this.aesKey(epoch), changeBytes));
209
+ const encryptedData = new Uint8Array(12 + ct.length);
210
+ encryptedData.set(iv, 0);
211
+ encryptedData.set(ct, 12);
212
+ const decoded = automerge_adapter_1.Automerge.decodeChange(changeBytes);
213
+ const deps = decoded.deps ?? [];
214
+ const meta = {
215
+ entryType,
216
+ id: await (0, idGeneration_1.generateDocEntryId)(docId, decoded.hash, deps, subtle),
217
+ contentHash: await (0, idGeneration_1.computeContentHash)(encryptedData, subtle),
218
+ docId,
219
+ dependencyIds: deps.map((hash) => state.entryByHash.get(hash)).filter((id) => Boolean(id)),
220
+ createdAt: Date.now(),
221
+ createdByPublicKey: this.options.keys.signingPublicKey,
222
+ decryptionKeyId: (0, sealedTypes_1.sealedKeyId)(this.options.groupDocId),
223
+ signature: await this.sign(encryptedData),
224
+ originalSize: changeBytes.length,
225
+ encryptedSize: encryptedData.length,
226
+ entryVersion: types_1.CURRENT_STORE_ENTRY_VERSION,
227
+ };
228
+ meta.metadataSignature = await this.sign((0, EntrySignature_1.buildEntrySigningBytes)((0, EntrySignature_1.entrySignatureFieldsFromEntry)(meta)));
229
+ if (decoded.hash)
230
+ state.entryByHash.set(decoded.hash, meta.id);
231
+ return { ...meta, encryptedData };
232
+ }
233
+ async push(entry) {
234
+ const ack = await this.docsStore.putEntries([entry]);
235
+ if (ack.rejected.length > 0)
236
+ throw new Error(`guest chat: ${ack.rejected.map((item) => item.reason).join("; ")}`);
237
+ this.known.add(entry.id);
238
+ }
239
+ /**
240
+ * Write a new document under the guest's prefix (`<writePrefix><suffix>`),
241
+ * strings as atomic values. Needs `chatWrite` and a key of the chat.
242
+ */
243
+ async create(suffix, fields) {
244
+ if (!this.options.writePrefix)
245
+ throw new Error("guest chat: this guest may not write");
246
+ if (!this.canRead)
247
+ throw new Error("guest chat: no key of the chat yet");
248
+ if (!/^[a-z0-9_]{1,80}$/.test(suffix))
249
+ throw new Error("guest chat: invalid document id");
250
+ const docId = `${this.options.writePrefix}${suffix}`;
251
+ const doc = automerge_adapter_1.Automerge.change(automerge_adapter_1.Automerge.init(), (draft) => {
252
+ for (const [key, value] of Object.entries(fields))
253
+ draft[key] = hydrate(value);
254
+ });
255
+ const change = automerge_adapter_1.Automerge.getLastLocalChange(doc);
256
+ if (!change)
257
+ throw new Error("guest chat: nothing to write");
258
+ const state = {
259
+ doc,
260
+ entryByHash: new Map(),
261
+ createdAt: Date.now(),
262
+ createdBy: this.options.keys.signingPublicKey,
263
+ deleted: false,
264
+ applied: new Set(),
265
+ hasBase: true,
266
+ };
267
+ const entry = await this.entryFor(docId, state, change, "doc_create");
268
+ await this.push(entry);
269
+ state.applied.add(entry.id);
270
+ this.docs.set(docId, state);
271
+ return docId;
272
+ }
273
+ /** Change fields of one of the guest's own documents. */
274
+ async update(docId, fields) {
275
+ const state = this.docs.get(docId);
276
+ if (!state || !this.options.writePrefix || !docId.startsWith(this.options.writePrefix)) {
277
+ throw new Error("guest chat: only the guest's own documents can be changed");
278
+ }
279
+ const next = automerge_adapter_1.Automerge.change(state.doc, (draft) => {
280
+ for (const [key, value] of Object.entries(fields)) {
281
+ if (value === undefined)
282
+ delete draft[key];
283
+ else
284
+ draft[key] = hydrate(value);
285
+ }
286
+ });
287
+ const change = automerge_adapter_1.Automerge.getLastLocalChange(next);
288
+ if (!change)
289
+ return;
290
+ const entry = await this.entryFor(docId, state, change, "doc_change");
291
+ await this.push(entry);
292
+ state.doc = next;
293
+ state.applied.add(entry.id);
294
+ }
295
+ }
296
+ exports.GuestChat = GuestChat;
297
+ //# sourceMappingURL=guestChat.js.map