@gakr-gakr/zalo 0.1.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.
@@ -0,0 +1,25 @@
1
+ import {
2
+ createResolvedApproverActionAuthAdapter,
3
+ resolveApprovalApprovers,
4
+ } from "autobot/plugin-sdk/approval-auth-runtime";
5
+ import { resolveZaloAccount } from "./accounts.js";
6
+
7
+ function normalizeZaloApproverId(value: string | number): string | undefined {
8
+ const normalized = String(value)
9
+ .trim()
10
+ .replace(/^(zalo|zl):/i, "")
11
+ .trim();
12
+ return /^\d+$/.test(normalized) ? normalized : undefined;
13
+ }
14
+
15
+ export const zaloApprovalAuth = createResolvedApproverActionAuthAdapter({
16
+ channelLabel: "Zalo",
17
+ resolveApprovers: ({ cfg, accountId }) => {
18
+ const account = resolveZaloAccount({ cfg, accountId }).config;
19
+ return resolveApprovalApprovers({
20
+ allowFrom: account.allowFrom,
21
+ normalizeApprover: normalizeZaloApproverId,
22
+ });
23
+ },
24
+ normalizeSenderId: (value) => normalizeZaloApproverId(value),
25
+ });
@@ -0,0 +1,93 @@
1
+ import { createAccountStatusSink } from "autobot/plugin-sdk/channel-lifecycle";
2
+ import { probeZalo } from "./probe.js";
3
+ import { resolveZaloProxyFetch } from "./proxy.js";
4
+ import {
5
+ PAIRING_APPROVED_MESSAGE,
6
+ type ChannelPlugin,
7
+ type AutoBotConfig,
8
+ } from "./runtime-api.js";
9
+ import { normalizeSecretInputString } from "./secret-input.js";
10
+ import { sendMessageZalo } from "./send.js";
11
+ import type { ResolvedZaloAccount } from "./types.js";
12
+
13
+ export async function notifyZaloPairingApproval(params: { cfg: AutoBotConfig; id: string }) {
14
+ const { resolveZaloAccount } = await import("./accounts.js");
15
+ const account = resolveZaloAccount({ cfg: params.cfg });
16
+ if (!account.token) {
17
+ throw new Error("Zalo token not configured");
18
+ }
19
+ await sendMessageZalo(params.id, PAIRING_APPROVED_MESSAGE, {
20
+ token: account.token,
21
+ });
22
+ }
23
+
24
+ export async function sendZaloText(
25
+ params: Parameters<typeof sendMessageZalo>[2] & {
26
+ to: string;
27
+ text: string;
28
+ },
29
+ ) {
30
+ return await sendMessageZalo(params.to, params.text, params);
31
+ }
32
+
33
+ export async function probeZaloAccount(params: {
34
+ account: import("./accounts.js").ResolvedZaloAccount;
35
+ timeoutMs?: number;
36
+ }) {
37
+ return await probeZalo(
38
+ params.account.token,
39
+ params.timeoutMs,
40
+ resolveZaloProxyFetch(params.account.config.proxy),
41
+ );
42
+ }
43
+
44
+ export async function startZaloGatewayAccount(
45
+ ctx: Parameters<
46
+ NonNullable<NonNullable<ChannelPlugin<ResolvedZaloAccount>["gateway"]>["startAccount"]>
47
+ >[0],
48
+ ) {
49
+ const account = ctx.account;
50
+ const token = account.token.trim();
51
+ const mode = account.config.webhookUrl ? "webhook" : "polling";
52
+ let zaloBotLabel = "";
53
+ const fetcher = resolveZaloProxyFetch(account.config.proxy);
54
+ try {
55
+ const probe = await probeZalo(token, 2500, fetcher);
56
+ const name = probe.ok ? probe.bot?.name?.trim() : null;
57
+ if (name) {
58
+ zaloBotLabel = ` (${name})`;
59
+ }
60
+ if (!probe.ok) {
61
+ ctx.log?.warn?.(
62
+ `[${account.accountId}] Zalo probe failed before provider start (${String(probe.elapsedMs)}ms): ${probe.error}`,
63
+ );
64
+ }
65
+ ctx.setStatus({
66
+ accountId: account.accountId,
67
+ bot: probe.bot,
68
+ });
69
+ } catch (err) {
70
+ ctx.log?.warn?.(
71
+ `[${account.accountId}] Zalo probe threw before provider start: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}`,
72
+ );
73
+ }
74
+ const statusSink = createAccountStatusSink({
75
+ accountId: ctx.accountId,
76
+ setStatus: ctx.setStatus,
77
+ });
78
+ ctx.log?.info(`[${account.accountId}] starting provider${zaloBotLabel} mode=${mode}`);
79
+ const { monitorZaloProvider } = await import("./monitor.js");
80
+ return monitorZaloProvider({
81
+ token,
82
+ account,
83
+ config: ctx.cfg,
84
+ runtime: ctx.runtime,
85
+ abortSignal: ctx.abortSignal,
86
+ useWebhook: Boolean(account.config.webhookUrl),
87
+ webhookUrl: account.config.webhookUrl,
88
+ webhookSecret: normalizeSecretInputString(account.config.webhookSecret),
89
+ webhookPath: account.config.webhookPath,
90
+ fetcher,
91
+ statusSink,
92
+ });
93
+ }
package/src/channel.ts ADDED
@@ -0,0 +1,309 @@
1
+ import { describeWebhookAccountSnapshot } from "autobot/plugin-sdk/account-helpers";
2
+ import { DEFAULT_ACCOUNT_ID } from "autobot/plugin-sdk/account-id";
3
+ import { formatAllowFromLowercase } from "autobot/plugin-sdk/allow-from";
4
+ import {
5
+ adaptScopedAccountAccessor,
6
+ createScopedChannelConfigAdapter,
7
+ createScopedDmSecurityResolver,
8
+ mapAllowFromEntries,
9
+ } from "autobot/plugin-sdk/channel-config-helpers";
10
+ import type { ChannelAccountSnapshot } from "autobot/plugin-sdk/channel-contract";
11
+ import {
12
+ buildChannelConfigSchema,
13
+ createChatChannelPlugin,
14
+ type ChannelPlugin,
15
+ } from "autobot/plugin-sdk/channel-core";
16
+ import { defineChannelMessageAdapter } from "autobot/plugin-sdk/channel-message";
17
+ import {
18
+ buildOpenGroupPolicyRestrictSendersWarning,
19
+ buildOpenGroupPolicyWarning,
20
+ createOpenProviderGroupPolicyWarningCollector,
21
+ } from "autobot/plugin-sdk/channel-policy";
22
+ import {
23
+ createEmptyChannelResult,
24
+ createRawChannelSendResultAdapter,
25
+ } from "autobot/plugin-sdk/channel-send-result";
26
+ import { buildTokenChannelStatusSummary } from "autobot/plugin-sdk/channel-status";
27
+ import type { AutoBotConfig } from "autobot/plugin-sdk/config-contracts";
28
+ import { createStaticReplyToModeResolver } from "autobot/plugin-sdk/conversation-runtime";
29
+ import { createChannelDirectoryAdapter } from "autobot/plugin-sdk/directory-runtime";
30
+ import { listResolvedDirectoryUserEntriesFromAllowFrom } from "autobot/plugin-sdk/directory-runtime";
31
+ import { createLazyRuntimeModule } from "autobot/plugin-sdk/lazy-runtime";
32
+ import {
33
+ isNumericTargetId,
34
+ sendPayloadWithChunkedTextAndMedia,
35
+ } from "autobot/plugin-sdk/reply-payload";
36
+ import {
37
+ createComputedAccountStatusAdapter,
38
+ createDefaultChannelRuntimeState,
39
+ } from "autobot/plugin-sdk/status-helpers";
40
+ import { chunkTextForOutbound } from "autobot/plugin-sdk/text-chunking";
41
+ import {
42
+ listZaloAccountIds,
43
+ resolveDefaultZaloAccountId,
44
+ resolveZaloAccount,
45
+ type ResolvedZaloAccount,
46
+ } from "./accounts.js";
47
+ import { zaloMessageActions } from "./actions.js";
48
+ import { zaloApprovalAuth } from "./approval-auth.js";
49
+ import { ZaloConfigSchema } from "./config-schema.js";
50
+ import type { ZaloProbeResult } from "./probe.js";
51
+ import { collectRuntimeConfigAssignments, secretTargetRegistryEntries } from "./secret-contract.js";
52
+ import { resolveZaloOutboundSessionRoute } from "./session-route.js";
53
+ import { createZaloSetupWizardProxy, zaloSetupAdapter } from "./setup-core.js";
54
+ import { collectZaloStatusIssues } from "./status-issues.js";
55
+
56
+ const meta = {
57
+ id: "zalo",
58
+ label: "Zalo",
59
+ selectionLabel: "Zalo (Bot API)",
60
+ docsPath: "/channels/zalo",
61
+ docsLabel: "zalo",
62
+ blurb: "Vietnam-focused messaging platform with Bot API.",
63
+ aliases: ["zl"],
64
+ order: 80,
65
+ quickstartAllowFrom: true,
66
+ };
67
+
68
+ function normalizeZaloMessagingTarget(raw: string): string | undefined {
69
+ const trimmed = raw?.trim();
70
+ if (!trimmed) {
71
+ return undefined;
72
+ }
73
+ return trimmed.replace(/^(zalo|zl):/i, "").trim();
74
+ }
75
+
76
+ const loadZaloChannelRuntime = createLazyRuntimeModule(() => import("./channel.runtime.js"));
77
+ const zaloSetupWizard = createZaloSetupWizardProxy(
78
+ async () => (await import("./setup-surface.js")).zaloSetupWizard,
79
+ );
80
+ const zaloTextChunkLimit = 2000;
81
+
82
+ const zaloRawSendResultAdapter = createRawChannelSendResultAdapter({
83
+ channel: "zalo",
84
+ sendText: async ({ to, text, accountId, cfg }) =>
85
+ await (
86
+ await loadZaloChannelRuntime()
87
+ ).sendZaloText({
88
+ to,
89
+ text,
90
+ accountId: accountId ?? undefined,
91
+ cfg,
92
+ }),
93
+ sendMedia: async ({ to, text, mediaUrl, accountId, cfg }) =>
94
+ await (
95
+ await loadZaloChannelRuntime()
96
+ ).sendZaloText({
97
+ to,
98
+ text,
99
+ accountId: accountId ?? undefined,
100
+ mediaUrl,
101
+ cfg,
102
+ }),
103
+ });
104
+
105
+ export const zaloMessageAdapter = defineChannelMessageAdapter({
106
+ id: "zalo",
107
+ durableFinal: {
108
+ capabilities: {
109
+ text: true,
110
+ media: true,
111
+ messageSendingHooks: true,
112
+ },
113
+ },
114
+ send: {
115
+ text: async ({ to, text, accountId, cfg }) =>
116
+ await (
117
+ await loadZaloChannelRuntime()
118
+ ).sendZaloText({
119
+ to,
120
+ text,
121
+ accountId: accountId ?? undefined,
122
+ cfg,
123
+ }),
124
+ media: async ({ to, text, mediaUrl, accountId, cfg }) =>
125
+ await (
126
+ await loadZaloChannelRuntime()
127
+ ).sendZaloText({
128
+ to,
129
+ text,
130
+ accountId: accountId ?? undefined,
131
+ mediaUrl,
132
+ cfg,
133
+ }),
134
+ },
135
+ });
136
+
137
+ const zaloConfigAdapter = createScopedChannelConfigAdapter<ResolvedZaloAccount>({
138
+ sectionKey: "zalo",
139
+ listAccountIds: listZaloAccountIds,
140
+ resolveAccount: adaptScopedAccountAccessor(resolveZaloAccount),
141
+ defaultAccountId: resolveDefaultZaloAccountId,
142
+ clearBaseFields: ["botToken", "tokenFile", "name"],
143
+ resolveAllowFrom: (account: ResolvedZaloAccount) => account.config.allowFrom,
144
+ formatAllowFrom: (allowFrom) =>
145
+ formatAllowFromLowercase({ allowFrom, stripPrefixRe: /^(zalo|zl):/i }),
146
+ });
147
+
148
+ const resolveZaloDmPolicy = createScopedDmSecurityResolver<ResolvedZaloAccount>({
149
+ channelKey: "zalo",
150
+ resolvePolicy: (account) => account.config.dmPolicy,
151
+ resolveAllowFrom: (account) => account.config.allowFrom,
152
+ policyPathSuffix: "dmPolicy",
153
+ normalizeEntry: (raw) => raw.trim().replace(/^(zalo|zl):/i, ""),
154
+ });
155
+
156
+ const collectZaloSecurityWarnings = createOpenProviderGroupPolicyWarningCollector<{
157
+ cfg: AutoBotConfig;
158
+ account: ResolvedZaloAccount;
159
+ }>({
160
+ providerConfigPresent: (cfg) => cfg.channels?.zalo !== undefined,
161
+ resolveGroupPolicy: ({ account }) => account.config.groupPolicy,
162
+ collect: ({ account, groupPolicy }) => {
163
+ if (groupPolicy !== "open") {
164
+ return [];
165
+ }
166
+ const explicitGroupAllowFrom = mapAllowFromEntries(account.config.groupAllowFrom);
167
+ const dmAllowFrom = mapAllowFromEntries(account.config.allowFrom);
168
+ const effectiveAllowFrom =
169
+ explicitGroupAllowFrom.length > 0 ? explicitGroupAllowFrom : dmAllowFrom;
170
+ if (effectiveAllowFrom.length > 0) {
171
+ return [
172
+ buildOpenGroupPolicyRestrictSendersWarning({
173
+ surface: "Zalo groups",
174
+ openScope: "any member",
175
+ groupPolicyPath: "channels.zalo.groupPolicy",
176
+ groupAllowFromPath: "channels.zalo.groupAllowFrom",
177
+ }),
178
+ ];
179
+ }
180
+ return [
181
+ buildOpenGroupPolicyWarning({
182
+ surface: "Zalo groups",
183
+ openBehavior:
184
+ "with no groupAllowFrom/allowFrom allowlist; any member can trigger (mention-gated)",
185
+ remediation: 'Set channels.zalo.groupPolicy="allowlist" + channels.zalo.groupAllowFrom',
186
+ }),
187
+ ];
188
+ },
189
+ });
190
+
191
+ export const zaloPlugin: ChannelPlugin<ResolvedZaloAccount, ZaloProbeResult> =
192
+ createChatChannelPlugin({
193
+ base: {
194
+ id: "zalo",
195
+ meta,
196
+ setup: zaloSetupAdapter,
197
+ setupWizard: zaloSetupWizard,
198
+ capabilities: {
199
+ chatTypes: ["direct", "group"],
200
+ media: true,
201
+ reactions: false,
202
+ threads: false,
203
+ polls: false,
204
+ nativeCommands: false,
205
+ blockStreaming: true,
206
+ },
207
+ reload: { configPrefixes: ["channels.zalo"] },
208
+ configSchema: buildChannelConfigSchema(ZaloConfigSchema),
209
+ config: {
210
+ ...zaloConfigAdapter,
211
+ isConfigured: (account) => Boolean(account.token?.trim()),
212
+ describeAccount: (account): ChannelAccountSnapshot =>
213
+ describeWebhookAccountSnapshot({
214
+ account,
215
+ configured: Boolean(account.token?.trim()),
216
+ mode: account.config.webhookUrl ? "webhook" : "polling",
217
+ extra: {
218
+ tokenSource: account.tokenSource,
219
+ },
220
+ }),
221
+ },
222
+ approvalCapability: zaloApprovalAuth,
223
+ secrets: {
224
+ secretTargetRegistryEntries,
225
+ collectRuntimeConfigAssignments,
226
+ },
227
+ groups: {
228
+ resolveRequireMention: () => true,
229
+ },
230
+ actions: zaloMessageActions,
231
+ messaging: {
232
+ targetPrefixes: ["zalo", "zl"],
233
+ normalizeTarget: normalizeZaloMessagingTarget,
234
+ resolveOutboundSessionRoute: (params) => resolveZaloOutboundSessionRoute(params),
235
+ targetResolver: {
236
+ looksLikeId: isNumericTargetId,
237
+ hint: "<chatId>",
238
+ },
239
+ },
240
+ directory: createChannelDirectoryAdapter({
241
+ listPeers: async (params) =>
242
+ listResolvedDirectoryUserEntriesFromAllowFrom<ResolvedZaloAccount>({
243
+ ...params,
244
+ resolveAccount: adaptScopedAccountAccessor(resolveZaloAccount),
245
+ resolveAllowFrom: (account) => account.config.allowFrom,
246
+ normalizeId: (entry) => entry.trim().replace(/^(zalo|zl):/i, ""),
247
+ }),
248
+ listGroups: async () => [],
249
+ }),
250
+ status: createComputedAccountStatusAdapter<ResolvedZaloAccount, ZaloProbeResult>({
251
+ defaultRuntime: createDefaultChannelRuntimeState(DEFAULT_ACCOUNT_ID),
252
+ collectStatusIssues: collectZaloStatusIssues,
253
+ buildChannelSummary: ({ snapshot }) => buildTokenChannelStatusSummary(snapshot),
254
+ probeAccount: async ({ account, timeoutMs }) =>
255
+ await (await loadZaloChannelRuntime()).probeZaloAccount({ account, timeoutMs }),
256
+ resolveAccountSnapshot: ({ account }) => {
257
+ const configured = Boolean(account.token?.trim());
258
+ return {
259
+ accountId: account.accountId,
260
+ name: account.name,
261
+ enabled: account.enabled,
262
+ configured,
263
+ extra: {
264
+ tokenSource: account.tokenSource,
265
+ mode: account.config.webhookUrl ? "webhook" : "polling",
266
+ dmPolicy: account.config.dmPolicy ?? "pairing",
267
+ },
268
+ };
269
+ },
270
+ }),
271
+ gateway: {
272
+ startAccount: async (ctx) =>
273
+ await (await loadZaloChannelRuntime()).startZaloGatewayAccount(ctx),
274
+ },
275
+ message: zaloMessageAdapter,
276
+ },
277
+ security: {
278
+ resolveDmPolicy: resolveZaloDmPolicy,
279
+ collectWarnings: collectZaloSecurityWarnings,
280
+ },
281
+ pairing: {
282
+ text: {
283
+ idLabel: "zaloUserId",
284
+ message: "Your pairing request has been approved.",
285
+ normalizeAllowEntry: (entry) => entry.trim().replace(/^(zalo|zl):/i, ""),
286
+ notify: async (params) =>
287
+ await (await loadZaloChannelRuntime()).notifyZaloPairingApproval(params),
288
+ },
289
+ },
290
+ threading: {
291
+ resolveReplyToMode: createStaticReplyToModeResolver("off"),
292
+ },
293
+ outbound: {
294
+ deliveryMode: "direct",
295
+ chunker: chunkTextForOutbound,
296
+ chunkerMode: "text",
297
+ textChunkLimit: zaloTextChunkLimit,
298
+ sendPayload: async (ctx) =>
299
+ await sendPayloadWithChunkedTextAndMedia({
300
+ ctx,
301
+ textChunkLimit: zaloTextChunkLimit,
302
+ chunker: chunkTextForOutbound,
303
+ sendText: (nextCtx) => zaloRawSendResultAdapter.sendText!(nextCtx),
304
+ sendMedia: (nextCtx) => zaloRawSendResultAdapter.sendMedia!(nextCtx),
305
+ emptyResult: createEmptyChannelResult("zalo"),
306
+ }),
307
+ ...zaloRawSendResultAdapter,
308
+ },
309
+ });
@@ -0,0 +1,29 @@
1
+ import {
2
+ AllowFromListSchema,
3
+ buildCatchallMultiAccountChannelSchema,
4
+ DmPolicySchema,
5
+ GroupPolicySchema,
6
+ MarkdownConfigSchema,
7
+ } from "autobot/plugin-sdk/channel-config-schema";
8
+ import { z } from "zod";
9
+ import { buildSecretInputSchema } from "./secret-input.js";
10
+
11
+ const zaloAccountSchema = z.object({
12
+ name: z.string().optional(),
13
+ enabled: z.boolean().optional(),
14
+ markdown: MarkdownConfigSchema,
15
+ botToken: buildSecretInputSchema().optional(),
16
+ tokenFile: z.string().optional(),
17
+ webhookUrl: z.string().optional(),
18
+ webhookSecret: buildSecretInputSchema().optional(),
19
+ webhookPath: z.string().optional(),
20
+ dmPolicy: DmPolicySchema.optional(),
21
+ allowFrom: AllowFromListSchema,
22
+ groupPolicy: GroupPolicySchema.optional(),
23
+ groupAllowFrom: AllowFromListSchema,
24
+ mediaMaxMb: z.number().optional(),
25
+ proxy: z.string().optional(),
26
+ responsePrefix: z.string().optional(),
27
+ });
28
+
29
+ export const ZaloConfigSchema = buildCatchallMultiAccountChannelSchema(zaloAccountSchema);
@@ -0,0 +1,23 @@
1
+ import type { GroupPolicy } from "autobot/plugin-sdk/config-contracts";
2
+ import { resolveOpenProviderRuntimeGroupPolicy } from "autobot/plugin-sdk/runtime-group-policy";
3
+
4
+ const ZALO_ALLOW_FROM_PREFIX_RE = /^(zalo|zl):/i;
5
+
6
+ export function normalizeZaloAllowEntry(value: string): string {
7
+ return value.trim().replace(ZALO_ALLOW_FROM_PREFIX_RE, "").trim().toLowerCase();
8
+ }
9
+
10
+ export function resolveZaloRuntimeGroupPolicy(params: {
11
+ providerConfigPresent: boolean;
12
+ groupPolicy?: GroupPolicy;
13
+ defaultGroupPolicy?: GroupPolicy;
14
+ }): {
15
+ groupPolicy: GroupPolicy;
16
+ providerMissingFallbackApplied: boolean;
17
+ } {
18
+ return resolveOpenProviderRuntimeGroupPolicy({
19
+ providerConfigPresent: params.providerConfigPresent,
20
+ groupPolicy: params.groupPolicy,
21
+ defaultGroupPolicy: params.defaultGroupPolicy,
22
+ });
23
+ }
@@ -0,0 +1,38 @@
1
+ import type { MarkdownTableMode } from "autobot/plugin-sdk/config-contracts";
2
+ import { resolveSendableOutboundReplyParts } from "autobot/plugin-sdk/reply-payload";
3
+ import type { OutboundReplyPayload } from "autobot/plugin-sdk/reply-payload";
4
+
5
+ export type ZaloDurableReplyOptions = {
6
+ to: string;
7
+ };
8
+
9
+ export function prepareZaloDurableReplyPayload(params: {
10
+ payload: OutboundReplyPayload;
11
+ tableMode: MarkdownTableMode;
12
+ convertMarkdownTables: (text: string, tableMode: MarkdownTableMode) => string;
13
+ }): OutboundReplyPayload {
14
+ if (!params.payload.text) {
15
+ return params.payload;
16
+ }
17
+ return {
18
+ ...params.payload,
19
+ text: params.convertMarkdownTables(params.payload.text, params.tableMode),
20
+ };
21
+ }
22
+
23
+ export function resolveZaloDurableReplyOptions(params: {
24
+ payload: OutboundReplyPayload;
25
+ infoKind: string;
26
+ chatId: string;
27
+ }): ZaloDurableReplyOptions | false {
28
+ if (params.infoKind !== "final") {
29
+ return false;
30
+ }
31
+ const reply = resolveSendableOutboundReplyParts(params.payload);
32
+ if (reply.hasMedia || !reply.hasText) {
33
+ return false;
34
+ }
35
+ return {
36
+ to: params.chatId,
37
+ };
38
+ }