@freesignal/protocol 0.3.0 → 0.4.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/double-ratchet.js DELETED
@@ -1,352 +0,0 @@
1
- "use strict";
2
- /**
3
- * FreeSignal Protocol
4
- *
5
- * Copyright (C) 2025 Christian Braghette
6
- *
7
- * This program is free software: you can redistribute it and/or modify
8
- * it under the terms of the GNU General Public License as published by
9
- * the Free Software Foundation, either version 3 of the License, or
10
- * (at your option) any later version.
11
- *
12
- * This program is distributed in the hope that it will be useful,
13
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
- * GNU General Public License for more details.
16
- *
17
- * You should have received a copy of the GNU General Public License
18
- * along with this program. If not, see <https://www.gnu.org/licenses/>
19
- */
20
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
21
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
22
- return new (P || (P = Promise))(function (resolve, reject) {
23
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
24
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
25
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
26
- step((generator = generator.apply(thisArg, _arguments || [])).next());
27
- });
28
- };
29
- var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
30
- if (value !== null && value !== void 0) {
31
- if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
32
- var dispose, inner;
33
- if (async) {
34
- if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
35
- dispose = value[Symbol.asyncDispose];
36
- }
37
- if (dispose === void 0) {
38
- if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
39
- dispose = value[Symbol.dispose];
40
- if (async) inner = dispose;
41
- }
42
- if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
43
- if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
44
- env.stack.push({ value: value, dispose: dispose, async: async });
45
- }
46
- else if (async) {
47
- env.stack.push({ async: true });
48
- }
49
- return value;
50
- };
51
- var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
52
- return function (env) {
53
- function fail(e) {
54
- env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
55
- env.hasError = true;
56
- }
57
- var r, s = 0;
58
- function next() {
59
- while (r = env.stack.pop()) {
60
- try {
61
- if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
62
- if (r.dispose) {
63
- var result = r.dispose.call(r.value);
64
- if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
65
- }
66
- else s |= 1;
67
- }
68
- catch (e) {
69
- fail(e);
70
- }
71
- }
72
- if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
73
- if (env.hasError) throw env.error;
74
- }
75
- return next();
76
- };
77
- })(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
78
- var e = new Error(message);
79
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
80
- });
81
- var __importDefault = (this && this.__importDefault) || function (mod) {
82
- return (mod && mod.__esModule) ? mod : { "default": mod };
83
- };
84
- Object.defineProperty(exports, "__esModule", { value: true });
85
- exports.EncryptedDataConstructor = exports.KeySession = void 0;
86
- const crypto_1 = __importDefault(require("@freesignal/crypto"));
87
- const utils_1 = require("@freesignal/utils");
88
- const types_1 = require("./types");
89
- const semaphore_ts_1 = require("semaphore.ts");
90
- /**
91
- * Represents a secure Double Ratchet session.
92
- * Used for forward-secure encryption and decryption of messages.
93
- */
94
- class KeySession {
95
- constructor(storage, opts = {}) {
96
- var _a;
97
- this.mutex = new semaphore_ts_1.AsyncMutex();
98
- this.previousKeys = new KeyMap();
99
- this.id = (_a = opts.id) !== null && _a !== void 0 ? _a : crypto_1.default.UUID.generate().toString();
100
- this.keyPair = crypto_1.default.ECDH.keyPair(opts.secretKey);
101
- if (opts.rootKey)
102
- this.rootKey = opts.rootKey;
103
- if (opts.remoteKey) {
104
- this.sendingChain = this.getChain(opts.remoteKey);
105
- }
106
- this.storage = storage;
107
- this.save();
108
- }
109
- getChain(remoteKey, previousCount) {
110
- const sharedKey = crypto_1.default.ECDH.scalarMult(this.keyPair.secretKey, remoteKey);
111
- if (!this.rootKey)
112
- this.rootKey = crypto_1.default.hash(sharedKey);
113
- const hashkey = crypto_1.default.hkdf(sharedKey, this.rootKey, KeySession.info, KeySession.keyLength * 2);
114
- this.rootKey = hashkey.subarray(0, KeySession.keyLength);
115
- return new KeyChain(this.publicKey, remoteKey, hashkey.subarray(KeySession.keyLength), previousCount);
116
- }
117
- save() {
118
- return this.storage.set(this.id, this.toJSON());
119
- }
120
- /**
121
- * Encrypts a message payload using the current sending chain.
122
- *
123
- * @param message - The message as a Uint8Array.
124
- * @returns An EncryptedPayload or undefined if encryption fails.
125
- */
126
- encrypt(message) {
127
- return __awaiter(this, void 0, void 0, function* () {
128
- const env_1 = { stack: [], error: void 0, hasError: false };
129
- try {
130
- const lock = __addDisposableResource(env_1, yield this.mutex.acquire(), false);
131
- if (!this.sendingChain)
132
- throw new Error("SendingChain not initialized");
133
- const key = this.sendingChain.getKey();
134
- const nonce = crypto_1.default.randomBytes(EncryptedDataConstructor.nonceLength);
135
- const ciphertext = crypto_1.default.box.encrypt(message, nonce, key);
136
- yield this.save();
137
- return new EncryptedDataConstructor(this.sendingChain.count, this.sendingChain.previousCount, this.keyPair.publicKey, nonce, ciphertext);
138
- }
139
- catch (e_1) {
140
- env_1.error = e_1;
141
- env_1.hasError = true;
142
- }
143
- finally {
144
- __disposeResources(env_1);
145
- }
146
- });
147
- }
148
- /**
149
- * Decrypts an encrypted message.
150
- *
151
- * @param payload - The received encrypted message.
152
- * @returns The decrypted message as a Uint8Array, or undefined if decryption fails.
153
- */
154
- decrypt(payload) {
155
- return __awaiter(this, void 0, void 0, function* () {
156
- var _a, _b, _c;
157
- const env_2 = { stack: [], error: void 0, hasError: false };
158
- try {
159
- const lock = __addDisposableResource(env_2, yield this.mutex.acquire(), false);
160
- const encrypted = types_1.EncryptedData.from(payload);
161
- if (!(0, utils_1.verifyArrays)(encrypted.publicKey, (_b = (_a = this.receivingChain) === null || _a === void 0 ? void 0 : _a.remoteKey) !== null && _b !== void 0 ? _b : new Uint8Array())) {
162
- while (this.receivingChain && this.receivingChain.count < encrypted.previous) {
163
- const key = this.receivingChain.getKey();
164
- this.previousKeys.set((0, utils_1.decodeBase64)(this.receivingChain.remoteKey) + this.receivingChain.count.toString(), key);
165
- }
166
- this.receivingChain = this.getChain(encrypted.publicKey);
167
- this.keyPair = crypto_1.default.ECDH.keyPair();
168
- this.sendingChain = this.getChain(encrypted.publicKey, (_c = this.sendingChain) === null || _c === void 0 ? void 0 : _c.count);
169
- }
170
- if (!this.receivingChain)
171
- throw new Error("Error initializing receivingChain");
172
- while (this.receivingChain.count < encrypted.count) {
173
- const key = this.receivingChain.getKey();
174
- this.previousKeys.set((0, utils_1.decodeBase64)(this.receivingChain.remoteKey) + this.receivingChain.count.toString(), key);
175
- }
176
- const key = this.previousKeys.get((0, utils_1.decodeBase64)(encrypted.publicKey) + encrypted.count.toString());
177
- if (!key)
178
- throw new Error("Error calculating key");
179
- yield this.save();
180
- const cleartext = crypto_1.default.box.decrypt(encrypted.ciphertext, encrypted.nonce, key);
181
- if (!cleartext)
182
- throw new Error("Error decrypting ciphertext");
183
- return cleartext;
184
- }
185
- catch (e_2) {
186
- env_2.error = e_2;
187
- env_2.hasError = true;
188
- }
189
- finally {
190
- __disposeResources(env_2);
191
- }
192
- });
193
- }
194
- /**
195
- * Whether both the sending and receiving chains are initialized.
196
- */
197
- get handshaked() { return this.sendingChain && this.receivingChain ? true : false; }
198
- /**
199
- * The public key of this session.
200
- */
201
- get publicKey() { return this.keyPair.publicKey; }
202
- /**
203
- * Export the state of the session;
204
- */
205
- toJSON() {
206
- var _a, _b;
207
- return {
208
- secretKey: (0, utils_1.decodeBase64)(this.keyPair.secretKey),
209
- rootKey: this.rootKey ? (0, utils_1.decodeBase64)(this.rootKey) : undefined,
210
- sendingChain: (_a = this.sendingChain) === null || _a === void 0 ? void 0 : _a.toJSON(),
211
- receivingChain: (_b = this.receivingChain) === null || _b === void 0 ? void 0 : _b.toJSON(),
212
- previousKeys: Array.from(this.previousKeys.entries())
213
- };
214
- }
215
- /**
216
- * Import a state.
217
- *
218
- * @param json string returned by `export()` method.
219
- * @returns session with the state parsed.
220
- */
221
- static from(data, storage) {
222
- const session = new KeySession(storage, { secretKey: (0, utils_1.encodeBase64)(data.secretKey), rootKey: data.rootKey ? (0, utils_1.encodeBase64)(data.rootKey) : undefined });
223
- //session._remoteKey = data.remoteKey ? encodeBase64(data.remoteKey) : undefined;
224
- session.sendingChain = data.sendingChain ? KeyChain.from(data.sendingChain) : undefined;
225
- session.receivingChain = data.receivingChain ? KeyChain.from(data.receivingChain) : undefined;
226
- session.previousKeys = new KeyMap(data.previousKeys);
227
- session.save();
228
- return session;
229
- }
230
- }
231
- exports.KeySession = KeySession;
232
- KeySession.keyLength = 32;
233
- KeySession.version = 1;
234
- KeySession.info = "/freesignal/double-ratchet/v0." + KeySession.version;
235
- class KeyChain {
236
- constructor(publicKey, remoteKey, chainKey, previousCount = 0) {
237
- this.publicKey = publicKey;
238
- this.remoteKey = remoteKey;
239
- this.chainKey = chainKey;
240
- this.previousCount = previousCount;
241
- this._count = 0;
242
- }
243
- getKey() {
244
- if (++this._count >= EncryptedDataConstructor.maxCount)
245
- throw new Error("SendingChain count too big");
246
- const hash = crypto_1.default.hkdf(this.chainKey, new Uint8Array(KeySession.keyLength).fill(0), KeySession.info, KeySession.keyLength * 2);
247
- this.chainKey = hash.subarray(0, KeySession.keyLength);
248
- return hash.subarray(KeySession.keyLength);
249
- }
250
- toString() {
251
- return "[object KeyChain]";
252
- }
253
- get count() {
254
- return this._count;
255
- }
256
- toJSON() {
257
- return {
258
- publicKey: (0, utils_1.decodeBase64)(this.publicKey),
259
- remoteKey: (0, utils_1.decodeBase64)(this.remoteKey),
260
- chainKey: (0, utils_1.decodeBase64)(this.chainKey),
261
- count: this.count,
262
- previousCount: this.previousCount
263
- };
264
- }
265
- static from(obj) {
266
- const chain = new KeyChain((0, utils_1.encodeBase64)(obj.publicKey), (0, utils_1.encodeBase64)(obj.remoteKey), (0, utils_1.encodeBase64)(obj.chainKey), obj.previousCount);
267
- chain._count = obj.count;
268
- return chain;
269
- }
270
- }
271
- class EncryptedDataConstructor {
272
- constructor(...arrays) {
273
- arrays = arrays.filter(value => value !== undefined);
274
- if (arrays[0] instanceof EncryptedDataConstructor) {
275
- this.raw = arrays[0].raw;
276
- return this;
277
- }
278
- if (typeof arrays[0] === 'number')
279
- arrays[0] = (0, utils_1.numberToArray)(arrays[0], EncryptedDataConstructor.countLength);
280
- if (typeof arrays[1] === 'number')
281
- arrays[1] = (0, utils_1.numberToArray)(arrays[1], EncryptedDataConstructor.countLength);
282
- if (arrays.length === 6) {
283
- arrays.unshift(typeof arrays[5] === 'number' ? (0, utils_1.numberToArray)(arrays[5]) : arrays[5]);
284
- arrays.pop();
285
- }
286
- else if (arrays.length > 1) {
287
- arrays.unshift((0, utils_1.numberToArray)(KeySession.version));
288
- }
289
- this.raw = (0, utils_1.concatArrays)(...arrays);
290
- }
291
- get length() { return this.raw.length; }
292
- get version() { return (0, utils_1.numberFromArray)(new Uint8Array(this.raw.buffer, ...Offsets.version.get)); }
293
- get count() { return (0, utils_1.numberFromArray)(new Uint8Array(this.raw.buffer, ...Offsets.count.get)); }
294
- get previous() { return (0, utils_1.numberFromArray)(new Uint8Array(this.raw.buffer, ...Offsets.previous.get)); }
295
- get publicKey() { return new Uint8Array(this.raw.buffer, ...Offsets.publicKey.get); }
296
- get nonce() { return new Uint8Array(this.raw.buffer, ...Offsets.nonce.get); }
297
- get ciphertext() { return new Uint8Array(this.raw.buffer, Offsets.ciphertext.start); }
298
- toBytes() {
299
- return this.raw;
300
- }
301
- toString() {
302
- return (0, utils_1.decodeBase64)(this.raw);
303
- }
304
- toJSON() {
305
- return {
306
- version: this.version,
307
- count: this.count,
308
- previous: this.previous,
309
- publicKey: (0, utils_1.decodeBase64)(this.publicKey),
310
- nonce: (0, utils_1.decodeBase64)(this.nonce),
311
- ciphertext: (0, utils_1.decodeBase64)(this.ciphertext)
312
- };
313
- }
314
- }
315
- exports.EncryptedDataConstructor = EncryptedDataConstructor;
316
- EncryptedDataConstructor.secretKeyLength = crypto_1.default.ECDH.secretKeyLength;
317
- EncryptedDataConstructor.publicKeyLength = crypto_1.default.ECDH.publicKeyLength;
318
- EncryptedDataConstructor.keyLength = crypto_1.default.box.keyLength;
319
- EncryptedDataConstructor.nonceLength = crypto_1.default.box.nonceLength;
320
- EncryptedDataConstructor.maxCount = 65536; //32768;
321
- EncryptedDataConstructor.countLength = 2;
322
- class Offsets {
323
- static set(start, length) {
324
- class Offset {
325
- constructor(start, length) {
326
- this.start = start;
327
- this.length = length;
328
- if (typeof length === 'number')
329
- this.end = start + length;
330
- }
331
- get get() {
332
- return [this.start, this.length];
333
- }
334
- }
335
- return new Offset(start, length);
336
- }
337
- }
338
- Offsets.checksum = Offsets.set(0, 0);
339
- Offsets.version = Offsets.set(Offsets.checksum.end, 1);
340
- Offsets.count = Offsets.set(Offsets.version.end, EncryptedDataConstructor.countLength);
341
- Offsets.previous = Offsets.set(Offsets.count.end, EncryptedDataConstructor.countLength);
342
- Offsets.publicKey = Offsets.set(Offsets.previous.end, EncryptedDataConstructor.publicKeyLength);
343
- Offsets.nonce = Offsets.set(Offsets.publicKey.end, EncryptedDataConstructor.nonceLength);
344
- Offsets.ciphertext = Offsets.set(Offsets.nonce.end, undefined);
345
- class KeyMap extends Map {
346
- get(key) {
347
- const out = super.get(key);
348
- if (out && !super.delete(key))
349
- throw new Error();
350
- return out;
351
- }
352
- }
package/node.d.ts DELETED
@@ -1,38 +0,0 @@
1
- import { Database, LocalStorage, Crypto, KeyExchangeDataBundle, KeyExchangeData } from "@freesignal/interfaces";
2
- import { Datagram, IdentityKey, PrivateIdentityKey, Protocols, UserId } from "./types";
3
- import { KeyExchange } from "./x3dh";
4
- import { ExportedKeySession, KeySession } from "./double-ratchet";
5
- export declare class FreeSignalNode {
6
- protected readonly privateIdentityKey: PrivateIdentityKey;
7
- protected readonly sessions: SessionMap;
8
- protected readonly users: LocalStorage<string, IdentityKey>;
9
- protected readonly keyExchange: KeyExchange;
10
- constructor(storage: Database<{
11
- sessions: LocalStorage<string, ExportedKeySession>;
12
- keyExchange: LocalStorage<string, Crypto.KeyPair>;
13
- users: LocalStorage<string, IdentityKey>;
14
- }>, privateIdentityKey?: PrivateIdentityKey);
15
- get userId(): UserId;
16
- get identityKey(): IdentityKey;
17
- generateKeyData(): Promise<KeyExchangeData>;
18
- generateKeyBundle(length?: number): Promise<KeyExchangeDataBundle>;
19
- encrypt(receiverId: string, protocol: Protocols, data: Uint8Array): Promise<Datagram>;
20
- sendHandshake(data: KeyExchangeData): Promise<Datagram>;
21
- sendData<T>(receiverId: string, data: T): Promise<Datagram>;
22
- sendRelay(receiverId: string, data: Datagram): Promise<Datagram>;
23
- sendDiscover(receiverId: string, discoverId: string): Promise<Datagram>;
24
- decrypt(datagram: Datagram): Promise<Uint8Array>;
25
- receive<T extends Uint8Array | UserId | Datagram | UserId | void>(datagram: Datagram | Uint8Array): Promise<T>;
26
- }
27
- declare class SessionMap implements LocalStorage<string, KeySession> {
28
- readonly storage: LocalStorage<string, ExportedKeySession>;
29
- readonly maxSize: number;
30
- private readonly cache;
31
- constructor(storage: LocalStorage<string, ExportedKeySession>, maxSize?: number);
32
- set(key: string, value: KeySession): Promise<void>;
33
- get(key: string): Promise<KeySession | undefined>;
34
- has(key: string): Promise<boolean>;
35
- delete(key: string): Promise<boolean>;
36
- clear(): Promise<void>;
37
- }
38
- export {};
package/node.js DELETED
@@ -1,139 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.FreeSignalNode = void 0;
13
- const types_1 = require("./types");
14
- const x3dh_1 = require("./x3dh");
15
- const double_ratchet_1 = require("./double-ratchet");
16
- const _1 = require(".");
17
- const utils_1 = require("@freesignal/utils");
18
- class FreeSignalNode {
19
- constructor(storage, privateIdentityKey) {
20
- this.privateIdentityKey = privateIdentityKey !== null && privateIdentityKey !== void 0 ? privateIdentityKey : (0, _1.createIdentity)();
21
- this.sessions = new SessionMap(storage.sessions);
22
- this.keyExchange = new x3dh_1.KeyExchange({ keys: storage.keyExchange, sessions: storage.sessions }, this.privateIdentityKey);
23
- this.users = storage.users;
24
- }
25
- get userId() {
26
- return types_1.UserId.fromKey(this.privateIdentityKey.identityKey);
27
- }
28
- get identityKey() {
29
- return this.privateIdentityKey.identityKey;
30
- }
31
- generateKeyData() {
32
- return this.keyExchange.generateData();
33
- }
34
- ;
35
- generateKeyBundle(length) {
36
- return this.keyExchange.generateBundle(length);
37
- }
38
- ;
39
- encrypt(receiverId, protocol, data) {
40
- return __awaiter(this, void 0, void 0, function* () {
41
- const session = yield this.sessions.get(receiverId);
42
- if (!session)
43
- throw new Error("Session not found for user: " + receiverId);
44
- return new types_1.Datagram(this.userId.toString(), receiverId, protocol, yield session.encrypt(data));
45
- });
46
- }
47
- sendHandshake(data) {
48
- return __awaiter(this, void 0, void 0, function* () {
49
- const { session, message, identityKey } = yield this.keyExchange.digestData(data);
50
- const remoteId = types_1.UserId.fromKey(identityKey);
51
- this.sessions.set(remoteId.toString(), session);
52
- return new types_1.Datagram(this.userId.toString(), types_1.UserId.fromKey(data.identityKey).toString(), types_1.Protocols.HANDSHAKE, (0, utils_1.encodeData)(message));
53
- });
54
- }
55
- sendData(receiverId, data) {
56
- return this.encrypt(receiverId, types_1.Protocols.MESSAGE, (0, utils_1.encodeData)(data));
57
- }
58
- sendRelay(receiverId, data) {
59
- return this.encrypt(receiverId, types_1.Protocols.RELAY, (0, utils_1.encodeData)(data));
60
- }
61
- sendDiscover(receiverId, discoverId) {
62
- return this.encrypt(receiverId, types_1.Protocols.DISCOVER, (0, utils_1.encodeData)(discoverId));
63
- }
64
- decrypt(datagram) {
65
- return __awaiter(this, void 0, void 0, function* () {
66
- const userId = datagram.sender;
67
- const session = yield this.sessions.get(userId);
68
- if (!session)
69
- throw new Error("Session not found for user: " + userId);
70
- if (!datagram.payload)
71
- throw new Error("Missing payload");
72
- const decrypted = yield session.decrypt(datagram.payload);
73
- if (!decrypted)
74
- throw new Error("Decryption failed");
75
- return decrypted;
76
- });
77
- }
78
- receive(datagram) {
79
- return __awaiter(this, void 0, void 0, function* () {
80
- if (datagram instanceof Uint8Array)
81
- datagram = types_1.Datagram.from(datagram);
82
- switch (datagram.protocol) {
83
- case types_1.Protocols.HANDSHAKE:
84
- if (!datagram.payload)
85
- throw new Error("Missing payload");
86
- const data = (0, utils_1.decodeData)(datagram.payload);
87
- const { session, identityKey } = yield this.keyExchange.digestMessage(data);
88
- this.sessions.set(types_1.UserId.fromKey(identityKey).toString(), session);
89
- return;
90
- case types_1.Protocols.MESSAGE:
91
- return yield this.decrypt(datagram);
92
- case types_1.Protocols.RELAY:
93
- return (0, utils_1.decodeData)(yield this.decrypt(datagram));
94
- case types_1.Protocols.DISCOVER:
95
- return types_1.UserId.from((0, utils_1.decodeData)(yield this.decrypt(datagram)));
96
- default:
97
- throw new Error("Invalid protocol");
98
- }
99
- });
100
- }
101
- }
102
- exports.FreeSignalNode = FreeSignalNode;
103
- class SessionMap {
104
- constructor(storage, maxSize = 50) {
105
- this.storage = storage;
106
- this.maxSize = maxSize;
107
- this.cache = new Map();
108
- }
109
- set(key, value) {
110
- this.cache.set(key, value);
111
- return this.storage.set(key, value.toJSON());
112
- }
113
- get(key) {
114
- return __awaiter(this, void 0, void 0, function* () {
115
- const session = this.cache.get(key);
116
- if (!session) {
117
- const sessionData = yield this.storage.get(key);
118
- if (!sessionData)
119
- return undefined;
120
- return double_ratchet_1.KeySession.from(sessionData, this.storage);
121
- }
122
- return session;
123
- });
124
- }
125
- has(key) {
126
- return __awaiter(this, void 0, void 0, function* () {
127
- return this.cache.has(key) || (yield this.storage.has(key));
128
- });
129
- }
130
- delete(key) {
131
- return __awaiter(this, void 0, void 0, function* () {
132
- return this.cache.delete(key) || (yield this.storage.delete(key));
133
- });
134
- }
135
- clear() {
136
- this.cache.clear();
137
- return this.storage.clear();
138
- }
139
- }
package/test.js DELETED
@@ -1,28 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- const utils_1 = require("@freesignal/utils");
13
- const _1 = require(".");
14
- const bob = (0, _1.createNode)({ keyExchange: new _1.AsyncMap(), sessions: new _1.AsyncMap(), users: new _1.AsyncMap() });
15
- const alice = (0, _1.createNode)({ keyExchange: new _1.AsyncMap(), sessions: new _1.AsyncMap(), users: new _1.AsyncMap() });
16
- setImmediate(() => __awaiter(void 0, void 0, void 0, function* () {
17
- const aliceHandshake = yield alice.sendHandshake(yield bob.generateKeyData());
18
- yield bob.receive(aliceHandshake);
19
- console.log("Session established successfully between Alice and Bob.");
20
- const first = (yield bob.sendData(alice.userId.toString(), (0, utils_1.encodeData)("Hi Alice!"))).toBytes();
21
- console.log("Bob: ", (0, utils_1.decodeData)(yield alice.receive(first)));
22
- const second = yield alice.sendData(bob.userId.toString(), (0, utils_1.encodeData)("Hi Bob!"));
23
- console.log("Alice: ", (0, utils_1.decodeData)(yield bob.receive(second)));
24
- const third = yield Promise.all(["How are you?", "How are this days?", "For me it's a good time"].map(msg => bob.sendData(alice.userId.toString(), (0, utils_1.encodeData)(msg))));
25
- third.forEach((value) => __awaiter(void 0, void 0, void 0, function* () {
26
- console.log("Bob: ", (0, utils_1.decodeData)(yield alice.receive(value)));
27
- }));
28
- }));
File without changes