Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2700e62935 | ||
|
|
517b93cc95 | ||
|
|
8e3fb9595d | ||
|
|
58be4abc31 | ||
|
|
480f0c1034 | ||
|
|
80beb2bb99 | ||
|
|
6ab4d77ca9 | ||
|
|
edfc399061 | ||
|
|
4a145f3488 | ||
|
|
868bdee615 | ||
|
|
6ebbb50f68 | ||
|
|
87eb56ff36 | ||
|
|
a348d37c21 | ||
|
|
5c166797b5 | ||
|
|
971b98a4cc | ||
|
|
81315eac8e | ||
|
|
1c1c95d332 | ||
|
|
844be42151 | ||
|
|
d59f4a10cd | ||
|
|
51ac88b9f5 | ||
|
|
523bcad602 | ||
|
|
32dd7bba46 | ||
|
|
71e2277643 | ||
|
|
079e1879b3 | ||
|
|
4de40f40fa | ||
|
|
94ceadbbe4 | ||
|
|
9797aed47f | ||
|
|
8b3657d056 | ||
|
|
01ec34a8cb | ||
|
|
ba3813e242 | ||
|
|
283f40239d | ||
|
|
53b631e6c6 | ||
|
|
6759bffd2a | ||
|
|
d2496bc51d | ||
|
|
bfecf04fa3 | ||
|
|
6d98d51222 | ||
|
|
c484da88ab | ||
|
|
1d475c382b | ||
|
|
3fea06ba2d | ||
|
|
1d1d407a6f | ||
|
|
46b2b8390f | ||
|
|
9e4aa9443b | ||
|
|
a27d564e1a | ||
|
|
4e95c5a4e4 | ||
|
|
463301b5db | ||
|
|
f178c59b5b | ||
|
|
6195b39f3d | ||
|
|
e0bf0f628a | ||
|
|
8a26d605b4 | ||
|
|
715961c007 | ||
|
|
ccd516e4e8 | ||
|
|
6aee5db588 | ||
|
|
649bbf6d6b | ||
|
|
e43f70d8a1 | ||
|
|
f22da4add1 | ||
|
|
de6335e999 | ||
|
|
7658a59b5d | ||
|
|
aaf5ac6530 | ||
|
|
3f30a48c40 | ||
|
|
c6340a1dc7 | ||
|
|
4ba43dd3b6 | ||
|
|
d11495061d | ||
|
|
fadc19d139 | ||
|
|
2ea1802290 | ||
|
|
15bdcf6e49 | ||
|
|
2529c9b428 | ||
|
|
4ddafdc041 | ||
|
|
88be252a29 | ||
|
|
db5dfc46ce | ||
|
|
e2ce5d4e96 | ||
|
|
735acff454 | ||
|
|
1193d6c7e6 | ||
|
|
62661ae45f | ||
|
|
4587e9d670 | ||
|
|
88a8a02e53 | ||
|
|
cbb3bffcf4 | ||
|
|
80ef65e04b | ||
|
|
361ec0b1eb | ||
|
|
ed9027b4ef | ||
|
|
d1f357c300 | ||
|
|
a126563542 | ||
|
|
a3cc62213f | ||
|
|
2d05c3fbc1 | ||
|
|
c0752e1363 | ||
|
|
1b09ec1e13 | ||
|
|
0f00ca1b8c | ||
|
|
7615b62945 | ||
|
|
ba23a1c6fa | ||
|
|
4b5815c1d6 | ||
|
|
29883ffc71 | ||
|
|
5724ab9536 | ||
|
|
0c15cc84df | ||
|
|
a729789922 | ||
|
|
26ec5864ae | ||
|
|
48425d1df1 | ||
|
|
a5e8d239ee | ||
|
|
532293e52a | ||
|
|
fd066a6991 | ||
|
|
bb72911fa2 | ||
|
|
9fafeb7d4b | ||
|
|
11ea9d5e12 | ||
|
|
b73927067f | ||
|
|
4b65e718ad | ||
|
|
f6f291966f | ||
|
|
11c428d4ff | ||
|
|
2eb407993b | ||
|
|
10946511b0 | ||
|
|
5f741c66c7 | ||
|
|
d7eb85ffdd | ||
|
|
1c89ed083e | ||
|
|
f40cc86cec | ||
|
|
6f31fa2503 | ||
|
|
98f1e80fca | ||
|
|
c1bcd358cc | ||
|
|
517753c420 | ||
|
|
ab3edd7dc9 | ||
|
|
c910d20bb7 | ||
|
|
bdc9b30ef2 | ||
|
|
c8190b953f | ||
|
|
1637d54e1b | ||
|
|
15294a40d8 | ||
|
|
bb78c86c40 | ||
|
|
c0e0ad8bc6 | ||
|
|
208c809a90 | ||
|
|
b7eb2549d4 | ||
|
|
91d0d2d297 | ||
|
|
862875428d | ||
|
|
2da8b065d0 | ||
|
|
60146fcc10 | ||
|
|
c278a0fd94 | ||
|
|
0b3aa28101 | ||
|
|
ecaf99665a | ||
|
|
3d9b4e4eb3 | ||
|
|
e048fc1570 | ||
|
|
4322de929a | ||
|
|
bfdfde68fb | ||
|
|
3649392b47 | ||
|
|
cbde3cce3f | ||
|
|
e450ae62a3 | ||
|
|
d56e876428 | ||
|
|
b79d416667 | ||
|
|
bf12392b88 | ||
|
|
ae9d5a6f3d | ||
|
|
1362e4672f | ||
|
|
35a830fa7b | ||
|
|
742821eba9 | ||
|
|
91f80de981 | ||
|
|
c584e42c54 | ||
|
|
545d733794 | ||
|
|
37ed1e49b7 | ||
|
|
df76be1b87 | ||
|
|
bd5a085802 | ||
|
|
bc4c79235e | ||
|
|
f2ebce0ef2 | ||
|
|
e10a94b2bc | ||
|
|
52fc7f73ce | ||
|
|
428079e632 | ||
|
|
19ea8b0122 | ||
|
|
6fdc29fc0f | ||
|
|
c91d8c2e29 | ||
|
|
3bb3411994 | ||
|
|
28fe7093f4 | ||
|
|
0803fd7bc4 | ||
|
|
03a058ad48 | ||
|
|
5e62f517fc | ||
|
|
44c86572c2 | ||
|
|
effdfdb6d6 | ||
|
|
c0b2abaeca | ||
|
|
e3395083db | ||
|
|
ae64c2dbb5 | ||
|
|
52cb2b6c77 | ||
|
|
df18979e5e | ||
|
|
a981a8bba4 | ||
|
|
a6d5740b77 | ||
|
|
6114c21a3f | ||
|
|
4ce4c8c2a4 | ||
|
|
7834b9e7ef | ||
|
|
c3967a98b0 | ||
|
|
9e2400c6de | ||
|
|
fb5aa8796a | ||
|
|
284838279d | ||
|
|
2c5a71518d | ||
|
|
a8014cf7cf | ||
|
|
3214f6c42d | ||
|
|
d24259e8d2 | ||
|
|
3343e891bd | ||
|
|
6f99d4190c | ||
|
|
5f990573c1 | ||
|
|
b50b5af763 | ||
|
|
35c9e4c34e | ||
|
|
7b6540a748 | ||
|
|
4b290fd0b7 | ||
|
|
f9d7cf2453 | ||
|
|
ac8aeebfbe | ||
|
|
1675b07694 | ||
|
|
d4f41892cd | ||
|
|
5046c21045 | ||
|
|
9c50e1a7b4 | ||
|
|
33df5632a3 | ||
|
|
3e3117e4a7 | ||
|
|
3b39d847cd | ||
|
|
dff25c62d9 | ||
|
|
200dfb1dbf | ||
|
|
a99cde8839 | ||
|
|
474c822640 | ||
|
|
0e8b6f813d | ||
|
|
7b6872c4b7 | ||
|
|
c17f7065d9 | ||
|
|
f44d987bc9 | ||
|
|
c83541c3eb | ||
|
|
dc2ce02d1a | ||
|
|
b9d692cf5b | ||
|
|
c19cf531b8 | ||
|
|
f0ef34646e | ||
|
|
6a340e9554 | ||
|
|
38565bbce2 | ||
|
|
c32b54f588 | ||
|
|
44987d2b5e | ||
|
|
2c3e8970cb | ||
|
|
395af0080c | ||
|
|
e3ea5fb6dc | ||
|
|
4451e921ca | ||
|
|
92949b7596 | ||
|
|
57bfbf874b | ||
|
|
1dc423a1c4 | ||
|
|
de8aaa5c45 | ||
|
|
1a1e3204ee | ||
|
|
6c4cc295b8 | ||
|
|
9f212ddcb8 | ||
|
|
5f82278282 | ||
|
|
f6a32ce610 | ||
|
|
0839975083 | ||
|
|
c90f3d0f01 | ||
|
|
5f3daf689b | ||
|
|
cc7fcdb4ef | ||
|
|
d75aed81e1 | ||
|
|
0cbaa8fc66 | ||
|
|
0686b3a3f2 | ||
|
|
9b15b93b96 | ||
|
|
8f2510f5ec | ||
|
|
e196d798c5 | ||
|
|
777a12ec89 | ||
|
|
6c6af775bc | ||
|
|
4f8c9f029d | ||
|
|
8f72994b46 | ||
|
|
d162f255c2 | ||
|
|
c8e252fefd | ||
|
|
b8f1ad9ab5 | ||
|
|
708ab506f1 | ||
|
|
ec1f4c9374 | ||
|
|
5528288c7b | ||
|
|
7bd098bdd0 | ||
|
|
cbea263a91 | ||
|
|
e8a247fe12 | ||
|
|
4b51e386e3 | ||
|
|
59aa7845ba | ||
|
|
5600c49bb6 | ||
|
|
21af8fe05e | ||
|
|
2c4d95e604 | ||
|
|
64bd094b47 | ||
|
|
53b33bbd36 | ||
|
|
5fa9b9dda5 | ||
|
|
4bc5424815 | ||
|
|
573e2e8449 | ||
|
|
00ae942c3c | ||
|
|
9c69c7a36e | ||
|
|
9568b7d345 | ||
|
|
6bba9b6199 | ||
|
|
2f55d32485 | ||
|
|
eec37ecb31 | ||
|
|
f947ee6f22 | ||
|
|
3330d83d08 | ||
|
|
de7ed84fcf | ||
|
|
e639c72e8b | ||
|
|
43ea660d52 | ||
|
|
1f85d448e2 | ||
|
|
e7f168c373 | ||
|
|
b42698616a | ||
|
|
a00473314f | ||
|
|
2dabcb2419 | ||
|
|
d9ae171cc7 | ||
|
|
e4e334c77a | ||
|
|
78d3d224af | ||
|
|
f9b1354460 | ||
|
|
95e5ec8485 | ||
|
|
d050b55baa | ||
|
|
7964563b62 | ||
|
|
e01dc4066c | ||
|
|
c286f49097 | ||
|
|
4c81d9ec04 | ||
|
|
a928666dfc | ||
|
|
64ba19e589 | ||
|
|
3a42012ac7 | ||
|
|
08e5c0d930 | ||
|
|
18788ac1ca | ||
|
|
d55dda3127 | ||
|
|
d637147f25 | ||
|
|
c1ed23c967 | ||
|
|
46001619e8 | ||
|
|
7a6df7760b | ||
|
|
d2d779c68f | ||
|
|
bbc12e0029 | ||
|
|
125718bb94 | ||
|
|
35d67c6b42 | ||
|
|
14c471e4ca | ||
|
|
42ceb6edc0 | ||
|
|
5bce1d74ff | ||
|
|
b4404f698e | ||
|
|
e4625894c9 | ||
|
|
af87d80baa | ||
|
|
1f84c9113c | ||
|
|
0cf0a26a97 | ||
|
|
0d4b694208 | ||
|
|
c40394ffd6 | ||
|
|
20ffb2b8bc | ||
|
|
0af79eb84b | ||
|
|
e2e98149cb | ||
|
|
f55ab31ae5 | ||
|
|
61a65d01c7 | ||
|
|
7aa3b74c6f | ||
|
|
7647109fb6 | ||
|
|
ad0c17da56 | ||
|
|
93ca6b8d94 | ||
|
|
c85df75d53 | ||
|
|
e16093a264 | ||
|
|
a54c8139b1 | ||
|
|
8de79e37e9 | ||
|
|
c662ecdbb2 | ||
|
|
8f6f63e572 | ||
|
|
22c22aba1b | ||
|
|
de106f9d91 | ||
|
|
8a38766c02 | ||
|
|
3a16ad3221 | ||
|
|
ec402cb9b3 | ||
|
|
663bc2be8d | ||
|
|
df28e2dc7d | ||
|
|
79fe9e94c7 | ||
|
|
c2afb2dfab | ||
|
|
0d1ed0ec67 | ||
|
|
99526ebfc2 | ||
|
|
e6baace00d | ||
|
|
743155b06a | ||
|
|
0a67a8278f | ||
|
|
26800a8553 | ||
|
|
93165644af | ||
|
|
4db1ccc3fc | ||
|
|
06c4d644b7 | ||
|
|
b5fa21a57c | ||
|
|
ddbe5237fe | ||
|
|
18e17cf198 | ||
|
|
6a6772d5ed | ||
|
|
50042cea27 | ||
|
|
3ccf890a21 | ||
|
|
d57f6c81cb | ||
|
|
c07816c2a1 | ||
|
|
73da0a5136 | ||
|
|
d12b797ebe | ||
|
|
7df43d8553 | ||
|
|
b1047590e6 | ||
|
|
e3cf0fe0c1 | ||
|
|
940c8938f1 | ||
|
|
e75e07f73f | ||
|
|
940a4d225b | ||
|
|
7386441e61 | ||
|
|
718251c67c | ||
|
|
b6c5471d27 | ||
|
|
fa22b8220a | ||
|
|
a5c575444b | ||
|
|
4dce71a1fe | ||
|
|
ee00eb3481 | ||
|
|
5d44b1606d | ||
|
|
e732c76490 | ||
|
|
fb02051538 | ||
|
|
6f3853de59 | ||
|
|
8790c45edc | ||
|
|
49824aff93 | ||
|
|
492beb095f | ||
|
|
d11c4af4d1 | ||
|
|
82a7c8490e | ||
|
|
457c829b2d | ||
|
|
da7f3e5718 | ||
|
|
76786b2eae | ||
|
|
3a299cae98 | ||
|
|
dd4737cfe9 | ||
|
|
02416654b6 | ||
|
|
85c992a9f9 | ||
|
|
38da58e5e9 | ||
|
|
519b131792 | ||
|
|
be2eb57369 | ||
|
|
19554e6e8f | ||
|
|
68b7e7c082 | ||
|
|
7648f6e1eb | ||
|
|
289c633189 | ||
|
|
857bb8ac9e | ||
|
|
cf6ad0b8e0 | ||
|
|
782dc5754d | ||
|
|
cf88680a13 | ||
|
|
6293259225 | ||
|
|
a8678b8842 | ||
|
|
5993b842a0 | ||
|
|
78cef418a1 | ||
|
|
d56ba0cf9b | ||
|
|
72dffe12e5 | ||
|
|
2d353ef839 | ||
|
|
f26ef53c8c | ||
|
|
98b95b2ab2 | ||
|
|
bc8611a662 | ||
|
|
2ddfceca36 | ||
|
|
862babb8f5 | ||
|
|
61cea95697 | ||
|
|
1fc1e23fce | ||
|
|
76155232a3 | ||
|
|
fa9e9de032 | ||
|
|
a6bd2e7dba | ||
|
|
e58dc1d056 | ||
|
|
ddc14ae853 | ||
|
|
0d54b1a631 | ||
|
|
afc405ec02 | ||
|
|
6a9f6aa65a | ||
|
|
8f725c7c84 | ||
|
|
97ab0a2c2c | ||
|
|
ddd58c20aa | ||
|
|
489c465599 | ||
|
|
451dd0327f | ||
|
|
e1f826357d | ||
|
|
8a136dde55 | ||
|
|
cc9b0f8a73 | ||
|
|
3cada63f15 | ||
|
|
7fdcb22515 | ||
|
|
d7b5d3f60e | ||
|
|
24f82b1be5 | ||
|
|
708dc81b88 | ||
|
|
35f5275d88 | ||
|
|
9567144390 | ||
|
|
1a5607f278 | ||
|
|
7e25c148cc | ||
|
|
122713c39a | ||
|
|
070fd812b2 | ||
|
|
4156cd436d | ||
|
|
996852a506 | ||
|
|
2fb588357a | ||
|
|
c3a276cde3 | ||
|
|
661bf2a9e7 | ||
|
|
007a908e83 | ||
|
|
23b4ec992d | ||
|
|
726f66762b | ||
|
|
3b77ca5570 | ||
|
|
8c0304273c | ||
|
|
dc9b88dedb |
@@ -1,13 +1,22 @@
|
||||
# Dependencies
|
||||
node_modules
|
||||
**/node_modules
|
||||
.pnp
|
||||
.pnp.js
|
||||
|
||||
# Build outputs
|
||||
dist
|
||||
.next
|
||||
.turbo
|
||||
out
|
||||
# Patterns without a leading `**/` only match the build-context root, NOT
|
||||
# nested directories. In this monorepo the actual outputs live under
|
||||
# apps/*/{dist,.next,.turbo} and packages/*/{dist,.turbo}; without `**/`
|
||||
# any stale local builds (from running `yarn dev` or `yarn build` on the
|
||||
# host) get copied into the image and override the freshly-built outputs,
|
||||
# producing silently broken builds (MODULE_NOT_FOUND for whatever the stale
|
||||
# bundle still references).
|
||||
**/dist
|
||||
**/.next
|
||||
**/.turbo
|
||||
**/build
|
||||
**/out
|
||||
|
||||
# Development
|
||||
.env
|
||||
@@ -57,6 +66,7 @@ vitest.config.ts
|
||||
Dockerfile*
|
||||
docker
|
||||
!docker/nginx
|
||||
!docker/*.sh
|
||||
.dockerignore
|
||||
|
||||
# Misc
|
||||
|
||||
@@ -18,6 +18,20 @@ DASHBOARD_DOMAIN=app.example.com
|
||||
LANDING_DOMAIN=www.example.com
|
||||
WIKI_DOMAIN=docs.example.com
|
||||
|
||||
# For local development: URIs for running services locally
|
||||
# These are used by the applications at runtime
|
||||
API_URI=http://localhost:8080
|
||||
DASHBOARD_URI=http://localhost:3000
|
||||
LANDING_URI=http://localhost:4000
|
||||
WIKI_URI=http://localhost:1000
|
||||
|
||||
# NEXT_PUBLIC_* variables are used for client-side code and sitemap generation
|
||||
# Use placeholder URLs that will be replaced at Docker container runtime
|
||||
NEXT_PUBLIC_API_URI=https://next-api.useplunk.com
|
||||
NEXT_PUBLIC_DASHBOARD_URI=https://next-app.useplunk.com
|
||||
NEXT_PUBLIC_LANDING_URI=https://www.useplunk.com
|
||||
NEXT_PUBLIC_WIKI_URI=https://next-wiki.useplunk.com
|
||||
|
||||
# Set to 'true' if using HTTPS in production (behind a reverse proxy/load balancer)
|
||||
# This affects how application URIs are auto-generated from domain names
|
||||
USE_HTTPS=false
|
||||
@@ -38,6 +52,13 @@ SES_CONFIGURATION_SET=plunk-configuration-set
|
||||
# When set, projects can choose to disable email tracking
|
||||
SES_CONFIGURATION_SET_NO_TRACKING=plunk-no-tracking-configuration-set
|
||||
|
||||
# Custom MAIL FROM subdomain — used to construct `<subdomain>.<your-domain>`
|
||||
# when a domain is added. Defaults to `plunk`. Override when `plunk.<your-domain>`
|
||||
# is already used for something else (e.g. an R2/CDN custom domain), since the
|
||||
# MAIL FROM hostname needs MX + TXT records that can't coexist with a CNAME.
|
||||
# Example: MAIL_FROM_SUBDOMAIN=emails → emails.<your-domain>
|
||||
# MAIL_FROM_SUBDOMAIN=
|
||||
|
||||
# ========================================
|
||||
# OPTIONAL: OAuth Login
|
||||
# ========================================
|
||||
@@ -46,15 +67,6 @@ GITHUB_OAUTH_SECRET=
|
||||
GOOGLE_OAUTH_CLIENT=
|
||||
GOOGLE_OAUTH_SECRET=
|
||||
|
||||
# ========================================
|
||||
# OPTIONAL: Stripe Billing
|
||||
# ========================================
|
||||
STRIPE_SK=
|
||||
STRIPE_WEBHOOK_SECRET=
|
||||
STRIPE_PRICE_ONBOARDING=
|
||||
STRIPE_PRICE_EMAIL_USAGE=
|
||||
STRIPE_METER_EVENT_NAME=emails
|
||||
|
||||
# ========================================
|
||||
# OPTIONAL: File Storage (Minio)
|
||||
# ========================================
|
||||
@@ -131,6 +143,39 @@ SMTP_DOMAIN=smtp.example.com
|
||||
# Default: true
|
||||
# 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
|
||||
|
||||
# ========================================
|
||||
# OPTIONAL: SES Sending Rate
|
||||
# ========================================
|
||||
# Caps the email-worker's send rate (messages per second) for the SES sandbox or
|
||||
# manually-throttled accounts. When unset, the worker probes the AWS account at
|
||||
# startup via ses:GetSendQuota; if that call is denied or transiently fails,
|
||||
# the worker silently falls back to 14/sec which may exceed sandbox limits and
|
||||
# trigger SES throttling errors. Set this explicitly to avoid the silent fallback.
|
||||
# Default: unset (auto-detect, falls back to 14)
|
||||
# EMAIL_RATE_LIMIT_PER_SECOND=1
|
||||
|
||||
# Number of emails the worker processes in parallel. When unset, concurrency is
|
||||
# derived from the effective rate limit (~ rate * 0.5, min 5, capped by
|
||||
# EMAIL_WORKER_MAX_CONCURRENCY) so a higher SES quota translates into higher
|
||||
# throughput automatically. Pin this only when the Prisma pool or memory is the
|
||||
# binding constraint.
|
||||
# Default: unset (auto-derived)
|
||||
# EMAIL_WORKER_CONCURRENCY=10
|
||||
|
||||
# Upper bound applied to the auto-derived concurrency. Raise this when your SES
|
||||
# quota is high AND the Prisma connection pool has been sized for it.
|
||||
# Default: 50
|
||||
# EMAIL_WORKER_MAX_CONCURRENCY=50
|
||||
|
||||
# ========================================
|
||||
# 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.
|
||||
@@ -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
|
||||
@@ -65,6 +65,18 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: yarn install --frozen-lockfile
|
||||
|
||||
- name: Tune Postgres for ephemeral CI workload
|
||||
env:
|
||||
PGPASSWORD: postgres
|
||||
run: |
|
||||
# synchronous_commit=off is the biggest single I/O win and is safe to lose
|
||||
# data on crash for a throwaway CI database.
|
||||
# synchronous_commit is dynamic — applies on reload. max_connections would
|
||||
# require a restart, so we leave it at the default of 100 and cap workers
|
||||
# at 4 × connection_limit=20 = 80 to stay under that budget.
|
||||
psql -h localhost -U postgres -d plunk_test -c "ALTER SYSTEM SET synchronous_commit = 'off';"
|
||||
psql -h localhost -U postgres -d plunk_test -c "SELECT pg_reload_conf();"
|
||||
|
||||
- name: Setup environment variables
|
||||
run: |
|
||||
cat > .env << EOF
|
||||
@@ -103,7 +115,7 @@ jobs:
|
||||
EOF
|
||||
|
||||
- name: Build shared packages
|
||||
run: yarn build --filter="@plunk/shared" --filter="@plunk/db"
|
||||
run: yarn build --filter="@plunk/db" --filter="@plunk/types" --filter="@plunk/shared"
|
||||
|
||||
- name: Generate Prisma Client
|
||||
run: yarn workspace @plunk/db db:generate
|
||||
@@ -188,7 +200,7 @@ jobs:
|
||||
EOF
|
||||
|
||||
- name: Build shared packages
|
||||
run: yarn build --filter="@plunk/shared" --filter="@plunk/db"
|
||||
run: yarn build --filter="@plunk/db" --filter="@plunk/types" --filter="@plunk/shared"
|
||||
|
||||
- name: Run linter
|
||||
run: yarn lint
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
## Design Context
|
||||
|
||||
### Users
|
||||
Developer-founders and indie hackers building SaaS products. They use Plunk to handle transactional and marketing email without the complexity of tools like Mailchimp or Customer.io. They notice tiny details — inconsistent spacing, placeholder text that adds no value, a button that doesn't communicate state. Context: professional environment, desktop-first.
|
||||
|
||||
### Brand Personality
|
||||
Sharp, minimal, confident. The product earns trust by being simple and correct, not by being flashy. Testimonials emphasize "transparent UI", "easy setup", "clean design" — the brand is *care without noise*.
|
||||
|
||||
### Aesthetic Direction
|
||||
Light mode only. Palette: black (`neutral-900`), neutral grays, white. No accent colors. No color for decoration — only for semantics (red = error, green = success). Backgrounds are near-white with subtle texture. Cards use white with a neutral border and light shadow. Typography should feel precise and legible, not editorial. Spacing should feel considered, not generous.
|
||||
|
||||
### Design Principles
|
||||
1. **Every pixel earns its place.** If something doesn't communicate information or provide affordance, remove it.
|
||||
2. **Neutral by default, semantic by exception.** Color is reserved for error/success/warning states, not decoration.
|
||||
3. **Interaction should feel fast.** Loading states communicate exactly what's happening. No silent actions.
|
||||
4. **Developer-grade precision.** Copy is short and direct. Placeholders only appear when they add value. Labels are unambiguous.
|
||||
5. **Consistency is trust.** The same pattern everywhere. One way to show errors. One way to show success. No creative variation in functional UI.
|
||||
@@ -1,3 +1,3 @@
|
||||
{
|
||||
".": "0.2.0"
|
||||
".": "0.11.0"
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ nodeLinker: node-modules
|
||||
|
||||
# Support multiple architectures - download pre-built binaries instead of compiling
|
||||
supportedArchitectures:
|
||||
os: [ "linux", "darwin" ]
|
||||
os: [ "linux", "darwin", "win32" ]
|
||||
cpu: [ "x64", "arm64" ]
|
||||
libc: [ "glibc" ]
|
||||
|
||||
|
||||
@@ -1,5 +1,344 @@
|
||||
# Changelog
|
||||
|
||||
## [0.11.0](https://github.com/useplunk/plunk/compare/v0.10.0...v0.11.0) (2026-05-13)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* Ability to change subscription status in workflows ([fadc19d](https://github.com/useplunk/plunk/commit/fadc19d139084550eb442a8b8368edcd6075cad0))
|
||||
* add 'notTriggeredWithin' operator to segment filters for enhanced event tracking ([0f00ca1](https://github.com/useplunk/plunk/commit/0f00ca1b8c9bd95f2158af845218ef432ab0d498))
|
||||
* add external link to edit email templates in SendEmailStepDialog and WorkflowBuilder ([4ba43dd](https://github.com/useplunk/plunk/commit/4ba43dd3b64776413f813e091f527aa3e56bfc84))
|
||||
* add Markdown cut link to footer and page for improved accessibility ([ccd516e](https://github.com/useplunk/plunk/commit/ccd516e4e882921fb1a8a3e87c47710e51e35311))
|
||||
* add project switching functionality to command palette ([5724ab9](https://github.com/useplunk/plunk/commit/5724ab9536ea4e3bb4e916e963b1f39ba51bb7f3))
|
||||
* add sanitize-html for improved email content sanitization ([735acff](https://github.com/useplunk/plunk/commit/735acff45423cb537f7aa636b9a9d31830775f93))
|
||||
* add search functionality to campaigns list with debounce effect ([d114950](https://github.com/useplunk/plunk/commit/d11495061d907bcee699d56987784fa7ebe31bf6))
|
||||
* add segment membership operators and enhance segment filter functionality ([a3cc622](https://github.com/useplunk/plunk/commit/a3cc62213f40f6a9341113b73b52852292fb9a10))
|
||||
* add SwitchOffer component to promote switching from competitors for enhanced user engagement ([6195b39](https://github.com/useplunk/plunk/commit/6195b39f3dbdd9fe783b79f9ae7f7942509a49a0))
|
||||
* add workflow duplication functionality with API endpoint and UI button ([c6340a1](https://github.com/useplunk/plunk/commit/c6340a1dc7385723d4ec30779340218935d814e6))
|
||||
* enhance campaign scheduling and audience settings UI for better clarity and usability ([7658a59](https://github.com/useplunk/plunk/commit/7658a59b5df4e325ad9eca37356cad3cbb70e942))
|
||||
* implement bulk contact action selector for improved flexibility in bulk operations ([de6335e](https://github.com/useplunk/plunk/commit/de6335e99999242f81e9eda9a20aeccab80a2de4))
|
||||
* implement caching for recent activity count to optimize performance and reduce database load ([f22da4a](https://github.com/useplunk/plunk/commit/f22da4add1e455678f380aba8c2fd02012ef6457))
|
||||
* implement early fraud warning handling in webhooks ([48425d1](https://github.com/useplunk/plunk/commit/48425d1df160a3fd5edb4cbdcc9e6725628db319))
|
||||
* make MAIL FROM subdomain configurable via MAIL_FROM_SUBDOMAIN env ([463301b](https://github.com/useplunk/plunk/commit/463301b5db27b08b483db3c56a992ac62d6653b8))
|
||||
* make MAIL FROM subdomain configurable via MAIL_FROM_SUBDOMAIN env var ([e0bf0f6](https://github.com/useplunk/plunk/commit/e0bf0f628af2a155ca3bbc38ef5c2f4ecc0455e6))
|
||||
* refactor template editing layout for improved usability and clarity ([aaf5ac6](https://github.com/useplunk/plunk/commit/aaf5ac65307266a4d9deb02986b610757e929b49))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* enhance campaign finalization process to handle pending emails and ensure accurate status updates ([2529c9b](https://github.com/useplunk/plunk/commit/2529c9b4282b003a94013259119e98654ae22b46))
|
||||
* enhance email content parsing and logging for better debugging ([4587e9d](https://github.com/useplunk/plunk/commit/4587e9d670fa3a27fbc1ca7669c8fc75d804e85e))
|
||||
* enhance project name validation to exclude invisible and decorative characters ([29883ff](https://github.com/useplunk/plunk/commit/29883ffc7104d4beb13965bfa65ea609367ede69))
|
||||
* enhance Quick Start card layout for improved responsiveness and usability ([649bbf6](https://github.com/useplunk/plunk/commit/649bbf6d6b9db5139295a455c69425a5565d4323))
|
||||
* handle undefined path in footer component for improved stability ([715961c](https://github.com/useplunk/plunk/commit/715961c007e450731434e5f343acff0debd6a851))
|
||||
* implement mergeContactData method for efficient contact data updates ([a27d564](https://github.com/useplunk/plunk/commit/a27d564e1af6e5cf72c9ef405650f2475bfd0c86))
|
||||
* improve iframe height adjustment logic in EmailEditor component ([9e4aa94](https://github.com/useplunk/plunk/commit/9e4aa9443b53ef38a3af1b269f4a949dd57e758f))
|
||||
* pass DISABLE_SIGNUPS and EMAIL_RATE_LIMIT_PER_SECOND through compose; trim .env.self-host.example ([8a26d60](https://github.com/useplunk/plunk/commit/8a26d605b4aa5fdea0e02a17159c1cae478a7e47))
|
||||
* pass missing env variables from .env.self-host.example to plunk service ([f178c59](https://github.com/useplunk/plunk/commit/f178c59b5bc461f9ba57dc6f0bac9617feaab4a3))
|
||||
* replace font loading method with utility function for improved performance ([ba23a1c](https://github.com/useplunk/plunk/commit/ba23a1c6fa70ca6fa0343391fa8d642155ad45c2))
|
||||
* update activity item colors and backgrounds for improved visual distinction ([e43f70d](https://github.com/useplunk/plunk/commit/e43f70d8a135b048d4e9ed013ffa25f1b2f89687))
|
||||
* update middleware matcher to exclude webmanifest files ([cbb3bff](https://github.com/useplunk/plunk/commit/cbb3bffcf4f789e9c36912c9b0ce0ba9f6a1d4dd))
|
||||
* update not found handling in GET route to return 404 response ([7615b62](https://github.com/useplunk/plunk/commit/7615b62945aa1939bf6a5b3638c232509090de60))
|
||||
* update segment filter logic to retain value and unit, enhance activity name mapping ([d1f357c](https://github.com/useplunk/plunk/commit/d1f357c300c7798d5c8d521e1219e39e7da821dd))
|
||||
* update segment filter logic to retain value and unit, enhance activity name mapping ([a126563](https://github.com/useplunk/plunk/commit/a1265635420e66b7cdef02a7136fdf9c3aec4418))
|
||||
* update TemplateSearchPicker to maintain selected template name on change ([2ea1802](https://github.com/useplunk/plunk/commit/2ea1802290a4378d68e3878a44e502ea8541b301))
|
||||
|
||||
|
||||
### Code Refactoring
|
||||
|
||||
* convert forwardRef components to function components for consistency ([361ec0b](https://github.com/useplunk/plunk/commit/361ec0b1eb17647696656c6a6d4cddd5b9348b45))
|
||||
* implement step dialog components for workflow editing ([ed9027b](https://github.com/useplunk/plunk/commit/ed9027b4ef9c37e91c69ed5a90d5b74c08c7a054))
|
||||
* remove unused .png files ([2d05c3f](https://github.com/useplunk/plunk/commit/2d05c3fbc1ded87880a307943bb93106b18cd406))
|
||||
|
||||
|
||||
### Documentation
|
||||
|
||||
* expand documentation with new sections on importing contacts, unsubscribe pages, and API key management ([4ddafdc](https://github.com/useplunk/plunk/commit/4ddafdc0419389818de7e45eb4a0c82c2e9382eb))
|
||||
* update README to clarify self-hosted alternative and add inbound emails feature ([80ef65e](https://github.com/useplunk/plunk/commit/80ef65e04b8c362f05ae5b7d5710b398a150cce5))
|
||||
|
||||
## [0.10.0](https://github.com/useplunk/plunk/compare/v0.9.0...v0.10.0) (2026-05-01)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add className prop to EmptyState component for custom styling ([c278a0f](https://github.com/useplunk/plunk/commit/c278a0fd944977d4ea3a0c5a4a43ff4cc0a13aa3))
|
||||
* add configurable attachment limits for email service ([2eb4079](https://github.com/useplunk/plunk/commit/2eb407993bd5fed3e74be73445185e517c18b994)), closes [#358](https://github.com/useplunk/plunk/issues/358)
|
||||
* add middleware support for .md file rewrites ([0b3aa28](https://github.com/useplunk/plunk/commit/0b3aa28101d50a734945ce19b924f9aa30631c64))
|
||||
* add updateActiveProject function for in-place project updates ([6f31fa2](https://github.com/useplunk/plunk/commit/6f31fa2503b11e3a9a37d753086bbb74b42f7bc4))
|
||||
* enhance contact addition with bulk email lookup and subscription options ([bb72911](https://github.com/useplunk/plunk/commit/bb72911fa25e3a204095e74c07efbc261154ac30))
|
||||
* enhance contact data handling by filtering empty strings and allowing null to delete fields ([1094651](https://github.com/useplunk/plunk/commit/10946511b019ff76ce5f785a39cc0db4ea9ce820))
|
||||
* Enhance ease of use of workflow editor ([c910d20](https://github.com/useplunk/plunk/commit/c910d20bb71ff5de4abf95f3f96be9c435342cb4))
|
||||
* implement CommandPalette for enhanced navigation and recent pages tracking ([1c89ed0](https://github.com/useplunk/plunk/commit/1c89ed083e49148967713e9a9c2f7f8833db07c4))
|
||||
* implement meter event processing with queue for Stripe billing ([e048fc1](https://github.com/useplunk/plunk/commit/e048fc157080b36f40fbfc4440db51367a2d374b))
|
||||
* implement phishing detection using OpenRouter API with configurable sampling rate ([2da8b06](https://github.com/useplunk/plunk/commit/2da8b065d08438aa2adea397d8ab2a560e996af6))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Add in-memory cache for lower-confidence phishing checks ([208c809](https://github.com/useplunk/plunk/commit/208c809a90d0721261e643523b338d05e23e2bf9))
|
||||
* add new configuration options for phishing detection thresholds ([c0e0ad8](https://github.com/useplunk/plunk/commit/c0e0ad8bc6bfdddea5193191156d18aad440c2b0))
|
||||
* add project name and sender email parameters to phishing content check ([1637d54](https://github.com/useplunk/plunk/commit/1637d54e1b132dd6864fb1c50d23a388c1c47bf5))
|
||||
* add project name and sender email parameters to phishing content check ([15294a4](https://github.com/useplunk/plunk/commit/15294a40d88289fa8fd876c9e7c201eb1e2ca956))
|
||||
* Consistency across buttons and labels ([c1bcd35](https://github.com/useplunk/plunk/commit/c1bcd358cc611594d851414687c04bf7a03759a1))
|
||||
* Consistency across cards ([517753c](https://github.com/useplunk/plunk/commit/517753c420204510e06decec01db7749894a9265))
|
||||
* Content negotiation for xml and txt ([c8190b9](https://github.com/useplunk/plunk/commit/c8190b953f9f2e28e6cfa98e72d8dcfbba7e251b))
|
||||
* Harmonize rings and hover states ([f40cc86](https://github.com/useplunk/plunk/commit/f40cc86cec661899fb862b56ce3e35bf70b33e54))
|
||||
* improve layout and accessibility of workflow header and buttons ([ab3edd7](https://github.com/useplunk/plunk/commit/ab3edd7dc9030eeb770ffd64087476adf10d2d06))
|
||||
* log message for projects passing phishing checks ([8628754](https://github.com/useplunk/plunk/commit/862875428d21de03643e8e51126cc59abef95ccb))
|
||||
* prevent unnecessary state updates in search input effect ([98f1e80](https://github.com/useplunk/plunk/commit/98f1e80fca8253c125ba24c4d84c5be86841e1fa))
|
||||
* reconcile totalRecipients in CampaignService to prevent stuck campaigns ([4322de9](https://github.com/useplunk/plunk/commit/4322de929a84279370bedcbb4f6b7dcd81145aea)), closes [#348](https://github.com/useplunk/plunk/issues/348)
|
||||
* **ses:** emit List-Unsubscribe inside the header section, not the body ([11c428d](https://github.com/useplunk/plunk/commit/11c428d4ffe7c8aa87aac4d24148aaa95e01507a))
|
||||
* standardize step type labels and update visual styles in workflow components ([bdc9b30](https://github.com/useplunk/plunk/commit/bdc9b30ef29396870aa42515b8e688485a4673e8))
|
||||
* Sync display name in TemplateSearchPicker when initialName changes ([3649392](https://github.com/useplunk/plunk/commit/3649392b475271198cd61295091e8acf708efa25))
|
||||
* Sync display name in TemplateSearchPicker when initialName changes ([cbde3cc](https://github.com/useplunk/plunk/commit/cbde3cce3fcee382dae04e79a9480e67ad896725))
|
||||
* turn warning into success log ([b7eb254](https://github.com/useplunk/plunk/commit/b7eb2549d433552f32783b6fb8c192f5afb48ecd))
|
||||
* update phishing confidence threshold to 95% ([bb78c86](https://github.com/useplunk/plunk/commit/bb78c86c400b60fb0e84c7872e20ad6f7c43c199))
|
||||
* update project disabled messages for clarity and consistency ([d7eb85f](https://github.com/useplunk/plunk/commit/d7eb85ffdd99177c5e27104779281f5a08fe36a7))
|
||||
* update project icon colors for improved visibility and consistency ([5f741c6](https://github.com/useplunk/plunk/commit/5f741c66c7f0c9c25c45b26917ff68529d15f958))
|
||||
* update response format for phishing analysis and improve JSON parsing comment ([91d0d2d](https://github.com/useplunk/plunk/commit/91d0d2d297cb38fe0dfdfd7f73df355e2f51096a))
|
||||
|
||||
## [0.9.0](https://github.com/useplunk/plunk/compare/v0.8.0...v0.9.0) (2026-04-20)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* Add accept/markdown to apps/landing ([df76be1](https://github.com/useplunk/plunk/commit/df76be1b87de14769a219ae0e6c99711edf993a1))
|
||||
* Add emailId field to webhook events for better correlation with send requests ([ae64c2d](https://github.com/useplunk/plunk/commit/ae64c2dbb5b76f16b562641953f262d76ea0d8e8)), closes [#344](https://github.com/useplunk/plunk/issues/344)
|
||||
* Add headless template type ([fb5aa87](https://github.com/useplunk/plunk/commit/fb5aa8796a8550be7a70fdd91616c9a41ed3047d))
|
||||
* Add onboarding flow ([bd5a085](https://github.com/useplunk/plunk/commit/bd5a0858021b9d74fae07cca5d2a0b8c10deabd7))
|
||||
* Add type to campaign ([d24259e](https://github.com/useplunk/plunk/commit/d24259e8d202edd1b8c7771a63cc212c982b52e1))
|
||||
* Block domain changes for disabled projects with appropriate error handling ([44c8657](https://github.com/useplunk/plunk/commit/44c86572c275221b5068605c64958f43a1f96ff4))
|
||||
* Disable projects on failed payment ([3343e89](https://github.com/useplunk/plunk/commit/3343e891bdbcfee7d17d73a0d7fb181652e7c262))
|
||||
* Enhance email processing to include parsed HTML body content in inbound email records ([e339508](https://github.com/useplunk/plunk/commit/e3395083db11fdb4b6cfdbace46518792ec132a3)), closes [#342](https://github.com/useplunk/plunk/issues/342)
|
||||
* Enhance login forms with last used authentication method ([f2ebce0](https://github.com/useplunk/plunk/commit/f2ebce0ef2ac9c9c4e994cb754f67f6fa8a3f465))
|
||||
* Enhance security metrics handling with new thresholds and improved messaging ([c0b2aba](https://github.com/useplunk/plunk/commit/c0b2abaeca5656743e189f975ab82ff9b25b577b))
|
||||
* implement AWS SNS signature verification in SecurityService ([b79d416](https://github.com/useplunk/plunk/commit/b79d4166671cc04cc1458d2c24af262af0e16c9e))
|
||||
* integrate DOMPurify for sanitizing HTML content ([bf12392](https://github.com/useplunk/plunk/commit/bf12392b88fc92b0760333e1b568e3d6d1b6ed74))
|
||||
* Update new project bounce thresholds for stricter email handling ([5e62f51](https://github.com/useplunk/plunk/commit/5e62f517fc896849c270e795cd31a110b83707cc))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Enhance email processing to support campaign types and improve unsubscribe logic ([9e2400c](https://github.com/useplunk/plunk/commit/9e2400c6de6f13c498f02c489f956ebf89de36b0))
|
||||
* Hint custom event names in combobox when no matches are found ([3214f6c](https://github.com/useplunk/plunk/commit/3214f6c42d4ca6ab628e905ac69ed82648ccf47c))
|
||||
* Implement content negotiation for markdown and html in middleware ([37ed1e4](https://github.com/useplunk/plunk/commit/37ed1e49b78eb9339e7b62fd2fd5b60d451707d6))
|
||||
* Implement SSRF protection in webhook handling with safeFetch method ([2c5a715](https://github.com/useplunk/plunk/commit/2c5a71518da358927bd5e41035b85fd278790b47))
|
||||
* Refactor date filtering logic for pagination in ActivityFeed and ActivityService ([52cb2b6](https://github.com/useplunk/plunk/commit/52cb2b6c77bc3912b356887bdd48e9c8b9b1728a))
|
||||
* Update language validation regex to support locale variants ([7834b9e](https://github.com/useplunk/plunk/commit/7834b9e7ef615ba029a1a091b0c37c8f40eb543c))
|
||||
|
||||
|
||||
### Documentation
|
||||
|
||||
* Add content negotiation to apps/wiki ([545d733](https://github.com/useplunk/plunk/commit/545d7337948f41f006f9cb0270b4bfff2b08ed2c))
|
||||
|
||||
## [0.8.0](https://github.com/useplunk/plunk/compare/v0.7.1...v0.8.0) (2026-03-31)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* Add multi-branch workflow conditions (switch/case) ([92949b7](https://github.com/useplunk/plunk/commit/92949b7596740b73d04c30e0e2bcc6305bbdf4a7))
|
||||
* **i18n:** add Chinese translations (zh-TW, zh-HK, zh-CN) ([33df563](https://github.com/useplunk/plunk/commit/33df5632a3d4068e641687c8d404a6eef4aa4d0e))
|
||||
* **i18n:** add Italian translation ([7b6872c](https://github.com/useplunk/plunk/commit/7b6872c4b79b0fde4491f02851a2049c846c83d6))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Adapt SNS Webhook validation regex pattern to also support AWS eusc partition ([7b6540a](https://github.com/useplunk/plunk/commit/7b6540a748a90c10f41b931450ac809e7ae23c01))
|
||||
* add alt text to email badge image ([3b39d84](https://github.com/useplunk/plunk/commit/3b39d847cd278317723b4b226434c26c49becebe))
|
||||
* broken links to next-wiki.useplunk.com ([e3ea5fb](https://github.com/useplunk/plunk/commit/e3ea5fb6dcea95b5028f140b77e54d5938497223))
|
||||
* Connect branches smoothly to original node ([2c3e897](https://github.com/useplunk/plunk/commit/2c3e8970cbc4ad2eb39fd505a4292345c6cae1c0))
|
||||
* Enhance email step configuration validation and recipient handling ([b50b5af](https://github.com/useplunk/plunk/commit/b50b5af763d8a44b09c7022e1d9135bfca7907f6))
|
||||
* Enhance email step configuration validation and recipient handling ([a99cde8](https://github.com/useplunk/plunk/commit/a99cde88392450bf719112cb94cc1b9e7c7c1478))
|
||||
* normalize field references and handle undefined values in JSON ([b9d692c](https://github.com/useplunk/plunk/commit/b9d692cf5b491ab22a40ec69e77ff7bdc62eec63))
|
||||
* Prevent switching if nodes are attached to multi-branch ([c32b54f](https://github.com/useplunk/plunk/commit/c32b54f588db79a501db456e6075a337dee8ed26))
|
||||
* update old references to next.useplunk.com ([44987d2](https://github.com/useplunk/plunk/commit/44987d2b5e8028c6f8f26c39e9dec386e1ccf6e1))
|
||||
* visual editor preview ([4451e92](https://github.com/useplunk/plunk/commit/4451e921caff45dab126006ba103d91816bed696))
|
||||
|
||||
|
||||
### Documentation
|
||||
|
||||
* Fix broken links on api overview page ([dc2ce02](https://github.com/useplunk/plunk/commit/dc2ce02d1a4e4d1641728b720ca856cedba719a7))
|
||||
* Improve self-hosting env variable documentation ([f0ef346](https://github.com/useplunk/plunk/commit/f0ef34646e7593f07a780141e14d6d2b735c1101))
|
||||
|
||||
## [0.7.1](https://github.com/useplunk/plunk/compare/v0.7.0...v0.7.1) (2026-03-10)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Align preview and actual email for templates and campaigns ([cc7fcdb](https://github.com/useplunk/plunk/commit/cc7fcdb4ef31e9dfb4f7403aa93479b6df56719d))
|
||||
|
||||
|
||||
### Documentation
|
||||
|
||||
* Add inbound to docs ([6c4cc29](https://github.com/useplunk/plunk/commit/6c4cc295b88db6da8d9edcf23064a3fc8e9f5c36))
|
||||
* Improve webhook documentation ([f6a32ce](https://github.com/useplunk/plunk/commit/f6a32ce610559050c1ca9978607bd57ac51e906f))
|
||||
|
||||
## [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)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* Add cooldown to resend verification email ([457c829](https://github.com/useplunk/plunk/commit/457c829b2d59debc41ac69f907f758dd5ded1c1a))
|
||||
* Add email verification on signup ([fb02051](https://github.com/useplunk/plunk/commit/fb02051538029d8a6b806ce69b25fb9e75622693))
|
||||
* Add forwarding domains as verification check ([e732c76](https://github.com/useplunk/plunk/commit/e732c76490e015b87a9165a98f1f1b5084552f84))
|
||||
* Add id as reserved field in templates, campaigns and workflows ([7386441](https://github.com/useplunk/plunk/commit/7386441e6137ac9f059a3818895f1b1059e2d99d))
|
||||
* Add platform emails for domain verification and expiration ([19554e6](https://github.com/useplunk/plunk/commit/19554e6e8f94fbcf74006017454aa83a707617ea))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Add better validation for sender email ([e75e07f](https://github.com/useplunk/plunk/commit/e75e07f73f5928ded281d2704b0fd06fedeb9077))
|
||||
* Catch unknown content-type headers ([a5c5754](https://github.com/useplunk/plunk/commit/a5c575444ba698624b3932b4d6414c5ad9df282a))
|
||||
* Check email volume for 7-day window ([492beb0](https://github.com/useplunk/plunk/commit/492beb095fd7be0cfd3de9761420d7ce1170d56f))
|
||||
* Copy types build files ([49824af](https://github.com/useplunk/plunk/commit/49824aff93c7ce09caa0cb57cfef68ae296f6626))
|
||||
* Enhance CORS handling to allow requests with rejection logging ([718251c](https://github.com/useplunk/plunk/commit/718251c67c876352a5dfca7592613e33f6713061))
|
||||
* Migrate over to new pagination format in dashboard ([8790c45](https://github.com/useplunk/plunk/commit/8790c45edc1374f9649b8438563fc8844a645367))
|
||||
* Reentry into segment not working after exit ([4dce71a](https://github.com/useplunk/plunk/commit/4dce71a1fe22774391bf0d0e87f1564c3b93b496))
|
||||
* Refactor CORS handling to allow unrestricted access for public API endpoints ([940c893](https://github.com/useplunk/plunk/commit/940c8938f163879da5be205bcc8bb82ecd69279a))
|
||||
* Update sentCount on campaign sent for correct overview stats ([ee00eb3](https://github.com/useplunk/plunk/commit/ee00eb34811270473d1f79729853eaada883a477))
|
||||
* Update template fetching to use Template type and simplify body access ([b6c5471](https://github.com/useplunk/plunk/commit/b6c5471d272e8ba835282691946a418385896c98))
|
||||
* Update templates data fetching to use PaginatedResponse type ([fa22b82](https://github.com/useplunk/plunk/commit/fa22b8220a909e7234948aeeb2a6734ae51aeec9))
|
||||
|
||||
|
||||
### Documentation
|
||||
|
||||
* Add more details about personalisation ([940a4d2](https://github.com/useplunk/plunk/commit/940a4d225b86ba5af5377851ab758a43b3aa71ff))
|
||||
|
||||
## [0.3.0](https://github.com/useplunk/plunk/compare/v0.2.0...v0.3.0) (2025-12-29)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* Ability to overwrite locale on contact level with locale key on data ([7615523](https://github.com/useplunk/plunk/commit/76155232a3383e75e8c7b44a498454b07472852a))
|
||||
* Add additional banner and information about security metrics ([bc8611a](https://github.com/useplunk/plunk/commit/bc8611a66250eb7747e7acd6e882a740c0028ba1))
|
||||
* Add bulk actions to contact overview ([726f667](https://github.com/useplunk/plunk/commit/726f66762b890c73041139432524d6c85d6bd709))
|
||||
* Add email verification and password reset ([1a5607f](https://github.com/useplunk/plunk/commit/1a5607f2780d5a4692492032dd0cd2e7521362d9))
|
||||
* Add email verification endpoint at /v1/verify ([6a9f6aa](https://github.com/useplunk/plunk/commit/6a9f6aa65a3219c5d4d6f33253cdcf145c3ff20b))
|
||||
* Add plus address check to /v1/verify ([afc405e](https://github.com/useplunk/plunk/commit/afc405ec028ac9d7333a7817c49f1232278fc28b))
|
||||
* Add project-scoped language for unsubscribe footer and contact-facing pages ([e1f8263](https://github.com/useplunk/plunk/commit/e1f826357d1e8cff7bd3c2811698734f578836f5))
|
||||
* Allow to pick currency when starting subscription ([8a136dd](https://github.com/useplunk/plunk/commit/8a136dde55fd1fae1f2a2e285019beb35fc75977))
|
||||
* Email preview in contact and activity feed ([72dffe1](https://github.com/useplunk/plunk/commit/72dffe12e53ff9d74ef43da2cf653d31e7a4df25))
|
||||
* **i18n:** add German translations and update supported languages ([a6bd2e7](https://github.com/useplunk/plunk/commit/a6bd2e7dba261a858eab6ab1f782ddc9efb136a5))
|
||||
* **i18n:** add Hindi translations for contact-facing pages ([ddc14ae](https://github.com/useplunk/plunk/commit/ddc14ae8534eda2e1368f148e0434388008bb7b5)), closes [#246](https://github.com/useplunk/plunk/issues/246)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Add styling for visual editor emails in preview ([5993b84](https://github.com/useplunk/plunk/commit/5993b842a0f17d66644aaa3057602ae8f3daebc2))
|
||||
* Correctly reserve fields from being set on contact ([61cea95](https://github.com/useplunk/plunk/commit/61cea95697ccb56c525002b08f76bf57da896837))
|
||||
* Date filtering not working properly for custom contact data ([97ab0a2](https://github.com/useplunk/plunk/commit/97ab0a2c2c811ac1b8a2b9039ab835e837a3f3be))
|
||||
* Do not check verification if platform emails are not enabled ([9567144](https://github.com/useplunk/plunk/commit/9567144390512173f7f615db71368c1cd26d9f4d))
|
||||
* Import no longer case-sensitive about email column ([451dd03](https://github.com/useplunk/plunk/commit/451dd0327f4866fd27343407a84a6c979cfcd70d))
|
||||
* Pass through email verification if auth type is apiKey ([d7b5d3f](https://github.com/useplunk/plunk/commit/d7b5d3f60ed1af6ca9bf8e2a659204a01ca3acb0))
|
||||
* Persistence of subscription state for existing contacts ([007a908](https://github.com/useplunk/plunk/commit/007a908e833cdd1b229f485c34c17c6510a55f9c))
|
||||
* Properly tag events in SegmentFilterBuilder.tsx ([8f725c7](https://github.com/useplunk/plunk/commit/8f725c7c84749eca5647fdbd19d41260f6998d6e))
|
||||
* Redirect verification link to dashboard instead of landing ([35f5275](https://github.com/useplunk/plunk/commit/35f5275d889b167e0fe75246b29a4ffa632bad46))
|
||||
* Set auth type before disable check ([862babb](https://github.com/useplunk/plunk/commit/862babb8f5ab47599ce6a841fc988fafa1ec0bbe))
|
||||
* Variable substitution in transactional emails ([8c03042](https://github.com/useplunk/plunk/commit/8c0304273c2bd1a64718ec56838632aa63447ef8))
|
||||
|
||||
|
||||
### Documentation
|
||||
|
||||
* Add locale overwrite to project documentation ([1fc1e23](https://github.com/useplunk/plunk/commit/1fc1e23fce69a870ccf95faf2fff644733de7145))
|
||||
* Add plus address check to /v1/verify ([0d54b1a](https://github.com/useplunk/plunk/commit/0d54b1a631415a15e504ff5bd4573ddb12cc421a))
|
||||
* Improve docs with core-concept and guides ([2ddfcec](https://github.com/useplunk/plunk/commit/2ddfceca3606b0d4d832f83fce14c7277b5eaa35))
|
||||
* Update openapi.json to match actual API outputs ([dc9b88d](https://github.com/useplunk/plunk/commit/dc9b88dedb75535814239b4bc73f62375570998b))
|
||||
|
||||
## [0.2.0](https://github.com/useplunk/plunk/compare/v0.1.1...v0.2.0) (2025-12-16)
|
||||
|
||||
|
||||
|
||||
@@ -64,10 +64,10 @@ to run them separately (e.g., for debugging), use `dev:server` and `dev:worker`
|
||||
### Applications (`apps/`)
|
||||
|
||||
- **api**: Express.js API server with TypeScript (ESM), uses @overnightjs/core
|
||||
- HTTP API endpoints for the platform
|
||||
- Background cron jobs (workflow processor, domain verification)
|
||||
- **Worker process** (separate): BullMQ worker for processing email, campaign, and workflow queues
|
||||
- **web**: Next.js app (Pages Router) - Main platform (app.useplunk.com)
|
||||
- HTTP API endpoints for the platform
|
||||
- Background cron jobs (workflow processor, domain verification)
|
||||
- **Worker process** (separate): BullMQ worker for processing email, campaign, and workflow queues
|
||||
- **web**: Next.js app (Pages Router) - Main platform (next-app.useplunk.com)
|
||||
- **landing**: Next.js app (Pages Router) - Marketing site (www.useplunk.com)
|
||||
- **wiki**: Next.js app - Documentation site (docs.useplunk.com)
|
||||
|
||||
@@ -108,6 +108,7 @@ between groups.
|
||||
- Consistent type imports preferred: `import type { ... }`
|
||||
- Unused vars allowed with `_` prefix
|
||||
- Strict type checking enabled across all packages
|
||||
- Try to avoid inline types in favor of shared types in `@plunk/types`
|
||||
|
||||
### Component Structure
|
||||
|
||||
@@ -147,6 +148,22 @@ 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)
|
||||
- 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)
|
||||
- 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
|
||||
- Attachment Limits (optional):
|
||||
- `MAX_ATTACHMENT_SIZE_MB` (default: 10) - Maximum total attachment size in megabytes per email. AWS SES supports up to 40 MB.
|
||||
- `MAX_ATTACHMENTS_COUNT` (default: 10) - Maximum number of attachments per email
|
||||
- Phishing Detection (optional):
|
||||
- `OPENROUTER_API_KEY` - API key for OpenRouter (enables phishing detection)
|
||||
- `OPENROUTER_MODEL` (default: anthropic/claude-3-haiku) - LLM model to use for content analysis
|
||||
- `PHISHING_DETECTION_SAMPLE_RATE` (default: 0.1) - Percentage of emails to check (0.0-1.0, e.g., 0.1 = 10%)
|
||||
- `PHISHING_CONFIDENCE_THRESHOLD` (default: 95) - Minimum confidence percentage (0-100) to auto-disable project for single detection
|
||||
- `PHISHING_CUMULATIVE_THRESHOLD` (default: 3) - Number of phishing detections within time window to trigger auto-disable
|
||||
- `PHISHING_CUMULATIVE_WINDOW_MS` (default: 3600000) - Time window in milliseconds for cumulative tracking (default 1 hour)
|
||||
|
||||
**Important Notes:**
|
||||
|
||||
@@ -155,4 +172,26 @@ Required for builds and deployment (see turbo.json and .env.example):
|
||||
allows the same Docker image to be used across different environments by simply changing environment variables at
|
||||
runtime
|
||||
- **Frontend Variables**: Next.js apps use `NEXT_PUBLIC_*` prefixed variables that are embedded at build time for
|
||||
client-side access
|
||||
client-side access
|
||||
|
||||
## Environment Variable Changes
|
||||
|
||||
When you add, rename, remove, or change the default/behaviour of any environment variable, you MUST update all THREE of the following in the same change:
|
||||
|
||||
1. `apps/api/.env.example` — local development defaults
|
||||
2. `.env.self-host.example` — self-hosting / production template
|
||||
3. `apps/wiki/content/docs/self-hosting/environment-variables.mdx` — user-facing reference
|
||||
|
||||
Rules:
|
||||
|
||||
- If the variable already exists in any file, **modify** its line/row/description — do not duplicate or leave a stale entry.
|
||||
- Keep section/category names consistent across all three files (e.g. "AWS SES", "Phishing Detection").
|
||||
- For dev-only or self-host-only variables, still mention them in the wiki and note the scope; only skip the example file where the variable is genuinely never applicable.
|
||||
- When in doubt about whether a variable belongs in `apps/api/.env.example` (development), include it commented out with a short note.
|
||||
|
||||
## Plugins
|
||||
|
||||
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.
|
||||
- superpowers: This plugin can help you with advanced tasks such as refactorings, new features or architectural changes. Use it when you need extra assistance beyond basic coding.
|
||||
|
||||
@@ -95,8 +95,8 @@ ARG TARGETPLATFORM
|
||||
# Build-time arguments for URL configuration
|
||||
# These are only used during the build process (for wiki OpenAPI generation and static assets)
|
||||
# Runtime URLs are configured via *_DOMAIN and USE_HTTPS environment variables at container startup
|
||||
ARG API_URI=https://api.useplunk.com
|
||||
ARG DASHBOARD_URI=https://app.useplunk.com
|
||||
ARG API_URI=https://next-api.useplunk.com
|
||||
ARG DASHBOARD_URI=https://next-app.useplunk.com
|
||||
ARG LANDING_URI=https://www.useplunk.com
|
||||
ARG WIKI_URI=https://docs.useplunk.com
|
||||
|
||||
@@ -123,6 +123,10 @@ COPY --from=deps /app/yarn.lock ./
|
||||
# Copy root config files needed for Turbo
|
||||
COPY turbo.json ./
|
||||
|
||||
# Copy manifest generation script
|
||||
COPY docker/generate-url-manifest.sh /usr/local/bin/
|
||||
RUN chmod +x /usr/local/bin/generate-url-manifest.sh
|
||||
|
||||
# Step 1: Copy and build shared packages (these change less frequently)
|
||||
# Shared packages are dependencies for apps, so build them first
|
||||
COPY packages ./packages
|
||||
@@ -171,6 +175,10 @@ RUN --mount=type=cache,target=/app/.turbo,sharing=locked \
|
||||
NEXT_PUBLIC_LANDING_URI=${LANDING_URI} \
|
||||
NEXT_PUBLIC_WIKI_URI=${WIKI_URI} \
|
||||
yarn turbo build --filter=wiki
|
||||
# Generate sitemap for wiki
|
||||
RUN NEXT_PUBLIC_WIKI_URI=${WIKI_URI} yarn workspace wiki sitemap
|
||||
# Generate URL replacement manifest for wiki (build-time optimization)
|
||||
RUN generate-url-manifest.sh wiki /app/apps/wiki
|
||||
|
||||
# Step 4: Copy and build Web dashboard
|
||||
COPY apps/web ./apps/web
|
||||
@@ -184,6 +192,10 @@ RUN --mount=type=cache,target=/app/.turbo,sharing=locked \
|
||||
NEXT_PUBLIC_LANDING_URI=${LANDING_URI} \
|
||||
NEXT_PUBLIC_WIKI_URI=${WIKI_URI} \
|
||||
yarn turbo build --filter=web
|
||||
# Generate sitemap for web
|
||||
RUN NEXT_PUBLIC_DASHBOARD_URI=${DASHBOARD_URI} yarn workspace web sitemap
|
||||
# Generate URL replacement manifest for web (build-time optimization)
|
||||
RUN generate-url-manifest.sh web /app/apps/web
|
||||
|
||||
# Step 5: Copy and build Landing page
|
||||
COPY apps/landing ./apps/landing
|
||||
@@ -197,6 +209,10 @@ RUN --mount=type=cache,target=/app/.turbo,sharing=locked \
|
||||
NEXT_PUBLIC_LANDING_URI=${LANDING_URI} \
|
||||
NEXT_PUBLIC_WIKI_URI=${WIKI_URI} \
|
||||
yarn turbo build --filter=landing
|
||||
# Generate sitemap for landing
|
||||
RUN NEXT_PUBLIC_LANDING_URI=${LANDING_URI} yarn workspace landing sitemap
|
||||
# Generate URL replacement manifest for landing (build-time optimization)
|
||||
RUN generate-url-manifest.sh landing /app/apps/landing
|
||||
|
||||
# Copy any remaining root files (if needed)
|
||||
COPY . .
|
||||
@@ -257,8 +273,7 @@ COPY --from=builder --chown=plunk:nodejs /app/packages/shared/dist ./packages/sh
|
||||
COPY --from=builder --chown=plunk:nodejs /app/packages/shared/package.json ./packages/shared/package.json
|
||||
COPY --from=builder --chown=plunk:nodejs /app/packages/email/dist ./packages/email/dist
|
||||
COPY --from=builder --chown=plunk:nodejs /app/packages/email/package.json ./packages/email/package.json
|
||||
# @plunk/types exports source TypeScript files directly (no build output)
|
||||
COPY --from=builder --chown=plunk:nodejs /app/packages/types/src ./packages/types/src
|
||||
COPY --from=builder --chown=plunk:nodejs /app/packages/types/dist ./packages/types/dist
|
||||
COPY --from=builder --chown=plunk:nodejs /app/packages/types/package.json ./packages/types/package.json
|
||||
|
||||
# Copy Prisma schema (needed for migrations at runtime)
|
||||
@@ -284,17 +299,26 @@ COPY --from=builder --chown=plunk:nodejs /app/apps/smtp/package.json ./apps/smtp
|
||||
COPY --from=builder --chown=plunk:nodejs /app/apps/web/.next/standalone ./apps/web/.next/standalone
|
||||
COPY --from=builder --chown=plunk:nodejs /app/apps/web/public ./apps/web/.next/standalone/apps/web/public
|
||||
COPY --from=builder --chown=plunk:nodejs /app/apps/web/.next/static ./apps/web/.next/standalone/apps/web/.next/static
|
||||
# Copy URL replacement manifests to standalone directory
|
||||
COPY --from=builder --chown=plunk:nodejs /app/apps/web/.next/url-manifest.txt ./apps/web/.next/standalone/apps/web/.next/url-manifest.txt
|
||||
COPY --from=builder --chown=plunk:nodejs /app/apps/web/.next/sitemap-manifest.txt ./apps/web/.next/standalone/apps/web/.next/sitemap-manifest.txt
|
||||
|
||||
# Landing app - standalone build with static assets
|
||||
COPY --from=builder --chown=plunk:nodejs /app/apps/landing/.next/standalone ./apps/landing/.next/standalone
|
||||
COPY --from=builder --chown=plunk:nodejs /app/apps/landing/public ./apps/landing/.next/standalone/apps/landing/public
|
||||
COPY --from=builder --chown=plunk:nodejs /app/apps/landing/.next/static ./apps/landing/.next/standalone/apps/landing/.next/static
|
||||
# Copy URL replacement manifests to standalone directory
|
||||
COPY --from=builder --chown=plunk:nodejs /app/apps/landing/.next/url-manifest.txt ./apps/landing/.next/standalone/apps/landing/.next/url-manifest.txt
|
||||
COPY --from=builder --chown=plunk:nodejs /app/apps/landing/.next/sitemap-manifest.txt ./apps/landing/.next/standalone/apps/landing/.next/sitemap-manifest.txt
|
||||
|
||||
# Wiki app - standalone build with static assets and OpenAPI spec
|
||||
COPY --from=builder --chown=plunk:nodejs /app/apps/wiki/.next/standalone ./apps/wiki/.next/standalone
|
||||
COPY --from=builder --chown=plunk:nodejs /app/apps/wiki/public ./apps/wiki/.next/standalone/apps/wiki/public
|
||||
COPY --from=builder --chown=plunk:nodejs /app/apps/wiki/.next/static ./apps/wiki/.next/standalone/apps/wiki/.next/static
|
||||
COPY --from=builder --chown=plunk:nodejs /app/apps/wiki/openapi.local.json ./apps/wiki/.next/standalone/apps/wiki/openapi.local.json
|
||||
# Copy URL replacement manifests to standalone directory
|
||||
COPY --from=builder --chown=plunk:nodejs /app/apps/wiki/.next/url-manifest.txt ./apps/wiki/.next/standalone/apps/wiki/.next/url-manifest.txt
|
||||
COPY --from=builder --chown=plunk:nodejs /app/apps/wiki/.next/sitemap-manifest.txt ./apps/wiki/.next/standalone/apps/wiki/.next/sitemap-manifest.txt
|
||||
|
||||
# Copy full .next directories for the entrypoint script (URL replacement via find command)
|
||||
# These are much smaller than node_modules and needed for runtime URL replacement
|
||||
@@ -311,6 +335,10 @@ COPY --from=builder --chown=plunk:nodejs /app/apps/wiki/openapi.local.json ./app
|
||||
COPY --chown=plunk:nodejs docker/nginx/ /app/docker/nginx/
|
||||
RUN chmod +x /app/docker/nginx/setup-nginx.sh
|
||||
|
||||
# Copy optimized URL replacement script
|
||||
COPY --chown=plunk:nodejs docker/replace-urls-optimized.sh /app/docker/
|
||||
RUN chmod +x /app/docker/replace-urls-optimized.sh
|
||||
|
||||
# Copy entrypoint script
|
||||
COPY --chown=plunk:nodejs docker-entrypoint-nginx.sh /usr/local/bin/
|
||||
RUN chmod +x /usr/local/bin/docker-entrypoint-nginx.sh
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||

|
||||

|
||||
|
||||
<h1 align="center">Plunk</h1>
|
||||
|
||||
@@ -7,27 +7,35 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/github/contributors/useplunk/plunk"/>
|
||||
<img src="https://img.shields.io/github/actions/workflow/status/useplunk/plunk/docker-publish.yml"/>
|
||||
<img src="https://img.shields.io/github/license/useplunk/plunk"/>
|
||||
<img src="https://img.shields.io/github/stars/useplunk/plunk"/>
|
||||
<a href="https://github.com/useplunk/plunk/graphs/contributors"><img src="https://img.shields.io/github/contributors/useplunk/plunk" alt="Contributors"/></a>
|
||||
<a href="https://github.com/useplunk/plunk/actions"><img src="https://img.shields.io/github/actions/workflow/status/useplunk/plunk/docker-publish.yml" alt="Build Status"/></a>
|
||||
<a href="https://github.com/useplunk/plunk/blob/next/LICENSE"><img src="https://img.shields.io/github/license/useplunk/plunk" alt="License"/></a>
|
||||
<a href="https://github.com/useplunk/plunk/stargazers"><img src="https://img.shields.io/github/stars/useplunk/plunk" alt="Stars"/></a>
|
||||
<a href="https://github.com/useplunk/plunk/issues"><img src="https://img.shields.io/github/issues/useplunk/plunk" alt="Issues"/></a>
|
||||
<a href="https://github.com/useplunk/plunk/network/members"><img src="https://img.shields.io/github/forks/useplunk/plunk" alt="Forks"/></a>
|
||||
<a href="https://github.com/useplunk/plunk/pkgs/container/plunk"><img src="https://img.shields.io/badge/docker-available-blue?logo=docker" alt="Docker"/></a>
|
||||
<a href="https://github.com/sponsors/driaug"><img src="https://img.shields.io/badge/sponsor-❤-ff69b4" alt="Sponsor"/></a>
|
||||
<a href="https://docs.useplunk.com"><img src="https://img.shields.io/badge/docs-docs.useplunk.com-black" alt="Documentation"/></a>
|
||||
<a href="https://useplunk.com/discord"><img src="https://img.shields.io/badge/discord-join-5865F2?logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
</p>
|
||||
|
||||
## Introduction
|
||||
|
||||
Plunk is an open-source email platform built on top of AWS SES. It allows you to easily send emails from your
|
||||
applications.
|
||||
It can be considered as a self-hosted alternative to services
|
||||
like [SendGrid](https://sendgrid.com/), [Resend](https://resend.com) or [Mailgun](https://www.mailgun.com/).
|
||||
Transactional emails, marketing campaigns, and workflow automation — in one platform. Self-hostable, $0.001 per email, no contact limits.
|
||||
|
||||
An open-source, self-hosted alternative to tools [SendGrid](https://sendgrid.com/), [Resend](https://resend.com) or [Mailgun](https://www.mailgun.com/).
|
||||
|
||||
## Features
|
||||
|
||||
- **Transactional Emails**: Send emails straight from your API with template support and variable substitution
|
||||
- **Campaigns**: Send newsletters and product updates to large audiences with segmentation
|
||||
- **SMTP**: Use Plunk as an SMTP relay to send emails from any existing tool or framework
|
||||
- **Campaigns**: Send newsletters and product updates to large audiences
|
||||
- **Workflows**: Create advanced automations with triggers, delays, and conditional logic
|
||||
- **Contact Management**: Organize contacts with custom fields and dynamic segmentation
|
||||
- **Segments**: Organize contacts with dynamic filtering and target the right audience
|
||||
- **Contact Management**: Manage contacts with custom fields and full activity history
|
||||
- **Analytics**: Track opens, clicks, bounces, and engagement metrics in real-time
|
||||
- **Custom Domains**: Verify and send from your own domains with DKIM/SPF support
|
||||
- **Inbound Emails**: Receive and process incoming emails with custom routing rules
|
||||
|
||||
## Sponsors
|
||||
|
||||
@@ -40,14 +48,19 @@ The easiest way to self-host Plunk is by using the `plunk` Docker image.
|
||||
You can pull the latest image from [Github](https://github.com/useplunk/plunk/pkgs/container/plunk).
|
||||
|
||||
A complete guide on how to deploy Plunk can be found in
|
||||
the [documentation](https://next-wiki.useplunk.com/self-hosting/introduction).
|
||||
the [documentation](https://docs.useplunk.com/self-hosting/introduction).
|
||||
|
||||
## Community
|
||||
|
||||
- **Documentation**: [docs.useplunk.com](https://docs.useplunk.com)
|
||||
- **Discord**: [useplunk.com/discord](https://useplunk.com/discord)
|
||||
|
||||
## Contributing
|
||||
|
||||
You are welcome to contribute to Plunk. You can find a guide on how to contribute in [CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
|
||||
<a href="https://github.com/useplunk/plunk/graphs/contributors">
|
||||
<img src="https://contrib.rocks/image?repo=useplunk/plunk" />
|
||||
<img src="https://contrib.rocks/image?repo=useplunk/plunk" alt="Contributors" />
|
||||
</a>
|
||||
|
||||
## License
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
# ==============================================================================
|
||||
NODE_ENV=development
|
||||
JWT_SECRET=hBx9Xh8J6KOMAGAsSjvcZJBT5TWyIkFX
|
||||
# Port the API server listens on (default: 8080)
|
||||
# PORT=8080
|
||||
|
||||
# ==============================================================================
|
||||
# Application URLs
|
||||
@@ -16,6 +18,7 @@ JWT_SECRET=hBx9Xh8J6KOMAGAsSjvcZJBT5TWyIkFX
|
||||
USE_HTTPS=false
|
||||
|
||||
API_URI=http://localhost:8080
|
||||
WIKI_URI=http://localhost:1000
|
||||
DASHBOARD_URI=http://localhost:3000
|
||||
LANDING_URI=http://localhost:4000
|
||||
|
||||
@@ -24,6 +27,8 @@ LANDING_URI=http://localhost:4000
|
||||
# ==============================================================================
|
||||
# API key for authenticating with the Plunk API (obtained from dashboard)
|
||||
PLUNK_API_KEY=
|
||||
# From address used for platform notification emails (project disabled, billing limits, etc.)
|
||||
# PLUNK_FROM_ADDRESS=
|
||||
|
||||
# ==============================================================================
|
||||
# Database & Redis
|
||||
@@ -60,6 +65,17 @@ SES_CONFIGURATION_SET_NO_TRACKING=plunk-configuration-set-no-tracking # Optiona
|
||||
# Default: Fetched from AWS (typically 14 for sandbox, higher for production accounts)
|
||||
# EMAIL_RATE_LIMIT_PER_SECOND=14
|
||||
|
||||
# Email worker concurrency (number of emails processed in parallel)
|
||||
# If not set, derived from the effective rate limit (~ rate * 0.5, min 5, capped
|
||||
# by EMAIL_WORKER_MAX_CONCURRENCY). Set this to pin a fixed value when the
|
||||
# Prisma connection pool or memory is the binding constraint.
|
||||
# EMAIL_WORKER_CONCURRENCY=10
|
||||
|
||||
# Upper bound for auto-derived worker concurrency
|
||||
# Raise this when your SES quota is high AND the Prisma pool has been sized for it.
|
||||
# Default: 50
|
||||
# EMAIL_WORKER_MAX_CONCURRENCY=50
|
||||
|
||||
# ==============================================================================
|
||||
# OAuth (Optional - for social login)
|
||||
# ==============================================================================
|
||||
@@ -84,3 +100,46 @@ STRIPE_METER_EVENT_NAME=emails # Meter event name (API key from your Stripe mete
|
||||
# Set to 'false' to disable automatic project suspension (useful for self-hosters who manage manually)
|
||||
# Default: true (automatic project disabling enabled)
|
||||
# AUTO_PROJECT_DISABLE=true
|
||||
|
||||
# ==============================================================================
|
||||
# Notifications (Optional - system notifications via ntfy)
|
||||
# ==============================================================================
|
||||
# ntfy topic URL for internal system notifications (e.g. project disabled, billing limits).
|
||||
# When unset, ntfy notifications are disabled.
|
||||
# Examples:
|
||||
# - Public ntfy.sh: https://ntfy.sh/your-unique-topic-name
|
||||
# - Self-hosted: https://your-ntfy-server.com/your-topic
|
||||
# NTFY_URL=
|
||||
|
||||
# ==============================================================================
|
||||
# Attachments (Optional)
|
||||
# ==============================================================================
|
||||
# Limits applied to attachments on transactional emails.
|
||||
# AWS SES caps total message size at 40 MB; the defaults below leave headroom.
|
||||
# MAX_ATTACHMENT_SIZE_MB=10
|
||||
# MAX_ATTACHMENTS_COUNT=10
|
||||
|
||||
# ==============================================================================
|
||||
# User Management (Optional)
|
||||
# ==============================================================================
|
||||
# When 'true', the signup endpoint rejects new user registrations.
|
||||
# Default: false
|
||||
# DISABLE_SIGNUPS=false
|
||||
# When 'true', validates emails on signup (disposable domains, plus-addressing,
|
||||
# domain existence, MX records).
|
||||
# Default: false
|
||||
# VERIFY_EMAIL_ON_SIGNUP=false
|
||||
|
||||
# ==============================================================================
|
||||
# Phishing Detection (Optional - AI-powered phishing scan via OpenRouter)
|
||||
# ==============================================================================
|
||||
# When OPENROUTER_API_KEY is set, a random sample of outgoing emails is
|
||||
# analyzed by an LLM. Projects can be auto-disabled if a single email exceeds
|
||||
# PHISHING_CONFIDENCE_THRESHOLD, or if PHISHING_CUMULATIVE_THRESHOLD emails are
|
||||
# flagged within PHISHING_CUMULATIVE_WINDOW_MS.
|
||||
# OPENROUTER_API_KEY=
|
||||
# OPENROUTER_MODEL=anthropic/claude-3-haiku
|
||||
# PHISHING_DETECTION_SAMPLE_RATE=0.1
|
||||
# PHISHING_CONFIDENCE_THRESHOLD=95
|
||||
# PHISHING_CUMULATIVE_THRESHOLD=3
|
||||
# PHISHING_CUMULATIVE_WINDOW_MS=3600000
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
"@plunk/shared": "*",
|
||||
"@plunk/types": "*",
|
||||
"@react-email/render": "^2.0.0",
|
||||
"@zootools/email-spell-checker": "^1.12.0",
|
||||
"bcrypt": "^6.0.0",
|
||||
"body-parser": "^2.2.0",
|
||||
"bullmq": "^5.63.2",
|
||||
@@ -34,8 +35,11 @@
|
||||
"helmet": "^8.1.0",
|
||||
"ioredis": "^5.8.2",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"mailchecker": "^6.0.19",
|
||||
"mailparser": "^3.9.8",
|
||||
"morgan": "^1.10.0",
|
||||
"multer": "^2.0.2",
|
||||
"multer": "^2.1.1",
|
||||
"sanitize-html": "^2.17.3",
|
||||
"signale": "^1.4.0",
|
||||
"stripe": "^20.0.0"
|
||||
},
|
||||
@@ -46,8 +50,10 @@
|
||||
"@types/express": "^5.0.5",
|
||||
"@types/helmet": "^4.0.0",
|
||||
"@types/jsonwebtoken": "^9.0.6",
|
||||
"@types/mailparser": "^3.4.6",
|
||||
"@types/morgan": "^1.9.9",
|
||||
"@types/multer": "^2.0.0",
|
||||
"@types/sanitize-html": "^2.16.1",
|
||||
"@types/signale": "^1.4.7",
|
||||
"concurrently": "^9.2.1",
|
||||
"tsx": "^4.20.6"
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
NotAuthenticated,
|
||||
NotFound,
|
||||
RateLimitError,
|
||||
ValidationError
|
||||
ValidationError,
|
||||
} from '../../exceptions/index.js';
|
||||
import {EmailService} from '../../services/EmailService.js';
|
||||
|
||||
@@ -733,4 +733,315 @@ describe('Actions API Integration Tests', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ========================================
|
||||
// SUBSCRIPTION STATUS PRESERVATION
|
||||
// ========================================
|
||||
describe('Subscription Status Preservation', () => {
|
||||
describe('/v1/send endpoint', () => {
|
||||
it('should NOT change subscription status when sending to subscribed contact without subscribed field', async () => {
|
||||
// Create a subscribed contact
|
||||
const contact = await factories.createContact({
|
||||
projectId,
|
||||
subscribed: true,
|
||||
email: 'subscribed@example.com',
|
||||
});
|
||||
|
||||
// Verify initial state
|
||||
expect(contact.subscribed).toBe(true);
|
||||
|
||||
// Send transactional email without specifying subscribed field
|
||||
await EmailService.sendTransactionalEmail({
|
||||
projectId,
|
||||
contactId: contact.id,
|
||||
subject: 'Test',
|
||||
body: 'Test',
|
||||
from: 'test@example.com',
|
||||
});
|
||||
|
||||
// Verify subscription status unchanged
|
||||
const updatedContact = await prisma.contact.findUnique({
|
||||
where: {id: contact.id},
|
||||
});
|
||||
|
||||
expect(updatedContact?.subscribed).toBe(true);
|
||||
});
|
||||
|
||||
it('should NOT change subscription status when sending to unsubscribed contact without subscribed field', async () => {
|
||||
// Create an unsubscribed contact
|
||||
const contact = await factories.createContact({
|
||||
projectId,
|
||||
subscribed: false,
|
||||
email: 'unsubscribed@example.com',
|
||||
});
|
||||
|
||||
// Verify initial state
|
||||
expect(contact.subscribed).toBe(false);
|
||||
|
||||
// Send transactional email without specifying subscribed field
|
||||
await EmailService.sendTransactionalEmail({
|
||||
projectId,
|
||||
contactId: contact.id,
|
||||
subject: 'Test',
|
||||
body: 'Test',
|
||||
from: 'test@example.com',
|
||||
});
|
||||
|
||||
// Verify subscription status unchanged (should still be false)
|
||||
const updatedContact = await prisma.contact.findUnique({
|
||||
where: {id: contact.id},
|
||||
});
|
||||
|
||||
expect(updatedContact?.subscribed).toBe(false);
|
||||
});
|
||||
|
||||
it('should allow explicit subscription when subscribed=true is provided', async () => {
|
||||
// Create an unsubscribed contact
|
||||
const contact = await factories.createContact({
|
||||
projectId,
|
||||
subscribed: false,
|
||||
email: 'resubscribe@example.com',
|
||||
});
|
||||
|
||||
// This test would need to be implemented at the controller level
|
||||
// since EmailService.sendTransactionalEmail doesn't accept subscribed parameter
|
||||
// For now, verify the schema allows it
|
||||
const result = ActionSchemas.send.safeParse({
|
||||
to: contact.email,
|
||||
subject: 'Test',
|
||||
body: 'Test',
|
||||
from: 'test@example.com',
|
||||
subscribed: true,
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
if (result.success) {
|
||||
expect(result.data.subscribed).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('should allow explicit unsubscription when subscribed=false is provided', async () => {
|
||||
// Verify the schema allows explicit false
|
||||
const result = ActionSchemas.send.safeParse({
|
||||
to: 'test@example.com',
|
||||
subject: 'Test',
|
||||
body: 'Test',
|
||||
from: 'test@example.com',
|
||||
subscribed: false,
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
if (result.success) {
|
||||
expect(result.data.subscribed).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('should default to undefined when subscribed field is omitted', () => {
|
||||
const result = ActionSchemas.send.safeParse({
|
||||
to: 'test@example.com',
|
||||
subject: 'Test',
|
||||
body: 'Test',
|
||||
from: 'test@example.com',
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
if (result.success) {
|
||||
// Should be undefined, not false
|
||||
expect(result.data.subscribed).toBeUndefined();
|
||||
}
|
||||
});
|
||||
|
||||
it('should create new contacts as unsubscribed when subscribed is undefined', async () => {
|
||||
const newEmail = 'new-send-contact@example.com';
|
||||
|
||||
// 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', () => {
|
||||
it('should NOT change subscription status when tracking event for subscribed contact', async () => {
|
||||
// Create a subscribed contact
|
||||
const contact = await factories.createContact({
|
||||
projectId,
|
||||
subscribed: true,
|
||||
email: 'track-subscribed@example.com',
|
||||
});
|
||||
|
||||
// Verify initial state
|
||||
expect(contact.subscribed).toBe(true);
|
||||
|
||||
// Track event without specifying subscribed field
|
||||
// This would be done via ContactService.upsert in the track endpoint
|
||||
const {ContactService} = await import('../../services/ContactService.js');
|
||||
await ContactService.upsert(projectId, contact.email, {event: 'test'}, undefined);
|
||||
|
||||
// Verify subscription status unchanged
|
||||
const updatedContact = await prisma.contact.findUnique({
|
||||
where: {id: contact.id},
|
||||
});
|
||||
|
||||
expect(updatedContact?.subscribed).toBe(true);
|
||||
});
|
||||
|
||||
it('should NOT re-subscribe unsubscribed contact when tracking event', async () => {
|
||||
// Create an unsubscribed contact
|
||||
const contact = await factories.createContact({
|
||||
projectId,
|
||||
subscribed: false,
|
||||
email: 'track-unsubscribed@example.com',
|
||||
});
|
||||
|
||||
// Verify initial state
|
||||
expect(contact.subscribed).toBe(false);
|
||||
|
||||
// Track event without specifying subscribed field
|
||||
const {ContactService} = await import('../../services/ContactService.js');
|
||||
await ContactService.upsert(projectId, contact.email, {event: 'test'}, undefined);
|
||||
|
||||
// Verify subscription status unchanged (should still be false, NOT re-subscribed)
|
||||
const updatedContact = await prisma.contact.findUnique({
|
||||
where: {id: contact.id},
|
||||
});
|
||||
|
||||
expect(updatedContact?.subscribed).toBe(false);
|
||||
});
|
||||
|
||||
it('should create new contacts as subscribed when subscribed is undefined', async () => {
|
||||
const newEmail = 'new-track-contact@example.com';
|
||||
|
||||
// Track event for new contact without specifying subscribed
|
||||
const {ContactService} = await import('../../services/ContactService.js');
|
||||
const contact = await ContactService.upsert(projectId, newEmail, {event: 'test'}, true);
|
||||
|
||||
// Event tracking should create contacts as subscribed by default
|
||||
expect(contact.subscribed).toBe(true);
|
||||
});
|
||||
|
||||
it('should allow explicit subscription when subscribed=true is provided', async () => {
|
||||
const result = ActionSchemas.track.safeParse({
|
||||
event: 'test',
|
||||
email: 'test@example.com',
|
||||
subscribed: true,
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
if (result.success) {
|
||||
expect(result.data.subscribed).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('should allow explicit unsubscription when subscribed=false is provided', async () => {
|
||||
const result = ActionSchemas.track.safeParse({
|
||||
event: 'test',
|
||||
email: 'test@example.com',
|
||||
subscribed: false,
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
if (result.success) {
|
||||
expect(result.data.subscribed).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('should default to undefined when subscribed field is omitted', () => {
|
||||
const result = ActionSchemas.track.safeParse({
|
||||
event: 'test',
|
||||
email: 'test@example.com',
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
if (result.success) {
|
||||
// Should be undefined, not true
|
||||
expect(result.data.subscribed).toBeUndefined();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('ContactService.upsert behavior', () => {
|
||||
it('should preserve subscription status when undefined is passed for existing contact', async () => {
|
||||
// Create a subscribed contact
|
||||
const contact = await factories.createContact({
|
||||
projectId,
|
||||
subscribed: true,
|
||||
email: 'upsert-test@example.com',
|
||||
});
|
||||
|
||||
const {ContactService} = await import('../../services/ContactService.js');
|
||||
|
||||
// Update with undefined subscribed
|
||||
await ContactService.upsert(projectId, contact.email, {firstName: 'John'}, undefined);
|
||||
|
||||
const updated = await prisma.contact.findUnique({
|
||||
where: {id: contact.id},
|
||||
});
|
||||
|
||||
expect(updated?.subscribed).toBe(true);
|
||||
});
|
||||
|
||||
it('should preserve unsubscribed status when undefined is passed', async () => {
|
||||
// Create an unsubscribed contact
|
||||
const contact = await factories.createContact({
|
||||
projectId,
|
||||
subscribed: false,
|
||||
email: 'upsert-unsub@example.com',
|
||||
});
|
||||
|
||||
const {ContactService} = await import('../../services/ContactService.js');
|
||||
|
||||
// Update with undefined subscribed
|
||||
await ContactService.upsert(projectId, contact.email, {firstName: 'Jane'}, undefined);
|
||||
|
||||
const updated = await prisma.contact.findUnique({
|
||||
where: {id: contact.id},
|
||||
});
|
||||
|
||||
expect(updated?.subscribed).toBe(false);
|
||||
});
|
||||
|
||||
it('should allow explicit subscription change to true', async () => {
|
||||
// Create an unsubscribed contact
|
||||
const contact = await factories.createContact({
|
||||
projectId,
|
||||
subscribed: false,
|
||||
email: 'explicit-sub@example.com',
|
||||
});
|
||||
|
||||
const {ContactService} = await import('../../services/ContactService.js');
|
||||
|
||||
// Explicitly subscribe
|
||||
await ContactService.upsert(projectId, contact.email, {}, true);
|
||||
|
||||
const updated = await prisma.contact.findUnique({
|
||||
where: {id: contact.id},
|
||||
});
|
||||
|
||||
expect(updated?.subscribed).toBe(true);
|
||||
});
|
||||
|
||||
it('should allow explicit subscription change to false', async () => {
|
||||
// Create a subscribed contact
|
||||
const contact = await factories.createContact({
|
||||
projectId,
|
||||
subscribed: true,
|
||||
email: 'explicit-unsub@example.com',
|
||||
});
|
||||
|
||||
const {ContactService} = await import('../../services/ContactService.js');
|
||||
|
||||
// Explicitly unsubscribe
|
||||
await ContactService.upsert(projectId, contact.email, {}, false);
|
||||
|
||||
const updated = await prisma.contact.findUnique({
|
||||
where: {id: contact.id},
|
||||
});
|
||||
|
||||
expect(updated?.subscribed).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import {describe, it, expect, beforeEach, beforeAll} from 'vitest';
|
||||
import {CampaignStatus, CampaignAudienceType} from '@plunk/db';
|
||||
import {beforeAll, beforeEach, describe, expect, it} from 'vitest';
|
||||
import {CampaignAudienceType, CampaignStatus} from '@plunk/db';
|
||||
import {factories, getPrismaClient} from '../../../../../test/helpers';
|
||||
|
||||
// Note: To run these integration tests, you need to:
|
||||
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
SMTP_ENABLED,
|
||||
STRIPE_ENABLED,
|
||||
TRACKING_TOGGLE_ENABLED,
|
||||
WIKI_URI
|
||||
WIKI_URI,
|
||||
} from './app/constants.js';
|
||||
import {Actions} from './controllers/Actions.js';
|
||||
import {Activity} from './controllers/Activity.js';
|
||||
@@ -76,23 +76,73 @@ const server = new (class extends Server {
|
||||
// Log all requests to database for historical tracking and analytics
|
||||
this.app.use(databaseRequestLogger);
|
||||
|
||||
this.app.use(['/v1', '/v1/track', '/v1/send'], (req, res, next) => {
|
||||
res.set({'Access-Control-Allow-Origin': '*'});
|
||||
next();
|
||||
});
|
||||
|
||||
// Build allowed origins from environment variables
|
||||
const allowedOrigins =
|
||||
NODE_ENV === 'development'
|
||||
? [/.*\.localhost:1000/, 'http://localhost:3000', 'http://localhost:4000']
|
||||
: [DASHBOARD_URI, LANDING_URI, WIKI_URI];
|
||||
|
||||
this.app.use(
|
||||
// Public API endpoints that should allow all origins
|
||||
const publicApiPaths = ['/v1', '/v1/track', '/v1/send'];
|
||||
|
||||
// Log CORS configuration on startup
|
||||
signale.info('CORS configuration', {
|
||||
environment: NODE_ENV,
|
||||
allowedOrigins: allowedOrigins.map(o => (o instanceof RegExp ? o.toString() : o)),
|
||||
publicApiPaths,
|
||||
});
|
||||
|
||||
// Apply restrictive CORS to all routes EXCEPT public API endpoints
|
||||
this.app.use((req, res, next) => {
|
||||
// Check if this is a public API endpoint
|
||||
const isPublicApi = publicApiPaths.some(path => req.path === path || req.path.startsWith(path + '/'));
|
||||
|
||||
if (isPublicApi) {
|
||||
// For public API endpoints, allow all origins
|
||||
res.set({
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
|
||||
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
|
||||
});
|
||||
// Handle preflight
|
||||
if (req.method === 'OPTIONS') {
|
||||
return res.sendStatus(200);
|
||||
}
|
||||
return next();
|
||||
}
|
||||
|
||||
// For other endpoints, apply restrictive CORS
|
||||
cors({
|
||||
origin: allowedOrigins,
|
||||
origin: (origin, callback) => {
|
||||
// Allow requests with no origin (e.g., mobile apps, curl, server-to-server)
|
||||
if (!origin) {
|
||||
return callback(null, true);
|
||||
}
|
||||
|
||||
// Check if origin matches any allowed origin (string or regex)
|
||||
const isAllowed = allowedOrigins.some(allowed => {
|
||||
if (allowed instanceof RegExp) {
|
||||
return allowed.test(origin);
|
||||
}
|
||||
return allowed === origin;
|
||||
});
|
||||
|
||||
if (isAllowed) {
|
||||
callback(null, true);
|
||||
} else {
|
||||
// Log CORS rejection with helpful information
|
||||
signale.warn('CORS request rejected', {
|
||||
origin,
|
||||
allowedOrigins: allowedOrigins.map(o => (o instanceof RegExp ? o.toString() : o)),
|
||||
hint: 'If using HTTPS, ensure USE_HTTPS=true is set in your environment variables',
|
||||
});
|
||||
// Reject the CORS request by passing false (don't send CORS headers)
|
||||
callback(null, false);
|
||||
}
|
||||
},
|
||||
credentials: true,
|
||||
}),
|
||||
);
|
||||
})(req, res, next);
|
||||
});
|
||||
|
||||
this.app.use(morgan(NODE_ENV === 'development' ? 'dev' : 'short'));
|
||||
|
||||
@@ -154,6 +204,34 @@ interface ErrorResponse {
|
||||
server.app.use((error: Error, req: Request, res: Response, _next: NextFunction) => {
|
||||
const requestId = res.locals.requestId as string | undefined;
|
||||
|
||||
// Handle JSON parsing errors (from express.json() middleware)
|
||||
if (error instanceof SyntaxError && 'body' in error) {
|
||||
const statusCode = 400;
|
||||
|
||||
logger.warn(
|
||||
'JSON parsing failed',
|
||||
{
|
||||
endpoint: `${req.method} ${req.path}`,
|
||||
contentType: req.get('content-type'),
|
||||
},
|
||||
res,
|
||||
);
|
||||
|
||||
const response: ErrorResponse = {
|
||||
success: false,
|
||||
error: {
|
||||
code: ErrorCode.VALIDATION_ERROR,
|
||||
message: 'Invalid JSON in request body',
|
||||
statusCode,
|
||||
requestId,
|
||||
suggestion: 'Ensure your request body is valid JSON and Content-Type header is set to "application/json".',
|
||||
},
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
|
||||
return res.status(statusCode).json(response);
|
||||
}
|
||||
|
||||
// Handle Zod validation errors
|
||||
if (error instanceof ZodError) {
|
||||
const fieldErrors: FieldError[] = error.errors.map(err => ({
|
||||
|
||||
@@ -45,6 +45,12 @@ export const AWS_SES_REGION = validateEnv('AWS_SES_REGION');
|
||||
export const AWS_SES_ACCESS_KEY_ID = validateEnv('AWS_SES_ACCESS_KEY_ID');
|
||||
export const AWS_SES_SECRET_ACCESS_KEY = validateEnv('AWS_SES_SECRET_ACCESS_KEY');
|
||||
|
||||
// Custom MAIL FROM subdomain used to construct `<subdomain>.<your-domain>`
|
||||
// when a domain is added. Defaults to `plunk`. Override when `plunk.<your-domain>`
|
||||
// is already used for something else (e.g. a CDN), since the MAIL FROM hostname
|
||||
// needs MX + TXT records that can't coexist with a CNAME.
|
||||
export const MAIL_FROM_SUBDOMAIN = validateEnv('MAIL_FROM_SUBDOMAIN', '').trim() || 'plunk';
|
||||
|
||||
// Email Processing Rate Limit (optional override)
|
||||
// If not set, will automatically fetch from AWS SES account quota
|
||||
// Set this to override AWS quota (useful for setting lower limits or testing)
|
||||
@@ -52,6 +58,20 @@ export const EMAIL_RATE_LIMIT_PER_SECOND = process.env.EMAIL_RATE_LIMIT_PER_SECO
|
||||
? Number(process.env.EMAIL_RATE_LIMIT_PER_SECOND)
|
||||
: undefined;
|
||||
|
||||
// Email Worker Concurrency (optional override)
|
||||
// If not set, concurrency is derived from the effective rate limit so a higher
|
||||
// SES quota actually translates into higher throughput. Set this to pin a fixed
|
||||
// value (useful when Prisma pool size or memory is the binding constraint).
|
||||
export const EMAIL_WORKER_CONCURRENCY = process.env.EMAIL_WORKER_CONCURRENCY
|
||||
? Number(process.env.EMAIL_WORKER_CONCURRENCY)
|
||||
: undefined;
|
||||
|
||||
// Upper bound for auto-derived concurrency. Raise this if you have a large SES
|
||||
// quota AND have sized the Prisma connection pool accordingly.
|
||||
export const EMAIL_WORKER_MAX_CONCURRENCY = process.env.EMAIL_WORKER_MAX_CONCURRENCY
|
||||
? Number(process.env.EMAIL_WORKER_MAX_CONCURRENCY)
|
||||
: 50;
|
||||
|
||||
// Storage
|
||||
export const REDIS_URL = validateEnv('REDIS_URL');
|
||||
export const DATABASE_URL = validateEnv('DATABASE_URL');
|
||||
@@ -103,3 +123,31 @@ export const PLUNK_ENABLED = PLUNK_API_KEY !== '' && PLUNK_FROM_ADDRESS !== '';
|
||||
// Controls whether projects are automatically disabled when bounce/complaint rate thresholds are exceeded
|
||||
// Useful for self-hosters who want to manage project status manually
|
||||
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';
|
||||
|
||||
// Attachment Limits (optional)
|
||||
// Maximum total attachment size in MB (default: 10). AWS SES supports up to 40 MB.
|
||||
export const MAX_ATTACHMENT_SIZE_MB = Number(validateEnv('MAX_ATTACHMENT_SIZE_MB', '10'));
|
||||
// Maximum number of attachments per email (default: 10)
|
||||
export const MAX_ATTACHMENTS_COUNT = Number(validateEnv('MAX_ATTACHMENTS_COUNT', '10'));
|
||||
|
||||
// Email Verification & Password Reset
|
||||
export const TOKEN_EXPIRY_SECONDS = 3600; // 1 hour
|
||||
export const EMAIL_VERIFICATION_RATE_LIMIT = 3; // Max 3 emails per hour
|
||||
export const PASSWORD_RESET_RATE_LIMIT = 3; // Max 3 emails per hour
|
||||
export const EMAIL_VERIFICATION_RATE_WINDOW = 3600; // 1 hour in seconds
|
||||
|
||||
// Phishing Detection (optional)
|
||||
// OpenRouter API integration for content safety checks
|
||||
export const OPENROUTER_API_KEY = validateEnv('OPENROUTER_API_KEY', '');
|
||||
export const OPENROUTER_MODEL = validateEnv('OPENROUTER_MODEL', 'anthropic/claude-3-haiku');
|
||||
export const PHISHING_DETECTION_SAMPLE_RATE = Number(validateEnv('PHISHING_DETECTION_SAMPLE_RATE', '0.1')); // Default 10% of emails
|
||||
export const PHISHING_DETECTION_ENABLED = OPENROUTER_API_KEY !== '';
|
||||
export const PHISHING_CONFIDENCE_THRESHOLD = Number(validateEnv('PHISHING_CONFIDENCE_THRESHOLD', '95')); // Confidence % required to auto-disable project from a single detection
|
||||
export const PHISHING_CUMULATIVE_THRESHOLD = Number(validateEnv('PHISHING_CUMULATIVE_THRESHOLD', '3')); // Number of phishing detections before auto-disable (default 3)
|
||||
export const PHISHING_CUMULATIVE_WINDOW_MS = Number(validateEnv('PHISHING_CUMULATIVE_WINDOW_MS', '3600000')); // Time window for cumulative tracking in ms (default 1 hour)
|
||||
|
||||
@@ -1,20 +1,20 @@
|
||||
import {Controller, Middleware, Post} from '@overnightjs/core';
|
||||
import {ActionSchemas} from '@plunk/shared';
|
||||
import type {NextFunction, Request, Response} from 'express';
|
||||
|
||||
import type {AuthResponse} from '../middleware/auth.js';
|
||||
import {requirePublicKey, requireSecretKey} from '../middleware/auth.js';
|
||||
import {prisma} from '../database/prisma.js';
|
||||
import {ContactService} from '../services/ContactService.js';
|
||||
import {DomainService} from '../services/DomainService.js';
|
||||
import {EmailService} from '../services/EmailService.js';
|
||||
import {EmailVerificationService} from '../services/EmailVerificationService.js';
|
||||
import {EventService} from '../services/EventService.js';
|
||||
import {NotFound, ValidationError} from '../exceptions/index.js';
|
||||
import {CatchAsync} from '../utils/asyncHandler.js';
|
||||
import {DASHBOARD_URI} from '../app/constants.js';
|
||||
|
||||
/**
|
||||
* Public API Actions Controller
|
||||
* Handles track event and transactional email endpoints
|
||||
* Handles track event, transactional email, and email verification endpoints
|
||||
*/
|
||||
@Controller('v1')
|
||||
export class Actions {
|
||||
@@ -25,7 +25,7 @@ export class Actions {
|
||||
* Request body:
|
||||
* - event: string (required) - Event name
|
||||
* - email: string (required) - Contact email
|
||||
* - subscribed: boolean (optional, default: true) - Contact subscription status
|
||||
* - subscribed: boolean (optional) - Contact subscription status (only updates if explicitly specified)
|
||||
* - data: object (optional) - Event and contact data
|
||||
* - Simple values are saved to contact (persistent)
|
||||
* - {value: any, persistent: false} are only available to workflows (non-persistent)
|
||||
@@ -50,7 +50,7 @@ export class Actions {
|
||||
@Middleware([requirePublicKey])
|
||||
@CatchAsync
|
||||
public async track(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
|
||||
// Zod validation - errors automatically handled by global error handler
|
||||
const {event, email, subscribed, data} = ActionSchemas.track.parse(req.body);
|
||||
@@ -72,6 +72,8 @@ export class Actions {
|
||||
|
||||
// Create or update contact with persistent data only
|
||||
// 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(
|
||||
auth.projectId,
|
||||
email,
|
||||
@@ -110,7 +112,7 @@ export class Actions {
|
||||
* - Array: ["user1@example.com", {name: "Jane", email: "user2@example.com"}]
|
||||
* - subject: string (required) - Email subject
|
||||
* - body: string (required) - Email HTML body
|
||||
* - subscribed: boolean (optional, default: false) - Contact subscription status
|
||||
* - subscribed: boolean (optional) - Contact subscription status (only updates if explicitly specified)
|
||||
* - name: string (optional) - Sender name (alternative to from.name)
|
||||
* - from: string | object (optional) - Sender email or {name, email} object (must be from verified domain)
|
||||
* - reply: string (optional) - Reply-to email
|
||||
@@ -118,7 +120,7 @@ export class Actions {
|
||||
* - data: object (optional) - Contact data and template variables
|
||||
* - Simple values are saved to contact (persistent)
|
||||
* - {value: any, persistent: false} are only used for this email (non-persistent)
|
||||
* - attachments: array (optional) - Email attachments (max 10, 10MB total)
|
||||
* - attachments: array (optional) - Email attachments (configurable via MAX_ATTACHMENTS_COUNT / MAX_ATTACHMENT_SIZE_MB, defaults: 10 / 10MB)
|
||||
* - filename: string (required) - Attachment filename
|
||||
* - content: string (required) - Base64 encoded file content
|
||||
* - contentType: string (required) - MIME type (e.g., "application/pdf")
|
||||
@@ -171,7 +173,7 @@ export class Actions {
|
||||
@Middleware([requireSecretKey])
|
||||
@CatchAsync
|
||||
public async send(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
|
||||
// Zod validation - errors automatically handled by global error handler
|
||||
const {to, subject, body, subscribed, name, from, reply, headers, data, template, attachments} =
|
||||
@@ -266,17 +268,32 @@ export class Actions {
|
||||
: (data as Record<string, unknown> | undefined);
|
||||
|
||||
// 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
|
||||
const mergedData = ContactService.getMergedData(contact, data as Record<string, unknown> | undefined);
|
||||
|
||||
// Add system variables (email, unsubscribe URLs, etc.) to merged data
|
||||
// These are always available for template rendering
|
||||
const dataWithSystemVars = {
|
||||
...mergedData,
|
||||
id: contact.id,
|
||||
email: contact.email,
|
||||
data: mergedData, // Also available as nested data for {{data.fieldName}} syntax
|
||||
unsubscribeUrl: `${DASHBOARD_URI}/unsubscribe/${contact.id}`,
|
||||
subscribeUrl: `${DASHBOARD_URI}/subscribe/${contact.id}`,
|
||||
manageUrl: `${DASHBOARD_URI}/manage/${contact.id}`,
|
||||
};
|
||||
|
||||
// Render template with contact data
|
||||
// Simple template variable replacement: {{fieldname}}
|
||||
let renderedSubject = emailSubject!;
|
||||
let renderedBody = emailBody!;
|
||||
|
||||
for (const [key, value] of Object.entries(mergedData)) {
|
||||
for (const [key, value] of Object.entries(dataWithSystemVars)) {
|
||||
const placeholder = new RegExp(`\\{\\{\\s*${key}\\s*\\}\\}`, 'g');
|
||||
const fallbackPlaceholder = new RegExp(`\\{\\{\\s*${key}\\s*\\?\\?\\s*([^}]+)\\}\\}`, 'g');
|
||||
|
||||
@@ -329,4 +346,58 @@ export class Actions {
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /v1/verify
|
||||
* Verify an email address
|
||||
*
|
||||
* Request body:
|
||||
* - email: string (required) - Email address to verify
|
||||
*
|
||||
* Response:
|
||||
* - success: boolean
|
||||
* - data: object with verification results
|
||||
* - email: string - Email address that was verified
|
||||
* - valid: boolean - Whether the email appears to be valid
|
||||
* - isDisposable: boolean - Whether the email is from a disposable domain
|
||||
* - hasMxRecords: boolean - Whether the domain has MX records configured
|
||||
* - suggestedEmail?: string - Suggested correction if typo detected
|
||||
* - reasons: string[] - Array of reasons describing the verification results
|
||||
*
|
||||
* Example:
|
||||
* {
|
||||
* email: "user@gmial.com"
|
||||
* }
|
||||
*
|
||||
* Response:
|
||||
* {
|
||||
* success: true,
|
||||
* data: {
|
||||
* email: "user@gmial.com",
|
||||
* valid: false,
|
||||
* isDisposable: false,
|
||||
* hasMxRecords: false,
|
||||
* suggestedEmail: "user@gmail.com",
|
||||
* reasons: [
|
||||
* "Possible typo detected, did you mean user@gmail.com?",
|
||||
* "Domain does not exist or has no MX records"
|
||||
* ]
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
@Post('verify')
|
||||
@Middleware([requireSecretKey])
|
||||
@CatchAsync
|
||||
public async verify(req: Request, res: Response, _next: NextFunction) {
|
||||
// Zod validation - errors automatically handled by global error handler
|
||||
const {email} = ActionSchemas.verify.parse(req.body);
|
||||
|
||||
// Verify the email address
|
||||
const verificationResult = await EmailVerificationService.verifyEmail(email);
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
data: verificationResult,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import {Controller, Get, Middleware} from '@overnightjs/core';
|
||||
import type {NextFunction, Request, Response} from 'express';
|
||||
|
||||
import type {AuthResponse} from '../middleware/auth.js';
|
||||
import {requireAuth} from '../middleware/auth.js';
|
||||
import {ActivityService, ActivityType} from '../services/ActivityService.js';
|
||||
import {ActivityType} from '@plunk/types';
|
||||
import {requireAuth, requireEmailVerified} from '../middleware/auth.js';
|
||||
import {ActivityService} from '../services/ActivityService.js';
|
||||
import {CatchAsync} from '../utils/asyncHandler.js';
|
||||
|
||||
@Controller('activity')
|
||||
@@ -21,10 +20,10 @@ export class Activity {
|
||||
* - endDate: ISO date string
|
||||
*/
|
||||
@Get('')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async getActivities(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const limit = Math.min(parseInt(req.query.limit as string) || 50, 100);
|
||||
const cursor = req.query.cursor as string | undefined;
|
||||
const contactId = req.query.contactId as string | undefined;
|
||||
@@ -62,10 +61,10 @@ export class Activity {
|
||||
* - endDate: ISO date string (defaults to now)
|
||||
*/
|
||||
@Get('stats')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async getStats(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const startDate = req.query.startDate ? new Date(req.query.startDate as string) : undefined;
|
||||
const endDate = req.query.endDate ? new Date(req.query.endDate as string) : undefined;
|
||||
|
||||
@@ -82,10 +81,10 @@ export class Activity {
|
||||
* - minutes: number (default 5)
|
||||
*/
|
||||
@Get('recent-count')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async getRecentCount(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const minutes = Math.min(parseInt(req.query.minutes as string) || 5, 60); // Max 60 minutes
|
||||
|
||||
const count = await ActivityService.getRecentActivityCount(auth.projectId, minutes);
|
||||
@@ -98,7 +97,7 @@ export class Activity {
|
||||
* Get available activity types (for UI filters)
|
||||
*/
|
||||
@Get('types')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async getTypes(_req: Request, res: Response, _next: NextFunction) {
|
||||
const types = Object.values(ActivityType);
|
||||
@@ -114,10 +113,10 @@ export class Activity {
|
||||
* - daysAhead: number (default 30, max 90)
|
||||
*/
|
||||
@Get('upcoming')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async getUpcoming(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const limit = Math.min(parseInt(req.query.limit as string) || 50, 100);
|
||||
const daysAhead = Math.min(parseInt(req.query.daysAhead as string) || 30, 90);
|
||||
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import {Controller, Get, Middleware} from '@overnightjs/core';
|
||||
import type {NextFunction, Request, Response} from 'express';
|
||||
|
||||
import type {AuthResponse} from '../middleware/auth.js';
|
||||
import {requireAuth} from '../middleware/auth.js';
|
||||
import {requireAuth, requireEmailVerified} from '../middleware/auth.js';
|
||||
import {AnalyticsService} from '../services/AnalyticsService.js';
|
||||
import {CatchAsync} from '../utils/asyncHandler.js';
|
||||
|
||||
@@ -19,10 +17,10 @@ export class Analytics {
|
||||
* Returns daily aggregated email metrics (sent, opened, clicked, bounced, delivered)
|
||||
*/
|
||||
@Get('timeseries')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async getTimeSeries(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const startDate = req.query.startDate ? new Date(req.query.startDate as string) : undefined;
|
||||
const endDate = req.query.endDate ? new Date(req.query.endDate as string) : undefined;
|
||||
|
||||
@@ -41,10 +39,10 @@ export class Analytics {
|
||||
* - endDate: ISO date string (defaults to now)
|
||||
*/
|
||||
@Get('top-campaigns')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async getTopCampaigns(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const limit = Math.min(parseInt(req.query.limit as string) || 10, 50);
|
||||
const startDate = req.query.startDate ? new Date(req.query.startDate as string) : undefined;
|
||||
const endDate = req.query.endDate ? new Date(req.query.endDate as string) : undefined;
|
||||
@@ -65,10 +63,10 @@ export class Analytics {
|
||||
* Returns aggregate stats: total campaigns, active, completed, average rates
|
||||
*/
|
||||
@Get('campaign-stats')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async getCampaignStats(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const startDate = req.query.startDate ? new Date(req.query.startDate as string) : undefined;
|
||||
const endDate = req.query.endDate ? new Date(req.query.endDate as string) : undefined;
|
||||
|
||||
@@ -89,10 +87,10 @@ export class Analytics {
|
||||
* Returns events sorted by frequency with trend data
|
||||
*/
|
||||
@Get('top-events')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async getTopEvents(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const limit = Math.min(parseInt(req.query.limit as string) || 5, 20);
|
||||
const startDate = req.query.startDate ? new Date(req.query.startDate as string) : undefined;
|
||||
const endDate = req.query.endDate ? new Date(req.query.endDate as string) : undefined;
|
||||
|
||||
@@ -1,12 +1,29 @@
|
||||
import {Controller, Get, Post} from '@overnightjs/core';
|
||||
import {AuthenticationSchemas} from '@plunk/shared';
|
||||
import {EmailVerificationEmail, PasswordResetEmail, sendPlatformEmail} from '@plunk/email';
|
||||
import {randomBytes} from 'node:crypto';
|
||||
import type {NextFunction, Request, Response} from 'express';
|
||||
import * as React from 'react';
|
||||
|
||||
import {GITHUB_OAUTH_ENABLED, GOOGLE_OAUTH_ENABLED} from '../app/constants.js';
|
||||
import {
|
||||
DASHBOARD_URI,
|
||||
DISABLE_SIGNUPS,
|
||||
EMAIL_VERIFICATION_RATE_LIMIT,
|
||||
EMAIL_VERIFICATION_RATE_WINDOW,
|
||||
GITHUB_OAUTH_ENABLED,
|
||||
GOOGLE_OAUTH_ENABLED,
|
||||
LANDING_URI,
|
||||
PASSWORD_RESET_RATE_LIMIT,
|
||||
PLUNK_ENABLED,
|
||||
TOKEN_EXPIRY_SECONDS,
|
||||
VERIFY_EMAIL_ON_SIGNUP,
|
||||
} from '../app/constants.js';
|
||||
import {prisma} from '../database/prisma.js';
|
||||
import {redis, REDIS_ONE_MINUTE} from '../database/redis.js';
|
||||
import {jwt} from '../middleware/auth.js';
|
||||
import {BadRequest, NotAuthenticated, RateLimitError} from '../exceptions/index.js';
|
||||
import {jwt, parseJwt} from '../middleware/auth.js';
|
||||
import {AuthService} from '../services/AuthService.js';
|
||||
import {EmailVerificationService} from '../services/EmailVerificationService.js';
|
||||
import {NtfyService} from '../services/NtfyService.js';
|
||||
import {UserService} from '../services/UserService.js';
|
||||
import {Keys} from '../services/keys.js';
|
||||
@@ -48,8 +65,43 @@ export class Auth {
|
||||
@Post('signup')
|
||||
@CatchAsync
|
||||
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);
|
||||
|
||||
// Verify email is valid and not disposable/plus-addressed (if verification enabled)
|
||||
if (VERIFY_EMAIL_ON_SIGNUP) {
|
||||
const verification = await EmailVerificationService.verifyEmail(email);
|
||||
|
||||
if (
|
||||
verification.isDisposable ||
|
||||
verification.isPlusAddressed ||
|
||||
!verification.domainExists ||
|
||||
!verification.hasMxRecords
|
||||
) {
|
||||
// Build list of reasons for notification
|
||||
const reasons: string[] = [];
|
||||
if (verification.isDisposable) reasons.push('disposable email');
|
||||
if (verification.isPlusAddressed) reasons.push('plus addressing');
|
||||
if (!verification.domainExists) reasons.push('domain does not exist');
|
||||
if (!verification.hasMxRecords) reasons.push('no MX records');
|
||||
|
||||
// Send notification about failed signup attempt
|
||||
await NtfyService.notifyFailedSignupAttempt(email, reasons);
|
||||
|
||||
return res.json({
|
||||
success: false,
|
||||
data: 'This email address cannot be used for signup',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const user = await UserService.email(email);
|
||||
|
||||
if (user) {
|
||||
@@ -64,6 +116,8 @@ export class Auth {
|
||||
email,
|
||||
password: await AuthService.generateHash(password),
|
||||
type: 'PASSWORD',
|
||||
// Auto-verify email if platform emails are disabled
|
||||
emailVerified: !PLUNK_ENABLED,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -72,6 +126,27 @@ export class Auth {
|
||||
// Send notification about new user signup
|
||||
await NtfyService.notifyUserSignup(created_user.email, created_user.id);
|
||||
|
||||
// Send email verification if platform emails are enabled
|
||||
if (PLUNK_ENABLED) {
|
||||
const verificationToken = randomBytes(32).toString('hex');
|
||||
await redis.setex(
|
||||
Keys.User.emailVerificationToken(verificationToken),
|
||||
TOKEN_EXPIRY_SECONDS,
|
||||
JSON.stringify({userId: created_user.id, email: created_user.email, createdAt: Date.now()}),
|
||||
);
|
||||
|
||||
const verificationUrl = `${DASHBOARD_URI}/auth/verify-email?token=${verificationToken}`;
|
||||
await sendPlatformEmail(
|
||||
created_user.email,
|
||||
'Verify your email address',
|
||||
React.createElement(EmailVerificationEmail, {
|
||||
email: created_user.email,
|
||||
verificationUrl,
|
||||
landingUrl: LANDING_URI,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const token = jwt.sign(created_user.id);
|
||||
const cookie = UserService.cookieOptions();
|
||||
|
||||
@@ -97,4 +172,159 @@ export class Auth {
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@Post('verify-email')
|
||||
@CatchAsync
|
||||
public async verifyEmail(req: Request, res: Response, _next: NextFunction) {
|
||||
const {token} = AuthenticationSchemas.verifyEmail.parse(req.body);
|
||||
|
||||
// Look up token in Redis
|
||||
const data = await redis.get(Keys.User.emailVerificationToken(token));
|
||||
|
||||
if (!data) {
|
||||
throw new BadRequest('Invalid or expired verification token');
|
||||
}
|
||||
|
||||
const {userId} = JSON.parse(data);
|
||||
|
||||
// Update user
|
||||
await prisma.user.update({
|
||||
where: {id: userId},
|
||||
data: {emailVerified: true},
|
||||
});
|
||||
|
||||
// Delete token (single use) and invalidate cache
|
||||
await redis.del(Keys.User.emailVerificationToken(token));
|
||||
await redis.del(Keys.User.id(userId));
|
||||
|
||||
return res.json({success: true, data: {message: 'Email verified successfully'}});
|
||||
}
|
||||
|
||||
@Post('request-verification')
|
||||
@CatchAsync
|
||||
public async requestVerification(req: Request, res: Response, _next: NextFunction) {
|
||||
const userId = parseJwt(req);
|
||||
const user = await UserService.id(userId);
|
||||
|
||||
if (!user) {
|
||||
throw new NotAuthenticated();
|
||||
}
|
||||
|
||||
if (user.emailVerified) {
|
||||
return res.json({success: true, data: {message: 'Email already verified'}});
|
||||
}
|
||||
|
||||
// Check rate limit
|
||||
const rateLimitKey = Keys.User.emailVerificationRateLimit(userId);
|
||||
const count = await redis.get(rateLimitKey);
|
||||
|
||||
if (count && parseInt(count) >= EMAIL_VERIFICATION_RATE_LIMIT) {
|
||||
throw new RateLimitError('Too many verification emails sent. Please try again later.');
|
||||
}
|
||||
|
||||
// Generate token
|
||||
const token = randomBytes(32).toString('hex');
|
||||
await redis.setex(
|
||||
Keys.User.emailVerificationToken(token),
|
||||
TOKEN_EXPIRY_SECONDS,
|
||||
JSON.stringify({userId, email: user.email, createdAt: Date.now()}),
|
||||
);
|
||||
|
||||
// Send email
|
||||
const verificationUrl = `${DASHBOARD_URI}/auth/verify-email?token=${token}`;
|
||||
await sendPlatformEmail(
|
||||
user.email,
|
||||
'Verify your email address',
|
||||
React.createElement(EmailVerificationEmail, {email: user.email, verificationUrl, landingUrl: LANDING_URI}),
|
||||
);
|
||||
|
||||
// Increment rate limit
|
||||
if (count) {
|
||||
await redis.incr(rateLimitKey);
|
||||
} else {
|
||||
await redis.setex(rateLimitKey, EMAIL_VERIFICATION_RATE_WINDOW, '1');
|
||||
}
|
||||
|
||||
return res.json({success: true, data: {message: 'Verification email sent'}});
|
||||
}
|
||||
|
||||
@Post('request-password-reset')
|
||||
@CatchAsync
|
||||
public async requestPasswordReset(req: Request, res: Response, _next: NextFunction) {
|
||||
const {email} = AuthenticationSchemas.requestPasswordReset.parse(req.body);
|
||||
|
||||
// Check rate limit
|
||||
const rateLimitKey = Keys.User.passwordResetRateLimit(email);
|
||||
const count = await redis.get(rateLimitKey);
|
||||
|
||||
if (count && parseInt(count) >= PASSWORD_RESET_RATE_LIMIT) {
|
||||
// Still return success to prevent enumeration
|
||||
return res.json({success: true, data: {message: 'If that email exists, a reset link has been sent'}});
|
||||
}
|
||||
|
||||
// Look up user
|
||||
const user = await UserService.email(email);
|
||||
|
||||
// Only send email if user exists and is PASSWORD type
|
||||
if (user && user.type === 'PASSWORD') {
|
||||
const token = randomBytes(32).toString('hex');
|
||||
await redis.setex(
|
||||
Keys.User.passwordResetToken(token),
|
||||
TOKEN_EXPIRY_SECONDS,
|
||||
JSON.stringify({userId: user.id, email: user.email, createdAt: Date.now()}),
|
||||
);
|
||||
|
||||
const resetUrl = `${DASHBOARD_URI}/auth/reset-password?token=${token}`;
|
||||
await sendPlatformEmail(
|
||||
user.email,
|
||||
'Reset your password',
|
||||
React.createElement(PasswordResetEmail, {email: user.email, resetUrl, landingUrl: LANDING_URI}),
|
||||
);
|
||||
|
||||
// Increment rate limit
|
||||
if (count) {
|
||||
await redis.incr(rateLimitKey);
|
||||
} else {
|
||||
await redis.setex(rateLimitKey, EMAIL_VERIFICATION_RATE_WINDOW, '1');
|
||||
}
|
||||
}
|
||||
|
||||
// Always return success (prevent enumeration)
|
||||
return res.json({success: true, data: {message: 'If that email exists, a reset link has been sent'}});
|
||||
}
|
||||
|
||||
@Post('reset-password')
|
||||
@CatchAsync
|
||||
public async resetPassword(req: Request, res: Response, _next: NextFunction) {
|
||||
const {token, newPassword} = AuthenticationSchemas.resetPassword.parse(req.body);
|
||||
|
||||
// Look up token
|
||||
const data = await redis.get(Keys.User.passwordResetToken(token));
|
||||
|
||||
if (!data) {
|
||||
throw new BadRequest('Invalid or expired reset token');
|
||||
}
|
||||
|
||||
const {userId} = JSON.parse(data);
|
||||
|
||||
// Get user and verify type
|
||||
const user = await prisma.user.findUnique({where: {id: userId}});
|
||||
|
||||
if (!user || user.type !== 'PASSWORD') {
|
||||
throw new BadRequest('Invalid reset token');
|
||||
}
|
||||
|
||||
// Hash new password and update
|
||||
const hashedPassword = await AuthService.generateHash(newPassword);
|
||||
await prisma.user.update({
|
||||
where: {id: userId},
|
||||
data: {password: hashedPassword},
|
||||
});
|
||||
|
||||
// Delete token and invalidate cache
|
||||
await redis.del(Keys.User.passwordResetToken(token));
|
||||
await redis.del(Keys.User.id(userId));
|
||||
|
||||
return res.json({success: true, data: {message: 'Password reset successfully'}});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import {Controller, Delete, Get, Middleware, Post, Put} from '@overnightjs/core';
|
||||
import {CampaignAudienceType, CampaignStatus} from '@plunk/db';
|
||||
import {CampaignAudienceType, CampaignStatus, TemplateType} from '@plunk/db';
|
||||
import {CampaignSchemas, UtilitySchemas} from '@plunk/shared';
|
||||
import type {NextFunction, Request, Response} from 'express';
|
||||
|
||||
import {HttpException} from '../exceptions/index.js';
|
||||
import type {AuthResponse} from '../middleware/auth.js';
|
||||
import {requireAuth} from '../middleware/auth.js';
|
||||
import {requireAuth, requireEmailVerified} from '../middleware/auth.js';
|
||||
import {CampaignService} from '../services/CampaignService.js';
|
||||
import {DomainService} from '../services/DomainService.js';
|
||||
import {CatchAsync} from '../utils/asyncHandler.js';
|
||||
@@ -17,14 +16,13 @@ export class Campaigns {
|
||||
* POST /campaigns
|
||||
*/
|
||||
@Post('')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
private async create(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const {name, description, subject, body, from, fromName, replyTo, audienceType, audienceCondition, segmentId} =
|
||||
const auth = res.locals.auth;
|
||||
const {name, description, subject, body, from, fromName, replyTo, type, audienceType, audienceCondition, segmentId} =
|
||||
CampaignSchemas.create.parse(req.body);
|
||||
|
||||
// Validate audience-specific fields
|
||||
if (audienceType === CampaignAudienceType.SEGMENT && !segmentId) {
|
||||
throw new HttpException(400, 'Segment ID is required for SEGMENT audience type');
|
||||
}
|
||||
@@ -44,6 +42,7 @@ export class Campaigns {
|
||||
from,
|
||||
fromName,
|
||||
replyTo,
|
||||
type,
|
||||
audienceType,
|
||||
audienceCondition,
|
||||
segmentId,
|
||||
@@ -60,11 +59,12 @@ export class Campaigns {
|
||||
* GET /campaigns
|
||||
*/
|
||||
@Get('')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
private async list(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const status = req.query.status as CampaignStatus | undefined;
|
||||
const search = typeof req.query.search === 'string' ? req.query.search.trim() || undefined : undefined;
|
||||
const page = parseInt(req.query.page as string) || 1;
|
||||
const pageSize = parseInt(req.query.pageSize as string) || 20;
|
||||
|
||||
@@ -75,17 +75,12 @@ export class Campaigns {
|
||||
|
||||
const result = await CampaignService.list(auth.projectId, {
|
||||
status,
|
||||
search,
|
||||
page,
|
||||
pageSize,
|
||||
});
|
||||
|
||||
return res.json({
|
||||
campaigns: result.campaigns,
|
||||
page: result.page,
|
||||
pageSize: result.pageSize,
|
||||
total: result.total,
|
||||
totalPages: result.totalPages,
|
||||
});
|
||||
return res.json(result);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -93,10 +88,10 @@ export class Campaigns {
|
||||
* GET /campaigns/:id
|
||||
*/
|
||||
@Get(':id')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
private async get(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const {id} = UtilitySchemas.id.parse(req.params);
|
||||
|
||||
const campaign = await CampaignService.get(auth.projectId, id!);
|
||||
@@ -112,12 +107,12 @@ export class Campaigns {
|
||||
* PUT /campaigns/:id
|
||||
*/
|
||||
@Put(':id')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
private async update(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const {id} = UtilitySchemas.id.parse(req.params);
|
||||
const {name, description, subject, body, from, fromName, replyTo, audienceType, audienceCondition, segmentId} =
|
||||
const {name, description, subject, body, from, fromName, replyTo, type, audienceType, audienceCondition, segmentId} =
|
||||
req.body;
|
||||
|
||||
// Validate audience-specific fields if audienceType is being updated
|
||||
@@ -142,6 +137,7 @@ export class Campaigns {
|
||||
from,
|
||||
fromName,
|
||||
replyTo,
|
||||
type: type as TemplateType | undefined,
|
||||
audienceType,
|
||||
audienceCondition,
|
||||
segmentId,
|
||||
@@ -158,10 +154,10 @@ export class Campaigns {
|
||||
* DELETE /campaigns/:id
|
||||
*/
|
||||
@Delete(':id')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
private async delete(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const {id} = UtilitySchemas.id.parse(req.params);
|
||||
|
||||
await CampaignService.delete(auth.projectId, id!);
|
||||
@@ -177,10 +173,10 @@ export class Campaigns {
|
||||
* POST /campaigns/:id/duplicate
|
||||
*/
|
||||
@Post(':id/duplicate')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
private async duplicate(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const {id} = UtilitySchemas.id.parse(req.params);
|
||||
|
||||
const campaign = await CampaignService.duplicate(auth.projectId, id!);
|
||||
@@ -197,10 +193,10 @@ export class Campaigns {
|
||||
* POST /campaigns/:id/send
|
||||
*/
|
||||
@Post(':id/send')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
private async send(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const {id} = UtilitySchemas.id.parse(req.params);
|
||||
const scheduledFor = req.body?.scheduledFor;
|
||||
|
||||
@@ -228,10 +224,10 @@ export class Campaigns {
|
||||
* POST /campaigns/:id/cancel
|
||||
*/
|
||||
@Post(':id/cancel')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
private async cancel(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const {id} = UtilitySchemas.id.parse(req.params);
|
||||
|
||||
const campaign = await CampaignService.cancel(auth.projectId, id!);
|
||||
@@ -248,10 +244,10 @@ export class Campaigns {
|
||||
* GET /campaigns/:id/stats
|
||||
*/
|
||||
@Get(':id/stats')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
private async stats(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const {id} = UtilitySchemas.id.parse(req.params);
|
||||
|
||||
const stats = await CampaignService.getStats(auth.projectId, id!);
|
||||
@@ -267,10 +263,10 @@ export class Campaigns {
|
||||
* POST /campaigns/:id/test
|
||||
*/
|
||||
@Post(':id/test')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
private async sendTest(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const {id} = UtilitySchemas.id.parse(req.params);
|
||||
const {email} = CampaignSchemas.sendTest.parse(req.body);
|
||||
|
||||
|
||||
@@ -3,10 +3,12 @@ import type {Request, Response} from 'express';
|
||||
|
||||
import {
|
||||
API_URI,
|
||||
AWS_SES_REGION,
|
||||
DASHBOARD_URI,
|
||||
GITHUB_OAUTH_ENABLED,
|
||||
GOOGLE_OAUTH_ENABLED,
|
||||
LANDING_URI,
|
||||
MAIL_FROM_SUBDOMAIN,
|
||||
NODE_ENV,
|
||||
S3_ENABLED,
|
||||
SMTP_DOMAIN,
|
||||
@@ -59,6 +61,10 @@ export class Config {
|
||||
: null,
|
||||
},
|
||||
},
|
||||
aws: {
|
||||
sesRegion: AWS_SES_REGION,
|
||||
mailFromSubdomain: MAIL_FROM_SUBDOMAIN,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import {Controller, Delete, Get, Middleware, Patch, Post} from '@overnightjs/core';
|
||||
import type {NextFunction, Request, Response} from 'express';
|
||||
import multer from 'multer';
|
||||
import {ContactSchemas} from '@plunk/shared';
|
||||
import type {BulkContactActionSelector} from '@plunk/types';
|
||||
import signale from 'signale';
|
||||
|
||||
import type {AuthResponse} from '../middleware/auth.js';
|
||||
import {requireAuth} from '../middleware/auth.js';
|
||||
import {requireAuth, requireEmailVerified} from '../middleware/auth.js';
|
||||
import {ContactService} from '../services/ContactService.js';
|
||||
import {QueueService} from '../services/QueueService.js';
|
||||
import {CatchAsync} from '../utils/asyncHandler.js';
|
||||
@@ -16,7 +16,6 @@ const upload = multer({
|
||||
fileSize: 5 * 1024 * 1024, // 5MB max file size
|
||||
},
|
||||
fileFilter: (_req, file, cb) => {
|
||||
// Only accept CSV files
|
||||
if (file.mimetype === 'text/csv' || file.originalname.endsWith('.csv')) {
|
||||
cb(null, true);
|
||||
} else {
|
||||
@@ -32,10 +31,10 @@ export class Contacts {
|
||||
* List all contacts for the authenticated project with cursor-based pagination
|
||||
*/
|
||||
@Get('')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async list(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const limit = Math.min(parseInt(req.query.limit as string) || 20, 100);
|
||||
const cursor = req.query.cursor as string | undefined;
|
||||
const search = req.query.search as string | undefined;
|
||||
@@ -51,10 +50,10 @@ export class Contacts {
|
||||
* Returns field names with inferred types (string, number, boolean, date)
|
||||
*/
|
||||
@Get('fields')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async getAvailableFields(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
|
||||
try {
|
||||
const fieldsWithTypes = await ContactService.getAvailableFields(auth.projectId!);
|
||||
@@ -77,10 +76,10 @@ export class Contacts {
|
||||
* Example: /contacts/fields/data.plan/values or /contacts/fields/subscribed/values
|
||||
*/
|
||||
@Get('fields/:field/values')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async getFieldValues(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const field = req.params.field;
|
||||
const limit = Math.min(parseInt(req.query.limit as string) || 100, 200);
|
||||
|
||||
@@ -110,10 +109,10 @@ export class Contacts {
|
||||
* Get a specific contact by ID
|
||||
*/
|
||||
@Get(':id')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async get(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const contactId = req.params.id;
|
||||
|
||||
if (!contactId) {
|
||||
@@ -130,10 +129,10 @@ export class Contacts {
|
||||
* Create or update a contact (upsert)
|
||||
*/
|
||||
@Post('')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async create(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const {email, data, subscribed} = req.body;
|
||||
|
||||
if (!email) {
|
||||
@@ -160,10 +159,10 @@ export class Contacts {
|
||||
* Update a contact
|
||||
*/
|
||||
@Patch(':id')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async update(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const contactId = req.params.id;
|
||||
const {email, data, subscribed} = req.body;
|
||||
|
||||
@@ -181,10 +180,10 @@ export class Contacts {
|
||||
* Delete a contact
|
||||
*/
|
||||
@Delete(':id')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async delete(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const contactId = req.params.id;
|
||||
|
||||
if (!contactId) {
|
||||
@@ -211,10 +210,24 @@ export class Contacts {
|
||||
|
||||
const contact = await ContactService.getById(contactId);
|
||||
|
||||
// Fetch project to get language preference
|
||||
const project = await ContactService.getProjectByContactId(contactId);
|
||||
|
||||
// Get contact-level locale (overrides project language)
|
||||
const contactLocale =
|
||||
contact.data &&
|
||||
typeof contact.data === 'object' &&
|
||||
!Array.isArray(contact.data) &&
|
||||
'locale' in contact.data &&
|
||||
typeof contact.data.locale === 'string'
|
||||
? contact.data.locale
|
||||
: null;
|
||||
|
||||
return res.status(200).json({
|
||||
id: contact.id,
|
||||
email: contact.email,
|
||||
subscribed: contact.subscribed,
|
||||
language: contactLocale || project?.language || 'en',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -262,6 +275,30 @@ export class Contacts {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /contacts/lookup
|
||||
* Bulk-check which emails already exist in the project (max 500)
|
||||
*/
|
||||
@Post('lookup')
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async lookup(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth;
|
||||
const {emails} = req.body as {emails: string[]};
|
||||
|
||||
if (!Array.isArray(emails) || emails.length === 0) {
|
||||
return res.status(400).json({error: 'emails must be a non-empty array'});
|
||||
}
|
||||
|
||||
if (emails.length > 500) {
|
||||
return res.status(400).json({error: 'Maximum 500 emails per lookup'});
|
||||
}
|
||||
|
||||
const result = await ContactService.lookup(auth.projectId!, emails);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /contacts/import
|
||||
* Import contacts from CSV file
|
||||
@@ -270,7 +307,7 @@ export class Contacts {
|
||||
@Middleware([requireAuth, upload.single('file')])
|
||||
@CatchAsync
|
||||
public async importCsv(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
|
||||
if (!req.file) {
|
||||
return res.status(400).json({error: 'CSV file is required'});
|
||||
@@ -301,9 +338,10 @@ export class Contacts {
|
||||
* Get import job status
|
||||
*/
|
||||
@Get('import/:jobId')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async getImportStatus(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth;
|
||||
const jobId = req.params.jobId;
|
||||
|
||||
if (!jobId) {
|
||||
@@ -311,7 +349,7 @@ export class Contacts {
|
||||
}
|
||||
|
||||
try {
|
||||
const status = await QueueService.getImportJobStatus(jobId);
|
||||
const status = await QueueService.getImportJobStatus(jobId, auth.projectId!);
|
||||
|
||||
if (!status) {
|
||||
return res.status(404).json({error: 'Import job not found'});
|
||||
@@ -332,10 +370,10 @@ export class Contacts {
|
||||
* Returns information about where the field is used and whether it can be safely deleted
|
||||
*/
|
||||
@Get('fields/:field/usage')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async getFieldUsage(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const field = req.params.field;
|
||||
|
||||
if (!field) {
|
||||
@@ -359,10 +397,10 @@ export class Contacts {
|
||||
* Only works if the field is not used in any segments or campaigns
|
||||
*/
|
||||
@Delete('fields/:field')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async deleteField(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const field = req.params.field;
|
||||
|
||||
if (!field) {
|
||||
@@ -379,4 +417,101 @@ export class Contacts {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /contacts/bulk-subscribe
|
||||
* Queue bulk subscribe operation
|
||||
*/
|
||||
@Post('bulk-subscribe')
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async bulkSubscribe(req: Request, res: Response, _next: NextFunction) {
|
||||
return queueBulkAction(req, res, 'subscribe');
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /contacts/bulk-unsubscribe
|
||||
* Queue bulk unsubscribe operation
|
||||
*/
|
||||
@Post('bulk-unsubscribe')
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async bulkUnsubscribe(req: Request, res: Response, _next: NextFunction) {
|
||||
return queueBulkAction(req, res, 'unsubscribe');
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /contacts/bulk-delete
|
||||
* Queue bulk delete operation
|
||||
*/
|
||||
@Post('bulk-delete')
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async bulkDelete(req: Request, res: Response, _next: NextFunction) {
|
||||
return queueBulkAction(req, res, 'delete');
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /contacts/bulk/:jobId
|
||||
* Get bulk action job status
|
||||
*/
|
||||
@Get('bulk/:jobId')
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async getBulkActionStatus(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth;
|
||||
const jobId = req.params.jobId;
|
||||
|
||||
if (!jobId) {
|
||||
return res.status(400).json({error: 'Job ID is required'});
|
||||
}
|
||||
|
||||
try {
|
||||
const status = await QueueService.getBulkActionJobStatus(jobId, auth.projectId!);
|
||||
|
||||
if (!status) {
|
||||
return res.status(404).json({error: 'Bulk action job not found'});
|
||||
}
|
||||
|
||||
return res.status(200).json(status);
|
||||
} catch (error) {
|
||||
signale.error('[CONTACTS] Failed to get bulk action status:', error);
|
||||
return res.status(500).json({
|
||||
error: error instanceof Error ? error.message : 'Failed to get bulk action status',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function queueBulkAction(
|
||||
req: Request,
|
||||
res: Response,
|
||||
operation: 'subscribe' | 'unsubscribe' | 'delete',
|
||||
) {
|
||||
const auth = res.locals.auth;
|
||||
|
||||
const parsed = ContactSchemas.bulkAction.safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
return res.status(400).json({
|
||||
error: parsed.error.errors[0]?.message ?? 'Invalid bulk action payload',
|
||||
});
|
||||
}
|
||||
|
||||
const selector: BulkContactActionSelector =
|
||||
parsed.data.mode === 'ids'
|
||||
? {mode: 'ids', contactIds: parsed.data.contactIds}
|
||||
: {mode: 'query', filter: parsed.data.filter, excludeIds: parsed.data.excludeIds};
|
||||
|
||||
try {
|
||||
const job = await QueueService.queueBulkContactAction(auth.projectId!, selector, operation);
|
||||
return res.status(202).json({
|
||||
message: `Bulk ${operation} queued successfully`,
|
||||
jobId: job.id,
|
||||
});
|
||||
} catch (error) {
|
||||
signale.error(`[CONTACTS] Failed to queue bulk ${operation}:`, error);
|
||||
return res.status(500).json({
|
||||
error: error instanceof Error ? error.message : `Failed to queue bulk ${operation}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,12 +3,12 @@ import {DomainSchemas, UtilitySchemas} from '@plunk/shared';
|
||||
import type {NextFunction, Request, Response} from 'express';
|
||||
|
||||
import {redis} from '../database/redis.js';
|
||||
import {NotFound} from '../exceptions/index.js';
|
||||
import type {AuthResponse} from '../middleware/auth.js';
|
||||
import {isAuthenticated} from '../middleware/auth.js';
|
||||
import {NotAllowed, NotFound} from '../exceptions/index.js';
|
||||
import {requireAuth, requireEmailVerified} from '../middleware/auth.js';
|
||||
import {DomainService} from '../services/DomainService.js';
|
||||
import {Keys} from '../services/keys.js';
|
||||
import {prisma} from '../database/prisma.js';
|
||||
import {MembershipService} from '../services/MembershipService.js';
|
||||
import {SecurityService} from '../services/SecurityService.js';
|
||||
import {CatchAsync} from '../utils/asyncHandler.js';
|
||||
|
||||
@Controller('domains')
|
||||
@@ -17,25 +17,12 @@ export class Domains {
|
||||
* Get all domains for a project
|
||||
*/
|
||||
@Get('project/:projectId')
|
||||
@Middleware([isAuthenticated])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async getProjectDomains(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const {projectId} = DomainSchemas.projectId.parse(req.params);
|
||||
public async getProjectDomains(_req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth;
|
||||
|
||||
// Verify user has access to this project
|
||||
const membership = await prisma.membership.findFirst({
|
||||
where: {
|
||||
userId: auth.userId,
|
||||
projectId,
|
||||
},
|
||||
});
|
||||
|
||||
if (!membership) {
|
||||
throw new NotFound('Project not found or you do not have access');
|
||||
}
|
||||
|
||||
const domains = await DomainService.getProjectDomains(projectId);
|
||||
const domains = await DomainService.getProjectDomains(auth.projectId!);
|
||||
|
||||
return res.status(200).json(domains);
|
||||
}
|
||||
@@ -44,35 +31,44 @@ export class Domains {
|
||||
* Add a new domain to a project
|
||||
*/
|
||||
@Post('')
|
||||
@Middleware([isAuthenticated])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async addDomain(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const {projectId, domain} = DomainSchemas.create.parse(req.body);
|
||||
const auth = res.locals.auth;
|
||||
const {domain} = DomainSchemas.create.parse(req.body);
|
||||
const projectId = auth.projectId!;
|
||||
|
||||
if (!auth.userId) {
|
||||
throw new NotFound('User authentication required');
|
||||
// Require admin role for JWT users (API keys bypass — project-scoped by design)
|
||||
if (auth.type === 'jwt') {
|
||||
await MembershipService.requireAdminAccess(auth.userId!, projectId);
|
||||
}
|
||||
|
||||
// Verify user has admin access to this project
|
||||
const membership = await prisma.membership.findFirst({
|
||||
where: {
|
||||
userId: auth.userId,
|
||||
projectId,
|
||||
role: {
|
||||
in: ['ADMIN', 'OWNER'],
|
||||
},
|
||||
},
|
||||
});
|
||||
// Block domain changes on disabled projects
|
||||
const isDisabled = await SecurityService.isProjectDisabled(projectId);
|
||||
if (isDisabled) {
|
||||
throw new NotAllowed(
|
||||
'This project has been disabled. Please contact support for assistance.',
|
||||
);
|
||||
}
|
||||
|
||||
if (!membership) {
|
||||
throw new NotFound('Project not found or you do not have permission');
|
||||
// Block subdomains whose root domain belongs to a disabled project
|
||||
const rootCheck = await DomainService.checkSubdomainOfDisabledRoot(domain);
|
||||
if (rootCheck.blocked) {
|
||||
throw new NotAllowed(
|
||||
'This domain cannot be added at this time. Please contact support for assistance.',
|
||||
);
|
||||
}
|
||||
|
||||
// Check if domain is already linked to another project
|
||||
const ownershipCheck = await DomainService.checkDomainOwnership(domain, auth.userId);
|
||||
|
||||
if (ownershipCheck.exists) {
|
||||
if (ownershipCheck.projectId === projectId) {
|
||||
return res.status(400).json({
|
||||
error: 'This domain is already linked to this project.',
|
||||
});
|
||||
}
|
||||
|
||||
// If domain exists and user is a member of that project, allow it
|
||||
if (ownershipCheck.isMember) {
|
||||
return res.status(400).json({
|
||||
@@ -104,30 +100,18 @@ export class Domains {
|
||||
* Check verification status for a domain
|
||||
*/
|
||||
@Get(':id/verify')
|
||||
@Middleware([isAuthenticated])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async checkVerification(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const {id} = UtilitySchemas.id.parse(req.params);
|
||||
|
||||
const domain = await DomainService.id(id);
|
||||
|
||||
if (!domain) {
|
||||
if (!domain || domain.projectId !== auth.projectId) {
|
||||
throw new NotFound('Domain not found');
|
||||
}
|
||||
|
||||
// Verify user has access to the project this domain belongs to
|
||||
const membership = await prisma.membership.findFirst({
|
||||
where: {
|
||||
userId: auth.userId,
|
||||
projectId: domain.projectId,
|
||||
},
|
||||
});
|
||||
|
||||
if (!membership) {
|
||||
throw new NotFound('Domain not found or you do not have access');
|
||||
}
|
||||
|
||||
const verificationStatus = await DomainService.checkVerification(id);
|
||||
|
||||
// Invalidate cache if status changed
|
||||
@@ -141,31 +125,29 @@ export class Domains {
|
||||
* Remove a domain from a project
|
||||
*/
|
||||
@Delete(':id')
|
||||
@Middleware([isAuthenticated])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async removeDomain(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const {id} = UtilitySchemas.id.parse(req.params);
|
||||
|
||||
const domain = await DomainService.id(id);
|
||||
|
||||
if (!domain) {
|
||||
if (!domain || domain.projectId !== auth.projectId) {
|
||||
throw new NotFound('Domain not found');
|
||||
}
|
||||
|
||||
// Verify user has admin access to the project this domain belongs to
|
||||
const membership = await prisma.membership.findFirst({
|
||||
where: {
|
||||
userId: auth.userId,
|
||||
projectId: domain.projectId,
|
||||
role: {
|
||||
in: ['ADMIN', 'OWNER'],
|
||||
},
|
||||
},
|
||||
});
|
||||
// Require admin role for JWT users (API keys bypass — project-scoped by design)
|
||||
if (auth.type === 'jwt') {
|
||||
await MembershipService.requireAdminAccess(auth.userId!, domain.projectId);
|
||||
}
|
||||
|
||||
if (!membership) {
|
||||
throw new NotFound('Domain not found or you do not have permission');
|
||||
// Block domain changes on disabled projects
|
||||
const isDisabled = await SecurityService.isProjectDisabled(domain.projectId);
|
||||
if (isDisabled) {
|
||||
throw new NotAllowed(
|
||||
'This project has been disabled. Please contact support for assistance.',
|
||||
);
|
||||
}
|
||||
|
||||
await DomainService.removeDomain(id);
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import {Controller, Delete, Get, Middleware, Post} from '@overnightjs/core';
|
||||
import type {NextFunction, Request, Response} from 'express';
|
||||
import signale from 'signale';
|
||||
|
||||
import type {AuthResponse} from '../middleware/auth.js';
|
||||
import {requireAuth} from '../middleware/auth.js';
|
||||
import {requireAuth, requireEmailVerified} from '../middleware/auth.js';
|
||||
import {EventService} from '../services/EventService.js';
|
||||
import {CatchAsync} from '../utils/asyncHandler.js';
|
||||
|
||||
@@ -14,10 +12,10 @@ export class Events {
|
||||
* Track a custom event (can trigger workflows)
|
||||
*/
|
||||
@Post('track')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async track(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const {name, contactId, emailId, data} = req.body;
|
||||
|
||||
if (!name) {
|
||||
@@ -34,10 +32,10 @@ export class Events {
|
||||
* List events for the project
|
||||
*/
|
||||
@Get('')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async list(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const eventName = req.query.eventName as string | undefined;
|
||||
const limit = parseInt(req.query.limit as string) || 100;
|
||||
|
||||
@@ -51,10 +49,10 @@ export class Events {
|
||||
* Get event statistics
|
||||
*/
|
||||
@Get('stats')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async stats(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const startDate = req.query.startDate ? new Date(req.query.startDate as string) : undefined;
|
||||
const endDate = req.query.endDate ? new Date(req.query.endDate as string) : undefined;
|
||||
|
||||
@@ -68,10 +66,10 @@ export class Events {
|
||||
* Get events for a specific contact
|
||||
*/
|
||||
@Get('contact/:contactId')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async getContactEvents(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const contactId = req.params.contactId;
|
||||
const limit = parseInt(req.query.limit as string) || 50;
|
||||
|
||||
@@ -89,10 +87,10 @@ export class Events {
|
||||
* Get unique event names for the project
|
||||
*/
|
||||
@Get('names')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async getEventNames(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
|
||||
const eventNames = await EventService.getUniqueEventNames(auth.projectId!);
|
||||
|
||||
@@ -105,10 +103,10 @@ export class Events {
|
||||
* Returns information about where the event is used and whether it can be safely deleted
|
||||
*/
|
||||
@Get(':eventName/usage')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async getEventUsage(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const eventName = req.params.eventName;
|
||||
|
||||
if (!eventName) {
|
||||
@@ -132,10 +130,10 @@ export class Events {
|
||||
* Only works if the event is not used in any segments or workflows
|
||||
*/
|
||||
@Delete(':eventName')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async deleteEvent(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const eventName = req.params.eventName;
|
||||
|
||||
if (!eventName) {
|
||||
|
||||
@@ -4,11 +4,13 @@ import type {NextFunction, Request, Response} from 'express';
|
||||
import {
|
||||
API_URI,
|
||||
DASHBOARD_URI,
|
||||
DISABLE_SIGNUPS,
|
||||
GITHUB_OAUTH_CLIENT,
|
||||
GITHUB_OAUTH_ENABLED,
|
||||
GITHUB_OAUTH_SECRET,
|
||||
} from '../../app/constants.js';
|
||||
import {prisma} from '../../database/prisma.js';
|
||||
import {BadRequest} from '../../exceptions/index.js';
|
||||
import {jwt} from '../../middleware/auth.js';
|
||||
import {NtfyService} from '../../services/NtfyService.js';
|
||||
import {UserService} from '../../services/UserService.js';
|
||||
@@ -81,10 +83,16 @@ export class Github {
|
||||
let isNewUser = false;
|
||||
|
||||
if (!user) {
|
||||
// Check if signups are disabled
|
||||
if (DISABLE_SIGNUPS) {
|
||||
throw new BadRequest('New user signups are currently disabled');
|
||||
}
|
||||
|
||||
user = await prisma.user.create({
|
||||
data: {
|
||||
email,
|
||||
type: 'GITHUB_OAUTH',
|
||||
emailVerified: true,
|
||||
},
|
||||
});
|
||||
isNewUser = true;
|
||||
|
||||
@@ -4,11 +4,13 @@ import type {NextFunction, Request, Response} from 'express';
|
||||
import {
|
||||
API_URI,
|
||||
DASHBOARD_URI,
|
||||
DISABLE_SIGNUPS,
|
||||
GOOGLE_OAUTH_CLIENT,
|
||||
GOOGLE_OAUTH_ENABLED,
|
||||
GOOGLE_OAUTH_SECRET,
|
||||
} from '../../app/constants.js';
|
||||
import {prisma} from '../../database/prisma.js';
|
||||
import {BadRequest} from '../../exceptions/index.js';
|
||||
import {jwt} from '../../middleware/auth.js';
|
||||
import {NtfyService} from '../../services/NtfyService.js';
|
||||
import {UserService} from '../../services/UserService.js';
|
||||
@@ -71,10 +73,16 @@ export class Google {
|
||||
let isNewUser = false;
|
||||
|
||||
if (!user) {
|
||||
// Check if signups are disabled
|
||||
if (DISABLE_SIGNUPS) {
|
||||
throw new BadRequest('New user signups are currently disabled');
|
||||
}
|
||||
|
||||
user = await prisma.user.create({
|
||||
data: {
|
||||
email,
|
||||
type: 'GOOGLE_OAUTH',
|
||||
emailVerified: true,
|
||||
},
|
||||
});
|
||||
isNewUser = true;
|
||||
|
||||
@@ -4,8 +4,8 @@ import {MembershipSchemas, UtilitySchemas} from '@plunk/shared';
|
||||
|
||||
import {prisma} from '../database/prisma.js';
|
||||
import {HttpException} from '../exceptions/index.js';
|
||||
import type {AuthResponse} from '../middleware/auth.js';
|
||||
import {requireAuth} from '../middleware/auth.js';
|
||||
import {requireAuth, requireEmailVerified} from '../middleware/auth.js';
|
||||
import {MembershipService} from '../services/MembershipService.js';
|
||||
import {SecurityService} from '../services/SecurityService.js';
|
||||
import {CatchAsync} from '../utils/asyncHandler.js';
|
||||
|
||||
@@ -16,23 +16,14 @@ export class Projects {
|
||||
* GET /projects/:id/setup-state
|
||||
*/
|
||||
@Get(':id/setup-state')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
private async getSetupState(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const {id} = UtilitySchemas.id.parse(req.params);
|
||||
|
||||
// Verify user has access to this project
|
||||
const membership = await prisma.membership.findFirst({
|
||||
where: {
|
||||
userId: auth.userId,
|
||||
projectId: id,
|
||||
},
|
||||
});
|
||||
|
||||
if (!membership) {
|
||||
throw new HttpException(404, 'Project not found or you do not have access');
|
||||
}
|
||||
await MembershipService.requireAccess(auth.userId!, id);
|
||||
|
||||
// Get project with relevant data
|
||||
const project = await prisma.project.findUnique({
|
||||
@@ -89,23 +80,14 @@ export class Projects {
|
||||
* GET /projects/:id/security
|
||||
*/
|
||||
@Get(':id/security')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
private async getSecurityMetrics(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const {id} = UtilitySchemas.id.parse(req.params);
|
||||
|
||||
// Verify user has access to this project
|
||||
const membership = await prisma.membership.findFirst({
|
||||
where: {
|
||||
userId: auth.userId,
|
||||
projectId: id,
|
||||
},
|
||||
});
|
||||
|
||||
if (!membership) {
|
||||
throw new HttpException(404, 'Project not found or you do not have access');
|
||||
}
|
||||
await MembershipService.requireAccess(auth.userId!, id);
|
||||
|
||||
// Use existing SecurityService
|
||||
const metrics = await SecurityService.getProjectSecurityMetrics(id);
|
||||
@@ -121,46 +103,21 @@ export class Projects {
|
||||
* GET /projects/:id/members
|
||||
*/
|
||||
@Get(':id/members')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
private async getMembers(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const {id} = UtilitySchemas.id.parse(req.params);
|
||||
|
||||
// Verify user has access to this project
|
||||
const membership = await prisma.membership.findFirst({
|
||||
where: {
|
||||
userId: auth.userId,
|
||||
projectId: id,
|
||||
},
|
||||
});
|
||||
|
||||
if (!membership) {
|
||||
throw new HttpException(404, 'Project not found or you do not have access');
|
||||
}
|
||||
await MembershipService.requireAccess(auth.userId!, id);
|
||||
|
||||
// Get all members of the project
|
||||
const members = await prisma.membership.findMany({
|
||||
where: {
|
||||
projectId: id,
|
||||
},
|
||||
include: {
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const members = await MembershipService.getMembers(id);
|
||||
|
||||
return res.json({
|
||||
success: true,
|
||||
data: members.map(m => ({
|
||||
userId: m.user.id,
|
||||
email: m.user.email,
|
||||
role: m.role,
|
||||
})),
|
||||
data: members,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -170,10 +127,10 @@ export class Projects {
|
||||
* Body: { email: string, role?: 'ADMIN' | 'MEMBER' }
|
||||
*/
|
||||
@Post(':id/members')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
private async addMember(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const {id} = UtilitySchemas.id.parse(req.params);
|
||||
|
||||
// Validate params
|
||||
@@ -190,19 +147,7 @@ export class Projects {
|
||||
const {email, role} = parseResult.data;
|
||||
|
||||
// Verify current user is ADMIN or OWNER
|
||||
const currentMembership = await prisma.membership.findFirst({
|
||||
where: {
|
||||
userId: auth.userId,
|
||||
projectId: id,
|
||||
role: {
|
||||
in: ['ADMIN', 'OWNER'],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!currentMembership) {
|
||||
throw new HttpException(403, 'Only project admins and owners can add members');
|
||||
}
|
||||
await MembershipService.requireAdminAccess(auth.userId!, id);
|
||||
|
||||
// Find user by email
|
||||
const userToAdd = await prisma.user.findUnique({
|
||||
@@ -214,28 +159,8 @@ export class Projects {
|
||||
throw new HttpException(404, 'User with this email does not have an account');
|
||||
}
|
||||
|
||||
// Check if user is already a member
|
||||
const existingMembership = await prisma.membership.findUnique({
|
||||
where: {
|
||||
userId_projectId: {
|
||||
userId: userToAdd.id,
|
||||
projectId: id,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (existingMembership) {
|
||||
throw new HttpException(409, 'User is already a member of this project');
|
||||
}
|
||||
|
||||
// Create membership
|
||||
const newMembership = await prisma.membership.create({
|
||||
data: {
|
||||
userId: userToAdd.id,
|
||||
projectId: id,
|
||||
role,
|
||||
},
|
||||
});
|
||||
// Add member to project
|
||||
const newMembership = await MembershipService.addMember(id, userToAdd.id, role);
|
||||
|
||||
return res.json({
|
||||
success: true,
|
||||
@@ -253,10 +178,10 @@ export class Projects {
|
||||
* Body: { role: 'ADMIN' | 'MEMBER' }
|
||||
*/
|
||||
@Patch(':id/members/:userId')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
private async updateMemberRole(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const {id, userId} = req.params;
|
||||
|
||||
// Validate params
|
||||
@@ -276,38 +201,7 @@ export class Projects {
|
||||
const {role} = parseResult.data;
|
||||
|
||||
// Verify current user is ADMIN or OWNER
|
||||
const currentMembership = await prisma.membership.findFirst({
|
||||
where: {
|
||||
userId: auth.userId,
|
||||
projectId: id,
|
||||
role: {
|
||||
in: ['ADMIN', 'OWNER'],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!currentMembership) {
|
||||
throw new HttpException(403, 'Only project admins and owners can update member roles');
|
||||
}
|
||||
|
||||
// Get target membership
|
||||
const targetMembership = await prisma.membership.findUnique({
|
||||
where: {
|
||||
userId_projectId: {
|
||||
userId,
|
||||
projectId: id,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!targetMembership) {
|
||||
throw new HttpException(404, 'Member not found');
|
||||
}
|
||||
|
||||
// Cannot change OWNER role
|
||||
if (targetMembership.role === 'OWNER') {
|
||||
throw new HttpException(403, 'Cannot change the role of the project owner');
|
||||
}
|
||||
await MembershipService.requireAdminAccess(auth.userId!, id);
|
||||
|
||||
// Get user info
|
||||
const user = await prisma.user.findUnique({
|
||||
@@ -319,16 +213,8 @@ export class Projects {
|
||||
throw new HttpException(404, 'User not found');
|
||||
}
|
||||
|
||||
// Update role
|
||||
await prisma.membership.update({
|
||||
where: {
|
||||
userId_projectId: {
|
||||
userId,
|
||||
projectId: id,
|
||||
},
|
||||
},
|
||||
data: {role},
|
||||
});
|
||||
// Update role (service handles validation)
|
||||
await MembershipService.updateRole(id, userId, role);
|
||||
|
||||
return res.json({
|
||||
success: true,
|
||||
@@ -345,10 +231,10 @@ export class Projects {
|
||||
* DELETE /projects/:id/members/:userId
|
||||
*/
|
||||
@Delete(':id/members/:userId')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
private async removeMember(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const {id, userId} = req.params;
|
||||
|
||||
// Validate params
|
||||
@@ -360,53 +246,15 @@ export class Projects {
|
||||
}
|
||||
|
||||
// Verify current user is ADMIN or OWNER
|
||||
const currentMembership = await prisma.membership.findFirst({
|
||||
where: {
|
||||
userId: auth.userId,
|
||||
projectId: id,
|
||||
role: {
|
||||
in: ['ADMIN', 'OWNER'],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!currentMembership) {
|
||||
throw new HttpException(403, 'Only project admins and owners can remove members');
|
||||
}
|
||||
|
||||
// Get target membership
|
||||
const targetMembership = await prisma.membership.findUnique({
|
||||
where: {
|
||||
userId_projectId: {
|
||||
userId,
|
||||
projectId: id,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!targetMembership) {
|
||||
throw new HttpException(404, 'Member not found');
|
||||
}
|
||||
|
||||
// Cannot remove OWNER
|
||||
if (targetMembership.role === 'OWNER') {
|
||||
throw new HttpException(403, 'Cannot remove the project owner');
|
||||
}
|
||||
await MembershipService.requireAdminAccess(auth.userId!, id);
|
||||
|
||||
// Cannot remove yourself
|
||||
if (userId === auth.userId) {
|
||||
throw new HttpException(403, 'You cannot remove yourself from the project');
|
||||
}
|
||||
|
||||
// Delete membership
|
||||
await prisma.membership.delete({
|
||||
where: {
|
||||
userId_projectId: {
|
||||
userId,
|
||||
projectId: id,
|
||||
},
|
||||
},
|
||||
});
|
||||
// Remove member (service handles validation)
|
||||
await MembershipService.removeMember(id, userId);
|
||||
|
||||
return res.json({
|
||||
success: true,
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import {Controller, Delete, Get, Middleware, Patch, Post} from '@overnightjs/core';
|
||||
import type {NextFunction, Request, Response} from 'express';
|
||||
|
||||
import type {AuthResponse} from '../middleware/auth.js';
|
||||
import {requireAuth} from '../middleware/auth.js';
|
||||
import {requireAuth, requireEmailVerified} from '../middleware/auth.js';
|
||||
import {SegmentService} from '../services/SegmentService.js';
|
||||
import {CatchAsync} from '../utils/asyncHandler.js';
|
||||
|
||||
@@ -13,10 +11,10 @@ export class Segments {
|
||||
* List all segments for the authenticated project
|
||||
*/
|
||||
@Get('')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async list(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
|
||||
const segments = await SegmentService.list(auth.projectId!);
|
||||
|
||||
@@ -28,10 +26,10 @@ export class Segments {
|
||||
* Get a specific segment by ID with member count
|
||||
*/
|
||||
@Get(':id')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async get(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const segmentId = req.params.id;
|
||||
|
||||
if (!segmentId) {
|
||||
@@ -48,10 +46,10 @@ export class Segments {
|
||||
* Get contacts that match a segment's filters
|
||||
*/
|
||||
@Get(':id/contacts')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async getContacts(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const segmentId = req.params.id;
|
||||
const page = parseInt(req.query.page as string) || 1;
|
||||
const pageSize = Math.min(parseInt(req.query.pageSize as string) || 20, 100);
|
||||
@@ -70,24 +68,27 @@ export class Segments {
|
||||
* Create a new segment
|
||||
*/
|
||||
@Post('')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async create(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const {name, description, condition, trackMembership} = req.body;
|
||||
const auth = res.locals.auth;
|
||||
const {name, description, type, condition, trackMembership} = req.body;
|
||||
|
||||
if (!name) {
|
||||
return res.status(400).json({error: 'Name is required'});
|
||||
}
|
||||
|
||||
if (!condition || typeof condition !== 'object') {
|
||||
return res.status(400).json({error: 'Condition is required and must be an object'});
|
||||
const segmentType = type ?? 'DYNAMIC';
|
||||
|
||||
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!, {
|
||||
name,
|
||||
description,
|
||||
condition,
|
||||
type: segmentType,
|
||||
condition: segmentType === 'DYNAMIC' ? condition : undefined,
|
||||
trackMembership,
|
||||
});
|
||||
|
||||
@@ -99,10 +100,10 @@ export class Segments {
|
||||
* Update a segment
|
||||
*/
|
||||
@Patch(':id')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async update(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const segmentId = req.params.id;
|
||||
const {name, description, condition, trackMembership} = req.body;
|
||||
|
||||
@@ -129,10 +130,10 @@ export class Segments {
|
||||
* Delete a segment
|
||||
*/
|
||||
@Delete(':id')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async delete(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const segmentId = req.params.id;
|
||||
|
||||
if (!segmentId) {
|
||||
@@ -144,15 +145,65 @@ export class Segments {
|
||||
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, createMissing, subscribed} = req.body as {emails: string[]; createMissing?: boolean; subscribed?: boolean};
|
||||
|
||||
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, createMissing ?? false, subscribed ?? true);
|
||||
|
||||
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
|
||||
* Recompute segment membership for all contacts
|
||||
*/
|
||||
@Post(':id/compute')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async compute(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const segmentId = req.params.id;
|
||||
|
||||
if (!segmentId) {
|
||||
@@ -169,10 +220,10 @@ export class Segments {
|
||||
* Refresh segment member count
|
||||
*/
|
||||
@Post(':id/refresh')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async refresh(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const segmentId = req.params.id;
|
||||
|
||||
if (!segmentId) {
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import {Controller, Delete, Get, Middleware, Patch, Post} from '@overnightjs/core';
|
||||
import {TemplateType} from '@plunk/db';
|
||||
import type {NextFunction, Request, Response} from 'express';
|
||||
|
||||
import type {AuthResponse} from '../middleware/auth.js';
|
||||
import {requireAuth} from '../middleware/auth.js';
|
||||
import {requireAuth, requireEmailVerified} from '../middleware/auth.js';
|
||||
import {DomainService} from '../services/DomainService.js';
|
||||
import {TemplateService} from '../services/TemplateService.js';
|
||||
import {CatchAsync} from '../utils/asyncHandler.js';
|
||||
@@ -15,10 +13,10 @@ export class Templates {
|
||||
* List all templates for the authenticated project
|
||||
*/
|
||||
@Get('')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async list(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const page = parseInt(req.query.page as string) || 1;
|
||||
const pageSize = Math.min(parseInt(req.query.pageSize as string) || 20, 100);
|
||||
const search = req.query.search as string | undefined;
|
||||
@@ -34,10 +32,10 @@ export class Templates {
|
||||
* Get a specific template by ID
|
||||
*/
|
||||
@Get(':id')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async get(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const templateId = req.params.id;
|
||||
|
||||
if (!templateId) {
|
||||
@@ -54,10 +52,10 @@ export class Templates {
|
||||
* Create a new template
|
||||
*/
|
||||
@Post('')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async create(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const {name, description, subject, body, from, fromName, replyTo, type} = req.body;
|
||||
|
||||
if (!name) {
|
||||
@@ -98,10 +96,10 @@ export class Templates {
|
||||
* Update a template
|
||||
*/
|
||||
@Patch(':id')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async update(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const templateId = req.params.id;
|
||||
const {name, description, subject, body, from, fromName, replyTo, type} = req.body;
|
||||
|
||||
@@ -133,10 +131,10 @@ export class Templates {
|
||||
* Delete a template
|
||||
*/
|
||||
@Delete(':id')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async delete(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const templateId = req.params.id;
|
||||
|
||||
if (!templateId) {
|
||||
@@ -153,10 +151,10 @@ export class Templates {
|
||||
* Duplicate a template
|
||||
*/
|
||||
@Post(':id/duplicate')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async duplicate(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const templateId = req.params.id;
|
||||
|
||||
if (!templateId) {
|
||||
@@ -173,10 +171,10 @@ export class Templates {
|
||||
* Get template usage statistics
|
||||
*/
|
||||
@Get(':id/usage')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async getUsage(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const templateId = req.params.id;
|
||||
|
||||
if (!templateId) {
|
||||
|
||||
@@ -2,12 +2,24 @@ import {Controller, Middleware, Post} from '@overnightjs/core';
|
||||
import type {NextFunction, Request, Response} from 'express';
|
||||
import multer from 'multer';
|
||||
import signale from 'signale';
|
||||
|
||||
import type {AuthResponse} from '../middleware/auth.js';
|
||||
import {requireAuth} from '../middleware/auth.js';
|
||||
import {requireAuth, requireEmailVerified} from '../middleware/auth.js';
|
||||
import * as S3Service from '../services/S3Service.js';
|
||||
import {CatchAsync} from '../utils/asyncHandler.js';
|
||||
|
||||
const MAGIC_BYTES: Record<string, Buffer[]> = {
|
||||
'image/jpeg': [Buffer.from([0xff, 0xd8, 0xff])],
|
||||
'image/jpg': [Buffer.from([0xff, 0xd8, 0xff])],
|
||||
'image/png': [Buffer.from([0x89, 0x50, 0x4e, 0x47])],
|
||||
'image/gif': [Buffer.from('GIF87a'), Buffer.from('GIF89a')],
|
||||
'image/webp': [Buffer.from('RIFF')],
|
||||
};
|
||||
|
||||
function validateMagicBytes(buffer: Buffer, mimetype: string): boolean {
|
||||
const signatures = MAGIC_BYTES[mimetype];
|
||||
if (!signatures) return false;
|
||||
return signatures.some(sig => buffer.subarray(0, sig.length).equals(sig));
|
||||
}
|
||||
|
||||
// Configure multer for file uploads (memory storage)
|
||||
const upload = multer({
|
||||
storage: multer.memoryStorage(),
|
||||
@@ -15,13 +27,12 @@ const upload = multer({
|
||||
fileSize: 10 * 1024 * 1024, // 10MB max file size
|
||||
},
|
||||
fileFilter: (_req, file, cb) => {
|
||||
// Only accept image files
|
||||
const allowedMimeTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml'];
|
||||
const allowedMimeTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
|
||||
|
||||
if (allowedMimeTypes.includes(file.mimetype)) {
|
||||
cb(null, true);
|
||||
} else {
|
||||
cb(new Error('Only image files are allowed (JPEG, PNG, GIF, WebP, SVG)'));
|
||||
cb(new Error('Only image files are allowed (JPEG, PNG, GIF, WebP)'));
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -33,10 +44,10 @@ export class Uploads {
|
||||
* Upload an image file to S3/Minio
|
||||
*/
|
||||
@Post('image')
|
||||
@Middleware([requireAuth, upload.single('image')])
|
||||
@Middleware([requireAuth, requireEmailVerified, upload.single('image')])
|
||||
@CatchAsync
|
||||
public async uploadImage(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
|
||||
try {
|
||||
if (!S3Service.isS3Enabled()) {
|
||||
@@ -51,6 +62,12 @@ export class Uploads {
|
||||
});
|
||||
}
|
||||
|
||||
if (!validateMagicBytes(req.file.buffer, req.file.mimetype)) {
|
||||
return res.status(400).json({
|
||||
error: 'File contents do not match the declared image type',
|
||||
});
|
||||
}
|
||||
|
||||
// Upload file to S3/Minio
|
||||
const result = await S3Service.uploadFile({
|
||||
file: req.file.buffer,
|
||||
|
||||
@@ -8,9 +8,9 @@ import {DASHBOARD_URI, STRIPE_ENABLED, STRIPE_PRICE_EMAIL_USAGE, STRIPE_PRICE_ON
|
||||
import {stripe} from '../app/stripe.js';
|
||||
import {prisma} from '../database/prisma.js';
|
||||
import {ErrorCode, HttpException, NotAuthenticated, NotFound} from '../exceptions/index.js';
|
||||
import type {AuthResponse} from '../middleware/auth.js';
|
||||
import {isAuthenticated} from '../middleware/auth.js';
|
||||
import {isAuthenticated, requireEmailVerified} from '../middleware/auth.js';
|
||||
import {BillingLimitService} from '../services/BillingLimitService.js';
|
||||
import {MembershipService} from '../services/MembershipService.js';
|
||||
import {NtfyService} from '../services/NtfyService.js';
|
||||
import {SecurityService} from '../services/SecurityService.js';
|
||||
import {UserService} from '../services/UserService.js';
|
||||
@@ -20,10 +20,10 @@ import signale from 'signale';
|
||||
@Controller('users')
|
||||
export class Users {
|
||||
@Get('@me')
|
||||
@Middleware([isAuthenticated])
|
||||
@Middleware([isAuthenticated, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async me(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
|
||||
if (!auth.userId) {
|
||||
throw new NotAuthenticated();
|
||||
@@ -39,10 +39,10 @@ export class Users {
|
||||
}
|
||||
|
||||
@Get('@me/projects')
|
||||
@Middleware([isAuthenticated])
|
||||
@Middleware([isAuthenticated, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async meProjects(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
|
||||
if (!auth.userId) {
|
||||
throw new NotAuthenticated();
|
||||
@@ -54,10 +54,10 @@ export class Users {
|
||||
}
|
||||
|
||||
@Post('@me/projects')
|
||||
@Middleware([isAuthenticated])
|
||||
@Middleware([isAuthenticated, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async createProject(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
|
||||
if (!auth.userId) {
|
||||
throw new NotAuthenticated();
|
||||
@@ -68,7 +68,7 @@ export class Users {
|
||||
if (hasDisabledProject) {
|
||||
throw new HttpException(
|
||||
403,
|
||||
`You cannot create new projects while you are a member of disabled projects: ${disabledProjectNames.join(', ')}. Please contact support to resolve security violations.`,
|
||||
`You cannot create new projects at this time. Please contact support for assistance.`,
|
||||
ErrorCode.PROJECT_DISABLED,
|
||||
);
|
||||
}
|
||||
@@ -101,27 +101,15 @@ export class Users {
|
||||
}
|
||||
|
||||
@Patch('@me/projects/:id')
|
||||
@Middleware([isAuthenticated])
|
||||
@Middleware([isAuthenticated, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async updateProject(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const {id} = UtilitySchemas.id.parse(req.params);
|
||||
const data = ProjectSchemas.update.parse(req.body);
|
||||
|
||||
// Verify user has access to this project
|
||||
const membership = await prisma.membership.findFirst({
|
||||
where: {
|
||||
userId: auth.userId,
|
||||
projectId: id,
|
||||
role: {
|
||||
in: ['ADMIN', 'OWNER'],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!membership) {
|
||||
throw new NotFound('Project not found or you do not have permission to update it');
|
||||
}
|
||||
// Verify user has admin/owner access to this project
|
||||
await MembershipService.requireAdminAccess(auth.userId!, id);
|
||||
|
||||
// Update the project
|
||||
const project = await prisma.project.update({
|
||||
@@ -133,26 +121,14 @@ export class Users {
|
||||
}
|
||||
|
||||
@Post('@me/projects/:id/regenerate-keys')
|
||||
@Middleware([isAuthenticated])
|
||||
@Middleware([isAuthenticated, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async regenerateProjectKeys(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const {id} = UtilitySchemas.id.parse(req.params);
|
||||
|
||||
// Verify user has admin/owner access to this project
|
||||
const membership = await prisma.membership.findFirst({
|
||||
where: {
|
||||
userId: auth.userId,
|
||||
projectId: id,
|
||||
role: {
|
||||
in: ['ADMIN', 'OWNER'],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!membership) {
|
||||
throw new NotFound('Project not found or you do not have permission to regenerate keys');
|
||||
}
|
||||
await MembershipService.requireAdminAccess(auth.userId!, id);
|
||||
|
||||
// Generate new unique API keys
|
||||
const publicKey = `pk_${randomBytes(32).toString('hex')}`;
|
||||
@@ -185,31 +161,20 @@ export class Users {
|
||||
}
|
||||
|
||||
@Post('@me/projects/:id/checkout')
|
||||
@Middleware([isAuthenticated])
|
||||
@Middleware([isAuthenticated, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async createCheckoutSession(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const {id} = UtilitySchemas.id.parse(req.params);
|
||||
const {currency} = req.query;
|
||||
|
||||
// Check if billing is enabled
|
||||
if (!STRIPE_ENABLED || !stripe) {
|
||||
return res.status(404).json({error: 'Billing is not enabled'});
|
||||
}
|
||||
|
||||
// Verify user has access to this project
|
||||
const membership = await prisma.membership.findFirst({
|
||||
where: {
|
||||
userId: auth.userId,
|
||||
projectId: id,
|
||||
role: {
|
||||
in: ['ADMIN', 'OWNER'],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!membership) {
|
||||
throw new NotFound('Project not found or you do not have permission to manage billing');
|
||||
}
|
||||
// Verify user has admin/owner access to this project
|
||||
await MembershipService.requireAdminAccess(auth.userId!, id);
|
||||
|
||||
// Get the project
|
||||
const project = await prisma.project.findUnique({
|
||||
@@ -245,6 +210,17 @@ export class Users {
|
||||
const nextMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);
|
||||
const billingCycleAnchor = Math.floor(nextMonth.getTime() / 1000);
|
||||
|
||||
// Validate currency if provided
|
||||
let checkoutCurrency: string | undefined;
|
||||
if (currency && typeof currency === 'string') {
|
||||
const validCurrencies = ['usd', 'eur', 'gbp'];
|
||||
if (validCurrencies.includes(currency.toLowerCase())) {
|
||||
checkoutCurrency = currency.toLowerCase();
|
||||
} else {
|
||||
return res.status(400).json({error: 'Invalid currency. Supported: USD, EUR, GBP'});
|
||||
}
|
||||
}
|
||||
|
||||
// Create checkout session
|
||||
// Note: proration_behavior cannot be set when one-time prices are included
|
||||
// The billing_cycle_anchor alone ensures the subscription is anchored to the 1st of the month
|
||||
@@ -253,6 +229,15 @@ export class Users {
|
||||
customer: project.customer ?? undefined, // Use existing customer if available
|
||||
client_reference_id: project.id, // Store project ID for webhook
|
||||
line_items: lineItems,
|
||||
...(checkoutCurrency && {currency: checkoutCurrency}),
|
||||
custom_fields: [
|
||||
{
|
||||
key: 'promo_code',
|
||||
label: {type: 'custom', custom: 'Promo code'},
|
||||
type: 'text',
|
||||
optional: true,
|
||||
},
|
||||
],
|
||||
subscription_data: {
|
||||
billing_cycle_anchor: billingCycleAnchor,
|
||||
},
|
||||
@@ -264,10 +249,10 @@ export class Users {
|
||||
}
|
||||
|
||||
@Post('@me/projects/:id/billing-portal')
|
||||
@Middleware([isAuthenticated])
|
||||
@Middleware([isAuthenticated, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async createBillingPortalSession(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const {id} = UtilitySchemas.id.parse(req.params);
|
||||
|
||||
// Check if billing is enabled
|
||||
@@ -275,20 +260,8 @@ export class Users {
|
||||
return res.status(404).json({error: 'Billing is not enabled'});
|
||||
}
|
||||
|
||||
// Verify user has access to this project
|
||||
const membership = await prisma.membership.findFirst({
|
||||
where: {
|
||||
userId: auth.userId,
|
||||
projectId: id,
|
||||
role: {
|
||||
in: ['ADMIN', 'OWNER'],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!membership) {
|
||||
throw new NotFound('Project not found or you do not have permission to manage billing');
|
||||
}
|
||||
// Verify user has admin/owner access to this project
|
||||
await MembershipService.requireAdminAccess(auth.userId!, id);
|
||||
|
||||
// Get the project
|
||||
const project = await prisma.project.findUnique({
|
||||
@@ -314,10 +287,10 @@ export class Users {
|
||||
}
|
||||
|
||||
@Get('@me/projects/:id/billing-limits')
|
||||
@Middleware([isAuthenticated])
|
||||
@Middleware([isAuthenticated, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async getBillingLimits(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const {id} = UtilitySchemas.id.parse(req.params);
|
||||
|
||||
if (!auth.userId) {
|
||||
@@ -329,16 +302,7 @@ export class Users {
|
||||
}
|
||||
|
||||
// Verify user has access to this project
|
||||
const membership = await prisma.membership.findFirst({
|
||||
where: {
|
||||
userId: auth.userId,
|
||||
projectId: id,
|
||||
},
|
||||
});
|
||||
|
||||
if (!membership) {
|
||||
throw new NotFound('Project not found or you do not have permission to view billing limits');
|
||||
}
|
||||
await MembershipService.requireAccess(auth.userId!, id);
|
||||
|
||||
// Get billing limits and usage
|
||||
const limitsAndUsage = await BillingLimitService.getLimitsAndUsage(id);
|
||||
@@ -347,10 +311,10 @@ export class Users {
|
||||
}
|
||||
|
||||
@Put('@me/projects/:id/billing-limits')
|
||||
@Middleware([isAuthenticated])
|
||||
@Middleware([isAuthenticated, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async updateBillingLimits(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const {id} = UtilitySchemas.id.parse(req.params);
|
||||
|
||||
if (!auth.userId) {
|
||||
@@ -364,19 +328,7 @@ export class Users {
|
||||
const data = BillingLimitSchemas.update.parse(req.body);
|
||||
|
||||
// Verify user has admin/owner access to this project
|
||||
const membership = await prisma.membership.findFirst({
|
||||
where: {
|
||||
userId: auth.userId,
|
||||
projectId: id,
|
||||
role: {
|
||||
in: ['ADMIN', 'OWNER'],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!membership) {
|
||||
throw new NotFound('Project not found or you do not have permission to update billing limits');
|
||||
}
|
||||
await MembershipService.requireAdminAccess(auth.userId!, id);
|
||||
|
||||
// Get the project with current limits
|
||||
const project = await prisma.project.findUnique({
|
||||
@@ -386,6 +338,7 @@ export class Users {
|
||||
billingLimitWorkflows: true,
|
||||
billingLimitCampaigns: true,
|
||||
billingLimitTransactional: true,
|
||||
billingLimitInbound: true,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -405,6 +358,7 @@ export class Users {
|
||||
billingLimitWorkflows: data.workflows,
|
||||
billingLimitCampaigns: data.campaigns,
|
||||
billingLimitTransactional: data.transactional,
|
||||
billingLimitInbound: data.inbound,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -416,6 +370,7 @@ export class Users {
|
||||
workflows: project.billingLimitWorkflows,
|
||||
campaigns: project.billingLimitCampaigns,
|
||||
transactional: project.billingLimitTransactional,
|
||||
inbound: project.billingLimitInbound,
|
||||
},
|
||||
data,
|
||||
);
|
||||
@@ -426,10 +381,10 @@ export class Users {
|
||||
}
|
||||
|
||||
@Get('@me/projects/:id/billing-consumption')
|
||||
@Middleware([isAuthenticated])
|
||||
@Middleware([isAuthenticated, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async getBillingConsumption(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const {id} = UtilitySchemas.id.parse(req.params);
|
||||
|
||||
// Check if billing is enabled
|
||||
@@ -446,16 +401,7 @@ export class Users {
|
||||
}
|
||||
|
||||
// Verify user has access to this project
|
||||
const membership = await prisma.membership.findFirst({
|
||||
where: {
|
||||
userId: auth.userId,
|
||||
projectId: id,
|
||||
},
|
||||
});
|
||||
|
||||
if (!membership) {
|
||||
throw new NotFound('Project not found or you do not have permission to view billing');
|
||||
}
|
||||
await MembershipService.requireAccess(auth.userId!, id);
|
||||
|
||||
const project = await prisma.project.findUnique({
|
||||
where: {id},
|
||||
@@ -552,10 +498,10 @@ export class Users {
|
||||
}
|
||||
|
||||
@Get('@me/projects/:id/billing-invoices')
|
||||
@Middleware([isAuthenticated])
|
||||
@Middleware([isAuthenticated, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async getBillingInvoices(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const {id} = UtilitySchemas.id.parse(req.params);
|
||||
|
||||
// Check if billing is enabled
|
||||
@@ -572,16 +518,7 @@ export class Users {
|
||||
}
|
||||
|
||||
// Verify user has access to this project
|
||||
const membership = await prisma.membership.findFirst({
|
||||
where: {
|
||||
userId: auth.userId,
|
||||
projectId: id,
|
||||
},
|
||||
});
|
||||
|
||||
if (!membership) {
|
||||
throw new NotFound('Project not found or you do not have permission to view billing');
|
||||
}
|
||||
await MembershipService.requireAccess(auth.userId!, id);
|
||||
|
||||
// Get the project
|
||||
const project = await prisma.project.findUnique({
|
||||
@@ -640,10 +577,10 @@ export class Users {
|
||||
}
|
||||
|
||||
@Get('@me/projects/:id/security')
|
||||
@Middleware([isAuthenticated])
|
||||
@Middleware([isAuthenticated, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async getSecurityHealth(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const {id} = UtilitySchemas.id.parse(req.params);
|
||||
|
||||
if (!auth.userId) {
|
||||
@@ -655,16 +592,7 @@ export class Users {
|
||||
}
|
||||
|
||||
// Verify user has access to this project
|
||||
const membership = await prisma.membership.findFirst({
|
||||
where: {
|
||||
userId: auth.userId,
|
||||
projectId: id,
|
||||
},
|
||||
});
|
||||
|
||||
if (!membership) {
|
||||
throw new NotFound('Project not found or you do not have permission to view security metrics');
|
||||
}
|
||||
await MembershipService.requireAccess(auth.userId!, id);
|
||||
|
||||
// Get security metrics
|
||||
const metrics = await SecurityService.getProjectSecurityMetrics(id);
|
||||
@@ -673,10 +601,10 @@ export class Users {
|
||||
}
|
||||
|
||||
@Post('@me/projects/:id/reset')
|
||||
@Middleware([isAuthenticated])
|
||||
@Middleware([isAuthenticated, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async resetProject(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const {id} = UtilitySchemas.id.parse(req.params);
|
||||
|
||||
if (!auth.userId) {
|
||||
@@ -688,26 +616,14 @@ export class Users {
|
||||
}
|
||||
|
||||
// Verify user has admin/owner access to this project
|
||||
const membership = await prisma.membership.findFirst({
|
||||
where: {
|
||||
userId: auth.userId,
|
||||
projectId: id,
|
||||
role: {
|
||||
in: ['ADMIN', 'OWNER'],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!membership) {
|
||||
throw new NotFound('Project not found or you do not have permission to reset it');
|
||||
}
|
||||
await MembershipService.requireAdminAccess(auth.userId!, id);
|
||||
|
||||
// Check if project is disabled - block reset operation
|
||||
const isDisabled = await SecurityService.isProjectDisabled(id);
|
||||
if (isDisabled) {
|
||||
throw new HttpException(
|
||||
403,
|
||||
'Cannot reset a disabled project. Please contact support to resolve security violations before making changes.',
|
||||
'This project has been disabled. Please contact support for assistance.',
|
||||
ErrorCode.PROJECT_DISABLED,
|
||||
);
|
||||
}
|
||||
@@ -759,10 +675,10 @@ export class Users {
|
||||
}
|
||||
|
||||
@Delete('@me/projects/:id')
|
||||
@Middleware([isAuthenticated])
|
||||
@Middleware([isAuthenticated, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async deleteProject(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const {id} = UtilitySchemas.id.parse(req.params);
|
||||
|
||||
if (!auth.userId) {
|
||||
@@ -774,21 +690,7 @@ export class Users {
|
||||
}
|
||||
|
||||
// Verify user has owner or admin access to this project
|
||||
const membership = await prisma.membership.findFirst({
|
||||
where: {
|
||||
userId: auth.userId,
|
||||
projectId: id,
|
||||
role: {
|
||||
in: ['OWNER', 'ADMIN'],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!membership) {
|
||||
throw new NotFound(
|
||||
'Project not found or you do not have permission to delete it. Only project owners and admins can delete projects.',
|
||||
);
|
||||
}
|
||||
await MembershipService.requireAdminAccess(auth.userId!, id);
|
||||
|
||||
// Get project to check for active subscription and disabled status
|
||||
const project = await prisma.project.findUnique({
|
||||
@@ -809,7 +711,7 @@ export class Users {
|
||||
if (project.disabled) {
|
||||
throw new HttpException(
|
||||
403,
|
||||
'Cannot delete a disabled project. Please contact support to resolve security violations.',
|
||||
'This project has been disabled. Please contact support for assistance.',
|
||||
ErrorCode.PROJECT_DISABLED,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,14 +1,23 @@
|
||||
import {Controller, Post} from '@overnightjs/core';
|
||||
import type {Prisma} from '@plunk/db';
|
||||
import {EmailStatus} from '@plunk/db';
|
||||
import {EmailSourceType, EmailStatus} from '@plunk/db';
|
||||
import type {Request, Response} from 'express';
|
||||
import {simpleParser} from 'mailparser';
|
||||
import sanitizeHtml from 'sanitize-html';
|
||||
import signale from 'signale';
|
||||
import type Stripe from 'stripe';
|
||||
|
||||
import {STRIPE_ENABLED, STRIPE_WEBHOOK_SECRET} from '../app/constants.js';
|
||||
import {ProjectDisabledPaymentEmail, sendPlatformEmail} from '@plunk/email';
|
||||
import React from 'react';
|
||||
|
||||
import {DASHBOARD_URI, LANDING_URI, STRIPE_ENABLED, STRIPE_WEBHOOK_SECRET} from '../app/constants.js';
|
||||
import {stripe} from '../app/stripe.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 {MembershipService} from '../services/MembershipService.js';
|
||||
import {MeterService} from '../services/MeterService.js';
|
||||
import {NtfyService} from '../services/NtfyService.js';
|
||||
import {SecurityService} from '../services/SecurityService.js';
|
||||
import {CatchAsync} from '../utils/asyncHandler.js';
|
||||
@@ -21,20 +30,52 @@ import {CatchAsync} from '../utils/asyncHandler.js';
|
||||
export class Webhooks {
|
||||
/**
|
||||
* 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')
|
||||
@CatchAsync
|
||||
public async receiveSNSWebhook(req: Request, res: Response) {
|
||||
try {
|
||||
// Verify SNS message signature before processing anything
|
||||
const signatureValid = await SecurityService.verifySnsSignature(req.body as Record<string, string>);
|
||||
if (!signatureValid) {
|
||||
signale.warn('[WEBHOOK] SNS signature verification failed — request rejected');
|
||||
return res.status(403).json({success: false, message: 'Invalid SNS signature'});
|
||||
}
|
||||
|
||||
// Handle SNS subscription confirmation FIRST (before parsing Message field)
|
||||
if (req.body.Type === 'SubscriptionConfirmation') {
|
||||
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 or sns.<region>.amazonaws.eu
|
||||
const SNS_HOST_RE = /^sns\.[a-z0-9-]+\.amazonaws\.(com|eu)$/;
|
||||
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
|
||||
try {
|
||||
const confirmResponse = await fetch(req.body.SubscribeURL);
|
||||
const confirmResponse = await fetch(subscribeURL);
|
||||
if (confirmResponse.ok) {
|
||||
signale.success('SNS subscription confirmed successfully');
|
||||
return res.status(200).json({
|
||||
@@ -46,7 +87,6 @@ export class Webhooks {
|
||||
return res.status(200).json({
|
||||
success: false,
|
||||
message: 'Failed to confirm subscription',
|
||||
subscribeURL: req.body.SubscribeURL,
|
||||
});
|
||||
}
|
||||
} catch (confirmError) {
|
||||
@@ -54,7 +94,6 @@ export class Webhooks {
|
||||
return res.status(200).json({
|
||||
success: false,
|
||||
message: 'Error confirming subscription',
|
||||
subscribeURL: req.body.SubscribeURL,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -67,6 +106,185 @@ export class Webhooks {
|
||||
|
||||
// Parse the nested SES event from the Message field
|
||||
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;
|
||||
|
||||
// Parse email content if available
|
||||
let htmlBody: string | undefined;
|
||||
|
||||
if (body.content && typeof body.content === 'string') {
|
||||
try {
|
||||
const isBase64 = body.receipt?.action?.encoding === 'BASE64';
|
||||
const emailBuffer = isBase64
|
||||
? Buffer.from(body.content, 'base64')
|
||||
: Buffer.from(body.content);
|
||||
|
||||
const parsed = await simpleParser(emailBuffer);
|
||||
const raw =
|
||||
(parsed.html ? String(parsed.html) : undefined) ??
|
||||
parsed.textAsHtml ??
|
||||
parsed.text ??
|
||||
undefined;
|
||||
|
||||
if (raw) {
|
||||
htmlBody = sanitizeHtml(raw, {
|
||||
allowedTags: sanitizeHtml.defaults.allowedTags.concat(['img']),
|
||||
allowedAttributes: {
|
||||
...sanitizeHtml.defaults.allowedAttributes,
|
||||
img: ['src', 'alt', 'width', 'height'],
|
||||
'*': ['style'],
|
||||
},
|
||||
allowedSchemes: ['http', 'https', 'mailto'],
|
||||
});
|
||||
}
|
||||
} catch (parseError) {
|
||||
signale.error('[WEBHOOK] Failed to parse email content:', parseError);
|
||||
}
|
||||
}
|
||||
|
||||
// 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 with parsed content
|
||||
const inboundEmail = await prisma.email.create({
|
||||
data: {
|
||||
projectId: domainRecord.projectId,
|
||||
contactId: contact!.id,
|
||||
subject: body.mail?.commonHeaders?.subject || '(No subject)',
|
||||
body: htmlBody || '', // Store HTML body in the body field
|
||||
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 including body content
|
||||
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,
|
||||
// Email body content
|
||||
body: htmlBody,
|
||||
// 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 messageId = body.mail?.messageId;
|
||||
|
||||
@@ -99,6 +317,7 @@ export class Webhooks {
|
||||
from: email.from,
|
||||
fromName: email.fromName,
|
||||
messageId: email.messageId,
|
||||
emailId: email.id,
|
||||
templateId: email.templateId,
|
||||
campaignId: email.campaignId,
|
||||
sourceType: email.sourceType,
|
||||
@@ -152,29 +371,62 @@ export class Webhooks {
|
||||
break;
|
||||
}
|
||||
|
||||
case 'Bounce':
|
||||
signale.warn(`[WEBHOOK] Bounce received for ${email.contact.email} from ${email.project.name}`);
|
||||
updateData.status = EmailStatus.BOUNCED;
|
||||
updateData.bouncedAt = now;
|
||||
// Unsubscribe contact on bounce
|
||||
await prisma.contact.update({
|
||||
where: {id: email.contactId},
|
||||
data: {subscribed: false},
|
||||
});
|
||||
eventData = {
|
||||
...baseEventData,
|
||||
bounceType: body.bounce?.bounceType,
|
||||
bouncedAt: now.toISOString(),
|
||||
};
|
||||
case 'Bounce': {
|
||||
const bounceType = body.bounce?.bounceType;
|
||||
const isPermanentBounce = bounceType === 'Permanent';
|
||||
const isTransientBounce = bounceType === 'Transient';
|
||||
|
||||
// Send notification about bounce
|
||||
await NtfyService.notifyEmailBounce(
|
||||
email.project.name,
|
||||
email.projectId,
|
||||
email.contact.email,
|
||||
body.bounce?.bounceType,
|
||||
);
|
||||
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.bouncedAt = now;
|
||||
// Unsubscribe contact on permanent bounce
|
||||
await prisma.contact.update({
|
||||
where: {id: email.contactId},
|
||||
data: {subscribed: false},
|
||||
});
|
||||
eventData = {
|
||||
...baseEventData,
|
||||
bounceType,
|
||||
bouncedAt: now.toISOString(),
|
||||
};
|
||||
|
||||
// Send notification about permanent bounce
|
||||
await NtfyService.notifyEmailBounce(email.project.name, email.projectId, email.contact.email, bounceType);
|
||||
} else if (isTransientBounce) {
|
||||
// Soft bounce (e.g., out-of-office, mailbox full) - don't count toward bounce rate
|
||||
signale.info(
|
||||
`[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;
|
||||
}
|
||||
|
||||
case 'Complaint':
|
||||
signale.warn(`[WEBHOOK] Complaint received for ${email.contact.email} from ${email.project.name}`);
|
||||
@@ -208,8 +460,10 @@ export class Webhooks {
|
||||
// Track event (this will trigger workflows)
|
||||
await EventService.trackEvent(email.projectId, eventName, email.contactId, email.id, eventData);
|
||||
|
||||
// Check security limits for bounce and complaint events
|
||||
if (eventType === 'Bounce' || eventType === 'Complaint') {
|
||||
// Check security limits only for permanent bounces and complaints
|
||||
// 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);
|
||||
}
|
||||
|
||||
@@ -276,10 +530,24 @@ export class Webhooks {
|
||||
},
|
||||
});
|
||||
|
||||
// Base onboarding credit: refund the 1-unit card-verification charge
|
||||
let creditBalance = -100;
|
||||
|
||||
// Switching-offer promo: 2 extra units of credit if the customer typed SWITCH
|
||||
// into the Promo code custom field on Stripe Checkout.
|
||||
const promoField = session.custom_fields?.find((f) => f.key === 'promo_code');
|
||||
const promoCode = promoField?.text?.value?.trim().toUpperCase();
|
||||
if (promoCode === 'SWITCH') {
|
||||
creditBalance -= 200;
|
||||
signale.success(`[WEBHOOK] SWITCH promo applied for project ${projectId}`);
|
||||
} else if (promoCode) {
|
||||
signale.info(`[WEBHOOK] Unknown promo code "${promoCode}" entered for project ${projectId}`);
|
||||
}
|
||||
|
||||
// Update Stripe customer name to match project name and add credit for onboarding fee
|
||||
await stripe.customers.update(customerId, {
|
||||
name: updatedProject.name,
|
||||
balance: -100,
|
||||
balance: creditBalance,
|
||||
});
|
||||
|
||||
signale.success(`[WEBHOOK] Checkout completed for project ${projectId}`);
|
||||
@@ -305,6 +573,16 @@ export class Webhooks {
|
||||
|
||||
signale.success(`[WEBHOOK] Invoice paid for project ${project.name} (${project.id})`);
|
||||
|
||||
// Re-enable the project only if it was previously disabled for a failed payment.
|
||||
// Projects disabled for other reasons (reputation, phishing, manual) must stay disabled.
|
||||
if (project.disabled && project.disabledReason === 'PAYMENT_FAILED') {
|
||||
await prisma.project.update({
|
||||
where: {id: project.id},
|
||||
data: {disabled: false, disabledReason: null},
|
||||
});
|
||||
signale.success(`[WEBHOOK] Project ${project.name} (${project.id}) re-enabled after payment`);
|
||||
}
|
||||
|
||||
// Send notification about invoice payment
|
||||
await NtfyService.notifyInvoicePaid(project.name, project.id);
|
||||
break;
|
||||
@@ -314,6 +592,16 @@ export class Webhooks {
|
||||
const invoice = event.data.object;
|
||||
const customerId = invoice.customer as string;
|
||||
|
||||
// Only disable projects that are already consuming (recurring billing).
|
||||
// If billing_reason is 'subscription_create', this is a first-time payment
|
||||
// attempt and the project has never had an active subscription — don't disable.
|
||||
if (invoice.billing_reason === 'subscription_create') {
|
||||
signale.info(
|
||||
`[WEBHOOK] Payment failed on initial subscription attempt for customer ${customerId}, skipping disable`,
|
||||
);
|
||||
break;
|
||||
}
|
||||
|
||||
// Find project by customer ID
|
||||
const project = await prisma.project.findUnique({
|
||||
where: {customer: customerId},
|
||||
@@ -324,10 +612,33 @@ export class Webhooks {
|
||||
break;
|
||||
}
|
||||
|
||||
signale.warn(`[WEBHOOK] Payment failed for project ${project.name} (${project.id})`);
|
||||
signale.warn(`[WEBHOOK] Payment failed for project ${project.name} (${project.id}), disabling project`);
|
||||
|
||||
// Send notification about payment failure
|
||||
await NtfyService.notifyPaymentFailed(project.name, project.id);
|
||||
await prisma.project.update({
|
||||
where: {id: project.id},
|
||||
data: {disabled: true, disabledReason: 'PAYMENT_FAILED'},
|
||||
});
|
||||
|
||||
await NtfyService.notifyProjectDisabledForPayment(project.name, project.id);
|
||||
|
||||
// Send email notification to project members
|
||||
try {
|
||||
const members = await MembershipService.getMembers(project.id);
|
||||
const emails = members.map(m => m.email);
|
||||
if (emails.length > 0) {
|
||||
const template = React.createElement(ProjectDisabledPaymentEmail, {
|
||||
projectName: project.name,
|
||||
projectId: project.id,
|
||||
dashboardUrl: DASHBOARD_URI,
|
||||
landingUrl: LANDING_URI,
|
||||
});
|
||||
await Promise.all(
|
||||
emails.map(email => sendPlatformEmail(email, 'Project Disabled - Payment Failed', template)),
|
||||
);
|
||||
}
|
||||
} catch (emailError) {
|
||||
signale.error(`[WEBHOOK] Failed to send project disabled email:`, emailError);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -384,6 +695,86 @@ export class Webhooks {
|
||||
break;
|
||||
}
|
||||
|
||||
case 'radar.early_fraud_warning.created': {
|
||||
const warning = event.data.object as Stripe.Radar.EarlyFraudWarning;
|
||||
const chargeId = typeof warning.charge === 'string' ? warning.charge : warning.charge?.id;
|
||||
|
||||
if (!chargeId) {
|
||||
signale.warn('[WEBHOOK] radar.early_fraud_warning.created missing charge ID');
|
||||
break;
|
||||
}
|
||||
|
||||
signale.warn(`[WEBHOOK] Early fraud warning received for charge ${chargeId} (${warning.fraud_type})`);
|
||||
|
||||
// Retrieve the charge to get card fingerprint and customer email
|
||||
const charge = await stripe.charges.retrieve(chargeId, {
|
||||
expand: ['payment_method_details', 'billing_details'],
|
||||
});
|
||||
|
||||
const cardFingerprint = charge.payment_method_details?.card?.fingerprint ?? null;
|
||||
const customerEmail = charge.billing_details?.email ?? null;
|
||||
|
||||
// Refund the charge
|
||||
try {
|
||||
await stripe.refunds.create({charge: chargeId});
|
||||
signale.success(`[WEBHOOK] Refunded charge ${chargeId} due to early fraud warning`);
|
||||
} catch (refundError) {
|
||||
signale.error(`[WEBHOOK] Failed to refund charge ${chargeId}:`, refundError);
|
||||
}
|
||||
|
||||
// Add card fingerprint and email to Stripe Radar blocklist value lists
|
||||
if (cardFingerprint) {
|
||||
try {
|
||||
const lists = await stripe.radar.valueLists.list({alias: 'blocked_card_fingerprints'});
|
||||
let listId: string;
|
||||
|
||||
const existingList = lists.data[0];
|
||||
if (existingList) {
|
||||
listId = existingList.id;
|
||||
} else {
|
||||
const newList = await stripe.radar.valueLists.create({
|
||||
alias: 'blocked_card_fingerprints',
|
||||
name: 'Blocked Card Fingerprints',
|
||||
item_type: 'card_fingerprint',
|
||||
});
|
||||
listId = newList.id;
|
||||
}
|
||||
|
||||
await stripe.radar.valueListItems.create({value_list: listId, value: cardFingerprint});
|
||||
signale.success(`[WEBHOOK] Added card fingerprint ${cardFingerprint} to Radar blocklist`);
|
||||
} catch (blocklistError) {
|
||||
signale.error(`[WEBHOOK] Failed to add card fingerprint to Radar blocklist:`, blocklistError);
|
||||
}
|
||||
}
|
||||
|
||||
if (customerEmail) {
|
||||
try {
|
||||
const emailLists = await stripe.radar.valueLists.list({alias: 'blocked_emails'});
|
||||
let emailListId: string;
|
||||
|
||||
const existingEmailList = emailLists.data[0];
|
||||
if (existingEmailList) {
|
||||
emailListId = existingEmailList.id;
|
||||
} else {
|
||||
const newList = await stripe.radar.valueLists.create({
|
||||
alias: 'blocked_emails',
|
||||
name: 'Blocked Emails',
|
||||
item_type: 'email',
|
||||
});
|
||||
emailListId = newList.id;
|
||||
}
|
||||
|
||||
await stripe.radar.valueListItems.create({value_list: emailListId, value: customerEmail});
|
||||
signale.success(`[WEBHOOK] Added email ${customerEmail} to Radar blocklist`);
|
||||
} catch (blocklistError) {
|
||||
signale.error(`[WEBHOOK] Failed to add email to Radar blocklist:`, blocklistError);
|
||||
}
|
||||
}
|
||||
|
||||
await NtfyService.notifyEarlyFraudWarning(chargeId, warning.fraud_type, cardFingerprint, customerEmail);
|
||||
break;
|
||||
}
|
||||
|
||||
// Unhandled events
|
||||
default:
|
||||
signale.info(`[WEBHOOK] Unhandled Stripe event type: ${event.type}`);
|
||||
|
||||
@@ -2,9 +2,7 @@ import {Controller, Delete, Get, Middleware, Patch, Post} from '@overnightjs/cor
|
||||
import {WorkflowExecutionStatus} from '@plunk/db';
|
||||
import type {NextFunction, Request, Response} from 'express';
|
||||
import signale from 'signale';
|
||||
|
||||
import type {AuthResponse} from '../middleware/auth.js';
|
||||
import {requireAuth} from '../middleware/auth.js';
|
||||
import {requireAuth, requireEmailVerified} from '../middleware/auth.js';
|
||||
import {WorkflowService} from '../services/WorkflowService.js';
|
||||
import {CatchAsync} from '../utils/asyncHandler.js';
|
||||
|
||||
@@ -15,10 +13,10 @@ export class Workflows {
|
||||
* List all workflows for the authenticated project
|
||||
*/
|
||||
@Get('')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async list(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const page = parseInt(req.query.page as string) || 1;
|
||||
const pageSize = Math.min(parseInt(req.query.pageSize as string) || 20, 100);
|
||||
const search = req.query.search as string | undefined;
|
||||
@@ -35,10 +33,10 @@ export class Workflows {
|
||||
* NOTE: This must be defined BEFORE the :id route to avoid conflicts
|
||||
*/
|
||||
@Get('fields')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async getAvailableFields(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const eventName = req.query.eventName as string | undefined;
|
||||
|
||||
try {
|
||||
@@ -58,10 +56,10 @@ export class Workflows {
|
||||
* Get a specific workflow with all steps and transitions
|
||||
*/
|
||||
@Get(':id')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async get(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const workflowId = req.params.id;
|
||||
|
||||
if (!workflowId) {
|
||||
@@ -78,10 +76,10 @@ export class Workflows {
|
||||
* Create a new workflow
|
||||
*/
|
||||
@Post('')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async create(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const {name, description, eventName, enabled, allowReentry} = req.body;
|
||||
|
||||
if (!name) {
|
||||
@@ -108,10 +106,10 @@ export class Workflows {
|
||||
* Update a workflow
|
||||
*/
|
||||
@Patch(':id')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async update(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const workflowId = req.params.id;
|
||||
const {name, description, triggerType, triggerConfig, enabled, allowReentry} = req.body;
|
||||
|
||||
@@ -136,10 +134,10 @@ export class Workflows {
|
||||
* Delete a workflow
|
||||
*/
|
||||
@Delete(':id')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async delete(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const workflowId = req.params.id;
|
||||
|
||||
if (!workflowId) {
|
||||
@@ -151,15 +149,35 @@ export class Workflows {
|
||||
return res.status(204).send();
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /workflows/:id/duplicate
|
||||
* Duplicate a workflow (always disabled, no execution state)
|
||||
*/
|
||||
@Post(':id/duplicate')
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async duplicate(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth;
|
||||
const workflowId = req.params.id;
|
||||
|
||||
if (!workflowId) {
|
||||
return res.status(400).json({error: 'Workflow ID is required'});
|
||||
}
|
||||
|
||||
const workflow = await WorkflowService.duplicate(auth.projectId!, workflowId);
|
||||
|
||||
return res.status(201).json(workflow);
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /workflows/:id/steps
|
||||
* Add a step to a workflow
|
||||
*/
|
||||
@Post(':id/steps')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async addStep(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const workflowId = req.params.id;
|
||||
const {type, name, position, config, templateId, autoConnect} = req.body;
|
||||
|
||||
@@ -188,10 +206,10 @@ export class Workflows {
|
||||
* Update a workflow step
|
||||
*/
|
||||
@Patch(':id/steps/:stepId')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async updateStep(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const workflowId = req.params.id;
|
||||
const stepId = req.params.stepId;
|
||||
const {name, position, config, templateId} = req.body;
|
||||
@@ -215,18 +233,23 @@ export class Workflows {
|
||||
* Delete a workflow step
|
||||
*/
|
||||
@Delete(':id/steps/:stepId')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async deleteStep(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const workflowId = req.params.id;
|
||||
const stepId = req.params.stepId;
|
||||
const splice = req.query.splice === 'true';
|
||||
|
||||
if (!workflowId || !stepId) {
|
||||
return res.status(400).json({error: 'Workflow ID and Step ID are required'});
|
||||
}
|
||||
|
||||
await WorkflowService.deleteStep(auth.projectId!, workflowId, stepId);
|
||||
if (splice) {
|
||||
await WorkflowService.spliceStep(auth.projectId!, workflowId, stepId);
|
||||
} else {
|
||||
await WorkflowService.deleteStep(auth.projectId!, workflowId, stepId);
|
||||
}
|
||||
|
||||
return res.status(204).send();
|
||||
}
|
||||
@@ -236,10 +259,10 @@ export class Workflows {
|
||||
* Create a transition between steps
|
||||
*/
|
||||
@Post(':id/transitions')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async createTransition(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const workflowId = req.params.id;
|
||||
const {fromStepId, toStepId, condition, priority} = req.body;
|
||||
|
||||
@@ -266,10 +289,10 @@ export class Workflows {
|
||||
* Delete a transition
|
||||
*/
|
||||
@Delete(':id/transitions/:transitionId')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async deleteTransition(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const workflowId = req.params.id;
|
||||
const transitionId = req.params.transitionId;
|
||||
|
||||
@@ -287,10 +310,10 @@ export class Workflows {
|
||||
* Start a workflow execution for a contact
|
||||
*/
|
||||
@Post(':id/executions')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async startExecution(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const workflowId = req.params.id;
|
||||
const {contactId, context} = req.body;
|
||||
|
||||
@@ -312,10 +335,10 @@ export class Workflows {
|
||||
* List executions for a workflow
|
||||
*/
|
||||
@Get(':id/executions')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async listExecutions(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const workflowId = req.params.id;
|
||||
const page = parseInt(req.query.page as string) || 1;
|
||||
const pageSize = Math.min(parseInt(req.query.pageSize as string) || 20, 100);
|
||||
@@ -335,10 +358,10 @@ export class Workflows {
|
||||
* Get a specific execution with details
|
||||
*/
|
||||
@Get(':id/executions/:executionId')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async getExecution(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const workflowId = req.params.id;
|
||||
const executionId = req.params.executionId;
|
||||
|
||||
@@ -356,10 +379,10 @@ export class Workflows {
|
||||
* Cancel a workflow execution
|
||||
*/
|
||||
@Delete(':id/executions/:executionId')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async cancelExecution(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const workflowId = req.params.id;
|
||||
const executionId = req.params.executionId;
|
||||
|
||||
@@ -377,10 +400,10 @@ export class Workflows {
|
||||
* Cancel all active executions for a workflow
|
||||
*/
|
||||
@Post(':id/executions/cancel-all')
|
||||
@Middleware([requireAuth])
|
||||
@Middleware([requireAuth, requireEmailVerified])
|
||||
@CatchAsync
|
||||
public async cancelAllExecutions(req: Request, res: Response, _next: NextFunction) {
|
||||
const auth = res.locals.auth as AuthResponse;
|
||||
const auth = res.locals.auth;
|
||||
const workflowId = req.params.id;
|
||||
|
||||
if (!workflowId) {
|
||||
|
||||
@@ -11,6 +11,7 @@ export enum ErrorCode {
|
||||
FORBIDDEN = 'FORBIDDEN',
|
||||
PROJECT_ACCESS_DENIED = 'PROJECT_ACCESS_DENIED',
|
||||
PROJECT_DISABLED = 'PROJECT_DISABLED',
|
||||
EMAIL_VERIFICATION_REQUIRED = 'EMAIL_VERIFICATION_REQUIRED',
|
||||
|
||||
// Resource Errors (404-409)
|
||||
RESOURCE_NOT_FOUND = 'RESOURCE_NOT_FOUND',
|
||||
@@ -73,9 +74,7 @@ export class NotFound extends HttpException {
|
||||
* @param id Optional resource identifier to include in the message
|
||||
*/
|
||||
public constructor(resource: string, id?: string) {
|
||||
const message = id
|
||||
? `${resource} with ID "${id}" was not found`
|
||||
: `That ${resource.toLowerCase()} was not found`;
|
||||
const message = id ? `${resource} with ID "${id}" was not found` : `That ${resource.toLowerCase()} was not found`;
|
||||
|
||||
// Map common resources to specific error codes
|
||||
const errorCodeMap: Record<string, ErrorCode> = {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import type {Prisma} from '@plunk/db';
|
||||
import {EmailSourceType, EmailStatus, TrackingMode} from '@plunk/db';
|
||||
import {toPrismaJson} from '@plunk/types';
|
||||
import {createServiceMocks, factories, getPrismaClient} from '../../../../../test/helpers';
|
||||
|
||||
// Mock MeterService
|
||||
@@ -29,12 +29,6 @@ describe('Email Processor', () => {
|
||||
status: EmailStatus.PENDING,
|
||||
});
|
||||
|
||||
// Mock the email processor logic
|
||||
// In a real implementation, you would:
|
||||
// 1. Create job tester
|
||||
// 2. Mock SES service
|
||||
// 3. Process the job
|
||||
// 4. Verify status changes
|
||||
|
||||
// Simulate processing
|
||||
await prisma.email.update({
|
||||
@@ -261,13 +255,13 @@ describe('Email Processor', () => {
|
||||
from: 'test@example.com',
|
||||
status: EmailStatus.PENDING,
|
||||
sourceType: EmailSourceType.TRANSACTIONAL,
|
||||
attachments: [
|
||||
attachments: toPrismaJson([
|
||||
{
|
||||
filename: 'document.pdf',
|
||||
content: 'base64encodedcontent',
|
||||
contentType: 'application/pdf',
|
||||
},
|
||||
] as unknown as Prisma.InputJsonValue,
|
||||
]),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -306,9 +300,7 @@ describe('Email Processor', () => {
|
||||
from: 'test@example.com',
|
||||
status: EmailStatus.PENDING,
|
||||
sourceType: EmailSourceType.TRANSACTIONAL,
|
||||
attachments: [
|
||||
{filename: 'file.pdf', content: 'base64', contentType: 'application/pdf'},
|
||||
] as unknown as Prisma.InputJsonValue,
|
||||
attachments: toPrismaJson([{filename: 'file.pdf', content: 'base64', contentType: 'application/pdf'}]),
|
||||
},
|
||||
include: {
|
||||
project: true,
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
import {beforeEach, describe, expect, it} from 'vitest';
|
||||
import {factories, getPrismaClient} from '../../../../../test/helpers';
|
||||
import {ContactService} from '../../services/ContactService.js';
|
||||
import {coerceCustomValue} from '../import-processor.js';
|
||||
|
||||
/**
|
||||
* Tests for Contact Import Processor - Subscription Status Preservation
|
||||
* Verifies that CSV imports preserve subscription status correctly
|
||||
*/
|
||||
describe('Contact Import - Subscription Status Preservation', () => {
|
||||
let projectId: string;
|
||||
const prisma = getPrismaClient();
|
||||
|
||||
beforeEach(async () => {
|
||||
const {project} = await factories.createUserWithProject();
|
||||
projectId = project.id;
|
||||
});
|
||||
|
||||
describe('Existing contacts', () => {
|
||||
it('should NOT change subscription status when CSV has no subscribed column for subscribed contact', async () => {
|
||||
// Create a subscribed contact
|
||||
const contact = await factories.createContact({
|
||||
projectId,
|
||||
subscribed: true,
|
||||
email: 'existing-subscribed@example.com',
|
||||
});
|
||||
|
||||
// Verify initial state
|
||||
expect(contact.subscribed).toBe(true);
|
||||
|
||||
// Simulate import without subscribed column (undefined)
|
||||
await ContactService.upsert(projectId, contact.email, {firstName: 'John'}, undefined);
|
||||
|
||||
// Verify subscription status unchanged
|
||||
const updated = await prisma.contact.findUnique({
|
||||
where: {id: contact.id},
|
||||
});
|
||||
|
||||
expect(updated?.subscribed).toBe(true);
|
||||
});
|
||||
|
||||
it('should NOT re-subscribe unsubscribed contact when CSV has no subscribed column', async () => {
|
||||
// Create an unsubscribed contact
|
||||
const contact = await factories.createContact({
|
||||
projectId,
|
||||
subscribed: false,
|
||||
email: 'existing-unsubscribed@example.com',
|
||||
});
|
||||
|
||||
// Verify initial state
|
||||
expect(contact.subscribed).toBe(false);
|
||||
|
||||
// Simulate import without subscribed column (undefined)
|
||||
await ContactService.upsert(projectId, contact.email, {firstName: 'Jane'}, undefined);
|
||||
|
||||
// Verify subscription status unchanged (should NOT be re-subscribed)
|
||||
const updated = await prisma.contact.findUnique({
|
||||
where: {id: contact.id},
|
||||
});
|
||||
|
||||
expect(updated?.subscribed).toBe(false);
|
||||
});
|
||||
|
||||
it('should update subscription status when CSV explicitly has subscribed=true', async () => {
|
||||
// Create an unsubscribed contact
|
||||
const contact = await factories.createContact({
|
||||
projectId,
|
||||
subscribed: false,
|
||||
email: 'import-resubscribe@example.com',
|
||||
});
|
||||
|
||||
// Verify initial state
|
||||
expect(contact.subscribed).toBe(false);
|
||||
|
||||
// Simulate import with explicit subscribed=true
|
||||
await ContactService.upsert(projectId, contact.email, {firstName: 'John'}, true);
|
||||
|
||||
// Verify subscription status changed
|
||||
const updated = await prisma.contact.findUnique({
|
||||
where: {id: contact.id},
|
||||
});
|
||||
|
||||
expect(updated?.subscribed).toBe(true);
|
||||
});
|
||||
|
||||
it('should update subscription status when CSV explicitly has subscribed=false', async () => {
|
||||
// Create a subscribed contact
|
||||
const contact = await factories.createContact({
|
||||
projectId,
|
||||
subscribed: true,
|
||||
email: 'import-unsubscribe@example.com',
|
||||
});
|
||||
|
||||
// Verify initial state
|
||||
expect(contact.subscribed).toBe(true);
|
||||
|
||||
// Simulate import with explicit subscribed=false
|
||||
await ContactService.upsert(projectId, contact.email, {firstName: 'Jane'}, false);
|
||||
|
||||
// Verify subscription status changed
|
||||
const updated = await prisma.contact.findUnique({
|
||||
where: {id: contact.id},
|
||||
});
|
||||
|
||||
expect(updated?.subscribed).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('New contacts', () => {
|
||||
it('should create new contact as subscribed when CSV has no subscribed column', async () => {
|
||||
const newEmail = 'new-import-default@example.com';
|
||||
|
||||
// Simulate import without subscribed column (undefined)
|
||||
const contact = await ContactService.upsert(projectId, newEmail, {firstName: 'New'}, undefined);
|
||||
|
||||
// New contacts should default to subscribed=true
|
||||
expect(contact.subscribed).toBe(true);
|
||||
});
|
||||
|
||||
it('should create new contact as subscribed when CSV explicitly has subscribed=true', async () => {
|
||||
const newEmail = 'new-import-explicit-sub@example.com';
|
||||
|
||||
// Simulate import with explicit subscribed=true
|
||||
const contact = await ContactService.upsert(projectId, newEmail, {firstName: 'New'}, true);
|
||||
|
||||
expect(contact.subscribed).toBe(true);
|
||||
});
|
||||
|
||||
it('should create new contact as unsubscribed when CSV explicitly has subscribed=false', async () => {
|
||||
const newEmail = 'new-import-explicit-unsub@example.com';
|
||||
|
||||
// Simulate import with explicit subscribed=false
|
||||
const contact = await ContactService.upsert(projectId, newEmail, {firstName: 'New'}, false);
|
||||
|
||||
expect(contact.subscribed).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('CSV parsing logic', () => {
|
||||
it('should parse "true" string as boolean true', () => {
|
||||
const subscribedValue = 'true';
|
||||
const lowerValue = subscribedValue.toLowerCase().trim();
|
||||
const subscribed = lowerValue === 'true' || lowerValue === '1' || lowerValue === 'yes';
|
||||
|
||||
expect(subscribed).toBe(true);
|
||||
});
|
||||
|
||||
it('should parse "1" string as boolean true', () => {
|
||||
const subscribedValue = '1';
|
||||
const lowerValue = subscribedValue.toLowerCase().trim();
|
||||
const subscribed = lowerValue === 'true' || lowerValue === '1' || lowerValue === 'yes';
|
||||
|
||||
expect(subscribed).toBe(true);
|
||||
});
|
||||
|
||||
it('should parse "yes" string as boolean true', () => {
|
||||
const subscribedValue = 'yes';
|
||||
const lowerValue = subscribedValue.toLowerCase().trim();
|
||||
const subscribed = lowerValue === 'true' || lowerValue === '1' || lowerValue === 'yes';
|
||||
|
||||
expect(subscribed).toBe(true);
|
||||
});
|
||||
|
||||
it('should parse "false" string as boolean false', () => {
|
||||
const subscribedValue = 'false';
|
||||
const lowerValue = subscribedValue.toLowerCase().trim();
|
||||
const subscribed = lowerValue === 'true' || lowerValue === '1' || lowerValue === 'yes';
|
||||
|
||||
expect(subscribed).toBe(false);
|
||||
});
|
||||
|
||||
it('should parse "0" string as boolean false', () => {
|
||||
const subscribedValue = '0';
|
||||
const lowerValue = subscribedValue.toLowerCase().trim();
|
||||
const subscribed = lowerValue === 'true' || lowerValue === '1' || lowerValue === 'yes';
|
||||
|
||||
expect(subscribed).toBe(false);
|
||||
});
|
||||
|
||||
it('should parse "no" string as boolean false', () => {
|
||||
const subscribedValue = 'no';
|
||||
const lowerValue = subscribedValue.toLowerCase().trim();
|
||||
const subscribed = lowerValue === 'true' || lowerValue === '1' || lowerValue === 'yes';
|
||||
|
||||
expect(subscribed).toBe(false);
|
||||
});
|
||||
|
||||
it('should handle empty string as undefined', () => {
|
||||
const subscribedValue = '';
|
||||
let subscribed: boolean | undefined;
|
||||
|
||||
if (subscribedValue !== undefined && subscribedValue !== '') {
|
||||
const lowerValue = subscribedValue.toLowerCase().trim();
|
||||
subscribed = lowerValue === 'true' || lowerValue === '1' || lowerValue === 'yes';
|
||||
}
|
||||
|
||||
expect(subscribed).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should handle undefined as undefined', () => {
|
||||
const subscribedValue = undefined;
|
||||
let subscribed: boolean | undefined;
|
||||
|
||||
if (subscribedValue !== undefined && subscribedValue !== '') {
|
||||
const lowerValue = subscribedValue.toLowerCase().trim();
|
||||
subscribed = lowerValue === 'true' || lowerValue === '1' || lowerValue === 'yes';
|
||||
}
|
||||
|
||||
expect(subscribed).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Data preservation', () => {
|
||||
it('should preserve existing contact data while updating subscription', async () => {
|
||||
// Create contact with existing data
|
||||
const contact = await factories.createContact({
|
||||
projectId,
|
||||
subscribed: false,
|
||||
email: 'preserve-data@example.com',
|
||||
data: {
|
||||
firstName: 'Original',
|
||||
lastName: 'Name',
|
||||
plan: 'pro',
|
||||
},
|
||||
});
|
||||
|
||||
// Update only subscription via import
|
||||
await ContactService.upsert(projectId, contact.email, {}, true);
|
||||
|
||||
const updated = await prisma.contact.findUnique({
|
||||
where: {id: contact.id},
|
||||
});
|
||||
|
||||
// Subscription should be updated
|
||||
expect(updated?.subscribed).toBe(true);
|
||||
|
||||
// Original data should be preserved
|
||||
const data = updated?.data as Record<string, unknown>;
|
||||
expect(data?.firstName).toBe('Original');
|
||||
expect(data?.lastName).toBe('Name');
|
||||
expect(data?.plan).toBe('pro');
|
||||
});
|
||||
|
||||
it('should merge new data while preserving subscription', async () => {
|
||||
// Create contact with existing data
|
||||
const contact = await factories.createContact({
|
||||
projectId,
|
||||
subscribed: false,
|
||||
email: 'merge-data@example.com',
|
||||
data: {
|
||||
firstName: 'John',
|
||||
plan: 'pro',
|
||||
},
|
||||
});
|
||||
|
||||
// Import new data without changing subscription
|
||||
await ContactService.upsert(
|
||||
projectId,
|
||||
contact.email,
|
||||
{
|
||||
lastName: 'Doe',
|
||||
company: 'Acme Inc',
|
||||
},
|
||||
undefined,
|
||||
);
|
||||
|
||||
const updated = await prisma.contact.findUnique({
|
||||
where: {id: contact.id},
|
||||
});
|
||||
|
||||
// Subscription should be unchanged
|
||||
expect(updated?.subscribed).toBe(false);
|
||||
|
||||
// Data should be merged
|
||||
const data = updated?.data as Record<string, unknown>;
|
||||
expect(data?.firstName).toBe('John'); // Preserved
|
||||
expect(data?.plan).toBe('pro'); // Preserved
|
||||
expect(data?.lastName).toBe('Doe'); // New
|
||||
expect(data?.company).toBe('Acme Inc'); // New
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('coerceCustomValue', () => {
|
||||
describe('boolean coercion', () => {
|
||||
it.each(['true', 'TRUE', 'True', ' true ', 'yes', 'YES', 'Yes'])('coerces %j to true', value => {
|
||||
expect(coerceCustomValue(value)).toBe(true);
|
||||
});
|
||||
|
||||
it.each(['false', 'FALSE', 'False', ' false ', 'no', 'NO', 'No'])('coerces %j to false', value => {
|
||||
expect(coerceCustomValue(value)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('number coercion', () => {
|
||||
it.each([
|
||||
['42', 42],
|
||||
['-7', -7],
|
||||
['3.14', 3.14],
|
||||
[' 42 ', 42],
|
||||
['0.5', 0.5],
|
||||
['-0.25', -0.25],
|
||||
['0', 0],
|
||||
['1', 1],
|
||||
])('coerces %j to %j', (value, expected) => {
|
||||
expect(coerceCustomValue(value)).toBe(expected);
|
||||
});
|
||||
|
||||
it.each(['01234', '+42', '.5', '42.', '1e10', 'NaN', 'Infinity', '1.2.3', '4-2'])(
|
||||
'leaves %j as a string (preserves IDs / rejects loose formats)',
|
||||
value => {
|
||||
expect(coerceCustomValue(value)).toBe(value);
|
||||
},
|
||||
);
|
||||
|
||||
it('"1.0" is a number (does not match the boolean truthy set)', () => {
|
||||
expect(coerceCustomValue('1.0')).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('passthrough', () => {
|
||||
it.each(['Alice', 'true!', 'yesno', 'maybe'])('leaves %j as a string', value => {
|
||||
expect(coerceCustomValue(value)).toBe(value);
|
||||
});
|
||||
|
||||
it('leaves empty string as empty string', () => {
|
||||
expect(coerceCustomValue('')).toBe('');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import {describe, it, expect, beforeEach, afterEach} from 'vitest';
|
||||
import {afterEach, beforeEach, describe, expect, it} from 'vitest';
|
||||
import {CampaignStatus} from '@plunk/db';
|
||||
import {factories, getPrismaClient, createTimeControl} from '../../../../../test/helpers';
|
||||
import {createTimeControl, factories, getPrismaClient} from '../../../../../test/helpers';
|
||||
|
||||
describe('Scheduled Campaign Processor', () => {
|
||||
let projectId: string;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type {ApiRequestCleanupJobData} from '@plunk/types';
|
||||
import type {Job} from 'bullmq';
|
||||
import {Worker} from 'bullmq';
|
||||
import type {RedisOptions} from 'ioredis';
|
||||
@@ -5,7 +6,6 @@ import signale from 'signale';
|
||||
|
||||
import {REDIS_URL} from '../app/constants.js';
|
||||
import {prisma} from '../database/prisma.js';
|
||||
import type {ApiRequestCleanupJobData} from '../services/QueueService.js';
|
||||
|
||||
/**
|
||||
* API Request Cleanup Worker
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
/**
|
||||
* Background Job: Bulk Contact Action Processor
|
||||
* Processes bulk subscribe, unsubscribe, and delete operations
|
||||
*/
|
||||
|
||||
import {Prisma} from '@plunk/db';
|
||||
import type {BulkContactActionJobData, BulkContactActionSelector} from '@plunk/types';
|
||||
import {type Job, Worker} from 'bullmq';
|
||||
import signale from 'signale';
|
||||
|
||||
import {prisma} from '../database/prisma.js';
|
||||
import {ContactService} from '../services/ContactService.js';
|
||||
import {bulkContactQueue} from '../services/QueueService.js';
|
||||
|
||||
const BATCH_SIZE = 100;
|
||||
|
||||
interface BulkActionResult {
|
||||
operation: 'subscribe' | 'unsubscribe' | 'delete';
|
||||
totalRequested: number;
|
||||
/** Contacts whose state was actually changed by this run. */
|
||||
successCount: number;
|
||||
/** Subscribe/unsubscribe only: contacts already in the target state. */
|
||||
unchangedCount: number;
|
||||
/** Contacts that errored or weren't found (e.g. wrong project). */
|
||||
failureCount: number;
|
||||
errors: {contactId: string; email: string; error: string}[];
|
||||
}
|
||||
|
||||
function buildQueryWhere(projectId: string, selector: Extract<BulkContactActionSelector, {mode: 'query'}>): Prisma.ContactWhereInput {
|
||||
const search = selector.filter?.search;
|
||||
const excludeIds = selector.excludeIds ?? [];
|
||||
return {
|
||||
projectId,
|
||||
...(search ? {email: {contains: search, mode: 'insensitive' as const}} : {}),
|
||||
...(excludeIds.length > 0 ? {id: {notIn: excludeIds}} : {}),
|
||||
};
|
||||
}
|
||||
|
||||
async function applyBatch(
|
||||
projectId: string,
|
||||
operation: BulkActionResult['operation'],
|
||||
ids: string[],
|
||||
): Promise<{changed: number; unchanged: number}> {
|
||||
switch (operation) {
|
||||
case 'subscribe': {
|
||||
const r = await ContactService.bulkSubscribe(projectId, ids);
|
||||
return {changed: r.updated, unchanged: r.unchanged};
|
||||
}
|
||||
case 'unsubscribe': {
|
||||
const r = await ContactService.bulkUnsubscribe(projectId, ids);
|
||||
return {changed: r.updated, unchanged: r.unchanged};
|
||||
}
|
||||
case 'delete': {
|
||||
const r = await ContactService.bulkDelete(projectId, ids);
|
||||
return {changed: r.deleted, unchanged: 0};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function createBulkContactWorker() {
|
||||
const worker = new Worker<BulkContactActionJobData>(
|
||||
bulkContactQueue.name,
|
||||
async (job: Job<BulkContactActionJobData>) => {
|
||||
const {projectId, operation, selector} = job.data;
|
||||
|
||||
const result: BulkActionResult = {
|
||||
operation,
|
||||
totalRequested: 0,
|
||||
successCount: 0,
|
||||
unchangedCount: 0,
|
||||
failureCount: 0,
|
||||
errors: [],
|
||||
};
|
||||
|
||||
if (selector.mode === 'ids') {
|
||||
const {contactIds} = selector;
|
||||
result.totalRequested = contactIds.length;
|
||||
|
||||
signale.info(
|
||||
`[BULK-CONTACT-PROCESSOR] Processing ${operation} for ${contactIds.length} contacts (ids mode) in project ${projectId}`,
|
||||
);
|
||||
|
||||
for (let i = 0; i < contactIds.length; i += BATCH_SIZE) {
|
||||
const batchIds = contactIds.slice(i, i + BATCH_SIZE);
|
||||
try {
|
||||
const {changed, unchanged} = await applyBatch(projectId, operation, batchIds);
|
||||
result.successCount += changed;
|
||||
result.unchangedCount += unchanged;
|
||||
const failed = batchIds.length - changed - unchanged;
|
||||
if (failed > 0) result.failureCount += failed;
|
||||
} catch (error) {
|
||||
signale.error('[BULK-CONTACT-PROCESSOR] Batch failed:', error);
|
||||
result.failureCount += batchIds.length;
|
||||
result.errors.push({
|
||||
contactId: 'batch',
|
||||
email: '',
|
||||
error: error instanceof Error ? error.message : 'Batch processing failed',
|
||||
});
|
||||
}
|
||||
await job.updateProgress(Math.round(((i + batchIds.length) / contactIds.length) * 100));
|
||||
}
|
||||
} else {
|
||||
const where = buildQueryWhere(projectId, selector);
|
||||
const total = await prisma.contact.count({where});
|
||||
result.totalRequested = total;
|
||||
|
||||
signale.info(
|
||||
`[BULK-CONTACT-PROCESSOR] Processing ${operation} for ${total} contacts (query mode) in project ${projectId}`,
|
||||
);
|
||||
|
||||
if (total === 0) {
|
||||
await job.updateProgress(100);
|
||||
return result;
|
||||
}
|
||||
|
||||
// Cursor-based iteration over matching contacts. We re-evaluate the where clause
|
||||
// each batch (with id < cursor) instead of Prisma's `cursor:` because for `delete`
|
||||
// the rows we just processed disappear — a stable cursor would either skip survivors
|
||||
// or revisit deletions. Sorting by id desc + `id < lastId` is idempotent under either.
|
||||
let lastId: string | undefined;
|
||||
let processedRows = 0;
|
||||
|
||||
// Cap the loop so a runaway query (e.g. growing table) can't spin forever.
|
||||
const maxIterations = Math.ceil(total / BATCH_SIZE) + 50;
|
||||
for (let iter = 0; iter < maxIterations; iter += 1) {
|
||||
const batch = await prisma.contact.findMany({
|
||||
where: {
|
||||
...where,
|
||||
...(lastId ? {id: {...(where.id as object | undefined), lt: lastId}} : {}),
|
||||
},
|
||||
select: {id: true},
|
||||
orderBy: {id: 'desc'},
|
||||
take: BATCH_SIZE,
|
||||
});
|
||||
|
||||
if (batch.length === 0) break;
|
||||
|
||||
const batchIds = batch.map(c => c.id);
|
||||
lastId = batchIds[batchIds.length - 1];
|
||||
|
||||
try {
|
||||
const {changed, unchanged} = await applyBatch(projectId, operation, batchIds);
|
||||
result.successCount += changed;
|
||||
result.unchangedCount += unchanged;
|
||||
const failed = batchIds.length - changed - unchanged;
|
||||
if (failed > 0) result.failureCount += failed;
|
||||
} catch (error) {
|
||||
signale.error('[BULK-CONTACT-PROCESSOR] Batch failed:', error);
|
||||
result.failureCount += batchIds.length;
|
||||
result.errors.push({
|
||||
contactId: 'batch',
|
||||
email: '',
|
||||
error: error instanceof Error ? error.message : 'Batch processing failed',
|
||||
});
|
||||
}
|
||||
|
||||
processedRows += batchIds.length;
|
||||
await job.updateProgress(Math.min(100, Math.round((processedRows / total) * 100)));
|
||||
|
||||
if (batch.length < BATCH_SIZE) break;
|
||||
}
|
||||
}
|
||||
|
||||
signale.info(
|
||||
`[BULK-CONTACT-PROCESSOR] ${operation} completed: ${result.successCount} succeeded, ${result.failureCount} failed`,
|
||||
);
|
||||
return result;
|
||||
},
|
||||
{
|
||||
connection: bulkContactQueue.opts.connection,
|
||||
concurrency: 3,
|
||||
},
|
||||
);
|
||||
|
||||
worker.on('completed', job => {
|
||||
signale.info(`[BULK-CONTACT-PROCESSOR] Job ${job.id} completed`);
|
||||
});
|
||||
|
||||
worker.on('failed', (job, err) => {
|
||||
signale.error(`[BULK-CONTACT-PROCESSOR] Job ${job?.id} failed:`, err.message);
|
||||
});
|
||||
|
||||
worker.on('error', err => {
|
||||
signale.error('[BULK-CONTACT-PROCESSOR] Worker error:', err);
|
||||
});
|
||||
|
||||
return worker;
|
||||
}
|
||||
@@ -3,11 +3,12 @@
|
||||
* Processes campaign batches (queues emails for each contact in the batch)
|
||||
*/
|
||||
|
||||
import type {CampaignBatchJobData} from '@plunk/types';
|
||||
import {type Job, Worker} from 'bullmq';
|
||||
import signale from 'signale';
|
||||
|
||||
import {CampaignService} from '../services/CampaignService.js';
|
||||
import {type CampaignBatchJobData, campaignQueue} from '../services/QueueService.js';
|
||||
import {campaignQueue} from '../services/QueueService.js';
|
||||
|
||||
export function createCampaignWorker() {
|
||||
const worker = new Worker<CampaignBatchJobData>(
|
||||
|
||||
@@ -3,10 +3,11 @@
|
||||
* Processes domain verification jobs from the BullMQ queue
|
||||
*/
|
||||
|
||||
import type {DomainVerificationJobData} from '@plunk/types';
|
||||
import {type Job, Worker} from 'bullmq';
|
||||
import signale from 'signale';
|
||||
|
||||
import {type DomainVerificationJobData, domainVerificationQueue} from '../services/QueueService.js';
|
||||
import {domainVerificationQueue} from '../services/QueueService.js';
|
||||
|
||||
import {checkDomainVerifications} from './domain-verification.js';
|
||||
|
||||
|
||||
@@ -6,10 +6,14 @@
|
||||
* Scheduled to run every 5 minutes via repeatable jobs
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import signale from 'signale';
|
||||
import {DomainUnverifiedEmail, DomainVerifiedEmail, sendPlatformEmail} from '@plunk/email';
|
||||
|
||||
import {DASHBOARD_URI, LANDING_URI} from '../app/constants.js';
|
||||
import {prisma} from '../database/prisma.js';
|
||||
import {redis} from '../database/redis.js';
|
||||
import {MembershipService} from '../services/MembershipService.js';
|
||||
import {disableFeedbackForwarding, getIdentities, verifyDomain} from '../services/SESService.js';
|
||||
import {Keys} from '../services/keys.js';
|
||||
|
||||
@@ -26,7 +30,15 @@ export async function checkDomainVerifications() {
|
||||
// Process domains in batches of 99 (AWS SES limit is 100)
|
||||
for (let i = 0; i < count; i += 99) {
|
||||
const domains = await prisma.domain.findMany({
|
||||
select: {id: true, domain: true, projectId: true, verified: true},
|
||||
select: {
|
||||
id: true,
|
||||
domain: true,
|
||||
projectId: true,
|
||||
verified: true,
|
||||
project: {
|
||||
select: {name: true},
|
||||
},
|
||||
},
|
||||
skip: i,
|
||||
take: 99,
|
||||
});
|
||||
@@ -64,7 +76,11 @@ export async function checkDomainVerifications() {
|
||||
signale.success(`[DOMAIN-VERIFICATION] Restarted verification for ${sesIdentity.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')) {
|
||||
if (
|
||||
error?.Code === 'Throttling' ||
|
||||
error?.name === 'Throttling' ||
|
||||
error?.message?.includes('Throttling')
|
||||
) {
|
||||
signale.warn(
|
||||
`[DOMAIN-VERIFICATION] Throttling detected, waiting ${delay / 1000} seconds (attempt ${attempt + 1})`,
|
||||
);
|
||||
@@ -72,7 +88,9 @@ export async function checkDomainVerifications() {
|
||||
delay *= 2; // Exponential backoff
|
||||
attempt++;
|
||||
} else {
|
||||
signale.error(`[DOMAIN-VERIFICATION] Error restarting verification: ${error?.message || 'Unknown error'}`);
|
||||
signale.error(
|
||||
`[DOMAIN-VERIFICATION] Error restarting verification: ${error?.message || 'Unknown error'}`,
|
||||
);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
@@ -102,6 +120,34 @@ export async function checkDomainVerifications() {
|
||||
signale.error(`[DOMAIN-VERIFICATION] Error disabling feedback forwarding: ${error}`);
|
||||
}
|
||||
|
||||
// Send email notification about domain verified
|
||||
try {
|
||||
// Use SETNX to atomically check and set the flag (prevents race conditions)
|
||||
const cacheKey = Keys.Domain.verifiedEmail(dbDomain.id);
|
||||
const ttl = 604800; // 7 days
|
||||
|
||||
// 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 emails = members.map(m => m.email);
|
||||
if (emails.length > 0) {
|
||||
const template = React.createElement(DomainVerifiedEmail, {
|
||||
projectName: dbDomain.project.name,
|
||||
projectId: dbDomain.projectId,
|
||||
domain: sesIdentity.domain,
|
||||
dashboardUrl: DASHBOARD_URI,
|
||||
landingUrl: LANDING_URI,
|
||||
});
|
||||
await Promise.all(
|
||||
emails.map(email => sendPlatformEmail(email, 'Domain Verified Successfully', template)),
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
signale.error(`[DOMAIN-VERIFICATION] Error sending verified email: ${error}`);
|
||||
}
|
||||
|
||||
// Invalidate cache
|
||||
await redis.del(Keys.Domain.id(dbDomain.id));
|
||||
await redis.del(Keys.Domain.project(dbDomain.projectId));
|
||||
@@ -111,6 +157,38 @@ export async function checkDomainVerifications() {
|
||||
if (dbDomain.verified && !isVerified) {
|
||||
signale.warn(`[DOMAIN-VERIFICATION] Domain ${sesIdentity.domain} is no longer verified`);
|
||||
|
||||
// Send email notification about domain verification failed
|
||||
try {
|
||||
// Use SETNX to atomically check and set the flag (prevents race conditions)
|
||||
const now = new Date();
|
||||
const year = now.getFullYear();
|
||||
const month = String(now.getMonth() + 1).padStart(2, '0');
|
||||
const cacheKey = Keys.Domain.unverifiedEmail(dbDomain.id, year, month);
|
||||
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) {
|
||||
const members = await MembershipService.getMembers(dbDomain.projectId);
|
||||
const emails = members.map(m => m.email);
|
||||
if (emails.length > 0) {
|
||||
const template = React.createElement(DomainUnverifiedEmail, {
|
||||
projectName: dbDomain.project.name,
|
||||
projectId: dbDomain.projectId,
|
||||
domain: sesIdentity.domain,
|
||||
dashboardUrl: DASHBOARD_URI,
|
||||
landingUrl: LANDING_URI,
|
||||
});
|
||||
await Promise.all(
|
||||
emails.map(email => sendPlatformEmail(email, 'Domain Verification Failed', template)),
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
signale.error(`[DOMAIN-VERIFICATION] Error sending unverified email: ${error}`);
|
||||
}
|
||||
|
||||
await redis.del(Keys.Domain.id(dbDomain.id));
|
||||
await redis.del(Keys.Domain.project(dbDomain.projectId));
|
||||
}
|
||||
|
||||
@@ -3,17 +3,25 @@
|
||||
* Processes individual emails from the queue (for all sources: transactional, campaign, workflow)
|
||||
*/
|
||||
|
||||
import {CampaignStatus, EmailSourceType, EmailStatus} from '@plunk/db';
|
||||
import {EmailSourceType, EmailStatus} from '@plunk/db';
|
||||
import type {SendEmailJobData} from '@plunk/types';
|
||||
import {type Job, Worker} from 'bullmq';
|
||||
import signale from 'signale';
|
||||
|
||||
import {
|
||||
DASHBOARD_URI,
|
||||
EMAIL_RATE_LIMIT_PER_SECOND,
|
||||
EMAIL_WORKER_CONCURRENCY,
|
||||
EMAIL_WORKER_MAX_CONCURRENCY,
|
||||
} from '../app/constants.js';
|
||||
import {prisma} from '../database/prisma.js';
|
||||
import {CampaignService} from '../services/CampaignService.js';
|
||||
import {EmailService} from '../services/EmailService.js';
|
||||
import {EventService} from '../services/EventService.js';
|
||||
import {MeterService} from '../services/MeterService.js';
|
||||
import {emailQueue, type SendEmailJobData} from '../services/QueueService.js';
|
||||
import {emailQueue} from '../services/QueueService.js';
|
||||
import {SecurityService} from '../services/SecurityService.js';
|
||||
import {getSendingQuota, sendRawEmail} from '../services/SESService.js';
|
||||
import {DASHBOARD_URI, EMAIL_RATE_LIMIT_PER_SECOND} from '../app/constants.js';
|
||||
|
||||
/**
|
||||
* Determine the email sending rate limit (emails per second)
|
||||
@@ -44,9 +52,31 @@ async function getEmailRateLimit(): Promise<number> {
|
||||
return DEFAULT_RATE_LIMIT;
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive worker concurrency from the rate limit so a higher SES quota actually
|
||||
* translates into higher throughput. The mean job duration is ~0.5s (Prisma
|
||||
* reads + HTML compile + SES call + writes), so `rate * 0.5` gives ~2× headroom
|
||||
* over the per-second cap. Clamped to keep sandbox accounts useful and to
|
||||
* protect the Prisma pool on very large quotas.
|
||||
*/
|
||||
function deriveWorkerConcurrency(rateLimit: number): number {
|
||||
if (EMAIL_WORKER_CONCURRENCY !== undefined) {
|
||||
return EMAIL_WORKER_CONCURRENCY;
|
||||
}
|
||||
|
||||
const TARGET_JOB_SECONDS = 0.5;
|
||||
const MIN_CONCURRENCY = 5;
|
||||
const derived = Math.ceil(rateLimit * TARGET_JOB_SECONDS);
|
||||
return Math.max(MIN_CONCURRENCY, Math.min(derived, EMAIL_WORKER_MAX_CONCURRENCY));
|
||||
}
|
||||
|
||||
export async function createEmailWorker() {
|
||||
// Fetch the rate limit (from env, AWS, or default)
|
||||
const rateLimit = await getEmailRateLimit();
|
||||
const concurrency = deriveWorkerConcurrency(rateLimit);
|
||||
signale.info(
|
||||
`[EMAIL-PROCESSOR] Worker concurrency: ${concurrency} (rate limit: ${rateLimit}/s)`,
|
||||
);
|
||||
const worker = new Worker<SendEmailJobData>(
|
||||
emailQueue.name,
|
||||
async (job: Job<SendEmailJobData>) => {
|
||||
@@ -57,6 +87,8 @@ export async function createEmailWorker() {
|
||||
include: {
|
||||
contact: true,
|
||||
project: true,
|
||||
template: {select: {type: true}},
|
||||
campaign: {select: {type: true}},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -78,6 +110,12 @@ export async function createEmailWorker() {
|
||||
error: 'Project is disabled',
|
||||
},
|
||||
});
|
||||
|
||||
// Cancelled emails are terminal for the campaign — finalize so it doesn't
|
||||
// stay stuck in SENDING forever waiting on emails that will never be sent.
|
||||
if (email.campaignId) {
|
||||
await CampaignService.finalizeIfDone(email.campaignId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -104,11 +142,15 @@ export async function createEmailWorker() {
|
||||
});
|
||||
|
||||
// Compile HTML with unsubscribe footer and badge
|
||||
// TRANSACTIONAL and HEADLESS emails don't get the Plunk unsubscribe footer
|
||||
const compiledHtml = EmailService.compile({
|
||||
content: formattedEmail.body,
|
||||
contact: email.contact,
|
||||
project: email.project,
|
||||
includeUnsubscribe: email.sourceType !== EmailSourceType.TRANSACTIONAL, // Don't add unsubscribe to transactional emails
|
||||
includeUnsubscribe:
|
||||
email.sourceType !== EmailSourceType.TRANSACTIONAL &&
|
||||
email.template?.type !== 'HEADLESS' &&
|
||||
email.campaign?.type !== 'HEADLESS',
|
||||
});
|
||||
|
||||
// Use fromName from database if available, otherwise fall back to project name
|
||||
@@ -116,14 +158,59 @@ export async function createEmailWorker() {
|
||||
const fromName = email.fromName || email.project.name;
|
||||
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
|
||||
const recipient: {name?: string; email: string} | string = email.toName
|
||||
? {name: email.toName, email: email.contact.email}
|
||||
: email.contact.email;
|
||||
? {name: email.toName, email: recipientEmail}
|
||||
: recipientEmail;
|
||||
|
||||
// Determine tracking based on project settings and email type
|
||||
const shouldTrack = EmailService.shouldTrackEmail(email.project.tracking, email.sourceType);
|
||||
|
||||
// Check for phishing/dangerous content before sending
|
||||
const phishingCheck = await SecurityService.checkPhishingContent(
|
||||
email.projectId,
|
||||
email.project.name,
|
||||
email.from,
|
||||
formattedEmail.subject,
|
||||
compiledHtml,
|
||||
);
|
||||
|
||||
if (phishingCheck.shouldDisable) {
|
||||
// Disable project immediately
|
||||
await SecurityService.disableProjectForPhishing(
|
||||
email.projectId,
|
||||
formattedEmail.subject,
|
||||
phishingCheck.confidence,
|
||||
'Phishing content detected',
|
||||
);
|
||||
|
||||
// Mark email as failed
|
||||
await prisma.email.update({
|
||||
where: {id: emailId},
|
||||
data: {
|
||||
status: EmailStatus.FAILED,
|
||||
error: 'This email could not be sent. The project has been disabled. Please contact support.',
|
||||
},
|
||||
});
|
||||
|
||||
throw new Error(`Project ${email.projectId} has been disabled due to a policy violation`);
|
||||
}
|
||||
|
||||
// Send via AWS SES
|
||||
const result = await sendRawEmail({
|
||||
from: {
|
||||
@@ -136,6 +223,7 @@ export async function createEmailWorker() {
|
||||
html: compiledHtml,
|
||||
},
|
||||
reply: email.replyTo || undefined,
|
||||
headers: publicHeaders,
|
||||
tracking: shouldTrack,
|
||||
attachments: email.attachments as {filename: string; content: string; contentType: string}[] | null,
|
||||
});
|
||||
@@ -165,61 +253,15 @@ export async function createEmailWorker() {
|
||||
from: email.from,
|
||||
fromName: email.fromName,
|
||||
messageId: result.messageId,
|
||||
emailId: email.id,
|
||||
templateId: email.templateId,
|
||||
campaignId: email.campaignId,
|
||||
sourceType: email.sourceType,
|
||||
sentAt: new Date().toISOString(),
|
||||
});
|
||||
|
||||
// If this email belongs to a campaign, check if all campaign emails have been sent
|
||||
if (email.campaignId) {
|
||||
const campaign = await prisma.campaign.findUnique({
|
||||
where: {id: email.campaignId},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
status: true,
|
||||
totalRecipients: true,
|
||||
projectId: true,
|
||||
project: {
|
||||
select: {name: true},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Only check if campaign is still in SENDING status
|
||||
if (campaign && campaign.status === CampaignStatus.SENDING) {
|
||||
// Count how many emails have been sent for this campaign
|
||||
const sentCount = await prisma.email.count({
|
||||
where: {
|
||||
campaignId: email.campaignId,
|
||||
sentAt: {not: null},
|
||||
},
|
||||
});
|
||||
|
||||
// If all emails have been sent, mark campaign as SENT
|
||||
if (sentCount >= campaign.totalRecipients) {
|
||||
await prisma.campaign.update({
|
||||
where: {id: email.campaignId},
|
||||
data: {
|
||||
status: CampaignStatus.SENT,
|
||||
},
|
||||
});
|
||||
|
||||
signale.success(
|
||||
`[EMAIL-PROCESSOR] Campaign ${campaign.name} completed: ${sentCount}/${campaign.totalRecipients} emails sent`,
|
||||
);
|
||||
|
||||
// Send notification about campaign send completed
|
||||
const {NtfyService} = await import('../services/NtfyService.js');
|
||||
await NtfyService.notifyCampaignSendCompleted(
|
||||
campaign.name,
|
||||
campaign.project.name,
|
||||
campaign.projectId,
|
||||
campaign.totalRecipients,
|
||||
);
|
||||
}
|
||||
}
|
||||
await CampaignService.finalizeIfDone(email.campaignId);
|
||||
}
|
||||
} catch (error) {
|
||||
signale.error(`[EMAIL-PROCESSOR] Failed to send email ${emailId}:`, error);
|
||||
@@ -238,7 +280,7 @@ export async function createEmailWorker() {
|
||||
},
|
||||
{
|
||||
connection: emailQueue.opts.connection,
|
||||
concurrency: 10, // Process up to 10 emails concurrently
|
||||
concurrency,
|
||||
limiter: {
|
||||
max: rateLimit, // Max emails per second (from env, AWS SES quota, or default)
|
||||
duration: 1000,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
* Processes CSV contact imports with validation and batch processing
|
||||
*/
|
||||
|
||||
import type {ContactImportJobData} from '@plunk/types';
|
||||
import {type Job, Worker} from 'bullmq';
|
||||
import {parse} from 'csv-parse/sync';
|
||||
import signale from 'signale';
|
||||
@@ -10,7 +11,7 @@ import signale from 'signale';
|
||||
import {prisma} from '../database/prisma.js';
|
||||
import {ContactService} from '../services/ContactService.js';
|
||||
import {NtfyService} from '../services/NtfyService.js';
|
||||
import {type ContactImportJobData, importQueue} from '../services/QueueService.js';
|
||||
import {importQueue} from '../services/QueueService.js';
|
||||
|
||||
const BATCH_SIZE = 100; // Process contacts in batches of 100
|
||||
|
||||
@@ -52,9 +53,9 @@ export function createImportWorker() {
|
||||
// Decode base64 CSV data
|
||||
const csvContent = Buffer.from(csvData, 'base64').toString('utf-8');
|
||||
|
||||
// Parse CSV
|
||||
// Parse CSV with column header normalization
|
||||
const records = parse(csvContent, {
|
||||
columns: true, // Use first row as header
|
||||
columns: (header: string[]) => header.map(h => h.toLowerCase()), // Normalize headers to lowercase
|
||||
skip_empty_lines: true,
|
||||
trim: true,
|
||||
relax_column_count: true, // Allow rows with different column counts
|
||||
@@ -72,10 +73,10 @@ export function createImportWorker() {
|
||||
// Notify that import has started
|
||||
await NtfyService.notifyContactImportStarted(projectName, projectId, filename, result.totalRows);
|
||||
|
||||
// Validate that 'email' column exists
|
||||
// Validate that 'email' column exists (case-insensitive)
|
||||
const firstRecord = records[0];
|
||||
if (firstRecord && typeof firstRecord === 'object' && !('email' in firstRecord)) {
|
||||
throw new Error('CSV must have an "email" column');
|
||||
throw new Error('CSV must have an "email" column (case-insensitive)');
|
||||
}
|
||||
|
||||
// Process contacts in batches
|
||||
@@ -110,7 +111,7 @@ export function createImportWorker() {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Extract subscribed field if present
|
||||
// Extract subscribed field if present (case-insensitive)
|
||||
const subscribedValue = record.subscribed;
|
||||
let subscribed: boolean | undefined;
|
||||
|
||||
@@ -122,14 +123,20 @@ export function createImportWorker() {
|
||||
|
||||
// Extract custom data (all fields except email and subscribed)
|
||||
const {email: _, subscribed: __, ...customData} = record;
|
||||
const data = Object.keys(customData).length > 0 ? customData : undefined;
|
||||
const customEntries = Object.entries(customData);
|
||||
const data =
|
||||
customEntries.length > 0
|
||||
? Object.fromEntries(customEntries.map(([k, v]) => [k, coerceCustomValue(v)]))
|
||||
: undefined;
|
||||
|
||||
// Check if contact exists before upserting
|
||||
const existingContact = await ContactService.findByEmail(projectId, email);
|
||||
const isUpdate = !!existingContact;
|
||||
|
||||
// Upsert contact with subscribed value from CSV if provided, otherwise default to true
|
||||
await ContactService.upsert(projectId, email, data, subscribed ?? true);
|
||||
// Upsert contact with subscribed value from CSV if provided
|
||||
// For new contacts, ContactService.upsert defaults to true
|
||||
// For existing contacts, only update if explicitly provided in CSV
|
||||
await ContactService.upsert(projectId, email, data, subscribed);
|
||||
|
||||
result.successCount++;
|
||||
if (isUpdate) {
|
||||
@@ -213,3 +220,30 @@ function isValidEmail(email: string): boolean {
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
return emailRegex.test(email);
|
||||
}
|
||||
|
||||
// Values considered as boolean during import.
|
||||
// Numbers (0, 1) are intentionally absent.
|
||||
const BOOLEAN_TRUE = new Set(['true', 'yes']);
|
||||
const BOOLEAN_FALSE = new Set(['false', 'no']);
|
||||
|
||||
// Strict integer-or-decimal number detection pattern.
|
||||
// Valid: 0, 42, -42, 3.14
|
||||
// Rejected: 007, +42, 1.2.3, 1e5
|
||||
const NUMERIC_RE = /^-?(0|[1-9]\d*)(\.\d+)?$/;
|
||||
|
||||
/**
|
||||
* Coerces a raw string into its most natural primitive type: `boolean`,
|
||||
* `number`, or `string`. Values that match neither are
|
||||
* returned unchanged.
|
||||
*
|
||||
* @param value The raw string to coerce.
|
||||
* @returns The coerced value as `boolean`, `number`, or `string`.
|
||||
*/
|
||||
export function coerceCustomValue(value: string): string | boolean | number {
|
||||
const trimmed = value.trim();
|
||||
const lower = trimmed.toLowerCase();
|
||||
if (BOOLEAN_TRUE.has(lower)) return true;
|
||||
if (BOOLEAN_FALSE.has(lower)) return false;
|
||||
if (NUMERIC_RE.test(trimmed)) return Number(trimmed);
|
||||
return value;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* Background Job: Meter Processor
|
||||
* Reliably records Stripe billing meter events with automatic retries
|
||||
*/
|
||||
|
||||
import type {MeterEventJobData} from '@plunk/types';
|
||||
import {type Job, Worker} from 'bullmq';
|
||||
import signale from 'signale';
|
||||
|
||||
import {STRIPE_ENABLED, STRIPE_METER_EVENT_NAME} from '../app/constants.js';
|
||||
import {stripe} from '../app/stripe.js';
|
||||
import {meterQueue} from '../services/QueueService.js';
|
||||
|
||||
async function processMeterEvent(job: Job<MeterEventJobData>): Promise<void> {
|
||||
const {customerId, value, idempotencyKey} = job.data;
|
||||
|
||||
if (!STRIPE_ENABLED || !stripe) {
|
||||
return;
|
||||
}
|
||||
|
||||
await stripe.billing.meterEvents.create({
|
||||
event_name: STRIPE_METER_EVENT_NAME,
|
||||
payload: {
|
||||
stripe_customer_id: customerId,
|
||||
value: value.toString(),
|
||||
},
|
||||
...(idempotencyKey && {identifier: idempotencyKey}),
|
||||
});
|
||||
|
||||
signale.debug(`[METER-WORKER] Recorded ${value} email(s) for customer ${customerId}`);
|
||||
}
|
||||
|
||||
export function createMeterWorker(): Worker {
|
||||
const worker = new Worker<MeterEventJobData>(
|
||||
meterQueue.name,
|
||||
async (job: Job<MeterEventJobData>) => {
|
||||
await processMeterEvent(job);
|
||||
},
|
||||
{
|
||||
connection: meterQueue.opts.connection,
|
||||
concurrency: 5,
|
||||
limiter: {
|
||||
max: 50,
|
||||
duration: 1000, // Stay well within Stripe's rate limits
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
worker.on('failed', (job, error) => {
|
||||
signale.error(`[METER-WORKER] Job ${job?.id} failed (attempt ${job?.attemptsMade}):`, error);
|
||||
});
|
||||
|
||||
worker.on('error', error => {
|
||||
signale.error('[METER-WORKER] Worker error:', error);
|
||||
});
|
||||
|
||||
return worker;
|
||||
}
|
||||
@@ -4,12 +4,13 @@
|
||||
*/
|
||||
|
||||
import {CampaignStatus} from '@plunk/db';
|
||||
import type {ScheduledCampaignJobData} from '@plunk/types';
|
||||
import {type Job, Worker} from 'bullmq';
|
||||
import signale from 'signale';
|
||||
|
||||
import {prisma} from '../database/prisma.js';
|
||||
import {CampaignService} from '../services/CampaignService.js';
|
||||
import {type ScheduledCampaignJobData, scheduledQueue} from '../services/QueueService.js';
|
||||
import {scheduledQueue} from '../services/QueueService.js';
|
||||
|
||||
export function createScheduledCampaignWorker() {
|
||||
const worker = new Worker<ScheduledCampaignJobData>(
|
||||
|
||||
@@ -3,12 +3,13 @@
|
||||
* Processes segment count update jobs from the BullMQ queue
|
||||
*/
|
||||
|
||||
import type {SegmentCountJobData} from '@plunk/types';
|
||||
import {type Job, Worker} from 'bullmq';
|
||||
import signale from 'signale';
|
||||
|
||||
import {prisma} from '../database/prisma.js';
|
||||
import {NtfyService} from '../services/NtfyService.js';
|
||||
import {type SegmentCountJobData, segmentCountQueue} from '../services/QueueService.js';
|
||||
import {segmentCountQueue} from '../services/QueueService.js';
|
||||
import {SegmentService} from '../services/SegmentService.js';
|
||||
|
||||
/**
|
||||
@@ -17,8 +18,6 @@ import {SegmentService} from '../services/SegmentService.js';
|
||||
* - For segments without trackMembership: only update counts
|
||||
*/
|
||||
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
|
||||
const segments = await prisma.segment.findMany({
|
||||
where: {projectId},
|
||||
@@ -28,45 +27,44 @@ async function processProjectSegments(projectId: string, projectName?: string):
|
||||
const trackedSegments = 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)
|
||||
let updatedSegmentCount = 0;
|
||||
let totalAdded = 0;
|
||||
let totalRemoved = 0;
|
||||
|
||||
if (trackedSegments.length > 0) {
|
||||
for (const segment of trackedSegments) {
|
||||
try {
|
||||
signale.info(
|
||||
`[SEGMENT-COUNT-WORKER] Computing membership for tracked segment "${segment.name}" (${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
|
||||
if (projectName && (result.added > 0 || result.removed > 0)) {
|
||||
await NtfyService.notifySegmentMembershipComputed(
|
||||
segment.name,
|
||||
projectName,
|
||||
projectId,
|
||||
result.total,
|
||||
result.added,
|
||||
result.removed,
|
||||
);
|
||||
// Track segments with actual changes for bundled notification
|
||||
if (result.added > 0 || result.removed > 0) {
|
||||
updatedSegmentCount++;
|
||||
totalAdded += result.added;
|
||||
totalRemoved += result.removed;
|
||||
}
|
||||
} catch (error) {
|
||||
signale.error(`[SEGMENT-COUNT-WORKER] Failed to compute membership for segment ${segment.id}:`, error);
|
||||
// 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)
|
||||
if (nonTrackedSegments.length > 0) {
|
||||
try {
|
||||
await SegmentService.refreshAllMemberCounts(projectId);
|
||||
signale.info(`[SEGMENT-COUNT-WORKER] Updated counts for ${nonTrackedSegments.length} non-tracked segments`);
|
||||
} catch (error) {
|
||||
signale.error(`[SEGMENT-COUNT-WORKER] Failed to update counts for non-tracked segments:`, error);
|
||||
}
|
||||
@@ -79,14 +77,10 @@ async function processProjectSegments(projectId: string, projectName?: string):
|
||||
async function processSegmentCountUpdate(job: Job<SegmentCountJobData>): Promise<void> {
|
||||
const {projectId} = job.data;
|
||||
|
||||
signale.info(`[SEGMENT-COUNT-WORKER] Starting segment count update job ${job.id}`);
|
||||
|
||||
try {
|
||||
if (projectId) {
|
||||
// Process specific project
|
||||
signale.info(`[SEGMENT-COUNT-WORKER] Processing segments for project ${projectId}`);
|
||||
await processProjectSegments(projectId);
|
||||
signale.success(`[SEGMENT-COUNT-WORKER] Completed segments for project ${projectId}`);
|
||||
} else {
|
||||
// Process all active projects
|
||||
const projects = await prisma.project.findMany({
|
||||
@@ -94,7 +88,7 @@ async function processSegmentCountUpdate(job: Job<SegmentCountJobData>): Promise
|
||||
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
|
||||
const PROJECT_BATCH_SIZE = 10;
|
||||
@@ -104,9 +98,7 @@ async function processSegmentCountUpdate(job: Job<SegmentCountJobData>): Promise
|
||||
await Promise.all(
|
||||
batch.map(async project => {
|
||||
try {
|
||||
signale.info(`[SEGMENT-COUNT-WORKER] Processing project ${project.name} (${project.id})`);
|
||||
await processProjectSegments(project.id, project.name);
|
||||
signale.success(`[SEGMENT-COUNT-WORKER] Completed project ${project.name}`);
|
||||
} catch (error) {
|
||||
signale.error(`[SEGMENT-COUNT-WORKER] Failed to process project ${project.id}:`, error);
|
||||
// Don't throw - continue with other projects
|
||||
@@ -119,8 +111,6 @@ async function processSegmentCountUpdate(job: Job<SegmentCountJobData>): Promise
|
||||
await new Promise(resolve => setTimeout(resolve, 2000));
|
||||
}
|
||||
}
|
||||
|
||||
signale.success(`[SEGMENT-COUNT-WORKER] Completed all segment updates`);
|
||||
}
|
||||
} catch (error) {
|
||||
signale.error(`[SEGMENT-COUNT-WORKER] Error processing job ${job.id}:`, error);
|
||||
@@ -147,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) => {
|
||||
signale.error(`[SEGMENT-COUNT-WORKER] Job ${job?.id} failed:`, error);
|
||||
});
|
||||
|
||||
@@ -10,10 +10,12 @@ import {Worker} from 'bullmq';
|
||||
import signale from 'signale';
|
||||
|
||||
import {createApiRequestCleanupWorker} from './api-request-cleanup-processor.js';
|
||||
import {createBulkContactWorker} from './bulk-contact-processor.js';
|
||||
import {createCampaignWorker} from './campaign-processor.js';
|
||||
import {createDomainVerificationWorker} from './domain-verification-processor.js';
|
||||
import {createEmailWorker} from './email-processor.js';
|
||||
import {createImportWorker} from './import-processor.js';
|
||||
import {createMeterWorker} from './meter-processor.js';
|
||||
import {createScheduledCampaignWorker} from './scheduled-processor.js';
|
||||
import {createSegmentCountWorker} from './segment-count-processor.js';
|
||||
import {createWorkflowWorker} from './workflow-processor-queue.js';
|
||||
@@ -49,6 +51,11 @@ async function startWorkers() {
|
||||
workers.push({name: 'import', worker: importWorker});
|
||||
signale.success('[WORKER] Import worker started');
|
||||
|
||||
// Start bulk contact action worker
|
||||
const bulkContactWorker = createBulkContactWorker();
|
||||
workers.push({name: 'bulk-contact-actions', worker: bulkContactWorker});
|
||||
signale.success('[WORKER] Bulk contact action worker started');
|
||||
|
||||
// Start segment count worker
|
||||
const segmentCountWorker = createSegmentCountWorker();
|
||||
workers.push({name: 'segment-count', worker: segmentCountWorker});
|
||||
@@ -64,6 +71,11 @@ async function startWorkers() {
|
||||
workers.push({name: 'api-request-cleanup', worker: apiRequestCleanupWorker});
|
||||
signale.success('[WORKER] API request cleanup worker started');
|
||||
|
||||
// Start meter worker
|
||||
const meterWorker = createMeterWorker();
|
||||
workers.push({name: 'meter', worker: meterWorker});
|
||||
signale.success('[WORKER] Meter worker started');
|
||||
|
||||
signale.success('[WORKER] All workers started successfully');
|
||||
} catch (error) {
|
||||
signale.error('[WORKER] Failed to start workers:', error);
|
||||
|
||||
@@ -3,10 +3,11 @@
|
||||
* Processes workflow steps from the queue (for delayed steps)
|
||||
*/
|
||||
|
||||
import type {WorkflowStepJobData} from '@plunk/types';
|
||||
import {type Job, Worker} from 'bullmq';
|
||||
import signale from 'signale';
|
||||
|
||||
import {workflowQueue, type WorkflowStepJobData} from '../services/QueueService.js';
|
||||
import {workflowQueue} from '../services/QueueService.js';
|
||||
import {WorkflowExecutionService} from '../services/WorkflowExecutionService.js';
|
||||
|
||||
export function createWorkflowWorker() {
|
||||
|
||||
@@ -3,6 +3,20 @@ import type {NextFunction, Request, Response} from 'express';
|
||||
import {databaseRequestLogger} from '../requestLogger.js';
|
||||
import {factories, getPrismaClient} from '../../../../../test/helpers';
|
||||
|
||||
async function waitForLog(prisma: ReturnType<typeof getPrismaClient>, id: string, timeoutMs = 2000) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() < deadline) {
|
||||
const record = await prisma.apiRequest.findUnique({where: {id}});
|
||||
if (record) return record;
|
||||
await new Promise(resolve => setTimeout(resolve, 20));
|
||||
}
|
||||
return prisma.apiRequest.findUnique({where: {id}});
|
||||
}
|
||||
|
||||
async function waitForNoLog(ms = 200) {
|
||||
await new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
describe('Request Logger Middleware', () => {
|
||||
const prisma = getPrismaClient();
|
||||
let req: Partial<Request>;
|
||||
@@ -16,7 +30,6 @@ describe('Request Logger Middleware', () => {
|
||||
projectId = project.id;
|
||||
userId = user.id;
|
||||
|
||||
// Mock request object
|
||||
req = {
|
||||
method: 'POST',
|
||||
path: '/v1/send',
|
||||
@@ -78,13 +91,7 @@ describe('Request Logger Middleware', () => {
|
||||
const responseBody = {success: true, data: {id: '123'}};
|
||||
await res.json!(responseBody);
|
||||
|
||||
// Wait for async logging to complete
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
// Verify database record was created
|
||||
const loggedRequest = await prisma.apiRequest.findUnique({
|
||||
where: {id: 'test-request-id-123'},
|
||||
});
|
||||
const loggedRequest = await waitForLog(prisma, 'test-request-id-123');
|
||||
|
||||
expect(loggedRequest).toBeDefined();
|
||||
expect(loggedRequest?.method).toBe('POST');
|
||||
@@ -110,11 +117,7 @@ describe('Request Logger Middleware', () => {
|
||||
const responseBody = {success: true};
|
||||
await res.json!(responseBody);
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
const loggedRequest = await prisma.apiRequest.findUnique({
|
||||
where: {id: 'public-request-id'},
|
||||
});
|
||||
const loggedRequest = await waitForLog(prisma, 'public-request-id');
|
||||
|
||||
expect(loggedRequest).toBeDefined();
|
||||
expect(loggedRequest?.projectId).toBeNull();
|
||||
@@ -132,11 +135,7 @@ describe('Request Logger Middleware', () => {
|
||||
|
||||
await res.json!({success: true});
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
const loggedRequest = await prisma.apiRequest.findUnique({
|
||||
where: {id: 'test-request-id-123'},
|
||||
});
|
||||
const loggedRequest = await waitForLog(prisma, 'test-request-id-123');
|
||||
|
||||
// Allow for timer imprecision (especially in CI environments)
|
||||
expect(loggedRequest?.duration).toBeGreaterThanOrEqual(45);
|
||||
@@ -163,11 +162,7 @@ describe('Request Logger Middleware', () => {
|
||||
|
||||
await res.json!(errorResponse);
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
const loggedRequest = await prisma.apiRequest.findUnique({
|
||||
where: {id: 'test-request-id-123'},
|
||||
});
|
||||
const loggedRequest = await waitForLog(prisma, 'test-request-id-123');
|
||||
|
||||
expect(loggedRequest).toBeDefined();
|
||||
expect(loggedRequest?.statusCode).toBe(400);
|
||||
@@ -190,11 +185,7 @@ describe('Request Logger Middleware', () => {
|
||||
|
||||
await res.json!(errorResponse);
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
const loggedRequest = await prisma.apiRequest.findUnique({
|
||||
where: {id: 'test-request-id-123'},
|
||||
});
|
||||
const loggedRequest = await waitForLog(prisma, 'test-request-id-123');
|
||||
|
||||
expect(loggedRequest?.statusCode).toBe(500);
|
||||
expect(loggedRequest?.errorCode).toBe('INTERNAL_SERVER_ERROR');
|
||||
@@ -210,11 +201,7 @@ describe('Request Logger Middleware', () => {
|
||||
error: {code: 'RESOURCE_NOT_FOUND', message: 'Template not found'},
|
||||
});
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
const loggedRequest = await prisma.apiRequest.findUnique({
|
||||
where: {id: 'test-request-id-123'},
|
||||
});
|
||||
const loggedRequest = await waitForLog(prisma, 'test-request-id-123');
|
||||
|
||||
expect(loggedRequest?.statusCode).toBe(404);
|
||||
expect(loggedRequest?.errorCode).toBe('RESOURCE_NOT_FOUND');
|
||||
@@ -307,11 +294,8 @@ describe('Request Logger Middleware', () => {
|
||||
|
||||
databaseRequestLogger(req as Request, res as Response, next);
|
||||
await res.json!({success: true});
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
const loggedRequest = await prisma.apiRequest.findUnique({
|
||||
where: {id: `log-${path.replace(/\//g, '-')}`},
|
||||
});
|
||||
const loggedRequest = await waitForLog(prisma, `log-${path.replace(/\//g, '-')}`);
|
||||
|
||||
expect(loggedRequest).toBeDefined();
|
||||
expect(loggedRequest?.path).toBe(path);
|
||||
@@ -334,12 +318,7 @@ describe('Request Logger Middleware', () => {
|
||||
await res.json!({success: true});
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
// TODO: Add assertion to verify request was NOT logged when disabled
|
||||
// const loggedRequest = await prisma.apiRequest.findUnique({
|
||||
// where: {id: 'test-request-id-123'},
|
||||
// });
|
||||
// expect(loggedRequest).toBeNull();
|
||||
|
||||
|
||||
// Restore original value
|
||||
if (originalEnv !== undefined) {
|
||||
process.env.REQUEST_LOGGING = originalEnv;
|
||||
@@ -358,17 +337,18 @@ describe('Request Logger Middleware', () => {
|
||||
|
||||
await res.json!({success: true});
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
// Should create a record with generated UUID
|
||||
const allRequests = await prisma.apiRequest.findMany({
|
||||
where: {
|
||||
path: '/v1/send',
|
||||
method: 'POST',
|
||||
},
|
||||
orderBy: {createdAt: 'desc'},
|
||||
take: 1,
|
||||
});
|
||||
// Should create a record with generated UUID — poll for it
|
||||
const deadline = Date.now() + 2000;
|
||||
let allRequests: Awaited<ReturnType<typeof prisma.apiRequest.findMany>> = [];
|
||||
while (Date.now() < deadline) {
|
||||
allRequests = await prisma.apiRequest.findMany({
|
||||
where: {path: '/v1/send', method: 'POST'},
|
||||
orderBy: {createdAt: 'desc'},
|
||||
take: 1,
|
||||
});
|
||||
if (allRequests.length > 0) break;
|
||||
await new Promise(resolve => setTimeout(resolve, 20));
|
||||
}
|
||||
|
||||
expect(allRequests.length).toBeGreaterThan(0);
|
||||
expect(allRequests[0].id).toBeDefined();
|
||||
@@ -424,11 +404,8 @@ describe('Request Logger Middleware', () => {
|
||||
databaseRequestLogger(reqWithSize as Request, resWithId as Response, next);
|
||||
|
||||
await resWithId.json!({success: true});
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
const loggedRequest = await prisma.apiRequest.findUnique({
|
||||
where: {id: 'test-size-5000'},
|
||||
});
|
||||
const loggedRequest = await waitForLog(prisma, 'test-size-5000');
|
||||
|
||||
expect(loggedRequest?.requestSize).toBe(5000);
|
||||
});
|
||||
@@ -451,11 +428,8 @@ describe('Request Logger Middleware', () => {
|
||||
databaseRequestLogger(reqNoSize as Request, resWithId as Response, next);
|
||||
|
||||
await resWithId.json!({success: true});
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
const loggedRequest = await prisma.apiRequest.findUnique({
|
||||
where: {id: 'test-no-size'},
|
||||
});
|
||||
const loggedRequest = await waitForLog(prisma, 'test-no-size');
|
||||
|
||||
expect(loggedRequest?.requestSize).toBeNull();
|
||||
});
|
||||
@@ -480,11 +454,8 @@ describe('Request Logger Middleware', () => {
|
||||
};
|
||||
|
||||
await resLarge.json!(largeResponse);
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
const loggedRequest = await prisma.apiRequest.findUnique({
|
||||
where: {id: 'test-large-response'},
|
||||
});
|
||||
const loggedRequest = await waitForLog(prisma, 'test-large-response');
|
||||
|
||||
const expectedSize = JSON.stringify(largeResponse).length;
|
||||
expect(loggedRequest?.responseSize).toBe(expectedSize);
|
||||
|
||||
@@ -2,15 +2,13 @@ import dayjs from 'dayjs';
|
||||
import type {NextFunction, Request, Response} from 'express';
|
||||
import jsonwebtoken from 'jsonwebtoken';
|
||||
|
||||
import {JWT_SECRET} from '../app/constants.js';
|
||||
import {prisma} from '../database/prisma.js';
|
||||
import {ErrorCode, HttpException, NotAuthenticated} from '../exceptions/index.js';
|
||||
import type {AuthResponse} from '@plunk/types';
|
||||
|
||||
export interface AuthResponse {
|
||||
type: 'jwt' | 'apiKey';
|
||||
userId?: string;
|
||||
projectId: string;
|
||||
}
|
||||
import {JWT_SECRET, PLUNK_ENABLED} from '../app/constants.js';
|
||||
import {ErrorCode, HttpException, NotAuthenticated} from '../exceptions/index.js';
|
||||
import {MembershipService} from '../services/MembershipService.js';
|
||||
import {ProjectService} from '../services/ProjectService.js';
|
||||
import {UserService} from '../services/UserService.js';
|
||||
|
||||
/**
|
||||
* Middleware to check if this unsubscribe is authenticated on the dashboard
|
||||
@@ -80,72 +78,6 @@ export function parseJwt(request: Request): string {
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Middleware to require project access
|
||||
* Validates that the user is authenticated and has access to the project specified in X-Project-Id header
|
||||
* @param req
|
||||
* @param res
|
||||
* @param next
|
||||
*/
|
||||
export const requireProjectAccess = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
// First authenticate the user
|
||||
const userId = parseJwt(req);
|
||||
|
||||
// Get project ID from header
|
||||
const projectId = req.headers['x-project-id'] as string | undefined;
|
||||
|
||||
if (!projectId) {
|
||||
throw new HttpException(400, 'Project ID is required in X-Project-Id header', ErrorCode.BAD_REQUEST);
|
||||
}
|
||||
|
||||
// Verify user has access to this project and get project status
|
||||
const [membership, project] = await Promise.all([
|
||||
prisma.membership.findUnique({
|
||||
where: {
|
||||
userId_projectId: {
|
||||
userId,
|
||||
projectId,
|
||||
},
|
||||
},
|
||||
}),
|
||||
prisma.project.findUnique({
|
||||
where: {id: projectId},
|
||||
select: {disabled: true},
|
||||
}),
|
||||
]);
|
||||
|
||||
if (!membership) {
|
||||
throw new HttpException(403, 'You do not have access to this project', ErrorCode.PROJECT_ACCESS_DENIED);
|
||||
}
|
||||
|
||||
// Check if project is disabled - block write operations
|
||||
if (project?.disabled) {
|
||||
const method = req.method.toUpperCase();
|
||||
const isWriteOperation = ['POST', 'PUT', 'PATCH', 'DELETE'].includes(method);
|
||||
|
||||
if (isWriteOperation) {
|
||||
throw new HttpException(
|
||||
403,
|
||||
'Project is disabled due to security violations. All write operations are blocked.',
|
||||
ErrorCode.PROJECT_DISABLED,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Set auth response with project ID
|
||||
res.locals.auth = {
|
||||
type: 'jwt',
|
||||
userId,
|
||||
projectId,
|
||||
} as AuthResponse;
|
||||
|
||||
next();
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Middleware to require public API key authentication (for /v1/track endpoint only)
|
||||
* Validates that the request has a valid public key and sets the project
|
||||
@@ -174,12 +106,12 @@ export const requirePublicKey = async (req: Request, res: Response, next: NextFu
|
||||
|
||||
const apiKey = parts[1];
|
||||
|
||||
if (!apiKey) {
|
||||
throw new HttpException(401, 'API key is required in Authorization header', ErrorCode.MISSING_AUTH);
|
||||
}
|
||||
|
||||
// Look up project by public key only
|
||||
const project = await prisma.project.findFirst({
|
||||
where: {
|
||||
public: apiKey,
|
||||
},
|
||||
});
|
||||
const project = await ProjectService.public(apiKey);
|
||||
|
||||
if (!project) {
|
||||
throw new HttpException(
|
||||
@@ -189,6 +121,12 @@ export const requirePublicKey = async (req: Request, res: Response, next: NextFu
|
||||
);
|
||||
}
|
||||
|
||||
// Set auth response with project ID (before disabled check so it's available for logging)
|
||||
res.locals.auth = {
|
||||
type: 'apiKey',
|
||||
projectId: project.id,
|
||||
};
|
||||
|
||||
// Check if project is disabled - block write operations
|
||||
if (project.disabled) {
|
||||
const method = req.method.toUpperCase();
|
||||
@@ -197,18 +135,12 @@ export const requirePublicKey = async (req: Request, res: Response, next: NextFu
|
||||
if (isWriteOperation) {
|
||||
throw new HttpException(
|
||||
403,
|
||||
'Project is disabled due to security violations. All write operations are blocked.',
|
||||
'This project has been disabled. Please contact support for assistance.',
|
||||
ErrorCode.PROJECT_DISABLED,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Set auth response with project ID
|
||||
res.locals.auth = {
|
||||
type: 'apiKey',
|
||||
projectId: project.id,
|
||||
} as AuthResponse;
|
||||
|
||||
next();
|
||||
} catch (error) {
|
||||
next(error);
|
||||
@@ -243,12 +175,12 @@ export const requireSecretKey = async (req: Request, res: Response, next: NextFu
|
||||
|
||||
const apiKey = parts[1];
|
||||
|
||||
if (!apiKey) {
|
||||
throw new HttpException(401, 'API key is required in Authorization header', ErrorCode.MISSING_AUTH);
|
||||
}
|
||||
|
||||
// Look up project by secret key only
|
||||
const project = await prisma.project.findFirst({
|
||||
where: {
|
||||
secret: apiKey,
|
||||
},
|
||||
});
|
||||
const project = await ProjectService.secret(apiKey);
|
||||
|
||||
if (!project) {
|
||||
throw new HttpException(
|
||||
@@ -258,6 +190,12 @@ export const requireSecretKey = async (req: Request, res: Response, next: NextFu
|
||||
);
|
||||
}
|
||||
|
||||
// Set auth response with project ID (before disabled check so it's available for logging)
|
||||
res.locals.auth = {
|
||||
type: 'apiKey',
|
||||
projectId: project.id,
|
||||
};
|
||||
|
||||
// Check if project is disabled - block write operations
|
||||
if (project.disabled) {
|
||||
const method = req.method.toUpperCase();
|
||||
@@ -266,18 +204,12 @@ export const requireSecretKey = async (req: Request, res: Response, next: NextFu
|
||||
if (isWriteOperation) {
|
||||
throw new HttpException(
|
||||
403,
|
||||
'Project is disabled due to security violations. All write operations are blocked.',
|
||||
'This project has been disabled. Please contact support for assistance.',
|
||||
ErrorCode.PROJECT_DISABLED,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Set auth response with project ID
|
||||
res.locals.auth = {
|
||||
type: 'apiKey',
|
||||
projectId: project.id,
|
||||
} as AuthResponse;
|
||||
|
||||
next();
|
||||
} catch (error) {
|
||||
next(error);
|
||||
@@ -310,12 +242,12 @@ export const requireAuth = async (req: Request, res: Response, next: NextFunctio
|
||||
}
|
||||
|
||||
const apiKey = parts[1];
|
||||
|
||||
if (!apiKey) {
|
||||
throw new HttpException(401, 'API key is required in Authorization header', ErrorCode.MISSING_AUTH);
|
||||
}
|
||||
// Look up project by secret key only (public keys not allowed)
|
||||
const project = await prisma.project.findFirst({
|
||||
where: {
|
||||
secret: apiKey,
|
||||
},
|
||||
});
|
||||
const project = await ProjectService.secret(apiKey);
|
||||
|
||||
if (!project) {
|
||||
throw new HttpException(
|
||||
@@ -325,6 +257,12 @@ export const requireAuth = async (req: Request, res: Response, next: NextFunctio
|
||||
);
|
||||
}
|
||||
|
||||
// Set auth response with project ID (before disabled check so it's available for logging)
|
||||
res.locals.auth = {
|
||||
type: 'apiKey',
|
||||
projectId: project.id,
|
||||
} as AuthResponse;
|
||||
|
||||
// Check if project is disabled - block write operations
|
||||
if (project.disabled) {
|
||||
const method = req.method.toUpperCase();
|
||||
@@ -333,18 +271,12 @@ export const requireAuth = async (req: Request, res: Response, next: NextFunctio
|
||||
if (isWriteOperation) {
|
||||
throw new HttpException(
|
||||
403,
|
||||
'Project is disabled due to security violations. All write operations are blocked.',
|
||||
'This project has been disabled. Please contact support for assistance.',
|
||||
ErrorCode.PROJECT_DISABLED,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Set auth response with project ID
|
||||
res.locals.auth = {
|
||||
type: 'apiKey',
|
||||
projectId: project.id,
|
||||
} as AuthResponse;
|
||||
|
||||
return next();
|
||||
}
|
||||
|
||||
@@ -360,24 +292,21 @@ export const requireAuth = async (req: Request, res: Response, next: NextFunctio
|
||||
|
||||
// Verify user has access to this project and get project status
|
||||
const [membership, project] = await Promise.all([
|
||||
prisma.membership.findUnique({
|
||||
where: {
|
||||
userId_projectId: {
|
||||
userId,
|
||||
projectId,
|
||||
},
|
||||
},
|
||||
}),
|
||||
prisma.project.findUnique({
|
||||
where: {id: projectId},
|
||||
select: {disabled: true},
|
||||
}),
|
||||
MembershipService.getMembership(userId, projectId),
|
||||
ProjectService.id(projectId),
|
||||
]);
|
||||
|
||||
if (!membership) {
|
||||
throw new HttpException(403, 'You do not have access to this project', ErrorCode.PROJECT_ACCESS_DENIED);
|
||||
}
|
||||
|
||||
// Set auth response with project ID (before disabled check so it's available for logging)
|
||||
res.locals.auth = {
|
||||
type: 'jwt',
|
||||
userId,
|
||||
projectId,
|
||||
};
|
||||
|
||||
// Check if project is disabled - block write operations
|
||||
if (project?.disabled) {
|
||||
const method = req.method.toUpperCase();
|
||||
@@ -386,18 +315,61 @@ export const requireAuth = async (req: Request, res: Response, next: NextFunctio
|
||||
if (isWriteOperation) {
|
||||
throw new HttpException(
|
||||
403,
|
||||
'Project is disabled due to security violations. All write operations are blocked.',
|
||||
'This project has been disabled. Please contact support for assistance.',
|
||||
ErrorCode.PROJECT_DISABLED,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Set auth response with project ID
|
||||
res.locals.auth = {
|
||||
type: 'jwt',
|
||||
userId,
|
||||
projectId,
|
||||
} as AuthResponse;
|
||||
next();
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Middleware to require email verification
|
||||
* Must be used AFTER isAuthenticated or requireProjectAccess
|
||||
* @param req
|
||||
* @param res
|
||||
* @param next
|
||||
*/
|
||||
export const requireEmailVerified = async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const auth = res.locals.auth;
|
||||
|
||||
if (auth.type === 'apiKey') {
|
||||
return next();
|
||||
}
|
||||
|
||||
if (!auth.userId) {
|
||||
throw new NotAuthenticated();
|
||||
}
|
||||
|
||||
const user = await UserService.id(auth.userId);
|
||||
|
||||
if (!user) {
|
||||
throw new NotAuthenticated();
|
||||
}
|
||||
|
||||
// If platform email verification is disabled, skip check
|
||||
if (!PLUNK_ENABLED) {
|
||||
return next();
|
||||
}
|
||||
|
||||
// OAuth users are always considered verified
|
||||
if (user.type !== 'PASSWORD') {
|
||||
return next();
|
||||
}
|
||||
|
||||
// PASSWORD users must verify email
|
||||
if (!user.emailVerified) {
|
||||
throw new HttpException(
|
||||
403,
|
||||
'Please verify your email address to access this resource',
|
||||
ErrorCode.EMAIL_VERIFICATION_REQUIRED,
|
||||
);
|
||||
}
|
||||
|
||||
next();
|
||||
} catch (error) {
|
||||
|
||||
@@ -1,61 +1,12 @@
|
||||
import type {Prisma} from '@plunk/db';
|
||||
import type {Activity, ActivityStats, CursorPaginatedResponse} from '@plunk/types';
|
||||
import {ActivityType} from '@plunk/types';
|
||||
import signale from 'signale';
|
||||
|
||||
import {prisma} from '../database/prisma.js';
|
||||
import {redis} from '../database/redis.js';
|
||||
import {Keys} from './keys.js';
|
||||
|
||||
/**
|
||||
* Activity types that can be tracked
|
||||
*/
|
||||
export enum ActivityType {
|
||||
EVENT_TRIGGERED = 'event.triggered',
|
||||
EMAIL_SENT = 'email.sent',
|
||||
EMAIL_DELIVERED = 'email.delivered',
|
||||
EMAIL_OPENED = 'email.opened',
|
||||
EMAIL_CLICKED = 'email.clicked',
|
||||
EMAIL_BOUNCED = 'email.bounced',
|
||||
CAMPAIGN_SENT = 'campaign.sent',
|
||||
CAMPAIGN_SCHEDULED = 'campaign.scheduled',
|
||||
WORKFLOW_STARTED = 'workflow.started',
|
||||
WORKFLOW_COMPLETED = 'workflow.completed',
|
||||
WORKFLOW_EMAIL_SCHEDULED = 'workflow.email.scheduled',
|
||||
}
|
||||
|
||||
/**
|
||||
* Unified activity item
|
||||
*/
|
||||
export interface Activity {
|
||||
id: string;
|
||||
type: ActivityType;
|
||||
timestamp: Date;
|
||||
contactEmail?: string;
|
||||
contactId?: string;
|
||||
metadata: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Paginated activity response
|
||||
*/
|
||||
export interface PaginatedActivities {
|
||||
activities: Activity[];
|
||||
nextCursor?: string;
|
||||
hasMore: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Activity stats for dashboard
|
||||
*/
|
||||
export interface ActivityStats {
|
||||
totalEvents: number;
|
||||
totalEmailsSent: number;
|
||||
totalEmailsOpened: number;
|
||||
totalEmailsClicked: number;
|
||||
totalWorkflowsStarted: number;
|
||||
openRate: number;
|
||||
clickRate: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Activity Service
|
||||
*
|
||||
@@ -107,7 +58,7 @@ export class ActivityService {
|
||||
contactId?: string,
|
||||
startDate?: Date,
|
||||
endDate?: Date,
|
||||
): Promise<PaginatedActivities> {
|
||||
): Promise<CursorPaginatedResponse<Activity>> {
|
||||
// Cap limit to prevent abuse
|
||||
const effectiveLimit = Math.min(limit, this.MAX_LIMIT);
|
||||
|
||||
@@ -116,10 +67,14 @@ export class ActivityService {
|
||||
const fetchLimit = effectiveLimit;
|
||||
|
||||
// Default date range to last 30 days if not specified
|
||||
// IMPORTANT: When cursor is provided (pagination), we should NOT apply the gte constraint
|
||||
// to allow users to paginate back beyond the initial date range
|
||||
const now = new Date();
|
||||
const defaultStartDate = new Date(now.getTime() - this.DEFAULT_DAYS_BACK * 24 * 60 * 60 * 1000);
|
||||
const dateFilter: Prisma.DateTimeFilter = {
|
||||
gte: startDate || defaultStartDate,
|
||||
// Only apply start date filter on initial load (no cursor)
|
||||
// This allows pagination to go back indefinitely
|
||||
...(cursor ? {} : {gte: startDate || defaultStartDate}),
|
||||
...(endDate ? {lte: endDate} : {}),
|
||||
};
|
||||
|
||||
@@ -158,8 +113,8 @@ export class ActivityService {
|
||||
const nextCursor = hasMore && lastActivity ? `${lastActivity.timestamp.getTime()}_${lastActivity.id}` : undefined;
|
||||
|
||||
return {
|
||||
activities: results,
|
||||
nextCursor,
|
||||
data: results,
|
||||
cursor: nextCursor,
|
||||
hasMore,
|
||||
};
|
||||
}
|
||||
@@ -267,11 +222,34 @@ export class ActivityService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Short Redis TTL for recent-count results. Short enough to feel live on the
|
||||
* dashboard live-pulse, long enough to absorb the polling load when many
|
||||
* tabs are open across the user base.
|
||||
*/
|
||||
private static readonly RECENT_COUNT_CACHE_TTL = 10; // seconds
|
||||
|
||||
/**
|
||||
* Get recent activity count (for real-time updates)
|
||||
* Returns count of activities in the last N minutes
|
||||
*
|
||||
* Backed by a short Redis cache because the dashboard polls this endpoint
|
||||
* every 30 seconds per open tab; without the cache, every poll would run
|
||||
* three COUNT queries against the events, emails, and workflow_executions
|
||||
* tables.
|
||||
*/
|
||||
public static async getRecentActivityCount(projectId: string, minutes = 5): Promise<number> {
|
||||
const cacheKey = Keys.Activity.recentCount(projectId, minutes);
|
||||
|
||||
try {
|
||||
const cached = await redis.get(cacheKey);
|
||||
if (cached !== null) {
|
||||
return parseInt(cached, 10);
|
||||
}
|
||||
} catch (error) {
|
||||
signale.warn('[ACTIVITY] Failed to read recent-count cache:', error);
|
||||
}
|
||||
|
||||
const since = new Date(Date.now() - minutes * 60 * 1000);
|
||||
const dateFilter: Prisma.DateTimeFilter = {gte: since};
|
||||
|
||||
@@ -290,7 +268,15 @@ export class ActivityService {
|
||||
}),
|
||||
]);
|
||||
|
||||
return eventCount + emailCount + workflowCount;
|
||||
const total = eventCount + emailCount + workflowCount;
|
||||
|
||||
try {
|
||||
await redis.setex(cacheKey, this.RECENT_COUNT_CACHE_TTL, total.toString());
|
||||
} catch (error) {
|
||||
signale.warn('[ACTIVITY] Failed to cache recent-count:', error);
|
||||
}
|
||||
|
||||
return total;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -413,17 +399,51 @@ export class ActivityService {
|
||||
const where: Prisma.EmailWhereInput = {
|
||||
projectId,
|
||||
...(contactId ? {contactId} : {}),
|
||||
// Apply cursor-based pagination filter on createdAt
|
||||
// This is critical for pagination to work correctly
|
||||
createdAt: cursorTimestamp
|
||||
? {
|
||||
...dateFilter,
|
||||
lt: cursorTimestamp,
|
||||
}
|
||||
: dateFilter,
|
||||
};
|
||||
|
||||
// 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({
|
||||
where: {
|
||||
...where,
|
||||
createdAt: cursorTimestamp
|
||||
? {
|
||||
...dateFilter,
|
||||
lt: cursorTimestamp,
|
||||
}
|
||||
: dateFilter,
|
||||
OR: orConditions,
|
||||
},
|
||||
orderBy: {createdAt: 'desc'},
|
||||
take: limit,
|
||||
@@ -450,16 +470,42 @@ 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
|
||||
for (const email of emails) {
|
||||
const baseMetadata = {
|
||||
subject: email.subject,
|
||||
body: email.body,
|
||||
from: email.from,
|
||||
fromName: email.fromName,
|
||||
replyTo: email.replyTo,
|
||||
toName: email.toName,
|
||||
sourceType: email.sourceType,
|
||||
campaignName: email.campaign?.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({
|
||||
id: `${email.id}_sent`,
|
||||
type: ActivityType.EMAIL_SENT,
|
||||
@@ -470,7 +516,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({
|
||||
id: `${email.id}_delivered`,
|
||||
type: ActivityType.EMAIL_DELIVERED,
|
||||
@@ -481,7 +531,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({
|
||||
id: `${email.id}_opened`,
|
||||
type: ActivityType.EMAIL_OPENED,
|
||||
@@ -496,7 +562,7 @@ export class ActivityService {
|
||||
}
|
||||
|
||||
// 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({
|
||||
id: `${email.id}_clicked`,
|
||||
type: ActivityType.EMAIL_CLICKED,
|
||||
@@ -511,7 +577,7 @@ export class ActivityService {
|
||||
}
|
||||
|
||||
// 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({
|
||||
id: `${email.id}_bounced`,
|
||||
type: ActivityType.EMAIL_BOUNCED,
|
||||
@@ -524,6 +590,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;
|
||||
|
||||
@@ -58,14 +58,16 @@ export class AnalyticsService {
|
||||
const limitedStartDate = effectiveStartDate < maxStartDate ? maxStartDate : effectiveStartDate;
|
||||
|
||||
// Check cache first
|
||||
const cacheKey = Keys.Analytics.timeseries(projectId, limitedStartDate.toISOString(), effectiveEndDate.toISOString());
|
||||
const cacheKey = Keys.Analytics.timeseries(
|
||||
projectId,
|
||||
limitedStartDate.toISOString(),
|
||||
effectiveEndDate.toISOString(),
|
||||
);
|
||||
const cached = await redis.get(cacheKey);
|
||||
if (cached) {
|
||||
return JSON.parse(cached);
|
||||
}
|
||||
|
||||
// Raw SQL query for efficient daily aggregation
|
||||
// Using raw SQL because Prisma's groupBy is less efficient for date truncation
|
||||
const result = await prisma.$queryRaw<
|
||||
{
|
||||
date: Date;
|
||||
@@ -191,7 +193,11 @@ export class AnalyticsService {
|
||||
const effectiveEndDate = endDate || now;
|
||||
|
||||
// Check cache
|
||||
const cacheKey = Keys.Analytics.campaignStats(projectId, effectiveStartDate.toISOString(), effectiveEndDate.toISOString());
|
||||
const cacheKey = Keys.Analytics.campaignStats(
|
||||
projectId,
|
||||
effectiveStartDate.toISOString(),
|
||||
effectiveEndDate.toISOString(),
|
||||
);
|
||||
const cached = await redis.get(cacheKey);
|
||||
if (cached) {
|
||||
return JSON.parse(cached);
|
||||
@@ -295,7 +301,12 @@ export class AnalyticsService {
|
||||
const effectiveEndDate = endDate || now;
|
||||
|
||||
// Check cache
|
||||
const cacheKey = Keys.Analytics.topEvents(projectId, limit, effectiveStartDate.toISOString(), effectiveEndDate.toISOString());
|
||||
const cacheKey = Keys.Analytics.topEvents(
|
||||
projectId,
|
||||
limit,
|
||||
effectiveStartDate.toISOString(),
|
||||
effectiveEndDate.toISOString(),
|
||||
);
|
||||
const cached = await redis.get(cacheKey);
|
||||
if (cached) {
|
||||
return JSON.parse(cached);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {EmailSourceType} from '@plunk/db';
|
||||
import type {BillingLimitsResponse, CategoryUsage, LimitCheckResult} from '@plunk/types';
|
||||
import {BillingLimitExceededEmail, BillingLimitWarningEmail, sendPlatformEmail} from '@plunk/email';
|
||||
import React from 'react';
|
||||
import signale from 'signale';
|
||||
@@ -8,41 +9,9 @@ import {stripe} from '../app/stripe.js';
|
||||
import {prisma} from '../database/prisma.js';
|
||||
import {redis} from '../database/redis.js';
|
||||
import {Keys} from './keys.js';
|
||||
import {MembershipService} from './MembershipService.js';
|
||||
import {NtfyService} from './NtfyService.js';
|
||||
|
||||
/**
|
||||
* Usage information for a specific email category
|
||||
*/
|
||||
export interface CategoryUsage {
|
||||
limit: number | null; // null = unlimited
|
||||
usage: number;
|
||||
percentage: number; // 0-100
|
||||
isWarning: boolean; // true if >= 80%
|
||||
isBlocked: boolean; // true if >= 100%
|
||||
}
|
||||
|
||||
/**
|
||||
* Complete billing limits and usage for a project
|
||||
*/
|
||||
export interface BillingLimitsResponse {
|
||||
workflows: CategoryUsage;
|
||||
campaigns: CategoryUsage;
|
||||
transactional: CategoryUsage;
|
||||
currency: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Result of limit check
|
||||
*/
|
||||
export interface LimitCheckResult {
|
||||
allowed: boolean;
|
||||
warning: boolean; // true if >= 80% but < 100%
|
||||
usage: number;
|
||||
limit: number | null;
|
||||
percentage: number;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Billing Limit Service
|
||||
* Handles usage tracking and enforcement of billing limits per email category
|
||||
@@ -188,6 +157,7 @@ export class BillingLimitService {
|
||||
billingLimitWorkflows: true,
|
||||
billingLimitCampaigns: true,
|
||||
billingLimitTransactional: true,
|
||||
billingLimitInbound: true,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -214,6 +184,9 @@ export class BillingLimitService {
|
||||
case EmailSourceType.TRANSACTIONAL:
|
||||
limit = project.billingLimitTransactional;
|
||||
break;
|
||||
case EmailSourceType.INBOUND:
|
||||
limit = project.billingLimitInbound;
|
||||
break;
|
||||
default:
|
||||
limit = null;
|
||||
}
|
||||
@@ -222,7 +195,8 @@ export class BillingLimitService {
|
||||
const hasCustomLimits =
|
||||
project.billingLimitWorkflows !== 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
|
||||
// Only enforce free tier limits if billing is enabled
|
||||
@@ -399,6 +373,7 @@ export class BillingLimitService {
|
||||
billingLimitWorkflows: true,
|
||||
billingLimitCampaigns: true,
|
||||
billingLimitTransactional: true,
|
||||
billingLimitInbound: true,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -421,10 +396,11 @@ export class BillingLimitService {
|
||||
}
|
||||
|
||||
// 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.CAMPAIGN),
|
||||
this.getUsage(projectId, EmailSourceType.TRANSACTIONAL),
|
||||
this.getUsage(projectId, EmailSourceType.INBOUND),
|
||||
]);
|
||||
|
||||
// Helper to calculate category usage
|
||||
@@ -443,18 +419,19 @@ export class BillingLimitService {
|
||||
const hasCustomLimits =
|
||||
project.billingLimitWorkflows !== 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
|
||||
// Only show free tier limits if billing is enabled
|
||||
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 percentage = (totalUsage / limit) * 100;
|
||||
const isWarning = percentage >= this.WARNING_THRESHOLD * 100;
|
||||
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
|
||||
const sharedUsageInfo: CategoryUsage = {
|
||||
limit,
|
||||
@@ -468,6 +445,7 @@ export class BillingLimitService {
|
||||
workflows: sharedUsageInfo,
|
||||
campaigns: sharedUsageInfo,
|
||||
transactional: sharedUsageInfo,
|
||||
inbound: sharedUsageInfo,
|
||||
currency,
|
||||
};
|
||||
}
|
||||
@@ -477,6 +455,7 @@ export class BillingLimitService {
|
||||
workflows: calculateCategoryUsage(workflowUsage, project.billingLimitWorkflows),
|
||||
campaigns: calculateCategoryUsage(campaignUsage, project.billingLimitCampaigns),
|
||||
transactional: calculateCategoryUsage(transactionalUsage, project.billingLimitTransactional),
|
||||
inbound: calculateCategoryUsage(inboundUsage, project.billingLimitInbound),
|
||||
currency,
|
||||
};
|
||||
} catch (error) {
|
||||
@@ -501,6 +480,7 @@ export class BillingLimitService {
|
||||
this.getCacheKey(projectId, EmailSourceType.WORKFLOW),
|
||||
this.getCacheKey(projectId, EmailSourceType.CAMPAIGN),
|
||||
this.getCacheKey(projectId, EmailSourceType.TRANSACTIONAL),
|
||||
this.getCacheKey(projectId, EmailSourceType.INBOUND),
|
||||
];
|
||||
|
||||
await Promise.all(keys.map(key => redis.del(key)));
|
||||
@@ -524,11 +504,13 @@ export class BillingLimitService {
|
||||
workflows: number | null;
|
||||
campaigns: number | null;
|
||||
transactional: number | null;
|
||||
inbound: number | null;
|
||||
},
|
||||
newLimits: {
|
||||
workflows: number | null;
|
||||
campaigns: number | null;
|
||||
transactional: number | null;
|
||||
inbound: number | null;
|
||||
},
|
||||
): Promise<void> {
|
||||
try {
|
||||
@@ -562,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) {
|
||||
await Promise.all(keysToDelete.map(key => redis.del(key)));
|
||||
signale.debug(
|
||||
@@ -611,16 +601,20 @@ export class BillingLimitService {
|
||||
const month = String(now.getMonth() + 1).padStart(2, '0');
|
||||
const cacheKey = Keys.Billing.warningEmail(projectId, sourceType, year, month);
|
||||
|
||||
const alreadySent = await redis.get(cacheKey);
|
||||
if (alreadySent === '1') {
|
||||
// Use SETNX (SET if Not eXists) to atomically check and set the flag
|
||||
// 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;
|
||||
}
|
||||
|
||||
const members = await prisma.membership.findMany({
|
||||
where: {projectId},
|
||||
include: {user: {select: {email: true}}},
|
||||
});
|
||||
const emails = members.map(m => m.user.email);
|
||||
const members = await MembershipService.getMembers(projectId);
|
||||
const emails = members.map(m => m.email);
|
||||
if (emails.length === 0) {
|
||||
return;
|
||||
}
|
||||
@@ -637,11 +631,6 @@ export class BillingLimitService {
|
||||
});
|
||||
|
||||
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) {
|
||||
signale.error(`[BILLING_LIMIT] Failed to send warning email:`, error);
|
||||
}
|
||||
@@ -664,16 +653,20 @@ export class BillingLimitService {
|
||||
const month = String(now.getMonth() + 1).padStart(2, '0');
|
||||
const cacheKey = Keys.Billing.limitEmail(projectId, sourceType, year, month);
|
||||
|
||||
const alreadySent = await redis.get(cacheKey);
|
||||
if (alreadySent === '1') {
|
||||
// Use SETNX (SET if Not eXists) to atomically check and set the flag
|
||||
// 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;
|
||||
}
|
||||
|
||||
const members = await prisma.membership.findMany({
|
||||
where: {projectId},
|
||||
include: {user: {select: {email: true}}},
|
||||
});
|
||||
const emails = members.map(m => m.user.email);
|
||||
const members = await MembershipService.getMembers(projectId);
|
||||
const emails = members.map(m => m.email);
|
||||
if (emails.length === 0) {
|
||||
return;
|
||||
}
|
||||
@@ -689,11 +682,6 @@ export class BillingLimitService {
|
||||
});
|
||||
|
||||
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) {
|
||||
signale.error(`[BILLING_LIMIT] Failed to send limit exceeded email:`, error);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type {Campaign, Contact, Prisma} from '@plunk/db';
|
||||
import {CampaignAudienceType, CampaignStatus, EmailSourceType} from '@plunk/db';
|
||||
import type {FilterCondition} from '@plunk/types';
|
||||
import {CampaignAudienceType, CampaignStatus, EmailSourceType, EmailStatus, TemplateType} from '@plunk/db';
|
||||
import type {CreateCampaignData, FilterCondition, PaginatedResponse, UpdateCampaignData} from '@plunk/types';
|
||||
import {fromPrismaJson, toPrismaJson} from '@plunk/types';
|
||||
import signale from 'signale';
|
||||
|
||||
import {prisma} from '../database/prisma.js';
|
||||
@@ -18,32 +19,6 @@ import {sendRawEmail} from './SESService.js';
|
||||
|
||||
const BATCH_SIZE = 500; // Number of emails to process per batch (increased for better performance)
|
||||
|
||||
export interface CreateCampaignData {
|
||||
name: string;
|
||||
description?: string;
|
||||
subject: string;
|
||||
body: string;
|
||||
from: string;
|
||||
fromName?: string | null;
|
||||
replyTo?: string | null;
|
||||
audienceType: CampaignAudienceType;
|
||||
audienceCondition?: FilterCondition;
|
||||
segmentId?: string;
|
||||
}
|
||||
|
||||
export interface UpdateCampaignData {
|
||||
name?: string;
|
||||
description?: string;
|
||||
subject?: string;
|
||||
body?: string;
|
||||
from?: string;
|
||||
fromName?: string | null;
|
||||
replyTo?: string | null;
|
||||
audienceType?: CampaignAudienceType;
|
||||
audienceCondition?: FilterCondition;
|
||||
segmentId?: string;
|
||||
}
|
||||
|
||||
export class CampaignService {
|
||||
/**
|
||||
* Create a new campaign
|
||||
@@ -84,8 +59,9 @@ export class CampaignService {
|
||||
from: data.from,
|
||||
fromName: data.fromName,
|
||||
replyTo: data.replyTo,
|
||||
type: data.type ?? TemplateType.MARKETING,
|
||||
audienceType: data.audienceType,
|
||||
audienceCondition: (data.audienceCondition || null) as unknown as Prisma.InputJsonValue,
|
||||
audienceCondition: toPrismaJson(data.audienceCondition || null),
|
||||
segmentId: data.segmentId,
|
||||
status: CampaignStatus.DRAFT,
|
||||
totalRecipients: 0, // Will be updated below
|
||||
@@ -125,6 +101,10 @@ export class CampaignService {
|
||||
const updateData: Prisma.CampaignUpdateInput = buildEmailFieldsUpdate(data) as Prisma.CampaignUpdateInput;
|
||||
|
||||
// Handle campaign-specific fields
|
||||
if (data.type !== undefined) {
|
||||
updateData.type = data.type;
|
||||
}
|
||||
|
||||
if (data.audienceType !== undefined) {
|
||||
updateData.audienceType = data.audienceType;
|
||||
}
|
||||
@@ -133,7 +113,7 @@ export class CampaignService {
|
||||
if (data.audienceCondition) {
|
||||
SegmentService.validateCondition(data.audienceCondition);
|
||||
}
|
||||
updateData.audienceCondition = (data.audienceCondition || null) as unknown as Prisma.InputJsonValue;
|
||||
updateData.audienceCondition = toPrismaJson(data.audienceCondition || null);
|
||||
}
|
||||
|
||||
if (data.segmentId !== undefined) {
|
||||
@@ -206,16 +186,26 @@ export class CampaignService {
|
||||
projectId: string,
|
||||
options: {
|
||||
status?: CampaignStatus;
|
||||
search?: string;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
} = {},
|
||||
): Promise<{campaigns: Campaign[]; total: number; page: number; pageSize: number; totalPages: number}> {
|
||||
const {status, page = 1, pageSize = 20} = options;
|
||||
): Promise<PaginatedResponse<Campaign>> {
|
||||
const {status, search, page = 1, pageSize = 20} = options;
|
||||
const skip = (page - 1) * pageSize;
|
||||
|
||||
const where: Prisma.CampaignWhereInput = {
|
||||
projectId,
|
||||
...(status ? {status} : {}),
|
||||
...(search
|
||||
? {
|
||||
OR: [
|
||||
{name: {contains: search, mode: 'insensitive' as const}},
|
||||
{subject: {contains: search, mode: 'insensitive' as const}},
|
||||
{from: {contains: search, mode: 'insensitive' as const}},
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
|
||||
const [campaigns, total] = await Promise.all([
|
||||
@@ -232,7 +222,7 @@ export class CampaignService {
|
||||
]);
|
||||
|
||||
return {
|
||||
campaigns,
|
||||
data: campaigns,
|
||||
total,
|
||||
page,
|
||||
pageSize,
|
||||
@@ -287,6 +277,7 @@ export class CampaignService {
|
||||
from: campaign.from,
|
||||
fromName: campaign.fromName,
|
||||
replyTo: campaign.replyTo,
|
||||
type: campaign.type,
|
||||
audienceType: campaign.audienceType,
|
||||
audienceCondition: campaign.audienceCondition as Prisma.InputJsonValue,
|
||||
segmentId: campaign.segmentId,
|
||||
@@ -476,6 +467,7 @@ export class CampaignService {
|
||||
const contactData =
|
||||
contact.data && typeof contact.data === 'object' && !Array.isArray(contact.data) ? contact.data : {};
|
||||
const variables = {
|
||||
id: contact.id,
|
||||
email: contact.email,
|
||||
...contactData,
|
||||
data: contactData,
|
||||
@@ -506,6 +498,7 @@ export class CampaignService {
|
||||
from: campaign.from,
|
||||
fromName: campaign.fromName || undefined,
|
||||
replyTo: campaign.replyTo || undefined,
|
||||
isTransactional: campaign.type === TemplateType.TRANSACTIONAL,
|
||||
});
|
||||
} catch (error) {
|
||||
signale.error(`[CAMPAIGN] Failed to queue email for contact ${contact.id}:`, error);
|
||||
@@ -522,9 +515,77 @@ export class CampaignService {
|
||||
limit,
|
||||
cursor: nextCursor,
|
||||
});
|
||||
} else {
|
||||
// Last batch: reconcile totalRecipients to the actual number of emails created.
|
||||
// Dynamic segments re-evaluate on each batch query, so contacts that left the
|
||||
// segment after totalRecipients was calculated are silently skipped. Without this
|
||||
// reconciliation, sentCount can never reach the original totalRecipients and the
|
||||
// campaign remains stuck in SENDING forever.
|
||||
const actualEmailCount = await prisma.email.count({where: {campaignId}});
|
||||
|
||||
await prisma.campaign.update({
|
||||
where: {id: campaignId},
|
||||
data: {totalRecipients: actualEmailCount},
|
||||
});
|
||||
|
||||
await this.finalizeIfDone(campaignId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finalize a SENDING campaign if every email has reached a terminal state.
|
||||
* Terminal = sentAt is set OR status is FAILED. Counting FAILED as terminal
|
||||
* unsticks campaigns where some emails couldn't be delivered (e.g. the project
|
||||
* was disabled mid-send), so the campaign moves to SENT with a partial sentCount.
|
||||
*/
|
||||
public static async finalizeIfDone(campaignId: string): Promise<void> {
|
||||
const campaign = await prisma.campaign.findUnique({
|
||||
where: {id: campaignId},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
status: true,
|
||||
totalRecipients: true,
|
||||
projectId: true,
|
||||
project: {select: {name: true}},
|
||||
},
|
||||
});
|
||||
|
||||
if (!campaign || campaign.status !== CampaignStatus.SENDING) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [processedCount, sentCount] = await Promise.all([
|
||||
prisma.email.count({
|
||||
where: {
|
||||
campaignId,
|
||||
OR: [{sentAt: {not: null}}, {status: EmailStatus.FAILED}],
|
||||
},
|
||||
}),
|
||||
prisma.email.count({where: {campaignId, sentAt: {not: null}}}),
|
||||
]);
|
||||
|
||||
if (campaign.totalRecipients > 0 && processedCount < campaign.totalRecipients) {
|
||||
return;
|
||||
}
|
||||
|
||||
await prisma.campaign.update({
|
||||
where: {id: campaignId},
|
||||
data: {status: CampaignStatus.SENT, sentCount},
|
||||
});
|
||||
|
||||
signale.success(
|
||||
`[CAMPAIGN] Campaign ${campaign.name} finalized: ${sentCount}/${campaign.totalRecipients} emails sent`,
|
||||
);
|
||||
|
||||
await NtfyService.notifyCampaignSendCompleted(
|
||||
campaign.name,
|
||||
campaign.project.name,
|
||||
campaign.projectId,
|
||||
sentCount,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel a campaign
|
||||
*/
|
||||
@@ -589,6 +650,7 @@ export class CampaignService {
|
||||
await prisma.campaign.update({
|
||||
where: {id: campaignId},
|
||||
data: {
|
||||
sentCount: sentEmails,
|
||||
deliveredCount: deliveredEmails,
|
||||
openedCount: openedEmails,
|
||||
clickedCount: clickedEmails,
|
||||
@@ -731,7 +793,8 @@ export class CampaignService {
|
||||
): Promise<Prisma.ContactWhereInput> {
|
||||
const baseWhere: Prisma.ContactWhereInput = {
|
||||
projectId,
|
||||
subscribed: true, // Only send to subscribed contacts
|
||||
// Transactional campaigns send to all contacts regardless of subscription status
|
||||
...(campaign.type !== TemplateType.TRANSACTIONAL && {subscribed: true}),
|
||||
};
|
||||
|
||||
switch (campaign.audienceType) {
|
||||
@@ -747,13 +810,13 @@ export class CampaignService {
|
||||
return this.buildSegmentWhereAsync(projectId, campaign.segmentId, baseWhere);
|
||||
|
||||
case CampaignAudienceType.FILTERED: {
|
||||
const condition = campaign.audienceCondition as unknown as FilterCondition;
|
||||
const condition = fromPrismaJson<FilterCondition>(campaign.audienceCondition);
|
||||
if (!condition) {
|
||||
throw new HttpException(400, 'Audience condition is required for FILTERED audience type');
|
||||
}
|
||||
|
||||
// Use the SegmentService to build the where clause from the condition
|
||||
const segmentWhere = SegmentService.buildConditionClause(condition);
|
||||
const segmentWhere = await SegmentService.buildConditionClause(condition);
|
||||
|
||||
return {
|
||||
...baseWhere,
|
||||
@@ -783,8 +846,20 @@ export class CampaignService {
|
||||
throw new HttpException(404, 'Segment not found');
|
||||
}
|
||||
|
||||
const condition = segment.condition as unknown as FilterCondition;
|
||||
const segmentWhere = SegmentService.buildConditionClause(condition);
|
||||
if (segment.type === 'STATIC') {
|
||||
return {
|
||||
...baseWhere,
|
||||
segmentMemberships: {
|
||||
some: {
|
||||
segmentId,
|
||||
exitedAt: null,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const condition = fromPrismaJson<FilterCondition>(segment.condition);
|
||||
const segmentWhere = await SegmentService.buildConditionClause(condition);
|
||||
|
||||
return {
|
||||
...baseWhere,
|
||||
|
||||
@@ -1,17 +1,11 @@
|
||||
import {type Contact, Prisma} from '@plunk/db';
|
||||
import type {FilterCondition, FilterGroup} from '@plunk/types';
|
||||
import type {CursorPaginatedResponse, FilterCondition, FilterGroup} from '@plunk/types';
|
||||
import {toPrismaJson} from '@plunk/types';
|
||||
|
||||
import {prisma} from '../database/prisma.js';
|
||||
import {HttpException} from '../exceptions/index.js';
|
||||
import {EventService} from './EventService.js';
|
||||
|
||||
export interface PaginatedContacts {
|
||||
contacts: Contact[];
|
||||
total: number;
|
||||
cursor?: string;
|
||||
hasMore: boolean;
|
||||
}
|
||||
|
||||
export class ContactService {
|
||||
/**
|
||||
* Get all contacts for a project with cursor-based pagination
|
||||
@@ -22,7 +16,7 @@ export class ContactService {
|
||||
limit = 20,
|
||||
cursor?: string,
|
||||
search?: string,
|
||||
): Promise<PaginatedContacts> {
|
||||
): Promise<CursorPaginatedResponse<Contact>> {
|
||||
const where: Prisma.ContactWhereInput = {
|
||||
projectId,
|
||||
...(search
|
||||
@@ -57,7 +51,7 @@ export class ContactService {
|
||||
const total = !cursor ? await prisma.contact.count({where}) : 0;
|
||||
|
||||
return {
|
||||
contacts: results,
|
||||
data: results,
|
||||
total,
|
||||
cursor: nextCursor,
|
||||
hasMore,
|
||||
@@ -82,6 +76,23 @@ export class ContactService {
|
||||
return contact;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bulk-check which emails exist in the project — single query, safe for up to 500 addresses.
|
||||
*/
|
||||
public static async lookup(
|
||||
projectId: string,
|
||||
emails: string[],
|
||||
): Promise<{found: string[]; notFound: string[]}> {
|
||||
const rows = await prisma.contact.findMany({
|
||||
where: {projectId, email: {in: emails, mode: 'insensitive'}},
|
||||
select: {email: true},
|
||||
});
|
||||
const foundSet = new Set(rows.map(r => r.email.toLowerCase()));
|
||||
const found = emails.filter(e => foundSet.has(e.toLowerCase()));
|
||||
const notFound = emails.filter(e => !foundSet.has(e.toLowerCase()));
|
||||
return {found, notFound};
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a contact by email (returns null if not found)
|
||||
*/
|
||||
@@ -124,6 +135,47 @@ export class ContactService {
|
||||
* Update a contact
|
||||
* Uses unique constraint violation to check for duplicates (more efficient)
|
||||
*/
|
||||
/**
|
||||
* Merge an incoming partial data object into existing contact data.
|
||||
* - `null` value on a key deletes that key
|
||||
* - empty strings are ignored
|
||||
* - reserved/system-generated keys are silently filtered
|
||||
* - `{value, persistent: false}` entries are skipped (non-persistent)
|
||||
*/
|
||||
private static mergeContactData(
|
||||
existing: Prisma.JsonValue | null,
|
||||
incoming: Record<string, unknown>,
|
||||
): Record<string, unknown> {
|
||||
const merged: Record<string, unknown> =
|
||||
existing && typeof existing === 'object' && !Array.isArray(existing) ? {...(existing as Record<string, unknown>)} : {};
|
||||
|
||||
const reservedFields = ['plunk_id', 'plunk_email', 'id', 'email', 'unsubscribeUrl', 'subscribeUrl', 'manageUrl'];
|
||||
|
||||
for (const [key, value] of Object.entries(incoming)) {
|
||||
if (reservedFields.includes(key)) continue;
|
||||
if (value === '') continue;
|
||||
if (value === null) {
|
||||
delete merged[key];
|
||||
continue;
|
||||
}
|
||||
if (key === 'locale' && typeof value !== 'string') {
|
||||
throw new HttpException(400, 'Locale must be a string');
|
||||
}
|
||||
if (
|
||||
typeof value === 'object' &&
|
||||
value !== null &&
|
||||
'value' in value &&
|
||||
'persistent' in value &&
|
||||
(value as {persistent: unknown}).persistent === false
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
merged[key] = value;
|
||||
}
|
||||
|
||||
return merged;
|
||||
}
|
||||
|
||||
public static async update(
|
||||
projectId: string,
|
||||
contactId: string,
|
||||
@@ -138,7 +190,14 @@ export class ContactService {
|
||||
updateData.email = data.email;
|
||||
}
|
||||
if (data.data !== undefined) {
|
||||
updateData.data = data.data === null ? Prisma.JsonNull : data.data;
|
||||
if (data.data === null) {
|
||||
updateData.data = Prisma.JsonNull;
|
||||
} else if (typeof data.data === 'object' && !Array.isArray(data.data)) {
|
||||
const merged = ContactService.mergeContactData(existing.data, data.data as Record<string, unknown>);
|
||||
updateData.data = Object.keys(merged).length > 0 ? toPrismaJson(merged) : Prisma.JsonNull;
|
||||
} else {
|
||||
throw new HttpException(400, 'data must be an object');
|
||||
}
|
||||
}
|
||||
if (data.subscribed !== undefined) {
|
||||
updateData.subscribed = data.subscribed;
|
||||
@@ -204,6 +263,7 @@ export class ContactService {
|
||||
email: string,
|
||||
data?: Record<string, unknown>,
|
||||
subscribed?: boolean,
|
||||
defaultSubscribed: boolean = true,
|
||||
): Promise<Contact> {
|
||||
// Find existing contact
|
||||
const existing = await prisma.contact.findFirst({
|
||||
@@ -213,72 +273,56 @@ export class ContactService {
|
||||
},
|
||||
});
|
||||
|
||||
// Process data to merge with existing data
|
||||
let mergedData: Record<string, unknown> = {};
|
||||
|
||||
if (existing?.data && typeof existing.data === 'object' && !Array.isArray(existing.data)) {
|
||||
// Start with existing data
|
||||
mergedData = {...existing.data};
|
||||
}
|
||||
|
||||
// Merge new data (if provided)
|
||||
if (data) {
|
||||
for (const [key, value] of Object.entries(data)) {
|
||||
// Skip reserved fields
|
||||
if (key === 'plunk_id' || key === 'plunk_email') {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Handle non-persistent data format: { value: "...", persistent: false }
|
||||
if (
|
||||
typeof value === 'object' &&
|
||||
value !== null &&
|
||||
'value' in value &&
|
||||
'persistent' in value &&
|
||||
value.persistent === false
|
||||
) {
|
||||
// Non-persistent fields are not stored in contact data
|
||||
// They would be used only for the current operation (like email template rendering)
|
||||
continue;
|
||||
}
|
||||
|
||||
// Store the value
|
||||
mergedData[key] = value;
|
||||
}
|
||||
}
|
||||
const mergedData = ContactService.mergeContactData(existing?.data ?? null, data ?? {});
|
||||
|
||||
if (existing) {
|
||||
// Track subscription status change
|
||||
const isSubscriptionChanging = subscribed !== undefined && existing.subscribed !== subscribed;
|
||||
const wasSubscribed = existing.subscribed;
|
||||
|
||||
const updated = await prisma.contact.update({
|
||||
where: {id: existing.id},
|
||||
data: {
|
||||
data: Object.keys(mergedData).length > 0 ? (mergedData as Prisma.InputJsonValue) : Prisma.JsonNull,
|
||||
...(subscribed !== undefined ? {subscribed} : {}),
|
||||
},
|
||||
});
|
||||
try {
|
||||
const updated = await prisma.contact.update({
|
||||
where: {id: existing.id},
|
||||
data: {
|
||||
data: Object.keys(mergedData).length > 0 ? toPrismaJson(mergedData) : Prisma.JsonNull,
|
||||
...(subscribed !== undefined ? {subscribed} : {}),
|
||||
},
|
||||
});
|
||||
|
||||
// Track subscription event if status changed
|
||||
if (isSubscriptionChanging) {
|
||||
if (subscribed && !wasSubscribed) {
|
||||
await EventService.trackEvent(projectId, 'contact.subscribed', updated.id);
|
||||
} else if (!subscribed && wasSubscribed) {
|
||||
await EventService.trackEvent(projectId, 'contact.unsubscribed', updated.id);
|
||||
// Track subscription event if status changed
|
||||
if (isSubscriptionChanging) {
|
||||
if (subscribed && !wasSubscribed) {
|
||||
await EventService.trackEvent(projectId, 'contact.subscribed', updated.id);
|
||||
} else if (!subscribed && wasSubscribed) {
|
||||
await EventService.trackEvent(projectId, 'contact.unsubscribed', updated.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return updated;
|
||||
return updated;
|
||||
} catch (error) {
|
||||
// Provide helpful error message for database/validation issues
|
||||
throw new HttpException(
|
||||
500,
|
||||
`Failed to update contact: ${error instanceof Error ? error.message : 'Unknown error'}`,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
return prisma.contact.create({
|
||||
data: {
|
||||
projectId,
|
||||
email,
|
||||
data: Object.keys(mergedData).length > 0 ? (mergedData as Prisma.InputJsonValue) : Prisma.JsonNull,
|
||||
subscribed: subscribed ?? true,
|
||||
},
|
||||
});
|
||||
try {
|
||||
return await prisma.contact.create({
|
||||
data: {
|
||||
projectId,
|
||||
email,
|
||||
data: Object.keys(mergedData).length > 0 ? toPrismaJson(mergedData) : Prisma.JsonNull,
|
||||
subscribed: subscribed ?? defaultSubscribed,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
// Provide helpful error message for database/validation issues
|
||||
throw new HttpException(
|
||||
500,
|
||||
`Failed to create contact: ${error instanceof Error ? error.message : 'Unknown error'}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -297,11 +341,18 @@ export class ContactService {
|
||||
Object.assign(mergedData, contact.data);
|
||||
}
|
||||
|
||||
// Explicitly expose locale as a predefined field (available in templates)
|
||||
// This ensures locale is always accessible even if not in contact.data
|
||||
if (mergedData.locale === undefined) {
|
||||
mergedData.locale = null;
|
||||
}
|
||||
|
||||
// Add temporary (non-persistent) data
|
||||
if (temporaryData) {
|
||||
for (const [key, value] of Object.entries(temporaryData)) {
|
||||
// Skip reserved fields
|
||||
if (key === 'plunk_id' || key === 'plunk_email') {
|
||||
// Skip reserved system-generated fields
|
||||
const reservedFields = ['plunk_id', 'plunk_email', 'email', 'unsubscribeUrl', 'subscribeUrl', 'manageUrl'];
|
||||
if (reservedFields.includes(key)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -339,6 +390,25 @@ export class ContactService {
|
||||
return contact;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get project by contact ID
|
||||
* Used to fetch project settings for public endpoints
|
||||
*/
|
||||
public static async getProjectByContactId(contactId: string): Promise<{language: string} | null> {
|
||||
const contact = await prisma.contact.findUnique({
|
||||
where: {id: contactId},
|
||||
select: {
|
||||
project: {
|
||||
select: {
|
||||
language: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return contact?.project || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* PUBLIC: Subscribe a contact
|
||||
*/
|
||||
@@ -635,6 +705,99 @@ export class ContactService {
|
||||
return {deletedFrom: result};
|
||||
}
|
||||
|
||||
/**
|
||||
* Bulk subscribe contacts
|
||||
* Updates multiple contacts to subscribed=true in batches.
|
||||
* `updated` = contacts flipped from unsubscribed to subscribed.
|
||||
* `unchanged` = contacts that were already subscribed (no-op, not a failure).
|
||||
*/
|
||||
public static async bulkSubscribe(
|
||||
projectId: string,
|
||||
contactIds: string[],
|
||||
): Promise<{updated: number; unchanged: number}> {
|
||||
const contacts = await prisma.contact.findMany({
|
||||
where: {id: {in: contactIds}, projectId},
|
||||
select: {id: true, subscribed: true},
|
||||
});
|
||||
|
||||
if (contacts.length === 0) {
|
||||
return {updated: 0, unchanged: 0};
|
||||
}
|
||||
|
||||
const unsubscribedIds = contacts.filter(c => !c.subscribed).map(c => c.id);
|
||||
const unchanged = contacts.length - unsubscribedIds.length;
|
||||
|
||||
if (unsubscribedIds.length === 0) {
|
||||
return {updated: 0, unchanged};
|
||||
}
|
||||
|
||||
const result = await prisma.contact.updateMany({
|
||||
where: {id: {in: unsubscribedIds}, projectId},
|
||||
data: {subscribed: true},
|
||||
});
|
||||
|
||||
this.trackEventsSequentially(projectId, 'contact.subscribed', unsubscribedIds).catch(error => {
|
||||
if (process.env.NODE_ENV !== 'test') {
|
||||
console.error('[ContactService] Failed to track bulk subscribe events:', error);
|
||||
}
|
||||
});
|
||||
|
||||
return {updated: result.count, unchanged};
|
||||
}
|
||||
|
||||
/**
|
||||
* Bulk unsubscribe contacts.
|
||||
* `updated` = contacts flipped from subscribed to unsubscribed.
|
||||
* `unchanged` = contacts that were already unsubscribed (no-op, not a failure).
|
||||
*/
|
||||
public static async bulkUnsubscribe(
|
||||
projectId: string,
|
||||
contactIds: string[],
|
||||
): Promise<{updated: number; unchanged: number}> {
|
||||
const contacts = await prisma.contact.findMany({
|
||||
where: {id: {in: contactIds}, projectId},
|
||||
select: {id: true, subscribed: true},
|
||||
});
|
||||
|
||||
if (contacts.length === 0) {
|
||||
return {updated: 0, unchanged: 0};
|
||||
}
|
||||
|
||||
const subscribedIds = contacts.filter(c => c.subscribed).map(c => c.id);
|
||||
const unchanged = contacts.length - subscribedIds.length;
|
||||
|
||||
if (subscribedIds.length === 0) {
|
||||
return {updated: 0, unchanged};
|
||||
}
|
||||
|
||||
const result = await prisma.contact.updateMany({
|
||||
where: {id: {in: subscribedIds}, projectId},
|
||||
data: {subscribed: false},
|
||||
});
|
||||
|
||||
this.trackEventsSequentially(projectId, 'contact.unsubscribed', subscribedIds).catch(error => {
|
||||
if (process.env.NODE_ENV !== 'test') {
|
||||
console.error('[ContactService] Failed to track bulk unsubscribe events:', error);
|
||||
}
|
||||
});
|
||||
|
||||
return {updated: result.count, unchanged};
|
||||
}
|
||||
|
||||
/**
|
||||
* Bulk delete contacts
|
||||
*/
|
||||
public static async bulkDelete(projectId: string, contactIds: string[]): Promise<{deleted: number}> {
|
||||
const result = await prisma.contact.deleteMany({
|
||||
where: {
|
||||
id: {in: contactIds},
|
||||
projectId,
|
||||
},
|
||||
});
|
||||
|
||||
return {deleted: result.count};
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper: Check if a field is used in a filter condition (recursive)
|
||||
*/
|
||||
@@ -679,4 +842,28 @@ export class ContactService {
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Track events sequentially to avoid database deadlocks
|
||||
* Processes events one at a time with error handling
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private static async trackEventsSequentially(
|
||||
projectId: string,
|
||||
eventName: string,
|
||||
contactIds: string[],
|
||||
): Promise<void> {
|
||||
for (const contactId of contactIds) {
|
||||
try {
|
||||
await EventService.trackEvent(projectId, eventName, contactId);
|
||||
} catch (error) {
|
||||
// Log error but continue processing remaining events
|
||||
// Suppress logging in test environments to reduce noise from cleanup race conditions
|
||||
if (process.env.NODE_ENV !== 'test') {
|
||||
console.error(`[ContactService] Failed to track event ${eventName} for contact ${contactId}:`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,19 @@
|
||||
import React from 'react';
|
||||
import signale from 'signale';
|
||||
import {DomainUnverifiedEmail, DomainVerifiedEmail, sendPlatformEmail} from '@plunk/email';
|
||||
import {DASHBOARD_URI, LANDING_URI} from '../app/constants.js';
|
||||
import {prisma} from '../database/prisma.js';
|
||||
import {wrapRedis} from '../database/redis.js';
|
||||
import {redis, wrapRedis} from '../database/redis.js';
|
||||
import {HttpException} from '../exceptions/index.js';
|
||||
import {Keys} from './keys.js';
|
||||
import {MembershipService} from './MembershipService.js';
|
||||
import {NtfyService} from './NtfyService.js';
|
||||
import {getDomainVerificationAttributes, verifyDomain} from './SESService.js';
|
||||
import {
|
||||
deleteIdentity,
|
||||
disableFeedbackForwarding,
|
||||
getDomainVerificationAttributes,
|
||||
verifyDomain,
|
||||
} from './SESService.js';
|
||||
|
||||
export class DomainService {
|
||||
/**
|
||||
@@ -67,6 +77,43 @@ export class DomainService {
|
||||
|
||||
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
|
||||
if (attributes.status === 'Success' && !domain.verified) {
|
||||
const updatedDomain = await prisma.domain.update({
|
||||
@@ -79,8 +126,42 @@ 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
|
||||
await NtfyService.notifyDomainVerified(domain.domain, updatedDomain.project.name, updatedDomain.project.id);
|
||||
|
||||
// Send email notification about domain verified
|
||||
try {
|
||||
// Use SETNX to atomically check and set the flag (prevents race conditions)
|
||||
const cacheKey = Keys.Domain.verifiedEmail(domainId);
|
||||
const ttl = 604800; // 7 days
|
||||
|
||||
// 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 emails = members.map(m => m.email);
|
||||
if (emails.length > 0) {
|
||||
const template = React.createElement(DomainVerifiedEmail, {
|
||||
projectName: updatedDomain.project.name,
|
||||
projectId: updatedDomain.project.id,
|
||||
domain: domain.domain,
|
||||
dashboardUrl: DASHBOARD_URI,
|
||||
landingUrl: LANDING_URI,
|
||||
});
|
||||
await Promise.all(emails.map(email => sendPlatformEmail(email, 'Domain Verified Successfully', template)));
|
||||
}
|
||||
}
|
||||
} catch (emailError) {
|
||||
signale.error('[DOMAIN-EMAIL] Failed to send domain verified email:', emailError);
|
||||
}
|
||||
} else if (attributes.status !== 'Success' && domain.verified) {
|
||||
const updatedDomain = await prisma.domain.update({
|
||||
where: {id: domainId},
|
||||
@@ -93,7 +174,41 @@ export class DomainService {
|
||||
});
|
||||
|
||||
// Send notification about domain verification failed
|
||||
await NtfyService.notifyDomainVerificationFailed(domain.domain, updatedDomain.project.name, updatedDomain.project.id);
|
||||
await NtfyService.notifyDomainVerificationFailed(
|
||||
domain.domain,
|
||||
updatedDomain.project.name,
|
||||
updatedDomain.project.id,
|
||||
);
|
||||
|
||||
// Send email notification about domain verification failed
|
||||
try {
|
||||
// Use SETNX to atomically check and set the flag (prevents race conditions)
|
||||
const now = new Date();
|
||||
const year = now.getFullYear();
|
||||
const month = String(now.getMonth() + 1).padStart(2, '0');
|
||||
const cacheKey = Keys.Domain.unverifiedEmail(domainId, year, month);
|
||||
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) {
|
||||
const members = await MembershipService.getMembers(updatedDomain.project.id);
|
||||
const emails = members.map(m => m.email);
|
||||
if (emails.length > 0) {
|
||||
const template = React.createElement(DomainUnverifiedEmail, {
|
||||
projectName: updatedDomain.project.name,
|
||||
projectId: updatedDomain.project.id,
|
||||
domain: domain.domain,
|
||||
dashboardUrl: DASHBOARD_URI,
|
||||
landingUrl: LANDING_URI,
|
||||
});
|
||||
await Promise.all(emails.map(email => sendPlatformEmail(email, 'Domain Verification Failed', template)));
|
||||
}
|
||||
}
|
||||
} catch (emailError) {
|
||||
signale.error('[DOMAIN-EMAIL] Failed to send domain unverified email:', emailError);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -184,6 +299,28 @@ export class DomainService {
|
||||
|
||||
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
|
||||
await NtfyService.notifyDomainRemoved(domainName, domain.project.name, domain.project.id);
|
||||
|
||||
@@ -251,6 +388,49 @@ export class DomainService {
|
||||
return domain;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the registrable root domain (last two labels) from a domain name.
|
||||
* e.g. "mail.example.com" → "example.com", "example.com" → "example.com"
|
||||
*/
|
||||
private static rootDomain(domain: string): string {
|
||||
const parts = domain.split('.');
|
||||
return parts.length > 2 ? parts.slice(-2).join('.') : domain;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether the root domain of `domain` is owned by a disabled project.
|
||||
* Prevents subdomains from being added when the parent domain is flagged.
|
||||
*/
|
||||
public static async checkSubdomainOfDisabledRoot(
|
||||
domain: string,
|
||||
): Promise<{blocked: boolean; projectName?: string; projectId?: string}> {
|
||||
const root = this.rootDomain(domain);
|
||||
|
||||
// Only relevant when the submitted domain is actually a subdomain
|
||||
if (root === domain) {
|
||||
return {blocked: false};
|
||||
}
|
||||
|
||||
const rootDomainRecord = await prisma.domain.findFirst({
|
||||
where: {domain: root},
|
||||
include: {
|
||||
project: {
|
||||
select: {id: true, name: true, disabled: true},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (rootDomainRecord?.project.disabled) {
|
||||
return {
|
||||
blocked: true,
|
||||
projectName: rootDomainRecord.project.name,
|
||||
projectId: rootDomainRecord.project.id,
|
||||
};
|
||||
}
|
||||
|
||||
return {blocked: false};
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a domain is already linked to another project
|
||||
* Used when adding a new domain to verify if the user has access to the existing project
|
||||
@@ -258,15 +438,14 @@ export class DomainService {
|
||||
* @param userId User ID to check membership
|
||||
* @returns Object with exists flag and membership info
|
||||
*/
|
||||
public static async checkDomainOwnership(domain: string, userId: string) {
|
||||
public static async checkDomainOwnership(domain: string, userId?: string) {
|
||||
const existingDomain = await prisma.domain.findFirst({
|
||||
where: {domain},
|
||||
include: {
|
||||
project: {
|
||||
include: {
|
||||
members: {
|
||||
where: {userId},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -276,8 +455,20 @@ export class DomainService {
|
||||
return {exists: false};
|
||||
}
|
||||
|
||||
// Check if user is a member of the project that owns this domain
|
||||
const isMember = existingDomain.project.members.length > 0;
|
||||
let isMember = false;
|
||||
|
||||
if (userId) {
|
||||
const membership = await prisma.membership.findUnique({
|
||||
where: {
|
||||
userId_projectId: {
|
||||
userId,
|
||||
projectId: existingDomain.project.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
isMember = membership !== null;
|
||||
}
|
||||
|
||||
return {
|
||||
exists: true,
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import type {Contact, Email, Prisma, Project} from '@plunk/db';
|
||||
import {EmailSourceType, EmailStatus, TrackingMode} from '@plunk/db';
|
||||
import {toPrismaJson} from '@plunk/types';
|
||||
import signale from 'signale';
|
||||
|
||||
import {DASHBOARD_URI, LANDING_URI, STRIPE_ENABLED} from '../app/constants.js';
|
||||
import {prisma} from '../database/prisma.js';
|
||||
import {HttpException} from '../exceptions/index.js';
|
||||
import {renderTemplate} from '@plunk/shared';
|
||||
import {createTranslatorSync, renderTemplate} from '@plunk/shared';
|
||||
|
||||
import {BillingLimitService} from './BillingLimitService.js';
|
||||
import {DomainService} from './DomainService.js';
|
||||
@@ -17,6 +18,8 @@ interface Attachment {
|
||||
filename: string;
|
||||
content: string; // Base64 encoded
|
||||
contentType: string;
|
||||
contentId?: string;
|
||||
disposition?: 'attachment' | 'inline';
|
||||
}
|
||||
|
||||
interface SendEmailParams {
|
||||
@@ -34,6 +37,8 @@ interface SendEmailParams {
|
||||
campaignId?: string;
|
||||
workflowExecutionId?: string;
|
||||
workflowStepExecutionId?: string;
|
||||
recipientEmail?: string; // Optional custom recipient email (overrides contact.email)
|
||||
isTransactional?: boolean; // Override source type to TRANSACTIONAL (e.g. for transactional campaigns)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -91,8 +96,8 @@ export class EmailService {
|
||||
fromName: params.fromName,
|
||||
toName: params.toName,
|
||||
replyTo: params.replyTo,
|
||||
headers: params.headers ? (params.headers as Prisma.InputJsonValue) : undefined,
|
||||
attachments: params.attachments ? (params.attachments as unknown as Prisma.InputJsonValue) : undefined,
|
||||
headers: params.headers ? toPrismaJson(params.headers) : undefined,
|
||||
attachments: params.attachments ? toPrismaJson(params.attachments) : undefined,
|
||||
sourceType: EmailSourceType.TRANSACTIONAL,
|
||||
templateId: params.templateId,
|
||||
status: EmailStatus.PENDING,
|
||||
@@ -103,7 +108,7 @@ export class EmailService {
|
||||
await BillingLimitService.incrementUsage(params.projectId, EmailSourceType.TRANSACTIONAL);
|
||||
|
||||
// Queue email for sending
|
||||
await this.queueEmail(email.id);
|
||||
await this.queueEmail(email.id, EmailSourceType.TRANSACTIONAL);
|
||||
|
||||
return email;
|
||||
}
|
||||
@@ -112,10 +117,12 @@ export class EmailService {
|
||||
* Send a campaign email
|
||||
*/
|
||||
public static async sendCampaignEmail(params: SendEmailParams): Promise<Email> {
|
||||
// Check if template is transactional to determine source type
|
||||
// Check if campaign or template is transactional to determine source type
|
||||
let sourceType: EmailSourceType = EmailSourceType.CAMPAIGN;
|
||||
|
||||
if (params.templateId) {
|
||||
if (params.isTransactional) {
|
||||
sourceType = EmailSourceType.TRANSACTIONAL;
|
||||
} else if (params.templateId) {
|
||||
const template = await prisma.template.findUnique({
|
||||
where: {id: params.templateId},
|
||||
select: {type: true},
|
||||
@@ -152,8 +159,8 @@ export class EmailService {
|
||||
from: params.from,
|
||||
fromName: params.fromName,
|
||||
replyTo: params.replyTo,
|
||||
headers: params.headers ? (params.headers as Prisma.InputJsonValue) : undefined,
|
||||
attachments: params.attachments ? (params.attachments as unknown as Prisma.InputJsonValue) : undefined,
|
||||
headers: params.headers ? toPrismaJson(params.headers) : undefined,
|
||||
attachments: params.attachments ? toPrismaJson(params.attachments) : undefined,
|
||||
sourceType,
|
||||
templateId: params.templateId,
|
||||
campaignId: params.campaignId,
|
||||
@@ -165,7 +172,7 @@ export class EmailService {
|
||||
await BillingLimitService.incrementUsage(params.projectId, sourceType);
|
||||
|
||||
// Queue email for sending
|
||||
await this.queueEmail(email.id);
|
||||
await this.queueEmail(email.id, sourceType);
|
||||
|
||||
return email;
|
||||
}
|
||||
@@ -192,7 +199,8 @@ export class EmailService {
|
||||
|
||||
// Check subscription status for marketing emails
|
||||
// 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({
|
||||
where: {id: params.contactId},
|
||||
select: {subscribed: true},
|
||||
@@ -213,8 +221,8 @@ export class EmailService {
|
||||
from: params.from,
|
||||
fromName: params.fromName,
|
||||
replyTo: params.replyTo,
|
||||
headers: params.headers ? (params.headers as Prisma.InputJsonValue) : undefined,
|
||||
attachments: params.attachments ? (params.attachments as unknown as Prisma.InputJsonValue) : undefined,
|
||||
headers: params.headers ? toPrismaJson(params.headers) : undefined,
|
||||
attachments: params.attachments ? toPrismaJson(params.attachments) : undefined,
|
||||
sourceType,
|
||||
templateId: params.templateId,
|
||||
workflowExecutionId: params.workflowExecutionId,
|
||||
@@ -241,6 +249,12 @@ export class EmailService {
|
||||
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({
|
||||
data: {
|
||||
projectId: params.projectId,
|
||||
@@ -250,8 +264,8 @@ export class EmailService {
|
||||
from: params.from,
|
||||
fromName: params.fromName,
|
||||
replyTo: params.replyTo,
|
||||
headers: params.headers ? (params.headers as Prisma.InputJsonValue) : undefined,
|
||||
attachments: params.attachments ? (params.attachments as unknown as Prisma.InputJsonValue) : undefined,
|
||||
headers: Object.keys(emailHeaders).length > 0 ? toPrismaJson(emailHeaders) : undefined,
|
||||
attachments: params.attachments ? toPrismaJson(params.attachments) : undefined,
|
||||
sourceType,
|
||||
templateId: params.templateId,
|
||||
workflowExecutionId: params.workflowExecutionId,
|
||||
@@ -264,7 +278,7 @@ export class EmailService {
|
||||
await BillingLimitService.incrementUsage(params.projectId, sourceType);
|
||||
|
||||
// Queue email for sending
|
||||
await this.queueEmail(email.id);
|
||||
await this.queueEmail(email.id, sourceType);
|
||||
|
||||
return email;
|
||||
}
|
||||
@@ -279,9 +293,8 @@ export class EmailService {
|
||||
include: {
|
||||
contact: true,
|
||||
project: true,
|
||||
template: {
|
||||
select: {type: true},
|
||||
},
|
||||
template: {select: {type: true}},
|
||||
campaign: {select: {type: true}},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -332,6 +345,7 @@ export class EmailService {
|
||||
subject: email.subject,
|
||||
body: email.body,
|
||||
data: {
|
||||
id: email.contact.id,
|
||||
email: email.contact.email,
|
||||
...contactData,
|
||||
data: contactData,
|
||||
@@ -342,11 +356,15 @@ export class EmailService {
|
||||
});
|
||||
|
||||
// Compile HTML with unsubscribe footer and badge
|
||||
// TRANSACTIONAL and HEADLESS emails don't get the Plunk unsubscribe footer
|
||||
const compiledHtml = this.compile({
|
||||
content: formattedEmail.body,
|
||||
contact: email.contact,
|
||||
project: email.project,
|
||||
includeUnsubscribe: email.sourceType !== EmailSourceType.TRANSACTIONAL, // Don't add unsubscribe to transactional emails
|
||||
includeUnsubscribe:
|
||||
email.sourceType !== EmailSourceType.TRANSACTIONAL &&
|
||||
email.template?.type !== 'HEADLESS' &&
|
||||
email.campaign?.type !== 'HEADLESS',
|
||||
});
|
||||
|
||||
// Use explicit fromName if provided, otherwise fall back to project name
|
||||
@@ -359,10 +377,25 @@ export class EmailService {
|
||||
? (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'];
|
||||
}
|
||||
|
||||
// Parse attachments from JSON
|
||||
const 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;
|
||||
|
||||
// Determine tracking based on project settings and email type
|
||||
@@ -374,13 +407,13 @@ export class EmailService {
|
||||
name: fromName,
|
||||
email: fromEmail,
|
||||
},
|
||||
to: [email.contact.email],
|
||||
to: [recipientEmail],
|
||||
content: {
|
||||
subject: formattedEmail.subject,
|
||||
html: compiledHtml,
|
||||
},
|
||||
reply: email.replyTo || undefined,
|
||||
headers: customHeaders,
|
||||
headers: publicHeaders,
|
||||
attachments: attachments,
|
||||
tracking: shouldTrack,
|
||||
});
|
||||
@@ -502,6 +535,42 @@ export class EmailService {
|
||||
data: updateData,
|
||||
});
|
||||
|
||||
// Update campaign stats if applicable
|
||||
if (email.campaignId) {
|
||||
const campaignUpdate: Prisma.CampaignUpdateInput = {};
|
||||
|
||||
switch (eventType) {
|
||||
case 'delivered':
|
||||
campaignUpdate.deliveredCount = {increment: 1};
|
||||
break;
|
||||
|
||||
case 'opened':
|
||||
// Only increment unique opens to match getStats logic
|
||||
if (!email.openedAt) {
|
||||
campaignUpdate.openedCount = {increment: 1};
|
||||
}
|
||||
break;
|
||||
|
||||
case 'clicked':
|
||||
// Only increment unique clicks to match getStats logic
|
||||
if (!email.clickedAt) {
|
||||
campaignUpdate.clickedCount = {increment: 1};
|
||||
}
|
||||
break;
|
||||
|
||||
case 'bounced':
|
||||
campaignUpdate.bouncedCount = {increment: 1};
|
||||
break;
|
||||
}
|
||||
|
||||
if (Object.keys(campaignUpdate).length > 0) {
|
||||
await prisma.campaign.update({
|
||||
where: {id: email.campaignId},
|
||||
data: campaignUpdate,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Track event
|
||||
await prisma.event.create({
|
||||
data: {
|
||||
@@ -509,7 +578,7 @@ export class EmailService {
|
||||
contactId: email.contactId,
|
||||
emailId: email.id,
|
||||
name: `email.${eventType}`,
|
||||
data: metadata ? (metadata as Prisma.InputJsonValue) : undefined,
|
||||
data: metadata ? toPrismaJson(metadata) : undefined,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -530,10 +599,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: {...where, status: EmailStatus.SENT}}),
|
||||
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.CLICKED}}),
|
||||
prisma.email.count({where: {...where, status: EmailStatus.BOUNCED}}),
|
||||
@@ -544,6 +614,7 @@ export class EmailService {
|
||||
total,
|
||||
sent,
|
||||
delivered,
|
||||
received,
|
||||
opened,
|
||||
clicked,
|
||||
bounced,
|
||||
@@ -585,6 +656,382 @@ export class EmailService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Detects if HTML contains custom patterns that indicate it was written in the HTML editor
|
||||
* rather than the visual editor. Mirrors the same logic in apps/web/src/lib/emailStyles.ts.
|
||||
*
|
||||
* The TipTap editor loads StarterKit + TextAlign + Color + TextStyle + Link +
|
||||
* ResizableImage + VariableMention. TextStyle/Color/Link round-trip <span style="..."> and
|
||||
* <a style="..."> markup. This detection therefore PERMITS span + inline styles and only
|
||||
* REJECTS markup TipTap cannot represent (tables, divs, forms, embeds, custom attrs,
|
||||
* <style> blocks, etc).
|
||||
*/
|
||||
private static detectCustomHtmlPatterns(html: string): boolean {
|
||||
if (!html || html.trim() === '') return false;
|
||||
|
||||
const classMatches = html.matchAll(/class\s*=\s*["']([^"']*)["']/gi);
|
||||
let hasCustomClasses = false;
|
||||
for (const match of classMatches) {
|
||||
const classValue = match[1];
|
||||
if (!classValue) continue;
|
||||
const classes = classValue.split(/\s+/).filter((c: string) => c.length > 0);
|
||||
const allowedPrefixes = ['prose', 'variable-', 'email-image', 'ProseMirror', 'resizable-image', 'selected', 'resize-handle'];
|
||||
const hasDisallowedClass = classes.some((cls: string) => !allowedPrefixes.some((prefix: string) => cls.startsWith(prefix)));
|
||||
if (hasDisallowedClass) {
|
||||
hasCustomClasses = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Element-attribute-scoped regex; the leading [\s"'] guard prevents `id=` inside
|
||||
// href URLs (e.g. `?id=...`) from false-matching as an HTML id attribute.
|
||||
const hasCustomAttributes = /<[a-z][^>]*?[\s"'](?:data-|aria-|role=|id=)/i.test(html);
|
||||
|
||||
// Elements TipTap cannot round-trip with the currently-loaded extension set.
|
||||
// <span> is intentionally excluded -- TipTap's TextStyle extension handles it.
|
||||
const hasCustomElements =
|
||||
/<(?:div|section|article|header|footer|nav|aside|main|table|tr|td|th|tbody|thead|tfoot|colgroup|col|form|input|button|select|textarea|iframe|video|audio|svg|object|embed|details|summary|dialog)\b/i.test(
|
||||
html,
|
||||
);
|
||||
|
||||
const hasMediaQueries = /@media/i.test(html);
|
||||
const hasStyleTags = /<style[^>]*>/i.test(html);
|
||||
|
||||
return hasCustomClasses || hasCustomAttributes || hasCustomElements || hasMediaQueries || hasStyleTags;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps visual editor content with a full HTML document and prose styles.
|
||||
* Mirrors wrapEmailWithStyles() in apps/web/src/lib/emailStyles.ts so sent emails
|
||||
* match the preview modal exactly.
|
||||
*/
|
||||
private static wrapWithEmailStyles(htmlBody: string): string {
|
||||
return `<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<style>
|
||||
/* Base reset */
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 16px;
|
||||
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
||||
line-height: 1.5;
|
||||
color: #111827;
|
||||
}
|
||||
|
||||
/* Tailwind Typography (prose) base styles */
|
||||
.prose {
|
||||
color: #374151;
|
||||
max-width: 600px;
|
||||
}
|
||||
.prose [class~="lead"] {
|
||||
color: #4b5563;
|
||||
font-size: 1.25em;
|
||||
line-height: 1.6;
|
||||
margin-top: 1.2em;
|
||||
margin-bottom: 1.2em;
|
||||
}
|
||||
.prose a {
|
||||
color: #3b82f6;
|
||||
text-decoration: underline;
|
||||
font-weight: 500;
|
||||
}
|
||||
.prose strong {
|
||||
color: #111827;
|
||||
font-weight: 600;
|
||||
}
|
||||
.prose ol, .prose ul {
|
||||
margin-top: 1.25em;
|
||||
margin-bottom: 1.25em;
|
||||
padding-left: 1.625em;
|
||||
}
|
||||
.prose li {
|
||||
margin-top: 0.5em;
|
||||
margin-bottom: 0.5em;
|
||||
}
|
||||
.prose ol > li {
|
||||
padding-left: 0.375em;
|
||||
}
|
||||
.prose ul > li {
|
||||
padding-left: 0.375em;
|
||||
}
|
||||
.prose > ul > li p {
|
||||
margin-top: 0.75em;
|
||||
margin-bottom: 0.75em;
|
||||
}
|
||||
.prose > ul > li > *:first-child {
|
||||
margin-top: 1.25em;
|
||||
}
|
||||
.prose > ul > li > *:last-child {
|
||||
margin-bottom: 1.25em;
|
||||
}
|
||||
.prose > ol > li > *:first-child {
|
||||
margin-top: 1.25em;
|
||||
}
|
||||
.prose > ol > li > *:last-child {
|
||||
margin-bottom: 1.25em;
|
||||
}
|
||||
.prose ul ul, .prose ul ol, .prose ol ul, .prose ol ol {
|
||||
margin-top: 0.75em;
|
||||
margin-bottom: 0.75em;
|
||||
}
|
||||
.prose hr {
|
||||
border: none;
|
||||
border-top: 1px solid #e5e7eb;
|
||||
margin-top: 3em;
|
||||
margin-bottom: 3em;
|
||||
}
|
||||
.prose blockquote {
|
||||
font-weight: 500;
|
||||
font-style: italic;
|
||||
color: #111827;
|
||||
border-left-width: 0.25rem;
|
||||
border-left-color: #e5e7eb;
|
||||
quotes: "\\201C""\\201D""\\2018""\\2019";
|
||||
margin-top: 1.6em;
|
||||
margin-bottom: 1.6em;
|
||||
padding-left: 1em;
|
||||
}
|
||||
.prose h1 {
|
||||
color: #111827;
|
||||
font-weight: 800;
|
||||
font-size: 2.25em;
|
||||
margin-top: 0;
|
||||
margin-bottom: 0.8888889em;
|
||||
line-height: 1.1111111;
|
||||
}
|
||||
.prose h2 {
|
||||
color: #111827;
|
||||
font-weight: 700;
|
||||
font-size: 1.5em;
|
||||
margin-top: 2em;
|
||||
margin-bottom: 1em;
|
||||
line-height: 1.3333333;
|
||||
}
|
||||
.prose h3 {
|
||||
color: #111827;
|
||||
font-weight: 600;
|
||||
font-size: 1.25em;
|
||||
margin-top: 1.6em;
|
||||
margin-bottom: 0.6em;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.prose h4 {
|
||||
color: #111827;
|
||||
font-weight: 600;
|
||||
margin-top: 1.5em;
|
||||
margin-bottom: 0.5em;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.prose img {
|
||||
margin-top: 2em;
|
||||
margin-bottom: 2em;
|
||||
}
|
||||
.prose figure {
|
||||
margin-top: 2em;
|
||||
margin-bottom: 2em;
|
||||
}
|
||||
.prose figure > * {
|
||||
margin-top: 0;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.prose code {
|
||||
color: #111827;
|
||||
font-weight: 600;
|
||||
font-size: 0.875em;
|
||||
}
|
||||
.prose code::before {
|
||||
content: "\`";
|
||||
}
|
||||
.prose code::after {
|
||||
content: "\`";
|
||||
}
|
||||
.prose pre {
|
||||
color: #e5e7eb;
|
||||
background-color: #1f2937;
|
||||
overflow-x: auto;
|
||||
font-size: 0.875em;
|
||||
line-height: 1.7142857;
|
||||
margin-top: 1.7142857em;
|
||||
margin-bottom: 1.7142857em;
|
||||
border-radius: 0.375rem;
|
||||
padding-top: 0.8571429em;
|
||||
padding-right: 1.1428571em;
|
||||
padding-bottom: 0.8571429em;
|
||||
padding-left: 1.1428571em;
|
||||
}
|
||||
.prose pre code {
|
||||
background-color: transparent;
|
||||
border-width: 0;
|
||||
border-radius: 0;
|
||||
padding: 0;
|
||||
font-weight: 400;
|
||||
color: inherit;
|
||||
font-size: inherit;
|
||||
font-family: inherit;
|
||||
line-height: inherit;
|
||||
}
|
||||
.prose pre code::before {
|
||||
content: none;
|
||||
}
|
||||
.prose pre code::after {
|
||||
content: none;
|
||||
}
|
||||
.prose table {
|
||||
width: 100%;
|
||||
table-layout: auto;
|
||||
text-align: left;
|
||||
margin-top: 2em;
|
||||
margin-bottom: 2em;
|
||||
font-size: 0.875em;
|
||||
line-height: 1.7142857;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
.prose thead {
|
||||
border-bottom-width: 1px;
|
||||
border-bottom-color: #d1d5db;
|
||||
}
|
||||
.prose thead th {
|
||||
color: #111827;
|
||||
font-weight: 600;
|
||||
vertical-align: bottom;
|
||||
padding-right: 0.5714286em;
|
||||
padding-bottom: 0.5714286em;
|
||||
padding-left: 0.5714286em;
|
||||
}
|
||||
.prose tbody tr {
|
||||
border-bottom-width: 1px;
|
||||
border-bottom-color: #e5e7eb;
|
||||
}
|
||||
.prose tbody tr:last-child {
|
||||
border-bottom-width: 0;
|
||||
}
|
||||
.prose tbody td {
|
||||
vertical-align: top;
|
||||
padding-top: 0.5714286em;
|
||||
padding-right: 0.5714286em;
|
||||
padding-bottom: 0.5714286em;
|
||||
padding-left: 0.5714286em;
|
||||
}
|
||||
.prose p {
|
||||
margin-top: 1.25em;
|
||||
margin-bottom: 1.25em;
|
||||
}
|
||||
|
||||
/* prose-sm modifier */
|
||||
.prose-sm {
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.7142857;
|
||||
}
|
||||
.prose-sm p {
|
||||
margin-top: 1.1428571em;
|
||||
margin-bottom: 1.1428571em;
|
||||
}
|
||||
.prose-sm h1 {
|
||||
font-size: 2.1428571em;
|
||||
margin-top: 0;
|
||||
margin-bottom: 0.8em;
|
||||
line-height: 1.2;
|
||||
}
|
||||
.prose-sm h2 {
|
||||
font-size: 1.4285714em;
|
||||
margin-top: 1.6em;
|
||||
margin-bottom: 0.8em;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.prose-sm h3 {
|
||||
font-size: 1.2857143em;
|
||||
margin-top: 1.5555556em;
|
||||
margin-bottom: 0.4444444em;
|
||||
line-height: 1.5555556;
|
||||
}
|
||||
.prose-sm h4 {
|
||||
margin-top: 1.4285714em;
|
||||
margin-bottom: 0.5714286em;
|
||||
line-height: 1.4285714;
|
||||
}
|
||||
.prose-sm img {
|
||||
margin-top: 1.7142857em;
|
||||
margin-bottom: 1.7142857em;
|
||||
}
|
||||
.prose-sm ol, .prose-sm ul {
|
||||
margin-top: 1.1428571em;
|
||||
margin-bottom: 1.1428571em;
|
||||
padding-left: 1.5714286em;
|
||||
}
|
||||
.prose-sm li {
|
||||
margin-top: 0.2857143em;
|
||||
margin-bottom: 0.2857143em;
|
||||
}
|
||||
|
||||
/* max-w-none utility */
|
||||
.max-w-none {
|
||||
max-width: none;
|
||||
}
|
||||
|
||||
/* Custom editor styles */
|
||||
.variable-highlight, .variable-placeholder, .variable-mention {
|
||||
background-color: #dbeafe;
|
||||
color: #1e40af;
|
||||
padding: 2px 6px;
|
||||
border-radius: 3px;
|
||||
font-family: 'Courier New', monospace;
|
||||
font-size: 14px;
|
||||
display: inline;
|
||||
}
|
||||
|
||||
.prose table {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
margin: 16px 0;
|
||||
}
|
||||
|
||||
.prose th, .prose td {
|
||||
border: 1px solid #e5e7eb;
|
||||
padding: 8px 12px;
|
||||
text-align: left;
|
||||
min-width: 100px;
|
||||
}
|
||||
|
||||
.prose th {
|
||||
background-color: #f3f4f6;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.prose img {
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
display: block;
|
||||
margin: 16px 0;
|
||||
}
|
||||
|
||||
.prose .resizable-image-wrapper {
|
||||
display: block;
|
||||
margin: 16px 0;
|
||||
}
|
||||
|
||||
.prose .resizable-image-container {
|
||||
display: inline-block;
|
||||
position: relative;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.prose .resizable-image-container img {
|
||||
margin: 0;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="prose prose-sm max-w-none">
|
||||
${htmlBody}
|
||||
</div>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compile HTML email with optional unsubscribe footer and badge
|
||||
* Adds unsubscribe link and Plunk badge for free tier users (only when billing is enabled)
|
||||
@@ -600,22 +1047,43 @@ export class EmailService {
|
||||
project: Project;
|
||||
includeUnsubscribe?: boolean;
|
||||
}): string {
|
||||
let html = content;
|
||||
// Wrap visual editor content with prose styles so the sent email matches the preview modal.
|
||||
// Custom HTML (from the HTML editor) already carries its own styles and is used as-is.
|
||||
let html = this.detectCustomHtmlPatterns(content) ? content : this.wrapWithEmailStyles(content);
|
||||
|
||||
const unsubscribeHtml = includeUnsubscribe
|
||||
? `<table align="center" width="100%" style="max-width: 480px; width: 100%; margin-left: auto; margin-right: auto; font-family: Inter, ui-sans-serif, system-ui, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; border: 0; cellpadding: 0; cellspacing: 0;" role="presentation">
|
||||
? (() => {
|
||||
// Get contact-level locale (overrides project language)
|
||||
const contactLocale =
|
||||
contact.data &&
|
||||
typeof contact.data === 'object' &&
|
||||
!Array.isArray(contact.data) &&
|
||||
'locale' in contact.data &&
|
||||
typeof contact.data.locale === 'string'
|
||||
? contact.data.locale
|
||||
: null;
|
||||
|
||||
// Get translator for contact's locale or project's language
|
||||
const translator = createTranslatorSync(contactLocale || project.language || 'en');
|
||||
const unsubscribeText = translator.t('email.footer.unsubscribeText', {
|
||||
projectName: project.name,
|
||||
});
|
||||
const updatePreferencesText = translator.t('email.footer.updatePreferences');
|
||||
|
||||
return `<table align="center" width="100%" style="max-width: 480px; width: 100%; margin-left: auto; margin-right: auto; font-family: Inter, ui-sans-serif, system-ui, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; border: 0; cellpadding: 0; cellspacing: 0;" role="presentation">
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>
|
||||
<hr style="border: none; border-top: 1px solid #eaeaea; width: 100%; margin-top: 12px; margin-bottom: 12px;">
|
||||
<p style="font-size: 12px; line-height: 24px; margin: 16px 0; text-align: center; color: rgb(64, 64, 64);">
|
||||
You received this email because you agreed to receive emails from ${project.name}. If you no longer wish to receive emails like this, please
|
||||
<a href="${DASHBOARD_URI}/unsubscribe/${contact.id}">update your preferences</a>.
|
||||
${unsubscribeText}
|
||||
<a href="${DASHBOARD_URI}/unsubscribe/${contact.id}">${updatePreferencesText}</a>.
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>`
|
||||
</table>`;
|
||||
})()
|
||||
: '';
|
||||
|
||||
// Add Plunk badge if billing is enabled and project has no subscription (free tier)
|
||||
@@ -635,7 +1103,7 @@ export class EmailService {
|
||||
<tr>
|
||||
<td style="width:180px;">
|
||||
<a href="${LANDING_URI}?ref=badge" target="_blank">
|
||||
<img height="auto" src="https://cdn.useplunk.com/badge.png" style="border:0;display:block;outline:none;text-decoration:none;height:auto;width:100%;font-size:13px;" width="180" />
|
||||
<img alt="Powered by Plunk" height="auto" src="https://cdn.useplunk.com/badge.png" style="border:0;display:block;outline:none;text-decoration:none;height:auto;width:100%;font-size:13px;" width="180" />
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
@@ -669,7 +1137,7 @@ export class EmailService {
|
||||
* Queue an email for sending
|
||||
* Adds email to the BullMQ queue for processing by workers
|
||||
*/
|
||||
private static async queueEmail(emailId: string, delay?: number): Promise<void> {
|
||||
await QueueService.queueEmail(emailId, delay);
|
||||
private static async queueEmail(emailId: string, sourceType: EmailSourceType, delay?: number): Promise<void> {
|
||||
await QueueService.queueEmail(emailId, sourceType, delay);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
import {promises as dns} from 'dns';
|
||||
import {run} from '@zootools/email-spell-checker';
|
||||
import type {EmailVerificationResult} from '@plunk/types';
|
||||
import {redis} from '../database/redis.js';
|
||||
|
||||
const DISPOSABLE_DOMAINS_URL =
|
||||
'https://raw.githubusercontent.com/disposable-email-domains/disposable-email-domains/main/disposable_email_blocklist.conf';
|
||||
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)
|
||||
|
||||
// Known email forwarding/alias services
|
||||
const FORWARDING_DOMAINS = new Set([
|
||||
'privaterelay.appleid.com', // Apple Sign In
|
||||
'mozmail.com', // Firefox Relay
|
||||
'simplelogin.com', // SimpleLogin
|
||||
'simplelogin.fr',
|
||||
'simplelogin.co',
|
||||
'simplelogin.io',
|
||||
'aleeas.com',
|
||||
'slmail.me',
|
||||
'dralias.com',
|
||||
'8shield.net',
|
||||
'anonaddy.com', // Addy.io
|
||||
'anonaddy.me',
|
||||
'addy.io',
|
||||
'duck.com', // DuckDuckGo
|
||||
'33mail.com', // 33mail
|
||||
'33m.co',
|
||||
'passmail.com', // Proton Pass
|
||||
'passmail.net',
|
||||
'passinbox.com',
|
||||
'passfwd.com',
|
||||
'y.yo.fr',
|
||||
'opayq.com', // IronVest (formerly Blur)
|
||||
'cloak.id', // Cloaked
|
||||
'erine.email', // Erine
|
||||
'use.startmail.com', // StartMail
|
||||
]);
|
||||
|
||||
export class EmailVerificationService {
|
||||
private static disposableDomainsSet: Set<string> | null = null;
|
||||
private static personalDomainsSet: Set<string> | null = null;
|
||||
|
||||
/**
|
||||
* Verify an email address
|
||||
* - Checks for NS records (proves domain exists in DNS)
|
||||
* - 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 personal/free email providers (Gmail, Hotmail, etc.)
|
||||
* - Detects forwarding/alias email addresses
|
||||
* - Suggests corrections for common typos
|
||||
*/
|
||||
static async verifyEmail(email: string): Promise<EmailVerificationResult> {
|
||||
const result: EmailVerificationResult = {
|
||||
email,
|
||||
valid: true,
|
||||
isDisposable: false,
|
||||
isAlias: false,
|
||||
isTypo: false,
|
||||
isPlusAddressed: false,
|
||||
isPersonalEmail: false,
|
||||
domainExists: false,
|
||||
hasWebsite: false,
|
||||
hasMxRecords: false,
|
||||
reasons: [],
|
||||
};
|
||||
|
||||
// Extract domain from email
|
||||
const emailParts = email.split('@');
|
||||
if (emailParts.length !== 2) {
|
||||
result.valid = false;
|
||||
result.reasons.push('Invalid email format');
|
||||
return result;
|
||||
}
|
||||
|
||||
const domain = emailParts[1]!; // Safe to assert, we already validated length
|
||||
|
||||
// Check if email is from a disposable domain using GitHub list
|
||||
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
|
||||
result.isAlias = this.isForwardingDomain(domain);
|
||||
|
||||
// Check for plus addressing
|
||||
result.isPlusAddressed = emailParts[0]!.includes('+');
|
||||
|
||||
// Check for common typos and suggest corrections
|
||||
const typoCheck = run({email});
|
||||
if (typoCheck && typoCheck.address && typoCheck.address !== email) {
|
||||
result.suggestedEmail = typoCheck.full;
|
||||
result.reasons.push(`Possible typo detected, did you mean ${typoCheck.domain}?`);
|
||||
result.isTypo = true;
|
||||
}
|
||||
|
||||
// Step 1: Check NS records - proves the domain exists in DNS
|
||||
try {
|
||||
const nsRecords = await dns.resolveNs(domain);
|
||||
result.domainExists = nsRecords && nsRecords.length > 0;
|
||||
} catch {
|
||||
result.domainExists = false;
|
||||
result.valid = false;
|
||||
result.reasons.push('Domain does not exist (no nameservers found)');
|
||||
// If domain doesn't exist, no point checking MX/A records
|
||||
return result;
|
||||
}
|
||||
|
||||
// Step 2: Check MX records - required for receiving email
|
||||
try {
|
||||
const mxRecords = await dns.resolveMx(domain);
|
||||
result.hasMxRecords = mxRecords && mxRecords.length > 0;
|
||||
if (!result.hasMxRecords) {
|
||||
result.valid = false;
|
||||
result.reasons.push('Domain cannot receive email (no MX records found)');
|
||||
}
|
||||
} catch {
|
||||
result.hasMxRecords = false;
|
||||
result.valid = false;
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
// If no issues were found, add a success reason
|
||||
if (result.valid && result.reasons.length === 0) {
|
||||
result.reasons.push('Email appears to be valid');
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch and cache the disposable domains list from GitHub
|
||||
* Uses Redis for caching with 24-hour TTL
|
||||
* Falls back to in-memory cache if Redis fails
|
||||
*/
|
||||
private static async getDisposableDomains(): Promise<Set<string>> {
|
||||
// Return in-memory cache if available
|
||||
if (this.disposableDomainsSet) {
|
||||
return this.disposableDomainsSet;
|
||||
}
|
||||
|
||||
try {
|
||||
// Try to get from Redis cache first
|
||||
const cached = await redis.get(DISPOSABLE_DOMAINS_CACHE_KEY);
|
||||
if (cached) {
|
||||
const domains = JSON.parse(cached) as string[];
|
||||
this.disposableDomainsSet = new Set(domains);
|
||||
return this.disposableDomainsSet;
|
||||
}
|
||||
|
||||
// Fetch from GitHub if not in cache
|
||||
const response = await fetch(DISPOSABLE_DOMAINS_URL);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch disposable 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(DISPOSABLE_DOMAINS_CACHE_KEY, JSON.stringify(domains), 'EX', CACHE_TTL_SECONDS);
|
||||
|
||||
// Cache in memory
|
||||
this.disposableDomainsSet = new Set(domains);
|
||||
return this.disposableDomainsSet;
|
||||
} catch (error) {
|
||||
console.error('Error fetching disposable domains:', error);
|
||||
// Return empty set as fallback - don't block email verification
|
||||
return new Set<string>();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a domain is disposable
|
||||
*/
|
||||
private static async isDisposableDomain(domain: string): Promise<boolean> {
|
||||
const disposableDomains = await this.getDisposableDomains();
|
||||
return disposableDomains.has(domain.toLowerCase());
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a domain is a known forwarding/alias service
|
||||
*/
|
||||
private static isForwardingDomain(domain: string): boolean {
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
import type {Event} from '@plunk/db';
|
||||
import {Prisma} from '@plunk/db';
|
||||
import type {FilterCondition, FilterGroup} from '@plunk/types';
|
||||
import {toPrismaJson} from '@plunk/types';
|
||||
import signale from 'signale';
|
||||
|
||||
import {prisma} from '../database/prisma.js';
|
||||
import {redis} from '../database/redis.js';
|
||||
import {ValidationError} from '../exceptions/index.js';
|
||||
import {Keys} from './keys.js';
|
||||
|
||||
import {WorkflowExecutionService} from './WorkflowExecutionService.js';
|
||||
@@ -33,7 +33,7 @@ export class EventService {
|
||||
contactId,
|
||||
emailId,
|
||||
name: eventName,
|
||||
data: data ? (data as Prisma.InputJsonValue) : undefined,
|
||||
data: data ? toPrismaJson(data) : undefined,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -473,7 +473,7 @@ export class EventService {
|
||||
contactId,
|
||||
status: 'RUNNING',
|
||||
currentStepId: triggerStep.id,
|
||||
context: context ? (context as Prisma.InputJsonValue) : undefined,
|
||||
context: context ? toPrismaJson(context) : undefined,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,368 @@
|
||||
import type {Membership} from '@plunk/db';
|
||||
import type {DisabledProjectInfo, MemberWithEmail, OwnerInfo} from '@plunk/types';
|
||||
|
||||
import {prisma} from '../database/prisma.js';
|
||||
import {redis, REDIS_ONE_MINUTE, wrapRedis} from '../database/redis.js';
|
||||
import {HttpException} from '../exceptions/index.js';
|
||||
import {Keys} from './keys.js';
|
||||
|
||||
const FIVE_MINUTES_IN_SECONDS = 5 * 60;
|
||||
|
||||
/**
|
||||
* Service for managing project memberships
|
||||
* Centralizes all membership-related database queries with caching
|
||||
*/
|
||||
export class MembershipService {
|
||||
// ============================================
|
||||
// AUTHORIZATION METHODS (Cached)
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* Check if user has any access to a project (any role)
|
||||
* CACHED (1 min TTL) - called on every authenticated request
|
||||
*/
|
||||
public static async hasAccess(userId: string, projectId: string): Promise<boolean> {
|
||||
return wrapRedis(
|
||||
Keys.Membership.access(userId, projectId),
|
||||
async () => {
|
||||
const membership = await prisma.membership.findUnique({
|
||||
where: {
|
||||
userId_projectId: {
|
||||
userId,
|
||||
projectId,
|
||||
},
|
||||
},
|
||||
});
|
||||
return membership !== null;
|
||||
},
|
||||
REDIS_ONE_MINUTE,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if user has admin or owner access to a project
|
||||
* CACHED (1 min TTL) - called before write operations
|
||||
*/
|
||||
public static async hasAdminAccess(userId: string, projectId: string): Promise<boolean> {
|
||||
return wrapRedis(
|
||||
Keys.Membership.admin(userId, projectId),
|
||||
async () => {
|
||||
const membership = await prisma.membership.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
projectId,
|
||||
role: {
|
||||
in: ['ADMIN', 'OWNER'],
|
||||
},
|
||||
},
|
||||
});
|
||||
return membership !== null;
|
||||
},
|
||||
REDIS_ONE_MINUTE,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get user's membership with role info
|
||||
* CACHED (1 min TTL) - returns full membership or null
|
||||
*/
|
||||
public static async getMembership(userId: string, projectId: string): Promise<Membership | null> {
|
||||
return wrapRedis(
|
||||
Keys.Membership.full(userId, projectId),
|
||||
async () => {
|
||||
return prisma.membership.findUnique({
|
||||
where: {
|
||||
userId_projectId: {
|
||||
userId,
|
||||
projectId,
|
||||
},
|
||||
},
|
||||
});
|
||||
},
|
||||
REDIS_ONE_MINUTE,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Require membership or throw 404
|
||||
* Uses cached getMembership internally
|
||||
*/
|
||||
public static async requireAccess(userId: string, projectId: string): Promise<Membership> {
|
||||
const membership = await this.getMembership(userId, projectId);
|
||||
|
||||
if (!membership) {
|
||||
throw new HttpException(404, 'Project not found or you do not have access');
|
||||
}
|
||||
|
||||
return membership;
|
||||
}
|
||||
|
||||
/**
|
||||
* Require admin/owner access or throw 403
|
||||
* Uses cached hasAdminAccess internally
|
||||
*/
|
||||
public static async requireAdminAccess(userId: string, projectId: string): Promise<Membership> {
|
||||
const membership = await this.getMembership(userId, projectId);
|
||||
|
||||
if (!membership) {
|
||||
throw new HttpException(404, 'Project not found or you do not have access');
|
||||
}
|
||||
|
||||
if (membership.role !== 'ADMIN' && membership.role !== 'OWNER') {
|
||||
throw new HttpException(403, 'Insufficient permissions. Admin or owner access required.');
|
||||
}
|
||||
|
||||
return membership;
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// MEMBER LISTING (Not Cached - Dynamic Data)
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* Get all members of a project with user info
|
||||
* NOT CACHED - returns fresh data for member management UI
|
||||
*/
|
||||
public static async getMembers(projectId: string): Promise<MemberWithEmail[]> {
|
||||
const memberships = await prisma.membership.findMany({
|
||||
where: {
|
||||
projectId,
|
||||
},
|
||||
include: {
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: 'asc',
|
||||
},
|
||||
});
|
||||
|
||||
return memberships.map(m => ({
|
||||
userId: m.userId,
|
||||
email: m.user.email,
|
||||
role: m.role,
|
||||
createdAt: m.createdAt,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get project owner
|
||||
* CACHED (5 min TTL) - owner rarely changes
|
||||
*/
|
||||
public static async getOwner(projectId: string): Promise<OwnerInfo> {
|
||||
return wrapRedis(
|
||||
Keys.Membership.owner(projectId),
|
||||
async () => {
|
||||
const ownerMembership = await prisma.membership.findFirst({
|
||||
where: {
|
||||
projectId,
|
||||
role: 'OWNER',
|
||||
},
|
||||
include: {
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!ownerMembership) {
|
||||
throw new HttpException(404, 'Project owner not found');
|
||||
}
|
||||
|
||||
return {
|
||||
userId: ownerMembership.userId,
|
||||
email: ownerMembership.user.email,
|
||||
};
|
||||
},
|
||||
FIVE_MINUTES_IN_SECONDS,
|
||||
);
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// CRUD OPERATIONS (Invalidate Cache)
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* Add a member to a project
|
||||
* Invalidates cache for the project
|
||||
*/
|
||||
public static async addMember(projectId: string, userId: string, role: 'ADMIN' | 'MEMBER'): Promise<Membership> {
|
||||
// Check if membership already exists
|
||||
const existingMembership = await prisma.membership.findUnique({
|
||||
where: {
|
||||
userId_projectId: {
|
||||
userId,
|
||||
projectId,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (existingMembership) {
|
||||
throw new HttpException(409, 'User is already a member of this project');
|
||||
}
|
||||
|
||||
// Create new membership
|
||||
const newMembership = await prisma.membership.create({
|
||||
data: {
|
||||
userId,
|
||||
projectId,
|
||||
role,
|
||||
},
|
||||
});
|
||||
|
||||
// Invalidate cache
|
||||
await this.invalidateCache(projectId, userId);
|
||||
|
||||
return newMembership;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a member's role
|
||||
* Throws if trying to change OWNER role
|
||||
* Invalidates cache
|
||||
*/
|
||||
public static async updateRole(projectId: string, userId: string, newRole: 'ADMIN' | 'MEMBER'): Promise<Membership> {
|
||||
// Get existing membership
|
||||
const existingMembership = await prisma.membership.findUnique({
|
||||
where: {
|
||||
userId_projectId: {
|
||||
userId,
|
||||
projectId,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!existingMembership) {
|
||||
throw new HttpException(404, 'Membership not found');
|
||||
}
|
||||
|
||||
// Prevent changing OWNER role
|
||||
if (existingMembership.role === 'OWNER') {
|
||||
throw new HttpException(403, 'Cannot change the role of the project owner');
|
||||
}
|
||||
|
||||
// Update role
|
||||
const updatedMembership = await prisma.membership.update({
|
||||
where: {
|
||||
userId_projectId: {
|
||||
userId,
|
||||
projectId,
|
||||
},
|
||||
},
|
||||
data: {
|
||||
role: newRole,
|
||||
},
|
||||
});
|
||||
|
||||
// Invalidate cache
|
||||
await this.invalidateCache(projectId, userId);
|
||||
|
||||
return updatedMembership;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a member from a project
|
||||
* Throws if trying to remove OWNER
|
||||
* Invalidates cache
|
||||
*/
|
||||
public static async removeMember(projectId: string, userId: string): Promise<void> {
|
||||
// Get existing membership
|
||||
const existingMembership = await prisma.membership.findUnique({
|
||||
where: {
|
||||
userId_projectId: {
|
||||
userId,
|
||||
projectId,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!existingMembership) {
|
||||
throw new HttpException(404, 'Membership not found');
|
||||
}
|
||||
|
||||
// Prevent removing OWNER
|
||||
if (existingMembership.role === 'OWNER') {
|
||||
throw new HttpException(403, 'Cannot remove the project owner');
|
||||
}
|
||||
|
||||
// Delete membership
|
||||
await prisma.membership.delete({
|
||||
where: {
|
||||
userId_projectId: {
|
||||
userId,
|
||||
projectId,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Invalidate cache
|
||||
await this.invalidateCache(projectId, userId);
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// UTILITY METHODS
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* Check if user is member of any disabled project
|
||||
* NOT CACHED - security-critical check
|
||||
*/
|
||||
public static async userHasDisabledProject(userId: string): Promise<DisabledProjectInfo> {
|
||||
const disabledMemberships = await prisma.membership.findMany({
|
||||
where: {
|
||||
userId,
|
||||
project: {
|
||||
disabled: true,
|
||||
},
|
||||
},
|
||||
include: {
|
||||
project: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
hasDisabledProject: disabledMemberships.length > 0,
|
||||
disabledProjectNames: disabledMemberships.map(m => m.project.name),
|
||||
};
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// PRIVATE CACHE MANAGEMENT
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* Invalidate all caches for a project and user
|
||||
* Called after membership changes
|
||||
*/
|
||||
private static async invalidateCache(projectId: string, userId?: string): Promise<void> {
|
||||
const keysToDelete: string[] = [];
|
||||
|
||||
if (userId) {
|
||||
// Invalidate user-specific caches
|
||||
keysToDelete.push(
|
||||
Keys.Membership.access(userId, projectId),
|
||||
Keys.Membership.admin(userId, projectId),
|
||||
Keys.Membership.full(userId, projectId),
|
||||
);
|
||||
}
|
||||
|
||||
// Invalidate project-wide caches
|
||||
keysToDelete.push(Keys.Membership.owner(projectId));
|
||||
|
||||
// Delete all keys
|
||||
if (keysToDelete.length > 0) {
|
||||
await redis.del(...keysToDelete);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,98 +1,28 @@
|
||||
import signale from 'signale';
|
||||
|
||||
import {STRIPE_ENABLED, STRIPE_METER_EVENT_NAME} from '../app/constants.js';
|
||||
import {stripe} from '../app/stripe.js';
|
||||
import {STRIPE_ENABLED} from '../app/constants.js';
|
||||
import {QueueService} from './QueueService.js';
|
||||
|
||||
/**
|
||||
* Meter Service
|
||||
* Handles recording usage events to Stripe billing meters for pay-as-you-go pricing
|
||||
*/
|
||||
export class MeterService {
|
||||
/**
|
||||
* Record an email sent event to Stripe meter
|
||||
* This is used for usage-based billing where customers pay per email sent
|
||||
*
|
||||
* @param customerId - Stripe customer ID
|
||||
* @param value - Number of emails sent (default: 1)
|
||||
* @param idempotencyKey - Optional unique identifier to prevent duplicate recording
|
||||
*/
|
||||
public static async recordEmailSent(customerId: string, value = 1, idempotencyKey?: string): Promise<void> {
|
||||
// Skip if billing is disabled (self-hosted mode)
|
||||
if (!STRIPE_ENABLED || !stripe) {
|
||||
if (!STRIPE_ENABLED) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip if no customer ID (not subscribed)
|
||||
if (!customerId) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await stripe.billing.meterEvents.create({
|
||||
event_name: STRIPE_METER_EVENT_NAME,
|
||||
payload: {
|
||||
stripe_customer_id: customerId,
|
||||
value: value.toString(), // Must be a string
|
||||
},
|
||||
...(idempotencyKey && {identifier: idempotencyKey}),
|
||||
});
|
||||
|
||||
signale.debug(`[METER] Recorded ${value} email(s) sent for customer ${customerId}`);
|
||||
await QueueService.queueMeterEvent(customerId, value, idempotencyKey);
|
||||
} catch (error) {
|
||||
// Log error but don't throw - we don't want billing issues to break email sending
|
||||
signale.error('[METER] Failed to record email sent event:', error);
|
||||
|
||||
// If it's a rate limit error, we might want to retry
|
||||
if (error instanceof Error && error.message.includes('429')) {
|
||||
signale.warn('[METER] Rate limited - consider implementing queue-based meter recording');
|
||||
}
|
||||
signale.error('[METER] Failed to enqueue meter event:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Record multiple emails in a single batch (for campaign sending)
|
||||
* More efficient than individual calls when sending bulk emails
|
||||
*
|
||||
* @param customerId - Stripe customer ID
|
||||
* @param count - Number of emails sent in this batch
|
||||
* @param batchId - Unique identifier for this batch
|
||||
*/
|
||||
public static async recordEmailBatch(customerId: string, count: number, batchId: string): Promise<void> {
|
||||
if (count <= 0) return;
|
||||
|
||||
await this.recordEmailSent(customerId, count, `batch_${batchId}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current usage for a customer in the current billing period
|
||||
* Useful for displaying usage dashboards or implementing soft limits
|
||||
*
|
||||
* @param customerId - Stripe customer ID
|
||||
* @param meterId - The meter ID from Stripe dashboard
|
||||
* @param startTime - Start of period (Unix timestamp)
|
||||
* @param endTime - End of period (Unix timestamp)
|
||||
*/
|
||||
public static async getUsageSummary(
|
||||
meterId: string,
|
||||
customerId: string,
|
||||
startTime: number,
|
||||
endTime: number,
|
||||
): Promise<unknown> {
|
||||
if (!STRIPE_ENABLED || !stripe) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const summaries = await stripe.billing.meters.listEventSummaries(meterId, {
|
||||
customer: customerId,
|
||||
start_time: startTime,
|
||||
end_time: endTime,
|
||||
});
|
||||
|
||||
return summaries;
|
||||
} catch (error) {
|
||||
signale.error('[METER] Failed to get usage summary:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,40 +1,6 @@
|
||||
import {type NtfyNotification, NtfyPriority, NtfyTag} from '@plunk/types';
|
||||
import signale from 'signale';
|
||||
|
||||
/**
|
||||
* Priority levels for ntfy notifications
|
||||
* Based on ntfy.sh documentation
|
||||
*/
|
||||
export enum NtfyPriority {
|
||||
MIN = 1, // No vibration/sound, relegated to "Other notifications"
|
||||
LOW = 2, // No vibration/sound, hidden until drawer opened
|
||||
DEFAULT = 3, // Short vibration and sound (standard)
|
||||
HIGH = 4, // Long vibration, pop-over notification
|
||||
MAX = 5, // Long vibration bursts, pop-over notification
|
||||
}
|
||||
|
||||
/**
|
||||
* Tags for ntfy notifications (emoji shortcuts)
|
||||
*/
|
||||
export enum NtfyTag {
|
||||
WARNING = 'warning',
|
||||
ERROR = 'rotating_light',
|
||||
SUCCESS = 'white_check_mark',
|
||||
MONEY = 'money_with_wings',
|
||||
SHIELD = 'shield',
|
||||
ROCKET = 'rocket',
|
||||
BELL = 'bell',
|
||||
CHART = 'chart_with_upwards_trend',
|
||||
SKULL = 'skull',
|
||||
INFO = 'information_source',
|
||||
}
|
||||
|
||||
export interface NtfyNotification {
|
||||
title: string;
|
||||
message: string;
|
||||
priority?: NtfyPriority;
|
||||
tags?: NtfyTag[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Service for sending notifications via ntfy.sh
|
||||
* Supports configurable ntfy server URL via NTFY_URL environment variable
|
||||
@@ -204,6 +170,17 @@ export class NtfyService {
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify about project disabled due to payment failure
|
||||
*/
|
||||
public static async notifyProjectDisabledForPayment(projectName: string, projectId: string): Promise<void> {
|
||||
await this.sendUrgent(
|
||||
'Project Disabled - Payment Failed',
|
||||
`Project "${projectName}" (${projectId}) was automatically disabled due to a failed recurring payment`,
|
||||
[NtfyTag.WARNING, NtfyTag.MONEY, NtfyTag.ERROR],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify about successful invoice payment - MIN priority (routine)
|
||||
*/
|
||||
@@ -241,6 +218,18 @@ export class NtfyService {
|
||||
* Notify about security warning (non-critical)
|
||||
*/
|
||||
public static async notifySecurityWarning(projectName: string, projectId: string, warnings: string[]): Promise<void> {
|
||||
// Import redis at runtime to avoid circular dependencies
|
||||
const {redis} = await import('../database/redis.js');
|
||||
|
||||
const cacheKey = `ntfy:security:warning:${projectId}`;
|
||||
const ttl = 3600; // 1 hour
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
const warningText = warnings.join(', ');
|
||||
await this.sendDefault(
|
||||
'Security Warning',
|
||||
@@ -251,7 +240,7 @@ export class NtfyService {
|
||||
|
||||
/**
|
||||
* 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(
|
||||
projectName: string,
|
||||
@@ -262,63 +251,51 @@ export class NtfyService {
|
||||
// Import redis at runtime to avoid circular dependencies
|
||||
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 projectCountKey = `ntfy:bounce:count:${projectId}`;
|
||||
const projectListKey = `ntfy:bounce:projects`;
|
||||
const bounceListKey = `ntfy:bounce:latest`;
|
||||
|
||||
// Increment global counter
|
||||
const globalCount = await redis.incr(globalCountKey);
|
||||
|
||||
// Increment project-specific counter
|
||||
await redis.incr(projectCountKey);
|
||||
|
||||
// Add project to the set of projects with bounces (for tracking)
|
||||
await redis.sadd(projectListKey, projectId);
|
||||
// Store this bounce event in a list (keep latest 20)
|
||||
const bounceEvent = JSON.stringify({
|
||||
projectName,
|
||||
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)
|
||||
if (globalCount === 1) {
|
||||
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
|
||||
if (globalCount % 20 === 0) {
|
||||
// Get all projects with bounces
|
||||
const projectIds = await redis.smembers(projectListKey);
|
||||
// Get the latest 20 bounces
|
||||
const latestBounces = await redis.lrange(bounceListKey, 0, 19);
|
||||
|
||||
// Get bounce counts for each project
|
||||
const projectCounts: Array<{projectId: string; count: number; name: string}> = [];
|
||||
for (const pid of projectIds) {
|
||||
const count = await redis.get(`ntfy:bounce:count:${pid}`);
|
||||
if (count) {
|
||||
// Fetch project name from database
|
||||
const {prisma} = await import('../database/prisma.js');
|
||||
const project = await prisma.project.findUnique({
|
||||
where: {id: pid},
|
||||
select: {name: true},
|
||||
});
|
||||
// Parse and format the bounce events
|
||||
const bounceDetails = latestBounces
|
||||
.map(bounce => {
|
||||
try {
|
||||
const parsed = JSON.parse(bounce);
|
||||
return ` • ${parsed.recipientEmail} (${parsed.bounceType}) - ${parsed.projectName}`;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
|
||||
projectCounts.push({
|
||||
projectId: pid,
|
||||
count: parseInt(count, 10),
|
||||
name: project?.name || 'Unknown',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 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({
|
||||
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,
|
||||
tags: [NtfyTag.WARNING],
|
||||
});
|
||||
@@ -352,6 +329,19 @@ export class NtfyService {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify about failed signup attempt with invalid email - LOW priority
|
||||
*/
|
||||
public static async notifyFailedSignupAttempt(email: string, reasons: string[]): Promise<void> {
|
||||
const reasonText = reasons.join(', ');
|
||||
await this.send({
|
||||
title: 'Failed Signup - Invalid Email',
|
||||
message: `Signup attempt blocked for email: ${email}\nReasons: ${reasonText}`,
|
||||
priority: NtfyPriority.LOW,
|
||||
tags: [NtfyTag.WARNING, NtfyTag.SHIELD],
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify about new user account created via OAuth - LOW priority
|
||||
*/
|
||||
@@ -610,6 +600,18 @@ export class NtfyService {
|
||||
percentage: number,
|
||||
sourceType: string,
|
||||
): Promise<void> {
|
||||
// Import redis at runtime to avoid circular dependencies
|
||||
const {redis} = await import('../database/redis.js');
|
||||
|
||||
const cacheKey = `ntfy:billing:warning:${projectId}:${sourceType}`;
|
||||
const ttl = 86400; // 24 hours
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
await this.sendDefault(
|
||||
'Billing Limit Warning',
|
||||
`Email usage at ${Math.round(percentage)}% (${usage}/${limit}) for ${sourceType} in project "${projectName}" (${projectId})`,
|
||||
@@ -629,6 +631,18 @@ export class NtfyService {
|
||||
limit: number,
|
||||
sourceType: string,
|
||||
): Promise<void> {
|
||||
// Import redis at runtime to avoid circular dependencies
|
||||
const {redis} = await import('../database/redis.js');
|
||||
|
||||
const cacheKey = `ntfy:billing:exceeded:${projectId}:${sourceType}`;
|
||||
const ttl = 86400; // 24 hours
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
await this.sendUrgent(
|
||||
'Billing Limit Exceeded',
|
||||
`Email usage limit reached (${usage}/${limit}) for ${sourceType} in project "${projectName}" (${projectId}). Further emails are blocked.`,
|
||||
@@ -747,6 +761,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
|
||||
*/
|
||||
@@ -759,6 +799,28 @@ export class NtfyService {
|
||||
});
|
||||
}
|
||||
|
||||
public static async notifyEarlyFraudWarning(
|
||||
chargeId: string,
|
||||
fraudType: string,
|
||||
cardFingerprint: string | null,
|
||||
customerEmail: string | null,
|
||||
): Promise<void> {
|
||||
const details = [
|
||||
`Charge: ${chargeId}`,
|
||||
`Fraud type: ${fraudType}`,
|
||||
cardFingerprint ? `Card fingerprint: ${cardFingerprint}` : null,
|
||||
customerEmail ? `Customer: ${customerEmail}` : null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' | ');
|
||||
|
||||
await this.sendUrgent('Stripe Early Fraud Warning', `Refunded and blocklisted. ${details}`, [
|
||||
NtfyTag.SHIELD,
|
||||
NtfyTag.MONEY,
|
||||
NtfyTag.SKULL,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the ntfy service with the configured URL
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import {Keys} from './keys.js';
|
||||
import {wrapRedis} from '../database/redis.js';
|
||||
import {prisma} from '../database/prisma.js';
|
||||
|
||||
export class ProjectService {
|
||||
public static async id(id: string) {
|
||||
return wrapRedis(Keys.Project.id(id), async () => {
|
||||
return prisma.project.findUnique({where: {id}});
|
||||
});
|
||||
}
|
||||
|
||||
public static async secret(key: string) {
|
||||
return wrapRedis(Keys.Project.secret(key), async () => {
|
||||
return prisma.project.findUnique({
|
||||
where: {
|
||||
secret: key,
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public static async public(key: string) {
|
||||
return wrapRedis(Keys.Project.public(key), async () => {
|
||||
return prisma.project.findUnique({
|
||||
where: {
|
||||
public: key,
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,57 +1,24 @@
|
||||
import {CampaignStatus, EmailSourceType, EmailStatus} from '@plunk/db';
|
||||
import {type Job, Queue} from 'bullmq';
|
||||
import type {RedisOptions} from 'ioredis';
|
||||
import signale from 'signale';
|
||||
import type {
|
||||
ApiRequestCleanupJobData,
|
||||
BulkContactActionJobData,
|
||||
BulkContactActionSelector,
|
||||
CampaignBatchJobData,
|
||||
ContactImportJobData,
|
||||
DomainVerificationJobData,
|
||||
MeterEventJobData,
|
||||
ScheduledCampaignJobData,
|
||||
SegmentCountJobData,
|
||||
SendEmailJobData,
|
||||
WorkflowStepJobData,
|
||||
} from '@plunk/types';
|
||||
|
||||
import {REDIS_URL} from '../app/constants.js';
|
||||
import {prisma} from '../database/prisma.js';
|
||||
|
||||
/**
|
||||
* Queue Job Data Types
|
||||
*/
|
||||
|
||||
export interface SendEmailJobData {
|
||||
emailId: string;
|
||||
}
|
||||
|
||||
export interface CampaignBatchJobData {
|
||||
campaignId: string;
|
||||
batchNumber: number;
|
||||
offset: number;
|
||||
limit: number;
|
||||
cursor?: string; // For cursor-based pagination
|
||||
}
|
||||
|
||||
export interface WorkflowStepJobData {
|
||||
executionId: string;
|
||||
stepId: string;
|
||||
type?: 'process-step' | 'timeout'; // Job type for different handling
|
||||
stepExecutionId?: string; // For timeout jobs, reference to the step execution
|
||||
}
|
||||
|
||||
export interface ScheduledCampaignJobData {
|
||||
campaignId: string;
|
||||
}
|
||||
|
||||
export interface ContactImportJobData {
|
||||
projectId: string;
|
||||
csvData: string; // Base64 encoded CSV content
|
||||
filename: string;
|
||||
}
|
||||
|
||||
export interface SegmentCountJobData {
|
||||
projectId?: string; // Optional: if provided, only update this project's segments
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
|
||||
export interface DomainVerificationJobData {
|
||||
// Empty for now - processes all domains
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
|
||||
export interface ApiRequestCleanupJobData {
|
||||
// Empty - cleans up old API request logs
|
||||
}
|
||||
|
||||
/**
|
||||
* Queue Configuration
|
||||
*/
|
||||
@@ -181,20 +148,69 @@ export const apiRequestCleanupQueue = new Queue<ApiRequestCleanupJobData>('api-r
|
||||
},
|
||||
});
|
||||
|
||||
export const bulkContactQueue = new Queue<BulkContactActionJobData>('bulk-contact-actions', {
|
||||
connection: redisConnection,
|
||||
defaultJobOptions: {
|
||||
attempts: 2, // Limited retries for bulk operations
|
||||
backoff: {
|
||||
type: 'exponential',
|
||||
delay: 5000,
|
||||
},
|
||||
removeOnComplete: 50, // Keep last 50 completed bulk operations
|
||||
removeOnFail: 100, // Keep last 100 failed bulk operations
|
||||
},
|
||||
});
|
||||
|
||||
export const meterQueue = new Queue<MeterEventJobData>('meter', {
|
||||
connection: redisConnection,
|
||||
defaultJobOptions: {
|
||||
attempts: 10,
|
||||
backoff: {
|
||||
type: 'exponential',
|
||||
delay: 5000,
|
||||
},
|
||||
removeOnComplete: 5000,
|
||||
removeOnFail: 10000,
|
||||
},
|
||||
});
|
||||
|
||||
function emailPriorityFor(sourceType: EmailSourceType): number {
|
||||
switch (sourceType) {
|
||||
case EmailSourceType.TRANSACTIONAL:
|
||||
return 1;
|
||||
case EmailSourceType.WORKFLOW:
|
||||
return 5;
|
||||
case EmailSourceType.CAMPAIGN:
|
||||
return 10;
|
||||
default:
|
||||
return 5;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Queue Service - Centralized queue management
|
||||
*/
|
||||
export class QueueService {
|
||||
/**
|
||||
* Add email to queue for sending
|
||||
* Add email to queue for sending.
|
||||
*
|
||||
* Transactional emails jump the queue ahead of workflow and campaign sends
|
||||
* via BullMQ's priority (lower number = higher precedence). This prevents
|
||||
* latency-sensitive sends (login codes, password resets) from queuing behind
|
||||
* large campaign bursts on the shared `email` queue.
|
||||
*/
|
||||
public static async queueEmail(emailId: string, delay?: number): Promise<Job<SendEmailJobData>> {
|
||||
public static async queueEmail(
|
||||
emailId: string,
|
||||
sourceType: EmailSourceType,
|
||||
delay?: number,
|
||||
): Promise<Job<SendEmailJobData>> {
|
||||
return emailQueue.add(
|
||||
'send-email',
|
||||
{emailId},
|
||||
{
|
||||
delay, // Optional delay in milliseconds
|
||||
jobId: `email-${emailId}`, // Prevent duplicate jobs
|
||||
delay,
|
||||
jobId: `email-${emailId}`,
|
||||
priority: emailPriorityFor(sourceType),
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -305,14 +321,89 @@ export class QueueService {
|
||||
|
||||
/**
|
||||
* 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);
|
||||
|
||||
if (!job) {
|
||||
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 progress = job.progress;
|
||||
const returnValue = job.returnvalue;
|
||||
const failedReason = job.failedReason;
|
||||
|
||||
return {
|
||||
id: job.id,
|
||||
state,
|
||||
progress,
|
||||
result: returnValue,
|
||||
data: job.data,
|
||||
failedReason,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Queue a Stripe meter event for reliable delivery with retries
|
||||
*/
|
||||
public static async queueMeterEvent(
|
||||
customerId: string,
|
||||
value: number,
|
||||
idempotencyKey?: string,
|
||||
): Promise<Job<MeterEventJobData>> {
|
||||
return meterQueue.add(
|
||||
'record-meter-event',
|
||||
{customerId, value, idempotencyKey},
|
||||
{
|
||||
jobId: idempotencyKey ? `meter-${idempotencyKey}` : undefined,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Queue bulk contact action job
|
||||
*/
|
||||
public static async queueBulkContactAction(
|
||||
projectId: string,
|
||||
selector: BulkContactActionSelector,
|
||||
operation: 'subscribe' | 'unsubscribe' | 'delete',
|
||||
): Promise<Job<BulkContactActionJobData>> {
|
||||
return bulkContactQueue.add(
|
||||
'bulk-contact-action',
|
||||
{projectId, operation, selector},
|
||||
{
|
||||
jobId: `bulk-${operation}-${projectId}-${Date.now()}`,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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, projectId: string) {
|
||||
const job = await bulkContactQueue.getJob(jobId);
|
||||
|
||||
if (!job) {
|
||||
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 progress = job.progress;
|
||||
const returnValue = job.returnvalue;
|
||||
@@ -354,6 +445,8 @@ export class QueueService {
|
||||
segmentCountCounts,
|
||||
domainVerificationCounts,
|
||||
apiRequestCleanupCounts,
|
||||
bulkContactCounts,
|
||||
meterCounts,
|
||||
] = await Promise.all([
|
||||
emailQueue.getJobCounts('waiting', 'active', 'completed', 'failed', 'delayed'),
|
||||
campaignQueue.getJobCounts('waiting', 'active', 'completed', 'failed', 'delayed'),
|
||||
@@ -363,6 +456,8 @@ export class QueueService {
|
||||
segmentCountQueue.getJobCounts('waiting', 'active', 'completed', 'failed', 'delayed'),
|
||||
domainVerificationQueue.getJobCounts('waiting', 'active', 'completed', 'failed', 'delayed'),
|
||||
apiRequestCleanupQueue.getJobCounts('waiting', 'active', 'completed', 'failed', 'delayed'),
|
||||
bulkContactQueue.getJobCounts('waiting', 'active', 'completed', 'failed', 'delayed'),
|
||||
meterQueue.getJobCounts('waiting', 'active', 'completed', 'failed', 'delayed'),
|
||||
]);
|
||||
|
||||
return {
|
||||
@@ -374,6 +469,8 @@ export class QueueService {
|
||||
segmentCount: segmentCountCounts,
|
||||
domainVerification: domainVerificationCounts,
|
||||
apiRequestCleanup: apiRequestCleanupCounts,
|
||||
bulkContact: bulkContactCounts,
|
||||
meter: meterCounts,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -390,6 +487,8 @@ export class QueueService {
|
||||
segmentCountQueue.pause(),
|
||||
domainVerificationQueue.pause(),
|
||||
apiRequestCleanupQueue.pause(),
|
||||
bulkContactQueue.pause(),
|
||||
meterQueue.pause(),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -406,6 +505,8 @@ export class QueueService {
|
||||
segmentCountQueue.resume(),
|
||||
domainVerificationQueue.resume(),
|
||||
apiRequestCleanupQueue.resume(),
|
||||
bulkContactQueue.resume(),
|
||||
meterQueue.resume(),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -430,6 +531,10 @@ export class QueueService {
|
||||
segmentCountQueue.clean(gracePeriod * 7, 50, 'failed'),
|
||||
domainVerificationQueue.clean(gracePeriod, 10, 'completed'),
|
||||
domainVerificationQueue.clean(gracePeriod * 7, 50, 'failed'),
|
||||
bulkContactQueue.clean(gracePeriod, 50, 'completed'),
|
||||
bulkContactQueue.clean(gracePeriod * 7, 100, 'failed'),
|
||||
meterQueue.clean(gracePeriod * 30, 5000, 'completed'), // Keep 30 days for billing audit
|
||||
meterQueue.clean(gracePeriod * 30, 10000, 'failed'),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -498,6 +603,39 @@ export class QueueService {
|
||||
}
|
||||
}
|
||||
|
||||
// Mark every still-PENDING email for this project as FAILED. We just stripped
|
||||
// their queue jobs, so without this they'd sit as PENDING forever and any
|
||||
// campaign waiting on them would stay stuck in SENDING.
|
||||
const failed = await prisma.email.updateMany({
|
||||
where: {projectId, status: EmailStatus.PENDING},
|
||||
data: {status: EmailStatus.FAILED, error: 'Project is disabled'},
|
||||
});
|
||||
|
||||
if (failed.count > 0) {
|
||||
signale.info(`[QUEUE] Marked ${failed.count} pending emails as failed for project ${projectId}`);
|
||||
}
|
||||
|
||||
// Finalize any in-flight campaigns. With the orphaned PENDING emails now FAILED
|
||||
// (terminal), the campaign can move to SENT with a partial sentCount instead of
|
||||
// staying stuck in SENDING. Reconcile totalRecipients first since the batch
|
||||
// chain may have been cut short.
|
||||
const sendingCampaigns = await prisma.campaign.findMany({
|
||||
where: {projectId, status: CampaignStatus.SENDING},
|
||||
select: {id: true},
|
||||
});
|
||||
|
||||
if (sendingCampaigns.length > 0) {
|
||||
const {CampaignService} = await import('./CampaignService.js');
|
||||
for (const campaign of sendingCampaigns) {
|
||||
const actualEmailCount = await prisma.email.count({where: {campaignId: campaign.id}});
|
||||
await prisma.campaign.update({
|
||||
where: {id: campaign.id},
|
||||
data: {totalRecipients: actualEmailCount},
|
||||
});
|
||||
await CampaignService.finalizeIfDone(campaign.id);
|
||||
}
|
||||
}
|
||||
|
||||
signale.info(`[QUEUE] Finished cancelling jobs for project ${projectId}`);
|
||||
}
|
||||
|
||||
@@ -514,6 +652,8 @@ export class QueueService {
|
||||
segmentCountQueue.close(),
|
||||
domainVerificationQueue.close(),
|
||||
apiRequestCleanupQueue.close(),
|
||||
bulkContactQueue.close(),
|
||||
meterQueue.close(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
import {
|
||||
S3Client,
|
||||
PutObjectCommand,
|
||||
CreateBucketCommand,
|
||||
HeadBucketCommand,
|
||||
PutBucketPolicyCommand,
|
||||
PutObjectCommand,
|
||||
S3Client,
|
||||
} from '@aws-sdk/client-s3';
|
||||
import crypto from 'crypto';
|
||||
import signale from 'signale';
|
||||
|
||||
import {
|
||||
S3_ENDPOINT,
|
||||
S3_ACCESS_KEY_ID,
|
||||
S3_ACCESS_KEY_SECRET,
|
||||
S3_BUCKET,
|
||||
S3_PUBLIC_URL,
|
||||
S3_FORCE_PATH_STYLE,
|
||||
S3_ENABLED,
|
||||
S3_ENDPOINT,
|
||||
S3_FORCE_PATH_STYLE,
|
||||
S3_PUBLIC_URL,
|
||||
} from '../app/constants.js';
|
||||
|
||||
/**
|
||||
@@ -46,7 +46,6 @@ export async function initializeBucket(): Promise<void> {
|
||||
let bucketExists = true;
|
||||
|
||||
try {
|
||||
// Check if bucket exists
|
||||
await s3Client.send(
|
||||
new HeadBucketCommand({
|
||||
Bucket: S3_BUCKET,
|
||||
|
||||
@@ -6,9 +6,10 @@ import {
|
||||
AWS_SES_REGION,
|
||||
AWS_SES_SECRET_ACCESS_KEY,
|
||||
DASHBOARD_URI,
|
||||
MAIL_FROM_SUBDOMAIN,
|
||||
SES_CONFIGURATION_SET,
|
||||
SES_CONFIGURATION_SET_NO_TRACKING,
|
||||
TRACKING_TOGGLE_ENABLED
|
||||
TRACKING_TOGGLE_ENABLED,
|
||||
} from '../app/constants.js';
|
||||
|
||||
/**
|
||||
@@ -40,6 +41,8 @@ interface SendRawEmailParams {
|
||||
filename: string;
|
||||
content: string; // Base64 encoded
|
||||
contentType: string;
|
||||
contentId?: string;
|
||||
disposition?: 'attachment' | 'inline';
|
||||
}[]
|
||||
| null;
|
||||
tracking?: boolean;
|
||||
@@ -101,8 +104,13 @@ export async function sendRawEmail({
|
||||
}
|
||||
|
||||
// Generate unique boundaries for multipart messages
|
||||
const boundary = `----=_NextPart_${Math.random().toString(36).substring(2)}`;
|
||||
const mixedBoundary = attachments?.length ? `----=_MixedPart_${Math.random().toString(36).substring(2)}` : null;
|
||||
const altBoundary = `----=_AltPart_${Math.random().toString(36).substring(2)}`;
|
||||
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
|
||||
const toHeader = to
|
||||
@@ -118,49 +126,87 @@ export async function sendRawEmail({
|
||||
// Extract just email addresses for Destinations (SES requirement)
|
||||
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 the additional headers (custom headers + List-Unsubscribe), filtering
|
||||
// out empties so we never emit a blank line inside the header section.
|
||||
// Per RFC 5322 §2.1, a blank line terminates the header section, so any blank
|
||||
// line here would push subsequent headers (notably List-Unsubscribe) into the body.
|
||||
const extraHeaderLines = [
|
||||
...(headers ? Object.entries(headers).map(([key, value]) => `${key}: ${value}`) : []),
|
||||
...(unsubscribeHeader ? [unsubscribeHeader] : []),
|
||||
];
|
||||
const extraHeaders = extraHeaderLines.length > 0 ? `\n${extraHeaderLines.join('\n')}` : '';
|
||||
|
||||
// Build raw MIME message
|
||||
const rawMessage = `From: ${from.name} <${from.email}>
|
||||
let rawMessage = `From: ${from.name} <${from.email}>
|
||||
To: ${toHeader}
|
||||
Reply-To: ${reply || from.email}
|
||||
Subject: ${content.subject}
|
||||
MIME-Version: 1.0
|
||||
${
|
||||
mixedBoundary
|
||||
? `Content-Type: multipart/mixed; boundary="${mixedBoundary}"`
|
||||
: `Content-Type: multipart/alternative; boundary="${boundary}"`
|
||||
}
|
||||
${
|
||||
headers
|
||||
? Object.entries(headers)
|
||||
.map(([key, value]) => `${key}: ${value}`)
|
||||
.join('\n')
|
||||
: ''
|
||||
}
|
||||
${unsubscribeHeader}
|
||||
Content-Type: ${rootContentType}${extraHeaders}
|
||||
|
||||
${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-Transfer-Encoding: 7bit
|
||||
|
||||
${breakLongLines(content.html, 500)}
|
||||
--${boundary}--
|
||||
${
|
||||
attachments && attachments.length > 0
|
||||
? '\n' +
|
||||
attachments
|
||||
.map(
|
||||
attachment => `--${mixedBoundary}
|
||||
--${altBoundary}--
|
||||
`;
|
||||
|
||||
// Add inline attachments to the related container
|
||||
if (relatedBoundary) {
|
||||
const inlineAttachments = attachments?.filter(a => a.disposition === 'inline') ?? [];
|
||||
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-Transfer-Encoding: base64
|
||||
Content-Disposition: attachment; filename="${attachment.filename}"
|
||||
|
||||
${breakLongLines(attachment.content, 76, true)}`,
|
||||
)
|
||||
.join('\n')
|
||||
: ''
|
||||
}${mixedBoundary ? `\n--${mixedBoundary}--` : ''}`;
|
||||
${breakLongLines(attachment.content, 76, true)}`;
|
||||
}
|
||||
rawMessage += `\n--${mixedBoundary}--`;
|
||||
}
|
||||
|
||||
// Determine which configuration set to use
|
||||
// Only use NO_TRACKING if tracking toggle is enabled AND tracking is disabled
|
||||
@@ -205,10 +251,13 @@ export const verifyDomain = async (domain: string): Promise<string[]> => {
|
||||
// Verify DKIM for the domain
|
||||
const DKIM = await ses.verifyDomainDkim({Domain: domain});
|
||||
|
||||
// Set custom MAIL FROM domain (plunk.yourdomain.com)
|
||||
// Set custom MAIL FROM domain. The subdomain defaults to `plunk` and can be
|
||||
// overridden via the MAIL_FROM_SUBDOMAIN env var — useful when `plunk.<domain>`
|
||||
// is already in use for something else (e.g., a CNAME to a CDN), since the
|
||||
// MAIL FROM subdomain needs MX + TXT records that conflict with a CNAME.
|
||||
await ses.setIdentityMailFromDomain({
|
||||
Identity: domain,
|
||||
MailFromDomain: `plunk.${domain}`,
|
||||
MailFromDomain: `${MAIL_FROM_SUBDOMAIN}.${domain}`,
|
||||
});
|
||||
|
||||
return DKIM.DkimTokens ?? [];
|
||||
@@ -258,6 +307,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
|
||||
* @returns MaxSendRate (emails per second) or null if the call fails
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import crypto from 'crypto';
|
||||
|
||||
import {ProjectDisabledEmail, sendPlatformEmail} from '@plunk/email';
|
||||
import React from 'react';
|
||||
import signale from 'signale';
|
||||
@@ -5,31 +7,119 @@ import signale from 'signale';
|
||||
import {prisma} from '../database/prisma.js';
|
||||
import {redis} from '../database/redis.js';
|
||||
import {Keys} from './keys.js';
|
||||
import {MembershipService} from './MembershipService.js';
|
||||
import {NtfyService} from './NtfyService.js';
|
||||
import {QueueService} from './QueueService.js';
|
||||
import {AUTO_PROJECT_DISABLE, DASHBOARD_URI, LANDING_URI} from '../app/constants.js';
|
||||
import {
|
||||
AUTO_PROJECT_DISABLE,
|
||||
DASHBOARD_URI,
|
||||
LANDING_URI,
|
||||
OPENROUTER_API_KEY,
|
||||
OPENROUTER_MODEL,
|
||||
PHISHING_CONFIDENCE_THRESHOLD,
|
||||
PHISHING_CUMULATIVE_THRESHOLD,
|
||||
PHISHING_CUMULATIVE_WINDOW_MS,
|
||||
PHISHING_DETECTION_ENABLED,
|
||||
PHISHING_DETECTION_SAMPLE_RATE,
|
||||
} from '../app/constants.js';
|
||||
|
||||
/**
|
||||
* Security thresholds for bounce and complaint rates
|
||||
* These limits protect AWS SES reputation and prevent account suspension
|
||||
*/
|
||||
const SECURITY_THRESHOLDS = {
|
||||
// Minimum emails required before enforcing limits (prevents false positives)
|
||||
// Minimum emails required before enforcing rate-based limits (prevents false positives)
|
||||
MIN_EMAILS_FOR_ENFORCEMENT: 100,
|
||||
|
||||
// Bounce rate thresholds (hard bounces only)
|
||||
BOUNCE_7DAY_WARNING: 3,
|
||||
BOUNCE_7DAY_CRITICAL: 8,
|
||||
BOUNCE_ALLTIME_WARNING: 2,
|
||||
BOUNCE_ALLTIME_CRITICAL: 5,
|
||||
BOUNCE_7DAY_WARNING: 5,
|
||||
BOUNCE_7DAY_CRITICAL: 10,
|
||||
BOUNCE_ALLTIME_WARNING: 4,
|
||||
BOUNCE_ALLTIME_CRITICAL: 8,
|
||||
|
||||
// Complaint rate thresholds (spam reports)
|
||||
COMPLAINT_7DAY_WARNING: 0.05,
|
||||
COMPLAINT_7DAY_CRITICAL: 0.1,
|
||||
COMPLAINT_ALLTIME_WARNING: 0.02,
|
||||
COMPLAINT_ALLTIME_CRITICAL: 0.08,
|
||||
COMPLAINT_7DAY_WARNING: 0.075,
|
||||
COMPLAINT_7DAY_CRITICAL: 0.15,
|
||||
COMPLAINT_ALLTIME_WARNING: 0.03,
|
||||
COMPLAINT_ALLTIME_CRITICAL: 0.12,
|
||||
|
||||
// Minimum absolute counts (prevents small sample size false positives)
|
||||
// Both percentage AND absolute count must be exceeded to trigger rate-based checks
|
||||
MIN_BOUNCES_FOR_CRITICAL: 10,
|
||||
MIN_BOUNCES_FOR_WARNING: 5,
|
||||
MIN_COMPLAINTS_FOR_CRITICAL: 5,
|
||||
MIN_COMPLAINTS_FOR_WARNING: 3,
|
||||
|
||||
// === Absolute count ceilings (new projects only) ===
|
||||
// These trigger regardless of rate — catches new accounts blasting emails
|
||||
// before their bounce rate has caught up. Established projects rely on
|
||||
// rate-based checks only, since high absolute counts at high volume
|
||||
// (e.g. 100 bounces out of 10K) don't indicate abuse.
|
||||
//
|
||||
// Legitimate senders ramp up gradually; spammers blast immediately.
|
||||
NEW_PROJECT_AGE_DAYS: 30,
|
||||
NEW_PROJECT_BOUNCE_24H_CEILING_WARNING: 10,
|
||||
NEW_PROJECT_BOUNCE_24H_CEILING_CRITICAL: 25,
|
||||
NEW_PROJECT_BOUNCE_7DAY_CEILING_WARNING: 25,
|
||||
NEW_PROJECT_BOUNCE_7DAY_CEILING_CRITICAL: 50,
|
||||
NEW_PROJECT_COMPLAINT_24H_CEILING_WARNING: 3,
|
||||
NEW_PROJECT_COMPLAINT_24H_CEILING_CRITICAL: 7,
|
||||
NEW_PROJECT_COMPLAINT_7DAY_CEILING_WARNING: 10,
|
||||
NEW_PROJECT_COMPLAINT_7DAY_CEILING_CRITICAL: 20,
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Redis-based tracking for phishing detections per project
|
||||
* Tracks timestamp and confidence of recent phishing detections
|
||||
* Uses sorted sets for efficient time-based filtering
|
||||
*/
|
||||
interface PhishingDetection {
|
||||
timestamp: number;
|
||||
confidence: number;
|
||||
subject: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Track a phishing detection for cumulative analysis using Redis
|
||||
*/
|
||||
async function trackPhishingDetection(projectId: string, confidence: number, subject: string): Promise<void> {
|
||||
const now = Date.now();
|
||||
const key = `phishing:detections:${projectId}`;
|
||||
|
||||
// Store detection as sorted set member (score = timestamp)
|
||||
// Value is JSON with confidence and subject
|
||||
const detection: PhishingDetection = {timestamp: now, confidence, subject};
|
||||
await redis.zadd(key, now, JSON.stringify(detection));
|
||||
|
||||
// Remove detections outside the time window
|
||||
const cutoff = now - PHISHING_CUMULATIVE_WINDOW_MS;
|
||||
await redis.zremrangebyscore(key, '-inf', cutoff);
|
||||
|
||||
// Set TTL to window duration to auto-cleanup old keys
|
||||
await redis.expire(key, Math.ceil(PHISHING_CUMULATIVE_WINDOW_MS / 1000));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get count of recent phishing detections for a project from Redis
|
||||
*/
|
||||
async function getRecentPhishingCount(projectId: string): Promise<number> {
|
||||
const now = Date.now();
|
||||
const cutoff = now - PHISHING_CUMULATIVE_WINDOW_MS;
|
||||
const key = `phishing:detections:${projectId}`;
|
||||
|
||||
// Count detections within the time window
|
||||
const count = await redis.zcount(key, cutoff, '+inf');
|
||||
return count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear phishing detection history for a project (e.g., after disable)
|
||||
*/
|
||||
async function clearPhishingHistory(projectId: string): Promise<void> {
|
||||
const key = `phishing:detections:${projectId}`;
|
||||
await redis.del(key);
|
||||
}
|
||||
|
||||
interface RateData {
|
||||
total: number;
|
||||
bounces: number;
|
||||
@@ -42,15 +132,84 @@ interface SecurityStatus {
|
||||
projectId: string;
|
||||
isHealthy: boolean;
|
||||
shouldDisable: boolean;
|
||||
twentyFourHour: RateData;
|
||||
sevenDay: RateData;
|
||||
allTime: RateData;
|
||||
isNewProject: boolean;
|
||||
violations: string[];
|
||||
warnings: string[];
|
||||
}
|
||||
|
||||
const SNS_CERT_HOST_RE = /^sns\.[a-z0-9-]+\.amazonaws\.(com|cn)$/;
|
||||
const snsSigningCertCache = new Map<string, string>();
|
||||
|
||||
async function fetchSigningCert(certUrl: string): Promise<string> {
|
||||
const cached = snsSigningCertCache.get(certUrl);
|
||||
if (cached) return cached;
|
||||
|
||||
const response = await fetch(certUrl);
|
||||
if (!response.ok) throw new Error(`Failed to fetch SNS signing cert: ${response.statusText}`);
|
||||
|
||||
const pem = await response.text();
|
||||
snsSigningCertCache.set(certUrl, pem);
|
||||
return pem;
|
||||
}
|
||||
|
||||
function buildSnsStringToSign(message: Record<string, string>): string {
|
||||
const fields =
|
||||
message['Type'] === 'Notification'
|
||||
? ['Message', 'MessageId', 'Subject', 'Timestamp', 'TopicArn', 'Type']
|
||||
: ['Message', 'MessageId', 'SubscribeURL', 'Timestamp', 'Token', 'TopicArn', 'Type'];
|
||||
|
||||
return fields
|
||||
.filter(key => message[key] !== undefined)
|
||||
.map(key => `${key}\n${message[key]}\n`)
|
||||
.join('');
|
||||
}
|
||||
|
||||
export class SecurityService {
|
||||
private static readonly CACHE_TTL = 300; // 5 minutes
|
||||
|
||||
/**
|
||||
* Verify an AWS SNS message signature. Returns false if the cert URL is
|
||||
* untrusted, or the signature doesn't match.
|
||||
*/
|
||||
public static async verifySnsSignature(body: Record<string, string>): Promise<boolean> {
|
||||
try {
|
||||
const certUrl = body['SigningCertURL'];
|
||||
const signature = body['Signature'];
|
||||
|
||||
if (!certUrl || !signature) {
|
||||
signale.warn('[SNS] Missing SigningCertURL or Signature');
|
||||
return false;
|
||||
}
|
||||
|
||||
let parsedUrl: URL;
|
||||
try {
|
||||
parsedUrl = new URL(certUrl);
|
||||
} catch {
|
||||
signale.warn('[SNS] Unparseable SigningCertURL');
|
||||
return false;
|
||||
}
|
||||
|
||||
if (parsedUrl.protocol !== 'https:' || !SNS_CERT_HOST_RE.test(parsedUrl.hostname)) {
|
||||
signale.warn(`[SNS] Untrusted SigningCertURL host: ${parsedUrl.hostname}`);
|
||||
return false;
|
||||
}
|
||||
|
||||
const pem = await fetchSigningCert(certUrl);
|
||||
const stringToSign = buildSnsStringToSign(body);
|
||||
const algorithm = body['SignatureVersion'] === '2' ? 'RSA-SHA256' : 'RSA-SHA1';
|
||||
|
||||
const verifier = crypto.createVerify(algorithm);
|
||||
verifier.update(stringToSign, 'utf8');
|
||||
return verifier.verify(pem, signature, 'base64');
|
||||
} catch (err) {
|
||||
signale.error('[SNS] Signature verification error:', err);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get security status for a project (with caching)
|
||||
*/
|
||||
@@ -78,6 +237,13 @@ export class SecurityService {
|
||||
projectId,
|
||||
isHealthy: true,
|
||||
shouldDisable: false,
|
||||
twentyFourHour: {
|
||||
total: 0,
|
||||
bounces: 0,
|
||||
complaints: 0,
|
||||
bounceRate: 0,
|
||||
complaintRate: 0,
|
||||
},
|
||||
sevenDay: {
|
||||
total: 0,
|
||||
bounces: 0,
|
||||
@@ -92,6 +258,7 @@ export class SecurityService {
|
||||
bounceRate: 0,
|
||||
complaintRate: 0,
|
||||
},
|
||||
isNewProject: false,
|
||||
violations: [],
|
||||
warnings: [],
|
||||
};
|
||||
@@ -125,12 +292,20 @@ export class SecurityService {
|
||||
`[SECURITY] Project ${projectId} (${project.name}) has CRITICAL security violations but auto-disable is turned off:`,
|
||||
status.violations,
|
||||
);
|
||||
signale.info(
|
||||
`[SECURITY] 24-hour stats: ${status.twentyFourHour.bounces} bounces, ${status.twentyFourHour.complaints} complaints out of ${status.twentyFourHour.total} emails`,
|
||||
);
|
||||
signale.info(
|
||||
`[SECURITY] 7-day stats: ${status.sevenDay.bounces} bounces, ${status.sevenDay.complaints} complaints out of ${status.sevenDay.total} emails`,
|
||||
);
|
||||
signale.info(
|
||||
`[SECURITY] All-time stats: ${status.allTime.bounces} bounces, ${status.allTime.complaints} complaints out of ${status.allTime.total} emails`,
|
||||
);
|
||||
if (status.isNewProject) {
|
||||
signale.info(
|
||||
`[SECURITY] Project is under ${SECURITY_THRESHOLDS.NEW_PROJECT_AGE_DAYS} days old — stricter ceilings apply`,
|
||||
);
|
||||
}
|
||||
|
||||
// Send notification about critical security violations
|
||||
await NtfyService.notifySecurityWarning(project.name, projectId, status.violations);
|
||||
@@ -177,26 +352,7 @@ export class SecurityService {
|
||||
hasDisabledProject: boolean;
|
||||
disabledProjectNames: string[];
|
||||
}> {
|
||||
const disabledMemberships = await prisma.membership.findMany({
|
||||
where: {
|
||||
userId,
|
||||
project: {
|
||||
disabled: true,
|
||||
},
|
||||
},
|
||||
include: {
|
||||
project: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
hasDisabledProject: disabledMemberships.length > 0,
|
||||
disabledProjectNames: disabledMemberships.map(m => m.project.name),
|
||||
};
|
||||
return MembershipService.userHasDisabledProject(userId);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -212,11 +368,17 @@ export class SecurityService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a project's security metrics (for admin/dashboard display)
|
||||
* Get a project's security metrics (for dashboard display)
|
||||
* Does NOT expose internal thresholds — only computed health levels
|
||||
*/
|
||||
public static async getProjectSecurityMetrics(projectId: string): Promise<{
|
||||
status: SecurityStatus;
|
||||
thresholds: typeof SECURITY_THRESHOLDS;
|
||||
levels: {
|
||||
bounce7Day: 'healthy' | 'warning' | 'critical';
|
||||
bounceAllTime: 'healthy' | 'warning' | 'critical';
|
||||
complaint7Day: 'healthy' | 'warning' | 'critical';
|
||||
complaintAllTime: 'healthy' | 'warning' | 'critical';
|
||||
};
|
||||
isDisabled: boolean;
|
||||
}> {
|
||||
const [status, project] = await Promise.all([
|
||||
@@ -227,13 +389,55 @@ export class SecurityService {
|
||||
}),
|
||||
]);
|
||||
|
||||
// Strip internal details from the client-facing response:
|
||||
// - Replace detailed violation/warning messages (they contain exact thresholds)
|
||||
// - Remove 24-hour data and new project flag (reveals enforcement windows)
|
||||
const sanitizedStatus: SecurityStatus = {
|
||||
...status,
|
||||
twentyFourHour: {total: 0, bounces: 0, complaints: 0, bounceRate: 0, complaintRate: 0},
|
||||
isNewProject: false,
|
||||
violations: status.violations.map(() => 'Security threshold exceeded'),
|
||||
warnings: status.warnings.map(() => 'Approaching security threshold'),
|
||||
};
|
||||
|
||||
return {
|
||||
status,
|
||||
thresholds: SECURITY_THRESHOLDS,
|
||||
status: sanitizedStatus,
|
||||
levels: {
|
||||
bounce7Day: this.computeLevel(
|
||||
status.sevenDay.bounceRate,
|
||||
SECURITY_THRESHOLDS.BOUNCE_7DAY_WARNING,
|
||||
SECURITY_THRESHOLDS.BOUNCE_7DAY_CRITICAL,
|
||||
),
|
||||
bounceAllTime: this.computeLevel(
|
||||
status.allTime.bounceRate,
|
||||
SECURITY_THRESHOLDS.BOUNCE_ALLTIME_WARNING,
|
||||
SECURITY_THRESHOLDS.BOUNCE_ALLTIME_CRITICAL,
|
||||
),
|
||||
complaint7Day: this.computeLevel(
|
||||
status.sevenDay.complaintRate,
|
||||
SECURITY_THRESHOLDS.COMPLAINT_7DAY_WARNING,
|
||||
SECURITY_THRESHOLDS.COMPLAINT_7DAY_CRITICAL,
|
||||
),
|
||||
complaintAllTime: this.computeLevel(
|
||||
status.allTime.complaintRate,
|
||||
SECURITY_THRESHOLDS.COMPLAINT_ALLTIME_WARNING,
|
||||
SECURITY_THRESHOLDS.COMPLAINT_ALLTIME_CRITICAL,
|
||||
),
|
||||
},
|
||||
isDisabled: project?.disabled ?? false,
|
||||
};
|
||||
}
|
||||
|
||||
private static computeLevel(
|
||||
value: number,
|
||||
warningThreshold: number,
|
||||
criticalThreshold: number,
|
||||
): 'healthy' | 'warning' | 'critical' {
|
||||
if (value >= criticalThreshold) return 'critical';
|
||||
if (value >= warningThreshold) return 'warning';
|
||||
return 'healthy';
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate bounce and complaint rates for a project
|
||||
*/
|
||||
@@ -281,10 +485,21 @@ export class SecurityService {
|
||||
*/
|
||||
private static async calculateSecurityStatus(projectId: string): Promise<SecurityStatus> {
|
||||
const now = new Date();
|
||||
const oneDayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
|
||||
const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
|
||||
|
||||
// Get 7-day and all-time rates in parallel
|
||||
const [sevenDay, allTime] = await Promise.all([
|
||||
// Get project age to determine if stricter new-project thresholds apply
|
||||
const project = await prisma.project.findUnique({
|
||||
where: {id: projectId},
|
||||
select: {createdAt: true},
|
||||
});
|
||||
|
||||
const projectAgeDays = project ? (now.getTime() - project.createdAt.getTime()) / (1000 * 60 * 60 * 24) : Infinity;
|
||||
const isNewProject = projectAgeDays < SECURITY_THRESHOLDS.NEW_PROJECT_AGE_DAYS;
|
||||
|
||||
// Get 24-hour, 7-day and all-time rates in parallel
|
||||
const [twentyFourHour, sevenDay, allTime] = await Promise.all([
|
||||
this.calculateRates(projectId, oneDayAgo),
|
||||
this.calculateRates(projectId, sevenDaysAgo),
|
||||
this.calculateRates(projectId),
|
||||
]);
|
||||
@@ -292,51 +507,130 @@ export class SecurityService {
|
||||
const violations: string[] = [];
|
||||
const warnings: string[] = [];
|
||||
|
||||
// === Absolute count ceiling checks (new projects only, rate-independent) ===
|
||||
// Catches new accounts blasting emails before their bounce rate catches up.
|
||||
// Established projects skip these — high absolute counts at high volume
|
||||
// (e.g. 100 bounces out of 10K) don't indicate abuse; rate checks handle them.
|
||||
if (isNewProject) {
|
||||
// 24-hour bounce ceilings
|
||||
if (twentyFourHour.bounces >= SECURITY_THRESHOLDS.NEW_PROJECT_BOUNCE_24H_CEILING_CRITICAL) {
|
||||
violations.push(
|
||||
`24-hour bounce count (new project) (${twentyFourHour.bounces} bounces) exceeds critical ceiling (${SECURITY_THRESHOLDS.NEW_PROJECT_BOUNCE_24H_CEILING_CRITICAL})`,
|
||||
);
|
||||
} else if (twentyFourHour.bounces >= SECURITY_THRESHOLDS.NEW_PROJECT_BOUNCE_24H_CEILING_WARNING) {
|
||||
warnings.push(
|
||||
`24-hour bounce count (new project) (${twentyFourHour.bounces} bounces) exceeds warning ceiling (${SECURITY_THRESHOLDS.NEW_PROJECT_BOUNCE_24H_CEILING_WARNING})`,
|
||||
);
|
||||
}
|
||||
|
||||
// 7-day bounce ceilings
|
||||
if (sevenDay.bounces >= SECURITY_THRESHOLDS.NEW_PROJECT_BOUNCE_7DAY_CEILING_CRITICAL) {
|
||||
violations.push(
|
||||
`7-day bounce count (new project) (${sevenDay.bounces} bounces) exceeds critical ceiling (${SECURITY_THRESHOLDS.NEW_PROJECT_BOUNCE_7DAY_CEILING_CRITICAL})`,
|
||||
);
|
||||
} else if (sevenDay.bounces >= SECURITY_THRESHOLDS.NEW_PROJECT_BOUNCE_7DAY_CEILING_WARNING) {
|
||||
warnings.push(
|
||||
`7-day bounce count (new project) (${sevenDay.bounces} bounces) exceeds warning ceiling (${SECURITY_THRESHOLDS.NEW_PROJECT_BOUNCE_7DAY_CEILING_WARNING})`,
|
||||
);
|
||||
}
|
||||
|
||||
// 24-hour complaint ceilings
|
||||
if (twentyFourHour.complaints >= SECURITY_THRESHOLDS.NEW_PROJECT_COMPLAINT_24H_CEILING_CRITICAL) {
|
||||
violations.push(
|
||||
`24-hour complaint count (new project) (${twentyFourHour.complaints} complaints) exceeds critical ceiling (${SECURITY_THRESHOLDS.NEW_PROJECT_COMPLAINT_24H_CEILING_CRITICAL})`,
|
||||
);
|
||||
} else if (twentyFourHour.complaints >= SECURITY_THRESHOLDS.NEW_PROJECT_COMPLAINT_24H_CEILING_WARNING) {
|
||||
warnings.push(
|
||||
`24-hour complaint count (new project) (${twentyFourHour.complaints} complaints) exceeds warning ceiling (${SECURITY_THRESHOLDS.NEW_PROJECT_COMPLAINT_24H_CEILING_WARNING})`,
|
||||
);
|
||||
}
|
||||
|
||||
// 7-day complaint ceilings
|
||||
if (sevenDay.complaints >= SECURITY_THRESHOLDS.NEW_PROJECT_COMPLAINT_7DAY_CEILING_CRITICAL) {
|
||||
violations.push(
|
||||
`7-day complaint count (new project) (${sevenDay.complaints} complaints) exceeds critical ceiling (${SECURITY_THRESHOLDS.NEW_PROJECT_COMPLAINT_7DAY_CEILING_CRITICAL})`,
|
||||
);
|
||||
} else if (sevenDay.complaints >= SECURITY_THRESHOLDS.NEW_PROJECT_COMPLAINT_7DAY_CEILING_WARNING) {
|
||||
warnings.push(
|
||||
`7-day complaint count (new project) (${sevenDay.complaints} complaints) exceeds warning ceiling (${SECURITY_THRESHOLDS.NEW_PROJECT_COMPLAINT_7DAY_CEILING_WARNING})`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// === Rate-based checks (existing logic) ===
|
||||
// Only enforce if minimum emails threshold is met
|
||||
const hasMinimumVolume = allTime.total >= SECURITY_THRESHOLDS.MIN_EMAILS_FOR_ENFORCEMENT;
|
||||
const hasMinimumVolumeAllTime = allTime.total >= SECURITY_THRESHOLDS.MIN_EMAILS_FOR_ENFORCEMENT;
|
||||
const hasMinimumVolume7Day = sevenDay.total >= SECURITY_THRESHOLDS.MIN_EMAILS_FOR_ENFORCEMENT;
|
||||
|
||||
if (hasMinimumVolume) {
|
||||
// Check 7-day bounce rate
|
||||
if (sevenDay.bounceRate >= SECURITY_THRESHOLDS.BOUNCE_7DAY_CRITICAL) {
|
||||
// Check 7-day bounce rate (only if 7-day volume is sufficient)
|
||||
if (hasMinimumVolume7Day) {
|
||||
if (
|
||||
sevenDay.bounceRate >= SECURITY_THRESHOLDS.BOUNCE_7DAY_CRITICAL &&
|
||||
sevenDay.bounces >= SECURITY_THRESHOLDS.MIN_BOUNCES_FOR_CRITICAL
|
||||
) {
|
||||
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(
|
||||
`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)
|
||||
if (hasMinimumVolume7Day) {
|
||||
if (
|
||||
sevenDay.complaintRate >= SECURITY_THRESHOLDS.COMPLAINT_7DAY_CRITICAL &&
|
||||
sevenDay.complaints >= SECURITY_THRESHOLDS.MIN_COMPLAINTS_FOR_CRITICAL
|
||||
) {
|
||||
violations.push(
|
||||
`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 &&
|
||||
sevenDay.complaints >= SECURITY_THRESHOLDS.MIN_COMPLAINTS_FOR_WARNING
|
||||
) {
|
||||
warnings.push(
|
||||
`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)
|
||||
if (hasMinimumVolumeAllTime) {
|
||||
if (
|
||||
allTime.bounceRate >= SECURITY_THRESHOLDS.BOUNCE_ALLTIME_CRITICAL &&
|
||||
allTime.bounces >= SECURITY_THRESHOLDS.MIN_BOUNCES_FOR_CRITICAL
|
||||
) {
|
||||
violations.push(
|
||||
`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 &&
|
||||
allTime.bounces >= SECURITY_THRESHOLDS.MIN_BOUNCES_FOR_WARNING
|
||||
) {
|
||||
warnings.push(
|
||||
`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 bounce rate
|
||||
if (allTime.bounceRate >= SECURITY_THRESHOLDS.BOUNCE_ALLTIME_CRITICAL) {
|
||||
if (
|
||||
allTime.complaintRate >= SECURITY_THRESHOLDS.COMPLAINT_ALLTIME_CRITICAL &&
|
||||
allTime.complaints >= SECURITY_THRESHOLDS.MIN_COMPLAINTS_FOR_CRITICAL
|
||||
) {
|
||||
violations.push(
|
||||
`All-time bounce rate (${allTime.bounceRate.toFixed(2)}%) exceeds critical threshold (${SECURITY_THRESHOLDS.BOUNCE_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.bounceRate >= SECURITY_THRESHOLDS.BOUNCE_ALLTIME_WARNING) {
|
||||
} else if (
|
||||
allTime.complaintRate >= SECURITY_THRESHOLDS.COMPLAINT_ALLTIME_WARNING &&
|
||||
allTime.complaints >= SECURITY_THRESHOLDS.MIN_COMPLAINTS_FOR_WARNING
|
||||
) {
|
||||
warnings.push(
|
||||
`All-time bounce rate (${allTime.bounceRate.toFixed(2)}%) exceeds warning threshold (${SECURITY_THRESHOLDS.BOUNCE_ALLTIME_WARNING}%)`,
|
||||
);
|
||||
}
|
||||
|
||||
// Check 7-day complaint rate
|
||||
if (sevenDay.complaintRate >= SECURITY_THRESHOLDS.COMPLAINT_7DAY_CRITICAL) {
|
||||
violations.push(
|
||||
`7-day complaint rate (${sevenDay.complaintRate.toFixed(3)}%) exceeds critical threshold (${SECURITY_THRESHOLDS.COMPLAINT_7DAY_CRITICAL}%)`,
|
||||
);
|
||||
} else if (sevenDay.complaintRate >= SECURITY_THRESHOLDS.COMPLAINT_7DAY_WARNING) {
|
||||
warnings.push(
|
||||
`7-day complaint rate (${sevenDay.complaintRate.toFixed(3)}%) exceeds warning threshold (${SECURITY_THRESHOLDS.COMPLAINT_7DAY_WARNING}%)`,
|
||||
);
|
||||
}
|
||||
|
||||
// Check all-time complaint rate
|
||||
if (allTime.complaintRate >= SECURITY_THRESHOLDS.COMPLAINT_ALLTIME_CRITICAL) {
|
||||
violations.push(
|
||||
`All-time complaint rate (${allTime.complaintRate.toFixed(3)}%) exceeds critical threshold (${SECURITY_THRESHOLDS.COMPLAINT_ALLTIME_CRITICAL}%)`,
|
||||
);
|
||||
} else if (allTime.complaintRate >= SECURITY_THRESHOLDS.COMPLAINT_ALLTIME_WARNING) {
|
||||
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)`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -345,8 +639,10 @@ export class SecurityService {
|
||||
projectId,
|
||||
isHealthy: violations.length === 0,
|
||||
shouldDisable: violations.length > 0,
|
||||
twentyFourHour,
|
||||
sevenDay,
|
||||
allTime,
|
||||
isNewProject,
|
||||
violations,
|
||||
warnings,
|
||||
};
|
||||
@@ -380,7 +676,7 @@ export class SecurityService {
|
||||
// Disable the project
|
||||
await prisma.project.update({
|
||||
where: {id: projectId},
|
||||
data: {disabled: true},
|
||||
data: {disabled: true, disabledReason: 'EMAIL_REPUTATION'},
|
||||
});
|
||||
|
||||
// Log critical security event
|
||||
@@ -408,11 +704,8 @@ export class SecurityService {
|
||||
|
||||
// Send email notification to project members
|
||||
try {
|
||||
const members = await prisma.membership.findMany({
|
||||
where: {projectId},
|
||||
include: {user: {select: {email: true}}},
|
||||
});
|
||||
const emails = members.map(m => m.user.email);
|
||||
const members = await MembershipService.getMembers(projectId);
|
||||
const emails = members.map(m => m.email);
|
||||
if (emails.length > 0) {
|
||||
const template = React.createElement(ProjectDisabledEmail, {
|
||||
projectName: project.name,
|
||||
@@ -422,7 +715,7 @@ export class SecurityService {
|
||||
landingUrl: LANDING_URI,
|
||||
});
|
||||
await Promise.all(
|
||||
emails.map(email => sendPlatformEmail(email, 'Project Disabled - Security Risk', template)),
|
||||
emails.map(email => sendPlatformEmail(email, 'Project Disabled', template)),
|
||||
);
|
||||
}
|
||||
} catch (emailError) {
|
||||
@@ -432,4 +725,293 @@ export class SecurityService {
|
||||
signale.error(`[SECURITY] Failed to disable project ${projectId}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check email content for phishing or dangerous content using LLM
|
||||
* Uses sampling to reduce costs - only checks a percentage of emails
|
||||
* @returns { isPhishing: boolean, confidence: number, shouldDisable: boolean }
|
||||
*/
|
||||
public static async checkPhishingContent(
|
||||
projectId: string,
|
||||
projectName: string,
|
||||
fromEmail: string,
|
||||
subject: string,
|
||||
body: string,
|
||||
): Promise<{isPhishing: boolean; confidence: number; shouldDisable: boolean}> {
|
||||
// Default safe response
|
||||
const safeResponse = {isPhishing: false, confidence: 0, shouldDisable: false};
|
||||
|
||||
try {
|
||||
// Check if phishing detection is enabled
|
||||
if (!PHISHING_DETECTION_ENABLED) {
|
||||
return safeResponse;
|
||||
}
|
||||
|
||||
// Sample-based checking - only check a percentage of emails
|
||||
if (Math.random() > PHISHING_DETECTION_SAMPLE_RATE) {
|
||||
return safeResponse;
|
||||
}
|
||||
|
||||
signale.info(`[PHISHING] Checking email for project ${projectId} (sampled)`);
|
||||
|
||||
// Strip HTML tags for content analysis (basic HTML removal)
|
||||
const strippedBody = body
|
||||
.replace(/<[^>]*>/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
|
||||
// Extract URLs from the original HTML body for domain analysis
|
||||
const urlMatches = body.match(/https?:\/\/[^\s"'<>]+/g) ?? [];
|
||||
const uniqueUrls = [...new Set(urlMatches.map(u => u.replace(/[.,;)]+$/, '')))].slice(0, 20);
|
||||
|
||||
// Extract sender domain for context
|
||||
const senderDomain = (fromEmail.split('@')[1] ?? fromEmail).toLowerCase();
|
||||
|
||||
// Check whether this domain is verified by the project. A verified
|
||||
// domain means the sender proved DNS/DKIM control — strong evidence of
|
||||
// legitimacy, especially for institutional TLDs like .gov, .edu, .mil.
|
||||
const verifiedDomain = await prisma.domain.findFirst({
|
||||
where: {projectId, domain: senderDomain, verified: true},
|
||||
select: {domain: true},
|
||||
});
|
||||
const isDomainVerified = verifiedDomain !== null;
|
||||
|
||||
// Institutional TLDs that imply a vetted, real-world entity behind the
|
||||
// domain (government, military, accredited education). When combined
|
||||
// with DKIM verification these effectively cannot be phishing senders.
|
||||
const institutionalTldPattern =
|
||||
/\.(gov|mil|edu)(\.[a-z]{2,})?$|\.gc\.ca$|\.gouv\.fr$|\.gov\.uk$|\.ac\.[a-z]{2,}$/i;
|
||||
const isInstitutionalDomain = institutionalTldPattern.test(senderDomain);
|
||||
|
||||
// Skip the LLM check entirely when the sender is a verified institutional
|
||||
// domain (e.g. a .gov customer). These TLDs are gated by registries that
|
||||
// verify the real-world entity, and DKIM verification proves the project
|
||||
// controls the domain — together they make phishing effectively
|
||||
// impossible from this sender. Avoids paying for an LLM call that
|
||||
// sometimes false-positives on official government communications.
|
||||
if (isDomainVerified && isInstitutionalDomain) {
|
||||
signale.info(
|
||||
`[PHISHING] Skipping check for project ${projectId} — verified institutional domain (${senderDomain})`,
|
||||
);
|
||||
return safeResponse;
|
||||
}
|
||||
|
||||
// Call OpenRouter API
|
||||
const response = await fetch('https://openrouter.ai/api/v1/chat/completions', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${OPENROUTER_API_KEY}`,
|
||||
'Content-Type': 'application/json',
|
||||
'HTTP-Referer': 'https://useplunk.com',
|
||||
'X-Title': 'Plunk Email Platform',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: OPENROUTER_MODEL,
|
||||
messages: [
|
||||
{
|
||||
role: 'system',
|
||||
content: `You are a security expert analyzing emails for phishing, scams, and dangerous content. Analyze the email subject and body and respond with a JSON object in this exact format:
|
||||
{
|
||||
"is_phishing": true/false,
|
||||
"confidence": 0-100,
|
||||
"reason": "brief explanation"
|
||||
}
|
||||
|
||||
Criteria for phishing/dangerous content:
|
||||
- Credential theft attempts (fake login pages, password requests)
|
||||
- Financial scams (fake invoices, lottery scams, advance-fee fraud)
|
||||
- Malicious links or attachments references
|
||||
- Impersonation of banks, government, or well-known companies
|
||||
- Urgent threats or fear-based manipulation
|
||||
- Suspicious cryptocurrency or investment schemes
|
||||
- Requests for sensitive personal information
|
||||
|
||||
IMPORTANT - Use sender and project context when evaluating:
|
||||
- The sender project name and domain are provided, along with whether the domain has been verified (DKIM/DNS) by this project.
|
||||
- A VERIFIED sender domain means the sender proved ownership of the domain via DNS records. This is strong evidence of legitimacy.
|
||||
- If the verified sender domain is an institutional domain (e.g. .gov, .gov.uk, .gouv.fr, .gc.ca, .mil, .edu, .ac.*), treat the email as legitimate institutional communication. Government, military, and accredited education domains cannot be obtained by phishers — do NOT flag these as impersonation of government/banks/etc. just because the content mentions official topics, taxes, benefits, court notices, etc.
|
||||
- Impersonation rules only apply when the sender domain does NOT match the brand being referenced. A verified bank domain sending a banking email is not impersonating itself.
|
||||
- Links to the sender's own domain(s) are expected and NOT suspicious.
|
||||
- URLs that match or are clearly related to the project name or sender domain add credibility.
|
||||
- Only flag a URL as suspicious if it is unrelated to or impersonates a different known brand.
|
||||
- Lack of recognizable brand does NOT make an email phishing — many legitimate businesses are not famous.
|
||||
|
||||
Be strict but fair. Marketing emails and legitimate transactional emails are NOT phishing.
|
||||
Only flag content that is CLEARLY attempting to deceive or harm recipients.
|
||||
Set confidence to 100 only if you are absolutely certain it's phishing.`,
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
content: `Sender project name: ${projectName}
|
||||
Sender domain: ${senderDomain}
|
||||
Sender domain verified (DKIM/DNS confirmed by project): ${isDomainVerified ? 'yes' : 'no'}
|
||||
Sender domain is an institutional TLD (gov/mil/edu/ac/etc.): ${isInstitutionalDomain ? 'yes' : 'no'}
|
||||
${uniqueUrls.length > 0 ? `URLs found in email: ${uniqueUrls.join(', ')}` : ''}
|
||||
|
||||
Subject: ${subject}
|
||||
|
||||
Body:
|
||||
${strippedBody.substring(0, 2000)}`,
|
||||
},
|
||||
],
|
||||
temperature: 0.1,
|
||||
max_tokens: 200,
|
||||
response_format: {type: 'json_object'},
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
signale.error(`[PHISHING] OpenRouter API error: ${response.status} ${response.statusText}`);
|
||||
return safeResponse;
|
||||
}
|
||||
|
||||
const data = (await response.json()) as {
|
||||
choices?: Array<{message?: {content?: string}}>;
|
||||
};
|
||||
|
||||
const content = data.choices?.[0]?.message?.content;
|
||||
if (!content) {
|
||||
signale.error('[PHISHING] No content in OpenRouter response');
|
||||
return safeResponse;
|
||||
}
|
||||
|
||||
// Parse the JSON response (response_format ensures clean JSON)
|
||||
const result = JSON.parse(content) as {
|
||||
is_phishing: boolean;
|
||||
confidence: number;
|
||||
reason: string;
|
||||
};
|
||||
|
||||
const isPhishing = result.is_phishing === true;
|
||||
const confidence = Math.min(100, Math.max(0, result.confidence || 0));
|
||||
|
||||
if (isPhishing) {
|
||||
signale.warn(
|
||||
`[PHISHING] Detected phishing content for project ${projectId} - Confidence: ${confidence}% - Reason: ${result.reason}`,
|
||||
);
|
||||
|
||||
// Track this detection for cumulative analysis
|
||||
await trackPhishingDetection(projectId, confidence, subject);
|
||||
|
||||
// Get count of recent detections
|
||||
const recentCount = await getRecentPhishingCount(projectId);
|
||||
signale.info(
|
||||
`[PHISHING] Project ${projectId} has ${recentCount} phishing detection(s) in the last ${PHISHING_CUMULATIVE_WINDOW_MS / 1000 / 60} minutes`,
|
||||
);
|
||||
} else {
|
||||
signale.success(`[PHISHING] Passed phishing check for project: ${projectId}`);
|
||||
}
|
||||
|
||||
// Determine if project should be disabled
|
||||
// Disable if EITHER:
|
||||
// 1. Single detection with high confidence (>= threshold)
|
||||
// 2. Multiple detections within time window (>= cumulative threshold)
|
||||
const meetsConfidenceThreshold = isPhishing && confidence >= PHISHING_CONFIDENCE_THRESHOLD;
|
||||
const recentCount = await getRecentPhishingCount(projectId);
|
||||
const meetsCumulativeThreshold = isPhishing && recentCount >= PHISHING_CUMULATIVE_THRESHOLD;
|
||||
const shouldDisable = meetsConfidenceThreshold || meetsCumulativeThreshold;
|
||||
|
||||
if (shouldDisable) {
|
||||
if (meetsConfidenceThreshold) {
|
||||
signale.error(
|
||||
`[PHISHING] High confidence phishing detected (${confidence}% >= ${PHISHING_CONFIDENCE_THRESHOLD}%) - will disable project ${projectId}`,
|
||||
);
|
||||
}
|
||||
if (meetsCumulativeThreshold) {
|
||||
signale.error(
|
||||
`[PHISHING] Cumulative threshold reached (${recentCount} >= ${PHISHING_CUMULATIVE_THRESHOLD} detections) - will disable project ${projectId}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Clear history after disabling
|
||||
await clearPhishingHistory(projectId);
|
||||
}
|
||||
|
||||
return {
|
||||
isPhishing,
|
||||
confidence,
|
||||
shouldDisable,
|
||||
};
|
||||
} catch (error) {
|
||||
// Log error but don't throw - we don't want phishing checks to break email sending
|
||||
// Better to let a phishing email through than to break legitimate emails
|
||||
signale.error(`[PHISHING] Failed to check content for project ${projectId}:`, error);
|
||||
return safeResponse;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable a project due to phishing detection
|
||||
*/
|
||||
public static async disableProjectForPhishing(
|
||||
projectId: string,
|
||||
subject: string,
|
||||
confidence: number,
|
||||
reason?: string,
|
||||
): Promise<void> {
|
||||
try {
|
||||
// Check if already disabled to avoid duplicate logs
|
||||
const project = await prisma.project.findUnique({
|
||||
where: {id: projectId},
|
||||
select: {id: true, disabled: true, name: true},
|
||||
});
|
||||
|
||||
if (!project) {
|
||||
signale.error(`[PHISHING] Project ${projectId} not found`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (project.disabled) {
|
||||
signale.warn(`[PHISHING] Project ${projectId} (${project.name}) already disabled`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Disable the project
|
||||
await prisma.project.update({
|
||||
where: {id: projectId},
|
||||
data: {disabled: true, disabledReason: 'PHISHING_DETECTED'},
|
||||
});
|
||||
|
||||
const violation = `A policy violation was detected. Please contact support for more details.`;
|
||||
|
||||
// Log critical security event
|
||||
signale.error(
|
||||
`[PHISHING] Project ${projectId} (${project.name}) has been automatically disabled due to phishing detection:`,
|
||||
violation,
|
||||
);
|
||||
|
||||
// Cancel all pending jobs for this project
|
||||
try {
|
||||
await QueueService.cancelAllProjectJobs(projectId);
|
||||
signale.info(`[PHISHING] Cancelled all pending jobs for project ${projectId}`);
|
||||
} catch (error) {
|
||||
signale.error(`[PHISHING] Failed to cancel pending jobs for project ${projectId}:`, error);
|
||||
}
|
||||
|
||||
// Send urgent notification about project suspension
|
||||
await NtfyService.notifyProjectDisabledForSecurity(project.name, projectId, [violation]);
|
||||
|
||||
// Send email notification to project members
|
||||
try {
|
||||
const members = await MembershipService.getMembers(projectId);
|
||||
const emails = members.map(m => m.email);
|
||||
if (emails.length > 0) {
|
||||
const template = React.createElement(ProjectDisabledEmail, {
|
||||
projectName: project.name,
|
||||
projectId,
|
||||
violations: [violation],
|
||||
dashboardUrl: DASHBOARD_URI,
|
||||
landingUrl: LANDING_URI,
|
||||
});
|
||||
await Promise.all(
|
||||
emails.map(email => sendPlatformEmail(email, 'Project Disabled', template)),
|
||||
);
|
||||
}
|
||||
} catch (emailError) {
|
||||
signale.error(`[PHISHING] Failed to send project disabled email:`, emailError);
|
||||
}
|
||||
} catch (error) {
|
||||
signale.error(`[PHISHING] Failed to disable project ${projectId}:`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {type Contact, Prisma, type Segment} from '@plunk/db';
|
||||
import type {FilterCondition, FilterGroup, SegmentFilter} from '@plunk/types';
|
||||
import type {FilterCondition, FilterGroup, PaginatedResponse, SegmentFilter, SegmentType} from '@plunk/types';
|
||||
import {fromPrismaJson, toPrismaJson} from '@plunk/types';
|
||||
import signale from 'signale';
|
||||
|
||||
import {prisma} from '../database/prisma.js';
|
||||
@@ -8,17 +9,8 @@ import {HttpException} from '../exceptions/index.js';
|
||||
import {EventService} from './EventService.js';
|
||||
import {NtfyService} from './NtfyService.js';
|
||||
|
||||
// Re-export types for use in other services
|
||||
export type {FilterCondition, FilterGroup, SegmentFilter} from '@plunk/types';
|
||||
|
||||
export interface PaginatedContacts {
|
||||
contacts: Contact[];
|
||||
total: number;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
totalPages: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert segment name to a URL-safe slug for event names
|
||||
* Example: "VIP Customers" -> "vip-customers"
|
||||
@@ -72,13 +64,35 @@ export class SegmentService {
|
||||
segmentId: string,
|
||||
page = 1,
|
||||
pageSize = 20,
|
||||
): Promise<PaginatedContacts> {
|
||||
): Promise<PaginatedResponse<Contact>> {
|
||||
const segment = await this.get(projectId, segmentId);
|
||||
const condition = segment.condition as unknown as FilterCondition;
|
||||
|
||||
const where = this.buildWhereClause(projectId, condition);
|
||||
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 = await this.buildWhereClause(projectId, condition);
|
||||
|
||||
const [contacts, total] = await Promise.all([
|
||||
prisma.contact.findMany({
|
||||
where,
|
||||
@@ -90,7 +104,7 @@ export class SegmentService {
|
||||
]);
|
||||
|
||||
return {
|
||||
contacts,
|
||||
data: contacts,
|
||||
total,
|
||||
page,
|
||||
pageSize,
|
||||
@@ -106,23 +120,35 @@ export class SegmentService {
|
||||
data: {
|
||||
name: string;
|
||||
description?: string;
|
||||
condition: FilterCondition;
|
||||
type?: SegmentType;
|
||||
condition?: FilterCondition;
|
||||
trackMembership?: boolean;
|
||||
},
|
||||
): Promise<Segment> {
|
||||
// Validate condition
|
||||
this.validateCondition(data.condition);
|
||||
const segmentType = data.type ?? 'DYNAMIC';
|
||||
let memberCount = 0;
|
||||
let conditionJson: Prisma.InputJsonValue | typeof Prisma.JsonNull = Prisma.JsonNull;
|
||||
|
||||
// Compute initial member count
|
||||
const where = this.buildWhereClause(projectId, data.condition);
|
||||
const memberCount = await prisma.contact.count({where});
|
||||
if (segmentType === 'DYNAMIC') {
|
||||
if (!data.condition) {
|
||||
throw new HttpException(400, 'Condition is required for DYNAMIC segments');
|
||||
}
|
||||
// Validate condition
|
||||
this.validateCondition(data.condition);
|
||||
|
||||
// Compute initial member count
|
||||
const where = await this.buildWhereClause(projectId, data.condition);
|
||||
memberCount = await prisma.contact.count({where});
|
||||
conditionJson = toPrismaJson(data.condition);
|
||||
}
|
||||
|
||||
const segment = await prisma.segment.create({
|
||||
data: {
|
||||
projectId,
|
||||
name: data.name,
|
||||
description: data.description,
|
||||
condition: data.condition as unknown as Prisma.InputJsonValue,
|
||||
type: segmentType,
|
||||
condition: conditionJson,
|
||||
trackMembership: data.trackMembership ?? false,
|
||||
memberCount,
|
||||
},
|
||||
@@ -153,12 +179,7 @@ export class SegmentService {
|
||||
},
|
||||
): Promise<Segment> {
|
||||
// First verify segment exists and belongs to project
|
||||
await this.get(projectId, segmentId);
|
||||
|
||||
// Validate condition if provided
|
||||
if (data.condition) {
|
||||
this.validateCondition(data.condition);
|
||||
}
|
||||
const existing = await this.get(projectId, segmentId);
|
||||
|
||||
const updateData: Prisma.SegmentUpdateInput = {};
|
||||
|
||||
@@ -168,11 +189,17 @@ export class SegmentService {
|
||||
if (data.description !== undefined) {
|
||||
updateData.description = data.description;
|
||||
}
|
||||
if (data.condition !== undefined) {
|
||||
updateData.condition = data.condition as unknown as Prisma.InputJsonValue;
|
||||
if (data.condition !== undefined && existing.type !== 'STATIC') {
|
||||
// Validate condition if provided (only for DYNAMIC segments)
|
||||
this.validateCondition(data.condition);
|
||||
|
||||
if (this.getReferencedSegmentIds(data.condition).has(segmentId)) {
|
||||
throw new HttpException(400, 'A segment cannot reference itself');
|
||||
}
|
||||
updateData.condition = toPrismaJson(data.condition);
|
||||
|
||||
// Recompute member count when condition changes
|
||||
const where = this.buildWhereClause(projectId, data.condition);
|
||||
const where = await this.buildWhereClause(projectId, data.condition);
|
||||
updateData.memberCount = await prisma.contact.count({where});
|
||||
}
|
||||
if (data.trackMembership !== undefined) {
|
||||
@@ -237,10 +264,16 @@ export class SegmentService {
|
||||
*/
|
||||
public static async refreshMemberCount(projectId: string, segmentId: string): Promise<number> {
|
||||
const segment = await this.get(projectId, segmentId);
|
||||
const condition = segment.condition as unknown as FilterCondition;
|
||||
const where = this.buildWhereClause(projectId, condition);
|
||||
|
||||
const memberCount = await prisma.contact.count({where});
|
||||
let memberCount: number;
|
||||
|
||||
if (segment.type === 'STATIC') {
|
||||
memberCount = await prisma.segmentMembership.count({where: {segmentId, exitedAt: null}});
|
||||
} else {
|
||||
const condition = fromPrismaJson<FilterCondition>(segment.condition);
|
||||
const where = await this.buildWhereClause(projectId, condition);
|
||||
memberCount = await prisma.contact.count({where});
|
||||
}
|
||||
|
||||
await prisma.segment.update({
|
||||
where: {id: segmentId},
|
||||
@@ -257,7 +290,7 @@ export class SegmentService {
|
||||
public static async refreshAllMemberCounts(projectId: string): Promise<void> {
|
||||
const segments = await prisma.segment.findMany({
|
||||
where: {projectId},
|
||||
select: {id: true, condition: true},
|
||||
select: {id: true, type: true, condition: true},
|
||||
});
|
||||
|
||||
// Process in batches to avoid overwhelming the database
|
||||
@@ -268,9 +301,17 @@ export class SegmentService {
|
||||
await Promise.all(
|
||||
batch.map(async segment => {
|
||||
try {
|
||||
const condition = segment.condition as unknown as FilterCondition;
|
||||
const where = this.buildWhereClause(projectId, condition);
|
||||
const memberCount = await prisma.contact.count({where});
|
||||
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 where = await this.buildWhereClause(projectId, condition);
|
||||
memberCount = await prisma.contact.count({where});
|
||||
}
|
||||
|
||||
await prisma.segment.update({
|
||||
where: {id: segment.id},
|
||||
@@ -284,6 +325,123 @@ export class SegmentService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add contacts to a static segment by email
|
||||
*/
|
||||
public static async addContacts(
|
||||
projectId: string,
|
||||
segmentId: string,
|
||||
emails: string[],
|
||||
createMissing = false,
|
||||
subscribed = true,
|
||||
): Promise<{added: number; created: 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)
|
||||
let contacts = await prisma.contact.findMany({
|
||||
where: {
|
||||
projectId,
|
||||
email: {in: emails, mode: 'insensitive'},
|
||||
},
|
||||
select: {id: true, email: true},
|
||||
});
|
||||
|
||||
let foundEmails = new Set(contacts.map(c => c.email.toLowerCase()));
|
||||
const missing = emails.filter(e => !foundEmails.has(e.toLowerCase()));
|
||||
|
||||
let created = 0;
|
||||
if (createMissing && missing.length > 0) {
|
||||
await prisma.contact.createMany({
|
||||
data: missing.map(email => ({projectId, email, subscribed})),
|
||||
skipDuplicates: true,
|
||||
});
|
||||
created = missing.length;
|
||||
// Re-fetch to include newly created contacts
|
||||
contacts = await prisma.contact.findMany({
|
||||
where: {projectId, email: {in: emails, mode: 'insensitive'}},
|
||||
select: {id: true, email: true},
|
||||
});
|
||||
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, created, 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
|
||||
* Now uses cursor-based pagination for memory efficiency with large contact lists
|
||||
@@ -298,8 +456,15 @@ export class SegmentService {
|
||||
throw new HttpException(400, 'Segment does not have membership tracking enabled');
|
||||
}
|
||||
|
||||
const condition = segment.condition as unknown as FilterCondition;
|
||||
const where = this.buildWhereClause(projectId, condition);
|
||||
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 where = await this.buildWhereClause(projectId, condition);
|
||||
|
||||
// Get all matching contacts using cursor-based pagination to avoid memory issues
|
||||
const BATCH_SIZE = 1000;
|
||||
@@ -364,15 +529,43 @@ export class SegmentService {
|
||||
for (let i = 0; i < toAdd.length; i += ADD_BATCH_SIZE) {
|
||||
const batch = toAdd.slice(i, i + ADD_BATCH_SIZE);
|
||||
|
||||
await prisma.segmentMembership.createMany({
|
||||
data: batch.map(contactId => ({
|
||||
// Check which contacts already have a membership record (inactive)
|
||||
const existingMemberships = await prisma.segmentMembership.findMany({
|
||||
where: {
|
||||
segmentId,
|
||||
contactId,
|
||||
enteredAt: new Date(),
|
||||
})),
|
||||
skipDuplicates: true,
|
||||
contactId: {in: batch},
|
||||
},
|
||||
select: {contactId: true},
|
||||
});
|
||||
|
||||
const existingContactIds = new Set(existingMemberships.map(m => m.contactId));
|
||||
const newEntries = batch.filter(id => !existingContactIds.has(id));
|
||||
const reEntries = batch.filter(id => existingContactIds.has(id));
|
||||
|
||||
if (newEntries.length > 0) {
|
||||
await prisma.segmentMembership.createMany({
|
||||
data: newEntries.map(contactId => ({
|
||||
segmentId,
|
||||
contactId,
|
||||
enteredAt: new Date(),
|
||||
})),
|
||||
skipDuplicates: true,
|
||||
});
|
||||
}
|
||||
|
||||
if (reEntries.length > 0) {
|
||||
await prisma.segmentMembership.updateMany({
|
||||
where: {
|
||||
segmentId,
|
||||
contactId: {in: reEntries},
|
||||
},
|
||||
data: {
|
||||
exitedAt: null,
|
||||
enteredAt: new Date(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Create segment-specific entry events for each contact in the batch
|
||||
for (const contactId of batch) {
|
||||
try {
|
||||
@@ -440,9 +633,57 @@ export class SegmentService {
|
||||
/**
|
||||
* Build a single filter condition
|
||||
*/
|
||||
public static buildFilterCondition(filter: SegmentFilter): Prisma.ContactWhereInput {
|
||||
public static async buildFilterCondition(
|
||||
filter: SegmentFilter,
|
||||
visitedSegments = new Set<string>(),
|
||||
): Promise<Prisma.ContactWhereInput> {
|
||||
const {field, operator, value, unit} = filter;
|
||||
|
||||
// Handle segment membership filters (e.g., "segment.<segmentId>")
|
||||
if (field.startsWith('segment.')) {
|
||||
const segmentId = field.substring(8);
|
||||
|
||||
if (visitedSegments.has(segmentId)) {
|
||||
throw new HttpException(400, 'Circular segment reference detected');
|
||||
}
|
||||
|
||||
const referencedSegment = await prisma.segment.findUnique({
|
||||
where: {id: segmentId},
|
||||
});
|
||||
|
||||
if (!referencedSegment) {
|
||||
throw new HttpException(400, `Referenced segment not found: ${segmentId}`);
|
||||
}
|
||||
|
||||
let memberIds: string[];
|
||||
|
||||
if (referencedSegment.type === 'STATIC' || referencedSegment.trackMembership) {
|
||||
// Use the membership table for static or tracked segments
|
||||
const memberships = await prisma.segmentMembership.findMany({
|
||||
where: {segmentId, exitedAt: null},
|
||||
select: {contactId: true},
|
||||
});
|
||||
memberIds = memberships.map(m => m.contactId);
|
||||
} else {
|
||||
// For untracked dynamic segments, evaluate the condition recursively
|
||||
const nestedCondition = fromPrismaJson<FilterCondition>(referencedSegment.condition);
|
||||
const nextVisited = new Set(visitedSegments).add(segmentId);
|
||||
const nestedWhere = await this.buildConditionClause(nestedCondition, nextVisited);
|
||||
|
||||
if (operator === 'memberOfSegment') {
|
||||
return nestedWhere;
|
||||
}
|
||||
|
||||
return {NOT: nestedWhere};
|
||||
}
|
||||
|
||||
if (operator === 'memberOfSegment') {
|
||||
return {id: {in: memberIds}};
|
||||
}
|
||||
|
||||
return {id: {notIn: memberIds}};
|
||||
}
|
||||
|
||||
// Handle event-based filters (e.g., "event.upgrade", "event.purchase")
|
||||
if (field.startsWith('event.')) {
|
||||
const eventName = field.substring(6); // Remove "event." prefix
|
||||
@@ -458,7 +699,7 @@ export class SegmentService {
|
||||
// Handle JSON field paths (e.g., "data.plan")
|
||||
if (field.startsWith('data.')) {
|
||||
const jsonPath = field.substring(5); // Remove "data." prefix
|
||||
return this.buildJsonFieldCondition(jsonPath, operator, value);
|
||||
return this.buildJsonFieldCondition(jsonPath, operator, value, unit);
|
||||
}
|
||||
|
||||
// Handle regular fields
|
||||
@@ -475,6 +716,26 @@ export class SegmentService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect all segment IDs directly referenced in a condition (non-recursive DB lookup)
|
||||
*/
|
||||
private static getReferencedSegmentIds(condition: FilterCondition): Set<string> {
|
||||
const ids = new Set<string>();
|
||||
for (const group of condition.groups) {
|
||||
for (const filter of group.filters) {
|
||||
if (filter.field.startsWith('segment.')) {
|
||||
ids.add(filter.field.substring(8));
|
||||
}
|
||||
}
|
||||
if (group.conditions) {
|
||||
for (const id of this.getReferencedSegmentIds(group.conditions)) {
|
||||
ids.add(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate segment condition (recursive)
|
||||
*/
|
||||
@@ -496,6 +757,24 @@ export class SegmentService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build Prisma clause from filter condition (recursive)
|
||||
*/
|
||||
public static async buildConditionClause(
|
||||
condition: FilterCondition,
|
||||
visitedSegments = new Set<string>(),
|
||||
): Promise<Prisma.ContactWhereInput> {
|
||||
const groupClauses = await Promise.all(
|
||||
condition.groups.map(group => this.buildGroupClause(group, visitedSegments)),
|
||||
);
|
||||
|
||||
if (condition.logic === 'AND') {
|
||||
return {AND: groupClauses};
|
||||
} else {
|
||||
return {OR: groupClauses};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate filter group (recursive)
|
||||
*/
|
||||
@@ -551,15 +830,28 @@ export class SegmentService {
|
||||
'exists',
|
||||
'notExists',
|
||||
'within',
|
||||
'olderThan',
|
||||
'triggered',
|
||||
'triggeredWithin',
|
||||
'triggeredOlderThan',
|
||||
'notTriggered',
|
||||
'notTriggeredWithin',
|
||||
'memberOfSegment',
|
||||
'notMemberOfSegment',
|
||||
];
|
||||
|
||||
if (!validOperators.includes(filter.operator)) {
|
||||
throw new HttpException(400, `Invalid operator: ${filter.operator}`);
|
||||
}
|
||||
|
||||
// Segment membership operators use the segmentId encoded in the field name, no separate value needed
|
||||
if (filter.operator === 'memberOfSegment' || filter.operator === 'notMemberOfSegment') {
|
||||
if (!filter.field.startsWith('segment.')) {
|
||||
throw new HttpException(400, 'memberOfSegment/notMemberOfSegment operators require a segment field (segment.<id>)');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate that operators that need a value have one
|
||||
const operatorsNeedingValue = [
|
||||
'equals',
|
||||
@@ -571,7 +863,10 @@ export class SegmentService {
|
||||
'greaterThanOrEqual',
|
||||
'lessThanOrEqual',
|
||||
'within',
|
||||
'olderThan',
|
||||
'triggeredWithin',
|
||||
'triggeredOlderThan',
|
||||
'notTriggeredWithin',
|
||||
];
|
||||
|
||||
if (operatorsNeedingValue.includes(filter.operator) && filter.value === undefined) {
|
||||
@@ -579,7 +874,7 @@ export class SegmentService {
|
||||
}
|
||||
|
||||
// Validate unit for time-based operators
|
||||
if (['within', 'triggeredWithin'].includes(filter.operator) && !filter.unit) {
|
||||
if (['within', 'triggeredWithin', 'olderThan', 'triggeredOlderThan', 'notTriggeredWithin'].includes(filter.operator) && !filter.unit) {
|
||||
throw new HttpException(400, `"${filter.operator}" operator requires a unit (days, hours, or minutes)`);
|
||||
}
|
||||
}
|
||||
@@ -587,40 +882,36 @@ export class SegmentService {
|
||||
/**
|
||||
* Build Prisma where clause from filter condition (entry point)
|
||||
*/
|
||||
private static buildWhereClause(projectId: string, condition: FilterCondition): Prisma.ContactWhereInput {
|
||||
private static async buildWhereClause(
|
||||
projectId: string,
|
||||
condition: FilterCondition,
|
||||
): Promise<Prisma.ContactWhereInput> {
|
||||
return {
|
||||
projectId,
|
||||
...this.buildConditionClause(condition),
|
||||
...(await this.buildConditionClause(condition)),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Build Prisma clause from filter condition (recursive)
|
||||
*/
|
||||
public static buildConditionClause(condition: FilterCondition): Prisma.ContactWhereInput {
|
||||
const groupClauses = condition.groups.map(group => this.buildGroupClause(group));
|
||||
|
||||
if (condition.logic === 'AND') {
|
||||
return {AND: groupClauses};
|
||||
} else {
|
||||
return {OR: groupClauses};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build Prisma clause from filter group (recursive)
|
||||
*/
|
||||
private static buildGroupClause(group: FilterGroup): Prisma.ContactWhereInput {
|
||||
private static async buildGroupClause(
|
||||
group: FilterGroup,
|
||||
visitedSegments = new Set<string>(),
|
||||
): Promise<Prisma.ContactWhereInput> {
|
||||
const clauses: Prisma.ContactWhereInput[] = [];
|
||||
|
||||
// Add filter conditions from this group
|
||||
if (group.filters.length > 0) {
|
||||
clauses.push(...group.filters.map(filter => this.buildFilterCondition(filter)));
|
||||
const filterClauses = await Promise.all(
|
||||
group.filters.map(filter => this.buildFilterCondition(filter, visitedSegments)),
|
||||
);
|
||||
clauses.push(...filterClauses);
|
||||
}
|
||||
|
||||
// Add nested condition if present
|
||||
if (group.conditions) {
|
||||
clauses.push(this.buildConditionClause(group.conditions));
|
||||
clauses.push(await this.buildConditionClause(group.conditions, visitedSegments));
|
||||
}
|
||||
|
||||
// All conditions within a group are combined with AND
|
||||
@@ -638,13 +929,38 @@ export class SegmentService {
|
||||
/**
|
||||
* Build condition for JSON fields (stored in contact.data)
|
||||
*/
|
||||
private static buildJsonFieldCondition(jsonPath: string, operator: string, value: unknown): Prisma.ContactWhereInput {
|
||||
private static buildJsonFieldCondition(
|
||||
jsonPath: string,
|
||||
operator: string,
|
||||
value: unknown,
|
||||
unit?: 'days' | 'hours' | 'minutes',
|
||||
): Prisma.ContactWhereInput {
|
||||
const path = jsonPath.split('.');
|
||||
|
||||
switch (operator) {
|
||||
case 'equals':
|
||||
// For date strings, compare only the date portion (ignore time)
|
||||
if (this.isDateString(value)) {
|
||||
const {startOfDay, startOfNextDay} = this.getDateRange(String(value));
|
||||
return {
|
||||
AND: [
|
||||
{data: {path, gte: startOfDay as Prisma.InputJsonValue}},
|
||||
{data: {path, lt: startOfNextDay as Prisma.InputJsonValue}},
|
||||
],
|
||||
};
|
||||
}
|
||||
return {data: {path, equals: value as Prisma.InputJsonValue}};
|
||||
case 'notEquals':
|
||||
// For date strings, exclude the entire day (not just exact timestamp)
|
||||
if (this.isDateString(value)) {
|
||||
const {startOfDay, startOfNextDay} = this.getDateRange(String(value));
|
||||
return {
|
||||
OR: [
|
||||
{data: {path, lt: startOfDay as Prisma.InputJsonValue}},
|
||||
{data: {path, gte: startOfNextDay as Prisma.InputJsonValue}},
|
||||
],
|
||||
};
|
||||
}
|
||||
return {NOT: {data: {path, equals: value as Prisma.InputJsonValue}}};
|
||||
case 'contains':
|
||||
return {data: {path, string_contains: String(value)}};
|
||||
@@ -670,6 +986,34 @@ export class SegmentService {
|
||||
return {
|
||||
OR: [{data: {path, equals: Prisma.DbNull}}, {data: {path, equals: Prisma.JsonNull}}],
|
||||
};
|
||||
case 'within': {
|
||||
// Note: Requires JSON date fields in ISO 8601 format for proper comparison
|
||||
if (!unit) {
|
||||
throw new HttpException(400, 'Unit is required for "within" operator');
|
||||
}
|
||||
|
||||
// Calculate the "since" date (X time units ago from now)
|
||||
const now = new Date();
|
||||
const milliseconds = this.getMilliseconds(value as number, unit);
|
||||
const since = new Date(now.getTime() - milliseconds);
|
||||
|
||||
// Use ISO string for lexicographic comparison in JSON
|
||||
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:
|
||||
throw new HttpException(400, `Unsupported operator for JSON field: ${operator}`);
|
||||
}
|
||||
@@ -721,6 +1065,28 @@ export class SegmentService {
|
||||
unit?: 'days' | 'hours' | 'minutes',
|
||||
): Prisma.ContactWhereInput {
|
||||
switch (operator) {
|
||||
case 'equals': {
|
||||
// For date fields, compare only the date portion (ignore time)
|
||||
if (this.isDateString(value)) {
|
||||
const {startOfDay, startOfNextDay} = this.getDateRange(String(value));
|
||||
return {
|
||||
AND: [{[field]: {gte: new Date(startOfDay)}}, {[field]: {lt: new Date(startOfNextDay)}}],
|
||||
};
|
||||
}
|
||||
// Exact timestamp match if not a date string
|
||||
return {[field]: new Date(value as string | number | Date)};
|
||||
}
|
||||
case 'notEquals': {
|
||||
// For date fields, exclude the entire day (not just exact timestamp)
|
||||
if (this.isDateString(value)) {
|
||||
const {startOfDay, startOfNextDay} = this.getDateRange(String(value));
|
||||
return {
|
||||
OR: [{[field]: {lt: new Date(startOfDay)}}, {[field]: {gte: new Date(startOfNextDay)}}],
|
||||
};
|
||||
}
|
||||
// Exclude exact timestamp if not a date string
|
||||
return {NOT: {[field]: new Date(value as string | number | Date)}};
|
||||
}
|
||||
case 'greaterThan':
|
||||
return {[field]: {gt: new Date(value as string | number | Date)}};
|
||||
case 'lessThan':
|
||||
@@ -741,6 +1107,18 @@ export class SegmentService {
|
||||
|
||||
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:
|
||||
throw new HttpException(400, `Unsupported operator for date field: ${operator}`);
|
||||
}
|
||||
@@ -762,6 +1140,41 @@ export class SegmentService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a value is a date string in YYYY-MM-DD format
|
||||
*/
|
||||
private static isDateString(value: unknown): boolean {
|
||||
if (typeof value !== 'string') return false;
|
||||
// Match YYYY-MM-DD format (with optional time component)
|
||||
const dateRegex = /^\d{4}-\d{2}-\d{2}(T|$)/;
|
||||
if (!dateRegex.test(value)) return false;
|
||||
// Verify it's a valid date
|
||||
const date = new Date(value);
|
||||
return !isNaN(date.getTime());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get date range for a date string (start of day to start of next day in UTC)
|
||||
* @param value - Date string in YYYY-MM-DD format
|
||||
* @returns Object with startOfDay and startOfNextDay as ISO strings
|
||||
*/
|
||||
private static getDateRange(value: string): {startOfDay: string; startOfNextDay: string} {
|
||||
// Extract just the date part (YYYY-MM-DD)
|
||||
const dateStr = value.split('T')[0];
|
||||
const startOfDay = `${dateStr}T00:00:00.000Z`;
|
||||
|
||||
if (!dateStr) {
|
||||
throw new HttpException(400, `Invalid date string: ${value}`);
|
||||
}
|
||||
|
||||
// Calculate start of next day
|
||||
const nextDay = new Date(dateStr);
|
||||
nextDay.setUTCDate(nextDay.getUTCDate() + 1);
|
||||
const startOfNextDay = nextDay.toISOString().split('T')[0] + 'T00:00:00.000Z';
|
||||
|
||||
return {startOfDay, startOfNextDay};
|
||||
}
|
||||
|
||||
/**
|
||||
* Build condition for event-based filters
|
||||
* Uses Prisma relations to efficiently query contacts who triggered specific events
|
||||
@@ -805,6 +1218,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':
|
||||
// Contact has never triggered this event
|
||||
return {
|
||||
@@ -815,6 +1264,28 @@ export class SegmentService {
|
||||
},
|
||||
};
|
||||
|
||||
case 'notTriggeredWithin': {
|
||||
// Contact has not triggered this event within the timeframe (includes never-triggered contacts)
|
||||
if (!unit) {
|
||||
throw new HttpException(400, 'Unit is required for "notTriggeredWithin" operator');
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const milliseconds = this.getMilliseconds(value as number, unit);
|
||||
const since = new Date(now.getTime() - milliseconds);
|
||||
|
||||
return {
|
||||
events: {
|
||||
none: {
|
||||
name: eventName,
|
||||
createdAt: {
|
||||
gte: since,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
default:
|
||||
throw new HttpException(400, `Unsupported operator for event field: ${operator}`);
|
||||
}
|
||||
@@ -830,13 +1301,18 @@ export class SegmentService {
|
||||
value: unknown,
|
||||
unit?: 'days' | 'hours' | 'minutes',
|
||||
): Prisma.ContactWhereInput {
|
||||
// Map activity names to Email model fields
|
||||
// Map activity names to Email model fields (accept both verb and past-tense forms)
|
||||
const fieldMap: Record<string, string> = {
|
||||
open: 'openedAt',
|
||||
opened: 'openedAt',
|
||||
click: 'clickedAt',
|
||||
clicked: 'clickedAt',
|
||||
bounce: 'bouncedAt',
|
||||
bounced: 'bouncedAt',
|
||||
complaint: 'complainedAt',
|
||||
complained: 'complainedAt',
|
||||
sent: 'sentAt',
|
||||
delivery: 'deliveredAt',
|
||||
delivered: 'deliveredAt',
|
||||
};
|
||||
|
||||
@@ -879,6 +1355,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':
|
||||
// Contact has never had this email activity
|
||||
return {
|
||||
@@ -891,6 +1403,27 @@ export class SegmentService {
|
||||
},
|
||||
};
|
||||
|
||||
case 'notTriggeredWithin': {
|
||||
// Contact has not had this email activity within the timeframe (includes contacts with no activity)
|
||||
if (!unit) {
|
||||
throw new HttpException(400, 'Unit is required for "notTriggeredWithin" operator');
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const milliseconds = this.getMilliseconds(value as number, unit);
|
||||
const since = new Date(now.getTime() - milliseconds);
|
||||
|
||||
return {
|
||||
emails: {
|
||||
none: {
|
||||
[field]: {
|
||||
gte: since,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
default:
|
||||
throw new HttpException(400, `Unsupported operator for email activity field: ${operator}`);
|
||||
}
|
||||
|
||||
@@ -1,18 +1,11 @@
|
||||
import type {Template} from '@plunk/db';
|
||||
import {Prisma} from '@plunk/db';
|
||||
import type {PaginatedResponse} from '@plunk/types';
|
||||
|
||||
import {prisma} from '../database/prisma.js';
|
||||
import {HttpException} from '../exceptions/index.js';
|
||||
import {buildEmailFieldsUpdate} from '../utils/modelUpdate.js';
|
||||
|
||||
export interface PaginatedTemplates {
|
||||
templates: Template[];
|
||||
total: number;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
totalPages: number;
|
||||
}
|
||||
|
||||
export class TemplateService {
|
||||
/**
|
||||
* Get all templates for a project with pagination
|
||||
@@ -23,7 +16,7 @@ export class TemplateService {
|
||||
pageSize = 20,
|
||||
search?: string,
|
||||
type?: Template['type'],
|
||||
): Promise<PaginatedTemplates> {
|
||||
): Promise<PaginatedResponse<Template>> {
|
||||
const skip = (page - 1) * pageSize;
|
||||
|
||||
const where: Prisma.TemplateWhereInput = {
|
||||
@@ -51,7 +44,7 @@ export class TemplateService {
|
||||
]);
|
||||
|
||||
return {
|
||||
templates,
|
||||
data: templates,
|
||||
total,
|
||||
page,
|
||||
pageSize,
|
||||
|
||||
@@ -10,6 +10,7 @@ import {Keys} from './keys.js';
|
||||
* Extract base domain from URL for cookie sharing across subdomains
|
||||
* e.g., "http://api.example.com" -> ".example.com"
|
||||
* e.g., "http://api.localhost" -> ".localhost"
|
||||
* e.g., "http://app.plunk.local" -> ".plunk.local"
|
||||
*/
|
||||
function getCookieDomain(): string | undefined {
|
||||
if (NODE_ENV === 'development') {
|
||||
@@ -28,10 +29,14 @@ function getCookieDomain(): string | undefined {
|
||||
// Extract base domain (last two parts for most domains, or .localhost)
|
||||
const parts = hostname.split('.');
|
||||
if (parts.length >= 2) {
|
||||
// For *.localhost or *.local, use the full hostname with leading dot
|
||||
if (hostname.endsWith('.localhost') || hostname.endsWith('.local')) {
|
||||
// For *.localhost, use .localhost (reserved TLD)
|
||||
if (hostname.endsWith('.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)
|
||||
return `.${parts.slice(-2).join('.')}`;
|
||||
}
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
import type {
|
||||
Contact,
|
||||
Prisma,
|
||||
Template,
|
||||
Workflow,
|
||||
WorkflowExecution,
|
||||
WorkflowStep,
|
||||
WorkflowStepExecution,
|
||||
Template,
|
||||
Workflow,
|
||||
} from '@plunk/db';
|
||||
import {StepExecutionStatus, WorkflowExecutionStatus} from '@plunk/db';
|
||||
import {WorkflowStepConfigSchemas, renderTemplate} from '@plunk/shared';
|
||||
import {toPrismaJson} from '@plunk/types';
|
||||
import {renderTemplate, WorkflowStepConfigSchemas} from '@plunk/shared';
|
||||
import dns from 'node:dns/promises';
|
||||
import net from 'node:net';
|
||||
import signale from 'signale';
|
||||
|
||||
import {prisma} from '../database/prisma.js';
|
||||
@@ -19,7 +22,6 @@ import {EmailService} from './EmailService.js';
|
||||
import {NtfyService} from './NtfyService.js';
|
||||
import {QueueService} from './QueueService.js';
|
||||
|
||||
// Type aliases for workflow execution context
|
||||
type StepConfig = Prisma.JsonValue;
|
||||
type StepResult = Record<string, unknown>;
|
||||
type WorkflowExecutionWithRelations = WorkflowExecution & {contact: Contact; workflow: Workflow};
|
||||
@@ -80,7 +82,9 @@ export class WorkflowExecutionService {
|
||||
signale.info(`[WORKFLOW] Execution ${executionId} is WAITING, resuming from delay`);
|
||||
// This is a delayed step - continue with execution
|
||||
} else if (initialExecution.status !== WorkflowExecutionStatus.RUNNING) {
|
||||
signale.info(`[WORKFLOW] Execution ${executionId} already completed or cancelled with status ${initialExecution.status}, skipping`);
|
||||
signale.info(
|
||||
`[WORKFLOW] Execution ${executionId} already completed or cancelled with status ${initialExecution.status}, skipping`,
|
||||
);
|
||||
return; // Already completed or cancelled
|
||||
}
|
||||
|
||||
@@ -241,7 +245,7 @@ export class WorkflowExecutionService {
|
||||
data: {
|
||||
status: StepExecutionStatus.COMPLETED,
|
||||
completedAt: new Date(),
|
||||
output: result ? (result as Prisma.InputJsonValue) : undefined,
|
||||
output: result ? toPrismaJson(result) : undefined,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -440,11 +444,11 @@ export class WorkflowExecutionService {
|
||||
data: {
|
||||
status: StepExecutionStatus.COMPLETED,
|
||||
completedAt: new Date(),
|
||||
output: {
|
||||
output: toPrismaJson({
|
||||
eventName,
|
||||
eventData: data ? (data as Prisma.InputJsonValue) : undefined,
|
||||
eventData: data ? toPrismaJson(data) : undefined,
|
||||
receivedAt: new Date().toISOString(),
|
||||
} as Prisma.InputJsonValue,
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -517,18 +521,22 @@ 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(
|
||||
step: WorkflowStepWithTemplate,
|
||||
execution: WorkflowExecutionWithRelations,
|
||||
stepExecution: WorkflowStepExecution,
|
||||
_config: StepConfig,
|
||||
config: StepConfig,
|
||||
): Promise<StepResult> {
|
||||
if (!step.template) {
|
||||
throw new Error('No template configured for SEND_EMAIL step');
|
||||
}
|
||||
|
||||
// Parse and validate step config using schema
|
||||
const stepConfig = WorkflowStepConfigSchemas.sendEmail.parse(config);
|
||||
const recipientConfig = stepConfig.recipient || {type: 'CONTACT' as const};
|
||||
|
||||
// Get contact data for variable substitution
|
||||
const contact = execution.contact;
|
||||
const contactData =
|
||||
@@ -543,6 +551,7 @@ export class WorkflowExecutionService {
|
||||
: {};
|
||||
|
||||
const variables = {
|
||||
id: contact.id,
|
||||
email: contact.email,
|
||||
...contactData,
|
||||
...executionContext,
|
||||
@@ -555,10 +564,14 @@ export class WorkflowExecutionService {
|
||||
const renderedSubject = this.renderTemplate(step.template.subject, variables);
|
||||
const renderedBody = this.renderTemplate(step.template.body, variables);
|
||||
|
||||
// Determine recipient email
|
||||
// Schema validation ensures customEmail exists when type is CUSTOM
|
||||
const recipientEmail = recipientConfig.type === 'CUSTOM' ? recipientConfig.customEmail! : contact.email;
|
||||
|
||||
// Send email via EmailService
|
||||
const email = await EmailService.sendWorkflowEmail({
|
||||
projectId: execution.workflow.projectId,
|
||||
contactId: contact.id,
|
||||
contactId: contact.id, // Keep original contact for tracking
|
||||
workflowExecutionId: execution.id,
|
||||
workflowStepExecutionId: stepExecution.id, // Use stepExecution.id, not step.id
|
||||
templateId: step.template.id,
|
||||
@@ -567,11 +580,15 @@ export class WorkflowExecutionService {
|
||||
from: step.template.from,
|
||||
fromName: step.template.fromName || undefined,
|
||||
replyTo: step.template.replyTo || undefined,
|
||||
// Pass custom recipient email if specified
|
||||
recipientEmail: recipientConfig.type === 'CUSTOM' ? recipientConfig.customEmail : undefined,
|
||||
});
|
||||
|
||||
return {
|
||||
emailId: email.id,
|
||||
sentAt: email.createdAt,
|
||||
recipientType: recipientConfig.type,
|
||||
recipientEmail,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -703,7 +720,7 @@ export class WorkflowExecutionService {
|
||||
_stepExecution: WorkflowStepExecution,
|
||||
config: StepConfig,
|
||||
): Promise<StepResult> {
|
||||
const {field, operator, value} = WorkflowStepConfigSchemas.condition.parse(config);
|
||||
const parsed = WorkflowStepConfigSchemas.condition.parse(config);
|
||||
|
||||
// Get the value to evaluate
|
||||
const contact = execution.contact;
|
||||
@@ -719,7 +736,7 @@ export class WorkflowExecutionService {
|
||||
// - data.firstName, data.lastName, etc.
|
||||
// - workflow.* (execution context - alias for event data)
|
||||
// - event.* (event data that triggered the workflow)
|
||||
const actualValue = this.resolveField(field, {
|
||||
const fieldData = {
|
||||
contact: {
|
||||
email: contact.email,
|
||||
subscribed: contact.subscribed,
|
||||
@@ -727,16 +744,47 @@ export class WorkflowExecutionService {
|
||||
data: contactData,
|
||||
workflow: context,
|
||||
event: context, // Alias for easier access to event data
|
||||
});
|
||||
};
|
||||
|
||||
// Evaluate the condition
|
||||
// Multi-branch mode (switch/case)
|
||||
if ('mode' in parsed && parsed.mode === 'multi') {
|
||||
const actualValue = this.resolveField(parsed.field, fieldData);
|
||||
|
||||
for (const branch of parsed.branches) {
|
||||
if (this.evaluateCondition(actualValue, branch.operator, branch.value)) {
|
||||
return {
|
||||
field: parsed.field,
|
||||
mode: 'multi',
|
||||
matchedBranch: branch.name,
|
||||
actualValue,
|
||||
branch: branch.id,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// No branch matched — use default
|
||||
return {
|
||||
field: parsed.field,
|
||||
mode: 'multi',
|
||||
matchedBranch: 'default',
|
||||
actualValue,
|
||||
branch: 'default',
|
||||
};
|
||||
}
|
||||
|
||||
// Legacy binary mode (if/else)
|
||||
const field = parsed.field;
|
||||
const operator = 'operator' in parsed ? parsed.operator : 'equals';
|
||||
const value = 'value' in parsed ? parsed.value : undefined;
|
||||
const actualValue = this.resolveField(field, fieldData);
|
||||
const result = this.evaluateCondition(actualValue, operator, value);
|
||||
|
||||
return {
|
||||
field,
|
||||
operator,
|
||||
expectedValue: value,
|
||||
actualValue,
|
||||
// Convert undefined to null so it's preserved in JSON (JSON.stringify removes undefined)
|
||||
actualValue: actualValue === undefined ? null : actualValue,
|
||||
result,
|
||||
branch: result ? 'yes' : 'no',
|
||||
};
|
||||
@@ -777,7 +825,97 @@ export class WorkflowExecutionService {
|
||||
}
|
||||
|
||||
/**
|
||||
* WEBHOOK step - Call an external webhook
|
||||
* Validates that an IP address is not in a private/reserved range to prevent SSRF.
|
||||
* Blocks loopback, private, link-local, and cloud metadata ranges.
|
||||
*/
|
||||
private static isPrivateIp(ip: string): boolean {
|
||||
// Normalize IPv6-mapped IPv4 (e.g. ::ffff:192.168.1.1)
|
||||
const addr = ip.startsWith('::ffff:') ? ip.slice(7) : ip;
|
||||
|
||||
if (net.isIPv4(addr)) {
|
||||
const parts = addr.split('.').map(Number);
|
||||
const a = parts[0] ?? -1;
|
||||
const b = parts[1] ?? -1;
|
||||
|
||||
return (
|
||||
a === 127 || // 127.0.0.0/8 loopback
|
||||
a === 10 || // 10.0.0.0/8 private
|
||||
(a === 172 && b >= 16 && b <= 31) || // 172.16.0.0/12 private
|
||||
(a === 192 && b === 168) || // 192.168.0.0/16 private
|
||||
(a === 169 && b === 254) || // 169.254.0.0/16 link-local / cloud metadata
|
||||
(a === 100 && b >= 64 && b <= 127) || // 100.64.0.0/10 shared address space
|
||||
a === 0 || // 0.0.0.0/8
|
||||
a >= 224 // 224.0.0.0+ multicast and reserved
|
||||
);
|
||||
}
|
||||
|
||||
if (net.isIPv6(addr)) {
|
||||
const normalized = addr.toLowerCase();
|
||||
return (
|
||||
normalized === '::1' || // loopback
|
||||
normalized.startsWith('fe80:') || // link-local
|
||||
normalized.startsWith('fc') || // unique local
|
||||
normalized.startsWith('fd') || // unique local
|
||||
normalized.startsWith('ff') // multicast
|
||||
);
|
||||
}
|
||||
|
||||
// Unknown format — reject to be safe
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* SSRF-safe fetch. Resolves the hostname, validates the IP is not internal,
|
||||
* and manually follows redirects re-validating each hop.
|
||||
*/
|
||||
private static async safeFetch(url: string, options: RequestInit): Promise<Response> {
|
||||
const MAX_REDIRECTS = 5;
|
||||
let currentUrl = url;
|
||||
|
||||
for (let redirects = 0; redirects <= MAX_REDIRECTS; redirects++) {
|
||||
const parsed = new URL(currentUrl);
|
||||
|
||||
if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
|
||||
throw new Error(`Webhook URL scheme not allowed: ${parsed.protocol}`);
|
||||
}
|
||||
|
||||
const {address} = await dns.lookup(parsed.hostname);
|
||||
|
||||
if (WorkflowExecutionService.isPrivateIp(address)) {
|
||||
throw new Error(`Webhook URL resolves to a private/internal IP address: ${address}`);
|
||||
}
|
||||
|
||||
const response = await fetch(currentUrl, {
|
||||
...options,
|
||||
redirect: 'manual',
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
});
|
||||
|
||||
if (response.status >= 300 && response.status < 400) {
|
||||
const location = response.headers.get('location');
|
||||
if (!location) {
|
||||
throw new Error('Redirect with no Location header');
|
||||
}
|
||||
// Resolve relative redirects against the current URL
|
||||
currentUrl = new URL(location, currentUrl).toString();
|
||||
continue;
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
throw new Error('Too many redirects');
|
||||
}
|
||||
|
||||
/**
|
||||
* WEBHOOK step - Call an external webhook.
|
||||
*
|
||||
* Renders `{{vars}}` in `url`, header values, and `body`. The variable
|
||||
* scope is a superset of the SEND_EMAIL scope: id, email, contact data,
|
||||
* execution context, and subscribe/unsubscribe/manage URLs — plus a
|
||||
* webhook-only `event` namespace exposing the trigger event payload.
|
||||
* `method` is intentionally NOT rendered — it must remain a literal
|
||||
* HTTP verb.
|
||||
*/
|
||||
private static async executeWebhook(
|
||||
_step: WorkflowStep,
|
||||
@@ -793,9 +931,37 @@ export class WorkflowExecutionService {
|
||||
contact.data && typeof contact.data === 'object' && !Array.isArray(contact.data)
|
||||
? (contact.data as Record<string, unknown>)
|
||||
: {};
|
||||
const executionContext =
|
||||
execution.context && typeof execution.context === 'object' && !Array.isArray(execution.context)
|
||||
? (execution.context as Record<string, unknown>)
|
||||
: {};
|
||||
const context = execution.context || {};
|
||||
|
||||
const payload = body || {
|
||||
// Render scope: SEND_EMAIL's scope (id, email, contact data, execution
|
||||
// context, subscribe/unsubscribe/manage URLs) plus a webhook-only
|
||||
// `event` namespace carrying the trigger event payload. `method` is
|
||||
// intentionally NOT rendered — it must remain a literal HTTP verb.
|
||||
const variables = {
|
||||
id: contact.id,
|
||||
email: contact.email,
|
||||
...contactData,
|
||||
...executionContext,
|
||||
data: contactData,
|
||||
event: context,
|
||||
unsubscribeUrl: `${DASHBOARD_URI}/unsubscribe/${contact.id}`,
|
||||
subscribeUrl: `${DASHBOARD_URI}/subscribe/${contact.id}`,
|
||||
manageUrl: `${DASHBOARD_URI}/manage/${contact.id}`,
|
||||
};
|
||||
|
||||
const renderedUrl = this.renderTemplate(url, variables);
|
||||
const renderedHeaders = headers
|
||||
? Object.fromEntries(
|
||||
Object.entries(headers).map(([key, value]) => [key, this.renderTemplate(value, variables)]),
|
||||
)
|
||||
: undefined;
|
||||
const renderedBody = body ? this.renderJsonTemplate(body, variables) : undefined;
|
||||
|
||||
const payload = renderedBody || {
|
||||
contact: {
|
||||
email: contact.email,
|
||||
subscribed: contact.subscribed,
|
||||
@@ -813,11 +979,11 @@ export class WorkflowExecutionService {
|
||||
};
|
||||
|
||||
// Make HTTP request
|
||||
const response = await fetch(url, {
|
||||
const response = await WorkflowExecutionService.safeFetch(renderedUrl, {
|
||||
method,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...headers,
|
||||
...renderedHeaders,
|
||||
},
|
||||
body: method !== 'GET' ? JSON.stringify(payload) : undefined,
|
||||
});
|
||||
@@ -831,7 +997,7 @@ export class WorkflowExecutionService {
|
||||
}
|
||||
|
||||
return {
|
||||
url,
|
||||
url: renderedUrl,
|
||||
method,
|
||||
statusCode: response.status,
|
||||
success: response.ok,
|
||||
@@ -839,6 +1005,28 @@ export class WorkflowExecutionService {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper: Recursively render template variables in any JSON-shaped value.
|
||||
* Strings are rendered, arrays/objects are walked, and non-string scalars
|
||||
* (numbers, booleans, null) are returned untouched.
|
||||
*/
|
||||
private static renderJsonTemplate(value: unknown, variables: Record<string, unknown>): unknown {
|
||||
if (typeof value === 'string') {
|
||||
return this.renderTemplate(value, variables);
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return value.map(item => this.renderJsonTemplate(item, variables));
|
||||
}
|
||||
if (value !== null && typeof value === 'object') {
|
||||
const result: Record<string, unknown> = {};
|
||||
for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
|
||||
result[key] = this.renderJsonTemplate(child, variables);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* UPDATE_CONTACT step - Update contact data
|
||||
*/
|
||||
@@ -848,7 +1036,7 @@ export class WorkflowExecutionService {
|
||||
_stepExecution: WorkflowStepExecution,
|
||||
config: StepConfig,
|
||||
): Promise<StepResult> {
|
||||
const {updates} = WorkflowStepConfigSchemas.updateContact.parse(config);
|
||||
const {updates, subscriptionAction} = WorkflowStepConfigSchemas.updateContact.parse(config);
|
||||
|
||||
const contact = execution.contact;
|
||||
const currentData =
|
||||
@@ -856,24 +1044,43 @@ export class WorkflowExecutionService {
|
||||
? (contact.data as Record<string, unknown>)
|
||||
: {};
|
||||
|
||||
// Merge updates with current data
|
||||
const newData = {
|
||||
...currentData,
|
||||
...updates,
|
||||
};
|
||||
const hasDataUpdates = updates && Object.keys(updates).length > 0;
|
||||
const newData = hasDataUpdates ? {...currentData, ...updates} : currentData;
|
||||
|
||||
// Update contact in database
|
||||
await prisma.contact.update({
|
||||
where: {id: contact.id},
|
||||
data: {
|
||||
data: newData ? (newData as Prisma.InputJsonValue) : undefined,
|
||||
},
|
||||
});
|
||||
const desiredSubscribed =
|
||||
subscriptionAction === 'subscribe' ? true : subscriptionAction === 'unsubscribe' ? false : undefined;
|
||||
const subscriptionChanging = desiredSubscribed !== undefined && desiredSubscribed !== contact.subscribed;
|
||||
|
||||
const updateData: Prisma.ContactUpdateInput = {};
|
||||
if (hasDataUpdates) {
|
||||
updateData.data = toPrismaJson(newData);
|
||||
}
|
||||
if (subscriptionChanging) {
|
||||
updateData.subscribed = desiredSubscribed;
|
||||
}
|
||||
|
||||
if (Object.keys(updateData).length > 0) {
|
||||
await prisma.contact.update({
|
||||
where: {id: contact.id},
|
||||
data: updateData,
|
||||
});
|
||||
}
|
||||
|
||||
if (subscriptionChanging) {
|
||||
const {EventService} = await import('./EventService.js');
|
||||
await EventService.trackEvent(
|
||||
execution.workflow.projectId,
|
||||
desiredSubscribed ? 'contact.subscribed' : 'contact.unsubscribed',
|
||||
contact.id,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
updated: true,
|
||||
updated: hasDataUpdates || subscriptionChanging,
|
||||
updates,
|
||||
newData,
|
||||
subscriptionAction,
|
||||
subscribed: desiredSubscribed ?? contact.subscribed,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -972,7 +1179,15 @@ export class WorkflowExecutionService {
|
||||
* Helper: Resolve field value from object using dot notation
|
||||
*/
|
||||
private static resolveField(field: string, data: Record<string, unknown>): unknown {
|
||||
const parts = field.split('.');
|
||||
// Handle legacy "contact.data.X" format by converting to "data.X"
|
||||
// The UI historically showed examples like "contact.data.plan" but the field structure
|
||||
// has "data" as a top-level key, not nested under "contact"
|
||||
let normalizedField = field;
|
||||
if (field.startsWith('contact.data.')) {
|
||||
normalizedField = field.substring(8); // Remove "contact." prefix, leaving "data.X"
|
||||
}
|
||||
|
||||
const parts = normalizedField.split('.');
|
||||
let value: unknown = data;
|
||||
|
||||
for (const part of parts) {
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import type {Workflow, WorkflowExecution, WorkflowStep, WorkflowStepExecution, WorkflowTransition} from '@plunk/db';
|
||||
import type {Workflow, WorkflowExecution, WorkflowStep, WorkflowTransition} from '@plunk/db';
|
||||
import {Prisma, WorkflowExecutionStatus} from '@plunk/db';
|
||||
import type {PaginatedResponse, WorkflowExecutionWithDetails, WorkflowWithDetails} from '@plunk/types';
|
||||
import {toPrismaJson} from '@plunk/types';
|
||||
import signale from 'signale';
|
||||
|
||||
import {prisma} from '../database/prisma.js';
|
||||
@@ -10,34 +12,16 @@ import {EventService} from './EventService.js';
|
||||
import {NtfyService} from './NtfyService.js';
|
||||
import {WorkflowExecutionService} from './WorkflowExecutionService.js';
|
||||
|
||||
export interface PaginatedWorkflows {
|
||||
workflows: Workflow[];
|
||||
total: number;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
totalPages: number;
|
||||
}
|
||||
|
||||
export interface WorkflowWithDetails extends Workflow {
|
||||
steps: (WorkflowStep & {
|
||||
template?: {id: string; name: string} | null;
|
||||
outgoingTransitions: WorkflowTransition[];
|
||||
incomingTransitions: WorkflowTransition[];
|
||||
})[];
|
||||
}
|
||||
|
||||
export interface WorkflowExecutionWithDetails extends WorkflowExecution {
|
||||
workflow: Workflow;
|
||||
contact: {id: string; email: string};
|
||||
currentStep?: WorkflowStep | null;
|
||||
stepExecutions: WorkflowStepExecution[];
|
||||
}
|
||||
|
||||
export class WorkflowService {
|
||||
/**
|
||||
* Get all workflows for a project with pagination
|
||||
*/
|
||||
public static async list(projectId: string, page = 1, pageSize = 20, search?: string): Promise<PaginatedWorkflows> {
|
||||
public static async list(
|
||||
projectId: string,
|
||||
page = 1,
|
||||
pageSize = 20,
|
||||
search?: string,
|
||||
): Promise<PaginatedResponse<Workflow>> {
|
||||
const skip = (page - 1) * pageSize;
|
||||
|
||||
const where: Prisma.WorkflowWhereInput = {
|
||||
@@ -71,7 +55,7 @@ export class WorkflowService {
|
||||
]);
|
||||
|
||||
return {
|
||||
workflows: workflows as Workflow[],
|
||||
data: workflows as Workflow[],
|
||||
total,
|
||||
page,
|
||||
pageSize,
|
||||
@@ -210,25 +194,57 @@ export class WorkflowService {
|
||||
}
|
||||
}
|
||||
|
||||
const updateData: Prisma.WorkflowUpdateInput = {};
|
||||
// Use transaction to update workflow and TRIGGER step atomically
|
||||
const updated = await prisma.$transaction(async tx => {
|
||||
const updateData: Prisma.WorkflowUpdateInput = {};
|
||||
|
||||
if (data.name !== undefined) updateData.name = data.name;
|
||||
if (data.description !== undefined) updateData.description = data.description;
|
||||
if (data.triggerType !== undefined) updateData.triggerType = data.triggerType;
|
||||
if (data.triggerConfig !== undefined) {
|
||||
updateData.triggerConfig = data.triggerConfig === null ? Prisma.JsonNull : data.triggerConfig;
|
||||
}
|
||||
if (data.enabled !== undefined) updateData.enabled = data.enabled;
|
||||
if (data.allowReentry !== undefined) updateData.allowReentry = data.allowReentry;
|
||||
if (data.name !== undefined) updateData.name = data.name;
|
||||
if (data.description !== undefined) updateData.description = data.description;
|
||||
if (data.triggerType !== undefined) updateData.triggerType = data.triggerType;
|
||||
if (data.triggerConfig !== undefined) {
|
||||
updateData.triggerConfig = data.triggerConfig === null ? Prisma.JsonNull : data.triggerConfig;
|
||||
}
|
||||
if (data.enabled !== undefined) updateData.enabled = data.enabled;
|
||||
if (data.allowReentry !== undefined) updateData.allowReentry = data.allowReentry;
|
||||
|
||||
const updated = await prisma.workflow.update({
|
||||
where: {id: workflowId},
|
||||
data: updateData,
|
||||
include: {
|
||||
project: {
|
||||
select: {name: true},
|
||||
const updatedWorkflow = await tx.workflow.update({
|
||||
where: {id: workflowId},
|
||||
data: updateData,
|
||||
include: {
|
||||
project: {
|
||||
select: {name: true},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// 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
|
||||
@@ -236,6 +252,11 @@ export class WorkflowService {
|
||||
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
|
||||
if (data.enabled !== undefined && data.enabled !== workflow.enabled) {
|
||||
if (data.enabled) {
|
||||
@@ -289,6 +310,72 @@ export class WorkflowService {
|
||||
await NtfyService.notifyWorkflowDeleted(workflow.name, workflow.project.name, projectId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Duplicate a workflow including all steps and transitions.
|
||||
* The duplicate always starts disabled to prevent accidental triggering.
|
||||
* Runtime execution state is intentionally not copied.
|
||||
*/
|
||||
public static async duplicate(projectId: string, workflowId: string): Promise<Workflow> {
|
||||
const source = await this.get(projectId, workflowId);
|
||||
|
||||
const transitions = await prisma.workflowTransition.findMany({
|
||||
where: {fromStep: {workflowId}},
|
||||
});
|
||||
|
||||
return prisma.$transaction(async tx => {
|
||||
const newWorkflow = await tx.workflow.create({
|
||||
data: {
|
||||
projectId,
|
||||
name: `${source.name} (Copy)`,
|
||||
description: source.description,
|
||||
triggerType: source.triggerType,
|
||||
triggerConfig:
|
||||
source.triggerConfig === null
|
||||
? Prisma.JsonNull
|
||||
: (source.triggerConfig as Prisma.InputJsonValue),
|
||||
enabled: false,
|
||||
allowReentry: source.allowReentry,
|
||||
},
|
||||
});
|
||||
|
||||
const stepIdMap = new Map<string, string>();
|
||||
|
||||
for (const step of source.steps) {
|
||||
const created = await tx.workflowStep.create({
|
||||
data: {
|
||||
workflowId: newWorkflow.id,
|
||||
type: step.type,
|
||||
name: step.name,
|
||||
position: step.position as Prisma.InputJsonValue,
|
||||
config: step.config as Prisma.InputJsonValue,
|
||||
templateId: step.templateId,
|
||||
},
|
||||
});
|
||||
stepIdMap.set(step.id, created.id);
|
||||
}
|
||||
|
||||
for (const transition of transitions) {
|
||||
const fromStepId = stepIdMap.get(transition.fromStepId);
|
||||
const toStepId = stepIdMap.get(transition.toStepId);
|
||||
if (!fromStepId || !toStepId) continue;
|
||||
|
||||
await tx.workflowTransition.create({
|
||||
data: {
|
||||
fromStepId,
|
||||
toStepId,
|
||||
condition:
|
||||
transition.condition === null
|
||||
? Prisma.JsonNull
|
||||
: (transition.condition as Prisma.InputJsonValue),
|
||||
priority: transition.priority,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return newWorkflow;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a step to a workflow
|
||||
*/
|
||||
@@ -321,8 +408,8 @@ export class WorkflowService {
|
||||
workflowId,
|
||||
type: data.type,
|
||||
name: data.name,
|
||||
position: data.position as Prisma.InputJsonValue,
|
||||
config: data.config as Prisma.InputJsonValue,
|
||||
position: toPrismaJson(data.position),
|
||||
config: toPrismaJson(data.config),
|
||||
templateId: data.templateId,
|
||||
},
|
||||
});
|
||||
@@ -403,8 +490,8 @@ export class WorkflowService {
|
||||
const updateData: Prisma.WorkflowStepUpdateInput = {};
|
||||
|
||||
if (data.name !== undefined) updateData.name = data.name;
|
||||
if (data.position !== undefined) updateData.position = data.position as Prisma.InputJsonValue;
|
||||
if (data.config !== undefined) updateData.config = data.config as Prisma.InputJsonValue;
|
||||
if (data.position !== undefined) updateData.position = toPrismaJson(data.position);
|
||||
if (data.config !== undefined) updateData.config = toPrismaJson(data.config);
|
||||
if (data.templateId !== undefined) {
|
||||
if (data.templateId === null) {
|
||||
updateData.template = {disconnect: true};
|
||||
@@ -555,6 +642,66 @@ export class WorkflowService {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Splice a step out of the flow: re-wire its parent(s) directly to its child,
|
||||
* then delete only the step itself. Not allowed for CONDITION or TRIGGER steps.
|
||||
*/
|
||||
public static async spliceStep(projectId: string, workflowId: string, stepId: string): Promise<void> {
|
||||
await this.get(projectId, workflowId);
|
||||
|
||||
const step = await prisma.workflowStep.findUnique({
|
||||
where: {id: stepId},
|
||||
include: {
|
||||
outgoingTransitions: true,
|
||||
incomingTransitions: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (step?.workflowId !== workflowId) {
|
||||
throw new HttpException(404, 'Workflow step not found');
|
||||
}
|
||||
|
||||
if (step.type === 'TRIGGER') {
|
||||
throw new HttpException(400, 'Cannot remove the trigger step.');
|
||||
}
|
||||
|
||||
if (step.type === 'CONDITION') {
|
||||
throw new HttpException(400, 'Cannot splice a condition step out of the flow.');
|
||||
}
|
||||
|
||||
// Check for active executions on this step
|
||||
const executionsOnStep = await prisma.workflowExecution.count({
|
||||
where: {
|
||||
workflowId,
|
||||
currentStepId: stepId,
|
||||
status: {in: [WorkflowExecutionStatus.RUNNING, WorkflowExecutionStatus.WAITING]},
|
||||
},
|
||||
});
|
||||
|
||||
if (executionsOnStep > 0) {
|
||||
throw new HttpException(
|
||||
409,
|
||||
`Cannot remove step "${step.name}" while ${executionsOnStep} execution(s) are currently on it. ` +
|
||||
'Please disable the workflow first or wait for executions to complete.',
|
||||
);
|
||||
}
|
||||
|
||||
// Re-wire: for each incoming transition, point it to our child (if we have one)
|
||||
const child = step.outgoingTransitions[0];
|
||||
|
||||
if (child) {
|
||||
for (const incoming of step.incomingTransitions) {
|
||||
await prisma.workflowTransition.update({
|
||||
where: {id: incoming.id},
|
||||
data: {toStepId: child.toStepId},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Delete the step — cascades and removes its own transitions
|
||||
await prisma.workflowStep.delete({where: {id: stepId}});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a transition between two steps
|
||||
*/
|
||||
@@ -596,7 +743,7 @@ export class WorkflowService {
|
||||
fromStepId: data.fromStepId,
|
||||
condition: {
|
||||
path: ['branch'],
|
||||
equals: conditionObj.branch as Prisma.InputJsonValue,
|
||||
equals: toPrismaJson(conditionObj.branch),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {describe, it, expect, beforeEach, vi} from 'vitest';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {EmailSourceType} from '@plunk/db';
|
||||
import {BillingLimitService} from '../BillingLimitService';
|
||||
import {EmailService} from '../EmailService';
|
||||
@@ -320,7 +320,10 @@ describe('BillingLimitService - Critical Enforcement', () => {
|
||||
data: {billingLimitCampaigns: 10},
|
||||
});
|
||||
|
||||
// Create a date in the previous month
|
||||
// Set day to 1 first to avoid month overflow issues (e.g., Jan 31 -> Feb 31 = Mar 3)
|
||||
const lastMonth = new Date();
|
||||
lastMonth.setDate(1);
|
||||
lastMonth.setMonth(lastMonth.getMonth() - 1);
|
||||
|
||||
await prisma.email.create({
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import {describe, it, expect, beforeEach, vi} from 'vitest';
|
||||
import {CampaignStatus, CampaignAudienceType} from '@plunk/db';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {CampaignAudienceType, CampaignStatus} from '@plunk/db';
|
||||
import {CampaignService} from '../CampaignService';
|
||||
import {factories, getPrismaClient} from '../../../../../test/helpers';
|
||||
|
||||
@@ -164,7 +164,7 @@ describe('CampaignService', () => {
|
||||
|
||||
const result = await CampaignService.list(projectId, {page: 1, pageSize: 10});
|
||||
|
||||
expect(result.campaigns).toHaveLength(10);
|
||||
expect(result.data).toHaveLength(10);
|
||||
expect(result.total).toBe(25);
|
||||
expect(result.totalPages).toBe(3);
|
||||
expect(result.page).toBe(1);
|
||||
@@ -177,8 +177,8 @@ describe('CampaignService', () => {
|
||||
|
||||
const result = await CampaignService.list(projectId, {status: CampaignStatus.DRAFT});
|
||||
|
||||
expect(result.campaigns).toHaveLength(2);
|
||||
expect(result.campaigns.every(c => c.status === CampaignStatus.DRAFT)).toBe(true);
|
||||
expect(result.data).toHaveLength(2);
|
||||
expect(result.data.every(c => c.status === CampaignStatus.DRAFT)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {describe, it, expect, beforeEach} from 'vitest';
|
||||
import {beforeEach, describe, expect, it} from 'vitest';
|
||||
import {ContactService} from '../ContactService';
|
||||
import {factories, getPrismaClient} from '../../../../../test/helpers';
|
||||
|
||||
@@ -336,19 +336,75 @@ describe('ContactService - Duplicate Prevention & Data Merging', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle null values in data', async () => {
|
||||
it('should delete keys when null value is passed', async () => {
|
||||
const email = 'test@example.com';
|
||||
|
||||
const contact = await ContactService.upsert(projectId, email, {
|
||||
firstName: 'John',
|
||||
middleName: null,
|
||||
middleName: null, // null should delete/not store the key
|
||||
lastName: 'Doe',
|
||||
});
|
||||
|
||||
expect(contact.data).toHaveProperty('firstName', 'John');
|
||||
expect(contact.data).toHaveProperty('middleName', null);
|
||||
expect(contact.data).not.toHaveProperty('middleName'); // Key should not exist
|
||||
expect(contact.data).toHaveProperty('lastName', 'Doe');
|
||||
});
|
||||
|
||||
it('should remove existing fields when null is passed', async () => {
|
||||
const email = 'test@example.com';
|
||||
|
||||
// Create contact with data
|
||||
await ContactService.upsert(projectId, email, {
|
||||
firstName: 'John',
|
||||
middleName: 'Michael',
|
||||
lastName: 'Doe',
|
||||
});
|
||||
|
||||
// Update with null to remove middleName
|
||||
const updated = await ContactService.upsert(projectId, email, {
|
||||
middleName: null, // Should delete this field
|
||||
});
|
||||
|
||||
expect(updated.data).toHaveProperty('firstName', 'John'); // Preserved
|
||||
expect(updated.data).not.toHaveProperty('middleName'); // Removed
|
||||
expect(updated.data).toHaveProperty('lastName', 'Doe'); // Preserved
|
||||
});
|
||||
|
||||
it('should filter out empty string values from data', async () => {
|
||||
const email = 'test@example.com';
|
||||
|
||||
const contact = await ContactService.upsert(projectId, email, {
|
||||
firstName: 'John',
|
||||
middleName: '', // Empty string should be filtered out
|
||||
lastName: 'Doe',
|
||||
company: '', // Empty string should be filtered out
|
||||
});
|
||||
|
||||
expect(contact.data).toHaveProperty('firstName', 'John');
|
||||
expect(contact.data).toHaveProperty('lastName', 'Doe');
|
||||
expect(contact.data).not.toHaveProperty('middleName');
|
||||
expect(contact.data).not.toHaveProperty('company');
|
||||
});
|
||||
|
||||
it('should not overwrite existing data with empty strings', async () => {
|
||||
const email = 'test@example.com';
|
||||
|
||||
// Create contact with data
|
||||
await ContactService.upsert(projectId, email, {
|
||||
firstName: 'John',
|
||||
company: 'Acme Inc',
|
||||
});
|
||||
|
||||
// Update with empty string - should preserve existing values
|
||||
const updated = await ContactService.upsert(projectId, email, {
|
||||
firstName: '', // Should be filtered out, preserving "John"
|
||||
lastName: 'Doe',
|
||||
});
|
||||
|
||||
expect(updated.data).toHaveProperty('firstName', 'John'); // Preserved
|
||||
expect(updated.data).toHaveProperty('company', 'Acme Inc'); // Preserved
|
||||
expect(updated.data).toHaveProperty('lastName', 'Doe'); // New value
|
||||
});
|
||||
});
|
||||
|
||||
describe('Contact CRUD Operations', () => {
|
||||
@@ -439,4 +495,266 @@ describe('ContactService - Duplicate Prevention & Data Merging', () => {
|
||||
expect(unsubscribed?.subscribed).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Bulk Contact Operations', () => {
|
||||
describe('bulkSubscribe', () => {
|
||||
it('should subscribe multiple unsubscribed contacts', async () => {
|
||||
const contact1 = await factories.createContact({projectId, subscribed: false});
|
||||
const contact2 = await factories.createContact({projectId, subscribed: false});
|
||||
const contact3 = await factories.createContact({projectId, subscribed: false});
|
||||
|
||||
const result = await ContactService.bulkSubscribe(projectId, [contact1.id, contact2.id, contact3.id]);
|
||||
|
||||
expect(result.updated).toBe(3);
|
||||
|
||||
const contacts = await prisma.contact.findMany({
|
||||
where: {id: {in: [contact1.id, contact2.id, contact3.id]}},
|
||||
});
|
||||
|
||||
expect(contacts.every(c => c.subscribed)).toBe(true);
|
||||
});
|
||||
|
||||
it('should only update unsubscribed contacts, not already subscribed ones', async () => {
|
||||
const unsubscribed1 = await factories.createContact({projectId, subscribed: false});
|
||||
const unsubscribed2 = await factories.createContact({projectId, subscribed: false});
|
||||
const alreadySubscribed = await factories.createContact({projectId, subscribed: true});
|
||||
|
||||
const result = await ContactService.bulkSubscribe(projectId, [
|
||||
unsubscribed1.id,
|
||||
unsubscribed2.id,
|
||||
alreadySubscribed.id,
|
||||
]);
|
||||
|
||||
expect(result.updated).toBe(2);
|
||||
});
|
||||
|
||||
it('should return 0 if no contacts need updating', async () => {
|
||||
const contact1 = await factories.createContact({projectId, subscribed: true});
|
||||
const contact2 = await factories.createContact({projectId, subscribed: true});
|
||||
|
||||
const result = await ContactService.bulkSubscribe(projectId, [contact1.id, contact2.id]);
|
||||
|
||||
expect(result.updated).toBe(0);
|
||||
});
|
||||
|
||||
it('should only update contacts belonging to the specified project', async () => {
|
||||
const {project: otherProject} = await factories.createUserWithProject();
|
||||
const ownContact = await factories.createContact({projectId, subscribed: false});
|
||||
const otherContact = await factories.createContact({projectId: otherProject.id, subscribed: false});
|
||||
|
||||
const result = await ContactService.bulkSubscribe(projectId, [ownContact.id, otherContact.id]);
|
||||
|
||||
expect(result.updated).toBe(1);
|
||||
|
||||
const ownContactAfter = await prisma.contact.findUnique({where: {id: ownContact.id}});
|
||||
const otherContactAfter = await prisma.contact.findUnique({where: {id: otherContact.id}});
|
||||
|
||||
expect(ownContactAfter?.subscribed).toBe(true);
|
||||
expect(otherContactAfter?.subscribed).toBe(false);
|
||||
});
|
||||
|
||||
it('should handle empty contact IDs array', async () => {
|
||||
const result = await ContactService.bulkSubscribe(projectId, []);
|
||||
|
||||
expect(result.updated).toBe(0);
|
||||
});
|
||||
|
||||
it('should handle non-existent contact IDs gracefully', async () => {
|
||||
const result = await ContactService.bulkSubscribe(projectId, ['non-existent-1', 'non-existent-2']);
|
||||
|
||||
expect(result.updated).toBe(0);
|
||||
});
|
||||
|
||||
it('should handle large batches efficiently', async () => {
|
||||
const contacts = await Promise.all(
|
||||
Array.from({length: 150}, () => factories.createContact({projectId, subscribed: false})),
|
||||
);
|
||||
const contactIds = contacts.map(c => c.id);
|
||||
|
||||
const result = await ContactService.bulkSubscribe(projectId, contactIds);
|
||||
|
||||
expect(result.updated).toBe(150);
|
||||
|
||||
const updatedContacts = await prisma.contact.findMany({
|
||||
where: {id: {in: contactIds}},
|
||||
});
|
||||
|
||||
expect(updatedContacts.every(c => c.subscribed)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('bulkUnsubscribe', () => {
|
||||
it('should unsubscribe multiple subscribed contacts', async () => {
|
||||
const contact1 = await factories.createContact({projectId, subscribed: true});
|
||||
const contact2 = await factories.createContact({projectId, subscribed: true});
|
||||
const contact3 = await factories.createContact({projectId, subscribed: true});
|
||||
|
||||
const result = await ContactService.bulkUnsubscribe(projectId, [contact1.id, contact2.id, contact3.id]);
|
||||
|
||||
expect(result.updated).toBe(3);
|
||||
|
||||
const contacts = await prisma.contact.findMany({
|
||||
where: {id: {in: [contact1.id, contact2.id, contact3.id]}},
|
||||
});
|
||||
|
||||
expect(contacts.every(c => !c.subscribed)).toBe(true);
|
||||
});
|
||||
|
||||
it('should only update subscribed contacts, not already unsubscribed ones', async () => {
|
||||
const subscribed1 = await factories.createContact({projectId, subscribed: true});
|
||||
const subscribed2 = await factories.createContact({projectId, subscribed: true});
|
||||
const alreadyUnsubscribed = await factories.createContact({projectId, subscribed: false});
|
||||
|
||||
const result = await ContactService.bulkUnsubscribe(projectId, [
|
||||
subscribed1.id,
|
||||
subscribed2.id,
|
||||
alreadyUnsubscribed.id,
|
||||
]);
|
||||
|
||||
expect(result.updated).toBe(2);
|
||||
});
|
||||
|
||||
it('should return 0 if no contacts need updating', async () => {
|
||||
const contact1 = await factories.createContact({projectId, subscribed: false});
|
||||
const contact2 = await factories.createContact({projectId, subscribed: false});
|
||||
|
||||
const result = await ContactService.bulkUnsubscribe(projectId, [contact1.id, contact2.id]);
|
||||
|
||||
expect(result.updated).toBe(0);
|
||||
});
|
||||
|
||||
it('should only update contacts belonging to the specified project', async () => {
|
||||
const {project: otherProject} = await factories.createUserWithProject();
|
||||
const ownContact = await factories.createContact({projectId, subscribed: true});
|
||||
const otherContact = await factories.createContact({projectId: otherProject.id, subscribed: true});
|
||||
|
||||
const result = await ContactService.bulkUnsubscribe(projectId, [ownContact.id, otherContact.id]);
|
||||
|
||||
expect(result.updated).toBe(1);
|
||||
|
||||
const ownContactAfter = await prisma.contact.findUnique({where: {id: ownContact.id}});
|
||||
const otherContactAfter = await prisma.contact.findUnique({where: {id: otherContact.id}});
|
||||
|
||||
expect(ownContactAfter?.subscribed).toBe(false);
|
||||
expect(otherContactAfter?.subscribed).toBe(true);
|
||||
});
|
||||
|
||||
it('should handle empty contact IDs array', async () => {
|
||||
const result = await ContactService.bulkUnsubscribe(projectId, []);
|
||||
|
||||
expect(result.updated).toBe(0);
|
||||
});
|
||||
|
||||
it('should handle non-existent contact IDs gracefully', async () => {
|
||||
const result = await ContactService.bulkUnsubscribe(projectId, ['non-existent-1', 'non-existent-2']);
|
||||
|
||||
expect(result.updated).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('bulkDelete', () => {
|
||||
it('should delete multiple contacts', async () => {
|
||||
const contact1 = await factories.createContact({projectId});
|
||||
const contact2 = await factories.createContact({projectId});
|
||||
const contact3 = await factories.createContact({projectId});
|
||||
|
||||
const result = await ContactService.bulkDelete(projectId, [contact1.id, contact2.id, contact3.id]);
|
||||
|
||||
expect(result.deleted).toBe(3);
|
||||
|
||||
const contacts = await prisma.contact.findMany({
|
||||
where: {id: {in: [contact1.id, contact2.id, contact3.id]}},
|
||||
});
|
||||
|
||||
expect(contacts).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should only delete contacts belonging to the specified project', async () => {
|
||||
const {project: otherProject} = await factories.createUserWithProject();
|
||||
const ownContact = await factories.createContact({projectId});
|
||||
const otherContact = await factories.createContact({projectId: otherProject.id});
|
||||
|
||||
const result = await ContactService.bulkDelete(projectId, [ownContact.id, otherContact.id]);
|
||||
|
||||
expect(result.deleted).toBe(1);
|
||||
|
||||
const ownContactAfter = await prisma.contact.findUnique({where: {id: ownContact.id}});
|
||||
const otherContactAfter = await prisma.contact.findUnique({where: {id: otherContact.id}});
|
||||
|
||||
expect(ownContactAfter).toBeNull();
|
||||
expect(otherContactAfter).not.toBeNull();
|
||||
});
|
||||
|
||||
it('should handle empty contact IDs array', async () => {
|
||||
const result = await ContactService.bulkDelete(projectId, []);
|
||||
|
||||
expect(result.deleted).toBe(0);
|
||||
});
|
||||
|
||||
it('should handle non-existent contact IDs gracefully', async () => {
|
||||
const result = await ContactService.bulkDelete(projectId, ['non-existent-1', 'non-existent-2']);
|
||||
|
||||
expect(result.deleted).toBe(0);
|
||||
});
|
||||
|
||||
it('should handle large batches efficiently', async () => {
|
||||
const contacts = await Promise.all(Array.from({length: 200}, () => factories.createContact({projectId})));
|
||||
const contactIds = contacts.map(c => c.id);
|
||||
|
||||
const result = await ContactService.bulkDelete(projectId, contactIds);
|
||||
|
||||
expect(result.deleted).toBe(200);
|
||||
|
||||
const remainingContacts = await prisma.contact.findMany({
|
||||
where: {id: {in: contactIds}},
|
||||
});
|
||||
|
||||
expect(remainingContacts).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should delete both subscribed and unsubscribed contacts', async () => {
|
||||
const subscribed = await factories.createContact({projectId, subscribed: true});
|
||||
const unsubscribed = await factories.createContact({projectId, subscribed: false});
|
||||
|
||||
const result = await ContactService.bulkDelete(projectId, [subscribed.id, unsubscribed.id]);
|
||||
|
||||
expect(result.deleted).toBe(2);
|
||||
});
|
||||
|
||||
it('should handle partial matches (some exist, some do not)', async () => {
|
||||
const existingContact = await factories.createContact({projectId});
|
||||
|
||||
const result = await ContactService.bulkDelete(projectId, [existingContact.id, 'non-existent-id']);
|
||||
|
||||
expect(result.deleted).toBe(1);
|
||||
|
||||
const contact = await prisma.contact.findUnique({where: {id: existingContact.id}});
|
||||
expect(contact).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Bulk Operations - Project Isolation', () => {
|
||||
it('should never leak contacts between projects in bulk operations', async () => {
|
||||
const {project: project1} = await factories.createUserWithProject();
|
||||
const {project: project2} = await factories.createUserWithProject();
|
||||
|
||||
const p1Contact1 = await factories.createContact({projectId: project1.id, subscribed: false});
|
||||
const p1Contact2 = await factories.createContact({projectId: project1.id, subscribed: false});
|
||||
const p2Contact1 = await factories.createContact({projectId: project2.id, subscribed: false});
|
||||
const p2Contact2 = await factories.createContact({projectId: project2.id, subscribed: false});
|
||||
|
||||
await ContactService.bulkSubscribe(project1.id, [p1Contact1.id, p1Contact2.id, p2Contact1.id, p2Contact2.id]);
|
||||
|
||||
const p1ContactsAfter = await prisma.contact.findMany({
|
||||
where: {projectId: project1.id},
|
||||
});
|
||||
const p2ContactsAfter = await prisma.contact.findMany({
|
||||
where: {projectId: project2.id},
|
||||
});
|
||||
|
||||
expect(p1ContactsAfter.every(c => c.subscribed)).toBe(true);
|
||||
expect(p2ContactsAfter.every(c => !c.subscribed)).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {describe, it, expect, beforeEach, vi} from 'vitest';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {factories, getPrismaClient} from '../../../../../test/helpers';
|
||||
import {DomainService} from '../DomainService.js';
|
||||
import {HttpException} from '../../exceptions/index.js';
|
||||
@@ -110,9 +110,7 @@ describe('DomainService', () => {
|
||||
it('should throw error for invalid email format', async () => {
|
||||
const {project} = await factories.createUserWithProject();
|
||||
|
||||
await expect(DomainService.verifyEmailDomain('invalid-email', project.id)).rejects.toThrow(
|
||||
HttpException,
|
||||
);
|
||||
await expect(DomainService.verifyEmailDomain('invalid-email', project.id)).rejects.toThrow(HttpException);
|
||||
|
||||
await expect(DomainService.verifyEmailDomain('invalid-email', project.id)).rejects.toThrow(
|
||||
/invalid email format/i,
|
||||
@@ -122,13 +120,13 @@ describe('DomainService', () => {
|
||||
it('should throw error when domain is not registered', async () => {
|
||||
const {project} = await factories.createUserWithProject();
|
||||
|
||||
await expect(
|
||||
DomainService.verifyEmailDomain('sender@unregistered.com', project.id),
|
||||
).rejects.toThrow(HttpException);
|
||||
await expect(DomainService.verifyEmailDomain('sender@unregistered.com', project.id)).rejects.toThrow(
|
||||
HttpException,
|
||||
);
|
||||
|
||||
await expect(
|
||||
DomainService.verifyEmailDomain('sender@unregistered.com', project.id),
|
||||
).rejects.toThrow(/not registered/i);
|
||||
await expect(DomainService.verifyEmailDomain('sender@unregistered.com', project.id)).rejects.toThrow(
|
||||
/not registered/i,
|
||||
);
|
||||
});
|
||||
|
||||
it('should throw error when domain belongs to different project', async () => {
|
||||
@@ -141,13 +139,11 @@ describe('DomainService', () => {
|
||||
data: {verified: true},
|
||||
});
|
||||
|
||||
await expect(
|
||||
DomainService.verifyEmailDomain('sender@project1.com', project2.id),
|
||||
).rejects.toThrow(HttpException);
|
||||
await expect(DomainService.verifyEmailDomain('sender@project1.com', project2.id)).rejects.toThrow(HttpException);
|
||||
|
||||
await expect(
|
||||
DomainService.verifyEmailDomain('sender@project1.com', project2.id),
|
||||
).rejects.toThrow(/belongs to a different project/i);
|
||||
await expect(DomainService.verifyEmailDomain('sender@project1.com', project2.id)).rejects.toThrow(
|
||||
/belongs to a different project/i,
|
||||
);
|
||||
});
|
||||
|
||||
it('should throw error when domain is not verified', async () => {
|
||||
@@ -155,13 +151,11 @@ describe('DomainService', () => {
|
||||
|
||||
await DomainService.addDomain(project.id, 'unverified.com');
|
||||
|
||||
await expect(
|
||||
DomainService.verifyEmailDomain('sender@unverified.com', project.id),
|
||||
).rejects.toThrow(HttpException);
|
||||
await expect(DomainService.verifyEmailDomain('sender@unverified.com', project.id)).rejects.toThrow(HttpException);
|
||||
|
||||
await expect(
|
||||
DomainService.verifyEmailDomain('sender@unverified.com', project.id),
|
||||
).rejects.toThrow(/not verified/i);
|
||||
await expect(DomainService.verifyEmailDomain('sender@unverified.com', project.id)).rejects.toThrow(
|
||||
/not verified/i,
|
||||
);
|
||||
});
|
||||
|
||||
it('should return domain when all checks pass', async () => {
|
||||
@@ -358,9 +352,9 @@ describe('DomainService', () => {
|
||||
});
|
||||
|
||||
it('should throw error for non-existent domain', async () => {
|
||||
await expect(
|
||||
DomainService.checkVerification('00000000-0000-0000-0000-000000000000'),
|
||||
).rejects.toThrow(/domain not found/i);
|
||||
await expect(DomainService.checkVerification('00000000-0000-0000-0000-000000000000')).rejects.toThrow(
|
||||
/domain not found/i,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -391,9 +385,7 @@ describe('DomainService', () => {
|
||||
|
||||
await expect(DomainService.removeDomain(domain.id)).rejects.toThrow(HttpException);
|
||||
|
||||
await expect(DomainService.removeDomain(domain.id)).rejects.toThrow(
|
||||
/used in.*template/i,
|
||||
);
|
||||
await expect(DomainService.removeDomain(domain.id)).rejects.toThrow(/used in.*template/i);
|
||||
});
|
||||
|
||||
it('should throw error when domain is used in active campaigns', async () => {
|
||||
@@ -409,9 +401,7 @@ describe('DomainService', () => {
|
||||
|
||||
await expect(DomainService.removeDomain(domain.id)).rejects.toThrow(HttpException);
|
||||
|
||||
await expect(DomainService.removeDomain(domain.id)).rejects.toThrow(
|
||||
/used in.*campaign/i,
|
||||
);
|
||||
await expect(DomainService.removeDomain(domain.id)).rejects.toThrow(/used in.*campaign/i);
|
||||
});
|
||||
|
||||
it('should allow removal when campaign is SENT (completed)', async () => {
|
||||
@@ -433,9 +423,9 @@ describe('DomainService', () => {
|
||||
});
|
||||
|
||||
it('should throw error for non-existent domain', async () => {
|
||||
await expect(
|
||||
DomainService.removeDomain('00000000-0000-0000-0000-000000000000'),
|
||||
).rejects.toThrow(/domain not found/i);
|
||||
await expect(DomainService.removeDomain('00000000-0000-0000-0000-000000000000')).rejects.toThrow(
|
||||
/domain not found/i,
|
||||
);
|
||||
});
|
||||
|
||||
it('should check usage in multiple templates', async () => {
|
||||
@@ -492,17 +482,15 @@ describe('DomainService', () => {
|
||||
expect(result.domain).toBe('mail.example.com');
|
||||
|
||||
// Different subdomain should fail
|
||||
await expect(
|
||||
DomainService.verifyEmailDomain('sender@other.example.com', project.id),
|
||||
).rejects.toThrow(/not registered/i);
|
||||
await expect(DomainService.verifyEmailDomain('sender@other.example.com', project.id)).rejects.toThrow(
|
||||
/not registered/i,
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle email with no @ sign', async () => {
|
||||
const {project} = await factories.createUserWithProject();
|
||||
|
||||
await expect(DomainService.verifyEmailDomain('nodomain', project.id)).rejects.toThrow(
|
||||
/invalid email format/i,
|
||||
);
|
||||
await expect(DomainService.verifyEmailDomain('nodomain', project.id)).rejects.toThrow(/invalid email format/i);
|
||||
});
|
||||
|
||||
it('should handle email with multiple @ signs', async () => {
|
||||
@@ -516,9 +504,7 @@ describe('DomainService', () => {
|
||||
it('should handle empty email string', async () => {
|
||||
const {project} = await factories.createUserWithProject();
|
||||
|
||||
await expect(DomainService.verifyEmailDomain('', project.id)).rejects.toThrow(
|
||||
/invalid email format/i,
|
||||
);
|
||||
await expect(DomainService.verifyEmailDomain('', project.id)).rejects.toThrow(/invalid email format/i);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -537,11 +523,7 @@ describe('DomainService', () => {
|
||||
]);
|
||||
|
||||
expect(results).toHaveLength(3);
|
||||
expect(results.map(d => d.domain).sort()).toEqual([
|
||||
'concurrent1.com',
|
||||
'concurrent2.com',
|
||||
'concurrent3.com',
|
||||
]);
|
||||
expect(results.map(d => d.domain).sort()).toEqual(['concurrent1.com', 'concurrent2.com', 'concurrent3.com']);
|
||||
});
|
||||
|
||||
it('should handle concurrent ownership checks', async () => {
|
||||
|
||||
@@ -1,11 +1,32 @@
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {EmailSourceType, EmailStatus} from '@plunk/db';
|
||||
import {beforeEach, describe, expect, it, vi, type Mock} from 'vitest';
|
||||
import {EmailSourceType, EmailStatus, TemplateType} from '@plunk/db';
|
||||
import {ActionSchemas} from '@plunk/shared';
|
||||
import {EmailService} from '../EmailService';
|
||||
import {sendRawEmail} from '../SESService';
|
||||
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', () => ({
|
||||
sendRawEmail: vi.fn(),
|
||||
}));
|
||||
@@ -166,6 +187,84 @@ describe('EmailService', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('Headless Email Behaviour', () => {
|
||||
it('should NOT send headless workflow emails to unsubscribed contacts', async () => {
|
||||
const unsubscribedContact = await factories.createContact({
|
||||
projectId,
|
||||
subscribed: false,
|
||||
});
|
||||
|
||||
const headlessTemplate = await factories.createTemplate({
|
||||
projectId,
|
||||
type: 'HEADLESS',
|
||||
});
|
||||
|
||||
const workflow = await factories.createWorkflow({projectId});
|
||||
const execution = await factories.createWorkflowExecution(workflow.id, unsubscribedContact.id);
|
||||
|
||||
const email = await EmailService.sendWorkflowEmail({
|
||||
projectId,
|
||||
contactId: unsubscribedContact.id,
|
||||
templateId: headlessTemplate.id,
|
||||
subject: 'Newsletter',
|
||||
body: 'Content',
|
||||
from: 'test@example.com',
|
||||
workflowExecutionId: execution.id,
|
||||
});
|
||||
|
||||
expect(email.status).toBe(EmailStatus.FAILED);
|
||||
expect(email.error).toMatch(/unsubscribed/i);
|
||||
});
|
||||
|
||||
it('should keep CAMPAIGN sourceType when campaign type is HEADLESS (no template)', async () => {
|
||||
const contact = await factories.createContact({projectId, subscribed: true});
|
||||
|
||||
// Campaign typed HEADLESS directly — no template involved (inline body)
|
||||
const campaign = await factories.createCampaign({
|
||||
projectId,
|
||||
type: TemplateType.HEADLESS,
|
||||
body: 'Content with <a href="https://example.com/unsubscribe">unsubscribe</a>',
|
||||
});
|
||||
|
||||
const email = await EmailService.sendCampaignEmail({
|
||||
projectId,
|
||||
contactId: contact.id,
|
||||
campaignId: campaign.id,
|
||||
subject: 'Newsletter',
|
||||
body: campaign.body,
|
||||
from: 'news@example.com',
|
||||
});
|
||||
|
||||
expect(email.sourceType).toBe(EmailSourceType.CAMPAIGN);
|
||||
expect(email.status).toBe(EmailStatus.PENDING);
|
||||
});
|
||||
|
||||
it('should keep CAMPAIGN sourceType when campaign uses headless template', async () => {
|
||||
const contact = await factories.createContact({projectId, subscribed: true});
|
||||
|
||||
const headlessTemplate = await factories.createTemplate({
|
||||
projectId,
|
||||
type: 'HEADLESS',
|
||||
});
|
||||
|
||||
const campaign = await factories.createCampaign({projectId});
|
||||
|
||||
const email = await EmailService.sendCampaignEmail({
|
||||
projectId,
|
||||
contactId: contact.id,
|
||||
campaignId: campaign.id,
|
||||
templateId: headlessTemplate.id,
|
||||
subject: 'Newsletter',
|
||||
body: 'Content with <a href="https://example.com/unsubscribe">unsubscribe</a>',
|
||||
from: 'news@example.com',
|
||||
});
|
||||
|
||||
// HEADLESS is not transactional — sourceType stays CAMPAIGN
|
||||
expect(email.sourceType).toBe(EmailSourceType.CAMPAIGN);
|
||||
expect(email.status).toBe(EmailStatus.PENDING);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Template Type Determines Email Type', () => {
|
||||
it('should use TRANSACTIONAL sourceType when campaign uses transactional template', async () => {
|
||||
const contact = await factories.createContact({
|
||||
@@ -688,8 +787,8 @@ describe('EmailService', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('should validate attachment size limit (10MB total)', () => {
|
||||
// Exceeds ~13.3M base64 chars limit
|
||||
it('should validate attachment size limit (10MB total default)', () => {
|
||||
// Exceeds ~13.4M base64 chars for the default 10MB limit
|
||||
const largeContent = 'A'.repeat(14000000);
|
||||
|
||||
const result = ActionSchemas.send.safeParse({
|
||||
@@ -801,5 +900,204 @@ describe('EmailService', () => {
|
||||
expect(result.success).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('should accept inline attachment with contentId', () => {
|
||||
const result = ActionSchemas.send.safeParse({
|
||||
to: 'test@example.com',
|
||||
from: 'test@example.com',
|
||||
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: 'test@example.com',
|
||||
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: 'test@example.com',
|
||||
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: 'sender@example.com'},
|
||||
to: ['recipient@example.com'],
|
||||
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: 'sender@example.com'},
|
||||
to: ['recipient@example.com'],
|
||||
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: 'sender@example.com'},
|
||||
to: ['recipient@example.com'],
|
||||
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}--`);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {EmailStatus, EmailSourceType} from '@plunk/db';
|
||||
import {SecurityService} from '../SecurityService';
|
||||
import {factories, getPrismaClient} from '../../../../../test/helpers';
|
||||
import {redis} from '../../database/redis';
|
||||
|
||||
vi.mock('../../app/constants.js', async () => {
|
||||
const actual = await vi.importActual('../../app/constants.js');
|
||||
return {
|
||||
...actual,
|
||||
AUTO_PROJECT_DISABLE: true,
|
||||
};
|
||||
});
|
||||
|
||||
// Mock NtfyService to prevent actual notifications
|
||||
vi.mock('../NtfyService.js', () => ({
|
||||
NtfyService: {
|
||||
notifySecurityWarning: vi.fn(),
|
||||
notifyProjectDisabledForSecurity: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock email sending for project disabled notifications
|
||||
vi.mock('@plunk/email', () => ({
|
||||
ProjectDisabledEmail: vi.fn(),
|
||||
sendPlatformEmail: vi.fn(),
|
||||
}));
|
||||
|
||||
describe('SecurityService', () => {
|
||||
let projectId: string;
|
||||
let contactId: string;
|
||||
const prisma = getPrismaClient();
|
||||
|
||||
beforeEach(async () => {
|
||||
const {project} = await factories.createUserWithProject();
|
||||
projectId = project.id;
|
||||
|
||||
const contact = await factories.createContact({projectId});
|
||||
contactId = contact.id;
|
||||
|
||||
// Clear redis cache
|
||||
await redis.flushdb();
|
||||
});
|
||||
|
||||
/**
|
||||
* Helper to create N emails, some of which are bounced
|
||||
*/
|
||||
async function createEmails(count: number, opts?: {bouncedCount?: number; complainedCount?: number; createdAt?: Date}) {
|
||||
const bouncedCount = opts?.bouncedCount ?? 0;
|
||||
const complainedCount = opts?.complainedCount ?? 0;
|
||||
const createdAt = opts?.createdAt ?? new Date();
|
||||
|
||||
const data = Array.from({length: count}, (_, i) => ({
|
||||
projectId,
|
||||
contactId,
|
||||
subject: `Test ${i}`,
|
||||
body: '<p>test</p>',
|
||||
from: 'test@example.com',
|
||||
status: EmailStatus.SENT,
|
||||
sourceType: EmailSourceType.TRANSACTIONAL,
|
||||
sentAt: createdAt,
|
||||
createdAt,
|
||||
bouncedAt: i < bouncedCount ? createdAt : null,
|
||||
complainedAt: i >= bouncedCount && i < bouncedCount + complainedCount ? createdAt : null,
|
||||
}));
|
||||
await prisma.email.createMany({data});
|
||||
}
|
||||
|
||||
describe('Rate-based checks (existing behavior)', () => {
|
||||
it('should report healthy when bounce rate is below warning', async () => {
|
||||
// 200 emails, 5 bounces = 2.5% (below 5% warning)
|
||||
await createEmails(200, {bouncedCount: 5});
|
||||
|
||||
const status = await SecurityService.getSecurityStatus(projectId);
|
||||
expect(status.isHealthy).toBe(true);
|
||||
expect(status.shouldDisable).toBe(false);
|
||||
expect(status.violations).toHaveLength(0);
|
||||
expect(status.warnings).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should trigger warning when 7-day bounce rate exceeds warning threshold', async () => {
|
||||
// 100 emails, 6 bounces = 6% (above 5% warning, below 10% critical)
|
||||
await createEmails(100, {bouncedCount: 6});
|
||||
|
||||
const status = await SecurityService.getSecurityStatus(projectId);
|
||||
expect(status.isHealthy).toBe(true);
|
||||
expect(status.warnings.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('should trigger violation when 7-day bounce rate exceeds critical threshold', async () => {
|
||||
// 100 emails, 11 bounces = 11% (above 10% critical)
|
||||
await createEmails(100, {bouncedCount: 11});
|
||||
|
||||
const status = await SecurityService.getSecurityStatus(projectId);
|
||||
expect(status.isHealthy).toBe(false);
|
||||
expect(status.shouldDisable).toBe(true);
|
||||
expect(status.violations.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('should not enforce rate checks when below minimum volume', async () => {
|
||||
// 50 emails (below 100 minimum), 10 bounces = 20% (would exceed critical)
|
||||
await createEmails(50, {bouncedCount: 10});
|
||||
|
||||
const status = await SecurityService.getSecurityStatus(projectId);
|
||||
expect(status.violations).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Established projects skip absolute ceilings', () => {
|
||||
// Age the project past the new-project window
|
||||
beforeEach(async () => {
|
||||
const oldDate = new Date(Date.now() - 31 * 24 * 60 * 60 * 1000);
|
||||
await prisma.project.update({
|
||||
where: {id: projectId},
|
||||
data: {createdAt: oldDate},
|
||||
});
|
||||
});
|
||||
|
||||
it('should NOT trigger on high absolute bounce count when rate is healthy', async () => {
|
||||
// 20,000 emails, 200 bounces = 1% rate (well below rate threshold)
|
||||
// Established projects rely solely on rates — high absolute counts at
|
||||
// high volume don't indicate abuse.
|
||||
await createEmails(20000, {bouncedCount: 200});
|
||||
|
||||
const status = await SecurityService.getSecurityStatus(projectId);
|
||||
expect(status.isHealthy).toBe(true);
|
||||
expect(status.shouldDisable).toBe(false);
|
||||
expect(status.violations).toHaveLength(0);
|
||||
expect(status.warnings).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should NOT trigger on high absolute complaint count when rate is healthy', async () => {
|
||||
// 100,000 emails, 30 complaints = 0.03% (at warning floor, below critical 0.15%)
|
||||
// Old absolute ceiling (25 complaints in 7d critical) would have tripped.
|
||||
await createEmails(100000, {complainedCount: 30});
|
||||
|
||||
const status = await SecurityService.getSecurityStatus(projectId);
|
||||
expect(status.shouldDisable).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('New project stricter thresholds', () => {
|
||||
it('should apply stricter ceilings for projects under 30 days old', async () => {
|
||||
// Default project is created "now", so it's a new project
|
||||
// 10,000 emails, 26 bounces (above 25 new project 24h critical ceiling)
|
||||
await createEmails(10000, {bouncedCount: 26});
|
||||
|
||||
const status = await SecurityService.getSecurityStatus(projectId);
|
||||
expect(status.isNewProject).toBe(true);
|
||||
expect(status.shouldDisable).toBe(true);
|
||||
expect(status.violations.some(v => v.includes('new project'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should NOT apply absolute ceilings for projects over 30 days old', async () => {
|
||||
// Age the project to 31 days
|
||||
const oldDate = new Date(Date.now() - 31 * 24 * 60 * 60 * 1000);
|
||||
await prisma.project.update({
|
||||
where: {id: projectId},
|
||||
data: {createdAt: oldDate},
|
||||
});
|
||||
|
||||
// 10,000 emails, 26 bounces — would trip new-project ceiling, but
|
||||
// established projects skip ceilings entirely (rate is 0.26%, healthy).
|
||||
await createEmails(10000, {bouncedCount: 26});
|
||||
|
||||
const status = await SecurityService.getSecurityStatus(projectId);
|
||||
expect(status.isNewProject).toBe(false);
|
||||
expect(status.warnings.some(w => w.includes('bounce count'))).toBe(false);
|
||||
expect(status.violations.some(v => v.includes('bounce count'))).toBe(false);
|
||||
});
|
||||
|
||||
it('should catch new project blasting emails with delayed bounces', async () => {
|
||||
// Simulate the spammer scenario: new project sends 20K emails,
|
||||
// only 30 bounces have come back so far (rate is tiny: 0.15%)
|
||||
await createEmails(20000, {bouncedCount: 30});
|
||||
|
||||
const status = await SecurityService.getSecurityStatus(projectId);
|
||||
expect(status.isNewProject).toBe(true);
|
||||
expect(status.shouldDisable).toBe(true);
|
||||
// 30 > 25 new project 24h critical ceiling
|
||||
expect(status.violations.some(v => v.includes('24-hour bounce count'))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('checkAndEnforceSecurityLimits', () => {
|
||||
it('should disable project when critical thresholds are exceeded', async () => {
|
||||
// New project, 20K emails with 30 bounces — exceeds new project 24h critical ceiling
|
||||
await createEmails(20000, {bouncedCount: 30});
|
||||
|
||||
await SecurityService.checkAndEnforceSecurityLimits(projectId);
|
||||
|
||||
const project = await prisma.project.findUnique({
|
||||
where: {id: projectId},
|
||||
select: {disabled: true},
|
||||
});
|
||||
expect(project?.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it('should NOT disable project when only warnings exist', async () => {
|
||||
// Established project, 200 emails, 12 bounces = 6% (above 5% warning, below 10% critical)
|
||||
const oldDate = new Date(Date.now() - 31 * 24 * 60 * 60 * 1000);
|
||||
await prisma.project.update({
|
||||
where: {id: projectId},
|
||||
data: {createdAt: oldDate},
|
||||
});
|
||||
await createEmails(200, {bouncedCount: 12});
|
||||
|
||||
await SecurityService.checkAndEnforceSecurityLimits(projectId);
|
||||
|
||||
const project = await prisma.project.findUnique({
|
||||
where: {id: projectId},
|
||||
select: {disabled: true},
|
||||
});
|
||||
expect(project?.disabled).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getProjectSecurityMetrics (client-facing)', () => {
|
||||
it('should NOT expose internal thresholds or detailed violation messages', async () => {
|
||||
// Create a violation scenario
|
||||
await createEmails(100, {bouncedCount: 15});
|
||||
|
||||
const metrics = await SecurityService.getProjectSecurityMetrics(projectId);
|
||||
|
||||
// Should have levels, not thresholds
|
||||
expect(metrics.levels).toBeDefined();
|
||||
expect((metrics as Record<string, unknown>).thresholds).toBeUndefined();
|
||||
|
||||
// Violation messages should be generic
|
||||
if (metrics.status.violations.length > 0) {
|
||||
for (const v of metrics.status.violations) {
|
||||
expect(v).toBe('Security threshold exceeded');
|
||||
expect(v).not.toMatch(/\d+%/); // No percentages
|
||||
expect(v).not.toMatch(/\d+ minimum/); // No absolute numbers
|
||||
}
|
||||
}
|
||||
|
||||
// 24-hour data should be zeroed out
|
||||
expect(metrics.status.twentyFourHour.total).toBe(0);
|
||||
expect(metrics.status.twentyFourHour.bounces).toBe(0);
|
||||
|
||||
// New project flag should be hidden
|
||||
expect(metrics.status.isNewProject).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -32,8 +32,8 @@ describe('SegmentService', () => {
|
||||
|
||||
const result = await SegmentService.getContacts(projectId, segment.id);
|
||||
|
||||
expect(result.contacts).toHaveLength(1);
|
||||
expect(result.contacts[0].id).toBe(subscribed.id);
|
||||
expect(result.data).toHaveLength(1);
|
||||
expect(result.data[0].id).toBe(subscribed.id);
|
||||
});
|
||||
|
||||
it('should filter contacts by custom data fields', async () => {
|
||||
@@ -53,8 +53,8 @@ describe('SegmentService', () => {
|
||||
|
||||
const result = await SegmentService.getContacts(projectId, segment.id);
|
||||
|
||||
expect(result.contacts).toHaveLength(1);
|
||||
expect(result.contacts[0].id).toBe(proUser.id);
|
||||
expect(result.data).toHaveLength(1);
|
||||
expect(result.data[0].id).toBe(proUser.id);
|
||||
});
|
||||
|
||||
it('should filter contacts with multiple conditions', async () => {
|
||||
@@ -85,8 +85,8 @@ describe('SegmentService', () => {
|
||||
|
||||
const result = await SegmentService.getContacts(projectId, segment.id);
|
||||
|
||||
expect(result.contacts).toHaveLength(1);
|
||||
expect(result.contacts[0].id).toBe(target.id);
|
||||
expect(result.data).toHaveLength(1);
|
||||
expect(result.data[0].id).toBe(target.id);
|
||||
});
|
||||
|
||||
it('should support notEquals operator', async () => {
|
||||
@@ -106,8 +106,8 @@ describe('SegmentService', () => {
|
||||
|
||||
const result = await SegmentService.getContacts(projectId, segment.id);
|
||||
|
||||
expect(result.contacts).toHaveLength(1);
|
||||
expect(result.contacts[0].id).toBe(pro.id);
|
||||
expect(result.data).toHaveLength(1);
|
||||
expect(result.data[0].id).toBe(pro.id);
|
||||
});
|
||||
|
||||
it('should support contains operator for strings', async () => {
|
||||
@@ -127,8 +127,8 @@ describe('SegmentService', () => {
|
||||
|
||||
const result = await SegmentService.getContacts(projectId, segment.id);
|
||||
|
||||
expect(result.contacts).toHaveLength(1);
|
||||
expect(result.contacts[0].id).toBe(match.id);
|
||||
expect(result.data).toHaveLength(1);
|
||||
expect(result.data[0].id).toBe(match.id);
|
||||
});
|
||||
|
||||
it('should support exists operator for custom fields', async () => {
|
||||
@@ -148,8 +148,8 @@ describe('SegmentService', () => {
|
||||
|
||||
const result = await SegmentService.getContacts(projectId, segment.id);
|
||||
|
||||
expect(result.contacts).toHaveLength(1);
|
||||
expect(result.contacts[0].id).toBe(withField.id);
|
||||
expect(result.data).toHaveLength(1);
|
||||
expect(result.data[0].id).toBe(withField.id);
|
||||
});
|
||||
|
||||
it('should handle empty segments', async () => {
|
||||
@@ -165,7 +165,7 @@ describe('SegmentService', () => {
|
||||
|
||||
const result = await SegmentService.getContacts(projectId, segment.id);
|
||||
|
||||
expect(result.contacts).toHaveLength(0);
|
||||
expect(result.data).toHaveLength(0);
|
||||
expect(result.total).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -192,7 +192,7 @@ describe('SegmentService', () => {
|
||||
const result = await SegmentService.getContacts(projectId, segment.id);
|
||||
|
||||
expect(result.total).toBe(2);
|
||||
expect(result.contacts).toHaveLength(2);
|
||||
expect(result.data).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('should support pagination', async () => {
|
||||
@@ -209,15 +209,15 @@ describe('SegmentService', () => {
|
||||
});
|
||||
|
||||
const page1 = await SegmentService.getContacts(projectId, segment.id, 1, 10);
|
||||
expect(page1.contacts).toHaveLength(10);
|
||||
expect(page1.data).toHaveLength(10);
|
||||
expect(page1.total).toBe(25);
|
||||
expect(page1.totalPages).toBe(3);
|
||||
|
||||
const page2 = await SegmentService.getContacts(projectId, segment.id, 2, 10);
|
||||
expect(page2.contacts).toHaveLength(10);
|
||||
expect(page2.data).toHaveLength(10);
|
||||
|
||||
const page3 = await SegmentService.getContacts(projectId, segment.id, 3, 10);
|
||||
expect(page3.contacts).toHaveLength(5);
|
||||
expect(page3.data).toHaveLength(5);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -278,7 +278,7 @@ describe('SegmentService', () => {
|
||||
|
||||
// Initially not in segment
|
||||
let result = await SegmentService.getContacts(projectId, proSegment.id);
|
||||
expect(result.contacts).toHaveLength(0);
|
||||
expect(result.data).toHaveLength(0);
|
||||
|
||||
// Update contact to pro plan
|
||||
await prisma.contact.update({
|
||||
@@ -288,8 +288,8 @@ describe('SegmentService', () => {
|
||||
|
||||
// Should now be in segment
|
||||
result = await SegmentService.getContacts(projectId, proSegment.id);
|
||||
expect(result.contacts).toHaveLength(1);
|
||||
expect(result.contacts[0].id).toBe(contact.id);
|
||||
expect(result.data).toHaveLength(1);
|
||||
expect(result.data[0].id).toBe(contact.id);
|
||||
});
|
||||
|
||||
it('should be removed from segment when criteria no longer met', async () => {
|
||||
@@ -304,7 +304,7 @@ describe('SegmentService', () => {
|
||||
|
||||
// Initially in segment
|
||||
let result = await SegmentService.getContacts(projectId, segment.id);
|
||||
expect(result.contacts).toHaveLength(1);
|
||||
expect(result.data).toHaveLength(1);
|
||||
|
||||
// Unsubscribe contact
|
||||
await prisma.contact.update({
|
||||
@@ -314,7 +314,7 @@ describe('SegmentService', () => {
|
||||
|
||||
// Should no longer be in segment
|
||||
result = await SegmentService.getContacts(projectId, segment.id);
|
||||
expect(result.contacts).toHaveLength(0);
|
||||
expect(result.data).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -506,8 +506,8 @@ describe('SegmentService', () => {
|
||||
|
||||
const result = await SegmentService.getContacts(projectId, segment.id);
|
||||
|
||||
expect(result.contacts.map(c => c.id).sort()).toEqual([other.id].sort());
|
||||
expect(result.contacts.map(c => c.id)).not.toContain(match.id);
|
||||
expect(result.data.map(c => c.id).sort()).toEqual([other.id].sort());
|
||||
expect(result.data.map(c => c.id)).not.toContain(match.id);
|
||||
});
|
||||
|
||||
it('should support case-insensitive equals/contains for email strings', async () => {
|
||||
@@ -526,7 +526,7 @@ describe('SegmentService', () => {
|
||||
});
|
||||
|
||||
const equalsResult = await SegmentService.getContacts(projectId, equalsSegment.id);
|
||||
const equalsIds = equalsResult.contacts.map(c => c.id);
|
||||
const equalsIds = equalsResult.data.map(c => c.id);
|
||||
expect(equalsIds).toContain(lower.id);
|
||||
expect(equalsIds).toContain(upper.id);
|
||||
|
||||
@@ -536,7 +536,7 @@ describe('SegmentService', () => {
|
||||
});
|
||||
|
||||
const containsResult = await SegmentService.getContacts(projectId, containsSegment.id);
|
||||
const containsIds = containsResult.contacts.map(c => c.id);
|
||||
const containsIds = containsResult.data.map(c => c.id);
|
||||
expect(containsIds).toContain(lower.id);
|
||||
expect(containsIds).toContain(upper.id);
|
||||
});
|
||||
@@ -557,7 +557,7 @@ describe('SegmentService', () => {
|
||||
});
|
||||
|
||||
const result = await SegmentService.getContacts(projectId, segment.id);
|
||||
const ids = result.contacts.map(c => c.id);
|
||||
const ids = result.data.map(c => c.id);
|
||||
|
||||
expect(ids).toContain(unsubscribed.id);
|
||||
expect(ids).not.toContain(subscribed.id);
|
||||
@@ -579,7 +579,7 @@ describe('SegmentService', () => {
|
||||
});
|
||||
|
||||
const notContainsResult = await SegmentService.getContacts(projectId, notContainsSegment.id);
|
||||
const notContainsIds = notContainsResult.contacts.map(c => c.id);
|
||||
const notContainsIds = notContainsResult.data.map(c => c.id);
|
||||
expect(notContainsIds).toContain(other.id);
|
||||
expect(notContainsIds).not.toContain(acme.id);
|
||||
|
||||
@@ -589,7 +589,7 @@ describe('SegmentService', () => {
|
||||
});
|
||||
|
||||
const notEqualsResult = await SegmentService.getContacts(projectId, notEqualsSegment.id);
|
||||
const notEqualsIds = notEqualsResult.contacts.map(c => c.id);
|
||||
const notEqualsIds = notEqualsResult.data.map(c => c.id);
|
||||
expect(notEqualsIds).toContain(other.id);
|
||||
expect(notEqualsIds).not.toContain(acme.id);
|
||||
});
|
||||
@@ -610,7 +610,7 @@ describe('SegmentService', () => {
|
||||
});
|
||||
|
||||
const existsResult = await SegmentService.getContacts(projectId, existsSegment.id);
|
||||
const existsIds = new Set(existsResult.contacts.map(c => c.id));
|
||||
const existsIds = new Set(existsResult.data.map(c => c.id));
|
||||
expect(existsIds.has(withCompany.id)).toBe(true);
|
||||
expect(existsIds.has(withNullCompany.id)).toBe(false);
|
||||
|
||||
@@ -620,7 +620,7 @@ describe('SegmentService', () => {
|
||||
});
|
||||
|
||||
const notExistsResult = await SegmentService.getContacts(projectId, notExistsSegment.id);
|
||||
const notExistsIds = new Set(notExistsResult.contacts.map(c => c.id));
|
||||
const notExistsIds = new Set(notExistsResult.data.map(c => c.id));
|
||||
expect(notExistsIds.has(withCompany.id)).toBe(false);
|
||||
expect(notExistsIds.has(withNullCompany.id)).toBe(true);
|
||||
});
|
||||
@@ -645,7 +645,7 @@ describe('SegmentService', () => {
|
||||
});
|
||||
|
||||
const greaterThanResult = await SegmentService.getContacts(projectId, greaterThanSegment.id);
|
||||
const gtIds = greaterThanResult.contacts.map(c => c.id);
|
||||
const gtIds = greaterThanResult.data.map(c => c.id);
|
||||
expect(gtIds).toContain(mid.id);
|
||||
expect(gtIds).toContain(high.id);
|
||||
expect(gtIds).not.toContain(low.id);
|
||||
@@ -656,7 +656,7 @@ describe('SegmentService', () => {
|
||||
});
|
||||
|
||||
const lteResult = await SegmentService.getContacts(projectId, lessThanOrEqualSegment.id);
|
||||
const lteIds = lteResult.contacts.map(c => c.id);
|
||||
const lteIds = lteResult.data.map(c => c.id);
|
||||
expect(lteIds).toContain(low.id);
|
||||
expect(lteIds).toContain(mid.id);
|
||||
expect(lteIds).not.toContain(high.id);
|
||||
@@ -674,7 +674,7 @@ describe('SegmentService', () => {
|
||||
});
|
||||
|
||||
const gtResult = await SegmentService.getContacts(projectId, gtSegment.id);
|
||||
const gtIds = gtResult.contacts.map(c => c.id);
|
||||
const gtIds = gtResult.data.map(c => c.id);
|
||||
expect(gtIds).toContain(newer.id);
|
||||
expect(gtIds).not.toContain(older.id);
|
||||
|
||||
@@ -684,7 +684,7 @@ describe('SegmentService', () => {
|
||||
});
|
||||
|
||||
const lteResult = await SegmentService.getContacts(projectId, lteSegment.id);
|
||||
const lteIds = lteResult.contacts.map(c => c.id);
|
||||
const lteIds = lteResult.data.map(c => c.id);
|
||||
expect(lteIds).toContain(older.id);
|
||||
expect(lteIds).toContain(newer.id);
|
||||
});
|
||||
@@ -705,7 +705,7 @@ describe('SegmentService', () => {
|
||||
});
|
||||
|
||||
const result = await SegmentService.getContacts(projectId, segment.id);
|
||||
const ids = result.contacts.map(c => c.id);
|
||||
const ids = result.data.map(c => c.id);
|
||||
expect(ids).toContain(recent.id);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {describe, it, expect, beforeEach} from 'vitest';
|
||||
import {beforeEach, describe, expect, it} from 'vitest';
|
||||
import {TemplateType} from '@plunk/db';
|
||||
import {TemplateService} from '../TemplateService';
|
||||
import {factories, getPrismaClient} from '../../../../../test/helpers';
|
||||
@@ -104,18 +104,18 @@ describe('TemplateService', () => {
|
||||
}
|
||||
|
||||
const page1 = await TemplateService.list(projectId, 1, 10);
|
||||
expect(page1.templates).toHaveLength(10);
|
||||
expect(page1.data).toHaveLength(10);
|
||||
expect(page1.total).toBe(25);
|
||||
expect(page1.page).toBe(1);
|
||||
expect(page1.pageSize).toBe(10);
|
||||
expect(page1.totalPages).toBe(3);
|
||||
|
||||
const page2 = await TemplateService.list(projectId, 2, 10);
|
||||
expect(page2.templates).toHaveLength(10);
|
||||
expect(page2.data).toHaveLength(10);
|
||||
expect(page2.page).toBe(2);
|
||||
|
||||
const page3 = await TemplateService.list(projectId, 3, 10);
|
||||
expect(page3.templates).toHaveLength(5);
|
||||
expect(page3.data).toHaveLength(5);
|
||||
expect(page3.page).toBe(3);
|
||||
});
|
||||
|
||||
@@ -127,7 +127,7 @@ describe('TemplateService', () => {
|
||||
const result = await TemplateService.list(projectId, 1, 20, 'welcome');
|
||||
|
||||
expect(result.total).toBe(2);
|
||||
expect(result.templates.every(t => t.name.toLowerCase().includes('welcome'))).toBe(true);
|
||||
expect(result.data.every(t => t.name.toLowerCase().includes('welcome'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should filter templates by search query (description)', async () => {
|
||||
@@ -165,7 +165,7 @@ describe('TemplateService', () => {
|
||||
const result = await TemplateService.list(projectId, 1, 20, 'new');
|
||||
|
||||
expect(result.total).toBe(2);
|
||||
expect(result.templates.map(t => t.description)).toEqual(
|
||||
expect(result.data.map(t => t.description)).toEqual(
|
||||
expect.arrayContaining([expect.stringContaining('new')]),
|
||||
);
|
||||
});
|
||||
@@ -193,14 +193,19 @@ describe('TemplateService', () => {
|
||||
await factories.createTemplate({projectId, type: TemplateType.MARKETING});
|
||||
await factories.createTemplate({projectId, type: TemplateType.MARKETING});
|
||||
await factories.createTemplate({projectId, type: TemplateType.TRANSACTIONAL});
|
||||
await factories.createTemplate({projectId, type: TemplateType.HEADLESS});
|
||||
|
||||
const marketingResult = await TemplateService.list(projectId, 1, 20, undefined, TemplateType.MARKETING);
|
||||
expect(marketingResult.total).toBe(2);
|
||||
expect(marketingResult.templates.every(t => t.type === TemplateType.MARKETING)).toBe(true);
|
||||
expect(marketingResult.data.every(t => t.type === TemplateType.MARKETING)).toBe(true);
|
||||
|
||||
const transactionalResult = await TemplateService.list(projectId, 1, 20, undefined, TemplateType.TRANSACTIONAL);
|
||||
expect(transactionalResult.total).toBe(1);
|
||||
expect(transactionalResult.templates[0].type).toBe(TemplateType.TRANSACTIONAL);
|
||||
expect(transactionalResult.data[0].type).toBe(TemplateType.TRANSACTIONAL);
|
||||
|
||||
const headlessResult = await TemplateService.list(projectId, 1, 20, undefined, TemplateType.HEADLESS);
|
||||
expect(headlessResult.total).toBe(1);
|
||||
expect(headlessResult.data[0].type).toBe(TemplateType.HEADLESS);
|
||||
});
|
||||
|
||||
it('should combine search and type filters', async () => {
|
||||
@@ -223,7 +228,7 @@ describe('TemplateService', () => {
|
||||
const result = await TemplateService.list(projectId, 1, 20, 'welcome', TemplateType.MARKETING);
|
||||
|
||||
expect(result.total).toBe(1);
|
||||
expect(result.templates[0].name).toBe('Welcome Email');
|
||||
expect(result.data[0].name).toBe('Welcome Email');
|
||||
});
|
||||
|
||||
it('should return templates ordered by creation date (newest first)', async () => {
|
||||
@@ -236,9 +241,9 @@ describe('TemplateService', () => {
|
||||
|
||||
const result = await TemplateService.list(projectId, 1, 20);
|
||||
|
||||
expect(result.templates[0].id).toBe(template3.id); // Newest
|
||||
expect(result.templates[1].id).toBe(template2.id);
|
||||
expect(result.templates[2].id).toBe(template1.id); // Oldest
|
||||
expect(result.data[0].id).toBe(template3.id); // Newest
|
||||
expect(result.data[1].id).toBe(template2.id);
|
||||
expect(result.data[2].id).toBe(template1.id); // Oldest
|
||||
});
|
||||
|
||||
it('should only return templates for the specified project', async () => {
|
||||
@@ -293,6 +298,19 @@ describe('TemplateService', () => {
|
||||
expect(updated.type).toBe(TemplateType.TRANSACTIONAL);
|
||||
});
|
||||
|
||||
it('should update template type to HEADLESS', async () => {
|
||||
const template = await factories.createTemplate({
|
||||
projectId,
|
||||
type: TemplateType.MARKETING,
|
||||
});
|
||||
|
||||
const updated = await TemplateService.update(projectId, template.id, {
|
||||
type: TemplateType.HEADLESS,
|
||||
});
|
||||
|
||||
expect(updated.type).toBe(TemplateType.HEADLESS);
|
||||
});
|
||||
|
||||
it('should update email fields (from, fromName, replyTo)', async () => {
|
||||
const template = await factories.createTemplate({projectId});
|
||||
|
||||
|
||||
@@ -722,4 +722,260 @@ describe('Workflow CONDITION Step - Comprehensive Operator Tests', () => {
|
||||
expect(branch).toBe('yes');
|
||||
});
|
||||
});
|
||||
|
||||
// ========================================
|
||||
// MULTI-BRANCH CONDITIONS (switch/case)
|
||||
// ========================================
|
||||
describe('Multi-Branch Conditions', () => {
|
||||
/**
|
||||
* Helper to create a workflow with a multi-branch condition step
|
||||
* Creates one exit step per branch + one for default
|
||||
*/
|
||||
async function createMultiBranchWorkflow(
|
||||
contactData: Record<string, unknown>,
|
||||
conditionConfig: Record<string, unknown>,
|
||||
) {
|
||||
const contact = await factories.createContact({
|
||||
projectId,
|
||||
data: contactData,
|
||||
});
|
||||
|
||||
const workflow = await factories.createWorkflow({projectId});
|
||||
const triggerStep = await prisma.workflowStep.findFirstOrThrow({
|
||||
where: {workflowId: workflow.id, type: WorkflowStepType.TRIGGER},
|
||||
});
|
||||
|
||||
const conditionStep = await prisma.workflowStep.create({
|
||||
data: {
|
||||
workflowId: workflow.id,
|
||||
type: WorkflowStepType.CONDITION,
|
||||
name: 'Multi Condition',
|
||||
position: {x: 100, y: 0},
|
||||
config: conditionConfig,
|
||||
},
|
||||
});
|
||||
|
||||
// Create exit steps for each branch + default
|
||||
const branches = conditionConfig.branches as Array<{id: string; name: string; operator: string; value?: unknown}>;
|
||||
const branchExits: Record<string, string> = {};
|
||||
for (let i = 0; i < branches.length; i++) {
|
||||
const branch = branches[i]!;
|
||||
const exitStep = await prisma.workflowStep.create({
|
||||
data: {
|
||||
workflowId: workflow.id,
|
||||
type: WorkflowStepType.EXIT,
|
||||
name: `${branch.name} Path`,
|
||||
position: {x: 200, y: i * 100},
|
||||
config: {reason: branch.name},
|
||||
},
|
||||
});
|
||||
branchExits[branch.id] = exitStep.id;
|
||||
|
||||
await prisma.workflowTransition.create({
|
||||
data: {
|
||||
fromStepId: conditionStep.id,
|
||||
toStepId: exitStep.id,
|
||||
condition: {branch: branch.id},
|
||||
priority: i,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Create default exit
|
||||
const defaultExit = await prisma.workflowStep.create({
|
||||
data: {
|
||||
workflowId: workflow.id,
|
||||
type: WorkflowStepType.EXIT,
|
||||
name: 'Default Path',
|
||||
position: {x: 200, y: branches.length * 100},
|
||||
config: {reason: 'default'},
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.workflowTransition.create({
|
||||
data: {
|
||||
fromStepId: conditionStep.id,
|
||||
toStepId: defaultExit.id,
|
||||
condition: {branch: 'default'},
|
||||
priority: branches.length,
|
||||
},
|
||||
});
|
||||
|
||||
// Connect trigger to condition
|
||||
await prisma.workflowTransition.create({
|
||||
data: {fromStepId: triggerStep.id, toStepId: conditionStep.id},
|
||||
});
|
||||
|
||||
const execution = await prisma.workflowExecution.create({
|
||||
data: {
|
||||
workflowId: workflow.id,
|
||||
contactId: contact.id,
|
||||
status: WorkflowExecutionStatus.RUNNING,
|
||||
currentStepId: triggerStep.id,
|
||||
context: {},
|
||||
},
|
||||
});
|
||||
|
||||
return {execution, triggerStep, conditionStep, contact, branchExits, defaultExitId: defaultExit.id};
|
||||
}
|
||||
|
||||
const planBranches = {
|
||||
mode: 'multi' as const,
|
||||
field: 'data.plan',
|
||||
branches: [
|
||||
{id: 'br-premium', name: 'Premium', operator: 'equals', value: 'premium'},
|
||||
{id: 'br-free', name: 'Free', operator: 'equals', value: 'free'},
|
||||
{id: 'br-enterprise', name: 'Enterprise', operator: 'equals', value: 'enterprise'},
|
||||
],
|
||||
};
|
||||
|
||||
it('should match the first matching branch', async () => {
|
||||
const {execution, triggerStep, conditionStep} = await createMultiBranchWorkflow(
|
||||
{plan: 'premium'},
|
||||
planBranches,
|
||||
);
|
||||
|
||||
await WorkflowExecutionService.processStepExecution(execution.id, triggerStep.id);
|
||||
await WorkflowExecutionService.processStepExecution(execution.id, conditionStep.id);
|
||||
|
||||
const branch = await getConditionBranch(execution.id, conditionStep.id);
|
||||
expect(branch).toBe('br-premium');
|
||||
});
|
||||
|
||||
it('should match a non-first branch correctly', async () => {
|
||||
const {execution, triggerStep, conditionStep} = await createMultiBranchWorkflow(
|
||||
{plan: 'enterprise'},
|
||||
planBranches,
|
||||
);
|
||||
|
||||
await WorkflowExecutionService.processStepExecution(execution.id, triggerStep.id);
|
||||
await WorkflowExecutionService.processStepExecution(execution.id, conditionStep.id);
|
||||
|
||||
const branch = await getConditionBranch(execution.id, conditionStep.id);
|
||||
expect(branch).toBe('br-enterprise');
|
||||
});
|
||||
|
||||
it('should fall through to default when no branch matches', async () => {
|
||||
const {execution, triggerStep, conditionStep} = await createMultiBranchWorkflow(
|
||||
{plan: 'starter'},
|
||||
planBranches,
|
||||
);
|
||||
|
||||
await WorkflowExecutionService.processStepExecution(execution.id, triggerStep.id);
|
||||
await WorkflowExecutionService.processStepExecution(execution.id, conditionStep.id);
|
||||
|
||||
const branch = await getConditionBranch(execution.id, conditionStep.id);
|
||||
expect(branch).toBe('default');
|
||||
});
|
||||
|
||||
it('should fall through to default when field is missing', async () => {
|
||||
const {execution, triggerStep, conditionStep} = await createMultiBranchWorkflow(
|
||||
{other: 'value'},
|
||||
planBranches,
|
||||
);
|
||||
|
||||
await WorkflowExecutionService.processStepExecution(execution.id, triggerStep.id);
|
||||
await WorkflowExecutionService.processStepExecution(execution.id, conditionStep.id);
|
||||
|
||||
const branch = await getConditionBranch(execution.id, conditionStep.id);
|
||||
expect(branch).toBe('default');
|
||||
});
|
||||
|
||||
it('should support mixed operators across branches', async () => {
|
||||
const {execution, triggerStep, conditionStep} = await createMultiBranchWorkflow(
|
||||
{score: 85},
|
||||
{
|
||||
mode: 'multi',
|
||||
field: 'data.score',
|
||||
branches: [
|
||||
{id: 'br-high', name: 'High', operator: 'greaterThanOrEqual', value: 90},
|
||||
{id: 'br-medium', name: 'Medium', operator: 'greaterThanOrEqual', value: 70},
|
||||
{id: 'br-low', name: 'Low', operator: 'lessThan', value: 70},
|
||||
],
|
||||
},
|
||||
);
|
||||
|
||||
await WorkflowExecutionService.processStepExecution(execution.id, triggerStep.id);
|
||||
await WorkflowExecutionService.processStepExecution(execution.id, conditionStep.id);
|
||||
|
||||
// 85 >= 90 is false, 85 >= 70 is true → should match "Medium"
|
||||
const branch = await getConditionBranch(execution.id, conditionStep.id);
|
||||
expect(branch).toBe('br-medium');
|
||||
});
|
||||
|
||||
it('should respect branch evaluation order (first match wins)', async () => {
|
||||
const {execution, triggerStep, conditionStep} = await createMultiBranchWorkflow(
|
||||
{plan: 'premium'},
|
||||
{
|
||||
mode: 'multi',
|
||||
field: 'data.plan',
|
||||
branches: [
|
||||
{id: 'br-first', name: 'First', operator: 'contains', value: 'prem'},
|
||||
{id: 'br-second', name: 'Second', operator: 'equals', value: 'premium'},
|
||||
],
|
||||
},
|
||||
);
|
||||
|
||||
await WorkflowExecutionService.processStepExecution(execution.id, triggerStep.id);
|
||||
await WorkflowExecutionService.processStepExecution(execution.id, conditionStep.id);
|
||||
|
||||
// Both match, but first one should win
|
||||
const branch = await getConditionBranch(execution.id, conditionStep.id);
|
||||
expect(branch).toBe('br-first');
|
||||
});
|
||||
|
||||
it('should support exists/notExists operators in branches', async () => {
|
||||
const {execution, triggerStep, conditionStep} = await createMultiBranchWorkflow(
|
||||
{plan: 'premium'},
|
||||
{
|
||||
mode: 'multi',
|
||||
field: 'data.plan',
|
||||
branches: [
|
||||
{id: 'br-has-plan', name: 'Has Plan', operator: 'exists'},
|
||||
],
|
||||
},
|
||||
);
|
||||
|
||||
await WorkflowExecutionService.processStepExecution(execution.id, triggerStep.id);
|
||||
await WorkflowExecutionService.processStepExecution(execution.id, conditionStep.id);
|
||||
|
||||
const branch = await getConditionBranch(execution.id, conditionStep.id);
|
||||
expect(branch).toBe('br-has-plan');
|
||||
});
|
||||
|
||||
it('should route to correct exit step via transitions', async () => {
|
||||
const {execution, triggerStep, branchExits, defaultExitId} = await createMultiBranchWorkflow(
|
||||
{plan: 'free'},
|
||||
planBranches,
|
||||
);
|
||||
|
||||
await WorkflowExecutionService.processStepExecution(execution.id, triggerStep.id);
|
||||
|
||||
// Check the execution completed and ended at the correct exit step
|
||||
const completedExecution = await prisma.workflowExecution.findUnique({
|
||||
where: {id: execution.id},
|
||||
});
|
||||
|
||||
// Workflow completed after reaching exit step
|
||||
expect(['EXITED', 'COMPLETED']).toContain(completedExecution?.status);
|
||||
|
||||
// Verify it went through the "free" branch exit, not default
|
||||
const exitStepExecution = await prisma.workflowStepExecution.findFirst({
|
||||
where: {
|
||||
executionId: execution.id,
|
||||
stepId: branchExits['br-free'],
|
||||
},
|
||||
});
|
||||
expect(exitStepExecution).not.toBeNull();
|
||||
|
||||
// Verify it did NOT go through the default exit
|
||||
const defaultStepExecution = await prisma.workflowStepExecution.findFirst({
|
||||
where: {
|
||||
executionId: execution.id,
|
||||
stepId: defaultExitId,
|
||||
},
|
||||
});
|
||||
expect(defaultStepExecution).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {Prisma, StepExecutionStatus, WorkflowExecutionStatus, WorkflowStepType} from '@plunk/db';
|
||||
import {StepExecutionStatus, WorkflowExecutionStatus, WorkflowStepType} from '@plunk/db';
|
||||
import {toPrismaJson} from '@plunk/types';
|
||||
import {WorkflowExecutionService} from '../WorkflowExecutionService';
|
||||
import {factories, getPrismaClient} from '../../../../../test/helpers';
|
||||
|
||||
vi.mock('node:dns/promises', () => ({
|
||||
default: {
|
||||
lookup: vi.fn(async () => ({address: '1.2.3.4', family: 4})),
|
||||
},
|
||||
}));
|
||||
|
||||
/**
|
||||
* Integration Tests: Workflow Execution Engine
|
||||
*
|
||||
@@ -59,11 +66,11 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.CONDITION,
|
||||
name: 'Check Premium Status',
|
||||
position: {x: 100, y: 0},
|
||||
config: {
|
||||
config: toPrismaJson({
|
||||
field: 'data.isPremium',
|
||||
operator: 'equals',
|
||||
value: true,
|
||||
},
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -74,7 +81,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.EXIT,
|
||||
name: 'Premium Path',
|
||||
position: {x: 200, y: -50},
|
||||
config: {reason: 'Premium customer'},
|
||||
config: toPrismaJson({reason: 'Premium customer'}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -84,7 +91,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.EXIT,
|
||||
name: 'Standard Path',
|
||||
position: {x: 200, y: 50},
|
||||
config: {reason: 'Standard customer'},
|
||||
config: toPrismaJson({reason: 'Standard customer'}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -97,7 +104,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
data: {
|
||||
fromStepId: conditionStep.id,
|
||||
toStepId: yesStep.id,
|
||||
condition: {branch: 'yes'},
|
||||
condition: toPrismaJson({branch: 'yes'}),
|
||||
priority: 1,
|
||||
},
|
||||
});
|
||||
@@ -106,7 +113,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
data: {
|
||||
fromStepId: conditionStep.id,
|
||||
toStepId: noStep.id,
|
||||
condition: {branch: 'no'},
|
||||
condition: toPrismaJson({branch: 'no'}),
|
||||
priority: 2,
|
||||
},
|
||||
});
|
||||
@@ -118,7 +125,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
contactId: contact.id,
|
||||
status: WorkflowExecutionStatus.RUNNING,
|
||||
currentStepId: triggerStep.id,
|
||||
context: {},
|
||||
context: toPrismaJson({}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -160,11 +167,11 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.CONDITION,
|
||||
name: 'Check Premium',
|
||||
position: {x: 100, y: 0},
|
||||
config: {
|
||||
config: toPrismaJson({
|
||||
field: 'data.isPremium',
|
||||
operator: 'equals',
|
||||
value: true,
|
||||
},
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -174,7 +181,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.EXIT,
|
||||
name: 'Premium',
|
||||
position: {x: 200, y: -50},
|
||||
config: {},
|
||||
config: toPrismaJson({}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -184,7 +191,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.EXIT,
|
||||
name: 'Standard',
|
||||
position: {x: 200, y: 50},
|
||||
config: {},
|
||||
config: toPrismaJson({}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -196,7 +203,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
data: {
|
||||
fromStepId: conditionStep.id,
|
||||
toStepId: yesStep.id,
|
||||
condition: {branch: 'yes'},
|
||||
condition: toPrismaJson({branch: 'yes'}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -204,7 +211,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
data: {
|
||||
fromStepId: conditionStep.id,
|
||||
toStepId: noStep.id,
|
||||
condition: {branch: 'no'},
|
||||
condition: toPrismaJson({branch: 'no'}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -214,7 +221,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
contactId: contact.id,
|
||||
status: WorkflowExecutionStatus.RUNNING,
|
||||
currentStepId: triggerStep.id,
|
||||
context: {},
|
||||
context: toPrismaJson({}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -250,7 +257,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.CONDITION,
|
||||
name: 'Check Country',
|
||||
position: {x: 100, y: 0},
|
||||
config: {field: 'data.country', operator: 'equals', value: 'US'},
|
||||
config: toPrismaJson({field: 'data.country', operator: 'equals', value: 'US'}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -261,7 +268,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.CONDITION,
|
||||
name: 'Check Premium (US)',
|
||||
position: {x: 200, y: -50},
|
||||
config: {field: 'data.isPremium', operator: 'equals', value: true},
|
||||
config: toPrismaJson({field: 'data.isPremium', operator: 'equals', value: true}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -271,7 +278,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.EXIT,
|
||||
name: 'US Premium',
|
||||
position: {x: 300, y: -75},
|
||||
config: {},
|
||||
config: toPrismaJson({}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -281,7 +288,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.EXIT,
|
||||
name: 'US Standard',
|
||||
position: {x: 300, y: -25},
|
||||
config: {},
|
||||
config: toPrismaJson({}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -291,7 +298,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.EXIT,
|
||||
name: 'Non-US',
|
||||
position: {x: 200, y: 50},
|
||||
config: {},
|
||||
config: toPrismaJson({}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -304,7 +311,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
data: {
|
||||
fromStepId: condition1.id,
|
||||
toStepId: condition2.id,
|
||||
condition: {branch: 'yes'},
|
||||
condition: toPrismaJson({branch: 'yes'}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -312,7 +319,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
data: {
|
||||
fromStepId: condition1.id,
|
||||
toStepId: nonUsExit.id,
|
||||
condition: {branch: 'no'},
|
||||
condition: toPrismaJson({branch: 'no'}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -320,7 +327,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
data: {
|
||||
fromStepId: condition2.id,
|
||||
toStepId: usPremiumExit.id,
|
||||
condition: {branch: 'yes'},
|
||||
condition: toPrismaJson({branch: 'yes'}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -328,7 +335,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
data: {
|
||||
fromStepId: condition2.id,
|
||||
toStepId: usStandardExit.id,
|
||||
condition: {branch: 'no'},
|
||||
condition: toPrismaJson({branch: 'no'}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -338,7 +345,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
contactId: contact.id,
|
||||
status: WorkflowExecutionStatus.RUNNING,
|
||||
currentStepId: triggerStep.id,
|
||||
context: {},
|
||||
context: toPrismaJson({}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -378,10 +385,10 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.WAIT_FOR_EVENT,
|
||||
name: 'Wait for Purchase',
|
||||
position: {x: 100, y: 0},
|
||||
config: {
|
||||
config: toPrismaJson({
|
||||
eventName: 'purchase.completed',
|
||||
timeout: 3600, // 1 hour
|
||||
},
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -391,7 +398,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.EXIT,
|
||||
name: 'Complete',
|
||||
position: {x: 200, y: 0},
|
||||
config: {},
|
||||
config: toPrismaJson({}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -409,7 +416,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
contactId: contact.id,
|
||||
status: WorkflowExecutionStatus.RUNNING,
|
||||
currentStepId: triggerStep.id,
|
||||
context: {},
|
||||
context: toPrismaJson({}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -447,10 +454,10 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.WAIT_FOR_EVENT,
|
||||
name: 'Wait for Event',
|
||||
position: {x: 100, y: 0},
|
||||
config: {
|
||||
config: toPrismaJson({
|
||||
eventName: 'user.verified',
|
||||
timeout: 3600,
|
||||
},
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -460,7 +467,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.EXIT,
|
||||
name: 'Done',
|
||||
position: {x: 200, y: 0},
|
||||
config: {},
|
||||
config: toPrismaJson({}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -478,7 +485,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
contactId: contact.id,
|
||||
status: WorkflowExecutionStatus.RUNNING,
|
||||
currentStepId: triggerStep.id,
|
||||
context: {},
|
||||
context: toPrismaJson({}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -526,7 +533,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.DELAY,
|
||||
name: 'Wait 1 day',
|
||||
position: {x: 100, y: 0},
|
||||
config: {amount: 1, unit: 'days'},
|
||||
config: toPrismaJson({amount: 1, unit: 'days'}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -536,7 +543,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.CONDITION,
|
||||
name: 'Check Status',
|
||||
position: {x: 200, y: 0},
|
||||
config: {field: 'contact.subscribed', operator: 'equals', value: true},
|
||||
config: toPrismaJson({field: 'contact.subscribed', operator: 'equals', value: true}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -546,7 +553,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.EXIT,
|
||||
name: 'Complete',
|
||||
position: {x: 300, y: 0},
|
||||
config: {},
|
||||
config: toPrismaJson({}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -561,7 +568,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
data: {
|
||||
fromStepId: condition.id,
|
||||
toStepId: exit.id,
|
||||
condition: {branch: 'yes'},
|
||||
condition: toPrismaJson({branch: 'yes'}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -571,7 +578,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
contactId: contact.id,
|
||||
status: WorkflowExecutionStatus.RUNNING,
|
||||
currentStepId: triggerStep.id,
|
||||
context: {},
|
||||
context: toPrismaJson({}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -611,7 +618,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.CONDITION,
|
||||
name: 'A/B Split',
|
||||
position: {x: 100, y: 0},
|
||||
config: {field: 'data.segment', operator: 'equals', value: 'A'},
|
||||
config: toPrismaJson({field: 'data.segment', operator: 'equals', value: 'A'}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -621,7 +628,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.DELAY,
|
||||
name: 'Path A Delay',
|
||||
position: {x: 200, y: -50},
|
||||
config: {amount: 1, unit: 'hours'},
|
||||
config: toPrismaJson({amount: 1, unit: 'hours'}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -631,7 +638,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.DELAY,
|
||||
name: 'Path B Delay',
|
||||
position: {x: 200, y: 50},
|
||||
config: {amount: 2, unit: 'hours'},
|
||||
config: toPrismaJson({amount: 2, unit: 'hours'}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -641,7 +648,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.EXIT,
|
||||
name: 'Merge Point',
|
||||
position: {x: 300, y: 0},
|
||||
config: {},
|
||||
config: toPrismaJson({}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -653,7 +660,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
data: {
|
||||
fromStepId: condition.id,
|
||||
toStepId: pathA.id,
|
||||
condition: {branch: 'yes'},
|
||||
condition: toPrismaJson({branch: 'yes'}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -661,7 +668,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
data: {
|
||||
fromStepId: condition.id,
|
||||
toStepId: pathB.id,
|
||||
condition: {branch: 'no'},
|
||||
condition: toPrismaJson({branch: 'no'}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -679,7 +686,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
contactId: contact.id,
|
||||
status: WorkflowExecutionStatus.RUNNING,
|
||||
currentStepId: triggerStep.id,
|
||||
context: {},
|
||||
context: toPrismaJson({}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -717,7 +724,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.CONDITION,
|
||||
name: 'Bad Condition',
|
||||
position: {x: 100, y: 0},
|
||||
config: {}, // Invalid - missing required fields
|
||||
config: toPrismaJson({}), // Invalid - missing required fields
|
||||
},
|
||||
});
|
||||
|
||||
@@ -731,7 +738,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
contactId: contact.id,
|
||||
status: WorkflowExecutionStatus.RUNNING,
|
||||
currentStepId: triggerStep.id,
|
||||
context: {},
|
||||
context: toPrismaJson({}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -764,11 +771,11 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.CONDITION,
|
||||
name: 'Check Missing Field',
|
||||
position: {x: 100, y: 0},
|
||||
config: {
|
||||
config: toPrismaJson({
|
||||
field: 'data.nonExistentField',
|
||||
operator: 'equals',
|
||||
value: 'something',
|
||||
},
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -778,7 +785,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.EXIT,
|
||||
name: 'Exit',
|
||||
position: {x: 200, y: 0},
|
||||
config: {},
|
||||
config: toPrismaJson({}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -790,7 +797,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
data: {
|
||||
fromStepId: condition.id,
|
||||
toStepId: noStep.id,
|
||||
condition: {branch: 'no'},
|
||||
condition: toPrismaJson({branch: 'no'}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -800,7 +807,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
contactId: contact.id,
|
||||
status: WorkflowExecutionStatus.RUNNING,
|
||||
currentStepId: triggerStep.id,
|
||||
context: {},
|
||||
context: toPrismaJson({}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -834,7 +841,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.EXIT,
|
||||
name: 'Early Exit',
|
||||
position: {x: 100, y: 0},
|
||||
config: {reason: 'User already converted'},
|
||||
config: toPrismaJson({reason: 'User already converted'}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -848,7 +855,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
contactId: contact.id,
|
||||
status: WorkflowExecutionStatus.RUNNING,
|
||||
currentStepId: triggerStep.id,
|
||||
context: {},
|
||||
context: toPrismaJson({}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -882,7 +889,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.TRIGGER,
|
||||
name: 'Start',
|
||||
position: {x: 0, y: 0},
|
||||
config: {},
|
||||
config: toPrismaJson({}),
|
||||
});
|
||||
|
||||
const exitStep = await factories.createWorkflowStep({
|
||||
@@ -890,7 +897,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.EXIT,
|
||||
name: 'End',
|
||||
position: {x: 100, y: 0},
|
||||
config: {},
|
||||
config: toPrismaJson({}),
|
||||
});
|
||||
|
||||
await prisma.workflowTransition.create({
|
||||
@@ -910,7 +917,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
contactId: contact.id,
|
||||
status: WorkflowExecutionStatus.RUNNING,
|
||||
currentStepId: triggerStep.id,
|
||||
context: contextData as Prisma.InputJsonValue,
|
||||
context: toPrismaJson(contextData),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -974,11 +981,11 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.CONDITION,
|
||||
name: 'Check if first open',
|
||||
position: {x: 100, y: 0},
|
||||
config: {
|
||||
config: toPrismaJson({
|
||||
field: 'event.isFirstOpen',
|
||||
operator: 'equals',
|
||||
value: true, // Use boolean, not string
|
||||
} as Prisma.InputJsonValue,
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -988,7 +995,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.EXIT,
|
||||
name: 'First Open',
|
||||
position: {x: 200, y: 0},
|
||||
config: {reason: 'first_open'} as Prisma.InputJsonValue,
|
||||
config: toPrismaJson({reason: 'first_open'}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -998,7 +1005,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.EXIT,
|
||||
name: 'Not First Open',
|
||||
position: {x: 200, y: 100},
|
||||
config: {reason: 'not_first_open'} as Prisma.InputJsonValue,
|
||||
config: toPrismaJson({reason: 'not_first_open'}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1007,10 +1014,10 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
data: {fromStepId: triggerStep!.id, toStepId: conditionStep.id},
|
||||
});
|
||||
await prisma.workflowTransition.create({
|
||||
data: {fromStepId: conditionStep.id, toStepId: yesStep.id, condition: {branch: 'yes'} as Prisma.InputJsonValue},
|
||||
data: {fromStepId: conditionStep.id, toStepId: yesStep.id, condition: toPrismaJson({branch: 'yes'})},
|
||||
});
|
||||
await prisma.workflowTransition.create({
|
||||
data: {fromStepId: conditionStep.id, toStepId: noStep.id, condition: {branch: 'no'} as Prisma.InputJsonValue},
|
||||
data: {fromStepId: conditionStep.id, toStepId: noStep.id, condition: toPrismaJson({branch: 'no'})},
|
||||
});
|
||||
|
||||
// Create execution with event data
|
||||
@@ -1020,12 +1027,12 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
contactId: contact.id,
|
||||
status: WorkflowExecutionStatus.RUNNING,
|
||||
currentStepId: triggerStep!.id,
|
||||
context: {
|
||||
context: toPrismaJson({
|
||||
subject: 'Welcome Email',
|
||||
from: 'hello@example.com',
|
||||
isFirstOpen: true,
|
||||
openedAt: new Date().toISOString(),
|
||||
} as Prisma.InputJsonValue,
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1056,11 +1063,11 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.CONDITION,
|
||||
name: 'Check subject',
|
||||
position: {x: 100, y: 0},
|
||||
config: {
|
||||
config: toPrismaJson({
|
||||
field: 'event.subject',
|
||||
operator: 'contains',
|
||||
value: 'Welcome',
|
||||
} as Prisma.InputJsonValue,
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1070,7 +1077,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.EXIT,
|
||||
name: 'Done',
|
||||
position: {x: 200, y: 0},
|
||||
config: {reason: 'matched'} as Prisma.InputJsonValue,
|
||||
config: toPrismaJson({reason: 'matched'}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1081,7 +1088,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
data: {
|
||||
fromStepId: conditionStep.id,
|
||||
toStepId: exitStep.id,
|
||||
condition: {branch: 'yes'} as Prisma.InputJsonValue,
|
||||
condition: toPrismaJson({branch: 'yes'}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1091,10 +1098,10 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
contactId: contact.id,
|
||||
status: WorkflowExecutionStatus.RUNNING,
|
||||
currentStepId: triggerStep!.id,
|
||||
context: {
|
||||
context: toPrismaJson({
|
||||
subject: 'Welcome to Plunk!',
|
||||
from: 'team@plunk.com',
|
||||
} as Prisma.InputJsonValue,
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1122,11 +1129,11 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.CONDITION,
|
||||
name: 'Check opens count',
|
||||
position: {x: 100, y: 0},
|
||||
config: {
|
||||
config: toPrismaJson({
|
||||
field: 'event.opens',
|
||||
operator: 'greaterThan',
|
||||
value: '3',
|
||||
} as Prisma.InputJsonValue,
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1136,7 +1143,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.EXIT,
|
||||
name: 'Done',
|
||||
position: {x: 200, y: 0},
|
||||
config: {reason: 'engaged'} as Prisma.InputJsonValue,
|
||||
config: toPrismaJson({reason: 'engaged'}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1147,7 +1154,7 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
data: {
|
||||
fromStepId: conditionStep.id,
|
||||
toStepId: exitStep.id,
|
||||
condition: {branch: 'yes'} as Prisma.InputJsonValue,
|
||||
condition: toPrismaJson({branch: 'yes'}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1157,10 +1164,10 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
contactId: contact.id,
|
||||
status: WorkflowExecutionStatus.RUNNING,
|
||||
currentStepId: triggerStep!.id,
|
||||
context: {
|
||||
context: toPrismaJson({
|
||||
subject: 'Newsletter',
|
||||
opens: 5,
|
||||
} as Prisma.InputJsonValue,
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1204,10 +1211,10 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
type: WorkflowStepType.WEBHOOK,
|
||||
name: 'Send Webhook',
|
||||
position: {x: 100, y: 0},
|
||||
config: {
|
||||
config: toPrismaJson({
|
||||
url: 'https://webhook.example.com/test',
|
||||
method: 'POST',
|
||||
} as Prisma.InputJsonValue,
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1221,13 +1228,13 @@ describe('WorkflowExecutionService - Integration Tests', () => {
|
||||
contactId: contact.id,
|
||||
status: WorkflowExecutionStatus.RUNNING,
|
||||
currentStepId: triggerStep!.id,
|
||||
context: {
|
||||
context: toPrismaJson({
|
||||
subject: 'Welcome Email',
|
||||
from: 'hello@example.com',
|
||||
messageId: 'msg-123',
|
||||
isFirstOpen: true,
|
||||
openedAt: '2024-01-15T10:00:00Z',
|
||||
} as Prisma.InputJsonValue,
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import {describe, it, expect, beforeEach} from 'vitest';
|
||||
import {beforeEach, describe, expect, it} from 'vitest';
|
||||
import {
|
||||
WorkflowStepType,
|
||||
StepExecutionStatus,
|
||||
WorkflowExecutionStatus,
|
||||
TemplateType,
|
||||
WorkflowExecutionStatus,
|
||||
WorkflowStepType,
|
||||
WorkflowTriggerType,
|
||||
} from '@plunk/db';
|
||||
import {WorkflowExecutionService} from '../WorkflowExecutionService';
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {StepExecutionStatus, WorkflowExecutionStatus, WorkflowStepType, WorkflowTriggerType} from '@plunk/db';
|
||||
import {WorkflowExecutionService} from '../WorkflowExecutionService';
|
||||
import {factories, getPrismaClient} from '../../../../../test/helpers';
|
||||
|
||||
/**
|
||||
* Tests for WEBHOOK step config templating.
|
||||
*
|
||||
* `executeWebhook` is a private static method but is invokable at runtime
|
||||
* through a `as any` cast. We mock `safeFetch` (also private) via the
|
||||
* same mechanism so we can capture the rendered request without making a
|
||||
* real network call.
|
||||
*/
|
||||
describe('WorkflowExecutionService.executeWebhook templating', () => {
|
||||
let projectId: string;
|
||||
const prisma = getPrismaClient();
|
||||
|
||||
// Capture (url, options) passed to safeFetch
|
||||
let safeFetchSpy: ReturnType<typeof vi.spyOn>;
|
||||
let captured: {url: string; options: RequestInit} | null = null;
|
||||
|
||||
beforeEach(async () => {
|
||||
const {project} = await factories.createUserWithProject();
|
||||
projectId = project.id;
|
||||
|
||||
captured = null;
|
||||
safeFetchSpy = vi
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
.spyOn(WorkflowExecutionService as any, 'safeFetch')
|
||||
.mockImplementation(async (...args: unknown[]) => {
|
||||
const [url, options] = args as [string, RequestInit];
|
||||
captured = {url, options};
|
||||
return new Response('{"ok":true}', {
|
||||
status: 200,
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
safeFetchSpy.mockRestore();
|
||||
});
|
||||
|
||||
/**
|
||||
* Helper: build a workflow with a single WEBHOOK step using the given
|
||||
* config, plus a contact and a RUNNING execution. Returns the args
|
||||
* shape `executeWebhook` expects.
|
||||
*/
|
||||
async function setup(
|
||||
webhookConfig: Record<string, unknown>,
|
||||
contactOverrides: {data?: Record<string, unknown>} = {},
|
||||
executionContext: Record<string, unknown> = {},
|
||||
) {
|
||||
const contact = await factories.createContact({
|
||||
projectId,
|
||||
data: contactOverrides.data,
|
||||
});
|
||||
|
||||
const workflow = await factories.createWorkflow({
|
||||
projectId,
|
||||
enabled: true,
|
||||
triggerType: WorkflowTriggerType.EVENT,
|
||||
triggerConfig: {eventName: 'test.event'},
|
||||
});
|
||||
|
||||
const step = await prisma.workflowStep.create({
|
||||
data: {
|
||||
workflowId: workflow.id,
|
||||
type: WorkflowStepType.WEBHOOK,
|
||||
name: 'Webhook',
|
||||
position: {x: 0, y: 0},
|
||||
config: webhookConfig,
|
||||
},
|
||||
});
|
||||
|
||||
const execution = await prisma.workflowExecution.create({
|
||||
data: {
|
||||
workflowId: workflow.id,
|
||||
contactId: contact.id,
|
||||
status: WorkflowExecutionStatus.RUNNING,
|
||||
context: executionContext,
|
||||
},
|
||||
include: {contact: true, workflow: true},
|
||||
});
|
||||
|
||||
const stepExecution = await prisma.workflowStepExecution.create({
|
||||
data: {
|
||||
executionId: execution.id,
|
||||
stepId: step.id,
|
||||
status: StepExecutionStatus.RUNNING,
|
||||
startedAt: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
return {step, execution, stepExecution};
|
||||
}
|
||||
|
||||
async function invokeWebhook(
|
||||
step: unknown,
|
||||
execution: unknown,
|
||||
stepExecution: unknown,
|
||||
config: unknown,
|
||||
) {
|
||||
// Call through `as any` because executeWebhook is private at the
|
||||
// TypeScript level. JS has no actual access control.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return (WorkflowExecutionService as any).executeWebhook(step, execution, stepExecution, config);
|
||||
}
|
||||
|
||||
it('renders {{vars}} in the URL from contact.data', async () => {
|
||||
const {step, execution, stepExecution} = await setup(
|
||||
{
|
||||
url: 'https://example.com/api/users/{{userId}}',
|
||||
method: 'GET',
|
||||
},
|
||||
{data: {userId: 'abc-123'}},
|
||||
);
|
||||
|
||||
await invokeWebhook(step, execution, stepExecution, step.config);
|
||||
|
||||
expect(captured).not.toBeNull();
|
||||
expect(captured!.url).toBe('https://example.com/api/users/abc-123');
|
||||
});
|
||||
|
||||
it('renders {{vars}} in header values', async () => {
|
||||
const {step, execution, stepExecution} = await setup(
|
||||
{
|
||||
url: 'https://example.com/hook',
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: 'Bearer {{apiToken}}',
|
||||
'X-Static': 'literal',
|
||||
},
|
||||
},
|
||||
{data: {apiToken: 'secret-token-xyz'}},
|
||||
);
|
||||
|
||||
await invokeWebhook(step, execution, stepExecution, step.config);
|
||||
|
||||
expect(captured).not.toBeNull();
|
||||
const headers = captured!.options.headers as Record<string, string>;
|
||||
expect(headers.Authorization).toBe('Bearer secret-token-xyz');
|
||||
expect(headers['X-Static']).toBe('literal');
|
||||
});
|
||||
|
||||
it('renders {{vars}} in nested object body leaves and JSON-encodes', async () => {
|
||||
const {step, execution, stepExecution} = await setup(
|
||||
{
|
||||
url: 'https://example.com/hook',
|
||||
method: 'POST',
|
||||
body: {
|
||||
user: {
|
||||
email: '{{email}}',
|
||||
name: '{{firstName}}',
|
||||
},
|
||||
ref: 'literal-ref',
|
||||
tags: ['plan:{{plan}}', 'static'],
|
||||
},
|
||||
},
|
||||
{data: {firstName: 'Ada', plan: 'gold'}},
|
||||
{campaignId: 'camp-9'},
|
||||
);
|
||||
|
||||
await invokeWebhook(step, execution, stepExecution, step.config);
|
||||
|
||||
expect(captured).not.toBeNull();
|
||||
const body = JSON.parse(captured!.options.body as string);
|
||||
expect(body.user.email).toBe(execution.contact.email);
|
||||
expect(body.user.name).toBe('Ada');
|
||||
expect(body.ref).toBe('literal-ref');
|
||||
expect(body.tags).toEqual(['plan:gold', 'static']);
|
||||
});
|
||||
|
||||
it('leaves non-string body leaves untouched', async () => {
|
||||
const {step, execution, stepExecution} = await setup({
|
||||
url: 'https://example.com/hook',
|
||||
method: 'POST',
|
||||
body: {
|
||||
score: 42,
|
||||
active: true,
|
||||
deleted: null,
|
||||
meta: {
|
||||
count: 7,
|
||||
enabled: false,
|
||||
},
|
||||
tags: ['{{plan ?? free}}', 100, false],
|
||||
},
|
||||
});
|
||||
|
||||
await invokeWebhook(step, execution, stepExecution, step.config);
|
||||
|
||||
expect(captured).not.toBeNull();
|
||||
const body = JSON.parse(captured!.options.body as string);
|
||||
expect(body.score).toBe(42);
|
||||
expect(body.active).toBe(true);
|
||||
expect(body.deleted).toBe(null);
|
||||
expect(body.meta).toEqual({count: 7, enabled: false});
|
||||
// String leaf rendered (with default), non-string leaves preserved.
|
||||
expect(body.tags).toEqual(['free', 100, false]);
|
||||
});
|
||||
|
||||
it('renders {{event.*}} variables from the trigger payload', async () => {
|
||||
const {step, execution, stepExecution} = await setup(
|
||||
{
|
||||
url: 'https://example.com/hooks/{{event.referrer}}',
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'X-Email-Id': '{{event.emailId}}',
|
||||
},
|
||||
body: {
|
||||
referrer: '{{event.referrer}}',
|
||||
subject: '{{event.subject}}',
|
||||
},
|
||||
},
|
||||
{},
|
||||
{referrer: 'newsletter-may', emailId: 'eml_abc123', subject: 'Welcome'},
|
||||
);
|
||||
|
||||
await invokeWebhook(step, execution, stepExecution, step.config);
|
||||
|
||||
expect(captured).not.toBeNull();
|
||||
expect(captured!.url).toBe('https://example.com/hooks/newsletter-may');
|
||||
const headers = captured!.options.headers as Record<string, string>;
|
||||
expect(headers['X-Email-Id']).toBe('eml_abc123');
|
||||
const body = JSON.parse(captured!.options.body as string);
|
||||
expect(body.referrer).toBe('newsletter-may');
|
||||
expect(body.subject).toBe('Welcome');
|
||||
});
|
||||
});
|
||||
@@ -205,7 +205,7 @@ describe('WorkflowService', () => {
|
||||
|
||||
const page1 = await WorkflowService.list(projectId, 1, 10);
|
||||
|
||||
expect(page1.workflows).toHaveLength(10);
|
||||
expect(page1.data).toHaveLength(10);
|
||||
expect(page1.total).toBe(25);
|
||||
expect(page1.totalPages).toBe(3);
|
||||
});
|
||||
@@ -218,7 +218,7 @@ describe('WorkflowService', () => {
|
||||
const result = await WorkflowService.list(projectId, 1, 20, 'welcome');
|
||||
|
||||
expect(result.total).toBe(2);
|
||||
expect(result.workflows.every(w => w.name.toLowerCase().includes('welcome'))).toBe(true);
|
||||
expect(result.data.every(w => w.name.toLowerCase().includes('welcome'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should include step and execution counts', async () => {
|
||||
@@ -234,8 +234,8 @@ describe('WorkflowService', () => {
|
||||
|
||||
const result = await WorkflowService.list(projectId);
|
||||
|
||||
const found = result.workflows.find(w => w.id === workflow.id) as
|
||||
| ((typeof result.workflows)[number] & {_count: {steps: number; executions: number}})
|
||||
const found = result.data.find(w => w.id === workflow.id) as
|
||||
| ((typeof result.data)[number] & {_count: {steps: number; executions: number}})
|
||||
| undefined;
|
||||
expect(found?._count.steps).toBe(3); // TRIGGER + 2 added
|
||||
expect(found?._count.executions).toBe(1);
|
||||
@@ -758,8 +758,20 @@ describe('WorkflowService', () => {
|
||||
});
|
||||
const contact = await factories.createContact({projectId});
|
||||
|
||||
// Start first execution (still running)
|
||||
await WorkflowService.startExecution(projectId, workflow.id, contact.id);
|
||||
// Insert a RUNNING execution directly to avoid racing with the background
|
||||
// step processor that startExecution kicks off (a trigger-only workflow can
|
||||
// transition to COMPLETED before the second call observes it as RUNNING).
|
||||
const triggerStep = await prisma.workflowStep.findFirst({
|
||||
where: {workflowId: workflow.id, type: WorkflowStepType.TRIGGER},
|
||||
});
|
||||
await prisma.workflowExecution.create({
|
||||
data: {
|
||||
workflowId: workflow.id,
|
||||
contactId: contact.id,
|
||||
status: WorkflowExecutionStatus.RUNNING,
|
||||
currentStepId: triggerStep?.id,
|
||||
},
|
||||
});
|
||||
|
||||
// Second execution should fail (first still running)
|
||||
await expect(WorkflowService.startExecution(projectId, workflow.id, contact.id)).rejects.toThrow(
|
||||
|
||||
@@ -6,6 +6,18 @@ export const Keys = {
|
||||
email(email: string): string {
|
||||
return `account:${email}`;
|
||||
},
|
||||
emailVerificationToken(token: string): string {
|
||||
return `auth:email_verification:${token}`;
|
||||
},
|
||||
passwordResetToken(token: string): string {
|
||||
return `auth:password_reset:${token}`;
|
||||
},
|
||||
emailVerificationRateLimit(userId: string): string {
|
||||
return `auth:email_verification_rate:${userId}`;
|
||||
},
|
||||
passwordResetRateLimit(email: string): string {
|
||||
return `auth:password_reset_rate:${email}`;
|
||||
},
|
||||
},
|
||||
Domain: {
|
||||
id(id: string): string {
|
||||
@@ -14,6 +26,12 @@ export const Keys = {
|
||||
project(projectId: string): string {
|
||||
return `domain:project:${projectId}`;
|
||||
},
|
||||
verifiedEmail(domainId: string): string {
|
||||
return `domain:verified_email:${domainId}`;
|
||||
},
|
||||
unverifiedEmail(domainId: string, year: number, month: string): string {
|
||||
return `domain:unverified_email:${domainId}:${year}-${month}`;
|
||||
},
|
||||
},
|
||||
Billing: {
|
||||
usage(projectId: string, sourceType: string, year: number, month: string): string {
|
||||
@@ -35,6 +53,9 @@ export const Keys = {
|
||||
stats(projectId: string, startTime: number | string, endTime: number | string): string {
|
||||
return `activity:stats:${projectId}:${startTime}:${endTime}`;
|
||||
},
|
||||
recentCount(projectId: string, minutes: number): string {
|
||||
return `activity:recent-count:${projectId}:${minutes}`;
|
||||
},
|
||||
},
|
||||
Analytics: {
|
||||
timeseries(projectId: string, startDate: string, endDate: string): string {
|
||||
@@ -52,4 +73,29 @@ export const Keys = {
|
||||
return `workflows:enabled:${projectId}`;
|
||||
},
|
||||
},
|
||||
Membership: {
|
||||
access(userId: string, projectId: string): string {
|
||||
return `membership:access:${userId}:${projectId}`;
|
||||
},
|
||||
admin(userId: string, projectId: string): string {
|
||||
return `membership:admin:${userId}:${projectId}`;
|
||||
},
|
||||
full(userId: string, projectId: string): string {
|
||||
return `membership:full:${userId}:${projectId}`;
|
||||
},
|
||||
owner(projectId: string): string {
|
||||
return `membership:owner:${projectId}`;
|
||||
},
|
||||
},
|
||||
Project: {
|
||||
id(id: string): string {
|
||||
return `project:id:${id}`;
|
||||
},
|
||||
secret(key: string): string {
|
||||
return `project:secret:${key}`;
|
||||
},
|
||||
public(key: string): string {
|
||||
return `project:public:${key}`;
|
||||
},
|
||||
},
|
||||
} as const;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/** @type {import('next-sitemap').IConfig} */
|
||||
module.exports = {
|
||||
siteUrl: process.env.NEXT_PUBLIC_LANDING_URI || 'https://www.swyp.be',
|
||||
siteUrl: process.env.NEXT_PUBLIC_LANDING_URI || 'https://www.useplunk.com',
|
||||
generateRobotsTxt: true,
|
||||
};
|
||||
|
||||
@@ -14,8 +14,20 @@
|
||||
"@plunk/db": "*",
|
||||
"@plunk/shared": "*",
|
||||
"@plunk/ui": "*",
|
||||
"@tiptap/core": "^3.11.0",
|
||||
"@tiptap/extension-color": "^3.11.0",
|
||||
"@tiptap/extension-image": "^3.11.0",
|
||||
"@tiptap/extension-link": "^3.11.0",
|
||||
"@tiptap/extension-placeholder": "^3.11.0",
|
||||
"@tiptap/extension-text-align": "^3.11.0",
|
||||
"@tiptap/extension-text-style": "^3.11.0",
|
||||
"@tiptap/extension-underline": "^3.11.0",
|
||||
"@tiptap/pm": "^3.11.0",
|
||||
"@tiptap/react": "^3.11.0",
|
||||
"@tiptap/starter-kit": "^3.11.0",
|
||||
"juice": "^11.0.3",
|
||||
"lucide-react": "^0.553.0",
|
||||
"next": "^16.0.10",
|
||||
"next": "^16.2.3",
|
||||
"next-seo": "^6.6.0",
|
||||
"react": "19.2.3",
|
||||
"react-dom": "19.2.3",
|
||||
|
||||
|
Before Width: | Height: | Size: 125 KiB |
@@ -0,0 +1,12 @@
|
||||
<svg width="192" height="30" viewBox="0 0 192 30" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<rect x="0.3" y="0.3" width="29.4" height="29.4" rx="14.7" fill="#C6FE1E"/>
|
||||
<rect x="0.3" y="0.3" width="29.4" height="29.4" rx="14.7" stroke="#B3E910" stroke-width="0.6"/>
|
||||
<mask id="mask0_1720_1740" style="mask-type:luminance" maskUnits="userSpaceOnUse" x="5" y="8" width="20" height="15">
|
||||
<path d="M24.0038 8H5.99805V23H24.0038V8Z" fill="white"/>
|
||||
</mask>
|
||||
<g mask="url(#mask0_1720_1740)">
|
||||
<path d="M12.9679 11.4606H12.9599C12.4637 11.3182 11.9387 11.603 11.7707 12.0734C11.585 12.579 11.8795 13.1582 12.3997 13.3182C13.6737 13.6798 14.2211 11.8542 12.9679 11.4606Z" fill="#00160D"/>
|
||||
<path d="M23.8265 14.0425C22.1859 10.4505 16.9523 11.9369 16.4689 10.9961C15.0525 8.77368 12.4084 7.52568 9.54993 8.16888C9.10979 7.99288 7.59411 7.94488 6.6146 8.56088L7.20518 8.82168C7.25 8.84088 7.23719 8.83608 7.30281 8.86008C7.5701 8.96088 7.52368 8.93208 7.33162 9.03768C6.89148 9.29528 6.34251 9.59448 6 10.0441C6.0144 10.0649 6.75384 10.2425 6.75384 10.2425C6.76664 10.2457 6.90429 10.2601 6.87388 10.3209C4.45551 14.1385 8.5336 19.9001 10.5134 23.0009H16.2449C15.3598 21.4169 14.3483 19.2553 14.694 17.7881C14.7564 17.5225 14.8364 17.1849 15.1629 17.1401C15.952 17.0137 17.0083 17.0249 17.7605 16.9401C17.7605 16.9401 17.7643 16.9401 17.7717 16.9401C17.9318 16.9321 21.8498 16.4345 22.7877 18.8761C22.8678 19.1001 23.0518 18.9545 23.1254 18.8073C23.8249 17.4169 24.2762 15.2281 23.8297 14.0441L23.8265 14.0425ZM17.5013 12.8633C17.226 13.3545 17.0387 13.9929 16.9907 14.5497C16.9651 14.9033 17.0019 15.2521 17.0371 15.6057C17.0563 15.8009 17.0579 16.0473 16.9011 16.1753C16.765 16.2905 16.5393 16.3017 16.3121 16.3177C15.1965 16.3129 12.4757 16.3177 11.4273 15.6041L11.4209 15.5993C9.89564 14.6697 9.07938 12.5705 9.98527 10.9401C10.2782 10.3865 10.8175 10.0265 11.4321 9.89048C12.2228 9.70968 13.0935 9.84408 13.7993 10.2137C14.0874 10.3593 14.4315 10.5513 14.694 10.7721C15.2141 11.2265 15.6591 11.6985 16.3409 11.8441C16.6546 11.9337 16.9811 11.9209 17.2948 11.9849C17.8822 12.1257 17.7349 12.4601 17.4997 12.8601L17.5013 12.8633Z" fill="#00160D"/>
|
||||
</g>
|
||||
<path d="M37.392 23V7.4H43.296C47.688 7.4 50.952 10.568 50.952 15.176C50.952 19.64 47.904 23 43.632 23H37.392ZM40.056 20.48H43.44C46.176 20.48 48.168 18.272 48.168 15.2C48.168 12.08 46.08 9.848 43.2 9.848H40.056V20.48ZM57.774 23.288C54.246 23.288 51.75 20.672 51.75 17C51.75 13.328 54.246 10.712 57.774 10.712C61.302 10.712 63.822 13.328 63.822 17C63.822 20.672 61.302 23.288 57.774 23.288ZM57.774 20.816C59.766 20.816 61.206 19.232 61.206 17C61.206 14.72 59.766 13.112 57.774 13.112C55.782 13.112 54.366 14.72 54.366 17C54.366 19.232 55.782 20.816 57.774 20.816ZM69.9786 23.288C66.7866 23.288 64.5066 20.672 64.5066 17C64.5066 13.304 66.7626 10.712 69.9546 10.712C71.5866 10.712 73.0026 11.432 73.9626 12.656V6.68H76.4826V20.6L76.5306 23H74.4666L74.0826 21.2C73.1226 22.496 71.6826 23.288 69.9786 23.288ZM70.5546 20.816C72.5466 20.816 73.9866 19.208 73.9866 17C73.9866 14.744 72.5466 13.136 70.5546 13.136C68.5626 13.136 67.1226 14.744 67.1226 17C67.1226 19.208 68.5626 20.816 70.5546 20.816ZM83.8965 23.288C80.3685 23.288 77.8725 20.672 77.8725 17C77.8725 13.328 80.3685 10.712 83.8965 10.712C87.4245 10.712 89.9445 13.328 89.9445 17C89.9445 20.672 87.4245 23.288 83.8965 23.288ZM83.8965 20.816C85.8885 20.816 87.3285 19.232 87.3285 17C87.3285 14.72 85.8885 13.112 83.8965 13.112C81.9045 13.112 80.4885 14.72 80.4885 17C80.4885 19.232 81.9045 20.816 83.8965 20.816ZM95.667 23V7.4H102.603C105.507 7.4 107.571 9.488 107.571 12.416C107.571 15.368 105.435 17.48 102.483 17.48H98.331V23H95.667ZM98.331 15.2H102.315C103.755 15.2 104.787 14.096 104.787 12.536C104.787 10.976 103.755 9.848 102.315 9.848H98.331V15.2ZM111.711 23.288C109.359 23.288 107.775 21.872 107.775 19.784C107.775 18.176 109.023 16.832 110.919 16.472L114.711 15.728C115.071 15.68 115.311 15.416 115.311 15.104C115.311 13.88 114.423 12.992 113.175 12.992C111.879 12.992 110.871 13.904 110.775 15.272L108.183 14.648C108.567 12.344 110.583 10.712 113.055 10.712C115.839 10.712 117.831 12.584 117.831 15.176V20.6L117.879 23H115.887L115.455 21.368C114.711 22.544 113.343 23.288 111.711 23.288ZM110.487 19.448C110.487 20.312 111.183 20.888 112.335 20.888C114.015 20.888 115.311 19.664 115.311 17.864V17.312C115.071 17.36 114.807 17.432 114.543 17.48L111.927 17.96C111.039 18.128 110.487 18.704 110.487 19.448ZM119.784 25.64C120.84 25.568 121.728 24.992 122.16 23.984L122.712 22.616L117.984 11H120.864L123.96 19.688L126.792 11H129.624L124.44 24.728C123.696 26.696 122.376 27.944 120.744 28.088L119.784 25.64ZM130.303 23V11H132.295L132.727 12.944C133.279 11.624 134.647 10.712 136.255 10.712C137.887 10.712 139.327 11.648 139.951 13.016C140.551 11.648 142.015 10.712 143.695 10.712C146.167 10.712 147.943 12.728 147.943 15.536V23H145.423V15.872C145.423 14.336 144.439 13.208 143.071 13.208C141.535 13.208 140.431 14.504 140.431 16.28V23H137.959V15.92C137.959 14.336 136.951 13.208 135.559 13.208C133.975 13.208 132.823 14.528 132.823 16.376V23H130.303ZM155.115 23.288C151.587 23.288 149.115 20.672 149.115 17C149.115 13.328 151.539 10.712 154.947 10.712C158.763 10.712 160.971 13.976 160.635 17.792H151.803C152.115 19.616 153.411 20.84 155.139 20.84C156.507 20.84 157.611 20.072 157.899 18.944L160.467 19.856C159.843 21.896 157.707 23.288 155.115 23.288ZM151.827 15.92H157.995C157.755 14.24 156.507 13.112 154.947 13.112C153.363 13.112 152.163 14.24 151.827 15.92ZM162.027 23V11H164.043L164.427 12.968C165.075 11.624 166.587 10.712 168.315 10.712C170.955 10.712 172.827 12.8 172.827 15.656V23H170.307V16.064C170.307 14.384 169.203 13.184 167.595 13.184C165.843 13.184 164.547 14.552 164.547 16.472V23H162.027ZM180.599 23.024C178.103 23.792 175.175 23.024 175.175 19.976V13.328H173.375V11H174.071C174.815 11 175.295 10.448 175.295 9.608V7.808H177.695V11H180.455V13.328H177.695V19.4C177.695 20.792 179.015 21.176 180.311 20.696L180.599 23.024ZM186.24 23.288C183.288 23.288 181.08 21.68 180.888 19.448L183.768 18.776C183.84 20.072 184.944 21.032 186.408 21.032C187.536 21.032 188.376 20.432 188.376 19.568C188.376 17.096 181.464 18.032 181.464 14.072C181.464 12.08 183.312 10.712 185.928 10.712C188.616 10.712 190.56 12.104 190.752 14.048L188.016 14.672C187.992 13.616 187.104 12.896 185.856 12.896C184.8 12.896 184.08 13.424 184.08 14.192C184.08 16.592 191.088 15.608 191.088 19.664C191.088 21.776 189.072 23.288 186.24 23.288Z" fill="#00160D"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 6.3 KiB |
@@ -0,0 +1,33 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Layer_1" x="0px" y="0px" width="100%" viewBox="0 0 2400 531" enable-background="new 0 0 2400 531" xml:space="preserve">
|
||||
|
||||
<path fill="#5A17DD" opacity="1.000000" stroke="none" d=" M177.531342,1.000000 C179.057083,2.016129 179.936691,3.463687 181.198273,3.982726 C196.529205,10.290123 206.246201,22.020750 211.758423,37.067310 C214.062714,43.357273 214.598770,50.496723 214.855927,57.290924 C215.321609,69.593918 214.975113,81.927650 214.610489,94.993073 C214.374802,105.590721 214.496323,115.443848 214.617844,125.296967 C214.731262,134.873642 214.844681,144.450302 214.696503,154.805176 C213.707352,157.641037 212.979782,159.698669 211.949341,161.867874 C185.808609,176.848602 159.744293,191.340149 134.183105,206.670563 C89.674866,233.364563 87.927750,297.038086 131.449005,324.829407 C157.666046,341.570770 185.279068,356.126007 212.344147,371.739380 C212.423538,371.815125 212.480209,372.027130 212.369049,372.418213 C212.169983,374.965424 212.006592,377.121552 212.005508,379.277710 C211.989853,410.547516 212.059357,441.817566 211.942383,473.086914 C211.919479,479.210052 212.244370,485.631836 210.591049,491.394318 C206.096237,507.060730 196.645874,519.126404 181.619370,526.280518 C177.450226,528.265381 173.208450,530.097656 169.000000,532.000000 C126.979103,532.000000 84.958214,532.000000 42.345772,531.676025 C41.124565,530.844910 40.572868,530.118103 39.853806,529.862976 C23.633379,524.108398 11.737153,513.795288 5.170585,497.604126 C4.555796,496.088257 2.426259,495.186737 1.000005,494.000000 C1.000000,341.645782 1.000000,189.291550 1.334632,36.704620 C2.153957,35.664326 2.605743,34.834736 3.128503,34.052578 C7.677545,27.246292 11.359032,19.558378 17.063332,13.917211 C22.027281,9.008199 29.292238,6.433895 35.493198,2.748482 C35.874008,2.522156 35.840652,1.598958 36.000000,1.000000 C83.020897,1.000000 130.041794,1.000000 177.531342,1.000000 z"/>
|
||||
<path fill="#211438" opacity="1.000000" stroke="none" d=" M2401.000000,108.531357 C2398.361084,112.502449 2395.684814,115.977570 2393.088867,119.511719 C2376.352051,142.298141 2344.292480,145.556335 2323.355225,127.012016 C2308.465820,113.824196 2304.169189,97.286690 2308.368164,78.826729 C2311.976562,62.963165 2329.512207,45.781548 2347.566895,44.760101 C2359.529297,44.083317 2370.719727,44.744938 2380.889160,51.499744 C2388.212158,56.364056 2393.808350,62.843418 2397.873047,70.647614 C2398.621338,72.084328 2399.502930,73.451706 2400.661621,74.925537 C2401.000000,86.020897 2401.000000,97.041786 2401.000000,108.531357 z"/>
|
||||
<path fill="#6515E3" opacity="1.000000" stroke="none" d=" M169.449982,532.000000 C173.208450,530.097656 177.450226,528.265381 181.619370,526.280518 C196.645874,519.126404 206.096237,507.060730 210.591049,491.394318 C212.244370,485.631836 211.919479,479.210052 211.942383,473.086914 C212.059357,441.817566 211.989853,410.547516 212.005508,379.277710 C212.006592,377.121552 212.169983,374.965424 212.549744,372.721863 C214.349487,374.014984 215.857407,375.395538 217.365311,376.776123 C216.627380,376.596680 215.889450,376.417236 214.968765,376.193359 C214.968765,408.622589 215.150024,440.841736 214.894073,473.057465 C214.761459,489.751343 210.865372,505.497742 198.480194,517.622131 C194.147690,521.863403 188.375244,524.644470 183.216888,528.026001 C181.331070,529.262268 179.319336,530.306396 177.682526,531.719116 C175.299988,532.000000 172.599976,532.000000 169.449982,532.000000 z"/>
|
||||
<path fill="#000000" opacity="1.000000" stroke="none" d=" M35.531342,1.000000 C35.840652,1.598958 35.874008,2.522156 35.493198,2.748482 C29.292238,6.433895 22.027281,9.008199 17.063332,13.917211 C11.359032,19.558378 7.677545,27.246292 3.128503,34.052578 C2.605743,34.834736 2.153957,35.664326 1.334632,36.235962 C1.000000,24.406746 1.000000,12.813491 1.000000,1.000000 C12.353279,1.000000 23.707981,1.000000 35.531342,1.000000 z"/>
|
||||
<path fill="#000000" opacity="1.000000" stroke="none" d=" M35.000000,532.000000 C23.740093,532.000000 12.480186,532.000000 1.000000,532.000000 C1.000000,520.980103 1.000000,509.958710 1.273971,498.144836 C3.225362,500.256165 4.904092,503.159210 6.579990,506.063904 C12.840562,516.914856 21.889536,524.612366 33.221706,529.786804 C33.990940,530.138062 34.415260,531.244690 35.000000,532.000000 z"/>
|
||||
<path fill="#6515E3" opacity="1.000000" stroke="none" d=" M35.437500,532.000000 C34.415260,531.244690 33.990940,530.138062 33.221706,529.786804 C21.889536,524.612366 12.840562,516.914856 6.579990,506.063904 C4.904092,503.159210 3.225362,500.256165 1.273971,497.676147 C1.000000,496.933319 1.000000,495.866669 1.000005,494.399994 C2.426259,495.186737 4.555796,496.088257 5.170585,497.604126 C11.737153,513.795288 23.633379,524.108398 39.853806,529.862976 C40.572868,530.118103 41.124565,530.844910 41.877113,531.676025 C39.958332,532.000000 37.916668,532.000000 35.437500,532.000000 z"/>
|
||||
<path fill="#F98F03" opacity="1.000000" stroke="none" d=" M217.701797,376.986237 C215.857407,375.395538 214.349487,374.014984 212.660889,372.330750 C212.480209,372.027130 212.423538,371.815125 212.456863,371.226196 C212.517105,301.832153 212.545151,233.027054 212.557709,164.221970 C212.557846,163.400101 212.358459,162.578186 212.252228,161.756302 C212.979782,159.698669 213.707352,157.641037 214.620636,155.265472 C215.344513,159.168213 217.859421,156.155777 218.749405,155.648453 C226.304214,151.342041 233.649414,146.669876 241.170090,142.301239 C255.990524,133.692307 270.865234,125.176292 285.751129,116.680748 C300.302887,108.375900 314.910339,100.168633 329.466583,91.871597 C338.091431,86.955467 346.691559,81.994705 355.254517,76.971642 C368.468292,69.220383 381.515259,61.175720 394.862762,53.663818 C410.999268,44.582294 426.814056,34.545036 443.863586,27.617456 C453.705078,23.618645 465.243103,23.051941 476.905975,25.483866 C488.326538,27.865265 498.757507,31.301670 507.881378,38.191151 C513.293030,42.277500 517.835571,47.514904 522.653503,52.659882 C522.633423,54.161774 522.340271,55.516911 522.882446,56.273506 C530.810730,67.338020 534.825439,79.932739 534.852600,93.238861 C535.088684,209.045868 535.109619,324.853851 534.812317,440.660553 C534.781067,452.832825 531.410339,464.720093 523.805542,474.833038 C520.241638,479.572327 516.591858,484.247070 512.647461,489.038055 C501.482788,497.758301 489.668152,504.786011 475.582489,505.381836 C465.246460,505.819031 454.537109,505.528076 444.535706,503.217438 C436.519775,501.365479 429.139435,496.303467 421.788544,492.118835 C400.427094,479.958344 379.239807,467.492371 357.951324,455.203186 C333.209625,440.920685 308.448273,426.672119 283.665619,412.460846 C270.255615,404.771027 256.805481,397.150024 243.301727,389.626770 C242.091843,388.952698 240.352737,389.228546 238.859421,389.063232 C238.616684,389.002136 238.373947,388.941010 237.917542,388.412506 C236.750076,387.639465 235.796280,387.333801 234.842499,387.028076 C229.241089,383.750854 223.639679,380.473602 217.701797,376.986237 M296.716461,310.239075 C304.943359,323.504425 315.864471,333.778931 329.811554,340.975372 C340.928680,346.711548 352.553436,350.545807 365.039307,350.861145 C373.992004,351.087280 382.719025,349.423523 391.553467,347.250214 C407.133850,343.417419 419.549103,334.649506 430.206177,323.768677 C438.862549,314.930573 445.481720,304.050262 449.011292,291.869385 C449.959442,291.079254 451.318390,290.469421 451.762421,289.457977 C452.481628,287.819763 452.588501,285.915344 452.974182,284.127716 C459.194275,255.296036 451.962433,229.585983 432.394684,208.282761 C406.602570,180.203156 367.770386,170.884338 331.654480,188.451065 C300.026855,203.834702 283.702362,229.894516 282.017212,265.013763 C281.409424,277.680542 284.214142,289.821014 289.155273,301.371735 C290.547760,304.626892 293.721344,307.120148 296.716461,310.239075 z"/>
|
||||
<path fill="#211438" opacity="1.000000" stroke="none" d=" M1744.174194,276.125854 C1743.397339,250.037003 1716.894165,228.103333 1693.279297,227.846497 C1678.464111,227.685364 1665.452637,231.062683 1653.901001,240.373459 C1641.084229,250.704025 1634.178711,264.113495 1634.095581,280.405457 C1633.831787,332.062531 1634.002563,383.721802 1633.999146,435.380219 C1633.998535,444.009430 1633.983765,444.016296 1625.421631,444.019470 C1604.758423,444.027161 1584.093994,443.917572 1563.432617,444.113464 C1558.626099,444.159027 1556.942017,442.406403 1556.949707,437.716370 C1557.035278,385.225494 1556.844727,332.733521 1557.119385,280.243896 C1557.196655,265.465637 1559.156006,250.830490 1564.858765,236.920059 C1573.162476,216.665894 1585.719849,199.820221 1603.551514,186.918121 C1617.478394,176.841232 1632.717773,169.587479 1649.459961,166.024292 C1667.382202,162.209900 1685.510498,161.295441 1703.915283,162.719238 C1720.459717,163.999130 1736.135376,167.906235 1750.562622,175.621109 C1760.132935,180.738770 1768.686768,187.785461 1777.553345,194.166153 C1779.232666,195.374664 1780.243896,197.511505 1780.926636,198.395660 C1791.135864,191.360275 1800.034424,184.745819 1809.402466,178.881607 C1824.746704,169.276382 1841.720825,164.639603 1859.721313,162.872437 C1878.759521,161.003418 1897.559570,162.090714 1916.189331,165.925613 C1932.132935,169.207581 1946.731934,175.813446 1960.179443,185.075195 C1974.098267,194.661621 1985.271973,206.717941 1993.764893,221.264038 C2001.136719,233.890305 2005.305786,247.682434 2007.892090,261.974640 C2008.567871,265.708923 2008.931152,269.553040 2008.935791,273.347351 C2008.999023,325.839020 2008.968994,378.330811 2008.993652,430.822571 C2008.994629,432.803070 2009.134277,434.820038 2009.523438,436.756927 C2010.615234,442.191498 2009.403442,443.998505 2003.981934,444.011566 C1981.818970,444.064911 1959.654907,443.918945 1937.493530,444.109344 C1932.375488,444.153351 1931.930420,441.525269 1931.935669,437.517609 C1932.002563,386.192505 1931.280640,334.853943 1932.255737,283.547241 C1932.811768,254.288528 1910.071411,232.334351 1888.143066,228.585251 C1855.772339,223.050873 1827.595581,243.656631 1822.208252,272.253021 C1821.964111,273.548920 1822.057983,274.908508 1821.744141,277.005432 C1821.331299,279.082092 1821.027954,280.391724 1821.026855,281.701599 C1820.988525,331.474060 1820.969482,381.246521 1821.002930,431.018982 C1821.003906,432.622162 1821.579956,434.224945 1821.888062,435.827911 C1822.129761,443.746552 1821.848755,444.027374 1813.989990,444.025299 C1793.012451,444.019684 1772.034912,444.036743 1751.057373,444.017181 C1744.453125,444.011047 1744.104248,443.630005 1744.039062,436.847382 C1744.013428,434.184235 1744.070435,431.520264 1744.308838,428.041931 C1744.685913,425.915863 1744.981689,424.604614 1744.982422,423.293274 C1745.006958,375.850342 1745.012085,328.407440 1744.969727,280.964539 C1744.968384,279.351410 1744.451050,277.738739 1744.174194,276.125854 z"/>
|
||||
<path fill="#211438" opacity="1.000000" stroke="none" d=" M997.272705,222.229736 C981.579956,246.333069 966.124878,270.164185 950.641724,293.976990 C948.382446,297.451782 947.862183,300.378418 950.462341,304.391327 C965.829834,328.109100 980.822998,352.069336 995.963135,375.934570 C1008.594299,395.844666 1021.280762,415.719696 1033.861938,435.661285 C1035.171021,437.736084 1035.930542,440.157471 1036.944946,442.418121 C1034.288818,442.960144 1031.634888,443.960419 1028.976196,443.972900 C1003.812378,444.090881 978.647278,443.964325 953.483704,444.114227 C949.271606,444.139343 946.969055,442.605499 944.811951,438.979584 C933.002319,419.128113 920.879944,399.462677 908.860474,379.736115 C901.511658,367.675049 894.033752,355.690063 886.872803,343.518524 C884.639282,339.722260 882.293396,337.716003 877.502808,337.876617 C865.683594,338.272888 853.836426,338.240082 842.013184,337.916168 C837.057373,337.780365 835.857788,339.551331 835.884644,344.231659 C836.061646,375.061371 835.986694,405.892578 835.980469,436.723297 C835.979004,444.027771 835.955444,444.024841 828.814270,444.025848 C807.982849,444.028748 787.151489,444.039551 766.320068,444.035645 C759.405029,444.034332 759.030701,443.712067 759.028259,436.617920 C759.003723,365.124664 759.001770,293.631439 759.000061,222.138184 C758.998840,167.810226 759.013245,113.482269 759.004761,59.154316 C759.003479,51.066788 758.963196,51.056705 766.879456,51.054558 C787.877686,51.048862 808.877380,51.187645 829.872925,50.951572 C834.715637,50.897114 836.080383,52.406761 836.071045,57.188786 C835.936829,126.182701 835.980042,195.176971 835.979553,264.171143 C835.979492,271.954742 835.976196,271.973450 843.903870,271.988312 C854.902405,272.008881 865.901855,271.923706 876.899048,272.045898 C880.193970,272.082520 882.186279,271.132050 884.099304,268.093018 C900.273743,242.399155 916.729797,216.882706 933.067810,191.291580 C937.070435,185.022079 940.811890,178.580414 944.982178,172.427185 C946.032654,170.877335 948.267334,169.177643 949.969910,169.164948 C975.798828,168.972351 1001.629822,169.045746 1027.460327,169.085663 C1028.082520,169.086624 1028.704102,169.418045 1030.490356,169.927292 C1020.262573,188.101135 1008.265137,204.650833 997.272705,222.229736 z"/>
|
||||
<path fill="#211438" opacity="1.000000" stroke="none" d=" M2204.980713,168.953308 C2221.043945,167.723450 2235.611572,171.417221 2248.408691,181.608231 C2262.422852,192.768524 2271.056885,206.990784 2273.989014,224.687134 C2275.840088,235.861588 2275.574219,246.926849 2271.864502,257.679626 C2266.530029,273.142853 2256.308350,284.991730 2243.103271,294.200104 C2227.181641,305.303131 2210.964111,315.983337 2194.834961,326.786987 C2176.219727,339.255676 2157.545654,351.635986 2138.938721,364.116943 C2136.184814,365.964355 2133.499512,367.985107 2131.103760,370.263489 C2130.050293,371.265289 2128.992188,373.410431 2129.392334,374.503479 C2129.902588,375.897949 2131.739502,377.129395 2133.278320,377.731842 C2134.744141,378.305695 2136.562012,378.041351 2138.225098,378.041504 C2163.891357,378.043518 2189.561035,377.755280 2215.222656,378.099121 C2238.070801,378.405243 2258.320312,385.447876 2273.743652,403.282074 C2282.235352,413.101044 2287.425049,424.725464 2288.739502,437.407593 C2290.328369,452.744629 2290.283447,468.249268 2291.014404,483.678101 C2291.190674,487.394714 2289.923584,489.159607 2285.892822,489.130707 C2267.590576,488.999359 2249.286865,489.078583 2230.983643,489.046204 C2224.881592,489.035400 2224.096680,488.253265 2224.054443,482.091431 C2223.998291,473.925415 2224.121826,465.757599 2224.010254,457.592712 C2223.896973,449.294525 2218.450439,444.013275 2210.188721,444.013000 C2177.356201,444.011871 2144.513184,444.532867 2111.694092,443.876923 C2084.124512,443.325928 2064.515137,429.566284 2052.293457,404.840302 C2045.920166,391.946564 2044.336182,378.257721 2046.364868,364.535309 C2048.635010,349.178345 2056.038330,335.666229 2068.413086,326.050751 C2082.422852,315.164703 2097.209473,305.262756 2111.828857,295.180389 C2134.516357,279.533936 2157.348389,264.096436 2180.119873,248.571442 C2182.999268,246.608231 2185.907227,244.685928 2188.759277,242.683517 C2192.981934,239.718597 2193.051514,238.521896 2189.006348,233.956650 C2186.638428,232.871384 2184.622803,232.059738 2182.605957,232.056213 C2141.426758,231.984299 2100.247803,232.004745 2059.068604,232.006760 C2059.047607,212.932755 2059.107666,193.858063 2058.941895,174.785309 C2058.905029,170.534119 2060.306885,168.788834 2064.690674,168.936020 C2071.814453,169.175186 2078.952881,168.985855 2087.021729,168.979980 C2126.965820,168.972794 2165.973389,168.963058 2204.980713,168.953308 z"/>
|
||||
<path fill="#211438" opacity="1.000000" stroke="none" d=" M1324.748779,324.688202 C1325.002808,341.574371 1330.428589,356.530090 1342.807983,368.154205 C1360.779785,385.029358 1382.398315,389.132507 1404.756104,380.121887 C1424.917969,371.996246 1438.287231,356.643585 1440.149292,333.570282 C1440.200928,332.929443 1440.546387,332.312317 1441.273193,331.148987 C1442.192749,328.741425 1442.941895,326.869507 1442.944336,324.996613 C1443.008179,275.239044 1443.006592,225.481339 1442.951050,175.723755 C1442.948853,173.800507 1442.302612,171.877975 1441.956543,169.955124 C1443.713989,169.636307 1445.470459,169.045197 1447.228882,169.040070 C1468.894775,168.976868 1490.562500,169.132477 1512.226074,168.895340 C1516.973755,168.843384 1518.081055,170.485931 1518.072388,174.928711 C1517.967285,229.093658 1518.430786,283.263855 1517.764526,337.420654 C1517.596558,351.070282 1513.692871,364.537415 1507.974609,377.318054 C1497.651611,400.390869 1481.522705,418.155945 1460.118652,431.234528 C1445.469849,440.185425 1429.464355,445.989227 1412.473145,447.821259 C1397.478638,449.437988 1382.223877,450.636871 1367.222656,449.728302 C1344.637451,448.360382 1322.903198,442.137604 1303.746826,429.729980 C1278.831665,413.592529 1261.509277,391.529053 1253.387329,362.369171 C1249.724243,349.217041 1248.143799,336.007904 1248.088867,322.576202 C1247.889404,273.744965 1247.997314,224.912491 1247.979248,176.080475 C1247.976685,169.203812 1248.125977,169.004700 1254.911133,169.001877 C1275.577271,168.993271 1296.243408,168.999054 1316.909546,169.004456 C1325.084473,169.006592 1325.084473,169.012848 1324.666870,178.200836 C1324.302979,188.990707 1324.174561,198.985367 1324.046143,208.980026 C1324.038940,237.012619 1324.031982,265.045227 1324.020264,294.014618 C1324.010010,297.109589 1323.947144,299.269409 1324.009399,301.425629 C1324.232910,309.180481 1324.498901,316.934113 1324.748779,324.688202 z"/>
|
||||
<path fill="#211438" opacity="1.000000" stroke="none" d=" M1199.972778,168.956024 C1203.770874,168.731750 1207.571411,168.541504 1211.366333,168.272598 C1214.481812,168.051849 1216.882690,169.153198 1216.878052,172.471832 C1216.850830,192.436768 1216.646729,212.401474 1215.937500,232.479248 C1214.740112,232.415009 1214.107422,232.084122 1213.473877,232.082840 C1192.925293,232.041290 1172.376465,231.980743 1151.829224,232.138947 C1150.552002,232.148788 1149.288086,233.913574 1148.018066,234.861877 C1140.789795,237.727463 1137.886230,242.948029 1137.907104,250.794800 C1138.072021,312.592224 1138.000488,374.390259 1137.996826,436.188110 C1137.996338,444.058746 1137.983398,444.035858 1130.363525,444.031433 C1109.375732,444.019287 1088.385986,443.880737 1067.401245,444.133820 C1062.243896,444.196014 1060.914062,442.400757 1060.923218,437.485229 C1061.046265,371.523376 1060.580811,305.557281 1061.192627,239.600922 C1061.443604,212.545868 1073.475708,190.881134 1097.595825,177.444977 C1107.154053,172.120529 1117.863037,169.110855 1129.092651,169.056427 C1133.423340,169.035431 1137.753906,169.004639 1143.021240,168.980804 C1162.629395,168.974197 1181.301147,168.965103 1199.972778,168.956024 z"/>
|
||||
<path fill="#211438" opacity="1.000000" stroke="none" d=" M2380.845947,169.001526 C2381.656006,169.001328 2381.989258,169.004852 2382.322510,169.000549 C2393.011719,168.862213 2393.027100,168.862091 2393.027344,180.050995 C2393.030029,265.520142 2393.027588,350.989288 2393.020996,436.458435 C2393.020508,444.034637 2393.002197,444.032440 2385.673828,444.031891 C2364.681641,444.030304 2343.689697,444.034119 2322.697510,444.028229 C2316.246338,444.026428 2316.014404,443.808044 2316.014404,437.219147 C2316.015137,349.750580 2316.058105,262.281952 2315.937256,174.813583 C2315.930664,170.164124 2317.346436,168.858414 2321.891113,168.908417 C2341.381592,169.122910 2360.876221,169.000931 2380.845947,169.001526 z"/>
|
||||
<path fill="#F69B04" opacity="1.000000" stroke="none" d=" M512.981018,488.951050 C516.591858,484.247070 520.241638,479.572327 523.805542,474.833038 C531.410339,464.720093 534.781067,452.832825 534.812317,440.660553 C535.109619,324.853851 535.088684,209.045868 534.852600,93.238861 C534.825439,79.932739 530.810730,67.338020 522.882446,56.273506 C522.340271,55.516911 522.633423,54.161774 522.811768,52.966721 C532.746765,66.097198 537.132141,80.735252 537.097900,97.310219 C536.859070,213.109009 537.071228,328.908752 536.783203,444.707336 C536.766357,451.480072 534.288208,458.484283 531.837341,464.957458 C528.213989,474.527679 522.099121,482.680542 514.226868,489.753632 C513.494446,489.452698 513.237732,489.201874 512.981018,488.951050 z"/>
|
||||
<path fill="#FEA802" opacity="1.000000" stroke="none" d=" M512.647461,489.038055 C513.237732,489.201874 513.494446,489.452698 513.919800,489.912903 C506.566620,496.667297 498.159180,501.780334 488.607025,504.629608 C483.231537,506.233032 477.625824,507.324402 472.046051,507.931946 C458.426300,509.414917 445.249451,507.433197 433.044342,500.998230 C424.097961,496.281494 415.389160,491.111206 406.608948,486.082886 C393.976715,478.848572 381.364380,471.579254 368.764679,464.288452 C356.062378,456.938293 343.425201,449.474762 330.683655,442.193573 C322.712036,437.638092 314.510223,433.482849 306.571594,428.872711 C293.298065,421.164520 280.196411,413.160675 266.937836,405.426239 C257.755310,400.069580 248.430557,394.956635 239.014374,389.399048 C240.352737,389.228546 242.091843,388.952698 243.301727,389.626770 C256.805481,397.150024 270.255615,404.771027 283.665619,412.460846 C308.448273,426.672119 333.209625,440.920685 357.951324,455.203186 C379.239807,467.492371 400.427094,479.958344 421.788544,492.118835 C429.139435,496.303467 436.519775,501.365479 444.535706,503.217438 C454.537109,505.528076 465.246460,505.819031 475.582489,505.381836 C489.668152,504.786011 501.482788,497.758301 512.647461,489.038055 z"/>
|
||||
<path fill="#281F4A" opacity="1.000000" stroke="none" d=" M1441.719482,170.298798 C1442.302612,171.877975 1442.948853,173.800507 1442.951050,175.723755 C1443.006592,225.481339 1443.008179,275.239044 1442.944336,324.996613 C1442.941895,326.869507 1442.192749,328.741425 1441.453369,330.780579 C1441.090210,278.826324 1441.062012,226.705276 1441.058960,174.584229 C1441.058838,173.270309 1441.334961,171.956390 1441.719482,170.298798 z"/>
|
||||
<path fill="#2F194A" opacity="1.000000" stroke="none" d=" M2059.285156,232.323334 C2100.247803,232.004745 2141.426758,231.984299 2182.605957,232.056213 C2184.622803,232.059738 2186.638428,232.871384 2188.822266,233.657455 C2148.397949,234.004074 2107.805420,234.024551 2067.213379,233.937744 C2064.641846,233.932251 2062.072266,233.091873 2059.285156,232.323334 z"/>
|
||||
<path fill="#430043" opacity="1.000000" stroke="none" d=" M1821.915771,435.376678 C1821.579956,434.224945 1821.003906,432.622162 1821.002930,431.018982 C1820.969482,381.246521 1820.988525,331.474060 1821.026855,281.701599 C1821.027954,280.391724 1821.331299,279.082092 1821.718506,277.440002 C1821.943604,329.713562 1821.943481,382.319489 1821.915771,435.376678 z"/>
|
||||
<path fill="#2E002E" opacity="1.000000" stroke="none" d=" M1744.130127,276.579529 C1744.451050,277.738739 1744.968384,279.351410 1744.969727,280.964539 C1745.012085,328.407440 1745.006958,375.850342 1744.982422,423.293274 C1744.981689,424.604614 1744.685913,425.915863 1744.323242,427.571960 C1744.107910,377.622253 1744.097046,327.327728 1744.130127,276.579529 z"/>
|
||||
<path fill="#2F194A" opacity="1.000000" stroke="none" d=" M1148.413940,234.743088 C1149.288086,233.913574 1150.552002,232.148788 1151.829224,232.138947 C1172.376465,231.980743 1192.925293,232.041290 1213.473877,232.082840 C1214.107422,232.084122 1214.740112,232.415009 1215.717163,232.834854 C1214.148804,233.389725 1212.237549,233.966492 1210.324219,233.973190 C1191.774780,234.038177 1173.224854,233.989151 1154.675293,234.031494 C1152.719727,234.035950 1150.764893,234.417633 1148.413940,234.743088 z"/>
|
||||
<path fill="#000080" opacity="1.000000" stroke="none" d=" M2204.687988,168.654999 C2165.973389,168.963058 2126.965820,168.972794 2087.491943,168.968307 C2088.258301,168.637283 2089.490723,168.045258 2090.723877,168.043686 C2127.796387,167.996536 2164.868896,168.005508 2201.941406,168.024231 C2202.759277,168.024643 2203.577393,168.241028 2204.687988,168.654999 z"/>
|
||||
<path fill="#000080" opacity="1.000000" stroke="none" d=" M1199.681885,168.656769 C1181.301147,168.965103 1162.629395,168.974197 1143.491089,168.969086 C1143.591187,168.664795 1144.158691,168.120102 1144.724731,168.121521 C1162.946899,168.167679 1181.168945,168.266556 1199.681885,168.656769 z"/>
|
||||
<path fill="#000080" opacity="1.000000" stroke="none" d=" M1324.344482,208.687668 C1324.174561,198.985367 1324.302979,188.990707 1324.605469,178.658905 C1324.734009,188.346268 1324.688477,198.370789 1324.344482,208.687668 z"/>
|
||||
<path fill="#000080" opacity="1.000000" stroke="none" d=" M1324.820923,324.249207 C1324.498901,316.934113 1324.232910,309.180481 1324.009399,301.425629 C1323.947144,299.269409 1324.010010,297.109589 1324.030762,294.484253 C1324.363892,297.208466 1324.900757,300.396149 1324.954712,303.591980 C1325.068115,310.329132 1324.928711,317.070526 1324.820923,324.249207 z"/>
|
||||
<path fill="#FF00FF" opacity="1.000000" stroke="none" d=" M214.788666,124.825363 C214.496323,115.443848 214.374802,105.590721 214.562286,95.472626 C214.900681,104.923019 214.930084,114.638390 214.788666,124.825363 z"/>
|
||||
<path fill="#FEA802" opacity="1.000000" stroke="none" d=" M234.931915,387.307251 C235.796280,387.333801 236.750076,387.639465 237.613724,388.191864 C236.689499,388.154510 235.855423,387.870422 234.931915,387.307251 z"/>
|
||||
<path fill="#221538" opacity="1.000000" stroke="none" d=" M211.949326,161.867874 C212.358459,162.578186 212.557846,163.400101 212.557709,164.221970 C212.545151,233.027054 212.517105,301.832153 212.377472,371.150421 C185.279068,356.126007 157.666046,341.570770 131.449005,324.829407 C87.927750,297.038086 89.674866,233.364563 134.183105,206.670563 C159.744293,191.340149 185.808609,176.848602 211.949326,161.867874 z"/>
|
||||
<path fill="#000000" opacity="1.000000" stroke="none" d=" M448.520416,291.576965 C445.481720,304.050262 438.862549,314.930573 430.206177,323.768677 C419.549103,334.649506 407.133850,343.417419 391.553467,347.250214 C382.719025,349.423523 373.992004,351.087280 365.039307,350.861145 C352.553436,350.545807 340.928680,346.711548 329.811554,340.975372 C315.864471,333.778931 304.943359,323.504425 296.341583,309.739136 C293.122955,302.430634 289.375671,295.847046 287.613251,288.769196 C283.192322,271.015137 283.284637,253.339325 290.253174,235.913177 C294.830750,224.466003 301.326721,214.610947 310.311005,206.244354 C329.706665,188.182205 352.128204,179.648621 378.927307,182.865051 C395.792664,184.889221 410.374329,191.639160 422.842163,202.571182 C436.770416,214.783829 446.404449,229.586563 450.512085,248.381592 C453.334473,261.295746 452.945831,273.469971 450.115540,286.313507 C450.094208,287.099060 450.145050,287.549835 450.121063,288.296448 C449.537628,289.587189 449.029022,290.582062 448.520416,291.576965 z"/>
|
||||
<path fill="#FEA802" opacity="1.000000" stroke="none" d=" M448.765869,291.723175 C449.029022,290.582062 449.537628,289.587189 450.257416,288.114380 C450.374969,287.083923 450.281342,286.531342 450.187683,285.978760 C452.945831,273.469971 453.334473,261.295746 450.512085,248.381592 C446.404449,229.586563 436.770416,214.783829 422.842163,202.571182 C410.374329,191.639160 395.792664,184.889221 378.927307,182.865051 C352.128204,179.648621 329.706665,188.182205 310.311005,206.244354 C301.326721,214.610947 294.830750,224.466003 290.253174,235.913177 C283.284637,253.339325 283.192322,271.015137 287.613251,288.769196 C289.375671,295.847046 293.122955,302.430634 296.022339,309.601044 C293.721344,307.120148 290.547760,304.626892 289.155273,301.371735 C284.214142,289.821014 281.409424,277.680542 282.017212,265.013763 C283.702362,229.894516 300.026855,203.834702 331.654480,188.451065 C367.770386,170.884338 406.602570,180.203156 432.394684,208.282761 C451.962433,229.585983 459.194275,255.296036 452.974182,284.127716 C452.588501,285.915344 452.481628,287.819763 451.762421,289.457977 C451.318390,290.469421 449.959442,291.079254 448.765869,291.723175 z"/>
|
||||
<path fill="#F98F03" opacity="1.000000" stroke="none" d=" M450.115540,286.313507 C450.281342,286.531342 450.374969,287.083923 450.332275,287.818573 C450.145050,287.549835 450.094208,287.099060 450.115540,286.313507 z"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 28 KiB |
|
Before Width: | Height: | Size: 27 KiB After Width: | Height: | Size: 24 KiB |
@@ -1,7 +1,3 @@
|
||||
<svg viewBox="0 0 1080 1080" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<rect width="1080" height="1080" fill="white"/>
|
||||
<path d="M976 284.628C976 348.237 959.54 406.608 926.62 459.74C893.701 512.873 845.817 556.276 782.97 589.952C720.124 623.627 645.306 643.458 558.517 649.445L510.26 919.971C491.556 1023.99 440.68 1076 357.632 1076C311.993 1076 269.721 1062.53 230.816 1035.59C192.659 1008.65 161.984 967.49 138.79 912.113C115.597 856.736 104 788.637 104 707.816C104 555.902 128.316 427.187 176.947 321.671C226.327 215.407 292.166 136.082 374.466 83.6984C457.514 30.5661 548.791 4 648.299 4C718.627 4 778.107 16.3476 826.739 41.0429C876.118 65.7382 913.153 99.4136 937.843 142.069C963.281 183.976 976 231.496 976 284.628ZM578.718 533.826C732.094 514.369 808.783 434.671 808.783 294.731C808.783 245.34 792.323 205.304 759.403 174.622C727.231 143.192 677.103 127.476 609.019 127.476C531.957 127.476 464.621 151.798 407.012 200.44C350.15 249.082 306.008 316.807 274.584 403.615C243.909 489.674 228.571 588.081 228.571 698.836C228.571 745.233 233.06 786.392 242.039 822.312C251.765 858.232 263.736 886.295 277.951 906.501C292.915 925.957 307.13 935.686 320.597 935.686C339.302 935.686 353.517 909.868 363.243 858.232L400.278 646.078C371.099 641.587 358.38 639.717 362.121 640.465C339.676 636.723 325.086 629.988 318.353 620.26C311.619 609.783 308.252 596.687 308.252 580.972C308.252 564.508 312.741 551.412 321.719 541.684C331.446 531.955 344.539 527.091 360.999 527.091C368.481 527.091 374.092 527.465 377.833 528.214C395.789 531.207 409.63 533.078 419.357 533.826C429.083 475.455 442.924 397.254 460.88 299.221C465.369 273.777 475.47 255.817 491.182 245.34C507.641 234.115 526.72 228.503 548.417 228.503C573.107 228.503 590.689 233.367 601.163 243.095C612.386 252.075 617.997 266.668 617.997 286.873C617.997 298.847 617.249 308.575 615.753 316.059L578.718 533.826Z"
|
||||
fill="black"/>
|
||||
<path d="M304.835 467.541L426.099 489.952L411.851 580.937L391.091 699.816L266.088 676.643L304.835 467.541Z"
|
||||
fill="white"/>
|
||||
<svg width="1080" height="1080" viewBox="0 0 1080 1080" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M955 296.539C955 357.181 939.314 412.83 907.942 463.484C876.57 514.138 830.938 555.517 771.046 587.622C711.155 619.727 639.855 638.633 557.147 644.34L511.158 902.248C493.333 1001.42 444.849 1051 365.707 1051C322.214 1051 281.929 1038.16 244.853 1012.47C208.49 986.791 179.257 947.551 157.154 894.757C135.051 841.963 124 777.04 124 699.988C124 555.161 147.172 432.449 193.517 331.854C240.575 230.546 303.319 154.922 381.749 104.981C460.892 54.327 547.878 29 642.707 29C709.728 29 766.412 40.7717 812.757 64.3152C859.815 87.8586 895.108 119.963 918.637 160.629C942.879 200.582 955 245.885 955 296.539ZM576.398 534.114C722.562 515.565 795.645 439.584 795.645 306.171C795.645 259.084 779.959 220.915 748.587 191.664C717.928 161.699 670.157 146.717 605.274 146.717C531.835 146.717 467.665 169.904 412.764 216.278C358.577 262.651 316.51 327.217 286.564 409.976C257.331 492.021 242.714 585.838 242.714 691.427C242.714 735.66 246.992 774.9 255.548 809.145C264.817 843.39 276.225 870.143 289.772 889.406C304.032 907.956 317.579 917.23 330.413 917.23C348.238 917.23 361.785 892.617 371.054 843.39L406.347 641.13L405.633 646.299L411.708 611.502L416.534 583.854L420.128 561.451L424.529 534.114C433.798 478.466 446.988 403.912 464.1 310.451C468.378 286.194 478.004 269.072 492.977 259.084C508.663 248.382 526.844 243.031 547.521 243.031C571.05 243.031 587.806 247.669 597.788 256.943C608.483 265.505 613.83 279.417 613.83 298.68C613.83 310.095 613.117 319.369 611.691 326.504C597.908 407.581 590.181 453.037 576.398 534.114Z" fill="black"/>
|
||||
</svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 2.0 KiB After Width: | Height: | Size: 1.6 KiB |
|
After Width: | Height: | Size: 22 KiB |
@@ -0,0 +1,24 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="840" height="262">
|
||||
<path d="M0 0 C8.69163006 7.71008755 13.14490087 16.89394432 14.22265625 28.37109375 C14.64705043 39.90354435 11.2436751 50.02540655 4 59 C-2.73007826 65.71611544 -11.11233981 69.18417403 -20.5625 69.4375 C-29.02193816 69.14854393 -34.47069789 67.31848169 -41 62 C-41.02505615 63.02472412 -41.0501123 64.04944824 -41.07592773 65.10522461 C-41.16984484 68.89409676 -41.27010317 72.68277881 -41.37231445 76.47143555 C-41.41572297 78.11364303 -41.45739358 79.75589739 -41.49731445 81.39819336 C-41.5548744 83.75388745 -41.61860892 86.10934428 -41.68359375 88.46484375 C-41.70866249 89.57266457 -41.70866249 89.57266457 -41.73423767 90.7028656 C-41.88612829 95.88612829 -41.88612829 95.88612829 -43 97 C-48.61 97 -54.22 97 -60 97 C-60 63.34 -60 29.68 -60 -5 C-54.39 -5 -48.78 -5 -43 -5 C-42.34 -3.35 -41.68 -1.7 -41 0 C-40.5153125 -0.33773437 -40.030625 -0.67546875 -39.53125 -1.0234375 C-26.76996544 -9.51459992 -12.64739523 -8.64871948 0 0 Z M-39.875 17.0625 C-43.59522645 22.95180763 -44.64765142 30.01356041 -43.375 36.8125 C-41.94960016 41.95313555 -39.20005286 46.63995771 -35 50 C-28.58262778 53.05106644 -21.3538322 53.05583606 -14.625 50.9375 C-9.59434454 47.22439716 -5.93848019 43.00217489 -4 37 C-3.12848553 29.65293034 -3.43441364 23.03609731 -8 17 C-11.50353653 13.33721181 -15.41705741 10.34492712 -20.515625 9.6640625 C-28.47529099 9.55035299 -34.61737158 10.70443772 -39.875 17.0625 Z " fill="#070709" transform="translate(709,111)"/>
|
||||
<path d="M0 0 C8.67817735 7.43616297 12.59651032 17.33058774 13.83984375 28.484375 C14.34206719 39.50879197 11.02283105 49.29470477 4.40234375 58.1328125 C-1.24768253 64.30376319 -9.32101987 68.57263825 -17.69921875 69.203125 C-27.77294256 69.3611442 -33.59239913 67.60506725 -42 62 C-42.33 73.55 -42.66 85.1 -43 97 C-48.61 97 -54.22 97 -60 97 C-60 63.34 -60 29.68 -60 -5 C-54.39 -5 -48.78 -5 -43 -5 C-42.67 -3.02 -42.34 -1.04 -42 1 C-41.443125 0.59007813 -40.88625 0.18015625 -40.3125 -0.2421875 C-27.3317457 -9.40765253 -13.36734014 -9.00970502 0 0 Z M-39.875 17.3125 C-44.23157366 24.27418696 -44.76257396 31.08547435 -43 39 C-40.78638 44.12807721 -37.69263635 47.91273924 -33 51 C-27.15219658 52.94926781 -20.47788508 52.78007493 -14.625 50.9375 C-9.34602898 47.04111663 -5.31463083 42.57315414 -4 36 C-3.21564863 28.35613939 -4.61809235 21.89395052 -9.25 15.6875 C-13.66336941 11.37443444 -17.85242164 9.85182121 -23.9375 9.5625 C-30.64560394 9.80717248 -35.72726168 11.94341599 -39.875 17.3125 Z " fill="#08080A" transform="translate(792,111)"/>
|
||||
<path d="M0 0 C0.33 -1.65 0.66 -3.3 1 -5 C6.61 -5 12.22 -5 18 -5 C18 18.76 18 42.52 18 67 C12.39 67 6.78 67 1 67 C0.67 65.35 0.34 63.7 0 62 C-0.76183594 62.50660156 -0.76183594 62.50660156 -1.5390625 63.0234375 C-2.22742188 63.46945313 -2.91578125 63.91546875 -3.625 64.375 C-4.29789062 64.81585938 -4.97078125 65.25671875 -5.6640625 65.7109375 C-13.58368891 70.0812999 -23.10758184 70.39808303 -31.75 67.9375 C-41.62995371 64.03990358 -47.55506909 56.75034748 -52.25390625 47.54296875 C-56.35291308 38.0167055 -56.62716497 26.83848226 -53.375 17 C-49.4819062 7.90703965 -42.53172578 -0.6908008 -33.375 -4.875 C-21.19078419 -8.93640527 -10.59035975 -6.93997523 0 0 Z M-34 18 C-37.50770356 23.5121056 -38.64816392 29.16310107 -37.5625 35.58984375 C-35.7557313 42.41655504 -33.20468193 46.65511078 -27.4375 50.875 C-20.99668564 52.98290288 -13.87867289 53.19665826 -7.5625 50.5 C-2.42266422 47.51247045 0.16916612 42.49250164 2 37 C2.63422426 29.45029199 2.42141667 22.41441403 -2.359375 16.24609375 C-5.96089837 12.3939489 -9.32538157 10.29977528 -14.68359375 9.69921875 C-23.26189343 9.66271535 -28.25050093 11.31814973 -34 18 Z " fill="#070709" transform="translate(467,111)"/>
|
||||
<path d="M0 0 C0.66 -1.65 1.32 -3.3 2 -5 C7.28 -5 12.56 -5 18 -5 C18.95704986 -1.17180055 19.12078914 1.77386172 19.11352539 5.69628906 C19.11367142 6.36011597 19.11381744 7.02394287 19.1139679 7.70788574 C19.11327332 9.8938325 19.10550231 12.07969319 19.09765625 14.265625 C19.09579045 15.78448439 19.09436731 17.30334438 19.09336853 18.82220459 C19.0895561 22.81377839 19.0797367 26.80531562 19.06866455 30.796875 C19.05842303 34.8723908 19.05386504 38.94791253 19.04882812 43.0234375 C19.03811327 51.01564362 19.0205268 59.00781305 19 67 C13.06 67 7.12 67 1 67 C0.67 65.35 0.34 63.7 0 62 C-1.010625 62.78375 -2.02125 63.5675 -3.0625 64.375 C-10.10252051 69.32545267 -17.61014034 69.82953556 -26 69 C-34.99458455 66.97833698 -42.57884408 62.69673031 -48.04296875 55.1953125 C-54.42675603 44.84962837 -56.76481094 34.43070846 -54.5 22.328125 C-51.38068518 10.91426851 -45.31231302 1.98738781 -35.0078125 -4.1953125 C-22.99567478 -9.69420221 -10.51231494 -7.00820996 0 0 Z M-33.703125 18.0859375 C-37.69553255 23.97834623 -37.83104269 30.1032024 -37 37 C-35.40099464 42.03034735 -33.28906668 46.48368849 -28.875 49.5625 C-22.1750793 52.91246035 -15.37047301 52.88405849 -8.1875 51 C-3.21333977 47.87895829 0.14016889 43.57949332 2 38 C2.61486532 30.06722942 3.08216386 22.53421067 -2 16 C-6.55661235 11.56022386 -11.09995043 9.7144683 -17.4375 9.6875 C-25.03557191 9.87083149 -28.89903754 12.42951194 -33.703125 18.0859375 Z " fill="#080809" transform="translate(617,111)"/>
|
||||
<path d="M0 0 C6.27 0 12.54 0 19 0 C19.86882812 2.09859375 20.73765625 4.1971875 21.6328125 6.359375 C22.49571507 8.43516367 23.36009471 10.51033151 24.22460938 12.58544922 C24.81566696 14.00635935 25.40523461 15.42789035 25.99316406 16.85009766 C29.67484115 25.75271955 33.54281316 34.45146929 38 43 C38.33209473 42.2251123 38.66418945 41.45022461 39.00634766 40.65185547 C42.10668945 33.41772461 42.10668945 33.41772461 45.20703125 26.18359375 C45.46780457 25.57501526 45.72857788 24.96643677 45.99725342 24.3394165 C46.52595131 23.10600543 47.05496437 21.8727294 47.58428955 20.6395874 C48.96437415 17.42332337 50.33821498 14.20459532 51.70214844 10.98144531 C51.97634613 10.33563507 52.25054382 9.68982483 52.53305054 9.02444458 C53.29495211 7.22937564 54.05452493 5.43331881 54.81396484 3.63720703 C56 1 56 1 57 0 C58.34267413 -0.08631874 59.68974322 -0.10706473 61.03515625 -0.09765625 C61.84404297 -0.09443359 62.65292969 -0.09121094 63.48632812 -0.08789062 C64.33646484 -0.07951172 65.18660156 -0.07113281 66.0625 -0.0625 C66.91650391 -0.05798828 67.77050781 -0.05347656 68.65039062 -0.04882812 C70.76695663 -0.03700373 72.88348685 -0.01906769 75 0 C73.16191407 5.91473461 70.9830678 11.44726207 68.25 17 C63.77345085 26.26927146 59.49910534 35.62503109 55.25 45 C54.92825806 45.70946777 54.60651611 46.41893555 54.27502441 47.14990234 C52.74027556 50.53437081 51.20654663 53.9192991 49.67382812 57.3046875 C47.45465601 62.20559819 45.22751178 67.10287487 43 72 C39.37 72 35.74 72 32 72 C26.23725499 60.94458283 21.08034555 49.63843719 16.02001953 38.24780273 C15.46135932 36.99067986 14.90260272 35.73359981 14.34375 34.4765625 C14.06707489 33.85417191 13.79039978 33.23178131 13.50534058 32.5905304 C11.61205991 28.34301709 9.67729179 24.11638141 7.71875 19.8984375 C7.20739502 18.79628906 6.69604004 17.69414063 6.16918945 16.55859375 C5.20099592 14.47830973 4.2283629 12.40008459 3.25073242 10.32421875 C2.60648315 8.93783203 2.60648315 8.93783203 1.94921875 7.5234375 C1.57112061 6.71825684 1.19302246 5.91307617 0.8034668 5.08349609 C0 3 0 3 0 0 Z " fill="#080809" transform="translate(250,106)"/>
|
||||
<path d="M0 0 C5.61 0 11.22 0 17 0 C17 35.64 17 71.28 17 108 C11.39 108 5.78 108 0 108 C0 72.36 0 36.72 0 0 Z " fill="#08080A" transform="translate(499,70)"/>
|
||||
<path d="M0 0 C1.58203125 1.66796875 1.58203125 1.66796875 1.58203125 5.66796875 C-0.24609375 8.0625 -0.24609375 8.0625 -2.66796875 10.48046875 C-3.456875 11.29128906 -4.24578125 12.10210937 -5.05859375 12.9375 C-7.41796875 14.66796875 -7.41796875 14.66796875 -9.58984375 14.4921875 C-10.87844933 13.91121361 -12.15367922 13.30011351 -13.41796875 12.66796875 C-18.59558143 12.15189951 -23.07162336 12.11500546 -27.91796875 14.10546875 C-33.66913025 20.00040929 -33.87356406 28.09995626 -33.9296875 35.953125 C-33.9476387 36.8948204 -33.9655899 37.83651581 -33.98408508 38.80674744 C-34.03777974 41.78127717 -34.07195171 44.75565028 -34.10546875 47.73046875 C-34.13867794 49.76108932 -34.17317088 51.79168932 -34.20898438 53.82226562 C-34.29348231 58.77071953 -34.36048689 63.71913029 -34.41796875 68.66796875 C-40.02796875 68.66796875 -45.63796875 68.66796875 -51.41796875 68.66796875 C-51.41796875 44.90796875 -51.41796875 21.14796875 -51.41796875 -3.33203125 C-45.80796875 -3.33203125 -40.19796875 -3.33203125 -34.41796875 -3.33203125 C-34.08796875 -1.68203125 -33.75796875 -0.03203125 -33.41796875 1.66796875 C-32.67546875 1.04921875 -31.93296875 0.43046875 -31.16796875 -0.20703125 C-21.53059322 -7.65409416 -9.77403562 -6.65866875 0 0 Z " fill="#070709" transform="translate(412.41796875,109.33203125)"/>
|
||||
<path d="M0 0 C3.62365347 3.99851417 3.44730059 8.25868181 3.28125 13.40625 C2.92171053 16.72200287 2.29410204 18.55295783 0 21 C-4.52162441 23.74080002 -7.47400283 24.31760393 -12.7109375 23.8359375 C-13.3530014 23.77965179 -13.99506531 23.72336609 -14.65658569 23.66537476 C-16.77451134 23.46887205 -18.8865471 23.23974308 -21 23 C-22.10486755 22.87558533 -22.10486755 22.87558533 -23.23205566 22.74865723 C-27.90893854 22.20777275 -32.5744168 21.59966694 -37.23779297 20.953125 C-39.65576921 20.62077073 -42.07569435 20.30634824 -44.49609375 19.9921875 C-46.05223146 19.77972796 -47.60822721 19.56622547 -49.1640625 19.3515625 C-50.23595322 19.21544052 -50.23595322 19.21544052 -51.32949829 19.0765686 C-55.51250758 18.4749119 -58.59393869 17.53147784 -62 15 C-63.43735246 12.12529507 -63.38172649 10.18105412 -63 7 C-58.54839678 1.78836696 -52.21129528 1.72201371 -45.8125 0.875 C-44.07432007 0.6279834 -44.07432007 0.6279834 -42.30102539 0.37597656 C-38.8697716 -0.10371979 -35.43624001 -0.55757005 -32 -1 C-31.06575195 -1.12149414 -30.13150391 -1.24298828 -29.16894531 -1.36816406 C-26.75978753 -1.6751507 -24.34975685 -1.96848703 -21.9375 -2.25 C-21.25598877 -2.33008301 -20.57447754 -2.41016602 -19.87231445 -2.49267578 C-4.80907763 -4.10186033 -4.80907763 -4.10186033 0 0 Z " fill="#FE7039" transform="translate(199,120)"/>
|
||||
<path d="M0 0 C0.85850555 0.1038652 1.71701111 0.20773041 2.60153198 0.31474304 C4.40186289 0.53467384 6.20184063 0.75751383 8.00146484 0.9831543 C10.74057943 1.32401864 13.48138243 1.64772427 16.22265625 1.97070312 C17.98189995 2.18775813 19.74101944 2.4058228 21.5 2.625 C22.31058868 2.71888504 23.12117737 2.81277008 23.95632935 2.90950012 C28.99308043 3.56175949 33.10027078 4.64497567 37.6171875 7.01171875 C39.6171875 10.01171875 39.6171875 10.01171875 39.3671875 13.57421875 C38.6171875 17.01171875 38.6171875 17.01171875 36.6171875 19.01171875 C34.55200195 19.55834961 34.55200195 19.55834961 31.98046875 19.9765625 C31.02132568 20.13543945 30.06218262 20.29431641 29.07397461 20.45800781 C28.03635986 20.62010742 26.99874512 20.78220703 25.9296875 20.94921875 C24.86564697 21.1203418 23.80160645 21.29146484 22.70532227 21.46777344 C15.1682882 22.66019807 7.61816829 23.7511583 0.0546875 24.76171875 C-1.36106567 24.95302368 -1.36106567 24.95302368 -2.80541992 25.14819336 C-17.31186215 27.01302693 -17.31186215 27.01302693 -23.3828125 23.01171875 C-27.02637584 19.12525119 -26.88210576 14.75758051 -26.73828125 9.67578125 C-26.23821448 5.92802806 -24.9286388 3.76969724 -22.3828125 1.01171875 C-15.84749844 -2.95266934 -7.24058287 -0.89735419 0 0 Z " fill="#FE7139" transform="translate(48.3828125,117.98828125)"/>
|
||||
<path d="M0 0 C2.69924999 1.79949999 3.97268929 2.98831891 5.625 5.75 C6.99344145 15.86914699 5.01332723 26.66429063 3.65356445 36.71191406 C3.30949244 39.27238125 2.98705575 41.83499184 2.66601562 44.3984375 C2.44920051 46.04704435 2.23114667 47.69548888 2.01171875 49.34375 C1.91783371 50.10006714 1.82394867 50.85638428 1.72721863 51.63562012 C1.09337 56.17414888 0.04108984 59.76523478 -2.375 63.75 C-5.4582635 65.29163175 -7.98378099 65.04747535 -11.375 64.75 C-15.22166785 61.31318029 -15.3272904 56.46613107 -15.98046875 51.62890625 C-16.10940018 50.73316391 -16.2383316 49.83742157 -16.37117004 48.91453552 C-16.64146628 47.01650682 -16.90586639 45.11763044 -17.16479492 43.21801758 C-17.55711089 40.35187129 -17.97132834 37.48954926 -18.38867188 34.62695312 C-22.01941843 9.12762749 -22.01941843 9.12762749 -19.36669922 3.67895508 C-14.53713333 -2.53836515 -6.89205685 -2.55261365 0 0 Z " fill="#FE723B" transform="translate(119.375,41.25)"/>
|
||||
<path d="M0 0 C2.90652991 2.90652991 2.876536 6.26706827 3.4375 10.1875 C3.62372925 11.43889771 3.62372925 11.43889771 3.8137207 12.71557617 C4.21906167 15.47570672 4.60956571 18.23772456 5 21 C5.14115234 21.96454102 5.28230469 22.92908203 5.42773438 23.92285156 C9.97022281 55.07281183 9.97022281 55.07281183 5.8125 61.25 C0.715773 64.4212968 -2.9058144 65.63043299 -9 65 C-12.29013805 63.71053175 -15.20895719 62.21495778 -17.18669128 59.17736816 C-19.85591311 52.03139945 -17.79685661 42.79141254 -16.79296875 35.40625 C-16.60387688 33.9753302 -16.60387688 33.9753302 -16.41096497 32.51550293 C-16.14485659 30.52187219 -15.87493824 28.52874651 -15.60131836 26.53613281 C-15.18498991 23.48158379 -14.79028617 20.42471259 -14.39648438 17.3671875 C-14.134117 15.42169863 -13.87049062 13.47637904 -13.60546875 11.53125 C-13.48970993 10.61879517 -13.37395111 9.70634033 -13.25468445 8.76623535 C-13.13478653 7.92105347 -13.01488861 7.07587158 -12.89135742 6.20507812 C-12.7914299 5.46326294 -12.69150238 4.72144775 -12.58854675 3.95715332 C-11.8654499 1.55256711 -10.95241701 0.55505439 -9 -1 C-5.19825711 -2.26724763 -3.6488868 -1.4750819 0 0 Z " fill="#FE723B" transform="translate(117,156)"/>
|
||||
<path d="M0 0 C5.94 0 11.88 0 18 0 C18 23.76 18 47.52 18 72 C12.06 72 6.12 72 0 72 C0 48.24 0 24.48 0 0 Z " fill="#070708" transform="translate(330,106)"/>
|
||||
<path d="M0 0 C5.04330987 4.1028907 7.71774978 9.39439884 10.75 15.0625 C11.24371094 15.96033203 11.73742187 16.85816406 12.24609375 17.78320312 C17.43420605 27.34212236 17.43420605 27.34212236 16.3125 31.625 C15 34 15 34 13.3125 35.375 C7.93375248 36.82871554 3.75347415 35.06129862 -0.91796875 32.453125 C-2.68187675 31.39768267 -4.43827823 30.32960785 -6.1875 29.25 C-7.07630859 28.7240625 -7.96511719 28.198125 -8.88085938 27.65625 C-13.35431143 24.94058564 -17.21257396 22.56892147 -20 18 C-20.61105403 13.79900352 -20.33783835 11.64968914 -18.375 7.875 C-13.06220859 1.44372619 -8.6335148 -2.08395185 0 0 Z " fill="#FE713A" transform="translate(63,62)"/>
|
||||
<path d="M0 0 C6.03297915 0.33114122 9.30476624 2.08342832 13.6171875 6.29296875 C16.38968616 9.47219093 17.04213903 11.96541114 17.65234375 16.0625 C17.06814734 20.15187485 15.13009417 22.36369578 12.21484375 25.125 C9.21149624 27.28908872 6.06168268 29.11960481 2.83984375 30.9375 C2.01484375 31.42669922 1.18984375 31.91589844 0.33984375 32.41992188 C-4.43543981 35.16002506 -8.25324942 36.89804998 -13.78515625 37.125 C-16.58087127 36.16857118 -17.46165114 35.77201022 -18.78515625 33.125 C-19.67120353 26.26932103 -16.95954186 21.84338012 -13.59765625 16 C-13.11490234 15.11957031 -12.63214844 14.23914063 -12.13476562 13.33203125 C-9.4652036 8.58056917 -6.87140939 4.73948324 -2.78515625 1.125 C-1.78515625 0.125 -1.78515625 0.125 0 0 Z " fill="#FE713A" transform="translate(163.78515625,60.875)"/>
|
||||
<path d="M0 0 C2.78888858 1.43213197 3.75957557 2.28489145 4.76171875 5.265625 C5.06866999 8.7880163 4.15658074 10.4564111 2.5 13.5625 C1.94570312 14.60535156 1.39140625 15.64820313 0.8203125 16.72265625 C0.21960938 17.80417969 -0.38109375 18.88570312 -1 20 C-1.60070312 21.09183594 -2.20140625 22.18367188 -2.8203125 23.30859375 C-8.27249431 32.95022261 -8.27249431 32.95022261 -12 36 C-16.40910476 37.09025136 -20.18006761 36.37843033 -24.25 34.5 C-28.79178106 30.37110812 -31.58989016 26.41964808 -32.625 20.3125 C-31.84891159 16.19923141 -30.15611216 14.52356363 -27 12 C-23.60919652 9.73474885 -20.10610667 7.70297221 -16.5625 5.6875 C-15.63373047 5.13771484 -14.70496094 4.58792969 -13.74804688 4.02148438 C-5.16887017 -0.89398698 -5.16887017 -0.89398698 0 0 Z " fill="#FE713A" transform="translate(75,163)"/>
|
||||
<path d="M0 0 C2.54541016 1.03808594 2.54541016 1.03808594 5.0390625 2.484375 C5.94914063 3.00773438 6.85921875 3.53109375 7.796875 4.0703125 C9.19679687 4.90175781 9.19679687 4.90175781 10.625 5.75 C11.56601563 6.28882813 12.50703125 6.82765625 13.4765625 7.3828125 C23.65542022 13.31084043 23.65542022 13.31084043 26 18 C26.23675113 23.05412198 25.48527501 26.97865449 22.25 30.9375 C18.41837476 34.85992204 15.48689762 35.78758605 10.0625 36.5625 C7.57335027 36.49114109 6.40429881 36.33826832 4.47973633 34.72802734 C0.68248769 30.09704219 -2.45567147 25.28818627 -5.375 20.0625 C-5.82488281 19.30259766 -6.27476562 18.54269531 -6.73828125 17.75976562 C-9.65990878 12.56033427 -10.65491643 8.96628872 -10 3 C-7.14254571 -0.51686681 -4.31419574 -0.2967049 0 0 Z " fill="#FE713A" transform="translate(155,163)"/>
|
||||
<path d="M0 0 C3.53733123 2.55892046 4.75963588 4.1887711 6 8.375 C6 12.7289874 5.17207574 15.23506872 3 19 C0.12121032 21.47895778 -1.66317695 21.95713161 -5.4375 22.4375 C-9.70968693 21.91284546 -11.75031771 20.79623825 -15 18 C-17.10863429 14.35781349 -17.50962203 11.16191328 -17 7 C-15.27978264 3.68698879 -13.9086019 1.58049566 -10.75 -0.4375 C-6.93940558 -1.21693977 -3.72934532 -1.15270673 0 0 Z " fill="#060608" transform="translate(548,158)"/>
|
||||
<path d="M0 0 C2.66915647 2.14834545 3.77943987 3.55633371 4.30078125 6.96875 C4.43294773 10.69723583 4.46252586 14.10920878 2 17 C-2.01955829 19.36444606 -4.10903676 20.14849387 -8.75 19.375 C-12.50920399 17.78456754 -14.19878159 16.60243682 -16 13 C-16.4128469 8.70639223 -16.2493583 6.46432234 -14.1875 2.625 C-10.27705848 -2.06752982 -5.52304925 -1.42562463 0 0 Z " fill="#060608" transform="translate(345,74)"/>
|
||||
<path d="M0 0 C5.61 0 11.22 0 17 0 C19 5 19 5 19 8 C18.01 8 17.02 8 16 8 C16 5.69 16 3.38 16 1 C11.05 1 6.1 1 1 1 C1 34 1 67 1 101 C5.62 101 10.24 101 15 101 C15 101.33 15 101.66 15 102 C10.05 102 5.1 102 0 102 C0 68.34 0 34.68 0 0 Z " fill="#000000" transform="translate(649,106)"/>
|
||||
<path d="M0 0 C1.48831242 0.00667405 2.97660807 0.01863442 4.46484375 0.03515625 C5.22345703 0.03966797 5.98207031 0.04417969 6.76367188 0.04882812 C8.64326246 0.06064945 10.52281274 0.07858547 12.40234375 0.09765625 C13.52283021 3.69273097 13.52281589 7.0427002 13.51586914 10.79394531 C13.51601517 11.45777222 13.51616119 12.12159912 13.51631165 12.80554199 C13.51561707 14.99148875 13.50784606 17.17734944 13.5 19.36328125 C13.4981342 20.88214064 13.49671106 22.40100063 13.49571228 23.91986084 C13.49189985 27.91143464 13.48208045 31.90297187 13.4710083 35.89453125 C13.46076678 39.97004705 13.45620879 44.04556878 13.45117188 48.12109375 C13.44045702 56.11329987 13.42287055 64.1054693 13.40234375 72.09765625 C7.46234375 72.09765625 1.52234375 72.09765625 -4.59765625 72.09765625 C-4.92765625 69.78765625 -5.25765625 67.47765625 -5.59765625 65.09765625 C-4.11265625 64.60265625 -4.11265625 64.60265625 -2.59765625 64.09765625 C-2.59765625 66.40765625 -2.59765625 68.71765625 -2.59765625 71.09765625 C2.02234375 71.09765625 6.64234375 71.09765625 11.40234375 71.09765625 C11.40234375 47.99765625 11.40234375 24.89765625 11.40234375 1.09765625 C6.78234375 1.09765625 2.16234375 1.09765625 -2.59765625 1.09765625 C-2.59765625 3.40765625 -2.59765625 5.71765625 -2.59765625 8.09765625 C-3.25765625 8.09765625 -3.91765625 8.09765625 -4.59765625 8.09765625 C-4.64007348 5.7647085 -4.63858562 3.43063058 -4.59765625 1.09765625 C-3.59765625 0.09765625 -3.59765625 0.09765625 0 0 Z " fill="#000000" transform="translate(622.59765625,105.90234375)"/>
|
||||
<path d="M0 0 C0.66 0.66 1.32 1.32 2 2 C0.3603125 1.9071875 0.3603125 1.9071875 -1.3125 1.8125 C-4.8362826 1.70189764 -4.8362826 1.70189764 -6.875 3.125 C-8.40430823 5.67384706 -8.67470941 8.07238473 -9 11 C-9.33 11 -9.66 11 -10 11 C-10.48541424 3.59743291 -10.48541424 3.59743291 -8.375 1 C-5.38358852 -0.25954167 -3.21567216 -0.34952958 0 0 Z " fill="#FE5D28" transform="translate(155,163)"/>
|
||||
<path d="M0 0 C0.99 0.33 1.98 0.66 3 1 C2.38125 1.598125 1.7625 2.19625 1.125 2.8125 C-1.13676954 5.00811144 -1.13676954 5.00811144 -3 8 C-3.36923077 3.44615385 -3.36923077 3.44615385 -1.5 1.1875 C-1.005 0.795625 -0.51 0.40375 0 0 Z " fill="#FE6B2D" transform="translate(139,124)"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 20 KiB |