@oxidezap/baileyrs 0.3.7 → 0.3.9
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/README.md +56 -8
- package/lib/Bridge/history-sync-wire.d.ts +2 -2
- package/lib/Bridge/history-sync-wire.js +4 -4
- package/lib/Bridge/schema.js +7 -1
- package/lib/Bridge/types.d.ts +7 -1
- package/lib/Compatibility/auth-state.d.ts +30 -0
- package/lib/Compatibility/auth-state.js +96 -0
- package/lib/Compatibility/encode-proto-core.d.ts +31 -0
- package/lib/Compatibility/encode-proto-core.js +51 -0
- package/lib/Compatibility/encode-proto.d.ts +0 -29
- package/lib/Compatibility/encode-proto.js +3 -50
- package/lib/Compatibility/host-auth-state.d.ts +6 -0
- package/lib/Compatibility/host-auth-state.js +162 -0
- package/lib/Compatibility/internal/auth-state.d.ts +3 -7
- package/lib/Compatibility/internal/auth-state.js +34 -1
- package/lib/Compatibility/internal/host-auth-state.d.ts +4 -0
- package/lib/Compatibility/internal/host-auth-state.js +14 -0
- package/lib/Compatibility/legacy-store/device.js +5 -5
- package/lib/Compatibility/message-ids.d.ts +17 -0
- package/lib/Compatibility/message-ids.js +47 -0
- package/lib/Compatibility/message-relay.d.ts +2 -2
- package/lib/Compatibility/message-relay.js +4 -4
- package/lib/Compatibility/proto-runtime.js +33 -11
- package/lib/Compatibility/socket-results.d.ts +1 -1
- package/lib/Compatibility/tagged-message-waiter.d.ts +5 -2
- package/lib/Compatibility/tagged-message-waiter.js +5 -5
- package/lib/Compatibility/usync/adapter.d.ts +1 -1
- package/lib/Compatibility/websocket-client.d.ts +11 -3
- package/lib/Compatibility/websocket-client.js +84 -11
- package/lib/Defaults/index.d.ts +8 -8
- package/lib/Defaults/index.js +8 -8
- package/lib/Media/content.d.ts +28 -0
- package/lib/Media/content.js +129 -0
- package/lib/Media/core.d.ts +34 -0
- package/lib/Media/core.js +120 -0
- package/lib/Media/mutations.d.ts +24 -0
- package/lib/Media/mutations.js +38 -0
- package/lib/Runtime/aes-gcm.d.ts +4 -0
- package/lib/Runtime/aes-gcm.js +11 -0
- package/lib/Runtime/bridge.d.ts +44 -0
- package/lib/Runtime/bridge.js +76 -0
- package/lib/Runtime/buffer.d.ts +9 -0
- package/lib/Runtime/buffer.js +22 -0
- package/lib/Runtime/bytes.d.ts +61 -0
- package/lib/Runtime/bytes.js +270 -0
- package/lib/Runtime/host.d.ts +22 -0
- package/lib/Runtime/host.js +43 -0
- package/lib/Runtime/long.d.ts +33 -0
- package/lib/Runtime/long.js +64 -0
- package/lib/Runtime/node-media-processors.d.ts +4 -0
- package/lib/Runtime/node-media-processors.js +29 -0
- package/lib/Runtime/node-media.d.ts +28 -0
- package/lib/Runtime/node-media.js +115 -0
- package/lib/Runtime/node.d.ts +14 -0
- package/lib/Runtime/node.js +81 -0
- package/lib/Runtime/paths.d.ts +4 -0
- package/lib/Runtime/paths.js +7 -0
- package/lib/Runtime/stream.d.ts +11 -0
- package/lib/Runtime/stream.js +25 -0
- package/lib/Runtime/types.d.ts +98 -0
- package/lib/Runtime/types.js +13 -0
- package/lib/Socket/core.d.ts +312 -0
- package/lib/Socket/core.js +1134 -0
- package/lib/Socket/events-core.d.ts +75 -0
- package/lib/Socket/events-core.js +1058 -0
- package/lib/Socket/events.d.ts +1 -63
- package/lib/Socket/events.js +4 -1047
- package/lib/Socket/groups.js +4 -3
- package/lib/Socket/index.d.ts +521 -103
- package/lib/Socket/index.js +10 -1007
- package/lib/Socket/messages-core.d.ts +41 -0
- package/lib/Socket/messages-core.js +270 -0
- package/lib/Socket/messages.d.ts +9 -36
- package/lib/Socket/messages.js +3 -260
- package/lib/Socket/newsletter.js +3 -3
- package/lib/Socket/profile.js +1 -1
- package/lib/Socket/terminal-close-reporter.d.ts +2 -0
- package/lib/Socket/terminal-close-reporter.js +3 -3
- package/lib/Socket/transport.d.ts +2 -0
- package/lib/Socket/transport.js +16 -1
- package/lib/Socket/types.d.ts +2 -0
- package/lib/Types/Auth.d.ts +11 -0
- package/lib/Types/Message.d.ts +1 -1
- package/lib/Types/Socket.d.ts +2 -2
- package/lib/Types/index.d.ts +6 -1
- package/lib/Utils/browser-utils.d.ts +4 -0
- package/lib/Utils/browser-utils.js +53 -2
- package/lib/Utils/crypto.d.ts +1 -0
- package/lib/Utils/crypto.js +1 -0
- package/lib/Utils/event-buffer.d.ts +6 -1
- package/lib/Utils/event-buffer.js +28 -27
- package/lib/Utils/link-preview.d.ts +4 -3
- package/lib/Utils/logger.d.ts +3 -0
- package/lib/Utils/logger.js +35 -6
- package/lib/Utils/messages-core.d.ts +174 -0
- package/lib/Utils/messages-core.js +1042 -0
- package/lib/Utils/messages-media-core.d.ts +73 -0
- package/lib/Utils/messages-media-core.js +319 -0
- package/lib/Utils/messages-media.d.ts +1 -72
- package/lib/Utils/messages-media.js +9 -358
- package/lib/Utils/messages.d.ts +1 -166
- package/lib/Utils/messages.js +7 -1040
- package/lib/Utils/optional-peer.js +14 -5
- package/lib/Utils/process-history-message-core.d.ts +36 -0
- package/lib/Utils/process-history-message-core.js +187 -0
- package/lib/Utils/process-history-message.d.ts +5 -43
- package/lib/Utils/process-history-message.js +11 -197
- package/lib/Utils/process-message-core.d.ts +29 -0
- package/lib/Utils/process-message-core.js +112 -0
- package/lib/Utils/process-message.d.ts +4 -24
- package/lib/Utils/process-message.js +6 -111
- package/lib/WABinary/generic-utils.js +7 -5
- package/lib/host-shared.d.ts +74 -0
- package/lib/host-shared.js +15 -0
- package/lib/host-socket-operations.d.ts +3 -0
- package/lib/host-socket-operations.js +2 -0
- package/lib/host-surface.d.ts +21 -0
- package/lib/host-surface.js +35 -0
- package/lib/host-types.d.ts +356 -0
- package/lib/host-types.js +2 -0
- package/lib/host.d.ts +33 -0
- package/lib/host.js +31 -0
- package/lib/node-surface.d.ts +9 -0
- package/lib/node-surface.js +15 -0
- package/lib/surface.d.ts +5 -0
- package/lib/surface.js +6 -0
- package/lib/wasm.d.ts +27 -0
- package/lib/wasm.js +27 -0
- package/package.json +18 -6
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/** Host-only auth bootstrap. It deliberately does not import legacy-store codecs. */
|
|
2
|
+
import { calculateSignature, generateKeyPair } from '@oxidezap/whatsapp-rust-bridge/host';
|
|
3
|
+
import { proto } from '@oxidezap/whatsapp-rust-bridge/proto-types';
|
|
4
|
+
import { base64Encode, concatBytes, randomBytes, readU16BE, utf8Decode } from '../Runtime/bytes.js';
|
|
5
|
+
import { jidEncode } from '../WABinary/jid-utils.js';
|
|
6
|
+
const pair = () => {
|
|
7
|
+
const value = generateKeyPair();
|
|
8
|
+
return { private: new Uint8Array(value.privKey), public: new Uint8Array(value.pubKey.subarray(1)) };
|
|
9
|
+
};
|
|
10
|
+
const signed = (identity) => {
|
|
11
|
+
const keyPair = pair();
|
|
12
|
+
const publicKey = keyPair.public.length === 33 ? keyPair.public : concatBytes([new Uint8Array([5]), keyPair.public]);
|
|
13
|
+
return { keyPair, keyId: 1, signature: new Uint8Array(calculateSignature(identity.private, publicKey)) };
|
|
14
|
+
};
|
|
15
|
+
export const initHostAuthCreds = () => {
|
|
16
|
+
const identity = pair();
|
|
17
|
+
return {
|
|
18
|
+
noiseKey: pair(),
|
|
19
|
+
pairingEphemeralKeyPair: pair(),
|
|
20
|
+
signedIdentityKey: identity,
|
|
21
|
+
signedPreKey: signed(identity),
|
|
22
|
+
registrationId: readU16BE(randomBytes(2)) & 0x3fff,
|
|
23
|
+
advSecretKey: base64Encode(randomBytes(32)),
|
|
24
|
+
processedHistoryMessages: [],
|
|
25
|
+
nextPreKeyId: 1,
|
|
26
|
+
firstUnuploadedPreKeyId: 1,
|
|
27
|
+
accountSyncCounter: 0,
|
|
28
|
+
accountSettings: { unarchiveChats: false },
|
|
29
|
+
registered: false,
|
|
30
|
+
pairingCode: undefined,
|
|
31
|
+
lastPropHash: undefined,
|
|
32
|
+
routingInfo: undefined,
|
|
33
|
+
additionalData: undefined
|
|
34
|
+
};
|
|
35
|
+
};
|
|
36
|
+
const PERSISTED_JID_DOMAINS = {
|
|
37
|
+
pn: new Set(['c.us', 's.whatsapp.net', 'hosted']),
|
|
38
|
+
lid: new Set(['lid', 'hosted.lid'])
|
|
39
|
+
};
|
|
40
|
+
const parsePersistedJid = (record, field) => {
|
|
41
|
+
const value = record[field];
|
|
42
|
+
if (value == null)
|
|
43
|
+
return undefined;
|
|
44
|
+
if (typeof value !== 'object')
|
|
45
|
+
throw new Error(`persisted auth record contains an invalid ${field} JID`);
|
|
46
|
+
const candidate = value;
|
|
47
|
+
if (typeof candidate.user !== 'string' ||
|
|
48
|
+
candidate.user.length === 0 ||
|
|
49
|
+
typeof candidate.server !== 'string' ||
|
|
50
|
+
!PERSISTED_JID_DOMAINS[field].has(candidate.server) ||
|
|
51
|
+
(candidate.device !== undefined &&
|
|
52
|
+
(typeof candidate.device !== 'number' || !Number.isSafeInteger(candidate.device) || candidate.device < 0))) {
|
|
53
|
+
throw new Error(`persisted auth record contains an invalid ${field} JID`);
|
|
54
|
+
}
|
|
55
|
+
return {
|
|
56
|
+
user: candidate.user,
|
|
57
|
+
server: candidate.server,
|
|
58
|
+
...(candidate.device === undefined ? {} : { device: candidate.device })
|
|
59
|
+
};
|
|
60
|
+
};
|
|
61
|
+
export const hydrateHostAuthCreds = async (store, creds) => {
|
|
62
|
+
const [payload, accountPayload] = await Promise.all([store.get('device', 'device'), store.get('device', 'account')]);
|
|
63
|
+
if (!payload) {
|
|
64
|
+
if (accountPayload)
|
|
65
|
+
creds.account = proto.ADVSignedDeviceIdentity.decode(accountPayload);
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
let record;
|
|
69
|
+
try {
|
|
70
|
+
record = JSON.parse(utf8Decode(payload));
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
throw new Error("failed to hydrate persisted auth record 'device'", { cause: error });
|
|
74
|
+
}
|
|
75
|
+
// Validate both identities before mutating the caller's credential mirror.
|
|
76
|
+
const pn = parsePersistedJid(record, 'pn');
|
|
77
|
+
const lid = parsePersistedJid(record, 'lid');
|
|
78
|
+
const mutable = creds;
|
|
79
|
+
const asBytes = (value) => Array.isArray(value) && value.every(byte => Number.isInteger(byte) && byte >= 0 && byte <= 255)
|
|
80
|
+
? new Uint8Array(value)
|
|
81
|
+
: undefined;
|
|
82
|
+
const keyPair = (value) => {
|
|
83
|
+
const bytes = asBytes(value);
|
|
84
|
+
if (!bytes || bytes.length !== 64 || bytes.every(byte => byte === 0))
|
|
85
|
+
return undefined;
|
|
86
|
+
return { private: bytes.slice(0, 32), public: bytes.slice(32, 64) };
|
|
87
|
+
};
|
|
88
|
+
const safeUnsigned = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
|
|
89
|
+
const registration = record.registration_id;
|
|
90
|
+
// Fresh Baileys mirrors use 14 bits; persisted devices come from Rust's 1..=2^31-1 generator.
|
|
91
|
+
if ('registration_id' in record && (!safeUnsigned(registration) || registration > 2147483647)) {
|
|
92
|
+
throw new Error('invalid persisted registration id');
|
|
93
|
+
}
|
|
94
|
+
if (safeUnsigned(registration))
|
|
95
|
+
mutable.registrationId = registration;
|
|
96
|
+
const noiseKey = keyPair(record.noise_key);
|
|
97
|
+
if ('noise_key' in record && !noiseKey) {
|
|
98
|
+
throw new Error('persisted auth record contains an invalid noise key');
|
|
99
|
+
}
|
|
100
|
+
const identityKey = keyPair(record.identity_key);
|
|
101
|
+
const signedPreKey = keyPair(record.signed_pre_key);
|
|
102
|
+
const hasSigningRecord = ['identity_key', 'signed_pre_key', 'signed_pre_key_id', 'signed_pre_key_signature'].some(field => field in record);
|
|
103
|
+
const signature = asBytes(record.signed_pre_key_signature);
|
|
104
|
+
const keyId = record.signed_pre_key_id;
|
|
105
|
+
if (hasSigningRecord &&
|
|
106
|
+
(!identityKey || !signedPreKey || !signature || signature.length !== 64 || !safeUnsigned(keyId))) {
|
|
107
|
+
throw new Error('persisted auth record contains an incomplete signing bundle');
|
|
108
|
+
}
|
|
109
|
+
if (noiseKey)
|
|
110
|
+
mutable.noiseKey = noiseKey;
|
|
111
|
+
if (hasSigningRecord) {
|
|
112
|
+
mutable.signedIdentityKey = identityKey;
|
|
113
|
+
mutable.signedPreKey = { keyPair: signedPreKey, keyId: keyId, signature: signature };
|
|
114
|
+
}
|
|
115
|
+
const advSecret = asBytes(record.adv_secret_key);
|
|
116
|
+
if ('adv_secret_key' in record && (!advSecret || advSecret.length !== 32)) {
|
|
117
|
+
throw new Error('persisted auth record contains an invalid adv secret');
|
|
118
|
+
}
|
|
119
|
+
if (advSecret)
|
|
120
|
+
mutable.advSecretKey = base64Encode(advSecret);
|
|
121
|
+
if ('next_pre_key_id' in record && !safeUnsigned(record.next_pre_key_id))
|
|
122
|
+
throw new Error('invalid persisted pre-key counter');
|
|
123
|
+
if (safeUnsigned(record.next_pre_key_id)) {
|
|
124
|
+
mutable.nextPreKeyId = record.next_pre_key_id;
|
|
125
|
+
mutable.firstUnuploadedPreKeyId = record.next_pre_key_id;
|
|
126
|
+
}
|
|
127
|
+
if (typeof record.props_hash === 'string')
|
|
128
|
+
mutable.lastPropHash = record.props_hash;
|
|
129
|
+
if (pn) {
|
|
130
|
+
const id = jidEncode(pn.user, pn.server, pn.device);
|
|
131
|
+
mutable.me = {
|
|
132
|
+
id,
|
|
133
|
+
name: typeof record.push_name === 'string' ? record.push_name : undefined,
|
|
134
|
+
...(lid ? { lid: jidEncode(lid.user, lid.server, lid.device) } : {})
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
else if (typeof record.push_name === 'string') {
|
|
138
|
+
mutable.me = { id: '', name: record.push_name };
|
|
139
|
+
}
|
|
140
|
+
if (mutable.me?.id)
|
|
141
|
+
mutable.registered = true;
|
|
142
|
+
if (typeof record.platform === 'string')
|
|
143
|
+
mutable.platform = record.platform;
|
|
144
|
+
const routingInfo = record.edge_routing_info;
|
|
145
|
+
const routingBytes = asBytes(routingInfo);
|
|
146
|
+
if ('edge_routing_info' in record && routingInfo !== null && !routingBytes) {
|
|
147
|
+
throw new Error('persisted auth record contains invalid routing info');
|
|
148
|
+
}
|
|
149
|
+
if (routingInfo === null)
|
|
150
|
+
mutable.routingInfo = undefined;
|
|
151
|
+
else if (routingBytes)
|
|
152
|
+
mutable.routingInfo = routingBytes;
|
|
153
|
+
if (accountPayload)
|
|
154
|
+
creds.account = proto.ADVSignedDeviceIdentity.decode(accountPayload);
|
|
155
|
+
};
|
|
156
|
+
/** Build host auth from the caller-owned native byte store. Rust remains the Signal authority. */
|
|
157
|
+
export const createAuthenticationState = async (store) => {
|
|
158
|
+
const creds = initHostAuthCreds();
|
|
159
|
+
await hydrateHostAuthCreds(store, creds);
|
|
160
|
+
return { creds: creds, store };
|
|
161
|
+
};
|
|
162
|
+
//# sourceMappingURL=host-auth-state.js.map
|
|
@@ -1,9 +1,6 @@
|
|
|
1
|
-
import type { AuthenticationState } from '../../Types/index.js';
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
creds?: AuthenticationState['creds'];
|
|
5
|
-
keys?: AuthenticationState['keys'];
|
|
6
|
-
};
|
|
1
|
+
import type { AuthenticationState, NativeAuthenticationState } from '../../Types/index.js';
|
|
2
|
+
export declare const refreshSocketAuthenticationState: (state: AuthenticationState) => Promise<void>;
|
|
3
|
+
export declare const waitForSocketAuthenticationState: (state: AuthenticationState) => Promise<void>;
|
|
7
4
|
/**
|
|
8
5
|
* Complete the public authentication view used by the socket when callers use
|
|
9
6
|
* the native byte-store path. The byte store remains authoritative: the key
|
|
@@ -11,5 +8,4 @@ type NativeAuthenticationState = {
|
|
|
11
8
|
* public, in-process mirror updated by socket events.
|
|
12
9
|
*/
|
|
13
10
|
export declare const normalizeSocketAuthenticationState: (input: AuthenticationState | NativeAuthenticationState) => AuthenticationState;
|
|
14
|
-
export {};
|
|
15
11
|
//# sourceMappingURL=auth-state.d.ts.map
|
|
@@ -1,5 +1,29 @@
|
|
|
1
|
+
import { Buffer } from 'node:buffer';
|
|
1
2
|
import { initAuthCreds } from '../../Utils/generics.js';
|
|
3
|
+
import { hydrateHostAuthCreds } from '../host-auth-state.js';
|
|
2
4
|
import { projectNativeStore } from '../legacy-store/native-projection.js';
|
|
5
|
+
const hydrationByState = new WeakMap();
|
|
6
|
+
const preserveNodeCredentialBytes = (creds) => {
|
|
7
|
+
for (const pair of [
|
|
8
|
+
creds.noiseKey,
|
|
9
|
+
creds.pairingEphemeralKeyPair,
|
|
10
|
+
creds.signedIdentityKey,
|
|
11
|
+
creds.signedPreKey.keyPair
|
|
12
|
+
]) {
|
|
13
|
+
pair.private = Buffer.from(pair.private);
|
|
14
|
+
pair.public = Buffer.from(pair.public);
|
|
15
|
+
}
|
|
16
|
+
creds.signedPreKey.signature = Buffer.from(creds.signedPreKey.signature);
|
|
17
|
+
if (creds.routingInfo)
|
|
18
|
+
creds.routingInfo = Buffer.from(creds.routingInfo);
|
|
19
|
+
};
|
|
20
|
+
export const refreshSocketAuthenticationState = async (state) => {
|
|
21
|
+
if (!state.store)
|
|
22
|
+
return;
|
|
23
|
+
await hydrateHostAuthCreds(state.store, state.creds);
|
|
24
|
+
preserveNodeCredentialBytes(state.creds);
|
|
25
|
+
};
|
|
26
|
+
export const waitForSocketAuthenticationState = (state) => hydrationByState.get(state) ?? Promise.resolve();
|
|
3
27
|
/**
|
|
4
28
|
* Complete the public authentication view used by the socket when callers use
|
|
5
29
|
* the native byte-store path. The byte store remains authoritative: the key
|
|
@@ -16,6 +40,15 @@ export const normalizeSocketAuthenticationState = (input) => {
|
|
|
16
40
|
if (!creds || !keys) {
|
|
17
41
|
throw new TypeError('auth must provide both creds and keys when no native store is configured');
|
|
18
42
|
}
|
|
19
|
-
|
|
43
|
+
const state = { creds, keys, ...(store ? { store } : {}) };
|
|
44
|
+
if (store && !input.creds) {
|
|
45
|
+
const hydration = refreshSocketAuthenticationState(state);
|
|
46
|
+
// The socket initialization awaits the original promise. Attach a
|
|
47
|
+
// rejection observer immediately so a synchronously rejecting store does
|
|
48
|
+
// not become an unhandled rejection before init reaches its first await.
|
|
49
|
+
void hydration.catch(() => undefined);
|
|
50
|
+
hydrationByState.set(state, hydration);
|
|
51
|
+
}
|
|
52
|
+
return state;
|
|
20
53
|
};
|
|
21
54
|
//# sourceMappingURL=auth-state.js.map
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { AuthenticationState, NativeAuthenticationState } from '../../Types/index.js';
|
|
2
|
+
/** Host normalization: native stores remain Rust-owned and expose no legacy key facade. */
|
|
3
|
+
export declare const normalizeHostAuthenticationState: (input: AuthenticationState | NativeAuthenticationState) => AuthenticationState;
|
|
4
|
+
//# sourceMappingURL=host-auth-state.d.ts.map
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Host normalization: native stores remain Rust-owned and expose no legacy key facade. */
|
|
2
|
+
export const normalizeHostAuthenticationState = (input) => {
|
|
3
|
+
if (!input || typeof input !== 'object')
|
|
4
|
+
throw new TypeError('auth must provide either { creds, keys } or a native store');
|
|
5
|
+
if (input.creds && input.keys)
|
|
6
|
+
return input;
|
|
7
|
+
if (input.store && input.creds)
|
|
8
|
+
return input;
|
|
9
|
+
if (input.store) {
|
|
10
|
+
throw new TypeError('host auth with a native store must be created with await createAuthenticationState(store)');
|
|
11
|
+
}
|
|
12
|
+
throw new TypeError('auth must provide both creds and keys when no native store is configured');
|
|
13
|
+
};
|
|
14
|
+
//# sourceMappingURL=host-auth-state.js.map
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
// Device credential projection for legacy Baileys authentication states.
|
|
2
|
-
import { Buffer } from 'node:buffer';
|
|
3
2
|
import { proto } from '@oxidezap/whatsapp-rust-bridge/proto-types';
|
|
3
|
+
import { base64Decode, base64Encode, publicBytes } from '../../Runtime/bytes.js';
|
|
4
4
|
import { WA_DEFAULT_VERSION } from '../../Defaults/index.js';
|
|
5
5
|
import { jidDecode, jidEncode } from '../../WABinary/jid-utils.js';
|
|
6
|
-
import { DeviceRecordKey,
|
|
6
|
+
import { DeviceRecordKey, SignalDomain, SignalKeyLength, TimeValue } from './constants.js';
|
|
7
7
|
import { bytesToNumbers, fromJsonBytes, toJsonBytes } from './common.js';
|
|
8
8
|
import { isAllZero, requireByteArray, requireSafeUnsignedInteger } from './validation.js';
|
|
9
9
|
const signedDeviceIdentityCodec = proto.ADVSignedDeviceIdentity;
|
|
@@ -73,7 +73,7 @@ function deviceFromCreds(creds) {
|
|
|
73
73
|
? bytesToNumbers(creds.signedPreKey.signature)
|
|
74
74
|
: Array(SignalKeyLength.SIGNATURE).fill(0),
|
|
75
75
|
adv_secret_key: creds.advSecretKey
|
|
76
|
-
? bytesToNumbers(
|
|
76
|
+
? bytesToNumbers(base64Decode(creds.advSecretKey))
|
|
77
77
|
: Array(SignalKeyLength.ADV_SECRET).fill(0),
|
|
78
78
|
account: null,
|
|
79
79
|
push_name: creds.me.name ?? '',
|
|
@@ -159,12 +159,12 @@ function prepareNativeDevice(payload) {
|
|
|
159
159
|
};
|
|
160
160
|
}
|
|
161
161
|
if (advSecret?.some(byte => byte !== 0)) {
|
|
162
|
-
creds.advSecretKey =
|
|
162
|
+
creds.advSecretKey = base64Encode(new Uint8Array(advSecret));
|
|
163
163
|
}
|
|
164
164
|
if (routingInfo === null)
|
|
165
165
|
creds.routingInfo = undefined;
|
|
166
166
|
else if (routingInfo)
|
|
167
|
-
creds.routingInfo =
|
|
167
|
+
creds.routingInfo = publicBytes(new Uint8Array(routingInfo));
|
|
168
168
|
};
|
|
169
169
|
}
|
|
170
170
|
export function parseDeviceRecordKey(value) {
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Portable message-identity helpers for the runtime-neutral graph.
|
|
3
|
+
*
|
|
4
|
+
* `generateMessageIDV2` is the one place every send path resolves a stanza
|
|
5
|
+
* id through (`Compatibility/message-relay.ts:resolveMessageId`, group
|
|
6
|
+
* invite stubs). The bytes are identical to `Utils/generics.ts` — 8-byte
|
|
7
|
+
* big-endian unix seconds, user JID + `@c.us`, 16 random bytes, SHA-256 hex,
|
|
8
|
+
* `3EB0` prefix — but built on `Runtime/bytes.ts` (portable SHA-256,
|
|
9
|
+
* WebCrypto randomness) instead of `node:crypto` + `Buffer`, so hosts get
|
|
10
|
+
* the same ids without a Node import.
|
|
11
|
+
*/
|
|
12
|
+
export declare const generateMessageIDV2Portable: (userId?: string, randomSource?: (length: number) => Uint8Array) => string;
|
|
13
|
+
/** `3EB0` + 36 uppercase hex chars from 18 random bytes (matches `generateMessageID`). */
|
|
14
|
+
export declare const generateMessageIDPortable: (randomSource?: (length: number) => Uint8Array) => string;
|
|
15
|
+
/** Concatenate without Buffer (pad helper for the portable graph). */
|
|
16
|
+
export declare const concatMessageBytes: (parts: ReadonlyArray<Uint8Array>) => Uint8Array;
|
|
17
|
+
//# sourceMappingURL=message-ids.d.ts.map
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Portable message-identity helpers for the runtime-neutral graph.
|
|
3
|
+
*
|
|
4
|
+
* `generateMessageIDV2` is the one place every send path resolves a stanza
|
|
5
|
+
* id through (`Compatibility/message-relay.ts:resolveMessageId`, group
|
|
6
|
+
* invite stubs). The bytes are identical to `Utils/generics.ts` — 8-byte
|
|
7
|
+
* big-endian unix seconds, user JID + `@c.us`, 16 random bytes, SHA-256 hex,
|
|
8
|
+
* `3EB0` prefix — but built on `Runtime/bytes.ts` (portable SHA-256,
|
|
9
|
+
* WebCrypto randomness) instead of `node:crypto` + `Buffer`, so hosts get
|
|
10
|
+
* the same ids without a Node import.
|
|
11
|
+
*/
|
|
12
|
+
import { concatBytes, hexEncode, randomBytes, sha256Sync, utf8Encode, writeU64BE } from '../Runtime/bytes.js';
|
|
13
|
+
const MESSAGE_ID_PREFIX = '3EB0';
|
|
14
|
+
const MESSAGE_ID_BYTES = 44;
|
|
15
|
+
const RANDOM_OFFSET = 28;
|
|
16
|
+
const writeAsciiInto = (target, text, offset) => {
|
|
17
|
+
const bytes = utf8Encode(text);
|
|
18
|
+
const length = Math.min(bytes.length, target.length - offset);
|
|
19
|
+
for (let i = 0; i < length; i++)
|
|
20
|
+
target[offset + i] = bytes[i];
|
|
21
|
+
};
|
|
22
|
+
/** Extract the user part of a JID without importing the JID utils (cycle-safe). */
|
|
23
|
+
const jidUser = (jid) => {
|
|
24
|
+
const at = jid.indexOf('@');
|
|
25
|
+
const user = at < 0 ? jid : jid.slice(0, at);
|
|
26
|
+
// Baileys hashes the bare user, not the device/agent suffix of a
|
|
27
|
+
// multi-device JID (`user:device` or `user_agent`).
|
|
28
|
+
const bareUser = user.split('_', 1)[0].split(':', 1)[0];
|
|
29
|
+
return bareUser.length > 0 ? bareUser : undefined;
|
|
30
|
+
};
|
|
31
|
+
export const generateMessageIDV2Portable = (userId, randomSource = randomBytes) => {
|
|
32
|
+
const data = new Uint8Array(MESSAGE_ID_BYTES);
|
|
33
|
+
const seconds = Math.floor(Date.now() / 1000);
|
|
34
|
+
data.set(writeU64BE(0, seconds >>> 0), 0);
|
|
35
|
+
const user = userId ? jidUser(userId) : undefined;
|
|
36
|
+
if (user) {
|
|
37
|
+
writeAsciiInto(data, user, 8);
|
|
38
|
+
writeAsciiInto(data, '@c.us', 8 + utf8Encode(user).length);
|
|
39
|
+
}
|
|
40
|
+
data.set(randomSource(16), RANDOM_OFFSET);
|
|
41
|
+
return `${MESSAGE_ID_PREFIX}${hexEncode(sha256Sync(data)).toUpperCase().slice(0, 18)}`;
|
|
42
|
+
};
|
|
43
|
+
/** `3EB0` + 36 uppercase hex chars from 18 random bytes (matches `generateMessageID`). */
|
|
44
|
+
export const generateMessageIDPortable = (randomSource = randomBytes) => `3EB0${hexEncode(randomSource(18)).toUpperCase()}`;
|
|
45
|
+
/** Concatenate without Buffer (pad helper for the portable graph). */
|
|
46
|
+
export const concatMessageBytes = (parts) => concatBytes(parts);
|
|
47
|
+
//# sourceMappingURL=message-ids.js.map
|
|
@@ -10,7 +10,7 @@ export type OwnRelayIdentity = {
|
|
|
10
10
|
* Every send path resolves through here, so `messageId` means the same thing
|
|
11
11
|
* on `sendMessage` and on `relayMessage`.
|
|
12
12
|
*/
|
|
13
|
-
export declare const resolveMessageId: (own: OwnRelayIdentity, messageId?: string) => string;
|
|
13
|
+
export declare const resolveMessageId: (own: OwnRelayIdentity, messageId?: string, randomBytes?: (length: number) => Uint8Array) => string;
|
|
14
14
|
export type MessageRelayPlan = {
|
|
15
15
|
kind: 'message';
|
|
16
16
|
messageId: string;
|
|
@@ -28,5 +28,5 @@ export type MessageRelayPlan = {
|
|
|
28
28
|
messageId: string;
|
|
29
29
|
input: MessageRetransmissionInput;
|
|
30
30
|
};
|
|
31
|
-
export declare const planMessageRelay: (jid: string, options: MessageRelayOptions, own: OwnRelayIdentity) => MessageRelayPlan;
|
|
31
|
+
export declare const planMessageRelay: (jid: string, options: MessageRelayOptions, own: OwnRelayIdentity, randomBytes?: (length: number) => Uint8Array) => MessageRelayPlan;
|
|
32
32
|
//# sourceMappingURL=message-relay.d.ts.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Boom } from '../Utils/boom.js';
|
|
2
|
-
import { generateMessageIDV2 } from '
|
|
2
|
+
import { generateMessageIDV2Portable as generateMessageIDV2 } from './message-ids.js';
|
|
3
3
|
import { areJidsSameUser, isJidBroadcast, isJidGroup, isJidNewsletter } from '../WABinary/index.js';
|
|
4
4
|
export const EMPTY_RELAY_NODES = [];
|
|
5
5
|
/**
|
|
@@ -7,7 +7,7 @@ export const EMPTY_RELAY_NODES = [];
|
|
|
7
7
|
* Every send path resolves through here, so `messageId` means the same thing
|
|
8
8
|
* on `sendMessage` and on `relayMessage`.
|
|
9
9
|
*/
|
|
10
|
-
export const resolveMessageId = (own, messageId) => messageId || generateMessageIDV2(own?.id);
|
|
10
|
+
export const resolveMessageId = (own, messageId, randomBytes) => messageId || generateMessageIDV2(own?.id, randomBytes);
|
|
11
11
|
const assertSupportedAttributes = (attributes) => {
|
|
12
12
|
if (!attributes)
|
|
13
13
|
return;
|
|
@@ -21,7 +21,7 @@ const assertSupportedAttributes = (attributes) => {
|
|
|
21
21
|
};
|
|
22
22
|
const isDirectConversation = (jid) => !isJidGroup(jid) && !isJidBroadcast(jid) && !isJidNewsletter(jid);
|
|
23
23
|
const isOwnDevice = (jid, own) => (own?.id !== undefined && areJidsSameUser(jid, own.id)) || (own?.lid !== undefined && areJidsSameUser(jid, own.lid));
|
|
24
|
-
export const planMessageRelay = (jid, options, own) => {
|
|
24
|
+
export const planMessageRelay = (jid, options, own, randomBytes) => {
|
|
25
25
|
const { messageId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList } = options;
|
|
26
26
|
assertSupportedAttributes(additionalAttributes);
|
|
27
27
|
const nodes = additionalNodes ?? EMPTY_RELAY_NODES;
|
|
@@ -30,7 +30,7 @@ export const planMessageRelay = (jid, options, own) => {
|
|
|
30
30
|
statusCode: 400
|
|
31
31
|
});
|
|
32
32
|
}
|
|
33
|
-
const id = resolveMessageId(own, messageId);
|
|
33
|
+
const id = resolveMessageId(own, messageId, randomBytes);
|
|
34
34
|
const refreshGroupMetadata = useCachedGroupMetadata === false;
|
|
35
35
|
if (participant) {
|
|
36
36
|
const requesterIsOwnDevice = isDirectConversation(jid) && isOwnDevice(participant.jid, own);
|
|
@@ -1,16 +1,12 @@
|
|
|
1
|
-
import
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import LongRuntime from '../Runtime/long.js';
|
|
2
|
+
import { BinaryReader } from '@oxidezap/whatsapp-rust-bridge/host';
|
|
3
|
+
import { base64Decode, base64Encode, publicBytes } from '../Runtime/bytes.js';
|
|
4
4
|
import { PROTO_ENUM_SCHEMAS, PROTO_FIELD_FLAG, PROTO_FIELD_KIND, PROTO_MESSAGE_SCHEMAS } from '../WAProto/compatibility-schema.js';
|
|
5
5
|
const INSTANCE_SCHEMA = Symbol('proto compatibility schema');
|
|
6
6
|
const EMPTY_ARRAY = Object.freeze([]);
|
|
7
7
|
const EMPTY_OBJECT = Object.freeze({});
|
|
8
8
|
const JSON_OPTIONS = Object.freeze({ longs: String, enums: String, bytes: String, json: true });
|
|
9
9
|
const WORD_BASE = 1n << 32n;
|
|
10
|
-
// protobufjs resolves the CommonJS Long constructor internally. Loading that
|
|
11
|
-
// same export keeps `instanceof` and prototype identity aligned without
|
|
12
|
-
// loading protobufjs itself or adding a second wire runtime.
|
|
13
|
-
const LongRuntime = createRequire(import.meta.url)('long');
|
|
14
10
|
const hasOwn = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
|
|
15
11
|
const isObject = (value) => typeof value === 'object' && value !== null;
|
|
16
12
|
const isReaderLike = (value) => isObject(value) && value.buf instanceof Uint8Array && typeof value.pos === 'number' && typeof value.len === 'number';
|
|
@@ -205,19 +201,45 @@ const longToNumber = (value, unsigned) => {
|
|
|
205
201
|
};
|
|
206
202
|
const bytesToBase64 = (value) => {
|
|
207
203
|
if (value instanceof Uint8Array) {
|
|
208
|
-
return
|
|
204
|
+
return base64Encode(value);
|
|
209
205
|
}
|
|
210
|
-
return
|
|
206
|
+
return base64Encode(Uint8Array.from(value));
|
|
211
207
|
};
|
|
212
208
|
const bytesFromObject = (value) => {
|
|
213
209
|
if (typeof value === 'string')
|
|
214
|
-
return
|
|
210
|
+
return nodeBytesFromBase64(value);
|
|
215
211
|
if (isObject(value) && typeof value.length === 'number')
|
|
216
212
|
return value;
|
|
217
213
|
if (Array.isArray(value))
|
|
218
214
|
return value;
|
|
219
215
|
return undefined;
|
|
220
216
|
};
|
|
217
|
+
/**
|
|
218
|
+
* Upstream protobufjs materializes `bytes` fields as Node `Buffer` on Node
|
|
219
|
+
* (`protobuf.util.Buffer`), and the compatibility contract asserts
|
|
220
|
+
* `deepStrictEqual` against that — `Buffer` vs `Uint8Array` fails even with
|
|
221
|
+
* identical contents. The host-neutral graph cannot import `node:buffer`,
|
|
222
|
+
* so the base64 decode stays portable and only the wrapping is Node-only,
|
|
223
|
+
* resolved lazily through `process.getBuiltinModule('buffer')` (same
|
|
224
|
+
* lazy-builtin shape `Utils/browser-utils.ts` uses for `node:os`): no
|
|
225
|
+
* static `node:` import, `Buffer.from(u8)` on Node, the plain `Uint8Array`
|
|
226
|
+
* on hosts where there is no upstream-Buffer constraint to keep.
|
|
227
|
+
*/
|
|
228
|
+
const nodeBytesFromBase64 = (value) => {
|
|
229
|
+
try {
|
|
230
|
+
const proc = globalThis.process;
|
|
231
|
+
const bufferModule = proc?.getBuiltinModule?.('buffer');
|
|
232
|
+
// protobufjs delegates string coercion to Buffer.from(), including its
|
|
233
|
+
// permissive handling of excess padding and ignored non-alphabet bytes.
|
|
234
|
+
const nodeBytes = bufferModule?.Buffer?.from?.(value, 'base64');
|
|
235
|
+
if (nodeBytes !== undefined)
|
|
236
|
+
return nodeBytes;
|
|
237
|
+
}
|
|
238
|
+
catch {
|
|
239
|
+
/* host runtimes use the strict portable decoder below */
|
|
240
|
+
}
|
|
241
|
+
return base64Decode(value);
|
|
242
|
+
};
|
|
221
243
|
const oneofName = (field) => {
|
|
222
244
|
const flags = field[3];
|
|
223
245
|
if (flags & PROTO_FIELD_FLAG.proto3Optional)
|
|
@@ -871,7 +893,7 @@ class ProtoCompatibilityRuntime {
|
|
|
871
893
|
case PROTO_FIELD_KIND.bool:
|
|
872
894
|
return false;
|
|
873
895
|
case PROTO_FIELD_KIND.bytes:
|
|
874
|
-
return options.bytes === String ? '' : options.bytes === Array ? [] :
|
|
896
|
+
return options.bytes === String ? '' : options.bytes === Array ? [] : publicBytes(new Uint8Array(0));
|
|
875
897
|
case PROTO_FIELD_KIND.signed64:
|
|
876
898
|
case PROTO_FIELD_KIND.unsigned64:
|
|
877
899
|
return options.longs === String
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { BlocklistEntryResult, BusinessProfileResult, MembershipRequestResult, ParticipantChangeResult } from '@oxidezap/whatsapp-rust-bridge';
|
|
1
|
+
import type { BlocklistEntryResult, BusinessProfileResult, MembershipRequestResult, ParticipantChangeResult } from '@oxidezap/whatsapp-rust-bridge/host';
|
|
2
2
|
import type { BinaryNode, WABusinessProfile } from '../Types/index.js';
|
|
3
3
|
export type ParticipantUpdateResult = {
|
|
4
4
|
status: string;
|
|
@@ -1,5 +1,8 @@
|
|
|
1
|
-
import type { EventEmitter } from '
|
|
1
|
+
import type { EventEmitter } from 'events';
|
|
2
2
|
import type { ILogger } from '../Utils/logger.js';
|
|
3
3
|
/** Build the low-level tagged-response waiter with upstream timeout semantics. */
|
|
4
|
-
export declare const makeTaggedMessageWaiter: (ws: EventEmitter, logger: ILogger, defaultTimeoutMs
|
|
4
|
+
export declare const makeTaggedMessageWaiter: (ws: EventEmitter, logger: ILogger, defaultTimeoutMs: number | undefined, timers: {
|
|
5
|
+
setTimeout: (callback: () => void, ms: number) => unknown;
|
|
6
|
+
clearTimeout: (handle: unknown) => void;
|
|
7
|
+
}) => <T>(msgId: string, timeoutMs?: number | undefined) => Promise<T | undefined>;
|
|
5
8
|
//# sourceMappingURL=tagged-message-waiter.d.ts.map
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
import { unrefTimer } from '../Runtime/bytes.js';
|
|
1
2
|
import { DisconnectReason } from '../Types/index.js';
|
|
2
3
|
import { Boom } from '../Utils/boom.js';
|
|
3
4
|
/** Build the low-level tagged-response waiter with upstream timeout semantics. */
|
|
4
|
-
export const makeTaggedMessageWaiter = (ws, logger, defaultTimeoutMs) => async function waitForMessage(msgId, timeoutMs = defaultTimeoutMs) {
|
|
5
|
+
export const makeTaggedMessageWaiter = (ws, logger, defaultTimeoutMs, timers) => async function waitForMessage(msgId, timeoutMs = defaultTimeoutMs) {
|
|
5
6
|
const tag = `TAG:${msgId}`;
|
|
6
7
|
let timer;
|
|
7
8
|
let onRecv;
|
|
@@ -16,8 +17,7 @@ export const makeTaggedMessageWaiter = (ws, logger, defaultTimeoutMs) => async f
|
|
|
16
17
|
ws.on('close', onError);
|
|
17
18
|
ws.on('error', onError);
|
|
18
19
|
if (timeoutMs) {
|
|
19
|
-
timer = setTimeout(() => reject(new Boom('Timed out waiting for message', { statusCode: DisconnectReason.timedOut })), timeoutMs);
|
|
20
|
-
timer.unref();
|
|
20
|
+
timer = unrefTimer(timers.setTimeout(() => reject(new Boom('Timed out waiting for message', { statusCode: DisconnectReason.timedOut })), timeoutMs));
|
|
21
21
|
}
|
|
22
22
|
});
|
|
23
23
|
}
|
|
@@ -29,8 +29,8 @@ export const makeTaggedMessageWaiter = (ws, logger, defaultTimeoutMs) => async f
|
|
|
29
29
|
throw error;
|
|
30
30
|
}
|
|
31
31
|
finally {
|
|
32
|
-
if (timer)
|
|
33
|
-
clearTimeout(timer);
|
|
32
|
+
if (timer !== undefined)
|
|
33
|
+
timers.clearTimeout(timer);
|
|
34
34
|
if (onRecv)
|
|
35
35
|
ws.off(tag, onRecv);
|
|
36
36
|
if (onError) {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { UsyncQuery as NativeUsyncQuery, UsyncResponse as NativeUsyncResponse } from '@oxidezap/whatsapp-rust-bridge';
|
|
1
|
+
import type { UsyncQuery as NativeUsyncQuery, UsyncResponse as NativeUsyncResponse } from '@oxidezap/whatsapp-rust-bridge/host';
|
|
2
2
|
import type { BinaryNode } from '../../Types/index.js';
|
|
3
3
|
import { type USyncQuery, type USyncQueryResult } from '../../WAUSync/USyncQuery.js';
|
|
4
4
|
export type RawUSyncQuery = (node: BinaryNode, timeoutMs?: number) => Promise<BinaryNode>;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { EventEmitter } from '
|
|
2
|
-
import { URL } from 'node:url';
|
|
1
|
+
import { EventEmitter } from 'events';
|
|
3
2
|
import type { WasmWhatsAppClient } from '@oxidezap/whatsapp-rust-bridge';
|
|
4
3
|
import type { SocketConfig } from '../Types/index.js';
|
|
4
|
+
import type { RuntimeEventEmitter } from '../Runtime/types.js';
|
|
5
5
|
type ReadyState = 0 | 1 | 2 | 3;
|
|
6
6
|
type EventListener = Parameters<EventEmitter['on']>[1];
|
|
7
7
|
export declare const isRawNodeForwardingEnabled: (client: WebSocketClient) => boolean;
|
|
@@ -19,9 +19,10 @@ export declare class WebSocketClient extends EventEmitter {
|
|
|
19
19
|
* still running — which is how teardown reached `free()` on a busy client.
|
|
20
20
|
*/
|
|
21
21
|
private closeState;
|
|
22
|
+
private readonly emitter?;
|
|
22
23
|
private readonly getClient;
|
|
23
24
|
private listenerMutationDepth;
|
|
24
|
-
constructor(url: string | URL, config: SocketConfig, getClient: () => WasmWhatsAppClient | undefined);
|
|
25
|
+
constructor(url: string | URL, config: SocketConfig, getClient: () => WasmWhatsAppClient | undefined, emitter?: RuntimeEventEmitter);
|
|
25
26
|
get isOpen(): boolean;
|
|
26
27
|
get isClosed(): boolean;
|
|
27
28
|
get isClosing(): boolean;
|
|
@@ -36,6 +37,13 @@ export declare class WebSocketClient extends EventEmitter {
|
|
|
36
37
|
removeListener(eventName: string | symbol, listener: EventListener): this;
|
|
37
38
|
off(eventName: string | symbol, listener: EventListener): this;
|
|
38
39
|
removeAllListeners(eventName?: string | symbol): this;
|
|
40
|
+
emit(eventName: string | symbol, ...args: unknown[]): boolean;
|
|
41
|
+
eventNames(): (string | symbol)[];
|
|
42
|
+
rawListeners(eventName: string | symbol): EventListener[];
|
|
43
|
+
listeners(eventName: string | symbol): EventListener[];
|
|
44
|
+
listenerCount(eventName: string | symbol, listener?: EventListener): number;
|
|
45
|
+
setMaxListeners(count: number): this;
|
|
46
|
+
getMaxListeners(): number;
|
|
39
47
|
connect(): void;
|
|
40
48
|
/**
|
|
41
49
|
* Idempotent, and a second caller joins the first rather than returning
|