whalibmob 5.40.41 → 5.40.42

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.
Files changed (2) hide show
  1. package/lib/Registration.js +177 -709
  2. package/package.json +1 -1
@@ -19,23 +19,10 @@ const { dbg: _whaDbg, warn: _whaWarn } = require('./logger');
19
19
 
20
20
  // ---------- Request envelope ----------
21
21
  //
22
- // The registration server reads which platform is calling out of the
23
- // User-Agent. There is no form field for it — none is sent — so a request whose
24
- // User-Agent does not name a platform it knows is refused with
25
- // {"param":"platform","reason":"bad_param"} on every endpoint. The
26
- // giveaway is that /client_log is refused the same way, and its body carries no
27
- // device fields at all: nothing about the platform is in the body to begin with.
28
- //
29
- // Android used to be sent as `WhatsApp/<version> A`, which names nothing, and
30
- // was refused everywhere. iOS has always sent the full form and has always
31
- // worked, which is why only one of the two platforms was broken.
32
- //
33
- // The three extra Android headers were observed on a live native Android
34
- // registration. The native iOS client omits all three, so the iOS envelope
35
- // stays exactly as it was.
36
- // The platform token in the User-Agent. The Business builds name themselves
37
- // differently — `SMBA` on Android, `SMB iOS` on iOS — and the registration
38
- // server reads the platform out of exactly this string.
22
+ // The server reads the platform only from the User-Agent; an unknown one is
23
+ // refused with {"param":"platform","reason":"bad_param"}. The extra Android
24
+ // headers match a live native registration; iOS sends none of them.
25
+ // Platform token: `SMBA` / `SMB iOS` for Business builds.
39
26
  function _uaPlatformName(device) {
40
27
  if (device.os === 'android') return device.business ? 'SMBA' : 'Android';
41
28
  return device.business ? 'SMB iOS' : 'iOS';
@@ -43,14 +30,11 @@ function _uaPlatformName(device) {
43
30
 
44
31
  function registrationHeaders(device, waVersion) {
45
32
  if (device.os === 'android') {
46
- // Header set and order mirror the native client's registration POST: no
47
- // Accept, Connection kept alive, gzip advertised (the response is gunzipped
48
- // on both the direct and SOCKS paths). request_token is an UPPERCASE UUID —
49
- // the native client never mints a lowercase one.
33
+ // Same headers and order as the native POST. request_token is an UPPERCASE UUID.
50
34
  return {
51
35
  'User-Agent': `WhatsApp/${waVersion} ${_uaPlatformName(device)}/${device.osVersion} Device/${device.manufacturer}-${device.modelId}`,
52
36
  'WaMsysRequest': '1',
53
- // A fresh one per request, the way the native client mints it.
37
+ // Fresh per request.
54
38
  'request_token': uuidv4().toUpperCase(),
55
39
  'Content-Type': 'application/x-www-form-urlencoded',
56
40
  'Connection': 'Keep-Alive',
@@ -64,12 +48,7 @@ function registrationHeaders(device, waVersion) {
64
48
  }
65
49
 
66
50
  // ---------- SOCKS4 / SOCKS5 / Tor support ----------
67
- //
68
- // The parsing, the dialer and the HTTPS agent all live in ./socks now, because
69
- // registration is no longer the only thing that needs them: the version
70
- // lookups below, the web sw.js probe, the WhatsApp Web socket and the mobile
71
- // TCP socket route through the same proxy. They are re-exported at the bottom
72
- // of this file so existing importers keep working.
51
+ // Lives in ./socks (shared by all transports); re-exported below for old importers.
73
52
  const {
74
53
  parseSocksProxy, socksProxyUrl, socksConnect, proxyAgent
75
54
  } = require('./socks');
@@ -78,9 +57,7 @@ async function httpPostViaSocks(path, body, waVersion, proxyUrl, authHeader, dev
78
57
  const dHost = 'v.whatsapp.net';
79
58
  const dPort = 443;
80
59
 
81
- // socksConnect carries the same 20s handshake timeout this used to set
82
- // inline: without one, a proxy that accepts the TCP connection and then says
83
- // nothing leaves the whole registration hanging with no error.
60
+ // socksConnect has a 20s handshake timeout, so a silent proxy cannot hang us.
84
61
  const rawSocket = await socksConnect(proxyUrl, dHost, dPort);
85
62
 
86
63
  const tlsSocket = tls.connect({
@@ -96,9 +73,7 @@ async function httpPostViaSocks(path, body, waVersion, proxyUrl, authHeader, dev
96
73
  });
97
74
 
98
75
  const headers = registrationHeaders(device || getDeviceConfig(), waVersion);
99
- // The native client submits the parameters twice: once in the clear as the
100
- // URL query, once encrypted inside ENC. The query string here is the exact
101
- // plaintext that was encrypted, byte for byte.
76
+ // Like the native client, params go both as the URL query and encrypted in ENC.
102
77
  const target = query ? `/v2${path}?${query}` : `/v2${path}`;
103
78
  const reqLines = [
104
79
  `POST ${target} HTTP/1.1`,
@@ -107,9 +82,7 @@ async function httpPostViaSocks(path, body, waVersion, proxyUrl, authHeader, dev
107
82
  `Content-Length: ${Buffer.byteLength(body)}`
108
83
  ];
109
84
  if (authHeader) reqLines.push(`Authorization: ${authHeader}`);
110
- // Connection: Keep-Alive rides in from registrationHeaders, matching the
111
- // native client; the response is still delimited by its own length and the
112
- // socket is destroyed once it is read.
85
+ // Keep-Alive comes from registrationHeaders; the socket is destroyed after the read.
113
86
  reqLines.push('', body);
114
87
  const req = reqLines.join('\r\n');
115
88
 
@@ -122,19 +95,9 @@ async function httpPostViaSocks(path, body, waVersion, proxyUrl, authHeader, dev
122
95
  try { return JSON.parse(bodyStr); } catch (_) { return { raw: bodyStr }; }
123
96
  }
124
97
 
125
- // A response is over when its own length says so, not when the socket shuts.
126
- //
127
- // This is the part `https.request` does for you and a hand-rolled socket does
128
- // not. WhatsApp answers a registration request in well under a second and then
129
- // leaves the connection open — `Connection: close` in the request does not
130
- // change that. Waiting for end or close therefore waited for something that
131
- // never came, and every proxied registration died on the read timeout with the
132
- // reply already sitting in the buffer.
133
- //
134
- // So: parse as the bytes arrive, and stop at the end of the body — the byte
135
- // count in Content-Length, or the terminating zero-length chunk. end and close
136
- // stay as a fallback, for a reply that declares neither and can only be
137
- // delimited by the connection itself.
98
+ // A response ends at its declared length (Content-Length or the last chunk),
99
+ // not when the socket closes: WhatsApp keeps the connection open. end/close
100
+ // remain a fallback for replies with no declared length.
138
101
  const MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
139
102
 
140
103
  function readHttpResponse(socket, label, timeoutMs) {
@@ -167,8 +130,7 @@ function readHttpResponse(socket, label, timeoutMs) {
167
130
  if (parsed) settle(resolve, parsed);
168
131
  }
169
132
 
170
- // The connection did close after all — then whatever arrived is the whole
171
- // reply, even without a declared length.
133
+ // Connection closed: whatever arrived is the whole reply.
172
134
  function onEnd() {
173
135
  const parsed = parseHttpResponse(raw, true);
174
136
  if (parsed) return settle(resolve, parsed);
@@ -184,10 +146,7 @@ function readHttpResponse(socket, label, timeoutMs) {
184
146
  });
185
147
  }
186
148
 
187
- // The registration POST advertises `Accept-Encoding: gzip`, so the server may
188
- // answer gzip-compressed. Decode by the response's own content-encoding; fall
189
- // back to the raw bytes if the header lies or the stream will not inflate, so a
190
- // plain reply still parses. `headers` is the raw header block (any case).
149
+ // Gunzip when content-encoding says gzip; otherwise (or on failure) raw bytes.
191
150
  function decodeBody(bodyBuf, headers) {
192
151
  if (/^content-encoding:[ \t]*gzip/im.test(headers || '')) {
193
152
  try { return zlib.gunzipSync(bodyBuf); } catch (_) { /* fall through */ }
@@ -195,13 +154,7 @@ function decodeBody(bodyBuf, headers) {
195
154
  return bodyBuf;
196
155
  }
197
156
 
198
- /**
199
- * Parse what has arrived so far.
200
- *
201
- * Returns { status, headers, body } once the response is complete, or null
202
- * while it is still short. With `atEof` the caller is telling us no more bytes
203
- * are coming, which is itself a valid way for a body to end.
204
- */
157
+ /** Returns { status, headers, body } when complete, else null. `atEof`: no more bytes coming. */
205
158
  function parseHttpResponse(raw, atEof) {
206
159
  const headerEnd = raw.indexOf('\r\n\r\n');
207
160
  if (headerEnd < 0) return null;
@@ -220,9 +173,7 @@ function parseHttpResponse(raw, atEof) {
220
173
  const match = /^content-length:[ \t]*(\d+)/im.exec(headers);
221
174
  if (match) {
222
175
  const length = parseInt(match[1], 10);
223
- // Counted in bytes, which is why this works on the buffer and not on a
224
- // decoded string — one accented character in an error message is two bytes
225
- // and would leave the check one short forever.
176
+ // Count bytes on the buffer, not characters on a string.
226
177
  if (raw.length - bodyStart >= length) {
227
178
  return { status, headers, body: raw.slice(bodyStart, bodyStart + length) };
228
179
  }
@@ -285,14 +236,8 @@ function md5Bytes(str) {
285
236
  }
286
237
 
287
238
  // ---------- Country metadata (MCC, MNC, locale) ----------
288
- // MCC = Mobile Country Code (3 digits, string)
289
- // MNC = Mobile Network Code (2-3 digits, string; most-common operator chosen)
290
- // lg = language tag (ISO 639-1)
291
- // lc = country tag (ISO 3166-1 alpha-2)
292
- //
293
- // WhatsApp uses sim_mcc / sim_mnc to validate that the SIM matches the
294
- // dialled country code. '000'/'000' is a known red flag that third-party
295
- // clients use. We map cc → the most-common domestic operator instead.
239
+ // cc → { mcc, mnc (main operator), lg (ISO 639-1), lc (ISO 3166-1) }.
240
+ // '000'/'000' looks like a SIM-less third-party client, so map to a real operator.
296
241
  const COUNTRY_META = {
297
242
  '1': { mcc: '310', mnc: '410', lg: 'en', lc: 'US' }, // US (AT&T)
298
243
  '7': { mcc: '250', mnc: '01', lg: 'ru', lc: 'RU' }, // Russia
@@ -356,11 +301,7 @@ const COUNTRY_META = {
356
301
  '971': { mcc: '424', mnc: '02', lg: 'ar', lc: 'AE' }, // UAE
357
302
  '972': { mcc: '425', mnc: '01', lg: 'he', lc: 'IL' }, // Israel
358
303
  '880': { mcc: '470', mnc: '01', lg: 'bn', lc: 'BD' }, // Bangladesh
359
- // Filled in from the ITU mobile-network tables so a number from anywhere
360
- // reports the carrier its country actually has. Without an entry a session
361
- // falls back to 000/000, which is what a handset with no SIM card reports.
362
- // One operational national operator per country; the point is a plausible
363
- // home network, not a particular one.
304
+ // From the ITU tables: one real operator per country (else 000/000 = no SIM).
364
305
  '53': { mcc: '368', mnc: '01', lg: 'es', lc: 'CU' }, // Cuba (CUBACEL)
365
306
  '211': { mcc: '659', mnc: '02', lg: 'en', lc: 'SS' }, // South Sudan (MTN)
366
307
  '220': { mcc: '607', mnc: '01', lg: 'en', lc: 'GM' }, // Gambia (Gamcel)
@@ -501,21 +442,9 @@ const COUNTRY_META = {
501
442
  '998': { mcc: '434', mnc: '03', lg: 'ru', lc: 'UZ' }, // Uzbekistan (UzMobile)
502
443
  };
503
444
 
504
- // The carrier metadata for a country calling code.
505
- //
506
- // The table names one operator per country — Romania is always Orange, Brazil
507
- // always Vivo — because that is the best a table keyed by calling code can do.
508
- // It cannot be better: number portability means the prefix stopped naming the
509
- // operator years ago, so guessing from the number would be wrong more often
510
- // than the table is.
511
- //
512
- // So the caller can say instead. Whoever is registering knows which SIM is in
513
- // the phone, and sim_mcc/sim_mnc are meant to describe that SIM; WA_SIM_MCC and
514
- // WA_SIM_MNC (or `simMcc`/`simMnc` in the options) override the guess with the
515
- // truth. The language and locale stay with the country either way.
516
- //
517
- // MNC keeps whatever width it is given: 226/10 and 226/010 are different
518
- // networks to the server, and normalising them would break one of the two.
445
+ // Carrier metadata for a calling code: one operator per country (number
446
+ // portability makes guessing from the prefix worse). WA_SIM_MCC/WA_SIM_MNC or
447
+ // opts.simMcc/simMnc override it. MNC width is kept as given (10 ≠ 010).
519
448
  function getCountryMeta(cc, opts) {
520
449
  const base = COUNTRY_META[cc] || { mcc: '000', mnc: '000', lg: 'en', lc: 'US' };
521
450
 
@@ -530,10 +459,7 @@ function getCountryMeta(cc, opts) {
530
459
  }
531
460
 
532
461
  // ---------- Phone number parsing ----------
533
- // Reproduces Java PhoneNumberUtil behaviour:
534
- // cc = country calling code string (e.g. "40")
535
- // national = national significant number string WITHOUT leading zeros
536
- // (Java long conversion removes them automatically)
462
+ // Like Java PhoneNumberUtil: cc (e.g. "40") and national number without leading zeros.
537
463
 
538
464
  const THREE_DIGIT_CCS = new Set([
539
465
  '211','212','213','216','218','220','221','222','223','224','225','226',
@@ -559,10 +485,7 @@ const TWO_DIGIT_CCS = new Set([
559
485
  '95','98'
560
486
  ]);
561
487
 
562
- // The country table only covers the places we carry carrier metadata for, which
563
- // is far fewer than the places that can register. Anything it names still has to
564
- // be splittable, so it is folded in — a no-op while the lists above are complete,
565
- // and a backstop if a code is ever added to the table and not to them.
488
+ // Backstop: every code in COUNTRY_META must also be splittable.
566
489
  for (const cc of Object.keys(COUNTRY_META)) {
567
490
  if (cc.length === 3) THREE_DIGIT_CCS.add(cc);
568
491
  else if (cc.length === 2) TWO_DIGIT_CCS.add(cc);
@@ -587,16 +510,8 @@ function parsePhone(phoneNumber) {
587
510
 
588
511
  // ---------- WhatsApp version fetch (iOS from iTunes, Android from Play Store) ----------
589
512
 
590
- // Cached per variant: the consumer and Business builds ship on their own
591
- // schedules, and announcing one's version as the other is a version the server
592
- // has no record of for that platform.
593
- //
594
- // The entries expire. Without that the first answer of a process is its last:
595
- // a session that reconnects for weeks would keep announcing whatever the store
596
- // happened to say the morning it started, which is the same stale-version
597
- // problem the refresh exists to solve. Six hours is short enough that a release
598
- // is picked up the day it lands and long enough that a connection flapping
599
- // every few seconds never reaches the network for it.
513
+ // Cached per variant (consumer / Business ship separately), for 6 hours, so
514
+ // long-running sessions pick up new releases without hammering the network.
600
515
  const VERSION_CACHE_TTL_MS = 6 * 60 * 60 * 1000;
601
516
 
602
517
  const _cachedIosVersion = {};
@@ -618,38 +533,20 @@ function _cacheVersion(cache, key, value) {
618
533
  return value;
619
534
  }
620
535
 
621
- /**
622
- * Drop the memoised lookups so the next call goes to the network.
623
- *
624
- * Ordinary callers are served by the TTL above; this exists for tests and for
625
- * anything that needs a definite answer right now.
626
- */
536
+ /** Clear the cached versions so the next call hits the network (mainly for tests). */
627
537
  function clearVersionCache() {
628
538
  for (const k of Object.keys(_cachedIosVersion)) delete _cachedIosVersion[k];
629
539
  for (const k of Object.keys(_cachedAndroidVersion)) delete _cachedAndroidVersion[k];
630
540
  for (const k of Object.keys(_cachedPlayVersion)) delete _cachedPlayVersion[k];
631
541
  }
632
542
 
633
- // How long to let the Play lookup run before giving up on it. This is on the
634
- // connect path, so a slow answer has to become "no answer" rather than a
635
- // connection that hangs; the caller keeps whatever version it already had.
543
+ // Play lookup timeout; on the connect path, so slow means "no answer", never a hang.
636
544
  const PLAY_VERSION_TIMEOUT_MS = 20000;
637
545
 
638
546
  /**
639
- * The version Google Play is actually serving, read through Play's own API.
640
- *
641
- * This is the Android counterpart of the iTunes lookup, and the only Android
642
- * source that can be trusted. The store *page* stopped carrying a version to
643
- * scrape: fetchAndroidVersion() below now usually returns the pinned fallback,
644
- * and when it does find a number on the page it can be the wrong one — a live
645
- * run had it read 2.26.27.85 off a listing that was serving 2.26.31.77, which
646
- * is older than the fallback it was supposed to improve on.
647
- *
648
- * Play's device-facing API answers with the real thing. It needs a Google
649
- * account, which the Aurora dispenser hands out anonymously — a free
650
- * third-party service that rate-limits, hence the six-hour memoisation shared
651
- * with the other lookups and the timeout above. A failure here is not an
652
- * error: the caller falls back to the scrape and then to the pinned version.
547
+ * The version Google Play serves, via Play's API (anonymous Aurora account).
548
+ * The only trustworthy Android source; the store page is often stale.
549
+ * Failure is not an error — the caller falls back.
653
550
  *
654
551
  * @param {boolean} business the w4b package rather than the consumer one
655
552
  * @returns {Promise<string|null>} e.g. "2.26.31.77", or null if Play did not answer
@@ -683,8 +580,7 @@ async function fetchPlayVersion(business) {
683
580
  } finally {
684
581
  if (timer) clearTimeout(timer);
685
582
  }
686
- // The race leaves the lookup running when the deadline wins; it must not take
687
- // the process down if it rejects after nobody is waiting on it any more.
583
+ // Swallow a late rejection after the deadline won.
688
584
  lookup.catch(() => {});
689
585
 
690
586
  if (!version) return null;
@@ -693,31 +589,15 @@ async function fetchPlayVersion(business) {
693
589
  }
694
590
 
695
591
  /**
696
- * The current Android version for a client that is connecting, best source
697
- * first: Play's API, then the store page, then the pinned fallback.
698
- *
699
- * Registration does not come through here — it reads the version off the APK
700
- * material it computed its token from, and the two must not be confused. See
701
- * fetchWaVersion().
592
+ * Android version for connecting: Play API, then store page, then the pinned
593
+ * fallback. Registration uses the APK material's version instead (fetchWaVersion).
702
594
  */
703
595
  async function fetchAndroidVersionLive(business) {
704
596
  const fromPlay = await fetchPlayVersion(business);
705
597
  if (fromPlay) return fromPlay;
706
598
 
707
- // Play did not answer. That happens on any host it will not serve — a
708
- // datacenter IP is the usual one, since the dispenser handing out the
709
- // anonymous account rate-limits them hard — so this path is what a bot on
710
- // hosting actually runs, every time.
711
- //
712
- // The store page is tried next, but it cannot be trusted on its own: it has
713
- // been observed answering 2.26.27.85 while Play was serving 2.26.31.77. Left
714
- // as-is that is worse than useless, because a value older than the pinned
715
- // version still counts as an answer and shadows it — the caller's "never go
716
- // backwards" guard then reads it as "already current" and the session sits
717
- // on whatever it had, with the newer pinned version never once applied.
718
- //
719
- // So the pinned version is a floor, not a last resort: anything the page
720
- // says that is older than it is discarded in its favour.
599
+ // Play unavailable (common on datacenter IPs). The store page can be stale,
600
+ // so the pinned version is a floor: older page values are discarded.
721
601
  const fromPage = await fetchAndroidVersion(business);
722
602
  if (fromPage && compareVersions(fromPage, ANDROID_VERSION_FALLBACK) > 0) {
723
603
  _whaDbg('[DBG] PLAY_VERSION unavailable — the store page says ' + fromPage);
@@ -759,9 +639,7 @@ async function fetchIosVersion(business) {
759
639
  });
760
640
  }
761
641
 
762
- // Fetch latest WhatsApp Android version from Google Play Store.
763
- // Parses the 4-part "2.x.x.x" version string embedded in the page JSON data.
764
- // Falls back to ANDROID_VERSION_FALLBACK on any error.
642
+ // Scrape the 2.x.x.x version from the Play Store page; fallback on any error.
765
643
  async function fetchAndroidVersion(business) {
766
644
  const key = business ? 'business' : 'personal';
767
645
  const hit = _cachedVersion(_cachedAndroidVersion, key);
@@ -769,9 +647,7 @@ async function fetchAndroidVersion(business) {
769
647
  const packageName = business ? WHATSAPP_BUSINESS_PACKAGE : WHATSAPP_PACKAGE;
770
648
  try {
771
649
  const axios = require('axios');
772
- // Unlike https.get, axios reads HTTP_PROXY/HTTPS_PROXY on its own. That
773
- // stays untouched when no SOCKS proxy is configured; `proxy: false` is set
774
- // only alongside our own agent, so the two never fight over the socket.
650
+ // `proxy: false` only with our SOCKS agent, so axios' env proxy never conflicts.
775
651
  const socksAgent = proxyAgent();
776
652
  const resp = await axios.get(
777
653
  'https://play.google.com/store/apps/details?id=' + packageName + '&hl=en&gl=us',
@@ -780,44 +656,34 @@ async function fetchAndroidVersion(business) {
780
656
  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
781
657
  'Accept': 'text/html,application/xhtml+xml',
782
658
  'Accept-Language': 'en-US,en;q=0.9',
783
- // Only what every axios build decompresses. A default that asks for
784
- // brotli and then gets bytes back undecoded is a page that parses to
785
- // nothing.
659
+ // No brotli: not every axios build decodes it.
786
660
  'Accept-Encoding': 'gzip, deflate'
787
661
  },
788
662
  responseType: 'text',
789
663
  decompress: true,
790
664
  timeout: 12000,
791
- // axios takes an agent under a different key than https.get does, but
792
- // drives it identically. Omitted, this lookup ignores SOCKS_PROXY and
793
- // silently falls back to a pinned version on a blocked network.
665
+ // Route through SOCKS_PROXY when set.
794
666
  ...(socksAgent ? { httpsAgent: socksAgent, proxy: false } : {})
795
667
  }
796
668
  );
797
- // Buffer when the response was compressed and axios handed the bytes back
798
- // as-is. String() on a Buffer of gzip is a page no regex will ever match,
799
- // which is how this came to fall through to a two-year-old fallback without
800
- // saying a word.
669
+ // axios may hand back a Buffer; decode it before matching.
801
670
  const html = Buffer.isBuffer(resp.data)
802
671
  ? resp.data.toString('utf8')
803
672
  : String(resp.data);
804
673
 
805
- // Primary: first quoted 4-part version string matching WhatsApp's "2.x.x.x" scheme.
806
- // In Play Store JSON the current stable version appears first, before beta/history entries.
674
+ // Primary: first quoted "2.x.x.x" (the stable version comes first).
807
675
  const primary = html.match(/"(2\.\d+\.\d+\.\d+)"/);
808
676
  if (primary) {
809
677
  return _cacheVersion(_cachedAndroidVersion, key, primary[1]);
810
678
  }
811
679
 
812
- // Secondary: unquoted version adjacent to "WhatsApp" text (catches alternate HTML structures).
680
+ // Secondary: a version next to "WhatsApp" text.
813
681
  const secondary = html.match(/WhatsApp[^<"]{0,200}?(2\.\d+\.\d+\.\d+)/);
814
682
  if (secondary) {
815
683
  return _cacheVersion(_cachedAndroidVersion, key, secondary[1]);
816
684
  }
817
685
 
818
- // Last resort: the highest 4-part version anywhere on the page. Play has
819
- // rearranged this page before, and a version read from the wrong element
820
- // still beats announcing one from two years ago.
686
+ // Last resort: the highest version anywhere on the page.
821
687
  const all = html.match(/2\.\d+\.\d+\.\d+/g);
822
688
  if (all && all.length) {
823
689
  const newest = all.sort(compareVersions).pop();
@@ -836,8 +702,7 @@ async function fetchAndroidVersion(business) {
836
702
  return ANDROID_VERSION_FALLBACK;
837
703
  }
838
704
 
839
- // Numeric, part by part: '2.26.9.75' is older than '2.26.29.73', which a
840
- // lexicographic sort gets backwards.
705
+ // Numeric compare, part by part ('2.26.9' < '2.26.29').
841
706
  function compareVersions(a, b) {
842
707
  const pa = String(a).split('.').map(Number);
843
708
  const pb = String(b).split('.').map(Number);
@@ -848,22 +713,10 @@ function compareVersions(a, b) {
848
713
  return 0;
849
714
  }
850
715
 
851
- // Return the appropriate WhatsApp version for the active device.
852
- // If WA_VERSION is set in the environment, that value is always used.
853
- //
854
- // On Android the APK the token material came from decides it: the versionName
855
- // of the APK that was downloaded. The token is signed over
856
- // that build's classes.dex, so a version read from anywhere else describes a
857
- // different build than the one the token proves — which the server sees as a
858
- // token that does not belong to the client sending it. The live lookup stays as
859
- // the fallback for when there is no material yet.
860
716
  /**
861
- * The version a device profile should be announcing right now, and where it
862
- * came from.
863
- *
864
- * Deliberately ignores WA_VERSION: this answers "what is current" so a stored
865
- * version can be brought up to date, and an override in the environment is the
866
- * opposite of that — it is what masks the session's own value at connect.
717
+ * The current version for a device profile, and its source. On Android it is
718
+ * the APK the token material came from (the token proves that build).
719
+ * Ignores WA_VERSION on purpose.
867
720
  *
868
721
  * @param {object} device the profile, for os and business
869
722
  * @returns {Promise<{version: string, source: string}>}
@@ -882,17 +735,8 @@ async function currentVersionFor(device) {
882
735
  }
883
736
 
884
737
  /**
885
- * Bring a session's stored version up to date.
886
- *
887
- * A session records the version it registered with and announces that forever
888
- * after; nothing else ever writes the field. Months later the server stops
889
- * accepting it and the connect is refused with a 405 that has nothing to do
890
- * with the account. Refreshing the APK material does not help on its own — it
891
- * updates the material, not the sessions already on disk. This is the part that
892
- * was missing.
893
- *
894
- * Touches `version` and nothing else. The device profile, the keys and the
895
- * registration are left exactly as they were.
738
+ * Update a session's stored version (an old one gets 405 on connect).
739
+ * Changes only `version`.
896
740
  *
897
741
  * @param {string} sessionFile path to <number>.json
898
742
  * @param {object} [opts] { version } to set one explicitly
@@ -913,12 +757,7 @@ async function refreshSessionVersion(sessionFile, opts) {
913
757
  ? { version: String(opts.version), source: 'the value you passed' }
914
758
  : await currentVersionFor(device);
915
759
 
916
- // Never go backwards on a lookup. The store the version is read from can be
917
- // behind what a session already holds — Play serves the build that matches
918
- // the device profile it was asked with, which is not always the newest one on
919
- // the listing — and moving a session to an older version is the one outcome
920
- // that makes a 405 more likely rather than less. A version named on the
921
- // command line is a decision, so that still applies either way.
760
+ // A looked-up version never goes backwards; an explicit one always applies.
922
761
  const olderThanStored = !explicit && !!before &&
923
762
  compareVersions(resolved.version, before) < 0;
924
763
 
@@ -954,48 +793,24 @@ async function fetchWaVersion(device) {
954
793
 
955
794
  // ---------- Token computation ----------
956
795
  //
957
- // The two platforms compute this differently, and only iOS derives it from a
958
- // static string:
959
- //
960
796
  // iOS MD5( staticToken + MD5hex(waVersion) + nationalNumber )
961
- // Android HMAC-SHA1, keyed by material taken out of the APK, over the
962
- // signing certificates, MD5(classes.dex) and the national number
963
- //
964
- // Android was being sent the iOS calculation with a different constant put in
965
- // front of it. No such constant exists — the Android client signs the token
966
- // with its own APK — and the server answered every attempt with bad_token. See
967
- // AndroidApk.js for the algorithm and where the material comes from.
797
+ // Android HMAC-SHA1 keyed from the APK, over the signing certs,
798
+ // MD5(classes.dex) and the national number (see AndroidApk.js)
968
799
  //
969
- // WA_STATIC_TOKEN therefore only means anything on iOS. It cannot substitute
970
- // for the Android material, so it is deliberately not consulted there.
971
-
972
- // Where the extracted Android material is kept. Beside the sessions by default,
973
- // since that is the directory the CLI already owns.
974
- // One file per package. The two builds are signed with different certificates
975
- // and carry a different classes.dex, so a token computed from the consumer APK
976
- // is not the token the Business endpoint expects — and the consumer file keeps
977
- // its original name, so nothing that already exists has to move.
800
+ // WA_STATIC_TOKEN applies to iOS only.
801
+
802
+ // Android material file, one per package (consumer / Business), in the session dir.
978
803
  function androidMaterialPath(device) {
979
804
  if (process.env.WA_ANDROID_APK_MATERIAL) return process.env.WA_ANDROID_APK_MATERIAL;
980
805
  const name = (device && device.business)
981
806
  ? 'android-apk-material-business.json'
982
807
  : 'android-apk-material.json';
983
808
 
984
- // The session directory, wherever it actually is — not a hardcoded
985
- // ~/.waSession. `wa apk-material` writes the file into the directory the CLI
986
- // resolved (--session, WA_SESSION_DIR, or the one remembered from the setup
987
- // prompt), while this read it from the home default and reported "no
988
- // material" for anything else. Anyone who moved their sessions had to set
989
- // WA_ANDROID_APK_MATERIAL by hand to make registration find a file that was
990
- // already there. SessionPaths.defaultBaseDir() is the same resolver the
991
- // writer goes through, and SHARED_FILES there already names both of these as
992
- // belonging to the base directory.
809
+ // Same resolver the writer (`wa apk-material`) uses.
993
810
  const { defaultBaseDir } = require('./SessionPaths');
994
811
  const primary = path.join(defaultBaseDir(), name);
995
812
 
996
- // Material extracted before the directory could be moved still sits in
997
- // ~/.waSession. If the configured directory has none but the old default
998
- // does, read that rather than claiming there is no material at all.
813
+ // Fall back to the legacy ~/.waSession copy.
999
814
  if (!fs.existsSync(primary)) {
1000
815
  const legacy = path.join(os.homedir(), '.waSession', name);
1001
816
  if (legacy !== primary && fs.existsSync(legacy)) return legacy;
@@ -1005,51 +820,15 @@ function androidMaterialPath(device) {
1005
820
 
1006
821
  const _androidMaterial = {};
1007
822
 
1008
- // The material if there is any, without insisting on it. fetchWaVersion asks
1009
- // this way: a missing file is the token's problem to report, not the version's.
823
+ // The material, or null if missing.
1010
824
  function tryLoadAndroidMaterial(device) {
1011
825
  try { return loadAndroidMaterial(device); } catch (_) { return null; }
1012
826
  }
1013
827
 
1014
- /**
1015
- * Which platform a registration speaks.
1016
- *
1017
- * Once a session has an account behind it, or has a code outstanding, its
1018
- * platform is settled: the account was created as that, the token and the
1019
- * User-Agent have to keep saying so, and re-reading WA_OS could only break it.
1020
- * A confirmation run from a shell without the variables must not flip to iOS
1021
- * halfway through.
1022
- *
1023
- * Before that, a session holds nothing but keys. Re-running the code request is
1024
- * how you start it over, and the environment is how you say what to start it
1025
- * over as — so the environment decides, and this stops being consulted the
1026
- * moment a code goes out.
1027
- *
1028
- * When the two disagree on a session that is settled, that is said out loud.
1029
- * Silently ignoring WA_OS is how you end up watching an Android registration go
1030
- * out under an iOS User-Agent and not knowing why.
1031
- */
1032
- // A session's device identity, frozen for the whole registration.
1033
- //
1034
- // createNewStore captures the device when the session is created and writes it
1035
- // to disk with everything else, so a session always arrives here already
1036
- // carrying one. From that point it is frozen: /exist, /code, /register and
1037
- // every retry read this same identity, and no request can describe one handset
1038
- // while a sibling request in the same flow describes another.
1039
- //
1040
- // The bug this closes: the gate here used to be `registered || codePending`, so
1041
- // the very first /code of a session ignored the stored device and re-read it
1042
- // from the environment. /exist had already gone out as the stored device — an
1043
- // Android/Samsung, say, loaded from the session file — and /code then went out
1044
- // as the environment default (iOS/iPhone). One number, two phones, in one flow.
1045
- // That is precisely the shape a "download the official app" block screen looks
1046
- // for, and it was reproducible from the logs. See
1047
- // test/registration-device-consistency.test.js.
1048
- //
1049
- // WA_OS / WA_BUSINESS therefore choose the device only for a session that does
1050
- // not have one yet — which in practice means never, since createNewStore always
1051
- // sets it. To change the platform of an existing session, start it over: delete
1052
- // the session file, and the next createNewStore picks up the current WA_OS.
828
+ // A session's device, frozen for the whole registration: /exist, /code,
829
+ // /register and retries all use the stored one, never a mix (see
830
+ // test/registration-device-consistency.test.js). WA_OS / WA_BUSINESS apply only
831
+ // to a session with no device; to switch, delete the session file. A mismatch is logged.
1053
832
  function deviceForRegistration(store, opts) {
1054
833
  const env = getDeviceConfig();
1055
834
  const stored = store && store.device;
@@ -1063,10 +842,7 @@ function deviceForRegistration(store, opts) {
1063
842
  'device. Delete the session file to start it over as ' + env.os + '.');
1064
843
  }
1065
844
 
1066
- // The same rule for the variant: an account is created as Business or as
1067
- // consumer, and the token, the User-Agent and the vname certificate all have
1068
- // to keep saying which. Flipping it halfway leaves a registration that no
1069
- // build can finish.
845
+ // Same rule for Business vs consumer.
1070
846
  if (!!stored.business !== !!env.business) {
1071
847
  say('note: this session was started as ' + (stored.business ? 'Business' : 'consumer') +
1072
848
  ', so it stays that — WA_BUSINESS=' + (env.business ? '1' : '0') +
@@ -1077,11 +853,7 @@ function deviceForRegistration(store, opts) {
1077
853
  return stored;
1078
854
  }
1079
855
 
1080
- // The device identity a request is about to go out with, logged so /exist and
1081
- // /code can be compared side by side. Gated behind the debug channel — it costs
1082
- // nothing when debug is off, and when a registration misbehaves it is the first
1083
- // thing worth seeing. The User-Agent is built the same way the real request
1084
- // builds it, so what this prints is what actually goes on the wire.
856
+ // Debug log of the device identity (and real User-Agent) a request goes out with.
1085
857
  function logDeviceIdentity(tag, store, waVersion) {
1086
858
  const stored = store && store.device;
1087
859
  const d = stored || getDeviceConfig();
@@ -1101,19 +873,9 @@ function logDeviceIdentity(tag, store, waVersion) {
1101
873
  }
1102
874
 
1103
875
  /**
1104
- * Have the Android token material ready, fetching the APK if it is not.
1105
- *
1106
- * Registering as Android cannot produce a token without material read out of a
1107
- * WhatsApp APK, and that material goes stale on every WhatsApp release. Asking
1108
- * the caller to go and find an APK first turns one command into a chore, so a
1109
- * registration that finds none fetches one from Play itself and carries on.
1110
- *
1111
- * Only a *missing* file is answered this way. An APK that turns out to be a
1112
- * repack is refused as it was before — downloading over somebody's deliberate
1113
- * choice of APK would be the wrong way to be helpful.
1114
- *
1115
- * A no-op on iOS, and WA_NO_APK_DOWNLOAD=1 turns it off for anyone who would
1116
- * rather a hundred megabytes were never fetched without being asked for.
876
+ * Ensure Android token material exists, downloading the APK from Play if it is
877
+ * missing (a repacked APK is still refused). No-op on iOS;
878
+ * WA_NO_APK_DOWNLOAD=1 disables the download.
1117
879
  */
1118
880
  async function ensureAndroidMaterial(opts, device) {
1119
881
  opts = opts || {};
@@ -1153,8 +915,7 @@ async function ensureAndroidMaterial(opts, device) {
1153
915
  fs.writeFileSync(file, JSON.stringify(AndroidApk.materialToJson(material), null, 2));
1154
916
  say(' token material written to ' + file);
1155
917
 
1156
- // Re-read it rather than using what is in hand, so the downloaded APK goes
1157
- // through the same signature check as one that was already on disk.
918
+ // Re-read so the download passes the same signature check.
1158
919
  _androidMaterial[variant] = null;
1159
920
  return loadAndroidMaterial(device);
1160
921
  }
@@ -1173,23 +934,14 @@ function loadAndroidMaterial(device) {
1173
934
  'or read it out of an APK you already have:\n' +
1174
935
  ' wa apk-material <base.apk> [split.apk ...]\n' +
1175
936
  'Registering as iOS needs none of this.', { statusCode: 404 });
1176
- // Told apart from a refused repack, which must never be answered by
1177
- // downloading over it.
937
+ // Distinct from a refused repack (never download over that).
1178
938
  err.code = 'NO_APK_MATERIAL';
1179
939
  throw err;
1180
940
  }
1181
941
  const material = AndroidApk.materialFromJson(JSON.parse(raw));
1182
942
 
1183
- // Refuse a repack before anything is sent.
1184
- //
1185
- // The token is an HMAC over the APK's signing certificates. An APK a mirror
1186
- // re-signed — commonly with the AOSP test key, whose private half ships in the
1187
- // Android sources — produces a well-formed token that belongs to nobody, and
1188
- // the server answers bad_token, exactly as it does when there is no material
1189
- // at all. Left to run, that spends /code attempts against a real phone number
1190
- // on a request that cannot succeed, and attempts are what gets a number rate
1191
- // limited. Checking the subject costs nothing and is the difference between a
1192
- // refusal here and a number burned.
943
+ // Refuse a re-signed APK up front: its token always gets bad_token and
944
+ // would only burn /code attempts on the number.
1193
945
  const signer = AndroidApk.describeCertificate(material.certificates[0]);
1194
946
  if (signer && !AndroidApk.looksLikeWhatsAppCertificate(signer) &&
1195
947
  process.env.WA_ALLOW_FOREIGN_APK !== '1') {
@@ -1210,8 +962,7 @@ function computeToken(waVersion, national, device) {
1210
962
  if (device.os === 'android') {
1211
963
  return AndroidApk.computeToken(loadAndroidMaterial(device), national);
1212
964
  }
1213
- // The Business build signs with its own constant. WA_STATIC_TOKEN still
1214
- // overrides either, for anyone who has a newer one than this ships with.
965
+ // Business has its own constant; WA_STATIC_TOKEN overrides both.
1215
966
  const staticToken = process.env.WA_STATIC_TOKEN ||
1216
967
  (device.business ? IOS_BUSINESS_STATIC_TOKEN : IOS_STATIC_TOKEN);
1217
968
  const versionHashHex = md5Bytes(waVersion).toString('hex');
@@ -1240,16 +991,11 @@ function toUrlHex(buf) {
1240
991
  }
1241
992
 
1242
993
  // ---------- Form builder — NO URL-encoding (matches Java toFormParams) ----------
1243
- // Java: entries[i] + "=" + entries[i+1], joined by "&", nulls skipped.
1244
- // IMPORTANT: do NOT use URLSearchParams here — it would double-encode the
1245
- // percent-hex sequences in the 'id' field (%AA → %25AA).
1246
-
1247
- // The native client inserts registration fields into a LinkedHashMap in a
1248
- // fixed order; the wire sequence is that insertion order, not a sort. These are
1249
- // the live orders captured from WhatsApp Android reverse engerring: 51 fields
1250
- // for /v2/code, 49 for /v2/register. gpia/token/vname that this build omits
1251
- // simply drop out — their slots collapse. first_api_level rides between
1252
- // e_skey_id and feo2_query_status, the slot the native client gives it.
994
+ // k=v joined by "&", nulls skipped. Not URLSearchParams: it would
995
+ // double-encode the %AA hex in 'id'.
996
+
997
+ // Native field order (LinkedHashMap insertion order) captured from Android:
998
+ // 51 fields for /v2/code, 49 for /v2/register. Missing fields just drop out.
1253
999
  const CODE_PARAM_ORDER = [
1254
1000
  'method', 'backup_token', '_gs', 'sim_mnc', 'id', 'mnc', '_gg',
1255
1001
  'network_radio_type', 'lg', 'rc', 'pid', '_ge', 'cellular_strength', 'gpia',
@@ -1273,12 +1019,8 @@ const REGISTER_PARAM_ORDER = [
1273
1019
  'e_skey_id', 'fdid', 'recaptcha', '_ga', 'lc'
1274
1020
  ];
1275
1021
 
1276
- // Reorder a flat [k, v, k, v, …] list to the native insertion order for the
1277
- // endpoint. Keys outside the reference order (push_token and any build-specific
1278
- // extras) keep their relative order and trail the known fields, so nothing is
1279
- // dropped. Only /v2/code and /v2/register have a reference order; every other
1280
- // endpoint (client_log, exist, …) and every non-Android device passes through
1281
- // untouched.
1022
+ // Reorder [k, v, …] to the native order for /code and /register (Android
1023
+ // only). Unknown keys keep their order and go last; nothing is dropped.
1282
1024
  function reorderRegistrationPairs(pairs, path, device) {
1283
1025
  const order = path === '/code' ? CODE_PARAM_ORDER
1284
1026
  : path === '/register' ? REGISTER_PARAM_ORDER
@@ -1317,9 +1059,7 @@ function buildForm(pairs, extraPairs) {
1317
1059
  }
1318
1060
 
1319
1061
  // ---------- access_session_id ----------
1320
- // 16 random bytes → URL-safe base64 without
1321
- // padding (a 22-char token). Generated once per store/session and reused on
1322
- // every attested endpoint, matching the native client.
1062
+ // 16 random bytes, URL-safe base64 without padding; one per session.
1323
1063
 
1324
1064
  function newAccessSessionId() {
1325
1065
  return crypto.randomBytes(16).toString('base64')
@@ -1332,22 +1072,10 @@ function getAccessSessionId(store) {
1332
1072
  }
1333
1073
 
1334
1074
  // ---------- /code verification-code parameters (per platform) ----------
1335
- // Returns the alternating name/value form fields the native client emits on a
1336
- // /code request. Android sends the long device-fingerprint list; iOS sends the
1337
- // short list. sim_mcc/sim_mnc/mcc/mnc carry real per-country values rather than
1338
- // a "000" placeholder, and advertising_id / backup_token come from the store.
1075
+ // Name/value pairs for /code: Android sends the long list, iOS the short one.
1339
1076
 
1340
- // How long the server said to wait, in seconds, or null when it did not say.
1341
- //
1342
- // The wait comes back in a field named after the delivery method, and there are
1343
- // seven of them. Reading only `sms_wait` meant a rate-limited voice or wa_old
1344
- // request reported no wait at all — which is the one number that matters in a
1345
- // `too_recent`, because without it the only advice left is "wait a few minutes"
1346
- // and people re-run the command instead, spending attempts and extending the
1347
- // very cooldown they are trying to get out of.
1348
- //
1349
- // The method's own field wins; the longest of the others is the fallback, since
1350
- // the server sometimes answers about a method other than the one asked for.
1077
+ // Server-requested wait in seconds, or null. The method's own *_wait field
1078
+ // wins, else the longest of the others, else retry_after.
1351
1079
  const WAIT_FIELDS = ['sms_wait', 'voice_wait', 'wa_old_wait', 'flash_wait',
1352
1080
  'email_otp_wait', 'send_sms_wait', 'silent_auth_wait'];
1353
1081
 
@@ -1369,19 +1097,8 @@ function waitHint(response, method) {
1369
1097
  }
1370
1098
 
1371
1099
  // ---------- device_ram ----------
1372
- //
1373
- // What the handset reports as usable RAM, in GiB, from
1374
- // ActivityManager.MemoryInfo.totalMem — which is always below the nominal
1375
- // figure on the box, because the kernel, the GPU and the secure world reserve a
1376
- // slice before Android ever sees it. A 12 GB phone reports around 11.5.
1377
- //
1378
- // This was the constant 3.57 on every request, while the same payload declared
1379
- // a Galaxy S24 Ultra beside it. There is no such handset: the S24 Ultra ships
1380
- // with 12 GB and no variant of it has ever had 3.57. Two fields of one request
1381
- // describing two different phones is not a fingerprint worth defending — it is
1382
- // simply wrong, in the way a wrong `os_version` would be. It now comes off the
1383
- // declared profile, so whichever handset the caller says they are on, the
1384
- // memory belongs to it.
1100
+ // Usable RAM in GiB (totalMem, below the nominal size: 12 GB → ~11.5), taken
1101
+ // from the device profile so it matches the declared phone.
1385
1102
  const DEFAULT_DEVICE_RAM = '5.62';
1386
1103
 
1387
1104
  function deviceRam(device) {
@@ -1393,16 +1110,8 @@ function deviceRam(device) {
1393
1110
  }
1394
1111
 
1395
1112
  // ---------- first_api_level ----------
1396
- //
1397
- // ro.product.first_api_level: the Android SDK the handset shipped with, which
1398
- // registration sends as first_api_level. It is a property of the model, not of
1399
- // the installed OS — a phone that launched on Android 13 and was updated to 14
1400
- // still reports 33 — so it is taken from the declared profile's firstApiLevel.
1401
- //
1402
- // When the profile does not pin one (a custom WA_DEVICE_* build), it is derived
1403
- // from osVersion: a phone is assumed to have shipped on the OS it now runs,
1404
- // which is true for anything bought on its launch version. The last resort is
1405
- // 34 (Android 14), the floor the default profiles sit on.
1113
+ // ro.product.first_api_level: the SDK the phone shipped with (not the current
1114
+ // OS). From the profile's firstApiLevel, else derived from osVersion, else 34.
1406
1115
  const ANDROID_VERSION_TO_API = {
1407
1116
  '10': 29, '11': 30, '12': 31, '13': 33, '14': 34, '15': 35, '16': 36
1408
1117
  };
@@ -1416,7 +1125,7 @@ function firstApiLevel(device) {
1416
1125
  }
1417
1126
  const osVersion = device && device.osVersion;
1418
1127
  if (osVersion != null) {
1419
- // Match on the major version so '14', '14.1' and '13.0' all resolve.
1128
+ // Major version only ('14.1' → '14').
1420
1129
  const major = String(osVersion).trim().split('.')[0];
1421
1130
  if (ANDROID_VERSION_TO_API[major] != null) {
1422
1131
  return String(ANDROID_VERSION_TO_API[major]);
@@ -1426,21 +1135,8 @@ function firstApiLevel(device) {
1426
1135
  }
1427
1136
 
1428
1137
  // ---------- pid ----------
1429
- //
1430
- // The process id of the app making the request.
1431
- //
1432
- // This sent `process.pid` — the Node process. Inside a container that is 1, and
1433
- // pid 1 on Android is `init`; no application process is ever 1. Elsewhere it is
1434
- // whatever the host happened to hand out, which is as likely to be 7 as 24000.
1435
- //
1436
- // Android hands out pids from a counter that starts near 300 and wraps at
1437
- // /proc/sys/kernel/pid_max, 32768 by default, so an app launched on a phone
1438
- // that has been up any length of time lands well inside that range. One is
1439
- // derived per store here, from the same identity material everything else in
1440
- // the payload comes from — deterministic on purpose, because /exist, /code and
1441
- // /register are three requests from one running app and a process does not
1442
- // change its pid between them. Restoring a saved session keeps the pid it had,
1443
- // for the same reason.
1138
+ // A realistic Android app pid, derived from the session identity so it stays
1139
+ // the same across /exist, /code and /register (not Node's process.pid).
1444
1140
  function getAppPid(store) {
1445
1141
  if (store._appPid) return store._appPid;
1446
1142
  const seed = (store.identityId && Buffer.isBuffer(store.identityId))
@@ -1453,14 +1149,9 @@ function getAppPid(store) {
1453
1149
  }
1454
1150
 
1455
1151
  // ---------- the install _gi describes ----------
1456
- //
1457
- // sourceDir is where Android put base.apk: two random 16-byte tags, each
1458
- // URL-safe base64 with padding, as PackageManager names them. did is the
1459
- // firmware: Build.ID, a dot, Build.VERSION.INCREMENTAL. Samsung's incremental
1460
- // is the model without "SM-", region XX, update type U, bootloader revision,
1461
- // major release, year (X = 2024) and month letters and a build digit; other
1462
- // vendors are given a numeric one. Both belong to one install, so they come
1463
- // from the session identity like pid and stay put across /code and /register.
1152
+ // sourceDir: base.apk path with two random 16-byte tags, as PackageManager
1153
+ // names it. did: Build.ID + "." + INCREMENTAL (Samsung-style for SM- models,
1154
+ // numeric otherwise). Both derived from the session identity, like pid.
1464
1155
  function getInstallIdentity(store, device, packageName) {
1465
1156
  const seed = (store.identityId && Buffer.isBuffer(store.identityId))
1466
1157
  ? store.identityId
@@ -1492,11 +1183,8 @@ function getInstallIdentity(store, device, packageName) {
1492
1183
  return { did: buildId + '.' + incremental, sourceDir };
1493
1184
  }
1494
1185
 
1495
- // Whether the request describes a phone with no SIM in it. The operator code
1496
- // is the tell: a real mcc means a card is present, a missing or all-zero mcc
1497
- // means none. Every SIM-shaped field (is_sim_absent here, sim_type/simnum and
1498
- // the operator fields in getRequestVerificationCodeParameters) reads it off
1499
- // this one test, so a request never says a SIM is both present and absent.
1186
+ // No SIM when mcc is missing or all zeros. Every SIM field uses this one test,
1187
+ // so a request never contradicts itself.
1500
1188
  function _simAbsent(meta) {
1501
1189
  const mcc = meta && meta.mcc != null ? String(meta.mcc).trim() : '';
1502
1190
  return !/^\d+$/.test(mcc) || /^0+$/.test(mcc);
@@ -1510,20 +1198,9 @@ function buildClientMetrics(attempt, meta) {
1510
1198
  return encodeURIComponent(json);
1511
1199
  }
1512
1200
 
1513
- // A note on `push_code`, because it looks like an omission and is not.
1514
- //
1515
- // It is not the field that makes silent push verification work. The code
1516
- // arrives over the push line *after* /code has been sent — that is the whole
1517
- // point of it — so a code cannot be in the request that asks for it. Filling
1518
- // this field by waiting for a push would hang /code forever on the push it is
1519
- // itself supposed to trigger. The working flow is the other shape entirely:
1520
- // open the MCS listener first, send /code, then await the push and hand what
1521
- // arrives to /register. That is what `receivePushCode` and `/reg push` do.
1522
- //
1523
- // So the field stays absent. An empty value is worse than no value: the server
1524
- // validates the shape of what it receives and answers a blank push_code with
1525
- // bad_param/bad_format naming that field, while a field that is not there is
1526
- // not validated at all. buildForm drops nulls, which is exactly what we want.
1201
+ // `push_code` is intentionally absent: the push code arrives after /code and is
1202
+ // sent on /register (see receivePushCode). An empty value would get bad_param,
1203
+ // so it stays null and buildForm drops it.
1527
1204
  function deviceAid(store) {
1528
1205
  const seed = (store.identityKeyPair && store.identityKeyPair.public)
1529
1206
  ? Buffer.from(store.identityKeyPair.public)
@@ -1533,19 +1210,9 @@ function deviceAid(store) {
1533
1210
 
1534
1211
  function getRequestVerificationCodeParameters(store, method, meta, device, attempt) {
1535
1212
  if (device && device.os === 'android') {
1536
- // Flash call is the one method whose delivery the server only routes when
1537
- // the client says it can observe an incoming call. The three fields below
1538
- // are that statement, and asking for `flash` while any of them still says
1539
- // otherwise gets the request answered with an SMS — or with no route at
1540
- // all. They stay at their headless-safe values for every other method.
1213
+ // Flash call is only routed when these three fields say the app can see calls.
1541
1214
  const wantsFlash = method === 'flash';
1542
- // One SIM story across every field. The operator codes decide it: a real
1543
- // mcc means a SIM is in the phone, so sim_type and simnum say "present" and
1544
- // the four operator fields carry the home network. A missing or all-zero
1545
- // mcc is a phone with no SIM, which reports "000" in all four and both SIM
1546
- // flags at 0 — the shape a device on Wi-Fi without a card actually sends.
1547
- // buildClientMetrics reads is_sim_absent off the same test, so the request
1548
- // never says a SIM is both there and not.
1215
+ // One SIM story: no SIM → "000" operator codes and SIM flags at 0.
1549
1216
  const simAbsent = _simAbsent(meta);
1550
1217
  const simMcc = simAbsent ? '000' : meta.mcc;
1551
1218
  const simMnc = simAbsent ? '000' : meta.mnc;
@@ -1600,11 +1267,7 @@ function getRequestVerificationCodeParameters(store, method, meta, device, attem
1600
1267
  }
1601
1268
 
1602
1269
  // ---------- /register device parameters (Android) ----------
1603
- //
1604
- // The Android app sends its device description again on /register, with the
1605
- // values it sent on /code, so they are taken from the /code list rather than
1606
- // restated. client_metrics is rebuilt: its attempt counter restarts at 0 on
1607
- // this screen.
1270
+ // Same values as on /code; client_metrics restarts its attempt counter at 0.
1608
1271
  const REGISTER_DEVICE_FIELDS = new Set([
1609
1272
  'backup_token', 'sim_mnc', 'device_ram', 'db', 'network_radio_type', 'pid',
1610
1273
  'cellular_strength', 'hasinrc', 'aid', 'mcc', 'mnc', 'sim_mcc',
@@ -1631,32 +1294,20 @@ function toBase64Url(buf) {
1631
1294
  return buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_');
1632
1295
  }
1633
1296
 
1634
- // The native client encodes the Signal-key and expid wire parameters with
1635
- // Base64.encodeToString(bytes, 11) = URL_SAFE | NO_WRAP | NO_PADDING: authkey
1636
- // (43 chars), e_ident/e_skey_val (43), e_skey_sig (86), e_regid (6), e_keytype,
1637
- // e_skey_id (4), expid (22) — never a trailing '='. The padded form still
1638
- // decodes server-side, but the bare '=' is a wire tell no real device emits.
1639
- // The ENC envelope and the vname certificate keep their own encoder above.
1297
+ // URL-safe base64 without padding, as the native client sends the Signal-key
1298
+ // fields and expid (Base64 flags 11). ENC and vname keep the padded form.
1640
1299
  function toBase64UrlNoPad(buf) {
1641
1300
  return toBase64Url(buf).replace(/=+$/, '');
1642
1301
  }
1643
1302
 
1644
1303
  // ---------- vname: the Business verified-name certificate ----------
1645
- //
1646
- // A Business registration carries one extra form field, `vname`, and a consumer
1647
- // one carries none. It is a VerifiedNameCertificate the client signs itself:
1304
+ // Business only. A self-signed VerifiedNameCertificate:
1648
1305
  //
1649
1306
  // Details { 1 serial (uint64), 2 issuer "smb:wa", 4 verifiedName "" }
1650
1307
  // Certificate { 1 details (the encoded Details), 2 signature }
1651
1308
  //
1652
- // The name is empty because there is nothing verified yet — WhatsApp issues the
1653
- // real one later, after the business is reviewed. What the server checks here is
1654
- // that the signature over the details is made with the identity key the same
1655
- // request registers, which ties the certificate to this account and no other.
1656
- //
1657
- // Written by hand rather than through the protobuf models: these two messages
1658
- // exist nowhere else in the library, and the encoder here is the same field/
1659
- // wire-type pair used everywhere else in proto.js.
1309
+ // Signed with the identity key being registered; the name stays empty until
1310
+ // WhatsApp verifies the business.
1660
1311
 
1661
1312
  const VNAME_ISSUER_SMALL_BUSINESS = 'smb:wa';
1662
1313
 
@@ -1685,9 +1336,7 @@ function _pbVarintField(fieldNum, value) {
1685
1336
  function buildVerifiedNameCertificate(store, device) {
1686
1337
  if (!device || !device.business) return null;
1687
1338
 
1688
- // A positive 63-bit serial: Java takes the absolute value of a random long,
1689
- // and Math.abs(Long.MIN_VALUE) is still negative there, so the top bit is
1690
- // simply never set here instead.
1339
+ // Positive 63-bit serial (top bit cleared).
1691
1340
  const serialBytes = crypto.randomBytes(8);
1692
1341
  serialBytes[0] &= 0x7f;
1693
1342
  const serial = serialBytes.readBigUInt64BE(0);
@@ -1698,8 +1347,7 @@ function buildVerifiedNameCertificate(store, device) {
1698
1347
  _pbLenField(4, Buffer.alloc(0)) // verifiedName: empty, not absent
1699
1348
  ]);
1700
1349
 
1701
- // Signed with the identity key, over the encoded details exactly as they go
1702
- // on the wire — the same XEdDSA signature the signed pre-key uses.
1350
+ // XEdDSA over the encoded details, with the identity key.
1703
1351
  const signature = Buffer.from(
1704
1352
  curveJs.sign(store.identityKeyPair.private, details));
1705
1353
 
@@ -1719,25 +1367,14 @@ async function buildPayload(store, waVersion, useToken, extraPairs, path) {
1719
1367
  ? store.fdid.toLowerCase()
1720
1368
  : store.fdid.toUpperCase();
1721
1369
 
1722
- // Device-attestation fields shipped on every attested endpoint.
1723
- // Empty by default (NONE fallback); populated when a
1724
- // Frida attestation server is configured via WA_FRIDA_HOST. The Play
1725
- // Integrity nonce is a stable per-session value derived from the store.
1370
+ // Attestation fields: empty unless WA_FRIDA_HOST is set. Stable per-session nonce.
1726
1371
  const nonceB64 = attestation.toBase64Url(
1727
1372
  crypto.createHash('sha256')
1728
1373
  .update(Buffer.concat([store.identityId, stripKeyPrefix(store.noiseKeyPair.public)]))
1729
1374
  .digest()
1730
1375
  );
1731
- // The push token a real install always has, taken from the transport that
1732
- // matches this device's platform: Firebase for Android, APNs for iOS. Asking
1733
- // ./fcm directly would put a Google token in an iPhone's registration body —
1734
- // a device that keeps an MCS stream to Google and announces itself as iOS is
1735
- // not a device anyone ships.
1736
- //
1737
- // Acquired once and cached on the store, so the two registration steps share
1738
- // one. Returns null on any failure or on a platform with no transport, which
1739
- // drops the field and leaves the body exactly as it was before push tokens
1740
- // were wired up.
1376
+ // Push token from the platform's own transport (FCM / APNs), cached on the
1377
+ // store; null on failure, which just drops the field.
1741
1378
  const pushToken = await pushClientFor(device).getPushToken(store, device);
1742
1379
 
1743
1380
  const authKeyRaw = stripKeyPrefix(store.noiseKeyPair.public);
@@ -1761,8 +1398,7 @@ async function buildPayload(store, waVersion, useToken, extraPairs, path) {
1761
1398
  'lg', meta.lg,
1762
1399
  'lc', meta.lc,
1763
1400
  'authkey', toBase64UrlNoPad(stripKeyPrefix(store.noiseKeyPair.public)),
1764
- // Business only; buildForm drops a null, so a consumer registration sends
1765
- // the same body it always has.
1401
+ // Business only (null is dropped).
1766
1402
  'vname', buildVerifiedNameCertificate(store, device),
1767
1403
  'e_regid', toBase64UrlNoPad(intToBytes(store.registrationId, 4)),
1768
1404
  'e_keytype', toBase64UrlNoPad(Buffer.from([SIGNAL_KEY_TYPE])),
@@ -1778,9 +1414,7 @@ async function buildPayload(store, waVersion, useToken, extraPairs, path) {
1778
1414
  ...attestFields
1779
1415
  ];
1780
1416
  const allPairs = extraPairs ? basePairs.concat(extraPairs) : basePairs;
1781
- // Emit the fields in the native client's fixed insertion order for /code and
1782
- // /register. The order is part of the wire fingerprint and, with the query
1783
- // now mirrored into the URL, is visible to the server in the clear.
1417
+ // Native field order for /code and /register (part of the fingerprint).
1784
1418
  return buildForm(reorderRegistrationPairs(allPairs, path, device));
1785
1419
  }
1786
1420
 
@@ -1811,12 +1445,9 @@ function httpPost(path, body, waVersion, authHeader, device, query) {
1811
1445
  registrationHeaders(device || getDeviceConfig(), waVersion),
1812
1446
  { 'Content-Length': bodyBuf.length }
1813
1447
  );
1814
- // Attestation cert-chain / App Attest header (Android cert chain, iOS
1815
- // <attestation>|<keyId>). Only present when body attestation is available.
1448
+ // Attestation header, only when available.
1816
1449
  if (authHeader) headers['Authorization'] = authHeader;
1817
- // The native client submits the parameters twice: once in the clear as the
1818
- // URL query, once encrypted inside ENC. The query is the exact ENC
1819
- // plaintext, byte for byte.
1450
+ // Params go both as the URL query and encrypted in ENC.
1820
1451
  const opts = {
1821
1452
  hostname: 'v.whatsapp.net',
1822
1453
  port: 443,
@@ -1854,22 +1485,12 @@ async function sendRequest(path, store, waVersion, useToken, extraPairs) {
1854
1485
  return sendEncrypted(path, plaintext, store, waVersion);
1855
1486
  }
1856
1487
 
1857
- /**
1858
- * Encrypt an already-built form body and post it.
1859
- *
1860
- * The attested endpoints reach this through sendRequest, which assembles the
1861
- * shared registration fields first. The funnel endpoints build their own much
1862
- * shorter body and come straight here — the native client sends no registration
1863
- * fields with a client log, only the identifiers and the screen names.
1864
- */
1488
+ /** Encrypt a built form body and post it (funnel endpoints call this directly). */
1865
1489
  async function sendEncrypted(path, plaintext, store, waVersion) {
1866
1490
  const enc = encryptPayload(plaintext); // base64url ENC payload (no prefix)
1867
1491
  let body = 'ENC=' + enc;
1868
1492
 
1869
- // Body attestation over the ENC payload: Android appends a hex Keystore
1870
- // signature as &H= and a cert-chain Authorization header; iOS appends the
1871
- // App Attest assertion as &H= and an <attestation>|<keyId> Authorization
1872
- // header. Both are empty (skipped) unless a Frida server is configured.
1493
+ // Body attestation (&H= plus an Authorization header); skipped unless Frida is configured.
1873
1494
  const device = store.device || getDeviceConfig();
1874
1495
  const bodyAtt = await attestation.attestBody(enc, device, {
1875
1496
  noisePubB64: stripKeyPrefix(store.noiseKeyPair.public).toString('base64')
@@ -1878,11 +1499,7 @@ async function sendEncrypted(path, plaintext, store, waVersion) {
1878
1499
 
1879
1500
  _whaDbg('[DBG] REG → ' + path + ' (' + body.length + ' bytes' +
1880
1501
  (bodyAtt.bodyAttestation ? ', attested' : '') + ')');
1881
- // The ENC plaintext is also the URL query: the native client submits every
1882
- // parameter twice, in the clear and encrypted, byte for byte identical. This
1883
- // is documented and verified only for the Android /code and /register
1884
- // requests, so the mirror is scoped to them; iOS and the funnel endpoints
1885
- // keep posting to a bare path, exactly as before.
1502
+ // Mirror the plaintext into the URL query, only for Android /code and /register.
1886
1503
  const mirrorQuery = device.os === 'android' && (path === '/code' || path === '/register');
1887
1504
  const result = await httpPost(path, body, waVersion, bodyAtt.authorizationHeader, device,
1888
1505
  mirrorQuery ? plaintext : undefined);
@@ -1894,24 +1511,14 @@ async function sendEncrypted(path, plaintext, store, waVersion) {
1894
1511
 
1895
1512
  // ---------- Pacing ----------
1896
1513
  //
1897
- // The funnel events say a person walked through the screens. The timestamps on
1898
- // them said otherwise: session_start, the number lookup and the code request
1899
- // left within a few milliseconds of each other, because nothing in between was
1900
- // waiting on a person. Nobody opens WhatsApp and has a phone number typed,
1901
- // checked and submitted inside one millisecond, and that gap is visible to the
1902
- // server on every event it receives.
1903
- //
1904
- // So the waits a person actually causes are put back. Each one is a range
1905
- // rather than a number — a fixed delay is its own signature — and each is
1906
- // named after the thing being waited for:
1514
+ // Random human-like pauses between steps (a range, never a fixed delay):
1907
1515
  //
1908
1516
  // enter_number typing the number in before the lookup fires
1909
1517
  // confirm_number the "is this your number?" sheet, and tapping through it
1910
1518
  // retry_code after a refused request, before asking again
1911
1519
  // switch_method picking a different delivery method out of the list
1912
1520
  //
1913
- // Set WA_REG_PACING=0 to drop all of it, for anything that wants the request
1914
- // shapes without the waiting.
1521
+ // WA_REG_PACING=0 disables them.
1915
1522
  const PACING_RANGES_MS = {
1916
1523
  enter_number: [1800, 5200],
1917
1524
  confirm_number: [1200, 3600],
@@ -1932,24 +1539,14 @@ function humanPause(kind) {
1932
1539
  }
1933
1540
 
1934
1541
  // ---------- Funnel telemetry ----------
1935
- //
1936
- // The native client reports every screen it moves through — the number entry,
1937
- // the code request, the code submission, a captcha appearing, a PIN prompt —
1938
- // to /client_log, and one session-start event to /pre_pn_client_log before the
1939
- // number is even known. A client that registers without any of that is doing
1940
- // something no real installation does.
1941
- //
1942
- // It is fire-and-forget by design. Every failure is swallowed: telemetry that
1943
- // can abort a registration is worse than no telemetry. Set WA_FUNNEL_LOG=0 to
1944
- // send none of it.
1542
+ // Screen events to /client_log (and /pre_pn_client_log before the number), as
1543
+ // the native client sends. Fire-and-forget; WA_FUNNEL_LOG=0 disables it.
1945
1544
 
1946
1545
  function funnelEnabled() {
1947
1546
  return process.env.WA_FUNNEL_LOG !== '0';
1948
1547
  }
1949
1548
 
1950
- // The screen a verification event belongs to, named after the method that was
1951
- // asked for — verify_sms, verify_voice. Before any request there is only the
1952
- // number entry screen.
1549
+ // verify_<method>, or enter_number before any request.
1953
1550
  function currentVerifyScreen(store) {
1954
1551
  return store._lastRequestedMethod ? 'verify_' + store._lastRequestedMethod : 'enter_number';
1955
1552
  }
@@ -1987,8 +1584,7 @@ async function sendFunnelLog(store, waVersion, currentScreen, actionTaken, event
1987
1584
  }
1988
1585
  }
1989
1586
 
1990
- // The one event that fires before a phone number is committed, so it carries
1991
- // neither cc nor in.
1587
+ // Fires before the number is known, so no cc / in.
1992
1588
  async function sendPrePnFunnelLog(store, waVersion, actionTaken, eventName) {
1993
1589
  if (!funnelEnabled()) return;
1994
1590
  try {
@@ -2033,12 +1629,7 @@ function is2FARequired(response) {
2033
1629
  return r === '2fa_required' || r === 'security_code' || r === 'two_factor_required';
2034
1630
  }
2035
1631
 
2036
- /**
2037
- * Decode a blob defensively.
2038
- *
2039
- * The server has been seen to switch between the standard and URL-safe base64
2040
- * alphabets between releases, so both are tried before giving up.
2041
- */
1632
+ /** Decode base64 or base64url (the server has used both); null if empty. */
2042
1633
  function decodeOrNull(b64) {
2043
1634
  if (!b64) return null;
2044
1635
  const str = String(b64);
@@ -2060,21 +1651,8 @@ function normalizeCodeResult(code) {
2060
1651
  return String(code == null ? '' : code).replace(/[\s\-]/g, '').replace(/\D/g, '');
2061
1652
  }
2062
1653
 
2063
- // A flash call carries no code of its own: WhatsApp rings the number from a
2064
- // one-time caller ID and drops the call, and the verification code IS that
2065
- // number — its trailing digits. The official Android app reads them out of the
2066
- // call log, which is a thing no server-side client has; here the person holding
2067
- // the handset reads the missed call instead and types what they see.
2068
- //
2069
- // So whatever arrives has to be reduced to those digits. Someone reading a
2070
- // missed call types it however their phone showed it — "+40 21 555 123456",
2071
- // "0040...", or already just the last six — and all three have to land on the
2072
- // same code. Digits are taken first, then the tail: a full number is longer
2073
- // than the code, and its END is the part the server compares.
2074
- //
2075
- // Six is what the decompiled app defaults to. Flash-call providers vary between
2076
- // four and six, so it is overridable rather than baked in, for the number whose
2077
- // server wants a different length.
1654
+ // Flash call: the code is the trailing digits of the missed call's number,
1655
+ // typed by the user in any format. Default length 6 (WA_FLASH_CODE_LEN overrides).
2078
1656
  const FLASH_CODE_LENGTH = 6;
2079
1657
 
2080
1658
  function flashCodeLength() {
@@ -2082,27 +1660,15 @@ function flashCodeLength() {
2082
1660
  return raw > 0 ? raw : FLASH_CODE_LENGTH;
2083
1661
  }
2084
1662
 
2085
- // The server's own rule for pulling the code out of the number that rang.
2086
- //
2087
- // The /code reply for a flash call carries cli_filter — a regex such as
2088
- // "(.*)373(.*)" — alongside cli_prefix and the code length. The code is the
2089
- // part the filter isolates after the prefix: for a caller id "393739799312"
2090
- // the filter's trailing group is "9799312", and the code is its last `length`
2091
- // digits. Applying this is the whole fix for a flash "mismatch" on a correctly
2092
- // read number — the national part of an Italian +39 373 XXXXXXX caller id has
2093
- // more digits after the prefix than the six-digit code, so the old assumption
2094
- // that the code was simply the last six digits took the wrong slice.
2095
- //
2096
- // Returns null when there is no filter, it does not compile, or it does not
2097
- // match, so the caller can fall back to the plain last-`length` behaviour.
1663
+ // Apply the server's cli_filter regex (e.g. "(.*)373(.*)") and return the last
1664
+ // group with digits; null if missing, invalid or no match.
2098
1665
  function applyFlashFilter(digits, filter) {
2099
1666
  if (!filter) return null;
2100
1667
  let re;
2101
1668
  try { re = new RegExp(String(filter)); } catch (_) { return null; }
2102
1669
  const m = re.exec(digits);
2103
1670
  if (!m) return null;
2104
- // The code follows the prefix, so it is the last capture group that has any
2105
- // digits in it; earlier groups hold the country code and prefix.
1671
+ // Last group with digits.
2106
1672
  for (let i = m.length - 1; i >= 1; i--) {
2107
1673
  const g = m[i] && m[i].replace(/\D/g, '');
2108
1674
  if (g) return g;
@@ -2110,10 +1676,7 @@ function applyFlashFilter(digits, filter) {
2110
1676
  return null;
2111
1677
  }
2112
1678
 
2113
- // `opts` may be a bare length (the historical signature) or
2114
- // { length, filter }. The filter, when it matches, decides which digits are the
2115
- // code; the length then trims them. Without a filter this is the old behaviour:
2116
- // the last `length` digits of whatever was typed.
1679
+ // `opts`: a length or { length, filter }. Filter picks the digits, length trims them.
2117
1680
  function flashCodeFromCallerId(input, opts) {
2118
1681
  const digits = normalizeCodeResult(input);
2119
1682
  const o = (opts && typeof opts === 'object') ? opts : { length: opts };
@@ -2122,44 +1685,30 @@ function flashCodeFromCallerId(input, opts) {
2122
1685
  const filtered = applyFlashFilter(digits, o.filter);
2123
1686
  const base = (filtered && filtered.length) ? filtered : digits;
2124
1687
 
2125
- // Shorter than the code means the caller already typed just the tail (or the
2126
- // handset showed a short number); there is nothing to trim and guessing would
2127
- // only corrupt it.
1688
+ // Already short enough: leave it.
2128
1689
  return base.length > want ? base.slice(-want) : base;
2129
1690
  }
2130
1691
 
2131
- // The digits /register is given, for whichever method the pending code came by.
2132
- // Split out so the choice can be tested on its own: it is the whole difference
2133
- // between confirming a flash call and confirming anything else, and it runs at
2134
- // a point in verifyCode that a test cannot otherwise reach without a network.
2135
- //
2136
- // The method is read off the session because the request and the confirmation
2137
- // are usually two separate commands; opts.method overrides it for a caller that
2138
- // knows better, or for a session saved before the field existed.
1692
+ // The code /register receives; flash calls get their digits extracted.
1693
+ // The method comes from the session (opts.method overrides).
2139
1694
  function codeForSubmission(store, code, opts) {
2140
1695
  const pending = String(
2141
1696
  (opts && opts.method) || (store && store.codeMethod) || ''
2142
1697
  ).toLowerCase();
2143
1698
  if (pending !== 'flash') return normalizeCodeResult(code);
2144
1699
 
2145
- // Length: an explicit WA_FLASH_CODE_LEN / opts.flashCodeLen wins, else the
2146
- // length the server named in its /code reply (captured as store.flashCodeLength),
2147
- // else the six-digit default inside flashCodeFromCallerId.
1700
+ // Length: env, then opts, then the server's value, then the default.
2148
1701
  const envLen = parseInt(process.env.WA_FLASH_CODE_LEN, 10);
2149
1702
  const length = envLen > 0 ? envLen
2150
1703
  : (opts && Number(opts.flashCodeLen) > 0 ? Number(opts.flashCodeLen)
2151
1704
  : (store && Number(store.flashCodeLength) > 0 ? Number(store.flashCodeLength) : 0));
2152
- // Filter: the server's cli_filter from the /code reply, isolating the code
2153
- // after the prefix. opts.flashFilter lets a caller state it outright.
1705
+ // Filter: opts.flashFilter or the server's cli_filter.
2154
1706
  const filter = (opts && opts.flashFilter) || (store && store.flashCliFilter) || null;
2155
1707
 
2156
1708
  return flashCodeFromCallerId(code, { length, filter });
2157
1709
  }
2158
1710
 
2159
- // Take the digits the server filed the account under. Brazilian mobiles are the
2160
- // standing example: they gained a ninth digit WhatsApp never adopted, and a
2161
- // session saved under the typed number sends a username on every connection
2162
- // that matches no registration.
1711
+ // Use the number the server registered (e.g. Brazil's extra ninth digit differs).
2163
1712
  function adoptCanonicalNumber(store, result) {
2164
1713
  const canonical = result.login ? String(result.login).replace(/\D/g, '') : null;
2165
1714
  if (canonical && canonical !== String(store.phoneNumber)) {
@@ -2171,12 +1720,8 @@ function adoptCanonicalNumber(store, result) {
2171
1720
  }
2172
1721
 
2173
1722
  /**
2174
- * Answer a captcha, and keep answering while the server keeps asking.
2175
- *
2176
- * A wrong answer is replied to with another challenge rather than a refusal,
2177
- * which is why this loops. Solving needs a caller that can show the image to
2178
- * somebody: without one there is nothing to do but say so, and hand the blobs
2179
- * over on the error so it can be dealt with elsewhere.
1723
+ * Solve captchas until the server stops asking (a wrong answer brings a new
1724
+ * one). Without a solveCaptcha handler it throws with the blobs attached.
2180
1725
  */
2181
1726
  async function handleChallenge(store, waVersion, initial, opts) {
2182
1727
  const screen = currentVerifyScreen(store);
@@ -2228,12 +1773,7 @@ async function handleChallenge(store, waVersion, initial, opts) {
2228
1773
  }
2229
1774
  }
2230
1775
 
2231
- /**
2232
- * Supply the two-step verification PIN the account has set.
2233
- *
2234
- * This is the account owner's own PIN, not anything the library can work out —
2235
- * without a handler to ask, the registration stops here.
2236
- */
1776
+ /** Submit the account's two-step PIN; throws without a twoFactorPin handler. */
2237
1777
  async function handle2FA(store, waVersion, opts) {
2238
1778
  await sendFunnelLog(store, waVersion, 'verify_twofac', 'twofac_shown', 'twofac_prompt_shown');
2239
1779
 
@@ -2275,20 +1815,11 @@ async function checkIfRegistered(store) {
2275
1815
  }
2276
1816
 
2277
1817
  /**
2278
- * Comprehensive check: determine if a phone number is active on WhatsApp.
2279
- * Does NOT require a pre-existing session. Uses an ephemeral store.
1818
+ * Is a number active on WhatsApp? Uses an ephemeral store.
2280
1819
  *
2281
- * Strategy:
2282
- * 1. /exist — fast; returns 'ok' if the number owns a session on this device.
2283
- * 2. /code wa_old — WhatsApp-to-WhatsApp delivery; non-intrusive for non-WA numbers.
2284
- * · sent → number IS on WhatsApp (received code via WA message)
2285
- * · custom_block_screen → IS on WhatsApp but banned from third-party clients
2286
- * · fail (no block) → not on WA or IP-level block; go to step 3
2287
- * 3. /code sms — only reached when wa_old was inconclusive.
2288
- * · sent → NOT on WhatsApp (can be registered; SMS code was delivered)
2289
- * · custom_block_screen → IS on WhatsApp but banned from third-party clients
2290
- * · too_recent → code already sent; wait 1-2 min
2291
- * · fail → likely datacenter IP block; status unknown
1820
+ * 1. /exist — 'ok' means registered.
1821
+ * 2. /code wa_old — sent → on WhatsApp; block screen → banned; else step 3.
1822
+ * 3. /code sms — sent → not on WhatsApp; too_recent → cooldown; fail → unknown.
2292
1823
  *
2293
1824
  * Returns:
2294
1825
  * { active: bool|null, usable: bool|null, status: string, note: string }
@@ -2374,13 +1905,11 @@ async function checkNumberStatus(phoneNumber) {
2374
1905
  }
2375
1906
 
2376
1907
  // ---------- assertRegistrationKeys ----------
2377
- // Makes up to two /exist attempts before giving up.
2378
- // Returns true → keys are fresh (safe to proceed with /code).
2379
- // Returns false → keys already registered (generate new store before /code).
1908
+ // Up to two /exist attempts. true → keys are fresh; false → already registered.
2380
1909
  async function assertRegistrationKeys(store, waVersion) {
2381
- // The session-start event the native client fires before it knows the number.
1910
+ // Session-start event (before the number is known).
2382
1911
  await sendPrePnFunnelLog(store, waVersion, 'session_start', 'registration_session_start');
2383
- // The number gets typed between those two events.
1912
+ // Typing the number.
2384
1913
  await humanPause('enter_number');
2385
1914
  await sendFunnelLog(store, waVersion, 'enter_number', 'exist_check', 'exist_attempt');
2386
1915
 
@@ -2409,14 +1938,10 @@ async function assertRegistrationKeys(store, waVersion) {
2409
1938
  return false;
2410
1939
  }
2411
1940
 
2412
- // The retry policy below is "unknown error once, then give up", so this only
2413
- // bites when the server keeps answering with a different reason each time.
1941
+ // Cap for a server that answers with a different reason every time.
2414
1942
  const MAX_CODE_REQUEST_ATTEMPTS = 5;
2415
1943
 
2416
- // The display name a registration is carrying, if the caller gave one. It is
2417
- // never sent to the registration endpoints — those take no name, and adding one
2418
- // would be inventing a field. It is written to the session, and the handshake
2419
- // on the first connection is what announces it.
1944
+ // Save opts.name to the session; it is announced on first connect, not sent here.
2420
1945
  function applyRegistrationName(store, opts) {
2421
1946
  if (!store || !opts || opts.name === undefined || opts.name === null) return;
2422
1947
  const { normalizePushName } = require('./Store');
@@ -2432,19 +1957,14 @@ async function requestSmsCode(store, method, opts) {
2432
1957
  method = method || 'sms';
2433
1958
  opts = opts || {};
2434
1959
  applyRegistrationName(store, opts);
2435
- // Before the version is read, since on Android the version comes out of the
2436
- // APK this fetches.
1960
+ // Before reading the version: on Android it comes from this APK.
2437
1961
  const _device = deviceForRegistration(store, opts);
2438
1962
  await ensureAndroidMaterial(opts, _device);
2439
1963
  const waVersion = await fetchWaVersion(_device);
2440
1964
  store.version = waVersion;
2441
1965
  store.device = _device;
2442
1966
 
2443
- // Flash exists on Android and nowhere else. iOS has no public way to read an
2444
- // incoming call's number, so the platform never offers the method and asking
2445
- // for it as iOS is answered with an ordinary SMS at best. Refusing here costs
2446
- // nothing; letting it through spends one of the number's attempts to learn
2447
- // the same thing from the server.
1967
+ // Flash is Android-only; refuse early instead of wasting an attempt.
2448
1968
  if (method === 'flash' && !(_device && _device.os === 'android')) {
2449
1969
  throw new Boom(
2450
1970
  'Flash call verification is Android-only — iOS has no API for reading an ' +
@@ -2467,24 +1987,17 @@ async function requestSmsCode(store, method, opts) {
2467
1987
  const _regMeta = getCountryMeta(_regCc, store);
2468
1988
 
2469
1989
  async function _tryMethod(m) {
2470
- // Retry loop:
2471
- // 1. Try /code
2472
- // 2. Success → return result
2473
- // 3. too_recent/too_many → throw immediately
2474
- // 4. no_routes → return null (caller handles fallback)
2475
- // 5. custom_block_screen → throw with IP hint
2476
- // 6. Same error twice → throw to break loop
2477
- // 7. Unknown error first time → retry once
1990
+ // Retry loop: success → return; too_recent → throw; no_routes → let the
1991
+ // caller fall back; block screen → throw; same error twice → throw; else retry.
2478
1992
  let lastReason = null;
2479
1993
  let attemptNum = 1;
2480
- // The confirmation sheet the app puts up before it will ask for a code.
1994
+ // "Is this your number?" sheet.
2481
1995
  await humanPause('confirm_number');
2482
1996
  while (true) {
2483
- // Rebuilt per attempt so client_metrics carries the current attempt count.
1997
+ // Rebuilt per attempt (client_metrics attempt count).
2484
1998
  const extra = getRequestVerificationCodeParameters(store, m, _regMeta, _device, attemptNum);
2485
1999
 
2486
- // The screen a later event belongs to is named after the method asked
2487
- // for here, so record it before the request rather than after.
2000
+ // Record the method first: later events are named after it.
2488
2001
  store._lastRequestedMethod = m;
2489
2002
  const verifyScreen = currentVerifyScreen(store);
2490
2003
  await sendFunnelLog(store, waVersion, verifyScreen, 'request_code', 'request_code_attempt');
@@ -2494,20 +2007,11 @@ async function requestSmsCode(store, method, opts) {
2494
2007
 
2495
2008
  const status = result.status;
2496
2009
  if (status === 'ok' || status === 'sent') {
2497
- // Which method actually went through, not which one was asked for: a
2498
- // flash request that fell back to SMS leaves a code in an SMS, and
2499
- // confirming it as flash would take the last six digits of a six-digit
2500
- // code — right by accident here, wrong the moment the lengths differ.
2501
- // The confirmation step is usually a separate command, so this is
2502
- // written to the session rather than kept in memory.
2010
+ // Save the method that actually worked (confirmation runs separately).
2503
2011
  store.codeMethod = m;
2504
2012
 
2505
- // A flash /code reply states exactly how to read the code out of the
2506
- // number that will ring: cli_filter is a regex isolating the code after
2507
- // cli_prefix, and `length` is how many digits it is. Confirmation is
2508
- // usually a separate command, so these are written to the session for
2509
- // codeForSubmission to use rather than kept in memory. flash_timeout is
2510
- // the window the call is valid for, carried so the CLI can warn.
2013
+ // Save the flash reply's cli_filter / prefix / length / timeout for
2014
+ // codeForSubmission and the CLI.
2511
2015
  if (m === 'flash') {
2512
2016
  const srvLen = Number(result.length);
2513
2017
  store.flashCliFilter = result.cli_filter || null;
@@ -2528,7 +2032,7 @@ async function requestSmsCode(store, method, opts) {
2528
2032
 
2529
2033
  const reason = result.reason || status || '';
2530
2034
 
2531
- // isTooRecent() — throw immediately, no point retrying
2035
+ // Too recent / too many: no point retrying.
2532
2036
  if (/too_recent|too_many|too_many_guesses|too_many_all_methods/i.test(reason) ||
2533
2037
  /too_recent|too_many|too_many_guesses|too_many_all_methods/i.test(status)) {
2534
2038
  const waitSec = waitHint(result, m);
@@ -2536,20 +2040,18 @@ async function requestSmsCode(store, method, opts) {
2536
2040
  throw new Boom(`code already sent recently — check your phone or wait a few minutes (${reason})${waitMsg}`, { statusCode: 429 });
2537
2041
  }
2538
2042
 
2539
- // isRegistrationBlocked() — no_routes: signal to try alternate method
2043
+ // no_routes: let the caller try another method.
2540
2044
  if (reason === 'no_routes' || status === 'no_routes') {
2541
2045
  return { _noRoutes: true, method: m };
2542
2046
  }
2543
2047
 
2544
- // custom_block_screen = WhatsApp security block (IP/number flagged)
2048
+ // Security block (IP or number flagged).
2545
2049
  if (result.custom_block_screen) {
2546
2050
  const body = result.custom_block_screen.body || 'blocked by WhatsApp security';
2547
2051
  throw new Boom(`WhatsApp security block: "${body}" — use a residential IP/proxy`, { statusCode: 403 });
2548
2052
  }
2549
2053
 
2550
- // Same error twice in a row → give up. Compared even when the reason is
2551
- // empty: a 200 carrying a non-JSON body leaves both status and reason
2552
- // undefined, and skipping those would retry a real /code request forever.
2054
+ // Same error twice → give up (empty reasons count too).
2553
2055
  if (reason === lastReason) {
2554
2056
  throw new Boom(`Registration error (${m}): ${reason || 'no status in response'} — raw: ${JSON.stringify(result)}`, { statusCode: 502 });
2555
2057
  }
@@ -2558,13 +2060,12 @@ async function requestSmsCode(store, method, opts) {
2558
2060
  lastReason = reason;
2559
2061
  attemptNum++;
2560
2062
 
2561
- // A server answering with a different reason every time would otherwise
2562
- // keep this loop going indefinitely.
2063
+ // Hard cap on attempts.
2563
2064
  if (attemptNum > MAX_CODE_REQUEST_ATTEMPTS) {
2564
2065
  throw new Boom(`Registration error (${m}): giving up after ${MAX_CODE_REQUEST_ATTEMPTS} attempts — raw: ${JSON.stringify(result)}`, { statusCode: 502 });
2565
2066
  }
2566
2067
 
2567
- // Nobody re-taps the button the instant the error lands.
2068
+ // Human pause before retrying.
2568
2069
  await humanPause('retry_code');
2569
2070
  }
2570
2071
  }
@@ -2576,18 +2077,13 @@ async function requestSmsCode(store, method, opts) {
2576
2077
  if (result && result._noRoutes && !autoFallbackDone) {
2577
2078
  autoFallbackDone = true;
2578
2079
  process.stderr.write(`[REG] ${method} returned no_routes — auto-trying ${fallbackMethod}\n`);
2579
- // Reading the refusal and picking another method off the list.
2080
+ // Human pause before switching method.
2580
2081
  await humanPause('switch_method');
2581
2082
  result = await _tryMethod(fallbackMethod);
2582
2083
  }
2583
2084
 
2584
- // Final no_routes — give up, and say what actually changes the answer.
2585
- //
2586
- // no_routes is the server declining to deliver, and what it weighs is the
2587
- // requester: the reputation of the IP, the history the number carries, and
2588
- // whether the platform has a route for it. None of that is in the client, so
2589
- // the advice has to point outside it. The old text suggested a VoIP number,
2590
- // which is backwards — virtual numbers are among the most refused.
2085
+ // Still no_routes: the server judges the IP, the number and the platform, so
2086
+ // the advice points there.
2591
2087
  if (result && result._noRoutes) {
2592
2088
  const tried = autoFallbackDone ? `${method}, then ${fallbackMethod}` : method;
2593
2089
  throw new Boom(
@@ -2612,22 +2108,14 @@ async function requestSmsCode(store, method, opts) {
2612
2108
  async function verifyCode(store, code, opts) {
2613
2109
  opts = opts || {};
2614
2110
  applyRegistrationName(store, opts);
2615
- // Normally already there from the code request, but a confirmation can be run
2616
- // from a fresh shell that never made one.
2111
+ // The confirmation may run from a fresh shell.
2617
2112
  const _device = deviceForRegistration(store, opts);
2618
2113
  await ensureAndroidMaterial(opts, _device);
2619
2114
  const waVersion = await fetchWaVersion(_device);
2620
2115
  store.version = waVersion;
2621
2116
  store.device = _device;
2622
- // A verification code is all digits, so callers reasonably hand one over as a
2623
- // number; coercing here keeps that from dying on .replace before we ask.
2624
- //
2625
- // Flash is the exception: nothing was ever sent to this number, so what the
2626
- // caller has is the missed call's own number and the code is its tail. Which
2627
- // method is pending is remembered from the code request — the two steps are
2628
- // usually separate commands, so it is read back off the session rather than
2629
- // assumed to still be in memory. opts.method lets a caller state it outright
2630
- // for a session that predates the field.
2117
+ // Codes may arrive as numbers. For flash, the caller types the missed call's
2118
+ // number; the pending method is read from the session (opts.method overrides).
2631
2119
  const pendingMethod = String(opts.method || store.codeMethod || '').toLowerCase();
2632
2120
  const normalized = codeForSubmission(store, code, opts);
2633
2121
 
@@ -2659,21 +2147,11 @@ async function verifyCode(store, code, opts) {
2659
2147
  if (status === 'ok' || status === 'sent' || status === 'verified') {
2660
2148
  await sendFunnelLog(store, waVersion, 'account_verification_complete',
2661
2149
  'submit_code', 'submit_code_success');
2662
- // Adopt the number in the server's own form.
2663
- //
2664
- // WhatsApp answers with `login`, the canonical digits it filed the account
2665
- // under, and that is not always what was typed. Brazilian mobiles are the
2666
- // standing example: they gained a ninth digit, WhatsApp keeps the account
2667
- // under the eight-digit form, and a session saved under the typed number
2668
- // sends a username on every connection that matches no registration. The
2669
- // handshake then fails with 401 and nothing in the message hints at why.
2150
+ // Adopt the server's canonical number (`login`), or the login fails with 401.
2670
2151
  return adoptCanonicalNumber(store, result);
2671
2152
  }
2672
2153
 
2673
- // Before reading the reason, because neither of these arrives as one. A
2674
- // captcha comes as image and audio blobs with nothing else to go on, and a
2675
- // PIN demand names a reason that none of the branches below would match —
2676
- // both would otherwise fall through to the generic failure.
2154
+ // Captcha and 2FA first: neither comes as a reason the checks below match.
2677
2155
  if (hasChallenge(result)) return handleChallenge(store, waVersion, result, opts);
2678
2156
  if (is2FARequired(result)) return handle2FA(store, waVersion, opts);
2679
2157
 
@@ -2690,18 +2168,8 @@ async function verifyCode(store, code, opts) {
2690
2168
  if (/too_many/.test(reason)) {
2691
2169
  throw new Boom('Verification failed: too many wrong attempts. Wait a few minutes then request a new code.', { statusCode: 429 });
2692
2170
  }
2693
- // Age / consent gate.
2694
- //
2695
- // The server found the account and did not complain about the code — it is
2696
- // asking for an age signal that only a real app-store install carries, and
2697
- // refusing to finish without it. Brazil is where this shows up, which fits:
2698
- // it is the market with an age-verification law behind it.
2699
- //
2700
- // Worth knowing before trying anything: the iOS request carries six fields
2701
- // and not one of them says anything about consent, terms or age. The Android
2702
- // one carries tos_version, education_screen_displayed and
2703
- // clicked_education_link. That is the difference to try first, and it costs
2704
- // nothing to try.
2171
+ // Age / consent gate (seen in Brazil): the code was accepted but an age
2172
+ // signal is required. Android sends the terms fields iOS lacks, so try Android.
2705
2173
  if (result.pending === 'app_store_age' || reason === 'consent') {
2706
2174
  const canonical = result.login ? String(result.login).replace(/\D/g, '') : null;
2707
2175
  const lines = [