Vibecode beehiiv
track this build5 phases, 16 steps, beginner friendly0%You can build a newsletter CMS and send emails, but beehiiv's moat is deliverability, growth network, recommendations, ad marketplace, automations, analytics, and migrations.
You are building a lean indie version of beehiiv. Create the following project files first, then implement the application by following them. Keep the files updated as decisions change. Do not collapse this into a single README or prompt. ===== README.md ===== # beehiiv · indie build Build a small newsletter publisher with a public archive and a safe send ledger. Estimated effort: **multi-day**. Work `BUILD_PLAN.md` top to bottom · every phase ends in a check that has to pass before the next one starts. ## Stack | Part | Choice | Why | | --- | --- | --- | | Runtime | Python 3.12+ and Flask | A small local HTTP application with readable server-side handlers and no JavaScript build pipeline. | | Storage | SQLite through Python sqlite3 | Local ownership with explicit transactions and a portable backup path. | | Interface | Jinja HTML templates, CSS and vanilla JavaScript | Implement the specified screens directly with labelled controls and progressive enhancement. | | Verification | Python unittest and browser acceptance fixtures | Check invariants and the actual user workflow before the next phase. | | Focused libraries | markdown, bleach | Use these only for the specific file, parsing or provider operations named in the phases; freeze tested versions. | ## Before you start Have every one of these ready. The plan assumes them from step one. - [ ] **Python 3.12 or newer and a terminal** · Python is free; this local prototype requires no hosting subscription. - Why: The local backend, tests and storage use Python. - Get it: Install Python from python.org. Open a terminal in a new empty project folder. On Windows, use py -3 where this guide says python if python is not on PATH; on macOS/Linux use python3 if needed. Create .venv and activate it before installing packages. - Verify: python --version reports 3.12+ and python -c "import sqlite3" succeeds. - [ ] **A current desktop browser and text editor** · No paid service required for this local step. - Why: You need to view the local interface and edit generated project files. - Get it: Use an installed Chrome, Firefox or Edge browser. Open the empty project folder in your editor; open the terminal there, not in this catalog repository. - Verify: You can create a text file in the project folder and open browser developer tools. - [ ] **beehiiv acceptance sample** · No paid service required for this local step. - Why: This fixture makes the first end-to-end check reproducible. - Get it: Create synthetic sample data before implementation: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Save it under fixtures/ with the expected results in fixtures/README.md; use no real credentials or customer records. - Verify: The fixture files and expected outcomes exist and can be inspected without a vendor account. - [ ] **Confirm the bounded replacement** · No paid service required for this local step. - Why: The full commercial product is larger than this guide. - Get it: The deliverable is a small newsletter publisher with a public archive and a safe send ledger. Read every exclusion below. Indie mode runs locally; any public or shared use requires the product access and deployment gates first. - Verify: You can name the primary workflow and the vendor features this version deliberately leaves out. - [ ] **An SMTP relay and one verified test recipient** · Provider-specific relay fees and domain costs; no free tier or delivery guarantee is assumed. - Why: Outbound confirmations or replies need a delivery provider; a fake adapter covers automated tests. - Get it: Obtain SMTP host, port, username and password from your chosen relay dashboard under SMTP settings. Verify the sender/domain using that provider DNS instructions. Use only your own test recipient initially and record the actual plan and rate limit in OPERATIONS.md. - Verify: The supplied smtp_probe.py sends one labelled test message to your own inbox and reports the relay response without logging credentials. ## Quick start ```sh python -m venv .venv python -m pip install Flask Flask-WTF python-dotenv waitress tzdata markdown bleach python -m pip freeze > requirements.txt python -m flask --app app run --host 127.0.0.1 ``` Then copy `.env.example` to `.env` and fill in the values it documents. ## Honest limits This build deliberately does not replace: - Referral networks, paid subscriptions and domain reputation are not reproduced by this publisher. - This is a small newsletter publisher with a public archive and a safe send ledger; full beehiiv feature parity, vendor hosting and support are not included. - email deliverability - referral/recommendation network - ad network - automations - analytics - paid newsletter tooling - migrations If one of those is essential to you, that is the reason to keep paying for beehiiv, and the README should say so rather than pretend. ===== BRIEF.md ===== # Build brief · beehiiv The one-shot brief this plan expands. `BUILD_PLAN.md` (or `MILESTONES.md`) is the same sequence broken into steps and checks; where the two disagree, the plan wins. Build me a small newsletter publisher with a public archive and a safe send ledger as a bounded replacement for beehiiv. Build it in phases in the order below. Do not write the whole product in one pass. Finish the current phase, run its Done when checks, fix failures, then continue. Indie mode completes Phases 1-5. Phase 6 is required before shared or public deployment. ### Stack (fixed, do not substitute) - Runtime: Python 3.12+ and Flask. A small local HTTP application with readable server-side handlers and no JavaScript build pipeline. - Storage: SQLite through Python sqlite3. Local ownership with explicit transactions and a portable backup path. - Interface: Jinja HTML templates, CSS and vanilla JavaScript. Implement the specified screens directly with labelled controls and progressive enhancement. - Verification: Python unittest and browser acceptance fixtures. Check invariants and the actual user workflow before the next phase. - Focused libraries: markdown, bleach. Use these only for the specific file, parsing or provider operations named in the phases; freeze tested versions. ### Data model (create this before Phase 1) - posts(id,slug,title,body,state) - subscribers(id,email,status,consent_at,token_hash) - campaigns(id,post_id,state) - deliveries(id,campaign_id,subscriber_id,state,message_id) - suppressions(email,reason,at) - Use stable ids and explicit relationships; add auxiliary tables named by the phases before those phases use them. - Acceptance fixture: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. ### Prerequisites and configuration - Python 3.12 or newer and a terminal: Install Python from python.org. Open a terminal in a new empty project folder. On Windows, use py -3 where this guide says python if python is not on PATH; on macOS/Linux use python3 if needed. Create .venv and activate it before installing packages. Verify: python --version reports 3.12+ and python -c "import sqlite3" succeeds. Cost: Python is free; this local prototype requires no hosting subscription. - A current desktop browser and text editor: Use an installed Chrome, Firefox or Edge browser. Open the empty project folder in your editor; open the terminal there, not in this catalog repository. Verify: You can create a text file in the project folder and open browser developer tools. Cost: No paid service required for this local step. - beehiiv acceptance sample: Create synthetic sample data before implementation: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Save it under fixtures/ with the expected results in fixtures/README.md; use no real credentials or customer records. Verify: The fixture files and expected outcomes exist and can be inspected without a vendor account. Cost: No paid service required for this local step. - Confirm the bounded replacement: The deliverable is a small newsletter publisher with a public archive and a safe send ledger. Read every exclusion below. Indie mode runs locally; any public or shared use requires the product access and deployment gates first. Verify: You can name the primary workflow and the vendor features this version deliberately leaves out. Cost: No paid service required for this local step. - An SMTP relay and one verified test recipient: Obtain SMTP host, port, username and password from your chosen relay dashboard under SMTP settings. Verify the sender/domain using that provider DNS instructions. Use only your own test recipient initially and record the actual plan and rate limit in OPERATIONS.md. Verify: The supplied smtp_probe.py sends one labelled test message to your own inbox and reports the relay response without logging credentials. Cost: Provider-specific relay fees and domain costs; no free tier or delivery guarantee is assumed. - Configuration: DATA_DIR, SECRET_KEY, APP_MODE, SITE_URL, SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASSWORD, MAIL_FROM, MAIL_TEST_TO. Ship .env.example, replace placeholders and exclude secrets from git. ### Phase 1 · Local foundation and data contract Build: Create the runnable local foundation for a small newsletter publisher with a public archive and a safe send ledger, including the real schema and acceptance fixture. - Run the venv command first, then stop and activate it before running the remaining commands. Use your OS instructions: Windows .venv\Scripts\activate.bat in cmd, or .venv\Scripts\Activate.ps1 in PowerShell; macOS/Linux source .venv/bin/activate. Then install the listed packages. Create app.py exposing app, load .env with python-dotenv, and add a /healthz route. Freeze tested dependency versions to requirements.txt. Create .env manually from .env.example; replace SECRET_KEY before launch. Commands, after creating the named files: `python -m venv .venv`; `python -m pip install Flask Flask-WTF python-dotenv waitress tzdata markdown bleach`; `python -m pip freeze > requirements.txt`; `python -m flask --app app run --host 127.0.0.1`. - For database-backed state create schema.sql and db.py using this model: posts(id,slug,title,body,state); subscribers(id,email,status,consent_at,token_hash); campaigns(id,post_id,state); deliveries(id,campaign_id,subscriber_id,state,message_id); suppressions(email,reason,at). Add the auxiliary relationships explicitly used in later phases; use stable ids, foreign keys, parameterized values and transactions. For canonical files use atomic replacement and hashes instead. Implement python manage.py init and python manage.py seed to create only synthetic data: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Re-running init must not erase data. Commands, after creating the named files: `python manage.py init`; `python manage.py seed`. - Install Flask-WTF CSRF protection for forms and same-origin fetches, validate Host and Origin against SITE_URL, bound inputs and escape output. Deliberately public intake endpoints get bounded validation and rate limits; signed provider webhooks use signature checks instead of browser CSRF tokens. All other admin routes stay local until product authentication exists. When a later phase tests viewer/member permissions, implement the users, hashed passwords, expiring server sessions and role checks in this foundation first; product mode must never use a fabricated identity from request input. Add error, empty, keyboard-focus and retry states now. - Create providers/mail.py using smtplib with a timeout, verified TLS/STARTTLS and an EmailMessage. Refuse placeholder credentials and non-test recipients until the owner enables sending. Implement scripts/smtp_probe.py to send one labelled message only to MAIL_TEST_TO, and provide a fake adapter for tests. Store no password or full message body in logs. Commands, after creating the named files: `python scripts/smtp_probe.py`. - Trap: The Flask development server is for local development only. Loopback binding alone does not replace CSRF and origin validation. Done when: The documented start command serves /healthz and the initial screen at http://127.0.0.1:5000. Restarting preserves the seeded records or canonical files; running init again deletes nothing. A cross-origin state-changing request to an admin route is refused. Do not build yet: Do not start publication and consent until these checks pass. ### Phase 2 · Publication and consent Build: Publication and consent for beehiiv: Build a Markdown post editor with sanitized email/web previews and a public archive containing only published posts. - Build a Markdown post editor with sanitized email/web previews and a public archive containing only published posts. - Implement double-opt-in signup with expiring hashed tokens and a suppression list; send confirmation through the configured SMTP adapter. - Use One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Check: Only the confirmed fixture becomes eligible for a campaign. Then check: A draft post cannot be fetched from its guessed archive URL. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Commands, after creating the named files: `python -m unittest discover -s test`. - Trap: The archive and email are different outputs; a preview must show both. Done when: Only the confirmed fixture becomes eligible for a campaign. A draft post cannot be fetched from its guessed archive URL. Do not build yet: Do not start campaign preparation until these checks pass. ### Phase 3 · Campaign preparation Build: Campaign preparation for beehiiv: Freeze the post content and recipient ids when preparing a campaign and show an exact recipient preview before sending. - Freeze the post content and recipient ids when preparing a campaign and show an exact recipient preview before sending. - Add a plain-text part, visible unsubscribe link and List-Unsubscribe headers; recheck suppression immediately before each send. - Use One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Check: Unsubscribing after preparation but before send excludes the recipient. Then check: The email preview contains a functional unsubscribe action and no script tags. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Commands, after creating the named files: `python -m unittest discover -s test`. - Trap: Do not equate successful SMTP submission with inbox delivery or a legal compliance guarantee. Done when: Unsubscribing after preparation but before send excludes the recipient. The email preview contains a functional unsubscribe action and no script tags. Do not build yet: Do not start send and reconcile until these checks pass. ### Phase 4 · Send and reconcile Build: Send and reconcile for beehiiv: Use a unique campaign/subscriber delivery row, bounded rate and a worker lease; record accepted, failed and unknown outcomes. - Use a unique campaign/subscriber delivery row, bounded rate and a worker lease; record accepted, failed and unknown outcomes. - Pause on ambiguous connection loss after transmission; offer operator reconciliation rather than blindly resending. - Use One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Check: Restarting skips accepted delivery rows and preserves unknown rows for review. Then check: A failed recipient does not prevent remaining eligible recipients from being processed. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Commands, after creating the named files: `python -m unittest discover -s test`. - Trap: Referral networks, paid subscriptions and domain reputation are not reproduced by this publisher. Done when: Restarting skips accepted delivery rows and preserves unknown rows for review. A failed recipient does not prevent remaining eligible recipients from being processed. Do not build yet: Do not start portable delivery and clean-start proof until these checks pass. ### Phase 5 · Portable delivery and clean-start proof Build: Finish the beehiiv replacement with a documented first-run path and a recoverable export. - Document prerequisites, every configuration variable, data locations and the three domain workflows: Publication and consent; Campaign preparation; Send and reconcile. Include the exclusions, actual costs and source check date 2026-09-05. Commands shown earlier that reference project files are files the builder must implement before running them. - Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for beehiiv. Restore into a separate empty directory or isolated deployment, with all outbound actions and schedules disabled. Recreate this proof: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Compare ids/counts and open the result before recording the restore date. Never test a restore over the only live copy. - Use a new folder and only README instructions to reach the fixture outcome. Install from requirements.txt, initialize storage, run the tests and exercise the UI at 375px and 1280px; use keyboard-only controls and inspect browser errors. Record exactly what passed; do not mark unrun checks complete. Commands, after creating the named files: `python -m pip install -r requirements.txt`; `python -m unittest discover -s test`. - Trap: Export without an import or restore rehearsal is not verified portability. Done when: A new folder reaches the documented fixture outcome using only README instructions. A backup restored in isolation preserves the proof data and can be opened. Do not build yet: Do not start operate and share with access controls until these checks pass. ### Phase 6 · Operate and share with access controls (product-builder only) Build: Product-builder only: make a small newsletter publisher with a public archive and a safe send ledger operable for its stated audience before allowing remote access. - Add owner/member/viewer authorization as appropriate, password hashes through Werkzeug, expiring server-side sessions, CSRF and login rate limits. Add users, sessions and audit schema migrations plus an owner-init command prompting securely for its password. Enforce ownership on every private read/write/download and fail closed when product setup is incomplete. Existing learner or admin identities must use this same boundary. - Serve app:app with Waitress on loopback behind Caddy HTTPS. Configure trusted proxy headers narrowly, Secure/HttpOnly/SameSite cookies, upload limits, request ids and structured logs without private content. Run background jobs as a separate supervised process when the domain workflow requires them. Commands, after creating the named files: `waitress-serve --listen=127.0.0.1:5000 app:app`. - Add a scheduled encrypted off-host backup using this procedure: Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for beehiiv. Monitor health, disk space, failed jobs and backup age. Stop the service to test an alert; rehearse recovery with outbound effects disabled and record recovery time. Rotate any exposed credentials and require reconciliation before resuming queues. - Trap: Product mode is additional engineering, not a switch that makes a local prototype production-ready. Done when: An unauthenticated visitor cannot read private records, download private files or mutate the admin surface. A viewer cannot mutate data by making a direct request, and guessed ids cannot cross ownership boundaries. Stopping the service triggers the configured alert and the latest off-host backup restores the fixture in isolation. Do not build yet: Do not add new providers or vendor-scale features until the release gates are recorded. ### Out of scope (and why) - Referral networks, paid subscriptions and domain reputation are not reproduced by this publisher. - This is a small newsletter publisher with a public archive and a safe send ledger; full beehiiv feature parity, vendor hosting and support are not included. - email deliverability: retain the paid product if this capability is essential; it is outside this bounded build. - referral/recommendation network: retain the paid product if this capability is essential; it is outside this bounded build. - ad network: retain the paid product if this capability is essential; it is outside this bounded build. - automations: retain the paid product if this capability is essential; it is outside this bounded build. - analytics: retain the paid product if this capability is essential; it is outside this bounded build. - paid newsletter tooling: retain the paid product if this capability is essential; it is outside this bounded build. - migrations: retain the paid product if this capability is essential; it is outside this bounded build. ### README must contain - Exact install, configure, initialize, start, test and recovery commands for a clean folder. - The schema, fixture, acceptance results, private data locations and export format. - Every prerequisite and secret source, actual running costs and deliberately excluded capabilities. - An honest distinction between tests actually run and checks still awaiting real credentials or deployment. - Dependency documentation reviewed 2026-09-05: https://flask.palletsprojects.com/en/stable/installation/ ; https://docs.python.org/3/library/sqlite3.html ; https://flask-wtf.readthedocs.io/en/1.2.x/csrf/ ; https://docs.pylonsproject.org/projects/waitress/en/stable/usage.html ; https://docs.python.org/3/library/smtplib.html ; https://python-markdown.github.io/reference/ ; https://bleach.readthedocs.io/en/latest/clean.html. Recheck before upgrading; freeze the versions actually tested. ===== AGENTS.md ===== # Agent instructions · beehiiv indie build - Read `README.md` and `BUILD_PLAN.md` before writing code. The stack is fixed: Python 3.12+ and Flask, SQLite through Python sqlite3, Jinja HTML templates, CSS and vanilla JavaScript, Python unittest and browser acceptance fixtures, markdown, bleach. Do not substitute. - Work one phase at a time, in order. Do not start a phase until every "Done when" item of the previous one passes. - Prefer the fewest moving parts that satisfy the step. No frameworks, services or dependencies the plan does not name. - Secrets live in `.env`, never in source or logs. Keep `.env.example` current when a variable is introduced. - Do not invent cryptography, security guarantees, APIs or compliance claims. - Add a focused test for every destructive, security-sensitive or data-loss path the plan names. - Run the project checks before declaring a phase complete, and record any deliberate shortcut in the README under "Tradeoffs". ## Known traps - The Flask development server is for local development only. Loopback binding alone does not replace CSRF and origin validation. - The archive and email are different outputs; a preview must show both. - Do not equate successful SMTP submission with inbox delivery or a legal compliance guarantee. - Referral networks, paid subscriptions and domain reputation are not reproduced by this publisher. - Export without an import or restore rehearsal is not verified portability. ===== BUILD_PLAN.md ===== # Build plan · beehiiv Build a small newsletter publisher with a public archive and a safe send ledger. Phases are in dependency order. Each ends in a "Done when" list; treat an unticked item as a blocker, not a note. ## Phase 1 · Local foundation and data contract Create the runnable local foundation for a small newsletter publisher with a public archive and a safe send ledger, including the real schema and acceptance fixture. ### Steps 1. Create and start the local application Run the venv command first, then stop and activate it before running the remaining commands. Use your OS instructions: Windows .venv\Scripts\activate.bat in cmd, or .venv\Scripts\Activate.ps1 in PowerShell; macOS/Linux source .venv/bin/activate. Then install the listed packages. Create app.py exposing app, load .env with python-dotenv, and add a /healthz route. Freeze tested dependency versions to requirements.txt. Create .env manually from .env.example; replace SECRET_KEY before launch. Files: `app.py`, `requirements.txt`, `.env.example`, `.gitignore` ```sh python -m venv .venv python -m pip install Flask Flask-WTF python-dotenv waitress tzdata markdown bleach python -m pip freeze > requirements.txt python -m flask --app app run --host 127.0.0.1 ``` 2. Implement storage and seed the named fixture For database-backed state create schema.sql and db.py using this model: posts(id,slug,title,body,state); subscribers(id,email,status,consent_at,token_hash); campaigns(id,post_id,state); deliveries(id,campaign_id,subscriber_id,state,message_id); suppressions(email,reason,at). Add the auxiliary relationships explicitly used in later phases; use stable ids, foreign keys, parameterized values and transactions. For canonical files use atomic replacement and hashes instead. Implement python manage.py init and python manage.py seed to create only synthetic data: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Re-running init must not erase data. Files: `schema.sql`, `db.py`, `manage.py`, `fixtures/README.md` ```sh python manage.py init python manage.py seed ``` 3. Protect the local request boundary Install Flask-WTF CSRF protection for forms and same-origin fetches, validate Host and Origin against SITE_URL, bound inputs and escape output. Deliberately public intake endpoints get bounded validation and rate limits; signed provider webhooks use signature checks instead of browser CSRF tokens. All other admin routes stay local until product authentication exists. When a later phase tests viewer/member permissions, implement the users, hashed passwords, expiring server sessions and role checks in this foundation first; product mode must never use a fabricated identity from request input. Add error, empty, keyboard-focus and retry states now. Files: `app.py`, `templates/base.html`, `test/test_foundation.py` 4. Implement and test the email adapter Create providers/mail.py using smtplib with a timeout, verified TLS/STARTTLS and an EmailMessage. Refuse placeholder credentials and non-test recipients until the owner enables sending. Implement scripts/smtp_probe.py to send one labelled message only to MAIL_TEST_TO, and provide a fake adapter for tests. Store no password or full message body in logs. Files: `providers/mail.py`, `scripts/smtp_probe.py` ```sh python scripts/smtp_probe.py ``` ### Done when - [ ] The documented start command serves /healthz and the initial screen at http://127.0.0.1:5000. - [ ] Restarting preserves the seeded records or canonical files; running init again deletes nothing. - [ ] A cross-origin state-changing request to an admin route is refused. ### Watch out - The Flask development server is for local development only. Loopback binding alone does not replace CSRF and origin validation. ## Phase 2 · Publication and consent Publication and consent for beehiiv: Build a Markdown post editor with sanitized email/web previews and a public archive containing only published posts. ### Steps 1. Build a Markdown post editor with sanitized email/web previews and a public archive containing only published posts. Build a Markdown post editor with sanitized email/web previews and a public archive containing only published posts. Files: `features/publication_and_consent.py`, `templates/publication_and_consent.html` 2. Implement double-opt-in signup with expiring hashed tokens and a suppression list; send confirmation through the configured SMTP adapter. Implement double-opt-in signup with expiring hashed tokens and a suppression list; send confirmation through the configured SMTP adapter. Files: `features/publication_and_consent.py` 3. Exercise the acceptance fixture Use One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Check: Only the confirmed fixture becomes eligible for a campaign. Then check: A draft post cannot be fetched from its guessed archive URL. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Files: `test/test_publication_and_consent.py` ```sh python -m unittest discover -s test ``` ### Done when - [ ] Only the confirmed fixture becomes eligible for a campaign. - [ ] A draft post cannot be fetched from its guessed archive URL. ### Watch out - The archive and email are different outputs; a preview must show both. ## Phase 3 · Campaign preparation Campaign preparation for beehiiv: Freeze the post content and recipient ids when preparing a campaign and show an exact recipient preview before sending. ### Steps 1. Freeze the post content and recipient ids when preparing a campaign and show an exact recipient preview before sending. Freeze the post content and recipient ids when preparing a campaign and show an exact recipient preview before sending. Files: `features/campaign_preparation.py`, `templates/campaign_preparation.html` 2. Add a plain-text part, visible unsubscribe link and List-Unsubscribe headers; recheck suppression immediately before each send. Add a plain-text part, visible unsubscribe link and List-Unsubscribe headers; recheck suppression immediately before each send. Files: `features/campaign_preparation.py` 3. Exercise the acceptance fixture Use One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Check: Unsubscribing after preparation but before send excludes the recipient. Then check: The email preview contains a functional unsubscribe action and no script tags. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Files: `test/test_campaign_preparation.py` ```sh python -m unittest discover -s test ``` ### Done when - [ ] Unsubscribing after preparation but before send excludes the recipient. - [ ] The email preview contains a functional unsubscribe action and no script tags. ### Watch out - Do not equate successful SMTP submission with inbox delivery or a legal compliance guarantee. ## Phase 4 · Send and reconcile Send and reconcile for beehiiv: Use a unique campaign/subscriber delivery row, bounded rate and a worker lease; record accepted, failed and unknown outcomes. ### Steps 1. Use a unique campaign/subscriber delivery row, bounded rate and a worker lease; record accepted, failed and unknown outcomes. Use a unique campaign/subscriber delivery row, bounded rate and a worker lease; record accepted, failed and unknown outcomes. Files: `features/send_and_reconcile.py`, `templates/send_and_reconcile.html` 2. Pause on ambiguous connection loss after transmission; offer operator reconciliation rather than blindly resending. Pause on ambiguous connection loss after transmission; offer operator reconciliation rather than blindly resending. Files: `features/send_and_reconcile.py` 3. Exercise the acceptance fixture Use One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Check: Restarting skips accepted delivery rows and preserves unknown rows for review. Then check: A failed recipient does not prevent remaining eligible recipients from being processed. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Files: `test/test_send_and_reconcile.py` ```sh python -m unittest discover -s test ``` ### Done when - [ ] Restarting skips accepted delivery rows and preserves unknown rows for review. - [ ] A failed recipient does not prevent remaining eligible recipients from being processed. ### Watch out - Referral networks, paid subscriptions and domain reputation are not reproduced by this publisher. ## Phase 5 · Portable delivery and clean-start proof Finish the beehiiv replacement with a documented first-run path and a recoverable export. ### Steps 1. Write the user-facing runbook Document prerequisites, every configuration variable, data locations and the three domain workflows: Publication and consent; Campaign preparation; Send and reconcile. Include the exclusions, actual costs and source check date 2026-09-05. Commands shown earlier that reference project files are files the builder must implement before running them. Files: `README.md`, `.env.example` 2. Create and rehearse a recoverable backup Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for beehiiv. Restore into a separate empty directory or isolated deployment, with all outbound actions and schedules disabled. Recreate this proof: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Compare ids/counts and open the result before recording the restore date. Never test a restore over the only live copy. Files: `OPERATIONS.md`, `scripts/backup.py` 3. Reproduce the first-run experience Use a new folder and only README instructions to reach the fixture outcome. Install from requirements.txt, initialize storage, run the tests and exercise the UI at 375px and 1280px; use keyboard-only controls and inspect browser errors. Record exactly what passed; do not mark unrun checks complete. Files: `README.md`, `verification.md` ```sh python -m pip install -r requirements.txt python -m unittest discover -s test ``` ### Done when - [ ] A new folder reaches the documented fixture outcome using only README instructions. - [ ] A backup restored in isolation preserves the proof data and can be opened. ### Watch out - Export without an import or restore rehearsal is not verified portability. ## Not in this build - Referral networks, paid subscriptions and domain reputation are not reproduced by this publisher. - This is a small newsletter publisher with a public archive and a safe send ledger; full beehiiv feature parity, vendor hosting and support are not included. - email deliverability - referral/recommendation network - ad network - automations - analytics - paid newsletter tooling - migrations ## After v1, if you want it - Extend send and reconcile only after the fixture and recovery checks pass. - Before adding another integration, document its credentials, limits, cost and failure behavior with primary-source links. ===== .env.example ===== # Copy to .env and fill in. Never commit .env; this file documents it. # Required. A new private folder this application creates on first run; never serve it as static files. DATA_DIR=./data/beehiiv # Required · secret. Generate with python -c "import secrets; print(secrets.token_hex(32))" and save only in .env. SECRET_KEY=replace-with-a-random-secret # Required. Use indie for loopback-only personal work. Product mode must refuse to start until owner login and the deployment gates are configured. APP_MODE=indie # Required. The origin used for local forms and links; replace with the chosen HTTPS origin in product mode. SITE_URL=http://127.0.0.1:5000 # Required. Copy the SMTP hostname from the relay dashboard. SMTP_HOST=replace-with-relay-host # Required. Use a relay supporting STARTTLS on this port; confirm it in its setup instructions. SMTP_PORT=587 # Required · secret. Copy the relay username; it may differ from your sign-in email. SMTP_USER=replace-with-smtp-user # Required · secret. Create SMTP credentials in the relay dashboard, not your personal mailbox password. SMTP_PASSWORD=replace-with-smtp-password # Required. Your relay-verified sender address; replace before real sends. MAIL_FROM=owner@example.com # Required. An inbox you control for the explicit preflight test. MAIL_TEST_TO=owner@example.com
You are building a lean indie version of beehiiv. Create the following project files first, then implement the application by following them. Keep the files updated as decisions change. Do not collapse this into a single README or prompt. ===== README.md ===== # beehiiv · indie build Build a small newsletter publisher with a public archive and a safe send ledger. Estimated effort: **multi-day**. Work `BUILD_PLAN.md` top to bottom · every phase ends in a check that has to pass before the next one starts. ## Stack | Part | Choice | Why | | --- | --- | --- | | Runtime | Python 3.12+ and Flask | A small local HTTP application with readable server-side handlers and no JavaScript build pipeline. | | Storage | SQLite through Python sqlite3 | Local ownership with explicit transactions and a portable backup path. | | Interface | Jinja HTML templates, CSS and vanilla JavaScript | Implement the specified screens directly with labelled controls and progressive enhancement. | | Verification | Python unittest and browser acceptance fixtures | Check invariants and the actual user workflow before the next phase. | | Focused libraries | markdown, bleach | Use these only for the specific file, parsing or provider operations named in the phases; freeze tested versions. | ## Before you start Have every one of these ready. The plan assumes them from step one. - [ ] **Python 3.12 or newer and a terminal** · Python is free; this local prototype requires no hosting subscription. - Why: The local backend, tests and storage use Python. - Get it: Install Python from python.org. Open a terminal in a new empty project folder. On Windows, use py -3 where this guide says python if python is not on PATH; on macOS/Linux use python3 if needed. Create .venv and activate it before installing packages. - Verify: python --version reports 3.12+ and python -c "import sqlite3" succeeds. - [ ] **A current desktop browser and text editor** · No paid service required for this local step. - Why: You need to view the local interface and edit generated project files. - Get it: Use an installed Chrome, Firefox or Edge browser. Open the empty project folder in your editor; open the terminal there, not in this catalog repository. - Verify: You can create a text file in the project folder and open browser developer tools. - [ ] **beehiiv acceptance sample** · No paid service required for this local step. - Why: This fixture makes the first end-to-end check reproducible. - Get it: Create synthetic sample data before implementation: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Save it under fixtures/ with the expected results in fixtures/README.md; use no real credentials or customer records. - Verify: The fixture files and expected outcomes exist and can be inspected without a vendor account. - [ ] **Confirm the bounded replacement** · No paid service required for this local step. - Why: The full commercial product is larger than this guide. - Get it: The deliverable is a small newsletter publisher with a public archive and a safe send ledger. Read every exclusion below. Indie mode runs locally; any public or shared use requires the product access and deployment gates first. - Verify: You can name the primary workflow and the vendor features this version deliberately leaves out. - [ ] **An SMTP relay and one verified test recipient** · Provider-specific relay fees and domain costs; no free tier or delivery guarantee is assumed. - Why: Outbound confirmations or replies need a delivery provider; a fake adapter covers automated tests. - Get it: Obtain SMTP host, port, username and password from your chosen relay dashboard under SMTP settings. Verify the sender/domain using that provider DNS instructions. Use only your own test recipient initially and record the actual plan and rate limit in OPERATIONS.md. - Verify: The supplied smtp_probe.py sends one labelled test message to your own inbox and reports the relay response without logging credentials. ## Quick start ```sh python -m venv .venv python -m pip install Flask Flask-WTF python-dotenv waitress tzdata markdown bleach python -m pip freeze > requirements.txt python -m flask --app app run --host 127.0.0.1 ``` Then copy `.env.example` to `.env` and fill in the values it documents. ## Honest limits This build deliberately does not replace: - Referral networks, paid subscriptions and domain reputation are not reproduced by this publisher. - This is a small newsletter publisher with a public archive and a safe send ledger; full beehiiv feature parity, vendor hosting and support are not included. - email deliverability - referral/recommendation network - ad network - automations - analytics - paid newsletter tooling - migrations If one of those is essential to you, that is the reason to keep paying for beehiiv, and the README should say so rather than pretend. ===== BRIEF.md ===== # Build brief · beehiiv The one-shot brief this plan expands. `BUILD_PLAN.md` (or `MILESTONES.md`) is the same sequence broken into steps and checks; where the two disagree, the plan wins. Build me a small newsletter publisher with a public archive and a safe send ledger as a bounded replacement for beehiiv. Build it in phases in the order below. Do not write the whole product in one pass. Finish the current phase, run its Done when checks, fix failures, then continue. Indie mode completes Phases 1-5. Phase 6 is required before shared or public deployment. ### Stack (fixed, do not substitute) - Runtime: Python 3.12+ and Flask. A small local HTTP application with readable server-side handlers and no JavaScript build pipeline. - Storage: SQLite through Python sqlite3. Local ownership with explicit transactions and a portable backup path. - Interface: Jinja HTML templates, CSS and vanilla JavaScript. Implement the specified screens directly with labelled controls and progressive enhancement. - Verification: Python unittest and browser acceptance fixtures. Check invariants and the actual user workflow before the next phase. - Focused libraries: markdown, bleach. Use these only for the specific file, parsing or provider operations named in the phases; freeze tested versions. ### Data model (create this before Phase 1) - posts(id,slug,title,body,state) - subscribers(id,email,status,consent_at,token_hash) - campaigns(id,post_id,state) - deliveries(id,campaign_id,subscriber_id,state,message_id) - suppressions(email,reason,at) - Use stable ids and explicit relationships; add auxiliary tables named by the phases before those phases use them. - Acceptance fixture: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. ### Prerequisites and configuration - Python 3.12 or newer and a terminal: Install Python from python.org. Open a terminal in a new empty project folder. On Windows, use py -3 where this guide says python if python is not on PATH; on macOS/Linux use python3 if needed. Create .venv and activate it before installing packages. Verify: python --version reports 3.12+ and python -c "import sqlite3" succeeds. Cost: Python is free; this local prototype requires no hosting subscription. - A current desktop browser and text editor: Use an installed Chrome, Firefox or Edge browser. Open the empty project folder in your editor; open the terminal there, not in this catalog repository. Verify: You can create a text file in the project folder and open browser developer tools. Cost: No paid service required for this local step. - beehiiv acceptance sample: Create synthetic sample data before implementation: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Save it under fixtures/ with the expected results in fixtures/README.md; use no real credentials or customer records. Verify: The fixture files and expected outcomes exist and can be inspected without a vendor account. Cost: No paid service required for this local step. - Confirm the bounded replacement: The deliverable is a small newsletter publisher with a public archive and a safe send ledger. Read every exclusion below. Indie mode runs locally; any public or shared use requires the product access and deployment gates first. Verify: You can name the primary workflow and the vendor features this version deliberately leaves out. Cost: No paid service required for this local step. - An SMTP relay and one verified test recipient: Obtain SMTP host, port, username and password from your chosen relay dashboard under SMTP settings. Verify the sender/domain using that provider DNS instructions. Use only your own test recipient initially and record the actual plan and rate limit in OPERATIONS.md. Verify: The supplied smtp_probe.py sends one labelled test message to your own inbox and reports the relay response without logging credentials. Cost: Provider-specific relay fees and domain costs; no free tier or delivery guarantee is assumed. - Configuration: DATA_DIR, SECRET_KEY, APP_MODE, SITE_URL, SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASSWORD, MAIL_FROM, MAIL_TEST_TO. Ship .env.example, replace placeholders and exclude secrets from git. ### Phase 1 · Local foundation and data contract Build: Create the runnable local foundation for a small newsletter publisher with a public archive and a safe send ledger, including the real schema and acceptance fixture. - Run the venv command first, then stop and activate it before running the remaining commands. Use your OS instructions: Windows .venv\Scripts\activate.bat in cmd, or .venv\Scripts\Activate.ps1 in PowerShell; macOS/Linux source .venv/bin/activate. Then install the listed packages. Create app.py exposing app, load .env with python-dotenv, and add a /healthz route. Freeze tested dependency versions to requirements.txt. Create .env manually from .env.example; replace SECRET_KEY before launch. Commands, after creating the named files: `python -m venv .venv`; `python -m pip install Flask Flask-WTF python-dotenv waitress tzdata markdown bleach`; `python -m pip freeze > requirements.txt`; `python -m flask --app app run --host 127.0.0.1`. - For database-backed state create schema.sql and db.py using this model: posts(id,slug,title,body,state); subscribers(id,email,status,consent_at,token_hash); campaigns(id,post_id,state); deliveries(id,campaign_id,subscriber_id,state,message_id); suppressions(email,reason,at). Add the auxiliary relationships explicitly used in later phases; use stable ids, foreign keys, parameterized values and transactions. For canonical files use atomic replacement and hashes instead. Implement python manage.py init and python manage.py seed to create only synthetic data: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Re-running init must not erase data. Commands, after creating the named files: `python manage.py init`; `python manage.py seed`. - Install Flask-WTF CSRF protection for forms and same-origin fetches, validate Host and Origin against SITE_URL, bound inputs and escape output. Deliberately public intake endpoints get bounded validation and rate limits; signed provider webhooks use signature checks instead of browser CSRF tokens. All other admin routes stay local until product authentication exists. When a later phase tests viewer/member permissions, implement the users, hashed passwords, expiring server sessions and role checks in this foundation first; product mode must never use a fabricated identity from request input. Add error, empty, keyboard-focus and retry states now. - Create providers/mail.py using smtplib with a timeout, verified TLS/STARTTLS and an EmailMessage. Refuse placeholder credentials and non-test recipients until the owner enables sending. Implement scripts/smtp_probe.py to send one labelled message only to MAIL_TEST_TO, and provide a fake adapter for tests. Store no password or full message body in logs. Commands, after creating the named files: `python scripts/smtp_probe.py`. - Trap: The Flask development server is for local development only. Loopback binding alone does not replace CSRF and origin validation. Done when: The documented start command serves /healthz and the initial screen at http://127.0.0.1:5000. Restarting preserves the seeded records or canonical files; running init again deletes nothing. A cross-origin state-changing request to an admin route is refused. Do not build yet: Do not start publication and consent until these checks pass. ### Phase 2 · Publication and consent Build: Publication and consent for beehiiv: Build a Markdown post editor with sanitized email/web previews and a public archive containing only published posts. - Build a Markdown post editor with sanitized email/web previews and a public archive containing only published posts. - Implement double-opt-in signup with expiring hashed tokens and a suppression list; send confirmation through the configured SMTP adapter. - Use One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Check: Only the confirmed fixture becomes eligible for a campaign. Then check: A draft post cannot be fetched from its guessed archive URL. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Commands, after creating the named files: `python -m unittest discover -s test`. - Trap: The archive and email are different outputs; a preview must show both. Done when: Only the confirmed fixture becomes eligible for a campaign. A draft post cannot be fetched from its guessed archive URL. Do not build yet: Do not start campaign preparation until these checks pass. ### Phase 3 · Campaign preparation Build: Campaign preparation for beehiiv: Freeze the post content and recipient ids when preparing a campaign and show an exact recipient preview before sending. - Freeze the post content and recipient ids when preparing a campaign and show an exact recipient preview before sending. - Add a plain-text part, visible unsubscribe link and List-Unsubscribe headers; recheck suppression immediately before each send. - Use One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Check: Unsubscribing after preparation but before send excludes the recipient. Then check: The email preview contains a functional unsubscribe action and no script tags. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Commands, after creating the named files: `python -m unittest discover -s test`. - Trap: Do not equate successful SMTP submission with inbox delivery or a legal compliance guarantee. Done when: Unsubscribing after preparation but before send excludes the recipient. The email preview contains a functional unsubscribe action and no script tags. Do not build yet: Do not start send and reconcile until these checks pass. ### Phase 4 · Send and reconcile Build: Send and reconcile for beehiiv: Use a unique campaign/subscriber delivery row, bounded rate and a worker lease; record accepted, failed and unknown outcomes. - Use a unique campaign/subscriber delivery row, bounded rate and a worker lease; record accepted, failed and unknown outcomes. - Pause on ambiguous connection loss after transmission; offer operator reconciliation rather than blindly resending. - Use One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Check: Restarting skips accepted delivery rows and preserves unknown rows for review. Then check: A failed recipient does not prevent remaining eligible recipients from being processed. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Commands, after creating the named files: `python -m unittest discover -s test`. - Trap: Referral networks, paid subscriptions and domain reputation are not reproduced by this publisher. Done when: Restarting skips accepted delivery rows and preserves unknown rows for review. A failed recipient does not prevent remaining eligible recipients from being processed. Do not build yet: Do not start portable delivery and clean-start proof until these checks pass. ### Phase 5 · Portable delivery and clean-start proof Build: Finish the beehiiv replacement with a documented first-run path and a recoverable export. - Document prerequisites, every configuration variable, data locations and the three domain workflows: Publication and consent; Campaign preparation; Send and reconcile. Include the exclusions, actual costs and source check date 2026-09-05. Commands shown earlier that reference project files are files the builder must implement before running them. - Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for beehiiv. Restore into a separate empty directory or isolated deployment, with all outbound actions and schedules disabled. Recreate this proof: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Compare ids/counts and open the result before recording the restore date. Never test a restore over the only live copy. - Use a new folder and only README instructions to reach the fixture outcome. Install from requirements.txt, initialize storage, run the tests and exercise the UI at 375px and 1280px; use keyboard-only controls and inspect browser errors. Record exactly what passed; do not mark unrun checks complete. Commands, after creating the named files: `python -m pip install -r requirements.txt`; `python -m unittest discover -s test`. - Trap: Export without an import or restore rehearsal is not verified portability. Done when: A new folder reaches the documented fixture outcome using only README instructions. A backup restored in isolation preserves the proof data and can be opened. Do not build yet: Do not start operate and share with access controls until these checks pass. ### Phase 6 · Operate and share with access controls (product-builder only) Build: Product-builder only: make a small newsletter publisher with a public archive and a safe send ledger operable for its stated audience before allowing remote access. - Add owner/member/viewer authorization as appropriate, password hashes through Werkzeug, expiring server-side sessions, CSRF and login rate limits. Add users, sessions and audit schema migrations plus an owner-init command prompting securely for its password. Enforce ownership on every private read/write/download and fail closed when product setup is incomplete. Existing learner or admin identities must use this same boundary. - Serve app:app with Waitress on loopback behind Caddy HTTPS. Configure trusted proxy headers narrowly, Secure/HttpOnly/SameSite cookies, upload limits, request ids and structured logs without private content. Run background jobs as a separate supervised process when the domain workflow requires them. Commands, after creating the named files: `waitress-serve --listen=127.0.0.1:5000 app:app`. - Add a scheduled encrypted off-host backup using this procedure: Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for beehiiv. Monitor health, disk space, failed jobs and backup age. Stop the service to test an alert; rehearse recovery with outbound effects disabled and record recovery time. Rotate any exposed credentials and require reconciliation before resuming queues. - Trap: Product mode is additional engineering, not a switch that makes a local prototype production-ready. Done when: An unauthenticated visitor cannot read private records, download private files or mutate the admin surface. A viewer cannot mutate data by making a direct request, and guessed ids cannot cross ownership boundaries. Stopping the service triggers the configured alert and the latest off-host backup restores the fixture in isolation. Do not build yet: Do not add new providers or vendor-scale features until the release gates are recorded. ### Out of scope (and why) - Referral networks, paid subscriptions and domain reputation are not reproduced by this publisher. - This is a small newsletter publisher with a public archive and a safe send ledger; full beehiiv feature parity, vendor hosting and support are not included. - email deliverability: retain the paid product if this capability is essential; it is outside this bounded build. - referral/recommendation network: retain the paid product if this capability is essential; it is outside this bounded build. - ad network: retain the paid product if this capability is essential; it is outside this bounded build. - automations: retain the paid product if this capability is essential; it is outside this bounded build. - analytics: retain the paid product if this capability is essential; it is outside this bounded build. - paid newsletter tooling: retain the paid product if this capability is essential; it is outside this bounded build. - migrations: retain the paid product if this capability is essential; it is outside this bounded build. ### README must contain - Exact install, configure, initialize, start, test and recovery commands for a clean folder. - The schema, fixture, acceptance results, private data locations and export format. - Every prerequisite and secret source, actual running costs and deliberately excluded capabilities. - An honest distinction between tests actually run and checks still awaiting real credentials or deployment. - Dependency documentation reviewed 2026-09-05: https://flask.palletsprojects.com/en/stable/installation/ ; https://docs.python.org/3/library/sqlite3.html ; https://flask-wtf.readthedocs.io/en/1.2.x/csrf/ ; https://docs.pylonsproject.org/projects/waitress/en/stable/usage.html ; https://docs.python.org/3/library/smtplib.html ; https://python-markdown.github.io/reference/ ; https://bleach.readthedocs.io/en/latest/clean.html. Recheck before upgrading; freeze the versions actually tested. ===== AGENTS.md ===== # Agent instructions · beehiiv indie build - Read `README.md` and `BUILD_PLAN.md` before writing code. The stack is fixed: Python 3.12+ and Flask, SQLite through Python sqlite3, Jinja HTML templates, CSS and vanilla JavaScript, Python unittest and browser acceptance fixtures, markdown, bleach. Do not substitute. - Work one phase at a time, in order. Do not start a phase until every "Done when" item of the previous one passes. - Prefer the fewest moving parts that satisfy the step. No frameworks, services or dependencies the plan does not name. - Secrets live in `.env`, never in source or logs. Keep `.env.example` current when a variable is introduced. - Do not invent cryptography, security guarantees, APIs or compliance claims. - Add a focused test for every destructive, security-sensitive or data-loss path the plan names. - Run the project checks before declaring a phase complete, and record any deliberate shortcut in the README under "Tradeoffs". ## Known traps - The Flask development server is for local development only. Loopback binding alone does not replace CSRF and origin validation. - The archive and email are different outputs; a preview must show both. - Do not equate successful SMTP submission with inbox delivery or a legal compliance guarantee. - Referral networks, paid subscriptions and domain reputation are not reproduced by this publisher. - Export without an import or restore rehearsal is not verified portability. ===== BUILD_PLAN.md ===== # Build plan · beehiiv Build a small newsletter publisher with a public archive and a safe send ledger. Phases are in dependency order. Each ends in a "Done when" list; treat an unticked item as a blocker, not a note. ## Phase 1 · Local foundation and data contract Create the runnable local foundation for a small newsletter publisher with a public archive and a safe send ledger, including the real schema and acceptance fixture. ### Steps 1. Create and start the local application Run the venv command first, then stop and activate it before running the remaining commands. Use your OS instructions: Windows .venv\Scripts\activate.bat in cmd, or .venv\Scripts\Activate.ps1 in PowerShell; macOS/Linux source .venv/bin/activate. Then install the listed packages. Create app.py exposing app, load .env with python-dotenv, and add a /healthz route. Freeze tested dependency versions to requirements.txt. Create .env manually from .env.example; replace SECRET_KEY before launch. Files: `app.py`, `requirements.txt`, `.env.example`, `.gitignore` ```sh python -m venv .venv python -m pip install Flask Flask-WTF python-dotenv waitress tzdata markdown bleach python -m pip freeze > requirements.txt python -m flask --app app run --host 127.0.0.1 ``` 2. Implement storage and seed the named fixture For database-backed state create schema.sql and db.py using this model: posts(id,slug,title,body,state); subscribers(id,email,status,consent_at,token_hash); campaigns(id,post_id,state); deliveries(id,campaign_id,subscriber_id,state,message_id); suppressions(email,reason,at). Add the auxiliary relationships explicitly used in later phases; use stable ids, foreign keys, parameterized values and transactions. For canonical files use atomic replacement and hashes instead. Implement python manage.py init and python manage.py seed to create only synthetic data: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Re-running init must not erase data. Files: `schema.sql`, `db.py`, `manage.py`, `fixtures/README.md` ```sh python manage.py init python manage.py seed ``` 3. Protect the local request boundary Install Flask-WTF CSRF protection for forms and same-origin fetches, validate Host and Origin against SITE_URL, bound inputs and escape output. Deliberately public intake endpoints get bounded validation and rate limits; signed provider webhooks use signature checks instead of browser CSRF tokens. All other admin routes stay local until product authentication exists. When a later phase tests viewer/member permissions, implement the users, hashed passwords, expiring server sessions and role checks in this foundation first; product mode must never use a fabricated identity from request input. Add error, empty, keyboard-focus and retry states now. Files: `app.py`, `templates/base.html`, `test/test_foundation.py` 4. Implement and test the email adapter Create providers/mail.py using smtplib with a timeout, verified TLS/STARTTLS and an EmailMessage. Refuse placeholder credentials and non-test recipients until the owner enables sending. Implement scripts/smtp_probe.py to send one labelled message only to MAIL_TEST_TO, and provide a fake adapter for tests. Store no password or full message body in logs. Files: `providers/mail.py`, `scripts/smtp_probe.py` ```sh python scripts/smtp_probe.py ``` ### Done when - [ ] The documented start command serves /healthz and the initial screen at http://127.0.0.1:5000. - [ ] Restarting preserves the seeded records or canonical files; running init again deletes nothing. - [ ] A cross-origin state-changing request to an admin route is refused. ### Watch out - The Flask development server is for local development only. Loopback binding alone does not replace CSRF and origin validation. ## Phase 2 · Publication and consent Publication and consent for beehiiv: Build a Markdown post editor with sanitized email/web previews and a public archive containing only published posts. ### Steps 1. Build a Markdown post editor with sanitized email/web previews and a public archive containing only published posts. Build a Markdown post editor with sanitized email/web previews and a public archive containing only published posts. Files: `features/publication_and_consent.py`, `templates/publication_and_consent.html` 2. Implement double-opt-in signup with expiring hashed tokens and a suppression list; send confirmation through the configured SMTP adapter. Implement double-opt-in signup with expiring hashed tokens and a suppression list; send confirmation through the configured SMTP adapter. Files: `features/publication_and_consent.py` 3. Exercise the acceptance fixture Use One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Check: Only the confirmed fixture becomes eligible for a campaign. Then check: A draft post cannot be fetched from its guessed archive URL. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Files: `test/test_publication_and_consent.py` ```sh python -m unittest discover -s test ``` ### Done when - [ ] Only the confirmed fixture becomes eligible for a campaign. - [ ] A draft post cannot be fetched from its guessed archive URL. ### Watch out - The archive and email are different outputs; a preview must show both. ## Phase 3 · Campaign preparation Campaign preparation for beehiiv: Freeze the post content and recipient ids when preparing a campaign and show an exact recipient preview before sending. ### Steps 1. Freeze the post content and recipient ids when preparing a campaign and show an exact recipient preview before sending. Freeze the post content and recipient ids when preparing a campaign and show an exact recipient preview before sending. Files: `features/campaign_preparation.py`, `templates/campaign_preparation.html` 2. Add a plain-text part, visible unsubscribe link and List-Unsubscribe headers; recheck suppression immediately before each send. Add a plain-text part, visible unsubscribe link and List-Unsubscribe headers; recheck suppression immediately before each send. Files: `features/campaign_preparation.py` 3. Exercise the acceptance fixture Use One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Check: Unsubscribing after preparation but before send excludes the recipient. Then check: The email preview contains a functional unsubscribe action and no script tags. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Files: `test/test_campaign_preparation.py` ```sh python -m unittest discover -s test ``` ### Done when - [ ] Unsubscribing after preparation but before send excludes the recipient. - [ ] The email preview contains a functional unsubscribe action and no script tags. ### Watch out - Do not equate successful SMTP submission with inbox delivery or a legal compliance guarantee. ## Phase 4 · Send and reconcile Send and reconcile for beehiiv: Use a unique campaign/subscriber delivery row, bounded rate and a worker lease; record accepted, failed and unknown outcomes. ### Steps 1. Use a unique campaign/subscriber delivery row, bounded rate and a worker lease; record accepted, failed and unknown outcomes. Use a unique campaign/subscriber delivery row, bounded rate and a worker lease; record accepted, failed and unknown outcomes. Files: `features/send_and_reconcile.py`, `templates/send_and_reconcile.html` 2. Pause on ambiguous connection loss after transmission; offer operator reconciliation rather than blindly resending. Pause on ambiguous connection loss after transmission; offer operator reconciliation rather than blindly resending. Files: `features/send_and_reconcile.py` 3. Exercise the acceptance fixture Use One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Check: Restarting skips accepted delivery rows and preserves unknown rows for review. Then check: A failed recipient does not prevent remaining eligible recipients from being processed. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Files: `test/test_send_and_reconcile.py` ```sh python -m unittest discover -s test ``` ### Done when - [ ] Restarting skips accepted delivery rows and preserves unknown rows for review. - [ ] A failed recipient does not prevent remaining eligible recipients from being processed. ### Watch out - Referral networks, paid subscriptions and domain reputation are not reproduced by this publisher. ## Phase 5 · Portable delivery and clean-start proof Finish the beehiiv replacement with a documented first-run path and a recoverable export. ### Steps 1. Write the user-facing runbook Document prerequisites, every configuration variable, data locations and the three domain workflows: Publication and consent; Campaign preparation; Send and reconcile. Include the exclusions, actual costs and source check date 2026-09-05. Commands shown earlier that reference project files are files the builder must implement before running them. Files: `README.md`, `.env.example` 2. Create and rehearse a recoverable backup Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for beehiiv. Restore into a separate empty directory or isolated deployment, with all outbound actions and schedules disabled. Recreate this proof: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Compare ids/counts and open the result before recording the restore date. Never test a restore over the only live copy. Files: `OPERATIONS.md`, `scripts/backup.py` 3. Reproduce the first-run experience Use a new folder and only README instructions to reach the fixture outcome. Install from requirements.txt, initialize storage, run the tests and exercise the UI at 375px and 1280px; use keyboard-only controls and inspect browser errors. Record exactly what passed; do not mark unrun checks complete. Files: `README.md`, `verification.md` ```sh python -m pip install -r requirements.txt python -m unittest discover -s test ``` ### Done when - [ ] A new folder reaches the documented fixture outcome using only README instructions. - [ ] A backup restored in isolation preserves the proof data and can be opened. ### Watch out - Export without an import or restore rehearsal is not verified portability. ## Not in this build - Referral networks, paid subscriptions and domain reputation are not reproduced by this publisher. - This is a small newsletter publisher with a public archive and a safe send ledger; full beehiiv feature parity, vendor hosting and support are not included. - email deliverability - referral/recommendation network - ad network - automations - analytics - paid newsletter tooling - migrations ## After v1, if you want it - Extend send and reconcile only after the fixture and recovery checks pass. - Before adding another integration, document its credentials, limits, cost and failure behavior with primary-source links. ===== .env.example ===== # Copy to .env and fill in. Never commit .env; this file documents it. # Required. A new private folder this application creates on first run; never serve it as static files. DATA_DIR=./data/beehiiv # Required · secret. Generate with python -c "import secrets; print(secrets.token_hex(32))" and save only in .env. SECRET_KEY=replace-with-a-random-secret # Required. Use indie for loopback-only personal work. Product mode must refuse to start until owner login and the deployment gates are configured. APP_MODE=indie # Required. The origin used for local forms and links; replace with the chosen HTTPS origin in product mode. SITE_URL=http://127.0.0.1:5000 # Required. Copy the SMTP hostname from the relay dashboard. SMTP_HOST=replace-with-relay-host # Required. Use a relay supporting STARTTLS on this port; confirm it in its setup instructions. SMTP_PORT=587 # Required · secret. Copy the relay username; it may differ from your sign-in email. SMTP_USER=replace-with-smtp-user # Required · secret. Create SMTP credentials in the relay dashboard, not your personal mailbox password. SMTP_PASSWORD=replace-with-smtp-password # Required. Your relay-verified sender address; replace before real sends. MAIL_FROM=owner@example.com # Required. An inbox you control for the explicit preflight test. MAIL_TEST_TO=owner@example.com
You are building a production product version of beehiiv. Create the following project files first, then implement the application by following them. Keep the files updated as decisions change. Do not collapse this into a single README or prompt. ===== PRODUCT.md ===== # beehiiv · product brief ## Problem You can build a newsletter CMS and send emails, but beehiiv's moat is deliverability, growth network, recommendations, ad marketplace, automations, analytics, and migrations. ## Product outcome An operated version of a small newsletter publisher with a public archive and a safe send ledger, with authorized access, restore evidence and honest scope limits. ## Target user A builder who needs a maintainable product foundation, not a one-off demo. ## Required capabilities - email service provider - domain/DNS auth - database - CMS/editor - unsubscribe/compliance - hosting ## Explicit non-goals for v1 - Referral networks, paid subscriptions and domain reputation are not reproduced by this publisher. - This is a small newsletter publisher with a public archive and a safe send ledger; full beehiiv feature parity, vendor hosting and support are not included. - email deliverability - referral/recommendation network - ad network - automations - analytics - paid newsletter tooling - migrations ## Success criteria - Only the confirmed fixture becomes eligible for a campaign. - Unsubscribing after preparation but before send excludes the recipient. - Restarting skips accepted delivery rows and preserves unknown rows for review. - A private-data authorization check passes using a second identity. - An off-host restore drill has a date, observed result and recovery time in OPERATIONS.md. - README names the excluded vendor capabilities and actual provider/hosting costs. ===== BRIEF.md ===== # Build brief · beehiiv The one-shot brief this plan expands. `BUILD_PLAN.md` (or `MILESTONES.md`) is the same sequence broken into steps and checks; where the two disagree, the plan wins. Build me a small newsletter publisher with a public archive and a safe send ledger as a bounded replacement for beehiiv. Build it in phases in the order below. Do not write the whole product in one pass. Finish the current phase, run its Done when checks, fix failures, then continue. Indie mode completes Phases 1-5. Phase 6 is required before shared or public deployment. ### Stack (fixed, do not substitute) - Runtime: Python 3.12+ and Flask. A small local HTTP application with readable server-side handlers and no JavaScript build pipeline. - Storage: SQLite through Python sqlite3. Local ownership with explicit transactions and a portable backup path. - Interface: Jinja HTML templates, CSS and vanilla JavaScript. Implement the specified screens directly with labelled controls and progressive enhancement. - Verification: Python unittest and browser acceptance fixtures. Check invariants and the actual user workflow before the next phase. - Focused libraries: markdown, bleach. Use these only for the specific file, parsing or provider operations named in the phases; freeze tested versions. ### Data model (create this before Phase 1) - posts(id,slug,title,body,state) - subscribers(id,email,status,consent_at,token_hash) - campaigns(id,post_id,state) - deliveries(id,campaign_id,subscriber_id,state,message_id) - suppressions(email,reason,at) - Use stable ids and explicit relationships; add auxiliary tables named by the phases before those phases use them. - Acceptance fixture: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. ### Prerequisites and configuration - Python 3.12 or newer and a terminal: Install Python from python.org. Open a terminal in a new empty project folder. On Windows, use py -3 where this guide says python if python is not on PATH; on macOS/Linux use python3 if needed. Create .venv and activate it before installing packages. Verify: python --version reports 3.12+ and python -c "import sqlite3" succeeds. Cost: Python is free; this local prototype requires no hosting subscription. - A current desktop browser and text editor: Use an installed Chrome, Firefox or Edge browser. Open the empty project folder in your editor; open the terminal there, not in this catalog repository. Verify: You can create a text file in the project folder and open browser developer tools. Cost: No paid service required for this local step. - beehiiv acceptance sample: Create synthetic sample data before implementation: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Save it under fixtures/ with the expected results in fixtures/README.md; use no real credentials or customer records. Verify: The fixture files and expected outcomes exist and can be inspected without a vendor account. Cost: No paid service required for this local step. - Confirm the bounded replacement: The deliverable is a small newsletter publisher with a public archive and a safe send ledger. Read every exclusion below. Indie mode runs locally; any public or shared use requires the product access and deployment gates first. Verify: You can name the primary workflow and the vendor features this version deliberately leaves out. Cost: No paid service required for this local step. - An SMTP relay and one verified test recipient: Obtain SMTP host, port, username and password from your chosen relay dashboard under SMTP settings. Verify the sender/domain using that provider DNS instructions. Use only your own test recipient initially and record the actual plan and rate limit in OPERATIONS.md. Verify: The supplied smtp_probe.py sends one labelled test message to your own inbox and reports the relay response without logging credentials. Cost: Provider-specific relay fees and domain costs; no free tier or delivery guarantee is assumed. - Configuration: DATA_DIR, SECRET_KEY, APP_MODE, SITE_URL, SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASSWORD, MAIL_FROM, MAIL_TEST_TO. Ship .env.example, replace placeholders and exclude secrets from git. ### Phase 1 · Local foundation and data contract Build: Create the runnable local foundation for a small newsletter publisher with a public archive and a safe send ledger, including the real schema and acceptance fixture. - Run the venv command first, then stop and activate it before running the remaining commands. Use your OS instructions: Windows .venv\Scripts\activate.bat in cmd, or .venv\Scripts\Activate.ps1 in PowerShell; macOS/Linux source .venv/bin/activate. Then install the listed packages. Create app.py exposing app, load .env with python-dotenv, and add a /healthz route. Freeze tested dependency versions to requirements.txt. Create .env manually from .env.example; replace SECRET_KEY before launch. Commands, after creating the named files: `python -m venv .venv`; `python -m pip install Flask Flask-WTF python-dotenv waitress tzdata markdown bleach`; `python -m pip freeze > requirements.txt`; `python -m flask --app app run --host 127.0.0.1`. - For database-backed state create schema.sql and db.py using this model: posts(id,slug,title,body,state); subscribers(id,email,status,consent_at,token_hash); campaigns(id,post_id,state); deliveries(id,campaign_id,subscriber_id,state,message_id); suppressions(email,reason,at). Add the auxiliary relationships explicitly used in later phases; use stable ids, foreign keys, parameterized values and transactions. For canonical files use atomic replacement and hashes instead. Implement python manage.py init and python manage.py seed to create only synthetic data: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Re-running init must not erase data. Commands, after creating the named files: `python manage.py init`; `python manage.py seed`. - Install Flask-WTF CSRF protection for forms and same-origin fetches, validate Host and Origin against SITE_URL, bound inputs and escape output. Deliberately public intake endpoints get bounded validation and rate limits; signed provider webhooks use signature checks instead of browser CSRF tokens. All other admin routes stay local until product authentication exists. When a later phase tests viewer/member permissions, implement the users, hashed passwords, expiring server sessions and role checks in this foundation first; product mode must never use a fabricated identity from request input. Add error, empty, keyboard-focus and retry states now. - Create providers/mail.py using smtplib with a timeout, verified TLS/STARTTLS and an EmailMessage. Refuse placeholder credentials and non-test recipients until the owner enables sending. Implement scripts/smtp_probe.py to send one labelled message only to MAIL_TEST_TO, and provide a fake adapter for tests. Store no password or full message body in logs. Commands, after creating the named files: `python scripts/smtp_probe.py`. - Trap: The Flask development server is for local development only. Loopback binding alone does not replace CSRF and origin validation. Done when: The documented start command serves /healthz and the initial screen at http://127.0.0.1:5000. Restarting preserves the seeded records or canonical files; running init again deletes nothing. A cross-origin state-changing request to an admin route is refused. Do not build yet: Do not start publication and consent until these checks pass. ### Phase 2 · Publication and consent Build: Publication and consent for beehiiv: Build a Markdown post editor with sanitized email/web previews and a public archive containing only published posts. - Build a Markdown post editor with sanitized email/web previews and a public archive containing only published posts. - Implement double-opt-in signup with expiring hashed tokens and a suppression list; send confirmation through the configured SMTP adapter. - Use One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Check: Only the confirmed fixture becomes eligible for a campaign. Then check: A draft post cannot be fetched from its guessed archive URL. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Commands, after creating the named files: `python -m unittest discover -s test`. - Trap: The archive and email are different outputs; a preview must show both. Done when: Only the confirmed fixture becomes eligible for a campaign. A draft post cannot be fetched from its guessed archive URL. Do not build yet: Do not start campaign preparation until these checks pass. ### Phase 3 · Campaign preparation Build: Campaign preparation for beehiiv: Freeze the post content and recipient ids when preparing a campaign and show an exact recipient preview before sending. - Freeze the post content and recipient ids when preparing a campaign and show an exact recipient preview before sending. - Add a plain-text part, visible unsubscribe link and List-Unsubscribe headers; recheck suppression immediately before each send. - Use One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Check: Unsubscribing after preparation but before send excludes the recipient. Then check: The email preview contains a functional unsubscribe action and no script tags. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Commands, after creating the named files: `python -m unittest discover -s test`. - Trap: Do not equate successful SMTP submission with inbox delivery or a legal compliance guarantee. Done when: Unsubscribing after preparation but before send excludes the recipient. The email preview contains a functional unsubscribe action and no script tags. Do not build yet: Do not start send and reconcile until these checks pass. ### Phase 4 · Send and reconcile Build: Send and reconcile for beehiiv: Use a unique campaign/subscriber delivery row, bounded rate and a worker lease; record accepted, failed and unknown outcomes. - Use a unique campaign/subscriber delivery row, bounded rate and a worker lease; record accepted, failed and unknown outcomes. - Pause on ambiguous connection loss after transmission; offer operator reconciliation rather than blindly resending. - Use One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Check: Restarting skips accepted delivery rows and preserves unknown rows for review. Then check: A failed recipient does not prevent remaining eligible recipients from being processed. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Commands, after creating the named files: `python -m unittest discover -s test`. - Trap: Referral networks, paid subscriptions and domain reputation are not reproduced by this publisher. Done when: Restarting skips accepted delivery rows and preserves unknown rows for review. A failed recipient does not prevent remaining eligible recipients from being processed. Do not build yet: Do not start portable delivery and clean-start proof until these checks pass. ### Phase 5 · Portable delivery and clean-start proof Build: Finish the beehiiv replacement with a documented first-run path and a recoverable export. - Document prerequisites, every configuration variable, data locations and the three domain workflows: Publication and consent; Campaign preparation; Send and reconcile. Include the exclusions, actual costs and source check date 2026-09-05. Commands shown earlier that reference project files are files the builder must implement before running them. - Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for beehiiv. Restore into a separate empty directory or isolated deployment, with all outbound actions and schedules disabled. Recreate this proof: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Compare ids/counts and open the result before recording the restore date. Never test a restore over the only live copy. - Use a new folder and only README instructions to reach the fixture outcome. Install from requirements.txt, initialize storage, run the tests and exercise the UI at 375px and 1280px; use keyboard-only controls and inspect browser errors. Record exactly what passed; do not mark unrun checks complete. Commands, after creating the named files: `python -m pip install -r requirements.txt`; `python -m unittest discover -s test`. - Trap: Export without an import or restore rehearsal is not verified portability. Done when: A new folder reaches the documented fixture outcome using only README instructions. A backup restored in isolation preserves the proof data and can be opened. Do not build yet: Do not start operate and share with access controls until these checks pass. ### Phase 6 · Operate and share with access controls (product-builder only) Build: Product-builder only: make a small newsletter publisher with a public archive and a safe send ledger operable for its stated audience before allowing remote access. - Add owner/member/viewer authorization as appropriate, password hashes through Werkzeug, expiring server-side sessions, CSRF and login rate limits. Add users, sessions and audit schema migrations plus an owner-init command prompting securely for its password. Enforce ownership on every private read/write/download and fail closed when product setup is incomplete. Existing learner or admin identities must use this same boundary. - Serve app:app with Waitress on loopback behind Caddy HTTPS. Configure trusted proxy headers narrowly, Secure/HttpOnly/SameSite cookies, upload limits, request ids and structured logs without private content. Run background jobs as a separate supervised process when the domain workflow requires them. Commands, after creating the named files: `waitress-serve --listen=127.0.0.1:5000 app:app`. - Add a scheduled encrypted off-host backup using this procedure: Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for beehiiv. Monitor health, disk space, failed jobs and backup age. Stop the service to test an alert; rehearse recovery with outbound effects disabled and record recovery time. Rotate any exposed credentials and require reconciliation before resuming queues. - Trap: Product mode is additional engineering, not a switch that makes a local prototype production-ready. Done when: An unauthenticated visitor cannot read private records, download private files or mutate the admin surface. A viewer cannot mutate data by making a direct request, and guessed ids cannot cross ownership boundaries. Stopping the service triggers the configured alert and the latest off-host backup restores the fixture in isolation. Do not build yet: Do not add new providers or vendor-scale features until the release gates are recorded. ### Out of scope (and why) - Referral networks, paid subscriptions and domain reputation are not reproduced by this publisher. - This is a small newsletter publisher with a public archive and a safe send ledger; full beehiiv feature parity, vendor hosting and support are not included. - email deliverability: retain the paid product if this capability is essential; it is outside this bounded build. - referral/recommendation network: retain the paid product if this capability is essential; it is outside this bounded build. - ad network: retain the paid product if this capability is essential; it is outside this bounded build. - automations: retain the paid product if this capability is essential; it is outside this bounded build. - analytics: retain the paid product if this capability is essential; it is outside this bounded build. - paid newsletter tooling: retain the paid product if this capability is essential; it is outside this bounded build. - migrations: retain the paid product if this capability is essential; it is outside this bounded build. ### README must contain - Exact install, configure, initialize, start, test and recovery commands for a clean folder. - The schema, fixture, acceptance results, private data locations and export format. - Every prerequisite and secret source, actual running costs and deliberately excluded capabilities. - An honest distinction between tests actually run and checks still awaiting real credentials or deployment. - Dependency documentation reviewed 2026-09-05: https://flask.palletsprojects.com/en/stable/installation/ ; https://docs.python.org/3/library/sqlite3.html ; https://flask-wtf.readthedocs.io/en/1.2.x/csrf/ ; https://docs.pylonsproject.org/projects/waitress/en/stable/usage.html ; https://docs.python.org/3/library/smtplib.html ; https://python-markdown.github.io/reference/ ; https://bleach.readthedocs.io/en/latest/clean.html. Recheck before upgrading; freeze the versions actually tested. ===== ARCHITECTURE.md ===== # Architecture · beehiiv ## Stack | Part | Choice | Why | | --- | --- | --- | | Runtime | Python 3.12+ and Flask | A small local HTTP application with readable server-side handlers and no JavaScript build pipeline. | | Storage | SQLite through Python sqlite3 | Local ownership with explicit transactions and a portable backup path. | | Interface | Jinja HTML templates, CSS and vanilla JavaScript | Implement the specified screens directly with labelled controls and progressive enhancement. | | Verification | Python unittest and browser acceptance fixtures | Check invariants and the actual user workflow before the next phase. | | Focused libraries | markdown, bleach | Use these only for the specific file, parsing or provider operations named in the phases; freeze tested versions. | ## Modules Each module has one owner concern and a documented way to replace it. | Module | Owns | How to replace it | | --- | --- | --- | | Data and identity | posts(id,slug,title,body,state); subscribers(id,email,status,consent_at,token_hash); campaigns(id,post_id,state); deliveries(id,campaign_id,subscriber_id,state,message_id); suppressions(email,reason,at) | Keep stable ids and a versioned repository interface; migrate storage behind it with a fixture round-trip. | | Publication and consent | Build a Markdown post editor with sanitized email/web previews and a public archive containing only published posts. | Keep the acceptance contract: Only the confirmed fixture becomes eligible for a campaign. Replace only this module after replaying its fixture; preserve ids and existing records. | | Campaign preparation | Freeze the post content and recipient ids when preparing a campaign and show an exact recipient preview before sending. | Keep the acceptance contract: Unsubscribing after preparation but before send excludes the recipient. Replace only this module after replaying its fixture; preserve ids and existing records. | | Send and reconcile | Use a unique campaign/subscriber delivery row, bounded rate and a worker lease; record accepted, failed and unknown outcomes. | Keep the acceptance contract: Restarting skips accepted delivery rows and preserves unknown rows for review. Replace only this module after replaying its fixture; preserve ids and existing records. | | Operations | Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for beehiiv. | Change host or backup destination only after an isolated restore and authorization check. | ## Configuration Every runtime setting is an environment variable documented in `.env.example`, validated at startup, with a safe local default wherever one exists. - `DATA_DIR` · required · A new private folder this application creates on first run; never serve it as static files. - `SECRET_KEY` · required, secret · Generate with python -c "import secrets; print(secrets.token_hex(32))" and save only in .env. - `APP_MODE` · required · Use indie for loopback-only personal work. Product mode must refuse to start until owner login and the deployment gates are configured. - `SITE_URL` · required · The origin used for local forms and links; replace with the chosen HTTPS origin in product mode. - `SMTP_HOST` · required · Copy the SMTP hostname from the relay dashboard. - `SMTP_PORT` · required · Use a relay supporting STARTTLS on this port; confirm it in its setup instructions. - `SMTP_USER` · required, secret · Copy the relay username; it may differ from your sign-in email. - `SMTP_PASSWORD` · required, secret · Create SMTP credentials in the relay dashboard, not your personal mailbox password. - `MAIL_FROM` · required · Your relay-verified sender address; replace before real sends. - `MAIL_TEST_TO` · required · An inbox you control for the explicit preflight test. ## Production baseline - Security: least privilege, input validation at every boundary, secret redaction in logs, rate limits on abuse-prone paths, no invented security primitives. - Data: explicit schema and migrations, transactional writes where integrity matters, backup and restore procedures that have been exercised. - Integrations: adapters around third-party providers, idempotent webhook or job processing, bounded retries, timeouts. - Observability: structured logs with request or operation ids, an error-tracking hook, and health and readiness checks where a server exists. - Quality: unit tests for domain rules, integration tests at module boundaries, one end-to-end test of the critical path. ## Decision records For each dependency in the stack table, keep a short note: why it was chosen, its failure mode, and how it is replaced. Do not add infrastructure until a requirement in `PRODUCT.md` justifies it. ===== AGENTS.md ===== # Agent instructions · beehiiv product build - Read `PRODUCT.md` and `ARCHITECTURE.md` before changing code. The stack is fixed: Python 3.12+ and Flask, SQLite through Python sqlite3, Jinja HTML templates, CSS and vanilla JavaScript, Python unittest and browser acceptance fixtures, markdown, bleach. - Implement milestone by milestone from `MILESTONES.md`; keep each change reviewable and leave the application runnable at every commit. - Treat authentication, payments, encryption, imports, webhooks and destructive actions as high-risk boundaries when present. - Never invent cryptography or silently weaken a requirement to make a check pass. - Put every external service behind an interface with a deterministic fake for tests. - Add migrations and rollback or recovery notes for every persistent data change. - Log useful operational context without credentials, tokens, passwords or personal data. - Update documentation and run every check before completing a milestone. ## Known traps - The Flask development server is for local development only. Loopback binding alone does not replace CSRF and origin validation. - The archive and email are different outputs; a preview must show both. - Do not equate successful SMTP submission with inbox delivery or a legal compliance guarantee. - Referral networks, paid subscriptions and domain reputation are not reproduced by this publisher. - Export without an import or restore rehearsal is not verified portability. - Product mode is additional engineering, not a switch that makes a local prototype production-ready. ===== MILESTONES.md ===== # Delivery milestones · beehiiv Estimated effort: **multi-day** for the indie phases; the production-only milestones add the trust and operability layer. ## M1 · Local foundation and data contract Create the runnable local foundation for a small newsletter publisher with a public archive and a safe send ledger, including the real schema and acceptance fixture. ### Steps 1. Create and start the local application Run the venv command first, then stop and activate it before running the remaining commands. Use your OS instructions: Windows .venv\Scripts\activate.bat in cmd, or .venv\Scripts\Activate.ps1 in PowerShell; macOS/Linux source .venv/bin/activate. Then install the listed packages. Create app.py exposing app, load .env with python-dotenv, and add a /healthz route. Freeze tested dependency versions to requirements.txt. Create .env manually from .env.example; replace SECRET_KEY before launch. Files: `app.py`, `requirements.txt`, `.env.example`, `.gitignore` ```sh python -m venv .venv python -m pip install Flask Flask-WTF python-dotenv waitress tzdata markdown bleach python -m pip freeze > requirements.txt python -m flask --app app run --host 127.0.0.1 ``` 2. Implement storage and seed the named fixture For database-backed state create schema.sql and db.py using this model: posts(id,slug,title,body,state); subscribers(id,email,status,consent_at,token_hash); campaigns(id,post_id,state); deliveries(id,campaign_id,subscriber_id,state,message_id); suppressions(email,reason,at). Add the auxiliary relationships explicitly used in later phases; use stable ids, foreign keys, parameterized values and transactions. For canonical files use atomic replacement and hashes instead. Implement python manage.py init and python manage.py seed to create only synthetic data: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Re-running init must not erase data. Files: `schema.sql`, `db.py`, `manage.py`, `fixtures/README.md` ```sh python manage.py init python manage.py seed ``` 3. Protect the local request boundary Install Flask-WTF CSRF protection for forms and same-origin fetches, validate Host and Origin against SITE_URL, bound inputs and escape output. Deliberately public intake endpoints get bounded validation and rate limits; signed provider webhooks use signature checks instead of browser CSRF tokens. All other admin routes stay local until product authentication exists. When a later phase tests viewer/member permissions, implement the users, hashed passwords, expiring server sessions and role checks in this foundation first; product mode must never use a fabricated identity from request input. Add error, empty, keyboard-focus and retry states now. Files: `app.py`, `templates/base.html`, `test/test_foundation.py` 4. Implement and test the email adapter Create providers/mail.py using smtplib with a timeout, verified TLS/STARTTLS and an EmailMessage. Refuse placeholder credentials and non-test recipients until the owner enables sending. Implement scripts/smtp_probe.py to send one labelled message only to MAIL_TEST_TO, and provide a fake adapter for tests. Store no password or full message body in logs. Files: `providers/mail.py`, `scripts/smtp_probe.py` ```sh python scripts/smtp_probe.py ``` ### Done when - [ ] The documented start command serves /healthz and the initial screen at http://127.0.0.1:5000. - [ ] Restarting preserves the seeded records or canonical files; running init again deletes nothing. - [ ] A cross-origin state-changing request to an admin route is refused. ### Watch out - The Flask development server is for local development only. Loopback binding alone does not replace CSRF and origin validation. ## M2 · Publication and consent Publication and consent for beehiiv: Build a Markdown post editor with sanitized email/web previews and a public archive containing only published posts. ### Steps 1. Build a Markdown post editor with sanitized email/web previews and a public archive containing only published posts. Build a Markdown post editor with sanitized email/web previews and a public archive containing only published posts. Files: `features/publication_and_consent.py`, `templates/publication_and_consent.html` 2. Implement double-opt-in signup with expiring hashed tokens and a suppression list; send confirmation through the configured SMTP adapter. Implement double-opt-in signup with expiring hashed tokens and a suppression list; send confirmation through the configured SMTP adapter. Files: `features/publication_and_consent.py` 3. Exercise the acceptance fixture Use One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Check: Only the confirmed fixture becomes eligible for a campaign. Then check: A draft post cannot be fetched from its guessed archive URL. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Files: `test/test_publication_and_consent.py` ```sh python -m unittest discover -s test ``` ### Done when - [ ] Only the confirmed fixture becomes eligible for a campaign. - [ ] A draft post cannot be fetched from its guessed archive URL. ### Watch out - The archive and email are different outputs; a preview must show both. ## M3 · Campaign preparation Campaign preparation for beehiiv: Freeze the post content and recipient ids when preparing a campaign and show an exact recipient preview before sending. ### Steps 1. Freeze the post content and recipient ids when preparing a campaign and show an exact recipient preview before sending. Freeze the post content and recipient ids when preparing a campaign and show an exact recipient preview before sending. Files: `features/campaign_preparation.py`, `templates/campaign_preparation.html` 2. Add a plain-text part, visible unsubscribe link and List-Unsubscribe headers; recheck suppression immediately before each send. Add a plain-text part, visible unsubscribe link and List-Unsubscribe headers; recheck suppression immediately before each send. Files: `features/campaign_preparation.py` 3. Exercise the acceptance fixture Use One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Check: Unsubscribing after preparation but before send excludes the recipient. Then check: The email preview contains a functional unsubscribe action and no script tags. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Files: `test/test_campaign_preparation.py` ```sh python -m unittest discover -s test ``` ### Done when - [ ] Unsubscribing after preparation but before send excludes the recipient. - [ ] The email preview contains a functional unsubscribe action and no script tags. ### Watch out - Do not equate successful SMTP submission with inbox delivery or a legal compliance guarantee. ## M4 · Send and reconcile Send and reconcile for beehiiv: Use a unique campaign/subscriber delivery row, bounded rate and a worker lease; record accepted, failed and unknown outcomes. ### Steps 1. Use a unique campaign/subscriber delivery row, bounded rate and a worker lease; record accepted, failed and unknown outcomes. Use a unique campaign/subscriber delivery row, bounded rate and a worker lease; record accepted, failed and unknown outcomes. Files: `features/send_and_reconcile.py`, `templates/send_and_reconcile.html` 2. Pause on ambiguous connection loss after transmission; offer operator reconciliation rather than blindly resending. Pause on ambiguous connection loss after transmission; offer operator reconciliation rather than blindly resending. Files: `features/send_and_reconcile.py` 3. Exercise the acceptance fixture Use One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Check: Restarting skips accepted delivery rows and preserves unknown rows for review. Then check: A failed recipient does not prevent remaining eligible recipients from being processed. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Files: `test/test_send_and_reconcile.py` ```sh python -m unittest discover -s test ``` ### Done when - [ ] Restarting skips accepted delivery rows and preserves unknown rows for review. - [ ] A failed recipient does not prevent remaining eligible recipients from being processed. ### Watch out - Referral networks, paid subscriptions and domain reputation are not reproduced by this publisher. ## M5 · Portable delivery and clean-start proof Finish the beehiiv replacement with a documented first-run path and a recoverable export. ### Steps 1. Write the user-facing runbook Document prerequisites, every configuration variable, data locations and the three domain workflows: Publication and consent; Campaign preparation; Send and reconcile. Include the exclusions, actual costs and source check date 2026-09-05. Commands shown earlier that reference project files are files the builder must implement before running them. Files: `README.md`, `.env.example` 2. Create and rehearse a recoverable backup Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for beehiiv. Restore into a separate empty directory or isolated deployment, with all outbound actions and schedules disabled. Recreate this proof: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Compare ids/counts and open the result before recording the restore date. Never test a restore over the only live copy. Files: `OPERATIONS.md`, `scripts/backup.py` 3. Reproduce the first-run experience Use a new folder and only README instructions to reach the fixture outcome. Install from requirements.txt, initialize storage, run the tests and exercise the UI at 375px and 1280px; use keyboard-only controls and inspect browser errors. Record exactly what passed; do not mark unrun checks complete. Files: `README.md`, `verification.md` ```sh python -m pip install -r requirements.txt python -m unittest discover -s test ``` ### Done when - [ ] A new folder reaches the documented fixture outcome using only README instructions. - [ ] A backup restored in isolation preserves the proof data and can be opened. ### Watch out - Export without an import or restore rehearsal is not verified portability. ## M6 · Operate and share with access controls (production only) Product-builder only: make a small newsletter publisher with a public archive and a safe send ledger operable for its stated audience before allowing remote access. ### Steps 1. Establish owner access before exposure Add owner/member/viewer authorization as appropriate, password hashes through Werkzeug, expiring server-side sessions, CSRF and login rate limits. Add users, sessions and audit schema migrations plus an owner-init command prompting securely for its password. Enforce ownership on every private read/write/download and fail closed when product setup is incomplete. Existing learner or admin identities must use this same boundary. Files: `ARCHITECTURE.md`, `OPERATIONS.md` 2. Deploy a monitored service Serve app:app with Waitress on loopback behind Caddy HTTPS. Configure trusted proxy headers narrowly, Secure/HttpOnly/SameSite cookies, upload limits, request ids and structured logs without private content. Run background jobs as a separate supervised process when the domain workflow requires them. Files: `Caddyfile`, `OPERATIONS.md` ```sh waitress-serve --listen=127.0.0.1:5000 app:app ``` 3. Rehearse loss and recovery Add a scheduled encrypted off-host backup using this procedure: Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for beehiiv. Monitor health, disk space, failed jobs and backup age. Stop the service to test an alert; rehearse recovery with outbound effects disabled and record recovery time. Rotate any exposed credentials and require reconciliation before resuming queues. Files: `OPERATIONS.md`, `release-checklist.md` ### Done when - [ ] An unauthenticated visitor cannot read private records, download private files or mutate the admin surface. - [ ] A viewer cannot mutate data by making a direct request, and guessed ids cannot cross ownership boundaries. - [ ] Stopping the service triggers the configured alert and the latest off-host backup restores the fixture in isolation. ### Watch out - Product mode is additional engineering, not a switch that makes a local prototype production-ready. ===== OPERATIONS.md ===== # Operations · beehiiv ## Backup Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for beehiiv. ## Restore Restore into a separate empty directory or isolated deployment, with all outbound actions and schedules disabled. Recreate this proof: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Compare ids/counts and open the result before recording the restore date. Never test a restore over the only live copy. Do a restore drill before the first real user, and write the date here when it passes. ## Monitoring Check HTTP availability, free disk, backup age and domain failures for Publication and consent, Campaign preparation, Send and reconcile. Alert without logging private payloads. ## Incident checklist Pause outbound jobs and public intake as appropriate, preserve redacted diagnostics, restore an isolated verified backup, rotate affected credentials and reconcile uncertain effects before reopening. 1. Contain the issue without destroying evidence or user data. 2. Record the timeline and affected scope. 3. Rotate exposed secrets and revoke compromised sessions or credentials. 4. Restore from a verified backup when needed. 5. Document the root cause, the remediation and the regression test. ## Release gate - [ ] Only the confirmed fixture becomes eligible for a campaign. - [ ] Unsubscribing after preparation but before send excludes the recipient. - [ ] Restarting skips accepted delivery rows and preserves unknown rows for review. - [ ] A private-data authorization check passes using a second identity. - [ ] An off-host restore drill has a date, observed result and recovery time in OPERATIONS.md. - [ ] README names the excluded vendor capabilities and actual provider/hosting costs. ## Launch constraint Do not market omitted beehiiv capabilities as implemented. The non-goals in `PRODUCT.md` remain user-visible limitations until they are deliberately delivered. ===== .env.example ===== # Copy to .env and fill in. Never commit .env; this file documents it. # Required. A new private folder this application creates on first run; never serve it as static files. DATA_DIR=./data/beehiiv # Required · secret. Generate with python -c "import secrets; print(secrets.token_hex(32))" and save only in .env. SECRET_KEY=replace-with-a-random-secret # Required. Use indie for loopback-only personal work. Product mode must refuse to start until owner login and the deployment gates are configured. APP_MODE=indie # Required. The origin used for local forms and links; replace with the chosen HTTPS origin in product mode. SITE_URL=http://127.0.0.1:5000 # Required. Copy the SMTP hostname from the relay dashboard. SMTP_HOST=replace-with-relay-host # Required. Use a relay supporting STARTTLS on this port; confirm it in its setup instructions. SMTP_PORT=587 # Required · secret. Copy the relay username; it may differ from your sign-in email. SMTP_USER=replace-with-smtp-user # Required · secret. Create SMTP credentials in the relay dashboard, not your personal mailbox password. SMTP_PASSWORD=replace-with-smtp-password # Required. Your relay-verified sender address; replace before real sends. MAIL_FROM=owner@example.com # Required. An inbox you control for the explicit preflight test. MAIL_TEST_TO=owner@example.com
# beehiiv · indie build Build a small newsletter publisher with a public archive and a safe send ledger. Estimated effort: **multi-day**. Work `BUILD_PLAN.md` top to bottom · every phase ends in a check that has to pass before the next one starts. ## Stack | Part | Choice | Why | | --- | --- | --- | | Runtime | Python 3.12+ and Flask | A small local HTTP application with readable server-side handlers and no JavaScript build pipeline. | | Storage | SQLite through Python sqlite3 | Local ownership with explicit transactions and a portable backup path. | | Interface | Jinja HTML templates, CSS and vanilla JavaScript | Implement the specified screens directly with labelled controls and progressive enhancement. | | Verification | Python unittest and browser acceptance fixtures | Check invariants and the actual user workflow before the next phase. | | Focused libraries | markdown, bleach | Use these only for the specific file, parsing or provider operations named in the phases; freeze tested versions. | ## Before you start Have every one of these ready. The plan assumes them from step one. - [ ] **Python 3.12 or newer and a terminal** · Python is free; this local prototype requires no hosting subscription. - Why: The local backend, tests and storage use Python. - Get it: Install Python from python.org. Open a terminal in a new empty project folder. On Windows, use py -3 where this guide says python if python is not on PATH; on macOS/Linux use python3 if needed. Create .venv and activate it before installing packages. - Verify: python --version reports 3.12+ and python -c "import sqlite3" succeeds. - [ ] **A current desktop browser and text editor** · No paid service required for this local step. - Why: You need to view the local interface and edit generated project files. - Get it: Use an installed Chrome, Firefox or Edge browser. Open the empty project folder in your editor; open the terminal there, not in this catalog repository. - Verify: You can create a text file in the project folder and open browser developer tools. - [ ] **beehiiv acceptance sample** · No paid service required for this local step. - Why: This fixture makes the first end-to-end check reproducible. - Get it: Create synthetic sample data before implementation: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Save it under fixtures/ with the expected results in fixtures/README.md; use no real credentials or customer records. - Verify: The fixture files and expected outcomes exist and can be inspected without a vendor account. - [ ] **Confirm the bounded replacement** · No paid service required for this local step. - Why: The full commercial product is larger than this guide. - Get it: The deliverable is a small newsletter publisher with a public archive and a safe send ledger. Read every exclusion below. Indie mode runs locally; any public or shared use requires the product access and deployment gates first. - Verify: You can name the primary workflow and the vendor features this version deliberately leaves out. - [ ] **An SMTP relay and one verified test recipient** · Provider-specific relay fees and domain costs; no free tier or delivery guarantee is assumed. - Why: Outbound confirmations or replies need a delivery provider; a fake adapter covers automated tests. - Get it: Obtain SMTP host, port, username and password from your chosen relay dashboard under SMTP settings. Verify the sender/domain using that provider DNS instructions. Use only your own test recipient initially and record the actual plan and rate limit in OPERATIONS.md. - Verify: The supplied smtp_probe.py sends one labelled test message to your own inbox and reports the relay response without logging credentials. ## Quick start ```sh python -m venv .venv python -m pip install Flask Flask-WTF python-dotenv waitress tzdata markdown bleach python -m pip freeze > requirements.txt python -m flask --app app run --host 127.0.0.1 ``` Then copy `.env.example` to `.env` and fill in the values it documents. ## Honest limits This build deliberately does not replace: - Referral networks, paid subscriptions and domain reputation are not reproduced by this publisher. - This is a small newsletter publisher with a public archive and a safe send ledger; full beehiiv feature parity, vendor hosting and support are not included. - email deliverability - referral/recommendation network - ad network - automations - analytics - paid newsletter tooling - migrations If one of those is essential to you, that is the reason to keep paying for beehiiv, and the README should say so rather than pretend.
# Build brief · beehiiv The one-shot brief this plan expands. `BUILD_PLAN.md` (or `MILESTONES.md`) is the same sequence broken into steps and checks; where the two disagree, the plan wins. Build me a small newsletter publisher with a public archive and a safe send ledger as a bounded replacement for beehiiv. Build it in phases in the order below. Do not write the whole product in one pass. Finish the current phase, run its Done when checks, fix failures, then continue. Indie mode completes Phases 1-5. Phase 6 is required before shared or public deployment. ### Stack (fixed, do not substitute) - Runtime: Python 3.12+ and Flask. A small local HTTP application with readable server-side handlers and no JavaScript build pipeline. - Storage: SQLite through Python sqlite3. Local ownership with explicit transactions and a portable backup path. - Interface: Jinja HTML templates, CSS and vanilla JavaScript. Implement the specified screens directly with labelled controls and progressive enhancement. - Verification: Python unittest and browser acceptance fixtures. Check invariants and the actual user workflow before the next phase. - Focused libraries: markdown, bleach. Use these only for the specific file, parsing or provider operations named in the phases; freeze tested versions. ### Data model (create this before Phase 1) - posts(id,slug,title,body,state) - subscribers(id,email,status,consent_at,token_hash) - campaigns(id,post_id,state) - deliveries(id,campaign_id,subscriber_id,state,message_id) - suppressions(email,reason,at) - Use stable ids and explicit relationships; add auxiliary tables named by the phases before those phases use them. - Acceptance fixture: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. ### Prerequisites and configuration - Python 3.12 or newer and a terminal: Install Python from python.org. Open a terminal in a new empty project folder. On Windows, use py -3 where this guide says python if python is not on PATH; on macOS/Linux use python3 if needed. Create .venv and activate it before installing packages. Verify: python --version reports 3.12+ and python -c "import sqlite3" succeeds. Cost: Python is free; this local prototype requires no hosting subscription. - A current desktop browser and text editor: Use an installed Chrome, Firefox or Edge browser. Open the empty project folder in your editor; open the terminal there, not in this catalog repository. Verify: You can create a text file in the project folder and open browser developer tools. Cost: No paid service required for this local step. - beehiiv acceptance sample: Create synthetic sample data before implementation: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Save it under fixtures/ with the expected results in fixtures/README.md; use no real credentials or customer records. Verify: The fixture files and expected outcomes exist and can be inspected without a vendor account. Cost: No paid service required for this local step. - Confirm the bounded replacement: The deliverable is a small newsletter publisher with a public archive and a safe send ledger. Read every exclusion below. Indie mode runs locally; any public or shared use requires the product access and deployment gates first. Verify: You can name the primary workflow and the vendor features this version deliberately leaves out. Cost: No paid service required for this local step. - An SMTP relay and one verified test recipient: Obtain SMTP host, port, username and password from your chosen relay dashboard under SMTP settings. Verify the sender/domain using that provider DNS instructions. Use only your own test recipient initially and record the actual plan and rate limit in OPERATIONS.md. Verify: The supplied smtp_probe.py sends one labelled test message to your own inbox and reports the relay response without logging credentials. Cost: Provider-specific relay fees and domain costs; no free tier or delivery guarantee is assumed. - Configuration: DATA_DIR, SECRET_KEY, APP_MODE, SITE_URL, SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASSWORD, MAIL_FROM, MAIL_TEST_TO. Ship .env.example, replace placeholders and exclude secrets from git. ### Phase 1 · Local foundation and data contract Build: Create the runnable local foundation for a small newsletter publisher with a public archive and a safe send ledger, including the real schema and acceptance fixture. - Run the venv command first, then stop and activate it before running the remaining commands. Use your OS instructions: Windows .venv\Scripts\activate.bat in cmd, or .venv\Scripts\Activate.ps1 in PowerShell; macOS/Linux source .venv/bin/activate. Then install the listed packages. Create app.py exposing app, load .env with python-dotenv, and add a /healthz route. Freeze tested dependency versions to requirements.txt. Create .env manually from .env.example; replace SECRET_KEY before launch. Commands, after creating the named files: `python -m venv .venv`; `python -m pip install Flask Flask-WTF python-dotenv waitress tzdata markdown bleach`; `python -m pip freeze > requirements.txt`; `python -m flask --app app run --host 127.0.0.1`. - For database-backed state create schema.sql and db.py using this model: posts(id,slug,title,body,state); subscribers(id,email,status,consent_at,token_hash); campaigns(id,post_id,state); deliveries(id,campaign_id,subscriber_id,state,message_id); suppressions(email,reason,at). Add the auxiliary relationships explicitly used in later phases; use stable ids, foreign keys, parameterized values and transactions. For canonical files use atomic replacement and hashes instead. Implement python manage.py init and python manage.py seed to create only synthetic data: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Re-running init must not erase data. Commands, after creating the named files: `python manage.py init`; `python manage.py seed`. - Install Flask-WTF CSRF protection for forms and same-origin fetches, validate Host and Origin against SITE_URL, bound inputs and escape output. Deliberately public intake endpoints get bounded validation and rate limits; signed provider webhooks use signature checks instead of browser CSRF tokens. All other admin routes stay local until product authentication exists. When a later phase tests viewer/member permissions, implement the users, hashed passwords, expiring server sessions and role checks in this foundation first; product mode must never use a fabricated identity from request input. Add error, empty, keyboard-focus and retry states now. - Create providers/mail.py using smtplib with a timeout, verified TLS/STARTTLS and an EmailMessage. Refuse placeholder credentials and non-test recipients until the owner enables sending. Implement scripts/smtp_probe.py to send one labelled message only to MAIL_TEST_TO, and provide a fake adapter for tests. Store no password or full message body in logs. Commands, after creating the named files: `python scripts/smtp_probe.py`. - Trap: The Flask development server is for local development only. Loopback binding alone does not replace CSRF and origin validation. Done when: The documented start command serves /healthz and the initial screen at http://127.0.0.1:5000. Restarting preserves the seeded records or canonical files; running init again deletes nothing. A cross-origin state-changing request to an admin route is refused. Do not build yet: Do not start publication and consent until these checks pass. ### Phase 2 · Publication and consent Build: Publication and consent for beehiiv: Build a Markdown post editor with sanitized email/web previews and a public archive containing only published posts. - Build a Markdown post editor with sanitized email/web previews and a public archive containing only published posts. - Implement double-opt-in signup with expiring hashed tokens and a suppression list; send confirmation through the configured SMTP adapter. - Use One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Check: Only the confirmed fixture becomes eligible for a campaign. Then check: A draft post cannot be fetched from its guessed archive URL. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Commands, after creating the named files: `python -m unittest discover -s test`. - Trap: The archive and email are different outputs; a preview must show both. Done when: Only the confirmed fixture becomes eligible for a campaign. A draft post cannot be fetched from its guessed archive URL. Do not build yet: Do not start campaign preparation until these checks pass. ### Phase 3 · Campaign preparation Build: Campaign preparation for beehiiv: Freeze the post content and recipient ids when preparing a campaign and show an exact recipient preview before sending. - Freeze the post content and recipient ids when preparing a campaign and show an exact recipient preview before sending. - Add a plain-text part, visible unsubscribe link and List-Unsubscribe headers; recheck suppression immediately before each send. - Use One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Check: Unsubscribing after preparation but before send excludes the recipient. Then check: The email preview contains a functional unsubscribe action and no script tags. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Commands, after creating the named files: `python -m unittest discover -s test`. - Trap: Do not equate successful SMTP submission with inbox delivery or a legal compliance guarantee. Done when: Unsubscribing after preparation but before send excludes the recipient. The email preview contains a functional unsubscribe action and no script tags. Do not build yet: Do not start send and reconcile until these checks pass. ### Phase 4 · Send and reconcile Build: Send and reconcile for beehiiv: Use a unique campaign/subscriber delivery row, bounded rate and a worker lease; record accepted, failed and unknown outcomes. - Use a unique campaign/subscriber delivery row, bounded rate and a worker lease; record accepted, failed and unknown outcomes. - Pause on ambiguous connection loss after transmission; offer operator reconciliation rather than blindly resending. - Use One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Check: Restarting skips accepted delivery rows and preserves unknown rows for review. Then check: A failed recipient does not prevent remaining eligible recipients from being processed. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Commands, after creating the named files: `python -m unittest discover -s test`. - Trap: Referral networks, paid subscriptions and domain reputation are not reproduced by this publisher. Done when: Restarting skips accepted delivery rows and preserves unknown rows for review. A failed recipient does not prevent remaining eligible recipients from being processed. Do not build yet: Do not start portable delivery and clean-start proof until these checks pass. ### Phase 5 · Portable delivery and clean-start proof Build: Finish the beehiiv replacement with a documented first-run path and a recoverable export. - Document prerequisites, every configuration variable, data locations and the three domain workflows: Publication and consent; Campaign preparation; Send and reconcile. Include the exclusions, actual costs and source check date 2026-09-05. Commands shown earlier that reference project files are files the builder must implement before running them. - Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for beehiiv. Restore into a separate empty directory or isolated deployment, with all outbound actions and schedules disabled. Recreate this proof: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Compare ids/counts and open the result before recording the restore date. Never test a restore over the only live copy. - Use a new folder and only README instructions to reach the fixture outcome. Install from requirements.txt, initialize storage, run the tests and exercise the UI at 375px and 1280px; use keyboard-only controls and inspect browser errors. Record exactly what passed; do not mark unrun checks complete. Commands, after creating the named files: `python -m pip install -r requirements.txt`; `python -m unittest discover -s test`. - Trap: Export without an import or restore rehearsal is not verified portability. Done when: A new folder reaches the documented fixture outcome using only README instructions. A backup restored in isolation preserves the proof data and can be opened. Do not build yet: Do not start operate and share with access controls until these checks pass. ### Phase 6 · Operate and share with access controls (product-builder only) Build: Product-builder only: make a small newsletter publisher with a public archive and a safe send ledger operable for its stated audience before allowing remote access. - Add owner/member/viewer authorization as appropriate, password hashes through Werkzeug, expiring server-side sessions, CSRF and login rate limits. Add users, sessions and audit schema migrations plus an owner-init command prompting securely for its password. Enforce ownership on every private read/write/download and fail closed when product setup is incomplete. Existing learner or admin identities must use this same boundary. - Serve app:app with Waitress on loopback behind Caddy HTTPS. Configure trusted proxy headers narrowly, Secure/HttpOnly/SameSite cookies, upload limits, request ids and structured logs without private content. Run background jobs as a separate supervised process when the domain workflow requires them. Commands, after creating the named files: `waitress-serve --listen=127.0.0.1:5000 app:app`. - Add a scheduled encrypted off-host backup using this procedure: Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for beehiiv. Monitor health, disk space, failed jobs and backup age. Stop the service to test an alert; rehearse recovery with outbound effects disabled and record recovery time. Rotate any exposed credentials and require reconciliation before resuming queues. - Trap: Product mode is additional engineering, not a switch that makes a local prototype production-ready. Done when: An unauthenticated visitor cannot read private records, download private files or mutate the admin surface. A viewer cannot mutate data by making a direct request, and guessed ids cannot cross ownership boundaries. Stopping the service triggers the configured alert and the latest off-host backup restores the fixture in isolation. Do not build yet: Do not add new providers or vendor-scale features until the release gates are recorded. ### Out of scope (and why) - Referral networks, paid subscriptions and domain reputation are not reproduced by this publisher. - This is a small newsletter publisher with a public archive and a safe send ledger; full beehiiv feature parity, vendor hosting and support are not included. - email deliverability: retain the paid product if this capability is essential; it is outside this bounded build. - referral/recommendation network: retain the paid product if this capability is essential; it is outside this bounded build. - ad network: retain the paid product if this capability is essential; it is outside this bounded build. - automations: retain the paid product if this capability is essential; it is outside this bounded build. - analytics: retain the paid product if this capability is essential; it is outside this bounded build. - paid newsletter tooling: retain the paid product if this capability is essential; it is outside this bounded build. - migrations: retain the paid product if this capability is essential; it is outside this bounded build. ### README must contain - Exact install, configure, initialize, start, test and recovery commands for a clean folder. - The schema, fixture, acceptance results, private data locations and export format. - Every prerequisite and secret source, actual running costs and deliberately excluded capabilities. - An honest distinction between tests actually run and checks still awaiting real credentials or deployment. - Dependency documentation reviewed 2026-09-05: https://flask.palletsprojects.com/en/stable/installation/ ; https://docs.python.org/3/library/sqlite3.html ; https://flask-wtf.readthedocs.io/en/1.2.x/csrf/ ; https://docs.pylonsproject.org/projects/waitress/en/stable/usage.html ; https://docs.python.org/3/library/smtplib.html ; https://python-markdown.github.io/reference/ ; https://bleach.readthedocs.io/en/latest/clean.html. Recheck before upgrading; freeze the versions actually tested.
# Agent instructions · beehiiv indie build - Read `README.md` and `BUILD_PLAN.md` before writing code. The stack is fixed: Python 3.12+ and Flask, SQLite through Python sqlite3, Jinja HTML templates, CSS and vanilla JavaScript, Python unittest and browser acceptance fixtures, markdown, bleach. Do not substitute. - Work one phase at a time, in order. Do not start a phase until every "Done when" item of the previous one passes. - Prefer the fewest moving parts that satisfy the step. No frameworks, services or dependencies the plan does not name. - Secrets live in `.env`, never in source or logs. Keep `.env.example` current when a variable is introduced. - Do not invent cryptography, security guarantees, APIs or compliance claims. - Add a focused test for every destructive, security-sensitive or data-loss path the plan names. - Run the project checks before declaring a phase complete, and record any deliberate shortcut in the README under "Tradeoffs". ## Known traps - The Flask development server is for local development only. Loopback binding alone does not replace CSRF and origin validation. - The archive and email are different outputs; a preview must show both. - Do not equate successful SMTP submission with inbox delivery or a legal compliance guarantee. - Referral networks, paid subscriptions and domain reputation are not reproduced by this publisher. - Export without an import or restore rehearsal is not verified portability.
# Build plan · beehiiv Build a small newsletter publisher with a public archive and a safe send ledger. Phases are in dependency order. Each ends in a "Done when" list; treat an unticked item as a blocker, not a note. ## Phase 1 · Local foundation and data contract Create the runnable local foundation for a small newsletter publisher with a public archive and a safe send ledger, including the real schema and acceptance fixture. ### Steps 1. Create and start the local application Run the venv command first, then stop and activate it before running the remaining commands. Use your OS instructions: Windows .venv\Scripts\activate.bat in cmd, or .venv\Scripts\Activate.ps1 in PowerShell; macOS/Linux source .venv/bin/activate. Then install the listed packages. Create app.py exposing app, load .env with python-dotenv, and add a /healthz route. Freeze tested dependency versions to requirements.txt. Create .env manually from .env.example; replace SECRET_KEY before launch. Files: `app.py`, `requirements.txt`, `.env.example`, `.gitignore` ```sh python -m venv .venv python -m pip install Flask Flask-WTF python-dotenv waitress tzdata markdown bleach python -m pip freeze > requirements.txt python -m flask --app app run --host 127.0.0.1 ``` 2. Implement storage and seed the named fixture For database-backed state create schema.sql and db.py using this model: posts(id,slug,title,body,state); subscribers(id,email,status,consent_at,token_hash); campaigns(id,post_id,state); deliveries(id,campaign_id,subscriber_id,state,message_id); suppressions(email,reason,at). Add the auxiliary relationships explicitly used in later phases; use stable ids, foreign keys, parameterized values and transactions. For canonical files use atomic replacement and hashes instead. Implement python manage.py init and python manage.py seed to create only synthetic data: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Re-running init must not erase data. Files: `schema.sql`, `db.py`, `manage.py`, `fixtures/README.md` ```sh python manage.py init python manage.py seed ``` 3. Protect the local request boundary Install Flask-WTF CSRF protection for forms and same-origin fetches, validate Host and Origin against SITE_URL, bound inputs and escape output. Deliberately public intake endpoints get bounded validation and rate limits; signed provider webhooks use signature checks instead of browser CSRF tokens. All other admin routes stay local until product authentication exists. When a later phase tests viewer/member permissions, implement the users, hashed passwords, expiring server sessions and role checks in this foundation first; product mode must never use a fabricated identity from request input. Add error, empty, keyboard-focus and retry states now. Files: `app.py`, `templates/base.html`, `test/test_foundation.py` 4. Implement and test the email adapter Create providers/mail.py using smtplib with a timeout, verified TLS/STARTTLS and an EmailMessage. Refuse placeholder credentials and non-test recipients until the owner enables sending. Implement scripts/smtp_probe.py to send one labelled message only to MAIL_TEST_TO, and provide a fake adapter for tests. Store no password or full message body in logs. Files: `providers/mail.py`, `scripts/smtp_probe.py` ```sh python scripts/smtp_probe.py ``` ### Done when - [ ] The documented start command serves /healthz and the initial screen at http://127.0.0.1:5000. - [ ] Restarting preserves the seeded records or canonical files; running init again deletes nothing. - [ ] A cross-origin state-changing request to an admin route is refused. ### Watch out - The Flask development server is for local development only. Loopback binding alone does not replace CSRF and origin validation. ## Phase 2 · Publication and consent Publication and consent for beehiiv: Build a Markdown post editor with sanitized email/web previews and a public archive containing only published posts. ### Steps 1. Build a Markdown post editor with sanitized email/web previews and a public archive containing only published posts. Build a Markdown post editor with sanitized email/web previews and a public archive containing only published posts. Files: `features/publication_and_consent.py`, `templates/publication_and_consent.html` 2. Implement double-opt-in signup with expiring hashed tokens and a suppression list; send confirmation through the configured SMTP adapter. Implement double-opt-in signup with expiring hashed tokens and a suppression list; send confirmation through the configured SMTP adapter. Files: `features/publication_and_consent.py` 3. Exercise the acceptance fixture Use One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Check: Only the confirmed fixture becomes eligible for a campaign. Then check: A draft post cannot be fetched from its guessed archive URL. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Files: `test/test_publication_and_consent.py` ```sh python -m unittest discover -s test ``` ### Done when - [ ] Only the confirmed fixture becomes eligible for a campaign. - [ ] A draft post cannot be fetched from its guessed archive URL. ### Watch out - The archive and email are different outputs; a preview must show both. ## Phase 3 · Campaign preparation Campaign preparation for beehiiv: Freeze the post content and recipient ids when preparing a campaign and show an exact recipient preview before sending. ### Steps 1. Freeze the post content and recipient ids when preparing a campaign and show an exact recipient preview before sending. Freeze the post content and recipient ids when preparing a campaign and show an exact recipient preview before sending. Files: `features/campaign_preparation.py`, `templates/campaign_preparation.html` 2. Add a plain-text part, visible unsubscribe link and List-Unsubscribe headers; recheck suppression immediately before each send. Add a plain-text part, visible unsubscribe link and List-Unsubscribe headers; recheck suppression immediately before each send. Files: `features/campaign_preparation.py` 3. Exercise the acceptance fixture Use One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Check: Unsubscribing after preparation but before send excludes the recipient. Then check: The email preview contains a functional unsubscribe action and no script tags. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Files: `test/test_campaign_preparation.py` ```sh python -m unittest discover -s test ``` ### Done when - [ ] Unsubscribing after preparation but before send excludes the recipient. - [ ] The email preview contains a functional unsubscribe action and no script tags. ### Watch out - Do not equate successful SMTP submission with inbox delivery or a legal compliance guarantee. ## Phase 4 · Send and reconcile Send and reconcile for beehiiv: Use a unique campaign/subscriber delivery row, bounded rate and a worker lease; record accepted, failed and unknown outcomes. ### Steps 1. Use a unique campaign/subscriber delivery row, bounded rate and a worker lease; record accepted, failed and unknown outcomes. Use a unique campaign/subscriber delivery row, bounded rate and a worker lease; record accepted, failed and unknown outcomes. Files: `features/send_and_reconcile.py`, `templates/send_and_reconcile.html` 2. Pause on ambiguous connection loss after transmission; offer operator reconciliation rather than blindly resending. Pause on ambiguous connection loss after transmission; offer operator reconciliation rather than blindly resending. Files: `features/send_and_reconcile.py` 3. Exercise the acceptance fixture Use One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Check: Restarting skips accepted delivery rows and preserves unknown rows for review. Then check: A failed recipient does not prevent remaining eligible recipients from being processed. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Files: `test/test_send_and_reconcile.py` ```sh python -m unittest discover -s test ``` ### Done when - [ ] Restarting skips accepted delivery rows and preserves unknown rows for review. - [ ] A failed recipient does not prevent remaining eligible recipients from being processed. ### Watch out - Referral networks, paid subscriptions and domain reputation are not reproduced by this publisher. ## Phase 5 · Portable delivery and clean-start proof Finish the beehiiv replacement with a documented first-run path and a recoverable export. ### Steps 1. Write the user-facing runbook Document prerequisites, every configuration variable, data locations and the three domain workflows: Publication and consent; Campaign preparation; Send and reconcile. Include the exclusions, actual costs and source check date 2026-09-05. Commands shown earlier that reference project files are files the builder must implement before running them. Files: `README.md`, `.env.example` 2. Create and rehearse a recoverable backup Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for beehiiv. Restore into a separate empty directory or isolated deployment, with all outbound actions and schedules disabled. Recreate this proof: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Compare ids/counts and open the result before recording the restore date. Never test a restore over the only live copy. Files: `OPERATIONS.md`, `scripts/backup.py` 3. Reproduce the first-run experience Use a new folder and only README instructions to reach the fixture outcome. Install from requirements.txt, initialize storage, run the tests and exercise the UI at 375px and 1280px; use keyboard-only controls and inspect browser errors. Record exactly what passed; do not mark unrun checks complete. Files: `README.md`, `verification.md` ```sh python -m pip install -r requirements.txt python -m unittest discover -s test ``` ### Done when - [ ] A new folder reaches the documented fixture outcome using only README instructions. - [ ] A backup restored in isolation preserves the proof data and can be opened. ### Watch out - Export without an import or restore rehearsal is not verified portability. ## Not in this build - Referral networks, paid subscriptions and domain reputation are not reproduced by this publisher. - This is a small newsletter publisher with a public archive and a safe send ledger; full beehiiv feature parity, vendor hosting and support are not included. - email deliverability - referral/recommendation network - ad network - automations - analytics - paid newsletter tooling - migrations ## After v1, if you want it - Extend send and reconcile only after the fixture and recovery checks pass. - Before adding another integration, document its credentials, limits, cost and failure behavior with primary-source links.
# Copy to .env and fill in. Never commit .env; this file documents it. # Required. A new private folder this application creates on first run; never serve it as static files. DATA_DIR=./data/beehiiv # Required · secret. Generate with python -c "import secrets; print(secrets.token_hex(32))" and save only in .env. SECRET_KEY=replace-with-a-random-secret # Required. Use indie for loopback-only personal work. Product mode must refuse to start until owner login and the deployment gates are configured. APP_MODE=indie # Required. The origin used for local forms and links; replace with the chosen HTTPS origin in product mode. SITE_URL=http://127.0.0.1:5000 # Required. Copy the SMTP hostname from the relay dashboard. SMTP_HOST=replace-with-relay-host # Required. Use a relay supporting STARTTLS on this port; confirm it in its setup instructions. SMTP_PORT=587 # Required · secret. Copy the relay username; it may differ from your sign-in email. SMTP_USER=replace-with-smtp-user # Required · secret. Create SMTP credentials in the relay dashboard, not your personal mailbox password. SMTP_PASSWORD=replace-with-smtp-password # Required. Your relay-verified sender address; replace before real sends. MAIL_FROM=owner@example.com # Required. An inbox you control for the explicit preflight test. MAIL_TEST_TO=owner@example.com
# beehiiv · product brief ## Problem You can build a newsletter CMS and send emails, but beehiiv's moat is deliverability, growth network, recommendations, ad marketplace, automations, analytics, and migrations. ## Product outcome An operated version of a small newsletter publisher with a public archive and a safe send ledger, with authorized access, restore evidence and honest scope limits. ## Target user A builder who needs a maintainable product foundation, not a one-off demo. ## Required capabilities - email service provider - domain/DNS auth - database - CMS/editor - unsubscribe/compliance - hosting ## Explicit non-goals for v1 - Referral networks, paid subscriptions and domain reputation are not reproduced by this publisher. - This is a small newsletter publisher with a public archive and a safe send ledger; full beehiiv feature parity, vendor hosting and support are not included. - email deliverability - referral/recommendation network - ad network - automations - analytics - paid newsletter tooling - migrations ## Success criteria - Only the confirmed fixture becomes eligible for a campaign. - Unsubscribing after preparation but before send excludes the recipient. - Restarting skips accepted delivery rows and preserves unknown rows for review. - A private-data authorization check passes using a second identity. - An off-host restore drill has a date, observed result and recovery time in OPERATIONS.md. - README names the excluded vendor capabilities and actual provider/hosting costs.
# Build brief · beehiiv The one-shot brief this plan expands. `BUILD_PLAN.md` (or `MILESTONES.md`) is the same sequence broken into steps and checks; where the two disagree, the plan wins. Build me a small newsletter publisher with a public archive and a safe send ledger as a bounded replacement for beehiiv. Build it in phases in the order below. Do not write the whole product in one pass. Finish the current phase, run its Done when checks, fix failures, then continue. Indie mode completes Phases 1-5. Phase 6 is required before shared or public deployment. ### Stack (fixed, do not substitute) - Runtime: Python 3.12+ and Flask. A small local HTTP application with readable server-side handlers and no JavaScript build pipeline. - Storage: SQLite through Python sqlite3. Local ownership with explicit transactions and a portable backup path. - Interface: Jinja HTML templates, CSS and vanilla JavaScript. Implement the specified screens directly with labelled controls and progressive enhancement. - Verification: Python unittest and browser acceptance fixtures. Check invariants and the actual user workflow before the next phase. - Focused libraries: markdown, bleach. Use these only for the specific file, parsing or provider operations named in the phases; freeze tested versions. ### Data model (create this before Phase 1) - posts(id,slug,title,body,state) - subscribers(id,email,status,consent_at,token_hash) - campaigns(id,post_id,state) - deliveries(id,campaign_id,subscriber_id,state,message_id) - suppressions(email,reason,at) - Use stable ids and explicit relationships; add auxiliary tables named by the phases before those phases use them. - Acceptance fixture: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. ### Prerequisites and configuration - Python 3.12 or newer and a terminal: Install Python from python.org. Open a terminal in a new empty project folder. On Windows, use py -3 where this guide says python if python is not on PATH; on macOS/Linux use python3 if needed. Create .venv and activate it before installing packages. Verify: python --version reports 3.12+ and python -c "import sqlite3" succeeds. Cost: Python is free; this local prototype requires no hosting subscription. - A current desktop browser and text editor: Use an installed Chrome, Firefox or Edge browser. Open the empty project folder in your editor; open the terminal there, not in this catalog repository. Verify: You can create a text file in the project folder and open browser developer tools. Cost: No paid service required for this local step. - beehiiv acceptance sample: Create synthetic sample data before implementation: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Save it under fixtures/ with the expected results in fixtures/README.md; use no real credentials or customer records. Verify: The fixture files and expected outcomes exist and can be inspected without a vendor account. Cost: No paid service required for this local step. - Confirm the bounded replacement: The deliverable is a small newsletter publisher with a public archive and a safe send ledger. Read every exclusion below. Indie mode runs locally; any public or shared use requires the product access and deployment gates first. Verify: You can name the primary workflow and the vendor features this version deliberately leaves out. Cost: No paid service required for this local step. - An SMTP relay and one verified test recipient: Obtain SMTP host, port, username and password from your chosen relay dashboard under SMTP settings. Verify the sender/domain using that provider DNS instructions. Use only your own test recipient initially and record the actual plan and rate limit in OPERATIONS.md. Verify: The supplied smtp_probe.py sends one labelled test message to your own inbox and reports the relay response without logging credentials. Cost: Provider-specific relay fees and domain costs; no free tier or delivery guarantee is assumed. - Configuration: DATA_DIR, SECRET_KEY, APP_MODE, SITE_URL, SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASSWORD, MAIL_FROM, MAIL_TEST_TO. Ship .env.example, replace placeholders and exclude secrets from git. ### Phase 1 · Local foundation and data contract Build: Create the runnable local foundation for a small newsletter publisher with a public archive and a safe send ledger, including the real schema and acceptance fixture. - Run the venv command first, then stop and activate it before running the remaining commands. Use your OS instructions: Windows .venv\Scripts\activate.bat in cmd, or .venv\Scripts\Activate.ps1 in PowerShell; macOS/Linux source .venv/bin/activate. Then install the listed packages. Create app.py exposing app, load .env with python-dotenv, and add a /healthz route. Freeze tested dependency versions to requirements.txt. Create .env manually from .env.example; replace SECRET_KEY before launch. Commands, after creating the named files: `python -m venv .venv`; `python -m pip install Flask Flask-WTF python-dotenv waitress tzdata markdown bleach`; `python -m pip freeze > requirements.txt`; `python -m flask --app app run --host 127.0.0.1`. - For database-backed state create schema.sql and db.py using this model: posts(id,slug,title,body,state); subscribers(id,email,status,consent_at,token_hash); campaigns(id,post_id,state); deliveries(id,campaign_id,subscriber_id,state,message_id); suppressions(email,reason,at). Add the auxiliary relationships explicitly used in later phases; use stable ids, foreign keys, parameterized values and transactions. For canonical files use atomic replacement and hashes instead. Implement python manage.py init and python manage.py seed to create only synthetic data: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Re-running init must not erase data. Commands, after creating the named files: `python manage.py init`; `python manage.py seed`. - Install Flask-WTF CSRF protection for forms and same-origin fetches, validate Host and Origin against SITE_URL, bound inputs and escape output. Deliberately public intake endpoints get bounded validation and rate limits; signed provider webhooks use signature checks instead of browser CSRF tokens. All other admin routes stay local until product authentication exists. When a later phase tests viewer/member permissions, implement the users, hashed passwords, expiring server sessions and role checks in this foundation first; product mode must never use a fabricated identity from request input. Add error, empty, keyboard-focus and retry states now. - Create providers/mail.py using smtplib with a timeout, verified TLS/STARTTLS and an EmailMessage. Refuse placeholder credentials and non-test recipients until the owner enables sending. Implement scripts/smtp_probe.py to send one labelled message only to MAIL_TEST_TO, and provide a fake adapter for tests. Store no password or full message body in logs. Commands, after creating the named files: `python scripts/smtp_probe.py`. - Trap: The Flask development server is for local development only. Loopback binding alone does not replace CSRF and origin validation. Done when: The documented start command serves /healthz and the initial screen at http://127.0.0.1:5000. Restarting preserves the seeded records or canonical files; running init again deletes nothing. A cross-origin state-changing request to an admin route is refused. Do not build yet: Do not start publication and consent until these checks pass. ### Phase 2 · Publication and consent Build: Publication and consent for beehiiv: Build a Markdown post editor with sanitized email/web previews and a public archive containing only published posts. - Build a Markdown post editor with sanitized email/web previews and a public archive containing only published posts. - Implement double-opt-in signup with expiring hashed tokens and a suppression list; send confirmation through the configured SMTP adapter. - Use One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Check: Only the confirmed fixture becomes eligible for a campaign. Then check: A draft post cannot be fetched from its guessed archive URL. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Commands, after creating the named files: `python -m unittest discover -s test`. - Trap: The archive and email are different outputs; a preview must show both. Done when: Only the confirmed fixture becomes eligible for a campaign. A draft post cannot be fetched from its guessed archive URL. Do not build yet: Do not start campaign preparation until these checks pass. ### Phase 3 · Campaign preparation Build: Campaign preparation for beehiiv: Freeze the post content and recipient ids when preparing a campaign and show an exact recipient preview before sending. - Freeze the post content and recipient ids when preparing a campaign and show an exact recipient preview before sending. - Add a plain-text part, visible unsubscribe link and List-Unsubscribe headers; recheck suppression immediately before each send. - Use One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Check: Unsubscribing after preparation but before send excludes the recipient. Then check: The email preview contains a functional unsubscribe action and no script tags. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Commands, after creating the named files: `python -m unittest discover -s test`. - Trap: Do not equate successful SMTP submission with inbox delivery or a legal compliance guarantee. Done when: Unsubscribing after preparation but before send excludes the recipient. The email preview contains a functional unsubscribe action and no script tags. Do not build yet: Do not start send and reconcile until these checks pass. ### Phase 4 · Send and reconcile Build: Send and reconcile for beehiiv: Use a unique campaign/subscriber delivery row, bounded rate and a worker lease; record accepted, failed and unknown outcomes. - Use a unique campaign/subscriber delivery row, bounded rate and a worker lease; record accepted, failed and unknown outcomes. - Pause on ambiguous connection loss after transmission; offer operator reconciliation rather than blindly resending. - Use One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Check: Restarting skips accepted delivery rows and preserves unknown rows for review. Then check: A failed recipient does not prevent remaining eligible recipients from being processed. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Commands, after creating the named files: `python -m unittest discover -s test`. - Trap: Referral networks, paid subscriptions and domain reputation are not reproduced by this publisher. Done when: Restarting skips accepted delivery rows and preserves unknown rows for review. A failed recipient does not prevent remaining eligible recipients from being processed. Do not build yet: Do not start portable delivery and clean-start proof until these checks pass. ### Phase 5 · Portable delivery and clean-start proof Build: Finish the beehiiv replacement with a documented first-run path and a recoverable export. - Document prerequisites, every configuration variable, data locations and the three domain workflows: Publication and consent; Campaign preparation; Send and reconcile. Include the exclusions, actual costs and source check date 2026-09-05. Commands shown earlier that reference project files are files the builder must implement before running them. - Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for beehiiv. Restore into a separate empty directory or isolated deployment, with all outbound actions and schedules disabled. Recreate this proof: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Compare ids/counts and open the result before recording the restore date. Never test a restore over the only live copy. - Use a new folder and only README instructions to reach the fixture outcome. Install from requirements.txt, initialize storage, run the tests and exercise the UI at 375px and 1280px; use keyboard-only controls and inspect browser errors. Record exactly what passed; do not mark unrun checks complete. Commands, after creating the named files: `python -m pip install -r requirements.txt`; `python -m unittest discover -s test`. - Trap: Export without an import or restore rehearsal is not verified portability. Done when: A new folder reaches the documented fixture outcome using only README instructions. A backup restored in isolation preserves the proof data and can be opened. Do not build yet: Do not start operate and share with access controls until these checks pass. ### Phase 6 · Operate and share with access controls (product-builder only) Build: Product-builder only: make a small newsletter publisher with a public archive and a safe send ledger operable for its stated audience before allowing remote access. - Add owner/member/viewer authorization as appropriate, password hashes through Werkzeug, expiring server-side sessions, CSRF and login rate limits. Add users, sessions and audit schema migrations plus an owner-init command prompting securely for its password. Enforce ownership on every private read/write/download and fail closed when product setup is incomplete. Existing learner or admin identities must use this same boundary. - Serve app:app with Waitress on loopback behind Caddy HTTPS. Configure trusted proxy headers narrowly, Secure/HttpOnly/SameSite cookies, upload limits, request ids and structured logs without private content. Run background jobs as a separate supervised process when the domain workflow requires them. Commands, after creating the named files: `waitress-serve --listen=127.0.0.1:5000 app:app`. - Add a scheduled encrypted off-host backup using this procedure: Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for beehiiv. Monitor health, disk space, failed jobs and backup age. Stop the service to test an alert; rehearse recovery with outbound effects disabled and record recovery time. Rotate any exposed credentials and require reconciliation before resuming queues. - Trap: Product mode is additional engineering, not a switch that makes a local prototype production-ready. Done when: An unauthenticated visitor cannot read private records, download private files or mutate the admin surface. A viewer cannot mutate data by making a direct request, and guessed ids cannot cross ownership boundaries. Stopping the service triggers the configured alert and the latest off-host backup restores the fixture in isolation. Do not build yet: Do not add new providers or vendor-scale features until the release gates are recorded. ### Out of scope (and why) - Referral networks, paid subscriptions and domain reputation are not reproduced by this publisher. - This is a small newsletter publisher with a public archive and a safe send ledger; full beehiiv feature parity, vendor hosting and support are not included. - email deliverability: retain the paid product if this capability is essential; it is outside this bounded build. - referral/recommendation network: retain the paid product if this capability is essential; it is outside this bounded build. - ad network: retain the paid product if this capability is essential; it is outside this bounded build. - automations: retain the paid product if this capability is essential; it is outside this bounded build. - analytics: retain the paid product if this capability is essential; it is outside this bounded build. - paid newsletter tooling: retain the paid product if this capability is essential; it is outside this bounded build. - migrations: retain the paid product if this capability is essential; it is outside this bounded build. ### README must contain - Exact install, configure, initialize, start, test and recovery commands for a clean folder. - The schema, fixture, acceptance results, private data locations and export format. - Every prerequisite and secret source, actual running costs and deliberately excluded capabilities. - An honest distinction between tests actually run and checks still awaiting real credentials or deployment. - Dependency documentation reviewed 2026-09-05: https://flask.palletsprojects.com/en/stable/installation/ ; https://docs.python.org/3/library/sqlite3.html ; https://flask-wtf.readthedocs.io/en/1.2.x/csrf/ ; https://docs.pylonsproject.org/projects/waitress/en/stable/usage.html ; https://docs.python.org/3/library/smtplib.html ; https://python-markdown.github.io/reference/ ; https://bleach.readthedocs.io/en/latest/clean.html. Recheck before upgrading; freeze the versions actually tested.
# Architecture · beehiiv ## Stack | Part | Choice | Why | | --- | --- | --- | | Runtime | Python 3.12+ and Flask | A small local HTTP application with readable server-side handlers and no JavaScript build pipeline. | | Storage | SQLite through Python sqlite3 | Local ownership with explicit transactions and a portable backup path. | | Interface | Jinja HTML templates, CSS and vanilla JavaScript | Implement the specified screens directly with labelled controls and progressive enhancement. | | Verification | Python unittest and browser acceptance fixtures | Check invariants and the actual user workflow before the next phase. | | Focused libraries | markdown, bleach | Use these only for the specific file, parsing or provider operations named in the phases; freeze tested versions. | ## Modules Each module has one owner concern and a documented way to replace it. | Module | Owns | How to replace it | | --- | --- | --- | | Data and identity | posts(id,slug,title,body,state); subscribers(id,email,status,consent_at,token_hash); campaigns(id,post_id,state); deliveries(id,campaign_id,subscriber_id,state,message_id); suppressions(email,reason,at) | Keep stable ids and a versioned repository interface; migrate storage behind it with a fixture round-trip. | | Publication and consent | Build a Markdown post editor with sanitized email/web previews and a public archive containing only published posts. | Keep the acceptance contract: Only the confirmed fixture becomes eligible for a campaign. Replace only this module after replaying its fixture; preserve ids and existing records. | | Campaign preparation | Freeze the post content and recipient ids when preparing a campaign and show an exact recipient preview before sending. | Keep the acceptance contract: Unsubscribing after preparation but before send excludes the recipient. Replace only this module after replaying its fixture; preserve ids and existing records. | | Send and reconcile | Use a unique campaign/subscriber delivery row, bounded rate and a worker lease; record accepted, failed and unknown outcomes. | Keep the acceptance contract: Restarting skips accepted delivery rows and preserves unknown rows for review. Replace only this module after replaying its fixture; preserve ids and existing records. | | Operations | Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for beehiiv. | Change host or backup destination only after an isolated restore and authorization check. | ## Configuration Every runtime setting is an environment variable documented in `.env.example`, validated at startup, with a safe local default wherever one exists. - `DATA_DIR` · required · A new private folder this application creates on first run; never serve it as static files. - `SECRET_KEY` · required, secret · Generate with python -c "import secrets; print(secrets.token_hex(32))" and save only in .env. - `APP_MODE` · required · Use indie for loopback-only personal work. Product mode must refuse to start until owner login and the deployment gates are configured. - `SITE_URL` · required · The origin used for local forms and links; replace with the chosen HTTPS origin in product mode. - `SMTP_HOST` · required · Copy the SMTP hostname from the relay dashboard. - `SMTP_PORT` · required · Use a relay supporting STARTTLS on this port; confirm it in its setup instructions. - `SMTP_USER` · required, secret · Copy the relay username; it may differ from your sign-in email. - `SMTP_PASSWORD` · required, secret · Create SMTP credentials in the relay dashboard, not your personal mailbox password. - `MAIL_FROM` · required · Your relay-verified sender address; replace before real sends. - `MAIL_TEST_TO` · required · An inbox you control for the explicit preflight test. ## Production baseline - Security: least privilege, input validation at every boundary, secret redaction in logs, rate limits on abuse-prone paths, no invented security primitives. - Data: explicit schema and migrations, transactional writes where integrity matters, backup and restore procedures that have been exercised. - Integrations: adapters around third-party providers, idempotent webhook or job processing, bounded retries, timeouts. - Observability: structured logs with request or operation ids, an error-tracking hook, and health and readiness checks where a server exists. - Quality: unit tests for domain rules, integration tests at module boundaries, one end-to-end test of the critical path. ## Decision records For each dependency in the stack table, keep a short note: why it was chosen, its failure mode, and how it is replaced. Do not add infrastructure until a requirement in `PRODUCT.md` justifies it.
# Agent instructions · beehiiv product build - Read `PRODUCT.md` and `ARCHITECTURE.md` before changing code. The stack is fixed: Python 3.12+ and Flask, SQLite through Python sqlite3, Jinja HTML templates, CSS and vanilla JavaScript, Python unittest and browser acceptance fixtures, markdown, bleach. - Implement milestone by milestone from `MILESTONES.md`; keep each change reviewable and leave the application runnable at every commit. - Treat authentication, payments, encryption, imports, webhooks and destructive actions as high-risk boundaries when present. - Never invent cryptography or silently weaken a requirement to make a check pass. - Put every external service behind an interface with a deterministic fake for tests. - Add migrations and rollback or recovery notes for every persistent data change. - Log useful operational context without credentials, tokens, passwords or personal data. - Update documentation and run every check before completing a milestone. ## Known traps - The Flask development server is for local development only. Loopback binding alone does not replace CSRF and origin validation. - The archive and email are different outputs; a preview must show both. - Do not equate successful SMTP submission with inbox delivery or a legal compliance guarantee. - Referral networks, paid subscriptions and domain reputation are not reproduced by this publisher. - Export without an import or restore rehearsal is not verified portability. - Product mode is additional engineering, not a switch that makes a local prototype production-ready.
# Delivery milestones · beehiiv Estimated effort: **multi-day** for the indie phases; the production-only milestones add the trust and operability layer. ## M1 · Local foundation and data contract Create the runnable local foundation for a small newsletter publisher with a public archive and a safe send ledger, including the real schema and acceptance fixture. ### Steps 1. Create and start the local application Run the venv command first, then stop and activate it before running the remaining commands. Use your OS instructions: Windows .venv\Scripts\activate.bat in cmd, or .venv\Scripts\Activate.ps1 in PowerShell; macOS/Linux source .venv/bin/activate. Then install the listed packages. Create app.py exposing app, load .env with python-dotenv, and add a /healthz route. Freeze tested dependency versions to requirements.txt. Create .env manually from .env.example; replace SECRET_KEY before launch. Files: `app.py`, `requirements.txt`, `.env.example`, `.gitignore` ```sh python -m venv .venv python -m pip install Flask Flask-WTF python-dotenv waitress tzdata markdown bleach python -m pip freeze > requirements.txt python -m flask --app app run --host 127.0.0.1 ``` 2. Implement storage and seed the named fixture For database-backed state create schema.sql and db.py using this model: posts(id,slug,title,body,state); subscribers(id,email,status,consent_at,token_hash); campaigns(id,post_id,state); deliveries(id,campaign_id,subscriber_id,state,message_id); suppressions(email,reason,at). Add the auxiliary relationships explicitly used in later phases; use stable ids, foreign keys, parameterized values and transactions. For canonical files use atomic replacement and hashes instead. Implement python manage.py init and python manage.py seed to create only synthetic data: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Re-running init must not erase data. Files: `schema.sql`, `db.py`, `manage.py`, `fixtures/README.md` ```sh python manage.py init python manage.py seed ``` 3. Protect the local request boundary Install Flask-WTF CSRF protection for forms and same-origin fetches, validate Host and Origin against SITE_URL, bound inputs and escape output. Deliberately public intake endpoints get bounded validation and rate limits; signed provider webhooks use signature checks instead of browser CSRF tokens. All other admin routes stay local until product authentication exists. When a later phase tests viewer/member permissions, implement the users, hashed passwords, expiring server sessions and role checks in this foundation first; product mode must never use a fabricated identity from request input. Add error, empty, keyboard-focus and retry states now. Files: `app.py`, `templates/base.html`, `test/test_foundation.py` 4. Implement and test the email adapter Create providers/mail.py using smtplib with a timeout, verified TLS/STARTTLS and an EmailMessage. Refuse placeholder credentials and non-test recipients until the owner enables sending. Implement scripts/smtp_probe.py to send one labelled message only to MAIL_TEST_TO, and provide a fake adapter for tests. Store no password or full message body in logs. Files: `providers/mail.py`, `scripts/smtp_probe.py` ```sh python scripts/smtp_probe.py ``` ### Done when - [ ] The documented start command serves /healthz and the initial screen at http://127.0.0.1:5000. - [ ] Restarting preserves the seeded records or canonical files; running init again deletes nothing. - [ ] A cross-origin state-changing request to an admin route is refused. ### Watch out - The Flask development server is for local development only. Loopback binding alone does not replace CSRF and origin validation. ## M2 · Publication and consent Publication and consent for beehiiv: Build a Markdown post editor with sanitized email/web previews and a public archive containing only published posts. ### Steps 1. Build a Markdown post editor with sanitized email/web previews and a public archive containing only published posts. Build a Markdown post editor with sanitized email/web previews and a public archive containing only published posts. Files: `features/publication_and_consent.py`, `templates/publication_and_consent.html` 2. Implement double-opt-in signup with expiring hashed tokens and a suppression list; send confirmation through the configured SMTP adapter. Implement double-opt-in signup with expiring hashed tokens and a suppression list; send confirmation through the configured SMTP adapter. Files: `features/publication_and_consent.py` 3. Exercise the acceptance fixture Use One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Check: Only the confirmed fixture becomes eligible for a campaign. Then check: A draft post cannot be fetched from its guessed archive URL. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Files: `test/test_publication_and_consent.py` ```sh python -m unittest discover -s test ``` ### Done when - [ ] Only the confirmed fixture becomes eligible for a campaign. - [ ] A draft post cannot be fetched from its guessed archive URL. ### Watch out - The archive and email are different outputs; a preview must show both. ## M3 · Campaign preparation Campaign preparation for beehiiv: Freeze the post content and recipient ids when preparing a campaign and show an exact recipient preview before sending. ### Steps 1. Freeze the post content and recipient ids when preparing a campaign and show an exact recipient preview before sending. Freeze the post content and recipient ids when preparing a campaign and show an exact recipient preview before sending. Files: `features/campaign_preparation.py`, `templates/campaign_preparation.html` 2. Add a plain-text part, visible unsubscribe link and List-Unsubscribe headers; recheck suppression immediately before each send. Add a plain-text part, visible unsubscribe link and List-Unsubscribe headers; recheck suppression immediately before each send. Files: `features/campaign_preparation.py` 3. Exercise the acceptance fixture Use One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Check: Unsubscribing after preparation but before send excludes the recipient. Then check: The email preview contains a functional unsubscribe action and no script tags. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Files: `test/test_campaign_preparation.py` ```sh python -m unittest discover -s test ``` ### Done when - [ ] Unsubscribing after preparation but before send excludes the recipient. - [ ] The email preview contains a functional unsubscribe action and no script tags. ### Watch out - Do not equate successful SMTP submission with inbox delivery or a legal compliance guarantee. ## M4 · Send and reconcile Send and reconcile for beehiiv: Use a unique campaign/subscriber delivery row, bounded rate and a worker lease; record accepted, failed and unknown outcomes. ### Steps 1. Use a unique campaign/subscriber delivery row, bounded rate and a worker lease; record accepted, failed and unknown outcomes. Use a unique campaign/subscriber delivery row, bounded rate and a worker lease; record accepted, failed and unknown outcomes. Files: `features/send_and_reconcile.py`, `templates/send_and_reconcile.html` 2. Pause on ambiguous connection loss after transmission; offer operator reconciliation rather than blindly resending. Pause on ambiguous connection loss after transmission; offer operator reconciliation rather than blindly resending. Files: `features/send_and_reconcile.py` 3. Exercise the acceptance fixture Use One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Check: Restarting skips accepted delivery rows and preserves unknown rows for review. Then check: A failed recipient does not prevent remaining eligible recipients from being processed. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Files: `test/test_send_and_reconcile.py` ```sh python -m unittest discover -s test ``` ### Done when - [ ] Restarting skips accepted delivery rows and preserves unknown rows for review. - [ ] A failed recipient does not prevent remaining eligible recipients from being processed. ### Watch out - Referral networks, paid subscriptions and domain reputation are not reproduced by this publisher. ## M5 · Portable delivery and clean-start proof Finish the beehiiv replacement with a documented first-run path and a recoverable export. ### Steps 1. Write the user-facing runbook Document prerequisites, every configuration variable, data locations and the three domain workflows: Publication and consent; Campaign preparation; Send and reconcile. Include the exclusions, actual costs and source check date 2026-09-05. Commands shown earlier that reference project files are files the builder must implement before running them. Files: `README.md`, `.env.example` 2. Create and rehearse a recoverable backup Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for beehiiv. Restore into a separate empty directory or isolated deployment, with all outbound actions and schedules disabled. Recreate this proof: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Compare ids/counts and open the result before recording the restore date. Never test a restore over the only live copy. Files: `OPERATIONS.md`, `scripts/backup.py` 3. Reproduce the first-run experience Use a new folder and only README instructions to reach the fixture outcome. Install from requirements.txt, initialize storage, run the tests and exercise the UI at 375px and 1280px; use keyboard-only controls and inspect browser errors. Record exactly what passed; do not mark unrun checks complete. Files: `README.md`, `verification.md` ```sh python -m pip install -r requirements.txt python -m unittest discover -s test ``` ### Done when - [ ] A new folder reaches the documented fixture outcome using only README instructions. - [ ] A backup restored in isolation preserves the proof data and can be opened. ### Watch out - Export without an import or restore rehearsal is not verified portability. ## M6 · Operate and share with access controls (production only) Product-builder only: make a small newsletter publisher with a public archive and a safe send ledger operable for its stated audience before allowing remote access. ### Steps 1. Establish owner access before exposure Add owner/member/viewer authorization as appropriate, password hashes through Werkzeug, expiring server-side sessions, CSRF and login rate limits. Add users, sessions and audit schema migrations plus an owner-init command prompting securely for its password. Enforce ownership on every private read/write/download and fail closed when product setup is incomplete. Existing learner or admin identities must use this same boundary. Files: `ARCHITECTURE.md`, `OPERATIONS.md` 2. Deploy a monitored service Serve app:app with Waitress on loopback behind Caddy HTTPS. Configure trusted proxy headers narrowly, Secure/HttpOnly/SameSite cookies, upload limits, request ids and structured logs without private content. Run background jobs as a separate supervised process when the domain workflow requires them. Files: `Caddyfile`, `OPERATIONS.md` ```sh waitress-serve --listen=127.0.0.1:5000 app:app ``` 3. Rehearse loss and recovery Add a scheduled encrypted off-host backup using this procedure: Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for beehiiv. Monitor health, disk space, failed jobs and backup age. Stop the service to test an alert; rehearse recovery with outbound effects disabled and record recovery time. Rotate any exposed credentials and require reconciliation before resuming queues. Files: `OPERATIONS.md`, `release-checklist.md` ### Done when - [ ] An unauthenticated visitor cannot read private records, download private files or mutate the admin surface. - [ ] A viewer cannot mutate data by making a direct request, and guessed ids cannot cross ownership boundaries. - [ ] Stopping the service triggers the configured alert and the latest off-host backup restores the fixture in isolation. ### Watch out - Product mode is additional engineering, not a switch that makes a local prototype production-ready.
# Operations · beehiiv ## Backup Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for beehiiv. ## Restore Restore into a separate empty directory or isolated deployment, with all outbound actions and schedules disabled. Recreate this proof: One confirmed subscriber, one unconfirmed address and one suppressed address; a draft post. Compare ids/counts and open the result before recording the restore date. Never test a restore over the only live copy. Do a restore drill before the first real user, and write the date here when it passes. ## Monitoring Check HTTP availability, free disk, backup age and domain failures for Publication and consent, Campaign preparation, Send and reconcile. Alert without logging private payloads. ## Incident checklist Pause outbound jobs and public intake as appropriate, preserve redacted diagnostics, restore an isolated verified backup, rotate affected credentials and reconcile uncertain effects before reopening. 1. Contain the issue without destroying evidence or user data. 2. Record the timeline and affected scope. 3. Rotate exposed secrets and revoke compromised sessions or credentials. 4. Restore from a verified backup when needed. 5. Document the root cause, the remediation and the regression test. ## Release gate - [ ] Only the confirmed fixture becomes eligible for a campaign. - [ ] Unsubscribing after preparation but before send excludes the recipient. - [ ] Restarting skips accepted delivery rows and preserves unknown rows for review. - [ ] A private-data authorization check passes using a second identity. - [ ] An off-host restore drill has a date, observed result and recovery time in OPERATIONS.md. - [ ] README names the excluded vendor capabilities and actual provider/hosting costs. ## Launch constraint Do not market omitted beehiiv capabilities as implemented. The non-goals in `PRODUCT.md` remain user-visible limitations until they are deliberately delivered.
# Copy to .env and fill in. Never commit .env; this file documents it. # Required. A new private folder this application creates on first run; never serve it as static files. DATA_DIR=./data/beehiiv # Required · secret. Generate with python -c "import secrets; print(secrets.token_hex(32))" and save only in .env. SECRET_KEY=replace-with-a-random-secret # Required. Use indie for loopback-only personal work. Product mode must refuse to start until owner login and the deployment gates are configured. APP_MODE=indie # Required. The origin used for local forms and links; replace with the chosen HTTPS origin in product mode. SITE_URL=http://127.0.0.1:5000 # Required. Copy the SMTP hostname from the relay dashboard. SMTP_HOST=replace-with-relay-host # Required. Use a relay supporting STARTTLS on this port; confirm it in its setup instructions. SMTP_PORT=587 # Required · secret. Copy the relay username; it may differ from your sign-in email. SMTP_USER=replace-with-smtp-user # Required · secret. Create SMTP credentials in the relay dashboard, not your personal mailbox password. SMTP_PASSWORD=replace-with-smtp-password # Required. Your relay-verified sender address; replace before real sends. MAIL_FROM=owner@example.com # Required. An inbox you control for the explicit preflight test. MAIL_TEST_TO=owner@example.com
$ choose a build depth, inspect the files, then open the complete pack in your agent
They pay because audience growth and email reliability are harder than writing and sending HTML.
xemail deliverability
xreferral/recommendation network
xad network
xautomations
xanalytics
xpaid newsletter tooling
xmigrations
Don't feel like building it? These folks already made it free.
no votes, no pay-to-list · just what's real
beehiiv pricing
| plan | monthly | annual (per mo) | what you get |
|---|---|---|---|
| launch | $0/workspace | $0/workspace | Up to 2,500 subscribers, unlimited email sends, 3 publications, 1 team member, 10 AI credits/day, 1 podcast episode/month, 1 show. |
| scale | $49/workspace | $43/workspace | Up to 100,000 subscribers, unlimited sends/posts, 3 publications, up to 3 team seats, 25 AI credits/day, 4 podcast episodes/month. |
| max | $109/workspace | $96/workspace | Up to 100,000 subscribers, 10 publications, unlimited team seats, 50 AI credits/day, unlimited podcast episodes, 3 shows, 3 Getty credits. |
| enterprise | custom | — | 100,000+ subscribers, custom publications/subscriber limits, 100 AI credits/day, 10 Getty credits, dedicated IPs, SSO, account manager. |
free tier$0; 2,500 subscribers, unlimited sends, 3 publications, 1 team member, 10 AI credits/day, 1 podcast episode/month, 1 show.
billingmonthly + annual; annual cards show lower per-month price billed annually
hidden costsStripe processing applies to paid subscriptions; beehiiv take rate is 0% on paid subscription revenue; Enterprise needed above 100K/custom limits.
verified 2026-08-10 · source ↗
Vibecode beehiiv
Kinda. The core of beehiiv is buildable in a weekend with the prompt on this page, but there are real gaps: email deliverability, referral/recommendation network. Read the honest list above before committing.
How much does beehiiv cost?
beehiiv costs about $49/month (Scale, checked 2026-07-30), which is $588 per year.
What do I lose by replacing beehiiv?
Honestly: email deliverability; referral/recommendation network; ad network; automations; analytics; paid newsletter tooling; migrations. If any of those are load-bearing for you, keep paying.
Is there an open-source alternative to beehiiv?
Yes: Ghost (Publishing, newsletters, memberships and paid subscriptions on your server; beehiiv's ad network and growth machinery stay behind.) The prompt is for when you want it exactly your way.