Skip to content

Commit 9178973

Browse files
committed
feat: custom logger libsignal
1 parent 4599ff8 commit 9178973

File tree

8 files changed

+33
-25
lines changed

8 files changed

+33
-25
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@
4343
"@cacheable/node-cache": "^1.4.0",
4444
"@hapi/boom": "^9.1.3",
4545
"async-mutex": "^0.5.0",
46-
"libsignal": "git+https://github.com/whiskeysockets/libsignal-node",
46+
"libsignal": "git+https://github.com/jlucaso1/libsignal-node#feat-custom-logger",
4747
"lru-cache": "^11.1.0",
4848
"music-metadata": "^11.7.0",
4949
"p-queue": "^9.0.0",

src/Signal/libsignal.ts

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
/* @ts-ignore */
21
import * as libsignal from 'libsignal'
32
import { LRUCache } from 'lru-cache'
43
import type { LIDMapping, SignalAuthState, SignalKeyStoreWithTransaction } from '../Types'
@@ -26,7 +25,7 @@ export function makeLibSignalRepository(
2625
pnToLIDFunc?: (jids: string[]) => Promise<LIDMapping[] | undefined>
2726
): SignalRepositoryWithLIDStore {
2827
const lidMapping = new LIDMappingStore(auth.keys as SignalKeyStoreWithTransaction, logger, pnToLIDFunc)
29-
const storage = signalStorage(auth, lidMapping)
28+
const storage = signalStorage(auth, lidMapping, logger)
3029

3130
const parsedKeys = auth.keys as SignalKeyStoreWithTransaction
3231
const migratedSessionCache = new LRUCache<string, true>({
@@ -77,7 +76,7 @@ export function makeLibSignalRepository(
7776
},
7877
async decryptMessage({ jid, type, ciphertext }) {
7978
const addr = jidToSignalProtocolAddress(jid)
80-
const session = new libsignal.SessionCipher(storage, addr)
79+
const session = new libsignal.SessionCipher(storage, addr, logger)
8180

8281
async function doDecrypt() {
8382
let result: Buffer
@@ -102,7 +101,7 @@ export function makeLibSignalRepository(
102101

103102
async encryptMessage({ jid, data }) {
104103
const addr = jidToSignalProtocolAddress(jid)
105-
const cipher = new libsignal.SessionCipher(storage, addr)
104+
const cipher = new libsignal.SessionCipher(storage, addr, logger)
106105

107106
// Use transaction to ensure atomicity
108107
return parsedKeys.transaction(async () => {
@@ -137,7 +136,7 @@ export function makeLibSignalRepository(
137136

138137
async injectE2ESession({ jid, session }) {
139138
logger.trace({ jid }, 'injecting E2EE session')
140-
const cipher = new libsignal.SessionBuilder(storage, jidToSignalProtocolAddress(jid))
139+
const cipher = new libsignal.SessionBuilder(storage, jidToSignalProtocolAddress(jid), logger)
141140
return parsedKeys.transaction(async () => {
142141
await cipher.initOutgoing(session)
143142
}, jid)
@@ -296,7 +295,7 @@ export function makeLibSignalRepository(
296295
const pnSession = pnSessions[pnAddrStr]
297296
if (pnSession) {
298297
// Session exists (guaranteed from device discovery)
299-
const fromSession = libsignal.SessionRecord.deserialize(pnSession)
298+
const fromSession = libsignal.SessionRecord.deserialize(pnSession, logger)
300299
if (fromSession.haveOpenSession()) {
301300
// Queue for bulk update: copy to LID, delete from PN
302301
sessionUpdates[lidAddrStr] = fromSession.serialize()
@@ -358,7 +357,8 @@ const jidToSignalSenderKeyName = (group: string, user: string): SenderKeyName =>
358357

359358
function signalStorage(
360359
{ creds, keys }: SignalAuthState,
361-
lidMapping: LIDMappingStore
360+
lidMapping: LIDMappingStore,
361+
logger?: ILogger
362362
): SenderKeyStore & libsignal.SignalStorage {
363363
// Shared function to resolve PN signal address to LID if mapping exists
364364
const resolveLIDSignalAddress = async (id: string): Promise<string> => {
@@ -388,7 +388,7 @@ function signalStorage(
388388
const { [wireJid]: sess } = await keys.get('session', [wireJid])
389389

390390
if (sess) {
391-
return libsignal.SessionRecord.deserialize(sess)
391+
return libsignal.SessionRecord.deserialize(sess, logger)
392392
}
393393
} catch (e) {
394394
return null

src/Socket/messages-recv.ts

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -815,7 +815,8 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
815815
const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped)
816816
const companionSharedKey = Curve.sharedKey(
817817
authState.creds.pairingEphemeralKeyPair.private,
818-
codePairingPublicKey
818+
codePairingPublicKey,
819+
logger
819820
)
820821
const random = randomBytes(32)
821822
const linkCodeSalt = randomBytes(32)
@@ -831,7 +832,11 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
831832
const encryptIv = randomBytes(12)
832833
const encrypted = aesEncryptGCM(encryptPayload, linkCodePairingExpanded, encryptIv, Buffer.alloc(0))
833834
const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted])
834-
const identitySharedKey = Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey)
835+
const identitySharedKey = Curve.sharedKey(
836+
authState.creds.signedIdentityKey.private,
837+
primaryIdentityPublicKey,
838+
logger
839+
)
835840
const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random])
836841
authState.creds.advSecretKey = (await hkdf(identityPayload, 32, { info: 'adv_secret' })).toString('base64')
837842
await query({

src/Socket/socket.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -847,7 +847,7 @@ export const makeSocket = (config: SocketConfig) => {
847847
ws.on('CB:iq,,pair-success', async (stanza: BinaryNode) => {
848848
logger.debug('pair success recv')
849849
try {
850-
const { reply, creds: updatedCreds } = configureSuccessfulPairing(stanza, creds)
850+
const { reply, creds: updatedCreds } = configureSuccessfulPairing(stanza, creds, logger)
851851

852852
logger.info(
853853
{ me: updatedCreds.me, platform: updatedCreds.platform },

src/Utils/crypto.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes }
22
import * as curve from 'libsignal/src/curve'
33
import { KEY_BUNDLE_TYPE } from '../Defaults'
44
import type { KeyPair } from '../Types'
5+
import type { ILogger } from './logger'
56

67
// insure browser & node compatibility
78
const { subtle } = globalThis.crypto
@@ -19,14 +20,14 @@ export const Curve = {
1920
public: Buffer.from(pubKey.slice(1))
2021
}
2122
},
22-
sharedKey: (privateKey: Uint8Array, publicKey: Uint8Array) => {
23-
const shared = curve.calculateAgreement(generateSignalPubKey(publicKey), privateKey)
23+
sharedKey: (privateKey: Uint8Array, publicKey: Uint8Array, logger?: ILogger) => {
24+
const shared = curve.calculateAgreement(generateSignalPubKey(publicKey), privateKey, logger)
2425
return Buffer.from(shared)
2526
},
2627
sign: (privateKey: Uint8Array, buf: Uint8Array) => curve.calculateSignature(privateKey, buf),
27-
verify: (pubKey: Uint8Array, message: Uint8Array, signature: Uint8Array) => {
28+
verify: (pubKey: Uint8Array, message: Uint8Array, signature: Uint8Array, logger?: ILogger) => {
2829
try {
29-
curve.verifySignature(generateSignalPubKey(pubKey), message, signature)
30+
curve.verifySignature(generateSignalPubKey(pubKey), message, signature, logger)
3031
return true
3132
} catch (error) {
3233
return false

src/Utils/noise-handler.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -105,10 +105,10 @@ export const makeNoiseHandler = ({
105105
finishInit,
106106
processHandshake: async ({ serverHello }: proto.HandshakeMessage, noiseKey: KeyPair) => {
107107
authenticate(serverHello!.ephemeral!)
108-
await mixIntoKey(Curve.sharedKey(privateKey, serverHello!.ephemeral!))
108+
await mixIntoKey(Curve.sharedKey(privateKey, serverHello!.ephemeral!, logger))
109109

110110
const decStaticContent = decrypt(serverHello!.static!)
111-
await mixIntoKey(Curve.sharedKey(privateKey, decStaticContent))
111+
await mixIntoKey(Curve.sharedKey(privateKey, decStaticContent, logger))
112112

113113
const certDecoded = decrypt(serverHello!.payload!)
114114

@@ -121,7 +121,7 @@ export const makeNoiseHandler = ({
121121
}
122122

123123
const keyEnc = encrypt(noiseKey.public)
124-
await mixIntoKey(Curve.sharedKey(noiseKey.private, serverHello!.ephemeral!))
124+
await mixIntoKey(Curve.sharedKey(noiseKey.private, serverHello!.ephemeral!, logger))
125125

126126
return keyEnc
127127
},

src/Utils/validate-connection.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import type { AuthenticationCreds, SignalCreds, SocketConfig } from '../Types'
1111
import { type BinaryNode, getBinaryNodeChild, jidDecode, S_WHATSAPP_NET } from '../WABinary'
1212
import { Curve, hmacSign } from './crypto'
1313
import { encodeBigEndian } from './generics'
14+
import type { ILogger } from './logger'
1415
import { createSignalIdentity } from './signal'
1516

1617
const getUserAgent = (config: SocketConfig): proto.ClientPayload.IUserAgent => {
@@ -145,7 +146,8 @@ export const configureSuccessfulPairing = (
145146
advSecretKey,
146147
signedIdentityKey,
147148
signalIdentities
148-
}: Pick<AuthenticationCreds, 'advSecretKey' | 'signedIdentityKey' | 'signalIdentities'>
149+
}: Pick<AuthenticationCreds, 'advSecretKey' | 'signedIdentityKey' | 'signalIdentities'>,
150+
logger?: ILogger
149151
) => {
150152
const msgId = stanza.attrs.id
151153

@@ -186,7 +188,7 @@ export const configureSuccessfulPairing = (
186188
? WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX
187189
: WA_ADV_ACCOUNT_SIG_PREFIX
188190
const accountMsg = Buffer.concat([accountSignaturePrefix, deviceDetails!, signedIdentityKey.public])
189-
if (!Curve.verify(accountSignatureKey!, accountMsg, accountSignature!)) {
191+
if (!Curve.verify(accountSignatureKey!, accountMsg, accountSignature!, logger)) {
190192
throw new Boom('Failed to verify account signature')
191193
}
192194

yarn.lock

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3007,7 +3007,7 @@ __metadata:
30073007
jimp: "npm:^1.6.0"
30083008
jiti: "npm:^2.4.2"
30093009
json: "npm:^11.0.0"
3010-
libsignal: "git+https://github.com/whiskeysockets/libsignal-node"
3010+
libsignal: "git+https://github.com/jlucaso1/libsignal-node#feat-custom-logger"
30113011
link-preview-js: "npm:^3.0.0"
30123012
lru-cache: "npm:^11.1.0"
30133013
music-metadata: "npm:^11.7.0"
@@ -6976,13 +6976,13 @@ __metadata:
69766976
languageName: node
69776977
linkType: hard
69786978

6979-
"libsignal@git+https://github.com/whiskeysockets/libsignal-node":
6979+
"libsignal@git+https://github.com/jlucaso1/libsignal-node#feat-custom-logger":
69806980
version: 2.0.1
6981-
resolution: "libsignal@https://github.com/whiskeysockets/libsignal-node.git#commit=e81ecfc32eb74951d789ab37f7e341ab66d5fff1"
6981+
resolution: "libsignal@https://github.com/jlucaso1/libsignal-node.git#commit=98e361089320a9dbac04e5304ede77b7dfa1628a"
69826982
dependencies:
69836983
curve25519-js: "npm:^0.0.4"
69846984
protobufjs: "npm:6.8.8"
6985-
checksum: 10c0/d1ae7d8a5fadd6bb1c486d1b2ebc388967fee57c13f52b473127c1cbd9cd647b44545ff07c2b9cc49b3dea4e25ccfcfece31c526fdbdbf065837c85d189e97a0
6985+
checksum: 10c0/61c3589038f85ccc85fdf925bdf9a876f93642e5e591c3b6a123ba71c183bd9bb5220f229dbe5c8267cdc95ad57b6103e5a6e1b5f60593b75882be29ff838046
69866986
languageName: node
69876987
linkType: hard
69886988

0 commit comments

Comments
 (0)