606 Commits

Author SHA1 Message Date
ae015986ca feat(web): llms.txt discoverability aliases, head link, footer link, robots
- next.config.js redirects(): /llm.txt, /llms, /.well-known/llms.txt ->
  /llms.txt (301) and /llm-full.txt, /.well-known/llms-full.txt ->
  /llms-full.txt (301). No case-only variant added: redirects() path
  matching is case-insensitive and would self-loop.
- <link rel="alternate" type="text/markdown" title="llms.txt"
  href="/llms.txt"> in <head> (the existing metadata.alternates.types entry
  has no field for title).
- Footer: new "llms.txt" link in the Company column (SiteFooter.tsx,
  rendered on the real marketing homepage via MarketingHome.tsx).
- New app/robots.ts: mail.scribase.com had no app-level robots.txt, so the
  zone's edge was serving Cloudflare's synthetic "content signals"
  placeholder (no real Allow/Disallow rules) instead of a real policy.
  Same explicit AI-crawler allow-list as scribase.com/docs.scribase.com.
2026-11-12 20:15:59 +03:00
981f9e6d6c feat(users): internal accounts never count as users
`User.isInternal` marks the operator's own accounts (owner, postmaster, QA);
the waitlist queue, its count and the per-domain active-user cap skip them.
Migration backfills the flag from the owner's test-address patterns and is
idempotent, so it may be applied by hand before it ships (owner decision
2026-11-12).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-12 04:19:13 +03:00
9622c742e4 fix(marketing): point Docs links at docs.scribase.com/docs/concepts/mail
Some checks failed
Publish Docker image / Build amd64 (push) Failing after 3m6s
Web Tests / web-tests (push) Failing after 41s
Publish Docker image / Build arm64 (push) Has been cancelled
Publish Docker image / Publish manifest (push) Has been cancelled
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>
2026-11-12 02:14:31 +03:00
2731b206a0 feat(provider): enforce TLS per domain on the self-hosted SMTP relay
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.
2026-11-11 04:41:22 +03:00
ee1694f26c feat(domains): claim a domain already verified under another team
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>
2026-11-11 01:37:39 +03:00
2209b3a4a1 fix(marketing): serve the real homepage at mail.scribase.com/ for anonymous visitors
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>
2026-11-07 22:25:50 +03:00
5f76bc68fa feat(ai-discoverability): add llms.txt/llms-full.txt/ai.txt + markdown mirror
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>
2026-11-07 20:54:24 +03:00
f992883823 fix(domains): wire the custom return-path CNAME into DNS records + settings UI
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>
2026-11-05 00:04:13 +03:00
d806795134 feat(marketing): add Resend-alternative positioning to live homepage
mail.scribase.com had zero mention of "Resend" anywhere on the live site
(title, meta, or body copy) despite the product's own stated pain point
("Resend alternative", "Resend pricing") and the gtm listing-targets
research explicitly calling for mail.scribase.com to be positioned as an
"alternative to Resend" for directory submissions. The README already had
this framing but the live marketing page did not.

- Updated <title>/meta description to target the "Resend alternative"
  search intent directly.
- Added a new homepage section with real, verified pricing parity copy
  (Resend's published Free/Pro pricing fetched live: $0/3,000 emails/100
  per day, $20/mo for 50,000 emails + $0.90/1,000 overage - identical to
  our own PRICING_PLANS) plus the real AGPL/self-host differentiator and
  a link to the existing /mail/migrate-from-resend guide.

Verified by running the real `next build` for the marketing app and
grepping the exported static out/index.html for the new title and
section copy - both render correctly.
2026-11-04 23:31:03 +03:00
15021a115e fix(deploy): wire AUTO_APPROVE_FREE_PROVIDERS into compose.scribase-mail.yml
env.js and waitlist-auto-approve-service.ts (526d6a9) already consume
AUTO_APPROVE_FREE_PROVIDERS and AUTO_APPROVE_FREE_PROVIDER_DAILY_CAP, but
the web service's environment allowlist in
deploy/compose.scribase-mail.yml never listed either var, and there is
no env_file fallback in this manifest. Setting them in deploy/.env alone
was a no-op: docker compose would not forward them into the container,
Zod would fall back to its "false" default, and free-provider
auto-approval stayed permanently off regardless of the env file.

Add both vars to the web service's environment block (default false /
10, matching the Zod schema defaults) and document them in
deploy/.env.example next to the existing AUTO_APPROVE_WAITLIST pair.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-04 23:26:48 +03:00
2e3d92594b fix(verification): auto-demote Reacher to lite fallback when SMTP self-test fails
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>
2026-11-04 16:30:51 +03:00
dddd5745c3 Merge feat/railyard-analytics: wire Railyard Insights into the signup -> checkout funnel
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>
2026-11-04 04:17:13 +03:00
f2d38ae56d Merge fix/mail-studio-reacher-fallback-fail-closed-syntax: close 2 correctness gaps in the Reacher-unavailable fallback
normalizeEmailDomain only validated the domain half of an email --
local-part was unchecked, letting malformed addresses ("john doe@x.com",
".john@x.com") pass as syntactically valid. The lite fallback's "safe"
verdict was also byte-identical to a real Reacher SMTP-confirmed "safe",
giving callers a false full-verification signal. Adds a real RFC
5322 local-part validator + RFC 5321 length caps, and an
AddressCheckResult.method field exposing which tier actually ran.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-04 04:17:10 +03:00
31a014eae5 feat(analytics): wire Railyard Insights into the real signup -> checkout funnel
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.
2026-11-04 04:08:02 +03:00
95e3b58fc8 fix(verification): close two real correctness gaps in the Reacher-unavailable fallback
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>
2026-11-04 04:06:17 +03:00
e3ef6d6bea feat(verification): real lite fallback (syntax+MX+disposable) when Reacher SMTP check is unavailable
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.
2026-11-04 03:19:21 +03:00
ba679d537c fix(mail-studio): match References header case-insensitively in reply threading
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.
2026-11-03 15:47:08 +03:00
5036bffcd8 fix(waitlist): release the correct daily-cap counter on free-provider auto-approve failure
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>
2026-11-03 01:45:26 +03:00
1e771009c1 fix(webhooks): pin outbound webhook delivery to the checked address, closing a DNS-rebinding SSRF window
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.
2026-10-29 13:22:38 +03:00
cf981431a8 feat(admin): list the actual waitlist queue instead of email-only lookup
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.
2026-10-29 10:49:23 +03:00
477355d545 docs(resend-migration): fix stale parity rows — path attachments + content_id inline images are live, not "Not yet"
Live-verified by sending a real test email through the production API
(mail-api.scribase.com) with a remote `path` attachment and a
`content_id` inline image: accepted by the OCI relay and sent with no
errors. Both features were already fully implemented (SSRF-guarded
server-side fetch for `path`, `cid` wired through to both the OCI and
SMTP providers) but the migration docs still told evaluators "Not
yet" and "use base64 content" instead — a false parity gap that would
make a developer comparing against Resend wrongly rule this out.
2026-10-29 09:51:24 +03:00
5f6ecbf44c docs(webhooks): fix stale parity docs — webhooks + Svix signing are live, not "coming soon"
The Resend-migration parity table and the webhooks guide both still said
GET/POST /webhooks were "Coming soon" and that Svix-compatible signing was
"on the roadmap"/"coming in Wave 4". Both have actually been fully shipped
since commit b510307 (2026-10-07) — the docs were just never updated, so a
developer evaluating migration from Resend would read this and wrongly
conclude webhooks (a core Resend feature) don't work here at all.

Verified live end to end before fixing the docs: created a webhook via the
real POST /webhooks on mail-api.scribase.com (got back
signature_format: "svix" + a whsec_ secret), sent a real test email through
the public API, and confirmed the real email.sent/email.opened webhook
deliveries at a webhook.site endpoint with valid svix-id/svix-timestamp/
svix-signature headers — then recomputed the HMAC in Python and confirmed it
matches the delivered signature byte for byte. Also corrected the
"Inboxes/received email: Coming soon" row, which is likewise already fully
implemented (including reply/forward extensions Resend itself doesn't have).
Cleaned up the temporary webhook, temporary API key, and test webhook.site
token afterward.
2026-10-29 09:18:35 +03:00
e2afe17617 feat(domains): ship Resend-parity custom tracking subdomain, end to end
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>
2026-10-29 07:49:47 +03:00
94ab9f4919 fix(signup): carry pricing-plan intent from marketing CTA through to billing
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>
2026-10-29 02:39:37 +03:00
526d6a90f0 feat: auto-approve free-email-provider waitlist signups under a capped daily limit
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>
2026-10-27 18:37:59 +03:00
5d454b1284 fix(auth): stop waitlisted users from landing on a broken dashboard
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>
2026-10-24 23:06:31 +03:00
d46e7e8a19 feat(receiving): forward received emails, reusing original attachments
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.
2026-10-24 00:44:23 +03:00
429514967c feat(receiving): multi-hop reply threading + reply on public API and MCP
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.
2026-10-24 00:14:51 +03:00
3d87b58e50 docs: record round 1 build log for 2026-10-23 backlog
Records what shipped this round (API logs, audit log, campaign
link analytics, topics preference center, segments UI), the
backlog-accuracy corrections found along the way (items 9 and 10
were already fully built; item 2's "dynamic segmentation" and item
7's "version on every edit" claims don't match the actual backend),
verification method used, and what's left for the next two rounds.
2026-10-23 17:20:34 +03:00
fd74f1b643 feat(contacts): add segments dashboard UI and campaign audience export
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.
2026-10-23 17:20:00 +03:00
19899f0b69 feat(topics): add subscription preference center and admin UI
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).
2026-10-23 17:19:37 +03:00
20b99b4cfe feat(campaigns): add per-link click analytics tab
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.
2026-10-23 17:18:21 +03:00
2723716777 feat(settings): add audit log dashboard page
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.
2026-10-23 17:17:59 +03:00
aca01aabcc feat(dev-settings): add API request log viewer page
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.
2026-10-23 17:17:45 +03:00
11b2a0783d docs: add deep build spec for pages, APIs, features (2026-10-23)
Internal build doc covering every route/API/feature with concrete
spec and what remains; also records why agentic-inbox can't be a
literal code-move (Workers/Durable Objects vs Next.js/Prisma) and
what was actually ported this session.
2026-10-23 07:56:41 +03:00
b4d58cf5ef feat(receiving): reply to received emails with threaded headers
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.
2026-10-23 07:56:27 +03:00
3629e1ac79 feat(resend): add contact topics list/update endpoints to resend-compat API
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.
2026-10-23 07:38:18 +03:00
3ce418af8f fix(mail): route self-hosted sign-in/invite emails through the right team's verified domain
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>
2026-10-22 03:36:53 +03:00
5bd1133ba9 fix(deps): patch critical Next.js and Auth.js advisories
Bump next 15.5.18 -> 15.5.27 (GHSA-2xp9-vwfh-vxw4, GHSA-p293-qw3h-jr36),
next-auth 4.24.14 -> 4.24.15 and @auth/core 0.41.2 -> 0.41.3 via
@auth/prisma-adapter 2.9.0 -> 2.11.3 (GHSA-7rqj-j65f-68wh). Our fork had
diverged from usesend/useSend upstream (commit daaa435) without this
critical security patch landing here. Verified: tsc --noEmit clean,
vitest unit suite 608/608 passing (including auth.unit.test.ts).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-22 02:45:42 +03:00
a7c6bade9e docs(deploy): record box SSH is down again, blocking the auth rate-limit deploy
ssh box (130.61.180.42) still refuses port 22 in this session, same as the
2026-10-18 pass. App itself is unaffected (mail.scribase.com/api/health is
Healthy over HTTPS) - only the deploy path is blocked. Needs an owner OCI
Console check (reboot or firewall/security-list fix for port 22).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-21 18:24:26 +03:00
4bc873f7e6 fix(auth): rate limit the email sign-in and callback routes
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>
2026-10-21 18:23:52 +03:00
3fc6dbc079 fix(email-editor): read textAlign (not just legacy alignment) on button/logo
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>
2026-10-21 16:35:26 +03:00
10ba24ddcf fix(web): remove leftover debug console statements from the send/editor paths
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>
2026-10-21 16:32:02 +03:00
2734f9183a docs(deploy): fix stale Resend-compat API coverage claim
DEPLOY.md's "Implemented so far" line still described the API as it was at
the initial skeleton commit (POST/GET /emails only) and claimed
attachments[].path/content_type/content_id return a 422 "not yet supported" -
all three have been fully implemented (with SSRF-guarded URL fetching for
path) since the Round 1a merge. Only topic_id is actually unsupported.

This matters for distribution: the product's whole pitch is "switch from
Resend with one line," and the deploy doc customers read to evaluate
migration was understating the real API surface (domains, api-keys,
webhooks, broadcasts, audiences/contacts, segments, contact-properties,
topics, templates, suppressions, logs, metrics, inbound mail - none of which
were mentioned at all) and incorrectly telling them a commonly-used Resend
field (attachment by URL) isn't supported when it is.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-21 16:28:51 +03:00
37601ea25f fix(billing): lift the per-team daily send cap to unlimited on PRO/SCALE upgrade
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>
2026-10-21 16:27:47 +03:00
f04ed9a888 fix(auth): use a CSPRNG for the email sign-in token, not Math.random
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>
2026-10-21 03:39:49 +03:00
b727901755 fix: guard entire email send job in try/catch to prevent stuck QUEUED status
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>
2026-10-20 03:26:38 +03:00
32e7b72933 feat(web): add X conversion tracking pixel to root layout
Loads the X (Twitter) base pixel once on every page via next/script
(strategy=afterInteractive), config id rhhqi.
2026-10-18 17:43:56 +03:00
b587f98612 docs: add launch copy + distribution record for Scribase Mail Studio
Real Launching Next directory submission (POST confirmed 200, thanks
page #163014) plus Product Hunt/HN/X/Reddit/LinkedIn launch drafts
generated via launchmaxxing. Notes existing open awesome-list PRs and
why awesome-selfhosted-data was skipped (its CONTRIBUTING.md bars
agent-authored submissions there).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-18 16:57:00 +03:00
f51523a098 docs(growth): record dedicated sending pool feature shipped and deployed live 2026-10-18 15:19:00 +03:00