@zervonexx/baileys 5.0.0 → 5.0.1

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 (125) hide show
  1. package/LICENSE +22 -22
  2. package/README.md +4112 -4112
  3. package/WAProto/WAProtoCompile.js +322 -322
  4. package/WAProto/fetcher.js +67 -67
  5. package/WAProto/index.js +95 -95
  6. package/WAProto/parser.js +333 -333
  7. package/lib/Builders/AIRich.js +673 -673
  8. package/lib/Builders/auto.js +49 -49
  9. package/lib/Builders/base.js +144 -144
  10. package/lib/Builders/builders.js +588 -588
  11. package/lib/Builders/index.js +3 -3
  12. package/lib/Defaults/index.js +248 -248
  13. package/lib/Signal/index.js +2 -2
  14. package/lib/Signal/libsignal.js +526 -526
  15. package/lib/Signal/lid-mapping.js +282 -282
  16. package/lib/Socket/Client/index.js +1 -1
  17. package/lib/Socket/Client/types.js +9 -9
  18. package/lib/Socket/Client/websocket.js +83 -83
  19. package/lib/Socket/business.js +151 -151
  20. package/lib/Socket/chats.js +854 -854
  21. package/lib/Socket/communities.js +146 -146
  22. package/lib/Socket/groups.js +293 -293
  23. package/lib/Socket/index.js +14 -14
  24. package/lib/Socket/messages-recv.js +993 -993
  25. package/lib/Socket/messages-send.js +722 -722
  26. package/lib/Socket/mex.js +33 -33
  27. package/lib/Socket/newsletter.js +783 -783
  28. package/lib/Socket/registration.js +154 -154
  29. package/lib/Socket/socket.js +797 -797
  30. package/lib/Socket/spam-report.js +143 -143
  31. package/lib/Socket/username.js +81 -81
  32. package/lib/Socket/zervonex-handler.js +57 -57
  33. package/lib/Store/index.js +6 -6
  34. package/lib/Store/make-cache-manager-store.js +80 -80
  35. package/lib/Store/make-in-memory-store.js +426 -426
  36. package/lib/Store/make-ordered-dictionary.js +81 -81
  37. package/lib/Store/object-repository.js +30 -30
  38. package/lib/Store/reporting-info-store.js +37 -37
  39. package/lib/Types/Auth.js +1 -1
  40. package/lib/Types/Bussines.js +1 -1
  41. package/lib/Types/Call.js +1 -1
  42. package/lib/Types/Chat.js +7 -7
  43. package/lib/Types/Contact.js +1 -1
  44. package/lib/Types/Events.js +1 -1
  45. package/lib/Types/GroupMetadata.js +1 -1
  46. package/lib/Types/Label.js +24 -24
  47. package/lib/Types/LabelAssociation.js +6 -6
  48. package/lib/Types/Message.js +14 -14
  49. package/lib/Types/Newsletter.js +99 -99
  50. package/lib/Types/Product.js +1 -1
  51. package/lib/Types/Signal.js +1 -1
  52. package/lib/Types/Socket.js +14 -14
  53. package/lib/Types/State.js +26 -26
  54. package/lib/Types/USync.js +1 -1
  55. package/lib/Types/index.js +30 -30
  56. package/lib/Utils/auth-utils.js +159 -159
  57. package/lib/Utils/baileys-event-stream.js +32 -32
  58. package/lib/Utils/bot-capabilities.js +40 -40
  59. package/lib/Utils/bot-planning-replay.js +43 -43
  60. package/lib/Utils/browser-utils.js +29 -29
  61. package/lib/Utils/business.js +74 -74
  62. package/lib/Utils/chat-utils.js +316 -316
  63. package/lib/Utils/companion-reg-client-utils.js +19 -19
  64. package/lib/Utils/consumer-application.js +37 -37
  65. package/lib/Utils/crypto.js +52 -52
  66. package/lib/Utils/cstoken.js +14 -14
  67. package/lib/Utils/decode-wa-message.js +199 -199
  68. package/lib/Utils/event-buffer.js +272 -272
  69. package/lib/Utils/extras.js +186 -186
  70. package/lib/Utils/generics.js +194 -194
  71. package/lib/Utils/history.js +50 -50
  72. package/lib/Utils/identity-change-handler.js +18 -18
  73. package/lib/Utils/index.js +40 -40
  74. package/lib/Utils/link-preview.js +50 -50
  75. package/lib/Utils/logger.js +2 -2
  76. package/lib/Utils/lt-hash.js +3 -3
  77. package/lib/Utils/make-mutex.js +15 -15
  78. package/lib/Utils/message-composer.js +61 -61
  79. package/lib/Utils/message-retry-manager.js +47 -47
  80. package/lib/Utils/messages-media.js +501 -501
  81. package/lib/Utils/messages.js +942 -942
  82. package/lib/Utils/meta-ai-msmsg.js +121 -121
  83. package/lib/Utils/meta-compositing.js +74 -74
  84. package/lib/Utils/modern-messages.js +234 -234
  85. package/lib/Utils/native-flow.js +80 -80
  86. package/lib/Utils/noise-handler.js +160 -160
  87. package/lib/Utils/pre-key-manager.js +75 -75
  88. package/lib/Utils/process-message.js +400 -400
  89. package/lib/Utils/reporting-utils.js +170 -170
  90. package/lib/Utils/signal.js +166 -166
  91. package/lib/Utils/spam-report-utils.js +165 -165
  92. package/lib/Utils/sync-action-utils.js +33 -33
  93. package/lib/Utils/tc-token-utils.js +153 -153
  94. package/lib/Utils/use-keyv-auth-state.js +199 -199
  95. package/lib/Utils/use-multi-file-auth-state.js +83 -83
  96. package/lib/Utils/validate-connection.js +171 -171
  97. package/lib/WABinary/constants.js +1320 -1320
  98. package/lib/WABinary/decode.js +151 -151
  99. package/lib/WABinary/encode.js +139 -139
  100. package/lib/WABinary/generic-utils.js +202 -202
  101. package/lib/WABinary/index.js +6 -6
  102. package/lib/WABinary/jid-utils.js +235 -235
  103. package/lib/WABinary/types.js +4 -4
  104. package/lib/WAM/BinaryInfo.js +9 -9
  105. package/lib/WAM/constants.js +22852 -22852
  106. package/lib/WAM/encode.js +149 -149
  107. package/lib/WAM/index.js +3 -3
  108. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +30 -30
  109. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +48 -48
  110. package/lib/WAUSync/Protocols/USyncContactProtocol.js +23 -23
  111. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +28 -28
  112. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +15 -15
  113. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +24 -24
  114. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +9 -9
  115. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +21 -21
  116. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +19 -19
  117. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +19 -19
  118. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +22 -22
  119. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +16 -16
  120. package/lib/WAUSync/Protocols/index.js +12 -12
  121. package/lib/WAUSync/USyncQuery.js +88 -88
  122. package/lib/WAUSync/USyncUser.js +20 -20
  123. package/lib/WAUSync/index.js +3 -3
  124. package/lib/index.js +66 -66
  125. package/package.json +191 -192
@@ -1,154 +1,154 @@
1
- import { randomBytes } from 'crypto'
2
- import { getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isJidMetaAI, isLidUser, isPnUser, jidNormalizedUser } from '../WABinary/index.js'
3
- import { unixTimestampSeconds } from './generics.js'
4
-
5
- // ─── Constants ────────────────────────────────────────────────────────────────
6
- export const TC_TOKEN_INDEX_KEY = '__index'
7
- const BOT_PHONE_REGEX = /^1313555\d{4}$|^131655500\d{2}$/
8
- const TC_TOKEN_BUCKET_DURATION = 604800 // 7 days
9
- const TC_TOKEN_NUM_BUCKETS = 4 // ~28-day rolling window
10
- const TC_TOKEN_MIN_BYTES = 1
11
- const TC_TOKEN_MAX_BYTES = 120 // DMW layer constraint
12
- const TC_TOKEN_MAX_RECIPIENTS = 5 // feature flag 20606 default cap
13
-
14
- const currentBucket = () => Math.floor(unixTimestampSeconds() / TC_TOKEN_BUCKET_DURATION)
15
- const generateTcToken = () => randomBytes(32) // local pre-seed fallback only; real tokens are server-issued
16
-
17
- // ─── JID helpers ──────────────────────────────────────────────────────────────
18
-
19
- export const isRegularUser = jid => {
20
- if (!jid) return false
21
- const user = jid.split('@')[0] ?? ''
22
- if (user === '0' || BOT_PHONE_REGEX.test(user) || isJidMetaAI(jid)) return false
23
- return !!(isPnUser(jid) || isLidUser(jid) || isHostedPnUser(jid) || isHostedLidUser(jid) || jid.endsWith('@c.us'))
24
- }
25
-
26
- // storage key is always LID when resolvable
27
- export const resolveTcTokenJid = async (jid, getLIDForPN) =>
28
- isLidUser(jid) ? jid : (await getLIDForPN(jid) || null)
29
-
30
- // bidirectional — respects useLidForEncryption flag
31
- export const resolveIssuanceJid = async (jid, issueToLid, getLIDForPN, getPNForLID) => {
32
- if (issueToLid) return isLidUser(jid) ? jid : (await getLIDForPN(jid)) ?? jid
33
- if (!isLidUser(jid)) return jid
34
- return getPNForLID ? (await getPNForLID(jid)) ?? jid : jid
35
- }
36
-
37
- // ─── Expiry ───────────────────────────────────────────────────────────────────
38
-
39
- export const isTcTokenExpired = timestamp => {
40
- if (timestamp == null) return true
41
- const ts = typeof timestamp === 'string' ? parseInt(timestamp) : timestamp
42
- return isNaN(ts) || ts < (currentBucket() - (TC_TOKEN_NUM_BUCKETS - 1)) * TC_TOKEN_BUCKET_DURATION
43
- }
44
-
45
- // re-issue only if sender crossed into a new bucket since last issuance
46
- export const shouldSendNewTcToken = senderTimestamp => {
47
- if (senderTimestamp === undefined) return true
48
- return currentBucket() > Math.floor(senderTimestamp / TC_TOKEN_BUCKET_DURATION)
49
- }
50
-
51
- // ─── Index ────────────────────────────────────────────────────────────────────
52
-
53
- export const readTcTokenIndex = async keys => {
54
- for (const key of [TC_TOKEN_INDEX_KEY, 'index']) {
55
- const entry = (await keys.get('tctoken', [key]))[key]
56
- if (!entry?.token?.length) continue
57
- try {
58
- const parsed = JSON.parse(Buffer.from(entry.token).toString())
59
- if (!Array.isArray(parsed)) continue
60
- return parsed.filter(j => typeof j === 'string' && j.length > 0 && j !== TC_TOKEN_INDEX_KEY && j !== 'index')
61
- } catch { continue }
62
- }
63
- return []
64
- }
65
-
66
- export const buildMergedTcTokenIndexWrite = async (keys, addedJids) => {
67
- const merged = new Set(await readTcTokenIndex(keys))
68
- for (const jid of addedJids) if (jid && jid !== TC_TOKEN_INDEX_KEY && jid !== 'index') merged.add(jid)
69
- return { [TC_TOKEN_INDEX_KEY]: { token: Buffer.from(JSON.stringify([...merged])) } }
70
- }
71
-
72
- // ─── Pre-seed ─────────────────────────────────────────────────────────────────
73
-
74
- export const preSeedTcToken = async ({ authState, jid, getLIDForPN, logger }) => {
75
- const tcTokenJid = await resolveTcTokenJid(jid, getLIDForPN)
76
- const existing = await authState.keys.get('tctoken', [tcTokenJid])
77
- if (existing[tcTokenJid]?.token?.length) return { token: existing[tcTokenJid].token, storageJid: tcTokenJid }
78
- const token = generateTcToken()
79
- const timestamp = String(unixTimestampSeconds())
80
- const indexWrite = await buildMergedTcTokenIndexWrite(authState.keys, [tcTokenJid])
81
- await authState.keys.set({ tctoken: { [tcTokenJid]: { ...(existing[tcTokenJid] || {}), token, timestamp }, ...indexWrite } })
82
- logger?.debug({ jid, tcTokenJid }, 'pre-seeded locally generated tctoken')
83
- return { token, storageJid: tcTokenJid }
84
- }
85
-
86
- // ─── Outgoing nodes ───────────────────────────────────────────────────────────
87
- // confirmed wire format: <tctoken>bytes</tctoken> — flat, identical to fanout format, no smax:any wrapper
88
- // timestamp attr is internal only, never sent on wire
89
- export const buildTcTokenFromJid = async ({ authState, jid, baseContent = [], getLIDForPN }) => {
90
- try {
91
- const storageJid = await resolveTcTokenJid(jid, getLIDForPN)
92
- const entry = (await authState.keys.get('tctoken', [storageJid]))?.[storageJid]
93
- const { token: tcTokenBuffer, timestamp, senderTimestamp } = entry ?? {}
94
- if (!tcTokenBuffer?.length || timestamp === undefined || isTcTokenExpired(timestamp)) {
95
- if (tcTokenBuffer) {
96
- const cleared = senderTimestamp !== undefined ? { token: Buffer.alloc(0), senderTimestamp } : null
97
- await authState.keys.set({ tctoken: { [storageJid]: cleared } })
98
- }
99
- return baseContent.length > 0 ? baseContent : undefined
100
- }
101
- if (tcTokenBuffer.length < TC_TOKEN_MIN_BYTES || tcTokenBuffer.length > TC_TOKEN_MAX_BYTES) return baseContent.length > 0 ? baseContent : undefined
102
- baseContent.push({ tag: 'tctoken', attrs: {}, content: tcTokenBuffer })
103
- return baseContent
104
- } catch { return baseContent.length > 0 ? baseContent : undefined }
105
- }
106
-
107
- // fanout <to> node — confirmed wire format: <tctoken>bytes</tctoken> (no smax:any wrapper)
108
- // enforces per-send JID dedup (EOC.A01 Set guard) and flag-20606 recipient cap
109
- export const buildFanoutTcTokenNode = ({ tokenBuffer, recipientsSeen, userJid }) => {
110
- if (
111
- !tokenBuffer?.length
112
- || tokenBuffer.length < TC_TOKEN_MIN_BYTES
113
- || tokenBuffer.length > TC_TOKEN_MAX_BYTES
114
- || recipientsSeen.size >= TC_TOKEN_MAX_RECIPIENTS
115
- || recipientsSeen.has(userJid)
116
- ) return null
117
- recipientsSeen.add(userJid)
118
- return { tag: 'tctoken', attrs: {}, content: tokenBuffer }
119
- }
120
-
121
- // ─── Incoming storage ─────────────────────────────────────────────────────────
122
-
123
- // handles both IQ result and privacy_token notification (same <tokens> structure)
124
- // wire format: <token type="trusted_contact" t="timestamp">bytes</token>
125
- export const storeTcTokensFromIqResult = async ({ result, fallbackJid, keys, getLIDForPN, onNewJidStored }) => {
126
- const tokensNode = getBinaryNodeChild(result, 'tokens')
127
- if (!tokensNode) return
128
- for (const tokenNode of getBinaryNodeChildren(tokensNode, 'token')) {
129
- if (tokenNode.attrs.type !== 'trusted_contact') continue
130
- if (!(tokenNode.content instanceof Uint8Array) || !tokenNode.content.length) continue
131
- const tokenBytes = tokenNode.content
132
- if (tokenBytes.length > TC_TOKEN_MAX_BYTES) continue
133
- const rawJid = jidNormalizedUser(fallbackJid || tokenNode.attrs.jid)
134
- if (!isRegularUser(rawJid)) continue
135
- const storageJid = await resolveTcTokenJid(rawJid, getLIDForPN)
136
- const existingEntry = (await keys.get('tctoken', [storageJid]))[storageJid]
137
- const existingTs = existingEntry?.timestamp ? Number(existingEntry.timestamp) : 0
138
- const incomingTs = tokenNode.attrs.t ? Number(tokenNode.attrs.t) : 0
139
- if (!incomingTs || (existingTs > 0 && existingTs > incomingTs)) continue
140
- await keys.set({ tctoken: { [storageJid]: { ...existingEntry, token: Buffer.from(tokenBytes), timestamp: tokenNode.attrs.t } } })
141
- onNewJidStored?.(storageJid)
142
- }
143
- }
144
-
145
- // ─── Content binding ──────────────────────────────────────────────────────────
146
-
147
- // URL-type messages only — confirmed from AbstractC2052DmX.A00()
148
- // wire format: <content_binding>bytes</content_binding> (flat, no wrapper)
149
- export const buildContentBindingNode = ({ userJid, contentBindingMap, messageType }) => {
150
- if (messageType !== 'url' || !contentBindingMap?.has(userJid)) return null
151
- const bytes = contentBindingMap.get(userJid)
152
- if (!bytes?.length) return null
153
- return { tag: 'content_binding', attrs: {}, content: bytes }
1
+ import { randomBytes } from 'crypto'
2
+ import { getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isJidMetaAI, isLidUser, isPnUser, jidNormalizedUser } from '../WABinary/index.js'
3
+ import { unixTimestampSeconds } from './generics.js'
4
+
5
+ // ─── Constants ────────────────────────────────────────────────────────────────
6
+ export const TC_TOKEN_INDEX_KEY = '__index'
7
+ const BOT_PHONE_REGEX = /^1313555\d{4}$|^131655500\d{2}$/
8
+ const TC_TOKEN_BUCKET_DURATION = 604800 // 7 days
9
+ const TC_TOKEN_NUM_BUCKETS = 4 // ~28-day rolling window
10
+ const TC_TOKEN_MIN_BYTES = 1
11
+ const TC_TOKEN_MAX_BYTES = 120 // DMW layer constraint
12
+ const TC_TOKEN_MAX_RECIPIENTS = 5 // feature flag 20606 default cap
13
+
14
+ const currentBucket = () => Math.floor(unixTimestampSeconds() / TC_TOKEN_BUCKET_DURATION)
15
+ const generateTcToken = () => randomBytes(32) // local pre-seed fallback only; real tokens are server-issued
16
+
17
+ // ─── JID helpers ──────────────────────────────────────────────────────────────
18
+
19
+ export const isRegularUser = jid => {
20
+ if (!jid) return false
21
+ const user = jid.split('@')[0] ?? ''
22
+ if (user === '0' || BOT_PHONE_REGEX.test(user) || isJidMetaAI(jid)) return false
23
+ return !!(isPnUser(jid) || isLidUser(jid) || isHostedPnUser(jid) || isHostedLidUser(jid) || jid.endsWith('@c.us'))
24
+ }
25
+
26
+ // storage key is always LID when resolvable
27
+ export const resolveTcTokenJid = async (jid, getLIDForPN) =>
28
+ isLidUser(jid) ? jid : (await getLIDForPN(jid) || null)
29
+
30
+ // bidirectional — respects useLidForEncryption flag
31
+ export const resolveIssuanceJid = async (jid, issueToLid, getLIDForPN, getPNForLID) => {
32
+ if (issueToLid) return isLidUser(jid) ? jid : (await getLIDForPN(jid)) ?? jid
33
+ if (!isLidUser(jid)) return jid
34
+ return getPNForLID ? (await getPNForLID(jid)) ?? jid : jid
35
+ }
36
+
37
+ // ─── Expiry ───────────────────────────────────────────────────────────────────
38
+
39
+ export const isTcTokenExpired = timestamp => {
40
+ if (timestamp == null) return true
41
+ const ts = typeof timestamp === 'string' ? parseInt(timestamp) : timestamp
42
+ return isNaN(ts) || ts < (currentBucket() - (TC_TOKEN_NUM_BUCKETS - 1)) * TC_TOKEN_BUCKET_DURATION
43
+ }
44
+
45
+ // re-issue only if sender crossed into a new bucket since last issuance
46
+ export const shouldSendNewTcToken = senderTimestamp => {
47
+ if (senderTimestamp === undefined) return true
48
+ return currentBucket() > Math.floor(senderTimestamp / TC_TOKEN_BUCKET_DURATION)
49
+ }
50
+
51
+ // ─── Index ────────────────────────────────────────────────────────────────────
52
+
53
+ export const readTcTokenIndex = async keys => {
54
+ for (const key of [TC_TOKEN_INDEX_KEY, 'index']) {
55
+ const entry = (await keys.get('tctoken', [key]))[key]
56
+ if (!entry?.token?.length) continue
57
+ try {
58
+ const parsed = JSON.parse(Buffer.from(entry.token).toString())
59
+ if (!Array.isArray(parsed)) continue
60
+ return parsed.filter(j => typeof j === 'string' && j.length > 0 && j !== TC_TOKEN_INDEX_KEY && j !== 'index')
61
+ } catch { continue }
62
+ }
63
+ return []
64
+ }
65
+
66
+ export const buildMergedTcTokenIndexWrite = async (keys, addedJids) => {
67
+ const merged = new Set(await readTcTokenIndex(keys))
68
+ for (const jid of addedJids) if (jid && jid !== TC_TOKEN_INDEX_KEY && jid !== 'index') merged.add(jid)
69
+ return { [TC_TOKEN_INDEX_KEY]: { token: Buffer.from(JSON.stringify([...merged])) } }
70
+ }
71
+
72
+ // ─── Pre-seed ─────────────────────────────────────────────────────────────────
73
+
74
+ export const preSeedTcToken = async ({ authState, jid, getLIDForPN, logger }) => {
75
+ const tcTokenJid = await resolveTcTokenJid(jid, getLIDForPN)
76
+ const existing = await authState.keys.get('tctoken', [tcTokenJid])
77
+ if (existing[tcTokenJid]?.token?.length) return { token: existing[tcTokenJid].token, storageJid: tcTokenJid }
78
+ const token = generateTcToken()
79
+ const timestamp = String(unixTimestampSeconds())
80
+ const indexWrite = await buildMergedTcTokenIndexWrite(authState.keys, [tcTokenJid])
81
+ await authState.keys.set({ tctoken: { [tcTokenJid]: { ...(existing[tcTokenJid] || {}), token, timestamp }, ...indexWrite } })
82
+ logger?.debug({ jid, tcTokenJid }, 'pre-seeded locally generated tctoken')
83
+ return { token, storageJid: tcTokenJid }
84
+ }
85
+
86
+ // ─── Outgoing nodes ───────────────────────────────────────────────────────────
87
+ // confirmed wire format: <tctoken>bytes</tctoken> — flat, identical to fanout format, no smax:any wrapper
88
+ // timestamp attr is internal only, never sent on wire
89
+ export const buildTcTokenFromJid = async ({ authState, jid, baseContent = [], getLIDForPN }) => {
90
+ try {
91
+ const storageJid = await resolveTcTokenJid(jid, getLIDForPN)
92
+ const entry = (await authState.keys.get('tctoken', [storageJid]))?.[storageJid]
93
+ const { token: tcTokenBuffer, timestamp, senderTimestamp } = entry ?? {}
94
+ if (!tcTokenBuffer?.length || timestamp === undefined || isTcTokenExpired(timestamp)) {
95
+ if (tcTokenBuffer) {
96
+ const cleared = senderTimestamp !== undefined ? { token: Buffer.alloc(0), senderTimestamp } : null
97
+ await authState.keys.set({ tctoken: { [storageJid]: cleared } })
98
+ }
99
+ return baseContent.length > 0 ? baseContent : undefined
100
+ }
101
+ if (tcTokenBuffer.length < TC_TOKEN_MIN_BYTES || tcTokenBuffer.length > TC_TOKEN_MAX_BYTES) return baseContent.length > 0 ? baseContent : undefined
102
+ baseContent.push({ tag: 'tctoken', attrs: {}, content: tcTokenBuffer })
103
+ return baseContent
104
+ } catch { return baseContent.length > 0 ? baseContent : undefined }
105
+ }
106
+
107
+ // fanout <to> node — confirmed wire format: <tctoken>bytes</tctoken> (no smax:any wrapper)
108
+ // enforces per-send JID dedup (EOC.A01 Set guard) and flag-20606 recipient cap
109
+ export const buildFanoutTcTokenNode = ({ tokenBuffer, recipientsSeen, userJid }) => {
110
+ if (
111
+ !tokenBuffer?.length
112
+ || tokenBuffer.length < TC_TOKEN_MIN_BYTES
113
+ || tokenBuffer.length > TC_TOKEN_MAX_BYTES
114
+ || recipientsSeen.size >= TC_TOKEN_MAX_RECIPIENTS
115
+ || recipientsSeen.has(userJid)
116
+ ) return null
117
+ recipientsSeen.add(userJid)
118
+ return { tag: 'tctoken', attrs: {}, content: tokenBuffer }
119
+ }
120
+
121
+ // ─── Incoming storage ─────────────────────────────────────────────────────────
122
+
123
+ // handles both IQ result and privacy_token notification (same <tokens> structure)
124
+ // wire format: <token type="trusted_contact" t="timestamp">bytes</token>
125
+ export const storeTcTokensFromIqResult = async ({ result, fallbackJid, keys, getLIDForPN, onNewJidStored }) => {
126
+ const tokensNode = getBinaryNodeChild(result, 'tokens')
127
+ if (!tokensNode) return
128
+ for (const tokenNode of getBinaryNodeChildren(tokensNode, 'token')) {
129
+ if (tokenNode.attrs.type !== 'trusted_contact') continue
130
+ if (!(tokenNode.content instanceof Uint8Array) || !tokenNode.content.length) continue
131
+ const tokenBytes = tokenNode.content
132
+ if (tokenBytes.length > TC_TOKEN_MAX_BYTES) continue
133
+ const rawJid = jidNormalizedUser(fallbackJid || tokenNode.attrs.jid)
134
+ if (!isRegularUser(rawJid)) continue
135
+ const storageJid = await resolveTcTokenJid(rawJid, getLIDForPN)
136
+ const existingEntry = (await keys.get('tctoken', [storageJid]))[storageJid]
137
+ const existingTs = existingEntry?.timestamp ? Number(existingEntry.timestamp) : 0
138
+ const incomingTs = tokenNode.attrs.t ? Number(tokenNode.attrs.t) : 0
139
+ if (!incomingTs || (existingTs > 0 && existingTs > incomingTs)) continue
140
+ await keys.set({ tctoken: { [storageJid]: { ...existingEntry, token: Buffer.from(tokenBytes), timestamp: tokenNode.attrs.t } } })
141
+ onNewJidStored?.(storageJid)
142
+ }
143
+ }
144
+
145
+ // ─── Content binding ──────────────────────────────────────────────────────────
146
+
147
+ // URL-type messages only — confirmed from AbstractC2052DmX.A00()
148
+ // wire format: <content_binding>bytes</content_binding> (flat, no wrapper)
149
+ export const buildContentBindingNode = ({ userJid, contentBindingMap, messageType }) => {
150
+ if (messageType !== 'url' || !contentBindingMap?.has(userJid)) return null
151
+ const bytes = contentBindingMap.get(userJid)
152
+ if (!bytes?.length) return null
153
+ return { tag: 'content_binding', attrs: {}, content: bytes }
154
154
  }