fb-messenger-e2ee 0.1.1 → 0.1.2

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 (110) hide show
  1. package/README.md +27 -2
  2. package/dist/index.cjs +8811 -0
  3. package/dist/index.cjs.map +1 -0
  4. package/dist/index.d.cts +885 -0
  5. package/dist/index.d.ts +885 -0
  6. package/dist/index.js +8843 -0
  7. package/dist/index.js.map +1 -0
  8. package/package.json +19 -4
  9. package/bun.lock +0 -1014
  10. package/examples/basic-usage.ts +0 -52
  11. package/jest.config.ts +0 -18
  12. package/src/config/env.ts +0 -15
  13. package/src/controllers/client.controller.ts +0 -805
  14. package/src/controllers/dgw-handler.ts +0 -171
  15. package/src/controllers/e2ee-handler.ts +0 -832
  16. package/src/controllers/event-mapper.ts +0 -327
  17. package/src/core/client.ts +0 -151
  18. package/src/e2ee/application/e2ee-client.ts +0 -376
  19. package/src/e2ee/application/fanout-planner.ts +0 -79
  20. package/src/e2ee/application/outbound-message-cache.ts +0 -58
  21. package/src/e2ee/application/prekey-maintenance.ts +0 -55
  22. package/src/e2ee/application/retry-manager.ts +0 -156
  23. package/src/e2ee/facebook/facebook-protocol-utils.ts +0 -230
  24. package/src/e2ee/facebook/icdc-payload.ts +0 -31
  25. package/src/e2ee/index.ts +0 -76
  26. package/src/e2ee/internal.ts +0 -27
  27. package/src/e2ee/media/media-crypto.ts +0 -147
  28. package/src/e2ee/media/media-upload.ts +0 -90
  29. package/src/e2ee/message/builders/client-payload.ts +0 -54
  30. package/src/e2ee/message/builders/consumer-application.ts +0 -362
  31. package/src/e2ee/message/builders/message-application.ts +0 -64
  32. package/src/e2ee/message/builders/message-transport.ts +0 -84
  33. package/src/e2ee/message/codecs/protobuf-codecs.ts +0 -101
  34. package/src/e2ee/message/constants.ts +0 -4
  35. package/src/e2ee/message/message-builder.ts +0 -15
  36. package/src/e2ee/signal/prekey-manager.ts +0 -140
  37. package/src/e2ee/signal/signal-manager.ts +0 -365
  38. package/src/e2ee/store/device-json.ts +0 -47
  39. package/src/e2ee/store/device-repository.ts +0 -12
  40. package/src/e2ee/store/device-store.ts +0 -538
  41. package/src/e2ee/transport/binary/decoder.ts +0 -180
  42. package/src/e2ee/transport/binary/encoder.ts +0 -143
  43. package/src/e2ee/transport/binary/stanzas.ts +0 -97
  44. package/src/e2ee/transport/binary/tokens.ts +0 -64
  45. package/src/e2ee/transport/binary/wa-binary.ts +0 -8
  46. package/src/e2ee/transport/dgw/dgw-socket.ts +0 -345
  47. package/src/e2ee/transport/noise/noise-handshake.ts +0 -417
  48. package/src/e2ee/transport/noise/noise-socket.ts +0 -230
  49. package/src/index.ts +0 -34
  50. package/src/models/client.ts +0 -26
  51. package/src/models/config.ts +0 -14
  52. package/src/models/domain.ts +0 -299
  53. package/src/models/e2ee.ts +0 -295
  54. package/src/models/media.ts +0 -41
  55. package/src/models/messaging.ts +0 -88
  56. package/src/models/thread.ts +0 -69
  57. package/src/repositories/session.repository.ts +0 -20
  58. package/src/services/auth.service.ts +0 -55
  59. package/src/services/e2ee.service.ts +0 -174
  60. package/src/services/facebook-gateway.service.ts +0 -245
  61. package/src/services/icdc.service.ts +0 -177
  62. package/src/services/media.service.ts +0 -304
  63. package/src/services/messaging.service.ts +0 -28
  64. package/src/services/thread.service.ts +0 -199
  65. package/src/types/advanced-types.ts +0 -61
  66. package/src/types/fca-unofficial.d.ts +0 -212
  67. package/src/types/protocol-types.ts +0 -43
  68. package/src/utils/fca-utils.ts +0 -30
  69. package/src/utils/logger.ts +0 -24
  70. package/src/utils/mime.ts +0 -51
  71. package/tests/.env.example +0 -87
  72. package/tests/data/1x1.png +0 -0
  73. package/tests/data/example.txt +0 -1
  74. package/tests/data/file_example.mp3 +0 -0
  75. package/tests/data/file_example.mp4 +0 -0
  76. package/tests/integration.test.ts +0 -498
  77. package/tests/script/echo-e2ee.ts +0 -174
  78. package/tests/script/send-e2ee-media.ts +0 -227
  79. package/tests/script/send-e2ee-reaction.ts +0 -108
  80. package/tests/script/send-e2ee-unsend.ts +0 -115
  81. package/tests/script/send-typing.ts +0 -107
  82. package/tests/script/test-group-send.ts +0 -105
  83. package/tests/setup.ts +0 -3
  84. package/tests/types.test.ts +0 -57
  85. package/tests/unit/controllers/dgw-handler.test.ts +0 -60
  86. package/tests/unit/controllers/e2ee-handler.test.ts +0 -293
  87. package/tests/unit/controllers/event-mapper.test.ts +0 -252
  88. package/tests/unit/e2ee/application-helpers.test.ts +0 -418
  89. package/tests/unit/e2ee/device-store.test.ts +0 -126
  90. package/tests/unit/e2ee/facebook-protocol-utils.test.ts +0 -134
  91. package/tests/unit/e2ee/media-crypto.test.ts +0 -55
  92. package/tests/unit/e2ee/media-upload.test.ts +0 -60
  93. package/tests/unit/e2ee/message-builder.test.ts +0 -42
  94. package/tests/unit/e2ee/message-builders.test.ts +0 -230
  95. package/tests/unit/e2ee/noise-handshake.test.ts +0 -260
  96. package/tests/unit/e2ee/prekey-manager.test.ts +0 -55
  97. package/tests/unit/e2ee/wa-binary.test.ts +0 -127
  98. package/tests/unit/services/e2ee.service.test.ts +0 -101
  99. package/tests/unit/services/facebook-gateway.service.test.ts +0 -138
  100. package/tests/unit/services/media.service.test.ts +0 -169
  101. package/tests/unit/utils/fca-utils.test.ts +0 -48
  102. package/tsconfig.json +0 -19
  103. /package/{src/e2ee/message/proto → proto}/ArmadilloApplication.proto +0 -0
  104. /package/{src/e2ee/message/proto → proto}/ArmadilloICDC.proto +0 -0
  105. /package/{src/e2ee/message/proto → proto}/ConsumerApplication.proto +0 -0
  106. /package/{src/e2ee/message/proto → proto}/MessageApplication.proto +0 -0
  107. /package/{src/e2ee/message/proto → proto}/MessageTransport.proto +0 -0
  108. /package/{src/e2ee/message/proto → proto}/WACommon.proto +0 -0
  109. /package/{src/e2ee/message/proto → proto}/WAMediaTransport.proto +0 -0
  110. /package/{src/e2ee/message/proto → proto}/proto-writer.ts +0 -0
@@ -1,538 +0,0 @@
1
- /**
2
- * E2EE DeviceStore - Layer 5
3
- *
4
- * Persists all Signal Protocol key material to a JSON file.
5
- * JSON schema is compatible with bridge-go DeviceJSON so existing device
6
- * files can be imported without re-registration.
7
- *
8
- * Implements the @signalapp/libsignal-client store interfaces:
9
- * IdentityKeyStore, SessionStore, PreKeyStore, SignedPreKeyStore, SenderKeyStore
10
- */
11
-
12
- import { randomBytes } from "node:crypto";
13
- import { randomUUID } from "node:crypto";
14
- import {
15
- Direction,
16
- IdentityKeyPair,
17
- IdentityKeyStore,
18
- KyberPreKeyRecord,
19
- KyberPreKeyStore,
20
- PreKeyRecord,
21
- PreKeyStore,
22
- PrivateKey,
23
- ProtocolAddress,
24
- PublicKey,
25
- SenderKeyRecord,
26
- SenderKeyStore,
27
- SessionRecord,
28
- SessionStore,
29
- SignedPreKeyRecord,
30
- SignedPreKeyStore,
31
- } from "@signalapp/libsignal-client";
32
- import { logger } from "../../utils/logger.ts";
33
- import {
34
- DEVICE_STORE_SCHEMA_VERSION,
35
- base64RecordFromMap,
36
- decodeBase64,
37
- encodeBase64,
38
- mapFromBase64Record,
39
- migrateDeviceJSON,
40
- parseDeviceJSON,
41
- } from "./device-json.ts";
42
- import { readDeviceJSONFile, writeDeviceJSONFile } from "./device-repository.ts";
43
-
44
- /** Cast for strict libsignal params */
45
- const u8 = (b: Buffer | Uint8Array): Buffer => Buffer.isBuffer(b) ? b : Buffer.from(b.buffer, b.byteOffset, b.byteLength);
46
-
47
- import type { DeviceJSON, NoiseKeyPair, ProtocolAddressStr, SenderKeyId } from "../../models/e2ee.ts";
48
- export type { DeviceJSON, NoiseKeyPair, ProtocolAddressStr, SenderKeyId };
49
-
50
- // DeviceStore
51
-
52
- export class DeviceStore
53
- implements
54
- IdentityKeyStore,
55
- SessionStore,
56
- PreKeyStore,
57
- SignedPreKeyStore,
58
- SenderKeyStore,
59
- KyberPreKeyStore {
60
- private identities: Map<ProtocolAddressStr, Uint8Array> = new Map();
61
- private sessions: Map<ProtocolAddressStr, Uint8Array> = new Map();
62
- private preKeys: Map<number, Uint8Array> = new Map();
63
- private signedPreKeys: Map<number, Uint8Array> = new Map();
64
- private senderKeys: Map<SenderKeyId, Uint8Array> = new Map();
65
- private kyberKeys: Map<number, Uint8Array> = new Map();
66
-
67
- // Noise transport key (not Signal - used in Noise XX handshake)
68
- public noiseKeyPriv: Buffer;
69
-
70
- // Signal identity
71
- private identityKeyPriv: Buffer;
72
- public signedPreKeyPriv: Buffer;
73
- public signedPreKeyId: number;
74
- public signedPreKeySig: Buffer;
75
- public registrationId: number;
76
-
77
- // Messenger-specific
78
- public advSecretKey: Buffer;
79
- public facebookUUID: string;
80
- public jidUser?: string;
81
- public jidDevice?: number;
82
-
83
- public nextPreKeyId: number;
84
- // Test helper: when true, skip identity trust checks (TOFU bypass)
85
- public autoTrust: boolean = false;
86
-
87
- private readonly path: string;
88
- private onDataChanged?: (json: string) => void;
89
-
90
- private constructor(path: string) {
91
- this.path = path;
92
- // Will be populated by factory methods
93
- this.noiseKeyPriv = Buffer.alloc(32);
94
- this.identityKeyPriv = Buffer.alloc(32);
95
- this.signedPreKeyPriv = Buffer.alloc(32);
96
- this.signedPreKeyId = 1;
97
- this.signedPreKeySig = Buffer.alloc(64);
98
- this.registrationId = 0;
99
- this.advSecretKey = Buffer.alloc(32);
100
- this.facebookUUID = "";
101
- this.nextPreKeyId = 1;
102
- }
103
-
104
- // Factory methods
105
-
106
- /** Create or load from a JSON file path. */
107
- /** Persist the Messenger JID assigned to this registered E2EE device. */
108
- setJIDs(id1: string, id2: string): void {
109
- const jid = id1 || id2;
110
- const [userPart = "", server = ""] = jid.split("@");
111
- if (server !== "msgr" || !userPart) return;
112
-
113
- const colonIdx = userPart.indexOf(":");
114
- const dotIdx = userPart.indexOf(".");
115
- const userEnd = dotIdx !== -1 ? dotIdx : (colonIdx !== -1 ? colonIdx : userPart.length);
116
- const user = userPart.slice(0, userEnd) || userPart;
117
- const rawDevice = colonIdx !== -1
118
- ? userPart.slice(colonIdx + 1)
119
- : (dotIdx !== -1 ? userPart.slice(dotIdx + 1) : "0");
120
- const device = Number(rawDevice) || 0;
121
-
122
- let changed = false;
123
- if (user && this.jidUser !== user) {
124
- this.jidUser = user;
125
- changed = true;
126
- }
127
- if (device > 0 && this.jidDevice !== device) {
128
- this.jidDevice = device;
129
- changed = true;
130
- }
131
-
132
- if (changed) this.saveToFile();
133
- }
134
-
135
- static async fromFile(path: string): Promise<DeviceStore> {
136
- const ds = new DeviceStore(path);
137
- const json = readDeviceJSONFile(path);
138
- if (json) {
139
- await ds.loadJSON(json);
140
- } else {
141
- await ds.initNew();
142
- ds.saveToFile();
143
- }
144
- return ds;
145
- }
146
-
147
- /** Load from a JSON string (no file I/O). */
148
- static async fromData(
149
- json: string,
150
- onDataChanged?: (json: string) => void,
151
- ): Promise<DeviceStore> {
152
- const ds = new DeviceStore("");
153
- ds.onDataChanged = onDataChanged;
154
- await ds.loadJSON(parseDeviceJSON(json));
155
- return ds;
156
- }
157
-
158
- /** Create a fresh in-memory device (nothing persisted). */
159
- static async memoryOnly(): Promise<DeviceStore> {
160
- const ds = new DeviceStore("");
161
- await ds.initNew();
162
- return ds;
163
- }
164
-
165
- // Init / load
166
-
167
- private async initNew(): Promise<void> {
168
- const { PrivateKey: PK, IdentityKeyPair: IKP } = await import("@signalapp/libsignal-client");
169
-
170
- this.noiseKeyPriv = randomBytes(32);
171
-
172
- // Generate X25519 identity key
173
- const identityPriv = PK.generate();
174
- this.identityKeyPriv = Buffer.from(identityPriv.serialize());
175
-
176
- // Generate signed prekey (also X25519, signed by identity key)
177
- const signedPreKeyPriv = PK.generate();
178
- this.signedPreKeyPriv = Buffer.from(signedPreKeyPriv.serialize());
179
- this.signedPreKeyId = 1;
180
- // Sign the signed prekey public key using identity key
181
- this.signedPreKeySig = Buffer.from(
182
- identityPriv.sign(signedPreKeyPriv.getPublicKey().serialize()),
183
- );
184
-
185
- // Registration ID: random 14-bit uint (range 1–16380)
186
- const buf = randomBytes(2);
187
- this.registrationId = ((buf.readUInt16BE(0) & 0x3fff) || 1);
188
-
189
- this.advSecretKey = randomBytes(32);
190
- this.facebookUUID = randomUUID();
191
- logger.debug("DeviceStore", "Generated new Facebook UUID:", this.facebookUUID);
192
- this.nextPreKeyId = 1;
193
- }
194
-
195
- private async loadJSON(input: DeviceJSON): Promise<void> {
196
- const d = migrateDeviceJSON(input);
197
-
198
- this.noiseKeyPriv = decodeBase64(d.noise_key_priv);
199
- this.identityKeyPriv = decodeBase64(d.identity_key_priv);
200
- this.signedPreKeyPriv = decodeBase64(d.signed_pre_key_priv);
201
- this.signedPreKeyId = d.signed_pre_key_id;
202
- this.signedPreKeySig = decodeBase64(d.signed_pre_key_sig);
203
- this.registrationId = d.registration_id;
204
- this.advSecretKey = decodeBase64(d.adv_secret_key);
205
- this.facebookUUID = d.facebook_uuid;
206
- this.jidUser = d.jid_user;
207
- this.jidDevice = d.jid_device;
208
- this.nextPreKeyId = d.next_pre_key_id;
209
-
210
- this.identities = mapFromBase64Record(d.identities, (key) => key as ProtocolAddressStr);
211
- this.sessions = mapFromBase64Record(d.sessions, (key) => key as ProtocolAddressStr);
212
- this.preKeys = mapFromBase64Record(d.pre_keys, Number);
213
- this.senderKeys = mapFromBase64Record(d.sender_keys, (key) => key as SenderKeyId);
214
- this.signedPreKeys = mapFromBase64Record(d.signed_pre_keys, Number);
215
- }
216
-
217
- // Serialization
218
-
219
- toJSON(): DeviceJSON {
220
- const d: DeviceJSON = {
221
- schema_version: DEVICE_STORE_SCHEMA_VERSION,
222
- noise_key_priv: encodeBase64(this.noiseKeyPriv),
223
- identity_key_priv: encodeBase64(this.identityKeyPriv),
224
- signed_pre_key_priv: encodeBase64(this.signedPreKeyPriv),
225
- signed_pre_key_id: this.signedPreKeyId,
226
- signed_pre_key_sig: encodeBase64(this.signedPreKeySig),
227
- registration_id: this.registrationId,
228
- adv_secret_key: encodeBase64(this.advSecretKey),
229
- facebook_uuid: this.facebookUUID,
230
- next_pre_key_id: this.nextPreKeyId,
231
- identities: base64RecordFromMap(this.identities),
232
- sessions: base64RecordFromMap(this.sessions),
233
- pre_keys: base64RecordFromMap(this.preKeys),
234
- sender_keys: base64RecordFromMap(this.senderKeys),
235
- signed_pre_keys: base64RecordFromMap(this.signedPreKeys),
236
- };
237
- if (this.jidUser) d.jid_user = this.jidUser;
238
- if (this.jidDevice) d.jid_device = this.jidDevice;
239
- return d;
240
- }
241
-
242
- getData(): string {
243
- return JSON.stringify(this.toJSON(), null, 2);
244
- }
245
-
246
- saveToFile(): void {
247
- if (this.path) {
248
- writeDeviceJSONFile(this.path, this.getData());
249
- } else if (this.onDataChanged) {
250
- this.onDataChanged(this.getData());
251
- }
252
- }
253
-
254
- public getIdentityPublicKey(): Buffer {
255
- return Buffer.from(PrivateKey.deserialize(u8(this.identityKeyPriv)).getPublicKey().serialize()).subarray(1);
256
- }
257
-
258
- public getIdentityPrivateKey(): Buffer {
259
- return this.identityKeyPriv;
260
- }
261
-
262
- public getSignedPreKeyPublicKey(): Buffer {
263
- return Buffer.from(PrivateKey.deserialize(u8(this.signedPreKeyPriv)).getPublicKey().serialize()).subarray(1);
264
- }
265
-
266
- // libsignal IdentityKeyStore
267
-
268
- async getIdentityKey(): Promise<PrivateKey> {
269
- return PrivateKey.deserialize(u8(this.identityKeyPriv));
270
- }
271
-
272
- async _getIdentityKey(): Promise<any> {
273
- const key = PrivateKey.deserialize(u8(this.identityKeyPriv));
274
- return (key as any)._nativeHandle;
275
- }
276
-
277
- async getLocalRegistrationId(): Promise<number> {
278
- return this.registrationId;
279
- }
280
-
281
- async _getLocalRegistrationId(): Promise<number> {
282
- return this.registrationId;
283
- }
284
-
285
- async _saveIdentity(name: any, key: any): Promise<boolean> {
286
- return this.saveIdentity(
287
- ProtocolAddress._fromNativeHandle(name),
288
- PublicKey._fromNativeHandle(key),
289
- );
290
- }
291
-
292
- async saveIdentity(name: ProtocolAddress, key: PublicKey): Promise<boolean> {
293
- const addr = name.toString() as ProtocolAddressStr;
294
- const existing = this.identities.get(addr);
295
- const keyBytes = key.serialize();
296
- const changed = existing == null || !Buffer.from(existing).equals(Buffer.from(keyBytes));
297
- this.identities.set(addr, new Uint8Array(keyBytes));
298
- this.saveToFile();
299
- return changed;
300
- }
301
-
302
- async isTrustedIdentity(
303
- name: ProtocolAddress,
304
- key: PublicKey,
305
- _direction: Direction,
306
- ): Promise<boolean> {
307
- if (this.autoTrust) return true;
308
- const addr = name.toString();
309
- const existing = this.identities.get(addr as ProtocolAddressStr);
310
- if (existing == null) return true; // First use -> trust on first use (TOFU)
311
- return Buffer.from(existing).equals(Buffer.from(key.serialize()));
312
- }
313
-
314
- async _isTrustedIdentity(name: any, key: any, sending: boolean): Promise<boolean> {
315
- // Synchronous version for Rust bridge
316
- const addr = ProtocolAddress._fromNativeHandle(name).toString();
317
- if (this.autoTrust) return true;
318
- const existing = this.identities.get(addr as ProtocolAddressStr);
319
- if (existing == null) return true;
320
- const pub = PublicKey._fromNativeHandle(key);
321
- return Buffer.from(existing).equals(Buffer.from(pub.serialize()));
322
- }
323
-
324
- async getIdentity(name: ProtocolAddress): Promise<PublicKey | null> {
325
- const bytes = this.identities.get(name.toString() as ProtocolAddressStr);
326
- if (!bytes) return null;
327
- return PublicKey.deserialize(Buffer.from(bytes));
328
- }
329
-
330
- async _getIdentity(name: any): Promise<any> {
331
- const key = await this.getIdentity(ProtocolAddress._fromNativeHandle(name));
332
- return key ? (key as any)._nativeHandle : null;
333
- }
334
-
335
- // libsignal SessionStore
336
-
337
- async saveSession(name: ProtocolAddress, record: SessionRecord): Promise<void> {
338
- this.sessions.set(name.toString() as ProtocolAddressStr, record.serialize());
339
- this.saveToFile();
340
- }
341
-
342
- async _saveSession(name: any, record: any): Promise<void> {
343
- return this.saveSession(
344
- ProtocolAddress._fromNativeHandle(name),
345
- SessionRecord._fromNativeHandle(record),
346
- );
347
- }
348
-
349
- async getSession(name: ProtocolAddress): Promise<SessionRecord | null> {
350
- const bytes = this.sessions.get(name.toString() as ProtocolAddressStr);
351
- if (!bytes) return null;
352
- return SessionRecord.deserialize(Buffer.from(bytes));
353
- }
354
-
355
- async _getSession(name: any): Promise<any> {
356
- const r = await this.getSession(ProtocolAddress._fromNativeHandle(name));
357
- return r ? (r as any)._nativeHandle : null;
358
- }
359
-
360
- async getExistingSessions(addresses: ProtocolAddress[]): Promise<SessionRecord[]> {
361
- const records: SessionRecord[] = [];
362
- for (const addr of addresses) {
363
- const r = await this.getSession(addr);
364
- if (r) records.push(r);
365
- }
366
- return records;
367
- }
368
-
369
- // libsignal PreKeyStore
370
-
371
- async savePreKey(id: number, record: PreKeyRecord): Promise<void> {
372
- logger.debug("DeviceStore", `savePreKey: ID=${id}`);
373
- this.preKeys.set(id, record.serialize());
374
- this.saveToFile();
375
- }
376
-
377
- async _savePreKey(id: number, record: any): Promise<void> {
378
- return this.savePreKey(id, PreKeyRecord._fromNativeHandle(record));
379
- }
380
-
381
- async getPreKey(id: number): Promise<PreKeyRecord> {
382
- const bytes = this.preKeys.get(id);
383
- if (!bytes) throw new Error(`PreKey ${id} not found`);
384
- return PreKeyRecord.deserialize(Buffer.from(bytes));
385
- }
386
-
387
- async _getPreKey(id: number): Promise<any> {
388
- const r = await this.getPreKey(id);
389
- return (r as any)._nativeHandle;
390
- }
391
-
392
- async removePreKey(id: number): Promise<void> {
393
- this.preKeys.delete(id);
394
- this.saveToFile();
395
- }
396
-
397
- async _removePreKey(id: number): Promise<void> {
398
- return this.removePreKey(id);
399
- }
400
-
401
- // libsignal SignedPreKeyStore
402
-
403
- async saveSignedPreKey(id: number, record: SignedPreKeyRecord): Promise<void> {
404
- this.signedPreKeys.set(id, Buffer.from(record.serialize()));
405
- this.signedPreKeyId = id; // Keep track of latest
406
- this.saveToFile();
407
- }
408
-
409
- async _saveSignedPreKey(id: number, record: any): Promise<void> {
410
- return this.saveSignedPreKey(id, SignedPreKeyRecord._fromNativeHandle(record));
411
- }
412
-
413
- async getSignedPreKey(id: number): Promise<SignedPreKeyRecord> {
414
- logger.debug("DeviceStore", `getSignedPreKey called for ID: ${id} (type: ${typeof id})`);
415
- logger.debug("DeviceStore", `Current signedPreKeys IDs:`, Array.from(this.signedPreKeys.keys()));
416
- const bytes = this.signedPreKeys.get(id);
417
- if (!bytes) {
418
- logger.debug("DeviceStore", `Key ${id} not found in map.`);
419
- // Fallback for transition if we only have the old fields
420
- if (id === this.signedPreKeyId && this.signedPreKeyPriv && this.signedPreKeySig) {
421
- logger.debug("DeviceStore", `Using fallback for key ${id}`);
422
- const priv = PrivateKey.deserialize(u8(this.signedPreKeyPriv));
423
- return SignedPreKeyRecord.new(
424
- this.signedPreKeyId,
425
- 0,
426
- priv.getPublicKey(),
427
- priv,
428
- u8(this.signedPreKeySig),
429
- );
430
- }
431
- throw new Error(`SignedPreKey ${id} not found`);
432
- }
433
- return SignedPreKeyRecord.deserialize(u8(bytes));
434
- }
435
-
436
- async _getSignedPreKey(id: number): Promise<any> {
437
- const r = await this.getSignedPreKey(id);
438
- return (r as any)._nativeHandle;
439
- }
440
-
441
- // libsignal SenderKeyStore
442
-
443
-
444
- async saveSenderKey(senderAddress: ProtocolAddress, distributionId: string, record: SenderKeyRecord): Promise<void> {
445
- const key = `${senderAddress.toString()}::${distributionId}`;
446
- logger.debug("DeviceStore", `saveSenderKey: ${key}`);
447
- this.senderKeys.set(key as SenderKeyId, record.serialize());
448
- this.saveToFile();
449
- }
450
-
451
- async _saveSenderKey(sender: any, distributionId: any, record: any): Promise<void> {
452
- return this.saveSenderKey(
453
- ProtocolAddress._fromNativeHandle(sender),
454
- distributionId.toString(),
455
- SenderKeyRecord._fromNativeHandle(record),
456
- );
457
- }
458
-
459
- async getSenderKey(senderAddress: ProtocolAddress, distributionId: string): Promise<SenderKeyRecord> {
460
- const key = `${senderAddress.toString()}::${distributionId}`;
461
- const bytes = this.senderKeys.get(key as SenderKeyId);
462
- logger.debug("DeviceStore", `getSenderKey: ${key}, found=${!!bytes}`);
463
- if (!bytes) return null as any;
464
- return SenderKeyRecord.deserialize(Buffer.from(bytes));
465
- }
466
-
467
- listSenderKeyDistributionIds(senderAddress: ProtocolAddress): string[] {
468
- const prefix = `${senderAddress.toString()}::`;
469
- const distributionIds: string[] = [];
470
- for (const key of this.senderKeys.keys()) {
471
- const keyString = String(key);
472
- if (keyString.startsWith(prefix)) {
473
- distributionIds.push(keyString.slice(prefix.length));
474
- }
475
- }
476
- return distributionIds;
477
- }
478
-
479
- async _getSenderKey(sender: any, distributionId: any): Promise<any> {
480
- const r = await this.getSenderKey(
481
- ProtocolAddress._fromNativeHandle(sender),
482
- distributionId.toString(),
483
- );
484
- return r ? (r as any)._nativeHandle : null;
485
- }
486
-
487
- // libsignal KyberPreKeyStore (Memory only - Messenger doesn't use Kyber)
488
-
489
- async saveKyberPreKey(id: number, record: KyberPreKeyRecord): Promise<void> {
490
- this.kyberKeys.set(id, Buffer.from(record.serialize()));
491
- }
492
-
493
- async _saveKyberPreKey(id: number, record: any): Promise<void> {
494
- return this.saveKyberPreKey(id, KyberPreKeyRecord._fromNativeHandle(record));
495
- }
496
-
497
- async getKyberPreKey(id: number): Promise<KyberPreKeyRecord> {
498
- const data = this.kyberKeys.get(id);
499
- if (!data) throw new Error(`Kyber pre-key ${id} not found`);
500
- return KyberPreKeyRecord.deserialize(u8(data));
501
- }
502
-
503
- async _getKyberPreKey(id: number): Promise<any> {
504
- const r = await this.getKyberPreKey(id);
505
- return (r as any)._nativeHandle;
506
- }
507
-
508
- async markKyberPreKeyUsed(id: number): Promise<void> {
509
- this.kyberKeys.delete(id);
510
- }
511
-
512
- async _markKyberPreKeyUsed(id: number): Promise<void> {
513
- return this.markKyberPreKeyUsed(id);
514
- }
515
-
516
- // Convenience: build IdentityKeyPair for libsignal operations
517
-
518
- async getIdentityKeyPair(): Promise<IdentityKeyPair> {
519
- // getIdentityKeyPair() is a concrete method in IdentityKeyStore base class
520
- // that calls getIdentityKey() - replicate it here since we use implements
521
- const priv = await this.getIdentityKey();
522
- return new IdentityKeyPair(priv.getPublicKey(), priv);
523
- }
524
-
525
- /** Get a fresh unused prekey ID and bump the counter */
526
- allocPreKeyId(): number {
527
- return this.nextPreKeyId++;
528
- }
529
-
530
- /** True if store has an established session for this address */
531
- hasSession(address: string): boolean {
532
- return this.sessions.has(address as ProtocolAddressStr);
533
- }
534
-
535
- getPreKeyCount(): number {
536
- return this.preKeys.size;
537
- }
538
- }