Compare commits

..
123 Commits
Author SHA1 Message Date
Dries Augustyns d75aed81e1 Merge pull request #295 from useplunk/release-please--branches--next--components--plunk 2026-03-05 11:58:38 +01:00
github-actions[bot] 0cbaa8fc66 chore(next): release 0.7.0 2026-03-05 10:27:05 +00:00
Dries Augustyns 0686b3a3f2 Merge pull request #307 from useplunk/dependabot/npm_and_yarn/tar-7.5.10
chore(deps): bump tar from 7.5.9 to 7.5.10
2026-03-05 11:26:52 +01:00
Dries Augustyns 9b15b93b96 Merge pull request #281 from 5h0ov/multipart/related-support-embed-image
feat(api): support inline images in emails using Content-ID
2026-03-05 11:26:41 +01:00
dependabot[bot] 8f2510f5ec chore(deps): bump tar from 7.5.9 to 7.5.10
Bumps [tar](https://github.com/isaacs/node-tar) from 7.5.9 to 7.5.10.
- [Release notes](https://github.com/isaacs/node-tar/releases)
- [Changelog](https://github.com/isaacs/node-tar/blob/main/CHANGELOG.md)
- [Commits](https://github.com/isaacs/node-tar/compare/v7.5.9...v7.5.10)

---
updated-dependencies:
- dependency-name: tar
  dependency-version: 7.5.10
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <[email protected]>
2026-03-05 10:03:03 +00:00
Dries Augustyns e196d798c5 Merge pull request #293 from useplunk/dependabot/npm_and_yarn/tar-7.5.9 2026-03-05 10:18:30 +01:00
Dries Augustyns 777a12ec89 Merge pull request #296 from useplunk/dependabot/npm_and_yarn/ajv-6.14.0 2026-03-05 10:18:21 +01:00
Dries Augustyns 6c6af775bc Merge pull request #301 from useplunk/dependabot/npm_and_yarn/rollup-4.59.0 2026-03-05 10:18:12 +01:00
Dries Augustyns 4f8c9f029d Merge pull request #305 from useplunk/dependabot/npm_and_yarn/mailparser-3.9.3 2026-03-05 10:18:03 +01:00
Dries Augustyns 8f72994b46 Merge pull request #306 from useplunk/dependabot/npm_and_yarn/multer-2.1.1 2026-03-05 10:17:43 +01:00
dependabot[bot] d162f255c2 chore(deps): bump multer from 2.0.2 to 2.1.1
Bumps [multer](https://github.com/expressjs/multer) from 2.0.2 to 2.1.1.
- [Release notes](https://github.com/expressjs/multer/releases)
- [Changelog](https://github.com/expressjs/multer/blob/main/CHANGELOG.md)
- [Commits](https://github.com/expressjs/multer/compare/v2.0.2...v2.1.1)

---
updated-dependencies:
- dependency-name: multer
  dependency-version: 2.1.1
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <[email protected]>
2026-03-05 07:56:38 +00:00
dependabot[bot] c8e252fefd chore(deps): bump mailparser from 3.9.1 to 3.9.3
Bumps [mailparser](https://github.com/nodemailer/mailparser) from 3.9.1 to 3.9.3.
- [Release notes](https://github.com/nodemailer/mailparser/releases)
- [Changelog](https://github.com/nodemailer/mailparser/blob/master/CHANGELOG.md)
- [Commits](https://github.com/nodemailer/mailparser/compare/v3.9.1...v3.9.3)

---
updated-dependencies:
- dependency-name: mailparser
  dependency-version: 3.9.3
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <[email protected]>
2026-03-04 22:23:43 +00:00
Dries Augustyns b8f1ad9ab5 fix: Verify SNS URL before sending fetch request 2026-03-03 08:02:36 +01:00
dependabot[bot] 708ab506f1 chore(deps): bump rollup from 4.53.3 to 4.59.0
Bumps [rollup](https://github.com/rollup/rollup) from 4.53.3 to 4.59.0.
- [Release notes](https://github.com/rollup/rollup/releases)
- [Changelog](https://github.com/rollup/rollup/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rollup/rollup/compare/v4.53.3...v4.59.0)

---
updated-dependencies:
- dependency-name: rollup
  dependency-version: 4.59.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <[email protected]>
2026-02-28 21:10:59 +00:00
Dries Augustyns ec1f4c9374 fix: Support any locale on creation 2026-02-26 20:57:14 +01:00
Dries Augustyns 5528288c7b Merge branch 'next' of https://github.com/useplunk/plunk into next 2026-02-23 21:45:25 +01:00
Dries Augustyns 7bd098bdd0 fix: Add support for STATIC segment type in CampaignService 2026-02-23 21:45:17 +01:00
Dries Augustyns cbea263a91 Merge pull request #298 from josephsellers/fix/cookie-domain-local-tld 2026-02-23 14:17:36 +01:00
Dries Augustyns e8a247fe12 docs: Static segments 2026-02-23 14:03:05 +01:00
Dries Augustyns 4b51e386e3 feat: Static segments 2026-02-23 13:57:32 +01:00
josephsellers 59aa7845ba fix: correct cookie domain for .local TLD hostnames
getCookieDomain() returns '.localhost' for hostnames ending in '.local'
(e.g., app.plunk.local), causing the browser to reject the cookie
because the domain doesn't match the request origin.

Split the .localhost and .local cases so that .local hostnames return
the actual base domain (e.g., .plunk.local).
2026-02-22 16:01:25 +00:00
dependabot[bot] 5600c49bb6 chore(deps): bump ajv from 6.12.6 to 6.14.0
Bumps [ajv](https://github.com/ajv-validator/ajv) from 6.12.6 to 6.14.0.
- [Release notes](https://github.com/ajv-validator/ajv/releases)
- [Commits](https://github.com/ajv-validator/ajv/compare/v6.12.6...v6.14.0)

---
updated-dependencies:
- dependency-name: ajv
  dependency-version: 6.14.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <[email protected]>
2026-02-22 13:46:46 +00:00
Dries Augustyns 21af8fe05e fix: Correctly set domain status on manual verify 2026-02-21 08:41:24 +01:00
Dries Augustyns 2c4d95e604 fix: Do not unsubscribe existing contacts 2026-02-20 16:58:17 +01:00
Dries Augustyns 64bd094b47 feat: Sort projects alphabetically in the dashboard and fix layout 2026-02-20 16:01:57 +01:00
dependabot[bot] 53b33bbd36 chore(deps): bump tar from 7.5.7 to 7.5.9
Bumps [tar](https://github.com/isaacs/node-tar) from 7.5.7 to 7.5.9.
- [Release notes](https://github.com/isaacs/node-tar/releases)
- [Changelog](https://github.com/isaacs/node-tar/blob/main/CHANGELOG.md)
- [Commits](https://github.com/isaacs/node-tar/compare/v7.5.7...v7.5.9)

---
updated-dependencies:
- dependency-name: tar
  dependency-version: 7.5.9
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <[email protected]>
2026-02-19 19:00:34 +00:00
Dries Augustyns 5fa9b9dda5 Merge pull request #291 from useplunk/release-please--branches--next--components--plunk
chore(next): release 0.6.0
2026-02-19 19:57:50 +01:00
Dries Augustyns 4bc5424815 Merge branch 'next' of https://github.com/useplunk/plunk into next 2026-02-19 19:51:28 +01:00
Dries Augustyns 573e2e8449 security: Enhance job status retrieval with project authorization 2026-02-19 19:51:22 +01:00
github-actions[bot] 00ae942c3c chore(next): release 0.6.0 2026-02-19 13:15:08 +00:00
Dries Augustyns 9c69c7a36e Merge pull request #292 from RyanCasas/patch-1
feat(i18n): Add Spanish language
2026-02-19 14:14:47 +01:00
Ryan Casas 9568b7d345 Add Spanish translations to i18n index 2026-02-19 12:16:40 +01:00
Ryan Casas 6bba9b6199 Add Spanish localization for email preferences 2026-02-19 12:10:29 +01:00
Ryan Casas 2f55d32485 Add Spanish (Spain) language support 2026-02-19 12:05:07 +01:00
Dries Augustyns eec37ecb31 feat: Ability to change workflow trigger 2026-02-18 20:26:41 +01:00
Dries Augustyns f947ee6f22 feat: Add dedicated received type 2026-02-18 16:24:55 +01:00
Dries Augustyns 3330d83d08 feat: Add billing for inbound 2026-02-18 15:38:41 +01:00
Dries Augustyns de7ed84fcf feat: Add billing for inbound 2026-02-18 15:23:31 +01:00
Dries Augustyns e639c72e8b fix: Enhance email bounce notification with latest bounce details 2026-02-18 10:20:58 +01:00
Dries Augustyns 43ea660d52 chore: Clean up linting 2026-02-18 10:08:23 +01:00
Dries Augustyns 1f85d448e2 chore: Updated terms, privacy and dpa 2026-02-18 10:00:54 +01:00
Dries Augustyns e7f168c373 Merge branch 'next' of https://github.com/useplunk/plunk into next 2026-02-18 08:34:55 +01:00
Dries Augustyns b42698616a docs: Add receiving emails functionality and update DNS records documentation 2026-02-18 08:34:49 +01:00
Dries Augustyns a00473314f Merge pull request #255 from useplunk/release-please--branches--next--components--plunk
chore(next): release 0.5.0
2026-02-17 19:16:13 +01:00
github-actions[bot] 2dabcb2419 chore(next): release 0.5.0 2026-02-17 18:09:45 +00:00
Dries Augustyns d9ae171cc7 chore: fix linting errors 2026-02-17 19:09:01 +01:00
Dries Augustyns e4e334c77a fix: Center "Add Step" nodes below parent nodes and update positions on drag 2026-02-17 19:06:22 +01:00
Dries Augustyns 78d3d224af feat: Add support for custom email recipients in workflow steps 2026-02-17 18:57:15 +01:00
Dries Augustyns f9b1354460 fix: Remove 'Optional' label from MAIL FROM Domain and Inbound Email headings 2026-02-17 18:19:58 +01:00
Dries Augustyns 95e5ec8485 Merge pull request #290 from useplunk/inbound
Inbound
2026-02-17 16:56:29 +01:00
Dries Augustyns d050b55baa feat: Add inbound handling 2026-02-17 16:52:56 +01:00
Dries Augustyns 7964563b62 feat: Add advanced DNS configuration 2026-02-17 16:33:34 +01:00
Dries Augustyns e01dc4066c Merge pull request #289 from useplunk/inbound
feat: Add initial handling in webhook for inbound
2026-02-17 16:07:52 +01:00
Dries Augustyns c286f49097 feat: Add initial handling in webhook for inbound 2026-02-17 16:03:50 +01:00
Dries Augustyns 4c81d9ec04 feat: add documentation link and redirect to WIKI_URI 2026-02-17 10:30:17 +01:00
Dries Augustyns a928666dfc fix: Update contact subscription logic for upsert operations 2026-02-17 10:25:01 +01:00
Shuvadipta Das 64ba19e589 fix(test): consolidate SES MIME boundary tests into EmailService.test.ts 2026-02-16 18:55:03 +05:30
Shuvadipta Das 3a42012ac7 fix: removed "any" data type from SESService.test.ts 2026-02-16 18:47:42 +05:30
Shuvadipta Das 08e5c0d930 fix: contentId header injection fixed and separte unit test SESService added to verify MIME boundaries 2026-02-16 18:27:32 +05:30
Shuvadipta Das 18788ac1ca Merge branch 'next' of https://github.com/5h0ov/plunk into multipart/related-support-embed-image 2026-02-16 18:27:07 +05:30
Dries Augustyns d55dda3127 feat: add minimum thresholds for bounce and complaint rates 2026-02-16 11:03:54 +01:00
Dries Augustyns d637147f25 Merge pull request #284 from useplunk/dependabot/npm_and_yarn/webpack-5.105.0
chore(deps): bump webpack from 5.103.0 to 5.105.0
2026-02-16 10:20:22 +01:00
Dries Augustyns c1ed23c967 Merge pull request #286 from useplunk/dependabot/npm_and_yarn/markdown-it-14.1.1
chore(deps): bump markdown-it from 14.1.0 to 14.1.1
2026-02-16 10:20:08 +01:00
Dries Augustyns 46001619e8 Merge pull request #287 from useplunk/dependabot/npm_and_yarn/qs-6.14.2
chore(deps): bump qs from 6.14.1 to 6.14.2
2026-02-16 10:19:52 +01:00
Dries Augustyns 7a6df7760b Merge pull request #288 from bpotmalnik/feat/add-polish
feat(i18n): add Polish locale translations
2026-02-16 10:00:38 +01:00
Bart Potmalnik d2d779c68f feat(i18n): add Polish locale translations
Add polish translations

Ref #246
2026-02-15 21:43:29 +01:00
dependabot[bot] bbc12e0029 chore(deps): bump qs from 6.14.1 to 6.14.2
Bumps [qs](https://github.com/ljharb/qs) from 6.14.1 to 6.14.2.
- [Changelog](https://github.com/ljharb/qs/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ljharb/qs/compare/v6.14.1...v6.14.2)

---
updated-dependencies:
- dependency-name: qs
  dependency-version: 6.14.2
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <[email protected]>
2026-02-14 12:57:41 +00:00
dependabot[bot] 125718bb94 chore(deps): bump markdown-it from 14.1.0 to 14.1.1
Bumps [markdown-it](https://github.com/markdown-it/markdown-it) from 14.1.0 to 14.1.1.
- [Changelog](https://github.com/markdown-it/markdown-it/blob/master/CHANGELOG.md)
- [Commits](https://github.com/markdown-it/markdown-it/compare/14.1.0...14.1.1)

---
updated-dependencies:
- dependency-name: markdown-it
  dependency-version: 14.1.1
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <[email protected]>
2026-02-13 20:46:34 +00:00
Dries Augustyns 35d67c6b42 Merge pull request #285 from yumhum/i18n-czech-locale 2026-02-11 08:39:37 +01:00
Jan Wunsch 14c471e4ca feat(i18n): add Czech locale translations
Add Czech (cs) translations for contact-facing pages and email footers,
and wire up the locale in the i18n system with the correct flag.
2026-02-11 01:48:38 +01:00
Dries Augustyns 42ceb6edc0 refactor: remove unnecessary logging for segment processing 2026-02-10 20:23:31 +01:00
Dries Augustyns 5bce1d74ff docs: add webhooks documentation for real-time event handling 2026-02-09 19:01:16 +01:00
Dries Augustyns b4404f698e docs: update contacts documentation to include subscription state and email delivery rules 2026-02-09 18:45:01 +01:00
dependabot[bot] e4625894c9 chore(deps): bump webpack from 5.103.0 to 5.105.0
Bumps [webpack](https://github.com/webpack/webpack) from 5.103.0 to 5.105.0.
- [Release notes](https://github.com/webpack/webpack/releases)
- [Changelog](https://github.com/webpack/webpack/blob/main/CHANGELOG.md)
- [Commits](https://github.com/webpack/webpack/compare/v5.103.0...v5.105.0)

---
updated-dependencies:
- dependency-name: webpack
  dependency-version: 5.105.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <[email protected]>
2026-02-06 08:04:36 +00:00
Dries Augustyns af87d80baa Merge pull request #280 from useplunk/dependabot/npm_and_yarn/next-16.1.6
chore(deps): bump next from 16.0.1 to 16.1.6
2026-02-06 09:01:56 +01:00
Dries Augustyns 1f84c9113c Merge branch 'next' of https://github.com/useplunk/plunk into next 2026-02-06 09:01:33 +01:00
Dries Augustyns 0cf0a26a97 feat: Integrate NuqsAdapter for improved state management and query handling 2026-02-06 09:01:25 +01:00
Dries Augustyns 0d4b694208 fix: Implement merging for activity updates to preserve component state 2026-02-06 08:55:24 +01:00
Shuvadipta Das c40394ffd6 feat(api): support inline images in emails using Content-ID 2026-01-31 10:23:42 +05:30
dependabot[bot] 20ffb2b8bc chore(deps): bump next from 16.0.1 to 16.1.6
Bumps [next](https://github.com/vercel/next.js) from 16.0.1 to 16.1.6.
- [Release notes](https://github.com/vercel/next.js/releases)
- [Changelog](https://github.com/vercel/next.js/blob/canary/release.js)
- [Commits](https://github.com/vercel/next.js/compare/v16.0.1...v16.1.6)

---
updated-dependencies:
- dependency-name: next
  dependency-version: 16.1.6
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <[email protected]>
2026-01-29 14:12:13 +00:00
Dries Augustyns 0af79eb84b Merge pull request #279 from useplunk/dependabot/npm_and_yarn/tar-7.5.7 2026-01-29 15:10:06 +01:00
Dries Augustyns e2e98149cb Merge pull request #278 from useplunk/dependabot/npm_and_yarn/next-16.1.5 2026-01-29 15:09:44 +01:00
Dries Augustyns f55ab31ae5 Merge pull request #277 from useplunk/dependabot/npm_and_yarn/lodash-4.17.23 2026-01-29 15:09:24 +01:00
Dries Augustyns 61a65d01c7 Merge pull request #275 from useplunk/dependabot/npm_and_yarn/diff-4.0.4 2026-01-29 15:09:05 +01:00
dependabot[bot] 7aa3b74c6f chore(deps): bump tar from 7.5.3 to 7.5.7
Bumps [tar](https://github.com/isaacs/node-tar) from 7.5.3 to 7.5.7.
- [Release notes](https://github.com/isaacs/node-tar/releases)
- [Changelog](https://github.com/isaacs/node-tar/blob/main/CHANGELOG.md)
- [Commits](https://github.com/isaacs/node-tar/compare/v7.5.3...v7.5.7)

---
updated-dependencies:
- dependency-name: tar
  dependency-version: 7.5.7
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <[email protected]>
2026-01-29 14:02:08 +00:00
dependabot[bot] 7647109fb6 chore(deps): bump next from 16.0.10 to 16.1.5
Bumps [next](https://github.com/vercel/next.js) from 16.0.10 to 16.1.5.
- [Release notes](https://github.com/vercel/next.js/releases)
- [Changelog](https://github.com/vercel/next.js/blob/canary/release.js)
- [Commits](https://github.com/vercel/next.js/compare/v16.0.10...v16.1.5)

---
updated-dependencies:
- dependency-name: next
  dependency-version: 16.1.5
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <[email protected]>
2026-01-27 20:11:43 +00:00
Dries Augustyns ad0c17da56 fix: Enhance email activity filtering by adding date range checks 2026-01-26 09:24:49 +01:00
dependabot[bot] 93ca6b8d94 chore(deps): bump lodash from 4.17.21 to 4.17.23
Bumps [lodash](https://github.com/lodash/lodash) from 4.17.21 to 4.17.23.
- [Release notes](https://github.com/lodash/lodash/releases)
- [Commits](https://github.com/lodash/lodash/compare/4.17.21...4.17.23)

---
updated-dependencies:
- dependency-name: lodash
  dependency-version: 4.17.23
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <[email protected]>
2026-01-23 06:43:35 +00:00
Dries Augustyns c85df75d53 feat: Add bounce and complaint filter to activity feed 2026-01-21 20:52:23 +01:00
Dries Augustyns e16093a264 chore: Increaes complaint thresholds 2026-01-21 20:46:33 +01:00
dependabot[bot] a54c8139b1 chore(deps): bump diff from 4.0.2 to 4.0.4
Bumps [diff](https://github.com/kpdecker/jsdiff) from 4.0.2 to 4.0.4.
- [Changelog](https://github.com/kpdecker/jsdiff/blob/master/release-notes.md)
- [Commits](https://github.com/kpdecker/jsdiff/compare/v4.0.2...v4.0.4)

---
updated-dependencies:
- dependency-name: diff
  dependency-version: 4.0.4
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <[email protected]>
2026-01-20 22:25:03 +00:00
Dries Augustyns 8de79e37e9 Merge pull request #269 from useplunk/dependabot/npm_and_yarn/undici-6.23.0 2026-01-17 20:28:36 +01:00
Dries Augustyns c662ecdbb2 Merge pull request #274 from useplunk/dependabot/npm_and_yarn/tar-7.5.3 2026-01-17 20:28:17 +01:00
dependabot[bot] 8f6f63e572 chore(deps): bump tar from 7.5.2 to 7.5.3
Bumps [tar](https://github.com/isaacs/node-tar) from 7.5.2 to 7.5.3.
- [Release notes](https://github.com/isaacs/node-tar/releases)
- [Changelog](https://github.com/isaacs/node-tar/blob/main/CHANGELOG.md)
- [Commits](https://github.com/isaacs/node-tar/compare/v7.5.2...v7.5.3)

---
updated-dependencies:
- dependency-name: tar
  dependency-version: 7.5.3
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <[email protected]>
2026-01-17 15:52:37 +00:00
Dries Augustyns 22c22aba1b Merge pull request #273 from wettiemans/fix/242-template-type-dropdown 2026-01-17 12:40:18 +01:00
Dries AugustynsandCopilot de106f9d91 Update apps/web/src/pages/templates/[id].tsx
Co-authored-by: Copilot <[email protected]>
2026-01-17 12:30:00 +01:00
Jan Behrends 8a38766c02 fix: Ensure template type is loaded before rendering Select
Addresses #242. The Select component renders with value={undefined}
before useEffect populates editedTemplate.type. This triggers a React
warning: 'Select is changing from uncontrolled to controlled.'

On the hosted environment, this likely causes Radix UI's data-placeholder
attribute to remain set on the trigger, with the selected value text
not being rendered despite the value being loaded in state.

This change extends the loading condition to wait for editedTemplate.type,
ensuring the Select never renders in an undefined/uncontrolled state.
2026-01-16 13:09:14 +01:00
Dries Augustyns 3a16ad3221 chore: Add bundled notification for segment membership updates 2026-01-15 19:47:12 +01:00
Dries Augustyns ec402cb9b3 Merge pull request #270 from mmihalev/next 2026-01-15 13:06:29 +01:00
Milen Mihalev 663bc2be8d feat(i18n): Add Bulgarian translations 2026-01-15 11:50:25 +02:00
Dries Augustyns df28e2dc7d Merge pull request #268 from marcelscruz/next 2026-01-15 09:40:52 +01:00
dependabot[bot] 79fe9e94c7 chore(deps): bump undici from 6.22.0 to 6.23.0
Bumps [undici](https://github.com/nodejs/undici) from 6.22.0 to 6.23.0.
- [Release notes](https://github.com/nodejs/undici/releases)
- [Commits](https://github.com/nodejs/undici/compare/v6.22.0...v6.23.0)

---
updated-dependencies:
- dependency-name: undici
  dependency-version: 6.23.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <[email protected]>
2026-01-15 00:25:59 +00:00
Marcel Cruz c2afb2dfab feat(i18n): Add Portuguese translations 2026-01-15 00:32:37 +01:00
Dries Augustyns 0d1ed0ec67 Merge pull request #263 from 5h0ov/new-olderthan-segmentfilter 2026-01-13 10:30:56 +01:00
Dries Augustyns 99526ebfc2 chore: Rename within field label to align with new older than 2026-01-13 10:25:10 +01:00
Dries Augustyns e6baace00d feat: Remove domain from AWS if no longer in use by other projects 2026-01-13 10:19:54 +01:00
Dries Augustyns 743155b06a chore: Add missing variables to turbo.json 2026-01-12 20:15:36 +01:00
Dries Augustyns 0a67a8278f feat: Add additional checks for website, NS records and personal emails 2026-01-12 20:02:08 +01:00
Dries Augustyns 26800a8553 fix: Improve email verification logic by prioritizing MX record checks and clarifying domain existence validation 2026-01-12 18:49:30 +01:00
Dries Augustyns 93165644af feat: Ability to disable signups and disable email verification for self-hosters 2026-01-12 15:20:14 +01:00
Dries Augustyns 4db1ccc3fc fix: Refactor Redis keys to prevent multiple messages on concurrent requests 2026-01-12 08:33:51 +01:00
Dries Augustyns 06c4d644b7 Merge pull request #262 from 5h0ov/development-enhancements 2026-01-12 08:07:47 +01:00
Shuvadipta Das b5fa21a57c feat: add "olderThan" segment filter operator
- Added `olderThan` and `triggeredOlderThan` operators to types and schemas
- Implemented backend logic for `olderThan` operator in SegmentService
- Updated SegmentFilterBuilder and shared index/types files to support new time-based operators
2026-01-12 11:10:53 +05:30
Shuvadipta Das ddbe5237fe fix: added missing services:down script, added "win32" to supportedArchitectures for yarn package installation, added missing required WIKI_URI to .env.example of api 2026-01-12 11:07:53 +05:30
Dries Augustyns 18e17cf198 chore: Remove default tag from issue template 2026-01-11 11:53:36 +01:00
Dries Augustyns 6a6772d5ed Update issue templates 2026-01-11 11:51:38 +01:00
Dries Augustyns 50042cea27 chore: Clean up variable replacement paths 2026-01-11 09:09:41 +01:00
Dries Augustyns 3ccf890a21 chore: Clean up variable replacement paths 2026-01-11 08:57:19 +01:00
Dries Augustyns d57f6c81cb chore: Clean up variable replacement paths 2026-01-11 08:37:01 +01:00
Dries Augustyns c07816c2a1 fix: Update URL replacement logic to handle runtime paths and add warnings for missing files 2026-01-11 08:26:59 +01:00
Dries Augustyns 73da0a5136 Merge pull request #257 from mmihalev/next 2026-01-10 10:20:57 +01:00
Milen Mihalev d12b797ebe Use environment variables for SMTP port configuration 2026-01-09 15:38:59 +02:00
Dries Augustyns 7df43d8553 fix: Improve bounce handling logic to differentiate between permanent and transient bounces 2026-01-09 11:48:20 +01:00
101 changed files with 7811 additions and 14455 deletions
+15
View File
@@ -145,6 +145,21 @@ SMTP_DOMAIN=smtp.example.com
# Default: true # Default: true
# AUTO_PROJECT_DISABLE=false # AUTO_PROJECT_DISABLE=false
# ========================================
# OPTIONAL: Self-Hosting User Management
# ========================================
# Controls whether new user signups are allowed
# When enabled (true), the signup endpoint will reject new user registration attempts
# Useful for private instances or when you want to manually manage users
# Default: false
# DISABLE_SIGNUPS=false
# Controls whether email validation checks are performed on signup
# When enabled (true), validates emails for disposable domains, plus-addressing, domain existence, and MX records
# When disabled (false), skips these validation checks and allows any email format
# Default: false
# VERIFY_EMAIL_ON_SIGNUP=false
# ======================================== # ========================================
# ADVANCED (rarely needed) # ADVANCED (rarely needed)
# ======================================== # ========================================
@@ -0,0 +1,21 @@
---
name: Feature requests
about: Use this template to suggest new features for Plunk
title: ''
labels: enhancement
assignees: ''
---
## Is your feature request related to a problem?
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
## Describe the solution you'd like
A clear and concise description of what you want to happen.
## Alternatives or workarounds
A clear and concise description of any alternative solutions or features you've considered.
## Additional context
Add any other context or screenshots about the feature request here.
+61
View File
@@ -0,0 +1,61 @@
---
name: Product Issues
about: Use this template for bugs and issues on Plunk
title: ''
labels: bug
assignees: ''
---
## Description
## To Reproduce
## Expected behavior
## Environment
Please select the option that applies:
* Deployment type:
* [ ] Hosted
* [ ] Self-hosted
If self-hosted, please provide relevant details (Docker, Kubernetes, bare metal, etc.):
## Version verification
> ⚠️ **Important:**
> Self-hosted issues **must** be reproduced on the latest commit.
> Issues without a confirmed commit SHA may be closed without investigation.
* [ ] I am using the hosted version
**If self-hosted:**
* [ ] I have confirmed this issue still exists on the **latest commit** (not the `latest` tag)
* Commit SHA tested: `__________`
## Logs / Error output
If applicable, add logs, stack traces, or error messages here.
```
PASTE LOGS HERE
```
## Screenshots / Recordings / Additional context
---
## Checklist
Please confirm the following before submitting:
* [ ] I have searched existing issues to ensure this bug has not already been reported
* [ ] I have provided clear reproduction steps
* [ ] I have included all relevant environment details
+1 -1
View File
@@ -1,3 +1,3 @@
{ {
".": "0.4.0" ".": "0.7.0"
} }
+1 -1
View File
@@ -2,7 +2,7 @@ nodeLinker: node-modules
# Support multiple architectures - download pre-built binaries instead of compiling # Support multiple architectures - download pre-built binaries instead of compiling
supportedArchitectures: supportedArchitectures:
os: [ "linux", "darwin" ] os: [ "linux", "darwin", "win32" ]
cpu: [ "x64", "arm64" ] cpu: [ "x64", "arm64" ]
libc: [ "glibc" ] libc: [ "glibc" ]
+95
View File
@@ -1,5 +1,100 @@
# Changelog # Changelog
## [0.7.0](https://github.com/useplunk/plunk/compare/v0.6.0...v0.7.0) (2026-03-05)
### Features
* **api:** support inline images in emails using Content-ID ([9b15b93](https://github.com/useplunk/plunk/commit/9b15b93b96344f811d869d103b3b6d344b531811))
* Sort projects alphabetically in the dashboard and fix layout ([64bd094](https://github.com/useplunk/plunk/commit/64bd094b47abbc4feaeb93d97915df57763b3907))
* Static segments ([4b51e38](https://github.com/useplunk/plunk/commit/4b51e386e39ae38d6ea52eb87858de36fa45ab46))
### Bug Fixes
* Add support for STATIC segment type in CampaignService ([7bd098b](https://github.com/useplunk/plunk/commit/7bd098bdd01a8af0dd41ec515880289b1795e5af))
* correct cookie domain for .local TLD hostnames ([59aa784](https://github.com/useplunk/plunk/commit/59aa7845bad69a1768bb88f83cfcea607c447538))
* Correctly set domain status on manual verify ([21af8fe](https://github.com/useplunk/plunk/commit/21af8fe05e0450e8d826a3a01224511a337ca072))
* Do not unsubscribe existing contacts ([2c4d95e](https://github.com/useplunk/plunk/commit/2c4d95e604cbed9189f7ee07c24b1f236fce7990))
* Support any locale on creation ([ec1f4c9](https://github.com/useplunk/plunk/commit/ec1f4c9374e06e3defed3c728be603c10e4e7baa))
* Verify SNS URL before sending fetch request ([b8f1ad9](https://github.com/useplunk/plunk/commit/b8f1ad9ab53c78f8ef063fdc125f397c8bfc7652))
### Documentation
* Static segments ([e8a247f](https://github.com/useplunk/plunk/commit/e8a247fe12b79ae8a25a74485179e93081fe2002))
## [0.6.0](https://github.com/useplunk/plunk/compare/v0.5.0...v0.6.0) (2026-02-19)
### Features
* Ability to change workflow trigger ([eec37ec](https://github.com/useplunk/plunk/commit/eec37ecb31c63888879a1933dba4fd0c6243018b))
* Add billing for inbound ([3330d83](https://github.com/useplunk/plunk/commit/3330d83d08904bc547740bfc9fdcbc5ff214d977))
* Add billing for inbound ([de7ed84](https://github.com/useplunk/plunk/commit/de7ed84fcfddde16a9297c947048e9876712f6fa))
* Add dedicated received type ([f947ee6](https://github.com/useplunk/plunk/commit/f947ee6f22371055801fa9cfc62e15df7851986c))
* **i18n:** Add Spanish language ([9c69c7a](https://github.com/useplunk/plunk/commit/9c69c7a36edd86fdc02b8d0d3e3f8d64ed8ecfa6))
### Bug Fixes
* Enhance email bounce notification with latest bounce details ([e639c72](https://github.com/useplunk/plunk/commit/e639c72e8b940ba1da472d355f930359da7c868b))
### Documentation
* Add receiving emails functionality and update DNS records documentation ([b426986](https://github.com/useplunk/plunk/commit/b42698616a3f7bb079a092375ac886f2a9d7405d))
## [0.5.0](https://github.com/useplunk/plunk/compare/v0.4.0...v0.5.0) (2026-02-17)
### Features
* Ability to disable signups and disable email verification for self-hosters ([9316564](https://github.com/useplunk/plunk/commit/93165644af1ebcd7d5eb1900b13e5e38c1af0262))
* add "olderThan" segment filter operator ([b5fa21a](https://github.com/useplunk/plunk/commit/b5fa21a57cbf491e0438eb29fc9419063fa2aea7))
* Add additional checks for website, NS records and personal emails ([0a67a82](https://github.com/useplunk/plunk/commit/0a67a8278f45d89b1abdf55be1cf251a470595cf))
* Add advanced DNS configuration ([7964563](https://github.com/useplunk/plunk/commit/7964563b620868279f5fb6baab0d7499c41f51ed))
* Add bounce and complaint filter to activity feed ([c85df75](https://github.com/useplunk/plunk/commit/c85df75d539f7e5500a9a109966b0e6d654d4022))
* add documentation link and redirect to WIKI_URI ([4c81d9e](https://github.com/useplunk/plunk/commit/4c81d9ec04003550b140d884f37ebbf13137166d))
* Add inbound handling ([d050b55](https://github.com/useplunk/plunk/commit/d050b55baaf46306be3fb6e5ad683205e158bd65))
* Add initial handling in webhook for inbound ([e01dc40](https://github.com/useplunk/plunk/commit/e01dc4066c5e5eb5e0e69ef92f8a5bb7786e5a91))
* Add initial handling in webhook for inbound ([c286f49](https://github.com/useplunk/plunk/commit/c286f490974d8dfe9c94695c63e6b48216b8052d))
* add minimum thresholds for bounce and complaint rates ([d55dda3](https://github.com/useplunk/plunk/commit/d55dda312718890231d1a428448e607792799c84))
* Add support for custom email recipients in workflow steps ([78d3d22](https://github.com/useplunk/plunk/commit/78d3d224af60cf5b58c6b18fdd0921320912fb09))
* **i18n:** Add Bulgarian translations ([663bc2b](https://github.com/useplunk/plunk/commit/663bc2be8da69733d2bbc53c6b1bfcc36ff55cf8))
* **i18n:** add Czech locale translations ([14c471e](https://github.com/useplunk/plunk/commit/14c471e4cadbe1bbf90e53522134fad3d81ff107))
* **i18n:** add Polish locale translations ([7a6df77](https://github.com/useplunk/plunk/commit/7a6df7760bc73dfe80dcf2d37612e320f6de1d30))
* **i18n:** add Polish locale translations ([d2d779c](https://github.com/useplunk/plunk/commit/d2d779c68f958a6ac0e77b7588e92a5c705a8fd4)), closes [#246](https://github.com/useplunk/plunk/issues/246)
* **i18n:** Add Portuguese translations ([c2afb2d](https://github.com/useplunk/plunk/commit/c2afb2dfab977ae74f3b694601a1f2d0353660a8))
* Integrate NuqsAdapter for improved state management and query handling ([0cf0a26](https://github.com/useplunk/plunk/commit/0cf0a26a97e608f654ed3046c1a46d414557e3ee))
* Remove domain from AWS if no longer in use by other projects ([e6baace](https://github.com/useplunk/plunk/commit/e6baace00d5f7a109e717b8a996bc2cda52cc9fa))
### Bug Fixes
* added missing services:down script, added "win32" to supportedArchitectures for yarn package installation, added missing required WIKI_URI to .env.example of api ([ddbe523](https://github.com/useplunk/plunk/commit/ddbe5237fe7012e197e3b398aebc8e2921a4328a))
* Center "Add Step" nodes below parent nodes and update positions on drag ([e4e334c](https://github.com/useplunk/plunk/commit/e4e334c77a7ba41e5a60b69b9c64fa3bb72f1e74))
* Enhance email activity filtering by adding date range checks ([ad0c17d](https://github.com/useplunk/plunk/commit/ad0c17da566a26a296229c05d9b4e18cf7d401ad))
* Ensure template type is loaded before rendering Select ([8a38766](https://github.com/useplunk/plunk/commit/8a38766c025afd5ef15fee4b7c5baea97a45ec48))
* Implement merging for activity updates to preserve component state ([0d4b694](https://github.com/useplunk/plunk/commit/0d4b694208fd8e516e1f50f7384d1ac5bd6561e0))
* Improve bounce handling logic to differentiate between permanent and transient bounces ([7df43d8](https://github.com/useplunk/plunk/commit/7df43d8553eca93b601915ea4deaf59233e848c7))
* Improve email verification logic by prioritizing MX record checks and clarifying domain existence validation ([26800a8](https://github.com/useplunk/plunk/commit/26800a85538fc90aa05fc43b1cc33cef95d8fb32))
* Refactor Redis keys to prevent multiple messages on concurrent requests ([4db1ccc](https://github.com/useplunk/plunk/commit/4db1ccc3fc59edb0187d8e2223f45bb0bce6deb5))
* Remove 'Optional' label from MAIL FROM Domain and Inbound Email headings ([f9b1354](https://github.com/useplunk/plunk/commit/f9b135446040de099484db66139560f43bbf027e))
* Update contact subscription logic for upsert operations ([a928666](https://github.com/useplunk/plunk/commit/a928666dfcdc65c90602051c79b3c008282674aa))
* Update URL replacement logic to handle runtime paths and add warnings for missing files ([c07816c](https://github.com/useplunk/plunk/commit/c07816c2a1b029d83400128f4720263e975214ad))
### Code Refactoring
* remove unnecessary logging for segment processing ([42ceb6e](https://github.com/useplunk/plunk/commit/42ceb6edc03ebc6f14c6d399e859914ac09f1ab6))
### Documentation
* add webhooks documentation for real-time event handling ([5bce1d7](https://github.com/useplunk/plunk/commit/5bce1d74fffb927bcbb2c7df624fde089101efc8))
* update contacts documentation to include subscription state and email delivery rules ([b4404f6](https://github.com/useplunk/plunk/commit/b4404f698ec28a59f32d728c15c59c8b7765d377))
## [0.4.0](https://github.com/useplunk/plunk/compare/v0.3.0...v0.4.0) (2026-01-08) ## [0.4.0](https://github.com/useplunk/plunk/compare/v0.3.0...v0.4.0) (2026-01-08)
+7
View File
@@ -148,6 +148,12 @@ Required for builds and deployment (see turbo.json and .env.example):
- Notifications (optional): `NTFY_URL` (ntfy.sh topic URL or self-hosted server for system notifications) - Notifications (optional): `NTFY_URL` (ntfy.sh topic URL or self-hosted server for system notifications)
- Platform Email Notifications (optional): `PLUNK_API_KEY` (enables email notifications to users for critical events like - Platform Email Notifications (optional): `PLUNK_API_KEY` (enables email notifications to users for critical events like
project disabled, billing limits, etc. If not set, only ntfy notifications are sent) project disabled, billing limits, etc. If not set, only ntfy notifications are sent)
- Self-hosting User Management (optional):
- `DISABLE_SIGNUPS` (default: false) - When set to true, prevents new user signups via the API
- `VERIFY_EMAIL_ON_SIGNUP` (default: false) - When set to true, validates emails on signup for disposable domains,
plus-addressing, domain existence, and MX records
- Security (optional): `AUTO_PROJECT_DISABLE` (default: true) - Controls whether projects are automatically disabled when
bounce/complaint rate thresholds are exceeded
**Important Notes:** **Important Notes:**
@@ -159,6 +165,7 @@ Required for builds and deployment (see turbo.json and .env.example):
client-side access client-side access
## Plugins ## Plugins
There are two plugins installed for you to use. There are two plugins installed for you to use.
- frontend-design: This plugin can help you to create polished user interfaces. Use it when working on design-related tasks. - frontend-design: This plugin can help you to create polished user interfaces. Use it when working on design-related tasks.
+1
View File
@@ -16,6 +16,7 @@ JWT_SECRET=hBx9Xh8J6KOMAGAsSjvcZJBT5TWyIkFX
USE_HTTPS=false USE_HTTPS=false
API_URI=http://localhost:8080 API_URI=http://localhost:8080
WIKI_URI=http://localhost:1000
DASHBOARD_URI=http://localhost:3000 DASHBOARD_URI=http://localhost:3000
LANDING_URI=http://localhost:4000 LANDING_URI=http://localhost:4000
+1 -1
View File
@@ -37,7 +37,7 @@
"jsonwebtoken": "^9.0.2", "jsonwebtoken": "^9.0.2",
"mailchecker": "^6.0.19", "mailchecker": "^6.0.19",
"morgan": "^1.10.0", "morgan": "^1.10.0",
"multer": "^2.0.2", "multer": "^2.1.1",
"signale": "^1.4.0", "signale": "^1.4.0",
"stripe": "^20.0.0" "stripe": "^20.0.0"
}, },
@@ -850,6 +850,17 @@ describe('Actions API Integration Tests', () => {
expect(result.data.subscribed).toBeUndefined(); expect(result.data.subscribed).toBeUndefined();
} }
}); });
it('should create new contacts as unsubscribed when subscribed is undefined', async () => {
const newEmail = '[email protected]';
// Send email to new contact without specifying subscribed
const {ContactService} = await import('../../services/ContactService.js');
const contact = await ContactService.upsert(projectId, newEmail, {name: 'Test'}, false);
// Transactional emails should create contacts as unsubscribed by default
expect(contact.subscribed).toBe(false);
});
}); });
describe('/v1/track endpoint', () => { describe('/v1/track endpoint', () => {
@@ -905,9 +916,9 @@ describe('Actions API Integration Tests', () => {
// Track event for new contact without specifying subscribed // Track event for new contact without specifying subscribed
const {ContactService} = await import('../../services/ContactService.js'); const {ContactService} = await import('../../services/ContactService.js');
const contact = await ContactService.upsert(projectId, newEmail, {event: 'test'}, undefined); const contact = await ContactService.upsert(projectId, newEmail, {event: 'test'}, true);
// New contacts should default to subscribed=true // Event tracking should create contacts as subscribed by default
expect(contact.subscribed).toBe(true); expect(contact.subscribed).toBe(true);
}); });
+6
View File
@@ -104,6 +104,12 @@ export const PLUNK_ENABLED = PLUNK_API_KEY !== '' && PLUNK_FROM_ADDRESS !== '';
// Useful for self-hosters who want to manage project status manually // Useful for self-hosters who want to manage project status manually
export const AUTO_PROJECT_DISABLE = validateEnv('AUTO_PROJECT_DISABLE', 'true') === 'true'; export const AUTO_PROJECT_DISABLE = validateEnv('AUTO_PROJECT_DISABLE', 'true') === 'true';
// Self-hosting Configuration (optional)
// Controls whether new user signups are allowed (default: false)
export const DISABLE_SIGNUPS = process.env.DISABLE_SIGNUPS === 'true';
// Controls whether email validation checks are performed on signup (default: false)
export const VERIFY_EMAIL_ON_SIGNUP = process.env.VERIFY_EMAIL_ON_SIGNUP === 'true';
// Email Verification & Password Reset // Email Verification & Password Reset
export const TOKEN_EXPIRY_SECONDS = 3600; // 1 hour export const TOKEN_EXPIRY_SECONDS = 3600; // 1 hour
export const EMAIL_VERIFICATION_RATE_LIMIT = 3; // Max 3 emails per hour export const EMAIL_VERIFICATION_RATE_LIMIT = 3; // Max 3 emails per hour
+6 -1
View File
@@ -72,6 +72,8 @@ export class Actions {
// Create or update contact with persistent data only // Create or update contact with persistent data only
// ContactService.upsert will filter out non-persistent fields // ContactService.upsert will filter out non-persistent fields
// Event tracking should subscribe new contacts by default (subscribed=true in ContactService)
// but preserve existing subscription state for existing contacts
const contact = await ContactService.upsert( const contact = await ContactService.upsert(
auth.projectId, auth.projectId,
email, email,
@@ -266,7 +268,10 @@ export class Actions {
: (data as Record<string, unknown> | undefined); : (data as Record<string, unknown> | undefined);
// Create or update contact with metadata // Create or update contact with metadata
const contact = await ContactService.upsert(auth.projectId, recipient.email, recipientData, subscribed); // Transactional emails should not subscribe contacts by default
// New contacts default to unsubscribed unless explicitly opted in
// Existing contacts preserve their subscription state unless explicitly changed
const contact = await ContactService.upsert(auth.projectId, recipient.email, recipientData, subscribed, false);
// Get merged data including non-persistent fields for template rendering // Get merged data including non-persistent fields for template rendering
const mergedData = ContactService.getMergedData(contact, data as Record<string, unknown> | undefined); const mergedData = ContactService.getMergedData(contact, data as Record<string, unknown> | undefined);
+13 -1
View File
@@ -7,6 +7,7 @@ import * as React from 'react';
import { import {
DASHBOARD_URI, DASHBOARD_URI,
DISABLE_SIGNUPS,
EMAIL_VERIFICATION_RATE_LIMIT, EMAIL_VERIFICATION_RATE_LIMIT,
EMAIL_VERIFICATION_RATE_WINDOW, EMAIL_VERIFICATION_RATE_WINDOW,
GITHUB_OAUTH_ENABLED, GITHUB_OAUTH_ENABLED,
@@ -15,6 +16,7 @@ import {
PASSWORD_RESET_RATE_LIMIT, PASSWORD_RESET_RATE_LIMIT,
PLUNK_ENABLED, PLUNK_ENABLED,
TOKEN_EXPIRY_SECONDS, TOKEN_EXPIRY_SECONDS,
VERIFY_EMAIL_ON_SIGNUP,
} from '../app/constants.js'; } from '../app/constants.js';
import {prisma} from '../database/prisma.js'; import {prisma} from '../database/prisma.js';
import {redis, REDIS_ONE_MINUTE} from '../database/redis.js'; import {redis, REDIS_ONE_MINUTE} from '../database/redis.js';
@@ -63,9 +65,18 @@ export class Auth {
@Post('signup') @Post('signup')
@CatchAsync @CatchAsync
public async signup(req: Request, res: Response, _next: NextFunction) { public async signup(req: Request, res: Response, _next: NextFunction) {
// Check if signups are disabled
if (DISABLE_SIGNUPS) {
return res.json({
success: false,
data: 'New user signups are currently disabled',
});
}
const {email, password} = AuthenticationSchemas.login.parse(req.body); const {email, password} = AuthenticationSchemas.login.parse(req.body);
// Verify email is valid and not disposable/plus-addressed // Verify email is valid and not disposable/plus-addressed (if verification enabled)
if (VERIFY_EMAIL_ON_SIGNUP) {
const verification = await EmailVerificationService.verifyEmail(email); const verification = await EmailVerificationService.verifyEmail(email);
if ( if (
@@ -89,6 +100,7 @@ export class Auth {
data: 'This email address cannot be used for signup', data: 'This email address cannot be used for signup',
}); });
} }
}
const user = await UserService.email(email); const user = await UserService.email(email);
+4
View File
@@ -3,6 +3,7 @@ import type {Request, Response} from 'express';
import { import {
API_URI, API_URI,
AWS_SES_REGION,
DASHBOARD_URI, DASHBOARD_URI,
GITHUB_OAUTH_ENABLED, GITHUB_OAUTH_ENABLED,
GOOGLE_OAUTH_ENABLED, GOOGLE_OAUTH_ENABLED,
@@ -59,6 +60,9 @@ export class Config {
: null, : null,
}, },
}, },
aws: {
sesRegion: AWS_SES_REGION,
},
}); });
} }
} }
+4 -2
View File
@@ -315,6 +315,7 @@ export class Contacts {
@Middleware([requireAuth, requireEmailVerified]) @Middleware([requireAuth, requireEmailVerified])
@CatchAsync @CatchAsync
public async getImportStatus(req: Request, res: Response, _next: NextFunction) { public async getImportStatus(req: Request, res: Response, _next: NextFunction) {
const auth = res.locals.auth;
const jobId = req.params.jobId; const jobId = req.params.jobId;
if (!jobId) { if (!jobId) {
@@ -322,7 +323,7 @@ export class Contacts {
} }
try { try {
const status = await QueueService.getImportJobStatus(jobId); const status = await QueueService.getImportJobStatus(jobId, auth.projectId!);
if (!status) { if (!status) {
return res.status(404).json({error: 'Import job not found'}); return res.status(404).json({error: 'Import job not found'});
@@ -502,6 +503,7 @@ export class Contacts {
@Middleware([requireAuth, requireEmailVerified]) @Middleware([requireAuth, requireEmailVerified])
@CatchAsync @CatchAsync
public async getBulkActionStatus(req: Request, res: Response, _next: NextFunction) { public async getBulkActionStatus(req: Request, res: Response, _next: NextFunction) {
const auth = res.locals.auth;
const jobId = req.params.jobId; const jobId = req.params.jobId;
if (!jobId) { if (!jobId) {
@@ -509,7 +511,7 @@ export class Contacts {
} }
try { try {
const status = await QueueService.getBulkActionJobStatus(jobId); const status = await QueueService.getBulkActionJobStatus(jobId, auth.projectId!);
if (!status) { if (!status) {
return res.status(404).json({error: 'Bulk action job not found'}); return res.status(404).json({error: 'Bulk action job not found'});
+7
View File
@@ -4,11 +4,13 @@ import type {NextFunction, Request, Response} from 'express';
import { import {
API_URI, API_URI,
DASHBOARD_URI, DASHBOARD_URI,
DISABLE_SIGNUPS,
GITHUB_OAUTH_CLIENT, GITHUB_OAUTH_CLIENT,
GITHUB_OAUTH_ENABLED, GITHUB_OAUTH_ENABLED,
GITHUB_OAUTH_SECRET, GITHUB_OAUTH_SECRET,
} from '../../app/constants.js'; } from '../../app/constants.js';
import {prisma} from '../../database/prisma.js'; import {prisma} from '../../database/prisma.js';
import {BadRequest} from '../../exceptions/index.js';
import {jwt} from '../../middleware/auth.js'; import {jwt} from '../../middleware/auth.js';
import {NtfyService} from '../../services/NtfyService.js'; import {NtfyService} from '../../services/NtfyService.js';
import {UserService} from '../../services/UserService.js'; import {UserService} from '../../services/UserService.js';
@@ -81,6 +83,11 @@ export class Github {
let isNewUser = false; let isNewUser = false;
if (!user) { if (!user) {
// Check if signups are disabled
if (DISABLE_SIGNUPS) {
throw new BadRequest('New user signups are currently disabled');
}
user = await prisma.user.create({ user = await prisma.user.create({
data: { data: {
email, email,
+7
View File
@@ -4,11 +4,13 @@ import type {NextFunction, Request, Response} from 'express';
import { import {
API_URI, API_URI,
DASHBOARD_URI, DASHBOARD_URI,
DISABLE_SIGNUPS,
GOOGLE_OAUTH_CLIENT, GOOGLE_OAUTH_CLIENT,
GOOGLE_OAUTH_ENABLED, GOOGLE_OAUTH_ENABLED,
GOOGLE_OAUTH_SECRET, GOOGLE_OAUTH_SECRET,
} from '../../app/constants.js'; } from '../../app/constants.js';
import {prisma} from '../../database/prisma.js'; import {prisma} from '../../database/prisma.js';
import {BadRequest} from '../../exceptions/index.js';
import {jwt} from '../../middleware/auth.js'; import {jwt} from '../../middleware/auth.js';
import {NtfyService} from '../../services/NtfyService.js'; import {NtfyService} from '../../services/NtfyService.js';
import {UserService} from '../../services/UserService.js'; import {UserService} from '../../services/UserService.js';
@@ -71,6 +73,11 @@ export class Google {
let isNewUser = false; let isNewUser = false;
if (!user) { if (!user) {
// Check if signups are disabled
if (DISABLE_SIGNUPS) {
throw new BadRequest('New user signups are currently disabled');
}
user = await prisma.user.create({ user = await prisma.user.create({
data: { data: {
email, email,
+57 -4
View File
@@ -72,20 +72,23 @@ export class Segments {
@CatchAsync @CatchAsync
public async create(req: Request, res: Response, _next: NextFunction) { public async create(req: Request, res: Response, _next: NextFunction) {
const auth = res.locals.auth; const auth = res.locals.auth;
const {name, description, condition, trackMembership} = req.body; const {name, description, type, condition, trackMembership} = req.body;
if (!name) { if (!name) {
return res.status(400).json({error: 'Name is required'}); return res.status(400).json({error: 'Name is required'});
} }
if (!condition || typeof condition !== 'object') { const segmentType = type ?? 'DYNAMIC';
return res.status(400).json({error: 'Condition is required and must be an object'});
if (segmentType === 'DYNAMIC' && (!condition || typeof condition !== 'object')) {
return res.status(400).json({error: 'Condition is required and must be an object for DYNAMIC segments'});
} }
const segment = await SegmentService.create(auth.projectId!, { const segment = await SegmentService.create(auth.projectId!, {
name, name,
description, description,
condition, type: segmentType,
condition: segmentType === 'DYNAMIC' ? condition : undefined,
trackMembership, trackMembership,
}); });
@@ -142,6 +145,56 @@ export class Segments {
return res.status(204).send(); return res.status(204).send();
} }
/**
* POST /segments/:id/members
* Add contacts to a static segment by email
*/
@Post(':id/members')
@Middleware([requireAuth, requireEmailVerified])
@CatchAsync
public async addMembers(req: Request, res: Response, _next: NextFunction) {
const auth = res.locals.auth;
const segmentId = req.params.id;
const {emails} = req.body;
if (!segmentId) {
return res.status(400).json({error: 'Segment ID is required'});
}
if (!Array.isArray(emails) || emails.length === 0) {
return res.status(400).json({error: 'emails must be a non-empty array'});
}
const result = await SegmentService.addContacts(auth.projectId!, segmentId, emails);
return res.status(200).json(result);
}
/**
* DELETE /segments/:id/members
* Remove contacts from a static segment by email
*/
@Delete(':id/members')
@Middleware([requireAuth, requireEmailVerified])
@CatchAsync
public async removeMembers(req: Request, res: Response, _next: NextFunction) {
const auth = res.locals.auth;
const segmentId = req.params.id;
const {emails} = req.body;
if (!segmentId) {
return res.status(400).json({error: 'Segment ID is required'});
}
if (!Array.isArray(emails) || emails.length === 0) {
return res.status(400).json({error: 'emails must be a non-empty array'});
}
const result = await SegmentService.removeContacts(auth.projectId!, segmentId, emails);
return res.status(200).json(result);
}
/** /**
* POST /segments/:id/compute * POST /segments/:id/compute
* Recompute segment membership for all contacts * Recompute segment membership for all contacts
+3
View File
@@ -330,6 +330,7 @@ export class Users {
billingLimitWorkflows: true, billingLimitWorkflows: true,
billingLimitCampaigns: true, billingLimitCampaigns: true,
billingLimitTransactional: true, billingLimitTransactional: true,
billingLimitInbound: true,
}, },
}); });
@@ -349,6 +350,7 @@ export class Users {
billingLimitWorkflows: data.workflows, billingLimitWorkflows: data.workflows,
billingLimitCampaigns: data.campaigns, billingLimitCampaigns: data.campaigns,
billingLimitTransactional: data.transactional, billingLimitTransactional: data.transactional,
billingLimitInbound: data.inbound,
}, },
}); });
@@ -360,6 +362,7 @@ export class Users {
workflows: project.billingLimitWorkflows, workflows: project.billingLimitWorkflows,
campaigns: project.billingLimitCampaigns, campaigns: project.billingLimitCampaigns,
transactional: project.billingLimitTransactional, transactional: project.billingLimitTransactional,
inbound: project.billingLimitInbound,
}, },
data, data,
); );
+223 -18
View File
@@ -1,6 +1,6 @@
import {Controller, Post} from '@overnightjs/core'; import {Controller, Post} from '@overnightjs/core';
import type {Prisma} from '@plunk/db'; import type {Prisma} from '@plunk/db';
import {EmailStatus} from '@plunk/db'; import {EmailSourceType, EmailStatus} from '@plunk/db';
import type {Request, Response} from 'express'; import type {Request, Response} from 'express';
import signale from 'signale'; import signale from 'signale';
import type Stripe from 'stripe'; import type Stripe from 'stripe';
@@ -8,7 +8,10 @@ import type Stripe from 'stripe';
import {STRIPE_ENABLED, STRIPE_WEBHOOK_SECRET} from '../app/constants.js'; import {STRIPE_ENABLED, STRIPE_WEBHOOK_SECRET} from '../app/constants.js';
import {stripe} from '../app/stripe.js'; import {stripe} from '../app/stripe.js';
import {prisma} from '../database/prisma.js'; import {prisma} from '../database/prisma.js';
import {BillingLimitService} from '../services/BillingLimitService.js';
import {ContactService} from '../services/ContactService.js';
import {EventService} from '../services/EventService.js'; import {EventService} from '../services/EventService.js';
import {MeterService} from '../services/MeterService.js';
import {NtfyService} from '../services/NtfyService.js'; import {NtfyService} from '../services/NtfyService.js';
import {SecurityService} from '../services/SecurityService.js'; import {SecurityService} from '../services/SecurityService.js';
import {CatchAsync} from '../utils/asyncHandler.js'; import {CatchAsync} from '../utils/asyncHandler.js';
@@ -21,7 +24,8 @@ import {CatchAsync} from '../utils/asyncHandler.js';
export class Webhooks { export class Webhooks {
/** /**
* Receive SNS webhook notifications from AWS SES * Receive SNS webhook notifications from AWS SES
* Handles email events: delivery, open, click, bounce, complaint * Handles outbound email events: delivery, open, click, bounce, complaint
* Handles inbound email notifications: received emails via SES receiving
*/ */
@Post('sns') @Post('sns')
@CatchAsync @CatchAsync
@@ -30,11 +34,35 @@ export class Webhooks {
// Handle SNS subscription confirmation FIRST (before parsing Message field) // Handle SNS subscription confirmation FIRST (before parsing Message field)
if (req.body.Type === 'SubscriptionConfirmation') { if (req.body.Type === 'SubscriptionConfirmation') {
signale.info('SNS Subscription Confirmation received'); signale.info('SNS Subscription Confirmation received');
signale.info('Subscribe URL:', req.body.SubscribeURL);
// Validate SubscribeURL to prevent SSRF: must be HTTPS and from an official AWS SNS host.
// Legitimate URLs look like:
// https://sns.<region>.amazonaws.com/?Action=ConfirmSubscription&...
const subscribeURL: unknown = req.body.SubscribeURL;
if (typeof subscribeURL !== 'string') {
signale.warn('SNS SubscriptionConfirmation missing SubscribeURL');
return res.status(400).json({success: false, message: 'Invalid SubscribeURL'});
}
let parsedURL: URL;
try {
parsedURL = new URL(subscribeURL);
} catch {
signale.warn('SNS SubscriptionConfirmation has unparseable SubscribeURL');
return res.status(400).json({success: false, message: 'Invalid SubscribeURL'});
}
// Only allow HTTPS requests to official AWS SNS endpoints.
// The hostname must be exactly sns.<region>.amazonaws.com.
const SNS_HOST_RE = /^sns\.[a-z0-9-]+\.amazonaws\.com$/;
if (parsedURL.protocol !== 'https:' || !SNS_HOST_RE.test(parsedURL.hostname)) {
signale.warn(`SNS SubscriptionConfirmation rejected — disallowed SubscribeURL host: ${parsedURL.hostname}`);
return res.status(400).json({success: false, message: 'Invalid SubscribeURL'});
}
// Automatically confirm the subscription // Automatically confirm the subscription
try { try {
const confirmResponse = await fetch(req.body.SubscribeURL); const confirmResponse = await fetch(subscribeURL);
if (confirmResponse.ok) { if (confirmResponse.ok) {
signale.success('SNS subscription confirmed successfully'); signale.success('SNS subscription confirmed successfully');
return res.status(200).json({ return res.status(200).json({
@@ -46,7 +74,6 @@ export class Webhooks {
return res.status(200).json({ return res.status(200).json({
success: false, success: false,
message: 'Failed to confirm subscription', message: 'Failed to confirm subscription',
subscribeURL: req.body.SubscribeURL,
}); });
} }
} catch (confirmError) { } catch (confirmError) {
@@ -54,7 +81,6 @@ export class Webhooks {
return res.status(200).json({ return res.status(200).json({
success: false, success: false,
message: 'Error confirming subscription', message: 'Error confirming subscription',
subscribeURL: req.body.SubscribeURL,
}); });
} }
} }
@@ -67,6 +93,150 @@ export class Webhooks {
// Parse the nested SES event from the Message field // Parse the nested SES event from the Message field
const body = JSON.parse(req.body.Message); const body = JSON.parse(req.body.Message);
// Check if this is an inbound email notification (SES Receiving)
if (body.notificationType === 'Received') {
signale.info('[WEBHOOK] Received inbound email notification from SES');
try {
// Extract recipient addresses from the inbound email
const recipients = body.receipt?.recipients || [];
if (recipients.length === 0) {
signale.warn('[WEBHOOK] No recipients found in inbound email');
return res.status(200).json({success: true, message: 'No recipients found'});
}
// For each recipient, identify the domain and create events
for (const recipient of recipients) {
const recipientEmail = recipient as string;
const domain = recipientEmail.split('@')[1];
if (!domain) {
signale.warn('[WEBHOOK] Invalid recipient email format:', recipientEmail);
continue;
}
// Find ALL projects that have this domain verified
// A domain can be shared across multiple projects if users are members of both
const domainRecords = await prisma.domain.findMany({
where: {
domain,
verified: true, // Only process emails for verified domains
},
include: {
project: true,
},
});
if (domainRecords.length === 0) {
signale.info(`[WEBHOOK] No verified domain found for: ${domain}`);
continue;
}
signale.info(
`[WEBHOOK] Found ${domainRecords.length} project(s) with verified domain ${domain}. Processing inbound email for all.`,
);
// Extract sender information (same for all projects)
const senderEmail = body.mail?.source;
const senderFromHeader = body.mail?.commonHeaders?.from?.[0] || senderEmail;
// Process inbound email for each project that has this domain verified
for (const domainRecord of domainRecords) {
signale.info(`[WEBHOOK] Processing inbound email for project: ${domainRecord.project.name}`);
// Check billing limits before processing inbound email
const limitCheck = await BillingLimitService.checkLimit(domainRecord.projectId, EmailSourceType.INBOUND);
if (!limitCheck.allowed) {
signale.warn(
`[WEBHOOK] Inbound email blocked for project ${domainRecord.project.name}: ${limitCheck.message}`,
);
continue; // Skip this project but continue processing for other projects
}
// Find or create a contact for the sender in this project
let contact;
if (senderEmail) {
contact = await ContactService.upsert(
domainRecord.projectId,
senderEmail,
undefined, // No additional data
true, // Subscribe by default for inbound email senders
);
}
// Create an Email record for tracking (no actual email content since it's inbound)
const inboundEmail = await prisma.email.create({
data: {
projectId: domainRecord.projectId,
contactId: contact!.id,
subject: body.mail?.commonHeaders?.subject || '(No subject)',
body: '', // Inbound emails don't have body content in our system
from: recipientEmail, // The recipient address that received the email
sourceType: EmailSourceType.INBOUND,
status: EmailStatus.RECEIVED, // Inbound emails use RECEIVED status
deliveredAt: new Date(body.mail?.timestamp || new Date()),
},
});
// Increment usage counter in cache
await BillingLimitService.incrementUsage(domainRecord.projectId, EmailSourceType.INBOUND);
// Record Stripe metering if project has customer
if (domainRecord.project.customer) {
await MeterService.recordEmailSent(
domainRecord.project.customer,
1, // Inbound emails count as 1 credit
`email_${inboundEmail.id}`,
);
}
// Prepare event data with all inbound email details
const eventData = {
messageId: body.mail?.messageId,
from: senderEmail,
fromHeader: senderFromHeader,
to: recipientEmail,
subject: body.mail?.commonHeaders?.subject,
timestamp: body.mail?.timestamp,
recipients: body.receipt?.recipients,
hasContent: !!body.content,
// Security verdicts
spamVerdict: body.receipt?.spamVerdict?.status,
virusVerdict: body.receipt?.virusVerdict?.status,
spfVerdict: body.receipt?.spfVerdict?.status,
dkimVerdict: body.receipt?.dkimVerdict?.status,
dmarcVerdict: body.receipt?.dmarcVerdict?.status,
// Processing metadata
processingTimeMillis: body.receipt?.processingTimeMillis,
};
// Create the email.received event (this will trigger workflows)
await EventService.trackEvent(
domainRecord.projectId,
'email.received',
contact?.id,
inboundEmail.id, // Link the event to the inbound email record
eventData,
);
signale.success(
`[WEBHOOK] Created email.received event for ${senderEmail}${recipientEmail} (project: ${domainRecord.project.name})`,
);
}
}
return res.status(200).json({success: true, message: 'Inbound email processed'});
} catch (inboundError) {
signale.error('[WEBHOOK] Error processing inbound email:', inboundError);
// Return 200 to acknowledge receipt even if processing failed
return res.status(200).json({success: true, message: 'Error processing inbound email'});
}
}
// Handle outbound email event notifications (existing logic)
const eventType = body.eventType as 'Bounce' | 'Delivery' | 'Open' | 'Complaint' | 'Click'; const eventType = body.eventType as 'Bounce' | 'Delivery' | 'Open' | 'Complaint' | 'Click';
const messageId = body.mail?.messageId; const messageId = body.mail?.messageId;
@@ -152,29 +322,62 @@ export class Webhooks {
break; break;
} }
case 'Bounce': case 'Bounce': {
signale.warn(`[WEBHOOK] Bounce received for ${email.contact.email} from ${email.project.name}`); const bounceType = body.bounce?.bounceType;
const isPermanentBounce = bounceType === 'Permanent';
const isTransientBounce = bounceType === 'Transient';
if (isPermanentBounce) {
// Hard bounce - counts toward bounce rate and unsubscribes contact
signale.warn(`[WEBHOOK] Permanent bounce received for ${email.contact.email} from ${email.project.name}`);
updateData.status = EmailStatus.BOUNCED; updateData.status = EmailStatus.BOUNCED;
updateData.bouncedAt = now; updateData.bouncedAt = now;
// Unsubscribe contact on bounce // Unsubscribe contact on permanent bounce
await prisma.contact.update({ await prisma.contact.update({
where: {id: email.contactId}, where: {id: email.contactId},
data: {subscribed: false}, data: {subscribed: false},
}); });
eventData = { eventData = {
...baseEventData, ...baseEventData,
bounceType: body.bounce?.bounceType, bounceType,
bouncedAt: now.toISOString(), bouncedAt: now.toISOString(),
}; };
// Send notification about bounce // Send notification about permanent bounce
await NtfyService.notifyEmailBounce( await NtfyService.notifyEmailBounce(email.project.name, email.projectId, email.contact.email, bounceType);
email.project.name, } else if (isTransientBounce) {
email.projectId, // Soft bounce (e.g., out-of-office, mailbox full) - don't count toward bounce rate
email.contact.email, signale.info(
body.bounce?.bounceType, `[WEBHOOK] Transient bounce received for ${email.contact.email} from ${email.project.name} (not counted toward bounce rate)`,
); );
// Don't update email status or unsubscribe contact
// Just track the event for visibility
eventData = {
...baseEventData,
bounceType,
transientBounce: true,
};
} else {
// Unknown bounce type - treat as permanent to be safe
signale.warn(
`[WEBHOOK] Unknown bounce type (${bounceType}) received for ${email.contact.email} from ${email.project.name} - treating as permanent`,
);
updateData.status = EmailStatus.BOUNCED;
updateData.bouncedAt = now;
await prisma.contact.update({
where: {id: email.contactId},
data: {subscribed: false},
});
eventData = {
...baseEventData,
bounceType,
bouncedAt: now.toISOString(),
};
await NtfyService.notifyEmailBounce(email.project.name, email.projectId, email.contact.email, bounceType);
}
break; break;
}
case 'Complaint': case 'Complaint':
signale.warn(`[WEBHOOK] Complaint received for ${email.contact.email} from ${email.project.name}`); signale.warn(`[WEBHOOK] Complaint received for ${email.contact.email} from ${email.project.name}`);
@@ -208,8 +411,10 @@ export class Webhooks {
// Track event (this will trigger workflows) // Track event (this will trigger workflows)
await EventService.trackEvent(email.projectId, eventName, email.contactId, email.id, eventData); await EventService.trackEvent(email.projectId, eventName, email.contactId, email.id, eventData);
// Check security limits for bounce and complaint events // Check security limits only for permanent bounces and complaints
if (eventType === 'Bounce' || eventType === 'Complaint') { // Transient bounces (soft bounces) don't count toward bounce rate
const isPermanentBounce = eventType === 'Bounce' && body.bounce?.bounceType === 'Permanent';
if (isPermanentBounce || eventType === 'Complaint') {
await SecurityService.checkAndEnforceSecurityLimits(email.projectId); await SecurityService.checkAndEnforceSecurityLimits(email.projectId);
} }
+13 -8
View File
@@ -122,9 +122,13 @@ export async function checkDomainVerifications() {
// Send email notification about domain verified // Send email notification about domain verified
try { try {
// Use SETNX to atomically check and set the flag (prevents race conditions)
const cacheKey = Keys.Domain.verifiedEmail(dbDomain.id); const cacheKey = Keys.Domain.verifiedEmail(dbDomain.id);
const alreadySent = await redis.get(cacheKey); const ttl = 604800; // 7 days
if (alreadySent !== '1') {
// SETNX returns 1 if key was set (didn't exist), 0 if key already existed
const wasSet = await redis.set(cacheKey, '1', 'EX', ttl, 'NX');
if (wasSet) {
const members = await MembershipService.getMembers(dbDomain.projectId); const members = await MembershipService.getMembers(dbDomain.projectId);
const emails = members.map(m => m.email); const emails = members.map(m => m.email);
if (emails.length > 0) { if (emails.length > 0) {
@@ -138,7 +142,6 @@ export async function checkDomainVerifications() {
await Promise.all( await Promise.all(
emails.map(email => sendPlatformEmail(email, 'Domain Verified Successfully', template)), emails.map(email => sendPlatformEmail(email, 'Domain Verified Successfully', template)),
); );
await redis.setex(cacheKey, 604800, '1'); // 7 days
} }
} }
} catch (error) { } catch (error) {
@@ -156,12 +159,17 @@ export async function checkDomainVerifications() {
// Send email notification about domain verification failed // Send email notification about domain verification failed
try { try {
// Use SETNX to atomically check and set the flag (prevents race conditions)
const now = new Date(); const now = new Date();
const year = now.getFullYear(); const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0'); const month = String(now.getMonth() + 1).padStart(2, '0');
const cacheKey = Keys.Domain.unverifiedEmail(dbDomain.id, year, month); const cacheKey = Keys.Domain.unverifiedEmail(dbDomain.id, year, month);
const alreadySent = await redis.get(cacheKey); const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);
if (alreadySent !== '1') { const ttl = Math.floor((endOfMonth.getTime() - now.getTime()) / 1000);
// SETNX returns 1 if key was set (didn't exist), 0 if key already existed
const wasSet = await redis.set(cacheKey, '1', 'EX', ttl, 'NX');
if (wasSet) {
const members = await MembershipService.getMembers(dbDomain.projectId); const members = await MembershipService.getMembers(dbDomain.projectId);
const emails = members.map(m => m.email); const emails = members.map(m => m.email);
if (emails.length > 0) { if (emails.length > 0) {
@@ -175,9 +183,6 @@ export async function checkDomainVerifications() {
await Promise.all( await Promise.all(
emails.map(email => sendPlatformEmail(email, 'Domain Verification Failed', template)), emails.map(email => sendPlatformEmail(email, 'Domain Verification Failed', template)),
); );
const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);
const ttl = Math.floor((endOfMonth.getTime() - now.getTime()) / 1000);
await redis.setex(cacheKey, ttl, '1');
} }
} }
} catch (error) { } catch (error) {
+18 -2
View File
@@ -117,10 +117,25 @@ export async function createEmailWorker() {
const fromName = email.fromName || email.project.name; const fromName = email.fromName || email.project.name;
const fromEmail = email.from; const fromEmail = email.from;
// Parse custom headers from JSON
const customHeaders =
email.headers && typeof email.headers === 'object' && !Array.isArray(email.headers)
? (email.headers as Record<string, string>)
: undefined;
// Check for custom recipient override in headers
const recipientEmail = customHeaders?.['X-Plunk-Recipient-Override'] || email.contact.email;
// Remove internal headers before sending
const publicHeaders = customHeaders ? {...customHeaders} : undefined;
if (publicHeaders && 'X-Plunk-Recipient-Override' in publicHeaders) {
delete publicHeaders['X-Plunk-Recipient-Override'];
}
// Build recipient with name if available // Build recipient with name if available
const recipient: {name?: string; email: string} | string = email.toName const recipient: {name?: string; email: string} | string = email.toName
? {name: email.toName, email: email.contact.email} ? {name: email.toName, email: recipientEmail}
: email.contact.email; : recipientEmail;
// Determine tracking based on project settings and email type // Determine tracking based on project settings and email type
const shouldTrack = EmailService.shouldTrackEmail(email.project.tracking, email.sourceType); const shouldTrack = EmailService.shouldTrackEmail(email.project.tracking, email.sourceType);
@@ -137,6 +152,7 @@ export async function createEmailWorker() {
html: compiledHtml, html: compiledHtml,
}, },
reply: email.replyTo || undefined, reply: email.replyTo || undefined,
headers: publicHeaders,
tracking: shouldTrack, tracking: shouldTrack,
attachments: email.attachments as {filename: string; content: string; contentType: string}[] | null, attachments: email.attachments as {filename: string; content: string; contentType: string}[] | null,
}); });
+21 -36
View File
@@ -18,8 +18,6 @@ import {SegmentService} from '../services/SegmentService.js';
* - For segments without trackMembership: only update counts * - For segments without trackMembership: only update counts
*/ */
async function processProjectSegments(projectId: string, projectName?: string): Promise<void> { async function processProjectSegments(projectId: string, projectName?: string): Promise<void> {
const logPrefix = projectName ? `${projectName} (${projectId})` : projectId;
// Get all segments for this project, separating tracked vs non-tracked // Get all segments for this project, separating tracked vs non-tracked
const segments = await prisma.segment.findMany({ const segments = await prisma.segment.findMany({
where: {projectId}, where: {projectId},
@@ -29,45 +27,44 @@ async function processProjectSegments(projectId: string, projectName?: string):
const trackedSegments = segments.filter(s => s.trackMembership); const trackedSegments = segments.filter(s => s.trackMembership);
const nonTrackedSegments = segments.filter(s => !s.trackMembership); const nonTrackedSegments = segments.filter(s => !s.trackMembership);
signale.info(
`[SEGMENT-COUNT-WORKER] Project ${logPrefix}: ${trackedSegments.length} tracked, ${nonTrackedSegments.length} non-tracked segments`,
);
// Process tracked segments with full membership computation (creates events) // Process tracked segments with full membership computation (creates events)
let updatedSegmentCount = 0;
let totalAdded = 0;
let totalRemoved = 0;
if (trackedSegments.length > 0) { if (trackedSegments.length > 0) {
for (const segment of trackedSegments) { for (const segment of trackedSegments) {
try { try {
signale.info(
`[SEGMENT-COUNT-WORKER] Computing membership for tracked segment "${segment.name}" (${segment.id})`,
);
const result = await SegmentService.computeMembership(projectId, segment.id); const result = await SegmentService.computeMembership(projectId, segment.id);
signale.success(
`[SEGMENT-COUNT-WORKER] Segment "${segment.name}": +${result.added} entries, -${result.removed} exits, ${result.total} total members`,
);
// Notify about segment membership update only if there were actual changes // Track segments with actual changes for bundled notification
if (projectName && (result.added > 0 || result.removed > 0)) { if (result.added > 0 || result.removed > 0) {
await NtfyService.notifySegmentMembershipComputed( updatedSegmentCount++;
segment.name, totalAdded += result.added;
projectName, totalRemoved += result.removed;
projectId,
result.total,
result.added,
result.removed,
);
} }
} catch (error) { } catch (error) {
signale.error(`[SEGMENT-COUNT-WORKER] Failed to compute membership for segment ${segment.id}:`, error); signale.error(`[SEGMENT-COUNT-WORKER] Failed to compute membership for segment ${segment.id}:`, error);
// Continue with other segments // Continue with other segments
} }
} }
// Send bundled notification if there were any changes
if (projectName && updatedSegmentCount > 0) {
await NtfyService.notifySegmentMembershipBundled(
projectName,
projectId,
updatedSegmentCount,
totalAdded,
totalRemoved,
);
}
} }
// Process non-tracked segments with count-only update (lightweight) // Process non-tracked segments with count-only update (lightweight)
if (nonTrackedSegments.length > 0) { if (nonTrackedSegments.length > 0) {
try { try {
await SegmentService.refreshAllMemberCounts(projectId); await SegmentService.refreshAllMemberCounts(projectId);
signale.info(`[SEGMENT-COUNT-WORKER] Updated counts for ${nonTrackedSegments.length} non-tracked segments`);
} catch (error) { } catch (error) {
signale.error(`[SEGMENT-COUNT-WORKER] Failed to update counts for non-tracked segments:`, error); signale.error(`[SEGMENT-COUNT-WORKER] Failed to update counts for non-tracked segments:`, error);
} }
@@ -80,14 +77,10 @@ async function processProjectSegments(projectId: string, projectName?: string):
async function processSegmentCountUpdate(job: Job<SegmentCountJobData>): Promise<void> { async function processSegmentCountUpdate(job: Job<SegmentCountJobData>): Promise<void> {
const {projectId} = job.data; const {projectId} = job.data;
signale.info(`[SEGMENT-COUNT-WORKER] Starting segment count update job ${job.id}`);
try { try {
if (projectId) { if (projectId) {
// Process specific project // Process specific project
signale.info(`[SEGMENT-COUNT-WORKER] Processing segments for project ${projectId}`);
await processProjectSegments(projectId); await processProjectSegments(projectId);
signale.success(`[SEGMENT-COUNT-WORKER] Completed segments for project ${projectId}`);
} else { } else {
// Process all active projects // Process all active projects
const projects = await prisma.project.findMany({ const projects = await prisma.project.findMany({
@@ -95,7 +88,7 @@ async function processSegmentCountUpdate(job: Job<SegmentCountJobData>): Promise
select: {id: true, name: true}, select: {id: true, name: true},
}); });
signale.info(`[SEGMENT-COUNT-WORKER] Found ${projects.length} active projects`); signale.info(`[SEGMENT-COUNT-WORKER] Processing ${projects.length} active projects`);
// Process projects in batches to avoid overwhelming the database // Process projects in batches to avoid overwhelming the database
const PROJECT_BATCH_SIZE = 10; const PROJECT_BATCH_SIZE = 10;
@@ -105,9 +98,7 @@ async function processSegmentCountUpdate(job: Job<SegmentCountJobData>): Promise
await Promise.all( await Promise.all(
batch.map(async project => { batch.map(async project => {
try { try {
signale.info(`[SEGMENT-COUNT-WORKER] Processing project ${project.name} (${project.id})`);
await processProjectSegments(project.id, project.name); await processProjectSegments(project.id, project.name);
signale.success(`[SEGMENT-COUNT-WORKER] Completed project ${project.name}`);
} catch (error) { } catch (error) {
signale.error(`[SEGMENT-COUNT-WORKER] Failed to process project ${project.id}:`, error); signale.error(`[SEGMENT-COUNT-WORKER] Failed to process project ${project.id}:`, error);
// Don't throw - continue with other projects // Don't throw - continue with other projects
@@ -120,8 +111,6 @@ async function processSegmentCountUpdate(job: Job<SegmentCountJobData>): Promise
await new Promise(resolve => setTimeout(resolve, 2000)); await new Promise(resolve => setTimeout(resolve, 2000));
} }
} }
signale.success(`[SEGMENT-COUNT-WORKER] Completed all segment updates`);
} }
} catch (error) { } catch (error) {
signale.error(`[SEGMENT-COUNT-WORKER] Error processing job ${job.id}:`, error); signale.error(`[SEGMENT-COUNT-WORKER] Error processing job ${job.id}:`, error);
@@ -148,10 +137,6 @@ export function createSegmentCountWorker(): Worker {
}, },
); );
worker.on('completed', job => {
signale.success(`[SEGMENT-COUNT-WORKER] Job ${job.id} completed`);
});
worker.on('failed', (job, error) => { worker.on('failed', (job, error) => {
signale.error(`[SEGMENT-COUNT-WORKER] Job ${job?.id} failed:`, error); signale.error(`[SEGMENT-COUNT-WORKER] Job ${job?.id} failed:`, error);
}); });
+97 -11
View File
@@ -366,15 +366,41 @@ export class ActivityService {
...(contactId ? {contactId} : {}), ...(contactId ? {contactId} : {}),
}; };
// Build OR conditions to filter by the appropriate timestamp field for each activity type
// This ensures we fetch emails where the specific activity (bounced, sent, etc.) occurred in the date range
const orConditions: Prisma.EmailWhereInput[] = [];
if (!types || types.includes(ActivityType.EMAIL_SENT)) {
orConditions.push({sentAt: {not: null, ...dateFilter}});
}
if (!types || types.includes(ActivityType.EMAIL_DELIVERED)) {
orConditions.push({deliveredAt: {not: null, ...dateFilter}});
}
if (!types || types.includes(ActivityType.EMAIL_RECEIVED)) {
orConditions.push({deliveredAt: {not: null, ...dateFilter}, sourceType: 'INBOUND'});
}
if (!types || types.includes(ActivityType.EMAIL_OPENED)) {
orConditions.push({openedAt: {not: null, ...dateFilter}});
}
if (!types || types.includes(ActivityType.EMAIL_CLICKED)) {
orConditions.push({clickedAt: {not: null, ...dateFilter}});
}
if (!types || types.includes(ActivityType.EMAIL_BOUNCED)) {
orConditions.push({bouncedAt: {not: null, ...dateFilter}});
}
if (!types || types.includes(ActivityType.EMAIL_COMPLAINT)) {
orConditions.push({complainedAt: {not: null, ...dateFilter}});
}
// If no OR conditions, return empty (shouldn't happen but defensive)
if (orConditions.length === 0) {
return [];
}
const emails = await prisma.email.findMany({ const emails = await prisma.email.findMany({
where: { where: {
...where, ...where,
createdAt: cursorTimestamp OR: orConditions,
? {
...dateFilter,
lt: cursorTimestamp,
}
: dateFilter,
}, },
orderBy: {createdAt: 'desc'}, orderBy: {createdAt: 'desc'},
take: limit, take: limit,
@@ -401,6 +427,27 @@ export class ActivityService {
}, },
}); });
// Helper function to check if timestamp is within date range
const isInDateRange = (timestamp: Date | null) => {
if (!timestamp) return false;
// Check against date filter
const time = timestamp.getTime();
if (dateFilter.gte) {
const gteTime = dateFilter.gte instanceof Date ? dateFilter.gte.getTime() : new Date(dateFilter.gte).getTime();
if (time < gteTime) return false;
}
if (dateFilter.lte) {
const lteTime = dateFilter.lte instanceof Date ? dateFilter.lte.getTime() : new Date(dateFilter.lte).getTime();
if (time > lteTime) return false;
}
// Check against cursor for pagination
if (cursorTimestamp && time >= cursorTimestamp.getTime()) return false;
return true;
};
// Convert each email into multiple activities based on its state // Convert each email into multiple activities based on its state
for (const email of emails) { for (const email of emails) {
const baseMetadata = { const baseMetadata = {
@@ -415,7 +462,7 @@ export class ActivityService {
workflowName: email.workflowExecution?.workflow?.name, workflowName: email.workflowExecution?.workflow?.name,
}; };
if (email.sentAt && (!types || types.includes(ActivityType.EMAIL_SENT))) { if (email.sentAt && (!types || types.includes(ActivityType.EMAIL_SENT)) && isInDateRange(email.sentAt)) {
activities.push({ activities.push({
id: `${email.id}_sent`, id: `${email.id}_sent`,
type: ActivityType.EMAIL_SENT, type: ActivityType.EMAIL_SENT,
@@ -426,7 +473,11 @@ export class ActivityService {
}); });
} }
if (email.deliveredAt && (!types || types.includes(ActivityType.EMAIL_DELIVERED))) { if (
email.deliveredAt &&
(!types || types.includes(ActivityType.EMAIL_DELIVERED)) &&
isInDateRange(email.deliveredAt)
) {
activities.push({ activities.push({
id: `${email.id}_delivered`, id: `${email.id}_delivered`,
type: ActivityType.EMAIL_DELIVERED, type: ActivityType.EMAIL_DELIVERED,
@@ -437,7 +488,23 @@ export class ActivityService {
}); });
} }
if (email.openedAt && (!types || types.includes(ActivityType.EMAIL_OPENED))) { if (
email.deliveredAt &&
email.sourceType === 'INBOUND' &&
(!types || types.includes(ActivityType.EMAIL_RECEIVED)) &&
isInDateRange(email.deliveredAt)
) {
activities.push({
id: `${email.id}_received`,
type: ActivityType.EMAIL_RECEIVED,
timestamp: email.deliveredAt,
contactEmail: email.contact.email,
contactId: email.contactId,
metadata: baseMetadata,
});
}
if (email.openedAt && (!types || types.includes(ActivityType.EMAIL_OPENED)) && isInDateRange(email.openedAt)) {
activities.push({ activities.push({
id: `${email.id}_opened`, id: `${email.id}_opened`,
type: ActivityType.EMAIL_OPENED, type: ActivityType.EMAIL_OPENED,
@@ -452,7 +519,7 @@ export class ActivityService {
} }
// Email clicked // Email clicked
if (email.clickedAt && (!types || types.includes(ActivityType.EMAIL_CLICKED))) { if (email.clickedAt && (!types || types.includes(ActivityType.EMAIL_CLICKED)) && isInDateRange(email.clickedAt)) {
activities.push({ activities.push({
id: `${email.id}_clicked`, id: `${email.id}_clicked`,
type: ActivityType.EMAIL_CLICKED, type: ActivityType.EMAIL_CLICKED,
@@ -467,7 +534,7 @@ export class ActivityService {
} }
// Email bounced // Email bounced
if (email.bouncedAt && (!types || types.includes(ActivityType.EMAIL_BOUNCED))) { if (email.bouncedAt && (!types || types.includes(ActivityType.EMAIL_BOUNCED)) && isInDateRange(email.bouncedAt)) {
activities.push({ activities.push({
id: `${email.id}_bounced`, id: `${email.id}_bounced`,
type: ActivityType.EMAIL_BOUNCED, type: ActivityType.EMAIL_BOUNCED,
@@ -480,6 +547,25 @@ export class ActivityService {
}, },
}); });
} }
// Email complaint
if (
email.complainedAt &&
(!types || types.includes(ActivityType.EMAIL_COMPLAINT)) &&
isInDateRange(email.complainedAt)
) {
activities.push({
id: `${email.id}_complaint`,
type: ActivityType.EMAIL_COMPLAINT,
timestamp: email.complainedAt,
contactEmail: email.contact.email,
contactId: email.contactId,
metadata: {
...baseMetadata,
error: email.error,
},
});
}
} }
return activities; return activities;
+44 -19
View File
@@ -157,6 +157,7 @@ export class BillingLimitService {
billingLimitWorkflows: true, billingLimitWorkflows: true,
billingLimitCampaigns: true, billingLimitCampaigns: true,
billingLimitTransactional: true, billingLimitTransactional: true,
billingLimitInbound: true,
}, },
}); });
@@ -183,6 +184,9 @@ export class BillingLimitService {
case EmailSourceType.TRANSACTIONAL: case EmailSourceType.TRANSACTIONAL:
limit = project.billingLimitTransactional; limit = project.billingLimitTransactional;
break; break;
case EmailSourceType.INBOUND:
limit = project.billingLimitInbound;
break;
default: default:
limit = null; limit = null;
} }
@@ -191,7 +195,8 @@ export class BillingLimitService {
const hasCustomLimits = const hasCustomLimits =
project.billingLimitWorkflows !== null || project.billingLimitWorkflows !== null ||
project.billingLimitCampaigns !== null || project.billingLimitCampaigns !== null ||
project.billingLimitTransactional !== null; project.billingLimitTransactional !== null ||
project.billingLimitInbound !== null;
// Free tier projects (no subscription and no custom limits): enforce total 1000 email/month limit // Free tier projects (no subscription and no custom limits): enforce total 1000 email/month limit
// Only enforce free tier limits if billing is enabled // Only enforce free tier limits if billing is enabled
@@ -368,6 +373,7 @@ export class BillingLimitService {
billingLimitWorkflows: true, billingLimitWorkflows: true,
billingLimitCampaigns: true, billingLimitCampaigns: true,
billingLimitTransactional: true, billingLimitTransactional: true,
billingLimitInbound: true,
}, },
}); });
@@ -390,10 +396,11 @@ export class BillingLimitService {
} }
// Get usage for all categories in parallel // Get usage for all categories in parallel
const [workflowUsage, campaignUsage, transactionalUsage] = await Promise.all([ const [workflowUsage, campaignUsage, transactionalUsage, inboundUsage] = await Promise.all([
this.getUsage(projectId, EmailSourceType.WORKFLOW), this.getUsage(projectId, EmailSourceType.WORKFLOW),
this.getUsage(projectId, EmailSourceType.CAMPAIGN), this.getUsage(projectId, EmailSourceType.CAMPAIGN),
this.getUsage(projectId, EmailSourceType.TRANSACTIONAL), this.getUsage(projectId, EmailSourceType.TRANSACTIONAL),
this.getUsage(projectId, EmailSourceType.INBOUND),
]); ]);
// Helper to calculate category usage // Helper to calculate category usage
@@ -412,18 +419,19 @@ export class BillingLimitService {
const hasCustomLimits = const hasCustomLimits =
project.billingLimitWorkflows !== null || project.billingLimitWorkflows !== null ||
project.billingLimitCampaigns !== null || project.billingLimitCampaigns !== null ||
project.billingLimitTransactional !== null; project.billingLimitTransactional !== null ||
project.billingLimitInbound !== null;
// Free tier projects (no subscription and no custom limits): show total usage with shared limit // Free tier projects (no subscription and no custom limits): show total usage with shared limit
// Only show free tier limits if billing is enabled // Only show free tier limits if billing is enabled
if (STRIPE_ENABLED && !project.subscription && !hasCustomLimits) { if (STRIPE_ENABLED && !project.subscription && !hasCustomLimits) {
const totalUsage = workflowUsage + campaignUsage + transactionalUsage; const totalUsage = workflowUsage + campaignUsage + transactionalUsage + inboundUsage;
const limit = this.FREE_TIER_TOTAL_LIMIT; const limit = this.FREE_TIER_TOTAL_LIMIT;
const percentage = (totalUsage / limit) * 100; const percentage = (totalUsage / limit) * 100;
const isWarning = percentage >= this.WARNING_THRESHOLD * 100; const isWarning = percentage >= this.WARNING_THRESHOLD * 100;
const isBlocked = totalUsage >= limit; const isBlocked = totalUsage >= limit;
// For free tier, show the same limit and total usage for all three categories // For free tier, show the same limit and total usage for all four categories
// This makes it clear in the UI that it's a shared limit // This makes it clear in the UI that it's a shared limit
const sharedUsageInfo: CategoryUsage = { const sharedUsageInfo: CategoryUsage = {
limit, limit,
@@ -437,6 +445,7 @@ export class BillingLimitService {
workflows: sharedUsageInfo, workflows: sharedUsageInfo,
campaigns: sharedUsageInfo, campaigns: sharedUsageInfo,
transactional: sharedUsageInfo, transactional: sharedUsageInfo,
inbound: sharedUsageInfo,
currency, currency,
}; };
} }
@@ -446,6 +455,7 @@ export class BillingLimitService {
workflows: calculateCategoryUsage(workflowUsage, project.billingLimitWorkflows), workflows: calculateCategoryUsage(workflowUsage, project.billingLimitWorkflows),
campaigns: calculateCategoryUsage(campaignUsage, project.billingLimitCampaigns), campaigns: calculateCategoryUsage(campaignUsage, project.billingLimitCampaigns),
transactional: calculateCategoryUsage(transactionalUsage, project.billingLimitTransactional), transactional: calculateCategoryUsage(transactionalUsage, project.billingLimitTransactional),
inbound: calculateCategoryUsage(inboundUsage, project.billingLimitInbound),
currency, currency,
}; };
} catch (error) { } catch (error) {
@@ -470,6 +480,7 @@ export class BillingLimitService {
this.getCacheKey(projectId, EmailSourceType.WORKFLOW), this.getCacheKey(projectId, EmailSourceType.WORKFLOW),
this.getCacheKey(projectId, EmailSourceType.CAMPAIGN), this.getCacheKey(projectId, EmailSourceType.CAMPAIGN),
this.getCacheKey(projectId, EmailSourceType.TRANSACTIONAL), this.getCacheKey(projectId, EmailSourceType.TRANSACTIONAL),
this.getCacheKey(projectId, EmailSourceType.INBOUND),
]; ];
await Promise.all(keys.map(key => redis.del(key))); await Promise.all(keys.map(key => redis.del(key)));
@@ -493,11 +504,13 @@ export class BillingLimitService {
workflows: number | null; workflows: number | null;
campaigns: number | null; campaigns: number | null;
transactional: number | null; transactional: number | null;
inbound: number | null;
}, },
newLimits: { newLimits: {
workflows: number | null; workflows: number | null;
campaigns: number | null; campaigns: number | null;
transactional: number | null; transactional: number | null;
inbound: number | null;
}, },
): Promise<void> { ): Promise<void> {
try { try {
@@ -531,6 +544,14 @@ export class BillingLimitService {
); );
} }
// Check inbound limit
if (oldLimits.inbound !== newLimits.inbound) {
keysToDelete.push(
Keys.Billing.warningEmail(projectId, EmailSourceType.INBOUND, year, month),
Keys.Billing.limitEmail(projectId, EmailSourceType.INBOUND, year, month),
);
}
if (keysToDelete.length > 0) { if (keysToDelete.length > 0) {
await Promise.all(keysToDelete.map(key => redis.del(key))); await Promise.all(keysToDelete.map(key => redis.del(key)));
signale.debug( signale.debug(
@@ -580,8 +601,15 @@ export class BillingLimitService {
const month = String(now.getMonth() + 1).padStart(2, '0'); const month = String(now.getMonth() + 1).padStart(2, '0');
const cacheKey = Keys.Billing.warningEmail(projectId, sourceType, year, month); const cacheKey = Keys.Billing.warningEmail(projectId, sourceType, year, month);
const alreadySent = await redis.get(cacheKey); // Use SETNX (SET if Not eXists) to atomically check and set the flag
if (alreadySent === '1') { // This prevents race conditions where multiple concurrent requests could all pass the check
const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);
const ttl = Math.floor((endOfMonth.getTime() - now.getTime()) / 1000);
// SETNX returns 1 if key was set (didn't exist), 0 if key already existed
const wasSet = await redis.set(cacheKey, '1', 'EX', ttl, 'NX');
if (!wasSet) {
// Email was already sent this month
return; return;
} }
@@ -603,11 +631,6 @@ export class BillingLimitService {
}); });
await Promise.all(emails.map(email => sendPlatformEmail(email, 'Billing Limit Warning', template))); await Promise.all(emails.map(email => sendPlatformEmail(email, 'Billing Limit Warning', template)));
// Mark that we've sent the warning email (expires at end of month)
const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);
const ttl = Math.floor((endOfMonth.getTime() - now.getTime()) / 1000);
await redis.setex(cacheKey, ttl, '1');
} catch (error) { } catch (error) {
signale.error(`[BILLING_LIMIT] Failed to send warning email:`, error); signale.error(`[BILLING_LIMIT] Failed to send warning email:`, error);
} }
@@ -630,8 +653,15 @@ export class BillingLimitService {
const month = String(now.getMonth() + 1).padStart(2, '0'); const month = String(now.getMonth() + 1).padStart(2, '0');
const cacheKey = Keys.Billing.limitEmail(projectId, sourceType, year, month); const cacheKey = Keys.Billing.limitEmail(projectId, sourceType, year, month);
const alreadySent = await redis.get(cacheKey); // Use SETNX (SET if Not eXists) to atomically check and set the flag
if (alreadySent === '1') { // This prevents race conditions where multiple concurrent requests could all pass the check
const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);
const ttl = Math.floor((endOfMonth.getTime() - now.getTime()) / 1000);
// SETNX returns 1 if key was set (didn't exist), 0 if key already existed
const wasSet = await redis.set(cacheKey, '1', 'EX', ttl, 'NX');
if (!wasSet) {
// Email was already sent this month
return; return;
} }
@@ -652,11 +682,6 @@ export class BillingLimitService {
}); });
await Promise.all(emails.map(email => sendPlatformEmail(email, 'Billing Limit Exceeded', template))); await Promise.all(emails.map(email => sendPlatformEmail(email, 'Billing Limit Exceeded', template)));
// Mark that we've sent the limit email (expires at end of month)
const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);
const ttl = Math.floor((endOfMonth.getTime() - now.getTime()) / 1000);
await redis.setex(cacheKey, ttl, '1');
} catch (error) { } catch (error) {
signale.error(`[BILLING_LIMIT] Failed to send limit exceeded email:`, error); signale.error(`[BILLING_LIMIT] Failed to send limit exceeded email:`, error);
} }
+12
View File
@@ -760,6 +760,18 @@ export class CampaignService {
throw new HttpException(404, 'Segment not found'); throw new HttpException(404, 'Segment not found');
} }
if (segment.type === 'STATIC') {
return {
...baseWhere,
segmentMemberships: {
some: {
segmentId,
exitedAt: null,
},
},
};
}
const condition = fromPrismaJson<FilterCondition>(segment.condition); const condition = fromPrismaJson<FilterCondition>(segment.condition);
const segmentWhere = SegmentService.buildConditionClause(condition); const segmentWhere = SegmentService.buildConditionClause(condition);
+4 -7
View File
@@ -1,5 +1,4 @@
import {type Contact, Prisma} from '@plunk/db'; import {type Contact, Prisma} from '@plunk/db';
import {isValidLanguageCode} from '@plunk/shared';
import type {CursorPaginatedResponse, FilterCondition, FilterGroup} from '@plunk/types'; import type {CursorPaginatedResponse, FilterCondition, FilterGroup} from '@plunk/types';
import {toPrismaJson} from '@plunk/types'; import {toPrismaJson} from '@plunk/types';
@@ -199,6 +198,7 @@ export class ContactService {
email: string, email: string,
data?: Record<string, unknown>, data?: Record<string, unknown>,
subscribed?: boolean, subscribed?: boolean,
defaultSubscribed: boolean = true,
): Promise<Contact> { ): Promise<Contact> {
// Find existing contact // Find existing contact
const existing = await prisma.contact.findFirst({ const existing = await prisma.contact.findFirst({
@@ -235,12 +235,9 @@ export class ContactService {
} }
// Validate locale field (special user-settable field) // Validate locale field (special user-settable field)
// Only validate type - any locale string is accepted since we default to English if unsupported
if (key === 'locale') { if (key === 'locale') {
if (typeof value === 'string') { if (value !== null && value !== undefined && typeof value !== 'string') {
if (!isValidLanguageCode(value)) {
throw new HttpException(400, `Invalid locale code: ${value}. Must be one of: en, nl, fr, hi, de`);
}
} else if (value !== null && value !== undefined) {
throw new HttpException(400, 'Locale must be a string'); throw new HttpException(400, 'Locale must be a string');
} }
} }
@@ -292,7 +289,7 @@ export class ContactService {
projectId, projectId,
email, email,
data: Object.keys(mergedData).length > 0 ? toPrismaJson(mergedData) : Prisma.JsonNull, data: Object.keys(mergedData).length > 0 ? toPrismaJson(mergedData) : Prisma.JsonNull,
subscribed: subscribed ?? true, subscribed: subscribed ?? defaultSubscribed,
}, },
}); });
} }
+86 -13
View File
@@ -8,7 +8,12 @@ import {HttpException} from '../exceptions/index.js';
import {Keys} from './keys.js'; import {Keys} from './keys.js';
import {MembershipService} from './MembershipService.js'; import {MembershipService} from './MembershipService.js';
import {NtfyService} from './NtfyService.js'; import {NtfyService} from './NtfyService.js';
import {getDomainVerificationAttributes, verifyDomain} from './SESService.js'; import {
deleteIdentity,
disableFeedbackForwarding,
getDomainVerificationAttributes,
verifyDomain,
} from './SESService.js';
export class DomainService { export class DomainService {
/** /**
@@ -72,6 +77,43 @@ export class DomainService {
const attributes = await getDomainVerificationAttributes(domain.domain); const attributes = await getDomainVerificationAttributes(domain.domain);
// If domain failed verification, retry
if (attributes.status === 'Failed') {
signale.warn(`[DOMAIN-SERVICE] Restarting verification for ${domain.domain}`);
let attempt = 0;
const maxAttempts = 5;
let success = false;
let delay = 5000;
while (attempt < maxAttempts && !success) {
try {
await verifyDomain(domain.domain);
success = true;
signale.success(`[DOMAIN-SERVICE] Restarted verification for ${domain.domain}`);
} catch (e: unknown) {
const error = e as {Code?: string; name?: string; message?: string};
if (error?.Code === 'Throttling' || error?.name === 'Throttling' || error?.message?.includes('Throttling')) {
signale.warn(
`[DOMAIN-SERVICE] Throttling detected, waiting ${delay / 1000} seconds (attempt ${attempt + 1})`,
);
await new Promise(r => setTimeout(r, delay));
delay *= 2; // Exponential backoff
attempt++;
} else {
signale.error(`[DOMAIN-SERVICE] Error restarting verification: ${error?.message || 'Unknown error'}`);
throw e;
}
}
}
if (!success) {
signale.error(
`[DOMAIN-SERVICE] Failed to verify ${domain.domain} after ${maxAttempts} attempts due to throttling`,
);
}
}
// Update domain if verification status changed // Update domain if verification status changed
if (attributes.status === 'Success' && !domain.verified) { if (attributes.status === 'Success' && !domain.verified) {
const updatedDomain = await prisma.domain.update({ const updatedDomain = await prisma.domain.update({
@@ -84,15 +126,26 @@ export class DomainService {
}, },
}); });
// Disable feedback forwarding for verified domain
try {
await disableFeedbackForwarding(domain.domain);
signale.info(`[DOMAIN-SERVICE] Disabled feedback forwarding for ${domain.domain}`);
} catch (error) {
signale.error(`[DOMAIN-SERVICE] Error disabling feedback forwarding for ${domain.domain}:`, error);
}
// Send notification about domain verified // Send notification about domain verified
await NtfyService.notifyDomainVerified(domain.domain, updatedDomain.project.name, updatedDomain.project.id); await NtfyService.notifyDomainVerified(domain.domain, updatedDomain.project.name, updatedDomain.project.id);
// Send email notification about domain verified // Send email notification about domain verified
try { try {
// Check deduplication cache // Use SETNX to atomically check and set the flag (prevents race conditions)
const cacheKey = Keys.Domain.verifiedEmail(domainId); const cacheKey = Keys.Domain.verifiedEmail(domainId);
const alreadySent = await redis.get(cacheKey); const ttl = 604800; // 7 days
if (alreadySent !== '1') {
// SETNX returns 1 if key was set (didn't exist), 0 if key already existed
const wasSet = await redis.set(cacheKey, '1', 'EX', ttl, 'NX');
if (wasSet) {
const members = await MembershipService.getMembers(updatedDomain.project.id); const members = await MembershipService.getMembers(updatedDomain.project.id);
const emails = members.map(m => m.email); const emails = members.map(m => m.email);
if (emails.length > 0) { if (emails.length > 0) {
@@ -104,8 +157,6 @@ export class DomainService {
landingUrl: LANDING_URI, landingUrl: LANDING_URI,
}); });
await Promise.all(emails.map(email => sendPlatformEmail(email, 'Domain Verified Successfully', template))); await Promise.all(emails.map(email => sendPlatformEmail(email, 'Domain Verified Successfully', template)));
// Set cache to prevent duplicate emails (7 days)
await redis.setex(cacheKey, 604800, '1');
} }
} }
} catch (emailError) { } catch (emailError) {
@@ -131,13 +182,17 @@ export class DomainService {
// Send email notification about domain verification failed // Send email notification about domain verification failed
try { try {
// Check deduplication cache (monthly) // Use SETNX to atomically check and set the flag (prevents race conditions)
const now = new Date(); const now = new Date();
const year = now.getFullYear(); const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0'); const month = String(now.getMonth() + 1).padStart(2, '0');
const cacheKey = Keys.Domain.unverifiedEmail(domainId, year, month); const cacheKey = Keys.Domain.unverifiedEmail(domainId, year, month);
const alreadySent = await redis.get(cacheKey); const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);
if (alreadySent !== '1') { const ttl = Math.floor((endOfMonth.getTime() - now.getTime()) / 1000);
// SETNX returns 1 if key was set (didn't exist), 0 if key already existed
const wasSet = await redis.set(cacheKey, '1', 'EX', ttl, 'NX');
if (wasSet) {
const members = await MembershipService.getMembers(updatedDomain.project.id); const members = await MembershipService.getMembers(updatedDomain.project.id);
const emails = members.map(m => m.email); const emails = members.map(m => m.email);
if (emails.length > 0) { if (emails.length > 0) {
@@ -149,10 +204,6 @@ export class DomainService {
landingUrl: LANDING_URI, landingUrl: LANDING_URI,
}); });
await Promise.all(emails.map(email => sendPlatformEmail(email, 'Domain Verification Failed', template))); await Promise.all(emails.map(email => sendPlatformEmail(email, 'Domain Verification Failed', template)));
// Set cache to prevent duplicate emails (until end of month)
const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);
const ttl = Math.floor((endOfMonth.getTime() - now.getTime()) / 1000);
await redis.setex(cacheKey, ttl, '1');
} }
} }
} catch (emailError) { } catch (emailError) {
@@ -248,6 +299,28 @@ export class DomainService {
await prisma.domain.delete({where: {id: domainId}}); await prisma.domain.delete({where: {id: domainId}});
// Check if this domain is still attached to another project
const domainExistsElsewhere = await prisma.domain.findFirst({
where: {
domain: domainName,
},
});
// If domain is not used by any other project, remove it from AWS SES
if (!domainExistsElsewhere) {
try {
await deleteIdentity(domainName);
signale.info(`[DOMAIN] Removed AWS SES identity for ${domainName} (no longer used by any project)`);
} catch (error) {
// Log error but don't fail the domain removal if AWS cleanup fails
signale.error(`[DOMAIN] Failed to remove AWS SES identity for ${domainName}:`, error);
}
} else {
signale.info(
`[DOMAIN] Keeping AWS SES identity for ${domainName} (still used by project ${domainExistsElsewhere.projectId})`,
);
}
// Send notification about domain removal // Send notification about domain removal
await NtfyService.notifyDomainRemoved(domainName, domain.project.name, domain.project.id); await NtfyService.notifyDomainRemoved(domainName, domain.project.name, domain.project.id);
+33 -6
View File
@@ -18,6 +18,8 @@ interface Attachment {
filename: string; filename: string;
content: string; // Base64 encoded content: string; // Base64 encoded
contentType: string; contentType: string;
contentId?: string;
disposition?: 'attachment' | 'inline';
} }
interface SendEmailParams { interface SendEmailParams {
@@ -35,6 +37,7 @@ interface SendEmailParams {
campaignId?: string; campaignId?: string;
workflowExecutionId?: string; workflowExecutionId?: string;
workflowStepExecutionId?: string; workflowStepExecutionId?: string;
recipientEmail?: string; // Optional custom recipient email (overrides contact.email)
} }
/** /**
@@ -193,7 +196,8 @@ export class EmailService {
// Check subscription status for marketing emails // Check subscription status for marketing emails
// Transactional emails should always be sent regardless of subscription status // Transactional emails should always be sent regardless of subscription status
if (sourceType !== EmailSourceType.TRANSACTIONAL) { // Custom recipient emails also bypass subscription checks (they're not in the contact list)
if (sourceType !== EmailSourceType.TRANSACTIONAL && !params.recipientEmail) {
const contact = await prisma.contact.findUnique({ const contact = await prisma.contact.findUnique({
where: {id: params.contactId}, where: {id: params.contactId},
select: {subscribed: true}, select: {subscribed: true},
@@ -242,6 +246,12 @@ export class EmailService {
signale.warn(`[BILLING_LIMIT] ${limitCheck.message}`); signale.warn(`[BILLING_LIMIT] ${limitCheck.message}`);
} }
// If custom recipient email is provided, store it in headers for later use
const emailHeaders = params.headers ? {...params.headers} : {};
if (params.recipientEmail) {
emailHeaders['X-Plunk-Recipient-Override'] = params.recipientEmail;
}
const email = await prisma.email.create({ const email = await prisma.email.create({
data: { data: {
projectId: params.projectId, projectId: params.projectId,
@@ -251,7 +261,7 @@ export class EmailService {
from: params.from, from: params.from,
fromName: params.fromName, fromName: params.fromName,
replyTo: params.replyTo, replyTo: params.replyTo,
headers: params.headers ? toPrismaJson(params.headers) : undefined, headers: Object.keys(emailHeaders).length > 0 ? toPrismaJson(emailHeaders) : undefined,
attachments: params.attachments ? toPrismaJson(params.attachments) : undefined, attachments: params.attachments ? toPrismaJson(params.attachments) : undefined,
sourceType, sourceType,
templateId: params.templateId, templateId: params.templateId,
@@ -361,10 +371,25 @@ export class EmailService {
? (email.headers as Record<string, string>) ? (email.headers as Record<string, string>)
: undefined; : undefined;
// Check for custom recipient override in headers
const recipientEmail = customHeaders?.['X-Plunk-Recipient-Override'] || email.contact.email;
// Remove internal headers before sending
const publicHeaders = customHeaders ? {...customHeaders} : undefined;
if (publicHeaders && 'X-Plunk-Recipient-Override' in publicHeaders) {
delete publicHeaders['X-Plunk-Recipient-Override'];
}
// Parse attachments from JSON // Parse attachments from JSON
const attachments = const attachments =
email.attachments && Array.isArray(email.attachments) email.attachments && Array.isArray(email.attachments)
? (email.attachments as Array<{filename: string; content: string; contentType: string}>) ? (email.attachments as Array<{
filename: string;
content: string;
contentType: string;
contentId?: string;
disposition?: 'attachment' | 'inline';
}>)
: undefined; : undefined;
// Determine tracking based on project settings and email type // Determine tracking based on project settings and email type
@@ -376,13 +401,13 @@ export class EmailService {
name: fromName, name: fromName,
email: fromEmail, email: fromEmail,
}, },
to: [email.contact.email], to: [recipientEmail],
content: { content: {
subject: formattedEmail.subject, subject: formattedEmail.subject,
html: compiledHtml, html: compiledHtml,
}, },
reply: email.replyTo || undefined, reply: email.replyTo || undefined,
headers: customHeaders, headers: publicHeaders,
attachments: attachments, attachments: attachments,
tracking: shouldTrack, tracking: shouldTrack,
}); });
@@ -568,10 +593,11 @@ export class EmailService {
: {}), : {}),
}; };
const [total, sent, delivered, opened, clicked, bounced, failed] = await Promise.all([ const [total, sent, delivered, received, opened, clicked, bounced, failed] = await Promise.all([
prisma.email.count({where}), prisma.email.count({where}),
prisma.email.count({where: {...where, status: EmailStatus.SENT}}), prisma.email.count({where: {...where, status: EmailStatus.SENT}}),
prisma.email.count({where: {...where, status: EmailStatus.DELIVERED}}), prisma.email.count({where: {...where, status: EmailStatus.DELIVERED}}),
prisma.email.count({where: {...where, status: EmailStatus.RECEIVED}}),
prisma.email.count({where: {...where, status: EmailStatus.OPENED}}), prisma.email.count({where: {...where, status: EmailStatus.OPENED}}),
prisma.email.count({where: {...where, status: EmailStatus.CLICKED}}), prisma.email.count({where: {...where, status: EmailStatus.CLICKED}}),
prisma.email.count({where: {...where, status: EmailStatus.BOUNCED}}), prisma.email.count({where: {...where, status: EmailStatus.BOUNCED}}),
@@ -582,6 +608,7 @@ export class EmailService {
total, total,
sent, sent,
delivered, delivered,
received,
opened, opened,
clicked, clicked,
bounced, bounced,
@@ -6,6 +6,9 @@ import {redis} from '../database/redis.js';
const DISPOSABLE_DOMAINS_URL = const DISPOSABLE_DOMAINS_URL =
'https://raw.githubusercontent.com/disposable-email-domains/disposable-email-domains/main/disposable_email_blocklist.conf'; 'https://raw.githubusercontent.com/disposable-email-domains/disposable-email-domains/main/disposable_email_blocklist.conf';
const DISPOSABLE_DOMAINS_CACHE_KEY = 'email:disposable_domains'; const DISPOSABLE_DOMAINS_CACHE_KEY = 'email:disposable_domains';
const PERSONAL_DOMAINS_URL =
'https://gist.githubusercontent.com/ammarshah/f5c2624d767f91a7cbdc4e54db8dd0bf/raw/660fd949eba09c0b86574d9d3aa0f2137161fc7c/all_email_provider_domains.txt';
const PERSONAL_DOMAINS_CACHE_KEY = 'email:personal_domains';
const CACHE_TTL_SECONDS = 24 * 60 * 60; // 24 hours (list updates daily) const CACHE_TTL_SECONDS = 24 * 60 * 60; // 24 hours (list updates daily)
// Known email forwarding/alias services // Known email forwarding/alias services
@@ -39,12 +42,15 @@ const FORWARDING_DOMAINS = new Set([
export class EmailVerificationService { export class EmailVerificationService {
private static disposableDomainsSet: Set<string> | null = null; private static disposableDomainsSet: Set<string> | null = null;
private static personalDomainsSet: Set<string> | null = null;
/** /**
* Verify an email address * Verify an email address
* - Checks if domain exists (DNS A/AAAA records) * - Checks for NS records (proves domain exists in DNS)
* - Checks for MX records * - Checks for MX records (required for receiving email)
* - Checks for A/AAAA records (informational - indicates if domain has a website)
* - Detects disposable email addresses * - Detects disposable email addresses
* - Detects personal/free email providers (Gmail, Hotmail, etc.)
* - Detects forwarding/alias email addresses * - Detects forwarding/alias email addresses
* - Suggests corrections for common typos * - Suggests corrections for common typos
*/ */
@@ -56,7 +62,9 @@ export class EmailVerificationService {
isAlias: false, isAlias: false,
isTypo: false, isTypo: false,
isPlusAddressed: false, isPlusAddressed: false,
isPersonalEmail: false,
domainExists: false, domainExists: false,
hasWebsite: false,
hasMxRecords: false, hasMxRecords: false,
reasons: [], reasons: [],
}; };
@@ -74,6 +82,9 @@ export class EmailVerificationService {
// Check if email is from a disposable domain using GitHub list // Check if email is from a disposable domain using GitHub list
result.isDisposable = await this.isDisposableDomain(domain); result.isDisposable = await this.isDisposableDomain(domain);
// Check if email is from a personal/free email provider
result.isPersonalEmail = await this.isPersonalEmailDomain(domain);
// Check if email is from a known forwarding/alias service // Check if email is from a known forwarding/alias service
result.isAlias = this.isForwardingDomain(domain); result.isAlias = this.isForwardingDomain(domain);
@@ -88,35 +99,46 @@ export class EmailVerificationService {
result.isTypo = true; result.isTypo = true;
} }
// Check if domain exists (has any DNS records) // Step 1: Check NS records - proves the domain exists in DNS
try { try {
await dns.resolve(domain, 'A'); const nsRecords = await dns.resolveNs(domain);
result.domainExists = true; result.domainExists = nsRecords && nsRecords.length > 0;
} catch {
// Try AAAA records if A records fail
try {
await dns.resolve(domain, 'AAAA');
result.domainExists = true;
} catch { } catch {
result.domainExists = false; result.domainExists = false;
result.valid = false; result.valid = false;
result.reasons.push('Domain does not exist'); result.reasons.push('Domain does not exist (no nameservers found)');
} // If domain doesn't exist, no point checking MX/A records
return result;
} }
// Check MX records (only if domain exists) // Step 2: Check MX records - required for receiving email
if (result.domainExists) {
try { try {
const mxRecords = await dns.resolveMx(domain); const mxRecords = await dns.resolveMx(domain);
result.hasMxRecords = mxRecords && mxRecords.length > 0; result.hasMxRecords = mxRecords && mxRecords.length > 0;
if (!result.hasMxRecords) { if (!result.hasMxRecords) {
result.valid = false; result.valid = false;
result.reasons.push('No MX records found for domain'); result.reasons.push('Domain cannot receive email (no MX records found)');
} }
} catch { } catch {
result.hasMxRecords = false; result.hasMxRecords = false;
result.valid = false; result.valid = false;
result.reasons.push('No MX records found for domain'); result.reasons.push('Domain cannot receive email (no MX records found)');
}
// Step 3: Check if domain has A/AAAA records - informational only
// This indicates if the domain has a website/web server
// Doesn't affect email validity since email only requires MX records
try {
await dns.resolve(domain, 'A');
result.hasWebsite = true;
} catch {
// Try AAAA records if A records fail
try {
await dns.resolve(domain, 'AAAA');
result.hasWebsite = true;
} catch {
// Domain doesn't have A/AAAA records (no website), but this is OK for email
result.hasWebsite = false;
} }
} }
@@ -187,4 +209,57 @@ export class EmailVerificationService {
private static isForwardingDomain(domain: string): boolean { private static isForwardingDomain(domain: string): boolean {
return FORWARDING_DOMAINS.has(domain.toLowerCase()); return FORWARDING_DOMAINS.has(domain.toLowerCase());
} }
/**
* Fetch and cache the personal email domains list from GitHub
* Uses Redis for caching with 24-hour TTL
* Falls back to in-memory cache if Redis fails
*/
private static async getPersonalEmailDomains(): Promise<Set<string>> {
// Return in-memory cache if available
if (this.personalDomainsSet) {
return this.personalDomainsSet;
}
try {
// Try to get from Redis cache first
const cached = await redis.get(PERSONAL_DOMAINS_CACHE_KEY);
if (cached) {
const domains = JSON.parse(cached) as string[];
this.personalDomainsSet = new Set(domains);
return this.personalDomainsSet;
}
// Fetch from GitHub if not in cache
const response = await fetch(PERSONAL_DOMAINS_URL);
if (!response.ok) {
throw new Error(`Failed to fetch personal email domains: ${response.statusText}`);
}
const text = await response.text();
const domains = text
.split('\n')
.map(line => line.trim())
.filter(line => line && !line.startsWith('#')); // Filter empty lines and comments
// Cache in Redis
await redis.set(PERSONAL_DOMAINS_CACHE_KEY, JSON.stringify(domains), 'EX', CACHE_TTL_SECONDS);
// Cache in memory
this.personalDomainsSet = new Set(domains);
return this.personalDomainsSet;
} catch (error) {
console.error('Error fetching personal email domains:', error);
// Return empty set as fallback - don't block email verification
return new Set<string>();
}
}
/**
* Check if a domain is a personal/free email provider
*/
private static async isPersonalEmailDomain(domain: string): Promise<boolean> {
const personalDomains = await this.getPersonalEmailDomains();
return personalDomains.has(domain.toLowerCase());
}
} }
+66 -55
View File
@@ -211,9 +211,11 @@ export class NtfyService {
const {redis} = await import('../database/redis.js'); const {redis} = await import('../database/redis.js');
const cacheKey = `ntfy:security:warning:${projectId}`; const cacheKey = `ntfy:security:warning:${projectId}`;
const exists = await redis.exists(cacheKey); const ttl = 3600; // 1 hour
if (exists) { // Use SETNX to atomically check and set the flag (prevents race conditions)
const wasSet = await redis.set(cacheKey, '1', 'EX', ttl, 'NX');
if (!wasSet) {
return; return;
} }
@@ -223,14 +225,11 @@ export class NtfyService {
`Project "${projectName}" (${projectId}) has security warnings: ${warningText}`, `Project "${projectName}" (${projectId}) has security warnings: ${warningText}`,
[NtfyTag.WARNING, NtfyTag.SHIELD], [NtfyTag.WARNING, NtfyTag.SHIELD],
); );
// Throttle for 1 hour
await redis.setex(cacheKey, 3600, '1');
} }
/** /**
* Notify about email bounce - LOW priority (high volume) * Notify about email bounce - LOW priority (high volume)
* Rate-limited to only send notification every 20 bounces with per-project breakdown * Rate-limited to only send notification every 20 bounces with latest 20 bounce details
*/ */
public static async notifyEmailBounce( public static async notifyEmailBounce(
projectName: string, projectName: string,
@@ -241,63 +240,51 @@ export class NtfyService {
// Import redis at runtime to avoid circular dependencies // Import redis at runtime to avoid circular dependencies
const {redis} = await import('../database/redis.js'); const {redis} = await import('../database/redis.js');
// Use Redis counters to track bounce count globally and per-project // Use Redis counters to track bounce count globally
const globalCountKey = `ntfy:bounce:count`; const globalCountKey = `ntfy:bounce:count`;
const projectCountKey = `ntfy:bounce:count:${projectId}`; const bounceListKey = `ntfy:bounce:latest`;
const projectListKey = `ntfy:bounce:projects`;
// Increment global counter // Increment global counter
const globalCount = await redis.incr(globalCountKey); const globalCount = await redis.incr(globalCountKey);
// Increment project-specific counter // Store this bounce event in a list (keep latest 20)
await redis.incr(projectCountKey); const bounceEvent = JSON.stringify({
projectName,
// Add project to the set of projects with bounces (for tracking) projectId,
await redis.sadd(projectListKey, projectId); recipientEmail,
bounceType: bounceType || 'Unknown',
timestamp: new Date().toISOString(),
});
await redis.lpush(bounceListKey, bounceEvent);
await redis.ltrim(bounceListKey, 0, 19); // Keep only latest 20
// Set expiry on first increment (24 hour rolling window) // Set expiry on first increment (24 hour rolling window)
if (globalCount === 1) { if (globalCount === 1) {
await redis.expire(globalCountKey, 86400); await redis.expire(globalCountKey, 86400);
await redis.expire(projectListKey, 86400); await redis.expire(bounceListKey, 86400);
} }
// Always refresh project counter expiry to match global window
await redis.expire(projectCountKey, 86400);
// Only send notification every 20 bounces // Only send notification every 20 bounces
if (globalCount % 20 === 0) { if (globalCount % 20 === 0) {
// Get all projects with bounces // Get the latest 20 bounces
const projectIds = await redis.smembers(projectListKey); const latestBounces = await redis.lrange(bounceListKey, 0, 19);
// Get bounce counts for each project // Parse and format the bounce events
const projectCounts: Array<{projectId: string; count: number; name: string}> = []; const bounceDetails = latestBounces
for (const pid of projectIds) { .map(bounce => {
const count = await redis.get(`ntfy:bounce:count:${pid}`); try {
if (count) { const parsed = JSON.parse(bounce);
// Fetch project name from database return `${parsed.recipientEmail} (${parsed.bounceType}) - ${parsed.projectName}`;
const {prisma} = await import('../database/prisma.js'); } catch {
const project = await prisma.project.findUnique({ return null;
where: {id: pid},
select: {name: true},
});
projectCounts.push({
projectId: pid,
count: parseInt(count, 10),
name: project?.name || 'Unknown',
});
}
} }
})
.filter(Boolean)
.join('\n');
// Sort by count descending
projectCounts.sort((a, b) => b.count - a.count);
// Build breakdown message
const breakdown = projectCounts.map(p => `${p.name} (${p.projectId}): ${p.count}`).join('\n');
const bounceInfo = bounceType ? ` (${bounceType})` : '';
await this.send({ await this.send({
title: 'Email Bounces', title: 'Email Bounces',
message: `20 email bounces detected (total: ${globalCount})\n\nBreakdown by project:\n${breakdown}\n\nLatest: ${recipientEmail}${bounceInfo} in "${projectName}"`, message: `20 email bounces detected (total: ${globalCount})\n\nLatest 20 bounces:\n${bounceDetails}`,
priority: NtfyPriority.LOW, priority: NtfyPriority.LOW,
tags: [NtfyTag.WARNING], tags: [NtfyTag.WARNING],
}); });
@@ -606,9 +593,11 @@ export class NtfyService {
const {redis} = await import('../database/redis.js'); const {redis} = await import('../database/redis.js');
const cacheKey = `ntfy:billing:warning:${projectId}:${sourceType}`; const cacheKey = `ntfy:billing:warning:${projectId}:${sourceType}`;
const exists = await redis.exists(cacheKey); const ttl = 86400; // 24 hours
if (exists) { // Use SETNX to atomically check and set the flag (prevents race conditions)
const wasSet = await redis.set(cacheKey, '1', 'EX', ttl, 'NX');
if (!wasSet) {
return; return;
} }
@@ -617,9 +606,6 @@ export class NtfyService {
`Email usage at ${Math.round(percentage)}% (${usage}/${limit}) for ${sourceType} in project "${projectName}" (${projectId})`, `Email usage at ${Math.round(percentage)}% (${usage}/${limit}) for ${sourceType} in project "${projectName}" (${projectId})`,
[NtfyTag.WARNING, NtfyTag.MONEY, NtfyTag.CHART], [NtfyTag.WARNING, NtfyTag.MONEY, NtfyTag.CHART],
); );
// Throttle for 24 hours
await redis.setex(cacheKey, 86400, '1');
} }
// ===== Billing and usage limit notifications ===== // ===== Billing and usage limit notifications =====
@@ -638,9 +624,11 @@ export class NtfyService {
const {redis} = await import('../database/redis.js'); const {redis} = await import('../database/redis.js');
const cacheKey = `ntfy:billing:exceeded:${projectId}:${sourceType}`; const cacheKey = `ntfy:billing:exceeded:${projectId}:${sourceType}`;
const exists = await redis.exists(cacheKey); const ttl = 86400; // 24 hours
if (exists) { // Use SETNX to atomically check and set the flag (prevents race conditions)
const wasSet = await redis.set(cacheKey, '1', 'EX', ttl, 'NX');
if (!wasSet) {
return; return;
} }
@@ -649,9 +637,6 @@ export class NtfyService {
`Email usage limit reached (${usage}/${limit}) for ${sourceType} in project "${projectName}" (${projectId}). Further emails are blocked.`, `Email usage limit reached (${usage}/${limit}) for ${sourceType} in project "${projectName}" (${projectId}). Further emails are blocked.`,
[NtfyTag.ERROR, NtfyTag.MONEY, NtfyTag.SKULL], [NtfyTag.ERROR, NtfyTag.MONEY, NtfyTag.SKULL],
); );
// Throttle for 24 hours
await redis.setex(cacheKey, 86400, '1');
} }
/** /**
@@ -765,6 +750,32 @@ export class NtfyService {
}); });
} }
/**
* Notify about bundled segment membership updates - LOW priority
* Used when multiple segments are updated in a single processing cycle
*/
public static async notifySegmentMembershipBundled(
projectName: string,
projectId: string,
segmentCount: number,
totalAdded: number,
totalRemoved: number,
): Promise<void> {
const changes: string[] = [];
if (totalAdded > 0) changes.push(`+${totalAdded} added`);
if (totalRemoved > 0) changes.push(`-${totalRemoved} removed`);
const changesText = changes.length > 0 ? ` (${changes.join(', ')})` : '';
const message = `${segmentCount} segment${segmentCount > 1 ? 's' : ''} updated in project "${projectName}" (${projectId})${changesText}`;
await this.send({
title: 'Segment Memberships Updated',
message,
priority: NtfyPriority.LOW,
tags: [NtfyTag.CHART],
});
}
/** /**
* Notify about segment deleted - MIN priority * Notify about segment deleted - MIN priority
*/ */
+18 -2
View File
@@ -282,14 +282,22 @@ export class QueueService {
/** /**
* Get import job status and progress * Get import job status and progress
* @param jobId - The job ID
* @param projectId - The project ID to verify authorization
* @returns Job status or null if not found or unauthorized
*/ */
public static async getImportJobStatus(jobId: string) { public static async getImportJobStatus(jobId: string, projectId: string) {
const job = await importQueue.getJob(jobId); const job = await importQueue.getJob(jobId);
if (!job) { if (!job) {
return null; return null;
} }
// Security: Verify that the job belongs to the requesting project
if (job.data.projectId !== projectId) {
return null;
}
const state = await job.getState(); const state = await job.getState();
const progress = job.progress; const progress = job.progress;
const returnValue = job.returnvalue; const returnValue = job.returnvalue;
@@ -324,14 +332,22 @@ export class QueueService {
/** /**
* Get bulk action job status and progress * Get bulk action job status and progress
* @param jobId - The job ID
* @param projectId - The project ID to verify authorization
* @returns Job status or null if not found or unauthorized
*/ */
public static async getBulkActionJobStatus(jobId: string) { public static async getBulkActionJobStatus(jobId: string, projectId: string) {
const job = await bulkContactQueue.getJob(jobId); const job = await bulkContactQueue.getJob(jobId);
if (!job) { if (!job) {
return null; return null;
} }
// Security: Verify that the job belongs to the requesting project
if (job.data.projectId !== projectId) {
return null;
}
const state = await job.getState(); const state = await job.getState();
const progress = job.progress; const progress = job.progress;
const returnValue = job.returnvalue; const returnValue = job.returnvalue;
+74 -24
View File
@@ -8,7 +8,7 @@ import {
DASHBOARD_URI, DASHBOARD_URI,
SES_CONFIGURATION_SET, SES_CONFIGURATION_SET,
SES_CONFIGURATION_SET_NO_TRACKING, SES_CONFIGURATION_SET_NO_TRACKING,
TRACKING_TOGGLE_ENABLED TRACKING_TOGGLE_ENABLED,
} from '../app/constants.js'; } from '../app/constants.js';
/** /**
@@ -40,6 +40,8 @@ interface SendRawEmailParams {
filename: string; filename: string;
content: string; // Base64 encoded content: string; // Base64 encoded
contentType: string; contentType: string;
contentId?: string;
disposition?: 'attachment' | 'inline';
}[] }[]
| null; | null;
tracking?: boolean; tracking?: boolean;
@@ -101,8 +103,13 @@ export async function sendRawEmail({
} }
// Generate unique boundaries for multipart messages // Generate unique boundaries for multipart messages
const boundary = `----=_NextPart_${Math.random().toString(36).substring(2)}`; const altBoundary = `----=_AltPart_${Math.random().toString(36).substring(2)}`;
const mixedBoundary = attachments?.length ? `----=_MixedPart_${Math.random().toString(36).substring(2)}` : null; const mixedBoundary = attachments?.some(a => (a.disposition ?? 'attachment') === 'attachment')
? `----=_MixedPart_${Math.random().toString(36).substring(2)}`
: null;
const relatedBoundary = attachments?.some(a => a.disposition === 'inline')
? `----=_RelatedPart_${Math.random().toString(36).substring(2)}`
: null;
// Format To header with names if provided // Format To header with names if provided
const toHeader = to const toHeader = to
@@ -118,17 +125,21 @@ export async function sendRawEmail({
// Extract just email addresses for Destinations (SES requirement) // Extract just email addresses for Destinations (SES requirement)
const destinations = to.map(recipient => (typeof recipient === 'string' ? recipient : recipient.email)); const destinations = to.map(recipient => (typeof recipient === 'string' ? recipient : recipient.email));
// Determine root content type
let rootContentType = `multipart/alternative; boundary="${altBoundary}"`;
if (mixedBoundary) {
rootContentType = `multipart/mixed; boundary="${mixedBoundary}"`;
} else if (relatedBoundary) {
rootContentType = `multipart/related; boundary="${relatedBoundary}"`;
}
// Build raw MIME message // Build raw MIME message
const rawMessage = `From: ${from.name} <${from.email}> let rawMessage = `From: ${from.name} <${from.email}>
To: ${toHeader} To: ${toHeader}
Reply-To: ${reply || from.email} Reply-To: ${reply || from.email}
Subject: ${content.subject} Subject: ${content.subject}
MIME-Version: 1.0 MIME-Version: 1.0
${ Content-Type: ${rootContentType}
mixedBoundary
? `Content-Type: multipart/mixed; boundary="${mixedBoundary}"`
: `Content-Type: multipart/alternative; boundary="${boundary}"`
}
${ ${
headers headers
? Object.entries(headers) ? Object.entries(headers)
@@ -138,29 +149,61 @@ ${
} }
${unsubscribeHeader} ${unsubscribeHeader}
${mixedBoundary ? `--${mixedBoundary}\n` : ''}${ `;
mixedBoundary ? `Content-Type: multipart/alternative; boundary="${boundary}"\n\n` : ''
}--${boundary} // building the body
if (mixedBoundary) {
rawMessage += `--${mixedBoundary}\n`;
if (relatedBoundary) {
rawMessage += `Content-Type: multipart/related; boundary="${relatedBoundary}"\n\n`;
rawMessage += `--${relatedBoundary}\n`;
}
} else if (relatedBoundary) {
rawMessage += `--${relatedBoundary}\n`;
}
// If we are nested, we need to specify that this next part is the alternative container
if (mixedBoundary || relatedBoundary) {
rawMessage += `Content-Type: multipart/alternative; boundary="${altBoundary}"\n\n`;
}
// The alternative part content (always contains HTML)
rawMessage += `--${altBoundary}
Content-Type: text/html; charset=utf-8 Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: 7bit Content-Transfer-Encoding: 7bit
${breakLongLines(content.html, 500)} ${breakLongLines(content.html, 500)}
--${boundary}-- --${altBoundary}--
${ `;
attachments && attachments.length > 0
? '\n' + // Add inline attachments to the related container
attachments if (relatedBoundary) {
.map( const inlineAttachments = attachments?.filter(a => a.disposition === 'inline') ?? [];
attachment => `--${mixedBoundary} for (const attachment of inlineAttachments) {
rawMessage += `\n--${relatedBoundary}
Content-Type: ${attachment.contentType}
Content-Transfer-Encoding: base64
Content-ID: <${attachment.contentId || attachment.filename}>
Content-Disposition: inline; filename="${attachment.filename}"
${breakLongLines(attachment.content, 76, true)}`;
}
rawMessage += `\n--${relatedBoundary}--`;
}
// Add regular attachments to the mixed container
if (mixedBoundary) {
const regularAttachments = attachments?.filter(a => (a.disposition ?? 'attachment') === 'attachment') ?? [];
for (const attachment of regularAttachments) {
rawMessage += `\n--${mixedBoundary}
Content-Type: ${attachment.contentType} Content-Type: ${attachment.contentType}
Content-Transfer-Encoding: base64 Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="${attachment.filename}" Content-Disposition: attachment; filename="${attachment.filename}"
${breakLongLines(attachment.content, 76, true)}`, ${breakLongLines(attachment.content, 76, true)}`;
) }
.join('\n') rawMessage += `\n--${mixedBoundary}--`;
: '' }
}${mixedBoundary ? `\n--${mixedBoundary}--` : ''}`;
// Determine which configuration set to use // Determine which configuration set to use
// Only use NO_TRACKING if tracking toggle is enabled AND tracking is disabled // Only use NO_TRACKING if tracking toggle is enabled AND tracking is disabled
@@ -258,6 +301,13 @@ export const disableFeedbackForwarding = async (domain: string): Promise<void> =
}); });
}; };
/**
* Delete a verified domain identity from AWS SES
*/
export const deleteIdentity = async (domain: string): Promise<void> => {
await ses.deleteIdentity({Identity: domain});
};
/** /**
* Get AWS SES account sending quota and rate limit * Get AWS SES account sending quota and rate limit
* @returns MaxSendRate (emails per second) or null if the call fails * @returns MaxSendRate (emails per second) or null if the call fails
+55 -22
View File
@@ -25,10 +25,17 @@ const SECURITY_THRESHOLDS = {
BOUNCE_ALLTIME_CRITICAL: 8, BOUNCE_ALLTIME_CRITICAL: 8,
// Complaint rate thresholds (spam reports) // Complaint rate thresholds (spam reports)
COMPLAINT_7DAY_WARNING: 0.05, COMPLAINT_7DAY_WARNING: 0.075,
COMPLAINT_7DAY_CRITICAL: 0.1, COMPLAINT_7DAY_CRITICAL: 0.15,
COMPLAINT_ALLTIME_WARNING: 0.02, COMPLAINT_ALLTIME_WARNING: 0.03,
COMPLAINT_ALLTIME_CRITICAL: 0.08, COMPLAINT_ALLTIME_CRITICAL: 0.12,
// Minimum absolute counts (prevents small sample size false positives)
// Both percentage AND absolute count must be exceeded to trigger
MIN_BOUNCES_FOR_CRITICAL: 10,
MIN_BOUNCES_FOR_WARNING: 5,
MIN_COMPLAINTS_FOR_CRITICAL: 5,
MIN_COMPLAINTS_FOR_WARNING: 3,
} as const; } as const;
interface RateData { interface RateData {
@@ -280,51 +287,77 @@ export class SecurityService {
// Check 7-day bounce rate (only if 7-day volume is sufficient) // Check 7-day bounce rate (only if 7-day volume is sufficient)
if (hasMinimumVolume7Day) { if (hasMinimumVolume7Day) {
if (sevenDay.bounceRate >= SECURITY_THRESHOLDS.BOUNCE_7DAY_CRITICAL) { // Critical: requires BOTH rate AND absolute count thresholds
if (
sevenDay.bounceRate >= SECURITY_THRESHOLDS.BOUNCE_7DAY_CRITICAL &&
sevenDay.bounces >= SECURITY_THRESHOLDS.MIN_BOUNCES_FOR_CRITICAL
) {
violations.push( violations.push(
`7-day bounce rate (${sevenDay.bounceRate.toFixed(2)}%) exceeds critical threshold (${SECURITY_THRESHOLDS.BOUNCE_7DAY_CRITICAL}%)`, `7-day bounce rate (${sevenDay.bounceRate.toFixed(2)}%, ${sevenDay.bounces} bounces) exceeds critical threshold (${SECURITY_THRESHOLDS.BOUNCE_7DAY_CRITICAL}%, ${SECURITY_THRESHOLDS.MIN_BOUNCES_FOR_CRITICAL} minimum)`,
); );
} else if (sevenDay.bounceRate >= SECURITY_THRESHOLDS.BOUNCE_7DAY_WARNING) { } else if (
sevenDay.bounceRate >= SECURITY_THRESHOLDS.BOUNCE_7DAY_WARNING &&
sevenDay.bounces >= SECURITY_THRESHOLDS.MIN_BOUNCES_FOR_WARNING
) {
warnings.push( warnings.push(
`7-day bounce rate (${sevenDay.bounceRate.toFixed(2)}%) exceeds warning threshold (${SECURITY_THRESHOLDS.BOUNCE_7DAY_WARNING}%)`, `7-day bounce rate (${sevenDay.bounceRate.toFixed(2)}%, ${sevenDay.bounces} bounces) exceeds warning threshold (${SECURITY_THRESHOLDS.BOUNCE_7DAY_WARNING}%, ${SECURITY_THRESHOLDS.MIN_BOUNCES_FOR_WARNING} minimum)`,
); );
} }
} }
// Check 7-day complaint rate (only if 7-day volume is sufficient) // Check 7-day complaint rate (only if 7-day volume is sufficient)
if (hasMinimumVolume7Day) { if (hasMinimumVolume7Day) {
if (sevenDay.complaintRate >= SECURITY_THRESHOLDS.COMPLAINT_7DAY_CRITICAL) { // Critical: requires BOTH rate AND absolute count thresholds
if (
sevenDay.complaintRate >= SECURITY_THRESHOLDS.COMPLAINT_7DAY_CRITICAL &&
sevenDay.complaints >= SECURITY_THRESHOLDS.MIN_COMPLAINTS_FOR_CRITICAL
) {
violations.push( violations.push(
`7-day complaint rate (${sevenDay.complaintRate.toFixed(3)}%) exceeds critical threshold (${SECURITY_THRESHOLDS.COMPLAINT_7DAY_CRITICAL}%)`, `7-day complaint rate (${sevenDay.complaintRate.toFixed(3)}%, ${sevenDay.complaints} complaints) exceeds critical threshold (${SECURITY_THRESHOLDS.COMPLAINT_7DAY_CRITICAL}%, ${SECURITY_THRESHOLDS.MIN_COMPLAINTS_FOR_CRITICAL} minimum)`,
); );
} else if (sevenDay.complaintRate >= SECURITY_THRESHOLDS.COMPLAINT_7DAY_WARNING) { } else if (
sevenDay.complaintRate >= SECURITY_THRESHOLDS.COMPLAINT_7DAY_WARNING &&
sevenDay.complaints >= SECURITY_THRESHOLDS.MIN_COMPLAINTS_FOR_WARNING
) {
warnings.push( warnings.push(
`7-day complaint rate (${sevenDay.complaintRate.toFixed(3)}%) exceeds warning threshold (${SECURITY_THRESHOLDS.COMPLAINT_7DAY_WARNING}%)`, `7-day complaint rate (${sevenDay.complaintRate.toFixed(3)}%, ${sevenDay.complaints} complaints) exceeds warning threshold (${SECURITY_THRESHOLDS.COMPLAINT_7DAY_WARNING}%, ${SECURITY_THRESHOLDS.MIN_COMPLAINTS_FOR_WARNING} minimum)`,
); );
} }
} }
// Check all-time rates (only if all-time volume is sufficient) // Check all-time rates (only if all-time volume is sufficient)
if (hasMinimumVolumeAllTime) { if (hasMinimumVolumeAllTime) {
// Check all-time bounce rate // Check all-time bounce rate - requires BOTH rate AND absolute count
if (allTime.bounceRate >= SECURITY_THRESHOLDS.BOUNCE_ALLTIME_CRITICAL) { if (
allTime.bounceRate >= SECURITY_THRESHOLDS.BOUNCE_ALLTIME_CRITICAL &&
allTime.bounces >= SECURITY_THRESHOLDS.MIN_BOUNCES_FOR_CRITICAL
) {
violations.push( violations.push(
`All-time bounce rate (${allTime.bounceRate.toFixed(2)}%) exceeds critical threshold (${SECURITY_THRESHOLDS.BOUNCE_ALLTIME_CRITICAL}%)`, `All-time bounce rate (${allTime.bounceRate.toFixed(2)}%, ${allTime.bounces} bounces) exceeds critical threshold (${SECURITY_THRESHOLDS.BOUNCE_ALLTIME_CRITICAL}%, ${SECURITY_THRESHOLDS.MIN_BOUNCES_FOR_CRITICAL} minimum)`,
); );
} else if (allTime.bounceRate >= SECURITY_THRESHOLDS.BOUNCE_ALLTIME_WARNING) { } else if (
allTime.bounceRate >= SECURITY_THRESHOLDS.BOUNCE_ALLTIME_WARNING &&
allTime.bounces >= SECURITY_THRESHOLDS.MIN_BOUNCES_FOR_WARNING
) {
warnings.push( warnings.push(
`All-time bounce rate (${allTime.bounceRate.toFixed(2)}%) exceeds warning threshold (${SECURITY_THRESHOLDS.BOUNCE_ALLTIME_WARNING}%)`, `All-time bounce rate (${allTime.bounceRate.toFixed(2)}%, ${allTime.bounces} bounces) exceeds warning threshold (${SECURITY_THRESHOLDS.BOUNCE_ALLTIME_WARNING}%, ${SECURITY_THRESHOLDS.MIN_BOUNCES_FOR_WARNING} minimum)`,
); );
} }
// Check all-time complaint rate // Check all-time complaint rate - requires BOTH rate AND absolute count
if (allTime.complaintRate >= SECURITY_THRESHOLDS.COMPLAINT_ALLTIME_CRITICAL) { if (
allTime.complaintRate >= SECURITY_THRESHOLDS.COMPLAINT_ALLTIME_CRITICAL &&
allTime.complaints >= SECURITY_THRESHOLDS.MIN_COMPLAINTS_FOR_CRITICAL
) {
violations.push( violations.push(
`All-time complaint rate (${allTime.complaintRate.toFixed(3)}%) exceeds critical threshold (${SECURITY_THRESHOLDS.COMPLAINT_ALLTIME_CRITICAL}%)`, `All-time complaint rate (${allTime.complaintRate.toFixed(3)}%, ${allTime.complaints} complaints) exceeds critical threshold (${SECURITY_THRESHOLDS.COMPLAINT_ALLTIME_CRITICAL}%, ${SECURITY_THRESHOLDS.MIN_COMPLAINTS_FOR_CRITICAL} minimum)`,
); );
} else if (allTime.complaintRate >= SECURITY_THRESHOLDS.COMPLAINT_ALLTIME_WARNING) { } else if (
allTime.complaintRate >= SECURITY_THRESHOLDS.COMPLAINT_ALLTIME_WARNING &&
allTime.complaints >= SECURITY_THRESHOLDS.MIN_COMPLAINTS_FOR_WARNING
) {
warnings.push( warnings.push(
`All-time complaint rate (${allTime.complaintRate.toFixed(3)}%) exceeds warning threshold (${SECURITY_THRESHOLDS.COMPLAINT_ALLTIME_WARNING}%)`, `All-time complaint rate (${allTime.complaintRate.toFixed(3)}%, ${allTime.complaints} complaints) exceeds warning threshold (${SECURITY_THRESHOLDS.COMPLAINT_ALLTIME_WARNING}%, ${SECURITY_THRESHOLDS.MIN_COMPLAINTS_FOR_WARNING} minimum)`,
); );
} }
} }
+271 -19
View File
@@ -1,5 +1,5 @@
import {type Contact, Prisma, type Segment} from '@plunk/db'; import {type Contact, Prisma, type Segment} from '@plunk/db';
import type {FilterCondition, FilterGroup, PaginatedResponse, SegmentFilter} from '@plunk/types'; import type {FilterCondition, FilterGroup, PaginatedResponse, SegmentFilter, SegmentType} from '@plunk/types';
import {fromPrismaJson, toPrismaJson} from '@plunk/types'; import {fromPrismaJson, toPrismaJson} from '@plunk/types';
import signale from 'signale'; import signale from 'signale';
@@ -66,11 +66,33 @@ export class SegmentService {
pageSize = 20, pageSize = 20,
): Promise<PaginatedResponse<Contact>> { ): Promise<PaginatedResponse<Contact>> {
const segment = await this.get(projectId, segmentId); const segment = await this.get(projectId, segmentId);
const condition = fromPrismaJson<FilterCondition>(segment.condition);
const where = this.buildWhereClause(projectId, condition);
const skip = (page - 1) * pageSize; const skip = (page - 1) * pageSize;
if (segment.type === 'STATIC') {
// For static segments, query via SegmentMembership records
const [memberships, total] = await Promise.all([
prisma.segmentMembership.findMany({
where: {segmentId, exitedAt: null},
include: {contact: true},
skip,
take: pageSize,
orderBy: {enteredAt: 'desc'},
}),
prisma.segmentMembership.count({where: {segmentId, exitedAt: null}}),
]);
return {
data: memberships.map(m => m.contact),
total,
page,
pageSize,
totalPages: Math.ceil(total / pageSize),
};
}
const condition = fromPrismaJson<FilterCondition>(segment.condition);
const where = this.buildWhereClause(projectId, condition);
const [contacts, total] = await Promise.all([ const [contacts, total] = await Promise.all([
prisma.contact.findMany({ prisma.contact.findMany({
where, where,
@@ -98,23 +120,35 @@ export class SegmentService {
data: { data: {
name: string; name: string;
description?: string; description?: string;
condition: FilterCondition; type?: SegmentType;
condition?: FilterCondition;
trackMembership?: boolean; trackMembership?: boolean;
}, },
): Promise<Segment> { ): Promise<Segment> {
const segmentType = data.type ?? 'DYNAMIC';
let memberCount = 0;
let conditionJson: Prisma.InputJsonValue | typeof Prisma.JsonNull = Prisma.JsonNull;
if (segmentType === 'DYNAMIC') {
if (!data.condition) {
throw new HttpException(400, 'Condition is required for DYNAMIC segments');
}
// Validate condition // Validate condition
this.validateCondition(data.condition); this.validateCondition(data.condition);
// Compute initial member count // Compute initial member count
const where = this.buildWhereClause(projectId, data.condition); const where = this.buildWhereClause(projectId, data.condition);
const memberCount = await prisma.contact.count({where}); memberCount = await prisma.contact.count({where});
conditionJson = toPrismaJson(data.condition);
}
const segment = await prisma.segment.create({ const segment = await prisma.segment.create({
data: { data: {
projectId, projectId,
name: data.name, name: data.name,
description: data.description, description: data.description,
condition: toPrismaJson(data.condition), type: segmentType,
condition: conditionJson,
trackMembership: data.trackMembership ?? false, trackMembership: data.trackMembership ?? false,
memberCount, memberCount,
}, },
@@ -145,12 +179,7 @@ export class SegmentService {
}, },
): Promise<Segment> { ): Promise<Segment> {
// First verify segment exists and belongs to project // First verify segment exists and belongs to project
await this.get(projectId, segmentId); const existing = await this.get(projectId, segmentId);
// Validate condition if provided
if (data.condition) {
this.validateCondition(data.condition);
}
const updateData: Prisma.SegmentUpdateInput = {}; const updateData: Prisma.SegmentUpdateInput = {};
@@ -160,7 +189,9 @@ export class SegmentService {
if (data.description !== undefined) { if (data.description !== undefined) {
updateData.description = data.description; updateData.description = data.description;
} }
if (data.condition !== undefined) { if (data.condition !== undefined && existing.type !== 'STATIC') {
// Validate condition if provided (only for DYNAMIC segments)
this.validateCondition(data.condition);
updateData.condition = toPrismaJson(data.condition); updateData.condition = toPrismaJson(data.condition);
// Recompute member count when condition changes // Recompute member count when condition changes
@@ -229,10 +260,16 @@ export class SegmentService {
*/ */
public static async refreshMemberCount(projectId: string, segmentId: string): Promise<number> { public static async refreshMemberCount(projectId: string, segmentId: string): Promise<number> {
const segment = await this.get(projectId, segmentId); const segment = await this.get(projectId, segmentId);
let memberCount: number;
if (segment.type === 'STATIC') {
memberCount = await prisma.segmentMembership.count({where: {segmentId, exitedAt: null}});
} else {
const condition = fromPrismaJson<FilterCondition>(segment.condition); const condition = fromPrismaJson<FilterCondition>(segment.condition);
const where = this.buildWhereClause(projectId, condition); const where = this.buildWhereClause(projectId, condition);
memberCount = await prisma.contact.count({where});
const memberCount = await prisma.contact.count({where}); }
await prisma.segment.update({ await prisma.segment.update({
where: {id: segmentId}, where: {id: segmentId},
@@ -249,7 +286,7 @@ export class SegmentService {
public static async refreshAllMemberCounts(projectId: string): Promise<void> { public static async refreshAllMemberCounts(projectId: string): Promise<void> {
const segments = await prisma.segment.findMany({ const segments = await prisma.segment.findMany({
where: {projectId}, where: {projectId},
select: {id: true, condition: true}, select: {id: true, type: true, condition: true},
}); });
// Process in batches to avoid overwhelming the database // Process in batches to avoid overwhelming the database
@@ -260,9 +297,17 @@ export class SegmentService {
await Promise.all( await Promise.all(
batch.map(async segment => { batch.map(async segment => {
try { try {
let memberCount: number;
if (segment.type === 'STATIC') {
memberCount = await prisma.segmentMembership.count({
where: {segmentId: segment.id, exitedAt: null},
});
} else {
const condition = fromPrismaJson<FilterCondition>(segment.condition); const condition = fromPrismaJson<FilterCondition>(segment.condition);
const where = this.buildWhereClause(projectId, condition); const where = this.buildWhereClause(projectId, condition);
const memberCount = await prisma.contact.count({where}); memberCount = await prisma.contact.count({where});
}
await prisma.segment.update({ await prisma.segment.update({
where: {id: segment.id}, where: {id: segment.id},
@@ -276,6 +321,104 @@ export class SegmentService {
} }
} }
/**
* Add contacts to a static segment by email
*/
public static async addContacts(
projectId: string,
segmentId: string,
emails: string[],
): Promise<{added: number; notFound: string[]}> {
const segment = await this.get(projectId, segmentId);
if (segment.type !== 'STATIC') {
throw new HttpException(400, 'Can only add contacts to STATIC segments');
}
// Look up contacts by email (case-insensitive)
const contacts = await prisma.contact.findMany({
where: {
projectId,
email: {in: emails, mode: 'insensitive'},
},
select: {id: true, email: true},
});
const foundEmails = new Set(contacts.map(c => c.email.toLowerCase()));
const notFound = emails.filter(e => !foundEmails.has(e.toLowerCase()));
if (contacts.length > 0) {
// Check for existing memberships (to reactivate vs create new)
const existingMemberships = await prisma.segmentMembership.findMany({
where: {segmentId, contactId: {in: contacts.map(c => c.id)}},
select: {contactId: true},
});
const existingIds = new Set(existingMemberships.map(m => m.contactId));
const newContactIds = contacts.filter(c => !existingIds.has(c.id)).map(c => c.id);
const reEntryIds = contacts.filter(c => existingIds.has(c.id)).map(c => c.id);
if (newContactIds.length > 0) {
await prisma.segmentMembership.createMany({
data: newContactIds.map(contactId => ({segmentId, contactId, enteredAt: new Date()})),
skipDuplicates: true,
});
}
if (reEntryIds.length > 0) {
await prisma.segmentMembership.updateMany({
where: {segmentId, contactId: {in: reEntryIds}},
data: {exitedAt: null, enteredAt: new Date()},
});
}
// Update member count
const memberCount = await prisma.segmentMembership.count({where: {segmentId, exitedAt: null}});
await prisma.segment.update({where: {id: segmentId}, data: {memberCount}});
}
return {added: contacts.length, notFound};
}
/**
* Remove contacts from a static segment by email
*/
public static async removeContacts(
projectId: string,
segmentId: string,
emails: string[],
): Promise<{removed: number}> {
const segment = await this.get(projectId, segmentId);
if (segment.type !== 'STATIC') {
throw new HttpException(400, 'Can only remove contacts from STATIC segments');
}
// Look up contacts by email
const contacts = await prisma.contact.findMany({
where: {
projectId,
email: {in: emails, mode: 'insensitive'},
},
select: {id: true},
});
if (contacts.length > 0) {
const contactIds = contacts.map(c => c.id);
await prisma.segmentMembership.updateMany({
where: {segmentId, contactId: {in: contactIds}, exitedAt: null},
data: {exitedAt: new Date()},
});
// Update member count
const memberCount = await prisma.segmentMembership.count({where: {segmentId, exitedAt: null}});
await prisma.segment.update({where: {id: segmentId}, data: {memberCount}});
}
return {removed: contacts.length};
}
/** /**
* Compute or recompute segment membership for all contacts * Compute or recompute segment membership for all contacts
* Now uses cursor-based pagination for memory efficiency with large contact lists * Now uses cursor-based pagination for memory efficiency with large contact lists
@@ -290,6 +433,13 @@ export class SegmentService {
throw new HttpException(400, 'Segment does not have membership tracking enabled'); throw new HttpException(400, 'Segment does not have membership tracking enabled');
} }
if (segment.type === 'STATIC') {
// For static segments, just update the count from memberships — no contact scanning
const total = await prisma.segmentMembership.count({where: {segmentId, exitedAt: null}});
await prisma.segment.update({where: {id: segmentId}, data: {memberCount: total}});
return {added: 0, removed: 0, total};
}
const condition = fromPrismaJson<FilterCondition>(segment.condition); const condition = fromPrismaJson<FilterCondition>(segment.condition);
const where = this.buildWhereClause(projectId, condition); const where = this.buildWhereClause(projectId, condition);
@@ -584,8 +734,10 @@ export class SegmentService {
'exists', 'exists',
'notExists', 'notExists',
'within', 'within',
'olderThan',
'triggered', 'triggered',
'triggeredWithin', 'triggeredWithin',
'triggeredOlderThan',
'notTriggered', 'notTriggered',
]; ];
@@ -604,7 +756,9 @@ export class SegmentService {
'greaterThanOrEqual', 'greaterThanOrEqual',
'lessThanOrEqual', 'lessThanOrEqual',
'within', 'within',
'olderThan',
'triggeredWithin', 'triggeredWithin',
'triggeredOlderThan',
]; ];
if (operatorsNeedingValue.includes(filter.operator) && filter.value === undefined) { if (operatorsNeedingValue.includes(filter.operator) && filter.value === undefined) {
@@ -612,7 +766,7 @@ export class SegmentService {
} }
// Validate unit for time-based operators // Validate unit for time-based operators
if (['within', 'triggeredWithin'].includes(filter.operator) && !filter.unit) { if (['within', 'triggeredWithin', 'olderThan', 'triggeredOlderThan'].includes(filter.operator) && !filter.unit) {
throw new HttpException(400, `"${filter.operator}" operator requires a unit (days, hours, or minutes)`); throw new HttpException(400, `"${filter.operator}" operator requires a unit (days, hours, or minutes)`);
} }
} }
@@ -729,6 +883,20 @@ export class SegmentService {
// Use ISO string for lexicographic comparison in JSON // Use ISO string for lexicographic comparison in JSON
return {data: {path, gte: since.toISOString() as Prisma.InputJsonValue}}; return {data: {path, gte: since.toISOString() as Prisma.InputJsonValue}};
} }
case 'olderThan': {
// Note: Requires JSON date fields in ISO 8601 format for proper comparison
if (!unit) {
throw new HttpException(400, 'Unit is required for "olderThan" operator');
}
// Calculate the "before" date (X time units ago from now)
const now = new Date();
const milliseconds = this.getMilliseconds(value as number, unit);
const before = new Date(now.getTime() - milliseconds);
// Use ISO string for lexicographic comparison in JSON
return {data: {path, lt: before.toISOString() as Prisma.InputJsonValue}};
}
default: default:
throw new HttpException(400, `Unsupported operator for JSON field: ${operator}`); throw new HttpException(400, `Unsupported operator for JSON field: ${operator}`);
} }
@@ -822,6 +990,18 @@ export class SegmentService {
return {[field]: {gte: since}}; return {[field]: {gte: since}};
} }
case 'olderThan': {
// "olderThan X days/hours/minutes" means more than X time units ago
if (!unit) {
throw new HttpException(400, 'Unit is required for "olderThan" operator');
}
const now = new Date();
const milliseconds = this.getMilliseconds(value as number, unit);
const before = new Date(now.getTime() - milliseconds);
return {[field]: {lt: before}};
}
default: default:
throw new HttpException(400, `Unsupported operator for date field: ${operator}`); throw new HttpException(400, `Unsupported operator for date field: ${operator}`);
} }
@@ -921,6 +1101,42 @@ export class SegmentService {
}; };
} }
case 'triggeredOlderThan': {
// Contact triggered this event, but only more than X time ago (not recently)
// This means: has event AND all occurrences are before the cutoff
if (!unit) {
throw new HttpException(400, 'Unit is required for "triggeredOlderThan" operator');
}
const now = new Date();
const milliseconds = this.getMilliseconds(value as number, unit);
const before = new Date(now.getTime() - milliseconds);
return {
AND: [
// Must have triggered the event at some point
{
events: {
some: {
name: eventName,
},
},
},
// But NOT within the recent timeframe
{
events: {
none: {
name: eventName,
createdAt: {
gte: before,
},
},
},
},
],
};
}
case 'notTriggered': case 'notTriggered':
// Contact has never triggered this event // Contact has never triggered this event
return { return {
@@ -995,6 +1211,42 @@ export class SegmentService {
}; };
} }
case 'triggeredOlderThan': {
// Contact had this email activity, but only more than X time ago (not recently)
if (!unit) {
throw new HttpException(400, 'Unit is required for "triggeredOlderThan" operator');
}
const now = new Date();
const milliseconds = this.getMilliseconds(value as number, unit);
const before = new Date(now.getTime() - milliseconds);
return {
AND: [
// Must have the email activity at some point
{
emails: {
some: {
[field]: {
not: null,
},
},
},
},
// But NOT within the recent timeframe
{
emails: {
none: {
[field]: {
gte: before,
},
},
},
},
],
};
}
case 'notTriggered': case 'notTriggered':
// Contact has never had this email activity // Contact has never had this email activity
return { return {
+7 -2
View File
@@ -10,6 +10,7 @@ import {Keys} from './keys.js';
* Extract base domain from URL for cookie sharing across subdomains * Extract base domain from URL for cookie sharing across subdomains
* e.g., "http://api.example.com" -> ".example.com" * e.g., "http://api.example.com" -> ".example.com"
* e.g., "http://api.localhost" -> ".localhost" * e.g., "http://api.localhost" -> ".localhost"
* e.g., "http://app.plunk.local" -> ".plunk.local"
*/ */
function getCookieDomain(): string | undefined { function getCookieDomain(): string | undefined {
if (NODE_ENV === 'development') { if (NODE_ENV === 'development') {
@@ -28,10 +29,14 @@ function getCookieDomain(): string | undefined {
// Extract base domain (last two parts for most domains, or .localhost) // Extract base domain (last two parts for most domains, or .localhost)
const parts = hostname.split('.'); const parts = hostname.split('.');
if (parts.length >= 2) { if (parts.length >= 2) {
// For *.localhost or *.local, use the full hostname with leading dot // For *.localhost, use .localhost (reserved TLD)
if (hostname.endsWith('.localhost') || hostname.endsWith('.local')) { if (hostname.endsWith('.localhost')) {
return '.localhost'; return '.localhost';
} }
// For *.local (mDNS TLD), use the actual base domain
if (hostname.endsWith('.local')) {
return `.${parts.slice(-2).join('.')}`;
}
// For other domains, use the last two parts (e.g., .example.com) // For other domains, use the last two parts (e.g., .example.com)
return `.${parts.slice(-2).join('.')}`; return `.${parts.slice(-2).join('.')}`;
} }
@@ -519,18 +519,25 @@ export class WorkflowExecutionService {
} }
/** /**
* SEND_EMAIL step - Send an email to the contact * SEND_EMAIL step - Send an email to the contact or a custom recipient
*/ */
private static async executeSendEmail( private static async executeSendEmail(
step: WorkflowStepWithTemplate, step: WorkflowStepWithTemplate,
execution: WorkflowExecutionWithRelations, execution: WorkflowExecutionWithRelations,
stepExecution: WorkflowStepExecution, stepExecution: WorkflowStepExecution,
_config: StepConfig, config: StepConfig,
): Promise<StepResult> { ): Promise<StepResult> {
if (!step.template) { if (!step.template) {
throw new Error('No template configured for SEND_EMAIL step'); throw new Error('No template configured for SEND_EMAIL step');
} }
// Parse step config to get recipient configuration
const stepConfig = config && typeof config === 'object' && !Array.isArray(config) ? config : {};
const recipientConfig =
stepConfig.recipient && typeof stepConfig.recipient === 'object' && !Array.isArray(stepConfig.recipient)
? (stepConfig.recipient as {type?: string; customEmail?: string})
: {type: 'CONTACT'};
// Get contact data for variable substitution // Get contact data for variable substitution
const contact = execution.contact; const contact = execution.contact;
const contactData = const contactData =
@@ -558,10 +565,20 @@ export class WorkflowExecutionService {
const renderedSubject = this.renderTemplate(step.template.subject, variables); const renderedSubject = this.renderTemplate(step.template.subject, variables);
const renderedBody = this.renderTemplate(step.template.body, variables); const renderedBody = this.renderTemplate(step.template.body, variables);
// Determine recipient email
let recipientEmail = contact.email;
let recipientContactId = contact.id;
if (recipientConfig.type === 'CUSTOM' && recipientConfig.customEmail) {
recipientEmail = recipientConfig.customEmail;
// For custom recipients, we don't associate with a contact
recipientContactId = contact.id; // Keep original contact for tracking
}
// Send email via EmailService // Send email via EmailService
const email = await EmailService.sendWorkflowEmail({ const email = await EmailService.sendWorkflowEmail({
projectId: execution.workflow.projectId, projectId: execution.workflow.projectId,
contactId: contact.id, contactId: recipientContactId,
workflowExecutionId: execution.id, workflowExecutionId: execution.id,
workflowStepExecutionId: stepExecution.id, // Use stepExecution.id, not step.id workflowStepExecutionId: stepExecution.id, // Use stepExecution.id, not step.id
templateId: step.template.id, templateId: step.template.id,
@@ -570,11 +587,15 @@ export class WorkflowExecutionService {
from: step.template.from, from: step.template.from,
fromName: step.template.fromName || undefined, fromName: step.template.fromName || undefined,
replyTo: step.template.replyTo || undefined, replyTo: step.template.replyTo || undefined,
// Pass custom recipient email if specified
recipientEmail: recipientConfig.type === 'CUSTOM' ? recipientEmail : undefined,
}); });
return { return {
emailId: email.id, emailId: email.id,
sentAt: email.createdAt, sentAt: email.createdAt,
recipientType: recipientConfig.type,
recipientEmail,
}; };
} }
+38 -1
View File
@@ -194,6 +194,8 @@ export class WorkflowService {
} }
} }
// Use transaction to update workflow and TRIGGER step atomically
const updated = await prisma.$transaction(async tx => {
const updateData: Prisma.WorkflowUpdateInput = {}; const updateData: Prisma.WorkflowUpdateInput = {};
if (data.name !== undefined) updateData.name = data.name; if (data.name !== undefined) updateData.name = data.name;
@@ -205,7 +207,7 @@ export class WorkflowService {
if (data.enabled !== undefined) updateData.enabled = data.enabled; if (data.enabled !== undefined) updateData.enabled = data.enabled;
if (data.allowReentry !== undefined) updateData.allowReentry = data.allowReentry; if (data.allowReentry !== undefined) updateData.allowReentry = data.allowReentry;
const updated = await prisma.workflow.update({ const updatedWorkflow = await tx.workflow.update({
where: {id: workflowId}, where: {id: workflowId},
data: updateData, data: updateData,
include: { include: {
@@ -215,11 +217,46 @@ export class WorkflowService {
}, },
}); });
// If triggerConfig changed and it's an EVENT trigger, update the TRIGGER step
if (data.triggerConfig !== undefined && updatedWorkflow.triggerType === 'EVENT') {
const newTriggerConfig = data.triggerConfig as {eventName?: string} | null;
const eventName = newTriggerConfig?.eventName;
if (eventName) {
// Find the TRIGGER step
const triggerStep = await tx.workflowStep.findFirst({
where: {
workflowId: workflowId,
type: 'TRIGGER',
},
});
if (triggerStep) {
// Update TRIGGER step config and name to match
await tx.workflowStep.update({
where: {id: triggerStep.id},
data: {
name: `Trigger: ${eventName}`,
config: {eventName},
},
});
}
}
}
return updatedWorkflow;
});
// Invalidate workflow cache if enabled status changed or workflow is enabled // Invalidate workflow cache if enabled status changed or workflow is enabled
if (data.enabled !== undefined || updated.enabled) { if (data.enabled !== undefined || updated.enabled) {
await EventService.invalidateWorkflowCache(projectId); await EventService.invalidateWorkflowCache(projectId);
} }
// Also invalidate cache if triggerConfig changed on an enabled workflow
if (data.triggerConfig !== undefined && updated.enabled) {
await EventService.invalidateWorkflowCache(projectId);
}
// Send notification if enabled status changed // Send notification if enabled status changed
if (data.enabled !== undefined && data.enabled !== workflow.enabled) { if (data.enabled !== undefined && data.enabled !== workflow.enabled) {
if (data.enabled) { if (data.enabled) {
@@ -1,11 +1,32 @@
import {beforeEach, describe, expect, it, vi} from 'vitest'; import {beforeEach, describe, expect, it, vi, type Mock} from 'vitest';
import {EmailSourceType, EmailStatus} from '@plunk/db'; import {EmailSourceType, EmailStatus} from '@plunk/db';
import {ActionSchemas} from '@plunk/shared'; import {ActionSchemas} from '@plunk/shared';
import {EmailService} from '../EmailService'; import {EmailService} from '../EmailService';
import {sendRawEmail} from '../SESService'; import {sendRawEmail} from '../SESService';
import {factories, getPrismaClient} from '../../../../../test/helpers'; import {factories, getPrismaClient} from '../../../../../test/helpers';
// Mock SES service // Mock AWS SDK globally (used by real SESService calls in MIME tests)
vi.mock('@aws-sdk/client-ses', () => {
const SESMock = vi.fn();
SESMock.prototype.sendRawEmail = vi.fn().mockResolvedValue({MessageId: 'test-message-id'});
return {SES: SESMock};
});
// Mock constants to provide AWS credentials for SESService, preserving other exports
vi.mock('../../app/constants.js', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../app/constants.js')>();
return {
...actual,
AWS_SES_ACCESS_KEY_ID: 'test-key-id',
AWS_SES_REGION: 'us-east-1',
AWS_SES_SECRET_ACCESS_KEY: 'test-secret',
SES_CONFIGURATION_SET: 'test-config-set',
SES_CONFIGURATION_SET_NO_TRACKING: 'test-no-tracking-set',
TRACKING_TOGGLE_ENABLED: true,
};
});
// Mock SES service (default behavior for most tests)
vi.mock('../SESService', () => ({ vi.mock('../SESService', () => ({
sendRawEmail: vi.fn(), sendRawEmail: vi.fn(),
})); }));
@@ -801,5 +822,204 @@ describe('EmailService', () => {
expect(result.success).toBe(true); expect(result.success).toBe(true);
} }
}); });
it('should accept inline attachment with contentId', () => {
const result = ActionSchemas.send.safeParse({
to: '[email protected]',
from: '[email protected]',
subject: 'Inline Image',
body: '<img src="cid:logo" />',
attachments: [
{
filename: 'logo.png',
content: Buffer.from('image').toString('base64'),
contentType: 'image/png',
contentId: 'logo',
disposition: 'inline',
},
],
});
expect(result.success).toBe(true);
if (result.success) {
const attachment = result.data.attachments![0];
expect(attachment.contentId).toBe('logo');
expect(attachment.disposition).toBe('inline');
}
});
it('should reject contentId exceeding 255 chars', () => {
const result = ActionSchemas.send.safeParse({
to: '[email protected]',
subject: 'Test',
body: 'Test',
attachments: [
{
filename: 'image.png',
content: Buffer.from('content').toString('base64'),
contentType: 'image/png',
contentId: 'a'.repeat(256),
disposition: 'inline',
},
],
});
expect(result.success).toBe(false);
});
it('should reject invalid disposition', () => {
const result = ActionSchemas.send.safeParse({
to: '[email protected]',
subject: 'Test',
body: 'Test',
attachments: [
{
filename: 'image.png',
content: Buffer.from('content').toString('base64'),
contentType: 'image/png',
disposition: 'invalid-disposition',
},
],
});
expect(result.success).toBe(false);
});
});
});
// ========================================
// SES MIME BOUNDARY STRUCTURE
// ========================================
// These tests verify the raw MIME assembly logic inside sendRawEmail.
// They need the REAL sendRawEmail (not the mock above), so we mock
// at the AWS SDK level instead.
describe('SES MIME Boundary Structure', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('should correctly structure MIME boundaries for mixed content (attachments)', async () => {
const {sendRawEmail: realSendRawEmail, ses} = await vi.importActual<typeof import('../SESService')>('../SESService');
const params = {
from: {name: 'Sender', email: '[email protected]'},
to: ['[email protected]'],
content: {subject: 'Test Subject', html: '<p>Hello world</p>'},
attachments: [
{
filename: 'test.txt',
content: 'SGVsbG8=',
contentType: 'text/plain',
disposition: 'attachment' as const,
},
],
};
await realSendRawEmail(params);
expect(ses.sendRawEmail).toHaveBeenCalled();
const callArgs = (ses.sendRawEmail as Mock).mock.calls[0][0];
const rawMessage = new TextDecoder().decode(callArgs.RawMessage.Data);
// Verify boundary hierarchy: Mixed -> Alternative
expect(rawMessage).toMatch(/^From:.*Content-Type: multipart\/mixed; boundary="([^"]+)"/s);
expect(rawMessage).toMatch(/Content-Type: multipart\/alternative; boundary="([^"]+)"/);
const mixedBoundaryMatch = rawMessage.match(/boundary="([^"]+)"/);
const mixedBoundary = mixedBoundaryMatch ? mixedBoundaryMatch[1] : '';
expect(rawMessage).toContain(`--${mixedBoundary}\nContent-Type: multipart/alternative`);
expect(rawMessage).toContain(`--${mixedBoundary}--`);
});
it('should correctly structure MIME boundaries for related content (inline images)', async () => {
const {sendRawEmail: realSendRawEmail, ses} = await vi.importActual<typeof import('../SESService')>('../SESService');
const params = {
from: {name: 'Sender', email: '[email protected]'},
to: ['[email protected]'],
content: {subject: 'Test Subject', html: '<p>Hello world <img src="cid:image1"></p>'},
attachments: [
{
filename: 'image.png',
content:
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=',
contentType: 'image/png',
contentId: 'image1',
disposition: 'inline' as const,
},
],
};
await realSendRawEmail(params);
const callArgs = (ses.sendRawEmail as Mock).mock.calls[0][0];
const rawMessage = new TextDecoder().decode(callArgs.RawMessage.Data);
// Verify boundary hierarchy: Related -> Alternative
expect(rawMessage).toMatch(/^From:.*Content-Type: multipart\/related; boundary="([^"]+)"/s);
const relatedBoundaryMatch = rawMessage.match(/boundary="([^"]+)"/);
const relatedBoundary = relatedBoundaryMatch ? relatedBoundaryMatch[1] : '';
expect(rawMessage).toContain(`--${relatedBoundary}\nContent-Type: multipart/alternative`);
expect(rawMessage).toContain(`Content-Disposition: inline; filename="image.png"`);
expect(rawMessage).toContain(`--${relatedBoundary}--`);
});
it('should correctly nest mixed > related > alternative boundaries', async () => {
const {sendRawEmail: realSendRawEmail, ses} = await vi.importActual<typeof import('../SESService')>('../SESService');
const params = {
from: {name: 'Sender', email: '[email protected]'},
to: ['[email protected]'],
content: {subject: 'Test Subject', html: '<p>Hello world <img src="cid:image1"></p>'},
attachments: [
{
filename: 'test.txt',
content: 'SGVsbG8=',
contentType: 'text/plain',
disposition: 'attachment' as const,
},
{
filename: 'image.png',
content:
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=',
contentType: 'image/png',
contentId: 'image1',
disposition: 'inline' as const,
},
],
};
await realSendRawEmail(params);
const callArgs = (ses.sendRawEmail as Mock).mock.calls[0][0];
const rawMessage = new TextDecoder().decode(callArgs.RawMessage.Data);
// Root should be mixed
expect(rawMessage).toMatch(/^From:.*Content-Type: multipart\/mixed; boundary="([^"]+)"/s);
const mixedMatch = rawMessage.match(/Content-Type: multipart\/mixed; boundary="([^"]+)"/);
const mixedBoundary = mixedMatch ? mixedMatch[1] : 'NOT_FOUND_MIXED';
// Within mixed, we should find related
expect(rawMessage).toContain(`--${mixedBoundary}\nContent-Type: multipart/related`);
const relatedMatch = rawMessage.match(/Content-Type: multipart\/related; boundary="([^"]+)"/);
const relatedBoundary = relatedMatch ? relatedMatch[1] : 'NOT_FOUND_RELATED';
// Within related, we should find alternative
expect(rawMessage).toContain(`--${relatedBoundary}\nContent-Type: multipart/alternative`);
const altMatch = rawMessage.match(/Content-Type: multipart\/alternative; boundary="([^"]+)"/);
const altBoundary = altMatch ? altMatch[1] : 'NOT_FOUND_ALT';
// Verify all closing boundaries exist
expect(rawMessage).toContain(`--${altBoundary}--`);
expect(rawMessage).toContain(`--${relatedBoundary}--`);
expect(rawMessage).toContain(`--${mixedBoundary}--`);
}); });
}); });
+1 -1
View File
@@ -27,7 +27,7 @@
"@tiptap/starter-kit": "^3.11.0", "@tiptap/starter-kit": "^3.11.0",
"juice": "^11.0.3", "juice": "^11.0.3",
"lucide-react": "^0.553.0", "lucide-react": "^0.553.0",
"next": "^16.0.10", "next": "^16.1.5",
"next-seo": "^6.6.0", "next-seo": "^6.6.0",
"react": "19.2.3", "react": "19.2.3",
"react-dom": "19.2.3", "react-dom": "19.2.3",
@@ -128,6 +128,11 @@ export default function Footer() {
Terms Terms
</Link> </Link>
</li> </li>
<li>
<Link href={'/dpa'} className="text-sm text-neutral-600 transition hover:text-neutral-900">
DPA
</Link>
</li>
</ul> </ul>
</div> </div>
</div> </div>
@@ -2,15 +2,16 @@ import {
AlertCircle, AlertCircle,
AlertTriangle, AlertTriangle,
CheckCircle, CheckCircle,
Forward,
Info, Info,
Mail, Mail,
Server, Server,
Shield, Shield,
Trash2, Trash2,
User,
XCircle, XCircle,
Forward,
} from 'lucide-react'; } from 'lucide-react';
import type {EmailVerificationResult as VerificationResult} from '../../lib/emailVerification'; import type {EmailVerificationResult as VerificationResult} from '@plunk/types';
interface EmailVerificationResultProps { interface EmailVerificationResultProps {
result: VerificationResult; result: VerificationResult;
@@ -52,7 +53,7 @@ export function EmailVerificationResult({result}: EmailVerificationResultProps)
<Server className="h-5 w-5 text-neutral-600" /> <Server className="h-5 w-5 text-neutral-600" />
<div> <div>
<p className="font-medium text-neutral-900">Domain Exists</p> <p className="font-medium text-neutral-900">Domain Exists</p>
<p className="text-sm text-neutral-600">DNS A/AAAA records found</p> <p className="text-sm text-neutral-600">Domain has nameservers (NS records)</p>
</div> </div>
</div> </div>
{result.domainExists ? ( {result.domainExists ? (
@@ -78,6 +79,22 @@ export function EmailVerificationResult({result}: EmailVerificationResultProps)
)} )}
</div> </div>
{/* Website/A Records */}
<div className="flex items-center justify-between px-6 py-4">
<div className="flex items-center gap-3">
<Server className="h-5 w-5 text-neutral-600" />
<div>
<p className="font-medium text-neutral-900">Has Website</p>
<p className="text-sm text-neutral-600">DNS A/AAAA records found</p>
</div>
</div>
{result.hasWebsite ? (
<CheckCircle className="h-5 w-5 text-green-600" />
) : (
<Info className="h-5 w-5 text-neutral-400" />
)}
</div>
{/* Disposable Email */} {/* Disposable Email */}
<div className="flex items-center justify-between px-6 py-4"> <div className="flex items-center justify-between px-6 py-4">
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
@@ -94,6 +111,22 @@ export function EmailVerificationResult({result}: EmailVerificationResultProps)
)} )}
</div> </div>
{/* Personal Email */}
<div className="flex items-center justify-between px-6 py-4">
<div className="flex items-center gap-3">
<User className="h-5 w-5 text-neutral-600" />
<div>
<p className="font-medium text-neutral-900">Personal Email</p>
<p className="text-sm text-neutral-600">Free email provider (Gmail, Hotmail, etc.)</p>
</div>
</div>
{result.isPersonalEmail ? (
<Info className="h-5 w-5 text-blue-600" />
) : (
<span className="text-sm text-neutral-500">No</span>
)}
</div>
{/* Alias/Forwarding Email */} {/* Alias/Forwarding Email */}
<div className="flex items-center justify-between px-6 py-4"> <div className="flex items-center justify-between px-6 py-4">
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
+1 -12
View File
@@ -1,15 +1,4 @@
export interface EmailVerificationResult { import type {EmailVerificationResult} from '@plunk/types';
email: string;
valid: boolean;
isDisposable: boolean;
isAlias: boolean;
isTypo: boolean;
isPlusAddressed: boolean;
domainExists: boolean;
hasMxRecords: boolean;
suggestedEmail?: string;
reasons: string[];
}
export async function verifyEmail(email: string): Promise<EmailVerificationResult> { export async function verifyEmail(email: string): Promise<EmailVerificationResult> {
const response = await fetch('/api/verify-email', { const response = await fetch('/api/verify-email', {
+6 -1
View File
@@ -1,4 +1,4 @@
import {CheckCircle, Mail, Search, Shield} from 'lucide-react'; import {CheckCircle, Mail, Search, Shield, User} from 'lucide-react';
/** /**
* Educational content for the email verification tool * Educational content for the email verification tool
@@ -29,6 +29,11 @@ export const EMAIL_VERIFICATION_FEATURES = [
description: 'Identify temporary email addresses that are often used for spam or fake signups.', description: 'Identify temporary email addresses that are often used for spam or fake signups.',
icon: Mail, icon: Mail,
}, },
{
title: 'Personal Email Detection',
description: 'Detect personal/free email providers like Gmail, Hotmail, Yahoo for B2B validation.',
icon: User,
},
{ {
title: 'Plus Addressing', title: 'Plus Addressing',
description: 'Detect plus-addressed emails ([email protected]) which can be useful for tracking.', description: 'Detect plus-addressed emails ([email protected]) which can be useful for tracking.',
+5 -13
View File
@@ -1,24 +1,16 @@
import type {NextApiRequest, NextApiResponse} from 'next'; import type {NextApiRequest, NextApiResponse} from 'next';
import type {EmailVerificationResult} from '@plunk/types';
import {UtilitySchemas} from '@plunk/shared'; import {UtilitySchemas} from '@plunk/shared';
import {API_URI} from '../../lib/constants'; import {API_URI} from '../../lib/constants';
interface VerifyEmailResponse {
email: string;
valid: boolean;
isDisposable: boolean;
isTypo: boolean;
isPlusAddressed: boolean;
domainExists: boolean;
hasMxRecords: boolean;
suggestedEmail?: string;
reasons: string[];
}
interface ErrorResponse { interface ErrorResponse {
error: string; error: string;
} }
export default async function handler(req: NextApiRequest, res: NextApiResponse<VerifyEmailResponse | ErrorResponse>) { export default async function handler(
req: NextApiRequest,
res: NextApiResponse<EmailVerificationResult | ErrorResponse>,
) {
// Only allow POST requests // Only allow POST requests
if (req.method !== 'POST') { if (req.method !== 'POST') {
return res.status(405).json({error: 'Method not allowed'}); return res.status(405).json({error: 'Method not allowed'});
+695
View File
@@ -0,0 +1,695 @@
import {NextSeo} from 'next-seo';
import React from 'react';
import {Navbar} from '../components';
export default function DataProcessingAgreement() {
return (
<>
<NextSeo
title="Plunk Data Processing Agreement (DPA) | GDPR Compliance"
description="Data Processing Agreement for Plunk customers. GDPR-compliant DPA covering data processing activities, sub-processors, security measures, and data subject rights."
openGraph={{
title: 'Plunk Data Processing Agreement (DPA) | GDPR Compliance',
description:
'Data Processing Agreement for Plunk customers. GDPR-compliant DPA covering data processing activities, sub-processors, security measures, and data subject rights.',
}}
additionalMetaTags={[
{
property: 'title',
content: 'Plunk Data Processing Agreement (DPA) | GDPR Compliance',
},
]}
/>
<div className="min-h-screen bg-white">
<div className="px-8 pb-32 sm:px-12 md:px-16 lg:px-20 xl:px-24 2xl:px-56">
<Navbar />
<div className="mx-auto max-w-4xl py-16">
{/* Hero */}
<div className="mb-12">
<h1 className="text-4xl font-bold text-neutral-900">Data Processing Agreement</h1>
<p className="mt-2 text-sm text-neutral-600">Last Updated: February 18, 2026</p>
<p className="mt-4 text-base leading-relaxed text-neutral-700">
This Data Processing Agreement ("DPA") forms part of the Terms of Service between you ("Customer", "Data
Controller") and Plunk ("Processor", "we", "us") and governs the processing of Personal Data in
accordance with GDPR requirements.
</p>
<div className="mt-6 rounded-lg border border-blue-200 bg-blue-50 p-4">
<p className="text-sm leading-relaxed text-blue-900">
<strong className="font-semibold">GDPR Requirement:</strong> This DPA is required under Article 28 of
the GDPR. By using Plunk's hosted service, you accept and agree to the terms of this DPA.
</p>
</div>
</div>
{/* Table of Contents */}
<nav className="mb-12 rounded-lg border border-neutral-200 bg-neutral-50 p-6">
<h2 className="mb-4 text-lg font-semibold text-neutral-900">Contents</h2>
<ol className="space-y-2 text-sm text-neutral-700">
<li>
<a href="#definitions" className="text-blue-600 hover:underline">
1. Definitions
</a>
</li>
<li>
<a href="#scope" className="text-blue-600 hover:underline">
2. Scope & Applicability
</a>
</li>
<li>
<a href="#processing-details" className="text-blue-600 hover:underline">
3. Processing Details
</a>
</li>
<li>
<a href="#obligations" className="text-blue-600 hover:underline">
4. Data Processor Obligations
</a>
</li>
<li>
<a href="#security" className="text-blue-600 hover:underline">
5. Security Measures
</a>
</li>
<li>
<a href="#sub-processors" className="text-blue-600 hover:underline">
6. Sub-Processors
</a>
</li>
<li>
<a href="#data-subject-rights" className="text-blue-600 hover:underline">
7. Data Subject Rights
</a>
</li>
<li>
<a href="#data-breach" className="text-blue-600 hover:underline">
8. Data Breach Notification
</a>
</li>
<li>
<a href="#international-transfers" className="text-blue-600 hover:underline">
9. International Data Transfers
</a>
</li>
<li>
<a href="#audits" className="text-blue-600 hover:underline">
10. Audits & Compliance
</a>
</li>
<li>
<a href="#deletion" className="text-blue-600 hover:underline">
11. Data Deletion & Return
</a>
</li>
<li>
<a href="#liability" className="text-blue-600 hover:underline">
12. Liability & Indemnification
</a>
</li>
<li>
<a href="#term" className="text-blue-600 hover:underline">
13. Term & Termination
</a>
</li>
</ol>
</nav>
{/* Content Sections */}
<div className="space-y-12">
{/* Section 1 */}
<section id="definitions" className="mb-12">
<h2 className="mb-4 text-2xl font-bold text-neutral-900">1. Definitions</h2>
<p className="mb-4 leading-relaxed text-neutral-700">
Terms used in this DPA have the meanings set forth in the GDPR. Specifically:
</p>
<ul className="mb-4 ml-6 list-disc space-y-2 text-neutral-700">
<li>
<strong className="font-semibold text-neutral-900">"Personal Data"</strong> means any information
relating to an identified or identifiable natural person processed via Plunk
</li>
<li>
<strong className="font-semibold text-neutral-900">"Data Controller"</strong> means the Customer who
determines the purposes and means of processing Personal Data
</li>
<li>
<strong className="font-semibold text-neutral-900">"Data Processor"</strong> means Plunk, which
processes Personal Data on behalf of the Data Controller
</li>
<li>
<strong className="font-semibold text-neutral-900">"Sub-processor"</strong> means any third party
engaged by Plunk to process Personal Data
</li>
<li>
<strong className="font-semibold text-neutral-900">"Data Subject"</strong> means the individuals
whose Personal Data is processed (your contacts/subscribers)
</li>
<li>
<strong className="font-semibold text-neutral-900">"GDPR"</strong> means Regulation (EU) 2016/679
(General Data Protection Regulation)
</li>
</ul>
</section>
{/* Section 2 */}
<section id="scope" className="mb-12">
<h2 className="mb-4 text-2xl font-bold text-neutral-900">2. Scope & Applicability</h2>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Hosted Service Only</h3>
<p className="mb-4 leading-relaxed text-neutral-700">
This DPA applies ONLY to customers using Plunk's hosted service (useplunk.com). Self-hosted
deployments are NOT covered by this DPA - you are solely responsible for GDPR compliance when
self-hosting.
</p>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Agreement Hierarchy</h3>
<p className="mb-4 leading-relaxed text-neutral-700">
This DPA supplements the Plunk Terms of Service and Privacy Policy. In case of conflict regarding data
processing:
</p>
<ol className="mb-4 ml-6 list-decimal space-y-2 text-neutral-700">
<li>This DPA takes precedence</li>
<li>Then the Terms of Service</li>
<li>Then the Privacy Policy</li>
</ol>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Acceptance</h3>
<p className="mb-4 leading-relaxed text-neutral-700">
By using Plunk's hosted service, you acknowledge that you have read, understood, and agree to be bound
by this DPA. This constitutes a legally binding agreement between Customer and Plunk.
</p>
</section>
{/* Section 3 */}
<section id="processing-details" className="mb-12">
<h2 className="mb-4 text-2xl font-bold text-neutral-900">3. Processing Details</h2>
<p className="mb-4 leading-relaxed text-neutral-700">
As required by GDPR Article 28(3), the following details describe the processing activities:
</p>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Subject Matter</h3>
<p className="mb-4 leading-relaxed text-neutral-700">
Processing of Personal Data necessary to provide email automation, transactional email, marketing
campaigns, and workflow automation services.
</p>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Duration</h3>
<p className="mb-4 leading-relaxed text-neutral-700">
Processing occurs for the duration of your Plunk subscription/account, plus 30 days for API logs
(which are automatically deleted), and until you request account deletion.
</p>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Nature & Purpose</h3>
<ul className="mb-4 ml-6 list-disc space-y-2 text-neutral-700">
<li>Storing and managing contact databases</li>
<li>Sending transactional, marketing, and workflow-triggered emails</li>
<li>Tracking email delivery, opens, clicks, bounces, and complaints (per your settings)</li>
<li>Managing email templates and automation workflows</li>
<li>Processing email events and webhooks</li>
<li>Providing analytics and reporting</li>
</ul>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Type of Personal Data</h3>
<ul className="mb-4 ml-6 list-disc space-y-2 text-neutral-700">
<li>Email addresses (required)</li>
<li>Names and custom contact fields (optional, Customer-defined)</li>
<li>Email content (subject lines, message bodies, attachments)</li>
<li>Subscription status and preferences</li>
<li>Email activity data (opens, clicks, bounces, complaints)</li>
<li>Timestamps and metadata</li>
</ul>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Categories of Data Subjects</h3>
<ul className="mb-4 ml-6 list-disc space-y-2 text-neutral-700">
<li>Customer's email subscribers and contacts</li>
<li>Recipients of transactional emails</li>
<li>Marketing campaign recipients</li>
<li>Workflow automation recipients</li>
</ul>
</section>
{/* Section 4 */}
<section id="obligations" className="mb-12">
<h2 className="mb-4 text-2xl font-bold text-neutral-900">4. Data Processor Obligations</h2>
<p className="mb-4 leading-relaxed text-neutral-700">
Plunk commits to the following obligations as Data Processor:
</p>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Processing Instructions</h3>
<ul className="mb-4 ml-6 list-disc space-y-2 text-neutral-700">
<li>
Process Personal Data only on documented instructions from Customer (via API, dashboard, etc.)
</li>
<li>Not process Personal Data for any other purpose without Customer's prior written consent</li>
<li>Immediately inform Customer if instructions violate GDPR or other EU data protection laws</li>
</ul>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Confidentiality</h3>
<ul className="mb-4 ml-6 list-disc space-y-2 text-neutral-700">
<li>Ensure persons authorized to process Personal Data are bound by confidentiality obligations</li>
<li>Maintain confidentiality of all Personal Data processed via Plunk</li>
<li>
Not disclose Personal Data to third parties except as required by law or with Customer consent
</li>
</ul>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Cooperation</h3>
<ul className="mb-4 ml-6 list-disc space-y-2 text-neutral-700">
<li>Assist Customer in responding to Data Subject rights requests (see Section 7)</li>
<li>
Assist Customer in ensuring compliance with GDPR security, breach notification, and impact
assessment obligations
</li>
<li>Provide information necessary to demonstrate compliance with Article 28</li>
</ul>
</section>
{/* Section 5 */}
<section id="security" className="mb-12">
<h2 className="mb-4 text-2xl font-bold text-neutral-900">5. Security Measures</h2>
<p className="mb-4 leading-relaxed text-neutral-700">
As required by GDPR Article 32, Plunk implements appropriate technical and organizational measures to
ensure a level of security appropriate to the risk:
</p>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Technical Safeguards</h3>
<ul className="mb-4 ml-6 list-disc space-y-2 text-neutral-700">
<li>Industry-standard password hashing (never stored in plaintext)</li>
<li>HTTPS-only API access (TLS 1.2+)</li>
<li>Database connections encrypted via TLS/SSL</li>
<li>HttpOnly, secure cookies with appropriate SameSite settings</li>
<li>Authentication tokens with limited expiration periods</li>
<li>Rate limiting to prevent brute force attacks</li>
</ul>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Organizational Safeguards</h3>
<ul className="mb-4 ml-6 list-disc space-y-2 text-neutral-700">
<li>Access controls limiting personnel access to Personal Data</li>
<li>Automated bounce and complaint rate monitoring</li>
<li>Regular security updates and patching</li>
<li>Data segregation by project (multi-tenancy with isolation)</li>
</ul>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Data Residency</h3>
<ul className="mb-4 ml-6 list-disc space-y-2 text-neutral-700">
<li>Primary data storage: EU/EEA (Hetzner infrastructure)</li>
<li>Database and file storage remain within EU/EEA</li>
<li>Email delivery may transit non-EU regions (see Section 9)</li>
</ul>
</section>
{/* Section 6 */}
<section id="sub-processors" className="mb-12">
<h2 className="mb-4 text-2xl font-bold text-neutral-900">6. Sub-Processors</h2>
<p className="mb-4 leading-relaxed text-neutral-700">
Customer authorizes Plunk to engage the following sub-processors to process Personal Data:
</p>
<div className="mb-6 overflow-x-auto">
<table className="min-w-full border border-neutral-300">
<thead className="bg-neutral-50">
<tr>
<th className="border border-neutral-300 px-4 py-2 text-left text-sm font-semibold text-neutral-900">
Sub-Processor
</th>
<th className="border border-neutral-300 px-4 py-2 text-left text-sm font-semibold text-neutral-900">
Service
</th>
<th className="border border-neutral-300 px-4 py-2 text-left text-sm font-semibold text-neutral-900">
Location
</th>
<th className="border border-neutral-300 px-4 py-2 text-left text-sm font-semibold text-neutral-900">
Purpose
</th>
</tr>
</thead>
<tbody className="bg-white">
<tr>
<td className="border border-neutral-300 px-4 py-2 text-sm text-neutral-700">
Amazon Web Services (AWS SES)
</td>
<td className="border border-neutral-300 px-4 py-2 text-sm text-neutral-700">Email Delivery</td>
<td className="border border-neutral-300 px-4 py-2 text-sm text-neutral-700">
Global (data in transit only)
</td>
<td className="border border-neutral-300 px-4 py-2 text-sm text-neutral-700">
Sending emails to recipients
</td>
</tr>
<tr>
<td className="border border-neutral-300 px-4 py-2 text-sm text-neutral-700">Stripe, Inc.</td>
<td className="border border-neutral-300 px-4 py-2 text-sm text-neutral-700">
Payment Processing
</td>
<td className="border border-neutral-300 px-4 py-2 text-sm text-neutral-700">
USA (PCI-DSS compliant)
</td>
<td className="border border-neutral-300 px-4 py-2 text-sm text-neutral-700">
Billing for paid accounts
</td>
</tr>
<tr>
<td className="border border-neutral-300 px-4 py-2 text-sm text-neutral-700">
Hetzner Online GmbH
</td>
<td className="border border-neutral-300 px-4 py-2 text-sm text-neutral-700">
Infrastructure Hosting
</td>
<td className="border border-neutral-300 px-4 py-2 text-sm text-neutral-700">
EU/EEA (Germany)
</td>
<td className="border border-neutral-300 px-4 py-2 text-sm text-neutral-700">
Database and application hosting
</td>
</tr>
</tbody>
</table>
</div>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Sub-Processor Obligations</h3>
<ul className="mb-4 ml-6 list-disc space-y-2 text-neutral-700">
<li>All sub-processors are bound by data protection obligations equivalent to this DPA</li>
<li>Plunk remains fully liable to Customer for sub-processor performance</li>
<li>Sub-processors have executed Data Processing Agreements with Plunk</li>
</ul>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Changes to Sub-Processors</h3>
<ul className="mb-4 ml-6 list-disc space-y-2 text-neutral-700">
<li>Plunk will provide 30 days advance notice of new or replacement sub-processors via email</li>
<li>Notice will be sent to the email address associated with your account</li>
<li>
If you object on reasonable grounds related to data protection, you may terminate your account
within 30 days
</li>
<li>Updated sub-processor list will be maintained on this page (check "Last Updated" date)</li>
</ul>
</section>
{/* Section 7 */}
<section id="data-subject-rights" className="mb-12">
<h2 className="mb-4 text-2xl font-bold text-neutral-900">7. Data Subject Rights</h2>
<p className="mb-4 leading-relaxed text-neutral-700">
Plunk will assist Customer in fulfilling Data Subject rights requests under GDPR Articles 15-22:
</p>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Self-Service via API</h3>
<p className="mb-4 leading-relaxed text-neutral-700">
Customer can fulfill most Data Subject requests independently via API:
</p>
<ul className="mb-4 ml-6 list-disc space-y-2 text-neutral-700">
<li>
<strong className="font-semibold text-neutral-900">Access (Art. 15):</strong> Retrieve contact data
via GET /contacts/:id
</li>
<li>
<strong className="font-semibold text-neutral-900">Rectification (Art. 16):</strong> Update contact
data via PATCH /contacts/:id
</li>
<li>
<strong className="font-semibold text-neutral-900">Erasure (Art. 17):</strong> Delete contact via
DELETE /contacts/:id
</li>
<li>
<strong className="font-semibold text-neutral-900">Restriction (Art. 18):</strong> Update
subscription status to "unsubscribed"
</li>
<li>
<strong className="font-semibold text-neutral-900">Portability (Art. 20):</strong> Use API to access
data in JSON format
</li>
</ul>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Assistance from Plunk</h3>
<p className="mb-4 leading-relaxed text-neutral-700">
If Customer cannot fulfill a request via API, contact legal@useplunk.com:
</p>
<ul className="mb-4 ml-6 list-disc space-y-2 text-neutral-700">
<li>Provide Data Subject's email address and nature of request</li>
<li>Plunk will respond within 10 business days with requested information or assistance</li>
<li>
Customer remains responsible for verifying Data Subject identity before disclosing information
</li>
</ul>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Email Activity Data</h3>
<ul className="mb-4 ml-6 list-disc space-y-2 text-neutral-700">
<li>Email opens, clicks, bounces, and complaints are linked to contact records</li>
<li>Deleting a contact will cascade delete associated email activity</li>
<li>API logs (non-Personal Data) are automatically deleted after 30 days</li>
</ul>
</section>
{/* Section 8 */}
<section id="data-breach" className="mb-12">
<h2 className="mb-4 text-2xl font-bold text-neutral-900">8. Data Breach Notification</h2>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Notification Obligation</h3>
<p className="mb-4 leading-relaxed text-neutral-700">
In the event of a Personal Data breach affecting Customer data, Plunk will:
</p>
<ul className="mb-4 ml-6 list-disc space-y-2 text-neutral-700">
<li>
Notify Customer without undue delay and within 72 hours of becoming aware of the breach (per GDPR
Art. 33)
</li>
<li>Send notification to the primary email address associated with Customer's account</li>
<li>Provide information to enable Customer to meet any GDPR breach reporting obligations</li>
</ul>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Breach Information</h3>
<p className="mb-4 leading-relaxed text-neutral-700">
Notifications will include (to the extent known):
</p>
<ul className="mb-4 ml-6 list-disc space-y-2 text-neutral-700">
<li>Nature of the breach (what happened)</li>
<li>Categories and approximate number of Data Subjects affected</li>
<li>Categories and approximate number of Personal Data records affected</li>
<li>Likely consequences of the breach</li>
<li>Measures taken or proposed to address the breach and mitigate harm</li>
<li>Contact point for more information (legal@useplunk.com)</li>
</ul>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Customer Responsibility</h3>
<ul className="mb-4 ml-6 list-disc space-y-2 text-neutral-700">
<li>Customer is responsible for notifying their supervisory authority if required by GDPR Art. 33</li>
<li>Customer is responsible for notifying affected Data Subjects if required by GDPR Art. 34</li>
<li>Plunk's breach notification to Customer does NOT constitute legal or compliance advice</li>
</ul>
</section>
{/* Section 9 */}
<section id="international-transfers" className="mb-12">
<h2 className="mb-4 text-2xl font-bold text-neutral-900">9. International Data Transfers</h2>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Primary Storage (EU/EEA)</h3>
<ul className="mb-4 ml-6 list-disc space-y-2 text-neutral-700">
<li>All contact data, templates, workflows, and account data stored in EU/EEA (Hetzner, Germany)</li>
<li>No routine transfers of stored Personal Data outside EU/EEA</li>
</ul>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Data in Transit (Email Delivery)</h3>
<p className="mb-4 leading-relaxed text-neutral-700">
When emails are sent to recipients, Personal Data may transit through non-EU regions:
</p>
<ul className="mb-4 ml-6 list-disc space-y-2 text-neutral-700">
<li>AWS SES processes emails globally for delivery purposes</li>
<li>Data is in transit only (not stored long-term outside EU/EEA)</li>
<li>Protected by AWS Data Processing Agreement and Standard Contractual Clauses (SCCs)</li>
</ul>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Payment Data (Stripe)</h3>
<ul className="mb-4 ml-6 list-disc space-y-2 text-neutral-700">
<li>Payment information (credit cards) processed by Stripe (USA-based)</li>
<li>Stripe is PCI-DSS Level 1 certified</li>
<li>Protected by Stripe's Data Processing Agreement and Standard Contractual Clauses</li>
<li>Plunk does NOT store credit card numbers (tokenized by Stripe)</li>
</ul>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Standard Contractual Clauses</h3>
<p className="mb-4 leading-relaxed text-neutral-700">
All sub-processors that process Personal Data outside EU/EEA have executed Standard Contractual
Clauses (SCCs) approved by the European Commission, providing appropriate safeguards for international
transfers per GDPR Article 46.
</p>
</section>
{/* Section 10 */}
<section id="audits" className="mb-12">
<h2 className="mb-4 text-2xl font-bold text-neutral-900">10. Audits & Compliance</h2>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Information Provision</h3>
<p className="mb-4 leading-relaxed text-neutral-700">
Plunk will make available to Customer information necessary to demonstrate compliance with GDPR
Article 28 obligations, including:
</p>
<ul className="mb-4 ml-6 list-disc space-y-2 text-neutral-700">
<li>This DPA (publicly available)</li>
<li>Privacy Policy describing processing activities</li>
<li>Sub-processor list (Section 6 above)</li>
<li>Security measures documentation (available upon reasonable request)</li>
</ul>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Audit Rights</h3>
<p className="mb-4 leading-relaxed text-neutral-700">
Customer may audit Plunk's compliance with this DPA, subject to the following:
</p>
<ul className="mb-4 ml-6 list-disc space-y-2 text-neutral-700">
<li>Audits limited to once per year unless required by supervisory authority</li>
<li>Request must be submitted in writing to legal@useplunk.com with 30 days notice</li>
<li>Audits must be conducted by independent third-party auditors bound by confidentiality</li>
<li>Audits conducted during business hours with minimal disruption to operations</li>
<li>Customer bears all costs of audit</li>
<li>Audit scope limited to GDPR compliance (not general security assessments)</li>
</ul>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Alternative to Audits</h3>
<p className="mb-4 leading-relaxed text-neutral-700">
In lieu of conducting a full audit, Customer may request and review sub-processor certifications and
compliance documentation (SOC 2, ISO 27001, etc.) where available.
</p>
</section>
{/* Section 11 */}
<section id="deletion" className="mb-12">
<h2 className="mb-4 text-2xl font-bold text-neutral-900">11. Data Deletion & Return</h2>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Account Deletion</h3>
<p className="mb-4 leading-relaxed text-neutral-700">
When Customer deletes their Plunk account (via dashboard or by request):
</p>
<ul className="mb-4 ml-6 list-disc space-y-2 text-neutral-700">
<li>All Personal Data is immediately deleted from production systems</li>
<li>No grace period or recovery window (deletion is permanent)</li>
<li>
Customer should access or backup data via API before deletion (Plunk does NOT provide data export)
</li>
<li>Deletion includes: contacts, emails, templates, workflows, campaigns, and email activity</li>
</ul>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Backup Retention</h3>
<ul className="mb-4 ml-6 list-disc space-y-2 text-neutral-700">
<li>Deleted data may remain in encrypted backups for up to 30 days for disaster recovery purposes</li>
<li>Backup data is not accessible or restorable after account deletion</li>
<li>Backups are automatically overwritten after retention period</li>
</ul>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Legal Retention</h3>
<p className="mb-4 leading-relaxed text-neutral-700">
Plunk may retain certain data if required by law (e.g., accounting records, fraud prevention):
</p>
<ul className="mb-4 ml-6 list-disc space-y-2 text-neutral-700">
<li>Billing records: Retained per tax/accounting laws (typically 7 years)</li>
<li>Fraud/abuse records: Retained for security purposes (email addresses of suspended accounts)</li>
<li>Legal requests: Data subject to legal holds retained as required by law</li>
</ul>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">No Data Return</h3>
<p className="mb-4 leading-relaxed text-neutral-700">
Plunk does NOT provide data export or return upon termination. Customer must retrieve data via API
before deleting account. Once deleted, data cannot be recovered.
</p>
</section>
{/* Section 12 */}
<section id="liability" className="mb-12">
<h2 className="mb-4 text-2xl font-bold text-neutral-900">12. Liability & Indemnification</h2>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Customer Responsibilities</h3>
<p className="mb-4 leading-relaxed text-neutral-700">Customer (Data Controller) is responsible for:</p>
<ul className="mb-4 ml-6 list-disc space-y-2 text-neutral-700">
<li>
Ensuring lawful basis for processing under GDPR (consent, contract, legitimate interest, etc.)
</li>
<li>Obtaining necessary consents from Data Subjects before adding them to Plunk</li>
<li>Providing privacy notices to Data Subjects per GDPR Article 13/14</li>
<li>Complying with anti-spam laws (CAN-SPAM, CASL, GDPR, etc.)</li>
<li>Verifying Data Subject identity before fulfilling rights requests</li>
<li>Notifying supervisory authorities and Data Subjects of breaches where required</li>
</ul>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Plunk's Liability</h3>
<ul className="mb-4 ml-6 list-disc space-y-2 text-neutral-700">
<li>Plunk is liable to Customer for compliance with this DPA and GDPR Article 28 obligations</li>
<li>Plunk is liable for sub-processor acts/omissions to the same extent as its own acts</li>
<li>
Liability limitations in Terms of Service apply, except where prohibited by GDPR (particularly Art.
82)
</li>
</ul>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Indemnification</h3>
<ul className="mb-4 ml-6 list-disc space-y-2 text-neutral-700">
<li>
Customer indemnifies Plunk for claims arising from Customer's violation of GDPR or data protection
laws
</li>
<li>
Plunk indemnifies Customer for claims arising solely from Plunk's breach of this DPA or GDPR Article
28
</li>
</ul>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">GDPR Fines</h3>
<p className="mb-4 leading-relaxed text-neutral-700">
Under GDPR Article 82(3), liability for damages is allocated between Controller and Processor based on
fault. Each party is liable only for the damage caused by its own GDPR violation.
</p>
</section>
{/* Section 13 */}
<section id="term" className="mb-12">
<h2 className="mb-4 text-2xl font-bold text-neutral-900">13. Term & Termination</h2>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Effective Date</h3>
<p className="mb-4 leading-relaxed text-neutral-700">
This DPA is effective as of the date you first use Plunk's hosted service and remains in effect for
the duration of the Terms of Service.
</p>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Termination</h3>
<p className="mb-4 leading-relaxed text-neutral-700">This DPA terminates automatically when:</p>
<ul className="mb-4 ml-6 list-disc space-y-2 text-neutral-700">
<li>Customer deletes their Plunk account</li>
<li>Terms of Service are terminated</li>
<li>All Personal Data has been deleted per Section 11</li>
</ul>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">Survival</h3>
<p className="mb-4 leading-relaxed text-neutral-700">
Obligations regarding confidentiality, data deletion, and liability survive termination to the extent
necessary to fulfill their purpose.
</p>
<h3 className="mb-3 mt-6 text-xl font-semibold text-neutral-900">DPA Updates</h3>
<ul className="mb-4 ml-6 list-disc space-y-2 text-neutral-700">
<li>Plunk may update this DPA to reflect changes in law, sub-processors, or processing activities</li>
<li>Material changes will be notified via email 30 days in advance</li>
<li>Continued use of Plunk after changes constitutes acceptance</li>
<li>Check "Last Updated" date at top of page for version tracking</li>
</ul>
</section>
{/* Contact Section */}
<section className="mb-12 rounded-lg border border-neutral-200 bg-neutral-50 p-6">
<h2 className="mb-4 text-xl font-semibold text-neutral-900">Questions or Requests?</h2>
<p className="mb-4 leading-relaxed text-neutral-700">
For questions about this DPA, data processing activities, or to exercise audit rights:
</p>
<p className="mb-2 leading-relaxed text-neutral-700">
<strong className="font-semibold text-neutral-900">Email:</strong> legal@useplunk.com
</p>
<p className="mb-4 leading-relaxed text-neutral-700">
<strong className="font-semibold text-neutral-900">Response Time:</strong> Within 10 business days
</p>
<p className="text-sm text-neutral-600">
For Data Subject rights requests, Customers should use the API (see Section 7) or contact
legal@useplunk.com with Data Subject's email address and nature of request.
</p>
</section>
</div>
</div>
</div>
</div>
</>
);
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -4,7 +4,8 @@ import {DASHBOARD_URI} from '../../lib/constants';
import React, {useState} from 'react'; import React, {useState} from 'react';
import {NextSeo} from 'next-seo'; import {NextSeo} from 'next-seo';
import {ArrowRight, CheckCircle, Loader2, Search} from 'lucide-react'; import {ArrowRight, CheckCircle, Loader2, Search} from 'lucide-react';
import {type EmailVerificationResult as VerificationResult, verifyEmail} from '../../lib/emailVerification'; import type {EmailVerificationResult as VerificationResult} from '@plunk/types';
import {verifyEmail} from '../../lib/emailVerification';
import {EmailVerificationResult} from '../../components/tools/EmailVerificationResult'; import {EmailVerificationResult} from '../../components/tools/EmailVerificationResult';
import {Button, Input} from '@plunk/ui'; import {Button, Input} from '@plunk/ui';
import {EMAIL_VERIFICATION_FEATURES} from '../../lib/toolsContent'; import {EMAIL_VERIFICATION_FEATURES} from '../../lib/toolsContent';
+1 -1
View File
@@ -13,7 +13,7 @@
"dependencies": { "dependencies": {
"@plunk/db": "*", "@plunk/db": "*",
"dotenv": "^17.2.3", "dotenv": "^17.2.3",
"mailparser": "^3.7.1", "mailparser": "^3.9.3",
"signale": "^1.4.0", "signale": "^1.4.0",
"smtp-server": "^3.13.4" "smtp-server": "^3.13.4"
}, },
+1 -1
View File
@@ -41,7 +41,7 @@
"framer-motion": "^12.23.24", "framer-motion": "^12.23.24",
"juice": "^11.0.3", "juice": "^11.0.3",
"lucide-react": "^0.553.0", "lucide-react": "^0.553.0",
"next": "^16.0.10", "next": "^16.1.5",
"next-seo": "^6.6.0", "next-seo": "^6.6.0",
"nuqs": "^2.7.3", "nuqs": "^2.7.3",
"react": "19.2.3", "react": "19.2.3",
+34 -5
View File
@@ -34,7 +34,8 @@ export function ActivityFeed({typeFilter, dateRangeDays = 30, contactId}: Activi
setIsLoadingMore(true); setIsLoadingMore(true);
} else { } else {
setIsLoading(true); setIsLoading(true);
setActivities([]); // Don't clear activities immediately - we'll do a smart merge
// This preserves React component instances and their local state
setNextCursor(undefined); setNextCursor(undefined);
setHasMore(true); setHasMore(true);
} }
@@ -58,11 +59,25 @@ export function ActivityFeed({typeFilter, dateRangeDays = 30, contactId}: Activi
const result = await network.fetch<CursorPaginatedResponse<Activity>>('GET', `/activity?${params.toString()}`); const result = await network.fetch<CursorPaginatedResponse<Activity>>('GET', `/activity?${params.toString()}`);
if (cursor) { if (cursor) {
// Append to existing activities // Append to existing activities (pagination)
setActivities(prev => [...prev, ...result.data]); setActivities(prev => [...prev, ...result.data]);
} else { } else {
// Replace activities // Smart merge: preserve existing activity objects by ID to maintain component state
setActivities(result.data); setActivities(prev => {
// If no previous activities, just use new data
if (prev.length === 0) {
return result.data;
}
// Create a map of existing activities by ID for fast lookup
const existingMap = new Map(prev.map(activity => [activity.id, activity]));
// For each new activity, reuse existing object if ID matches (preserves React component instances)
// Otherwise use new object. This maintains correct ordering while preserving component state.
return result.data.map(newActivity =>
existingMap.get(newActivity.id) ?? newActivity
);
});
} }
setNextCursor(result.cursor); setNextCursor(result.cursor);
@@ -95,7 +110,21 @@ export function ActivityFeed({typeFilter, dateRangeDays = 30, contactId}: Activi
const result = await network.fetch<{activities: Activity[]}>('GET', `/activity/upcoming?${params.toString()}`); const result = await network.fetch<{activities: Activity[]}>('GET', `/activity/upcoming?${params.toString()}`);
setUpcomingActivities(result.activities); // Smart merge: preserve existing activity objects by ID to maintain component state
setUpcomingActivities(prev => {
// If no previous activities, just use new data
if (prev.length === 0) {
return result.activities;
}
// Create a map of existing activities by ID for fast lookup
const existingMap = new Map(prev.map(activity => [activity.id, activity]));
// For each new activity, reuse existing object if ID matches
return result.activities.map(newActivity =>
existingMap.get(newActivity.id) ?? newActivity
);
});
} catch (err) { } catch (err) {
console.error('Error fetching upcoming activities:', err); console.error('Error fetching upcoming activities:', err);
// Don't set error state for upcoming - just fail silently // Don't set error state for upcoming - just fail silently
+41 -1
View File
@@ -9,8 +9,10 @@ import {
CheckCircle, CheckCircle,
ChevronRight, ChevronRight,
Eye, Eye,
Inbox,
MousePointerClick, MousePointerClick,
Send, Send,
ShieldAlert,
Workflow, Workflow,
XCircle, XCircle,
Zap, Zap,
@@ -95,7 +97,15 @@ function getUpcomingTime(date: Date): string {
* Check if an activity is an email activity * Check if an activity is an email activity
*/ */
function isEmailActivity(type: string): boolean { function isEmailActivity(type: string): boolean {
return ['email.sent', 'email.delivered', 'email.opened', 'email.clicked', 'email.bounced'].includes(type); return [
'email.sent',
'email.delivered',
'email.received',
'email.opened',
'email.clicked',
'email.bounced',
'email.complaint',
].includes(type);
} }
interface ActivityItemProps { interface ActivityItemProps {
@@ -173,6 +183,19 @@ function getActivityConfig(activity: Activity): ActivityConfig {
}, },
}; };
case 'email.received':
return {
icon: Inbox,
color: 'text-blue-600',
bgColor: 'bg-blue-100',
title: (typeof metadata.subject === 'string' ? metadata.subject : undefined) || 'Email received',
description: typeof metadata.from === 'string' ? `From: ${metadata.from}` : 'Inbound email',
badge: {
label: 'Received',
variant: 'default',
},
};
case 'email.opened': case 'email.opened':
return { return {
icon: Eye, icon: Eye,
@@ -226,6 +249,23 @@ function getActivityConfig(activity: Activity): ActivityConfig {
}, },
}; };
case 'email.complaint':
return {
icon: ShieldAlert,
color: 'text-red-600',
bgColor: 'bg-red-100',
title: (typeof metadata.subject === 'string' ? metadata.subject : undefined) || 'Spam complaint',
description: metadata.campaignName
? `Campaign: ${String(metadata.campaignName)}`
: metadata.workflowName
? `Workflow: ${String(metadata.workflowName)}`
: 'Recipient marked as spam',
badge: {
label: 'Complaint',
variant: 'destructive',
},
};
case 'workflow.started': case 'workflow.started':
return { return {
icon: Workflow, icon: Workflow,
+34
View File
@@ -78,6 +78,7 @@ export function BillingLimits({projectId, hasSubscription, billingEnabled}: Bill
workflows: null, workflows: null,
campaigns: null, campaigns: null,
transactional: null, transactional: null,
inbound: null,
}, },
}); });
@@ -88,6 +89,7 @@ export function BillingLimits({projectId, hasSubscription, billingEnabled}: Bill
workflows: limitsData.workflows.limit, workflows: limitsData.workflows.limit,
campaigns: limitsData.campaigns.limit, campaigns: limitsData.campaigns.limit,
transactional: limitsData.transactional.limit, transactional: limitsData.transactional.limit,
inbound: limitsData.inbound.limit,
}); });
} }
}, [limitsData, form]); }, [limitsData, form]);
@@ -121,6 +123,7 @@ export function BillingLimits({projectId, hasSubscription, billingEnabled}: Bill
workflows: limitsData.workflows.limit, workflows: limitsData.workflows.limit,
campaigns: limitsData.campaigns.limit, campaigns: limitsData.campaigns.limit,
transactional: limitsData.transactional.limit, transactional: limitsData.transactional.limit,
inbound: limitsData.inbound.limit,
}); });
} }
setIsEditing(false); setIsEditing(false);
@@ -217,6 +220,7 @@ export function BillingLimits({projectId, hasSubscription, billingEnabled}: Bill
usage={limitsData.transactional} usage={limitsData.transactional}
currency={limitsData.currency} currency={limitsData.currency}
/> />
<UsageDisplay category="Inbound" usage={limitsData.inbound} currency={limitsData.currency} />
</> </>
)} )}
@@ -322,6 +326,36 @@ export function BillingLimits({projectId, hasSubscription, billingEnabled}: Bill
}} }}
/> />
<FormField
control={form.control}
name="inbound"
render={({field}) => {
const estimatedCost =
limitsData?.currency && field.value
? formatEmailCost(Number(field.value), limitsData.currency)
: null;
return (
<FormItem>
<FormLabel>Inbound Emails Limit</FormLabel>
<FormControl>
<Input
type="number"
placeholder="Unlimited"
{...field}
value={field.value ?? ''}
onChange={e => field.onChange(e.target.value === '' ? null : e.target.value)}
/>
</FormControl>
<FormDescription>
Maximum inbound emails per month. Leave empty for unlimited.
{estimatedCost && <span className="text-neutral-500"> {estimatedCost}/month</span>}
</FormDescription>
<FormMessage />
</FormItem>
);
}}
/>
<div className="flex justify-end gap-2 pt-4"> <div className="flex justify-end gap-2 pt-4">
<Button type="button" variant="outline" onClick={handleCancel}> <Button type="button" variant="outline" onClick={handleCancel}>
Cancel Cancel
+152
View File
@@ -0,0 +1,152 @@
import type {Contact} from '@plunk/db';
import type {CursorPaginatedResponse} from '@plunk/types';
import {Input, Popover, PopoverContent, PopoverTrigger} from '@plunk/ui';
import {Check, ChevronsUpDown, MailCheck, MailX, Search, X} from 'lucide-react';
import {useEffect, useRef, useState} from 'react';
import useSWR from 'swr';
interface ContactPickerProps {
/** Currently selected emails */
selected: string[];
/** Called when selection changes */
onChange: (emails: string[]) => void;
/** Emails already in the segment (shown as disabled) */
existing?: string[];
placeholder?: string;
}
/**
* Searchable multi-select contact picker backed by the /contacts API.
* Only fetches when the user types (safe for large contact lists).
*/
export function ContactPicker({
selected,
onChange,
existing = [],
placeholder = 'Search contacts...',
}: ContactPickerProps) {
const [open, setOpen] = useState(false);
const [search, setSearch] = useState('');
const [debouncedSearch, setDebouncedSearch] = useState('');
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => {
if (debounceRef.current) clearTimeout(debounceRef.current);
debounceRef.current = setTimeout(() => setDebouncedSearch(search), 300);
return () => {
if (debounceRef.current) clearTimeout(debounceRef.current);
};
}, [search]);
// Only fetch when there's a search term — avoids loading all contacts on open
const {data, isLoading} = useSWR<CursorPaginatedResponse<Contact>>(
open && debouncedSearch.length > 0 ? `/contacts?limit=20&search=${encodeURIComponent(debouncedSearch)}` : null,
{revalidateOnFocus: false},
);
const contacts = data?.data ?? [];
const toggle = (email: string) => {
if (selected.includes(email)) {
onChange(selected.filter(e => e !== email));
} else {
onChange([...selected, email]);
}
};
return (
<div className="space-y-3">
<Popover open={open} onOpenChange={v => { setOpen(v); if (!v) setSearch(''); }}>
<PopoverTrigger asChild>
<button
type="button"
role="combobox"
aria-expanded={open}
className="flex h-10 w-full items-center justify-between rounded-md border border-neutral-200 bg-white px-3 py-2 text-sm text-neutral-500 hover:border-neutral-300 focus:outline-none focus:ring-2 focus:ring-neutral-900 focus:ring-offset-0 transition-colors"
>
<span>{placeholder}</span>
<ChevronsUpDown className="h-4 w-4 opacity-40 shrink-0" />
</button>
</PopoverTrigger>
<PopoverContent
className="p-0"
style={{width: 'var(--radix-popover-trigger-width)'}}
align="start"
>
{/* Search input */}
<div className="flex items-center border-b border-neutral-200 px-3 py-2">
<Search className="mr-2 h-4 w-4 shrink-0 text-neutral-400" />
<Input
placeholder="Type an email to search..."
value={search}
onChange={e => setSearch(e.target.value)}
className="border-0 p-0 h-8 focus-visible:ring-0 focus-visible:ring-offset-0 text-sm"
autoFocus
/>
</div>
{/* Results */}
<div className="max-h-[240px] overflow-y-auto p-1">
{debouncedSearch.length === 0 ? (
<p className="py-6 text-center text-sm text-neutral-400">Type to search contacts</p>
) : isLoading ? (
<p className="py-6 text-center text-sm text-neutral-400">Searching...</p>
) : contacts.length === 0 ? (
<p className="py-6 text-center text-sm text-neutral-400">No contacts found</p>
) : (
contacts.map(contact => {
const isSelected = selected.includes(contact.email);
const isExisting = existing.includes(contact.email);
return (
<button
key={contact.id}
type="button"
disabled={isExisting}
onClick={() => toggle(contact.email)}
className="w-full flex items-center gap-2 rounded-sm px-2 py-1.5 text-sm hover:bg-neutral-50 disabled:opacity-40 disabled:cursor-not-allowed text-left transition-colors"
>
{contact.subscribed ? (
<MailCheck className="h-4 w-4 text-green-600 shrink-0" />
) : (
<MailX className="h-4 w-4 text-red-500 shrink-0" />
)}
<span className="flex-1 truncate text-neutral-900">{contact.email}</span>
{isExisting && (
<span className="text-xs text-neutral-400 shrink-0">already member</span>
)}
{isSelected && !isExisting && (
<Check className="h-4 w-4 text-neutral-900 shrink-0" />
)}
</button>
);
})
)}
</div>
</PopoverContent>
</Popover>
{/* Selected chips */}
{selected.length > 0 && (
<div className="flex flex-wrap gap-2">
{selected.map(email => (
<span
key={email}
className="inline-flex items-center gap-1.5 rounded-full bg-neutral-100 border border-neutral-200 pl-3 pr-1.5 py-1 text-sm text-neutral-800"
>
{email}
<button
type="button"
onClick={() => onChange(selected.filter(e => e !== email))}
className="rounded-full p-0.5 hover:bg-neutral-300 transition-colors"
aria-label={`Remove ${email}`}
>
<X className="h-3 w-3" />
</button>
</span>
))}
</div>
)}
</div>
);
}
+24 -7
View File
@@ -1,9 +1,11 @@
import {useActiveProject} from '../lib/contexts/ActiveProjectProvider'; import {useActiveProject} from '../lib/contexts/ActiveProjectProvider';
import {useUser} from '../lib/hooks/useUser'; import {useUser} from '../lib/hooks/useUser';
import {WIKI_URI} from '../lib/constants';
import {network} from '../lib/network'; import {network} from '../lib/network';
import { import {
Activity, Activity,
BarChart3, BarChart3,
BookOpen,
ChevronDown, ChevronDown,
FileText, FileText,
Layers, Layers,
@@ -20,7 +22,7 @@ import {
import Image from 'next/image'; import Image from 'next/image';
import Link from 'next/link'; import Link from 'next/link';
import {useRouter} from 'next/router'; import {useRouter} from 'next/router';
import {useCallback, useEffect, useRef, useState} from 'react'; import {useCallback, useEffect, useMemo, useRef, useState} from 'react';
interface DashboardLayoutProps { interface DashboardLayoutProps {
children: React.ReactNode; children: React.ReactNode;
@@ -72,6 +74,11 @@ export function DashboardLayout({children}: DashboardLayoutProps) {
const mobileProjectMenuRef = useRef<HTMLDivElement>(null); const mobileProjectMenuRef = useRef<HTMLDivElement>(null);
const mobileUserMenuRef = useRef<HTMLDivElement>(null); const mobileUserMenuRef = useRef<HTMLDivElement>(null);
// Sort projects alphabetically by name
const sortedProjects = useMemo(() => {
return [...availableProjects].sort((a, b) => a.name.localeCompare(b.name));
}, [availableProjects]);
// Handle click outside for project menu // Handle click outside for project menu
useEffect(() => { useEffect(() => {
function handleClickOutside(event: MouseEvent) { function handleClickOutside(event: MouseEvent) {
@@ -177,8 +184,8 @@ export function DashboardLayout({children}: DashboardLayoutProps) {
{/* Project Dropdown */} {/* Project Dropdown */}
{showProjectMenu && ( {showProjectMenu && (
<div className="absolute top-full left-0 right-0 mt-1 bg-white border border-neutral-200 rounded-lg shadow-lg z-50 py-1"> <div className="absolute top-full left-0 right-0 mt-1 bg-white border border-neutral-200 rounded-lg shadow-lg z-50 py-1 max-h-[400px] overflow-y-auto min-w-full w-max">
{availableProjects.map(project => ( {sortedProjects.map(project => (
<button <button
key={project.id} key={project.id}
onClick={e => { onClick={e => {
@@ -187,14 +194,14 @@ export function DashboardLayout({children}: DashboardLayoutProps) {
setActiveProject(project); setActiveProject(project);
setShowProjectMenu(false); setShowProjectMenu(false);
}} }}
className="w-full flex items-center gap-2 px-3 py-2 text-sm hover:bg-neutral-50 transition-colors" className="w-full flex items-center gap-2 px-3 py-2 text-sm hover:bg-neutral-50 transition-colors whitespace-nowrap"
> >
<div className="h-6 w-6 rounded bg-neutral-900 text-white flex items-center justify-center text-xs font-medium"> <div className="h-6 w-6 rounded bg-neutral-900 text-white flex items-center justify-center text-xs font-medium flex-shrink-0">
{project.name.charAt(0).toUpperCase()} {project.name.charAt(0).toUpperCase()}
</div> </div>
<span className="text-neutral-900 text-left flex-1">{project.name}</span> <span className="text-neutral-900 text-left flex-1">{project.name}</span>
{activeProject?.id === project.id && ( {activeProject?.id === project.id && (
<div className="ml-auto h-1.5 w-1.5 rounded-full bg-neutral-900" /> <div className="ml-auto h-1.5 w-1.5 rounded-full bg-neutral-900 flex-shrink-0" />
)} )}
</button> </button>
))} ))}
@@ -202,7 +209,7 @@ export function DashboardLayout({children}: DashboardLayoutProps) {
<Link <Link
href="/projects/create" href="/projects/create"
onClick={() => setShowProjectMenu(false)} onClick={() => setShowProjectMenu(false)}
className="w-full flex items-center gap-2 px-3 py-2 text-sm hover:bg-neutral-50 transition-colors text-neutral-700" className="w-full flex items-center gap-2 px-3 py-2 text-sm hover:bg-neutral-50 transition-colors text-neutral-700 whitespace-nowrap"
> >
<Plus className="h-4 w-4" /> <Plus className="h-4 w-4" />
<span>Create project</span> <span>Create project</span>
@@ -246,6 +253,16 @@ export function DashboardLayout({children}: DashboardLayoutProps) {
{/* Settings & User Menu */} {/* Settings & User Menu */}
<div className="border-t border-neutral-200 p-3 space-y-1"> <div className="border-t border-neutral-200 p-3 space-y-1">
<a
href={WIKI_URI}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-3 px-3 py-2 text-sm font-medium rounded-lg transition-colors text-neutral-700 hover:bg-neutral-50 hover:text-neutral-900"
>
<BookOpen className="h-5 w-5" />
Documentation
</a>
<Link <Link
href="/settings" href="/settings"
onClick={() => setShowMobileMenu(false)} onClick={() => setShowMobileMenu(false)}
+198 -22
View File
@@ -3,8 +3,6 @@ import {useForm} from 'react-hook-form';
import {zodResolver} from '@hookform/resolvers/zod'; import {zodResolver} from '@hookform/resolvers/zod';
import {DomainSchemas} from '@plunk/shared'; import {DomainSchemas} from '@plunk/shared';
import { import {
Alert,
AlertDescription,
Badge, Badge,
Button, Button,
Card, Card,
@@ -22,7 +20,8 @@ import {
Input, Input,
} from '@plunk/ui'; } from '@plunk/ui';
import {AnimatePresence, motion} from 'framer-motion'; import {AnimatePresence, motion} from 'framer-motion';
import {Check, CheckCircle2, Copy, Loader2, RefreshCw, Trash2, XCircle} from 'lucide-react'; import {Check, CheckCircle2, ChevronDown, Copy, Loader2, RefreshCw, Trash2, XCircle} from 'lucide-react';
import {useConfig} from '../lib/hooks/useConfig';
import {useAddDomain, useCheckDomainVerification, useDomains, useRemoveDomain} from '../lib/hooks/useDomains'; import {useAddDomain, useCheckDomainVerification, useDomains, useRemoveDomain} from '../lib/hooks/useDomains';
interface DomainsSettingsProps { interface DomainsSettingsProps {
@@ -34,6 +33,7 @@ export function DomainsSettings({projectId}: DomainsSettingsProps) {
const {addDomain} = useAddDomain(); const {addDomain} = useAddDomain();
const {checkVerification} = useCheckDomainVerification(); const {checkVerification} = useCheckDomainVerification();
const {removeDomain} = useRemoveDomain(); const {removeDomain} = useRemoveDomain();
const {data: config} = useConfig();
const [successMessage, setSuccessMessage] = useState<string | null>(null); const [successMessage, setSuccessMessage] = useState<string | null>(null);
const [errorMessage, setErrorMessage] = useState<string | null>(null); const [errorMessage, setErrorMessage] = useState<string | null>(null);
@@ -47,6 +47,7 @@ export function DomainsSettings({projectId}: DomainsSettingsProps) {
const [cooldownSeconds, setCooldownSeconds] = useState<{[key: string]: number}>({}); const [cooldownSeconds, setCooldownSeconds] = useState<{[key: string]: number}>({});
const [showRemoveDialog, setShowRemoveDialog] = useState(false); const [showRemoveDialog, setShowRemoveDialog] = useState(false);
const [domainToRemove, setDomainToRemove] = useState<{id: string; name: string} | null>(null); const [domainToRemove, setDomainToRemove] = useState<{id: string; name: string} | null>(null);
const [expandedDomains, setExpandedDomains] = useState<{[key: string]: boolean}>({});
const form = useForm<{domain: string}>({ const form = useForm<{domain: string}>({
resolver: zodResolver(DomainSchemas.create.omit({projectId: true})), resolver: zodResolver(DomainSchemas.create.omit({projectId: true})),
@@ -86,6 +87,28 @@ export function DomainsSettings({projectId}: DomainsSettingsProps) {
return () => clearInterval(interval); return () => clearInterval(interval);
}, [lastVerificationCheck]); }, [lastVerificationCheck]);
// Auto-expand unverified domains on initial load
useEffect(() => {
if (domains && domains.length > 0) {
const unverifiedDomains = domains
.filter(d => !d.verified)
.reduce(
(acc, d) => {
acc[d.id] = true;
return acc;
},
{} as {[key: string]: boolean},
);
if (Object.keys(unverifiedDomains).length > 0) {
setExpandedDomains(prev => ({
...prev,
...unverifiedDomains,
}));
}
}
}, [domains]);
const showMessage = (type: 'success' | 'error', message: string) => { const showMessage = (type: 'success' | 'error', message: string) => {
if (type === 'success') { if (type === 'success') {
setSuccessMessage(message); setSuccessMessage(message);
@@ -113,6 +136,11 @@ export function DomainsSettings({projectId}: DomainsSettingsProps) {
}, },
})); }));
setSelectedDomain(newDomain.id); setSelectedDomain(newDomain.id);
// Auto-expand newly added domain
setExpandedDomains(prev => ({
...prev,
[newDomain.id]: true,
}));
} }
await mutateDomains(); await mutateDomains();
@@ -322,20 +350,42 @@ export function DomainsSettings({projectId}: DomainsSettingsProps) {
</div> </div>
</div> </div>
{!status.verified && Array.isArray(status.tokens) && (status.tokens as string[]).length > 0 && ( {Array.isArray(status.tokens) && (status.tokens as string[]).length > 0 && (
<div className="mt-4 pt-4 border-t border-neutral-200"> <div className="mt-3">
<Alert> <button
<AlertDescription> onClick={() =>
<div className="space-y-4"> setExpandedDomains(prev => ({
...prev,
[domain.id]: !prev[domain.id],
}))
}
className="flex items-center gap-1.5 text-xs text-neutral-600 hover:text-neutral-900 transition-colors"
>
<ChevronDown
className={`h-3.5 w-3.5 transition-transform ${
expandedDomains[domain.id] ? 'rotate-180' : ''
}`}
/>
<span>{status.verified ? 'View DNS Records' : 'DNS Configuration Required'}</span>
</button>
{expandedDomains[domain.id] && (
<div className="mt-3 space-y-4">
{/* Required DKIM Records for Sending */}
<div> <div>
<p className="font-medium text-sm mb-1">DNS Configuration Required</p> <div className="flex items-center gap-2 mb-2">
<p className="text-xs text-neutral-600"> <h4 className="text-xs font-semibold text-neutral-900">Required for Sending</h4>
Add the following DNS records to verify your domain. DNS changes can take up to 48 <Badge variant="default" className="text-[10px] px-1.5 py-0">
hours to propagate. REQUIRED
</Badge>
</div>
{!status.verified && (
<p className="text-xs text-neutral-600 mb-2">
Add these DKIM records to verify your domain and send emails. DNS changes can take up
to 48 hours to propagate.
</p> </p>
</div> )}
{/* DNS Records Table */}
<div className="overflow-x-auto"> <div className="overflow-x-auto">
<table className="w-full text-xs border-collapse"> <table className="w-full text-xs border-collapse">
<thead> <thead>
@@ -401,8 +451,42 @@ export function DomainsSettings({projectId}: DomainsSettingsProps) {
</td> </td>
</tr> </tr>
))} ))}
</tbody>
</table>
</div>
</div>
{/* MX Record */} {/* Optional: Custom MAIL FROM Domain */}
{config?.aws?.sesRegion && (
<div>
<div className="flex items-center gap-2 mb-2">
<h4 className="text-xs font-semibold text-neutral-900">Custom MAIL FROM Domain</h4>
<Badge variant="secondary" className="text-[10px] px-1.5 py-0">
OPTIONAL
</Badge>
</div>
<p className="text-xs text-neutral-600 mb-2">
Set up a custom MAIL FROM domain (plunk.{domain.domain}) to improve deliverability and
handle bounces/complaints.
</p>
<div className="overflow-x-auto">
<table className="w-full text-xs border-collapse">
<thead>
<tr className="border-b border-neutral-200">
<th className="text-left py-2 px-3 font-medium text-neutral-700 bg-neutral-50">
Type
</th>
<th className="text-left py-2 px-3 font-medium text-neutral-700 bg-neutral-50">
Name
</th>
<th className="text-left py-2 px-3 font-medium text-neutral-700 bg-neutral-50">
Value
</th>
</tr>
</thead>
<tbody className="divide-y divide-neutral-200">
{/* MX Record (Bounce/Complaint Handling) */}
<tr className="hover:bg-neutral-50/50"> <tr className="hover:bg-neutral-50/50">
<td className="py-3 px-3"> <td className="py-3 px-3">
<code className="text-xs font-medium text-neutral-900">MX</code> <code className="text-xs font-medium text-neutral-900">MX</code>
@@ -429,17 +513,21 @@ export function DomainsSettings({projectId}: DomainsSettingsProps) {
<td className="py-3 px-3"> <td className="py-3 px-3">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<code className="text-xs font-mono text-neutral-700 break-all flex-1"> <code className="text-xs font-mono text-neutral-700 break-all flex-1">
10 feedback-smtp.eu-north-1.amazonses.com 10 feedback-smtp.{config.aws.sesRegion}.amazonses.com
</code> </code>
<Button <Button
variant="ghost" variant="ghost"
size="sm" size="sm"
onClick={() => onClick={() =>
handleCopyToken('10 feedback-smtp.eu-north-1.amazonses.com', 1000) handleCopyToken(
`10 feedback-smtp.${config.aws.sesRegion}.amazonses.com`,
1000,
)
} }
className="shrink-0 h-6 w-6 p-0" className="shrink-0 h-6 w-6 p-0"
> >
{copiedToken === '10 feedback-smtp.eu-north-1.amazonses.com-1000' ? ( {copiedToken ===
`10 feedback-smtp.${config.aws.sesRegion}.amazonses.com-1000` ? (
<Check className="h-3 w-3 text-green-600" /> <Check className="h-3 w-3 text-green-600" />
) : ( ) : (
<Copy className="h-3 w-3" /> <Copy className="h-3 w-3" />
@@ -481,7 +569,9 @@ export function DomainsSettings({projectId}: DomainsSettingsProps) {
<Button <Button
variant="ghost" variant="ghost"
size="sm" size="sm"
onClick={() => handleCopyToken('"v=spf1 include:amazonses.com ~all"', 1001)} onClick={() =>
handleCopyToken('"v=spf1 include:amazonses.com ~all"', 1001)
}
className="shrink-0 h-6 w-6 p-0" className="shrink-0 h-6 w-6 p-0"
> >
{copiedToken === '"v=spf1 include:amazonses.com ~all"-1001' ? ( {copiedToken === '"v=spf1 include:amazonses.com ~all"-1001' ? (
@@ -496,8 +586,95 @@ export function DomainsSettings({projectId}: DomainsSettingsProps) {
</tbody> </tbody>
</table> </table>
</div> </div>
</div>
)}
<div className="flex items-start gap-2 p-3 bg-blue-50 rounded-lg border border-blue-200"> {/* Optional: Inbound Email */}
{config?.aws?.sesRegion && (
<div>
<div className="flex items-center gap-2 mb-2">
<h4 className="text-xs font-semibold text-neutral-900">Inbound Email</h4>
<Badge variant="secondary" className="text-[10px] px-1.5 py-0">
OPTIONAL
</Badge>
</div>
<p className="text-xs text-neutral-600 mb-2">
Configure this MX record to receive emails at your domain.
</p>
<div className="overflow-x-auto">
<table className="w-full text-xs border-collapse">
<thead>
<tr className="border-b border-neutral-200">
<th className="text-left py-2 px-3 font-medium text-neutral-700 bg-neutral-50">
Type
</th>
<th className="text-left py-2 px-3 font-medium text-neutral-700 bg-neutral-50">
Name
</th>
<th className="text-left py-2 px-3 font-medium text-neutral-700 bg-neutral-50">
Value
</th>
</tr>
</thead>
<tbody className="divide-y divide-neutral-200">
{/* Inbound MX Record */}
<tr className="hover:bg-neutral-50/50">
<td className="py-3 px-3">
<code className="text-xs font-medium text-neutral-900">MX</code>
</td>
<td className="py-3 px-3">
<div className="flex items-center gap-2">
<code className="text-xs font-mono text-neutral-700 break-all flex-1">
{domain.domain}
</code>
<Button
variant="ghost"
size="sm"
onClick={() => handleCopyToken(domain.domain, 3002)}
className="shrink-0 h-6 w-6 p-0"
>
{copiedToken === `${domain.domain}-3002` ? (
<Check className="h-3 w-3 text-green-600" />
) : (
<Copy className="h-3 w-3" />
)}
</Button>
</div>
</td>
<td className="py-3 px-3">
<div className="flex items-center gap-2">
<code className="text-xs font-mono text-neutral-700 break-all flex-1">
10 inbound-smtp.{config.aws.sesRegion}.amazonaws.com
</code>
<Button
variant="ghost"
size="sm"
onClick={() =>
handleCopyToken(
`10 inbound-smtp.${config.aws.sesRegion}.amazonaws.com`,
1002,
)
}
className="shrink-0 h-6 w-6 p-0"
>
{copiedToken ===
`10 inbound-smtp.${config.aws.sesRegion}.amazonaws.com-1002` ? (
<Check className="h-3 w-3 text-green-600" />
) : (
<Copy className="h-3 w-3" />
)}
</Button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
)}
<div className="flex items-start gap-2 p-3 bg-blue-50 rounded-lg border border-blue-200 mt-3">
<div className="text-blue-600 mt-0.5"> <div className="text-blue-600 mt-0.5">
<svg className="h-4 w-4" fill="currentColor" viewBox="0 0 20 20"> <svg className="h-4 w-4" fill="currentColor" viewBox="0 0 20 20">
<path <path
@@ -513,8 +690,7 @@ export function DomainsSettings({projectId}: DomainsSettingsProps) {
</p> </p>
</div> </div>
</div> </div>
</AlertDescription> )}
</Alert>
</div> </div>
)} )}
</div> </div>
@@ -27,12 +27,14 @@ const STANDARD_OPERATORS: {value: SegmentFilterOperator; label: string}[] = [
{value: 'lessThanOrEqual', label: 'Less than or equal to'}, {value: 'lessThanOrEqual', label: 'Less than or equal to'},
{value: 'exists', label: 'Exists'}, {value: 'exists', label: 'Exists'},
{value: 'notExists', label: 'Does not exist'}, {value: 'notExists', label: 'Does not exist'},
{value: 'within', label: 'Within (time)'}, {value: 'within', label: 'Younger than (time)'},
{value: 'olderThan', label: 'Older than (time)'},
]; ];
const EVENT_OPERATORS: {value: SegmentFilterOperator; label: string}[] = [ const EVENT_OPERATORS: {value: SegmentFilterOperator; label: string}[] = [
{value: 'triggered', label: 'Ever occurred'}, {value: 'triggered', label: 'Ever occurred'},
{value: 'triggeredWithin', label: 'Occurred within'}, {value: 'triggeredWithin', label: 'Occurred within'},
{value: 'triggeredOlderThan', label: 'Occurred over (time) ago'},
{value: 'notTriggered', label: 'Never occurred'}, {value: 'notTriggered', label: 'Never occurred'},
]; ];
@@ -172,6 +174,7 @@ const FilterRow = memo(function FilterRow({filter, onChange, onRemove, available
'exists', 'exists',
'notExists', 'notExists',
'within', 'within',
'olderThan',
].includes(op.value), ].includes(op.value),
); );
} }
@@ -183,7 +186,7 @@ const FilterRow = memo(function FilterRow({filter, onChange, onRemove, available
}, []); }, []);
const needsValue = !['exists', 'notExists', 'triggered', 'notTriggered'].includes(filter.operator); const needsValue = !['exists', 'notExists', 'triggered', 'notTriggered'].includes(filter.operator);
const needsUnit = ['within', 'triggeredWithin'].includes(filter.operator); const needsUnit = ['within', 'triggeredWithin', 'olderThan', 'triggeredOlderThan'].includes(filter.operator);
// Get field type from available fields // Get field type from available fields
const fieldOption = useMemo( const fieldOption = useMemo(
@@ -217,6 +220,7 @@ const FilterRow = memo(function FilterRow({filter, onChange, onRemove, available
'exists', 'exists',
'notExists', 'notExists',
'within', 'within',
'olderThan',
].includes(op.value), ].includes(op.value),
); );
} }
@@ -232,7 +236,9 @@ const FilterRow = memo(function FilterRow({filter, onChange, onRemove, available
const selectedField = availableFields.find(f => f.value === value); const selectedField = availableFields.find(f => f.value === value);
const newFieldType = selectedField?.type || 'string'; const newFieldType = selectedField?.type || 'string';
const isEvent = newFieldType === 'event' || newFieldType === 'email'; const isEvent = newFieldType === 'event' || newFieldType === 'email';
const currentOperatorIsEvent = ['triggered', 'triggeredWithin', 'notTriggered'].includes(filter.operator); const currentOperatorIsEvent = ['triggered', 'triggeredWithin', 'triggeredOlderThan', 'notTriggered'].includes(
filter.operator,
);
// Determine default operator and value based on new field type // Determine default operator and value based on new field type
let newOperator = filter.operator; let newOperator = filter.operator;
@@ -267,7 +273,9 @@ const FilterRow = memo(function FilterRow({filter, onChange, onRemove, available
newUnit = undefined; newUnit = undefined;
// If the new operator doesn't support units but we had them, ensure value is appropriate // If the new operator doesn't support units but we had them, ensure value is appropriate
const newOperatorNeedsUnit = ['within', 'triggeredWithin'].includes(newOperator); const newOperatorNeedsUnit = ['within', 'triggeredWithin', 'olderThan', 'triggeredOlderThan'].includes(
newOperator,
);
if (!newOperatorNeedsUnit) { if (!newOperatorNeedsUnit) {
// Convert numeric value back to appropriate type for the field // Convert numeric value back to appropriate type for the field
newValue = getDefaultValueForType(newFieldType); newValue = getDefaultValueForType(newFieldType);
@@ -399,8 +407,12 @@ const FilterRow = memo(function FilterRow({filter, onChange, onRemove, available
// Check if we're switching between operators that need different value types // Check if we're switching between operators that need different value types
const oldNeedsValue = !['exists', 'notExists', 'triggered', 'notTriggered'].includes(oldOperator); const oldNeedsValue = !['exists', 'notExists', 'triggered', 'notTriggered'].includes(oldOperator);
const newNeedsValue = !['exists', 'notExists', 'triggered', 'notTriggered'].includes(newOperator); const newNeedsValue = !['exists', 'notExists', 'triggered', 'notTriggered'].includes(newOperator);
const oldNeedsUnit = ['within', 'triggeredWithin'].includes(oldOperator); const oldNeedsUnit = ['within', 'triggeredWithin', 'olderThan', 'triggeredOlderThan'].includes(
const newNeedsUnit = ['within', 'triggeredWithin'].includes(newOperator); oldOperator,
);
const newNeedsUnit = ['within', 'triggeredWithin', 'olderThan', 'triggeredOlderThan'].includes(
newOperator,
);
const updatedFilter: SegmentFilter = {...filter, operator: newOperator}; const updatedFilter: SegmentFilter = {...filter, operator: newOperator};
+119 -8
View File
@@ -128,7 +128,29 @@ function getLayoutedElements(nodes: Node[], edges: Edge[]) {
}; };
}); });
return {nodes: layoutedNodes, edges}; // Center "Add Step" nodes directly below their parent nodes
const adjustedNodes = layoutedNodes.map(node => {
if (node.type === 'addStep') {
// Find the parent node (the source of the edge connecting to this add node)
const parentEdge = edges.find(edge => edge.target === node.id);
if (parentEdge) {
const parentNode = layoutedNodes.find(n => n.id === parentEdge.source);
if (parentNode) {
// Center the add node below the parent node
return {
...node,
position: {
x: parentNode.position.x + nodeWidth / 2 - 32, // 32 is half of the 64px (w-16) width of the add button
y: node.position.y,
},
};
}
}
}
return node;
});
return {nodes: adjustedNodes, edges};
} }
// Add Step Node - appears at the end of flow paths // Add Step Node - appears at the end of flow paths
@@ -204,6 +226,22 @@ function CustomNode({
onMouseLeave={() => setShowActions(false)} onMouseLeave={() => setShowActions(false)}
> >
{/* Action buttons - shown on hover */} {/* Action buttons - shown on hover */}
{showActions && data.type === 'TRIGGER' && (
<div className="absolute -top-3 -right-3 flex gap-1.5 z-10">
<Button
onClick={e => {
e.stopPropagation();
data.onEdit?.();
}}
variant="outline"
size="icon"
className="h-7 w-7 shadow-md"
title="Edit trigger settings"
>
<Settings className="h-3.5 w-3.5" />
</Button>
</div>
)}
{showActions && data.type !== 'TRIGGER' && ( {showActions && data.type !== 'TRIGGER' && (
<div className="absolute -top-3 -right-3 flex gap-1.5 z-10"> <div className="absolute -top-3 -right-3 flex gap-1.5 z-10">
<Button <Button
@@ -300,6 +338,14 @@ function CustomNode({
</div> </div>
</div> </div>
)} )}
{data.type === 'TRIGGER' && data.config?.eventName && (
<div className="mt-3 pt-3 border-t border-neutral-100">
<div className="flex items-center gap-2 text-xs text-neutral-600">
<Lightbulb className="h-3 w-3" />
<span className="truncate">{data.config.eventName}</span>
</div>
</div>
)}
{data.type === 'WEBHOOK' && data.config?.url && ( {data.type === 'WEBHOOK' && data.config?.url && (
<div className="mt-3 pt-3 border-t border-neutral-100"> <div className="mt-3 pt-3 border-t border-neutral-100">
<div className="flex items-center gap-2 text-xs text-neutral-600"> <div className="flex items-center gap-2 text-xs text-neutral-600">
@@ -353,11 +399,23 @@ export function WorkflowBuilder({workflowId, steps, onUpdate}: WorkflowBuilderPr
const [stepToDelete, setStepToDelete] = useState<string | null>(null); const [stepToDelete, setStepToDelete] = useState<string | null>(null);
// Define handlers before they are used in useMemo // Define handlers before they are used in useMemo
const handleEditStep = useCallback((stepId: string) => { const handleEditStep = useCallback(
// This will be handled by the parent component (stepId: string) => {
// Check if this is a TRIGGER step
const step = steps.find(s => s.id === stepId);
if (step?.type === 'TRIGGER') {
// For TRIGGER steps, open workflow settings instead
const event = new CustomEvent('workflow-open-settings');
window.dispatchEvent(event);
} else {
// For other steps, open step editor
const event = new CustomEvent('workflow-edit-step', {detail: {stepId}}); const event = new CustomEvent('workflow-edit-step', {detail: {stepId}});
window.dispatchEvent(event); window.dispatchEvent(event);
}, []); }
},
[steps],
);
const handleDeleteStepClick = useCallback((stepId: string) => { const handleDeleteStepClick = useCallback((stepId: string) => {
setStepToDelete(stepId); setStepToDelete(stepId);
@@ -412,6 +470,7 @@ export function WorkflowBuilder({workflowId, steps, onUpdate}: WorkflowBuilderPr
id: `${step.id}-add-yes`, id: `${step.id}-add-yes`,
type: 'addStep', type: 'addStep',
position: {x: 0, y: 0}, position: {x: 0, y: 0},
draggable: false,
data: { data: {
label: 'Yes', label: 'Yes',
onClick: () => setAddStepContext({fromStepId: step.id, branch: 'yes'}), onClick: () => setAddStepContext({fromStepId: step.id, branch: 'yes'}),
@@ -424,6 +483,7 @@ export function WorkflowBuilder({workflowId, steps, onUpdate}: WorkflowBuilderPr
id: `${step.id}-add-no`, id: `${step.id}-add-no`,
type: 'addStep', type: 'addStep',
position: {x: 0, y: 0}, position: {x: 0, y: 0},
draggable: false,
data: { data: {
label: 'No', label: 'No',
onClick: () => setAddStepContext({fromStepId: step.id, branch: 'no'}), onClick: () => setAddStepContext({fromStepId: step.id, branch: 'no'}),
@@ -437,6 +497,7 @@ export function WorkflowBuilder({workflowId, steps, onUpdate}: WorkflowBuilderPr
id: `${step.id}-add`, id: `${step.id}-add`,
type: 'addStep', type: 'addStep',
position: {x: 0, y: 0}, position: {x: 0, y: 0},
draggable: false,
data: { data: {
label: '', label: '',
onClick: () => setAddStepContext({fromStepId: step.id}), onClick: () => setAddStepContext({fromStepId: step.id}),
@@ -510,7 +571,7 @@ export function WorkflowBuilder({workflowId, steps, onUpdate}: WorkflowBuilderPr
id: `${step.id}-add-yes-edge`, id: `${step.id}-add-yes-edge`,
source: step.id, source: step.id,
target: `${step.id}-add-yes`, target: `${step.id}-add-yes`,
type: 'smoothstep', type: 'straight',
animated: false, animated: false,
label: 'Yes', label: 'Yes',
labelStyle: {fill: '#16a34a', fontWeight: 600, fontSize: 12}, labelStyle: {fill: '#16a34a', fontWeight: 600, fontSize: 12},
@@ -527,7 +588,7 @@ export function WorkflowBuilder({workflowId, steps, onUpdate}: WorkflowBuilderPr
id: `${step.id}-add-no-edge`, id: `${step.id}-add-no-edge`,
source: step.id, source: step.id,
target: `${step.id}-add-no`, target: `${step.id}-add-no`,
type: 'smoothstep', type: 'straight',
animated: false, animated: false,
label: 'No', label: 'No',
labelStyle: {fill: '#dc2626', fontWeight: 600, fontSize: 12}, labelStyle: {fill: '#dc2626', fontWeight: 600, fontSize: 12},
@@ -544,7 +605,7 @@ export function WorkflowBuilder({workflowId, steps, onUpdate}: WorkflowBuilderPr
id: `${step.id}-add-edge`, id: `${step.id}-add-edge`,
source: step.id, source: step.id,
target: `${step.id}-add`, target: `${step.id}-add`,
type: 'smoothstep', type: 'straight',
animated: false, animated: false,
style: {stroke: '#94a3b8', strokeWidth: 2.5, strokeDasharray: '5,5'}, style: {stroke: '#94a3b8', strokeWidth: 2.5, strokeDasharray: '5,5'},
markerEnd: {type: MarkerType.ArrowClosed, color: '#94a3b8', width: 22, height: 22}, markerEnd: {type: MarkerType.ArrowClosed, color: '#94a3b8', width: 22, height: 22},
@@ -565,6 +626,56 @@ export function WorkflowBuilder({workflowId, steps, onUpdate}: WorkflowBuilderPr
const [nodes, setNodes, onNodesChange] = useNodesState(layoutedNodes); const [nodes, setNodes, onNodesChange] = useNodesState(layoutedNodes);
const [edges, setEdges, onEdgesChange] = useEdgesState(layoutedEdges); const [edges, setEdges, onEdgesChange] = useEdgesState(layoutedEdges);
// Custom nodes change handler that updates "+" node positions when parent nodes move
const handleNodesChange = useCallback(
(changes: any[]) => {
onNodesChange(changes);
// Check if any position changes occurred
const positionChanges = changes.filter(change => change.type === 'position' && change.dragging);
if (positionChanges.length > 0) {
setNodes(currentNodes => {
const updatedNodes = [...currentNodes];
const nodeWidth = 280;
positionChanges.forEach((change: any) => {
const movedNode = updatedNodes.find(n => n.id === change.id);
if (movedNode && movedNode.type === 'custom' && change.position) {
// Find all "+" nodes connected to this parent node
const connectedAddNodes = updatedNodes.filter(node => {
if (node.type !== 'addStep') return false;
// Check if this add node is connected to the moved node
return (
node.id === `${movedNode.id}-add` ||
node.id === `${movedNode.id}-add-yes` ||
node.id === `${movedNode.id}-add-no`
);
});
// Update positions of connected "+" nodes to stay centered below parent
connectedAddNodes.forEach(addNode => {
const addNodeIndex = updatedNodes.findIndex(n => n.id === addNode.id);
if (addNodeIndex !== -1 && updatedNodes[addNodeIndex]) {
const existingNode = updatedNodes[addNodeIndex];
updatedNodes[addNodeIndex] = {
...existingNode,
position: {
x: change.position.x + nodeWidth / 2 - 32, // Center below parent
y: existingNode.position.y,
},
};
}
});
}
});
return updatedNodes;
});
}
},
[onNodesChange, setNodes],
);
// Update nodes/edges when layout changes // Update nodes/edges when layout changes
useEffect(() => { useEffect(() => {
setNodes(layoutedNodes); setNodes(layoutedNodes);
@@ -727,7 +838,7 @@ export function WorkflowBuilder({workflowId, steps, onUpdate}: WorkflowBuilderPr
<ReactFlow <ReactFlow
nodes={nodes} nodes={nodes}
edges={edges} edges={edges}
onNodesChange={onNodesChange} onNodesChange={handleNodesChange}
onEdgesChange={onEdgesChange} onEdgesChange={onEdgesChange}
nodeTypes={nodeTypes} nodeTypes={nodeTypes}
fitView fitView
+3
View File
@@ -19,6 +19,9 @@ export interface ConfigResponse {
ports: {secure: number; submission: number} | null; ports: {secure: number; submission: number} | null;
}; };
}; };
aws: {
sesRegion: string;
};
} }
/** /**
+3
View File
@@ -5,6 +5,7 @@ import React, {useEffect} from 'react';
import {Toaster} from 'sonner'; import {Toaster} from 'sonner';
import {SWRConfig} from 'swr'; import {SWRConfig} from 'swr';
import {DefaultSeo} from 'next-seo'; import {DefaultSeo} from 'next-seo';
import {NuqsAdapter} from 'nuqs/adapters/next/pages';
import {Loader} from '@plunk/ui'; import {Loader} from '@plunk/ui';
import {ActiveProjectProvider} from '../lib/contexts/ActiveProjectProvider'; import {ActiveProjectProvider} from '../lib/contexts/ActiveProjectProvider';
import {useProjects} from '../lib/hooks/useProject'; import {useProjects} from '../lib/hooks/useProject';
@@ -103,6 +104,7 @@ function ProjectGuard({children}: {children: React.ReactNode}) {
*/ */
export default function WithProviders(props: AppProps) { export default function WithProviders(props: AppProps) {
return ( return (
<NuqsAdapter>
<SWRConfig <SWRConfig
value={{ value={{
fetcher: (url: string) => network.fetch('GET', url), fetcher: (url: string) => network.fetch('GET', url),
@@ -114,6 +116,7 @@ export default function WithProviders(props: AppProps) {
<Root {...props} /> <Root {...props} />
</ActiveProjectProvider> </ActiveProjectProvider>
</SWRConfig> </SWRConfig>
</NuqsAdapter>
); );
} }
+8 -4
View File
@@ -14,7 +14,7 @@ import {DashboardLayout} from '../../components/DashboardLayout';
import {ActivityFeed} from '../../components/ActivityFeed'; import {ActivityFeed} from '../../components/ActivityFeed';
import {Eye, MousePointerClick, Send, Zap} from 'lucide-react'; import {Eye, MousePointerClick, Send, Zap} from 'lucide-react';
import {NextSeo} from 'next-seo'; import {NextSeo} from 'next-seo';
import {useState} from 'react'; import {useQueryState, parseAsString} from 'nuqs';
import useSWR from 'swr'; import useSWR from 'swr';
interface ActivityStats { interface ActivityStats {
@@ -28,8 +28,8 @@ interface ActivityStats {
} }
export default function ActivityPage() { export default function ActivityPage() {
const [typeFilter, setTypeFilter] = useState<string>('ALL'); const [typeFilter, setTypeFilter] = useQueryState('type', parseAsString.withDefault('ALL'));
const [dateRange, setDateRange] = useState<string>('30'); const [dateRange, setDateRange] = useQueryState('days', parseAsString.withDefault('30'));
// Fetch activity stats // Fetch activity stats
const {data: stats} = useSWR<ActivityStats>(`/activity/stats`, { const {data: stats} = useSWR<ActivityStats>(`/activity/stats`, {
@@ -119,12 +119,16 @@ export default function ActivityPage() {
<SelectContent> <SelectContent>
<SelectItem value="ALL">All Activity Types</SelectItem> <SelectItem value="ALL">All Activity Types</SelectItem>
<SelectItem value="event.triggered">Events</SelectItem> <SelectItem value="event.triggered">Events</SelectItem>
<SelectItem value="email.sent,email.delivered,email.opened,email.clicked,email.bounced"> <SelectItem value="email.sent,email.delivered,email.received,email.opened,email.clicked,email.bounced,email.complaint">
Emails Emails
</SelectItem> </SelectItem>
<SelectItem value="email.sent">Emails Sent</SelectItem> <SelectItem value="email.sent">Emails Sent</SelectItem>
<SelectItem value="email.delivered">Emails Delivered</SelectItem>
<SelectItem value="email.received">Emails Received</SelectItem>
<SelectItem value="email.opened">Emails Opened</SelectItem> <SelectItem value="email.opened">Emails Opened</SelectItem>
<SelectItem value="email.clicked">Emails Clicked</SelectItem> <SelectItem value="email.clicked">Emails Clicked</SelectItem>
<SelectItem value="email.bounced">Emails Bounced</SelectItem>
<SelectItem value="email.complaint">Email Complaints</SelectItem>
<SelectItem value="workflow.started,workflow.completed">Workflows</SelectItem> <SelectItem value="workflow.started,workflow.completed">Workflows</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
+15
View File
@@ -0,0 +1,15 @@
import {WIKI_URI} from '../lib/constants';
import type {GetServerSideProps} from 'next';
export default function Docs() {
return null;
}
export const getServerSideProps: GetServerSideProps = async () => {
return {
redirect: {
destination: WIKI_URI,
permanent: false,
},
};
};
+125 -12
View File
@@ -13,7 +13,7 @@ import type {Contact, Segment} from '@plunk/db';
import type {PaginatedResponse} from '@plunk/types'; import type {PaginatedResponse} from '@plunk/types';
import {DashboardLayout} from '../../components/DashboardLayout'; import {DashboardLayout} from '../../components/DashboardLayout';
import {network} from '../../lib/network'; import {network} from '../../lib/network';
import {ArrowLeft, Database, Filter, MailCheck, MailX, RefreshCw, Save, Trash2, Users} from 'lucide-react'; import {ArrowLeft, Database, Filter, MailCheck, MailX, RefreshCw, Save, Trash2, UserMinus, Users} from 'lucide-react';
import Link from 'next/link'; import Link from 'next/link';
import {useRouter} from 'next/router'; import {useRouter} from 'next/router';
import {useEffect, useState} from 'react'; import {useEffect, useState} from 'react';
@@ -22,8 +22,12 @@ import useSWR from 'swr';
import type {FilterCondition} from '@plunk/types'; import type {FilterCondition} from '@plunk/types';
import {SegmentSchemas} from '@plunk/shared'; import {SegmentSchemas} from '@plunk/shared';
import {SegmentFilterBuilder} from '../../components/SegmentFilterBuilder'; import {SegmentFilterBuilder} from '../../components/SegmentFilterBuilder';
import {ContactPicker} from '../../components/ContactPicker';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
type SegmentType = 'DYNAMIC' | 'STATIC';
type SegmentWithType = Segment & {type: SegmentType};
// Count total filters in a condition (recursive) // Count total filters in a condition (recursive)
function countFilters(condition: FilterCondition): number { function countFilters(condition: FilterCondition): number {
let count = 0; let count = 0;
@@ -40,11 +44,13 @@ export default function SegmentDetailPage() {
const router = useRouter(); const router = useRouter();
const {id} = router.query; const {id} = router.query;
const {data: segment, mutate, isLoading} = useSWR<Segment>(id ? `/segments/${id}` : null); const {data: segment, mutate, isLoading} = useSWR<SegmentWithType>(id ? `/segments/${id}` : null);
const [contactsPage, setContactsPage] = useState(1); const [contactsPage, setContactsPage] = useState(1);
const {data: contactsData, isLoading: isLoadingContacts} = useSWR<PaginatedResponse<Contact>>( const {
id ? `/segments/${id}/contacts?page=${contactsPage}&pageSize=10` : null, data: contactsData,
); isLoading: isLoadingContacts,
mutate: mutateContacts,
} = useSWR<PaginatedResponse<Contact>>(id ? `/segments/${id}/contacts?page=${contactsPage}&pageSize=10` : null);
const [name, setName] = useState(''); const [name, setName] = useState('');
const [description, setDescription] = useState(''); const [description, setDescription] = useState('');
@@ -57,6 +63,11 @@ export default function SegmentDetailPage() {
const [isComputing, setIsComputing] = useState(false); const [isComputing, setIsComputing] = useState(false);
const [showDeleteDialog, setShowDeleteDialog] = useState(false); const [showDeleteDialog, setShowDeleteDialog] = useState(false);
// Static segment member management
const [pickedEmails, setPickedEmails] = useState<string[]>([]);
const [isAddingMembers, setIsAddingMembers] = useState(false);
const [removingEmail, setRemovingEmail] = useState<string | null>(null);
useEffect(() => { useEffect(() => {
if (segment) { if (segment) {
setName(segment.name); setName(segment.name);
@@ -79,7 +90,7 @@ export default function SegmentDetailPage() {
await network.fetch<Segment, typeof SegmentSchemas.update>('PATCH', `/segments/${id}`, { await network.fetch<Segment, typeof SegmentSchemas.update>('PATCH', `/segments/${id}`, {
name, name,
description: description || undefined, description: description || undefined,
condition, ...(segment?.type !== 'STATIC' && {condition}),
trackMembership, trackMembership,
}); });
toast.success('Segment updated successfully'); toast.success('Segment updated successfully');
@@ -112,6 +123,47 @@ export default function SegmentDetailPage() {
} }
}; };
const handleAddMembers = async () => {
if (pickedEmails.length === 0) {
toast.error('Select at least one contact');
return;
}
setIsAddingMembers(true);
try {
const result = await network.fetch<{added: number; notFound: string[]}, typeof SegmentSchemas.members>(
'POST',
`/segments/${id}/members`,
{emails: pickedEmails},
);
toast.success(`Added ${result.added} contact${result.added !== 1 ? 's' : ''} to segment`);
setPickedEmails([]);
void mutate();
void mutateContacts();
} catch (error) {
toast.error(error instanceof Error ? error.message : 'Failed to add contacts');
} finally {
setIsAddingMembers(false);
}
};
const handleRemoveMember = async (email: string) => {
setRemovingEmail(email);
try {
await network.fetch<{removed: number}, typeof SegmentSchemas.members>('DELETE', `/segments/${id}/members`, {
emails: [email],
});
toast.success(`Removed ${email} from segment`);
void mutate();
void mutateContacts();
} catch (error) {
toast.error(error instanceof Error ? error.message : 'Failed to remove contact');
} finally {
setRemovingEmail(null);
}
};
const handleDelete = async () => { const handleDelete = async () => {
try { try {
await network.fetch('DELETE', `/segments/${id}`); await network.fetch('DELETE', `/segments/${id}`);
@@ -166,6 +218,8 @@ export default function SegmentDetailPage() {
); );
} }
const isStatic = segment.type === 'STATIC';
return ( return (
<DashboardLayout> <DashboardLayout>
<div className="space-y-6"> <div className="space-y-6">
@@ -178,8 +232,17 @@ export default function SegmentDetailPage() {
</Button> </Button>
</Link> </Link>
<div> <div>
<div className="flex items-center gap-2">
<h1 className="text-3xl font-bold text-neutral-900">{segment.name}</h1> <h1 className="text-3xl font-bold text-neutral-900">{segment.name}</h1>
<p className="text-neutral-500 mt-1">{segment.description}</p> <span
className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
isStatic ? 'bg-purple-100 text-purple-700' : 'bg-blue-100 text-blue-700'
}`}
>
{isStatic ? 'Static' : 'Dynamic'}
</span>
</div>
{segment.description && <p className="text-neutral-500 mt-1">{segment.description}</p>}
</div> </div>
</div> </div>
<Button variant="destructive" onClick={() => setShowDeleteDialog(true)}> <Button variant="destructive" onClick={() => setShowDeleteDialog(true)}>
@@ -244,12 +307,14 @@ export default function SegmentDetailPage() {
</CardContent> </CardContent>
</Card> </Card>
{/* Filter Builder */} {/* Filter Builder (DYNAMIC only) */}
{!isStatic && (
<Card> <Card>
<CardContent className="pt-6"> <CardContent className="pt-6">
<SegmentFilterBuilder condition={condition} onChange={setCondition} /> <SegmentFilterBuilder condition={condition} onChange={setCondition} />
</CardContent> </CardContent>
</Card> </Card>
)}
{/* Actions */} {/* Actions */}
<div className="flex items-center justify-end"> <div className="flex items-center justify-end">
@@ -260,15 +325,44 @@ export default function SegmentDetailPage() {
</div> </div>
</form> </form>
{/* Static member management */}
{isStatic && (
<Card>
<CardHeader>
<CardTitle>Add Members</CardTitle>
<CardDescription>Search and select contacts to add to this segment</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<ContactPicker
selected={pickedEmails}
onChange={setPickedEmails}
existing={contactsData?.data.map(c => c.email) ?? []}
placeholder="Search contacts to add..."
/>
<Button
type="button"
onClick={handleAddMembers}
disabled={isAddingMembers || pickedEmails.length === 0}
>
{isAddingMembers
? 'Adding...'
: `Add ${pickedEmails.length > 0 ? pickedEmails.length : ''} Contact${pickedEmails.length !== 1 ? 's' : ''}`}
</Button>
</CardContent>
</Card>
)}
{/* Contacts */} {/* Contacts */}
<Card> <Card>
<CardHeader> <CardHeader>
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div> <div>
<CardTitle>Matching Contacts</CardTitle> <CardTitle>{isStatic ? 'Members' : 'Matching Contacts'}</CardTitle>
<CardDescription>Contacts that match this segment&apos;s filters</CardDescription> <CardDescription>
{isStatic ? 'Contacts in this static segment' : "Contacts that match this segment's filters"}
</CardDescription>
</div> </div>
{trackMembership && ( {!isStatic && trackMembership && (
<Button variant="outline" size="sm" onClick={handleComputeMembership} disabled={isComputing}> <Button variant="outline" size="sm" onClick={handleComputeMembership} disabled={isComputing}>
<RefreshCw className={`h-4 w-4 ${isComputing ? 'animate-spin' : ''}`} /> <RefreshCw className={`h-4 w-4 ${isComputing ? 'animate-spin' : ''}`} />
{isComputing ? 'Computing...' : 'Recompute'} {isComputing ? 'Computing...' : 'Recompute'}
@@ -284,7 +378,9 @@ export default function SegmentDetailPage() {
) : contactsData?.data.length === 0 ? ( ) : contactsData?.data.length === 0 ? (
<div className="text-center py-8"> <div className="text-center py-8">
<Users className="h-12 w-12 text-neutral-400 mx-auto mb-4" /> <Users className="h-12 w-12 text-neutral-400 mx-auto mb-4" />
<p className="text-neutral-500">No contacts match this segment</p> <p className="text-neutral-500">
{isStatic ? 'No members in this segment yet' : 'No contacts match this segment'}
</p>
</div> </div>
) : ( ) : (
<> <>
@@ -299,11 +395,24 @@ export default function SegmentDetailPage() {
)} )}
<span className="text-sm font-medium">{contact.email}</span> <span className="text-sm font-medium">{contact.email}</span>
</div> </div>
<div className="flex items-center gap-2">
<Link href={`/contacts/${contact.id}`}> <Link href={`/contacts/${contact.id}`}>
<Button variant="ghost" size="sm"> <Button variant="ghost" size="sm">
View View
</Button> </Button>
</Link> </Link>
{isStatic && (
<Button
variant="ghost"
size="sm"
onClick={() => handleRemoveMember(contact.email)}
disabled={removingEmail === contact.email}
className="text-red-600 hover:text-red-700 hover:bg-red-50"
>
<UserMinus className="h-4 w-4" />
</Button>
)}
</div>
</div> </div>
))} ))}
</div> </div>
@@ -355,6 +464,8 @@ export default function SegmentDetailPage() {
<span className="text-2xl font-bold text-neutral-900">{segment.memberCount}</span> <span className="text-2xl font-bold text-neutral-900">{segment.memberCount}</span>
</div> </div>
{!isStatic && (
<>
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Filter className="h-4 w-4 text-neutral-500" /> <Filter className="h-4 w-4 text-neutral-500" />
@@ -373,6 +484,8 @@ export default function SegmentDetailPage() {
{(segment.condition as unknown as FilterCondition)?.groups?.length || 0} {(segment.condition as unknown as FilterCondition)?.groups?.length || 0}
</span> </span>
</div> </div>
</>
)}
</CardContent> </CardContent>
</Card> </Card>
+14 -1
View File
@@ -146,7 +146,18 @@ export default function SegmentsPage() {
<CardHeader> <CardHeader>
<div className="flex items-start justify-between"> <div className="flex items-start justify-between">
<div className="flex-1"> <div className="flex-1">
<div className="flex items-center gap-2">
<CardTitle className="text-lg">{segment.name}</CardTitle> <CardTitle className="text-lg">{segment.name}</CardTitle>
<span
className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${
(segment as unknown as {type: string}).type === 'STATIC'
? 'bg-purple-100 text-purple-700'
: 'bg-blue-100 text-blue-700'
}`}
>
{(segment as unknown as {type: string}).type === 'STATIC' ? 'Static' : 'Dynamic'}
</span>
</div>
{segment.description && ( {segment.description && (
<CardDescription className="mt-1">{segment.description}</CardDescription> <CardDescription className="mt-1">{segment.description}</CardDescription>
)} )}
@@ -170,7 +181,9 @@ export default function SegmentsPage() {
<span className="text-sm text-neutral-600">Filters</span> <span className="text-sm text-neutral-600">Filters</span>
</div> </div>
<span className="text-sm font-medium text-neutral-900"> <span className="text-sm font-medium text-neutral-900">
{countFiltersInCondition(segment.condition)} {(segment as unknown as {type: string}).type === 'STATIC'
? '—'
: countFiltersInCondition(segment.condition)}
</span> </span>
</div> </div>
+77 -4
View File
@@ -2,6 +2,7 @@ import {Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input
import {NextSeo} from 'next-seo'; import {NextSeo} from 'next-seo';
import {DashboardLayout} from '../../components/DashboardLayout'; import {DashboardLayout} from '../../components/DashboardLayout';
import {SegmentFilterBuilder} from '../../components/SegmentFilterBuilder'; import {SegmentFilterBuilder} from '../../components/SegmentFilterBuilder';
import {ContactPicker} from '../../components/ContactPicker';
import {network} from '../../lib/network'; import {network} from '../../lib/network';
import {ArrowLeft, Save} from 'lucide-react'; import {ArrowLeft, Save} from 'lucide-react';
import Link from 'next/link'; import Link from 'next/link';
@@ -12,10 +13,13 @@ import type {FilterCondition} from '@plunk/types';
import type {Segment} from '@plunk/db'; import type {Segment} from '@plunk/db';
import {SegmentSchemas} from '@plunk/shared'; import {SegmentSchemas} from '@plunk/shared';
type SegmentType = 'DYNAMIC' | 'STATIC';
export default function NewSegmentPage() { export default function NewSegmentPage() {
const router = useRouter(); const router = useRouter();
const [name, setName] = useState(''); const [name, setName] = useState('');
const [description, setDescription] = useState(''); const [description, setDescription] = useState('');
const [segmentType, setSegmentType] = useState<SegmentType>('DYNAMIC');
const [trackMembership, setTrackMembership] = useState(false); const [trackMembership, setTrackMembership] = useState(false);
const [condition, setCondition] = useState<FilterCondition>({ const [condition, setCondition] = useState<FilterCondition>({
logic: 'AND', logic: 'AND',
@@ -25,6 +29,7 @@ export default function NewSegmentPage() {
}, },
], ],
}); });
const [selectedContacts, setSelectedContacts] = useState<string[]>([]);
const [isSubmitting, setIsSubmitting] = useState(false); const [isSubmitting, setIsSubmitting] = useState(false);
const handleSubmit = async (e: React.FormEvent) => { const handleSubmit = async (e: React.FormEvent) => {
@@ -32,13 +37,33 @@ export default function NewSegmentPage() {
setIsSubmitting(true); setIsSubmitting(true);
try { try {
await network.fetch<Segment, typeof SegmentSchemas.create>('POST', '/segments', { const segment = await network.fetch<Segment, typeof SegmentSchemas.create>('POST', '/segments', {
name, name,
description: description || undefined, description: description || undefined,
condition, type: segmentType,
condition: segmentType === 'DYNAMIC' ? condition : undefined,
trackMembership, trackMembership,
}); });
// For static segments with pre-selected contacts, add them now
if (segmentType === 'STATIC' && selectedContacts.length > 0) {
try {
const result = await network.fetch<{added: number; notFound: string[]}, typeof SegmentSchemas.members>(
'POST',
`/segments/${segment.id}/members`,
{emails: selectedContacts},
);
toast.success(
`Segment created with ${result.added} contact${result.added !== 1 ? 's' : ''}`,
);
} catch {
// Segment was created; just warn about members
toast.warning('Segment created, but some contacts could not be added');
}
} else {
toast.success('Segment created successfully'); toast.success('Segment created successfully');
}
void router.push('/segments'); void router.push('/segments');
} catch (error) { } catch (error) {
toast.error(error instanceof Error ? error.message : 'Failed to create segment'); toast.error(error instanceof Error ? error.message : 'Failed to create segment');
@@ -61,10 +86,40 @@ export default function NewSegmentPage() {
</Link> </Link>
<div> <div>
<h1 className="text-3xl font-bold text-neutral-900">Create Segment</h1> <h1 className="text-3xl font-bold text-neutral-900">Create Segment</h1>
<p className="text-neutral-500 mt-1">Build complex audience filters with AND/OR logic</p> <p className="text-neutral-500 mt-1">
{segmentType === 'DYNAMIC'
? 'Build complex audience filters with AND/OR logic'
: 'Manually curate a list of contacts'}
</p>
</div> </div>
</div> </div>
{/* Type Toggle */}
<div className="flex gap-2 p-1 bg-neutral-100 rounded-lg w-fit">
<button
type="button"
onClick={() => setSegmentType('DYNAMIC')}
className={`px-4 py-2 text-sm font-medium rounded-md transition-colors ${
segmentType === 'DYNAMIC'
? 'bg-white text-neutral-900 shadow-sm'
: 'text-neutral-600 hover:text-neutral-900'
}`}
>
Dynamic
</button>
<button
type="button"
onClick={() => setSegmentType('STATIC')}
className={`px-4 py-2 text-sm font-medium rounded-md transition-colors ${
segmentType === 'STATIC'
? 'bg-white text-neutral-900 shadow-sm'
: 'text-neutral-600 hover:text-neutral-900'
}`}
>
Static
</button>
</div>
<form onSubmit={handleSubmit} className="space-y-6"> <form onSubmit={handleSubmit} className="space-y-6">
{/* Basic Info */} {/* Basic Info */}
<Card> <Card>
@@ -118,12 +173,30 @@ export default function NewSegmentPage() {
</CardContent> </CardContent>
</Card> </Card>
{/* Filter Builder */} {/* Filter Builder or Contact Picker */}
{segmentType === 'DYNAMIC' ? (
<Card> <Card>
<CardContent className="pt-6"> <CardContent className="pt-6">
<SegmentFilterBuilder condition={condition} onChange={setCondition} /> <SegmentFilterBuilder condition={condition} onChange={setCondition} />
</CardContent> </CardContent>
</Card> </Card>
) : (
<Card>
<CardHeader>
<CardTitle>Initial Members</CardTitle>
<CardDescription>
Optionally add contacts now you can always add or remove members later
</CardDescription>
</CardHeader>
<CardContent>
<ContactPicker
selected={selectedContacts}
onChange={setSelectedContacts}
placeholder="Search and select contacts..."
/>
</CardContent>
</Card>
)}
{/* Actions */} {/* Actions */}
<div className="flex items-center justify-end gap-2"> <div className="flex items-center justify-end gap-2">
+1 -1
View File
@@ -118,7 +118,7 @@ export default function TemplateEditorPage() {
} }
}; };
if (!template) { if (!template || Object.keys(editedTemplate).length === 0) {
return ( return (
<DashboardLayout> <DashboardLayout>
<div className="flex items-center justify-center min-h-[400px]"> <div className="flex items-center justify-center min-h-[400px]">
File diff suppressed because it is too large Load Diff
@@ -244,11 +244,13 @@ For a complete list of error codes and troubleshooting guidance, see the [Error
### Segments ### Segments
**GET /segments** — List all segments **GET /segments** — List all segments
**POST /segments** — Create new segment **POST /segments** — Create new segment (Dynamic or Static)
**GET /segments/:id** — Get segment details **GET /segments/:id** — Get segment details
**PATCH /segments/:id** — Update segment **PATCH /segments/:id** — Update segment
**DELETE /segments/:id** — Delete segment **DELETE /segments/:id** — Delete segment
**GET /segments/:id/contacts** — List segment members **GET /segments/:id/contacts** — List segment members
**POST /segments/:id/members** — Add contacts to a static segment (by email)
**DELETE /segments/:id/members** — Remove contacts from a static segment (by email)
### Workflows ### Workflows
@@ -44,3 +44,31 @@ Certain keys are reserved by the system and automatically set by Plunk:
| Key | Description | | Key | Description |
|-----|-------------| |-----|-------------|
| locale | The contact's preferred locale in ISO 639 (e.g. 'en', 'fr', 'es'). Specifying the locale field on a contact will override the project-wide locale for contact-facing pages and email footers | | locale | The contact's preferred locale in ISO 639 (e.g. 'en', 'fr', 'es'). Specifying the locale field on a contact will override the project-wide locale for contact-facing pages and email footers |
## Subscription State
Every contact has a `subscribed` field that determines which types of emails they will receive. A newly created contact is subscribed by default.
### How contacts become unsubscribed
A contact can become unsubscribed in several ways:
- **Manually** through the dashboard or via the API
- **Self-service** by clicking the unsubscribe link in an email
- **Automatically** when an email to the contact bounces or results in a complaint
### Emails by subscription state
The subscription state controls whether a contact receives marketing emails. Transactional emails are always delivered regardless of subscription state.
| Email type | Subscribed | Unsubscribed |
|---|---|---|
| **Transactional** (via [/v1/send](/api-reference/public-api/sendTransactionalEmail)) | Delivered | Delivered |
| **Campaigns** | Delivered | Not delivered |
| **Automations** (transactional template) | Delivered | Delivered |
| **Automations** (marketing template) | Delivered | Not delivered |
<Callout
title="Transactional emails and marketing templates"
variant="warn">
Even when using the transactional API endpoint (`/v1/send`), you cannot send a marketing template to an unsubscribed contact. Use a transactional template instead if the email must reach unsubscribed contacts.
</Callout>
+44 -8
View File
@@ -1,20 +1,56 @@
--- ---
title: Segments title: Segments
description: Group and target your contacts with dynamic segments description: Group and target your contacts with dynamic or static segments
icon: Layers icon: Layers
--- ---
Segments in Plunk allow you to create dynamic groups of contacts based on [contact data](/concepts/contacts#contact-data) and events. Segments let you create named groups of contacts that can be targeted in campaigns and used as triggers in workflows. There are two types: **Dynamic** and **Static**.
## Creating segments ## Dynamic segments
Segments can be created through the Plunk dashboard. When creating a segment, you can define multiple conditions that contacts must meet to be included in the segment. Plunk will automatically update the segment membership as contact data and events change.
### Track Membership Changes Dynamic segments evaluate a set of filter conditions against your contacts in real time. Membership is kept up to date automatically as contact data and events change — no manual work required.
Plunk will automatically add and remove contacts from segments as their data and events change. When toggling on `Track membership changes`, Plunk will send an event to your webhook each time a contact is added or removed from the segment.
These events will have the following name `segment.trial-users.entry` or `segment.trial-users.exit`, where `trial-users` is the segment's name. You can filter on:
- Contact fields (`email`, `subscribed`, custom data fields like `data.plan`)
- Contact dates (`createdAt`, `updatedAt`)
- Custom events (`event.signed_up`, `event.purchased`, …)
- Email activity (`email.opened`, `email.clicked`, `email.bounced`, …)
Conditions can be combined with `AND`/`OR` logic and nested into groups for complex rules.
## Static segments
Static segments are manually curated lists. Membership does not change automatically — you decide exactly who is in the segment. This is useful for things like beta testers, event attendees, or any group imported from an external source.
## Creating a segment
Go to **Segments** in the dashboard and click **Create Segment**. Use the toggle at the top to choose **Dynamic** or **Static**.
**For dynamic segments**, use the filter builder to define your conditions. Plunk will show you a live count of matching contacts.
**For static segments**, you can optionally add initial members right away using the contact search. Start typing an email address and select contacts from the list — selected contacts appear as chips you can remove before saving.
## Managing static segment members
Open a static segment and use the **Add Members** search to find and select contacts. The search looks up contacts already in your project, so you can't accidentally add someone who doesn't exist. Contacts already in the segment are greyed out.
To remove a member, click the remove button on their row in the members list.
## Track membership changes
Both segment types support **Track membership changes**. When enabled, Plunk fires a webhook event each time a contact enters or leaves the segment:
- `segment.trial-users.entry` — contact joined the segment
- `segment.trial-users.exit` — contact left the segment
Where `trial-users` is derived from the segment name. See [Webhooks](/guides/webhooks) for the full event payload.
## Using segments ## Using segments
Segment can be used in various parts of Plunk, including:
Segments can be used in:
- Targeting contacts in [email campaigns](/concepts/campaigns) - Targeting contacts in [email campaigns](/concepts/campaigns)
- Triggering workflows in [marketing automation](/concepts/workflows) - Triggering workflows in [marketing automation](/concepts/workflows)
## Managing members via API
If you need to manage static segment membership programmatically, use the `POST /segments/:id/members` and `DELETE /segments/:id/members` endpoints. See the [API reference](/api-reference/overview#segments) for details.
+1 -1
View File
@@ -1,3 +1,3 @@
{ {
"pages": ["list-hygiene", "verifying-domains", "tracking", "api-keys", "localization"] "pages": ["list-hygiene", "verifying-domains", "receiving-emails", "tracking", "api-keys", "localization", "webhooks"]
} }
@@ -0,0 +1,142 @@
---
title: Receiving emails
description: Receive incoming emails at your verified domain and trigger automated workflows
icon: Inbox
---
Plunk can receive emails sent to your verified domain and turn them into `email.received` events. This allows you to build automated workflows that respond to inbound emails, such as support ticket systems, auto-responders, or email-based integrations.
## How it works
When someone sends an email to your verified domain (e.g., `[email protected]` or `[email protected]`), Plunk will:
1. Receive the email through AWS SES
2. Automatically create or update a contact for the sender
3. Trigger an `email.received` event that can start workflows
4. Make the email metadata available to your workflow steps
The sender is automatically added to your contacts as a subscribed contact, allowing you to respond using Plunk's email sending capabilities.
## Setting up inbound email
<div className='fd-steps [&_h3]:fd-step'>
### Verify your domain
Before you can receive emails, your domain must be verified in Plunk. Follow the [verifying domains](/guides/verifying-domains) guide to set up the required DKIM, SPF, and MX records for sending.
### Add the inbound MX record
In your project settings, navigate to the **Domains** tab and expand your verified domain. You'll see an optional "Inbound Email" section with an MX record configuration:
- **Type**: MX
- **Name**: `yourdomain.com` (your root domain)
- **Value**: `10 inbound-smtp.eu-north-1.amazonaws.com`
Add this MX record to your domain's DNS settings. The priority value `10` ensures that inbound emails are routed to AWS SES for processing.
<Callout title="Multiple MX records" variant="warning">
If you're already using MX records for another email service (like Google Workspace or Microsoft 365), adding this MX
record may conflict. You can only have one primary email receiver per domain. Consider using a subdomain (e.g.,
`mail.yourdomain.com`) if you need to maintain both services.
</Callout>
### Wait for DNS propagation
DNS changes can take anywhere from a few minutes to 48 hours to fully propagate. You can verify the MX record is set correctly using:
```bash
dig MX yourdomain.com
```
You should see the AWS SES inbound endpoint in the response.
</div>
## Creating workflows with email.received
Once your MX record is configured, you can create workflows that respond to incoming emails.
### Event trigger
Create a new workflow and use `email.received` as the trigger event. This workflow will run every time an email is received at your domain.
### Available event data
The `email.received` event includes the following data that you can use in your workflow steps:
| Field | Type | Description |
| ---------------------- | -------- | ---------------------------------------------- |
| `messageId` | string | Unique identifier for the received message |
| `from` | string | Email address of the sender |
| `fromHeader` | string | Full "From" header including display name |
| `to` | string | Primary recipient email address |
| `subject` | string | Email subject line |
| `timestamp` | string | ISO 8601 timestamp when the email was received |
| `recipients` | string[] | All recipient email addresses |
| `hasContent` | boolean | Whether the email body was captured |
| `spamVerdict` | string | Spam check result (e.g., "PASS", "FAIL") |
| `virusVerdict` | string | Virus scan result (e.g., "PASS", "FAIL") |
| `spfVerdict` | string | SPF authentication result |
| `dkimVerdict` | string | DKIM authentication result |
| `dmarcVerdict` | string | DMARC authentication result |
| `processingTimeMillis` | number | Time taken to process the email |
You can access these fields in your workflow using variable syntax, for example: `{{event.subject}}` or `{{event.from}}`.
## Multi-project domains
If you have verified the same domain in multiple projects, incoming emails will be processed for **all projects** that have the domain verified. Each project will:
- Create/update the sender as a contact in that project
- Trigger the `email.received` event in that project
- Run any workflows configured for that event
This allows you to segment inbound email handling across different projects if needed.
## Limitations
<Callout title="Email body content" variant="warning">
Currently, the email body content is not stored or made available in the event data. Only metadata (sender, subject,
recipients, timestamps, and security verdicts) is captured. The `hasContent` field indicates whether body content was
present, but the content itself is not accessible in workflows.
</Callout>
- **Catch-all addresses**: Plunk receives emails sent to any address at your verified domain (e.g., `[email protected]`). You can use workflow conditions to route emails based on the `to` field.
- **Attachments**: Email attachments are not currently captured or stored.
- **Email size**: AWS SES has a maximum message size limit of 40 MB for inbound emails.
## Security considerations
Plunk captures several security verdicts for each incoming email:
- **SPF (Sender Policy Framework)**: Verifies the sender's mail server is authorized
- **DKIM (DomainKeys Identified Mail)**: Validates the email hasn't been tampered with
- **DMARC (Domain-based Message Authentication)**: Combines SPF and DKIM for additional validation
- **Spam verdict**: AWS SES's spam detection result
- **Virus verdict**: AWS SES's virus scanning result
You can use these verdicts in workflow conditions to automatically filter or quarantine suspicious emails before processing them.
## Troubleshooting
### Emails not being received
1. **Check DNS propagation**: Verify the MX record is correctly set using `dig MX yourdomain.com`
2. **Verify domain**: Ensure your domain is fully verified in Plunk (all DKIM, SPF, and MX records for sending)
3. **Check workflow**: Create a simple test workflow with just an `email.received` trigger and a webhook to verify events are being generated
4. **Check sender**: Try sending from a different email provider as some may cache DNS records
### Duplicate events
If you have the same domain verified in multiple projects, you will receive duplicate `email.received` events (one per project). This is expected behavior. Use project-specific workflows to handle this.
### Security verdicts failing
If incoming emails consistently show failing security verdicts:
- **SPF failures**: The sender's domain may not have SPF configured correctly
- **DKIM failures**: The sender's domain may not have DKIM configured, or the email was forwarded/modified in transit
- **DMARC failures**: The sender fails both SPF and DKIM checks
These are issues with the sender's configuration, not your Plunk setup. You can choose to process these emails anyway or filter them using workflow conditions.
@@ -9,9 +9,78 @@ Verifying your domain is a requirement to send emails through Plunk. Domain veri
## Verifying a domain ## Verifying a domain
You can verify a domain by adding it in the domain tab of the project settings. Once added, Plunk will provide you with the necessary DNS records to add to your domain's DNS settings. You can verify a domain by adding it in the domain tab of the project settings. Once added, Plunk will provide you with the necessary DNS records to add to your domain's DNS settings.
Once you have added the DNS records, it may take some time for the changes to propagate. You can check the verification status in the domain tab of the project settings. Once you have added the DNS records, it may take some time for the changes to propagate. You can check the verification status in the domain tab of the project settings.
### DNS Records ## DNS Records
- 3 CNAME records for DKIM (DomainKeys Identified Mail) to authenticate your emails.
- 1 TXT record for SPF (Sender Policy Framework) to specify which mail servers are authorized Domain verification requires adding several DNS records to your domain. Each record serves a specific purpose in email authentication and delivery.
- 1 MX record to handle bounces and feedback loops
### DKIM Records (3 CNAME records)
**DomainKeys Identified Mail (DKIM)** adds a digital signature to your emails, proving they haven't been tampered with during transit.
You'll need to add **3 CNAME records** provided by Plunk. These records contain cryptographic keys that email receivers use to verify your emails are authentic.
**Why it matters:**
- Prevents email spoofing and tampering
- Improves deliverability and inbox placement
- Required by most email providers (Gmail, Outlook, etc.)
### SPF Record (1 TXT record)
**Sender Policy Framework (SPF)** specifies which mail servers are authorized to send emails on behalf of your domain.
You'll need to add **1 TXT record** that lists the authorized sending servers.
**Why it matters:**
- Prevents unauthorized servers from sending emails using your domain
- Reduces the likelihood of your domain being used for spam
- Works together with DKIM for complete authentication
### Bounce Handling (1 MX record)
This **MX record** allows Plunk to receive bounce notifications and spam complaints from email providers.
**Why it matters:**
- Automatically tracks which contacts have bounced or complained
- Helps maintain your sender reputation
- Prevents sending to invalid email addresses
- Required for deliverability monitoring
<Callout title="Receiving inbound emails" variant="idea">
The MX record above is for sending emails (handling bounces and complaints). If you want to **receive** emails at your
domain and trigger workflows, see the [receiving emails](/guides/receiving-emails) guide for additional MX record
setup.
</Callout>
## Verification Status
After adding all DNS records, Plunk will automatically check the verification status. Verification typically completes within a few minutes but can take up to 72 hours depending on DNS propagation.
You can check the status in the Domains section of your project settings. Each record type will show as verified once detected.
## Troubleshooting
### Records not verifying
If your DNS records aren't verifying after 24 hours:
1. **Double-check the values**: Ensure you copied the exact values without extra spaces
2. **Check DNS propagation**: Use tools like `dig` or online DNS checkers to verify the records are published
3. **TTL settings**: Some DNS providers cache records. Try lowering the TTL (Time To Live) value
4. **Contact your DNS provider**: Some providers have specific requirements or interfaces for adding these record types
### Emails still going to spam
Even with a verified domain, emails may go to spam if:
- Your content triggers spam filters (excessive links, suspicious keywords)
- Your sender reputation is new or low
- Recipients have marked your emails as spam in the past
- You're sending to invalid or unengaged contacts
Follow email best practices and maintain good [list hygiene](/guides/list-hygiene) to improve deliverability.
+153
View File
@@ -0,0 +1,153 @@
---
title: Webhooks
description: Send real-time event data from Plunk to your own application using webhooks
icon: Webhook
---
Plunk can send real-time HTTP requests to your application when specific events occur, such as email bounces, spam complaints, or custom events. This is done by creating a [workflow](/concepts/workflows) that uses the **Webhook** step to forward event data to your own endpoint.
## How it works
Webhooks in Plunk are powered by the workflow system. The basic flow is:
1. An event occurs in Plunk (e.g. an email bounces, a contact subscribes, or a custom event is tracked)
2. A workflow is triggered by that event
3. The workflow executes a **Webhook** step, sending an HTTP request to your URL with relevant data
This means you can receive notifications for any event Plunk tracks, including both system events and your own custom events.
## Internal events
Plunk automatically tracks a set of internal events that you can use as workflow triggers. These events cannot be manually tracked via the API — they are generated by the system.
### Email events
| Event | Description |
| ----------------- | -------------------------------------------------------------------------------------------------------- |
| `email.sent` | An email was successfully sent |
| `email.delivery` | An email was delivered to the recipient |
| `email.open` | A contact opened an email for the first time |
| `email.click` | A contact clicked a link in an email for the first time |
| `email.bounce` | An email bounced (hard or soft bounce) |
| `email.complaint` | A contact marked an email as spam |
| `email.received` | An email was received at your verified domain (requires [inbound email setup](/guides/receiving-emails)) |
### Contact events
| Event | Description |
| ---------------------- | ------------------------------------------------------- |
| `contact.subscribed` | A contact's subscription status changed to subscribed |
| `contact.unsubscribed` | A contact's subscription status changed to unsubscribed |
### Segment events
| Event | Description |
| ---------------------- | --------------------------- |
| `segment.<name>.entry` | A contact entered a segment |
| `segment.<name>.exit` | A contact exited a segment |
<Callout title="Segment event names" variant="idea">
Segment events use a slugified version of the segment name. For example, a segment called "VIP Users" would produce
the events `segment.vip-users.entry` and `segment.vip-users.exit`.
</Callout>
## Setting up a webhook
<div className='fd-steps [&_h3]:fd-step'>
### Create the workflow
Navigate to the **Workflows** section in the dashboard and create a new workflow. Choose the event you want to listen for as the trigger. For example, to receive notifications when an email bounces, use `email.bounce` as the trigger event.
### Add a Webhook step
After the trigger, add a **Webhook** step and configure it:
- **URL**: The endpoint on your server that will receive the webhook (e.g. `https://api.example.com/webhooks/plunk`)
- **Method**: The HTTP method to use. Defaults to `POST`, which is recommended for most use cases.
- **Headers** (optional): Custom headers to include in the request, provided as JSON. This is useful for authentication.
```json
{
"Authorization": "Bearer your-secret-token"
}
```
### Enable the workflow
Once configured, enable the workflow. It will start sending webhook requests whenever the trigger event occurs.
</div>
## Webhook payload
When using the default payload (no custom body configured), Plunk sends a JSON request with the following structure:
```json
{
"contact": {
"email": "[email protected]",
"subscribed": true,
"data": {
"name": "John",
"plan": "pro"
}
},
"workflow": {
"id": "wf_abc123",
"name": "Bounce Notifications"
},
"execution": {
"id": "exec_xyz789",
"startedAt": "2025-01-15T10:30:00.000Z"
},
"event": {
"subject": "Welcome to Plunk",
"from": "[email protected]",
"bounceType": "Permanent"
}
}
```
The `event` field contains the data associated with the event that triggered the workflow. The exact contents depend on the event type.
### Event data by type
The `event` field varies depending on which event triggered the workflow:
| Event | Fields in `event` |
| ----------------- | ------------------------------------------------------------------------ |
| `email.sent` | `subject`, `from`, `messageId`, `templateId`, `campaignId`, `sourceType` |
| `email.open` | `subject`, `from`, `openedAt`, `isFirstOpen` |
| `email.click` | `subject`, `from`, `clickedAt`, `clicks`, `isFirstClick` |
| `email.bounce` | `subject`, `from`, `bounceType`, `bouncedAt` |
| `email.complaint` | `subject`, `from`, `complainedAt` |
| Custom events | Whatever data you passed when tracking the event |
## Common use cases
### Bounce and complaint monitoring
Create a workflow triggered by `email.bounce` or `email.complaint` to forward these events to your application. This allows you to keep your own database in sync with Plunk's contact statuses.
You can use additional workflow steps before the webhook to add logic:
- **Condition**: Only send the webhook for hard bounces by checking the `bounceType` field
- **Delay**: Add a short delay to batch-process related events
- **Update Contact**: Mark the contact with metadata before sending the webhook
### Syncing unsubscribes
Trigger a workflow on `contact.unsubscribed` to notify your application when a contact opts out. This is useful for keeping subscription status synchronized across multiple systems.
### Custom event forwarding
If you track custom events in Plunk (e.g. `user.signup`, `order.completed`), you can forward those same events to other services via webhooks. This turns Plunk into an event router — track once, distribute to multiple endpoints.
## Adding conditions and delays
Since webhooks are part of the workflow system, you can combine them with other step types for more advanced setups:
- Use a **Condition** step to only fire the webhook when certain criteria are met (e.g. only notify for contacts on a specific plan)
- Use a **Wait for Event** step to wait for a follow-up event before sending the webhook (e.g. wait to see if a bounced contact re-subscribes)
- Use a **Delay** step to add a time buffer before the webhook fires
+22 -3
View File
@@ -596,7 +596,7 @@
"post": { "post": {
"tags": ["Public API"], "tags": ["Public API"],
"summary": "Verify email address", "summary": "Verify email address",
"description": "Verify an email address for validity, check if it's from a disposable domain, verify MX records, and detect potential typos with suggestions.", "description": "Verify an email address for validity, check if it's from a disposable domain or personal email provider, verify MX records, and detect potential typos with suggestions.",
"operationId": "verifyEmail", "operationId": "verifyEmail",
"requestBody": { "requestBody": {
"required": true, "required": true,
@@ -676,9 +676,17 @@
"type": "boolean", "type": "boolean",
"description": "Whether the email uses plus addressing (contains a + in the local part)" "description": "Whether the email uses plus addressing (contains a + in the local part)"
}, },
"isPersonalEmail": {
"type": "boolean",
"description": "Whether the email is from a personal/free email provider (Gmail, Hotmail, Yahoo, etc.)"
},
"domainExists": { "domainExists": {
"type": "boolean", "type": "boolean",
"description": "Whether the domain exists (has DNS A or AAAA records)" "description": "Whether the domain exists in DNS (has NS records)"
},
"hasWebsite": {
"type": "boolean",
"description": "Whether the domain has a website (has DNS A or AAAA records) - informational only"
}, },
"hasMxRecords": { "hasMxRecords": {
"type": "boolean", "type": "boolean",
@@ -705,7 +713,9 @@
"isAlias", "isAlias",
"isTypo", "isTypo",
"isPlusAddressed", "isPlusAddressed",
"isPersonalEmail",
"domainExists", "domainExists",
"hasWebsite",
"hasMxRecords", "hasMxRecords",
"reasons" "reasons"
] ]
@@ -724,7 +734,9 @@
"isAlias": false, "isAlias": false,
"isTypo": false, "isTypo": false,
"isPlusAddressed": false, "isPlusAddressed": false,
"isPersonalEmail": true,
"domainExists": true, "domainExists": true,
"hasWebsite": true,
"hasMxRecords": true, "hasMxRecords": true,
"reasons": ["Email appears to be valid"] "reasons": ["Email appears to be valid"]
} }
@@ -741,10 +753,15 @@
"isAlias": false, "isAlias": false,
"isTypo": true, "isTypo": true,
"isPlusAddressed": false, "isPlusAddressed": false,
"isPersonalEmail": false,
"domainExists": false, "domainExists": false,
"hasWebsite": false,
"hasMxRecords": false, "hasMxRecords": false,
"suggestedEmail": "[email protected]", "suggestedEmail": "[email protected]",
"reasons": ["Possible typo detected, did you mean gmail.com?", "Domain does not exist"] "reasons": [
"Possible typo detected, did you mean gmail.com?",
"Domain does not exist (no nameservers found)"
]
} }
} }
}, },
@@ -759,7 +776,9 @@
"isAlias": false, "isAlias": false,
"isTypo": false, "isTypo": false,
"isPlusAddressed": false, "isPlusAddressed": false,
"isPersonalEmail": false,
"domainExists": true, "domainExists": true,
"hasWebsite": true,
"hasMxRecords": true, "hasMxRecords": true,
"reasons": ["Email appears to be valid"] "reasons": ["Email appears to be valid"]
} }
+1 -1
View File
@@ -21,7 +21,7 @@
"fumadocs-openapi": "^10.0.11", "fumadocs-openapi": "^10.0.11",
"fumadocs-ui": "16.0.8", "fumadocs-ui": "16.0.8",
"lucide-react": "^0.553.0", "lucide-react": "^0.553.0",
"next": "^16.0.10", "next": "^16.1.5",
"next-sitemap": "^4.2.3", "next-sitemap": "^4.2.3",
"react": "^19.2.3", "react": "^19.2.3",
"react-dom": "^19.2.3", "react-dom": "^19.2.3",
+2 -2
View File
@@ -202,8 +202,8 @@ services:
ports: ports:
# SMTP ports (for email relay) # SMTP ports (for email relay)
- "465:465" # SMTPS (implicit TLS) - "${PORT_SECURE:-465}:465" # SMTPS (implicit TLS)
- "587:587" # SMTP Submission (STARTTLS) - "${PORT_SUBMISSION:-587}:587" # SMTP Submission (STARTTLS)
# Optional: Expose individual service ports for debugging # Optional: Expose individual service ports for debugging
# - "8080:8080" # API # - "8080:8080" # API
# - "3000:3000" # Web # - "3000:3000" # Web
+35 -6
View File
@@ -25,11 +25,32 @@ PLACEHOLDER_WIKI="https://next-wiki.useplunk.com"
# Output manifest file # Output manifest file
MANIFEST_FILE="$APP_DIR/.next/url-manifest.txt" MANIFEST_FILE="$APP_DIR/.next/url-manifest.txt"
# Find all files that contain placeholder URLs and save to manifest # At build time, Next.js creates:
# Search in .next directory for relevant file types # - .next/static/* - Static assets (copied separately to standalone in Dockerfile)
find "$APP_DIR/.next" -type f \( -name "*.js" -o -name "*.json" -o -name "*.html" -o -name "*.rsc" \) \ # - .next/standalone/apps/<app>/.next/* - Server files
#
# We need to scan BOTH and store paths relative to where they'll be at runtime:
# Runtime location: /app/apps/<app>/.next/standalone/apps/<app>/
# Clear manifest file
> "$MANIFEST_FILE"
# 1. Scan static assets (these will be copied to standalone/.next/static at runtime)
if [ -d "$APP_DIR/.next/static" ]; then
echo " Scanning .next/static directory..."
find "$APP_DIR/.next/static" -type f \( -name "*.js" -o -name "*.json" -o -name "*.html" \) \
-exec grep -l -E "$PLACEHOLDER_API|$PLACEHOLDER_DASHBOARD|$PLACEHOLDER_LANDING|$PLACEHOLDER_WIKI" {} \; \ -exec grep -l -E "$PLACEHOLDER_API|$PLACEHOLDER_DASHBOARD|$PLACEHOLDER_LANDING|$PLACEHOLDER_WIKI" {} \; \
2>/dev/null > "$MANIFEST_FILE" || true 2>/dev/null | sed "s|$APP_DIR/||g" >> "$MANIFEST_FILE" || true
fi
# 2. Scan standalone server files
STANDALONE_DIR="$APP_DIR/.next/standalone/apps/$APP_NAME"
if [ -d "$STANDALONE_DIR/.next" ]; then
echo " Scanning standalone directory..."
find "$STANDALONE_DIR/.next" -type f \( -name "*.js" -o -name "*.json" -o -name "*.html" -o -name "*.rsc" \) \
-exec grep -l -E "$PLACEHOLDER_API|$PLACEHOLDER_DASHBOARD|$PLACEHOLDER_LANDING|$PLACEHOLDER_WIKI" {} \; \
2>/dev/null | sed "s|$STANDALONE_DIR/||g" >> "$MANIFEST_FILE" || true
fi
# Count files # Count files
FILE_COUNT=$(wc -l < "$MANIFEST_FILE" | tr -d ' ') FILE_COUNT=$(wc -l < "$MANIFEST_FILE" | tr -d ' ')
@@ -37,9 +58,17 @@ FILE_COUNT=$(wc -l < "$MANIFEST_FILE" | tr -d ' ')
echo "✅ Generated manifest for $APP_NAME: $FILE_COUNT files need URL replacement" echo "✅ Generated manifest for $APP_NAME: $FILE_COUNT files need URL replacement"
echo " Manifest saved to: $MANIFEST_FILE" echo " Manifest saved to: $MANIFEST_FILE"
# Also generate manifest for sitemap/robots files # Also generate manifest for sitemap/robots files in standalone public directory
SITEMAP_MANIFEST_FILE="$APP_DIR/.next/sitemap-manifest.txt" SITEMAP_MANIFEST_FILE="$APP_DIR/.next/sitemap-manifest.txt"
find "$APP_DIR/public" -type f \( -name "sitemap*.xml" -o -name "robots.txt" \) 2>/dev/null > "$SITEMAP_MANIFEST_FILE" || true
# Scan public directory (will be copied to standalone/public at runtime)
if [ -d "$APP_DIR/public" ]; then
find "$APP_DIR/public" -type f \( -name "sitemap*.xml" -o -name "robots.txt" \) \
2>/dev/null | sed "s|$APP_DIR/||g" > "$SITEMAP_MANIFEST_FILE" || true
else
> "$SITEMAP_MANIFEST_FILE"
fi
SITEMAP_COUNT=$(wc -l < "$SITEMAP_MANIFEST_FILE" | tr -d ' ') SITEMAP_COUNT=$(wc -l < "$SITEMAP_MANIFEST_FILE" | tr -d ' ')
echo "✅ Generated sitemap manifest for $APP_NAME: $SITEMAP_COUNT files" echo "✅ Generated sitemap manifest for $APP_NAME: $SITEMAP_COUNT files"
+23 -18
View File
@@ -37,21 +37,24 @@ replace_urls_in_app() {
echo " 📊 Processing $file_count files from manifest" echo " 📊 Processing $file_count files from manifest"
if [ "$file_count" -gt 0 ]; then if [ "$file_count" -gt 0 ]; then
# Process files using xargs for better performance # Process files line by line
# Use -P 4 to process up to 4 files in parallel # The manifest now contains RELATIVE paths (e.g., .next/static/chunks/abc.js)
# This significantly speeds up processing of many files # We just need to prepend the app_dir
cat "$manifest_file" | xargs -P 4 -I {} sh -c '
file="{}"
if [ -f "$file" ]; then
sed -e "s|'"$PLACEHOLDER_API"'|'"$API_URI"'|g" \
-e "s|'"$PLACEHOLDER_DASHBOARD"'|'"$DASHBOARD_URI"'|g" \
-e "s|'"$PLACEHOLDER_LANDING"'|'"$LANDING_URI"'|g" \
-e "s|'"$PLACEHOLDER_WIKI"'|'"$WIKI_URI"'|g" \
"$file" > "${file}.tmp" && mv "${file}.tmp" "$file"
fi
'
echo " ✅ Successfully replaced URLs in $file_count files" cat "$manifest_file" | while IFS= read -r rel_path; do
# Construct full runtime path
runtime_path="$app_dir/$rel_path"
if [ -f "$runtime_path" ]; then
sed -e "s|$PLACEHOLDER_API|$API_URI|g" \
-e "s|$PLACEHOLDER_DASHBOARD|$DASHBOARD_URI|g" \
-e "s|$PLACEHOLDER_LANDING|$LANDING_URI|g" \
-e "s|$PLACEHOLDER_WIKI|$WIKI_URI|g" \
"$runtime_path" > "${runtime_path}.tmp" && mv "${runtime_path}.tmp" "$runtime_path"
fi
done
echo " ✅ Successfully replaced URLs in files"
else else
echo " ️ No files found with placeholder URLs" echo " ️ No files found with placeholder URLs"
fi fi
@@ -61,14 +64,16 @@ replace_urls_in_app() {
local sitemap_manifest="$app_dir/.next/sitemap-manifest.txt" local sitemap_manifest="$app_dir/.next/sitemap-manifest.txt"
if [ -f "$sitemap_manifest" ]; then if [ -f "$sitemap_manifest" ]; then
while IFS= read -r sitemap_file; do while IFS= read -r rel_path; do
if [ -f "$sitemap_file" ]; then # Manifest contains relative paths, just prepend app_dir
local rel_path="${sitemap_file#$app_dir/}" runtime_sitemap_path="$app_dir/$rel_path"
if [ -f "$runtime_sitemap_path" ]; then
sed -e "s|$PLACEHOLDER_API|$API_URI|g" \ sed -e "s|$PLACEHOLDER_API|$API_URI|g" \
-e "s|$PLACEHOLDER_DASHBOARD|$DASHBOARD_URI|g" \ -e "s|$PLACEHOLDER_DASHBOARD|$DASHBOARD_URI|g" \
-e "s|$PLACEHOLDER_LANDING|$LANDING_URI|g" \ -e "s|$PLACEHOLDER_LANDING|$LANDING_URI|g" \
-e "s|$PLACEHOLDER_WIKI|$WIKI_URI|g" \ -e "s|$PLACEHOLDER_WIKI|$WIKI_URI|g" \
"$sitemap_file" > "${sitemap_file}.tmp" && mv "${sitemap_file}.tmp" "$sitemap_file" "$runtime_sitemap_path" > "${runtime_sitemap_path}.tmp" && mv "${runtime_sitemap_path}.tmp" "$runtime_sitemap_path"
fi fi
done < "$sitemap_manifest" done < "$sitemap_manifest"
else else
+2 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "plunk", "name": "plunk",
"version": "0.4.0", "version": "0.7.0",
"private": true, "private": true,
"scripts": { "scripts": {
"build": "turbo build", "build": "turbo build",
@@ -10,6 +10,7 @@
"clean": "turbo clean --concurrency 20 && rimraf node_modules .turbo", "clean": "turbo clean --concurrency 20 && rimraf node_modules .turbo",
"format": "prettier --write \"**/*.{ts,tsx,md}\"", "format": "prettier --write \"**/*.{ts,tsx,md}\"",
"services:up": "docker compose -f docker/docker-compose.dev.yml up -d", "services:up": "docker compose -f docker/docker-compose.dev.yml up -d",
"services:down": "docker compose -f docker/docker-compose.dev.yml down",
"test": "vitest", "test": "vitest",
"test:watch": "vitest --watch", "test:watch": "vitest --watch",
"test:ui": "vitest --ui", "test:ui": "vitest --ui",
@@ -0,0 +1,5 @@
-- AlterEnum
ALTER TYPE "EmailSourceType" ADD VALUE 'INBOUND';
-- AlterTable
ALTER TABLE "projects" ADD COLUMN "billingLimitInbound" INTEGER;
@@ -0,0 +1,2 @@
-- AlterEnum
ALTER TYPE "EmailStatus" ADD VALUE 'RECEIVED';
@@ -0,0 +1,6 @@
-- CreateEnum
CREATE TYPE "SegmentType" AS ENUM ('DYNAMIC', 'STATIC');
-- AlterTable
ALTER TABLE "segments" ADD COLUMN "type" "SegmentType" NOT NULL DEFAULT 'DYNAMIC',
ALTER COLUMN "condition" DROP NOT NULL;
+13 -2
View File
@@ -53,6 +53,7 @@ model Project {
billingLimitWorkflows Int? // Max workflow emails per month billingLimitWorkflows Int? // Max workflow emails per month
billingLimitCampaigns Int? // Max campaign emails per month billingLimitCampaigns Int? // Max campaign emails per month
billingLimitTransactional Int? // Max transactional emails per month billingLimitTransactional Int? // Max transactional emails per month
billingLimitInbound Int? // Max inbound emails per month
// Email Tracking // Email Tracking
tracking TrackingMode @default(ENABLED) // Open and click tracking mode tracking TrackingMode @default(ENABLED) // Open and click tracking mode
@@ -198,8 +199,11 @@ model Segment {
name String name String
description String? description String?
// Filter condition (evaluated dynamically) // Segment type: DYNAMIC (filter-based) or STATIC (manually managed)
condition Json type SegmentType @default(DYNAMIC)
// Filter condition (evaluated dynamically, null for STATIC segments)
condition Json?
// Nested filter structure with AND/OR logic: // Nested filter structure with AND/OR logic:
// { // {
// logic: "OR", // logic: "OR",
@@ -746,10 +750,16 @@ enum StepExecutionStatus {
FAILED // Failed with error FAILED // Failed with error
} }
enum SegmentType {
DYNAMIC // Filter-based segment evaluated against contacts at query time
STATIC // Manually curated list of contacts managed via memberships
}
enum EmailSourceType { enum EmailSourceType {
TRANSACTIONAL // Sent via API call TRANSACTIONAL // Sent via API call
CAMPAIGN // Sent as part of broadcast CAMPAIGN // Sent as part of broadcast
WORKFLOW // Sent via workflow automation WORKFLOW // Sent via workflow automation
INBOUND // Received via SES inbound
} }
enum EmailStatus { enum EmailStatus {
@@ -757,6 +767,7 @@ enum EmailStatus {
SENDING // Currently being sent SENDING // Currently being sent
SENT // Successfully sent to provider SENT // Successfully sent to provider
DELIVERED // Confirmed delivered DELIVERED // Confirmed delivered
RECEIVED // Received by platform (inbound)
OPENED // Recipient opened email OPENED // Recipient opened email
CLICKED // Recipient clicked link CLICKED // Recipient clicked link
BOUNCED // Bounced (hard or soft) BOUNCED // Bounced (hard or soft)
+11
View File
@@ -5,6 +5,12 @@ import nlTranslations from './locales/nl.json' with {type: 'json'};
import frTranslations from './locales/fr.json' with {type: 'json'}; import frTranslations from './locales/fr.json' with {type: 'json'};
import deTranslations from './locales/de.json' with {type: 'json'}; import deTranslations from './locales/de.json' with {type: 'json'};
import hiTranslations from './locales/hi.json' with {type: 'json'}; import hiTranslations from './locales/hi.json' with {type: 'json'};
import ptTranslations from './locales/pt.json' with {type: 'json'};
import bgTranslations from './locales/bg.json' with {type: 'json'};
import csTranslations from './locales/cs.json' with {type: 'json'};
import plTranslations from './locales/pl.json' with {type: 'json'};
import esTranslations from './locales/es.json' with {type: 'json'};
export { export {
SUPPORTED_LANGUAGES, SUPPORTED_LANGUAGES,
DEFAULT_LANGUAGE, DEFAULT_LANGUAGE,
@@ -34,6 +40,11 @@ const translationsMap: Record<string, Translations> = {
de: deTranslations, de: deTranslations,
fr: frTranslations, fr: frTranslations,
hi: hiTranslations, hi: hiTranslations,
pt: ptTranslations,
bg: bgTranslations,
cs: csTranslations,
pl: plTranslations,
es: esTranslations,
}; };
// In-memory cache for loaded translations // In-memory cache for loaded translations
+5
View File
@@ -11,6 +11,11 @@ export const SUPPORTED_LANGUAGES: Language[] = [
{code: 'fr', name: 'French', nativeName: 'Français', flag: '🇫🇷'}, {code: 'fr', name: 'French', nativeName: 'Français', flag: '🇫🇷'},
{code: 'hi', name: 'Hindi', nativeName: 'हिंदी', flag: '🇮🇳'}, {code: 'hi', name: 'Hindi', nativeName: 'हिंदी', flag: '🇮🇳'},
{code: 'de', name: 'German', nativeName: 'Deutsch', flag: '🇩🇪'}, {code: 'de', name: 'German', nativeName: 'Deutsch', flag: '🇩🇪'},
{code: 'pt', name: 'Portuguese', nativeName: 'Português', flag: '🇧🇷'},
{code: 'bg', name: 'Bulgarian', nativeName: 'Български', flag: '🇧🇬'},
{code: 'cs', name: 'Czech', nativeName: 'Čeština', flag: '🇨🇿'},
{code: 'pl', name: 'Polish', nativeName: 'Polski', flag: '🇵🇱'},
{code: 'es', name: 'Spanish (Spain)', nativeName: 'Español (España)', flag: '🇪🇸'},
]; ];
export const DEFAULT_LANGUAGE = 'en'; export const DEFAULT_LANGUAGE = 'en';
+45
View File
@@ -0,0 +1,45 @@
{
"pages": {
"unsubscribe": {
"title": "Отписване",
"description": "Съжаляваме, че си тръгвате. Сигурни ли сте, че искате да отпишете {email} от получаването на имейли?",
"button": "Отпиши",
"buttonLoading": "Отписване...",
"managePreferences": "Управлявай настройки",
"successTitle": "Отписани сте",
"successDescription": "{email} е отписан. Няма да получавате повече имейли от нас.",
"changedMind": "Размислихте?",
"subscribeAgain": "Абонирай се пак"
},
"subscribe": {
"title": "Абонамент за новини",
"description": "Искате ли да абонирате {email} за имейли?",
"button": "Абонирай",
"buttonLoading": "Абониране...",
"successTitle": "Абонирани сте!",
"successDescription": "{email} вече е абониран за имейли от нас."
},
"manage": {
"title": "Настройки",
"description": "Настройки за {email}",
"subscriptionLabel": "Абонамент",
"subscribedStatus": "В момента сте абониран",
"unsubscribedStatus": "В момента сте отписан",
"subscribedSuccess": "Успешно абониране!",
"unsubscribedSuccess": "Успешно отписване!",
"unsubscribeCompletely": "Пълно отписване",
"subscribeToEmails": "Абонирай за имейли",
"disclaimer": "Тук управлявате имейл настройките си. Статусът се обновява веднага."
},
"common": {
"loading": "Зарежда...",
"error": "Грешка"
}
},
"email": {
"footer": {
"unsubscribeText": "Получихте този имейл, защото сте се съгласили да получавате имейли от {projectName}. Ако не желаете повече такива имейли, моля",
"updatePreferences": "променете настройките"
}
}
}
+45
View File
@@ -0,0 +1,45 @@
{
"pages": {
"unsubscribe": {
"title": "Odhlášení z odběru",
"description": "Mrzí nás, že odcházíte. Opravdu chcete odhlásit {email} z odběru e-mailů?",
"button": "Odhlásit se",
"buttonLoading": "Odhlašování...",
"managePreferences": "Spravovat předvolby",
"successTitle": "Odběr byl zrušen",
"successDescription": "E-mail {email} byl odhlášen z odběru. Už vám nebudeme zasílat žádné e-maily.",
"changedMind": "Změnili jste názor?",
"subscribeAgain": "Přihlásit se znovu"
},
"subscribe": {
"title": "Přihlášení k odběru",
"description": "Chcete přihlásit {email} k odběru e-mailů?",
"button": "Přihlásit se k odběru",
"buttonLoading": "Přihlašování...",
"successTitle": "Odběr byl aktivován!",
"successDescription": "E-mail {email} byl přihlášen k odběru e-mailů."
},
"manage": {
"title": "Správa předvoleb",
"description": "Správa e-mailových předvoleb pro {email}",
"subscriptionLabel": "Odběr e-mailů",
"subscribedStatus": "Aktuálně jste přihlášeni k odběru e-mailů",
"unsubscribedStatus": "Aktuálně jste odhlášeni z odběru e-mailů",
"subscribedSuccess": "Odběr byl úspěšně aktivován!",
"unsubscribedSuccess": "Odběr byl úspěšně zrušen!",
"unsubscribeCompletely": "Úplně se odhlásit z odběru",
"subscribeToEmails": "Přihlásit se k odběru e-mailů",
"disclaimer": "Na této stránce můžete spravovat své e-mailové předvolby. Stav odběru se aktualizuje v reálném čase."
},
"common": {
"loading": "Načítání...",
"error": "Chyba"
}
},
"email": {
"footer": {
"unsubscribeText": "Tento e-mail jste obdrželi, protože jste souhlasili se zasíláním e-mailů od {projectName}. Pokud si již nepřejete dostávat tyto e-maily, můžete",
"updatePreferences": "změnit své předvolby"
}
}
}
+45
View File
@@ -0,0 +1,45 @@
{
"pages": {
"unsubscribe": {
"title": "Cancelar suscripción",
"description": "Lamentamos que te vayas. ¿Estás seguro de que quieres cancelar la suscripción de {email} para dejar de recibir correos electrónicos?",
"button": "Cancelar suscripción",
"buttonLoading": "Cancelando suscripción...",
"managePreferences": "Gestionar preferencias en su lugar",
"successTitle": "Suscripción cancelada",
"successDescription": "Se ha cancelado la suscripción de {email}. No recibirás más correos electrónicos de nuestra parte.",
"changedMind": "¿Has cambiado de opinión?",
"subscribeAgain": "Suscribirse de nuevo"
},
"subscribe": {
"title": "Suscribirse a las novedades",
"description": "¿Te gustaría suscribir {email} para recibir correos electrónicos?",
"button": "Suscribirse",
"buttonLoading": "Suscribiendo...",
"successTitle": "¡Suscripción completada!",
"successDescription": "{email} está ahora suscrito para recibir correos electrónicos de nuestra parte."
},
"manage": {
"title": "Gestionar preferencias",
"description": "Gestiona las preferencias de correo electrónico de {email}",
"subscriptionLabel": "Suscripción de correo electrónico",
"subscribedStatus": "Actualmente estás suscrito para recibir correos electrónicos",
"unsubscribedStatus": "Actualmente tienes cancelada la suscripción a los correos electrónicos",
"subscribedSuccess": "¡Suscripción realizada con éxito!",
"unsubscribedSuccess": "¡Suscripción cancelada con éxito!",
"unsubscribeCompletely": "Cancelar suscripción completamente",
"subscribeToEmails": "Suscribirse a los correos electrónicos",
"disclaimer": "Esta página te permite gestionar tus preferencias de correo electrónico. El estado de tu suscripción se actualiza en tiempo real."
},
"common": {
"loading": "Cargando...",
"error": "Error"
}
},
"email": {
"footer": {
"unsubscribeText": "Has recibido este correo electrónico porque aceptaste recibir correos electrónicos de {projectName}. Si ya no deseas recibir correos electrónicos como este, por favor",
"updatePreferences": "actualiza tus preferencias"
}
}
}
+45
View File
@@ -0,0 +1,45 @@
{
"pages": {
"unsubscribe": {
"title": "Wypisz się",
"description": "Przykro nam, że odchodzisz. Czy na pewno chcesz wypisać {email} z otrzymywania wiadomości?",
"button": "Wypisz się",
"buttonLoading": "Wypisywanie...",
"managePreferences": "Zarządzaj preferencjami zamiast tego",
"successTitle": "Wypisano",
"successDescription": "{email} został wypisany. Nie będziesz już otrzymywać od nas wiadomości.",
"changedMind": "Zmieniłeś(-aś) zdanie?",
"subscribeAgain": "Zapisz się ponownie"
},
"subscribe": {
"title": "Zapisz się na aktualizacje",
"description": "Czy chcesz zapisać {email} do otrzymywania wiadomości?",
"button": "Zapisz się",
"buttonLoading": "Zapisywanie...",
"successTitle": "Zapisano!",
"successDescription": "{email} jest teraz zapisany do otrzymywania od nas wiadomości."
},
"manage": {
"title": "Zarządzaj preferencjami",
"description": "Zarządzaj preferencjami e-mail dla adresu {email}",
"subscriptionLabel": "Subskrypcja e-mail",
"subscribedStatus": "Obecnie jesteś zapisany do otrzymywania wiadomości",
"unsubscribedStatus": "Obecnie jesteś wypisany z otrzymywania wiadomości",
"subscribedSuccess": "Pomyślnie zapisano!",
"unsubscribedSuccess": "Pomyślnie wypisano!",
"unsubscribeCompletely": "Wypisz się całkowicie",
"subscribeToEmails": "Zapisz się na e-maile",
"disclaimer": "Ta strona pozwala zarządzać preferencjami e-mail. Status subskrypcji jest aktualizowany w czasie rzeczywistym."
},
"common": {
"loading": "Ładowanie...",
"error": "Błąd"
}
},
"email": {
"footer": {
"unsubscribeText": "Otrzymujesz tę wiadomość, ponieważ wyraziłeś(-aś) zgodę na otrzymywanie wiadomości od {projectName}. Jeśli nie chcesz już otrzymywać takich wiadomości, prosimy",
"updatePreferences": "zaktualizuj swoje preferencje"
}
}
}
+45
View File
@@ -0,0 +1,45 @@
{
"pages": {
"unsubscribe": {
"title": "Cancelar inscrição",
"description": "Lamentamos vê-lo partir. Tem certeza de que deseja cancelar a inscrição de {email} para não receber mais e-mails?",
"button": "Cancelar inscrição",
"buttonLoading": "Cancelando inscrição...",
"managePreferences": "Gerenciar preferências",
"successTitle": "Inscrição cancelada",
"successDescription": "{email} foi removido da lista. Você não receberá mais e-mails nossos.",
"changedMind": "Mudou de ideia?",
"subscribeAgain": "Inscrever-se novamente"
},
"subscribe": {
"title": "Inscrever-se para atualizações",
"description": "Deseja inscrever {email} para receber e-mails?",
"button": "Inscrever-se",
"buttonLoading": "Inscrevendo...",
"successTitle": "Você está inscrito!",
"successDescription": "{email} agora está inscrito para receber nossos e-mails."
},
"manage": {
"title": "Gerenciar Preferências",
"description": "Gerenciar preferências de e-mail para {email}",
"subscriptionLabel": "Inscrição de E-mail",
"subscribedStatus": "Você está inscrito para receber e-mails",
"unsubscribedStatus": "Você cancelou a inscrição de e-mails",
"subscribedSuccess": "Inscrito com sucesso!",
"unsubscribedSuccess": "Inscrição cancelada com sucesso!",
"unsubscribeCompletely": "Cancelar inscrição completamente",
"subscribeToEmails": "Inscrever-se para e-mails",
"disclaimer": "Esta página permite que você gerencie suas preferências de e-mail. Seu status de inscrição é atualizado em tempo real."
},
"common": {
"loading": "Carregando...",
"error": "Erro"
}
},
"email": {
"footer": {
"unsubscribeText": "Você recebeu este e-mail porque concordou em receber e-mails de {projectName}. Se não deseja mais receber e-mails como este, por favor",
"updatePreferences": "atualize suas preferências"
}
}
}
+42 -1
View File
@@ -101,8 +101,10 @@ const segmentFilterSchema = z.object({
'exists', 'exists',
'notExists', 'notExists',
'within', 'within',
'olderThan',
'triggered', 'triggered',
'triggeredWithin', 'triggeredWithin',
'triggeredOlderThan',
'notTriggered', 'notTriggered',
]), ]),
value: z.any().optional(), value: z.any().optional(),
@@ -130,15 +132,20 @@ export const SegmentSchemas = {
create: z.object({ create: z.object({
name: z.string().min(1).max(100), name: z.string().min(1).max(100),
description: z.string().max(500).optional(), description: z.string().max(500).optional(),
condition: filterConditionSchema, type: z.enum(['DYNAMIC', 'STATIC']).default('DYNAMIC'),
condition: filterConditionSchema.optional(),
trackMembership: z.boolean().default(false), trackMembership: z.boolean().default(false),
}), }),
update: z.object({ update: z.object({
name: z.string().min(1).max(100).optional(), name: z.string().min(1).max(100).optional(),
description: z.string().max(500).optional(), description: z.string().max(500).optional(),
type: z.enum(['DYNAMIC', 'STATIC']).optional(),
condition: filterConditionSchema.optional(), condition: filterConditionSchema.optional(),
trackMembership: z.boolean().optional(), trackMembership: z.boolean().optional(),
}), }),
members: z.object({
emails: z.array(z.string().email()).min(1).max(500),
}),
}; };
export const TemplateSchemas = { export const TemplateSchemas = {
@@ -178,6 +185,7 @@ export const WorkflowSchemas = {
triggerType: z.nativeEnum(WorkflowTriggerType).optional(), triggerType: z.nativeEnum(WorkflowTriggerType).optional(),
triggerConfig: jsonSchema.optional(), triggerConfig: jsonSchema.optional(),
enabled: z.boolean().optional(), enabled: z.boolean().optional(),
allowReentry: z.boolean().optional(),
}), }),
addStep: z.object({ addStep: z.object({
type: z.nativeEnum(WorkflowStepType), type: z.nativeEnum(WorkflowStepType),
@@ -206,6 +214,27 @@ export const WorkflowSchemas = {
}; };
export const WorkflowStepConfigSchemas = { export const WorkflowStepConfigSchemas = {
sendEmail: z.object({
templateId: uuid,
recipient: z
.object({
type: z.enum(['CONTACT', 'CUSTOM']),
customEmail: email.optional(),
})
.refine(
data => {
// If type is CUSTOM, customEmail must be provided
if (data.type === 'CUSTOM') {
return !!data.customEmail;
}
return true;
},
{
message: 'Custom email is required when recipient type is CUSTOM',
},
)
.optional(),
}),
delay: z delay: z
.object({ .object({
amount: z.number().positive(), amount: z.number().positive(),
@@ -378,6 +407,17 @@ export const ActionSchemas = {
filename: z.string().min(1).max(255), filename: z.string().min(1).max(255),
content: z.string().min(1), // Base64 encoded file content content: z.string().min(1), // Base64 encoded file content
contentType: z.string().min(1).max(255), contentType: z.string().min(1).max(255),
contentId: z
.string()
.min(1)
.max(255)
.regex(/^[^<>\r\n]+$/, 'Content ID cannot contain <, >, \\r, or \\n')
.optional(),
disposition: z.enum(['attachment', 'inline']).default('attachment'),
})
.refine(data => data.disposition !== 'inline' || !!data.contentId, {
message: 'Content ID is required when disposition is inline',
path: ['contentId'],
}), }),
) )
.max(10) // Maximum 10 attachments per email .max(10) // Maximum 10 attachments per email
@@ -416,6 +456,7 @@ export const BillingLimitSchemas = {
workflows: z.coerce.number().int().positive().nullable(), workflows: z.coerce.number().int().positive().nullable(),
campaigns: z.coerce.number().int().positive().nullable(), campaigns: z.coerce.number().int().positive().nullable(),
transactional: z.coerce.number().int().positive().nullable(), transactional: z.coerce.number().int().positive().nullable(),
inbound: z.coerce.number().int().positive().nullable(),
}), }),
} as const; } as const;
+2
View File
@@ -9,9 +9,11 @@ export enum ActivityType {
EVENT_TRIGGERED = 'event.triggered', EVENT_TRIGGERED = 'event.triggered',
EMAIL_SENT = 'email.sent', EMAIL_SENT = 'email.sent',
EMAIL_DELIVERED = 'email.delivered', EMAIL_DELIVERED = 'email.delivered',
EMAIL_RECEIVED = 'email.received',
EMAIL_OPENED = 'email.opened', EMAIL_OPENED = 'email.opened',
EMAIL_CLICKED = 'email.clicked', EMAIL_CLICKED = 'email.clicked',
EMAIL_BOUNCED = 'email.bounced', EMAIL_BOUNCED = 'email.bounced',
EMAIL_COMPLAINT = 'email.complaint',
CAMPAIGN_SENT = 'campaign.sent', CAMPAIGN_SENT = 'campaign.sent',
CAMPAIGN_SCHEDULED = 'campaign.scheduled', CAMPAIGN_SCHEDULED = 'campaign.scheduled',
WORKFLOW_STARTED = 'workflow.started', WORKFLOW_STARTED = 'workflow.started',
+1
View File
@@ -20,6 +20,7 @@ export interface BillingLimitsResponse {
workflows: CategoryUsage; workflows: CategoryUsage;
campaigns: CategoryUsage; campaigns: CategoryUsage;
transactional: CategoryUsage; transactional: CategoryUsage;
inbound: CategoryUsage;
currency: string | null; currency: string | null;
} }
+4 -2
View File
@@ -12,8 +12,10 @@ export interface EmailVerificationResult {
isAlias: boolean; isAlias: boolean;
isTypo: boolean; isTypo: boolean;
isPlusAddressed: boolean; isPlusAddressed: boolean;
domainExists: boolean; isPersonalEmail: boolean; // Email is from a personal/free provider (Gmail, Hotmail, etc.)
hasMxRecords: boolean; domainExists: boolean; // Domain exists in DNS (has NS records)
hasWebsite: boolean; // Domain has A/AAAA records (informational - not required for email)
hasMxRecords: boolean; // Domain has MX records (required for receiving email)
suggestedEmail?: string; suggestedEmail?: string;
reasons: string[]; reasons: string[];
} }
+3
View File
@@ -26,3 +26,6 @@ export * from './segments/index.js';
// Security types // Security types
export * from './security/index.js'; export * from './security/index.js';
// Workflow types
export * from './workflows/index.js';
+7 -1
View File
@@ -2,6 +2,8 @@
* Segment and filter types * Segment and filter types
*/ */
export type SegmentType = 'DYNAMIC' | 'STATIC';
// Segment filter types // Segment filter types
export type SegmentFilterOperator = export type SegmentFilterOperator =
// Standard operators (for contact fields) // Standard operators (for contact fields)
@@ -16,9 +18,11 @@ export type SegmentFilterOperator =
| 'exists' | 'exists'
| 'notExists' | 'notExists'
| 'within' | 'within'
| 'olderThan' // More than X time ago (for date fields)
// Event-based operators // Event-based operators
| 'triggered' // Event/email activity occurred (any time) | 'triggered' // Event/email activity occurred (any time)
| 'triggeredWithin' // Event/email activity occurred within timeframe | 'triggeredWithin' // Event/email activity occurred within timeframe
| 'triggeredOlderThan' // Event/email activity occurred more than X time ago
| 'notTriggered'; // Event/email activity never occurred | 'notTriggered'; // Event/email activity never occurred
export type SegmentFilterLogic = 'AND' | 'OR'; export type SegmentFilterLogic = 'AND' | 'OR';
@@ -43,13 +47,15 @@ export interface FilterCondition {
export interface CreateSegmentData { export interface CreateSegmentData {
name: string; name: string;
description?: string; description?: string;
condition: FilterCondition; type?: SegmentType;
condition?: FilterCondition;
trackMembership?: boolean; trackMembership?: boolean;
} }
export interface UpdateSegmentData { export interface UpdateSegmentData {
name?: string; name?: string;
description?: string; description?: string;
type?: SegmentType;
condition?: FilterCondition; condition?: FilterCondition;
trackMembership?: boolean; trackMembership?: boolean;
} }
+33
View File
@@ -0,0 +1,33 @@
/**
* Workflow-specific type definitions
*/
/**
* Recipient type for workflow email steps
*/
export enum EmailRecipientType {
/** Send to the contact that triggered the workflow */
CONTACT = 'CONTACT',
/** Send to a custom email address */
CUSTOM = 'CUSTOM',
}
/**
* Configuration for email recipient in SEND_EMAIL workflow step
*/
export interface EmailRecipientConfig {
/** Type of recipient */
type: EmailRecipientType;
/** Custom email address (required when type is CUSTOM) */
customEmail?: string;
}
/**
* Configuration for SEND_EMAIL workflow step
*/
export interface SendEmailStepConfig {
/** Template ID to use for the email */
templateId: string;
/** Recipient configuration */
recipient?: EmailRecipientConfig;
}
+33 -3
View File
@@ -34,6 +34,7 @@
"dependsOn": ["^start"], "dependsOn": ["^start"],
"env": [ "env": [
"NODE_ENV", "NODE_ENV",
"PORT",
"JWT_SECRET", "JWT_SECRET",
"DATABASE_URL", "DATABASE_URL",
"DIRECT_DATABASE_URL", "DIRECT_DATABASE_URL",
@@ -53,6 +54,7 @@
"AWS_SES_SECRET_ACCESS_KEY", "AWS_SES_SECRET_ACCESS_KEY",
"SES_CONFIGURATION_SET", "SES_CONFIGURATION_SET",
"SES_CONFIGURATION_SET_NO_TRACKING", "SES_CONFIGURATION_SET_NO_TRACKING",
"EMAIL_RATE_LIMIT_PER_SECOND",
"GITHUB_OAUTH_CLIENT", "GITHUB_OAUTH_CLIENT",
"GITHUB_OAUTH_SECRET", "GITHUB_OAUTH_SECRET",
"GOOGLE_OAUTH_CLIENT", "GOOGLE_OAUTH_CLIENT",
@@ -67,7 +69,15 @@
"NEXT_PUBLIC_DASHBOARD_URI", "NEXT_PUBLIC_DASHBOARD_URI",
"NEXT_PUBLIC_WIKI_URI", "NEXT_PUBLIC_WIKI_URI",
"PLUNK_API_KEY", "PLUNK_API_KEY",
"PLUNK_FROM_ADDRESS" "PLUNK_FROM_ADDRESS",
"NTFY_URL",
"SMTP_ENABLED",
"SMTP_DOMAIN",
"PORT_SECURE",
"PORT_SUBMISSION",
"AUTO_PROJECT_DISABLE",
"DISABLE_SIGNUPS",
"VERIFY_EMAIL_ON_SIGNUP"
], ],
"inputs": ["$TURBO_DEFAULT$", ".env*"] "inputs": ["$TURBO_DEFAULT$", ".env*"]
}, },
@@ -84,6 +94,7 @@
"persistent": true, "persistent": true,
"env": [ "env": [
"NODE_ENV", "NODE_ENV",
"PORT",
"JWT_SECRET", "JWT_SECRET",
"DATABASE_URL", "DATABASE_URL",
"DIRECT_DATABASE_URL", "DIRECT_DATABASE_URL",
@@ -103,6 +114,7 @@
"AWS_SES_SECRET_ACCESS_KEY", "AWS_SES_SECRET_ACCESS_KEY",
"SES_CONFIGURATION_SET", "SES_CONFIGURATION_SET",
"SES_CONFIGURATION_SET_NO_TRACKING", "SES_CONFIGURATION_SET_NO_TRACKING",
"EMAIL_RATE_LIMIT_PER_SECOND",
"GITHUB_OAUTH_CLIENT", "GITHUB_OAUTH_CLIENT",
"GITHUB_OAUTH_SECRET", "GITHUB_OAUTH_SECRET",
"GOOGLE_OAUTH_CLIENT", "GOOGLE_OAUTH_CLIENT",
@@ -117,7 +129,15 @@
"NEXT_PUBLIC_DASHBOARD_URI", "NEXT_PUBLIC_DASHBOARD_URI",
"NEXT_PUBLIC_WIKI_URI", "NEXT_PUBLIC_WIKI_URI",
"PLUNK_API_KEY", "PLUNK_API_KEY",
"PLUNK_FROM_ADDRESS" "PLUNK_FROM_ADDRESS",
"NTFY_URL",
"SMTP_ENABLED",
"SMTP_DOMAIN",
"PORT_SECURE",
"PORT_SUBMISSION",
"AUTO_PROJECT_DISABLE",
"DISABLE_SIGNUPS",
"VERIFY_EMAIL_ON_SIGNUP"
] ]
}, },
"dev:worker": { "dev:worker": {
@@ -125,6 +145,7 @@
"persistent": true, "persistent": true,
"env": [ "env": [
"NODE_ENV", "NODE_ENV",
"PORT",
"JWT_SECRET", "JWT_SECRET",
"DATABASE_URL", "DATABASE_URL",
"DIRECT_DATABASE_URL", "DIRECT_DATABASE_URL",
@@ -144,6 +165,7 @@
"AWS_SES_SECRET_ACCESS_KEY", "AWS_SES_SECRET_ACCESS_KEY",
"SES_CONFIGURATION_SET", "SES_CONFIGURATION_SET",
"SES_CONFIGURATION_SET_NO_TRACKING", "SES_CONFIGURATION_SET_NO_TRACKING",
"EMAIL_RATE_LIMIT_PER_SECOND",
"GITHUB_OAUTH_CLIENT", "GITHUB_OAUTH_CLIENT",
"GITHUB_OAUTH_SECRET", "GITHUB_OAUTH_SECRET",
"GOOGLE_OAUTH_CLIENT", "GOOGLE_OAUTH_CLIENT",
@@ -158,7 +180,15 @@
"NEXT_PUBLIC_DASHBOARD_URI", "NEXT_PUBLIC_DASHBOARD_URI",
"NEXT_PUBLIC_WIKI_URI", "NEXT_PUBLIC_WIKI_URI",
"PLUNK_API_KEY", "PLUNK_API_KEY",
"PLUNK_FROM_ADDRESS" "PLUNK_FROM_ADDRESS",
"NTFY_URL",
"SMTP_ENABLED",
"SMTP_DOMAIN",
"PORT_SECURE",
"PORT_SUBMISSION",
"AUTO_PROJECT_DISABLE",
"DISABLE_SIGNUPS",
"VERIFY_EMAIL_ON_SIGNUP"
] ]
}, },
"clean": { "clean": {

Some files were not shown because too many files have changed in this diff Show More