whalibmob 5.33.34 → 5.40.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli.js CHANGED
@@ -62,6 +62,9 @@ const {
62
62
  const { assertMeId, initAuthCreds } = require('./lib/auth-utils');
63
63
  const { defaultBaseDir, sessionDirFor, storeFileFor, webStoreFileFor,
64
64
  listSessions, migrateSession, isLegacyLayout } = require('./lib/SessionPaths');
65
+ // Everything the link commands do and say. This file only reads their
66
+ // arguments, asks y/N, and prints what comes back.
67
+ const LinkCli = require('./lib/cli/linkCommands');
65
68
 
66
69
  // ─── Wire trace implementation ────────────────────────────────────────────────
67
70
  // Everything below is CLI-only instrumentation; the library is untouched.
@@ -439,6 +442,12 @@ function resolveAuthFolder(name) {
439
442
  return path.join(os.homedir(), raw);
440
443
  }
441
444
 
445
+ // A leading ~ is the home directory. The shell expands it in `--session ~/x`,
446
+ // but not after an `=`, so `--session=~/x` used to name a folder called "~".
447
+ function expandHome(p) {
448
+ return p === '~' || /^~[\/\\]/.test(p) ? path.join(os.homedir(), p.slice(1)) : p;
449
+ }
450
+
442
451
  // Ask what to call the authentication folder, once, and remember the answer.
443
452
  //
444
453
  // Skipped entirely when --session or WA_SESSION_DIR already say where it is,
@@ -447,7 +456,7 @@ function resolveAuthFolder(name) {
447
456
  // not a terminal, so scripts and cron never block on it.
448
457
  function askSessionDir(cmd, explicit) {
449
458
  const OFFLINE = ['version', '--version', '-v', 'help', '--help', '-h'];
450
- if (explicit) return Promise.resolve(explicit);
459
+ if (explicit) return Promise.resolve(expandHome(explicit));
451
460
  if (cmd && OFFLINE.includes(cmd)) return Promise.resolve(defaultSessionDir());
452
461
  if (process.env.WA_SESSION_DIR) return Promise.resolve(process.env.WA_SESSION_DIR);
453
462
 
@@ -509,6 +518,108 @@ function printCodeNextSteps(store, phone, confirmCmd) {
509
518
  out(' run: ' + confirmCmd + ' <code>');
510
519
  }
511
520
 
521
+ // A number registered here starts its message store at registration, so a
522
+ // companion it links later is handed everything since then and is told so,
523
+ // instead of everything since some later connect. These are the files the
524
+ // client opens at each login (Client._openMessageStore): the number's session
525
+ // folder under the base, and the number the session file carries.
526
+ //
527
+ // A store already there is from before this registration: an earlier one of
528
+ // the same number, or connects before it. Nothing in it records the time in
529
+ // between, so carried on it would claim a coverage it does not have. It is
530
+ // renamed aside (kept, never handed over) and the store starts again here.
531
+ // That happens under --no-message-store too, which then starts none: the old
532
+ // one must not be picked up again by a later connect with the store on.
533
+ //
534
+ // It is renamed under the store's own lock, as a store holds it from open to
535
+ // close: a wa that has it open right now (or a lock no one can prove gone) is
536
+ // BUSY, and then nothing is renamed and the holder is named.
537
+ //
538
+ // Nothing here may cost the registration: a failure is a warning.
539
+ async function startMessageStoreAtRegistration(store, phone) {
540
+ const dir = sessionDirFor(_sessDir, phone);
541
+ const who = String(store.phoneNumber || phone);
542
+ if (_messageStoreUnlock) await unlockMessageStore(dir, who, askYesNo);
543
+ const { PrimaryMessageStore } = require('./lib/primary/MessageStore');
544
+ let setAside = false;
545
+ try {
546
+ if (earlierStoreFiles(dir, who).length) PrimaryMessageStore.withLock({ dir, phone: who }, () => setEarlierStoreAside(dir, who));
547
+ setAside = true;
548
+ if (!_messageStoreOn) return;
549
+ PrimaryMessageStore.open({ dir, phone: who, origin: 'registration', lc: store.connectionLc || 0 }).close();
550
+ } catch (e) {
551
+ const code = e && typeof e.code === 'string' && e.code.startsWith('PRIMARY_') ? e.code : null;
552
+ warn('the message store did not start: ' +
553
+ (code ? LinkCli.explainError(code, e).title + ' (' + code + ')' : (e && e.message) || String(e)));
554
+ const base = path.join(dir, who + '.primary-messages');
555
+ if (setAside) {
556
+ out(' the registration itself is fine. The store starts at the first connect instead, and a');
557
+ out(' companion linked later is told it holds only the messages kept from then on.');
558
+ } else if (code === 'PRIMARY_MESSAGE_STORE_BUSY') {
559
+ out(' the registration itself is fine, but the earlier store was not set aside, as another wa holds it.');
560
+ out(' stop that wa, then move ' + base + '.log and ' + base + '.json out of the session folder before connecting;');
561
+ out(' if no wa is running any more, move them all the same and connect with --unlock-message-store.');
562
+ } else {
563
+ out(' the registration itself is fine, but the earlier store could not be set aside. Move');
564
+ out(' ' + path.join(dir, who + '.primary-messages.*') + ' out of the session folder before connecting.');
565
+ }
566
+ }
567
+ }
568
+
569
+ // --unlock-message-store, for the number whose store is about to open in
570
+ // `dir`: who holds its lock, and the lock broken on a yes (LinkCli's
571
+ // runMessageStoreUnlock). `ask(question)` is the y/N, or null where nothing can
572
+ // be asked. Used once a run. A failure is said and the run goes on: the store
573
+ // then reports BUSY, with who holds it, when it opens.
574
+ async function unlockMessageStore(dir, phone, ask) {
575
+ _messageStoreUnlock = false;
576
+ const { PrimaryMessageStore } = require('./lib/primary/MessageStore');
577
+ try {
578
+ return await LinkCli.runMessageStoreUnlock({
579
+ phone,
580
+ readHolder: () => PrimaryMessageStore.readHolder({ dir, phone }),
581
+ breakLock: (holder) => PrimaryMessageStore.breakLock({ dir, phone, holder }),
582
+ confirm: ask ? (question) => ask(question + ' [y/N] ') : null,
583
+ print: out
584
+ });
585
+ } catch (e) {
586
+ failLink(e, 'unlock');
587
+ return { status: 'failed' };
588
+ }
589
+ }
590
+
591
+ const fileThere = file => { try { fs.lstatSync(file); return true; } catch (_) { return false; } };
592
+
593
+ // An earlier store's journal and snapshot, those that are there.
594
+ function earlierStoreFiles(dir, who) {
595
+ return [who + '.primary-messages.log', who + '.primary-messages.json'].map(name => path.join(dir, name)).filter(fileThere);
596
+ }
597
+
598
+ // Run under the store's lock. A write-failed marker the earlier store left
599
+ // (a window of refused writes it never wrote down) is its own and goes aside
600
+ // with it, under the same stamp.
601
+ function setEarlierStoreAside(dir, who) {
602
+ const files = earlierStoreFiles(dir, who);
603
+ if (!files.length) return;
604
+ const present = files.concat([path.join(dir, who + '.primary-messages.write-failed')].filter(fileThere));
605
+ // When it was set aside, without the colons some filesystems refuse.
606
+ const suffix = '.before-' + new Date().toISOString().replace(/[:.]/g, '-');
607
+ const moved = [];
608
+ try {
609
+ for (const file of present) {
610
+ if (fs.existsSync(file + suffix)) throw new Error(file + suffix + ' already exists');
611
+ fs.renameSync(file, file + suffix);
612
+ moved.push(file);
613
+ }
614
+ } catch (e) {
615
+ // All or nothing: half a store set aside is a store neither old nor new.
616
+ for (const file of moved.reverse()) { try { fs.renameSync(file + suffix, file); } catch (_) {} }
617
+ throw e;
618
+ }
619
+ out(' the earlier message store of this number is kept, set aside and no longer handed over: ' +
620
+ path.join(dir, who + '.primary-messages.*' + suffix));
621
+ }
622
+
512
623
  function normalizeJid(s) {
513
624
  if (!s) return null;
514
625
  s = String(s);
@@ -539,6 +650,25 @@ let _sessDir = defaultSessionDir();
539
650
  // /fixnumber knows what it is fixing without probing the server again.
540
651
  let _pendingFix = null;
541
652
  let _rl = null;
653
+ // Whether clients keep the primary message store: the record of what this
654
+ // number sends and receives that a companion it links is handed as history.
655
+ // On unless `--no-message-store` was given (the library's own default is off).
656
+ let _messageStoreOn = true;
657
+ // --reset-message-store: a store whose files are damaged is started again,
658
+ // its files kept beside it as <file>.corrupt-<time> (PRIMARY_MESSAGE_STORE_
659
+ // LOG_CORRUPT and SNAPSHOT_CORRUPT say to run with it).
660
+ let _messageStoreReset = false;
661
+ // What the clients are given as their messageStore option.
662
+ const messageStoreOption = () => (!_messageStoreOn ? false : _messageStoreReset ? { setAsideCorrupt: true } : true);
663
+ // --unlock-message-store: before this run first opens a number's message
664
+ // store (a connect of a registered number, or a registration), show who holds
665
+ // its lock and break it on a y. Once a run; wa listen cannot ask, and refuses.
666
+ let _messageStoreUnlock = false;
667
+ // Link commands still running, and whether one of them is waiting on a y/N.
668
+ // An event that arrives meanwhile prints among the command's lines rather than
669
+ // redrawing the prompt in the middle of them.
670
+ let _linkActive = 0;
671
+ let _linkAsking = false;
542
672
 
543
673
  // ─── shell help ───────────────────────────────────────────────────────────────
544
674
 
@@ -681,19 +811,52 @@ const HELP = `
681
811
  /connect <phone> [sms|pair] connect to WhatsApp (asks which if unset)
682
812
  /pair <phone> [code] link to an existing account by 8-digit code
683
813
  /qrcode <phone> link to an existing account by scanning a QR
684
- /link-code <code> [invitationId] primary approves a separate companion's code
685
- /link-qr <qr-payload-or-wa.me-url> primary approves a separate companion's QR
686
814
  /fixnumber re-file a session under the number WhatsApp uses
687
815
  /disconnect disconnect
688
816
  /reconnect force reconnection
689
817
  /session show session info
690
818
 
819
+ Companions (this number is the primary: it approves WhatsApp Web and hands it the chats)
820
+ the chats are the messages this program has kept for the number: since it
821
+ registered here, or since the store was first on (wa --no-message-store keeps none)
822
+ /link-invitations pairing requests waiting from WhatsApp Web
823
+ /link-code CODE [n|id] approve Web's 8-character code, then send the chats
824
+ n|id: which request, when more than one is waiting
825
+ /link-qr PAYLOAD approve Web's QR (its text or wa.me link), then send the chats
826
+ /link-status where the link and the chat handover stand
827
+ /linked-devices this number's companions
828
+ /link-bootstrap [--resume] [--resend-uncertain]
829
+ send the chats, or continue a handover that stopped
830
+ /link-confirm FILE|JSON confirm an approval with the companion's public proof
831
+ /link-retire clear an approval whose companion never appeared
832
+ /link-unlock show who holds the link-journal lock; break it on a y
833
+
691
834
  /help show this help
692
835
  /quit /exit disconnect and exit
693
836
  `.trim();
694
837
 
695
838
  // ─── incoming event display ───────────────────────────────────────────────────
696
839
 
840
+ // A failure reported by an event rather than by a command: what went wrong and
841
+ // the step to take, in linkCommands' words, with the code to report. `error`,
842
+ // when the event carries one, can say more (a busy store names its holder).
843
+ function failEvent(what, code, detail, context, error) {
844
+ const { title, next } = LinkCli.explainError(code, error || null, context);
845
+ fail(what + ': ' + title + ' (' + code + (detail ? ', ' + detail : '') + ')');
846
+ out(' next: ' + next);
847
+ }
848
+
849
+ // The message store reports each message it could not record, and on a full
850
+ // disk that is every message. Shown once per code a minute; the next one shown
851
+ // says how many were held back meanwhile.
852
+ const storeErrors = LinkCli.createEventLimiter();
853
+
854
+ function storeErrorEvent(e, held, context) {
855
+ const event = e || {};
856
+ failEvent('message store', event.code, event.op, context, event.err);
857
+ if (held) out(LinkCli.formatHeldBack(held));
858
+ }
859
+
697
860
  function attachEvents(client) {
698
861
  client.on('message', (msg) => {
699
862
  _rl && _rl.pause();
@@ -903,6 +1066,34 @@ function attachEvents(client) {
903
1066
  notConnected();
904
1067
  });
905
1068
 
1069
+ // Linking a companion, as the primary. A pairing request is announced as it
1070
+ // arrives, whether or not a /link-code is waiting for it; the rest is the
1071
+ // link's own progress, in the words /link-status uses, and the message store
1072
+ // reporting that it could not record something.
1073
+ //
1074
+ // In the middle of a link command the line goes in among the command's own,
1075
+ // which redraws the prompt when it is done. Otherwise the prompt (or a
1076
+ // pending y/N) is cleared off its line first and drawn again under it.
1077
+ const linkEvent = (print) => (e) => {
1078
+ if (_linkActive > 0 && !_linkAsking) { print(e || {}); return; }
1079
+ if (_rl && process.stdout.isTTY) {
1080
+ readline.cursorTo(process.stdout, 0);
1081
+ readline.clearLine(process.stdout, 0);
1082
+ }
1083
+ _rl && _rl.pause();
1084
+ print(e || {});
1085
+ _rl && (_rl.resume(), _rl.prompt(true));
1086
+ };
1087
+ client.on('primary_link_invitation', linkEvent(inv => out(LinkCli.formatInvitationNotice(inv))));
1088
+ client.on('primary_link_progress', linkEvent(e => out(' ' + LinkCli.formatLinkProgress(e))));
1089
+ client.on('primary_linked', linkEvent(e => out(' ' + LinkCli.formatLinkStatus({ phase: 'committed', confirmed: true })[0] +
1090
+ ' companion #' + e.deviceId + ', key index ' + e.keyIndex)));
1091
+ client.on('primary_link_error', linkEvent(e => failEvent('link request', e.code)));
1092
+ client.on('primary_message_store_error', (e) => {
1093
+ const shown = storeErrors(e && e.code);
1094
+ if (shown) linkEvent(event => storeErrorEvent(event, shown.held))(e);
1095
+ });
1096
+
906
1097
  client.on('error', (e) => {
907
1098
  _rl && _rl.pause();
908
1099
  fail(e.message || String(e));
@@ -1051,7 +1242,7 @@ function registrationPrompts() {
1051
1242
  async function doConnectWeb(phone, opts) {
1052
1243
  opts = opts || {};
1053
1244
  phone = normalizePhone(phone);
1054
- const client = new WhalibmobClient({ sessionDir: _sessDir });
1245
+ const client = new WhalibmobClient({ sessionDir: _sessDir, messageStore: messageStoreOption() });
1055
1246
  attachEvents(client);
1056
1247
 
1057
1248
  client.on('pair_device', () => { /* QR path — nothing to draw in a terminal */ });
@@ -1111,7 +1302,7 @@ async function doConnectWeb(phone, opts) {
1111
1302
  // ref into a QR, and this draws it in the terminal for the phone to scan.
1112
1303
  async function doConnectWebQr(phone) {
1113
1304
  phone = normalizePhone(phone);
1114
- const client = new WhalibmobClient({ sessionDir: _sessDir });
1305
+ const client = new WhalibmobClient({ sessionDir: _sessDir, messageStore: messageStoreOption() });
1115
1306
  attachEvents(client);
1116
1307
 
1117
1308
  let renderQr = null;
@@ -1188,7 +1379,10 @@ async function doConnect(phone) {
1188
1379
  'stored in the session. Unset it to use the session\'s own.');
1189
1380
  }
1190
1381
 
1191
- const client = new WhalibmobClient({ sessionDir: _sessDir });
1382
+ // Before the client, so before the store it opens at login.
1383
+ if (_messageStoreUnlock) await unlockMessageStore(sessionDirFor(_sessDir, phone), phone, askYesNo);
1384
+
1385
+ const client = new WhalibmobClient({ sessionDir: _sessDir, messageStore: messageStoreOption() });
1192
1386
  attachEvents(client);
1193
1387
 
1194
1388
  // The session may be re-filed mid-connect when WhatsApp turns out to keep the
@@ -1315,6 +1509,216 @@ function tokens(line) {
1315
1509
  return t;
1316
1510
  }
1317
1511
 
1512
+ // ─── companion linking ────────────────────────────────────────────────────────
1513
+ //
1514
+ // This number as the primary: it approves a separate companion (WhatsApp Web)
1515
+ // and hands it the chats it has kept. What each command does, and every word
1516
+ // it prints about the link, comes from lib/cli/linkCommands.js. What is here
1517
+ // reads the arguments, asks y/N, and prints.
1518
+
1519
+ const printLines = (lines) => { for (const line of lines) out(line); };
1520
+
1521
+ // A failure as linkCommands explains it: what happened, the step to take, and
1522
+ // the code to report. Never a stack.
1523
+ function failLink(e, context) {
1524
+ const [first, ...rest] = LinkCli.describeError(e, context);
1525
+ fail(first);
1526
+ printLines(rest);
1527
+ }
1528
+
1529
+ function linkUsage(usage, ...more) {
1530
+ fail('usage: ' + usage);
1531
+ for (const line of more) out(' ' + line);
1532
+ }
1533
+
1534
+ // Approving a companion is the primary's job. A companion session would be
1535
+ // refused by the library too, in terms that do not say what to do instead.
1536
+ function requirePrimary() {
1537
+ requireConn();
1538
+ if (_client._mode !== 'mobile') {
1539
+ const e = new Error('PRIMARY_LINK_PRIMARY_REQUIRED');
1540
+ e.code = 'PRIMARY_LINK_PRIMARY_REQUIRED';
1541
+ throw e;
1542
+ }
1543
+ }
1544
+
1545
+ // y/N through the shell's own reader: a second reader on the same stdin would
1546
+ // split the answer with it. Anything but y or yes is no, and so is having no
1547
+ // way to ask. Before the shell is open (wa registration --register) a terminal
1548
+ // is asked through a reader of its own, as the startup questions are; a pipe
1549
+ // is not, since a reader closed on one keeps lines meant for the shell.
1550
+ function askYesNo(question) {
1551
+ return new Promise((resolve) => {
1552
+ if (!_rl && process.stdin.isTTY) {
1553
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
1554
+ return rl.question(question, (answer) => { rl.close(); resolve(/^y(es)?$/i.test(String(answer).trim())); });
1555
+ }
1556
+ if (!_rl || _linkAsking) return resolve(false);
1557
+ _linkAsking = true;
1558
+ _rl.question(question, (answer) => {
1559
+ _linkAsking = false;
1560
+ resolve(/^y(es)?$/i.test(String(answer).trim()));
1561
+ });
1562
+ });
1563
+ }
1564
+
1565
+ // Asked only when the readiness check says the history is partial, after it
1566
+ // has printed what is and is not in it, and after the request is chosen: the
1567
+ // question (linkCommands' words) names that browser.
1568
+ const confirmHistory = (readiness, ask) =>
1569
+ askYesNo(((ask && ask.question) || 'approve the link and send this history?') + ' [y/N] ');
1570
+
1571
+ // The number this connection is the primary for.
1572
+ const linkPhone = () => String((_client && _client.store && _client.store.phoneNumber) || _phone || '');
1573
+
1574
+ function linkOutcome(result) {
1575
+ if (result && result.status === 'aborted') out('cancelled: nothing was approved');
1576
+ }
1577
+
1578
+ // The proof /link-confirm takes: a file, or the JSON itself. It is read off
1579
+ // the line as typed, because the tokenizer drops quotes that JSON needs.
1580
+ function proofText(arg) {
1581
+ const quoted = /^(["'])([\s\S]*)\1$/.exec(arg);
1582
+ const text = quoted ? quoted[2].trim() : arg;
1583
+ if (text.startsWith('{')) return { text };
1584
+ const file = path.resolve(expandHome(text));
1585
+ try { return { text: fs.readFileSync(file, 'utf8') }; }
1586
+ catch (error) { return { file, error }; }
1587
+ }
1588
+
1589
+ async function linkCommand(cmd, p, line) {
1590
+ const K = LinkCli.COMMANDS;
1591
+ _linkActive++;
1592
+ try {
1593
+ switch (cmd) {
1594
+ case '/link-code': {
1595
+ // Web shows the code in two halves, and `ABCD EFGH` is how it gets
1596
+ // typed. A half is never a whole code, so two 4-character tokens are
1597
+ // one code, and the selector, if any, comes after them.
1598
+ const split = p.length >= 3 && p[1].length === 4 && p[2].length === 4;
1599
+ const args = split ? [p[0], p[1] + p[2], ...p.slice(3)] : p;
1600
+ if (!args[1] || args.length > 3) {
1601
+ return linkUsage('/link-code CODE [n|id]',
1602
+ 'CODE the 8-character code WhatsApp Web shows after "Link with phone number"',
1603
+ 'n|id which request, when ' + K.invitations + ' lists more than one: its number or its id');
1604
+ }
1605
+ requirePrimary();
1606
+ linkOutcome(await LinkCli.runLinkCode({
1607
+ client: _client, code: args[1], selector: args[2], confirm: confirmHistory, print: out
1608
+ }));
1609
+ return;
1610
+ }
1611
+
1612
+ case '/link-qr': {
1613
+ if (p.length !== 2) {
1614
+ return linkUsage('/link-qr PAYLOAD', 'PAYLOAD the text of the QR WhatsApp Web shows, or its wa.me link');
1615
+ }
1616
+ requirePrimary();
1617
+ linkOutcome(await LinkCli.runLinkQr({ client: _client, payload: p[1], confirm: confirmHistory, print: out }));
1618
+ return;
1619
+ }
1620
+
1621
+ case '/link-invitations': {
1622
+ if (p.length > 1) return linkUsage('/link-invitations');
1623
+ requirePrimary();
1624
+ // One reading of the clock, so what is grouped is what is shown.
1625
+ const now = Date.now();
1626
+ printLines(LinkCli.formatInvitations(LinkCli.groupInvitations(await _client.getPrimaryLinkInvitations(), now), now));
1627
+ return;
1628
+ }
1629
+
1630
+ case '/link-status': {
1631
+ if (p.length > 1) return linkUsage('/link-status');
1632
+ requirePrimary();
1633
+ printLines(LinkCli.formatLinkStatus(await _client.getPrimaryLinkStatus()));
1634
+ return;
1635
+ }
1636
+
1637
+ case '/linked-devices': {
1638
+ if (p.length > 1) return linkUsage('/linked-devices');
1639
+ requirePrimary();
1640
+ // The status carries the device list and the journal, from one query:
1641
+ // how and when the companion was linked and what history it was handed
1642
+ // are kept in the journal, so they outlive the run that made the link.
1643
+ const status = await _client.getPrimaryLinkStatus();
1644
+ printLines(LinkCli.formatLinkedDevices({ phone: linkPhone(), devices: status && status.devices, journal: status }));
1645
+ return;
1646
+ }
1647
+
1648
+ case '/link-retire': {
1649
+ if (p.length > 1) return linkUsage('/link-retire');
1650
+ requirePrimary();
1651
+ const result = await _client.retireAbsentPrimaryLink();
1652
+ out('retired the unfinished approval' +
1653
+ (result && result.operationId ? ' (operation ' + String(result.operationId).slice(0, 8) + ')' : '') +
1654
+ '; nothing was linked');
1655
+ printLines(LinkCli.formatLinkStatus(await _client.getPrimaryLinkStatus()));
1656
+ return;
1657
+ }
1658
+
1659
+ case '/link-confirm': {
1660
+ const arg = line.replace(/^\S+\s*/, '');
1661
+ if (!arg) {
1662
+ return linkUsage(K.reconcile,
1663
+ "FILE a file holding the companion's public proof JSON",
1664
+ 'JSON or that JSON itself, on the line');
1665
+ }
1666
+ requirePrimary();
1667
+ const given = proofText(arg);
1668
+ if (given.error) {
1669
+ fail('could not read ' + given.file + ' (' + (given.error.code || given.error.message) + ')');
1670
+ out(' next: ' + LinkCli.explainError('PRIMARY_LINK_WEB_PROOF_INVALID').next);
1671
+ return;
1672
+ }
1673
+ const { parseWhatsAppWebPublicProof } = require('./lib/WhatsAppWebProof');
1674
+ const result = await _client.reconcilePrimaryLink(parseWhatsAppWebPublicProof(given.text));
1675
+ out("confirmed: the companion's proof was verified" +
1676
+ (result && Number.isFinite(result.deviceId) ? ' (companion #' + result.deviceId + ')' : ''));
1677
+ printLines(LinkCli.formatLinkStatus(await _client.getPrimaryLinkStatus()));
1678
+ return;
1679
+ }
1680
+
1681
+ case '/link-bootstrap': {
1682
+ const options = { history: 'store', resume: false, resendUncertain: false };
1683
+ for (const t of p.slice(1)) {
1684
+ if (t === '--resume') options.resume = true;
1685
+ else if (t === '--resend-uncertain') options.resendUncertain = true;
1686
+ else {
1687
+ return linkUsage('/link-bootstrap [--resume] [--resend-uncertain]',
1688
+ '--resume continue the last attempt after its last accepted step (harmless when there is none)',
1689
+ '--resend-uncertain with --resume: send once more a step whose reply never came');
1690
+ }
1691
+ }
1692
+ requirePrimary();
1693
+ // A resend is a resend of the attempt on record; without --resume the
1694
+ // library would refuse it as already attempted.
1695
+ if (options.resendUncertain && !options.resume) {
1696
+ options.resume = true;
1697
+ out('note: --resend-uncertain only counts on a resume, so this runs as ' + K.resend);
1698
+ }
1699
+ out('sending the stored history to the companion...');
1700
+ const result = await _client.bootstrapPrimaryCompanion(options);
1701
+ printLines(LinkCli.formatBootstrapResult(result));
1702
+ return;
1703
+ }
1704
+
1705
+ case '/link-unlock': {
1706
+ if (p.length > 1) return linkUsage('/link-unlock');
1707
+ // No connection needed: the lock is a file, and a session that cannot
1708
+ // link because of it is still able to connect. Who holds it is shown
1709
+ // first, and it is broken only on a y; Enter is no.
1710
+ if (!_client) throw new Error('not connected — use /connect <phone>');
1711
+ await LinkCli.runLinkUnlock({ client: _client, confirm: (question) => askYesNo(question + ' [y/N] '), print: out });
1712
+ return;
1713
+ }
1714
+ }
1715
+ } catch (e) {
1716
+ failLink(e, cmd === '/link-unlock' ? 'unlock' : cmd === '/link-bootstrap' ? 'bootstrap' : undefined);
1717
+ } finally {
1718
+ _linkActive--;
1719
+ }
1720
+ }
1721
+
1318
1722
  // ─── command dispatch ─────────────────────────────────────────────────────────
1319
1723
 
1320
1724
  async function handleLine(line) {
@@ -1424,24 +1828,19 @@ async function handleLine(line) {
1424
1828
  break;
1425
1829
  }
1426
1830
 
1831
+ // ── companion linking (this number as the primary) ─────────────────────
1832
+
1427
1833
  case '/link-code':
1428
- case '/link-qr': {
1429
- requireConn();
1430
- if (!p[1] || p.length > (cmd === '/link-code' ? 3 : 2)) {
1431
- fail(cmd === '/link-code' ? 'usage: /link-code <8-char-code> [invitationId]' : 'usage: /link-qr <qr-payload-or-wa.me-url>');
1432
- break;
1433
- }
1434
- const result = cmd === '/link-code'
1435
- ? await _client.linkCompanionWithCode(p[1], p[2] ? { invitationId: p[2] } : undefined)
1436
- : await _client.linkCompanionWithQr(p[1]);
1437
- kv('status', result.status);
1438
- kv('operation', result.operationId);
1439
- if (result.status === 'awaiting_confirmation') {
1440
- out(' approval sent; independent companion proof and a fresh device list are still required');
1441
- out(' reconcile this operation through the runner; do not repeat approval');
1442
- }
1834
+ case '/link-qr':
1835
+ case '/link-invitations':
1836
+ case '/link-status':
1837
+ case '/linked-devices':
1838
+ case '/link-retire':
1839
+ case '/link-confirm':
1840
+ case '/link-bootstrap':
1841
+ case '/link-unlock':
1842
+ await linkCommand(cmd, p, line);
1443
1843
  break;
1444
- }
1445
1844
 
1446
1845
  case '/disconnect':
1447
1846
  if (_client) { _client.disconnect(); _client = null; _phone = null; }
@@ -2475,6 +2874,7 @@ async function handleLine(line) {
2475
2874
  const savedPhone = String(finalStore.phoneNumber || ph);
2476
2875
  const savedFile = storeFileFor(_sessDir, savedPhone);
2477
2876
  saveStore(finalStore, savedFile);
2877
+ await startMessageStoreAtRegistration(finalStore, savedPhone);
2478
2878
  if (r.canonicalPhoneNumber) {
2479
2879
  out('note: WhatsApp knows this account as +' + r.canonicalPhoneNumber +
2480
2880
  ', not +' + r.typedPhoneNumber);
@@ -2572,6 +2972,7 @@ async function handleLine(line) {
2572
2972
  finalStore.registered = true; finalStore.codePending = false;
2573
2973
  const savedPhone = String(finalStore.phoneNumber || ph);
2574
2974
  saveStore(finalStore, storeFileFor(_sessDir, savedPhone));
2975
+ await startMessageStoreAtRegistration(finalStore, savedPhone);
2575
2976
  out('registered via push session saved');
2576
2977
  out('now run: /connect ' + savedPhone);
2577
2978
  } else {
@@ -2768,28 +3169,65 @@ async function handleLine(line) {
2768
3169
 
2769
3170
  // ─── argument parser ──────────────────────────────────────────────────────────
2770
3171
 
3172
+ // Options that are switches: on when present, and never followed by a value,
3173
+ // so `wa connect --no-message-store <phone>` keeps the phone as the phone.
3174
+ // Every other option takes the argument after it as its value, unless that is
3175
+ // itself an option.
3176
+ const SWITCHES = new Set(['no-message-store', 'reset-message-store', 'unlock-message-store', 'sms', 'pair', 'business', 'all', 'download']);
3177
+ // What `--switch=value` may say.
3178
+ const SWITCH_VALUES = { 'true': true, 'yes': true, 'on': true, '1': true,
3179
+ 'false': false, 'no': false, 'off': false, '0': false };
3180
+ // Commands spelled like options. Typed first, they are still the command.
3181
+ const COMMAND_OPTIONS = new Set(['--version', '--help']);
3182
+
3183
+ // `wa [options] <command> [<sub>] [arguments and options]`
3184
+ //
3185
+ // An option is `--name value` or `--name=value`, and may come before the
3186
+ // command as well as after it: `wa --session ~/s connect <phone>` reads as
3187
+ // `wa connect <phone> --session ~/s`. `--session=./dir` used to be taken for an
3188
+ // option called "session=./dir" and ignored, and an option typed before the
3189
+ // command was taken for the command. `--name=` is an empty value, which
3190
+ // --session refuses like a missing one.
2771
3191
  function parseArgs(argv) {
2772
3192
  const a = argv.slice(2);
2773
- const r = { cmd: null, sub: null, flags: {}, pos: [] };
2774
- if (!a.length) return r;
2775
- r.cmd = a[0];
2776
- let i = 1;
3193
+ const r = { cmd: null, sub: null, flags: {}, pos: [], error: null };
3194
+
3195
+ // The option at a[i]; returns the index of what follows it.
3196
+ const option = (i) => {
3197
+ const body = a[i].slice(2);
3198
+ const eq = body.indexOf('=');
3199
+ const name = eq === -1 ? body : body.slice(0, eq);
3200
+ if (eq !== -1) {
3201
+ const value = body.slice(eq + 1);
3202
+ if (!SWITCHES.has(name)) r.flags[name] = value;
3203
+ else if (Object.prototype.hasOwnProperty.call(SWITCH_VALUES, value.toLowerCase())) r.flags[name] = SWITCH_VALUES[value.toLowerCase()];
3204
+ else if (!r.error) r.error = '--' + name + ' is a switch and takes no value (got "' + value + '")';
3205
+ return i + 1;
3206
+ }
3207
+ if (SWITCHES.has(name)) { r.flags[name] = true; return i + 1; }
3208
+ if (a[i + 1] && !a[i + 1].startsWith('-')) { r.flags[name] = a[i + 1]; return i + 2; }
3209
+ r.flags[name] = true;
3210
+ return i + 1;
3211
+ };
3212
+
3213
+ let i = 0;
3214
+ while (i < a.length && a[i].startsWith('--') && !COMMAND_OPTIONS.has(a[i])) i = option(i);
3215
+ if (i >= a.length) return r;
3216
+ r.cmd = a[i++];
2777
3217
  if (a[i] && !a[i].startsWith('-')) r.sub = a[i++];
2778
3218
  while (i < a.length) {
2779
- if (a[i].startsWith('--')) {
2780
- const k = a[i].slice(2);
2781
- const v = a[i + 1] && !a[i + 1].startsWith('-') ? a[++i] : true;
2782
- r.flags[k] = v;
2783
- } else {
2784
- r.pos.push(a[i]);
2785
- }
2786
- i++;
3219
+ if (a[i].startsWith('--')) i = option(i);
3220
+ else r.pos.push(a[i++]);
2787
3221
  }
2788
3222
  return r;
2789
3223
  }
2790
3224
 
2791
3225
  // ─── main ─────────────────────────────────────────────────────────────────────
2792
3226
 
3227
+ // The commands main() runs, by name. Keep in step with it.
3228
+ const MAIN_COMMANDS = new Set(['connect', 'pair', 'listen', 'registration', 'reg', 'apk-material',
3229
+ 'refresh-version', 'migrate-sessions', 'version', 'help']);
3230
+
2793
3231
  const USAGE = `
2794
3232
  whalibmob v${VERSION}
2795
3233
 
@@ -2807,8 +3245,14 @@ usage:
2807
3245
  wa migrate-sessions [phone] move old flat sessions into folders
2808
3246
  wa version
2809
3247
 
2810
- options:
3248
+ options: before or after the command; --session <dir> and --session=<dir> are the same
2811
3249
  --session <dir> authentication folder (default: remembered, else ~/.waSession)
3250
+ --no-message-store keep no record of messages. By default a registered number keeps
3251
+ one, from registration on, to hand a companion it links as history
3252
+ --reset-message-store when the message store's files are damaged, keep them (renamed
3253
+ <file>.corrupt-<time>) and start the store again; history starts from now
3254
+ --unlock-message-store before the message store opens, show who holds its lock and
3255
+ break it on a y — for a wa that is gone (wa listen cannot ask, and refuses)
2812
3256
  --out <file> where apk-material writes (default: <session dir>/android-apk-material.json)
2813
3257
  --sms connect by registering this number over SMS
2814
3258
  --pair connect by linking to an existing account (8-digit code)
@@ -2901,12 +3345,46 @@ function askDonation(cmd) {
2901
3345
  }
2902
3346
 
2903
3347
  async function main() {
2904
- const { cmd, sub, flags, pos } = parseArgs(process.argv);
3348
+ const { cmd, sub, flags, pos, error } = parseArgs(process.argv);
3349
+ if (error) {
3350
+ fail(error);
3351
+ process.exit(1);
3352
+ }
3353
+ _messageStoreOn = !flags['no-message-store'];
3354
+ _messageStoreReset = !!flags['reset-message-store'];
3355
+ _messageStoreUnlock = !!flags['unlock-message-store'];
3356
+ if (_messageStoreReset && !_messageStoreOn) {
3357
+ fail('--reset-message-store starts the message store again, and --no-message-store keeps none: use one of them');
3358
+ process.exit(1);
3359
+ }
3360
+
3361
+ // `--session` with nothing after it parses as `true`, and so does an empty
3362
+ // value, which is what `--session "$DIR"` turns into when $DIR is unset.
3363
+ // Neither names a folder. Carried on as one, it either ends up as a directory
3364
+ // called "true" or surfaces as a TypeError from path handling that never
3365
+ // mentions the flag, so refuse it here, before a prompt, a file or a
3366
+ // connection depends on the answer.
3367
+ if (flags.session !== undefined && !(typeof flags.session === 'string' && flags.session.trim())) {
3368
+ fail('--session needs a directory, e.g. --session ./sessions');
3369
+ process.exit(1);
3370
+ }
3371
+ // `wa --session connect <phone>` (the folder left out) reads "connect" as
3372
+ // the folder and the phone as the command. A folder named after a command is
3373
+ // that mistake far more often than a real folder, so say where options go.
3374
+ if (typeof flags.session === 'string' && MAIN_COMMANDS.has(flags.session.trim())) {
3375
+ fail('--session needs a directory; put options after the command, e.g. wa connect <phone> --session <dir>');
3376
+ process.exit(1);
3377
+ }
2905
3378
 
2906
3379
  // The authentication folder first: it decides where everything this run
2907
3380
  // touches lives, and asking it after the other two made the answer to the
2908
3381
  // first question land in the wrong prompt.
2909
- _sessDir = await askSessionDir(cmd, flags.session);
3382
+ //
3383
+ // Absolute from here on, however it was given — --session, WA_SESSION_DIR,
3384
+ // the remembered answer or the prompt all come back through askSessionDir.
3385
+ // It is published below and handed to every client, and none of them should
3386
+ // depend on the directory the command happens to run in.
3387
+ _sessDir = path.resolve(await askSessionDir(cmd, flags.session));
2910
3388
 
2911
3389
  // One source of truth for the rest of the run. The library resolves the files
2912
3390
  // that belong to the installation rather than to a number — the Android token
@@ -3225,6 +3703,7 @@ async function main() {
3225
3703
  sessionDirFor(_sessDir, savedPhone, { create: true });
3226
3704
  const savedFile = storeFileFor(_sessDir, savedPhone);
3227
3705
  saveStore(finalStore, savedFile);
3706
+ await startMessageStoreAtRegistration(finalStore, savedPhone);
3228
3707
  if (r.canonicalPhoneNumber) {
3229
3708
  out('note: WhatsApp knows this account as +' + r.canonicalPhoneNumber +
3230
3709
  ', not +' + r.typedPhoneNumber);
@@ -3287,7 +3766,13 @@ async function main() {
3287
3766
  const phone = normalizePhone(sub || pos[0] || flags.phone || '');
3288
3767
  if (!phone) { fail('phone number required'); process.exit(1); }
3289
3768
 
3290
- const client = new WhalibmobClient({ sessionDir: _sessDir });
3769
+ // No one to ask here: a lock that is held is named, and left as it is.
3770
+ if (_messageStoreUnlock) {
3771
+ const unlock = await unlockMessageStore(sessionDirFor(_sessDir, phone), phone, null);
3772
+ if (unlock.status === 'refused') process.exit(1);
3773
+ }
3774
+
3775
+ const client = new WhalibmobClient({ sessionDir: _sessDir, messageStore: messageStoreOption() });
3291
3776
 
3292
3777
  client.on('connected', () => {
3293
3778
  _client = client;
@@ -3367,6 +3852,10 @@ async function main() {
3367
3852
  client.on('reconnecting', ({ delay }) => out(' reconnecting in ' + delay / 1000 + 's...'));
3368
3853
  client.on('reconnected', () => out(' reconnected'));
3369
3854
  client.on('auth_failure', (f) => { fail('session revoked: ' + f.reason); process.exit(1); });
3855
+ client.on('primary_message_store_error', (e) => {
3856
+ const shown = storeErrors(e && e.code);
3857
+ if (shown) storeErrorEvent(e, shown.held, 'listen');
3858
+ });
3370
3859
  client.on('error', (e) => fail(e.message));
3371
3860
 
3372
3861
  process.on('SIGINT', () => { out('\nstopping...'); client.disconnect(); process.exit(0); });