@unknownncat/swt-libsignal 1.0.4 → 1.0.6
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/LICENSE +21 -0
- package/dist/crypto.d.ts +1 -1
- package/dist/crypto.js +69 -35
- package/dist/curve.d.ts +1 -1
- package/dist/index.d.ts +4 -5
- package/dist/index.js +1 -2
- package/dist/job_queue.js +22 -18
- package/dist/key-helper.d.ts +1 -1
- package/dist/{base_key_type.d.ts → ratchet-types.d.ts} +5 -0
- package/dist/{chain_type.js → ratchet-types.js} +4 -0
- package/dist/session/builder/session-builder.js +31 -11
- package/dist/session/cipher/session-cipher.js +99 -50
- package/dist/session/record/session-entry.js +2 -3
- package/dist/session/record/session-record.js +1 -1
- package/dist/session/record/types.d.ts +3 -3
- package/dist/types/asymmetric.d.ts +41 -0
- package/dist/types/crypto.d.ts +69 -0
- package/dist/types/index.d.ts +2 -0
- package/package.json +11 -3
- package/readme.md +2 -0
- package/dist/base_key_type.js +0 -4
- package/dist/chain_type.d.ts +0 -5
- package/dist/teste.d.ts +0 -1
- package/dist/teste.js +0 -18
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 @unknownncat/swt-libsignal
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/crypto.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import type { CryptoAPI } from '
|
|
1
|
+
import type { CryptoAPI } from './types/crypto.js';
|
|
2
2
|
export declare const crypto: CryptoAPI;
|
package/dist/crypto.js
CHANGED
|
@@ -8,34 +8,26 @@ function toBuffer(data) {
|
|
|
8
8
|
function toUint8(data) {
|
|
9
9
|
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
10
10
|
}
|
|
11
|
-
|
|
11
|
+
function encrypt(key, plaintext, options) {
|
|
12
12
|
const k = toBuffer(key);
|
|
13
|
-
if (k.length !== 32)
|
|
13
|
+
if (k.length !== 32)
|
|
14
14
|
throw new Error('Key must be 32 bytes');
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
: randomBytes(12);
|
|
15
|
+
const iv = options?.iv ? toBuffer(options.iv) : randomBytes(12);
|
|
16
|
+
if (iv.length !== 12)
|
|
17
|
+
throw new Error('IV must be 12 bytes for AES-GCM');
|
|
19
18
|
const cipher = createCipheriv('aes-256-gcm', k, iv);
|
|
20
|
-
if (options?.aad)
|
|
19
|
+
if (options?.aad)
|
|
21
20
|
cipher.setAAD(toBuffer(options.aad));
|
|
22
|
-
|
|
23
|
-
const plainBuf = toBuffer(plaintext);
|
|
24
|
-
const encrypted = cipher.update(plainBuf);
|
|
25
|
-
const final = cipher.final();
|
|
26
|
-
const ciphertext = encrypted.length === 0
|
|
27
|
-
? final
|
|
28
|
-
: encrypted.length === final.length
|
|
29
|
-
? Buffer.concat([encrypted, final], encrypted.length + final.length)
|
|
30
|
-
: Buffer.concat([encrypted, final]);
|
|
21
|
+
const encrypted = Buffer.concat([cipher.update(toBuffer(plaintext)), cipher.final()]);
|
|
31
22
|
const tag = cipher.getAuthTag();
|
|
23
|
+
k.fill(0);
|
|
32
24
|
return {
|
|
33
|
-
ciphertext: toUint8(
|
|
25
|
+
ciphertext: toUint8(encrypted),
|
|
34
26
|
iv: toUint8(iv),
|
|
35
27
|
tag: toUint8(tag)
|
|
36
28
|
};
|
|
37
29
|
}
|
|
38
|
-
|
|
30
|
+
function decrypt(key, data, options) {
|
|
39
31
|
const k = toBuffer(key);
|
|
40
32
|
const decipher = createDecipheriv('aes-256-gcm', k, toBuffer(data.iv));
|
|
41
33
|
if (options?.aad) {
|
|
@@ -53,28 +45,70 @@ async function decrypt(key, data, options) {
|
|
|
53
45
|
return toUint8(plaintext);
|
|
54
46
|
}
|
|
55
47
|
function hkdf(ikm, salt, info, options) {
|
|
48
|
+
if (!Buffer.isBuffer(Buffer.from(ikm)) && !(ikm instanceof Uint8Array)) {
|
|
49
|
+
throw new TypeError('ikm must be Uint8Array');
|
|
50
|
+
}
|
|
51
|
+
if (ikm.length === 0) {
|
|
52
|
+
throw new Error('IKM cannot be empty');
|
|
53
|
+
}
|
|
54
|
+
if (ikm.length > 1024 * 1024) {
|
|
55
|
+
throw new Error('IKM too large (max 1MB)');
|
|
56
|
+
}
|
|
57
|
+
if (!(salt instanceof Uint8Array)) {
|
|
58
|
+
throw new TypeError('salt must be Uint8Array');
|
|
59
|
+
}
|
|
60
|
+
if (!(info instanceof Uint8Array)) {
|
|
61
|
+
throw new TypeError('info must be Uint8Array');
|
|
62
|
+
}
|
|
56
63
|
const length = options.length;
|
|
64
|
+
if (!Number.isInteger(length) || length <= 0) {
|
|
65
|
+
throw new Error(`length must be positive integer, got ${length}`);
|
|
66
|
+
}
|
|
67
|
+
if (length > 255 * 32) {
|
|
68
|
+
throw new Error(`length exceeds maximum (${255 * 32} bytes)`);
|
|
69
|
+
}
|
|
57
70
|
const hashLen = 32;
|
|
58
71
|
const blocksNeeded = Math.ceil(length / hashLen);
|
|
59
|
-
const
|
|
60
|
-
|
|
61
|
-
.digest();
|
|
62
|
-
const output = Buffer.allocUnsafe(length);
|
|
72
|
+
const ikmBuf = toBuffer(ikm);
|
|
73
|
+
const saltBuf = toBuffer(salt);
|
|
63
74
|
const infoBuf = toBuffer(info);
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
75
|
+
const prkKey = saltBuf.length ? saltBuf : Buffer.alloc(hashLen, 0);
|
|
76
|
+
try {
|
|
77
|
+
const prk = createHmac('sha256', prkKey)
|
|
78
|
+
.update(ikmBuf)
|
|
79
|
+
.digest();
|
|
80
|
+
const output = Buffer.alloc(length);
|
|
81
|
+
let prev = EMPTY_BUFFER;
|
|
82
|
+
const counter = Buffer.alloc(1);
|
|
83
|
+
for (let i = 0; i < blocksNeeded; i++) {
|
|
84
|
+
const hmac = createHmac('sha256', prk);
|
|
85
|
+
if (prev.length) {
|
|
86
|
+
hmac.update(prev);
|
|
87
|
+
}
|
|
88
|
+
if (infoBuf.length) {
|
|
89
|
+
hmac.update(infoBuf);
|
|
90
|
+
}
|
|
91
|
+
counter[0] = i + 1;
|
|
92
|
+
hmac.update(counter);
|
|
93
|
+
prev = hmac.digest();
|
|
94
|
+
const copyLen = Math.min(hashLen, length - (i * hashLen));
|
|
95
|
+
prev.copy(output, i * hashLen, 0, copyLen);
|
|
96
|
+
}
|
|
97
|
+
prk.fill(0);
|
|
98
|
+
prev.fill(0);
|
|
99
|
+
ikmBuf.fill(0);
|
|
100
|
+
if (saltBuf.length)
|
|
101
|
+
saltBuf.fill(0);
|
|
102
|
+
infoBuf.fill(0);
|
|
103
|
+
return toUint8(output);
|
|
104
|
+
}
|
|
105
|
+
catch (err) {
|
|
106
|
+
ikmBuf.fill(0);
|
|
107
|
+
if (saltBuf.length)
|
|
108
|
+
saltBuf.fill(0);
|
|
109
|
+
infoBuf.fill(0);
|
|
110
|
+
throw err;
|
|
76
111
|
}
|
|
77
|
-
return toUint8(output);
|
|
78
112
|
}
|
|
79
113
|
function sha512(data) {
|
|
80
114
|
return toUint8(createHash('sha512')
|
package/dist/curve.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { DHKeyPair, SignalAsymmetricAPI } from '
|
|
1
|
+
import type { DHKeyPair, SignalAsymmetricAPI } from './types/asymmetric.js';
|
|
2
2
|
declare function generateKeyPair(): Promise<DHKeyPair>;
|
|
3
3
|
declare function calculateSignature(identityPrivateKey: Uint8Array, data: Uint8Array): Uint8Array<ArrayBufferLike>;
|
|
4
4
|
export declare const signalCrypto: SignalAsymmetricAPI;
|
package/dist/index.d.ts
CHANGED
|
@@ -7,14 +7,13 @@ export { SessionBuilder } from './session/builder/session-builder.js';
|
|
|
7
7
|
export type { PreKeyBundle, SessionBuilderStorage, KeyPair, IdentityKeyPair } from './session/builder/index.js';
|
|
8
8
|
export { crypto } from './crypto.js';
|
|
9
9
|
export { signalCrypto, generateKeyPair, calculateSignature } from './curve.js';
|
|
10
|
-
export type { CryptoAPI } from '
|
|
11
|
-
export type { SignalAsymmetricAPI, IdentityKeyPair as AsymIdentityKeyPair, DHKeyPair } from '
|
|
10
|
+
export type { CryptoAPI } from './types/crypto.js';
|
|
11
|
+
export type { SignalAsymmetricAPI, IdentityKeyPair as AsymIdentityKeyPair, DHKeyPair } from './types/asymmetric.js';
|
|
12
12
|
export { generateIdentityKeyPair, generateRegistrationId, generateSignedPreKey, generatePreKey } from './key-helper.js';
|
|
13
13
|
export type { SignedPreKey, PreKey } from './key-helper.js';
|
|
14
14
|
export { FingerprintGenerator } from './fingerprint.js';
|
|
15
15
|
export { SignalError, UntrustedIdentityKeyError, SessionError, MessageCounterError, PreKeyError } from './signal-errors.js';
|
|
16
|
-
export
|
|
17
|
-
export { BaseKeyType } from './
|
|
18
|
-
export type { BaseKeyType as BaseKeyTypeValue } from './base_key_type.js';
|
|
16
|
+
export * from "./ratchet-types.js";
|
|
17
|
+
export type { BaseKeyType as BaseKeyTypeValue } from './ratchet-types.js';
|
|
19
18
|
export { PreKeyWhisperMessage, WhisperMessage } from './protobuf.js';
|
|
20
19
|
export { enqueue } from './job_queue.js';
|
package/dist/index.js
CHANGED
|
@@ -7,7 +7,6 @@ export { signalCrypto, generateKeyPair, calculateSignature } from './curve.js';
|
|
|
7
7
|
export { generateIdentityKeyPair, generateRegistrationId, generateSignedPreKey, generatePreKey } from './key-helper.js';
|
|
8
8
|
export { FingerprintGenerator } from './fingerprint.js';
|
|
9
9
|
export { SignalError, UntrustedIdentityKeyError, SessionError, MessageCounterError, PreKeyError } from './signal-errors.js';
|
|
10
|
-
export
|
|
11
|
-
export { BaseKeyType } from './base_key_type.js';
|
|
10
|
+
export * from "./ratchet-types.js";
|
|
12
11
|
export { PreKeyWhisperMessage, WhisperMessage } from './protobuf.js';
|
|
13
12
|
export { enqueue } from './job_queue.js';
|
package/dist/job_queue.js
CHANGED
|
@@ -2,28 +2,32 @@ const queueBuckets = new Map();
|
|
|
2
2
|
const GC_LIMIT = 10_000;
|
|
3
3
|
async function asyncQueueExecutor(bucket, state) {
|
|
4
4
|
const queue = state.queue;
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
5
|
+
try {
|
|
6
|
+
while (state.offset < queue.length) {
|
|
7
|
+
const limit = Math.min(queue.length, state.offset + GC_LIMIT);
|
|
8
|
+
for (let i = state.offset; i < limit; i++) {
|
|
9
|
+
const job = queue[i];
|
|
10
|
+
if (!job)
|
|
11
|
+
continue;
|
|
12
|
+
try {
|
|
13
|
+
const result = await job.awaitable();
|
|
14
|
+
job.resolve(result);
|
|
15
|
+
}
|
|
16
|
+
catch (err) {
|
|
17
|
+
job.reject(err);
|
|
18
|
+
}
|
|
14
19
|
}
|
|
15
|
-
|
|
16
|
-
|
|
20
|
+
state.offset = limit;
|
|
21
|
+
if (limit < queue.length) {
|
|
22
|
+
queue.splice(0, limit);
|
|
23
|
+
state.offset = 0;
|
|
17
24
|
}
|
|
18
25
|
}
|
|
19
|
-
state.offset = limit;
|
|
20
|
-
if (limit < queue.length) {
|
|
21
|
-
queue.splice(0, limit);
|
|
22
|
-
state.offset = 0;
|
|
23
|
-
}
|
|
24
26
|
}
|
|
25
|
-
|
|
26
|
-
|
|
27
|
+
finally {
|
|
28
|
+
state.running = false;
|
|
29
|
+
queueBuckets.delete(bucket);
|
|
30
|
+
}
|
|
27
31
|
}
|
|
28
32
|
export function enqueue(bucket, awaitable) {
|
|
29
33
|
let state = queueBuckets.get(bucket);
|
package/dist/key-helper.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import { BaseKeyType } from
|
|
2
|
-
import { ChainType } from '../../chain_type.js';
|
|
1
|
+
import { BaseKeyType, ChainType } from "../../ratchet-types.js";
|
|
3
2
|
import { SessionRecord } from '../record/index.js';
|
|
4
3
|
import { crypto } from '../../crypto.js';
|
|
5
4
|
import { signalCrypto } from '../../curve.js';
|
|
@@ -13,12 +12,33 @@ export class SessionBuilder {
|
|
|
13
12
|
this.storage = storage;
|
|
14
13
|
}
|
|
15
14
|
async initOutgoing(device) {
|
|
15
|
+
if (!device) {
|
|
16
|
+
throw new TypeError('device must be a PreKeyBundle');
|
|
17
|
+
}
|
|
18
|
+
if (!device.identityKey || device.identityKey.length === 0) {
|
|
19
|
+
throw new Error('Invalid device.identityKey');
|
|
20
|
+
}
|
|
21
|
+
if (!device.signedPreKey) {
|
|
22
|
+
throw new Error('Missing device.signedPreKey');
|
|
23
|
+
}
|
|
24
|
+
if (!device.signedPreKey.publicKey || device.signedPreKey.publicKey.length === 0) {
|
|
25
|
+
throw new Error('Invalid device.signedPreKey.publicKey');
|
|
26
|
+
}
|
|
27
|
+
if (!device.signedPreKey.signature || device.signedPreKey.signature.length === 0) {
|
|
28
|
+
throw new Error('Invalid device.signedPreKey.signature');
|
|
29
|
+
}
|
|
30
|
+
if (device.registrationId == null || device.registrationId < 0) {
|
|
31
|
+
throw new Error('Invalid device.registrationId');
|
|
32
|
+
}
|
|
16
33
|
const fqAddr = this.addr.toString();
|
|
17
34
|
return enqueue(fqAddr, async () => {
|
|
18
35
|
if (!await this.storage.isTrustedIdentity(this.addr.id, device.identityKey)) {
|
|
19
36
|
throw new UntrustedIdentityKeyError(this.addr.id, device.identityKey);
|
|
20
37
|
}
|
|
21
|
-
signalCrypto.verify(device.identityKey, device.signedPreKey.publicKey, device.signedPreKey.signature);
|
|
38
|
+
const signatureValid = signalCrypto.verify(device.identityKey, device.signedPreKey.publicKey, device.signedPreKey.signature);
|
|
39
|
+
if (!signatureValid) {
|
|
40
|
+
throw new Error(`Invalid signature on signedPreKey from ${this.addr}. Possible MITM attack.`);
|
|
41
|
+
}
|
|
22
42
|
const baseKey = await signalCrypto.generateDHKeyPair();
|
|
23
43
|
const session = await this.initSession(true, { pubKey: baseKey.publicKey, privKey: baseKey.privateKey }, undefined, device.identityKey, device.preKey?.publicKey, device.signedPreKey.publicKey, device.registrationId);
|
|
24
44
|
const pendingPreKey = {
|
|
@@ -70,26 +90,26 @@ export class SessionBuilder {
|
|
|
70
90
|
return message.preKeyId;
|
|
71
91
|
}
|
|
72
92
|
async initSession(isInitiator, ourEphemeralKey, ourSignedKey, theirIdentityPubKey, theirEphemeralPubKey, theirSignedPubKey, registrationId) {
|
|
93
|
+
let ourEphemeralForInitSession = ourEphemeralKey;
|
|
94
|
+
let theirEphemeralForInitSession = theirEphemeralPubKey;
|
|
73
95
|
if (isInitiator) {
|
|
74
96
|
ourSignedKey = ourEphemeralKey;
|
|
75
97
|
}
|
|
76
98
|
else {
|
|
77
99
|
theirSignedPubKey = theirEphemeralPubKey;
|
|
78
100
|
}
|
|
79
|
-
const sharedSecretLen = (!
|
|
101
|
+
const sharedSecretLen = (!ourEphemeralForInitSession || !theirEphemeralForInitSession) ? 128 : 160;
|
|
80
102
|
const sharedSecret = new Uint8Array(sharedSecretLen);
|
|
81
103
|
sharedSecret.fill(0xff, 0, 32);
|
|
82
104
|
const ourIdentityKey = await this.storage.getOurIdentity();
|
|
83
|
-
const
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
signalCrypto.calculateAgreement(theirSignedPubKey, ourSignedKey.privKey)
|
|
87
|
-
]);
|
|
105
|
+
const a1 = signalCrypto.calculateAgreement(theirSignedPubKey, ourIdentityKey.privKey);
|
|
106
|
+
const a2 = signalCrypto.calculateAgreement(theirIdentityPubKey, ourSignedKey.privKey);
|
|
107
|
+
const a3 = signalCrypto.calculateAgreement(theirSignedPubKey, ourSignedKey.privKey);
|
|
88
108
|
sharedSecret.set(a1, isInitiator ? 32 : 64);
|
|
89
109
|
sharedSecret.set(a2, isInitiator ? 64 : 32);
|
|
90
110
|
sharedSecret.set(a3, 96);
|
|
91
|
-
if (
|
|
92
|
-
const a4 = signalCrypto.calculateAgreement(
|
|
111
|
+
if (ourEphemeralForInitSession && theirEphemeralForInitSession) {
|
|
112
|
+
const a4 = signalCrypto.calculateAgreement(theirEphemeralForInitSession, ourEphemeralForInitSession.privKey);
|
|
93
113
|
sharedSecret.set(a4, 128);
|
|
94
114
|
}
|
|
95
115
|
const masterKey = this.deriveSecrets(sharedSecret, new Uint8Array(32), new TextEncoder().encode('WhisperText'), 2);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { PROTOCOL_VERSION } from '../constants.js';
|
|
2
2
|
import { WhisperMessageEncoder } from './encoding.js';
|
|
3
|
-
import { assertUint8 } from '../utils.js';
|
|
4
|
-
import { ChainType } from
|
|
3
|
+
import { assertUint8, toBase64 } from '../utils.js';
|
|
4
|
+
import { ChainType } from "../../ratchet-types.js";
|
|
5
5
|
import { ProtocolAddress } from '../../protocol_address.js';
|
|
6
6
|
import { SessionBuilder } from '../builder/session-builder.js';
|
|
7
7
|
import { SessionRecord } from '../record/index.js';
|
|
@@ -69,45 +69,54 @@ export class SessionCipher {
|
|
|
69
69
|
if (!messageKey)
|
|
70
70
|
throw new Error('Message key not generated');
|
|
71
71
|
const keys = this.deriveSecrets(messageKey, new Uint8Array(32), new TextEncoder().encode('WhisperMessageKeys'));
|
|
72
|
-
delete chain.messageKeys[chain.chainKey.counter];
|
|
73
72
|
const [cipherKey, macKey, aadKey] = keys;
|
|
74
|
-
if (!cipherKey || !macKey || !aadKey)
|
|
75
|
-
throw new Error('
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
macInput.set(ourIdentity.pubKey);
|
|
86
|
-
macInput.set(remoteIdentityKey, 33);
|
|
87
|
-
macInput[66] = this._encodeTupleByte(PROTOCOL_VERSION, PROTOCOL_VERSION);
|
|
88
|
-
macInput.set(msgBuf, 67);
|
|
89
|
-
const mac = crypto.hmacSha256(macKey, macInput);
|
|
90
|
-
const result = new Uint8Array(msgBuf.byteLength + 9);
|
|
91
|
-
result[0] = this._encodeTupleByte(PROTOCOL_VERSION, PROTOCOL_VERSION);
|
|
92
|
-
result.set(msgBuf, 1);
|
|
93
|
-
result.set(mac.subarray(0, 8), msgBuf.byteLength + 1);
|
|
94
|
-
await this.storeRecord(record);
|
|
95
|
-
if (session.pendingPreKey) {
|
|
96
|
-
const preKeyMsg = {
|
|
97
|
-
identityKey: ourIdentity.pubKey,
|
|
98
|
-
registrationId: await this.storage.getOurRegistrationId(),
|
|
99
|
-
baseKey: session.pendingPreKey.baseKey,
|
|
100
|
-
signedPreKeyId: session.pendingPreKey.signedKeyId,
|
|
101
|
-
preKeyId: session.pendingPreKey.preKeyId,
|
|
102
|
-
message: result
|
|
73
|
+
if (!cipherKey || !macKey || !aadKey || cipherKey.length !== 32 || macKey.length !== 32 || aadKey.length !== 32) {
|
|
74
|
+
throw new Error('Invalid key derivation');
|
|
75
|
+
}
|
|
76
|
+
let result;
|
|
77
|
+
try {
|
|
78
|
+
const encrypted = await crypto.encrypt(cipherKey, data, { aad: aadKey.subarray(0, 16) });
|
|
79
|
+
const msg = {
|
|
80
|
+
ephemeralKey: session.currentRatchet.ephemeralKeyPair.pubKey,
|
|
81
|
+
counter: chain.chainKey.counter,
|
|
82
|
+
previousCounter: session.currentRatchet.previousCounter,
|
|
83
|
+
ciphertext: encrypted.ciphertext
|
|
103
84
|
};
|
|
104
|
-
const
|
|
105
|
-
const
|
|
85
|
+
const msgBuf = WhisperMessageEncoder.encodeWhisperMessage(msg);
|
|
86
|
+
const macInput = new Uint8Array(msgBuf.byteLength + 67);
|
|
87
|
+
macInput.set(ourIdentity.pubKey);
|
|
88
|
+
macInput.set(remoteIdentityKey, 33);
|
|
89
|
+
macInput[66] = this._encodeTupleByte(PROTOCOL_VERSION, PROTOCOL_VERSION);
|
|
90
|
+
macInput.set(msgBuf, 67);
|
|
91
|
+
const mac = crypto.hmacSha256(macKey, macInput);
|
|
92
|
+
const body = new Uint8Array(msgBuf.byteLength + 9);
|
|
106
93
|
body[0] = this._encodeTupleByte(PROTOCOL_VERSION, PROTOCOL_VERSION);
|
|
107
|
-
body.set(
|
|
108
|
-
|
|
94
|
+
body.set(msgBuf, 1);
|
|
95
|
+
body.set(mac.subarray(0, 8), msgBuf.byteLength + 1);
|
|
96
|
+
if (session.pendingPreKey) {
|
|
97
|
+
const preKeyMsg = {
|
|
98
|
+
identityKey: ourIdentity.pubKey,
|
|
99
|
+
registrationId: await this.storage.getOurRegistrationId(),
|
|
100
|
+
baseKey: session.pendingPreKey.baseKey,
|
|
101
|
+
signedPreKeyId: session.pendingPreKey.signedKeyId,
|
|
102
|
+
preKeyId: session.pendingPreKey.preKeyId,
|
|
103
|
+
message: body
|
|
104
|
+
};
|
|
105
|
+
const preKeyBuf = WhisperMessageEncoder.encodePreKeyWhisperMessage(preKeyMsg);
|
|
106
|
+
const finalBody = new Uint8Array(1 + preKeyBuf.byteLength);
|
|
107
|
+
finalBody[0] = this._encodeTupleByte(PROTOCOL_VERSION, PROTOCOL_VERSION);
|
|
108
|
+
finalBody.set(preKeyBuf, 1);
|
|
109
|
+
result = { type: 3, body: finalBody, registrationId: session.registrationId };
|
|
110
|
+
}
|
|
111
|
+
else {
|
|
112
|
+
result = { type: 1, body, registrationId: session.registrationId };
|
|
113
|
+
}
|
|
109
114
|
}
|
|
110
|
-
|
|
115
|
+
finally {
|
|
116
|
+
delete chain.messageKeys[chain.chainKey.counter];
|
|
117
|
+
}
|
|
118
|
+
await this.storeRecord(record);
|
|
119
|
+
return result;
|
|
111
120
|
});
|
|
112
121
|
}
|
|
113
122
|
async decryptWhisperMessage(data) {
|
|
@@ -136,9 +145,22 @@ export class SessionCipher {
|
|
|
136
145
|
return this.queueJob(async () => {
|
|
137
146
|
let record = await this.getRecord();
|
|
138
147
|
const preKeyProto = WhisperMessageEncoder.decodePreKeyWhisperMessage(data.subarray(1));
|
|
148
|
+
if (!preKeyProto.identityKey || preKeyProto.identityKey.length === 0) {
|
|
149
|
+
throw new Error('Missing or empty identityKey in PreKeyWhisperMessage');
|
|
150
|
+
}
|
|
151
|
+
if (!preKeyProto.baseKey || preKeyProto.baseKey.length === 0) {
|
|
152
|
+
throw new Error('Missing or empty baseKey in PreKeyWhisperMessage');
|
|
153
|
+
}
|
|
154
|
+
if (!preKeyProto.message || preKeyProto.message.length === 0) {
|
|
155
|
+
throw new Error('Missing or empty message in PreKeyWhisperMessage');
|
|
156
|
+
}
|
|
157
|
+
if (preKeyProto.signedPreKeyId == null) {
|
|
158
|
+
throw new Error('Missing signedPreKeyId in PreKeyWhisperMessage');
|
|
159
|
+
}
|
|
160
|
+
if (preKeyProto.registrationId == null) {
|
|
161
|
+
throw new Error('Missing registrationId in PreKeyWhisperMessage');
|
|
162
|
+
}
|
|
139
163
|
if (!record) {
|
|
140
|
-
if (preKeyProto.registrationId == null)
|
|
141
|
-
throw new Error('No registrationId');
|
|
142
164
|
record = new SessionRecord();
|
|
143
165
|
}
|
|
144
166
|
const builder = new SessionBuilder(this.storage, this.addr);
|
|
@@ -175,19 +197,25 @@ export class SessionCipher {
|
|
|
175
197
|
if (!sessions.length)
|
|
176
198
|
throw new SessionError('No sessions available');
|
|
177
199
|
const errors = [];
|
|
178
|
-
for (
|
|
200
|
+
for (let i = 0; i < sessions.length; i++) {
|
|
201
|
+
const session = sessions[i];
|
|
202
|
+
const sessionKey = toBase64(session.indexInfo.baseKey);
|
|
179
203
|
try {
|
|
180
204
|
const plaintext = await this.doDecryptWhisperMessage(data, session);
|
|
181
205
|
session.indexInfo.used = Date.now();
|
|
182
206
|
return { session, plaintext };
|
|
183
207
|
}
|
|
184
208
|
catch (e) {
|
|
185
|
-
errors.push(
|
|
209
|
+
errors.push({
|
|
210
|
+
sessionKey,
|
|
211
|
+
error: e instanceof Error ? e : new Error(String(e))
|
|
212
|
+
});
|
|
186
213
|
}
|
|
187
214
|
}
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
215
|
+
const errorDetails = errors
|
|
216
|
+
.map(({ sessionKey, error }) => `[${sessionKey}]: ${error.message}`)
|
|
217
|
+
.join(' | ');
|
|
218
|
+
throw new SessionError(`No matching sessions found for message. Tried ${sessions.length} sessions. Errors: ${errorDetails}`, { cause: errors[0]?.error });
|
|
191
219
|
}
|
|
192
220
|
async doDecryptWhisperMessage(messageBuffer, session) {
|
|
193
221
|
assertUint8(messageBuffer);
|
|
@@ -231,8 +259,13 @@ export class SessionCipher {
|
|
|
231
259
|
fillMessageKeys(chain, targetCounter) {
|
|
232
260
|
if (chain.chainKey.counter >= targetCounter)
|
|
233
261
|
return;
|
|
234
|
-
|
|
235
|
-
|
|
262
|
+
const maxFutureMessages = 2000;
|
|
263
|
+
const newMessages = targetCounter - chain.chainKey.counter;
|
|
264
|
+
if (newMessages > maxFutureMessages) {
|
|
265
|
+
throw new SessionError(`Over ${maxFutureMessages} messages into the future: ${newMessages} messages`);
|
|
266
|
+
}
|
|
267
|
+
if (targetCounter > Number.MAX_SAFE_INTEGER - 1000) {
|
|
268
|
+
throw new SessionError(`Counter would overflow: current=${chain.chainKey.counter}, target=${targetCounter}`);
|
|
236
269
|
}
|
|
237
270
|
if (chain.chainKey.key === undefined) {
|
|
238
271
|
throw new SessionError('Chain closed');
|
|
@@ -283,18 +316,34 @@ export class SessionCipher {
|
|
|
283
316
|
ratchet.rootKey = masterKeys[0];
|
|
284
317
|
}
|
|
285
318
|
deriveSecrets(input, salt, info, chunks = 3) {
|
|
286
|
-
const
|
|
319
|
+
const expectedLength = chunks * 32;
|
|
320
|
+
const hkdf = crypto.hkdf(input, salt, info, { length: expectedLength });
|
|
321
|
+
if (hkdf.length !== expectedLength) {
|
|
322
|
+
throw new Error(`HKDF derivation failed: expected ${expectedLength} bytes, got ${hkdf.length}`);
|
|
323
|
+
}
|
|
287
324
|
const result = [];
|
|
288
325
|
for (let i = 0; i < chunks; i++) {
|
|
289
|
-
|
|
326
|
+
const key = hkdf.subarray(i * 32, (i + 1) * 32);
|
|
327
|
+
if (key.length !== 32) {
|
|
328
|
+
throw new Error(`Invalid key derivation at chunk ${i}: expected 32 bytes, got ${key.length}`);
|
|
329
|
+
}
|
|
330
|
+
result.push(key);
|
|
290
331
|
}
|
|
291
332
|
return result;
|
|
292
333
|
}
|
|
293
334
|
verifyMAC(macInput, key, mac, length) {
|
|
335
|
+
if (mac.length < length) {
|
|
336
|
+
throw new Error('MAC too short');
|
|
337
|
+
}
|
|
294
338
|
const computed = crypto.hmacSha256(key, macInput);
|
|
339
|
+
let match = true;
|
|
295
340
|
for (let i = 0; i < length; i++) {
|
|
296
|
-
if (computed[i] !== mac[i])
|
|
297
|
-
|
|
341
|
+
if (computed[i] !== mac[i]) {
|
|
342
|
+
match = false;
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
if (!match) {
|
|
346
|
+
throw new Error('MAC verification failed');
|
|
298
347
|
}
|
|
299
348
|
}
|
|
300
349
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { assertUint8, toBase64, u8 } from '../utils.js';
|
|
1
|
+
import { assertUint8, toBase64, fromBase64, u8 } from '../utils.js';
|
|
2
2
|
export class SessionEntry {
|
|
3
3
|
registrationId;
|
|
4
4
|
currentRatchet;
|
|
@@ -113,7 +113,7 @@ export class SessionEntry {
|
|
|
113
113
|
return {
|
|
114
114
|
baseKey: u8.decode(data.baseKey),
|
|
115
115
|
signedKeyId: data.signedKeyId,
|
|
116
|
-
preKeyId: data.preKeyId,
|
|
116
|
+
...(data.preKeyId !== undefined && { preKeyId: data.preKeyId }),
|
|
117
117
|
};
|
|
118
118
|
}
|
|
119
119
|
static deserialize(data) {
|
|
@@ -143,4 +143,3 @@ export class SessionEntry {
|
|
|
143
143
|
return obj;
|
|
144
144
|
}
|
|
145
145
|
}
|
|
146
|
-
import { fromBase64 } from '../utils.js';
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { SessionEntry } from './session-entry.js';
|
|
2
2
|
import { CLOSED_SESSIONS_MAX, SESSION_RECORD_VERSION } from '../constants.js';
|
|
3
3
|
import { assertUint8, toBase64 } from '../utils.js';
|
|
4
|
-
import { BaseKeyType } from
|
|
4
|
+
import { BaseKeyType } from "../../ratchet-types.js";
|
|
5
5
|
export class SessionRecord {
|
|
6
6
|
sessions = {};
|
|
7
7
|
version = SESSION_RECORD_VERSION;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { BaseKeyType } from "../../
|
|
1
|
+
import type { BaseKeyType, ChainType } from "../../ratchet-types.js";
|
|
2
2
|
export interface PendingPreKey {
|
|
3
3
|
baseKey: Uint8Array;
|
|
4
4
|
signedKeyId: number;
|
|
@@ -10,7 +10,7 @@ export interface ChainKey {
|
|
|
10
10
|
}
|
|
11
11
|
export interface ChainState {
|
|
12
12
|
chainKey: ChainKey;
|
|
13
|
-
chainType:
|
|
13
|
+
chainType: ChainType;
|
|
14
14
|
messageKeys: Record<string, Uint8Array>;
|
|
15
15
|
}
|
|
16
16
|
export interface CurrentRatchet {
|
|
@@ -35,7 +35,7 @@ export interface SerializedChainState {
|
|
|
35
35
|
counter: number;
|
|
36
36
|
key: string | undefined;
|
|
37
37
|
};
|
|
38
|
-
chainType:
|
|
38
|
+
chainType: ChainType;
|
|
39
39
|
messageKeys: Record<string, string>;
|
|
40
40
|
}
|
|
41
41
|
export interface SerializedPendingPreKey {
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
export interface IdentityKeyPair {
|
|
2
|
+
readonly publicKey: Uint8Array // 32 bytes Ed25519
|
|
3
|
+
readonly privateKey: Uint8Array // 64 bytes Ed25519
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
export interface DHKeyPair {
|
|
7
|
+
readonly publicKey: Uint8Array // 32 bytes X25519
|
|
8
|
+
readonly privateKey: Uint8Array // 32 bytes X25519
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface SignalAsymmetricAPI {
|
|
12
|
+
/* Identity (Ed25519) */
|
|
13
|
+
generateIdentityKeyPair(): Promise<IdentityKeyPair>
|
|
14
|
+
sign(
|
|
15
|
+
privateKey: Uint8Array,
|
|
16
|
+
message: Uint8Array
|
|
17
|
+
): Uint8Array
|
|
18
|
+
verify(
|
|
19
|
+
publicKey: Uint8Array,
|
|
20
|
+
message: Uint8Array,
|
|
21
|
+
signature: Uint8Array
|
|
22
|
+
): boolean
|
|
23
|
+
|
|
24
|
+
/* DH (X25519) */
|
|
25
|
+
generateDHKeyPair(): Promise<DHKeyPair>
|
|
26
|
+
calculateAgreement(
|
|
27
|
+
publicKey: Uint8Array,
|
|
28
|
+
privateKey: Uint8Array
|
|
29
|
+
): Uint8Array
|
|
30
|
+
|
|
31
|
+
/* Conversion */
|
|
32
|
+
convertIdentityPublicToX25519(
|
|
33
|
+
edPublicKey: Uint8Array
|
|
34
|
+
): Uint8Array
|
|
35
|
+
|
|
36
|
+
convertIdentityPrivateToX25519(
|
|
37
|
+
edPrivateKey: Uint8Array
|
|
38
|
+
): Uint8Array
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export const signalCrypto: SignalAsymmetricAPI
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
export interface CipherResult {
|
|
2
|
+
readonly ciphertext: Uint8Array
|
|
3
|
+
readonly iv: Uint8Array
|
|
4
|
+
readonly tag: Uint8Array
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export interface EncryptOptions {
|
|
8
|
+
readonly aad?: Uint8Array
|
|
9
|
+
readonly iv?: Uint8Array
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface DecryptOptions {
|
|
13
|
+
readonly aad?: Uint8Array
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface HKDFOptions {
|
|
17
|
+
readonly length: number
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* High-level cryptographic API
|
|
22
|
+
*/
|
|
23
|
+
export interface CryptoAPI {
|
|
24
|
+
/**
|
|
25
|
+
* AES-256-GCM encryption
|
|
26
|
+
*/
|
|
27
|
+
encrypt(
|
|
28
|
+
key: Uint8Array,
|
|
29
|
+
plaintext: Uint8Array,
|
|
30
|
+
options?: EncryptOptions
|
|
31
|
+
): CipherResult
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* AES-256-GCM decryption
|
|
35
|
+
*/
|
|
36
|
+
decrypt(
|
|
37
|
+
key: Uint8Array,
|
|
38
|
+
data: CipherResult,
|
|
39
|
+
options?: DecryptOptions
|
|
40
|
+
): Uint8Array
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* HKDF using HMAC-SHA256
|
|
44
|
+
*/
|
|
45
|
+
hkdf(
|
|
46
|
+
ikm: Uint8Array,
|
|
47
|
+
salt: Uint8Array,
|
|
48
|
+
info: Uint8Array,
|
|
49
|
+
options: HKDFOptions
|
|
50
|
+
): Uint8Array
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* SHA-512 digest
|
|
54
|
+
*/
|
|
55
|
+
sha512(data: Uint8Array): Uint8Array
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* HMAC-SHA256
|
|
59
|
+
*/
|
|
60
|
+
hmacSha256(
|
|
61
|
+
key: Uint8Array,
|
|
62
|
+
data: Uint8Array
|
|
63
|
+
): Uint8Array
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Default Node implementation
|
|
68
|
+
*/
|
|
69
|
+
export const crypto: CryptoAPI
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@unknownncat/swt-libsignal",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.6",
|
|
4
4
|
"description": "Libsignal reimplementation using libsodium",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -18,9 +18,14 @@
|
|
|
18
18
|
"dist"
|
|
19
19
|
],
|
|
20
20
|
"scripts": {
|
|
21
|
-
"build": "tsc -p tsconfig.json",
|
|
21
|
+
"build": "tsc -p tsconfig.json && cpy \"src/**/*.d.ts\" dist",
|
|
22
22
|
"dev": "tsx src/index.ts",
|
|
23
23
|
"clean": "rimraf dist",
|
|
24
|
+
"test": "vitest run",
|
|
25
|
+
"test:watch": "vitest",
|
|
26
|
+
"test:coverage": "vitest run --coverage",
|
|
27
|
+
"test:stress": "vitest run test/stress",
|
|
28
|
+
"test:security": "vitest run test/security",
|
|
24
29
|
"prepublishOnly": "npm run clean && npm run build"
|
|
25
30
|
},
|
|
26
31
|
"engines": {
|
|
@@ -33,8 +38,11 @@
|
|
|
33
38
|
"devDependencies": {
|
|
34
39
|
"@protobuf-ts/plugin": "^2.11.1",
|
|
35
40
|
"@types/node": "^20.19.33",
|
|
41
|
+
"@vitest/coverage-v8": "^2.0.0",
|
|
42
|
+
"cpy-cli": "^7.0.0",
|
|
36
43
|
"rimraf": "^5.0.0",
|
|
37
44
|
"tsx": "^4.7.0",
|
|
38
|
-
"typescript": "^5.4.0"
|
|
45
|
+
"typescript": "^5.4.0",
|
|
46
|
+
"vitest": "^2.0.0"
|
|
39
47
|
}
|
|
40
48
|
}
|
package/readme.md
ADDED
package/dist/base_key_type.js
DELETED
package/dist/chain_type.d.ts
DELETED
package/dist/teste.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
package/dist/teste.js
DELETED
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
import * as KeyHelper from "./key-helper.js";
|
|
2
|
-
const preKeys = [];
|
|
3
|
-
const identityKeyPairs = [];
|
|
4
|
-
const signedPreKeys = [];
|
|
5
|
-
for (let i = 0; i < 100; i++) {
|
|
6
|
-
console.time("identityKeyPair");
|
|
7
|
-
const identityKeyPair = await KeyHelper.generateIdentityKeyPair();
|
|
8
|
-
console.timeEnd("identityKeyPair");
|
|
9
|
-
console.time("signedPreKey");
|
|
10
|
-
const signedPreKey = await KeyHelper.generateSignedPreKey(identityKeyPair, i);
|
|
11
|
-
console.timeEnd("signedPreKey");
|
|
12
|
-
preKeys.push(await KeyHelper.generatePreKey(i));
|
|
13
|
-
identityKeyPairs.push(identityKeyPair);
|
|
14
|
-
signedPreKeys.push(signedPreKey);
|
|
15
|
-
}
|
|
16
|
-
console.log(preKeys);
|
|
17
|
-
console.log(identityKeyPairs);
|
|
18
|
-
console.log(signedPreKeys);
|