Compare commits

..
Author SHA1 Message Date
dependabot[bot] 754461d4a8 build(deps): bump next from 16.2.3 to 16.2.6
Bumps [next](https://github.com/vercel/next.js) from 16.2.3 to 16.2.6.
- [Release notes](https://github.com/vercel/next.js/releases)
- [Changelog](https://github.com/vercel/next.js/blob/canary/release.js)
- [Commits](https://github.com/vercel/next.js/compare/v16.2.3...v16.2.6)

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

Signed-off-by: dependabot[bot] <[email protected]>
2026-05-11 17:07:53 +00:00
87 changed files with 532 additions and 2433 deletions
+4 -13
View File
@@ -1,22 +1,13 @@
# Dependencies # Dependencies
node_modules node_modules
**/node_modules
.pnp .pnp
.pnp.js .pnp.js
# Build outputs # Build outputs
# Patterns without a leading `**/` only match the build-context root, NOT dist
# nested directories. In this monorepo the actual outputs live under .next
# apps/*/{dist,.next,.turbo} and packages/*/{dist,.turbo}; without `**/` .turbo
# any stale local builds (from running `yarn dev` or `yarn build` on the out
# 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 # Development
.env .env
+14 -30
View File
@@ -52,13 +52,6 @@ SES_CONFIGURATION_SET=plunk-configuration-set
# When set, projects can choose to disable email tracking # When set, projects can choose to disable email tracking
SES_CONFIGURATION_SET_NO_TRACKING=plunk-no-tracking-configuration-set 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 # OPTIONAL: OAuth Login
# ======================================== # ========================================
@@ -67,6 +60,15 @@ GITHUB_OAUTH_SECRET=
GOOGLE_OAUTH_CLIENT= GOOGLE_OAUTH_CLIENT=
GOOGLE_OAUTH_SECRET= 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) # OPTIONAL: File Storage (Minio)
# ======================================== # ========================================
@@ -152,29 +154,11 @@ SMTP_DOMAIN=smtp.example.com
# Default: false # Default: false
# DISABLE_SIGNUPS=false # DISABLE_SIGNUPS=false
# ======================================== # Controls whether email validation checks are performed on signup
# OPTIONAL: SES Sending Rate # When enabled (true), validates emails for disposable domains, plus-addressing, domain existence, and MX records
# ======================================== # When disabled (false), skips these validation checks and allows any email format
# Caps the email-worker's send rate (messages per second) for the SES sandbox or # Default: false
# manually-throttled accounts. When unset, the worker probes the AWS account at # VERIFY_EMAIL_ON_SIGNUP=false
# 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) # ADVANCED (rarely needed)
-12
View File
@@ -65,18 +65,6 @@ jobs:
- name: Install dependencies - name: Install dependencies
run: yarn install --frozen-lockfile 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 - name: Setup environment variables
run: | run: |
cat > .env << EOF cat > .env << EOF
+1 -1
View File
@@ -1,3 +1,3 @@
{ {
".": "0.12.0" ".": "0.10.0"
} }
-98
View File
@@ -1,103 +1,5 @@
# Changelog # Changelog
## [0.12.0](https://github.com/useplunk/plunk/compare/v0.11.0...v0.12.0) (2026-05-27)
### Features
* add disabledReason field to projects for better tracking of disable reasons ([94ceadb](https://github.com/useplunk/plunk/commit/94ceadbbe417f0cb3ab72c66bfad9428bdce2d11))
* **api:** allow API key authentication for domain endpoints ([d2496bc](https://github.com/useplunk/plunk/commit/d2496bc51d17657380160dbfc20e099d3f4eadba))
* **contacts:** make email cell a link to the contact detail page ([6759bff](https://github.com/useplunk/plunk/commit/6759bffd2a1f0bfb09b754bb0efdfe5c347ea2b3))
* **contacts:** make email cell a link to the contact detail page ([6d98d51](https://github.com/useplunk/plunk/commit/6d98d512222ffb422bc2a4bef4284a644558b39d))
* **EmailService:** add worker concurrency settings and improve email queue prioritization ([80beb2b](https://github.com/useplunk/plunk/commit/80beb2bb9937101d1723f2d54648060fdcbe6cef))
* make detectCustomHtmlPatterns aware of TipTap's actual capabilities ([9797aed](https://github.com/useplunk/plunk/commit/9797aed47f520aba51bec4e09c9bc4b7762e02f8))
* make detectCustomHtmlPatterns aware of TipTap's actual capabilities ([ba3813e](https://github.com/useplunk/plunk/commit/ba3813e2422d9fe4e252a90242393cada65644dc))
* render template variables in WEBHOOK step url, headers and body ([bfecf04](https://github.com/useplunk/plunk/commit/bfecf04fa38309804ee19e99b9908caf51c5e039))
* render template variables in WEBHOOK step url, headers and body ([c484da8](https://github.com/useplunk/plunk/commit/c484da88ab7b4635987868e2e3c6fdded68ade8c))
* **SecurityService:** enhance phishing detection by verifying sender domains and institutional TLDs ([6ab4d77](https://github.com/useplunk/plunk/commit/6ab4d77ca9bebd01f75d8799dad23fdec7768b52))
* **SecurityService:** enhance phishing detection by verifying sender domains and institutional TLDs ([edfc399](https://github.com/useplunk/plunk/commit/edfc399061cb7fd079b7f11167a2796df766d8ac))
* **tests:** enhance test database setup and cleanup for improved isolation and performance ([32dd7bb](https://github.com/useplunk/plunk/commit/32dd7bba462a6f4a13d59b8fb03708f971d1eff0))
### Bug Fixes
* coerce boolean and numeric values in custom CSV columns ([4a145f3](https://github.com/useplunk/plunk/commit/4a145f3488bee63c2d82a4a477f6dfaaaaede64b))
* **filters:** land templates/workflows/campaigns search inputs at 32px to match filter buttons ([283f402](https://github.com/useplunk/plunk/commit/283f40239dcc81e78d35b39cb9b31f97b435b8d7))
* make email templates, campaigns and workflow search inputs same height as the rest of the app ([8b3657d](https://github.com/useplunk/plunk/commit/8b3657d056938b17f0634c0fe8d664ae1e07cd73))
### Code Refactoring
* **database:** increase Prisma connection pool limits for improved test performance ([71e2277](https://github.com/useplunk/plunk/commit/71e227764319e6fc732aefdebd11f3e844257ef6))
* **SecurityService:** update absolute count ceilings for new projects to improve spam detection ([4de40f4](https://github.com/useplunk/plunk/commit/4de40f40fa300c9e9ed2ed35f367ca4cd601f309))
### Documentation
* add env-var sync rule to CLAUDE.md ([a348d37](https://github.com/useplunk/plunk/commit/a348d37c21ecf1d57845f31210f66a8113fadb8d))
* add new recipe pages for waitlist and sync unsubscribes ([01ec34a](https://github.com/useplunk/plunk/commit/01ec34a8cbbe0f4a158398c0eb8300d847bc29ab))
* correct PHISHING_CONFIDENCE_THRESHOLD default in CLAUDE.md ([5c16679](https://github.com/useplunk/plunk/commit/5c166797b57f2e7b714957824ee1acdcb22c05f2))
* **env:** add wiki-documented vars to apps/api/.env.example ([81315ea](https://github.com/useplunk/plunk/commit/81315eac8eb32a7d2e61617c6a84f349afaf7860))
* **env:** sync .env.self-host.example with missing variables ([1c1c95d](https://github.com/useplunk/plunk/commit/1c1c95d332fb9ab6c2f926f6d51071cfb245ed86))
* **env:** sync env example files, fix CLAUDE.md drift, add process rule ([6ebbb50](https://github.com/useplunk/plunk/commit/6ebbb50f6817f1354f26cc7734631d3b6ded32ed))
* **wiki:** document MAIL_FROM_SUBDOMAIN and NGINX_PORT env vars ([971b98a](https://github.com/useplunk/plunk/commit/971b98a4cc6145571204f5a4ad794aa3d09ea71c))
## [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) ## [0.10.0](https://github.com/useplunk/plunk/compare/v0.9.0...v0.10.0) (2026-05-01)
+1 -16
View File
@@ -161,7 +161,7 @@ Required for builds and deployment (see turbo.json and .env.example):
- `OPENROUTER_API_KEY` - API key for OpenRouter (enables phishing detection) - `OPENROUTER_API_KEY` - API key for OpenRouter (enables phishing detection)
- `OPENROUTER_MODEL` (default: anthropic/claude-3-haiku) - LLM model to use for content analysis - `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_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_CONFIDENCE_THRESHOLD` (default: 85) - 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_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) - `PHISHING_CUMULATIVE_WINDOW_MS` (default: 3600000) - Time window in milliseconds for cumulative tracking (default 1 hour)
@@ -174,21 +174,6 @@ Required for builds and deployment (see turbo.json and .env.example):
- **Frontend Variables**: Next.js apps use `NEXT_PUBLIC_*` prefixed variables that are embedded at build time for - **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 ## Plugins
There are two plugins installed for you to use. There are two plugins installed for you to use.
-58
View File
@@ -8,8 +8,6 @@
# ============================================================================== # ==============================================================================
NODE_ENV=development NODE_ENV=development
JWT_SECRET=hBx9Xh8J6KOMAGAsSjvcZJBT5TWyIkFX JWT_SECRET=hBx9Xh8J6KOMAGAsSjvcZJBT5TWyIkFX
# Port the API server listens on (default: 8080)
# PORT=8080
# ============================================================================== # ==============================================================================
# Application URLs # Application URLs
@@ -27,8 +25,6 @@ LANDING_URI=http://localhost:4000
# ============================================================================== # ==============================================================================
# API key for authenticating with the Plunk API (obtained from dashboard) # API key for authenticating with the Plunk API (obtained from dashboard)
PLUNK_API_KEY= PLUNK_API_KEY=
# From address used for platform notification emails (project disabled, billing limits, etc.)
# PLUNK_FROM_ADDRESS=
# ============================================================================== # ==============================================================================
# Database & Redis # Database & Redis
@@ -65,17 +61,6 @@ SES_CONFIGURATION_SET_NO_TRACKING=plunk-configuration-set-no-tracking # Optiona
# Default: Fetched from AWS (typically 14 for sandbox, higher for production accounts) # Default: Fetched from AWS (typically 14 for sandbox, higher for production accounts)
# EMAIL_RATE_LIMIT_PER_SECOND=14 # 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) # OAuth (Optional - for social login)
# ============================================================================== # ==============================================================================
@@ -100,46 +85,3 @@ 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) # Set to 'false' to disable automatic project suspension (useful for self-hosters who manage manually)
# Default: true (automatic project disabling enabled) # Default: true (automatic project disabling enabled)
# AUTO_PROJECT_DISABLE=true # 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
-20
View File
@@ -45,12 +45,6 @@ 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_ACCESS_KEY_ID = validateEnv('AWS_SES_ACCESS_KEY_ID');
export const AWS_SES_SECRET_ACCESS_KEY = validateEnv('AWS_SES_SECRET_ACCESS_KEY'); 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) // Email Processing Rate Limit (optional override)
// If not set, will automatically fetch from AWS SES account quota // If not set, will automatically fetch from AWS SES account quota
// Set this to override AWS quota (useful for setting lower limits or testing) // Set this to override AWS quota (useful for setting lower limits or testing)
@@ -58,20 +52,6 @@ export const EMAIL_RATE_LIMIT_PER_SECOND = process.env.EMAIL_RATE_LIMIT_PER_SECO
? Number(process.env.EMAIL_RATE_LIMIT_PER_SECOND) ? Number(process.env.EMAIL_RATE_LIMIT_PER_SECOND)
: undefined; : 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 // Storage
export const REDIS_URL = validateEnv('REDIS_URL'); export const REDIS_URL = validateEnv('REDIS_URL');
export const DATABASE_URL = validateEnv('DATABASE_URL'); export const DATABASE_URL = validateEnv('DATABASE_URL');
-2
View File
@@ -8,7 +8,6 @@ import {
GITHUB_OAUTH_ENABLED, GITHUB_OAUTH_ENABLED,
GOOGLE_OAUTH_ENABLED, GOOGLE_OAUTH_ENABLED,
LANDING_URI, LANDING_URI,
MAIL_FROM_SUBDOMAIN,
NODE_ENV, NODE_ENV,
S3_ENABLED, S3_ENABLED,
SMTP_DOMAIN, SMTP_DOMAIN,
@@ -63,7 +62,6 @@ export class Config {
}, },
aws: { aws: {
sesRegion: AWS_SES_REGION, sesRegion: AWS_SES_REGION,
mailFromSubdomain: MAIL_FROM_SUBDOMAIN,
}, },
}); });
} }
+24 -24
View File
@@ -4,7 +4,7 @@ import type {NextFunction, Request, Response} from 'express';
import {redis} from '../database/redis.js'; import {redis} from '../database/redis.js';
import {NotAllowed, NotFound} from '../exceptions/index.js'; import {NotAllowed, NotFound} from '../exceptions/index.js';
import {requireAuth, requireEmailVerified} from '../middleware/auth.js'; import {isAuthenticated, requireEmailVerified} from '../middleware/auth.js';
import {DomainService} from '../services/DomainService.js'; import {DomainService} from '../services/DomainService.js';
import {Keys} from '../services/keys.js'; import {Keys} from '../services/keys.js';
import {MembershipService} from '../services/MembershipService.js'; import {MembershipService} from '../services/MembershipService.js';
@@ -17,12 +17,16 @@ export class Domains {
* Get all domains for a project * Get all domains for a project
*/ */
@Get('project/:projectId') @Get('project/:projectId')
@Middleware([requireAuth, requireEmailVerified]) @Middleware([isAuthenticated, requireEmailVerified])
@CatchAsync @CatchAsync
public async getProjectDomains(_req: Request, res: Response, _next: NextFunction) { public async getProjectDomains(req: Request, res: Response, _next: NextFunction) {
const auth = res.locals.auth; const auth = res.locals.auth;
const {projectId} = DomainSchemas.projectId.parse(req.params);
const domains = await DomainService.getProjectDomains(auth.projectId!); // Verify user has access to this project
await MembershipService.requireAccess(auth.userId!, projectId);
const domains = await DomainService.getProjectDomains(projectId);
return res.status(200).json(domains); return res.status(200).json(domains);
} }
@@ -31,18 +35,19 @@ export class Domains {
* Add a new domain to a project * Add a new domain to a project
*/ */
@Post('') @Post('')
@Middleware([requireAuth, requireEmailVerified]) @Middleware([isAuthenticated, requireEmailVerified])
@CatchAsync @CatchAsync
public async addDomain(req: Request, res: Response, _next: NextFunction) { public async addDomain(req: Request, res: Response, _next: NextFunction) {
const auth = res.locals.auth; const auth = res.locals.auth;
const {domain} = DomainSchemas.create.parse(req.body); const {projectId, domain} = DomainSchemas.create.parse(req.body);
const projectId = auth.projectId!;
// Require admin role for JWT users (API keys bypass — project-scoped by design) if (!auth.userId) {
if (auth.type === 'jwt') { throw new NotFound('User authentication required');
await MembershipService.requireAdminAccess(auth.userId!, projectId);
} }
// Verify user has admin access to this project
await MembershipService.requireAdminAccess(auth.userId!, projectId);
// Block domain changes on disabled projects // Block domain changes on disabled projects
const isDisabled = await SecurityService.isProjectDisabled(projectId); const isDisabled = await SecurityService.isProjectDisabled(projectId);
if (isDisabled) { if (isDisabled) {
@@ -63,12 +68,6 @@ export class Domains {
const ownershipCheck = await DomainService.checkDomainOwnership(domain, auth.userId); const ownershipCheck = await DomainService.checkDomainOwnership(domain, auth.userId);
if (ownershipCheck.exists) { 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 domain exists and user is a member of that project, allow it
if (ownershipCheck.isMember) { if (ownershipCheck.isMember) {
return res.status(400).json({ return res.status(400).json({
@@ -100,7 +99,7 @@ export class Domains {
* Check verification status for a domain * Check verification status for a domain
*/ */
@Get(':id/verify') @Get(':id/verify')
@Middleware([requireAuth, requireEmailVerified]) @Middleware([isAuthenticated, requireEmailVerified])
@CatchAsync @CatchAsync
public async checkVerification(req: Request, res: Response, _next: NextFunction) { public async checkVerification(req: Request, res: Response, _next: NextFunction) {
const auth = res.locals.auth; const auth = res.locals.auth;
@@ -108,10 +107,13 @@ export class Domains {
const domain = await DomainService.id(id); const domain = await DomainService.id(id);
if (!domain || domain.projectId !== auth.projectId) { if (!domain) {
throw new NotFound('Domain not found'); throw new NotFound('Domain not found');
} }
// Verify user has access to the project this domain belongs to
await MembershipService.requireAccess(auth.userId!, domain.projectId);
const verificationStatus = await DomainService.checkVerification(id); const verificationStatus = await DomainService.checkVerification(id);
// Invalidate cache if status changed // Invalidate cache if status changed
@@ -125,7 +127,7 @@ export class Domains {
* Remove a domain from a project * Remove a domain from a project
*/ */
@Delete(':id') @Delete(':id')
@Middleware([requireAuth, requireEmailVerified]) @Middleware([isAuthenticated, requireEmailVerified])
@CatchAsync @CatchAsync
public async removeDomain(req: Request, res: Response, _next: NextFunction) { public async removeDomain(req: Request, res: Response, _next: NextFunction) {
const auth = res.locals.auth; const auth = res.locals.auth;
@@ -133,14 +135,12 @@ export class Domains {
const domain = await DomainService.id(id); const domain = await DomainService.id(id);
if (!domain || domain.projectId !== auth.projectId) { if (!domain) {
throw new NotFound('Domain not found'); throw new NotFound('Domain not found');
} }
// Require admin role for JWT users (API keys bypass — project-scoped by design) // Verify user has admin access to the project this domain belongs to
if (auth.type === 'jwt') { await MembershipService.requireAdminAccess(auth.userId!, domain.projectId);
await MembershipService.requireAdminAccess(auth.userId!, domain.projectId);
}
// Block domain changes on disabled projects // Block domain changes on disabled projects
const isDisabled = await SecurityService.isProjectDisabled(domain.projectId); const isDisabled = await SecurityService.isProjectDisabled(domain.projectId);
-8
View File
@@ -230,14 +230,6 @@ export class Users {
client_reference_id: project.id, // Store project ID for webhook client_reference_id: project.id, // Store project ID for webhook
line_items: lineItems, line_items: lineItems,
...(checkoutCurrency && {currency: checkoutCurrency}), ...(checkoutCurrency && {currency: checkoutCurrency}),
custom_fields: [
{
key: 'promo_code',
label: {type: 'custom', custom: 'Promo code'},
type: 'text',
optional: true,
},
],
subscription_data: { subscription_data: {
billing_cycle_anchor: billingCycleAnchor, billing_cycle_anchor: billingCycleAnchor,
}, },
+2 -26
View File
@@ -530,24 +530,10 @@ 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 // Update Stripe customer name to match project name and add credit for onboarding fee
await stripe.customers.update(customerId, { await stripe.customers.update(customerId, {
name: updatedProject.name, name: updatedProject.name,
balance: creditBalance, balance: -100,
}); });
signale.success(`[WEBHOOK] Checkout completed for project ${projectId}`); signale.success(`[WEBHOOK] Checkout completed for project ${projectId}`);
@@ -573,16 +559,6 @@ export class Webhooks {
signale.success(`[WEBHOOK] Invoice paid for project ${project.name} (${project.id})`); 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 // Send notification about invoice payment
await NtfyService.notifyInvoicePaid(project.name, project.id); await NtfyService.notifyInvoicePaid(project.name, project.id);
break; break;
@@ -616,7 +592,7 @@ export class Webhooks {
await prisma.project.update({ await prisma.project.update({
where: {id: project.id}, where: {id: project.id},
data: {disabled: true, disabledReason: 'PAYMENT_FAILED'}, data: {disabled: true},
}); });
await NtfyService.notifyProjectDisabledForPayment(project.name, project.id); await NtfyService.notifyProjectDisabledForPayment(project.name, project.id);
@@ -1,7 +1,6 @@
import {beforeEach, describe, expect, it} from 'vitest'; import {beforeEach, describe, expect, it} from 'vitest';
import {factories, getPrismaClient} from '../../../../../test/helpers'; import {factories, getPrismaClient} from '../../../../../test/helpers';
import {ContactService} from '../../services/ContactService.js'; import {ContactService} from '../../services/ContactService.js';
import {coerceCustomValue} from '../import-processor.js';
/** /**
* Tests for Contact Import Processor - Subscription Status Preservation * Tests for Contact Import Processor - Subscription Status Preservation
@@ -280,51 +279,3 @@ describe('Contact Import - Subscription Status Preservation', () => {
}); });
}); });
}); });
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('');
});
});
});
+2 -29
View File
@@ -8,12 +8,7 @@ import type {SendEmailJobData} from '@plunk/types';
import {type Job, Worker} from 'bullmq'; import {type Job, Worker} from 'bullmq';
import signale from 'signale'; import signale from 'signale';
import { import {DASHBOARD_URI, EMAIL_RATE_LIMIT_PER_SECOND} from '../app/constants.js';
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 {prisma} from '../database/prisma.js';
import {CampaignService} from '../services/CampaignService.js'; import {CampaignService} from '../services/CampaignService.js';
import {EmailService} from '../services/EmailService.js'; import {EmailService} from '../services/EmailService.js';
@@ -52,31 +47,9 @@ async function getEmailRateLimit(): Promise<number> {
return DEFAULT_RATE_LIMIT; 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() { export async function createEmailWorker() {
// Fetch the rate limit (from env, AWS, or default) // Fetch the rate limit (from env, AWS, or default)
const rateLimit = await getEmailRateLimit(); const rateLimit = await getEmailRateLimit();
const concurrency = deriveWorkerConcurrency(rateLimit);
signale.info(
`[EMAIL-PROCESSOR] Worker concurrency: ${concurrency} (rate limit: ${rateLimit}/s)`,
);
const worker = new Worker<SendEmailJobData>( const worker = new Worker<SendEmailJobData>(
emailQueue.name, emailQueue.name,
async (job: Job<SendEmailJobData>) => { async (job: Job<SendEmailJobData>) => {
@@ -280,7 +253,7 @@ export async function createEmailWorker() {
}, },
{ {
connection: emailQueue.opts.connection, connection: emailQueue.opts.connection,
concurrency, concurrency: 10, // Process up to 10 emails concurrently
limiter: { limiter: {
max: rateLimit, // Max emails per second (from env, AWS SES quota, or default) max: rateLimit, // Max emails per second (from env, AWS SES quota, or default)
duration: 1000, duration: 1000,
+1 -32
View File
@@ -123,11 +123,7 @@ export function createImportWorker() {
// Extract custom data (all fields except email and subscribed) // Extract custom data (all fields except email and subscribed)
const {email: _, subscribed: __, ...customData} = record; const {email: _, subscribed: __, ...customData} = record;
const customEntries = Object.entries(customData); const data = Object.keys(customData).length > 0 ? customData : undefined;
const data =
customEntries.length > 0
? Object.fromEntries(customEntries.map(([k, v]) => [k, coerceCustomValue(v)]))
: undefined;
// Check if contact exists before upserting // Check if contact exists before upserting
const existingContact = await ContactService.findByEmail(projectId, email); const existingContact = await ContactService.findByEmail(projectId, email);
@@ -220,30 +216,3 @@ function isValidEmail(email: string): boolean {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email); 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;
}
+64 -50
View File
@@ -135,47 +135,6 @@ export class ContactService {
* Update a contact * Update a contact
* Uses unique constraint violation to check for duplicates (more efficient) * 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( public static async update(
projectId: string, projectId: string,
contactId: string, contactId: string,
@@ -190,14 +149,7 @@ export class ContactService {
updateData.email = data.email; updateData.email = data.email;
} }
if (data.data !== undefined) { if (data.data !== undefined) {
if (data.data === null) { updateData.data = data.data === null ? Prisma.JsonNull : data.data;
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) { if (data.subscribed !== undefined) {
updateData.subscribed = data.subscribed; updateData.subscribed = data.subscribed;
@@ -273,7 +225,69 @@ export class ContactService {
}, },
}); });
const mergedData = ContactService.mergeContactData(existing?.data ?? null, data ?? {}); // 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 system-generated fields
// These fields are dynamically added during template rendering and cannot be overridden
const reservedFields = [
'plunk_id',
'plunk_email',
'id',
'email',
'unsubscribeUrl',
'subscribeUrl',
'manageUrl',
];
if (reservedFields.includes(key)) {
continue;
}
// Skip empty string values - they don't provide meaningful data
// and can cause issues with template rendering and data integrity
if (value === '') {
continue;
}
// Delete field if null is passed (allows removing fields from contact data)
if (value === null) {
delete mergedData[key];
continue;
}
// Validate locale field (special user-settable field)
// Only validate type - any locale string is accepted since we default to English if unsupported
if (key === 'locale') {
if (value !== undefined && typeof value !== 'string') {
throw new HttpException(400, 'Locale must be a string');
}
}
// 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;
}
}
if (existing) { if (existing) {
// Track subscription status change // Track subscription status change
+7 -18
View File
@@ -438,14 +438,15 @@ export class DomainService {
* @param userId User ID to check membership * @param userId User ID to check membership
* @returns Object with exists flag and membership info * @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({ const existingDomain = await prisma.domain.findFirst({
where: {domain}, where: {domain},
include: { include: {
project: { project: {
select: { include: {
id: true, members: {
name: true, where: {userId},
},
}, },
}, },
}, },
@@ -455,20 +456,8 @@ export class DomainService {
return {exists: false}; return {exists: false};
} }
let isMember = false; // Check if user is a member of the project that owns this domain
const isMember = existingDomain.project.members.length > 0;
if (userId) {
const membership = await prisma.membership.findUnique({
where: {
userId_projectId: {
userId,
projectId: existingDomain.project.id,
},
},
});
isMember = membership !== null;
}
return { return {
exists: true, exists: true,
+19 -23
View File
@@ -108,7 +108,7 @@ export class EmailService {
await BillingLimitService.incrementUsage(params.projectId, EmailSourceType.TRANSACTIONAL); await BillingLimitService.incrementUsage(params.projectId, EmailSourceType.TRANSACTIONAL);
// Queue email for sending // Queue email for sending
await this.queueEmail(email.id, EmailSourceType.TRANSACTIONAL); await this.queueEmail(email.id);
return email; return email;
} }
@@ -172,7 +172,7 @@ export class EmailService {
await BillingLimitService.incrementUsage(params.projectId, sourceType); await BillingLimitService.incrementUsage(params.projectId, sourceType);
// Queue email for sending // Queue email for sending
await this.queueEmail(email.id, sourceType); await this.queueEmail(email.id);
return email; return email;
} }
@@ -278,7 +278,7 @@ export class EmailService {
await BillingLimitService.incrementUsage(params.projectId, sourceType); await BillingLimitService.incrementUsage(params.projectId, sourceType);
// Queue email for sending // Queue email for sending
await this.queueEmail(email.id, sourceType); await this.queueEmail(email.id);
return email; return email;
} }
@@ -659,16 +659,12 @@ export class EmailService {
/** /**
* Detects if HTML contains custom patterns that indicate it was written in the HTML editor * 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. * 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 { private static detectCustomHtmlPatterns(html: string): boolean {
if (!html || html.trim() === '') return false; if (!html || html.trim() === '') return false;
const hasInlineStyles = /<[^>]+style\s*=\s*["'][^"']*["']/i.test(html);
const classMatches = html.matchAll(/class\s*=\s*["']([^"']*)["']/gi); const classMatches = html.matchAll(/class\s*=\s*["']([^"']*)["']/gi);
let hasCustomClasses = false; let hasCustomClasses = false;
for (const match of classMatches) { for (const match of classMatches) {
@@ -683,21 +679,21 @@ export class EmailService {
} }
} }
// Element-attribute-scoped regex; the leading [\s"'] guard prevents `id=` inside const hasCustomAttributes = /<[^>]+(?:data-|aria-|role=|id=)/i.test(html);
// href URLs (e.g. `?id=...`) from false-matching as an HTML id attribute. const hasComplexTables = /<table[^>]*>[\s\S]*?<table/i.test(html);
const hasCustomAttributes = /<[a-z][^>]*?[\s"'](?:data-|aria-|role=|id=)/i.test(html); const hasCustomElements = /<(?:div|span|section|article|header|footer|nav|aside)[^>]*>/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 hasMediaQueries = /@media/i.test(html);
const hasStyleTags = /<style[^>]*>/i.test(html); const hasStyleTags = /<style[^>]*>/i.test(html);
return hasCustomClasses || hasCustomAttributes || hasCustomElements || hasMediaQueries || hasStyleTags; return (
hasInlineStyles ||
hasCustomClasses ||
hasCustomAttributes ||
hasComplexTables ||
hasCustomElements ||
hasMediaQueries ||
hasStyleTags
);
} }
/** /**
@@ -1137,7 +1133,7 @@ export class EmailService {
* Queue an email for sending * Queue an email for sending
* Adds email to the BullMQ queue for processing by workers * Adds email to the BullMQ queue for processing by workers
*/ */
private static async queueEmail(emailId: string, sourceType: EmailSourceType, delay?: number): Promise<void> { private static async queueEmail(emailId: string, delay?: number): Promise<void> {
await QueueService.queueEmail(emailId, sourceType, delay); await QueueService.queueEmail(emailId, delay);
} }
} }
+5 -28
View File
@@ -1,4 +1,4 @@
import {CampaignStatus, EmailSourceType, EmailStatus} from '@plunk/db'; import {CampaignStatus, EmailStatus} from '@plunk/db';
import {type Job, Queue} from 'bullmq'; import {type Job, Queue} from 'bullmq';
import type {RedisOptions} from 'ioredis'; import type {RedisOptions} from 'ioredis';
import signale from 'signale'; import signale from 'signale';
@@ -174,43 +174,20 @@ export const meterQueue = new Queue<MeterEventJobData>('meter', {
}, },
}); });
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 * Queue Service - Centralized queue management
*/ */
export class QueueService { 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( public static async queueEmail(emailId: string, delay?: number): Promise<Job<SendEmailJobData>> {
emailId: string,
sourceType: EmailSourceType,
delay?: number,
): Promise<Job<SendEmailJobData>> {
return emailQueue.add( return emailQueue.add(
'send-email', 'send-email',
{emailId}, {emailId},
{ {
delay, delay, // Optional delay in milliseconds
jobId: `email-${emailId}`, jobId: `email-${emailId}`, // Prevent duplicate jobs
priority: emailPriorityFor(sourceType),
}, },
); );
} }
+2 -6
View File
@@ -6,7 +6,6 @@ import {
AWS_SES_REGION, AWS_SES_REGION,
AWS_SES_SECRET_ACCESS_KEY, AWS_SES_SECRET_ACCESS_KEY,
DASHBOARD_URI, DASHBOARD_URI,
MAIL_FROM_SUBDOMAIN,
SES_CONFIGURATION_SET, SES_CONFIGURATION_SET,
SES_CONFIGURATION_SET_NO_TRACKING, SES_CONFIGURATION_SET_NO_TRACKING,
TRACKING_TOGGLE_ENABLED, TRACKING_TOGGLE_ENABLED,
@@ -251,13 +250,10 @@ export const verifyDomain = async (domain: string): Promise<string[]> => {
// Verify DKIM for the domain // Verify DKIM for the domain
const DKIM = await ses.verifyDomainDkim({Domain: domain}); const DKIM = await ses.verifyDomainDkim({Domain: domain});
// Set custom MAIL FROM domain. The subdomain defaults to `plunk` and can be // Set custom MAIL FROM domain (plunk.yourdomain.com)
// 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({ await ses.setIdentityMailFromDomain({
Identity: domain, Identity: domain,
MailFromDomain: `${MAIL_FROM_SUBDOMAIN}.${domain}`, MailFromDomain: `plunk.${domain}`,
}); });
return DKIM.DkimTokens ?? []; return DKIM.DkimTokens ?? [];
+93 -91
View File
@@ -50,13 +50,22 @@ const SECURITY_THRESHOLDS = {
MIN_COMPLAINTS_FOR_CRITICAL: 5, MIN_COMPLAINTS_FOR_CRITICAL: 5,
MIN_COMPLAINTS_FOR_WARNING: 3, MIN_COMPLAINTS_FOR_WARNING: 3,
// === Absolute count ceilings (new projects only) === // === Absolute count ceilings ===
// These trigger regardless of rate — catches new accounts blasting emails // These trigger regardless of rate — catches high-volume spammers who dilute their bounce rate
// before their bounce rate has caught up. Established projects rely on // 24-hour absolute ceilings
// rate-based checks only, since high absolute counts at high volume BOUNCE_24H_CEILING_WARNING: 50,
// (e.g. 100 bounces out of 10K) don't indicate abuse. BOUNCE_24H_CEILING_CRITICAL: 100,
// COMPLAINT_24H_CEILING_WARNING: 10,
// Legitimate senders ramp up gradually; spammers blast immediately. COMPLAINT_24H_CEILING_CRITICAL: 25,
// 7-day absolute ceilings
BOUNCE_7DAY_CEILING_WARNING: 200,
BOUNCE_7DAY_CEILING_CRITICAL: 500,
COMPLAINT_7DAY_CEILING_WARNING: 30,
COMPLAINT_7DAY_CEILING_CRITICAL: 75,
// === New project thresholds (projects < 30 days old) ===
// Legitimate senders ramp up gradually; spammers blast immediately
NEW_PROJECT_AGE_DAYS: 30, NEW_PROJECT_AGE_DAYS: 30,
NEW_PROJECT_BOUNCE_24H_CEILING_WARNING: 10, NEW_PROJECT_BOUNCE_24H_CEILING_WARNING: 10,
NEW_PROJECT_BOUNCE_24H_CEILING_CRITICAL: 25, NEW_PROJECT_BOUNCE_24H_CEILING_CRITICAL: 25,
@@ -507,54 +516,82 @@ export class SecurityService {
const violations: string[] = []; const violations: string[] = [];
const warnings: string[] = []; const warnings: string[] = [];
// === Absolute count ceiling checks (new projects only, rate-independent) === // Pick absolute count ceilings based on project age
// Catches new accounts blasting emails before their bounce rate catches up. const bounceCeilings = isNewProject
// 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. ceiling24hWarning: SECURITY_THRESHOLDS.NEW_PROJECT_BOUNCE_24H_CEILING_WARNING,
if (isNewProject) { ceiling24hCritical: SECURITY_THRESHOLDS.NEW_PROJECT_BOUNCE_24H_CEILING_CRITICAL,
// 24-hour bounce ceilings ceiling7dWarning: SECURITY_THRESHOLDS.NEW_PROJECT_BOUNCE_7DAY_CEILING_WARNING,
if (twentyFourHour.bounces >= SECURITY_THRESHOLDS.NEW_PROJECT_BOUNCE_24H_CEILING_CRITICAL) { ceiling7dCritical: SECURITY_THRESHOLDS.NEW_PROJECT_BOUNCE_7DAY_CEILING_CRITICAL,
violations.push( }
`24-hour bounce count (new project) (${twentyFourHour.bounces} bounces) exceeds critical ceiling (${SECURITY_THRESHOLDS.NEW_PROJECT_BOUNCE_24H_CEILING_CRITICAL})`, : {
); ceiling24hWarning: SECURITY_THRESHOLDS.BOUNCE_24H_CEILING_WARNING,
} else if (twentyFourHour.bounces >= SECURITY_THRESHOLDS.NEW_PROJECT_BOUNCE_24H_CEILING_WARNING) { ceiling24hCritical: SECURITY_THRESHOLDS.BOUNCE_24H_CEILING_CRITICAL,
warnings.push( ceiling7dWarning: SECURITY_THRESHOLDS.BOUNCE_7DAY_CEILING_WARNING,
`24-hour bounce count (new project) (${twentyFourHour.bounces} bounces) exceeds warning ceiling (${SECURITY_THRESHOLDS.NEW_PROJECT_BOUNCE_24H_CEILING_WARNING})`, ceiling7dCritical: SECURITY_THRESHOLDS.BOUNCE_7DAY_CEILING_CRITICAL,
); };
}
// 7-day bounce ceilings const complaintCeilings = isNewProject
if (sevenDay.bounces >= SECURITY_THRESHOLDS.NEW_PROJECT_BOUNCE_7DAY_CEILING_CRITICAL) { ? {
violations.push( ceiling24hWarning: SECURITY_THRESHOLDS.NEW_PROJECT_COMPLAINT_24H_CEILING_WARNING,
`7-day bounce count (new project) (${sevenDay.bounces} bounces) exceeds critical ceiling (${SECURITY_THRESHOLDS.NEW_PROJECT_BOUNCE_7DAY_CEILING_CRITICAL})`, ceiling24hCritical: SECURITY_THRESHOLDS.NEW_PROJECT_COMPLAINT_24H_CEILING_CRITICAL,
); ceiling7dWarning: SECURITY_THRESHOLDS.NEW_PROJECT_COMPLAINT_7DAY_CEILING_WARNING,
} else if (sevenDay.bounces >= SECURITY_THRESHOLDS.NEW_PROJECT_BOUNCE_7DAY_CEILING_WARNING) { ceiling7dCritical: SECURITY_THRESHOLDS.NEW_PROJECT_COMPLAINT_7DAY_CEILING_CRITICAL,
warnings.push( }
`7-day bounce count (new project) (${sevenDay.bounces} bounces) exceeds warning ceiling (${SECURITY_THRESHOLDS.NEW_PROJECT_BOUNCE_7DAY_CEILING_WARNING})`, : {
); ceiling24hWarning: SECURITY_THRESHOLDS.COMPLAINT_24H_CEILING_WARNING,
} ceiling24hCritical: SECURITY_THRESHOLDS.COMPLAINT_24H_CEILING_CRITICAL,
ceiling7dWarning: SECURITY_THRESHOLDS.COMPLAINT_7DAY_CEILING_WARNING,
ceiling7dCritical: SECURITY_THRESHOLDS.COMPLAINT_7DAY_CEILING_CRITICAL,
};
// 24-hour complaint ceilings const projectLabel = isNewProject ? ' (new project)' : '';
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 // === Absolute count ceiling checks (rate-independent) ===
if (sevenDay.complaints >= SECURITY_THRESHOLDS.NEW_PROJECT_COMPLAINT_7DAY_CEILING_CRITICAL) { // These catch high-volume spammers who dilute their bounce rate by blasting emails
violations.push(
`7-day complaint count (new project) (${sevenDay.complaints} complaints) exceeds critical ceiling (${SECURITY_THRESHOLDS.NEW_PROJECT_COMPLAINT_7DAY_CEILING_CRITICAL})`, // 24-hour bounce ceilings
); if (twentyFourHour.bounces >= bounceCeilings.ceiling24hCritical) {
} else if (sevenDay.complaints >= SECURITY_THRESHOLDS.NEW_PROJECT_COMPLAINT_7DAY_CEILING_WARNING) { violations.push(
warnings.push( `24-hour bounce count${projectLabel} (${twentyFourHour.bounces} bounces) exceeds critical ceiling (${bounceCeilings.ceiling24hCritical})`,
`7-day complaint count (new project) (${sevenDay.complaints} complaints) exceeds warning ceiling (${SECURITY_THRESHOLDS.NEW_PROJECT_COMPLAINT_7DAY_CEILING_WARNING})`, );
); } else if (twentyFourHour.bounces >= bounceCeilings.ceiling24hWarning) {
} warnings.push(
`24-hour bounce count${projectLabel} (${twentyFourHour.bounces} bounces) exceeds warning ceiling (${bounceCeilings.ceiling24hWarning})`,
);
}
// 7-day bounce ceilings
if (sevenDay.bounces >= bounceCeilings.ceiling7dCritical) {
violations.push(
`7-day bounce count${projectLabel} (${sevenDay.bounces} bounces) exceeds critical ceiling (${bounceCeilings.ceiling7dCritical})`,
);
} else if (sevenDay.bounces >= bounceCeilings.ceiling7dWarning) {
warnings.push(
`7-day bounce count${projectLabel} (${sevenDay.bounces} bounces) exceeds warning ceiling (${bounceCeilings.ceiling7dWarning})`,
);
}
// 24-hour complaint ceilings
if (twentyFourHour.complaints >= complaintCeilings.ceiling24hCritical) {
violations.push(
`24-hour complaint count${projectLabel} (${twentyFourHour.complaints} complaints) exceeds critical ceiling (${complaintCeilings.ceiling24hCritical})`,
);
} else if (twentyFourHour.complaints >= complaintCeilings.ceiling24hWarning) {
warnings.push(
`24-hour complaint count${projectLabel} (${twentyFourHour.complaints} complaints) exceeds warning ceiling (${complaintCeilings.ceiling24hWarning})`,
);
}
// 7-day complaint ceilings
if (sevenDay.complaints >= complaintCeilings.ceiling7dCritical) {
violations.push(
`7-day complaint count${projectLabel} (${sevenDay.complaints} complaints) exceeds critical ceiling (${complaintCeilings.ceiling7dCritical})`,
);
} else if (sevenDay.complaints >= complaintCeilings.ceiling7dWarning) {
warnings.push(
`7-day complaint count${projectLabel} (${sevenDay.complaints} complaints) exceeds warning ceiling (${complaintCeilings.ceiling7dWarning})`,
);
} }
// === Rate-based checks (existing logic) === // === Rate-based checks (existing logic) ===
@@ -676,7 +713,7 @@ export class SecurityService {
// Disable the project // Disable the project
await prisma.project.update({ await prisma.project.update({
where: {id: projectId}, where: {id: projectId},
data: {disabled: true, disabledReason: 'EMAIL_REPUTATION'}, data: {disabled: true},
}); });
// Log critical security event // Log critical security event
@@ -765,36 +802,7 @@ export class SecurityService {
const uniqueUrls = [...new Set(urlMatches.map(u => u.replace(/[.,;)]+$/, '')))].slice(0, 20); const uniqueUrls = [...new Set(urlMatches.map(u => u.replace(/[.,;)]+$/, '')))].slice(0, 20);
// Extract sender domain for context // Extract sender domain for context
const senderDomain = (fromEmail.split('@')[1] ?? fromEmail).toLowerCase(); const senderDomain = fromEmail.includes('@') ? fromEmail.split('@')[1] : fromEmail;
// 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 // Call OpenRouter API
const response = await fetch('https://openrouter.ai/api/v1/chat/completions', { const response = await fetch('https://openrouter.ai/api/v1/chat/completions', {
@@ -827,11 +835,7 @@ Criteria for phishing/dangerous content:
- Requests for sensitive personal information - Requests for sensitive personal information
IMPORTANT - Use sender and project context when evaluating: 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. - The sender project name and domain are provided. Links to the sender's own domain(s) are expected and NOT suspicious.
- 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. - 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. - 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. - Lack of recognizable brand does NOT make an email phishing — many legitimate businesses are not famous.
@@ -844,8 +848,6 @@ Set confidence to 100 only if you are absolutely certain it's phishing.`,
role: 'user', role: 'user',
content: `Sender project name: ${projectName} content: `Sender project name: ${projectName}
Sender domain: ${senderDomain} 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(', ')}` : ''} ${uniqueUrls.length > 0 ? `URLs found in email: ${uniqueUrls.join(', ')}` : ''}
Subject: ${subject} Subject: ${subject}
@@ -969,7 +971,7 @@ ${strippedBody.substring(0, 2000)}`,
// Disable the project // Disable the project
await prisma.project.update({ await prisma.project.update({
where: {id: projectId}, where: {id: projectId},
data: {disabled: true, disabledReason: 'PHISHING_DETECTED'}, data: {disabled: true},
}); });
const violation = `A policy violation was detected. Please contact support for more details.`; const violation = `A policy violation was detected. Please contact support for more details.`;
@@ -908,14 +908,7 @@ export class WorkflowExecutionService {
} }
/** /**
* WEBHOOK step - Call an external webhook. * 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( private static async executeWebhook(
_step: WorkflowStep, _step: WorkflowStep,
@@ -931,37 +924,9 @@ export class WorkflowExecutionService {
contact.data && typeof contact.data === 'object' && !Array.isArray(contact.data) contact.data && typeof contact.data === 'object' && !Array.isArray(contact.data)
? (contact.data as Record<string, unknown>) ? (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 context = execution.context || {};
// Render scope: SEND_EMAIL's scope (id, email, contact data, execution const payload = body || {
// 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: { contact: {
email: contact.email, email: contact.email,
subscribed: contact.subscribed, subscribed: contact.subscribed,
@@ -979,11 +944,11 @@ export class WorkflowExecutionService {
}; };
// Make HTTP request // Make HTTP request
const response = await WorkflowExecutionService.safeFetch(renderedUrl, { const response = await WorkflowExecutionService.safeFetch(url, {
method, method,
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
...renderedHeaders, ...headers,
}, },
body: method !== 'GET' ? JSON.stringify(payload) : undefined, body: method !== 'GET' ? JSON.stringify(payload) : undefined,
}); });
@@ -997,7 +962,7 @@ export class WorkflowExecutionService {
} }
return { return {
url: renderedUrl, url,
method, method,
statusCode: response.status, statusCode: response.status,
success: response.ok, success: response.ok,
@@ -1005,28 +970,6 @@ 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 * UPDATE_CONTACT step - Update contact data
*/ */
@@ -50,20 +50,27 @@ describe('SecurityService', () => {
const complainedCount = opts?.complainedCount ?? 0; const complainedCount = opts?.complainedCount ?? 0;
const createdAt = opts?.createdAt ?? new Date(); const createdAt = opts?.createdAt ?? new Date();
const data = Array.from({length: count}, (_, i) => ({ const emails = [];
projectId, for (let i = 0; i < count; i++) {
contactId, emails.push(
subject: `Test ${i}`, prisma.email.create({
body: '<p>test</p>', data: {
from: '[email protected]', projectId,
status: EmailStatus.SENT, contactId,
sourceType: EmailSourceType.TRANSACTIONAL, subject: `Test ${i}`,
sentAt: createdAt, body: '<p>test</p>',
createdAt, from: '[email protected]',
bouncedAt: i < bouncedCount ? createdAt : null, status: EmailStatus.SENT,
complainedAt: i >= bouncedCount && i < bouncedCount + complainedCount ? createdAt : null, sourceType: EmailSourceType.TRANSACTIONAL,
})); sentAt: createdAt,
await prisma.email.createMany({data}); createdAt,
bouncedAt: i < bouncedCount ? createdAt : null,
complainedAt: i >= bouncedCount && i < bouncedCount + complainedCount ? createdAt : null,
},
}),
);
}
await Promise.all(emails);
} }
describe('Rate-based checks (existing behavior)', () => { describe('Rate-based checks (existing behavior)', () => {
@@ -102,12 +109,14 @@ describe('SecurityService', () => {
await createEmails(50, {bouncedCount: 10}); await createEmails(50, {bouncedCount: 10});
const status = await SecurityService.getSecurityStatus(projectId); const status = await SecurityService.getSecurityStatus(projectId);
// Rate-based check doesn't trigger, but absolute count ceiling might
// With 10 bounces in 24h, this is below the 50-bounce ceiling for established projects
expect(status.violations).toHaveLength(0); expect(status.violations).toHaveLength(0);
}); });
}); });
describe('Established projects skip absolute ceilings', () => { describe('Absolute count ceilings (established projects)', () => {
// Age the project past the new-project window // Age the project past the new-project window so standard ceilings apply
beforeEach(async () => { beforeEach(async () => {
const oldDate = new Date(Date.now() - 31 * 24 * 60 * 60 * 1000); const oldDate = new Date(Date.now() - 31 * 24 * 60 * 60 * 1000);
await prisma.project.update({ await prisma.project.update({
@@ -116,27 +125,45 @@ describe('SecurityService', () => {
}); });
}); });
it('should NOT trigger on high absolute bounce count when rate is healthy', async () => { it('should trigger critical when 24-hour bounce count exceeds ceiling', async () => {
// 20,000 emails, 200 bounces = 1% rate (well below rate threshold) // 20,000 emails, 101 bounces = 0.5% rate (well below rate threshold)
// Established projects rely solely on rates — high absolute counts at // But 101 bounces > 100 (24h critical ceiling for established projects)
// high volume don't indicate abuse. await createEmails(20000, {bouncedCount: 101});
await createEmails(20000, {bouncedCount: 200});
const status = await SecurityService.getSecurityStatus(projectId);
expect(status.shouldDisable).toBe(true);
expect(status.violations.some(v => v.includes('24-hour bounce count'))).toBe(true);
});
it('should trigger warning when 24-hour bounce count exceeds warning ceiling', async () => {
// 10,000 emails, 51 bounces = 0.51% (below rate threshold)
// But 51 > 50 (24h warning ceiling), below 100 critical
await createEmails(10000, {bouncedCount: 51});
const status = await SecurityService.getSecurityStatus(projectId);
expect(status.isHealthy).toBe(true); // warnings don't make it unhealthy
expect(status.warnings.some(w => w.includes('24-hour bounce count'))).toBe(true);
});
it('should trigger critical when 24-hour complaint count exceeds ceiling', async () => {
// 20,000 emails, 26 complaints = 0.13% (below complaint rate critical of 0.15%)
// But 26 > 25 (24h complaint critical ceiling)
await createEmails(20000, {complainedCount: 26});
const status = await SecurityService.getSecurityStatus(projectId);
expect(status.shouldDisable).toBe(true);
expect(status.violations.some(v => v.includes('24-hour complaint count'))).toBe(true);
});
it('should NOT trigger ceiling when bounce count is below ceiling', async () => {
// 20,000 emails, 40 bounces = below 50 warning ceiling for established projects
await createEmails(20000, {bouncedCount: 40});
const status = await SecurityService.getSecurityStatus(projectId); const status = await SecurityService.getSecurityStatus(projectId);
expect(status.isHealthy).toBe(true); expect(status.isHealthy).toBe(true);
expect(status.shouldDisable).toBe(false);
expect(status.violations).toHaveLength(0); expect(status.violations).toHaveLength(0);
expect(status.warnings).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', () => { describe('New project stricter thresholds', () => {
@@ -151,7 +178,7 @@ describe('SecurityService', () => {
expect(status.violations.some(v => v.includes('new project'))).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 () => { it('should apply standard ceilings for projects over 30 days old', async () => {
// Age the project to 31 days // Age the project to 31 days
const oldDate = new Date(Date.now() - 31 * 24 * 60 * 60 * 1000); const oldDate = new Date(Date.now() - 31 * 24 * 60 * 60 * 1000);
await prisma.project.update({ await prisma.project.update({
@@ -159,14 +186,15 @@ describe('SecurityService', () => {
data: {createdAt: oldDate}, data: {createdAt: oldDate},
}); });
// 10,000 emails, 26 bounces — would trip new-project ceiling, but // 10,000 emails, 26 bounces (above 25 new project ceiling, below 50 standard warning ceiling)
// established projects skip ceilings entirely (rate is 0.26%, healthy).
await createEmails(10000, {bouncedCount: 26}); await createEmails(10000, {bouncedCount: 26});
const status = await SecurityService.getSecurityStatus(projectId); const status = await SecurityService.getSecurityStatus(projectId);
expect(status.isNewProject).toBe(false); expect(status.isNewProject).toBe(false);
expect(status.warnings.some(w => w.includes('bounce count'))).toBe(false); // 26 is below the 50-bounce 24h warning ceiling for established projects
expect(status.violations.some(v => v.includes('bounce count'))).toBe(false); expect(status.warnings.some(w => w.includes('24-hour bounce count'))).toBe(false);
// And below the 100-bounce 24h critical ceiling
expect(status.violations.some(v => v.includes('24-hour bounce count'))).toBe(false);
}); });
it('should catch new project blasting emails with delayed bounces', async () => { it('should catch new project blasting emails with delayed bounces', async () => {
@@ -184,8 +212,8 @@ describe('SecurityService', () => {
describe('checkAndEnforceSecurityLimits', () => { describe('checkAndEnforceSecurityLimits', () => {
it('should disable project when critical thresholds are exceeded', async () => { it('should disable project when critical thresholds are exceeded', async () => {
// New project, 20K emails with 30 bounces — exceeds new project 24h critical ceiling // Create enough bounces to trigger critical
await createEmails(20000, {bouncedCount: 30}); await createEmails(20000, {bouncedCount: 101});
await SecurityService.checkAndEnforceSecurityLimits(projectId); await SecurityService.checkAndEnforceSecurityLimits(projectId);
@@ -197,13 +225,13 @@ describe('SecurityService', () => {
}); });
it('should NOT disable project when only warnings exist', async () => { it('should NOT disable project when only warnings exist', async () => {
// Established project, 200 emails, 12 bounces = 6% (above 5% warning, below 10% critical) // 10,000 emails, 51 bounces (above warning but below critical for established project)
const oldDate = new Date(Date.now() - 31 * 24 * 60 * 60 * 1000); const oldDate = new Date(Date.now() - 31 * 24 * 60 * 60 * 1000);
await prisma.project.update({ await prisma.project.update({
where: {id: projectId}, where: {id: projectId},
data: {createdAt: oldDate}, data: {createdAt: oldDate},
}); });
await createEmails(200, {bouncedCount: 12}); await createEmails(10000, {bouncedCount: 51});
await SecurityService.checkAndEnforceSecurityLimits(projectId); await SecurityService.checkAndEnforceSecurityLimits(projectId);
@@ -1,229 +0,0 @@
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');
});
});
+1 -1
View File
@@ -27,7 +27,7 @@
"@tiptap/starter-kit": "^3.11.0", "@tiptap/starter-kit": "^3.11.0",
"juice": "^11.0.3", "juice": "^11.0.3",
"lucide-react": "^0.553.0", "lucide-react": "^0.553.0",
"next": "^16.2.3", "next": "^16.2.6",
"next-seo": "^6.6.0", "next-seo": "^6.6.0",
"react": "19.2.3", "react": "19.2.3",
"react-dom": "19.2.3", "react-dom": "19.2.3",
-78
View File
@@ -1,78 +0,0 @@
# Plunk
> Plunk is an open-source, all-in-one email platform for developers. It unifies marketing, transactional, and broadcast email behind a single API — built to handle millions of contacts with workflows, segments, templates, and deliverability tooling out of the box.
Plunk can be used as a hosted service at useplunk.com or self-hosted via Docker. Source code lives at https://github.com/useplunk/plunk.
Pages listed below with a `.md` suffix serve a Markdown version (also available by requesting the same URL with `Accept: text/markdown`). Other pages are HTML only.
For full product documentation, see the docs site: https://docs.useplunk.com/llms.txt
## Product
- [Plunk home](https://www.useplunk.com/index.md): Product overview, features, and positioning
- [Pricing](https://www.useplunk.com/pricing.md): Plans, included volume, and overage pricing
- [Made by humans](https://www.useplunk.com/made-by-humans): The team and story behind Plunk
## Features
- [Email editor](https://www.useplunk.com/features/email-editor.md): Drag-and-drop and code-based template editor
- [Workflows](https://www.useplunk.com/features/workflows.md): Event- and segment-triggered automation flows
- [Segments](https://www.useplunk.com/features/segments.md): Dynamic and static contact segments
- [SMTP](https://www.useplunk.com/features/smtp.md): Send through Plunk over standard SMTP
- [Inbound email](https://www.useplunk.com/features/inbound-email.md): Receive email at your verified domain and turn it into events
## Comparisons
- [Plunk vs Resend](https://www.useplunk.com/vs/resend)
- [Plunk vs SendGrid](https://www.useplunk.com/vs/sendgrid)
- [Plunk vs Mailchimp](https://www.useplunk.com/vs/mailchimp)
- [Plunk vs Mailgun](https://www.useplunk.com/vs/mailgun)
- [Plunk vs Postmark](https://www.useplunk.com/vs/postmark)
- [Plunk vs Customer.io](https://www.useplunk.com/vs/customerio)
- [Plunk vs Loops](https://www.useplunk.com/vs/loops)
- [Plunk vs Brevo](https://www.useplunk.com/vs/brevo)
- [Plunk vs ActiveCampaign](https://www.useplunk.com/vs/activecampaign)
- [Plunk vs Klaviyo](https://www.useplunk.com/vs/klaviyo)
- [Plunk vs ConvertKit](https://www.useplunk.com/vs/convertkit)
- [Plunk vs Bento](https://www.useplunk.com/vs/bento)
- [Plunk vs MailerLite](https://www.useplunk.com/vs/mailerlite)
- [Plunk vs Amazon SES](https://www.useplunk.com/vs/amazon-ses)
- [Plunk vs Mailjet](https://www.useplunk.com/vs/mailjet)
- [Plunk vs Buttondown](https://www.useplunk.com/vs/buttondown)
- [All comparisons](https://www.useplunk.com/vs)
## Guides
- [Email API guide](https://www.useplunk.com/guides/email-api-guide): Choosing and integrating with an email API
- [Email deliverability](https://www.useplunk.com/guides/email-deliverability): Reaching the inbox reliably
- [Email bounce rate](https://www.useplunk.com/guides/email-bounce-rate): What it is and how to reduce it
- [Email open rate](https://www.useplunk.com/guides/email-open-rate): Benchmarks and improvement tactics
- [Email click-through rate](https://www.useplunk.com/guides/email-click-through-rate): Measuring and improving CTR
- [Email sender reputation](https://www.useplunk.com/guides/email-sender-reputation): Protecting your sending reputation
- [Email marketing best practices](https://www.useplunk.com/guides/email-marketing-best-practices)
- [Transactional vs marketing email](https://www.useplunk.com/guides/transactional-vs-marketing-email)
- [What is SPF](https://www.useplunk.com/guides/what-is-spf)
- [What is DKIM](https://www.useplunk.com/guides/what-is-dkim)
- [What is DMARC](https://www.useplunk.com/guides/what-is-dmarc)
- [All guides](https://www.useplunk.com/guides)
## Tools
- [Verify email](https://www.useplunk.com/tools/verify-email): Check a single email address for validity
- [Spam checker](https://www.useplunk.com/tools/spam-checker): Score an email for spam triggers
- [Markdown to email](https://www.useplunk.com/tools/markdown-to-email): Convert Markdown into HTML email
- [SPF checker](https://www.useplunk.com/tools/spf-checker)
- [DKIM checker](https://www.useplunk.com/tools/dkim-checker)
- [DMARC checker](https://www.useplunk.com/tools/dmarc-checker)
- [MX checker](https://www.useplunk.com/tools/mx-checker)
- [Email headers analyzer](https://www.useplunk.com/tools/email-headers)
- [All tools](https://www.useplunk.com/tools)
## Optional
- [Documentation](https://docs.useplunk.com): Product, API, and self-hosting docs
- [Discord community](https://www.useplunk.com/discord)
- [Privacy policy](https://www.useplunk.com/privacy)
- [Terms of service](https://www.useplunk.com/terms)
- [Data processing agreement](https://www.useplunk.com/dpa)
+1 -13
View File
@@ -1,6 +1,5 @@
import Image from 'next/image'; import Image from 'next/image';
import Link from 'next/link'; import Link from 'next/link';
import {useRouter} from 'next/router';
import {WIKI_URI} from '../../lib/constants'; import {WIKI_URI} from '../../lib/constants';
import logo from '../../../public/assets/logo.svg'; import logo from '../../../public/assets/logo.svg';
@@ -8,10 +7,6 @@ import logo from '../../../public/assets/logo.svg';
* *
*/ */
export default function Footer() { export default function Footer() {
const router = useRouter();
const path = (router.asPath || '/').split(/[?#]/)[0] ?? '/';
const trimmed = path === '/' ? '/' : path.replace(/\/$/, '');
const mdHref = `${trimmed}.md`;
return ( return (
<> <>
<footer className={'border-t border-neutral-200 bg-white'}> <footer className={'border-t border-neutral-200 bg-white'}>
@@ -268,15 +263,8 @@ export default function Footer() {
</div> </div>
</div> </div>
<div className="mt-16 flex flex-col gap-2 border-t border-neutral-200 pt-8 sm:flex-row sm:items-center sm:justify-between"> <div className="mt-16 border-t border-neutral-200 pt-8">
<p className="text-sm text-neutral-500">&copy; {new Date().getFullYear()} Plunk. All rights reserved.</p> <p className="text-sm text-neutral-500">&copy; {new Date().getFullYear()} Plunk. All rights reserved.</p>
<p style={{fontFamily: 'var(--font-mono)'}} className="text-[11px] text-neutral-400">
Reading this with electronic eyes? Append{' '}
<a href={mdHref} className="text-neutral-500 underline decoration-dotted underline-offset-2 transition hover:text-neutral-900">
<code>.md</code>
</a>{' '}
to any URL for the Markdown cut.
</p>
</div> </div>
</div> </div>
</footer> </footer>
-114
View File
@@ -1,114 +0,0 @@
import {AnimatePresence, motion} from 'framer-motion';
import React, {useEffect, useState} from 'react';
import {ArrowRight, Gift, X} from 'lucide-react';
import {DASHBOARD_URI} from '../lib/constants';
interface SwitchOfferProps {
competitorName: string;
}
export function SwitchOffer({competitorName}: SwitchOfferProps) {
const storageKey = `switch-offer-dismissed:${competitorName}`;
const [visible, setVisible] = useState(false);
useEffect(() => {
if (typeof window === 'undefined') return;
if (window.localStorage.getItem(storageKey) === '1') return;
const t = window.setTimeout(() => setVisible(true), 800);
return () => window.clearTimeout(t);
}, [storageKey]);
const dismiss = () => {
setVisible(false);
if (typeof window !== 'undefined') {
window.localStorage.setItem(storageKey, '1');
}
};
return (
<AnimatePresence>
{visible && (
<motion.div
initial={{opacity: 0, y: 24, scale: 0.96}}
animate={{opacity: 1, y: 0, scale: 1}}
exit={{opacity: 0, y: 16, scale: 0.97}}
transition={{duration: 0.45, ease: [0.22, 1, 0.36, 1]}}
className={
'pointer-events-auto fixed bottom-4 right-4 z-50 w-[calc(100vw-2rem)] max-w-sm sm:bottom-6 sm:right-6'
}
role="dialog"
aria-label={`Switch from ${competitorName} to Plunk offer`}
>
<div
className={
'relative overflow-hidden rounded-2xl border border-neutral-900 bg-white shadow-[0_24px_60px_-20px_rgba(0,0,0,0.35)]'
}
>
<button
type="button"
onClick={dismiss}
aria-label="Dismiss offer"
className={
'absolute right-2.5 top-2.5 inline-flex h-7 w-7 items-center justify-center rounded-full text-neutral-500 transition hover:bg-neutral-100 hover:text-neutral-900'
}
>
<X className="h-3.5 w-3.5" />
</button>
<div className={'p-5 pr-10 sm:p-6 sm:pr-12'}>
<div
className={
'inline-flex items-center gap-1.5 rounded-full border border-neutral-200 bg-neutral-50 px-2 py-1'
}
>
<Gift className="h-3 w-3 text-neutral-700" />
<span
style={{fontFamily: 'var(--font-mono)'}}
className={'text-[10px] uppercase tracking-[0.18em] text-neutral-600'}
>
Switching offer
</span>
</div>
<h3
style={{fontFamily: 'var(--font-display)'}}
className={'mt-3 text-lg font-bold leading-[1.15] tracking-[-0.02em] text-neutral-900'}
>
Switching from {competitorName}?
<br />
<span className={'text-neutral-500'}>Get 2,000 free emails.</span>
</h3>
<p className={'mt-3 text-xs leading-relaxed text-neutral-600'}>
Sign up and enter this code at checkout to redeem 2,000 email credits.
</p>
<div className={'mt-3 rounded-xl border border-dashed border-neutral-300 bg-neutral-50 px-3 py-2.5'}>
<div className={'mt-1 flex items-baseline justify-between gap-2'}>
<span
style={{fontFamily: 'var(--font-mono)'}}
className={'text-base font-bold tracking-[0.08em] text-neutral-900'}
>
SWITCH
</span>
</div>
</div>
<motion.a
whileHover={{scale: 1.015}}
whileTap={{scale: 0.985}}
href={`${DASHBOARD_URI}/auth/signup`}
className={
'group mt-4 inline-flex w-full items-center justify-center gap-1.5 rounded-full bg-neutral-900 px-4 py-2.5 text-xs font-semibold text-white transition hover:bg-neutral-800'
}
>
Claim your credits
<ArrowRight className="h-3.5 w-3.5 transition-transform group-hover:translate-x-0.5" />
</motion.a>
</div>
</div>
</motion.div>
)}
</AnimatePresence>
);
}
-1
View File
@@ -4,4 +4,3 @@ export * from './ComparisonTable';
export * from './FAQSection'; export * from './FAQSection';
export * from './CodeBlock'; export * from './CodeBlock';
export * from './SectionHeader'; export * from './SectionHeader';
export * from './SwitchOffer';
@@ -1,14 +0,0 @@
export const MARKDOWN_SLUGS: ReadonlySet<string> = new Set([
'index',
'pricing',
'features/workflows',
'features/segments',
'features/inbound-email',
'features/email-editor',
'features/smtp',
]);
export function hasMarkdownVariant(pathname: string): boolean {
const slug = pathname.replace(/^\/+|\/+$/g, '') || 'index';
return MARKDOWN_SLUGS.has(slug);
}
-2
View File
@@ -341,5 +341,3 @@ Plunk provides SMTP credentials so you can send emails from any application or f
[Back to features](/features) | [Pricing](/pricing) | [Documentation](https://docs.useplunk.com) [Back to features](/features) | [Pricing](/pricing) | [Documentation](https://docs.useplunk.com)
`, `,
}; };
export {MARKDOWN_SLUGS, hasMarkdownVariant} from './markdown-slugs';
+1 -6
View File
@@ -1,8 +1,6 @@
import { NextResponse } from 'next/server'; import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server'; import type { NextRequest } from 'next/server';
import { hasMarkdownVariant } from './content/markdown-slugs';
type Negotiated = 'markdown' | 'html' | 'none'; type Negotiated = 'markdown' | 'html' | 'none';
function parseAccept(accept: string): Array<{ type: string; q: number }> { function parseAccept(accept: string): Array<{ type: string; q: number }> {
@@ -28,7 +26,7 @@ function getQ(types: Array<{ type: string; q: number }>, target: string): number
function negotiate(accept: string): Negotiated { function negotiate(accept: string): Negotiated {
if (!accept) return 'html'; if (!accept) return 'html';
const types = parseAccept(accept); const types = parseAccept(accept);
const mdQ = types.find(t => t.type === 'text/markdown')?.q ?? -1; const mdQ = getQ(types, 'text/markdown');
const htmlQ = getQ(types, 'text/html'); const htmlQ = getQ(types, 'text/html');
if (mdQ <= 0 && htmlQ <= 0) return 'none'; if (mdQ <= 0 && htmlQ <= 0) return 'none';
if (mdQ > 0 && mdQ >= htmlQ) return 'markdown'; if (mdQ > 0 && mdQ >= htmlQ) return 'markdown';
@@ -61,9 +59,6 @@ export function middleware(request: NextRequest) {
const response = NextResponse.next(); const response = NextResponse.next();
response.headers.set('Vary', 'Accept'); response.headers.set('Vary', 'Accept');
if (hasMarkdownVariant(pathname)) {
response.headers.append('Link', `<${pathname}.md>; rel="alternate"; type="text/markdown"`);
}
return response; return response;
} }
-7
View File
@@ -2,11 +2,9 @@ import '../styles/globals.css';
import React, {useEffect} from 'react'; import React, {useEffect} from 'react';
import Head from 'next/head'; import Head from 'next/head';
import {AppProps} from 'next/app'; import {AppProps} from 'next/app';
import {useRouter} from 'next/router';
import {toast, Toaster} from 'sonner'; import {toast, Toaster} from 'sonner';
import {SWRConfig} from 'swr'; import {SWRConfig} from 'swr';
import {network} from '../lib/network'; import {network} from '../lib/network';
import {hasMarkdownVariant} from '../content/markdown-slugs';
import {DefaultSeo} from 'next-seo'; import {DefaultSeo} from 'next-seo';
import Script from 'next/script'; import Script from 'next/script';
import {Bricolage_Grotesque, Hanken_Grotesk, JetBrains_Mono} from 'next/font/google'; import {Bricolage_Grotesque, Hanken_Grotesk, JetBrains_Mono} from 'next/font/google';
@@ -39,10 +37,6 @@ const mono = JetBrains_Mono({
* @param props.pageProps * @param props.pageProps
*/ */
function App({Component, pageProps}: AppProps) { function App({Component, pageProps}: AppProps) {
const router = useRouter();
const pathname = (router.asPath.split('?')[0] ?? '').split('#')[0] ?? '/';
const markdownHref = hasMarkdownVariant(pathname) ? `${pathname === '/' ? '/index' : pathname}.md` : null;
useEffect(() => { useEffect(() => {
const searchParams = new URLSearchParams(window.location.search); const searchParams = new URLSearchParams(window.location.search);
const message = searchParams.get('message'); const message = searchParams.get('message');
@@ -57,7 +51,6 @@ function App({Component, pageProps}: AppProps) {
<Head> <Head>
<title>Plunk | The Open-Source Email Platform</title> <title>Plunk | The Open-Source Email Platform</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" key={'viewport'} /> <meta name="viewport" content="width=device-width, initial-scale=1.0" key={'viewport'} />
{markdownHref && <link rel="alternate" type="text/markdown" href={markdownHref} />}
</Head> </Head>
<Toaster position={'top-right'} /> <Toaster position={'top-right'} />
-1
View File
@@ -725,7 +725,6 @@ export default function Index() {
viewport={{once: true}} viewport={{once: true}}
transition={{duration: 0.8, delay: 0.9, ease: [0.22, 1, 0.36, 1]}} transition={{duration: 0.8, delay: 0.9, ease: [0.22, 1, 0.36, 1]}}
className={'mx-auto max-w-xl'} className={'mx-auto max-w-xl'}
data-nosnippet
> >
<div className={'overflow-hidden rounded-[20px] border border-neutral-200 bg-white'}> <div className={'overflow-hidden rounded-[20px] border border-neutral-200 bg-white'}>
<div className={'flex items-center gap-5 p-6'}> <div className={'flex items-center gap-5 p-6'}>
+1 -3
View File
@@ -1,4 +1,4 @@
import {ComparisonTable, FAQSection, Footer, Navbar, SwitchOffer} from '../../components'; import {ComparisonTable, FAQSection, Footer, Navbar} from '../../components';
import {motion} from 'framer-motion'; import {motion} from 'framer-motion';
import {DASHBOARD_URI, WIKI_URI} from '../../lib/constants'; import {DASHBOARD_URI, WIKI_URI} from '../../lib/constants';
import React from 'react'; import React from 'react';
@@ -170,8 +170,6 @@ export default function ActiveCampaignComparison() {
{/* FAQ */} {/* FAQ */}
<FAQSection faqs={faqs} schemaId="faq-schema-activecampaign" /> <FAQSection faqs={faqs} schemaId="faq-schema-activecampaign" />
<SwitchOffer competitorName="ActiveCampaign" />
{/* CTA */} {/* CTA */}
<section className={'relative overflow-hidden border-t border-neutral-900 bg-neutral-900 text-white'}> <section className={'relative overflow-hidden border-t border-neutral-900 bg-neutral-900 text-white'}>
<div className={'mx-auto max-w-[88rem] px-6 py-24 sm:px-10 sm:py-32'}> <div className={'mx-auto max-w-[88rem] px-6 py-24 sm:px-10 sm:py-32'}>
+1 -3
View File
@@ -1,4 +1,4 @@
import {ComparisonTable, FAQSection, Footer, Navbar, SwitchOffer} from '../../components'; import {ComparisonTable, FAQSection, Footer, Navbar} from '../../components';
import {motion} from 'framer-motion'; import {motion} from 'framer-motion';
import {DASHBOARD_URI, WIKI_URI} from '../../lib/constants'; import {DASHBOARD_URI, WIKI_URI} from '../../lib/constants';
import React from 'react'; import React from 'react';
@@ -186,8 +186,6 @@ export default function AmazonSesComparison() {
{/* FAQ */} {/* FAQ */}
<FAQSection faqs={faqs} schemaId="faq-schema-amazon-ses" /> <FAQSection faqs={faqs} schemaId="faq-schema-amazon-ses" />
<SwitchOffer competitorName="Amazon SES" />
{/* CTA */} {/* CTA */}
<section className={'relative overflow-hidden border-t border-neutral-900 bg-neutral-900 text-white'}> <section className={'relative overflow-hidden border-t border-neutral-900 bg-neutral-900 text-white'}>
<div className={'mx-auto max-w-[88rem] px-6 py-24 sm:px-10 sm:py-32'}> <div className={'mx-auto max-w-[88rem] px-6 py-24 sm:px-10 sm:py-32'}>
+1 -3
View File
@@ -1,4 +1,4 @@
import {ComparisonTable, FAQSection, Footer, Navbar, SwitchOffer} from '../../components'; import {ComparisonTable, FAQSection, Footer, Navbar} from '../../components';
import {motion} from 'framer-motion'; import {motion} from 'framer-motion';
import {DASHBOARD_URI, WIKI_URI} from '../../lib/constants'; import {DASHBOARD_URI, WIKI_URI} from '../../lib/constants';
import React from 'react'; import React from 'react';
@@ -169,8 +169,6 @@ export default function BentoComparison() {
{/* FAQ */} {/* FAQ */}
<FAQSection faqs={faqs} schemaId="faq-schema-bento" /> <FAQSection faqs={faqs} schemaId="faq-schema-bento" />
<SwitchOffer competitorName="Bento" />
{/* CTA */} {/* CTA */}
<section className={'relative overflow-hidden border-t border-neutral-900 bg-neutral-900 text-white'}> <section className={'relative overflow-hidden border-t border-neutral-900 bg-neutral-900 text-white'}>
<div className={'mx-auto max-w-[88rem] px-6 py-24 sm:px-10 sm:py-32'}> <div className={'mx-auto max-w-[88rem] px-6 py-24 sm:px-10 sm:py-32'}>
+1 -3
View File
@@ -1,4 +1,4 @@
import {ComparisonTable, FAQSection, Footer, Navbar, SwitchOffer} from '../../components'; import {ComparisonTable, FAQSection, Footer, Navbar} from '../../components';
import {motion} from 'framer-motion'; import {motion} from 'framer-motion';
import {DASHBOARD_URI, WIKI_URI} from '../../lib/constants'; import {DASHBOARD_URI, WIKI_URI} from '../../lib/constants';
import React from 'react'; import React from 'react';
@@ -193,8 +193,6 @@ export default function BrevoComparison() {
{/* FAQ */} {/* FAQ */}
<FAQSection faqs={faqs} schemaId="faq-schema-brevo" /> <FAQSection faqs={faqs} schemaId="faq-schema-brevo" />
<SwitchOffer competitorName="Brevo" />
{/* CTA */} {/* CTA */}
<section className={'relative overflow-hidden border-t border-neutral-900 bg-neutral-900 text-white'}> <section className={'relative overflow-hidden border-t border-neutral-900 bg-neutral-900 text-white'}>
<div className={'mx-auto max-w-[88rem] px-6 py-24 sm:px-10 sm:py-32'}> <div className={'mx-auto max-w-[88rem] px-6 py-24 sm:px-10 sm:py-32'}>
+1 -3
View File
@@ -1,4 +1,4 @@
import {ComparisonTable, FAQSection, Footer, Navbar, SwitchOffer} from '../../components'; import {ComparisonTable, FAQSection, Footer, Navbar} from '../../components';
import {motion} from 'framer-motion'; import {motion} from 'framer-motion';
import {DASHBOARD_URI, WIKI_URI} from '../../lib/constants'; import {DASHBOARD_URI, WIKI_URI} from '../../lib/constants';
import React from 'react'; import React from 'react';
@@ -186,8 +186,6 @@ export default function ButtondownComparison() {
{/* FAQ */} {/* FAQ */}
<FAQSection faqs={faqs} schemaId="faq-schema-buttondown" /> <FAQSection faqs={faqs} schemaId="faq-schema-buttondown" />
<SwitchOffer competitorName="Buttondown" />
{/* CTA */} {/* CTA */}
<section className={'relative overflow-hidden border-t border-neutral-900 bg-neutral-900 text-white'}> <section className={'relative overflow-hidden border-t border-neutral-900 bg-neutral-900 text-white'}>
<div className={'mx-auto max-w-[88rem] px-6 py-24 sm:px-10 sm:py-32'}> <div className={'mx-auto max-w-[88rem] px-6 py-24 sm:px-10 sm:py-32'}>
+1 -3
View File
@@ -1,4 +1,4 @@
import {ComparisonTable, FAQSection, Footer, Navbar, SwitchOffer} from '../../components'; import {ComparisonTable, FAQSection, Footer, Navbar} from '../../components';
import {motion} from 'framer-motion'; import {motion} from 'framer-motion';
import {DASHBOARD_URI, WIKI_URI} from '../../lib/constants'; import {DASHBOARD_URI, WIKI_URI} from '../../lib/constants';
import React from 'react'; import React from 'react';
@@ -193,8 +193,6 @@ export default function ConvertkitComparison() {
{/* FAQ */} {/* FAQ */}
<FAQSection faqs={faqs} schemaId="faq-schema-convertkit" /> <FAQSection faqs={faqs} schemaId="faq-schema-convertkit" />
<SwitchOffer competitorName="ConvertKit" />
{/* CTA */} {/* CTA */}
<section className={'relative overflow-hidden border-t border-neutral-900 bg-neutral-900 text-white'}> <section className={'relative overflow-hidden border-t border-neutral-900 bg-neutral-900 text-white'}>
<div className={'mx-auto max-w-[88rem] px-6 py-24 sm:px-10 sm:py-32'}> <div className={'mx-auto max-w-[88rem] px-6 py-24 sm:px-10 sm:py-32'}>
+1 -3
View File
@@ -1,4 +1,4 @@
import {ComparisonTable, FAQSection, Footer, Navbar, SwitchOffer} from '../../components'; import {ComparisonTable, FAQSection, Footer, Navbar} from '../../components';
import {motion} from 'framer-motion'; import {motion} from 'framer-motion';
import {DASHBOARD_URI, WIKI_URI} from '../../lib/constants'; import {DASHBOARD_URI, WIKI_URI} from '../../lib/constants';
import React from 'react'; import React from 'react';
@@ -189,8 +189,6 @@ export default function CustomerioComparison() {
{/* FAQ */} {/* FAQ */}
<FAQSection faqs={faqs} schemaId="faq-schema-customerio" /> <FAQSection faqs={faqs} schemaId="faq-schema-customerio" />
<SwitchOffer competitorName="Customer.io" />
{/* CTA */} {/* CTA */}
<section className={'relative overflow-hidden border-t border-neutral-900 bg-neutral-900 text-white'}> <section className={'relative overflow-hidden border-t border-neutral-900 bg-neutral-900 text-white'}>
<div className={'mx-auto max-w-[88rem] px-6 py-24 sm:px-10 sm:py-32'}> <div className={'mx-auto max-w-[88rem] px-6 py-24 sm:px-10 sm:py-32'}>
+1 -3
View File
@@ -1,4 +1,4 @@
import {ComparisonTable, FAQSection, Footer, Navbar, SwitchOffer} from '../../components'; import {ComparisonTable, FAQSection, Footer, Navbar} from '../../components';
import {motion} from 'framer-motion'; import {motion} from 'framer-motion';
import {DASHBOARD_URI, WIKI_URI} from '../../lib/constants'; import {DASHBOARD_URI, WIKI_URI} from '../../lib/constants';
import React from 'react'; import React from 'react';
@@ -170,8 +170,6 @@ export default function KlaviyoComparison() {
{/* FAQ */} {/* FAQ */}
<FAQSection faqs={faqs} schemaId="faq-schema-klaviyo" /> <FAQSection faqs={faqs} schemaId="faq-schema-klaviyo" />
<SwitchOffer competitorName="Klaviyo" />
{/* CTA */} {/* CTA */}
<section className={'relative overflow-hidden border-t border-neutral-900 bg-neutral-900 text-white'}> <section className={'relative overflow-hidden border-t border-neutral-900 bg-neutral-900 text-white'}>
<div className={'mx-auto max-w-[88rem] px-6 py-24 sm:px-10 sm:py-32'}> <div className={'mx-auto max-w-[88rem] px-6 py-24 sm:px-10 sm:py-32'}>
+1 -3
View File
@@ -1,4 +1,4 @@
import {ComparisonTable, FAQSection, Footer, Navbar, SwitchOffer} from '../../components'; import {ComparisonTable, FAQSection, Footer, Navbar} from '../../components';
import {motion} from 'framer-motion'; import {motion} from 'framer-motion';
import {DASHBOARD_URI, WIKI_URI} from '../../lib/constants'; import {DASHBOARD_URI, WIKI_URI} from '../../lib/constants';
import React from 'react'; import React from 'react';
@@ -193,8 +193,6 @@ export default function LoopsComparison() {
{/* FAQ */} {/* FAQ */}
<FAQSection faqs={faqs} schemaId="faq-schema-loops" /> <FAQSection faqs={faqs} schemaId="faq-schema-loops" />
<SwitchOffer competitorName="Loops" />
{/* CTA */} {/* CTA */}
<section className={'relative overflow-hidden border-t border-neutral-900 bg-neutral-900 text-white'}> <section className={'relative overflow-hidden border-t border-neutral-900 bg-neutral-900 text-white'}>
<div className={'mx-auto max-w-[88rem] px-6 py-24 sm:px-10 sm:py-32'}> <div className={'mx-auto max-w-[88rem] px-6 py-24 sm:px-10 sm:py-32'}>
+1 -3
View File
@@ -1,4 +1,4 @@
import {ComparisonTable, FAQSection, Footer, Navbar, SwitchOffer} from '../../components'; import {ComparisonTable, FAQSection, Footer, Navbar} from '../../components';
import {motion} from 'framer-motion'; import {motion} from 'framer-motion';
import {DASHBOARD_URI, WIKI_URI} from '../../lib/constants'; import {DASHBOARD_URI, WIKI_URI} from '../../lib/constants';
import React from 'react'; import React from 'react';
@@ -195,8 +195,6 @@ export default function MailchimpComparison() {
{/* FAQ */} {/* FAQ */}
<FAQSection faqs={faqs} schemaId="faq-schema-mailchimp" /> <FAQSection faqs={faqs} schemaId="faq-schema-mailchimp" />
<SwitchOffer competitorName="Mailchimp" />
{/* CTA */} {/* CTA */}
<section className={'relative overflow-hidden border-t border-neutral-900 bg-neutral-900 text-white'}> <section className={'relative overflow-hidden border-t border-neutral-900 bg-neutral-900 text-white'}>
<div className={'mx-auto max-w-[88rem] px-6 py-24 sm:px-10 sm:py-32'}> <div className={'mx-auto max-w-[88rem] px-6 py-24 sm:px-10 sm:py-32'}>
+1 -3
View File
@@ -1,4 +1,4 @@
import {ComparisonTable, FAQSection, Footer, Navbar, SwitchOffer} from '../../components'; import {ComparisonTable, FAQSection, Footer, Navbar} from '../../components';
import {motion} from 'framer-motion'; import {motion} from 'framer-motion';
import {DASHBOARD_URI, WIKI_URI} from '../../lib/constants'; import {DASHBOARD_URI, WIKI_URI} from '../../lib/constants';
import React from 'react'; import React from 'react';
@@ -170,8 +170,6 @@ export default function MailerliteComparison() {
{/* FAQ */} {/* FAQ */}
<FAQSection faqs={faqs} schemaId="faq-schema-mailerlite" /> <FAQSection faqs={faqs} schemaId="faq-schema-mailerlite" />
<SwitchOffer competitorName="MailerLite" />
{/* CTA */} {/* CTA */}
<section className={'relative overflow-hidden border-t border-neutral-900 bg-neutral-900 text-white'}> <section className={'relative overflow-hidden border-t border-neutral-900 bg-neutral-900 text-white'}>
<div className={'mx-auto max-w-[88rem] px-6 py-24 sm:px-10 sm:py-32'}> <div className={'mx-auto max-w-[88rem] px-6 py-24 sm:px-10 sm:py-32'}>
+1 -3
View File
@@ -1,4 +1,4 @@
import {ComparisonTable, FAQSection, Footer, Navbar, SwitchOffer} from '../../components'; import {ComparisonTable, FAQSection, Footer, Navbar} from '../../components';
import {motion} from 'framer-motion'; import {motion} from 'framer-motion';
import {DASHBOARD_URI, WIKI_URI} from '../../lib/constants'; import {DASHBOARD_URI, WIKI_URI} from '../../lib/constants';
import React from 'react'; import React from 'react';
@@ -189,8 +189,6 @@ export default function MailgunComparison() {
{/* FAQ */} {/* FAQ */}
<FAQSection faqs={faqs} schemaId="faq-schema-mailgun" /> <FAQSection faqs={faqs} schemaId="faq-schema-mailgun" />
<SwitchOffer competitorName="Mailgun" />
{/* CTA */} {/* CTA */}
<section className={'relative overflow-hidden border-t border-neutral-900 bg-neutral-900 text-white'}> <section className={'relative overflow-hidden border-t border-neutral-900 bg-neutral-900 text-white'}>
<div className={'mx-auto max-w-[88rem] px-6 py-24 sm:px-10 sm:py-32'}> <div className={'mx-auto max-w-[88rem] px-6 py-24 sm:px-10 sm:py-32'}>
+1 -3
View File
@@ -1,4 +1,4 @@
import {ComparisonTable, FAQSection, Footer, Navbar, SwitchOffer} from '../../components'; import {ComparisonTable, FAQSection, Footer, Navbar} from '../../components';
import {motion} from 'framer-motion'; import {motion} from 'framer-motion';
import {DASHBOARD_URI, WIKI_URI} from '../../lib/constants'; import {DASHBOARD_URI, WIKI_URI} from '../../lib/constants';
import React from 'react'; import React from 'react';
@@ -186,8 +186,6 @@ export default function MailjetComparison() {
{/* FAQ */} {/* FAQ */}
<FAQSection faqs={faqs} schemaId="faq-schema-mailjet" /> <FAQSection faqs={faqs} schemaId="faq-schema-mailjet" />
<SwitchOffer competitorName="Mailjet" />
{/* CTA */} {/* CTA */}
<section className={'relative overflow-hidden border-t border-neutral-900 bg-neutral-900 text-white'}> <section className={'relative overflow-hidden border-t border-neutral-900 bg-neutral-900 text-white'}>
<div className={'mx-auto max-w-[88rem] px-6 py-24 sm:px-10 sm:py-32'}> <div className={'mx-auto max-w-[88rem] px-6 py-24 sm:px-10 sm:py-32'}>
+1 -3
View File
@@ -1,4 +1,4 @@
import {ComparisonTable, FAQSection, Footer, Navbar, SwitchOffer} from '../../components'; import {ComparisonTable, FAQSection, Footer, Navbar} from '../../components';
import {motion} from 'framer-motion'; import {motion} from 'framer-motion';
import {DASHBOARD_URI, WIKI_URI} from '../../lib/constants'; import {DASHBOARD_URI, WIKI_URI} from '../../lib/constants';
import React from 'react'; import React from 'react';
@@ -190,8 +190,6 @@ export default function PostmarkComparison() {
{/* FAQ */} {/* FAQ */}
<FAQSection faqs={faqs} schemaId="faq-schema-postmark" /> <FAQSection faqs={faqs} schemaId="faq-schema-postmark" />
<SwitchOffer competitorName="Postmark" />
{/* CTA */} {/* CTA */}
<section className={'relative overflow-hidden border-t border-neutral-900 bg-neutral-900 text-white'}> <section className={'relative overflow-hidden border-t border-neutral-900 bg-neutral-900 text-white'}>
<div className={'mx-auto max-w-[88rem] px-6 py-24 sm:px-10 sm:py-32'}> <div className={'mx-auto max-w-[88rem] px-6 py-24 sm:px-10 sm:py-32'}>
+1 -3
View File
@@ -1,4 +1,4 @@
import {ComparisonTable, FAQSection, Footer, Navbar, SwitchOffer} from '../../components'; import {ComparisonTable, FAQSection, Footer, Navbar} from '../../components';
import {motion} from 'framer-motion'; import {motion} from 'framer-motion';
import {DASHBOARD_URI, WIKI_URI} from '../../lib/constants'; import {DASHBOARD_URI, WIKI_URI} from '../../lib/constants';
import React from 'react'; import React from 'react';
@@ -189,8 +189,6 @@ export default function ResendComparison() {
{/* FAQ */} {/* FAQ */}
<FAQSection faqs={faqs} schemaId="faq-schema-resend" /> <FAQSection faqs={faqs} schemaId="faq-schema-resend" />
<SwitchOffer competitorName="Resend" />
{/* CTA */} {/* CTA */}
<section className={'relative overflow-hidden border-t border-neutral-900 bg-neutral-900 text-white'}> <section className={'relative overflow-hidden border-t border-neutral-900 bg-neutral-900 text-white'}>
<div className={'mx-auto max-w-[88rem] px-6 py-24 sm:px-10 sm:py-32'}> <div className={'mx-auto max-w-[88rem] px-6 py-24 sm:px-10 sm:py-32'}>
+1 -3
View File
@@ -1,4 +1,4 @@
import {ComparisonTable, FAQSection, Footer, Navbar, SwitchOffer} from '../../components'; import {ComparisonTable, FAQSection, Footer, Navbar} from '../../components';
import {motion} from 'framer-motion'; import {motion} from 'framer-motion';
import {DASHBOARD_URI, WIKI_URI} from '../../lib/constants'; import {DASHBOARD_URI, WIKI_URI} from '../../lib/constants';
import React from 'react'; import React from 'react';
@@ -193,8 +193,6 @@ export default function SendGridComparison() {
{/* FAQ */} {/* FAQ */}
<FAQSection faqs={faqs} schemaId="faq-schema-sendgrid" /> <FAQSection faqs={faqs} schemaId="faq-schema-sendgrid" />
<SwitchOffer competitorName="SendGrid" />
{/* CTA */} {/* CTA */}
<section className={'relative overflow-hidden border-t border-neutral-900 bg-neutral-900 text-white'}> <section className={'relative overflow-hidden border-t border-neutral-900 bg-neutral-900 text-white'}>
<div className={'mx-auto max-w-[88rem] px-6 py-24 sm:px-10 sm:py-32'}> <div className={'mx-auto max-w-[88rem] px-6 py-24 sm:px-10 sm:py-32'}>
+1 -1
View File
@@ -43,7 +43,7 @@
"framer-motion": "^12.23.24", "framer-motion": "^12.23.24",
"juice": "^11.0.3", "juice": "^11.0.3",
"lucide-react": "^0.553.0", "lucide-react": "^0.553.0",
"next": "^16.2.3", "next": "^16.2.6",
"next-seo": "^6.6.0", "next-seo": "^6.6.0",
"nuqs": "^2.7.3", "nuqs": "^2.7.3",
"react": "19.2.3", "react": "19.2.3",
+8 -10
View File
@@ -335,8 +335,6 @@ export function DomainsSettings({projectId}: DomainsSettingsProps) {
<div className="space-y-4"> <div className="space-y-4">
{domains.map(domain => { {domains.map(domain => {
const status = getDomainStatus(domain); const status = getDomainStatus(domain);
const mailFromSubdomain = config?.aws?.mailFromSubdomain ?? 'plunk';
const mailFromHost = `${mailFromSubdomain}.${domain.domain}`;
return ( return (
<div key={domain.id} className="border border-neutral-200 rounded-lg p-4"> <div key={domain.id} className="border border-neutral-200 rounded-lg p-4">
<div className="flex items-center justify-between mb-3"> <div className="flex items-center justify-between mb-3">
@@ -496,8 +494,8 @@ export function DomainsSettings({projectId}: DomainsSettingsProps) {
</Badge> </Badge>
</div> </div>
<p className="text-xs text-neutral-600 mb-2"> <p className="text-xs text-neutral-600 mb-2">
Set up a custom MAIL FROM domain ({mailFromHost}) to improve deliverability and handle Set up a custom MAIL FROM domain (plunk.{domain.domain}) to improve deliverability and
bounces/complaints. handle bounces/complaints.
</p> </p>
<div className="overflow-x-auto"> <div className="overflow-x-auto">
@@ -524,16 +522,16 @@ export function DomainsSettings({projectId}: DomainsSettingsProps) {
<td className="py-3 px-3"> <td className="py-3 px-3">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<code className="text-xs font-mono text-neutral-700 break-all flex-1"> <code className="text-xs font-mono text-neutral-700 break-all flex-1">
{mailFromHost} plunk.{domain.domain}
</code> </code>
<Button <Button
variant="ghost" variant="ghost"
size="sm" size="sm"
onClick={() => handleCopyToken(mailFromHost, 3000)} onClick={() => handleCopyToken(`plunk.${domain.domain}`, 3000)}
className="shrink-0 h-6 w-6 p-0 overflow-hidden" className="shrink-0 h-6 w-6 p-0 overflow-hidden"
> >
<AnimatedCopyIcon <AnimatedCopyIcon
isCopied={copiedToken === `${mailFromHost}-3000`} isCopied={copiedToken === `plunk.${domain.domain}-3000`}
/> />
</Button> </Button>
</div> </div>
@@ -573,16 +571,16 @@ export function DomainsSettings({projectId}: DomainsSettingsProps) {
<td className="py-3 px-3"> <td className="py-3 px-3">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<code className="text-xs font-mono text-neutral-700 break-all flex-1"> <code className="text-xs font-mono text-neutral-700 break-all flex-1">
{mailFromHost} plunk.{domain.domain}
</code> </code>
<Button <Button
variant="ghost" variant="ghost"
size="sm" size="sm"
onClick={() => handleCopyToken(mailFromHost, 3001)} onClick={() => handleCopyToken(`plunk.${domain.domain}`, 3001)}
className="shrink-0 h-6 w-6 p-0 overflow-hidden" className="shrink-0 h-6 w-6 p-0 overflow-hidden"
> >
<AnimatedCopyIcon <AnimatedCopyIcon
isCopied={copiedToken === `${mailFromHost}-3001`} isCopied={copiedToken === `plunk.${domain.domain}-3001`}
/> />
</Button> </Button>
</div> </div>
@@ -306,31 +306,21 @@ export function EmailEditor({value, onChange, placeholder, subject, from, replyT
iframeDoc.write(fullHtml); iframeDoc.write(fullHtml);
iframeDoc.close(); iframeDoc.close();
// Auto-adjust iframe height to content. Reset to a small value first so // Auto-adjust iframe height to content
// body content that uses % / vh heights doesn't lock the iframe to its
// previous size (which would otherwise cause the iframe to grow by the
// padding offset on every preview-device switch).
const adjustHeight = () => { const adjustHeight = () => {
if (!iframe.contentWindow) return; if (iframe.contentWindow) {
iframe.style.height = '0px'; const height = iframe.contentWindow.document.body.scrollHeight;
const doc = iframe.contentWindow.document; iframe.style.height = `${Math.max(400, height + 40)}px`;
const height = Math.max( }
doc.body?.scrollHeight ?? 0,
doc.documentElement?.scrollHeight ?? 0,
);
iframe.style.height = `${Math.max(400, height + 40)}px`;
}; };
const timeouts = [ // Adjust height after content loads
window.setTimeout(adjustHeight, 100), if (iframe.contentWindow) {
window.setTimeout(adjustHeight, 300), iframe.contentWindow.addEventListener('load', adjustHeight);
]; // Also adjust immediately for already-loaded content
iframe.contentWindow?.addEventListener('load', adjustHeight); setTimeout(adjustHeight, 100);
setTimeout(adjustHeight, 300); // Fallback for slow-loading images
return () => { }
timeouts.forEach(window.clearTimeout);
iframe.contentWindow?.removeEventListener('load', adjustHeight);
};
} }
} }
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
@@ -1,126 +0,0 @@
import {describe, expect, it} from 'vitest';
import {detectCustomHtmlPatterns} from '../emailStyles';
describe('detectCustomHtmlPatterns', () => {
describe('empty / whitespace input', () => {
it('returns false for empty string', () => {
expect(detectCustomHtmlPatterns('')).toBe(false);
});
it('returns false for whitespace-only string', () => {
expect(detectCustomHtmlPatterns(' \n\t ')).toBe(false);
});
});
describe('content TipTap can round-trip (should NOT be flagged as custom)', () => {
it('returns false for a basic paragraph', () => {
expect(detectCustomHtmlPatterns('<p>Hello</p>')).toBe(false);
});
it('returns false for headings, lists, blockquote, bold, italic', () => {
expect(
detectCustomHtmlPatterns(
'<h1>Title</h1><p><strong>bold</strong> <em>italic</em></p><ul><li>one</li></ul><blockquote>quote</blockquote>',
),
).toBe(false);
});
it('returns false for <span> with inline color style (TipTap TextStyle output)', () => {
expect(detectCustomHtmlPatterns('<span style="color: rgb(220, 38, 38)">red</span>')).toBe(false);
});
it('returns false for <span> with background-color: initial (TipTap export artifact)', () => {
expect(detectCustomHtmlPatterns('<span style="background-color: initial">stuff</span>')).toBe(false);
});
it('returns false for <span> with background-color: transparent (TipTap export artifact)', () => {
expect(detectCustomHtmlPatterns('<span style="background-color: transparent">stuff</span>')).toBe(false);
});
it('returns false for <a> with inline style (TipTap Link output)', () => {
expect(detectCustomHtmlPatterns('<a href="https://example.com" style="color: red">link</a>')).toBe(false);
});
it('returns false for paragraph with inline text-align style', () => {
expect(detectCustomHtmlPatterns('<p style="text-align: center">centered</p>')).toBe(false);
});
it('returns false when an href URL contains "id=" or "contactId=" (must not match custom-attr regex)', () => {
expect(
detectCustomHtmlPatterns('<a href="https://example.com/u?contactId=abc&id=123">unsub</a>'),
).toBe(false);
});
it('returns false for allowed class prefixes', () => {
expect(detectCustomHtmlPatterns('<p class="prose">x</p>')).toBe(false);
expect(detectCustomHtmlPatterns('<span class="variable-mention">x</span>')).toBe(false);
expect(detectCustomHtmlPatterns('<img class="email-image" src="x" />')).toBe(false);
});
it('returns false for a TipTap-style colored span wrapped in a paragraph', () => {
expect(
detectCustomHtmlPatterns('<p>Hello <span style="color: rgb(220, 38, 38);">world</span>!</p>'),
).toBe(false);
});
});
describe('content TipTap can NOT round-trip (should be flagged as custom)', () => {
it('returns true for <div>', () => {
expect(detectCustomHtmlPatterns('<div>stuff</div>')).toBe(true);
});
it('returns true for <table> markup (no TipTap Table extension loaded)', () => {
expect(detectCustomHtmlPatterns('<table><tr><td>x</td></tr></table>')).toBe(true);
});
it('returns true for a single <table> tag', () => {
expect(detectCustomHtmlPatterns('<table>x</table>')).toBe(true);
});
it('returns true for <style> tag', () => {
expect(detectCustomHtmlPatterns('<style>p { color: red; }</style>')).toBe(true);
});
it('returns true for @media query inside a style block', () => {
expect(detectCustomHtmlPatterns('@media (max-width: 600px) { ... }')).toBe(true);
});
it('returns true for custom data-* attribute', () => {
expect(detectCustomHtmlPatterns('<p data-foo="bar">x</p>')).toBe(true);
});
it('returns true for aria-* attribute', () => {
expect(detectCustomHtmlPatterns('<p aria-label="x">y</p>')).toBe(true);
});
it('returns true for role= attribute', () => {
expect(detectCustomHtmlPatterns('<p role="presentation">x</p>')).toBe(true);
});
it('returns true for id= attribute on an element', () => {
expect(detectCustomHtmlPatterns('<p id="main">x</p>')).toBe(true);
});
it('returns true for a disallowed CSS class', () => {
expect(detectCustomHtmlPatterns('<p class="custom">x</p>')).toBe(true);
});
it('returns true for <section>, <article>, <header>, <footer>, <nav>, <aside>, <main>', () => {
expect(detectCustomHtmlPatterns('<section>x</section>')).toBe(true);
expect(detectCustomHtmlPatterns('<article>x</article>')).toBe(true);
expect(detectCustomHtmlPatterns('<header>x</header>')).toBe(true);
expect(detectCustomHtmlPatterns('<footer>x</footer>')).toBe(true);
expect(detectCustomHtmlPatterns('<nav>x</nav>')).toBe(true);
expect(detectCustomHtmlPatterns('<aside>x</aside>')).toBe(true);
expect(detectCustomHtmlPatterns('<main>x</main>')).toBe(true);
});
it('returns true for form/input/button/iframe/svg', () => {
expect(detectCustomHtmlPatterns('<form>x</form>')).toBe(true);
expect(detectCustomHtmlPatterns('<input type="text" />')).toBe(true);
expect(detectCustomHtmlPatterns('<button>x</button>')).toBe(true);
expect(detectCustomHtmlPatterns('<iframe src="x"></iframe>')).toBe(true);
expect(detectCustomHtmlPatterns('<svg><circle /></svg>')).toBe(true);
});
});
});
+14 -24
View File
@@ -1,15 +1,10 @@
// Detects if HTML contains custom patterns that indicate it was written in the HTML editor // Detects if HTML contains custom patterns that indicate it was written in the HTML editor
// rather than the visual editor. Custom HTML should render as-is without prose wrapper. // rather than the visual editor. Custom HTML should render as-is without prose wrapper.
//
// The TipTap editor in EmailEditor.tsx loads: StarterKit (paragraphs, headings, lists,
// blockquote, code, hr, bold, italic, strike, etc.), TextAlign, Color, TextStyle, Link,
// ResizableImage, and VariableMention. Of these, TextStyle + Color + Link natively
// round-trip <span style="color: ..."> / <a style="color: ..."> markup that TipTap itself
// generates when you change text color or style a link. We must therefore PERMIT what
// TipTap can represent and REJECT only what it can't.
export const detectCustomHtmlPatterns = (html: string): boolean => { export const detectCustomHtmlPatterns = (html: string): boolean => {
if (!html || html.trim() === '') return false; if (!html || html.trim() === '') return false;
const hasInlineStyles = /<[^>]+style\s*=\s*["'][^"']*["']/i.test(html);
const classMatches = html.matchAll(/class\s*=\s*["']([^"']*)["']/gi); const classMatches = html.matchAll(/class\s*=\s*["']([^"']*)["']/gi);
let hasCustomClasses = false; let hasCustomClasses = false;
for (const match of classMatches) { for (const match of classMatches) {
@@ -33,26 +28,21 @@ export const detectCustomHtmlPatterns = (html: string): boolean => {
} }
} }
// Custom attributes that carry semantics TipTap doesn't preserve. We require an const hasCustomAttributes = /<[^>]+(?:data-|aria-|role=|id=)/i.test(html);
// attribute-boundary (whitespace, `=`, or quote) before the prefix so that query const hasComplexTables = /<table[^>]*>[\s\S]*?<table/i.test(html);
// strings like `?id=...` inside an `href="..."` value don't false-match. const hasCustomElements = /<(?:div|span|section|article|header|footer|nav|aside)[^>]*>/i.test(html);
const hasCustomAttributes = /<[a-z][^>]*?[\s"'](?:data-|aria-|role=|id=)/i.test(html);
// Elements TipTap cannot round-trip with the currently-loaded extension set.
// - No Table/TableRow/TableCell extensions are loaded -> all table markup is custom.
// - No Div/Section/etc. block-layout extensions -> reject layout containers.
// - Form/embed/media/interactive elements have no TipTap representation here.
// <span> is intentionally NOT in this list: TipTap's TextStyle extension emits and
// accepts <span style="..."> for things like text color.
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 hasMediaQueries = /@media/i.test(html);
const hasStyleTags = /<style[^>]*>/i.test(html); const hasStyleTags = /<style[^>]*>/i.test(html);
return hasCustomClasses || hasCustomAttributes || hasCustomElements || hasMediaQueries || hasStyleTags; return (
hasInlineStyles ||
hasCustomClasses ||
hasCustomAttributes ||
hasComplexTables ||
hasCustomElements ||
hasMediaQueries ||
hasStyleTags
);
}; };
export const wrapEmailWithStyles = (htmlBody: string): string => { export const wrapEmailWithStyles = (htmlBody: string): string => {
-1
View File
@@ -21,7 +21,6 @@ export interface ConfigResponse {
}; };
aws: { aws: {
sesRegion: string; sesRegion: string;
mailFromSubdomain: string;
}; };
} }
+2 -2
View File
@@ -252,7 +252,7 @@ export default function CampaignsPage() {
</div> </div>
{/* Search & Filters */} {/* Search & Filters */}
<div className="flex flex-col sm:flex-row sm:items-center gap-3"> <div className="flex flex-col sm:flex-row gap-3">
<div className="relative flex-1"> <div className="relative flex-1">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-neutral-400" /> <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-neutral-400" />
<Input <Input
@@ -260,7 +260,7 @@ export default function CampaignsPage() {
placeholder="Search campaigns..." placeholder="Search campaigns..."
value={searchInput} value={searchInput}
onChange={e => setSearchInput(e.target.value)} onChange={e => setSearchInput(e.target.value)}
className="pl-10 pr-10 h-8 text-xs" className="pl-10 pr-10"
/> />
{searchInput && ( {searchInput && (
<button <button
+2 -12
View File
@@ -405,12 +405,7 @@ export default function ContactsPage() {
) : ( ) : (
<MailX className="h-4 w-4 text-red-600" /> <MailX className="h-4 w-4 text-red-600" />
)} )}
<Link <span className="text-sm font-medium text-neutral-900">{contact.email}</span>
href={`/contacts/${contact.id}`}
className="text-sm font-medium text-neutral-900 hover:text-neutral-700 focus-visible:outline-none focus-visible:underline"
>
{contact.email}
</Link>
</div> </div>
</td> </td>
<td className="px-6 py-4 whitespace-nowrap"> <td className="px-6 py-4 whitespace-nowrap">
@@ -460,12 +455,7 @@ export default function ContactsPage() {
) : ( ) : (
<MailX className="h-4 w-4 text-red-600 flex-shrink-0" /> <MailX className="h-4 w-4 text-red-600 flex-shrink-0" />
)} )}
<Link <span className="text-sm font-medium text-neutral-900 truncate">{contact.email}</span>
href={`/contacts/${contact.id}`}
className="text-sm font-medium text-neutral-900 truncate hover:text-neutral-700 focus-visible:outline-none focus-visible:underline"
>
{contact.email}
</Link>
</div> </div>
<span <span
className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium flex-shrink-0 ${ className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium flex-shrink-0 ${
+2 -2
View File
@@ -90,7 +90,7 @@ export default function TemplatesPage() {
</div> </div>
{/* Search & Filters */} {/* Search & Filters */}
<div className="flex flex-col sm:flex-row sm:items-center gap-3"> <div className="flex flex-col sm:flex-row gap-3">
<div className="relative flex-1"> <div className="relative flex-1">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-neutral-400" /> <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-neutral-400" />
<Input <Input
@@ -98,7 +98,7 @@ export default function TemplatesPage() {
placeholder="Search templates..." placeholder="Search templates..."
value={searchInput} value={searchInput}
onChange={e => setSearchInput(e.target.value)} onChange={e => setSearchInput(e.target.value)}
className="pl-10 pr-10 h-8 text-xs" className="pl-10 pr-10"
/> />
{searchInput && ( {searchInput && (
<button <button
+1 -1
View File
@@ -117,7 +117,7 @@ export default function WorkflowsPage() {
placeholder="Search workflows..." placeholder="Search workflows..."
value={searchInput} value={searchInput}
onChange={e => setSearchInput(e.target.value)} onChange={e => setSearchInput(e.target.value)}
className="pl-10 pr-10 h-8 text-xs" className="pl-10 pr-10"
/> />
{searchInput && ( {searchInput && (
<button <button
-12
View File
@@ -26,13 +26,6 @@ export default async function Page(props: {params: Promise<{slug?: string[]}>})
markdownUrl={`/llms.mdx${page.url}`} markdownUrl={`/llms.mdx${page.url}`}
githubUrl={`https://github.com/useplunk/plunk/blob/next/apps/wiki/content/docs/${page.path}`} githubUrl={`https://github.com/useplunk/plunk/blob/next/apps/wiki/content/docs/${page.path}`}
/> />
<p className="ml-auto hidden text-[11px] text-fd-muted-foreground sm:block">
Reading this with electronic eyes? Add{' '}
<a href={`${page.url}.md`} className="underline decoration-dotted underline-offset-2 transition hover:text-fd-foreground">
<code>.md</code>
</a>{' '}
for the Markdown cut.
</p>
</div> </div>
<DocsBody> <DocsBody>
@@ -64,11 +57,6 @@ export async function generateMetadata(props: {params: Promise<{slug?: string[]}
return { return {
title: page.data.title, title: page.data.title,
description: page.data.description, description: page.data.description,
alternates: {
types: {
'text/markdown': `${page.url}.md`,
},
},
openGraph: { openGraph: {
images: [{url: ogUrl.toString(), width: 1200, height: 630}], images: [{url: ogUrl.toString(), width: 1200, height: 630}],
}, },
-13
View File
@@ -6,16 +6,3 @@
body { body {
font-family: 'Inter', sans-serif; font-family: 'Inter', sans-serif;
} }
/*
* Two-tone palette: white content, gray chrome.
* `--color-fd-background` paints the page (content area + nav).
* `--color-fd-card` paints the sidebar (via `bg-fd-card` on `#nd-sidebar`)
* and the `<Cards>` component both read well as soft gray against white.
*/
:root {
--color-fd-background: hsl(0, 0%, 100%);
--color-fd-card: hsl(0, 0%, 96.5%);
--color-fd-secondary: hsl(0, 0%, 95%);
--color-fd-border: hsla(0, 0%, 80%, 60%);
}
-16
View File
@@ -1,16 +0,0 @@
import {openapi} from '@/lib/openapi';
export const revalidate = false;
export async function GET() {
const schemas = await openapi.getSchemas();
const first = Object.values(schemas)[0];
if (!first) return new Response('Not found', {status: 404});
return new Response(JSON.stringify(first.bundled), {
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'public, max-age=300, s-maxage=3600',
},
});
}
@@ -37,7 +37,7 @@ A workflow always begins with a single auto-created `TRIGGER` step. You build th
| `DELAY` | Pauses the execution for a fixed duration before continuing. | `amount`, `unit` (`minutes` / `hours` / `days`) | | `DELAY` | Pauses the execution for a fixed duration before continuing. | `amount`, `unit` (`minutes` / `hours` / `days`) |
| `WAIT_FOR_EVENT` | Pauses until a specified event is tracked on the contact, with a timeout fallback. | `eventName`, `timeout` (seconds) | | `WAIT_FOR_EVENT` | Pauses until a specified event is tracked on the contact, with a timeout fallback. | `eventName`, `timeout` (seconds) |
| `CONDITION` | Branches the execution based on contact data or event data. Each `CONDITION` step has two outgoing transitions tagged `yes` / `no`. | A filter expression (same shape as segment filters) | | `CONDITION` | Branches the execution based on contact data or event data. Each `CONDITION` step has two outgoing transitions tagged `yes` / `no`. | A filter expression (same shape as segment filters) |
| `WEBHOOK` | Calls an external HTTPS endpoint with contact + execution context as the JSON body. `url`, header values, and `body` support `{{variables}}`. | `url`, optional `method`, `headers`, `body` | | `WEBHOOK` | Calls an external HTTPS endpoint with contact + execution context as the JSON body. | `url`, optional `method`, `headers` |
| `UPDATE_CONTACT` | Patches contact data — useful for tagging contacts as they progress (`{ stage: "activated" }`). | `data` object | | `UPDATE_CONTACT` | Patches contact data — useful for tagging contacts as they progress (`{ stage: "activated" }`). | `data` object |
| `EXIT` | Terminates the execution. Optionally records an `exitReason` for analytics. | optional `reason` | | `EXIT` | Terminates the execution. Optionally records an `exitReason` for analytics. | optional `reason` |
@@ -37,8 +37,6 @@ In this example, every imported contact ends up with `data.firstName`, `data.pla
- **Email column**: must be present and valid. Rows with missing or invalid emails are reported back as errors. - **Email column**: must be present and valid. Rows with missing or invalid emails are reported back as errors.
- **Reserved column names**: `id`, `subscribed`, `createdAt`, `updatedAt`, and the auto-generated URL variables (`unsubscribeUrl`, etc.) are silently filtered out. Don't include them as columns. - **Reserved column names**: `id`, `subscribed`, `createdAt`, `updatedAt`, and the auto-generated URL variables (`unsubscribeUrl`, etc.) are silently filtered out. Don't include them as columns.
- **Date columns**: use ISO 8601 (`2026-05-06T12:00:00Z`) so they're typed as dates and become usable with `within` / `olderThan` segment operators. - **Date columns**: use ISO 8601 (`2026-05-06T12:00:00Z`) so they're typed as dates and become usable with `within` / `olderThan` segment operators.
- **Boolean columns**: `true`, `false`, `yes`, `no` (case-insensitive) are stored as booleans and get the boolean toggle in segment filters.
- **Numeric columns**: plain integers and decimals (`42`, `3.14`) are stored as numbers and become usable with `gt` / `lt` segment operators. Leading-zero values (`01234`), `+`-prefixed numbers, and scientific notation stay strings so IDs, zip codes, and phone numbers aren't corrupted.
- **Existing contacts**: if a row's email matches an existing contact, the import **updates** the contact (merging the CSV's columns into `data`). It doesn't create a duplicate or overwrite the whole record. - **Existing contacts**: if a row's email matches an existing contact, the import **updates** the contact (merging the CSV's columns into `data`). It doesn't create a duplicate or overwrite the whole record.
## Importing your CSV ## Importing your CSV
@@ -84,53 +84,6 @@ After the trigger, add a **Webhook** step and configure it:
} }
``` ```
- **Body** (optional): Custom request body. When omitted, Plunk sends the [default payload](#webhook-payload) shown below. When provided, the value replaces the default payload entirely and is JSON-encoded before being sent.
</Step>
<Step>
### Use variables in the request (optional)
The `url`, header values, and `body` all support `{{variable}}` interpolation. The available scope is the same as `SEND_EMAIL` templates, plus a webhook-only `event` namespace exposing the trigger event payload:
| Variable | Value |
| --------------------------------------------------------- | --------------------------------------------------------------------------- |
| `{{id}}`, `{{email}}` | The contact's ID and email. |
| `{{<key>}}` (top-level) | Any key from the contact's `data` JSON (e.g. `{{firstName}}`, `{{plan}}`). |
| `{{data.<key>}}` | The same contact data, addressed via the `data` namespace. |
| `{{event.<key>}}` | Webhook-only. Fields from the trigger event payload (e.g. `{{event.subject}}`). |
| `{{<key>}}` (from execution context) | Keys passed in as `context` when starting a `MANUAL` execution. |
| `{{unsubscribeUrl}}`, `{{subscribeUrl}}`, `{{manageUrl}}` | Per-contact subscription management URLs. |
The HTTP `method` is **not** templated — it must be a literal verb (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`). The `url` must include a static scheme (`http://` or `https://`); placeholders are supported inside the URL but cannot replace the scheme.
Example — forward a contact event to your own API, parameterised by contact data:
**URL**
```text
https://api.example.com/users/{{id}}/events
```
**Headers**
```json
{
"Authorization": "Bearer your-secret-token"
}
```
**Body**
```json
{
"email": "{{email}}",
"plan": "{{plan}}",
"referrer": "{{event.referrer}}"
}
```
</Step> </Step>
<Step> <Step>
-2
View File
@@ -4,8 +4,6 @@
"---Docs---", "---Docs---",
"concepts", "concepts",
"guides", "guides",
"---Recipes---",
"recipes",
"---API Reference---", "---API Reference---",
"api-reference", "api-reference",
"---Self-Hosting---", "---Self-Hosting---",
@@ -1,102 +0,0 @@
---
title: Double opt-in
description: Require a confirmation click before a new signup starts receiving marketing email
icon: MailCheck
---
Double opt-in adds a confirmation step between "user signs up" and "user starts getting marketing email." It's the standard way to avoid mailing typoed addresses, role accounts, and anyone who didn't actually consent.
The trick is `{{subscribeUrl}}`: a per-contact link Plunk auto-injects into every send. Clicking it flips `subscribed` to `true` and fires a `contact.subscribed` event.
## Setup
import {Step, Steps} from 'fumadocs-ui/components/steps';
<Steps>
<Step>
### Create two templates
- A **Transactional** template for the confirmation email, containing `{{subscribeUrl}}`:
```html
<p>Hi {{firstName}}, please confirm your email to start receiving updates:</p>
<p><a href="{{subscribeUrl}}">Confirm my email</a></p>
```
- A **Marketing** template for the welcome email that goes out *after* they confirm.
<Callout title="The confirmation must be transactional" type="warn">
A marketing template targeted at an unsubscribed contact is [silently skipped](/concepts/contacts#emails-by-subscription-state). Use a transactional template for the confirmation specifically — it bypasses the subscription check.
</Callout>
</Step>
<Step>
### Trigger the signup from your backend
Two calls with your secret key (`sk_*`): create the contact unsubscribed, then track the event that fires the confirmation workflow.
```bash
curl https://next-api.useplunk.com/contacts \
-H "Authorization: Bearer sk_your_secret_key" \
-d '{ "email": "[email protected]", "subscribed": false, "data": { "firstName": "Ada" } }'
curl https://next-api.useplunk.com/v1/track \
-H "Authorization: Bearer sk_your_secret_key" \
-d '{ "event": "signup.pending", "email": "[email protected]", "subscribed": false }'
```
Both calls pass `subscribed: false`. If you skip the first call and rely on `/v1/track` alone, tracking on an unknown email creates the contact — but defaults it to subscribed, which defeats the point.
</Step>
<Step>
### Workflow A: send the confirmation
**Workflows → New workflow**:
- **Trigger**: `EVENT` on `signup.pending`
- `SEND_EMAIL` step → transactional confirmation template
Enable it.
</Step>
<Step>
### Workflow B: welcome them after confirmation
**Workflows → New workflow**:
- **Trigger**: `EVENT` on `contact.subscribed`
- `SEND_EMAIL` step → marketing welcome template
Enable it. `contact.subscribed` fires whenever a contact opts in — including via `{{subscribeUrl}}`, the preferences page, or the API — so this workflow handles both first-time confirmations and resubscribes.
</Step>
</Steps>
## Reminder if they don't confirm
Extend Workflow A with a `WAIT_FOR_EVENT` step after the send:
- **Event**: `contact.subscribed`
- **Timeout**: `86400` (24 hours)
On timeout, send a single reminder (also transactional). Keep the number of reminders small — repeated confirmation prompts look like spam to mailbox providers as much as to recipients.
## What's next
<Cards>
<Card title="Unsubscribe & preferences pages" href="/guides/unsubscribe-pages">
Detail on `{{subscribeUrl}}` and the hosted pages.
</Card>
<Card title="Templates" href="/concepts/templates">
The difference between Marketing, Transactional, and Headless templates.
</Card>
</Cards>
-19
View File
@@ -1,19 +0,0 @@
---
title: Recipes
description: End-to-end walkthroughs for common patterns built on Plunk events and workflows
icon: ChefHat
---
Recipes are concrete, step-by-step builds for patterns we see most often in Plunk projects. Each one assumes you already understand the underlying [concepts](/concepts/workflows) and walks you through the exact API calls, workflow steps, and template variables involved.
<Cards>
<Card title="Waitlist with confirmation email" href="/recipes/waitlist">
Capture signups with a single tracked event, then automatically email each person who joins.
</Card>
<Card title="Sync unsubscribes to your database" href="/recipes/sync-unsubscribes">
Keep your own user table in step with Plunk's subscription state using a webhook step.
</Card>
<Card title="Double opt-in" href="/recipes/double-opt-in">
Add a confirmation step before a contact starts receiving marketing email, using `{{subscribeUrl}}`.
</Card>
</Cards>
-3
View File
@@ -1,3 +0,0 @@
{
"pages": ["index", "waitlist", "sync-unsubscribes", "double-opt-in"]
}
@@ -1,87 +0,0 @@
---
title: Sync unsubscribes to your database
description: Mirror Plunk's subscription state into your own user table using a workflow + webhook
icon: RefreshCw
---
Every flip of a contact's `subscribed` state — manual edits, the hosted unsubscribe page, bounces, complaints — fires a `contact.unsubscribed` event. Wire a workflow with a `WEBHOOK` step to forward that to your backend.
## Setup
import {Step, Steps} from 'fumadocs-ui/components/steps';
<Steps>
<Step>
### Build the receiving endpoint
A public HTTPS endpoint that verifies a shared secret and updates the user row. Webhook requests time out after 10 seconds, so do the work async if it's slow.
```ts
app.post('/plunk/unsubscribes', async (req, res) => {
if (req.header('authorization') !== `Bearer ${process.env.PLUNK_WEBHOOK_SECRET}`) {
return res.status(401).end();
}
const { contact, event } = req.body;
await db.user.update({
where: { email: contact.email },
data: {
emailSubscribed: false,
emailUnsubscribedReason: event.reason ?? 'user_action',
},
});
res.status(204).end();
});
```
`event.reason` is `"bounce"` or `"complaint"` for automatic unsubscribes, and absent for manual / self-service ones.
</Step>
<Step>
### Create the workflow
**Workflows → New workflow**:
- **Trigger**: `EVENT` on `contact.unsubscribed`
- Add a `WEBHOOK` step:
- **URL**: `https://api.example.com/plunk/unsubscribes`
- **Headers**: `{ "Authorization": "Bearer your-shared-secret" }`
- Leave the body blank to get the [default payload](/guides/webhooks#webhook-payload).
Enable the workflow.
</Step>
</Steps>
## Mirroring resubscribes
Build a second workflow with the same shape, triggered by `contact.subscribed`. Keep it separate from the unsubscribe flow — two short workflows are easier to monitor than one branched one.
## The reverse direction
If your product is the source of truth (a user toggles their email preference in your settings UI), call `PATCH /contacts/:id` from your backend:
```bash
curl -X PATCH https://next-api.useplunk.com/contacts/cnt_abc \
-H "Authorization: Bearer sk_your_secret_key" \
-d '{"subscribed": false}'
```
That flip also fires `contact.unsubscribed`, meaning your own webhook will round-trip back into your handler. That's usually harmless because the update is idempotent — but be aware of it.
## What's next
<Cards>
<Card title="Webhooks" href="/guides/webhooks">
Webhook step reference, payload shape, and safety.
</Card>
<Card title="Unsubscribe pages" href="/guides/unsubscribe-pages">
The hosted pages and template URL variables.
</Card>
</Cards>
@@ -1,89 +0,0 @@
---
title: Waitlist with confirmation email
description: Track signups as a custom event, store everyone who joins as a contact, and automatically email them
icon: ListOrdered
---
A waitlist is the simplest possible Plunk workflow: one tracked event from your app, one workflow that listens for it, one email.
## Setup
import {Step, Steps} from 'fumadocs-ui/components/steps';
<Steps>
<Step>
### Create the confirmation template
In **Templates → New template**, create a **Marketing** template. Use `{{variable}}` placeholders for anything you want to personalise from contact data:
```text
Subject: You're on the list, {{firstName}}
Hi {{firstName}}, thanks for joining the {{product}} waitlist.
We'll let you know as soon as your spot opens up.
```
</Step>
<Step>
### Track the signup from your backend
Call `POST /v1/track` when a user submits the form. Use a secret key (`sk_*`) — never call this from the browser.
```bash
curl https://next-api.useplunk.com/v1/track \
-H "Authorization: Bearer sk_your_secret_key" \
-H "Content-Type: application/json" \
-d '{
"event": "waitlist.joined",
"email": "[email protected]",
"data": { "firstName": "Ada", "product": "Beta" }
}'
```
This call upserts the contact (subscribed by default) and records `waitlist.joined` on them. Anything you put in `data` lands on the contact and is available as `{{firstName}}`, `{{product}}`, etc. in the template.
<Callout title="Pick a stable event name" type="info">
A workflow's trigger event **cannot be changed after the first execution**. Namespace it (`waitlist.joined`) rather than something generic you might want to reuse.
</Callout>
</Step>
<Step>
### Create the workflow
**Workflows → New workflow**:
- **Trigger**: `EVENT` on `waitlist.joined`
- Add a `SEND_EMAIL` step pointing at the template from step 1
Enable the workflow. Workflows are created disabled — until the toggle is on, nothing fires.
</Step>
</Steps>
## Tagging signups for later
If you want to segment on waitlist signups later, add an `UPDATE_CONTACT` step before the email:
```json
{ "stage": "waitlist", "waitlistSource": "{{event.referrer}}" }
```
You can then build a [segment](/concepts/segments) of contacts where `stage == "waitlist"` to target with follow-up campaigns. This is cleaner than filtering on "ever fired `waitlist.joined`."
## What's next
<Cards>
<Card title="Workflows" href="/concepts/workflows">
Step types and trigger semantics.
</Card>
<Card title="Track event API" href="/api-reference/public-api/trackEvent">
Full reference for `POST /v1/track`.
</Card>
</Cards>
@@ -36,7 +36,6 @@ Set your subdomains here. The application automatically derives all internal and
| `AWS_SES_SECRET_ACCESS_KEY` | Yes | AWS secret access key for SES. | `wJalr...` | | `AWS_SES_SECRET_ACCESS_KEY` | Yes | AWS secret access key for SES. | `wJalr...` |
| `SES_CONFIGURATION_SET` | No | SES configuration set name used for open/click tracking. | `plunk-configuration-set` (default) | | `SES_CONFIGURATION_SET` | No | SES configuration set name used for open/click tracking. | `plunk-configuration-set` (default) |
| `SES_CONFIGURATION_SET_NO_TRACKING` | No | A second SES configuration set without tracking. When set, projects can toggle email tracking on/off. If omitted, the tracking toggle is hidden. | `plunk-no-tracking-configuration-set` (default) | | `SES_CONFIGURATION_SET_NO_TRACKING` | No | A second SES configuration set without tracking. When set, projects can toggle email tracking on/off. If omitted, the tracking toggle is hidden. | `plunk-no-tracking-configuration-set` (default) |
| `MAIL_FROM_SUBDOMAIN` | No | Subdomain prefix used when constructing the MAIL FROM hostname for a verified domain (e.g. with default `plunk` and domain `yourdomain.com`, the MAIL FROM is `plunk.yourdomain.com`). Override when the default subdomain is already in use (e.g. by an R2/CDN custom domain), since the MAIL FROM hostname needs MX + TXT records that can't coexist with a CNAME. | `plunk` |
## Storage (Minio) ## Storage (Minio)
@@ -130,16 +129,6 @@ Plunk bundles a self-hosted [ntfy](https://ntfy.sh) server for internal system n
| ----------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | ----------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| `AUTO_PROJECT_DISABLE` | No | When `true`, projects are automatically suspended when bounce or complaint rate thresholds are exceeded. Set to `false` to manage project status manually. | `true` | | `AUTO_PROJECT_DISABLE` | No | When `true`, projects are automatically suspended when bounce or complaint rate thresholds are exceeded. Set to `false` to manage project status manually. | `true` |
| `EMAIL_RATE_LIMIT_PER_SECOND` | No | Override the email sending rate limit. If not set, Plunk automatically fetches the quota from your AWS SES account. | — | | `EMAIL_RATE_LIMIT_PER_SECOND` | No | Override the email sending rate limit. If not set, Plunk automatically fetches the quota from your AWS SES account. | — |
| `EMAIL_WORKER_CONCURRENCY` | No | Number of emails the worker processes in parallel. When unset, derived from the effective rate limit so a higher SES quota scales throughput automatically. | — |
| `EMAIL_WORKER_MAX_CONCURRENCY`| No | Upper bound applied to the auto-derived worker concurrency. Raise this only after sizing the Prisma connection pool accordingly. | `50` |
## Advanced
Variables for unusual deployments. The defaults work for the standard Docker Compose setup — only change these if you know you need to.
| Variable | Required | Description | Default |
| ------------ | -------- | ------------------------------------------------------------------------------------------------------------------------ | ------- |
| `NGINX_PORT` | No | Host port the bundled Nginx reverse proxy binds to. Override when port 80/443 is already in use on the host (e.g. running behind another reverse proxy that forwards to a different port). | `80` |
## Phishing Detection ## Phishing Detection
+1 -9
View File
@@ -1,17 +1,9 @@
import {renderOpenAPIOperationFromMDX} from '@/lib/render-openapi-operation';
import {source} from '@/lib/source'; import {source} from '@/lib/source';
import type {InferPageType} from 'fumadocs-core/source'; import type {InferPageType} from 'fumadocs-core/source';
export async function getLLMText(page: InferPageType<typeof source>) { export async function getLLMText(page: InferPageType<typeof source>) {
const isOpenAPI = Boolean((page.data as {_openapi?: unknown})._openapi);
if (isOpenAPI) {
const raw = await page.data.getText('raw');
const rendered = await renderOpenAPIOperationFromMDX(raw, page.data.title, page.url);
if (rendered) return rendered;
}
const processed = await page.data.getText('processed'); const processed = await page.data.getText('processed');
return `# ${page.data.title} (${page.url}) return `# ${page.data.title} (${page.url})
${processed}`; ${processed}`;
-279
View File
@@ -1,279 +0,0 @@
import {openapi} from '@/lib/openapi';
interface SchemaLike {
type?: string | string[];
format?: string;
enum?: unknown[];
description?: string;
default?: unknown;
example?: unknown;
required?: string[];
properties?: Record<string, SchemaLike>;
items?: SchemaLike;
oneOf?: SchemaLike[];
anyOf?: SchemaLike[];
allOf?: SchemaLike[];
nullable?: boolean;
[key: string]: unknown;
}
interface Parameter {
name: string;
in: string;
required?: boolean;
description?: string;
schema?: SchemaLike;
}
interface Operation {
operationId?: string;
summary?: string;
description?: string;
deprecated?: boolean;
tags?: string[];
parameters?: Parameter[];
requestBody?: {
required?: boolean;
description?: string;
content?: Record<string, {schema?: SchemaLike}>;
};
responses?: Record<
string,
{
description?: string;
content?: Record<string, {schema?: SchemaLike}>;
}
>;
security?: Array<Record<string, string[]>>;
}
function typeLabel(schema?: SchemaLike): string {
if (!schema) return 'unknown';
if (schema.enum) return `enum (${schema.enum.map(v => JSON.stringify(v)).join(' | ')})`;
if (schema.oneOf) return schema.oneOf.map(typeLabel).join(' | ');
if (schema.anyOf) return schema.anyOf.map(typeLabel).join(' | ');
if (schema.allOf) return schema.allOf.map(typeLabel).join(' & ');
if (Array.isArray(schema.type)) return schema.type.join(' | ');
const base = schema.type ?? 'object';
if (base === 'array' && schema.items) return `array<${typeLabel(schema.items)}>`;
if (schema.format) return `${base} (${schema.format})`;
return base;
}
function renderSchemaTree(schema: SchemaLike | undefined, depth = 0, lines: string[] = []): string[] {
if (!schema) return lines;
const indent = ' '.repeat(depth);
if (schema.allOf) {
for (const sub of schema.allOf) renderSchemaTree(sub, depth, lines);
return lines;
}
if (schema.type === 'object' || schema.properties) {
const required = new Set(schema.required ?? []);
const props = schema.properties ?? {};
for (const [name, prop] of Object.entries(props)) {
const tag = required.has(name) ? ' (required)' : '';
const desc = prop.description ? `${prop.description.replace(/\n+/g, ' ')}` : '';
lines.push(`${indent}- \`${name}\`: ${typeLabel(prop)}${tag}${desc}`);
if (prop.type === 'object' || prop.properties) {
renderSchemaTree(prop, depth + 1, lines);
} else if (prop.type === 'array' && prop.items && (prop.items.type === 'object' || prop.items.properties)) {
lines.push(`${indent} items:`);
renderSchemaTree(prop.items, depth + 2, lines);
}
}
return lines;
}
if (schema.type === 'array' && schema.items) {
lines.push(`${indent}- items: ${typeLabel(schema.items)}`);
renderSchemaTree(schema.items, depth + 1, lines);
}
return lines;
}
function exampleFromSchema(schema?: SchemaLike): unknown {
if (!schema) return undefined;
if (schema.example !== undefined) return schema.example;
if (schema.default !== undefined) return schema.default;
if (schema.enum && schema.enum.length > 0) return schema.enum[0];
if (schema.allOf) {
const merged: Record<string, unknown> = {};
for (const sub of schema.allOf) Object.assign(merged, exampleFromSchema(sub) as object ?? {});
return merged;
}
if (schema.oneOf?.[0]) return exampleFromSchema(schema.oneOf[0]);
if (schema.anyOf?.[0]) return exampleFromSchema(schema.anyOf[0]);
if (schema.properties) {
const out: Record<string, unknown> = {};
const required = new Set(schema.required ?? Object.keys(schema.properties));
for (const [name, prop] of Object.entries(schema.properties)) {
if (!required.has(name) && schema.required) continue;
out[name] = exampleFromSchema(prop);
}
return out;
}
if (schema.type === 'array') {
const item = exampleFromSchema(schema.items);
return item === undefined ? [] : [item];
}
switch (schema.type) {
case 'string':
if (schema.format === 'email') return '[email protected]';
if (schema.format === 'date-time') return new Date().toISOString();
if (schema.format === 'uri' || schema.format === 'url') return 'https://example.com';
return 'string';
case 'integer':
case 'number':
return 0;
case 'boolean':
return false;
default:
return null;
}
}
function findOperationByMethodPath(
doc: {paths?: Record<string, Record<string, Operation>>},
method: string,
path: string,
): Operation | undefined {
const pathItem = doc.paths?.[path];
return pathItem?.[method.toLowerCase()];
}
function extractOperationRef(mdxBody: string): {method: string; path: string} | undefined {
const block = mdxBody.match(/operations=\{(\[[\s\S]*?\])\}/);
if (!block) return undefined;
const pathMatch = block[1].match(/['"]?path['"]?\s*:\s*['"]([^'"]+)['"]/);
const methodMatch = block[1].match(/['"]?method['"]?\s*:\s*['"]([^'"]+)['"]/);
if (!pathMatch || !methodMatch) return undefined;
return {path: pathMatch[1], method: methodMatch[1]};
}
export async function renderOpenAPIOperationFromMDX(
mdxBody: string,
fallbackTitle: string,
pageUrl: string,
): Promise<string | undefined> {
const ref = extractOperationRef(mdxBody);
if (!ref) return undefined;
const schemas = await openapi.getSchemas();
const first = Object.values(schemas)[0];
if (!first) return undefined;
const doc = first.dereferenced as {
servers?: Array<{url: string}>;
paths?: Record<string, Record<string, Operation>>;
};
const op = findOperationByMethodPath(doc, ref.method, ref.path);
if (!op) return undefined;
const lines: string[] = [];
const method = ref.method.toUpperCase();
const baseUrl = doc.servers?.[0]?.url ?? '';
lines.push(`# ${op.summary ?? fallbackTitle} (${pageUrl})`);
lines.push('');
lines.push(`\`${method} ${ref.path}\``);
lines.push('');
if (baseUrl) {
lines.push(`Base URL: \`${baseUrl}\``);
lines.push('');
}
if (op.description) {
lines.push(op.description);
lines.push('');
}
if (op.deprecated) {
lines.push('> **Deprecated.** This endpoint should not be used in new integrations.');
lines.push('');
}
if (op.parameters && op.parameters.length > 0) {
const grouped: Record<string, Parameter[]> = {};
for (const p of op.parameters) (grouped[p.in] ??= []).push(p);
for (const [location, params] of Object.entries(grouped)) {
lines.push(`## ${location[0].toUpperCase()}${location.slice(1)} parameters`);
lines.push('');
for (const p of params) {
const req = p.required ? ' (required)' : '';
const desc = p.description ? `${p.description.replace(/\n+/g, ' ')}` : '';
lines.push(`- \`${p.name}\`: ${typeLabel(p.schema)}${req}${desc}`);
}
lines.push('');
}
}
const body = op.requestBody?.content?.['application/json']?.schema;
if (body) {
lines.push('## Request body');
lines.push('');
if (op.requestBody?.description) {
lines.push(op.requestBody.description);
lines.push('');
}
const tree = renderSchemaTree(body);
if (tree.length > 0) {
lines.push(...tree);
lines.push('');
}
const example = exampleFromSchema(body);
if (example !== undefined) {
lines.push('Example:');
lines.push('');
lines.push('```json');
lines.push(JSON.stringify(example, null, 2));
lines.push('```');
lines.push('');
}
}
if (op.responses) {
lines.push('## Responses');
lines.push('');
for (const [status, resp] of Object.entries(op.responses)) {
const desc = resp.description ? `${resp.description.replace(/\n+/g, ' ')}` : '';
lines.push(`### \`${status}\`${desc}`);
lines.push('');
const schema = resp.content?.['application/json']?.schema;
if (schema) {
const tree = renderSchemaTree(schema);
if (tree.length > 0) {
lines.push(...tree);
lines.push('');
}
const example = exampleFromSchema(schema);
if (example !== undefined) {
lines.push('```json');
lines.push(JSON.stringify(example, null, 2));
lines.push('```');
lines.push('');
}
}
}
}
if (baseUrl) {
lines.push('## Example request');
lines.push('');
lines.push('```bash');
const curlParts = [`curl -X ${method} '${baseUrl}${ref.path}'`, " -H 'Authorization: Bearer YOUR_API_KEY'"];
if (body) {
curlParts.push(" -H 'Content-Type: application/json'");
const example = exampleFromSchema(body);
curlParts.push(` -d '${JSON.stringify(example)}'`);
}
lines.push(curlParts.join(' \\\n'));
lines.push('```');
lines.push('');
}
return lines.join('\n');
}
+2 -3
View File
@@ -26,7 +26,7 @@ function getQ(types: Array<{ type: string; q: number }>, target: string): number
function negotiate(accept: string): Negotiated { function negotiate(accept: string): Negotiated {
if (!accept) return 'html'; if (!accept) return 'html';
const types = parseAccept(accept); const types = parseAccept(accept);
const mdQ = types.find(t => t.type === 'text/markdown')?.q ?? -1; const mdQ = getQ(types, 'text/markdown');
const htmlQ = getQ(types, 'text/html'); const htmlQ = getQ(types, 'text/html');
if (mdQ <= 0 && htmlQ <= 0) return 'none'; if (mdQ <= 0 && htmlQ <= 0) return 'none';
if (mdQ > 0 && mdQ >= htmlQ) return 'markdown'; if (mdQ > 0 && mdQ >= htmlQ) return 'markdown';
@@ -57,10 +57,9 @@ export function middleware(request: NextRequest) {
const response = NextResponse.next(); const response = NextResponse.next();
response.headers.set('Vary', 'Accept'); response.headers.set('Vary', 'Accept');
response.headers.append('Link', `<${pathname}.md>; rel="alternate"; type="text/markdown"`);
return response; return response;
} }
export const config = { export const config = {
matcher: ['/((?!llms\\.mdx|api/search|openapi\\.json|_next|.*\\.(?:png|jpg|jpeg|gif|svg|ico|webp|woff|woff2|ttf|css|js|json|xml|txt|webmanifest)).*)',], matcher: ['/((?!llms\\.mdx|api/search|_next|.*\\.(?:png|jpg|jpeg|gif|svg|ico|webp|woff|woff2|ttf|css|js|xml|txt|webmanifest)).*)',],
}; };
+1 -1
View File
@@ -21,7 +21,7 @@
"fumadocs-openapi": "^10.0.11", "fumadocs-openapi": "^10.0.11",
"fumadocs-ui": "16.0.8", "fumadocs-ui": "16.0.8",
"lucide-react": "^0.553.0", "lucide-react": "^0.553.0",
"next": "^16.2.3", "next": "^16.2.6",
"next-sitemap": "^4.2.3", "next-sitemap": "^4.2.3",
"react": "^19.2.3", "react": "^19.2.3",
"react-dom": "^19.2.3", "react-dom": "^19.2.3",
-83
View File
@@ -1,83 +0,0 @@
# Plunk Documentation
> Documentation for Plunk, an open-source email platform for developers. Covers core concepts, integration guides, the REST API, and self-hosting.
Every documentation page is available as Markdown by appending `.md` to the path (for example, `https://docs.useplunk.com/concepts/contacts.md`), or by requesting the page URL with `Accept: text/markdown`. API reference endpoints render the OpenAPI operation — including parameters, request/response schemas, and a sample curl — directly into the Markdown response.
The full OpenAPI specification is available at [https://docs.useplunk.com/openapi.json](https://docs.useplunk.com/openapi.json).
## Getting Started
- [Welcome to Plunk](https://docs.useplunk.com/index.md): What Plunk is and how to get started
## Concepts
- [Contacts](https://docs.useplunk.com/concepts/contacts.md): Manage and organize your contacts
- [Segments](https://docs.useplunk.com/concepts/segments.md): Group and target contacts with dynamic or static segments
- [Templates](https://docs.useplunk.com/concepts/templates.md): Reusable email templates for campaigns, workflows, and transactional emails
- [Campaigns](https://docs.useplunk.com/concepts/campaigns.md): One-off broadcast emails sent to a defined audience
- [Workflows](https://docs.useplunk.com/concepts/workflows.md): Automated, multi-step journeys triggered by events, segments, schedules, or manual entry
- [Transactional emails](https://docs.useplunk.com/concepts/transactional-emails.md): Send emails via API
- [Billing](https://docs.useplunk.com/concepts/billing.md): How Plunk's pricing, limits, and consumption work
## Guides
- [API keys](https://docs.useplunk.com/guides/api-keys.md): Plunk's two-key model and how to rotate or revoke keys safely
- [Verifying domains](https://docs.useplunk.com/guides/verifying-domains.md): Verify sending domains so emails reach the inbox
- [Tracking](https://docs.useplunk.com/guides/tracking.md): Track opens and clicks on emails sent through Plunk
- [Webhooks](https://docs.useplunk.com/guides/webhooks.md): Send real-time event data from Plunk to your own application
- [Receiving emails](https://docs.useplunk.com/guides/receiving-emails.md): Receive inbound email at your verified domain and turn it into events
- [Custom fields](https://docs.useplunk.com/guides/custom-fields.md): Store arbitrary data on contacts and use it for personalization and segmentation
- [Segment filter reference](https://docs.useplunk.com/guides/segment-filters.md): How to write filters for dynamic segments, campaign audiences, and workflow conditions
- [Importing contacts from CSV](https://docs.useplunk.com/guides/importing-contacts.md): Bulk-load contacts and their custom fields
- [Unsubscribe & preferences pages](https://docs.useplunk.com/guides/unsubscribe-pages.md): Hosted pages for unsubscribe, resubscribe, and preference management
- [Localization](https://docs.useplunk.com/guides/localization.md): Translate the unsubscribe footer and contact-facing pages
- [List hygiene](https://docs.useplunk.com/guides/list-hygiene.md): Maintain a healthy email list
## API Reference
- [API overview](https://docs.useplunk.com/api-reference/overview.md): Complete Plunk API documentation
- [Error codes](https://docs.useplunk.com/api-reference/errors.md): API error codes and troubleshooting
### Public API
- [Send transactional email](https://docs.useplunk.com/api-reference/public-api/sendEmail.md): POST — send a transactional email; auto-creates/updates contacts
- [Track event](https://docs.useplunk.com/api-reference/public-api/trackEvent.md): POST — track an event for a contact
- [Verify email address](https://docs.useplunk.com/api-reference/public-api/verifyEmail.md): POST — validate an address, check disposable/MX/typos
### Contacts
- [Create or update contact](https://docs.useplunk.com/api-reference/contacts/createContact.md): POST — upsert by email
- [Get contact](https://docs.useplunk.com/api-reference/contacts/getContact.md): GET — single contact by ID
- [List contacts](https://docs.useplunk.com/api-reference/contacts/listContacts.md): GET — paginated, cursor-based
- [Update contact](https://docs.useplunk.com/api-reference/contacts/updateContact.md): PATCH
- [Delete contact](https://docs.useplunk.com/api-reference/contacts/deleteContact.md): DELETE
### Campaigns
- [Create campaign](https://docs.useplunk.com/api-reference/campaigns/createCampaign.md): POST
- [List campaigns](https://docs.useplunk.com/api-reference/campaigns/listCampaigns.md): GET — paginated
- [Send or schedule campaign](https://docs.useplunk.com/api-reference/campaigns/sendCampaign.md): POST — send immediately or schedule
### Templates
- [Create template](https://docs.useplunk.com/api-reference/templates/createTemplate.md): POST
- [List templates](https://docs.useplunk.com/api-reference/templates/listTemplates.md): GET — paginated
### Segments
- [Create segment](https://docs.useplunk.com/api-reference/segments/createSegment.md): POST
- [List segments](https://docs.useplunk.com/api-reference/segments/listSegments.md): GET
## Self-Hosting
- [Self-hosting introduction](https://docs.useplunk.com/self-hosting/introduction.md): Deploy Plunk on your own infrastructure
- [Docker deployment](https://docs.useplunk.com/self-hosting/docker.md): Deploy with Docker Compose
- [Environment variables](https://docs.useplunk.com/self-hosting/environment-variables.md): Configuration reference
- [AWS SES setup](https://docs.useplunk.com/self-hosting/email-setup.md): Configure email delivery
## Optional
- [Marketing site](https://www.useplunk.com)
- [GitHub repository](https://github.com/useplunk/plunk)
- [Discord community](https://www.useplunk.com/discord)
-12
View File
@@ -154,10 +154,6 @@ services:
SES_CONFIGURATION_SET: ${SES_CONFIGURATION_SET} SES_CONFIGURATION_SET: ${SES_CONFIGURATION_SET}
SES_CONFIGURATION_SET_NO_TRACKING: ${SES_CONFIGURATION_SET_NO_TRACKING:-} SES_CONFIGURATION_SET_NO_TRACKING: ${SES_CONFIGURATION_SET_NO_TRACKING:-}
# Custom MAIL FROM subdomain (defaults to 'plunk'; override when
# plunk.<your-domain> is already used for something else, e.g. a CDN)
MAIL_FROM_SUBDOMAIN: ${MAIL_FROM_SUBDOMAIN:-}
# Optional: OAuth # Optional: OAuth
GITHUB_OAUTH_CLIENT: ${GITHUB_OAUTH_CLIENT:-} GITHUB_OAUTH_CLIENT: ${GITHUB_OAUTH_CLIENT:-}
GITHUB_OAUTH_SECRET: ${GITHUB_OAUTH_SECRET:-} GITHUB_OAUTH_SECRET: ${GITHUB_OAUTH_SECRET:-}
@@ -194,14 +190,6 @@ services:
# Security # Security
AUTO_PROJECT_DISABLE: ${AUTO_PROJECT_DISABLE:-false} AUTO_PROJECT_DISABLE: ${AUTO_PROJECT_DISABLE:-false}
# Self-hosting user management (documented in .env.self-host.example
# and read by apps/api/src/app/constants.ts at import time)
DISABLE_SIGNUPS: ${DISABLE_SIGNUPS:-false}
# Explicit SES sending rate (avoid silent fallback to 14/sec when
# ses:GetSendQuota is denied or transiently fails at worker startup)
EMAIL_RATE_LIMIT_PER_SECOND: ${EMAIL_RATE_LIMIT_PER_SECOND:-}
volumes: volumes:
# Persistent storage for application data # Persistent storage for application data
- plunk_data:/app/data - plunk_data:/app/data
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "plunk", "name": "plunk",
"version": "0.12.0", "version": "0.10.0",
"private": true, "private": true,
"scripts": { "scripts": {
"build": "turbo build", "build": "turbo build",
@@ -1,5 +0,0 @@
-- CreateEnum
CREATE TYPE "ProjectDisabledReason" AS ENUM ('PAYMENT_FAILED', 'EMAIL_REPUTATION', 'PHISHING_DETECTED', 'MANUAL');
-- AlterTable
ALTER TABLE "projects" ADD COLUMN "disabledReason" "ProjectDisabledReason";
+1 -9
View File
@@ -43,8 +43,7 @@ model Project {
secret String @unique secret String @unique
// Admin // Admin
disabled Boolean @default(false) disabled Boolean @default(false)
disabledReason ProjectDisabledReason?
// Billing // Billing
customer String? @unique customer String? @unique
@@ -633,13 +632,6 @@ model Event {
// ENUMS // ENUMS
// ============================================ // ============================================
enum ProjectDisabledReason {
PAYMENT_FAILED // Subscription renewal payment failed
EMAIL_REPUTATION // Bounce or complaint rate thresholds exceeded
PHISHING_DETECTED // Phishing content detected by LLM scan
MANUAL // Disabled by support/admin (e.g. directly in DB)
}
enum AuthMethod { enum AuthMethod {
PASSWORD PASSWORD
GOOGLE_OAUTH GOOGLE_OAUTH
+78 -86
View File
@@ -1,50 +1,6 @@
import {PrismaClient} from '@plunk/db'; import {PrismaClient} from '@plunk/db';
import {execSync} from 'child_process'; import {execSync} from 'child_process';
// Snake-cased table names from prisma schema (see @@map directives).
// Order doesn't matter — TRUNCATE with CASCADE handles FK dependencies in one statement.
const TRUNCATE_TABLES = [
'events',
'workflow_step_executions',
'emails',
'workflow_executions',
'workflow_transitions',
'workflow_steps',
'workflows',
'campaigns',
'templates',
'segment_memberships',
'segments',
'contacts',
'domains',
'memberships',
'projects',
'users',
];
/**
* Connects to the admin `postgres` database to ensure the worker's test DB exists.
* Postgres has no `CREATE DATABASE IF NOT EXISTS`, so we check pg_database first.
*/
async function ensureDatabaseExists(databaseUrl: string, workerDbName: string) {
const adminUrl = new URL(databaseUrl);
adminUrl.pathname = '/postgres';
adminUrl.searchParams.delete('connection_limit');
adminUrl.searchParams.delete('pool_timeout');
const admin = new PrismaClient({datasources: {db: {url: adminUrl.toString()}}});
try {
const rows = await admin.$queryRawUnsafe<{exists: boolean}[]>(
`SELECT EXISTS(SELECT 1 FROM pg_database WHERE datname = '${workerDbName}') AS exists`,
);
if (!rows[0]?.exists) {
await admin.$executeRawUnsafe(`CREATE DATABASE "${workerDbName}"`);
}
} finally {
await admin.$disconnect();
}
}
/** /**
* Test database helper * Test database helper
* Manages test database isolation and cleanup * Manages test database isolation and cleanup
@@ -53,56 +9,44 @@ class TestDatabase {
private prisma: PrismaClient | null = null; private prisma: PrismaClient | null = null;
async initialize() { async initialize() {
// setup.ts has already rewritten DATABASE_URL to include the per-worker DB name // Use test database URL if provided, otherwise use main database
// (e.g. plunk_test_w1, plunk_test_w2). We create that DB if missing, migrate it,
// then open the long-lived client we use for tests.
const databaseUrl = process.env.TEST_DATABASE_URL || process.env.DATABASE_URL; const databaseUrl = process.env.TEST_DATABASE_URL || process.env.DATABASE_URL;
if (!databaseUrl) { if (!databaseUrl) {
throw new Error('DATABASE_URL or TEST_DATABASE_URL must be set for testing'); throw new Error('DATABASE_URL or TEST_DATABASE_URL must be set for testing');
} }
const url = new URL(databaseUrl); // Create Prisma client with connection pool limits
const workerDbName = url.pathname.replace(/^\//, ''); this.prisma = new PrismaClient({
if (!workerDbName) { datasources: {
throw new Error('DATABASE_URL must include a database name'); db: {
} url: databaseUrl,
},
},
// Limit connection pool to prevent memory issues in tests
// @ts-ignore - These options exist but may not be in types
__internal: {
engine: {
connection_limit: 5,
},
},
});
// Bump the pool above Prisma's default (~5 on CI). Test Postgres has // Connect to database
// max_connections=100; with N workers we want N*20 ≤ 100 — fine up to 4 workers. await this.prisma.$connect();
if (!url.searchParams.has('connection_limit')) {
url.searchParams.set('connection_limit', '20');
}
if (!url.searchParams.has('pool_timeout')) {
url.searchParams.set('pool_timeout', '20');
}
await ensureDatabaseExists(databaseUrl, workerDbName); // Run migrations (only once per test suite)
// Run pending migrations against this worker's DB. `migrate deploy` is a no-op
// when up-to-date and avoids the drift prompts that `migrate dev` does.
try { try {
execSync('yarn workspace @plunk/db migrate:prod', { execSync('yarn workspace @plunk/db migrate:dev', {
env: { env: {
...process.env, ...process.env,
DATABASE_URL: url.toString(), DATABASE_URL: databaseUrl,
DIRECT_DATABASE_URL: process.env.DIRECT_DATABASE_URL || url.toString(),
}, },
encoding: 'utf8', stdio: 'ignore',
stdio: ['ignore', 'pipe', 'pipe'],
}); });
} catch (error) { } catch (error) {
const err = error as {stdout?: string; stderr?: string; message?: string}; console.warn('Migration warning (may already be up to date):', error);
console.error('Migration failed for', workerDbName);
if (err.stdout) console.error('stdout:', err.stdout);
if (err.stderr) console.error('stderr:', err.stderr);
if (!err.stdout && !err.stderr) console.error(err.message);
throw error;
} }
this.prisma = new PrismaClient({
datasources: {db: {url: url.toString()}},
});
await this.prisma.$connect();
} }
/** /**
@@ -116,32 +60,80 @@ class TestDatabase {
} }
/** /**
* Wipe all per-test data with a single TRUNCATE ... CASCADE statement. * Clean up database after each test
* Roughly an order of magnitude faster than 14 sequential deleteMany calls * Deletes all records in reverse order of dependencies
* TRUNCATE skips the row scan and only touches table headers. * Uses batched deletes to prevent memory issues with large datasets
* Retries on deadlock to handle race conditions with background event tracking
*/ */
async cleanup() { async cleanup() {
if (!this.prisma) return; if (!this.prisma) return;
const tables = TRUNCATE_TABLES.map(t => `"${t}"`).join(', ');
const maxRetries = 3; const maxRetries = 3;
let lastError: Error | null = null; let lastError: Error | null = null;
for (let attempt = 1; attempt <= maxRetries; attempt++) { for (let attempt = 1; attempt <= maxRetries; attempt++) {
try { try {
await this.prisma.$executeRawUnsafe(`TRUNCATE TABLE ${tables} RESTART IDENTITY CASCADE`); // Use a transaction to ensure all deletes happen atomically
// This prevents foreign key constraint violations and race conditions
await this.prisma.$transaction([
// Level 1: Delete deepest dependencies first
this.prisma.event.deleteMany(),
this.prisma.workflowStepExecution.deleteMany(),
// Level 2: Delete entities that depend on Level 1
this.prisma.email.deleteMany(),
this.prisma.workflowExecution.deleteMany(),
// Level 3: Delete workflow structure
this.prisma.workflowTransition.deleteMany(),
this.prisma.workflowStep.deleteMany(),
this.prisma.workflow.deleteMany(),
// Level 4: Delete campaigns and templates
this.prisma.campaign.deleteMany(),
this.prisma.template.deleteMany(),
// Level 5: Delete segment relationships
this.prisma.segmentMembership.deleteMany(),
this.prisma.segment.deleteMany(),
// Level 6: Delete contacts
this.prisma.contact.deleteMany(),
// Level 7: Delete domains
this.prisma.domain.deleteMany(),
// Level 8: Delete memberships (has FK to both user and project)
this.prisma.membership.deleteMany(),
// Level 9: Delete projects
this.prisma.project.deleteMany(),
// Level 10: Delete users last
this.prisma.user.deleteMany(),
]);
// Success - exit retry loop
return; return;
} catch (error) { } catch (error) {
lastError = error as Error; lastError = error as Error;
// Check if this is a deadlock error (PostgreSQL error code 40P01)
const isDeadlock = error instanceof Error && error.message?.includes('deadlock detected'); const isDeadlock = error instanceof Error && error.message?.includes('deadlock detected');
if (isDeadlock && attempt < maxRetries) { if (isDeadlock && attempt < maxRetries) {
await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 50)); // Wait before retrying (exponential backoff)
const delay = Math.pow(2, attempt) * 50; // 100ms, 200ms, 400ms
await new Promise(resolve => setTimeout(resolve, delay));
continue; continue;
} }
// Not a deadlock or out of retries
break; break;
} }
} }
// If we get here, all retries failed
console.error(`Error cleaning up database after ${maxRetries} attempts:`, lastError); console.error(`Error cleaning up database after ${maxRetries} attempts:`, lastError);
throw lastError; throw lastError;
} }
+1 -3
View File
@@ -108,9 +108,7 @@ export class TestFactories {
async createUser(options: UserFactoryOptions = {}) { async createUser(options: UserFactoryOptions = {}) {
const email = options.email || `user-${uniqueId()}@test.com`; const email = options.email || `user-${uniqueId()}@test.com`;
const password = options.password || 'password123'; const password = options.password || 'password123';
// Cost factor 4 is the bcrypt minimum — ~100x faster than the production cost of 10. const hashedPassword = await bcrypt.hash(password, 10);
// Test users don't need real-world hash strength.
const hashedPassword = await bcrypt.hash(password, 4);
return this.prisma.user.create({ return this.prisma.user.create({
data: { data: {
+22 -35
View File
@@ -1,52 +1,39 @@
// IMPORTANT: this file runs before each test file's imports execute. import { beforeAll, afterAll, afterEach, vi } from 'vitest';
// We rewrite DATABASE_URL and REDIS_URL here so per-worker isolation is import { testDatabase } from './helpers/database';
// applied before any service module constructs a Prisma/Redis client.
import dotenv from 'dotenv'; import dotenv from 'dotenv';
import path from 'path'; import path from 'path';
import {afterAll, afterEach, beforeAll, vi} from 'vitest';
dotenv.config({path: path.resolve(__dirname, '../.env')}); // Load environment variables from root .env file
dotenv.config({ path: path.resolve(__dirname, '../.env') });
// Vitest assigns each worker a 1-based pool id; defaults to "1" for single-worker runs.
const workerId = process.env.VITEST_POOL_ID || '1';
if (process.env.DATABASE_URL) {
const url = new URL(process.env.DATABASE_URL);
const baseDb = url.pathname.replace(/^\//, '') || 'plunk_test';
url.pathname = `/${baseDb}_w${workerId}`;
process.env.DATABASE_URL = url.toString();
// Mirror onto DIRECT_DATABASE_URL so prisma migrate uses the same worker DB.
if (process.env.DIRECT_DATABASE_URL) {
const direct = new URL(process.env.DIRECT_DATABASE_URL);
direct.pathname = `/${baseDb}_w${workerId}`;
process.env.DIRECT_DATABASE_URL = direct.toString();
}
}
if (process.env.REDIS_URL) {
const url = new URL(process.env.REDIS_URL);
url.pathname = `/${(parseInt(workerId, 10) - 1) % 16}`;
process.env.REDIS_URL = url.toString();
}
process.env.NODE_ENV = 'test';
process.env.JWT_SECRET = process.env.JWT_SECRET || 'test-jwt-secret-key-for-testing';
// Static import is safe: database.ts only reads env in initialize(), which runs
// in beforeAll — well after the env mutations above.
import {testDatabase} from './helpers/database';
// Global test setup
beforeAll(async () => { beforeAll(async () => {
// Initialize test database
await testDatabase.initialize(); await testDatabase.initialize();
}); });
afterEach(async () => { afterEach(async () => {
// Clear all mocks first
vi.clearAllMocks(); vi.clearAllMocks();
// Restore real timers
vi.useRealTimers(); vi.useRealTimers();
// Clean up database after each test
// This must be last to ensure proper cleanup order
await testDatabase.cleanup(); await testDatabase.cleanup();
// Force garbage collection hint (if available in test environment)
if (global.gc) {
global.gc();
}
}); });
afterAll(async () => { afterAll(async () => {
// Disconnect from database
await testDatabase.disconnect(); await testDatabase.disconnect();
}); });
// Set test environment variables
process.env.NODE_ENV = 'test';
process.env.JWT_SECRET = process.env.JWT_SECRET || 'test-jwt-secret-key-for-testing';
+7 -8
View File
@@ -22,19 +22,18 @@ export default defineConfig({
}, },
testTimeout: 30000, testTimeout: 30000,
hookTimeout: 30000, hookTimeout: 30000,
// Each fork is a worker with an isolated Postgres database and Redis db-number // Memory optimization: Run tests in sequence to prevent memory issues
// (see test/setup.ts). That isolation is what lets us run files in parallel // This is critical for tests that create large datasets
// without the cross-test interference we used to hit with a shared DB.
pool: 'forks', pool: 'forks',
poolOptions: { poolOptions: {
forks: { forks: {
// Cap at 4 to stay within Postgres' default max_connections=100 singleFork: true, // Run all tests in a single fork to limit memory
// when each worker uses connection_limit=20.
maxForks: 4,
minForks: 1,
}, },
}, },
maxConcurrency: 5, // Run tests sequentially to avoid database cleanup conflicts
fileParallelism: false,
// Limit concurrent test files to reduce memory pressure
maxConcurrency: 3,
// Only include our test files, not dependency tests // Only include our test files, not dependency tests
include: [ include: [
'apps/**/__tests__/**/*.{test,spec}.{ts,tsx}', 'apps/**/__tests__/**/*.{test,spec}.{ts,tsx}',
+44 -44
View File
@@ -3003,10 +3003,10 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"@next/env@npm:16.2.3": "@next/env@npm:16.2.6":
version: 16.2.3 version: 16.2.6
resolution: "@next/env@npm:16.2.3" resolution: "@next/env@npm:16.2.6"
checksum: 10c0/56c3fee8ea226efe59ef065e054380f872c00c45c9fe4475eaa45f80773c3c1adc3ead3ccdd77447d3c1aeb4b3004aaaa033dd4a100d3e572fd01b83f992dde8 checksum: 10c0/466722ce30a9561d29c08a7ba78091a47fef3644f422d04751c7124a24457ffe11eb25bb6c59c1e1d57735d9c68c58d185cc19ea58befd7a9c5b81dc05ca550d
languageName: node languageName: node
linkType: hard linkType: hard
@@ -3033,9 +3033,9 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"@next/swc-darwin-arm64@npm:16.2.3": "@next/swc-darwin-arm64@npm:16.2.6":
version: 16.2.3 version: 16.2.6
resolution: "@next/swc-darwin-arm64@npm:16.2.3" resolution: "@next/swc-darwin-arm64@npm:16.2.6"
conditions: os=darwin & cpu=arm64 conditions: os=darwin & cpu=arm64
languageName: node languageName: node
linkType: hard linkType: hard
@@ -3047,9 +3047,9 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"@next/swc-darwin-x64@npm:16.2.3": "@next/swc-darwin-x64@npm:16.2.6":
version: 16.2.3 version: 16.2.6
resolution: "@next/swc-darwin-x64@npm:16.2.3" resolution: "@next/swc-darwin-x64@npm:16.2.6"
conditions: os=darwin & cpu=x64 conditions: os=darwin & cpu=x64
languageName: node languageName: node
linkType: hard linkType: hard
@@ -3061,9 +3061,9 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"@next/swc-linux-arm64-gnu@npm:16.2.3": "@next/swc-linux-arm64-gnu@npm:16.2.6":
version: 16.2.3 version: 16.2.6
resolution: "@next/swc-linux-arm64-gnu@npm:16.2.3" resolution: "@next/swc-linux-arm64-gnu@npm:16.2.6"
conditions: os=linux & cpu=arm64 & libc=glibc conditions: os=linux & cpu=arm64 & libc=glibc
languageName: node languageName: node
linkType: hard linkType: hard
@@ -3075,9 +3075,9 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"@next/swc-linux-arm64-musl@npm:16.2.3": "@next/swc-linux-arm64-musl@npm:16.2.6":
version: 16.2.3 version: 16.2.6
resolution: "@next/swc-linux-arm64-musl@npm:16.2.3" resolution: "@next/swc-linux-arm64-musl@npm:16.2.6"
conditions: os=linux & cpu=arm64 & libc=musl conditions: os=linux & cpu=arm64 & libc=musl
languageName: node languageName: node
linkType: hard linkType: hard
@@ -3089,9 +3089,9 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"@next/swc-linux-x64-gnu@npm:16.2.3": "@next/swc-linux-x64-gnu@npm:16.2.6":
version: 16.2.3 version: 16.2.6
resolution: "@next/swc-linux-x64-gnu@npm:16.2.3" resolution: "@next/swc-linux-x64-gnu@npm:16.2.6"
conditions: os=linux & cpu=x64 & libc=glibc conditions: os=linux & cpu=x64 & libc=glibc
languageName: node languageName: node
linkType: hard linkType: hard
@@ -3103,9 +3103,9 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"@next/swc-linux-x64-musl@npm:16.2.3": "@next/swc-linux-x64-musl@npm:16.2.6":
version: 16.2.3 version: 16.2.6
resolution: "@next/swc-linux-x64-musl@npm:16.2.3" resolution: "@next/swc-linux-x64-musl@npm:16.2.6"
conditions: os=linux & cpu=x64 & libc=musl conditions: os=linux & cpu=x64 & libc=musl
languageName: node languageName: node
linkType: hard linkType: hard
@@ -3117,9 +3117,9 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"@next/swc-win32-arm64-msvc@npm:16.2.3": "@next/swc-win32-arm64-msvc@npm:16.2.6":
version: 16.2.3 version: 16.2.6
resolution: "@next/swc-win32-arm64-msvc@npm:16.2.3" resolution: "@next/swc-win32-arm64-msvc@npm:16.2.6"
conditions: os=win32 & cpu=arm64 conditions: os=win32 & cpu=arm64
languageName: node languageName: node
linkType: hard linkType: hard
@@ -3131,9 +3131,9 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"@next/swc-win32-x64-msvc@npm:16.2.3": "@next/swc-win32-x64-msvc@npm:16.2.6":
version: 16.2.3 version: 16.2.6
resolution: "@next/swc-win32-x64-msvc@npm:16.2.3" resolution: "@next/swc-win32-x64-msvc@npm:16.2.6"
conditions: os=win32 & cpu=x64 conditions: os=win32 & cpu=x64
languageName: node languageName: node
linkType: hard linkType: hard
@@ -13263,7 +13263,7 @@ __metadata:
eslint-config-next: "npm:^16.0.1" eslint-config-next: "npm:^16.0.1"
juice: "npm:^11.0.3" juice: "npm:^11.0.3"
lucide-react: "npm:^0.553.0" lucide-react: "npm:^0.553.0"
next: "npm:^16.2.3" next: "npm:^16.2.6"
next-seo: "npm:^6.6.0" next-seo: "npm:^6.6.0"
next-sitemap: "npm:^4.2.3" next-sitemap: "npm:^4.2.3"
postcss: "npm:^8.4.33" postcss: "npm:^8.4.33"
@@ -15042,19 +15042,19 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"next@npm:^16.2.3": "next@npm:^16.2.6":
version: 16.2.3 version: 16.2.6
resolution: "next@npm:16.2.3" resolution: "next@npm:16.2.6"
dependencies: dependencies:
"@next/env": "npm:16.2.3" "@next/env": "npm:16.2.6"
"@next/swc-darwin-arm64": "npm:16.2.3" "@next/swc-darwin-arm64": "npm:16.2.6"
"@next/swc-darwin-x64": "npm:16.2.3" "@next/swc-darwin-x64": "npm:16.2.6"
"@next/swc-linux-arm64-gnu": "npm:16.2.3" "@next/swc-linux-arm64-gnu": "npm:16.2.6"
"@next/swc-linux-arm64-musl": "npm:16.2.3" "@next/swc-linux-arm64-musl": "npm:16.2.6"
"@next/swc-linux-x64-gnu": "npm:16.2.3" "@next/swc-linux-x64-gnu": "npm:16.2.6"
"@next/swc-linux-x64-musl": "npm:16.2.3" "@next/swc-linux-x64-musl": "npm:16.2.6"
"@next/swc-win32-arm64-msvc": "npm:16.2.3" "@next/swc-win32-arm64-msvc": "npm:16.2.6"
"@next/swc-win32-x64-msvc": "npm:16.2.3" "@next/swc-win32-x64-msvc": "npm:16.2.6"
"@swc/helpers": "npm:0.5.15" "@swc/helpers": "npm:0.5.15"
baseline-browser-mapping: "npm:^2.9.19" baseline-browser-mapping: "npm:^2.9.19"
caniuse-lite: "npm:^1.0.30001579" caniuse-lite: "npm:^1.0.30001579"
@@ -15098,7 +15098,7 @@ __metadata:
optional: true optional: true
bin: bin:
next: dist/bin/next next: dist/bin/next
checksum: 10c0/8a9d27fc773d69f7f471cf1a23bde2ab2950e0411ef3e0d5c1664ed9654e94c3304eae1c4283ec0fa4e70e7b3f4416913350e118e0c18e8b055693dc5d021883 checksum: 10c0/3572071eb0e8051c3b007224dcf642037ce27a2f4b75c45f7e0fe7f2343e98e66604ce8696dde56ecd72963900d330d3a3af0f068f34cfc67520180263effa5f
languageName: node languageName: node
linkType: hard linkType: hard
@@ -19539,7 +19539,7 @@ __metadata:
framer-motion: "npm:^12.23.24" framer-motion: "npm:^12.23.24"
juice: "npm:^11.0.3" juice: "npm:^11.0.3"
lucide-react: "npm:^0.553.0" lucide-react: "npm:^0.553.0"
next: "npm:^16.2.3" next: "npm:^16.2.6"
next-seo: "npm:^6.6.0" next-seo: "npm:^6.6.0"
next-sitemap: "npm:^4.2.3" next-sitemap: "npm:^4.2.3"
nuqs: "npm:^2.7.3" nuqs: "npm:^2.7.3"
@@ -19736,7 +19736,7 @@ __metadata:
fumadocs-openapi: "npm:^10.0.11" fumadocs-openapi: "npm:^10.0.11"
fumadocs-ui: "npm:16.0.8" fumadocs-ui: "npm:16.0.8"
lucide-react: "npm:^0.553.0" lucide-react: "npm:^0.553.0"
next: "npm:^16.2.3" next: "npm:^16.2.6"
next-sitemap: "npm:^4.2.3" next-sitemap: "npm:^4.2.3"
postcss: "npm:^8.4.33" postcss: "npm:^8.4.33"
react: "npm:^19.2.3" react: "npm:^19.2.3"