newsman

Self-host one newsletter on Cloudflare, deliver through Amazon SES, and run every web operation through an allowlisted HTTP MCP server.

This is a web app spec on Spekkr, published by dwrtz. It is listed with the other specs. Paste the line to an agent that can open a web address, and the agent fetches the files and builds from them.

Spec
dwrtz/newsman
Version
0.1.0
Published by
dwrtz
Updated
24 Nov 2026

This is version 0.1.0. The newest version is 0.4.1.

Build this version

Build the spec at https://spekkr.com/dwrtz/newsman/v/0.1.0/start.md.

Paste this to your AI agent. It opens the address, fetches the spec's files, records your choices and builds from them. Nothing to install, no account.

Published by dwrtz.

What can I customize?

Your choices go into the line you copy. Anything else is yours to edit, but it leaves the tested path.

What do I get?

  • spec.md Product scope and nine requirements with acceptance checks.

    newsman

    One publication per installation. A publisher runs newsman in their own Cloudflare account and pays Amazon SES for the email they send. An editor can operate the entire newsletter from the web console or from a remote MCP client. Readers use the publication’s existing website and their email inbox.

    R1. Install and admit operators

    Deploy the Worker, its static console, subscriber D1, private object storage, delivery queue and dead-letter queue in the publisher’s account. Configure one public origin, from identity, monitored reply address, postal footer, SES region and feedback topic. A deploy-time initial owner and exact verified identities form the operator allowlist. One entry is a complete single-user installation. The allowlist controls operators. Readers may request a subscription without an operator identity. Show setup status and the specific outstanding prerequisite before enabling a live send. See operator access and delivery.

    Accept when a fresh installation with one allowed identity can preview a draft through either interface. An unlisted identity cannot read audience data, call operator tools, or acquire a grant. A misconfigured installation still gives its owner actionable diagnostics.

    R2. Subscribe on the existing site

    Accept a standard email-only form, including with JavaScript off. Record the first valid campaign attribution and consent wording version. Use the same check-inbox response for new, pending, active and suppressed addresses. An eligible pending reader gets a confirmation email. Limit resends and stale tokens. The link opens a landing page and an explicit confirmation submits the proof, so a link scanner’s GET cannot opt anyone in. A reader becomes active exactly once. The confirmed page is a destination people may revisit. A deliberate new opt-in can lift a voluntary unsubscribe with fresh proof and an audit trail. Hard-bounce, complaint and administrative holds win over self-service. Support a visible unsubscribe link and RFC 8058 one-click POST. See migration for old links.

    Accept when replaying signup and confirmation gives one active reader and one first-confirmation event. A simple form POST, a resend and a browser reload produce the same subscription state as the corresponding reader tools.

    R3. Manage the audience

    Search subscribers, inspect consent history and provenance, tag or remove tags, define named segments, preview their membership, suppress an address, and erase or export a reader’s personal data. Suppression takes effect on queued mail. Retain the minimum keyed suppression tombstone needed to honor prior opt-outs, subject to the publisher’s disclosed retention policy. Import and export through bounded transfers with downloadable machine-readable results. Dry-run an import and count actionable, duplicate, held and unknown rows before applying it. A provider’s verified active status with provenance may be migrated. Uncertain records stay ineligible. Never infer consent from an address alone.

    Accept when importing a stale active row alongside a prior complaint keeps the address suppressed. Tags and saved segment membership filter the same list in the console, exported CSV and MCP.

    R4. Edit an issue and prepare its email

    An editor can write an issue in the console or submit an edition bundle from an existing publisher workflow. Import a stable external key, canonical path, edition and archive timestamps, source HTML, title, summary and optional hero. For AudioTech, the checked-in edition remains the editorial source. The import adapter runs beside the site build and pushes an immutable revision to newsman. A changed source creates a new revision for review. Surface local mail-only edits before replacing a draft. Editing subjects, preheaders, sender settings, content, template and alt text must work programmatically. Store versions and present the exact text and sanitized HTML of a preview, including image references and links. Stage an embargo-safe mail hero separately from the public archive.

    Accept when an operator can create a blank edition, import a second edition, revise one, upload an image, inspect its rendered email and send an allowlisted test. A source correction or template change cannot silently change an approved send. The same frozen inputs produce the same rendered digest. Draft revisions are restorable.

    R5. Review, send and stop

    Display subject, from/reply-to, audience rule, estimated eligible count, suppression exclusions, snapshot digest, scheduled instant in UTC and publication time, and forecast provider sends. Support a test message, immediate dispatch, future scheduling and cancellation. Both interfaces use a prepare step followed by a commit bound to the exact plan. Either interface can perform both steps. A changed revision, audience rule, settings or expired plan requires another review. Snapshot membership and approved content at commit. Exclusions may always reduce delivery. A reader who confirms after the snapshot becomes eligible for a later edition. For a scheduled send, cancellation stops work that has yet to cross the provider boundary.

    Accept when replaying a commit returns one campaign. A suppressed reader is skipped even if present in its snapshot. The operator can see accepted, delivered, suppressed, failed and uncertain counts and inspect unresolved attempts. The operator can stop remaining work through either interface.

    R6. Respect archive timing

    The publisher’s existing website owns its canonical routes, asset deployment and feed. Newsman tracks edition time, expected public release and externally observed release as distinct fields. It hands an archive bundle to the publisher and can verify the live canonical URL and feed entry after release. Handle web-first, simultaneous or delayed publishing. For AudioTech, default the public release to one edition week later. During the gap, omit a read-online link to an unpublished issue. Emails with images must render using a mail-appropriate asset address. A failed/pending release stays visible as such in both interfaces.

    Accept when sending a Friday issue permits an approved Friday send and a public release one week later without an early listing or a broken read-online link. A correction preserves the canonical URL and Atom entry ID, and does not dispatch a second campaign.

    R7. Report useful outcomes

    Report accepted and delivered separately. For each edition show hard bounces, complaints, opt-outs and distinct editorial clickers per delivered recipient. Record link purpose so sponsor and editorial clicks can be reported separately. Label bot-filtering assumptions, measurement window and denominator. When click tracking is disabled report that signal as unavailable. A click proxy cannot establish a verified human read. Aggregate first-confirmations by first-touch campaign and cohort; preserve unknown attribution. Export subscriber, consent, delivery, link and aggregated reports with documented fields. UTC timestamps travel over the wire, and the selected publication time zone controls day or week labels in the console.

    Accept when receiving the same provider event twice changes a report once, a confirmed signup belongs to one acquisition cohort, and web and MCP produce matching report numbers and export digests.

    R8. Manage the publication over HTTP MCP

    Use one domain operation registry for the web console and the HTTPS MCP server. The operator endpoint is /mcp. Every web query, mutation, preview, data transfer, setting, allowlist change, grant revocation and recovery action offered in the console has a named MCP tool with the same authorization and results. Public reader interactions offered by newsman have corresponding reader tools at /reader/mcp; a subscriber can act only with the applicable proof. Links into the host site remain ordinary links. Authentication and granting a client consent use the OAuth/identity-provider protocol. Once connected, an authorized client can run the entire publishing workflow over HTTP. Operation registry · Parity contract · Access contract

    Accept when a standard remote MCP client can go from an empty publication through signup, draft, proof, scheduled send, provider feedback, reporting and export in a test environment. A web control that reaches a domain operation missing from MCP fails the release build.

    R9. Operate and recover

    Support recipient-level audit and redaction, paginated operator history, provider health, queue lag, manual pause, resumable jobs and safe recovery. Credentials and message proofs stay out of logs and tool results. A restore exercise reconciles provider activity and opt-outs before sending resumes. Include a migration from beehiiv, a budget calculation and an owner-operated rollback procedure. Delivery · Migration · Build and acceptance

    Accept when the same issue is processed under queue redelivery and a simulated provider timeout without an automatic duplicate submission. Rehearsal totals account for every imported row, and a rollback honors opt-outs through either system.

    # newsman
    
    One publication per installation. A publisher runs newsman in their own Cloudflare account and pays Amazon SES for the email they send. An editor can operate the entire newsletter from the web console or from a remote MCP client. Readers use the publication’s existing website and their email inbox.
    
    ## R1. Install and admit operators
    
    Deploy the Worker, its static console, subscriber D1, private object storage, delivery queue and dead-letter queue in the publisher’s account. Configure one public origin, from identity, monitored reply address, postal footer, SES region and feedback topic. A deploy-time initial owner and exact verified identities form the operator allowlist. One entry is a complete single-user installation. The allowlist controls operators. Readers may request a subscription without an operator identity. Show setup status and the specific outstanding prerequisite before enabling a live send. See [operator access](access.md) and [delivery](delivery.md).
    
    **Accept when** a fresh installation with one allowed identity can preview a draft through either interface. An unlisted identity cannot read audience data, call operator tools, or acquire a grant. A misconfigured installation still gives its owner actionable diagnostics.
    
    ## R2. Subscribe on the existing site
    
    Accept a standard email-only form, including with JavaScript off. Record the first valid campaign attribution and consent wording version. Use the same check-inbox response for new, pending, active and suppressed addresses. An eligible pending reader gets a confirmation email. Limit resends and stale tokens. The link opens a landing page and an explicit confirmation submits the proof, so a link scanner’s GET cannot opt anyone in. A reader becomes active exactly once. The confirmed page is a destination people may revisit. A deliberate new opt-in can lift a voluntary unsubscribe with fresh proof and an audit trail. Hard-bounce, complaint and administrative holds win over self-service. Support a visible unsubscribe link and RFC 8058 one-click POST. See [migration](migration.md) for old links.
    
    **Accept when** replaying signup and confirmation gives one active reader and one first-confirmation event. A simple form POST, a resend and a browser reload produce the same subscription state as the corresponding reader tools.
    
    ## R3. Manage the audience
    
    Search subscribers, inspect consent history and provenance, tag or remove tags, define named segments, preview their membership, suppress an address, and erase or export a reader’s personal data. Suppression takes effect on queued mail. Retain the minimum keyed suppression tombstone needed to honor prior opt-outs, subject to the publisher’s disclosed retention policy. Import and export through bounded transfers with downloadable machine-readable results. Dry-run an import and count actionable, duplicate, held and unknown rows before applying it. A provider’s verified active status with provenance may be migrated. Uncertain records stay ineligible. Never infer consent from an address alone.
    
    **Accept when** importing a stale active row alongside a prior complaint keeps the address suppressed. Tags and saved segment membership filter the same list in the console, exported CSV and MCP.
    
    ## R4. Edit an issue and prepare its email
    
    An editor can write an issue in the console or submit an edition bundle from an existing publisher workflow. Import a stable external key, canonical path, edition and archive timestamps, source HTML, title, summary and optional hero. For AudioTech, the checked-in edition remains the editorial source. The import adapter runs beside the site build and pushes an immutable revision to newsman. A changed source creates a new revision for review. Surface local mail-only edits before replacing a draft. Editing subjects, preheaders, sender settings, content, template and alt text must work programmatically. Store versions and present the exact text and sanitized HTML of a preview, including image references and links. Stage an embargo-safe mail hero separately from the public archive.
    
    **Accept when** an operator can create a blank edition, import a second edition, revise one, upload an image, inspect its rendered email and send an allowlisted test. A source correction or template change cannot silently change an approved send. The same frozen inputs produce the same rendered digest. Draft revisions are restorable.
    
    ## R5. Review, send and stop
    
    Display subject, from/reply-to, audience rule, estimated eligible count, suppression exclusions, snapshot digest, scheduled instant in UTC and publication time, and forecast provider sends. Support a test message, immediate dispatch, future scheduling and cancellation. Both interfaces use a prepare step followed by a commit bound to the exact plan. Either interface can perform both steps. A changed revision, audience rule, settings or expired plan requires another review. Snapshot membership and approved content at commit. Exclusions may always reduce delivery. A reader who confirms after the snapshot becomes eligible for a later edition. For a scheduled send, cancellation stops work that has yet to cross the provider boundary.
    
    **Accept when** replaying a commit returns one campaign. A suppressed reader is skipped even if present in its snapshot. The operator can see accepted, delivered, suppressed, failed and uncertain counts and inspect unresolved attempts. The operator can stop remaining work through either interface.
    
    ## R6. Respect archive timing
    
    The publisher’s existing website owns its canonical routes, asset deployment and feed. Newsman tracks edition time, expected public release and externally observed release as distinct fields. It hands an archive bundle to the publisher and can verify the live canonical URL and feed entry after release. Handle web-first, simultaneous or delayed publishing. For AudioTech, default the public release to one edition week later. During the gap, omit a read-online link to an unpublished issue. Emails with images must render using a mail-appropriate asset address. A failed/pending release stays visible as such in both interfaces.
    
    **Accept when** sending a Friday issue permits an approved Friday send and a public release one week later without an early listing or a broken read-online link. A correction preserves the canonical URL and Atom entry ID, and does not dispatch a second campaign.
    
    ## R7. Report useful outcomes
    
    Report accepted and delivered separately. For each edition show hard bounces, complaints, opt-outs and distinct editorial clickers per delivered recipient. Record link purpose so sponsor and editorial clicks can be reported separately. Label bot-filtering assumptions, measurement window and denominator. When click tracking is disabled report that signal as unavailable. A click proxy cannot establish a verified human read. Aggregate first-confirmations by first-touch campaign and cohort; preserve unknown attribution. Export subscriber, consent, delivery, link and aggregated reports with documented fields. UTC timestamps travel over the wire, and the selected publication time zone controls day or week labels in the console.
    
    **Accept when** receiving the same provider event twice changes a report once, a confirmed signup belongs to one acquisition cohort, and web and MCP produce matching report numbers and export digests.
    
    ## R8. Manage the publication over HTTP MCP
    
    Use one domain operation registry for the web console and the HTTPS MCP server. The operator endpoint is `/mcp`. Every web query, mutation, preview, data transfer, setting, allowlist change, grant revocation and recovery action offered in the console has a named MCP tool with the same authorization and results. Public reader interactions offered by newsman have corresponding reader tools at `/reader/mcp`; a subscriber can act only with the applicable proof. Links into the host site remain ordinary links. Authentication and granting a client consent use the OAuth/identity-provider protocol. Once connected, an authorized client can run the entire publishing workflow over HTTP. [Operation registry](operations.json) · [Parity contract](parity.md) · [Access contract](access.md)
    
    **Accept when** a standard remote MCP client can go from an empty publication through signup, draft, proof, scheduled send, provider feedback, reporting and export in a test environment. A web control that reaches a domain operation missing from MCP fails the release build.
    
    ## R9. Operate and recover
    
    Support recipient-level audit and redaction, paginated operator history, provider health, queue lag, manual pause, resumable jobs and safe recovery. Credentials and message proofs stay out of logs and tool results. A restore exercise reconciles provider activity and opt-outs before sending resumes. Include a migration from beehiiv, a budget calculation and an owner-operated rollback procedure. [Delivery](delivery.md) · [Migration](migration.md) · [Build and acceptance](acceptance.md)
    
    **Accept when** the same issue is processed under queue redelivery and a simulated provider timeout without an automatic duplicate submission. Rehearsal totals account for every imported row, and a rollback honors opt-outs through either system.
    
    

    Open spec.md as plain text

  • operations.json Machine-readable operation inventory with JSON Schemas, scopes and UI views for operator and reader tools.
  • parity.md Shared web/MCP execution contract, wire examples, file transfer and a release-blocking parity test.
    # Web and HTTP MCP parity
    
    The release contract is a set equality. Every publication operation reachable from a web screen must exist in MCP for the same actor. Both interfaces call the same validator, permission check, command or query, and receipt store. A button opening a browser, returning an admin URL or asking someone to click “finish” in the console cannot complete an MCP action. A prompt or free-form SQL tool cannot substitute for a missing operation.
    
    ## Machine-readable inventory
    
    [operations.json](operations.json) declares each operation's stable name, surface, screen, scope, mode, description, input and output. Resolve schema references against the file's shared definitions. When emitting `tools/list`, expand a root reference into a root object and attach its transitively reachable `$defs` to each input and output schema. Use JSON Schema 2020-12. A single registry drives MCP tool descriptors, web command identifiers, server dispatch, input validation, structured results and the parity test. Every screen declares its read queries as well as its buttons. Tab selection, local sorting, text selection and OAuth login or consent are client or identity-protocol interactions. Domain-visible settings and grant revocation are shared operations.
    
    | Web workflow | Example tool sequence |
    | --- | --- |
    | Check who can operate the publication | `operators_list`, `operators_add`, `grants_list`, `grants_revoke`, `operators_remove` |
    | Start with an existing issue or an empty editor | `file_begin` → `file_write` → `file_finish` → `issue_import`, or `issue_create` → `issue_update` |
    | Review and send | `issue_render` → `send_test` → `send_prepare` → `send_commit` → `campaign_get`. Use `send_cancel` to stop pending work. |
    | Rehearse a migration | Stage source files → `import_prepare` → `import_commit` → `job_get` → `migration_status`. Subsequent deltas use `migration_reconcile`. |
    | Download private data | `export_create` → `job_get` → successive `file_read` calls. A client can reconstruct and verify all bytes. |
    | Manage a subscription | On the reader endpoint, `reader_subscribe`, `reader_resend`, `reader_confirm` and `reader_unsubscribe` use the same public contract as the HTML flow. |
    | Hand an edition to an existing site | `archive_bundle` → `job_get` → `file_read`; after the host publishes it, `archive_verify` records the observed result. |
    
    ## Requests and results
    
    MCP speaks JSON-RPC over HTTPS using Streamable HTTP at `/mcp` for operators and `/reader/mcp` for readers. Implement lifecycle and discovery before calling tools. After initialization, send the negotiated protocol version. For `tools/list`, clients follow pagination to exhaustion if the server paginates. Never infer that the first page is the complete inventory. The web adapter can use a same-origin command route with a cookie and CSRF protection. A browser authorization cookie is unnecessary for an MCP call with a valid grant. [Transport and identity details](access.md)
    
    A successful call returns the typed result in `structuredContent` and an equivalent JSON text content item for clients that use text. Use the same fields, ISO 8601 UTC instants, filter semantics and cursor ordering on the web. Pages sort by an explicit immutable key with ID as a tie-breaker. Bind each opaque cursor to its operation, filter and stable read cut. Reject modified or mismatched cursors. Long-running actions return durable jobs with progress and an optional result file. Polling is sufficient. Never put an email address, reader proof or OAuth credential into diagnostic context.
    
    Operator commands take a caller-generated `key`. Scope it to the instance, operator membership and operation; web and MCP can retry each other's calls. Authorize every replay. Persist the canonical input digest, result or job reference, and command receipt atomically at the mutation boundary. Same key and input returns the first result, even when a revision has advanced. A different payload under that key returns `idempotency_conflict`. An unrecognized key modifying stale state returns `revision_conflict` with the current revision when permitted. Reader actions use challenge and consent state to deduplicate. Enforce rate limits and the same generic responses on both reader entry points.
    
    Use protocol errors for malformed JSON-RPC and unknown methods. Authentication errors use the HTTP challenge defined in the access contract. Known tool execution failures return `isError: true` with a stable code, actionable message, retryability and permitted detail. Specify parity fixtures for `invalid_input`, `not_found`, `permission_denied`, `revision_conflict`, `idempotency_conflict`, `expired_plan`, `rate_limited`, `suppressed`, `dispatch_paused` and `outcome_unknown`. Public signup conceals individual suppression and membership states. Showing a file, job or audit record requires both the operation scope and authority for the underlying data. Metadata about sensitive jobs obeys the same rule as their result.
    
    ### A send from an MCP client
    
    After authentication and initialization, a client calls `send_prepare` for the issue revision and segment it reviewed. Omitting `due_at` requests immediate dispatch upon commit. A future instant schedules the same campaign.
    
    ```json
    {"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"send_prepare","arguments":{"key":"prepare-week-014","issue_id":"issue-014","issue_version":3,"audience":{"statuses":["active"]},"due_at":"2027-01-08T10:00:00Z"}}}
    ```
    
    The result includes the plan ID, subject, sender, time, estimated cost and counts, the audience and issue digests, expiry, and a digest for the complete plan. The cost object specifies the currency, estimated message count and SES base charge. A client submits the exact server-returned ID and digest to `send_commit` with a fresh command key. Check for intervening content, settings or membership changes before commit. Make membership cuts reproducible via a materialized or versioned set. Require another prepare if the eligible audience changed before commit. After commit, suppressions still take immediate precedence over queued work. The same two operations power the web review and final send button.
    
    ```json
    {"jsonrpc":"2.0","id":9,"method":"tools/call","params":{"name":"campaign_get","arguments":{"id":"campaign-014"}}}
    ```
    
    ### Files and issue bundles
    
    Receive uploads in ordered chunks of at most 49,152 decoded bytes. Verify chunk offsets/digests, total bytes and final SHA-256. Limit staged objects to 25 MiB for v1 and expire unfinished uploads after 24 hours. Read chunks under the caller’s grant and verify the full hash at EOF. Reject arbitrary URL fetches. For migration and export data also require `admin` on each transfer step. A grant for all four operator scopes can perform the complete workflow. Validate images by actual type, size and dimensions. Treat imported markup as untrusted, render only allowed email markup and produce a text part. Fetch archive checks only on the configured publication origin. The host remains in charge of its public deployment.
    
    An `issue_bundle` is UTF-8 JSON with format version 1, a `source` object conforming to the registry, and optional email overrides for subject, preheader and text. The client uploads a hero first and references its sealed asset ID. Hash the exact bundle bytes. A new external key creates one issue. A matching key and hash returns the existing revision. A different digest requires the expected current revision. Blank editor drafts and imported issues converge on the same renderer. A template uses a single issue-body slot, explicit text fallbacks and escaped fields. Reject unresolved tokens before approval. Derive per-recipient unsubscribe and optional link-tracking capabilities only at delivery.
    
    ## Contract test that blocks release
    
    1. Render each web screen with all features enabled on a fresh single-publication installation. Collect every declared query and action ID, plus actions observed from actual browser interactions. Fail on handler calls that bypass the registry, unregistered forms, missing reports, missing uploads or a web action implemented only as a privileged route.
    2. Initialize an external SDK client against the HTTP Worker. For an allowlisted operator with all scopes, compare the complete operator tool list with the operator web inventory and registry. Repeat independently for the reader surface. Compare input and output schema hashes after expanding references. Missing tools, orphan tools, unexpected scope drift and schema mismatches fail CI.
    3. For every operation, run the same fixture against the web adapter and the remote client on independent copies of the initial database, with a fixed clock, stable ID factory, test mailbox and simulated SNS. Compare structured output, state changes, emitted jobs, audit actor, final sends and file contents. Normalize only transport-specific IDs/headers and the recorded channel. Exercise invalid and forbidden inputs as well as the success case. An opaque download, job or preview handle is complete only if the MCP test can retrieve the result.
    4. Run cross-channel retries on the same database. Submit an approved send on web, replay through MCP as the same operator and observe one campaign and one mail capture per eligible recipient. Reverse the channels, then try a different payload with the same key. Test removal of an operator and grant revocation during an active client session. Add a dummy web-only action in a negative build fixture and assert the parity suite fails.
    

    Open parity.md as plain text

  • access.md Allowlisted identities, delegated OAuth, token revocation, reader proofs and Streamable HTTP.
    # Operator access and remote MCP
    
    One deployment serves one publication. A solo operator and a small editorial team use the same configuration. Any active operator can run every publication operation, including managing the allowlist. An operator can delegate fewer operations to an MCP client. Newsletter subscribers have a separate identity and lifecycle.
    
    ## Entry points
    
    | Endpoint | Caller and authentication |
    | --- | --- |
    | Operator web app and its command API | A human signs in through Cloudflare Access. On every request the Worker validates the signed Access application JWT and resolves an active operator. State-changing browser calls also require an allowed Origin and a CSRF token. |
    | `POST /mcp` | A remote client presents a newsman OAuth bearer token issued for the canonical HTTPS `/mcp` URL. Authentication failures return an HTTP challenge a client can read. |
    | OAuth authorization and consent page | The operator signs in with Access, sees the identified client, resource, requested scopes and duration, and submits a CSRF-protected consent decision. Bind the pending authorization transaction to that operator and browser. |
    | Discovery, token and revocation endpoints | Accessible to OAuth clients over HTTPS. Apply the provider's client, authorization code, PKCE and refresh checks at the relevant endpoints. Configure Access path policies around browser routes so protocol requests reach the Worker directly. |
    | Reader form, email-link endpoints and `POST /reader/mcp` | Open signup and resend take bounded anonymous requests. A reader presents a purpose-bound capability from their own email for confirmation or unsubscribe. The reader endpoint offers only public reader operations. |
    
    The canonical operator origin, OAuth issuer and MCP resource identifier are deployment settings. Preview has its own audiences, storage and issuer/resource pair. Scope Access policies to the actual browser routes on each hostname, including both methods of the consent endpoint. Verify the primary domain and any alternate Worker URL enforce the same identity checks. [Cloudflare Access application JWT verification](https://developers.cloudflare.com/cloudflare-one/access-controls/applications/http-apps/authorization-cookie/validating-json/) · [Cloudflare remote MCP authorization](https://developers.cloudflare.com/agents/model-context-protocol/protocol/authorization/)
    
    ## Allowlist and grants
    
    1. Provision one or more explicit operator email addresses through a one-time deployment bootstrap. An empty list leaves the operator surfaces closed. Bootstrap runs once per new instance. A later deploy preserves additions and removals. An authorized infrastructure owner can recover access through an explicit audited membership repair against D1.
    2. Configure Access with a trusted identity provider or verified email login. Read the assertion from `Cf-Access-Jwt-Assertion`. Verify its signature against the configured team's rotating keys, issuer, expected application audience and validity window. Accept an asserted human identity with an email and a stable subject. Service tokens and unsigned email headers cannot claim a seat.
    3. Store allowlist entries in D1 under immutable operator IDs. Trim and case-fold email consistently, using exact addresses without domain wildcards, alias stripping or plus-address rewriting. On first login atomically bind the eligible address to the verified issuer and subject. Subsequent requests must match the bound identity and active entry. Changing identities requires an explicit membership change.
    4. `operators_list`, `operators_add` and `operators_remove` have the same behavior in the web app and MCP. List whether an address is awaiting first login or bound. Prevent removing the last bound active operator in the same transaction as removal. An unclaimed invitation cannot serve as that operator. Removing someone disables their entry and revokes their grants. Re-adding an address creates a fresh membership generation.
    5. Keep a D1 authorization ledger keyed by an opaque grant reference, operator ID, membership generation, client, scopes, status and timestamps. Store the reference and generation in server-controlled OAuth grant properties. `grants_list` shows who authorized which client and scopes. `grants_revoke` invalidates the ledger entry first, then revokes the corresponding provider grant. Retry provider cleanup if needed. These views show metadata only.
    6. Check current membership in primary-consistent D1 on each web command, OAuth code/refresh exchange and MCP request. MCP also requires an active grant for the same generation and client. Evaluate membership/grant as a write precondition when accepting a mutation. After a committed removal or revocation, old cookies and outstanding tokens cannot admit another command, even during provider-cache propagation. An authorization-store outage returns a temporary failure. Already accepted sends follow their recorded job and cancellation semantics. [Cloudflare OAuth provider](https://github.com/cloudflare/workers-oauth-provider) · [D1 consistency](https://developers.cloudflare.com/d1/best-practices/read-replication/)
    
    ## Remote authorization
    
    Use the Cloudflare Workers OAuth Provider for the authorization server and protected-resource adapter. Allocate its private `OAUTH_KV` binding in each environment. Token validation can use a private Worker service binding when the issuer and resource server are deployed separately. Restrict the issuer to the configured newsman resource. The provider handles token material. The application owns its membership ledger, grant checks and consent screen. [Workers OAuth Provider](https://github.com/cloudflare/workers-oauth-provider)
    
    - An unauthenticated `/mcp` call receives HTTP 401 with `WWW-Authenticate: Bearer resource_metadata="https://news.example/.well-known/oauth-protected-resource/mcp"` using the installation's actual origin. Publish matching RFC 9728 resource metadata and RFC 8414 issuer metadata with authorization, token and revocation endpoints, supported scopes and S256. For a small deployment, support pre-registered clients with their exact permitted redirect URIs. Document the endpoint, client ID and callback the operator must register.
    - Use the authorization code flow with PKCE S256 and client-checked state. Bind each single-use code to the grant, client, redirect URI and exact resource. Require the same resource during code exchange. Issue short-lived access tokens, e.g. 15 minutes. Validate token audience, expiry, client, grant and scope on every call. Reject an Access login JWT, a reader link or a token issued by another instance as an MCP credential.
    - The application scopes are `read`, `write`, `send` and `admin`. The operation catalog specifies the scope for every tool. Each scope grants its listed actions independently. Approving all four gives an allowlisted operator's full web capabilities. Choose individual scopes for a reporting or publishing client. Missing scope returns HTTP 403 with an `insufficient_scope` Bearer challenge. An invalid or expired bearer returns 401.
    - With separately consented `offline_access`, an unattended client can store its refresh token privately, refresh within the granted resource and scopes, and renew credentials without a browser during the grant's lifetime. Rotate refresh tokens according to the provider's supported policy and reject reuse outside its documented retry window. Grant revocation or membership removal ends this access. Token or grant secrets stay out of logs and application exports. [MCP authorization](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization)
    
    ## Streamable HTTP behavior
    
    Implement the published MCP `2025-11-25` baseline on both endpoints. Use UTF-8 JSON-RPC 2.0 over Streamable HTTP. Each client POST carries one message, `Content-Type: application/json` and an Accept header allowing JSON and event streams. For this stateless profile the server returns JSON for requests, 202 with an empty body for accepted notifications and 405 for an authenticated operator GET or a reader GET requesting a standalone stream. No MCP session ID or sticky Worker is needed. Reject a present, disallowed HTTP Origin with 403. Headless clients may omit Origin.
    
    Support `initialize`, `notifications/initialized`, `ping`, `tools/list` and `tools/call`. Advertise tools and only implemented capabilities. Return the baseline if offered or propose a supported revision when the client's proposed version differs. The client continues only when it supports the returned revision. Subsequent requests carry the negotiated `MCP-Protocol-Version`. Reject unsupported versions with 400. Pin and test the SDK against this baseline before advertising another revision. [MCP transport](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports) · [MCP lifecycle](https://modelcontextprotocol.io/specification/2025-11-25/basic/lifecycle)
    
    For authenticated operators, both adapters invoke the same command with the resolved actor, input schema, idempotency key, revision and audit context. Web preview/commit steps, such as scheduling a live issue, expose equivalent callable steps and return the same review data and receipt through MCP. Background work returns a job ID that either interface can inspect. Public reader tools share the form's validation, rate limits and generic responses. Use an explicit confirmed POST for action links. Email-link landing GETs are safe to preview. A single-use confirmation proof and an unsubscribe proof have distinct purposes. Keep unsubscribe usable from previously delivered mail. Discard reader proofs from logs and telemetry.
    
    ## Acceptance
    
    - Sign in with one bootstrap identity, add a second operator from MCP, bind that operator on the web and revoke their delegated grant from either interface. Verify subsequent calls and refresh fail. Exercise the same sequence in reverse, including re-addition and a stale old grant. Two concurrent removals leave a bound operator.
    - A fresh remote client discovers the issuer from the 401, obtains a token, initializes, lists tools, prepares and commits a send to a synthetic audience and reads its receipt over HTTP. The read-only grant can inspect permitted records and receives 403 when it tries to send. Repeat for a wrong resource, expired grant, wrong OAuth redirect and mismatched PKCE verifier.
    - Submit a reader signup through each adapter. For matching inputs, both return the same pending outcome and require the same consent proof. An anonymous reader cannot enumerate subscribers, discover operator tools at the reader endpoint, or invoke an operator command by guessing its name.
    

    Open access.md as plain text

  • delivery.md Cloudflare deployment, SES feedback, reliable dispatch, archive handling, quotas, recovery and cost examples.
    # Running the newsletter on Cloudflare and Amazon SES
    
    One deployment serves one publication. The publisher owns the Cloudflare and AWS accounts and controls the sender domain. Newsman stores the audience and editions. Amazon SES v2 delivers confirmation mail, test mail and individual copies of each issue. A delivery receipt means the receiving mail server accepted the message. Inbox placement and reader engagement are separate measurements.
    
    ## What to deploy
    
    | Component | Responsibility |
    | --- | --- |
    | Cloudflare Worker | Serve the operator web app and HTTP MCP endpoint, handle the site's signup and reader actions, verify provider feedback, and run scheduled and queued work. All operator actions go through the shared authorization and command layer. |
    | D1 | Store reader status and consent history, suppressions, issue revisions, approved campaigns, immutable audience membership, delivery attempts, receipts, command keys and audit records. Put audience data in a dedicated private database. Use indexed opaque identifiers in links and jobs. |
    | Private R2 bucket | Store immutable email images, staged import files, completed exports and backup objects. Give files scoped, expiring access. Give a mailbox client access only to the individual image intended for email. |
    | Cron Trigger and Queues | Cron discovers due work and abandoned job leases. Queue messages carry opaque IDs. D1 owns the work state so expiration, redelivery and overlapping ticks are recoverable. |
    | SES and an SNS Standard topic | SES sends in a single configured region. A configuration set forwards event records to a signed HTTPS subscription on the Worker. A monitored publisher mailbox receives replies. |
    
    Deploy the Worker using Cloudflare bindings and the Cloudflare CLI. The site adapter can use a service binding while keeping its existing same-origin form contract. Configure the canonical HTTPS origin, publisher identity, From, Reply-To, postal address, display timezone, AWS region, expected SNS topic ARN and SES configuration set. Keep signing material, AWS credentials and OAuth secrets in Worker secrets. Sign SES v2 HTTPS requests with AWS Signature Version 4 for the configured service and region, using least-privilege credentials and the session token when present. Restrict the sender's AWS permissions to its verified identity, configuration set and sending needs. Use a separate administrative identity for AWS setup. Preview gets separate bindings, credentials, origins, queues and recipient limits. Its default sender writes to a local capture sink. SES mailbox simulator addresses or a fixed operator-owned seed inbox can exercise a real preview configuration. [Worker bindings](https://developers.cloudflare.com/workers/runtime-apis/bindings/) · [SES production access](https://docs.aws.amazon.com/ses/latest/dg/request-production-access.html)
    
    ## Rendering and planning
    
    Render from the existing site's issue source. At approval, persist the revision ID, a digest, subject, preheader, sender settings, HTML and plain text, link classifications, asset versions, UTC delivery time and archive release time. Use bound SQL parameters. Limit the combined serialized message snapshot to 512 KiB before writing it to a single D1 row. Reject an oversized revision with the measured size and limit during preview. Resolve personalization and unsubscribe links from the frozen template. A later edit creates a revision and requires fresh approval before it can replace a queued edition. [D1 limits](https://developers.cloudflare.com/d1/platform/limits/)
    
    When the publisher enables click tracking, use the first-party redirect as the canonical click source. Resolve opaque link IDs against frozen, approved HTTP(S) destinations. Exclude confirmation and unsubscribe links from rewriting. Classify editorial and sponsor clicks separately and label scanner uncertainty. Preserve historical provider metrics as a separate series. A provider click on an already tracked redirect contributes zero additional first-party clicks.
    
    Read an embargoed edition in email during the gap before its public release. Omit a “read online” link while its destination is private. Freeze the displayed email hero at approval. A dedicated Worker route may serve that one approved image from private R2 by an unguessable, issue-scoped read capability that works in ordinary email clients and can be shared by recipients. Serve an appropriate image media type, immutable bytes and no directory listing. Keep preview images private. Give visitors access to the canonical web issue, full-size archive assets and Atom entry together at the site's authorized public release.
    
    Record the committed audience cut, segment revision and selection timestamp for each campaign. Materialize recipient membership against that cut with a unique campaign and subscriber key. A large selection must support bounded paging using versioned membership or a materialized snapshot. A live mutable query cannot reproduce a prior audience. New confirmations after the cut wait for a later edition. Commit the selection and resumable outbox state before enqueueing IDs. Each dispatch checks current consent and suppression again.
    
    ## How a send survives interruption
    
    1. Enforce a unique committed plan and one live dispatch per edition, even across operators and command keys. A later source correction updates the archive independently. The shared web/MCP command validates the expected revision and idempotency key, records the approved send or schedule and returns its durable ID. A repeated key with the same arguments returns the original result. A conflicting payload fails before dispatch. A UTC cron tick claims due work using a conditional write. Bounded pages and unique recipient rows let the next tick continue after a crash.
    2. A queue consumer obtains a short D1 lease by conditional update. Before a network call, atomically verify that the campaign is enabled, the reader is still active and unsuppressed, and rate and volume capacity remain. Persist the attempt ID and `submitting` state. Use one recipient per `SendEmail`, a configuration set and opaque campaign, recipient-delivery and attempt tags. Disable automatic network/SDK retries for the submission. Correctness depends on the stored attempt even if two consumers handle the same queue item. Cancellation or opt-out blocks work that has yet to enter submission. A request already handed to SES may finish.
    3. A successful SES response records the provider message ID and `accepted`. Track delivery, rejection, hard bounce and complaint from authenticated feedback. Permanent bounces and complaints immediately suppress future messages to the affected address. Transient delivery failures remain visible for the issue. A later delivery event cannot clear a suppression. Count each recipient once per reported outcome and use a separately labeled denominator for each rate.
    4. A definite throttling rejection can be retried with backoff and jitter. A validation error ends the attempt and exposes a repairable cause. An expired lease before the submission fence may be reclaimed. A disconnect, timeout, server error, expired post-fence lease, or crash while persisting a success yields `unknown`. Do not automatically resend such an attempt. A signed SES event carrying its tags can reconcile it even if the initial reply was lost. Unresolved entries stay visible in both interfaces. Operators can record evidence of provider acceptance, permanently skip delivery, or authorize a new attempt after establishing that the original was never submitted. If the outcome remains uncertain, keep the hold or permanently skip. The same rule applies to web and MCP. [SES sending errors](https://docs.aws.amazon.com/ses/latest/dg/troubleshoot-error-messages.html) · [Cloudflare Queue delivery guarantees](https://developers.cloudflare.com/queues/reference/delivery-guarantees/)
    
    Apply the same boundary to confirmation and test mail. Deduplicate confirmation jobs by pending challenge and enforce a resend cooldown. Use a deployment-wide send-rate limiter and rolling 24-hour allowance below the SES account's current regional limits. Include confirmation and test traffic. Reserve before sending and charge unknown outcomes conservatively. Give due work a new dispatch opportunity when capacity returns. A local monthly ceiling, backlog age, throttling, unknown outcomes and feedback health are visible from the operator console and MCP. [SES quotas](https://docs.aws.amazon.com/ses/latest/dg/manage-sending-quotas.html)
    
    ## Provider setup and reader controls
    
    Verify the sending domain in the delivery region, enable Easy DKIM, publish the provided DNS records and set up DMARC alignment. For a custom MAIL FROM domain configure its MX and SPF as SES specifies. Obtain production access in that region before delivering to the general audience. Send a seed message and inspect its actual headers, aligned DKIM result, return path, monitored Reply-To and unsubscribe behavior. Enable SES account-level hard-bounce and complaint suppression as a second check. [SES DKIM](https://docs.aws.amazon.com/ses/latest/dg/send-email-authentication-dkim.html) · [Custom MAIL FROM](https://docs.aws.amazon.com/ses/latest/dg/mail-from.html) · [SES suppression](https://docs.aws.amazon.com/ses/latest/dg/sending-email-suppression-list.html)
    
    Add an HTTPS `List-Unsubscribe` URL and `List-Unsubscribe-Post: List-Unsubscribe=One-Click` to every newsletter. One valid aligned DKIM signature must cover both headers. Include a visible unsubscribe link in both rendered alternatives. An opaque, subscriber- and purpose-bound token authorizes exactly this reader's opt-out. Accept the RFC 8058 POST form, including its permitted encodings, without login, cookies or redirects. Persist the suppression before returning success. Repeats succeed. A GET opens a confirmation page with a deliberate POST action so scanner prefetches leave consent intact. Public signup and confirmation also respect suppression. Reserve resubscription for a fresh, explicit opt-in through the consent rules. [RFC 8058](https://datatracker.ietf.org/doc/html/rfc8058) · [SES one-click integration](https://aws.amazon.com/blogs/messaging-and-targeting/using-one-click-unsubscribe-with-amazon-ses/)
    
    Allow only the expected SES configuration set to publish to the expected SNS topic. Configure signature version 2 and standard signed SNS envelopes. Verify the topic ARN, canonical signed fields for the message type, signing certificate, chain and signature before any action. Restrict certificate lookup to documented HTTPS SNS hosts and paths in the configured AWS partition. Confirm the intended subscription through the AWS operation with the authenticated token and expected topic. Persist the SNS message ID and normalized event in one transaction before acknowledging. Return a retryable status for storage failure. Redelivery of an envelope, and duplicate semantic delivery or suppression events, must leave totals and state correct. Store provider event times independently of arrival order. Where complaint feedback identifies an address in this publication outside a known attempt, still apply the verified suppression. Unknown tags or events with insufficient identity become review items. Keep raw receipts, addresses and tokens out of logs. [SNS signature verification](https://docs.aws.amazon.com/sns/latest/dg/sns-verify-signature-of-message.html) · [SES event formats](https://docs.aws.amazon.com/ses/latest/dg/event-publishing-retrieving-sns-contents.html)
    
    ## Cost and recovery
    
    Illustrative US-dollar base estimates at published list rates on 2026-11-24, before credits. Each example assumes four issues a month, one recipient per send, and Cloudflare usage within applicable allowances.
    
    | Confirmed recipients | Issue deliveries | SES à-la-carte base | SES plus a stand-alone Workers Paid subscription |
    | ---: | ---: | ---: | ---: |
    | 1,000 | 4,000 | $0.40 | $5.40 |
    | 10,000 | 40,000 | $4.00 | $9.00 |
    
    SES base is $0.10 per 1,000 outbound emails. Add confirmations and tests, applicable data charges, SNS requests and HTTPS notifications, and any Cloudflare overages. Existing Workers Paid customers share the account's $5 monthly subscription and included capacity. Workers Free may cover a small publication. Check the actual send-day load against daily limits. A 10,000-reader issue using one successful small queue message per reader consumes about 30,000 queue operations alone. Workers Free currently includes 10,000 queue operations per day. Batching does not reduce that per-message meter. Show projected recipient count and base send cost at approval, then actual accepted attempts and measured usage. [SES pricing](https://aws.amazon.com/ses/pricing/) · [SNS pricing](https://aws.amazon.com/sns/pricing/) · [Workers pricing](https://developers.cloudflare.com/workers/platform/pricing/) · [Queues pricing](https://developers.cloudflare.com/queues/platform/pricing/) · [D1 pricing](https://developers.cloudflare.com/d1/platform/pricing/) · [R2 pricing](https://developers.cloudflare.com/r2/pricing/)
    
    Ship a deployment check for bindings, database migration version, sender status, event delivery and DNS. Start newly installed and restored instances with live dispatch paused. Keep recoverable database exports and a private backup of required objects, token keys and settings under the publisher's control. Test restoration in an isolated environment. D1 Time Travel covers the database only. Reconcile post-backup opt-outs, complaints, admissions, accepted or ambiguous attempts and queue generations before resuming. If a data-loss interval cannot be reconstructed, exclude the affected recipients or retire the affected edition. An operator should be able to explain who may still receive mail before turning dispatch on. [D1 Time Travel](https://developers.cloudflare.com/d1/reference/time-travel/)
    

    Open delivery.md as plain text

  • migration.md Suppression-first beehiiv cutover and rollback, reconciled against a synthetic fixture.
    # Moving one publication from beehiiv
    
    The publication owns its website, issue sources and Atom feed. Change the service behind its email form and the sender of its weekly issue. The migration succeeds when every eligible reader can receive the right edition once, prior opt-outs continue to work, and the publisher can explain the audience count before sending. Every newsman operation below is available through both the web console and the HTTP MCP server. Both interfaces use the same import jobs, receipts and release controls.
    
    ## Rehearse with the sender paused
    
    1. Record the export time in UTC and a checksum for each input. Take an all-status subscriber export, available opt-out, complaint and bounce records, and an inventory of sent and scheduled editions. Include prior provider IDs, signup and confirmation evidence, original campaign tags and deletion requests where available. Inspect actual export headers and missing fields in the dry run. Collect equivalent SES regional account suppressions for the new sending identity. Keep raw exports inside private storage with an expiry. [beehiiv exports](https://www.beehiiv.com/support/article/12258595483543-exporting-post-content-or-subscriber-data-from-beehiiv) · [SES suppression lists](https://docs.aws.amazon.com/ses/latest/dg/sending-email-suppression-list.html)
    2. Stage and validate all inputs before making anyone eligible. Resolve identities using provider IDs and the subscriber store's email comparison rule. Quarantine collisions for review. Apply unsubscribes, complaints, hard bounces and deletion exclusions first. Give a negative record precedence over an active row from another snapshot. Preserve an explicit confirmation time where available. A native active entry can qualify with evidence that the publication collected double opt-in for that entry. Mark that evidence as an observed status when its timestamp is unknown. Hold unverified imports and ambiguous statuses. Pending readers stay pending and can request a fresh confirmation.
    3. Produce a dry-run receipt with input totals, duplicates, conflicts, suppressed, pending, eligible, test-only and unresolved counts, plus the rejected row numbers and reasons. Each distinct identity receives one disposition. Calculate a private digest over the sorted eligible identity set as well as its count. Commit against the reviewed input checksums and mapping version. Replay the same import through the other interface and verify an identical audience, zero extra confirmation events and zero outgoing mail.
    
    Use this synthetic fixture in the build. The labels denote private test identities.
    
    | Identity | Input evidence | Expected result |
    | --- | --- | --- |
    | A | Native active, confirmed, original campaign present | Eligible with original campaign and date |
    | B | Older active row and later opt-out row | One suppressed identity |
    | C | Permanent bounce | Suppressed |
    | D | Complaint | Suppressed |
    | E | Pending opt-in | Pending |
    | F | Manual addition, consent evidence missing | Held for review |
    | G | Explicit test identity marked active | Test-only |
    
    Eight input rows yield seven identities, one duplicate, three suppressed, one pending, one held, one test-only and one eligible. Reverse the import order, repeat the commit and restore it into an isolated preview. The eligible set must equal **{A}** in all three runs. In a second run, mark A unsubscribed after planning and before dispatch. The local sender must observe zero deliveries.
    
    ## Verify the existing site and reports
    
    - Exercise the email-only form at `/subscribe/` through `POST /api/newsletter/subscribe`. An accepted submission redirects to `/subscribe/#check-inbox`. Verify one confirmation after a tagged submission, a repeat, a mail-scanner fetch and a deliberate reader confirmation. A reload of `/confirmed/` produces zero new confirmations. Check a link-expiry and resend case. Preserve the first valid source, medium, campaign and content values and the existing fallback for unknown attribution.
    - Compare the public inventory of issue URLs, Atom entry IDs and publication timestamps before and after the switch. A preview issue with an edition date today and archive release seven days later stays private during the interval, including its website hero. The delivered email has working links and any email-specific image loads. At archive release, the existing generator publishes the page and feed entry together. A correction retains the issue and Atom identifiers.
    - Export the columns consumed by the private acquisition report. Compare the same campaign, reporting timezone, observation window and confirmation denominator across the cutover. Carry forward the publication's four-eligible-issue engagement window. Baseline imports contribute zero new acquisitions. Track test identities explicitly and keep historical beehiiv click metrics labeled by source. Scanners can generate clicks. Label current first-party redirect measurements and historical provider measurements separately. Use aggregate reports for editorial or sponsor reporting and keep email addresses, tokens and private audience files outside public site builds and logs.
    - Rehearse signed SES delivery, bounce and complaint feedback, one-click unsubscribe, replies to a monitored mailbox and a repeat feedback delivery. Use test fixtures or the SES mailbox simulator and a controlled inbox. Verify preview activity contributes zero production recipients, sends or advertising conversions. [SES mailbox simulator](https://docs.aws.amazon.com/ses/latest/dg/send-an-email-from-console.html)
    
    ## Switch between editions
    
    1. Confirm that SES production access, the authenticated sender, feedback processing and rate limits work in the selected region. Disable outstanding beehiiv sends and automations. Register previously sent editions as historical so an import or worker restart cannot schedule them. Capture one last subscriber and suppression delta. Record a cutoff and a watermark for both systems.
    2. Switch the existing signup route to newsman, then reconcile changes that arrived on either side of the cutoff. Record which system owns new signups and which system owns the next edition. Enable dispatch only after reconciling the eligible identity set, clearing unexplained differences, and verifying a single active sender for that edition.
    3. Give previously issued beehiiv links a working path. While old unsubscribe and pending confirmation links are in circulation, ingest their verified status changes by webhook or by overlapping, deduplicated authenticated reads. If exports are the available source, reconcile a fresh snapshot before dispatch and record its age. A stale or failed reconciliation pauses affected sends. An authenticated legacy confirmation can advance its pending identity once, subject to subsequent opt-outs. Where old confirmation links expire, direct the reader to the first-party resend form. Keep the integration active for actionable legacy unsubscribe links. Retire it only when those links still reach the suppression ledger through a verified replacement path or the affected identities are excluded from future delivery.
    4. Send the next authorized edition once. Reconcile its frozen audience against excluded, queued, accepted, ambiguous and terminal recipient records. Record deliveries separately as feedback arrives. Review actual SES volume, Cloudflare usage and operator time after the first billing cycle.
    
    ## Rollback drill
    
    Pause dispatch and fence queued newsman jobs first. Keep public signup, confirmation, unsubscribe and SES feedback routes serving. Save the send ledger, the current state and a delta of all opt-outs, complaints, bounces, signups and confirmations since the cutoff. Before restoring beehiiv as sender, apply suppressions first and bring consent changes across. Preserve pending status and honor unexpired links at the system that issued them. Test a newsman unsubscribe from an already delivered issue against the restored sender.
    
    Roll back signup and sending independently. If delivery was partly accepted or its outcome is unknown, retire that edition from the second sender until its affected recipients can be reconciled individually. A failed reconciliation leaves dispatch paused and the archive available. Finish the drill when the restored eligible set matches the reviewed ledger, the opted-out test reader receives zero mail and the interrupted edition has zero duplicate sends.
    

    Open migration.md as plain text

  • acceptance.md Build sequence and executable acceptance scenarios for a clean installation and the existing AudioTech site.
    # Build and acceptance
    
    Build a deployable newsman application in its own directory. The local test suite runs against isolated Cloudflare-compatible bindings, a mock identity provider, controlled time, signed feedback fixtures and a recording mail transport. A publisher can install it without access to the AudioTech repository. AudioTech supplies the reference integration contract. Checkout credentials, subscribers and private articles are never build inputs to this public spec.
    
    ## 1. Start a single publication (R1, R8, R9)
    
    Ship a pinned TypeScript project, lockfile, Cloudflare CLI configuration, numbered D1 migrations and local sample configuration. Bind a Worker with static admin assets, subscriber D1, private R2, OAuth KV, Cron, a send queue and a dead-letter queue. Bind the site’s public form by custom domain route or service binding. Keep deployment names, AWS region, origins, allowed operator addresses and sending identities configurable. A clean install uses the local mail sink, a closed operator list until bootstrapped, and paused production dispatch.
    
    Resolve pull settings for publication name, HTTPS public origin, IANA time zone, archive lag in whole days, and SES region. Validate them on bootstrap. Store editable publication settings with a version; changing the existing public origin requires identity and archive revalidation. Set the initial operator allowlist in deployment configuration using verified emails. If the list is empty, show the infrastructure owner how to add their first entry through the documented bootstrap. Cloudflare Access, AWS identity and OAuth client registration remain infrastructure setup. Document every binding, its purpose, creation or rotation procedure, health check and the distinction between preview and live. Keep secrets in the publisher’s secret store. Synthetic development uses fixture keys.
    
    **Check** a new publisher installs on their own accounts without a third-party newsman service. The local admin can complete setup from the console and read the same readiness results from a remote MCP client. A missing AWS sender identity leaves draft and preview available and live dispatch paused.
    
    ## 2. Establish the operation registry before building screens (R1, R8)
    
    Load [operations.json](operations.json), resolve the per-operation schemas, and generate types, two transport adapters and the initial web view inventory. Implement the identity contract in [access.md](access.md). Render lightweight console views for Overview, Issues, Campaigns, Audience, Segments, Templates, Reports, Transfers, Migration, Jobs, Operations, Audit, Operators, Connections and Settings. Include Archive in an issue’s detail view. Display clear empty, loading, conflict and unavailable states. Reuse the publication’s existing public form and confirmation pages.
    
    **Check** two verified identities try the same actions. Only the allowlisted operator succeeds. An unattended delegated client with full scopes can initialize, upload, read, write, send, export and manage its grant without screen automation. Removing its operator invalidates a previously authorized client. Run every test in [parity.md](parity.md), including the deliberately broken web-only control.
    
    ## 3. Build consent and segmentation (R2, R3, R7)
    
    Make the D1 schema enforce unique normalized address lookup and a stable opaque subscriber ID. Keep an append-only consent history, suppression rules, challenge digest and expiry, confirmed timestamp and immutable first-touch attribution. Key tombstones with a secret distinct from token signing. Store timestamps in UTC. A reader’s address comparison rule must be identical during signup, opt-out and import. Trim whitespace and normalize the domain; document the local-part policy and quarantine ambiguous import collisions. Never strip plus tags. Keep subscriber identities, evidence files and operator exports private. Index segment filters before offering them to the operator.
    
    For the existing site accept same-origin form-encoded `POST /api/newsletter/subscribe` with `email` and four optional UTM fields. Keep only values matching `[A-Za-z0-9_.-]{1,128}`. On acceptance respond `303 Location: /subscribe/#check-inbox`. Present generic expiry/resend paths and redirect a valid confirmation to `/confirmed/`. Configure signup abuse limits across web and reader MCP. Permanent suppressions apply to both. A normal browser session can reach the site’s archive and feed during mail downtime.
    
    **Check** submit the same reader twice across transports, open the confirmation URL with a scanner GET, then consume it once with an explicit POST. Only that last action confirms. Replay, direct confirmed-page visits and later import produce zero additional confirmed events. One-click opt-out blocks a scheduled recipient even if their audience membership was already frozen.
    
    ## 4. Import, edit and schedule a weekly edition (R4, R5, R6)
    
    Load the versioned issue bundle and render escaped, sanitized HTML and plain text. Pin subject, preheader, sender, reply address, links and the immutable hero at approval. Make test delivery and web/mobile previews available before scheduling. Keep the existing archive URL, Atom ID, edition date, archive release time and correction time separate in the adapter. Preserve the host site's preview and publication flags. Check the public feed content type and reader links. Schedule in local publication time with an explicit zone offset or validated UTC instant; ambiguous daylight-saving input requires an explicit offset.
    
    **Check** a sample edition with one editorial destination, one sponsor link and a hero renders both parts, passes accessible alt text checks, sends a labeled proof, and schedules from either channel. Reusing a stale approved plan after a content edit fails. Sending leaves the protected edition out of the host site's public archive until release. After the host deploys, verify the original canonical and Atom identity. Reimporting a source correction increments the edition revision without generating another send.
    
    ## 5. Deliver once where the provider outcome is known (R5, R7, R9)
    
    Store one plan/campaign receipt per accepted command, one frozen membership per campaign and reader, and a separate identity for each submission attempt. Index due work and maintain a suppression lookup at the final send boundary. Test against a clock advanced through rate limits, a feedback stream with delayed and reordered events, and a consumer killed both before and after it submits to SES.
    
    | Synthetic case | Required result |
    | --- | --- |
    | Two concurrent commits of the same plan; queue redelivers one item three times | One campaign and one accepted submission to the local mail sink for each eligible reader. |
    | Worker loses its SES response after provider acceptance | Attempt becomes unknown. A matching signed feedback event correlates it without another send. Without evidence, it remains unresolved or is permanently skipped. |
    | Complaint arrives after scheduling; later an older delivery event arrives | The reader stays suppressed across all subsequent campaigns. The previous delivery remains correctly attributed. |
    | Consent revoked after the send worker has handed the request to SES | Record that in-flight boundary in the audit. Block all following submissions for that reader. |
    | SNS callbacks repeat, arrive out of order, carry a different topic or have a bad signature | Count a valid event once. An untrusted callback leaves no consent or delivery mutation. |
    | CSV upload or result download is interrupted; same bytes are resumed from MCP | Per-chunk and final digest checks pass. The resumed import or export has one receipt. |
    
    **Check** the operator can pause and inspect a partially processed send, resolve an attempt using evidence, and resume eligible work through either interface. Check actual SES regional quota and a controlled proof before production. Use [delivery.md](delivery.md) for the failure boundaries and recovery plan.
    
    ## 6. Verify cost, migration and a working handoff (R3, R6, R7, R9)
    
    Exercise [migration.md](migration.md) using its eight input rows. Test the rollback as well as the forward switch. For a 10,000-recipient four-issue model, the baseline issue count is 40,000 SES messages before tests, confirmations, retries and new readers. The dashboard compares forecast and actual billable activity and surfaces monthly headroom. Compare the new bill against the publisher’s actual prior plan and hosting costs. The build must never require a beehiiv subscription for ordinary operation after legacy link obligations are resolved.
    
    **Check** a fresh self-hoster can run the documented installation, authorize a remote client, import a newsletter, rehearse a send, verify one-click unsubscribe, inspect an export and restore a backup in isolation. For the AudioTech adapter compare the signup response and archive/Atom fixtures to [the recorded evidence](evidence.md). Historical and QA events stay out of new-acquisition counts.
    
    ## Definition of done for an implementation
    
    The built project supplies `npm ci`, `npm test`, `npm run test:parity`, `npm run test:e2e` and `npm run build`. A clean checkout passes them with a local capture transport. A Cloudflare dry run through `npx cf deploy --dry-run` validates its bindings. Capture an MCP discovery transcript, assertion totals for every registered action, cross-channel duplicate-send results, a private migration reconciliation receipt and a restore drill. Use synthetic examples in shared reports. Production deployment, domain verification and real recipient sends are operator actions in the resulting installation.
    

    Open acceptance.md as plain text

  • evidence.md Public signup and archive evidence, REA artifacts identified by digest, and analysis limitations.
    # Evidence behind the site integration
    
    On 2026-11-24, two publicly served JavaScript files were downloaded and parsed locally with REA 6.10.1 using `analyze-javascript-application`. Each analysis covered one file and reported zero parse failures. The evidence references below identify the complete static analysis records. The file digests identify the exact bytes inspected, since both URLs may change. [REA on GitHub](https://github.com/morluto/rea)
    
    | Surface | Observation | What newsman should preserve |
    | --- | --- | --- |
    | beehiiv public form loader | REA identified references to a form attribute, an iframe, and campaign parameters. Inspection of those source locations showed where the script selected a form and put attribution on the iframe URL. [Public form loader](https://subscribe-forms.beehiiv.com/v3/loader.js) | A publisher can place a signup on its own site and retain the campaign that brought a reader there. A native HTML form serves this purpose for AudioTech. |
    | AudioTech public signup | The page serves an email field that posts to `/api/newsletter/subscribe`. REA located the handler for the browser’s form-data event. Its source reads four campaign keys, checks their values and attaches the accepted values to the submission. [Signup page](https://audiotech.news/subscribe/) · [Signup script](https://audiotech.news/assets/signup.js) | Accept an ordinary form POST from the existing site. Support `utm_source`, `utm_medium`, `utm_campaign` and `utm_content`. Signup with JavaScript disabled still requests confirmation. |
    | Reader confirmation | The public signup page tells readers to check their inbox. The confirmation page has a link to the latest public issue. A read of the existing site integration verified that an accepted submission redirects with HTTP 303 to `/subscribe/#check-inbox`. [Signup](https://audiotech.news/subscribe/) · [Confirmation page](https://audiotech.news/confirmed/) | Treat submission as pending. A verified opt-in records confirmation exactly once. An ordinary visit to the existing confirmation page leaves subscriber state alone. |
    | Edition and archive | The public Atom feed uses the issue URL for each entry’s ID. Its issue dates and publication timestamps reflect the site's email-first release cadence. The existing publication workflow gives email readers the issue one week before its web release. [Issue archive](https://audiotech.news/issues/) · [Atom feed](https://audiotech.news/feed.atom) | Keep the site's stable issue identifiers. Record sending and archive release separately. Previewing or sending an email must respect the chosen archive release date. |
    
    | Analyzed file | File SHA-256 | REA evidence ID |
    | --- | --- | --- |
    | beehiiv public form loader | `30e9e5e230bc70bd202af25db3d3c12ca84ee4d6f65190a6138de7d096c366d5` | `ev_7db54375a4f3d371e3ec0c129142a5387ec9eec8f7e9a31e7c3a9a26bc8fe4d7` |
    | AudioTech public signup script | `394c36b0d1db0e24cc92bc81bdaacff6ef705d15e25befb4d7b54cd8d533e9f7` | `ev_27ee1a44f63fb4b76632696fa3a03f0b34e657f2028778462583770c12d8ec86` |
    
    The observed behavior covers published scripts, pages, feed output and the host site's integration contract. Browser execution, inbox delivery and beehiiv's internal implementation fall outside that evidence. The allowlist, SES event handling and web-to-MCP parity are original requirements for newsman. Use the acceptance scenarios to verify them on the implementation.
    

    Open evidence.md as plain text

Is it for me?

Platforms
web, backend
Tools
TypeScript, Cloudflare Workers, Cloudflare D1, Cloudflare R2, Cloudflare KV, Cloudflare Queues, Cloudflare Access, Amazon SES v2, Amazon SNS, Model Context Protocol

What does it need?

Agent permissions
shell, network
Commands it runs
npm ci npm test npm run test:parity npm run test:e2e npm run build npx cf deploy --dry-run
Secrets it reads
AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN READER_TOKEN_KEY SUPPRESSION_HMAC_KEY OAUTH_ENCRYPTION_KEY CSRF_SECRET

What changed?

  • 0.1.024 Nov 2026First specification for a self-hosted publication, Amazon SES delivery, allowlisted access and complete web-to-HTTP-MCP parity.

For agents: start.md says how to build this spec, spec.json holds its manifest and the address of every file, and bundle.tar.gz holds its files.