@openclaw/zalouser 2026.3.12 → 2026.5.1-beta.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/README.md +4 -3
  2. package/api.ts +9 -0
  3. package/channel-plugin-api.ts +3 -0
  4. package/contract-api.ts +2 -0
  5. package/doctor-contract-api.ts +1 -0
  6. package/index.ts +29 -24
  7. package/openclaw.plugin.json +288 -1
  8. package/package.json +38 -11
  9. package/runtime-api.ts +67 -0
  10. package/secret-contract-api.ts +4 -0
  11. package/setup-entry.ts +9 -0
  12. package/setup-plugin-api.ts +2 -0
  13. package/src/accounts.runtime.ts +1 -0
  14. package/src/accounts.test-mocks.ts +14 -0
  15. package/src/accounts.test.ts +53 -1
  16. package/src/accounts.ts +52 -37
  17. package/src/channel-api.ts +20 -0
  18. package/src/channel.adapters.ts +390 -0
  19. package/src/channel.directory.test.ts +48 -61
  20. package/src/channel.runtime.ts +12 -0
  21. package/src/channel.sendpayload.test.ts +42 -37
  22. package/src/channel.setup.test.ts +33 -0
  23. package/src/channel.setup.ts +12 -0
  24. package/src/channel.test.ts +258 -56
  25. package/src/channel.ts +176 -692
  26. package/src/config-schema.ts +5 -5
  27. package/src/directory.ts +54 -0
  28. package/src/doctor-contract.ts +156 -0
  29. package/src/doctor.test.ts +77 -0
  30. package/src/doctor.ts +37 -0
  31. package/src/group-policy.test.ts +4 -4
  32. package/src/group-policy.ts +4 -2
  33. package/src/monitor.account-scope.test.ts +4 -10
  34. package/src/monitor.group-gating.test.ts +319 -190
  35. package/src/monitor.ts +233 -182
  36. package/src/probe.ts +3 -2
  37. package/src/qr-temp-file.ts +1 -1
  38. package/src/reaction.ts +5 -2
  39. package/src/runtime.ts +6 -3
  40. package/src/security-audit.test.ts +80 -0
  41. package/src/security-audit.ts +71 -0
  42. package/src/send.test.ts +2 -2
  43. package/src/send.ts +3 -3
  44. package/src/session-route.ts +121 -0
  45. package/src/setup-core.ts +33 -0
  46. package/src/setup-surface.test.ts +363 -0
  47. package/src/setup-surface.ts +470 -0
  48. package/src/setup-test-helpers.ts +42 -0
  49. package/src/shared.ts +92 -0
  50. package/src/status-issues.test.ts +5 -17
  51. package/src/status-issues.ts +18 -30
  52. package/src/test-helpers.ts +26 -0
  53. package/src/text-styles.test.ts +1 -1
  54. package/src/text-styles.ts +5 -2
  55. package/src/tool.test.ts +66 -3
  56. package/src/tool.ts +76 -14
  57. package/src/types.ts +3 -3
  58. package/src/zalo-js.credentials.test.ts +465 -0
  59. package/src/zalo-js.test-mocks.ts +89 -0
  60. package/src/zalo-js.ts +491 -274
  61. package/src/zca-client.test.ts +24 -0
  62. package/src/zca-client.ts +24 -58
  63. package/src/zca-constants.ts +55 -0
  64. package/test-api.ts +21 -0
  65. package/tsconfig.json +16 -0
  66. package/CHANGELOG.md +0 -101
  67. package/src/onboarding.ts +0 -340
package/src/accounts.ts CHANGED
@@ -1,7 +1,19 @@
1
- import { DEFAULT_ACCOUNT_ID, normalizeAccountId } from "openclaw/plugin-sdk/account-id";
2
- import { createAccountListHelpers, type OpenClawConfig } from "openclaw/plugin-sdk/zalouser";
1
+ import {
2
+ createAccountListHelpers,
3
+ DEFAULT_ACCOUNT_ID,
4
+ normalizeAccountId,
5
+ resolveMergedAccountConfig,
6
+ } from "openclaw/plugin-sdk/account-resolution";
7
+ import type { OpenClawConfig } from "openclaw/plugin-sdk/config-types";
8
+ import { normalizeOptionalString } from "openclaw/plugin-sdk/text-runtime";
3
9
  import type { ResolvedZalouserAccount, ZalouserAccountConfig, ZalouserConfig } from "./types.js";
4
- import { checkZaloAuthenticated, getZaloUserInfo } from "./zalo-js.js";
10
+
11
+ let zalouserAccountsRuntimePromise: Promise<typeof import("./accounts.runtime.js")> | undefined;
12
+
13
+ async function loadZalouserAccountsRuntime() {
14
+ zalouserAccountsRuntimePromise ??= import("./accounts.runtime.js");
15
+ return await zalouserAccountsRuntimePromise;
16
+ }
5
17
 
6
18
  const {
7
19
  listAccountIds: listZalouserAccountIds,
@@ -9,22 +21,20 @@ const {
9
21
  } = createAccountListHelpers("zalouser");
10
22
  export { listZalouserAccountIds, resolveDefaultZalouserAccountId };
11
23
 
12
- function resolveAccountConfig(
13
- cfg: OpenClawConfig,
14
- accountId: string,
15
- ): ZalouserAccountConfig | undefined {
16
- const accounts = (cfg.channels?.zalouser as ZalouserConfig | undefined)?.accounts;
17
- if (!accounts || typeof accounts !== "object") {
18
- return undefined;
19
- }
20
- return accounts[accountId] as ZalouserAccountConfig | undefined;
21
- }
22
-
23
24
  function mergeZalouserAccountConfig(cfg: OpenClawConfig, accountId: string): ZalouserAccountConfig {
24
- const raw = (cfg.channels?.zalouser ?? {}) as ZalouserConfig;
25
- const { accounts: _ignored, defaultAccount: _ignored2, ...base } = raw;
26
- const account = resolveAccountConfig(cfg, accountId) ?? {};
27
- return { ...base, ...account };
25
+ const merged = resolveMergedAccountConfig<ZalouserAccountConfig>({
26
+ channelConfig: cfg.channels?.zalouser as ZalouserAccountConfig | undefined,
27
+ accounts: (cfg.channels?.zalouser as ZalouserConfig | undefined)?.accounts as
28
+ | Record<string, Partial<ZalouserAccountConfig>>
29
+ | undefined,
30
+ accountId,
31
+ omitKeys: ["defaultAccount"],
32
+ });
33
+ return {
34
+ ...merged,
35
+ // Match Telegram's safe default: groups stay allowlisted unless explicitly opened.
36
+ groupPolicy: merged.groupPolicy ?? "allowlist",
37
+ };
28
38
  }
29
39
 
30
40
  function resolveProfile(config: ZalouserAccountConfig, accountId: string): string {
@@ -43,22 +53,31 @@ function resolveProfile(config: ZalouserAccountConfig, accountId: string): strin
43
53
  return "default";
44
54
  }
45
55
 
56
+ function resolveZalouserAccountBase(params: { cfg: OpenClawConfig; accountId?: string | null }) {
57
+ const accountId = normalizeAccountId(
58
+ params.accountId ?? resolveDefaultZalouserAccountId(params.cfg),
59
+ );
60
+ const baseEnabled =
61
+ (params.cfg.channels?.zalouser as ZalouserConfig | undefined)?.enabled !== false;
62
+ const merged = mergeZalouserAccountConfig(params.cfg, accountId);
63
+ return {
64
+ accountId,
65
+ enabled: baseEnabled && merged.enabled !== false,
66
+ merged,
67
+ profile: resolveProfile(merged, accountId),
68
+ };
69
+ }
70
+
46
71
  export async function resolveZalouserAccount(params: {
47
72
  cfg: OpenClawConfig;
48
73
  accountId?: string | null;
49
74
  }): Promise<ResolvedZalouserAccount> {
50
- const accountId = normalizeAccountId(params.accountId);
51
- const baseEnabled =
52
- (params.cfg.channels?.zalouser as ZalouserConfig | undefined)?.enabled !== false;
53
- const merged = mergeZalouserAccountConfig(params.cfg, accountId);
54
- const accountEnabled = merged.enabled !== false;
55
- const enabled = baseEnabled && accountEnabled;
56
- const profile = resolveProfile(merged, accountId);
57
- const authenticated = await checkZaloAuthenticated(profile);
75
+ const { accountId, enabled, merged, profile } = resolveZalouserAccountBase(params);
76
+ const authenticated = await (await loadZalouserAccountsRuntime()).checkZaloAuthenticated(profile);
58
77
 
59
78
  return {
60
79
  accountId,
61
- name: merged.name?.trim() || undefined,
80
+ name: normalizeOptionalString(merged.name),
62
81
  enabled,
63
82
  profile,
64
83
  authenticated,
@@ -70,17 +89,11 @@ export function resolveZalouserAccountSync(params: {
70
89
  cfg: OpenClawConfig;
71
90
  accountId?: string | null;
72
91
  }): ResolvedZalouserAccount {
73
- const accountId = normalizeAccountId(params.accountId);
74
- const baseEnabled =
75
- (params.cfg.channels?.zalouser as ZalouserConfig | undefined)?.enabled !== false;
76
- const merged = mergeZalouserAccountConfig(params.cfg, accountId);
77
- const accountEnabled = merged.enabled !== false;
78
- const enabled = baseEnabled && accountEnabled;
79
- const profile = resolveProfile(merged, accountId);
92
+ const { accountId, enabled, merged, profile } = resolveZalouserAccountBase(params);
80
93
 
81
94
  return {
82
95
  accountId,
83
- name: merged.name?.trim() || undefined,
96
+ name: normalizeOptionalString(merged.name),
84
97
  enabled,
85
98
  profile,
86
99
  authenticated: false,
@@ -101,7 +114,7 @@ export async function listEnabledZalouserAccounts(
101
114
  export async function getZcaUserInfo(
102
115
  profile: string,
103
116
  ): Promise<{ userId?: string; displayName?: string } | null> {
104
- const info = await getZaloUserInfo(profile);
117
+ const info = await (await loadZalouserAccountsRuntime()).getZaloUserInfo(profile);
105
118
  if (!info) {
106
119
  return null;
107
120
  }
@@ -111,6 +124,8 @@ export async function getZcaUserInfo(
111
124
  };
112
125
  }
113
126
 
114
- export { checkZaloAuthenticated as checkZcaAuthenticated };
127
+ export async function checkZcaAuthenticated(profile: string): Promise<boolean> {
128
+ return await (await loadZalouserAccountsRuntime()).checkZaloAuthenticated(profile);
129
+ }
115
130
 
116
131
  export type { ResolvedZalouserAccount } from "./types.js";
@@ -0,0 +1,20 @@
1
+ export { formatAllowFromLowercase } from "openclaw/plugin-sdk/allow-from";
2
+ export type {
3
+ ChannelDirectoryEntry,
4
+ ChannelGroupContext,
5
+ ChannelMessageActionAdapter,
6
+ } from "openclaw/plugin-sdk/channel-contract";
7
+ export { buildChannelConfigSchema } from "openclaw/plugin-sdk/channel-config-schema";
8
+ export type { ChannelPlugin } from "openclaw/plugin-sdk/core";
9
+ export {
10
+ DEFAULT_ACCOUNT_ID,
11
+ normalizeAccountId,
12
+ type OpenClawConfig,
13
+ } from "openclaw/plugin-sdk/core";
14
+ export { isDangerousNameMatchingEnabled } from "openclaw/plugin-sdk/dangerous-name-runtime";
15
+ export type { GroupToolPolicyConfig } from "openclaw/plugin-sdk/config-types";
16
+ export { chunkTextForOutbound } from "openclaw/plugin-sdk/text-chunking";
17
+ export {
18
+ isNumericTargetId,
19
+ sendPayloadWithChunkedTextAndMedia,
20
+ } from "openclaw/plugin-sdk/reply-payload";
@@ -0,0 +1,390 @@
1
+ import { createScopedDmSecurityResolver } from "openclaw/plugin-sdk/channel-config-helpers";
2
+ import { createPairingPrefixStripper } from "openclaw/plugin-sdk/channel-pairing";
3
+ import {
4
+ createEmptyChannelResult,
5
+ createRawChannelSendResultAdapter,
6
+ } from "openclaw/plugin-sdk/channel-send-result";
7
+ import { createStaticReplyToModeResolver } from "openclaw/plugin-sdk/conversation-runtime";
8
+ import { createLazyRuntimeModule } from "openclaw/plugin-sdk/lazy-runtime";
9
+ import type { RuntimeEnv } from "openclaw/plugin-sdk/runtime-env";
10
+ import { normalizeLowercaseStringOrEmpty } from "openclaw/plugin-sdk/text-runtime";
11
+ import {
12
+ checkZcaAuthenticated,
13
+ listZalouserAccountIds,
14
+ resolveDefaultZalouserAccountId,
15
+ resolveZalouserAccountSync,
16
+ type ResolvedZalouserAccount,
17
+ } from "./accounts.js";
18
+ import type {
19
+ ChannelGroupContext,
20
+ ChannelMessageActionAdapter,
21
+ GroupToolPolicyConfig,
22
+ OpenClawConfig,
23
+ } from "./channel-api.js";
24
+ import {
25
+ DEFAULT_ACCOUNT_ID,
26
+ chunkTextForOutbound,
27
+ isDangerousNameMatchingEnabled,
28
+ isNumericTargetId,
29
+ normalizeAccountId,
30
+ sendPayloadWithChunkedTextAndMedia,
31
+ } from "./channel-api.js";
32
+ import { buildZalouserGroupCandidates, findZalouserGroupEntry } from "./group-policy.js";
33
+ import { resolveZalouserReactionMessageIds } from "./message-sid.js";
34
+ import { writeQrDataUrlToTempFile } from "./qr-temp-file.js";
35
+ import { getZalouserRuntime } from "./runtime.js";
36
+ import {
37
+ normalizeZalouserTarget,
38
+ parseZalouserOutboundTarget,
39
+ resolveZalouserOutboundSessionRoute,
40
+ } from "./session-route.js";
41
+
42
+ const loadZalouserChannelRuntime = createLazyRuntimeModule(() => import("./channel.runtime.js"));
43
+
44
+ const ZALOUSER_TEXT_CHUNK_LIMIT = 2000;
45
+
46
+ export function resolveZalouserQrProfile(accountId?: string | null): string {
47
+ const normalized = normalizeAccountId(accountId);
48
+ if (!normalized || normalized === DEFAULT_ACCOUNT_ID) {
49
+ return process.env.ZALOUSER_PROFILE?.trim() || process.env.ZCA_PROFILE?.trim() || "default";
50
+ }
51
+ return normalized;
52
+ }
53
+
54
+ function resolveZalouserOutboundChunkMode(cfg: OpenClawConfig, accountId?: string) {
55
+ return getZalouserRuntime().channel.text.resolveChunkMode(cfg, "zalouser", accountId);
56
+ }
57
+
58
+ function resolveZalouserOutboundTextChunkLimit(cfg: OpenClawConfig, accountId?: string) {
59
+ return getZalouserRuntime().channel.text.resolveTextChunkLimit(cfg, "zalouser", accountId, {
60
+ fallbackLimit: ZALOUSER_TEXT_CHUNK_LIMIT,
61
+ });
62
+ }
63
+
64
+ function resolveZalouserGroupPolicyEntry(params: ChannelGroupContext) {
65
+ const account = resolveZalouserAccountSync({
66
+ cfg: params.cfg,
67
+ accountId: params.accountId ?? undefined,
68
+ });
69
+ const groups = account.config.groups ?? {};
70
+ return findZalouserGroupEntry(
71
+ groups,
72
+ buildZalouserGroupCandidates({
73
+ groupId: params.groupId,
74
+ groupChannel: params.groupChannel,
75
+ includeWildcard: true,
76
+ allowNameMatching: isDangerousNameMatchingEnabled(account.config),
77
+ }),
78
+ );
79
+ }
80
+
81
+ function resolveZalouserGroupToolPolicy(
82
+ params: ChannelGroupContext,
83
+ ): GroupToolPolicyConfig | undefined {
84
+ return resolveZalouserGroupPolicyEntry(params)?.tools;
85
+ }
86
+
87
+ function resolveZalouserRequireMention(params: ChannelGroupContext): boolean {
88
+ const entry = resolveZalouserGroupPolicyEntry(params);
89
+ if (typeof entry?.requireMention === "boolean") {
90
+ return entry.requireMention;
91
+ }
92
+ return true;
93
+ }
94
+
95
+ const zalouserRawSendResultAdapter = createRawChannelSendResultAdapter({
96
+ channel: "zalouser",
97
+ sendText: async ({ to, text, accountId, cfg }) => {
98
+ const { sendMessageZalouser } = await loadZalouserChannelRuntime();
99
+ const account = resolveZalouserAccountSync({ cfg: cfg, accountId });
100
+ const target = parseZalouserOutboundTarget(to);
101
+ return await sendMessageZalouser(target.threadId, text, {
102
+ profile: account.profile,
103
+ isGroup: target.isGroup,
104
+ textMode: "markdown",
105
+ textChunkMode: resolveZalouserOutboundChunkMode(cfg, account.accountId),
106
+ textChunkLimit: resolveZalouserOutboundTextChunkLimit(cfg, account.accountId),
107
+ });
108
+ },
109
+ sendMedia: async ({ to, text, mediaUrl, accountId, cfg, mediaLocalRoots, mediaReadFile }) => {
110
+ const { sendMessageZalouser } = await loadZalouserChannelRuntime();
111
+ const account = resolveZalouserAccountSync({ cfg: cfg, accountId });
112
+ const target = parseZalouserOutboundTarget(to);
113
+ return await sendMessageZalouser(target.threadId, text, {
114
+ profile: account.profile,
115
+ isGroup: target.isGroup,
116
+ mediaUrl,
117
+ mediaLocalRoots,
118
+ mediaReadFile,
119
+ textMode: "markdown",
120
+ textChunkMode: resolveZalouserOutboundChunkMode(cfg, account.accountId),
121
+ textChunkLimit: resolveZalouserOutboundTextChunkLimit(cfg, account.accountId),
122
+ });
123
+ },
124
+ });
125
+
126
+ const resolveZalouserDmPolicy = createScopedDmSecurityResolver<ResolvedZalouserAccount>({
127
+ channelKey: "zalouser",
128
+ resolvePolicy: (account) => account.config.dmPolicy,
129
+ resolveAllowFrom: (account) => account.config.allowFrom,
130
+ policyPathSuffix: "dmPolicy",
131
+ normalizeEntry: (raw) => raw.trim().replace(/^(zalouser|zlu):/i, ""),
132
+ });
133
+
134
+ export const zalouserGroupsAdapter = {
135
+ resolveRequireMention: resolveZalouserRequireMention,
136
+ resolveToolPolicy: resolveZalouserGroupToolPolicy,
137
+ };
138
+
139
+ export const zalouserMessageActions: ChannelMessageActionAdapter = {
140
+ describeMessageTool: ({ cfg, accountId }) => {
141
+ const accounts = accountId
142
+ ? [resolveZalouserAccountSync({ cfg, accountId })].filter((account) => account.enabled)
143
+ : listZalouserAccountIds(cfg)
144
+ .map((resolvedAccountId) =>
145
+ resolveZalouserAccountSync({ cfg, accountId: resolvedAccountId }),
146
+ )
147
+ .filter((account) => account.enabled);
148
+ if (accounts.length === 0) {
149
+ return null;
150
+ }
151
+ return { actions: ["react"] };
152
+ },
153
+ supportsAction: ({ action }) => action === "react",
154
+ handleAction: async ({ action, params, cfg, accountId, toolContext }) => {
155
+ if (action !== "react") {
156
+ throw new Error(`Zalouser action ${action} not supported`);
157
+ }
158
+ const { sendReactionZalouser } = await loadZalouserChannelRuntime();
159
+ const account = resolveZalouserAccountSync({ cfg, accountId });
160
+ const threadId =
161
+ (typeof params.threadId === "string" ? params.threadId.trim() : "") ||
162
+ (typeof params.to === "string" ? params.to.trim() : "") ||
163
+ (typeof params.chatId === "string" ? params.chatId.trim() : "") ||
164
+ (toolContext?.currentChannelId?.trim() ?? "");
165
+ if (!threadId) {
166
+ throw new Error("Zalouser react requires threadId (or to/chatId).");
167
+ }
168
+ const emoji = typeof params.emoji === "string" ? params.emoji.trim() : "";
169
+ if (!emoji) {
170
+ throw new Error("Zalouser react requires emoji.");
171
+ }
172
+ const ids = resolveZalouserReactionMessageIds({
173
+ messageId: typeof params.messageId === "string" ? params.messageId : undefined,
174
+ cliMsgId: typeof params.cliMsgId === "string" ? params.cliMsgId : undefined,
175
+ currentMessageId: toolContext?.currentMessageId,
176
+ });
177
+ if (!ids) {
178
+ throw new Error(
179
+ "Zalouser react requires messageId + cliMsgId (or a current message context id).",
180
+ );
181
+ }
182
+ const result = await sendReactionZalouser({
183
+ profile: account.profile,
184
+ threadId,
185
+ isGroup: params.isGroup === true,
186
+ msgId: ids.msgId,
187
+ cliMsgId: ids.cliMsgId,
188
+ emoji,
189
+ remove: params.remove === true,
190
+ });
191
+ if (!result.ok) {
192
+ throw new Error(result.error || "Failed to react on Zalo message");
193
+ }
194
+ return {
195
+ content: [
196
+ {
197
+ type: "text" as const,
198
+ text:
199
+ params.remove === true
200
+ ? `Removed reaction ${emoji} from ${ids.msgId}`
201
+ : `Reacted ${emoji} on ${ids.msgId}`,
202
+ },
203
+ ],
204
+ details: {
205
+ messageId: ids.msgId,
206
+ cliMsgId: ids.cliMsgId,
207
+ threadId,
208
+ },
209
+ };
210
+ },
211
+ };
212
+
213
+ export const zalouserResolverAdapter = {
214
+ resolveTargets: async ({
215
+ cfg,
216
+ accountId,
217
+ inputs,
218
+ kind,
219
+ runtime,
220
+ }: {
221
+ cfg: OpenClawConfig;
222
+ accountId?: string | null;
223
+ inputs: string[];
224
+ kind: "user" | "group";
225
+ runtime: RuntimeEnv;
226
+ }) => {
227
+ const results = [];
228
+ for (const input of inputs) {
229
+ const trimmed = input.trim();
230
+ if (!trimmed) {
231
+ results.push({ input, resolved: false, note: "empty input" });
232
+ continue;
233
+ }
234
+ if (/^\d+$/.test(trimmed)) {
235
+ results.push({ input, resolved: true, id: trimmed });
236
+ continue;
237
+ }
238
+ try {
239
+ const runtimeModule = await loadZalouserChannelRuntime();
240
+ const account = resolveZalouserAccountSync({
241
+ cfg: cfg,
242
+ accountId: accountId ?? resolveDefaultZalouserAccountId(cfg),
243
+ });
244
+ if (kind === "user") {
245
+ const friends = await runtimeModule.listZaloFriendsMatching(account.profile, trimmed);
246
+ const best = friends[0];
247
+ results.push({
248
+ input,
249
+ resolved: Boolean(best?.userId),
250
+ id: best?.userId,
251
+ name: best?.displayName,
252
+ note: friends.length > 1 ? "multiple matches; chose first" : undefined,
253
+ });
254
+ } else {
255
+ const groups = await runtimeModule.listZaloGroupsMatching(account.profile, trimmed);
256
+ const best =
257
+ groups.find(
258
+ (group) =>
259
+ normalizeLowercaseStringOrEmpty(group.name) ===
260
+ normalizeLowercaseStringOrEmpty(trimmed),
261
+ ) ?? groups[0];
262
+ results.push({
263
+ input,
264
+ resolved: Boolean(best?.groupId),
265
+ id: best?.groupId,
266
+ name: best?.name,
267
+ note: groups.length > 1 ? "multiple matches; chose first" : undefined,
268
+ });
269
+ }
270
+ } catch (err) {
271
+ runtime.error?.(`zalouser resolve failed: ${String(err)}`);
272
+ results.push({ input, resolved: false, note: "lookup failed" });
273
+ }
274
+ }
275
+ return results;
276
+ },
277
+ };
278
+
279
+ export const zalouserAuthAdapter = {
280
+ login: async ({
281
+ cfg,
282
+ accountId,
283
+ runtime,
284
+ }: {
285
+ cfg: OpenClawConfig;
286
+ accountId?: string | null;
287
+ runtime: RuntimeEnv;
288
+ }) => {
289
+ const { startZaloQrLogin, waitForZaloQrLogin } = await loadZalouserChannelRuntime();
290
+ const account = resolveZalouserAccountSync({
291
+ cfg: cfg,
292
+ accountId: accountId ?? resolveDefaultZalouserAccountId(cfg),
293
+ });
294
+
295
+ runtime.log(
296
+ `Generating QR login for Zalo Personal (account: ${account.accountId}, profile: ${account.profile})...`,
297
+ );
298
+
299
+ const started = await startZaloQrLogin({
300
+ profile: account.profile,
301
+ timeoutMs: 35_000,
302
+ });
303
+ if (!started.qrDataUrl) {
304
+ throw new Error(started.message || "Failed to start QR login");
305
+ }
306
+
307
+ const qrPath = await writeQrDataUrlToTempFile(started.qrDataUrl, account.profile);
308
+ if (qrPath) {
309
+ runtime.log(`Scan QR image: ${qrPath}`);
310
+ } else {
311
+ runtime.log("QR generated but could not be written to a temp file.");
312
+ }
313
+
314
+ const waited = await waitForZaloQrLogin({ profile: account.profile, timeoutMs: 180_000 });
315
+ if (!waited.connected) {
316
+ throw new Error(waited.message || "Zalouser login failed");
317
+ }
318
+
319
+ runtime.log(waited.message);
320
+ },
321
+ };
322
+
323
+ export const zalouserSecurityAdapter = {
324
+ resolveDmPolicy: resolveZalouserDmPolicy,
325
+ collectAuditFindings: async (params: {
326
+ accountId?: string | null;
327
+ account: ResolvedZalouserAccount;
328
+ orderedAccountIds: string[];
329
+ hasExplicitAccountPath: boolean;
330
+ }) => (await loadZalouserChannelRuntime()).collectZalouserSecurityAuditFindings(params),
331
+ };
332
+
333
+ export const zalouserThreadingAdapter = {
334
+ resolveReplyToMode: createStaticReplyToModeResolver("off"),
335
+ };
336
+
337
+ export const zalouserPairingTextAdapter = {
338
+ idLabel: "zalouserUserId",
339
+ message: "Your pairing request has been approved.",
340
+ normalizeAllowEntry: createPairingPrefixStripper(/^(zalouser|zlu):/i),
341
+ notify: async ({ cfg, id, message }: { cfg: OpenClawConfig; id: string; message: string }) => {
342
+ const { sendMessageZalouser } = await loadZalouserChannelRuntime();
343
+ const account = resolveZalouserAccountSync({ cfg: cfg });
344
+ const authenticated = await checkZcaAuthenticated(account.profile);
345
+ if (!authenticated) {
346
+ throw new Error("Zalouser not authenticated");
347
+ }
348
+ await sendMessageZalouser(id, message, {
349
+ profile: account.profile,
350
+ });
351
+ },
352
+ };
353
+
354
+ export const zalouserOutboundAdapter = {
355
+ deliveryMode: "direct" as const,
356
+ chunker: chunkTextForOutbound,
357
+ chunkerMode: "markdown" as const,
358
+ sendPayload: async (
359
+ ctx: { payload: object } & Parameters<
360
+ NonNullable<typeof zalouserRawSendResultAdapter.sendText>
361
+ >[0],
362
+ ) =>
363
+ await sendPayloadWithChunkedTextAndMedia({
364
+ ctx,
365
+ sendText: (nextCtx) => zalouserRawSendResultAdapter.sendText!(nextCtx),
366
+ sendMedia: (nextCtx) => zalouserRawSendResultAdapter.sendMedia!(nextCtx),
367
+ emptyResult: createEmptyChannelResult("zalouser"),
368
+ }),
369
+ ...zalouserRawSendResultAdapter,
370
+ };
371
+
372
+ export const zalouserMessagingAdapter = {
373
+ normalizeTarget: (raw: string) => normalizeZalouserTarget(raw),
374
+ resolveOutboundSessionRoute: (
375
+ params: Parameters<typeof resolveZalouserOutboundSessionRoute>[0],
376
+ ) => resolveZalouserOutboundSessionRoute(params),
377
+ targetResolver: {
378
+ looksLikeId: (raw: string) => {
379
+ const normalized = normalizeZalouserTarget(raw);
380
+ if (!normalized) {
381
+ return false;
382
+ }
383
+ if (/^group:[^\s]+$/i.test(normalized) || /^user:[^\s]+$/i.test(normalized)) {
384
+ return true;
385
+ }
386
+ return isNumericTargetId(normalized);
387
+ },
388
+ hint: "<user:id|group:id>",
389
+ },
390
+ };
@@ -1,72 +1,59 @@
1
- import type { RuntimeEnv } from "openclaw/plugin-sdk/zalouser";
2
- import { describe, expect, it, vi } from "vitest";
3
-
4
- const listZaloGroupMembersMock = vi.hoisted(() => vi.fn(async () => []));
5
-
6
- vi.mock("./zalo-js.js", async (importOriginal) => {
7
- const actual = (await importOriginal()) as Record<string, unknown>;
8
- return {
9
- ...actual,
10
- listZaloGroupMembers: listZaloGroupMembersMock,
11
- };
12
- });
13
-
14
- vi.mock("./accounts.js", async (importOriginal) => {
15
- const actual = (await importOriginal()) as Record<string, unknown>;
16
- return {
17
- ...actual,
18
- resolveZalouserAccountSync: () => ({
19
- accountId: "default",
20
- profile: "default",
21
- name: "test",
22
- enabled: true,
23
- authenticated: true,
24
- config: {},
25
- }),
26
- };
27
- });
28
-
29
- import { zalouserPlugin } from "./channel.js";
30
-
31
- const runtimeStub: RuntimeEnv = {
32
- log: vi.fn(),
33
- error: vi.fn(),
34
- exit: ((code: number): never => {
35
- throw new Error(`exit ${code}`);
36
- }) as RuntimeEnv["exit"],
37
- };
1
+ import { beforeEach, describe, expect, it } from "vitest";
2
+ import "./accounts.test-mocks.js";
3
+ import { listZalouserDirectoryGroupMembers } from "./directory.js";
4
+ import "./zalo-js.test-mocks.js";
5
+ import { listZaloGroupMembersMock } from "./zalo-js.test-mocks.js";
38
6
 
39
7
  describe("zalouser directory group members", () => {
40
- it("accepts prefixed group ids from directory groups list output", async () => {
41
- await zalouserPlugin.directory!.listGroupMembers!({
42
- cfg: {},
43
- accountId: "default",
44
- groupId: "group:1471383327500481391",
45
- runtime: runtimeStub,
46
- });
8
+ beforeEach(() => {
9
+ listZaloGroupMembersMock.mockClear();
10
+ });
47
11
 
48
- expect(listZaloGroupMembersMock).toHaveBeenCalledWith("default", "1471383327500481391");
12
+ it("accepts prefixed group ids from directory groups list output", async () => {
13
+ await listZalouserDirectoryGroupMembers(
14
+ {
15
+ cfg: {},
16
+ accountId: "default",
17
+ groupId: "group:1471383327500481391",
18
+ },
19
+ {
20
+ listZaloGroupMembers: async (profile, groupId) =>
21
+ await listZaloGroupMembersMock(profile, groupId),
22
+ },
23
+ );
24
+
25
+ expect(listZaloGroupMembersMock).toHaveBeenLastCalledWith("default", "1471383327500481391");
49
26
  });
50
27
 
51
28
  it("keeps backward compatibility for raw group ids", async () => {
52
- await zalouserPlugin.directory!.listGroupMembers!({
53
- cfg: {},
54
- accountId: "default",
55
- groupId: "1471383327500481391",
56
- runtime: runtimeStub,
57
- });
58
-
59
- expect(listZaloGroupMembersMock).toHaveBeenCalledWith("default", "1471383327500481391");
29
+ await listZalouserDirectoryGroupMembers(
30
+ {
31
+ cfg: {},
32
+ accountId: "default",
33
+ groupId: "1471383327500481391",
34
+ },
35
+ {
36
+ listZaloGroupMembers: async (profile, groupId) =>
37
+ await listZaloGroupMembersMock(profile, groupId),
38
+ },
39
+ );
40
+
41
+ expect(listZaloGroupMembersMock).toHaveBeenLastCalledWith("default", "1471383327500481391");
60
42
  });
61
43
 
62
44
  it("accepts provider-native g- group ids without stripping the prefix", async () => {
63
- await zalouserPlugin.directory!.listGroupMembers!({
64
- cfg: {},
65
- accountId: "default",
66
- groupId: "g-1471383327500481391",
67
- runtime: runtimeStub,
68
- });
69
-
70
- expect(listZaloGroupMembersMock).toHaveBeenCalledWith("default", "g-1471383327500481391");
45
+ await listZalouserDirectoryGroupMembers(
46
+ {
47
+ cfg: {},
48
+ accountId: "default",
49
+ groupId: "g-1471383327500481391",
50
+ },
51
+ {
52
+ listZaloGroupMembers: async (profile, groupId) =>
53
+ await listZaloGroupMembersMock(profile, groupId),
54
+ },
55
+ );
56
+
57
+ expect(listZaloGroupMembersMock).toHaveBeenLastCalledWith("default", "g-1471383327500481391");
71
58
  });
72
59
  });
@@ -0,0 +1,12 @@
1
+ export { probeZalouser } from "./probe.js";
2
+ export { collectZalouserSecurityAuditFindings } from "./security-audit.js";
3
+ export { sendMessageZalouser, sendReactionZalouser } from "./send.js";
4
+ export {
5
+ listZaloFriendsMatching,
6
+ listZaloGroupMembers,
7
+ listZaloGroupsMatching,
8
+ logoutZaloProfile,
9
+ startZaloQrLogin,
10
+ waitForZaloQrLogin,
11
+ getZaloUserInfo,
12
+ } from "./zalo-js.js";