@freesignal/protocol 0.2.2 → 0.2.4

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/api.d.ts CHANGED
@@ -33,6 +33,5 @@ export declare class FreeSignalAPI {
33
33
  protected unpackIdList(data: Uint8Array): DatagramId[];
34
34
  protected packDatagrams(messages: Datagram[]): Uint8Array;
35
35
  protected unpackDatagrams(data: Uint8Array): Datagram[];
36
- static getUserId(publicKey: string | Uint8Array): string;
37
36
  }
38
37
  export {};
package/api.js CHANGED
@@ -33,8 +33,8 @@ class FreeSignalAPI {
33
33
  }
34
34
  get identityKeys() {
35
35
  return {
36
- publicKey: (0, utils_1.encodeBase64)(this.signKey.publicKey),
37
- identityKey: (0, utils_1.encodeBase64)(this.boxKey.publicKey)
36
+ publicKey: (0, utils_1.decodeBase64)(this.signKey.publicKey),
37
+ identityKey: (0, utils_1.decodeBase64)(this.boxKey.publicKey)
38
38
  };
39
39
  }
40
40
  encryptData(data, userId) {
@@ -64,43 +64,43 @@ class FreeSignalAPI {
64
64
  const res = yield fetch(url, {
65
65
  method: 'GET',
66
66
  headers: {
67
- authorization: this.createToken(publicKey instanceof Uint8Array ? publicKey : (0, utils_1.decodeBase64)(publicKey))
67
+ authorization: this.createToken(publicKey instanceof Uint8Array ? publicKey : (0, utils_1.encodeBase64)(publicKey))
68
68
  }
69
69
  });
70
- return this.unpackDatagrams(yield this.decryptData(new Uint8Array(yield res.arrayBuffer()), FreeSignalAPI.getUserId(publicKey)));
70
+ return this.unpackDatagrams(yield this.decryptData(new Uint8Array(yield res.arrayBuffer()), types_1.UserId.getUserId(publicKey).toString()));
71
71
  });
72
72
  }
73
73
  postDatagrams(datagrams, publicKey, url) {
74
74
  return __awaiter(this, void 0, void 0, function* () {
75
- const data = yield this.encryptData(this.packDatagrams(datagrams), FreeSignalAPI.getUserId(publicKey));
75
+ const data = yield this.encryptData(this.packDatagrams(datagrams), types_1.UserId.getUserId(publicKey).toString());
76
76
  const res = yield fetch(url, {
77
77
  method: 'POST',
78
78
  headers: {
79
79
  'Content-Type': exports.FREESIGNAL_MIME,
80
- authorization: this.createToken(publicKey instanceof Uint8Array ? publicKey : (0, utils_1.decodeBase64)(publicKey))
80
+ authorization: this.createToken(publicKey instanceof Uint8Array ? publicKey : (0, utils_1.encodeBase64)(publicKey))
81
81
  },
82
82
  body: data.encode()
83
83
  });
84
- return (0, utils_1.numberFromUint8Array)(yield this.decryptData(new Uint8Array(yield res.arrayBuffer()), FreeSignalAPI.getUserId(publicKey)));
84
+ return (0, utils_1.numberFromUint8Array)(yield this.decryptData(new Uint8Array(yield res.arrayBuffer()), types_1.UserId.getUserId(publicKey).toString()));
85
85
  });
86
86
  }
87
87
  deleteDatagrams(datagramIds, publicKey, url) {
88
88
  return __awaiter(this, void 0, void 0, function* () {
89
- const data = yield this.encryptData(this.packIdList(datagramIds), FreeSignalAPI.getUserId(publicKey));
89
+ const data = yield this.encryptData(this.packIdList(datagramIds), types_1.UserId.getUserId(publicKey).toString());
90
90
  const res = yield fetch(url, {
91
91
  method: 'DELETE',
92
92
  headers: {
93
93
  'Content-Type': exports.FREESIGNAL_MIME,
94
- authorization: this.createToken(publicKey instanceof Uint8Array ? publicKey : (0, utils_1.decodeBase64)(publicKey))
94
+ authorization: this.createToken(publicKey instanceof Uint8Array ? publicKey : (0, utils_1.encodeBase64)(publicKey))
95
95
  },
96
96
  body: data.encode()
97
97
  });
98
- return (0, utils_1.numberFromUint8Array)(yield this.decryptData(new Uint8Array(yield res.arrayBuffer()), FreeSignalAPI.getUserId(publicKey)));
98
+ return (0, utils_1.numberFromUint8Array)(yield this.decryptData(new Uint8Array(yield res.arrayBuffer()), types_1.UserId.getUserId(publicKey).toString()));
99
99
  });
100
100
  }
101
101
  createToken(publicKey) {
102
102
  const sharedId = crypto_1.default.hash(crypto_1.default.ECDH.scalarMult(publicKey, this.boxKey.secretKey));
103
- return `Bearer ${(0, utils_1.encodeBase64)(this.userId)}:${(0, utils_1.encodeBase64)(sharedId)}`;
103
+ return `Bearer ${(0, utils_1.decodeBase64)(this.userId)}:${(0, utils_1.decodeBase64)(sharedId)}`;
104
104
  }
105
105
  ;
106
106
  digestToken(auth) {
@@ -110,7 +110,7 @@ class FreeSignalAPI {
110
110
  const identityKeys = yield this.users.get(userId);
111
111
  if (!identityKeys)
112
112
  throw new Error('User not found or invalid auth token');
113
- if ((0, utils_1.verifyUint8Array)(crypto_1.default.hash(crypto_1.default.ECDH.scalarMult((0, utils_1.decodeBase64)(identityKeys.publicKey), this.boxKey.secretKey)), (0, utils_1.decodeBase64)(sharedId)))
113
+ if ((0, utils_1.verifyUint8Array)(crypto_1.default.hash(crypto_1.default.ECDH.scalarMult((0, utils_1.encodeBase64)(identityKeys.publicKey), this.boxKey.secretKey)), (0, utils_1.encodeBase64)(sharedId)))
114
114
  return { identityKeys, userId: auth };
115
115
  else
116
116
  throw new Error('Authorization token not valid');
@@ -160,8 +160,5 @@ class FreeSignalAPI {
160
160
  }
161
161
  return messages;
162
162
  }
163
- static getUserId(publicKey) {
164
- return (0, utils_1.encodeBase64)(crypto_1.default.hash(publicKey instanceof Uint8Array ? publicKey : (0, utils_1.decodeBase64)(publicKey)));
165
- }
166
163
  }
167
164
  exports.FreeSignalAPI = FreeSignalAPI;
package/double-ratchet.js CHANGED
@@ -143,11 +143,11 @@ class KeySession {
143
143
  */
144
144
  export() {
145
145
  return {
146
- secretKey: (0, utils_1.encodeBase64)((0, utils_1.concatUint8Array)(this.keyPair.secretKey)),
147
- remoteKey: (0, utils_1.encodeBase64)(this._remoteKey),
148
- rootKey: (0, utils_1.encodeBase64)(this.rootKey),
149
- sendingChain: (0, utils_1.encodeBase64)(this.sendingChain),
150
- receivingChain: (0, utils_1.encodeBase64)(this.receivingChain),
146
+ secretKey: (0, utils_1.decodeBase64)((0, utils_1.concatUint8Array)(this.keyPair.secretKey)),
147
+ remoteKey: (0, utils_1.decodeBase64)(this._remoteKey),
148
+ rootKey: (0, utils_1.decodeBase64)(this.rootKey),
149
+ sendingChain: (0, utils_1.decodeBase64)(this.sendingChain),
150
+ receivingChain: (0, utils_1.decodeBase64)(this.receivingChain),
151
151
  sendingCount: this.sendingCount,
152
152
  receivingCount: this.receivingCount,
153
153
  previousCount: this.previousCount,
@@ -162,10 +162,10 @@ class KeySession {
162
162
  */
163
163
  static import(json) {
164
164
  const data = JSON.parse(json);
165
- const session = new KeySession({ secretKey: (0, utils_1.decodeBase64)(data.secretKey), rootKey: (0, utils_1.decodeBase64)(data.rootKey) });
166
- session._remoteKey = (0, utils_1.decodeBase64)(data.remoteKey);
167
- session.sendingChain = (0, utils_1.decodeBase64)(data.sendingChain);
168
- session.receivingChain = (0, utils_1.decodeBase64)(data.receivingChain);
165
+ const session = new KeySession({ secretKey: (0, utils_1.encodeBase64)(data.secretKey), rootKey: (0, utils_1.encodeBase64)(data.rootKey) });
166
+ session._remoteKey = (0, utils_1.encodeBase64)(data.remoteKey);
167
+ session.sendingChain = (0, utils_1.encodeBase64)(data.sendingChain);
168
+ session.receivingChain = (0, utils_1.encodeBase64)(data.receivingChain);
169
169
  session.sendingCount = data.sendingCount;
170
170
  session.receivingCount = data.receivingCount;
171
171
  session.previousCount = data.previousCount;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@freesignal/protocol",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "description": "Signal Protocol implementation in javascript",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "author": "Christian Braghette",
package/test.js CHANGED
@@ -10,14 +10,14 @@ const bob = (0, _1.createKeyExchange)(crypto_1.default.EdDSA.keyPair().secretKey
10
10
  const alice = (0, _1.createKeyExchange)(crypto_1.default.EdDSA.keyPair().secretKey, crypto_1.default.ECDH.keyPair().secretKey);
11
11
  const bobmessage = bob.generateData();
12
12
  const { session: alicesession, message: aliceack } = alice.digestData(bobmessage);
13
- bob.digestMessage(aliceack).then(({ session: bobsession, cleartext }) => {
13
+ bob.digestMessage(aliceack).then(({ session: bobsession, identityKeys }) => {
14
14
  var _a;
15
- if (bobsession && cleartext) {
15
+ if (bobsession && identityKeys) {
16
16
  console.log("Session established successfully between Alice and Bob.");
17
- const datagram = _1.Datagram.create(bob.signatureKey, alice.signatureKey, _1.Protocols.MESSAGE, (_a = bobsession.encrypt((0, utils_1.decodeUTF8)("Hi Alice!"))) === null || _a === void 0 ? void 0 : _a.encode());
17
+ const datagram = _1.Datagram.create(bob.signatureKey, alice.signatureKey, _1.Protocols.MESSAGE, (_a = bobsession.encrypt((0, utils_1.encodeUTF8)("Hi Alice!"))) === null || _a === void 0 ? void 0 : _a.encode());
18
18
  //console.log(datagram.payload);
19
19
  const msg = datagram.encode();
20
- console.log((0, utils_1.encodeUTF8)(alicesession.decrypt(_1.Datagram.from(msg).payload)));
20
+ console.log((0, utils_1.decodeUTF8)(alicesession.decrypt(_1.Datagram.from(msg).payload)));
21
21
  if (alicesession.handshaked && bobsession.handshaked)
22
22
  console.log("Successfully handshaked");
23
23
  else
package/types.d.ts CHANGED
@@ -18,22 +18,34 @@
18
18
  */
19
19
  import { Encodable } from "@freesignal/interfaces";
20
20
  export type UserId = string;
21
+ export declare namespace UserId {
22
+ class UserIdConstructor {
23
+ private readonly array;
24
+ constructor(array: Uint8Array);
25
+ toString(): string;
26
+ toUint8Array(): Uint8Array;
27
+ }
28
+ export function getUserId(publicKey: string | Uint8Array): UserIdConstructor;
29
+ export function from(userId: string | Uint8Array): UserIdConstructor;
30
+ export {};
31
+ }
21
32
  export interface IdentityKeys {
22
33
  readonly publicKey: string;
23
34
  readonly identityKey: string;
24
35
  }
25
36
  export declare namespace IdentityKeys {
26
- const keyLength: number;
27
- function isIdentityKeys(obj: any): boolean;
28
- function from(identityKeys: IdentityKeys): IdentityKeysConstructor;
29
- }
30
- declare class IdentityKeysConstructor implements IdentityKeys, Encodable {
31
- readonly publicKey: string;
32
- readonly identityKey: string;
33
- constructor(identityKeys: IdentityKeys | Uint8Array | string);
34
- encode(): Uint8Array;
35
- toString(): string;
36
- toJSON(): string;
37
+ export const keyLength: number;
38
+ class IdentityKeysConstructor implements IdentityKeys, Encodable {
39
+ readonly publicKey: string;
40
+ readonly identityKey: string;
41
+ constructor(identityKeys: IdentityKeys | Uint8Array | string);
42
+ encode(): Uint8Array;
43
+ toString(): string;
44
+ toJSON(): string;
45
+ }
46
+ export function isIdentityKeys(obj: any): boolean;
47
+ export function from(identityKeys: IdentityKeys): IdentityKeysConstructor;
48
+ export {};
37
49
  }
38
50
  export declare enum Protocols {
39
51
  NULL = "",
@@ -58,26 +70,27 @@ export interface Datagram {
58
70
  payload?: Uint8Array;
59
71
  }
60
72
  export declare namespace Datagram {
61
- const version = 1;
62
- function create(sender: Uint8Array | string, receiver: Uint8Array | string, protocol: Protocols, payload?: Uint8Array | Encodable): DatagramConstructor;
63
- function isDatagram(obj: any): boolean;
64
- function from(data: Uint8Array | Datagram | string): DatagramConstructor;
65
- }
66
- declare class DatagramConstructor implements Encodable, Datagram {
67
- readonly id: string;
68
- readonly version: number;
69
- readonly sender: string;
70
- readonly receiver: string;
71
- readonly protocol: Protocols;
72
- readonly createdAt: number;
73
- payload?: Uint8Array;
74
- private static headerOffset;
75
- constructor(sender: Uint8Array | string, receiver: Uint8Array | string, protocol: Protocols, payload?: Uint8Array | Encodable);
76
- constructor(data: Uint8Array | Datagram);
77
- encode(compression?: boolean): Uint8Array;
78
- encodeSigned(secretKey: Uint8Array, compression?: boolean): Uint8Array;
79
- toString(): string;
80
- toJSON(): string;
73
+ export const version = 1;
74
+ class DatagramConstructor implements Encodable, Datagram {
75
+ readonly id: string;
76
+ readonly version: number;
77
+ readonly sender: UserId;
78
+ readonly receiver: UserId;
79
+ readonly protocol: Protocols;
80
+ readonly createdAt: number;
81
+ payload?: Uint8Array;
82
+ private static headerOffset;
83
+ constructor(sender: Uint8Array | string, receiver: Uint8Array | string, protocol: Protocols, payload?: Uint8Array | Encodable);
84
+ constructor(data: Uint8Array | Datagram);
85
+ encode(compression?: boolean): Uint8Array;
86
+ encodeSigned(secretKey: Uint8Array, compression?: boolean): Uint8Array;
87
+ toString(): string;
88
+ toJSON(): string;
89
+ }
90
+ export function create(sender: Uint8Array | string, receiver: Uint8Array | string, protocol: Protocols, payload?: Uint8Array | Encodable): DatagramConstructor;
91
+ export function isDatagram(obj: any): boolean;
92
+ export function from(data: Uint8Array | Datagram | string): DatagramConstructor;
93
+ export {};
81
94
  }
82
95
  /**
83
96
  * Interface representing an encrypted payload.
@@ -163,4 +176,3 @@ export declare class EncryptedDataConstructor implements EncryptedData {
163
176
  toString(): string;
164
177
  toJSON(): string;
165
178
  }
166
- export {};
package/types.js CHANGED
@@ -21,14 +21,60 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
21
21
  return (mod && mod.__esModule) ? mod : { "default": mod };
22
22
  };
23
23
  Object.defineProperty(exports, "__esModule", { value: true });
24
- exports.EncryptedDataConstructor = exports.EncryptedData = exports.Datagram = exports.Protocols = exports.IdentityKeys = void 0;
24
+ exports.EncryptedDataConstructor = exports.EncryptedData = exports.Datagram = exports.Protocols = exports.IdentityKeys = exports.UserId = void 0;
25
25
  const utils_1 = require("@freesignal/utils");
26
26
  const crypto_1 = __importDefault(require("@freesignal/crypto"));
27
27
  const fflate_1 = __importDefault(require("fflate"));
28
28
  const double_ratchet_1 = require("./double-ratchet");
29
+ var UserId;
30
+ (function (UserId) {
31
+ class UserIdConstructor {
32
+ constructor(array) {
33
+ this.array = array;
34
+ }
35
+ ;
36
+ toString() {
37
+ return (0, utils_1.decodeBase64)(this.array);
38
+ }
39
+ toUint8Array() {
40
+ return this.array;
41
+ }
42
+ }
43
+ function getUserId(publicKey) {
44
+ return new UserIdConstructor(crypto_1.default.hash(publicKey instanceof Uint8Array ? publicKey : (0, utils_1.encodeBase64)(publicKey)));
45
+ }
46
+ UserId.getUserId = getUserId;
47
+ function from(userId) {
48
+ return new UserIdConstructor(userId instanceof Uint8Array ? userId : (0, utils_1.encodeBase64)(userId));
49
+ }
50
+ UserId.from = from;
51
+ })(UserId || (exports.UserId = UserId = {}));
29
52
  var IdentityKeys;
30
53
  (function (IdentityKeys) {
31
54
  IdentityKeys.keyLength = crypto_1.default.ECDH.publicKeyLength;
55
+ class IdentityKeysConstructor {
56
+ constructor(identityKeys) {
57
+ if (typeof identityKeys === 'string')
58
+ identityKeys = (0, utils_1.encodeBase64)(identityKeys);
59
+ if (identityKeys instanceof Uint8Array) {
60
+ this.publicKey = (0, utils_1.decodeBase64)(identityKeys.subarray(0, IdentityKeys.keyLength));
61
+ this.identityKey = (0, utils_1.decodeBase64)(identityKeys.subarray(IdentityKeys.keyLength));
62
+ }
63
+ else {
64
+ this.publicKey = identityKeys.publicKey;
65
+ this.identityKey = identityKeys.identityKey;
66
+ }
67
+ }
68
+ encode() {
69
+ return (0, utils_1.concatUint8Array)((0, utils_1.encodeBase64)(this.publicKey), (0, utils_1.encodeBase64)(this.identityKey));
70
+ }
71
+ toString() {
72
+ throw (0, utils_1.decodeBase64)(this.encode());
73
+ }
74
+ toJSON() {
75
+ throw this.toString();
76
+ }
77
+ }
32
78
  function isIdentityKeys(obj) {
33
79
  return (typeof obj === 'object' && obj.publicKey && obj.identityKey);
34
80
  }
@@ -38,29 +84,6 @@ var IdentityKeys;
38
84
  }
39
85
  IdentityKeys.from = from;
40
86
  })(IdentityKeys || (exports.IdentityKeys = IdentityKeys = {}));
41
- class IdentityKeysConstructor {
42
- constructor(identityKeys) {
43
- if (typeof identityKeys === 'string')
44
- identityKeys = (0, utils_1.decodeBase64)(identityKeys);
45
- if (identityKeys instanceof Uint8Array) {
46
- this.publicKey = (0, utils_1.encodeBase64)(identityKeys.subarray(0, IdentityKeys.keyLength));
47
- this.identityKey = (0, utils_1.encodeBase64)(identityKeys.subarray(IdentityKeys.keyLength));
48
- }
49
- else {
50
- this.publicKey = identityKeys.publicKey;
51
- this.identityKey = identityKeys.identityKey;
52
- }
53
- }
54
- encode() {
55
- return (0, utils_1.concatUint8Array)((0, utils_1.decodeBase64)(this.publicKey), (0, utils_1.decodeBase64)(this.identityKey));
56
- }
57
- toString() {
58
- throw (0, utils_1.encodeBase64)(this.encode());
59
- }
60
- toJSON() {
61
- throw this.toString();
62
- }
63
- }
64
87
  var Protocols;
65
88
  (function (Protocols) {
66
89
  Protocols["NULL"] = "";
@@ -98,6 +121,88 @@ var Protocols;
98
121
  var Datagram;
99
122
  (function (Datagram) {
100
123
  Datagram.version = 1;
124
+ class DatagramConstructor {
125
+ constructor(data, receiver, protocol, payload) {
126
+ if (!receiver && !protocol && !payload) {
127
+ if (data instanceof Uint8Array) {
128
+ this.version = data[0] & 63;
129
+ this.protocol = Protocols.decode(data.subarray(1, 2));
130
+ this.id = crypto_1.default.UUID.stringify(data.subarray(2, 18));
131
+ this.createdAt = (0, utils_1.numberFromUint8Array)(data.subarray(18, 26));
132
+ this.sender = (0, utils_1.decodeBase64)(data.subarray(26, 26 + crypto_1.default.EdDSA.publicKeyLength));
133
+ this.receiver = (0, utils_1.decodeBase64)(data.subarray(26 + crypto_1.default.EdDSA.publicKeyLength, DatagramConstructor.headerOffset));
134
+ if (data[0] & 128) {
135
+ const signature = data.subarray(data.length - crypto_1.default.EdDSA.signatureLength);
136
+ if (!crypto_1.default.EdDSA.verify(data.subarray(0, data.length - crypto_1.default.EdDSA.signatureLength), signature, data.subarray(26, 26 + crypto_1.default.EdDSA.publicKeyLength)))
137
+ throw new Error('Invalid signature for Datagram');
138
+ }
139
+ if (data[0] & 64)
140
+ this.payload = fflate_1.default.inflateSync(data.subarray(DatagramConstructor.headerOffset, data.length));
141
+ else
142
+ this.payload = data.subarray(DatagramConstructor.headerOffset, data.length);
143
+ }
144
+ else if (Datagram.isDatagram(data)) {
145
+ const datagram = data;
146
+ this.id = datagram.id;
147
+ this.version = datagram.version;
148
+ this.sender = datagram.sender;
149
+ this.receiver = datagram.receiver;
150
+ this.protocol = datagram.protocol;
151
+ this.createdAt = datagram.createdAt;
152
+ this.payload = datagram.payload;
153
+ }
154
+ else
155
+ throw new Error('Invalid constructor arguments for Datagram');
156
+ }
157
+ else if (typeof data === 'string' || data instanceof Uint8Array) {
158
+ this.id = crypto_1.default.UUID.generate().toString();
159
+ this.version = Datagram.version;
160
+ this.sender = typeof data === 'string' ? data : (0, utils_1.decodeBase64)(data);
161
+ this.receiver = typeof receiver === 'string' ? receiver : (0, utils_1.decodeBase64)(receiver);
162
+ this.protocol = protocol;
163
+ this.createdAt = Date.now();
164
+ this.payload = payload instanceof Uint8Array ? payload : payload === null || payload === void 0 ? void 0 : payload.encode();
165
+ }
166
+ else
167
+ throw new Error('Invalid constructor arguments for Datagram');
168
+ }
169
+ encode(compression = true) {
170
+ var _a;
171
+ compression = compression && this.payload != undefined && this.payload.length > 1024;
172
+ return (0, utils_1.concatUint8Array)(new Uint8Array(1).fill(this.version | (compression ? 64 : 0)), //1
173
+ Protocols.encode(this.protocol), //1
174
+ (_a = crypto_1.default.UUID.parse(this.id)) !== null && _a !== void 0 ? _a : [], //16
175
+ (0, utils_1.numberToUint8Array)(this.createdAt, 8), //8
176
+ (0, utils_1.encodeBase64)(this.sender), //32
177
+ (0, utils_1.encodeBase64)(this.receiver), //32
178
+ ...(this.payload ? [compression ? fflate_1.default.deflateSync(this.payload) : this.payload] : []));
179
+ }
180
+ encodeSigned(secretKey, compression) {
181
+ //if (!this.payload) throw new Error('Cannot sign a datagram without payload');
182
+ const header = this.encode(compression);
183
+ header[0] |= 128; // Set the sign bit
184
+ const signature = crypto_1.default.EdDSA.sign(header, secretKey);
185
+ return (0, utils_1.concatUint8Array)(header, signature);
186
+ }
187
+ toString() {
188
+ return (0, utils_1.decodeBase64)(this.encode());
189
+ }
190
+ toJSON() {
191
+ /*return JSON.stringify({
192
+ id: this.id,
193
+ version: this.version,
194
+ senderKey: this.senderKey,
195
+ senderRelay: this.senderRelay,
196
+ receiverKey: this.receiverKey,
197
+ receiverRelay: this.receiverRelay,
198
+ protocol: this.protocol,
199
+ createdAt: this.createdAt,
200
+ payload: this.payload ? encodeBase64(this.payload) : undefined
201
+ });*/
202
+ return this.toString();
203
+ }
204
+ }
205
+ DatagramConstructor.headerOffset = 26 + crypto_1.default.EdDSA.publicKeyLength * 2;
101
206
  function create(sender, receiver, protocol, payload) {
102
207
  return new DatagramConstructor(sender, receiver, protocol, payload);
103
208
  }
@@ -108,7 +213,7 @@ var Datagram;
108
213
  Datagram.isDatagram = isDatagram;
109
214
  function from(data) {
110
215
  if (typeof data === 'string') {
111
- const decoded = (0, utils_1.decodeBase64)(data);
216
+ const decoded = (0, utils_1.encodeBase64)(data);
112
217
  return new DatagramConstructor(decoded);
113
218
  }
114
219
  else
@@ -116,88 +221,6 @@ var Datagram;
116
221
  }
117
222
  Datagram.from = from;
118
223
  })(Datagram || (exports.Datagram = Datagram = {}));
119
- class DatagramConstructor {
120
- constructor(data, receiver, protocol, payload) {
121
- if (!receiver && !protocol && !payload) {
122
- if (data instanceof Uint8Array) {
123
- this.version = data[0] & 63;
124
- this.protocol = Protocols.decode(data.subarray(1, 2));
125
- this.id = crypto_1.default.UUID.stringify(data.subarray(2, 18));
126
- this.createdAt = (0, utils_1.numberFromUint8Array)(data.subarray(18, 26));
127
- this.sender = (0, utils_1.encodeBase64)(data.subarray(26, 26 + crypto_1.default.EdDSA.publicKeyLength));
128
- this.receiver = (0, utils_1.encodeBase64)(data.subarray(26 + crypto_1.default.EdDSA.publicKeyLength, DatagramConstructor.headerOffset));
129
- if (data[0] & 128) {
130
- const signature = data.subarray(data.length - crypto_1.default.EdDSA.signatureLength);
131
- if (!crypto_1.default.EdDSA.verify(data.subarray(0, data.length - crypto_1.default.EdDSA.signatureLength), signature, data.subarray(26, 26 + crypto_1.default.EdDSA.publicKeyLength)))
132
- throw new Error('Invalid signature for Datagram');
133
- }
134
- if (data[0] & 64)
135
- this.payload = fflate_1.default.inflateSync(data.subarray(DatagramConstructor.headerOffset, data.length));
136
- else
137
- this.payload = data.subarray(DatagramConstructor.headerOffset, data.length);
138
- }
139
- else if (Datagram.isDatagram(data)) {
140
- const datagram = data;
141
- this.id = datagram.id;
142
- this.version = datagram.version;
143
- this.sender = datagram.sender;
144
- this.receiver = datagram.receiver;
145
- this.protocol = datagram.protocol;
146
- this.createdAt = datagram.createdAt;
147
- this.payload = datagram.payload;
148
- }
149
- else
150
- throw new Error('Invalid constructor arguments for Datagram');
151
- }
152
- else if (typeof data === 'string' || data instanceof Uint8Array) {
153
- this.id = crypto_1.default.UUID.generate().toString();
154
- this.version = Datagram.version;
155
- this.sender = typeof data === 'string' ? data : (0, utils_1.encodeBase64)(data);
156
- this.receiver = typeof receiver === 'string' ? receiver : (0, utils_1.encodeBase64)(receiver);
157
- this.protocol = protocol;
158
- this.createdAt = Date.now();
159
- this.payload = payload instanceof Uint8Array ? payload : payload === null || payload === void 0 ? void 0 : payload.encode();
160
- }
161
- else
162
- throw new Error('Invalid constructor arguments for Datagram');
163
- }
164
- encode(compression = true) {
165
- var _a;
166
- compression = compression && this.payload != undefined && this.payload.length > 1024;
167
- return (0, utils_1.concatUint8Array)(new Uint8Array(1).fill(this.version | (compression ? 64 : 0)), //1
168
- Protocols.encode(this.protocol), //1
169
- (_a = crypto_1.default.UUID.parse(this.id)) !== null && _a !== void 0 ? _a : [], //16
170
- (0, utils_1.numberToUint8Array)(this.createdAt, 8), //8
171
- (0, utils_1.decodeBase64)(this.sender), //32
172
- (0, utils_1.decodeBase64)(this.receiver), //32
173
- ...(this.payload ? [compression ? fflate_1.default.deflateSync(this.payload) : this.payload] : []));
174
- }
175
- encodeSigned(secretKey, compression) {
176
- //if (!this.payload) throw new Error('Cannot sign a datagram without payload');
177
- const header = this.encode(compression);
178
- header[0] |= 128; // Set the sign bit
179
- const signature = crypto_1.default.EdDSA.sign(header, secretKey);
180
- return (0, utils_1.concatUint8Array)(header, signature);
181
- }
182
- toString() {
183
- return (0, utils_1.encodeBase64)(this.encode());
184
- }
185
- toJSON() {
186
- /*return JSON.stringify({
187
- id: this.id,
188
- version: this.version,
189
- senderKey: this.senderKey,
190
- senderRelay: this.senderRelay,
191
- receiverKey: this.receiverKey,
192
- receiverRelay: this.receiverRelay,
193
- protocol: this.protocol,
194
- createdAt: this.createdAt,
195
- payload: this.payload ? encodeBase64(this.payload) : undefined
196
- });*/
197
- return this.toString();
198
- }
199
- }
200
- DatagramConstructor.headerOffset = 26 + crypto_1.default.EdDSA.publicKeyLength * 2;
201
224
  class EncryptedData {
202
225
  /**
203
226
  * Static factory method that constructs an `EncryptedPayload` from a raw Uint8Array.
@@ -245,13 +268,13 @@ class EncryptedDataConstructor {
245
268
  version: this.version,
246
269
  count: this.count,
247
270
  previous: this.previous,
248
- publicKey: (0, utils_1.encodeBase64)(this.publicKey),
249
- nonce: (0, utils_1.encodeBase64)(this.nonce),
250
- ciphertext: (0, utils_1.encodeBase64)(this.ciphertext)
271
+ publicKey: (0, utils_1.decodeBase64)(this.publicKey),
272
+ nonce: (0, utils_1.decodeBase64)(this.nonce),
273
+ ciphertext: (0, utils_1.decodeBase64)(this.ciphertext)
251
274
  };
252
275
  }
253
276
  toString() {
254
- return (0, utils_1.encodeBase64)(this.raw);
277
+ return (0, utils_1.decodeBase64)(this.raw);
255
278
  }
256
279
  toJSON() {
257
280
  return JSON.stringify(this.decode());
package/x3dh.d.ts CHANGED
@@ -18,6 +18,7 @@
18
18
  */
19
19
  import { KeyExchangeData, KeyExchangeDataBundle, KeyExchangeSynMessage, LocalStorage, Crypto } from "@freesignal/interfaces";
20
20
  import { KeySession } from "./double-ratchet";
21
+ import { IdentityKeys } from "./types";
21
22
  export declare class KeyExchange {
22
23
  static readonly version = 1;
23
24
  private static readonly hkdfInfo;
@@ -35,9 +36,10 @@ export declare class KeyExchange {
35
36
  digestData(message: KeyExchangeData): {
36
37
  session: KeySession;
37
38
  message: KeyExchangeSynMessage;
39
+ identityKeys: IdentityKeys;
38
40
  };
39
41
  digestMessage(message: KeyExchangeSynMessage): Promise<{
40
42
  session: KeySession;
41
- cleartext: Uint8Array;
43
+ identityKeys: IdentityKeys;
42
44
  }>;
43
45
  }
package/x3dh.js CHANGED
@@ -45,13 +45,13 @@ class KeyExchange {
45
45
  generateSPK() {
46
46
  const signedPreKey = crypto_1.default.ECDH.keyPair();
47
47
  const signedPreKeyHash = crypto_1.default.hash(signedPreKey.publicKey);
48
- this.bundleStore.set((0, utils_1.encodeBase64)(signedPreKeyHash), signedPreKey);
48
+ this.bundleStore.set((0, utils_1.decodeBase64)(signedPreKeyHash), signedPreKey);
49
49
  return { signedPreKey, signedPreKeyHash };
50
50
  }
51
51
  generateOPK(spkHash) {
52
52
  const onetimePreKey = crypto_1.default.ECDH.keyPair();
53
53
  const onetimePreKeyHash = crypto_1.default.hash(onetimePreKey.publicKey);
54
- this.bundleStore.set((0, utils_1.encodeBase64)(spkHash).concat((0, utils_1.encodeBase64)(onetimePreKeyHash)), onetimePreKey);
54
+ this.bundleStore.set((0, utils_1.decodeBase64)(spkHash).concat((0, utils_1.decodeBase64)(onetimePreKeyHash)), onetimePreKey);
55
55
  return { onetimePreKey, onetimePreKeyHash };
56
56
  }
57
57
  generateBundle(length) {
@@ -59,11 +59,11 @@ class KeyExchange {
59
59
  const onetimePreKey = new Array(length !== null && length !== void 0 ? length : KeyExchange.maxOPK).fill(0).map(() => this.generateOPK(signedPreKeyHash).onetimePreKey);
60
60
  return {
61
61
  version: KeyExchange.version,
62
- publicKey: (0, utils_1.encodeBase64)(this._signatureKey.publicKey),
63
- identityKey: (0, utils_1.encodeBase64)(this._identityKey.publicKey),
64
- signedPreKey: (0, utils_1.encodeBase64)(signedPreKey.publicKey),
65
- signature: (0, utils_1.encodeBase64)(crypto_1.default.EdDSA.sign(signedPreKeyHash, this._signatureKey.secretKey)),
66
- onetimePreKey: onetimePreKey.map(opk => (0, utils_1.encodeBase64)(opk.publicKey))
62
+ publicKey: (0, utils_1.decodeBase64)(this._signatureKey.publicKey),
63
+ identityKey: (0, utils_1.decodeBase64)(this._identityKey.publicKey),
64
+ signedPreKey: (0, utils_1.decodeBase64)(signedPreKey.publicKey),
65
+ signature: (0, utils_1.decodeBase64)(crypto_1.default.EdDSA.sign(signedPreKeyHash, this._signatureKey.secretKey)),
66
+ onetimePreKey: onetimePreKey.map(opk => (0, utils_1.decodeBase64)(opk.publicKey))
67
67
  };
68
68
  }
69
69
  generateData() {
@@ -71,20 +71,20 @@ class KeyExchange {
71
71
  const { onetimePreKey } = this.generateOPK(signedPreKeyHash);
72
72
  return {
73
73
  version: KeyExchange.version,
74
- publicKey: (0, utils_1.encodeBase64)(this._signatureKey.publicKey),
75
- identityKey: (0, utils_1.encodeBase64)(this._identityKey.publicKey),
76
- signedPreKey: (0, utils_1.encodeBase64)(signedPreKey.publicKey),
77
- signature: (0, utils_1.encodeBase64)(crypto_1.default.EdDSA.sign(signedPreKeyHash, this._signatureKey.secretKey)),
78
- onetimePreKey: (0, utils_1.encodeBase64)(onetimePreKey.publicKey)
74
+ publicKey: (0, utils_1.decodeBase64)(this._signatureKey.publicKey),
75
+ identityKey: (0, utils_1.decodeBase64)(this._identityKey.publicKey),
76
+ signedPreKey: (0, utils_1.decodeBase64)(signedPreKey.publicKey),
77
+ signature: (0, utils_1.decodeBase64)(crypto_1.default.EdDSA.sign(signedPreKeyHash, this._signatureKey.secretKey)),
78
+ onetimePreKey: (0, utils_1.decodeBase64)(onetimePreKey.publicKey)
79
79
  };
80
80
  }
81
81
  digestData(message) {
82
82
  const ephemeralKey = crypto_1.default.ECDH.keyPair();
83
- const signedPreKey = (0, utils_1.decodeBase64)(message.signedPreKey);
84
- if (!crypto_1.default.EdDSA.verify(crypto_1.default.hash(signedPreKey), (0, utils_1.decodeBase64)(message.signature), (0, utils_1.decodeBase64)(message.publicKey)))
83
+ const signedPreKey = (0, utils_1.encodeBase64)(message.signedPreKey);
84
+ if (!crypto_1.default.EdDSA.verify(crypto_1.default.hash(signedPreKey), (0, utils_1.encodeBase64)(message.signature), (0, utils_1.encodeBase64)(message.publicKey)))
85
85
  throw new Error("Signature verification failed");
86
- const identityKey = (0, utils_1.decodeBase64)(message.identityKey);
87
- const onetimePreKey = message.onetimePreKey ? (0, utils_1.decodeBase64)(message.onetimePreKey) : undefined;
86
+ const identityKey = (0, utils_1.encodeBase64)(message.identityKey);
87
+ const onetimePreKey = message.onetimePreKey ? (0, utils_1.encodeBase64)(message.onetimePreKey) : undefined;
88
88
  const signedPreKeyHash = crypto_1.default.hash(signedPreKey);
89
89
  const onetimePreKeyHash = onetimePreKey ? crypto_1.default.hash(onetimePreKey) : new Uint8Array();
90
90
  const rootKey = crypto_1.default.hkdf(new Uint8Array([
@@ -96,18 +96,22 @@ class KeyExchange {
96
96
  const session = new double_ratchet_1.KeySession({ remoteKey: identityKey, rootKey });
97
97
  const cyphertext = session.encrypt((0, utils_1.concatUint8Array)(crypto_1.default.hash(this._identityKey.publicKey), crypto_1.default.hash(identityKey)));
98
98
  if (!cyphertext)
99
- throw new Error();
99
+ throw new Error("Decryption error");
100
100
  return {
101
101
  session,
102
102
  message: {
103
103
  version: KeyExchange.version,
104
- publicKey: (0, utils_1.encodeBase64)(this._signatureKey.publicKey),
105
- identityKey: (0, utils_1.encodeBase64)(this._identityKey.publicKey),
106
- ephemeralKey: (0, utils_1.encodeBase64)(ephemeralKey.publicKey),
107
- signedPreKeyHash: (0, utils_1.encodeBase64)(signedPreKeyHash),
108
- onetimePreKeyHash: (0, utils_1.encodeBase64)(onetimePreKeyHash),
109
- associatedData: (0, utils_1.encodeBase64)(cyphertext.encode())
110
- }
104
+ publicKey: (0, utils_1.decodeBase64)(this._signatureKey.publicKey),
105
+ identityKey: (0, utils_1.decodeBase64)(this._identityKey.publicKey),
106
+ ephemeralKey: (0, utils_1.decodeBase64)(ephemeralKey.publicKey),
107
+ signedPreKeyHash: (0, utils_1.decodeBase64)(signedPreKeyHash),
108
+ onetimePreKeyHash: (0, utils_1.decodeBase64)(onetimePreKeyHash),
109
+ associatedData: (0, utils_1.decodeBase64)(cyphertext.encode())
110
+ },
111
+ identityKeys: {
112
+ publicKey: message.publicKey,
113
+ identityKey: message.identityKey
114
+ },
111
115
  };
112
116
  }
113
117
  digestMessage(message) {
@@ -119,8 +123,8 @@ class KeyExchange {
119
123
  throw new Error("ACK message malformed");
120
124
  if (!this.bundleStore.delete(hash))
121
125
  throw new Error("Bundle store deleting error");
122
- const identityKey = (0, utils_1.decodeBase64)(message.identityKey);
123
- const ephemeralKey = (0, utils_1.decodeBase64)(message.ephemeralKey);
126
+ const identityKey = (0, utils_1.encodeBase64)(message.identityKey);
127
+ const ephemeralKey = (0, utils_1.encodeBase64)(message.ephemeralKey);
124
128
  const rootKey = crypto_1.default.hkdf(new Uint8Array([
125
129
  ...crypto_1.default.ECDH.scalarMult(signedPreKey.secretKey, identityKey),
126
130
  ...crypto_1.default.ECDH.scalarMult(this._identityKey.secretKey, ephemeralKey),
@@ -128,18 +132,24 @@ class KeyExchange {
128
132
  ...onetimePreKey ? crypto_1.default.ECDH.scalarMult(onetimePreKey.secretKey, ephemeralKey) : new Uint8Array()
129
133
  ]), new Uint8Array(double_ratchet_1.KeySession.rootKeyLength).fill(0), KeyExchange.hkdfInfo, double_ratchet_1.KeySession.rootKeyLength);
130
134
  const session = new double_ratchet_1.KeySession({ secretKey: this._identityKey.secretKey, rootKey });
131
- const cleartext = session.decrypt((0, utils_1.decodeBase64)(message.associatedData));
135
+ const cleartext = session.decrypt((0, utils_1.encodeBase64)(message.associatedData));
132
136
  if (!cleartext)
133
137
  throw new Error("Error decrypting ACK message");
134
138
  if (!(0, utils_1.verifyUint8Array)(cleartext, (0, utils_1.concatUint8Array)(crypto_1.default.hash(identityKey), crypto_1.default.hash(this._identityKey.publicKey))))
135
139
  throw new Error("Error verifing Associated Data");
136
- return { session, cleartext };
140
+ return {
141
+ session,
142
+ identityKeys: {
143
+ publicKey: message.publicKey,
144
+ identityKey: message.identityKey
145
+ }
146
+ };
137
147
  });
138
148
  }
139
149
  }
140
150
  exports.KeyExchange = KeyExchange;
141
151
  KeyExchange.version = 1;
142
- KeyExchange.hkdfInfo = (0, utils_1.decodeUTF8)("freesignal/x3dh/" + KeyExchange.version);
152
+ KeyExchange.hkdfInfo = (0, utils_1.encodeUTF8)("freesignal/x3dh/" + KeyExchange.version);
143
153
  KeyExchange.maxOPK = 10;
144
154
  class AsyncMap {
145
155
  constructor() {