@openclaw/zalo 2026.2.17 → 2026.2.19

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/CHANGELOG.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Changelog
2
2
 
3
- ## 2026.2.17
3
+ ## 2026.2.19
4
4
 
5
5
  ### Changes
6
6
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openclaw/zalo",
3
- "version": "2026.2.17",
3
+ "version": "2026.2.19",
4
4
  "description": "OpenClaw Zalo channel plugin",
5
5
  "type": "module",
6
6
  "dependencies": {
package/src/monitor.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { timingSafeEqual } from "node:crypto";
1
2
  import type { IncomingMessage, ServerResponse } from "node:http";
2
3
  import type { OpenClawConfig, MarkdownTableMode } from "openclaw/plugin-sdk";
3
4
  import {
@@ -50,8 +51,13 @@ export type ZaloMonitorResult = {
50
51
 
51
52
  const ZALO_TEXT_LIMIT = 2000;
52
53
  const DEFAULT_MEDIA_MAX_MB = 5;
54
+ const ZALO_WEBHOOK_RATE_LIMIT_WINDOW_MS = 60_000;
55
+ const ZALO_WEBHOOK_RATE_LIMIT_MAX_REQUESTS = 120;
56
+ const ZALO_WEBHOOK_REPLAY_WINDOW_MS = 5 * 60_000;
57
+ const ZALO_WEBHOOK_COUNTER_LOG_EVERY = 25;
53
58
 
54
59
  type ZaloCoreRuntime = ReturnType<typeof getZaloRuntime>;
60
+ type WebhookRateLimitState = { count: number; windowStartMs: number };
55
61
 
56
62
  function logVerbose(core: ZaloCoreRuntime, runtime: ZaloRuntimeEnv, message: string): void {
57
63
  if (core.logging.shouldLogVerbose()) {
@@ -84,6 +90,91 @@ type WebhookTarget = {
84
90
  };
85
91
 
86
92
  const webhookTargets = new Map<string, WebhookTarget[]>();
93
+ const webhookRateLimits = new Map<string, WebhookRateLimitState>();
94
+ const recentWebhookEvents = new Map<string, number>();
95
+ const webhookStatusCounters = new Map<string, number>();
96
+
97
+ function isJsonContentType(value: string | string[] | undefined): boolean {
98
+ const first = Array.isArray(value) ? value[0] : value;
99
+ if (!first) {
100
+ return false;
101
+ }
102
+ const mediaType = first.split(";", 1)[0]?.trim().toLowerCase();
103
+ return mediaType === "application/json" || Boolean(mediaType?.endsWith("+json"));
104
+ }
105
+
106
+ function timingSafeEquals(left: string, right: string): boolean {
107
+ const leftBuffer = Buffer.from(left);
108
+ const rightBuffer = Buffer.from(right);
109
+
110
+ if (leftBuffer.length !== rightBuffer.length) {
111
+ const length = Math.max(1, leftBuffer.length, rightBuffer.length);
112
+ const paddedLeft = Buffer.alloc(length);
113
+ const paddedRight = Buffer.alloc(length);
114
+ leftBuffer.copy(paddedLeft);
115
+ rightBuffer.copy(paddedRight);
116
+ timingSafeEqual(paddedLeft, paddedRight);
117
+ return false;
118
+ }
119
+
120
+ return timingSafeEqual(leftBuffer, rightBuffer);
121
+ }
122
+
123
+ function isWebhookRateLimited(key: string, nowMs: number): boolean {
124
+ const state = webhookRateLimits.get(key);
125
+ if (!state || nowMs - state.windowStartMs >= ZALO_WEBHOOK_RATE_LIMIT_WINDOW_MS) {
126
+ webhookRateLimits.set(key, { count: 1, windowStartMs: nowMs });
127
+ return false;
128
+ }
129
+
130
+ state.count += 1;
131
+ if (state.count > ZALO_WEBHOOK_RATE_LIMIT_MAX_REQUESTS) {
132
+ return true;
133
+ }
134
+ return false;
135
+ }
136
+
137
+ function isReplayEvent(update: ZaloUpdate, nowMs: number): boolean {
138
+ const messageId = update.message?.message_id;
139
+ if (!messageId) {
140
+ return false;
141
+ }
142
+ const key = `${update.event_name}:${messageId}`;
143
+ const seenAt = recentWebhookEvents.get(key);
144
+ recentWebhookEvents.set(key, nowMs);
145
+
146
+ if (seenAt && nowMs - seenAt < ZALO_WEBHOOK_REPLAY_WINDOW_MS) {
147
+ return true;
148
+ }
149
+
150
+ if (recentWebhookEvents.size > 5000) {
151
+ for (const [eventKey, timestamp] of recentWebhookEvents) {
152
+ if (nowMs - timestamp >= ZALO_WEBHOOK_REPLAY_WINDOW_MS) {
153
+ recentWebhookEvents.delete(eventKey);
154
+ }
155
+ }
156
+ }
157
+
158
+ return false;
159
+ }
160
+
161
+ function recordWebhookStatus(
162
+ runtime: ZaloRuntimeEnv | undefined,
163
+ path: string,
164
+ statusCode: number,
165
+ ): void {
166
+ if (![400, 401, 408, 413, 415, 429].includes(statusCode)) {
167
+ return;
168
+ }
169
+ const key = `${path}:${statusCode}`;
170
+ const next = (webhookStatusCounters.get(key) ?? 0) + 1;
171
+ webhookStatusCounters.set(key, next);
172
+ if (next === 1 || next % ZALO_WEBHOOK_COUNTER_LOG_EVERY === 0) {
173
+ runtime?.log?.(
174
+ `[zalo] webhook anomaly path=${path} status=${statusCode} count=${String(next)}`,
175
+ );
176
+ }
177
+ }
87
178
 
88
179
  export function registerZaloWebhookTarget(target: WebhookTarget): () => void {
89
180
  return registerWebhookTarget(webhookTargets, target).unregister;
@@ -104,18 +195,37 @@ export async function handleZaloWebhookRequest(
104
195
  }
105
196
 
106
197
  const headerToken = String(req.headers["x-bot-api-secret-token"] ?? "");
107
- const matching = targets.filter((entry) => entry.secret === headerToken);
198
+ const matching = targets.filter((entry) => timingSafeEquals(entry.secret, headerToken));
108
199
  if (matching.length === 0) {
109
200
  res.statusCode = 401;
110
201
  res.end("unauthorized");
202
+ recordWebhookStatus(targets[0]?.runtime, req.url ?? "<unknown>", res.statusCode);
111
203
  return true;
112
204
  }
113
205
  if (matching.length > 1) {
114
206
  res.statusCode = 401;
115
207
  res.end("ambiguous webhook target");
208
+ recordWebhookStatus(targets[0]?.runtime, req.url ?? "<unknown>", res.statusCode);
116
209
  return true;
117
210
  }
118
211
  const target = matching[0];
212
+ const path = req.url ?? "<unknown>";
213
+ const rateLimitKey = `${path}:${req.socket.remoteAddress ?? "unknown"}`;
214
+ const nowMs = Date.now();
215
+
216
+ if (isWebhookRateLimited(rateLimitKey, nowMs)) {
217
+ res.statusCode = 429;
218
+ res.end("Too Many Requests");
219
+ recordWebhookStatus(target.runtime, path, res.statusCode);
220
+ return true;
221
+ }
222
+
223
+ if (!isJsonContentType(req.headers["content-type"])) {
224
+ res.statusCode = 415;
225
+ res.end("Unsupported Media Type");
226
+ recordWebhookStatus(target.runtime, path, res.statusCode);
227
+ return true;
228
+ }
119
229
 
120
230
  const body = await readJsonBodyWithLimit(req, {
121
231
  maxBytes: 1024 * 1024,
@@ -125,11 +235,14 @@ export async function handleZaloWebhookRequest(
125
235
  if (!body.ok) {
126
236
  res.statusCode =
127
237
  body.code === "PAYLOAD_TOO_LARGE" ? 413 : body.code === "REQUEST_BODY_TIMEOUT" ? 408 : 400;
128
- res.end(
129
- body.code === "REQUEST_BODY_TIMEOUT"
130
- ? requestBodyErrorToText("REQUEST_BODY_TIMEOUT")
131
- : body.error,
132
- );
238
+ const message =
239
+ body.code === "PAYLOAD_TOO_LARGE"
240
+ ? requestBodyErrorToText("PAYLOAD_TOO_LARGE")
241
+ : body.code === "REQUEST_BODY_TIMEOUT"
242
+ ? requestBodyErrorToText("REQUEST_BODY_TIMEOUT")
243
+ : "Bad Request";
244
+ res.end(message);
245
+ recordWebhookStatus(target.runtime, path, res.statusCode);
133
246
  return true;
134
247
  }
135
248
 
@@ -143,7 +256,14 @@ export async function handleZaloWebhookRequest(
143
256
 
144
257
  if (!update?.event_name) {
145
258
  res.statusCode = 400;
146
- res.end("invalid payload");
259
+ res.end("Bad Request");
260
+ recordWebhookStatus(target.runtime, path, res.statusCode);
261
+ return true;
262
+ }
263
+
264
+ if (isReplayEvent(update, nowMs)) {
265
+ res.statusCode = 200;
266
+ res.end("ok");
147
267
  return true;
148
268
  }
149
269
 
@@ -56,11 +56,13 @@ describe("handleZaloWebhookRequest", () => {
56
56
  method: "POST",
57
57
  headers: {
58
58
  "x-bot-api-secret-token": "secret",
59
+ "content-type": "application/json",
59
60
  },
60
61
  body: "null",
61
62
  });
62
63
 
63
64
  expect(response.status).toBe(400);
65
+ expect(await response.text()).toBe("Bad Request");
64
66
  },
65
67
  );
66
68
  } finally {
@@ -131,4 +133,175 @@ describe("handleZaloWebhookRequest", () => {
131
133
  unregisterB();
132
134
  }
133
135
  });
136
+
137
+ it("returns 415 for non-json content-type", async () => {
138
+ const core = {} as PluginRuntime;
139
+ const account: ResolvedZaloAccount = {
140
+ accountId: "default",
141
+ enabled: true,
142
+ token: "tok",
143
+ tokenSource: "config",
144
+ config: {},
145
+ };
146
+ const unregister = registerZaloWebhookTarget({
147
+ token: "tok",
148
+ account,
149
+ config: {} as OpenClawConfig,
150
+ runtime: {},
151
+ core,
152
+ secret: "secret",
153
+ path: "/hook-content-type",
154
+ mediaMaxMb: 5,
155
+ });
156
+
157
+ try {
158
+ await withServer(
159
+ async (req, res) => {
160
+ const handled = await handleZaloWebhookRequest(req, res);
161
+ if (!handled) {
162
+ res.statusCode = 404;
163
+ res.end("not found");
164
+ }
165
+ },
166
+ async (baseUrl) => {
167
+ const response = await fetch(`${baseUrl}/hook-content-type`, {
168
+ method: "POST",
169
+ headers: {
170
+ "x-bot-api-secret-token": "secret",
171
+ "content-type": "text/plain",
172
+ },
173
+ body: "{}",
174
+ });
175
+
176
+ expect(response.status).toBe(415);
177
+ },
178
+ );
179
+ } finally {
180
+ unregister();
181
+ }
182
+ });
183
+
184
+ it("deduplicates webhook replay by event_name + message_id", async () => {
185
+ const core = {} as PluginRuntime;
186
+ const account: ResolvedZaloAccount = {
187
+ accountId: "default",
188
+ enabled: true,
189
+ token: "tok",
190
+ tokenSource: "config",
191
+ config: {},
192
+ };
193
+ const sink = vi.fn();
194
+ const unregister = registerZaloWebhookTarget({
195
+ token: "tok",
196
+ account,
197
+ config: {} as OpenClawConfig,
198
+ runtime: {},
199
+ core,
200
+ secret: "secret",
201
+ path: "/hook-replay",
202
+ mediaMaxMb: 5,
203
+ statusSink: sink,
204
+ });
205
+
206
+ const payload = {
207
+ event_name: "message.text.received",
208
+ message: {
209
+ from: { id: "123" },
210
+ chat: { id: "123", chat_type: "PRIVATE" },
211
+ message_id: "msg-replay-1",
212
+ date: Math.floor(Date.now() / 1000),
213
+ text: "hello",
214
+ },
215
+ };
216
+
217
+ try {
218
+ await withServer(
219
+ async (req, res) => {
220
+ const handled = await handleZaloWebhookRequest(req, res);
221
+ if (!handled) {
222
+ res.statusCode = 404;
223
+ res.end("not found");
224
+ }
225
+ },
226
+ async (baseUrl) => {
227
+ const first = await fetch(`${baseUrl}/hook-replay`, {
228
+ method: "POST",
229
+ headers: {
230
+ "x-bot-api-secret-token": "secret",
231
+ "content-type": "application/json",
232
+ },
233
+ body: JSON.stringify(payload),
234
+ });
235
+ const second = await fetch(`${baseUrl}/hook-replay`, {
236
+ method: "POST",
237
+ headers: {
238
+ "x-bot-api-secret-token": "secret",
239
+ "content-type": "application/json",
240
+ },
241
+ body: JSON.stringify(payload),
242
+ });
243
+
244
+ expect(first.status).toBe(200);
245
+ expect(second.status).toBe(200);
246
+ expect(sink).toHaveBeenCalledTimes(1);
247
+ },
248
+ );
249
+ } finally {
250
+ unregister();
251
+ }
252
+ });
253
+
254
+ it("returns 429 when per-path request rate exceeds threshold", async () => {
255
+ const core = {} as PluginRuntime;
256
+ const account: ResolvedZaloAccount = {
257
+ accountId: "default",
258
+ enabled: true,
259
+ token: "tok",
260
+ tokenSource: "config",
261
+ config: {},
262
+ };
263
+ const unregister = registerZaloWebhookTarget({
264
+ token: "tok",
265
+ account,
266
+ config: {} as OpenClawConfig,
267
+ runtime: {},
268
+ core,
269
+ secret: "secret",
270
+ path: "/hook-rate",
271
+ mediaMaxMb: 5,
272
+ });
273
+
274
+ try {
275
+ await withServer(
276
+ async (req, res) => {
277
+ const handled = await handleZaloWebhookRequest(req, res);
278
+ if (!handled) {
279
+ res.statusCode = 404;
280
+ res.end("not found");
281
+ }
282
+ },
283
+ async (baseUrl) => {
284
+ let saw429 = false;
285
+ for (let i = 0; i < 130; i += 1) {
286
+ const response = await fetch(`${baseUrl}/hook-rate`, {
287
+ method: "POST",
288
+ headers: {
289
+ "x-bot-api-secret-token": "secret",
290
+ "content-type": "application/json",
291
+ },
292
+ body: "{}",
293
+ });
294
+ if (response.status === 429) {
295
+ saw429 = true;
296
+ break;
297
+ }
298
+ }
299
+
300
+ expect(saw429).toBe(true);
301
+ },
302
+ );
303
+ } finally {
304
+ unregister();
305
+ }
306
+ });
134
307
  });