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