@laburen/openclaw-plugin-whatsapp-api 0.0.1 → 0.2.0

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/src/types.ts DELETED
@@ -1,32 +0,0 @@
1
- export type ResolvedWhatsAppApiAccount = {
2
- accountId: string;
3
- enabled: boolean;
4
- webhookPath: string;
5
- inboundSharedSecret?: string;
6
- outboundPhoneNumberId?: string;
7
- outboundAccessToken?: string;
8
- outboundApiVersion: string;
9
- requestTimeoutMs: number;
10
- maxRetries: number;
11
- retryBackoffMs: number;
12
- dedupeTtlMs: number;
13
- maxBodyBytes: number;
14
- };
15
-
16
- export type WhatsAppApiInboundMessage = {
17
- accountId: string;
18
- from: string;
19
- to: string;
20
- messageId: string;
21
- text: string;
22
- chatType: "direct";
23
- timestamp?: number;
24
- senderName?: string;
25
- replyToId?: string;
26
- };
27
-
28
- export type WhatsAppApiSendTextParams = {
29
- to: string;
30
- text: string;
31
- account: ResolvedWhatsAppApiAccount;
32
- };
package/src/webhook.ts DELETED
@@ -1,119 +0,0 @@
1
- import type { IncomingMessage, ServerResponse } from "node:http";
2
- import { parseWhatsAppCloudInbound } from "./inbound.js";
3
- import type { ResolvedWhatsAppApiAccount, WhatsAppApiInboundMessage } from "./types.js";
4
-
5
- type LogLike = {
6
- info?: (message: string) => void;
7
- warn?: (message: string) => void;
8
- error?: (message: string) => void;
9
- };
10
-
11
- const dedupeStore = new Map<string, number>();
12
-
13
- function cleanupDedupe(now: number): void {
14
- for (const [key, expiresAt] of dedupeStore.entries()) {
15
- if (expiresAt <= now) {
16
- dedupeStore.delete(key);
17
- }
18
- }
19
- }
20
-
21
- function isDuplicate(accountId: string, messageId: string, ttlMs: number): boolean {
22
- const now = Date.now();
23
- cleanupDedupe(now);
24
- const key = `${accountId}:${messageId}`;
25
- const current = dedupeStore.get(key);
26
- if (current && current > now) {
27
- return true;
28
- }
29
- dedupeStore.set(key, now + ttlMs);
30
- return false;
31
- }
32
-
33
- async function readBody(req: IncomingMessage, maxBodyBytes: number): Promise<string> {
34
- const chunks: Buffer[] = [];
35
- let total = 0;
36
- for await (const chunk of req) {
37
- const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
38
- total += buf.length;
39
- if (total > maxBodyBytes) {
40
- throw new Error("Payload exceeds maxBodyBytes");
41
- }
42
- chunks.push(buf);
43
- }
44
- return Buffer.concat(chunks).toString("utf8");
45
- }
46
-
47
- function isAuthorized(req: IncomingMessage, account: ResolvedWhatsAppApiAccount): boolean {
48
- const required = account.inboundSharedSecret?.trim();
49
- if (!required) {
50
- return true;
51
- }
52
- const header = req.headers["x-openclaw-shared-secret"];
53
- const value = Array.isArray(header) ? header[0] : header;
54
- return value?.trim() === required;
55
- }
56
-
57
- function json(res: ServerResponse, statusCode: number, body: Record<string, unknown>) {
58
- res.statusCode = statusCode;
59
- res.setHeader("content-type", "application/json; charset=utf-8");
60
- res.end(JSON.stringify(body));
61
- }
62
-
63
- export async function handleWhatsAppApiWebhook(params: {
64
- req: IncomingMessage;
65
- res: ServerResponse;
66
- account: ResolvedWhatsAppApiAccount;
67
- log?: LogLike;
68
- onMessage: (message: WhatsAppApiInboundMessage) => Promise<void>;
69
- }): Promise<boolean> {
70
- const { req, res, account, log, onMessage } = params;
71
- if (req.method !== "POST") {
72
- json(res, 405, { ok: false, error: "Method not allowed" });
73
- return true;
74
- }
75
-
76
- if (!isAuthorized(req, account)) {
77
- json(res, 403, { ok: false, error: "Forbidden" });
78
- return true;
79
- }
80
-
81
- let payload: unknown;
82
- try {
83
- const bodyText = await readBody(req, account.maxBodyBytes);
84
- payload = bodyText ? JSON.parse(bodyText) : {};
85
- } catch (err) {
86
- log?.warn?.(`[whatsapp-api] invalid inbound payload for account ${account.accountId}: ${String(err)}`);
87
- json(res, 400, { ok: false, error: "Invalid payload" });
88
- return true;
89
- }
90
-
91
- const inboundMessages = parseWhatsAppCloudInbound({
92
- payload,
93
- accountId: account.accountId,
94
- });
95
-
96
- // ACK immediately; process asynchronously to keep webhook latency low.
97
- json(res, 200, {
98
- ok: true,
99
- accepted: inboundMessages.length,
100
- accountId: account.accountId,
101
- });
102
-
103
- void (async () => {
104
- for (const message of inboundMessages) {
105
- if (isDuplicate(account.accountId, message.messageId, account.dedupeTtlMs)) {
106
- continue;
107
- }
108
- try {
109
- await onMessage(message);
110
- } catch (err) {
111
- log?.error?.(
112
- `[whatsapp-api] failed processing message ${message.messageId} for account ${account.accountId}: ${String(err)}`,
113
- );
114
- }
115
- }
116
- })();
117
-
118
- return true;
119
- }