From 1f96960088e805e4d8bb14556693268a974f08b5 Mon Sep 17 00:00:00 2001 From: TheRealToxicDev Date: Sat, 9 May 2026 07:54:56 -0600 Subject: [PATCH 1/9] updated random stuff --- README.md | 12 ++++---- apps/docs/README.md | 38 +++++++++++-------------- apps/docs/docs.json | 6 ++-- apps/docs/get-started/local.mdx | 6 ++-- apps/docs/get-started/set-up-docker.mdx | 2 +- apps/docs/self-hosting/overview.mdx | 4 +-- 6 files changed, 32 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index d2ca2b8..293d18e 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ ![ByteSend](./apps/web/public/nameplate.png) -**Open-source email infrastructure that works.** REST API, SMTP relay, campaigns, contact management, and real-time webhooks self-hostable or managed on [bytesend.cloud](https://bytesend.cloud). +**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/xqkqzVRC4S) @@ -12,13 +12,13 @@ The fastest way to get started is the managed cloud at [bytesend.cloud](https:// | Plan | Price | Emails/month | Domains | Contacts | |---|---|---|---|---| -| **Free** | CA$0 | 5,000 | 3 | 500 | -| **Hobby** | CA$5/mo | 15,000 | 5 | 2,000 | -| **Lite** | CA$10/mo | 50,000 | 10 | 10,000 | +| **Free** | CA$0 | 12,500 | 2 | 100 | +| **Hobby** | CA$5/mo | 25,000 | 4 | 200 | +| **Lite** | CA$10/mo | 50,000 | 6 | 300 | | **Professional** | CA$30/mo | 150,000 | 100 | 1,000,000 | | **Lifetime** | CA$60 once | Unlimited | 500 | 10,000,000 | -Hobby and above include marketing campaigns and overage billing. Professional and Lifetime include advanced analytics and priority support. +Hobby and above include marketing campaigns and usage-based overage billing. Professional and Lifetime include advanced analytics and priority support. --- @@ -27,7 +27,7 @@ Hobby and above include marketing campaigns and overage billing. Professional an ByteSend is fully self-hostable under the AGPL-3.0 license. ```bash -git clone https://github.com/NodeByteHosting/bytesend.git +git clone https://github.com/NodeByteLTD/ByteSend.git 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 diff --git a/apps/docs/README.md b/apps/docs/README.md index 063d3f8..3495426 100644 --- a/apps/docs/README.md +++ b/apps/docs/README.md @@ -1,32 +1,28 @@ -# Mintlify Starter Kit +# ByteSend Docs -Click on `Use this template` to copy the Mintlify starter kit. The starter kit contains examples including +Documentation for ByteSend cloud and self-hosted users. -- Guide pages -- Navigation -- Customizations -- API Reference pages -- Use of popular components +- Cloud dashboard: https://bytesend.cloud +- Docs: https://docs.bytesend.cloud +- API reference: https://docs.bytesend.cloud/api-reference/introduction -### Development +## Local development -Install the [Mintlify CLI](https://www.npmjs.com/package/mintlify) to preview the documentation changes locally. To install, use the following command +From the repository root: +```bash +pnpm install +pnpm dev:docs ``` -npm i -g mintlify -``` - -Run the following command at the root of your documentation (where mint.json is) -``` -mintlify dev -``` +This starts the docs locally using Mintlify. -### Publishing Changes +## Editing guidelines -Install our GitHub App to auto propagate changes from your repo to your deployment. Changes will be deployed to production automatically after pushing to the default branch. Find the link to install on your dashboard. +- Use `https://bytesend.cloud` for cloud-hosted links. +- Prefer absolute links for dashboard paths in docs examples. +- Keep API examples aligned with `https://bytesend.cloud/api`. -#### Troubleshooting +## Deployment -- Mintlify dev isn't running - Run `mintlify install` it'll re-install dependencies. -- Page loads as a 404 - Make sure you are running in a folder with `mint.json` +Docs are deployed from this repository. Push changes to the default branch after review. diff --git a/apps/docs/docs.json b/apps/docs/docs.json index 133dd95..62a2bcc 100644 --- a/apps/docs/docs.json +++ b/apps/docs/docs.json @@ -147,7 +147,7 @@ "anchors": [ { "anchor": "GitHub", - "href": "https://github.com/NodeByteHosting", + "href": "https://github.com/NodeByteLTD/ByteSend", "icon": "github" }, { @@ -177,7 +177,7 @@ "display": "interactive" }, "mdx": { - "server": "https://mintlify.com/api", + "server": "https://bytesend.cloud/api", "auth": { "method": "bearer" } @@ -199,7 +199,7 @@ "footer": { "socials": { "x": "https://x.com/TryByteSend", - "github": "https://github.com/NodeByteHosting" + "github": "https://github.com/NodeByteLTD/ByteSend" } }, "contextual": { diff --git a/apps/docs/get-started/local.mdx b/apps/docs/get-started/local.mdx index 036220d..88c8528 100644 --- a/apps/docs/get-started/local.mdx +++ b/apps/docs/get-started/local.mdx @@ -32,12 +32,12 @@ packages/ - Click the **Fork** button on [GitHub](https://github.com/NodeByteHosting/bytesend) to fork the repo. + Click the **Fork** button on [GitHub](https://github.com/NodeByteLTD/ByteSend) to fork the repo. ```bash - git clone https://github.com/your-username/bytesend.git - cd bytesend + git clone https://github.com/your-username/ByteSend.git + cd ByteSend ``` diff --git a/apps/docs/get-started/set-up-docker.mdx b/apps/docs/get-started/set-up-docker.mdx index 8b6363b..0f6eb92 100644 --- a/apps/docs/get-started/set-up-docker.mdx +++ b/apps/docs/get-started/set-up-docker.mdx @@ -18,7 +18,7 @@ This guide covers the fastest path to a running ByteSend instance using Docker C ## 1. Clone the repository ```bash -git clone https://github.com/NodeByteHosting/bytesend.git +git clone https://github.com/NodeByteLTD/ByteSend.git cd bytesend ``` diff --git a/apps/docs/self-hosting/overview.mdx b/apps/docs/self-hosting/overview.mdx index 39475a2..30fd26d 100644 --- a/apps/docs/self-hosting/overview.mdx +++ b/apps/docs/self-hosting/overview.mdx @@ -40,7 +40,7 @@ newgrp docker ### 2. Clone the repository ```bash -git clone https://github.com/NodeByteHosting/bytesend.git +git clone https://github.com/NodeByteLTD/ByteSend.git cd bytesend ``` @@ -157,7 +157,7 @@ sudo systemctl start redis-server ### 4. Clone and install ```bash -git clone https://github.com/NodeByteHosting/bytesend.git +git clone https://github.com/NodeByteLTD/ByteSend.git cd bytesend pnpm install ``` From b0eebd137aaf514b6177bb65904e25b284284dd7 Mon Sep 17 00:00:00 2001 From: TheRealToxicDev Date: Sat, 9 May 2026 08:06:45 -0600 Subject: [PATCH 2/9] more stuff --- apps/docs/self-hosting/smtp-server.mdx | 33 +- apps/smtp-server | 1 - apps/smtp-server/.dockerignore | 34 ++ apps/smtp-server/.env.example | 20 + apps/smtp-server/.github/CODEOWNERS | 1 + apps/smtp-server/.github/FUNDING.yml | 4 + apps/smtp-server/.gitignore | 50 ++ apps/smtp-server/CHANGELOG.md | 36 ++ apps/smtp-server/Dockerfile | 35 ++ apps/smtp-server/LICENSE | 660 +++++++++++++++++++++++++ apps/smtp-server/README.md | 281 +++++++++++ apps/smtp-server/SECURITY.md | 182 +++++++ apps/smtp-server/docker-compose.yml | 28 ++ apps/smtp-server/package.json | 28 ++ apps/smtp-server/src/server.ts | 214 ++++++++ apps/smtp-server/src/usage.js | 30 ++ apps/smtp-server/tsconfig.json | 24 + apps/smtp-server/tsup.config.ts | 13 + 18 files changed, 1656 insertions(+), 18 deletions(-) delete mode 160000 apps/smtp-server create mode 100644 apps/smtp-server/.dockerignore create mode 100644 apps/smtp-server/.env.example create mode 100644 apps/smtp-server/.github/CODEOWNERS create mode 100644 apps/smtp-server/.github/FUNDING.yml create mode 100644 apps/smtp-server/.gitignore create mode 100644 apps/smtp-server/CHANGELOG.md create mode 100644 apps/smtp-server/Dockerfile create mode 100644 apps/smtp-server/LICENSE create mode 100644 apps/smtp-server/README.md create mode 100644 apps/smtp-server/SECURITY.md create mode 100644 apps/smtp-server/docker-compose.yml create mode 100644 apps/smtp-server/package.json create mode 100644 apps/smtp-server/src/server.ts create mode 100644 apps/smtp-server/src/usage.js create mode 100644 apps/smtp-server/tsconfig.json create mode 100644 apps/smtp-server/tsup.config.ts diff --git a/apps/docs/self-hosting/smtp-server.mdx b/apps/docs/self-hosting/smtp-server.mdx index 1a18c20..b26811b 100644 --- a/apps/docs/self-hosting/smtp-server.mdx +++ b/apps/docs/self-hosting/smtp-server.mdx @@ -3,9 +3,9 @@ title: ByteSend SMTP Server description: "An end-to-end guide on how to self-host the ByteSend SMTP Server." --- -The ByteSend SMTP Server is an independent, lightweight Node.js application that forwards incoming SMTP connections to the ByteSend API. It runs separately from the main ByteSend application and can be deployed on the same host or an entirely different machine. +The ByteSend SMTP Server is a lightweight Node.js application inside the ByteSend monorepo that forwards incoming SMTP connections to the ByteSend API. It can be deployed on the same host as ByteSend or on a separate machine. -**Repository:** [github.com/NodeByteHosting/ByteSend-SMTP](https://github.com/NodeByteHosting/ByteSend-SMTP) +**Source path:** [`apps/smtp-server`](https://github.com/NodeByteLTD/ByteSend/tree/main/apps/smtp-server) --- @@ -62,10 +62,10 @@ The server supports two TLS configurations: #### Quick Start -1. **Clone the ByteSend SMTP repository:** +1. **Clone the ByteSend repository:** ```bash - git clone https://github.com/NodeByteHosting/ByteSend-SMTP.git - cd ByteSend-SMTP + git clone https://github.com/NodeByteLTD/ByteSend.git + cd ByteSend/apps/smtp-server ``` 2. **Set up environment variables:** @@ -145,8 +145,8 @@ The server supports two TLS configurations: 1. **Clone and install:** ```bash - git clone https://github.com/NodeByteHosting/ByteSend-SMTP.git - cd ByteSend-SMTP + git clone https://github.com/NodeByteLTD/ByteSend.git + cd ByteSend/apps/smtp-server npm install ``` @@ -303,21 +303,21 @@ Save as `/etc/systemd/system/bytesend-smtp.service`: ```ini [Unit] Description=ByteSend SMTP Server -Documentation=https://github.com/NodeByteHosting/ByteSend-SMTP +Documentation=https://github.com/NodeByteLTD/ByteSend/tree/main/apps/smtp-server After=network.target [Service] Type=simple User=smtp -WorkingDirectory=/opt/bytesend-smtp -ExecStart=/usr/bin/node /opt/bytesend-smtp/dist/server.js +WorkingDirectory=/opt/bytesend-smtp/apps/smtp-server +ExecStart=/usr/bin/node /opt/bytesend-smtp/apps/smtp-server/dist/server.js Restart=on-failure RestartSec=10 StandardOutput=journal StandardError=journal # Load environment from .env file (optional) -EnvironmentFile=-/opt/bytesend-smtp/.env +EnvironmentFile=-/opt/bytesend-smtp/apps/smtp-server/.env # Or set directly (override .env if both exist): Environment="NODE_ENV=production" @@ -354,13 +354,12 @@ sudo chown smtp:smtp /opt/bytesend-smtp/logs # Clone and build cd /opt/bytesend-smtp -sudo -u smtp HOME=/opt/bytesend-smtp git clone https://github.com/NodeByteHosting/ByteSend-SMTP.git . -sudo -u smtp HOME=/opt/bytesend-smtp npm install -sudo -u smtp HOME=/opt/bytesend-smtp npm run build +sudo -u smtp HOME=/opt/bytesend-smtp git clone https://github.com/NodeByteLTD/ByteSend.git . +sudo -u smtp HOME=/opt/bytesend-smtp bash -lc "cd /opt/bytesend-smtp/apps/smtp-server && npm install && npm run build" # (Optional) Copy and configure .env file -sudo -u smtp cp .env.example .env -sudo nano /opt/bytesend-smtp/.env # Edit with your settings +sudo -u smtp cp /opt/bytesend-smtp/apps/smtp-server/.env.example /opt/bytesend-smtp/apps/smtp-server/.env +sudo nano /opt/bytesend-smtp/apps/smtp-server/.env # Edit with your settings ``` The `HOME=/opt/bytesend-smtp` prefix is needed if Node.js is installed via snap, which restricts home directory access to `/home`. If you get "home directories outside of /home needs configuration", use this workaround or install Node.js via `apt` or `nvm` instead. @@ -485,7 +484,7 @@ For high-volume deployments, consider: ## Support & Issues For bugs, feature requests, or questions: -- **GitHub Issues:** [github.com/NodeByteHosting/ByteSend-SMTP](https://github.com/NodeByteHosting/ByteSend-SMTP) +- **GitHub Issues:** [github.com/NodeByteLTD/ByteSend/issues](https://github.com/NodeByteLTD/ByteSend/issues) - **ByteSend Support:** [Contact us](https://bytesend.cloud/support) diff --git a/apps/smtp-server b/apps/smtp-server deleted file mode 160000 index ad1f458..0000000 --- a/apps/smtp-server +++ /dev/null @@ -1 +0,0 @@ -Subproject commit ad1f458992d8acd424e529e9c3079141de7f05e9 diff --git a/apps/smtp-server/.dockerignore b/apps/smtp-server/.dockerignore new file mode 100644 index 0000000..9687261 --- /dev/null +++ b/apps/smtp-server/.dockerignore @@ -0,0 +1,34 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +node_modules +.pnp +.pnp.js + + + +# next.js +.next/ +out/ +build + +# misc +.DS_Store + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# local env files +.env +.env.local +.env.development.local +.env.test.local +.env.production.local + +# turbo +.turbo + +# vercel +.vercel \ No newline at end of file diff --git a/apps/smtp-server/.env.example b/apps/smtp-server/.env.example new file mode 100644 index 0000000..01470c7 --- /dev/null +++ b/apps/smtp-server/.env.example @@ -0,0 +1,20 @@ +# SMTP Server Configuration +# Copy this file to .env and update values for your deployment + +# Node environment +NODE_ENV=production + +# SMTP authentication username +SMTP_AUTH_USERNAME=bytesend + +# Base URL for ByteSend (used in SMTP responses and forwarding) +BYTESEND_BASE_URL=https://bytesend.cloud + +# TLS Mode for SMTP connections +# 'none' - Plain SMTP, suitable when behind a reverse proxy (nginx, Traefik) +# 'manual' - Server handles TLS directly; requires SMTP_TLS_CERT_PATH and SMTP_TLS_KEY_PATH +SMTP_TLS_MODE=none + +# TLS certificate and key paths (only used when SMTP_TLS_MODE=manual) +# SMTP_TLS_CERT_PATH=/certs/fullchain.pem +# SMTP_TLS_KEY_PATH=/certs/privkey.pem diff --git a/apps/smtp-server/.github/CODEOWNERS b/apps/smtp-server/.github/CODEOWNERS new file mode 100644 index 0000000..0682084 --- /dev/null +++ b/apps/smtp-server/.github/CODEOWNERS @@ -0,0 +1 @@ +* @CodeMeAPixel \ No newline at end of file diff --git a/apps/smtp-server/.github/FUNDING.yml b/apps/smtp-server/.github/FUNDING.yml new file mode 100644 index 0000000..c599279 --- /dev/null +++ b/apps/smtp-server/.github/FUNDING.yml @@ -0,0 +1,4 @@ +# These are supported funding model platforms + +github: ['CodeMeAPixel', 'NodeByteHosting'] +open_collective: nodebyte diff --git a/apps/smtp-server/.gitignore b/apps/smtp-server/.gitignore new file mode 100644 index 0000000..eb4071b --- /dev/null +++ b/apps/smtp-server/.gitignore @@ -0,0 +1,50 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# Dependencies +node_modules +.pnp +.pnp.js + +# Local env files +.env +.env.local +.env.development.local +.env.test.local +.env.production.local +.env.selfhost +.docs +.docker +.references + +# Testing +coverage +.idea + +# Turbo +.turbo + +# Vercel +.vercel + +# Build Outputs +.next/ +out/ +build +dist + + +# Debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Misc +.DS_Store +*.pem +prod_db.tar + +bin +__pycache__ +memory-profiles +memory-baseline.json +memory-analysis-report.html \ No newline at end of file diff --git a/apps/smtp-server/CHANGELOG.md b/apps/smtp-server/CHANGELOG.md new file mode 100644 index 0000000..4941ae7 --- /dev/null +++ b/apps/smtp-server/CHANGELOG.md @@ -0,0 +1,36 @@ +# Changelog + +All notable changes to the ByteSend SMTP Server project are documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +--- + +## [Unreleased] + + +## [1.0.0] - 2026-04-07 + +### Added +- SMTP server supporting ports 25 (SMT), 587 (submission), 465 (SMTPS) +- Two TLS modes: + - `none` — Plain SMTP (intended for use behind reverse proxy) + - `manual` — Server handles TLS directly with certificate files +- API key-based authentication using ByteSend API credentials +- Automatic email forwarding to ByteSend API endpoints +- Support for both implicit TLS (SMTPS) and opportunistic TLS (STARTTLS) +- Support for custom SMTP auth username via `SMTP_AUTH_USERNAME` environment variable +- Hot-reload functionality for TLS certificates (zero-downtime renewal) +- Structured logging with JSON output to stdout (systemd/Docker compatible) +- Environment variable validation with clear error messages + +### Changed +- Improved STARTTLS handling to prevent downgrade attacks +- Enhanced error messages for certificate loading failures + +### Fixed +- Proper cleanup of connections on server shutdown +- File watcher edge cases during certificate renewal + +### Security +- Added security policy and vulnerability disclosure guidelines diff --git a/apps/smtp-server/Dockerfile b/apps/smtp-server/Dockerfile new file mode 100644 index 0000000..15c7d9b --- /dev/null +++ b/apps/smtp-server/Dockerfile @@ -0,0 +1,35 @@ +FROM node:20.19-alpine3.20 AS base +ENV PNPM_HOME="/pnpm" +ENV PATH="$PNPM_HOME:$PATH" + +RUN corepack enable +RUN corepack prepare pnpm@latest --activate + +FROM base AS builder +RUN apk add --no-cache libc6-compat +WORKDIR /app + +COPY package.json pnpm-lock.yaml ./ +RUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm install --frozen-lockfile + +# Build the SMTP server +COPY src ./src +COPY tsconfig.json tsup.config.ts ./ +RUN pnpm run build + +FROM base AS runner +RUN apk add --no-cache libc6-compat +WORKDIR /app + +COPY --from=builder /app/dist ./dist +COPY --from=builder /app/node_modules ./node_modules + +# Expose SMTP ports +# 25: SMTP (unencrypted) +# 587: Submission (STARTTLS) +# 465: SMTPS (implicit SSL/TLS) +# 2587: Alternative submission port +# 2465: Alternative SMTPS port +EXPOSE 25 465 587 2465 2587 + +CMD ["node", "apps/smtp-server/dist/server.js"] diff --git a/apps/smtp-server/LICENSE b/apps/smtp-server/LICENSE new file mode 100644 index 0000000..f53cd9d --- /dev/null +++ b/apps/smtp-server/LICENSE @@ -0,0 +1,660 @@ +GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. +Everyone is permitted to copy and distribute verbatim copies +of this license document, but changing it is not allowed. + + Preamble + +The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + +When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + +Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + +A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + +The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + +An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + +The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + +0. Definitions. + +"This License" refers to version 3 of the GNU Affero General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based +on the Program. + +To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + +1. Source Code. + +The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + +A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + +The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + +The Corresponding Source for a work in source code form is that +same work. + +2. Basic Permissions. + +All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. + +No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + +4. Conveying Verbatim Copies. + +You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. + +You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + +a) The work must carry prominent notices stating that you modified +it, and giving a relevant date. + +b) The work must carry prominent notices stating that it is +released under this License and any conditions added under section +7. This requirement modifies the requirement in section 4 to +"keep intact all notices". + +c) You must license the entire work, as a whole, under this +License to anyone who comes into possession of a copy. This +License will therefore apply, along with any applicable section 7 +additional terms, to the whole of the work, and all its parts, +regardless of how they are packaged. This License gives no +permission to license the work in any other way, but it does not +invalidate such permission if you have separately received it. + +d) If the work has interactive user interfaces, each must display +Appropriate Legal Notices; however, if the Program has interactive +interfaces that do not display Appropriate Legal Notices, your +work need not make them do so. + +A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + +6. Conveying Non-Source Forms. + +You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + +a) Convey the object code in, or embodied in, a physical product +(including a physical distribution medium), accompanied by the +Corresponding Source fixed on a durable physical medium +customarily used for software interchange. + +b) Convey the object code in, or embodied in, a physical product +(including a physical distribution medium), accompanied by a +written offer, valid for at least three years and valid for as +long as you offer spare parts or customer support for that product +model, to give anyone who possesses the object code either (1) a +copy of the Corresponding Source for all the software in the +product that is covered by this License, on a durable physical +medium customarily used for software interchange, for a price no +more than your reasonable cost of physically performing this +conveying of source, or (2) access to copy the +Corresponding Source from a network server at no charge. + +c) Convey individual copies of the object code with a copy of the +written offer to provide the Corresponding Source. This +alternative is allowed only occasionally and noncommercially, and +only if you received the object code with such an offer, in accord +with subsection 6b. + +d) Convey the object code by offering access from a designated +place (gratis or for a charge), and offer equivalent access to the +Corresponding Source in the same way through the same place at no +further charge. You need not require recipients to copy the +Corresponding Source along with the object code. If the place to +copy the object code is a network server, the Corresponding Source +may be on a different server (operated by you or a third party) +that supports equivalent copying facilities, provided you maintain +clear directions next to the object code saying where to find the +Corresponding Source. Regardless of what server hosts the +Corresponding Source, you remain obligated to ensure that it is +available for as long as needed to satisfy these requirements. + +e) Convey the object code using peer-to-peer transmission, provided +you inform other peers where the object code and Corresponding +Source of the work are being offered to the general public at no +charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + +"Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + +7. Additional Terms. + +"Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + +a) Disclaiming warranty or limiting liability differently from the +terms of sections 15 and 16 of this License; or + +b) Requiring preservation of specified reasonable legal notices or +author attributions in that material or in the Appropriate Legal +Notices displayed by works containing it; or + +c) Prohibiting misrepresentation of the origin of that material, or +requiring that modified versions of such material be marked in +reasonable ways as different from the original version; or + +d) Limiting the use for publicity purposes of names of licensors or +authors of the material; or + +e) Declining to grant rights under trademark law for use of some +trade names, trademarks, or service marks; or + +f) Requiring indemnification of licensors and authors of that +material by anyone who conveys the material (or modified versions of +it) with contractual assumptions of liability to the recipient, for +any liability that these contractual assumptions directly impose on +those licensors and authors. + +All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + +8. Termination. + +You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + +However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + +Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + +9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + +11. Patents. + +A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + +If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + +A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + +13. Remote Network Interaction; Use with the GNU General Public License. + +Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + +Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + +14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + +Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + +15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + +Copyright (C) 2026 NodeByte LTD + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published +by the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + +You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. \ No newline at end of file diff --git a/apps/smtp-server/README.md b/apps/smtp-server/README.md new file mode 100644 index 0000000..6e338c4 --- /dev/null +++ b/apps/smtp-server/README.md @@ -0,0 +1,281 @@ +# ByteSend SMTP Server + +A lightweight, production-ready SMTP server that forwards incoming email to the ByteSend API. Deploy it standalone or behind a reverse proxy to accept SMTP connections and integrate with ByteSend's email delivery platform. + +[![GitHub](https://img.shields.io/badge/GitHub-ByteSend-181717?logo=github)](https://github.com/NodeByteLTD/ByteSend/tree/main/apps/smtp-server) +[![License](https://img.shields.io/badge/License-AGPLv3-blue.svg)](LICENSE) +[![Node.js](https://img.shields.io/badge/Node.js-18+-green)](https://nodejs.org) + +--- + +## Features + +- ✅ **Simple & Lightweight** — Minimal dependencies, ~10 MB Docker image +- ✅ **Flexible TLS** — `none` (behind proxy) or `manual` (standalone with certs) +- ✅ **API Key Auth** — Secure SMTP authentication using ByteSend API keys +- ✅ **Hot-Reload Certs** — Automatic certificate reload on renewal (zero downtime) +- ✅ **Multi-Port** — Listens on 25 (SMT), 587 (submission), 465 (implicit TLS) +- ✅ **Container-Ready** — Docker & Kubernetes-friendly +- ✅ **Systemd Support** — Native Linux service integration +- ✅ **Production Logs** — Structured logging via stdout/journald + +--- + +## Quick Start + +### Docker (Recommended) + +```bash +# Clone the repository +git clone https://github.com/NodeByteLTD/ByteSend.git +cd ByteSend/apps/smtp-server + +# Configure docker-compose.yml +# (See docs/self-hosting/smtp-server.mdx for details) + +# Start the server +docker compose up -d --build + +# Check logs +docker compose logs -f smtp +``` + +### Node.js + +```bash +# Clone and install +git clone https://github.com/NodeByteLTD/ByteSend.git +cd ByteSend/apps/smtp-server +npm install +npm run build + +# Run +NODE_ENV=production SMTP_AUTH_USERNAME=bytesend BYTESEND_BASE_URL=https://bytesend.cloud node dist/server.js +``` + +### Systemd + +```bash +# Copy service file +sudo cp contrib/bytesend-smtp.service /etc/systemd/system/ + +# Enable and start +sudo systemctl daemon-reload +sudo systemctl enable bytesend-smtp +sudo systemctl start bytesend-smtp +``` + +--- + +## Configuration + +Set environment variables to configure the server: + +| Variable | Default | Description | +|----------|---------|-------------| +| `SMTP_AUTH_USERNAME` | `bytesend` | Username for SMTP authentication | +| `BYTESEND_BASE_URL` | `https://bytesend.cloud` | ByteSend API endpoint (e.g., `https://api.example.com`) | +| `SMTP_TLS_MODE` | `none` | TLS mode: `none` (plain) or `manual` (with certs) | +| `SMTP_TLS_CERT_PATH` | — | Path to full certificate chain (PEM format) | +| `SMTP_TLS_KEY_PATH` | — | Path to private key (PEM format) | +| `NODE_ENV` | `development` | Set to `production` for production use | + +### Example: Manual TLS with Let's Encrypt + +```bash +export SMTP_TLS_MODE=manual +export SMTP_TLS_CERT_PATH=/etc/letsencrypt/live/smtp.example.com/fullchain.pem +export SMTP_TLS_KEY_PATH=/etc/letsencrypt/live/smtp.example.com/privkey.pem +node dist/server.js +``` + +--- + +## Architecture + +``` +┌─────────────────┐ +│ SMTP Clients │ +│ (port 25/587) │ +└────────┬────────┘ + │ + [STARTTLS] + │ + ▼ +┌──────────────────────┐ +│ SMTP Server │ +│ (Node.js) │ +│ - Auth │ +│ - Parse Email │ +│ - Forward to API │ +└──────────┬───────────┘ + │ + ▼ + ┌──────────────┐ + │ ByteSend API │ + │ /api/v1/... │ + └──────────────┘ +``` + +--- + +## Supported Ports + +- **25** — Standard SMTP (plain or STARTTLS) +- **587** — Submission port (plain or STARTTLS) +- **465** — Implicit TLS (SMTPS, manual mode only) +- **2465 & 2587** — Alternative ports for testing/internal use + +--- + +## Usage Example + +### Nodemailer (Node.js) + +```javascript +const nodemailer = require("nodemailer"); + +const transporter = nodemailer.createTransport({ + host: "smtp.example.com", + port: 587, + secure: false, + auth: { + user: "bytesend", + pass: "your_api_key_here", + }, +}); + +transporter.sendMail({ + from: "sender@example.com", + to: "recipient@example.com", + subject: "Hello", + text: "Email via ByteSend SMTP", +}, (err, info) => { + console.log(err || info); +}); +``` + +### Postfix + +Add to `main.cf`: + +``` +relayhost = smtp.example.com:587 +smtp_tls_security_level = encrypt +smtp_sasl_auth_enable = yes +smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd +``` + +Then in `/etc/postfix/sasl_passwd`: + +``` +smtp.example.com:587 bytesend:your_api_key_here +``` + +--- + +## Deployment + +### Docker Compose +See [docs/self-hosting/smtp-server.mdx](https://github.com/NodeByteLTD/ByteSend/blob/main/apps/docs/self-hosting/smtp-server.mdx#option-1-docker-recommended) + +### Kubernetes +See [contrib/k8s/deployment.yaml](contrib/k8s/deployment.yaml) + +### Systemd +See [docs/self-hosting/smtp-server.mdx](https://github.com/NodeByteLTD/ByteSend/blob/main/apps/docs/self-hosting/smtp-server.mdx#systemd-service-setup) + +### Nginx Reverse Proxy +See [docs/self-hosting/smtp-server.mdx](https://github.com/NodeByteLTD/ByteSend/blob/main/apps/docs/self-hosting/smtp-server.mdx#reverse-proxy-setup) + +--- + +## Security + +- **Uses AGPL v3.0** — Must share modifications +- **Authenticate with API keys** — Store keys securely, rotate regularly +- **Enable TLS in production** — Use `manual` mode with valid certificates or a reverse proxy +- **Restrict network access** — Limit port access by IP if possible +- **Monitor logs** — Watch for authentication failures and connection issues + +See [SECURITY.md](SECURITY.md) for detailed security guidelines. + +--- + +## Troubleshooting + +### Connection Refused +```bash +netstat -tulpn | grep :587 +telnet smtp.example.com 587 +``` + +### Authentication Failed +- Verify the API key is correct +- Check `SMTP_AUTH_USERNAME` matches client config +- Review server logs: `docker compose logs smtp` + +### STARTTLS Not Supported +- In `none` mode, STARTTLS is disabled (use a reverse proxy instead) +- In `manual` mode, ensure cert paths are valid: `openssl x509 -in /path/to/cert.pem -text` + +### TLS Certificate Errors +- Verify certificate and key files exist and are readable +- Test the cert: `openssl verify /path/to/cert.pem` +- Check file permissions: `ls -la /path/to/cert.pem` + +--- + +## Contributing + +Contributions are welcome! Please: + +1. Fork the repository +2. Create a feature branch (`git checkout -b feature/my-feature`) +3. Commit changes (`git commit -m 'Add my feature'`) +4. Push to the branch (`git push origin feature/my-feature`) +5. Open a Pull Request + +See [CONTRIBUTING.md](CONTRIBUTING.md) for detailed guidelines. + +--- + +## License + +This project is licensed under the **GNU Affero General Public License v3.0** (AGPL-3.0). + +See [LICENSE](LICENSE) for full details. + +**In short:** +- ✅ Free to use and modify +- ✅ Must share modifications +- ✅ Must include license notice +- ✅ Network use is distribution (modifications must be shared with users) + +--- + +## Changelog + +See [CHANGELOG.md](CHANGELOG.md) for version history and release notes. + +--- + +## Support + +- 📖 **Documentation:** [ByteSend Self-Hosting Guide](https://docs.bytesend.cloud/self-hosting/smtp-server) +- 🐛 **Issues:** [GitHub Issues](https://github.com/NodeByteLTD/ByteSend/issues) +- 💬 **Discussions:** [GitHub Discussions](https://github.com/NodeByteLTD/ByteSend/discussions) +- 📧 **Email:** [support@bytesend.cloud](mailto:support@bytesend.cloud) + +--- + +## Acknowledgments + +Built with: +- [smtp-server](https://nodemailer.com/smtp/server/) — SMTP server implementation +- [mailparser](https://nodemailer.com/extras/mailparser/) — Email parsing +- Node.js & the open source community + +--- + +**Made with ❤️ by [NodeByte Hosting](https://nodebyte.co.uk)** diff --git a/apps/smtp-server/SECURITY.md b/apps/smtp-server/SECURITY.md new file mode 100644 index 0000000..b11ee6e --- /dev/null +++ b/apps/smtp-server/SECURITY.md @@ -0,0 +1,182 @@ +# Security Policy + +## Overview + +The ByteSend SMTP Server is designed with security as a core principle. This document outlines security practices, vulnerability reporting, and guidelines for secure deployment. + +--- + +## Security Considerations + +### Authentication + +- **API Key Based:** The server uses ByteSend API keys as SMTP passwords +- **Username Verification:** Default username is `bytesend` (configurable via `SMTP_AUTH_USERNAME`) +- **No Password Storage:** Keys are never persisted; validated on each connection +- **API Key Management:** + - Store keys in environment variables or secrets management systems (never in version control) + - Rotate API keys regularly + - Use separate keys per environment (dev, staging, production) + - Revoke compromised keys immediately + +### Transport Security (TLS) + +#### Mode: `none` (Behind Reverse Proxy) +- Server runs plain SMTP; TLS is handled by the proxy +- `STARTTLS` is disabled at the server level +- Use with: + - Nginx with SSL module + - Traefik with TLS routers + - AWS ALB with TLS listeners +- **Best practice:** Restrict the proxy-to-SMTP connection to a private network + +#### Mode: `manual` (Standalone) +- Server handles TLS directly +- Requires valid certificates from a trusted CA (Let's Encrypt, etc.) +- Self-signed certificates are supported for testing only +- **Best practice:** + - Use multi-year certificates or automate renewal + - Implement certificate pinning if possible + - Monitor certificate expiration dates + +### Network Isolation + +- **Firewall Rules:** Restrict SMTP ports (25, 587, 465) to trusted IPs or subnets +- **Docker Networks:** Use custom networks instead of host networking +- **Private Networks:** Consider running the SMTP server on a private network, exposing only to authorized applications +- **Rate Limiting:** Implement rate limiting at the reverse proxy level to prevent brute-force attacks + +### Logging & Monitoring + +- **Structured Logging:** All logs are output to stdout (compatible with journald, Docker, Kubernetes) +- **Sensitive Data:** API keys are **never** logged; only connection status and errors +- **Monitoring Recommendations:** + - Monitor authentication failure rates + - Alert on TLS certificate errors + - Track email submission rates (early detection of hijacked credentials) + - Set up alerting for process crashes or unexpected restarts + +### File Permissions + +- **Certificate Files:** Should be readable only by the SMTP server process + ```bash + sudo chown smtp:smtp /path/to/cert.pem /path/to/key.pem + sudo chmod 600 /path/to/key.pem + sudo chmod 644 /path/to/cert.pem + ``` +- **Systemd Service:** Runs as unprivileged `smtp` user +- **Docker:** Non-root user recommended (add to `Dockerfile.smtp`): + ```dockerfile + USER node + ``` + +### Dependency Security + +- **Regular Updates:** Keep Node.js and npm dependencies up to date + ```bash + npm audit + npm audit fix + ``` +- **Minimal Dependencies:** The server uses only essential packages: + - `smtp-server` — SMTP server implementation + - `mailparser` — Email parsing +- **Pinned Versions:** Lock dependency versions in `package-lock.json` + +--- + +## Deployment Security Checklist + +- [ ] Change default `SMTP_AUTH_USERNAME` if using in production +- [ ] Generate and store API keys securely (environment variables, secrets manager) +- [ ] Enable TLS (`manual` mode with valid certs or behind reverse proxy) +- [ ] Set file permissions on certificates (600 for private key) +- [ ] Restrict firewall rules to trusted IPs/networks +- [ ] Configure logging and monitoring +- [ ] Set up certificate renewal automation +- [ ] Run as non-root user (systemd: `User=smtp`, Docker: non-root) +- [ ] Use `NODE_ENV=production` +- [ ] Test authentication and TLS with external tools +- [ ] Document all configuration and access controls + +--- + +## Common Vulnerabilities & Mitigations + +### Unauthorized Email Injection +**Risk:** Attackers use valid credentials to send emails impersonating legitimate senders + +**Mitigations:** +- Restrict API key usage to specific users/teams in ByteSend dashboard +- Monitor sender addresses and volume anomalies +- Rate-limit submissions at the reverse proxy +- Use dedicated API keys per application/service + +### Man-in-the-Middle (MITM) Attacks +**Risk:** Credentials or email content intercepted in transit + +**Mitigations:** +- Always use TLS (mode `manual` or reverse proxy) +- Use certificates from trusted CAs (avoid self-signed in production) +- Implement certificate pinning (client-side) +- Restrict network access to trusted networks + +### Brute-Force Authentication +**Risk:** Attackers attempt multiple API keys to gain access + +**Mitigations:** +- Implement rate limiting at reverse proxy level +- Monitor authentication failure logs +- Use strong, random API keys +- Rotate keys regularly +- Consider IP-based access controls + +### Denial of Service (DoS) +**Risk:** Attackers send excessive SMTP connections or large emails + +**Mitigations:** +- Set reasonable connection limits at the reverse proxy +- Limit email size (default: 10 MB, configurable in code) +- Monitor network bandwidth +- Use DDoS protection services if behind a public IP +- Implement per-IP rate limiting + +--- + +## Security Contact + +If you discover a security vulnerability, please **do not** open a public GitHub issue. Instead: + +1. **Email:** [security@nodebyte.co.uk](mailto:security@nodebyte.co.uk) +2. **Include:** + - Description of the vulnerability + - Steps to reproduce + - Potential impact + - Suggested mitigation (if any) + +**Disclosure Policy:** +- We will acknowledge your report within 24 hours +- We aim to patch critical issues within 7 days +- We will credit you in the release notes (unless you prefer anonymity) +- We request 90 days before public disclosure to allow deployment of patches + +--- + +## Compliance & Certifications + +- **AGPL-3.0 License:** Source code must be shared; see [LICENSE](LICENSE) +- **Data Privacy:** The server does not store email data; all emails are forwarded to ByteSend API +- **SMTP Standards:** Implements RFC 5321 (SMTP) and RFC 3207 (STARTTLS) + +--- + +## Additional Resources + +- [OWASP SMTP Security](https://owasp.org/www-community/attacks/smtp_injection) +- [Let's Encrypt Documentation](https://letsencrypt.org/docs/) +- [Certbot Renewal Guide](https://certbot.eff.org/docs/using.html#renewal) +- [Nginx SSL Configuration](https://nginx.org/en/docs/http/configuring_https_ssl.html) +- [Systemd Security Best Practices](https://www.freedesktop.org/wiki/Software/systemd/SecurityFeatures/) + +--- + +**Last Updated:** 2026-04-07 diff --git a/apps/smtp-server/docker-compose.yml b/apps/smtp-server/docker-compose.yml new file mode 100644 index 0000000..e83792b --- /dev/null +++ b/apps/smtp-server/docker-compose.yml @@ -0,0 +1,28 @@ +version: '3.8' + +services: + smtp: + build: + context: . + dockerfile: Dockerfile + restart: unless-stopped + ports: + - "25:25" + - "587:587" + - "465:465" + - "2465:2465" + - "2587:2587" + environment: + - NODE_ENV=${NODE_ENV:-production} + - SMTP_AUTH_USERNAME=${SMTP_AUTH_USERNAME:-bytesend} + - BYTESEND_BASE_URL=${BYTESEND_BASE_URL:-https://bytesend.cloud} + # TLS_MODE: 'none' (default) — plain SMTP, suitable behind a reverse proxy + # 'manual' — server handles TLS; set cert/key paths below + - SMTP_TLS_MODE=${SMTP_TLS_MODE:-none} + # Uncomment and set these when using SMTP_TLS_MODE=manual: + # - SMTP_TLS_CERT_PATH=${SMTP_TLS_CERT_PATH:-/certs/fullchain.pem} + # - SMTP_TLS_KEY_PATH=${SMTP_TLS_KEY_PATH:-/certs/privkey.pem} + # When using manual TLS, mount your cert directory: + # volumes: + # - /etc/letsencrypt/live/smtp.example.com:/certs:ro + diff --git a/apps/smtp-server/package.json b/apps/smtp-server/package.json new file mode 100644 index 0000000..da662c8 --- /dev/null +++ b/apps/smtp-server/package.json @@ -0,0 +1,28 @@ +{ + "name": "smtp-server", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1", + "build": "tsup", + "start": "node dist/server.js" + }, + "keywords": [], + "author": "", + "license": "ISC", + "dependencies": { + "@types/mailparser": "^3.4.5", + "@types/smtp-server": "^3.5.10", + "dotenv": "^16.5.0", + "mailparser": "^3.7.2", + "nodemailer": "^6.10.1", + "smtp-server": "^3.13.6" + }, + "devDependencies": { + "@types/node": "^22.15.2", + "@types/nodemailer": "^6.4.17", + "tsup": "^8.4.0", + "typescript": "^5.8.3" + } +} \ No newline at end of file diff --git a/apps/smtp-server/src/server.ts b/apps/smtp-server/src/server.ts new file mode 100644 index 0000000..86cecf7 --- /dev/null +++ b/apps/smtp-server/src/server.ts @@ -0,0 +1,214 @@ +import dotenv from "dotenv"; +import { Readable } from "stream"; +import { simpleParser } from "mailparser"; +import { readFileSync, watch, FSWatcher } from "fs"; +import { SMTPServer, SMTPServerOptions, SMTPServerSession } from "smtp-server"; + +dotenv.config(); + +const BASE_URL = process.env.BYTESEND_BASE_URL ?? "https://bytesend.cloud"; + +async function verifySmtpCredentials( + username: string, + password: string, +): Promise { + try { + const url = new URL("/api/v1/smtp/auth", BASE_URL); + const response = await fetch(url.href, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ username, password }), + }); + return response.ok; + } catch (error) { + console.error("SMTP auth check failed:", error); + return false; + } +} +const TLS_MODE = (process.env.SMTP_TLS_MODE ?? "none").toLowerCase(); +const SSL_KEY_PATH = process.env.SMTP_TLS_KEY_PATH; +const SSL_CERT_PATH = process.env.SMTP_TLS_CERT_PATH; + +async function sendEmailToByteSend(emailData: any, apiKey: string) { + try { + const apiEndpoint = "/api/v1/emails"; + const url = new URL(apiEndpoint, BASE_URL); + console.log("Sending email to ByteSend API at:", url.href); + + const emailDataText = JSON.stringify(emailData); + + const response = await fetch(url.href, { + method: "POST", + headers: { + Authorization: `Bearer ${apiKey}`, + "Content-Type": "application/json", + }, + body: emailDataText, + }); + + if (!response.ok) { + const errorData = await response.text(); + console.error( + "ByteSend API error response: error:", + JSON.stringify(errorData, null, 4), + `\nemail data: ${emailDataText}`, + ); + throw new Error( + `Failed to send email: ${errorData || "Unknown error from server"}`, + ); + } + + const responseData = await response.json(); + console.log("ByteSend API response:", responseData); + } catch (error) { + if (error instanceof Error) { + console.error("Error message:", error.message); + throw new Error(`Failed to send email: ${error.message}`); + } else { + console.error("Unexpected error:", error); + throw new Error("Failed to send email: Unexpected error occurred"); + } + } +} + +function loadCertificates(): { key?: Buffer; cert?: Buffer } { + if (TLS_MODE !== "manual") return {}; + if (!SSL_KEY_PATH || !SSL_CERT_PATH) { + throw new Error( + "SMTP_TLS_MODE is 'manual' but SMTP_TLS_KEY_PATH / SMTP_TLS_CERT_PATH are not set", + ); + } + return { + key: readFileSync(SSL_KEY_PATH), + cert: readFileSync(SSL_CERT_PATH), + }; +} + +const initialCerts = loadCertificates(); + +const serverOptions: SMTPServerOptions = { + secure: false, + key: initialCerts.key, + cert: initialCerts.cert, + disabledCommands: TLS_MODE === "none" ? ["STARTTLS"] : [], + allowInsecureAuth: TLS_MODE === "none", + onData( + stream: Readable, + session: SMTPServerSession, + callback: (error?: Error) => void, + ) { + console.log("Receiving email data..."); + simpleParser(stream, (err, parsed) => { + if (err) { + console.error("Failed to parse email data:", err.message); + return callback(err); + } + + if (!session.user) { + console.error("No API key found in session"); + return callback(new Error("No API key found in session")); + } + + const emailObject = { + to: Array.isArray(parsed.to) + ? parsed.to.map((addr) => addr.text).join(", ") + : parsed.to?.text, + from: Array.isArray(parsed.from) + ? parsed.from.map((addr) => addr.text).join(", ") + : parsed.from?.text, + subject: parsed.subject, + text: parsed.text, + html: parsed.html, + replyTo: parsed.replyTo?.text, + }; + + sendEmailToByteSend(emailObject, session.user) + .then(() => callback()) + .then(() => console.log("Email sent successfully to: ", emailObject.to)) + .catch((error) => { + console.error("Failed to send email:", error.message); + callback(error); + }); + }); + }, + onAuth(auth, session: any, callback: (error?: Error, user?: any) => void) { + if (!auth.password) { + console.error("SMTP auth rejected: no password provided"); + return callback(new Error("Invalid username or password")); + } + verifySmtpCredentials(auth.username ?? "", auth.password).then((valid) => { + if (valid) { + console.log("Authenticated successfully"); + callback(undefined, { user: auth.password }); + } else { + console.error("Invalid username or password"); + callback(new Error("Invalid username or password")); + } + }); + }, + size: 10485760, +}; + +function startServers() { + const servers: SMTPServer[] = []; + const watchers: FSWatcher[] = []; + + console.log(`SMTP TLS mode: ${TLS_MODE}`); + + if (TLS_MODE === "manual") { + [465, 2465].forEach((port) => { + const server = new SMTPServer({ ...serverOptions, secure: true }); + server.listen(port, () => { + console.log(`SMTP server (implicit TLS) is listening on port ${port}`); + }); + server.on("error", (err) => { + console.error(`Error occurred on port ${port}:`, err); + }); + servers.push(server); + }); + } + + [25, 587, 2587].forEach((port) => { + const server = new SMTPServer(serverOptions); + server.listen(port, () => { + const label = TLS_MODE === "manual" ? "STARTTLS" : "plain (no TLS)"; + console.log(`SMTP server (${label}) is listening on port ${port}`); + }); + server.on("error", (err) => { + console.error(`Error occurred on port ${port}:`, err); + }); + servers.push(server); + }); + + if (TLS_MODE === "manual" && SSL_KEY_PATH && SSL_CERT_PATH) { + const reloadCertificates = () => { + try { + const { key, cert } = loadCertificates(); + if (key && cert) { + servers.forEach((srv) => srv.updateSecureContext({ key, cert })); + console.log("TLS certificates reloaded"); + } + } catch (err) { + console.error("Failed to reload TLS certificates", err); + } + }; + [SSL_KEY_PATH, SSL_CERT_PATH].forEach((file) => { + watchers.push(watch(file, { persistent: false }, reloadCertificates)); + }); + } + + return { servers, watchers }; +} + +const { servers, watchers } = startServers(); + +function shutdown() { + console.log("Shutting down SMTP server..."); + watchers.forEach((w) => w.close()); + servers.forEach((s) => s.close()); + process.exit(0); +} + +["SIGINT", "SIGTERM", "SIGQUIT"].forEach((signal) => { + process.on(signal, shutdown); +}); diff --git a/apps/smtp-server/src/usage.js b/apps/smtp-server/src/usage.js new file mode 100644 index 0000000..054d74b --- /dev/null +++ b/apps/smtp-server/src/usage.js @@ -0,0 +1,30 @@ +const nodemailer = require("nodemailer"); + +const transporter = nodemailer.createTransport({ + host: "localhost", + port: 25, + secure: false, + auth: { + user: "bytesend", + pass: "bs_123", + }, + tls: { + rejectUnauthorized: false, + }, +}); + +const mailOptions = { + to: "sender@example.com", + from: "hello@example.com", + subject: "Testing SMTP", + html: "THIS IS USING SMTP,

using ByteSend

", + text: "hello,\n\nusing ByteSend", +}; + +transporter.sendMail(mailOptions, (error, info) => { + if (error) { + console.error("Error sending email:", error); + } else { + console.log("Email sent successfully:", info.response); + } +}); diff --git a/apps/smtp-server/tsconfig.json b/apps/smtp-server/tsconfig.json new file mode 100644 index 0000000..b4722b8 --- /dev/null +++ b/apps/smtp-server/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + /* Language and Environment */ + "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + "module": "commonjs", /* Specify what module code is generated. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Modules */ + "rootDir": "./src", /* Specify the root folder within your source files. */ + "outDir": "./dist", /* Specify an output folder for all emitted files. */ + + /* Emit */ + "sourceMap": true, /* Create source map files for emitted JavaScript files. */ + "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + "removeComments": true, /* Disable emitting comments. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + "skipLibCheck": true /* Skip type checking all .d.ts files. */ + }, + "include": ["src/**/*.ts"], /* Include all TypeScript files in the src directory. */ + "exclude": ["node_modules"] /* Exclude node_modules from compilation. */ +} diff --git a/apps/smtp-server/tsup.config.ts b/apps/smtp-server/tsup.config.ts new file mode 100644 index 0000000..e7d1815 --- /dev/null +++ b/apps/smtp-server/tsup.config.ts @@ -0,0 +1,13 @@ +// eslint-disable-next-line import/no-extraneous-dependencies +import { defineConfig, Options } from "tsup"; + +// eslint-disable-next-line import/no-default-export +export default defineConfig((options: Options) => ({ + entry: ["src/server.ts"], + format: ["cjs"], + dts: true, + minify: true, + clean: true, + injectStyle: true, + ...options, +})); From bd3b649d02d82b018b5aefb5a59c0cb82e23dfef Mon Sep 17 00:00:00 2001 From: TheRealToxicDev Date: Sat, 9 May 2026 08:23:04 -0600 Subject: [PATCH 3/9] more stuff yes --- apps/docs/get-started/smtp.mdx | 4 +- apps/docs/self-hosting/smtp-server.mdx | 17 +++++- apps/smtp-server/README.md | 15 ++++- apps/smtp-server/src/server.ts | 79 +++++++++++++++++++------- 4 files changed, 88 insertions(+), 27 deletions(-) diff --git a/apps/docs/get-started/smtp.mdx b/apps/docs/get-started/smtp.mdx index 0e8a780..257db1b 100644 --- a/apps/docs/get-started/smtp.mdx +++ b/apps/docs/get-started/smtp.mdx @@ -17,7 +17,7 @@ To set up your SMTP integration, you'll need to provide the following credential - **Host:** ```smtp.bytesend.cloud``` - **Port:** ```465```, ```587```, ```2465```, or ```2587``` -- **Username:** ```bytesend``` +- **Username:** your SMTP username from ByteSend Dev Settings (default: ```bytesend```) - **Password:** ```YOUR-API-KEY``` ## Example with Nodemailer @@ -32,7 +32,7 @@ const transporter = nodemailer.createTransport({ port: 465, secure: false, auth: { - user: "bytesend", + user: "your_smtp_username", pass: "bs_your_api_key", }, tls: { diff --git a/apps/docs/self-hosting/smtp-server.mdx b/apps/docs/self-hosting/smtp-server.mdx index b26811b..81c7ba2 100644 --- a/apps/docs/self-hosting/smtp-server.mdx +++ b/apps/docs/self-hosting/smtp-server.mdx @@ -75,7 +75,7 @@ The server supports two TLS configurations: # Edit with your values # BYTESEND_BASE_URL=https://your-bytesend-instance.com - # SMTP_AUTH_USERNAME=bytesend + # SMTP_AUTH_USERNAME=bytesend # Optional legacy fallback when client omits username # SMTP_TLS_MODE=none # or 'manual' if you have certs ``` @@ -166,7 +166,7 @@ The server supports two TLS configurations: Or set them in your shell: ```bash export NODE_ENV=production - export SMTP_AUTH_USERNAME=bytesend + export SMTP_AUTH_USERNAME=bytesend export BYTESEND_BASE_URL=https://bytesend.cloud export SMTP_TLS_MODE=none # For manual TLS: @@ -187,7 +187,7 @@ The server supports two TLS configurations: | Variable | Default | Description | |----------|---------|-------------| -| `SMTP_AUTH_USERNAME` | `bytesend` | Username for SMTP authentication | +| `SMTP_AUTH_USERNAME` | `bytesend` | Optional legacy fallback if SMTP client omits username | | `BYTESEND_BASE_URL` | `https://bytesend.cloud` | URL to your ByteSend instance (e.g., `https://api.example.com`) | | `SMTP_TLS_MODE` | `none` | TLS mode: `none` or `manual` | | `SMTP_TLS_CERT_PATH` | — | Path to certificate file (required if `SMTP_TLS_MODE=manual`) | @@ -217,6 +217,17 @@ Docker Compose automatically loads variables from `.env` and the docker-compose. - **Local Testing:** Use `.env` file for local development with `docker compose up` - **Production:** Both methods work; use .env or set variables directly in your deployment platform +### Health Checks + +For status pages, monitor the SMTP listener ports directly: + +- `25` +- `587` +- `2587` +- `465` and `2465` when `SMTP_TLS_MODE=manual` + +Most status providers support TCP checks for SMTP services, which is the recommended way to monitor this server. + ### TLS Certificates When using `SMTP_TLS_MODE=manual`, you need a valid certificate and private key. See the [Certificate Setup](./certificates) guide for full instructions covering Let's Encrypt (certbot), self-signed certs, and commercial certificates. diff --git a/apps/smtp-server/README.md b/apps/smtp-server/README.md index 6e338c4..c309385 100644 --- a/apps/smtp-server/README.md +++ b/apps/smtp-server/README.md @@ -50,7 +50,7 @@ npm install npm run build # Run -NODE_ENV=production SMTP_AUTH_USERNAME=bytesend BYTESEND_BASE_URL=https://bytesend.cloud node dist/server.js +NODE_ENV=production BYTESEND_BASE_URL=https://bytesend.cloud node dist/server.js ``` ### Systemd @@ -73,7 +73,7 @@ Set environment variables to configure the server: | Variable | Default | Description | |----------|---------|-------------| -| `SMTP_AUTH_USERNAME` | `bytesend` | Username for SMTP authentication | +| `SMTP_AUTH_USERNAME` | `bytesend` | Legacy fallback username candidate (used if the client omits username) | | `BYTESEND_BASE_URL` | `https://bytesend.cloud` | ByteSend API endpoint (e.g., `https://api.example.com`) | | `SMTP_TLS_MODE` | `none` | TLS mode: `none` (plain) or `manual` (with certs) | | `SMTP_TLS_CERT_PATH` | — | Path to full certificate chain (PEM format) | @@ -126,6 +126,15 @@ node dist/server.js - **465** — Implicit TLS (SMTPS, manual mode only) - **2465 & 2587** — Alternative ports for testing/internal use +## Health Checks + +Monitor SMTP listener ports directly from your status page: + +- `25` +- `587` +- `2587` +- `465` and `2465` when `SMTP_TLS_MODE=manual` + --- ## Usage Example @@ -212,7 +221,7 @@ telnet smtp.example.com 587 ### Authentication Failed - Verify the API key is correct -- Check `SMTP_AUTH_USERNAME` matches client config +- Check the SMTP client username matches the team's configured SMTP username in ByteSend - Review server logs: `docker compose logs smtp` ### STARTTLS Not Supported diff --git a/apps/smtp-server/src/server.ts b/apps/smtp-server/src/server.ts index 86cecf7..764729e 100644 --- a/apps/smtp-server/src/server.ts +++ b/apps/smtp-server/src/server.ts @@ -1,12 +1,35 @@ import dotenv from "dotenv"; -import { Readable } from "stream"; -import { simpleParser } from "mailparser"; import { readFileSync, watch, FSWatcher } from "fs"; +import { simpleParser } from "mailparser"; import { SMTPServer, SMTPServerOptions, SMTPServerSession } from "smtp-server"; +import { Readable } from "stream"; dotenv.config(); const BASE_URL = process.env.BYTESEND_BASE_URL ?? "https://bytesend.cloud"; +const TLS_MODE = (process.env.SMTP_TLS_MODE ?? "none").toLowerCase(); +const SSL_KEY_PATH = process.env.SMTP_TLS_KEY_PATH; +const SSL_CERT_PATH = process.env.SMTP_TLS_CERT_PATH; + +const LEGACY_DEFAULT_USERNAME = (process.env.SMTP_AUTH_USERNAME ?? "bytesend").trim(); + +const SMTP_PLAIN_PORTS = [25, 587, 2587] as const; +const SMTP_IMPLICIT_TLS_PORTS = [465, 2465] as const; + +function buildUsernameCandidates(username: unknown): string[] { + const candidates = new Set(); + + const providedUsername = typeof username === "string" ? username.trim() : ""; + if (providedUsername) { + candidates.add(providedUsername); + } + + if (LEGACY_DEFAULT_USERNAME) { + candidates.add(LEGACY_DEFAULT_USERNAME); + } + + return [...candidates]; +} async function verifySmtpCredentials( username: string, @@ -19,15 +42,13 @@ async function verifySmtpCredentials( headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username, password }), }); + return response.ok; } catch (error) { console.error("SMTP auth check failed:", error); return false; } } -const TLS_MODE = (process.env.SMTP_TLS_MODE ?? "none").toLowerCase(); -const SSL_KEY_PATH = process.env.SMTP_TLS_KEY_PATH; -const SSL_CERT_PATH = process.env.SMTP_TLS_CERT_PATH; async function sendEmailToByteSend(emailData: any, apiKey: string) { try { @@ -64,20 +85,22 @@ async function sendEmailToByteSend(emailData: any, apiKey: string) { if (error instanceof Error) { console.error("Error message:", error.message); throw new Error(`Failed to send email: ${error.message}`); - } else { - console.error("Unexpected error:", error); - throw new Error("Failed to send email: Unexpected error occurred"); } + + console.error("Unexpected error:", error); + throw new Error("Failed to send email: Unexpected error occurred"); } } function loadCertificates(): { key?: Buffer; cert?: Buffer } { if (TLS_MODE !== "manual") return {}; + if (!SSL_KEY_PATH || !SSL_CERT_PATH) { throw new Error( "SMTP_TLS_MODE is 'manual' but SMTP_TLS_KEY_PATH / SMTP_TLS_CERT_PATH are not set", ); } + return { key: readFileSync(SSL_KEY_PATH), cert: readFileSync(SSL_CERT_PATH), @@ -131,19 +154,36 @@ const serverOptions: SMTPServerOptions = { }); }); }, - onAuth(auth, session: any, callback: (error?: Error, user?: any) => void) { - if (!auth.password) { + onAuth(auth, _session: any, callback: (error?: Error, user?: any) => void) { + const providedPassword = + typeof auth.password === "string" ? auth.password : ""; + + if (!providedPassword.trim()) { console.error("SMTP auth rejected: no password provided"); return callback(new Error("Invalid username or password")); } - verifySmtpCredentials(auth.username ?? "", auth.password).then((valid) => { - if (valid) { - console.log("Authenticated successfully"); - callback(undefined, { user: auth.password }); - } else { - console.error("Invalid username or password"); - callback(new Error("Invalid username or password")); + + const usernameCandidates = buildUsernameCandidates(auth.username); + if (usernameCandidates.length === 0) { + console.error("SMTP auth rejected: no username provided"); + return callback(new Error("Invalid username or password")); + } + + void (async () => { + for (const username of usernameCandidates) { + const valid = await verifySmtpCredentials(username, providedPassword); + if (valid) { + console.log(`Authenticated successfully with username '${username}'`); + callback(undefined, { user: providedPassword, smtpUsername: username }); + return; + } } + + console.error("Invalid username or password"); + callback(new Error("Invalid username or password")); + })().catch((error) => { + console.error("SMTP auth processing failed", error); + callback(new Error("Invalid username or password")); }); }, size: 10485760, @@ -156,7 +196,7 @@ function startServers() { console.log(`SMTP TLS mode: ${TLS_MODE}`); if (TLS_MODE === "manual") { - [465, 2465].forEach((port) => { + SMTP_IMPLICIT_TLS_PORTS.forEach((port) => { const server = new SMTPServer({ ...serverOptions, secure: true }); server.listen(port, () => { console.log(`SMTP server (implicit TLS) is listening on port ${port}`); @@ -168,7 +208,7 @@ function startServers() { }); } - [25, 587, 2587].forEach((port) => { + SMTP_PLAIN_PORTS.forEach((port) => { const server = new SMTPServer(serverOptions); server.listen(port, () => { const label = TLS_MODE === "manual" ? "STARTTLS" : "plain (no TLS)"; @@ -192,6 +232,7 @@ function startServers() { console.error("Failed to reload TLS certificates", err); } }; + [SSL_KEY_PATH, SSL_CERT_PATH].forEach((file) => { watchers.push(watch(file, { persistent: false }, reloadCertificates)); }); From c4369810df014a29a70fae6f7527837f3864a820 Mon Sep 17 00:00:00 2001 From: TheRealToxicDev Date: Sat, 9 May 2026 08:31:51 -0600 Subject: [PATCH 4/9] v0.2.5 prep --- .github/ISSUE_TEMPLATE/bug.yml | 111 ++++-- .github/ISSUE_TEMPLATE/config.yml | 11 + .github/ISSUE_TEMPLATE/docs.yml | 29 ++ .github/ISSUE_TEMPLATE/feature.yml | 49 +++ .github/ISSUE_TEMPLATE/marketing.yml | 59 ++- .github/ISSUE_TEMPLATE/smtp.yml | 90 ++++- .github/PULL_REQUEST_TEMPLATE.md | 36 ++ .gitignore | 1 - .references/README.md | 20 + .references/release-playbook.md | 65 ++++ .references/repository-governance.md | 62 +++ .references/smtp-auth-and-operations.md | 90 +++++ .references/webhook-architecture.md | 476 ++++++++++++++++++++++++ CHANGELOG.md | 42 ++- CODE_OF_CONDUCT.md | 72 ++++ CONTRIBUTING.md | 86 +++++ README.md | 7 + SECURITY.md | 55 +++ SUPPORT.md | 19 + 19 files changed, 1333 insertions(+), 47 deletions(-) create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/docs.yml create mode 100644 .github/ISSUE_TEMPLATE/feature.yml create mode 100644 .github/PULL_REQUEST_TEMPLATE.md create mode 100644 .references/README.md create mode 100644 .references/release-playbook.md create mode 100644 .references/repository-governance.md create mode 100644 .references/smtp-auth-and-operations.md create mode 100644 .references/webhook-architecture.md create mode 100644 CODE_OF_CONDUCT.md create mode 100644 CONTRIBUTING.md create mode 100644 SECURITY.md create mode 100644 SUPPORT.md diff --git a/.github/ISSUE_TEMPLATE/bug.yml b/.github/ISSUE_TEMPLATE/bug.yml index 69ac525..52ead5d 100644 --- a/.github/ISSUE_TEMPLATE/bug.yml +++ b/.github/ISSUE_TEMPLATE/bug.yml @@ -1,44 +1,109 @@ -name: Bug Report -description: File a bug report. -labels: ["bug"] -title: "🐞 - " +name: Bug report +description: Report a reproducible bug in ByteSend. +title: "bug: " +labels: ["bug", "needs-triage"] body: - type: markdown attributes: value: | - Thanks for taking the time to fill out this bug report! + Thanks for reporting this. Please provide enough detail so we can reproduce quickly. + + - type: input + id: version + attributes: + label: Version / commit + description: Which version/tag/commit are you running? + placeholder: v0.2.5 or commit SHA + validations: + required: true + + - type: dropdown + id: deployment + attributes: + label: Deployment + description: Where does the issue happen? + options: + - ByteSend Cloud + - Self-hosted + default: 0 + validations: + required: true + + - type: dropdown + id: area + attributes: + label: Affected area + options: + - API + - Dashboard UI + - SMTP relay + - Webhooks + - Billing + - Docs + - CI / workflows + - Other + validations: + required: true + - type: textarea - id: what-happened + id: description attributes: label: What happened? - placeholder: Tell us what you see! + description: Describe the bug clearly. validations: required: true + - type: textarea - id: replication + id: steps attributes: - label: Replication Steps - description: Provide clear steps as to how this happened - value: "1. First click this \n2. Navigate to this \n3. Click this \n4. See this" + label: Steps to reproduce + value: | + 1. Go to ... + 2. Click ... + 3. Submit ... + 4. Observe ... validations: - required: false - - type: dropdown - id: kind + required: true + + - type: textarea + id: expected attributes: - label: Self hosted or Cloud? - description: Does this happen on bytesend.cloud or on your own instance? - options: - - Cloud - - Self hosted - default: 0 + label: Expected behavior + validations: + required: true + + - type: textarea + id: actual + attributes: + label: Actual behavior validations: required: true + - type: dropdown - id: browsers + id: browser attributes: - label: What browsers are you seeing the problem on? + label: Browser (if UI issue) multiple: true options: + - Not applicable + - Chrome - Firefox - - Chrome (or chrome based like Brave, Arc, etc) - Safari + - Edge + - Other + + - type: textarea + id: logs + attributes: + label: Relevant logs or errors + description: Paste stack traces, request IDs, or screenshots. Redact secrets. + + - type: checkboxes + id: checks + attributes: + label: Confirmation + options: + - label: I searched existing issues and did not find a duplicate. + required: true + - label: I removed API keys, tokens, and sensitive data from this report. + required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..885e3ed --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,11 @@ +blank_issues_enabled: false +contact_links: + - name: Security report + url: https://github.com/NodeByteLTD/ByteSend/blob/main/SECURITY.md + about: Please report vulnerabilities privately. + - name: Community support (Discord) + url: https://discord.gg/xqkqzVRC4S + about: Ask questions and get help from the community. + - name: Documentation + url: https://docs.bytesend.cloud + about: Read guides, API references, and self-hosting docs. diff --git a/.github/ISSUE_TEMPLATE/docs.yml b/.github/ISSUE_TEMPLATE/docs.yml new file mode 100644 index 0000000..128327c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/docs.yml @@ -0,0 +1,29 @@ +name: Documentation issue +description: Report missing, incorrect, or unclear docs. +title: "docs: " +labels: ["documentation", "needs-triage"] +body: + - type: input + id: page + attributes: + label: Docs page / file + placeholder: https://docs.bytesend.cloud/... or apps/docs/... + validations: + required: true + + - type: textarea + id: issue + attributes: + label: What is wrong or missing? + validations: + required: true + + - type: textarea + id: expected + attributes: + label: What should the docs say? + + - type: textarea + id: context + attributes: + label: Extra context diff --git a/.github/ISSUE_TEMPLATE/feature.yml b/.github/ISSUE_TEMPLATE/feature.yml new file mode 100644 index 0000000..e62deb0 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature.yml @@ -0,0 +1,49 @@ +name: Feature request +description: Suggest a new feature or improvement. +title: "feat: " +labels: ["enhancement", "needs-triage"] +body: + - type: markdown + attributes: + value: | + Thanks for the suggestion. Help us understand the problem first, then the proposed solution. + + - type: textarea + id: problem + attributes: + label: Problem statement + description: What problem are you trying to solve? + validations: + required: true + + - type: textarea + id: proposal + attributes: + label: Proposed solution + description: Describe the behavior you want. + validations: + required: true + + - type: textarea + id: alternatives + attributes: + label: Alternatives considered + + - type: dropdown + id: impact + attributes: + label: Expected impact + options: + - Low + - Medium + - High + validations: + required: true + + - type: checkboxes + id: checks + attributes: + label: Confirmation + options: + - label: I searched existing issues and discussions for duplicates. + required: true diff --git a/.github/ISSUE_TEMPLATE/marketing.yml b/.github/ISSUE_TEMPLATE/marketing.yml index 17faadd..3666103 100644 --- a/.github/ISSUE_TEMPLATE/marketing.yml +++ b/.github/ISSUE_TEMPLATE/marketing.yml @@ -1,23 +1,60 @@ -name: Marketing Issue -description: Issue relataed to Marketing -labels: ["marketing"] +name: Marketing website issue +description: Report a bug or UX/content issue in the public marketing site. +title: "marketing: " +labels: ["marketing", "needs-triage"] body: - type: markdown attributes: value: | - Thanks for taking the time to create this issue + Thanks for reporting a marketing site issue. + + - type: input + id: page + attributes: + label: Affected page URL + placeholder: https://bytesend.cloud/ + validations: + required: true + - type: textarea - id: what-happened + id: description attributes: label: What happened? - placeholder: Tell us what you see! validations: required: true + + - type: textarea + id: steps + attributes: + label: Steps to reproduce + value: | + 1. Open ... + 2. Click ... + 3. Observe ... + validations: + required: true + - type: textarea - id: replication + id: expected + attributes: + label: Expected behavior + validations: + required: true + + - type: dropdown + id: browser attributes: - label: Replication Steps - description: Provide clear steps as to how this happened - value: "1. First click this \n2. Navigate to this \n3. Click this \n4. See this" + label: Browser + options: + - Chrome + - Firefox + - Safari + - Edge + - Other validations: - required: false \ No newline at end of file + required: true + + - type: textarea + id: screenshots + attributes: + label: Screenshots or recordings \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/smtp.yml b/.github/ISSUE_TEMPLATE/smtp.yml index 1b65f2e..62a84e3 100644 --- a/.github/ISSUE_TEMPLATE/smtp.yml +++ b/.github/ISSUE_TEMPLATE/smtp.yml @@ -1,23 +1,91 @@ -name: SMTP Issue -description: Issue relataed to SMTP -labels: ["smtp"] +name: SMTP relay issue +description: Report an SMTP server issue (auth, TLS, relay, ports, delivery behavior). +title: "smtp: " +labels: ["smtp", "needs-triage"] body: - type: markdown attributes: value: | - Thanks for taking the time to create this issue + Thanks for reporting an SMTP issue. Include as much operational detail as possible. + - type: input + id: version + attributes: + label: Version / commit + placeholder: v0.2.5 or commit SHA + validations: + required: true + + - type: dropdown + id: deployment + attributes: + label: Deployment type + options: + - ByteSend Cloud SMTP + - Self-hosted SMTP + default: 1 + validations: + required: true + + - type: dropdown + id: tls_mode + attributes: + label: TLS mode + options: + - none + - manual + - unknown + default: 2 + + - type: checkboxes + id: ports + attributes: + label: Affected port(s) + options: + - label: 25 + - label: 587 + - label: 2587 + - label: 465 + - label: 2465 - type: textarea - id: what-happened + id: description attributes: label: What happened? - placeholder: Tell us what you see! validations: required: true + - type: textarea - id: replication + id: steps attributes: - label: Replication Steps - description: Provide clear steps as to how this happened - value: "1. First click this \n2. Navigate to this \n3. Click this \n4. See this" + label: Steps to reproduce + value: | + 1. Configure SMTP client with ... + 2. Connect using ... + 3. Authenticate with ... + 4. Observe ... validations: - required: false \ No newline at end of file + required: true + + - type: textarea + id: expected + attributes: + label: Expected behavior + validations: + required: true + + - type: textarea + id: logs + attributes: + label: SMTP server logs / client errors + description: Include protocol error text and redact keys/tokens. + + - type: checkboxes + id: checks + attributes: + label: Confirmation + options: + - label: I used a valid API key as SMTP password. + required: true + - label: I verified the SMTP username matches my team settings (or default bytesend). + required: true + - label: I removed secrets from logs and screenshots. + required: true \ No newline at end of file diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..5a4158a --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,36 @@ +## Summary + +Describe what changed and why. + +## Type of Change + +- [ ] Bug fix +- [ ] New feature +- [ ] Breaking change +- [ ] Documentation update +- [ ] Chore / maintenance + +## Testing + +List what you ran: + +- [ ] `pnpm lint` +- [ ] `pnpm build` +- [ ] Relevant tests for changed area + +Commands/results: + +```txt +Paste test output or brief notes here. +``` + +## Screenshots / Evidence (if applicable) + +Add screenshots, recordings, or logs. + +## Checklist + +- [ ] I linked related issue(s) +- [ ] I updated docs where needed +- [ ] I updated changelog for user-facing changes +- [ ] I removed secrets from code, logs, and screenshots diff --git a/.gitignore b/.gitignore index eb4071b..d7a95f0 100644 --- a/.gitignore +++ b/.gitignore @@ -14,7 +14,6 @@ node_modules .env.selfhost .docs .docker -.references # Testing coverage diff --git a/.references/README.md b/.references/README.md new file mode 100644 index 0000000..544f3ff --- /dev/null +++ b/.references/README.md @@ -0,0 +1,20 @@ +# ByteSend Internal References + +This folder contains technical reference docs for maintainers and contributors. + +## Documents + +- webhook-architecture.md + - Event emission, queue processing, retries, signatures, and payload contracts +- smtp-auth-and-operations.md + - SMTP relay auth flow, custom username behavior, TLS modes, port strategy, and troubleshooting +- release-playbook.md + - Practical release checklist from changelog prep to tags and GitHub release publication +- repository-governance.md + - Contributor workflow, issue/PR templates, and community health files + +## Usage Guidance + +- Keep references implementation-aware and code-grounded. +- Update docs in this folder when changing architecture or operations. +- Prefer adding "last reviewed" dates for high-churn systems. diff --git a/.references/release-playbook.md b/.references/release-playbook.md new file mode 100644 index 0000000..21f5d99 --- /dev/null +++ b/.references/release-playbook.md @@ -0,0 +1,65 @@ +# Release Playbook + +Last reviewed: 2026-05-09 + +## Goal + +Provide a repeatable release process for ByteSend tags and release notes. + +## Branch and Tag Context + +- Active development branch: develop +- Default branch: main +- Release tags: vX.Y.Z + +## Pre-Release Checklist + +1. Ensure working tree is clean. +2. Ensure develop is pushed and up to date. +3. Confirm commits since latest tag: + - git log --oneline ..HEAD +4. Verify changelog has: + - New version section with date + - Accurate Added/Changed/Fixed entries + - Updated compare links at bottom +5. Run critical validation: + - pnpm build + - Targeted tests for changed areas + +## Changelog Link Rules + +At minimum keep these links correct: + +- [Unreleased] should compare from latest released tag to HEAD +- [current release] should compare previous tag to current tag + +Example after releasing v0.2.5: + +- [Unreleased]: compare/v0.2.5...HEAD +- [0.2.5]: compare/v0.2.4...v0.2.5 + +## Tag and Publish Steps + +1. Commit release prep changes: + - git add CHANGELOG.md + - git commit -m "chore(release): prepare vX.Y.Z" +2. Create annotated tag: + - git tag -a vX.Y.Z -m "vX.Y.Z" +3. Push branch and tag: + - git push origin develop + - git push origin vX.Y.Z +4. Create GitHub release: + - gh release create vX.Y.Z --title "vX.Y.Z" --generate-notes + +## Suggested Versioning Heuristics + +- Patch (X.Y.Z+1): fixes, docs, CI/workflow changes, compatibility improvements +- Minor (X.Y+1.0): notable user-facing features, new APIs, expanded capability +- Major (X+1.0.0): intentional breaking changes + +## Post-Release Checks + +1. Confirm tag exists on remote. +2. Confirm GitHub release created with expected notes. +3. Verify changelog compare links render correctly. +4. Announce release in docs/channels if applicable. diff --git a/.references/repository-governance.md b/.references/repository-governance.md new file mode 100644 index 0000000..989683e --- /dev/null +++ b/.references/repository-governance.md @@ -0,0 +1,62 @@ +# Repository Governance Reference + +Last reviewed: 2026-05-09 + +## Purpose + +This document maps repository-level governance files so maintainers can keep contributor and security processes consistent. + +## Community Health Files + +Root-level: + +- SECURITY.md +- CODE_OF_CONDUCT.md +- CONTRIBUTING.md +- SUPPORT.md + +GitHub-level: + +- .github/PULL_REQUEST_TEMPLATE.md +- .github/ISSUE_TEMPLATE/bug.yml +- .github/ISSUE_TEMPLATE/smtp.yml +- .github/ISSUE_TEMPLATE/marketing.yml +- .github/ISSUE_TEMPLATE/feature.yml +- .github/ISSUE_TEMPLATE/docs.yml +- .github/ISSUE_TEMPLATE/config.yml + +## Triage Labels Referenced by Templates + +Current templates rely on: + +- bug +- smtp +- marketing +- enhancement +- documentation +- needs-triage + +Keep repository labels aligned with template expectations. + +## Maintenance Checklist + +Run this checklist after major workflow or process changes: + +1. SECURITY.md contact channel still valid +2. CONTRIBUTING.md setup commands still accurate +3. Issue template fields still match current product areas +4. PR template checklist reflects required CI checks +5. README links to governance docs remain valid + +## Security Reporting Rule + +Security vulnerabilities should be reported privately per SECURITY.md and not through public issue templates. + +## When to Update + +Update governance references when: + +- You add or remove issue templates +- You change support/security contact paths +- You modify expected PR quality gates +- You change branch/release process semantics diff --git a/.references/smtp-auth-and-operations.md b/.references/smtp-auth-and-operations.md new file mode 100644 index 0000000..330c0a6 --- /dev/null +++ b/.references/smtp-auth-and-operations.md @@ -0,0 +1,90 @@ +# SMTP Auth and Operations Reference + +Last reviewed: 2026-05-09 + +## Scope + +This document explains how the SMTP relay authenticates clients, routes messages, and should be monitored in production. + +Primary files: + +- apps/smtp-server/src/server.ts +- apps/web/src/server/public-api/api/smtp/smtp-auth.ts + +## Authentication Flow + +1. SMTP client connects to relay on one of the SMTP ports. +2. Relay receives username/password in AUTH. +3. Relay sends a POST request to /api/v1/smtp/auth on ByteSend API with: + - username + - password (API key) +4. API resolves team by API key and checks expected username: + - expected = team.smtpUsername ?? SMTP_USER +5. API returns 200 valid or 401 invalid. + +## Custom Username Compatibility + +The relay builds username candidates in this order: + +1. Provided SMTP username (trimmed) +2. Legacy fallback from SMTP_AUTH_USERNAME env var (default bytesend) + +It attempts remote auth against each candidate until one succeeds. + +This keeps compatibility for: + +- Teams using new per-team usernames +- Older clients still using the legacy default username + +## Port and TLS Behavior + +SMTP plain ports (always): + +- 25 +- 587 +- 2587 + +Implicit TLS ports (manual TLS mode only): + +- 465 +- 2465 + +TLS mode values: + +- none: STARTTLS disabled, insecure auth allowed +- manual: cert/key loaded and STARTTLS enabled on plain ports + +## Health Monitoring Strategy + +The relay does not expose an HTTP health endpoint on a separate port. + +Recommended monitoring for status pages: + +- TCP checks against 25, 587, 2587 +- Additional checks against 465 and 2465 when SMTP_TLS_MODE=manual + +Optional deeper synthetic checks: + +- SMTP handshake and AUTH probe with test API key +- End-to-end send to a controlled mailbox + +## Certificate Reload Behavior + +In manual TLS mode, certificate files are watched. +When key/cert files change, secure context is reloaded without full process restart. + +## Common Failure Modes + +- Invalid API key (password) sent by SMTP client +- Username mismatch with team SMTP username +- TLS misconfiguration in manual mode (missing/unreadable cert paths) +- Base URL misconfigured, causing auth request failures + +## Debug Checklist + +1. Confirm BYTESEND_BASE_URL points to the intended API instance. +2. Verify team SMTP username in dashboard dev settings. +3. Verify SMTP_AUTH_USERNAME fallback usage for legacy clients. +4. Confirm TLS mode and cert path validity when using manual mode. +5. Check relay logs for auth rejection vs upstream request failures. +6. Confirm target ports are reachable from client and monitoring provider. diff --git a/.references/webhook-architecture.md b/.references/webhook-architecture.md new file mode 100644 index 0000000..269729f --- /dev/null +++ b/.references/webhook-architecture.md @@ -0,0 +1,476 @@ +# Webhook Architecture + +This document explains the webhook system architecture, including how events are emitted, queued, delivered, and displayed. + +Last reviewed: 2026-05-09 + +## Architecture Diagram + +``` +┌─────────────────────────────────────────────────────────────────────────────────────┐ +│ EVENT SOURCES │ +├─────────────────────┬─────────────────────┬─────────────────────────────────────────┤ +│ Email Service │ Contact Service │ Domain Service │ +│ (SES callbacks) │ (CRUD operations) │ (verification, etc.) │ +└─────────┬───────────┴──────────┬──────────┴──────────────────┬──────────────────────┘ + │ │ │ + │ ▼ │ + │ ┌───────────────────────┐ │ + └────────►│ WebhookService.emit │◄─────────────────┘ + │ (teamId, type, │ + │ payload) │ + └───────────┬───────────┘ + │ + ┌───────────▼───────────┐ + │ Find Active Webhooks │ + │ matching event type │ + └───────────┬───────────┘ + │ + ┌─────────────────┼─────────────────┐ + ▼ ▼ ▼ + ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ + │ Webhook A │ │ Webhook B │ │ Webhook C │ + └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ + │ │ │ + ▼ ▼ ▼ +┌─────────────────────────────────────────────────────────────────────────────────────┐ +│ PostgreSQL Database │ +│ ┌─────────────────────────────────────────────────────────────────────────────┐ │ +│ │ WebhookCall (one per matching webhook) │ │ +│ │ ├── status: PENDING │ │ +│ │ ├── payload: { event data only } │ │ +│ │ └── attempt: 0 │ │ +│ └─────────────────────────────────────────────────────────────────────────────┘ │ +└─────────────────────────────────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────────────────────────────┐ +│ Redis + BullMQ │ +│ ┌─────────────────────────────────────────────────────────────────────────────┐ │ +│ │ WEBHOOK_DISPATCH_QUEUE │ │ +│ │ ├── Job: { callId: "call_abc", teamId: 123 } │ │ +│ │ ├── Job: { callId: "call_def", teamId: 123 } │ │ +│ │ └── Job: { callId: "call_ghi", teamId: 456 } │ │ +│ └─────────────────────────────────────────────────────────────────────────────┘ │ +└─────────────────────────────────────────────────────────────────────────────────────┘ + │ + │ BullMQ Worker (concurrency: 25) + ▼ + ┌───────────────────────┐ + │ processWebhookCall │ + └───────────┬───────────┘ + │ + ┌───────────▼───────────┐ + │ Acquire Redis Lock │──────┐ + │ (per webhook ID) │ │ Lock failed + └───────────┬───────────┘ │ + │ Lock acquired ▼ + │ ┌─────────────┐ + ┌───────────▼──────┐ │ Retry later │ + │ Check webhook │ └─────────────┘ + │ status = ACTIVE? │ + └───────────┬──────┘ + Yes │ No + ┌───────────┘ └──────────────┐ + ▼ ▼ + ┌─────────────────┐ ┌─────────────────┐ + │ buildPayload │ │ Mark call as │ + │ (wrap event │ │ DISCARDED │ + │ data) │ └─────────────────┘ + └────────┬────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────────────────────────────┐ +│ HTTP POST Request │ +│ ┌─────────────────────────────────────────────────────────────────────────────┐ │ +│ │ Headers: │ │ +│ │ ├── X-ByteSend-Signature: v1= │ │ +│ │ ├── X-ByteSend-Timestamp: 1705312200000 │ │ +│ │ ├── X-ByteSend-Event: email.delivered │ │ +│ │ └── X-ByteSend-Call: call_abc123 │ │ +│ │ │ │ +│ │ Body: { │ │ +│ │ "id": "call_abc123", │ │ +│ │ "type": "email.delivered", │ │ +│ │ "version": "2026-01-18", │ │ +│ │ "createdAt": "...", │ │ +│ │ "teamId": 123, │ │ +│ │ "data": { ... event payload ... }, │ │ +│ │ "attempt": 1 │ │ +│ │ } │ │ +│ └─────────────────────────────────────────────────────────────────────────────┘ │ +└─────────────────────────────────────────────────────────────────────────────────────┘ + │ + ┌───────────┴───────────┐ + ▼ ▼ + ┌─────────────┐ ┌─────────────┐ + │ 2xx OK │ │ Non-2xx / │ + │ │ │ Timeout │ + └──────┬──────┘ └──────┬──────┘ + │ │ + ▼ ▼ + ┌─────────────────┐ ┌─────────────────────┐ + │ Mark DELIVERED │ │ Increment failures │ + │ Reset failures │ │ attempt < 6? │ + │ to 0 │ └──────────┬──────────┘ + └─────────────────┘ Yes │ No + ┌──────────┘ └──────────┐ + ▼ ▼ + ┌─────────────────┐ ┌─────────────────┐ + │ Mark PENDING │ │ Mark FAILED │ + │ Schedule retry │ │ │ + │ (exp. backoff) │ │ failures >= 30? │ + └─────────────────┘ └────────┬────────┘ + Yes │ No + ┌───────────┘ └────┐ + ▼ ▼ + ┌─────────────────┐ ┌──────────┐ + │ AUTO_DISABLE │ │ Done │ + │ webhook │ └──────────┘ + └─────────────────┘ +``` + +## Call Status State Machine + +``` + ┌──────────────────────────────────────┐ + │ │ + ▼ │ +┌─────────┐ enqueue ┌───────────┐ worker picks up ┌─────────────────┐ +│ (start) │ ──────────►│ PENDING │ ─────────────────►│ IN_PROGRESS │ +└─────────┘ └───────────┘ └────────┬────────┘ + ▲ │ + │ ┌────────────┼────────────┐ + │ │ │ │ + │ retry (attempt<6) │ │ │ + │ ▼ ▼ ▼ + │ ┌───────────┐ ┌───────────┐ ┌───────────┐ + └────────────│ (fail) │ │ SUCCESS │ │ WEBHOOK │ + └─────┬─────┘ └─────┬─────┘ │ INACTIVE │ + │ │ └─────┬─────┘ + │ │ │ + attempt >= 6 │ │ + │ ▼ ▼ + │ ┌───────────┐ ┌───────────┐ + └─────►│ FAILED │ │ DISCARDED │ + └───────────┘ └───────────┘ +``` + +## Overview + +The webhook system allows users to receive real-time HTTP notifications when events occur (emails sent, contacts created, domains verified, etc.). The system is built with reliability in mind, featuring: + +- Asynchronous delivery via BullMQ +- Exponential backoff with jitter for retries +- Automatic webhook disabling after consecutive failures +- Per-webhook locking to ensure ordered delivery +- HMAC signature verification for security + +## Core Components + +### 1. Database Models + +Located in `apps/web/prisma/schema.prisma`: + +``` +Webhook +├── id (cuid) +├── teamId (FK → Team) +├── url (endpoint URL) +├── secret (signing key, prefixed with "whsec_") +├── status (ACTIVE | PAUSED | AUTO_DISABLED) +├── eventTypes (string[] - empty means all events) +├── apiVersion (optional version string) +├── consecutiveFailures (counter for auto-disable) +├── lastFailureAt / lastSuccessAt (timestamps) +└── createdByUserId (FK → User) + +WebhookCall +├── id (cuid) +├── webhookId (FK → Webhook) +├── teamId (FK → Team) +├── type (event type, e.g., "email.delivered") +├── payload (JSON string - event data only) +├── status (PENDING | IN_PROGRESS | DELIVERED | FAILED | DISCARDED) +├── attempt (current attempt number) +├── nextAttemptAt (scheduled retry time) +├── lastError (error message if failed) +├── responseStatus / responseTimeMs / responseText +└── createdAt / updatedAt +``` + +### 2. Service Layer + +Located in `apps/web/src/server/service/webhook-service.ts`: + +- **WebhookService**: CRUD operations for webhooks and webhook calls +- **WebhookQueueService**: BullMQ queue management for async delivery + +### 3. Event Types + +Defined in `packages/lib/src/webhook/webhook-events.ts`: + +```typescript +// Contact events +"contact.created" | "contact.updated" | "contact.deleted"; + +// Domain events +"domain.created" | "domain.verified" | "domain.updated" | "domain.deleted"; + +// Email events +"email.queued" | + "email.sent" | + "email.delivery_delayed" | + "email.delivered" | + "email.bounced" | + "email.rejected" | + "email.rendering_failure" | + "email.complained" | + "email.failed" | + "email.cancelled" | + "email.suppressed" | + "email.opened" | + "email.clicked"; + +// Test events +("webhook.test"); +``` + +## Webhook Flow + +### Step 1: Event Emission + +When an event occurs in the system, `WebhookService.emit()` is called: + +```typescript +// Example: emitting an email.delivered event +await WebhookService.emit(teamId, "email.delivered", { + id: email.id, + status: "DELIVERED", + from: email.from, + to: email.to, + occurredAt: new Date().toISOString(), + // ... other fields +}); +``` + +### Step 2: Webhook Matching & Call Creation + +`emit()` performs the following: + +1. Finds all ACTIVE webhooks for the team that subscribe to the event type +2. Creates a `WebhookCall` record for each matching webhook (stores event data as `payload`) +3. Enqueues the call ID to BullMQ for async processing + +```typescript +// Webhook matching logic +const activeWebhooks = await db.webhook.findMany({ + where: { + teamId, + status: WebhookStatus.ACTIVE, + OR: [ + { eventTypes: { has: type } }, // Subscribed to this event + { eventTypes: { isEmpty: true } }, // Subscribed to ALL events + ], + }, +}); +``` + +### Step 3: Queue Processing + +The BullMQ worker (`processWebhookCall`) handles delivery: + +1. **Lock Acquisition**: Acquires a Redis lock per webhook to ensure ordered delivery +2. **Status Check**: Skips if webhook is no longer ACTIVE (marks call as DISCARDED) +3. **Payload Building**: Wraps the stored event data in the full payload structure +4. **HTTP POST**: Sends signed request to the webhook URL +5. **Result Handling**: Updates call status and webhook metrics + +### Step 4: Payload Structure + +**Important**: The stored `WebhookCall.payload` contains only the event data. The actual HTTP request body is built at delivery time by `buildPayload()`: + +```typescript +// Stored in WebhookCall.payload (event data only): +{ + "id": "email_123", + "status": "DELIVERED", + "from": "sender@example.com", + "to": ["recipient@example.com"], + "occurredAt": "2024-01-15T10:30:00Z" +} + +// Actual payload sent to webhook endpoint: +{ + "id": "call_abc123", // WebhookCall ID + "type": "email.delivered", // Event type + "version": "2026-01-18", // API version + "createdAt": "2024-01-15T10:30:00Z", + "teamId": 123, + "data": { // Original event data nested here + "id": "email_123", + "status": "DELIVERED", + "from": "sender@example.com", + "to": ["recipient@example.com"], + "occurredAt": "2024-01-15T10:30:00Z" + }, + "attempt": 1 +} +``` + +### Step 5: Request Signing + +Each request includes security headers for verification: + +``` +Content-Type: application/json +User-Agent: ByteSend-Webhook/1.0 +X-ByteSend-Event: email.delivered +X-ByteSend-Call: call_abc123 +X-ByteSend-Timestamp: 1705312200000 +X-ByteSend-Signature: v1= +X-ByteSend-Retry: false +``` + +Signature computation: + +```typescript +const signature = HMAC_SHA256(secret, `${timestamp}.${JSON.stringify(body)}`); +// Format: "v1=" + hex(signature) +``` + +## Retry & Failure Handling + +### Retry Configuration + +```typescript +const WEBHOOK_MAX_ATTEMPTS = 6; +const WEBHOOK_BASE_BACKOFF_MS = 5_000; // 5 seconds +const WEBHOOK_AUTO_DISABLE_THRESHOLD = 30; +``` + +### Backoff Schedule (approximate) + +| Attempt | Delay (base) | With Jitter | +| ------- | ------------ | ----------- | +| 1 | 5s | 5-6.5s | +| 2 | 10s | 10-13s | +| 3 | 20s | 20-26s | +| 4 | 40s | 40-52s | +| 5 | 80s | 80-104s | +| 6 | 160s | 160-208s | + +### Auto-Disable + +After 30 consecutive failures across any calls, the webhook is automatically set to `AUTO_DISABLED` status. This prevents continued delivery attempts to consistently failing endpoints. + +### Call Status Flow + +``` +PENDING → IN_PROGRESS → DELIVERED (success) + → PENDING (retry on failure, attempts < 6) + → FAILED (max attempts reached) + → DISCARDED (webhook disabled/paused) +``` + +## SDK Webhook Verification + +Located in `packages/sdk/src/webhooks.ts`: + +```typescript +import { ByteSend } from "bytesend"; + +const bytesend = new ByteSend("us_api_key"); +const webhooks = bytesend.webhooks("whsec_your_secret"); + +// Option 1: Verify only (returns boolean) +const isValid = webhooks.verify(rawBody, { headers: request.headers }); + +// Option 2: Verify and parse (throws on invalid) +const event = webhooks.constructEvent(rawBody, { headers: request.headers }); + +if (event.type === "email.delivered") { + console.log(event.data.to); // Type-safe access +} +``` + +## UI Payload Display + +The webhook call details UI (`apps/web/src/app/(dashboard)/webhooks/[webhookId]/webhook-call-details.tsx`) reconstructs the full payload for display, matching what was actually sent to the endpoint. This uses the same structure as `buildPayload()` in the service layer. + +## Important Files + +| File | Purpose | +| ------------------------------------------------ | --------------------------- | +| `apps/web/prisma/schema.prisma` | Database models | +| `apps/web/src/server/service/webhook-service.ts` | Core service & queue worker | +| `apps/web/src/server/api/routers/webhook.ts` | TRPC API routes | +| `apps/web/src/lib/constants/plans.ts` | Webhook limits per plan | +| `packages/lib/src/webhook/webhook-events.ts` | Event type definitions | +| `packages/sdk/src/webhooks.ts` | SDK verification utilities | +| `apps/web/src/app/(dashboard)/webhooks/` | UI components | + +## Configuration Constants + +```typescript +// apps/web/src/server/service/webhook-service.ts +const WEBHOOK_DISPATCH_CONCURRENCY = 25; // Parallel workers +const WEBHOOK_MAX_ATTEMPTS = 6; // Max delivery attempts +const WEBHOOK_BASE_BACKOFF_MS = 5_000; // Initial retry delay +const WEBHOOK_LOCK_TTL_MS = 15_000; // Redis lock TTL +const WEBHOOK_LOCK_RETRY_DELAY_MS = 2_000; // Lock retry delay +const WEBHOOK_AUTO_DISABLE_THRESHOLD = 30; // Failures before disable +const WEBHOOK_REQUEST_TIMEOUT_MS = 10_000; // HTTP timeout +const WEBHOOK_RESPONSE_TEXT_LIMIT = 4_096; // Max response body stored +const WEBHOOK_EVENT_VERSION = "2026-01-18"; // Default API version +``` + +## Plan Limits + +```typescript +// apps/web/src/lib/constants/plans.ts +FREE: { + webhooks: 1; +} +HOBBY: { + webhooks: PLANS.HOBBY.limits.maxWebhooks; +} +LITE: { + webhooks: PLANS.LITE.limits.maxWebhooks; +} +BASIC: { + webhooks: PLANS.BASIC.limits.maxWebhooks; +} +LIFETIME: { + webhooks: PLANS.LIFETIME.limits.maxWebhooks; +} +``` + +## Operational Checklist + +Use this quick checklist when debugging production webhook delivery: + +1. Confirm webhook status is `ACTIVE` (not `PAUSED` or `AUTO_DISABLED`) +2. Verify endpoint availability and response time (< 10s timeout) +3. Validate signature handling with current secret (`whsec_...`) +4. Check `WebhookCall` status progression (`PENDING -> IN_PROGRESS -> DELIVERED/FAILED`) +5. Inspect `consecutiveFailures` for auto-disable risk +6. Confirm queue/worker health in Redis and BullMQ + +## Common Failure Modes + +- Invalid signature verification due to parsing/serialization mismatch +- Endpoint returning non-2xx for retriable transient errors +- Worker backlog increasing because endpoint latency spikes +- Webhook silently discarded after webhook status changes to non-active +- Replay-protection windows too strict on receiver side + +## Change Safety Notes + +When changing webhook behavior, verify all of the following: + +- Payload shape remains backward-compatible or versioned +- Signature input string remains stable +- Retry/backoff constants are documented and communicated +- UI payload preview still mirrors transmitted payload +- SDK verification utilities still parse headers/body consistently diff --git a/CHANGELOG.md b/CHANGELOG.md index 3064f1d..fd8b010 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,44 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 --- +## [0.2.5] - 2026-05-09 + +### Added + +#### CI / Automation +- **Issue summary workflow** — added `.github/workflows/issue-summary.yml` to automatically summarize newly opened issues +- **Stale cleanup workflow** — added `.github/workflows/stale-cleanup.yml` to clean up inactive issues and pull requests +- **CodeQL workflow** — introduced `.github/workflows/codeql.yml` and enabled `develop` branch triggers + +### Changed + +#### SMTP Server +- **SMTP server vendored into monorepo** — `apps/smtp-server` is now tracked directly in this repository (no gitlink/submodule-style entry), simplifying versioning and release consistency +- **Authentication compatibility fallback** — SMTP auth now supports the API-driven custom team username flow while retaining a legacy fallback username candidate for older client configurations + +#### Documentation +- **SMTP docs refreshed for monorepo paths** — clone/build/deployment documentation now references `NodeByteLTD/ByteSend` and `apps/smtp-server` paths throughout +- **SMTP quickstart clarified** — get-started docs now direct users to use their configured SMTP username (default `bytesend`) rather than implying only a fixed username + +#### Workflows +- **PR labeling workflow rename** — renamed the workflow file to `label-prs.yml` +- **Label action token update** — updated token reference in `.github/workflows/label.yml` +- **Website test workflow tuning** — adjusted website test workflow behavior +- **Docker publish workflow update** — updated `.github/workflows/docker-publish.yml` + +### Fixed + +#### Suppressions +- **Suppression removal reliability** — improved suppression deletion flow to handle non-canonical casing/inputs more robustly in dashboard and backend paths + +#### Limits / Usage +- **Usage limit consistency** — fixed plan usage limit handling to align dashboard/service behavior with shared plan constants + +#### Marketing Site +- **Contact CTA destination** — changed the marketing contact link from email to Discord + +--- + ## [0.2.4] - 2026-05-08 ### Added @@ -393,7 +431,9 @@ Initial public beta release of ByteSend — an all-in-one email infrastructure p --- -[Unreleased]: https://github.com/nodebyte/bytesend/compare/v0.2.3...HEAD +[Unreleased]: https://github.com/nodebyte/bytesend/compare/v0.2.5...HEAD +[0.2.5]: https://github.com/nodebyte/bytesend/compare/v0.2.4...v0.2.5 +[0.2.4]: https://github.com/nodebyte/bytesend/compare/v0.2.3...v0.2.4 [0.2.3]: https://github.com/nodebyte/bytesend/compare/v0.2.2...v0.2.3 [0.2.2]: https://github.com/nodebyte/bytesend/compare/v0.2.1...v0.2.2 [0.2.1]: https://github.com/nodebyte/bytesend/compare/v0.2.0...v0.2.1 diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..ce9392a --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,72 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment include: + +- Demonstrating empathy and kindness toward other people +- Being respectful of differing opinions, viewpoints, and experiences +- Giving and gracefully accepting constructive feedback +- Taking responsibility and apologizing to those affected by our mistakes +- Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +- The use of sexualized language or imagery, and sexual attention or + advances of any kind +- Trolling, insulting or derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or email + address, without their explicit permission +- Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to behavior that they deem inappropriate, threatening, offensive, +or harmful. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders at support@bytesend.cloud. All complaints will +be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +1. Correction +2. Warning +3. Temporary Ban +4. Permanent Ban + +## Attribution + +This Code of Conduct is adapted from the Contributor Covenant, version 2.1, +available at: +https://www.contributor-covenant.org/version/2/1/code_of_conduct.html diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..5a5e9e6 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,86 @@ +# Contributing to ByteSend + +Thanks for your interest in contributing. + +## Before You Start + +- Read the Code of Conduct in `CODE_OF_CONDUCT.md` +- Check open issues and pull requests to avoid duplicate work +- For security vulnerabilities, follow `SECURITY.md` (do not post publicly) + +## Development Setup + +Prerequisites: + +- Node.js 20.19+ +- pnpm 9+ +- Docker (recommended for local infra) + +Setup: + +```bash +pnpm install +cp .env.example .env +pnpm dx:up +pnpm db:migrate-dev +pnpm dev +``` + +Useful commands: + +```bash +pnpm lint +pnpm build +pnpm test:web +pnpm test:web:all +pnpm test:infra:down +``` + +## Branching and Commits + +- Create a feature branch from `develop` +- Use clear commit messages (Conventional Commits preferred) + +Examples: + +- `fix(smtp): accept legacy username fallback` +- `docs(self-hosting): clarify smtp deployment path` + +## Pull Requests + +Please include: + +- What changed and why +- Screenshots or logs for UI/behavior changes +- Testing notes (what you ran) +- Any migration or rollout impact + +Checklist before opening a PR: + +- Lint passes +- Relevant tests pass +- Changelog updated when user-facing behavior changes +- No unrelated refactors mixed into the PR + +## Documentation Changes + +- Keep docs and code behavior aligned +- Prefer concise examples that copy/paste cleanly +- Update affected docs when config names or workflows change + +## Issue Reporting + +Use the issue templates and provide reproducible details. + +For bugs, include: + +- Deployment type (Cloud or self-hosted) +- Version/commit +- Expected vs actual behavior +- Steps to reproduce +- Logs/errors (with secrets removed) + +## Contributor License / Licensing Notes + +By contributing, you agree your contributions are provided under the repository +license (AGPL-3.0-only). diff --git a/README.md b/README.md index 293d18e..9fe60e7 100644 --- a/README.md +++ b/README.md @@ -73,6 +73,13 @@ See [docs.bytesend.cloud/get-started/local](https://docs.bytesend.cloud/get-star Please check existing issues before opening a new one. +See also: + +- [Contributing Guide](CONTRIBUTING.md) +- [Code of Conduct](CODE_OF_CONDUCT.md) +- [Security Policy](SECURITY.md) +- [Support](SUPPORT.md) + --- ## License diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..72bc799 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,55 @@ +# Security Policy + +Thanks for helping keep ByteSend and its users safe. + +## Supported Versions + +We provide security fixes for: + +| Version | Supported | +| --- | --- | +| Latest stable release | Yes | +| Previous stable release | Yes | +| `main` branch | Best effort | +| `develop` branch | Best effort | +| Older unsupported releases | No | + +## Reporting a Vulnerability + +Please do not open public GitHub issues for security vulnerabilities. + +Report privately by emailing: security@nodebyte.co.uk + +Use subject line: `[SECURITY] ` + +Include: + +- Affected component and version/commit +- Reproduction steps or proof of concept +- Impact and likely attack scenario +- Any suggested mitigation + +If needed, include encrypted details and share a secure channel for follow-up. + +## What to Expect + +- Initial acknowledgment within 72 hours +- Triage and severity assessment +- A plan for fix and coordinated disclosure +- Credit in release notes if you want attribution + +## Scope + +In-scope: + +- Remote code execution +- Auth bypass / privilege escalation +- Sensitive data exposure +- Injection vulnerabilities +- SSRF / major misconfiguration issues + +Out-of-scope (unless chainable to significant impact): + +- Missing best-practice headers only +- Self-XSS without escalation path +- Rate-limit bypass with no practical abuse impact diff --git a/SUPPORT.md b/SUPPORT.md new file mode 100644 index 0000000..5dba923 --- /dev/null +++ b/SUPPORT.md @@ -0,0 +1,19 @@ +# Support + +Need help with ByteSend? + +## Community Support + +- Discord: https://discord.gg/xqkqzVRC4S +- Docs: https://docs.bytesend.cloud + +## Commercial / Cloud Support + +- support@bytesend.cloud + +## Security Reports + +Do not open public issues for vulnerabilities. + +- See `SECURITY.md` +- Email: support@bytesend.cloud From 4cc6ea8b44a833c18dd40a747c08545ffd032dcb Mon Sep 17 00:00:00 2001 From: TheRealToxicDev Date: Sat, 9 May 2026 08:32:22 -0600 Subject: [PATCH 5/9] updated changelog --- CHANGELOG.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index fd8b010..1c6ab24 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **Stale cleanup workflow** — added `.github/workflows/stale-cleanup.yml` to clean up inactive issues and pull requests - **CodeQL workflow** — introduced `.github/workflows/codeql.yml` and enabled `develop` branch triggers +#### Community / Governance +- **Repository security policy** — added root `SECURITY.md` with supported versions, private reporting process, and response expectations +- **Code of Conduct** — added root `CODE_OF_CONDUCT.md` (Contributor Covenant v2.1) +- **Contributing guide** — added root `CONTRIBUTING.md` with development workflow, PR expectations, and testing checklist +- **Support guide** — added root `SUPPORT.md` with support channels and security-report routing + +#### GitHub Templates +- **PR template** — added `.github/PULL_REQUEST_TEMPLATE.md` to standardize change summaries, testing notes, and release-impact checks +- **Issue template config** — added `.github/ISSUE_TEMPLATE/config.yml` with contact links and blank-issue controls +- **New issue forms** — added `.github/ISSUE_TEMPLATE/feature.yml` and `.github/ISSUE_TEMPLATE/docs.yml` + ### Changed #### SMTP Server @@ -29,6 +40,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 #### Documentation - **SMTP docs refreshed for monorepo paths** — clone/build/deployment documentation now references `NodeByteLTD/ByteSend` and `apps/smtp-server` paths throughout - **SMTP quickstart clarified** — get-started docs now direct users to use their configured SMTP username (default `bytesend`) rather than implying only a fixed username +- **Core docs/readme refresh** — updated main README and docs navigation/content pages for current monorepo structure and self-hosting guidance (`apps/docs/README.md`, `apps/docs/docs.json`, local/docker/self-hosting guide pages) + +#### References +- **Internal references expanded** — added `.references/README.md`, `smtp-auth-and-operations.md`, `release-playbook.md`, and `repository-governance.md` +- **Webhook reference improvements** — expanded `.references/webhook-architecture.md` with operations checklist, common failure modes, and change-safety notes + +#### GitHub Templates +- **Issue form upgrades** — revamped bug/marketing/SMTP templates with clearer triage metadata, reproducibility fields, and validation checkboxes #### Workflows - **PR labeling workflow rename** — renamed the workflow file to `label-prs.yml` From 441defe871ddffd2c459ca04ac89a5bbd8a73190 Mon Sep 17 00:00:00 2001 From: TheRealToxicDev Date: Sat, 9 May 2026 08:39:14 -0600 Subject: [PATCH 6/9] more security hardening --- .github/workflows/website-test.yml | 3 + CHANGELOG.md | 10 ++++ apps/web/src/app/api/ses_callback/route.ts | 57 +++++++++++++++++-- apps/web/src/server/aws/ses.ts | 2 +- apps/web/src/server/service/domain-service.ts | 27 +++++++-- .../example/webhook-test-project/receiver.py | 12 +++- packages/scripts/stripe-seed.ts | 2 +- 7 files changed, 102 insertions(+), 11 deletions(-) diff --git a/.github/workflows/website-test.yml b/.github/workflows/website-test.yml index 8f33c8f..2a135f7 100644 --- a/.github/workflows/website-test.yml +++ b/.github/workflows/website-test.yml @@ -11,6 +11,9 @@ on: paths: - "apps/web/**" +permissions: + contents: read + jobs: web-tests: runs-on: ubuntu-latest diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c6ab24..01705c2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,6 +66,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 #### Marketing Site - **Contact CTA destination** — changed the marketing contact link from email to Discord +### Security + +- **SES callback SSRF hardening** — `apps/web/src/app/api/ses_callback/route.ts` no longer fetches user-provided `SubscribeURL` directly; it now constructs a trusted AWS SNS confirmation URL from validated `TopicArn`/`Token` components before issuing the request +- **SES callback log-safety hardening** — replaced ad-hoc request/parse logging in `apps/web/src/app/api/ses_callback/route.ts` with constant-format structured logs to avoid tainted-format-string risks from untrusted payload fields +- **SPF verification sanitization fix** — `apps/web/src/server/service/domain-service.ts` now parses SPF TXT mechanisms and validates `include:` domains (`amazonses.com` or subdomains) instead of broad substring checks +- **DKIM key strength upgrade** — `apps/web/src/server/aws/ses.ts` now generates 2048-bit RSA keys (up from 1024-bit) +- **Stripe seed secret logging removal** — `packages/scripts/stripe-seed.ts` no longer logs any portion of `STRIPE_SECRET_KEY` +- **Python webhook example exception exposure fix** — `packages/python-sdk/example/webhook-test-project/receiver.py` now returns a generic verification failure message and avoids exposing exception text to clients +- **Workflow least-privilege permissions** — `.github/workflows/website-test.yml` now sets explicit `permissions` with `contents: read` + --- ## [0.2.4] - 2026-05-08 diff --git a/apps/web/src/app/api/ses_callback/route.ts b/apps/web/src/app/api/ses_callback/route.ts index 70913c1..a1514b8 100644 --- a/apps/web/src/app/api/ses_callback/route.ts +++ b/apps/web/src/app/api/ses_callback/route.ts @@ -14,11 +14,19 @@ export async function GET() { export async function POST(req: Request) { const data = await req.json(); - console.log(data, data.Message); + logger.debug( + { + type: data?.Type, + topicArn: data?.TopicArn, + messageId: data?.MessageId, + hasMessage: typeof data?.Message === "string", + }, + "Received SES callback payload", + ); const isEventValid = await checkEventValidity(data); - console.log("Is event valid: ", isEventValid); + logger.debug({ isEventValid }, "SES callback topic validation result"); if (!isEventValid) { return Response.json({ data: "Event is not valid" }); @@ -42,7 +50,10 @@ export async function POST(req: Request) { return Response.json({ data: "Success" }); } catch (e) { - console.error(e); + logger.error( + { error: e instanceof Error ? e.message : "Unknown error" }, + "Failed to parse SES callback message", + ); return Response.json({ data: "Error is parsing hook" }); } } @@ -51,7 +62,9 @@ export async function POST(req: Request) { * Handles the subscription confirmation event. called only once for a webhook */ async function handleSubscription(message: any) { - await fetch(message.SubscribeURL, { + const subscribeUrl = buildSnsSubscribeConfirmUrl(message); + + await fetch(subscribeUrl, { method: "GET", }); @@ -80,6 +93,42 @@ async function handleSubscription(message: any) { return Response.json({ data: "Success" }); } +/** + * Build a trusted SNS subscription confirmation URL from message fields. + * We intentionally do not use message.SubscribeURL directly to prevent SSRF. + */ +function buildSnsSubscribeConfirmUrl(message: { + TopicArn?: string; + Token?: string; +}) { + const topicArn = message.TopicArn; + const token = message.Token; + + if (!topicArn || !token) { + throw new Error("Invalid SNS subscription payload"); + } + + const arnParts = topicArn.split(":"); + if (arnParts.length < 6 || arnParts[2] !== "sns") { + throw new Error("Invalid SNS TopicArn"); + } + + const partition = arnParts[1]; + const region = arnParts[3]; + + if (!region) { + throw new Error("SNS TopicArn is missing region"); + } + + const domain = partition === "aws-cn" ? "amazonaws.com.cn" : "amazonaws.com"; + const confirmUrl = new URL(`https://sns.${region}.${domain}/`); + confirmUrl.searchParams.set("Action", "ConfirmSubscription"); + confirmUrl.searchParams.set("TopicArn", topicArn); + confirmUrl.searchParams.set("Token", token); + + return confirmUrl.toString(); +} + /** * A simple check to ensure that the event is from the correct topic */ diff --git a/apps/web/src/server/aws/ses.ts b/apps/web/src/server/aws/ses.ts index 26adecd..7507560 100644 --- a/apps/web/src/server/aws/ses.ts +++ b/apps/web/src/server/aws/ses.ts @@ -60,7 +60,7 @@ function getSesClient(region: string) { function generateKeyPair() { const { privateKey, publicKey } = generateKeyPairSync("rsa", { - modulusLength: 1024, // Length of your key in bits + modulusLength: 2048, // Minimum recommended RSA key length publicKeyEncoding: { type: "spki", // Recommended to be 'spki' by the Node.js docs format: "pem", diff --git a/apps/web/src/server/service/domain-service.ts b/apps/web/src/server/service/domain-service.ts index e775f2d..b15bcc1 100644 --- a/apps/web/src/server/service/domain-service.ts +++ b/apps/web/src/server/service/domain-service.ts @@ -143,10 +143,29 @@ async function checkDkimDnsRecord( async function checkSpfDnsRecord(mailDomain: string): Promise { try { const records = await dnsResolveTxt(mailDomain); - const flat = records.flat().join(" "); - return flat.includes("v=spf1") && flat.includes("amazonses.com") - ? "found" - : "not_found"; + const spfRecords = records + .map((parts) => parts.join("")) + .map((record) => record.trim().toLowerCase()) + .filter((record) => record.startsWith("v=spf1")); + + const hasAmazonSesInclude = spfRecords.some((record) => { + const mechanisms = record.split(/\s+/).filter(Boolean); + + return mechanisms.some((mechanism) => { + const normalized = mechanism.replace(/^[+\-~?]/, ""); + if (!normalized.startsWith("include:")) { + return false; + } + + const includeDomain = normalized.slice("include:".length); + return ( + includeDomain === "amazonses.com" || + includeDomain.endsWith(".amazonses.com") + ); + }); + }); + + return hasAmazonSesInclude ? "found" : "not_found"; } catch { return "not_found"; } diff --git a/packages/python-sdk/example/webhook-test-project/receiver.py b/packages/python-sdk/example/webhook-test-project/receiver.py index 5dff477..8d0876a 100644 --- a/packages/python-sdk/example/webhook-test-project/receiver.py +++ b/packages/python-sdk/example/webhook-test-project/receiver.py @@ -22,7 +22,17 @@ def webhook() -> ResponseReturnValue: try: event = webhooks.construct_event(raw_body, headers=request.headers) except WebhookVerificationError as exc: - return jsonify({"ok": False, "code": exc.code, "message": str(exc)}), 400 + app.logger.warning("Webhook verification failed: %s", exc.code) + return ( + jsonify( + { + "ok": False, + "code": exc.code, + "message": "Webhook signature verification failed", + } + ), + 400, + ) print(f"Received event: {event['type']}") diff --git a/packages/scripts/stripe-seed.ts b/packages/scripts/stripe-seed.ts index d207f43..66b275f 100644 --- a/packages/scripts/stripe-seed.ts +++ b/packages/scripts/stripe-seed.ts @@ -27,7 +27,7 @@ async function main() { }); console.log(`📦 Environment : ${ENVIRONMENT}`); - console.log(`🔑 Stripe key : ${STRIPE_SECRET_KEY.slice(0, 20)}...`); + console.log("🔑 Stripe key : configured"); console.log("\n📝 Syncing plans to Stripe...\n"); const result = await syncPlansToStripe(stripe, ENVIRONMENT); From fc3f5a4458b0ff37f3088cfb249d7388e1ef0139 Mon Sep 17 00:00:00 2001 From: TheRealToxicDev Date: Sat, 9 May 2026 08:50:17 -0600 Subject: [PATCH 7/9] fix web test failure --- .github/workflows/website-test.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/website-test.yml b/.github/workflows/website-test.yml index 2a135f7..f4f079b 100644 --- a/.github/workflows/website-test.yml +++ b/.github/workflows/website-test.yml @@ -59,8 +59,6 @@ jobs: - name: Setup pnpm uses: pnpm/action-setup@v4 - with: - version: 8.9.0 - name: Setup Node uses: actions/setup-node@v4 From c5e477107e3e6b5a29ae548229c864dd07273d5b Mon Sep 17 00:00:00 2001 From: TheRealToxicDev Date: Sat, 9 May 2026 08:56:55 -0600 Subject: [PATCH 8/9] CWE fixes --- apps/web/src/app/api/ses_callback/route.ts | 52 ++++++++++++---------- 1 file changed, 29 insertions(+), 23 deletions(-) diff --git a/apps/web/src/app/api/ses_callback/route.ts b/apps/web/src/app/api/ses_callback/route.ts index a1514b8..dc59ee4 100644 --- a/apps/web/src/app/api/ses_callback/route.ts +++ b/apps/web/src/app/api/ses_callback/route.ts @@ -24,7 +24,8 @@ export async function POST(req: Request) { "Received SES callback payload", ); - const isEventValid = await checkEventValidity(data); + const trustedTopicArn = await getTrustedTopicArn(data?.TopicArn); + const isEventValid = trustedTopicArn !== null; logger.debug({ isEventValid }, "SES callback topic validation result"); @@ -33,7 +34,7 @@ export async function POST(req: Request) { } if (data.Type === "SubscriptionConfirmation") { - return handleSubscription(data); + return handleSubscription(data, trustedTopicArn); } let message = null; @@ -61,17 +62,19 @@ export async function POST(req: Request) { /** * Handles the subscription confirmation event. called only once for a webhook */ -async function handleSubscription(message: any) { - const subscribeUrl = buildSnsSubscribeConfirmUrl(message); +async function handleSubscription( + message: { Token?: string }, + trustedTopicArn: string, +) { + const subscribeUrl = buildSnsSubscribeConfirmUrl(trustedTopicArn, message.Token); await fetch(subscribeUrl, { method: "GET", }); - const topicArn = message.TopicArn as string; const setting = await db.sesSetting.findFirst({ where: { - topicArn, + topicArn: trustedTopicArn, }, }); @@ -97,14 +100,9 @@ async function handleSubscription(message: any) { * Build a trusted SNS subscription confirmation URL from message fields. * We intentionally do not use message.SubscribeURL directly to prevent SSRF. */ -function buildSnsSubscribeConfirmUrl(message: { - TopicArn?: string; - Token?: string; -}) { - const topicArn = message.TopicArn; - const token = message.Token; - - if (!topicArn || !token) { +function buildSnsSubscribeConfirmUrl(topicArn: string, token?: string) { + + if (!token) { throw new Error("Invalid SNS subscription payload"); } @@ -130,19 +128,27 @@ function buildSnsSubscribeConfirmUrl(message: { } /** - * A simple check to ensure that the event is from the correct topic + * Returns an exact TopicArn from server configuration if input matches. + * This keeps downstream URL construction anchored to trusted configuration. */ -async function checkEventValidity(message: SnsNotificationMessage) { - if (env.NODE_ENV === "development") { - return true; +async function getTrustedTopicArn(topicArn: SnsNotificationMessage["TopicArn"]) { + if (!topicArn || typeof topicArn !== "string") { + return null; } - const { TopicArn } = message; - const configuredTopicArn = await SesSettingsService.getTopicArns(); + const configuredTopicArns = await SesSettingsService.getTopicArns(); + const trustedTopicArn = configuredTopicArns.find((configured) => configured === topicArn); + + if (trustedTopicArn) { + return trustedTopicArn; + } - if (!configuredTopicArn.includes(TopicArn)) { - return false; + if (env.NODE_ENV === "development") { + logger.warn( + { topicArn }, + "SES callback TopicArn not configured in development", + ); } - return true; + return null; } From d9cb6c5626c52d913e8a1250f92b916ff44e2bec Mon Sep 17 00:00:00 2001 From: TheRealToxicDev Date: Sat, 9 May 2026 08:57:53 -0600 Subject: [PATCH 9/9] fix labeler --- .github/{workflows/label-prs.yml => labeler.yml} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .github/{workflows/label-prs.yml => labeler.yml} (100%) diff --git a/.github/workflows/label-prs.yml b/.github/labeler.yml similarity index 100% rename from .github/workflows/label-prs.yml rename to .github/labeler.yml