@hiroosy/baileys-lite 0.3.8 → 0.4.0

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.
@@ -1,9 +1,10 @@
1
1
  import { createNoopLogger, unpadPkcs7, writeRandomPadMax16 } from '../shim/core.js';
2
2
  import { getProto } from '../shim/proto.js';
3
3
  import { parseSignalAddressFromJid, toUserJid } from '../shim/protocol.js';
4
- import { buildReceiptNode, findNodeChild, getFirstNodeChild, getNodeChildren, getNodeChildrenByTag } from '../shim/transport.js';
4
+ import { buildAckNode, buildReceiptNode, findNodeChild, getFirstNodeChild, getNodeChildren, getNodeChildrenByTag } from '../shim/transport.js';
5
5
  import { bytesToHex, toError } from '../shim/util.js';
6
6
  import { randomBytes } from '../crypto/primitives.js';
7
+ import { TEXT_ENCODER } from '../bytes.js';
7
8
  export async function encodeWAMessage(message) {
8
9
  const proto = await getProto();
9
10
  return writeRandomPadMax16(proto.Message.encode(message).finish());
@@ -489,3 +490,433 @@ export const ENCRYPTED_TAGS = ['preaccept', 'accept'];
489
490
  export function needsDecryption(tag) {
490
491
  return ENCRYPTED_TAGS.includes(tag);
491
492
  }
493
+ const groupCapabilityOffer = new Uint8Array([0x01, 0x05, 0xf7, 0x09, 0xe0, 0xbb, 0x13]);
494
+ export const GroupCapability = Object.freeze({
495
+ offer: groupCapabilityOffer,
496
+ videoOffer: new Uint8Array([0x01, 0x05, 0xf7, 0x09, 0xe0, 0xfa, 0x13]),
497
+ preaccept: new Uint8Array([0x01, 0x05, 0xf7, 0x09, 0xe0, 0xbb, 0x07])
498
+ });
499
+ export function callJidFor(callId) {
500
+ return `${callId}@call`;
501
+ }
502
+ function readOptionalUint(node, key) {
503
+ const raw = node?.attrs?.[key];
504
+ if (raw === undefined || raw === null || raw === '') {
505
+ return undefined;
506
+ }
507
+ const value = Number(raw);
508
+ if (!Number.isInteger(value) || value < 0 || value > 0xffffffff) {
509
+ throw new Error(`invalid ${key} "${raw}"`);
510
+ }
511
+ return value;
512
+ }
513
+ function readRequiredUint(node, key) {
514
+ const value = readOptionalUint(node, key);
515
+ if (value === undefined) {
516
+ throw new Error(`missing ${key}`);
517
+ }
518
+ return value;
519
+ }
520
+ function readNodeBytes(node) {
521
+ if (node?.content instanceof Uint8Array) {
522
+ return node.content;
523
+ }
524
+ if (typeof node?.content === 'string') {
525
+ return TEXT_ENCODER.encode(node.content);
526
+ }
527
+ return undefined;
528
+ }
529
+ function sameBytes(left, right) {
530
+ return !!left && !!right && bytesToHex(left) === bytesToHex(right);
531
+ }
532
+ function buildGroupUserNodes(participants, creator, video) {
533
+ return participants.map((participant) => {
534
+ if (!participant.jid || !participant.devices?.length) {
535
+ throw new Error('group participant is incomplete');
536
+ }
537
+ const attrs = { jid: participant.jid };
538
+ if (participant.state) {
539
+ attrs.state = participant.state;
540
+ }
541
+ return {
542
+ tag: 'user',
543
+ attrs,
544
+ content: participant.devices.map((device) => {
545
+ if (!device.jid) {
546
+ throw new Error('group device jid is required');
547
+ }
548
+ let content;
549
+ if (device.capability) {
550
+ content = [
551
+ {
552
+ tag: 'capability',
553
+ attrs: device.capabilityVersion ? { ver: String(device.capabilityVersion) } : {},
554
+ content: video && device.jid === creator && sameBytes(device.capability, groupCapabilityOffer) ? GroupCapability.videoOffer : device.capability
555
+ }
556
+ ];
557
+ }
558
+ return { tag: 'device', attrs: { jid: device.jid }, content };
559
+ })
560
+ };
561
+ });
562
+ }
563
+ function buildGroupVideoOfferNode() {
564
+ return {
565
+ tag: 'video',
566
+ attrs: { enc: 'h.264', dec: 'H264', screen_width: '1920', screen_height: '1080', device_orientation: '0' }
567
+ };
568
+ }
569
+ export function buildInitialGroupOfferStanza({ callId, creator, groupJid, participants, video }) {
570
+ if (!callId || !creator) {
571
+ throw new Error('call id and creator are required');
572
+ }
573
+ if (participants.length < 3) {
574
+ throw new Error('a group call needs yourself and at least two other participants');
575
+ }
576
+ const content = [
577
+ { tag: 'audio', attrs: { enc: 'opus', rate: '8000' } },
578
+ { tag: 'audio', attrs: { enc: 'opus', rate: '16000' } }
579
+ ];
580
+ if (video) {
581
+ content.push(buildGroupVideoOfferNode());
582
+ }
583
+ content.push({ tag: 'net', attrs: { medium: '3' } }, { tag: 'group_info', attrs: {}, content: buildGroupUserNodes(participants, creator, video) });
584
+ const attrs = { 'call-id': callId, 'call-creator': creator };
585
+ if (groupJid) {
586
+ attrs['group-jid'] = groupJid;
587
+ }
588
+ return {
589
+ tag: 'call',
590
+ attrs: { to: callJidFor(callId) },
591
+ content: [{ tag: 'offer', attrs, content }]
592
+ };
593
+ }
594
+ export function buildGroupInviteOfferStanza({ callId, to, creator, targetDevices, participants, video }) {
595
+ if (!callId || !to || !creator || !targetDevices?.length || !participants?.length) {
596
+ throw new Error('invite needs call identity, target devices and roster');
597
+ }
598
+ const content = [{ tag: 'audio', attrs: { enc: 'opus', rate: '16000' } }];
599
+ if (video) {
600
+ content.push(buildGroupVideoOfferNode());
601
+ }
602
+ content.push({ tag: 'net', attrs: { medium: '2' } }, {
603
+ tag: 'destination',
604
+ attrs: {},
605
+ content: targetDevices.map((jid) => ({ tag: 'to', attrs: { jid } }))
606
+ }, { tag: 'group_info', attrs: {}, content: buildGroupUserNodes(participants, undefined, false) });
607
+ return {
608
+ tag: 'call',
609
+ attrs: { to },
610
+ content: [{ tag: 'offer', attrs: { 'call-id': callId, 'call-creator': creator }, content }]
611
+ };
612
+ }
613
+ export function buildGroupPreacceptStanza(callId, creator, video) {
614
+ const content = [{ tag: 'audio', attrs: { enc: 'opus', rate: '16000' } }];
615
+ if (video) {
616
+ content.push({
617
+ tag: 'video',
618
+ attrs: { dec: 'H264', device_orientation: '0', screen_width: '0', screen_height: '0' }
619
+ });
620
+ }
621
+ content.push({ tag: 'encopt', attrs: { keygen: '2' } }, { tag: 'capability', attrs: { ver: '1' }, content: video ? groupCapabilityOffer : GroupCapability.preaccept });
622
+ return {
623
+ tag: 'call',
624
+ attrs: { to: callJidFor(callId), id: generateCallStanzaId() },
625
+ content: [{ tag: 'preaccept', attrs: { 'call-id': callId, 'call-creator': creator }, content }]
626
+ };
627
+ }
628
+ export function buildGroupAcceptStanza(callId, creator) {
629
+ return {
630
+ tag: 'call',
631
+ attrs: { to: callJidFor(callId), id: generateCallStanzaId() },
632
+ content: [
633
+ {
634
+ tag: 'accept',
635
+ attrs: { 'call-id': callId, 'call-creator': creator },
636
+ content: [
637
+ { tag: 'audio', attrs: { enc: 'opus', rate: '16000' } },
638
+ { tag: 'net', attrs: { medium: '2' } },
639
+ { tag: 'encopt', attrs: { keygen: '2' } }
640
+ ]
641
+ }
642
+ ]
643
+ };
644
+ }
645
+ export function buildGroupTerminateStanza(callId, creator) {
646
+ return {
647
+ tag: 'call',
648
+ attrs: { to: callJidFor(callId), id: generateCallStanzaId() },
649
+ content: [{ tag: 'terminate', attrs: { 'call-id': callId, 'call-creator': creator } }]
650
+ };
651
+ }
652
+ export function buildGroupEncRekeyStanza({ callId, to, creator, transactionId, encType, ciphertext }) {
653
+ if (!callId || !to || !creator || !transactionId || !ciphertext?.length) {
654
+ throw new Error('group rekey is incomplete');
655
+ }
656
+ if (encType !== 'msg' && encType !== 'pkmsg') {
657
+ throw new Error(`unsupported group rekey encryption ${encType}`);
658
+ }
659
+ return {
660
+ tag: 'call',
661
+ attrs: { to, id: generateCallStanzaId() },
662
+ content: [
663
+ {
664
+ tag: 'enc_rekey',
665
+ attrs: { 'call-id': callId, 'call-creator': creator, 'transaction-id': String(transactionId) },
666
+ content: [
667
+ { tag: 'encopt', attrs: { keygen: '2' } },
668
+ { tag: 'enc', attrs: { v: '2', type: encType, count: '0' }, content: ciphertext }
669
+ ]
670
+ }
671
+ ]
672
+ };
673
+ }
674
+ function parseGroupDeviceNode(node) {
675
+ const capabilityNode = findNodeChild(node, 'capability');
676
+ return {
677
+ jid: node.attrs?.jid,
678
+ platform: node.attrs?.platform,
679
+ pid: readOptionalUint(node, 'pid'),
680
+ capabilityVersion: capabilityNode ? readOptionalUint(capabilityNode, 'ver') : undefined,
681
+ capability: capabilityNode ? readNodeBytes(capabilityNode) : undefined
682
+ };
683
+ }
684
+ function parseGroupInfoNode(groupInfo) {
685
+ const participants = getNodeChildrenByTag(groupInfo, 'user').map((user) => ({
686
+ jid: user.attrs?.jid,
687
+ pn: user.attrs?.user_pn,
688
+ state: user.attrs?.state || '',
689
+ type: user.attrs?.type,
690
+ rekey: user.attrs?.rekey === '1',
691
+ devices: getNodeChildrenByTag(user, 'device').map(parseGroupDeviceNode)
692
+ }));
693
+ return {
694
+ groupJid: groupInfo.attrs?.['group-jid'],
695
+ media: groupInfo.attrs?.media,
696
+ joinable: groupInfo.attrs?.joinable === '1',
697
+ rekeyRequested: groupInfo.attrs?.rekey === '1' || participants.some((participant) => participant.rekey),
698
+ transactionId: readRequiredUint(groupInfo, 'transaction-id'),
699
+ connectedLimit: readRequiredUint(groupInfo, 'connected-limit'),
700
+ participants
701
+ };
702
+ }
703
+ function parseGroupRelayNode(relayNode) {
704
+ const hbhKey = readNodeBytes(findNodeChild(relayNode, 'hbh_key'));
705
+ return {
706
+ node: relayNode,
707
+ uuid: relayNode.attrs?.uuid,
708
+ participantUuid: relayNode.attrs?.participant_uuid,
709
+ transactionId: readOptionalUint(relayNode, 'transaction-id'),
710
+ selfPid: readOptionalUint(relayNode, 'self_pid'),
711
+ warpMiTagLength: readOptionalUint(relayNode, 'warp_mi_tag_len'),
712
+ hbhKey: hbhKey && hbhKey.length === 30 ? hbhKey : undefined
713
+ };
714
+ }
715
+ export function parseGroupInviteSnapshot(offerNode) {
716
+ const groupInfo = findNodeChild(offerNode, 'group_info');
717
+ if (!groupInfo) {
718
+ return null;
719
+ }
720
+ const update = {
721
+ callId: offerNode.attrs?.['call-id'],
722
+ callCreator: offerNode.attrs?.['call-creator'],
723
+ ...parseGroupInfoNode(groupInfo)
724
+ };
725
+ update.joinable = offerNode.attrs?.joinable === '1';
726
+ return update;
727
+ }
728
+ export function parseInitialGroupAck(ackNode) {
729
+ const groupInfo = findNodeChild(ackNode, 'group_info');
730
+ if (!groupInfo) {
731
+ return null;
732
+ }
733
+ const update = {
734
+ callId: groupInfo.attrs?.['call-id'],
735
+ callCreator: groupInfo.attrs?.['call-creator'],
736
+ ...parseGroupInfoNode(groupInfo)
737
+ };
738
+ const relayNode = findNodeChild(ackNode, 'relay');
739
+ if (relayNode) {
740
+ update.relay = parseGroupRelayNode(relayNode);
741
+ }
742
+ return update;
743
+ }
744
+ export function parseGroupUpdate(node) {
745
+ const groupInfo = findNodeChild(node, 'group_info');
746
+ if (!groupInfo) {
747
+ throw new Error('group_update is missing group_info');
748
+ }
749
+ const update = {
750
+ callId: node.attrs?.['call-id'],
751
+ callCreator: node.attrs?.['call-creator'],
752
+ ...parseGroupInfoNode(groupInfo)
753
+ };
754
+ update.avUpgradable = findNodeChild(node, 'av_upgrade')?.attrs?.['av-upgradable'] === '1';
755
+ const relayNode = findNodeChild(node, 'relay');
756
+ if (relayNode) {
757
+ update.relay = parseGroupRelayNode(relayNode);
758
+ }
759
+ return update;
760
+ }
761
+ export function parseGroupEncRekey(node) {
762
+ const encopt = findNodeChild(node, 'encopt');
763
+ const enc = findNodeChild(node, 'enc');
764
+ if (!encopt || !enc) {
765
+ throw new Error('enc_rekey is missing encopt or enc');
766
+ }
767
+ if (readRequiredUint(encopt, 'keygen') !== 2) {
768
+ throw new Error('unsupported key generation');
769
+ }
770
+ const encType = enc.attrs?.type;
771
+ if ((encType !== 'msg' && encType !== 'pkmsg') || readRequiredUint(enc, 'v') !== 2) {
772
+ throw new Error('unsupported group rekey encryption');
773
+ }
774
+ if (!(enc.content instanceof Uint8Array)) {
775
+ throw new Error('enc_rekey ciphertext is missing');
776
+ }
777
+ return {
778
+ callId: node.attrs?.['call-id'],
779
+ callCreator: node.attrs?.['call-creator'],
780
+ transactionId: readRequiredUint(node, 'transaction-id'),
781
+ encType,
782
+ ciphertext: enc.content
783
+ };
784
+ }
785
+ export function buildCallControlAckNode(node, childTag) {
786
+ const { id, from, participant, recipient } = node.attrs ?? {};
787
+ if (!id || !from || !childTag) {
788
+ return null;
789
+ }
790
+ return buildAckNode({
791
+ kind: 'custom',
792
+ ackClass: 'call',
793
+ to: from,
794
+ id,
795
+ type: childTag,
796
+ participant: participant && participant !== from ? participant : undefined,
797
+ recipient: recipient || undefined
798
+ });
799
+ }
800
+ function normalizeLinkMedia(media) {
801
+ if (media !== 'audio' && media !== 'video') {
802
+ throw new Error(`invalid call link media "${media}"`);
803
+ }
804
+ return media;
805
+ }
806
+ export function buildCallLinkUrl(token, media) {
807
+ return `https://call.whatsapp.com/${normalizeLinkMedia(media) === 'video' ? 'video' : 'voice'}/${token}`;
808
+ }
809
+ export function parseCallLink(raw) {
810
+ const text = String(raw ?? '').trim();
811
+ if (!text) {
812
+ throw new Error('call link token is required');
813
+ }
814
+ if (!text.includes('://')) {
815
+ if (text.includes('/')) {
816
+ throw new Error('invalid call link token');
817
+ }
818
+ return { token: text, media: undefined };
819
+ }
820
+ const url = new URL(text);
821
+ const parts = url.pathname.split('/').filter(Boolean);
822
+ if (url.protocol !== 'https:' || url.hostname !== 'call.whatsapp.com' || parts.length !== 2 || !['audio', 'video', 'voice'].includes(parts[0])) {
823
+ throw new Error('invalid WhatsApp call link');
824
+ }
825
+ return { token: parts[1], media: parts[0] === 'video' ? 'video' : 'audio' };
826
+ }
827
+ export function parseCallLinkToken(raw) {
828
+ return parseCallLink(raw).token;
829
+ }
830
+ function buildCallServiceRequest(requestId, action) {
831
+ return { tag: 'call', attrs: { to: '@call', id: requestId }, content: [action] };
832
+ }
833
+ export function buildCallLinkCreateStanza(media, requestId) {
834
+ return buildCallServiceRequest(requestId, { tag: 'link_create', attrs: { media: normalizeLinkMedia(media) } });
835
+ }
836
+ export function buildCallLinkQueryStanza(token, media, requestId) {
837
+ return buildCallServiceRequest(requestId, { tag: 'link_query', attrs: { token, media: normalizeLinkMedia(media) } });
838
+ }
839
+ export function buildCallLinkJoinStanza(token, media, requestId) {
840
+ const content = [{ tag: 'audio', attrs: { enc: 'opus', rate: '16000' } }];
841
+ if (normalizeLinkMedia(media) === 'video') {
842
+ content.push({ tag: 'video', attrs: { dec: 'H264', device_orientation: '0' } });
843
+ }
844
+ content.push({ tag: 'net', attrs: { medium: '2' } }, { tag: 'capability', attrs: { ver: '1' }, content: groupCapabilityOffer });
845
+ return buildCallServiceRequest(requestId, { tag: 'link_join', attrs: { token, media }, content });
846
+ }
847
+ export function buildWaitingRoomRequestStanza(tag, callId, creator, requestId, extraAttrs = {}, children = undefined) {
848
+ return {
849
+ tag: 'call',
850
+ attrs: { to: callJidFor(callId), id: requestId },
851
+ content: [{ tag, attrs: { 'call-id': callId, 'call-creator': creator, ...extraAttrs }, content: children }]
852
+ };
853
+ }
854
+ function validateCallLinkAck(node, expectedType) {
855
+ if (!node || node.tag !== 'ack' || node.attrs?.class !== 'call' || node.attrs?.type !== expectedType) {
856
+ const reason = node?.attrs?.error ? ` (error ${node.attrs.error})` : '';
857
+ throw new Error(`unexpected ${expectedType} response${reason}`);
858
+ }
859
+ return findNodeChild(node, expectedType);
860
+ }
861
+ export function parseCallLinkCreateAck(node) {
862
+ const child = validateCallLinkAck(node, 'link_create');
863
+ const token = child?.attrs?.token;
864
+ if (!token) {
865
+ throw new Error('link_create response has no token');
866
+ }
867
+ return { token, media: normalizeLinkMedia(child.attrs.media) };
868
+ }
869
+ export function parseCallLinkQueryAck(node) {
870
+ const child = validateCallLinkAck(node, 'link_query');
871
+ if (!child) {
872
+ throw new Error('link_query response has no payload');
873
+ }
874
+ const room = findNodeChild(child, 'waiting_room');
875
+ if (!room) {
876
+ throw new Error('link_query response has no waiting_room');
877
+ }
878
+ return {
879
+ token: child.attrs?.token,
880
+ media: normalizeLinkMedia(child.attrs?.media),
881
+ creator: child.attrs?.link_creator,
882
+ creatorPn: child.attrs?.link_creator_pn,
883
+ waitingRoomEnabled: room.attrs?.enabled === '1',
884
+ isAdmin: room.attrs?.is_admin === '1'
885
+ };
886
+ }
887
+ function parseWaitingRoomNode(node) {
888
+ const transactionId = node.attrs?.['transaction-id'];
889
+ return {
890
+ callId: node.attrs?.['call-id'],
891
+ callCreator: node.attrs?.['call-creator'],
892
+ linkToken: node.attrs?.['link-token'],
893
+ media: normalizeLinkMedia(node.attrs?.media),
894
+ enabled: node.attrs?.enabled === '1',
895
+ isAdmin: node.attrs?.is_admin === '1',
896
+ transactionId: transactionId ? Number(transactionId) : 0,
897
+ users: getNodeChildrenByTag(node, 'user').map((user) => ({
898
+ jid: user.attrs?.jid,
899
+ pn: user.attrs?.user_pn,
900
+ state: user.attrs?.state || ''
901
+ }))
902
+ };
903
+ }
904
+ export function parseCallLinkJoinAck(node) {
905
+ validateCallLinkAck(node, 'link_join');
906
+ const waitingNode = findNodeChild(node, 'waiting_room');
907
+ const result = { waitingRoom: waitingNode ? parseWaitingRoomNode(waitingNode) : null, group: parseInitialGroupAck(node) };
908
+ if (!result.waitingRoom && !result.group) {
909
+ throw new Error('link_join response has no group_info or waiting_room');
910
+ }
911
+ result.callId = result.waitingRoom?.callId || result.group.callId;
912
+ result.callCreator = result.waitingRoom?.callCreator || result.group.callCreator;
913
+ result.inWaitingRoom = !!result.waitingRoom && result.waitingRoom.enabled && !result.group;
914
+ return result;
915
+ }
916
+ export function parseWaitingRoomUpdate(node) {
917
+ const child = findNodeChild(node, 'waiting_room');
918
+ if (!child) {
919
+ throw new Error('waiting_room_update has no waiting_room');
920
+ }
921
+ return parseWaitingRoomNode(child);
922
+ }
package/src/voip/types.js CHANGED
@@ -5,6 +5,7 @@ export var CallState;
5
5
  CallState["IncomingRinging"] = "incoming_ringing";
6
6
  CallState["Connecting"] = "connecting";
7
7
  CallState["Active"] = "active";
8
+ CallState["WaitingRoom"] = "waiting_room";
8
9
  CallState["OnHold"] = "on_hold";
9
10
  CallState["Ended"] = "ended";
10
11
  })(CallState || (CallState = {}));
@@ -174,6 +174,9 @@ export async function createVoipDeps(sock) {
174
174
  lowLevelCoordinator: {
175
175
  async sendNode(node) {
176
176
  await sock.sendNode(node);
177
+ },
178
+ async query(node, timeoutMs) {
179
+ return sock.query(node, timeoutMs);
177
180
  }
178
181
  },
179
182
  signalDeviceSync: {
@@ -191,6 +194,10 @@ export async function createVoipDeps(sock) {
191
194
  }
192
195
  return out;
193
196
  },
197
+ async getDevices(jids) {
198
+ const devices = await sock.getUSyncDevices(jids, true, false);
199
+ return devices.map((device) => device.jid).filter(Boolean);
200
+ },
194
201
  async queryLidsByPhoneJids(jids) {
195
202
  const out = [];
196
203
  for (const jid of jids) {