From a059fddae1a754a97d889b439629c84a16535e49 Mon Sep 17 00:00:00 2001 From: TheRealToxicDev Date: Tue, 20 Oct 2026 21:29:32 -0600 Subject: [PATCH] feat: more new stuff --- CHANGELOG.md | 24 +- apps/docs/guides/inbound-email.mdx | 42 +++- apps/web/src/app/(marketing)/compare/page.tsx | 190 +++++++++++++++ apps/web/src/app/(marketing)/dpa/page.tsx | 5 +- .../src/app/(marketing)/open-source/page.tsx | 154 ++++++++++++ apps/web/src/app/(marketing)/pricing/page.tsx | 227 +++++++++++++++++ apps/web/src/app/(marketing)/privacy/page.tsx | 2 +- .../src/app/(marketing)/receiving/page.tsx | 229 ++++++++++++++++++ .../web/src/app/(marketing)/security/page.tsx | 142 +++++++++++ apps/web/src/app/(marketing)/smtp/page.tsx | 187 ++++++++++++++ .../(marketing)/tools/dkim/dkim-checker.tsx | 99 ++++++++ .../src/app/(marketing)/tools/dkim/page.tsx | 44 ++++ .../(marketing)/tools/dmarc/dmarc-checker.tsx | 98 ++++++++ .../src/app/(marketing)/tools/dmarc/page.tsx | 53 ++++ apps/web/src/app/(marketing)/tools/page.tsx | 39 +++ .../src/app/(marketing)/tools/spf/page.tsx | 52 ++++ .../app/(marketing)/tools/spf/spf-checker.tsx | 75 ++++++ apps/web/src/app/api/tools/dkim/route.ts | 29 +++ apps/web/src/app/api/tools/dmarc/route.ts | 26 ++ apps/web/src/app/api/tools/spf/route.ts | 27 +++ .../src/components/marketing/Comparison.tsx | 38 ++- apps/web/src/components/marketing/Hero.tsx | 2 +- .../components/marketing/PricingSection.tsx | 9 +- .../src/components/marketing/SiteFooter.tsx | 55 +++-- apps/web/src/components/marketing/TopNav.tsx | 3 +- .../components/marketing/tools/tool-page.tsx | 86 +++++++ .../marketing/tools/tool-result.tsx | 87 +++++++ .../marketing/tools/use-tool-check.ts | 53 ++++ .../src/server/service/dkim-check-service.ts | 114 +++++++++ .../src/server/service/dmarc-check-service.ts | 170 +++++++++++++ .../service/dmarc-check-service.unit.test.ts | 71 ++++++ .../src/server/service/spf-check-service.ts | 163 +++++++++++++ .../service/spf-dkim-check.unit.test.ts | 72 ++++++ .../web/src/server/service/tool-rate-limit.ts | 22 ++ packages/sdk/README.md | 38 +++ packages/sdk/index.ts | 2 + packages/sdk/package.json | 2 +- packages/sdk/src/bytesend.ts | 2 + packages/sdk/src/inbound.ts | 62 +++++ packages/sdk/types/schema.d.ts | 120 +++++++++ 40 files changed, 2877 insertions(+), 38 deletions(-) create mode 100644 apps/web/src/app/(marketing)/compare/page.tsx create mode 100644 apps/web/src/app/(marketing)/open-source/page.tsx create mode 100644 apps/web/src/app/(marketing)/pricing/page.tsx create mode 100644 apps/web/src/app/(marketing)/receiving/page.tsx create mode 100644 apps/web/src/app/(marketing)/security/page.tsx create mode 100644 apps/web/src/app/(marketing)/smtp/page.tsx create mode 100644 apps/web/src/app/(marketing)/tools/dkim/dkim-checker.tsx create mode 100644 apps/web/src/app/(marketing)/tools/dkim/page.tsx create mode 100644 apps/web/src/app/(marketing)/tools/dmarc/dmarc-checker.tsx create mode 100644 apps/web/src/app/(marketing)/tools/dmarc/page.tsx create mode 100644 apps/web/src/app/(marketing)/tools/page.tsx create mode 100644 apps/web/src/app/(marketing)/tools/spf/page.tsx create mode 100644 apps/web/src/app/(marketing)/tools/spf/spf-checker.tsx create mode 100644 apps/web/src/app/api/tools/dkim/route.ts create mode 100644 apps/web/src/app/api/tools/dmarc/route.ts create mode 100644 apps/web/src/app/api/tools/spf/route.ts create mode 100644 apps/web/src/components/marketing/tools/tool-page.tsx create mode 100644 apps/web/src/components/marketing/tools/tool-result.tsx create mode 100644 apps/web/src/components/marketing/tools/use-tool-check.ts create mode 100644 apps/web/src/server/service/dkim-check-service.ts create mode 100644 apps/web/src/server/service/dmarc-check-service.ts create mode 100644 apps/web/src/server/service/dmarc-check-service.unit.test.ts create mode 100644 apps/web/src/server/service/spf-check-service.ts create mode 100644 apps/web/src/server/service/spf-dkim-check.unit.test.ts create mode 100644 apps/web/src/server/service/tool-rate-limit.ts create mode 100644 packages/sdk/src/inbound.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index f4fc017..6a5e06f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 --- +## [0.9.2] - 2026-10-21 + +### Added +- **Pricing page** at `/pricing`: the plan cards and calculator, plus every plan limit side by side, what's included on every plan, and a pricing FAQ +- **Compare page** at `/compare`: the full feature comparison with Resend, SendGrid, Postmark and Amazon SES, when each is the better fit, and how to switch +- **Receiving page** at `/receiving`: how receiving works, what people build with it (reply by email, invoice parsing, support inboxes, polling the API) and each plan's allowance +- **Free DMARC checker** at `/tools/dmarc`: check any domain's DMARC record, see what's wrong in plain language, and get a record to publish +- **Free SPF and DKIM checkers** at `/tools/spf` and `/tools/dkim`, with a `/tools` page listing all three. SPF counts DNS lookups through every include against the limit of 10; DKIM finds keys under common selectors and checks their strength +- **SMTP relay page** at `/smtp`: connection settings and ready-to-paste setup for Node, Laravel, Django, Rails and WordPress +- **Open source page** at `/open-source`: what the AGPL means for you, how to run ByteSend yourself, and how cloud and self-hosted compare +- **Security page** at `/security`: how your account, email and data are protected, who processes your data, and how to report a vulnerability +- **Receiving in the TypeScript SDK** (`bytesend-js` 0.2.0): `bytesend.inbound.list()`, `get()` and `downloadAttachment()`, with `email.received` webhooks verified and typed through `bytesend.webhooks()` + +### Changed +- The website footer is grouped into Product, Features, Free tools, Resources and Company + +### Fixed +- The DPA and privacy policy list the same sub-processors: NodeByte Hosting, Amazon Web Services (now including S3 for received email), Stripe and Simple Analytics + +--- + ## [0.9.1] - 2026-10-21 ### Added @@ -1055,7 +1076,8 @@ Initial public beta release of ByteSend: an all-in-one email infrastructure plat --- -[Unreleased]: https://github.com/ByteSendApp/ByteSend/compare/v0.9.1...HEAD +[Unreleased]: https://github.com/ByteSendApp/ByteSend/compare/v0.9.2...HEAD +[0.9.2]: https://github.com/ByteSendApp/ByteSend/compare/v0.9.1...v0.9.2 [0.9.1]: https://github.com/ByteSendApp/ByteSend/compare/v0.9.0...v0.9.1 [0.9.0]: https://github.com/ByteSendApp/ByteSend/compare/v0.8.0...v0.9.0 [0.8.0]: https://github.com/ByteSendApp/ByteSend/compare/v0.7.0...v0.8.0 diff --git a/apps/docs/guides/inbound-email.mdx b/apps/docs/guides/inbound-email.mdx index 4360359..0d52d80 100644 --- a/apps/docs/guides/inbound-email.mdx +++ b/apps/docs/guides/inbound-email.mdx @@ -93,20 +93,58 @@ Add a webhook and choose the **email.received** event (under *Inbound events*). - **Authentication:** `spf`, `dkim` and `dmarc` say whether the sender is who they claim to be. Be careful acting on mail where these are `fail`. Messages with a virus are kept but never forwarded. - Verify the webhook's signature as described in [Webhooks](/guides/webhooks#signature-verification). +With the TypeScript SDK (`bytesend-js` 0.2 or later), the event is verified and typed for you: + +```ts +import { ByteSend } from "bytesend-js"; + +const webhooks = new ByteSend("bs_...").webhooks(process.env.BYTESEND_WEBHOOK_SECRET!); + +export async function POST(request: Request) { + const event = webhooks.constructEvent(await request.text(), { headers: request.headers }); + + if (event.type === "email.received" && event.data.inReplyToEmailId) { + await comments.create({ thread: event.data.inReplyToEmailId, body: event.data.text }); + } + + return new Response("ok"); +} +``` + ## Fetching received mail from the API -```bash + + +```ts Node.js +const { data } = await bytesend.inbound.list({ limit: 20 }); +``` + +```bash cURL curl https://bytesend.cloud/api/v1/inbound/emails?limit=20 \ -H "Authorization: Bearer bs_..." ``` + + Filter with `recipient`, `since` (an ISO 8601 time) and `page`. Get one message, including its text, HTML and attachment links: -```bash + + +```ts Node.js +const { data: email } = await bytesend.inbound.get("inb_4f1c2a9e8d7b6a5c4f3e2d1c"); + +for (const attachment of email!.attachments) { + const file = await bytesend.inbound.downloadAttachment(attachment); +} +``` + +```bash cURL curl https://bytesend.cloud/api/v1/inbound/emails/inb_4f1c2a9e8d7b6a5c4f3e2d1c \ -H "Authorization: Bearer bs_..." ``` + + API keys limited to one domain only see mail received on that domain. ## Forwarding diff --git a/apps/web/src/app/(marketing)/compare/page.tsx b/apps/web/src/app/(marketing)/compare/page.tsx new file mode 100644 index 0000000..b5767e6 --- /dev/null +++ b/apps/web/src/app/(marketing)/compare/page.tsx @@ -0,0 +1,190 @@ +import type { Metadata } from "next"; +import Link from "next/link"; +import { notFound } from "next/navigation"; +import { ArrowRight } from "lucide-react"; +import { Button } from "@bytesend/ui/src/button"; +import { CallToAction } from "~/components/marketing/CallToAction"; +import { ComparisonGrid } from "~/components/marketing/Comparison"; +import { Reveal } from "~/components/marketing/Reveal"; +import { HairlineGrid, Section, SectionHeader } from "~/components/marketing/Section"; +import { highlightCode } from "~/lib/highlighter"; +import { isCloud } from "~/utils/common"; + +export const metadata: Metadata = { + title: "ByteSend vs Resend, SendGrid, Postmark and Amazon SES", + description: + "An honest comparison of ByteSend with Resend, SendGrid, Postmark and sending through Amazon SES directly: features, free tiers, and when each one is the better fit.", + alternates: { canonical: "https://bytesend.cloud/compare" }, +}; + +const PROVIDERS = [ + { + name: "Resend", + them: "You want React Email built in from the people who created it, and a polished, developer-first API.", + us: "You want the same developer experience with open source code you can self-host, receiving that's out of beta, DMARC reports, and pricing in your own currency.", + }, + { + name: "SendGrid", + them: "You need a long-established provider with enterprise contracts, or you already run on Twilio.", + us: "You want a simpler product with a permanent free tier instead of a trial, clear pay-as-you-go pricing, and code you can read and run yourself.", + }, + { + name: "Postmark", + them: "You only send transactional email and want a provider focused on nothing else.", + us: "You send marketing email too, with a visual editor and contact books, and want 5,000 free emails a month to start instead of 100.", + }, + { + name: "Amazon SES", + them: "You have engineers to build bounce handling, suppression lists, dashboards and webhooks yourself, and want the lowest possible raw price.", + us: "You want all of that already built on top of SES. ByteSend runs on SES, so you can also self-host it on your own AWS account.", + }, +]; + +const BEFORE = `import { Resend } from "resend"; + +const resend = new Resend("re_••••••••"); + +await resend.emails.send({ + from: "hello@yourapp.com", + to: "jane@example.com", + subject: "Welcome", + html: "

Thanks for signing up!

", +});`; + +const AFTER = `import { ByteSend } from "bytesend-js"; + +const bytesend = new ByteSend("bs_••••••••"); + +await bytesend.emails.send({ + from: "hello@yourapp.com", + to: "jane@example.com", + subject: "Welcome", + html: "

Thanks for signing up!

", +});`; + +const STEPS = [ + { + title: "Add your domain", + text: "Add the DNS records we show you. If your domain is on Cloudflare, paste an API token and we add them for you.", + }, + { + title: "Swap your API key or SMTP settings", + text: "Use our SDK or REST API, or point your existing SMTP setup at smtp.bytesend.cloud on port 587 or 465, with the username from Settings → SMTP and an API key as the password.", + }, + { + title: "Test without sending", + text: "A test API key simulates deliveries, bounces and complaints, with real webhooks, so you can check your integration before any mail goes out.", + }, + { + title: "Point your webhooks at ByteSend's events", + text: "email.delivered, email.bounced, email.complained and the rest arrive signed, with retries. The SDK verifies and types them for you.", + }, +]; + +export default async function ComparePage() { + if (!isCloud()) notFound(); + + const themes = { dark: "catppuccin-mocha", light: "catppuccin-latte" } as const; + const [beforeHtml, afterHtml] = await Promise.all([ + highlightCode(BEFORE, { lang: "ts", themes }).catch(() => ""), + highlightCode(AFTER, { lang: "ts", themes }).catch(() => ""), + ]); + + return ( +
+
+
+
+

Compare

+

ByteSend and the alternatives

+

+ Every email provider is good at something. Here's an honest look at where ByteSend fits next to Resend, SendGrid, Postmark and + sending through Amazon SES yourself. +

+
+
+
+ +
+ + +
+ +
+ +
+ {PROVIDERS.map((provider) => ( + +
+

ByteSend vs {provider.name}

+
+
+
+

Choose {provider.name} if

+

{provider.them}

+
+
+

Choose ByteSend if

+

{provider.us}

+
+
+
+ ))} +
+
+ +
+ + + {STEPS.map((step, index) => ( +
+

{String(index + 1).padStart(2, "0")}

+

{step.title}

+

{step.text}

+
+ ))} +
+ +
+ {[ + { label: "Before", html: beforeHtml, code: BEFORE }, + { label: "After", html: afterHtml, code: AFTER }, + ].map((sample) => ( +
+
{sample.label}
+ {sample.html ? ( +
+ ) : ( +
+                  {sample.code}
+                
+ )} +
+ ))} +
+ +
+ + +
+
+ + +
+ ); +} diff --git a/apps/web/src/app/(marketing)/dpa/page.tsx b/apps/web/src/app/(marketing)/dpa/page.tsx index 35d3fa4..2dd0901 100644 --- a/apps/web/src/app/(marketing)/dpa/page.tsx +++ b/apps/web/src/app/(marketing)/dpa/page.tsx @@ -171,8 +171,9 @@ export default function DpaPage() { {[ { name: "NodeByte Hosting", role: "Application hosting and infrastructure", loc: "United Kingdom" }, - { name: "Amazon Web Services (SES)", role: "Email delivery infrastructure", loc: "EU / US" }, - { name: "Upstash (Redis)", role: "Queue processing and caching", loc: "EU" }, + { name: "Amazon Web Services (SES, S3)", role: "Sending and receiving email, and storing received email", loc: "EU / US" }, + { name: "Simple Analytics", role: "Privacy-friendly aggregate website analytics", loc: "Netherlands" }, + { name: "Stripe", role: "Payment processing and billing", loc: "United States" }, ].map(({ name, role, loc }) => ( {name} diff --git a/apps/web/src/app/(marketing)/open-source/page.tsx b/apps/web/src/app/(marketing)/open-source/page.tsx new file mode 100644 index 0000000..740f23c --- /dev/null +++ b/apps/web/src/app/(marketing)/open-source/page.tsx @@ -0,0 +1,154 @@ +import type { Metadata } from "next"; +import Link from "next/link"; +import { notFound } from "next/navigation"; +import { ArrowRight } from "lucide-react"; +import { FaGithub } from "react-icons/fa6"; +import { Button } from "@bytesend/ui/src/button"; +import { CallToAction } from "~/components/marketing/CallToAction"; +import { Reveal } from "~/components/marketing/Reveal"; +import { HairlineGrid, Section, SectionHeader } from "~/components/marketing/Section"; +import { highlightCode } from "~/lib/highlighter"; +import { isCloud } from "~/utils/common"; + +export const metadata: Metadata = { + title: "Open source email platform – ByteSend", + description: + "ByteSend is open source under the AGPL-3.0. Read every line, run it on your own servers with your own Amazon SES account, or use our cloud. Same code either way.", + alternates: { canonical: "https://bytesend.cloud/open-source" }, +}; + +const GITHUB = "https://github.com/ByteSendApp/ByteSend"; +const SELF_HOSTING_DOCS = "https://docs.bytesend.cloud/self-hosting/overview"; + +const QUICK_START = `git clone https://github.com/ByteSendApp/ByteSend.git +cd ByteSend +cp docker/prod/.env.example docker/prod/.env +docker compose -f docker/prod/compose.yml --env-file docker/prod/.env up -d`; + +const REASONS = [ + { title: "Read every line", text: "The sending pipeline, the dashboard, the API and the SDKs are all public. Nothing about how your email is handled is hidden." }, + { title: "No lock-in", text: "If you ever want to leave our cloud, run the same software yourself. Your integration only needs a new base URL." }, + { title: "Your data, your servers", text: "Self-hosted, your email, contacts and logs never leave your infrastructure, and you send through your own SES account." }, + { title: "Built in the open", text: "Issues, pull requests and the roadmap happen on GitHub, and every release is in the changelog." }, +]; + +const COMPARE = [ + { label: "Where it runs", cloud: "Our infrastructure", self: "Your servers" }, + { label: "Sending", cloud: "Through our Amazon SES accounts", self: "Through your own Amazon SES account" }, + { label: "Cost", cloud: "Free up to 5,000 emails a month, then plans from $5", self: "Free software. You pay your hosting and AWS directly" }, + { label: "Updates", cloud: "Automatic", self: "Pull new images when you're ready" }, + { label: "Plan limits", cloud: "Per plan", self: "None" }, + { label: "Features", cloud: "Everything", self: "Everything" }, +]; + +export default async function OpenSourcePage() { + if (!isCloud()) notFound(); + + const quickStart = await highlightCode(QUICK_START, { + lang: "bash", + themes: { dark: "catppuccin-mocha", light: "catppuccin-latte" }, + }).catch(() => ""); + + return ( +
+
+
+
+

Open source

+

Email infrastructure you can read, run and own

+

+ ByteSend is open source under the AGPL-3.0. Use our cloud, or run the same code on your own servers with your own Amazon SES + account. +

+ +
+ + +
Run it yourself
+ {quickStart ? ( +
+ ) : ( +
+                {QUICK_START}
+              
+ )} +

+ Starts the app, PostgreSQL, Redis, storage and the SMTP relay. Fill in your SES credentials in .env first. +

+ +
+
+ +
+ + + {REASONS.map((reason) => ( +
+

{reason.title}

+

{reason.text}

+
+ ))} +
+
+ +
+ + + + + + + + + + + {COMPARE.map((row) => ( + + + + + + ))} + +
+ ByteSend CloudSelf-hosted
{row.label}{row.cloud}{row.self}
+
+
+ +

+ Cloud pricing + +

+

No servers to run. Free to start, and you only pay for what you send.

+ + +

+ The AGPL-3.0 licence + +

+

+ Using ByteSend puts no obligations on your own code. If you change ByteSend and offer it as a service, you share those changes. +

+
+
+
+ + +
+ ); +} diff --git a/apps/web/src/app/(marketing)/pricing/page.tsx b/apps/web/src/app/(marketing)/pricing/page.tsx new file mode 100644 index 0000000..d737b6e --- /dev/null +++ b/apps/web/src/app/(marketing)/pricing/page.tsx @@ -0,0 +1,227 @@ +import type { Metadata } from "next"; +import Link from "next/link"; +import { notFound } from "next/navigation"; +import { Check, Minus } from "lucide-react"; +import { PLANS, type PlanType } from "@bytesend/lib"; +import { CallToAction } from "~/components/marketing/CallToAction"; +import { Pricing } from "~/components/marketing/PricingSection"; +import { Reveal } from "~/components/marketing/Reveal"; +import { Section, SectionHeader } from "~/components/marketing/Section"; +import { isCloud } from "~/utils/common"; + +export const metadata: Metadata = { + title: "Pricing – ByteSend", + description: + "Start free with 5,000 emails a month. Paid plans from $5 include a monthly allowance, then you pay per 1,000 emails. Every limit, add-on and answer in one place.", + alternates: { canonical: "https://bytesend.cloud/pricing" }, +}; + +const PLAN_ORDER: PlanType[] = ["FREE", "HOBBY", "BASIC", "SCALE"]; +const number = new Intl.NumberFormat("en-US"); +const usd = (value: number) => `$${value.toFixed(2)}`; + +type Cell = string | boolean; +interface Row { + label: string; + hint?: string; + value(plan: PlanType): Cell; +} + +const limits = (plan: PlanType) => PLANS[plan].limits; +const perThousand = (plan: PlanType, kind: "transactional" | "marketing") => { + const rate = PLANS[plan].usageMetering?.[kind]; + return rate === undefined ? "Hard limit" : `${usd(rate * 1000)} / 1,000`; +}; + +const GROUPS: Array<{ title: string; rows: Row[] }> = [ + { + title: "Sending", + rows: [ + { label: "Price", value: (plan) => (PLANS[plan].monthlyPrice === 0 ? "Free" : `$${PLANS[plan].monthlyPrice / 100} / month`) }, + { label: "Emails included", hint: "Each month", value: (plan) => number.format(limits(plan).monthlyEmailLimit) }, + { + label: "Daily sending limit", + value: (plan) => (Number.isFinite(limits(plan).dailyEmailLimit) ? number.format(limits(plan).dailyEmailLimit) : "None"), + }, + { label: "Extra transactional email", value: (plan) => perThousand(plan, "transactional") }, + { label: "Extra marketing email", value: (plan) => perThousand(plan, "marketing") }, + { label: "SMTP connections at once", value: (plan) => String(limits(plan).concurrentConnections) }, + ], + }, + { + title: "Receiving", + rows: [ + { label: "Received emails", hint: "Each month", value: (plan) => number.format(limits(plan).inboundEmailsPerMonth) }, + { label: "Hosted address and your own domains", value: () => true }, + { label: "DMARC reports", value: () => true }, + ], + }, + { + title: "Team and audience", + rows: [ + { label: "Domains", value: (plan) => String(limits(plan).maxDomains) }, + { label: "Team members", value: (plan) => String(limits(plan).maxTeamMembers) }, + { label: "Marketing contacts", value: (plan) => number.format(limits(plan).contactsLimit) }, + { label: "Contact books", value: (plan) => number.format(limits(plan).maxContactBooks) }, + { label: "Campaigns", hint: "In total", value: (plan) => number.format(limits(plan).campaignsLimit) }, + { label: "Webhooks", value: (plan) => String(limits(plan).maxWebhooks) }, + ], + }, + { + title: "Insights and support", + rows: [ + { label: "Delivery, bounce and complaint tracking", value: () => true }, + { label: "Open and click analytics", value: (plan) => limits(plan).advancedAnalytics }, + { label: "Priority support", value: (plan) => limits(plan).prioritySupport }, + ], + }, +]; + +const INCLUDED = [ + "REST API, SMTP relay and SDKs for TypeScript, Python and Go", + "Transactional and marketing email, with templates and a visual editor", + "Signed webhooks for every email, domain and contact event", + "Test mode keys that simulate delivery, bounces and complaints", + "Automatic bounce and complaint suppression", + "DKIM, SPF and DMARC setup with DNS monitoring", + "One-click DNS setup for domains on Cloudflare", + "A choice of AWS sending regions for each domain", +]; + +const FAQ = [ + { + q: "How does paying for extra email work?", + a: "Paid plans include a monthly allowance. If you send more, extra emails are billed per 1,000 at your plan's rate, and the rate gets cheaper on bigger plans. The Free plan has a hard limit instead, so you're never charged.", + }, + { + q: "What's the difference between transactional and marketing email?", + a: "Transactional email is sent to one person because of something they did, like a password reset or receipt, through the API or SMTP. Marketing email is a campaign or broadcast sent to a contact book. Marketing costs a little more because it carries more deliverability risk.", + }, + { + q: "What happens when I reach the Free plan's limit?", + a: "Sending pauses until your allowance resets, and nothing is charged. New accounts also have a lower daily limit during their first week while we check for abuse.", + }, + { + q: "Do received emails count toward my sending allowance?", + a: "No. Received email has its own monthly allowance on every plan, and DMARC reports don't count toward either.", + }, + { + q: "Do test mode emails cost anything?", + a: "No. Emails sent with a test key are never delivered and don't count toward usage. Each team can send up to 1,000 test emails a day.", + }, + { + q: "Which currencies can I pay in?", + a: "US dollars, pounds sterling or euros. Checkout shows prices in your local currency where we support it. Prices exclude VAT and sales tax, which are added at checkout where they apply.", + }, + { + q: "Can I change plans or cancel?", + a: "Yes, at any time from Settings → Billing.", + }, + { + q: "Is self-hosting free?", + a: "Yes. ByteSend is open source under the AGPL-3.0. When you self-host there are no plans or limits, and you pay Amazon SES directly for sending.", + }, + { + q: "I send more than 500,000 emails a month.", + a: "Talk to us on Discord and we'll put together a custom plan with your own limits and dedicated support.", + }, +]; + +function CellValue({ value }: { value: Cell }) { + if (value === true) return ; + if (value === false) return ; + return {value}; +} + +export default function PricingPage() { + if (!isCloud()) notFound(); + + return ( +
+ + +
+ + + + + + + {PLAN_ORDER.map((plan) => ( + + ))} + + + {GROUPS.map((group) => ( + + + + + {group.rows.map((row) => ( + + + {PLAN_ORDER.map((plan) => ( + + ))} + + ))} + + ))} +
Plan + {PLANS[plan].displayName} +
+ {group.title} +
+ {row.label} + {row.hint ? {row.hint} : null} + + +
+
+

+ Prices in US dollars. Pounds and euros are shown in the plan cards above and at checkout. +

+
+ +
+
+ +

Included on every plan

+

+ No feature gates on the basics. Plans differ in volume and team size, not in what you can build. +

+
    + {INCLUDED.map((item) => ( +
  • + + {item} +
  • + ))} +
+

+ Wondering how we compare?{" "} + + See ByteSend next to Resend, SendGrid, Postmark and Amazon SES + + . +

+
+ + +

Questions

+
+ {FAQ.map((item) => ( +
+
{item.q}
+
{item.a}
+
+ ))} +
+
+
+
+ + +
+ ); +} diff --git a/apps/web/src/app/(marketing)/privacy/page.tsx b/apps/web/src/app/(marketing)/privacy/page.tsx index 343ea5d..a4f3c73 100644 --- a/apps/web/src/app/(marketing)/privacy/page.tsx +++ b/apps/web/src/app/(marketing)/privacy/page.tsx @@ -165,7 +165,7 @@ export default function PrivacyPage() { {[ { p: "NodeByte Hosting", purpose: "Application hosting, networking, security", loc: "United Kingdom" }, - { p: "Amazon Web Services (SES)", purpose: "Transactional email delivery", loc: "EU / US" }, + { p: "Amazon Web Services (SES, S3)", purpose: "Sending and receiving email, and storing received email", loc: "EU / US" }, { p: "Simple Analytics", purpose: "Privacy-friendly aggregate analytics", loc: "Netherlands" }, { p: "Stripe", purpose: "Payment processing and billing", loc: "United States" }, ].map(({ p, purpose, loc }) => ( diff --git a/apps/web/src/app/(marketing)/receiving/page.tsx b/apps/web/src/app/(marketing)/receiving/page.tsx new file mode 100644 index 0000000..d16f6cf --- /dev/null +++ b/apps/web/src/app/(marketing)/receiving/page.tsx @@ -0,0 +1,229 @@ +import type { Metadata } from "next"; +import Link from "next/link"; +import { notFound } from "next/navigation"; +import { ArrowRight, AtSign, FileText, Forward, Inbox, MessageSquareReply, ShieldCheck, Webhook } from "lucide-react"; +import { PLANS, type PlanType } from "@bytesend/lib"; +import { Button } from "@bytesend/ui/src/button"; +import { CallToAction } from "~/components/marketing/CallToAction"; +import { Reveal } from "~/components/marketing/Reveal"; +import { HairlineGrid, Section, SectionHeader } from "~/components/marketing/Section"; +import { highlightCode, type HighlightLang } from "~/lib/highlighter"; +import { isCloud } from "~/utils/common"; + +export const metadata: Metadata = { + title: "Receive email in your app – ByteSend", + description: + "Receive email on a hosted address or your own domain, and get every message as a webhook, through the API, in an inbox, or forwarded on.", + alternates: { canonical: "https://bytesend.cloud/receiving" }, +}; + +const DOCS = "https://docs.bytesend.cloud/guides/inbound-email"; +const PLAN_ORDER: PlanType[] = ["FREE", "HOBBY", "BASIC", "SCALE"]; +const number = new Intl.NumberFormat("en-US"); + +const STEPS = [ + { + icon: AtSign, + title: "Pick an address", + text: "Use your team's hosted address straight away, or receive on a subdomain of your own domain like reply.yourapp.com with one MX record.", + }, + { + icon: ShieldCheck, + title: "Mail arrives", + text: "We receive it, scan it for spam and viruses, check SPF, DKIM and DMARC, and split out the text, HTML and attachments.", + }, + { + icon: Webhook, + title: "You get it", + text: "As an email.received webhook, through the API, in the dashboard inbox, or forwarded to any mailbox. Use one or all four.", + }, +]; + +const USE_CASES: Array<{ + icon: typeof Inbox; + title: string; + text: string; + file: string; + lang: HighlightLang; + code: string; +}> = [ + { + icon: MessageSquareReply, + title: "Reply by email", + text: "Let people answer a notification straight from their inbox. Replies to email you sent through ByteSend come with the original email's ID, so you know exactly which thread they belong to. The SDK checks the signature and types the event for you.", + file: "app/api/inbound/route.ts", + lang: "ts", + code: `import { ByteSend } from "bytesend-js"; + +const webhooks = new ByteSend().webhooks(process.env.BYTESEND_WEBHOOK_SECRET!); + +export async function POST(req: Request) { + const event = webhooks.constructEvent(await req.text(), { headers: req.headers }); + + if (event.type === "email.received" && event.data.inReplyToEmailId) { + const { inReplyToEmailId, from, text } = event.data; + await comments.create({ thread: inReplyToEmailId, author: from, body: text }); + } + return new Response("ok"); +}`, + }, + { + icon: FileText, + title: "Parse invoices and receipts", + text: "Give each customer an address like acme+invoices@ and pull the PDFs out of everything that arrives. Every attachment comes with a signed download link.", + file: "import-invoices.ts", + lang: "ts", + code: `const { from, attachments } = event.data; + +for (const file of attachments) { + if (file.contentType !== "application/pdf") continue; + const pdf = await fetch(file.url).then((res) => res.arrayBuffer()); + await invoices.import({ vendor: from, pdf }); +}`, + }, + { + icon: Inbox, + title: "A support inbox", + text: "Point support@ at a receiving subdomain, read everything in the dashboard inbox, and forward a copy to your helpdesk. Replies go back to the customer, not to us.", + file: "Forwarding rule", + lang: "bash", + code: `support@reply.yourapp.com → team@yourapp.com`, + }, + { + icon: Forward, + title: "Process mail on your schedule", + text: "No public endpoint? Fetch received mail from the API whenever it suits you, filtered by address or time.", + file: "terminal", + lang: "bash", + code: `curl "https://bytesend.cloud/api/v1/inbound/emails?recipient=support@reply.yourapp.com" \\ + -H "Authorization: Bearer bs_••••••••"`, + }, +]; + +const DETAILS = [ + { title: "+tags on every address", text: "acme+orders@ and acme+invoices@ both arrive, so you can tell senders apart without new addresses." }, + { title: "Authentication results", text: "Every message shows whether SPF, DKIM and DMARC passed, plus spam and virus verdicts." }, + { title: "Signed webhooks", text: "Each delivery is signed and retried until your endpoint accepts it." }, + { title: "Kept for 30 days", text: "Messages and attachments stay in your inbox and API for 30 days, then they're deleted." }, + { title: "DMARC reports included", text: "Point your DMARC record at ByteSend and we read the reports for you. They don't count toward your allowance." }, + { title: "Open source", text: "Receiving is part of the AGPL codebase, so you can run it on your own AWS account too." }, +]; + +export default async function ReceivingPage() { + if (!isCloud()) notFound(); + + const samples = await Promise.all( + USE_CASES.map((useCase) => + highlightCode(useCase.code, { + lang: useCase.lang, + themes: { dark: "catppuccin-mocha", light: "catppuccin-latte" }, + }).catch(() => ""), + ), + ); + + return ( +
+
+
+
+

Receiving

+

Receive email in your app

+

+ ByteSend doesn't just send. Give your app an address, and every message that arrives reaches you as a webhook, through the API, + in an inbox, or forwarded on. +

+
+ + +
+

+ {number.format(PLANS.FREE.limits.inboundEmailsPerMonth)} received emails a month free · No credit card +

+
+
+
+ +
+ + + {STEPS.map((step, index) => ( + + +

{step.title}

+

{step.text}

+
+ ))} +
+
+ +
+ +
+ {USE_CASES.map((useCase, index) => ( + +
+ +

{useCase.title}

+

{useCase.text}

+
+
+
{useCase.file}
+ {samples[index] ? ( +
+ ) : ( +
+                    {useCase.code}
+                  
+ )} +
+ + ))} +
+
+ +
+ + + {DETAILS.map((detail) => ( +
+

{detail.title}

+

{detail.text}

+
+ ))} +
+
+ +
+ + + {PLAN_ORDER.map((plan) => ( +
+

{PLANS[plan].displayName}

+

{number.format(PLANS[plan].limits.inboundEmailsPerMonth)}

+

received emails a month

+
+ ))} +
+

+ + See full pricing + +

+
+ + +
+ ); +} diff --git a/apps/web/src/app/(marketing)/security/page.tsx b/apps/web/src/app/(marketing)/security/page.tsx new file mode 100644 index 0000000..a96a3b2 --- /dev/null +++ b/apps/web/src/app/(marketing)/security/page.tsx @@ -0,0 +1,142 @@ +import type { Metadata } from "next"; +import Link from "next/link"; +import { notFound } from "next/navigation"; +import { isCloud } from "~/utils/common"; + +export const metadata: Metadata = { + title: "Security – ByteSend", + description: "How ByteSend protects your account, your email and your data, who processes it, and how to report a vulnerability.", + alternates: { canonical: "https://bytesend.cloud/security" }, +}; + +const SECTIONS: Array<{ id: string; title: string; items: string[] }> = [ + { + id: "data", + title: "Your data", + items: [ + "All traffic to and from ByteSend is encrypted with TLS, and the database is encrypted at rest.", + "API keys are stored as one-way scrypt hashes. We show a key once, when you create it, and can't recover it afterwards.", + "Received email and its attachments are deleted after 30 days, DMARC reports after 90 days, and email sending logs after up to 12 months.", + "Access to customer data is limited to staff who need it, and staff actions on accounts are recorded in an audit log.", + ], + }, + { + id: "accounts", + title: "Your account", + items: [ + "Sign in with GitHub, Google, Discord, an email link, or a password.", + "Two-factor authentication with any authenticator app, with recovery codes in case you lose your device.", + "API keys can be limited to a single domain, and test keys can never send real email.", + ], + }, + { + id: "email", + title: "Your email", + items: [ + "Webhooks are signed with HMAC-SHA256 and a timestamp, so you can verify they came from us and reject replays.", + "Links to received attachments are signed, expire after an hour, and always download rather than open in the browser.", + "Received HTML is shown in a sandboxed frame with no scripts. Incoming mail is scanned for spam and viruses, and infected mail is never forwarded.", + "Outgoing mail is scanned for phishing and abuse before it's queued, and hard bounces and complaints are suppressed automatically.", + "Domains are re-checked twice a day, and you're told if a DKIM, SPF or MX record changes.", + ], + }, + { + id: "open-source", + title: "Open source", + items: [ + "ByteSend's code is public under the AGPL-3.0, so anyone can review how your email and data are handled.", + "Dependencies are kept up to date, and fixes for security issues ship in the latest and previous stable releases.", + ], + }, +]; + +const PROCESSORS = [ + { name: "NodeByte Hosting", role: "Application hosting, database and networking", location: "United Kingdom" }, + { name: "Amazon Web Services (SES, S3)", role: "Sending and receiving email, and storing received email", location: "EU / US" }, + { name: "Stripe", role: "Payment processing and billing", location: "United States" }, + { name: "Simple Analytics", role: "Privacy-friendly aggregate website analytics", location: "Netherlands" }, +]; + +export default function SecurityPage() { + if (!isCloud()) notFound(); + + return ( +
+
+

Security

+

Keeping your email safe

+

+ How we protect your account, your email and your data, who helps us process it, and how to tell us about a problem. +

+ +
+ {SECTIONS.map((section) => ( +
+

{section.title}

+
    + {section.items.map((item) => ( +
  • + + {item} +
  • + ))} +
+
+ ))} + +
+

Who processes your data

+

+ The companies that help us run ByteSend. Our{" "} + + Data Processing Agreement + {" "} + covers how we use them. +

+
+ + + + + + + + + + {PROCESSORS.map((processor) => ( + + + + + + ))} + +
CompanyWhat forWhere
{processor.name}{processor.role}{processor.location}
+
+
+ +
+

Report a vulnerability

+

+ Please don't open a public GitHub issue. Email{" "} + + security@nodebyte.co.uk + {" "} + with [SECURITY] in the subject, and include the affected component, steps to reproduce, and + the impact. +

+
    +
  • We acknowledge reports within 72 hours.
  • +
  • We assess severity, plan a fix, and agree disclosure with you.
  • +
  • If you'd like, we credit you in the release notes.
  • +
+

+ In scope: remote code execution, authentication bypass, data exposure, injection, and SSRF. Missing best-practice headers, self-XSS and + rate-limit bypasses with no real impact are out of scope. +

+
+
+
+
+ ); +} diff --git a/apps/web/src/app/(marketing)/smtp/page.tsx b/apps/web/src/app/(marketing)/smtp/page.tsx new file mode 100644 index 0000000..147c66d --- /dev/null +++ b/apps/web/src/app/(marketing)/smtp/page.tsx @@ -0,0 +1,187 @@ +import type { Metadata } from "next"; +import Link from "next/link"; +import { notFound } from "next/navigation"; +import { ArrowRight } from "lucide-react"; +import { Button } from "@bytesend/ui/src/button"; +import { CallToAction } from "~/components/marketing/CallToAction"; +import { Reveal } from "~/components/marketing/Reveal"; +import { HairlineGrid, Section, SectionHeader } from "~/components/marketing/Section"; +import { highlightCode, type HighlightLang } from "~/lib/highlighter"; +import { isCloud } from "~/utils/common"; + +export const metadata: Metadata = { + title: "SMTP relay service – ByteSend", + description: + "Send email from any app that speaks SMTP: WordPress, Laravel, Django, Rails, Node and more. Change one setting, keep your code, and get delivery tracking and analytics.", + alternates: { canonical: "https://bytesend.cloud/smtp" }, +}; + +const SETTINGS = [ + { label: "Host", value: "smtp.bytesend.cloud" }, + { label: "Port (STARTTLS)", value: "587 or 2587" }, + { label: "Port (TLS)", value: "465 or 2465" }, + { label: "Username", value: "Your SMTP username, from Settings → SMTP" }, + { label: "Password", value: "An API key" }, +]; + +const SNIPPETS: Array<{ name: string; file: string; lang: HighlightLang; code: string }> = [ + { + name: "Node.js", + file: "mailer.ts", + lang: "ts", + code: `import nodemailer from "nodemailer"; + +const transport = nodemailer.createTransport({ + host: "smtp.bytesend.cloud", + port: 587, + auth: { user: process.env.BYTESEND_SMTP_USER, pass: process.env.BYTESEND_API_KEY }, +}); + +await transport.sendMail({ + from: "hello@yourapp.com", + to: "jane@example.com", + subject: "Welcome", + html: "

Thanks for signing up!

", +});`, + }, + { + name: "Laravel", + file: ".env", + lang: "bash", + code: `MAIL_MAILER=smtp +MAIL_HOST=smtp.bytesend.cloud +MAIL_PORT=587 +MAIL_USERNAME=your-smtp-username +MAIL_PASSWORD=bs_•••••••• +MAIL_FROM_ADDRESS=hello@yourapp.com`, + }, + { + name: "Django", + file: "settings.py", + lang: "python", + code: `import os + +EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" +EMAIL_HOST = "smtp.bytesend.cloud" +EMAIL_PORT = 587 +EMAIL_USE_TLS = True +EMAIL_HOST_USER = os.environ["BYTESEND_SMTP_USER"] +EMAIL_HOST_PASSWORD = os.environ["BYTESEND_API_KEY"]`, + }, + { + name: "Rails", + file: "config/environments/production.rb", + lang: "ruby", + code: `config.action_mailer.delivery_method = :smtp +config.action_mailer.smtp_settings = { + address: "smtp.bytesend.cloud", + port: 587, + user_name: ENV["BYTESEND_SMTP_USER"], + password: ENV["BYTESEND_API_KEY"], + enable_starttls_auto: true, +}`, + }, +]; + +const WHY = [ + { title: "No code changes", text: "Anything that can send email over SMTP works, including apps and plugins you can't edit." }, + { title: "Every email tracked", text: "Mail sent over SMTP shows up in your dashboard with its delivery status, just like the API." }, + { title: "Bounces handled for you", text: "Hard bounces and spam complaints are suppressed automatically, protecting your sender reputation." }, + { title: "Your domain, signed", text: "DKIM, SPF and DMARC for your domain, so mail lands in the inbox instead of spam." }, + { title: "Webhooks too", text: "Get delivered, bounced, opened and clicked events for SMTP mail, signed and retried." }, + { title: "Same price as the API", text: "SMTP email counts toward your plan like any other. 5,000 a month free." }, +]; + +export default async function SmtpPage() { + if (!isCloud()) notFound(); + + const highlighted = await Promise.all( + SNIPPETS.map((snippet) => + highlightCode(snippet.code, { lang: snippet.lang, themes: { dark: "catppuccin-mocha", light: "catppuccin-latte" } }).catch(() => ""), + ), + ); + + return ( +
+
+
+
+

SMTP relay

+

Change one setting, keep your code

+

+ Point any app that sends email over SMTP at ByteSend: WordPress, Laravel, Django, Rails, Node, or software you can't change. + You get delivery tracking, bounce handling and analytics without touching your code. +

+
+ + +
+
+ + +
Connection settings
+
+ {SETTINGS.map((setting) => ( +
+
{setting.label}
+
{setting.value}
+
+ ))} +
+
+
+
+ +
+ +
+ {SNIPPETS.map((snippet, index) => ( + +
+ {snippet.name} + {snippet.file} +
+ {highlighted[index] ? ( +
+ ) : ( +
+                  {snippet.code}
+                
+ )} + + ))} +
+

+ WordPress: install an SMTP plugin such as WP Mail SMTP, choose "Other SMTP", and + enter the settings above with TLS on port 587. +

+
+ +
+ + + {WHY.map((item) => ( +
+

{item.title}

+

{item.text}

+
+ ))} +
+
+ + +
+ ); +} diff --git a/apps/web/src/app/(marketing)/tools/dkim/dkim-checker.tsx b/apps/web/src/app/(marketing)/tools/dkim/dkim-checker.tsx new file mode 100644 index 0000000..81a76a0 --- /dev/null +++ b/apps/web/src/app/(marketing)/tools/dkim/dkim-checker.tsx @@ -0,0 +1,99 @@ +"use client"; + +import { Search } from "lucide-react"; +import { Button } from "@bytesend/ui/src/button"; +import { Input } from "@bytesend/ui/src/input"; +import { ToolError, ToolResultCard } from "~/components/marketing/tools/tool-result"; +import { useToolCheck } from "~/components/marketing/tools/use-tool-check"; +import type { DkimCheck } from "~/server/service/dkim-check-service"; + +const FIELDS = ["domain", "selector"]; + +const GRADES: Record = { + missing: { label: "Not found", variant: "danger", summary: "No DKIM key found." }, + broken: { label: "Broken", variant: "danger", summary: "A DKIM key exists, but signatures using it will fail." }, + weak: { label: "Weak", variant: "danger", summary: "The DKIM key is too short to be trusted." }, + ok: { label: "OK", variant: "warning", summary: "DKIM works, but a stronger key is recommended." }, + strong: { label: "Strong", variant: "success", summary: "DKIM is set up with a strong key." }, +}; + +export function DkimChecker() { + const { values, setValue, run, result, error, loading } = useToolCheck("/api/tools/dkim", FIELDS); + const domain = values.domain ?? ""; + const grade = result ? GRADES[result.grade] : null; + + return ( +
+
{ + event.preventDefault(); + void run(); + }} + > + setValue("domain", event.target.value)} + placeholder="yourdomain.com" + aria-label="Domain" + autoCapitalize="none" + autoCorrect="off" + spellCheck={false} + inputMode="url" + className="h-11 text-base sm:text-sm" + /> + setValue("selector", event.target.value)} + placeholder="Selector (optional)" + aria-label="Selector" + autoCapitalize="none" + autoCorrect="off" + spellCheck={false} + className="h-11 text-base sm:text-sm" + /> + +
+ + {error ? : null} + + {result && grade ? ( + result.keys.length === 0 ? ( + + ) : ( +
+ {result.keys.map((key) => ( + + ))} +
+ ) + ) : null} +
+ ); +} diff --git a/apps/web/src/app/(marketing)/tools/dkim/page.tsx b/apps/web/src/app/(marketing)/tools/dkim/page.tsx new file mode 100644 index 0000000..5a55456 --- /dev/null +++ b/apps/web/src/app/(marketing)/tools/dkim/page.tsx @@ -0,0 +1,44 @@ +import type { Metadata } from "next"; +import { notFound } from "next/navigation"; +import { ToolPage } from "~/components/marketing/tools/tool-page"; +import { isCloud } from "~/utils/common"; +import { DkimChecker } from "./dkim-checker"; + +export const metadata: Metadata = { + title: "Free DKIM checker – ByteSend", + description: "Find a domain's DKIM keys and check them: key size, revoked or test-mode keys, and broken records.", + alternates: { canonical: "https://bytesend.cloud/tools/dkim" }, +}; + +const FAQ = [ + { + q: "What is DKIM?", + a: "A signature added to every email you send, checked against a public key in your DNS. It proves the message came from you and wasn't changed on the way.", + }, + { + q: "What's a selector?", + a: "The name your DKIM key is published under, at ._domainkey.yourdomain.com. Each provider uses its own, so a domain can have several keys. You can find it in the s= tag of the DKIM-Signature header on an email you've sent.", + }, + { + q: "How long should my key be?", + a: "2048 bits. 1024-bit keys still work but are considered weak, and anything shorter is ignored by many providers.", + }, + { + q: "Which selector does ByteSend use?", + a: "bytesend, or bytesend- if you've moved a domain to another sending region. The domain page in your dashboard shows the exact record.", + }, +]; + +export default function DkimCheckerPage() { + if (!isCloud()) notFound(); + + return ( + } + faq={FAQ} + /> + ); +} diff --git a/apps/web/src/app/(marketing)/tools/dmarc/dmarc-checker.tsx b/apps/web/src/app/(marketing)/tools/dmarc/dmarc-checker.tsx new file mode 100644 index 0000000..e15ebb5 --- /dev/null +++ b/apps/web/src/app/(marketing)/tools/dmarc/dmarc-checker.tsx @@ -0,0 +1,98 @@ +"use client"; + +import { Search } from "lucide-react"; +import { Button } from "@bytesend/ui/src/button"; +import { Input } from "@bytesend/ui/src/input"; +import { ToolError, ToolResultCard } from "~/components/marketing/tools/tool-result"; +import { useToolCheck } from "~/components/marketing/tools/use-tool-check"; +import type { DmarcCheck, DmarcGrade } from "~/server/service/dmarc-check-service"; + +const FIELDS = ["domain"]; + +const GRADES: Record = { + missing: { label: "Not protected", variant: "danger", summary: "This domain has no DMARC record." }, + invalid: { label: "Broken", variant: "danger", summary: "This domain's DMARC record won't be honoured." }, + monitoring: { label: "Monitoring only", variant: "warning", summary: "DMARC is set up, but spoofed mail is still delivered." }, + partial: { label: "Partly enforced", variant: "warning", summary: "Some spoofed mail is still getting through." }, + enforced: { label: "Enforced", variant: "success", summary: "Mail pretending to be this domain is blocked." }, +}; + +export function DmarcChecker() { + const { values, setValue, run, result, error, loading } = useToolCheck("/api/tools/dmarc", FIELDS); + const domain = values.domain ?? ""; + const grade = result ? GRADES[result.grade] : null; + + return ( +
+
{ + event.preventDefault(); + void run(); + }} + > + setValue("domain", event.target.value)} + placeholder="yourdomain.com" + aria-label="Domain" + autoCapitalize="none" + autoCorrect="off" + spellCheck={false} + inputMode="url" + className="h-11 text-base sm:text-sm" + /> + +
+ + {error ? : null} + + {result && grade ? ( + + {result.record ? "A better record to start from" : "A record to start with"} (TXT at{" "} + _dmarc.{result.lookedUp}) + + ), + value: result.suggestion, + } + : null + } + cta={{ + text: ( + <> + See every server sending as {result.lookedUp}, and whether it passes. ByteSend + reads your DMARC reports for free. + + ), + label: "Get DMARC reports", + href: "/signup", + }} + /> + ) : null} +
+ ); +} diff --git a/apps/web/src/app/(marketing)/tools/dmarc/page.tsx b/apps/web/src/app/(marketing)/tools/dmarc/page.tsx new file mode 100644 index 0000000..ab811a2 --- /dev/null +++ b/apps/web/src/app/(marketing)/tools/dmarc/page.tsx @@ -0,0 +1,53 @@ +import type { Metadata } from "next"; +import { notFound } from "next/navigation"; +import { ToolPage } from "~/components/marketing/tools/tool-page"; +import { isCloud } from "~/utils/common"; +import { DmarcChecker } from "./dmarc-checker"; + +export const metadata: Metadata = { + title: "Free DMARC checker – ByteSend", + description: "Check any domain's DMARC record in seconds: whether it's valid, how strict it is, and what to fix next.", + alternates: { canonical: "https://bytesend.cloud/tools/dmarc" }, +}; + +const FAQ = [ + { + q: "What is DMARC?", + a: "A DNS record that tells mail providers what to do with email that claims to be from your domain but fails SPF and DKIM checks, and where to send reports about it.", + }, + { + q: "Do I need it?", + a: "Yes, if you send email. Gmail and Yahoo require a DMARC record from anyone sending in bulk, and without one your domain is easy to spoof in phishing.", + }, + { + q: "Why not go straight to p=reject?", + a: "Because any legitimate service sending as your domain that isn't set up yet, like a helpdesk or CRM, would have its mail rejected too. Start with p=none, read the reports, fix what fails, then tighten the policy.", + }, + { + q: "What are DMARC reports?", + a: "Daily summaries from Google, Microsoft, Yahoo and others listing every server that sent mail as your domain and whether it passed. They're XML files, which is why ByteSend reads them for you.", + }, +]; + +export default function DmarcCheckerPage() { + if (!isCloud()) notFound(); + + return ( + } + explainer={{ + title: "The three policies", + description: "Most domains should move through them in order.", + items: [ + { label: "p=none", title: "Monitoring", text: "Nothing is blocked. Mail providers send you reports, so you can see who sends as your domain." }, + { label: "p=quarantine", title: "Quarantine", text: "Mail that fails DMARC goes to spam. A good middle step once your legitimate senders pass." }, + { label: "p=reject", title: "Reject", text: "Mail that fails DMARC is refused outright. The goal: nobody can send as your domain." }, + ], + }} + faq={FAQ} + /> + ); +} diff --git a/apps/web/src/app/(marketing)/tools/page.tsx b/apps/web/src/app/(marketing)/tools/page.tsx new file mode 100644 index 0000000..39e3979 --- /dev/null +++ b/apps/web/src/app/(marketing)/tools/page.tsx @@ -0,0 +1,39 @@ +import type { Metadata } from "next"; +import Link from "next/link"; +import { notFound } from "next/navigation"; +import { ArrowRight } from "lucide-react"; +import { TOOLS } from "~/components/marketing/tools/tool-page"; +import { isCloud } from "~/utils/common"; + +export const metadata: Metadata = { + title: "Free email tools – ByteSend", + description: "Free checkers for DMARC, SPF and DKIM. See how well your domain is protected and what to fix, no sign-up needed.", + alternates: { canonical: "https://bytesend.cloud/tools" }, +}; + +export default function ToolsPage() { + if (!isCloud()) notFound(); + + return ( +
+
+

Free tools

+

Check your email setup

+

+ SPF, DKIM and DMARC decide whether your email is trusted. Check each one in seconds, with plain-language results. No sign-up needed. +

+
+ {TOOLS.map((tool) => ( + +

+ {tool.name} + +

+

{tool.text}

+ + ))} +
+
+
+ ); +} diff --git a/apps/web/src/app/(marketing)/tools/spf/page.tsx b/apps/web/src/app/(marketing)/tools/spf/page.tsx new file mode 100644 index 0000000..16dcbbb --- /dev/null +++ b/apps/web/src/app/(marketing)/tools/spf/page.tsx @@ -0,0 +1,52 @@ +import type { Metadata } from "next"; +import { notFound } from "next/navigation"; +import { ToolPage } from "~/components/marketing/tools/tool-page"; +import { isCloud } from "~/utils/common"; +import { SpfChecker } from "./spf-checker"; + +export const metadata: Metadata = { + title: "Free SPF checker – ByteSend", + description: "Check any domain's SPF record: which servers it allows, how many DNS lookups it uses, and whether it's broken.", + alternates: { canonical: "https://bytesend.cloud/tools/spf" }, +}; + +const FAQ = [ + { + q: "What is SPF?", + a: "A DNS record listing the servers allowed to send email for your domain. Mail providers check it to spot mail from servers you didn't authorise.", + }, + { + q: "What's the 10-lookup limit?", + a: "Each include:, a, mx, ptr, exists and redirect= costs a DNS lookup, including the ones inside the records you include. Go over 10 and SPF fails for every message. It's the most common way SPF breaks as you add providers.", + }, + { + q: "Should I use ~all or -all?", + a: "~all is what most senders use: unlisted servers are marked suspicious and DMARC decides what happens. -all is stricter. Both are fine once DMARC is in place. Never use +all.", + }, + { + q: "Where does ByteSend's SPF go?", + a: "On a mail. subdomain of your domain, which ByteSend uses as the bounce address. So it doesn't touch your main SPF record or its lookup count.", + }, +]; + +export default function SpfCheckerPage() { + if (!isCloud()) notFound(); + + return ( + } + explainer={{ + title: "How the record ends matters", + items: [ + { label: "-all", title: "Fail", text: "Mail from unlisted servers fails SPF. The strictest option." }, + { label: "~all", title: "Soft fail", text: "Unlisted servers are marked suspicious, and DMARC decides. What most senders use." }, + { label: "+all", title: "Allow everything", text: "Any server may send as you. This defeats the point of SPF, so never use it." }, + ], + }} + faq={FAQ} + /> + ); +} diff --git a/apps/web/src/app/(marketing)/tools/spf/spf-checker.tsx b/apps/web/src/app/(marketing)/tools/spf/spf-checker.tsx new file mode 100644 index 0000000..b9cc786 --- /dev/null +++ b/apps/web/src/app/(marketing)/tools/spf/spf-checker.tsx @@ -0,0 +1,75 @@ +"use client"; + +import { Search } from "lucide-react"; +import { Button } from "@bytesend/ui/src/button"; +import { Input } from "@bytesend/ui/src/input"; +import { ToolError, ToolResultCard } from "~/components/marketing/tools/tool-result"; +import { useToolCheck } from "~/components/marketing/tools/use-tool-check"; +import type { SpfCheck, SpfGrade } from "~/server/service/spf-check-service"; + +const FIELDS = ["domain"]; + +const GRADES: Record = { + missing: { label: "No SPF", variant: "danger", summary: "This domain doesn't say which servers may send as it." }, + invalid: { label: "Broken", variant: "danger", summary: "Mail providers will treat this SPF record as an error." }, + open: { label: "Wide open", variant: "danger", summary: "This record lets any server send as this domain." }, + neutral: { label: "Weak", variant: "warning", summary: "SPF is set up, but it doesn't reject anything." }, + softfail: { label: "Good", variant: "success", summary: "SPF is set up the way most senders use it." }, + strict: { label: "Strict", variant: "success", summary: "Only the servers listed may send as this domain." }, +}; + +export function SpfChecker() { + const { values, setValue, run, result, error, loading } = useToolCheck("/api/tools/spf", FIELDS); + const domain = values.domain ?? ""; + const grade = result ? GRADES[result.grade] : null; + + return ( +
+
{ + event.preventDefault(); + void run(); + }} + > + setValue("domain", event.target.value)} + placeholder="yourdomain.com" + aria-label="Domain" + autoCapitalize="none" + autoCorrect="off" + spellCheck={false} + inputMode="url" + className="h-11 text-base sm:text-sm" + /> + +
+ + {error ? : null} + + {result && grade ? ( + + ) : null} +
+ ); +} diff --git a/apps/web/src/app/api/tools/dkim/route.ts b/apps/web/src/app/api/tools/dkim/route.ts new file mode 100644 index 0000000..e3711d9 --- /dev/null +++ b/apps/web/src/app/api/tools/dkim/route.ts @@ -0,0 +1,29 @@ +import { logger } from "~/server/logger/log"; +import { DmarcLookupError } from "~/server/service/dmarc-check-service"; +import { checkDomainDkim } from "~/server/service/dkim-check-service"; +import { toolRateLimited } from "~/server/service/tool-rate-limit"; +import { isCloud } from "~/utils/common"; + +export const dynamic = "force-dynamic"; + +export async function GET(request: Request) { + if (!isCloud()) return Response.json({ error: "Not found" }, { status: 404 }); + + const params = new URL(request.url).searchParams; + const domain = params.get("domain") ?? ""; + const selector = params.get("selector"); + if (!domain || domain.length > 300 || (selector?.length ?? 0) > 120) { + return Response.json({ error: "Enter a domain, like example.com." }, { status: 400 }); + } + if (await toolRateLimited(request, "dkim")) { + return Response.json({ error: "That's a lot of checks. Wait a minute and try again." }, { status: 429 }); + } + + try { + return Response.json(await checkDomainDkim(domain, selector), { headers: { "Cache-Control": "no-store" } }); + } catch (error) { + if (error instanceof DmarcLookupError) return Response.json({ error: error.message }, { status: 400 }); + logger.error({ err: error, domain }, "[DkimTool]: Check failed"); + return Response.json({ error: "Something went wrong. Try again in a moment." }, { status: 500 }); + } +} diff --git a/apps/web/src/app/api/tools/dmarc/route.ts b/apps/web/src/app/api/tools/dmarc/route.ts new file mode 100644 index 0000000..57ec97d --- /dev/null +++ b/apps/web/src/app/api/tools/dmarc/route.ts @@ -0,0 +1,26 @@ +import { logger } from "~/server/logger/log"; +import { DmarcLookupError, checkDomainDmarc } from "~/server/service/dmarc-check-service"; +import { toolRateLimited } from "~/server/service/tool-rate-limit"; +import { isCloud } from "~/utils/common"; + +export const dynamic = "force-dynamic"; + +export async function GET(request: Request) { + if (!isCloud()) return Response.json({ error: "Not found" }, { status: 404 }); + + const domain = new URL(request.url).searchParams.get("domain") ?? ""; + if (!domain || domain.length > 300) { + return Response.json({ error: "Enter a domain, like example.com." }, { status: 400 }); + } + if (await toolRateLimited(request, "dmarc")) { + return Response.json({ error: "That's a lot of checks. Wait a minute and try again." }, { status: 429 }); + } + + try { + return Response.json(await checkDomainDmarc(domain), { headers: { "Cache-Control": "no-store" } }); + } catch (error) { + if (error instanceof DmarcLookupError) return Response.json({ error: error.message }, { status: 400 }); + logger.error({ err: error, domain }, "[DmarcTool]: Check failed"); + return Response.json({ error: "Something went wrong. Try again in a moment." }, { status: 500 }); + } +} diff --git a/apps/web/src/app/api/tools/spf/route.ts b/apps/web/src/app/api/tools/spf/route.ts new file mode 100644 index 0000000..112b99e --- /dev/null +++ b/apps/web/src/app/api/tools/spf/route.ts @@ -0,0 +1,27 @@ +import { logger } from "~/server/logger/log"; +import { DmarcLookupError } from "~/server/service/dmarc-check-service"; +import { checkDomainSpf } from "~/server/service/spf-check-service"; +import { toolRateLimited } from "~/server/service/tool-rate-limit"; +import { isCloud } from "~/utils/common"; + +export const dynamic = "force-dynamic"; + +export async function GET(request: Request) { + if (!isCloud()) return Response.json({ error: "Not found" }, { status: 404 }); + + const domain = new URL(request.url).searchParams.get("domain") ?? ""; + if (!domain || domain.length > 300) { + return Response.json({ error: "Enter a domain, like example.com." }, { status: 400 }); + } + if (await toolRateLimited(request, "spf")) { + return Response.json({ error: "That's a lot of checks. Wait a minute and try again." }, { status: 429 }); + } + + try { + return Response.json(await checkDomainSpf(domain), { headers: { "Cache-Control": "no-store" } }); + } catch (error) { + if (error instanceof DmarcLookupError) return Response.json({ error: error.message }, { status: 400 }); + logger.error({ err: error, domain }, "[SpfTool]: Check failed"); + return Response.json({ error: "Something went wrong. Try again in a moment." }, { status: 500 }); + } +} diff --git a/apps/web/src/components/marketing/Comparison.tsx b/apps/web/src/components/marketing/Comparison.tsx index e5968ee..475b189 100644 --- a/apps/web/src/components/marketing/Comparison.tsx +++ b/apps/web/src/components/marketing/Comparison.tsx @@ -8,9 +8,9 @@ import { Reveal } from "./Reveal"; import { Section, SectionHeader } from "./Section"; // Competitor details as published on their pricing and docs pages; re-check before changing claims. -const COMPARISON_CHECKED = "October 2026"; +export const COMPARISON_CHECKED = "October 2026"; -const comparisonRows: { feature: string; bs: string | boolean; resend: string | boolean; sendgrid: string | boolean; postmark: string | boolean; ses: string | boolean }[] = [ +export const comparisonRows: { feature: string; bs: string | boolean; resend: string | boolean; sendgrid: string | boolean; postmark: string | boolean; ses: string | boolean }[] = [ { feature: "Free tier", bs: "5,000/mo (200/day)", resend: "3,000/mo (100/day)", sendgrid: "60-day trial", postmark: "100/mo", ses: "Pay-per-use" }, { feature: "Marketing campaigns", bs: true, resend: true, sendgrid: true, postmark: "Broadcast API", ses: false }, { feature: "Visual email editor", bs: true, resend: true, sendgrid: true, postmark: false, ses: false }, @@ -28,10 +28,6 @@ const comparisonRows: { feature: string; bs: string | boolean; resend: string | const APP_URL = "/signup"; export function ComparisonTable() { - - const cols = ["ByteSend", "Resend", "SendGrid", "Postmark", "AWS SES"] as const; - const vals = (row: (typeof comparisonRows)[0]) => [row.bs, row.resend, row.sendgrid, row.postmark, row.ses] as (string | boolean)[]; - return (
+ + +
+ +

+ + See the full comparison + +

+
+
+ ); +} + +export function ComparisonGrid() { + const cols = ["ByteSend", "Resend", "SendGrid", "Postmark", "AWS SES"] as const; + const vals = (row: (typeof comparisonRows)[0]) => [row.bs, row.resend, row.sendgrid, row.postmark, row.ses] as (string | boolean)[]; + + return ( + <> @@ -76,13 +94,7 @@ export function ComparisonTable() {

Based on each provider's published plans, checked {COMPARISON_CHECKED}.

- -
- -
- + ); } diff --git a/apps/web/src/components/marketing/Hero.tsx b/apps/web/src/components/marketing/Hero.tsx index 387d92f..42b7cef 100644 --- a/apps/web/src/components/marketing/Hero.tsx +++ b/apps/web/src/components/marketing/Hero.tsx @@ -14,7 +14,7 @@ export function Hero() {
New diff --git a/apps/web/src/components/marketing/PricingSection.tsx b/apps/web/src/components/marketing/PricingSection.tsx index 2c475df..8d09d01 100644 --- a/apps/web/src/components/marketing/PricingSection.tsx +++ b/apps/web/src/components/marketing/PricingSection.tsx @@ -43,7 +43,7 @@ function highlights(plan: PlanType) { return items; } -export function Pricing() { +export function Pricing({ showDetailsLink = true }: { showDetailsLink?: boolean } = {}) { const [currency, setCurrency] = React.useState("usd"); return ( @@ -125,6 +125,13 @@ export function Pricing() { Prices exclude VAT and sales tax, which are added at checkout where they apply. Every plan includes the API, SMTP relay, SDKs, webhooks, templates and marketing email.

+ {showDetailsLink ? ( +

+ + Compare every plan limit and read the pricing FAQ + +

+ ) : null}
diff --git a/apps/web/src/components/marketing/SiteFooter.tsx b/apps/web/src/components/marketing/SiteFooter.tsx index 015ffcc..8b7b214 100644 --- a/apps/web/src/components/marketing/SiteFooter.tsx +++ b/apps/web/src/components/marketing/SiteFooter.tsx @@ -13,32 +13,59 @@ const COLUMNS: Array<{ title: string; links: FooterLink[] }> = [ title: "Product", links: [ { label: "Features", href: "/#features", cloudOnly: true }, - { label: "Pricing", href: "/#pricing", cloudOnly: true }, + { label: "Pricing", href: "/pricing", cloudOnly: true }, + { label: "Compare", href: "/compare", cloudOnly: true }, { label: "Changelog", href: "/changelog", cloudOnly: true }, - { label: "Live stats", href: "/stats", cloudOnly: true }, - { label: "Status", href: "https://status.bytesend.cloud", cloudOnly: true }, + { label: "Open source", href: "/open-source", cloudOnly: true }, ], }, { - title: "Developers", + title: "Features", + links: [ + { label: "SMTP relay", href: "/smtp", cloudOnly: true }, + { label: "Receiving", href: "/receiving", cloudOnly: true }, + { label: "DMARC reports", href: "https://docs.bytesend.cloud/guides/dmarc-reports" }, + { label: "Test mode", href: "https://docs.bytesend.cloud/guides/test-mode" }, + { label: "Webhooks", href: "https://docs.bytesend.cloud/guides/webhooks" }, + ], + }, + { + title: "Free tools", + links: [ + { label: "DMARC checker", href: "/tools/dmarc", cloudOnly: true }, + { label: "SPF checker", href: "/tools/spf", cloudOnly: true }, + { label: "DKIM checker", href: "/tools/dkim", cloudOnly: true }, + { label: "All tools", href: "/tools", cloudOnly: true }, + ], + }, + { + title: "Resources", links: [ { label: "Documentation", href: "https://docs.bytesend.cloud" }, { label: "API reference", href: "https://docs.bytesend.cloud/api-reference/introduction" }, { label: "Self-hosting", href: "https://docs.bytesend.cloud/self-hosting/overview" }, - { label: "GitHub", href: "https://github.com/ByteSendApp/ByteSend" }, + { label: "Live stats", href: "/stats", cloudOnly: true }, + { label: "Status", href: "https://status.bytesend.cloud", cloudOnly: true }, ], }, { title: "Company", links: [ { label: "Discord", href: "https://discord.gg/C2Q4GHXKQA" }, + { label: "Security", href: "/security", cloudOnly: true }, { label: "Legal", href: "/legal", cloudOnly: true }, { label: "Privacy", href: "/privacy", cloudOnly: true }, { label: "Terms", href: "/terms", cloudOnly: true }, + { label: "DPA", href: "/dpa", cloudOnly: true }, ], }, ]; +const VISIBLE_COLUMNS = COLUMNS.map((column) => ({ + ...column, + links: column.links.filter((link) => isCloud || !link.cloudOnly), +})).filter((column) => column.links.length > 0); + const SOCIALS = [ { label: "GitHub", href: "https://github.com/ByteSendApp/ByteSend", Icon: FaGithub }, { label: "Discord", href: "https://discord.gg/C2Q4GHXKQA", Icon: FaDiscord }, @@ -63,7 +90,7 @@ export function SiteFooter() { return (
-
+
@@ -85,18 +112,16 @@ export function SiteFooter() { ))}
-
- {COLUMNS.map((column) => ( +
+ {VISIBLE_COLUMNS.map((column) => (

{column.title}

    - {column.links - .filter((link) => isCloud || !link.cloudOnly) - .map((link) => ( -
  • - -
  • - ))} + {column.links.map((link) => ( +
  • + +
  • + ))}
))} diff --git a/apps/web/src/components/marketing/TopNav.tsx b/apps/web/src/components/marketing/TopNav.tsx index 5f78791..ac5a52c 100644 --- a/apps/web/src/components/marketing/TopNav.tsx +++ b/apps/web/src/components/marketing/TopNav.tsx @@ -7,7 +7,8 @@ const isCloud = env.NEXT_PUBLIC_IS_CLOUD; export const NAV_LINKS = [ { href: "/#features", label: "Features", cloudOnly: true }, - { href: "/#pricing", label: "Pricing", cloudOnly: true }, + { href: "/receiving", label: "Receiving", cloudOnly: true }, + { href: "/pricing", label: "Pricing", cloudOnly: true }, { href: "/changelog", label: "Changelog", cloudOnly: true }, { href: "/stats", label: "Stats", cloudOnly: true }, { href: "https://docs.bytesend.cloud", label: "Docs", cloudOnly: false }, diff --git a/apps/web/src/components/marketing/tools/tool-page.tsx b/apps/web/src/components/marketing/tools/tool-page.tsx new file mode 100644 index 0000000..2878601 --- /dev/null +++ b/apps/web/src/components/marketing/tools/tool-page.tsx @@ -0,0 +1,86 @@ +import Link from "next/link"; +import { ArrowRight } from "lucide-react"; + +export const TOOLS = [ + { href: "/tools/dmarc", name: "DMARC checker", text: "Is your domain protected from spoofing, and are reports being collected?" }, + { href: "/tools/spf", name: "SPF checker", text: "Which servers may send as your domain, and is the record within its lookup limit?" }, + { href: "/tools/dkim", name: "DKIM checker", text: "Find your DKIM keys, check their strength, and spot broken or test-mode keys." }, +]; + +export function ToolPage({ + current, + title, + intro, + checker, + explainer, + faq, +}: { + current: string; + title: string; + intro: string; + checker: React.ReactNode; + explainer?: { title: string; description?: string; items: Array<{ label: string; title: string; text: string }> }; + faq: Array<{ q: string; a: string }>; +}) { + const others = TOOLS.filter((tool) => tool.href !== current); + + return ( +
+
+
+ + Free tool + +

{title}

+

{intro}

+
{checker}
+
+
+ +
+ {explainer ? ( +
+

{explainer.title}

+ {explainer.description ?

{explainer.description}

: null} +
+ {explainer.items.map((item) => ( +
+

{item.label}

+

{item.title}

+

{item.text}

+
+ ))} +
+
+ ) : null} + +
+

Questions

+
+ {faq.map((item) => ( +
+
{item.q}
+
{item.a}
+
+ ))} +
+
+ +
+

More free tools

+
+ {others.map((tool) => ( + +

+ {tool.name} + +

+

{tool.text}

+ + ))} +
+
+
+
+ ); +} diff --git a/apps/web/src/components/marketing/tools/tool-result.tsx b/apps/web/src/components/marketing/tools/tool-result.tsx new file mode 100644 index 0000000..c55f248 --- /dev/null +++ b/apps/web/src/components/marketing/tools/tool-result.tsx @@ -0,0 +1,87 @@ +import Link from "next/link"; +import { AlertTriangle, ArrowRight, CheckCircle2, XCircle } from "lucide-react"; +import { Badge } from "@bytesend/ui/src/badge"; +import { Button } from "@bytesend/ui/src/button"; +import { CopyField } from "@bytesend/ui/src/copy-field"; + +export type ToolFinding = { level: "good" | "warning" | "problem"; title: string; detail: string }; + +const FINDING_ICON: Record = { + good: , + warning: , + problem: , +}; + +export function ToolResultCard({ + subject, + summary, + badge, + records = [], + findings, + suggestion, + cta, +}: { + subject: string; + summary: string; + badge: { label: string; variant: "success" | "warning" | "danger" }; + records?: Array<{ label: React.ReactNode; value: string }>; + findings: ToolFinding[]; + suggestion?: { label: React.ReactNode; value: string } | null; + cta: { text: React.ReactNode; label: string; href: string }; +}) { + return ( +
+
+
+

{subject}

+

{summary}

+
+ + {badge.label} + +
+ +
+ {records.map((record, index) => ( +
+

{record.label}

+

{record.value}

+
+ ))} + +
    + {findings.map((finding) => ( +
  • + {FINDING_ICON[finding.level]} +
    +

    {finding.title}

    +

    {finding.detail}

    +
    +
  • + ))} +
+ + {suggestion ? ( +
+

{suggestion.label}

+ +
+ ) : null} +
+ +
+

{cta.text}

+ +
+
+ ); +} + +export function ToolError({ message }: { message: string }) { + return

{message}

; +} diff --git a/apps/web/src/components/marketing/tools/use-tool-check.ts b/apps/web/src/components/marketing/tools/use-tool-check.ts new file mode 100644 index 0000000..9ac8ec7 --- /dev/null +++ b/apps/web/src/components/marketing/tools/use-tool-check.ts @@ -0,0 +1,53 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; + +export function useToolCheck(endpoint: string, fields: string[]) { + const [values, setValues] = useState>({}); + const [result, setResult] = useState(null); + const [error, setError] = useState(null); + const [loading, setLoading] = useState(false); + + const run = useCallback( + async (input: Record) => { + const params = new URLSearchParams(); + for (const field of fields) { + const value = input[field]?.trim(); + if (value) params.set(field, value); + } + if (!params.get(fields[0]!)) return; + + setLoading(true); + setError(null); + try { + const response = await fetch(`${endpoint}?${params}`); + const body = await response.json(); + if (!response.ok) { + setResult(null); + setError(body.error ?? "Something went wrong. Try again in a moment."); + return; + } + setResult(body as T); + window.history.replaceState(null, "", `?${params}`); + } catch { + setError("Couldn't reach the checker. Check your connection and try again."); + } finally { + setLoading(false); + } + }, + [endpoint, fields], + ); + + useEffect(() => { + const search = new URLSearchParams(window.location.search); + const initial = Object.fromEntries(fields.map((field) => [field, search.get(field) ?? ""])); + if (initial[fields[0]!]) { + setValues(initial); + void run(initial); + } + }, [fields, run]); + + const setValue = (field: string, value: string) => setValues((current) => ({ ...current, [field]: value })); + + return { values, setValue, run: () => run(values), result, error, loading }; +} diff --git a/apps/web/src/server/service/dkim-check-service.ts b/apps/web/src/server/service/dkim-check-service.ts new file mode 100644 index 0000000..d93081e --- /dev/null +++ b/apps/web/src/server/service/dkim-check-service.ts @@ -0,0 +1,114 @@ +import { createPublicKey } from "node:crypto"; +import { promises as dns } from "node:dns"; +import { DmarcLookupError, normalizeDomainInput, parseDmarcTags as parseTags, type DmarcFinding as ToolFinding } from "./dmarc-check-service"; + +export const COMMON_DKIM_SELECTORS = [ + "bytesend", + "google", + "selector1", + "selector2", + "default", + "dkim", + "mail", + "k1", + "k2", + "s1", + "s2", + "resend", + "mandrill", + "smtp", + "everlytickey1", +]; + +const SELECTOR = /^[a-z0-9](?:[a-z0-9._-]{0,61}[a-z0-9])?$/i; + +export type DkimKey = { + selector: string; + record: string; + keyType: string; + bits: number | null; + findings: ToolFinding[]; + grade: "strong" | "ok" | "weak" | "broken"; +}; + +export type DkimCheck = { + domain: string; + searched: string[]; + keys: DkimKey[]; + grade: "missing" | "broken" | "weak" | "ok" | "strong"; +}; + +async function lookupKey(domain: string, selector: string) { + try { + const answers = await dns.resolveTxt(`${selector}._domainkey.${domain}`); + return answers.map((chunks) => chunks.join("")).find((record) => /(^|;)\s*p=/i.test(record) || /^v=dkim1/i.test(record.trim())) ?? null; + } catch (error) { + const code = (error as { code?: string }).code; + if (code === "ENOTFOUND" || code === "ENODATA" || code === "NXDOMAIN" || code === "ESERVFAIL") return null; + throw new DmarcLookupError("Couldn't look up that domain's DNS. Try again in a moment."); + } +} + +export function analyzeDkimKey(selector: string, record: string): DkimKey { + const tags = parseTags(record); + const keyType = (tags.k ?? "rsa").toLowerCase(); + const publicKey = (tags.p ?? "").replace(/\s+/g, ""); + const findings: ToolFinding[] = []; + + if (!publicKey) { + findings.push({ level: "problem", title: "Key revoked", detail: "This selector publishes an empty key, so signatures using it fail. That's expected if you've retired it." }); + return { selector, record, keyType, bits: null, findings, grade: "broken" }; + } + + let bits: number | null = null; + if (keyType === "ed25519") { + bits = 256; + } else { + try { + bits = createPublicKey({ key: Buffer.from(publicKey, "base64"), format: "der", type: "spki" }).asymmetricKeyDetails?.modulusLength ?? null; + } catch { + findings.push({ level: "problem", title: "The key can't be read", detail: "The p= value isn't a valid public key, often because it was cut off when it was pasted into DNS." }); + return { selector, record, keyType, bits: null, findings, grade: "broken" }; + } + } + + let grade: DkimKey["grade"]; + if (keyType === "ed25519") { + grade = "strong"; + findings.push({ level: "good", title: "Ed25519 key", detail: "A modern, strong key type. Some providers don't verify it yet, so it's usually published next to an RSA key." }); + } else if (bits !== null && bits >= 2048) { + grade = "strong"; + findings.push({ level: "good", title: `${bits}-bit RSA key`, detail: "Strong. This is the recommended size." }); + } else if (bits !== null && bits >= 1024) { + grade = "ok"; + findings.push({ level: "warning", title: `${bits}-bit RSA key`, detail: "Still accepted, but 2048-bit keys are recommended. Rotate to a longer key when you can." }); + } else { + grade = "weak"; + findings.push({ level: "problem", title: `${bits ?? "Unknown"}-bit RSA key`, detail: "Too short to be trusted. Many providers ignore keys under 1024 bits. Generate a 2048-bit key." }); + } + + if ((tags.t ?? "").toLowerCase().split(":").includes("y")) { + findings.push({ level: "warning", title: "Testing mode (t=y)", detail: "Receivers may treat signatures from this key as unverified. Remove t=y once you're done testing." }); + } + + return { selector, record, keyType, bits, findings, grade }; +} + +const RANK: Record = { broken: 0, weak: 1, ok: 2, strong: 3 }; + +export async function checkDomainDkim(input: string, selectorInput?: string | null): Promise { + const parsed = normalizeDomainInput(input); + if (!parsed) throw new DmarcLookupError("That doesn't look like a domain. Try something like example.com."); + + const selector = selectorInput?.trim().toLowerCase().replace(/\._domainkey.*$/, ""); + if (selector && !SELECTOR.test(selector)) { + throw new DmarcLookupError("That selector doesn't look right. It's the part before ._domainkey, like google or selector1."); + } + + const searched = selector ? [selector] : COMMON_DKIM_SELECTORS; + const found = await Promise.all(searched.map(async (name) => ({ name, record: await lookupKey(parsed.host, name) }))); + const keys = found.filter((entry) => entry.record).map((entry) => analyzeDkimKey(entry.name, entry.record!)); + + const best = keys.reduce((current, key) => (current === null || RANK[key.grade] > RANK[current] ? key.grade : current), null); + return { domain: parsed.host, searched, keys, grade: best ?? "missing" }; +} diff --git a/apps/web/src/server/service/dmarc-check-service.ts b/apps/web/src/server/service/dmarc-check-service.ts new file mode 100644 index 0000000..3dc60b8 --- /dev/null +++ b/apps/web/src/server/service/dmarc-check-service.ts @@ -0,0 +1,170 @@ +import { promises as dns } from "node:dns"; +import * as tldts from "tldts"; + +export type DmarcFinding = { level: "good" | "warning" | "problem"; title: string; detail: string }; + +export type DmarcGrade = "missing" | "invalid" | "monitoring" | "partial" | "enforced"; + +export type DmarcCheck = { + domain: string; + lookedUp: string; + inherited: boolean; + record: string | null; + tags: Record; + grade: DmarcGrade; + findings: DmarcFinding[]; + suggestion: string | null; +}; + +export class DmarcLookupError extends Error {} + +export function normalizeDomainInput(input: string) { + const host = input + .trim() + .toLowerCase() + .replace(/^[a-z]+:\/\//, "") + .replace(/^[^@]*@/, "") + .split(/[/?#:]/)[0]! + .replace(/\.$/, ""); + const parsed = tldts.parse(host); + if (!parsed.domain || !parsed.isIcann || parsed.isIp || host.length > 253) return null; + return { host, orgDomain: parsed.domain }; +} + +export function parseDmarcTags(record: string) { + const tags: Record = {}; + for (const part of record.split(";")) { + const index = part.indexOf("="); + if (index === -1) continue; + const key = part.slice(0, index).trim().toLowerCase(); + const value = part.slice(index + 1).trim(); + if (key && !(key in tags)) tags[key] = value; + } + return tags; +} + +const POLICIES = new Set(["none", "quarantine", "reject"]); + +export function analyzeDmarc(records: string[], domain: string): Omit { + const dmarc = records.filter((record) => record.trim().toLowerCase().startsWith("v=dmarc1")); + const findings: DmarcFinding[] = []; + + if (dmarc.length === 0) { + findings.push({ + level: "problem", + title: "No DMARC record", + detail: "Anyone can send email that claims to be from this domain, and Gmail and Yahoo require DMARC from bulk senders.", + }); + return { record: null, tags: {}, grade: "missing", findings, suggestion: "v=DMARC1; p=none; rua=mailto:dmarc@" + domain }; + } + + if (dmarc.length > 1) { + findings.push({ + level: "problem", + title: "More than one DMARC record", + detail: "Mail providers ignore DMARC entirely when a domain publishes two records. Keep one and delete the rest.", + }); + return { record: dmarc[0]!, tags: parseDmarcTags(dmarc[0]!), grade: "invalid", findings, suggestion: null }; + } + + const record = dmarc[0]!; + const tags = parseDmarcTags(record); + const policy = tags.p?.toLowerCase(); + + if (!policy || !POLICIES.has(policy)) { + findings.push({ + level: "problem", + title: "The policy is missing or invalid", + detail: "The p= tag must be none, quarantine or reject. Without a valid one, mail providers treat the record as broken.", + }); + return { record, tags, grade: "invalid", findings, suggestion: null }; + } + + const pct = tags.pct === undefined ? 100 : Number.parseInt(tags.pct, 10); + let grade: DmarcGrade = policy === "none" ? "monitoring" : pct < 100 ? "partial" : "enforced"; + + if (policy === "none") { + findings.push({ + level: "warning", + title: "Monitoring only (p=none)", + detail: "Failing mail is still delivered. That's the right place to start, but spoofed mail gets through until you move to quarantine or reject.", + }); + } else if (pct < 100) { + findings.push({ + level: "warning", + title: `Applied to ${Number.isFinite(pct) ? pct : 0}% of failing mail`, + detail: `pct=${tags.pct} means the ${policy} policy only covers part of the mail that fails. Raise it to 100 once you're confident.`, + }); + } else { + findings.push({ + level: "good", + title: policy === "reject" ? "Spoofed mail is rejected" : "Spoofed mail goes to spam", + detail: `p=${policy} applies to all mail that fails DMARC.`, + }); + } + + const subPolicy = tags.sp?.toLowerCase(); + if (policy !== "none" && subPolicy === "none") { + grade = "partial"; + findings.push({ + level: "warning", + title: "Subdomains aren't protected", + detail: "sp=none lets mail from any subdomain through, even though the main domain is protected.", + }); + } + + const rua = (tags.rua ?? "") + .split(",") + .map((address) => address.trim()) + .filter(Boolean); + if (rua.length === 0) { + findings.push({ + level: "warning", + title: "Reports aren't being sent anywhere", + detail: "Without a rua= address you can't see who's sending as your domain, which you need before tightening the policy.", + }); + } else { + findings.push({ + level: "good", + title: "Reports are being collected", + detail: `Aggregate reports go to ${rua.map((address) => address.replace(/^mailto:/i, "")).join(", ")}.`, + }); + } + + if (tags.adkim?.toLowerCase() === "s" || tags.aspf?.toLowerCase() === "s") { + findings.push({ + level: "good", + title: "Strict alignment", + detail: "DKIM or SPF must match the From domain exactly, not just the same organisation.", + }); + } + + return { record, tags, grade, findings, suggestion: rua.length === 0 ? `${record.replace(/;\s*$/, "")}; rua=mailto:dmarc@${domain}` : null }; +} + +async function lookupDmarc(name: string) { + try { + const answers = await dns.resolveTxt(`_dmarc.${name}`); + return answers.map((chunks) => chunks.join("")); + } catch (error) { + const code = (error as { code?: string }).code; + if (code === "ENOTFOUND" || code === "ENODATA" || code === "NXDOMAIN") return []; + throw new DmarcLookupError("Couldn't look up that domain's DNS. Try again in a moment."); + } +} + +export async function checkDomainDmarc(input: string): Promise { + const parsed = normalizeDomainInput(input); + if (!parsed) throw new DmarcLookupError("That doesn't look like a domain. Try something like example.com."); + + let lookedUp = parsed.host; + let records = await lookupDmarc(parsed.host); + let inherited = false; + if (!records.some((record) => record.toLowerCase().startsWith("v=dmarc1")) && parsed.host !== parsed.orgDomain) { + lookedUp = parsed.orgDomain; + records = await lookupDmarc(parsed.orgDomain); + inherited = true; + } + + return { domain: parsed.host, lookedUp, inherited, ...analyzeDmarc(records, parsed.orgDomain) }; +} diff --git a/apps/web/src/server/service/dmarc-check-service.unit.test.ts b/apps/web/src/server/service/dmarc-check-service.unit.test.ts new file mode 100644 index 0000000..a955ecb --- /dev/null +++ b/apps/web/src/server/service/dmarc-check-service.unit.test.ts @@ -0,0 +1,71 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const { mockResolveTxt } = vi.hoisted(() => ({ mockResolveTxt: vi.fn() })); +vi.mock("node:dns", () => ({ promises: { resolveTxt: mockResolveTxt } })); + +import { analyzeDmarc, checkDomainDmarc, normalizeDomainInput } from "./dmarc-check-service"; + +describe("normalizeDomainInput", () => { + it("accepts domains, URLs and email addresses", () => { + expect(normalizeDomainInput("Example.COM")).toEqual({ host: "example.com", orgDomain: "example.com" }); + expect(normalizeDomainInput("https://mail.example.co.uk/path")).toEqual({ host: "mail.example.co.uk", orgDomain: "example.co.uk" }); + expect(normalizeDomainInput("jane@example.com")).toEqual({ host: "example.com", orgDomain: "example.com" }); + }); + + it("rejects things that aren't public domains", () => { + expect(normalizeDomainInput("localhost")).toBeNull(); + expect(normalizeDomainInput("10.0.0.1")).toBeNull(); + expect(normalizeDomainInput("not a domain")).toBeNull(); + }); +}); + +describe("analyzeDmarc", () => { + it("flags a missing record and suggests a monitoring one", () => { + const result = analyzeDmarc([], "example.com"); + expect(result.grade).toBe("missing"); + expect(result.suggestion).toBe("v=DMARC1; p=none; rua=mailto:dmarc@example.com"); + }); + + it("treats duplicate records as invalid", () => { + expect(analyzeDmarc(["v=DMARC1; p=none", "v=DMARC1; p=reject"], "example.com").grade).toBe("invalid"); + }); + + it("grades policies and keeps an existing one in the suggestion", () => { + const monitoring = analyzeDmarc(["v=DMARC1; p=none;"], "example.com"); + expect(monitoring.grade).toBe("monitoring"); + expect(monitoring.suggestion).toBe("v=DMARC1; p=none; rua=mailto:dmarc@example.com"); + + expect(analyzeDmarc(["v=DMARC1; p=quarantine; pct=50; rua=mailto:a@b.com"], "example.com").grade).toBe("partial"); + expect(analyzeDmarc(["v=DMARC1; p=reject; sp=none; rua=mailto:a@b.com"], "example.com").grade).toBe("partial"); + + const enforced = analyzeDmarc(["v=DMARC1; p=reject; rua=mailto:a@b.com"], "example.com"); + expect(enforced.grade).toBe("enforced"); + expect(enforced.suggestion).toBeNull(); + }); + + it("ignores unrelated TXT records", () => { + expect(analyzeDmarc(["google-site-verification=abc"], "example.com").grade).toBe("missing"); + }); + + it("calls out an invalid policy", () => { + expect(analyzeDmarc(["v=DMARC1; p=block"], "example.com").grade).toBe("invalid"); + }); +}); + +describe("checkDomainDmarc", () => { + beforeEach(() => mockResolveTxt.mockReset()); + + it("falls back to the organisational domain like mail providers do", async () => { + mockResolveTxt.mockImplementation(async (name: string) => { + if (name === "_dmarc.example.com") return [["v=DMARC1; p=reject; rua=mailto:a@b.com"]]; + throw Object.assign(new Error("none"), { code: "ENOTFOUND" }); + }); + const result = await checkDomainDmarc("mail.example.com"); + expect(result).toMatchObject({ domain: "mail.example.com", lookedUp: "example.com", inherited: true, grade: "enforced" }); + }); + + it("joins records split across several strings", async () => { + mockResolveTxt.mockResolvedValue([["v=DMARC1; p=quar", "antine; rua=mailto:a@b.com"]]); + expect((await checkDomainDmarc("example.com")).grade).toBe("enforced"); + }); +}); diff --git a/apps/web/src/server/service/spf-check-service.ts b/apps/web/src/server/service/spf-check-service.ts new file mode 100644 index 0000000..1122d4d --- /dev/null +++ b/apps/web/src/server/service/spf-check-service.ts @@ -0,0 +1,163 @@ +import { promises as dns } from "node:dns"; +import { DmarcLookupError, normalizeDomainInput, type DmarcFinding as ToolFinding } from "./dmarc-check-service"; + +export type SpfGrade = "missing" | "invalid" | "strict" | "softfail" | "neutral" | "open"; + +export type SpfCheck = { + domain: string; + record: string | null; + grade: SpfGrade; + lookups: number; + includes: string[]; + findings: ToolFinding[]; +}; + +const MAX_LOOKUPS = 10; +const MAX_FETCHES = 25; +const LOOKUP_TERMS = /^[+\-~?]?(include:|a\b|a:|a\/|mx\b|mx:|mx\/|ptr\b|ptr:|exists:|redirect=)/i; + +async function spfRecords(domain: string) { + try { + const answers = await dns.resolveTxt(domain); + return answers.map((chunks) => chunks.join("")).filter((record) => /^v=spf1(\s|$)/i.test(record.trim())); + } catch (error) { + const code = (error as { code?: string }).code; + if (code === "ENOTFOUND" || code === "ENODATA" || code === "NXDOMAIN") return []; + throw new DmarcLookupError("Couldn't look up that domain's DNS. Try again in a moment."); + } +} + +export function spfTerms(record: string) { + return record.trim().split(/\s+/).slice(1); +} + +function targetOf(term: string) { + const match = /^[+\-~?]?(?:include:|redirect=)(.+)$/i.exec(term); + return match?.[1]?.toLowerCase() ?? null; +} + +export async function countSpfLookups(record: string, budget = { fetches: 0 }, seen = new Set()): Promise { + let lookups = 0; + for (const term of spfTerms(record)) { + if (!LOOKUP_TERMS.test(term)) continue; + lookups++; + const target = targetOf(term); + if (!target || seen.has(target) || budget.fetches >= MAX_FETCHES) continue; + seen.add(target); + budget.fetches++; + const nested = (await spfRecords(target).catch(() => []))[0]; + if (nested) lookups += await countSpfLookups(nested, budget, seen); + if (lookups > MAX_LOOKUPS) return lookups; + } + return lookups; +} + +export function gradeSpf(record: string, lookups: number): { grade: SpfGrade; findings: ToolFinding[] } { + const terms = spfTerms(record); + const findings: ToolFinding[] = []; + const all = terms.find((term) => /^[+\-~?]?all$/i.test(term)); + const qualifier = all ? (/^[+\-~?]/.test(all) ? all[0] : "+") : null; + const redirects = terms.some((term) => /^redirect=/i.test(term)); + + let grade: SpfGrade; + if (qualifier === "-") { + grade = "strict"; + findings.push({ level: "good", title: "Unlisted servers fail (-all)", detail: "Mail from any server not in this record fails SPF." }); + } else if (qualifier === "~") { + grade = "softfail"; + findings.push({ + level: "good", + title: "Unlisted servers soft-fail (~all)", + detail: "Mail from servers not in this record is marked suspicious. Most senders use this, and DMARC decides what happens next.", + }); + } else if (qualifier === "?") { + grade = "neutral"; + findings.push({ + level: "warning", + title: "No opinion on unlisted servers (?all)", + detail: "Mail from any server is treated as neutral, so SPF gives no protection. Use ~all or -all.", + }); + } else if (qualifier === "+") { + grade = "open"; + findings.push({ + level: "problem", + title: "Any server is allowed (+all)", + detail: "This record says every server on the internet may send as this domain. Change +all to ~all or -all straight away.", + }); + } else if (redirects) { + grade = "softfail"; + findings.push({ level: "good", title: "Uses another domain's policy", detail: "redirect= hands the decision to another domain's SPF record." }); + } else { + grade = "neutral"; + findings.push({ + level: "warning", + title: "No all mechanism", + detail: "Without ~all or -all at the end, servers that aren't listed are treated as neutral. Add ~all.", + }); + } + + if (lookups > MAX_LOOKUPS) { + grade = "invalid"; + findings.push({ + level: "problem", + title: `Too many DNS lookups (${lookups})`, + detail: "SPF allows at most 10. Past that, mail providers treat the record as broken and SPF fails for every message. Remove includes you no longer use.", + }); + } else { + findings.push({ + level: lookups >= 8 ? "warning" : "good", + title: `${lookups} of 10 DNS lookups used`, + detail: lookups >= 8 ? "You're close to the limit. Adding another provider could break SPF." : "Well within SPF's limit of 10.", + }); + } + + if (terms.some((term) => /^[+\-~?]?ptr(:|$)/i.test(term))) { + findings.push({ level: "warning", title: "Uses ptr", detail: "The ptr mechanism is slow, unreliable and discouraged by the SPF standard. Replace it with ip4:, ip6: or include:." }); + } + + return { grade, findings }; +} + +export async function checkDomainSpf(input: string): Promise { + const parsed = normalizeDomainInput(input); + if (!parsed) throw new DmarcLookupError("That doesn't look like a domain. Try something like example.com."); + + const records = await spfRecords(parsed.host); + if (records.length === 0) { + return { + domain: parsed.host, + record: null, + grade: "missing", + lookups: 0, + includes: [], + findings: [ + { + level: "problem", + title: "No SPF record", + detail: "Nothing says which servers may send as this domain. If it sends email, add a TXT record starting with v=spf1. If it never sends, publish v=spf1 -all.", + }, + ], + }; + } + if (records.length > 1) { + return { + domain: parsed.host, + record: records[0]!, + grade: "invalid", + lookups: 0, + includes: [], + findings: [ + { + level: "problem", + title: "More than one SPF record", + detail: "A domain may only publish one. With two, SPF fails for every message. Merge them into a single record.", + }, + ], + }; + } + + const record = records[0]!; + const lookups = await countSpfLookups(record); + const includes = spfTerms(record).map(targetOf).filter((target): target is string => Boolean(target)); + return { domain: parsed.host, record, lookups, includes, ...gradeSpf(record, lookups) }; +} diff --git a/apps/web/src/server/service/spf-dkim-check.unit.test.ts b/apps/web/src/server/service/spf-dkim-check.unit.test.ts new file mode 100644 index 0000000..4b1c67f --- /dev/null +++ b/apps/web/src/server/service/spf-dkim-check.unit.test.ts @@ -0,0 +1,72 @@ +import { generateKeyPairSync } from "node:crypto"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const { mockResolveTxt } = vi.hoisted(() => ({ mockResolveTxt: vi.fn() })); +vi.mock("node:dns", () => ({ promises: { resolveTxt: mockResolveTxt } })); + +import { analyzeDkimKey, checkDomainDkim } from "./dkim-check-service"; +import { checkDomainSpf, countSpfLookups, gradeSpf } from "./spf-check-service"; + +const notFound = () => Object.assign(new Error("none"), { code: "ENOTFOUND" }); +const rsaKey = (bits: number) => + generateKeyPairSync("rsa", { modulusLength: bits }).publicKey.export({ format: "der", type: "spki" }).toString("base64"); + +beforeEach(() => mockResolveTxt.mockReset()); + +describe("SPF", () => { + it("grades the all mechanism", () => { + expect(gradeSpf("v=spf1 include:amazonses.com -all", 1).grade).toBe("strict"); + expect(gradeSpf("v=spf1 include:amazonses.com ~all", 1).grade).toBe("softfail"); + expect(gradeSpf("v=spf1 ?all", 0).grade).toBe("neutral"); + expect(gradeSpf("v=spf1 +all", 0).grade).toBe("open"); + expect(gradeSpf("v=spf1 all", 0).grade).toBe("open"); + }); + + it("marks more than 10 lookups as broken", () => { + expect(gradeSpf("v=spf1 ~all", 11).grade).toBe("invalid"); + }); + + it("counts lookups through includes, without looping forever", async () => { + mockResolveTxt.mockImplementation(async (name: string) => { + if (name === "_spf.google.com") return [["v=spf1 include:_netblocks.google.com include:_spf.google.com ~all"]]; + if (name === "_netblocks.google.com") return [["v=spf1 ip4:35.190.247.0/24 a mx ~all"]]; + throw notFound(); + }); + expect(await countSpfLookups("v=spf1 include:_spf.google.com include:amazonses.com ip4:1.2.3.4 ~all")).toBe(6); + }); + + it("reports a missing record and duplicates", async () => { + mockResolveTxt.mockRejectedValue(notFound()); + expect((await checkDomainSpf("example.com")).grade).toBe("missing"); + + mockResolveTxt.mockResolvedValue([["v=spf1 -all"], ["v=spf1 ~all"], ["google-site-verification=x"]]); + expect((await checkDomainSpf("example.com")).grade).toBe("invalid"); + }); +}); + +describe("DKIM", () => { + it("grades keys by size and spots broken ones", () => { + expect(analyzeDkimKey("s", `v=DKIM1; k=rsa; p=${rsaKey(2048)}`)).toMatchObject({ grade: "strong", bits: 2048 }); + expect(analyzeDkimKey("s", `v=DKIM1; k=rsa; p=${rsaKey(1024)}`)).toMatchObject({ grade: "ok", bits: 1024 }); + expect(analyzeDkimKey("s", "v=DKIM1; p=").grade).toBe("broken"); + expect(analyzeDkimKey("s", "v=DKIM1; p=notakey").grade).toBe("broken"); + expect(analyzeDkimKey("s", `v=DKIM1; t=y; p=${rsaKey(2048)}`).findings.some((f) => f.title.startsWith("Testing"))).toBe(true); + }); + + it("finds keys under common selectors when none is given", async () => { + const key = rsaKey(2048); + mockResolveTxt.mockImplementation(async (name: string) => { + if (name === "google._domainkey.example.com") return [[`v=DKIM1; k=rsa; p=${key.slice(0, 200)}`, key.slice(200)]]; + throw notFound(); + }); + const result = await checkDomainDkim("example.com"); + expect(result.grade).toBe("strong"); + expect(result.keys.map((k) => k.selector)).toEqual(["google"]); + }); + + it("checks only the selector given", async () => { + mockResolveTxt.mockRejectedValue(notFound()); + const result = await checkDomainDkim("example.com", "selector9._domainkey.example.com"); + expect(result).toMatchObject({ grade: "missing", searched: ["selector9"] }); + }); +}); diff --git a/apps/web/src/server/service/tool-rate-limit.ts b/apps/web/src/server/service/tool-rate-limit.ts new file mode 100644 index 0000000..8904932 --- /dev/null +++ b/apps/web/src/server/service/tool-rate-limit.ts @@ -0,0 +1,22 @@ +import { logger } from "../logger/log"; +import { getRedis, redisKey } from "../redis"; + +const LIMIT_PER_MINUTE = 20; + +export function clientIp(request: Request) { + const headers = request.headers; + return headers.get("cf-connecting-ip") ?? headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? headers.get("x-real-ip") ?? "unknown"; +} + +export async function toolRateLimited(request: Request, tool: string) { + try { + const redis = getRedis(); + const key = redisKey(`rl:tools:${tool}:${clientIp(request)}`); + const count = await redis.incr(key); + if (count === 1) await redis.expire(key, 60); + return count > LIMIT_PER_MINUTE; + } catch (error) { + logger.warn({ err: error, tool }, "[Tools]: Rate limit unavailable"); + return false; + } +} diff --git a/packages/sdk/README.md b/packages/sdk/README.md index a121fa7..50ae461 100644 --- a/packages/sdk/README.md +++ b/packages/sdk/README.md @@ -116,6 +116,44 @@ await bytesend.campaigns.pause(campaign.data.id); await bytesend.campaigns.resume(campaign.data.id); ``` +## Receiving email + +Mail sent to your [receiving addresses](https://docs.bytesend.cloud/guides/inbound-email) arrives as an `email.received` webhook: + +```ts +import { ByteSend } from "bytesend-js"; + +const bytesend = new ByteSend("bs_12345"); +const webhooks = bytesend.webhooks(process.env.BYTESEND_WEBHOOK_SECRET!); + +export async function POST(request: Request) { + const event = webhooks.constructEvent(await request.text(), { headers: request.headers }); + + if (event.type === "email.received") { + const { from, subject, text, inReplyToEmailId, attachments } = event.data; + console.log(`${from} wrote "${subject}"`, { text, inReplyToEmailId, attachments: attachments.length }); + } + + return new Response("ok"); +} +``` + +`inReplyToEmailId` is set when the message replies to an email you sent through ByteSend. + +You can also fetch received mail from the API: + +```ts +const { data } = await bytesend.inbound.list({ recipient: "support@reply.acme.com", limit: 20 }); + +const { data: email } = await bytesend.inbound.get(data!.data[0]!.id); + +for (const attachment of email!.attachments) { + const file = await bytesend.inbound.downloadAttachment(attachment); +} +``` + +`list()` also takes `page` and `since` (an ISO 8601 date). Attachment links are signed and expire after an hour; if one has expired, call `inbound.get()` again for a fresh link. + ## Webhooks Verify webhook signatures and get typed events: diff --git a/packages/sdk/index.ts b/packages/sdk/index.ts index 218237b..1172b1a 100644 --- a/packages/sdk/index.ts +++ b/packages/sdk/index.ts @@ -1,6 +1,8 @@ export { ByteSend } from "./src/bytesend"; export { Campaigns } from "./src/campaign"; export { ContactBooks } from "./src/contactBook"; +export { Inbound } from "./src/inbound"; +export type { InboundAttachment, InboundEmail, InboundEmailSummary } from "./src/inbound"; export { Webhooks, WebhookVerificationError, diff --git a/packages/sdk/package.json b/packages/sdk/package.json index 7268771..41532f7 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -1,6 +1,6 @@ { "name": "bytesend-js", - "version": "0.1.4", + "version": "0.2.0", "description": "Official JavaScript SDK for ByteSend, the email sending service built for developers.", "license": "AGPL-3.0-only", "repository": { diff --git a/packages/sdk/src/bytesend.ts b/packages/sdk/src/bytesend.ts index 792f0c6..080c4fe 100644 --- a/packages/sdk/src/bytesend.ts +++ b/packages/sdk/src/bytesend.ts @@ -6,6 +6,7 @@ import { Domains } from "./domain"; import { Campaigns } from "./campaign"; import { Analytics } from "./analytics"; import { Webhooks } from "./webhooks"; +import { Inbound } from "./inbound"; const defaultBaseUrl = "https://bytesend.cloud"; // eslint-disable-next-line turbo/no-undeclared-env-vars @@ -28,6 +29,7 @@ export class ByteSend { readonly contactBooks = new ContactBooks(this); readonly campaigns = new Campaigns(this); readonly analytics = new Analytics(this); + readonly inbound = new Inbound(this); url = baseUrl; constructor( diff --git a/packages/sdk/src/inbound.ts b/packages/sdk/src/inbound.ts new file mode 100644 index 0000000..fe623c1 --- /dev/null +++ b/packages/sdk/src/inbound.ts @@ -0,0 +1,62 @@ +import { paths } from "../types/schema"; +import { ErrorResponse } from "../types"; +import { ByteSend } from "./bytesend"; + +type ListInboundEmailsQuery = NonNullable; + +type ListInboundEmailsResponseSuccess = + paths["/v1/inbound/emails"]["get"]["responses"]["200"]["content"]["application/json"]; + +type ListInboundEmailsResponse = { + data: ListInboundEmailsResponseSuccess | null; + error: ErrorResponse | null; +}; + +export type InboundEmail = + paths["/v1/inbound/emails/{id}"]["get"]["responses"]["200"]["content"]["application/json"]; + +export type InboundEmailSummary = ListInboundEmailsResponseSuccess["data"][number]; + +export type InboundAttachment = InboundEmail["attachments"][number]; + +type GetInboundEmailResponse = { + data: InboundEmail | null; + error: ErrorResponse | null; +}; + +export class Inbound { + constructor(private readonly bytesend: ByteSend) { + this.bytesend = bytesend; + } + + async list(query?: ListInboundEmailsQuery): Promise { + const params = new URLSearchParams(); + if (query?.page) params.set("page", String(query.page)); + if (query?.limit) params.set("limit", String(query.limit)); + if (query?.recipient) params.set("recipient", query.recipient); + if (query?.since) params.set("since", query.since); + + const queryString = params.toString(); + const path = queryString ? `/inbound/emails?${queryString}` : "/inbound/emails"; + return this.bytesend.get(path); + } + + async get(id: string): Promise { + return this.bytesend.get(`/inbound/emails/${encodeURIComponent(id)}`); + } + + async downloadAttachment(attachment: { url?: string | null; filename?: string }): Promise { + if (!attachment.url) { + throw new Error(`No download link for ${attachment.filename ?? "this attachment"}. Fetch the email again with inbound.get() for a fresh one.`); + } + const response = await fetch(attachment.url); + if (!response.ok) { + throw new Error( + response.status === 403 + ? "The attachment link has expired. Fetch the email again with inbound.get() for a fresh one." + : `Couldn't download the attachment (${response.status}).`, + ); + } + return response.arrayBuffer(); + } +} diff --git a/packages/sdk/types/schema.d.ts b/packages/sdk/types/schema.d.ts index 44805ac..8b197c1 100644 --- a/packages/sdk/types/schema.d.ts +++ b/packages/sdk/types/schema.d.ts @@ -2060,6 +2060,126 @@ export interface paths { patch?: never; trace?: never; }; + "/v1/inbound/emails": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get: { + parameters: { + query?: { + page?: number; + limit?: number; + recipient?: string; + since?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Received emails, newest first */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + data: { + id: string; + recipient: string; + from: string; + fromName: string | null; + subject: string; + attachmentCount: number; + inReplyToEmailId: string | null; + receivedAt: string; + }[]; + hasMore: boolean; + }; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/v1/inbound/emails/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description A received email, with signed links to its attachments */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + id: string; + recipient: string; + from: string; + fromName?: string | null; + to: string[]; + cc: string[]; + replyTo: string[]; + subject: string; + text?: string | null; + html?: string | null; + messageId?: string | null; + inReplyTo?: string | null; + inReplyToEmailId?: string | null; + attachments: { + id: string; + filename: string; + contentType: string; + size: number; + /** @description Signed download link, valid for one hour */ + url?: string; + }[]; + authentication: { + spf?: string | null; + dkim?: string | null; + dmarc?: string | null; + spam?: string | null; + virus?: string | null; + }; + domainId?: number | null; + receivedAt: string; + }; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; } export type webhooks = Record; export interface components {