diff --git a/.env.example b/.env.example index dbf2c2c..ac1e492 100644 --- a/.env.example +++ b/.env.example @@ -17,6 +17,12 @@ DATABASE_URL=postgresql://bytesend:changeme@localhost:5432/bytesend REDIS_URL=redis://localhost:6379 +# Optional: Spamhaus Data Query Service key. Public DNSBL queries from cloud resolvers are refused, so blacklist checks report "unknown" without it. +SPAMHAUS_DQS_KEY= + +# Development only: print every SQL query Prisma runs (very noisy). +# PRISMA_LOG_QUERIES=true + # Optional: prefix all Redis keys (useful when sharing a Redis instance) # REDIS_KEY_PREFIX=bytesend: diff --git a/.github/README.md b/.github/README.md index aaaf550..a02c50c 100644 --- a/.github/README.md +++ b/.github/README.md @@ -1,80 +1,142 @@ -![ByteSend](../apps/web/public/nameplate.png) +

+ + + ByteSend + +

+ +

+ Open-source email infrastructure for developers.
+ Transactional and marketing email through a REST API, SMTP relay and SDKs managed on + bytesend.cloud or self-hosted on your own AWS account. +

+ +

+ Website · + Docs · + API reference · + Releases · + Discord +

+ +

+ License: AGPL-3.0 + Latest release + Discord +

-**Open-source email infrastructure that works.** REST API, SMTP relay, campaigns, contact management, and real-time webhooks self-hosted or managed on [bytesend.cloud](https://bytesend.cloud). +--- -[Dashboard](https://bytesend.cloud) · [Docs](https://docs.bytesend.cloud) · [API Reference](https://docs.bytesend.cloud/api-reference/introduction) · [Discord](https://discord.gg/nodebyte) +## Send your first email ---- +```ts +import { ByteSend } from "bytesend-js"; + +const bytesend = new ByteSend("bs_your_api_key"); -## Cloud +await bytesend.emails.send({ + from: "Acme ", + to: "customer@example.com", + subject: "Welcome to Acme", + html: "

Thanks for signing up!

", +}); +``` -The fastest way to get started is the managed cloud at [bytesend.cloud](https://bytesend.cloud). No infrastructure to manage just sign up, verify a domain, and start sending. +Prefer another language or no code at all? Use the [Python](../packages/python-sdk) or [Go](../packages/go-sdk) SDK, call the [REST API](https://docs.bytesend.cloud/api-reference/introduction) directly, or point any app at the [SMTP relay](https://docs.bytesend.cloud/get-started/smtp). +## What's included ---- +**Sending** +- REST API, SMTP relay, and SDKs for TypeScript, Python and Go +- Scheduled sends, batch sends of up to 100 emails, idempotency keys and custom headers +- Templates built in a visual editor, with variables +- Per-domain open and click tracking + +**Marketing** +- Contact books with double opt-in and one-click (RFC 8058) unsubscribe +- Campaigns with batching and send windows -## Self-Hosting +**Deliverability** +- Guided domain setup with DKIM, SPF (custom MAIL FROM) and DMARC checks +- Automatic suppression of hard bounces and complaints +- Bounce and complaint rates enforced per team at Google and Yahoo sender thresholds +- Outbound spam scoring: suspicious mail is flagged, high-risk mail is held for review +- Daily domain blocklist monitoring (Spamhaus DBL, SURBL, URIBL) +- Move a domain between SES regions without downtime -ByteSend is fully self-hostable under the AGPL-3.0 license. +**Operations** +- Signed webhooks with retries for every email and domain event +- Team notifications to Discord, Slack, Microsoft Teams, Telegram or any webhook +- Teams with roles, API keys scoped by permission and domain, and 2FA +- An admin panel with platform overview, audit log, email explorer and spam review + +## Cloud or self-hosted + +**Cloud** — [bytesend.cloud](https://bytesend.cloud) is the fastest start: sign up, verify a domain and send. No infrastructure to run. + +**Self-hosted** — ByteSend is free to self-host under AGPL-3.0. You bring PostgreSQL, Redis and an AWS account with SES. ```bash git clone https://github.com/NodeByteLTD/ByteSend.git -cp docker/prod/.env.example docker/prod/.env -# fill in your values +cd ByteSend +cp docker/prod/.env.example docker/prod/.env # fill in your values docker compose -f docker/prod/compose.yml --env-file docker/prod/.env up -d docker compose -f docker/prod/compose.yml --env-file docker/prod/.env exec web pnpm db:migrate-deploy ``` -Full setup guide (reverse proxy, TLS, firewall, SMTP relay): [docs.bytesend.cloud/self-hosting/overview](https://docs.bytesend.cloud/self-hosting/overview) - ---- - -## Tech Stack +The [self-hosting guide](https://docs.bytesend.cloud/self-hosting/overview) covers SES setup, reverse proxy and TLS, the SMTP relay and upgrades. -| | | -|---|---| -| Framework | Next.js 15 (App Router) | -| Language | TypeScript | -| Database | PostgreSQL + Prisma | -| Cache | Redis | -| Email delivery | AWS SES | -| Auth | NextAuth.js v5 | -| Monorepo | Turborepo + pnpm | - ---- +## Local development -## Development +You need Node.js 20.19+, pnpm 9+ and Docker. ```bash pnpm install -cp .env.example .env # fill in values, then symlink: ln -s ../../.env apps/web/.env -pnpm dev # starts app at http://localhost:3000 -pnpm db:migrate-dev # run migrations +cp .env.example .env # fill in values +pnpm dx:up # Postgres, Redis and MinIO in Docker +pnpm db:migrate-dev # apply database migrations +pnpm dev # web app on http://localhost:3000 ``` -See [docs.bytesend.cloud/get-started/local](https://docs.bytesend.cloud/get-started/local) for the full local setup guide. +| Command | What it does | +|---|---| +| `pnpm dev` | Run every app in watch mode | +| `pnpm build` | Production build | +| `pnpm lint` | Lint all packages | +| `pnpm test:web` | Web unit tests (Vitest) | +| `pnpm test:web:all` | Unit and integration tests (needs `pnpm dx:up`) | +| `pnpm db:studio` | Open Prisma Studio | +| `pnpm dx:down` | Stop the local Docker services | ---- +The [local setup guide](https://docs.bytesend.cloud/get-started/local) walks through the environment variables. -## Contributing +## Repository layout -1. Fork the repo and create a feature branch -2. Commit with [Conventional Commits](https://www.conventionalcommits.org/) -3. Open a pull request against `main` +| Path | What's there | +|---|---| +| [`apps/web`](../apps/web) | Next.js dashboard, tRPC API, public REST API (Hono) and background jobs | +| [`apps/smtp-server`](../apps/smtp-server) | SMTP relay that forwards mail to the ByteSend API | +| [`apps/docs`](../apps/docs) | Documentation site | +| [`packages/sdk`](../packages/sdk) | TypeScript SDK (`bytesend-js`) | +| [`packages/python-sdk`](../packages/python-sdk) | Python SDK (`bytesend`) | +| [`packages/go-sdk`](../packages/go-sdk) | Go SDK (`github.com/nodebyteltd/bytesend-go`) | +| [`packages/ui`](../packages/ui) | Shared UI components | +| [`packages/email-editor`](../packages/email-editor) | Visual email template editor | -Please check existing issues before opening a new one. +**Built with** Next.js 16 · TypeScript · tRPC · Hono · Prisma · PostgreSQL · Redis · BullMQ · AWS SES · NextAuth · Tailwind CSS · Turborepo -See also: +## Contributing -- [Contributing Guide](CONTRIBUTING.md) -- [Code of Conduct](CODE_OF_CONDUCT.md) -- [Security Policy](SECURITY.md) -- [Support](SUPPORT.md) +Contributions are welcome. ---- +1. Open or comment on an issue first, so work doesn't overlap. +2. Branch from `develop` and use [Conventional Commits](https://www.conventionalcommits.org/) (`feat(scope): …`, `fix(scope): …`). +3. Open your pull request against `develop`. -## License +Read the [contributing guide](CONTRIBUTING.md) and [code of conduct](CODE_OF_CONDUCT.md) before you start. Notes for AI coding agents are in [AGENTS.md](../AGENTS.md). + +Found a security issue? Please report it privately as described in the [security policy](SECURITY.md) rather than opening an issue. For help, see [support](SUPPORT.md). -ByteSend is licensed under the **GNU Affero General Public License v3.0** (AGPL-3.0). +## License -See [LICENSE](LICENSE) for full details. +ByteSend is licensed under the [GNU Affero General Public License v3.0](../LICENSE). If you run a modified version as a network service, the AGPL requires you to make your changes available to its users. diff --git a/.github/SUPPORT.md b/.github/SUPPORT.md index 9763bc8..9a12140 100644 --- a/.github/SUPPORT.md +++ b/.github/SUPPORT.md @@ -4,7 +4,7 @@ Need help with ByteSend? ## Community Support -- Discord: https://discord.gg/nodebyte +- Discord: https://https://discord.gg/C2Q4GHXKQA - Docs: https://docs.bytesend.cloud ## Commercial / Cloud Support diff --git a/CHANGELOG.md b/CHANGELOG.md index 32e2b46..26d89f2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,65 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 --- +## [0.4.0] - 2026-10-18 + +### Added + +#### Brand +- **New identity: "Speed Ribbon"** — nested envelope-arrows trailing into motion lines, in the existing four blues (`#85FCFF`, `#00C3D6`, `#1FB5FF`, `#0057FF`) on ink `#05070D`, with a two-tone Sora wordmark; ships in full, compact (≤40px) and glyph (≤20px) detail levels so it stays legible down to a 16px favicon +- **Brand asset kit** (`public/brand/`) — SVG marks (colour, mono black/white, compact, glyph), light/dark wordmarks, 1024px app icon, social avatar, GitHub social preview (1280×640), Discord banner (960×540) and invite splash (1920×1080), X/Twitter header (1500×500) +- **`pnpm --filter web brand:generate`** — regenerates every logo, favicon, app icon and banner from the shared geometry in `src/lib/brand.tsx` +- **Open Graph & Twitter images** — generated `opengraph-image` / `twitter-image` routes for the site and the changelog using `next/og`, replacing the externally hosted share image + +#### Admin Panel +- **Overview dashboard** (`/admin`) — 7/30/90-day KPIs with prior-period deltas, sending and signup charts, SES quota and sandbox status per region, a "Needs attention" panel (teams over bounce/complaint warning thresholds, blocked teams, failing domains) and recent admin activity +- **Grouped admin navigation** and **Ctrl/⌘+K global search** across users, teams, domains and emails +- **Audit log** (`/admin/audit`) — every admin mutation is recorded with actor, target and a before/after diff; filterable, and shown per team and per user +- **Team detail pages** (`/admin/teams/[id]`) — usage, 7-day deliverability gauges, members, domains (with blacklist and region-move status), API keys, webhooks, subscription, limits, plan assignment, audited block/unblock with a reason, and typed-confirmation delete +- **User detail pages** (`/admin/users/[id]`) — flags, 2FA, sign-in methods, active sessions, backup emails and teams +- **Deliverability** (`/admin/deliverability`) — every team's 7-day hard-bounce and complaint rates against the enforcement thresholds, with block/unblock +- **Email explorer** (`/admin/emails`) — cross-team sending history with status, recipient, sender and subject filters and an event timeline; viewing a message body is audited and rendered in a fully sandboxed frame +- **Domain blacklist monitoring** (`/admin/blacklists`) — verified sending domains checked daily against Spamhaus DBL, SURBL and URIBL with Discord alerts on new listings and manual re-checks; refused public-resolver queries report "Unknown" instead of a false "clean" +- **Spam review** (`/admin/spam`) — queue of held and flagged outbound messages with rule hits, release and reject + +#### Sending +- **Outbound spam detection** — rule-based scoring for phishing phrases, brand impersonation, mismatched/IP/shortened/punycode links, `javascript:`/`data:` links, executable attachments, hidden text and more; score ≥ 5 is flagged and sent, ≥ 10 is held for review with the new `HELD` email status; campaigns are scanned once at launch; five holds in 24 hours blocks the team automatically +- **Change sending region** — team admins can move a verified domain to another SES region from the domain page with no downtime: the new identity is registered under a region-specific DKIM selector, sending stays on the old region until the new DKIM and MAIL FROM verify, then switches automatically; the old identity is retired 24 hours later + +#### Account +- **Connected accounts** — connect, reconnect and disconnect GitHub, Google and Discord from account settings; "Use this email" adopts a provider's email through the existing two-step email-change verification +- Email changes are now available to users who signed up with OAuth + +### Changed +- **Campaign scheduler** — skips the database entirely while no campaign is due (Redis idle flag, cleared whenever a campaign is scheduled, resumed or sent), and registers its tick with `upsertJobScheduler` after removing stale repeatable jobs left by earlier tick intervals +- **Prisma query logging** is now opt-in in development via `PRISMA_LOG_QUERIES=true` +- Teams and users admin pages are now searchable lists that open the new detail pages; domains, webhooks, billing and email analytics share the refreshed admin layout +- Bounce/complaint thresholds moved to `src/lib/constants/deliverability.ts`, shared by `LimitService` and the admin views + +### Fixed +- **Security: OAuth account takeover** — sign-in with GitHub, Google or Discord now requires the provider to have verified the email address; previously an unverified provider email could be linked to an existing ByteSend account +- Webhook-call cleanup job was never started, so call history was never pruned +- "Paid users only" in admin email analytics only counted the BASIC plan +- Admin team settings reset dropped extra domain/member slots after saving; literal `…`/`–` text in the teams page +- Web manifest pointed at icon paths that did not exist +- Discord notification icon URL now uses `bytesend.cloud` + +### Documentation +- New guides: [Spam Protection](https://docs.bytesend.cloud/guides/spam-protection), [Changing Sending Region](https://docs.bytesend.cloud/guides/sending-regions), [Connected Accounts](https://docs.bytesend.cloud/guides/connected-accounts) and, for self-hosters, [Admin Panel](https://docs.bytesend.cloud/self-hosting/admin-panel) +- Team roles corrected to Admin and Member (the guide previously described Editor and Viewer roles that don't exist), and built-in two-factor authentication documented +- `HELD` added to the email status enums in the OpenAPI spec; TypeScript SDK types regenerated (also picks up the previously missing `/v1/smtp/auth` types) +- TypeScript SDK README now installs the correct package, `bytesend-js` +- Docs site and repository README use the new brand + +### Migrations +- `20261018200000_add_admin_audit_log`, `20261018210000_add_domain_blacklist_checks`, `20261018220000_add_account_email`, `20261018230000_add_domain_region_move`, `20261019000000_add_spam_scans` + +### Environment +- `SPAMHAUS_DQS_KEY` (optional) — Spamhaus Data Query Service key for reliable DBL lookups +- `PRISMA_LOG_QUERIES` (optional, development) + +--- + ## [0.3.2] - 2026-06-23 ### Added diff --git a/apps/docs/api-reference/openapi.json b/apps/docs/api-reference/openapi.json index f1ec8da..16bf232 100644 --- a/apps/docs/api-reference/openapi.json +++ b/apps/docs/api-reference/openapi.json @@ -564,7 +564,8 @@ "COMPLAINED", "FAILED", "CANCELLED", - "SUPPRESSED" + "SUPPRESSED", + "HELD" ] }, "createdAt": { "type": "string" }, @@ -755,7 +756,8 @@ "COMPLAINED", "FAILED", "CANCELLED", - "SUPPRESSED" + "SUPPRESSED", + "HELD" ] }, "scheduledAt": { diff --git a/apps/docs/docs.json b/apps/docs/docs.json index 3168377..91ecae8 100644 --- a/apps/docs/docs.json +++ b/apps/docs/docs.json @@ -3,19 +3,20 @@ "theme": "maple", "name": "ByteSend", "colors": { - "primary": "#0066CC", - "light": "#E6F2FF", - "dark": "#3D9FFF" + "primary": "#0057FF", + "light": "#1FB5FF", + "dark": "#0046CC" }, "background": { "color": { "light": "#F8F9FB", - "dark": "#0A0A0A" + "dark": "#05070D" } }, "fonts": { "heading": { - "family": "Inter" + "family": "Sora", + "weight": 700 }, "body": { "family": "Inter" @@ -52,7 +53,8 @@ "self-hosting/certificates", "self-hosting/firewall", "self-hosting/reverse-proxy", - "self-hosting/security" + "self-hosting/security", + "self-hosting/admin-panel" ] } ] @@ -66,6 +68,7 @@ "guides/github-oauth", "guides/google-oauth", "guides/discord-oauth", + "guides/connected-accounts", "guides/api-authentication" ] }, @@ -91,7 +94,9 @@ { "group": "Deliverability", "pages": [ - "guides/deliverability" + "guides/deliverability", + "guides/spam-protection", + "guides/sending-regions" ] }, { @@ -116,7 +121,9 @@ "groups": [ { "group": "API Reference", - "pages": ["api-reference/introduction"] + "pages": [ + "api-reference/introduction" + ] }, { "group": "Emails", @@ -189,7 +196,6 @@ } ] } - ], "global": { "anchors": [ @@ -200,7 +206,7 @@ }, { "anchor": "Discord", - "href": "https://discord.gg/nodebyte", + "href": "https://https://discord.gg/C2Q4GHXKQA", "icon": "discord" }, { @@ -212,8 +218,8 @@ } }, "logo": { - "light": "/logo/logo-wordmark.svg", - "dark": "/logo/logo-wordmark-dark.svg" + "light": "/logo/wordmark-light.png", + "dark": "/logo/wordmark-dark.png" }, "api": { "playground": { @@ -230,7 +236,7 @@ "links": [ { "label": "Support", - "href": "https://discord.gg/nodebyte" + "href": "https://https://discord.gg/C2Q4GHXKQA" } ], "primary": { @@ -246,6 +252,12 @@ } }, "contextual": { - "options": ["copy", "view", "chatgpt", "claude", "perplexity"] + "options": [ + "copy", + "view", + "chatgpt", + "claude", + "perplexity" + ] } -} +} \ No newline at end of file diff --git a/apps/docs/favicon.svg b/apps/docs/favicon.svg index ceffa59..991bf65 100644 --- a/apps/docs/favicon.svg +++ b/apps/docs/favicon.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/apps/docs/guides/admin-operations.mdx b/apps/docs/guides/admin-operations.mdx index e2fb359..ce155e9 100644 --- a/apps/docs/guides/admin-operations.mdx +++ b/apps/docs/guides/admin-operations.mdx @@ -14,8 +14,7 @@ Admin operations allow you to manage billing, team permissions, and advanced acc **Team Member Management**: - Add and remove team members -- Assign and modify roles (Admin, Editor, Viewer) -- View member activity and last login information +- Assign and modify roles (Admin or Member) - Manage pending invitations **Plan & Billing Management**: @@ -26,10 +25,10 @@ Admin operations allow you to manage billing, team permissions, and advanced acc - Set up billing notifications **Workspace Settings**: -- Configure account name and branding +- Configure the team name and image - Manage API keys -- Set security policies - Configure notification channels +- Change a domain's sending region ## Billing Management @@ -182,73 +181,44 @@ Each invoice includes: ## Team Permissions & Roles -### Admin Role +Every team member is either an **Admin** or a **Member**. -**Capabilities**: -- Add/remove team members -- Change member roles -- Access all account settings -- Manage billing and payment methods -- View all team activity -- Create and manage API keys -- Configure notifications +| Action | Admin | Member | +| --- | :---: | :---: | +| Send email, manage domains, templates, contacts and campaigns | ✓ | ✓ | +| Create API keys, webhooks and notification providers | ✓ | ✓ | +| View analytics and email logs | ✓ | ✓ | +| Invite members and change their roles | ✓ | | +| Edit the team name, image and SMTP username | ✓ | | +| Manage billing, plans, add-on slots and the billing email | ✓ | | +| Change a domain's sending region | ✓ | | +| Delete the team | ✓ | | -**Best for**: Account owners, billing contacts, senior team members - -### Editor Role - -**Capabilities**: -- Create and edit campaigns -- Manage email templates -- Verify new domains -- Create webhooks -- View analytics and reports -- Access API with owned keys - -**Restrictions**: Cannot manage team members, billing, or settings - -**Best for**: Team members actively managing emails - -### Viewer Role - -**Capabilities**: -- View campaigns and reports -- View analytics and dashboards -- Read-only access to settings -- Cannot make changes - -**Restrictions**: Cannot send emails, create campaigns, or modify settings - -**Best for**: Stakeholders, clients, observers + +Give the Admin role only to people who manage billing or the team itself. Everyone who only sends email can be a Member. + ## Security & Compliance ### Two-Factor Authentication -For GitHub OAuth users: -- Enable 2FA on your GitHub account -- [GitHub 2FA setup](https://github.com/settings/security) +Turn on two-factor authentication in **Settings → Account** with any authenticator app. Store the recovery codes somewhere safe — they are the only way back in if you lose your device. If you sign in with GitHub, Google or Discord, enable 2FA on that provider too. ### API Key Management -Admin admins should: +Admins should: - Regularly audit active API keys - Revoke old or unused keys - Use different keys for different environments - Never share keys with team members - Store keys in environment variables -### Audit Logs +### Activity History -Monitor admin actions: -- Team member additions/removals -- Plan changes -- Payment method updates -- API key generation/revocation - - -Keep audit logs for compliance and security purposes. Consider setting up webhook notifications for admin activity. - +ByteSend does not yet keep a team-visible audit log. To keep an eye on your account: +- Review your API keys regularly — the dashboard shows when each key was last used +- Subscribe a [webhook](/guides/webhooks) or [notification provider](/guides/notification-providers) to email and domain events +- Check **Settings → Members** for unexpected members or pending invites ## Compliance & Business Management diff --git a/apps/docs/guides/connected-accounts.mdx b/apps/docs/guides/connected-accounts.mdx new file mode 100644 index 0000000..be0e512 --- /dev/null +++ b/apps/docs/guides/connected-accounts.mdx @@ -0,0 +1,40 @@ +--- +title: Connected Accounts +description: "Sign in with GitHub, Google or Discord, and keep your ByteSend email in sync" +icon: link +--- + +## Overview + +You can sign in to ByteSend with your email address or with any connected GitHub, Google or Discord account. Manage them in **Settings → Account → Connected Accounts**. + +| Action | What it does | +| --- | --- | +| **Connect** | Links another provider to your ByteSend account, so you can sign in with it | +| **Reconnect** | Signs in with the provider again to refresh the email address and avatar it shares with ByteSend | +| **Disconnect** | Removes the provider. You can still sign in with your email address | +| **Use this email** | Makes the provider's email address your ByteSend email, after verification | + +Which providers appear depends on how your ByteSend instance is configured. + +--- + +## Changing your email to a provider's email + +If you changed the email address on your GitHub, Google or Discord account: + +1. Select **Reconnect** next to the provider so ByteSend sees the new address. +2. Select **Use this email**. +3. Enter the code sent to your current email, then the code sent to the new one. + +You need access to both addresses, the same as any other email change. If two-factor authentication is on and you have lost access to your current email, you can use one of your recovery codes in place of the first code. + +--- + +## Verified emails only + +ByteSend only accepts a provider sign-in when the provider has verified that email address. If you see *"That account's email address isn't verified with the provider"*, verify the email in your GitHub, Google or Discord settings, then try again — or sign in with your email address instead. + + +This protects your account: without it, anyone could add your email address to a new account on another service and use it to sign in to ByteSend as you. + diff --git a/apps/docs/guides/deliverability.mdx b/apps/docs/guides/deliverability.mdx index f07b788..0f601fa 100644 --- a/apps/docs/guides/deliverability.mdx +++ b/apps/docs/guides/deliverability.mdx @@ -108,6 +108,8 @@ Start with your most engaged users: people who have recently interacted with you - Keep your image-to-text ratio reasonable. Pure-image emails perform poorly. - Always include a visible, working unsubscribe link +ByteSend also scores every outbound email before it is sent, and holds high-risk messages for review. See [Spam Protection](/guides/spam-protection) for what is checked and how to avoid false positives. + ### 5. Monitor Bounces and Complaints in Real Time Set up a [webhook](/guides/webhooks) for `email.bounced` and `email.complained` events so you can react immediately: @@ -154,7 +156,7 @@ Configure [Discord or Slack notifications](/guides/notification-providers) for ` ByteSend maintains an automatic suppression list. Addresses that hard bounce are added automatically and will be silently skipped on future sends rather than bouncing again, protecting your reputation. -If you need to manually remove an address from the suppression list (e.g., after the recipient fixed a typo in their email), contact support via [Discord](https://discord.gg/Bg3Sf5fqa4). +If you need to manually remove an address from the suppression list (e.g., after the recipient fixed a typo in their email), contact support via [Discord](https://discord.gg/C2Q4GHXKQA). --- @@ -166,7 +168,7 @@ If your sending is blocked due to reputation thresholds: 2. **Check the dashboard** for the specific metric that triggered it. 3. **Clean your list.** Remove bounced addresses and unsubscribe anyone who has complained. 4. **Wait for the 7-day window to roll.** As old events age out, your rate will naturally improve. -5. **Contact support** on [Discord](https://discord.gg/Bg3Sf5fqa4) if you need the block lifted sooner and can explain why the spike occurred +5. **Contact support** on [Discord](https://discord.gg/C2Q4GHXKQA) if you need the block lifted sooner and can explain why the spike occurred --- @@ -196,3 +198,10 @@ If your sending is blocked due to reputation thresholds: - Dashboard reputation metrics reviewed weekly + +--- + +## Related + +- [Spam Protection](/guides/spam-protection) — outbound scoring and held emails +- [Changing Sending Region](/guides/sending-regions) — move a domain to another AWS region without downtime diff --git a/apps/docs/guides/discord-oauth.mdx b/apps/docs/guides/discord-oauth.mdx index 1fc83d4..d05b91d 100644 --- a/apps/docs/guides/discord-oauth.mdx +++ b/apps/docs/guides/discord-oauth.mdx @@ -12,7 +12,7 @@ ByteSend supports Discord OAuth, letting you sign in with your Discord account f - **Single Sign-On**: Use your Discord account to access ByteSend - **Automatic avatar sync**: Your Discord profile picture is imported and kept up to date on each sign-in -- **Community integration**: Same account you use in our [Discord server](https://discord.gg/Bg3Sf5fqa4) +- **Community integration**: Same account you use in our [Discord server](https://discord.gg/C2Q4GHXKQA) - **Account linking**: Connect Discord to an existing ByteSend account ## Signing In with Discord @@ -75,7 +75,7 @@ After revoking, you can still sign in via email magic link if your account uses Clear your browser cookies and try again. If you're using a VPN, try disabling it. Discord sometimes blocks OAuth callbacks from certain regions. - Contact [ByteSend Support on Discord](https://discord.gg/Bg3Sf5fqa4) and include both email addresses. We can manually unlink accounts. + Contact [ByteSend Support on Discord](https://discord.gg/C2Q4GHXKQA) and include both email addresses. We can manually unlink accounts. @@ -83,4 +83,4 @@ After revoking, you can still sign in via email magic link if your account uses - [Create your first API key](/guides/api-authentication) - [Add a verified domain](https://bytesend.cloud/domains) -- [Join the ByteSend Discord community](https://discord.gg/Bg3Sf5fqa4) +- [Join the ByteSend Discord community](https://discord.gg/C2Q4GHXKQA) diff --git a/apps/docs/guides/error-codes.mdx b/apps/docs/guides/error-codes.mdx index 6897f5f..375ba07 100644 --- a/apps/docs/guides/error-codes.mdx +++ b/apps/docs/guides/error-codes.mdx @@ -80,7 +80,7 @@ The API key is valid but the action is not permitted. This usually happens becau { "error": { "code": "FORBIDDEN", - "message": "This team has been blocked. Please contact support via Discord: https://discord.gg/Bg3Sf5fqa4" + "message": "This team has been blocked. Please contact support via Discord: https://discord.gg/C2Q4GHXKQA" } } ``` @@ -179,7 +179,7 @@ An unexpected error occurred on the ByteSend server. These are rare and typicall **What to do:** - Retry the request with exponential backoff -- If the error persists, contact support via [Discord](https://discord.gg/Bg3Sf5fqa4) +- If the error persists, contact support via [Discord](https://discord.gg/C2Q4GHXKQA) --- diff --git a/apps/docs/guides/google-oauth.mdx b/apps/docs/guides/google-oauth.mdx index b165a52..7d6206f 100644 --- a/apps/docs/guides/google-oauth.mdx +++ b/apps/docs/guides/google-oauth.mdx @@ -69,7 +69,7 @@ After revoking, you can still sign in via email magic link if your account has t Clear your browser cookies and try again. If the error persists, make sure the Google account has email verification enabled and is not a Google Workspace account with admin restrictions. - Contact [ByteSend Support on Discord](https://discord.gg/Bg3Sf5fqa4) and include both email addresses. We can manually unlink and re-link accounts. + Contact [ByteSend Support on Discord](https://discord.gg/C2Q4GHXKQA) and include both email addresses. We can manually unlink and re-link accounts. diff --git a/apps/docs/guides/rate-limits.mdx b/apps/docs/guides/rate-limits.mdx index bbb45c6..bdf2cb6 100644 --- a/apps/docs/guides/rate-limits.mdx +++ b/apps/docs/guides/rate-limits.mdx @@ -128,4 +128,4 @@ def send_with_retry(payload: dict, max_retries: int = 3) -> dict: ## Need a Higher Limit? -If your use case requires a higher rate limit than your plan provides, contact us on [Discord](https://discord.gg/Bg3Sf5fqa4) and we'll work something out. +If your use case requires a higher rate limit than your plan provides, contact us on [Discord](https://discord.gg/C2Q4GHXKQA) and we'll work something out. diff --git a/apps/docs/guides/sending-regions.mdx b/apps/docs/guides/sending-regions.mdx new file mode 100644 index 0000000..1e44271 --- /dev/null +++ b/apps/docs/guides/sending-regions.mdx @@ -0,0 +1,48 @@ +--- +title: Changing Sending Region +description: "Move a verified domain to a different AWS region without interrupting delivery" +icon: globe +--- + +## Overview + +Every domain sends from one AWS SES region, chosen when you add it. You can move a verified domain to another region — for example to keep data in the EU, or to sit closer to your recipients — without any downtime. + +Only team **Admins** can change a domain's region. + +--- + +## How a move works + +Your domain keeps sending from its current region for the whole move. ByteSend registers it in the new region alongside the old one and only switches over once the new region is fully verified. + + + + Open the domain in the dashboard, select **Change region** in the **Sending region** card and choose the new region. + + + Add the new `TXT` record shown on the domain page. Its name includes the region (for example `bytesend-eu-west-2._domainkey`), so it sits **alongside** your existing DKIM record — don't delete the old one yet. + + + Change the `MX` record on your `mail.` subdomain to the new region's value, for example `feedback-smtp.eu-west-2.amazonses.com`. Replace the old value; don't add a second record. Your SPF record does not change. + + + ByteSend checks the new records automatically every hour, or immediately when you select **Check now**. As soon as DKIM and the custom MAIL FROM domain are verified in the new region, the domain switches over and all new email sends from there. + + + The old region stays registered for 24 hours after the switch so that any email already in flight still delivers. After that you can delete the old DKIM `TXT` record. The domain page tells you when. + + + +--- + +## What to expect during a move + +- **No downtime.** Email keeps sending from the old region until the switch. +- **Between steps 3 and 4**, the old region temporarily uses Amazon's default MAIL FROM domain instead of your `mail.` subdomain. Email still delivers and still passes DMARC through DKIM; only SPF alignment is briefly lost. +- **DNS takes time.** Most providers update within minutes, but changes can take up to an hour to be visible. **Check now** tells you which record isn't visible yet. +- **You can cancel** at any time before the switch. The domain stays on its current region; remove the new DKIM record and change the `MX` record back if you already changed them. + + +You can't start another move until 24 hours after the previous one finished, while the old region is still being retired. + diff --git a/apps/docs/guides/spam-protection.mdx b/apps/docs/guides/spam-protection.mdx new file mode 100644 index 0000000..e0ad5a3 --- /dev/null +++ b/apps/docs/guides/spam-protection.mdx @@ -0,0 +1,68 @@ +--- +title: Spam Protection +description: "How ByteSend screens outbound email, what a held message means, and how to avoid false positives" +icon: shield-halved +--- + +## Overview + +Every email you send through the API, the SMTP relay or a campaign is scored by ByteSend's spam protection before it is queued. It protects your domain's reputation — and every other customer's — from compromised API keys, phishing and accidental spam. + +Most mail never notices it: ordinary transactional email such as password resets, verification codes and receipts scores well below the thresholds. + +| Score | What happens | +| --- | --- | +| Below **5** | Sent normally | +| **5 – 9** (flagged) | Sent normally, and recorded for review | +| **10 or more** (held) | Not sent. The email gets the `HELD` status until ByteSend reviews it | + +--- + +## What is checked + +Each signal adds to the score. Scores are capped per category, so a single strong phrase cannot hold a message on its own. + +| Signal | Example | +| --- | --- | +| Phishing language | "Verify your account", "your account has been suspended", "unusual sign-in activity" | +| Brand impersonation | A sender name of "PayPal Security" sent from a domain that isn't PayPal's | +| Misleading links | Link text that shows one domain while the link goes to another | +| Risky links | Links to raw IP addresses, URL shorteners, punycode look-alike domains, or `javascript:` / `data:` URLs | +| Dangerous attachments | Executables and macro-enabled documents such as `.exe`, `.js`, `.iso`, `.docm`, `.xlsm` | +| Spam patterns | "100% free", "act now", ALL-CAPS subjects, `!!!`, image-only bodies, hidden text | +| Blocklisted links | Links to domains on the Spamhaus Domain Block List (when enabled on the instance) | +| New account | A small extra weight for teams created in the last 7 days | + +--- + +## Held emails + +When an email is held: + +- The API still accepts the request and returns the email ID, so your integration does not error. +- The email's status is `HELD`, and its event timeline explains that it is waiting for review. +- ByteSend reviews it and either **releases** it (it is queued and sent as normal) or **rejects** it (its status becomes `REJECTED` and it is never sent). + +If you subscribe to [webhooks](/guides/webhooks), you receive the normal events for a released email once it is sent. + +### Campaigns + +Campaigns are scored once, when you start sending. If a campaign is held, it is paused and you see a message explaining that it is waiting for review. Once released, it sends as usual. + + +If five of a team's messages are held within 24 hours, sending is blocked for that team until ByteSend reviews the account. Contact support on [Discord](https://discord.gg/C2Q4GHXKQA) if this happens to legitimate mail. + + +--- + +## Avoiding false positives + +- **Make link text match the link.** If the text shows `acme.com/orders/42`, link to that address rather than a different domain. (ByteSend's own click tracking is applied after scanning and doesn't count.) +- **Avoid URL shorteners.** Link to your own domain. If you want click analytics, turn on click tracking in your domain's settings. +- **Use a sender name that matches your domain.** Don't put another company's name in your From name. +- **Don't attach executables or macro documents.** Link to a download on your own site instead. +- **Include real text.** An email that is a single image with no text looks like spam to every filter, not just ByteSend's. + + +Think a legitimate email was held? Contact support on [Discord](https://discord.gg/C2Q4GHXKQA) with the email ID — reviews also help ByteSend tune the rules. + diff --git a/apps/docs/introduction.mdx b/apps/docs/introduction.mdx index 1ea33c4..7490d8c 100644 --- a/apps/docs/introduction.mdx +++ b/apps/docs/introduction.mdx @@ -277,7 +277,7 @@ Want to run ByteSend on your own infrastructure? ## Quick Links - [View GitHub Repository](https://github.com/NodeByteLTD/ByteSend) -- [Join Community Discord](https://discord.gg/nodebyte) +- [Join Community Discord](https://https://discord.gg/C2Q4GHXKQA) - [Follow on Twitter](https://twitter.com/TryByteSend) - [Dashboard](https://bytesend.cloud) @@ -285,5 +285,5 @@ Want to run ByteSend on your own infrastructure? - Browse the [API Reference](/api-reference/introduction) - Check out [Integration Guides](/guides/webhooks) -- Join our [Community Discord](https://discord.gg/nodebyte) +- Join our [Community Discord](https://https://discord.gg/C2Q4GHXKQA) - View [GitHub Discussions](https://github.com/NodeByteLTD/ByteSend/discussions) diff --git a/apps/docs/logo/logo-wordmark-dark.svg b/apps/docs/logo/logo-wordmark-dark.svg deleted file mode 100644 index 8c41f88..0000000 --- a/apps/docs/logo/logo-wordmark-dark.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/apps/docs/logo/logo-wordmark.svg b/apps/docs/logo/logo-wordmark.svg deleted file mode 100644 index 8c41f88..0000000 --- a/apps/docs/logo/logo-wordmark.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/apps/docs/logo/wordmark-dark.png b/apps/docs/logo/wordmark-dark.png new file mode 100644 index 0000000..855fa0c Binary files /dev/null and b/apps/docs/logo/wordmark-dark.png differ diff --git a/apps/docs/logo/wordmark-light.png b/apps/docs/logo/wordmark-light.png new file mode 100644 index 0000000..ad92c80 Binary files /dev/null and b/apps/docs/logo/wordmark-light.png differ diff --git a/apps/docs/self-hosting/admin-panel.mdx b/apps/docs/self-hosting/admin-panel.mdx new file mode 100644 index 0000000..4b4753e --- /dev/null +++ b/apps/docs/self-hosting/admin-panel.mdx @@ -0,0 +1,73 @@ +--- +title: Admin Panel +description: "Run your ByteSend instance: platform health, teams, deliverability, spam review and the audit log" +icon: gauge +--- + +## Access + +Open **Admin Panel** from the account menu at the bottom of the sidebar, or go to `/admin`. + +- **Self-hosted:** every signed-in user can open the admin panel. +- **Cloud mode** (`NEXT_PUBLIC_IS_CLOUD=true`): only users with the admin flag, or the addresses in `FOUNDER_EMAIL` / `ADMIN_EMAIL`. Granting admin and beta access is limited to the founder. + +Press Ctrl/⌘ + K anywhere in the admin panel to search users, teams, domains and emails (by ID, or by recipient for the last 30 days). + +Some sections only appear in cloud mode; they are marked below. + +--- + +## Sections + +| Section | What it's for | +| --- | --- | +| **Overview** | Sends, delivery, bounce and complaint rates, signups and paid teams over 7, 30 or 90 days; SES quota and sandbox status per region; teams that need attention; recent admin activity | +| **Users** *(cloud)* | Find a user and manage their access: ban, admin and beta flags, plus their 2FA, sign-in methods, sessions and teams | +| **Teams** *(cloud)* | A page per team: usage, deliverability, members, domains, API keys, webhooks, subscription, limits, plan, block/unblock and delete | +| **Domains** *(cloud)* | Every domain on the instance; force-verify a stuck domain or delete one | +| **Emails** | Sending history across all teams, filtered by time, status, recipient, sender, subject or team, with each email's event timeline | +| **Email analytics** *(cloud)* | Per-team totals for today or this month | +| **Deliverability** | Every team's 7-day hard-bounce and complaint rates against the limits that block sending | +| **Blacklists** *(cloud)* | Daily blocklist status for verified domains | +| **Spam review** | Held and flagged outbound messages: release or reject held ones | +| **Billing** *(cloud)* | Plans and Stripe subscription state per team | +| **SES regions** | The AWS SES regions the instance sends through, with quotas and callback status | +| **Webhooks** *(cloud)* | Customer webhook endpoints and their delivery health | +| **Audit log** | Every change made through the admin panel | + +--- + +## Audit log + +Every admin action is recorded with who did it, when and to what, including a before/after diff for team settings. That covers: + +- Banning or unbanning users and changing admin or beta access +- Team settings, plan assignments, blocks and deletions +- Force-verifying or deleting domains, starting or cancelling region moves and blocklist re-checks +- Releasing or rejecting held messages +- Viewing an email's content in the email explorer + +Message bodies are hidden in the email explorer until you choose **View content**, and every view is logged. + +--- + +## Blocklist monitoring + +Every day at 04:30 UTC, ByteSend checks each verified sending domain against the Spamhaus Domain Block List, SURBL and URIBL, and posts newly listed domains to the Discord webhook in `DISCORD_WEBHOOK_URL`. Checks are kept for 30 days. + +These lists refuse queries that come through large public DNS resolvers, which most cloud servers use. ByteSend shows those results as **Unknown** rather than reporting a false "clean". For reliable Spamhaus results, set `SPAMHAUS_DQS_KEY` — see [environment variables](/self-hosting/docker#environment-variable-reference). + + +ByteSend sends through Amazon's shared SES IP addresses, so only your sending **domains** are checked, not IPs. + + +--- + +## Spam review + +Outbound email is scored before it is queued ([how scoring works](/guides/spam-protection)). Messages scoring 5 or more are flagged and still sent; messages scoring 10 or more are held with the `HELD` status until you review them in **Spam review**: + +- **Release** queues the email (or resumes the campaign) and sends it normally. +- **Reject** never sends it; the email's status becomes `REJECTED`. You must give a reason, which is saved to the audit log. + +A team with five held messages in 24 hours is blocked automatically. Unblock it from the team's page once you have reviewed it. diff --git a/apps/docs/self-hosting/docker.mdx b/apps/docs/self-hosting/docker.mdx index 7c32875..c043992 100644 --- a/apps/docs/self-hosting/docker.mdx +++ b/apps/docs/self-hosting/docker.mdx @@ -154,4 +154,6 @@ docker compose -f docker/prod/compose.yml --env-file docker/prod/.env up -d | `GOOGLE_CLIENT_SECRET` | No | Google OAuth app client secret | | `STRIPE_SECRET_KEY` | No | Stripe secret key (billing) | | `STRIPE_WEBHOOK_SECRET` | No | Stripe webhook signing secret | +| `DISCORD_WEBHOOK_URL` | No | Discord webhook for platform alerts (signups, blocked teams, blocklisted domains) | +| `SPAMHAUS_DQS_KEY` | No | Spamhaus Data Query Service key for reliable blocklist and link-reputation checks | diff --git a/apps/docs/self-hosting/overview.mdx b/apps/docs/self-hosting/overview.mdx index 69fe6ec..09799be 100644 --- a/apps/docs/self-hosting/overview.mdx +++ b/apps/docs/self-hosting/overview.mdx @@ -8,7 +8,7 @@ ByteSend is fully self-hostable. This guide covers two deployment paths: - **[Docker (recommended)](#docker-deployment)** — spin up the entire stack with a single `docker compose` command - **[Manual / bare-metal](#manual-deployment)** — install directly on a Linux server using Node.js and pnpm -If you have questions, join [#self-host](https://discord.gg/nodebyte) on Discord. +If you have questions, join [#self-host](https://https://discord.gg/C2Q4GHXKQA) on Discord. --- @@ -272,6 +272,8 @@ sudo journalctl -u bytesend -f | `S3_COMPATIBLE_*` | No | S3-compatible storage (defaults to bundled MinIO) | | `SMTP_HOST` / `SMTP_USER` | No | External SMTP relay for account emails | | `ADMIN_EMAIL` | No | Grants admin panel access to this address | +| `DISCORD_WEBHOOK_URL` | No | Discord webhook for platform alerts (signups, blocked teams, blocklisted domains) | +| `SPAMHAUS_DQS_KEY` | No | Spamhaus Data Query Service key for reliable blocklist and link-reputation checks | | `API_RATE_LIMIT` | No | API requests per second per key (default `1`) | | `AUTH_EMAIL_RATE_LIMIT` | No | Magic-link emails per minute (default `5`) | @@ -286,4 +288,5 @@ sudo journalctl -u bytesend -f | Firewall (UFW) | [Firewall Setup](./firewall) | | Reverse proxy | [Nginx / Traefik](./reverse-proxy) | | Security hardening | [Security](./security) | +| Running the instance | [Admin Panel](./admin-panel) | diff --git a/apps/web/middleware.ts b/apps/web/middleware.ts index d0f304c..0d82357 100644 --- a/apps/web/middleware.ts +++ b/apps/web/middleware.ts @@ -5,12 +5,6 @@ import { validateTwoFactorCookieEdge, TWO_FACTOR_COOKIE } from "~/lib/edge-2fa-u export async function middleware(request: NextRequest) { const pathname = request.nextUrl.pathname; - // Skip middleware for: - // - Public routes - // - API routes - // - Auth routes - // - Marketing routes - // - Static assets const publicPaths = [ "/login", "/signup", @@ -34,27 +28,17 @@ export async function middleware(request: NextRequest) { return NextResponse.next(); } - // For dashboard routes, check 2FA if (pathname.startsWith("/dashboard") || pathname.startsWith("/broadcasts") || pathname.startsWith("/campaigns")) { const token = await getToken({ req: request, secret: process.env.NEXTAUTH_SECRET }); if (!token) { - // Not authenticated, redirect to login return NextResponse.redirect(new URL("/login", request.url)); } - // Redirect banned users before any other checks if (token.isBanned) { return NextResponse.redirect(new URL("/banned", request.url)); } - // User is authenticated. Check if they have 2FA enabled. - // We can't query the DB from middleware easily, so we rely on: - // 1. The 2FA cookie being set after verification - // 2. If no cookie, we let the client-side check handle it (DashboardProvider) - // But for maximum security, we could also check via an API call - - // For now, just verify the cookie if it exists const cookieValue = request.cookies.get(TWO_FACTOR_COOKIE)?.value; const userId = token.sub ? parseInt(token.sub, 10) : null; @@ -65,19 +49,14 @@ export async function middleware(request: NextRequest) { process.env.NEXTAUTH_SECRET ?? "dev-secret" ); if (!isValid) { - // Invalid/expired cookie, redirect to 2FA verification const url = new URL("/auth/2fa-verify", request.url); const res = NextResponse.redirect(url); res.cookies.delete(TWO_FACTOR_COOKIE); return res; } - // Valid cookie, allow access return NextResponse.next(); } - // No cookie — the DashboardProvider will handle the 2FA gate client-side - // But optionally we could require 2FA verification here - // For now, allow the request to proceed and let the dashboard provider gate it return NextResponse.next(); } @@ -86,7 +65,6 @@ export async function middleware(request: NextRequest) { export const config = { matcher: [ - // Match all paths except static files and api/auth/callback "/((?!api/auth/callback|_next/static|_next/image|favicon.ico).*)", ], }; diff --git a/apps/web/package.json b/apps/web/package.json index 728a7e3..5558c4e 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -3,6 +3,8 @@ "private": true, "type": "module", "scripts": { + "brand:generate": "tsx --tsconfig scripts/brand/tsconfig.json scripts/brand/generate.tsx", + "brand:emojis": "tsx --tsconfig scripts/brand/tsconfig.json scripts/brand/emojis.tsx", "dev": "next dev -p 3000 --turbopack", "build": "next build", "start": "next start", @@ -105,6 +107,7 @@ "@types/mime-types": "^2.1.4", "@types/node": "^22.15.2", "@types/nodemailer": "^6.4.17", + "@types/pngjs": "6.0.5", "@types/react": "^19.1.2", "@types/react-dom": "^19.1.2", "@types/ua-parser-js": "^0.7.39", @@ -114,6 +117,8 @@ "dotenv": "^16.5.0", "eslint": "^8.57.1", "eslint-config-next": "^15.3.1", + "gifenc": "1.0.3", + "pngjs": "7.0.0", "postcss": "^8.5.3", "prettier": "^3.5.3", "prettier-plugin-tailwindcss": "^0.6.11", diff --git a/apps/web/prisma/migrations/20261018200000_add_admin_audit_log/migration.sql b/apps/web/prisma/migrations/20261018200000_add_admin_audit_log/migration.sql new file mode 100644 index 0000000..2ac6769 --- /dev/null +++ b/apps/web/prisma/migrations/20261018200000_add_admin_audit_log/migration.sql @@ -0,0 +1,29 @@ +-- CreateTable +CREATE TABLE "AdminAuditLog" ( + "id" TEXT NOT NULL, + "actorId" INTEGER, + "actorEmail" TEXT, + "action" TEXT NOT NULL, + "targetType" TEXT NOT NULL, + "targetId" TEXT NOT NULL, + "metadata" JSONB, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "AdminAuditLog_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE INDEX "AdminAuditLog_createdAt_idx" ON "AdminAuditLog"("createdAt" DESC); + +-- CreateIndex +CREATE INDEX "AdminAuditLog_targetType_targetId_idx" ON "AdminAuditLog"("targetType", "targetId"); + +-- CreateIndex +CREATE INDEX "AdminAuditLog_actorId_idx" ON "AdminAuditLog"("actorId"); + +-- CreateIndex +CREATE INDEX "AdminAuditLog_action_idx" ON "AdminAuditLog"("action"); + +-- AddForeignKey +ALTER TABLE "AdminAuditLog" ADD CONSTRAINT "AdminAuditLog_actorId_fkey" FOREIGN KEY ("actorId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE; + diff --git a/apps/web/prisma/migrations/20261018210000_add_domain_blacklist_checks/migration.sql b/apps/web/prisma/migrations/20261018210000_add_domain_blacklist_checks/migration.sql new file mode 100644 index 0000000..f2f6e01 --- /dev/null +++ b/apps/web/prisma/migrations/20261018210000_add_domain_blacklist_checks/migration.sql @@ -0,0 +1,24 @@ +-- CreateEnum +CREATE TYPE "BlacklistStatus" AS ENUM ('LISTED', 'CLEAN', 'ERROR'); + +-- CreateTable +CREATE TABLE "DomainBlacklistCheck" ( + "id" TEXT NOT NULL, + "domainId" INTEGER NOT NULL, + "list" TEXT NOT NULL, + "status" "BlacklistStatus" NOT NULL, + "returnCode" TEXT, + "checkedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "DomainBlacklistCheck_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE INDEX "DomainBlacklistCheck_domainId_checkedAt_idx" ON "DomainBlacklistCheck"("domainId", "checkedAt" DESC); + +-- CreateIndex +CREATE INDEX "DomainBlacklistCheck_status_checkedAt_idx" ON "DomainBlacklistCheck"("status", "checkedAt" DESC); + +-- AddForeignKey +ALTER TABLE "DomainBlacklistCheck" ADD CONSTRAINT "DomainBlacklistCheck_domainId_fkey" FOREIGN KEY ("domainId") REFERENCES "Domain"("id") ON DELETE CASCADE ON UPDATE CASCADE; + diff --git a/apps/web/prisma/migrations/20261018220000_add_account_email/migration.sql b/apps/web/prisma/migrations/20261018220000_add_account_email/migration.sql new file mode 100644 index 0000000..c5630bb --- /dev/null +++ b/apps/web/prisma/migrations/20261018220000_add_account_email/migration.sql @@ -0,0 +1,3 @@ +-- AlterTable +ALTER TABLE "Account" ADD COLUMN "email" TEXT; + diff --git a/apps/web/prisma/migrations/20261018230000_add_domain_region_move/migration.sql b/apps/web/prisma/migrations/20261018230000_add_domain_region_move/migration.sql new file mode 100644 index 0000000..67e085b --- /dev/null +++ b/apps/web/prisma/migrations/20261018230000_add_domain_region_move/migration.sql @@ -0,0 +1,10 @@ +-- AlterTable +ALTER TABLE "Domain" ADD COLUMN "pendingDkimSelector" TEXT, +ADD COLUMN "pendingDkimStatus" TEXT, +ADD COLUMN "pendingMailFromStatus" TEXT, +ADD COLUMN "pendingPublicKey" TEXT, +ADD COLUMN "pendingRegion" TEXT, +ADD COLUMN "regionMoveStartedAt" TIMESTAMP(3), +ADD COLUMN "retiredRegion" TEXT, +ADD COLUMN "retiredRegionAt" TIMESTAMP(3); + diff --git a/apps/web/prisma/migrations/20261019000000_add_spam_scans/migration.sql b/apps/web/prisma/migrations/20261019000000_add_spam_scans/migration.sql new file mode 100644 index 0000000..7cd794b --- /dev/null +++ b/apps/web/prisma/migrations/20261019000000_add_spam_scans/migration.sql @@ -0,0 +1,41 @@ +-- CreateEnum +CREATE TYPE "SpamVerdict" AS ENUM ('FLAG', 'HOLD'); + +-- CreateEnum +CREATE TYPE "SpamReviewDecision" AS ENUM ('RELEASED', 'REJECTED'); + +-- AlterEnum +ALTER TYPE "EmailStatus" ADD VALUE 'HELD'; + +-- CreateTable +CREATE TABLE "SpamScan" ( + "id" TEXT NOT NULL, + "teamId" INTEGER NOT NULL, + "emailId" TEXT, + "campaignId" TEXT, + "score" INTEGER NOT NULL, + "verdict" "SpamVerdict" NOT NULL, + "hits" JSONB NOT NULL, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "reviewedById" INTEGER, + "reviewedAt" TIMESTAMP(3), + "reviewDecision" "SpamReviewDecision", + + CONSTRAINT "SpamScan_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE INDEX "SpamScan_verdict_reviewedAt_createdAt_idx" ON "SpamScan"("verdict", "reviewedAt", "createdAt" DESC); + +-- CreateIndex +CREATE INDEX "SpamScan_teamId_createdAt_idx" ON "SpamScan"("teamId", "createdAt" DESC); + +-- CreateIndex +CREATE INDEX "SpamScan_emailId_idx" ON "SpamScan"("emailId"); + +-- CreateIndex +CREATE INDEX "SpamScan_campaignId_idx" ON "SpamScan"("campaignId"); + +-- AddForeignKey +ALTER TABLE "SpamScan" ADD CONSTRAINT "SpamScan_teamId_fkey" FOREIGN KEY ("teamId") REFERENCES "Team"("id") ON DELETE CASCADE ON UPDATE CASCADE; + diff --git a/apps/web/prisma/schema.prisma b/apps/web/prisma/schema.prisma index 3f85b16..7e32c50 100644 --- a/apps/web/prisma/schema.prisma +++ b/apps/web/prisma/schema.prisma @@ -58,6 +58,7 @@ model Account { scope String? id_token String? // @db.Text session_state String? + email String? user User @relation(fields: [userId], references: [id], onDelete: Cascade) @@unique([provider, providerAccountId]) @@ -100,6 +101,7 @@ model User { twoFactorRecoveryCodes TwoFactorRecoveryCode[] backupEmails BackupEmail[] @relation("userBackupEmails") pendingBackupEmailVerifications PendingBackupEmailVerification[] + adminAuditLogs AdminAuditLog[] } model PendingEmailChange { @@ -206,6 +208,7 @@ model Team { webhookCalls WebhookCall[] notificationProviders NotificationProvider[] notificationLogs NotificationLog[] + spamScans SpamScan[] } model TeamInvite { @@ -261,26 +264,35 @@ enum DomainStatus { } model Domain { - id Int @id @default(autoincrement()) - name String @unique - teamId Int - status DomainStatus @default(PENDING) - region String @default("us-east-1") - clickTracking Boolean @default(false) - openTracking Boolean @default(false) - publicKey String - dkimSelector String? @default("bytesend") - dkimStatus String? - spfDetails String? - dmarcAdded Boolean @default(false) - errorMessage String? - subdomain String? - sesTenantId String? - isVerifying Boolean @default(false) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - team Team @relation(fields: [teamId], references: [id], onDelete: Cascade) - apiKeys ApiKey[] + id Int @id @default(autoincrement()) + name String @unique + teamId Int + status DomainStatus @default(PENDING) + region String @default("us-east-1") + clickTracking Boolean @default(false) + openTracking Boolean @default(false) + publicKey String + dkimSelector String? @default("bytesend") + dkimStatus String? + spfDetails String? + dmarcAdded Boolean @default(false) + errorMessage String? + subdomain String? + sesTenantId String? + isVerifying Boolean @default(false) + pendingRegion String? + pendingDkimSelector String? + pendingPublicKey String? + pendingDkimStatus String? + pendingMailFromStatus String? + regionMoveStartedAt DateTime? + retiredRegion String? + retiredRegionAt DateTime? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + team Team @relation(fields: [teamId], references: [id], onDelete: Cascade) + apiKeys ApiKey[] + blacklistChecks DomainBlacklistCheck[] } enum ApiPermission { @@ -319,6 +331,7 @@ enum EmailStatus { FAILED CANCELLED SUPPRESSED + HELD } model Email { @@ -663,3 +676,69 @@ model NotificationLog { @@index([teamId, providerId, status]) @@index([createdAt(sort: Desc)]) } + +model AdminAuditLog { + id String @id @default(cuid()) + actorId Int? + actorEmail String? + action String + targetType String + targetId String + metadata Json? + createdAt DateTime @default(now()) + actor User? @relation(fields: [actorId], references: [id], onDelete: SetNull) + + @@index([createdAt(sort: Desc)]) + @@index([targetType, targetId]) + @@index([actorId]) + @@index([action]) +} + +enum BlacklistStatus { + LISTED + CLEAN + ERROR +} + +model DomainBlacklistCheck { + id String @id @default(cuid()) + domainId Int + list String + status BlacklistStatus + returnCode String? + checkedAt DateTime @default(now()) + domain Domain @relation(fields: [domainId], references: [id], onDelete: Cascade) + + @@index([domainId, checkedAt(sort: Desc)]) + @@index([status, checkedAt(sort: Desc)]) +} + +enum SpamVerdict { + FLAG + HOLD +} + +enum SpamReviewDecision { + RELEASED + REJECTED +} + +model SpamScan { + id String @id @default(cuid()) + teamId Int + emailId String? + campaignId String? + score Int + verdict SpamVerdict + hits Json + createdAt DateTime @default(now()) + reviewedById Int? + reviewedAt DateTime? + reviewDecision SpamReviewDecision? + team Team @relation(fields: [teamId], references: [id], onDelete: Cascade) + + @@index([verdict, reviewedAt, createdAt(sort: Desc)]) + @@index([teamId, createdAt(sort: Desc)]) + @@index([emailId]) + @@index([campaignId]) +} diff --git a/apps/web/public/brand/app-icon-1024.png b/apps/web/public/brand/app-icon-1024.png new file mode 100644 index 0000000..4fc53a5 Binary files /dev/null and b/apps/web/public/brand/app-icon-1024.png differ diff --git a/apps/web/public/brand/discord-banner.png b/apps/web/public/brand/discord-banner.png new file mode 100644 index 0000000..4ab1a70 Binary files /dev/null and b/apps/web/public/brand/discord-banner.png differ diff --git a/apps/web/public/brand/discord-emojis/bs_api.png b/apps/web/public/brand/discord-emojis/bs_api.png new file mode 100644 index 0000000..b0c5716 Binary files /dev/null and b/apps/web/public/brand/discord-emojis/bs_api.png differ diff --git a/apps/web/public/brand/discord-emojis/bs_bounced.png b/apps/web/public/brand/discord-emojis/bs_bounced.png new file mode 100644 index 0000000..e6d4241 Binary files /dev/null and b/apps/web/public/brand/discord-emojis/bs_bounced.png differ diff --git a/apps/web/public/brand/discord-emojis/bs_delivered.png b/apps/web/public/brand/discord-emojis/bs_delivered.png new file mode 100644 index 0000000..bb6f4ee Binary files /dev/null and b/apps/web/public/brand/discord-emojis/bs_delivered.png differ diff --git a/apps/web/public/brand/discord-emojis/bs_held.png b/apps/web/public/brand/discord-emojis/bs_held.png new file mode 100644 index 0000000..dc76b1a Binary files /dev/null and b/apps/web/public/brand/discord-emojis/bs_held.png differ diff --git a/apps/web/public/brand/discord-emojis/bs_loading.gif b/apps/web/public/brand/discord-emojis/bs_loading.gif new file mode 100644 index 0000000..c094f27 Binary files /dev/null and b/apps/web/public/brand/discord-emojis/bs_loading.gif differ diff --git a/apps/web/public/brand/discord-emojis/bs_logo.png b/apps/web/public/brand/discord-emojis/bs_logo.png new file mode 100644 index 0000000..d7dc3e5 Binary files /dev/null and b/apps/web/public/brand/discord-emojis/bs_logo.png differ diff --git a/apps/web/public/brand/discord-emojis/bs_mailfly.gif b/apps/web/public/brand/discord-emojis/bs_mailfly.gif new file mode 100644 index 0000000..a4c9e29 Binary files /dev/null and b/apps/web/public/brand/discord-emojis/bs_mailfly.gif differ diff --git a/apps/web/public/brand/discord-emojis/bs_send.png b/apps/web/public/brand/discord-emojis/bs_send.png new file mode 100644 index 0000000..2482355 Binary files /dev/null and b/apps/web/public/brand/discord-emojis/bs_send.png differ diff --git a/apps/web/public/brand/discord-emojis/bs_sending.gif b/apps/web/public/brand/discord-emojis/bs_sending.gif new file mode 100644 index 0000000..f641a46 Binary files /dev/null and b/apps/web/public/brand/discord-emojis/bs_sending.gif differ diff --git a/apps/web/public/brand/discord-emojis/bs_verified.png b/apps/web/public/brand/discord-emojis/bs_verified.png new file mode 100644 index 0000000..0cce940 Binary files /dev/null and b/apps/web/public/brand/discord-emojis/bs_verified.png differ diff --git a/apps/web/public/brand/discord-invite-splash.png b/apps/web/public/brand/discord-invite-splash.png new file mode 100644 index 0000000..475e9d7 Binary files /dev/null and b/apps/web/public/brand/discord-invite-splash.png differ diff --git a/apps/web/public/brand/github-social-preview.png b/apps/web/public/brand/github-social-preview.png new file mode 100644 index 0000000..1bac323 Binary files /dev/null and b/apps/web/public/brand/github-social-preview.png differ diff --git a/apps/web/public/brand/mark-compact.svg b/apps/web/public/brand/mark-compact.svg new file mode 100644 index 0000000..991bf65 --- /dev/null +++ b/apps/web/public/brand/mark-compact.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/web/public/brand/mark-glyph.svg b/apps/web/public/brand/mark-glyph.svg new file mode 100644 index 0000000..b57b9c5 --- /dev/null +++ b/apps/web/public/brand/mark-glyph.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/web/public/brand/mark-mono-black.svg b/apps/web/public/brand/mark-mono-black.svg new file mode 100644 index 0000000..ecffaaa --- /dev/null +++ b/apps/web/public/brand/mark-mono-black.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/web/public/brand/mark-mono-white.svg b/apps/web/public/brand/mark-mono-white.svg new file mode 100644 index 0000000..d8c1128 --- /dev/null +++ b/apps/web/public/brand/mark-mono-white.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/web/public/brand/mark.svg b/apps/web/public/brand/mark.svg new file mode 100644 index 0000000..f41f813 --- /dev/null +++ b/apps/web/public/brand/mark.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/web/public/brand/social-avatar.png b/apps/web/public/brand/social-avatar.png new file mode 100644 index 0000000..8357b7d Binary files /dev/null and b/apps/web/public/brand/social-avatar.png differ diff --git a/apps/web/public/brand/wordmark-dark-tight.png b/apps/web/public/brand/wordmark-dark-tight.png new file mode 100644 index 0000000..855fa0c Binary files /dev/null and b/apps/web/public/brand/wordmark-dark-tight.png differ diff --git a/apps/web/public/brand/wordmark-dark.png b/apps/web/public/brand/wordmark-dark.png new file mode 100644 index 0000000..23c701a Binary files /dev/null and b/apps/web/public/brand/wordmark-dark.png differ diff --git a/apps/web/public/brand/wordmark-light-tight.png b/apps/web/public/brand/wordmark-light-tight.png new file mode 100644 index 0000000..ad92c80 Binary files /dev/null and b/apps/web/public/brand/wordmark-light-tight.png differ diff --git a/apps/web/public/brand/wordmark-light.png b/apps/web/public/brand/wordmark-light.png new file mode 100644 index 0000000..7e018fb Binary files /dev/null and b/apps/web/public/brand/wordmark-light.png differ diff --git a/apps/web/public/brand/x-header.png b/apps/web/public/brand/x-header.png new file mode 100644 index 0000000..a652b00 Binary files /dev/null and b/apps/web/public/brand/x-header.png differ diff --git a/apps/web/public/favicon.ico b/apps/web/public/favicon.ico index 4780abc..ab25de4 100644 Binary files a/apps/web/public/favicon.ico and b/apps/web/public/favicon.ico differ diff --git a/apps/web/public/favicon.svg b/apps/web/public/favicon.svg new file mode 100644 index 0000000..991bf65 --- /dev/null +++ b/apps/web/public/favicon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/web/public/favicon_io/android-chrome-192x192.png b/apps/web/public/favicon_io/android-chrome-192x192.png index 4780abc..c1fd7e4 100644 Binary files a/apps/web/public/favicon_io/android-chrome-192x192.png and b/apps/web/public/favicon_io/android-chrome-192x192.png differ diff --git a/apps/web/public/favicon_io/android-chrome-512x512.png b/apps/web/public/favicon_io/android-chrome-512x512.png index 4780abc..95aec3b 100644 Binary files a/apps/web/public/favicon_io/android-chrome-512x512.png and b/apps/web/public/favicon_io/android-chrome-512x512.png differ diff --git a/apps/web/public/favicon_io/apple-touch-icon.png b/apps/web/public/favicon_io/apple-touch-icon.png index 4780abc..d6b6713 100644 Binary files a/apps/web/public/favicon_io/apple-touch-icon.png and b/apps/web/public/favicon_io/apple-touch-icon.png differ diff --git a/apps/web/public/favicon_io/favicon-16x16.png b/apps/web/public/favicon_io/favicon-16x16.png index 4780abc..135c910 100644 Binary files a/apps/web/public/favicon_io/favicon-16x16.png and b/apps/web/public/favicon_io/favicon-16x16.png differ diff --git a/apps/web/public/favicon_io/favicon-32x32.png b/apps/web/public/favicon_io/favicon-32x32.png index 4780abc..5b5c6a3 100644 Binary files a/apps/web/public/favicon_io/favicon-32x32.png and b/apps/web/public/favicon_io/favicon-32x32.png differ diff --git a/apps/web/public/favicon_io/favicon.ico b/apps/web/public/favicon_io/favicon.ico index 4780abc..ab25de4 100644 Binary files a/apps/web/public/favicon_io/favicon.ico and b/apps/web/public/favicon_io/favicon.ico differ diff --git a/apps/web/public/favicon_io/site.webmanifest b/apps/web/public/favicon_io/site.webmanifest index dd4c4b6..dd16dd0 100644 --- a/apps/web/public/favicon_io/site.webmanifest +++ b/apps/web/public/favicon_io/site.webmanifest @@ -1 +1 @@ -{"name":"ByteSend","short_name":"ByteSend","icons":[{"src":"/android-chrome-192x192.png","sizes":"192x192","type":"image/png"},{"src":"/android-chrome-512x512.png","sizes":"512x512","type":"image/png"}],"theme_color":"#ffffff","background_color":"#ffffff","display":"standalone"} \ No newline at end of file +{"name": "ByteSend", "short_name": "ByteSend", "icons": [{"src": "/favicon_io/android-chrome-192x192.png", "sizes": "192x192", "type": "image/png"}, {"src": "/favicon_io/android-chrome-512x512.png", "sizes": "512x512", "type": "image/png"}], "theme_color": "#05070d", "background_color": "#05070d", "display": "standalone"} diff --git a/apps/web/public/logo-squircle.png b/apps/web/public/logo-squircle.png index 5a09934..725b49b 100644 Binary files a/apps/web/public/logo-squircle.png and b/apps/web/public/logo-squircle.png differ diff --git a/apps/web/public/logo.png b/apps/web/public/logo.png index 4780abc..676eb53 100644 Binary files a/apps/web/public/logo.png and b/apps/web/public/logo.png differ diff --git a/apps/web/public/logo.svg b/apps/web/public/logo.svg index ceffa59..f41f813 100644 --- a/apps/web/public/logo.svg +++ b/apps/web/public/logo.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/apps/web/public/nameplate.png b/apps/web/public/nameplate.png index 22db6a8..7e018fb 100644 Binary files a/apps/web/public/nameplate.png and b/apps/web/public/nameplate.png differ diff --git a/apps/web/scripts/brand/emojis.tsx b/apps/web/scripts/brand/emojis.tsx new file mode 100644 index 0000000..c1fbcc5 --- /dev/null +++ b/apps/web/scripts/brand/emojis.tsx @@ -0,0 +1,226 @@ +import { mkdirSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import type { ReactElement, ReactNode } from "react"; +import { ImageResponse } from "next/og"; +import { PNG } from "pngjs"; +import gifenc from "gifenc"; +import { BRAND_COLORS, BrandMark } from "../../src/lib/brand"; + +// gifenc is CommonJS, so its named exports are only reachable through the default import. +const { GIFEncoder, applyPalette, quantize } = gifenc; + +const OUT_DIR = join(dirname(fileURLToPath(import.meta.url)), "../../public/brand/discord-emojis"); +const SIZE = 128; +// Discord rejects emoji uploads over 256 KB. +const MAX_BYTES = 256 * 1024; + +// GIF alpha is 1-bit, so "off" states use a solid muted tone instead of opacity. +const DIM = "#7d8aa6"; + +const STATUS = { + success: "#16c784", + danger: "#ef4444", + warning: "#f5a524", +} as const; + +function frame(children: ReactNode) { + return ( +
+ {children} +
+ ); +} + +async function renderPng(element: ReactElement) { + const response = new ImageResponse(element, { width: SIZE, height: SIZE }); + return Buffer.from(await response.arrayBuffer()); +} + +function save(name: string, data: Buffer | Uint8Array) { + if (data.length > MAX_BYTES) { + throw new Error(`${name} is ${Math.round(data.length / 1024)} KB, over Discord's 256 KB emoji limit`); + } + mkdirSync(OUT_DIR, { recursive: true }); + writeFileSync(join(OUT_DIR, name), data); + console.log(`wrote ${name} (${Math.round(data.length / 1024)} KB)`); +} + +// GIF transparency is 1-bit, so each frame is quantized with a hard alpha cutoff. +async function renderGif(frames: ReactElement[], delayMs: number) { + const gif = GIFEncoder(); + for (const element of frames) { + const { data } = PNG.sync.read(await renderPng(element)); + const rgba = new Uint8Array(data.buffer, data.byteOffset, data.length); + const palette = quantize(rgba, 256, { format: "rgba4444", oneBitAlpha: true, clearAlpha: true }); + const index = applyPalette(rgba, palette, "rgba4444"); + const transparentIndex = palette.findIndex((color) => color[3] === 0); + gif.writeFrame(index, SIZE, SIZE, { + palette, + delay: delayMs, + transparent: transparentIndex >= 0, + transparentIndex: Math.max(transparentIndex, 0), + dispose: 2, + }); + } + gif.finish(); + return gif.bytes(); +} + +// Satori serializes inline SVG itself and skips fragments and components nested inside , +// so the status emojis are composed from plain element arrays. +function envelopeWithBadge(badgeColor: string, glyph: ReactElement[]) { + return ( + + + + + {glyph} + + ); +} + +const checkGlyph = [ + , +]; +const crossGlyph = [ + , +]; +const alertGlyph = [ + , + , +]; + +function Chevrons({ lit }: { lit: number }) { + const colors = [BRAND_COLORS.blue, BRAND_COLORS.sky, BRAND_COLORS.teal]; + return ( + + {[0, 1, 2].map((i) => ( + + ))} + + ); +} + +function SendingPulse({ step }: { step: number }) { + const outerOn = step >= 6; + const middleOn = step >= 3; + return ( + + + + + + + ); +} + +function FlyingMail({ offset }: { offset: number }) { + const x = offset; + return ( + + + + + + + + ); +} + +async function main() { + save("bs_logo.png", await renderPng(frame())); + save("bs_send.png", await renderPng(frame())); + save( + "bs_api.png", + await renderPng( + frame( + + + + + , + ), + ), + ); + save("bs_delivered.png", await renderPng(frame(envelopeWithBadge(STATUS.success, checkGlyph)))); + save("bs_bounced.png", await renderPng(frame(envelopeWithBadge(STATUS.danger, crossGlyph)))); + save("bs_held.png", await renderPng(frame(envelopeWithBadge(STATUS.warning, alertGlyph)))); + save( + "bs_verified.png", + await renderPng( + frame( + + + + + , + ), + ), + ); + + save( + "bs_sending.gif", + await renderGif( + Array.from({ length: 12 }, (_, step) => frame()), + 90, + ), + ); + save( + "bs_loading.gif", + await renderGif( + [0, 1, 2].map((lit) => frame()), + 180, + ), + ); + save( + "bs_mailfly.gif", + await renderGif( + Array.from({ length: 16 }, (_, i) => frame()), + 55, + ), + ); +} + +await main(); diff --git a/apps/web/scripts/brand/generate.tsx b/apps/web/scripts/brand/generate.tsx new file mode 100644 index 0000000..cb97dcd --- /dev/null +++ b/apps/web/scripts/brand/generate.tsx @@ -0,0 +1,220 @@ +import { mkdirSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import type { ReactElement } from "react"; +import { ImageResponse } from "next/og"; +import { + BRAND_COLORS, + BRAND_MARK_ASPECT, + BRAND_NAME, + BRAND_TAGLINE, + BrandMark, + brandMarkSvgString, + type BrandMarkDetail, +} from "../../src/lib/brand"; + +const PUBLIC_DIR = join(dirname(fileURLToPath(import.meta.url)), "../../public"); + +type Font = { name: string; data: ArrayBuffer; weight: 400 | 600 | 800; style: "normal" }; + +async function loadGoogleFont(family: string, weight: 400 | 600 | 800): Promise { + const css = await (await fetch(`https://fonts.googleapis.com/css2?family=${family}:wght@${weight}`)).text(); + const url = css.match(/src: url\((.+?)\) format\('(opentype|truetype)'\)/)?.[1]; + if (!url) throw new Error(`No TTF for ${family} ${weight}`); + return { name: family, data: await (await fetch(url)).arrayBuffer(), weight, style: "normal" }; +} + +function write(relativePath: string, data: Buffer | string) { + const target = join(PUBLIC_DIR, relativePath); + mkdirSync(dirname(target), { recursive: true }); + writeFileSync(target, data); + console.log("wrote", relativePath); +} + +async function png(element: ReactElement, width: number, height: number, fonts: Font[]) { + const response = new ImageResponse(element, { width, height, fonts }); + return Buffer.from(await response.arrayBuffer()); +} + +// ICO files may embed PNG frames directly; each directory entry points at one frame. +function encodeIco(frames: Array<{ size: number; data: Buffer }>) { + const header = Buffer.alloc(6); + header.writeUInt16LE(0, 0); + header.writeUInt16LE(1, 2); + header.writeUInt16LE(frames.length, 4); + + let offset = 6 + frames.length * 16; + const entries = frames.map(({ size, data }) => { + const entry = Buffer.alloc(16); + entry.writeUInt8(size >= 256 ? 0 : size, 0); + entry.writeUInt8(size >= 256 ? 0 : size, 1); + entry.writeUInt16LE(1, 4); + entry.writeUInt16LE(32, 6); + entry.writeUInt32LE(data.length, 8); + entry.writeUInt32LE(offset, 12); + offset += data.length; + return entry; + }); + + return Buffer.concat([header, ...entries, ...frames.map((frame) => frame.data)]); +} + +function Wordmark({ height, onDark }: { height: number; onDark: boolean }) { + return ( +
+ +
+ Byte + Send +
+
+ ); +} + +function MarkOnly({ size, detail, background, radius = 0, inset = 0.14 }: { + size: number; + detail: BrandMarkDetail; + background?: string; + radius?: number; + inset?: number; +}) { + const markWidth = size * (1 - inset * 2); + return ( +
+ +
+ ); +} + +function Banner({ + width, + height, + align = "center", + showTagline = true, + contentScale = 1, +}: { + width: number; + height: number; + align?: "center" | "right"; + showTagline?: boolean; + contentScale?: number; +}) { + const unit = Math.min(width / 1280, height / 640) * contentScale; + return ( +
+
+ +
+
+ + {showTagline ? ( + {BRAND_TAGLINE} + ) : null} + + bytesend.cloud + +
+
+ {[BRAND_COLORS.ice, BRAND_COLORS.teal, BRAND_COLORS.sky, BRAND_COLORS.blue].map((color) => ( +
+ ))} +
+
+ ); +} + +async function main() { + const fonts = await Promise.all([ + loadGoogleFont("Sora", 400), + loadGoogleFont("Sora", 600), + loadGoogleFont("Sora", 800), + ]); + + write("logo.svg", brandMarkSvgString({ detail: "full" })); + write("favicon.svg", brandMarkSvgString({ detail: "compact" })); + write("brand/mark.svg", brandMarkSvgString({ detail: "full" })); + write("brand/mark-compact.svg", brandMarkSvgString({ detail: "compact" })); + write("brand/mark-glyph.svg", brandMarkSvgString({ detail: "glyph" })); + write("brand/mark-mono-black.svg", brandMarkSvgString({ detail: "full", variant: "mono", monoColor: "#000000" })); + write("brand/mark-mono-white.svg", brandMarkSvgString({ detail: "full", variant: "mono", monoColor: "#ffffff" })); + + write("logo.png", await png(, 1024, 1024, fonts)); + write( + "logo-squircle.png", + await png(, 512, 512, fonts), + ); + write("nameplate.png", await png(
, 1600, 500, fonts)); + write("brand/wordmark-light.png", await png(
, 1600, 500, fonts)); + write("brand/wordmark-dark.png", await png(
, 1600, 500, fonts)); + // Tight crops for places that scale a logo to a fixed height, such as the docs navbar. + write("brand/wordmark-light-tight.png", await png(
, 1200, 220, fonts)); + write("brand/wordmark-dark-tight.png", await png(
, 1200, 220, fonts)); + write("brand/app-icon-1024.png", await png(, 1024, 1024, fonts)); + + write("favicon_io/android-chrome-512x512.png", await png(, 512, 512, fonts)); + write("favicon_io/android-chrome-192x192.png", await png(, 192, 192, fonts)); + write("favicon_io/apple-touch-icon.png", await png(, 180, 180, fonts)); + + const favicon16 = await png(, 16, 16, fonts); + const favicon32 = await png(, 32, 32, fonts); + const favicon48 = await png(, 48, 48, fonts); + write("favicon_io/favicon-16x16.png", favicon16); + write("favicon_io/favicon-32x32.png", favicon32); + const ico = encodeIco([ + { size: 16, data: favicon16 }, + { size: 32, data: favicon32 }, + { size: 48, data: favicon48 }, + ]); + write("favicon.ico", ico); + write("favicon_io/favicon.ico", ico); + + write("brand/github-social-preview.png", await png(, 1280, 640, fonts)); + write("brand/discord-banner.png", await png(, 960, 540, fonts)); + write("brand/discord-invite-splash.png", await png(, 1920, 1080, fonts)); + // X's mobile app zooms the header, crops both sides and overlays buttons in the top corners, + // so the lockup stays small and centred inside the area every client shows. + write("brand/x-header.png", await png(, 1500, 500, fonts)); + write("brand/social-avatar.png", await png(, 400, 400, fonts)); + + console.log(`\n${BRAND_NAME} brand assets generated.`); +} + +await main(); diff --git a/apps/web/scripts/brand/gifenc.d.ts b/apps/web/scripts/brand/gifenc.d.ts new file mode 100644 index 0000000..50f5e0a --- /dev/null +++ b/apps/web/scripts/brand/gifenc.d.ts @@ -0,0 +1,30 @@ +declare module "gifenc" { + type Palette = number[][]; + type Format = "rgb565" | "rgb444" | "rgba4444"; + interface Encoder { + writeFrame( + index: Uint8Array, + width: number, + height: number, + options?: { + palette?: Palette; + delay?: number; + transparent?: boolean; + transparentIndex?: number; + dispose?: number; + }, + ): void; + finish(): void; + bytes(): Uint8Array; + } + const gifenc: { + GIFEncoder(): Encoder; + quantize( + rgba: Uint8Array, + maxColors: number, + options?: { format?: Format; oneBitAlpha?: boolean | number; clearAlpha?: boolean }, + ): Palette; + applyPalette(rgba: Uint8Array, palette: Palette, format?: Format): Uint8Array; + }; + export default gifenc; +} diff --git a/apps/web/scripts/brand/tsconfig.json b/apps/web/scripts/brand/tsconfig.json new file mode 100644 index 0000000..70f97a1 --- /dev/null +++ b/apps/web/scripts/brand/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { "jsx": "react-jsx" }, + "include": ["./**/*", "../../src/lib/brand.tsx", "../../src/lib/og/**/*"] +} diff --git a/apps/web/src/app/(dashboard)/admin/_components/admin-command-search.tsx b/apps/web/src/app/(dashboard)/admin/_components/admin-command-search.tsx new file mode 100644 index 0000000..ff83ceb --- /dev/null +++ b/apps/web/src/app/(dashboard)/admin/_components/admin-command-search.tsx @@ -0,0 +1,160 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { useRouter } from "next/navigation"; +import { useDebounce } from "use-debounce"; +import { Building2, Globe, Mail, Search, User } from "lucide-react"; +import { + Command, + CommandEmpty, + CommandGroup, + CommandInput, + CommandItem, + CommandList, +} from "@bytesend/ui/src/command"; +import { Dialog, DialogContent, DialogTitle } from "@bytesend/ui/src/dialog"; +import { api } from "~/trpc/react"; +import { StatusPill } from "./status-pill"; + +const MIN_QUERY_LENGTH = 2; + +export function AdminCommandSearch() { + const router = useRouter(); + const [open, setOpen] = useState(false); + const [input, setInput] = useState(""); + const [query] = useDebounce(input.trim(), 200); + + useEffect(() => { + const onKeyDown = (event: KeyboardEvent) => { + if (event.key.toLowerCase() === "k" && (event.metaKey || event.ctrlKey)) { + event.preventDefault(); + setOpen((value) => !value); + } + }; + window.addEventListener("keydown", onKeyDown); + return () => window.removeEventListener("keydown", onKeyDown); + }, []); + + const searchQuery = api.admin.globalSearch.useQuery( + { query }, + { enabled: open && query.length >= MIN_QUERY_LENGTH, placeholderData: (prev) => prev, staleTime: 15_000 }, + ); + const results = query.length >= MIN_QUERY_LENGTH ? searchQuery.data : undefined; + const hasResults = + !!results && + results.users.length + results.teams.length + results.domains.length + results.emails.length > 0; + + const go = (href: string) => { + setOpen(false); + setInput(""); + router.push(href); + }; + + return ( + <> + + + { + setOpen(next); + if (!next) setInput(""); + }} + > + + Admin search + + + + {query.length < MIN_QUERY_LENGTH ? ( +

+ Type at least {MIN_QUERY_LENGTH} characters. Recipient addresses search the last 30 days of mail. +

+ ) : searchQuery.isLoading ? ( +

Searching…

+ ) : ( + No matches for “{query}” + )} + + {results && hasResults ? ( + <> + {results.users.length ? ( + + {results.users.map((user) => ( + go(`/admin/users/${user.id}`)}> + + {user.email ?? user.name} + {user.isBanned ? Banned : null} + #{user.id} + + ))} + + ) : null} + {results.teams.length ? ( + + {results.teams.map((team) => ( + go(`/admin/teams/${team.id}`)}> + + {team.name} + {team.isBlocked ? Blocked : null} + {team.plan} + + ))} + + ) : null} + {results.domains.length ? ( + + {results.domains.map((domain) => ( + go(`/admin/teams/${domain.team.id}`)} + > + + {domain.name} + {domain.team.name} + + ))} + + ) : null} + {results.emails.length ? ( + + {results.emails.map((email) => ( + go(`/admin/emails?id=${email.id}`)} + > + + {email.subject || "(no subject)"} + {email.latestStatus.toLowerCase()} + + ))} + + ) : null} + + ) : null} +
+
+
+
+ + ); +} diff --git a/apps/web/src/app/(dashboard)/admin/_components/admin-nav.tsx b/apps/web/src/app/(dashboard)/admin/_components/admin-nav.tsx new file mode 100644 index 0000000..45f13ee --- /dev/null +++ b/apps/web/src/app/(dashboard)/admin/_components/admin-nav.tsx @@ -0,0 +1,119 @@ +"use client"; + +import Link from "next/link"; +import { usePathname } from "next/navigation"; +import type { LucideIcon } from "lucide-react"; +import { + Activity, + Building2, + CreditCard, + Globe, + LayoutDashboard, + Mail, + MailWarning, + ScrollText, + Server, + ShieldAlert, + ShieldBan, + Users, + Webhook, +} from "lucide-react"; +import { cn } from "@bytesend/ui/lib/utils"; +import { isCloud } from "~/utils/common"; + +type AdminNavItem = { + href: string; + label: string; + icon: LucideIcon; + cloudOnly?: boolean; + requiresAdminFlag?: boolean; +}; + +type AdminNavGroup = { label?: string; items: AdminNavItem[] }; + +const NAV_GROUPS: AdminNavGroup[] = [ + { items: [{ href: "/admin", label: "Overview", icon: LayoutDashboard }] }, + { + label: "Platform", + items: [ + { href: "/admin/users", label: "Users", icon: Users, cloudOnly: true, requiresAdminFlag: true }, + { href: "/admin/teams", label: "Teams", icon: Building2, cloudOnly: true }, + { href: "/admin/domains", label: "Domains", icon: Globe, cloudOnly: true }, + { href: "/admin/emails", label: "Emails", icon: Mail }, + ], + }, + { + label: "Health", + items: [ + { href: "/admin/email-analytics", label: "Email analytics", icon: Activity, cloudOnly: true }, + { href: "/admin/deliverability", label: "Deliverability", icon: ShieldAlert }, + { href: "/admin/blacklists", label: "Blacklists", icon: ShieldBan, cloudOnly: true }, + { href: "/admin/spam", label: "Spam review", icon: MailWarning }, + ], + }, + { + label: "Business", + items: [{ href: "/admin/billing", label: "Billing", icon: CreditCard, cloudOnly: true }], + }, + { + label: "Infrastructure", + items: [ + { href: "/admin/ses", label: "SES regions", icon: Server }, + { href: "/admin/webhooks", label: "Webhooks", icon: Webhook, cloudOnly: true }, + ], + }, + { items: [{ href: "/admin/audit", label: "Audit log", icon: ScrollText }] }, +]; + +function isActivePath(pathname: string, href: string) { + return href === "/admin" ? pathname === href : pathname === href || pathname.startsWith(`${href}/`); +} + +export function AdminNav({ isAdmin }: { isAdmin: boolean }) { + const pathname = usePathname(); + const cloud = isCloud(); + + const groups = NAV_GROUPS.map((group) => ({ + ...group, + items: group.items.filter( + (item) => (!item.cloudOnly || cloud) && (!item.requiresAdminFlag || isAdmin), + ), + })).filter((group) => group.items.length > 0); + + return ( + + ); +} diff --git a/apps/web/src/app/(dashboard)/admin/_components/admin-page-header.tsx b/apps/web/src/app/(dashboard)/admin/_components/admin-page-header.tsx new file mode 100644 index 0000000..7fedb7e --- /dev/null +++ b/apps/web/src/app/(dashboard)/admin/_components/admin-page-header.tsx @@ -0,0 +1,23 @@ +import type { ReactNode } from "react"; + +export function AdminPageHeader({ + title, + description, + actions, +}: { + title: string; + description?: string; + actions?: ReactNode; +}) { + return ( +
+
+

{title}

+ {description ? ( +

{description}

+ ) : null} +
+ {actions ?
{actions}
: null} +
+ ); +} diff --git a/apps/web/src/app/(dashboard)/admin/_components/audit-log-table.tsx b/apps/web/src/app/(dashboard)/admin/_components/audit-log-table.tsx new file mode 100644 index 0000000..bacd17e --- /dev/null +++ b/apps/web/src/app/(dashboard)/admin/_components/audit-log-table.tsx @@ -0,0 +1,127 @@ +"use client"; + +import { format, formatDistanceToNow } from "date-fns"; +import { Button } from "@bytesend/ui/src/button"; +import { Skeleton } from "@bytesend/ui/src/skeleton"; +import { + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, +} from "@bytesend/ui/src/table"; +import { api } from "~/trpc/react"; +import { adminAuditActionLabel, type AdminAuditTargetType } from "~/lib/constants/admin-audit"; +import { AuditMetadata } from "./audit-metadata"; +import { StatusPill, type StatusTone } from "./status-pill"; + +function actionTone(action: string): StatusTone { + if (/\.(delete|ban|block)$/.test(action)) return "destructive"; + if (/\.(unban|unblock|force_verify)$/.test(action)) return "warning"; + return "muted"; +} + +export function AuditLogTable({ + query, + action, + targetType, + targetId, + pageSize = 50, + showTarget = true, + emptyLabel = "No admin actions recorded yet", +}: { + query?: string; + action?: string; + targetType?: AdminAuditTargetType; + targetId?: string; + pageSize?: number; + showTarget?: boolean; + emptyLabel?: string; +}) { + const auditQuery = api.admin.listAuditLog.useInfiniteQuery( + { limit: pageSize, query, action, targetType, targetId }, + { getNextPageParam: (lastPage) => lastPage.nextCursor }, + ); + + const entries = auditQuery.data?.pages.flatMap((page) => page.entries) ?? []; + const columnCount = showTarget ? 5 : 4; + + return ( +
+
+
+ + + + When + Admin + Action + {showTarget ? Target : null} + Details + + + + {auditQuery.isLoading ? ( + Array.from({ length: 4 }, (_, i) => ( + + {Array.from({ length: columnCount }, (__, j) => ( + + + + ))} + + )) + ) : entries.length === 0 ? ( + + + {emptyLabel} + + + ) : ( + entries.map((entry) => ( + + + + {formatDistanceToNow(entry.createdAt, { addSuffix: true })} + + + + {entry.actor?.email ?? entry.actorEmail ?? ( + Deleted user + )} + + + {adminAuditActionLabel(entry.action)} + + {showTarget ? ( + + {entry.targetType} #{entry.targetId} + + ) : null} + + + + + )) + )} + +
+
+
+ + {auditQuery.hasNextPage ? ( +
+ +
+ ) : null} +
+ ); +} diff --git a/apps/web/src/app/(dashboard)/admin/_components/audit-metadata.tsx b/apps/web/src/app/(dashboard)/admin/_components/audit-metadata.tsx new file mode 100644 index 0000000..c86101d --- /dev/null +++ b/apps/web/src/app/(dashboard)/admin/_components/audit-metadata.tsx @@ -0,0 +1,45 @@ +type Change = { from: unknown; to: unknown }; + +function formatValue(value: unknown) { + if (value === null || value === undefined) return "—"; + if (typeof value === "boolean") return value ? "yes" : "no"; + if (typeof value === "number") return value === -1 ? "unlimited" : value.toLocaleString(); + return String(value); +} + +function isChangeMap(value: unknown): value is Record { + return ( + typeof value === "object" && + value !== null && + Object.values(value).every((v) => typeof v === "object" && v !== null && "from" in v && "to" in v) + ); +} + +export function AuditMetadata({ metadata }: { metadata: unknown }) { + if (!metadata || typeof metadata !== "object") { + return —; + } + + const { changes, ...rest } = metadata as Record; + + return ( +
+ {isChangeMap(changes) + ? Object.entries(changes).map(([field, change]) => ( +

+ {field}{" "} + + {formatValue(change.from)} + {" "} + → {formatValue(change.to)} +

+ )) + : null} + {Object.entries(rest).map(([key, value]) => ( +

+ {key} {formatValue(value)} +

+ ))} +
+ ); +} diff --git a/apps/web/src/app/(dashboard)/admin/_components/block-team-dialog.tsx b/apps/web/src/app/(dashboard)/admin/_components/block-team-dialog.tsx new file mode 100644 index 0000000..bd5c1c2 --- /dev/null +++ b/apps/web/src/app/(dashboard)/admin/_components/block-team-dialog.tsx @@ -0,0 +1,97 @@ +"use client"; + +import { useState } from "react"; +import { Button } from "@bytesend/ui/src/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@bytesend/ui/src/dialog"; +import { Textarea } from "@bytesend/ui/src/textarea"; +import { toast } from "@bytesend/ui/src/toaster"; +import { api } from "~/trpc/react"; + +export function BlockTeamDialog({ + team, + open, + onOpenChange, +}: { + team: { id: number; name: string; isBlocked: boolean } | null; + open: boolean; + onOpenChange: (open: boolean) => void; +}) { + const [reason, setReason] = useState(""); + const utils = api.useUtils(); + const willBlock = !team?.isBlocked; + + const mutation = api.admin.setTeamBlocked.useMutation({ + onSuccess: async (updated) => { + toast.success(updated.isBlocked ? `${updated.name} blocked` : `${updated.name} unblocked`); + setReason(""); + onOpenChange(false); + await Promise.all([ + utils.admin.listDeliverability.invalidate(), + utils.admin.getOverview.invalidate(), + utils.admin.listAuditLog.invalidate(), + utils.admin.listTeams.invalidate(), + utils.admin.getTeamDetail.invalidate({ teamId: updated.id }), + ]); + }, + onError: (error) => toast.error("Could not update team", { description: error.message }), + }); + + return ( + { + if (!next) setReason(""); + onOpenChange(next); + }} + > + + + + {willBlock ? "Block" : "Unblock"} {team?.name} + + + {willBlock + ? "All sending for this team will be rejected until it is unblocked. The reason is saved to the audit log." + : "The team will be able to send again, subject to its normal limits. The reason is saved to the audit log."} + + +
{ + event.preventDefault(); + if (!team) return; + mutation.mutate({ teamId: team.id, isBlocked: willBlock, reason }); + }} + > +