@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.
- package/dist/accounts-9NLDDlZ8.js +118 -0
- package/dist/actions.runtime-kJ65ZxW7.js +5 -0
- package/dist/api.js +5 -0
- package/dist/channel-VPbtV3Oq.js +343 -0
- package/dist/channel-plugin-api.js +2 -0
- package/dist/channel.runtime-BnTAWQx5.js +106 -0
- package/dist/contract-api.js +3 -0
- package/dist/group-access-DZR43lOR.js +30 -0
- package/dist/index.js +22 -0
- package/dist/monitor-DMysJBWa.js +823 -0
- package/dist/monitor.webhook-DqnuvgjV.js +175 -0
- package/dist/proxy-CY8VuC6H.js +135 -0
- package/dist/runtime-BRFxnYQx.js +8 -0
- package/dist/runtime-api-MOTmRW4F.js +19 -0
- package/dist/runtime-api.js +3 -0
- package/dist/secret-contract-Dw93tGo2.js +87 -0
- package/dist/secret-contract-api.js +2 -0
- package/dist/send-Gv3l5EGI.js +101 -0
- package/dist/setup-api.js +30 -0
- package/dist/setup-core-DigRD3j1.js +166 -0
- package/dist/setup-entry.js +15 -0
- package/dist/setup-surface-2Up3yWov.js +216 -0
- package/dist/test-api.js +2 -0
- package/package.json +15 -6
- package/api.ts +0 -9
- package/channel-plugin-api.ts +0 -1
- package/contract-api.ts +0 -5
- package/index.test.ts +0 -15
- package/index.ts +0 -20
- package/runtime-api.test.ts +0 -17
- package/runtime-api.ts +0 -75
- package/secret-contract-api.ts +0 -5
- package/setup-api.ts +0 -34
- package/setup-entry.ts +0 -13
- package/src/accounts.test.ts +0 -70
- package/src/accounts.ts +0 -60
- package/src/actions.runtime.ts +0 -5
- package/src/actions.test.ts +0 -32
- package/src/actions.ts +0 -62
- package/src/api.test.ts +0 -149
- package/src/api.ts +0 -265
- package/src/approval-auth.test.ts +0 -17
- package/src/approval-auth.ts +0 -25
- package/src/channel.directory.test.ts +0 -59
- package/src/channel.runtime.ts +0 -93
- package/src/channel.startup.test.ts +0 -101
- package/src/channel.ts +0 -275
- package/src/config-schema.test.ts +0 -30
- package/src/config-schema.ts +0 -29
- package/src/group-access.ts +0 -49
- package/src/monitor.group-policy.test.ts +0 -94
- package/src/monitor.image.polling.test.ts +0 -110
- package/src/monitor.lifecycle.test.ts +0 -198
- package/src/monitor.pairing.lifecycle.test.ts +0 -141
- package/src/monitor.polling.media-reply.test.ts +0 -425
- package/src/monitor.reply-once.lifecycle.test.ts +0 -171
- package/src/monitor.ts +0 -1028
- package/src/monitor.types.ts +0 -4
- package/src/monitor.webhook.test.ts +0 -806
- package/src/monitor.webhook.ts +0 -278
- package/src/outbound-media.test.ts +0 -182
- package/src/outbound-media.ts +0 -241
- package/src/outbound-payload.contract.test.ts +0 -45
- package/src/probe.ts +0 -45
- package/src/proxy.ts +0 -24
- package/src/runtime-api.ts +0 -75
- package/src/runtime-support.ts +0 -91
- package/src/runtime.ts +0 -9
- package/src/secret-contract.ts +0 -109
- package/src/secret-input.ts +0 -5
- package/src/send.test.ts +0 -120
- package/src/send.ts +0 -153
- package/src/session-route.ts +0 -32
- package/src/setup-allow-from.ts +0 -94
- package/src/setup-core.ts +0 -149
- package/src/setup-status.test.ts +0 -33
- package/src/setup-surface.test.ts +0 -175
- package/src/setup-surface.ts +0 -291
- package/src/status-issues.test.ts +0 -17
- package/src/status-issues.ts +0 -37
- package/src/test-support/lifecycle-test-support.ts +0 -413
- package/src/test-support/monitor-mocks-test-support.ts +0 -209
- package/src/token.test.ts +0 -92
- package/src/token.ts +0 -79
- package/src/types.ts +0 -50
- package/test-api.ts +0 -1
- package/tsconfig.json +0 -16
package/src/monitor.ts
DELETED
|
@@ -1,1028 +0,0 @@
|
|
|
1
|
-
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
-
import { logTypingFailure } from "openclaw/plugin-sdk/channel-feedback";
|
|
3
|
-
import { createChannelPairingController } from "openclaw/plugin-sdk/channel-pairing";
|
|
4
|
-
import { createChannelReplyPipeline } from "openclaw/plugin-sdk/channel-reply-pipeline";
|
|
5
|
-
import {
|
|
6
|
-
resolveDirectDmAuthorizationOutcome,
|
|
7
|
-
resolveSenderCommandAuthorizationWithRuntime,
|
|
8
|
-
} from "openclaw/plugin-sdk/command-auth";
|
|
9
|
-
import type { MarkdownTableMode, OpenClawConfig } from "openclaw/plugin-sdk/config-types";
|
|
10
|
-
import { resolveInboundRouteEnvelopeBuilderWithRuntime } from "openclaw/plugin-sdk/inbound-envelope";
|
|
11
|
-
import { resolveSendableOutboundReplyParts } from "openclaw/plugin-sdk/reply-payload";
|
|
12
|
-
import {
|
|
13
|
-
deliverTextOrMediaReply,
|
|
14
|
-
type OutboundReplyPayload,
|
|
15
|
-
} from "openclaw/plugin-sdk/reply-payload";
|
|
16
|
-
import { waitForAbortSignal } from "openclaw/plugin-sdk/runtime-env";
|
|
17
|
-
import {
|
|
18
|
-
resolveDefaultGroupPolicy,
|
|
19
|
-
warnMissingProviderGroupPolicyFallbackOnce,
|
|
20
|
-
} from "openclaw/plugin-sdk/runtime-group-policy";
|
|
21
|
-
import { registerPluginHttpRoute, resolveWebhookPath } from "openclaw/plugin-sdk/webhook-ingress";
|
|
22
|
-
import type { ResolvedZaloAccount } from "./accounts.js";
|
|
23
|
-
import {
|
|
24
|
-
ZaloApiError,
|
|
25
|
-
deleteWebhook,
|
|
26
|
-
getWebhookInfo,
|
|
27
|
-
getUpdates,
|
|
28
|
-
sendChatAction,
|
|
29
|
-
sendMessage,
|
|
30
|
-
sendPhoto,
|
|
31
|
-
setWebhook,
|
|
32
|
-
type ZaloFetch,
|
|
33
|
-
type ZaloMessage,
|
|
34
|
-
type ZaloUpdate,
|
|
35
|
-
} from "./api.js";
|
|
36
|
-
import {
|
|
37
|
-
evaluateZaloGroupAccess,
|
|
38
|
-
isZaloSenderAllowed,
|
|
39
|
-
resolveZaloRuntimeGroupPolicy,
|
|
40
|
-
} from "./group-access.js";
|
|
41
|
-
import { resolveZaloProxyFetch } from "./proxy.js";
|
|
42
|
-
import { getZaloRuntime } from "./runtime.js";
|
|
43
|
-
export type { ZaloRuntimeEnv } from "./monitor.types.js";
|
|
44
|
-
import type { ZaloRuntimeEnv } from "./monitor.types.js";
|
|
45
|
-
import {
|
|
46
|
-
prepareHostedZaloMediaUrl,
|
|
47
|
-
resolveHostedZaloMediaRoutePrefix,
|
|
48
|
-
tryHandleHostedZaloMediaRequest,
|
|
49
|
-
} from "./outbound-media.js";
|
|
50
|
-
|
|
51
|
-
export type ZaloMonitorOptions = {
|
|
52
|
-
token: string;
|
|
53
|
-
account: ResolvedZaloAccount;
|
|
54
|
-
config: OpenClawConfig;
|
|
55
|
-
runtime: ZaloRuntimeEnv;
|
|
56
|
-
abortSignal: AbortSignal;
|
|
57
|
-
useWebhook?: boolean;
|
|
58
|
-
webhookUrl?: string;
|
|
59
|
-
webhookSecret?: string;
|
|
60
|
-
webhookPath?: string;
|
|
61
|
-
fetcher?: ZaloFetch;
|
|
62
|
-
statusSink?: (patch: { lastInboundAt?: number; lastOutboundAt?: number }) => void;
|
|
63
|
-
};
|
|
64
|
-
|
|
65
|
-
const ZALO_TEXT_LIMIT = 2000;
|
|
66
|
-
const DEFAULT_MEDIA_MAX_MB = 5;
|
|
67
|
-
const WEBHOOK_CLEANUP_TIMEOUT_MS = 5_000;
|
|
68
|
-
const ZALO_TYPING_TIMEOUT_MS = 5_000;
|
|
69
|
-
|
|
70
|
-
type ZaloCoreRuntime = ReturnType<typeof getZaloRuntime>;
|
|
71
|
-
type ZaloStatusSink = (patch: { lastInboundAt?: number; lastOutboundAt?: number }) => void;
|
|
72
|
-
type ZaloWebhookModule = typeof import("./monitor.webhook.js");
|
|
73
|
-
type ZaloProcessingContext = {
|
|
74
|
-
token: string;
|
|
75
|
-
account: ResolvedZaloAccount;
|
|
76
|
-
config: OpenClawConfig;
|
|
77
|
-
runtime: ZaloRuntimeEnv;
|
|
78
|
-
core: ZaloCoreRuntime;
|
|
79
|
-
mediaMaxMb: number;
|
|
80
|
-
canHostMedia: boolean;
|
|
81
|
-
webhookUrl?: string;
|
|
82
|
-
webhookPath?: string;
|
|
83
|
-
statusSink?: ZaloStatusSink;
|
|
84
|
-
fetcher?: ZaloFetch;
|
|
85
|
-
};
|
|
86
|
-
type ZaloPollingLoopParams = ZaloProcessingContext & {
|
|
87
|
-
abortSignal: AbortSignal;
|
|
88
|
-
isStopped: () => boolean;
|
|
89
|
-
};
|
|
90
|
-
type ZaloUpdateProcessingParams = ZaloProcessingContext & {
|
|
91
|
-
update: ZaloUpdate;
|
|
92
|
-
};
|
|
93
|
-
|
|
94
|
-
let zaloWebhookModulePromise: Promise<ZaloWebhookModule> | undefined;
|
|
95
|
-
const hostedMediaRouteRefs = new Map<string, { count: number; unregisters: Array<() => void> }>();
|
|
96
|
-
|
|
97
|
-
function loadZaloWebhookModule(): Promise<ZaloWebhookModule> {
|
|
98
|
-
zaloWebhookModulePromise ??= import("./monitor.webhook.js");
|
|
99
|
-
return zaloWebhookModulePromise;
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
function registerSharedHostedMediaRoute(params: {
|
|
103
|
-
path: string;
|
|
104
|
-
accountId: string;
|
|
105
|
-
log?: (message: string) => void;
|
|
106
|
-
}): () => void {
|
|
107
|
-
const unregister = registerPluginHttpRoute({
|
|
108
|
-
auth: "plugin",
|
|
109
|
-
match: "prefix",
|
|
110
|
-
path: params.path,
|
|
111
|
-
pluginId: "zalo",
|
|
112
|
-
source: "zalo-hosted-media",
|
|
113
|
-
accountId: params.accountId,
|
|
114
|
-
log: params.log,
|
|
115
|
-
handler: async (req, res) => {
|
|
116
|
-
const handled = await tryHandleHostedZaloMediaRequest(req, res);
|
|
117
|
-
if (!handled && !res.headersSent) {
|
|
118
|
-
res.statusCode = 404;
|
|
119
|
-
res.setHeader("Content-Type", "text/plain; charset=utf-8");
|
|
120
|
-
res.end("Not Found");
|
|
121
|
-
}
|
|
122
|
-
},
|
|
123
|
-
});
|
|
124
|
-
|
|
125
|
-
const existing = hostedMediaRouteRefs.get(params.path);
|
|
126
|
-
if (existing) {
|
|
127
|
-
existing.count += 1;
|
|
128
|
-
existing.unregisters.push(unregister);
|
|
129
|
-
return () => {
|
|
130
|
-
const current = hostedMediaRouteRefs.get(params.path);
|
|
131
|
-
if (!current) {
|
|
132
|
-
return;
|
|
133
|
-
}
|
|
134
|
-
if (current.count > 1) {
|
|
135
|
-
current.count -= 1;
|
|
136
|
-
return;
|
|
137
|
-
}
|
|
138
|
-
hostedMediaRouteRefs.delete(params.path);
|
|
139
|
-
for (const unregisterHandle of current.unregisters) {
|
|
140
|
-
unregisterHandle();
|
|
141
|
-
}
|
|
142
|
-
};
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
hostedMediaRouteRefs.set(params.path, { count: 1, unregisters: [unregister] });
|
|
146
|
-
return () => {
|
|
147
|
-
const current = hostedMediaRouteRefs.get(params.path);
|
|
148
|
-
if (!current) {
|
|
149
|
-
return;
|
|
150
|
-
}
|
|
151
|
-
if (current.count > 1) {
|
|
152
|
-
current.count -= 1;
|
|
153
|
-
return;
|
|
154
|
-
}
|
|
155
|
-
hostedMediaRouteRefs.delete(params.path);
|
|
156
|
-
for (const unregisterHandle of current.unregisters) {
|
|
157
|
-
unregisterHandle();
|
|
158
|
-
}
|
|
159
|
-
};
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
type ZaloMessagePipelineParams = ZaloProcessingContext & {
|
|
163
|
-
message: ZaloMessage;
|
|
164
|
-
text?: string;
|
|
165
|
-
mediaPath?: string;
|
|
166
|
-
mediaType?: string;
|
|
167
|
-
authorization?: ZaloMessageAuthorizationResult;
|
|
168
|
-
};
|
|
169
|
-
type ZaloImageMessageParams = ZaloProcessingContext & {
|
|
170
|
-
message: ZaloMessage;
|
|
171
|
-
};
|
|
172
|
-
type ZaloMessageAuthorizationResult = {
|
|
173
|
-
chatId: string;
|
|
174
|
-
commandAuthorized: boolean | undefined;
|
|
175
|
-
isGroup: boolean;
|
|
176
|
-
rawBody: string;
|
|
177
|
-
senderId: string;
|
|
178
|
-
senderName: string | undefined;
|
|
179
|
-
};
|
|
180
|
-
|
|
181
|
-
function formatZaloError(error: unknown): string {
|
|
182
|
-
if (error instanceof Error) {
|
|
183
|
-
return error.stack ?? `${error.name}: ${error.message}`;
|
|
184
|
-
}
|
|
185
|
-
return String(error);
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
function describeWebhookTarget(rawUrl: string): string {
|
|
189
|
-
try {
|
|
190
|
-
const parsed = new URL(rawUrl);
|
|
191
|
-
return `${parsed.origin}${parsed.pathname}`;
|
|
192
|
-
} catch {
|
|
193
|
-
return rawUrl;
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
function normalizeWebhookUrl(url: string | undefined): string | undefined {
|
|
198
|
-
const trimmed = url?.trim();
|
|
199
|
-
return trimmed ? trimmed : undefined;
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
function logVerbose(core: ZaloCoreRuntime, runtime: ZaloRuntimeEnv, message: string): void {
|
|
203
|
-
if (core.logging.shouldLogVerbose()) {
|
|
204
|
-
runtime.log?.(`[zalo] ${message}`);
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
export async function handleZaloWebhookRequest(
|
|
209
|
-
req: IncomingMessage,
|
|
210
|
-
res: ServerResponse,
|
|
211
|
-
): Promise<boolean> {
|
|
212
|
-
const { handleZaloWebhookRequest: handleZaloWebhookRequestInternal } =
|
|
213
|
-
await loadZaloWebhookModule();
|
|
214
|
-
return await handleZaloWebhookRequestInternal(req, res, async ({ update, target }) => {
|
|
215
|
-
await processUpdate({
|
|
216
|
-
update,
|
|
217
|
-
token: target.token,
|
|
218
|
-
account: target.account,
|
|
219
|
-
config: target.config,
|
|
220
|
-
runtime: target.runtime,
|
|
221
|
-
core: target.core as ZaloCoreRuntime,
|
|
222
|
-
mediaMaxMb: target.mediaMaxMb,
|
|
223
|
-
canHostMedia: target.canHostMedia,
|
|
224
|
-
webhookUrl: target.webhookUrl,
|
|
225
|
-
webhookPath: target.webhookPath,
|
|
226
|
-
statusSink: target.statusSink,
|
|
227
|
-
fetcher: target.fetcher,
|
|
228
|
-
});
|
|
229
|
-
});
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
function startPollingLoop(params: ZaloPollingLoopParams) {
|
|
233
|
-
const {
|
|
234
|
-
token,
|
|
235
|
-
account,
|
|
236
|
-
config,
|
|
237
|
-
runtime,
|
|
238
|
-
core,
|
|
239
|
-
mediaMaxMb,
|
|
240
|
-
canHostMedia,
|
|
241
|
-
webhookUrl,
|
|
242
|
-
webhookPath,
|
|
243
|
-
abortSignal,
|
|
244
|
-
isStopped,
|
|
245
|
-
statusSink,
|
|
246
|
-
fetcher,
|
|
247
|
-
} = params;
|
|
248
|
-
const pollTimeout = 30;
|
|
249
|
-
const processingContext = {
|
|
250
|
-
token,
|
|
251
|
-
account,
|
|
252
|
-
config,
|
|
253
|
-
runtime,
|
|
254
|
-
core,
|
|
255
|
-
mediaMaxMb,
|
|
256
|
-
canHostMedia,
|
|
257
|
-
webhookUrl,
|
|
258
|
-
webhookPath,
|
|
259
|
-
statusSink,
|
|
260
|
-
fetcher,
|
|
261
|
-
};
|
|
262
|
-
|
|
263
|
-
runtime.log?.(`[${account.accountId}] Zalo polling loop started timeout=${String(pollTimeout)}s`);
|
|
264
|
-
|
|
265
|
-
const poll = async (): Promise<void> => {
|
|
266
|
-
if (isStopped() || abortSignal.aborted) {
|
|
267
|
-
return undefined;
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
try {
|
|
271
|
-
const response = await getUpdates(token, { timeout: pollTimeout }, fetcher);
|
|
272
|
-
if (isStopped() || abortSignal.aborted) {
|
|
273
|
-
return undefined;
|
|
274
|
-
}
|
|
275
|
-
if (response.ok && response.result) {
|
|
276
|
-
statusSink?.({ lastInboundAt: Date.now() });
|
|
277
|
-
await processUpdate({
|
|
278
|
-
update: response.result,
|
|
279
|
-
...processingContext,
|
|
280
|
-
});
|
|
281
|
-
}
|
|
282
|
-
} catch (err) {
|
|
283
|
-
if (err instanceof ZaloApiError && err.isPollingTimeout) {
|
|
284
|
-
// no updates
|
|
285
|
-
} else if (!isStopped() && !abortSignal.aborted) {
|
|
286
|
-
runtime.error?.(`[${account.accountId}] Zalo polling error: ${formatZaloError(err)}`);
|
|
287
|
-
await new Promise((resolve) => setTimeout(resolve, 5000));
|
|
288
|
-
}
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
if (!isStopped() && !abortSignal.aborted) {
|
|
292
|
-
setImmediate(poll);
|
|
293
|
-
}
|
|
294
|
-
};
|
|
295
|
-
|
|
296
|
-
void poll();
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
async function processUpdate(params: ZaloUpdateProcessingParams): Promise<void> {
|
|
300
|
-
const { update, token, account, config, runtime, core, mediaMaxMb, statusSink, fetcher } = params;
|
|
301
|
-
const { event_name, message } = update;
|
|
302
|
-
const sharedContext = {
|
|
303
|
-
token,
|
|
304
|
-
account,
|
|
305
|
-
config,
|
|
306
|
-
runtime,
|
|
307
|
-
core,
|
|
308
|
-
mediaMaxMb,
|
|
309
|
-
canHostMedia: params.canHostMedia,
|
|
310
|
-
webhookUrl: params.webhookUrl,
|
|
311
|
-
webhookPath: params.webhookPath,
|
|
312
|
-
statusSink,
|
|
313
|
-
fetcher,
|
|
314
|
-
};
|
|
315
|
-
if (!message) {
|
|
316
|
-
return undefined;
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
switch (event_name) {
|
|
320
|
-
case "message.text.received":
|
|
321
|
-
await handleTextMessage({
|
|
322
|
-
message,
|
|
323
|
-
...sharedContext,
|
|
324
|
-
});
|
|
325
|
-
break;
|
|
326
|
-
case "message.image.received":
|
|
327
|
-
await handleImageMessage({
|
|
328
|
-
message,
|
|
329
|
-
...sharedContext,
|
|
330
|
-
mediaMaxMb,
|
|
331
|
-
});
|
|
332
|
-
break;
|
|
333
|
-
case "message.sticker.received":
|
|
334
|
-
logVerbose(core, runtime, `[${account.accountId}] Received sticker from ${message.from.id}`);
|
|
335
|
-
break;
|
|
336
|
-
case "message.unsupported.received":
|
|
337
|
-
logVerbose(
|
|
338
|
-
core,
|
|
339
|
-
runtime,
|
|
340
|
-
`[${account.accountId}] Received unsupported message type from ${message.from.id}`,
|
|
341
|
-
);
|
|
342
|
-
break;
|
|
343
|
-
}
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
async function handleTextMessage(
|
|
347
|
-
params: ZaloProcessingContext & { message: ZaloMessage },
|
|
348
|
-
): Promise<void> {
|
|
349
|
-
const { message } = params;
|
|
350
|
-
const { text } = message;
|
|
351
|
-
if (!text?.trim()) {
|
|
352
|
-
return undefined;
|
|
353
|
-
}
|
|
354
|
-
|
|
355
|
-
await processMessageWithPipeline({
|
|
356
|
-
...params,
|
|
357
|
-
text,
|
|
358
|
-
mediaPath: undefined,
|
|
359
|
-
mediaType: undefined,
|
|
360
|
-
});
|
|
361
|
-
}
|
|
362
|
-
|
|
363
|
-
async function handleImageMessage(params: ZaloImageMessageParams): Promise<void> {
|
|
364
|
-
const { message, mediaMaxMb, account, core, runtime } = params;
|
|
365
|
-
const { photo_url, caption } = message;
|
|
366
|
-
const authorization = await authorizeZaloMessage({
|
|
367
|
-
...params,
|
|
368
|
-
text: caption,
|
|
369
|
-
// Use a sentinel so auth sees this as an inbound image before the download happens.
|
|
370
|
-
mediaPath: photo_url ? "__pending_media__" : undefined,
|
|
371
|
-
mediaType: undefined,
|
|
372
|
-
});
|
|
373
|
-
if (!authorization) {
|
|
374
|
-
return;
|
|
375
|
-
}
|
|
376
|
-
|
|
377
|
-
let mediaPath: string | undefined;
|
|
378
|
-
let mediaType: string | undefined;
|
|
379
|
-
|
|
380
|
-
if (photo_url) {
|
|
381
|
-
try {
|
|
382
|
-
const maxBytes = mediaMaxMb * 1024 * 1024;
|
|
383
|
-
const fetched = await core.channel.media.fetchRemoteMedia({ url: photo_url, maxBytes });
|
|
384
|
-
const saved = await core.channel.media.saveMediaBuffer(
|
|
385
|
-
fetched.buffer,
|
|
386
|
-
fetched.contentType,
|
|
387
|
-
"inbound",
|
|
388
|
-
maxBytes,
|
|
389
|
-
);
|
|
390
|
-
mediaPath = saved.path;
|
|
391
|
-
mediaType = saved.contentType;
|
|
392
|
-
} catch (err) {
|
|
393
|
-
runtime.error?.(`[${account.accountId}] Failed to download Zalo image: ${String(err)}`);
|
|
394
|
-
}
|
|
395
|
-
}
|
|
396
|
-
|
|
397
|
-
await processMessageWithPipeline({
|
|
398
|
-
...params,
|
|
399
|
-
authorization,
|
|
400
|
-
text: caption,
|
|
401
|
-
mediaPath,
|
|
402
|
-
mediaType,
|
|
403
|
-
});
|
|
404
|
-
}
|
|
405
|
-
|
|
406
|
-
async function authorizeZaloMessage(
|
|
407
|
-
params: ZaloMessagePipelineParams,
|
|
408
|
-
): Promise<ZaloMessageAuthorizationResult | undefined> {
|
|
409
|
-
const { message, account, config, runtime, core, text, mediaPath, token, statusSink, fetcher } =
|
|
410
|
-
params;
|
|
411
|
-
const pairing = createChannelPairingController({
|
|
412
|
-
core,
|
|
413
|
-
channel: "zalo",
|
|
414
|
-
accountId: account.accountId,
|
|
415
|
-
});
|
|
416
|
-
const { from, chat } = message;
|
|
417
|
-
|
|
418
|
-
const isGroup = chat.chat_type === "GROUP";
|
|
419
|
-
const chatId = chat.id;
|
|
420
|
-
const senderId = from.id;
|
|
421
|
-
const senderName = from.display_name ?? from.name;
|
|
422
|
-
|
|
423
|
-
const dmPolicy = account.config.dmPolicy ?? "pairing";
|
|
424
|
-
const configAllowFrom = (account.config.allowFrom ?? []).map((v) => String(v));
|
|
425
|
-
const configuredGroupAllowFrom = (account.config.groupAllowFrom ?? []).map((v) => String(v));
|
|
426
|
-
const groupAllowFrom =
|
|
427
|
-
configuredGroupAllowFrom.length > 0 ? configuredGroupAllowFrom : configAllowFrom;
|
|
428
|
-
const defaultGroupPolicy = resolveDefaultGroupPolicy(config);
|
|
429
|
-
const groupAccess = isGroup
|
|
430
|
-
? evaluateZaloGroupAccess({
|
|
431
|
-
providerConfigPresent: config.channels?.zalo !== undefined,
|
|
432
|
-
configuredGroupPolicy: account.config.groupPolicy,
|
|
433
|
-
defaultGroupPolicy,
|
|
434
|
-
groupAllowFrom,
|
|
435
|
-
senderId,
|
|
436
|
-
})
|
|
437
|
-
: undefined;
|
|
438
|
-
if (groupAccess) {
|
|
439
|
-
warnMissingProviderGroupPolicyFallbackOnce({
|
|
440
|
-
providerMissingFallbackApplied: groupAccess.providerMissingFallbackApplied,
|
|
441
|
-
providerKey: "zalo",
|
|
442
|
-
accountId: account.accountId,
|
|
443
|
-
log: (message) => logVerbose(core, runtime, message),
|
|
444
|
-
});
|
|
445
|
-
if (!groupAccess.allowed) {
|
|
446
|
-
if (groupAccess.reason === "disabled") {
|
|
447
|
-
logVerbose(core, runtime, `zalo: drop group ${chatId} (groupPolicy=disabled)`);
|
|
448
|
-
} else if (groupAccess.reason === "empty_allowlist") {
|
|
449
|
-
logVerbose(
|
|
450
|
-
core,
|
|
451
|
-
runtime,
|
|
452
|
-
`zalo: drop group ${chatId} (groupPolicy=allowlist, no groupAllowFrom)`,
|
|
453
|
-
);
|
|
454
|
-
} else if (groupAccess.reason === "sender_not_allowlisted") {
|
|
455
|
-
logVerbose(core, runtime, `zalo: drop group sender ${senderId} (groupPolicy=allowlist)`);
|
|
456
|
-
}
|
|
457
|
-
return undefined;
|
|
458
|
-
}
|
|
459
|
-
}
|
|
460
|
-
|
|
461
|
-
const rawBody = text?.trim() || (mediaPath ? "<media:image>" : "");
|
|
462
|
-
const { senderAllowedForCommands, commandAuthorized } =
|
|
463
|
-
await resolveSenderCommandAuthorizationWithRuntime({
|
|
464
|
-
cfg: config,
|
|
465
|
-
rawBody,
|
|
466
|
-
isGroup,
|
|
467
|
-
dmPolicy,
|
|
468
|
-
configuredAllowFrom: configAllowFrom,
|
|
469
|
-
configuredGroupAllowFrom: groupAllowFrom,
|
|
470
|
-
senderId,
|
|
471
|
-
isSenderAllowed: isZaloSenderAllowed,
|
|
472
|
-
channel: "zalo",
|
|
473
|
-
accountId: account.accountId,
|
|
474
|
-
readAllowFromStore: pairing.readAllowFromStore,
|
|
475
|
-
runtime: core.channel.commands,
|
|
476
|
-
});
|
|
477
|
-
|
|
478
|
-
const directDmOutcome = resolveDirectDmAuthorizationOutcome({
|
|
479
|
-
isGroup,
|
|
480
|
-
dmPolicy,
|
|
481
|
-
senderAllowedForCommands,
|
|
482
|
-
});
|
|
483
|
-
if (directDmOutcome === "disabled") {
|
|
484
|
-
logVerbose(core, runtime, `Blocked zalo DM from ${senderId} (dmPolicy=disabled)`);
|
|
485
|
-
return undefined;
|
|
486
|
-
}
|
|
487
|
-
if (directDmOutcome === "unauthorized") {
|
|
488
|
-
if (dmPolicy === "pairing") {
|
|
489
|
-
await pairing.issueChallenge({
|
|
490
|
-
senderId,
|
|
491
|
-
senderIdLine: `Your Zalo user id: ${senderId}`,
|
|
492
|
-
meta: { name: senderName ?? undefined },
|
|
493
|
-
onCreated: () => {
|
|
494
|
-
logVerbose(core, runtime, `zalo pairing request sender=${senderId}`);
|
|
495
|
-
},
|
|
496
|
-
sendPairingReply: async (text) => {
|
|
497
|
-
await sendMessage(
|
|
498
|
-
token,
|
|
499
|
-
{
|
|
500
|
-
chat_id: chatId,
|
|
501
|
-
text,
|
|
502
|
-
},
|
|
503
|
-
fetcher,
|
|
504
|
-
);
|
|
505
|
-
statusSink?.({ lastOutboundAt: Date.now() });
|
|
506
|
-
},
|
|
507
|
-
onReplyError: (err) => {
|
|
508
|
-
logVerbose(core, runtime, `zalo pairing reply failed for ${senderId}: ${String(err)}`);
|
|
509
|
-
},
|
|
510
|
-
});
|
|
511
|
-
} else {
|
|
512
|
-
logVerbose(
|
|
513
|
-
core,
|
|
514
|
-
runtime,
|
|
515
|
-
`Blocked unauthorized zalo sender ${senderId} (dmPolicy=${dmPolicy})`,
|
|
516
|
-
);
|
|
517
|
-
}
|
|
518
|
-
return undefined;
|
|
519
|
-
}
|
|
520
|
-
|
|
521
|
-
return {
|
|
522
|
-
chatId,
|
|
523
|
-
commandAuthorized,
|
|
524
|
-
isGroup,
|
|
525
|
-
rawBody,
|
|
526
|
-
senderId,
|
|
527
|
-
senderName,
|
|
528
|
-
};
|
|
529
|
-
}
|
|
530
|
-
|
|
531
|
-
async function processMessageWithPipeline(params: ZaloMessagePipelineParams): Promise<void> {
|
|
532
|
-
const {
|
|
533
|
-
message,
|
|
534
|
-
token,
|
|
535
|
-
account,
|
|
536
|
-
config,
|
|
537
|
-
runtime,
|
|
538
|
-
core,
|
|
539
|
-
mediaPath,
|
|
540
|
-
mediaType,
|
|
541
|
-
statusSink,
|
|
542
|
-
fetcher,
|
|
543
|
-
authorization: authorizationOverride,
|
|
544
|
-
} = params;
|
|
545
|
-
const { message_id, date } = message;
|
|
546
|
-
const authorization =
|
|
547
|
-
authorizationOverride ??
|
|
548
|
-
(await authorizeZaloMessage({
|
|
549
|
-
...params,
|
|
550
|
-
mediaPath,
|
|
551
|
-
mediaType,
|
|
552
|
-
}));
|
|
553
|
-
if (!authorization) {
|
|
554
|
-
return;
|
|
555
|
-
}
|
|
556
|
-
const { isGroup, chatId, senderId, senderName, rawBody, commandAuthorized } = authorization;
|
|
557
|
-
|
|
558
|
-
const { route, buildEnvelope } = resolveInboundRouteEnvelopeBuilderWithRuntime({
|
|
559
|
-
cfg: config,
|
|
560
|
-
channel: "zalo",
|
|
561
|
-
accountId: account.accountId,
|
|
562
|
-
peer: {
|
|
563
|
-
kind: isGroup ? ("group" as const) : ("direct" as const),
|
|
564
|
-
id: chatId,
|
|
565
|
-
},
|
|
566
|
-
runtime: core.channel,
|
|
567
|
-
sessionStore: config.session?.store,
|
|
568
|
-
});
|
|
569
|
-
|
|
570
|
-
if (
|
|
571
|
-
isGroup &&
|
|
572
|
-
core.channel.commands.isControlCommandMessage(rawBody, config) &&
|
|
573
|
-
commandAuthorized !== true
|
|
574
|
-
) {
|
|
575
|
-
logVerbose(core, runtime, `zalo: drop control command from unauthorized sender ${senderId}`);
|
|
576
|
-
return;
|
|
577
|
-
}
|
|
578
|
-
|
|
579
|
-
const fromLabel = isGroup ? `group:${chatId}` : senderName || `user:${senderId}`;
|
|
580
|
-
const { storePath, body } = buildEnvelope({
|
|
581
|
-
channel: "Zalo",
|
|
582
|
-
from: fromLabel,
|
|
583
|
-
timestamp: date ? date * 1000 : undefined,
|
|
584
|
-
body: rawBody,
|
|
585
|
-
});
|
|
586
|
-
|
|
587
|
-
const ctxPayload = core.channel.turn.buildContext({
|
|
588
|
-
channel: "zalo",
|
|
589
|
-
accountId: route.accountId,
|
|
590
|
-
messageId: message_id,
|
|
591
|
-
timestamp: date ? date * 1000 : undefined,
|
|
592
|
-
from: isGroup ? `zalo:group:${chatId}` : `zalo:${senderId}`,
|
|
593
|
-
sender: {
|
|
594
|
-
id: senderId,
|
|
595
|
-
name: senderName || undefined,
|
|
596
|
-
},
|
|
597
|
-
conversation: {
|
|
598
|
-
kind: isGroup ? "group" : "direct",
|
|
599
|
-
id: chatId,
|
|
600
|
-
label: fromLabel,
|
|
601
|
-
routePeer: {
|
|
602
|
-
kind: isGroup ? "group" : "direct",
|
|
603
|
-
id: chatId,
|
|
604
|
-
},
|
|
605
|
-
},
|
|
606
|
-
route: {
|
|
607
|
-
agentId: route.agentId,
|
|
608
|
-
accountId: route.accountId,
|
|
609
|
-
routeSessionKey: route.sessionKey,
|
|
610
|
-
},
|
|
611
|
-
reply: {
|
|
612
|
-
to: `zalo:${chatId}`,
|
|
613
|
-
originatingTo: `zalo:${chatId}`,
|
|
614
|
-
},
|
|
615
|
-
message: {
|
|
616
|
-
body,
|
|
617
|
-
bodyForAgent: rawBody,
|
|
618
|
-
rawBody,
|
|
619
|
-
commandBody: rawBody,
|
|
620
|
-
envelopeFrom: fromLabel,
|
|
621
|
-
},
|
|
622
|
-
media:
|
|
623
|
-
mediaPath || mediaType
|
|
624
|
-
? [
|
|
625
|
-
{
|
|
626
|
-
path: mediaPath,
|
|
627
|
-
url: mediaPath,
|
|
628
|
-
contentType: mediaType,
|
|
629
|
-
},
|
|
630
|
-
]
|
|
631
|
-
: undefined,
|
|
632
|
-
extra: {
|
|
633
|
-
CommandAuthorized: commandAuthorized,
|
|
634
|
-
GroupSubject: undefined,
|
|
635
|
-
},
|
|
636
|
-
});
|
|
637
|
-
|
|
638
|
-
const tableMode = core.channel.text.resolveMarkdownTableMode({
|
|
639
|
-
cfg: config,
|
|
640
|
-
channel: "zalo",
|
|
641
|
-
accountId: account.accountId,
|
|
642
|
-
});
|
|
643
|
-
const { onModelSelected, ...replyPipeline } = createChannelReplyPipeline({
|
|
644
|
-
cfg: config,
|
|
645
|
-
agentId: route.agentId,
|
|
646
|
-
channel: "zalo",
|
|
647
|
-
accountId: account.accountId,
|
|
648
|
-
typing: {
|
|
649
|
-
start: async () => {
|
|
650
|
-
await sendChatAction(
|
|
651
|
-
token,
|
|
652
|
-
{
|
|
653
|
-
chat_id: chatId,
|
|
654
|
-
action: "typing",
|
|
655
|
-
},
|
|
656
|
-
fetcher,
|
|
657
|
-
ZALO_TYPING_TIMEOUT_MS,
|
|
658
|
-
);
|
|
659
|
-
},
|
|
660
|
-
onStartError: (err) => {
|
|
661
|
-
logTypingFailure({
|
|
662
|
-
log: (message) => logVerbose(core, runtime, message),
|
|
663
|
-
channel: "zalo",
|
|
664
|
-
action: "start",
|
|
665
|
-
target: chatId,
|
|
666
|
-
error: err,
|
|
667
|
-
});
|
|
668
|
-
},
|
|
669
|
-
},
|
|
670
|
-
});
|
|
671
|
-
|
|
672
|
-
await core.channel.turn.run({
|
|
673
|
-
channel: "zalo",
|
|
674
|
-
accountId: account.accountId,
|
|
675
|
-
raw: message,
|
|
676
|
-
adapter: {
|
|
677
|
-
ingest: () => ({
|
|
678
|
-
id: message_id,
|
|
679
|
-
timestamp: date ? date * 1000 : undefined,
|
|
680
|
-
rawText: rawBody,
|
|
681
|
-
textForAgent: rawBody,
|
|
682
|
-
textForCommands: rawBody,
|
|
683
|
-
raw: message,
|
|
684
|
-
}),
|
|
685
|
-
resolveTurn: () => ({
|
|
686
|
-
cfg: config,
|
|
687
|
-
channel: "zalo",
|
|
688
|
-
accountId: account.accountId,
|
|
689
|
-
agentId: route.agentId,
|
|
690
|
-
routeSessionKey: route.sessionKey,
|
|
691
|
-
storePath,
|
|
692
|
-
ctxPayload,
|
|
693
|
-
recordInboundSession: core.channel.session.recordInboundSession,
|
|
694
|
-
dispatchReplyWithBufferedBlockDispatcher:
|
|
695
|
-
core.channel.reply.dispatchReplyWithBufferedBlockDispatcher,
|
|
696
|
-
delivery: {
|
|
697
|
-
deliver: async (payload) => {
|
|
698
|
-
await deliverZaloReply({
|
|
699
|
-
payload,
|
|
700
|
-
token,
|
|
701
|
-
chatId,
|
|
702
|
-
runtime,
|
|
703
|
-
core,
|
|
704
|
-
config,
|
|
705
|
-
webhookUrl: params.webhookUrl,
|
|
706
|
-
webhookPath: params.webhookPath,
|
|
707
|
-
proxyUrl: account.config.proxy,
|
|
708
|
-
mediaMaxBytes: params.mediaMaxMb * 1024 * 1024,
|
|
709
|
-
canHostMedia: params.canHostMedia,
|
|
710
|
-
accountId: account.accountId,
|
|
711
|
-
statusSink,
|
|
712
|
-
fetcher,
|
|
713
|
-
tableMode,
|
|
714
|
-
});
|
|
715
|
-
},
|
|
716
|
-
onError: (err, info) => {
|
|
717
|
-
runtime.error?.(
|
|
718
|
-
`[${account.accountId}] Zalo ${info.kind} reply failed: ${String(err)}`,
|
|
719
|
-
);
|
|
720
|
-
},
|
|
721
|
-
},
|
|
722
|
-
dispatcherOptions: replyPipeline,
|
|
723
|
-
replyOptions: {
|
|
724
|
-
onModelSelected,
|
|
725
|
-
},
|
|
726
|
-
record: {
|
|
727
|
-
onRecordError: (err) => {
|
|
728
|
-
runtime.error?.(`zalo: failed updating session meta: ${String(err)}`);
|
|
729
|
-
},
|
|
730
|
-
},
|
|
731
|
-
}),
|
|
732
|
-
},
|
|
733
|
-
});
|
|
734
|
-
}
|
|
735
|
-
|
|
736
|
-
async function deliverZaloReply(params: {
|
|
737
|
-
payload: OutboundReplyPayload;
|
|
738
|
-
token: string;
|
|
739
|
-
chatId: string;
|
|
740
|
-
runtime: ZaloRuntimeEnv;
|
|
741
|
-
core: ZaloCoreRuntime;
|
|
742
|
-
config: OpenClawConfig;
|
|
743
|
-
webhookUrl?: string;
|
|
744
|
-
webhookPath?: string;
|
|
745
|
-
proxyUrl?: string;
|
|
746
|
-
mediaMaxBytes: number;
|
|
747
|
-
canHostMedia: boolean;
|
|
748
|
-
accountId?: string;
|
|
749
|
-
statusSink?: ZaloStatusSink;
|
|
750
|
-
fetcher?: ZaloFetch;
|
|
751
|
-
tableMode?: MarkdownTableMode;
|
|
752
|
-
}): Promise<void> {
|
|
753
|
-
const {
|
|
754
|
-
payload,
|
|
755
|
-
token,
|
|
756
|
-
chatId,
|
|
757
|
-
runtime,
|
|
758
|
-
core,
|
|
759
|
-
config,
|
|
760
|
-
webhookUrl,
|
|
761
|
-
webhookPath,
|
|
762
|
-
proxyUrl,
|
|
763
|
-
mediaMaxBytes,
|
|
764
|
-
canHostMedia,
|
|
765
|
-
accountId,
|
|
766
|
-
statusSink,
|
|
767
|
-
fetcher,
|
|
768
|
-
} = params;
|
|
769
|
-
const tableMode = params.tableMode ?? "code";
|
|
770
|
-
const reply = resolveSendableOutboundReplyParts(payload, {
|
|
771
|
-
text: core.channel.text.convertMarkdownTables(payload.text ?? "", tableMode),
|
|
772
|
-
});
|
|
773
|
-
const chunkMode = core.channel.text.resolveChunkMode(config, "zalo", accountId);
|
|
774
|
-
await deliverTextOrMediaReply({
|
|
775
|
-
payload,
|
|
776
|
-
text: reply.text,
|
|
777
|
-
chunkText: (value) =>
|
|
778
|
-
core.channel.text.chunkMarkdownTextWithMode(value, ZALO_TEXT_LIMIT, chunkMode),
|
|
779
|
-
sendText: async (chunk) => {
|
|
780
|
-
try {
|
|
781
|
-
await sendMessage(token, { chat_id: chatId, text: chunk }, fetcher);
|
|
782
|
-
statusSink?.({ lastOutboundAt: Date.now() });
|
|
783
|
-
} catch (err) {
|
|
784
|
-
runtime.error?.(`Zalo message send failed: ${String(err)}`);
|
|
785
|
-
}
|
|
786
|
-
},
|
|
787
|
-
sendMedia: async ({ mediaUrl, caption }) => {
|
|
788
|
-
const sendableMediaUrl =
|
|
789
|
-
canHostMedia && webhookUrl && webhookPath
|
|
790
|
-
? await prepareHostedZaloMediaUrl({
|
|
791
|
-
mediaUrl,
|
|
792
|
-
webhookUrl,
|
|
793
|
-
webhookPath,
|
|
794
|
-
maxBytes: mediaMaxBytes,
|
|
795
|
-
proxyUrl,
|
|
796
|
-
})
|
|
797
|
-
: mediaUrl;
|
|
798
|
-
await sendPhoto(token, { chat_id: chatId, photo: sendableMediaUrl, caption }, fetcher);
|
|
799
|
-
statusSink?.({ lastOutboundAt: Date.now() });
|
|
800
|
-
},
|
|
801
|
-
onMediaError: (error) => {
|
|
802
|
-
runtime.error?.(
|
|
803
|
-
`Zalo photo send failed: ${error instanceof Error ? error.message : JSON.stringify(error)}`,
|
|
804
|
-
);
|
|
805
|
-
},
|
|
806
|
-
});
|
|
807
|
-
}
|
|
808
|
-
|
|
809
|
-
export async function monitorZaloProvider(options: ZaloMonitorOptions): Promise<void> {
|
|
810
|
-
const {
|
|
811
|
-
token,
|
|
812
|
-
account,
|
|
813
|
-
config,
|
|
814
|
-
runtime,
|
|
815
|
-
abortSignal,
|
|
816
|
-
useWebhook,
|
|
817
|
-
webhookUrl,
|
|
818
|
-
webhookSecret,
|
|
819
|
-
webhookPath,
|
|
820
|
-
statusSink,
|
|
821
|
-
fetcher: fetcherOverride,
|
|
822
|
-
} = options;
|
|
823
|
-
|
|
824
|
-
const core = getZaloRuntime();
|
|
825
|
-
const effectiveMediaMaxMb = account.config.mediaMaxMb ?? DEFAULT_MEDIA_MAX_MB;
|
|
826
|
-
const fetcher = fetcherOverride ?? resolveZaloProxyFetch(account.config.proxy);
|
|
827
|
-
const mode = useWebhook ? "webhook" : "polling";
|
|
828
|
-
const effectiveWebhookUrl = normalizeWebhookUrl(webhookUrl ?? account.config.webhookUrl);
|
|
829
|
-
const effectiveWebhookPath =
|
|
830
|
-
effectiveWebhookUrl || webhookPath?.trim() || account.config.webhookPath?.trim()
|
|
831
|
-
? (resolveWebhookPath({
|
|
832
|
-
webhookPath: webhookPath ?? account.config.webhookPath,
|
|
833
|
-
webhookUrl: effectiveWebhookUrl,
|
|
834
|
-
defaultPath: null,
|
|
835
|
-
}) ?? undefined)
|
|
836
|
-
: undefined;
|
|
837
|
-
const canHostMedia = Boolean(effectiveWebhookUrl && effectiveWebhookPath);
|
|
838
|
-
const hostedMediaRoutePath =
|
|
839
|
-
canHostMedia && effectiveWebhookUrl
|
|
840
|
-
? resolveHostedZaloMediaRoutePrefix({
|
|
841
|
-
webhookUrl: effectiveWebhookUrl,
|
|
842
|
-
webhookPath: effectiveWebhookPath,
|
|
843
|
-
})
|
|
844
|
-
: undefined;
|
|
845
|
-
|
|
846
|
-
let stopped = false;
|
|
847
|
-
const stopHandlers: Array<() => void> = [];
|
|
848
|
-
let cleanupWebhook: (() => Promise<void>) | undefined;
|
|
849
|
-
|
|
850
|
-
const stop = () => {
|
|
851
|
-
if (stopped) {
|
|
852
|
-
return;
|
|
853
|
-
}
|
|
854
|
-
stopped = true;
|
|
855
|
-
for (const handler of stopHandlers) {
|
|
856
|
-
handler();
|
|
857
|
-
}
|
|
858
|
-
};
|
|
859
|
-
const stopOnAbort = () => {
|
|
860
|
-
if (!useWebhook) {
|
|
861
|
-
stop();
|
|
862
|
-
}
|
|
863
|
-
};
|
|
864
|
-
|
|
865
|
-
abortSignal.addEventListener("abort", stopOnAbort, { once: true });
|
|
866
|
-
|
|
867
|
-
runtime.log?.(
|
|
868
|
-
`[${account.accountId}] Zalo provider init mode=${mode} mediaMaxMb=${String(effectiveMediaMaxMb)}`,
|
|
869
|
-
);
|
|
870
|
-
|
|
871
|
-
try {
|
|
872
|
-
if (hostedMediaRoutePath) {
|
|
873
|
-
const unregisterHostedMediaRoute = registerSharedHostedMediaRoute({
|
|
874
|
-
path: hostedMediaRoutePath,
|
|
875
|
-
accountId: account.accountId,
|
|
876
|
-
log: runtime.log,
|
|
877
|
-
});
|
|
878
|
-
stopHandlers.push(unregisterHostedMediaRoute);
|
|
879
|
-
}
|
|
880
|
-
|
|
881
|
-
if (useWebhook) {
|
|
882
|
-
const { registerZaloWebhookTarget } = await loadZaloWebhookModule();
|
|
883
|
-
if (!effectiveWebhookUrl || !webhookSecret) {
|
|
884
|
-
throw new Error("Zalo webhookUrl and webhookSecret are required for webhook mode");
|
|
885
|
-
}
|
|
886
|
-
if (!effectiveWebhookUrl.startsWith("https://")) {
|
|
887
|
-
throw new Error("Zalo webhook URL must use HTTPS");
|
|
888
|
-
}
|
|
889
|
-
if (webhookSecret.length < 8 || webhookSecret.length > 256) {
|
|
890
|
-
throw new Error("Zalo webhook secret must be 8-256 characters");
|
|
891
|
-
}
|
|
892
|
-
|
|
893
|
-
const path = effectiveWebhookPath;
|
|
894
|
-
if (!path) {
|
|
895
|
-
throw new Error("Zalo webhookPath could not be derived");
|
|
896
|
-
}
|
|
897
|
-
|
|
898
|
-
runtime.log?.(
|
|
899
|
-
`[${account.accountId}] Zalo configuring webhook path=${path} target=${describeWebhookTarget(effectiveWebhookUrl)}`,
|
|
900
|
-
);
|
|
901
|
-
await setWebhook(token, { url: effectiveWebhookUrl, secret_token: webhookSecret }, fetcher);
|
|
902
|
-
let webhookCleanupPromise: Promise<void> | undefined;
|
|
903
|
-
cleanupWebhook = async () => {
|
|
904
|
-
if (!webhookCleanupPromise) {
|
|
905
|
-
webhookCleanupPromise = (async () => {
|
|
906
|
-
runtime.log?.(`[${account.accountId}] Zalo stopping; deleting webhook`);
|
|
907
|
-
try {
|
|
908
|
-
await deleteWebhook(token, fetcher, WEBHOOK_CLEANUP_TIMEOUT_MS);
|
|
909
|
-
runtime.log?.(`[${account.accountId}] Zalo webhook deleted`);
|
|
910
|
-
} catch (err) {
|
|
911
|
-
const detail =
|
|
912
|
-
err instanceof Error && err.name === "AbortError"
|
|
913
|
-
? `timed out after ${String(WEBHOOK_CLEANUP_TIMEOUT_MS)}ms`
|
|
914
|
-
: formatZaloError(err);
|
|
915
|
-
runtime.error?.(`[${account.accountId}] Zalo webhook delete failed: ${detail}`);
|
|
916
|
-
}
|
|
917
|
-
})();
|
|
918
|
-
}
|
|
919
|
-
await webhookCleanupPromise;
|
|
920
|
-
};
|
|
921
|
-
runtime.log?.(`[${account.accountId}] Zalo webhook registered path=${path}`);
|
|
922
|
-
|
|
923
|
-
const unregister = registerZaloWebhookTarget(
|
|
924
|
-
{
|
|
925
|
-
token,
|
|
926
|
-
account,
|
|
927
|
-
config,
|
|
928
|
-
runtime,
|
|
929
|
-
core,
|
|
930
|
-
path,
|
|
931
|
-
webhookUrl: effectiveWebhookUrl,
|
|
932
|
-
webhookPath: path,
|
|
933
|
-
secret: webhookSecret,
|
|
934
|
-
statusSink: (patch) => statusSink?.(patch),
|
|
935
|
-
mediaMaxMb: effectiveMediaMaxMb,
|
|
936
|
-
canHostMedia,
|
|
937
|
-
fetcher,
|
|
938
|
-
},
|
|
939
|
-
{
|
|
940
|
-
route: {
|
|
941
|
-
auth: "plugin",
|
|
942
|
-
match: "exact",
|
|
943
|
-
pluginId: "zalo",
|
|
944
|
-
source: "zalo-webhook",
|
|
945
|
-
accountId: account.accountId,
|
|
946
|
-
log: runtime.log,
|
|
947
|
-
handler: async (req, res) => {
|
|
948
|
-
const handled = await handleZaloWebhookRequest(req, res);
|
|
949
|
-
if (!handled && !res.headersSent) {
|
|
950
|
-
res.statusCode = 404;
|
|
951
|
-
res.setHeader("Content-Type", "text/plain; charset=utf-8");
|
|
952
|
-
res.end("Not Found");
|
|
953
|
-
}
|
|
954
|
-
},
|
|
955
|
-
},
|
|
956
|
-
},
|
|
957
|
-
);
|
|
958
|
-
stopHandlers.push(unregister);
|
|
959
|
-
await waitForAbortSignal(abortSignal);
|
|
960
|
-
return;
|
|
961
|
-
}
|
|
962
|
-
|
|
963
|
-
runtime.log?.(`[${account.accountId}] Zalo polling mode: clearing webhook before startup`);
|
|
964
|
-
try {
|
|
965
|
-
try {
|
|
966
|
-
const currentWebhookUrl = normalizeWebhookUrl(
|
|
967
|
-
(await getWebhookInfo(token, fetcher)).result?.url,
|
|
968
|
-
);
|
|
969
|
-
if (!currentWebhookUrl) {
|
|
970
|
-
runtime.log?.(`[${account.accountId}] Zalo polling mode ready (no webhook configured)`);
|
|
971
|
-
} else {
|
|
972
|
-
runtime.log?.(
|
|
973
|
-
`[${account.accountId}] Zalo polling mode disabling existing webhook ${describeWebhookTarget(currentWebhookUrl)}`,
|
|
974
|
-
);
|
|
975
|
-
await deleteWebhook(token, fetcher);
|
|
976
|
-
runtime.log?.(`[${account.accountId}] Zalo polling mode ready (webhook disabled)`);
|
|
977
|
-
}
|
|
978
|
-
} catch (err) {
|
|
979
|
-
if (err instanceof ZaloApiError && err.errorCode === 404) {
|
|
980
|
-
// Some Zalo environments do not expose webhook inspection for polling bots.
|
|
981
|
-
runtime.log?.(
|
|
982
|
-
`[${account.accountId}] Zalo polling mode webhook inspection unavailable; continuing without webhook cleanup`,
|
|
983
|
-
);
|
|
984
|
-
} else {
|
|
985
|
-
throw err;
|
|
986
|
-
}
|
|
987
|
-
}
|
|
988
|
-
} catch (err) {
|
|
989
|
-
runtime.error?.(
|
|
990
|
-
`[${account.accountId}] Zalo polling startup could not clear webhook: ${formatZaloError(err)}`,
|
|
991
|
-
);
|
|
992
|
-
}
|
|
993
|
-
|
|
994
|
-
startPollingLoop({
|
|
995
|
-
token,
|
|
996
|
-
account,
|
|
997
|
-
config,
|
|
998
|
-
runtime,
|
|
999
|
-
core,
|
|
1000
|
-
canHostMedia,
|
|
1001
|
-
webhookUrl: effectiveWebhookUrl,
|
|
1002
|
-
webhookPath: effectiveWebhookPath,
|
|
1003
|
-
abortSignal,
|
|
1004
|
-
isStopped: () => stopped,
|
|
1005
|
-
mediaMaxMb: effectiveMediaMaxMb,
|
|
1006
|
-
statusSink,
|
|
1007
|
-
fetcher,
|
|
1008
|
-
});
|
|
1009
|
-
|
|
1010
|
-
await waitForAbortSignal(abortSignal);
|
|
1011
|
-
} catch (err) {
|
|
1012
|
-
runtime.error?.(
|
|
1013
|
-
`[${account.accountId}] Zalo provider startup failed mode=${mode}: ${formatZaloError(err)}`,
|
|
1014
|
-
);
|
|
1015
|
-
throw err;
|
|
1016
|
-
} finally {
|
|
1017
|
-
abortSignal.removeEventListener("abort", stopOnAbort);
|
|
1018
|
-
await cleanupWebhook?.();
|
|
1019
|
-
stop();
|
|
1020
|
-
runtime.log?.(`[${account.accountId}] Zalo provider stopped mode=${mode}`);
|
|
1021
|
-
}
|
|
1022
|
-
}
|
|
1023
|
-
|
|
1024
|
-
export const __testing = {
|
|
1025
|
-
evaluateZaloGroupAccess,
|
|
1026
|
-
resolveZaloRuntimeGroupPolicy,
|
|
1027
|
-
clearHostedMediaRouteRefsForTest: () => hostedMediaRouteRefs.clear(),
|
|
1028
|
-
};
|