@ikyyjee/ikyysinggle 1.7.7
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/WAProto/GenerateStatics.sh +3 -0
- package/WAProto/WAProto.proto +8083 -0
- package/WAProto/fix-imports.js +85 -0
- package/WAProto/index.d.ts +29095 -0
- package/WAProto/index.js +172336 -0
- package/engine-requirements.js +10 -0
- package/lib/Defaults/index.js +194 -0
- package/lib/Signal/Group/ciphertext-message.js +12 -0
- package/lib/Signal/Group/group-session-builder.js +30 -0
- package/lib/Signal/Group/group_cipher.js +82 -0
- package/lib/Signal/Group/index.js +12 -0
- package/lib/Signal/Group/keyhelper.js +18 -0
- package/lib/Signal/Group/sender-chain-key.js +26 -0
- package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
- package/lib/Signal/Group/sender-key-message.js +66 -0
- package/lib/Signal/Group/sender-key-name.js +48 -0
- package/lib/Signal/Group/sender-key-record.js +41 -0
- package/lib/Signal/Group/sender-key-state.js +84 -0
- package/lib/Signal/Group/sender-message-key.js +26 -0
- package/lib/Signal/libsignal.js +431 -0
- package/lib/Signal/lid-mapping.js +277 -0
- package/lib/Socket/Client/index.js +3 -0
- package/lib/Socket/Client/types.js +11 -0
- package/lib/Socket/Client/websocket.js +102 -0
- package/lib/Socket/aigroups.js +221 -0
- package/lib/Socket/business.js +379 -0
- package/lib/Socket/chats.js +1193 -0
- package/lib/Socket/communities.js +431 -0
- package/lib/Socket/graphql.js +524 -0
- package/lib/Socket/groups.js +408 -0
- package/lib/Socket/index.js +49 -0
- package/lib/Socket/interop.js +341 -0
- package/lib/Socket/luxu.js +510 -0
- package/lib/Socket/managed-account.js +99 -0
- package/lib/Socket/messages-recv.js +2009 -0
- package/lib/Socket/messages-send.js +1608 -0
- package/lib/Socket/mex.js +41 -0
- package/lib/Socket/newsletter.js +399 -0
- package/lib/Socket/privacy.js +128 -0
- package/lib/Socket/registration.js +238 -0
- package/lib/Socket/socket.js +1000 -0
- package/lib/Socket/text-router.js +67 -0
- package/lib/Socket/username.js +234 -0
- package/lib/Store/index.js +10 -0
- package/lib/Store/keyed-db.js +108 -0
- package/lib/Store/make-cache-manager-store.js +85 -0
- package/lib/Store/make-in-memory-store.js +198 -0
- package/lib/Store/make-ordered-dictionary.js +75 -0
- package/lib/Store/object-repository.js +32 -0
- package/lib/Types/Auth.js +2 -0
- package/lib/Types/Bussines.js +2 -0
- package/lib/Types/Call.js +2 -0
- package/lib/Types/Chat.js +8 -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 +25 -0
- package/lib/Types/LabelAssociation.js +7 -0
- package/lib/Types/Message.js +11 -0
- package/lib/Types/Mex.js +114 -0
- package/lib/Types/Product.js +2 -0
- package/lib/Types/Signal.js +2 -0
- package/lib/Types/Socket.js +3 -0
- package/lib/Types/State.js +56 -0
- package/lib/Types/USync.js +2 -0
- package/lib/Types/index.js +26 -0
- package/lib/Utils/adaptive-healing.js +53 -0
- package/lib/Utils/auth-utils.js +302 -0
- package/lib/Utils/browser-utils.js +50 -0
- package/lib/Utils/business.js +231 -0
- package/lib/Utils/chat-utils.js +872 -0
- package/lib/Utils/command-loader.js +108 -0
- package/lib/Utils/companion-reg-client-utils.js +35 -0
- package/lib/Utils/consumer-application.js +106 -0
- package/lib/Utils/crypto.js +137 -0
- package/lib/Utils/curve25519-js.js +262 -0
- package/lib/Utils/decode-wa-message.js +498 -0
- package/lib/Utils/event-buffer.js +622 -0
- package/lib/Utils/generics.js +403 -0
- package/lib/Utils/group-history.js +47 -0
- package/lib/Utils/history.js +134 -0
- package/lib/Utils/identity-change-handler.js +50 -0
- package/lib/Utils/index.js +38 -0
- package/lib/Utils/jid-display-normalization.js +198 -0
- package/lib/Utils/link-preview.js +85 -0
- package/lib/Utils/logger.js +3 -0
- package/lib/Utils/lt-hash.js +8 -0
- package/lib/Utils/make-mutex.js +33 -0
- package/lib/Utils/message-composer.js +273 -0
- package/lib/Utils/message-retry-manager.js +267 -0
- package/lib/Utils/messages-media.js +791 -0
- package/lib/Utils/messages.js +1260 -0
- package/lib/Utils/meta-ai-msmsg.js +271 -0
- package/lib/Utils/native-bridge.js +77 -0
- package/lib/Utils/noise-handler.js +201 -0
- package/lib/Utils/offline-node-processor.js +40 -0
- package/lib/Utils/optimizer.js +90 -0
- package/lib/Utils/pre-key-manager.js +106 -0
- package/lib/Utils/process-message.js +630 -0
- package/lib/Utils/reporting-utils.js +258 -0
- package/lib/Utils/session-pool.js +73 -0
- package/lib/Utils/signal.js +207 -0
- package/lib/Utils/stanza-ack.js +38 -0
- package/lib/Utils/sticker.js +139 -0
- package/lib/Utils/sync-action-utils.js +49 -0
- package/lib/Utils/tc-token-utils.js +163 -0
- package/lib/Utils/use-multi-file-auth-state.js +121 -0
- package/lib/Utils/use-sqlite-auth-state.js +168 -0
- package/lib/Utils/validate-connection.js +203 -0
- package/lib/Utils/view-once-cache.js +79 -0
- package/lib/Utils/voip-rekey.js +25 -0
- package/lib/Utils/warmup.js +117 -0
- package/lib/WABinary/constants.js +1301 -0
- package/lib/WABinary/decode.js +262 -0
- package/lib/WABinary/encode.js +220 -0
- package/lib/WABinary/generic-utils.js +204 -0
- package/lib/WABinary/index.js +6 -0
- package/lib/WABinary/jid-utils.js +98 -0
- package/lib/WABinary/types.js +2 -0
- package/lib/WAM/BinaryInfo.js +10 -0
- package/lib/WAM/constants.js +22853 -0
- package/lib/WAM/encode.js +150 -0
- package/lib/WAM/index.js +4 -0
- package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +41 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
- package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +52 -0
- package/lib/WAUSync/Protocols/USyncPictureProtocol.js +31 -0
- package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +26 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
- package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +35 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
- package/lib/WAUSync/Protocols/index.js +13 -0
- package/lib/WAUSync/USyncQuery.js +127 -0
- package/lib/WAUSync/USyncUser.js +31 -0
- package/lib/WAUSync/index.js +4 -0
- package/lib/antiban.js +4083 -0
- package/lib/index.js +24 -0
- package/package.json +147 -0
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/Utils/sticker.js — image/video -> WhatsApp WebP sticker conversion,
|
|
3
|
+
* plus writing the sticker-pack EXIF metadata WhatsApp reads for the pack
|
|
4
|
+
* name/publisher/emoji. Requires the optional "sharp" dependency; video
|
|
5
|
+
* conversion additionally shells out to a locally-installed `ffmpeg`.
|
|
6
|
+
*
|
|
7
|
+
* Note on the ffmpeg call: options.fps/seconds are strictly validated and
|
|
8
|
+
* coerced to bounded integers, and the process is spawned with an argv
|
|
9
|
+
* array (execFile), never a shell string — so there's no way for a caller
|
|
10
|
+
* (or attacker-controlled option) to inject extra shell commands here.
|
|
11
|
+
*/
|
|
12
|
+
import os from 'os';
|
|
13
|
+
import path from 'path';
|
|
14
|
+
import fs from 'fs';
|
|
15
|
+
import crypto from 'crypto';
|
|
16
|
+
import { execFile } from 'child_process';
|
|
17
|
+
|
|
18
|
+
export const addExifToWebp = async (webpBuffer, { packName = '', packPublisher = '', categories = [] } = {}) => {
|
|
19
|
+
const json = {
|
|
20
|
+
'sticker-pack-id': crypto.randomBytes(16).toString('hex'),
|
|
21
|
+
'sticker-pack-name': packName,
|
|
22
|
+
'sticker-pack-publisher': packPublisher,
|
|
23
|
+
emojis: categories.length ? categories : ['😀']
|
|
24
|
+
};
|
|
25
|
+
const jsonBuffer = Buffer.from(JSON.stringify(json), 'utf-8');
|
|
26
|
+
const exifAttr = Buffer.from([
|
|
27
|
+
0x49, 0x49, 0x2a, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x41, 0x57, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16,
|
|
28
|
+
0x00, 0x00, 0x00
|
|
29
|
+
]);
|
|
30
|
+
exifAttr.writeUIntLE(jsonBuffer.length, 14, 4);
|
|
31
|
+
const exifPayload = Buffer.concat([exifAttr, jsonBuffer]);
|
|
32
|
+
const pad = (buf) => (buf.length % 2 === 1 ? Buffer.concat([buf, Buffer.from([0x00])]) : buf);
|
|
33
|
+
const makeChunk = (tag, data) => {
|
|
34
|
+
const sizeField = Buffer.alloc(4);
|
|
35
|
+
sizeField.writeUInt32LE(data.length, 0);
|
|
36
|
+
return Buffer.concat([Buffer.from(tag, 'ascii'), sizeField, pad(data)]);
|
|
37
|
+
};
|
|
38
|
+
const exifChunk = makeChunk('EXIF', exifPayload);
|
|
39
|
+
if (webpBuffer.slice(0, 4).toString('ascii') !== 'RIFF' || webpBuffer.slice(8, 12).toString('ascii') !== 'WEBP') {
|
|
40
|
+
throw new Error('addExifToWebp expects a valid WebP buffer');
|
|
41
|
+
}
|
|
42
|
+
let offset = 12;
|
|
43
|
+
let vp8xChunk = null;
|
|
44
|
+
const otherChunks = [];
|
|
45
|
+
while (offset < webpBuffer.length) {
|
|
46
|
+
const tag = webpBuffer.slice(offset, offset + 4).toString('ascii');
|
|
47
|
+
const size = webpBuffer.readUInt32LE(offset + 4);
|
|
48
|
+
const chunkTotal = 8 + size + (size % 2);
|
|
49
|
+
if (tag === 'VP8X') {
|
|
50
|
+
vp8xChunk = webpBuffer.slice(offset, offset + chunkTotal);
|
|
51
|
+
}
|
|
52
|
+
else if (tag !== 'EXIF') {
|
|
53
|
+
otherChunks.push(webpBuffer.slice(offset, offset + chunkTotal));
|
|
54
|
+
}
|
|
55
|
+
offset += chunkTotal;
|
|
56
|
+
}
|
|
57
|
+
let flags;
|
|
58
|
+
let canvasWidth;
|
|
59
|
+
let canvasHeight;
|
|
60
|
+
if (vp8xChunk) {
|
|
61
|
+
flags = vp8xChunk.readUInt8(8);
|
|
62
|
+
canvasWidth = vp8xChunk.readUIntLE(12, 3) + 1;
|
|
63
|
+
canvasHeight = vp8xChunk.readUIntLE(15, 3) + 1;
|
|
64
|
+
}
|
|
65
|
+
else {
|
|
66
|
+
flags = 0;
|
|
67
|
+
let sharp;
|
|
68
|
+
try {
|
|
69
|
+
sharp = (await import('sharp')).default;
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
throw new Error('addExifToWebp needs the optional "sharp" dependency to read image dimensions');
|
|
73
|
+
}
|
|
74
|
+
const meta = await sharp(webpBuffer).metadata();
|
|
75
|
+
canvasWidth = meta.width;
|
|
76
|
+
canvasHeight = meta.height;
|
|
77
|
+
}
|
|
78
|
+
flags |= 0x08;
|
|
79
|
+
const vp8xData = Buffer.alloc(10);
|
|
80
|
+
vp8xData.writeUInt8(flags, 0);
|
|
81
|
+
vp8xData.writeUIntLE(canvasWidth - 1, 4, 3);
|
|
82
|
+
vp8xData.writeUIntLE(canvasHeight - 1, 7, 3);
|
|
83
|
+
const newVp8xChunk = makeChunk('VP8X', vp8xData);
|
|
84
|
+
const body = Buffer.concat([newVp8xChunk, ...otherChunks, exifChunk]);
|
|
85
|
+
const fileSize = Buffer.alloc(4);
|
|
86
|
+
fileSize.writeUInt32LE(4 + body.length, 0);
|
|
87
|
+
return Buffer.concat([Buffer.from('RIFF', 'ascii'), fileSize, Buffer.from('WEBP', 'ascii'), body]);
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
export const imageToWebpSticker = async (imageBuffer, options = {}) => {
|
|
91
|
+
let sharp;
|
|
92
|
+
try {
|
|
93
|
+
sharp = (await import('sharp')).default;
|
|
94
|
+
}
|
|
95
|
+
catch (error) {
|
|
96
|
+
throw new Error('imageToWebpSticker requires the optional "sharp" dependency to be installed');
|
|
97
|
+
}
|
|
98
|
+
const webp = await sharp(imageBuffer)
|
|
99
|
+
.resize(512, 512, { fit: 'contain', background: { r: 0, g: 0, b: 0, alpha: 0 } })
|
|
100
|
+
.webp({ quality: options.quality ?? 80 })
|
|
101
|
+
.toBuffer();
|
|
102
|
+
return addExifToWebp(webp, options);
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
/** Clamp a user-supplied numeric option to a safe integer range, with a default if invalid. */
|
|
106
|
+
const boundedInt = (value, { min, max, fallback }) => {
|
|
107
|
+
const n = Number(value);
|
|
108
|
+
if (!Number.isFinite(n)) {
|
|
109
|
+
return fallback;
|
|
110
|
+
}
|
|
111
|
+
return Math.min(max, Math.max(min, Math.round(n)));
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
export const videoToWebpSticker = async (videoBuffer, options = {}) => {
|
|
115
|
+
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'xayz-baileys-sticker-'));
|
|
116
|
+
const inputPath = path.join(tmpDir, 'input.mp4');
|
|
117
|
+
const outputPath = path.join(tmpDir, 'output.webp');
|
|
118
|
+
fs.writeFileSync(inputPath, videoBuffer);
|
|
119
|
+
// Validated/clamped, not interpolated into a shell string — see execFile call below.
|
|
120
|
+
const fps = boundedInt(options.fps, { min: 1, max: 30, fallback: 10 });
|
|
121
|
+
const seconds = boundedInt(options.seconds, { min: 1, max: 10, fallback: 5 });
|
|
122
|
+
const vf = `fps=${fps},scale=512:512:force_original_aspect_ratio=decrease,` +
|
|
123
|
+
`pad=512:512:(ow-iw)/2:(oh-ih)/2:color=0x00000000,split[a][b];` +
|
|
124
|
+
`[a]palettegen=reserve_transparent=1[p];[b][p]paletteuse`;
|
|
125
|
+
const args = ['-y', '-i', inputPath, '-t', String(seconds), '-vf', vf, '-loop', '0', '-preset', 'default', '-an', '-vsync', '0', outputPath];
|
|
126
|
+
try {
|
|
127
|
+
await new Promise((resolve, reject) => {
|
|
128
|
+
// execFile with an argv array — ffmpeg is invoked directly, no shell is
|
|
129
|
+
// spawned, so nothing in `args` (all of which are numbers/paths we built
|
|
130
|
+
// ourselves) can be interpreted as a shell command.
|
|
131
|
+
execFile('ffmpeg', args, (err) => (err ? reject(err) : resolve()));
|
|
132
|
+
});
|
|
133
|
+
const webp = fs.readFileSync(outputPath);
|
|
134
|
+
return await addExifToWebp(webp, options);
|
|
135
|
+
}
|
|
136
|
+
finally {
|
|
137
|
+
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
138
|
+
}
|
|
139
|
+
};
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { proto } from '../../WAProto/index.js';
|
|
2
|
+
import { isLidUser, isPnUser } from '../WABinary/index.js';
|
|
3
|
+
/**
|
|
4
|
+
* Process contactAction and return events to emit.
|
|
5
|
+
* Pure function - no side effects.
|
|
6
|
+
*/
|
|
7
|
+
export const processContactAction = (action, id, logger) => {
|
|
8
|
+
const results = [];
|
|
9
|
+
if (!id) {
|
|
10
|
+
logger?.warn({ hasFullName: !!action.fullName, hasLidJid: !!action.lidJid, hasPnJid: !!action.pnJid }, 'contactAction sync: missing id in index');
|
|
11
|
+
return results;
|
|
12
|
+
}
|
|
13
|
+
const lidJid = action.lidJid;
|
|
14
|
+
const idIsPn = isPnUser(id);
|
|
15
|
+
// PN is in index[1], not in contactAction.pnJid which is usually null
|
|
16
|
+
const phoneNumber = idIsPn ? id : action.pnJid || undefined;
|
|
17
|
+
// Always emit contacts.upsert
|
|
18
|
+
results.push({
|
|
19
|
+
event: 'contacts.upsert',
|
|
20
|
+
data: [
|
|
21
|
+
{
|
|
22
|
+
id,
|
|
23
|
+
name: action.fullName || action.firstName || action.username || undefined,
|
|
24
|
+
username: action.username || undefined,
|
|
25
|
+
lid: lidJid || undefined,
|
|
26
|
+
phoneNumber
|
|
27
|
+
}
|
|
28
|
+
]
|
|
29
|
+
});
|
|
30
|
+
// Emit lid-mapping.update if we have valid LID-PN pair
|
|
31
|
+
if (lidJid && isLidUser(lidJid) && idIsPn) {
|
|
32
|
+
results.push({
|
|
33
|
+
event: 'lid-mapping.update',
|
|
34
|
+
data: { lid: lidJid, pn: id }
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
return results;
|
|
38
|
+
};
|
|
39
|
+
export const emitSyncActionResults = (ev, results) => {
|
|
40
|
+
for (const result of results) {
|
|
41
|
+
if (result.event === 'contacts.upsert') {
|
|
42
|
+
ev.emit('contacts.upsert', result.data);
|
|
43
|
+
}
|
|
44
|
+
else {
|
|
45
|
+
ev.emit('lid-mapping.update', result.data);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
//# sourceMappingURL=sync-action-utils.js.map
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isJidMetaAI, isLidUser, isPnUser, jidNormalizedUser } from '../WABinary/index.js';
|
|
2
|
+
// Same phone-number pattern as WABinary's isJidBot, applied against the user
|
|
3
|
+
// part so the check is invariant to @c.us ↔ @s.whatsapp.net normalization.
|
|
4
|
+
const BOT_PHONE_REGEX = /^1313555\d{4}$|^131655500\d{2}$/;
|
|
5
|
+
/**
|
|
6
|
+
* Mirrors WA Web's `Wid.isRegularUser()` (user ∧ ¬PSA ∧ ¬Bot). Used to gate tctoken
|
|
7
|
+
* storage against malformed notifications — WA Web filters server-side but we
|
|
8
|
+
* defend here for parity with `WAWebSetTcTokenChatAction.handleIncomingTcToken`.
|
|
9
|
+
* Works for both pre- and post-normalized JIDs (`@c.us` vs `@s.whatsapp.net`).
|
|
10
|
+
*/
|
|
11
|
+
function isRegularUser(jid) {
|
|
12
|
+
if (!jid)
|
|
13
|
+
return false;
|
|
14
|
+
const user = jid.split('@')[0] ?? '';
|
|
15
|
+
if (user === '0')
|
|
16
|
+
return false; // PSA
|
|
17
|
+
if (BOT_PHONE_REGEX.test(user))
|
|
18
|
+
return false; // Bot by phone pattern
|
|
19
|
+
if (isJidMetaAI(jid))
|
|
20
|
+
return false; // MetaAI (@bot server)
|
|
21
|
+
return !!(isPnUser(jid) || isLidUser(jid) || isHostedPnUser(jid) || isHostedLidUser(jid) || jid.endsWith('@c.us'));
|
|
22
|
+
}
|
|
23
|
+
const TC_TOKEN_BUCKET_DURATION = 604800; // 7 days
|
|
24
|
+
const TC_TOKEN_NUM_BUCKETS = 4; // ~28-day rolling window
|
|
25
|
+
/** Sentinel key under `tctoken` store holding a JSON array of tracked storage JIDs for cross-session pruning. */
|
|
26
|
+
export const TC_TOKEN_INDEX_KEY = '__index';
|
|
27
|
+
/** Read the persisted tctoken JID index and return its entries (never contains the sentinel key itself). */
|
|
28
|
+
export async function readTcTokenIndex(keys) {
|
|
29
|
+
const data = await keys.get('tctoken', [TC_TOKEN_INDEX_KEY]);
|
|
30
|
+
const entry = data[TC_TOKEN_INDEX_KEY];
|
|
31
|
+
if (!entry?.token?.length)
|
|
32
|
+
return [];
|
|
33
|
+
try {
|
|
34
|
+
const parsed = JSON.parse(Buffer.from(entry.token).toString());
|
|
35
|
+
if (!Array.isArray(parsed))
|
|
36
|
+
return [];
|
|
37
|
+
return parsed.filter((j) => typeof j === 'string' && j.length > 0 && j !== TC_TOKEN_INDEX_KEY);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return [];
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** Build a SignalDataSet fragment that writes the merged index (persisted ∪ added) under the sentinel key. */
|
|
44
|
+
export async function buildMergedTcTokenIndexWrite(keys, addedJids) {
|
|
45
|
+
const persisted = await readTcTokenIndex(keys);
|
|
46
|
+
const merged = new Set(persisted);
|
|
47
|
+
for (const jid of addedJids) {
|
|
48
|
+
if (jid && jid !== TC_TOKEN_INDEX_KEY)
|
|
49
|
+
merged.add(jid);
|
|
50
|
+
}
|
|
51
|
+
return {
|
|
52
|
+
[TC_TOKEN_INDEX_KEY]: { token: Buffer.from(JSON.stringify([...merged])) }
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
// WA Web has separate sender/receiver AB props for these but they're identical today
|
|
56
|
+
export function isTcTokenExpired(timestamp) {
|
|
57
|
+
if (timestamp === null || timestamp === undefined)
|
|
58
|
+
return true;
|
|
59
|
+
const ts = typeof timestamp === 'string' ? parseInt(timestamp) : timestamp;
|
|
60
|
+
if (isNaN(ts))
|
|
61
|
+
return true;
|
|
62
|
+
const now = Math.floor(Date.now() / 1000);
|
|
63
|
+
const currentBucket = Math.floor(now / TC_TOKEN_BUCKET_DURATION);
|
|
64
|
+
const cutoffBucket = currentBucket - (TC_TOKEN_NUM_BUCKETS - 1);
|
|
65
|
+
const cutoffTimestamp = cutoffBucket * TC_TOKEN_BUCKET_DURATION;
|
|
66
|
+
return ts < cutoffTimestamp;
|
|
67
|
+
}
|
|
68
|
+
export function shouldSendNewTcToken(senderTimestamp) {
|
|
69
|
+
if (senderTimestamp === undefined)
|
|
70
|
+
return true;
|
|
71
|
+
const now = Math.floor(Date.now() / 1000);
|
|
72
|
+
const currentBucket = Math.floor(now / TC_TOKEN_BUCKET_DURATION);
|
|
73
|
+
const senderBucket = Math.floor(senderTimestamp / TC_TOKEN_BUCKET_DURATION);
|
|
74
|
+
return currentBucket > senderBucket;
|
|
75
|
+
}
|
|
76
|
+
/** Resolve JID to LID for tctoken storage (WA Web stores under LID) */
|
|
77
|
+
export async function resolveTcTokenJid(jid, getLIDForPN) {
|
|
78
|
+
if (isLidUser(jid))
|
|
79
|
+
return jid;
|
|
80
|
+
const lid = await getLIDForPN(jid);
|
|
81
|
+
return lid ?? jid;
|
|
82
|
+
}
|
|
83
|
+
/** Resolve target JID for issuing privacy token based on AB prop 14303 */
|
|
84
|
+
export async function resolveIssuanceJid(jid, issueToLid, getLIDForPN, getPNForLID) {
|
|
85
|
+
if (issueToLid) {
|
|
86
|
+
if (isLidUser(jid))
|
|
87
|
+
return jid;
|
|
88
|
+
const lid = await getLIDForPN(jid);
|
|
89
|
+
return lid ?? jid;
|
|
90
|
+
}
|
|
91
|
+
if (!isLidUser(jid))
|
|
92
|
+
return jid;
|
|
93
|
+
if (getPNForLID) {
|
|
94
|
+
const pn = await getPNForLID(jid);
|
|
95
|
+
return pn ?? jid;
|
|
96
|
+
}
|
|
97
|
+
return jid;
|
|
98
|
+
}
|
|
99
|
+
export async function buildTcTokenFromJid({ authState, jid, baseContent = [], getLIDForPN }) {
|
|
100
|
+
try {
|
|
101
|
+
const storageJid = await resolveTcTokenJid(jid, getLIDForPN);
|
|
102
|
+
const tcTokenData = await authState.keys.get('tctoken', [storageJid]);
|
|
103
|
+
const entry = tcTokenData?.[storageJid];
|
|
104
|
+
const tcTokenBuffer = entry?.token;
|
|
105
|
+
if (!tcTokenBuffer?.length || isTcTokenExpired(entry?.timestamp)) {
|
|
106
|
+
if (tcTokenBuffer) {
|
|
107
|
+
// Preserve senderTimestamp so shouldSendNewTcToken() keeps its dedupe state
|
|
108
|
+
// after we drop the unusable peer token. Only wipe the record entirely when
|
|
109
|
+
// there's nothing worth keeping.
|
|
110
|
+
const cleared = entry?.senderTimestamp !== undefined
|
|
111
|
+
? { token: Buffer.alloc(0), senderTimestamp: entry.senderTimestamp }
|
|
112
|
+
: null;
|
|
113
|
+
await authState.keys.set({ tctoken: { [storageJid]: cleared } });
|
|
114
|
+
}
|
|
115
|
+
return baseContent.length > 0 ? baseContent : undefined;
|
|
116
|
+
}
|
|
117
|
+
baseContent.push({
|
|
118
|
+
tag: 'tctoken',
|
|
119
|
+
attrs: {},
|
|
120
|
+
content: tcTokenBuffer
|
|
121
|
+
});
|
|
122
|
+
return baseContent;
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
return baseContent.length > 0 ? baseContent : undefined;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
export async function storeTcTokensFromIqResult({ result, fallbackJid, keys, getLIDForPN, onNewJidStored }) {
|
|
129
|
+
const tokensNode = getBinaryNodeChild(result, 'tokens');
|
|
130
|
+
if (!tokensNode)
|
|
131
|
+
return;
|
|
132
|
+
const tokenNodes = getBinaryNodeChildren(tokensNode, 'token');
|
|
133
|
+
for (const tokenNode of tokenNodes) {
|
|
134
|
+
if (tokenNode.attrs.type !== 'trusted_contact' || !(tokenNode.content instanceof Uint8Array)) {
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
// In notifications tokenNode.attrs.jid is your own device JID, not the sender's
|
|
138
|
+
const rawJid = jidNormalizedUser(fallbackJid || tokenNode.attrs.jid);
|
|
139
|
+
if (!isRegularUser(rawJid))
|
|
140
|
+
continue;
|
|
141
|
+
const storageJid = await resolveTcTokenJid(rawJid, getLIDForPN);
|
|
142
|
+
const existingTcData = await keys.get('tctoken', [storageJid]);
|
|
143
|
+
const existingEntry = existingTcData[storageJid];
|
|
144
|
+
const existingTs = existingEntry?.timestamp ? Number(existingEntry.timestamp) : 0;
|
|
145
|
+
const incomingTs = tokenNode.attrs.t ? Number(tokenNode.attrs.t) : 0;
|
|
146
|
+
// timestamp-less tokens would be immediately expired
|
|
147
|
+
if (!incomingTs)
|
|
148
|
+
continue;
|
|
149
|
+
if (existingTs > 0 && existingTs > incomingTs)
|
|
150
|
+
continue;
|
|
151
|
+
await keys.set({
|
|
152
|
+
tctoken: {
|
|
153
|
+
[storageJid]: {
|
|
154
|
+
...existingEntry,
|
|
155
|
+
token: Buffer.from(tokenNode.content),
|
|
156
|
+
timestamp: tokenNode.attrs.t
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
onNewJidStored?.(storageJid);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
//# sourceMappingURL=tc-token-utils.js.map
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { Mutex } from 'async-mutex';
|
|
2
|
+
import { mkdir, readFile, stat, unlink, writeFile } from 'fs/promises';
|
|
3
|
+
import { join } from 'path';
|
|
4
|
+
import { proto } from '../../WAProto/index.js';
|
|
5
|
+
import { initAuthCreds } from './auth-utils.js';
|
|
6
|
+
import { BufferJSON } from './generics.js';
|
|
7
|
+
// We need to lock files due to the fact that we are using async functions to read and write files
|
|
8
|
+
// https://github.com/WhiskeySockets/Baileys/issues/794
|
|
9
|
+
// https://github.com/nodejs/node/issues/26338
|
|
10
|
+
// Use a Map to store mutexes for each file path
|
|
11
|
+
const fileLocks = new Map();
|
|
12
|
+
// Get or create a mutex for a specific file path
|
|
13
|
+
const getFileLock = (path) => {
|
|
14
|
+
let mutex = fileLocks.get(path);
|
|
15
|
+
if (!mutex) {
|
|
16
|
+
mutex = new Mutex();
|
|
17
|
+
fileLocks.set(path, mutex);
|
|
18
|
+
}
|
|
19
|
+
return mutex;
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* stores the full authentication state in a single folder.
|
|
23
|
+
* Far more efficient than singlefileauthstate
|
|
24
|
+
*
|
|
25
|
+
* Again, I wouldn't endorse this for any production level use other than perhaps a bot.
|
|
26
|
+
* Would recommend writing an auth state for use with a proper SQL or No-SQL DB
|
|
27
|
+
* */
|
|
28
|
+
export const useMultiFileAuthState = async (folder) => {
|
|
29
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
30
|
+
const writeData = async (data, file) => {
|
|
31
|
+
const filePath = join(folder, fixFileName(file));
|
|
32
|
+
const mutex = getFileLock(filePath);
|
|
33
|
+
return mutex.acquire().then(async (release) => {
|
|
34
|
+
try {
|
|
35
|
+
await writeFile(filePath, JSON.stringify(data, BufferJSON.replacer));
|
|
36
|
+
}
|
|
37
|
+
finally {
|
|
38
|
+
release();
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
};
|
|
42
|
+
const readData = async (file) => {
|
|
43
|
+
try {
|
|
44
|
+
const filePath = join(folder, fixFileName(file));
|
|
45
|
+
const mutex = getFileLock(filePath);
|
|
46
|
+
return await mutex.acquire().then(async (release) => {
|
|
47
|
+
try {
|
|
48
|
+
const data = await readFile(filePath, { encoding: 'utf-8' });
|
|
49
|
+
return JSON.parse(data, BufferJSON.reviver);
|
|
50
|
+
}
|
|
51
|
+
finally {
|
|
52
|
+
release();
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
const removeData = async (file) => {
|
|
61
|
+
try {
|
|
62
|
+
const filePath = join(folder, fixFileName(file));
|
|
63
|
+
const mutex = getFileLock(filePath);
|
|
64
|
+
return mutex.acquire().then(async (release) => {
|
|
65
|
+
try {
|
|
66
|
+
await unlink(filePath);
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
}
|
|
70
|
+
finally {
|
|
71
|
+
release();
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
catch { }
|
|
76
|
+
};
|
|
77
|
+
const folderInfo = await stat(folder).catch(() => { });
|
|
78
|
+
if (folderInfo) {
|
|
79
|
+
if (!folderInfo.isDirectory()) {
|
|
80
|
+
throw new Error(`found something that is not a directory at ${folder}, either delete it or specify a different location`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
await mkdir(folder, { recursive: true });
|
|
85
|
+
}
|
|
86
|
+
const fixFileName = (file) => file?.replace(/\//g, '__')?.replace(/:/g, '-');
|
|
87
|
+
const creds = (await readData('creds.json')) || initAuthCreds();
|
|
88
|
+
return {
|
|
89
|
+
state: {
|
|
90
|
+
creds,
|
|
91
|
+
keys: {
|
|
92
|
+
get: async (type, ids) => {
|
|
93
|
+
const data = {};
|
|
94
|
+
await Promise.all(ids.map(async (id) => {
|
|
95
|
+
let value = await readData(`${type}-${id}.json`);
|
|
96
|
+
if (type === 'app-state-sync-key' && value) {
|
|
97
|
+
value = proto.Message.AppStateSyncKeyData.fromObject(value);
|
|
98
|
+
}
|
|
99
|
+
data[id] = value;
|
|
100
|
+
}));
|
|
101
|
+
return data;
|
|
102
|
+
},
|
|
103
|
+
set: async (data) => {
|
|
104
|
+
const tasks = [];
|
|
105
|
+
for (const category in data) {
|
|
106
|
+
for (const id in data[category]) {
|
|
107
|
+
const value = data[category][id];
|
|
108
|
+
const file = `${category}-${id}.json`;
|
|
109
|
+
tasks.push(value ? writeData(value, file) : removeData(file));
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
await Promise.all(tasks);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
},
|
|
116
|
+
saveCreds: async () => {
|
|
117
|
+
return writeData(creds, 'creds.json');
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
};
|
|
121
|
+
//# sourceMappingURL=use-multi-file-auth-state.js.map
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/Utils/use-sqlite-auth-state.js — alternative auth-state storage using
|
|
3
|
+
* Node's built-in `node:sqlite` module (Node 22.5+), instead of one JSON
|
|
4
|
+
* file per key like `useMultiFileAuthState`. Single-file storage scales much
|
|
5
|
+
* better for a busy bot with lots of app-state-sync keys/prekeys.
|
|
6
|
+
*
|
|
7
|
+
* Optional: if `node:sqlite` isn't available (older Node), this throws a
|
|
8
|
+
* clear error telling you to upgrade or use `useMultiFileAuthState` instead
|
|
9
|
+
* — nothing else in the library depends on this file or on `node:sqlite`.
|
|
10
|
+
*/
|
|
11
|
+
import { mkdir, readdir, readFile } from 'fs/promises';
|
|
12
|
+
import { dirname, join } from 'path';
|
|
13
|
+
import { proto } from '../../WAProto/index.js';
|
|
14
|
+
import { initAuthCreds } from './auth-utils.js';
|
|
15
|
+
|
|
16
|
+
export const useSqliteAuthState = async (pathOrFolder, options = {}) => {
|
|
17
|
+
const { fileName = 'auth.db', migrateFromFolder, logger } = options;
|
|
18
|
+
const dbPath = /\.(db|sqlite|sqlite3)$/i.test(pathOrFolder) ? pathOrFolder : join(pathOrFolder, fileName);
|
|
19
|
+
const bufReplacer = (_, value) => {
|
|
20
|
+
if (Buffer.isBuffer(value) || value instanceof Uint8Array || value?.type === 'Buffer') {
|
|
21
|
+
return { type: 'Buffer', data: Buffer.from(value?.data || value).toString('base64') };
|
|
22
|
+
}
|
|
23
|
+
return value;
|
|
24
|
+
};
|
|
25
|
+
const bufReviver = (_, value) => {
|
|
26
|
+
if (value && typeof value === 'object' && value.type === 'Buffer' && typeof value.data === 'string') {
|
|
27
|
+
return Buffer.from(value.data, 'base64');
|
|
28
|
+
}
|
|
29
|
+
return value;
|
|
30
|
+
};
|
|
31
|
+
const encode = (value) => {
|
|
32
|
+
if (Buffer.isBuffer(value) || value instanceof Uint8Array) {
|
|
33
|
+
return Buffer.concat([Buffer.from([1]), Buffer.from(value)]);
|
|
34
|
+
}
|
|
35
|
+
return Buffer.concat([Buffer.from([0]), Buffer.from(JSON.stringify(value, bufReplacer), 'utf8')]);
|
|
36
|
+
};
|
|
37
|
+
const decode = (blob) => {
|
|
38
|
+
if (!blob || blob.length === 0)
|
|
39
|
+
return null;
|
|
40
|
+
if (blob[0] === 1)
|
|
41
|
+
return Buffer.from(blob.subarray(1));
|
|
42
|
+
return JSON.parse(Buffer.from(blob.subarray(1)).toString('utf8'), bufReviver);
|
|
43
|
+
};
|
|
44
|
+
const fixName = (s) => s?.replace(/\//g, '__')?.replace(/:/g, '-');
|
|
45
|
+
const keyOf = (category, id) => fixName(`${category}-${id}`);
|
|
46
|
+
let DatabaseSync;
|
|
47
|
+
try {
|
|
48
|
+
({ DatabaseSync } = await import('node:sqlite'));
|
|
49
|
+
}
|
|
50
|
+
catch (err) {
|
|
51
|
+
throw new Error("useSqliteAuthState needs the built-in 'node:sqlite' module (Node 22.5+). Upgrade Node, or use useMultiFileAuthState instead.");
|
|
52
|
+
}
|
|
53
|
+
await mkdir(dirname(dbPath), { recursive: true }).catch(() => { });
|
|
54
|
+
const db = new DatabaseSync(dbPath);
|
|
55
|
+
db.exec('PRAGMA journal_mode = TRUNCATE');
|
|
56
|
+
db.exec('PRAGMA synchronous = NORMAL');
|
|
57
|
+
db.exec('PRAGMA busy_timeout = 5000');
|
|
58
|
+
db.exec('CREATE TABLE IF NOT EXISTS auth_state (k TEXT PRIMARY KEY, v BLOB NOT NULL) WITHOUT ROWID');
|
|
59
|
+
const qGet = db.prepare('SELECT v FROM auth_state WHERE k = ?');
|
|
60
|
+
const qUpsert = db.prepare('INSERT INTO auth_state(k,v) VALUES(?,?) ON CONFLICT(k) DO UPDATE SET v=excluded.v');
|
|
61
|
+
const qDelete = db.prepare('DELETE FROM auth_state WHERE k = ?');
|
|
62
|
+
const runTx = (fn) => {
|
|
63
|
+
db.exec('BEGIN');
|
|
64
|
+
try {
|
|
65
|
+
const r = fn();
|
|
66
|
+
db.exec('COMMIT');
|
|
67
|
+
return r;
|
|
68
|
+
}
|
|
69
|
+
catch (err) {
|
|
70
|
+
db.exec('ROLLBACK');
|
|
71
|
+
throw err;
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
const readRaw = (k) => {
|
|
75
|
+
const row = qGet.get(k);
|
|
76
|
+
if (!row)
|
|
77
|
+
return null;
|
|
78
|
+
try {
|
|
79
|
+
return decode(row.v);
|
|
80
|
+
}
|
|
81
|
+
catch (err) {
|
|
82
|
+
logger?.warn?.({ k, err: err?.message }, 'sqlite-auth: failed to decode row, treating as missing');
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
const runMigration = async (folder) => {
|
|
87
|
+
let files;
|
|
88
|
+
try {
|
|
89
|
+
files = await readdir(folder);
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
return 0;
|
|
93
|
+
}
|
|
94
|
+
const rows = [];
|
|
95
|
+
for (const file of files) {
|
|
96
|
+
if (!file.endsWith('.json'))
|
|
97
|
+
continue;
|
|
98
|
+
let value;
|
|
99
|
+
try {
|
|
100
|
+
value = JSON.parse(await readFile(join(folder, file), 'utf8'), bufReviver);
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
if (value === null || value === undefined)
|
|
106
|
+
continue;
|
|
107
|
+
rows.push([file.slice(0, -'.json'.length), encode(value)]);
|
|
108
|
+
}
|
|
109
|
+
runTx(() => {
|
|
110
|
+
for (const [k, v] of rows)
|
|
111
|
+
qUpsert.run(k, v);
|
|
112
|
+
});
|
|
113
|
+
return rows.length;
|
|
114
|
+
};
|
|
115
|
+
const hasCreds = () => !!qGet.get('creds');
|
|
116
|
+
if (migrateFromFolder && !hasCreds()) {
|
|
117
|
+
const n = await runMigration(migrateFromFolder);
|
|
118
|
+
if (n > 0)
|
|
119
|
+
logger?.info?.({ count: n, from: migrateFromFolder }, 'sqlite-auth: migrated legacy auth state');
|
|
120
|
+
}
|
|
121
|
+
let creds = readRaw('creds');
|
|
122
|
+
if (!creds) {
|
|
123
|
+
creds = initAuthCreds();
|
|
124
|
+
qUpsert.run('creds', encode(creds));
|
|
125
|
+
}
|
|
126
|
+
const keys = {
|
|
127
|
+
get: async (type, ids) => {
|
|
128
|
+
const data = {};
|
|
129
|
+
for (const id of ids) {
|
|
130
|
+
let value = readRaw(keyOf(type, id));
|
|
131
|
+
if (type === 'app-state-sync-key' && value) {
|
|
132
|
+
value = proto.Message.AppStateSyncKeyData.fromObject(value);
|
|
133
|
+
}
|
|
134
|
+
if (value !== null && value !== undefined) {
|
|
135
|
+
data[id] = value;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return data;
|
|
139
|
+
},
|
|
140
|
+
set: async (data) => {
|
|
141
|
+
const ops = [];
|
|
142
|
+
for (const category in data) {
|
|
143
|
+
for (const id in data[category]) {
|
|
144
|
+
ops.push([keyOf(category, id), data[category][id]]);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
runTx(() => {
|
|
148
|
+
for (const [k, value] of ops) {
|
|
149
|
+
if (value === null || value === undefined)
|
|
150
|
+
qDelete.run(k);
|
|
151
|
+
else
|
|
152
|
+
qUpsert.run(k, encode(value));
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
},
|
|
156
|
+
clear: async () => {
|
|
157
|
+
db.prepare("DELETE FROM auth_state WHERE k <> 'creds'").run();
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
return {
|
|
161
|
+
state: { creds, keys },
|
|
162
|
+
saveCreds: async () => {
|
|
163
|
+
qUpsert.run('creds', encode(creds));
|
|
164
|
+
},
|
|
165
|
+
db,
|
|
166
|
+
close: () => db.close()
|
|
167
|
+
};
|
|
168
|
+
};
|