@ms-nicky/baileys 2.0.3
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/README.md +461 -0
- package/WAProto/index.js +169661 -0
- package/lib/Defaults/baileys-version.json +3 -0
- package/lib/Defaults/index.js +147 -0
- package/lib/Defaults/phonenumber-mcc.json +223 -0
- package/lib/Signal/Group/ciphertext-message.js +15 -0
- package/lib/Signal/Group/group-session-builder.js +64 -0
- package/lib/Signal/Group/group_cipher.js +96 -0
- package/lib/Signal/Group/index.js +57 -0
- package/lib/Signal/Group/keyhelper.js +55 -0
- package/lib/Signal/Group/queue-job.js +57 -0
- package/lib/Signal/Group/sender-chain-key.js +34 -0
- package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
- package/lib/Signal/Group/sender-key-message.js +69 -0
- package/lib/Signal/Group/sender-key-name.js +51 -0
- package/lib/Signal/Group/sender-key-record.js +53 -0
- package/lib/Signal/Group/sender-key-state.js +99 -0
- package/lib/Signal/Group/sender-message-key.js +29 -0
- package/lib/Signal/libsignal.js +174 -0
- package/lib/Socket/Client/abstract-socket-client.js +13 -0
- package/lib/Socket/Client/index.js +19 -0
- package/lib/Socket/Client/mobile-socket-client.js +65 -0
- package/lib/Socket/Client/web-socket-client.js +62 -0
- package/lib/Socket/business.js +263 -0
- package/lib/Socket/chats.js +1017 -0
- package/lib/Socket/dugong.js +637 -0
- package/lib/Socket/groups.js +320 -0
- package/lib/Socket/index.js +11 -0
- package/lib/Socket/messages-recv.js +1121 -0
- package/lib/Socket/messages-send.js +848 -0
- package/lib/Socket/newsletter.js +430 -0
- package/lib/Socket/registration.js +169 -0
- package/lib/Socket/socket.js +736 -0
- package/lib/Socket/usync.js +70 -0
- package/lib/Store/index.js +10 -0
- package/lib/Store/make-cache-manager-store.js +83 -0
- package/lib/Store/make-in-memory-store.js +427 -0
- package/lib/Store/make-ordered-dictionary.js +81 -0
- package/lib/Store/object-repository.js +27 -0
- package/lib/Types/Auth.js +2 -0
- package/lib/Types/Call.js +2 -0
- package/lib/Types/Chat.js +4 -0
- package/lib/Types/Contact.js +2 -0
- package/lib/Types/Events.js +2 -0
- package/lib/Types/GroupMetadata.js +2 -0
- package/lib/Types/Label.js +27 -0
- package/lib/Types/LabelAssociation.js +9 -0
- package/lib/Types/Message.js +9 -0
- package/lib/Types/Newsletter.js +38 -0
- package/lib/Types/Product.js +2 -0
- package/lib/Types/Signal.js +2 -0
- package/lib/Types/Socket.js +2 -0
- package/lib/Types/State.js +2 -0
- package/lib/Types/USync.js +2 -0
- package/lib/Types/index.js +42 -0
- package/lib/Utils/auth-utils.js +206 -0
- package/lib/Utils/baileys-event-stream.js +63 -0
- package/lib/Utils/business.js +234 -0
- package/lib/Utils/chat-utils.js +729 -0
- package/lib/Utils/crypto.js +151 -0
- package/lib/Utils/decode-wa-message.js +198 -0
- package/lib/Utils/event-buffer.js +514 -0
- package/lib/Utils/generics.js +509 -0
- package/lib/Utils/history.js +96 -0
- package/lib/Utils/index.js +33 -0
- package/lib/Utils/link-preview.js +93 -0
- package/lib/Utils/logger.js +7 -0
- package/lib/Utils/lt-hash.js +51 -0
- package/lib/Utils/make-mutex.js +43 -0
- package/lib/Utils/messages-media.js +822 -0
- package/lib/Utils/messages.js +787 -0
- package/lib/Utils/noise-handler.js +158 -0
- package/lib/Utils/process-message.js +321 -0
- package/lib/Utils/signal.js +153 -0
- package/lib/Utils/use-multi-file-auth-state.js +119 -0
- package/lib/Utils/validate-connection.js +229 -0
- package/lib/Voip/assets/wasm/loader.js +5 -0
- package/lib/Voip/assets/wasm/whatsapp.wasm +0 -0
- package/lib/Voip/assets/wasm/worker-modules.js +273 -0
- package/lib/Voip/baileys.mjs +23 -0
- package/lib/Voip/dist/audio-feeder.d.mts +15 -0
- package/lib/Voip/dist/audio-feeder.mjs +132 -0
- package/lib/Voip/dist/index.d.mts +50 -0
- package/lib/Voip/dist/index.mjs +373 -0
- package/lib/Voip/dist/relay-transport.d.mts +43 -0
- package/lib/Voip/dist/relay-transport.mjs +559 -0
- package/lib/Voip/dist/signaling.d.mts +41 -0
- package/lib/Voip/dist/signaling.mjs +602 -0
- package/lib/Voip/dist/types.d.mts +69 -0
- package/lib/Voip/dist/types.mjs +17 -0
- package/lib/Voip/dist/wasm-engine.d.mts +103 -0
- package/lib/Voip/dist/wasm-engine.mjs +1214 -0
- package/lib/Voip/dist/worker-bootstrap.mjs +1042 -0
- package/lib/Voip/index.js +26 -0
- package/lib/WABinary/constants.js +40 -0
- package/lib/WABinary/decode.js +252 -0
- package/lib/WABinary/encode.js +265 -0
- package/lib/WABinary/generic-utils.js +198 -0
- package/lib/WABinary/index.js +21 -0
- package/lib/WABinary/jid-utils.js +62 -0
- package/lib/WABinary/types.js +2 -0
- package/lib/WAM/BinaryInfo.js +13 -0
- package/lib/WAM/constants.js +15350 -0
- package/lib/WAM/encode.js +155 -0
- package/lib/WAM/index.js +19 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
- package/lib/WAUSync/Protocols/index.js +20 -0
- package/lib/WAUSync/USyncQuery.js +89 -0
- package/lib/WAUSync/USyncUser.js +26 -0
- package/lib/WAUSync/index.js +19 -0
- package/lib/index.js +39 -0
- package/package.json +108 -0
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import cjs from "../index.js";
|
|
2
|
+
export const {
|
|
3
|
+
default: makeWASocket,
|
|
4
|
+
useMultiFileAuthState,
|
|
5
|
+
makeCacheableSignalKeyStore,
|
|
6
|
+
DisconnectReason,
|
|
7
|
+
Browsers,
|
|
8
|
+
proto,
|
|
9
|
+
jidNormalizedUser,
|
|
10
|
+
jidEncode,
|
|
11
|
+
jidDecode,
|
|
12
|
+
generateMessageID,
|
|
13
|
+
encodeSignedDeviceIdentity,
|
|
14
|
+
decodeBinaryNode,
|
|
15
|
+
getBinaryNodeChild,
|
|
16
|
+
getAllBinaryNodeChildren,
|
|
17
|
+
getCallStatusFromNode,
|
|
18
|
+
encodeBinaryNode,
|
|
19
|
+
parseAndInjectE2ESessions,
|
|
20
|
+
encodeWAMessage,
|
|
21
|
+
unpadRandomMax16,
|
|
22
|
+
} = cjs;
|
|
23
|
+
export default makeWASocket;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export declare class AudioFeeder {
|
|
2
|
+
#private;
|
|
3
|
+
private readonly sampleRate;
|
|
4
|
+
private readonly channels;
|
|
5
|
+
private readonly framesPerChunk;
|
|
6
|
+
private readonly onChunk;
|
|
7
|
+
private readonly source;
|
|
8
|
+
droppedChunks: number;
|
|
9
|
+
underflowChunks: number;
|
|
10
|
+
bytesProduced: number;
|
|
11
|
+
chunksEmitted: number;
|
|
12
|
+
constructor(sampleRate: number, channels: number, framesPerChunk: number, onChunk: (chunk: Float32Array) => void, source?: string);
|
|
13
|
+
start: () => void;
|
|
14
|
+
stop: () => void;
|
|
15
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Audio feeder.
|
|
3
|
+
*
|
|
4
|
+
* Spawns ffmpeg to decode `source` into f32le PCM at the requested rate, then
|
|
5
|
+
* meters frames out at chunk-cadence to the WASM uplink.
|
|
6
|
+
*
|
|
7
|
+
* @author ShellTear
|
|
8
|
+
*/
|
|
9
|
+
import { spawn } from "node:child_process";
|
|
10
|
+
const LOW_WATERMARK_CHUNKS = 16;
|
|
11
|
+
const MAX_QUEUED_CHUNKS = 1024;
|
|
12
|
+
const DEFAULT_WARMUP_MS = 500;
|
|
13
|
+
export class AudioFeeder {
|
|
14
|
+
sampleRate;
|
|
15
|
+
channels;
|
|
16
|
+
framesPerChunk;
|
|
17
|
+
onChunk;
|
|
18
|
+
source;
|
|
19
|
+
#proc = null;
|
|
20
|
+
#pending = Buffer.alloc(0);
|
|
21
|
+
#queue = [];
|
|
22
|
+
#emitTimer = null;
|
|
23
|
+
#nextEmitAtMs = 0;
|
|
24
|
+
#warmupUntilMs = 0;
|
|
25
|
+
droppedChunks = 0;
|
|
26
|
+
underflowChunks = 0;
|
|
27
|
+
bytesProduced = 0;
|
|
28
|
+
chunksEmitted = 0;
|
|
29
|
+
constructor(sampleRate, channels, framesPerChunk, onChunk, source = "silence") {
|
|
30
|
+
this.sampleRate = sampleRate;
|
|
31
|
+
this.channels = channels;
|
|
32
|
+
this.framesPerChunk = framesPerChunk;
|
|
33
|
+
this.onChunk = onChunk;
|
|
34
|
+
this.source = source;
|
|
35
|
+
}
|
|
36
|
+
start = () => {
|
|
37
|
+
if (this.#proc)
|
|
38
|
+
return;
|
|
39
|
+
const chunkSamples = this.framesPerChunk * this.channels;
|
|
40
|
+
const chunkBytes = chunkSamples * Float32Array.BYTES_PER_ELEMENT;
|
|
41
|
+
const chunkIntervalMs = (this.framesPerChunk / this.sampleRate) * 1000;
|
|
42
|
+
const inputArgs = this.#resolveInputArgs();
|
|
43
|
+
this.#proc = spawn("ffmpeg", [
|
|
44
|
+
"-hide_banner",
|
|
45
|
+
"-loglevel", "error",
|
|
46
|
+
"-thread_queue_size", "512",
|
|
47
|
+
...inputArgs,
|
|
48
|
+
"-f", "f32le",
|
|
49
|
+
"-ac", String(this.channels),
|
|
50
|
+
"-ar", String(this.sampleRate),
|
|
51
|
+
"pipe:1",
|
|
52
|
+
]);
|
|
53
|
+
this.#proc.stdout.on("data", (chunk) => {
|
|
54
|
+
this.#pending = Buffer.concat([this.#pending, chunk]);
|
|
55
|
+
while (this.#pending.length >= chunkBytes) {
|
|
56
|
+
if (this.#queue.length >= MAX_QUEUED_CHUNKS) {
|
|
57
|
+
this.#proc?.stdout.pause();
|
|
58
|
+
break;
|
|
59
|
+
}
|
|
60
|
+
const frame = this.#pending.subarray(0, chunkBytes);
|
|
61
|
+
this.#pending = this.#pending.subarray(chunkBytes);
|
|
62
|
+
const out = new Float32Array(chunkSamples);
|
|
63
|
+
out.set(new Float32Array(frame.buffer, frame.byteOffset, chunkSamples));
|
|
64
|
+
this.bytesProduced += chunkBytes;
|
|
65
|
+
this.#queue.push(out);
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
this.#proc.stderr.on("data", (chunk) => {
|
|
69
|
+
process.stderr.write(`[AudioFeeder] ${chunk.toString().trim()}\n`);
|
|
70
|
+
});
|
|
71
|
+
this.#proc.on("exit", (code) => {
|
|
72
|
+
if (code !== 0 && code !== null) {
|
|
73
|
+
process.stderr.write(`[AudioFeeder] ffmpeg exited with code=${code}\n`);
|
|
74
|
+
}
|
|
75
|
+
this.#proc = null;
|
|
76
|
+
});
|
|
77
|
+
this.#nextEmitAtMs = 0;
|
|
78
|
+
this.#warmupUntilMs = Date.now() + DEFAULT_WARMUP_MS;
|
|
79
|
+
this.#scheduleNext(chunkSamples, chunkIntervalMs);
|
|
80
|
+
};
|
|
81
|
+
stop = () => {
|
|
82
|
+
if (this.#emitTimer) {
|
|
83
|
+
clearTimeout(this.#emitTimer);
|
|
84
|
+
this.#emitTimer = null;
|
|
85
|
+
}
|
|
86
|
+
this.#proc?.kill("SIGTERM");
|
|
87
|
+
this.#proc = null;
|
|
88
|
+
this.#pending = Buffer.alloc(0);
|
|
89
|
+
this.#queue = [];
|
|
90
|
+
this.#warmupUntilMs = 0;
|
|
91
|
+
};
|
|
92
|
+
#resolveInputArgs = () => {
|
|
93
|
+
if (!this.source || this.source === "silence") {
|
|
94
|
+
return ["-f", "lavfi", "-i", `aevalsrc=0:d=3600:s=${this.sampleRate}`];
|
|
95
|
+
}
|
|
96
|
+
if (this.source.startsWith("lavfi:")) {
|
|
97
|
+
return ["-f", "lavfi", "-i", this.source.slice("lavfi:".length)];
|
|
98
|
+
}
|
|
99
|
+
return ["-i", this.source];
|
|
100
|
+
};
|
|
101
|
+
#scheduleNext = (chunkSamples, chunkIntervalMs) => {
|
|
102
|
+
if (!this.#proc)
|
|
103
|
+
return;
|
|
104
|
+
const now = Date.now();
|
|
105
|
+
if (this.#nextEmitAtMs === 0)
|
|
106
|
+
this.#nextEmitAtMs = now;
|
|
107
|
+
const delayMs = Math.max(0, this.#nextEmitAtMs - now);
|
|
108
|
+
this.#emitTimer = setTimeout(() => {
|
|
109
|
+
this.#emitTimer = null;
|
|
110
|
+
if (this.#queue.length < LOW_WATERMARK_CHUNKS && Date.now() < this.#warmupUntilMs) {
|
|
111
|
+
this.#nextEmitAtMs = Date.now() + 10;
|
|
112
|
+
this.#scheduleNext(chunkSamples, chunkIntervalMs);
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
this.#flushOne(chunkSamples);
|
|
116
|
+
this.#nextEmitAtMs += chunkIntervalMs;
|
|
117
|
+
this.#scheduleNext(chunkSamples, chunkIntervalMs);
|
|
118
|
+
}, delayMs);
|
|
119
|
+
};
|
|
120
|
+
#flushOne = (chunkSamples) => {
|
|
121
|
+
let nextChunk = this.#queue.shift();
|
|
122
|
+
if (!nextChunk) {
|
|
123
|
+
nextChunk = new Float32Array(chunkSamples);
|
|
124
|
+
this.underflowChunks += 1;
|
|
125
|
+
}
|
|
126
|
+
this.chunksEmitted += 1;
|
|
127
|
+
this.onChunk(nextChunk);
|
|
128
|
+
if (this.#proc?.stdout.isPaused() && this.#queue.length <= MAX_QUEUED_CHUNKS / 4) {
|
|
129
|
+
this.#proc.stdout.resume();
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* baileys-caller — WhatsApp voice calling for Node.js.
|
|
3
|
+
*
|
|
4
|
+
* Wraps WhatsApp Web's official VoIP WASM stack and routes signaling through
|
|
5
|
+
* Baileys. Public surface:
|
|
6
|
+
*
|
|
7
|
+
* const client = new VoipClient({ authDir })
|
|
8
|
+
* await client.connect()
|
|
9
|
+
* const call = await client.call("12345678901", { audioSource: "./hi.mp3" })
|
|
10
|
+
*
|
|
11
|
+
* @author ShellTear
|
|
12
|
+
*/
|
|
13
|
+
import { EventEmitter } from "node:events";
|
|
14
|
+
import { WasmEngine } from "./wasm-engine.mjs";
|
|
15
|
+
import { CallState, type VoipSdkConfig } from "./types.mjs";
|
|
16
|
+
export type { VoipSdkConfig, CallOptions, CallEvents, AudioConfig } from "./types.mjs";
|
|
17
|
+
export { CallState } from "./types.mjs";
|
|
18
|
+
/** A live or recently-ended call. */
|
|
19
|
+
export declare class ActiveCall extends EventEmitter {
|
|
20
|
+
#private;
|
|
21
|
+
readonly callId: string;
|
|
22
|
+
private readonly engine;
|
|
23
|
+
/** @internal mirrors the source path for the audio feeder */
|
|
24
|
+
_audioSource: string;
|
|
25
|
+
constructor(callId: string, engine: WasmEngine, durationMs: number);
|
|
26
|
+
get state(): CallState;
|
|
27
|
+
end: () => void;
|
|
28
|
+
mute: (muted: boolean) => void;
|
|
29
|
+
waitForEnd: () => Promise<string>;
|
|
30
|
+
/** @internal — called by VoipClient on WASM call-state change */
|
|
31
|
+
_updateState: (state: number) => void;
|
|
32
|
+
/** @internal */
|
|
33
|
+
_emitAudio: (pcm: Float32Array) => void;
|
|
34
|
+
/** @internal */
|
|
35
|
+
_forceEnd: (reason: string) => void;
|
|
36
|
+
}
|
|
37
|
+
/** Top-level client. Connects to WhatsApp and lets you place calls. */
|
|
38
|
+
export declare class VoipClient {
|
|
39
|
+
#private;
|
|
40
|
+
constructor(config: VoipSdkConfig);
|
|
41
|
+
/** Connect to WhatsApp and bring up the WASM VoIP stack. */
|
|
42
|
+
connect: () => Promise<void>;
|
|
43
|
+
/** Place an outbound voice call. */
|
|
44
|
+
call: (phoneNumber: string, opts?: {
|
|
45
|
+
audioSource?: string;
|
|
46
|
+
durationMs?: number;
|
|
47
|
+
}) => Promise<ActiveCall>;
|
|
48
|
+
/** Tear down the WhatsApp socket and release resources. */
|
|
49
|
+
disconnect: () => void;
|
|
50
|
+
}
|
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* baileys-caller — WhatsApp voice calling for Node.js.
|
|
3
|
+
*
|
|
4
|
+
* Wraps WhatsApp Web's official VoIP WASM stack and routes signaling through
|
|
5
|
+
* Baileys. Public surface:
|
|
6
|
+
*
|
|
7
|
+
* const client = new VoipClient({ authDir })
|
|
8
|
+
* await client.connect()
|
|
9
|
+
* const call = await client.call("12345678901", { audioSource: "./hi.mp3" })
|
|
10
|
+
*
|
|
11
|
+
* @author ShellTear
|
|
12
|
+
*/
|
|
13
|
+
import { EventEmitter } from "node:events";
|
|
14
|
+
import { randomBytes, createHmac } from "node:crypto";
|
|
15
|
+
import { resolve } from "node:path";
|
|
16
|
+
import { WasmEngine } from "./wasm-engine.mjs";
|
|
17
|
+
import { RelayRtcTransport } from "./relay-transport.mjs";
|
|
18
|
+
import { SignalingBridge } from "./signaling.mjs";
|
|
19
|
+
import { AudioFeeder } from "./audio-feeder.mjs";
|
|
20
|
+
import { CallState } from "./types.mjs";
|
|
21
|
+
export { CallState } from "./types.mjs";
|
|
22
|
+
const SHA256_LEN = 32;
|
|
23
|
+
const loadBaileys = async () => {
|
|
24
|
+
try {
|
|
25
|
+
return await import("../baileys.mjs");
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
throw new Error("Could not import @ms-nicky/baileys.");
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
const toBareJid = (jid) => {
|
|
32
|
+
if (!jid)
|
|
33
|
+
return jid;
|
|
34
|
+
const at = jid.indexOf("@");
|
|
35
|
+
if (at < 0)
|
|
36
|
+
return jid;
|
|
37
|
+
const user = jid.slice(0, at).split(":")[0];
|
|
38
|
+
return `${user}@${jid.slice(at + 1)}`;
|
|
39
|
+
};
|
|
40
|
+
const computeHkdf = (key, salt, info, length) => {
|
|
41
|
+
const effectiveSalt = salt && salt.length > 0 ? Buffer.from(salt) : Buffer.alloc(SHA256_LEN, 0);
|
|
42
|
+
const prk = createHmac("sha256", effectiveSalt).update(key).digest();
|
|
43
|
+
const blocks = Math.ceil(length / SHA256_LEN);
|
|
44
|
+
const okm = Buffer.alloc(blocks * SHA256_LEN);
|
|
45
|
+
let prev = Buffer.alloc(0);
|
|
46
|
+
for (let i = 1; i <= blocks; i += 1) {
|
|
47
|
+
prev = createHmac("sha256", prk)
|
|
48
|
+
.update(prev)
|
|
49
|
+
.update(info)
|
|
50
|
+
.update(Buffer.from([i]))
|
|
51
|
+
.digest();
|
|
52
|
+
prev.copy(okm, (i - 1) * SHA256_LEN);
|
|
53
|
+
}
|
|
54
|
+
return new Uint8Array(okm.buffer, okm.byteOffset, length);
|
|
55
|
+
};
|
|
56
|
+
const computeHmacSha256 = (data, key) => {
|
|
57
|
+
const result = createHmac("sha256", Buffer.from(key)).update(data).digest();
|
|
58
|
+
return new Uint8Array(result.buffer, result.byteOffset, result.byteLength);
|
|
59
|
+
};
|
|
60
|
+
const isCallReceiptNode = (node) => {
|
|
61
|
+
if (node?.tag !== "receipt")
|
|
62
|
+
return false;
|
|
63
|
+
const child = Array.isArray(node.content) ? node.content[0] : null;
|
|
64
|
+
return !!(child?.attrs?.["call-id"] || child?.attrs?.call_id);
|
|
65
|
+
};
|
|
66
|
+
/** A live or recently-ended call. */
|
|
67
|
+
export class ActiveCall extends EventEmitter {
|
|
68
|
+
callId;
|
|
69
|
+
engine;
|
|
70
|
+
#state = CallState.Idle;
|
|
71
|
+
#endResolver;
|
|
72
|
+
#endPromise;
|
|
73
|
+
#endTimer = null;
|
|
74
|
+
#ended = false;
|
|
75
|
+
/** @internal mirrors the source path for the audio feeder */
|
|
76
|
+
_audioSource = "silence";
|
|
77
|
+
constructor(callId, engine, durationMs) {
|
|
78
|
+
super();
|
|
79
|
+
this.callId = callId;
|
|
80
|
+
this.engine = engine;
|
|
81
|
+
this.#endPromise = new Promise((res) => { this.#endResolver = res; });
|
|
82
|
+
if (durationMs > 0) {
|
|
83
|
+
this.#endTimer = setTimeout(() => this.end(), durationMs);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
get state() { return this.#state; }
|
|
87
|
+
end = () => {
|
|
88
|
+
if (this.#ended)
|
|
89
|
+
return;
|
|
90
|
+
this.#ended = true;
|
|
91
|
+
if (this.#endTimer) {
|
|
92
|
+
clearTimeout(this.#endTimer);
|
|
93
|
+
this.#endTimer = null;
|
|
94
|
+
}
|
|
95
|
+
try {
|
|
96
|
+
this.engine.endCall(0, true);
|
|
97
|
+
}
|
|
98
|
+
catch { }
|
|
99
|
+
};
|
|
100
|
+
mute = (muted) => {
|
|
101
|
+
try {
|
|
102
|
+
this.engine.setMute(muted);
|
|
103
|
+
}
|
|
104
|
+
catch { }
|
|
105
|
+
};
|
|
106
|
+
waitForEnd = () => this.#endPromise;
|
|
107
|
+
/** @internal — called by VoipClient on WASM call-state change */
|
|
108
|
+
_updateState = (state) => {
|
|
109
|
+
this.#state = state;
|
|
110
|
+
if (state === CallState.PreacceptReceived)
|
|
111
|
+
this.emit("ringing");
|
|
112
|
+
else if (state === CallState.Active)
|
|
113
|
+
this.emit("connected");
|
|
114
|
+
else if (state === CallState.Idle || state === CallState.Ending) {
|
|
115
|
+
this._forceEnd("ended");
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
/** @internal */
|
|
119
|
+
_emitAudio = (pcm) => { this.emit("audio", pcm); };
|
|
120
|
+
/** @internal */
|
|
121
|
+
_forceEnd = (reason) => {
|
|
122
|
+
if (this.#ended)
|
|
123
|
+
return;
|
|
124
|
+
this.#ended = true;
|
|
125
|
+
if (this.#endTimer) {
|
|
126
|
+
clearTimeout(this.#endTimer);
|
|
127
|
+
this.#endTimer = null;
|
|
128
|
+
}
|
|
129
|
+
this.emit("ended", reason);
|
|
130
|
+
this.#endResolver(reason);
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
/** Top-level client. Connects to WhatsApp and lets you place calls. */
|
|
134
|
+
export class VoipClient {
|
|
135
|
+
#config;
|
|
136
|
+
#engine = null;
|
|
137
|
+
#relay = null;
|
|
138
|
+
#signaling = null;
|
|
139
|
+
#sock = null;
|
|
140
|
+
#activeCall = null;
|
|
141
|
+
#baileys = null;
|
|
142
|
+
// Capture state populated when WASM negotiates audio params
|
|
143
|
+
#capturePtr = 0;
|
|
144
|
+
#captureChunkBytes = 0;
|
|
145
|
+
#captureSampleRate = 16000;
|
|
146
|
+
#captureChannels = 1;
|
|
147
|
+
#captureFramesPerChunk = 320;
|
|
148
|
+
#feeder = null;
|
|
149
|
+
constructor(config) {
|
|
150
|
+
this.#config = config;
|
|
151
|
+
}
|
|
152
|
+
/** Connect to WhatsApp and bring up the WASM VoIP stack. */
|
|
153
|
+
connect = async () => {
|
|
154
|
+
this.#baileys = await loadBaileys();
|
|
155
|
+
const { useMultiFileAuthState, default: makeWASocket, DisconnectReason } = this.#baileys;
|
|
156
|
+
const makeSocket = makeWASocket ?? this.#baileys.makeWASocket ?? this.#baileys;
|
|
157
|
+
const authDir = resolve(this.#config.authDir);
|
|
158
|
+
const { state, saveCreds } = await useMultiFileAuthState(authDir);
|
|
159
|
+
const silentLogger = {
|
|
160
|
+
level: "silent",
|
|
161
|
+
child: () => silentLogger,
|
|
162
|
+
trace: () => { },
|
|
163
|
+
debug: () => { },
|
|
164
|
+
info: () => { },
|
|
165
|
+
warn: () => { },
|
|
166
|
+
error: () => { },
|
|
167
|
+
fatal: () => { },
|
|
168
|
+
};
|
|
169
|
+
const createSocket = () => makeSocket({
|
|
170
|
+
auth: state,
|
|
171
|
+
emitOwnEvents: true,
|
|
172
|
+
logger: silentLogger,
|
|
173
|
+
});
|
|
174
|
+
// Connect with auto-reconnect on the post-QR 515 stream-error path.
|
|
175
|
+
await new Promise((resolveOpen, rejectOpen) => {
|
|
176
|
+
let opened = false;
|
|
177
|
+
let retries = 0;
|
|
178
|
+
const maxRetries = 5;
|
|
179
|
+
const connectSocket = () => {
|
|
180
|
+
this.#sock = createSocket();
|
|
181
|
+
this.#sock.ev.on("creds.update", saveCreds);
|
|
182
|
+
process.removeAllListeners("uncaughtException");
|
|
183
|
+
process.on("uncaughtException", (err) => {
|
|
184
|
+
const code = err?.output?.statusCode ?? err?.data?.attrs?.code;
|
|
185
|
+
if ((code === 515 || code === "515") && !opened && retries < maxRetries) {
|
|
186
|
+
retries += 1;
|
|
187
|
+
setTimeout(connectSocket, 1500);
|
|
188
|
+
}
|
|
189
|
+
else if (!opened) {
|
|
190
|
+
rejectOpen(err);
|
|
191
|
+
}
|
|
192
|
+
});
|
|
193
|
+
this.#sock.ev.on("connection.update", (update) => {
|
|
194
|
+
if (update.qr) {
|
|
195
|
+
void import("qrcode-terminal")
|
|
196
|
+
.then((qrt) => (qrt.default ?? qrt).generate(update.qr, { small: true }))
|
|
197
|
+
.catch(() => {
|
|
198
|
+
console.log("Scan this QR code in WhatsApp > Linked Devices:");
|
|
199
|
+
console.log(update.qr);
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
if (update.connection === "open") {
|
|
203
|
+
opened = true;
|
|
204
|
+
process.removeAllListeners("uncaughtException");
|
|
205
|
+
resolveOpen();
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
if (update.connection === "close" && !opened) {
|
|
209
|
+
const statusCode = update.lastDisconnect?.error?.output?.statusCode;
|
|
210
|
+
const shouldReconnect = statusCode === 515 || statusCode === DisconnectReason?.restartRequired;
|
|
211
|
+
if (shouldReconnect && retries < maxRetries) {
|
|
212
|
+
retries += 1;
|
|
213
|
+
setTimeout(connectSocket, 1000);
|
|
214
|
+
}
|
|
215
|
+
else {
|
|
216
|
+
rejectOpen(update.lastDisconnect?.error ?? new Error("socket closed before open"));
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
});
|
|
220
|
+
};
|
|
221
|
+
connectSocket();
|
|
222
|
+
});
|
|
223
|
+
this.#signaling = new SignalingBridge({ sock: this.#sock });
|
|
224
|
+
await this.#signaling.init();
|
|
225
|
+
this.#relay = new RelayRtcTransport({
|
|
226
|
+
onTransportMessage: (data, ip, port) => this.#engine?.handleOnTransportMessage(data, ip, port),
|
|
227
|
+
onIceRtt: (rttMs, ip, port) => this.#engine?.updateIceRtt(rttMs, ip, port),
|
|
228
|
+
});
|
|
229
|
+
this.#engine = new WasmEngine({
|
|
230
|
+
callbacks: {
|
|
231
|
+
onSignalingXmpp: (peerJid, callId, xmlPayload) => this.#signaling.sendSignaling(peerJid, callId, xmlPayload),
|
|
232
|
+
onCallEvent: (eventType, eventData) => this.#handleCallEvent(eventType, eventData),
|
|
233
|
+
sendDataToRelay: (data, ip, port) => this.#relay.send(data, ip, port),
|
|
234
|
+
onAudioCaptureInit: (config) => this.#handleAudioCaptureInit(config),
|
|
235
|
+
onAudioCaptureStart: () => this.#handleAudioCaptureStart(),
|
|
236
|
+
onAudioCaptureStop: () => this.#handleAudioCaptureStop(),
|
|
237
|
+
onAudioPlaybackData: (audioData) => this.#activeCall?._emitAudio(audioData),
|
|
238
|
+
cryptoHkdf: computeHkdf,
|
|
239
|
+
hmacSha256: computeHmacSha256,
|
|
240
|
+
},
|
|
241
|
+
});
|
|
242
|
+
await this.#engine.initialize();
|
|
243
|
+
this.#signaling.attachEngine(this.#engine);
|
|
244
|
+
const selfPnJid = this.#sock.authState.creds.me?.id;
|
|
245
|
+
const selfLidJid = this.#sock.authState.creds.me?.lid;
|
|
246
|
+
this.#engine.initVoipStack(selfPnJid, toBareJid(selfPnJid), selfLidJid);
|
|
247
|
+
await this.#engine.waitForVoipStackReady();
|
|
248
|
+
try {
|
|
249
|
+
this.#engine.updateNetworkMedium(2, 0);
|
|
250
|
+
}
|
|
251
|
+
catch { }
|
|
252
|
+
this.#sock.ws.on("CB:call", (node) => {
|
|
253
|
+
this.#signaling.processIncomingCall(node, this.#engine, this.#activeCall?.callId ?? "");
|
|
254
|
+
});
|
|
255
|
+
this.#sock.ws.on("CB:receipt", (node) => {
|
|
256
|
+
if (!isCallReceiptNode(node))
|
|
257
|
+
return;
|
|
258
|
+
this.#signaling.processIncomingReceipt(node, this.#engine, this.#activeCall?.callId ?? "");
|
|
259
|
+
});
|
|
260
|
+
};
|
|
261
|
+
/** Place an outbound voice call. */
|
|
262
|
+
call = async (phoneNumber, opts = {}) => {
|
|
263
|
+
if (!this.#engine || !this.#signaling)
|
|
264
|
+
throw new Error("Not connected. Call connect() first.");
|
|
265
|
+
if (this.#activeCall)
|
|
266
|
+
throw new Error("A call is already active.");
|
|
267
|
+
const targetNumber = phoneNumber.replace(/\D/g, "");
|
|
268
|
+
const targetPnJid = `${targetNumber}@s.whatsapp.net`;
|
|
269
|
+
const durationMs = opts.durationMs ?? 120_000;
|
|
270
|
+
const audioSource = opts.audioSource ?? "silence";
|
|
271
|
+
const peerLid = await this.#signaling.resolveLid(targetPnJid);
|
|
272
|
+
const useLid = !!peerLid;
|
|
273
|
+
const peerJid = useLid ? peerLid : targetPnJid;
|
|
274
|
+
for (const jid of [targetPnJid, peerJid]) {
|
|
275
|
+
try {
|
|
276
|
+
await this.#sock.presenceSubscribe(jid);
|
|
277
|
+
}
|
|
278
|
+
catch { }
|
|
279
|
+
}
|
|
280
|
+
await new Promise((r) => setTimeout(r, 750));
|
|
281
|
+
let deviceList = [toBareJid(peerJid)];
|
|
282
|
+
if (useLid) {
|
|
283
|
+
const peerDeviceJids = await this.#signaling.discoverPeerDevices(peerLid);
|
|
284
|
+
deviceList = peerDeviceJids.length ? peerDeviceJids : deviceList;
|
|
285
|
+
}
|
|
286
|
+
await this.#signaling.ensureSessionsForPeers(deviceList);
|
|
287
|
+
await new Promise((r) => setTimeout(r, 500));
|
|
288
|
+
if (useLid) {
|
|
289
|
+
await this.#signaling.issueTcToken(peerLid);
|
|
290
|
+
}
|
|
291
|
+
const tcToken = useLid ? await this.#signaling.ensureTcToken(peerLid, targetPnJid) : "";
|
|
292
|
+
const callId = ("00" + randomBytes(16).toString("hex").slice(2)).toUpperCase();
|
|
293
|
+
const call = new ActiveCall(callId, this.#engine, durationMs);
|
|
294
|
+
call._audioSource = audioSource;
|
|
295
|
+
this.#activeCall = call;
|
|
296
|
+
this.#engine.startCall({
|
|
297
|
+
peerJid,
|
|
298
|
+
peerPn: targetPnJid,
|
|
299
|
+
peerList: deviceList,
|
|
300
|
+
callId,
|
|
301
|
+
isVideo: false,
|
|
302
|
+
isLidCall: useLid,
|
|
303
|
+
isFromDialer: false,
|
|
304
|
+
extraData: tcToken,
|
|
305
|
+
});
|
|
306
|
+
return call;
|
|
307
|
+
};
|
|
308
|
+
/** Tear down the WhatsApp socket and release resources. */
|
|
309
|
+
disconnect = () => {
|
|
310
|
+
this.#activeCall?._forceEnd("disconnect");
|
|
311
|
+
this.#activeCall = null;
|
|
312
|
+
this.#relay?.closeAll();
|
|
313
|
+
this.#engine?.destroy();
|
|
314
|
+
this.#sock?.end?.();
|
|
315
|
+
this.#engine = null;
|
|
316
|
+
this.#relay = null;
|
|
317
|
+
this.#signaling = null;
|
|
318
|
+
this.#sock = null;
|
|
319
|
+
};
|
|
320
|
+
// ─── private ──────────────────────────────────────────────────────────────
|
|
321
|
+
#handleCallEvent = (eventType, eventData) => {
|
|
322
|
+
if (eventType === 16 && eventData) {
|
|
323
|
+
try {
|
|
324
|
+
const parsed = JSON.parse(eventData);
|
|
325
|
+
const info = parsed.call_info ?? parsed.callInfo ?? {};
|
|
326
|
+
const callState = Number(info.call_state ?? info.callState ?? 0);
|
|
327
|
+
this.#activeCall?._updateState(callState);
|
|
328
|
+
}
|
|
329
|
+
catch { }
|
|
330
|
+
}
|
|
331
|
+
else if (eventType === 156 && eventData) {
|
|
332
|
+
try {
|
|
333
|
+
const update = JSON.parse(eventData);
|
|
334
|
+
this.#relay?.updateRelayList(update);
|
|
335
|
+
}
|
|
336
|
+
catch { }
|
|
337
|
+
}
|
|
338
|
+
else if (eventType === 2) {
|
|
339
|
+
this.#activeCall?._forceEnd("remote_end");
|
|
340
|
+
}
|
|
341
|
+
};
|
|
342
|
+
#handleAudioCaptureInit = (config) => {
|
|
343
|
+
if (!this.#engine)
|
|
344
|
+
return;
|
|
345
|
+
this.#captureSampleRate = config.sampleRate || 16000;
|
|
346
|
+
this.#captureChannels = config.channels || 1;
|
|
347
|
+
this.#captureFramesPerChunk = config.framesPerChunk || 320;
|
|
348
|
+
const chunkSamples = this.#captureFramesPerChunk * this.#captureChannels;
|
|
349
|
+
this.#captureChunkBytes = chunkSamples * Float32Array.BYTES_PER_ELEMENT;
|
|
350
|
+
this.#capturePtr = this.#engine.malloc(this.#captureChunkBytes);
|
|
351
|
+
};
|
|
352
|
+
#handleAudioCaptureStart = () => {
|
|
353
|
+
if (!this.#engine || !this.#capturePtr)
|
|
354
|
+
return;
|
|
355
|
+
const audioSource = this.#activeCall?._audioSource ?? "silence";
|
|
356
|
+
this.#feeder = new AudioFeeder(this.#captureSampleRate, this.#captureChannels, this.#captureFramesPerChunk, (chunk) => {
|
|
357
|
+
if (this.#engine && this.#capturePtr)
|
|
358
|
+
this.#engine.sendAudioData(chunk, this.#capturePtr);
|
|
359
|
+
}, audioSource);
|
|
360
|
+
this.#feeder.start();
|
|
361
|
+
};
|
|
362
|
+
#handleAudioCaptureStop = () => {
|
|
363
|
+
this.#feeder?.stop();
|
|
364
|
+
this.#feeder = null;
|
|
365
|
+
if (this.#engine && this.#capturePtr) {
|
|
366
|
+
try {
|
|
367
|
+
this.#engine.free(this.#capturePtr);
|
|
368
|
+
}
|
|
369
|
+
catch { }
|
|
370
|
+
this.#capturePtr = 0;
|
|
371
|
+
}
|
|
372
|
+
};
|
|
373
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
type RelayAddress = {
|
|
2
|
+
protocol: number;
|
|
3
|
+
ipv4?: string;
|
|
4
|
+
ipv6?: string;
|
|
5
|
+
port?: number;
|
|
6
|
+
port_v6?: number;
|
|
7
|
+
};
|
|
8
|
+
type RelayDescriptor = {
|
|
9
|
+
relay_id: number;
|
|
10
|
+
relay_name: string;
|
|
11
|
+
token_id: number;
|
|
12
|
+
auth_token_id?: number;
|
|
13
|
+
addresses: RelayAddress[];
|
|
14
|
+
};
|
|
15
|
+
export type RelayListUpdatePayload = {
|
|
16
|
+
relay_key: string;
|
|
17
|
+
relay_tokens: string[];
|
|
18
|
+
auth_tokens?: string[];
|
|
19
|
+
enable_edgeray_dtls_active_mode?: boolean;
|
|
20
|
+
relays: RelayDescriptor[];
|
|
21
|
+
};
|
|
22
|
+
export type RelayTransportStats = {
|
|
23
|
+
sentPackets: number;
|
|
24
|
+
receivedPackets: number;
|
|
25
|
+
sentBytes: number;
|
|
26
|
+
receivedBytes: number;
|
|
27
|
+
droppedPackets: number;
|
|
28
|
+
openConnections: number;
|
|
29
|
+
};
|
|
30
|
+
export type RelayTransportConfig = {
|
|
31
|
+
onTransportMessage: (data: Uint8Array, ip: string, port: number) => void;
|
|
32
|
+
onIceRtt?: (rttMs: number, ip: string, port: number) => void;
|
|
33
|
+
};
|
|
34
|
+
export declare class RelayRtcTransport {
|
|
35
|
+
#private;
|
|
36
|
+
private readonly config;
|
|
37
|
+
constructor(config: RelayTransportConfig);
|
|
38
|
+
updateRelayList: (update: RelayListUpdatePayload) => void;
|
|
39
|
+
send: (packet: Uint8Array | Buffer, ip: string, port: number) => number;
|
|
40
|
+
getStats: () => RelayTransportStats;
|
|
41
|
+
closeAll: () => Promise<void>;
|
|
42
|
+
}
|
|
43
|
+
export {};
|