scribase.com/docs/mail returns 404; the real page is
https://docs.scribase.com/docs/concepts/mail. Update DOCS_URL in both
apps (web + marketing) and route the three hardcoded Docs hrefs
(sidebar, both "Read the docs" buttons) through the constant so the
URL lives in one place per app.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Domain.tlsMode's ENFORCED setting was stored (Resend's tls: "enforced")
but never read: every send used the same opportunistic-TLS transport,
so a domain configured as enforced got silently downgraded. Threads
requireTls through SendRawEmailInput from the from-domain's tlsMode,
and GenericSmtpProvider now routes an enforced send through a dedicated
STARTTLS/implicit-TLS-required transport, refusing the send outright
rather than falling back to the default transport when no TLS-capable
relay is configured.
PATCH /domains/:id now only rejects tls: "enforced" for OCI (which has
no such switch yet, same 422 as before); the self-hosted SMTP provider
accepts and actually honors it.
Resend parity: POST /domains/claim. Adding a domain whose name is
already verified under a different team (moving it between two of
your own teams, or taking over one a previous integration added)
previously had no path at all other than a raw Prisma unique-
constraint error from createDomain.
Adds a DomainClaim model (name is globally unique on Domain, so a
second row for the same name can't exist until ownership actually
transfers) plus claimDomain/verifyDomainClaim in domain-service.ts.
Claiming issues a one-time TXT record and never re-touches the email
provider: the existing Domain row already has working DKIM/SPF/MX, so
once the requester proves DNS control, ownership transfers via one
db.$transaction (claim -> VERIFIED, domain.teamId -> requester) with
zero re-verification wait. The hourly domain-verification job now
also polls pending claims the same way it polls pending domains.
Verified against a real local Postgres: migration applies cleanly,
the unique index genuinely rejects a duplicate pending claim, and a
direct (non-mocked) claim+transfer round trip persists correctly on
re-read. 28/28 domain-service unit tests, 7/7 new + existing resend
domains API tests, 4/4 verification-job tests, full apps/web
`tsc --noEmit` and eslint clean.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
apps/web/src/app/page.tsx unconditionally redirect()ed every anonymous
visitor to /login (a bare auth form, no value-prop copy). The real,
already-written marketing homepage -- hero, "Looking for a Resend
alternative?" positioning, feature grid, live pricing, "Part of
Scribase" -- lived in apps/marketing (a separate Next.js app, port
3001) but was never wired into deploy/compose.scribase-mail.yml or
Caddy, so it never actually served production traffic.
Ports that content into apps/web (the surface that IS deployed) under
src/components/marketing/*, since apps/web already depends on the same
shared @usesend/ui/@usesend/lib packages the content needs -- smaller
and lower-risk than standing up a second deployed service. page.tsx now
renders MarketingHome for anonymous visitors and keeps the exact same
redirect behavior (dashboard/waitlist) for authenticated ones. Also
ports the /privacy and /terms pages the footer links to (previously
only live at apps/marketing's unused build), so no new dead links are
introduced.
Updates the ai-content comment (added earlier today) to drop the now-
stale "never wired" note -- the llms.txt/index.md AI mirror and the
real human-visible homepage now describe the same page.
Verified for real: tsc --noEmit clean; real `next build` succeeds, all
new routes (/, /privacy, /terms) present in the manifest; ran a real
throwaway Postgres 16 + Redis 7 locally, applied all 8 prisma
migrations, started the real `next start` server and curled it --
`/` returns 200 with the full real marketing HTML (hero, Resend-
alternative section, Free $0/Pro $20/Scale $90 pricing matching
PRICING_PLANS), not a redirect; /login, /privacy, /terms all 200; a
bogus path still 404s; all 5 new public image assets 200; llms.txt/
llms-full.txt/index.md content confirmed to match what a human now
sees. 665/665 existing unit tests pass unchanged.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
mail.scribase.com was missing the llmstxt.org/ai-visibility.org.uk
AI-discoverability pass already shipped this session for scribase.com,
HomePlan, Bidstage, Yokharita Web and Railyard Vend/Toolgate/Insights.
Real finding: apps/web's root page (the only thing actually deployed to
mail.scribase.com) always redirects an anonymous visitor straight to
/login -- there is no marketing/pricing HTML live at `/` today, even
though apps/marketing (real written Resend-alternative copy, d806795) was
fully built and never wired into deploy/compose or Caddy. Rather than
invent new copy or silently pretend a page is live, the new /llms.txt,
/llms-full.txt, /index.md and /ai.txt routes mirror that real,
already-authored apps/marketing copy (hero, Resend-alternative
positioning, features, "Part of Scribase") into the surface that IS
actually deployed, with prices pulled live from the shared
PRICING_PLANS source of truth so they can't drift.
- apps/web/src/lib/ai-content/mail-pages.ts: real content + AI_SUMMARY
- app/llms.txt, app/llms-full.txt, app/ai.txt: new public routes
- app/index.md: per-page markdown mirror with the established header
contract (text/markdown, X-Robots-Tag: noindex/follow, canonical Link)
- app/layout.tsx: <meta name="ai-summary"> + <link rel="alternate"
type="text/markdown"> on the shared root metadata
- login-page.tsx: footer link to /llms.txt next to the existing AGPL
source-code link
Verified locally against a real throwaway Postgres+Redis (not mocked):
next build clean, tsc clean, 665/665 unit tests unchanged, all 4 new
routes curled with correct content-type/headers/body, bogus paths still
404, and the metadata/footer-link changes confirmed present in the real
rendered page payload and compiled bundle.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
The mail-at-scale decision doc flagged that bounce.scribase.com's return-path
CNAME was never set up on the house domain. Tracing the code showed why: the
customReturnPath/returnPathStatus DB columns and the updateReturnPath mutation
already existed (admin-only, no UI), but buildDnsRecords() never generated a
record for it and the domain settings page had no input to set it at all -
the feature was unreachable through the product for any domain, house or
customer. Add a RETURN_PATH_CNAME_HOSTNAME env var (default bounce.scribase.com,
mirrors the existing INBOUND_MX_HOSTNAME pattern), generate the CNAME record
in buildDnsRecords() when customReturnPath is set, and add a settings section
mirroring the existing tracking-subdomain UI so a return-path label can
actually be saved from the dashboard.
Verified: tsc --noEmit clean, existing domain-service/deliverability-insights
unit tests pass unchanged (28/28), `next build` compiles the touched files
successfully (fails later only on unrelated missing Redis/auth-provider infra
during page-data collection, not on anything touched here).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
isConfigured() only checked that REACHER_ENABLED/REACHER_API_URL were set,
never that Reacher could actually complete a real SMTP check. On a host
where outbound TCP 25 is blocked (e.g. Oracle Cloud default), a configured
Reacher backend returns 200 is_reachable:"unknown" for every address
forever, and checkOne() labeled that method:"reacher_smtp" as if it were
authoritative -- silently losing the disposable-domain/syntax/MX coverage
liteCheck() already provides for free.
Add ensureReacherHealthy(): a cached, periodically-refreshed self-test that
probes a made-up mailbox at a real, non-catch-all provider
(REACHER_SELFTEST_EMAIL, default gmail.com). A healthy Reacher must return a
determinate verdict (e.g. "invalid") for that probe since the mailbox
doesn't exist; a structurally broken one can only ever return "unknown".
checkAddresses() now demotes to liteCheck() whenever the probe fails,
logging a clear warning (not a silent downgrade), and logs a recovery
notice once a later probe succeeds again.
9 new unit tests cover the healthy-probe path, the demoted-fallback path,
probe caching (no fetch spam), and recovery after a simulated TTL window.
Full suite re-verified: unit 665/665, trpc 43/43, api 144/144, tsc clean.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Ships the existing injector key directly into the app layout plus
signup_email_submitted and checkout_started event tracking. Second
live site on Railyard Insights custom-event instrumentation alongside
Bidstage.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
mail.scribase.com only ever got pageview-level counting from Railyard's edge
injector (ry_site_scribase_mail_7e3c28c34586) -- zero custom events, so there
was no real step-level view of signup -> Pro/Scale checkout, the exact funnel
plans/product-analytics.md and plans/mail-studio.md both care about (goal: 3
paid external teams by EOY). Ships that same already-registered site key
directly in apps/web's own root layout too (belt-and-suspenders, same pattern
yokharita.com/oxhanatelier.com use), and adds two named railyard.track()
events: signup_email_submitted (login-page.tsx, after a real signup OTP email
is sent) and checkout_started (UpgradeButton.tsx, after a real Dodo checkout
session URL comes back, before the redirect). Same window.railyard.track()
pattern bidstage-tenders already ships (web/track.ts).
Verified: tsc clean on apps/web; `next build` compiles the changed files
successfully (next build's later failure is a pre-existing missing
OAuth/DB/Redis secrets issue in this sandbox, unrelated to this change, not
introduced by it); both event shapes were round-tripped against the live
https://insights.ereboslab.com/api/send ingest endpoint with the real already-
registered site key and a real browser user agent -- accepted (202, no
x-railyard-dropped header), confirming the pipeline actually stores them.
The prior lite fallback (e3ef6d6) already ran real syntax+MX+disposable
checks instead of a blind "unverified", but two gaps remained:
1. normalizeEmailDomain only validated the domain half of an address.
The local-part was unchecked, so "john doe@x.com", "john..doe@x.com",
".john@x.com" and a 65+-octet local-part all passed as syntactically
"valid" and could be reported "safe". Added a real RFC 5322 dot-atom /
quoted-string local-part validator (isValidLocalPart) plus the RFC 5321
64-octet local-part and 254-octet address length caps, wired into
normalizeEmailDomain so every caller (signup screening + the lite
fallback) gets the stricter check.
2. The lite fallback's "safe" verdict was indistinguishable from a real
Reacher SMTP-confirmed "safe" -- a caller inspecting only `verdict`
would see the same string either way, i.e. a false "fully verified"
signal when only syntax+MX+disposable had actually run. Added
AddressCheckResult.method ("reacher_smtp" | "lite_fallback" | "none")
so the degraded-confidence tier is honestly visible without changing
the existing `verdict`/`blocked` contract (REACHER_BLOCK_VERDICTS and
existing callers are unaffected).
Behavior confirmed fail-open by design at every layer already (unreachable/
timeout/non-2xx Reacher, and MX-lookup-blip in the lite path all return
unverified/unknown, never a false reject) -- this change doesn't alter that,
it only makes a bad-syntax/no-MX/disposable "invalid"/"risky" determination
syntactically correct, and makes the fallback's reduced confidence visible
instead of silently equal to a real SMTP-confirmed verdict.
18 new unit tests (local-part RFC validation + method field across both
real Reacher and lite-fallback paths); full suite 656/656 unit + 43/43 trpc
+ 144/144 api; tsc clean.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Oracle Cloud blocks outbound TCP 25 on this box, so a self-hosted Reacher
backend can never complete its SMTP handshake here even when configured.
Previously the fallback silently treated every address as "unverified" —
a real check instead, reusing signup-screening's already-tested
normalizeEmailDomain/isDisposableDomain/checkMx primitives: invalid syntax
or no MX record -> invalid, disposable domain -> risky, MX lookup failure
-> unknown (fail open), otherwise -> safe. Respects REACHER_BLOCK_VERDICTS
the same as the Reacher path.
18/18 unit tests (6 new), full suite 812/812, tsc clean.
buildReferencesChain looked up the inbound References header via a
hardcoded lowercase key (headers.references), but extractForwardedHeaders
stores it under its real on-the-wire casing (References, capital R) —
the casing virtually every real MTA/MUA sends. The lookup was always
undefined in production, so replies silently fell back to single-hop
threading instead of chaining beyond one hop per RFC 5322 S3.6.4.
Look up the key case-insensitively instead. Added unit tests on
replyToReceivedEmail covering the real capitalized-header shape (fails
before this fix, passes after), the lowercase-header shape, and the
no-prior-References fallback.
tryAutoApproveUser's rollback on a failed db.user.update always released the
business-domain daily slot + domain claim, even for a free-provider (gmail.com
etc.) approval — which reserves a separate freeProviderDailyCap Redis counter
and never claims a domain. That leaked the free-provider slot forever on every
failure (shrinking its real daily budget over time) while wrongly decrementing
the unrelated business-domain counter, letting one extra business-domain
signup through per such failure. Added releaseFreeProviderDailySlot and route
the rollback by which path the decision actually took.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
postWebhook() re-checked the customer-configured URL at send time
(assertPublicWebhookUrl), but then called fetch(url, ...) for the real
delivery — which re-resolves the hostname a second time to connect. A
DNS-rebinding host can answer a public address for the check and a
private one (loopback, link-local, cloud metadata, an internal Docker
service) moments later for the actual connection, reaching internal
services from inside the deployment network on every real webhook
delivery (and its retries, for up to 6 attempts).
resolvePinnedWebhookAddress() now returns the exact address its check
resolved; the new pinnedPost() (../utils/pinned-http.ts) connects the
socket to that address via a custom http(s).Agent lookup, never
re-resolving the hostname — the same resolve-once-and-pin pattern
already used elsewhere for customer-named hosts. TLS SNI/certificate
checks still use the real hostname, only the TCP destination is pinned.
Verified: tsc --noEmit clean; full apps/web unit suite 615/615 (updated
the 5 tests that mocked global fetch to mock pinnedPost instead); a
throwaway live test (real sockets, no mocks, deleted before commit)
proved pinnedPost connects to the exact pinned address rather than
letting Node re-resolve the URL's real hostname.
The admin waitlist tool could only search one user at a time by exact
email, with no way to see who is actually waiting. Add a real
listWaitlistedUsers tRPC query (paginated, oldest sign-up first) and
render it as a worked queue with inline Approve/Reject buttons, reusing
the existing updateUserWaitlist/rejectWaitlistUser mutations. Closes the
gap flagged repeatedly in plans/mail-studio.md as the "remaining
highest-value next step" for getting real external sign-ups approved.
Resend's migration guide listed "Custom tracking subdomain" as a hard
"Not yet" gap. Finishes and ships the mostly-complete prior WIP that
closed it, plus the piece it was missing: dashboard UI.
- domain-service: generate the CNAME DNS record for a saved tracking
label; updateDomain accepts trackingSubdomain.
- email-tracking: normalizeTrackingSubdomain + trackingLinkBaseUrl pick
https://{label}.{domain} for open/click links when a label is set,
falling back to the app origin otherwise.
- email-queue-service: wire the new base URL into the actual send path
(applyTracking), not just the API layer.
- Resend-compat public API (PATCH /domains/:id): accepts
tracking_subdomain (rejects clearing it, matching Resend's own rule).
- NEW: dashboard domain settings page gets an actual input + save
button for the subdomain (previously only settable via the raw API,
so no dashboard user could ever use the feature end to end) wired to
a new domainRouter.updateDomain trackingSubdomain field.
- docs/guides/resend-migration.mdx: flips the parity table row from
"Not yet" to how to use it.
Verified: apps/web `pnpm run typecheck` clean (0 errors), full
`pnpm run test:unit` 615/615 passing (44 in the directly touched
files), plus a real send through the live prod pipeline (see
plans/mail-studio.md for the HTTP/email evidence).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
The marketing site's "Choose Pro"/"Choose Scale" buttons on scribase.com/mail
link straight to the generic /signup page with no way to carry that intent
through sign-up: a visitor who clicked "Choose Pro" landed on the exact same
dashboard as someone who clicked "Create a free account", with zero memory
of which plan they picked. They then had to independently find
Settings > Billing and pick Pro again from scratch — a real dead-end for
anyone who clicked with payment intent, closing off the shortest path from
"I want to pay" to an actual subscription.
/login and /signup now accept ?plan=pro|scale, show it back to the user
("Continuing to Pro ($20/mo)..."), and the OTP/OAuth post-auth redirect
(post-auth-redirect.ts) sends the user straight to
/settings/billing?plan=PRO instead of the generic /dashboard. The billing
page reads the same param and PlanPicker highlights that plan card
("Picked for you") and scrolls it into view, so the plan a visitor picked
on the marketing page is still what they see first in billing, ready to
upgrade, instead of a blank plan grid with no memory of their intent.
Verified with tsc --noEmit (clean) and a one-off runtime check of
getPostAuthPath/parsePlanIntent covering invite-vs-plan precedence, case
normalization, and invalid plan values falling back to /dashboard.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Free-provider inboxes (gmail.com, outlook.com, etc.) previously hard-failed
waitlist auto-approval and sat in a manual review queue nobody is actively
working, blocking most real organic evaluators of the product. Adds an
opt-in AUTO_APPROVE_FREE_PROVIDERS path with its own smaller daily cap,
skipping the per-domain "first account" exclusivity rule since free
domains are shared across unrelated sign-ups.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Sign-in redirects straight to /dashboard, which has no server-side
waitlist check (only the root `/` page redirects to /wait-list). A
waitlisted external sign-up — the overwhelming majority of real
evaluators, since auto-approve only fires for a verified business
domain — landed on a fully rendered Analytics dashboard where every
tRPC call then failed with UNAUTHORIZED one at a time, with no
explanation. Add the same session/isWaitlisted redirect at the
(dashboard) layout level so it covers all 30+ routes in the group
instead of only the one page that happened to check it.
Verified live: signed up a real account via the live OTP email flow,
confirmed isWaitlisted:true in the session, and confirmed /dashboard
previously returned 200 with the full app shell instead of
redirecting to /wait-list.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Adds the forward action for inbound mail across all three surfaces, picking
up the top-ranked item left in PLAN-2026-10-23-DEEP.md after round 2's
reply work:
- forwardReceivedEmail() (received-email-service.ts): builds a
Gmail-style "Forwarded message" header block + optional comment,
prepended to the original text/html, and reuses the original
attachments by reading their bytes straight from inbound storage
(new getStorageObjectBytes() in inbound-storage-service.ts) instead of
re-uploading them, before handing off to the existing sendEmail
pipeline (same quota/screening/suppression checks as send/reply).
- POST /emails/received/:id/forward on the Resend-compat public API and
receivedEmail.forward on the dashboard tRPC router, both thin wrappers
over the same service so behavior is identical everywhere.
- MCP tool forward_received_email, completing the reply/forward loop for
AI-agent callers.
- Dashboard ForwardComposer UI (recipient input + optional note),
toggled by a header-bar Forward icon next to Reply.
Verified via typecheck, eslint (0 errors), targeted vitest (both existing
suites still pass unmodified), and `pnpm build` for packages/mcp-server.
No migration, no new test files, per standing rules.
Inbound MX server now captures the full forwardable header chain
(extractForwardedHeaders, reused from the outbound submission proxy) and
persists it on ReceivedEmail.headers (no migration, already Json?).
replyToReceivedEmail builds the real RFC 5322 References chain from it
instead of only the immediate message's own Message-ID, so a reply to a
reply-of-a-reply now threads correctly beyond one hop.
Also exposes reply on the two surfaces that were dashboard-only: a new
POST /emails/received/:id/reply on the public Resend-compat API, and an
MCP tool reply_to_received_email wired to it, so external SDK callers and
AI agents can reply too.
Also records two untracked planning docs (architecture, competitive/GTM
strategy) written earlier this session, and updates the build log/plan
doc with round 2 progress and the revised priority order.
SegmentService (static contact-book-spanning membership) was only
reachable through the Resend-compat API; there was no dashboard way
to create a segment or use it for a campaign, which only targets a
whole contact book.
Adds segment.ts router (CRUD + addContacts/removeContacts) and a
list/detail UI: create a segment, pull contacts into it from any
contact book, remove members, rename, delete.
Campaign has no segmentId column and adding one needs a migration,
which this round intentionally skipped. Instead,
segment.createCampaignAudience snapshots the segment's current
members into a brand-new contact book via the existing
createContactBook service, so "send to segment" works today by
pointing a normal campaign at that snapshot book.
Topic/ContactTopic backend (topic-service.ts, public-api resend
routes) was fully built and tested but had zero UI, so every
unsubscribe was all-or-nothing. Adds:
- topic.ts router: team CRUD over TopicService, plus public
getPublicPreferences/updatePublicPreferences procedures that reuse
the existing signed unsubscribe-link id/hash (exported
verifyUnsubscribeLink from campaign-service instead of
duplicating the HMAC scheme).
- Admin CRUD UI under Contacts > Topics (create/edit/delete with
type-to-confirm).
- A public preference panel rendered on /unsubscribe whenever the
link is valid and the team has public topics, letting a recipient
opt out of one topic while staying subscribed to the rest.
Registers both the topic and segment routers in root.ts (segment
router lands in the next commit).
Campaign analytics only showed opens/clicks/bounces as totals, with
no link-level breakdown, even though every click already records
its destination URL on EmailEvent.data via the /api/t/c tracking
redirect.
Adds campaign.linkStats (raw SQL aggregation of CLICKED EmailEvents
grouped by destination URL) and a "Links" tab next to the existing
email preview on the campaign detail page, showing total clicks,
unique clicks and click rate per link.
The AuditLog backend (audit.ts router, recordAudit() call sites
across api keys/webhooks/billing/team/admin) was already fully
built, but there was no page to read it back. Adds an admin-only
Settings > Audit log page: filter by action category, actor, target
type and date range, infinite list, and a detail sheet showing the
full metadata JSON.
Also extends audit.list to resolve actor display names (user
name/email or API key name) server-side instead of leaving raw ids.
Expose the already-populated ApiRequestLog table (written by
request-log-middleware for every public API call) through a new
Dev Settings > API Logs page, so a user can check whether their
Resend-compat SDK call actually reached the server instead of
guessing from a silent failure.
Adds api.getRequestLogs/getRequestLog tRPC procedures (cursor
pagination, filters by outcome/method/API key/path) and a page with
a filterable table, infinite load-more, and a request/response body
detail sheet.
Received mail was strictly read-only (list/get/setReceiving only). Add
receivedEmail.reply, threading via In-Reply-To/References against the
original Message-ID and reusing the existing sendEmail pipeline so
suppression/screening/domain checks still apply. Adds a reply composer
to the /receiving detail panel. Ported from agentic-inbox's
reply-forward threading approach, reimplemented against this repo's
Prisma ReceivedEmail model.
Resume stranded work: GET/PATCH /contacts/:id/topics mirrors the Resend
SDK's resend.contacts.topics.list/update, returning per-topic opt_in/opt_out
derived from ContactTopic rows with the topic's default as fallback.
mailer.ts's self-hosted fallback (used whenever the provider relay is not
configured or fails) picked `db.team.findFirst({})` - an arbitrary team - and
then that team's most-recently-created domain regardless of verification
status, with no error handling around the send. In a multi-team self-hosted
install this meant:
- A team invite for Team B could silently be sent "from" an unrelated Team
A's domain, whichever team happened to sort first with no `orderBy`.
- If that domain wasn't verified yet (`status !== "SUCCESS"`), the fallback
called `sendEmail()` anyway, which throws inside `validateDomainFromEmail` -
uncaught, crashing the NextAuth sign-in request or the team-invite tRPC
mutation for every team in the install, not just the affected one.
Fix: thread the real inviting team's id from `team-service.ts` (`
createTeamInvite`/`resendTeamInvite`, which already has it) through
`sendTeamInviteEmail` -> `sendMail`, so the fallback uses that team's own
domain. Filter to verified (`SUCCESS`) domains before picking one, log a
clear actionable error and return (instead of throwing) when none exist, and
wrap the final `sendEmail()` call in try/catch so a failure is logged, never
crashes the caller. Sign-in emails (no team exists yet) keep the "first team"
fallback but now only via a verified domain.
Verified: tsc --noEmit clean; full apps/web unit suite 608/608 and tRPC suite
43/43 passing (no regressions). Additionally exercised the real `sendMail`/
`sendTeamInviteEmail` control flow directly (temporary vitest file, deleted
after use, never committed) against a fake two-team DB: Team A (first in DB)
with only an unverified domain, Team B with a verified domain. Confirmed (1)
a Team B invite sends from Team B's verified domain and never touches Team
A's domain, (2) Team A's unverified-only case logs the new clear error and
returns without throwing where the old code would have crashed, (3) the
no-team-context sign-in path still falls back gracefully. Could not run a
live end-to-end SMTP/Mailpit send in this sandbox: the local Docker (colima)
image store is corrupted (`input/output error` pulling postgres/redis
images for `docker/dev/compose.yml`) - unrelated to this change, flagging as
a separate owner-attention infra item, not fixed here to avoid touching
other products' shared containers on this Mac.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Neither /api/auth/signin/email (request a magic link) nor
/api/auth/callback/email (consume the token) had any rate limiting - there
was no middleware.ts in this app at all. The CSPRNG token fix from earlier
today (f04ed9a) made brute-forcing the token itself impractical, but left
the signin-request endpoint open to inbox-flooding and the callback endpoint
with no defense-in-depth against guessing.
Adds a pure, unit-tested fixed-window limiter
(server/auth/auth-rate-limit.ts, 4 new tests covering under-limit,
over-limit, per-key isolation, and fail-open on a store error) and wires it
through the app's first middleware.ts: 5 signin requests / 10 min / IP, 20
callback attempts / 10 min / IP, 429 + Retry-After when exceeded. Runs on
the Node.js middleware runtime (not Edge) since ioredis needs a real TCP
socket.
apps/web unit suite: 608/608 passed. tsc --noEmit: 0 errors.
Also in GROWTH-BLOCKERS-2026-10-18.md: marked the dailyEmailLimit sync item
as already fixed (37601ea, verified by reading the current webhook handler,
not just the commit message - the doc was stale), and recorded the
analytics gap as an owner-only blocker (current Cloudflare token lacks
rum:edit scope to provision Web Analytics via API).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Paragraph and heading nodes store their alignment under textAlign; button
and logo nodes used a bespoke alignment attribute instead, flagged with two
`@TODO: Update the attribute to textAlign` comments in renderer.tsx. Any
content built or imported using the rest of the editor's own textAlign
convention (e.g. programmatic template generation) would have its button/
logo alignment silently ignored and fall back to the hardcoded default.
Both render methods now prefer attrs.textAlign and fall back to the legacy
attrs.alignment, so older saved templates keep rendering exactly as before
while new/imported content can use the same attribute name as every other
aligned node. Only renderer.tsx changes - the Tiptap node schemas
(ButtonExtension, etc.) still read/write `alignment` for the live editor UI,
so there is no risk of the editor dropping an old template's alignment on
load.
Added 5 renderer tests (apps/web/src/lib/email-editor-node-alignment.unit.test.ts,
the only place in this repo with test infra for the EmailRenderer, matching
the existing campaign.unit.test.ts pattern) covering textAlign, legacy
alignment, and the default for both node types.
Closes#2.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Nine console.log/console.error calls left over from development were still
running in production, including two with real impact:
button.tsx's ButtonComponent logged its entire NodeViewProps object on every
render of every button block in the email editor (hot path, large object);
login-page.tsx logged the user's email to the browser console on every OTP
submit. The rest (instrumentation startup, to-html render timing/errors,
drag-and-drop clipboard serialization, image upload progress, variable
autocomplete) were pure dev leftovers with no guard. Routed the two
server-side ones (instrumentation.ts, to-html/route.ts) through the existing
shared logger instead of dropping them, since they carry real operational
signal (startup confirmation, render latency/failures); the rest were purely
debug noise and are just removed.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
LimitService enforces daily sends against the Team.dailyEmailLimit DB column
(default 10,000), not PLAN_LIMITS.PRO/SCALE.emailsPerDay (-1). Marketing
advertises "No daily sending cap" for Pro/Scale, but nothing ever synced the
enforced column to match: a team's dailyEmailLimit stayed at the schema
default forever unless an admin manually raised it. 10k/day doesn't bite a
50k/month (Pro) or 100k/month (Scale) customer in practice, so this hasn't
been reported, but it's a real gap between what's promised and what's
enforced for any high-volume customer who does approach it.
processDodoWebhook's applySubscription now sets dailyEmailLimit to -1
(unlimited) when a team's subscription becomes active on a paid plan and its
dailyEmailLimit is still exactly the untouched schema default - any other
value means an admin deliberately tightened it for abuse control, and is
left alone.
Added 2 unit tests: a team on the default limit gets unlocked on upgrade; a
team with an admin-customized limit keeps it. Full suite still green:
vitest unit 599/599, trpc 43/43, tsc --noEmit 0 errors.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
NextAuth's EmailProvider defaults to crypto.randomBytes(32).toString("hex")
(256 bits of CSPRNG entropy) for its passwordless sign-in token. This app
overrode generateVerificationToken with
Math.random().toString(36).substring(2, 7) so the value could double as a
short, human-typed OTP (see sendSignUpEmail) - but Math.random() is not
cryptographically secure, the 5-char result only has ~26 bits of entropy
(36^5 ~= 60M combinations), and there is no rate limiting anywhere on the
/api/auth/callback/email route (no middleware.ts in this app at all). Anyone
who knew a target's email could brute-force a valid sign-in token within its
24h validity window and take over the account.
Replace it with generateSignInToken(), which draws each character from
crypto.randomInt (CSPRNG) and defaults to 8 characters (36^8 ~= 2.8e12
combinations), and set the EmailProvider's maxAge to 15 minutes instead of
NextAuth's 24h default to further bound the brute-force window, since this
token is shown to users as both a magic link and a manually-typed code.
Added unit tests asserting the token generator never calls Math.random, has
>=8 chars of alphanumeric entropy, produces distinct values across calls, and
that the configured EmailProvider carries both the new generator and the
shortened maxAge.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
executeEmail (the BullMQ worker that sends a queued email) only wrapped the
limit-check-through-provider-send portion in try/catch. Setup steps that ran
before it — parsing email.attachments JSON, contact-variable subject
templating, and resolving the in-reply-to message id — were unguarded. If any
of those threw, the exception propagated out of the BullMQ processor
uncaught; once BullMQ exhausted its retry attempts, nothing ever updated
Email.latestStatus, leaving the row permanently stuck at QUEUED with no
FAILED event recorded and no way to tell what happened.
This reproduces the "stuck in Queued forever" symptom reported in #406 and
#407, even though this fork's send pipeline (OCI provider + BullMQ) has fully
diverged from the AWS SES/SNS-based architecture those issues were originally
filed against.
Moves all pre-send setup inside the existing try block so every failure path
reaches the same catch-all, which already classifies errors correctly
(retryable ProviderSendErrors are retried by BullMQ; everything else
immediately records a terminal FAILED status). No other behavior changed.
Refs #406, #407
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Team.sendingPool and team.setSendingPool/getSendingPool (tRPC, admin-only,
audited via AuditAction.SENDING_POOL_CHANGED) already existed in the schema
and API, and multi-region-service.ts already had a fully unit-tested
getSmtpCredentialsForPool() for resolving OCI_SMTP_POOL_<NAME>_* env creds -
but nothing ever called it. Setting a pool persisted to the DB and changed
nothing about where mail actually sent: a dormant, coded-but-unwired
subsystem, same pattern as this session's other beat-the-gap passes.
This is Scribase Mail's dedicated-IP-pool equivalent: Resend sells dedicated
IPs for reputation isolation on high-volume senders; useSend (the fork base)
has nothing like it. Wires the existing pieces together instead of building
anything new:
- SendRawEmailInput gains an optional sendingPool field.
- OciEmailProvider and GenericSmtpProvider both resolve a per-pool transport
at send time (cached per pool name, since nodemailer pools connections)
and fall back to the shared relay when a pool isn't provisioned - never
throws, matches getSmtpCredentialsForPool's existing fallback semantics.
- email-queue-service.ts reads the sending team's pool right before send and
passes it through.
- New team settings UI (admin-only) to set/clear the pool name.
44 new/updated unit + trpc tests, full web unit suite green (591/591) and
trpc suite green (43/43); tsc --noEmit clean.
DeliverabilityInsightsService (DMARC/SPF/DKIM, return-path, tracking
subdomain, 30-day bounce and complaint rate) already existed with a
tested service layer and a getDeliverabilityInsights tRPC query, but no
page ever rendered it -- the only way to see reputation health was the
account-wide dashboard chart, not per-domain, and the DNS/return-path
checks were invisible entirely.
Add a Deliverability & sender reputation panel to the domain detail
page that calls the existing query and renders every check with its
severity, plus 30-day sent/bounce/complaint stats. Fetch failures show
a visible error banner instead of being hidden, matching this
product's no-silent-failure rule.
Neither Resend nor the useSend base this product forks from ships a
per-domain panel combining DNS-health auditing with bounce/complaint
thresholds in one place; Resend's newer Metrics API/Insights dashboard
is account-level engagement data, and useSend only relays bounce/
complaint into suppression lists without auditing DMARC/SPF/DKIM
policy quality.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Every new cloud team's first 20 emails (or first 48 hours, whichever is
later) are held for manual admin review (send-gate-service.ts), with no
synchronous signal to the caller: the API/SDK call returns 200 immediately
and the hold happens async in the queue worker. DEPLOY.md's own documented
smoke test is `{"to":"<you>"}` - a brand new paying customer's very first
"does the one-line Resend switch actually work" test send is exactly the
kind of send this silently stalls on, unless an admin happens to be
watching the review queue within the hold window.
A send to only the team's own members can't reach a third-party mailbox,
so it carries none of the reputation/abuse risk the first-sends review
exists to catch. Let it through immediately while keeping first-sends
review in place for every other recipient, and keeping content screening
(malicious links/phishing) active unconditionally for everyone.
- send-gate-service.ts: isSelfTestSend() checks every `to` address against
the sending team's member emails; only skips the FIRST_SENDS reason, not
CONTENT.
- email-queue-service.ts: pass the email's recipients into the gate.
- 2 new unit tests (self-test send passes, send with any non-member
recipient still held).
Note: apps/web/node_modules/.pnpm was wiped on this machine (disk-cleanup
side effect, unrelated to this change), so the full test/typecheck suite
could not be run locally. Verified instead with an isolated TS syntax
parse of the changed files (0 diagnostics) and a manual read against the
Prisma schema for the teamUser/user relation used.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Wires reacherhq/check-if-email-exists (self-hosted, MIT licensed) as a
pre-send validator in the queue worker, right before the provider dispatch
that every send path (API, SMTP proxy, campaigns, scheduled, double opt-in)
shares. Recipients confirmed undeliverable are dropped before a send credit
is spent instead of bouncing after the fact.
Fails open by design: disabled, unconfigured, slow, or unreachable verifier
means every recipient is treated as unverified and the send proceeds
unchanged. A down validator must never silently drop a legitimate send.
- apps/web/src/server/service/address-verification-service.ts: REST client
for the reacherhq/backend HTTP API (POST /v0/check_email), batched,
timeout-bounded, never throws.
- apps/web/src/server/service/email-queue-service.ts: call the verifier
right before provider.sendRawEmail; reject with status REJECTED when
every recipient is invalid, otherwise send to the deliverable subset only.
- apps/web/src/env.js: REACHER_ENABLED / REACHER_API_URL / REACHER_API_KEY /
REACHER_TIMEOUT_MS / REACHER_BLOCK_VERDICTS.
- compose.yml: optional `reacher` sidecar behind a profile (needs outbound
port 25, so it's opt-in, not part of the default self-host stack).
- docs/SELF-HOSTING.md, .env.example, .env.selfhost.example: how to turn it
on.
25 new/updated unit tests (12 for the service in isolation covering block,
allow, fail-open on error/timeout/non-2xx, disabled, unconfigured, batching,
custom block list; 13 in the queue worker covering full-block, partial-block,
and the default pass-through path). Full web unit suite: 574/574 passing.
The fire-and-forget ApiRequestLog write ran db.apiRequestLog.create
directly inside queueMicrotask, so a synchronous throw escaped as an
uncaught exception (50 of them failed the Web Tests CI job).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
EMAIL_PROVIDER=smtp sends through any SMTP relay, signs DKIM with a
per-domain RSA key stored in DomainDkimKey (never returned with domains),
verifies domains by DNS TXT lookup and shows TXT DKIM records. RFC 2606
reserved names (.test, .localhost, .example, .invalid) verify without DNS
for local trials. Default stays oci, so existing installs are unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
On the hosted instance (IS_CLOUD) a new or waitlisted user is let in
automatically when their verified account email is on a business domain:
not a free/consumer provider, not a disposable inbox (CC0 list from
disposable-email-domains), with a usable MX record (3 s timeout, null MX
and IP/localhost exchanges rejected). One account per domain (DB check +
Redis claim) and a daily cap (AUTO_APPROVE_DAILY_CAP, default 25).
Everything fails closed to the existing waitlist flow.
Opt-in via AUTO_APPROVE_WAITLIST (default off). Approval only clears
User.isWaitlisted, so warm-up caps, reputation auto-pause, content
screening and the review queue still apply to new teams. Decisions are
logged, recorded in the admin team's audit log and mailed to the admin.
The waitlist form re-checks the account email (never the self-declared
domain) and sends approved users straight to the dashboard.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Webhook deliveries are POSTed from inside the deployment network and the
response body is stored in the delivery log, so a customer URL pointing at
169.254.169.254, Redis, Postgres or another container could read internal
services. URLs are now checked on create, update and again at send time
(DNS may change): http(s) only, no credentials, no localhost, and every
resolved address must be public. WEBHOOK_ALLOWED_PRIVATE_HOSTS exempts
named internal hosts for operator smoke tests.
Webhooks created through the Resend API passed userId 0 into
createdByUserId, which violates the User foreign key; store null instead.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Fixes on merge: DEVELOPER role in team UI/context, Prisma JSON nulls,
test typings, and a brute-force guard for TOTP/recovery codes (5
failures lock the second factor for 15 minutes).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Fixes on merge: route order (fixed /emails/<word> paths before
/emails/:id), Prisma JSON null handling, and the public /share/<token>
page now renders customer HTML in a sandboxed iframe instead of
dangerouslySetInnerHTML (stored XSS on the app origin).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Includes a fix to the attachment path fetch: connect to the validated
address (no DNS rebinding), refuse redirects, and block more reserved
ranges (198.18/15, multicast and above).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>