@kodelyth/zalo 2026.5.42 → 2026.6.2

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 (67) hide show
  1. package/klaw.plugin.json +509 -2
  2. package/package.json +19 -6
  3. package/api.ts +0 -8
  4. package/channel-plugin-api.ts +0 -1
  5. package/contract-api.ts +0 -5
  6. package/index.test.ts +0 -15
  7. package/index.ts +0 -20
  8. package/runtime-api.test.ts +0 -10
  9. package/runtime-api.ts +0 -71
  10. package/secret-contract-api.ts +0 -5
  11. package/setup-api.ts +0 -34
  12. package/setup-entry.ts +0 -13
  13. package/src/accounts.test.ts +0 -95
  14. package/src/accounts.ts +0 -65
  15. package/src/actions.runtime.ts +0 -5
  16. package/src/actions.test.ts +0 -32
  17. package/src/actions.ts +0 -62
  18. package/src/api.test.ts +0 -166
  19. package/src/api.ts +0 -265
  20. package/src/approval-auth.test.ts +0 -17
  21. package/src/approval-auth.ts +0 -25
  22. package/src/channel.directory.test.ts +0 -56
  23. package/src/channel.runtime.ts +0 -89
  24. package/src/channel.startup.test.ts +0 -121
  25. package/src/channel.ts +0 -309
  26. package/src/config-schema.test.ts +0 -30
  27. package/src/config-schema.ts +0 -29
  28. package/src/group-access.ts +0 -23
  29. package/src/monitor-durable.test.ts +0 -49
  30. package/src/monitor-durable.ts +0 -38
  31. package/src/monitor.group-policy.test.ts +0 -213
  32. package/src/monitor.image.polling.test.ts +0 -113
  33. package/src/monitor.lifecycle.test.ts +0 -194
  34. package/src/monitor.pairing.lifecycle.test.ts +0 -139
  35. package/src/monitor.polling.media-reply.test.ts +0 -433
  36. package/src/monitor.reply-once.lifecycle.test.ts +0 -178
  37. package/src/monitor.ts +0 -1009
  38. package/src/monitor.types.ts +0 -4
  39. package/src/monitor.webhook.test.ts +0 -808
  40. package/src/monitor.webhook.ts +0 -278
  41. package/src/outbound-media.test.ts +0 -186
  42. package/src/outbound-media.ts +0 -236
  43. package/src/outbound-payload.contract.test.ts +0 -143
  44. package/src/probe.ts +0 -45
  45. package/src/proxy.ts +0 -18
  46. package/src/runtime-api.ts +0 -71
  47. package/src/runtime-support.ts +0 -82
  48. package/src/runtime.ts +0 -9
  49. package/src/secret-contract.ts +0 -109
  50. package/src/secret-input.ts +0 -5
  51. package/src/send.test.ts +0 -150
  52. package/src/send.ts +0 -207
  53. package/src/session-route.ts +0 -32
  54. package/src/setup-allow-from.ts +0 -97
  55. package/src/setup-core.ts +0 -152
  56. package/src/setup-status.test.ts +0 -33
  57. package/src/setup-surface.test.ts +0 -193
  58. package/src/setup-surface.ts +0 -294
  59. package/src/status-issues.test.ts +0 -17
  60. package/src/status-issues.ts +0 -34
  61. package/src/test-support/lifecycle-test-support.ts +0 -456
  62. package/src/test-support/monitor-mocks-test-support.ts +0 -209
  63. package/src/token.test.ts +0 -92
  64. package/src/token.ts +0 -79
  65. package/src/types.ts +0 -50
  66. package/test-api.ts +0 -1
  67. package/tsconfig.json +0 -16
package/src/channel.ts DELETED
@@ -1,309 +0,0 @@
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
- });
@@ -1,30 +0,0 @@
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
- });
@@ -1,29 +0,0 @@
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);
@@ -1,23 +0,0 @@
1
- import type { GroupPolicy } from "klaw/plugin-sdk/config-contracts";
2
- import { resolveOpenProviderRuntimeGroupPolicy } from "klaw/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
- }
@@ -1,49 +0,0 @@
1
- import { describe, expect, it, vi } from "vitest";
2
- import {
3
- prepareZaloDurableReplyPayload,
4
- resolveZaloDurableReplyOptions,
5
- } from "./monitor-durable.js";
6
-
7
- describe("Zalo durable reply helpers", () => {
8
- it("normalizes markdown tables before durable or legacy delivery", () => {
9
- const convertMarkdownTables = vi.fn(() => "converted table");
10
-
11
- expect(
12
- prepareZaloDurableReplyPayload({
13
- payload: { text: "| a |\n| - |" },
14
- tableMode: "code",
15
- convertMarkdownTables,
16
- }),
17
- ).toEqual({ text: "converted table" });
18
- expect(convertMarkdownTables).toHaveBeenCalledWith("| a |\n| - |", "code");
19
- });
20
-
21
- it("uses durable final delivery for text-only final replies", () => {
22
- expect(
23
- resolveZaloDurableReplyOptions({
24
- payload: { text: "hello" },
25
- infoKind: "final",
26
- chatId: "123456789",
27
- }),
28
- ).toEqual({
29
- to: "123456789",
30
- });
31
- });
32
-
33
- it("keeps media and non-final replies on the legacy path", () => {
34
- expect(
35
- resolveZaloDurableReplyOptions({
36
- payload: { text: "photo", mediaUrl: "https://example.com/photo.jpg" },
37
- infoKind: "final",
38
- chatId: "123456789",
39
- }),
40
- ).toBe(false);
41
- expect(
42
- resolveZaloDurableReplyOptions({
43
- payload: { text: "hello" },
44
- infoKind: "block",
45
- chatId: "123456789",
46
- }),
47
- ).toBe(false);
48
- });
49
- });
@@ -1,38 +0,0 @@
1
- import type { MarkdownTableMode } from "klaw/plugin-sdk/config-contracts";
2
- import { resolveSendableOutboundReplyParts } from "klaw/plugin-sdk/reply-payload";
3
- import type { OutboundReplyPayload } from "klaw/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
- }
@@ -1,213 +0,0 @@
1
- import { resolveStableChannelMessageIngress } from "klaw/plugin-sdk/channel-ingress-runtime";
2
- import type { GroupPolicy, KlawConfig } from "klaw/plugin-sdk/config-contracts";
3
- import { describe, expect, it, vi } from "vitest";
4
- import { normalizeZaloAllowEntry, resolveZaloRuntimeGroupPolicy } from "./group-access.js";
5
- import type { ZaloAccountConfig } from "./types.js";
6
-
7
- function stringEntries(entries: Array<string | number> | undefined): string[] {
8
- return (entries ?? []).map((entry) => String(entry));
9
- }
10
-
11
- const groupPolicyCases: Array<[string, ZaloAccountConfig, string, boolean, string]> = [
12
- [
13
- "disabled policy",
14
- { groupPolicy: "disabled", groupAllowFrom: ["zalo:123"] },
15
- "123",
16
- false,
17
- "group_policy_disabled",
18
- ],
19
- [
20
- "empty allowlist",
21
- { groupPolicy: "allowlist", groupAllowFrom: [] },
22
- "attacker",
23
- false,
24
- "group_policy_empty_allowlist",
25
- ],
26
- [
27
- "allowlist mismatch",
28
- { groupPolicy: "allowlist", groupAllowFrom: ["zalo:victim-user-001"] },
29
- "attacker-user-999",
30
- false,
31
- "group_policy_not_allowlisted",
32
- ],
33
- [
34
- "Zalo prefix match",
35
- { groupPolicy: "allowlist", groupAllowFrom: ["zl:12345"] },
36
- "12345",
37
- true,
38
- "group_policy_allowed",
39
- ],
40
- [
41
- "allowFrom fallback",
42
- { groupPolicy: "allowlist", allowFrom: ["zl:12345"], groupAllowFrom: [] },
43
- "12345",
44
- true,
45
- "group_policy_allowed",
46
- ],
47
- [
48
- "open policy",
49
- { groupPolicy: "open", groupAllowFrom: [] },
50
- "attacker-user-999",
51
- true,
52
- "group_policy_open",
53
- ],
54
- ];
55
-
56
- async function resolveAccess(
57
- params: {
58
- cfg?: KlawConfig;
59
- accountConfig?: ZaloAccountConfig;
60
- providerConfigPresent?: boolean;
61
- defaultGroupPolicy?: GroupPolicy;
62
- isGroup?: boolean;
63
- senderId?: string;
64
- rawBody?: string;
65
- storeAllowFrom?: string[];
66
- shouldComputeCommandAuthorized?: boolean;
67
- } = {},
68
- ) {
69
- const readAllowFromStore = vi.fn(async () => params.storeAllowFrom ?? []);
70
- const accountConfig = {
71
- dmPolicy: "pairing",
72
- groupPolicy: "allowlist",
73
- allowFrom: [],
74
- groupAllowFrom: [],
75
- ...params.accountConfig,
76
- } satisfies ZaloAccountConfig;
77
- const { groupPolicy, providerMissingFallbackApplied } = resolveZaloRuntimeGroupPolicy({
78
- providerConfigPresent: params.providerConfigPresent ?? true,
79
- groupPolicy: accountConfig.groupPolicy,
80
- defaultGroupPolicy: params.defaultGroupPolicy ?? "open",
81
- });
82
- const shouldComputeAuth = params.shouldComputeCommandAuthorized ?? false;
83
- const isGroup = params.isGroup ?? true;
84
- const result = await resolveStableChannelMessageIngress({
85
- channelId: "zalo",
86
- accountId: "default",
87
- identity: {
88
- key: "zalo-user-id",
89
- normalize: normalizeZaloAllowEntry,
90
- sensitivity: "pii",
91
- entryIdPrefix: "zalo-entry",
92
- },
93
- accessGroups: params.cfg?.accessGroups,
94
- readStoreAllowFrom: async () => await readAllowFromStore(),
95
- useAccessGroups: params.cfg?.commands?.useAccessGroups !== false,
96
- subject: { stableId: params.senderId ?? "123" },
97
- conversation: {
98
- kind: isGroup ? "group" : "direct",
99
- id: "chat-1",
100
- },
101
- providerMissingFallbackApplied,
102
- dmPolicy: accountConfig.dmPolicy ?? "pairing",
103
- groupPolicy,
104
- policy: { groupAllowFromFallbackToAllowFrom: true },
105
- allowFrom: stringEntries(accountConfig.allowFrom),
106
- groupAllowFrom: stringEntries(accountConfig.groupAllowFrom),
107
- command: shouldComputeAuth ? {} : undefined,
108
- });
109
- return { result, readAllowFromStore };
110
- }
111
-
112
- function stableSenderAccess(access: { allowed: boolean; decision: string; reasonCode: string }) {
113
- return {
114
- allowed: access.allowed,
115
- decision: access.decision,
116
- reasonCode: access.reasonCode,
117
- };
118
- }
119
-
120
- describe("zalo shared ingress access policy", () => {
121
- it.each(groupPolicyCases)(
122
- "maps %s through shared ingress",
123
- async (_name, accountConfig, senderId, allowed, reasonCode) => {
124
- const { result } = await resolveAccess({ accountConfig, senderId });
125
- expect(stableSenderAccess(result.senderAccess)).toEqual({
126
- allowed,
127
- decision: allowed ? "allow" : "block",
128
- reasonCode,
129
- });
130
- },
131
- );
132
-
133
- it("keeps group control-command authorization separate from group sender access", async () => {
134
- const { result } = await resolveAccess({
135
- accountConfig: {
136
- groupPolicy: "open",
137
- allowFrom: [],
138
- groupAllowFrom: [],
139
- },
140
- rawBody: "/reset",
141
- shouldComputeCommandAuthorized: true,
142
- });
143
-
144
- expect(result.senderAccess.decision).toBe("allow");
145
- expect(result.commandAccess.authorized).toBe(false);
146
- });
147
-
148
- it("authorizes direct commands from the pairing store", async () => {
149
- const { result, readAllowFromStore } = await resolveAccess({
150
- isGroup: false,
151
- accountConfig: {
152
- dmPolicy: "pairing",
153
- allowFrom: [],
154
- },
155
- senderId: "12345",
156
- storeAllowFrom: ["zl:12345"],
157
- rawBody: "/status",
158
- shouldComputeCommandAuthorized: true,
159
- });
160
-
161
- expect(readAllowFromStore).toHaveBeenCalledTimes(1);
162
- expect(stableSenderAccess(result.senderAccess)).toEqual({
163
- allowed: true,
164
- decision: "allow",
165
- reasonCode: "dm_policy_allowlisted",
166
- });
167
- expect(result.commandAccess.authorized).toBe(true);
168
- });
169
-
170
- it("requires an explicit wildcard or allowlist match for open DMs", async () => {
171
- const { result, readAllowFromStore } = await resolveAccess({
172
- isGroup: false,
173
- accountConfig: {
174
- dmPolicy: "open",
175
- allowFrom: [],
176
- },
177
- senderId: "12345",
178
- });
179
-
180
- expect(readAllowFromStore).not.toHaveBeenCalled();
181
- expect(stableSenderAccess(result.senderAccess)).toEqual({
182
- allowed: false,
183
- decision: "block",
184
- reasonCode: "dm_policy_not_allowlisted",
185
- });
186
- });
187
-
188
- it("matches static access-group entries through the shared ingress resolver", async () => {
189
- const { result } = await resolveAccess({
190
- cfg: {
191
- accessGroups: {
192
- operators: {
193
- type: "message.senders",
194
- members: {
195
- zalo: ["zl:12345"],
196
- },
197
- },
198
- },
199
- },
200
- accountConfig: {
201
- groupPolicy: "allowlist",
202
- groupAllowFrom: ["accessGroup:operators"],
203
- },
204
- senderId: "12345",
205
- });
206
-
207
- expect(stableSenderAccess(result.senderAccess)).toEqual({
208
- allowed: true,
209
- decision: "allow",
210
- reasonCode: "group_policy_allowed",
211
- });
212
- });
213
- });