backend-manager 5.9.7 → 5.9.8

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 (209) hide show
  1. package/package.json +5 -3
  2. package/templates/_.env +42 -0
  3. package/templates/_.gitignore +60 -0
  4. package/templates/backend-manager-config.json +249 -0
  5. package/templates/database.rules.json +83 -0
  6. package/templates/firebase.json +66 -0
  7. package/templates/firestore.indexes.json +4 -0
  8. package/templates/firestore.rules +112 -0
  9. package/templates/public/404.html +26 -0
  10. package/templates/public/index.html +24 -0
  11. package/templates/remoteconfig.template.json +1 -0
  12. package/templates/storage-lifecycle-config-1-day.json +9 -0
  13. package/templates/storage-lifecycle-config-30-days.json +9 -0
  14. package/templates/storage.rules +8 -0
  15. package/test/_init/accounts-validation.js +58 -0
  16. package/test/_legacy/ai/index.js +231 -0
  17. package/test/_legacy/ai/test.jpg +0 -0
  18. package/test/_legacy/ai/test.pdf +0 -0
  19. package/test/_legacy/index.js +31 -0
  20. package/test/_legacy/payment-resolver/chargebee/orders/refunded.json +0 -0
  21. package/test/_legacy/payment-resolver/chargebee/orders/unpaid.json +98 -0
  22. package/test/_legacy/payment-resolver/chargebee/subscriptions/active.json +578 -0
  23. package/test/_legacy/payment-resolver/chargebee/subscriptions/trial-in-trial.json +38 -0
  24. package/test/_legacy/payment-resolver/chargebee/subscriptions/trial-skipped-to-active.json +135 -0
  25. package/test/_legacy/payment-resolver/chargebee/subscriptions/trial-to-active-to-cancelled.json +42 -0
  26. package/test/_legacy/payment-resolver/chargebee/subscriptions/trial-to-active.json +44 -0
  27. package/test/_legacy/payment-resolver/chargebee/subscriptions/trial-to-cancelled.json +39 -0
  28. package/test/_legacy/payment-resolver/chargebee/subscriptions/trial-to-refund.json +143 -0
  29. package/test/_legacy/payment-resolver/chargebee/subscriptions/trial-to-suspended.json +48 -0
  30. package/test/_legacy/payment-resolver/coinbase/orders/regular.json +204 -0
  31. package/test/_legacy/payment-resolver/coinbase/subscriptions/cancelled.json +204 -0
  32. package/test/_legacy/payment-resolver/coinbase/subscriptions/paid-2.json +125 -0
  33. package/test/_legacy/payment-resolver/index.js +1558 -0
  34. package/test/_legacy/payment-resolver/paypal/orders/refunded.json +0 -0
  35. package/test/_legacy/payment-resolver/paypal/orders/regular.json +120 -0
  36. package/test/_legacy/payment-resolver/paypal/subscriptions/active-refund-previous-stmnt.json +323 -0
  37. package/test/_legacy/payment-resolver/paypal/subscriptions/active.json +192 -0
  38. package/test/_legacy/payment-resolver/paypal/subscriptions/trial-in-trial.json +125 -0
  39. package/test/_legacy/payment-resolver/paypal/subscriptions/trial-payment-not-complete.json +76 -0
  40. package/test/_legacy/payment-resolver/paypal/subscriptions/trial-payment-overdue-2.json +114 -0
  41. package/test/_legacy/payment-resolver/paypal/subscriptions/trial-payment-overdue.json +114 -0
  42. package/test/_legacy/payment-resolver/paypal/subscriptions/trial-to-active-to-cancelled.json +111 -0
  43. package/test/_legacy/payment-resolver/paypal/subscriptions/trial-to-active.json +132 -0
  44. package/test/_legacy/payment-resolver/paypal/subscriptions/trial-to-cancelled.json +107 -0
  45. package/test/_legacy/payment-resolver/paypal/subscriptions/trial-to-expired.json +91 -0
  46. package/test/_legacy/payment-resolver/paypal/subscriptions/trial-to-refund.json +147 -0
  47. package/test/_legacy/payment-resolver/paypal/subscriptions/trial-to-suspended.json +120 -0
  48. package/test/_legacy/payment-resolver/stripe/orders/refunded.json +0 -0
  49. package/test/_legacy/payment-resolver/stripe/orders/regular.json +91 -0
  50. package/test/_legacy/payment-resolver/stripe/subscriptions/active.json +421 -0
  51. package/test/_legacy/payment-resolver/stripe/subscriptions/trial-in-trial.json +349 -0
  52. package/test/_legacy/payment-resolver/stripe/subscriptions/trial-to-active-failed-authorization.json +430 -0
  53. package/test/_legacy/payment-resolver/stripe/subscriptions/trial-to-active.json +319 -0
  54. package/test/_legacy/payment-resolver/stripe/subscriptions/trial-to-cancelled.json +319 -0
  55. package/test/_legacy/payment-resolver/stripe/subscriptions/trial-to-refund.json +414 -0
  56. package/test/_legacy/payment-resolver/stripe/subscriptions/trial-to-suspended.json +319 -0
  57. package/test/_legacy/payment-resolver/stripe/subscriptions/unsure.json +339 -0
  58. package/test/_legacy/test-new +1178 -0
  59. package/test/_legacy/test.md +89 -0
  60. package/test/_legacy/usage.js +175 -0
  61. package/test/_legacy/user.js +31 -0
  62. package/test/ai/tools-live.js +170 -0
  63. package/test/boot/emulator-boots.js +37 -0
  64. package/test/content/blog-generate.js +160 -0
  65. package/test/email/campaign-send.js +45 -0
  66. package/test/email/consent-lifecycle.js +257 -0
  67. package/test/email/feedback-and-plain-send.js +52 -0
  68. package/test/email/fixtures/clean.json +30 -0
  69. package/test/email/fixtures/editorial.json +30 -0
  70. package/test/email/fixtures/field-report.json +53 -0
  71. package/test/email/marketing-lifecycle.js +132 -0
  72. package/test/email/newsletter-generate.js +819 -0
  73. package/test/email/newsletter-templates.js +491 -0
  74. package/test/email/templates.js +207 -0
  75. package/test/email/transactional-send.js +34 -0
  76. package/test/email/transactional.js +560 -0
  77. package/test/email/validation.js +710 -0
  78. package/test/events/auth-delete-race.js +201 -0
  79. package/test/events/payments/journey-payments-cancel-endpoint.js +100 -0
  80. package/test/events/payments/journey-payments-cancel.js +182 -0
  81. package/test/events/payments/journey-payments-discount.js +89 -0
  82. package/test/events/payments/journey-payments-failure.js +146 -0
  83. package/test/events/payments/journey-payments-legacy-product.js +149 -0
  84. package/test/events/payments/journey-payments-one-time-failure.js +111 -0
  85. package/test/events/payments/journey-payments-one-time.js +136 -0
  86. package/test/events/payments/journey-payments-plan-change.js +144 -0
  87. package/test/events/payments/journey-payments-refund-webhook.js +180 -0
  88. package/test/events/payments/journey-payments-suspend.js +181 -0
  89. package/test/events/payments/journey-payments-trial-cancel.js +130 -0
  90. package/test/events/payments/journey-payments-trial.js +171 -0
  91. package/test/events/payments/journey-payments-uid-resolution.js +132 -0
  92. package/test/events/payments/journey-payments-upgrade.js +135 -0
  93. package/test/fixtures/chargebee/invoice-one-time.json +27 -0
  94. package/test/fixtures/chargebee/subscription-active.json +44 -0
  95. package/test/fixtures/chargebee/subscription-cancelled.json +42 -0
  96. package/test/fixtures/chargebee/subscription-in-trial.json +41 -0
  97. package/test/fixtures/chargebee/subscription-legacy-plan.json +41 -0
  98. package/test/fixtures/chargebee/subscription-non-renewing.json +41 -0
  99. package/test/fixtures/chargebee/subscription-paused.json +42 -0
  100. package/test/fixtures/chargebee/webhook-payment-failed.json +51 -0
  101. package/test/fixtures/chargebee/webhook-subscription-created.json +47 -0
  102. package/test/fixtures/paypal/order-approved.json +62 -0
  103. package/test/fixtures/paypal/order-completed.json +110 -0
  104. package/test/fixtures/paypal/subscription-active.json +76 -0
  105. package/test/fixtures/paypal/subscription-cancelled.json +50 -0
  106. package/test/fixtures/paypal/subscription-suspended.json +65 -0
  107. package/test/fixtures/stripe/checkout-session-completed.json +130 -0
  108. package/test/fixtures/stripe/invoice-payment-failed.json +148 -0
  109. package/test/fixtures/stripe/invoice-subscription-payment-failed.json +28 -0
  110. package/test/fixtures/stripe/subscription-active.json +161 -0
  111. package/test/fixtures/stripe/subscription-canceled.json +161 -0
  112. package/test/fixtures/stripe/subscription-trialing.json +161 -0
  113. package/test/functions/admin/database-read.js +134 -0
  114. package/test/functions/admin/database-write.js +159 -0
  115. package/test/functions/admin/edit-post.js +366 -0
  116. package/test/functions/admin/firestore-query.js +207 -0
  117. package/test/functions/admin/firestore-read.js +129 -0
  118. package/test/functions/admin/firestore-write.js +105 -0
  119. package/test/functions/admin/get-stats.js +115 -0
  120. package/test/functions/admin/send-email.js +119 -0
  121. package/test/functions/admin/send-notification.js +208 -0
  122. package/test/functions/admin/write-repo-content.js +223 -0
  123. package/test/functions/general/add-marketing-contact.js +335 -0
  124. package/test/functions/general/fetch-post.js +54 -0
  125. package/test/functions/general/generate-uuid.js +114 -0
  126. package/test/functions/test/authenticate.js +64 -0
  127. package/test/functions/user/create-custom-token.js +73 -0
  128. package/test/functions/user/delete.js +135 -0
  129. package/test/functions/user/get-active-sessions.js +111 -0
  130. package/test/functions/user/get-subscription-info.js +99 -0
  131. package/test/functions/user/regenerate-api-keys.js +156 -0
  132. package/test/functions/user/resolve.js +52 -0
  133. package/test/functions/user/sign-out-all-sessions.js +94 -0
  134. package/test/functions/user/sign-up.js +252 -0
  135. package/test/functions/user/submit-feedback.js +104 -0
  136. package/test/functions/user/validate-settings.js +82 -0
  137. package/test/helpers/ai-request-payload.js +300 -0
  138. package/test/helpers/ai-test-provider.js +202 -0
  139. package/test/helpers/ai-tools-format.js +383 -0
  140. package/test/helpers/content/blog-auto-publisher.js +484 -0
  141. package/test/helpers/content/feed-parser.js +528 -0
  142. package/test/helpers/content/ghostii-blocks.js +134 -0
  143. package/test/helpers/content/ghostii-feed-integration.js +404 -0
  144. package/test/helpers/content/ghostii-write-article.js +243 -0
  145. package/test/helpers/environment.js +230 -0
  146. package/test/helpers/infer-contact.js +113 -0
  147. package/test/helpers/merge-line-files.js +271 -0
  148. package/test/helpers/payment/chargebee/parse-webhook.js +413 -0
  149. package/test/helpers/payment/chargebee/to-unified-one-time.js +147 -0
  150. package/test/helpers/payment/chargebee/to-unified-subscription.js +648 -0
  151. package/test/helpers/payment/paypal/parse-webhook.js +539 -0
  152. package/test/helpers/payment/paypal/to-unified-one-time.js +382 -0
  153. package/test/helpers/payment/paypal/to-unified-subscription.js +820 -0
  154. package/test/helpers/payment/stripe/parse-webhook.js +447 -0
  155. package/test/helpers/payment/stripe/to-unified-one-time.js +306 -0
  156. package/test/helpers/payment/stripe/to-unified-subscription.js +708 -0
  157. package/test/helpers/sanitize.js +222 -0
  158. package/test/helpers/slugify.js +394 -0
  159. package/test/helpers/storage.js +194 -0
  160. package/test/helpers/user.js +755 -0
  161. package/test/helpers/webhook-forward.js +418 -0
  162. package/test/mcp/discovery.js +53 -0
  163. package/test/mcp/oauth.js +161 -0
  164. package/test/mcp/protocol.js +268 -0
  165. package/test/mcp/roles.js +188 -0
  166. package/test/mcp/utils.js +245 -0
  167. package/test/routes/admin/create-post.js +364 -0
  168. package/test/routes/admin/database.js +131 -0
  169. package/test/routes/admin/deduplicate-image-alts.js +190 -0
  170. package/test/routes/admin/email.js +114 -0
  171. package/test/routes/admin/firestore-query.js +204 -0
  172. package/test/routes/admin/firestore.js +127 -0
  173. package/test/routes/admin/infer-contact.js +218 -0
  174. package/test/routes/admin/notification.js +198 -0
  175. package/test/routes/admin/post-resize-image.js +184 -0
  176. package/test/routes/admin/post.js +368 -0
  177. package/test/routes/admin/repo-content.js +223 -0
  178. package/test/routes/admin/stats.js +112 -0
  179. package/test/routes/content/post.js +54 -0
  180. package/test/routes/general/uuid.js +115 -0
  181. package/test/routes/marketing/campaign.js +125 -0
  182. package/test/routes/marketing/contact.js +370 -0
  183. package/test/routes/marketing/email-preferences.js +292 -0
  184. package/test/routes/marketing/push-send.js +32 -0
  185. package/test/routes/marketing/webhook-forward.js +61 -0
  186. package/test/routes/marketing/webhook.js +639 -0
  187. package/test/routes/payments/cancel.js +163 -0
  188. package/test/routes/payments/discount.js +80 -0
  189. package/test/routes/payments/dispute-alert.js +320 -0
  190. package/test/routes/payments/intent.js +336 -0
  191. package/test/routes/payments/portal.js +92 -0
  192. package/test/routes/payments/refund.js +179 -0
  193. package/test/routes/payments/trial-eligibility.js +71 -0
  194. package/test/routes/payments/webhook.js +107 -0
  195. package/test/routes/test/authenticate.js +59 -0
  196. package/test/routes/test/schema.js +554 -0
  197. package/test/routes/test/usage.js +342 -0
  198. package/test/routes/user/api-keys.js +156 -0
  199. package/test/routes/user/delete.js +136 -0
  200. package/test/routes/user/feedback.js +104 -0
  201. package/test/routes/user/sessions.js +199 -0
  202. package/test/routes/user/settings-validate.js +82 -0
  203. package/test/routes/user/signup.js +542 -0
  204. package/test/routes/user/subscription.js +99 -0
  205. package/test/routes/user/token.js +73 -0
  206. package/test/routes/user/user.js +157 -0
  207. package/test/rules/notifications.js +410 -0
  208. package/test/rules/payments-carts.js +371 -0
  209. package/test/rules/user.js +396 -0
@@ -0,0 +1,639 @@
1
+ /**
2
+ * Test: POST /marketing/webhook
3
+ *
4
+ * Cross-provider unsubscribe webhook receiver. Phase E covers SendGrid;
5
+ * Beehiiv will be added in a separate file.
6
+ *
7
+ * Dispatcher tests:
8
+ * - Auth via ?key= query param
9
+ * - Provider validation
10
+ * - Brand filter (ignore mismatched brand)
11
+ * - Idempotent re-delivery (handlers re-run safely; no dedup ledger)
12
+ *
13
+ * SendGrid processor tests:
14
+ * - Various event types (group_unsubscribe, unsubscribe, spamreport, bounce, dropped)
15
+ * - bounce/dropped only revoke on bounce_classification='Invalid Address' (hard bounce);
16
+ * technical bounces are sender-side issues and must NOT revoke consent
17
+ * - Email lookup → user doc mutation with source='sendgrid'
18
+ * - Silent skip when email doesn't map to a user (shared SendGrid account scenario)
19
+ * - Batched events processed independently
20
+ * - Unsupported event types ignored
21
+ *
22
+ * All revoke-event tests target the dedicated `journey-webhook-revoke` account: they
23
+ * leave it with consent.marketing.status='revoked' (persistent side-effect data), which
24
+ * must never land on the shared `basic` account — revoked consent persists for the rest
25
+ * of the run and trips the email library's consent gate for later syncs of that account.
26
+ */
27
+
28
+ // Helper — generate a unique sg_event_id per test
29
+ function sgEventId(name) {
30
+ return `_test-sg-${name}-${Date.now()}`;
31
+ }
32
+
33
+ // Helper — build a SendGrid event payload
34
+ function sgEvent({ id, type, email, timestamp, asmGroupId, bounceClassification }) {
35
+ return {
36
+ sg_event_id: id,
37
+ event: type,
38
+ email,
39
+ timestamp: timestamp || Math.floor(Date.now() / 1000),
40
+ ...(asmGroupId !== undefined ? { asm_group_id: asmGroupId } : {}),
41
+ ...(bounceClassification !== undefined ? { bounce_classification: bounceClassification } : {}),
42
+ };
43
+ }
44
+
45
+ module.exports = {
46
+ description: 'Marketing webhook endpoint (SendGrid)',
47
+ type: 'group',
48
+ timeout: 30000,
49
+
50
+ tests: [
51
+ // ─── Dispatcher auth + validation ───
52
+
53
+ {
54
+ name: 'rejects-missing-provider',
55
+ auth: 'none',
56
+ async run({ http, assert }) {
57
+ const response = await http.as('none').post('backend-manager/marketing/webhook', []);
58
+ assert.isError(response, 400, 'Should reject missing provider');
59
+ },
60
+ },
61
+
62
+ {
63
+ name: 'rejects-missing-key',
64
+ auth: 'none',
65
+ async run({ http, assert }) {
66
+ const response = await http.as('none').post('backend-manager/marketing/webhook?provider=sendgrid', []);
67
+ assert.isError(response, 401, 'Should reject missing key');
68
+ },
69
+ },
70
+
71
+ {
72
+ name: 'rejects-invalid-key',
73
+ auth: 'none',
74
+ async run({ http, assert }) {
75
+ const response = await http.as('none').post('backend-manager/marketing/webhook?provider=sendgrid&key=wrong-key', []);
76
+ assert.isError(response, 401, 'Should reject invalid key');
77
+ },
78
+ },
79
+
80
+ {
81
+ name: 'rejects-unknown-provider',
82
+ auth: 'none',
83
+ async run({ http, assert }) {
84
+ const response = await http.as('none').post(
85
+ `backend-manager/marketing/webhook?provider=unknown&key=${process.env.BACKEND_MANAGER_WEBHOOK_KEY}`,
86
+ []
87
+ );
88
+ assert.isError(response, 400, 'Should reject unknown provider');
89
+ },
90
+ },
91
+
92
+ {
93
+ name: 'ignores-mismatched-brand',
94
+ auth: 'none',
95
+ async run({ http, assert }) {
96
+ // Brand filter should silently ignore (200 with ignored: true), not error
97
+ const response = await http.as('none').post(
98
+ `backend-manager/marketing/webhook?provider=sendgrid&key=${process.env.BACKEND_MANAGER_WEBHOOK_KEY}&brand=some-other-brand-that-does-not-exist`,
99
+ []
100
+ );
101
+ assert.isSuccess(response, 'Should silently ignore mismatched brand (200 OK)');
102
+ assert.propertyEquals(response, 'data.ignored', true, 'Response should indicate ignored');
103
+ },
104
+ },
105
+
106
+ // ─── SendGrid processor — supported events ───
107
+
108
+ {
109
+ name: 'sendgrid-group-unsubscribe-writes-consent',
110
+ auth: 'none',
111
+ async run({ http, firestore, assert, accounts }) {
112
+ const uid = accounts['journey-webhook-revoke'].uid;
113
+ const email = accounts['journey-webhook-revoke'].email;
114
+ const eventId = sgEventId('group-unsub');
115
+ const eventTimestamp = Math.floor(Date.now() / 1000);
116
+
117
+ const response = await http.as('none').post(
118
+ `backend-manager/marketing/webhook?provider=sendgrid&key=${process.env.BACKEND_MANAGER_WEBHOOK_KEY}`,
119
+ [sgEvent({ id: eventId, type: 'group_unsubscribe', email, timestamp: eventTimestamp, asmGroupId: 25928 })]
120
+ );
121
+
122
+ assert.isSuccess(response, `Webhook should accept group_unsubscribe: ${JSON.stringify(response, null, 2)}`);
123
+ assert.propertyEquals(response, 'data.processed', 1, 'Should report 1 event processed');
124
+
125
+ // User doc should now show revoked marketing with source=sendgrid
126
+ const userDoc = await firestore.get(`users/${uid}`);
127
+ assert.equal(userDoc?.consent?.marketing?.status, 'revoked', 'marketing.status should be revoked');
128
+ assert.equal(userDoc?.consent?.marketing?.revokedAt?.source, 'sendgrid', 'revokedAt.source should be sendgrid');
129
+ assert.equal(userDoc?.consent?.marketing?.revokedAt?.timestampUNIX, eventTimestamp, 'revokedAt.timestampUNIX should match event timestamp');
130
+ },
131
+ },
132
+
133
+ {
134
+ name: 'sendgrid-unsubscribe-event-handled',
135
+ auth: 'none',
136
+ async run({ http, firestore, assert, accounts }) {
137
+ const uid = accounts['journey-webhook-revoke'].uid;
138
+ const email = accounts['journey-webhook-revoke'].email;
139
+ const eventId = sgEventId('unsub');
140
+
141
+ const response = await http.as('none').post(
142
+ `backend-manager/marketing/webhook?provider=sendgrid&key=${process.env.BACKEND_MANAGER_WEBHOOK_KEY}`,
143
+ [sgEvent({ id: eventId, type: 'unsubscribe', email })]
144
+ );
145
+
146
+ assert.isSuccess(response);
147
+ assert.propertyEquals(response, 'data.processed', 1, 'Should process the unsubscribe event');
148
+
149
+ const userDoc = await firestore.get(`users/${uid}`);
150
+ assert.equal(userDoc?.consent?.marketing?.status, 'revoked', 'marketing.status should be revoked');
151
+ assert.equal(userDoc?.consent?.marketing?.revokedAt?.source, 'sendgrid', 'source should be sendgrid');
152
+ },
153
+ },
154
+
155
+ {
156
+ name: 'sendgrid-spamreport-event-handled',
157
+ auth: 'none',
158
+ async run({ http, firestore, assert, accounts }) {
159
+ const uid = accounts['journey-webhook-revoke'].uid;
160
+ const email = accounts['journey-webhook-revoke'].email;
161
+ const eventId = sgEventId('spamreport');
162
+
163
+ const response = await http.as('none').post(
164
+ `backend-manager/marketing/webhook?provider=sendgrid&key=${process.env.BACKEND_MANAGER_WEBHOOK_KEY}`,
165
+ [sgEvent({ id: eventId, type: 'spamreport', email })]
166
+ );
167
+
168
+ assert.isSuccess(response);
169
+ assert.propertyEquals(response, 'data.processed', 1, 'Spamreport should be treated as a revoke');
170
+
171
+ const userDoc = await firestore.get(`users/${uid}`);
172
+ assert.equal(userDoc?.consent?.marketing?.status, 'revoked');
173
+ },
174
+ },
175
+
176
+ {
177
+ name: 'sendgrid-hard-bounce-event-handled',
178
+ auth: 'none',
179
+ async run({ http, firestore, assert, accounts }) {
180
+ const uid = accounts['journey-webhook-revoke'].uid;
181
+ const email = accounts['journey-webhook-revoke'].email;
182
+ const eventId = sgEventId('hard-bounce');
183
+
184
+ // Only hard bounces (bounce_classification='Invalid Address') revoke consent.
185
+ const response = await http.as('none').post(
186
+ `backend-manager/marketing/webhook?provider=sendgrid&key=${process.env.BACKEND_MANAGER_WEBHOOK_KEY}`,
187
+ [sgEvent({ id: eventId, type: 'bounce', email, bounceClassification: 'Invalid Address' })]
188
+ );
189
+
190
+ assert.isSuccess(response);
191
+ assert.propertyEquals(response, 'data.processed', 1, 'Hard bounce should be treated as a revoke');
192
+
193
+ const userDoc = await firestore.get(`users/${uid}`);
194
+ assert.equal(userDoc?.consent?.marketing?.status, 'revoked');
195
+ },
196
+ },
197
+
198
+ {
199
+ name: 'sendgrid-dropped-hard-bounce-handled',
200
+ auth: 'none',
201
+ async run({ http, firestore, assert, accounts }) {
202
+ const uid = accounts['journey-webhook-revoke'].uid;
203
+ const email = accounts['journey-webhook-revoke'].email;
204
+ const eventId = sgEventId('dropped');
205
+
206
+ // 'dropped' follows the same classification filter as 'bounce'.
207
+ const response = await http.as('none').post(
208
+ `backend-manager/marketing/webhook?provider=sendgrid&key=${process.env.BACKEND_MANAGER_WEBHOOK_KEY}`,
209
+ [sgEvent({ id: eventId, type: 'dropped', email, bounceClassification: 'Invalid Address' })]
210
+ );
211
+
212
+ assert.isSuccess(response);
213
+ assert.propertyEquals(response, 'data.processed', 1, 'Dropped with Invalid Address should be treated as a revoke');
214
+
215
+ const userDoc = await firestore.get(`users/${uid}`);
216
+ assert.equal(userDoc?.consent?.marketing?.status, 'revoked');
217
+ },
218
+ },
219
+
220
+ // ─── SendGrid processor — events we ignore ───
221
+
222
+ {
223
+ name: 'sendgrid-technical-bounce-ignored',
224
+ auth: 'none',
225
+ async run({ http, assert, accounts }) {
226
+ const email = accounts['journey-webhook-revoke'].email;
227
+ const eventId = sgEventId('technical-bounce');
228
+
229
+ // Technical bounces (DMARC, TLS, DNS) are sender-side issues — the recipient's
230
+ // mailbox is still valid, so consent must NOT be revoked.
231
+ const response = await http.as('none').post(
232
+ `backend-manager/marketing/webhook?provider=sendgrid&key=${process.env.BACKEND_MANAGER_WEBHOOK_KEY}`,
233
+ [sgEvent({ id: eventId, type: 'bounce', email, bounceClassification: 'Technical Failure' })]
234
+ );
235
+
236
+ assert.isSuccess(response, 'Should accept the request (not error) but ignore the event');
237
+ assert.propertyEquals(response, 'data.processed', 0, 'Technical bounce should not be processed');
238
+ assert.propertyEquals(response, 'data.skipped', 1, '1 event should be skipped');
239
+ },
240
+ },
241
+
242
+ {
243
+ name: 'sendgrid-bounce-without-classification-ignored',
244
+ auth: 'none',
245
+ async run({ http, assert, accounts }) {
246
+ const email = accounts['journey-webhook-revoke'].email;
247
+ const eventId = sgEventId('unclassified-bounce');
248
+
249
+ // No bounce_classification — can't confirm a hard bounce, so skip.
250
+ const response = await http.as('none').post(
251
+ `backend-manager/marketing/webhook?provider=sendgrid&key=${process.env.BACKEND_MANAGER_WEBHOOK_KEY}`,
252
+ [sgEvent({ id: eventId, type: 'bounce', email })]
253
+ );
254
+
255
+ assert.isSuccess(response, 'Should accept the request (not error) but ignore the event');
256
+ assert.propertyEquals(response, 'data.processed', 0, 'Unclassified bounce should not be processed');
257
+ assert.propertyEquals(response, 'data.skipped', 1, '1 event should be skipped');
258
+ },
259
+ },
260
+
261
+ {
262
+ name: 'sendgrid-delivered-event-ignored',
263
+ auth: 'none',
264
+ async run({ http, firestore, assert, accounts }) {
265
+ const email = accounts['journey-webhook-revoke'].email;
266
+ const eventId = sgEventId('delivered');
267
+
268
+ const response = await http.as('none').post(
269
+ `backend-manager/marketing/webhook?provider=sendgrid&key=${process.env.BACKEND_MANAGER_WEBHOOK_KEY}`,
270
+ [sgEvent({ id: eventId, type: 'delivered', email })]
271
+ );
272
+
273
+ assert.isSuccess(response, 'Should accept the request (not error) but ignore the event');
274
+ assert.propertyEquals(response, 'data.processed', 0, 'No events should be processed');
275
+ assert.propertyEquals(response, 'data.skipped', 1, '1 event should be skipped');
276
+ },
277
+ },
278
+
279
+ {
280
+ name: 'sendgrid-open-event-ignored',
281
+ auth: 'none',
282
+ async run({ http, assert, accounts }) {
283
+ const email = accounts['journey-webhook-revoke'].email;
284
+ const eventId = sgEventId('open');
285
+
286
+ const response = await http.as('none').post(
287
+ `backend-manager/marketing/webhook?provider=sendgrid&key=${process.env.BACKEND_MANAGER_WEBHOOK_KEY}`,
288
+ [sgEvent({ id: eventId, type: 'open', email })]
289
+ );
290
+
291
+ assert.isSuccess(response);
292
+ assert.propertyEquals(response, 'data.processed', 0, 'Open events should be ignored');
293
+ },
294
+ },
295
+
296
+ // ─── Email not mapped to a user ───
297
+
298
+ {
299
+ name: 'sendgrid-unknown-email-silent-skip',
300
+ auth: 'none',
301
+ async run({ http, assert }) {
302
+ // Email that doesn't match any user in this brand's Firestore — shared SendGrid scenario
303
+ const eventId = sgEventId('unknown-email');
304
+
305
+ const response = await http.as('none').post(
306
+ `backend-manager/marketing/webhook?provider=sendgrid&key=${process.env.BACKEND_MANAGER_WEBHOOK_KEY}`,
307
+ [sgEvent({ id: eventId, type: 'group_unsubscribe', email: '_test.never-existed@example.com' })]
308
+ );
309
+
310
+ // Dispatcher still runs the handler (which returns handled:false). From the
311
+ // dispatcher's POV this counts as 'processed=1' since the handler didn't throw.
312
+ // The handler's internal "user-not-found" branch is silent by design.
313
+ assert.isSuccess(response, 'Should accept unknown-email gracefully');
314
+ assert.propertyEquals(response, 'data.failed', 0, 'No failures for unknown email');
315
+ },
316
+ },
317
+
318
+ // ─── Batched events ───
319
+
320
+ {
321
+ name: 'sendgrid-batched-events-processed-independently',
322
+ auth: 'none',
323
+ async run({ http, firestore, assert, accounts }) {
324
+ const uid = accounts['journey-webhook-revoke'].uid;
325
+ const email = accounts['journey-webhook-revoke'].email;
326
+ const e1 = sgEventId('batch-1');
327
+ const e2 = sgEventId('batch-2');
328
+ const e3 = sgEventId('batch-3');
329
+
330
+ const response = await http.as('none').post(
331
+ `backend-manager/marketing/webhook?provider=sendgrid&key=${process.env.BACKEND_MANAGER_WEBHOOK_KEY}`,
332
+ [
333
+ sgEvent({ id: e1, type: 'group_unsubscribe', email }),
334
+ sgEvent({ id: e2, type: 'open', email }), // ignored — unsupported type
335
+ sgEvent({ id: e3, type: 'spamreport', email }),
336
+ ]
337
+ );
338
+
339
+ assert.isSuccess(response);
340
+ assert.propertyEquals(response, 'data.processed', 2, '2 supported events should be processed');
341
+ assert.propertyEquals(response, 'data.skipped', 1, '1 unsupported event should be skipped');
342
+
343
+ // User doc should be revoked
344
+ const userDoc = await firestore.get(`users/${uid}`);
345
+ assert.equal(userDoc?.consent?.marketing?.status, 'revoked');
346
+ },
347
+ },
348
+
349
+ // ─── Idempotent re-delivery (no dedup ledger) ───
350
+
351
+ {
352
+ name: 'sendgrid-duplicate-event-reprocessed-idempotently',
353
+ auth: 'none',
354
+ async run({ http, firestore, assert, accounts }) {
355
+ const uid = accounts['journey-webhook-revoke'].uid;
356
+ const email = accounts['journey-webhook-revoke'].email;
357
+ const eventId = sgEventId('duplicate');
358
+
359
+ // First delivery
360
+ const response1 = await http.as('none').post(
361
+ `backend-manager/marketing/webhook?provider=sendgrid&key=${process.env.BACKEND_MANAGER_WEBHOOK_KEY}`,
362
+ [sgEvent({ id: eventId, type: 'group_unsubscribe', email })]
363
+ );
364
+ assert.isSuccess(response1);
365
+ assert.propertyEquals(response1, 'data.processed', 1, 'First delivery should process');
366
+
367
+ // Second delivery — same eventId. With no dedup ledger the handler runs
368
+ // again, but the revoke is idempotent so the end state is unchanged.
369
+ const response2 = await http.as('none').post(
370
+ `backend-manager/marketing/webhook?provider=sendgrid&key=${process.env.BACKEND_MANAGER_WEBHOOK_KEY}`,
371
+ [sgEvent({ id: eventId, type: 'group_unsubscribe', email })]
372
+ );
373
+ assert.isSuccess(response2);
374
+ assert.propertyEquals(response2, 'data.processed', 1, 'Re-delivery reprocesses (idempotent), not skipped');
375
+
376
+ const userDoc = await firestore.get(`users/${uid}`);
377
+ assert.equal(userDoc?.consent?.marketing?.status, 'revoked', 'User remains revoked after re-delivery');
378
+ },
379
+ },
380
+
381
+ // ─── Missing event ID — still processed (no dedup requirement) ───
382
+
383
+ {
384
+ name: 'sendgrid-event-without-eventId-processed',
385
+ auth: 'none',
386
+ async run({ http, firestore, assert, accounts }) {
387
+ const uid = accounts['journey-webhook-revoke'].uid;
388
+ const email = accounts['journey-webhook-revoke'].email;
389
+
390
+ const response = await http.as('none').post(
391
+ `backend-manager/marketing/webhook?provider=sendgrid&key=${process.env.BACKEND_MANAGER_WEBHOOK_KEY}`,
392
+ [{ event: 'group_unsubscribe', email, timestamp: Math.floor(Date.now() / 1000) }] // NO sg_event_id
393
+ );
394
+
395
+ assert.isSuccess(response, 'Should accept the request');
396
+ assert.propertyEquals(response, 'data.processed', 1, 'Event without eventId is still processed (no dedup needed)');
397
+
398
+ const userDoc = await firestore.get(`users/${uid}`);
399
+ assert.equal(userDoc?.consent?.marketing?.status, 'revoked', 'User should be revoked');
400
+ },
401
+ },
402
+
403
+ // ──────────────────────────────────────────────────────────────────────
404
+ // Beehiiv processor tests
405
+ // ──────────────────────────────────────────────────────────────────────
406
+
407
+ {
408
+ name: 'beehiiv-subscription-unsubscribed-writes-consent',
409
+ auth: 'none',
410
+ async run({ http, firestore, assert, accounts, config, skip }) {
411
+ const uid = accounts['journey-webhook-revoke'].uid;
412
+ const email = accounts['journey-webhook-revoke'].email;
413
+ const eventId = `_test-bh-unsub-${Date.now()}`;
414
+ const eventISO = new Date().toISOString();
415
+ const publicationId = config.marketing?.newsletter?.publicationId;
416
+
417
+ if (!publicationId) {
418
+ return skip('No Beehiiv publication ID configured for this brand');
419
+ }
420
+
421
+ const response = await http.as('none').post(
422
+ `backend-manager/marketing/webhook?provider=beehiiv&key=${process.env.BACKEND_MANAGER_WEBHOOK_KEY}`,
423
+ {
424
+ id: eventId,
425
+ event: 'subscription.unsubscribed',
426
+ email,
427
+ publication_id: publicationId,
428
+ created_at: eventISO,
429
+ }
430
+ );
431
+
432
+ assert.isSuccess(response, `Beehiiv unsub should succeed: ${JSON.stringify(response, null, 2)}`);
433
+ assert.propertyEquals(response, 'data.processed', 1, 'Should process 1 event');
434
+
435
+ const userDoc = await firestore.get(`users/${uid}`);
436
+ assert.equal(userDoc?.consent?.marketing?.status, 'revoked', 'marketing.status should be revoked');
437
+ assert.equal(userDoc?.consent?.marketing?.revokedAt?.source, 'beehiiv', 'revokedAt.source should be beehiiv');
438
+ assert.ok(userDoc?.consent?.marketing?.revokedAt?.timestamp, 'revokedAt.timestamp should be set');
439
+ },
440
+ },
441
+
442
+ {
443
+ name: 'beehiiv-subscription-deleted-handled',
444
+ auth: 'none',
445
+ async run({ http, firestore, assert, accounts, config }) {
446
+ const uid = accounts['journey-webhook-revoke'].uid;
447
+ const email = accounts['journey-webhook-revoke'].email;
448
+ const eventId = `_test-bh-deleted-${Date.now()}`;
449
+ const publicationId = config.marketing?.newsletter?.publicationId;
450
+
451
+ const response = await http.as('none').post(
452
+ `backend-manager/marketing/webhook?provider=beehiiv&key=${process.env.BACKEND_MANAGER_WEBHOOK_KEY}`,
453
+ {
454
+ id: eventId,
455
+ event: 'subscription.deleted',
456
+ email,
457
+ publication_id: publicationId,
458
+ created_at: new Date().toISOString(),
459
+ }
460
+ );
461
+
462
+ assert.isSuccess(response);
463
+ assert.propertyEquals(response, 'data.processed', 1, 'subscription.deleted should be processed as a revoke');
464
+
465
+ const userDoc = await firestore.get(`users/${uid}`);
466
+ assert.equal(userDoc?.consent?.marketing?.status, 'revoked');
467
+ assert.equal(userDoc?.consent?.marketing?.revokedAt?.source, 'beehiiv');
468
+ },
469
+ },
470
+
471
+ {
472
+ name: 'beehiiv-subscription-paused-handled',
473
+ auth: 'none',
474
+ async run({ http, firestore, assert, accounts, config }) {
475
+ const uid = accounts['journey-webhook-revoke'].uid;
476
+ const email = accounts['journey-webhook-revoke'].email;
477
+ const eventId = `_test-bh-paused-${Date.now()}`;
478
+ const publicationId = config.marketing?.newsletter?.publicationId;
479
+
480
+ const response = await http.as('none').post(
481
+ `backend-manager/marketing/webhook?provider=beehiiv&key=${process.env.BACKEND_MANAGER_WEBHOOK_KEY}`,
482
+ {
483
+ id: eventId,
484
+ event: 'subscription.paused',
485
+ email,
486
+ publication_id: publicationId,
487
+ created_at: new Date().toISOString(),
488
+ }
489
+ );
490
+
491
+ assert.isSuccess(response);
492
+ assert.propertyEquals(response, 'data.processed', 1, 'subscription.paused should be processed as a revoke');
493
+
494
+ const userDoc = await firestore.get(`users/${uid}`);
495
+ assert.equal(userDoc?.consent?.marketing?.status, 'revoked');
496
+ },
497
+ },
498
+
499
+ {
500
+ name: 'beehiiv-publication-mismatch-silent-skip',
501
+ auth: 'none',
502
+ async run({ http, firestore, assert, accounts }) {
503
+ // Send an event with a publication_id that does NOT match this brand's pub.
504
+ // Simulates the shared-devbeans scenario where the parent forwarder fans
505
+ // an event to brands that don't share the publication — they silent-skip.
506
+ const email = accounts['journey-webhook-revoke'].email;
507
+ const eventId = `_test-bh-pubmismatch-${Date.now()}`;
508
+
509
+ // Snapshot revokedAt BEFORE the request so we can prove the pub-mismatch
510
+ // handler didn't write anything new. (The basic account may already have
511
+ // a beehiiv-sourced revoke from a prior test that legitimately fired.)
512
+ const beforeDoc = await firestore.get(`users/${accounts['journey-webhook-revoke'].uid}`);
513
+ const beforeRevokedAt = beforeDoc?.consent?.marketing?.revokedAt || null;
514
+
515
+ const response = await http.as('none').post(
516
+ `backend-manager/marketing/webhook?provider=beehiiv&key=${process.env.BACKEND_MANAGER_WEBHOOK_KEY}`,
517
+ {
518
+ id: eventId,
519
+ event: 'subscription.unsubscribed',
520
+ email,
521
+ publication_id: 'pub_does-not-belong-to-this-brand-xxxxxxxxxxxxxx',
522
+ created_at: new Date().toISOString(),
523
+ }
524
+ );
525
+
526
+ // The dispatcher counts this as 'processed' from its POV (the handler
527
+ // ran without error), but the handler returned
528
+ // { handled: false, reason: 'publication-mismatch' }.
529
+ // What matters: the user doc should NOT have been mutated.
530
+ assert.isSuccess(response, 'Pub-mismatch event should be accepted gracefully');
531
+
532
+ // Reload the user doc and verify revokedAt is byte-equivalent to before —
533
+ // pub-mismatch must not write a new revoke entry.
534
+ const afterDoc = await firestore.get(`users/${accounts['journey-webhook-revoke'].uid}`);
535
+ const afterRevokedAt = afterDoc?.consent?.marketing?.revokedAt || null;
536
+
537
+ assert.deepEqual(
538
+ afterRevokedAt,
539
+ beforeRevokedAt,
540
+ 'consent.marketing.revokedAt must be UNCHANGED after a pub-mismatch event (handler should silent-skip)'
541
+ );
542
+ },
543
+ },
544
+
545
+ {
546
+ name: 'beehiiv-unknown-email-silent-skip',
547
+ auth: 'none',
548
+ async run({ http, assert, config }) {
549
+ // Email that doesn't map to any user — shared publication scenario where
550
+ // multiple brands receive the same event but only one has the user.
551
+ const publicationId = config.marketing?.newsletter?.publicationId;
552
+ const eventId = `_test-bh-unknown-${Date.now()}`;
553
+
554
+ const response = await http.as('none').post(
555
+ `backend-manager/marketing/webhook?provider=beehiiv&key=${process.env.BACKEND_MANAGER_WEBHOOK_KEY}`,
556
+ {
557
+ id: eventId,
558
+ event: 'subscription.unsubscribed',
559
+ email: '_test.no-such-user@example.com',
560
+ publication_id: publicationId,
561
+ created_at: new Date().toISOString(),
562
+ }
563
+ );
564
+
565
+ assert.isSuccess(response, 'Unknown email should not error');
566
+ assert.propertyEquals(response, 'data.failed', 0, 'No failures for unknown email');
567
+ },
568
+ },
569
+
570
+ {
571
+ name: 'beehiiv-unsupported-event-ignored',
572
+ auth: 'none',
573
+ async run({ http, assert, accounts, config }) {
574
+ // 'subscription.created' (new signup) is NOT a revoke — should be ignored.
575
+ const email = accounts['journey-webhook-revoke'].email;
576
+ const publicationId = config.marketing?.newsletter?.publicationId;
577
+ const eventId = `_test-bh-created-${Date.now()}`;
578
+
579
+ const response = await http.as('none').post(
580
+ `backend-manager/marketing/webhook?provider=beehiiv&key=${process.env.BACKEND_MANAGER_WEBHOOK_KEY}`,
581
+ {
582
+ id: eventId,
583
+ event: 'subscription.created',
584
+ email,
585
+ publication_id: publicationId,
586
+ created_at: new Date().toISOString(),
587
+ }
588
+ );
589
+
590
+ assert.isSuccess(response);
591
+ assert.propertyEquals(response, 'data.processed', 0, 'Unsupported events should not be processed');
592
+ assert.propertyEquals(response, 'data.skipped', 1, 'Unsupported events should be skipped');
593
+ },
594
+ },
595
+
596
+ {
597
+ name: 'beehiiv-duplicate-event-reprocessed-idempotently',
598
+ auth: 'none',
599
+ async run({ http, firestore, assert, accounts, config, skip }) {
600
+ const uid = accounts['journey-webhook-revoke'].uid;
601
+ const email = accounts['journey-webhook-revoke'].email;
602
+ const publicationId = config.marketing?.newsletter?.publicationId;
603
+ const eventId = `_test-bh-dup-${Date.now()}`;
604
+
605
+ if (!publicationId) {
606
+ return skip('No Beehiiv publication ID configured for this brand');
607
+ }
608
+
609
+ const payload = {
610
+ id: eventId,
611
+ event: 'subscription.unsubscribed',
612
+ email,
613
+ publication_id: publicationId,
614
+ created_at: new Date().toISOString(),
615
+ };
616
+
617
+ // First delivery
618
+ const r1 = await http.as('none').post(
619
+ `backend-manager/marketing/webhook?provider=beehiiv&key=${process.env.BACKEND_MANAGER_WEBHOOK_KEY}`,
620
+ payload
621
+ );
622
+ assert.isSuccess(r1);
623
+ assert.propertyEquals(r1, 'data.processed', 1, 'First delivery should process');
624
+
625
+ // Second delivery — same id. No dedup ledger, so it reprocesses; the
626
+ // revoke is idempotent so the end state is unchanged.
627
+ const r2 = await http.as('none').post(
628
+ `backend-manager/marketing/webhook?provider=beehiiv&key=${process.env.BACKEND_MANAGER_WEBHOOK_KEY}`,
629
+ payload
630
+ );
631
+ assert.isSuccess(r2);
632
+ assert.propertyEquals(r2, 'data.processed', 1, 'Re-delivery reprocesses (idempotent), not skipped');
633
+
634
+ const userDoc = await firestore.get(`users/${uid}`);
635
+ assert.equal(userDoc?.consent?.marketing?.status, 'revoked', 'User remains revoked after re-delivery');
636
+ },
637
+ },
638
+ ],
639
+ };