@openclaw/whatsapp 2026.5.2-beta.2 → 2026.5.3-beta.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 (301) hide show
  1. package/dist/access-control-BQ3tCkH8.js +288 -0
  2. package/dist/account-config-CNQ33oav.js +47 -0
  3. package/dist/account-ids-DG18xddX.js +5 -0
  4. package/dist/accounts-BDqgpFEB.js +116 -0
  5. package/dist/action-runtime-DTGNgG-i.js +74 -0
  6. package/dist/action-runtime-api.js +2 -0
  7. package/dist/action-runtime.runtime.js +2 -0
  8. package/dist/active-listener-N7GFKsuN.js +11 -0
  9. package/dist/agent-tools-login-DpRxLNRB.js +89 -0
  10. package/dist/api.js +148 -0
  11. package/dist/audio-preflight.runtime-Bcdsl_ri.js +7 -0
  12. package/dist/auth-presence.js +32 -0
  13. package/dist/auth-store-BjCb50Ry.js +381 -0
  14. package/dist/channel-DQ-5Xoj9.js +542 -0
  15. package/dist/channel-config-api.js +2 -0
  16. package/dist/channel-plugin-api.js +2 -0
  17. package/dist/channel-react-action-Df20qAy9.js +42 -0
  18. package/dist/channel.runtime-DKXRnA8x.js +55 -0
  19. package/dist/channel.setup-DOHR2BGp.js +20 -0
  20. package/dist/command-policy-O8sRnqUV.js +8 -0
  21. package/dist/config-schema-Dmo66Ubb.js +27 -0
  22. package/dist/connection-controller-BiHAsTM8.js +596 -0
  23. package/dist/connection-controller-registry-D_iIGz5m.js +22 -0
  24. package/dist/constants-DLGCIbfl.js +4 -0
  25. package/dist/constants.js +2 -0
  26. package/dist/contract-api.js +19 -0
  27. package/dist/creds-files-_2V8jzQa.js +19 -0
  28. package/dist/directory-config-DVs4ffXu.js +37 -0
  29. package/dist/directory-contract-api.js +2 -0
  30. package/dist/doctor-A9tXm9Om.js +48 -0
  31. package/dist/doctor-contract-api.js +10 -0
  32. package/dist/group-session-contract-B8QBn0I2.js +15 -0
  33. package/dist/identity-QHAlV7Fu.js +75 -0
  34. package/dist/index.js +18 -0
  35. package/dist/legacy-session-surface-api.js +8 -0
  36. package/dist/legacy-state-migrations-api.js +2 -0
  37. package/dist/light-runtime-api.js +5 -0
  38. package/dist/login-DymdrKca.js +52 -0
  39. package/dist/login-qr-DIS0Iv-7.js +378 -0
  40. package/dist/login-qr-api.js +2 -0
  41. package/dist/login-qr-runtime.js +16 -0
  42. package/dist/monitor-C4Fhg_lD.js +3349 -0
  43. package/dist/normalize-CWYiGkXw.js +2 -0
  44. package/dist/normalize-target-BPVHNsM5.js +74 -0
  45. package/dist/outbound-adapter-BssVnZdz.js +29 -0
  46. package/dist/outbound-base-Bq1UYEK5.js +119 -0
  47. package/dist/outbound-media-contract-CGss_QHy.js +163 -0
  48. package/dist/outbound-payload-test-api.js +2 -0
  49. package/dist/quoted-message-TENQzyxV.js +108 -0
  50. package/dist/reaction-level-CRVEVAfi.js +16 -0
  51. package/dist/reply-resolver.runtime-BRCgoO4C.js +2 -0
  52. package/dist/resolve-outbound-target-CN-Wo6IY.js +39 -0
  53. package/dist/rolldown-runtime-RkAeH_Qm.js +27 -0
  54. package/dist/runtime-6fZ67abR.js +8 -0
  55. package/dist/runtime-api.js +15 -0
  56. package/dist/runtime-group-policy-Gp1lQ0at.js +11 -0
  57. package/dist/secret-contract-api.js +5 -0
  58. package/dist/security-contract-DqH8JDX6.js +26 -0
  59. package/dist/security-contract-api.js +2 -0
  60. package/dist/send-CIyLFxdZ.js +234 -0
  61. package/dist/session-contract-B0efQf9P.js +27 -0
  62. package/dist/session-errors-CSuKZPub.js +63 -0
  63. package/dist/session.runtime-C1eSE_KK.js +13 -0
  64. package/dist/setup-core-DZKvpzbH.js +46 -0
  65. package/dist/setup-entry.js +23 -0
  66. package/dist/setup-plugin-api.js +2 -0
  67. package/dist/setup-surface-ieFnIW4g.js +344 -0
  68. package/dist/shared-D_wzSVar.js +307 -0
  69. package/dist/state-migrations-DnCdvoYD.js +39 -0
  70. package/dist/targets.js +2 -0
  71. package/dist/test-api.js +3 -0
  72. package/dist/text-runtime-C1zNiZeO.js +116 -0
  73. package/package.json +14 -6
  74. package/action-runtime-api.ts +0 -1
  75. package/action-runtime.runtime.ts +0 -1
  76. package/api.ts +0 -213
  77. package/auth-presence.ts +0 -80
  78. package/channel-config-api.ts +0 -1
  79. package/channel-plugin-api.ts +0 -3
  80. package/config-api.ts +0 -4
  81. package/constants.ts +0 -1
  82. package/contract-api.ts +0 -29
  83. package/directory-contract-api.ts +0 -4
  84. package/doctor-contract-api.ts +0 -8
  85. package/index.test.ts +0 -13
  86. package/index.ts +0 -16
  87. package/legacy-session-surface-api.ts +0 -6
  88. package/legacy-state-migrations-api.ts +0 -1
  89. package/light-runtime-api.ts +0 -12
  90. package/login-qr-api.ts +0 -1
  91. package/login-qr-runtime.ts +0 -23
  92. package/outbound-payload-test-api.ts +0 -1
  93. package/runtime-api.ts +0 -84
  94. package/secret-contract-api.ts +0 -4
  95. package/security-contract-api.ts +0 -4
  96. package/setup-entry.test.ts +0 -21
  97. package/setup-entry.ts +0 -21
  98. package/setup-plugin-api.ts +0 -3
  99. package/src/account-config.ts +0 -77
  100. package/src/account-ids.ts +0 -13
  101. package/src/account-types.ts +0 -5
  102. package/src/accounts.test.ts +0 -182
  103. package/src/accounts.ts +0 -176
  104. package/src/accounts.whatsapp-auth.test.ts +0 -59
  105. package/src/action-runtime-target-auth.ts +0 -27
  106. package/src/action-runtime.test.ts +0 -330
  107. package/src/action-runtime.ts +0 -76
  108. package/src/active-listener.test.ts +0 -65
  109. package/src/active-listener.ts +0 -17
  110. package/src/agent-tools-login.test.ts +0 -81
  111. package/src/agent-tools-login.ts +0 -113
  112. package/src/approval-auth.test.ts +0 -24
  113. package/src/approval-auth.ts +0 -27
  114. package/src/auth-store.runtime.ts +0 -1
  115. package/src/auth-store.test.ts +0 -311
  116. package/src/auth-store.ts +0 -502
  117. package/src/auto-reply/config.runtime.ts +0 -16
  118. package/src/auto-reply/constants.ts +0 -1
  119. package/src/auto-reply/deliver-reply.test.ts +0 -843
  120. package/src/auto-reply/deliver-reply.ts +0 -279
  121. package/src/auto-reply/loggers.ts +0 -6
  122. package/src/auto-reply/mentions.ts +0 -131
  123. package/src/auto-reply/monitor/ack-reaction.test.ts +0 -170
  124. package/src/auto-reply/monitor/ack-reaction.ts +0 -99
  125. package/src/auto-reply/monitor/audio-preflight.runtime.ts +0 -9
  126. package/src/auto-reply/monitor/broadcast.ts +0 -153
  127. package/src/auto-reply/monitor/commands.ts +0 -19
  128. package/src/auto-reply/monitor/echo.ts +0 -64
  129. package/src/auto-reply/monitor/group-activation.runtime.ts +0 -1
  130. package/src/auto-reply/monitor/group-activation.test.ts +0 -189
  131. package/src/auto-reply/monitor/group-activation.ts +0 -73
  132. package/src/auto-reply/monitor/group-gating.audio-preflight.test.ts +0 -103
  133. package/src/auto-reply/monitor/group-gating.runtime.ts +0 -8
  134. package/src/auto-reply/monitor/group-gating.ts +0 -217
  135. package/src/auto-reply/monitor/group-members.test.ts +0 -56
  136. package/src/auto-reply/monitor/group-members.ts +0 -65
  137. package/src/auto-reply/monitor/inbound-context.test.ts +0 -97
  138. package/src/auto-reply/monitor/inbound-context.ts +0 -92
  139. package/src/auto-reply/monitor/inbound-dispatch.runtime.ts +0 -21
  140. package/src/auto-reply/monitor/inbound-dispatch.test.ts +0 -895
  141. package/src/auto-reply/monitor/inbound-dispatch.ts +0 -422
  142. package/src/auto-reply/monitor/last-route.test.ts +0 -37
  143. package/src/auto-reply/monitor/last-route.ts +0 -61
  144. package/src/auto-reply/monitor/message-line.runtime.ts +0 -38
  145. package/src/auto-reply/monitor/message-line.ts +0 -54
  146. package/src/auto-reply/monitor/on-message.audio-preflight.test.ts +0 -354
  147. package/src/auto-reply/monitor/on-message.ts +0 -291
  148. package/src/auto-reply/monitor/peer.ts +0 -17
  149. package/src/auto-reply/monitor/process-message.audio-preflight.test.ts +0 -420
  150. package/src/auto-reply/monitor/process-message.test.ts +0 -355
  151. package/src/auto-reply/monitor/process-message.ts +0 -531
  152. package/src/auto-reply/monitor/runtime-api.ts +0 -30
  153. package/src/auto-reply/monitor-state.test.ts +0 -64
  154. package/src/auto-reply/monitor-state.ts +0 -106
  155. package/src/auto-reply/monitor.ts +0 -600
  156. package/src/auto-reply/reply-resolver.runtime.ts +0 -1
  157. package/src/auto-reply/types.ts +0 -48
  158. package/src/auto-reply/util.ts +0 -63
  159. package/src/auto-reply/web-auto-reply-monitor.test.ts +0 -687
  160. package/src/auto-reply/web-auto-reply-utils.test.ts +0 -392
  161. package/src/auto-reply.broadcast-groups.combined.test.ts +0 -246
  162. package/src/auto-reply.broadcast-groups.test-harness.ts +0 -47
  163. package/src/auto-reply.impl.ts +0 -6
  164. package/src/auto-reply.test-harness.ts +0 -421
  165. package/src/auto-reply.ts +0 -1
  166. package/src/auto-reply.web-auto-reply.compresses-common-formats-jpeg-cap.test.ts +0 -427
  167. package/src/auto-reply.web-auto-reply.connection-and-logging.e2e.test.ts +0 -908
  168. package/src/auto-reply.web-auto-reply.last-route.test.ts +0 -184
  169. package/src/channel-actions.runtime.ts +0 -7
  170. package/src/channel-actions.test.ts +0 -216
  171. package/src/channel-actions.ts +0 -84
  172. package/src/channel-outbound.test.ts +0 -131
  173. package/src/channel-outbound.ts +0 -36
  174. package/src/channel-react-action.runtime.ts +0 -7
  175. package/src/channel-react-action.test.ts +0 -294
  176. package/src/channel-react-action.ts +0 -84
  177. package/src/channel.runtime.ts +0 -117
  178. package/src/channel.setup.test.ts +0 -461
  179. package/src/channel.setup.ts +0 -28
  180. package/src/channel.ts +0 -334
  181. package/src/command-policy.ts +0 -7
  182. package/src/config-accessors.test.ts +0 -34
  183. package/src/config-accessors.ts +0 -22
  184. package/src/config-schema.test.ts +0 -121
  185. package/src/config-schema.ts +0 -6
  186. package/src/config-ui-hints.ts +0 -24
  187. package/src/connection-controller-registry.test.ts +0 -27
  188. package/src/connection-controller-registry.ts +0 -49
  189. package/src/connection-controller.test.ts +0 -282
  190. package/src/connection-controller.ts +0 -679
  191. package/src/creds-files.ts +0 -19
  192. package/src/creds-persistence.ts +0 -102
  193. package/src/directory-config.test.ts +0 -60
  194. package/src/directory-config.ts +0 -40
  195. package/src/directory-contract.test.ts +0 -56
  196. package/src/doctor-contract.ts +0 -11
  197. package/src/doctor.test.ts +0 -74
  198. package/src/doctor.ts +0 -56
  199. package/src/group-intro.ts +0 -15
  200. package/src/group-policy.test.ts +0 -36
  201. package/src/group-policy.ts +0 -40
  202. package/src/group-session-contract.ts +0 -20
  203. package/src/group-session-key.test.ts +0 -53
  204. package/src/group-session-key.ts +0 -41
  205. package/src/heartbeat.ts +0 -34
  206. package/src/identity.ts +0 -164
  207. package/src/inbound/access-control.test-harness.ts +0 -37
  208. package/src/inbound/access-control.test.ts +0 -375
  209. package/src/inbound/access-control.ts +0 -237
  210. package/src/inbound/dedupe.ts +0 -132
  211. package/src/inbound/extract.test.ts +0 -282
  212. package/src/inbound/extract.ts +0 -488
  213. package/src/inbound/lifecycle.ts +0 -39
  214. package/src/inbound/media.node.test.ts +0 -83
  215. package/src/inbound/media.ts +0 -102
  216. package/src/inbound/monitor.ts +0 -890
  217. package/src/inbound/runtime-api.ts +0 -7
  218. package/src/inbound/save-media.runtime.ts +0 -1
  219. package/src/inbound/send-api.test.ts +0 -307
  220. package/src/inbound/send-api.ts +0 -141
  221. package/src/inbound/send-result.ts +0 -61
  222. package/src/inbound/types.ts +0 -106
  223. package/src/inbound-context.contract.test.ts +0 -32
  224. package/src/inbound-policy.ts +0 -231
  225. package/src/inbound.media.test.ts +0 -320
  226. package/src/inbound.test.ts +0 -290
  227. package/src/inbound.ts +0 -9
  228. package/src/login-qr.test.ts +0 -483
  229. package/src/login-qr.ts +0 -542
  230. package/src/login.coverage.test.ts +0 -133
  231. package/src/login.test.ts +0 -89
  232. package/src/login.ts +0 -70
  233. package/src/logout.test.ts +0 -162
  234. package/src/media.test.ts +0 -480
  235. package/src/media.ts +0 -10
  236. package/src/monitor-inbox.allows-messages-from-senders-allowfrom-list.test-support.ts +0 -400
  237. package/src/monitor-inbox.append-upsert.test-support.ts +0 -133
  238. package/src/monitor-inbox.behavior.test.ts +0 -5
  239. package/src/monitor-inbox.blocks-messages-from-unauthorized-senders-not-allowfrom.test-support.ts +0 -362
  240. package/src/monitor-inbox.captures-media-path-image-messages.test-support.ts +0 -306
  241. package/src/monitor-inbox.streams-inbound-messages.test-support.ts +0 -729
  242. package/src/monitor-inbox.test-harness.ts +0 -304
  243. package/src/normalize-target.ts +0 -112
  244. package/src/normalize.ts +0 -6
  245. package/src/outbound-adapter.poll.test.ts +0 -62
  246. package/src/outbound-adapter.sendpayload.test.ts +0 -195
  247. package/src/outbound-adapter.ts +0 -36
  248. package/src/outbound-base.test.ts +0 -560
  249. package/src/outbound-base.ts +0 -244
  250. package/src/outbound-media-contract.ts +0 -278
  251. package/src/outbound-media.runtime.ts +0 -36
  252. package/src/outbound-payload.contract.test.ts +0 -61
  253. package/src/outbound-send-deps.ts +0 -1
  254. package/src/outbound-test-support.ts +0 -16
  255. package/src/pairing-security.test-harness.ts +0 -59
  256. package/src/qr-image.ts +0 -1
  257. package/src/qr-terminal.ts +0 -1
  258. package/src/quoted-message.test.ts +0 -83
  259. package/src/quoted-message.ts +0 -184
  260. package/src/reaction-level.test.ts +0 -94
  261. package/src/reaction-level.ts +0 -21
  262. package/src/reconnect.test.ts +0 -51
  263. package/src/reconnect.ts +0 -55
  264. package/src/resolve-outbound-target.test.ts +0 -265
  265. package/src/resolve-outbound-target.ts +0 -54
  266. package/src/resolve-target.test.ts +0 -97
  267. package/src/runtime-api.ts +0 -59
  268. package/src/runtime-group-policy.ts +0 -16
  269. package/src/runtime.ts +0 -9
  270. package/src/security-contract.ts +0 -47
  271. package/src/security-fix.ts +0 -71
  272. package/src/send.test.ts +0 -515
  273. package/src/send.ts +0 -287
  274. package/src/session-contract.test.ts +0 -31
  275. package/src/session-contract.ts +0 -43
  276. package/src/session-errors.ts +0 -125
  277. package/src/session-route.ts +0 -26
  278. package/src/session.runtime.ts +0 -8
  279. package/src/session.test.ts +0 -559
  280. package/src/session.ts +0 -330
  281. package/src/setup-core.ts +0 -52
  282. package/src/setup-finalize.ts +0 -446
  283. package/src/setup-surface.test.ts +0 -367
  284. package/src/setup-surface.ts +0 -69
  285. package/src/setup-test-helpers.ts +0 -216
  286. package/src/shared.ts +0 -291
  287. package/src/socket-timing.test.ts +0 -49
  288. package/src/socket-timing.ts +0 -38
  289. package/src/state-migrations.ts +0 -54
  290. package/src/status-issues.test.ts +0 -137
  291. package/src/status-issues.ts +0 -185
  292. package/src/system-prompt.test.ts +0 -199
  293. package/src/system-prompt.ts +0 -31
  294. package/src/targets-runtime.ts +0 -180
  295. package/src/test-helpers.ts +0 -690
  296. package/src/text-runtime.test.ts +0 -162
  297. package/src/text-runtime.ts +0 -11
  298. package/src/vcard.ts +0 -84
  299. package/targets.ts +0 -5
  300. package/test-api.ts +0 -2
  301. package/tsconfig.json +0 -16
@@ -1,559 +0,0 @@
1
- import { EventEmitter } from "node:events";
2
- import fsSync from "node:fs";
3
- import fs from "node:fs/promises";
4
- import path from "node:path";
5
- import { resetLogger, setLoggerOverride } from "openclaw/plugin-sdk/runtime-env";
6
- import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
7
- import { enqueueCredsSave } from "./creds-persistence.js";
8
- import { baileys, getLastSocket, resetBaileysMocks, resetLoadConfigMock } from "./test-helpers.js";
9
-
10
- const useMultiFileAuthStateMock = vi.mocked(baileys.useMultiFileAuthState);
11
-
12
- let createWaSocket: typeof import("./session.js").createWaSocket;
13
- let formatError: typeof import("./session.js").formatError;
14
- let logWebSelfId: typeof import("./session.js").logWebSelfId;
15
- let waitForWaConnection: typeof import("./session.js").waitForWaConnection;
16
- let waitForCredsSaveQueue: typeof import("./session.js").waitForCredsSaveQueue;
17
- let writeCredsJsonAtomically: typeof import("./session.js").writeCredsJsonAtomically;
18
- let DEFAULT_WHATSAPP_SOCKET_TIMING: typeof import("./socket-timing.js").DEFAULT_WHATSAPP_SOCKET_TIMING;
19
-
20
- async function flushCredsUpdate() {
21
- await new Promise<void>((resolve) => setImmediate(resolve));
22
- }
23
-
24
- async function emitCredsUpdate(authDir?: string) {
25
- const sock = getLastSocket();
26
- sock.ev.emit("creds.update", {});
27
- await flushCredsUpdate();
28
- if (authDir) {
29
- await waitForCredsSaveQueue(authDir);
30
- }
31
- }
32
-
33
- function createTempAuthDir(prefix: string) {
34
- return fsSync.mkdtempSync(
35
- path.join((process.env.TMPDIR ?? "/tmp").replace(/\/+$/, ""), `${prefix}-`),
36
- );
37
- }
38
-
39
- function mockFsOpenForCredsWrites(params?: {
40
- onTempWrite?: (filePath: string) => Promise<void> | void;
41
- }) {
42
- const open = fs.open.bind(fs);
43
- const tempHandles: Array<{
44
- filePath: string;
45
- writeFile: ReturnType<typeof vi.fn>;
46
- sync: ReturnType<typeof vi.fn>;
47
- close: ReturnType<typeof vi.fn>;
48
- }> = [];
49
- const dirHandles: Array<{
50
- filePath: string;
51
- sync: ReturnType<typeof vi.fn>;
52
- close: ReturnType<typeof vi.fn>;
53
- }> = [];
54
- const openSpy = vi.spyOn(fs, "open").mockImplementation(async (filePath, flags, mode) => {
55
- if (typeof filePath === "string" && flags === "w" && filePath.includes(".creds.")) {
56
- const handle = {
57
- filePath,
58
- writeFile: vi.fn(async () => {
59
- await params?.onTempWrite?.(filePath);
60
- }),
61
- sync: vi.fn(async () => {}),
62
- close: vi.fn(async () => {}),
63
- };
64
- tempHandles.push(handle);
65
- return handle as never;
66
- }
67
- if (typeof filePath === "string" && flags === "r") {
68
- const handle = {
69
- filePath,
70
- sync: vi.fn(async () => {}),
71
- close: vi.fn(async () => {}),
72
- };
73
- dirHandles.push(handle);
74
- return handle as never;
75
- }
76
- return open(filePath as never, flags as never, mode as never);
77
- });
78
- return {
79
- openSpy,
80
- tempHandles,
81
- dirHandles,
82
- restore() {
83
- openSpy.mockRestore();
84
- },
85
- };
86
- }
87
-
88
- function mockCredsJsonSpies(readContents: string) {
89
- const credsSuffix = path.join("/tmp", "openclaw-oauth", "whatsapp", "default", "creds.json");
90
- const copySpy = vi.spyOn(fsSync, "copyFileSync").mockImplementation(() => {});
91
- const existsSpy = vi.spyOn(fsSync, "existsSync").mockImplementation((p) => {
92
- if (typeof p !== "string") {
93
- return false;
94
- }
95
- return p.endsWith(credsSuffix);
96
- });
97
- const statSpy = vi.spyOn(fsSync, "statSync").mockImplementation((p) => {
98
- if (typeof p === "string" && p.endsWith(credsSuffix)) {
99
- return { isFile: () => true, size: 12 } as never;
100
- }
101
- throw new Error(`unexpected statSync path: ${String(p)}`);
102
- });
103
- const readSpy = vi.spyOn(fsSync, "readFileSync").mockImplementation((p) => {
104
- if (typeof p === "string" && p.endsWith(credsSuffix)) {
105
- return readContents as never;
106
- }
107
- throw new Error(`unexpected readFileSync path: ${String(p)}`);
108
- });
109
- return {
110
- copySpy,
111
- credsSuffix,
112
- restore: () => {
113
- copySpy.mockRestore();
114
- existsSpy.mockRestore();
115
- statSpy.mockRestore();
116
- readSpy.mockRestore();
117
- },
118
- };
119
- }
120
-
121
- function mockLogWebSelfIdCreds(me: Record<string, string>) {
122
- const existsSpy = vi.spyOn(fsSync, "existsSync").mockImplementation((p) => {
123
- if (typeof p !== "string") {
124
- return false;
125
- }
126
- return p.endsWith("creds.json");
127
- });
128
- const readSpy = vi.spyOn(fsSync, "readFileSync").mockImplementation((p) => {
129
- if (typeof p === "string" && p.endsWith("creds.json")) {
130
- return JSON.stringify({ me });
131
- }
132
- throw new Error(`unexpected readFileSync path: ${String(p)}`);
133
- });
134
- return {
135
- restore() {
136
- existsSpy.mockRestore();
137
- readSpy.mockRestore();
138
- },
139
- };
140
- }
141
-
142
- describe("web session", () => {
143
- beforeAll(async () => {
144
- ({
145
- createWaSocket,
146
- formatError,
147
- logWebSelfId,
148
- waitForWaConnection,
149
- waitForCredsSaveQueue,
150
- writeCredsJsonAtomically,
151
- } = await import("./session.js"));
152
- ({ DEFAULT_WHATSAPP_SOCKET_TIMING } = await import("./socket-timing.js"));
153
- });
154
-
155
- beforeEach(() => {
156
- vi.clearAllMocks();
157
- resetBaileysMocks();
158
- resetLoadConfigMock();
159
- });
160
-
161
- afterEach(async () => {
162
- await waitForCredsSaveQueue();
163
- resetLogger();
164
- setLoggerOverride(null);
165
- vi.unstubAllEnvs();
166
- vi.useRealTimers();
167
- });
168
-
169
- it("creates WA socket with QR handler", async () => {
170
- const authDir = createTempAuthDir("openclaw-wa-creds-test");
171
- const openMock = mockFsOpenForCredsWrites();
172
-
173
- await createWaSocket(true, false, { authDir });
174
- const makeWASocket = baileys.makeWASocket as ReturnType<typeof vi.fn>;
175
- expect(makeWASocket).toHaveBeenCalledWith(
176
- expect.objectContaining({
177
- printQRInTerminal: false,
178
- ...DEFAULT_WHATSAPP_SOCKET_TIMING,
179
- }),
180
- );
181
- const passed = makeWASocket.mock.calls[0][0];
182
- const passedLogger = (passed as { logger?: { level?: string; trace?: unknown } }).logger;
183
- expect(passedLogger?.level).toBe("silent");
184
- expect(typeof passedLogger?.trace).toBe("function");
185
- await emitCredsUpdate(authDir);
186
-
187
- expect(openMock.openSpy).toHaveBeenCalledWith(
188
- expect.stringContaining(path.join(authDir, ".creds.")),
189
- "w",
190
- 0o600,
191
- );
192
- openMock.restore();
193
- });
194
-
195
- it("passes explicit Baileys socket timing overrides", async () => {
196
- await createWaSocket(false, false, {
197
- keepAliveIntervalMs: 10_000,
198
- connectTimeoutMs: 90_000,
199
- defaultQueryTimeoutMs: 120_000,
200
- });
201
-
202
- expect(baileys.makeWASocket).toHaveBeenCalledWith(
203
- expect.objectContaining({
204
- keepAliveIntervalMs: 10_000,
205
- connectTimeoutMs: 90_000,
206
- defaultQueryTimeoutMs: 120_000,
207
- }),
208
- );
209
- });
210
-
211
- it("uses ambient env proxy agent when HTTPS_PROXY is configured", async () => {
212
- vi.stubEnv("HTTPS_PROXY", "http://proxy.test:8080");
213
-
214
- await createWaSocket(false, false);
215
-
216
- const passed = (baileys.makeWASocket as ReturnType<typeof vi.fn>).mock.calls[0]?.[0] as {
217
- agent?: unknown;
218
- fetchAgent?: unknown;
219
- };
220
- expect(passed.agent).toBeDefined();
221
- expect(passed.fetchAgent).toBeDefined();
222
- expect(passed.fetchAgent).not.toBe(passed.agent);
223
- expect(typeof (passed.fetchAgent as { dispatch?: unknown } | undefined)?.dispatch).toBe(
224
- "function",
225
- );
226
- });
227
-
228
- it("uses lowercase HTTPS proxy before uppercase for WA WebSocket connection", async () => {
229
- vi.stubEnv("HTTPS_PROXY", "http://upper-proxy.test:8080");
230
- vi.stubEnv("https_proxy", "http://lower-proxy.test:8080");
231
-
232
- await createWaSocket(false, false);
233
-
234
- const passed = (baileys.makeWASocket as ReturnType<typeof vi.fn>).mock.calls[0]?.[0] as {
235
- agent?: { proxy?: URL };
236
- };
237
- expect(passed.agent).toBeDefined();
238
- expect(passed.agent?.proxy?.href).toContain("lower-proxy.test");
239
- });
240
-
241
- it("skips WA WebSocket env proxy agent when NO_PROXY covers WhatsApp Web", async () => {
242
- vi.stubEnv("HTTPS_PROXY", "http://proxy.test:8080");
243
- vi.stubEnv("NO_PROXY", "mmg.whatsapp.net");
244
-
245
- await createWaSocket(false, false);
246
-
247
- const passed = (baileys.makeWASocket as ReturnType<typeof vi.fn>).mock.calls[0]?.[0] as {
248
- agent?: unknown;
249
- fetchAgent?: unknown;
250
- };
251
- expect(passed.agent).toBeUndefined();
252
- expect(passed.fetchAgent).toBeDefined();
253
- });
254
-
255
- it("does not create a proxy agent when no env proxy is configured", async () => {
256
- for (const key of [
257
- "ALL_PROXY",
258
- "all_proxy",
259
- "HTTP_PROXY",
260
- "http_proxy",
261
- "HTTPS_PROXY",
262
- "https_proxy",
263
- ]) {
264
- vi.stubEnv(key, "");
265
- }
266
-
267
- await createWaSocket(false, false);
268
-
269
- const passed = (baileys.makeWASocket as ReturnType<typeof vi.fn>).mock.calls[0]?.[0] as {
270
- agent?: unknown;
271
- fetchAgent?: unknown;
272
- };
273
- expect(passed.agent).toBeUndefined();
274
- expect(passed.fetchAgent).toBeUndefined();
275
- });
276
-
277
- it("waits for connection open", async () => {
278
- const ev = new EventEmitter();
279
- const promise = waitForWaConnection({ ev } as unknown as ReturnType<
280
- typeof baileys.makeWASocket
281
- >);
282
- ev.emit("connection.update", { connection: "open" });
283
- await expect(promise).resolves.toBeUndefined();
284
- });
285
-
286
- it("rejects when connection closes", async () => {
287
- const ev = new EventEmitter();
288
- const promise = waitForWaConnection({ ev } as unknown as ReturnType<
289
- typeof baileys.makeWASocket
290
- >);
291
- ev.emit("connection.update", {
292
- connection: "close",
293
- lastDisconnect: new Error("bye"),
294
- });
295
- await expect(promise).rejects.toBeInstanceOf(Error);
296
- });
297
-
298
- it("logWebSelfId prints cached E.164 when creds exist", () => {
299
- const creds = mockLogWebSelfIdCreds({ id: "12345@s.whatsapp.net" });
300
- const runtime = {
301
- log: vi.fn(),
302
- error: vi.fn(),
303
- exit: vi.fn(),
304
- };
305
-
306
- logWebSelfId("/tmp/wa-creds", runtime as never, true);
307
-
308
- expect(runtime.log).toHaveBeenCalledWith(
309
- expect.stringContaining("Web Channel: +12345 (jid 12345@s.whatsapp.net)"),
310
- );
311
- creds.restore();
312
- });
313
-
314
- it("logWebSelfId prints cached lid details when creds include a lid", () => {
315
- const creds = mockLogWebSelfIdCreds({
316
- id: "12345@s.whatsapp.net",
317
- lid: "777@lid",
318
- });
319
- const runtime = {
320
- log: vi.fn(),
321
- error: vi.fn(),
322
- exit: vi.fn(),
323
- };
324
-
325
- logWebSelfId("/tmp/wa-creds", runtime as never, true);
326
-
327
- expect(runtime.log).toHaveBeenCalledWith(
328
- expect.stringContaining("Web Channel: +12345 (jid 12345@s.whatsapp.net, lid 777@lid)"),
329
- );
330
- creds.restore();
331
- });
332
-
333
- it("formatError prints Boom-like payload message", () => {
334
- const err = {
335
- error: {
336
- isBoom: true,
337
- output: {
338
- statusCode: 408,
339
- payload: {
340
- statusCode: 408,
341
- error: "Request Time-out",
342
- message: "QR refs attempts ended",
343
- },
344
- },
345
- },
346
- };
347
- expect(formatError(err)).toContain("status=408");
348
- expect(formatError(err)).toContain("Request Time-out");
349
- expect(formatError(err)).toContain("QR refs attempts ended");
350
- });
351
-
352
- it("does not clobber creds backup when creds.json is corrupted", async () => {
353
- const creds = mockCredsJsonSpies("{");
354
- const openMock = mockFsOpenForCredsWrites();
355
-
356
- await createWaSocket(false, false);
357
- await emitCredsUpdate();
358
-
359
- expect(creds.copySpy).not.toHaveBeenCalled();
360
- expect(openMock.tempHandles).toHaveLength(1);
361
-
362
- creds.restore();
363
- openMock.restore();
364
- });
365
-
366
- it("serializes creds.update saves to avoid overlapping writes", async () => {
367
- let inFlight = 0;
368
- let maxInFlight = 0;
369
- let release: (() => void) | null = null;
370
- const gate = new Promise<void>((resolve) => {
371
- release = resolve;
372
- });
373
-
374
- const authDir = createTempAuthDir("openclaw-wa-queue");
375
- const openMock = mockFsOpenForCredsWrites({
376
- onTempWrite: async (filePath) => {
377
- if (filePath.startsWith(authDir)) {
378
- inFlight += 1;
379
- maxInFlight = Math.max(maxInFlight, inFlight);
380
- await gate;
381
- inFlight -= 1;
382
- }
383
- },
384
- });
385
-
386
- await createWaSocket(false, false, { authDir });
387
- const sock = getLastSocket();
388
-
389
- sock.ev.emit("creds.update", {});
390
- sock.ev.emit("creds.update", {});
391
-
392
- try {
393
- await vi.waitFor(() => {
394
- expect(inFlight).toBe(1);
395
- });
396
- } finally {
397
- (release as (() => void) | null)?.();
398
- }
399
-
400
- await waitForCredsSaveQueue(authDir);
401
-
402
- expect(openMock.tempHandles).toHaveLength(2);
403
- expect(maxInFlight).toBe(1);
404
- expect(inFlight).toBe(0);
405
- openMock.restore();
406
- });
407
-
408
- it("lets different authDir queues flush independently", async () => {
409
- let inFlightA = 0;
410
- let inFlightB = 0;
411
- let releaseA: (() => void) | null = null;
412
- let releaseB: (() => void) | null = null;
413
- const gateA = new Promise<void>((resolve) => {
414
- releaseA = resolve;
415
- });
416
- const gateB = new Promise<void>((resolve) => {
417
- releaseB = resolve;
418
- });
419
-
420
- const authDirA = createTempAuthDir("openclaw-wa-a");
421
- const authDirB = createTempAuthDir("openclaw-wa-b");
422
- const onError = vi.fn();
423
-
424
- enqueueCredsSave(
425
- authDirA,
426
- async () => {
427
- inFlightA += 1;
428
- await gateA;
429
- inFlightA -= 1;
430
- },
431
- onError,
432
- );
433
- enqueueCredsSave(
434
- authDirB,
435
- async () => {
436
- inFlightB += 1;
437
- await gateB;
438
- inFlightB -= 1;
439
- },
440
- onError,
441
- );
442
-
443
- try {
444
- await vi.waitFor(() => {
445
- expect(inFlightA).toBe(1);
446
- expect(inFlightB).toBe(1);
447
- });
448
- } finally {
449
- (releaseA as (() => void) | null)?.();
450
- (releaseB as (() => void) | null)?.();
451
- }
452
-
453
- await Promise.all([waitForCredsSaveQueue(authDirA), waitForCredsSaveQueue(authDirB)]);
454
-
455
- expect(inFlightA).toBe(0);
456
- expect(inFlightB).toBe(0);
457
- expect(onError).not.toHaveBeenCalled();
458
- });
459
-
460
- it("rotates creds backup when creds.json is valid JSON", async () => {
461
- const creds = mockCredsJsonSpies("{}");
462
- const openMock = mockFsOpenForCredsWrites();
463
- const backupSuffix = path.join(
464
- "/tmp",
465
- "openclaw-oauth",
466
- "whatsapp",
467
- "default",
468
- "creds.json.bak",
469
- );
470
-
471
- await createWaSocket(false, false);
472
- await emitCredsUpdate();
473
-
474
- expect(creds.copySpy).toHaveBeenCalledTimes(1);
475
- const args = creds.copySpy.mock.calls[0] ?? [];
476
- expect(String(args[0] ?? "")).toContain(creds.credsSuffix);
477
- expect(String(args[1] ?? "")).toContain(backupSuffix);
478
- expect(openMock.tempHandles).toHaveLength(1);
479
-
480
- creds.restore();
481
- openMock.restore();
482
- });
483
-
484
- it("writes creds.json atomically via temp file and rename", async () => {
485
- const openMock = mockFsOpenForCredsWrites();
486
- const renameSpy = vi.spyOn(fs, "rename").mockResolvedValue(undefined);
487
- const rmSpy = vi.spyOn(fs, "rm").mockResolvedValue(undefined);
488
- const chmodSpy = vi.spyOn(fs, "chmod").mockResolvedValue(undefined);
489
-
490
- await writeCredsJsonAtomically("/tmp/openclaw-oauth/whatsapp/default", {
491
- me: { id: "123@s.whatsapp.net" },
492
- });
493
-
494
- expect(openMock.tempHandles).toHaveLength(1);
495
- expect(openMock.tempHandles[0]?.writeFile).toHaveBeenCalledTimes(1);
496
- expect(openMock.tempHandles[0]?.sync).toHaveBeenCalledTimes(1);
497
- expect(openMock.tempHandles[0]?.close).toHaveBeenCalledTimes(1);
498
- expect(renameSpy).toHaveBeenCalledTimes(1);
499
- expect(rmSpy).not.toHaveBeenCalled();
500
- expect(chmodSpy).toHaveBeenCalledOnce();
501
- expect(openMock.dirHandles).toHaveLength(1);
502
- expect(openMock.dirHandles[0]?.sync).toHaveBeenCalledTimes(1);
503
- const writePath = openMock.tempHandles[0]?.filePath;
504
- const renameArgs = renameSpy.mock.calls[0] ?? [];
505
- expect(typeof writePath).toBe("string");
506
- expect(writePath).toContain(".creds.");
507
- expect(String(renameArgs[1] ?? "")).toContain(
508
- path.join("/tmp", "openclaw-oauth", "whatsapp", "default", "creds.json"),
509
- );
510
-
511
- openMock.restore();
512
- renameSpy.mockRestore();
513
- rmSpy.mockRestore();
514
- chmodSpy.mockRestore();
515
- });
516
-
517
- it("keeps the previous creds.json valid if the atomic rename fails", async () => {
518
- const authDir = createTempAuthDir("openclaw-wa-creds-atomic");
519
- const credsPath = path.join(authDir, "creds.json");
520
- const originalCreds = { me: { id: "old@s.whatsapp.net" } };
521
- const nextCreds = { me: { id: "new@s.whatsapp.net" } };
522
- fsSync.writeFileSync(credsPath, JSON.stringify(originalCreds), "utf-8");
523
- const rename = fs.rename.bind(fs);
524
- const renameSpy = vi.spyOn(fs, "rename").mockImplementation(async (from, to) => {
525
- if (
526
- typeof from === "string" &&
527
- typeof to === "string" &&
528
- from.startsWith(path.join(authDir, ".creds.")) &&
529
- to === credsPath
530
- ) {
531
- throw new Error("simulated atomic rename failure");
532
- }
533
- return rename(from, to);
534
- });
535
-
536
- useMultiFileAuthStateMock.mockResolvedValueOnce({
537
- state: {
538
- creds: nextCreds as never,
539
- keys: {} as never,
540
- },
541
- saveCreds: vi.fn(),
542
- });
543
-
544
- await createWaSocket(false, false, { authDir });
545
- await emitCredsUpdate(authDir);
546
-
547
- const raw = fsSync.readFileSync(credsPath, "utf-8");
548
- const tempEntries = fsSync
549
- .readdirSync(authDir)
550
- .filter((entry) => entry.startsWith(".creds.") && entry.endsWith(".tmp"));
551
-
552
- expect(renameSpy).toHaveBeenCalledOnce();
553
- expect(() => JSON.parse(raw)).not.toThrow();
554
- expect(JSON.parse(raw)).toMatchObject(originalCreds);
555
- expect(tempEntries).toHaveLength(0);
556
-
557
- renameSpy.mockRestore();
558
- });
559
- });