@vicacha-devs/medusa-plugin-notifications 0.0.0-stage → 0.0.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 (241) hide show
  1. package/.medusa/server/src/admin/index.cjs +4215 -0
  2. package/.medusa/server/src/admin/index.js +4193 -0
  3. package/.medusa/server/src/api/admin/mpn/broadcasts/route.js +99 -0
  4. package/.medusa/server/src/api/admin/mpn/channels/route.js +109 -0
  5. package/.medusa/server/src/api/admin/mpn/logs/route.js +33 -0
  6. package/.medusa/server/src/api/admin/mpn/mappings/[id]/route.js +33 -0
  7. package/.medusa/server/src/api/admin/mpn/mappings/route.js +51 -0
  8. package/.medusa/server/src/api/admin/mpn/render-template/route.js +37 -0
  9. package/.medusa/server/src/api/admin/mpn/sandbox/route.js +36 -0
  10. package/.medusa/server/src/api/admin/mpn/send/route.js +135 -0
  11. package/.medusa/server/src/api/admin/mpn/templates/[id]/route.js +77 -0
  12. package/.medusa/server/src/api/admin/mpn/templates/route.js +71 -0
  13. package/.medusa/server/src/api/admin/plugin/route.js +4 -0
  14. package/.medusa/server/src/api/middlewares.js +28 -0
  15. package/.medusa/server/src/api/store/mpn/consent/route.js +37 -0
  16. package/.medusa/server/src/api/store/mpn/webhooks/[provider]/route.js +97 -0
  17. package/.medusa/server/src/api/store/plugin/route.js +4 -0
  18. package/.medusa/server/src/api/validators.js +118 -0
  19. package/.medusa/server/src/hooks/index.js +7 -0
  20. package/.medusa/server/src/hooks/use-mpn-channels.js +13 -0
  21. package/.medusa/server/src/hooks/use-mpn-dispatch.js +45 -0
  22. package/.medusa/server/src/hooks/use-mpn-mappings.js +21 -0
  23. package/.medusa/server/src/hooks/use-mpn-templates.js +34 -0
  24. package/.medusa/server/src/hooks/use-order-notifications-widget-state.js +79 -0
  25. package/.medusa/server/src/hooks/use-sdk-primitives.js +113 -0
  26. package/.medusa/server/src/index.js +14 -0
  27. package/.medusa/server/src/integrations/automations-action-handler.js +112 -0
  28. package/.medusa/server/src/jobs/abandoned-cart-recovery.js +123 -0
  29. package/.medusa/server/src/jobs/log-retention-and-broadcasts.js +15 -0
  30. package/.medusa/server/src/modules/notifications/i18n/index.js +65 -0
  31. package/.medusa/server/src/modules/notifications/i18n/locales/ar.js +76 -0
  32. package/.medusa/server/src/modules/notifications/i18n/locales/de.js +76 -0
  33. package/.medusa/server/src/modules/notifications/i18n/locales/en.js +76 -0
  34. package/.medusa/server/src/modules/notifications/i18n/locales/es.js +76 -0
  35. package/.medusa/server/src/modules/notifications/i18n/locales/fr.js +76 -0
  36. package/.medusa/server/src/modules/notifications/i18n/locales/it.js +76 -0
  37. package/.medusa/server/src/modules/notifications/i18n/locales/nl.js +76 -0
  38. package/.medusa/server/src/modules/notifications/i18n/locales/pl.js +76 -0
  39. package/.medusa/server/src/modules/notifications/i18n/locales/pt.js +76 -0
  40. package/.medusa/server/src/modules/notifications/i18n/locales/tr.js +76 -0
  41. package/.medusa/server/src/modules/notifications/i18n/types.js +2 -0
  42. package/.medusa/server/src/modules/notifications/index.js +9 -0
  43. package/.medusa/server/src/modules/notifications/integrations/documents-and-b2b-resolver.js +129 -0
  44. package/.medusa/server/src/modules/notifications/migrations/Migration20261010000000.js +184 -0
  45. package/.medusa/server/src/modules/notifications/models/index.js +118 -0
  46. package/.medusa/server/src/modules/notifications/renderer/block-helpers.js +36 -0
  47. package/.medusa/server/src/modules/notifications/renderer/email.js +161 -0
  48. package/.medusa/server/src/modules/notifications/renderer/index.js +240 -0
  49. package/.medusa/server/src/modules/notifications/renderer/slack.js +114 -0
  50. package/.medusa/server/src/modules/notifications/renderer/telegram.js +99 -0
  51. package/.medusa/server/src/modules/notifications/renderer/whatsapp.js +91 -0
  52. package/.medusa/server/src/modules/notifications/service-helpers/channel-config.js +45 -0
  53. package/.medusa/server/src/modules/notifications/service-helpers/consent.js +65 -0
  54. package/.medusa/server/src/modules/notifications/service-helpers/delivery-log.js +29 -0
  55. package/.medusa/server/src/modules/notifications/service-helpers/event-conditions.js +46 -0
  56. package/.medusa/server/src/modules/notifications/service-helpers/external-templates.js +80 -0
  57. package/.medusa/server/src/modules/notifications/service-helpers/recipient-resolution.js +85 -0
  58. package/.medusa/server/src/modules/notifications/service-helpers/sender-profiles.js +29 -0
  59. package/.medusa/server/src/modules/notifications/service-helpers/template-blocks.js +81 -0
  60. package/.medusa/server/src/modules/notifications/service-helpers/template-catalog.js +129 -0
  61. package/.medusa/server/src/modules/notifications/service-helpers/template-render.js +65 -0
  62. package/.medusa/server/src/modules/notifications/service.js +340 -0
  63. package/.medusa/server/src/modules/notifications/types.js +2 -0
  64. package/.medusa/server/src/modules/notifications/utils/auth-presets.js +140 -0
  65. package/.medusa/server/src/modules/notifications/utils/interpolation.js +178 -0
  66. package/.medusa/server/src/modules/notifications/utils/security.js +312 -0
  67. package/.medusa/server/src/modules/notifications/utils/system-presets.js +651 -0
  68. package/.medusa/server/src/modules/notifications/utils/transformers.js +358 -0
  69. package/.medusa/server/src/providers/dummy-sandbox/index.js +96 -0
  70. package/.medusa/server/src/providers/email-smtp/index.js +187 -0
  71. package/.medusa/server/src/providers/index.js +7 -0
  72. package/.medusa/server/src/providers/slack/index.js +54 -0
  73. package/.medusa/server/src/providers/sms/index.js +254 -0
  74. package/.medusa/server/src/providers/telegram/index.js +119 -0
  75. package/.medusa/server/src/providers/whatsapp/index.js +371 -0
  76. package/.medusa/server/src/rbac.js +109 -0
  77. package/.medusa/server/src/sdk/client.js +186 -0
  78. package/.medusa/server/src/sdk/index.js +3 -0
  79. package/.medusa/server/src/sdk/query-keys.js +61 -0
  80. package/.medusa/server/src/subscribers/customer-and-document-events.js +33 -0
  81. package/.medusa/server/src/subscribers/fulfillment-and-inventory-events.js +30 -0
  82. package/.medusa/server/src/subscribers/order-events.js +28 -0
  83. package/.medusa/server/src/types/constants.js +129 -0
  84. package/.medusa/server/src/types/core.js +2 -0
  85. package/.medusa/server/src/types/domain.js +2 -0
  86. package/.medusa/server/src/types/enums.js +53 -0
  87. package/.medusa/server/src/types/errors.js +28 -0
  88. package/.medusa/server/src/types/hooks.js +2 -0
  89. package/.medusa/server/src/types/index.js +12 -0
  90. package/.medusa/server/src/types/providers.js +2 -0
  91. package/.medusa/server/src/types/records.js +2 -0
  92. package/.medusa/server/src/types/render.js +2 -0
  93. package/.medusa/server/src/types/sdk-api.js +2 -0
  94. package/.medusa/server/src/types/translations.js +2 -0
  95. package/.medusa/server/src/workflows/index.js +461 -0
  96. package/LICENSE +21 -0
  97. package/README.md +389 -2
  98. package/package.json +133 -3
  99. package/src/admin/README.md +123 -0
  100. package/src/admin/components/mpn/broadcast-consent-section.tsx +62 -0
  101. package/src/admin/components/mpn/broadcasts-tab.tsx +208 -0
  102. package/src/admin/components/mpn/channels-main-section.tsx +205 -0
  103. package/src/admin/components/mpn/channels-side-section.tsx +88 -0
  104. package/src/admin/components/mpn/channels-tab.tsx +130 -0
  105. package/src/admin/components/mpn/constants.ts +8 -0
  106. package/src/admin/components/mpn/delivery-logs-tab.tsx +70 -0
  107. package/src/admin/components/mpn/event-mapping-form.tsx +191 -0
  108. package/src/admin/components/mpn/event-mappings-tab.tsx +165 -0
  109. package/src/admin/components/mpn/header-bar.tsx +35 -0
  110. package/src/admin/components/mpn/index.ts +17 -0
  111. package/src/admin/components/mpn/overview-cards.tsx +103 -0
  112. package/src/admin/components/mpn/sandbox-tab.tsx +93 -0
  113. package/src/admin/components/mpn/template-editor-section.tsx +203 -0
  114. package/src/admin/components/mpn/template-preview-section.tsx +122 -0
  115. package/src/admin/components/mpn/templates-list-section.tsx +115 -0
  116. package/src/admin/components/mpn/templates-tab.tsx +188 -0
  117. package/src/admin/components/mpn/use-notification-studio.ts +84 -0
  118. package/src/admin/components/rbac-guard.tsx +153 -0
  119. package/src/admin/i18n/README.md +134 -0
  120. package/src/admin/i18n/index.ts +23 -0
  121. package/src/admin/i18n/json/ar.json +157 -0
  122. package/src/admin/i18n/json/de.json +157 -0
  123. package/src/admin/i18n/json/en.json +157 -0
  124. package/src/admin/i18n/json/es.json +157 -0
  125. package/src/admin/i18n/json/fr.json +157 -0
  126. package/src/admin/i18n/json/it.json +157 -0
  127. package/src/admin/i18n/json/nl.json +157 -0
  128. package/src/admin/i18n/json/pl.json +157 -0
  129. package/src/admin/i18n/json/pt.json +157 -0
  130. package/src/admin/i18n/json/tr.json +157 -0
  131. package/src/admin/routes/mpn/broadcasts/page.tsx +75 -0
  132. package/src/admin/routes/mpn/channels/page.tsx +66 -0
  133. package/src/admin/routes/mpn/logs/page.tsx +50 -0
  134. package/src/admin/routes/mpn/mappings/page.tsx +62 -0
  135. package/src/admin/routes/mpn/page.tsx +200 -0
  136. package/src/admin/routes/mpn/sandbox/page.tsx +53 -0
  137. package/src/admin/routes/mpn/templates/page.tsx +55 -0
  138. package/src/admin/tsconfig.json +23 -0
  139. package/src/admin/vite-env.d.ts +1 -0
  140. package/src/admin/widgets/order-notifications-widget.tsx +178 -0
  141. package/src/api/README.md +98 -0
  142. package/src/api/admin/mpn/broadcasts/route.ts +130 -0
  143. package/src/api/admin/mpn/channels/route.ts +143 -0
  144. package/src/api/admin/mpn/logs/route.ts +41 -0
  145. package/src/api/admin/mpn/mappings/[id]/route.ts +45 -0
  146. package/src/api/admin/mpn/mappings/route.ts +68 -0
  147. package/src/api/admin/mpn/render-template/route.ts +46 -0
  148. package/src/api/admin/mpn/sandbox/route.ts +51 -0
  149. package/src/api/admin/mpn/send/route.ts +163 -0
  150. package/src/api/admin/mpn/templates/[id]/route.ts +101 -0
  151. package/src/api/admin/mpn/templates/route.ts +99 -0
  152. package/src/api/admin/plugin/route.ts +5 -0
  153. package/src/api/middlewares.ts +42 -0
  154. package/src/api/store/mpn/consent/route.ts +45 -0
  155. package/src/api/store/mpn/webhooks/[provider]/route.ts +119 -0
  156. package/src/api/store/plugin/route.ts +5 -0
  157. package/src/api/validators.ts +149 -0
  158. package/src/hooks/index.ts +14 -0
  159. package/src/hooks/use-mpn-channels.ts +43 -0
  160. package/src/hooks/use-mpn-dispatch.ts +149 -0
  161. package/src/hooks/use-mpn-mappings.ts +75 -0
  162. package/src/hooks/use-mpn-templates.ts +120 -0
  163. package/src/hooks/use-order-notifications-widget-state.ts +103 -0
  164. package/src/hooks/use-sdk-primitives.ts +157 -0
  165. package/src/index.ts +16 -0
  166. package/src/integrations/automations-action-handler.ts +156 -0
  167. package/src/jobs/README.md +41 -0
  168. package/src/jobs/abandoned-cart-recovery.ts +152 -0
  169. package/src/jobs/log-retention-and-broadcasts.ts +23 -0
  170. package/src/links/README.md +52 -0
  171. package/src/modules/README.md +99 -0
  172. package/src/modules/notifications/i18n/index.ts +83 -0
  173. package/src/modules/notifications/i18n/locales/ar.ts +84 -0
  174. package/src/modules/notifications/i18n/locales/de.ts +83 -0
  175. package/src/modules/notifications/i18n/locales/en.ts +84 -0
  176. package/src/modules/notifications/i18n/locales/es.ts +84 -0
  177. package/src/modules/notifications/i18n/locales/fr.ts +82 -0
  178. package/src/modules/notifications/i18n/locales/it.ts +82 -0
  179. package/src/modules/notifications/i18n/locales/nl.ts +83 -0
  180. package/src/modules/notifications/i18n/locales/pl.ts +84 -0
  181. package/src/modules/notifications/i18n/locales/pt.ts +82 -0
  182. package/src/modules/notifications/i18n/locales/tr.ts +86 -0
  183. package/src/modules/notifications/i18n/types.ts +1 -0
  184. package/src/modules/notifications/index.ts +10 -0
  185. package/src/modules/notifications/integrations/documents-and-b2b-resolver.ts +168 -0
  186. package/src/modules/notifications/migrations/Migration20261010000000.ts +185 -0
  187. package/src/modules/notifications/models/index.ts +125 -0
  188. package/src/modules/notifications/renderer/block-helpers.ts +51 -0
  189. package/src/modules/notifications/renderer/email.ts +281 -0
  190. package/src/modules/notifications/renderer/index.ts +301 -0
  191. package/src/modules/notifications/renderer/slack.ts +168 -0
  192. package/src/modules/notifications/renderer/telegram.ts +161 -0
  193. package/src/modules/notifications/renderer/whatsapp.ts +156 -0
  194. package/src/modules/notifications/service-helpers/channel-config.ts +65 -0
  195. package/src/modules/notifications/service-helpers/consent.ts +88 -0
  196. package/src/modules/notifications/service-helpers/delivery-log.ts +56 -0
  197. package/src/modules/notifications/service-helpers/event-conditions.ts +66 -0
  198. package/src/modules/notifications/service-helpers/external-templates.ts +127 -0
  199. package/src/modules/notifications/service-helpers/recipient-resolution.ts +124 -0
  200. package/src/modules/notifications/service-helpers/sender-profiles.ts +34 -0
  201. package/src/modules/notifications/service-helpers/template-blocks.ts +116 -0
  202. package/src/modules/notifications/service-helpers/template-catalog.ts +170 -0
  203. package/src/modules/notifications/service-helpers/template-render.ts +113 -0
  204. package/src/modules/notifications/service.ts +589 -0
  205. package/src/modules/notifications/types.ts +1 -0
  206. package/src/modules/notifications/utils/auth-presets.ts +145 -0
  207. package/src/modules/notifications/utils/interpolation.ts +231 -0
  208. package/src/modules/notifications/utils/security.ts +378 -0
  209. package/src/modules/notifications/utils/system-presets.ts +695 -0
  210. package/src/modules/notifications/utils/transformers.ts +456 -0
  211. package/src/providers/README.md +92 -0
  212. package/src/providers/dummy-sandbox/index.ts +143 -0
  213. package/src/providers/email-smtp/index.ts +257 -0
  214. package/src/providers/index.ts +38 -0
  215. package/src/providers/slack/index.ts +82 -0
  216. package/src/providers/sms/index.ts +342 -0
  217. package/src/providers/telegram/index.ts +181 -0
  218. package/src/providers/whatsapp/index.ts +505 -0
  219. package/src/rbac.ts +123 -0
  220. package/src/sdk/client.ts +319 -0
  221. package/src/sdk/index.ts +48 -0
  222. package/src/sdk/query-keys.ts +89 -0
  223. package/src/subscribers/README.md +50 -0
  224. package/src/subscribers/customer-and-document-events.ts +36 -0
  225. package/src/subscribers/fulfillment-and-inventory-events.ts +35 -0
  226. package/src/subscribers/order-events.ts +31 -0
  227. package/src/types/constants.ts +143 -0
  228. package/src/types/core.ts +96 -0
  229. package/src/types/domain.ts +84 -0
  230. package/src/types/enums.ts +73 -0
  231. package/src/types/errors.ts +32 -0
  232. package/src/types/hooks.ts +48 -0
  233. package/src/types/index.ts +11 -0
  234. package/src/types/providers.ts +96 -0
  235. package/src/types/records.ts +100 -0
  236. package/src/types/render.ts +74 -0
  237. package/src/types/sdk-api.ts +228 -0
  238. package/src/types/translations.ts +75 -0
  239. package/src/workflows/README.md +67 -0
  240. package/src/workflows/index.ts +619 -0
  241. package/tsconfig.json +40 -0
@@ -0,0 +1,505 @@
1
+ import type { Logger, NotificationTypes } from "@medusajs/framework/types"
2
+ import {
3
+ AbstractNotificationProviderService,
4
+ ModuleProvider,
5
+ Modules,
6
+ } from "@medusajs/framework/utils"
7
+ import type {
8
+ WhatsAppDriver,
9
+ WhatsAppInteractiveButton,
10
+ WhatsAppProviderOptions,
11
+ } from "../../types"
12
+ import {
13
+ normalizeE164Phone,
14
+ toWhatsAppDigitsOnly,
15
+ validateSafeExternalUrl,
16
+ } from "../../modules/notifications/utils/security"
17
+
18
+ export const MPN_WHATSAPP_PROVIDER_ID = "mpn-whatsapp"
19
+ export type { WhatsAppProviderOptions } from "../../types"
20
+
21
+ type InjectedDependencies = {
22
+ logger?: Logger
23
+ }
24
+
25
+ export class WhatsAppNotificationProviderService extends AbstractNotificationProviderService {
26
+ static identifier = MPN_WHATSAPP_PROVIDER_ID
27
+ protected readonly logger_?: Logger
28
+ protected readonly options_: WhatsAppProviderOptions
29
+
30
+ constructor(
31
+ container: InjectedDependencies,
32
+ options?: WhatsAppProviderOptions
33
+ ) {
34
+ super()
35
+ this.logger_ = container?.logger
36
+ this.options_ = options ?? {}
37
+ }
38
+
39
+ getActiveDriver(): WhatsAppDriver {
40
+ return (
41
+ this.options_.driver ||
42
+ (process.env.WHATSAPP_DRIVER as WhatsAppDriver) ||
43
+ (process.env.OPENWA_BASE_URL ? "openwa" : undefined) ||
44
+ (process.env.WAHA_BASE_URL ? "waha" : undefined) ||
45
+ (process.env.EVOLUTION_BASE_URL ? "evolution" : undefined) ||
46
+ "meta-cloud"
47
+ )
48
+ }
49
+
50
+ /**
51
+ * Builds the exact request payload and endpoint for any of the 4 WhatsApp drivers:
52
+ * - `meta-cloud` (Official Meta Graph API v21/v25: approved templates, interactive buttons, documents, session text)
53
+ * - `openwa` (`rmyndharis/OpenWA` REST API: `/api/sessions/{sessionId}/messages/send-text`, `/send-document`)
54
+ * - `waha` (WAHA WhatsApp HTTP API: `/api/sendText`, `/api/sendFile`)
55
+ * - `evolution` (Evolution API v2: `/message/sendText/{instance}`, `/message/sendMedia/{instance}`)
56
+ */
57
+ buildDriverRequest(params: {
58
+ driver?: WhatsAppDriver
59
+ to: string
60
+ text: string
61
+ whatsappOptions?: {
62
+ message_type?: "template" | "text" | "interactive" | "document"
63
+ meta_template_name?: string | null
64
+ meta_language_code?: string
65
+ meta_components?: Array<Record<string, any>>
66
+ buttons?: WhatsAppInteractiveButton[]
67
+ }
68
+ attachments?: Array<{
69
+ filename?: string
70
+ content?: string
71
+ content_type?: string
72
+ }>
73
+ }): {
74
+ driver: WhatsAppDriver
75
+ endpoint: string
76
+ headers: Record<string, string>
77
+ body: Record<string, any>
78
+ } {
79
+ const driver = params.driver || this.getActiveDriver()
80
+ const e164 = normalizeE164Phone(params.to)
81
+ const digitsOnly = toWhatsAppDigitsOnly(params.to)
82
+ if (!e164 || !digitsOnly) {
83
+ throw new Error(
84
+ "WhatsApp recipient must be a valid E.164 phone number (e.g. +14155552671)"
85
+ )
86
+ }
87
+
88
+ const waOpts = params.whatsappOptions || {}
89
+ const attachments = params.attachments || []
90
+ const firstAttachment = attachments[0]
91
+
92
+ // -------------------------------------------------------------------------
93
+ // DRIVER 1: OpenWA (https://github.com/rmyndharis/OpenWA REST API)
94
+ // -------------------------------------------------------------------------
95
+ if (driver === "openwa") {
96
+ const baseUrl = (
97
+ this.options_.gatewayUrl ||
98
+ process.env.OPENWA_BASE_URL ||
99
+ "http://127.0.0.1:2785"
100
+ ).replace(/\/$/, "")
101
+ const check = validateSafeExternalUrl(baseUrl, {
102
+ allowLocalhost:
103
+ this.options_.allowLocalhost ?? process.env.NODE_ENV !== "production",
104
+ })
105
+ if (!check.valid) {
106
+ throw new Error(`Unsafe OpenWA Gateway URL: ${check.reason}`)
107
+ }
108
+
109
+ const rawSession = (
110
+ this.options_.sessionId ||
111
+ process.env.OPENWA_SESSION_ID ||
112
+ "default"
113
+ ).trim()
114
+ if (!/^[a-zA-Z0-9._-]{1,64}$/.test(rawSession)) {
115
+ throw new Error("Invalid OpenWA session identifier")
116
+ }
117
+ const sessionId = encodeURIComponent(rawSession)
118
+
119
+ const apiKey =
120
+ this.options_.gatewayApiKey || process.env.OPENWA_API_KEY || ""
121
+ const chatId = `${digitsOnly}@c.us`
122
+ const headers: Record<string, string> = {
123
+ "Content-Type": "application/json",
124
+ ...(apiKey
125
+ ? { "X-API-Key": apiKey, Authorization: `Bearer ${apiKey}` }
126
+ : {}),
127
+ }
128
+
129
+ if (firstAttachment && firstAttachment.content) {
130
+ const mime = firstAttachment.content_type || "application/pdf"
131
+ return {
132
+ driver: "openwa",
133
+ endpoint: `${baseUrl}/api/sessions/${sessionId}/messages/send-document`,
134
+ headers,
135
+ body: {
136
+ chatId,
137
+ base64: `data:${mime};base64,${firstAttachment.content}`,
138
+ filename: firstAttachment.filename || "document.pdf",
139
+ caption: params.text,
140
+ },
141
+ }
142
+ }
143
+
144
+ const formattedText =
145
+ waOpts.buttons && waOpts.buttons.length > 0
146
+ ? `${params.text}\n\n${waOpts.buttons
147
+ .slice(0, 3)
148
+ .map((b, idx) =>
149
+ b.url
150
+ ? `${idx + 1}. ${b.title}: ${b.url}`
151
+ : `${idx + 1}. ${b.title}`
152
+ )
153
+ .join("\n")}`
154
+ : params.text
155
+
156
+ return {
157
+ driver: "openwa",
158
+ endpoint: `${baseUrl}/api/sessions/${sessionId}/messages/send-text`,
159
+ headers,
160
+ body: {
161
+ chatId,
162
+ text: formattedText,
163
+ },
164
+ }
165
+ }
166
+
167
+ // -------------------------------------------------------------------------
168
+ // DRIVER 2: WAHA (WhatsApp HTTP API)
169
+ // -------------------------------------------------------------------------
170
+ if (driver === "waha") {
171
+ const baseUrl = (
172
+ this.options_.gatewayUrl ||
173
+ process.env.WAHA_BASE_URL ||
174
+ "http://127.0.0.1:3000"
175
+ ).replace(/\/$/, "")
176
+ const check = validateSafeExternalUrl(baseUrl, {
177
+ allowLocalhost:
178
+ this.options_.allowLocalhost ?? process.env.NODE_ENV !== "production",
179
+ })
180
+ if (!check.valid) {
181
+ throw new Error(`Unsafe WAHA Gateway URL: ${check.reason}`)
182
+ }
183
+
184
+ const apiKey =
185
+ this.options_.gatewayApiKey || process.env.WAHA_API_KEY || ""
186
+ const session =
187
+ this.options_.sessionId || process.env.WAHA_SESSION || "default"
188
+ const chatId = `${digitsOnly}@c.us`
189
+ const headers: Record<string, string> = {
190
+ "Content-Type": "application/json",
191
+ ...(apiKey ? { "X-Api-Key": apiKey } : {}),
192
+ }
193
+
194
+ if (firstAttachment && firstAttachment.content) {
195
+ return {
196
+ driver: "waha",
197
+ endpoint: `${baseUrl}/api/sendFile`,
198
+ headers,
199
+ body: {
200
+ session,
201
+ chatId,
202
+ caption: params.text,
203
+ file: {
204
+ mimetype: firstAttachment.content_type || "application/pdf",
205
+ filename: firstAttachment.filename || "document.pdf",
206
+ data: firstAttachment.content,
207
+ },
208
+ },
209
+ }
210
+ }
211
+
212
+ return {
213
+ driver: "waha",
214
+ endpoint: `${baseUrl}/api/sendText`,
215
+ headers,
216
+ body: {
217
+ session,
218
+ chatId,
219
+ text: params.text,
220
+ },
221
+ }
222
+ }
223
+
224
+ // -------------------------------------------------------------------------
225
+ // DRIVER 3: Evolution API v2
226
+ // -------------------------------------------------------------------------
227
+ if (driver === "evolution") {
228
+ const baseUrl = (
229
+ this.options_.gatewayUrl ||
230
+ process.env.EVOLUTION_BASE_URL ||
231
+ "http://127.0.0.1:8080"
232
+ ).replace(/\/$/, "")
233
+ const check = validateSafeExternalUrl(baseUrl, {
234
+ allowLocalhost:
235
+ this.options_.allowLocalhost ?? process.env.NODE_ENV !== "production",
236
+ })
237
+ if (!check.valid) {
238
+ throw new Error(`Unsafe Evolution API URL: ${check.reason}`)
239
+ }
240
+
241
+ const apiKey =
242
+ this.options_.gatewayApiKey || process.env.EVOLUTION_API_KEY || ""
243
+ const instance =
244
+ this.options_.sessionId || process.env.EVOLUTION_INSTANCE || "store"
245
+ const headers: Record<string, string> = {
246
+ "Content-Type": "application/json",
247
+ ...(apiKey ? { apikey: apiKey } : {}),
248
+ }
249
+
250
+ if (firstAttachment && firstAttachment.content) {
251
+ return {
252
+ driver: "evolution",
253
+ endpoint: `${baseUrl}/message/sendMedia/${encodeURIComponent(instance)}`,
254
+ headers,
255
+ body: {
256
+ number: digitsOnly,
257
+ mediatype: "document",
258
+ mimetype: firstAttachment.content_type || "application/pdf",
259
+ caption: params.text,
260
+ media: firstAttachment.content,
261
+ fileName: firstAttachment.filename || "document.pdf",
262
+ },
263
+ }
264
+ }
265
+
266
+ return {
267
+ driver: "evolution",
268
+ endpoint: `${baseUrl}/message/sendText/${encodeURIComponent(instance)}`,
269
+ headers,
270
+ body: {
271
+ number: digitsOnly,
272
+ text: params.text,
273
+ },
274
+ }
275
+ }
276
+
277
+ // -------------------------------------------------------------------------
278
+ // DRIVER 4: Official Meta WhatsApp Business Cloud API (`meta-cloud`)
279
+ // -------------------------------------------------------------------------
280
+ const phoneNumberId =
281
+ this.options_.phoneNumberId || process.env.WHATSAPP_PHONE_NUMBER_ID || ""
282
+ const accessToken =
283
+ this.options_.accessToken || process.env.WHATSAPP_ACCESS_TOKEN || ""
284
+ const version =
285
+ this.options_.graphAPIVersion ||
286
+ process.env.WHATSAPP_API_VERSION ||
287
+ "v22.0"
288
+
289
+ const endpoint = `https://graph.facebook.com/${version}/${encodeURIComponent(phoneNumberId || "000000")}/messages`
290
+ const headers: Record<string, string> = {
291
+ "Content-Type": "application/json",
292
+ ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
293
+ }
294
+
295
+ // Meta approved template message (works outside the 24h customer care window)
296
+ if (waOpts.meta_template_name) {
297
+ return {
298
+ driver: "meta-cloud",
299
+ endpoint,
300
+ headers,
301
+ body: {
302
+ messaging_product: "whatsapp",
303
+ recipient_type: "individual",
304
+ to: digitsOnly,
305
+ type: "template",
306
+ template: {
307
+ name: waOpts.meta_template_name,
308
+ language: {
309
+ code: waOpts.meta_language_code || "en",
310
+ },
311
+ ...(Array.isArray(waOpts.meta_components) &&
312
+ waOpts.meta_components.length > 0
313
+ ? { components: waOpts.meta_components }
314
+ : {}),
315
+ },
316
+ },
317
+ }
318
+ }
319
+
320
+ // Meta interactive reply buttons message
321
+ if (waOpts.buttons && waOpts.buttons.length > 0) {
322
+ return {
323
+ driver: "meta-cloud",
324
+ endpoint,
325
+ headers,
326
+ body: {
327
+ messaging_product: "whatsapp",
328
+ recipient_type: "individual",
329
+ to: digitsOnly,
330
+ type: "interactive",
331
+ interactive: {
332
+ type: "button",
333
+ body: { text: params.text.slice(0, 1024) },
334
+ action: {
335
+ buttons: waOpts.buttons.slice(0, 3).map((b) => ({
336
+ type: "reply",
337
+ reply: {
338
+ id: b.id.slice(0, 256),
339
+ title: b.title.slice(0, 20),
340
+ },
341
+ })),
342
+ },
343
+ },
344
+ },
345
+ }
346
+ }
347
+
348
+ // Meta session text message (inside 24h window)
349
+ return {
350
+ driver: "meta-cloud",
351
+ endpoint,
352
+ headers,
353
+ body: {
354
+ messaging_product: "whatsapp",
355
+ recipient_type: "individual",
356
+ to: digitsOnly,
357
+ type: "text",
358
+ text: {
359
+ preview_url: true,
360
+ body: params.text,
361
+ },
362
+ },
363
+ }
364
+ }
365
+
366
+ /**
367
+ * Queries session status / QR pairing code from OpenWA, WAHA, or Evolution API,
368
+ * or verifies Meta WABA configuration.
369
+ */
370
+ async getSessionStatus(driverOverride?: WhatsAppDriver): Promise<{
371
+ driver: WhatsAppDriver
372
+ connected: boolean
373
+ session_state: string
374
+ qr_code?: string | null
375
+ details?: Record<string, any>
376
+ }> {
377
+ const driver = driverOverride || this.getActiveDriver()
378
+ if (driver === "meta-cloud") {
379
+ const configured = Boolean(
380
+ (this.options_.accessToken || process.env.WHATSAPP_ACCESS_TOKEN) &&
381
+ (this.options_.phoneNumberId || process.env.WHATSAPP_PHONE_NUMBER_ID)
382
+ )
383
+ return {
384
+ driver: "meta-cloud",
385
+ connected: configured,
386
+ session_state: configured
387
+ ? "WABA_CONFIGURED"
388
+ : "MISSING_ENV_CREDENTIALS",
389
+ details: {
390
+ phone_number_id:
391
+ this.options_.phoneNumberId ||
392
+ process.env.WHATSAPP_PHONE_NUMBER_ID ||
393
+ null,
394
+ waba_id:
395
+ this.options_.wabaId ||
396
+ process.env.WHATSAPP_BUSINESS_ACCOUNT_ID ||
397
+ null,
398
+ },
399
+ }
400
+ }
401
+
402
+ return {
403
+ driver,
404
+ connected: Boolean(
405
+ this.options_.gatewayUrl ||
406
+ process.env.OPENWA_BASE_URL ||
407
+ process.env.WAHA_BASE_URL ||
408
+ process.env.EVOLUTION_BASE_URL
409
+ ),
410
+ session_state: "GATEWAY_READY",
411
+ qr_code: null,
412
+ }
413
+ }
414
+
415
+ async send(
416
+ notification: NotificationTypes.ProviderSendNotificationDTO
417
+ ): Promise<NotificationTypes.ProviderSendNotificationResultsDTO> {
418
+ if (this.options_.enabled === false) {
419
+ return { id: `wa_disabled_${Date.now()}` }
420
+ }
421
+
422
+ const data = (notification.data || {}) as Record<string, any>
423
+ const content = (notification.content || {}) as Record<string, any>
424
+ const text =
425
+ content.text ||
426
+ (data.text as string) ||
427
+ (data.body as string) ||
428
+ (data.title as string) ||
429
+ ""
430
+
431
+ const reqSpec = this.buildDriverRequest({
432
+ driver: (data.whatsapp_driver as WhatsAppDriver) || undefined,
433
+ to: notification.to,
434
+ text,
435
+ whatsappOptions: data.whatsapp_options as any,
436
+ attachments: notification.attachments as any,
437
+ })
438
+
439
+ // In local/test environments without live credentials, return deterministic dry-run ID
440
+ if (
441
+ reqSpec.driver === "meta-cloud" &&
442
+ !this.options_.accessToken &&
443
+ !process.env.WHATSAPP_ACCESS_TOKEN
444
+ ) {
445
+ this.logger_?.warn(
446
+ "[mpn-whatsapp] WHATSAPP_ACCESS_TOKEN not set; returning dry-run message ID."
447
+ )
448
+ return { id: `wamid.dryrun_${Date.now()}` }
449
+ }
450
+
451
+ const timeoutMs = Number(
452
+ this.options_.timeoutMs || process.env.WHATSAPP_API_TIMEOUT_MS || 15000
453
+ )
454
+ const controller = new AbortController()
455
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
456
+
457
+ try {
458
+ const response = await fetch(reqSpec.endpoint, {
459
+ method: "POST",
460
+ headers: reqSpec.headers,
461
+ body: JSON.stringify(reqSpec.body),
462
+ signal: controller.signal,
463
+ })
464
+
465
+ const json = (await response.json().catch(() => ({}))) as Record<
466
+ string,
467
+ any
468
+ >
469
+
470
+ if (!response.ok) {
471
+ const metaError = json?.error
472
+ const detail =
473
+ metaError?.error_data?.details ||
474
+ metaError?.message ||
475
+ json?.message ||
476
+ `HTTP ${response.status}`
477
+ const code = metaError?.code ? ` (#${metaError.code})` : ""
478
+ throw new Error(`WhatsApp (${reqSpec.driver}) failed${code}: ${detail}`)
479
+ }
480
+
481
+ // Meta Cloud API requires verifying that a message ID (`wamid.*`) was actually returned
482
+ const messageId =
483
+ json?.messages?.[0]?.id ||
484
+ json?.response?.id ||
485
+ json?.id ||
486
+ json?.key?.id
487
+
488
+ if (reqSpec.driver === "meta-cloud" && !messageId) {
489
+ throw new Error(
490
+ "Meta WhatsApp Graph API returned HTTP 200 without a valid message ID"
491
+ )
492
+ }
493
+
494
+ return {
495
+ id: String(messageId || `wa_${reqSpec.driver}_${Date.now()}`),
496
+ }
497
+ } finally {
498
+ clearTimeout(timer)
499
+ }
500
+ }
501
+ }
502
+
503
+ export default ModuleProvider(Modules.NOTIFICATION, {
504
+ services: [WhatsAppNotificationProviderService],
505
+ })
package/src/rbac.ts ADDED
@@ -0,0 +1,123 @@
1
+ // Auto-generated RBAC descriptors compatible with @abhi1693/medusa-rbac AccessControlOptions.
2
+ export type RbacPermissionTuple = readonly [
3
+ id: string,
4
+ label: string,
5
+ group: string,
6
+ ]
7
+ export type RbacRoutePolicy = {
8
+ method: string
9
+ path: string
10
+ permissions: string[]
11
+ superuser?: boolean
12
+ }
13
+
14
+ export const RBAC_PERMISSIONS: readonly RbacPermissionTuple[] = [
15
+ [
16
+ "notifications.read",
17
+ "Read notification channels, templates, mappings & logs",
18
+ "Notifications",
19
+ ],
20
+ [
21
+ "notifications.write",
22
+ "Send notifications, broadcasts & manage templates/mappings",
23
+ "Notifications",
24
+ ],
25
+ ] as const
26
+
27
+ export const RBAC_ROUTES: RbacRoutePolicy[] = [
28
+ {
29
+ method: "GET",
30
+ path: "/admin/mpn/broadcasts",
31
+ permissions: ["notifications.read"],
32
+ },
33
+ {
34
+ method: "POST",
35
+ path: "/admin/mpn/broadcasts",
36
+ permissions: ["notifications.write"],
37
+ },
38
+ {
39
+ method: "GET",
40
+ path: "/admin/mpn/channels",
41
+ permissions: ["notifications.read"],
42
+ },
43
+ {
44
+ method: "POST",
45
+ path: "/admin/mpn/channels",
46
+ permissions: ["notifications.write"],
47
+ },
48
+ {
49
+ method: "GET",
50
+ path: "/admin/mpn/logs",
51
+ permissions: ["notifications.read"],
52
+ },
53
+ {
54
+ method: "POST",
55
+ path: "/admin/mpn/mappings/:id",
56
+ permissions: ["notifications.write"],
57
+ },
58
+ {
59
+ method: "DELETE",
60
+ path: "/admin/mpn/mappings/:id",
61
+ permissions: ["notifications.write"],
62
+ },
63
+ {
64
+ method: "GET",
65
+ path: "/admin/mpn/mappings",
66
+ permissions: ["notifications.read"],
67
+ },
68
+ {
69
+ method: "POST",
70
+ path: "/admin/mpn/mappings",
71
+ permissions: ["notifications.write"],
72
+ },
73
+ {
74
+ method: "POST",
75
+ path: "/admin/mpn/render-template",
76
+ permissions: ["notifications.write"],
77
+ },
78
+ {
79
+ method: "GET",
80
+ path: "/admin/mpn/sandbox",
81
+ permissions: ["notifications.read"],
82
+ },
83
+ {
84
+ method: "DELETE",
85
+ path: "/admin/mpn/sandbox",
86
+ permissions: ["notifications.write"],
87
+ },
88
+ {
89
+ method: "POST",
90
+ path: "/admin/mpn/send",
91
+ permissions: ["notifications.write"],
92
+ },
93
+ {
94
+ method: "GET",
95
+ path: "/admin/mpn/templates/:id",
96
+ permissions: ["notifications.read"],
97
+ },
98
+ {
99
+ method: "POST",
100
+ path: "/admin/mpn/templates/:id",
101
+ permissions: ["notifications.write"],
102
+ },
103
+ {
104
+ method: "DELETE",
105
+ path: "/admin/mpn/templates/:id",
106
+ permissions: ["notifications.write"],
107
+ },
108
+ {
109
+ method: "GET",
110
+ path: "/admin/mpn/templates",
111
+ permissions: ["notifications.read"],
112
+ },
113
+ {
114
+ method: "POST",
115
+ path: "/admin/mpn/templates",
116
+ permissions: ["notifications.write"],
117
+ },
118
+ ]
119
+
120
+ export const rbacAccess = {
121
+ permissions: [...RBAC_PERMISSIONS],
122
+ routes: RBAC_ROUTES,
123
+ }