@laburen/openclaw-plugin-whatsapp-api 0.1.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/index.d.ts +21 -0
- package/index.js +1356 -0
- package/package.json +33 -7
- package/index.ts +0 -16
- package/src/accounts.ts +0 -102
- package/src/channel.ts +0 -253
- package/src/inbound.ts +0 -233
- package/src/outbound.ts +0 -390
- package/src/runtime.ts +0 -18
- package/src/types.ts +0 -61
- package/src/utils/common.ts +0 -19
- package/src/utils/media/inbound.ts +0 -164
- package/src/utils/media/mime.ts +0 -74
- package/src/utils/outbound/payload.ts +0 -173
- package/src/webhook.ts +0 -119
package/src/utils/media/mime.ts
DELETED
|
@@ -1,74 +0,0 @@
|
|
|
1
|
-
import path from "node:path";
|
|
2
|
-
|
|
3
|
-
const MIME_BY_EXT: Record<string, string> = {
|
|
4
|
-
".jpg": "image/jpeg",
|
|
5
|
-
".jpeg": "image/jpeg",
|
|
6
|
-
".png": "image/png",
|
|
7
|
-
".webp": "image/webp",
|
|
8
|
-
".gif": "image/gif",
|
|
9
|
-
".mp4": "video/mp4",
|
|
10
|
-
".mov": "video/quicktime",
|
|
11
|
-
".webm": "video/webm",
|
|
12
|
-
".mp3": "audio/mpeg",
|
|
13
|
-
".wav": "audio/wav",
|
|
14
|
-
".ogg": "audio/ogg",
|
|
15
|
-
".opus": "audio/ogg",
|
|
16
|
-
".m4a": "audio/mp4",
|
|
17
|
-
".pdf": "application/pdf",
|
|
18
|
-
".txt": "text/plain",
|
|
19
|
-
".csv": "text/csv",
|
|
20
|
-
".json": "application/json",
|
|
21
|
-
".zip": "application/zip",
|
|
22
|
-
};
|
|
23
|
-
|
|
24
|
-
function normalizeMime(value?: string): string | undefined {
|
|
25
|
-
const trimmed = value?.trim();
|
|
26
|
-
if (!trimmed) {
|
|
27
|
-
return undefined;
|
|
28
|
-
}
|
|
29
|
-
return trimmed.split(";")[0]?.trim().toLowerCase();
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
export function mediaKindFromMimeOrName(params: {
|
|
33
|
-
mimeType?: string;
|
|
34
|
-
fileNameOrUrl?: string;
|
|
35
|
-
}): "image" | "video" | "audio" | "document" {
|
|
36
|
-
const mime = normalizeMime(params.mimeType);
|
|
37
|
-
if (mime?.startsWith("image/")) {
|
|
38
|
-
return "image";
|
|
39
|
-
}
|
|
40
|
-
if (mime?.startsWith("video/")) {
|
|
41
|
-
return "video";
|
|
42
|
-
}
|
|
43
|
-
if (mime?.startsWith("audio/")) {
|
|
44
|
-
return "audio";
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
const ext = path.extname(params.fileNameOrUrl ?? "").toLowerCase();
|
|
48
|
-
const extMime = MIME_BY_EXT[ext];
|
|
49
|
-
if (extMime?.startsWith("image/")) {
|
|
50
|
-
return "image";
|
|
51
|
-
}
|
|
52
|
-
if (extMime?.startsWith("video/")) {
|
|
53
|
-
return "video";
|
|
54
|
-
}
|
|
55
|
-
if (extMime?.startsWith("audio/")) {
|
|
56
|
-
return "audio";
|
|
57
|
-
}
|
|
58
|
-
return "document";
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
export function mimeFromFileName(fileNameOrPath: string): string | undefined {
|
|
62
|
-
const ext = path.extname(fileNameOrPath).toLowerCase();
|
|
63
|
-
return MIME_BY_EXT[ext];
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
export function extensionFromMime(mimeType?: string): string {
|
|
67
|
-
const mime = normalizeMime(mimeType);
|
|
68
|
-
if (!mime) {
|
|
69
|
-
return ".bin";
|
|
70
|
-
}
|
|
71
|
-
const found = Object.entries(MIME_BY_EXT).find(([, value]) => value === mime)?.[0];
|
|
72
|
-
return found ?? ".bin";
|
|
73
|
-
}
|
|
74
|
-
|
|
@@ -1,173 +0,0 @@
|
|
|
1
|
-
export type NormalizedOutboundPayload = {
|
|
2
|
-
text: string;
|
|
3
|
-
mediaUrls: string[];
|
|
4
|
-
location?: {
|
|
5
|
-
latitude: number;
|
|
6
|
-
longitude: number;
|
|
7
|
-
name?: string;
|
|
8
|
-
address?: string;
|
|
9
|
-
};
|
|
10
|
-
contacts: Array<{
|
|
11
|
-
name: {
|
|
12
|
-
formatted_name: string;
|
|
13
|
-
first_name?: string;
|
|
14
|
-
last_name?: string;
|
|
15
|
-
};
|
|
16
|
-
phones?: Array<{
|
|
17
|
-
phone: string;
|
|
18
|
-
type?: string;
|
|
19
|
-
wa_id?: string;
|
|
20
|
-
}>;
|
|
21
|
-
}>;
|
|
22
|
-
};
|
|
23
|
-
|
|
24
|
-
function toTrimmedString(value: unknown): string {
|
|
25
|
-
if (typeof value !== "string") {
|
|
26
|
-
return "";
|
|
27
|
-
}
|
|
28
|
-
return value.trim();
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
function asRecord(value: unknown): Record<string, unknown> | null {
|
|
32
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
33
|
-
return null;
|
|
34
|
-
}
|
|
35
|
-
return value as Record<string, unknown>;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
function parseNumber(value: unknown): number | undefined {
|
|
39
|
-
const numeric = Number(value);
|
|
40
|
-
return Number.isFinite(numeric) ? numeric : undefined;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
function getWhatsAppPayload(record: Record<string, unknown>): Record<string, unknown> {
|
|
44
|
-
const whatsapp = asRecord(record.whatsapp) ?? {};
|
|
45
|
-
const channelData = asRecord(record.channelData) ?? {};
|
|
46
|
-
const channelDataWhatsapp = asRecord(channelData.whatsapp) ?? {};
|
|
47
|
-
return {
|
|
48
|
-
...channelDataWhatsapp,
|
|
49
|
-
...whatsapp,
|
|
50
|
-
};
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
function normalizeOutboundLocation(record: Record<string, unknown>): NormalizedOutboundPayload["location"] {
|
|
54
|
-
const whatsapp = getWhatsAppPayload(record);
|
|
55
|
-
const raw = asRecord(record.location) ?? asRecord(whatsapp.location);
|
|
56
|
-
if (!raw) {
|
|
57
|
-
return undefined;
|
|
58
|
-
}
|
|
59
|
-
const latitude = parseNumber(raw.latitude ?? raw.lat);
|
|
60
|
-
const longitude = parseNumber(raw.longitude ?? raw.lng ?? raw.lon);
|
|
61
|
-
if (latitude === undefined || longitude === undefined) {
|
|
62
|
-
return undefined;
|
|
63
|
-
}
|
|
64
|
-
return {
|
|
65
|
-
latitude,
|
|
66
|
-
longitude,
|
|
67
|
-
name: toTrimmedString(raw.name || raw.title) || undefined,
|
|
68
|
-
address: toTrimmedString(raw.address) || undefined,
|
|
69
|
-
};
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
function normalizeSingleContact(value: unknown): NormalizedOutboundPayload["contacts"][number] | undefined {
|
|
73
|
-
const raw = asRecord(value);
|
|
74
|
-
if (!raw) {
|
|
75
|
-
return undefined;
|
|
76
|
-
}
|
|
77
|
-
const nameRecord = asRecord(raw.name);
|
|
78
|
-
const firstName = toTrimmedString(nameRecord?.first_name ?? raw.first_name ?? raw.firstName);
|
|
79
|
-
const lastName = toTrimmedString(nameRecord?.last_name ?? raw.last_name ?? raw.lastName);
|
|
80
|
-
const formattedName =
|
|
81
|
-
toTrimmedString(nameRecord?.formatted_name) ||
|
|
82
|
-
toTrimmedString(raw.formatted_name || raw.formattedName || raw.display_name || raw.displayName) ||
|
|
83
|
-
[firstName, lastName].filter(Boolean).join(" ") ||
|
|
84
|
-
toTrimmedString(raw.phone || raw.msisdn);
|
|
85
|
-
if (!formattedName) {
|
|
86
|
-
return undefined;
|
|
87
|
-
}
|
|
88
|
-
const phones = new Set<string>();
|
|
89
|
-
const directPhone = toTrimmedString(raw.phone || raw.msisdn);
|
|
90
|
-
if (directPhone) {
|
|
91
|
-
phones.add(directPhone);
|
|
92
|
-
}
|
|
93
|
-
const rawPhones = Array.isArray(raw.phones) ? raw.phones : [];
|
|
94
|
-
for (const rawPhone of rawPhones) {
|
|
95
|
-
if (typeof rawPhone === "string") {
|
|
96
|
-
const cleaned = toTrimmedString(rawPhone);
|
|
97
|
-
if (cleaned) {
|
|
98
|
-
phones.add(cleaned);
|
|
99
|
-
}
|
|
100
|
-
continue;
|
|
101
|
-
}
|
|
102
|
-
const phoneRecord = asRecord(rawPhone);
|
|
103
|
-
const cleaned = toTrimmedString(phoneRecord?.phone);
|
|
104
|
-
if (cleaned) {
|
|
105
|
-
phones.add(cleaned);
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
return {
|
|
109
|
-
name: {
|
|
110
|
-
formatted_name: formattedName,
|
|
111
|
-
first_name: firstName || undefined,
|
|
112
|
-
last_name: lastName || undefined,
|
|
113
|
-
},
|
|
114
|
-
phones:
|
|
115
|
-
phones.size > 0
|
|
116
|
-
? [...phones].map((phone) => ({
|
|
117
|
-
phone,
|
|
118
|
-
}))
|
|
119
|
-
: undefined,
|
|
120
|
-
};
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
function normalizeOutboundContacts(record: Record<string, unknown>): NormalizedOutboundPayload["contacts"] {
|
|
124
|
-
const whatsapp = getWhatsAppPayload(record);
|
|
125
|
-
const rawContacts =
|
|
126
|
-
(Array.isArray(record.contacts) && record.contacts) ||
|
|
127
|
-
(Array.isArray(whatsapp.contacts) && whatsapp.contacts) ||
|
|
128
|
-
[];
|
|
129
|
-
const contacts: NormalizedOutboundPayload["contacts"] = [];
|
|
130
|
-
for (const rawContact of rawContacts) {
|
|
131
|
-
const normalized = normalizeSingleContact(rawContact);
|
|
132
|
-
if (normalized) {
|
|
133
|
-
contacts.push(normalized);
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
const singleContact =
|
|
137
|
-
normalizeSingleContact(record.contact) ??
|
|
138
|
-
normalizeSingleContact(whatsapp.contact);
|
|
139
|
-
if (singleContact) {
|
|
140
|
-
contacts.push(singleContact);
|
|
141
|
-
}
|
|
142
|
-
return contacts;
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
export function normalizeOutboundPayload(payload: unknown): NormalizedOutboundPayload {
|
|
146
|
-
if (!payload || typeof payload !== "object") {
|
|
147
|
-
return { text: "", mediaUrls: [], contacts: [] };
|
|
148
|
-
}
|
|
149
|
-
const record = payload as Record<string, unknown>;
|
|
150
|
-
const text = toTrimmedString(record.text) || toTrimmedString(record.body);
|
|
151
|
-
|
|
152
|
-
const mediaUrls = new Set<string>();
|
|
153
|
-
const mediaUrl = toTrimmedString(record.mediaUrl);
|
|
154
|
-
if (mediaUrl) {
|
|
155
|
-
mediaUrls.add(mediaUrl);
|
|
156
|
-
}
|
|
157
|
-
if (Array.isArray(record.mediaUrls)) {
|
|
158
|
-
for (const value of record.mediaUrls) {
|
|
159
|
-
const url = toTrimmedString(value);
|
|
160
|
-
if (url) {
|
|
161
|
-
mediaUrls.add(url);
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
return {
|
|
167
|
-
text,
|
|
168
|
-
mediaUrls: [...mediaUrls],
|
|
169
|
-
location: normalizeOutboundLocation(record),
|
|
170
|
-
contacts: normalizeOutboundContacts(record),
|
|
171
|
-
};
|
|
172
|
-
}
|
|
173
|
-
|
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
|
-
}
|