@openclaw/zalo 2026.5.2 → 2026.5.3-beta.2

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 (87) hide show
  1. package/dist/accounts-9NLDDlZ8.js +118 -0
  2. package/dist/actions.runtime-kJ65ZxW7.js +5 -0
  3. package/dist/api.js +5 -0
  4. package/dist/channel-VPbtV3Oq.js +343 -0
  5. package/dist/channel-plugin-api.js +2 -0
  6. package/dist/channel.runtime-BnTAWQx5.js +106 -0
  7. package/dist/contract-api.js +3 -0
  8. package/dist/group-access-DZR43lOR.js +30 -0
  9. package/dist/index.js +22 -0
  10. package/dist/monitor-DMysJBWa.js +823 -0
  11. package/dist/monitor.webhook-DqnuvgjV.js +175 -0
  12. package/dist/proxy-CY8VuC6H.js +135 -0
  13. package/dist/runtime-BRFxnYQx.js +8 -0
  14. package/dist/runtime-api-MOTmRW4F.js +19 -0
  15. package/dist/runtime-api.js +3 -0
  16. package/dist/secret-contract-Dw93tGo2.js +87 -0
  17. package/dist/secret-contract-api.js +2 -0
  18. package/dist/send-Gv3l5EGI.js +101 -0
  19. package/dist/setup-api.js +30 -0
  20. package/dist/setup-core-DigRD3j1.js +166 -0
  21. package/dist/setup-entry.js +15 -0
  22. package/dist/setup-surface-2Up3yWov.js +216 -0
  23. package/dist/test-api.js +2 -0
  24. package/package.json +15 -6
  25. package/api.ts +0 -9
  26. package/channel-plugin-api.ts +0 -1
  27. package/contract-api.ts +0 -5
  28. package/index.test.ts +0 -15
  29. package/index.ts +0 -20
  30. package/runtime-api.test.ts +0 -17
  31. package/runtime-api.ts +0 -75
  32. package/secret-contract-api.ts +0 -5
  33. package/setup-api.ts +0 -34
  34. package/setup-entry.ts +0 -13
  35. package/src/accounts.test.ts +0 -70
  36. package/src/accounts.ts +0 -60
  37. package/src/actions.runtime.ts +0 -5
  38. package/src/actions.test.ts +0 -32
  39. package/src/actions.ts +0 -62
  40. package/src/api.test.ts +0 -149
  41. package/src/api.ts +0 -265
  42. package/src/approval-auth.test.ts +0 -17
  43. package/src/approval-auth.ts +0 -25
  44. package/src/channel.directory.test.ts +0 -59
  45. package/src/channel.runtime.ts +0 -93
  46. package/src/channel.startup.test.ts +0 -101
  47. package/src/channel.ts +0 -275
  48. package/src/config-schema.test.ts +0 -30
  49. package/src/config-schema.ts +0 -29
  50. package/src/group-access.ts +0 -49
  51. package/src/monitor.group-policy.test.ts +0 -94
  52. package/src/monitor.image.polling.test.ts +0 -110
  53. package/src/monitor.lifecycle.test.ts +0 -198
  54. package/src/monitor.pairing.lifecycle.test.ts +0 -141
  55. package/src/monitor.polling.media-reply.test.ts +0 -425
  56. package/src/monitor.reply-once.lifecycle.test.ts +0 -171
  57. package/src/monitor.ts +0 -1028
  58. package/src/monitor.types.ts +0 -4
  59. package/src/monitor.webhook.test.ts +0 -806
  60. package/src/monitor.webhook.ts +0 -278
  61. package/src/outbound-media.test.ts +0 -182
  62. package/src/outbound-media.ts +0 -241
  63. package/src/outbound-payload.contract.test.ts +0 -45
  64. package/src/probe.ts +0 -45
  65. package/src/proxy.ts +0 -24
  66. package/src/runtime-api.ts +0 -75
  67. package/src/runtime-support.ts +0 -91
  68. package/src/runtime.ts +0 -9
  69. package/src/secret-contract.ts +0 -109
  70. package/src/secret-input.ts +0 -5
  71. package/src/send.test.ts +0 -120
  72. package/src/send.ts +0 -153
  73. package/src/session-route.ts +0 -32
  74. package/src/setup-allow-from.ts +0 -94
  75. package/src/setup-core.ts +0 -149
  76. package/src/setup-status.test.ts +0 -33
  77. package/src/setup-surface.test.ts +0 -175
  78. package/src/setup-surface.ts +0 -291
  79. package/src/status-issues.test.ts +0 -17
  80. package/src/status-issues.ts +0 -37
  81. package/src/test-support/lifecycle-test-support.ts +0 -413
  82. package/src/test-support/monitor-mocks-test-support.ts +0 -209
  83. package/src/token.test.ts +0 -92
  84. package/src/token.ts +0 -79
  85. package/src/types.ts +0 -50
  86. package/test-api.ts +0 -1
  87. package/tsconfig.json +0 -16
@@ -0,0 +1,823 @@
1
+ import { n as isZaloSenderAllowed, t as evaluateZaloGroupAccess } from "./group-access-DZR43lOR.js";
2
+ import { t as getZaloRuntime } from "./runtime-BRFxnYQx.js";
3
+ import { a as getUpdates, c as sendMessage, l as sendPhoto, n as ZaloApiError, o as getWebhookInfo, r as deleteWebhook, s as sendChatAction, t as resolveZaloProxyFetch, u as setWebhook } from "./proxy-CY8VuC6H.js";
4
+ import { deliverTextOrMediaReply, resolveSendableOutboundReplyParts } from "openclaw/plugin-sdk/reply-payload";
5
+ import { resolveDefaultGroupPolicy, warnMissingProviderGroupPolicyFallbackOnce } from "openclaw/plugin-sdk/runtime-group-policy";
6
+ import { createChannelPairingController } from "openclaw/plugin-sdk/channel-pairing";
7
+ import { createChannelReplyPipeline } from "openclaw/plugin-sdk/channel-reply-pipeline";
8
+ import { logTypingFailure } from "openclaw/plugin-sdk/channel-feedback";
9
+ import { resolveDirectDmAuthorizationOutcome, resolveSenderCommandAuthorizationWithRuntime } from "openclaw/plugin-sdk/command-auth";
10
+ import { resolveInboundRouteEnvelopeBuilderWithRuntime } from "openclaw/plugin-sdk/inbound-envelope";
11
+ import { registerPluginHttpRoute, resolveWebhookPath } from "openclaw/plugin-sdk/webhook-ingress";
12
+ import { waitForAbortSignal } from "openclaw/plugin-sdk/runtime-env";
13
+ import { randomBytes } from "node:crypto";
14
+ import { chmod, mkdir, readFile, readdir, stat, unlink, writeFile } from "node:fs/promises";
15
+ import { join } from "node:path";
16
+ import { loadOutboundMediaFromUrl } from "openclaw/plugin-sdk/outbound-media";
17
+ import { resolvePreferredOpenClawTmpDir } from "openclaw/plugin-sdk/temp-path";
18
+ //#region extensions/zalo/src/outbound-media.ts
19
+ const ZALO_OUTBOUND_MEDIA_TTL_MS = 2 * 6e4;
20
+ const ZALO_OUTBOUND_MEDIA_SEGMENT = "media";
21
+ const ZALO_OUTBOUND_MEDIA_PREFIX = `/${ZALO_OUTBOUND_MEDIA_SEGMENT}/`;
22
+ const ZALO_OUTBOUND_MEDIA_DIR = join(resolvePreferredOpenClawTmpDir(), "openclaw-zalo-outbound-media");
23
+ const ZALO_OUTBOUND_MEDIA_ID_RE = /^[a-f0-9]{24}$/;
24
+ function resolveHostedZaloMediaMetadataPath(id) {
25
+ return join(ZALO_OUTBOUND_MEDIA_DIR, `${id}.json`);
26
+ }
27
+ function resolveHostedZaloMediaBufferPath(id) {
28
+ return join(ZALO_OUTBOUND_MEDIA_DIR, `${id}.bin`);
29
+ }
30
+ function createHostedZaloMediaId() {
31
+ return randomBytes(12).toString("hex");
32
+ }
33
+ function createHostedZaloMediaToken() {
34
+ return randomBytes(24).toString("hex");
35
+ }
36
+ async function ensureHostedZaloMediaDir() {
37
+ await mkdir(ZALO_OUTBOUND_MEDIA_DIR, {
38
+ recursive: true,
39
+ mode: 448
40
+ });
41
+ await chmod(ZALO_OUTBOUND_MEDIA_DIR, 448).catch(() => void 0);
42
+ }
43
+ async function deleteHostedZaloMediaEntry(id) {
44
+ await Promise.all([unlink(resolveHostedZaloMediaMetadataPath(id)).catch(() => void 0), unlink(resolveHostedZaloMediaBufferPath(id)).catch(() => void 0)]);
45
+ }
46
+ async function cleanupExpiredHostedZaloMedia(nowMs = Date.now()) {
47
+ let fileNames;
48
+ try {
49
+ fileNames = await readdir(ZALO_OUTBOUND_MEDIA_DIR);
50
+ } catch {
51
+ return;
52
+ }
53
+ await Promise.all(fileNames.filter((fileName) => fileName.endsWith(".json")).map(async (fileName) => {
54
+ const id = fileName.slice(0, -5);
55
+ try {
56
+ const metadataRaw = await readFile(resolveHostedZaloMediaMetadataPath(id), "utf8");
57
+ if (JSON.parse(metadataRaw).expiresAt <= nowMs) await deleteHostedZaloMediaEntry(id);
58
+ } catch {
59
+ await deleteHostedZaloMediaEntry(id);
60
+ }
61
+ }));
62
+ }
63
+ async function readHostedZaloMediaEntry(id) {
64
+ try {
65
+ const [metadataRaw, buffer] = await Promise.all([readFile(resolveHostedZaloMediaMetadataPath(id), "utf8"), readFile(resolveHostedZaloMediaBufferPath(id))]);
66
+ return {
67
+ metadata: JSON.parse(metadataRaw),
68
+ buffer
69
+ };
70
+ } catch {
71
+ return null;
72
+ }
73
+ }
74
+ function resolveHostedZaloMediaRoutePrefix(params) {
75
+ const webhookRoutePath = resolveWebhookPath({
76
+ webhookPath: params.webhookPath,
77
+ webhookUrl: params.webhookUrl,
78
+ defaultPath: null
79
+ });
80
+ if (!webhookRoutePath) throw new Error("Zalo webhookPath could not be derived for outbound media hosting");
81
+ return webhookRoutePath === "/" ? `/${ZALO_OUTBOUND_MEDIA_SEGMENT}` : `${webhookRoutePath}/${ZALO_OUTBOUND_MEDIA_SEGMENT}`;
82
+ }
83
+ function resolveHostedZaloMediaRoutePath(params) {
84
+ return `${resolveHostedZaloMediaRoutePrefix(params)}/`;
85
+ }
86
+ async function prepareHostedZaloMediaUrl(params) {
87
+ await ensureHostedZaloMediaDir();
88
+ await cleanupExpiredHostedZaloMedia();
89
+ const media = await loadOutboundMediaFromUrl(params.mediaUrl, {
90
+ maxBytes: params.maxBytes,
91
+ ...params.proxyUrl ? { proxyUrl: params.proxyUrl } : {}
92
+ });
93
+ const routePath = resolveHostedZaloMediaRoutePath({
94
+ webhookUrl: params.webhookUrl,
95
+ webhookPath: params.webhookPath
96
+ });
97
+ const id = createHostedZaloMediaId();
98
+ const token = createHostedZaloMediaToken();
99
+ const publicBaseUrl = new URL(params.webhookUrl).origin;
100
+ await writeFile(resolveHostedZaloMediaBufferPath(id), media.buffer, { mode: 384 });
101
+ try {
102
+ await writeFile(resolveHostedZaloMediaMetadataPath(id), JSON.stringify({
103
+ routePath,
104
+ token,
105
+ contentType: media.contentType,
106
+ expiresAt: Date.now() + ZALO_OUTBOUND_MEDIA_TTL_MS
107
+ }), {
108
+ encoding: "utf8",
109
+ mode: 384
110
+ });
111
+ } catch (error) {
112
+ await deleteHostedZaloMediaEntry(id);
113
+ throw error;
114
+ }
115
+ return `${publicBaseUrl}${routePath}${id}?token=${token}`;
116
+ }
117
+ async function tryHandleHostedZaloMediaRequest(req, res) {
118
+ await cleanupExpiredHostedZaloMedia();
119
+ const method = req.method ?? "GET";
120
+ if (method !== "GET" && method !== "HEAD") return false;
121
+ let url;
122
+ try {
123
+ url = new URL(req.url ?? "/", "http://localhost");
124
+ } catch {
125
+ return false;
126
+ }
127
+ const mediaPath = url.pathname;
128
+ const prefixIndex = mediaPath.lastIndexOf(ZALO_OUTBOUND_MEDIA_PREFIX);
129
+ if (prefixIndex < 0) return false;
130
+ const routePath = mediaPath.slice(0, prefixIndex + ZALO_OUTBOUND_MEDIA_PREFIX.length);
131
+ const id = mediaPath.slice(prefixIndex + ZALO_OUTBOUND_MEDIA_PREFIX.length);
132
+ if (!id || !ZALO_OUTBOUND_MEDIA_ID_RE.test(id)) {
133
+ res.statusCode = 404;
134
+ res.end("Not Found");
135
+ return true;
136
+ }
137
+ const entry = await readHostedZaloMediaEntry(id);
138
+ if (!entry || entry.metadata.routePath !== routePath) {
139
+ res.statusCode = 404;
140
+ res.end("Not Found");
141
+ return true;
142
+ }
143
+ if (entry.metadata.expiresAt <= Date.now()) {
144
+ await deleteHostedZaloMediaEntry(id);
145
+ res.statusCode = 410;
146
+ res.end("Expired");
147
+ return true;
148
+ }
149
+ if (url.searchParams.get("token") !== entry.metadata.token) {
150
+ res.statusCode = 401;
151
+ res.end("Unauthorized");
152
+ return true;
153
+ }
154
+ if (entry.metadata.contentType) res.setHeader("Content-Type", entry.metadata.contentType);
155
+ res.setHeader("Cache-Control", "no-store");
156
+ res.setHeader("X-Content-Type-Options", "nosniff");
157
+ const bufferStats = await stat(resolveHostedZaloMediaBufferPath(id)).catch(() => null);
158
+ if (bufferStats) res.setHeader("Content-Length", String(bufferStats.size));
159
+ if (method === "HEAD") {
160
+ res.statusCode = 200;
161
+ res.end();
162
+ return true;
163
+ }
164
+ res.statusCode = 200;
165
+ res.end(entry.buffer);
166
+ await deleteHostedZaloMediaEntry(id);
167
+ return true;
168
+ }
169
+ //#endregion
170
+ //#region extensions/zalo/src/monitor.ts
171
+ const ZALO_TEXT_LIMIT = 2e3;
172
+ const DEFAULT_MEDIA_MAX_MB = 5;
173
+ const WEBHOOK_CLEANUP_TIMEOUT_MS = 5e3;
174
+ const ZALO_TYPING_TIMEOUT_MS = 5e3;
175
+ let zaloWebhookModulePromise;
176
+ const hostedMediaRouteRefs = /* @__PURE__ */ new Map();
177
+ function loadZaloWebhookModule() {
178
+ zaloWebhookModulePromise ??= import("./monitor.webhook-DqnuvgjV.js");
179
+ return zaloWebhookModulePromise;
180
+ }
181
+ function registerSharedHostedMediaRoute(params) {
182
+ const unregister = registerPluginHttpRoute({
183
+ auth: "plugin",
184
+ match: "prefix",
185
+ path: params.path,
186
+ pluginId: "zalo",
187
+ source: "zalo-hosted-media",
188
+ accountId: params.accountId,
189
+ log: params.log,
190
+ handler: async (req, res) => {
191
+ if (!await tryHandleHostedZaloMediaRequest(req, res) && !res.headersSent) {
192
+ res.statusCode = 404;
193
+ res.setHeader("Content-Type", "text/plain; charset=utf-8");
194
+ res.end("Not Found");
195
+ }
196
+ }
197
+ });
198
+ const existing = hostedMediaRouteRefs.get(params.path);
199
+ if (existing) {
200
+ existing.count += 1;
201
+ existing.unregisters.push(unregister);
202
+ return () => {
203
+ const current = hostedMediaRouteRefs.get(params.path);
204
+ if (!current) return;
205
+ if (current.count > 1) {
206
+ current.count -= 1;
207
+ return;
208
+ }
209
+ hostedMediaRouteRefs.delete(params.path);
210
+ for (const unregisterHandle of current.unregisters) unregisterHandle();
211
+ };
212
+ }
213
+ hostedMediaRouteRefs.set(params.path, {
214
+ count: 1,
215
+ unregisters: [unregister]
216
+ });
217
+ return () => {
218
+ const current = hostedMediaRouteRefs.get(params.path);
219
+ if (!current) return;
220
+ if (current.count > 1) {
221
+ current.count -= 1;
222
+ return;
223
+ }
224
+ hostedMediaRouteRefs.delete(params.path);
225
+ for (const unregisterHandle of current.unregisters) unregisterHandle();
226
+ };
227
+ }
228
+ function formatZaloError(error) {
229
+ if (error instanceof Error) return error.stack ?? `${error.name}: ${error.message}`;
230
+ return String(error);
231
+ }
232
+ function describeWebhookTarget(rawUrl) {
233
+ try {
234
+ const parsed = new URL(rawUrl);
235
+ return `${parsed.origin}${parsed.pathname}`;
236
+ } catch {
237
+ return rawUrl;
238
+ }
239
+ }
240
+ function normalizeWebhookUrl(url) {
241
+ const trimmed = url?.trim();
242
+ return trimmed ? trimmed : void 0;
243
+ }
244
+ function logVerbose(core, runtime, message) {
245
+ if (core.logging.shouldLogVerbose()) runtime.log?.(`[zalo] ${message}`);
246
+ }
247
+ async function handleZaloWebhookRequest(req, res) {
248
+ const { handleZaloWebhookRequest: handleZaloWebhookRequestInternal } = await loadZaloWebhookModule();
249
+ return await handleZaloWebhookRequestInternal(req, res, async ({ update, target }) => {
250
+ await processUpdate({
251
+ update,
252
+ token: target.token,
253
+ account: target.account,
254
+ config: target.config,
255
+ runtime: target.runtime,
256
+ core: target.core,
257
+ mediaMaxMb: target.mediaMaxMb,
258
+ canHostMedia: target.canHostMedia,
259
+ webhookUrl: target.webhookUrl,
260
+ webhookPath: target.webhookPath,
261
+ statusSink: target.statusSink,
262
+ fetcher: target.fetcher
263
+ });
264
+ });
265
+ }
266
+ function startPollingLoop(params) {
267
+ const { token, account, config, runtime, core, mediaMaxMb, canHostMedia, webhookUrl, webhookPath, abortSignal, isStopped, statusSink, fetcher } = params;
268
+ const pollTimeout = 30;
269
+ const processingContext = {
270
+ token,
271
+ account,
272
+ config,
273
+ runtime,
274
+ core,
275
+ mediaMaxMb,
276
+ canHostMedia,
277
+ webhookUrl,
278
+ webhookPath,
279
+ statusSink,
280
+ fetcher
281
+ };
282
+ runtime.log?.(`[${account.accountId}] Zalo polling loop started timeout=${String(pollTimeout)}s`);
283
+ const poll = async () => {
284
+ if (isStopped() || abortSignal.aborted) return;
285
+ try {
286
+ const response = await getUpdates(token, { timeout: pollTimeout }, fetcher);
287
+ if (isStopped() || abortSignal.aborted) return;
288
+ if (response.ok && response.result) {
289
+ statusSink?.({ lastInboundAt: Date.now() });
290
+ await processUpdate({
291
+ update: response.result,
292
+ ...processingContext
293
+ });
294
+ }
295
+ } catch (err) {
296
+ if (err instanceof ZaloApiError && err.isPollingTimeout) {} else if (!isStopped() && !abortSignal.aborted) {
297
+ runtime.error?.(`[${account.accountId}] Zalo polling error: ${formatZaloError(err)}`);
298
+ await new Promise((resolve) => setTimeout(resolve, 5e3));
299
+ }
300
+ }
301
+ if (!isStopped() && !abortSignal.aborted) setImmediate(poll);
302
+ };
303
+ poll();
304
+ }
305
+ async function processUpdate(params) {
306
+ const { update, token, account, config, runtime, core, mediaMaxMb, statusSink, fetcher } = params;
307
+ const { event_name, message } = update;
308
+ const sharedContext = {
309
+ token,
310
+ account,
311
+ config,
312
+ runtime,
313
+ core,
314
+ mediaMaxMb,
315
+ canHostMedia: params.canHostMedia,
316
+ webhookUrl: params.webhookUrl,
317
+ webhookPath: params.webhookPath,
318
+ statusSink,
319
+ fetcher
320
+ };
321
+ if (!message) return;
322
+ switch (event_name) {
323
+ case "message.text.received":
324
+ await handleTextMessage({
325
+ message,
326
+ ...sharedContext
327
+ });
328
+ break;
329
+ case "message.image.received":
330
+ await handleImageMessage({
331
+ message,
332
+ ...sharedContext,
333
+ mediaMaxMb
334
+ });
335
+ break;
336
+ case "message.sticker.received":
337
+ logVerbose(core, runtime, `[${account.accountId}] Received sticker from ${message.from.id}`);
338
+ break;
339
+ case "message.unsupported.received":
340
+ logVerbose(core, runtime, `[${account.accountId}] Received unsupported message type from ${message.from.id}`);
341
+ break;
342
+ }
343
+ }
344
+ async function handleTextMessage(params) {
345
+ const { message } = params;
346
+ const { text } = message;
347
+ if (!text?.trim()) return;
348
+ await processMessageWithPipeline({
349
+ ...params,
350
+ text,
351
+ mediaPath: void 0,
352
+ mediaType: void 0
353
+ });
354
+ }
355
+ async function handleImageMessage(params) {
356
+ const { message, mediaMaxMb, account, core, runtime } = params;
357
+ const { photo_url, caption } = message;
358
+ const authorization = await authorizeZaloMessage({
359
+ ...params,
360
+ text: caption,
361
+ mediaPath: photo_url ? "__pending_media__" : void 0,
362
+ mediaType: void 0
363
+ });
364
+ if (!authorization) return;
365
+ let mediaPath;
366
+ let mediaType;
367
+ if (photo_url) try {
368
+ const maxBytes = mediaMaxMb * 1024 * 1024;
369
+ const fetched = await core.channel.media.fetchRemoteMedia({
370
+ url: photo_url,
371
+ maxBytes
372
+ });
373
+ const saved = await core.channel.media.saveMediaBuffer(fetched.buffer, fetched.contentType, "inbound", maxBytes);
374
+ mediaPath = saved.path;
375
+ mediaType = saved.contentType;
376
+ } catch (err) {
377
+ runtime.error?.(`[${account.accountId}] Failed to download Zalo image: ${String(err)}`);
378
+ }
379
+ await processMessageWithPipeline({
380
+ ...params,
381
+ authorization,
382
+ text: caption,
383
+ mediaPath,
384
+ mediaType
385
+ });
386
+ }
387
+ async function authorizeZaloMessage(params) {
388
+ const { message, account, config, runtime, core, text, mediaPath, token, statusSink, fetcher } = params;
389
+ const pairing = createChannelPairingController({
390
+ core,
391
+ channel: "zalo",
392
+ accountId: account.accountId
393
+ });
394
+ const { from, chat } = message;
395
+ const isGroup = chat.chat_type === "GROUP";
396
+ const chatId = chat.id;
397
+ const senderId = from.id;
398
+ const senderName = from.display_name ?? from.name;
399
+ const dmPolicy = account.config.dmPolicy ?? "pairing";
400
+ const configAllowFrom = (account.config.allowFrom ?? []).map((v) => String(v));
401
+ const configuredGroupAllowFrom = (account.config.groupAllowFrom ?? []).map((v) => String(v));
402
+ const groupAllowFrom = configuredGroupAllowFrom.length > 0 ? configuredGroupAllowFrom : configAllowFrom;
403
+ const defaultGroupPolicy = resolveDefaultGroupPolicy(config);
404
+ const groupAccess = isGroup ? evaluateZaloGroupAccess({
405
+ providerConfigPresent: config.channels?.zalo !== void 0,
406
+ configuredGroupPolicy: account.config.groupPolicy,
407
+ defaultGroupPolicy,
408
+ groupAllowFrom,
409
+ senderId
410
+ }) : void 0;
411
+ if (groupAccess) {
412
+ warnMissingProviderGroupPolicyFallbackOnce({
413
+ providerMissingFallbackApplied: groupAccess.providerMissingFallbackApplied,
414
+ providerKey: "zalo",
415
+ accountId: account.accountId,
416
+ log: (message) => logVerbose(core, runtime, message)
417
+ });
418
+ if (!groupAccess.allowed) {
419
+ if (groupAccess.reason === "disabled") logVerbose(core, runtime, `zalo: drop group ${chatId} (groupPolicy=disabled)`);
420
+ else if (groupAccess.reason === "empty_allowlist") logVerbose(core, runtime, `zalo: drop group ${chatId} (groupPolicy=allowlist, no groupAllowFrom)`);
421
+ else if (groupAccess.reason === "sender_not_allowlisted") logVerbose(core, runtime, `zalo: drop group sender ${senderId} (groupPolicy=allowlist)`);
422
+ return;
423
+ }
424
+ }
425
+ const rawBody = text?.trim() || (mediaPath ? "<media:image>" : "");
426
+ const { senderAllowedForCommands, commandAuthorized } = await resolveSenderCommandAuthorizationWithRuntime({
427
+ cfg: config,
428
+ rawBody,
429
+ isGroup,
430
+ dmPolicy,
431
+ configuredAllowFrom: configAllowFrom,
432
+ configuredGroupAllowFrom: groupAllowFrom,
433
+ senderId,
434
+ isSenderAllowed: isZaloSenderAllowed,
435
+ channel: "zalo",
436
+ accountId: account.accountId,
437
+ readAllowFromStore: pairing.readAllowFromStore,
438
+ runtime: core.channel.commands
439
+ });
440
+ const directDmOutcome = resolveDirectDmAuthorizationOutcome({
441
+ isGroup,
442
+ dmPolicy,
443
+ senderAllowedForCommands
444
+ });
445
+ if (directDmOutcome === "disabled") {
446
+ logVerbose(core, runtime, `Blocked zalo DM from ${senderId} (dmPolicy=disabled)`);
447
+ return;
448
+ }
449
+ if (directDmOutcome === "unauthorized") {
450
+ if (dmPolicy === "pairing") await pairing.issueChallenge({
451
+ senderId,
452
+ senderIdLine: `Your Zalo user id: ${senderId}`,
453
+ meta: { name: senderName ?? void 0 },
454
+ onCreated: () => {
455
+ logVerbose(core, runtime, `zalo pairing request sender=${senderId}`);
456
+ },
457
+ sendPairingReply: async (text) => {
458
+ await sendMessage(token, {
459
+ chat_id: chatId,
460
+ text
461
+ }, fetcher);
462
+ statusSink?.({ lastOutboundAt: Date.now() });
463
+ },
464
+ onReplyError: (err) => {
465
+ logVerbose(core, runtime, `zalo pairing reply failed for ${senderId}: ${String(err)}`);
466
+ }
467
+ });
468
+ else logVerbose(core, runtime, `Blocked unauthorized zalo sender ${senderId} (dmPolicy=${dmPolicy})`);
469
+ return;
470
+ }
471
+ return {
472
+ chatId,
473
+ commandAuthorized,
474
+ isGroup,
475
+ rawBody,
476
+ senderId,
477
+ senderName
478
+ };
479
+ }
480
+ async function processMessageWithPipeline(params) {
481
+ const { message, token, account, config, runtime, core, mediaPath, mediaType, statusSink, fetcher, authorization: authorizationOverride } = params;
482
+ const { message_id, date } = message;
483
+ const authorization = authorizationOverride ?? await authorizeZaloMessage({
484
+ ...params,
485
+ mediaPath,
486
+ mediaType
487
+ });
488
+ if (!authorization) return;
489
+ const { isGroup, chatId, senderId, senderName, rawBody, commandAuthorized } = authorization;
490
+ const { route, buildEnvelope } = resolveInboundRouteEnvelopeBuilderWithRuntime({
491
+ cfg: config,
492
+ channel: "zalo",
493
+ accountId: account.accountId,
494
+ peer: {
495
+ kind: isGroup ? "group" : "direct",
496
+ id: chatId
497
+ },
498
+ runtime: core.channel,
499
+ sessionStore: config.session?.store
500
+ });
501
+ if (isGroup && core.channel.commands.isControlCommandMessage(rawBody, config) && commandAuthorized !== true) {
502
+ logVerbose(core, runtime, `zalo: drop control command from unauthorized sender ${senderId}`);
503
+ return;
504
+ }
505
+ const fromLabel = isGroup ? `group:${chatId}` : senderName || `user:${senderId}`;
506
+ const { storePath, body } = buildEnvelope({
507
+ channel: "Zalo",
508
+ from: fromLabel,
509
+ timestamp: date ? date * 1e3 : void 0,
510
+ body: rawBody
511
+ });
512
+ const ctxPayload = core.channel.turn.buildContext({
513
+ channel: "zalo",
514
+ accountId: route.accountId,
515
+ messageId: message_id,
516
+ timestamp: date ? date * 1e3 : void 0,
517
+ from: isGroup ? `zalo:group:${chatId}` : `zalo:${senderId}`,
518
+ sender: {
519
+ id: senderId,
520
+ name: senderName || void 0
521
+ },
522
+ conversation: {
523
+ kind: isGroup ? "group" : "direct",
524
+ id: chatId,
525
+ label: fromLabel,
526
+ routePeer: {
527
+ kind: isGroup ? "group" : "direct",
528
+ id: chatId
529
+ }
530
+ },
531
+ route: {
532
+ agentId: route.agentId,
533
+ accountId: route.accountId,
534
+ routeSessionKey: route.sessionKey
535
+ },
536
+ reply: {
537
+ to: `zalo:${chatId}`,
538
+ originatingTo: `zalo:${chatId}`
539
+ },
540
+ message: {
541
+ body,
542
+ bodyForAgent: rawBody,
543
+ rawBody,
544
+ commandBody: rawBody,
545
+ envelopeFrom: fromLabel
546
+ },
547
+ media: mediaPath || mediaType ? [{
548
+ path: mediaPath,
549
+ url: mediaPath,
550
+ contentType: mediaType
551
+ }] : void 0,
552
+ extra: {
553
+ CommandAuthorized: commandAuthorized,
554
+ GroupSubject: void 0
555
+ }
556
+ });
557
+ const tableMode = core.channel.text.resolveMarkdownTableMode({
558
+ cfg: config,
559
+ channel: "zalo",
560
+ accountId: account.accountId
561
+ });
562
+ const { onModelSelected, ...replyPipeline } = createChannelReplyPipeline({
563
+ cfg: config,
564
+ agentId: route.agentId,
565
+ channel: "zalo",
566
+ accountId: account.accountId,
567
+ typing: {
568
+ start: async () => {
569
+ await sendChatAction(token, {
570
+ chat_id: chatId,
571
+ action: "typing"
572
+ }, fetcher, ZALO_TYPING_TIMEOUT_MS);
573
+ },
574
+ onStartError: (err) => {
575
+ logTypingFailure({
576
+ log: (message) => logVerbose(core, runtime, message),
577
+ channel: "zalo",
578
+ action: "start",
579
+ target: chatId,
580
+ error: err
581
+ });
582
+ }
583
+ }
584
+ });
585
+ await core.channel.turn.run({
586
+ channel: "zalo",
587
+ accountId: account.accountId,
588
+ raw: message,
589
+ adapter: {
590
+ ingest: () => ({
591
+ id: message_id,
592
+ timestamp: date ? date * 1e3 : void 0,
593
+ rawText: rawBody,
594
+ textForAgent: rawBody,
595
+ textForCommands: rawBody,
596
+ raw: message
597
+ }),
598
+ resolveTurn: () => ({
599
+ cfg: config,
600
+ channel: "zalo",
601
+ accountId: account.accountId,
602
+ agentId: route.agentId,
603
+ routeSessionKey: route.sessionKey,
604
+ storePath,
605
+ ctxPayload,
606
+ recordInboundSession: core.channel.session.recordInboundSession,
607
+ dispatchReplyWithBufferedBlockDispatcher: core.channel.reply.dispatchReplyWithBufferedBlockDispatcher,
608
+ delivery: {
609
+ deliver: async (payload) => {
610
+ await deliverZaloReply({
611
+ payload,
612
+ token,
613
+ chatId,
614
+ runtime,
615
+ core,
616
+ config,
617
+ webhookUrl: params.webhookUrl,
618
+ webhookPath: params.webhookPath,
619
+ proxyUrl: account.config.proxy,
620
+ mediaMaxBytes: params.mediaMaxMb * 1024 * 1024,
621
+ canHostMedia: params.canHostMedia,
622
+ accountId: account.accountId,
623
+ statusSink,
624
+ fetcher,
625
+ tableMode
626
+ });
627
+ },
628
+ onError: (err, info) => {
629
+ runtime.error?.(`[${account.accountId}] Zalo ${info.kind} reply failed: ${String(err)}`);
630
+ }
631
+ },
632
+ dispatcherOptions: replyPipeline,
633
+ replyOptions: { onModelSelected },
634
+ record: { onRecordError: (err) => {
635
+ runtime.error?.(`zalo: failed updating session meta: ${String(err)}`);
636
+ } }
637
+ })
638
+ }
639
+ });
640
+ }
641
+ async function deliverZaloReply(params) {
642
+ const { payload, token, chatId, runtime, core, config, webhookUrl, webhookPath, proxyUrl, mediaMaxBytes, canHostMedia, accountId, statusSink, fetcher } = params;
643
+ const tableMode = params.tableMode ?? "code";
644
+ const reply = resolveSendableOutboundReplyParts(payload, { text: core.channel.text.convertMarkdownTables(payload.text ?? "", tableMode) });
645
+ const chunkMode = core.channel.text.resolveChunkMode(config, "zalo", accountId);
646
+ await deliverTextOrMediaReply({
647
+ payload,
648
+ text: reply.text,
649
+ chunkText: (value) => core.channel.text.chunkMarkdownTextWithMode(value, ZALO_TEXT_LIMIT, chunkMode),
650
+ sendText: async (chunk) => {
651
+ try {
652
+ await sendMessage(token, {
653
+ chat_id: chatId,
654
+ text: chunk
655
+ }, fetcher);
656
+ statusSink?.({ lastOutboundAt: Date.now() });
657
+ } catch (err) {
658
+ runtime.error?.(`Zalo message send failed: ${String(err)}`);
659
+ }
660
+ },
661
+ sendMedia: async ({ mediaUrl, caption }) => {
662
+ await sendPhoto(token, {
663
+ chat_id: chatId,
664
+ photo: canHostMedia && webhookUrl && webhookPath ? await prepareHostedZaloMediaUrl({
665
+ mediaUrl,
666
+ webhookUrl,
667
+ webhookPath,
668
+ maxBytes: mediaMaxBytes,
669
+ proxyUrl
670
+ }) : mediaUrl,
671
+ caption
672
+ }, fetcher);
673
+ statusSink?.({ lastOutboundAt: Date.now() });
674
+ },
675
+ onMediaError: (error) => {
676
+ runtime.error?.(`Zalo photo send failed: ${error instanceof Error ? error.message : JSON.stringify(error)}`);
677
+ }
678
+ });
679
+ }
680
+ async function monitorZaloProvider(options) {
681
+ const { token, account, config, runtime, abortSignal, useWebhook, webhookUrl, webhookSecret, webhookPath, statusSink, fetcher: fetcherOverride } = options;
682
+ const core = getZaloRuntime();
683
+ const effectiveMediaMaxMb = account.config.mediaMaxMb ?? DEFAULT_MEDIA_MAX_MB;
684
+ const fetcher = fetcherOverride ?? resolveZaloProxyFetch(account.config.proxy);
685
+ const mode = useWebhook ? "webhook" : "polling";
686
+ const effectiveWebhookUrl = normalizeWebhookUrl(webhookUrl ?? account.config.webhookUrl);
687
+ const effectiveWebhookPath = effectiveWebhookUrl || webhookPath?.trim() || account.config.webhookPath?.trim() ? resolveWebhookPath({
688
+ webhookPath: webhookPath ?? account.config.webhookPath,
689
+ webhookUrl: effectiveWebhookUrl,
690
+ defaultPath: null
691
+ }) ?? void 0 : void 0;
692
+ const canHostMedia = Boolean(effectiveWebhookUrl && effectiveWebhookPath);
693
+ const hostedMediaRoutePath = canHostMedia && effectiveWebhookUrl ? resolveHostedZaloMediaRoutePrefix({
694
+ webhookUrl: effectiveWebhookUrl,
695
+ webhookPath: effectiveWebhookPath
696
+ }) : void 0;
697
+ let stopped = false;
698
+ const stopHandlers = [];
699
+ let cleanupWebhook;
700
+ const stop = () => {
701
+ if (stopped) return;
702
+ stopped = true;
703
+ for (const handler of stopHandlers) handler();
704
+ };
705
+ const stopOnAbort = () => {
706
+ if (!useWebhook) stop();
707
+ };
708
+ abortSignal.addEventListener("abort", stopOnAbort, { once: true });
709
+ runtime.log?.(`[${account.accountId}] Zalo provider init mode=${mode} mediaMaxMb=${String(effectiveMediaMaxMb)}`);
710
+ try {
711
+ if (hostedMediaRoutePath) {
712
+ const unregisterHostedMediaRoute = registerSharedHostedMediaRoute({
713
+ path: hostedMediaRoutePath,
714
+ accountId: account.accountId,
715
+ log: runtime.log
716
+ });
717
+ stopHandlers.push(unregisterHostedMediaRoute);
718
+ }
719
+ if (useWebhook) {
720
+ const { registerZaloWebhookTarget } = await loadZaloWebhookModule();
721
+ if (!effectiveWebhookUrl || !webhookSecret) throw new Error("Zalo webhookUrl and webhookSecret are required for webhook mode");
722
+ if (!effectiveWebhookUrl.startsWith("https://")) throw new Error("Zalo webhook URL must use HTTPS");
723
+ if (webhookSecret.length < 8 || webhookSecret.length > 256) throw new Error("Zalo webhook secret must be 8-256 characters");
724
+ const path = effectiveWebhookPath;
725
+ if (!path) throw new Error("Zalo webhookPath could not be derived");
726
+ runtime.log?.(`[${account.accountId}] Zalo configuring webhook path=${path} target=${describeWebhookTarget(effectiveWebhookUrl)}`);
727
+ await setWebhook(token, {
728
+ url: effectiveWebhookUrl,
729
+ secret_token: webhookSecret
730
+ }, fetcher);
731
+ let webhookCleanupPromise;
732
+ cleanupWebhook = async () => {
733
+ if (!webhookCleanupPromise) webhookCleanupPromise = (async () => {
734
+ runtime.log?.(`[${account.accountId}] Zalo stopping; deleting webhook`);
735
+ try {
736
+ await deleteWebhook(token, fetcher, WEBHOOK_CLEANUP_TIMEOUT_MS);
737
+ runtime.log?.(`[${account.accountId}] Zalo webhook deleted`);
738
+ } catch (err) {
739
+ const detail = err instanceof Error && err.name === "AbortError" ? `timed out after ${String(WEBHOOK_CLEANUP_TIMEOUT_MS)}ms` : formatZaloError(err);
740
+ runtime.error?.(`[${account.accountId}] Zalo webhook delete failed: ${detail}`);
741
+ }
742
+ })();
743
+ await webhookCleanupPromise;
744
+ };
745
+ runtime.log?.(`[${account.accountId}] Zalo webhook registered path=${path}`);
746
+ const unregister = registerZaloWebhookTarget({
747
+ token,
748
+ account,
749
+ config,
750
+ runtime,
751
+ core,
752
+ path,
753
+ webhookUrl: effectiveWebhookUrl,
754
+ webhookPath: path,
755
+ secret: webhookSecret,
756
+ statusSink: (patch) => statusSink?.(patch),
757
+ mediaMaxMb: effectiveMediaMaxMb,
758
+ canHostMedia,
759
+ fetcher
760
+ }, { route: {
761
+ auth: "plugin",
762
+ match: "exact",
763
+ pluginId: "zalo",
764
+ source: "zalo-webhook",
765
+ accountId: account.accountId,
766
+ log: runtime.log,
767
+ handler: async (req, res) => {
768
+ if (!await handleZaloWebhookRequest(req, res) && !res.headersSent) {
769
+ res.statusCode = 404;
770
+ res.setHeader("Content-Type", "text/plain; charset=utf-8");
771
+ res.end("Not Found");
772
+ }
773
+ }
774
+ } });
775
+ stopHandlers.push(unregister);
776
+ await waitForAbortSignal(abortSignal);
777
+ return;
778
+ }
779
+ runtime.log?.(`[${account.accountId}] Zalo polling mode: clearing webhook before startup`);
780
+ try {
781
+ try {
782
+ const currentWebhookUrl = normalizeWebhookUrl((await getWebhookInfo(token, fetcher)).result?.url);
783
+ if (!currentWebhookUrl) runtime.log?.(`[${account.accountId}] Zalo polling mode ready (no webhook configured)`);
784
+ else {
785
+ runtime.log?.(`[${account.accountId}] Zalo polling mode disabling existing webhook ${describeWebhookTarget(currentWebhookUrl)}`);
786
+ await deleteWebhook(token, fetcher);
787
+ runtime.log?.(`[${account.accountId}] Zalo polling mode ready (webhook disabled)`);
788
+ }
789
+ } catch (err) {
790
+ if (err instanceof ZaloApiError && err.errorCode === 404) runtime.log?.(`[${account.accountId}] Zalo polling mode webhook inspection unavailable; continuing without webhook cleanup`);
791
+ else throw err;
792
+ }
793
+ } catch (err) {
794
+ runtime.error?.(`[${account.accountId}] Zalo polling startup could not clear webhook: ${formatZaloError(err)}`);
795
+ }
796
+ startPollingLoop({
797
+ token,
798
+ account,
799
+ config,
800
+ runtime,
801
+ core,
802
+ canHostMedia,
803
+ webhookUrl: effectiveWebhookUrl,
804
+ webhookPath: effectiveWebhookPath,
805
+ abortSignal,
806
+ isStopped: () => stopped,
807
+ mediaMaxMb: effectiveMediaMaxMb,
808
+ statusSink,
809
+ fetcher
810
+ });
811
+ await waitForAbortSignal(abortSignal);
812
+ } catch (err) {
813
+ runtime.error?.(`[${account.accountId}] Zalo provider startup failed mode=${mode}: ${formatZaloError(err)}`);
814
+ throw err;
815
+ } finally {
816
+ abortSignal.removeEventListener("abort", stopOnAbort);
817
+ await cleanupWebhook?.();
818
+ stop();
819
+ runtime.log?.(`[${account.accountId}] Zalo provider stopped mode=${mode}`);
820
+ }
821
+ }
822
+ //#endregion
823
+ export { monitorZaloProvider };