@abraca/dabra 2.102.0 → 2.103.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/abracadabra-provider.cjs +6673 -6543
- package/dist/abracadabra-provider.cjs.map +1 -1
- package/dist/esm/AbracadabraBaseProvider.js +558 -0
- package/dist/esm/AbracadabraBaseProvider.js.map +1 -0
- package/dist/esm/AbracadabraClient.js +1424 -0
- package/dist/esm/AbracadabraClient.js.map +1 -0
- package/dist/esm/AbracadabraProvider.js +547 -0
- package/dist/esm/AbracadabraProvider.js.map +1 -0
- package/dist/esm/AbracadabraWS.js +398 -0
- package/dist/esm/AbracadabraWS.js.map +1 -0
- package/dist/esm/BackgroundSyncManager.js +571 -0
- package/dist/esm/BackgroundSyncManager.js.map +1 -0
- package/dist/esm/BackgroundSyncPersistence.js +62 -0
- package/dist/esm/BackgroundSyncPersistence.js.map +1 -0
- package/dist/esm/ChatClient.js +176 -0
- package/dist/esm/ChatClient.js.map +1 -0
- package/dist/esm/CloseEvents.js +45 -0
- package/dist/esm/CloseEvents.js.map +1 -0
- package/dist/esm/ContentManager.js +153 -0
- package/dist/esm/ContentManager.js.map +1 -0
- package/dist/esm/CoverReconcile.js +124 -0
- package/dist/esm/CoverReconcile.js.map +1 -0
- package/dist/esm/CryptoIdentityKeystore.js +580 -0
- package/dist/esm/CryptoIdentityKeystore.js.map +1 -0
- package/dist/esm/DeviceRegistrationService.js +158 -0
- package/dist/esm/DeviceRegistrationService.js.map +1 -0
- package/dist/esm/DocConverters.js +1300 -0
- package/dist/esm/DocConverters.js.map +1 -0
- package/dist/esm/DocKeyManager.js +145 -0
- package/dist/esm/DocKeyManager.js.map +1 -0
- package/dist/esm/DocTypes.js +792 -0
- package/dist/esm/DocTypes.js.map +1 -0
- package/dist/esm/DocUtils.js +180 -0
- package/dist/esm/DocUtils.js.map +1 -0
- package/dist/esm/DocumentCache.js +131 -0
- package/dist/esm/DocumentCache.js.map +1 -0
- package/dist/esm/DocumentManager.js +240 -0
- package/dist/esm/DocumentManager.js.map +1 -0
- package/dist/esm/E2EAbracadabraProvider.js +273 -0
- package/dist/esm/E2EAbracadabraProvider.js.map +1 -0
- package/dist/esm/E2EOfflineStore.js +53 -0
- package/dist/esm/E2EOfflineStore.js.map +1 -0
- package/dist/esm/EncryptedChatClient.js +156 -0
- package/dist/esm/EncryptedChatClient.js.map +1 -0
- package/dist/esm/EncryptedY.js +115 -0
- package/dist/esm/EncryptedY.js.map +1 -0
- package/dist/esm/EventEmitter.js +40 -0
- package/dist/esm/EventEmitter.js.map +1 -0
- package/dist/esm/FileBlobStore.js +410 -0
- package/dist/esm/FileBlobStore.js.map +1 -0
- package/dist/esm/IdentityDoc.js +413 -0
- package/dist/esm/IdentityDoc.js.map +1 -0
- package/dist/esm/IncomingMessage.js +39 -0
- package/dist/esm/IncomingMessage.js.map +1 -0
- package/dist/esm/LifecycleGate.js +124 -0
- package/dist/esm/LifecycleGate.js.map +1 -0
- package/dist/esm/MessageReceiver.js +86 -0
- package/dist/esm/MessageReceiver.js.map +1 -0
- package/dist/esm/MessageSender.js +19 -0
- package/dist/esm/MessageSender.js.map +1 -0
- package/dist/esm/MetaManager.js +112 -0
- package/dist/esm/MetaManager.js.map +1 -0
- package/dist/esm/MnemonicKeyDerivation.js +137 -0
- package/dist/esm/MnemonicKeyDerivation.js.map +1 -0
- package/dist/esm/NodeConnect.js +63 -0
- package/dist/esm/NodeConnect.js.map +1 -0
- package/dist/esm/NodeIdentity.js +212 -0
- package/dist/esm/NodeIdentity.js.map +1 -0
- package/dist/esm/NotificationsClient.js +136 -0
- package/dist/esm/NotificationsClient.js.map +1 -0
- package/dist/esm/OfflineStore.js +291 -0
- package/dist/esm/OfflineStore.js.map +1 -0
- package/dist/esm/OutgoingMessage.js +18 -0
- package/dist/esm/OutgoingMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/AuthenticationMessage.js +24 -0
- package/dist/esm/OutgoingMessages/AuthenticationMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/AwarenessMessage.js +28 -0
- package/dist/esm/OutgoingMessages/AwarenessMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/CloseMessage.js +21 -0
- package/dist/esm/OutgoingMessages/CloseMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/QueryAwarenessMessage.js +21 -0
- package/dist/esm/OutgoingMessages/QueryAwarenessMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/StatelessMessage.js +22 -0
- package/dist/esm/OutgoingMessages/StatelessMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/SubdocMessage.js +34 -0
- package/dist/esm/OutgoingMessages/SubdocMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/SyncStepOneMessage.js +24 -0
- package/dist/esm/OutgoingMessages/SyncStepOneMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/UpdateMessage.js +23 -0
- package/dist/esm/OutgoingMessages/UpdateMessage.js.map +1 -0
- package/dist/esm/PerfCounters.js +336 -0
- package/dist/esm/PerfCounters.js.map +1 -0
- package/dist/esm/QueryClient.js +117 -0
- package/dist/esm/QueryClient.js.map +1 -0
- package/dist/esm/RpcClient.js +456 -0
- package/dist/esm/RpcClient.js.map +1 -0
- package/dist/esm/SchemaTypes.js +38 -0
- package/dist/esm/SchemaTypes.js.map +1 -0
- package/dist/esm/SearchIndex.js +167 -0
- package/dist/esm/SearchIndex.js.map +1 -0
- package/dist/esm/ServerRegistry.js +139 -0
- package/dist/esm/ServerRegistry.js.map +1 -0
- package/dist/esm/ServerReset.js +170 -0
- package/dist/esm/ServerReset.js.map +1 -0
- package/dist/esm/TokenManager.js +236 -0
- package/dist/esm/TokenManager.js.map +1 -0
- package/dist/esm/TreeManager.js +655 -0
- package/dist/esm/TreeManager.js.map +1 -0
- package/dist/esm/TreeTimestamps.js +61 -0
- package/dist/esm/TreeTimestamps.js.map +1 -0
- package/dist/esm/auth.js +43 -0
- package/dist/esm/auth.js.map +1 -0
- package/dist/esm/awarenessStatesToArray.js +13 -0
- package/dist/esm/awarenessStatesToArray.js.map +1 -0
- package/dist/esm/docIds.js +53 -0
- package/dist/esm/docIds.js.map +1 -0
- package/dist/esm/encryptedContent.js +21 -0
- package/dist/esm/encryptedContent.js.map +1 -0
- package/dist/esm/index.js +61 -0
- package/dist/esm/messageRecord.js +64 -0
- package/dist/esm/messageRecord.js.map +1 -0
- package/dist/esm/sync/BroadcastChannelSync.js +160 -0
- package/dist/esm/sync/BroadcastChannelSync.js.map +1 -0
- package/dist/esm/types.js +54 -0
- package/dist/esm/types.js.map +1 -0
- package/dist/esm/webrtc/AbracadabraWebRTC.js +483 -0
- package/dist/esm/webrtc/AbracadabraWebRTC.js.map +1 -0
- package/dist/esm/webrtc/DataChannelRouter.js +124 -0
- package/dist/esm/webrtc/DataChannelRouter.js.map +1 -0
- package/dist/esm/webrtc/DevicePairingChannel.js +335 -0
- package/dist/esm/webrtc/DevicePairingChannel.js.map +1 -0
- package/dist/esm/webrtc/E2EEChannel.js +137 -0
- package/dist/esm/webrtc/E2EEChannel.js.map +1 -0
- package/dist/esm/webrtc/FileTransferChannel.js +250 -0
- package/dist/esm/webrtc/FileTransferChannel.js.map +1 -0
- package/dist/esm/webrtc/ManualSignaling.js +161 -0
- package/dist/esm/webrtc/ManualSignaling.js.map +1 -0
- package/dist/esm/webrtc/PeerConnection.js +96 -0
- package/dist/esm/webrtc/PeerConnection.js.map +1 -0
- package/dist/esm/webrtc/SignalingSocket.js +274 -0
- package/dist/esm/webrtc/SignalingSocket.js.map +1 -0
- package/dist/esm/webrtc/YjsDataChannel.js +135 -0
- package/dist/esm/webrtc/YjsDataChannel.js.map +1 -0
- package/dist/esm/webrtc/types.js +29 -0
- package/dist/esm/webrtc/types.js.map +1 -0
- package/dist/esm/x25519Convert.js +69 -0
- package/dist/esm/x25519Convert.js.map +1 -0
- package/dist/index.d.ts +26 -11
- package/package.json +6 -4
- package/dist/abracadabra-provider.esm.js +0 -14860
- package/dist/abracadabra-provider.esm.js.map +0 -1
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { decryptField, encryptField } from "./EncryptedY.js";
|
|
2
|
+
import { E2E_SENTINEL, isEncryptedContent } from "./encryptedContent.js";
|
|
3
|
+
|
|
4
|
+
//#region packages/provider/src/EncryptedChatClient.ts
|
|
5
|
+
/**
|
|
6
|
+
* EncryptedChatClient — `ChatClient` wrapper that transparently encrypts
|
|
7
|
+
* message content for channels in `e2e` mode and decrypts entries read
|
|
8
|
+
* back from the period doc's `messages` Y.Array.
|
|
9
|
+
*
|
|
10
|
+
* Threat model
|
|
11
|
+
* - Server cannot read message bodies (the `content` field is opaque
|
|
12
|
+
* ciphertext bytes, base64-encoded into the wire string).
|
|
13
|
+
* - Server CAN see `sender_id`, `channel_doc_id`, `period_id`, `ts`,
|
|
14
|
+
* `mentions[]` (kept cleartext for fan-out), `message_id`,
|
|
15
|
+
* and the `server_sig` it stamps. That envelope is the only thing
|
|
16
|
+
* the server inspects to do its job.
|
|
17
|
+
*
|
|
18
|
+
* Wire format
|
|
19
|
+
* `content` for an e2e message is the literal string
|
|
20
|
+
* `"e2e:1:<base64>"`
|
|
21
|
+
* where the decoded blob is `[nonce(12) || AES-GCM-ciphertext]` and
|
|
22
|
+
* the AES-256-GCM key is the channel's existing DocKey (the same one
|
|
23
|
+
* used for `EncryptedY` doc-level encryption — same threat boundary,
|
|
24
|
+
* no extra key derivation, identical envelope distribution).
|
|
25
|
+
*
|
|
26
|
+
* The `e2e:1:` sentinel is a strict prefix to disambiguate from
|
|
27
|
+
* cleartext content that happens to start with "{". Never unwrap a
|
|
28
|
+
* message whose content doesn't start with the sentinel — passing
|
|
29
|
+
* ciphertext from a server you don't trust through `decrypt` would
|
|
30
|
+
* open the door to malformed-input oracles.
|
|
31
|
+
*/
|
|
32
|
+
function toBase64(bytes) {
|
|
33
|
+
let s = "";
|
|
34
|
+
for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);
|
|
35
|
+
return btoa(s);
|
|
36
|
+
}
|
|
37
|
+
function fromBase64(b64) {
|
|
38
|
+
const bin = atob(b64);
|
|
39
|
+
const out = new Uint8Array(bin.length);
|
|
40
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
|
41
|
+
return out;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Decrypt an `e2e:1:` envelope back to cleartext using the channel's
|
|
45
|
+
* DocKey. Returns null if the envelope is malformed (don't surface
|
|
46
|
+
* partial decryption — show the user a placeholder instead).
|
|
47
|
+
*/
|
|
48
|
+
async function decryptChatContent(content, docKey) {
|
|
49
|
+
if (!isEncryptedContent(content)) return content;
|
|
50
|
+
try {
|
|
51
|
+
const plain = await decryptField(fromBase64(content.slice(E2E_SENTINEL.length)), docKey);
|
|
52
|
+
return new TextDecoder().decode(plain);
|
|
53
|
+
} catch {
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Encrypt cleartext into an `e2e:1:` envelope ready to send as the
|
|
59
|
+
* stateless `messages:send` `content` field.
|
|
60
|
+
*/
|
|
61
|
+
async function encryptChatContent(content, docKey) {
|
|
62
|
+
return E2E_SENTINEL + toBase64(await encryptField(new TextEncoder().encode(content), docKey));
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Per-channel encryption-mode + DocKey resolver. Caches the encryption
|
|
66
|
+
* mode lookup for `cacheTtlMs`; the DocKey itself is cached inside
|
|
67
|
+
* `DocKeyManager`. Returns `null` for non-E2E channels.
|
|
68
|
+
*/
|
|
69
|
+
/** Module constant, not a `static` field — see `DOC_KEY_CACHE_TTL` in `DocKeyManager.ts`. */
|
|
70
|
+
const CHANNEL_KEY_DEFAULT_TTL_MS = 300 * 1e3;
|
|
71
|
+
var ChannelKeyResolver = class {
|
|
72
|
+
constructor(client, docKeys, keystore, options = {}) {
|
|
73
|
+
this.client = client;
|
|
74
|
+
this.docKeys = docKeys;
|
|
75
|
+
this.keystore = keystore;
|
|
76
|
+
this.options = options;
|
|
77
|
+
this.modeCache = /* @__PURE__ */ new Map();
|
|
78
|
+
}
|
|
79
|
+
async modeFor(channelDocId) {
|
|
80
|
+
const cached = this.modeCache.get(channelDocId);
|
|
81
|
+
const ttl = this.options.cacheTtlMs ?? CHANNEL_KEY_DEFAULT_TTL_MS;
|
|
82
|
+
if (cached && Date.now() - cached.fetchedAt < ttl) return cached.mode;
|
|
83
|
+
const mode = (await this.client.getDocEncryption(channelDocId)).effective_mode;
|
|
84
|
+
this.modeCache.set(channelDocId, {
|
|
85
|
+
mode,
|
|
86
|
+
fetchedAt: Date.now()
|
|
87
|
+
});
|
|
88
|
+
return mode;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Returns the DocKey for an E2E channel, or null for cleartext channels
|
|
92
|
+
* (no envelope to fetch). Throws if the channel is E2E but no envelope
|
|
93
|
+
* exists for the current user — the caller should let the send fail
|
|
94
|
+
* loudly rather than fall back to cleartext, which would silently
|
|
95
|
+
* downgrade the threat model.
|
|
96
|
+
*/
|
|
97
|
+
async docKeyFor(channelDocId) {
|
|
98
|
+
if (await this.modeFor(channelDocId) !== "e2e") return null;
|
|
99
|
+
const key = await this.docKeys.getDocKey(channelDocId, this.client, this.keystore);
|
|
100
|
+
if (!key) throw new Error(`EncryptedChatClient: no key envelope for channel ${channelDocId} — user is not provisioned for this E2E channel.`);
|
|
101
|
+
return key;
|
|
102
|
+
}
|
|
103
|
+
/** Drop the cached encryption mode for `channelDocId` (or all). */
|
|
104
|
+
clearCache(channelDocId) {
|
|
105
|
+
if (channelDocId) this.modeCache.delete(channelDocId);
|
|
106
|
+
else this.modeCache.clear();
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
/**
|
|
110
|
+
* Drop-in wrapper around an existing ChatClient that intercepts the
|
|
111
|
+
* write side (`send` / `edit`) and encrypts content for E2E channels.
|
|
112
|
+
* Reading is handled separately — the consumer pumps the period's Y.Array
|
|
113
|
+
* directly and calls `decryptChatContent` per record.
|
|
114
|
+
*
|
|
115
|
+
* Channels in `none` or `cse` mode are passed through untouched.
|
|
116
|
+
*/
|
|
117
|
+
var EncryptedChatClient = class {
|
|
118
|
+
constructor(inner, resolver) {
|
|
119
|
+
this.inner = inner;
|
|
120
|
+
this.resolver = resolver;
|
|
121
|
+
}
|
|
122
|
+
async send(input) {
|
|
123
|
+
const docKey = await this.resolver.docKeyFor(input.channel_doc_id);
|
|
124
|
+
if (!docKey) return this.inner.send(input);
|
|
125
|
+
const ciphertext = await encryptChatContent(input.content, docKey);
|
|
126
|
+
return this.inner.send({
|
|
127
|
+
...input,
|
|
128
|
+
content: ciphertext
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
async edit(input) {
|
|
132
|
+
const docKey = await this.resolver.docKeyFor(input.channel_doc_id);
|
|
133
|
+
if (!docKey) return this.inner.edit(input);
|
|
134
|
+
const ciphertext = await encryptChatContent(input.content, docKey);
|
|
135
|
+
return this.inner.edit({
|
|
136
|
+
...input,
|
|
137
|
+
content: ciphertext
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
delete(...args) {
|
|
141
|
+
return this.inner.delete(...args);
|
|
142
|
+
}
|
|
143
|
+
markRead(...args) {
|
|
144
|
+
return this.inner.markRead(...args);
|
|
145
|
+
}
|
|
146
|
+
typing(...args) {
|
|
147
|
+
return this.inner.typing(...args);
|
|
148
|
+
}
|
|
149
|
+
destroy() {
|
|
150
|
+
this.inner.destroy();
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
//#endregion
|
|
155
|
+
export { ChannelKeyResolver, EncryptedChatClient, decryptChatContent, encryptChatContent };
|
|
156
|
+
//# sourceMappingURL=EncryptedChatClient.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"EncryptedChatClient.js","names":["SENTINEL"],"sources":["../../src/EncryptedChatClient.ts"],"sourcesContent":["/**\n * EncryptedChatClient — `ChatClient` wrapper that transparently encrypts\n * message content for channels in `e2e` mode and decrypts entries read\n * back from the period doc's `messages` Y.Array.\n *\n * Threat model\n * - Server cannot read message bodies (the `content` field is opaque\n * ciphertext bytes, base64-encoded into the wire string).\n * - Server CAN see `sender_id`, `channel_doc_id`, `period_id`, `ts`,\n * `mentions[]` (kept cleartext for fan-out), `message_id`,\n * and the `server_sig` it stamps. That envelope is the only thing\n * the server inspects to do its job.\n *\n * Wire format\n * `content` for an e2e message is the literal string\n * `\"e2e:1:<base64>\"`\n * where the decoded blob is `[nonce(12) || AES-GCM-ciphertext]` and\n * the AES-256-GCM key is the channel's existing DocKey (the same one\n * used for `EncryptedY` doc-level encryption — same threat boundary,\n * no extra key derivation, identical envelope distribution).\n *\n * The `e2e:1:` sentinel is a strict prefix to disambiguate from\n * cleartext content that happens to start with \"{\". Never unwrap a\n * message whose content doesn't start with the sentinel — passing\n * ciphertext from a server you don't trust through `decrypt` would\n * open the door to malformed-input oracles.\n */\n\nimport { encryptField, decryptField } from \"./EncryptedY.ts\";\nimport { DocKeyManager } from \"./DocKeyManager.ts\";\nimport { E2E_SENTINEL as SENTINEL, isEncryptedContent } from \"./encryptedContent.ts\";\nimport type { AbracadabraClient } from \"./AbracadabraClient.ts\";\nimport type { CryptoIdentityKeystore } from \"./CryptoIdentityKeystore.ts\";\nimport type {\n ChatClient,\n SendMessageInput,\n SendMessageResult,\n EditMessageInput,\n} from \"./ChatClient.ts\";\n\n\nfunction toBase64(bytes: Uint8Array): string {\n let s = \"\";\n for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]!);\n return btoa(s);\n}\n\nfunction fromBase64(b64: string): Uint8Array {\n const bin = atob(b64);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n\n// `isEncryptedContent` lives in the leaf module `encryptedContent.ts` (a chat\n// list checks every message with it; importing it from here dragged in the\n// key manager and `@noble/curves`). Re-exported unchanged.\nexport { isEncryptedContent }\n\n/**\n * Decrypt an `e2e:1:` envelope back to cleartext using the channel's\n * DocKey. Returns null if the envelope is malformed (don't surface\n * partial decryption — show the user a placeholder instead).\n */\nexport async function decryptChatContent(content: string, docKey: CryptoKey): Promise<string | null> {\n if (!isEncryptedContent(content)) return content; // already cleartext\n try {\n const blob = fromBase64(content.slice(SENTINEL.length));\n const plain = await decryptField(blob, docKey);\n return new TextDecoder().decode(plain);\n } catch {\n return null;\n }\n}\n\n/**\n * Encrypt cleartext into an `e2e:1:` envelope ready to send as the\n * stateless `messages:send` `content` field.\n */\nexport async function encryptChatContent(content: string, docKey: CryptoKey): Promise<string> {\n const blob = await encryptField(new TextEncoder().encode(content), docKey);\n return SENTINEL + toBase64(blob);\n}\n\n/**\n * Per-channel encryption-mode + DocKey resolver. Caches the encryption\n * mode lookup for `cacheTtlMs`; the DocKey itself is cached inside\n * `DocKeyManager`. Returns `null` for non-E2E channels.\n */\n/** Module constant, not a `static` field — see `DOC_KEY_CACHE_TTL` in `DocKeyManager.ts`. */\nconst CHANNEL_KEY_DEFAULT_TTL_MS = 5 * 60 * 1000;\n\nexport class ChannelKeyResolver {\n private modeCache = new Map<string, { mode: \"none\" | \"cse\" | \"e2e\"; fetchedAt: number }>();\n\n constructor(\n private readonly client: AbracadabraClient,\n private readonly docKeys: DocKeyManager,\n private readonly keystore: CryptoIdentityKeystore,\n private readonly options: { cacheTtlMs?: number } = {},\n ) {}\n\n async modeFor(channelDocId: string): Promise<\"none\" | \"cse\" | \"e2e\"> {\n const cached = this.modeCache.get(channelDocId);\n const ttl = this.options.cacheTtlMs ?? CHANNEL_KEY_DEFAULT_TTL_MS;\n if (cached && Date.now() - cached.fetchedAt < ttl) return cached.mode;\n const info = await this.client.getDocEncryption(channelDocId);\n const mode = info.effective_mode;\n this.modeCache.set(channelDocId, { mode, fetchedAt: Date.now() });\n return mode;\n }\n\n /**\n * Returns the DocKey for an E2E channel, or null for cleartext channels\n * (no envelope to fetch). Throws if the channel is E2E but no envelope\n * exists for the current user — the caller should let the send fail\n * loudly rather than fall back to cleartext, which would silently\n * downgrade the threat model.\n */\n async docKeyFor(channelDocId: string): Promise<CryptoKey | null> {\n const mode = await this.modeFor(channelDocId);\n if (mode !== \"e2e\") return null;\n const key = await this.docKeys.getDocKey(channelDocId, this.client, this.keystore);\n if (!key) {\n throw new Error(\n `EncryptedChatClient: no key envelope for channel ${channelDocId} — user is not provisioned for this E2E channel.`,\n );\n }\n return key;\n }\n\n /** Drop the cached encryption mode for `channelDocId` (or all). */\n clearCache(channelDocId?: string): void {\n if (channelDocId) this.modeCache.delete(channelDocId);\n else this.modeCache.clear();\n }\n}\n\n/**\n * Drop-in wrapper around an existing ChatClient that intercepts the\n * write side (`send` / `edit`) and encrypts content for E2E channels.\n * Reading is handled separately — the consumer pumps the period's Y.Array\n * directly and calls `decryptChatContent` per record.\n *\n * Channels in `none` or `cse` mode are passed through untouched.\n */\nexport class EncryptedChatClient {\n constructor(\n private readonly inner: ChatClient,\n private readonly resolver: ChannelKeyResolver,\n ) {}\n\n async send(input: SendMessageInput): Promise<SendMessageResult> {\n const docKey = await this.resolver.docKeyFor(input.channel_doc_id);\n if (!docKey) return this.inner.send(input);\n const ciphertext = await encryptChatContent(input.content, docKey);\n return this.inner.send({ ...input, content: ciphertext });\n }\n\n async edit(input: EditMessageInput): Promise<void> {\n const docKey = await this.resolver.docKeyFor(input.channel_doc_id);\n if (!docKey) return this.inner.edit(input);\n const ciphertext = await encryptChatContent(input.content, docKey);\n return this.inner.edit({ ...input, content: ciphertext });\n }\n\n // Pass-through methods that don't carry encryptable content.\n delete(...args: Parameters<ChatClient[\"delete\"]>) { return this.inner.delete(...args); }\n markRead(...args: Parameters<ChatClient[\"markRead\"]>) { return this.inner.markRead(...args); }\n typing(...args: Parameters<ChatClient[\"typing\"]>) { return this.inner.typing(...args); }\n destroy() { this.inner.destroy(); }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,SAAS,SAAS,OAA2B;CA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edY.ts
|
|
4
|
+
/** Encrypt a field value with AES-256-GCM. Returns [nonce(12) || ciphertext]. */
|
|
5
|
+
async function encryptField(value, docKey) {
|
|
6
|
+
const nonce = crypto.getRandomValues(new Uint8Array(12));
|
|
7
|
+
const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
|
|
8
|
+
name: "AES-GCM",
|
|
9
|
+
iv: nonce
|
|
10
|
+
}, docKey, value));
|
|
11
|
+
const result = new Uint8Array(12 + ciphertext.length);
|
|
12
|
+
result.set(nonce, 0);
|
|
13
|
+
result.set(ciphertext, 12);
|
|
14
|
+
return result;
|
|
15
|
+
}
|
|
16
|
+
/** Decrypt a field value from [nonce(12) || ciphertext] format. */
|
|
17
|
+
async function decryptField(ciphertext, docKey) {
|
|
18
|
+
const nonce = ciphertext.slice(0, 12);
|
|
19
|
+
const ct = ciphertext.slice(12);
|
|
20
|
+
return new Uint8Array(await crypto.subtle.decrypt({
|
|
21
|
+
name: "AES-GCM",
|
|
22
|
+
iv: nonce
|
|
23
|
+
}, docKey, ct));
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* A proxy wrapper around a Y.Map<Uint8Array> that transparently encrypts
|
|
27
|
+
* values on .set() and decrypts on .get().
|
|
28
|
+
*
|
|
29
|
+
* NOTE: Concurrent writes to the same key produce last-write-wins (LWW)
|
|
30
|
+
* because encrypted values are opaque blobs from Yrs's perspective.
|
|
31
|
+
*/
|
|
32
|
+
var EncryptedYMap = class {
|
|
33
|
+
constructor(ymap, docKey) {
|
|
34
|
+
this.ymap = ymap;
|
|
35
|
+
this.docKey = docKey;
|
|
36
|
+
}
|
|
37
|
+
async set(key, value) {
|
|
38
|
+
const encrypted = await encryptField(value, this.docKey);
|
|
39
|
+
this.ymap.set(key, encrypted);
|
|
40
|
+
}
|
|
41
|
+
async get(key) {
|
|
42
|
+
const encrypted = this.ymap.get(key);
|
|
43
|
+
if (!encrypted) return null;
|
|
44
|
+
try {
|
|
45
|
+
return await decryptField(encrypted, this.docKey);
|
|
46
|
+
} catch {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
has(key) {
|
|
51
|
+
return this.ymap.has(key);
|
|
52
|
+
}
|
|
53
|
+
delete(key) {
|
|
54
|
+
this.ymap.delete(key);
|
|
55
|
+
}
|
|
56
|
+
get size() {
|
|
57
|
+
return this.ymap.size;
|
|
58
|
+
}
|
|
59
|
+
/** Get all keys (encrypted values remain opaque until .get() is called). */
|
|
60
|
+
keys() {
|
|
61
|
+
return Array.from(this.ymap.keys());
|
|
62
|
+
}
|
|
63
|
+
/** Observe changes on the underlying Y.Map. */
|
|
64
|
+
observe(f) {
|
|
65
|
+
this.ymap.observe(f);
|
|
66
|
+
}
|
|
67
|
+
unobserve(f) {
|
|
68
|
+
this.ymap.unobserve(f);
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
/** Create an EncryptedYMap wrapping a Y.Map<Uint8Array>. */
|
|
72
|
+
function makeEncryptedYMap(ymap, docKey) {
|
|
73
|
+
return new EncryptedYMap(ymap, docKey);
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Stores full text as a single encrypted blob in a Y.Map<Uint8Array> under a
|
|
77
|
+
* fixed field name. This is last-write-wins for the entire text field.
|
|
78
|
+
*
|
|
79
|
+
* NOTE: This does NOT preserve character-level CRDT merge for concurrent edits.
|
|
80
|
+
* It trades CRDT merge for confidentiality.
|
|
81
|
+
*/
|
|
82
|
+
var EncryptedYText = class {
|
|
83
|
+
constructor(ydoc, fieldName, docKey) {
|
|
84
|
+
this.docKey = docKey;
|
|
85
|
+
this.ymap = ydoc.getMap(`_encrypted_${fieldName}`);
|
|
86
|
+
}
|
|
87
|
+
async set(text) {
|
|
88
|
+
const encrypted = await encryptField(new TextEncoder().encode(text), this.docKey);
|
|
89
|
+
this.ymap.set("v", encrypted);
|
|
90
|
+
}
|
|
91
|
+
async get() {
|
|
92
|
+
const encrypted = this.ymap.get("v");
|
|
93
|
+
if (!encrypted) return null;
|
|
94
|
+
try {
|
|
95
|
+
const decoded = await decryptField(encrypted, this.docKey);
|
|
96
|
+
return new TextDecoder().decode(decoded);
|
|
97
|
+
} catch {
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
observe(f) {
|
|
102
|
+
this.ymap.observe(f);
|
|
103
|
+
}
|
|
104
|
+
unobserve(f) {
|
|
105
|
+
this.ymap.unobserve(f);
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
/** Create an EncryptedYText for a field in a Y.Doc. */
|
|
109
|
+
function makeEncryptedYText(ydoc, fieldName, docKey) {
|
|
110
|
+
return new EncryptedYText(ydoc, fieldName, docKey);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
//#endregion
|
|
114
|
+
export { EncryptedYMap, EncryptedYText, decryptField, encryptField, makeEncryptedYMap, makeEncryptedYText };
|
|
115
|
+
//# sourceMappingURL=EncryptedY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"EncryptedY.js","names":[],"sources":["../../src/EncryptedY.ts"],"sourcesContent":["/**\n * EncryptedY - CSE (Client-Side Encryption) primitives for Yjs documents.\n *\n * Wire format for encrypted fields: [nonce(12) || AES-GCM ciphertext]\n *\n * Limitations (documented):\n * - Concurrent writes to the same Y.Map key produce last-write-wins semantics\n * (not character-level CRDT merge), because encrypted values are opaque to Yrs.\n */\n\nimport * as Y from \"yjs\";\n\n// ── Field-level encryption ─────────────────────────────────────────────────────\n\n/** Encrypt a field value with AES-256-GCM. Returns [nonce(12) || ciphertext]. */\nexport async function encryptField(value: Uint8Array, docKey: CryptoKey): Promise<Uint8Array> {\n\tconst nonce = crypto.getRandomValues(new Uint8Array(12));\n\tconst ciphertext = new Uint8Array(\n\t\tawait crypto.subtle.encrypt({ name: \"AES-GCM\", iv: nonce as BufferSource }, docKey, value as BufferSource),\n\t);\n\tconst result = new Uint8Array(12 + ciphertext.length);\n\tresult.set(nonce, 0);\n\tresult.set(ciphertext, 12);\n\treturn result;\n}\n\n/** Decrypt a field value from [nonce(12) || ciphertext] format. */\nexport async function decryptField(ciphertext: Uint8Array, docKey: CryptoKey): Promise<Uint8Array> {\n\tconst nonce = ciphertext.slice(0, 12);\n\tconst ct = ciphertext.slice(12);\n\treturn new Uint8Array(await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: nonce as BufferSource }, docKey, ct as BufferSource));\n}\n\n// ── EncryptedYMap ─────────────────────────────────────────────────────────────\n\n/**\n * A proxy wrapper around a Y.Map<Uint8Array> that transparently encrypts\n * values on .set() and decrypts on .get().\n *\n * NOTE: Concurrent writes to the same key produce last-write-wins (LWW)\n * because encrypted values are opaque blobs from Yrs's perspective.\n */\nexport class EncryptedYMap {\n\tconstructor(\n\t\tprivate readonly ymap: Y.Map<Uint8Array>,\n\t\tprivate readonly docKey: CryptoKey,\n\t) {}\n\n\tasync set(key: string, value: Uint8Array): Promise<void> {\n\t\tconst encrypted = await encryptField(value, this.docKey);\n\t\tthis.ymap.set(key, encrypted);\n\t}\n\n\tasync get(key: string): Promise<Uint8Array | null> {\n\t\tconst encrypted = this.ymap.get(key);\n\t\tif (!encrypted) return null;\n\t\ttry {\n\t\t\treturn await decryptField(encrypted, this.docKey);\n\t\t} catch {\n\t\t\treturn null; // Decryption failed (wrong key or corrupted)\n\t\t}\n\t}\n\n\thas(key: string): boolean {\n\t\treturn this.ymap.has(key);\n\t}\n\n\tdelete(key: string): void {\n\t\tthis.ymap.delete(key);\n\t}\n\n\tget size(): number {\n\t\treturn this.ymap.size;\n\t}\n\n\t/** Get all keys (encrypted values remain opaque until .get() is called). */\n\tkeys(): string[] {\n\t\treturn Array.from(this.ymap.keys());\n\t}\n\n\t/** Observe changes on the underlying Y.Map. */\n\tobserve(f: (event: Y.YMapEvent<Uint8Array>) => void): void {\n\t\tthis.ymap.observe(f);\n\t}\n\n\tunobserve(f: (event: Y.YMapEvent<Uint8Array>) => void): void {\n\t\tthis.ymap.unobserve(f);\n\t}\n}\n\n/** Create an EncryptedYMap wrapping a Y.Map<Uint8Array>. */\nexport function makeEncryptedYMap(ymap: Y.Map<Uint8Array>, docKey: CryptoKey): EncryptedYMap {\n\treturn new EncryptedYMap(ymap, docKey);\n}\n\n// ── EncryptedYText ────────────────────────────────────────────────────────────\n\n/**\n * Stores full text as a single encrypted blob in a Y.Map<Uint8Array> under a\n * fixed field name. This is last-write-wins for the entire text field.\n *\n * NOTE: This does NOT preserve character-level CRDT merge for concurrent edits.\n * It trades CRDT merge for confidentiality.\n */\nexport class EncryptedYText {\n\tprivate readonly ymap: Y.Map<Uint8Array>;\n\n\tconstructor(\n\t\tydoc: Y.Doc,\n\t\tfieldName: string,\n\t\tprivate readonly docKey: CryptoKey,\n\t) {\n\t\tthis.ymap = ydoc.getMap(`_encrypted_${fieldName}`);\n\t}\n\n\tasync set(text: string): Promise<void> {\n\t\tconst encoded = new TextEncoder().encode(text);\n\t\tconst encrypted = await encryptField(encoded, this.docKey);\n\t\tthis.ymap.set(\"v\", encrypted);\n\t}\n\n\tasync get(): Promise<string | null> {\n\t\tconst encrypted = this.ymap.get(\"v\");\n\t\tif (!encrypted) return null;\n\t\ttry {\n\t\t\tconst decoded = await decryptField(encrypted, this.docKey);\n\t\t\treturn new TextDecoder().decode(decoded);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tobserve(f: (event: Y.YMapEvent<Uint8Array>) => void): void {\n\t\tthis.ymap.observe(f);\n\t}\n\n\tunobserve(f: (event: Y.YMapEvent<Uint8Array>) => void): void {\n\t\tthis.ymap.unobserve(f);\n\t}\n}\n\n/** Create an EncryptedYText for a field in a Y.Doc. */\nexport function makeEncryptedYText(ydoc: Y.Doc, fieldName: string, docKey: CryptoKey): EncryptedYText {\n\treturn new EncryptedYText(ydoc, fieldName, docKey);\n}\n"],"mappings":";;;;AAeA,eAAsB,aAAa,OAAmB,QAAwC;CAC7F,MAAM,QAAQ,OAAO,gBAAgB,IAAI,WAAW,GAAG,CAA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MAAM,OAAO;;;;;;;;;AAYvC,IAAa,iBAAb,MAA4B;CAG3B,YACC,MACA,WACA,AAAiB,QAChB;EADgB;AAEjB,OAAK,OAAO,KAAK,OAAO,cAAc,YAAY;;CAGnD,MAAM,IAAI,MAA6B;EAEtC,MAAM,YAAY,MAAM,aADR,IAAI,aAAa,CAAC,OAAO,KAAK,EACA,KAAK,OAAO;AAC1D,OAAK,KAAK,IAAI,KAAK,UAAU;;CAG9B,MAAM,MAA8B;EACnC,MAAM,YAAY,KAAK,KAAK,IAAI,IAAI;AACpC,MAAI,CAAC,UAAW,QAAO;AACvB,MAAI;GACH,MAAM,UAAU,MAAM,aAAa,WAAW,KAAK,OAAO;AAC1D,UAAO,IAAI,aAAa,CAAC,OAAO,QAAQ;UACjC;AACP,UAAO;;;CAIT,QAAQ,GAAmD;AAC1D,OAAK,KAAK,QAAQ,EAAE;;CAGrB,UAAU,GAAmD;AAC5D,OAAK,KAAK,UAAU,EAAE;;;;AAKxB,SAAgB,mBAAmB,MAAa,WAAmB,QAAmC;AACrG,QAAO,IAAI,eAAe,MAAM,WAAW,OAAO"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
//#region packages/provider/src/EventEmitter.ts
|
|
2
|
+
var EventEmitter = class {
|
|
3
|
+
constructor() {
|
|
4
|
+
this.callbacks = {};
|
|
5
|
+
}
|
|
6
|
+
on(event, fn) {
|
|
7
|
+
if (!this.callbacks[event]) this.callbacks[event] = [];
|
|
8
|
+
this.callbacks[event].push(fn);
|
|
9
|
+
return this;
|
|
10
|
+
}
|
|
11
|
+
once(event, fn) {
|
|
12
|
+
const wrapper = (...args) => {
|
|
13
|
+
this.off(event, wrapper);
|
|
14
|
+
fn.apply(this, args);
|
|
15
|
+
};
|
|
16
|
+
return this.on(event, wrapper);
|
|
17
|
+
}
|
|
18
|
+
emit(event, ...args) {
|
|
19
|
+
const callbacks = this.callbacks[event];
|
|
20
|
+
if (callbacks) for (const callback of callbacks) try {
|
|
21
|
+
callback.apply(this, args);
|
|
22
|
+
} catch (err) {
|
|
23
|
+
console.error(`[EventEmitter] Error in "${event}" listener:`, err);
|
|
24
|
+
}
|
|
25
|
+
return this;
|
|
26
|
+
}
|
|
27
|
+
off(event, fn) {
|
|
28
|
+
const callbacks = this.callbacks[event];
|
|
29
|
+
if (callbacks) if (fn) this.callbacks[event] = callbacks.filter((callback) => callback !== fn);
|
|
30
|
+
else delete this.callbacks[event];
|
|
31
|
+
return this;
|
|
32
|
+
}
|
|
33
|
+
removeAllListeners() {
|
|
34
|
+
this.callbacks = {};
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
//#endregion
|
|
39
|
+
export { EventEmitter as default };
|
|
40
|
+
//# sourceMappingURL=EventEmitter.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"EventEmitter.js","names":[],"sources":["../../src/EventEmitter.ts"],"sourcesContent":["export default class EventEmitter {\n\t// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n\tpublic callbacks: { [key: string]: Function[] } = {};\n\n\t// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n\tpublic on(event: string, fn: Function): this {\n\t\tif (!this.callbacks[event]) {\n\t\t\tthis.callbacks[event] = [];\n\t\t}\n\n\t\tthis.callbacks[event].push(fn);\n\n\t\treturn this;\n\t}\n\n\t// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n\tpublic once(event: string, fn: Function): this {\n\t\tconst wrapper = (...args: any[]) => {\n\t\t\tthis.off(event, wrapper);\n\t\t\tfn.apply(this, args);\n\t\t};\n\t\treturn this.on(event, wrapper);\n\t}\n\n\tprotected emit(event: string, ...args: any): this {\n\t\tconst callbacks = this.callbacks[event];\n\n\t\tif (callbacks) {\n\t\t\tfor (const callback of callbacks) {\n\t\t\t\ttry {\n\t\t\t\t\tcallback.apply(this, args);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconsole.error(`[EventEmitter] Error in \"${event}\" listener:`, err);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n\tpublic off(event: string, fn?: Function): this {\n\t\tconst callbacks = this.callbacks[event];\n\n\t\tif (callbacks) {\n\t\t\tif (fn) {\n\t\t\t\tthis.callbacks[event] = callbacks.filter((callback) => callback !== fn);\n\t\t\t} else {\n\t\t\t\tdelete this.callbacks[event];\n\t\t\t}\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tremoveAllListeners(): void {\n\t\tthis.callbacks = {};\n\t}\n}\n"],"mappings":";AAAA,IAAqB,eAArB,MAAkC;;mBAEiB,EAAE;;CAGpD,AAAO,GAAG,OAAe,IAAoB;AAC5C,MAAI,CAAC,KAAK,UAAU,OACnB,MAAK,UAAU,SAAS,EAAE;AAG3B,OAAK,UAAU,OAAO,KAAK,GAAG;AAE9B,SAAO;;CAIR,AAAO,KAAK,OAAe,IAAoB;EAC9C,MAAM,WAAW,GAAG,SAAgB;AACnC,QAAK,IAAI,OAAO,QAAQ;AACxB,MAAG,MAAM,MAAM,KAAK;;AAErB,SAAO,KAAK,GAAG,OAAO,QAAQ;;CAG/B,AAAU,KAAK,OAAe,GAAG,MAAiB;EACjD,MAAM,YAAY,KAAK,UAAU;AAEjC,MAAI,UACH,MAAK,MAAM,YAAY,UACtB,KAAI;AACH,YAAS,MAAM,MAAM,KAAK;WAClB,KAAK;AACb,WAAQ,MAAM,4BAA4B,MAAM,cAAc,IAAI;;AAKrE,SAAO;;CAIR,AAAO,IAAI,OAAe,IAAqB;EAC9C,MAAM,YAAY,KAAK,UAAU;AAEjC,MAAI,UACH,KAAI,GACH,MAAK,UAAU,SAAS,UAAU,QAAQ,aAAa,aAAa,GAAG;MAEvE,QAAO,KAAK,UAAU;AAIxB,SAAO;;CAGR,qBAA2B;AAC1B,OAAK,YAAY,EAAE"}
|