@kodelyth/zalo 2026.5.39 → 2026.5.42

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.
Files changed (97) hide show
  1. package/README.md +50 -0
  2. package/api.ts +8 -0
  3. package/channel-plugin-api.ts +1 -0
  4. package/contract-api.ts +5 -0
  5. package/dist/actions.runtime-C61oPfyd.js +5 -0
  6. package/dist/api.js +5 -0
  7. package/dist/channel-D8ylaEdN.js +367 -0
  8. package/dist/channel-plugin-api.js +2 -0
  9. package/dist/channel.runtime-sf-rx5n-.js +105 -0
  10. package/dist/contract-api.js +3 -0
  11. package/dist/group-access-DTQVR6Nd.js +15 -0
  12. package/dist/index.js +22 -0
  13. package/dist/monitor-CQ1bjGih.js +825 -0
  14. package/dist/monitor.webhook-CDxUxa9l.js +175 -0
  15. package/dist/runtime-api-CxXTp1Q2.js +23 -0
  16. package/dist/runtime-api.js +2 -0
  17. package/dist/secret-contract-CRFukr2n.js +87 -0
  18. package/dist/secret-contract-api.js +2 -0
  19. package/dist/send-CGAqdfSA.js +270 -0
  20. package/dist/setup-api.js +30 -0
  21. package/dist/setup-core-Dr75wK6l.js +287 -0
  22. package/dist/setup-entry.js +15 -0
  23. package/dist/setup-surface-C8zxrnzG.js +216 -0
  24. package/dist/test-api.js +2 -0
  25. package/index.test.ts +15 -0
  26. package/index.ts +20 -0
  27. package/klaw.plugin.json +2 -509
  28. package/package.json +4 -4
  29. package/runtime-api.test.ts +10 -0
  30. package/runtime-api.ts +71 -0
  31. package/secret-contract-api.ts +5 -0
  32. package/setup-api.ts +34 -0
  33. package/setup-entry.ts +13 -0
  34. package/src/accounts.test.ts +95 -0
  35. package/src/accounts.ts +65 -0
  36. package/src/actions.runtime.ts +5 -0
  37. package/src/actions.test.ts +32 -0
  38. package/src/actions.ts +62 -0
  39. package/src/api.test.ts +166 -0
  40. package/src/api.ts +265 -0
  41. package/src/approval-auth.test.ts +17 -0
  42. package/src/approval-auth.ts +25 -0
  43. package/src/channel.directory.test.ts +56 -0
  44. package/src/channel.runtime.ts +89 -0
  45. package/src/channel.startup.test.ts +121 -0
  46. package/src/channel.ts +309 -0
  47. package/src/config-schema.test.ts +30 -0
  48. package/src/config-schema.ts +29 -0
  49. package/src/group-access.ts +23 -0
  50. package/src/monitor-durable.test.ts +49 -0
  51. package/src/monitor-durable.ts +38 -0
  52. package/src/monitor.group-policy.test.ts +213 -0
  53. package/src/monitor.image.polling.test.ts +113 -0
  54. package/src/monitor.lifecycle.test.ts +194 -0
  55. package/src/monitor.pairing.lifecycle.test.ts +139 -0
  56. package/src/monitor.polling.media-reply.test.ts +433 -0
  57. package/src/monitor.reply-once.lifecycle.test.ts +178 -0
  58. package/src/monitor.ts +1009 -0
  59. package/src/monitor.types.ts +4 -0
  60. package/src/monitor.webhook.test.ts +808 -0
  61. package/src/monitor.webhook.ts +278 -0
  62. package/src/outbound-media.test.ts +186 -0
  63. package/src/outbound-media.ts +236 -0
  64. package/src/outbound-payload.contract.test.ts +143 -0
  65. package/src/probe.ts +45 -0
  66. package/src/proxy.ts +18 -0
  67. package/src/runtime-api.ts +71 -0
  68. package/src/runtime-support.ts +82 -0
  69. package/src/runtime.ts +9 -0
  70. package/src/secret-contract.ts +109 -0
  71. package/src/secret-input.ts +5 -0
  72. package/src/send.test.ts +150 -0
  73. package/src/send.ts +207 -0
  74. package/src/session-route.ts +32 -0
  75. package/src/setup-allow-from.ts +97 -0
  76. package/src/setup-core.ts +152 -0
  77. package/src/setup-status.test.ts +33 -0
  78. package/src/setup-surface.test.ts +193 -0
  79. package/src/setup-surface.ts +294 -0
  80. package/src/status-issues.test.ts +17 -0
  81. package/src/status-issues.ts +34 -0
  82. package/src/test-support/lifecycle-test-support.ts +456 -0
  83. package/src/test-support/monitor-mocks-test-support.ts +209 -0
  84. package/src/token.test.ts +92 -0
  85. package/src/token.ts +79 -0
  86. package/src/types.ts +50 -0
  87. package/test-api.ts +1 -0
  88. package/tsconfig.json +16 -0
  89. package/api.js +0 -7
  90. package/channel-plugin-api.js +0 -7
  91. package/contract-api.js +0 -7
  92. package/index.js +0 -7
  93. package/runtime-api.js +0 -7
  94. package/secret-contract-api.js +0 -7
  95. package/setup-api.js +0 -7
  96. package/setup-entry.js +0 -7
  97. package/test-api.js +0 -7
@@ -0,0 +1,17 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { zaloApprovalAuth } from "./approval-auth.js";
3
+
4
+ describe("zaloApprovalAuth", () => {
5
+ it("authorizes numeric Zalo user ids", () => {
6
+ const cfg = { channels: { zalo: { allowFrom: ["zl:123"] } } };
7
+
8
+ expect(
9
+ zaloApprovalAuth.authorizeActorAction({
10
+ cfg,
11
+ senderId: "123",
12
+ action: "approve",
13
+ approvalKind: "exec",
14
+ }),
15
+ ).toEqual({ authorized: true });
16
+ });
17
+ });
@@ -0,0 +1,25 @@
1
+ import {
2
+ createResolvedApproverActionAuthAdapter,
3
+ resolveApprovalApprovers,
4
+ } from "klaw/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,56 @@
1
+ import {
2
+ createDirectoryTestRuntime,
3
+ expectDirectorySurface,
4
+ } from "klaw/plugin-sdk/channel-test-helpers";
5
+ import { describe, expect, it } from "vitest";
6
+ import type { KlawConfig, RuntimeEnv } from "../runtime-api.js";
7
+ import { zaloPlugin } from "./channel.js";
8
+
9
+ describe("zalo directory", () => {
10
+ const runtimeEnv = createDirectoryTestRuntime() as RuntimeEnv;
11
+ const directory = expectDirectorySurface(zaloPlugin.directory);
12
+
13
+ async function expectPeersFromAllowFrom(allowFrom: string[]) {
14
+ const cfg = {
15
+ channels: {
16
+ zalo: {
17
+ allowFrom,
18
+ },
19
+ },
20
+ } as unknown as KlawConfig;
21
+
22
+ const peers = await directory.listPeers({
23
+ cfg,
24
+ accountId: undefined,
25
+ query: undefined,
26
+ limit: undefined,
27
+ runtime: runtimeEnv,
28
+ });
29
+ expect(peers).toStrictEqual([
30
+ { kind: "user", id: "123" },
31
+ { kind: "user", id: "234" },
32
+ { kind: "user", id: "345" },
33
+ ]);
34
+
35
+ await expect(
36
+ directory.listGroups({
37
+ cfg,
38
+ accountId: undefined,
39
+ query: undefined,
40
+ limit: undefined,
41
+ runtime: runtimeEnv,
42
+ }),
43
+ ).resolves.toStrictEqual([]);
44
+ }
45
+
46
+ it("lists peers from allowFrom", async () => {
47
+ await expectPeersFromAllowFrom(["zalo:123", "zl:234", "345"]);
48
+ });
49
+
50
+ it("normalizes spaced zalo prefixes in allowFrom and pairing entries", async () => {
51
+ await expectPeersFromAllowFrom([" zalo:123 ", " zl:234 ", " 345 "]);
52
+
53
+ expect(zaloPlugin.pairing?.normalizeAllowEntry?.(" zalo:123 ")).toBe("123");
54
+ expect(zaloPlugin.messaging?.normalizeTarget?.(" zl:234 ")).toBe("234");
55
+ });
56
+ });
@@ -0,0 +1,89 @@
1
+ import { createAccountStatusSink } from "klaw/plugin-sdk/channel-lifecycle";
2
+ import { probeZalo } from "./probe.js";
3
+ import { resolveZaloProxyFetch } from "./proxy.js";
4
+ import { PAIRING_APPROVED_MESSAGE, type ChannelPlugin, type KlawConfig } from "./runtime-api.js";
5
+ import { normalizeSecretInputString } from "./secret-input.js";
6
+ import { sendMessageZalo } from "./send.js";
7
+ import type { ResolvedZaloAccount } from "./types.js";
8
+
9
+ export async function notifyZaloPairingApproval(params: { cfg: KlawConfig; id: string }) {
10
+ const { resolveZaloAccount } = await import("./accounts.js");
11
+ const account = resolveZaloAccount({ cfg: params.cfg });
12
+ if (!account.token) {
13
+ throw new Error("Zalo token not configured");
14
+ }
15
+ await sendMessageZalo(params.id, PAIRING_APPROVED_MESSAGE, {
16
+ token: account.token,
17
+ });
18
+ }
19
+
20
+ export async function sendZaloText(
21
+ params: Parameters<typeof sendMessageZalo>[2] & {
22
+ to: string;
23
+ text: string;
24
+ },
25
+ ) {
26
+ return await sendMessageZalo(params.to, params.text, params);
27
+ }
28
+
29
+ export async function probeZaloAccount(params: {
30
+ account: import("./accounts.js").ResolvedZaloAccount;
31
+ timeoutMs?: number;
32
+ }) {
33
+ return await probeZalo(
34
+ params.account.token,
35
+ params.timeoutMs,
36
+ resolveZaloProxyFetch(params.account.config.proxy),
37
+ );
38
+ }
39
+
40
+ export async function startZaloGatewayAccount(
41
+ ctx: Parameters<
42
+ NonNullable<NonNullable<ChannelPlugin<ResolvedZaloAccount>["gateway"]>["startAccount"]>
43
+ >[0],
44
+ ) {
45
+ const account = ctx.account;
46
+ const token = account.token.trim();
47
+ const mode = account.config.webhookUrl ? "webhook" : "polling";
48
+ let zaloBotLabel = "";
49
+ const fetcher = resolveZaloProxyFetch(account.config.proxy);
50
+ try {
51
+ const probe = await probeZalo(token, 2500, fetcher);
52
+ const name = probe.ok ? probe.bot?.name?.trim() : null;
53
+ if (name) {
54
+ zaloBotLabel = ` (${name})`;
55
+ }
56
+ if (!probe.ok) {
57
+ ctx.log?.warn?.(
58
+ `[${account.accountId}] Zalo probe failed before provider start (${String(probe.elapsedMs)}ms): ${probe.error}`,
59
+ );
60
+ }
61
+ ctx.setStatus({
62
+ accountId: account.accountId,
63
+ bot: probe.bot,
64
+ });
65
+ } catch (err) {
66
+ ctx.log?.warn?.(
67
+ `[${account.accountId}] Zalo probe threw before provider start: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}`,
68
+ );
69
+ }
70
+ const statusSink = createAccountStatusSink({
71
+ accountId: ctx.accountId,
72
+ setStatus: ctx.setStatus,
73
+ });
74
+ ctx.log?.info(`[${account.accountId}] starting provider${zaloBotLabel} mode=${mode}`);
75
+ const { monitorZaloProvider } = await import("./monitor.js");
76
+ return monitorZaloProvider({
77
+ token,
78
+ account,
79
+ config: ctx.cfg,
80
+ runtime: ctx.runtime,
81
+ abortSignal: ctx.abortSignal,
82
+ useWebhook: Boolean(account.config.webhookUrl),
83
+ webhookUrl: account.config.webhookUrl,
84
+ webhookSecret: normalizeSecretInputString(account.config.webhookSecret),
85
+ webhookPath: account.config.webhookPath,
86
+ fetcher,
87
+ statusSink,
88
+ });
89
+ }
@@ -0,0 +1,121 @@
1
+ import {
2
+ expectLifecyclePatch,
3
+ expectPendingUntilAbort,
4
+ startAccountAndTrackLifecycle,
5
+ waitForStartedMocks,
6
+ } from "klaw/plugin-sdk/channel-test-helpers";
7
+ import { afterEach, describe, expect, it, vi } from "vitest";
8
+ import type { ResolvedZaloAccount } from "./accounts.js";
9
+
10
+ const hoisted = vi.hoisted(() => ({
11
+ monitorZaloProvider: vi.fn(),
12
+ probeZalo: vi.fn(async () => ({
13
+ ok: false as const,
14
+ error: "probe failed",
15
+ elapsedMs: 1,
16
+ })),
17
+ }));
18
+
19
+ vi.mock("./monitor.js", () => {
20
+ return {
21
+ monitorZaloProvider: hoisted.monitorZaloProvider,
22
+ };
23
+ });
24
+
25
+ vi.mock("./probe.js", () => {
26
+ return {
27
+ probeZalo: hoisted.probeZalo,
28
+ };
29
+ });
30
+
31
+ vi.mock("./channel.runtime.js", () => ({
32
+ probeZaloAccount: hoisted.probeZalo,
33
+ startZaloGatewayAccount: async (ctx: {
34
+ account: ResolvedZaloAccount;
35
+ abortSignal: AbortSignal;
36
+ setStatus: (patch: Partial<ResolvedZaloAccount>) => void;
37
+ }) => {
38
+ await hoisted.probeZalo();
39
+ ctx.setStatus({ accountId: ctx.account.accountId });
40
+ return await hoisted.monitorZaloProvider({
41
+ token: ctx.account.token,
42
+ account: ctx.account,
43
+ abortSignal: ctx.abortSignal,
44
+ useWebhook: false,
45
+ });
46
+ },
47
+ }));
48
+
49
+ import { zaloPlugin } from "./channel.js";
50
+
51
+ type ZaloGateway = NonNullable<typeof zaloPlugin.gateway>;
52
+ type ZaloStartAccount = NonNullable<ZaloGateway["startAccount"]>;
53
+
54
+ function requireStartAccount(): ZaloStartAccount {
55
+ const startAccount = zaloPlugin.gateway?.startAccount;
56
+ if (!startAccount) {
57
+ throw new Error("Expected Zalo gateway startAccount");
58
+ }
59
+ return startAccount;
60
+ }
61
+
62
+ function buildAccount(): ResolvedZaloAccount {
63
+ return {
64
+ accountId: "default",
65
+ enabled: true,
66
+ token: "test-token",
67
+ tokenSource: "config",
68
+ config: {},
69
+ };
70
+ }
71
+
72
+ function requireMonitorArgs() {
73
+ const [call] = hoisted.monitorZaloProvider.mock.calls;
74
+ if (!call) {
75
+ throw new Error("expected Zalo monitor call");
76
+ }
77
+ const [monitorArgs] = call;
78
+ return monitorArgs;
79
+ }
80
+
81
+ describe("zaloPlugin gateway.startAccount", () => {
82
+ afterEach(() => {
83
+ vi.clearAllMocks();
84
+ });
85
+
86
+ it("keeps startAccount pending until abort", async () => {
87
+ hoisted.monitorZaloProvider.mockImplementationOnce(
88
+ async ({ abortSignal }: { abortSignal: AbortSignal }) =>
89
+ await new Promise<void>((resolve) => {
90
+ if (abortSignal.aborted) {
91
+ resolve();
92
+ return;
93
+ }
94
+ abortSignal.addEventListener("abort", () => resolve(), { once: true });
95
+ }),
96
+ );
97
+
98
+ const { abort, patches, task, isSettled } = startAccountAndTrackLifecycle({
99
+ startAccount: requireStartAccount(),
100
+ account: buildAccount(),
101
+ });
102
+
103
+ await expectPendingUntilAbort({
104
+ waitForStarted: waitForStartedMocks(hoisted.probeZalo, hoisted.monitorZaloProvider),
105
+ isSettled,
106
+ abort,
107
+ task,
108
+ });
109
+
110
+ expectLifecyclePatch(patches, { accountId: "default" });
111
+ expect(isSettled()).toBe(true);
112
+ expect(hoisted.monitorZaloProvider).toHaveBeenCalledTimes(1);
113
+ const monitorArgs = requireMonitorArgs();
114
+ expect(monitorArgs).toStrictEqual({
115
+ token: "test-token",
116
+ account: buildAccount(),
117
+ abortSignal: abort.signal,
118
+ useWebhook: false,
119
+ });
120
+ });
121
+ });
package/src/channel.ts ADDED
@@ -0,0 +1,309 @@
1
+ import { describeWebhookAccountSnapshot } from "klaw/plugin-sdk/account-helpers";
2
+ import { DEFAULT_ACCOUNT_ID } from "klaw/plugin-sdk/account-id";
3
+ import { formatAllowFromLowercase } from "klaw/plugin-sdk/allow-from";
4
+ import {
5
+ adaptScopedAccountAccessor,
6
+ createScopedChannelConfigAdapter,
7
+ createScopedDmSecurityResolver,
8
+ mapAllowFromEntries,
9
+ } from "klaw/plugin-sdk/channel-config-helpers";
10
+ import type { ChannelAccountSnapshot } from "klaw/plugin-sdk/channel-contract";
11
+ import {
12
+ buildChannelConfigSchema,
13
+ createChatChannelPlugin,
14
+ type ChannelPlugin,
15
+ } from "klaw/plugin-sdk/channel-core";
16
+ import { defineChannelMessageAdapter } from "klaw/plugin-sdk/channel-message";
17
+ import {
18
+ buildOpenGroupPolicyRestrictSendersWarning,
19
+ buildOpenGroupPolicyWarning,
20
+ createOpenProviderGroupPolicyWarningCollector,
21
+ } from "klaw/plugin-sdk/channel-policy";
22
+ import {
23
+ createEmptyChannelResult,
24
+ createRawChannelSendResultAdapter,
25
+ } from "klaw/plugin-sdk/channel-send-result";
26
+ import { buildTokenChannelStatusSummary } from "klaw/plugin-sdk/channel-status";
27
+ import type { KlawConfig } from "klaw/plugin-sdk/config-contracts";
28
+ import { createStaticReplyToModeResolver } from "klaw/plugin-sdk/conversation-runtime";
29
+ import { createChannelDirectoryAdapter } from "klaw/plugin-sdk/directory-runtime";
30
+ import { listResolvedDirectoryUserEntriesFromAllowFrom } from "klaw/plugin-sdk/directory-runtime";
31
+ import { createLazyRuntimeModule } from "klaw/plugin-sdk/lazy-runtime";
32
+ import {
33
+ isNumericTargetId,
34
+ sendPayloadWithChunkedTextAndMedia,
35
+ } from "klaw/plugin-sdk/reply-payload";
36
+ import {
37
+ createComputedAccountStatusAdapter,
38
+ createDefaultChannelRuntimeState,
39
+ } from "klaw/plugin-sdk/status-helpers";
40
+ import { chunkTextForOutbound } from "klaw/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: KlawConfig;
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,30 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { ZaloConfigSchema } from "./config-schema.js";
3
+
4
+ describe("ZaloConfigSchema SecretInput", () => {
5
+ it("accepts SecretRef botToken and webhookSecret at top-level", () => {
6
+ const result = ZaloConfigSchema.safeParse({
7
+ botToken: { source: "env", provider: "default", id: "ZALO_BOT_TOKEN" },
8
+ webhookUrl: "https://example.com/zalo",
9
+ webhookSecret: { source: "env", provider: "default", id: "ZALO_WEBHOOK_SECRET" },
10
+ });
11
+ expect(result.success).toBe(true);
12
+ });
13
+
14
+ it("accepts SecretRef botToken and webhookSecret on account", () => {
15
+ const result = ZaloConfigSchema.safeParse({
16
+ accounts: {
17
+ work: {
18
+ botToken: { source: "env", provider: "default", id: "ZALO_WORK_BOT_TOKEN" },
19
+ webhookUrl: "https://example.com/zalo/work",
20
+ webhookSecret: {
21
+ source: "env",
22
+ provider: "default",
23
+ id: "ZALO_WORK_WEBHOOK_SECRET",
24
+ },
25
+ },
26
+ },
27
+ });
28
+ expect(result.success).toBe(true);
29
+ });
30
+ });
@@ -0,0 +1,29 @@
1
+ import {
2
+ AllowFromListSchema,
3
+ buildCatchallMultiAccountChannelSchema,
4
+ DmPolicySchema,
5
+ GroupPolicySchema,
6
+ MarkdownConfigSchema,
7
+ } from "klaw/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);