@rune-kit/rune 2.1.1 → 2.2.1

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 (157) hide show
  1. package/README.md +40 -34
  2. package/compiler/__tests__/pack-split.test.js +145 -0
  3. package/compiler/adapters/antigravity.js +1 -1
  4. package/compiler/adapters/codex.js +77 -0
  5. package/compiler/adapters/cursor.js +1 -1
  6. package/compiler/adapters/generic.js +1 -1
  7. package/compiler/adapters/index.js +4 -0
  8. package/compiler/adapters/opencode.js +86 -0
  9. package/compiler/adapters/windsurf.js +1 -1
  10. package/compiler/bin/rune.js +10 -7
  11. package/compiler/doctor.js +42 -0
  12. package/compiler/emitter.js +64 -10
  13. package/compiler/parser.js +42 -3
  14. package/compiler/transformer.js +10 -6
  15. package/compiler/transforms/branding.js +1 -1
  16. package/compiler/transforms/compliance.js +40 -0
  17. package/extensions/ai-ml/PACK.md +38 -474
  18. package/extensions/ai-ml/skills/ai-agents.md +172 -0
  19. package/extensions/ai-ml/skills/code-sandbox.md +187 -0
  20. package/extensions/ai-ml/skills/deep-research.md +146 -0
  21. package/extensions/ai-ml/skills/embedding-search.md +66 -0
  22. package/extensions/ai-ml/skills/fine-tuning-guide.md +74 -0
  23. package/extensions/ai-ml/skills/llm-architect.md +125 -0
  24. package/extensions/ai-ml/skills/llm-integration.md +64 -0
  25. package/extensions/ai-ml/skills/prompt-patterns.md +72 -0
  26. package/extensions/ai-ml/skills/rag-patterns.md +66 -0
  27. package/extensions/ai-ml/skills/web-extraction.md +114 -0
  28. package/extensions/analytics/PACK.md +19 -484
  29. package/extensions/analytics/skills/ab-testing.md +72 -0
  30. package/extensions/analytics/skills/dashboard-patterns.md +83 -0
  31. package/extensions/analytics/skills/data-validation.md +68 -0
  32. package/extensions/analytics/skills/funnel-analysis.md +81 -0
  33. package/extensions/analytics/skills/sql-patterns.md +57 -0
  34. package/extensions/analytics/skills/statistical-analysis.md +79 -0
  35. package/extensions/analytics/skills/tracking-setup.md +71 -0
  36. package/extensions/backend/PACK.md +44 -618
  37. package/extensions/backend/skills/api-patterns.md +84 -0
  38. package/extensions/backend/skills/async-pipeline.md +193 -0
  39. package/extensions/backend/skills/auth-patterns.md +97 -0
  40. package/extensions/backend/skills/background-jobs.md +133 -0
  41. package/extensions/backend/skills/caching-patterns.md +108 -0
  42. package/extensions/backend/skills/cli-generation.md +133 -0
  43. package/extensions/backend/skills/database-patterns.md +87 -0
  44. package/extensions/backend/skills/middleware-patterns.md +104 -0
  45. package/extensions/chrome-ext/PACK.md +19 -921
  46. package/extensions/chrome-ext/skills/cws-preflight.md +143 -0
  47. package/extensions/chrome-ext/skills/cws-publish.md +104 -0
  48. package/extensions/chrome-ext/skills/ext-ai-integration.md +251 -0
  49. package/extensions/chrome-ext/skills/ext-messaging.md +139 -0
  50. package/extensions/chrome-ext/skills/ext-storage.md +133 -0
  51. package/extensions/chrome-ext/skills/mv3-scaffold.md +164 -0
  52. package/extensions/content/PACK.md +43 -335
  53. package/extensions/content/skills/blog-patterns.md +88 -0
  54. package/extensions/content/skills/cms-integration.md +131 -0
  55. package/extensions/content/skills/content-scoring.md +107 -0
  56. package/extensions/content/skills/i18n.md +83 -0
  57. package/extensions/content/skills/mdx-authoring.md +137 -0
  58. package/extensions/content/skills/reference.md +1014 -0
  59. package/extensions/content/skills/seo-patterns.md +67 -0
  60. package/extensions/content/skills/video-repurpose.md +153 -0
  61. package/extensions/devops/PACK.md +38 -457
  62. package/extensions/devops/skills/chaos-testing.md +67 -0
  63. package/extensions/devops/skills/ci-cd.md +75 -0
  64. package/extensions/devops/skills/docker.md +58 -0
  65. package/extensions/devops/skills/edge-serverless.md +163 -0
  66. package/extensions/devops/skills/infra-as-code.md +158 -0
  67. package/extensions/devops/skills/kubernetes.md +110 -0
  68. package/extensions/devops/skills/monitoring.md +57 -0
  69. package/extensions/devops/skills/server-setup.md +64 -0
  70. package/extensions/devops/skills/ssl-domain.md +42 -0
  71. package/extensions/ecommerce/PACK.md +62 -226
  72. package/extensions/ecommerce/skills/cart-system.md +79 -0
  73. package/extensions/ecommerce/skills/inventory-mgmt.md +102 -0
  74. package/extensions/ecommerce/skills/order-management.md +126 -0
  75. package/extensions/ecommerce/skills/payment-integration.md +472 -0
  76. package/extensions/ecommerce/skills/shopify-dev.md +69 -0
  77. package/extensions/ecommerce/skills/subscription-billing.md +93 -0
  78. package/extensions/ecommerce/skills/tax-compliance.md +117 -0
  79. package/extensions/gamedev/PACK.md +66 -317
  80. package/extensions/gamedev/skills/asset-pipeline.md +74 -0
  81. package/extensions/gamedev/skills/audio-system.md +129 -0
  82. package/extensions/gamedev/skills/camera-system.md +87 -0
  83. package/extensions/gamedev/skills/ecs.md +98 -0
  84. package/extensions/gamedev/skills/game-loops.md +72 -0
  85. package/extensions/gamedev/skills/input-system.md +199 -0
  86. package/extensions/gamedev/skills/multiplayer.md +180 -0
  87. package/extensions/gamedev/skills/particles.md +105 -0
  88. package/extensions/gamedev/skills/physics-engine.md +89 -0
  89. package/extensions/gamedev/skills/scene-management.md +146 -0
  90. package/extensions/gamedev/skills/threejs-patterns.md +90 -0
  91. package/extensions/gamedev/skills/webgl.md +71 -0
  92. package/extensions/mobile/PACK.md +56 -223
  93. package/extensions/mobile/skills/app-store-connect.md +152 -0
  94. package/extensions/mobile/skills/app-store-prep.md +66 -0
  95. package/extensions/mobile/skills/deep-linking.md +109 -0
  96. package/extensions/mobile/skills/flutter.md +60 -0
  97. package/extensions/mobile/skills/ios-build-pipeline.md +142 -0
  98. package/extensions/mobile/skills/native-bridge.md +66 -0
  99. package/extensions/mobile/skills/ota-updates.md +97 -0
  100. package/extensions/mobile/skills/push-notifications.md +111 -0
  101. package/extensions/mobile/skills/react-native.md +82 -0
  102. package/extensions/saas/PACK.md +26 -720
  103. package/extensions/saas/skills/billing-integration.md +121 -0
  104. package/extensions/saas/skills/feature-flags.md +130 -0
  105. package/extensions/saas/skills/multi-tenant.md +103 -0
  106. package/extensions/saas/skills/onboarding-flow.md +139 -0
  107. package/extensions/saas/skills/subscription-flow.md +95 -0
  108. package/extensions/saas/skills/team-management.md +144 -0
  109. package/extensions/security/PACK.md +10 -448
  110. package/extensions/security/skills/api-security.md +140 -0
  111. package/extensions/security/skills/compliance.md +68 -0
  112. package/extensions/security/skills/owasp-audit.md +64 -0
  113. package/extensions/security/skills/pentest-patterns.md +77 -0
  114. package/extensions/security/skills/secret-mgmt.md +65 -0
  115. package/extensions/security/skills/supply-chain.md +65 -0
  116. package/extensions/trading/PACK.md +18 -535
  117. package/extensions/trading/skills/chart-components.md +55 -0
  118. package/extensions/trading/skills/experiment-loop.md +125 -0
  119. package/extensions/trading/skills/fintech-patterns.md +47 -0
  120. package/extensions/trading/skills/indicator-library.md +58 -0
  121. package/extensions/trading/skills/quant-analysis.md +111 -0
  122. package/extensions/trading/skills/realtime-data.md +58 -0
  123. package/extensions/trading/skills/trade-logic.md +104 -0
  124. package/extensions/ui/PACK.md +34 -853
  125. package/extensions/ui/skills/a11y-audit.md +91 -0
  126. package/extensions/ui/skills/animation-patterns.md +106 -0
  127. package/extensions/ui/skills/component-patterns.md +75 -0
  128. package/extensions/ui/skills/design-decision.md +98 -0
  129. package/extensions/ui/skills/design-system.md +68 -0
  130. package/extensions/ui/skills/landing-patterns.md +155 -0
  131. package/extensions/ui/skills/palette-picker.md +162 -0
  132. package/extensions/ui/skills/react-health.md +90 -0
  133. package/extensions/ui/skills/type-system.md +125 -0
  134. package/extensions/ui/skills/web-vitals.md +153 -0
  135. package/extensions/zalo/PACK.md +117 -0
  136. package/extensions/zalo/skills/zalo-oa-mcp.md +317 -0
  137. package/extensions/zalo/skills/zalo-oa-messaging.md +429 -0
  138. package/extensions/zalo/skills/zalo-oa-setup.md +236 -0
  139. package/extensions/zalo/skills/zalo-oa-webhook.md +189 -0
  140. package/extensions/zalo/skills/zalo-personal-messaging.md +194 -0
  141. package/extensions/zalo/skills/zalo-personal-setup.md +153 -0
  142. package/extensions/zalo/skills/zalo-rate-guard.md +219 -0
  143. package/package.json +5 -2
  144. package/skills/brainstorm/SKILL.md +63 -1
  145. package/skills/cook/SKILL.md +89 -6
  146. package/skills/debug/SKILL.md +5 -0
  147. package/skills/fix/SKILL.md +5 -0
  148. package/skills/mcp-builder/SKILL.md +48 -1
  149. package/skills/neural-memory/SKILL.md +362 -0
  150. package/skills/plan/SKILL.md +3 -0
  151. package/skills/rescue/SKILL.md +5 -0
  152. package/skills/review/SKILL.md +44 -5
  153. package/skills/review-intake/SKILL.md +17 -1
  154. package/skills/skill-router/SKILL.md +106 -8
  155. package/skills/team/SKILL.md +24 -1
  156. package/skills/test/SKILL.md +18 -0
  157. package/skills/verification/SKILL.md +40 -1
@@ -0,0 +1,429 @@
1
+ ---
2
+ name: zalo-oa-messaging
3
+ pack: "@rune/zalo"
4
+ description: All 8 OA message types (text, image, file, sticker, list, template, transaction, promotion), follower management, and broadcast with demographic targeting.
5
+ model: sonnet
6
+ tools: "Read, Glob, Grep, Bash, Write, Edit"
7
+ ---
8
+
9
+ # zalo-oa-messaging
10
+
11
+ Send any of the 8 Zalo OA message types, manage followers, and run broadcast campaigns via the v3 Official Account API.
12
+
13
+ ## Base Config
14
+
15
+ ```
16
+ Base URL : https://openapi.zalo.me/v3.0/oa
17
+ Upload : https://openapi.zalo.me/v2.0/oa (intentional version mismatch)
18
+ Auth : Authorization: Bearer {oa_access_token}
19
+ Content : Content-Type: application/json
20
+ Endpoint : POST /message/cs (all 8 CS message types)
21
+ ```
22
+
23
+ ## Step 1 — Identify the Message Type
24
+
25
+ | # | Type | Use Case | Constraint |
26
+ |---|------|----------|------------|
27
+ | 1 | Text | Simple reply, notification | 2000 char limit |
28
+ | 2 | Image | Product photo, banner | attachment_id from upload |
29
+ | 3 | File | PDF, invoice, document | attachment_id from upload |
30
+ | 4 | Sticker | Friendly interaction | sticker_id from catalog |
31
+ | 5 | List | Menu, product listing | max 10 items |
32
+ | 6 | Template | CTA with buttons | max 5 buttons |
33
+ | 7 | Transaction | Order/shipping update | pre-approved template required |
34
+ | 8 | Promotion | Marketing campaign | approved template + quota |
35
+
36
+ **All CS messages**: only sendable within 7 days of user's last interaction with the OA.
37
+
38
+ ---
39
+
40
+ ## Step 2 — Send the Right Payload
41
+
42
+ ### Type 1 — Text Message
43
+
44
+ ```http
45
+ POST https://openapi.zalo.me/v3.0/oa/message/cs
46
+ Authorization: Bearer {oa_access_token}
47
+
48
+ {
49
+ "recipient": { "user_id": "4337842264521611405" },
50
+ "message": { "text": "Xin chào! Chúng tôi có thể giúp gì cho bạn?" }
51
+ }
52
+ ```
53
+
54
+ Response (success):
55
+ ```json
56
+ { "error": 0, "message": "Success", "data": { "message_id": "oaMsgId.567890" } }
57
+ ```
58
+
59
+ ---
60
+
61
+ ### Type 2 — Image Message
62
+
63
+ Upload first (v2.0 endpoint), then send:
64
+
65
+ ```http
66
+ POST https://openapi.zalo.me/v2.0/oa/upload/image
67
+ Authorization: Bearer {oa_access_token}
68
+ Content-Type: multipart/form-data
69
+
70
+ file=@banner.jpg (max 1MB)
71
+ ```
72
+
73
+ ```json
74
+ { "error": 0, "data": { "attachment_id": "f8d5a7e1-2b3c-4d5e-8f9a-1b2c3d4e5f6a" } }
75
+ ```
76
+
77
+ Then send:
78
+
79
+ ```json
80
+ {
81
+ "recipient": { "user_id": "4337842264521611405" },
82
+ "message": {
83
+ "attachment": {
84
+ "type": "template",
85
+ "payload": {
86
+ "template_type": "media",
87
+ "elements": [{
88
+ "media_type": "image",
89
+ "attachment_id": "f8d5a7e1-2b3c-4d5e-8f9a-1b2c3d4e5f6a"
90
+ }]
91
+ }
92
+ }
93
+ }
94
+ }
95
+ ```
96
+
97
+ ---
98
+
99
+ ### Type 3 — File Message
100
+
101
+ ```http
102
+ POST https://openapi.zalo.me/v2.0/oa/upload/file
103
+ Authorization: Bearer {oa_access_token}
104
+ Content-Type: multipart/form-data
105
+
106
+ file=@invoice.pdf (max 5MB)
107
+ ```
108
+
109
+ ```json
110
+ { "error": 0, "data": { "attachment_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890" } }
111
+ ```
112
+
113
+ Send payload same shape as image but `"media_type": "file"`.
114
+
115
+ ---
116
+
117
+ ### Type 4 — Sticker Message
118
+
119
+ ```json
120
+ {
121
+ "recipient": { "user_id": "4337842264521611405" },
122
+ "message": {
123
+ "attachment": {
124
+ "type": "template",
125
+ "payload": {
126
+ "template_type": "media",
127
+ "elements": [{ "media_type": "sticker", "attachment_id": "87521" }]
128
+ }
129
+ }
130
+ }
131
+ }
132
+ ```
133
+
134
+ Sticker IDs: fetch from Zalo sticker catalog. Common IDs: 87521 (thumbs up), 87522 (heart), 87523 (smile).
135
+
136
+ ---
137
+
138
+ ### Type 5 — List Message
139
+
140
+ ```json
141
+ {
142
+ "recipient": { "user_id": "4337842264521611405" },
143
+ "message": {
144
+ "attachment": {
145
+ "type": "template",
146
+ "payload": {
147
+ "template_type": "list",
148
+ "elements": [
149
+ {
150
+ "title": "Sản phẩm A",
151
+ "subtitle": "Giá: 299.000đ",
152
+ "image_url": "https://cdn.example.com/product-a.jpg",
153
+ "default_action": { "type": "oa.open.url", "url": "https://example.com/product-a" }
154
+ },
155
+ {
156
+ "title": "Sản phẩm B",
157
+ "subtitle": "Giá: 199.000đ",
158
+ "image_url": "https://cdn.example.com/product-b.jpg",
159
+ "default_action": { "type": "oa.open.url", "url": "https://example.com/product-b" }
160
+ }
161
+ ],
162
+ "buttons": [{
163
+ "title": "Xem tất cả sản phẩm",
164
+ "type": "oa.open.url",
165
+ "payload": { "url": "https://example.com/products" }
166
+ }]
167
+ }
168
+ }
169
+ }
170
+ }
171
+ ```
172
+
173
+ Limits: max 10 elements, max 5 buttons at bottom.
174
+
175
+ ---
176
+
177
+ ### Type 6 — Template Message (Button Template)
178
+
179
+ ```json
180
+ {
181
+ "recipient": { "user_id": "4337842264521611405" },
182
+ "message": {
183
+ "attachment": {
184
+ "type": "template",
185
+ "payload": {
186
+ "template_type": "button",
187
+ "text": "Chọn hành động bạn muốn thực hiện:",
188
+ "buttons": [
189
+ {
190
+ "title": "Xem đơn hàng",
191
+ "type": "oa.open.url",
192
+ "payload": { "url": "https://example.com/orders" }
193
+ },
194
+ {
195
+ "title": "Gọi hỗ trợ",
196
+ "type": "oa.open.phone",
197
+ "payload": { "phone_code": "0901234567" }
198
+ },
199
+ {
200
+ "title": "Theo dõi vận chuyển",
201
+ "type": "oa.query.show",
202
+ "payload": { "content": "TRACK_ORDER_12345" }
203
+ }
204
+ ]
205
+ }
206
+ }
207
+ }
208
+ }
209
+ ```
210
+
211
+ Button types: `oa.open.url`, `oa.open.phone`, `oa.query.show` (postback), `oa.open.sms`.
212
+
213
+ ---
214
+
215
+ ### Type 7 — Transaction Message
216
+
217
+ Requires a pre-approved template from Zalo OA portal. Cannot send arbitrary content.
218
+
219
+ ```json
220
+ {
221
+ "recipient": { "user_id": "4337842264521611405" },
222
+ "message": {
223
+ "attachment": {
224
+ "type": "template",
225
+ "payload": {
226
+ "template_type": "transaction_order",
227
+ "language": "VI",
228
+ "elements": [{
229
+ "attachment_id": "approved-template-id-from-zalo",
230
+ "type": "banner"
231
+ }],
232
+ "parameters": {
233
+ "order_id": "ORD-2026-001234",
234
+ "order_status": "Đã giao hàng",
235
+ "delivery_date": "15/03/2026",
236
+ "tracking_url": "https://example.com/track/ORD-2026-001234"
237
+ }
238
+ }
239
+ }
240
+ }
241
+ }
242
+ ```
243
+
244
+ Template must match an approved template ID. Parameter keys defined by the template.
245
+
246
+ ---
247
+
248
+ ### Type 8 — Promotion Message
249
+
250
+ Requires approved template + sufficient broadcast quota.
251
+
252
+ ```json
253
+ {
254
+ "recipient": { "user_id": "4337842264521611405" },
255
+ "message": {
256
+ "attachment": {
257
+ "type": "template",
258
+ "payload": {
259
+ "template_type": "promotion",
260
+ "language": "VI",
261
+ "elements": [{
262
+ "attachment_id": "approved-promo-banner-id",
263
+ "type": "banner"
264
+ }],
265
+ "parameters": {
266
+ "coupon_code": "SALE30",
267
+ "discount": "30%",
268
+ "expiry": "31/03/2026"
269
+ }
270
+ }
271
+ }
272
+ }
273
+ }
274
+ ```
275
+
276
+ ---
277
+
278
+ ## Step 3 — Long Text Chunking
279
+
280
+ Text limit is 2000 chars. Chunk before sending:
281
+
282
+ ```typescript
283
+ function chunkMessage(text: string, limit = 2000): string[] {
284
+ if (text.length <= limit) return [text]
285
+ const chunks: string[] = []
286
+ let remaining = text
287
+ while (remaining.length > 0) {
288
+ if (remaining.length <= limit) { chunks.push(remaining); break }
289
+ let splitAt = remaining.lastIndexOf('\n', limit)
290
+ if (splitAt === -1) splitAt = remaining.lastIndexOf(' ', limit)
291
+ if (splitAt === -1) splitAt = limit
292
+ chunks.push(remaining.slice(0, splitAt))
293
+ remaining = remaining.slice(splitAt).trimStart()
294
+ }
295
+ return chunks
296
+ }
297
+
298
+ // Send each chunk with delay to respect rate limits
299
+ for (const chunk of chunkMessage(longText)) {
300
+ await sendTextMessage(userId, chunk)
301
+ await new Promise(r => setTimeout(r, 300))
302
+ }
303
+ ```
304
+
305
+ ---
306
+
307
+ ## Step 4 — Follower Management
308
+
309
+ ### List Followers
310
+
311
+ ```http
312
+ GET https://openapi.zalo.me/v3.0/oa/user/getlist?offset=0&count=50
313
+ Authorization: Bearer {oa_access_token}
314
+ ```
315
+
316
+ ```json
317
+ {
318
+ "error": 0,
319
+ "data": {
320
+ "users": [
321
+ { "user_id": "4337842264521611405", "display_name": "Nguyen Van A", "followed_date": 1709827200 }
322
+ ],
323
+ "total": 1250,
324
+ "offset": 0,
325
+ "count": 50
326
+ }
327
+ }
328
+ ```
329
+
330
+ Paginate: increment `offset` by `count` until `offset >= total`.
331
+
332
+ ### User Profile
333
+
334
+ ```http
335
+ GET https://openapi.zalo.me/v3.0/oa/user/detail?user_id=4337842264521611405
336
+ Authorization: Bearer {oa_access_token}
337
+ ```
338
+
339
+ ```json
340
+ {
341
+ "error": 0,
342
+ "data": {
343
+ "user_id": "4337842264521611405",
344
+ "display_name": "Nguyen Van A",
345
+ "birth_date": 0,
346
+ "gender": 1,
347
+ "phone": "",
348
+ "city": "Ho Chi Minh City",
349
+ "district": "",
350
+ "tags_and_notes_info": { "tag_names": ["VIP", "Repeat-buyer"] }
351
+ }
352
+ }
353
+ ```
354
+
355
+ Note: `user_id` is OA-scoped — same person has a different `user_id` for each OA they follow.
356
+
357
+ ### Tag Management
358
+
359
+ ```http
360
+ POST https://openapi.zalo.me/v3.0/oa/tag/tagfollower
361
+ Authorization: Bearer {oa_access_token}
362
+
363
+ { "user_id": "4337842264521611405", "tag_name": "VIP" }
364
+ ```
365
+
366
+ ```http
367
+ POST https://openapi.zalo.me/v3.0/oa/tag/rmfollowerfromtag
368
+ Authorization: Bearer {oa_access_token}
369
+
370
+ { "user_id": "4337842264521611405", "tag_name": "VIP" }
371
+ ```
372
+
373
+ ---
374
+
375
+ ## Step 5 — Broadcast
376
+
377
+ ```http
378
+ POST https://openapi.zalo.me/v3.0/oa/message/promotion
379
+ Authorization: Bearer {oa_access_token}
380
+
381
+ {
382
+ "recipient": {
383
+ "target": {
384
+ "gender": 1,
385
+ "ages": ["18-25", "26-35"],
386
+ "cities": ["Ho Chi Minh City", "Ha Noi"],
387
+ "platforms": ["iOS", "Android"],
388
+ "telcos": ["Viettel", "Mobifone"]
389
+ }
390
+ },
391
+ "message": {
392
+ "attachment": {
393
+ "type": "template",
394
+ "payload": {
395
+ "template_type": "promotion",
396
+ "language": "VI",
397
+ "elements": [{ "attachment_id": "approved-promo-banner-id", "type": "banner" }],
398
+ "parameters": { "coupon_code": "SUMMER30", "discount": "30%" }
399
+ }
400
+ }
401
+ }
402
+ }
403
+ ```
404
+
405
+ Response includes estimated reach count before send is confirmed. Quota resets monthly.
406
+
407
+ ---
408
+
409
+ ## Sharp Edges
410
+
411
+ - **7-day CS window** — `error: 12` means the user hasn't interacted in 7 days. Cannot bypass. Solution: use Transaction or Promotion templates (pre-approved) which ignore the window.
412
+ - **Version mismatch is intentional** — upload endpoints stay on `v2.0`, message send is `v3.0`. Do not "fix" this.
413
+ - **OA-scoped user_id** — never assume the same physical person has the same `user_id` across different OAs. Always store per-OA.
414
+ - **Template approval lag** — Transaction/Promotion templates take 1-5 business days to approve. Plan ahead; cannot substitute with CS messages after approval delay.
415
+ - **Image 1MB / File 5MB hard limits** — compress images server-side before upload. Zalo returns `error: 201` for oversized files.
416
+ - **Broadcast quota** — based on follower count × OA verification tier. Track monthly usage; `error: 133` = quota exceeded.
417
+ - **Button limit 5** — template messages silently drop buttons beyond index 4. Always validate `buttons.length <= 5` before sending.
418
+
419
+ ## Error Codes Quick Reference
420
+
421
+ | Code | Meaning | Fix |
422
+ |------|---------|-----|
423
+ | 0 | Success | — |
424
+ | 12 | Outside 7-day CS window | Use approved template type |
425
+ | 14 | Invalid access token | Refresh token, retry |
426
+ | 107 | Invalid recipient | Verify user_id is OA-scoped and valid |
427
+ | 133 | Broadcast quota exceeded | Wait for monthly reset |
428
+ | 201 | File size exceeded | Compress/split before upload |
429
+ | 216 | Template not approved | Submit template for Zalo review |
@@ -0,0 +1,236 @@
1
+ ---
2
+ name: zalo-oa-setup
3
+ pack: "@rune/zalo"
4
+ description: "Zalo OA OAuth2 PKCE setup — app registration, dual-token management (User vs OA), appsecret_proof signing, and auto-refresh middleware."
5
+ model: sonnet
6
+ tools: "Read, Glob, Grep, Bash, Write, Edit"
7
+ ---
8
+
9
+ # zalo-oa-setup
10
+
11
+ #### Purpose
12
+
13
+ Zalo's OAuth2 system has two completely separate token hierarchies — User tokens and OA tokens — that are not interchangeable. Most developers fail because they conflate the two or skip PKCE entirely. This skill walks through app registration, implements PKCE code challenge generation, builds a token auto-refresh middleware, and secures every API call with appsecret_proof signing.
14
+
15
+ #### Workflow
16
+
17
+ **Step 1 — App registration at developers.zalo.me**
18
+
19
+ Navigate to https://developers.zalo.me → Create App → note `app_id` and `secret_key`. Under "Official Account", bind your OA to the app. Configure redirect URI (must be HTTPS in production; `http://localhost:PORT/callback` for dev). Set webhook URL if receiving events. Add `app_id` and `secret_key` to `.env` — never commit them.
20
+
21
+ ```
22
+ ZALO_APP_ID=your_app_id
23
+ ZALO_APP_SECRET=your_secret_key
24
+ ZALO_REDIRECT_URI=https://yourapp.com/auth/zalo/callback
25
+ ZALO_OA_ID=your_oa_id
26
+ ```
27
+
28
+ **Step 2 — Decide which token track you need**
29
+
30
+ | Track | Endpoint prefix | Use case |
31
+ |-------|----------------|----------|
32
+ | User OAuth2 | `oauth.zaloapp.com/v4/permission` | Log in users, read user profile |
33
+ | OA OAuth2 | `oauth.zaloapp.com/v4/oa/permission` | Send messages, manage followers, all bot operations |
34
+
35
+ Most bots only need the OA track. If you only build a chatbot, skip User OAuth2 entirely.
36
+
37
+ **Step 3 — Generate PKCE pair**
38
+
39
+ PKCE prevents auth-code interception. Store `code_verifier` in session/memory between the redirect and the callback — it must survive that round-trip.
40
+
41
+ ```typescript
42
+ import crypto from 'crypto'
43
+
44
+ export function generateCodeVerifier(): string {
45
+ // 32 random bytes → base64url = 43-char verifier (RFC 7636 compliant)
46
+ return crypto.randomBytes(32).toString('base64url')
47
+ }
48
+
49
+ export function generateCodeChallenge(verifier: string): string {
50
+ return crypto.createHash('sha256').update(verifier).digest('base64url')
51
+ }
52
+ ```
53
+
54
+ **Step 4 — Build the authorization URL**
55
+
56
+ ```typescript
57
+ import { generateCodeVerifier, generateCodeChallenge } from './pkce'
58
+
59
+ interface AuthUrlResult {
60
+ url: string
61
+ codeVerifier: string // store in session — needed for token exchange
62
+ state: string
63
+ }
64
+
65
+ export function buildOaAuthUrl(appId: string, redirectUri: string): AuthUrlResult {
66
+ const codeVerifier = generateCodeVerifier()
67
+ const codeChallenge = generateCodeChallenge(codeVerifier)
68
+ const state = crypto.randomBytes(16).toString('hex') // CSRF protection
69
+
70
+ const params = new URLSearchParams({
71
+ app_id: appId,
72
+ redirect_uri: redirectUri,
73
+ code_challenge: codeChallenge,
74
+ code_challenge_method: 'S256',
75
+ state,
76
+ })
77
+
78
+ return {
79
+ url: `https://oauth.zaloapp.com/v4/oa/permission?${params}`,
80
+ codeVerifier,
81
+ state,
82
+ }
83
+ }
84
+ ```
85
+
86
+ **Step 5 — Exchange auth code for tokens (callback handler)**
87
+
88
+ ```typescript
89
+ import { z } from 'zod'
90
+
91
+ const TokenResponseSchema = z.object({
92
+ access_token: z.string(),
93
+ refresh_token: z.string(),
94
+ expires_in: z.number(), // seconds
95
+ })
96
+
97
+ export async function exchangeOaCode(
98
+ code: string,
99
+ codeVerifier: string,
100
+ appId: string,
101
+ appSecret: string,
102
+ ): Promise<z.infer<typeof TokenResponseSchema>> {
103
+ const res = await fetch('https://oauth.zaloapp.com/v4/oa/access_token', {
104
+ method: 'POST',
105
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'secret_key': appSecret },
106
+ body: new URLSearchParams({
107
+ app_id: appId,
108
+ code,
109
+ code_verifier: codeVerifier,
110
+ grant_type: 'authorization_code',
111
+ }),
112
+ })
113
+
114
+ if (!res.ok) throw new Error(`Token exchange failed: ${res.status} ${await res.text()}`)
115
+ return TokenResponseSchema.parse(await res.json())
116
+ }
117
+ ```
118
+
119
+ **Step 6 — Token store with auto-refresh middleware**
120
+
121
+ OA access_token expires in ~24h. Never make an API call without first verifying the token is still valid. When refreshing, Zalo returns a NEW refresh_token — the old one is invalidated immediately.
122
+
123
+ ```typescript
124
+ import fs from 'fs/promises'
125
+ import path from 'path'
126
+ import os from 'os'
127
+
128
+ const CREDENTIALS_PATH = path.join(os.homedir(), '.zalo-mcp', 'credentials.json')
129
+ const REFRESH_BUFFER_MS = 5 * 60 * 1000 // refresh if <5 min remaining
130
+
131
+ export interface ZaloTokenStore {
132
+ oa_access_token: string
133
+ oa_refresh_token: string
134
+ oa_expires_at: number // Unix timestamp ms
135
+ user_access_token?: string
136
+ user_refresh_token?: string
137
+ user_expires_at?: number
138
+ }
139
+
140
+ export async function loadTokens(): Promise<ZaloTokenStore> {
141
+ const raw = await fs.readFile(CREDENTIALS_PATH, 'utf-8')
142
+ return JSON.parse(raw) as ZaloTokenStore
143
+ }
144
+
145
+ export async function saveTokens(tokens: ZaloTokenStore): Promise<void> {
146
+ await fs.mkdir(path.dirname(CREDENTIALS_PATH), { recursive: true })
147
+ await fs.writeFile(CREDENTIALS_PATH, JSON.stringify(tokens, null, 2), { mode: 0o600 })
148
+ }
149
+
150
+ async function refreshOaToken(
151
+ refreshToken: string,
152
+ appId: string,
153
+ appSecret: string,
154
+ ): Promise<{ access_token: string; refresh_token: string; expires_in: number }> {
155
+ const res = await fetch('https://oauth.zaloapp.com/v4/oa/access_token', {
156
+ method: 'POST',
157
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'secret_key': appSecret },
158
+ body: new URLSearchParams({
159
+ app_id: appId,
160
+ refresh_token: refreshToken,
161
+ grant_type: 'refresh_token',
162
+ }),
163
+ })
164
+
165
+ if (!res.ok) throw new Error(`Token refresh failed: ${res.status} ${await res.text()}`)
166
+ return res.json()
167
+ }
168
+
169
+ export async function getValidOaToken(appId: string, appSecret: string): Promise<string> {
170
+ const store = await loadTokens()
171
+ const now = Date.now()
172
+
173
+ if (store.oa_expires_at - now > REFRESH_BUFFER_MS) {
174
+ return store.oa_access_token // still fresh
175
+ }
176
+
177
+ // Token expired or expiring soon — refresh
178
+ const refreshed = await refreshOaToken(store.oa_refresh_token, appId, appSecret)
179
+ const updated: ZaloTokenStore = {
180
+ ...store,
181
+ oa_access_token: refreshed.access_token,
182
+ oa_refresh_token: refreshed.refresh_token, // rotate — old token is now dead
183
+ oa_expires_at: now + refreshed.expires_in * 1000,
184
+ }
185
+ await saveTokens(updated)
186
+ return updated.oa_access_token
187
+ }
188
+ ```
189
+
190
+ **Step 7 — appsecret_proof signing for server-side calls**
191
+
192
+ appsecret_proof is an HMAC-SHA256 of the access_token keyed with app_secret. It binds a token to your server — even if a token leaks, it cannot be replayed without the secret.
193
+
194
+ ```typescript
195
+ import crypto from 'crypto'
196
+
197
+ export function generateAppSecretProof(accessToken: string, appSecret: string): string {
198
+ return crypto.createHmac('sha256', appSecret).update(accessToken).digest('hex')
199
+ }
200
+
201
+ // Usage: attach to every OA API call
202
+ export async function oaApiCall(
203
+ endpoint: string,
204
+ body: Record<string, unknown>,
205
+ appId: string,
206
+ appSecret: string,
207
+ ): Promise<unknown> {
208
+ const accessToken = await getValidOaToken(appId, appSecret)
209
+ const proof = generateAppSecretProof(accessToken, appSecret)
210
+
211
+ const res = await fetch(`https://openapi.zalo.me/v3.0/oa/${endpoint}`, {
212
+ method: 'POST',
213
+ headers: {
214
+ 'Content-Type': 'application/json',
215
+ 'access_token': accessToken,
216
+ 'X-Appsecret-Proof': proof,
217
+ },
218
+ body: JSON.stringify(body),
219
+ })
220
+
221
+ if (!res.ok) throw new Error(`OA API ${endpoint} failed: ${res.status} ${await res.text()}`)
222
+ return res.json()
223
+ }
224
+ ```
225
+
226
+ #### Sharp Edges
227
+
228
+ | Failure | Symptom | Fix |
229
+ |---------|---------|-----|
230
+ | Using User token for OA API | `error_code: 216` or permission denied | Check token source — OA APIs require OA track token, not user track |
231
+ | Lost `code_verifier` between redirect and callback | `invalid_grant` on token exchange | Store verifier in server-side session (not cookie) before redirecting |
232
+ | Redirect URI mismatch | `redirect_uri does not match` | URI must EXACTLY match registered value — trailing slash, protocol, and port all matter |
233
+ | Not rotating refresh token | Refresh silently fails after first use | Always write the NEW `refresh_token` from refresh response back to store |
234
+ | `appsecret_proof` missing on server calls | Token accepted but flagged; future calls blocked | Add `X-Appsecret-Proof` header on ALL server-side API calls, not just some |
235
+ | `secret_key` sent from browser | Secret exposure in network tab | `secret_key` header and appsecret_proof are server-side only — never from browser JS |
236
+ | Credentials file world-readable | Token leak on shared host | `chmod 600 ~/.zalo-mcp/credentials.json` — enforced by `saveTokens` above |