@mosadd/mcp 3.0.0-alpha.4 → 3.0.0-alpha.40
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/CHANGELOG.md +298 -0
- package/README.md +70 -36
- package/dist/bin/mcp.js +42 -3
- package/dist/chunk-7ZAAJ52G.js +3475 -0
- package/dist/index.d.ts +115 -6
- package/dist/index.js +7 -3
- package/package.json +8 -5
- package/src/__tests__/golden-path.test.ts +139 -137
- package/src/__tests__/integration.test.ts +179 -178
- package/src/__tests__/knowledge-ingest.test.ts +114 -0
- package/src/__tests__/mdm-e2ee.test.ts +212 -178
- package/src/__tests__/mtalk.test.ts +122 -122
- package/src/__tests__/presence.test.ts +178 -0
- package/src/__tests__/server.test.ts +71 -67
- package/src/__tests__/tool-count-consistency.test.ts +164 -0
- package/src/bin/login.ts +138 -138
- package/src/bin/mcp.ts +145 -97
- package/src/config.ts +66 -66
- package/src/crypto/mdm-session.ts +502 -403
- package/src/index.ts +19 -17
- package/src/observability/sentry.ts +79 -79
- package/src/providers/blob-upload.ts +116 -0
- package/src/providers/memory-voice.ts +79 -79
- package/src/providers/supabase-dm.ts +122 -117
- package/src/providers/supabase-voice.ts +91 -91
- package/src/providers/supabase.ts +155 -96
- package/src/server.ts +60 -9
- package/src/tools/actions.ts +166 -0
- package/src/tools/attachments.ts +276 -0
- package/src/tools/capabilities.ts +70 -68
- package/src/tools/embed.ts +110 -0
- package/src/tools/index.ts +177 -43
- package/src/tools/knowledge-graph.ts +186 -0
- package/src/tools/knowledge.ts +327 -91
- package/src/tools/mail-agentbox.ts +155 -0
- package/src/tools/mail-aliases.ts +25 -0
- package/src/tools/mail-provenance.ts +137 -0
- package/src/tools/mail.ts +403 -89
- package/src/tools/mcall.ts +216 -0
- package/src/tools/mdm-as-agent.ts +126 -0
- package/src/tools/mdm-voice.ts +220 -0
- package/src/tools/mdm.ts +494 -392
- package/src/tools/mirc-edge.ts +196 -0
- package/src/tools/mirc-members.ts +61 -20
- package/src/tools/mirc-messages.ts +185 -151
- package/src/tools/mirc.ts +104 -10
- package/src/tools/mroom-messages.ts +142 -142
- package/src/tools/mroom.ts +221 -189
- package/src/tools/mtalk.ts +131 -121
- package/src/tools/murl.ts +314 -0
- package/src/tools/presence.ts +333 -0
- package/src/tools/ptt-ingest.ts +99 -0
- package/src/tools/threat.ts +123 -0
- package/src/types.ts +121 -85
- package/src/version.ts +8 -0
- package/src/voice/floor.ts +132 -132
- package/dist/chunk-YDFU6S5E.js +0 -1471
|
@@ -1,403 +1,502 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* mDM end-to-end encryption — session layer (LINEAR-2357).
|
|
3
|
-
*
|
|
4
|
-
* Sits ABOVE the DmProvider. The provider moves opaque bytes; THIS module
|
|
5
|
-
* decides what those bytes are: an X3DH handshake + Double Ratchet ciphertext
|
|
6
|
-
* envelope, produced from `@mosadd/crypto` primitives.
|
|
7
|
-
*
|
|
8
|
-
* Flow (decision "1a" — prekey distribution rides the DmProvider):
|
|
9
|
-
* - Each peer publishes a prekey bundle via `dm.publishPrekeyBundle(bytes)`.
|
|
10
|
-
* - First contact: sender `dm.fetchPrekeyBundle(peer)` → X3DH (initiator) →
|
|
11
|
-
* Double Ratchet. The first ciphertext carries a handshake header
|
|
12
|
-
* (initiator IK + EK + consumed one-time-prekey id) so the recipient can
|
|
13
|
-
* run X3DH (responder) and derive the SAME root key.
|
|
14
|
-
* - Subsequent messages reuse the stored ratchet session (no header).
|
|
15
|
-
*
|
|
16
|
-
* SCOPE / known follow-ups (tracked on LINEAR-2357, NOT silently hidden):
|
|
17
|
-
* - Ratchet is strict in-order (no skipped-message keys) — fine for a single
|
|
18
|
-
* ordered thread; out-of-order/lossy transports need skipped-key handling.
|
|
19
|
-
* - Signed-prekey signature is carried but NOT yet verified (auth follow-up).
|
|
20
|
-
* - Initiator "glare" (both sides open simultaneously) not resolved.
|
|
21
|
-
* - Default keystore is in-memory (per-process); file/OS-keychain backing is
|
|
22
|
-
* a follow-up. The MdmKeyStore seam makes that a drop-in.
|
|
23
|
-
*/
|
|
24
|
-
|
|
25
|
-
import {
|
|
26
|
-
decryptBytes,
|
|
27
|
-
encryptBytes,
|
|
28
|
-
generateEd25519KeyPair,
|
|
29
|
-
generateX25519KeyPair,
|
|
30
|
-
initializeRatchet,
|
|
31
|
-
performX3dh,
|
|
32
|
-
performX3dhResponder,
|
|
33
|
-
ratchetReceive,
|
|
34
|
-
ratchetSend,
|
|
35
|
-
signEd25519,
|
|
36
|
-
verifyEd25519,
|
|
37
|
-
toBase64,
|
|
38
|
-
fromBase64,
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
/**
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
/**
|
|
87
|
-
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
/**
|
|
91
|
-
*
|
|
92
|
-
* is
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
return this.material;
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
const
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
this.
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
//
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
1
|
+
/**
|
|
2
|
+
* mDM end-to-end encryption — session layer (LINEAR-2357).
|
|
3
|
+
*
|
|
4
|
+
* Sits ABOVE the DmProvider. The provider moves opaque bytes; THIS module
|
|
5
|
+
* decides what those bytes are: an X3DH handshake + Double Ratchet ciphertext
|
|
6
|
+
* envelope, produced from `@mosadd/crypto` primitives.
|
|
7
|
+
*
|
|
8
|
+
* Flow (decision "1a" — prekey distribution rides the DmProvider):
|
|
9
|
+
* - Each peer publishes a prekey bundle via `dm.publishPrekeyBundle(bytes)`.
|
|
10
|
+
* - First contact: sender `dm.fetchPrekeyBundle(peer)` → X3DH (initiator) →
|
|
11
|
+
* Double Ratchet. The first ciphertext carries a handshake header
|
|
12
|
+
* (initiator IK + EK + consumed one-time-prekey id) so the recipient can
|
|
13
|
+
* run X3DH (responder) and derive the SAME root key.
|
|
14
|
+
* - Subsequent messages reuse the stored ratchet session (no header).
|
|
15
|
+
*
|
|
16
|
+
* SCOPE / known follow-ups (tracked on LINEAR-2357, NOT silently hidden):
|
|
17
|
+
* - Ratchet is strict in-order (no skipped-message keys) — fine for a single
|
|
18
|
+
* ordered thread; out-of-order/lossy transports need skipped-key handling.
|
|
19
|
+
* - Signed-prekey signature is carried but NOT yet verified (auth follow-up).
|
|
20
|
+
* - Initiator "glare" (both sides open simultaneously) not resolved.
|
|
21
|
+
* - Default keystore is in-memory (per-process); file/OS-keychain backing is
|
|
22
|
+
* a follow-up. The MdmKeyStore seam makes that a drop-in.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import {
|
|
26
|
+
decryptBytes,
|
|
27
|
+
encryptBytes,
|
|
28
|
+
generateEd25519KeyPair,
|
|
29
|
+
generateX25519KeyPair,
|
|
30
|
+
initializeRatchet,
|
|
31
|
+
performX3dh,
|
|
32
|
+
performX3dhResponder,
|
|
33
|
+
ratchetReceive,
|
|
34
|
+
ratchetSend,
|
|
35
|
+
signEd25519,
|
|
36
|
+
verifyEd25519,
|
|
37
|
+
toBase64,
|
|
38
|
+
fromBase64,
|
|
39
|
+
initRatchetInitiator,
|
|
40
|
+
initRatchetResponder,
|
|
41
|
+
ratchetEncrypt,
|
|
42
|
+
ratchetDecrypt,
|
|
43
|
+
type EncryptedPayload,
|
|
44
|
+
type RatchetState,
|
|
45
|
+
type DhRatchetState,
|
|
46
|
+
type SessionRole,
|
|
47
|
+
} from "@mosadd/crypto";
|
|
48
|
+
import type { DmProvider } from "@mosadd/providers";
|
|
49
|
+
|
|
50
|
+
export const PREKEY_BUNDLE_VERSION = "mosadd.prekeys.v1" as const;
|
|
51
|
+
/** Legacy symmetric-ratchet envelope (no PCS). Still DECODED for back-compat. */
|
|
52
|
+
export const E2EE_ENVELOPE_VERSION = "mosadd.e2ee.v1" as const;
|
|
53
|
+
/** Double-Ratchet-with-DH envelope — post-compromise security (LINEAR-3409). New sends use this. */
|
|
54
|
+
export const E2EE_ENVELOPE_VERSION_V2 = "mosadd.e2ee.v2" as const;
|
|
55
|
+
|
|
56
|
+
const DEFAULT_ONE_TIME_PREKEYS = 8;
|
|
57
|
+
|
|
58
|
+
// ---- Key material types ----
|
|
59
|
+
|
|
60
|
+
interface X25519Pair {
|
|
61
|
+
publicKey: Uint8Array;
|
|
62
|
+
privateKey: Uint8Array;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The local peer's long-term identity + prekeys (private halves included). */
|
|
66
|
+
export interface OwnPrekeyMaterial {
|
|
67
|
+
/** X25519 DH identity — used in X3DH. */
|
|
68
|
+
identity: X25519Pair;
|
|
69
|
+
/**
|
|
70
|
+
* Ed25519 SIGNING identity — the long-term key a peer pins out-of-band
|
|
71
|
+
* (the "safety number"). Signs the bundle so a network/radio MITM can't swap
|
|
72
|
+
* the signed prekey or DH identity in transit.
|
|
73
|
+
*/
|
|
74
|
+
signingIdentity: { publicKey: Uint8Array; privateKey: Uint8Array };
|
|
75
|
+
signedPrekey: { id: number; pair: X25519Pair };
|
|
76
|
+
oneTimePrekeys: Array<{ id: number; pair: X25519Pair }>;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** A peer's PUBLIC prekey bundle, as parsed off the wire. */
|
|
80
|
+
export interface PublicPrekeyBundle {
|
|
81
|
+
identityPublicKey: Uint8Array;
|
|
82
|
+
/** Ed25519 signing-identity public key the signature is verified against. */
|
|
83
|
+
signingIdentityPublicKey: Uint8Array;
|
|
84
|
+
signedPrekey: { id: number; publicKey: Uint8Array };
|
|
85
|
+
oneTimePrekeys: Array<{ id: number; publicKey: Uint8Array }>;
|
|
86
|
+
/** Ed25519 signature over (DH identity pub ‖ signed-prekey pub). */
|
|
87
|
+
signature: Uint8Array;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Persisted per-peer ratchet session. Plain data → trivially serializable.
|
|
92
|
+
* A session is either v1 (`ratchet`, symmetric) or v2 (`ratchet2`, DH ratchet /
|
|
93
|
+
* PCS). New sessions are v2; an existing v1 session keeps running v1.
|
|
94
|
+
*/
|
|
95
|
+
export interface MdmSessionRecord {
|
|
96
|
+
ratchet?: RatchetState; // v1 (legacy symmetric)
|
|
97
|
+
ratchet2?: DhRatchetState; // v2 (DH ratchet, PCS — LINEAR-3409)
|
|
98
|
+
role: SessionRole;
|
|
99
|
+
/** Handshake header still owed to the peer (initiator only, until first send). */
|
|
100
|
+
pendingHandshake?: { ik: Uint8Array; ek: Uint8Array; opkId?: number };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Local custody of private key material + ratchet sessions. The default impl
|
|
105
|
+
* is in-memory; a host may inject a file- or keychain-backed implementation.
|
|
106
|
+
*/
|
|
107
|
+
export interface MdmKeyStore {
|
|
108
|
+
/** Own identity + prekeys. Generated lazily on first access, then stable. */
|
|
109
|
+
getOwnMaterial(): Promise<OwnPrekeyMaterial>;
|
|
110
|
+
/** Consume (one-time) a prekey private by id. Returns undefined if unknown. */
|
|
111
|
+
takeOneTimePrekey(id: number): Promise<Uint8Array | undefined>;
|
|
112
|
+
getSession(peerId: string): Promise<MdmSessionRecord | undefined>;
|
|
113
|
+
putSession(peerId: string, record: MdmSessionRecord): Promise<void>;
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* OPTIONAL local "sent items" cache. The Double Ratchet is forward-secret and
|
|
117
|
+
* asymmetric: once we seal a message for a peer we cannot re-derive its
|
|
118
|
+
* plaintext from our own ratchet on read. So mDM_list cannot show the sender
|
|
119
|
+
* their OWN outgoing text unless we keep a local copy. These two methods are
|
|
120
|
+
* that copy — keyed by the provider-assigned message id.
|
|
121
|
+
*
|
|
122
|
+
* Honesty note: this is a LOCAL plaintext cache, not synced across devices.
|
|
123
|
+
* A second device (or a fresh process) won't have it and will fall back to a
|
|
124
|
+
* "<encrypted · sent by you>" marker. Cross-device sent-history sync is a
|
|
125
|
+
* tracked follow-up (would need an encrypt-to-self session). Optional so
|
|
126
|
+
* existing MdmKeyStore implementations keep compiling.
|
|
127
|
+
*/
|
|
128
|
+
putSentMessage?(messageId: string, plaintext: Uint8Array): Promise<void>;
|
|
129
|
+
getSentMessage?(messageId: string): Promise<Uint8Array | undefined>;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// ---- In-memory keystore (default) ----
|
|
133
|
+
|
|
134
|
+
export class InMemoryMdmKeyStore implements MdmKeyStore {
|
|
135
|
+
private material: OwnPrekeyMaterial | null = null;
|
|
136
|
+
private readonly oneTimeById = new Map<number, Uint8Array>();
|
|
137
|
+
private readonly sessions = new Map<string, MdmSessionRecord>();
|
|
138
|
+
private readonly sentMessages = new Map<string, Uint8Array>();
|
|
139
|
+
|
|
140
|
+
async getOwnMaterial(): Promise<OwnPrekeyMaterial> {
|
|
141
|
+
if (this.material) return this.material;
|
|
142
|
+
const identity = await generateX25519KeyPair();
|
|
143
|
+
const signingIdentity = await generateEd25519KeyPair();
|
|
144
|
+
const signedPrekeyPair = await generateX25519KeyPair();
|
|
145
|
+
const signedPrekey = { id: randomId(), pair: signedPrekeyPair };
|
|
146
|
+
const oneTimePrekeys: OwnPrekeyMaterial["oneTimePrekeys"] = [];
|
|
147
|
+
for (let i = 0; i < DEFAULT_ONE_TIME_PREKEYS; i += 1) {
|
|
148
|
+
const pair = await generateX25519KeyPair();
|
|
149
|
+
const id = randomId();
|
|
150
|
+
oneTimePrekeys.push({ id, pair });
|
|
151
|
+
this.oneTimeById.set(id, pair.privateKey);
|
|
152
|
+
}
|
|
153
|
+
this.material = { identity, signingIdentity, signedPrekey, oneTimePrekeys };
|
|
154
|
+
return this.material;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async takeOneTimePrekey(id: number): Promise<Uint8Array | undefined> {
|
|
158
|
+
const priv = this.oneTimeById.get(id);
|
|
159
|
+
if (priv) this.oneTimeById.delete(id); // one-time: consume on use
|
|
160
|
+
return priv;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async getSession(peerId: string): Promise<MdmSessionRecord | undefined> {
|
|
164
|
+
return this.sessions.get(peerId);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async putSession(peerId: string, record: MdmSessionRecord): Promise<void> {
|
|
168
|
+
this.sessions.set(peerId, record);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async putSentMessage(messageId: string, plaintext: Uint8Array): Promise<void> {
|
|
172
|
+
this.sentMessages.set(messageId, plaintext);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
async getSentMessage(messageId: string): Promise<Uint8Array | undefined> {
|
|
176
|
+
return this.sentMessages.get(messageId);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function randomId(): number {
|
|
181
|
+
return crypto.getRandomValues(new Uint32Array(1))[0]!;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// ---- Bundle codec (opaque bytes the provider moves) ----
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* The exact bytes signed by / verified against the Ed25519 signing identity:
|
|
188
|
+
* the DH identity public key concatenated with the signed-prekey public key.
|
|
189
|
+
* Binding both means a MITM cannot swap either without invalidating the sig.
|
|
190
|
+
*/
|
|
191
|
+
function bundleSigningMessage(dhIdentityPub: Uint8Array, signedPrekeyPub: Uint8Array): Uint8Array {
|
|
192
|
+
const msg = new Uint8Array(dhIdentityPub.length + signedPrekeyPub.length);
|
|
193
|
+
msg.set(dhIdentityPub, 0);
|
|
194
|
+
msg.set(signedPrekeyPub, dhIdentityPub.length);
|
|
195
|
+
return msg;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
export function serializePublicBundle(material: OwnPrekeyMaterial): Uint8Array {
|
|
199
|
+
const signature = signEd25519(
|
|
200
|
+
material.signingIdentity.privateKey,
|
|
201
|
+
bundleSigningMessage(material.identity.publicKey, material.signedPrekey.pair.publicKey),
|
|
202
|
+
);
|
|
203
|
+
const json = JSON.stringify({
|
|
204
|
+
v: PREKEY_BUNDLE_VERSION,
|
|
205
|
+
ik: toBase64(material.identity.publicKey),
|
|
206
|
+
sik: toBase64(material.signingIdentity.publicKey),
|
|
207
|
+
spk: { id: material.signedPrekey.id, pub: toBase64(material.signedPrekey.pair.publicKey) },
|
|
208
|
+
opks: material.oneTimePrekeys.map((k) => ({ id: k.id, pub: toBase64(k.pair.publicKey) })),
|
|
209
|
+
sig: toBase64(signature),
|
|
210
|
+
});
|
|
211
|
+
return new Uint8Array(Buffer.from(json, "utf8"));
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export function parsePublicBundle(bytes: Uint8Array): PublicPrekeyBundle {
|
|
215
|
+
const obj = JSON.parse(Buffer.from(bytes).toString("utf8"));
|
|
216
|
+
if (obj?.v !== PREKEY_BUNDLE_VERSION) {
|
|
217
|
+
throw new Error(`Unsupported prekey bundle version: ${obj?.v}`);
|
|
218
|
+
}
|
|
219
|
+
if (typeof obj.sik !== "string" || typeof obj.sig !== "string") {
|
|
220
|
+
throw new Error("Prekey bundle is missing its signing identity / signature.");
|
|
221
|
+
}
|
|
222
|
+
return {
|
|
223
|
+
identityPublicKey: fromBase64(obj.ik),
|
|
224
|
+
signingIdentityPublicKey: fromBase64(obj.sik),
|
|
225
|
+
signedPrekey: { id: obj.spk.id, publicKey: fromBase64(obj.spk.pub) },
|
|
226
|
+
oneTimePrekeys: (obj.opks ?? []).map((k: { id: number; pub: string }) => ({
|
|
227
|
+
id: k.id,
|
|
228
|
+
publicKey: fromBase64(k.pub),
|
|
229
|
+
})),
|
|
230
|
+
signature: fromBase64(obj.sig),
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Verify the bundle's self-signature: the signing identity must have signed
|
|
236
|
+
* (DH identity ‖ signed prekey). Rejecting a bad signature is the MITM defense
|
|
237
|
+
* at X3DH first contact — an attacker who rewrites the bundle in transit cannot
|
|
238
|
+
* forge this without the peer's Ed25519 signing private key.
|
|
239
|
+
*
|
|
240
|
+
* NOTE: this authenticates the bundle UNDER its signing identity. Pinning that
|
|
241
|
+
* identity (safety numbers / TOFU) is a separate layer, tracked on 2342.
|
|
242
|
+
*/
|
|
243
|
+
export function verifyPublicBundle(bundle: PublicPrekeyBundle): boolean {
|
|
244
|
+
return verifyEd25519(
|
|
245
|
+
bundle.signature,
|
|
246
|
+
bundleSigningMessage(bundle.identityPublicKey, bundle.signedPrekey.publicKey),
|
|
247
|
+
bundle.signingIdentityPublicKey,
|
|
248
|
+
);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// ---- Envelope codec ----
|
|
252
|
+
|
|
253
|
+
interface E2eeEnvelope {
|
|
254
|
+
v: typeof E2EE_ENVELOPE_VERSION;
|
|
255
|
+
/** Handshake header — present only on the initiator's first message. */
|
|
256
|
+
hdr?: { ik: string; ek: string; opk?: number };
|
|
257
|
+
/** Ratchet message index (strict in-order). */
|
|
258
|
+
i: number;
|
|
259
|
+
ct: EncryptedPayload;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** v2 envelope: carries the DH ratchet header (dh/pn/n) instead of a flat index. */
|
|
263
|
+
interface E2eeEnvelopeV2 {
|
|
264
|
+
v: typeof E2EE_ENVELOPE_VERSION_V2;
|
|
265
|
+
hdr?: { ik: string; ek: string; opk?: number };
|
|
266
|
+
dh: string; // base64 ratchet public key
|
|
267
|
+
pn: number;
|
|
268
|
+
n: number;
|
|
269
|
+
ct: EncryptedPayload;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** Quick check whether on-wire bytes are an mDM E2EE envelope (v1 or v2). */
|
|
273
|
+
export function isE2eeEnvelope(bytes: Uint8Array): boolean {
|
|
274
|
+
try {
|
|
275
|
+
const obj = JSON.parse(Buffer.from(bytes).toString("utf8"));
|
|
276
|
+
if (!obj?.ct) return false;
|
|
277
|
+
if (obj.v === E2EE_ENVELOPE_VERSION) return typeof obj.i === "number";
|
|
278
|
+
if (obj.v === E2EE_ENVELOPE_VERSION_V2) return typeof obj.dh === "string" && typeof obj.n === "number";
|
|
279
|
+
return false;
|
|
280
|
+
} catch {
|
|
281
|
+
return false;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** Read the envelope version without validating the rest. */
|
|
286
|
+
function peekEnvelopeVersion(bytes: Uint8Array): string | undefined {
|
|
287
|
+
try {
|
|
288
|
+
return JSON.parse(Buffer.from(bytes).toString("utf8"))?.v;
|
|
289
|
+
} catch {
|
|
290
|
+
return undefined;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function serializeEnvelope(env: E2eeEnvelope | E2eeEnvelopeV2): Uint8Array {
|
|
295
|
+
return new Uint8Array(Buffer.from(JSON.stringify(env), "utf8"));
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function parseEnvelope(bytes: Uint8Array): E2eeEnvelope {
|
|
299
|
+
const obj = JSON.parse(Buffer.from(bytes).toString("utf8"));
|
|
300
|
+
if (obj?.v !== E2EE_ENVELOPE_VERSION) throw new Error(`Unsupported mDM envelope version: ${obj?.v}`);
|
|
301
|
+
return obj as E2eeEnvelope;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function parseEnvelopeV2(bytes: Uint8Array): E2eeEnvelopeV2 {
|
|
305
|
+
const obj = JSON.parse(Buffer.from(bytes).toString("utf8"));
|
|
306
|
+
if (obj?.v !== E2EE_ENVELOPE_VERSION_V2) throw new Error(`Unsupported mDM envelope version: ${obj?.v}`);
|
|
307
|
+
return obj as E2eeEnvelopeV2;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// ---- Publish ----
|
|
311
|
+
|
|
312
|
+
/** Serialize the local bundle and hand it to the provider's key directory. */
|
|
313
|
+
export async function publishOwnPrekeys(
|
|
314
|
+
keystore: MdmKeyStore,
|
|
315
|
+
dm: DmProvider,
|
|
316
|
+
): Promise<{ oneTimePrekeyCount: number }> {
|
|
317
|
+
const material = await keystore.getOwnMaterial();
|
|
318
|
+
await dm.publishPrekeyBundle(serializePublicBundle(material));
|
|
319
|
+
return { oneTimePrekeyCount: material.oneTimePrekeys.length };
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// ---- Encrypt (send) ----
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Seal `plaintext` for `peerId`, establishing an X3DH+ratchet session on first
|
|
326
|
+
* contact (fetching the peer's published bundle via the provider). Returns the
|
|
327
|
+
* opaque envelope bytes to hand to `dm.send`.
|
|
328
|
+
*/
|
|
329
|
+
export async function encryptForPeer(
|
|
330
|
+
keystore: MdmKeyStore,
|
|
331
|
+
dm: DmProvider,
|
|
332
|
+
peerId: string,
|
|
333
|
+
plaintext: Uint8Array,
|
|
334
|
+
): Promise<Uint8Array> {
|
|
335
|
+
let session = await keystore.getSession(peerId);
|
|
336
|
+
|
|
337
|
+
if (!session) {
|
|
338
|
+
const raw = await dm.fetchPrekeyBundle(peerId);
|
|
339
|
+
if (!raw) {
|
|
340
|
+
throw new Error(
|
|
341
|
+
`Peer "${peerId}" has not published a prekey bundle yet, so an encrypted session cannot be established. ` +
|
|
342
|
+
`Ask them to run mDM_publish_keys, or use mDM_send_unencrypted (deprecated) for the migration window.`,
|
|
343
|
+
);
|
|
344
|
+
}
|
|
345
|
+
const peer = parsePublicBundle(raw);
|
|
346
|
+
// MITM defense: reject a bundle whose self-signature doesn't verify before
|
|
347
|
+
// we derive any key material from it.
|
|
348
|
+
if (!verifyPublicBundle(peer)) {
|
|
349
|
+
throw new Error(
|
|
350
|
+
`Prekey bundle for "${peerId}" failed signature verification — refusing to start an ` +
|
|
351
|
+
`encrypted session (possible tampering / man-in-the-middle).`,
|
|
352
|
+
);
|
|
353
|
+
}
|
|
354
|
+
const own = await keystore.getOwnMaterial();
|
|
355
|
+
const ephemeral = await generateX25519KeyPair();
|
|
356
|
+
const opk = peer.oneTimePrekeys[0]; // pick one if offered
|
|
357
|
+
|
|
358
|
+
const { rootKey } = await performX3dh(own.identity.privateKey, ephemeral.privateKey, {
|
|
359
|
+
identityPublicKey: peer.identityPublicKey,
|
|
360
|
+
signedPreKeyPublicKey: peer.signedPrekey.publicKey,
|
|
361
|
+
oneTimePreKeyPublicKey: opk?.publicKey,
|
|
362
|
+
});
|
|
363
|
+
// New sessions use the DH ratchet (v2 / PCS). The initial remote ratchet key
|
|
364
|
+
// is the peer's signed prekey (the X3DH→DR handoff). LINEAR-3409.
|
|
365
|
+
const ratchet2 = await initRatchetInitiator(rootKey, peer.signedPrekey.publicKey);
|
|
366
|
+
session = {
|
|
367
|
+
ratchet2,
|
|
368
|
+
role: "initiator",
|
|
369
|
+
pendingHandshake: { ik: own.identity.publicKey, ek: ephemeral.publicKey, opkId: opk?.id },
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
// v2 (DH ratchet) path for new + v2 sessions.
|
|
374
|
+
if (session.ratchet2) {
|
|
375
|
+
const { header, ct } = await ratchetEncrypt(session.ratchet2, plaintext);
|
|
376
|
+
const env: E2eeEnvelopeV2 = {
|
|
377
|
+
v: E2EE_ENVELOPE_VERSION_V2,
|
|
378
|
+
dh: toBase64(header.dh),
|
|
379
|
+
pn: header.pn,
|
|
380
|
+
n: header.n,
|
|
381
|
+
ct,
|
|
382
|
+
};
|
|
383
|
+
if (session.pendingHandshake) {
|
|
384
|
+
env.hdr = {
|
|
385
|
+
ik: toBase64(session.pendingHandshake.ik),
|
|
386
|
+
ek: toBase64(session.pendingHandshake.ek),
|
|
387
|
+
opk: session.pendingHandshake.opkId,
|
|
388
|
+
};
|
|
389
|
+
session.pendingHandshake = undefined;
|
|
390
|
+
}
|
|
391
|
+
await keystore.putSession(peerId, session);
|
|
392
|
+
return serializeEnvelope(env);
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
// v1 (legacy symmetric) path — only for a session already established as v1.
|
|
396
|
+
const step = await ratchetSend(session.ratchet!);
|
|
397
|
+
const ct = await encryptBytes(step.messageKey, plaintext);
|
|
398
|
+
const env: E2eeEnvelope = { v: E2EE_ENVELOPE_VERSION, i: step.messageIndex, ct };
|
|
399
|
+
if (session.pendingHandshake && step.messageIndex === 0) {
|
|
400
|
+
env.hdr = {
|
|
401
|
+
ik: toBase64(session.pendingHandshake.ik),
|
|
402
|
+
ek: toBase64(session.pendingHandshake.ek),
|
|
403
|
+
opk: session.pendingHandshake.opkId,
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
session.pendingHandshake = undefined;
|
|
407
|
+
await keystore.putSession(peerId, session);
|
|
408
|
+
return serializeEnvelope(env);
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
// ---- Decrypt (receive) ----
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* Open an envelope from `peerId`, running X3DH (responder) on the first message
|
|
415
|
+
* to derive the shared root key. Returns the inner plaintext bytes.
|
|
416
|
+
*/
|
|
417
|
+
/** Run X3DH (responder side) from a first-contact handshake header → shared root key. */
|
|
418
|
+
async function responderRootKey(
|
|
419
|
+
keystore: MdmKeyStore,
|
|
420
|
+
hdr: { ik: string; ek: string; opk?: number },
|
|
421
|
+
): Promise<Uint8Array> {
|
|
422
|
+
const own = await keystore.getOwnMaterial();
|
|
423
|
+
let oneTimePreKeyPrivateKey: Uint8Array | undefined;
|
|
424
|
+
if (hdr.opk !== undefined) {
|
|
425
|
+
oneTimePreKeyPrivateKey = await keystore.takeOneTimePrekey(hdr.opk);
|
|
426
|
+
if (!oneTimePreKeyPrivateKey) {
|
|
427
|
+
throw new Error(`Handshake references one-time prekey ${hdr.opk} which is unknown or already consumed.`);
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
const { rootKey } = await performX3dhResponder(
|
|
431
|
+
{
|
|
432
|
+
identityPrivateKey: own.identity.privateKey,
|
|
433
|
+
signedPreKeyPrivateKey: own.signedPrekey.pair.privateKey,
|
|
434
|
+
oneTimePreKeyPrivateKey,
|
|
435
|
+
},
|
|
436
|
+
{
|
|
437
|
+
initiatorIdentityPublicKey: fromBase64(hdr.ik),
|
|
438
|
+
initiatorEphemeralPublicKey: fromBase64(hdr.ek),
|
|
439
|
+
usedOneTimePreKeyId: hdr.opk,
|
|
440
|
+
},
|
|
441
|
+
);
|
|
442
|
+
return rootKey;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
export async function decryptFromPeer(
|
|
446
|
+
keystore: MdmKeyStore,
|
|
447
|
+
peerId: string,
|
|
448
|
+
envelopeBytes: Uint8Array,
|
|
449
|
+
): Promise<Uint8Array> {
|
|
450
|
+
// v2 (DH ratchet / PCS) — LINEAR-3409.
|
|
451
|
+
if (peekEnvelopeVersion(envelopeBytes) === E2EE_ENVELOPE_VERSION_V2) {
|
|
452
|
+
const env = parseEnvelopeV2(envelopeBytes);
|
|
453
|
+
let session = await keystore.getSession(peerId);
|
|
454
|
+
if (!session) {
|
|
455
|
+
if (!env.hdr) {
|
|
456
|
+
throw new Error(`No session with "${peerId}" and the message carries no handshake header — cannot decrypt.`);
|
|
457
|
+
}
|
|
458
|
+
const rootKey = await responderRootKey(keystore, env.hdr);
|
|
459
|
+
const own = await keystore.getOwnMaterial();
|
|
460
|
+
const ratchet2 = await initRatchetResponder(rootKey, {
|
|
461
|
+
publicKey: own.signedPrekey.pair.publicKey,
|
|
462
|
+
privateKey: own.signedPrekey.pair.privateKey,
|
|
463
|
+
});
|
|
464
|
+
session = { ratchet2, role: "responder" };
|
|
465
|
+
}
|
|
466
|
+
if (!session.ratchet2) {
|
|
467
|
+
throw new Error(`Received a v2 mDM envelope but the session with "${peerId}" is v1 — refusing to mix ratchets.`);
|
|
468
|
+
}
|
|
469
|
+
const plaintext = await ratchetDecrypt(
|
|
470
|
+
session.ratchet2,
|
|
471
|
+
{ dh: fromBase64(env.dh), pn: env.pn, n: env.n },
|
|
472
|
+
env.ct,
|
|
473
|
+
);
|
|
474
|
+
await keystore.putSession(peerId, session);
|
|
475
|
+
return plaintext;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
// v1 (legacy symmetric) — back-compat decode.
|
|
479
|
+
const env = parseEnvelope(envelopeBytes);
|
|
480
|
+
let session = await keystore.getSession(peerId);
|
|
481
|
+
if (!session) {
|
|
482
|
+
if (!env.hdr) {
|
|
483
|
+
throw new Error(`No session with "${peerId}" and the message carries no handshake header — cannot decrypt.`);
|
|
484
|
+
}
|
|
485
|
+
const rootKey = await responderRootKey(keystore, env.hdr);
|
|
486
|
+
const ratchet = await initializeRatchet(rootKey, "responder");
|
|
487
|
+
session = { ratchet, role: "responder" };
|
|
488
|
+
}
|
|
489
|
+
if (!session.ratchet) {
|
|
490
|
+
throw new Error(`Received a v1 mDM envelope but the session with "${peerId}" is v2 — refusing to mix ratchets.`);
|
|
491
|
+
}
|
|
492
|
+
const step = await ratchetReceive(session.ratchet);
|
|
493
|
+
if (step.messageIndex !== env.i) {
|
|
494
|
+
throw new Error(
|
|
495
|
+
`Out-of-order mDM message (expected ratchet index ${step.messageIndex}, got ${env.i}). ` +
|
|
496
|
+
`Skipped-key handling is a tracked follow-up (LINEAR-2357).`,
|
|
497
|
+
);
|
|
498
|
+
}
|
|
499
|
+
const plaintext = await decryptBytes(step.messageKey, env.ct);
|
|
500
|
+
await keystore.putSession(peerId, session);
|
|
501
|
+
return plaintext;
|
|
502
|
+
}
|