mirror of
https://github.com/juherr/kill-the-news.git
synced 2026-06-21 06:13:48 +00:00
Compare commits
116 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d778849e02 | |||
| 5083f7e151 | |||
| ffe96586c7 | |||
| 3242f0e3f1 | |||
| 1332362005 | |||
| cbf6bb7e7e | |||
| 0f18d4c123 | |||
| e8078b2673 | |||
| ea7332b752 | |||
| 8cd8c940fa | |||
| fe5728de59 | |||
| 35262d5d0b | |||
| a18d9f165f | |||
| 8a0dbf25b0 | |||
| 6236274ce8 | |||
| 5362d478e3 | |||
| ee0e7eef5d | |||
| dc2ccfdd1c | |||
| 86d18eb390 | |||
| 3c48181c05 | |||
| df5546fedd | |||
| 021aeabd05 | |||
| 69ed07db51 | |||
| 6dad6741ed | |||
| d2f3e1ca27 | |||
| 664d0c02ba | |||
| 757dd3a53f | |||
| 16029460bc | |||
| 82a4bd8341 | |||
| e86beeeb8a | |||
| 7086526670 | |||
| 70552e5fa6 | |||
| 4e3d378850 | |||
| 421430632e | |||
| 5f05068449 | |||
| fc86b5f7d1 | |||
| 0929d4f0b7 | |||
| 4d47ca623b | |||
| 7019800769 | |||
| f44c6c1eda | |||
| 1525b36cab | |||
| c4d591b962 | |||
| 36d58ade48 | |||
| 79bb4902b9 | |||
| d561b6b81f | |||
| e4e3d62f5a | |||
| f2e0353438 | |||
| 6bf11493ab | |||
| 5b54659b4d | |||
| 0488b9d066 | |||
| 2a3aeb8a18 | |||
| b3a979fd03 | |||
| 1a4a479190 | |||
| f7f10779bc | |||
| 0abd5f306c | |||
| 334713fbd9 | |||
| 97ce9a62b4 | |||
| 81e46c9026 | |||
| 1583e95875 | |||
| 2c450817df | |||
| 6cb036fe2c | |||
| b002f8ad43 | |||
| 5137637181 | |||
| be45e70571 | |||
| 06c436c36a | |||
| d68a24867d | |||
| ad196f1761 | |||
| b3d42f6c50 | |||
| 46af982c40 | |||
| f823a5f222 | |||
| 23dd0a0c96 | |||
| e324571122 | |||
| 7bf0f71f86 | |||
| ab1c15e69a | |||
| 05388b45c8 | |||
| c45f6677fe | |||
| a31ff42f59 | |||
| b347f2f625 | |||
| 49f69ff19e | |||
| c65aabe7f4 | |||
| 8f036cf223 | |||
| 6b51173722 | |||
| 2b3f00f7e3 | |||
| a0eaebe749 | |||
| c2a0a68058 | |||
| daa93d8093 | |||
| 45d2a14a12 | |||
| 7f5b913576 | |||
| db31e33a8b | |||
| 8ffa4ad5e7 | |||
| 7f4afa3ec8 | |||
| 3368b0d1d2 | |||
| 5fc91a0be4 | |||
| debbfc623e | |||
| 6cd2d425a2 | |||
| 9141cf89bd | |||
| ddde0e26a2 | |||
| 20c9bca34a | |||
| 2de09b2a5d | |||
| f150d40c45 | |||
| 7226e718f7 | |||
| f4e751e40b | |||
| 766f2717a7 | |||
| d322bc1e92 | |||
| 3ad0188bc0 | |||
| eb12f21894 | |||
| d299c8891d | |||
| a67baa71f4 | |||
| b985e2c643 | |||
| 81d05e5774 | |||
| 4db9fc1b8a | |||
| 6bfaa4dec7 | |||
| fd6a1a945f | |||
| d1959acad1 | |||
| b534ce5bf8 | |||
| f4d5edda0e |
@@ -0,0 +1,30 @@
|
|||||||
|
{
|
||||||
|
"version": "0.0.1",
|
||||||
|
"configurations": [
|
||||||
|
{
|
||||||
|
"name": "docs",
|
||||||
|
"runtimeExecutable": "npx",
|
||||||
|
"runtimeArgs": ["serve", "docs", "-p", "4321", "--no-clipboard"],
|
||||||
|
"port": 4321
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "dev",
|
||||||
|
"runtimeExecutable": "npm",
|
||||||
|
"runtimeArgs": ["run", "dev"],
|
||||||
|
"port": 8787
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "dev-build",
|
||||||
|
"runtimeExecutable": "npx",
|
||||||
|
"runtimeArgs": [
|
||||||
|
"wrangler",
|
||||||
|
"dev",
|
||||||
|
"--config",
|
||||||
|
"wrangler.build.toml",
|
||||||
|
"--port",
|
||||||
|
"8788"
|
||||||
|
],
|
||||||
|
"port": 8788
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -21,6 +21,42 @@ jobs:
|
|||||||
|
|
||||||
- run: npm ci
|
- run: npm ci
|
||||||
|
|
||||||
|
# The tagged commit is the release: `npm run release` commits the bare
|
||||||
|
# X.Y.Z to it (main otherwise carries a `-develop` suffix). Verify the tag
|
||||||
|
# matches that committed version exactly — this catches tagging the wrong
|
||||||
|
# commit (e.g. a `-develop` one) without rewriting anything.
|
||||||
|
- name: Verify package.json matches the tag
|
||||||
|
env:
|
||||||
|
TAG_NAME: ${{ github.ref_name }}
|
||||||
|
run: |
|
||||||
|
VERSION="${TAG_NAME#v}"
|
||||||
|
PKG="$(node -p 'require("./package.json").version')"
|
||||||
|
if [ "$VERSION" != "$PKG" ]; then
|
||||||
|
echo "Tag $TAG_NAME does not match package.json ($PKG)." >&2
|
||||||
|
echo "The tagged commit must carry the bare release version ($VERSION)." >&2
|
||||||
|
echo "Cut releases with: npm run release $VERSION" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Release notes come from the CHANGELOG section for this version, which is
|
||||||
|
# written incrementally and reviewed in PRs — never hand-typed at release.
|
||||||
|
- name: Extract release notes from CHANGELOG
|
||||||
|
env:
|
||||||
|
TAG_NAME: ${{ github.ref_name }}
|
||||||
|
run: |
|
||||||
|
VERSION="${TAG_NAME#v}"
|
||||||
|
awk -v ver="$VERSION" '
|
||||||
|
$0 ~ "^## \\[" ver "\\]" {grab=1; next}
|
||||||
|
/^## \[/ && grab {exit}
|
||||||
|
grab { if (!started && $0 ~ /^[[:space:]]*$/) next; started=1; print }
|
||||||
|
' CHANGELOG.md > release-notes.md
|
||||||
|
if [ ! -s release-notes.md ]; then
|
||||||
|
echo "No CHANGELOG section found for $VERSION." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "Release notes for $VERSION:"
|
||||||
|
cat release-notes.md
|
||||||
|
|
||||||
- run: npm run build
|
- run: npm run build
|
||||||
|
|
||||||
- name: Locate bundled output
|
- name: Locate bundled output
|
||||||
@@ -41,5 +77,5 @@ jobs:
|
|||||||
TAG_NAME: ${{ github.ref_name }}
|
TAG_NAME: ${{ github.ref_name }}
|
||||||
BUNDLE_PATH: ${{ steps.bundle.outputs.path }}
|
BUNDLE_PATH: ${{ steps.bundle.outputs.path }}
|
||||||
run: |
|
run: |
|
||||||
gh release create "$TAG_NAME" --generate-notes --verify-tag || true
|
gh release create "$TAG_NAME" --notes-file release-notes.md --verify-tag || true
|
||||||
gh release upload "$TAG_NAME" "$BUNDLE_PATH" --clobber
|
gh release upload "$TAG_NAME" "$BUNDLE_PATH" --clobber
|
||||||
|
|||||||
+130
@@ -0,0 +1,130 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
All notable changes to this project are documented in this file.
|
||||||
|
|
||||||
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||||
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||||
|
|
||||||
|
Keep the `## [Unreleased]` section up to date **as part of every change** (the
|
||||||
|
same rule as the rest of the docs). At release time `npm run release X.Y.Z`
|
||||||
|
promotes this section to `## [X.Y.Z]` and the Release workflow publishes it
|
||||||
|
verbatim as the GitHub Release notes — so what you write here is what ships.
|
||||||
|
|
||||||
|
## [Unreleased]
|
||||||
|
|
||||||
|
## [0.3.1] - 2026-05-25
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Feed self link (RSS/Atom/JSON) is derived from the configured domain instead
|
||||||
|
of the request host — it no longer leaks the `workers.dev` host when a feed is
|
||||||
|
reached directly, and now matches the alternate link.
|
||||||
|
|
||||||
|
## [0.3.0] - 2026-05-25
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **Native feed detection** — incoming newsletters are inspected for a
|
||||||
|
self-advertised Atom/RSS/JSON feed (`rel=alternate` links in the email HTML);
|
||||||
|
discovered feeds are stored per sender on the Feed aggregate and surfaced as
|
||||||
|
chips on the feed detail page, a dashboard pill, and (read-only) on the REST
|
||||||
|
`Feed` schema, with a dismissable notice.
|
||||||
|
- **Subscription confirmation surfacing** — confirmation emails ("click to
|
||||||
|
confirm your subscription") are detected at ingestion and flagged on the feed;
|
||||||
|
the admin UI surfaces the confirmation link, a badge, a dashboard pill, and an
|
||||||
|
inline banner (all dismissable), tightened against false positives via a
|
||||||
|
weak-signal heuristic.
|
||||||
|
- **JSON Feed 1.1** output (`/json/:feedId`).
|
||||||
|
- **OPML export** of all feeds (`/admin/opml`).
|
||||||
|
- **Conditional GET** (ETag / Last-Modified / 304) on the feed routes.
|
||||||
|
- Per-feed **Subscribe chips** for RSS/Atom/JSON with copy / open / validate
|
||||||
|
actions, reused across dashboard and feed detail page.
|
||||||
|
- Email detail page links to its public entry page; land on the feed's emails
|
||||||
|
page right after creation.
|
||||||
|
- Optional **per-feed "sender in title"** toggle.
|
||||||
|
- Running **version** shown in the admin/status footer, `/health`, and
|
||||||
|
`/api/v1/stats`.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- **Read/write identity decoupling (privacy)** — the public read id (`FeedId`,
|
||||||
|
used in `/rss/:feedId`) is fully decoupled from the inbound email address
|
||||||
|
(`MailboxId`, `noun.noun.NN`); a feed's read URL never reveals its inbound
|
||||||
|
alias and vice-versa (reading `/rss/<noun.noun.NN>` 404s).
|
||||||
|
- Sender display name, site URL and parsing now owned by the `EmailAddress`
|
||||||
|
value object (DDD cleanup).
|
||||||
|
- Release version is derived from the git tag; CI guards against tagging the
|
||||||
|
wrong commit.
|
||||||
|
|
||||||
|
## [0.2.1] - 2026-05-24
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Optional `FALLBACK_FORWARD_ADDRESS`: forward non-feed mail to a verified
|
||||||
|
address so a domain catch-all can point at kill-the-news without swallowing
|
||||||
|
personal mail (forwarded mail is counted in the stats dashboard).
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Feed, entry, and attachment responses send `X-Robots-Tag: noindex`; a new
|
||||||
|
`/robots.txt` disallows `/rss`, `/atom`, `/entries`, `/files`, and `/admin` —
|
||||||
|
private feeds and emails stay out of search engines.
|
||||||
|
- Relative links/images in email bodies are absolutized against the sender's
|
||||||
|
site; lazy-loaded images are promoted so they don't render blank.
|
||||||
|
- Feed `<title>` is plain text (HTML stripped, entities decoded).
|
||||||
|
- Sender-site derivation moved onto the `EmailAddress` value object
|
||||||
|
(`siteBaseUrl`).
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- XML-illegal control characters are stripped from generated feeds (valid astral
|
||||||
|
characters such as emoji preserved).
|
||||||
|
|
||||||
|
## [0.2.0] - 2026-05-24
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Versioned REST API (`/api/v1/feeds*`) with an OpenAPI 3.1 spec
|
||||||
|
(`/api/openapi.json`) and rendered reference docs via Scalar (`/api/docs`).
|
||||||
|
- `/api/v1/stats` as the canonical public stats endpoint (JSON + CORS).
|
||||||
|
- Optional R2 attachment storage with a config toggle, storage metrics, download
|
||||||
|
links on the email/admin views, and inline `cid:` image rendering.
|
||||||
|
- Project favicon (`/favicon.svg`, `/favicon.ico`) and per-feed favicon derived
|
||||||
|
from the last sender's domain (`/favicon/:feedId`).
|
||||||
|
- RFC 8058 one-click unsubscribe dispatched when a feed is deleted.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Large internal refactor toward a clean domain-driven architecture; redesigned
|
||||||
|
landing/status page.
|
||||||
|
|
||||||
|
### Removed
|
||||||
|
|
||||||
|
- The deprecated `/api/stats` endpoint (use `/api/v1/stats`).
|
||||||
|
|
||||||
|
## [0.1.0] - 2026-05-22
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **Atom feed format** (`/atom/:feedId`) alongside RSS 2.0.
|
||||||
|
- **WebSub push notifications** advertised via `Link` header for real-time
|
||||||
|
delivery instead of polling.
|
||||||
|
- **HTML email processing** — bodies sanitized via `linkedom` + `escape-html`
|
||||||
|
(XSS prevention, MSO style stripping, plain-text fallback).
|
||||||
|
- **Email attachments as RSS enclosures**, stored in R2 and served at
|
||||||
|
`/files/:attachmentId/:filename`.
|
||||||
|
- **Sender blocklist** with 4-level priority matching and a quick-add dropdown.
|
||||||
|
- **`EMAIL_DOMAIN`** env var to separate web domain and email domain.
|
||||||
|
- **Authelia / reverse-proxy auth** via trusted headers (`Remote-User`,
|
||||||
|
`X-Forwarded-User`).
|
||||||
|
- Demo environment auto-deployed to `demo.kill-the.news` with a nightly KV
|
||||||
|
reset.
|
||||||
|
- Admin UI redesign (Inter font, orange theme), client scripts compiled via
|
||||||
|
esbuild, templates on `hono/jsx`.
|
||||||
|
|
||||||
|
[Unreleased]: https://github.com/juherr/kill-the-news/compare/v0.3.1...HEAD
|
||||||
|
[0.3.1]: https://github.com/juherr/kill-the-news/compare/v0.3.0...v0.3.1
|
||||||
|
[0.3.0]: https://github.com/juherr/kill-the-news/compare/v0.2.1...v0.3.0
|
||||||
|
[0.2.1]: https://github.com/juherr/kill-the-news/compare/v0.2.0...v0.2.1
|
||||||
|
[0.2.0]: https://github.com/juherr/kill-the-news/compare/v0.1.0...v0.2.0
|
||||||
|
[0.1.0]: https://github.com/juherr/kill-the-news/releases/tag/v0.1.0
|
||||||
@@ -26,19 +26,36 @@ npx vitest run src/routes/admin.test.ts
|
|||||||
|
|
||||||
kill-the-news is a Cloudflare Worker that ingests email newsletters and exposes them as private RSS/Atom feeds. Self-hosted, free-tier-friendly (Cloudflare + ForwardEmail).
|
kill-the-news is a Cloudflare Worker that ingests email newsletters and exposes them as private RSS/Atom feeds. Self-hosted, free-tier-friendly (Cloudflare + ForwardEmail).
|
||||||
|
|
||||||
|
## Development approach
|
||||||
|
|
||||||
|
Work **test-first (TDD)** and **domain-driven (DDD)** in this repo — both are first-class, not optional.
|
||||||
|
|
||||||
|
**TDD.** Write or extend a test before/with the change, then make it pass. Mirror the existing test layout (`*.test.ts` next to the source, `createMockEnv()` from `src/test/setup.ts`, MSW for outbound HTTP). End every change green: `npx tsc --noEmit`, `npm test`, and `npm run build` (dry-run deploy) must all pass before declaring done.
|
||||||
|
|
||||||
|
**DDD.** Before adding logic, check whether the domain already models the concept — reach for the value objects in `src/domain/value-objects/` (`EmailAddress`, `Domain`, `FeedId`, `MailboxId`, `Lifetime`, `SenderPolicy`) and the `Feed` aggregate rather than re-deriving things ad hoc. New behavior belongs on the type that owns the data (e.g. "sender site URL" lives on `EmailAddress`, not in a helper). Respect the layering and aggregate rules below — imports point inward (routes → application → domain; infrastructure implements ports), and never reach across a layer for convenience (e.g. importing a favicon/infra helper just to parse a domain). When the same derivation appears twice, that's the signal to push it onto a domain type.
|
||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
|
|
||||||
Single Cloudflare Worker built with Hono. Routes:
|
Single Cloudflare Worker built with Hono. Routes:
|
||||||
|
|
||||||
| Method | Path | Purpose |
|
| Method | Path | Purpose |
|
||||||
| ------------------------------------ | ---------------------------------------------------------------------- | ------- |
|
| ------------------------------------ | ---------------------------------------------------------------------- | ------- |
|
||||||
|
| `GET /` | Public status page (monitoring counters + link to admin) |
|
||||||
| `POST /api/inbound` | Webhook from ForwardEmail; IP-allowlisted to their MX sources |
|
| `POST /api/inbound` | Webhook from ForwardEmail; IP-allowlisted to their MX sources |
|
||||||
| `GET /rss/:feedId` | Public RSS 2.0 feed |
|
| `/api/v1/feeds*` | Versioned REST API (Bearer/proxy auth) — feeds + emails CRUD |
|
||||||
| `GET /atom/:feedId` | Public Atom feed (with WebSub hub header) |
|
| `GET /api/v1/stats` | Public monitoring counters (JSON, CORS); canonical stats endpoint |
|
||||||
|
| `GET /api/openapi.json` | OpenAPI 3.1 spec (public) |
|
||||||
|
| `GET /api/docs` | Rendered API reference (Scalar, public) |
|
||||||
|
| `GET /rss/:feedId` | Public RSS 2.0 feed (conditional GET: ETag/Last-Modified/304) |
|
||||||
|
| `GET /atom/:feedId` | Public Atom feed (WebSub hub header; conditional GET ETag/304) |
|
||||||
|
| `GET /json/:feedId` | Public JSON Feed |
|
||||||
| `GET /entries/:feedId/:entryId` | Individual email HTML view |
|
| `GET /entries/:feedId/:entryId` | Individual email HTML view |
|
||||||
| `GET /files/:attachmentId/:filename` | R2 attachment serving |
|
| `GET /files/:attachmentId/:filename` | R2 attachment serving |
|
||||||
| `GET /admin` | Password-protected admin UI |
|
| `GET /admin` | Password-protected admin UI |
|
||||||
|
| `GET /admin/opml` | OPML export of all feeds (admin-protected) |
|
||||||
| `/hub` | WebSub hub (subscribe/publish) |
|
| `/hub` | WebSub hub (subscribe/publish) |
|
||||||
|
| `GET /favicon.svg`, `/favicon.ico` | Project favicon (envelope logo); fallback for per-feed favicons |
|
||||||
|
| `GET /favicon/:feedId` | Per-feed favicon from the last sender's domain (falls back to project) |
|
||||||
| `GET /health` | Health check |
|
| `GET /health` | Health check |
|
||||||
| `email` | Cloudflare Email routing handler (alternative to ForwardEmail webhook) |
|
| `email` | Cloudflare Email routing handler (alternative to ForwardEmail webhook) |
|
||||||
|
|
||||||
@@ -49,31 +66,62 @@ src/
|
|||||||
index.ts # App entrypoint: CORS, IP middleware, route mounting, email handler export
|
index.ts # App entrypoint: CORS, IP middleware, route mounting, email handler export
|
||||||
config/constants.ts # Shared constants (TTLs, limits)
|
config/constants.ts # Shared constants (TTLs, limits)
|
||||||
types/index.ts # Env, FeedConfig, EmailData, WebSubSubscription, etc.
|
types/index.ts # Env, FeedConfig, EmailData, WebSubSubscription, etc.
|
||||||
|
domain/ # Framework-agnostic core (no Hono/infra imports leak out)
|
||||||
|
feed.aggregate.ts # Feed aggregate: consistency boundary; holds domain FeedState (camelCase), exposes intention-revealing reads, never raw state/metadata
|
||||||
|
feed-state.ts # FeedState: the aggregate's config in domain (camelCase) vocabulary — NOT the snake_case persistence DTO
|
||||||
|
feed.ts # The expiry predicate (`isExpired`) — the one invariant shared with the read-model routes
|
||||||
|
feed-keys.ts # The KV key schema (pure string builders), shared by every repository
|
||||||
|
clock.ts # Clock port (systemClock) — injected into the aggregate; no ambient Date.now()
|
||||||
|
events.ts # FeedEvent union (FeedCreated, EmailIngested) — each carries its feedId
|
||||||
|
email-parser.ts # Email parsing (addresses, headers, encoded words)
|
||||||
|
format.ts # Pure formatting helpers (formatBytes)
|
||||||
|
native-feed.ts # Detect a newsletter's self-advertised Atom/RSS/JSON feed (pure)
|
||||||
|
value-objects/ # FeedId (opaque read id), MailboxId (inbound noun.noun.NN), EmailAddress, Domain, SenderPolicy, Lifetime (immutable, self-validating)
|
||||||
|
application/ # Use-cases / orchestration (wires domain + infrastructure)
|
||||||
|
feed-service.ts # createFeedRecord / editFeedDetails / editFeed / deleteFeedRecord (admin UI + REST API)
|
||||||
|
feed-cleanup.ts # Feed/email storage cleanup: purgeFeedKeysStep, collectUnsubscribeUrls, attachment+key deletion
|
||||||
|
feed-events.ts # Dispatcher: maps aggregate FeedEvents to side effects (counters, WebSub, favicon)
|
||||||
|
email-processor.ts # Core ingestion: load aggregate → accepts? → feed.ingest → persist
|
||||||
|
feed-fetcher.ts # Read model for RSS/Atom rendering (config + email bodies; bypasses the aggregate)
|
||||||
|
stats.ts # Monitoring counters increment policy + storage scans
|
||||||
|
infrastructure/ # Adapters: KV/R2, outbound HTTP, logging, framework glue
|
||||||
|
logger.ts # JSON structured logger
|
||||||
|
feed-repository.ts # KV adapter for the Feed aggregate + global feed list + email bodies (load/save)
|
||||||
|
feed-mapper.ts # Translation seam: domain FeedState ↔ persistence DTOs (FeedConfig/FeedListItem); sole owner of snake_case outside the edge
|
||||||
|
icon-repository.ts # KV adapter for cached favicons (icon:*)
|
||||||
|
websub-subscription-repository.ts # KV adapter for WebSub subscriber lists (websub:subs:*)
|
||||||
|
counters-repository.ts # KV adapter for the monitoring counters singleton (stats:counters)
|
||||||
|
auth.ts # timingSafeEqual, proxy-auth check, API bearer middleware
|
||||||
|
cloudflare-email.ts # Cloudflare Email routing handler
|
||||||
|
forwardemail.ts # ForwardEmail webhook types/parsing
|
||||||
|
worker.ts # Typed worker / waitUntil helper
|
||||||
|
attachments.ts # R2 bucket accessor
|
||||||
|
favicon-fetcher.ts # Outbound favicon fetch + cache (uses IconRepository)
|
||||||
|
feed-generator.ts # RSS/Atom/JSON Feed XML+JSON generation
|
||||||
|
http-cache.ts # Conditional-GET validators (ETag/Last-Modified) for feed routes
|
||||||
|
html-processor.ts # Email HTML sanitization / inline cid: rewriting
|
||||||
|
websub.ts # WebSub subscription management + delivery
|
||||||
|
unsubscribe.ts # RFC 8058 one-click unsubscribe dispatch
|
||||||
|
urls.ts # URL builders
|
||||||
routes/
|
routes/
|
||||||
inbound.ts # ForwardEmail webhook handler
|
inbound.ts # ForwardEmail webhook handler
|
||||||
rss.ts # RSS feed renderer
|
rss.ts # RSS feed renderer
|
||||||
atom.ts # Atom feed renderer
|
atom.ts # Atom feed renderer
|
||||||
|
json.ts # JSON Feed renderer
|
||||||
|
opml.ts # OPML export of all feeds (admin-protected handler)
|
||||||
entries.ts # Single email HTML view
|
entries.ts # Single email HTML view
|
||||||
files.ts # R2 attachment serving
|
files.ts # R2 attachment serving
|
||||||
hub.ts # WebSub hub
|
hub.ts # WebSub hub
|
||||||
|
home.tsx # Public status page (GET /)
|
||||||
admin.tsx # Admin UI entrypoint (hono/jsx)
|
admin.tsx # Admin UI entrypoint (hono/jsx)
|
||||||
admin/ # Admin sub-modules
|
admin/ # Admin sub-modules
|
||||||
feeds.tsx # Feeds CRUD UI
|
feeds.tsx # Feeds CRUD UI
|
||||||
emails.tsx # Emails list/delete UI
|
emails.tsx # Emails list/delete UI
|
||||||
ui.tsx # Shared UI components
|
ui.tsx # Shared UI components
|
||||||
helpers.ts # Shared admin helpers
|
helpers.ts # Shared admin helpers
|
||||||
lib/
|
api/ # Versioned REST API (@hono/zod-openapi)
|
||||||
cloudflare-email.ts # Cloudflare Email routing handler
|
index.ts # OpenAPIHono app: /v1 routes + /openapi.json + /docs
|
||||||
email-parser.ts # Email parsing (mailparser)
|
schemas.ts # Zod schemas (validation + OpenAPI source of truth)
|
||||||
email-processor.ts # Core ingestion logic (parse → store)
|
|
||||||
feed-fetcher.ts # KV feed/email fetch helpers
|
|
||||||
feed-generator.ts # RSS/Atom XML generation
|
|
||||||
forwardemail.ts # ForwardEmail webhook types/parsing
|
|
||||||
id-generator.ts # Feed/entry ID generation
|
|
||||||
logger.ts # JSON structured logger
|
|
||||||
storage.ts # KV key helpers
|
|
||||||
websub.ts # WebSub subscription management
|
|
||||||
worker.ts # Typed worker export helper
|
|
||||||
scripts/
|
scripts/
|
||||||
client/ # TypeScript client scripts (compiled by esbuild)
|
client/ # TypeScript client scripts (compiled by esbuild)
|
||||||
dashboard.ts # Admin dashboard interactions
|
dashboard.ts # Admin dashboard interactions
|
||||||
@@ -92,15 +140,34 @@ src/
|
|||||||
|
|
||||||
All data lives in the `EMAIL_STORAGE` KV namespace:
|
All data lives in the `EMAIL_STORAGE` KV namespace:
|
||||||
|
|
||||||
| Key | Value |
|
| Key | Value |
|
||||||
| -------------------------------- | ------------------------------------------------------------------------ |
|
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
| `feeds:list` | `{ feeds: Array<{ id, title, description? }> }` |
|
| `feeds:list` | `{ feeds: Array<{ id, title, description?, mailbox_id?, expires_at? }> }` |
|
||||||
| `feed:<feedId>:config` | `FeedConfig` |
|
| `feed:<feedId>:config` | `FeedConfig` |
|
||||||
| `feed:<feedId>:metadata` | `{ emails: Array<{ key, subject, receivedAt, size?, attachmentIds? }> }` |
|
| `feed:<feedId>:metadata` | `{ emails: Array<{ key, subject, receivedAt, size?, attachmentIds?, inlineAttachmentIds? }>, nativeFeeds?: Record<string, NativeFeed[]>, nativeFeedDismissed?: boolean }` |
|
||||||
| `feed:<feedId>:<timestamp>` | Full `EmailData` |
|
| `feed:<feedId>:<timestamp>` | Full `EmailData` |
|
||||||
| `websub:<feedId>:<callbackHash>` | `WebSubSubscription` |
|
| `inbound:<mailboxId>` | The feed id this inbound address (`noun.noun.NN`) routes to (resolved only at reception) |
|
||||||
|
| `websub:subs:<feedId>` | `WebSubSubscription[]` (per-feed subscriber list) |
|
||||||
|
| `icon:<domain>` | Cached favicon record (base64 + content type; negative entries allowed) |
|
||||||
|
| `stats:counters` | `Counters` (cumulative monitoring counters singleton) |
|
||||||
|
|
||||||
`src/lib/storage.ts` contains key-builder helpers — use them; don't inline key strings in routes.
|
`feedId` is an **opaque random token** — the feed's identity, its KV storage key, and the public read id (`/rss/:feedId`). It is **decoupled** from the inbound email address: each feed also has a friendly `MailboxId` (`noun.noun.NN`) whose only mapping to the feed is the `inbound:<mailboxId>` secondary index, read **only** at email reception. So the feed's read URL never reveals its inbound address and vice-versa; reading `/rss/<noun.noun.NN>` 404s.
|
||||||
|
|
||||||
|
The KV key schema lives in `src/domain/feed-keys.ts` (pure, framework-agnostic) — never inline a `feed:`/`feeds:list`/`inbound:`/`websub:`/`icon:`/`stats:counters` key string anywhere else. KV access is owned by four repository **adapters** in `src/infrastructure/`, each for one concern: `FeedRepository` (the Feed aggregate + global list + email bodies), `IconRepository` (`icon:*`), `WebSubSubscriptionRepository` (`websub:subs:*`), and `CountersRepository` (`stats:counters`). Go through a repository, never `env.EMAIL_STORAGE.get/put` directly. The domain depends only on the key schema, not on these adapters.
|
||||||
|
|
||||||
|
### Domain & layering rules
|
||||||
|
|
||||||
|
- **Layers**: `domain/` is framework-agnostic (no Hono). `application/` orchestrates use-cases. `infrastructure/` holds adapters (KV/R2, HTTP, logging). `routes/` is the HTTP edge. Imports point inward: routes → application → domain; infrastructure implements ports the inner layers call.
|
||||||
|
- **The `Feed` aggregate is the only writer of feed config + the email index.** Load it with `FeedRepository.load(feedId)`, mutate via its methods (`ingest`, `removeEmails`, `edit`), then persist with `save`/`saveMetadata`/`saveConfig`. No route or service mutates `metadata.emails` directly. Email **bodies** are large blobs outside the aggregate — flush them (`putEmail`/`deleteEmail`) alongside the metadata save.
|
||||||
|
- **The domain never speaks the storage dialect.** The aggregate holds its config as domain `FeedState` (camelCase), never the snake_case `FeedConfig` DTO. The translation `FeedState ↔ FeedConfig/FeedListItem` lives in `infrastructure/feed-mapper.ts` — the only place outside the HTTP edge that knows the persisted field names. `FeedRepository.load` maps DTO→state on the way in; `save`/`saveConfig` map state→DTO on the way out.
|
||||||
|
- **The aggregate never exposes its raw state.** It has no `state`/`metadata` getters (a shallow `Readonly<…>` would still leak mutable arrays). Read named accessors (`title`, `expiresAt`, `emails`, `allowedSenders()`, …) which return copies; the repository reads `state()`/`toMetadataSnapshot()` (copies) and runs them through the mapper.
|
||||||
|
- **One edit path.** `edit(patch, { lifetime? })` is the single mutation for config. A `Lifetime` VO is resolved by the application (env `FEED_TTL_HOURS` override + client request); its **presence recomputes expiry, its absence preserves it** — which is exactly the dashboard's title/description quick-edit (no lifetime passed). It rejects an already-expired feed, so a quick-edit can no more touch an expired feed than a full edit can.
|
||||||
|
- **`feeds:list` and the `inbound:` index stay in sync automatically.** `FeedRepository.save`/`saveConfig` upsert the registry entry via `toListItemDTO(feed.id, feed.state())` _and_ write the `inbound:<mailbox> → feedId` index — services never mirror title/description/expiry into the list by hand. Symmetrically, `removeFromList`/`removeFromListBulk` drop the inbound index (the mailbox is cached on the list item) — so the index lives outside the `feed:<id>:` prefix the key purge sweeps, but is still cleared wherever a feed leaves the list (`deleteFeedRecord`, bulk admin delete, the cron). `deleteFeedFastDetailed` only removes config+metadata; it does **not** touch the index.
|
||||||
|
- Read-only RSS/Atom rendering uses the `feed-fetcher` read model, not the aggregate (no invariant to enforce on the hot path).
|
||||||
|
- KV has no multi-key transaction; the aggregate is the seam a future Durable Object would wrap to serialise concurrent ingests (see `email-processor.ts`).
|
||||||
|
- **Side effects via domain events.** Mutations with consequences record a `FeedEvent` (`FeedCreated`, `EmailIngested`), each carrying its own `feedId`. After persisting, the caller hands the aggregate to `application/feed-events.dispatchFeedEvents(feed, env, schedule)` — the single dispatch entry point that drains `pullEvents()` and runs the counters/WebSub/favicon. Don't pull events or thread the feed id by hand at call sites. Side effects with no aggregate mutation (a rejected email, feed deletion that bypasses the aggregate, bulk admin ops, the cron) stay imperative — they have no event to ride on.
|
||||||
|
- **`FeedId` flows through the layers.** It is the identity type taken by the domain (`Feed.id`), the application use-cases (`editFeed`, `editFeedDetails`, `deleteFeedRecord`, `fetchFeedData`, the cleanup steps) and the infrastructure repositories/services (`FeedRepository`, `WebSubSubscriptionRepository`, `notifySubscribers`, …). Mint it **once** at the edge — `FeedId.generate()` (opaque) for a new feed, `FeedId.unchecked(param)` at the read/HTTP edge (no revalidation: a bad id just misses in KV and 404s) — then pass the VO inward. Unwrap to `.value` (string) only at the true serialisation edges: URL builders (`urls.ts`), XML generation (`feed-generator.ts`), the KV key schema (`feed-keys.ts`), logs and JSON responses.
|
||||||
|
- **`FeedId` (read) vs `MailboxId` (write) are distinct identities.** `MailboxId` (`noun.noun.NN`) owns the inbound address and the untrusted-input boundary: `MailboxId.parse(address)` at reception is the only place an external string becomes a mailbox. Ingestion then resolves it to the feed via `FeedRepository.resolveInbound(mailbox)` and loads by the resulting `FeedId`. The mailbox is an attribute of the feed (held on `FeedState.mailboxId`, exposed as `Feed.mailboxId: MailboxId`, persisted as `mailbox_id`, projected into `feeds:list`); the `mailbox@domain` shape lives on the VO (`MailboxId.emailAddress(domain)`), with `urls.feedEmailAddress` only resolving the env domain. Never derive one id from the other — the decoupling is the privacy guarantee.
|
||||||
|
|
||||||
### Worker bindings (`Env`)
|
### Worker bindings (`Env`)
|
||||||
|
|
||||||
@@ -134,11 +201,31 @@ MSW (`msw/node`) handles external HTTP mocks. Tests that hit validation paths in
|
|||||||
- `ADMIN_PASSWORD` is set via `wrangler secret put` — never in config files
|
- `ADMIN_PASSWORD` is set via `wrangler secret put` — never in config files
|
||||||
- Keep `compatibility_date` current on runtime upgrades
|
- Keep `compatibility_date` current on runtime upgrades
|
||||||
|
|
||||||
|
## Releasing (read before cutting a release)
|
||||||
|
|
||||||
|
`package.json` `version` is inlined at build time as `APP_VERSION` (`src/config/version.ts`) and surfaced in the admin/status footer, `/health`, and `/api/v1/stats`. **`main` always carries a `-develop` pre-release suffix** (e.g. `0.4.0-develop`) so a dev build is never mistaken for a shipped one.
|
||||||
|
|
||||||
|
When asked to "release X.Y.Z", **run the script — never tag/bump/write notes by hand**:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run release X.Y.Z # next dev cycle defaults to next minor
|
||||||
|
npm run release X.Y.Z A.B.C # ...or pass an explicit next dev base (e.g. a patch line)
|
||||||
|
```
|
||||||
|
|
||||||
|
`X.Y.Z` must equal `main`'s current `X.Y.Z-develop` base. `scripts/release.sh` guards (clean tree, on `main`, synced with origin, version match, **non-empty `## [Unreleased]`**), then atomically: promotes `CHANGELOG.md`'s `## [Unreleased]` → `## [X.Y.Z]`, commits the **bare** `X.Y.Z` as a real release commit, tags it, opens the next `-develop` cycle (fresh `## [Unreleased]` + bump), and pushes `main` + the tag after a confirmation prompt.
|
||||||
|
|
||||||
|
The `v*` tag triggers the Release workflow (`.github/workflows/release.yml`), which **verifies** the tagged commit's `package.json` equals the tag exactly (wrong/`-develop`-commit guard), builds, and publishes a GitHub Release whose notes are the `## [X.Y.Z]` CHANGELOG section. **Release notes are never hand-typed** — they come from `CHANGELOG.md`, which you keep current under `## [Unreleased]` as part of every change (treat it like the other docs). Full flow in [CONTRIBUTING.md](CONTRIBUTING.md) under "Releasing".
|
||||||
|
|
||||||
## When changing behavior
|
## When changing behavior
|
||||||
|
|
||||||
Update together:
|
**Always document evolutions** — treat docs as part of the change, not a follow-up. When you add or change a feature, update the relevant docs in the same change:
|
||||||
|
|
||||||
|
- `CHANGELOG.md` — add a bullet under `## [Unreleased]` for any user-facing change (this is what the next release notes are built from; never deferred to release time)
|
||||||
- `README.md`
|
- `README.md`
|
||||||
- `AGENTS.md`
|
- `INSTALL.md` (setup, deployment, and configuration guide)
|
||||||
- `setup.sh` (if setup/deploy assumptions changed)
|
- `setup.sh` (if setup/deploy assumptions changed)
|
||||||
- Tests under `src/routes/*.test.ts` and `src/test/setup.ts`
|
- Tests under `src/routes/*.test.ts` and `src/test/setup.ts`
|
||||||
|
|
||||||
|
Keep it proportionate: user-facing or config changes warrant doc updates; purely internal refactors usually don't.
|
||||||
|
|
||||||
|
**Marketing landing page (`docs/index.html`).** This is the public GH Pages site (served at the `CNAME` domain), not the in-app status page (`src/routes/home.tsx`). When a feature is also a selling point — something a prospective self-hoster would care about (privacy guarantees, full-body capture, burnable aliases, reader compatibility, automation/API, AI features…) — surface it there too (hero copy or a feature card), matching the existing section/card style. Internal correctness fixes don't belong on the landing page; differentiators do.
|
||||||
|
|||||||
+121
@@ -0,0 +1,121 @@
|
|||||||
|
# Contributing to kill-the-news
|
||||||
|
|
||||||
|
Thanks for your interest in contributing! This is a small, self-hosted
|
||||||
|
Cloudflare Worker project. Issues, bug fixes, and well-scoped features are all
|
||||||
|
welcome.
|
||||||
|
|
||||||
|
## Getting started
|
||||||
|
|
||||||
|
Requirements: Node.js (LTS) and npm. A Cloudflare account is only needed to
|
||||||
|
deploy, not to run tests locally.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://github.com/juherr/kill-the-news.git
|
||||||
|
cd kill-the-news
|
||||||
|
npm install # installs deps and builds client scripts (prepare hook)
|
||||||
|
npm run dev # start the local dev server (wrangler dev)
|
||||||
|
```
|
||||||
|
|
||||||
|
For full setup, deployment, and configuration details, see
|
||||||
|
[INSTALL.md](INSTALL.md).
|
||||||
|
|
||||||
|
## Development workflow
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm test # run all tests once
|
||||||
|
npm run test:watch # run tests in watch mode
|
||||||
|
npm run build # dry-run deploy bundle (wrangler deploy --dry-run)
|
||||||
|
npm run format # format with Prettier
|
||||||
|
```
|
||||||
|
|
||||||
|
Run a single test file:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx vitest run src/routes/admin.test.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
Client-side scripts live in `src/scripts/client/` and are compiled by esbuild
|
||||||
|
into `src/scripts/generated/` (gitignored). They rebuild on `npm install`; to
|
||||||
|
rebuild manually:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run build:client
|
||||||
|
```
|
||||||
|
|
||||||
|
The architecture, source layout, and KV schema are documented in
|
||||||
|
[CLAUDE.md](CLAUDE.md) — a good orientation before making changes.
|
||||||
|
|
||||||
|
## Before opening a pull request
|
||||||
|
|
||||||
|
- **Add or update tests** for any behavior change. Tests live in
|
||||||
|
`src/routes/*.test.ts`, with shared mocks in `src/test/setup.ts`.
|
||||||
|
- **Run the checks**: `npm test`, `npm run build`, and `npm run format`.
|
||||||
|
Pre-commit hooks (husky + lint-staged) run lint/format on staged files.
|
||||||
|
- **Keep docs in sync.** When you change behavior, update the relevant files
|
||||||
|
together:
|
||||||
|
- `README.md`
|
||||||
|
- `INSTALL.md` (setup, deployment, configuration)
|
||||||
|
- `setup.sh` (if setup/deploy assumptions changed)
|
||||||
|
- **Keep PRs focused.** One logical change per PR is easier to review.
|
||||||
|
|
||||||
|
## Commit messages
|
||||||
|
|
||||||
|
This project follows [Conventional Commits](https://www.conventionalcommits.org/)
|
||||||
|
with a scope, matching the existing history. Examples:
|
||||||
|
|
||||||
|
```
|
||||||
|
feat(admin): collapse create-feed form into accordion
|
||||||
|
fix(attachments): render inline cid: images in emails and feeds
|
||||||
|
refactor(home): dedupe byte formatting in storage cards
|
||||||
|
docs(readme): add Continuous deployment section
|
||||||
|
```
|
||||||
|
|
||||||
|
Common types: `feat`, `fix`, `refactor`, `docs`, `test`, `chore`.
|
||||||
|
|
||||||
|
## Releasing
|
||||||
|
|
||||||
|
The running version is read from `package.json` `version` and inlined at build
|
||||||
|
time (footer, `/health`, `/api/v1/stats`). `main` **always** carries a
|
||||||
|
`-develop` pre-release suffix (e.g. `0.4.0-develop`) so a dev build is never
|
||||||
|
mistaken for a shipped one — `0.4.0-develop` sorts _below_ `0.4.0` per SemVer,
|
||||||
|
meaning "heading toward 0.4.0, not yet released".
|
||||||
|
|
||||||
|
**Cut releases with one command — never by hand:**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run release X.Y.Z # next dev cycle defaults to the next minor
|
||||||
|
npm run release X.Y.Z A.B.C # ...or pass an explicit next dev base (e.g. a patch line)
|
||||||
|
```
|
||||||
|
|
||||||
|
`X.Y.Z` must equal `main`'s current `X.Y.Z-develop` base. The script
|
||||||
|
(`scripts/release.sh`) guards (clean tree, on `main`, in sync with `origin`,
|
||||||
|
version match, non-empty changelog), then in one shot:
|
||||||
|
|
||||||
|
1. promotes the `## [Unreleased]` section of `CHANGELOG.md` to `## [X.Y.Z]`,
|
||||||
|
2. commits the **bare** `X.Y.Z` to `main` (a real release commit) and tags it,
|
||||||
|
3. opens the next `-develop` cycle (a fresh `## [Unreleased]` + bumped version),
|
||||||
|
4. pushes `main` + the tag (after showing you the notes and asking to confirm).
|
||||||
|
|
||||||
|
The `v*` tag triggers the Release workflow (`.github/workflows/release.yml`),
|
||||||
|
which **verifies** the tagged commit's `package.json` equals the tag exactly
|
||||||
|
(catching a wrong or `-develop` commit), builds the bundle, and publishes a
|
||||||
|
GitHub Release whose notes are the `## [X.Y.Z]` section of `CHANGELOG.md` — so the
|
||||||
|
changelog you maintained in-repo is what ships. Keep `## [Unreleased]` up to date
|
||||||
|
**as part of every change**; the release notes are never hand-typed.
|
||||||
|
|
||||||
|
If you ever release manually, the tagged commit must carry the bare `X.Y.Z` in
|
||||||
|
`package.json` and the matching `## [X.Y.Z]` section must exist in
|
||||||
|
`CHANGELOG.md` — the workflow fails fast otherwise.
|
||||||
|
|
||||||
|
## Reporting bugs and requesting features
|
||||||
|
|
||||||
|
Open an issue at
|
||||||
|
[github.com/juherr/kill-the-news/issues](https://github.com/juherr/kill-the-news/issues).
|
||||||
|
For bugs, include reproduction steps, expected vs. actual behavior, and your
|
||||||
|
environment (ingestion method, relevant config). For security issues, follow
|
||||||
|
[SECURITY.md](SECURITY.md) instead of opening a public issue.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
By contributing, you agree that your contributions will be licensed under the
|
||||||
|
[MIT License](LICENSE).
|
||||||
+265
@@ -0,0 +1,265 @@
|
|||||||
|
# Installation & deployment
|
||||||
|
|
||||||
|
How to set up, run, deploy, and configure kill-the-news. For an overview of what the project does, see [README.md](README.md).
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
- Node.js 20+
|
||||||
|
- A Cloudflare account (free plan works — Workers, KV, and Email Routing are all included)
|
||||||
|
- A domain added to Cloudflare as a zone (DNS managed by Cloudflare)
|
||||||
|
- A ForwardEmail account _(Option B only)_
|
||||||
|
|
||||||
|
## Cloudflare setup
|
||||||
|
|
||||||
|
If your domain is not yet on Cloudflare: in the [Cloudflare dashboard](https://dash.cloudflare.com/), go to _Add a site_, enter your domain, choose the Free plan, and follow the instructions to update your nameservers at your registrar. Wait for the zone to become active (usually a few minutes).
|
||||||
|
|
||||||
|
## Setup
|
||||||
|
|
||||||
|
1. Clone this repository.
|
||||||
|
2. Authenticate Wrangler:
|
||||||
|
```bash
|
||||||
|
npx wrangler login
|
||||||
|
```
|
||||||
|
3. Run setup:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bash setup.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
The script will prompt for an admin password and your domain, then:
|
||||||
|
- install npm dependencies
|
||||||
|
- verify Cloudflare auth (`wrangler whoami`)
|
||||||
|
- create KV namespaces (`EMAIL_STORAGE` + preview) in your account
|
||||||
|
- set the `ADMIN_PASSWORD` secret in the `production` environment
|
||||||
|
- generate `wrangler.toml` from `wrangler-example.toml` with your KV IDs, domain, and today's compatibility date
|
||||||
|
|
||||||
|
4. Configure email ingestion — choose **one** of the two options below.
|
||||||
|
|
||||||
|
### Option A — Cloudflare Email Workers (recommended)
|
||||||
|
|
||||||
|
No third-party service required. Cloudflare receives the email and hands it directly to the Worker.
|
||||||
|
|
||||||
|
1. In the Cloudflare dashboard, go to _Email → Email Routing_ for your zone and click **Enable Email Routing**. Cloudflare will prompt you to add MX and SPF records — accept and it adds them automatically.
|
||||||
|
2. Under _Email Routing → Routing Rules_, add a **Catch-all** rule:
|
||||||
|
- Action: **Send to Worker**
|
||||||
|
- Worker: `kill-the-news` (the name from `wrangler.toml`)
|
||||||
|
|
||||||
|
That's it. No webhook configuration is needed.
|
||||||
|
|
||||||
|
### Option B — ForwardEmail (alternative)
|
||||||
|
|
||||||
|
Use this if you prefer ForwardEmail's additional features (sender filtering, open-tracking, etc.).
|
||||||
|
|
||||||
|
Add these DNS records in Cloudflare (_DNS → Records_):
|
||||||
|
|
||||||
|
| Type | Name | Content | Notes |
|
||||||
|
| ---- | ---- | ---------------------------------------------------- | ----------------------- |
|
||||||
|
| MX | @ | `mx1.forwardemail.net` | Priority `10`, DNS only |
|
||||||
|
| MX | @ | `mx2.forwardemail.net` | Priority `10`, DNS only |
|
||||||
|
| TXT | @ | `"forward-email=https://yourdomain.com/api/inbound"` | webhook target |
|
||||||
|
| TXT | @ | `"v=spf1 include:spf.forwardemail.net -all"` | SPF |
|
||||||
|
|
||||||
|
Replace `yourdomain.com` with your actual domain.
|
||||||
|
|
||||||
|
The Worker verifies each webhook request against ForwardEmail's published MX IP list before processing it.
|
||||||
|
|
||||||
|
5. Deploy:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run deploy
|
||||||
|
```
|
||||||
|
|
||||||
|
Wrangler will create the Worker and register `yourdomain.com` (and `www.yourdomain.com`) as custom domains pointing to it. Cloudflare handles TLS automatically.
|
||||||
|
|
||||||
|
6. Open `https://yourdomain.com/admin` and sign in.
|
||||||
|
|
||||||
|
> **Tip:** To verify the Worker is running, check _Workers & Pages → kill-the-news_ in the Cloudflare dashboard. The _Custom Domains_ tab should list your domain once the deploy succeeds.
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install
|
||||||
|
npm run dev
|
||||||
|
npm test
|
||||||
|
npm run build
|
||||||
|
```
|
||||||
|
|
||||||
|
## Continuous deployment (GitHub Actions)
|
||||||
|
|
||||||
|
The repo ships a [`Deploy Demo`](.github/workflows/demo.yml) workflow that generates `wrangler.toml` from `wrangler-example.toml` and runs `wrangler deploy --env demo` after CI passes on `main`. To wire up your own automated deploys, set these repository secrets (_Settings → Secrets and variables → Actions_):
|
||||||
|
|
||||||
|
| Secret | Purpose |
|
||||||
|
| ----------------------- | ------------------------------------------------------------------- |
|
||||||
|
| `CLOUDFLARE_API_TOKEN` | Scoped API token used by Wrangler to deploy (see permissions below) |
|
||||||
|
| `CLOUDFLARE_ACCOUNT_ID` | Target Cloudflare account ID |
|
||||||
|
| `DEMO_KV_NAMESPACE_ID` | KV namespace ID substituted into the generated `wrangler.toml` |
|
||||||
|
| `DEMO_ADMIN_PASSWORD` | Admin password set via `wrangler secret put` |
|
||||||
|
|
||||||
|
### Deploy token permissions
|
||||||
|
|
||||||
|
Local `npx wrangler login` uses OAuth and already has every permission, so the gaps below only bite **scoped API tokens** (i.e. CI). Create the token at <https://dash.cloudflare.com/profile/api-tokens> — the **"Edit Cloudflare Workers"** template is the easiest base — and make sure it carries the permissions matching the bindings you actually deploy:
|
||||||
|
|
||||||
|
| Permission | Needed for |
|
||||||
|
| ------------------------------------------------- | -------------------------------------------------------------------------- |
|
||||||
|
| Account · **Workers Scripts** · Edit | Deploying the Worker and running `wrangler secret put` |
|
||||||
|
| Account · **Workers KV Storage** · Edit | The `EMAIL_STORAGE` KV binding |
|
||||||
|
| Account · **Workers R2 Storage** · Edit | The `ATTACHMENT_BUCKET` R2 binding (only when attachments are enabled) |
|
||||||
|
| Zone · **Workers Routes** · Edit + **DNS** · Edit | The `custom_domain` routes (e.g. `demo.kill-the.news`), scoped to its zone |
|
||||||
|
|
||||||
|
Scope the token to the relevant **account** and, for custom domains, the relevant **zone**. A missing R2 permission fails with `Authentication error [code: 10000]` on `/r2/buckets/...`; a missing routes/DNS permission fails while provisioning the custom domain. The `User Details`/`Memberships` warnings Wrangler prints are only for `whoami` display and are not fatal.
|
||||||
|
|
||||||
|
## Configuration notes
|
||||||
|
|
||||||
|
- `wrangler-example.toml` is the template; `wrangler.toml` is generated locally.
|
||||||
|
- Keep `compatibility_date` fresh when doing runtime upgrades.
|
||||||
|
- `ADMIN_PASSWORD` is a Cloudflare Worker secret, not a plain env var in config.
|
||||||
|
|
||||||
|
### Native feed detection
|
||||||
|
|
||||||
|
When an incoming email's HTML advertises the newsletter's own syndication feed via `<link rel="alternate" type="application/atom+xml|rss+xml|feed+json">`, the worker captures those URLs at ingestion and shows them per feed — no configuration required:
|
||||||
|
|
||||||
|
- **Email detail page** — a "Native feeds" chip group lists each discovered feed URL with a copy button.
|
||||||
|
- **Feed dashboard** — a "Native feed available" pill signals that the source publishes its own feed.
|
||||||
|
- **Emails page banner** — a dismissable banner prompts you to subscribe to the source directly; once dismissed it stays hidden.
|
||||||
|
- **REST API** — the read-only `nativeFeeds` array on `GET/POST/PATCH /api/v1/feeds` exposes the same data for automation.
|
||||||
|
|
||||||
|
### Subscription confirmation
|
||||||
|
|
||||||
|
When a newsletter sends a "confirm your email" message, the worker detects it at ingestion using multilingual keyword matching and link scoring. Detected emails are automatically flagged and surfaced throughout the admin UI:
|
||||||
|
|
||||||
|
- **Email detail page** — a dedicated "Confirm your subscription" section appears at the top with a primary button linking directly to the confirmation URL.
|
||||||
|
- **Email list** — a "Confirmation" badge appears next to the subject so pending confirmations stand out at a glance.
|
||||||
|
- **Feed dashboard** — a "Confirmation pending" pill on the feed card signals that action is needed.
|
||||||
|
- **Emails page banner** — a dismissible banner with a "Mark as confirmed" button lets you clear the flag once you've clicked the link.
|
||||||
|
|
||||||
|
**v1 performs no outbound request.** The admin clicks the confirmation link themselves in their browser; the worker only detects and surfaces it. Server-side on-detect actions (auto-click from the worker, or forwarding the original email to a fallback address) are planned for a future version.
|
||||||
|
|
||||||
|
### Catch-all fallback forwarding
|
||||||
|
|
||||||
|
By default, inbound mail that doesn't match a feed is dropped (logged, then discarded). If you want to point a domain's **catch-all** at this worker without losing your personal mail, set an optional fallback address — non-feed mail is forwarded there instead of dropped:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[vars]
|
||||||
|
FALLBACK_FORWARD_ADDRESS = "you@example.com"
|
||||||
|
```
|
||||||
|
|
||||||
|
**Prerequisite:** the address must be a **verified destination** in _Email → Email Routing → Destination addresses_ (Cloudflare won't forward to an unverified address — `message.forward()` fails, and the worker just logs a warning). This only applies to the Cloudflare Email Workers path (Option A).
|
||||||
|
|
||||||
|
What gets forwarded vs dropped:
|
||||||
|
|
||||||
|
| Situation | Action |
|
||||||
|
| -------------------------------------------------- | --------------------- |
|
||||||
|
| Address isn't a feed (e.g. `you@`, typo) | forward |
|
||||||
|
| Well-formed feed address but no such feed | forward |
|
||||||
|
| Feed exists but is **expired** | drop |
|
||||||
|
| Feed exists but the sender is **blocked/filtered** | drop |
|
||||||
|
| Delivered to a live feed | ingested (no forward) |
|
||||||
|
|
||||||
|
Expired feeds and blocked senders are dropped on purpose, so a real newsletter never leaks into your fallback inbox. Leave the variable unset to keep the original drop-and-log behavior.
|
||||||
|
|
||||||
|
### Inbound address vs feed URL
|
||||||
|
|
||||||
|
Each feed has **two independent identifiers**, on purpose:
|
||||||
|
|
||||||
|
- a friendly **inbound address** you subscribe newsletters with — `noun.noun.NN@yourdomain.com` (e.g. `apple.mountain.42@yourdomain.com`);
|
||||||
|
- an **opaque feed URL** for your reader — `https://yourdomain.com/rss/<random-id>` (also `/atom/<id>`, `/json/<id>`).
|
||||||
|
|
||||||
|
They are not derivable from each other. This means you can hand someone a feed URL without revealing the address that feeds it, and an address harvested by a newsletter sender can't be turned into your feed (requesting `/rss/<your-address>` returns 404). The admin dashboard shows both per feed; copy the address into signup forms and the feed URL into your reader. (Internally the inbound address is mapped to the feed by an `inbound:<address>` KV entry, resolved only when mail arrives.)
|
||||||
|
|
||||||
|
### Feed size limit
|
||||||
|
|
||||||
|
By default the worker keeps emails until the feed's stored data exceeds **512 KB**, then drops the oldest entries (and their KV records) to stay under the limit. This is more robust than a fixed entry count for HTML-heavy newsletters.
|
||||||
|
|
||||||
|
To override the threshold, add to `wrangler.toml` under `[vars]`:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
FEED_MAX_SIZE_BYTES = "524288" # 512 KB — adjust as needed
|
||||||
|
```
|
||||||
|
|
||||||
|
### Email attachments (R2)
|
||||||
|
|
||||||
|
When an incoming email contains attachments, the Worker can store them in a Cloudflare R2 bucket and expose them as `<enclosure>` elements in the RSS feed (and `<link rel="enclosure">` in Atom). Each attachment is served at `/files/{id}/{filename}` with an immutable cache header. Attachments are also listed with download links on the admin email detail page and the public entry view.
|
||||||
|
|
||||||
|
Inline images (the ones an email references with `src="cid:…"`) are handled separately: they are still stored in R2 (and deleted with the email), but instead of appearing in the attachment list they render in place — the `cid:` reference is rewritten to the stored `/files/{id}/{filename}` URL in the feed, the admin preview, and the public entry view.
|
||||||
|
|
||||||
|
This feature is **optional**. If no R2 bucket is bound, attachments are silently ignored and nothing else changes.
|
||||||
|
|
||||||
|
**Setup (automated):** `setup.sh` now asks _"Enable email attachments stored in R2?"_. Answer yes and it creates the buckets (`<worker>-attachments` and `<worker>-attachments-preview`) and wires the binding into the generated `wrangler.toml` for you.
|
||||||
|
|
||||||
|
**Setup (manual):**
|
||||||
|
|
||||||
|
1. Create an R2 bucket in the Cloudflare dashboard (_R2 Object Storage → Create bucket_), or with Wrangler:
|
||||||
|
```bash
|
||||||
|
npx wrangler r2 bucket create your-bucket-name
|
||||||
|
```
|
||||||
|
2. In `wrangler.toml`, uncomment and fill in the R2 binding (the commented block from `wrangler-example.toml`):
|
||||||
|
```toml
|
||||||
|
r2_buckets = [
|
||||||
|
{ binding = "ATTACHMENT_BUCKET", bucket_name = "your-bucket-name", preview_bucket_name = "your-bucket-name-preview" }
|
||||||
|
]
|
||||||
|
```
|
||||||
|
The binding is **per environment**: add it under every env you deploy (`[env.production]`, `[env.demo]`, …), each pointing at its own bucket.
|
||||||
|
3. Redeploy:
|
||||||
|
```bash
|
||||||
|
npm run deploy
|
||||||
|
```
|
||||||
|
|
||||||
|
> **Deploy token permission:** with an R2 binding, `wrangler deploy` verifies the bucket exists, so a scoped CI token also needs **Account → Workers R2 Storage** — see [Continuous deployment](#continuous-deployment-github-actions). Local `npx wrangler login` already has it.
|
||||||
|
|
||||||
|
**Turning it off:** set `ATTACHMENTS_ENABLED = "false"` in `[vars]` to disable attachments even while the R2 bucket stays bound (useful to cap usage on a demo). Any other value (or leaving it unset) keeps the feature on whenever R2 is configured.
|
||||||
|
|
||||||
|
Attachments are deleted from R2 automatically when the corresponding email is deleted from the admin UI, or when an email is dropped during feed size trimming.
|
||||||
|
|
||||||
|
**Monitoring storage / free tier:** the status page (`/`) and `/api/v1/stats` report R2 space used (against the **10 GB** R2 free tier) and an estimate of KV space used (against the **1 GB** KV free tier). The figures are refreshed hourly by the cron trigger. KV usage is an estimate based on stored email sizes, so treat it as a lower bound.
|
||||||
|
|
||||||
|
### External auth provider (Authelia / Authentik / reverse proxy)
|
||||||
|
|
||||||
|
Instead of the built-in password login you can delegate admin authentication to a reverse proxy that sets a trusted user header (`Remote-User` or `X-Forwarded-User`).
|
||||||
|
|
||||||
|
**Required Worker secrets** (set with `wrangler secret put`, never in `[vars]`):
|
||||||
|
|
||||||
|
| Secret | Description |
|
||||||
|
| ------------------- | ---------------------------------------------- |
|
||||||
|
| `PROXY_AUTH_SECRET` | Shared secret between the proxy and the Worker |
|
||||||
|
|
||||||
|
**Required `[vars]`** in `wrangler.toml`:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
PROXY_TRUSTED_IPS = "10.0.0.1" # comma-separated IPs of your reverse proxy
|
||||||
|
```
|
||||||
|
|
||||||
|
When both are configured, the Worker authenticates a request if:
|
||||||
|
|
||||||
|
1. `CF-Connecting-IP` is in `PROXY_TRUSTED_IPS`
|
||||||
|
2. The `X-Auth-Proxy-Secret` header matches `PROXY_AUTH_SECRET`
|
||||||
|
3. `Remote-User` or `X-Forwarded-User` is non-empty
|
||||||
|
|
||||||
|
Password login remains available as a fallback when the proxy check fails.
|
||||||
|
|
||||||
|
> **Security note:** `CF-Connecting-IP` can be spoofed on direct `workers.dev` requests. Disable the `workers.dev` subdomain in production (`workers_dev = false` in `[env.production]`).
|
||||||
|
|
||||||
|
### REST API authentication
|
||||||
|
|
||||||
|
The versioned REST API (`/api/v1/*`) is authenticated independently of the cookie-based
|
||||||
|
admin UI — there is no CSRF check, so it is suited to server-to-server automation. A
|
||||||
|
request is authorized when **either**:
|
||||||
|
|
||||||
|
- it carries `Authorization: Bearer <ADMIN_PASSWORD>` (the same admin password secret), **or**
|
||||||
|
- it passes the reverse-proxy check above (`PROXY_TRUSTED_IPS` + `X-Auth-Proxy-Secret` + `Remote-User`).
|
||||||
|
|
||||||
|
The OpenAPI 3.1 spec (`/api/openapi.json`) and the Scalar reference (`/api/docs`) are
|
||||||
|
public. In the Scalar UI, click **Authorize** and paste the admin password as the bearer
|
||||||
|
token to try requests. See the route table in [README.md](README.md#rest-api).
|
||||||
|
|
||||||
|
## Upgrading dependencies
|
||||||
|
|
||||||
|
To refresh dependencies to latest:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm outdated
|
||||||
|
npm install
|
||||||
|
npm test
|
||||||
|
npm run build
|
||||||
|
```
|
||||||
|
|
||||||
|
Then update `compatibility_date` and redeploy.
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
MIT License
|
MIT License
|
||||||
|
|
||||||
Copyright (c) 2025 Young Lee
|
Copyright (c) 2025 Young Lee
|
||||||
|
Copyright (c) 2025-2026 Julien Herr
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
|||||||
@@ -16,15 +16,28 @@ kill-the-news keeps the same workflow while avoiding shared domains and shared d
|
|||||||
- Bulk feed/email deletion from the admin dashboard (safe checkbox-based flow)
|
- Bulk feed/email deletion from the admin dashboard (safe checkbox-based flow)
|
||||||
- Inline double-confirm delete interactions with toast feedback in the admin dashboard
|
- Inline double-confirm delete interactions with toast feedback in the admin dashboard
|
||||||
- Resizable + sortable table columns in the admin dashboard (Table view)
|
- Resizable + sortable table columns in the admin dashboard (Table view)
|
||||||
|
- Per-feed "Subscribe" chips in the admin dashboard — copy, open, or validate the feed in one click for each of RSS, Atom, and JSON Feed (validation via the W3C Feed Validator and validator.jsonfeed.org)
|
||||||
- Unique newsletter addresses per feed (for example `apple.mountain.42@yourdomain.com`)
|
- Unique newsletter addresses per feed (for example `apple.mountain.42@yourdomain.com`)
|
||||||
|
- **Separate inbound address and feed URL** — the address you subscribe with (`apple.mountain.42@yourdomain.com`) and the public feed URL (`/rss/<opaque-id>`) use **independent** ids, so you can share a feed without leaking the address that feeds it, and an address harvested by a newsletter can't be used to read your feed (`/rss/<your-address>` 404s)
|
||||||
- Cloudflare Email Workers ingestion (no third-party service)
|
- Cloudflare Email Workers ingestion (no third-party service)
|
||||||
- ForwardEmail webhook ingestion with source-IP verification (optional alternative)
|
- ForwardEmail webhook ingestion with source-IP verification (optional alternative)
|
||||||
- Optional per-feed sender allowlist (`email@domain.com` or `domain.com`)
|
- Optional per-feed sender allowlist (`email@domain.com` or `domain.com`)
|
||||||
|
- Optional per-feed "sender in title" toggle — renders each entry as `[Sender] Subject` for at-a-glance scanning in your reader
|
||||||
- RSS generation on demand (`/rss/:feedId`)
|
- RSS generation on demand (`/rss/:feedId`)
|
||||||
- Atom feed at `/atom/:feedId`
|
- Atom feed at `/atom/:feedId`
|
||||||
|
- JSON Feed at `/json/:feedId` (natively consumed by NetNewsWire, Reeder, NewsBlur, Feedly)
|
||||||
|
- Bandwidth-friendly polling: RSS/Atom send a strong `ETag` + `Last-Modified` and answer `304 Not Modified` on conditional requests
|
||||||
|
- Duplicate-send dedup: a newsletter delivered twice (matched by `Message-ID`, then by a content hash) is stored once
|
||||||
|
- OPML export of all feeds at `/admin/opml` (admin-protected) for one-click bulk import into any reader
|
||||||
|
- Reader-friendly output: relative links/images absolutized to the sender's site, lazy-loaded images promoted (`data-src` → `src`), plain-text feed titles, and XML-illegal control characters stripped so feeds parse in strict readers
|
||||||
|
- Per-feed favicon derived from the last sender's domain (`/favicon/:feedId`), cached and shown in feeds + admin
|
||||||
|
- Automatic RFC 8058 one-click unsubscribe when a feed is deleted — stops newsletters from mailing the now-dead address
|
||||||
|
- **Subscription confirmation surfacing** — at ingestion the worker detects "confirm your subscription" emails (multilingual keyword + link scoring) and surfaces them in the admin: a dedicated section with a primary "Confirm subscription" button on the email detail page, a "Confirmation" badge in the email list, a "Confirmation pending" pill on the dashboard, and a banner on the feed's emails page with a "Mark as confirmed" dismiss button; v1 surfaces the link only — no outbound request is made
|
||||||
|
- **Native feed detection** — when a newsletter advertises its own RSS/Atom/JSON feed via `<link rel="alternate">` in the email HTML, KTN surfaces it in the admin (a "Native feeds" chip group on the email detail page, a dashboard pill, and a dismissable banner) and on the REST API (`nativeFeeds` field), so you can subscribe to the source directly
|
||||||
- Email attachments stored in Cloudflare R2 and exposed as RSS enclosures (optional)
|
- Email attachments stored in Cloudflare R2 and exposed as RSS enclosures (optional)
|
||||||
- Cloudflare KV storage for feed config + email metadata/content
|
- Cloudflare KV storage for feed config + email metadata/content
|
||||||
- Password-protected admin UI
|
- Password-protected admin UI
|
||||||
|
- Versioned REST API (`/api/v1/*`) with an OpenAPI 3.1 spec and Scalar docs for automation
|
||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
|
|
||||||
@@ -37,192 +50,104 @@ Two ingestion methods are supported — pick one or use both:
|
|||||||
|
|
||||||
Common path:
|
Common path:
|
||||||
|
|
||||||
1. Incoming email arrives at `user@yourdomain.com`.
|
1. Incoming email arrives at `apple.mountain.42@yourdomain.com` (the feed's inbound address).
|
||||||
2. The Worker resolves the feed from the recipient address and stores the email in KV.
|
2. The Worker resolves the feed from the recipient address (via the `inbound:` index) and stores the email in KV.
|
||||||
3. `https://yourdomain.com/rss/:feedId` renders RSS from stored items.
|
3. `https://yourdomain.com/rss/<opaque-feed-id>` renders RSS from stored items — note the feed id is a separate opaque token, not the inbound address.
|
||||||
4. `/admin` provides feed management and email deletion.
|
4. `/admin` provides feed management and email deletion.
|
||||||
|
5. `https://yourdomain.com/` shows a public status page with monitoring counters and a link to the admin.
|
||||||
|
|
||||||
Main routes:
|
Main routes:
|
||||||
|
|
||||||
- `src/lib/cloudflare-email.ts`: Cloudflare Email Workers ingestion
|
- `src/lib/cloudflare-email.ts`: Cloudflare Email Workers ingestion
|
||||||
- `src/routes/inbound.ts`: ForwardEmail webhook ingestion
|
- `src/routes/inbound.ts`: ForwardEmail webhook ingestion
|
||||||
- `src/routes/rss.ts`: RSS rendering
|
- `src/routes/rss.ts`: RSS rendering (with conditional-GET / ETag support)
|
||||||
- `src/routes/atom.ts`: Atom feed rendering
|
- `src/routes/atom.ts`: Atom feed rendering (with conditional-GET / ETag support)
|
||||||
|
- `src/routes/json.ts`: JSON Feed rendering
|
||||||
|
- `src/routes/opml.ts`: OPML export of all feeds (admin-protected, mounted at `/admin/opml`)
|
||||||
- `src/routes/files.ts`: attachment file serving from R2
|
- `src/routes/files.ts`: attachment file serving from R2
|
||||||
- `src/routes/admin.ts`: admin UI + feed CRUD
|
- `src/routes/admin.tsx`: admin UI + feed CRUD
|
||||||
|
- `src/routes/api/`: versioned REST API + OpenAPI spec/docs (`/api/v1/*`, `/api/openapi.json`, `/api/docs`)
|
||||||
|
- `src/lib/feed-service.ts`: shared feed create/update/delete (used by the admin UI and the REST API)
|
||||||
|
- `src/routes/home.tsx`: public status page (`GET /`)
|
||||||
|
|
||||||
## Requirements
|
### Monitoring
|
||||||
|
|
||||||
- Node.js 20+
|
`GET /api/v1/stats` returns JSON counters (public, no auth, CORS-enabled) for
|
||||||
- A Cloudflare account (free plan works — Workers, KV, and Email Routing are all included)
|
uptime/monitoring tools and the landing page:
|
||||||
- A domain added to Cloudflare as a zone (DNS managed by Cloudflare)
|
|
||||||
- A ForwardEmail account _(Option B only)_
|
|
||||||
|
|
||||||
## Cloudflare setup
|
| Field | Meaning |
|
||||||
|
| ----------------------------- | -------------------------------------------------------- |
|
||||||
|
| `active_feeds` | Feeds currently configured (live) |
|
||||||
|
| `feeds_created` | Total feeds ever created (cumulative) |
|
||||||
|
| `feeds_deleted` | Total feeds ever deleted (cumulative) |
|
||||||
|
| `emails_received` | Total emails ingested successfully (cumulative) |
|
||||||
|
| `emails_rejected` | Total emails rejected during validation (cumulative) |
|
||||||
|
| `websub_subscriptions_active` | Active WebSub subscriptions (live) |
|
||||||
|
| `last_email_at` | ISO 8601 date-time of the last ingested email |
|
||||||
|
| `last_feed_created_at` | ISO 8601 date-time of the last feed creation |
|
||||||
|
| `first_seen` | ISO 8601 date-time the instance first recorded a counter |
|
||||||
|
|
||||||
If your domain is not yet on Cloudflare: in the [Cloudflare dashboard](https://dash.cloudflare.com/), go to _Add a site_, enter your domain, choose the Free plan, and follow the instructions to update your nameservers at your registrar. Wait for the zone to become active (usually a few minutes).
|
The same figures are rendered on the public status page at `GET /`. Cumulative counters
|
||||||
|
are persisted in the `EMAIL_STORAGE` KV under the `stats:counters` key.
|
||||||
|
|
||||||
## Setup
|
### REST API
|
||||||
|
|
||||||
1. Clone this repository.
|
A versioned REST API lets you automate feed and email management without scraping the
|
||||||
2. Authenticate Wrangler:
|
admin UI. The OpenAPI 3.1 spec is served at `GET /api/openapi.json` and a rendered
|
||||||
```bash
|
reference (Scalar) at `GET /api/docs` — both public.
|
||||||
npx wrangler login
|
|
||||||
```
|
|
||||||
3. Run setup:
|
|
||||||
|
|
||||||
```bash
|
The feed and email endpoints require authentication, using either:
|
||||||
bash setup.sh
|
|
||||||
```
|
|
||||||
|
|
||||||
The script will prompt for an admin password and your domain, then:
|
- **Bearer token**: `Authorization: Bearer <ADMIN_PASSWORD>`, or
|
||||||
- install npm dependencies
|
- **Reverse-proxy auth**: the same trusted-IP + `X-Auth-Proxy-Secret` + `Remote-User`
|
||||||
- verify Cloudflare auth (`wrangler whoami`)
|
headers as the admin UI (see [INSTALL.md](INSTALL.md)).
|
||||||
- create KV namespaces (`EMAIL_STORAGE` + preview) in your account
|
|
||||||
- set the `ADMIN_PASSWORD` secret in the `production` environment
|
|
||||||
- generate `wrangler.toml` from `wrangler-example.toml` with your KV IDs, domain, and today's compatibility date
|
|
||||||
|
|
||||||
4. Configure email ingestion — choose **one** of the two options below.
|
`GET /api/v1/stats`, the OpenAPI spec, and the docs page are public.
|
||||||
|
|
||||||
### Option A — Cloudflare Email Workers (recommended)
|
| Method | Path | Auth | Purpose |
|
||||||
|
| -------- | ------------------------------------ | ------ | ------------------------ |
|
||||||
|
| `GET` | `/api/v1/feeds` | yes | List feeds |
|
||||||
|
| `POST` | `/api/v1/feeds` | yes | Create a feed |
|
||||||
|
| `GET` | `/api/v1/feeds/{feedId}` | yes | Get a feed |
|
||||||
|
| `PATCH` | `/api/v1/feeds/{feedId}` | yes | Update a feed |
|
||||||
|
| `DELETE` | `/api/v1/feeds/{feedId}` | yes | Delete a feed |
|
||||||
|
| `GET` | `/api/v1/feeds/{feedId}/emails` | yes | List a feed's emails |
|
||||||
|
| `GET` | `/api/v1/feeds/{feedId}/emails/{id}` | yes | Get a single email |
|
||||||
|
| `DELETE` | `/api/v1/feeds/{feedId}/emails/{id}` | yes | Delete a single email |
|
||||||
|
| `GET` | `/api/v1/stats` | public | Read monitoring counters |
|
||||||
|
|
||||||
No third-party service required. Cloudflare receives the email and hands it directly to the Worker.
|
The email `{id}` is the email's `receivedAt` timestamp (as returned by the list endpoint).
|
||||||
|
|
||||||
1. In the Cloudflare dashboard, go to _Email → Email Routing_ for your zone and click **Enable Email Routing**. Cloudflare will prompt you to add MX and SPF records — accept and it adds them automatically.
|
|
||||||
2. Under _Email Routing → Routing Rules_, add a **Catch-all** rule:
|
|
||||||
- Action: **Send to Worker**
|
|
||||||
- Worker: `kill-the-news` (the name from `wrangler.toml`)
|
|
||||||
|
|
||||||
That's it. No webhook configuration is needed.
|
|
||||||
|
|
||||||
### Option B — ForwardEmail (alternative)
|
|
||||||
|
|
||||||
Use this if you prefer ForwardEmail's additional features (sender filtering, open-tracking, etc.).
|
|
||||||
|
|
||||||
Add these DNS records in Cloudflare (_DNS → Records_):
|
|
||||||
|
|
||||||
| Type | Name | Content | Notes |
|
|
||||||
| ---- | ---- | ---------------------------------------------------- | ----------------------- |
|
|
||||||
| MX | @ | `mx1.forwardemail.net` | Priority `10`, DNS only |
|
|
||||||
| MX | @ | `mx2.forwardemail.net` | Priority `10`, DNS only |
|
|
||||||
| TXT | @ | `"forward-email=https://yourdomain.com/api/inbound"` | webhook target |
|
|
||||||
| TXT | @ | `"v=spf1 include:spf.forwardemail.net -all"` | SPF |
|
|
||||||
|
|
||||||
Replace `yourdomain.com` with your actual domain.
|
|
||||||
|
|
||||||
The Worker verifies each webhook request against ForwardEmail's published MX IP list before processing it.
|
|
||||||
|
|
||||||
5. Deploy:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npm run deploy
|
|
||||||
```
|
|
||||||
|
|
||||||
Wrangler will create the Worker and register `yourdomain.com` (and `www.yourdomain.com`) as custom domains pointing to it. Cloudflare handles TLS automatically.
|
|
||||||
|
|
||||||
6. Open `https://yourdomain.com/admin` and sign in.
|
|
||||||
|
|
||||||
> **Tip:** To verify the Worker is running, check _Workers & Pages → kill-the-news_ in the Cloudflare dashboard. The _Custom Domains_ tab should list your domain once the deploy succeeds.
|
|
||||||
|
|
||||||
## Development
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm install
|
# Create a feed
|
||||||
npm run dev
|
curl -X POST https://yourdomain.com/api/v1/feeds \
|
||||||
npm test
|
-H "Authorization: Bearer $ADMIN_PASSWORD" \
|
||||||
npm run build
|
-H 'Content-Type: application/json' \
|
||||||
|
-d '{"title":"Daily Digest","allowedSenders":["news@example.com"]}'
|
||||||
```
|
```
|
||||||
|
|
||||||
## Configuration notes
|
## Installation
|
||||||
|
|
||||||
- `wrangler-example.toml` is the template; `wrangler.toml` is generated locally.
|
See **[INSTALL.md](INSTALL.md)** for the full setup, deployment, and configuration guide. Quick start:
|
||||||
- Keep `compatibility_date` fresh when doing runtime upgrades.
|
|
||||||
- `ADMIN_PASSWORD` is a Cloudflare Worker secret, not a plain env var in config.
|
|
||||||
|
|
||||||
### Feed size limit
|
```bash
|
||||||
|
npx wrangler login
|
||||||
By default the worker keeps emails until the feed's stored data exceeds **512 KB**, then drops the oldest entries (and their KV records) to stay under the limit. This is more robust than a fixed entry count for HTML-heavy newsletters.
|
bash setup.sh # prompts for admin password + domain, provisions KV, generates wrangler.toml
|
||||||
|
npm run deploy # deploys the Worker and registers your custom domain
|
||||||
To override the threshold, add to `wrangler.toml` under `[vars]`:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
FEED_MAX_SIZE_BYTES = "524288" # 512 KB — adjust as needed
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Email attachments (R2)
|
Then enable email ingestion (Cloudflare Email Workers or ForwardEmail) and open `https://yourdomain.com/admin`. Details, options, and configuration knobs (feed size limit, R2 attachments, reverse-proxy auth, CI deploys) are all in [INSTALL.md](INSTALL.md).
|
||||||
|
|
||||||
When an incoming email contains attachments, the Worker can store them in a Cloudflare R2 bucket and expose them as `<enclosure>` elements in the RSS feed (and `<link rel="enclosure">` in Atom). Each attachment is served at `/files/{id}/{filename}` with an immutable cache header.
|
|
||||||
|
|
||||||
This feature is **optional**. If no R2 bucket is bound, attachments are silently ignored and nothing else changes.
|
|
||||||
|
|
||||||
**Setup:**
|
|
||||||
|
|
||||||
1. Create an R2 bucket in the Cloudflare dashboard (_R2 Object Storage → Create bucket_), or with Wrangler:
|
|
||||||
```bash
|
|
||||||
npx wrangler r2 bucket create your-bucket-name
|
|
||||||
```
|
|
||||||
2. In `wrangler.toml`, uncomment and fill in the R2 binding (the commented block from `wrangler-example.toml`):
|
|
||||||
```toml
|
|
||||||
r2_buckets = [
|
|
||||||
{ binding = "ATTACHMENT_BUCKET", bucket_name = "your-bucket-name", preview_bucket_name = "your-bucket-name-preview" }
|
|
||||||
]
|
|
||||||
```
|
|
||||||
Do the same under `[env.production]` (without `preview_bucket_name`).
|
|
||||||
3. Redeploy:
|
|
||||||
```bash
|
|
||||||
npm run deploy
|
|
||||||
```
|
|
||||||
|
|
||||||
Attachments are deleted from R2 automatically when the corresponding email is deleted from the admin UI, or when an email is dropped during feed size trimming.
|
|
||||||
|
|
||||||
### External auth provider (Authelia / Authentik / reverse proxy)
|
|
||||||
|
|
||||||
Instead of the built-in password login you can delegate admin authentication to a reverse proxy that sets a trusted user header (`Remote-User` or `X-Forwarded-User`).
|
|
||||||
|
|
||||||
**Required Worker secrets** (set with `wrangler secret put`, never in `[vars]`):
|
|
||||||
|
|
||||||
| Secret | Description |
|
|
||||||
| ------------------- | ---------------------------------------------- |
|
|
||||||
| `PROXY_AUTH_SECRET` | Shared secret between the proxy and the Worker |
|
|
||||||
|
|
||||||
**Required `[vars]`** in `wrangler.toml`:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
PROXY_TRUSTED_IPS = "10.0.0.1" # comma-separated IPs of your reverse proxy
|
|
||||||
```
|
|
||||||
|
|
||||||
When both are configured, the Worker authenticates a request if:
|
|
||||||
|
|
||||||
1. `CF-Connecting-IP` is in `PROXY_TRUSTED_IPS`
|
|
||||||
2. The `X-Auth-Proxy-Secret` header matches `PROXY_AUTH_SECRET`
|
|
||||||
3. `Remote-User` or `X-Forwarded-User` is non-empty
|
|
||||||
|
|
||||||
Password login remains available as a fallback when the proxy check fails.
|
|
||||||
|
|
||||||
> **Security note:** `CF-Connecting-IP` can be spoofed on direct `workers.dev` requests. Disable the `workers.dev` subdomain in production (`workers_dev = false` in `[env.production]`).
|
|
||||||
|
|
||||||
## Security notes
|
## Security notes
|
||||||
|
|
||||||
- When using Option B (ForwardEmail), inbound webhook access is IP-restricted to ForwardEmail MX sources.
|
- When using Option B (ForwardEmail), inbound webhook access is IP-restricted to ForwardEmail MX sources.
|
||||||
- Admin auth uses a signed, `HttpOnly`, `Secure`, `SameSite=Strict` cookie.
|
- Admin auth uses a signed, `HttpOnly`, `Secure`, `SameSite=Strict` cookie.
|
||||||
- Admin responses are `no-store` to avoid cache leakage.
|
- Admin responses are `no-store` to avoid cache leakage.
|
||||||
|
- Feed, entry, and attachment responses send `X-Robots-Tag: noindex`, and `/robots.txt` disallows `/rss`, `/atom`, `/entries`, `/files`, and `/admin`, so private feeds and emails are kept out of search engines.
|
||||||
- For high-value feeds, set `Allowed senders` so only known sender addresses/domains are accepted.
|
- For high-value feeds, set `Allowed senders` so only known sender addresses/domains are accepted.
|
||||||
- You should use a strong admin password and rotate periodically.
|
- You should use a strong admin password and rotate periodically.
|
||||||
- All secret comparisons (admin password, proxy secret) use constant-time comparison to prevent timing attacks.
|
- All secret comparisons (admin password, proxy secret) use constant-time comparison to prevent timing attacks.
|
||||||
|
|
||||||
## Upgrading dependencies
|
|
||||||
|
|
||||||
To refresh dependencies to latest:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npm outdated
|
|
||||||
npm install
|
|
||||||
npm test
|
|
||||||
npm run build
|
|
||||||
```
|
|
||||||
|
|
||||||
Then update `compatibility_date` and redeploy.
|
|
||||||
|
|
||||||
## Acknowledgements
|
## Acknowledgements
|
||||||
|
|
||||||
- [kill-the-newsletter](https://github.com/leafac/kill-the-newsletter) by Leandro Facchinetti — the inspiration for this project and the reference implementation for feature ideas (Atom feeds, attachment enclosures, entry HTML views, and more).
|
- [kill-the-newsletter](https://github.com/leafac/kill-the-newsletter) by Leandro Facchinetti — the inspiration for this project and the reference implementation for feature ideas (Atom feeds, attachment enclosures, entry HTML views, and more).
|
||||||
|
|||||||
+61
@@ -0,0 +1,61 @@
|
|||||||
|
# Security Policy
|
||||||
|
|
||||||
|
## Supported versions
|
||||||
|
|
||||||
|
kill-the-news is a self-hosted, single-Worker application. Only the latest
|
||||||
|
release on the `main` branch receives security fixes. If you run a fork or an
|
||||||
|
older deployment, update to the latest `main` before reporting an issue.
|
||||||
|
|
||||||
|
## Reporting a vulnerability
|
||||||
|
|
||||||
|
**Please do not open a public GitHub issue for security problems.**
|
||||||
|
|
||||||
|
Report privately through one of:
|
||||||
|
|
||||||
|
- [GitHub Security Advisories](https://github.com/juherr/kill-the-news/security/advisories/new) (preferred)
|
||||||
|
- Email: me@juherr.dev
|
||||||
|
|
||||||
|
Please include:
|
||||||
|
|
||||||
|
- A description of the issue and its impact
|
||||||
|
- Steps to reproduce (proof-of-concept if possible)
|
||||||
|
- Affected route, file, or configuration
|
||||||
|
- Any suggested remediation
|
||||||
|
|
||||||
|
You can expect an acknowledgement within a few days. Since this is a
|
||||||
|
volunteer-maintained project, fix timelines depend on severity and
|
||||||
|
availability, but credible reports are taken seriously. Coordinated disclosure
|
||||||
|
is appreciated — please give a reasonable window for a fix before going public.
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
Because this Worker ingests email and exposes feeds, the security-sensitive
|
||||||
|
surface includes:
|
||||||
|
|
||||||
|
- **Admin authentication** — password handling, the signed session cookie, and
|
||||||
|
constant-time secret comparison (`ADMIN_PASSWORD`, `PROXY_AUTH_SECRET`).
|
||||||
|
- **Inbound ingestion** — the ForwardEmail webhook (`POST /api/inbound`),
|
||||||
|
IP allowlisting, and the Cloudflare Email Workers handler.
|
||||||
|
- **Email rendering** — HTML sanitization for stored emails and feed output
|
||||||
|
(XSS via `entries/`, `rss/`, `atom/`, inline `cid:` images).
|
||||||
|
- **Public endpoints** — `GET /`, `GET /api/stats`, `GET /rss/:feedId`,
|
||||||
|
`GET /atom/:feedId`, `GET /files/:attachmentId/:filename`,
|
||||||
|
`GET /favicon/:feedId`.
|
||||||
|
|
||||||
|
### Out of scope
|
||||||
|
|
||||||
|
- Vulnerabilities in Cloudflare, ForwardEmail, or other third-party
|
||||||
|
infrastructure (report those to the respective vendor).
|
||||||
|
- Misconfiguration of a self-hosted deployment (e.g. a weak `ADMIN_PASSWORD`,
|
||||||
|
an exposed `workers.dev` subdomain, or committing secrets). See the security
|
||||||
|
notes in [README.md](README.md) and [INSTALL.md](INSTALL.md).
|
||||||
|
- Denial of service from sending large volumes of email.
|
||||||
|
|
||||||
|
## Hardening reminders for operators
|
||||||
|
|
||||||
|
- Use a strong, unique `ADMIN_PASSWORD` and rotate it periodically.
|
||||||
|
- Set `ADMIN_PASSWORD` via `wrangler secret put` — never in config files.
|
||||||
|
- Disable the `workers.dev` subdomain in production (`workers_dev = false`),
|
||||||
|
since `CF-Connecting-IP` can be spoofed on direct `workers.dev` requests.
|
||||||
|
- Set per-feed `Allowed senders` for high-value feeds.
|
||||||
|
- Never commit `wrangler.toml` or `.dev.vars` (both are gitignored).
|
||||||
@@ -2,28 +2,251 @@
|
|||||||
|
|
||||||
Feature gaps identified by comparing with [kill-the-newsletter](https://github.com/leafac/kill-the-newsletter).
|
Feature gaps identified by comparing with [kill-the-newsletter](https://github.com/leafac/kill-the-newsletter).
|
||||||
|
|
||||||
|
> **Origin tags.** Every idea carries an `_origin:_` reference so we can notify the source when it ships.
|
||||||
|
>
|
||||||
|
> - `ktn#N` → a [kill-the-newsletter issue/PR](https://github.com/leafac/kill-the-newsletter/issues) — **comment there when implemented** to close the loop with the requester.
|
||||||
|
> - A tool/spec URL → external inspiration (a competitor or standard); no individual to notify, but the rationale is traceable.
|
||||||
|
> - `internal` → our own design/code audit; no external requester.
|
||||||
|
|
||||||
|
> **Priority × size.** Each idea is tagged `Pn·Size`. Priority by user value: **P1** (high) / **P2** (medium) / **P3** (nice-to-have). Effort by implementation size: **S** (hours) / **M** (~1–2 days) / **L** (several days) / **XL** (week+). Done items keep the tag as a retrospective estimate.
|
||||||
|
|
||||||
## Quick wins
|
## Quick wins
|
||||||
|
|
||||||
- [x] **Author field in RSS entries** — expose the `from` address as `<author>` in each RSS `<item>`. The value is already stored in KV, just not rendered in the feed XML.
|
- [x] `P1·S` **Author field in RSS entries** — expose the `from` address as `<author>` in each RSS `<item>`. The value is already stored in KV, just not rendered in the feed XML. — _origin: [ktn#102](https://github.com/leafac/kill-the-newsletter/issues/102) (ktn CHANGELOG 2.0.6 "author to entry")_
|
||||||
|
|
||||||
- [x] **HTML view for individual entries** — serve each email as an HTML page at e.g. `/entries/:feedId/:timestamp`. Useful for reading emails outside a feed reader and for debugging. kill-the-newsletter serves these at `/feeds/{feedId}/entries/{entryId}.html` with a Content-Security-Policy header.
|
- [x] `P1·M` **HTML view for individual entries** — serve each email as an HTML page at e.g. `/entries/:feedId/:timestamp`. Useful for reading emails outside a feed reader and for debugging. kill-the-newsletter serves these at `/feeds/{feedId}/entries/{entryId}.html` with a Content-Security-Policy header. — _origin: upstream alternate-HTML view; gives each item a valid URL ([ktn#17](https://github.com/leafac/kill-the-newsletter/issues/17), [ktn#40](https://github.com/leafac/kill-the-newsletter/issues/40))_
|
||||||
|
|
||||||
- [x] **JSON API for feed creation** — accept `Content-Type: application/json` on `POST /admin/feeds` and return `{ feedId, email, feedUrl }`. Useful for automation (e.g. Tofu/OpenTofu provisioning).
|
- [x] `P2·S` **JSON API for feed creation** — accept `Content-Type: application/json` on `POST /admin/feeds` and return `{ feedId, email, feedUrl }`. Useful for automation (e.g. Tofu/OpenTofu provisioning). — _origin: [ktn#43](https://github.com/leafac/kill-the-newsletter/issues/43) (ktn CHANGELOG 2.0.5)_
|
||||||
|
|
||||||
|
- [x] `P2·S` **Project favicon** — serve a single bundled icon at `/favicon.ico` and add a `<link rel="icon">` in the shared `Layout` so the admin UI, status page, and entry views stop 404-ing. Doubles as the default/fallback icon for the per-feed favicon feature below. — _origin: internal (404 fix); related [ktn#131](https://github.com/leafac/kill-the-newsletter/issues/131)_
|
||||||
|
|
||||||
## Medium effort
|
## Medium effort
|
||||||
|
|
||||||
- [x] **Size-based feed trimming** — instead of a fixed 50-entry cap, drop the oldest entries when the feed exceeds a size threshold (kill-the-newsletter uses ~512 KB). More robust for HTML-heavy newsletters where one entry can dominate.
|
- [x] `P2·M` **Size-based feed trimming** — instead of a fixed 50-entry cap, drop the oldest entries when the feed exceeds a size threshold (kill-the-newsletter uses ~512 KB). More robust for HTML-heavy newsletters where one entry can dominate. — _origin: upstream size limit (ktn CHANGELOG 2.0.8); related [ktn#59](https://github.com/leafac/kill-the-newsletter/issues/59), [ktn#115](https://github.com/leafac/kill-the-newsletter/issues/115)_
|
||||||
|
|
||||||
- [x] **Atom feed format** — expose feeds as Atom (`application/atom+xml`) in addition to or instead of RSS 2.0. Atom has better native support for HTML content and author metadata.
|
- [x] `P1·M` **Atom feed format** — expose feeds as Atom (`application/atom+xml`) in addition to or instead of RSS 2.0. Atom has better native support for HTML content and author metadata. — _origin: upstream (Atom-native product) / internal parity_
|
||||||
|
|
||||||
- [x] **Authelia / external auth provider support** — allow delegating admin authentication to an external identity provider (e.g. Authelia, Authentik) via a trusted header (`Remote-User`, `X-Forwarded-User`) set by a reverse proxy. The Worker would accept the header as proof of authentication instead of checking the cookie, with a configurable secret or IP allowlist to trust only the proxy.
|
- [x] `P3·M` **Authelia / external auth provider support** — allow delegating admin authentication to an external identity provider (e.g. Authelia, Authentik) via a trusted header (`Remote-User`, `X-Forwarded-User`) set by a reverse proxy. The Worker would accept the header as proof of authentication instead of checking the cookie, with a configurable secret or IP allowlist to trust only the proxy. — _origin: internal_
|
||||||
|
|
||||||
|
- [x] `P2·M` **Per-feed favicon from the last sender's domain** — give each feed an icon by fetching the favicon of the last sender's domain, so feeds are visually distinguishable in readers and the admin UI. Resolve the domain from the most recent email's `from`, fetch its favicon (e.g. `https://<domain>/favicon.ico` or a parsed `<link rel="icon">`, with a fallback service), and cache the result aggressively (KV/R2 + Cache API with a long TTL) so it isn't re-fetched on every request. Expose it via the RSS `<image>` / Atom `<icon>` and the admin feed list. — _origin: [ktn#92](https://github.com/leafac/kill-the-newsletter/issues/92) (ktn CHANGELOG 2.0.6/2.0.7)_
|
||||||
|
|
||||||
|
- [x] `P2·M` **RFC 8058 one-click unsubscribe on feed deletion** — when a feed is deleted, automatically unsubscribe from the newsletters that fed it so messages stop arriving at the now-dead address. Parse and store the `List-Unsubscribe` / `List-Unsubscribe-Post` headers ([RFC 8058](https://www.rfc-editor.org/rfc/rfc8058.txt)) from incoming emails, then on deletion POST `List-Unsubscribe=One-Click` to each stored unsubscribe URL. Requires capturing the headers during ingestion (`src/lib/email-processor.ts`) and firing the outbound requests from the feed-delete paths (`src/routes/admin/feeds.tsx`), ideally via `ctx.waitUntil`. — _origin: internal ([RFC 8058](https://www.rfc-editor.org/rfc/rfc8058.txt))_
|
||||||
|
|
||||||
## Heavy
|
## Heavy
|
||||||
|
|
||||||
- [x] **Email attachments as RSS enclosures** — store attachments in Cloudflare R2 and expose them as `<enclosure>` elements in the feed. kill-the-newsletter serves them at `/files/{enclosureId}/{filename}`.
|
- [x] `P1·L` **Email attachments as RSS enclosures** — store attachments in Cloudflare R2 and expose them as `<enclosure>` elements in the feed. kill-the-newsletter serves them at `/files/{enclosureId}/{filename}`. — _origin: [ktn#66](https://github.com/leafac/kill-the-newsletter/issues/66), [ktn#86](https://github.com/leafac/kill-the-newsletter/issues/86) (ktn CHANGELOG 2.0.5)_
|
||||||
|
|
||||||
- [x] **WebSub (PubSubHubbub) push notifications** — notify subscribers in real time when a new email arrives, instead of requiring them to poll the feed. Requires either integrating a public WebSub hub or implementing the hub protocol directly.
|
- [x] `P2·L` **WebSub (PubSubHubbub) push notifications** — notify subscribers in real time when a new email arrives, instead of requiring them to poll the feed. Requires either integrating a public WebSub hub or implementing the hub protocol directly. — _origin: [ktn#68](https://github.com/leafac/kill-the-newsletter/issues/68) (ktn CHANGELOG 2.0.4)_
|
||||||
|
|
||||||
- [x] **Rate limiting via Cloudflare WAF rules** — protect `/api/inbound` and `/admin` against abuse. Configure WAF custom rules in the Cloudflare dashboard (or via Terraform): rate-limit `/api/inbound` to ~60 req/min per IP, and `/admin` to ~20 req/min per IP. No code changes required; this is pure infrastructure configuration.
|
- [x] `P2·S` **Rate limiting via Cloudflare WAF rules** — protect `/api/inbound` and `/admin` against abuse. Configure WAF custom rules in the Cloudflare dashboard (or via Terraform): rate-limit `/api/inbound` to ~60 req/min per IP, and `/admin` to ~20 req/min per IP. No code changes required; this is pure infrastructure configuration. — _origin: upstream parity (ktn CHANGELOG 2.0.3) / internal_
|
||||||
|
|
||||||
- [ ] **Migrate feed metadata to Durable Objects for atomic writes** — the current KV-based metadata store has a read-modify-write race condition: two concurrent emails to the same feed can silently overwrite each other's changes. Cloudflare Durable Objects serialise access per feed and eliminate the race entirely. Requires replacing `feed:<feedId>:metadata` KV writes in `src/lib/email-processor.ts` with a Durable Object that exposes an `appendEmail()` RPC, updating `wrangler.toml` with a DO binding, and migrating existing metadata at deploy time.
|
- [x] `P2·L` **REST API with OpenAPI description** — expose a documented, machine-consumable REST API for feed/email management (create/list/update/delete feeds, list/read/delete emails, read stats) so the service can be automated without scraping the admin UI. Implemented as a versioned `/api/v1/*` surface (Bearer-token auth with the admin password, plus the existing proxy-auth) built on `@hono/zod-openapi`; the OpenAPI 3.1 spec is served at `/api/openapi.json` with a Scalar docs page at `/api/docs`. Feed create/update/delete logic was extracted into `src/lib/feed-service.ts` so the admin UI and the REST API share a single source of truth. — _origin: [ktn#43](https://github.com/leafac/kill-the-newsletter/issues/43)_
|
||||||
|
|
||||||
|
- [ ] `P3·XL` **Migrate feed metadata to Durable Objects for atomic writes** — the current KV-based metadata store has a read-modify-write race condition: two concurrent emails to the same feed can silently overwrite each other's changes. Cloudflare Durable Objects serialise access per feed and eliminate the race entirely. Requires replacing `feed:<feedId>:metadata` KV writes in `src/lib/email-processor.ts` with a Durable Object that exposes an `appendEmail()` RPC, updating `wrangler.toml` with a DO binding, and migrating existing metadata at deploy time. — _origin: internal; same race behind [ktn#6](https://github.com/leafac/kill-the-newsletter/issues/6), [ktn#31](https://github.com/leafac/kill-the-newsletter/issues/31)_
|
||||||
|
|
||||||
|
## From upstream issues/PRs (2026-05-24 review)
|
||||||
|
|
||||||
|
Gaps found by reading every open/closed issue + PR on [kill-the-newsletter](https://github.com/leafac/kill-the-newsletter/issues). These are requests we do **not** yet satisfy (many other recurring requests — dark mode, copy buttons, favicon, expiration, attachments, API, WebSub, sender-in-author — we already cover).
|
||||||
|
|
||||||
|
- [x] `P1·M` **Subscription confirmation handling** — _the single most recurring upstream request_ ([#5](https://github.com/leafac/kill-the-newsletter/issues/5), [#23](https://github.com/leafac/kill-the-newsletter/issues/23), [#57](https://github.com/leafac/kill-the-newsletter/issues/57), [#73](https://github.com/leafac/kill-the-newsletter/issues/73), [#89](https://github.com/leafac/kill-the-newsletter/issues/89), [#95](https://github.com/leafac/kill-the-newsletter/issues/95), [#97](https://github.com/leafac/kill-the-newsletter/issues/97)). Newsletters require a "click to confirm your email" step; users can't easily find/click the link buried in a feed reader. Our admin already lists emails, but nothing **surfaces** the confirmation link or shows the first email inline right after feed creation. Low effort, high payoff (admin UX in `src/routes/admin/feeds.tsx` + maybe extract candidate confirm links during ingestion in `src/application/email-processor.ts`). — **Shipped:** v1 detects confirmation emails at ingestion (multilingual keyword + link scoring) and surfaces the link in the admin (detail section, list badge, dashboard pill, emails-page banner + dismiss); post-create now lands on the feed's emails page. v1 does no outbound request; server on-detect actions deferred (see below).
|
||||||
|
|
||||||
|
- [ ] `P2·M` **Confirmation on-detect server action (none / autoclick / forward)** — extend the shipped confirmation detection with a server-configured action via an env var (default `none`): `autoclick` = follow the detected confirm link server-side from the worker (⚠ guard SSRF: http(s) only, block internal/private IP ranges, timeout, no redirect to non-http schemes); `forward` = forward the original email to `FALLBACK_FORWARD_ADDRESS`. Touches `src/application/email-processor.ts`, `Env` (`src/types/index.ts`), `src/infrastructure/cloudflare-email.ts`. — _origin: internal (juherr)_
|
||||||
|
|
||||||
|
- [x] `P1·M` **Separate write (email) / read (feed) IDs** — _most-requested privacy gap, still open upstream_ ([#114](https://github.com/leafac/kill-the-newsletter/issues/114), [#93](https://github.com/leafac/kill-the-newsletter/issues/93), [#75](https://github.com/leafac/kill-the-newsletter/issues/75)). The two identities are now decoupled: `FeedId` is an **opaque random token** (`FeedId.generate()` → 22-char base64url) used as the KV storage key and the public read id (`/rss/:feedId`), while the inbound address is a separate `MailboxId` VO (`noun.noun.NN`, the old format) resolved to its feed **only at reception** via a new `inbound:<mailboxId>` secondary index (`src/infrastructure/feed-repository.ts` `resolveInbound`). `MailboxId.parse` owns the untrusted-input boundary (moved off `FeedId`); the mailbox lives on `FeedState.mailboxId` / `mailbox_id` and is projected into `feeds:list`. Reading `/rss/<noun.noun.NN>` 404s and no public feed output contains the inbound address. Pre-release, so no migration/backward-compat. — _origin: [ktn#114](https://github.com/leafac/kill-the-newsletter/issues/114), [ktn#93](https://github.com/leafac/kill-the-newsletter/issues/93), [ktn#75](https://github.com/leafac/kill-the-newsletter/issues/75)_
|
||||||
|
|
||||||
|
- [ ] `P2·S` **Rotate the inbound mailbox and/or feed id** — _follow-up to the write/read separation above_. Now that the inbound address (`MailboxId`) and the read id (`FeedId`) are decoupled, offer an admin + REST action to **re-mint** either one to revoke a leaked subscribe address or a shared feed URL. Rotating the mailbox: generate a new `MailboxId`, write the new `inbound:<new>` index, delete the old; rotating the read id is heavier (it's the KV storage key — would require re-keying `feed:<id>:*`, so prefer rotating only the mailbox first). Touch `feed-service.ts`, `feed-repository.ts`, admin UI, `api/index.ts`. — _origin: internal (privacy)_
|
||||||
|
|
||||||
|
- [ ] `P2·M` **Proxy/prefetch remote images** ([#69](https://github.com/leafac/kill-the-newsletter/issues/69)). We already proxy inline `cid:` images via R2, but remote `<img src="https://…">` stay remote → tracking pixels fire on read. Extend `src/infrastructure/html-processor.ts` to rewrite remote image src through a worker proxy/cache endpoint (reuse the R2 + Cache API pattern from favicons).
|
||||||
|
|
||||||
|
- [ ] `P3·M` **Tracking-link redirect resolver** ([#36](https://github.com/leafac/kill-the-newsletter/issues/36)). Unwrap marketing/tracking URLs (e.g. `click.convertkit-mail…`) to their final destination so the redirect/tracking happens server-side (or is stripped) instead of from the reader. Lives in `src/infrastructure/html-processor.ts`. Mind SSRF/abuse surface when following redirects.
|
||||||
|
|
||||||
|
- [ ] `P2·S` **Strip-styles / plaintext rendering option** ([#74](https://github.com/leafac/kill-the-newsletter/issues/74), [#119](https://github.com/leafac/kill-the-newsletter/issues/119)). Some readers render newsletter HTML/CSS poorly. Offer an opt-in to strip `<style>` + inline styles (keeping links), or to prefer the `text/plain` part. Per-feed setting + `src/infrastructure/html-processor.ts`.
|
||||||
|
|
||||||
|
- [x] `P2·S` **Optional sender in entry title** ([#123 — open PR upstream](https://github.com/leafac/kill-the-newsletter/pull/123), [#124](https://github.com/leafac/kill-the-newsletter/issues/124)). We already emit `<author>`, but some users want `[Sender] Subject` as the entry title for at-a-glance scanning in the reader. Per-feed toggle + `src/infrastructure/feed-generator.ts`. — **Shipped:** per-feed `senderInTitle` flag (domain `FeedState.senderInTitle` ↔ `FeedConfig.sender_in_title`); when set, `buildFeed` prefixes each entry title with `[Sender]` (display name, falling back to the email address). Toggle exposed as an admin edit-form checkbox and on the REST API (`FeedCreate`/`FeedUpdate`/`Feed` schemas).
|
||||||
|
|
||||||
|
- [x] `P2·S` **Detect a newsletter's native Atom/RSS feed** — _top item on upstream's own [TODO](https://github.com/leafac/kill-the-newsletter/blob/main/TODO.md), not yet built there_. When an incoming email's HTML contains `<link rel="alternate" type="application/atom+xml">` (or `application/rss+xml`), surface it: "this newsletter already publishes a feed — subscribe to it directly instead." We already parse HTML with linkedom in `src/infrastructure/html-processor.ts`, so detection is cheap; store the discovered URL on the feed and show it in the admin UI / a feed entry. A genuine differentiator — we'd ship it before upstream. — **Shipped:** per-sender detection of `<link rel="alternate">` (Atom, RSS, JSON Feed) in incoming email HTML at ingestion (`src/domain/native-feed.ts` pure detector, wired in `src/application/email-processor.ts`); discovered feeds stored as `nativeFeeds: Record<string, NativeFeed[]>` on the feed metadata; admin detail page shows a "Native feeds" copyable chip group per sender, feed dashboard shows a `pill-native` ("Native feed available") pill, and a dismissable banner on the emails page prompts subscribing at the source (`nativeFeedDismissed` flag); read-only `nativeFeeds: [{ url, type }]` array on the REST `FeedSchema` (`GET`/`POST`/`PATCH /api/v1/feeds`); no change to public RSS/Atom/JSON feed output.
|
||||||
|
|
||||||
|
- [x] `P1·S` **`X-Robots-Tag: none` on feed + entry routes** ([#33](https://github.com/leafac/kill-the-newsletter/issues/33)). Private feeds/emails should never be search-indexed. Upstream sets `X-Robots-Tag: none` on its responses; we set a CSP on `/entries` but **no** robots header anywhere. Add `X-Robots-Tag: noindex` to `rss.ts`, `atom.ts`, `entries.ts`, `files.ts` (and optionally a `/robots.txt`). Low effort, real privacy gap.
|
||||||
|
|
||||||
|
## From similar projects & RSS readers (2026-05-24 review)
|
||||||
|
|
||||||
|
Ideas from competitors (Feedbin, Readwise Reader, Inoreader, Omnivore, LetterFeed, Mailbrew, mail2rss) and from what leading readers (NetNewsWire, Reeder, Feedly, Inoreader, NewsBlur, Miniflux, FreshRSS) can consume. Deduplicated against the upstream-issues section above. Tagged **[table-stakes]** vs **[differentiating]**.
|
||||||
|
|
||||||
|
### Feed-output enrichments (small XML wins — we use the `feed` lib, which already emits `content:encoded`, `atom:link rel="self"`, stable `<guid>`)
|
||||||
|
|
||||||
|
- [x] `P2·S` **JSON Feed endpoint** `GET /json/:feedId` **[differentiating, cheap]** — the `feed` lib's `.json1()` (emits JSON Feed v1) wired via `generateJsonFeed` in `src/infrastructure/feed-generator.ts`, served at `/json/:feedId` (`src/routes/json.ts`) with `Content-Type: application/feed+json` + WebSub hub `Link`. All three formats cross-link via `feedLinks`. Natively consumed by NetNewsWire, Reeder, NewsBlur, Feedly. — _origin: [JSON Feed 1.1 spec](https://www.jsonfeed.org/version/1.1/) (reader ecosystem)_
|
||||||
|
|
||||||
|
- [ ] `P3·S` **Upgrade JSON Feed output to v1.1** **[correctness, niche]** — our `/json/:feedId` emits `version: "https://jsonfeed.org/version/1"` because the `feed` lib's `.json1()` only implements v1, and the upstream request to bump it was **closed as _not planned_** ([jpmonette/feed#139](https://github.com/jpmonette/feed/issues/139)). So a true v1.1 feed needs a small post-process pass on the `.json1()` object in `generateJsonFeed` (`src/infrastructure/feed-generator.ts`): set `version` to `https://jsonfeed.org/version/1.1`, and apply the [v1.1 changes](https://www.jsonfeed.org/version/1.1/#changes-a-name-changes-a) — promote the deprecated top-level/item `author` to `authors` (array), and add the top-level `language` field. Low value (every reader still parses v1) but cheap and removes a spec-compliance footnote. — _origin: [jpmonette/feed#139 (closed, not planned)](https://github.com/jpmonette/feed/issues/139); [JSON Feed 1.1 spec](https://www.jsonfeed.org/version/1.1/)_
|
||||||
|
|
||||||
|
- [ ] `P2·M` **Per-item `<category>` + per-feed tags/categories** **[differentiating]** — we set no categories today. Tag entries by sender (or a user-set feed category) so readers (Inoreader, Feedly, NewsBlur) can filter/mute subsets. Pairs with the filtering item below; touches `FeedState`, `feed-generator.ts`. — _origin: [RSS best practices (kevincox)](https://kevincox.ca/2022/05/06/rss-feed-best-practices/); Inoreader/Feedly filtering_
|
||||||
|
|
||||||
|
- [ ] `P3·S` **Reader cadence hints: `<ttl>` + `sy:updatePeriod`/`sy:updateFrequency`** **[table-stakes, niche]** — advertise the feed's real update rhythm so pollers (FreshRSS, Miniflux, Inoreader) back off; complements our WebSub push. Support is uneven, so keep it as a hint alongside WebSub. Also advertise the WebSub hub link _inside_ the XML (`<atom:link rel="hub">`), not only the HTTP `Link` header. — _origin: [FreshRSS TTL #6721](https://github.com/FreshRSS/FreshRSS/issues/6721)_
|
||||||
|
|
||||||
|
- [ ] `P2·M` **Media RSS lead image (`<media:content>`/`<media:thumbnail>`)** **[differentiating]** — extract the first image of each email as a thumbnail so card/story layouts (Feedly, Inoreader, NewsBlur) show a preview. The `feed` lib doesn't emit Media RSS, so this needs post-processing or a custom serializer. — _origin: [Media RSS spec](https://www.rssboard.org/media-rss); Feedly/Inoreader consume it_
|
||||||
|
|
||||||
|
### Ingestion & processing
|
||||||
|
|
||||||
|
- [ ] `P2·M` **Keyword/subject filtering rules (keep/drop)** **[differentiating]** — we already have _sender_ allow/block (`SenderPolicy`), but no content rules. Add per-feed keep/drop rules by subject or body keyword (Inoreader/Omnivore-style), applied in `src/application/email-processor.ts` at the same gate as the sender policy. — _origin: [Inoreader rules](https://www.inoreader.com/blog/2020/02/declutter-your-inbox-subscribe-to-email-newsletters-straight-into-inoreader.html); Omnivore filters_
|
||||||
|
|
||||||
|
- [ ] `P2·M` **Confirmation-code relay** **[differentiating]** — _extends the "Subscription confirmation handling" item above_. Readwise Reader auto-detects "reply with code X" / "click to confirm" emails and surfaces (or relays) the code. Beyond just showing the link: detect the confirm pattern and present a one-tap action in admin. — _origin: [Readwise Reader docs](https://docs.readwise.io/reader/docs/faqs/email-newsletters); also [ktn#89](https://github.com/leafac/kill-the-newsletter/issues/89) (reply-to-confirm)_
|
||||||
|
|
||||||
|
- [ ] `P3·XL` **IMAP-pull ingestion option** **[differentiating for self-hosters]** — alternative to the ForwardEmail/Cloudflare-Email webhook: poll an existing IMAP mailbox and route allow-listed senders to feeds (LetterFeed model). Big lift on a Worker (needs a scheduled fetch + IMAP over a TCP socket / external relay); evaluate feasibility before committing. — _origin: [LetterFeed](https://github.com/LeonMusCoden/LetterFeed); also [ktn#26](https://github.com/leafac/kill-the-newsletter/issues/26) (use IMAP instead of hosting a mail server)_
|
||||||
|
|
||||||
|
### Reading experience
|
||||||
|
|
||||||
|
- [x] `P2·S` **OPML export** `GET /admin/opml` **[table-stakes, easy]** — export all feeds as an OPML 2.0 outline (`<outline type="rss" xmlUrl=…>` per feed, XML-attr-escaped) so users can bulk-import every feed into their reader in one shot. Mounted on the admin Hono app (inherits the admin auth middleware) rather than public, because the registry lists every feed's RSS URL — a public endpoint would leak them all. Returns `Content-Disposition: attachment; filename="feeds.opml"`. Implemented in `src/routes/opml.ts` over `FeedRepository.listFeeds()`. — _origin: reader ecosystem ([NetNewsWire](https://github.com/Ranchero-Software/NetNewsWire/)); Feedbin OPML export_
|
||||||
|
|
||||||
|
- [ ] `P2·L` **Full-text search across received emails** **[differentiating]** — admin-side search over subjects + bodies (Omnivore/Feedbin have this). On KV this means an index or scan; consider scope (subject-only first) before building. — _origin: [Omnivore](https://www.timeatlas.com/omnivore-newsletters/); Feedbin search_
|
||||||
|
|
||||||
|
- [ ] `P3·L` **Readability / clean-text view toggle** **[differentiating]** — _related to "strip-styles" above but distinct_: run a readability extraction (article body only) as an opt-in per feed, remembered per sender (Readwise pattern), rather than just stripping CSS. — _origin: [Readwise Reader feed docs](https://docs.readwise.io/reader/docs/faqs/feed)_
|
||||||
|
|
||||||
|
### Greenfield differentiators
|
||||||
|
|
||||||
|
- [ ] `P2·L` **AI per-newsletter summarization** **[differentiating]** — generate a short TL;DR per email (or a daily digest summary) using Cloudflare Workers AI (no new vendor, no key to manage). Almost no competitor ships this well. Add an `AI` binding + an opt-in per-feed flag; render the summary atop the entry content. — _origin: [Precis](https://github.com/leozqin/precis), [babarot AI reader](https://dev.to/babarot/i-built-a-self-hosted-rss-reader-with-ai-summarization-translation-and-an-mcp-server-316c)_
|
||||||
|
|
||||||
|
- [ ] `P3·L` **Digest / bundling mode** **[differentiating]** — for low-volume feeds, batch N emails into a single periodic digest entry (Mailbrew model) so readers aren't flooded. Per-feed cadence setting; runs on the existing cron. — _origin: [Mailbrew](https://www.readless.app/blog/mailbrew-pricing-2026)_
|
||||||
|
|
||||||
|
## Robustness, delivery, auth & integrations (2026-05-24 deep dig)
|
||||||
|
|
||||||
|
Verified-missing in our code, deduplicated against the sections above. From a code audit + a sweep of niche/recent tools (Precis, changedetection.io+Apprise, MailCast email-to-podcast, FreshRSS/Miniflux token auth, RFC 5005, postly dedup).
|
||||||
|
|
||||||
|
### Delivery / bandwidth
|
||||||
|
|
||||||
|
- [x] `P2·S` **Conditional GET on feeds (ETag + Last-Modified + 304)** **[table-stakes, easy]** — `rss.ts`/`atom.ts` now emit a strong `ETag` (`"<format>-<feedId>-<count>-<maxReceivedAt>"`) and `Last-Modified` (newest `receivedAt`), and return `304 Not Modified` on matching `If-None-Match`/`If-Modified-Since` before generating any XML. Validators are computed from the loaded `FeedData` (not the rendered bytes) in `src/infrastructure/http-cache.ts` (`computeFeedValidators`/`isNotModified`/`notModifiedResponse`), shared by both routes; rss vs atom get distinct ETags via the format prefix. Cuts bandwidth for every polling reader. — _origin: internal code audit ([RFC 9110 conditional requests](https://www.rfc-editor.org/rfc/rfc9110#name-conditional-requests))_
|
||||||
|
|
||||||
|
- [ ] `P3·L` **RFC 5005 paged / archived feeds** **[differentiating, niche]** — readers only ever see the capped current window; older entries vanish. Mark the subscription document `fh:complete` and expose `prev-archive` pages so readers can backfill history. Pairs naturally with our expiring-feed model (an expired feed = a sealed archive). ([RFC 5005](https://www.rfc-editor.org/rfc/rfc5005.html))
|
||||||
|
|
||||||
|
### Ingestion robustness
|
||||||
|
|
||||||
|
- [x] `P1·M` **Duplicate-send dedup** **[differentiating]** — a newsletter resent (or delivered twice) is now stored once. `storeEmail` (`src/application/email-processor.ts`) computes the `Message-ID` (case-insensitive header lookup) and a SHA-256 of normalized `subject+content`, then asks the aggregate `feed.hasDuplicate(messageId, dedupHash)` (`src/domain/feed.aggregate.ts`): primary match on `Message-ID`, fallback to the content hash when neither side has a Message-ID. A duplicate is a successful no-op (`{ ok: true }`, nothing stored/dispatched) and bumps a new `emails_deduplicated` counter (status page + `/api/v1/stats`). `EmailMetadata` gained additive `messageId?`/`dedupHash?` fields, so pre-feature entries never false-match. Fixes the upstream "duplicate posts" complaint ([#31](https://github.com/leafac/kill-the-newsletter/issues/31), [#6](https://github.com/leafac/kill-the-newsletter/issues/6)).
|
||||||
|
|
||||||
|
- [ ] `P3·M` **Calendar (.ics) invite extraction** **[differentiating, novel]** — no email→feed tool does this. Detect `text/calendar` parts, parse the event, and surface it in the entry (summary + an `.ics` enclosure / add-to-calendar link). Useful for event/booking newsletters. — _origin: internal (novel; no external requester)_
|
||||||
|
|
||||||
|
- [x] `P2·S` **`FALLBACK_FORWARD_ADDRESS` — catch-all fallback forwarding** **[differentiating for self-hosters]** — today `handleCloudflareEmail` silently drops (just `logger.warn`) any address that isn't a feed, so you can't point a domain's _catch-all_ at KTN without swallowing your personal mail. Add an optional `FALLBACK_FORWARD_ADDRESS` env var: after `processEmail`, forward non-feed mail to it based on `result.reason` — **forward** on `invalid_address` (not a `noun.noun.NN` address) and `feed_not_found` (well-formed but no such feed); **drop** on `feed_expired` and `sender_blocked` (don't leak a newsletter to the fallback box); nothing on `ok`. Unset env → current drop+log behavior unchanged. The destination must be a _verified_ Cloudflare Email Routing address or `message.forward()` fails; `await` it in a `try/catch` (`logger.warn` on failure), forward at most once. Touch: `Env` (`src/types/index.ts`), `src/infrastructure/cloudflare-email.ts` (`result.reason` already available), `cloudflare-email.test.ts` (forwarded for `feed_not_found`/`invalid_address` when set; not for `feed_expired`/`sender_blocked`; not when unset), `wrangler-example.toml` (commented `# FALLBACK_FORWARD_ADDRESS` under `[vars]`), `INSTALL.md` ("Catch-all fallback forwarding" section: verified-destination prerequisite + use case). — _origin: internal (juherr — self-host on juherr.dev catch-all); generic "use KTN as my domain's catch-all"_
|
||||||
|
|
||||||
|
### Auth & privacy
|
||||||
|
|
||||||
|
- [ ] `P2·M` **Scoped / multiple API tokens (admin-managed)** **[security]** — the REST API currently accepts the single `ADMIN_PASSWORD` as the bearer (`src/infrastructure/auth.ts`). Add named, independently-revocable tokens (optionally read-only or feed-scoped) that the admin can **create, list, and revoke from the admin UI** (stored hashed in KV, shown once on creation), so automation doesn't hold the master password. The bearer middleware then accepts either `ADMIN_PASSWORD` or any active token; revoking a token is instant. — _origin: internal security audit; juherr (manage API tokens)_
|
||||||
|
|
||||||
|
- [ ] `P2·S` **Change the admin password from the UI** **[security]** — today `ADMIN_PASSWORD` is a Worker secret set via `wrangler secret put`, so rotating it means a redeploy. Add an admin-UI action (current password + new password) that stores a hashed password override in KV (e.g. `admin:password`); `src/infrastructure/auth.ts` checks the KV override first and falls back to the `ADMIN_PASSWORD` env secret when unset, so existing installs keep working and the env var becomes the bootstrap/reset default. Pairs with the API-tokens item (same auth surface). — _origin: internal; juherr (change admin password)_
|
||||||
|
|
||||||
|
- [ ] `P3·XL` **Multi-user support** **[differentiating]** — today the app is single-admin (one `ADMIN_PASSWORD` guards all feeds; `feeds:list` is global). Support multiple user accounts, each owning a private subset of feeds: per-user credentials/sessions, feed ownership on `FeedState`, per-user feed registry (scope `feeds:list` by owner), and admin scoping across the admin UI + REST API. Big lift — touches auth, the feed registry/key schema, and every admin/API route; depends on the change-password and API-token items as the auth foundation. ⚠ Note the off-Cloudflare epic currently lists "Multi-tenant / multi-domain admin" as out of scope — reconcile that scope boundary before committing. — _origin: internal; juherr (multi-user)_
|
||||||
|
|
||||||
|
- [ ] `P2·M` **Token-protected private feeds** **[security, differentiating]** — `/rss` and `/atom` are public-by-obscurity (anyone with the URL reads it). Offer an opt-in `?token=…` (FreshRSS-style) or HMAC-signed, optionally expiring URL (fits our expiring-feed model) so a feed can be truly private and shareable without leaking the inbound address. Complements the _separate write/read IDs_ item above. ([FreshRSS](https://freshrss.github.io/FreshRSS/en/admins/09_AccessControl.html))
|
||||||
|
|
||||||
|
### Push & integrations
|
||||||
|
|
||||||
|
- [ ] `P2·L` **Push new items to chat (per-feed)** **[differentiating]** — for users who don't run a reader, push each new email to Telegram / Discord / ntfy / a generic webhook, routed per feed, instant-vs-digest toggle (Precis / changedetection.io+Apprise pattern). Fires from the existing event dispatcher (`src/application/feed-events.ts`) via `ctx.waitUntil`. ([Precis](https://github.com/leozqin/precis))
|
||||||
|
|
||||||
|
### Novel / stretch (Cloudflare-native)
|
||||||
|
|
||||||
|
- [ ] `P3·M` **MCP server over your feeds** **[differentiating, novel]** — expose feeds/emails to AI agents via a Model Context Protocol endpoint on the Worker, so an assistant can read/search a user's newsletters. Cheap to add on a Worker, genuinely new in this space. — _origin: [babarot AI reader + MCP](https://dev.to/babarot/i-built-a-self-hosted-rss-reader-with-ai-summarization-translation-and-an-mcp-server-316c)_
|
||||||
|
|
||||||
|
- [ ] `P3·L` **Email-to-podcast (TTS audio enclosure)** **[differentiating, novel]** — opt-in: synthesize each newsletter to audio (Cloudflare Workers AI TTS), store in R2, attach as an `<enclosure>` so the feed doubles as a private podcast. Reframes feed item = audio. ([prior art](https://github.com/tcanfarotta/email-to-podcast-rss))
|
||||||
|
|
||||||
|
> Framing notes (no code, worth surfacing in docs/landing): we already deliver several things competitors charge for — **full-body capture bypasses Substack/"read more" truncation** (we ingest the email, not the scraped page), and each feed's inbound address is effectively a **burnable alias** (delete the feed + RFC 8058 one-click unsubscribe already kills the sender). Market these explicitly.
|
||||||
|
|
||||||
|
## Feed namespaces & reader-rendering correctness (2026-05-24 deep dig)
|
||||||
|
|
||||||
|
Two final angles: (1) less-common RSS/Atom namespaces that visibly improve feeds in real readers, and (2) generator-side correctness fixes that stop feeds breaking in self-hosted readers. The `feed` lib emits `content:encoded`/`atom:link rel=self`/stable `<guid>` but does **not** handle the items below — they need its custom-namespace/extension hooks or a post-process pass.
|
||||||
|
|
||||||
|
### Namespaces worth emitting
|
||||||
|
|
||||||
|
- [ ] `P2·S` **WebFeeds branding (`webfeeds:accentColor`, `webfeeds:icon`, `webfeeds:logo`, `webfeeds:cover`)** **[differentiating, high visible payoff]** — Feedly puts your SVG logo on every story and recolors links to your accent color. We already derive a per-feed favicon; add an accent + logo for branded-looking feeds. — _origin: [Working With Web Feeds (CSS-Tricks)](https://css-tricks.com/working-with-web-feeds-its-more-than-rss/)_
|
||||||
|
|
||||||
|
- [ ] `P2·M` **Media RSS thumbnail/credit (`media:thumbnail`, `media:description`, `media:credit`)** **[differentiating]** — richer than the lead-image item above: gives readers a card image, alt text, and attribution. — _origin: [Media RSS spec](https://www.rssboard.org/media-rss)_
|
||||||
|
|
||||||
|
- [ ] `P3·S` **Dublin Core `dc:creator`** **[niche, cheap]** — credits the newsletter sender **without** an email address (RSS `<author>` requires one); safer than a synthetic `noreply@`. — _origin: [RSS Best Practices Profile](https://www.rssboard.org/rss-profile), [mod_dublincore](https://www.oreilly.com/library/view/developing-feeds-with/0596008813/re08.html)_
|
||||||
|
|
||||||
|
- [ ] `P3·M` **Podcast namespace (`itunes:*` + `podcast:transcript`/`chapters`)** **[stretch]** — only if the email-to-podcast item ships; turns the audio feed into a real Podcasting 2.0 feed. — _origin: [Podcast Namespace](https://podcasting2.org/docs/podcast-namespace)_
|
||||||
|
|
||||||
|
### Reader-rendering correctness (turn these into hardening tasks)
|
||||||
|
|
||||||
|
- [x] `P1·S` **Rewrite relative URLs in content to absolute** **[correctness]** — most readers ignore `xml:base`; relative `src`/`href` in `content:encoded` break in Miniflux/NetNewsWire. Absolutize every link/image before emitting (`src/infrastructure/html-processor.ts`). — _origin: [W3C ContainsRelRef](https://validator.w3.org/feed/docs/warning/ContainsRelRef.html)_
|
||||||
|
|
||||||
|
- [x] `P1·S` **Promote lazy-loaded images (`data-src` → `src`, strip `loading="lazy"`)** **[correctness]** — newsletters with lazy images render blank in readers. — _origin: [Hugo RSS & lazy images](https://brainbaking.com/post/2021/01/hugo-rss-feeds-and-lazy-image-loading/)_
|
||||||
|
|
||||||
|
- [x] `P1·S` **Strip XML-illegal control chars + guarantee valid UTF-8** **[correctness]** — a single bad codepoint fails the _whole_ feed parse in strict readers (newsboat). Sanitize before serialization. — _origin: [newsboat #2328](https://github.com/newsboat/newsboat/issues/2328), [W3C SAXError](https://validator.w3.org/feed/docs/error/SAXError.html); upstream hit this too ([ktn#1](https://github.com/leafac/kill-the-newsletter/issues/1) cyrillic, [ktn#9](https://github.com/leafac/kill-the-newsletter/issues/9) invalid XML char)_
|
||||||
|
|
||||||
|
- [ ] `P2·S` **Real `enclosure` byte length + correct type (never `length="0"`)** **[correctness]** — zero/missing length makes podcast clients reject the enclosure; use the actual R2 object size. — _origin: [AzuraCast #7809](https://github.com/AzuraCast/AzuraCast/issues/7809)_
|
||||||
|
|
||||||
|
- [x] `P1·S` **Plain-text `<title>` (strip HTML, decode entities)** **[correctness]** — raw tags in titles show literally in readers; keep markup only in `content`. — _origin: [RSS.app feed output guide](https://help.rss.app/en/articles/10769849-guide-to-feed-output); upstream [ktn#11](https://github.com/leafac/kill-the-newsletter/issues/11) (subject placed as link)_
|
||||||
|
|
||||||
|
## Per-feed favicon — design notes
|
||||||
|
|
||||||
|
Breakdown of the _"Per-feed favicon from the last sender's domain"_ item above (the parent is `P2·M`; these sub-tasks are each ~`S`). Goal: each feed shows an icon derived from its newsletter source, fetched once and cached so it never re-fetches on a normal request.
|
||||||
|
|
||||||
|
- [x] `P2·S` **Resolve the sender domain** — on ingestion, extract the domain from the latest email's `from` address (`extractEmailDomain` in `src/utils/favicon-fetcher.ts`) and persist it as `iconDomain` on the feed metadata so the icon tracks the most recent sender.
|
||||||
|
|
||||||
|
- [x] `P2·S` **Fetch the favicon** — resolve an icon URL for the domain: try `https://<domain>/favicon.ico`, then fall back to `https://icons.duckduckgo.com/ip3/<domain>.ico`. Runs async via `ctx.waitUntil` so it never blocks email processing.
|
||||||
|
|
||||||
|
- [x] `P2·S` **Cache aggressively** — store the fetched bytes (base64) keyed by domain in KV with a 1-week TTL (`ICON_TTL_SECONDS`). The domain is the cache key so feeds from the same sender share one fetch; the fetch only fires when the cache entry is absent/expired.
|
||||||
|
|
||||||
|
- [x] `P2·S` **Serve endpoint** — `GET /favicon/:feedId` returns the cached bytes with the correct `Content-Type` and a long `Cache-Control`, falling back to the project favicon when no domain icon is found.
|
||||||
|
|
||||||
|
- [x] `P2·S` **Expose in outputs** — the icon is referenced from the RSS `<image>` and Atom `<icon>`/`<logo>` in `src/utils/feed-generator.ts`, and rendered next to each feed in the admin list/table (`src/routes/admin.tsx`).
|
||||||
|
|
||||||
|
- [x] `P2·S` **Failure handling** — missing/blocked favicons degrade gracefully to the project favicon fallback (negative cache entry); icon fetch errors never surface to ingestion or feed rendering.
|
||||||
|
|
||||||
|
## Operability, versioning & ecosystem (2026-05-24)
|
||||||
|
|
||||||
|
Self-host operational quality-of-life: knowing which version you run, when to update, and how many people run KTN.
|
||||||
|
|
||||||
|
- [x] `P3·S` **Display the running version** **[table-stakes, easy]** — surface the deployed app version (from `package.json` `version`, currently `0.2.1`) somewhere visible: the admin UI footer and/or the public status page (`src/routes/home.tsx`), and ideally the `/health` JSON. Bundle the version at build time (inline the `package.json` version into the Worker, since there's no filesystem at runtime) and render it. Foundation for the update-notification item below. — **Shipped:** `package.json` version is inlined at bundle time via `src/config/version.ts` (`import pkg from "../../package.json"`, `resolveJsonModule`), exposed as `APP_VERSION`; rendered in the shared admin/status footer (`src/routes/admin/ui.tsx` Layout, so both the status page and admin show it), added to the `/health` JSON, and to the canonical monitoring endpoint `/api/v1/stats` (`StatsResponse.version`, public). — _origin: internal_
|
||||||
|
|
||||||
|
- [ ] `P3·M` **Notify when an update is available** **[differentiating for self-hosters]** — compare the running version against the latest GitHub Release tag and show a discreet "update available → vX.Y.Z" banner in the admin UI when behind. Fetch `https://api.github.com/repos/<owner>/<repo>/releases/latest` (cache aggressively — Cache API / KV with a long TTL — to respect GitHub rate limits and avoid a call per page load), compare semver against the bundled version. Depends on the "display version" item. Keep it opt-out-able (it makes one outbound call). — _origin: internal_
|
||||||
|
|
||||||
|
- [ ] `P3·L` **Public instances directory and/or instance counter (opt-in telemetry)** **[differentiating, ecosystem]** — let a self-hosted instance optionally announce itself to a central registry so we can show a count of live instances (and, if the operator opts in to being listed, a public directory of instances). Each instance periodically pings a central endpoint (on the existing cron) with minimal, **opt-in** data (e.g. an anonymous instance id + version; a public listing would additionally need a name/URL the operator explicitly provides). ⚠ Privacy-first: **off by default**, clearly documented, no PII/feed data ever sent; respect "count me but don't list me". Needs a central collector (a separate tiny Worker + KV/DO) plus an `INSTANCE_TELEMETRY`/`INSTANCE_DIRECTORY` opt-in env on the client side, fired from `index.ts`'s `scheduled` handler. — _origin: internal_
|
||||||
|
|
||||||
|
## Epic: Pluggable runtime, storage & ingestion (off-Cloudflare support)
|
||||||
|
|
||||||
|
`P2·XL` **Run KTN off Cloudflare from one codebase, adapter-selected by config.** Reference non-CF target: **Clever Cloud** (container + Cellar S3 + a KV/SQL add-on) with **Sweego** inbound for email. — _origin: internal (broader audience / reduced lock-in)_
|
||||||
|
|
||||||
|
**Context / motivation.** KTN is Cloudflare-native: Workers runtime, KV + R2 bindings, Email Workers, cron triggers. The v0.2.0 DDD refactor already introduced the seams that make portability tractable — KV access is behind repository adapters (`FeedRepository`, `IconRepository`, `WebSubSubscriptionRepository`, `CountersRepository`), ingestion is transport-agnostic (`processEmail` is decoupled from the CF email handler, and a webhook path `/api/inbound` already exists), HTTP is Hono (runtime-agnostic), and background work is abstracted behind `BackgroundScheduler`. This epic turns those seams into selectable adapters so KTN can run on a plain Node/container host with non-CF storage and email ingestion.
|
||||||
|
|
||||||
|
**Goal / outcome.** KTN runs on two reference profiles from one codebase:
|
||||||
|
|
||||||
|
- **A — CF-native (today):** Workers + KV + R2 + Cloudflare Email Routing.
|
||||||
|
- **B — Clever+Sweego:** Node container + Cellar (S3 blob) + KV-store add-on + Sweego inbound webhook + Node scheduler.
|
||||||
|
|
||||||
|
Adapter chosen by config (env), no code change. Same test suite green on both.
|
||||||
|
|
||||||
|
**Coupling points → adapters.**
|
||||||
|
|
||||||
|
| Area | CF-native (today) | New adapter (target B) |
|
||||||
|
| ------------------ | ------------------------------------------------------ | -------------------------------------------------------------- |
|
||||||
|
| Runtime/entrypoint | `export default { fetch, email, scheduled }` | Node entrypoint (`@hono/node-server`) + Dockerfile |
|
||||||
|
| HTTP | Hono (portable) | Hono (no change; abstract CF-only globals) |
|
||||||
|
| KV store | `KVNamespace` binding | SQL (Postgres/SQLite) or Redis (Materia KV) adapter |
|
||||||
|
| Blob/attachments | `R2Bucket` binding | S3-compatible (Cellar) via aws4fetch/S3 client |
|
||||||
|
| Email ingestion | CF Email Worker (`ForwardableEmailMessage`) | Sweego inbound webhook → `/api/inbound` |
|
||||||
|
| Cron cleanup | CF cron trigger | Node scheduler (node-cron) or external trigger |
|
||||||
|
| Background | `ctx.waitUntil` (already behind `BackgroundScheduler`) | run-and-await Node impl |
|
||||||
|
| Config/DI | CF bindings on `Env` | driver-selection layer (`*_DRIVER` envs) wiring repos→backends |
|
||||||
|
|
||||||
|
**Sub-tasks (deliverable independently).**
|
||||||
|
|
||||||
|
- [ ] `P2·M` **Storage driver abstraction + config layer** — formalize the repository interfaces already implied by `FeedRepository` et al.; add a DI/config layer selecting backends from env. Foundation; no behavior change on CF. — _origin: internal_
|
||||||
|
- [ ] `P2·M` **Blob adapter: S3-compatible (Cellar)** — put attachments behind a `BlobStore` interface; CF R2 + S3 (aws4fetch, works on Workers and Node). Lowest risk, immediately reusable. — _origin: internal_
|
||||||
|
- [ ] `P2·L` **KV-store adapter for self-host** — implement the key schema over SQL (recommended: Postgres/SQLite for list-by-prefix semantics) and/or Redis. ⚠ If targeting Materia KV, confirm KTN never relies on `RENAME` (Materia lacks it — see consumer's ADR-0011); audit the single key schema. — _origin: internal_
|
||||||
|
- [ ] `P2·L` **Node runtime entrypoint + container** — `@hono/node-server`, Dockerfile, health endpoint; abstract CF-only globals (`caches`, reliance on `CF-Connecting-IP` in proxy-auth → generalize to `X-Forwarded-For`/trusted-proxy config). — _origin: internal_
|
||||||
|
- [ ] `P2·L` **Ingestion transport abstraction + Sweego adapter** — generalize `/api/inbound` to provider-agnostic: pluggable payload parser (Sweego JSON → `ProcessEmailInput`, mirroring `parseForwardEmailPayload`) + pluggable webhook auth (HMAC signature / shared secret / IP allowlist). Document that `message.forward()` fallback is CF-Email-Worker-only; on webhook transports, unmatched-mail handling is the provider's concern (Sweego catch-all is isolated to the inbound domain, so the fallback hack isn't needed). — _origin: internal_
|
||||||
|
- [ ] `P2·M` **Scheduler adapter** — make `feed-cleanup` runnable via a Node scheduler or an authenticated `/internal/cron` endpoint for external triggers. — _origin: internal_
|
||||||
|
- [ ] `P2·M` **CI matrix + docs** — build/test both targets; INSTALL.md Clever+Sweego profile; deployment guide. — _origin: internal_
|
||||||
|
|
||||||
|
**Open questions (resolve before the Sweego adapter sub-task).**
|
||||||
|
|
||||||
|
- Sweego inbound: webhook auth mechanism (HMAC? signed header? IP list?), JSON payload schema, and attachment delivery (inline base64 vs URLs vs multipart) — drives the parser + how attachments stream into the blob store.
|
||||||
|
- Clever KV backend choice: Materia KV (Redis, no `RENAME`) vs Postgres add-on — decide from the key-op audit in the KV-store sub-task.
|
||||||
|
|
||||||
|
**Out of scope.**
|
||||||
|
|
||||||
|
- Running KTN's own SMTP/MTA server (inbound stays delegated: CF Email Routing, Sweego, or ForwardEmail). No port-25 listener.
|
||||||
|
- Multi-tenant / multi-domain admin.
|
||||||
|
|
||||||
|
**Acceptance criteria.**
|
||||||
|
|
||||||
|
- One codebase deploys to both profiles via config only.
|
||||||
|
- Full vitest suite green on both runtimes.
|
||||||
|
- Documented end-to-end Clever+Sweego deploy: a newsletter to `noun.noun.NN@<inbound-domain>` lands in a feed; attachments served from Cellar; cleanup cron runs.
|
||||||
|
- No regression on the CF-native profile.
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 4.2 KiB |
@@ -0,0 +1,7 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="32" height="32">
|
||||||
|
<rect width="32" height="32" rx="7" fill="#f6821f"/>
|
||||||
|
<g fill="none" stroke="#ffffff" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<path d="M7 9h18c1.1 0 2 .9 2 2v10c0 1.1-.9 2-2 2H7c-1.1 0-2-.9-2-2V11c0-1.1.9-2 2-2z"/>
|
||||||
|
<polyline points="27,11 16,18.5 5,11"/>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 391 B |
+308
-20
@@ -5,6 +5,8 @@
|
|||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>kill-the-news — Private newsletter feeds on Cloudflare Workers</title>
|
<title>kill-the-news — Private newsletter feeds on Cloudflare Workers</title>
|
||||||
<meta name="description" content="Convert email newsletters into private RSS feeds using Cloudflare Workers. Self-hosted, free tier, your own domain." />
|
<meta name="description" content="Convert email newsletters into private RSS feeds using Cloudflare Workers. Self-hosted, free tier, your own domain." />
|
||||||
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||||
|
<link rel="icon" type="image/x-icon" href="/favicon.ico" sizes="32x32" />
|
||||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet" />
|
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet" />
|
||||||
@@ -171,6 +173,38 @@
|
|||||||
|
|
||||||
.section-header { margin-bottom: 3rem; }
|
.section-header { margin-bottom: 3rem; }
|
||||||
|
|
||||||
|
/* ── FAQ ── */
|
||||||
|
.faq-list { display: flex; flex-direction: column; gap: 0.75rem; }
|
||||||
|
.faq-item {
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
background: var(--surface);
|
||||||
|
transition: border-color 0.2s;
|
||||||
|
}
|
||||||
|
.faq-item[open] { border-color: rgba(246,130,31,0.4); }
|
||||||
|
.faq-item summary {
|
||||||
|
cursor: pointer;
|
||||||
|
list-style: none;
|
||||||
|
padding: 1.1rem 1.35rem;
|
||||||
|
font-weight: 600;
|
||||||
|
font-size: 0.95rem;
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
.faq-item summary::-webkit-details-marker { display: none; }
|
||||||
|
.faq-item summary::after { content: "+"; color: var(--accent); font-size: 1.2rem; line-height: 1; }
|
||||||
|
.faq-item[open] summary::after { content: "−"; }
|
||||||
|
.faq-item p {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0 1.35rem 1.2rem;
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
line-height: 1.65;
|
||||||
|
}
|
||||||
|
.faq-item a { color: var(--accent); }
|
||||||
|
|
||||||
/* ── Features ── */
|
/* ── Features ── */
|
||||||
.features-grid {
|
.features-grid {
|
||||||
display: grid;
|
display: grid;
|
||||||
@@ -446,6 +480,35 @@
|
|||||||
.demo-note { text-align: left; }
|
.demo-note { text-align: left; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ── Live stats ── */
|
||||||
|
.stats-section { padding: 4rem 2rem; }
|
||||||
|
.stats-inner { max-width: 1100px; margin: 0 auto; text-align: center; }
|
||||||
|
.stats-live {
|
||||||
|
display: inline-flex; align-items: center; gap: 0.5rem;
|
||||||
|
font-size: 0.78rem; color: var(--muted);
|
||||||
|
text-transform: uppercase; letter-spacing: 0.08em; margin-bottom: 2rem;
|
||||||
|
}
|
||||||
|
.stats-dot {
|
||||||
|
width: 8px; height: 8px; border-radius: 50%; background: var(--accent);
|
||||||
|
animation: stats-pulse 2s infinite;
|
||||||
|
}
|
||||||
|
@keyframes stats-pulse {
|
||||||
|
0% { box-shadow: 0 0 0 0 rgba(246,130,31,0.5); }
|
||||||
|
70% { box-shadow: 0 0 0 8px rgba(246,130,31,0); }
|
||||||
|
100% { box-shadow: 0 0 0 0 rgba(246,130,31,0); }
|
||||||
|
}
|
||||||
|
.stats-grid {
|
||||||
|
display: grid; grid-template-columns: repeat(2, 1fr);
|
||||||
|
gap: 2rem; max-width: 600px; margin: 0 auto;
|
||||||
|
}
|
||||||
|
.stat-num {
|
||||||
|
font-size: clamp(2.5rem, 6vw, 4rem); font-weight: 700;
|
||||||
|
color: var(--accent); letter-spacing: -0.03em;
|
||||||
|
font-variant-numeric: tabular-nums; line-height: 1;
|
||||||
|
}
|
||||||
|
.stat-label { font-size: 0.9rem; color: var(--muted); margin-top: 0.6rem; }
|
||||||
|
@media (max-width: 600px) { .stats-grid { gap: 1.5rem; } }
|
||||||
|
|
||||||
/* ── Nav links ── */
|
/* ── Nav links ── */
|
||||||
nav-links {
|
nav-links {
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -474,7 +537,7 @@
|
|||||||
|
|
||||||
.install-step {
|
.install-step {
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: 48px 1fr;
|
grid-template-columns: 48px minmax(0, 1fr);
|
||||||
gap: 1.25rem;
|
gap: 1.25rem;
|
||||||
align-items: start;
|
align-items: start;
|
||||||
}
|
}
|
||||||
@@ -561,30 +624,49 @@
|
|||||||
border-collapse: collapse;
|
border-collapse: collapse;
|
||||||
font-size: 0.85rem;
|
font-size: 0.85rem;
|
||||||
margin-top: 0.75rem;
|
margin-top: 0.75rem;
|
||||||
|
table-layout: fixed;
|
||||||
}
|
}
|
||||||
.waf-table th {
|
.waf-table th,
|
||||||
|
.waf-table td {
|
||||||
text-align: left;
|
text-align: left;
|
||||||
padding: 0.5rem 0.75rem;
|
padding: 0.5rem 0.6rem;
|
||||||
|
vertical-align: top;
|
||||||
|
}
|
||||||
|
.waf-table thead th:first-child { width: 38%; }
|
||||||
|
.waf-table thead th {
|
||||||
border-bottom: 1px solid var(--border);
|
border-bottom: 1px solid var(--border);
|
||||||
|
color: var(--text);
|
||||||
|
font-weight: 600;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
}
|
||||||
|
.waf-table tbody th {
|
||||||
color: var(--muted);
|
color: var(--muted);
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
font-size: 0.8rem;
|
font-size: 0.8rem;
|
||||||
}
|
|
||||||
.waf-table td {
|
|
||||||
padding: 0.5rem 0.75rem;
|
|
||||||
border-bottom: 1px solid rgba(255,255,255,0.04);
|
border-bottom: 1px solid rgba(255,255,255,0.04);
|
||||||
vertical-align: top;
|
|
||||||
}
|
}
|
||||||
.waf-table td code {
|
.waf-table tbody td {
|
||||||
|
border-bottom: 1px solid rgba(255,255,255,0.04);
|
||||||
|
color: var(--text);
|
||||||
|
}
|
||||||
|
.waf-table code {
|
||||||
font-family: 'JetBrains Mono', monospace;
|
font-family: 'JetBrains Mono', monospace;
|
||||||
font-size: 0.8em;
|
font-size: 0.8em;
|
||||||
color: var(--accent);
|
color: var(--accent);
|
||||||
|
overflow-wrap: anywhere;
|
||||||
}
|
}
|
||||||
.waf-table tr:last-child td { border-bottom: none; }
|
.waf-table tbody tr:last-child th,
|
||||||
|
.waf-table tbody tr:last-child td { border-bottom: none; }
|
||||||
|
|
||||||
@media (max-width: 600px) {
|
@media (max-width: 600px) {
|
||||||
.step:not(:last-child)::after { display: none; }
|
.step:not(:last-child)::after { display: none; }
|
||||||
.step { padding-right: 0; }
|
.step { padding-right: 0; }
|
||||||
|
section { padding-left: 1.25rem; padding-right: 1.25rem; }
|
||||||
|
#how-it-works { padding-left: 1.25rem; padding-right: 1.25rem; }
|
||||||
|
.install-step { grid-template-columns: 34px minmax(0, 1fr); gap: 0.85rem; }
|
||||||
|
.install-step-num { width: 34px; height: 34px; font-size: 0.8rem; }
|
||||||
|
.install-step-connector { margin-left: 16px; }
|
||||||
|
.code-block pre { padding: 1rem; }
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
@@ -603,6 +685,7 @@
|
|||||||
<a href="#features" class="nav-link">Features</a>
|
<a href="#features" class="nav-link">Features</a>
|
||||||
<a href="#how-it-works" class="nav-link">How it works</a>
|
<a href="#how-it-works" class="nav-link">How it works</a>
|
||||||
<a href="#install" class="nav-link">Install</a>
|
<a href="#install" class="nav-link">Install</a>
|
||||||
|
<a href="#faq" class="nav-link">FAQ</a>
|
||||||
<a href="https://github.com/sponsors/juherr" class="nav-link nav-link-sponsor" target="_blank" rel="noopener">
|
<a href="https://github.com/sponsors/juherr" class="nav-link nav-link-sponsor" target="_blank" rel="noopener">
|
||||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M12 21.593c-.524-.505-3.655-3.536-5.905-5.8C3.39 13.078 2 10.538 2 8a6 6 0 0 1 10-4.472A6 6 0 0 1 22 8c0 2.538-1.39 5.078-4.095 7.793-2.25 2.264-5.381 5.295-5.905 5.8z"/></svg>
|
<svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M12 21.593c-.524-.505-3.655-3.536-5.905-5.8C3.39 13.078 2 10.538 2 8a6 6 0 0 1 10-4.472A6 6 0 0 1 22 8c0 2.538-1.39 5.078-4.095 7.793-2.25 2.264-5.381 5.295-5.905 5.8z"/></svg>
|
||||||
Sponsor
|
Sponsor
|
||||||
@@ -624,7 +707,7 @@
|
|||||||
<h1>Turn email newsletters into <span>private RSS feeds</span></h1>
|
<h1>Turn email newsletters into <span>private RSS feeds</span></h1>
|
||||||
<p>Self-hosted on Cloudflare Workers. Your data stays in your own account, served from your own domain.</p>
|
<p>Self-hosted on Cloudflare Workers. Your data stays in your own account, served from your own domain.</p>
|
||||||
<div class="hero-ctas">
|
<div class="hero-ctas">
|
||||||
<a href="https://demo.kill-the.news/admin" class="btn btn-primary" target="_blank" rel="noopener">
|
<a href="https://demo.kill-the.news" class="btn btn-primary" target="_blank" rel="noopener">
|
||||||
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="5 3 19 12 5 21 5 3"/></svg>
|
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="5 3 19 12 5 21 5 3"/></svg>
|
||||||
Try the demo
|
Try the demo
|
||||||
</a>
|
</a>
|
||||||
@@ -636,6 +719,23 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Live stats (demo instance) -->
|
||||||
|
<section id="stats" class="stats-section" hidden>
|
||||||
|
<div class="stats-inner">
|
||||||
|
<div class="stats-live"><span class="stats-dot"></span> Live from the demo instance</div>
|
||||||
|
<div class="stats-grid">
|
||||||
|
<div class="stat">
|
||||||
|
<div class="stat-num" data-stat="feeds_created">0</div>
|
||||||
|
<div class="stat-label">Feeds created</div>
|
||||||
|
</div>
|
||||||
|
<div class="stat">
|
||||||
|
<div class="stat-num" data-stat="emails_received">0</div>
|
||||||
|
<div class="stat-label">Emails received</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
<!-- Demo banner -->
|
<!-- Demo banner -->
|
||||||
<div class="demo-banner">
|
<div class="demo-banner">
|
||||||
<div class="inner">
|
<div class="inner">
|
||||||
@@ -646,13 +746,13 @@
|
|||||||
Create a feed, grab the RSS URL, and add it to your reader — all without deploying anything.
|
Create a feed, grab the RSS URL, and add it to your reader — all without deploying anything.
|
||||||
</p>
|
</p>
|
||||||
<div class="demo-creds">
|
<div class="demo-creds">
|
||||||
<span class="cred-item">URL <strong>demo.kill-the.news/admin</strong></span>
|
<span class="cred-item">URL <strong>demo.kill-the.news</strong></span>
|
||||||
<span class="cred-sep">·</span>
|
<span class="cred-sep">·</span>
|
||||||
<span class="cred-item">Password <strong>password</strong></span>
|
<span class="cred-item">Password <strong>password</strong></span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="demo-actions">
|
<div class="demo-actions">
|
||||||
<a href="https://demo.kill-the.news/admin" class="btn btn-primary" target="_blank" rel="noopener" style="font-size:0.95rem;padding:0.6rem 1.35rem;">
|
<a href="https://demo.kill-the.news" class="btn btn-primary" target="_blank" rel="noopener" style="font-size:0.95rem;padding:0.6rem 1.35rem;">
|
||||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="5 3 19 12 5 21 5 3"/></svg>
|
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="5 3 19 12 5 21 5 3"/></svg>
|
||||||
Open demo
|
Open demo
|
||||||
</a>
|
</a>
|
||||||
@@ -678,6 +778,14 @@
|
|||||||
<p>Your emails and feeds live exclusively in your own Cloudflare account. No shared infrastructure, no data mining.</p>
|
<p>Your emails and feeds live exclusively in your own Cloudflare account. No shared infrastructure, no data mining.</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="feature-card">
|
||||||
|
<div class="feature-icon">
|
||||||
|
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M9 12l2 2 4-4"/></svg>
|
||||||
|
</div>
|
||||||
|
<h3>Separate Address & Feed URL</h3>
|
||||||
|
<p>Your subscribe address and your feed's reading URL are independent, unguessable ids. Share a feed without leaking the inbox that feeds it — and an address a newsletter harvests can never be turned into your feed.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="feature-card">
|
<div class="feature-card">
|
||||||
<div class="feature-icon">
|
<div class="feature-icon">
|
||||||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>
|
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>
|
||||||
@@ -710,6 +818,38 @@
|
|||||||
<p>Email attachments are stored in Cloudflare R2 and exposed as RSS enclosures — no extra hosting needed.</p>
|
<p>Email attachments are stored in Cloudflare R2 and exposed as RSS enclosures — no extra hosting needed.</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="feature-card">
|
||||||
|
<div class="feature-icon">
|
||||||
|
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
|
||||||
|
</div>
|
||||||
|
<h3>Per-Feed Icons</h3>
|
||||||
|
<p>Each feed picks up the favicon of its newsletter's sender domain, so feeds are easy to tell apart in your reader and the admin UI.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="feature-card">
|
||||||
|
<div class="feature-icon">
|
||||||
|
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
|
||||||
|
</div>
|
||||||
|
<h3>Auto-Expiring Feeds</h3>
|
||||||
|
<p>Give a feed a lifetime and it deletes itself when the timer runs out — perfect as a disposable inbox for one-off sign-ups you don't want to keep around.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="feature-card">
|
||||||
|
<div class="feature-icon">
|
||||||
|
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18.36 6.64a9 9 0 1 1-12.73 0"/><line x1="12" y1="2" x2="12" y2="12"/></svg>
|
||||||
|
</div>
|
||||||
|
<h3>Auto-Unsubscribe on Delete</h3>
|
||||||
|
<p>Deleting a feed fires RFC 8058 one-click unsubscribe requests to its newsletters, so the messages stop arriving at the now-dead address.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="feature-card">
|
||||||
|
<div class="feature-icon">
|
||||||
|
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 12h-6l-2 3h-4l-2-3H2"/><path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/></svg>
|
||||||
|
</div>
|
||||||
|
<h3>Catch-All Fallback</h3>
|
||||||
|
<p>Point your whole domain at kill-the-news: anything that isn't a feed is forwarded to a fallback address instead of dropped, so your personal mail still gets through.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="feature-card">
|
<div class="feature-card">
|
||||||
<div class="feature-icon">
|
<div class="feature-icon">
|
||||||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
|
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
|
||||||
@@ -718,6 +858,54 @@
|
|||||||
<p>Optionally delegate admin authentication to Authelia, Authentik, or any reverse proxy that sets <code style="font-family:monospace;font-size:0.8em;color:var(--accent)">Remote-User</code>.</p>
|
<p>Optionally delegate admin authentication to Authelia, Authentik, or any reverse proxy that sets <code style="font-family:monospace;font-size:0.8em;color:var(--accent)">Remote-User</code>.</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="feature-card">
|
||||||
|
<div class="feature-icon">
|
||||||
|
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>
|
||||||
|
</div>
|
||||||
|
<h3>REST API & OpenAPI</h3>
|
||||||
|
<p>Automate feeds and emails through a versioned REST API, documented with an OpenAPI 3.1 spec and a <a href="https://demo.kill-the.news/api/docs" target="_blank" rel="noopener" style="color:var(--accent)">live interactive reference</a>.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="feature-card">
|
||||||
|
<div class="feature-icon">
|
||||||
|
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 11a9 9 0 0 1 9 9"/><path d="M4 4a16 16 0 0 1 16 16"/><circle cx="5" cy="19" r="1"/></svg>
|
||||||
|
</div>
|
||||||
|
<h3>RSS, Atom & JSON Feed</h3>
|
||||||
|
<p>Every feed is served in all three formats — RSS 2.0, Atom, and JSON Feed — so it just works in NetNewsWire, Reeder, Feedly, NewsBlur and any other reader. Conditional requests (ETag / 304) keep polling cheap.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="feature-card">
|
||||||
|
<div class="feature-icon">
|
||||||
|
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="8" y1="13" x2="16" y2="13"/><line x1="8" y1="17" x2="16" y2="17"/></svg>
|
||||||
|
</div>
|
||||||
|
<h3>One-Click OPML Export</h3>
|
||||||
|
<p>Export all your feeds as an OPML file and bulk-import them into any reader in one shot — easy onboarding, and no lock-in if you ever want to move.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="feature-card">
|
||||||
|
<div class="feature-icon">
|
||||||
|
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07A19.5 19.5 0 0 1 4.69 12a19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 3.6 1.27h3a2 2 0 0 1 2 1.72c.127.96.361 1.903.7 2.81a2 2 0 0 1-.45 2.11L7.91 8.37a16 16 0 0 0 5.72 5.72l1.17-.94a2 2 0 0 1 2.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0 1 22 16.92z"/><path d="M14.05 2a9 9 0 0 1 8 7.94"/><path d="M14.05 6A5 5 0 0 1 18 10"/></svg>
|
||||||
|
</div>
|
||||||
|
<h3>Never Lose a Confirmation Link</h3>
|
||||||
|
<p>kill-the-news detects "confirm your subscription" emails at ingestion and surfaces the link prominently in the admin — unlike kill-the-newsletter, where the confirm email lands buried in your feed reader and is easily missed.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="feature-card">
|
||||||
|
<div class="feature-icon">
|
||||||
|
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>
|
||||||
|
</div>
|
||||||
|
<h3>Find the Source Feed</h3>
|
||||||
|
<p>If a newsletter already publishes RSS, Atom, or JSON Feed, kill-the-news spots it and points you to the original — subscribe at the source directly when you prefer.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="feature-card">
|
||||||
|
<div class="feature-icon">
|
||||||
|
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19.439 7.85c-.049.322.059.648.289.878l1.568 1.568c.47.47.706 1.087.706 1.704s-.235 1.233-.706 1.704l-1.611 1.611a.98.98 0 0 1-.837.276c-.47-.07-.802-.48-.968-.925a2.501 2.501 0 1 0-3.214 3.214c.446.166.855.497.925.968a.979.979 0 0 1-.276.837l-1.61 1.61a2.404 2.404 0 0 1-1.705.707 2.402 2.402 0 0 1-1.704-.706l-1.568-1.568a1.026 1.026 0 0 0-.877-.29c-.493.074-.84.504-1.02.968a2.5 2.5 0 1 1-3.237-3.237c.464-.18.894-.527.967-1.02a1.026 1.026 0 0 0-.289-.877l-1.568-1.568A2.402 2.402 0 0 1 1.998 12c0-.617.236-1.234.706-1.704L4.23 8.77c.24-.24.581-.353.917-.303.515.077.877.528 1.073 1.01a2.5 2.5 0 1 0 3.259-3.259c-.482-.196-.933-.558-1.01-1.073-.05-.336.062-.676.303-.917l1.525-1.525A2.402 2.402 0 0 1 12 1.998c.617 0 1.234.236 1.704.706l1.568 1.568c.23.23.556.338.877.29.493-.074.84-.504 1.02-.968a2.5 2.5 0 1 1 3.237 3.237c-.464.18-.894.527-.967 1.02Z"/></svg>
|
||||||
|
</div>
|
||||||
|
<h3>Native FreshRSS Support</h3>
|
||||||
|
<p>Manage your kill-the-news feeds without leaving <a href="https://freshrss.org" target="_blank" rel="noopener" style="color:var(--accent)">FreshRSS</a>, thanks to the <a href="https://github.com/juherr/xExtension-KillTheNews" target="_blank" rel="noopener" style="color:var(--accent)">xExtension-KillTheNews</a> extension.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@@ -938,23 +1126,36 @@ bucket_name = "kill-the-news-attachments"</span></pre>
|
|||||||
<div class="code-block-header"><span class="dot-r"></span><span class="dot-y"></span><span class="dot-g"></span> WAF rules</div>
|
<div class="code-block-header"><span class="dot-r"></span><span class="dot-y"></span><span class="dot-g"></span> WAF rules</div>
|
||||||
<table class="waf-table">
|
<table class="waf-table">
|
||||||
<thead>
|
<thead>
|
||||||
<tr><th>Endpoint</th><th>Condition (URI Path)</th><th>Limit (recommended)</th><th>Limit (free tier)</th><th>Action (recommended)</th><th>Action (free tier)</th></tr>
|
<tr>
|
||||||
|
<th scope="col">Setting</th>
|
||||||
|
<th scope="col"><code>/api/inbound</code></th>
|
||||||
|
<th scope="col"><code>/admin*</code></th>
|
||||||
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
<tr>
|
<tr>
|
||||||
<td><code>/api/inbound</code></td>
|
<th scope="row">Condition (URI Path)</th>
|
||||||
<td>wildcard <code>/api/inbound/*</code></td>
|
<td>wildcard <code>/api/inbound/*</code></td>
|
||||||
<td>60 req / min / IP</td>
|
<td>wildcard <code>/admin/*</code></td>
|
||||||
<td>10 req / 10 s / IP</td>
|
|
||||||
<td>Block (1 min)</td>
|
|
||||||
<td>Block (10 s)</td>
|
|
||||||
</tr>
|
</tr>
|
||||||
<tr>
|
<tr>
|
||||||
<td><code>/admin*</code></td>
|
<th scope="row">Limit (recommended)</th>
|
||||||
<td>wildcard <code>/admin/*</code></td>
|
<td>60 req / min / IP</td>
|
||||||
<td>20 req / min / IP</td>
|
<td>20 req / min / IP</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<th scope="row">Limit (free tier)</th>
|
||||||
|
<td>10 req / 10 s / IP</td>
|
||||||
<td>20 req / 10 s / IP</td>
|
<td>20 req / 10 s / IP</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<th scope="row">Action (recommended)</th>
|
||||||
|
<td>Block (1 min)</td>
|
||||||
<td>Managed Challenge (5 min)</td>
|
<td>Managed Challenge (5 min)</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<th scope="row">Action (free tier)</th>
|
||||||
|
<td>Block (10 s)</td>
|
||||||
<td>Managed Challenge (10 s)</td>
|
<td>Managed Challenge (10 s)</td>
|
||||||
</tr>
|
</tr>
|
||||||
</tbody>
|
</tbody>
|
||||||
@@ -1007,6 +1208,57 @@ bucket_name = "kill-the-news-attachments"</span></pre>
|
|||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- FAQ -->
|
||||||
|
<section id="faq">
|
||||||
|
<div class="section-header">
|
||||||
|
<div class="section-label">FAQ</div>
|
||||||
|
<h2 class="section-title">Questions & answers</h2>
|
||||||
|
<p class="section-sub">The practical stuff — subscribing, privacy, troubleshooting, and how kill-the-news differs.</p>
|
||||||
|
</div>
|
||||||
|
<div class="faq-list">
|
||||||
|
<details class="faq-item">
|
||||||
|
<summary>How does kill-the-news work?</summary>
|
||||||
|
<p>Create a feed in the admin UI and you get a unique address on your domain (e.g. <code style="font-family:monospace;color:var(--accent)">newsletter.42@yourdomain.com</code>) plus an RSS and an Atom feed. Any email sent to that address is turned into entries in those feeds.</p>
|
||||||
|
</details>
|
||||||
|
<details class="faq-item">
|
||||||
|
<summary>How do I confirm a newsletter subscription?</summary>
|
||||||
|
<p>Confirmation emails arrive as feed entries — open the entry in your reader and click the confirmation link. If a publisher requires a reply, subscribe with your normal inbox instead and set up a filter that auto-forwards its mail to your feed address.</p>
|
||||||
|
</details>
|
||||||
|
<details class="faq-item">
|
||||||
|
<summary>Are my feeds private?</summary>
|
||||||
|
<p>Yes. Each feed URL carries an unguessable ID, it is served from your own domain on your own Cloudflare account, and the admin UI is password-protected. Treat the feed URL like a password — anyone who has it can read your newsletters.</p>
|
||||||
|
</details>
|
||||||
|
<details class="faq-item">
|
||||||
|
<summary>Why are old entries disappearing?</summary>
|
||||||
|
<p>Feeds honor an optional size and time-to-live cap so RSS readers stay happy — some readers choke on feeds that grow too large. When a limit is reached, the oldest entries (and their R2 attachments) are purged automatically.</p>
|
||||||
|
</details>
|
||||||
|
<details class="faq-item">
|
||||||
|
<summary>Can I share a feed with someone?</summary>
|
||||||
|
<p>Don't. Anyone with the URL can read your newsletters and even unsubscribe you. Share the project instead, so others can self-host and create their own feeds.</p>
|
||||||
|
</details>
|
||||||
|
<details class="faq-item">
|
||||||
|
<summary>Why isn't my feed updating?</summary>
|
||||||
|
<p>Send a test email to the feed address. If it shows up within a minute, the delay is on the newsletter publisher's side, not kill-the-news. Readers that support WebSub get near-instant push updates instead of waiting for the next poll.</p>
|
||||||
|
</details>
|
||||||
|
<details class="faq-item">
|
||||||
|
<summary>How is this different from kill-the-newsletter.com?</summary>
|
||||||
|
<p>kill-the-news is self-hosted on your own Cloudflare account: your data, your domain, RSS <em>and</em> Atom output, attachments served as enclosures, WebSub push updates — all running on the free tier.</p>
|
||||||
|
</details>
|
||||||
|
<details class="faq-item">
|
||||||
|
<summary>How much does it cost?</summary>
|
||||||
|
<p>It runs on Cloudflare's free tier (Workers + KV + R2) plus the cost of your domain. With Cloudflare Email Routing, no third-party service is required at all.</p>
|
||||||
|
</details>
|
||||||
|
<details class="faq-item">
|
||||||
|
<summary>How do I delete a feed?</summary>
|
||||||
|
<p>From the password-protected admin UI — open the Feeds tab and delete it there. Its entries and attachments are removed along with it.</p>
|
||||||
|
</details>
|
||||||
|
<details class="faq-item">
|
||||||
|
<summary>Does it handle attachments?</summary>
|
||||||
|
<p>Yes — optionally. When an R2 bucket is configured, email attachments are stored there and exposed as RSS/Atom enclosures, downloadable from each entry. It's off by default: if no R2 bucket is bound (or you set <code>ATTACHMENTS_ENABLED = "false"</code>), attachments are simply skipped and everything else works as usual. R2 usage is shown on the status page so you can stay within the 10 GB free tier.</p>
|
||||||
|
</details>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
<!-- Tech Stack -->
|
<!-- Tech Stack -->
|
||||||
<section id="tech-stack" style="padding-top:0;">
|
<section id="tech-stack" style="padding-top:0;">
|
||||||
<div class="section-header">
|
<div class="section-header">
|
||||||
@@ -1064,5 +1316,41 @@ bucket_name = "kill-the-news-attachments"</span></pre>
|
|||||||
</p>
|
</p>
|
||||||
</footer>
|
</footer>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
(async function () {
|
||||||
|
const section = document.getElementById('stats');
|
||||||
|
let data;
|
||||||
|
try {
|
||||||
|
const res = await fetch('https://demo.kill-the.news/api/v1/stats', { cache: 'no-store' });
|
||||||
|
if (!res.ok) return; // section stays hidden
|
||||||
|
data = await res.json();
|
||||||
|
} catch { return; }
|
||||||
|
|
||||||
|
const nums = section.querySelectorAll('.stat-num');
|
||||||
|
nums.forEach(el => { el.dataset.value = data[el.dataset.stat] ?? 0; });
|
||||||
|
section.hidden = false;
|
||||||
|
|
||||||
|
const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||||
|
const fmt = n => n.toLocaleString('en-US');
|
||||||
|
const ease = t => 1 - Math.pow(1 - t, 3);
|
||||||
|
|
||||||
|
function animate(el) {
|
||||||
|
const target = Number(el.dataset.value) || 0;
|
||||||
|
if (reduce || target === 0) { el.textContent = fmt(target); return; }
|
||||||
|
const dur = 1400, start = performance.now();
|
||||||
|
(function step(now) {
|
||||||
|
const t = Math.min((now - start) / dur, 1);
|
||||||
|
el.textContent = fmt(Math.round(ease(t) * target));
|
||||||
|
if (t < 1) requestAnimationFrame(step);
|
||||||
|
})(performance.now());
|
||||||
|
}
|
||||||
|
|
||||||
|
const io = new IntersectionObserver((entries) => {
|
||||||
|
entries.forEach(e => { if (e.isIntersecting) { animate(e.target); io.unobserve(e.target); } });
|
||||||
|
}, { threshold: 0.4 });
|
||||||
|
nums.forEach(el => io.observe(el));
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,178 @@
|
|||||||
|
# Detect a newsletter's native Atom/RSS/JSON feed — design
|
||||||
|
|
||||||
|
_Date: 2026-05-25 · Backlog item: TODO.md "Detect a newsletter's native Atom/RSS feed" (P2·S)_
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
When an incoming newsletter email's HTML advertises its own syndication feed via
|
||||||
|
`<link rel="alternate" type="…">`, detect it and surface it to the admin:
|
||||||
|
"this newsletter already publishes a feed — you can subscribe to it directly."
|
||||||
|
|
||||||
|
A genuine differentiator: it is the top item on upstream kill-the-newsletter's
|
||||||
|
own TODO and is not built there. Per the user, detect **Atom, RSS, and JSON Feed**.
|
||||||
|
|
||||||
|
## Approach
|
||||||
|
|
||||||
|
Reuse the existing, proven pipeline — identical to the **confirmation-detection**
|
||||||
|
feature and the **per-sender unsubscribe** storage:
|
||||||
|
|
||||||
|
infra parses the HTML → a **pure domain detector** decides which links count →
|
||||||
|
the result rides into the aggregate via `IngestOptions` (like `unsub`) → the
|
||||||
|
aggregate stores it per-sender → admin surfaces it (detail + list badge +
|
||||||
|
dashboard pill + dismiss) → exposed read-only on the REST API.
|
||||||
|
|
||||||
|
Alternative considered and rejected: an ad-hoc detector living in infrastructure.
|
||||||
|
The "which MIME types are a feed" rule is business knowledge, so it belongs in
|
||||||
|
`domain/`, mirroring `domain/confirmation.ts`.
|
||||||
|
|
||||||
|
## Data model
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// New value shape
|
||||||
|
type NativeFeed = { url: string; type: "rss" | "atom" | "json" };
|
||||||
|
|
||||||
|
// FeedMetadata (src/types/index.ts) — additive, like `unsubscribe` / `pendingConfirmation`
|
||||||
|
nativeFeeds?: Record<string, NativeFeed[]>; // key = senderKey (same scheme as `unsubscribe`)
|
||||||
|
nativeFeedDismissed?: boolean; // dismiss: hides pill + badge, keeps the URLs
|
||||||
|
|
||||||
|
// FeedListItem (src/types/index.ts) — projected flag for the dashboard, like pendingConfirmation
|
||||||
|
hasNativeFeed?: boolean;
|
||||||
|
```
|
||||||
|
|
||||||
|
Update semantics (chosen by the user: "accumulation, but latest-per-sender"):
|
||||||
|
|
||||||
|
- Storage is **per sender**, keyed by the same `senderKey` used for `unsubscribe`
|
||||||
|
(`input.senders[0] || iconDomain || input.from`).
|
||||||
|
- **Latest non-empty wins per sender**: the most recent email from a given sender
|
||||||
|
that declares feeds overwrites _that sender's_ list; other senders are preserved.
|
||||||
|
Mirrors how `ingest` updates `unsubscribe` only when an unsubscribe URL is present.
|
||||||
|
- The aggregate exposes `nativeFeeds(): NativeFeed[]` = the **union across senders,
|
||||||
|
deduped by URL** (returns a copy).
|
||||||
|
- Projected flag `hasNativeFeed = nativeFeeds().length > 0 && !nativeFeedDismissed`.
|
||||||
|
|
||||||
|
Smart re-notify (avoid nagging on every email):
|
||||||
|
|
||||||
|
- On ingest, if a **previously-unseen URL** appears (not in the current union),
|
||||||
|
clear `nativeFeedDismissed` (re-raise the notice).
|
||||||
|
- If ingestion only re-discovers already-known URLs, leave `nativeFeedDismissed`
|
||||||
|
untouched, so a dismiss sticks until a genuinely new native feed shows up.
|
||||||
|
|
||||||
|
## Detection
|
||||||
|
|
||||||
|
**Infra — `src/infrastructure/html-processor.ts`**: new
|
||||||
|
`extractFeedLinks(content): { href: string; type: string }[]`.
|
||||||
|
|
||||||
|
- Parse `<link>` elements whose `rel` token-list contains `alternate` and that
|
||||||
|
carry a `type` attribute (`link[rel~="alternate"][type]`).
|
||||||
|
- Return the raw `href` + `type` tuples; absolutize a relative `href` best-effort
|
||||||
|
via the existing `toAbsolute` helper; http(s) only (drop others).
|
||||||
|
- Plain-text bodies have no `<link>` → returns `[]`.
|
||||||
|
|
||||||
|
**Domain — `src/domain/native-feed.ts`** (pure, no DOM/IO, mirrors `confirmation.ts`):
|
||||||
|
`detectNativeFeeds(links): NativeFeed[]`.
|
||||||
|
|
||||||
|
- Owns the recognized MIME → kind table (strict, the three canonical types only):
|
||||||
|
- `application/atom+xml` → `"atom"`
|
||||||
|
- `application/rss+xml` → `"rss"`
|
||||||
|
- `application/feed+json` → `"json"`
|
||||||
|
- Ignores any other type (no `application/json` — too broad, would capture non-feeds).
|
||||||
|
- Dedupes by URL; preserves first-seen kind for a URL.
|
||||||
|
|
||||||
|
## Ingestion wiring
|
||||||
|
|
||||||
|
**`src/application/email-processor.ts`**: alongside the existing confirmation +
|
||||||
|
unsubscribe extraction, call `extractFeedLinks(input.content)` →
|
||||||
|
`detectNativeFeeds(...)`. When non-empty, pass into `feed.ingest` via
|
||||||
|
`IngestOptions`:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
nativeFeeds?: { senderKey: string; feeds: NativeFeed[] };
|
||||||
|
```
|
||||||
|
|
||||||
|
`senderKey` is the same value already computed for `unsub`.
|
||||||
|
|
||||||
|
**`src/domain/feed.aggregate.ts`**:
|
||||||
|
|
||||||
|
- `ingest`: when `opts.nativeFeeds` is present, set
|
||||||
|
`_metadata.nativeFeeds[senderKey] = feeds`; if any feed URL is new vs the
|
||||||
|
pre-update union, set `_metadata.nativeFeedDismissed = false`.
|
||||||
|
- Getter `nativeFeeds(): NativeFeed[]` — union deduped by URL (copy).
|
||||||
|
- Getter `hasNativeFeed(): boolean` — `nativeFeeds().length > 0 && !dismissed`.
|
||||||
|
- `dismissNativeFeed(): void` — sets `nativeFeedDismissed = true` (lower-only,
|
||||||
|
mirrors `dismissConfirmation`).
|
||||||
|
- `removeEmails` does **not** touch native feeds (the data is per-sender, not
|
||||||
|
per-email; deleting emails should not drop a discovered native feed).
|
||||||
|
|
||||||
|
**`src/infrastructure/feed-mapper.ts`**: `toListItemDTO` gains a `hasNativeFeed`
|
||||||
|
parameter (like `pendingConfirmation`), projected into `FeedListItem`. The
|
||||||
|
repository passes `feed.hasNativeFeed()` when saving. `nativeFeeds` /
|
||||||
|
`nativeFeedDismissed` persist as part of `FeedMetadata` (stored directly in KV —
|
||||||
|
additive, no mapper change for the metadata blob itself).
|
||||||
|
|
||||||
|
## REST API
|
||||||
|
|
||||||
|
**`src/routes/api/schemas.ts`** — `FeedSchema` gains a read-only field:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
nativeFeeds: z.array(z.object({
|
||||||
|
url: z.string(),
|
||||||
|
type: z.enum(["rss", "atom", "json"]),
|
||||||
|
})),
|
||||||
|
```
|
||||||
|
|
||||||
|
Populated from `feed.nativeFeeds()` in the feed-read handler so an API client can
|
||||||
|
choose which native feed to subscribe to. Read-only — not accepted on
|
||||||
|
`FeedCreate`/`FeedUpdate`.
|
||||||
|
|
||||||
|
## Admin UI
|
||||||
|
|
||||||
|
Mirror the confirmation surfaces (detail + badge + pill + dismiss).
|
||||||
|
|
||||||
|
- **Detail (per-feed view, `src/routes/admin/emails.tsx`)**: next to the existing
|
||||||
|
`FeedFormats` "Subscribe" block (the **KTN feeds**), render a second group
|
||||||
|
**"Native feeds"** when `nativeFeeds()` is non-empty. Each native feed is a
|
||||||
|
copyable chip (type label RSS/Atom/JSON + copy + open-in-new-tab), reusing the
|
||||||
|
existing copyable/chip styling. Net result: KTN feeds on one side, native feeds
|
||||||
|
on the other, both copy-pasteable into a reader. Include a "dismiss" control
|
||||||
|
(POST to the dismiss route) to clear the dashboard/list notice.
|
||||||
|
- **List badge (`src/routes/admin.tsx` feed row)**: a discreet badge when
|
||||||
|
`hasNativeFeed`.
|
||||||
|
- **Dashboard pill**: `pill-native` (styled like `pill-confirmation`) on the
|
||||||
|
dashboard feed list when `hasNativeFeed`.
|
||||||
|
- **Dismiss route**: `POST /admin/feeds/:feedId/native-feed/dismiss` → load
|
||||||
|
aggregate → `feed.dismissNativeFeed()` → save → JSON ok. Client script wired
|
||||||
|
like the existing `confirmation-dismiss` (in `src/scripts/client/`).
|
||||||
|
- **Styles**: add `.native-feeds` group + `.pill-native` + badge rules in
|
||||||
|
`src/styles/components.css`, matching the format-chip / confirmation styling.
|
||||||
|
|
||||||
|
## Out of scope (v1)
|
||||||
|
|
||||||
|
- No change to the **public XML/JSON feed output** (user decision: native feeds
|
||||||
|
live in admin + REST, not in the rendered feeds).
|
||||||
|
- No anchor-text heuristics ("Subscribe via RSS" links) — `<link rel=alternate>`
|
||||||
|
only, to keep false positives near zero.
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
- `src/domain/native-feed.test.ts` — MIME mapping, dedupe, ignores unknown types.
|
||||||
|
- `src/infrastructure/html-processor.test.ts` — `extractFeedLinks`: rel/type
|
||||||
|
parsing, relative-href absolutization, http(s)-only, plain-text → `[]`.
|
||||||
|
- `src/domain/feed.aggregate.test.ts` — ingest per-sender latest-wins, union
|
||||||
|
getter, re-notify on new URL, dismiss lower-only, removeEmails leaves it intact.
|
||||||
|
- `src/application/email-processor.test.ts` — end-to-end: an email with a
|
||||||
|
`<link rel=alternate>` populates `nativeFeeds`; one without leaves it alone.
|
||||||
|
- `src/infrastructure/feed-mapper.test.ts` / repository — `hasNativeFeed`
|
||||||
|
projection into `feeds:list`.
|
||||||
|
- `src/routes/admin.test.ts` — detail "native-feeds" group, list badge, dashboard
|
||||||
|
`pill-native`, dismiss route clears the flag.
|
||||||
|
- REST API test — `FeedSchema.nativeFeeds` present in the feed-read response.
|
||||||
|
|
||||||
|
End green: `npx tsc --noEmit`, `npm test`, `npm run build`.
|
||||||
|
|
||||||
|
## Docs
|
||||||
|
|
||||||
|
- `README.md` / `INSTALL.md` — mention native-feed detection.
|
||||||
|
- `docs/index.html` (marketing landing) — add a feature card (it's a
|
||||||
|
differentiator we ship before upstream).
|
||||||
|
- `CLAUDE.md` — add `domain/native-feed.ts` to the source layout; note the new
|
||||||
|
`FeedMetadata.nativeFeeds` / `nativeFeedDismissed` fields.
|
||||||
@@ -0,0 +1,206 @@
|
|||||||
|
# Subscription confirmation surfacing — design
|
||||||
|
|
||||||
|
_Date: 2026-05-25 · Origin: TODO.md `P1·M` "Subscription confirmation handling" (upstream issues #5, #23, #57, #73, #89, #95, #97)_
|
||||||
|
|
||||||
|
## Problem
|
||||||
|
|
||||||
|
Newsletters require a "click to confirm your subscription" step. The confirmation
|
||||||
|
email lands in the feed like any other item, so the user has to hunt the link
|
||||||
|
inside a feed reader — the single most recurring upstream request. Until they
|
||||||
|
confirm, the feed stays empty and the tool looks broken.
|
||||||
|
|
||||||
|
## Goal (v1 scope)
|
||||||
|
|
||||||
|
Detect confirmation emails at ingestion, **mark** them, and **surface the
|
||||||
|
confirmation link prominently** in the admin so the user can click it. No outbound
|
||||||
|
requests — the worker never follows the link in v1.
|
||||||
|
|
||||||
|
Explicitly deferred to a later batch (noted in TODO): a server-configured
|
||||||
|
on-detection action (`none` / `autoclick` / `forward` to the fallback box).
|
||||||
|
|
||||||
|
## Non-goals
|
||||||
|
|
||||||
|
- No auto-clicking / server-side following of confirmation links (SSRF surface).
|
||||||
|
- No per-feed action configuration.
|
||||||
|
- No detection of whether confirmation actually succeeded (impossible without
|
||||||
|
autoclick) — "dismiss" just stops the reminder.
|
||||||
|
|
||||||
|
## Architecture overview
|
||||||
|
|
||||||
|
Detection is a **pure domain service** fed by infra-extracted links/text; the
|
||||||
|
result is persisted on the email's metadata at ingestion and a feed-level flag is
|
||||||
|
projected into `feeds:list` so the dashboard stays at one KV read.
|
||||||
|
|
||||||
|
```
|
||||||
|
ingestion (storeEmail)
|
||||||
|
├─ infra: htmlToText(content) + extractLinks(content)
|
||||||
|
├─ domain: detectConfirmation({subject, text, links}) → {score, links[]} | null
|
||||||
|
├─ if detected → EmailMetadata.confirmation = { links }
|
||||||
|
└─ Feed.ingest() raises FeedMetadata.pendingConfirmation = true
|
||||||
|
→ FeedRepository.saveMetadata projects pendingConfirmation into feeds:list
|
||||||
|
```
|
||||||
|
|
||||||
|
## 1. Detection
|
||||||
|
|
||||||
|
### `src/domain/confirmation.ts` (new, pure — no DOM)
|
||||||
|
|
||||||
|
```ts
|
||||||
|
detectConfirmation(input: {
|
||||||
|
subject: string;
|
||||||
|
text: string; // plain-text rendition of the body
|
||||||
|
links: { href: string; text: string }[];
|
||||||
|
}): { score: number; links: string[] } | null
|
||||||
|
```
|
||||||
|
|
||||||
|
- **Multilingual keyword lists** (FR/EN/DE/ES and extensible) for subject + body:
|
||||||
|
`confirm`, `verify`, `activate`, `subscribe`, `confirmer`, `valider`,
|
||||||
|
`activer`, `bestätigen`, `confirmar`, `verificar`, … (case/diacritic-insensitive
|
||||||
|
matching).
|
||||||
|
- **Link scoring** by anchor text + URL path/query signals: `/confirm`, `/verify`,
|
||||||
|
`/activate`, `/subscribe`, `/opt-in`, `token=`, `confirm=`, `?c=`, etc.
|
||||||
|
- **Combined score** = subject/body keyword signal + best link signal. Above a
|
||||||
|
tuned `THRESHOLD` → return the ranked candidate links (top 3). Below → `null`.
|
||||||
|
- Only `http(s):` links are ever considered/returned (no `javascript:`/`data:`/
|
||||||
|
`mailto:`).
|
||||||
|
- This module owns the business knowledge (keyword vocab, weights, threshold);
|
||||||
|
it is unit-tested in isolation.
|
||||||
|
|
||||||
|
### `src/infrastructure/html-processor.ts` — `extractLinks`
|
||||||
|
|
||||||
|
```ts
|
||||||
|
extractLinks(content: string): { href: string; text: string }[]
|
||||||
|
```
|
||||||
|
|
||||||
|
- HTML: linkedom parse, collect `<a href>` + anchor text.
|
||||||
|
- Plain text: regex URL fallback (href = url, text = url).
|
||||||
|
- Infra owns DOM parsing; the domain receives plain data.
|
||||||
|
|
||||||
|
### `src/application/email-processor.ts` — wire-in
|
||||||
|
|
||||||
|
In `storeEmail`, before building `newEntry`:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const text = htmlToText(input.content);
|
||||||
|
const links = extractLinks(input.content);
|
||||||
|
const confirmation = detectConfirmation({
|
||||||
|
subject: input.subject,
|
||||||
|
text,
|
||||||
|
links,
|
||||||
|
});
|
||||||
|
// → EmailMetadata.confirmation = confirmation ? { links: confirmation.links } : undefined
|
||||||
|
```
|
||||||
|
|
||||||
|
Computed once at reception. Dedup/ingest flow otherwise unchanged.
|
||||||
|
|
||||||
|
## 2. Data model (additive)
|
||||||
|
|
||||||
|
### `EmailMetadata` (`src/types/index.ts`)
|
||||||
|
|
||||||
|
```ts
|
||||||
|
confirmation?: { links: string[] }; // present ⇒ detected; links = ranked top-3
|
||||||
|
```
|
||||||
|
|
||||||
|
Presence powers the list badge and the detail section. Additive → pre-feature
|
||||||
|
emails have nothing (no retroactive false positives).
|
||||||
|
|
||||||
|
### `FeedMetadata` (`src/types/index.ts`)
|
||||||
|
|
||||||
|
```ts
|
||||||
|
pendingConfirmation?: boolean; // ≥1 unactioned confirmation email present
|
||||||
|
```
|
||||||
|
|
||||||
|
### `FeedListItem` (`src/types/index.ts`)
|
||||||
|
|
||||||
|
```ts
|
||||||
|
pendingConfirmation?: boolean; // projected from FeedMetadata for the dashboard
|
||||||
|
```
|
||||||
|
|
||||||
|
### Aggregate `Feed` (`src/domain/feed.aggregate.ts`)
|
||||||
|
|
||||||
|
- `ingest()` sets `pendingConfirmation = true` when the new `EmailMetadata` carries
|
||||||
|
`confirmation`.
|
||||||
|
- `removeEmails()` recomputes the flag (false when no confirmation email remains).
|
||||||
|
- `dismissConfirmation()` sets it to false.
|
||||||
|
- read accessor `pendingConfirmation`.
|
||||||
|
|
||||||
|
### Persistence (`src/infrastructure/feed-repository.ts` + `feed-mapper.ts`)
|
||||||
|
|
||||||
|
- `FeedMetadata` round-trips `pendingConfirmation`.
|
||||||
|
- **Sync invariant extended**: `saveMetadata` projects `pendingConfirmation` into
|
||||||
|
the `feeds:list` item (today only `save`/`saveConfig` upsert the list). This is
|
||||||
|
the one metadata-derived field the list carries; it keeps the dashboard at a
|
||||||
|
single KV read instead of N per-feed metadata reads.
|
||||||
|
|
||||||
|
## 3. Admin UI
|
||||||
|
|
||||||
|
### a) Detail view — dedicated section (`routes/admin/emails.tsx`, `GET /emails/:emailKey`)
|
||||||
|
|
||||||
|
Above the Rendered/Raw toggle, shown when `email.confirmation`:
|
||||||
|
|
||||||
|
- Heading "Confirm your subscription".
|
||||||
|
- Best-scored link as a **primary button**; remaining candidates as secondary
|
||||||
|
links. URLs shown in clear text (transparency). `target="_blank" rel="noopener
|
||||||
|
noreferrer"`.
|
||||||
|
|
||||||
|
### b) Email list badge (`routes/admin/emails.tsx`, `GET /feeds/:feedId/emails`)
|
||||||
|
|
||||||
|
A "Confirmation" badge in the subject cell of rows where `email.confirmation`
|
||||||
|
exists, styled like the existing attachment indicator.
|
||||||
|
|
||||||
|
### c) Dashboard indicator (`routes/admin.tsx`, `GET /`)
|
||||||
|
|
||||||
|
A "Confirmation pending" pill on feeds whose `FeedListItem.pendingConfirmation` is
|
||||||
|
true (list + table views), read with zero extra KV reads. Links to the feed's
|
||||||
|
emails page.
|
||||||
|
|
||||||
|
### d) Feed emails-page banner (`routes/admin/emails.tsx`)
|
||||||
|
|
||||||
|
When `feedMetadata.pendingConfirmation`: a top banner "A confirmation email was
|
||||||
|
detected" linking to the latest confirmation email, plus a "Mark as confirmed"
|
||||||
|
button (dismiss).
|
||||||
|
|
||||||
|
### Post-creation redirect
|
||||||
|
|
||||||
|
`POST /admin/feeds/create` redirects to `/admin/feeds/:feedId/emails` (not the
|
||||||
|
dashboard) so the user lands where the banner appears once the (async) confirmation
|
||||||
|
email arrives.
|
||||||
|
|
||||||
|
## 4. Dismiss action
|
||||||
|
|
||||||
|
`POST /admin/feeds/:feedId/confirmation/dismiss`:
|
||||||
|
|
||||||
|
- load aggregate → `feed.dismissConfirmation()` → `repo.saveMetadata(feed)`
|
||||||
|
(reprojects `pendingConfirmation:false` into `feeds:list`).
|
||||||
|
- JSON response for the banner's fetch (mirrors the existing sender-filter
|
||||||
|
pattern); redirect fallback for no-JS.
|
||||||
|
- Protected by the existing admin auth + CSRF middleware.
|
||||||
|
|
||||||
|
"Dismiss" = "stop reminding me" (no real confirmation tracking without autoclick).
|
||||||
|
Deleting the confirmation email(s) also clears the flag via `removeEmails`.
|
||||||
|
|
||||||
|
## Security
|
||||||
|
|
||||||
|
- v1 performs **no outbound request** → no SSRF surface.
|
||||||
|
- Candidate `href`s filtered to `http(s):` only; never `javascript:`/`data:`.
|
||||||
|
- Output escaped via normal hono/jsx rendering.
|
||||||
|
|
||||||
|
## Testing (TDD)
|
||||||
|
|
||||||
|
- `confirmation.test.ts` (domain): multilingual scoring, threshold, link ranking,
|
||||||
|
negative cases (normal newsletter doesn't trigger), plain-text body.
|
||||||
|
- `html-processor.test.ts`: `extractLinks` for HTML and plain text.
|
||||||
|
- `email-processor.test.ts`: confirmation email → `EmailMetadata.confirmation`
|
||||||
|
populated + `pendingConfirmation` raised; dedup/ingest otherwise unchanged.
|
||||||
|
- `admin.test.ts` / emails tests: list badge, detail section, dashboard pill,
|
||||||
|
banner, dismiss route (clears flag + reprojects into list).
|
||||||
|
|
||||||
|
Close green: `npx tsc --noEmit`, `npm test`, `npm run build`.
|
||||||
|
|
||||||
|
## Docs
|
||||||
|
|
||||||
|
- `README.md` + `INSTALL.md`: "Subscription confirmation surfacing" capability.
|
||||||
|
- `docs/index.html` (landing): feature card — a genuine differentiator vs
|
||||||
|
kill-the-newsletter.
|
||||||
|
- `TODO.md`: check off `P1·M` "Subscription confirmation handling"; add a new
|
||||||
|
`P2·M` "Confirmation on-detect action (none/autoclick/forward)" item capturing
|
||||||
|
the deferred server options + SSRF/fallback notes.
|
||||||
+1
-1
@@ -2,7 +2,7 @@ import prettier from "eslint-config-prettier";
|
|||||||
import tseslint from "typescript-eslint";
|
import tseslint from "typescript-eslint";
|
||||||
|
|
||||||
export default tseslint.config(
|
export default tseslint.config(
|
||||||
{ ignores: ["dist/", "coverage/"] },
|
{ ignores: ["dist/", "coverage/", "src/scripts/generated/"] },
|
||||||
...tseslint.configs.recommended,
|
...tseslint.configs.recommended,
|
||||||
prettier,
|
prettier,
|
||||||
{
|
{
|
||||||
|
|||||||
Generated
+136
-6
@@ -1,15 +1,17 @@
|
|||||||
{
|
{
|
||||||
"name": "kill-the-news",
|
"name": "kill-the-news",
|
||||||
"version": "0.1.0",
|
"version": "0.3.1",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "kill-the-news",
|
"name": "kill-the-news",
|
||||||
"version": "0.1.0",
|
"version": "0.3.1",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@hono/zod-openapi": "^1.4.0",
|
||||||
"@hono/zod-validator": "^0.8.0",
|
"@hono/zod-validator": "^0.8.0",
|
||||||
|
"@scalar/hono-api-reference": "^0.10.19",
|
||||||
"escape-html": "^1.0.3",
|
"escape-html": "^1.0.3",
|
||||||
"feed": "5.2.1",
|
"feed": "5.2.1",
|
||||||
"hono": "4.12.22",
|
"hono": "4.12.22",
|
||||||
@@ -37,6 +39,18 @@
|
|||||||
"wrangler": "4.94.0"
|
"wrangler": "4.94.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@asteasolutions/zod-to-openapi": {
|
||||||
|
"version": "8.5.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@asteasolutions/zod-to-openapi/-/zod-to-openapi-8.5.0.tgz",
|
||||||
|
"integrity": "sha512-SABbKiObg5dLRiTFnqiW1WWwGcg1BJfmHtT2asIBnBHg6Smy/Ms2KHc650+JI4Hw7lSkdiNebEGXpwoxfben8Q==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"openapi3-ts": "^4.1.2"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"zod": "^4.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@babel/helper-string-parser": {
|
"node_modules/@babel/helper-string-parser": {
|
||||||
"version": "7.27.1",
|
"version": "7.27.1",
|
||||||
"resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz",
|
"resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz",
|
||||||
@@ -822,6 +836,24 @@
|
|||||||
"node": "^20.19.0 || ^22.13.0 || >=24"
|
"node": "^20.19.0 || ^22.13.0 || >=24"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@hono/zod-openapi": {
|
||||||
|
"version": "1.4.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@hono/zod-openapi/-/zod-openapi-1.4.0.tgz",
|
||||||
|
"integrity": "sha512-AFchqR1N/NxfI4hUOSGI2/g8zLROxA1OE7Oh5JJFlTaGxhrdRyH+93gd0tIBpb0z8s9r8hUoNnaOBfHbdb4NMw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@asteasolutions/zod-to-openapi": "^8.5.0",
|
||||||
|
"@hono/zod-validator": "^0.8.0",
|
||||||
|
"openapi3-ts": "^4.5.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=16.0.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"hono": ">=4.10.0",
|
||||||
|
"zod": "^4.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@hono/zod-validator": {
|
"node_modules/@hono/zod-validator": {
|
||||||
"version": "0.8.0",
|
"version": "0.8.0",
|
||||||
"resolved": "https://registry.npmjs.org/@hono/zod-validator/-/zod-validator-0.8.0.tgz",
|
"resolved": "https://registry.npmjs.org/@hono/zod-validator/-/zod-validator-0.8.0.tgz",
|
||||||
@@ -1954,6 +1986,99 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/@scalar/client-side-rendering": {
|
||||||
|
"version": "0.1.12",
|
||||||
|
"resolved": "https://registry.npmjs.org/@scalar/client-side-rendering/-/client-side-rendering-0.1.12.tgz",
|
||||||
|
"integrity": "sha512-prwHK4ozTU268BHZ/5OstoKB23JSidDuvddAOp0bVz9c29ZxsyzzxPtPcVgF7X16LiZnS1OzY030FoDCM+iC9Q==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@scalar/schemas": "0.3.2",
|
||||||
|
"@scalar/types": "0.12.2",
|
||||||
|
"@scalar/validation": "0.6.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=22"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@scalar/helpers": {
|
||||||
|
"version": "0.8.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@scalar/helpers/-/helpers-0.8.0.tgz",
|
||||||
|
"integrity": "sha512-gmOC6VravNB9VDl6wnt/GOj4K/hn48tj5bpW4AM4MhH8Ubil6uu7g1DSoKHwltu8Ks79KEtR6JmOrROi9R7jaQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=22"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@scalar/hono-api-reference": {
|
||||||
|
"version": "0.10.19",
|
||||||
|
"resolved": "https://registry.npmjs.org/@scalar/hono-api-reference/-/hono-api-reference-0.10.19.tgz",
|
||||||
|
"integrity": "sha512-6EfwN/lfPvePzAxe9UE8fr/ZuAAqS6ttUwQu9JTgk2Xl/clicaVVSOc0gyGt+8GLXdysoNinjZ74we8xqNWyCA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@scalar/client-side-rendering": "0.1.12"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=22"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"hono": "^4.12.5"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@scalar/schemas": {
|
||||||
|
"version": "0.3.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@scalar/schemas/-/schemas-0.3.2.tgz",
|
||||||
|
"integrity": "sha512-iadXBgJ02XUU5C5s6/xh/PmGLzUPd7X8upXIvPWBXDcQ4FHACNgkG8PPZ/beYM8UPDDkTUPM3ygEs0G6jKwGjQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@scalar/helpers": "0.8.0",
|
||||||
|
"@scalar/validation": "0.6.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=22"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@scalar/types": {
|
||||||
|
"version": "0.12.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@scalar/types/-/types-0.12.2.tgz",
|
||||||
|
"integrity": "sha512-EzLkubCb7xioiTm9eYnmn/032akaq4kkrrdclgV2uezwtniR8ErQICjhMl2AjBWL6nstHiFZ9RnPZm2Z2/KM0Q==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@scalar/helpers": "0.8.0",
|
||||||
|
"nanoid": "^5.1.6",
|
||||||
|
"type-fest": "^5.3.1",
|
||||||
|
"zod": "^4.3.5"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=22"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@scalar/types/node_modules/nanoid": {
|
||||||
|
"version": "5.1.11",
|
||||||
|
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.1.11.tgz",
|
||||||
|
"integrity": "sha512-v+KEsUv2ps74PaSKv0gHTxTCgMXOIfBEbaqa6w6ISIGC7ZsvHN4N9oJ8d4cmf0n5oTzQz2SLmThbQWhjd/8eKg==",
|
||||||
|
"funding": [
|
||||||
|
{
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/ai"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"bin": {
|
||||||
|
"nanoid": "bin/nanoid.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "^18 || >=20"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@scalar/validation": {
|
||||||
|
"version": "0.6.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@scalar/validation/-/validation-0.6.0.tgz",
|
||||||
|
"integrity": "sha512-tpmmG+/xRE2Kn9RpflU3AIyZv08v10+E1ZrJCx7z6+/91zHVxy0M73kC1LT4/8PbYNt85ywyC8+n+D99JdMcGA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@sindresorhus/is": {
|
"node_modules/@sindresorhus/is": {
|
||||||
"version": "7.2.0",
|
"version": "7.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-7.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-7.2.0.tgz",
|
||||||
@@ -4459,6 +4584,15 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/openapi3-ts": {
|
||||||
|
"version": "4.5.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/openapi3-ts/-/openapi3-ts-4.5.0.tgz",
|
||||||
|
"integrity": "sha512-jaL+HgTq2Gj5jRcfdutgRGLosCy/hT8sQf6VOy+P+g36cZOjI1iukdPnijC+4CmeRzg/jEllJUboEic2FhxhtQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"yaml": "^2.8.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/optionator": {
|
"node_modules/optionator": {
|
||||||
"version": "0.9.4",
|
"version": "0.9.4",
|
||||||
"resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",
|
"resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",
|
||||||
@@ -5026,7 +5160,6 @@
|
|||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/tagged-tag/-/tagged-tag-1.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/tagged-tag/-/tagged-tag-1.0.0.tgz",
|
||||||
"integrity": "sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng==",
|
"integrity": "sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng==",
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=20"
|
"node": ">=20"
|
||||||
@@ -5150,7 +5283,6 @@
|
|||||||
"version": "5.6.0",
|
"version": "5.6.0",
|
||||||
"resolved": "https://registry.npmjs.org/type-fest/-/type-fest-5.6.0.tgz",
|
"resolved": "https://registry.npmjs.org/type-fest/-/type-fest-5.6.0.tgz",
|
||||||
"integrity": "sha512-8ZiHFm91orbSAe2PSAiSVBVko18pbhbiB3U9GglSzF/zCGkR+rxpHx6sEMCUm4kxY4LjDIUGgCfUMtwfZfjfUA==",
|
"integrity": "sha512-8ZiHFm91orbSAe2PSAiSVBVko18pbhbiB3U9GglSzF/zCGkR+rxpHx6sEMCUm4kxY4LjDIUGgCfUMtwfZfjfUA==",
|
||||||
"dev": true,
|
|
||||||
"license": "(MIT OR CC0-1.0)",
|
"license": "(MIT OR CC0-1.0)",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"tagged-tag": "^1.0.0"
|
"tagged-tag": "^1.0.0"
|
||||||
@@ -6097,9 +6229,7 @@
|
|||||||
"version": "2.9.0",
|
"version": "2.9.0",
|
||||||
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz",
|
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz",
|
||||||
"integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==",
|
"integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==",
|
||||||
"dev": true,
|
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"optional": true,
|
|
||||||
"bin": {
|
"bin": {
|
||||||
"yaml": "bin.mjs"
|
"yaml": "bin.mjs"
|
||||||
},
|
},
|
||||||
|
|||||||
+7
-3
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "kill-the-news",
|
"name": "kill-the-news",
|
||||||
"version": "0.1.0",
|
"version": "0.3.1",
|
||||||
"description": "Convert email newsletters into private RSS feeds using Cloudflare Workers",
|
"description": "Convert email newsletters into private RSS feeds using Cloudflare Workers",
|
||||||
"main": "dist/worker.js",
|
"main": "dist/worker.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -16,11 +16,13 @@
|
|||||||
"test": "vitest run",
|
"test": "vitest run",
|
||||||
"test:watch": "vitest",
|
"test:watch": "vitest",
|
||||||
"test:coverage": "vitest run --coverage",
|
"test:coverage": "vitest run --coverage",
|
||||||
"typecheck": "tsc --noEmit",
|
"typecheck": "tsc --noEmit && npm run typecheck:client",
|
||||||
|
"typecheck:client": "tsc -p src/scripts/client/tsconfig.json --noEmit",
|
||||||
|
"release": "bash scripts/release.sh",
|
||||||
"prepare": "husky && npm run build:client"
|
"prepare": "husky && npm run build:client"
|
||||||
},
|
},
|
||||||
"lint-staged": {
|
"lint-staged": {
|
||||||
"*.{ts,js}": [
|
"*.{ts,tsx,js,jsx}": [
|
||||||
"eslint --fix",
|
"eslint --fix",
|
||||||
"prettier --write"
|
"prettier --write"
|
||||||
],
|
],
|
||||||
@@ -50,7 +52,9 @@
|
|||||||
"wrangler": "4.94.0"
|
"wrangler": "4.94.0"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@hono/zod-openapi": "^1.4.0",
|
||||||
"@hono/zod-validator": "^0.8.0",
|
"@hono/zod-validator": "^0.8.0",
|
||||||
|
"@scalar/hono-api-reference": "^0.10.19",
|
||||||
"escape-html": "^1.0.3",
|
"escape-html": "^1.0.3",
|
||||||
"feed": "5.2.1",
|
"feed": "5.2.1",
|
||||||
"hono": "4.12.22",
|
"hono": "4.12.22",
|
||||||
|
|||||||
Executable
+151
@@ -0,0 +1,151 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
#
|
||||||
|
# Cut a release. Usage:
|
||||||
|
#
|
||||||
|
# npm run release X.Y.Z [NEXT_DEV_BASE]
|
||||||
|
#
|
||||||
|
# X.Y.Z the version to release (must equal main's current X.Y.Z-develop base)
|
||||||
|
# NEXT_DEV_BASE optional base to open next (defaults to next minor, e.g. 0.4.0 -> 0.5.0)
|
||||||
|
#
|
||||||
|
# It guards, then in one shot:
|
||||||
|
# 1. promotes CHANGELOG "## [Unreleased]" -> "## [X.Y.Z] - <date>"
|
||||||
|
# 2. sets package.json to the bare X.Y.Z and commits the release commit
|
||||||
|
# 3. tags vX.Y.Z on that commit
|
||||||
|
# 4. opens the next "-develop" cycle (package.json + fresh Unreleased) and commits
|
||||||
|
# 5. pushes main + the tag (after an explicit confirmation) -> triggers the Release workflow
|
||||||
|
#
|
||||||
|
# The tag points at a commit whose package.json reads exactly X.Y.Z, so the
|
||||||
|
# published bundle and the git history agree on the version. CI verifies the
|
||||||
|
# match and publishes the promoted CHANGELOG section as the release notes.
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
die() {
|
||||||
|
echo "release: $*" >&2
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
semver_re='^[0-9]+\.[0-9]+\.[0-9]+$'
|
||||||
|
|
||||||
|
VERSION="${1:-}"
|
||||||
|
[ -n "$VERSION" ] || die "missing version. Usage: npm run release X.Y.Z [NEXT_DEV_BASE]"
|
||||||
|
[[ "$VERSION" =~ $semver_re ]] || die "version '$VERSION' is not X.Y.Z"
|
||||||
|
|
||||||
|
# Default next dev base: bump the minor, reset patch.
|
||||||
|
if [ -n "${2:-}" ]; then
|
||||||
|
NEXT_BASE="$2"
|
||||||
|
[[ "$NEXT_BASE" =~ $semver_re ]] || die "next dev base '$NEXT_BASE' is not X.Y.Z"
|
||||||
|
else
|
||||||
|
IFS='.' read -r MA MI _PA <<<"$VERSION"
|
||||||
|
NEXT_BASE="${MA}.$((MI + 1)).0"
|
||||||
|
fi
|
||||||
|
NEXT_DEV="${NEXT_BASE}-develop"
|
||||||
|
|
||||||
|
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||||
|
cd "$ROOT"
|
||||||
|
|
||||||
|
# --- Guards ----------------------------------------------------------------
|
||||||
|
|
||||||
|
BRANCH="$(git rev-parse --abbrev-ref HEAD)"
|
||||||
|
[ "$BRANCH" = "main" ] || die "must be on 'main' (currently on '$BRANCH')"
|
||||||
|
|
||||||
|
[ -z "$(git status --porcelain)" ] || die "working tree is not clean — commit or stash first"
|
||||||
|
|
||||||
|
git fetch --quiet origin main || die "could not fetch origin/main"
|
||||||
|
LOCAL="$(git rev-parse @)"
|
||||||
|
REMOTE="$(git rev-parse '@{u}')"
|
||||||
|
[ "$LOCAL" = "$REMOTE" ] || die "local main is not in sync with origin/main — pull/push first"
|
||||||
|
|
||||||
|
PKG_BASE="$(node -p 'require("./package.json").version.split("-")[0]')"
|
||||||
|
[ "$PKG_BASE" = "$VERSION" ] || die "package.json base is $PKG_BASE, expected $VERSION — bump main to ${VERSION}-develop first (or release $PKG_BASE)"
|
||||||
|
|
||||||
|
git rev-parse -q --verify "refs/tags/v$VERSION" >/dev/null && die "tag v$VERSION already exists"
|
||||||
|
|
||||||
|
[ -f CHANGELOG.md ] || die "CHANGELOG.md not found"
|
||||||
|
# The Unreleased section must carry content — an empty changelog ships empty notes.
|
||||||
|
UNRELEASED_BODY="$(awk '
|
||||||
|
/^## \[Unreleased\]/ {grab=1; next}
|
||||||
|
/^## / && grab {exit}
|
||||||
|
grab {print}
|
||||||
|
' CHANGELOG.md | grep -v '^[[:space:]]*$' || true)"
|
||||||
|
[ -n "$UNRELEASED_BODY" ] || die "CHANGELOG '## [Unreleased]' is empty — write the release notes there first"
|
||||||
|
|
||||||
|
# --- Plan ------------------------------------------------------------------
|
||||||
|
|
||||||
|
DATE="$(date +%Y-%m-%d)"
|
||||||
|
echo "Release plan:"
|
||||||
|
echo " version : $VERSION (tag v$VERSION)"
|
||||||
|
echo " release date : $DATE"
|
||||||
|
echo " next cycle : $NEXT_DEV"
|
||||||
|
echo
|
||||||
|
echo "Unreleased notes that will become the v$VERSION release notes:"
|
||||||
|
echo "$UNRELEASED_BODY" | sed 's/^/ | /'
|
||||||
|
echo
|
||||||
|
read -r -p "Proceed (commits, tag, and PUSH to origin)? [y/N] " ANSWER
|
||||||
|
case "$ANSWER" in
|
||||||
|
y | Y | yes | YES) ;;
|
||||||
|
*) die "aborted" ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
# --- 1. Promote CHANGELOG Unreleased -> this version -----------------------
|
||||||
|
|
||||||
|
node - "$VERSION" "$DATE" <<'NODE'
|
||||||
|
const fs = require("fs");
|
||||||
|
const [version, date] = process.argv.slice(2);
|
||||||
|
const file = "CHANGELOG.md";
|
||||||
|
let text = fs.readFileSync(file, "utf8");
|
||||||
|
|
||||||
|
if (text.includes(`## [${version}]`)) {
|
||||||
|
console.error(`release: CHANGELOG already has a [${version}] section`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Replace the Unreleased heading with a fresh empty Unreleased + the new version.
|
||||||
|
text = text.replace(
|
||||||
|
/^## \[Unreleased\][^\n]*\n/m,
|
||||||
|
`## [Unreleased]\n\n## [${version}] - ${date}\n`,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Refresh the link reference block at the bottom, if present.
|
||||||
|
const repo = "https://github.com/juherr/kill-the-news";
|
||||||
|
const unreleasedLink = `[Unreleased]: ${repo}/compare/v${version}...HEAD`;
|
||||||
|
if (/^\[Unreleased\]:/m.test(text)) {
|
||||||
|
text = text.replace(
|
||||||
|
/^\[Unreleased\]:.*$/m,
|
||||||
|
`${unreleasedLink}\n[${version}]: ${repo}/compare/PREV...v${version}`,
|
||||||
|
);
|
||||||
|
// Best-effort: point the new version diff at the previous tagged version.
|
||||||
|
const prev = [...text.matchAll(/^\[(\d+\.\d+\.\d+)\]:/gm)]
|
||||||
|
.map((m) => m[1])
|
||||||
|
.find((v) => v !== version);
|
||||||
|
if (prev) {
|
||||||
|
text = text.replace("compare/PREV...", `compare/v${prev}...`);
|
||||||
|
} else {
|
||||||
|
text = text.replace(`/compare/PREV...v${version}`, `/releases/tag/v${version}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fs.writeFileSync(file, text);
|
||||||
|
console.log(`Updated CHANGELOG.md for ${version}`);
|
||||||
|
NODE
|
||||||
|
|
||||||
|
# --- 2. Release commit (bare version) + 3. tag -----------------------------
|
||||||
|
|
||||||
|
npm version "$VERSION" --no-git-tag-version --allow-same-version >/dev/null
|
||||||
|
git add package.json package-lock.json CHANGELOG.md
|
||||||
|
git commit -m "chore(release): $VERSION" >/dev/null
|
||||||
|
git tag "v$VERSION"
|
||||||
|
echo "Committed release v$VERSION and tagged it."
|
||||||
|
|
||||||
|
# --- 4. Open the next develop cycle ----------------------------------------
|
||||||
|
|
||||||
|
npm version "$NEXT_DEV" --no-git-tag-version >/dev/null
|
||||||
|
git add package.json package-lock.json
|
||||||
|
git commit -m "chore: open $NEXT_BASE develop cycle" >/dev/null
|
||||||
|
echo "Opened next cycle: $NEXT_DEV."
|
||||||
|
|
||||||
|
# --- 5. Push ----------------------------------------------------------------
|
||||||
|
|
||||||
|
git push origin main "v$VERSION"
|
||||||
|
echo
|
||||||
|
echo "Pushed main + v$VERSION. The Release workflow will publish the GitHub Release."
|
||||||
@@ -134,6 +134,34 @@ if [ -z "$domain" ]; then
|
|||||||
fi
|
fi
|
||||||
echo "✅ Domain: $domain"
|
echo "✅ Domain: $domain"
|
||||||
|
|
||||||
|
ENABLE_R2=false
|
||||||
|
R2_BUCKET=""
|
||||||
|
R2_PREVIEW_BUCKET=""
|
||||||
|
read -r -p "Enable email attachments stored in R2? [y/N]: " enable_r2
|
||||||
|
if [[ "$enable_r2" =~ ^[Yy]$ ]]; then
|
||||||
|
R2_BUCKET="${WORKER_NAME}-attachments"
|
||||||
|
R2_PREVIEW_BUCKET="${R2_BUCKET}-preview"
|
||||||
|
echo "🪣 Creating R2 buckets..."
|
||||||
|
set +e
|
||||||
|
R2_OUT="$(npx wrangler r2 bucket create "$R2_BUCKET" 2>&1)"
|
||||||
|
R2_STATUS=$?
|
||||||
|
R2_PREVIEW_OUT="$(npx wrangler r2 bucket create "$R2_PREVIEW_BUCKET" 2>&1)"
|
||||||
|
R2_PREVIEW_STATUS=$?
|
||||||
|
set -e
|
||||||
|
# An existing bucket is fine; only treat real failures as blocking.
|
||||||
|
echo "$R2_OUT" | grep -qi "already exists" && R2_STATUS=0
|
||||||
|
echo "$R2_PREVIEW_OUT" | grep -qi "already exists" && R2_PREVIEW_STATUS=0
|
||||||
|
if [ "$R2_STATUS" -eq 0 ] && [ "$R2_PREVIEW_STATUS" -eq 0 ]; then
|
||||||
|
ENABLE_R2=true
|
||||||
|
echo " ✅ R2 bucket: $R2_BUCKET"
|
||||||
|
echo " ✅ R2 preview bucket: $R2_PREVIEW_BUCKET"
|
||||||
|
else
|
||||||
|
echo " ⚠️ Could not create R2 buckets (is R2 enabled on your account?)."
|
||||||
|
echo " Attachments will stay disabled — see INSTALL.md → 'Email attachments (R2)'."
|
||||||
|
echo "$R2_OUT"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
escape_sed_replacement() {
|
escape_sed_replacement() {
|
||||||
printf '%s' "$1" | sed -e 's/[\/&]/\\&/g'
|
printf '%s' "$1" | sed -e 's/[\/&]/\\&/g'
|
||||||
}
|
}
|
||||||
@@ -158,8 +186,26 @@ else
|
|||||||
sed -i "s/REPLACE_WITH_COMPATIBILITY_DATE/$COMPATIBILITY_DATE_ESCAPED/g" wrangler.toml
|
sed -i "s/REPLACE_WITH_COMPATIBILITY_DATE/$COMPATIBILITY_DATE_ESCAPED/g" wrangler.toml
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
if [ "$ENABLE_R2" = true ]; then
|
||||||
|
echo "🔗 Enabling R2 attachment binding in wrangler.toml..."
|
||||||
|
node - "wrangler.toml" "$R2_BUCKET" "$R2_PREVIEW_BUCKET" <<'NODE'
|
||||||
|
const fs = require("node:fs");
|
||||||
|
const [file, bucket, previewBucket] = process.argv.slice(2);
|
||||||
|
let txt = fs.readFileSync(file, "utf8");
|
||||||
|
txt = txt.split("REPLACE_WITH_YOUR_PREVIEW_BUCKET_NAME").join(previewBucket);
|
||||||
|
txt = txt.split("REPLACE_WITH_YOUR_BUCKET_NAME").join(bucket);
|
||||||
|
// Uncomment the commented r2_buckets blocks (global + [env.production]).
|
||||||
|
txt = txt.replace(
|
||||||
|
/# r2_buckets = \[\n#(\s+\{ binding = "ATTACHMENT_BUCKET".*\})\n# \]/g,
|
||||||
|
'r2_buckets = [\n$1\n]',
|
||||||
|
);
|
||||||
|
fs.writeFileSync(file, txt);
|
||||||
|
NODE
|
||||||
|
echo " ✅ ATTACHMENT_BUCKET bound to $R2_BUCKET"
|
||||||
|
fi
|
||||||
|
|
||||||
echo "✅ wrangler.toml has been created and configured successfully!"
|
echo "✅ wrangler.toml has been created and configured successfully!"
|
||||||
echo ""
|
echo ""
|
||||||
echo "✅ Setup complete! Next steps:"
|
echo "✅ Setup complete! Next steps:"
|
||||||
echo "1. Set up MX records for your domain with ForwardEmail.net (see README for details)"
|
echo "1. Configure email ingestion — Cloudflare Email Workers or ForwardEmail (see INSTALL.md for details)"
|
||||||
echo "2. Deploy with 'npm run deploy'"
|
echo "2. Deploy with 'npm run deploy'"
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,306 @@
|
|||||||
|
import { MailboxId } from "../domain/value-objects/mailbox-id";
|
||||||
|
import { EmailAddress } from "../domain/value-objects/email-address";
|
||||||
|
import { AttachmentData, EmailMetadata, Env } from "../types";
|
||||||
|
import { bumpCounters } from "../application/stats";
|
||||||
|
import { dispatchFeedEvents } from "../application/feed-events";
|
||||||
|
import { parseOneClickUnsubscribe } from "../infrastructure/unsubscribe";
|
||||||
|
import { getAttachmentBucket } from "../infrastructure/attachments";
|
||||||
|
import {
|
||||||
|
extractFeedLinks,
|
||||||
|
extractInlineCids,
|
||||||
|
extractLinks,
|
||||||
|
htmlToText,
|
||||||
|
} from "../infrastructure/html-processor";
|
||||||
|
import { detectConfirmation } from "../domain/confirmation";
|
||||||
|
import { detectNativeFeeds } from "../domain/native-feed";
|
||||||
|
import { attachmentIdsForCleanup } from "./feed-cleanup";
|
||||||
|
import { FeedRepository } from "../infrastructure/feed-repository";
|
||||||
|
import { BackgroundScheduler } from "../infrastructure/worker";
|
||||||
|
import { Feed } from "../domain/feed.aggregate";
|
||||||
|
import { logger } from "../infrastructure/logger";
|
||||||
|
import { FEED_MAX_BYTES } from "../config/constants";
|
||||||
|
|
||||||
|
export interface RawAttachment {
|
||||||
|
filename: string;
|
||||||
|
contentType: string;
|
||||||
|
content: ArrayBuffer;
|
||||||
|
contentId?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ProcessEmailInput {
|
||||||
|
toAddress: string;
|
||||||
|
from: string;
|
||||||
|
senders: string[];
|
||||||
|
subject: string;
|
||||||
|
content: string;
|
||||||
|
receivedAt: number;
|
||||||
|
headers?: Record<string, string>;
|
||||||
|
attachments?: RawAttachment[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export type IngestRejectionReason =
|
||||||
|
| "invalid_address"
|
||||||
|
| "mailbox_unknown"
|
||||||
|
| "feed_not_found"
|
||||||
|
| "feed_expired"
|
||||||
|
| "sender_blocked";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Outcome of ingesting an email — a domain result, not an HTTP concern. The edge
|
||||||
|
* (forwardemail.ts) maps this to a status code; the Cloudflare email handler
|
||||||
|
* logs the reason. Keeping HTTP out of the core keeps ingestion transport-agnostic.
|
||||||
|
*/
|
||||||
|
export type IngestResult =
|
||||||
|
| { ok: true; feedId: string }
|
||||||
|
| { ok: false; reason: IngestRejectionReason };
|
||||||
|
|
||||||
|
async function uploadAttachments(
|
||||||
|
attachments: RawAttachment[],
|
||||||
|
bucket: R2Bucket,
|
||||||
|
inlineCids: Set<string>,
|
||||||
|
): Promise<AttachmentData[]> {
|
||||||
|
return Promise.all(
|
||||||
|
attachments.map(async (att) => {
|
||||||
|
const id = crypto.randomUUID();
|
||||||
|
const inline = att.contentId ? inlineCids.has(att.contentId) : false;
|
||||||
|
await bucket.put(id, att.content, {
|
||||||
|
httpMetadata: {
|
||||||
|
contentType: att.contentType,
|
||||||
|
contentDisposition: `${inline ? "inline" : "attachment"}; filename="${att.filename}"`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
filename: att.filename,
|
||||||
|
contentType: att.contentType,
|
||||||
|
size: att.content.byteLength,
|
||||||
|
...(att.contentId ? { contentId: att.contentId } : {}),
|
||||||
|
...(inline ? { inline: true } : {}),
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadAcceptingFeed(
|
||||||
|
input: ProcessEmailInput,
|
||||||
|
env: Env,
|
||||||
|
): Promise<
|
||||||
|
{ ok: true; feed: Feed } | { ok: false; reason: IngestRejectionReason }
|
||||||
|
> {
|
||||||
|
// MailboxId.parse is the single boundary where an untrusted inbound address
|
||||||
|
// (the most untrusted input in the system) becomes a validated mailbox.
|
||||||
|
const mailbox = MailboxId.parse(input.toAddress);
|
||||||
|
if (!mailbox) {
|
||||||
|
logger.error("Invalid email address format", {
|
||||||
|
toAddress: input.toAddress,
|
||||||
|
});
|
||||||
|
return { ok: false, reason: "invalid_address" };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve the inbound mailbox to the feed's opaque id (decoupled identities).
|
||||||
|
const repo = FeedRepository.from(env);
|
||||||
|
const feedId = await repo.resolveInbound(mailbox);
|
||||||
|
if (!feedId) {
|
||||||
|
// No feed claims this address — the common "wrong/unknown alias" case.
|
||||||
|
logger.error("Unknown inbound mailbox", { mailbox: mailbox.value });
|
||||||
|
return { ok: false, reason: "mailbox_unknown" };
|
||||||
|
}
|
||||||
|
|
||||||
|
const feed = await repo.load(feedId);
|
||||||
|
if (!feed) {
|
||||||
|
// The index resolved but the feed is gone — a dangling index (should be
|
||||||
|
// near-impossible now the index is dropped on feed deletion).
|
||||||
|
logger.error("Feed not found", {
|
||||||
|
mailbox: mailbox.value,
|
||||||
|
feedId: feedId.value,
|
||||||
|
});
|
||||||
|
return { ok: false, reason: "feed_not_found" };
|
||||||
|
}
|
||||||
|
if (feed.isExpired()) {
|
||||||
|
logger.warn("Rejected email: feed expired", { feedId: feedId.value });
|
||||||
|
return { ok: false, reason: "feed_expired" };
|
||||||
|
}
|
||||||
|
if (feed.accepts(input.senders) === "blocked") {
|
||||||
|
logger.warn("Rejected email: sender filter", {
|
||||||
|
feedId: feedId.value,
|
||||||
|
senders: input.senders,
|
||||||
|
allowedSenders: feed.allowedSenders(),
|
||||||
|
blockedSenders: feed.blockedSenders(),
|
||||||
|
});
|
||||||
|
return { ok: false, reason: "sender_blocked" };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { ok: true, feed };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compute a SHA-256 hex digest of a normalised string combining subject and
|
||||||
|
* content. Used as a dedup fallback when no Message-ID header is present.
|
||||||
|
* "Normalised" means lower-cased and all whitespace runs collapsed to a single
|
||||||
|
* space — so minor whitespace differences in re-sent mails still match.
|
||||||
|
*/
|
||||||
|
async function computeDedupHash(
|
||||||
|
subject: string,
|
||||||
|
content: string,
|
||||||
|
): Promise<string> {
|
||||||
|
const normalize = (s: string) => s.toLowerCase().replace(/\s+/g, " ").trim();
|
||||||
|
const raw = `${normalize(subject)}\n${normalize(content)}`;
|
||||||
|
const buf = await crypto.subtle.digest(
|
||||||
|
"SHA-256",
|
||||||
|
new TextEncoder().encode(raw),
|
||||||
|
);
|
||||||
|
return Array.from(new Uint8Array(buf))
|
||||||
|
.map((b) => b.toString(16).padStart(2, "0"))
|
||||||
|
.join("");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extract the Message-ID from request headers (case-insensitive key lookup).
|
||||||
|
* Returns undefined when absent or empty.
|
||||||
|
*/
|
||||||
|
function extractMessageId(
|
||||||
|
headers: Record<string, string> | undefined,
|
||||||
|
): string | undefined {
|
||||||
|
if (!headers) return undefined;
|
||||||
|
const value = Object.entries(headers).find(
|
||||||
|
([k]) => k.toLowerCase() === "message-id",
|
||||||
|
)?.[1];
|
||||||
|
const trimmed = value?.trim();
|
||||||
|
return trimmed || undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function storeEmail(
|
||||||
|
feed: Feed,
|
||||||
|
input: ProcessEmailInput,
|
||||||
|
env: Env,
|
||||||
|
ctx?: ExecutionContext,
|
||||||
|
): Promise<boolean> {
|
||||||
|
// ── Dedup check ──────────────────────────────────────────────────────────
|
||||||
|
// Compute both dedup signals up-front (hash is async) so we only do it once.
|
||||||
|
const messageId = extractMessageId(input.headers);
|
||||||
|
const dedupHash = await computeDedupHash(input.subject, input.content);
|
||||||
|
|
||||||
|
if (feed.hasDuplicate(messageId, dedupHash)) {
|
||||||
|
logger.info("Duplicate email skipped", {
|
||||||
|
feedId: feed.id.value,
|
||||||
|
...(messageId ? { messageId } : { dedupHash }),
|
||||||
|
});
|
||||||
|
await bumpCounters(env.EMAIL_STORAGE, { emails_deduplicated: 1 });
|
||||||
|
return false; // signal: skipped (not stored)
|
||||||
|
}
|
||||||
|
|
||||||
|
const confirmationLinks = detectConfirmation({
|
||||||
|
subject: input.subject,
|
||||||
|
text: htmlToText(input.content),
|
||||||
|
links: extractLinks(input.content),
|
||||||
|
});
|
||||||
|
|
||||||
|
const sender = EmailAddress.parse(input.from);
|
||||||
|
const nativeFeedList = detectNativeFeeds(
|
||||||
|
extractFeedLinks(input.content, sender?.siteBaseUrl() ?? ""),
|
||||||
|
);
|
||||||
|
|
||||||
|
const attachmentBucket = getAttachmentBucket(env);
|
||||||
|
const inlineCids = extractInlineCids(input.content);
|
||||||
|
const storedAttachments: AttachmentData[] =
|
||||||
|
attachmentBucket && input.attachments?.length
|
||||||
|
? await uploadAttachments(input.attachments, attachmentBucket, inlineCids)
|
||||||
|
: [];
|
||||||
|
|
||||||
|
const emailData = {
|
||||||
|
subject: input.subject,
|
||||||
|
from: input.from,
|
||||||
|
content: input.content,
|
||||||
|
receivedAt: input.receivedAt,
|
||||||
|
headers: input.headers ?? {},
|
||||||
|
...(storedAttachments.length > 0 ? { attachments: storedAttachments } : {}),
|
||||||
|
};
|
||||||
|
|
||||||
|
const repo = FeedRepository.from(env);
|
||||||
|
const emailKey = repo.newEmailKey(feed.id);
|
||||||
|
await repo.putEmail(emailKey, emailData);
|
||||||
|
|
||||||
|
const serialisedSize = new TextEncoder().encode(
|
||||||
|
JSON.stringify(emailData),
|
||||||
|
).byteLength;
|
||||||
|
const downloadableIds = storedAttachments
|
||||||
|
.filter((a) => !a.inline)
|
||||||
|
.map((a) => a.id);
|
||||||
|
const inlineIds = storedAttachments.filter((a) => a.inline).map((a) => a.id);
|
||||||
|
const newEntry: EmailMetadata = {
|
||||||
|
key: emailKey,
|
||||||
|
subject: emailData.subject,
|
||||||
|
receivedAt: emailData.receivedAt,
|
||||||
|
size: serialisedSize,
|
||||||
|
...(downloadableIds.length > 0 ? { attachmentIds: downloadableIds } : {}),
|
||||||
|
...(inlineIds.length > 0 ? { inlineAttachmentIds: inlineIds } : {}),
|
||||||
|
...(messageId ? { messageId } : {}),
|
||||||
|
dedupHash,
|
||||||
|
...(confirmationLinks
|
||||||
|
? { confirmation: { links: confirmationLinks } }
|
||||||
|
: {}),
|
||||||
|
};
|
||||||
|
|
||||||
|
// Track the latest sender's domain (feed icon) and capture the RFC 8058
|
||||||
|
// one-click unsubscribe link, keyed by sender so each newsletter keeps its
|
||||||
|
// own latest URL (fired when the feed is deleted).
|
||||||
|
const iconDomain = sender?.domain.value;
|
||||||
|
const senderKey = input.senders[0] || iconDomain || input.from;
|
||||||
|
const unsubUrl = parseOneClickUnsubscribe(input.headers ?? {});
|
||||||
|
const unsub = unsubUrl ? { senderKey, url: unsubUrl } : undefined;
|
||||||
|
|
||||||
|
const maxBytes =
|
||||||
|
parseInt(env.FEED_MAX_SIZE_BYTES ?? "", 10) || FEED_MAX_BYTES;
|
||||||
|
|
||||||
|
const { dropped } = feed.ingest(newEntry, {
|
||||||
|
maxBytes,
|
||||||
|
iconDomain: iconDomain ?? undefined,
|
||||||
|
unsub,
|
||||||
|
...(nativeFeedList.length > 0
|
||||||
|
? { nativeFeeds: { senderKey, feeds: nativeFeedList } }
|
||||||
|
: {}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const r2Deletions =
|
||||||
|
attachmentBucket && dropped.length > 0
|
||||||
|
? dropped
|
||||||
|
.flatMap((e) => attachmentIdsForCleanup(e))
|
||||||
|
.map((id) => attachmentBucket.delete(id))
|
||||||
|
: [];
|
||||||
|
|
||||||
|
// KV has no compare-and-swap: the load (in loadAcceptingFeed) and this write
|
||||||
|
// are not serialised, so concurrent ingests for one feed can lose updates.
|
||||||
|
// Accepted under KV's eventual-consistency model; the Feed aggregate is the
|
||||||
|
// seam a Durable Object would later wrap to serialise these writers.
|
||||||
|
await Promise.all([
|
||||||
|
repo.saveMetadata(feed),
|
||||||
|
...dropped.map((e) => repo.deleteEmail(e.key)),
|
||||||
|
...r2Deletions,
|
||||||
|
]);
|
||||||
|
|
||||||
|
logger.info("Email processed", { feedId: feed.id.value });
|
||||||
|
|
||||||
|
// The aggregate recorded an EmailIngested event; the dispatcher applies its
|
||||||
|
// side effects (received counter, WebSub ping, favicon fetch). Background work
|
||||||
|
// rides on ctx.waitUntil when present, and is skipped in its absence (tests).
|
||||||
|
const schedule: BackgroundScheduler = ctx
|
||||||
|
? (p) => ctx.waitUntil(p)
|
||||||
|
: () => {};
|
||||||
|
await dispatchFeedEvents(feed, env, schedule);
|
||||||
|
return true; // signal: stored
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function processEmail(
|
||||||
|
input: ProcessEmailInput,
|
||||||
|
env: Env,
|
||||||
|
ctx?: ExecutionContext,
|
||||||
|
): Promise<IngestResult> {
|
||||||
|
const validation = await loadAcceptingFeed(input, env);
|
||||||
|
if (!validation.ok) {
|
||||||
|
await bumpCounters(env.EMAIL_STORAGE, { emails_rejected: 1 });
|
||||||
|
return validation;
|
||||||
|
}
|
||||||
|
|
||||||
|
await storeEmail(validation.feed, input, env, ctx);
|
||||||
|
return { ok: true, feedId: validation.feed.id.value };
|
||||||
|
}
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
import { EmailData, EmailMetadata, Env } from "../types";
|
||||||
|
import { logger } from "../infrastructure/logger";
|
||||||
|
import { getAttachmentBucket } from "../infrastructure/attachments";
|
||||||
|
import { FeedRepository } from "../infrastructure/feed-repository";
|
||||||
|
import { FeedId } from "../domain/value-objects/feed-id";
|
||||||
|
|
||||||
|
// All R2 object ids an email owns — both downloadable attachments and inline
|
||||||
|
// images. Inline images are hidden from the user-facing lists but must still be
|
||||||
|
// purged from the bucket when the email is deleted.
|
||||||
|
export function attachmentIdsForCleanup(e: EmailMetadata): string[] {
|
||||||
|
return [...(e.attachmentIds ?? []), ...(e.inlineAttachmentIds ?? [])];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete the R2 attachments belonging to the given email keys. Call before the
|
||||||
|
// emails are removed from feed metadata, while `emails` still carries their
|
||||||
|
// attachment ids.
|
||||||
|
export async function deleteAttachmentsForEmails(
|
||||||
|
env: Env,
|
||||||
|
emails: readonly EmailMetadata[],
|
||||||
|
keys: Iterable<string>,
|
||||||
|
): Promise<void> {
|
||||||
|
const keySet = new Set(keys);
|
||||||
|
const attachmentIds = emails
|
||||||
|
.filter((e) => keySet.has(e.key))
|
||||||
|
.flatMap((e) => attachmentIdsForCleanup(e));
|
||||||
|
if (attachmentIds.length === 0) return;
|
||||||
|
|
||||||
|
const bucket = getAttachmentBucket(env);
|
||||||
|
if (!bucket) return;
|
||||||
|
|
||||||
|
await Promise.allSettled(attachmentIds.map((id) => bucket.delete(id)));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteKeysWithConcurrency(
|
||||||
|
emailStorage: KVNamespace,
|
||||||
|
keys: string[],
|
||||||
|
concurrency: number,
|
||||||
|
): Promise<{ ok: string[]; failed: string[] }> {
|
||||||
|
const uniqueKeys = Array.from(new Set(keys.filter(Boolean)));
|
||||||
|
const ok: string[] = [];
|
||||||
|
const failed: string[] = [];
|
||||||
|
const limit = Math.max(1, Math.floor(concurrency) || 1);
|
||||||
|
|
||||||
|
for (let i = 0; i < uniqueKeys.length; i += limit) {
|
||||||
|
const batch = uniqueKeys.slice(i, i + limit);
|
||||||
|
const results = await Promise.allSettled(
|
||||||
|
batch.map((key) => emailStorage.delete(key)),
|
||||||
|
);
|
||||||
|
results.forEach((result, idx) => {
|
||||||
|
const key = batch[idx];
|
||||||
|
if (result.status === "fulfilled") {
|
||||||
|
ok.push(key);
|
||||||
|
} else {
|
||||||
|
failed.push(key);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return { ok, failed };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read a feed's stored RFC 8058 one-click unsubscribe URLs (one per sender).
|
||||||
|
* Must be called before the feed metadata is deleted. Never throws.
|
||||||
|
*/
|
||||||
|
export async function collectUnsubscribeUrls(
|
||||||
|
emailStorage: KVNamespace,
|
||||||
|
feedId: FeedId,
|
||||||
|
): Promise<string[]> {
|
||||||
|
try {
|
||||||
|
const metadata = await new FeedRepository(emailStorage).getMetadata(feedId);
|
||||||
|
return Object.values(metadata?.unsubscribe ?? {});
|
||||||
|
} catch (error) {
|
||||||
|
logger.error("Error reading unsubscribe URLs", {
|
||||||
|
feedId: feedId.value,
|
||||||
|
error: String(error),
|
||||||
|
});
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function purgeFeedKeysStep(
|
||||||
|
emailStorage: KVNamespace,
|
||||||
|
feedId: FeedId,
|
||||||
|
options: { cursor?: string; limit?: number; bucket?: R2Bucket } = {},
|
||||||
|
): Promise<{
|
||||||
|
deletedKeys: string[];
|
||||||
|
failedKeys: string[];
|
||||||
|
cursor: string;
|
||||||
|
listComplete: boolean;
|
||||||
|
}> {
|
||||||
|
const repo = new FeedRepository(emailStorage);
|
||||||
|
const listed = await repo.listFeedKeys(feedId, {
|
||||||
|
cursor: options.cursor,
|
||||||
|
limit: options.limit,
|
||||||
|
});
|
||||||
|
const keys = listed.names;
|
||||||
|
|
||||||
|
if (options.bucket && keys.length > 0) {
|
||||||
|
const emailKeys = keys.filter((k) => repo.isEmailKey(feedId, k));
|
||||||
|
if (emailKeys.length > 0) {
|
||||||
|
const emailDataResults = await Promise.allSettled(
|
||||||
|
emailKeys.map((k) => repo.getEmail(k)),
|
||||||
|
);
|
||||||
|
const attachmentIds = emailDataResults
|
||||||
|
.filter(
|
||||||
|
(r): r is PromiseFulfilledResult<EmailData | null> =>
|
||||||
|
r.status === "fulfilled",
|
||||||
|
)
|
||||||
|
.flatMap((r) => r.value?.attachments?.map((a) => a.id) ?? []);
|
||||||
|
if (attachmentIds.length > 0) {
|
||||||
|
await Promise.allSettled(
|
||||||
|
attachmentIds.map((id) => options.bucket!.delete(id)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const { ok, failed } = await deleteKeysWithConcurrency(
|
||||||
|
emailStorage,
|
||||||
|
keys,
|
||||||
|
35,
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
deletedKeys: ok,
|
||||||
|
failedKeys: failed,
|
||||||
|
cursor: listed.cursor,
|
||||||
|
listComplete: listed.listComplete,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function purgeExpiredFeeds(
|
||||||
|
emailStorage: KVNamespace,
|
||||||
|
feedId: FeedId,
|
||||||
|
bucket?: R2Bucket,
|
||||||
|
): Promise<void> {
|
||||||
|
let cursor: string | undefined;
|
||||||
|
do {
|
||||||
|
const step = await purgeFeedKeysStep(emailStorage, feedId, {
|
||||||
|
bucket,
|
||||||
|
limit: 100,
|
||||||
|
cursor,
|
||||||
|
});
|
||||||
|
cursor = step.listComplete ? undefined : step.cursor;
|
||||||
|
} while (cursor);
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import { Env } from "../types";
|
||||||
|
import { FeedEvent } from "../domain/events";
|
||||||
|
import { Feed } from "../domain/feed.aggregate";
|
||||||
|
import { BackgroundScheduler } from "../infrastructure/worker";
|
||||||
|
import { bumpCounters } from "./stats";
|
||||||
|
import { notifySubscribers } from "../infrastructure/websub";
|
||||||
|
import { cacheFaviconForDomain } from "../infrastructure/favicon-fetcher";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Apply the side effects of a feed's domain events — the single place that maps
|
||||||
|
* "what happened" (FeedCreated, EmailIngested) to its consequences. Each event
|
||||||
|
* carries its own `feedId`, so nothing has to be threaded in. Counter writes are
|
||||||
|
* awaited (they must land); WebSub pings and favicon fetches are handed to the
|
||||||
|
* caller's background scheduler (`ctx.waitUntil` at the edge, a no-op when none
|
||||||
|
* is available).
|
||||||
|
*/
|
||||||
|
export async function applyFeedEvents(
|
||||||
|
events: FeedEvent[],
|
||||||
|
env: Env,
|
||||||
|
schedule: BackgroundScheduler,
|
||||||
|
): Promise<void> {
|
||||||
|
for (const event of events) {
|
||||||
|
switch (event.type) {
|
||||||
|
case "FeedCreated":
|
||||||
|
await bumpCounters(env.EMAIL_STORAGE, {
|
||||||
|
feeds_created: 1,
|
||||||
|
last_feed_created_at: new Date().toISOString(),
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
case "EmailIngested":
|
||||||
|
await bumpCounters(env.EMAIL_STORAGE, {
|
||||||
|
emails_received: 1,
|
||||||
|
last_email_at: new Date().toISOString(),
|
||||||
|
});
|
||||||
|
schedule(notifySubscribers(event.feedId, env));
|
||||||
|
if (event.iconDomain) {
|
||||||
|
schedule(cacheFaviconForDomain(event.iconDomain, env));
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Drain a freshly-persisted aggregate's events and apply their side effects. The
|
||||||
|
* single dispatch entry point: callers persist the `Feed`, then call this — no
|
||||||
|
* caller pulls events or passes the feed id by hand.
|
||||||
|
*/
|
||||||
|
export async function dispatchFeedEvents(
|
||||||
|
feed: Feed,
|
||||||
|
env: Env,
|
||||||
|
schedule: BackgroundScheduler,
|
||||||
|
): Promise<void> {
|
||||||
|
await applyFeedEvents(feed.pullEvents(), env, schedule);
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { Env, FeedConfig, EmailData } from "../types";
|
||||||
|
import { MAX_FEED_ITEMS } from "../config/constants";
|
||||||
|
import { FeedRepository } from "../infrastructure/feed-repository";
|
||||||
|
import { FeedId } from "../domain/value-objects/feed-id";
|
||||||
|
|
||||||
|
export interface FeedData {
|
||||||
|
feedConfig: FeedConfig;
|
||||||
|
emails: EmailData[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchFeedData(
|
||||||
|
feedId: FeedId,
|
||||||
|
env: Env,
|
||||||
|
): Promise<FeedData | null> {
|
||||||
|
const repo = FeedRepository.from(env);
|
||||||
|
|
||||||
|
const feedMetadata = await repo.getMetadata(feedId);
|
||||||
|
if (!feedMetadata) return null;
|
||||||
|
|
||||||
|
const feedConfig = (await repo.getConfig(feedId)) ?? {
|
||||||
|
title: `Newsletter Feed ${feedId.value}`,
|
||||||
|
description: "Converted email newsletter",
|
||||||
|
language: "en",
|
||||||
|
// Read-model fallback only: the RSS/Atom/JSON path never builds the inbound
|
||||||
|
// address, so an empty mailbox is inert here (the real one lives on config).
|
||||||
|
mailbox_id: "",
|
||||||
|
created_at: Date.now(),
|
||||||
|
};
|
||||||
|
|
||||||
|
const emailRefs = feedMetadata.emails.slice(0, MAX_FEED_ITEMS);
|
||||||
|
const emails: EmailData[] = [];
|
||||||
|
for (const ref of emailRefs) {
|
||||||
|
const data = await repo.getEmail(ref.key);
|
||||||
|
if (data) emails.push(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { feedConfig, emails };
|
||||||
|
}
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import { createMockEnv } from "../test/setup";
|
||||||
|
import {
|
||||||
|
createFeedRecord,
|
||||||
|
editFeed,
|
||||||
|
deleteFeedRecord,
|
||||||
|
deleteFeedFastDetailed,
|
||||||
|
} from "./feed-service";
|
||||||
|
import { getCounters } from "./stats";
|
||||||
|
import { FeedRepository } from "../infrastructure/feed-repository";
|
||||||
|
import { FeedId } from "../domain/value-objects/feed-id";
|
||||||
|
import { MailboxId } from "../domain/value-objects/mailbox-id";
|
||||||
|
import type { Env } from "../types";
|
||||||
|
|
||||||
|
const mkEnv = (overrides: Partial<Env> = {}) =>
|
||||||
|
({ ...createMockEnv(), ...overrides }) as unknown as Env;
|
||||||
|
|
||||||
|
const baseInput = {
|
||||||
|
title: "N",
|
||||||
|
language: "en",
|
||||||
|
allowedSenders: [],
|
||||||
|
blockedSenders: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
const TWO_HOURS = 2 * 3_600_000;
|
||||||
|
|
||||||
|
// The lifetime policy (parse env, apply the server-side FEED_TTL_HOURS override)
|
||||||
|
// lives here in the application layer; the domain only receives a resolved
|
||||||
|
// ttlHours. These tests pin that policy at the public service boundary.
|
||||||
|
describe("createFeedRecord — TTL policy", () => {
|
||||||
|
it("never expires when neither server nor client lifetime is set", async () => {
|
||||||
|
const { config } = await createFeedRecord(mkEnv(), { ...baseInput });
|
||||||
|
expect(config.expires_at).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("uses the client lifetimeHours when there is no server override", async () => {
|
||||||
|
const before = Date.now();
|
||||||
|
const { config } = await createFeedRecord(mkEnv(), {
|
||||||
|
...baseInput,
|
||||||
|
lifetimeHours: 2,
|
||||||
|
});
|
||||||
|
expect(config.expires_at!).toBeGreaterThanOrEqual(before + TWO_HOURS);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("lets a server FEED_TTL_HOURS override a larger client lifetime", async () => {
|
||||||
|
const before = Date.now();
|
||||||
|
const { config } = await createFeedRecord(mkEnv({ FEED_TTL_HOURS: "1" }), {
|
||||||
|
...baseInput,
|
||||||
|
lifetimeHours: 9999,
|
||||||
|
});
|
||||||
|
// 1h (server) wins over 9999h (client).
|
||||||
|
expect(config.expires_at!).toBeLessThan(before + TWO_HOURS);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("bumps the feeds_created counter via the FeedCreated domain event", async () => {
|
||||||
|
const env = mkEnv();
|
||||||
|
await createFeedRecord(env, { ...baseInput });
|
||||||
|
const counters = await getCounters(env.EMAIL_STORAGE);
|
||||||
|
expect(counters.feeds_created).toBe(1);
|
||||||
|
expect(counters.last_feed_created_at).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("deleting a feed drops its inbound mailbox index", () => {
|
||||||
|
it("deleteFeedRecord removes the inbound index so the address stops resolving", async () => {
|
||||||
|
const env = mkEnv();
|
||||||
|
const { feedId, mailboxId } = await createFeedRecord(env, { ...baseInput });
|
||||||
|
const repo = FeedRepository.from(env);
|
||||||
|
|
||||||
|
// Sanity: the address resolves to the feed before deletion.
|
||||||
|
expect(
|
||||||
|
(await repo.resolveInbound(MailboxId.unchecked(mailboxId)))?.value,
|
||||||
|
).toBe(feedId);
|
||||||
|
|
||||||
|
await deleteFeedRecord(env, FeedId.unchecked(feedId), () => {});
|
||||||
|
|
||||||
|
expect(
|
||||||
|
await repo.resolveInbound(MailboxId.unchecked(mailboxId)),
|
||||||
|
).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("the bulk path (deleteFeedFastDetailed + removeFromListBulk) clears the inbound index", async () => {
|
||||||
|
const env = mkEnv();
|
||||||
|
const { feedId, mailboxId } = await createFeedRecord(env, { ...baseInput });
|
||||||
|
const repo = FeedRepository.from(env);
|
||||||
|
|
||||||
|
// The bulk admin path drops config/metadata, then removes from the list —
|
||||||
|
// the latter is what clears the inbound index (symmetric with save()).
|
||||||
|
await deleteFeedFastDetailed(env.EMAIL_STORAGE, FeedId.unchecked(feedId));
|
||||||
|
await repo.removeFromListBulk([feedId]);
|
||||||
|
|
||||||
|
expect(
|
||||||
|
await repo.resolveInbound(MailboxId.unchecked(mailboxId)),
|
||||||
|
).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("editFeed — TTL policy", () => {
|
||||||
|
it("recomputes expiry from the server override on edit", async () => {
|
||||||
|
const env = mkEnv({ FEED_TTL_HOURS: "1" });
|
||||||
|
const { feedId } = await createFeedRecord(env, { ...baseInput });
|
||||||
|
|
||||||
|
const before = Date.now();
|
||||||
|
const result = await editFeed(env, FeedId.unchecked(feedId), {
|
||||||
|
title: "renamed",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.status).toBe("ok");
|
||||||
|
if (result.status === "ok") {
|
||||||
|
expect(result.config.title).toBe("renamed");
|
||||||
|
expect(result.config.expires_at!).toBeLessThan(before + TWO_HOURS);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("preserves expiry when neither server TTL nor client lifetime is given", async () => {
|
||||||
|
const env = mkEnv();
|
||||||
|
const { feedId, config } = await createFeedRecord(env, {
|
||||||
|
...baseInput,
|
||||||
|
lifetimeHours: 5,
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await editFeed(env, FeedId.unchecked(feedId), {
|
||||||
|
title: "x",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.status).toBe("ok");
|
||||||
|
if (result.status === "ok") {
|
||||||
|
expect(result.config.expires_at).toBe(config.expires_at);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,197 @@
|
|||||||
|
import { Env, FeedConfig } from "../types";
|
||||||
|
import { bumpCounters } from "../application/stats";
|
||||||
|
import { dispatchFeedEvents } from "./feed-events";
|
||||||
|
import { sendUnsubscribes } from "../infrastructure/unsubscribe";
|
||||||
|
import { getAttachmentBucket } from "../infrastructure/attachments";
|
||||||
|
import { FeedRepository } from "../infrastructure/feed-repository";
|
||||||
|
import { toConfigDTO } from "../infrastructure/feed-mapper";
|
||||||
|
import { BackgroundScheduler } from "../infrastructure/worker";
|
||||||
|
import { FeedId } from "../domain/value-objects/feed-id";
|
||||||
|
import { MailboxId } from "../domain/value-objects/mailbox-id";
|
||||||
|
import { Lifetime } from "../domain/value-objects/lifetime";
|
||||||
|
import {
|
||||||
|
Feed,
|
||||||
|
CreateFeedInput,
|
||||||
|
UpdateFeedInput,
|
||||||
|
} from "../domain/feed.aggregate";
|
||||||
|
import { purgeFeedKeysStep, collectUnsubscribeUrls } from "./feed-cleanup";
|
||||||
|
|
||||||
|
export type { CreateFeedInput, UpdateFeedInput };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve the effective feed `Lifetime` from a client request and the
|
||||||
|
* server-side `FEED_TTL_HOURS` override. Parsing the env string and applying the
|
||||||
|
* override is application/config policy — the domain only receives the resolved
|
||||||
|
* VO. Returns `Lifetime.never` when the feed should never expire.
|
||||||
|
*/
|
||||||
|
function resolveLifetime(env: Env, requestedHours?: number): Lifetime {
|
||||||
|
const hours = env.FEED_TTL_HOURS
|
||||||
|
? parseInt(env.FEED_TTL_HOURS, 10)
|
||||||
|
: (requestedHours ?? NaN);
|
||||||
|
return Number.isFinite(hours) && hours > 0
|
||||||
|
? Lifetime.ofHours(hours)
|
||||||
|
: Lifetime.never;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a feed: mint an opaque `FeedId` (the read id) and a friendly `MailboxId`
|
||||||
|
* (the inbound address), write its config + empty metadata, register it in the
|
||||||
|
* global list + inbound index, and bump the `feeds_created` counter. Returns the
|
||||||
|
* new feed id, its mailbox, and config.
|
||||||
|
*/
|
||||||
|
export async function createFeedRecord(
|
||||||
|
env: Env,
|
||||||
|
input: CreateFeedInput,
|
||||||
|
): Promise<{ feedId: string; mailboxId: string; config: FeedConfig }> {
|
||||||
|
const repo = FeedRepository.from(env);
|
||||||
|
const feed = Feed.create(FeedId.generate(), input, {
|
||||||
|
mailboxId: MailboxId.generate(),
|
||||||
|
lifetime: resolveLifetime(env, input.lifetimeHours),
|
||||||
|
});
|
||||||
|
|
||||||
|
// save() also writes the inbound:<mailbox> → feedId index.
|
||||||
|
await repo.save(feed);
|
||||||
|
|
||||||
|
// FeedCreated → bumps the feeds_created counter (no background work to schedule).
|
||||||
|
await dispatchFeedEvents(feed, env, () => {});
|
||||||
|
|
||||||
|
return {
|
||||||
|
feedId: feed.id.value,
|
||||||
|
mailboxId: feed.mailboxId.value,
|
||||||
|
config: toConfigDTO(feed.state()),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export type UpdateFeedResult =
|
||||||
|
| { status: "ok"; config: FeedConfig }
|
||||||
|
| { status: "not_found" }
|
||||||
|
| { status: "expired" };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Quick-edit of title/description only — never recomputes expiry. Used by the
|
||||||
|
* dashboard's minimal edit. Delegates to the aggregate's single `edit` path, so
|
||||||
|
* an expired feed is rejected here too. The list projection is kept in sync by
|
||||||
|
* the repository on `saveConfig`.
|
||||||
|
*/
|
||||||
|
export async function editFeedDetails(
|
||||||
|
env: Env,
|
||||||
|
feedId: FeedId,
|
||||||
|
patch: { title?: string; description?: string },
|
||||||
|
): Promise<UpdateFeedResult> {
|
||||||
|
const repo = FeedRepository.from(env);
|
||||||
|
const feed = await repo.load(feedId);
|
||||||
|
if (!feed) return { status: "not_found" };
|
||||||
|
|
||||||
|
// No lifetime passed ⇒ expiry preserved (quick-edit never recomputes it).
|
||||||
|
if (feed.edit(patch).status === "expired") {
|
||||||
|
return { status: "expired" };
|
||||||
|
}
|
||||||
|
await repo.saveConfig(feed);
|
||||||
|
|
||||||
|
return { status: "ok", config: toConfigDTO(feed.state()) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Full edit: apply the patch, recompute expiry, and reject expired feeds. Fields
|
||||||
|
* left undefined are preserved. Mirrors title/description/expiry into the list.
|
||||||
|
*/
|
||||||
|
export async function editFeed(
|
||||||
|
env: Env,
|
||||||
|
feedId: FeedId,
|
||||||
|
input: UpdateFeedInput,
|
||||||
|
): Promise<UpdateFeedResult> {
|
||||||
|
const repo = FeedRepository.from(env);
|
||||||
|
const feed = await repo.load(feedId);
|
||||||
|
if (!feed) return { status: "not_found" };
|
||||||
|
|
||||||
|
// Recompute expiry only when a server TTL or a client lifetime applies;
|
||||||
|
// otherwise pass no lifetime so the aggregate preserves the current expiry.
|
||||||
|
const lifetime =
|
||||||
|
Boolean(env.FEED_TTL_HOURS) || input.lifetimeHours !== undefined
|
||||||
|
? resolveLifetime(env, input.lifetimeHours)
|
||||||
|
: undefined;
|
||||||
|
if (feed.edit(input, { lifetime }).status === "expired") {
|
||||||
|
return { status: "expired" };
|
||||||
|
}
|
||||||
|
|
||||||
|
await repo.saveConfig(feed);
|
||||||
|
|
||||||
|
return { status: "ok", config: toConfigDTO(feed.state()) };
|
||||||
|
}
|
||||||
|
|
||||||
|
type DeleteFeedFastResult = {
|
||||||
|
ok: boolean;
|
||||||
|
configDeleted: boolean;
|
||||||
|
metadataDeleted: boolean;
|
||||||
|
errors: string[];
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete a feed's config + metadata keys, reporting per-key outcomes. The larger
|
||||||
|
* email/attachment cleanup is handled separately via purgeFeedKeysStep, and the
|
||||||
|
* inbound `inbound:<mailbox>` index is dropped by `removeFromList(Bulk)` (which
|
||||||
|
* every caller invokes next) — symmetric with `save()` writing it.
|
||||||
|
*/
|
||||||
|
export async function deleteFeedFastDetailed(
|
||||||
|
emailStorage: KVNamespace,
|
||||||
|
feedId: FeedId,
|
||||||
|
): Promise<DeleteFeedFastResult> {
|
||||||
|
const repo = new FeedRepository(emailStorage);
|
||||||
|
|
||||||
|
const errors: string[] = [];
|
||||||
|
let configDeleted = false;
|
||||||
|
let metadataDeleted = false;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await repo.deleteConfig(feedId);
|
||||||
|
configDeleted = true;
|
||||||
|
} catch (error) {
|
||||||
|
errors.push(`config delete failed: ${String(error)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await repo.deleteMetadata(feedId);
|
||||||
|
metadataDeleted = true;
|
||||||
|
} catch (error) {
|
||||||
|
errors.push(`metadata delete failed: ${String(error)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { ok: configDeleted, configDeleted, metadataDeleted, errors };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete a single feed end-to-end: capture unsubscribe URLs, drop its config +
|
||||||
|
* metadata, remove it from the list, bump the counter, and hand the background
|
||||||
|
* unsubscribe requests + key purge to the supplied scheduler. Returns whether
|
||||||
|
* the feed was present in the global list.
|
||||||
|
*/
|
||||||
|
export async function deleteFeedRecord(
|
||||||
|
env: Env,
|
||||||
|
feedId: FeedId,
|
||||||
|
schedule: BackgroundScheduler,
|
||||||
|
): Promise<boolean> {
|
||||||
|
const emailStorage = env.EMAIL_STORAGE;
|
||||||
|
const repo = new FeedRepository(emailStorage);
|
||||||
|
|
||||||
|
// Read unsubscribe URLs before the metadata is deleted below.
|
||||||
|
const unsubscribeUrls = await collectUnsubscribeUrls(emailStorage, feedId);
|
||||||
|
|
||||||
|
await deleteFeedFastDetailed(emailStorage, feedId);
|
||||||
|
// removeFromList also drops the feed's inbound mailbox index.
|
||||||
|
const removed = await repo.removeFromList(feedId);
|
||||||
|
if (removed) {
|
||||||
|
await bumpCounters(emailStorage, { feeds_deleted: 1 });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (unsubscribeUrls.length > 0) {
|
||||||
|
schedule(sendUnsubscribes(unsubscribeUrls, env));
|
||||||
|
}
|
||||||
|
|
||||||
|
schedule(
|
||||||
|
purgeFeedKeysStep(emailStorage, feedId, {
|
||||||
|
bucket: getAttachmentBucket(env),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
return removed;
|
||||||
|
}
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import { createMockEnv, MockR2 } from "../test/setup";
|
||||||
|
import {
|
||||||
|
getCounters,
|
||||||
|
bumpCounters,
|
||||||
|
countKeysByPrefix,
|
||||||
|
getStats,
|
||||||
|
scanR2Usage,
|
||||||
|
scanKvUsage,
|
||||||
|
setStorageSnapshot,
|
||||||
|
} from "./stats";
|
||||||
|
import { getAttachmentBucket } from "../infrastructure/attachments";
|
||||||
|
import { STATS_KEY, FEEDS_LIST_KEY } from "../config/constants";
|
||||||
|
import { Env } from "../types";
|
||||||
|
|
||||||
|
describe("stats helper", () => {
|
||||||
|
it("returns zeroed counters when nothing is stored", async () => {
|
||||||
|
const env = createMockEnv() as unknown as Env;
|
||||||
|
const counters = await getCounters(env.EMAIL_STORAGE);
|
||||||
|
expect(counters).toMatchObject({
|
||||||
|
feeds_created: 0,
|
||||||
|
feeds_deleted: 0,
|
||||||
|
emails_received: 0,
|
||||||
|
emails_rejected: 0,
|
||||||
|
});
|
||||||
|
expect(counters.first_seen).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("accumulates numeric deltas across bumps", async () => {
|
||||||
|
const env = createMockEnv() as unknown as Env;
|
||||||
|
const kv = env.EMAIL_STORAGE;
|
||||||
|
|
||||||
|
await bumpCounters(kv, { emails_received: 1 });
|
||||||
|
await bumpCounters(kv, { emails_received: 2, emails_rejected: 1 });
|
||||||
|
await bumpCounters(kv, { feeds_created: 1, feeds_deleted: 3 });
|
||||||
|
|
||||||
|
const counters = await getCounters(kv);
|
||||||
|
expect(counters.emails_received).toBe(3);
|
||||||
|
expect(counters.emails_rejected).toBe(1);
|
||||||
|
expect(counters.feeds_created).toBe(1);
|
||||||
|
expect(counters.feeds_deleted).toBe(3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("overwrites date-time fields and sets first_seen once", async () => {
|
||||||
|
const env = createMockEnv() as unknown as Env;
|
||||||
|
const kv = env.EMAIL_STORAGE;
|
||||||
|
|
||||||
|
await bumpCounters(kv, {
|
||||||
|
emails_received: 1,
|
||||||
|
last_email_at: "2026-01-01T00:00:00.000Z",
|
||||||
|
});
|
||||||
|
const first = await getCounters(kv);
|
||||||
|
const firstSeen = first.first_seen;
|
||||||
|
expect(firstSeen).toBeDefined();
|
||||||
|
expect(first.last_email_at).toBe("2026-01-01T00:00:00.000Z");
|
||||||
|
|
||||||
|
await bumpCounters(kv, {
|
||||||
|
emails_received: 1,
|
||||||
|
last_email_at: "2026-02-02T00:00:00.000Z",
|
||||||
|
});
|
||||||
|
const second = await getCounters(kv);
|
||||||
|
expect(second.last_email_at).toBe("2026-02-02T00:00:00.000Z");
|
||||||
|
expect(second.first_seen).toBe(firstSeen);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("counts keys by prefix", async () => {
|
||||||
|
const env = createMockEnv() as unknown as Env;
|
||||||
|
const kv = env.EMAIL_STORAGE;
|
||||||
|
await kv.put("websub:a:1", "{}");
|
||||||
|
await kv.put("websub:a:2", "{}");
|
||||||
|
await kv.put("feed:x:config", "{}");
|
||||||
|
|
||||||
|
expect(await countKeysByPrefix(kv, "websub:")).toBe(2);
|
||||||
|
expect(await countKeysByPrefix(kv, "missing:")).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("getStats combines persisted counters with live values", async () => {
|
||||||
|
const env = createMockEnv() as unknown as Env;
|
||||||
|
const kv = env.EMAIL_STORAGE;
|
||||||
|
|
||||||
|
await kv.put(
|
||||||
|
FEEDS_LIST_KEY,
|
||||||
|
JSON.stringify({
|
||||||
|
feeds: [
|
||||||
|
{ id: "a", title: "A" },
|
||||||
|
{ id: "b", title: "B" },
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
await kv.put("websub:subs:a", "{}");
|
||||||
|
await bumpCounters(kv, { emails_received: 5, feeds_created: 2 });
|
||||||
|
|
||||||
|
const stats = await getStats(env);
|
||||||
|
expect(stats.active_feeds).toBe(2);
|
||||||
|
expect(stats.websub_subscriptions_active).toBe(1);
|
||||||
|
expect(stats.emails_received).toBe(5);
|
||||||
|
expect(stats.feeds_created).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("never throws on a failing KV (counters are best-effort)", async () => {
|
||||||
|
const brokenKv = {
|
||||||
|
get: async () => {
|
||||||
|
throw new Error("kv down");
|
||||||
|
},
|
||||||
|
put: async () => {
|
||||||
|
throw new Error("kv down");
|
||||||
|
},
|
||||||
|
} as unknown as KVNamespace;
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
bumpCounters(brokenKv, { emails_received: 1 }),
|
||||||
|
).resolves.toBeUndefined();
|
||||||
|
expect(await getCounters(brokenKv)).toMatchObject({ emails_received: 0 });
|
||||||
|
expect(await countKeysByPrefix(brokenKv, "websub:")).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("persists under the stats KV key", async () => {
|
||||||
|
const env = createMockEnv() as unknown as Env;
|
||||||
|
const kv = env.EMAIL_STORAGE;
|
||||||
|
await bumpCounters(kv, { feeds_created: 1 });
|
||||||
|
const raw = (await kv.get(STATS_KEY, { type: "json" })) as {
|
||||||
|
feeds_created: number;
|
||||||
|
};
|
||||||
|
expect(raw.feeds_created).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("getStats reports attachments_enabled based on the toggle", async () => {
|
||||||
|
const off = createMockEnv() as unknown as Env;
|
||||||
|
expect((await getStats(off)).attachments_enabled).toBe(false);
|
||||||
|
|
||||||
|
const on = createMockEnv({ withR2: true }) as unknown as Env;
|
||||||
|
expect((await getStats(on)).attachments_enabled).toBe(true);
|
||||||
|
|
||||||
|
const disabled = createMockEnv({ withR2: true }) as unknown as Env;
|
||||||
|
(disabled as any).ATTACHMENTS_ENABLED = "false";
|
||||||
|
expect((await getStats(disabled)).attachments_enabled).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("getAttachmentBucket", () => {
|
||||||
|
it("returns the bucket when bound and not disabled", () => {
|
||||||
|
const env = createMockEnv({ withR2: true }) as unknown as Env;
|
||||||
|
expect(getAttachmentBucket(env)).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns undefined when no bucket is bound", () => {
|
||||||
|
const env = createMockEnv() as unknown as Env;
|
||||||
|
expect(getAttachmentBucket(env)).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns undefined when explicitly disabled", () => {
|
||||||
|
const env = createMockEnv({ withR2: true }) as unknown as Env;
|
||||||
|
(env as any).ATTACHMENTS_ENABLED = "false";
|
||||||
|
expect(getAttachmentBucket(env)).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("storage usage scans", () => {
|
||||||
|
it("scanR2Usage sums object sizes and counts", async () => {
|
||||||
|
const bucket = new MockR2();
|
||||||
|
await bucket.put("a", new Uint8Array(100));
|
||||||
|
await bucket.put("b", new Uint8Array(250));
|
||||||
|
const usage = await scanR2Usage(bucket as unknown as R2Bucket);
|
||||||
|
expect(usage.count).toBe(2);
|
||||||
|
expect(usage.bytes).toBe(350);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("scanR2Usage returns zeros for an empty bucket", async () => {
|
||||||
|
const usage = await scanR2Usage(new MockR2() as unknown as R2Bucket);
|
||||||
|
expect(usage).toEqual({ bytes: 0, count: 0 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("scanKvUsage estimates KV bytes from stored email sizes", async () => {
|
||||||
|
const env = createMockEnv() as unknown as Env;
|
||||||
|
const kv = env.EMAIL_STORAGE;
|
||||||
|
await kv.put(
|
||||||
|
FEEDS_LIST_KEY,
|
||||||
|
JSON.stringify({
|
||||||
|
feeds: [
|
||||||
|
{ id: "a", title: "A" },
|
||||||
|
{ id: "b", title: "B" },
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
await kv.put(
|
||||||
|
"feed:a:metadata",
|
||||||
|
JSON.stringify({
|
||||||
|
emails: [
|
||||||
|
{ key: "k1", size: 100 },
|
||||||
|
{ key: "k2", size: 50 },
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
await kv.put(
|
||||||
|
"feed:b:metadata",
|
||||||
|
JSON.stringify({ emails: [{ key: "k3", size: 25 }] }),
|
||||||
|
);
|
||||||
|
|
||||||
|
const usage = await scanKvUsage(kv);
|
||||||
|
expect(usage.bytes).toBe(175);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("setStorageSnapshot writes the snapshot fields", async () => {
|
||||||
|
const env = createMockEnv() as unknown as Env;
|
||||||
|
const kv = env.EMAIL_STORAGE;
|
||||||
|
await setStorageSnapshot(kv, {
|
||||||
|
attachments_bytes: 1234,
|
||||||
|
attachments_count: 5,
|
||||||
|
kv_bytes_estimated: 678,
|
||||||
|
});
|
||||||
|
const counters = await getCounters(kv);
|
||||||
|
expect(counters.attachments_bytes).toBe(1234);
|
||||||
|
expect(counters.attachments_count).toBe(5);
|
||||||
|
expect(counters.kv_bytes_estimated).toBe(678);
|
||||||
|
expect(counters.storage_scanned_at).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
import { Counters, Env, StatsResponse } from "../types";
|
||||||
|
import { APP_VERSION } from "../config/version";
|
||||||
|
import { logger } from "../infrastructure/logger";
|
||||||
|
import { FeedRepository } from "../infrastructure/feed-repository";
|
||||||
|
import { CountersRepository } from "../infrastructure/counters-repository";
|
||||||
|
import { WebSubSubscriptionRepository } from "../infrastructure/websub-subscription-repository";
|
||||||
|
import { FeedId } from "../domain/value-objects/feed-id";
|
||||||
|
import { getAttachmentBucket } from "../infrastructure/attachments";
|
||||||
|
|
||||||
|
const EMPTY_COUNTERS: Counters = {
|
||||||
|
feeds_created: 0,
|
||||||
|
feeds_deleted: 0,
|
||||||
|
emails_received: 0,
|
||||||
|
emails_rejected: 0,
|
||||||
|
emails_forwarded: 0,
|
||||||
|
emails_deduplicated: 0,
|
||||||
|
unsubscribes_sent: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function getCounters(kv: KVNamespace): Promise<Counters> {
|
||||||
|
try {
|
||||||
|
const stored = await new CountersRepository(kv).getRaw();
|
||||||
|
return { ...EMPTY_COUNTERS, ...(stored || {}) };
|
||||||
|
} catch (error) {
|
||||||
|
logger.error("Error reading counters", { error: String(error) });
|
||||||
|
return { ...EMPTY_COUNTERS };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read-modify-write the counters singleton. KV has no atomic increment, so
|
||||||
|
* concurrent invocations can lose updates — accepted given KV's eventual
|
||||||
|
* consistency and this app's low volume (see email-processor.ts storeEmail).
|
||||||
|
* Never throws: counter failures must not break ingestion or admin flows.
|
||||||
|
*/
|
||||||
|
export async function bumpCounters(
|
||||||
|
kv: KVNamespace,
|
||||||
|
changes: Partial<Omit<Counters, "first_seen">>,
|
||||||
|
): Promise<void> {
|
||||||
|
try {
|
||||||
|
const current = await getCounters(kv);
|
||||||
|
|
||||||
|
current.feeds_created += changes.feeds_created ?? 0;
|
||||||
|
current.feeds_deleted += changes.feeds_deleted ?? 0;
|
||||||
|
current.emails_received += changes.emails_received ?? 0;
|
||||||
|
current.emails_rejected += changes.emails_rejected ?? 0;
|
||||||
|
current.emails_forwarded += changes.emails_forwarded ?? 0;
|
||||||
|
current.emails_deduplicated += changes.emails_deduplicated ?? 0;
|
||||||
|
current.unsubscribes_sent += changes.unsubscribes_sent ?? 0;
|
||||||
|
if (changes.last_email_at) current.last_email_at = changes.last_email_at;
|
||||||
|
if (changes.last_feed_created_at)
|
||||||
|
current.last_feed_created_at = changes.last_feed_created_at;
|
||||||
|
if (!current.first_seen) current.first_seen = new Date().toISOString();
|
||||||
|
|
||||||
|
await new CountersRepository(kv).put(current);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error("Error updating counters", { error: String(error) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function countKeysByPrefix(
|
||||||
|
kv: KVNamespace,
|
||||||
|
prefix: string,
|
||||||
|
): Promise<number> {
|
||||||
|
return new FeedRepository(kv).countKeysByPrefix(prefix);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getStats(env: Env): Promise<StatsResponse> {
|
||||||
|
const repo = FeedRepository.from(env);
|
||||||
|
const [counters, feeds, websubCount] = await Promise.all([
|
||||||
|
getCounters(env.EMAIL_STORAGE),
|
||||||
|
repo.listFeeds(),
|
||||||
|
WebSubSubscriptionRepository.from(env).countKeys(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
...counters,
|
||||||
|
active_feeds: feeds.length,
|
||||||
|
websub_subscriptions_active: websubCount,
|
||||||
|
attachments_enabled: !!getAttachmentBucket(env),
|
||||||
|
version: APP_VERSION,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Sum the byte size and object count of every attachment stored in R2. */
|
||||||
|
export async function scanR2Usage(
|
||||||
|
bucket: R2Bucket,
|
||||||
|
): Promise<{ bytes: number; count: number }> {
|
||||||
|
let bytes = 0;
|
||||||
|
let count = 0;
|
||||||
|
let cursor: string | undefined;
|
||||||
|
try {
|
||||||
|
do {
|
||||||
|
const listed = await bucket.list({ cursor });
|
||||||
|
for (const obj of listed.objects) {
|
||||||
|
bytes += obj.size;
|
||||||
|
count += 1;
|
||||||
|
}
|
||||||
|
cursor = listed.truncated ? listed.cursor : undefined;
|
||||||
|
} while (cursor);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error("Error scanning R2 usage", { error: String(error) });
|
||||||
|
}
|
||||||
|
return { bytes, count };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Estimate KV storage used. KV exposes no size API, so we sum the per-email
|
||||||
|
* sizes already recorded in each feed's metadata — email bodies dominate KV
|
||||||
|
* usage. Feed config/websub/stats keys are excluded, so this is a lower-bound
|
||||||
|
* estimate.
|
||||||
|
*/
|
||||||
|
export async function scanKvUsage(kv: KVNamespace): Promise<{ bytes: number }> {
|
||||||
|
let bytes = 0;
|
||||||
|
try {
|
||||||
|
const repo = new FeedRepository(kv);
|
||||||
|
const feeds = await repo.listFeeds();
|
||||||
|
for (const feed of feeds) {
|
||||||
|
const metadata = await repo.getMetadata(FeedId.unchecked(feed.id));
|
||||||
|
if (!metadata) continue;
|
||||||
|
for (const email of metadata.emails) {
|
||||||
|
bytes += email.size ?? 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
logger.error("Error estimating KV usage", { error: String(error) });
|
||||||
|
}
|
||||||
|
return { bytes };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Overwrite the storage-usage snapshot fields on the counters singleton.
|
||||||
|
* Unlike bumpCounters these are set (not incremented). Never throws.
|
||||||
|
*/
|
||||||
|
export async function setStorageSnapshot(
|
||||||
|
kv: KVNamespace,
|
||||||
|
snapshot: {
|
||||||
|
attachments_bytes: number;
|
||||||
|
attachments_count: number;
|
||||||
|
kv_bytes_estimated: number;
|
||||||
|
},
|
||||||
|
): Promise<void> {
|
||||||
|
try {
|
||||||
|
const current = await getCounters(kv);
|
||||||
|
current.attachments_bytes = snapshot.attachments_bytes;
|
||||||
|
current.attachments_count = snapshot.attachments_count;
|
||||||
|
current.kv_bytes_estimated = snapshot.kv_bytes_estimated;
|
||||||
|
current.storage_scanned_at = new Date().toISOString();
|
||||||
|
if (!current.first_seen) current.first_seen = new Date().toISOString();
|
||||||
|
await new CountersRepository(kv).put(current);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error("Error writing storage snapshot", { error: String(error) });
|
||||||
|
}
|
||||||
|
}
|
||||||
+21
-3
@@ -1,6 +1,12 @@
|
|||||||
/** Maximum total size of emails stored per feed (bytes). */
|
/** Maximum total size of emails stored per feed (bytes). */
|
||||||
export const FEED_MAX_BYTES = 524288; // 512 KB
|
export const FEED_MAX_BYTES = 524288; // 512 KB
|
||||||
|
|
||||||
|
/** Cloudflare R2 free tier storage allowance (bytes). */
|
||||||
|
export const R2_FREE_TIER_BYTES = 10 * 1024 ** 3; // 10 GB
|
||||||
|
|
||||||
|
/** Cloudflare KV free tier storage allowance (bytes). */
|
||||||
|
export const KV_FREE_TIER_BYTES = 1 * 1024 ** 3; // 1 GB
|
||||||
|
|
||||||
/** Cache TTL for ForwardEmail.net IP list (milliseconds). */
|
/** Cache TTL for ForwardEmail.net IP list (milliseconds). */
|
||||||
export const FORWARD_EMAIL_IPS_CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
|
export const FORWARD_EMAIL_IPS_CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
|
||||||
|
|
||||||
@@ -10,9 +16,6 @@ export const ADMIN_COOKIE_MAX_AGE = 60 * 60 * 24 * 7; // 1 week
|
|||||||
/** Maximum number of feed items exposed in RSS/Atom responses. */
|
/** Maximum number of feed items exposed in RSS/Atom responses. */
|
||||||
export const MAX_FEED_ITEMS = 20;
|
export const MAX_FEED_ITEMS = 20;
|
||||||
|
|
||||||
/** Maximum number of email entries kept in feed metadata. */
|
|
||||||
export const MAX_METADATA_EMAILS = 50;
|
|
||||||
|
|
||||||
/** Default WebSub lease duration (seconds). */
|
/** Default WebSub lease duration (seconds). */
|
||||||
export const DEFAULT_LEASE_SECONDS = 86400; // 24 hours
|
export const DEFAULT_LEASE_SECONDS = 86400; // 24 hours
|
||||||
|
|
||||||
@@ -21,3 +24,18 @@ export const MAX_LEASE_SECONDS = 30 * 24 * 3600; // 30 days
|
|||||||
|
|
||||||
/** KV key for the global feed list. */
|
/** KV key for the global feed list. */
|
||||||
export const FEEDS_LIST_KEY = "feeds:list";
|
export const FEEDS_LIST_KEY = "feeds:list";
|
||||||
|
|
||||||
|
/** KV key for the monitoring counters singleton. */
|
||||||
|
export const STATS_KEY = "stats:counters";
|
||||||
|
|
||||||
|
/** Default TTL for a cached per-domain favicon (seconds). */
|
||||||
|
export const ICON_TTL_SECONDS = 7 * 24 * 60 * 60; // 1 week
|
||||||
|
|
||||||
|
/** Maximum accepted favicon size (bytes); larger responses are rejected. */
|
||||||
|
export const MAX_ICON_BYTES = 100 * 1024; // 100 KB
|
||||||
|
|
||||||
|
/** Timeout for an outbound favicon fetch (milliseconds). */
|
||||||
|
export const ICON_FETCH_TIMEOUT_MS = 5000;
|
||||||
|
|
||||||
|
/** Timeout for an outbound RFC 8058 one-click unsubscribe request (milliseconds). */
|
||||||
|
export const UNSUBSCRIBE_TIMEOUT_MS = 5000;
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import pkg from "../../package.json";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The running app version, inlined from package.json at bundle time (the Worker
|
||||||
|
* has no filesystem at runtime). Surfaced in the admin/status footer and the
|
||||||
|
* /health JSON so a self-hoster can tell which build is deployed.
|
||||||
|
*/
|
||||||
|
export const APP_VERSION: string = pkg.version;
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
/**
|
||||||
|
* A source of "now", injected into the domain so aggregates never reach for
|
||||||
|
* ambient `Date.now()`. Production wires `systemClock`; tests can supply a fixed
|
||||||
|
* clock for deterministic expiry/timestamp assertions.
|
||||||
|
*/
|
||||||
|
export interface Clock {
|
||||||
|
now(): number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const systemClock: Clock = {
|
||||||
|
now: () => Date.now(),
|
||||||
|
};
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import { detectConfirmation } from "./confirmation";
|
||||||
|
|
||||||
|
describe("detectConfirmation", () => {
|
||||||
|
it("detects an English confirmation email and returns the confirm link", () => {
|
||||||
|
const result = detectConfirmation({
|
||||||
|
subject: "Please confirm your subscription",
|
||||||
|
text: "Click the button below to verify your email address.",
|
||||||
|
links: [
|
||||||
|
{
|
||||||
|
href: "https://news.example.com/confirm?token=abc123",
|
||||||
|
text: "Confirm subscription",
|
||||||
|
},
|
||||||
|
{ href: "https://news.example.com/home", text: "Home" },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(result).not.toBeNull();
|
||||||
|
expect(result![0]).toBe("https://news.example.com/confirm?token=abc123");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("detects a French confirmation email (accent-insensitive)", () => {
|
||||||
|
const result = detectConfirmation({
|
||||||
|
subject: "Confirmez votre inscription",
|
||||||
|
text: "Cliquez pour activer votre abonnement.",
|
||||||
|
links: [
|
||||||
|
{
|
||||||
|
href: "https://lettre.example.fr/valider/xyz",
|
||||||
|
text: "Valider mon inscription",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(result).not.toBeNull();
|
||||||
|
expect(result![0]).toBe("https://lettre.example.fr/valider/xyz");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns null for a normal newsletter with only an unsubscribe link", () => {
|
||||||
|
const result = detectConfirmation({
|
||||||
|
subject: "This week in tech",
|
||||||
|
text: "Here are the top stories. To stop receiving these, unsubscribe here.",
|
||||||
|
links: [
|
||||||
|
{ href: "https://news.example.com/article/42", text: "Read more" },
|
||||||
|
{
|
||||||
|
href: "https://news.example.com/unsubscribe?u=9",
|
||||||
|
text: "Unsubscribe",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(result).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns null when no candidate link is present even if the subject matches", () => {
|
||||||
|
const result = detectConfirmation({
|
||||||
|
subject: "Confirm your subscription",
|
||||||
|
text: "Reply to this email to confirm.",
|
||||||
|
links: [],
|
||||||
|
});
|
||||||
|
expect(result).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("never treats an unsubscribe link as a confirmation candidate", () => {
|
||||||
|
const result = detectConfirmation({
|
||||||
|
subject: "Confirm your email",
|
||||||
|
text: "Verify your address.",
|
||||||
|
links: [
|
||||||
|
{ href: "https://x.example/verify/abc", text: "Verify email" },
|
||||||
|
{ href: "https://x.example/unsubscribe", text: "unsubscribe" },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(result).not.toBeNull();
|
||||||
|
expect(result!).not.toContain("https://x.example/unsubscribe");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ranks the strongest candidate first and caps at three links", () => {
|
||||||
|
const result = detectConfirmation({
|
||||||
|
subject: "Confirm your subscription",
|
||||||
|
text: "verify activate",
|
||||||
|
links: [
|
||||||
|
{ href: "https://x.example/help", text: "help" },
|
||||||
|
{ href: "https://x.example/a?token=1", text: "click" },
|
||||||
|
{ href: "https://x.example/confirm?token=2", text: "Confirm" },
|
||||||
|
{ href: "https://x.example/activate", text: "Activate account" },
|
||||||
|
{ href: "https://x.example/verify", text: "Verify" },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(result).not.toBeNull();
|
||||||
|
expect(result!.length).toBeLessThanOrEqual(3);
|
||||||
|
expect(result![0]).toBe("https://x.example/confirm?token=2");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ignores non-http(s) links", () => {
|
||||||
|
const result = detectConfirmation({
|
||||||
|
subject: "Confirm your subscription",
|
||||||
|
text: "verify",
|
||||||
|
links: [{ href: "mailto:confirm@x.example", text: "confirm" }],
|
||||||
|
});
|
||||||
|
expect(result).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── False-positive guards: ordinary newsletters must NOT be flagged ──────────
|
||||||
|
// A "manage subscription" footer link is only a weak signal (+1), so a stray
|
||||||
|
// body keyword (active/valid) cannot push it over the threshold.
|
||||||
|
|
||||||
|
it("does not flag a newsletter with a manage-subscription footer + 'active' in body", () => {
|
||||||
|
const result = detectConfirmation({
|
||||||
|
subject: "This week in tech",
|
||||||
|
text: "Thanks to our most active community members for the great discussion.",
|
||||||
|
links: [
|
||||||
|
{ href: "https://news.example.com/article/42", text: "Read more" },
|
||||||
|
{
|
||||||
|
href: "https://news.example.com/account/subscription",
|
||||||
|
text: "Manage your subscription",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(result).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not flag a newsletter with a subscription-preferences link + 'valid' in body", () => {
|
||||||
|
const result = detectConfirmation({
|
||||||
|
subject: "Weekend deals are here",
|
||||||
|
text: "These offers are valid until Friday — don't miss out.",
|
||||||
|
links: [
|
||||||
|
{
|
||||||
|
href: "https://shop.example.com/subscription/preferences",
|
||||||
|
text: "Subscription preferences",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(result).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not flag a marketing 'Subscribe & save' CTA + 'activate' in body", () => {
|
||||||
|
const result = detectConfirmation({
|
||||||
|
subject: "Your weekly digest",
|
||||||
|
text: "Activate your free trial and start saving today.",
|
||||||
|
links: [
|
||||||
|
{
|
||||||
|
href: "https://shop.example.com/subscribe",
|
||||||
|
text: "Subscribe & save",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(result).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── Recall: a genuine confirmation still passes via the weak signal ──────────
|
||||||
|
it("detects a genuine confirm-subscription email whose only link is a bare /subscribe", () => {
|
||||||
|
const result = detectConfirmation({
|
||||||
|
subject: "Please confirm your subscription",
|
||||||
|
text: "Tap the button to finish signing up.",
|
||||||
|
links: [
|
||||||
|
{
|
||||||
|
href: "https://news.example.com/subscribe/abc123",
|
||||||
|
text: "Subscribe",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(result).not.toBeNull();
|
||||||
|
expect(result![0]).toBe("https://news.example.com/subscribe/abc123");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("dedupes a confirmation link repeated in the body", () => {
|
||||||
|
const result = detectConfirmation({
|
||||||
|
subject: "Confirm your subscription",
|
||||||
|
text: "verify your address",
|
||||||
|
links: [
|
||||||
|
{ href: "https://x.example/confirm?token=1", text: "Confirm" },
|
||||||
|
{ href: "https://x.example/confirm?token=1", text: "Confirm here" },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(result).toEqual(["https://x.example/confirm?token=1"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
/**
|
||||||
|
* Pure detection of "confirm your subscription" emails. No DOM, no I/O — it
|
||||||
|
* receives already-extracted subject/body text and link tuples (infra parses the
|
||||||
|
* HTML). This module owns the business knowledge: the multilingual keyword vocab,
|
||||||
|
* the link-signal patterns, the scoring weights and the threshold.
|
||||||
|
*
|
||||||
|
* Returns the ranked candidate confirmation links (top 3) when the combined score
|
||||||
|
* clears the threshold AND at least one candidate link exists; otherwise null.
|
||||||
|
* Only http(s) links are ever considered or returned.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export interface DetectConfirmationInput {
|
||||||
|
subject: string;
|
||||||
|
text: string;
|
||||||
|
links: { href: string; text: string }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Confirmation-positive stems, already normalized (lowercased, diacritics stripped).
|
||||||
|
// EN / FR / DE / ES — extend here to add a language.
|
||||||
|
const KEYWORDS = [
|
||||||
|
"confirm",
|
||||||
|
"verif",
|
||||||
|
"activ",
|
||||||
|
"valid",
|
||||||
|
"bestatig",
|
||||||
|
"aktivier",
|
||||||
|
"opt-in",
|
||||||
|
"opt in",
|
||||||
|
"optin",
|
||||||
|
];
|
||||||
|
|
||||||
|
// Strong URL signals: an unambiguous confirm/verify/activate action or a token.
|
||||||
|
// A link URL matching any scores +2.
|
||||||
|
const STRONG_LINK_SIGNALS = [
|
||||||
|
"confirm",
|
||||||
|
"verif",
|
||||||
|
"activ",
|
||||||
|
"valid",
|
||||||
|
"bestatig",
|
||||||
|
"aktivier",
|
||||||
|
"optin",
|
||||||
|
"opt-in",
|
||||||
|
"double-optin",
|
||||||
|
"token=",
|
||||||
|
"confirm=",
|
||||||
|
"activation",
|
||||||
|
];
|
||||||
|
|
||||||
|
// Weak URL signals: ambiguous subscribe/subscription words that also appear in
|
||||||
|
// ordinary "manage subscription" footers. Worth only +1 so they cannot, on their
|
||||||
|
// own (with a stray body keyword), cross the threshold and cry wolf — but still
|
||||||
|
// let a genuine "confirm your subscription" subject + a bare /subscribe link pass.
|
||||||
|
const WEAK_LINK_SIGNALS = ["subscription", "subscribe"];
|
||||||
|
|
||||||
|
// Negative patterns: a link matching any of these is NEVER a candidate, and these
|
||||||
|
// tokens are stripped from text before keyword scanning (kills the unsubscribe
|
||||||
|
// false positive — "unsubscribe" contains "subscribe").
|
||||||
|
const NEGATIVE = [
|
||||||
|
"unsubscribe",
|
||||||
|
"desabonn",
|
||||||
|
"desinscri",
|
||||||
|
"abbestell",
|
||||||
|
"opt-out",
|
||||||
|
"optout",
|
||||||
|
"list-unsubscribe",
|
||||||
|
];
|
||||||
|
|
||||||
|
const THRESHOLD = 3;
|
||||||
|
|
||||||
|
function normalize(s: string): string {
|
||||||
|
return s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
function isHttp(href: string): boolean {
|
||||||
|
return /^https?:\/\//i.test(href.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
function matchesAny(haystack: string, needles: string[]): boolean {
|
||||||
|
return needles.some((n) => haystack.includes(n));
|
||||||
|
}
|
||||||
|
|
||||||
|
function linkScore(href: string, text: string): number {
|
||||||
|
const h = normalize(href);
|
||||||
|
const t = normalize(text);
|
||||||
|
if (matchesAny(h, NEGATIVE) || matchesAny(t, NEGATIVE)) return 0;
|
||||||
|
let score = 0;
|
||||||
|
if (matchesAny(h, STRONG_LINK_SIGNALS)) score += 2;
|
||||||
|
else if (matchesAny(h, WEAK_LINK_SIGNALS)) score += 1;
|
||||||
|
if (matchesAny(t, KEYWORDS)) score += 2;
|
||||||
|
return score;
|
||||||
|
}
|
||||||
|
|
||||||
|
function stripNegatives(text: string): string {
|
||||||
|
let out = text;
|
||||||
|
for (const n of NEGATIVE) out = out.split(n).join(" ");
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function detectConfirmation(
|
||||||
|
input: DetectConfirmationInput,
|
||||||
|
): string[] | null {
|
||||||
|
const candidates = input.links
|
||||||
|
.filter((l) => isHttp(l.href))
|
||||||
|
.map((l) => ({ href: l.href.trim(), score: linkScore(l.href, l.text) }))
|
||||||
|
.filter((l) => l.score > 0)
|
||||||
|
.sort((a, b) => b.score - a.score);
|
||||||
|
|
||||||
|
if (candidates.length === 0) return null;
|
||||||
|
|
||||||
|
const subject = stripNegatives(normalize(input.subject));
|
||||||
|
const text = stripNegatives(normalize(input.text));
|
||||||
|
|
||||||
|
const subjectScore = matchesAny(subject, KEYWORDS) ? 2 : 0;
|
||||||
|
const bodyScore = matchesAny(text, KEYWORDS) ? 1 : 0;
|
||||||
|
const bestLinkScore = candidates[0].score;
|
||||||
|
|
||||||
|
if (subjectScore + bodyScore + bestLinkScore < THRESHOLD) return null;
|
||||||
|
|
||||||
|
// Dedupe by href before capping, so a link repeated in the body never wastes
|
||||||
|
// one of the three surfaced slots.
|
||||||
|
return [...new Set(candidates.map((c) => c.href))].slice(0, 3);
|
||||||
|
}
|
||||||
@@ -1,37 +1,8 @@
|
|||||||
import { describe, it, expect } from "vitest";
|
import { describe, it, expect } from "vitest";
|
||||||
import { EmailParser } from "./email-parser";
|
import { EmailParser } from "./email-parser";
|
||||||
|
|
||||||
describe("EmailParser.extractFeedId", () => {
|
// Inbound mailbox parsing lives on the MailboxId VO (see mailbox-id.test.ts);
|
||||||
it("extracts a valid feed ID from an email address", () => {
|
// EmailParser no longer wraps it.
|
||||||
expect(EmailParser.extractFeedId("river.castle.42@example.com")).toBe(
|
|
||||||
"river.castle.42",
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("is case-insensitive for the local part", () => {
|
|
||||||
expect(EmailParser.extractFeedId("River.Castle.42@example.com")).toBe(
|
|
||||||
"River.Castle.42",
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns null for an address with no feed ID format", () => {
|
|
||||||
expect(EmailParser.extractFeedId("user@example.com")).toBeNull();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns null for a plain string without @", () => {
|
|
||||||
expect(EmailParser.extractFeedId("notanemail")).toBeNull();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns null when the numeric suffix is only one digit", () => {
|
|
||||||
expect(EmailParser.extractFeedId("river.castle.4@example.com")).toBeNull();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns null when the numeric suffix has more than two digits", () => {
|
|
||||||
expect(
|
|
||||||
EmailParser.extractFeedId("river.castle.123@example.com"),
|
|
||||||
).toBeNull();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("EmailParser.decodeEncodedWords", () => {
|
describe("EmailParser.decodeEncodedWords", () => {
|
||||||
it("returns plain text unchanged", () => {
|
it("returns plain text unchanged", () => {
|
||||||
@@ -1,12 +1,6 @@
|
|||||||
import { EmailData } from "../types";
|
import { EmailData } from "../types";
|
||||||
|
|
||||||
export class EmailParser {
|
export class EmailParser {
|
||||||
// Matches noun1.noun2.XY (the feed ID format) before the @ symbol
|
|
||||||
static extractFeedId(emailAddress: string): string | null {
|
|
||||||
const match = emailAddress.match(/^([a-z]+\.[a-z]+\.\d{2})@/i);
|
|
||||||
return match ? match[1] : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
static parseForwardEmailPayload(payload: any): EmailData {
|
static parseForwardEmailPayload(payload: any): EmailData {
|
||||||
if (!payload) {
|
if (!payload) {
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { FeedId } from "./value-objects/feed-id";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Domain events the Feed aggregate records when it mutates. They describe *what
|
||||||
|
* happened* in business terms and carry their own `feedId`, so the application
|
||||||
|
* dispatcher can route side effects (counters, WebSub pings, favicon caching)
|
||||||
|
* without the caller threading the id back in. This keeps the aggregate ignorant
|
||||||
|
* of infrastructure and the orchestration code free of scattered, inline effects.
|
||||||
|
*
|
||||||
|
* Only mutations that currently have side effects emit events — feed creation
|
||||||
|
* and email ingestion. Edits and removals carry no side effect, so they emit
|
||||||
|
* nothing. Side effects that don't flow through the aggregate (a rejected email,
|
||||||
|
* a feed deletion that bypasses the aggregate, bulk admin operations) stay
|
||||||
|
* outside this mechanism by design — they have no aggregate event to ride on.
|
||||||
|
*/
|
||||||
|
export type FeedEvent =
|
||||||
|
| { type: "FeedCreated"; feedId: FeedId }
|
||||||
|
| { type: "EmailIngested"; feedId: FeedId; iconDomain?: string };
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import { FEEDS_LIST_KEY, STATS_KEY } from "../config/constants";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The KV key schema, in one pure place. Every repository builds its keys here so
|
||||||
|
* the wire format lives in a single module — never inline a `feed:`/`icon:`/
|
||||||
|
* `websub:` string elsewhere. Strings are byte-identical to the original schema;
|
||||||
|
* changing them would require migrating live KV data.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const WEBSUB_PREFIX = "websub:subs:";
|
||||||
|
|
||||||
|
export const feedKeys = {
|
||||||
|
config: (feedId: string): string => `feed:${feedId}:config`,
|
||||||
|
metadata: (feedId: string): string => `feed:${feedId}:metadata`,
|
||||||
|
|
||||||
|
/** Secondary index: inbound mailbox local part → feed id (resolved at reception). */
|
||||||
|
inbound: (mailboxId: string): string => `inbound:${mailboxId}`,
|
||||||
|
|
||||||
|
/** Prefix covering every key owned by a feed (config, metadata, emails). */
|
||||||
|
feedPrefix: (feedId: string): string => `feed:${feedId}:`,
|
||||||
|
|
||||||
|
/** Mint a fresh, time-ordered email key. Call once and reuse the result. */
|
||||||
|
newEmail: (feedId: string): string => `feed:${feedId}:${Date.now()}`,
|
||||||
|
|
||||||
|
/** KV key for a domain's cached favicon (shared across feeds). */
|
||||||
|
icon: (domain: string): string => `icon:${domain}`,
|
||||||
|
|
||||||
|
websub: (feedId: string): string => `${WEBSUB_PREFIX}${feedId}`,
|
||||||
|
|
||||||
|
/** Prefix matching every per-feed WebSub subscription key. */
|
||||||
|
websubPrefix: (): string => WEBSUB_PREFIX,
|
||||||
|
|
||||||
|
/** True when `key` is an email entry (not the feed's config/metadata key). */
|
||||||
|
isEmail: (feedId: string, key: string): boolean => {
|
||||||
|
const suffix = key.slice(feedKeys.feedPrefix(feedId).length);
|
||||||
|
return suffix !== "config" && suffix !== "metadata";
|
||||||
|
},
|
||||||
|
|
||||||
|
/** Recover the feed id embedded in an email key (`feed:<id>:<ts>`). */
|
||||||
|
feedIdFromEmail: (key: string): string => key.split(":")[1],
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export { FEEDS_LIST_KEY, STATS_KEY };
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
/**
|
||||||
|
* The Feed aggregate's internal config state, in domain (camelCase) vocabulary.
|
||||||
|
* This is deliberately NOT the persistence shape: the snake_case `FeedConfig`
|
||||||
|
* DTO is an infrastructure concern, and the translation between the two lives in
|
||||||
|
* `infrastructure/feed-mapper.ts`. The domain never speaks the storage dialect.
|
||||||
|
*
|
||||||
|
* `expiresAt` is an absolute instant (epoch ms) already resolved from a
|
||||||
|
* `Lifetime`; the aggregate stores the resolved value, not the policy.
|
||||||
|
*/
|
||||||
|
export interface FeedState {
|
||||||
|
title: string;
|
||||||
|
description?: string;
|
||||||
|
language: string;
|
||||||
|
/** The feed's inbound mailbox local part (`noun.noun.NN`) — its email address
|
||||||
|
* is `mailboxId@domain`. Decoupled from the feed's `FeedId` (the read id). */
|
||||||
|
mailboxId: string;
|
||||||
|
author?: string;
|
||||||
|
/** When true, entry titles in the feed output are rendered as `[Sender] Subject`. */
|
||||||
|
senderInTitle?: boolean;
|
||||||
|
allowedSenders: string[];
|
||||||
|
blockedSenders: string[];
|
||||||
|
createdAt: number;
|
||||||
|
updatedAt?: number;
|
||||||
|
expiresAt?: number;
|
||||||
|
}
|
||||||
@@ -0,0 +1,413 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import { createMockEnv } from "../test/setup";
|
||||||
|
import { Feed, CreateFeedInput } from "./feed.aggregate";
|
||||||
|
import { FeedRepository } from "../infrastructure/feed-repository";
|
||||||
|
import { FeedId } from "./value-objects/feed-id";
|
||||||
|
import { MailboxId } from "./value-objects/mailbox-id";
|
||||||
|
import { Lifetime } from "./value-objects/lifetime";
|
||||||
|
import { FeedState } from "./feed-state";
|
||||||
|
import { Clock } from "./clock";
|
||||||
|
import type { Env, EmailMetadata } from "../types";
|
||||||
|
|
||||||
|
const FID = FeedId.unchecked("opaque-feed-id");
|
||||||
|
const MBOX = MailboxId.unchecked("a.b.42");
|
||||||
|
|
||||||
|
const mockEnv = () => createMockEnv() as unknown as Env;
|
||||||
|
|
||||||
|
const fixedClock = (now: number): Clock => ({ now: () => now });
|
||||||
|
|
||||||
|
const createInput = (
|
||||||
|
overrides: Partial<CreateFeedInput> = {},
|
||||||
|
): CreateFeedInput => ({
|
||||||
|
title: "News",
|
||||||
|
language: "en",
|
||||||
|
allowedSenders: [],
|
||||||
|
blockedSenders: [],
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
const state = (overrides: Partial<FeedState> = {}): FeedState => ({
|
||||||
|
title: "T",
|
||||||
|
language: "en",
|
||||||
|
mailboxId: "a.b.42",
|
||||||
|
allowedSenders: [],
|
||||||
|
blockedSenders: [],
|
||||||
|
createdAt: 0,
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
const entry = (overrides: Partial<EmailMetadata> = {}): EmailMetadata => ({
|
||||||
|
key: "feed:a.b.42:1",
|
||||||
|
subject: "Hello",
|
||||||
|
receivedAt: 1,
|
||||||
|
size: 10,
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Feed.create", () => {
|
||||||
|
it("builds a config with an empty email index and no expiry by default", () => {
|
||||||
|
const feed = Feed.create(FID, createInput(), { mailboxId: MBOX });
|
||||||
|
expect(feed.id.value).toBe("opaque-feed-id");
|
||||||
|
expect(feed.mailboxId.value).toBe("a.b.42");
|
||||||
|
expect(feed.title).toBe("News");
|
||||||
|
expect(feed.expiresAt).toBeUndefined();
|
||||||
|
expect(feed.emails).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("resolves expiry from the supplied lifetime using the injected clock", () => {
|
||||||
|
const NOW = 1_000_000;
|
||||||
|
const feed = Feed.create(FID, createInput(), {
|
||||||
|
mailboxId: MBOX,
|
||||||
|
clock: fixedClock(NOW),
|
||||||
|
lifetime: Lifetime.ofHours(2),
|
||||||
|
});
|
||||||
|
expect(feed.createdAt).toBe(NOW);
|
||||||
|
expect(feed.updatedAt).toBe(NOW);
|
||||||
|
expect(feed.expiresAt).toBe(NOW + 2 * 3_600_000);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("trusts only deps.lifetime, not the client lifetimeHours field", () => {
|
||||||
|
// The aggregate no longer parses lifetime policy: the application resolves
|
||||||
|
// the effective Lifetime (env override etc.) and hands it in.
|
||||||
|
const feed = Feed.create(FID, createInput({ lifetimeHours: 9999 }), {
|
||||||
|
mailboxId: MBOX,
|
||||||
|
});
|
||||||
|
expect(feed.expiresAt).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("treats a non-positive lifetime as no expiry", () => {
|
||||||
|
expect(
|
||||||
|
Feed.create(FID, createInput(), {
|
||||||
|
mailboxId: MBOX,
|
||||||
|
lifetime: Lifetime.ofHours(0),
|
||||||
|
}).expiresAt,
|
||||||
|
).toBeUndefined();
|
||||||
|
expect(
|
||||||
|
Feed.create(FID, createInput(), {
|
||||||
|
mailboxId: MBOX,
|
||||||
|
lifetime: Lifetime.ofHours(-5),
|
||||||
|
}).expiresAt,
|
||||||
|
).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Feed.isExpired / accepts", () => {
|
||||||
|
it("reports expiry against the configured instant", () => {
|
||||||
|
const feed = Feed.reconstitute(FID, state({ expiresAt: 100 }), {
|
||||||
|
emails: [],
|
||||||
|
});
|
||||||
|
expect(feed.isExpired(50)).toBe(false);
|
||||||
|
expect(feed.isExpired(150)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("uses the injected clock when no instant is supplied", () => {
|
||||||
|
const feed = Feed.reconstitute(
|
||||||
|
FID,
|
||||||
|
state({ expiresAt: 100 }),
|
||||||
|
{ emails: [] },
|
||||||
|
fixedClock(150),
|
||||||
|
);
|
||||||
|
expect(feed.isExpired()).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("applies the sender policy", () => {
|
||||||
|
const feed = Feed.reconstitute(
|
||||||
|
FID,
|
||||||
|
state({ allowedSenders: ["good@example.com"] }),
|
||||||
|
{ emails: [] },
|
||||||
|
);
|
||||||
|
expect(feed.accepts(["good@example.com"])).toBe("accepted");
|
||||||
|
expect(feed.accepts(["bad@example.com"])).toBe("blocked");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Feed.edit", () => {
|
||||||
|
it("recomputes expiry only when a lifetime is supplied", () => {
|
||||||
|
const NOW = 5_000_000;
|
||||||
|
const FUTURE = NOW + 10 * 3_600_000;
|
||||||
|
const feed = Feed.reconstitute(
|
||||||
|
FID,
|
||||||
|
state({ expiresAt: FUTURE }),
|
||||||
|
{ emails: [] },
|
||||||
|
fixedClock(NOW),
|
||||||
|
);
|
||||||
|
|
||||||
|
feed.edit({ title: "T2" }); // no lifetime ⇒ expiry preserved
|
||||||
|
expect(feed.expiresAt).toBe(FUTURE);
|
||||||
|
expect(feed.updatedAt).toBe(NOW);
|
||||||
|
|
||||||
|
feed.edit({ title: "T3" }, { lifetime: Lifetime.ofHours(1) });
|
||||||
|
expect(feed.expiresAt).toBe(NOW + 3_600_000);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("refuses to edit an already-expired feed", () => {
|
||||||
|
const feed = Feed.reconstitute(
|
||||||
|
FID,
|
||||||
|
state({ expiresAt: 100 }),
|
||||||
|
{ emails: [] },
|
||||||
|
fixedClock(200),
|
||||||
|
);
|
||||||
|
expect(feed.edit({ title: "X" }).status).toBe("expired");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Feed.ingest", () => {
|
||||||
|
it("prepends the entry, tracks icon/unsub and trims to the byte budget", () => {
|
||||||
|
const feed = Feed.reconstitute(FID, state(), {
|
||||||
|
emails: [entry({ key: "old", size: 400 })],
|
||||||
|
});
|
||||||
|
|
||||||
|
const { dropped } = feed.ingest(entry({ key: "new", size: 400 }), {
|
||||||
|
maxBytes: 500,
|
||||||
|
iconDomain: "example.com",
|
||||||
|
unsub: { senderKey: "news@example.com", url: "https://u/1" },
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(feed.emails[0].key).toBe("new");
|
||||||
|
expect(feed.iconDomain).toBe("example.com");
|
||||||
|
expect(feed.unsubscribeUrls()).toEqual({
|
||||||
|
"news@example.com": "https://u/1",
|
||||||
|
});
|
||||||
|
expect(dropped.map((e) => e.key)).toEqual(["old"]);
|
||||||
|
expect(feed.emails.map((e) => e.key)).toEqual(["new"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("always keeps the just-ingested entry, even when it alone is oversized", () => {
|
||||||
|
const feed = Feed.reconstitute(FID, state(), { emails: [] });
|
||||||
|
|
||||||
|
const { dropped } = feed.ingest(entry({ key: "huge", size: 999 }), {
|
||||||
|
maxBytes: 1,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(dropped).toEqual([]);
|
||||||
|
expect(feed.emails.map((e) => e.key)).toEqual(["huge"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Feed.removeEmails", () => {
|
||||||
|
it("drops matching keys and returns the removed entries", () => {
|
||||||
|
const feed = Feed.reconstitute(FID, state(), {
|
||||||
|
emails: [
|
||||||
|
entry({ key: "k1" }),
|
||||||
|
entry({ key: "k2" }),
|
||||||
|
entry({ key: "k3" }),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const { removed } = feed.removeEmails(["k1", "k3", "missing"]);
|
||||||
|
expect(removed.map((e) => e.key).sort()).toEqual(["k1", "k3"]);
|
||||||
|
expect(feed.emails.map((e) => e.key)).toEqual(["k2"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Feed events", () => {
|
||||||
|
it("records FeedCreated on create and drains it once", () => {
|
||||||
|
const feed = Feed.create(FID, createInput(), { mailboxId: MBOX });
|
||||||
|
expect(feed.pullEvents()).toEqual([{ type: "FeedCreated", feedId: FID }]);
|
||||||
|
// Draining clears: a second pull is empty.
|
||||||
|
expect(feed.pullEvents()).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("records EmailIngested (with icon domain) on ingest", () => {
|
||||||
|
const feed = Feed.reconstitute(FID, state(), { emails: [] });
|
||||||
|
feed.ingest(entry({ key: "k" }), {
|
||||||
|
maxBytes: 1_000_000,
|
||||||
|
iconDomain: "example.com",
|
||||||
|
});
|
||||||
|
expect(feed.pullEvents()).toEqual([
|
||||||
|
{ type: "EmailIngested", feedId: FID, iconDomain: "example.com" },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("emits no events for edit / removeEmails", () => {
|
||||||
|
const feed = Feed.reconstitute(
|
||||||
|
FID,
|
||||||
|
state({ expiresAt: 9_999_999_999 }),
|
||||||
|
{ emails: [entry({ key: "k1" })] },
|
||||||
|
fixedClock(1000),
|
||||||
|
);
|
||||||
|
feed.edit({ title: "X" });
|
||||||
|
feed.edit({ description: "Y" });
|
||||||
|
feed.removeEmails(["k1"]);
|
||||||
|
expect(feed.pullEvents()).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
function newFeed(): Feed {
|
||||||
|
return Feed.create(
|
||||||
|
FeedId.generate(),
|
||||||
|
{
|
||||||
|
title: "T",
|
||||||
|
description: "",
|
||||||
|
language: "en",
|
||||||
|
allowedSenders: [],
|
||||||
|
blockedSenders: [],
|
||||||
|
},
|
||||||
|
{ mailboxId: MailboxId.unchecked("alpha.beta.10") },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function confirmationEmail(
|
||||||
|
key: string,
|
||||||
|
confirmation?: { links: string[] },
|
||||||
|
): EmailMetadata {
|
||||||
|
return {
|
||||||
|
key,
|
||||||
|
subject: "s",
|
||||||
|
receivedAt: Date.now(),
|
||||||
|
size: 10,
|
||||||
|
...(confirmation ? { confirmation } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("Feed pendingConfirmation", () => {
|
||||||
|
it("is false on a fresh feed", () => {
|
||||||
|
expect(newFeed().pendingConfirmation).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("is raised when a confirmation email is ingested", () => {
|
||||||
|
const feed = newFeed();
|
||||||
|
feed.ingest(confirmationEmail("k1", { links: ["https://x/confirm"] }), {
|
||||||
|
maxBytes: 1_000_000,
|
||||||
|
});
|
||||||
|
expect(feed.pendingConfirmation).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("stays false for a non-confirmation email", () => {
|
||||||
|
const feed = newFeed();
|
||||||
|
feed.ingest(confirmationEmail("k1"), { maxBytes: 1_000_000 });
|
||||||
|
expect(feed.pendingConfirmation).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("is cleared by dismissConfirmation", () => {
|
||||||
|
const feed = newFeed();
|
||||||
|
feed.ingest(confirmationEmail("k1", { links: ["https://x/confirm"] }), {
|
||||||
|
maxBytes: 1_000_000,
|
||||||
|
});
|
||||||
|
feed.dismissConfirmation();
|
||||||
|
expect(feed.pendingConfirmation).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not re-raise after dismiss when removing an unrelated email", () => {
|
||||||
|
const feed = newFeed();
|
||||||
|
feed.ingest(confirmationEmail("k1", { links: ["https://x/confirm"] }), {
|
||||||
|
maxBytes: 1_000_000,
|
||||||
|
});
|
||||||
|
feed.ingest(confirmationEmail("k2"), { maxBytes: 1_000_000 });
|
||||||
|
feed.dismissConfirmation();
|
||||||
|
feed.removeEmails(["k2"]);
|
||||||
|
expect(feed.pendingConfirmation).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("clears when the last confirmation email is removed", () => {
|
||||||
|
const feed = newFeed();
|
||||||
|
feed.ingest(confirmationEmail("k1", { links: ["https://x/confirm"] }), {
|
||||||
|
maxBytes: 1_000_000,
|
||||||
|
});
|
||||||
|
feed.removeEmails(["k1"]);
|
||||||
|
expect(feed.pendingConfirmation).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("FeedRepository.load / save round-trip", () => {
|
||||||
|
it("persists a created feed and reflects later mutations", async () => {
|
||||||
|
const repo = new FeedRepository(mockEnv().EMAIL_STORAGE);
|
||||||
|
const created = Feed.create(FID, createInput({ title: "Round" }), {
|
||||||
|
mailboxId: MBOX,
|
||||||
|
});
|
||||||
|
await repo.save(created);
|
||||||
|
|
||||||
|
const loaded = await repo.load(FID);
|
||||||
|
expect(loaded).not.toBeNull();
|
||||||
|
expect(loaded!.title).toBe("Round");
|
||||||
|
expect(loaded!.mailboxId.value).toBe("a.b.42");
|
||||||
|
|
||||||
|
loaded!.ingest(entry({ key: "feed:opaque-feed-id:1" }), {
|
||||||
|
maxBytes: 1_000_000,
|
||||||
|
});
|
||||||
|
await repo.saveMetadata(loaded!);
|
||||||
|
|
||||||
|
const reloaded = await repo.load(FID);
|
||||||
|
expect(reloaded!.emails.map((e) => e.key)).toEqual([
|
||||||
|
"feed:opaque-feed-id:1",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns null when the feed has no config", async () => {
|
||||||
|
const repo = new FeedRepository(mockEnv().EMAIL_STORAGE);
|
||||||
|
expect(await repo.load(FeedId.unchecked("missing"))).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Feed native feeds", () => {
|
||||||
|
const nf = (
|
||||||
|
senderKey: string,
|
||||||
|
url: string,
|
||||||
|
type: "rss" | "atom" | "json",
|
||||||
|
) => ({
|
||||||
|
maxBytes: 1_000_000_000,
|
||||||
|
nativeFeeds: { senderKey, feeds: [{ url, type }] },
|
||||||
|
});
|
||||||
|
|
||||||
|
it("stores native feeds and raises the flag on ingest", () => {
|
||||||
|
const feed = Feed.create(FID, createInput(), { mailboxId: MBOX });
|
||||||
|
feed.ingest(entry(), nf("a@x.com", "https://x.com/rss", "rss"));
|
||||||
|
expect(feed.nativeFeeds()).toEqual([
|
||||||
|
{ url: "https://x.com/rss", type: "rss" },
|
||||||
|
]);
|
||||||
|
expect(feed.hasNativeFeed()).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("latest non-empty wins per sender; other senders preserved", () => {
|
||||||
|
const feed = Feed.create(FID, createInput(), { mailboxId: MBOX });
|
||||||
|
feed.ingest(
|
||||||
|
entry({ key: "k1" }),
|
||||||
|
nf("a@x.com", "https://x.com/old", "rss"),
|
||||||
|
);
|
||||||
|
feed.ingest(
|
||||||
|
entry({ key: "k2" }),
|
||||||
|
nf("b@y.com", "https://y.com/atom", "atom"),
|
||||||
|
);
|
||||||
|
feed.ingest(
|
||||||
|
entry({ key: "k3" }),
|
||||||
|
nf("a@x.com", "https://x.com/new", "rss"),
|
||||||
|
);
|
||||||
|
expect(feed.nativeFeeds()).toEqual([
|
||||||
|
{ url: "https://x.com/new", type: "rss" },
|
||||||
|
{ url: "https://y.com/atom", type: "atom" },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("dismiss hides the notice but keeps URLs; only a new URL re-raises", () => {
|
||||||
|
const feed = Feed.create(FID, createInput(), { mailboxId: MBOX });
|
||||||
|
feed.ingest(
|
||||||
|
entry({ key: "k1" }),
|
||||||
|
nf("a@x.com", "https://x.com/rss", "rss"),
|
||||||
|
);
|
||||||
|
feed.dismissNativeFeed();
|
||||||
|
expect(feed.hasNativeFeed()).toBe(false);
|
||||||
|
expect(feed.nativeFeeds()).toHaveLength(1);
|
||||||
|
feed.ingest(
|
||||||
|
entry({ key: "k2" }),
|
||||||
|
nf("a@x.com", "https://x.com/rss", "rss"),
|
||||||
|
);
|
||||||
|
expect(feed.hasNativeFeed()).toBe(false); // same URL → stays dismissed
|
||||||
|
feed.ingest(
|
||||||
|
entry({ key: "k3" }),
|
||||||
|
nf("a@x.com", "https://x.com/rss2", "rss"),
|
||||||
|
);
|
||||||
|
expect(feed.hasNativeFeed()).toBe(true); // new URL → re-raise
|
||||||
|
});
|
||||||
|
|
||||||
|
it("removeEmails leaves native feeds intact", () => {
|
||||||
|
const feed = Feed.create(FID, createInput(), { mailboxId: MBOX });
|
||||||
|
feed.ingest(
|
||||||
|
entry({ key: "k1" }),
|
||||||
|
nf("a@x.com", "https://x.com/rss", "rss"),
|
||||||
|
);
|
||||||
|
feed.removeEmails(["k1"]);
|
||||||
|
expect(feed.nativeFeeds()).toEqual([
|
||||||
|
{ url: "https://x.com/rss", type: "rss" },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,393 @@
|
|||||||
|
import { FeedMetadata, EmailMetadata, NativeFeed } from "../types";
|
||||||
|
import { FeedState } from "./feed-state";
|
||||||
|
import { FeedId } from "./value-objects/feed-id";
|
||||||
|
import { MailboxId } from "./value-objects/mailbox-id";
|
||||||
|
import { Lifetime } from "./value-objects/lifetime";
|
||||||
|
import { SenderPolicy, SenderDecision } from "./value-objects/sender-policy";
|
||||||
|
import { Clock, systemClock } from "./clock";
|
||||||
|
import { FeedEvent } from "./events";
|
||||||
|
import { unionNativeFeeds } from "./native-feed";
|
||||||
|
|
||||||
|
export interface CreateFeedInput {
|
||||||
|
title: string;
|
||||||
|
description?: string;
|
||||||
|
language: string;
|
||||||
|
allowedSenders: string[];
|
||||||
|
blockedSenders: string[];
|
||||||
|
/** When true, render entry titles as `[Sender] Subject` in the feed output. */
|
||||||
|
senderInTitle?: boolean;
|
||||||
|
/** Raw client-requested lifetime; the application resolves it into a `Lifetime`. */
|
||||||
|
lifetimeHours?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UpdateFeedInput {
|
||||||
|
title?: string;
|
||||||
|
description?: string;
|
||||||
|
language?: string;
|
||||||
|
allowedSenders?: string[];
|
||||||
|
blockedSenders?: string[];
|
||||||
|
senderInTitle?: boolean;
|
||||||
|
lifetimeHours?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Dependencies the aggregate needs from the outside but must not reach for
|
||||||
|
* itself: a clock (never ambient `Date.now()`) and an already-resolved
|
||||||
|
* `Lifetime`. The application layer decides the lifetime — parsing env config and
|
||||||
|
* applying any server-side `FEED_TTL_HOURS` override — and hands the VO in.
|
||||||
|
*/
|
||||||
|
export interface CreateFeedDeps {
|
||||||
|
/** The feed's inbound mailbox, minted by the application alongside its FeedId. */
|
||||||
|
mailboxId: MailboxId;
|
||||||
|
clock?: Clock;
|
||||||
|
/** Effective lifetime, already resolved by the application. */
|
||||||
|
lifetime?: Lifetime;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface EditFeedDeps {
|
||||||
|
/**
|
||||||
|
* Effective lifetime, already resolved by the application. Its *presence* means
|
||||||
|
* "recompute expiry"; its absence preserves the current expiry — which covers
|
||||||
|
* the dashboard's title/description quick-edit.
|
||||||
|
*/
|
||||||
|
lifetime?: Lifetime;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IngestOptions {
|
||||||
|
maxBytes: number;
|
||||||
|
iconDomain?: string;
|
||||||
|
/** RFC 8058 one-click unsubscribe link, keyed by the sending newsletter. */
|
||||||
|
unsub?: { senderKey: string; url: string };
|
||||||
|
/** Native syndication feeds the sender advertised, keyed by sender. */
|
||||||
|
nativeFeeds?: { senderKey: string; feeds: NativeFeed[] };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The Feed aggregate: the consistency boundary around a feed's config and the
|
||||||
|
* metadata index of its emails. All mutations to either go through a method
|
||||||
|
* here so the invariants (expiry policy, sender policy, byte budget) live in one
|
||||||
|
* place. Email bodies are large blobs referenced by `metadata.emails[].key` and
|
||||||
|
* deliberately sit *outside* the aggregate — the caller flushes them alongside
|
||||||
|
* `FeedRepository.save`/`saveMetadata`.
|
||||||
|
*
|
||||||
|
* Its config is held as domain `FeedState` (camelCase), never the snake_case
|
||||||
|
* persistence DTO — `FeedRepository` translates via `feed-mapper.ts`. I/O-free
|
||||||
|
* and time-free: load and persist through the repository; time comes from an
|
||||||
|
* injected `Clock`. KV has no multi-key transaction, so a future Durable Object
|
||||||
|
* keyed by feed id would wrap load→mutate→save to serialise concurrent writers
|
||||||
|
* (see email-processor.ts).
|
||||||
|
*/
|
||||||
|
export class Feed {
|
||||||
|
private readonly _events: FeedEvent[] = [];
|
||||||
|
|
||||||
|
private constructor(
|
||||||
|
readonly id: FeedId,
|
||||||
|
private _state: FeedState,
|
||||||
|
private _metadata: FeedMetadata,
|
||||||
|
private readonly clock: Clock,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/** Mint a brand-new feed with an empty email index. */
|
||||||
|
static create(
|
||||||
|
id: FeedId,
|
||||||
|
input: CreateFeedInput,
|
||||||
|
deps: CreateFeedDeps,
|
||||||
|
): Feed {
|
||||||
|
const clock = deps.clock ?? systemClock;
|
||||||
|
const now = clock.now();
|
||||||
|
const expiresAt = (deps.lifetime ?? Lifetime.never).resolveExpiry(now);
|
||||||
|
const state: FeedState = {
|
||||||
|
title: input.title,
|
||||||
|
description: input.description,
|
||||||
|
language: input.language,
|
||||||
|
mailboxId: deps.mailboxId.value,
|
||||||
|
senderInTitle: input.senderInTitle,
|
||||||
|
allowedSenders: input.allowedSenders,
|
||||||
|
blockedSenders: input.blockedSenders,
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now,
|
||||||
|
expiresAt,
|
||||||
|
};
|
||||||
|
const feed = new Feed(id, state, { emails: [] }, clock);
|
||||||
|
feed._events.push({ type: "FeedCreated", feedId: id });
|
||||||
|
return feed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Rebuild an aggregate from persisted (already-mapped) domain state. */
|
||||||
|
static reconstitute(
|
||||||
|
id: FeedId,
|
||||||
|
state: FeedState,
|
||||||
|
metadata: FeedMetadata,
|
||||||
|
clock: Clock = systemClock,
|
||||||
|
): Feed {
|
||||||
|
return new Feed(id, state, metadata, clock);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Intention-revealing reads ─────────────────────────────────────────────
|
||||||
|
// The aggregate exposes named fields and copies of its collections, never the
|
||||||
|
// raw `state`/`metadata` objects — a shallow `Readonly<…>` would still let a
|
||||||
|
// caller mutate the arrays inside. Persistence reads `state()` /
|
||||||
|
// `toMetadataSnapshot()`; the mapper derives the DTOs.
|
||||||
|
|
||||||
|
get title(): string {
|
||||||
|
return this._state.title;
|
||||||
|
}
|
||||||
|
|
||||||
|
get description(): string | undefined {
|
||||||
|
return this._state.description;
|
||||||
|
}
|
||||||
|
|
||||||
|
get language(): string {
|
||||||
|
return this._state.language;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The inbound mailbox (`noun.noun.NN`) — the feed's email address is `mailboxId@domain`. */
|
||||||
|
get mailboxId(): MailboxId {
|
||||||
|
return MailboxId.unchecked(this._state.mailboxId);
|
||||||
|
}
|
||||||
|
|
||||||
|
get createdAt(): number {
|
||||||
|
return this._state.createdAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
get updatedAt(): number | undefined {
|
||||||
|
return this._state.updatedAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
get expiresAt(): number | undefined {
|
||||||
|
return this._state.expiresAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
get iconDomain(): string | undefined {
|
||||||
|
return this._metadata.iconDomain;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True while at least one unactioned confirmation email is present. */
|
||||||
|
get pendingConfirmation(): boolean {
|
||||||
|
return this._metadata.pendingConfirmation ?? false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Discovered native feeds (Atom/RSS/JSON), union across senders, deduped. */
|
||||||
|
nativeFeeds(): NativeFeed[] {
|
||||||
|
return unionNativeFeeds(this._metadata.nativeFeeds);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True when a native feed was discovered and the notice was not dismissed. */
|
||||||
|
hasNativeFeed(): boolean {
|
||||||
|
return this.nativeFeeds().length > 0 && !this._metadata.nativeFeedDismissed;
|
||||||
|
}
|
||||||
|
|
||||||
|
allowedSenders(): string[] {
|
||||||
|
return [...this._state.allowedSenders];
|
||||||
|
}
|
||||||
|
|
||||||
|
blockedSenders(): string[] {
|
||||||
|
return [...this._state.blockedSenders];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A copy of the email index — mutating it never touches aggregate state. */
|
||||||
|
get emails(): readonly EmailMetadata[] {
|
||||||
|
return [...this._metadata.emails];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Per-sender one-click unsubscribe links (copy). */
|
||||||
|
unsubscribeUrls(): Record<string, string> {
|
||||||
|
return { ...(this._metadata.unsubscribe ?? {}) };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Persistence snapshots (repository-only) ───────────────────────────────
|
||||||
|
|
||||||
|
/** A copy of the domain config state for the repository to map + persist. */
|
||||||
|
state(): FeedState {
|
||||||
|
return {
|
||||||
|
...this._state,
|
||||||
|
allowedSenders: [...this._state.allowedSenders],
|
||||||
|
blockedSenders: [...this._state.blockedSenders],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A serialisable copy of the email index for the repository to persist. */
|
||||||
|
toMetadataSnapshot(): FeedMetadata {
|
||||||
|
return { ...this._metadata, emails: [...this._metadata.emails] };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Drain the domain events recorded since the last pull. The application layer
|
||||||
|
* calls this after persisting and feeds them to a dispatcher that runs the
|
||||||
|
* side effects (counters, WebSub, favicon). Clearing on read keeps a long-lived
|
||||||
|
* aggregate from re-emitting.
|
||||||
|
*/
|
||||||
|
pullEvents(): FeedEvent[] {
|
||||||
|
return this._events.splice(0, this._events.length);
|
||||||
|
}
|
||||||
|
|
||||||
|
isExpired(now: number = this.clock.now()): boolean {
|
||||||
|
// The shared `isExpired` predicate (domain/feed.ts) lives on the read path
|
||||||
|
// and speaks the persistence DTO; the aggregate checks its own domain state.
|
||||||
|
return this._state.expiresAt !== undefined && this._state.expiresAt <= now;
|
||||||
|
}
|
||||||
|
|
||||||
|
accepts(senders: string[]): SenderDecision {
|
||||||
|
return SenderPolicy.fromLists(
|
||||||
|
this._state.allowedSenders,
|
||||||
|
this._state.blockedSenders,
|
||||||
|
).decide(senders);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check whether the email index already contains a duplicate of the incoming
|
||||||
|
* email. Dedup uses `messageId` as the primary key (when both sides have one)
|
||||||
|
* and falls back to `dedupHash` (SHA-256 of normalised subject+content).
|
||||||
|
* Old entries that predate the feature and carry neither field are never
|
||||||
|
* matched — they cannot cause false positives.
|
||||||
|
*/
|
||||||
|
hasDuplicate(messageId?: string, dedupHash?: string): boolean {
|
||||||
|
for (const entry of this._metadata.emails) {
|
||||||
|
if (messageId && entry.messageId && entry.messageId === messageId) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
!messageId &&
|
||||||
|
dedupHash &&
|
||||||
|
entry.dedupHash &&
|
||||||
|
entry.dedupHash === dedupHash
|
||||||
|
) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add an email to the front of the index, refresh the icon domain and the
|
||||||
|
* per-sender unsubscribe link, then trim the oldest entries back under the
|
||||||
|
* byte budget. Returns the dropped entries so the caller can purge their
|
||||||
|
* bodies/attachments.
|
||||||
|
*/
|
||||||
|
ingest(
|
||||||
|
entry: EmailMetadata,
|
||||||
|
opts: IngestOptions,
|
||||||
|
): { dropped: EmailMetadata[] } {
|
||||||
|
this._metadata.emails.unshift(entry);
|
||||||
|
|
||||||
|
if (opts.iconDomain) {
|
||||||
|
this._metadata.iconDomain = opts.iconDomain;
|
||||||
|
}
|
||||||
|
if (opts.unsub) {
|
||||||
|
this._metadata.unsubscribe = {
|
||||||
|
...(this._metadata.unsubscribe ?? {}),
|
||||||
|
[opts.unsub.senderKey]: opts.unsub.url,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (entry.confirmation) {
|
||||||
|
this._metadata.pendingConfirmation = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (opts.nativeFeeds && opts.nativeFeeds.feeds.length > 0) {
|
||||||
|
const known = new Set(this.nativeFeeds().map((f) => f.url));
|
||||||
|
this._metadata.nativeFeeds = {
|
||||||
|
...(this._metadata.nativeFeeds ?? {}),
|
||||||
|
[opts.nativeFeeds.senderKey]: opts.nativeFeeds.feeds,
|
||||||
|
};
|
||||||
|
// Re-raise the notice only when a genuinely new URL appears, so a dismiss
|
||||||
|
// survives the same feed being re-advertised on every subsequent email.
|
||||||
|
if (opts.nativeFeeds.feeds.some((f) => !known.has(f.url))) {
|
||||||
|
this._metadata.nativeFeedDismissed = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this._events.push({
|
||||||
|
type: "EmailIngested",
|
||||||
|
feedId: this.id,
|
||||||
|
iconDomain: opts.iconDomain,
|
||||||
|
});
|
||||||
|
return this.trimToByteBudget(opts.maxBytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enforce the per-feed byte budget by dropping the oldest emails (from the
|
||||||
|
* tail of the index) until the total fits, always keeping at least one entry.
|
||||||
|
* Returns the dropped entries so the caller can purge their KV/R2 storage.
|
||||||
|
*/
|
||||||
|
private trimToByteBudget(maxBytes: number): { dropped: EmailMetadata[] } {
|
||||||
|
const emails = this._metadata.emails;
|
||||||
|
let totalSize = emails.reduce((sum, e) => sum + (e.size ?? 0), 0);
|
||||||
|
const dropped: EmailMetadata[] = [];
|
||||||
|
while (totalSize > maxBytes && emails.length > 1) {
|
||||||
|
const entry = emails.pop()!;
|
||||||
|
totalSize -= entry.size ?? 0;
|
||||||
|
dropped.push(entry);
|
||||||
|
}
|
||||||
|
return { dropped };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Drop the given email keys from the index. Returns the removed entries so the
|
||||||
|
* caller can purge their bodies/attachments.
|
||||||
|
*/
|
||||||
|
removeEmails(keys: string[]): { removed: EmailMetadata[] } {
|
||||||
|
const target = new Set(keys);
|
||||||
|
const removed: EmailMetadata[] = [];
|
||||||
|
const kept: EmailMetadata[] = [];
|
||||||
|
for (const entry of this._metadata.emails) {
|
||||||
|
(target.has(entry.key) ? removed : kept).push(entry);
|
||||||
|
}
|
||||||
|
this._metadata.emails = kept;
|
||||||
|
// Lower-only: clear when no confirmation email remains. Never re-raise here,
|
||||||
|
// so an admin "dismiss" survives deletion of unrelated emails.
|
||||||
|
if (!kept.some((e) => e.confirmation)) {
|
||||||
|
this._metadata.pendingConfirmation = false;
|
||||||
|
}
|
||||||
|
return { removed };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mark the pending confirmation as handled — "stop reminding me". */
|
||||||
|
dismissConfirmation(): void {
|
||||||
|
this._metadata.pendingConfirmation = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mark the native-feed notice as handled — "stop reminding me". */
|
||||||
|
dismissNativeFeed(): void {
|
||||||
|
this._metadata.nativeFeedDismissed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The single edit path. Apply the patch (only the fields it carries) and
|
||||||
|
* recompute expiry when the application supplies a `Lifetime` — an absent
|
||||||
|
* lifetime preserves the current expiry, which covers the dashboard's
|
||||||
|
* title/description quick-edit. Rejects an already-expired feed without
|
||||||
|
* mutating it, so a quick-edit can no more touch an expired feed than a full
|
||||||
|
* edit can.
|
||||||
|
*/
|
||||||
|
edit(
|
||||||
|
patch: UpdateFeedInput,
|
||||||
|
deps: EditFeedDeps = {},
|
||||||
|
): { status: "ok" | "expired" } {
|
||||||
|
if (this.isExpired()) return { status: "expired" };
|
||||||
|
|
||||||
|
const now = this.clock.now();
|
||||||
|
const expiresAt = deps.lifetime
|
||||||
|
? deps.lifetime.resolveExpiry(now)
|
||||||
|
: this._state.expiresAt;
|
||||||
|
|
||||||
|
if (patch.title !== undefined) this._state.title = patch.title;
|
||||||
|
if (patch.description !== undefined) {
|
||||||
|
this._state.description = patch.description;
|
||||||
|
}
|
||||||
|
if (patch.language !== undefined) this._state.language = patch.language;
|
||||||
|
if (patch.senderInTitle !== undefined) {
|
||||||
|
this._state.senderInTitle = patch.senderInTitle;
|
||||||
|
}
|
||||||
|
if (patch.allowedSenders !== undefined) {
|
||||||
|
this._state.allowedSenders = patch.allowedSenders;
|
||||||
|
}
|
||||||
|
if (patch.blockedSenders !== undefined) {
|
||||||
|
this._state.blockedSenders = patch.blockedSenders;
|
||||||
|
}
|
||||||
|
this._state.updatedAt = now;
|
||||||
|
this._state.expiresAt = expiresAt;
|
||||||
|
|
||||||
|
return { status: "ok" };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import { isExpired } from "./feed";
|
||||||
|
|
||||||
|
describe("isExpired", () => {
|
||||||
|
it("is false when no expiry is set", () => {
|
||||||
|
expect(isExpired({ expires_at: undefined }, 1000)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("is true at or past the expiry instant", () => {
|
||||||
|
expect(isExpired({ expires_at: 1000 }, 1000)).toBe(true);
|
||||||
|
expect(isExpired({ expires_at: 1000 }, 1001)).toBe(true);
|
||||||
|
expect(isExpired({ expires_at: 1000 }, 999)).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { FeedConfig } from "../types";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The expiry predicate, shared between the Feed aggregate and the read-model
|
||||||
|
* routes (rss/atom/entries) that render from a config snapshot without loading
|
||||||
|
* the aggregate. This is the *only* feed invariant that lives outside the
|
||||||
|
* aggregate, precisely because the hot read path bypasses it.
|
||||||
|
*
|
||||||
|
* `now` defaults to the wall clock for convenience at the HTTP edge; the
|
||||||
|
* aggregate always passes its injected clock so its own behaviour stays
|
||||||
|
* deterministic.
|
||||||
|
*/
|
||||||
|
export function isExpired(
|
||||||
|
config: Pick<FeedConfig, "expires_at">,
|
||||||
|
now: number = Date.now(),
|
||||||
|
): boolean {
|
||||||
|
return config.expires_at !== undefined && config.expires_at <= now;
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
/** Human-readable byte size (B / KB / MB / GB). */
|
||||||
|
export function formatBytes(bytes: number): string {
|
||||||
|
if (bytes < 1024) return `${bytes} B`;
|
||||||
|
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
||||||
|
if (bytes < 1024 * 1024 * 1024)
|
||||||
|
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
||||||
|
return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import { detectNativeFeeds, unionNativeFeeds } from "./native-feed";
|
||||||
|
|
||||||
|
describe("detectNativeFeeds", () => {
|
||||||
|
it("maps the three canonical MIME types to kinds", () => {
|
||||||
|
expect(
|
||||||
|
detectNativeFeeds([
|
||||||
|
{ href: "https://x.com/atom", type: "application/atom+xml" },
|
||||||
|
{ href: "https://x.com/rss", type: "application/rss+xml" },
|
||||||
|
{ href: "https://x.com/json", type: "application/feed+json" },
|
||||||
|
]),
|
||||||
|
).toEqual([
|
||||||
|
{ url: "https://x.com/atom", type: "atom" },
|
||||||
|
{ url: "https://x.com/rss", type: "rss" },
|
||||||
|
{ url: "https://x.com/json", type: "json" },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ignores unknown MIME types (application/json, text/html)", () => {
|
||||||
|
expect(
|
||||||
|
detectNativeFeeds([
|
||||||
|
{ href: "https://x.com/api", type: "application/json" },
|
||||||
|
{ href: "https://x.com/", type: "text/html" },
|
||||||
|
]),
|
||||||
|
).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("strips MIME parameters and is case-insensitive", () => {
|
||||||
|
expect(
|
||||||
|
detectNativeFeeds([
|
||||||
|
{ href: "https://x.com/f", type: "Application/RSS+XML; charset=utf-8" },
|
||||||
|
]),
|
||||||
|
).toEqual([{ url: "https://x.com/f", type: "rss" }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("dedupes by URL (first kind wins)", () => {
|
||||||
|
expect(
|
||||||
|
detectNativeFeeds([
|
||||||
|
{ href: "https://x.com/f", type: "application/rss+xml" },
|
||||||
|
{ href: "https://x.com/f", type: "application/atom+xml" },
|
||||||
|
]),
|
||||||
|
).toEqual([{ url: "https://x.com/f", type: "rss" }]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("unionNativeFeeds", () => {
|
||||||
|
it("returns [] for undefined", () => {
|
||||||
|
expect(unionNativeFeeds(undefined)).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("unions across senders, deduping by URL", () => {
|
||||||
|
expect(
|
||||||
|
unionNativeFeeds({
|
||||||
|
"a@x.com": [{ url: "https://x.com/rss", type: "rss" }],
|
||||||
|
"b@y.com": [
|
||||||
|
{ url: "https://x.com/rss", type: "rss" },
|
||||||
|
{ url: "https://y.com/atom", type: "atom" },
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
).toEqual([
|
||||||
|
{ url: "https://x.com/rss", type: "rss" },
|
||||||
|
{ url: "https://y.com/atom", type: "atom" },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
/**
|
||||||
|
* Pure detection of a newsletter's own syndication feed. No DOM, no I/O — it
|
||||||
|
* receives already-extracted <link> tuples (infra parses the HTML) and decides
|
||||||
|
* which ones are real feeds. This module owns the business knowledge: the strict
|
||||||
|
* set of recognized feed MIME types.
|
||||||
|
*/
|
||||||
|
import { NativeFeed } from "../types";
|
||||||
|
|
||||||
|
// MIME type → feed kind. Strict: only the three canonical syndication types.
|
||||||
|
// `application/json` is deliberately excluded — too broad, captures non-feeds.
|
||||||
|
const MIME_TO_KIND: Record<string, NativeFeed["type"]> = {
|
||||||
|
"application/atom+xml": "atom",
|
||||||
|
"application/rss+xml": "rss",
|
||||||
|
"application/feed+json": "json",
|
||||||
|
};
|
||||||
|
|
||||||
|
// Drop MIME parameters ("; charset=…"), trim, lowercase.
|
||||||
|
function normalizeMime(type: string): string {
|
||||||
|
return type.split(";")[0].trim().toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Map raw <link> tuples to recognized native feeds, deduped by URL. */
|
||||||
|
export function detectNativeFeeds(
|
||||||
|
links: { href: string; type: string }[],
|
||||||
|
): NativeFeed[] {
|
||||||
|
const out: NativeFeed[] = [];
|
||||||
|
const seen = new Set<string>();
|
||||||
|
for (const link of links) {
|
||||||
|
const kind = MIME_TO_KIND[normalizeMime(link.type)];
|
||||||
|
if (!kind) continue;
|
||||||
|
const url = link.href.trim();
|
||||||
|
if (!url || seen.has(url)) continue;
|
||||||
|
seen.add(url);
|
||||||
|
out.push({ url, type: kind });
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Flatten per-sender native feeds into one list, deduped by URL (first wins). */
|
||||||
|
export function unionNativeFeeds(
|
||||||
|
bySender: Record<string, NativeFeed[]> | undefined,
|
||||||
|
): NativeFeed[] {
|
||||||
|
if (!bySender) return [];
|
||||||
|
const out: NativeFeed[] = [];
|
||||||
|
const seen = new Set<string>();
|
||||||
|
for (const feeds of Object.values(bySender)) {
|
||||||
|
for (const feed of feeds) {
|
||||||
|
if (seen.has(feed.url)) continue;
|
||||||
|
seen.add(feed.url);
|
||||||
|
out.push({ ...feed });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import { Domain } from "./domain";
|
||||||
|
|
||||||
|
describe("Domain", () => {
|
||||||
|
it("normalises case and whitespace", () => {
|
||||||
|
expect(Domain.parse(" Example.COM ")?.value).toBe("example.com");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("strips a leading @ and trailing dots", () => {
|
||||||
|
expect(Domain.parse("@example.com")?.value).toBe("example.com");
|
||||||
|
expect(Domain.parse("example.com.")?.value).toBe("example.com");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns null for empty input", () => {
|
||||||
|
expect(Domain.parse("")).toBeNull();
|
||||||
|
expect(Domain.parse("@")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("compares by normalised value", () => {
|
||||||
|
expect(
|
||||||
|
Domain.parse("Example.com")!.matches(Domain.parse("example.com")!),
|
||||||
|
).toBe(true);
|
||||||
|
expect(Domain.parse("a.com")!.matches(Domain.parse("b.com")!)).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
/**
|
||||||
|
* A normalised DNS domain (lowercased, no leading `@`, no trailing dots).
|
||||||
|
* Accepts both bare (`example.com`) and allowlist-style (`@example.com`) input.
|
||||||
|
*/
|
||||||
|
export class Domain {
|
||||||
|
private constructor(readonly value: string) {}
|
||||||
|
|
||||||
|
static parse(raw: string): Domain | null {
|
||||||
|
const normalized = raw
|
||||||
|
.trim()
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/^@+/, "")
|
||||||
|
.replace(/\.+$/, "");
|
||||||
|
return normalized ? new Domain(normalized) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
matches(other: Domain): boolean {
|
||||||
|
return this.value === other.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
toString(): string {
|
||||||
|
return this.value;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import { EmailAddress } from "./email-address";
|
||||||
|
|
||||||
|
describe("EmailAddress", () => {
|
||||||
|
it("parses a bare address and normalises it", () => {
|
||||||
|
const email = EmailAddress.parse("News@Example.COM")!;
|
||||||
|
expect(email.normalized).toBe("news@example.com");
|
||||||
|
expect(email.domain.value).toBe("example.com");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("parses a display form (Name <addr>)", () => {
|
||||||
|
const email = EmailAddress.parse("GitHub <news@GitHub.com>")!;
|
||||||
|
expect(email.normalized).toBe("news@github.com");
|
||||||
|
expect(email.domain.value).toBe("github.com");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("strips a trailing dot from the domain", () => {
|
||||||
|
expect(EmailAddress.parse("a@Example.COM.")?.domain.value).toBe(
|
||||||
|
"example.com",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns null when there is no address", () => {
|
||||||
|
expect(EmailAddress.parse("not an email")).toBeNull();
|
||||||
|
expect(EmailAddress.parse("")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("derives the sender site base URL from the domain", () => {
|
||||||
|
expect(EmailAddress.parse("News <a@Example.com>")?.siteBaseUrl()).toBe(
|
||||||
|
"https://example.com/",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("captures the display name verbatim from a display form", () => {
|
||||||
|
const email = EmailAddress.parse("Alice B <Alice@Example.com>")!;
|
||||||
|
expect(email.displayName).toBe("Alice B");
|
||||||
|
expect(email.label()).toBe("Alice B");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("has no display name for a bare address and labels by the address", () => {
|
||||||
|
const email = EmailAddress.parse("Bob@Example.com")!;
|
||||||
|
expect(email.displayName).toBeUndefined();
|
||||||
|
expect(email.label()).toBe("bob@example.com");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("falls back to the address as the label when the display name is empty", () => {
|
||||||
|
expect(EmailAddress.parse("<a@b.com>")?.label()).toBe("a@b.com");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { Domain } from "./domain";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A normalised email address. `parse` accepts a bare address (`a@b.com`) or a
|
||||||
|
* display form (`Name <a@b.com>`), lowercasing the local part and normalising
|
||||||
|
* the domain. When the input carries a display name it is captured (verbatim,
|
||||||
|
* not normalised — names are case-sensitive). Returns null when no plausible
|
||||||
|
* address can be found.
|
||||||
|
*/
|
||||||
|
export class EmailAddress {
|
||||||
|
private constructor(
|
||||||
|
readonly normalized: string,
|
||||||
|
readonly domain: Domain,
|
||||||
|
/** The sender's display name from a `Name <addr>` input, if any. */
|
||||||
|
readonly displayName?: string,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
static parse(raw: string): EmailAddress | null {
|
||||||
|
const match = raw.match(/([^\s<>@]+)@([^\s<>@]+)/);
|
||||||
|
if (!match) return null;
|
||||||
|
const domain = Domain.parse(match[2]);
|
||||||
|
if (!domain) return null;
|
||||||
|
const local = match[1].trim().toLowerCase();
|
||||||
|
const displayName =
|
||||||
|
raw.match(/^\s*(.+?)\s*<[^>]+>\s*$/)?.[1].trim() || undefined;
|
||||||
|
return new EmailAddress(`${local}@${domain.value}`, domain, displayName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The best human-readable label for this sender: the display name when the
|
||||||
|
* address came in `Name <addr>` form, else the normalised address.
|
||||||
|
*/
|
||||||
|
label(): string {
|
||||||
|
return this.displayName ?? this.normalized;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Best-effort website origin implied by the sender's domain
|
||||||
|
* (e.g. `https://example.com/`). Used to absolutize relative links in the
|
||||||
|
* email body — the sender's site is the only base we can infer.
|
||||||
|
*/
|
||||||
|
siteBaseUrl(): string {
|
||||||
|
return `https://${this.domain.value}/`;
|
||||||
|
}
|
||||||
|
|
||||||
|
toString(): string {
|
||||||
|
return this.normalized;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import { FeedId } from "./feed-id";
|
||||||
|
|
||||||
|
describe("FeedId.generate", () => {
|
||||||
|
it("produces an opaque base64url token", () => {
|
||||||
|
for (let i = 0; i < 50; i++) {
|
||||||
|
expect(FeedId.generate().value).toMatch(/^[A-Za-z0-9_-]{22}$/);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("is unguessable: 50 ids are all distinct", () => {
|
||||||
|
const ids = new Set(
|
||||||
|
Array.from({ length: 50 }, () => FeedId.generate().value),
|
||||||
|
);
|
||||||
|
expect(ids.size).toBe(50);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not produce the legacy noun.noun.NN format", () => {
|
||||||
|
expect(FeedId.generate().value).not.toMatch(/^[a-z]+\.[a-z]+\.\d{2}$/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("FeedId.unchecked", () => {
|
||||||
|
it("wraps a value without validation", () => {
|
||||||
|
expect(FeedId.unchecked("anything").value).toBe("anything");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
/** Encode bytes as unpadded base64url (URL- and KV-key-safe). */
|
||||||
|
function base64url(bytes: Uint8Array): string {
|
||||||
|
let binary = "";
|
||||||
|
for (const b of bytes) binary += String.fromCharCode(b);
|
||||||
|
return btoa(binary)
|
||||||
|
.replace(/\+/g, "-")
|
||||||
|
.replace(/\//g, "_")
|
||||||
|
.replace(/=+$/, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A feed's identity: the KV storage key AND the public read id in `/rss/:feedId`
|
||||||
|
* etc. It is an opaque, high-entropy random token — unguessable, so a feed's read
|
||||||
|
* URL can be shared without revealing its inbound address (the `MailboxId`, a
|
||||||
|
* separate value that resolves here via the `inbound:` index at reception).
|
||||||
|
*
|
||||||
|
* `generate` mints a fresh token; `unchecked` wraps a route param or stored key
|
||||||
|
* without revalidation (a wrong id simply misses in KV and 404s downstream).
|
||||||
|
*/
|
||||||
|
export class FeedId {
|
||||||
|
private constructor(readonly value: string) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wrap a string as a FeedId WITHOUT revalidating it. The caller asserts the id
|
||||||
|
* originated from our own minting — a route param echoing a stored id, a
|
||||||
|
* `feeds:list` entry, an `inbound:` index value, or a KV key. The name is
|
||||||
|
* deliberately blunt: a wrong id is not rejected here, it simply misses in KV
|
||||||
|
* and 404s downstream.
|
||||||
|
*/
|
||||||
|
static unchecked(value: string): FeedId {
|
||||||
|
return new FeedId(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mint a fresh, opaque identity (128 bits of entropy → 22 base64url chars). */
|
||||||
|
static generate(): FeedId {
|
||||||
|
const bytes = new Uint8Array(16);
|
||||||
|
crypto.getRandomValues(bytes);
|
||||||
|
return new FeedId(base64url(bytes));
|
||||||
|
}
|
||||||
|
|
||||||
|
toString(): string {
|
||||||
|
return this.value;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import { Lifetime } from "./lifetime";
|
||||||
|
|
||||||
|
const NOW = 1_000_000;
|
||||||
|
const HOUR = 3_600_000;
|
||||||
|
|
||||||
|
describe("Lifetime", () => {
|
||||||
|
it("resolves a positive lifetime to an absolute expiry", () => {
|
||||||
|
expect(Lifetime.ofHours(2).resolveExpiry(NOW)).toBe(NOW + 2 * HOUR);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("never expires for Lifetime.never", () => {
|
||||||
|
expect(Lifetime.never.resolveExpiry(NOW)).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("treats non-positive or non-finite hours as no expiry", () => {
|
||||||
|
expect(Lifetime.ofHours(0).resolveExpiry(NOW)).toBeUndefined();
|
||||||
|
expect(Lifetime.ofHours(-5).resolveExpiry(NOW)).toBeUndefined();
|
||||||
|
expect(Lifetime.ofHours(NaN).resolveExpiry(NOW)).toBeUndefined();
|
||||||
|
expect(Lifetime.ofHours(Infinity).resolveExpiry(NOW)).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
const HOUR_MS = 3_600_000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A feed's lifetime as a value object: either a positive number of hours or
|
||||||
|
* "never". `resolveExpiry(now)` turns it into an absolute `expires_at` instant
|
||||||
|
* (or undefined for a feed that never expires).
|
||||||
|
*
|
||||||
|
* Which lifetime applies — client request vs. server-side `FEED_TTL_HOURS`
|
||||||
|
* override — is the application layer's policy; it builds the VO and hands it to
|
||||||
|
* the aggregate. The aggregate never parses env config or reaches for a clock to
|
||||||
|
* compute expiry itself.
|
||||||
|
*/
|
||||||
|
export class Lifetime {
|
||||||
|
private constructor(private readonly hours: number | undefined) {}
|
||||||
|
|
||||||
|
/** A finite, positive lifetime. Non-positive/non-finite inputs collapse to never. */
|
||||||
|
static ofHours(hours: number): Lifetime {
|
||||||
|
return new Lifetime(hours);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A feed that never expires. */
|
||||||
|
static readonly never = new Lifetime(undefined);
|
||||||
|
|
||||||
|
/** The absolute expiry instant for this lifetime, or undefined if it never expires. */
|
||||||
|
resolveExpiry(now: number): number | undefined {
|
||||||
|
return this.hours !== undefined &&
|
||||||
|
Number.isFinite(this.hours) &&
|
||||||
|
this.hours > 0
|
||||||
|
? now + this.hours * HOUR_MS
|
||||||
|
: undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import { MailboxId } from "./mailbox-id";
|
||||||
|
|
||||||
|
describe("MailboxId.parse", () => {
|
||||||
|
it("extracts the mailbox id from an inbound address", () => {
|
||||||
|
expect(MailboxId.parse("river.castle.42@example.com")?.value).toBe(
|
||||||
|
"river.castle.42",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("preserves the original casing of the local part", () => {
|
||||||
|
expect(MailboxId.parse("River.Castle.42@example.com")?.value).toBe(
|
||||||
|
"River.Castle.42",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects malformed mailbox ids", () => {
|
||||||
|
expect(MailboxId.parse("user@example.com")).toBeNull();
|
||||||
|
expect(MailboxId.parse("notanemail")).toBeNull();
|
||||||
|
expect(MailboxId.parse("river.castle.4@example.com")).toBeNull();
|
||||||
|
expect(MailboxId.parse("river.castle.123@example.com")).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("MailboxId.generate", () => {
|
||||||
|
it("produces the noun.noun.NN format", () => {
|
||||||
|
for (let i = 0; i < 50; i++) {
|
||||||
|
expect(MailboxId.generate().value).toMatch(/^[a-z]+\.[a-z]+\.\d{2}$/);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("round-trips through parse from an address", () => {
|
||||||
|
const id = MailboxId.generate();
|
||||||
|
expect(MailboxId.parse(`${id.value}@example.com`)?.value).toBe(id.value);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("MailboxId.unchecked", () => {
|
||||||
|
it("wraps a value without validation", () => {
|
||||||
|
expect(MailboxId.unchecked("anything").value).toBe("anything");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("MailboxId.emailAddress", () => {
|
||||||
|
it("builds the full inbound address from the mailbox and a domain", () => {
|
||||||
|
expect(
|
||||||
|
MailboxId.unchecked("river.castle.42").emailAddress("news.app"),
|
||||||
|
).toBe("river.castle.42@news.app");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { nouns } from "../../data/nouns";
|
||||||
|
|
||||||
|
// Inbound mailbox ids are noun1.noun2.XY (two lowercase nouns + a 2-digit suffix).
|
||||||
|
const MAILBOX_IN_ADDRESS = /^([a-z]+\.[a-z]+\.\d{2})@/i;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A feed's inbound mailbox identifier — the friendly `noun.noun.NN` local part of
|
||||||
|
* the address newsletters are sent to (`<mailboxId>@domain`). It is deliberately
|
||||||
|
* NOT the feed's identity: a `MailboxId` resolves to a `FeedId` through the
|
||||||
|
* `inbound:` index at reception, so the public read URL (the opaque `FeedId`) and
|
||||||
|
* the inbound address stay decoupled.
|
||||||
|
*
|
||||||
|
* `parse` pulls it from an untrusted inbound address (the most untrusted input in
|
||||||
|
* the system); `generate` mints a fresh one. The original casing is preserved.
|
||||||
|
*/
|
||||||
|
export class MailboxId {
|
||||||
|
private constructor(readonly value: string) {}
|
||||||
|
|
||||||
|
/** Extract the mailbox id from an inbound address (`noun.noun.NN@domain`). */
|
||||||
|
static parse(emailAddress: string): MailboxId | null {
|
||||||
|
const match = emailAddress.match(MAILBOX_IN_ADDRESS);
|
||||||
|
return match ? new MailboxId(match[1]) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wrap a string as a MailboxId WITHOUT revalidating it. The caller asserts the
|
||||||
|
* value originated from our own minting (a stored `mailbox_id`). Untrusted
|
||||||
|
* external input (an inbound address) must go through `parse` instead.
|
||||||
|
*/
|
||||||
|
static unchecked(value: string): MailboxId {
|
||||||
|
return new MailboxId(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
static generate(): MailboxId {
|
||||||
|
const noun1 = nouns[Math.floor(Math.random() * nouns.length)];
|
||||||
|
const noun2 = nouns[Math.floor(Math.random() * nouns.length)];
|
||||||
|
const number = Math.floor(Math.random() * 90) + 10;
|
||||||
|
return new MailboxId(`${noun1}.${noun2}.${number}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The full inbound email address (`<mailboxId>@<domain>`) newsletters target. */
|
||||||
|
emailAddress(domain: string): string {
|
||||||
|
return `${this.value}@${domain}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
toString(): string {
|
||||||
|
return this.value;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import { EmailAddress } from "./email-address";
|
||||||
|
import { Domain } from "./domain";
|
||||||
|
|
||||||
|
export type SenderDecision = "accepted" | "blocked";
|
||||||
|
|
||||||
|
type SenderMatch = "blocked" | "allowed" | "neutral";
|
||||||
|
|
||||||
|
function normalizeEmail(value: string): string {
|
||||||
|
return value.trim().toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
function toDomains(entries: string[]): Domain[] {
|
||||||
|
return entries
|
||||||
|
.map((e) => Domain.parse(e))
|
||||||
|
.filter((d): d is Domain => d !== null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The sender allow/block policy as a value object, built ONCE from a feed's
|
||||||
|
* lists. The exact-vs-domain split is pre-computed here so `decide` is a cheap
|
||||||
|
* lookup per candidate sender instead of re-parsing both lists for every one
|
||||||
|
* (the previous `applySenderPolicy` was O(senders × lists)).
|
||||||
|
*
|
||||||
|
* Semantics (unchanged): no lists ⇒ everything accepted; a blocklist hit always
|
||||||
|
* rejects; an allowlist (when present) must be matched by at least one sender.
|
||||||
|
*/
|
||||||
|
export class SenderPolicy {
|
||||||
|
private constructor(
|
||||||
|
private readonly exactAllowed: string[],
|
||||||
|
private readonly exactBlocked: string[],
|
||||||
|
private readonly domainAllowed: Domain[],
|
||||||
|
private readonly domainBlocked: Domain[],
|
||||||
|
private readonly hasAllowlist: boolean,
|
||||||
|
private readonly hasAnyRule: boolean,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
static fromLists(
|
||||||
|
allowed: string[] = [],
|
||||||
|
blocked: string[] = [],
|
||||||
|
): SenderPolicy {
|
||||||
|
const allowedSenders = allowed.map(normalizeEmail).filter(Boolean);
|
||||||
|
const blockedSenders = blocked.map(normalizeEmail).filter(Boolean);
|
||||||
|
return new SenderPolicy(
|
||||||
|
allowedSenders.filter((e) => e.includes("@")),
|
||||||
|
blockedSenders.filter((e) => e.includes("@")),
|
||||||
|
toDomains(allowedSenders.filter((e) => !e.includes("@"))),
|
||||||
|
toDomains(blockedSenders.filter((e) => !e.includes("@"))),
|
||||||
|
allowedSenders.length > 0,
|
||||||
|
allowedSenders.length > 0 || blockedSenders.length > 0,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private evaluate(sender: string): SenderMatch {
|
||||||
|
const parsed = EmailAddress.parse(sender);
|
||||||
|
const normalized = parsed ? parsed.normalized : normalizeEmail(sender);
|
||||||
|
const senderDomain = parsed?.domain ?? null;
|
||||||
|
|
||||||
|
if (this.exactBlocked.includes(normalized)) return "blocked";
|
||||||
|
if (this.exactAllowed.includes(normalized)) return "allowed";
|
||||||
|
if (senderDomain && this.domainBlocked.some((d) => d.matches(senderDomain)))
|
||||||
|
return "blocked";
|
||||||
|
if (senderDomain && this.domainAllowed.some((d) => d.matches(senderDomain)))
|
||||||
|
return "allowed";
|
||||||
|
return "neutral";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Decide whether an inbound email is accepted, given its candidate sender
|
||||||
|
* addresses. A blocklist hit on any sender rejects; with an allowlist set, at
|
||||||
|
* least one sender must match it.
|
||||||
|
*/
|
||||||
|
decide(senders: string[]): SenderDecision {
|
||||||
|
if (!this.hasAnyRule) return "accepted";
|
||||||
|
|
||||||
|
const accepted = senders.some((sender) => {
|
||||||
|
const decision = this.evaluate(sender);
|
||||||
|
if (decision === "allowed") return true;
|
||||||
|
if (decision === "blocked") return false;
|
||||||
|
return !this.hasAllowlist;
|
||||||
|
});
|
||||||
|
|
||||||
|
return accepted ? "accepted" : "blocked";
|
||||||
|
}
|
||||||
|
}
|
||||||
+81
-4
@@ -1,10 +1,20 @@
|
|||||||
import { describe, it, expect } from "vitest";
|
import { describe, it, expect } from "vitest";
|
||||||
import worker from "./index";
|
import worker from "./index";
|
||||||
|
import { APP_VERSION } from "./config/version";
|
||||||
import { createMockEnv } from "./test/setup";
|
import { createMockEnv } from "./test/setup";
|
||||||
|
import { createFeedRecord } from "./application/feed-service";
|
||||||
|
import { FeedRepository } from "./infrastructure/feed-repository";
|
||||||
|
import { FeedId } from "./domain/value-objects/feed-id";
|
||||||
|
import { MailboxId } from "./domain/value-objects/mailbox-id";
|
||||||
import type { Env } from "./types";
|
import type { Env } from "./types";
|
||||||
|
|
||||||
const env = createMockEnv();
|
const env = createMockEnv();
|
||||||
|
|
||||||
|
const noopCtx = {
|
||||||
|
waitUntil: () => {},
|
||||||
|
passThroughOnException: () => {},
|
||||||
|
} as unknown as ExecutionContext;
|
||||||
|
|
||||||
function req(path: string, init: RequestInit = {}): Request {
|
function req(path: string, init: RequestInit = {}): Request {
|
||||||
return new Request(`https://test.getmynews.app${path}`, init);
|
return new Request(`https://test.getmynews.app${path}`, init);
|
||||||
}
|
}
|
||||||
@@ -12,11 +22,11 @@ function req(path: string, init: RequestInit = {}): Request {
|
|||||||
describe("CORS middleware", () => {
|
describe("CORS middleware", () => {
|
||||||
it("adds CORS headers for an allowed origin", async () => {
|
it("adds CORS headers for an allowed origin", async () => {
|
||||||
const res = await worker.fetch(
|
const res = await worker.fetch(
|
||||||
req("/rss/some-feed", { headers: { Origin: "https://getmynews.app" } }),
|
req("/rss/some-feed", { headers: { Origin: "https://kill-the.news" } }),
|
||||||
env as unknown as Env,
|
env as unknown as Env,
|
||||||
);
|
);
|
||||||
expect(res.headers.get("Access-Control-Allow-Origin")).toBe(
|
expect(res.headers.get("Access-Control-Allow-Origin")).toBe(
|
||||||
"https://getmynews.app",
|
"https://kill-the.news",
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -33,7 +43,7 @@ describe("CORS middleware", () => {
|
|||||||
req("/rss/some-feed", {
|
req("/rss/some-feed", {
|
||||||
method: "OPTIONS",
|
method: "OPTIONS",
|
||||||
headers: {
|
headers: {
|
||||||
Origin: "https://getmynews.app",
|
Origin: "https://kill-the.news",
|
||||||
"Access-Control-Request-Method": "GET",
|
"Access-Control-Request-Method": "GET",
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
@@ -41,7 +51,74 @@ describe("CORS middleware", () => {
|
|||||||
);
|
);
|
||||||
expect(res.status).toBe(204);
|
expect(res.status).toBe(204);
|
||||||
expect(res.headers.get("Access-Control-Allow-Origin")).toBe(
|
expect(res.headers.get("Access-Control-Allow-Origin")).toBe(
|
||||||
"https://getmynews.app",
|
"https://kill-the.news",
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("makes /api/v1/stats readable from any origin", async () => {
|
||||||
|
const res = await worker.fetch(
|
||||||
|
req("/api/v1/stats", { headers: { Origin: "https://example.com" } }),
|
||||||
|
env as unknown as Env,
|
||||||
|
);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(res.headers.get("Access-Control-Allow-Origin")).toBe("*");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("scheduled (cron) TTL cleanup", () => {
|
||||||
|
it("drops the inbound mailbox index when an expired feed is purged", async () => {
|
||||||
|
const cronEnv = createMockEnv() as unknown as Env;
|
||||||
|
const { feedId, mailboxId } = await createFeedRecord(cronEnv, {
|
||||||
|
title: "Expiring",
|
||||||
|
language: "en",
|
||||||
|
allowedSenders: [],
|
||||||
|
blockedSenders: [],
|
||||||
|
});
|
||||||
|
const repo = FeedRepository.from(cronEnv);
|
||||||
|
|
||||||
|
// The address resolves to the feed before the cron runs.
|
||||||
|
expect(
|
||||||
|
(await repo.resolveInbound(MailboxId.unchecked(mailboxId)))?.value,
|
||||||
|
).toBe(feedId);
|
||||||
|
|
||||||
|
// Backdate the feed so the cron treats it as expired.
|
||||||
|
const list = (await cronEnv.EMAIL_STORAGE.get("feeds:list", "json")) as {
|
||||||
|
feeds: Array<{ id: string; expires_at?: number; mailbox_id?: string }>;
|
||||||
|
};
|
||||||
|
list.feeds[0].expires_at = Date.now() - 1000;
|
||||||
|
await cronEnv.EMAIL_STORAGE.put("feeds:list", JSON.stringify(list));
|
||||||
|
|
||||||
|
await worker.scheduled({} as ScheduledEvent, cronEnv, noopCtx);
|
||||||
|
|
||||||
|
// The feed is gone AND its inbound address no longer resolves.
|
||||||
|
expect(await repo.getConfig(FeedId.unchecked(feedId))).toBeNull();
|
||||||
|
expect(
|
||||||
|
await repo.resolveInbound(MailboxId.unchecked(mailboxId)),
|
||||||
|
).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("GET /health", () => {
|
||||||
|
it("reports status ok and the bundled app version", async () => {
|
||||||
|
const res = await worker.fetch(req("/health"), env as unknown as Env);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const body = (await res.json()) as { status: string; version: string };
|
||||||
|
expect(body.status).toBe("ok");
|
||||||
|
expect(body.version).toBe(APP_VERSION);
|
||||||
|
expect(body.version).toMatch(/^\d+\.\d+\.\d+/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("GET /robots.txt", () => {
|
||||||
|
it("returns 200 and disallows the private feed/entry paths", async () => {
|
||||||
|
const res = await worker.fetch(req("/robots.txt"), env as unknown as Env);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const body = await res.text();
|
||||||
|
expect(body).toContain("User-agent: *");
|
||||||
|
expect(body).toContain("Disallow: /rss/");
|
||||||
|
expect(body).toContain("Disallow: /atom/");
|
||||||
|
expect(body).toContain("Disallow: /entries/");
|
||||||
|
expect(body).toContain("Disallow: /files/");
|
||||||
|
expect(body).toContain("Disallow: /admin/");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+85
-17
@@ -3,18 +3,33 @@ import { cors } from "hono/cors";
|
|||||||
import { handle as handleInbound } from "./routes/inbound";
|
import { handle as handleInbound } from "./routes/inbound";
|
||||||
import { handle as handleRSS } from "./routes/rss";
|
import { handle as handleRSS } from "./routes/rss";
|
||||||
import { handle as handleAtom } from "./routes/atom";
|
import { handle as handleAtom } from "./routes/atom";
|
||||||
|
import { handle as handleJSON } from "./routes/json";
|
||||||
import { handle as handleAdmin } from "./routes/admin";
|
import { handle as handleAdmin } from "./routes/admin";
|
||||||
import { handle as handleEntry } from "./routes/entries";
|
import { handle as handleEntry } from "./routes/entries";
|
||||||
import { handle as handleFiles } from "./routes/files";
|
import { handle as handleFiles } from "./routes/files";
|
||||||
|
import { handle as handleHome } from "./routes/home";
|
||||||
|
import { handle as handleFavicon, handleFeedFavicon } from "./routes/favicon";
|
||||||
import { hubRouter } from "./routes/hub";
|
import { hubRouter } from "./routes/hub";
|
||||||
import { handleCloudflareEmail } from "./lib/cloudflare-email";
|
import { apiApp } from "./routes/api";
|
||||||
|
import { handleCloudflareEmail } from "./infrastructure/cloudflare-email";
|
||||||
import { Env } from "./types";
|
import { Env } from "./types";
|
||||||
import { logger } from "./lib/logger";
|
import { APP_VERSION } from "./config/version";
|
||||||
|
import { logger } from "./infrastructure/logger";
|
||||||
|
import { FeedRepository } from "./infrastructure/feed-repository";
|
||||||
|
import { purgeExpiredFeeds } from "./application/feed-cleanup";
|
||||||
|
import { FeedId } from "./domain/value-objects/feed-id";
|
||||||
|
import {
|
||||||
|
bumpCounters,
|
||||||
|
scanR2Usage,
|
||||||
|
scanKvUsage,
|
||||||
|
setStorageSnapshot,
|
||||||
|
} from "./application/stats";
|
||||||
|
import { getAttachmentBucket } from "./infrastructure/attachments";
|
||||||
import { FORWARD_EMAIL_IPS_CACHE_TTL_MS } from "./config/constants";
|
import { FORWARD_EMAIL_IPS_CACHE_TTL_MS } from "./config/constants";
|
||||||
|
|
||||||
type AppEnv = { Bindings: Env };
|
type AppEnv = { Bindings: Env };
|
||||||
|
|
||||||
const ALLOWED_ORIGINS = ["https://getmynews.app", "https://www.getmynews.app"];
|
const ALLOWED_ORIGINS = ["https://kill-the.news", "https://www.kill-the.news"];
|
||||||
|
|
||||||
// Fallback ForwardEmail.net IP addresses in case API fetch fails
|
// Fallback ForwardEmail.net IP addresses in case API fetch fails
|
||||||
const FALLBACK_FORWARD_EMAIL_IPS = [
|
const FALLBACK_FORWARD_EMAIL_IPS = [
|
||||||
@@ -103,6 +118,7 @@ app.use(
|
|||||||
const api = new Hono<AppEnv>();
|
const api = new Hono<AppEnv>();
|
||||||
const rss = new Hono<AppEnv>();
|
const rss = new Hono<AppEnv>();
|
||||||
const atom = new Hono<AppEnv>();
|
const atom = new Hono<AppEnv>();
|
||||||
|
const json = new Hono<AppEnv>();
|
||||||
const entries = new Hono<AppEnv>();
|
const entries = new Hono<AppEnv>();
|
||||||
const files = new Hono<AppEnv>();
|
const files = new Hono<AppEnv>();
|
||||||
const admin = new Hono<AppEnv>();
|
const admin = new Hono<AppEnv>();
|
||||||
@@ -138,6 +154,9 @@ rss.get("/:feedId", handleRSS);
|
|||||||
// Atom feed routes (public)
|
// Atom feed routes (public)
|
||||||
atom.get("/:feedId", handleAtom);
|
atom.get("/:feedId", handleAtom);
|
||||||
|
|
||||||
|
// JSON Feed routes (public)
|
||||||
|
json.get("/:feedId", handleJSON);
|
||||||
|
|
||||||
// Email entry HTML view (public)
|
// Email entry HTML view (public)
|
||||||
entries.get("/:feedId/:entryId", handleEntry);
|
entries.get("/:feedId/:entryId", handleEntry);
|
||||||
|
|
||||||
@@ -149,18 +168,38 @@ admin.route("/", handleAdmin);
|
|||||||
|
|
||||||
// Mount the route groups
|
// Mount the route groups
|
||||||
app.route("/api", api);
|
app.route("/api", api);
|
||||||
|
// Versioned REST API + OpenAPI spec/docs (/api/v1/*, /api/openapi.json, /api/docs)
|
||||||
|
app.route("/api", apiApp);
|
||||||
app.route("/rss", rss);
|
app.route("/rss", rss);
|
||||||
app.route("/atom", atom);
|
app.route("/atom", atom);
|
||||||
|
app.route("/json", json);
|
||||||
app.route("/entries", entries);
|
app.route("/entries", entries);
|
||||||
app.route("/files", files);
|
app.route("/files", files);
|
||||||
app.route("/admin", admin);
|
app.route("/admin", admin);
|
||||||
app.route("/hub", hubRouter);
|
app.route("/hub", hubRouter);
|
||||||
|
|
||||||
// Health check endpoint for monitoring
|
// Project favicon (also the fallback for the per-feed favicon)
|
||||||
app.get("/health", (c) => c.json({ status: "ok", timestamp: Date.now() }));
|
app.get("/favicon.svg", handleFavicon);
|
||||||
|
app.get("/favicon.ico", handleFavicon); // readers/browsers that hardcode .ico
|
||||||
|
|
||||||
// Root path redirects to admin dashboard
|
// Per-feed favicon derived from the last sender's domain
|
||||||
app.get("/", (c) => c.redirect("/admin"));
|
app.get("/favicon/:feedId", handleFeedFavicon);
|
||||||
|
|
||||||
|
// Health check endpoint for monitoring
|
||||||
|
app.get("/health", (c) =>
|
||||||
|
c.json({ status: "ok", version: APP_VERSION, timestamp: Date.now() }),
|
||||||
|
);
|
||||||
|
|
||||||
|
// Public status page (counters + link to admin)
|
||||||
|
app.get("/", handleHome);
|
||||||
|
|
||||||
|
// Keep private feeds/emails out of search engines (defense in depth alongside
|
||||||
|
// the X-Robots-Tag headers on the feed/entry/file responses).
|
||||||
|
app.get("/robots.txt", (c) =>
|
||||||
|
c.text(
|
||||||
|
"User-agent: *\nDisallow: /rss/\nDisallow: /atom/\nDisallow: /entries/\nDisallow: /files/\nDisallow: /admin/\n",
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
// Catch-all for 404s
|
// Catch-all for 404s
|
||||||
app.all("*", (c) => c.text("Not Found", 404));
|
app.all("*", (c) => c.text("Not Found", 404));
|
||||||
@@ -176,16 +215,45 @@ export default {
|
|||||||
await handleCloudflareEmail(message, env, ctx);
|
await handleCloudflareEmail(message, env, ctx);
|
||||||
},
|
},
|
||||||
async scheduled(_event: ScheduledEvent, env: Env, _ctx: ExecutionContext) {
|
async scheduled(_event: ScheduledEvent, env: Env, _ctx: ExecutionContext) {
|
||||||
let cursor: string | undefined;
|
const attachmentBucket = getAttachmentBucket(env);
|
||||||
let deleted = 0;
|
const repo = FeedRepository.from(env);
|
||||||
do {
|
const feeds = await repo.listFeeds();
|
||||||
const result = await env.EMAIL_STORAGE.list({ cursor });
|
const now = Date.now();
|
||||||
await Promise.all(
|
const expiredIds = feeds
|
||||||
result.keys.map(({ name }) => env.EMAIL_STORAGE.delete(name)),
|
.filter((f) => f.expires_at !== undefined && f.expires_at <= now)
|
||||||
|
.map((f) => f.id);
|
||||||
|
|
||||||
|
for (const feedId of expiredIds) {
|
||||||
|
await purgeExpiredFeeds(
|
||||||
|
env.EMAIL_STORAGE,
|
||||||
|
FeedId.unchecked(feedId),
|
||||||
|
attachmentBucket,
|
||||||
);
|
);
|
||||||
deleted += result.keys.length;
|
}
|
||||||
cursor = result.list_complete ? undefined : result.cursor;
|
if (expiredIds.length > 0) {
|
||||||
} while (cursor);
|
// removeFromListBulk also drops each feed's inbound mailbox index.
|
||||||
logger.info("Demo KV reset complete", { deleted });
|
await repo.removeFromListBulk(expiredIds);
|
||||||
|
await bumpCounters(env.EMAIL_STORAGE, {
|
||||||
|
feeds_deleted: expiredIds.length,
|
||||||
|
});
|
||||||
|
logger.info("Feed TTL cleanup", { deleted: expiredIds.length });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Refresh the cached storage-usage snapshot for the status page / /api/v1/stats.
|
||||||
|
try {
|
||||||
|
const r2 = attachmentBucket
|
||||||
|
? await scanR2Usage(attachmentBucket)
|
||||||
|
: { bytes: 0, count: 0 };
|
||||||
|
const kv = await scanKvUsage(env.EMAIL_STORAGE);
|
||||||
|
await setStorageSnapshot(env.EMAIL_STORAGE, {
|
||||||
|
attachments_bytes: r2.bytes,
|
||||||
|
attachments_count: r2.count,
|
||||||
|
kv_bytes_estimated: kv.bytes,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
logger.error("Error refreshing storage snapshot", {
|
||||||
|
error: String(error),
|
||||||
|
});
|
||||||
|
}
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { Env } from "../types";
|
||||||
|
|
||||||
|
// Returns the attachment bucket only when the feature is enabled, so callers can
|
||||||
|
// narrow cleanly. Attachments are on whenever R2 is bound, unless explicitly
|
||||||
|
// turned off with ATTACHMENTS_ENABLED="false".
|
||||||
|
export function getAttachmentBucket(env: Env): R2Bucket | undefined {
|
||||||
|
if (env.ATTACHMENTS_ENABLED === "false") return undefined;
|
||||||
|
return env.ATTACHMENT_BUCKET;
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
import { Context } from "hono";
|
||||||
|
import { Env } from "../types";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Constant-time string comparison. Prefers the runtime's native
|
||||||
|
* `crypto.subtle.timingSafeEqual` (Cloudflare Workers) and falls back to a
|
||||||
|
* manual constant-time loop in environments that lack it (Node test runtime).
|
||||||
|
*/
|
||||||
|
export function timingSafeEqual(a: string, b: string): boolean {
|
||||||
|
const enc = new TextEncoder();
|
||||||
|
const aBytes = enc.encode(a);
|
||||||
|
const bBytes = enc.encode(b);
|
||||||
|
// Try native timing-safe implementation first (Cloudflare Workers runtime)
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
const subtle = crypto.subtle as any;
|
||||||
|
if (typeof subtle.timingSafeEqual === "function") {
|
||||||
|
if (aBytes.length !== bBytes.length) return false;
|
||||||
|
return subtle.timingSafeEqual(aBytes, bBytes);
|
||||||
|
}
|
||||||
|
// Constant-time fallback for Node (test environment): encode length
|
||||||
|
// mismatch into `diff` so the loop always runs over the full length.
|
||||||
|
const len = Math.max(aBytes.length, bBytes.length);
|
||||||
|
let diff = aBytes.length ^ bBytes.length;
|
||||||
|
for (let i = 0; i < len; i++) {
|
||||||
|
diff |= (aBytes[i] ?? 0) ^ (bBytes[i] ?? 0);
|
||||||
|
}
|
||||||
|
return diff === 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reverse-proxy authentication: trusted only when both `PROXY_AUTH_SECRET` and
|
||||||
|
* `PROXY_TRUSTED_IPS` are configured, the request comes from a trusted IP, the
|
||||||
|
* shared secret matches, and a `Remote-User`/`X-Forwarded-User` is present.
|
||||||
|
*/
|
||||||
|
export function checkProxyAuth(c: Context, env: Env): boolean {
|
||||||
|
if (!env.PROXY_AUTH_SECRET || !env.PROXY_TRUSTED_IPS) return false;
|
||||||
|
|
||||||
|
const trustedIps = env.PROXY_TRUSTED_IPS.split(",")
|
||||||
|
.map((s: string) => s.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
const clientIp = c.req.header("CF-Connecting-IP") ?? "";
|
||||||
|
const providedSecret = c.req.header("X-Auth-Proxy-Secret") ?? "";
|
||||||
|
const remoteUser =
|
||||||
|
c.req.header("Remote-User") || c.req.header("X-Forwarded-User") || "";
|
||||||
|
|
||||||
|
return (
|
||||||
|
trustedIps.includes(clientIp) &&
|
||||||
|
timingSafeEqual(providedSecret, env.PROXY_AUTH_SECRET) &&
|
||||||
|
remoteUser.length > 0
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Authentication for the machine-facing REST API (`/api/v1/*`).
|
||||||
|
* Grants access when proxy auth passes OR the request carries a valid
|
||||||
|
* `Authorization: Bearer <ADMIN_PASSWORD>`. No cookie, no CSRF — token only.
|
||||||
|
*/
|
||||||
|
export async function apiAuthMiddleware(
|
||||||
|
c: Context<{ Bindings: Env }>,
|
||||||
|
next: () => Promise<void>,
|
||||||
|
): Promise<Response | void> {
|
||||||
|
const env = c.env;
|
||||||
|
|
||||||
|
if (checkProxyAuth(c, env)) {
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
|
||||||
|
const authHeader = c.req.header("Authorization") ?? "";
|
||||||
|
const token = authHeader.startsWith("Bearer ")
|
||||||
|
? authHeader.slice("Bearer ".length)
|
||||||
|
: "";
|
||||||
|
|
||||||
|
if (token && timingSafeEqual(token, env.ADMIN_PASSWORD)) {
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.json({ error: "Unauthorized" }, 401);
|
||||||
|
}
|
||||||
@@ -0,0 +1,299 @@
|
|||||||
|
import { describe, it, expect, beforeEach } from "vitest";
|
||||||
|
import "../test/setup";
|
||||||
|
import { createMockEnv, seedInboundIndex } from "../test/setup";
|
||||||
|
import { handleCloudflareEmail } from "./cloudflare-email";
|
||||||
|
import { getCounters } from "../application/stats";
|
||||||
|
|
||||||
|
const VALID_FEED_ID = "apple.mountain.42";
|
||||||
|
const DOMAIN = "test.getmynews.app";
|
||||||
|
|
||||||
|
const RAW_EMAIL = [
|
||||||
|
"From: Sender Name <sender@example.com>",
|
||||||
|
`To: ${VALID_FEED_ID}@${DOMAIN}`,
|
||||||
|
"Subject: Hello World",
|
||||||
|
"Date: Thu, 01 Jan 2026 12:00:00 +0000",
|
||||||
|
"MIME-Version: 1.0",
|
||||||
|
"Content-Type: text/plain; charset=utf-8",
|
||||||
|
"",
|
||||||
|
"This is the email body.",
|
||||||
|
].join("\r\n");
|
||||||
|
|
||||||
|
function makeMessage(
|
||||||
|
overrides: Partial<{
|
||||||
|
from: string;
|
||||||
|
to: string;
|
||||||
|
rawText: string;
|
||||||
|
forward: (rcptTo: string, headers?: Headers) => Promise<void>;
|
||||||
|
}> = {},
|
||||||
|
): ForwardableEmailMessage {
|
||||||
|
const rawText = overrides.rawText ?? RAW_EMAIL;
|
||||||
|
const encoder = new TextEncoder();
|
||||||
|
const bytes = encoder.encode(rawText);
|
||||||
|
const stream = new ReadableStream<Uint8Array>({
|
||||||
|
start(controller) {
|
||||||
|
controller.enqueue(bytes);
|
||||||
|
controller.close();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
from: overrides.from ?? "sender@example.com",
|
||||||
|
to: overrides.to ?? `${VALID_FEED_ID}@${DOMAIN}`,
|
||||||
|
headers: new Headers(),
|
||||||
|
raw: stream,
|
||||||
|
rawSize: bytes.length,
|
||||||
|
forward: overrides.forward ?? (async () => {}),
|
||||||
|
reply: async () => {},
|
||||||
|
setReject: () => {},
|
||||||
|
} as unknown as ForwardableEmailMessage;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Records every message.forward() call so tests can assert on routing. */
|
||||||
|
function spyForward() {
|
||||||
|
const calls: string[] = [];
|
||||||
|
const forward = async (rcptTo: string) => {
|
||||||
|
calls.push(rcptTo);
|
||||||
|
};
|
||||||
|
return { calls, forward };
|
||||||
|
}
|
||||||
|
|
||||||
|
const FALLBACK = "fallback@personal.example";
|
||||||
|
|
||||||
|
describe("handleCloudflareEmail", () => {
|
||||||
|
let env: ReturnType<typeof createMockEnv>;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
env = createMockEnv();
|
||||||
|
await seedInboundIndex(env, VALID_FEED_ID);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("stores email in KV when feed exists", async () => {
|
||||||
|
await env.EMAIL_STORAGE.put(
|
||||||
|
`feed:${VALID_FEED_ID}:config`,
|
||||||
|
JSON.stringify({}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await handleCloudflareEmail(
|
||||||
|
makeMessage(),
|
||||||
|
env as any,
|
||||||
|
{ waitUntil: () => {} } as any,
|
||||||
|
);
|
||||||
|
|
||||||
|
const metadata = await env.EMAIL_STORAGE.get(
|
||||||
|
`feed:${VALID_FEED_ID}:metadata`,
|
||||||
|
"json",
|
||||||
|
);
|
||||||
|
expect(metadata.emails).toHaveLength(1);
|
||||||
|
expect(metadata.emails[0].subject).toBe("Hello World");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not throw when feed does not exist", async () => {
|
||||||
|
await expect(
|
||||||
|
handleCloudflareEmail(
|
||||||
|
makeMessage(),
|
||||||
|
env as any,
|
||||||
|
{ waitUntil: () => {} } as any,
|
||||||
|
),
|
||||||
|
).resolves.toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not throw when email is malformed", async () => {
|
||||||
|
const msg = makeMessage({ rawText: "not a valid email" });
|
||||||
|
await expect(
|
||||||
|
handleCloudflareEmail(msg, env as any, { waitUntil: () => {} } as any),
|
||||||
|
).resolves.toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("uses sender from message.from for allowlist check", async () => {
|
||||||
|
await env.EMAIL_STORAGE.put(
|
||||||
|
`feed:${VALID_FEED_ID}:config`,
|
||||||
|
JSON.stringify({ allowed_senders: ["sender@example.com"] }),
|
||||||
|
);
|
||||||
|
|
||||||
|
await handleCloudflareEmail(
|
||||||
|
makeMessage(),
|
||||||
|
env as any,
|
||||||
|
{ waitUntil: () => {} } as any,
|
||||||
|
);
|
||||||
|
|
||||||
|
const metadata = await env.EMAIL_STORAGE.get(
|
||||||
|
`feed:${VALID_FEED_ID}:metadata`,
|
||||||
|
"json",
|
||||||
|
);
|
||||||
|
expect(metadata.emails).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects email when sender is not in allowlist (stored nothing)", async () => {
|
||||||
|
await env.EMAIL_STORAGE.put(
|
||||||
|
`feed:${VALID_FEED_ID}:config`,
|
||||||
|
JSON.stringify({ allowed_senders: ["other@example.com"] }),
|
||||||
|
);
|
||||||
|
|
||||||
|
await handleCloudflareEmail(
|
||||||
|
makeMessage(),
|
||||||
|
env as any,
|
||||||
|
{ waitUntil: () => {} } as any,
|
||||||
|
);
|
||||||
|
|
||||||
|
const metadata = await env.EMAIL_STORAGE.get(
|
||||||
|
`feed:${VALID_FEED_ID}:metadata`,
|
||||||
|
"json",
|
||||||
|
);
|
||||||
|
expect(metadata).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("FALLBACK_FORWARD_ADDRESS catch-all fallback", () => {
|
||||||
|
it("forwards to the fallback when the feed does not exist", async () => {
|
||||||
|
const { calls, forward } = spyForward();
|
||||||
|
env.FALLBACK_FORWARD_ADDRESS = FALLBACK;
|
||||||
|
|
||||||
|
await handleCloudflareEmail(
|
||||||
|
makeMessage({ forward }),
|
||||||
|
env as any,
|
||||||
|
{ waitUntil: () => {} } as any,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(calls).toEqual([FALLBACK]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("forwards to the fallback when the address is not a feed", async () => {
|
||||||
|
const { calls, forward } = spyForward();
|
||||||
|
env.FALLBACK_FORWARD_ADDRESS = FALLBACK;
|
||||||
|
|
||||||
|
await handleCloudflareEmail(
|
||||||
|
makeMessage({ to: `not-a-feed@${DOMAIN}`, forward }),
|
||||||
|
env as any,
|
||||||
|
{ waitUntil: () => {} } as any,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(calls).toEqual([FALLBACK]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does NOT forward an expired feed's mail (no newsletter leak)", async () => {
|
||||||
|
const { calls, forward } = spyForward();
|
||||||
|
env.FALLBACK_FORWARD_ADDRESS = FALLBACK;
|
||||||
|
await env.EMAIL_STORAGE.put(
|
||||||
|
`feed:${VALID_FEED_ID}:config`,
|
||||||
|
JSON.stringify({ expires_at: Date.now() - 1000 }),
|
||||||
|
);
|
||||||
|
|
||||||
|
await handleCloudflareEmail(
|
||||||
|
makeMessage({ forward }),
|
||||||
|
env as any,
|
||||||
|
{ waitUntil: () => {} } as any,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(calls).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does NOT forward when the sender is blocked", async () => {
|
||||||
|
const { calls, forward } = spyForward();
|
||||||
|
env.FALLBACK_FORWARD_ADDRESS = FALLBACK;
|
||||||
|
await env.EMAIL_STORAGE.put(
|
||||||
|
`feed:${VALID_FEED_ID}:config`,
|
||||||
|
JSON.stringify({ allowed_senders: ["other@example.com"] }),
|
||||||
|
);
|
||||||
|
|
||||||
|
await handleCloudflareEmail(
|
||||||
|
makeMessage({ forward }),
|
||||||
|
env as any,
|
||||||
|
{ waitUntil: () => {} } as any,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(calls).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does NOT forward when the email was ingested", async () => {
|
||||||
|
const { calls, forward } = spyForward();
|
||||||
|
env.FALLBACK_FORWARD_ADDRESS = FALLBACK;
|
||||||
|
await env.EMAIL_STORAGE.put(
|
||||||
|
`feed:${VALID_FEED_ID}:config`,
|
||||||
|
JSON.stringify({}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await handleCloudflareEmail(
|
||||||
|
makeMessage({ forward }),
|
||||||
|
env as any,
|
||||||
|
{ waitUntil: () => {} } as any,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(calls).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does NOT forward when the env var is unset (current drop behavior)", async () => {
|
||||||
|
const { calls, forward } = spyForward();
|
||||||
|
// env.FALLBACK_FORWARD_ADDRESS intentionally left unset.
|
||||||
|
|
||||||
|
await handleCloudflareEmail(
|
||||||
|
makeMessage({ forward }),
|
||||||
|
env as any,
|
||||||
|
{ waitUntil: () => {} } as any,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(calls).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not throw when the fallback forward fails (unverified address)", async () => {
|
||||||
|
env.FALLBACK_FORWARD_ADDRESS = FALLBACK;
|
||||||
|
const forward = async () => {
|
||||||
|
throw new Error("destination address not verified");
|
||||||
|
};
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
handleCloudflareEmail(
|
||||||
|
makeMessage({ forward }),
|
||||||
|
env as any,
|
||||||
|
{ waitUntil: () => {} } as any,
|
||||||
|
),
|
||||||
|
).resolves.toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("increments the emails_forwarded counter on a successful forward", async () => {
|
||||||
|
const { forward } = spyForward();
|
||||||
|
env.FALLBACK_FORWARD_ADDRESS = FALLBACK;
|
||||||
|
|
||||||
|
await handleCloudflareEmail(
|
||||||
|
makeMessage({ forward }),
|
||||||
|
env as any,
|
||||||
|
{ waitUntil: () => {} } as any,
|
||||||
|
);
|
||||||
|
|
||||||
|
const counters = await getCounters(env.EMAIL_STORAGE as any);
|
||||||
|
expect(counters.emails_forwarded).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not increment emails_forwarded when the forward fails", async () => {
|
||||||
|
env.FALLBACK_FORWARD_ADDRESS = FALLBACK;
|
||||||
|
const forward = async () => {
|
||||||
|
throw new Error("destination address not verified");
|
||||||
|
};
|
||||||
|
|
||||||
|
await handleCloudflareEmail(
|
||||||
|
makeMessage({ forward }),
|
||||||
|
env as any,
|
||||||
|
{ waitUntil: () => {} } as any,
|
||||||
|
);
|
||||||
|
|
||||||
|
const counters = await getCounters(env.EMAIL_STORAGE as any);
|
||||||
|
expect(counters.emails_forwarded).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not increment emails_forwarded for dropped reasons", async () => {
|
||||||
|
const { forward } = spyForward();
|
||||||
|
env.FALLBACK_FORWARD_ADDRESS = FALLBACK;
|
||||||
|
await env.EMAIL_STORAGE.put(
|
||||||
|
`feed:${VALID_FEED_ID}:config`,
|
||||||
|
JSON.stringify({ expires_at: Date.now() - 1000 }),
|
||||||
|
);
|
||||||
|
|
||||||
|
await handleCloudflareEmail(
|
||||||
|
makeMessage({ forward }),
|
||||||
|
env as any,
|
||||||
|
{ waitUntil: () => {} } as any,
|
||||||
|
);
|
||||||
|
|
||||||
|
const counters = await getCounters(env.EMAIL_STORAGE as any);
|
||||||
|
expect(counters.emails_forwarded).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
import PostalMime from "postal-mime";
|
||||||
|
import { Env } from "../types";
|
||||||
|
import {
|
||||||
|
processEmail,
|
||||||
|
RawAttachment,
|
||||||
|
IngestRejectionReason,
|
||||||
|
} from "../application/email-processor";
|
||||||
|
import { bumpCounters } from "../application/stats";
|
||||||
|
import { normalizeCid } from "../infrastructure/html-processor";
|
||||||
|
import { logger } from "./logger";
|
||||||
|
|
||||||
|
export async function handleCloudflareEmail(
|
||||||
|
message: ForwardableEmailMessage,
|
||||||
|
env: Env,
|
||||||
|
ctx: ExecutionContext,
|
||||||
|
): Promise<void> {
|
||||||
|
try {
|
||||||
|
const email = await PostalMime.parse(message.raw);
|
||||||
|
|
||||||
|
const fromAddress = email.from?.address ?? message.from;
|
||||||
|
const from =
|
||||||
|
email.from?.name && email.from.address
|
||||||
|
? `${email.from.name} <${email.from.address}>`
|
||||||
|
: fromAddress;
|
||||||
|
|
||||||
|
const headers: Record<string, string> = {};
|
||||||
|
for (const h of email.headers) {
|
||||||
|
headers[h.key] = h.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
const rawAttachments: RawAttachment[] = (email.attachments ?? [])
|
||||||
|
.filter((a) => a.content instanceof ArrayBuffer)
|
||||||
|
.map((a) => ({
|
||||||
|
filename: a.filename || "attachment",
|
||||||
|
contentType: a.mimeType || "application/octet-stream",
|
||||||
|
content: a.content as ArrayBuffer,
|
||||||
|
contentId: normalizeCid(a.contentId),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const result = await processEmail(
|
||||||
|
{
|
||||||
|
toAddress: message.to,
|
||||||
|
from,
|
||||||
|
senders: [message.from],
|
||||||
|
subject: email.subject ?? "(no subject)",
|
||||||
|
content: email.html ?? email.text ?? "",
|
||||||
|
receivedAt: email.date ? new Date(email.date).getTime() : Date.now(),
|
||||||
|
headers,
|
||||||
|
attachments: rawAttachments,
|
||||||
|
},
|
||||||
|
env,
|
||||||
|
ctx,
|
||||||
|
);
|
||||||
|
if (!result.ok) {
|
||||||
|
logger.warn("Inbound email rejected", {
|
||||||
|
to: message.to,
|
||||||
|
reason: result.reason,
|
||||||
|
});
|
||||||
|
await maybeForwardFallback(message, env, result.reason);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error processing Cloudflare email:", error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reasons safe to forward to the catch-all fallback: the mail was never a feed's
|
||||||
|
// (wrong address shape, or no such feed). Expired feeds and blocked senders are
|
||||||
|
// dropped so a real newsletter never leaks into the fallback inbox.
|
||||||
|
const FORWARDABLE_REASONS = new Set<IngestRejectionReason>([
|
||||||
|
"invalid_address",
|
||||||
|
"mailbox_unknown",
|
||||||
|
"feed_not_found",
|
||||||
|
]);
|
||||||
|
|
||||||
|
async function maybeForwardFallback(
|
||||||
|
message: ForwardableEmailMessage,
|
||||||
|
env: Env,
|
||||||
|
reason: IngestRejectionReason,
|
||||||
|
): Promise<void> {
|
||||||
|
const fallback = env.FALLBACK_FORWARD_ADDRESS;
|
||||||
|
if (!fallback || !FORWARDABLE_REASONS.has(reason)) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await message.forward(fallback);
|
||||||
|
// Counted as a subset of emails_rejected (already bumped in processEmail);
|
||||||
|
// the dropped count is derived as emails_rejected − emails_forwarded.
|
||||||
|
await bumpCounters(env.EMAIL_STORAGE, { emails_forwarded: 1 });
|
||||||
|
} catch (error) {
|
||||||
|
logger.warn("Fallback forward failed", {
|
||||||
|
to: message.to,
|
||||||
|
fallback,
|
||||||
|
error: error instanceof Error ? error.message : String(error),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import { createMockEnv } from "../test/setup";
|
||||||
|
import { CountersRepository } from "./counters-repository";
|
||||||
|
import type { Env } from "../types";
|
||||||
|
|
||||||
|
const mockEnv = () => createMockEnv() as unknown as Env;
|
||||||
|
|
||||||
|
describe("CountersRepository", () => {
|
||||||
|
it("round-trips the counters singleton", async () => {
|
||||||
|
const repo = new CountersRepository(mockEnv().EMAIL_STORAGE);
|
||||||
|
expect(await repo.getRaw()).toBeNull();
|
||||||
|
await repo.put({
|
||||||
|
feeds_created: 1,
|
||||||
|
feeds_deleted: 0,
|
||||||
|
emails_received: 2,
|
||||||
|
emails_rejected: 0,
|
||||||
|
emails_forwarded: 0,
|
||||||
|
emails_deduplicated: 0,
|
||||||
|
unsubscribes_sent: 0,
|
||||||
|
});
|
||||||
|
expect(await repo.getRaw()).toMatchObject({ emails_received: 2 });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import { Counters, Env } from "../types";
|
||||||
|
import { STATS_KEY } from "../domain/feed-keys";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* KV access for the monitoring counters singleton (`stats:counters`). The
|
||||||
|
* increment policy lives in the application layer (utils/stats.ts); this
|
||||||
|
* repository owns only the raw read/write of the blob.
|
||||||
|
*/
|
||||||
|
export class CountersRepository {
|
||||||
|
constructor(private readonly kv: KVNamespace) {}
|
||||||
|
|
||||||
|
static from(env: Env): CountersRepository {
|
||||||
|
return new CountersRepository(env.EMAIL_STORAGE);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getRaw(): Promise<Counters | null> {
|
||||||
|
return (await this.kv.get(STATS_KEY, { type: "json" })) as Counters | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async put(counters: Counters): Promise<void> {
|
||||||
|
await this.kv.put(STATS_KEY, JSON.stringify(counters));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import { http, HttpResponse } from "msw";
|
||||||
|
import { server, createMockEnv } from "../test/setup";
|
||||||
|
import {
|
||||||
|
cacheFaviconForDomain,
|
||||||
|
extractEmailDomain,
|
||||||
|
getCachedIcon,
|
||||||
|
} from "./favicon-fetcher";
|
||||||
|
import { MAX_ICON_BYTES } from "../config/constants";
|
||||||
|
|
||||||
|
const iconKey = (domain: string) => `icon:${domain}`;
|
||||||
|
import type { Env } from "../types";
|
||||||
|
|
||||||
|
const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 1, 2, 3, 4]);
|
||||||
|
|
||||||
|
function imageResponse(bytes: Uint8Array, contentType = "image/png") {
|
||||||
|
return new HttpResponse(bytes, { headers: { "Content-Type": contentType } });
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("extractEmailDomain", () => {
|
||||||
|
it("parses a bare address", () => {
|
||||||
|
expect(extractEmailDomain("news@github.com")).toBe("github.com");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("parses a display-form address", () => {
|
||||||
|
expect(extractEmailDomain("GitHub <news@GitHub.com>")).toBe("github.com");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("strips a trailing dot and lowercases", () => {
|
||||||
|
expect(extractEmailDomain("a@Example.COM.")).toBe("example.com");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns null when there is no address", () => {
|
||||||
|
expect(extractEmailDomain("not an email")).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("cacheFaviconForDomain", () => {
|
||||||
|
it("caches the direct /favicon.ico when available", async () => {
|
||||||
|
const env = createMockEnv() as unknown as Env;
|
||||||
|
server.use(
|
||||||
|
http.get("https://github.com/favicon.ico", () => imageResponse(PNG)),
|
||||||
|
);
|
||||||
|
|
||||||
|
await cacheFaviconForDomain("github.com", env);
|
||||||
|
|
||||||
|
const record = await env.EMAIL_STORAGE.get(iconKey("github.com"), "json");
|
||||||
|
expect(record).toMatchObject({ contentType: "image/png" });
|
||||||
|
expect((record as { data: string }).data).toBeTruthy();
|
||||||
|
expect(record).not.toHaveProperty("fetchedAt");
|
||||||
|
|
||||||
|
const icon = await getCachedIcon("github.com", env);
|
||||||
|
expect(icon?.contentType).toBe("image/png");
|
||||||
|
expect(new Uint8Array(icon!.bytes)).toEqual(PNG);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("falls back to DuckDuckGo when the direct icon 404s", async () => {
|
||||||
|
const env = createMockEnv() as unknown as Env;
|
||||||
|
server.use(
|
||||||
|
http.get("https://acme.test/favicon.ico", () =>
|
||||||
|
HttpResponse.text("nope", { status: 404 }),
|
||||||
|
),
|
||||||
|
http.get("https://icons.duckduckgo.com/ip3/acme.test.ico", () =>
|
||||||
|
imageResponse(PNG, "image/x-icon"),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
await cacheFaviconForDomain("acme.test", env);
|
||||||
|
|
||||||
|
const icon = await getCachedIcon("acme.test", env);
|
||||||
|
expect(icon?.contentType).toBe("image/x-icon");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("writes a negative entry when no icon is found", async () => {
|
||||||
|
const env = createMockEnv() as unknown as Env;
|
||||||
|
server.use(
|
||||||
|
http.get("https://nope.test/favicon.ico", () =>
|
||||||
|
HttpResponse.text("", { status: 404 }),
|
||||||
|
),
|
||||||
|
http.get("https://icons.duckduckgo.com/ip3/nope.test.ico", () =>
|
||||||
|
HttpResponse.text("", { status: 404 }),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
await cacheFaviconForDomain("nope.test", env);
|
||||||
|
|
||||||
|
const record = await env.EMAIL_STORAGE.get(iconKey("nope.test"), "json");
|
||||||
|
expect(record).toEqual({ data: null, contentType: "" });
|
||||||
|
expect(await getCachedIcon("nope.test", env)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects oversized responses as negative", async () => {
|
||||||
|
const env = createMockEnv() as unknown as Env;
|
||||||
|
const big = new Uint8Array(MAX_ICON_BYTES + 1);
|
||||||
|
server.use(
|
||||||
|
http.get("https://big.test/favicon.ico", () => imageResponse(big)),
|
||||||
|
http.get("https://icons.duckduckgo.com/ip3/big.test.ico", () =>
|
||||||
|
HttpResponse.text("", { status: 404 }),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
await cacheFaviconForDomain("big.test", env);
|
||||||
|
expect(await getCachedIcon("big.test", env)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects non-image content types as negative", async () => {
|
||||||
|
const env = createMockEnv() as unknown as Env;
|
||||||
|
server.use(
|
||||||
|
http.get("https://html.test/favicon.ico", () =>
|
||||||
|
HttpResponse.text("<html>", {
|
||||||
|
headers: { "Content-Type": "text/html" },
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
http.get("https://icons.duckduckgo.com/ip3/html.test.ico", () =>
|
||||||
|
HttpResponse.text("", { status: 404 }),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
await cacheFaviconForDomain("html.test", env);
|
||||||
|
expect(await getCachedIcon("html.test", env)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("short-circuits when an entry already exists (no outbound fetch)", async () => {
|
||||||
|
const env = createMockEnv() as unknown as Env;
|
||||||
|
// Pre-seed a record; with MSW onUnhandledRequest:"error", any fetch fails.
|
||||||
|
await env.EMAIL_STORAGE.put(
|
||||||
|
iconKey("cached.test"),
|
||||||
|
JSON.stringify({ data: null, contentType: "" }),
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
cacheFaviconForDomain("cached.test", env),
|
||||||
|
).resolves.toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("never throws on network errors", async () => {
|
||||||
|
const env = createMockEnv() as unknown as Env;
|
||||||
|
server.use(
|
||||||
|
http.get("https://err.test/favicon.ico", () => HttpResponse.error()),
|
||||||
|
http.get("https://icons.duckduckgo.com/ip3/err.test.ico", () =>
|
||||||
|
HttpResponse.error(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
cacheFaviconForDomain("err.test", env),
|
||||||
|
).resolves.toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
import { Env } from "../types";
|
||||||
|
import {
|
||||||
|
ICON_FETCH_TIMEOUT_MS,
|
||||||
|
ICON_TTL_SECONDS,
|
||||||
|
MAX_ICON_BYTES,
|
||||||
|
} from "../config/constants";
|
||||||
|
import { IconRepository } from "./icon-repository";
|
||||||
|
import { EmailAddress } from "../domain/value-objects/email-address";
|
||||||
|
import { logger } from "./logger";
|
||||||
|
|
||||||
|
interface IconRecord {
|
||||||
|
data: string | null; // base64 icon bytes, or null for a negative cache entry
|
||||||
|
contentType: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extract the lowercased domain from a `from` value, accepting either a bare
|
||||||
|
* address (`a@b.com`) or a display form (`Name <a@b.com>`). Returns null when
|
||||||
|
* no plausible address can be parsed.
|
||||||
|
*/
|
||||||
|
export function extractEmailDomain(from: string): string | null {
|
||||||
|
return EmailAddress.parse(from)?.domain.value ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function arrayBufferToBase64(buffer: ArrayBuffer): string {
|
||||||
|
const bytes = new Uint8Array(buffer);
|
||||||
|
let binary = "";
|
||||||
|
const chunkSize = 0x8000;
|
||||||
|
for (let i = 0; i < bytes.length; i += chunkSize) {
|
||||||
|
binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));
|
||||||
|
}
|
||||||
|
return btoa(binary);
|
||||||
|
}
|
||||||
|
|
||||||
|
function base64ToArrayBuffer(base64: string): ArrayBuffer {
|
||||||
|
const binary = atob(base64);
|
||||||
|
const bytes = new Uint8Array(binary.length);
|
||||||
|
for (let i = 0; i < binary.length; i++) {
|
||||||
|
bytes[i] = binary.charCodeAt(i);
|
||||||
|
}
|
||||||
|
return bytes.buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchIconFrom(
|
||||||
|
url: string,
|
||||||
|
): Promise<{ buffer: ArrayBuffer; contentType: string } | null> {
|
||||||
|
const res = await fetch(url, {
|
||||||
|
redirect: "follow",
|
||||||
|
signal: AbortSignal.timeout(ICON_FETCH_TIMEOUT_MS),
|
||||||
|
headers: { "User-Agent": "kill-the-news/1.0" },
|
||||||
|
});
|
||||||
|
if (!res.ok) return null;
|
||||||
|
|
||||||
|
const contentType = res.headers.get("content-type") ?? "";
|
||||||
|
if (!contentType.startsWith("image/")) return null;
|
||||||
|
|
||||||
|
const buffer = await res.arrayBuffer();
|
||||||
|
if (buffer.byteLength === 0 || buffer.byteLength > MAX_ICON_BYTES)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
return { buffer, contentType: contentType.split(";")[0].trim() };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function resolveIcon(
|
||||||
|
domain: string,
|
||||||
|
): Promise<{ buffer: ArrayBuffer; contentType: string } | null> {
|
||||||
|
const candidates = [
|
||||||
|
`https://${domain}/favicon.ico`,
|
||||||
|
`https://icons.duckduckgo.com/ip3/${domain}.ico`,
|
||||||
|
];
|
||||||
|
for (const url of candidates) {
|
||||||
|
try {
|
||||||
|
const icon = await fetchIconFrom(url);
|
||||||
|
if (icon) return icon;
|
||||||
|
} catch {
|
||||||
|
// Try the next candidate; network/timeout errors must never propagate.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve and cache the favicon for a sender domain. Idempotent and never
|
||||||
|
* throws: if a (success or negative) cache entry already exists it returns
|
||||||
|
* immediately, so callers can fire this on every email without refetching.
|
||||||
|
* The KV TTL is the sole expiry mechanism.
|
||||||
|
*/
|
||||||
|
export async function cacheFaviconForDomain(
|
||||||
|
domain: string,
|
||||||
|
env: Env,
|
||||||
|
): Promise<void> {
|
||||||
|
try {
|
||||||
|
const repo = IconRepository.from(env);
|
||||||
|
const existing = await repo.getText(domain);
|
||||||
|
if (existing !== null) return; // present (incl. negative) → nothing to do
|
||||||
|
|
||||||
|
const icon = await resolveIcon(domain);
|
||||||
|
const record: IconRecord = icon
|
||||||
|
? {
|
||||||
|
data: arrayBufferToBase64(icon.buffer),
|
||||||
|
contentType: icon.contentType,
|
||||||
|
}
|
||||||
|
: { data: null, contentType: "" };
|
||||||
|
|
||||||
|
await repo.put(domain, JSON.stringify(record), ICON_TTL_SECONDS);
|
||||||
|
} catch (error) {
|
||||||
|
logger.warn("Favicon cache failed", { domain, error: String(error) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read a cached icon for a domain. Returns null on a miss or a negative entry.
|
||||||
|
*/
|
||||||
|
export async function getCachedIcon(
|
||||||
|
domain: string,
|
||||||
|
env: Env,
|
||||||
|
): Promise<{ bytes: ArrayBuffer; contentType: string } | null> {
|
||||||
|
const record = await IconRepository.from(env).getJson<IconRecord>(domain);
|
||||||
|
if (!record || record.data === null) return null;
|
||||||
|
return {
|
||||||
|
bytes: base64ToArrayBuffer(record.data),
|
||||||
|
contentType: record.contentType,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -10,6 +10,7 @@ const mockFeedConfig: FeedConfig = {
|
|||||||
title: "Test Newsletter",
|
title: "Test Newsletter",
|
||||||
description: "A test feed",
|
description: "A test feed",
|
||||||
language: "en",
|
language: "en",
|
||||||
|
mailbox_id: "test.news.42",
|
||||||
created_at: 1700000000000,
|
created_at: 1700000000000,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -72,6 +73,17 @@ describe("generateRssFeed", () => {
|
|||||||
expect(result).toContain("<title>Test Newsletter</title>");
|
expect(result).toContain("<title>Test Newsletter</title>");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("includes the per-feed icon as the channel <image>", () => {
|
||||||
|
const result = generateRssFeed(
|
||||||
|
mockFeedConfig,
|
||||||
|
mockEmails,
|
||||||
|
BASE_URL,
|
||||||
|
FEED_ID,
|
||||||
|
);
|
||||||
|
expect(result).toContain("<image>");
|
||||||
|
expect(result).toContain(`${BASE_URL}/favicon/${FEED_ID}`);
|
||||||
|
});
|
||||||
|
|
||||||
it("includes <enclosure> element for email with attachment", () => {
|
it("includes <enclosure> element for email with attachment", () => {
|
||||||
const result = generateRssFeed(
|
const result = generateRssFeed(
|
||||||
mockFeedConfig,
|
mockFeedConfig,
|
||||||
@@ -135,14 +147,46 @@ describe("generateRssFeed", () => {
|
|||||||
expect(result).not.toContain("<item>");
|
expect(result).not.toContain("<item>");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("feed link points to admin emails page", () => {
|
it("leaves the item title unprefixed by default", () => {
|
||||||
const result = generateRssFeed(
|
const result = generateRssFeed(
|
||||||
mockFeedConfig,
|
mockFeedConfig,
|
||||||
mockEmails,
|
mockEmails,
|
||||||
BASE_URL,
|
BASE_URL,
|
||||||
FEED_ID,
|
FEED_ID,
|
||||||
);
|
);
|
||||||
expect(result).toContain(`${BASE_URL}/admin/feeds/${FEED_ID}/emails`);
|
expect(result).toContain("Hello World");
|
||||||
|
expect(result).not.toContain("[Alice]");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("prefixes the item title with the sender when sender_in_title is set", () => {
|
||||||
|
const result = generateRssFeed(
|
||||||
|
{ ...mockFeedConfig, sender_in_title: true },
|
||||||
|
mockEmails,
|
||||||
|
BASE_URL,
|
||||||
|
FEED_ID,
|
||||||
|
);
|
||||||
|
expect(result).toContain("[Alice] Hello World");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("falls back to the email address when the sender has no display name", () => {
|
||||||
|
const result = generateRssFeed(
|
||||||
|
{ ...mockFeedConfig, sender_in_title: true },
|
||||||
|
[{ ...mockEmails[0], from: "bob@example.com" }],
|
||||||
|
BASE_URL,
|
||||||
|
FEED_ID,
|
||||||
|
);
|
||||||
|
expect(result).toContain("[bob@example.com] Hello World");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("feed link points to the public read URL, never an admin path", () => {
|
||||||
|
const result = generateRssFeed(
|
||||||
|
mockFeedConfig,
|
||||||
|
mockEmails,
|
||||||
|
BASE_URL,
|
||||||
|
FEED_ID,
|
||||||
|
);
|
||||||
|
expect(result).toContain(`<link>${BASE_URL}/rss/${FEED_ID}</link>`);
|
||||||
|
expect(result).not.toContain("/admin/");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("strips html/head/body wrapper from item description", () => {
|
it("strips html/head/body wrapper from item description", () => {
|
||||||
@@ -172,6 +216,18 @@ describe("generateAtomFeed", () => {
|
|||||||
expect(result).toContain('xmlns="http://www.w3.org/2005/Atom"');
|
expect(result).toContain('xmlns="http://www.w3.org/2005/Atom"');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("includes the per-feed icon as <icon> and <logo>", () => {
|
||||||
|
const result = generateAtomFeed(
|
||||||
|
mockFeedConfig,
|
||||||
|
mockEmails,
|
||||||
|
BASE_URL,
|
||||||
|
FEED_ID,
|
||||||
|
);
|
||||||
|
const iconUrl = `${BASE_URL}/favicon/${FEED_ID}`;
|
||||||
|
expect(result).toContain(`<icon>${iconUrl}</icon>`);
|
||||||
|
expect(result).toContain(`<logo>${iconUrl}</logo>`);
|
||||||
|
});
|
||||||
|
|
||||||
it("contains <feed> root element", () => {
|
it("contains <feed> root element", () => {
|
||||||
const result = generateAtomFeed(
|
const result = generateAtomFeed(
|
||||||
mockFeedConfig,
|
mockFeedConfig,
|
||||||
@@ -240,14 +296,15 @@ describe("generateAtomFeed", () => {
|
|||||||
expect(result).not.toContain("<entry>");
|
expect(result).not.toContain("<entry>");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("feed link points to admin emails page", () => {
|
it("feed link points to the public read URL, never an admin path", () => {
|
||||||
const result = generateAtomFeed(
|
const result = generateAtomFeed(
|
||||||
mockFeedConfig,
|
mockFeedConfig,
|
||||||
mockEmails,
|
mockEmails,
|
||||||
BASE_URL,
|
BASE_URL,
|
||||||
FEED_ID,
|
FEED_ID,
|
||||||
);
|
);
|
||||||
expect(result).toContain(`${BASE_URL}/admin/feeds/${FEED_ID}/emails`);
|
expect(result).toContain(`${BASE_URL}/rss/${FEED_ID}`);
|
||||||
|
expect(result).not.toContain("/admin/");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("strips html/head/body wrapper from entry content", () => {
|
it("strips html/head/body wrapper from entry content", () => {
|
||||||
@@ -290,6 +347,66 @@ describe("generateAtomFeed", () => {
|
|||||||
expect(result).toContain("Bob");
|
expect(result).toContain("Bob");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("renders the subject as plain text in <title> (strips tags, decodes entities)", () => {
|
||||||
|
const emailWithHtmlSubject: EmailData = {
|
||||||
|
...mockEmails[0],
|
||||||
|
subject: "<b>Sale</b> Tom & Jerry",
|
||||||
|
};
|
||||||
|
const result = generateAtomFeed(
|
||||||
|
mockFeedConfig,
|
||||||
|
[emailWithHtmlSubject],
|
||||||
|
BASE_URL,
|
||||||
|
FEED_ID,
|
||||||
|
);
|
||||||
|
// Tags are stripped and entities decoded; markup must not survive.
|
||||||
|
expect(result).toContain("Sale Tom & Jerry");
|
||||||
|
expect(result).not.toContain("<b>Sale</b>");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("strips XML-illegal control characters from the output", () => {
|
||||||
|
const emailWithControlChar: EmailData = {
|
||||||
|
...mockEmails[0],
|
||||||
|
subject: "Bad\x00\x1Fchar",
|
||||||
|
content: "<p>body\x0Bhere</p>",
|
||||||
|
};
|
||||||
|
const result = generateAtomFeed(
|
||||||
|
mockFeedConfig,
|
||||||
|
[emailWithControlChar],
|
||||||
|
BASE_URL,
|
||||||
|
FEED_ID,
|
||||||
|
);
|
||||||
|
expect(result).not.toMatch(/[\x00\x0B\x1F]/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("preserves emoji (surrogate pairs) in the output", () => {
|
||||||
|
const emailWithEmoji: EmailData = {
|
||||||
|
...mockEmails[0],
|
||||||
|
subject: "Launch 🚀 today",
|
||||||
|
};
|
||||||
|
const result = generateAtomFeed(
|
||||||
|
mockFeedConfig,
|
||||||
|
[emailWithEmoji],
|
||||||
|
BASE_URL,
|
||||||
|
FEED_ID,
|
||||||
|
);
|
||||||
|
expect(result).toContain("🚀");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("absolutizes relative content URLs against the sender domain", () => {
|
||||||
|
const emailWithRelative: EmailData = {
|
||||||
|
...mockEmails[0],
|
||||||
|
from: "News <news@acme.com>",
|
||||||
|
content: '<body><a href="/article">read</a></body>',
|
||||||
|
};
|
||||||
|
const result = generateAtomFeed(
|
||||||
|
mockFeedConfig,
|
||||||
|
[emailWithRelative],
|
||||||
|
BASE_URL,
|
||||||
|
FEED_ID,
|
||||||
|
);
|
||||||
|
expect(result).toContain("https://acme.com/article");
|
||||||
|
});
|
||||||
|
|
||||||
it("includes enclosure link for email with attachment in Atom feed", () => {
|
it("includes enclosure link for email with attachment in Atom feed", () => {
|
||||||
const result = generateAtomFeed(
|
const result = generateAtomFeed(
|
||||||
mockFeedConfig,
|
mockFeedConfig,
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
import { Feed } from "feed";
|
||||||
|
import { FeedConfig, EmailData } from "../types";
|
||||||
|
import { processEmailContent, htmlToText } from "./html-processor";
|
||||||
|
import { EmailAddress } from "../domain/value-objects/email-address";
|
||||||
|
import { entryPath } from "./urls";
|
||||||
|
|
||||||
|
export { processEmailContent as extractBodyContent };
|
||||||
|
|
||||||
|
// XML 1.0 valid chars: #x9 #xA #xD #x20-#xD7FF #xE000-#xFFFD #x10000-#x10FFFF.
|
||||||
|
// A single illegal codepoint fails the whole feed parse in strict readers, so
|
||||||
|
// strip the complement before returning. The `u` flag iterates by code point, so
|
||||||
|
// valid surrogate pairs (emoji, …) survive while lone surrogates are removed.
|
||||||
|
function stripInvalidXmlChars(xml: string): string {
|
||||||
|
return xml.replace(/[^\x09\x0A\x0D\x20--�\u{10000}-\u{10FFFF}]/gu, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildFeed(
|
||||||
|
feedConfig: FeedConfig,
|
||||||
|
emails: EmailData[],
|
||||||
|
baseUrl: string,
|
||||||
|
feedId: string,
|
||||||
|
selfUrl?: { rss?: string; atom?: string; json?: string },
|
||||||
|
): Feed {
|
||||||
|
const iconUrl = `${baseUrl}/favicon/${feedId}`;
|
||||||
|
const feed = new Feed({
|
||||||
|
title: feedConfig.title,
|
||||||
|
description: feedConfig.description || "",
|
||||||
|
// Per-feed icon derived from the last sender's domain (self-falls-back to
|
||||||
|
// the project icon). image → RSS <image>/Atom <logo>; favicon → Atom <icon>.
|
||||||
|
image: iconUrl,
|
||||||
|
favicon: iconUrl,
|
||||||
|
// Computed dynamically so the id is always canonical regardless of what
|
||||||
|
// was stored in KV at feed-creation time (which may have used a stale domain).
|
||||||
|
id: `${baseUrl}/rss/${feedId}`,
|
||||||
|
// Public "website" for this feed: its own read URL (never the inbound address
|
||||||
|
// or an auth-gated admin path, so the feed output leaks neither).
|
||||||
|
link: `${baseUrl}/rss/${feedId}`,
|
||||||
|
language: feedConfig.language,
|
||||||
|
updated: new Date(),
|
||||||
|
generator: "kill-the-news",
|
||||||
|
copyright: `Copyright © ${new Date().getFullYear()} ${feedConfig.title}`,
|
||||||
|
feedLinks: {
|
||||||
|
rss: selfUrl?.rss ?? `${baseUrl}/rss/${feedId}`,
|
||||||
|
atom: selfUrl?.atom ?? `${baseUrl}/atom/${feedId}`,
|
||||||
|
json: selfUrl?.json ?? `${baseUrl}/json/${feedId}`,
|
||||||
|
},
|
||||||
|
author: feedConfig.author
|
||||||
|
? {
|
||||||
|
name: feedConfig.author,
|
||||||
|
email: `noreply@${new URL(baseUrl).hostname}`,
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const email of emails) {
|
||||||
|
const entryUrl = `${baseUrl}${entryPath(feedId, email.receivedAt)}`;
|
||||||
|
// Inline images are rendered in the body, not surfaced as an enclosure.
|
||||||
|
const firstAttachment = email.attachments?.find((a) => !a.inline);
|
||||||
|
const sender = EmailAddress.parse(email.from);
|
||||||
|
const senderLabel = sender?.label() ?? email.from.trim();
|
||||||
|
const bodyContent = processEmailContent(
|
||||||
|
email.content,
|
||||||
|
email.attachments,
|
||||||
|
baseUrl,
|
||||||
|
sender?.siteBaseUrl() ?? "",
|
||||||
|
);
|
||||||
|
const subject = htmlToText(email.subject);
|
||||||
|
feed.addItem({
|
||||||
|
title: feedConfig.sender_in_title
|
||||||
|
? `[${senderLabel}] ${subject}`
|
||||||
|
: subject,
|
||||||
|
id: entryUrl,
|
||||||
|
link: entryUrl,
|
||||||
|
description: bodyContent,
|
||||||
|
content: bodyContent,
|
||||||
|
author: [
|
||||||
|
sender
|
||||||
|
? { name: senderLabel, email: sender.normalized }
|
||||||
|
: { name: senderLabel },
|
||||||
|
],
|
||||||
|
date: new Date(email.receivedAt),
|
||||||
|
enclosure: firstAttachment
|
||||||
|
? {
|
||||||
|
url: `${baseUrl}/files/${firstAttachment.id}/${encodeURIComponent(firstAttachment.filename)}`,
|
||||||
|
type: firstAttachment.contentType,
|
||||||
|
length: firstAttachment.size,
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return feed;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function generateRssFeed(
|
||||||
|
feedConfig: FeedConfig,
|
||||||
|
emails: EmailData[],
|
||||||
|
baseUrl: string,
|
||||||
|
feedId: string,
|
||||||
|
selfUrl?: string,
|
||||||
|
): string {
|
||||||
|
return stripInvalidXmlChars(
|
||||||
|
buildFeed(
|
||||||
|
feedConfig,
|
||||||
|
emails,
|
||||||
|
baseUrl,
|
||||||
|
feedId,
|
||||||
|
selfUrl ? { rss: selfUrl } : undefined,
|
||||||
|
).rss2(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function generateAtomFeed(
|
||||||
|
feedConfig: FeedConfig,
|
||||||
|
emails: EmailData[],
|
||||||
|
baseUrl: string,
|
||||||
|
feedId: string,
|
||||||
|
selfUrl?: string,
|
||||||
|
): string {
|
||||||
|
return stripInvalidXmlChars(
|
||||||
|
buildFeed(
|
||||||
|
feedConfig,
|
||||||
|
emails,
|
||||||
|
baseUrl,
|
||||||
|
feedId,
|
||||||
|
selfUrl ? { atom: selfUrl } : undefined,
|
||||||
|
).atom1(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function generateJsonFeed(
|
||||||
|
feedConfig: FeedConfig,
|
||||||
|
emails: EmailData[],
|
||||||
|
baseUrl: string,
|
||||||
|
feedId: string,
|
||||||
|
selfUrl?: string,
|
||||||
|
): string {
|
||||||
|
return buildFeed(
|
||||||
|
feedConfig,
|
||||||
|
emails,
|
||||||
|
baseUrl,
|
||||||
|
feedId,
|
||||||
|
selfUrl ? { json: selfUrl } : undefined,
|
||||||
|
).json1();
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import { fromConfigDTO, toConfigDTO, toListItemDTO } from "./feed-mapper";
|
||||||
|
import { FeedId } from "../domain/value-objects/feed-id";
|
||||||
|
import type { FeedConfig } from "../types";
|
||||||
|
|
||||||
|
const fullConfig: FeedConfig = {
|
||||||
|
title: "News",
|
||||||
|
description: "desc",
|
||||||
|
language: "en",
|
||||||
|
mailbox_id: "a.b.42",
|
||||||
|
author: "Jane",
|
||||||
|
allowed_senders: ["a@x.com"],
|
||||||
|
blocked_senders: ["b@y.com"],
|
||||||
|
created_at: 1000,
|
||||||
|
updated_at: 2000,
|
||||||
|
expires_at: 3000,
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("feed-mapper", () => {
|
||||||
|
it("round-trips a full config DTO through domain state unchanged", () => {
|
||||||
|
expect(toConfigDTO(fromConfigDTO(fullConfig))).toEqual(fullConfig);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("defaults absent sender lists to empty arrays on the domain side", () => {
|
||||||
|
const state = fromConfigDTO({
|
||||||
|
title: "T",
|
||||||
|
language: "en",
|
||||||
|
mailbox_id: "t.t.42",
|
||||||
|
created_at: 1,
|
||||||
|
});
|
||||||
|
expect(state.allowedSenders).toEqual([]);
|
||||||
|
expect(state.blockedSenders).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("projects the feeds:list item from domain state", () => {
|
||||||
|
const item = toListItemDTO(
|
||||||
|
FeedId.unchecked("a.b.42"),
|
||||||
|
fromConfigDTO(fullConfig),
|
||||||
|
);
|
||||||
|
expect(item).toEqual({
|
||||||
|
id: "a.b.42",
|
||||||
|
title: "News",
|
||||||
|
description: "desc",
|
||||||
|
mailbox_id: "a.b.42",
|
||||||
|
expires_at: 3000,
|
||||||
|
pendingConfirmation: false,
|
||||||
|
hasNativeFeed: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("projects hasNativeFeed when passed", () => {
|
||||||
|
const item = toListItemDTO(
|
||||||
|
FeedId.unchecked("a.b.42"),
|
||||||
|
fromConfigDTO(fullConfig),
|
||||||
|
true,
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
expect(item.pendingConfirmation).toBe(true);
|
||||||
|
expect(item.hasNativeFeed).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import { FeedConfig, FeedListItem } from "../types";
|
||||||
|
import { FeedState } from "../domain/feed-state";
|
||||||
|
import { FeedId } from "../domain/value-objects/feed-id";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The translation seam between the Feed aggregate's domain state (camelCase) and
|
||||||
|
* the persistence/edge DTOs (`FeedConfig`/`FeedListItem`, snake_case). This is
|
||||||
|
* the ONLY place outside the HTTP edge that knows the stored field names — the
|
||||||
|
* domain stays free of the storage dialect, and the repository round-trips
|
||||||
|
* through here on every load/save.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** Persisted config DTO → domain state (used by `FeedRepository.load`). */
|
||||||
|
export function fromConfigDTO(dto: FeedConfig): FeedState {
|
||||||
|
return {
|
||||||
|
title: dto.title,
|
||||||
|
description: dto.description,
|
||||||
|
language: dto.language,
|
||||||
|
mailboxId: dto.mailbox_id,
|
||||||
|
author: dto.author,
|
||||||
|
senderInTitle: dto.sender_in_title,
|
||||||
|
allowedSenders: dto.allowed_senders ?? [],
|
||||||
|
blockedSenders: dto.blocked_senders ?? [],
|
||||||
|
createdAt: dto.created_at,
|
||||||
|
updatedAt: dto.updated_at,
|
||||||
|
expiresAt: dto.expires_at,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Domain state → persisted config DTO (used by `FeedRepository.save`). */
|
||||||
|
export function toConfigDTO(state: FeedState): FeedConfig {
|
||||||
|
return {
|
||||||
|
title: state.title,
|
||||||
|
description: state.description,
|
||||||
|
language: state.language,
|
||||||
|
mailbox_id: state.mailboxId,
|
||||||
|
author: state.author,
|
||||||
|
sender_in_title: state.senderInTitle,
|
||||||
|
allowed_senders: state.allowedSenders,
|
||||||
|
blocked_senders: state.blockedSenders,
|
||||||
|
created_at: state.createdAt,
|
||||||
|
updated_at: state.updatedAt,
|
||||||
|
expires_at: state.expiresAt,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Domain state → the projection cached in the global `feeds:list` registry. */
|
||||||
|
export function toListItemDTO(
|
||||||
|
id: FeedId,
|
||||||
|
state: FeedState,
|
||||||
|
pendingConfirmation = false,
|
||||||
|
hasNativeFeed = false,
|
||||||
|
): FeedListItem {
|
||||||
|
return {
|
||||||
|
id: id.value,
|
||||||
|
title: state.title,
|
||||||
|
description: state.description,
|
||||||
|
mailbox_id: state.mailboxId,
|
||||||
|
expires_at: state.expiresAt,
|
||||||
|
pendingConfirmation,
|
||||||
|
hasNativeFeed,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,281 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import { createMockEnv } from "../test/setup";
|
||||||
|
import { FeedRepository } from "./feed-repository";
|
||||||
|
import { Feed } from "../domain/feed.aggregate";
|
||||||
|
import { FeedId } from "../domain/value-objects/feed-id";
|
||||||
|
import { MailboxId } from "../domain/value-objects/mailbox-id";
|
||||||
|
import type { Env, FeedConfig, FeedMetadata, EmailData } from "../types";
|
||||||
|
|
||||||
|
const mockEnv = () => createMockEnv() as unknown as Env;
|
||||||
|
const fid = (value: string) => FeedId.unchecked(value);
|
||||||
|
|
||||||
|
const sampleConfig = (overrides: Partial<FeedConfig> = {}): FeedConfig => ({
|
||||||
|
title: "Test Feed",
|
||||||
|
language: "en",
|
||||||
|
mailbox_id: "test.feed.42",
|
||||||
|
created_at: 1000,
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
const sampleEmail = (overrides: Partial<EmailData> = {}): EmailData => ({
|
||||||
|
subject: "Hello",
|
||||||
|
from: "news@example.com",
|
||||||
|
content: "<p>hi</p>",
|
||||||
|
receivedAt: 1234,
|
||||||
|
headers: {},
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("FeedRepository key schema", () => {
|
||||||
|
it("builds the canonical KV keys via the public API", () => {
|
||||||
|
const repo = new FeedRepository(mockEnv().EMAIL_STORAGE);
|
||||||
|
expect(repo.feedKeyPrefix(fid("a.b.42"))).toBe("feed:a.b.42:");
|
||||||
|
expect(repo.newEmailKey(fid("a.b.42"))).toMatch(/^feed:a\.b\.42:\d+$/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("recognises email keys vs config/metadata keys", () => {
|
||||||
|
const repo = new FeedRepository(mockEnv().EMAIL_STORAGE);
|
||||||
|
expect(repo.isEmailKey(fid("a.b.42"), "feed:a.b.42:config")).toBe(false);
|
||||||
|
expect(repo.isEmailKey(fid("a.b.42"), "feed:a.b.42:metadata")).toBe(false);
|
||||||
|
expect(repo.isEmailKey(fid("a.b.42"), "feed:a.b.42:1700000000000")).toBe(
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("recovers the feed id from an email key", () => {
|
||||||
|
const repo = new FeedRepository(mockEnv().EMAIL_STORAGE);
|
||||||
|
expect(repo.feedIdFromEmailKey("feed:a.b.42:1700000000000")).toBe("a.b.42");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("FeedRepository inbound index", () => {
|
||||||
|
const mbox = (v: string) => MailboxId.unchecked(v);
|
||||||
|
|
||||||
|
it("resolves a mailbox to its feed id and back to null after delete", async () => {
|
||||||
|
const repo = new FeedRepository(mockEnv().EMAIL_STORAGE);
|
||||||
|
expect(await repo.resolveInbound(mbox("river.castle.42"))).toBeNull();
|
||||||
|
|
||||||
|
await repo.putInboundIndex(mbox("river.castle.42"), fid("opaque-id-1"));
|
||||||
|
expect((await repo.resolveInbound(mbox("river.castle.42")))?.value).toBe(
|
||||||
|
"opaque-id-1",
|
||||||
|
);
|
||||||
|
|
||||||
|
await repo.deleteInboundIndex(mbox("river.castle.42"));
|
||||||
|
expect(await repo.resolveInbound(mbox("river.castle.42"))).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("save() writes the inbound index from the aggregate's mailbox", async () => {
|
||||||
|
const repo = new FeedRepository(mockEnv().EMAIL_STORAGE);
|
||||||
|
await repo.save(
|
||||||
|
Feed.reconstitute(
|
||||||
|
fid("opaque-id-2"),
|
||||||
|
{
|
||||||
|
title: "T",
|
||||||
|
language: "en",
|
||||||
|
mailboxId: "lake.tower.77",
|
||||||
|
allowedSenders: [],
|
||||||
|
blockedSenders: [],
|
||||||
|
createdAt: 1000,
|
||||||
|
},
|
||||||
|
{ emails: [] },
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect((await repo.resolveInbound(mbox("lake.tower.77")))?.value).toBe(
|
||||||
|
"opaque-id-2",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("FeedRepository config & metadata", () => {
|
||||||
|
it("round-trips and deletes a feed config", async () => {
|
||||||
|
const repo = new FeedRepository(mockEnv().EMAIL_STORAGE);
|
||||||
|
expect(await repo.getConfig(fid("a.b.42"))).toBeNull();
|
||||||
|
await repo.putConfig(fid("a.b.42"), sampleConfig());
|
||||||
|
expect(await repo.getConfig(fid("a.b.42"))).toMatchObject({
|
||||||
|
title: "Test Feed",
|
||||||
|
});
|
||||||
|
await repo.deleteConfig(fid("a.b.42"));
|
||||||
|
expect(await repo.getConfig(fid("a.b.42"))).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("round-trips and deletes feed metadata", async () => {
|
||||||
|
const repo = new FeedRepository(mockEnv().EMAIL_STORAGE);
|
||||||
|
const meta: FeedMetadata = { emails: [] };
|
||||||
|
await repo.putMetadata(fid("a.b.42"), meta);
|
||||||
|
expect(await repo.getMetadata(fid("a.b.42"))).toEqual(meta);
|
||||||
|
await repo.deleteMetadata(fid("a.b.42"));
|
||||||
|
expect(await repo.getMetadata(fid("a.b.42"))).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("FeedRepository emails", () => {
|
||||||
|
it("stores and reads an email under a minted key", async () => {
|
||||||
|
const repo = new FeedRepository(mockEnv().EMAIL_STORAGE);
|
||||||
|
const key = repo.newEmailKey(fid("a.b.42"));
|
||||||
|
await repo.putEmail(key, sampleEmail());
|
||||||
|
expect(await repo.getEmail(key)).toMatchObject({ subject: "Hello" });
|
||||||
|
await repo.deleteEmail(key);
|
||||||
|
expect(await repo.getEmail(key)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("lists every key under a feed prefix", async () => {
|
||||||
|
const repo = new FeedRepository(mockEnv().EMAIL_STORAGE);
|
||||||
|
await repo.putConfig(fid("a.b.42"), sampleConfig());
|
||||||
|
await repo.putMetadata(fid("a.b.42"), { emails: [] });
|
||||||
|
const emailKey = repo.newEmailKey(fid("a.b.42"));
|
||||||
|
await repo.putEmail(emailKey, sampleEmail());
|
||||||
|
|
||||||
|
const listed = await repo.listFeedKeys(fid("a.b.42"));
|
||||||
|
expect(listed.names).toContain("feed:a.b.42:config");
|
||||||
|
expect(listed.names).toContain("feed:a.b.42:metadata");
|
||||||
|
expect(listed.names).toContain(emailKey);
|
||||||
|
expect(
|
||||||
|
listed.names.filter((k) => repo.isEmailKey(fid("a.b.42"), k)),
|
||||||
|
).toEqual([emailKey]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("FeedRepository feed list", () => {
|
||||||
|
const feedWith = (
|
||||||
|
id: string,
|
||||||
|
title: string,
|
||||||
|
opts: { description?: string; expires_at?: number } = {},
|
||||||
|
) =>
|
||||||
|
Feed.reconstitute(
|
||||||
|
fid(id),
|
||||||
|
{
|
||||||
|
title,
|
||||||
|
language: "en",
|
||||||
|
mailboxId: `${id}.mbox`,
|
||||||
|
allowedSenders: [],
|
||||||
|
blockedSenders: [],
|
||||||
|
createdAt: 1000,
|
||||||
|
description: opts.description,
|
||||||
|
expiresAt: opts.expires_at,
|
||||||
|
},
|
||||||
|
{ emails: [] },
|
||||||
|
);
|
||||||
|
|
||||||
|
it("upserts the list entry from the aggregate on save/saveConfig", async () => {
|
||||||
|
const repo = new FeedRepository(mockEnv().EMAIL_STORAGE);
|
||||||
|
await repo.save(
|
||||||
|
feedWith("a.b.42", "One", { description: "desc", expires_at: 5000 }),
|
||||||
|
);
|
||||||
|
await repo.save(feedWith("c.d.99", "Two"));
|
||||||
|
|
||||||
|
let feeds = await repo.listFeeds();
|
||||||
|
expect(feeds).toHaveLength(2);
|
||||||
|
expect(feeds.find((f) => f.id === "a.b.42")).toMatchObject({
|
||||||
|
title: "One",
|
||||||
|
expires_at: 5000,
|
||||||
|
});
|
||||||
|
|
||||||
|
// saveConfig refreshes the same entry in place (no duplicate, expiry cleared).
|
||||||
|
await repo.saveConfig(feedWith("a.b.42", "One-updated"));
|
||||||
|
feeds = await repo.listFeeds();
|
||||||
|
expect(feeds.filter((f) => f.id === "a.b.42")).toHaveLength(1);
|
||||||
|
const updated = feeds.find((f) => f.id === "a.b.42");
|
||||||
|
expect(updated).toMatchObject({ title: "One-updated" });
|
||||||
|
expect(updated?.expires_at).toBeUndefined();
|
||||||
|
|
||||||
|
expect(await repo.removeFromList(fid("a.b.42"))).toBe(true);
|
||||||
|
expect(await repo.removeFromList(fid("missing"))).toBe(false);
|
||||||
|
feeds = await repo.listFeeds();
|
||||||
|
expect(feeds.map((f) => f.id)).toEqual(["c.d.99"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("bulk-removes only the matching ids", async () => {
|
||||||
|
const repo = new FeedRepository(mockEnv().EMAIL_STORAGE);
|
||||||
|
await repo.save(feedWith("a.b.42", "One"));
|
||||||
|
await repo.save(feedWith("c.d.99", "Two"));
|
||||||
|
await repo.save(feedWith("e.f.10", "Three"));
|
||||||
|
|
||||||
|
const removed = await repo.removeFromListBulk(["a.b.42", "e.f.10", "nope"]);
|
||||||
|
expect(removed.sort()).toEqual(["a.b.42", "e.f.10"]);
|
||||||
|
expect((await repo.listFeeds()).map((f) => f.id)).toEqual(["c.d.99"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("drops each removed feed's inbound index (symmetric with save)", async () => {
|
||||||
|
const repo = new FeedRepository(mockEnv().EMAIL_STORAGE);
|
||||||
|
const mbox = (v: string) => MailboxId.unchecked(v);
|
||||||
|
await repo.save(feedWith("a.b.42", "One"));
|
||||||
|
await repo.save(feedWith("c.d.99", "Two"));
|
||||||
|
|
||||||
|
// Both addresses resolve before removal.
|
||||||
|
expect(await repo.resolveInbound(mbox("a.b.42.mbox"))).not.toBeNull();
|
||||||
|
expect(await repo.resolveInbound(mbox("c.d.99.mbox"))).not.toBeNull();
|
||||||
|
|
||||||
|
await repo.removeFromListBulk(["a.b.42"]);
|
||||||
|
|
||||||
|
// The removed feed's address stops resolving; the survivor's still does.
|
||||||
|
expect(await repo.resolveInbound(mbox("a.b.42.mbox"))).toBeNull();
|
||||||
|
expect((await repo.resolveInbound(mbox("c.d.99.mbox")))?.value).toBe(
|
||||||
|
"c.d.99",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("FeedRepository pendingConfirmation projection", () => {
|
||||||
|
function makeFeed(): Feed {
|
||||||
|
return Feed.create(
|
||||||
|
FeedId.generate(),
|
||||||
|
{
|
||||||
|
title: "T",
|
||||||
|
description: "",
|
||||||
|
language: "en",
|
||||||
|
allowedSenders: [],
|
||||||
|
blockedSenders: [],
|
||||||
|
},
|
||||||
|
{ mailboxId: MailboxId.unchecked("alpha.beta.11") },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
it("saveMetadata projects pendingConfirmation into feeds:list", async () => {
|
||||||
|
const repo = new FeedRepository(mockEnv().EMAIL_STORAGE);
|
||||||
|
const feed = makeFeed();
|
||||||
|
await repo.save(feed);
|
||||||
|
|
||||||
|
feed.ingest(
|
||||||
|
{
|
||||||
|
key: "k1",
|
||||||
|
subject: "s",
|
||||||
|
receivedAt: Date.now(),
|
||||||
|
size: 10,
|
||||||
|
confirmation: { links: ["https://x/confirm"] },
|
||||||
|
},
|
||||||
|
{ maxBytes: 1_000_000 },
|
||||||
|
);
|
||||||
|
await repo.saveMetadata(feed);
|
||||||
|
|
||||||
|
const list = await repo.listFeeds();
|
||||||
|
const entry = list.find((f) => f.id === feed.id.value);
|
||||||
|
expect(entry?.pendingConfirmation).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("saveMetadata clears the projected flag after dismiss", async () => {
|
||||||
|
const repo = new FeedRepository(mockEnv().EMAIL_STORAGE);
|
||||||
|
const feed = makeFeed();
|
||||||
|
feed.ingest(
|
||||||
|
{
|
||||||
|
key: "k1",
|
||||||
|
subject: "s",
|
||||||
|
receivedAt: Date.now(),
|
||||||
|
size: 10,
|
||||||
|
confirmation: { links: ["https://x/confirm"] },
|
||||||
|
},
|
||||||
|
{ maxBytes: 1_000_000 },
|
||||||
|
);
|
||||||
|
await repo.save(feed);
|
||||||
|
expect(
|
||||||
|
(await repo.listFeeds()).find((f) => f.id === feed.id.value)
|
||||||
|
?.pendingConfirmation,
|
||||||
|
).toBe(true);
|
||||||
|
|
||||||
|
feed.dismissConfirmation();
|
||||||
|
await repo.saveMetadata(feed);
|
||||||
|
expect(
|
||||||
|
(await repo.listFeeds()).find((f) => f.id === feed.id.value)
|
||||||
|
?.pendingConfirmation,
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,332 @@
|
|||||||
|
import {
|
||||||
|
EmailData,
|
||||||
|
Env,
|
||||||
|
FeedConfig,
|
||||||
|
FeedList,
|
||||||
|
FeedListItem,
|
||||||
|
FeedMetadata,
|
||||||
|
} from "../types";
|
||||||
|
import { FEEDS_LIST_KEY } from "../config/constants";
|
||||||
|
import { feedKeys } from "../domain/feed-keys";
|
||||||
|
import { Feed } from "../domain/feed.aggregate";
|
||||||
|
import { FeedId } from "../domain/value-objects/feed-id";
|
||||||
|
import { MailboxId } from "../domain/value-objects/mailbox-id";
|
||||||
|
import { fromConfigDTO, toConfigDTO, toListItemDTO } from "./feed-mapper";
|
||||||
|
import { logger } from "./logger";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Single source of truth for KV access to the Feed aggregate. The key schema
|
||||||
|
* itself lives in `feed-keys.ts`; this repository owns the get/put operations.
|
||||||
|
* No other module should build a `feed:`/`feeds:list`/`websub:`/`icon:`/
|
||||||
|
* `stats:counters` key string — go through `feed-keys` or a repository method.
|
||||||
|
*
|
||||||
|
* Wraps one `KVNamespace`; construct per request via `FeedRepository.from(env)`.
|
||||||
|
*/
|
||||||
|
export class FeedRepository {
|
||||||
|
constructor(private readonly kv: KVNamespace) {}
|
||||||
|
|
||||||
|
static from(env: Env): FeedRepository {
|
||||||
|
return new FeedRepository(env.EMAIL_STORAGE);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Key schema (delegates to feed-keys) ───────────────────────────────────
|
||||||
|
|
||||||
|
private configKey(feedId: FeedId): string {
|
||||||
|
return feedKeys.config(feedId.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private metadataKey(feedId: FeedId): string {
|
||||||
|
return feedKeys.metadata(feedId.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Prefix covering every key owned by a feed (config, metadata, emails). */
|
||||||
|
feedKeyPrefix(feedId: FeedId): string {
|
||||||
|
return feedKeys.feedPrefix(feedId.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mint a fresh, time-ordered email key. Call once and reuse the result. */
|
||||||
|
newEmailKey(feedId: FeedId): string {
|
||||||
|
return feedKeys.newEmail(feedId.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True when `key` is an email entry (not the feed's config/metadata key). */
|
||||||
|
isEmailKey(feedId: FeedId, key: string): boolean {
|
||||||
|
return feedKeys.isEmail(feedId.value, key);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Recover the feed id embedded in an email key (`feed:<id>:<ts>`). */
|
||||||
|
feedIdFromEmailKey(key: string): string {
|
||||||
|
return feedKeys.feedIdFromEmail(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Feed aggregate ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load the aggregate (config + email index). A feed exists iff it has a
|
||||||
|
* config; metadata defaults to empty so a freshly-created feed still loads.
|
||||||
|
*/
|
||||||
|
async load(feedId: FeedId): Promise<Feed | null> {
|
||||||
|
const [config, metadata] = await Promise.all([
|
||||||
|
this.getConfig(feedId),
|
||||||
|
this.getMetadata(feedId),
|
||||||
|
]);
|
||||||
|
if (!config) return null;
|
||||||
|
return Feed.reconstitute(
|
||||||
|
feedId,
|
||||||
|
fromConfigDTO(config),
|
||||||
|
metadata ?? { emails: [] },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Persist both keys the aggregate owns (config + metadata) and keep the global
|
||||||
|
* `feeds:list` entry in sync. Config/list DTOs are derived from the aggregate's
|
||||||
|
* domain `state()` via `feed-mapper`, so no caller has to mirror snake_case.
|
||||||
|
*/
|
||||||
|
async save(feed: Feed): Promise<void> {
|
||||||
|
await Promise.all([
|
||||||
|
this.putConfig(feed.id, toConfigDTO(feed.state())),
|
||||||
|
this.putMetadata(feed.id, feed.toMetadataSnapshot()),
|
||||||
|
this.upsertListEntry(
|
||||||
|
toListItemDTO(
|
||||||
|
feed.id,
|
||||||
|
feed.state(),
|
||||||
|
feed.pendingConfirmation,
|
||||||
|
feed.hasNativeFeed(),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
this.putInboundIndex(feed.mailboxId, feed.id),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Persist only the email index. Used by the ingest/delete paths where config
|
||||||
|
* is unchanged — avoids a redundant config write on the hot path. Also
|
||||||
|
* refreshes the `feeds:list` entry's `pendingConfirmation` projection so the
|
||||||
|
* dashboard reflects the latest flag state with a single subsequent KV read.
|
||||||
|
*/
|
||||||
|
async saveMetadata(feed: Feed): Promise<void> {
|
||||||
|
await Promise.all([
|
||||||
|
this.putMetadata(feed.id, feed.toMetadataSnapshot()),
|
||||||
|
this.upsertListEntry(
|
||||||
|
toListItemDTO(
|
||||||
|
feed.id,
|
||||||
|
feed.state(),
|
||||||
|
feed.pendingConfirmation,
|
||||||
|
feed.hasNativeFeed(),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Persist only the config and refresh the `feeds:list` entry from it. Used by
|
||||||
|
* the rename/edit paths where metadata is unchanged — avoids re-writing (and
|
||||||
|
* risking clobbering) the email index.
|
||||||
|
*/
|
||||||
|
async saveConfig(feed: Feed): Promise<void> {
|
||||||
|
await Promise.all([
|
||||||
|
this.putConfig(feed.id, toConfigDTO(feed.state())),
|
||||||
|
this.upsertListEntry(
|
||||||
|
toListItemDTO(
|
||||||
|
feed.id,
|
||||||
|
feed.state(),
|
||||||
|
feed.pendingConfirmation,
|
||||||
|
feed.hasNativeFeed(),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
this.putInboundIndex(feed.mailboxId, feed.id),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Inbound mailbox index ─────────────────────────────────────────────────
|
||||||
|
// Secondary index mapping the friendly inbound address (`noun.noun.NN`) to the
|
||||||
|
// feed's opaque id. Resolved only at reception (the write edge), so the public
|
||||||
|
// read id and the inbound address stay decoupled.
|
||||||
|
|
||||||
|
/** Resolve an inbound mailbox to its feed id, or null when no feed claims it. */
|
||||||
|
async resolveInbound(mailboxId: MailboxId): Promise<FeedId | null> {
|
||||||
|
const feedId = await this.kv.get(feedKeys.inbound(mailboxId.value), {
|
||||||
|
type: "text",
|
||||||
|
});
|
||||||
|
return feedId ? FeedId.unchecked(feedId) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async putInboundIndex(mailboxId: MailboxId, feedId: FeedId): Promise<void> {
|
||||||
|
await this.kv.put(feedKeys.inbound(mailboxId.value), feedId.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteInboundIndex(mailboxId: MailboxId): Promise<void> {
|
||||||
|
await this.kv.delete(feedKeys.inbound(mailboxId.value));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Feed config ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async getConfig(feedId: FeedId): Promise<FeedConfig | null> {
|
||||||
|
return (await this.kv.get(this.configKey(feedId), {
|
||||||
|
type: "json",
|
||||||
|
})) as FeedConfig | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async putConfig(feedId: FeedId, config: FeedConfig): Promise<void> {
|
||||||
|
await this.kv.put(this.configKey(feedId), JSON.stringify(config));
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteConfig(feedId: FeedId): Promise<void> {
|
||||||
|
await this.kv.delete(this.configKey(feedId));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Feed metadata ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async getMetadata(feedId: FeedId): Promise<FeedMetadata | null> {
|
||||||
|
return (await this.kv.get(this.metadataKey(feedId), {
|
||||||
|
type: "json",
|
||||||
|
})) as FeedMetadata | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async putMetadata(feedId: FeedId, metadata: FeedMetadata): Promise<void> {
|
||||||
|
await this.kv.put(this.metadataKey(feedId), JSON.stringify(metadata));
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteMetadata(feedId: FeedId): Promise<void> {
|
||||||
|
await this.kv.delete(this.metadataKey(feedId));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Emails ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async putEmail(key: string, data: EmailData): Promise<void> {
|
||||||
|
await this.kv.put(key, JSON.stringify(data));
|
||||||
|
}
|
||||||
|
|
||||||
|
async getEmail(key: string): Promise<EmailData | null> {
|
||||||
|
return (await this.kv.get(key, { type: "json" })) as EmailData | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteEmail(key: string): Promise<void> {
|
||||||
|
await this.kv.delete(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Global feed list ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async listFeeds(): Promise<FeedListItem[]> {
|
||||||
|
try {
|
||||||
|
const feedList = (await this.kv.get(FEEDS_LIST_KEY, {
|
||||||
|
type: "json",
|
||||||
|
})) as FeedList | null;
|
||||||
|
return feedList?.feeds || [];
|
||||||
|
} catch (error) {
|
||||||
|
logger.error("Error listing feeds", { error: String(error) });
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Insert-or-update a feed's entry in the global `feeds:list` registry from its
|
||||||
|
* aggregate summary. Idempotent by feed id. Private: callers persist a `Feed`
|
||||||
|
* via `save`/`saveConfig`, which keep the projection in sync — never mirror the
|
||||||
|
* list by hand. (Read-modify-write is not atomic under KV, unchanged from the
|
||||||
|
* prior add/update split.)
|
||||||
|
*/
|
||||||
|
private async upsertListEntry(summary: FeedListItem): Promise<void> {
|
||||||
|
try {
|
||||||
|
const feedList = ((await this.kv.get(FEEDS_LIST_KEY, {
|
||||||
|
type: "json",
|
||||||
|
})) as FeedList | null) || { feeds: [] };
|
||||||
|
|
||||||
|
const index = feedList.feeds.findIndex((feed) => feed.id === summary.id);
|
||||||
|
if (index === -1) {
|
||||||
|
feedList.feeds.push(summary);
|
||||||
|
} else {
|
||||||
|
feedList.feeds[index] = summary;
|
||||||
|
}
|
||||||
|
await this.kv.put(FEEDS_LIST_KEY, JSON.stringify(feedList));
|
||||||
|
} catch (error) {
|
||||||
|
logger.error("Error upserting feed in list", {
|
||||||
|
feedId: summary.id,
|
||||||
|
error: String(error),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async removeFromListBulk(feedIds: string[]): Promise<string[]> {
|
||||||
|
try {
|
||||||
|
const feedList = ((await this.kv.get(FEEDS_LIST_KEY, {
|
||||||
|
type: "json",
|
||||||
|
})) as FeedList | null) || { feeds: [] };
|
||||||
|
|
||||||
|
const toRemove = new Set(feedIds.filter(Boolean));
|
||||||
|
if (toRemove.size === 0) return [];
|
||||||
|
|
||||||
|
const removed: string[] = [];
|
||||||
|
const droppedMailboxes: string[] = [];
|
||||||
|
const nextFeeds: FeedListItem[] = [];
|
||||||
|
|
||||||
|
for (const feed of feedList.feeds) {
|
||||||
|
if (toRemove.has(feed.id)) {
|
||||||
|
removed.push(feed.id);
|
||||||
|
if (feed.mailbox_id) droppedMailboxes.push(feed.mailbox_id);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
nextFeeds.push(feed);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (removed.length === 0) return [];
|
||||||
|
|
||||||
|
feedList.feeds = nextFeeds;
|
||||||
|
await this.kv.put(FEEDS_LIST_KEY, JSON.stringify(feedList));
|
||||||
|
|
||||||
|
// Drop each removed feed's inbound index — symmetric with save() writing
|
||||||
|
// it. The index lives outside the feed:<id>: prefix the key purge sweeps,
|
||||||
|
// so a deleted feed's address would keep resolving if left behind. The
|
||||||
|
// mailbox is cached on the list item we just removed.
|
||||||
|
await Promise.all(
|
||||||
|
droppedMailboxes.map((mailbox) =>
|
||||||
|
this.deleteInboundIndex(MailboxId.unchecked(mailbox)),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
return removed;
|
||||||
|
} catch (error) {
|
||||||
|
logger.error("Error removing feeds from list", { error: String(error) });
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async removeFromList(feedId: FeedId): Promise<boolean> {
|
||||||
|
const removed = await this.removeFromListBulk([feedId.value]);
|
||||||
|
return removed.includes(feedId.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Key listing / counting ────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async listFeedKeys(
|
||||||
|
feedId: FeedId,
|
||||||
|
options: { cursor?: string; limit?: number } = {},
|
||||||
|
): Promise<{ names: string[]; cursor: string; listComplete: boolean }> {
|
||||||
|
const prefix = this.feedKeyPrefix(feedId);
|
||||||
|
const limit = Math.min(1000, Math.max(1, Math.floor(options.limit || 100)));
|
||||||
|
const cursor = options.cursor || undefined;
|
||||||
|
|
||||||
|
const listed = await this.kv.list({ prefix, cursor, limit });
|
||||||
|
return {
|
||||||
|
names: (listed.keys || []).map((k) => k.name),
|
||||||
|
cursor: listed.cursor || "",
|
||||||
|
listComplete: !!listed.list_complete,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async countKeysByPrefix(prefix: string): Promise<number> {
|
||||||
|
let total = 0;
|
||||||
|
let cursor: string | undefined;
|
||||||
|
try {
|
||||||
|
do {
|
||||||
|
const listed = await this.kv.list({ prefix, cursor, limit: 1000 });
|
||||||
|
total += listed.keys.length;
|
||||||
|
cursor = listed.list_complete ? undefined : listed.cursor;
|
||||||
|
} while (cursor);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error("Error counting keys", { prefix, error: String(error) });
|
||||||
|
}
|
||||||
|
return total;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,37 @@
|
|||||||
import { EmailParser } from "../utils/email-parser";
|
import { EmailParser } from "../domain/email-parser";
|
||||||
import { Env } from "../types";
|
import { Env } from "../types";
|
||||||
import { processEmail, RawAttachment } from "./email-processor";
|
import {
|
||||||
|
processEmail,
|
||||||
|
IngestResult,
|
||||||
|
RawAttachment,
|
||||||
|
} from "../application/email-processor";
|
||||||
|
import { normalizeCid } from "../infrastructure/html-processor";
|
||||||
|
|
||||||
|
/** Map an ingestion result to the HTTP response ForwardEmail expects. */
|
||||||
|
export function ingestResultToResponse(result: IngestResult): Response {
|
||||||
|
if (result.ok) {
|
||||||
|
return new Response("Email processed successfully", { status: 200 });
|
||||||
|
}
|
||||||
|
switch (result.reason) {
|
||||||
|
case "invalid_address":
|
||||||
|
return new Response("Invalid email address format", { status: 400 });
|
||||||
|
case "mailbox_unknown":
|
||||||
|
return new Response("No feed for this address", { status: 404 });
|
||||||
|
case "feed_not_found":
|
||||||
|
return new Response("Feed does not exist", { status: 404 });
|
||||||
|
case "feed_expired":
|
||||||
|
return new Response("Feed has expired", { status: 410 });
|
||||||
|
case "sender_blocked":
|
||||||
|
return new Response("Sender not allowed for this feed", { status: 403 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export interface ForwardEmailAttachment {
|
export interface ForwardEmailAttachment {
|
||||||
filename?: string;
|
filename?: string;
|
||||||
contentType?: string;
|
contentType?: string;
|
||||||
size?: number;
|
size?: number;
|
||||||
|
cid?: string;
|
||||||
|
contentId?: string;
|
||||||
content?: { type: "Buffer"; data: number[] } | ArrayBuffer | ArrayBufferView;
|
content?: { type: "Buffer"; data: number[] } | ArrayBuffer | ArrayBufferView;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,18 +99,19 @@ export async function handleForwardEmail(
|
|||||||
const emailData = EmailParser.parseForwardEmailPayload(payload);
|
const emailData = EmailParser.parseForwardEmailPayload(payload);
|
||||||
|
|
||||||
const rawAttachments: RawAttachment[] = (payload.attachments ?? [])
|
const rawAttachments: RawAttachment[] = (payload.attachments ?? [])
|
||||||
.map((a) => {
|
.map((a): RawAttachment | null => {
|
||||||
const buffer = toArrayBuffer(a.content);
|
const buffer = toArrayBuffer(a.content);
|
||||||
if (!buffer) return null;
|
if (!buffer) return null;
|
||||||
return {
|
return {
|
||||||
filename: a.filename || "attachment",
|
filename: a.filename || "attachment",
|
||||||
contentType: a.contentType || "application/octet-stream",
|
contentType: a.contentType || "application/octet-stream",
|
||||||
content: buffer,
|
content: buffer,
|
||||||
|
contentId: normalizeCid(a.cid ?? a.contentId),
|
||||||
};
|
};
|
||||||
})
|
})
|
||||||
.filter((a): a is RawAttachment => a !== null);
|
.filter((a): a is RawAttachment => a !== null);
|
||||||
|
|
||||||
return processEmail(
|
const result = await processEmail(
|
||||||
{
|
{
|
||||||
toAddress: payload.recipients?.[0] || "",
|
toAddress: payload.recipients?.[0] || "",
|
||||||
from: emailData.from,
|
from: emailData.from,
|
||||||
@@ -98,4 +125,5 @@ export async function handleForwardEmail(
|
|||||||
env,
|
env,
|
||||||
ctx,
|
ctx,
|
||||||
);
|
);
|
||||||
|
return ingestResultToResponse(result);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,397 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import {
|
||||||
|
processEmailContent,
|
||||||
|
extractInlineCids,
|
||||||
|
htmlToText,
|
||||||
|
extractLinks,
|
||||||
|
extractFeedLinks,
|
||||||
|
} from "./html-processor";
|
||||||
|
import type { AttachmentData } from "../types";
|
||||||
|
|
||||||
|
describe("processEmailContent — body extraction", () => {
|
||||||
|
it("extracts content inside <body> tags", () => {
|
||||||
|
const html = "<html><head></head><body><p>Hello</p></body></html>";
|
||||||
|
expect(processEmailContent(html)).toBe("<p>Hello</p>");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("handles body tag with attributes", () => {
|
||||||
|
const html = '<html><body style="margin:0"><p>Hi</p></body></html>';
|
||||||
|
expect(processEmailContent(html)).toBe("<p>Hi</p>");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns fragment unchanged when no body tags present", () => {
|
||||||
|
const fragment = "<p>Already a fragment</p>";
|
||||||
|
expect(processEmailContent(fragment)).toBe("<p>Already a fragment</p>");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("is case-insensitive for body tag matching", () => {
|
||||||
|
const html = "<HTML><BODY><p>content</p></BODY></HTML>";
|
||||||
|
expect(processEmailContent(html)).toBe("<p>content</p>");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("processEmailContent — plain text", () => {
|
||||||
|
it("wraps plain text in <pre>", () => {
|
||||||
|
const text = "Hello world\nSecond line";
|
||||||
|
const result = processEmailContent(text);
|
||||||
|
expect(result).toMatch(/^<pre /);
|
||||||
|
expect(result).toContain("Hello world\nSecond line");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("escapes < and > in plain text", () => {
|
||||||
|
const text = "Price < 10 & size > 5";
|
||||||
|
const result = processEmailContent(text);
|
||||||
|
expect(result).toContain("<");
|
||||||
|
expect(result).toContain(">");
|
||||||
|
expect(result).toContain("&");
|
||||||
|
expect(result).not.toContain("<10");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns empty string for empty input", () => {
|
||||||
|
expect(processEmailContent("")).toBe("");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("processEmailContent — dangerous element removal", () => {
|
||||||
|
it("removes <script> tags", () => {
|
||||||
|
const html = "<body><p>Hello</p><script>alert('xss')</script></body>";
|
||||||
|
const result = processEmailContent(html);
|
||||||
|
expect(result).not.toContain("<script");
|
||||||
|
expect(result).not.toContain("alert");
|
||||||
|
expect(result).toContain("<p>Hello</p>");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("removes <iframe> tags", () => {
|
||||||
|
const html =
|
||||||
|
"<body><iframe src='https://evil.com'></iframe><p>ok</p></body>";
|
||||||
|
const result = processEmailContent(html);
|
||||||
|
expect(result).not.toContain("<iframe");
|
||||||
|
expect(result).toContain("<p>ok</p>");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("removes <object> and <embed> tags", () => {
|
||||||
|
const html = "<body><object></object><embed src='x'/><p>ok</p></body>";
|
||||||
|
const result = processEmailContent(html);
|
||||||
|
expect(result).not.toContain("<object");
|
||||||
|
expect(result).not.toContain("<embed");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("processEmailContent — attribute sanitization", () => {
|
||||||
|
it("removes event handler attributes", () => {
|
||||||
|
const html =
|
||||||
|
"<body><a href='https://x.com' onclick='evil()'>link</a></body>";
|
||||||
|
const result = processEmailContent(html);
|
||||||
|
expect(result).not.toContain("onclick");
|
||||||
|
expect(result).toContain('href="https://x.com"');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("removes onerror on images", () => {
|
||||||
|
const html = "<body><img src='x' onerror='evil()' /></body>";
|
||||||
|
const result = processEmailContent(html);
|
||||||
|
expect(result).not.toContain("onerror");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("removes javascript: hrefs", () => {
|
||||||
|
const html = "<body><a href='javascript:evil()'>click</a></body>";
|
||||||
|
const result = processEmailContent(html);
|
||||||
|
expect(result).not.toContain("javascript:");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("preserves legitimate href and src attributes", () => {
|
||||||
|
const html =
|
||||||
|
"<body><a href='https://example.com'>link</a><img src='https://example.com/img.png'/></body>";
|
||||||
|
const result = processEmailContent(html);
|
||||||
|
expect(result).toContain("https://example.com");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("processEmailContent — mso style cleanup", () => {
|
||||||
|
it("strips mso-* properties from inline styles", () => {
|
||||||
|
const html =
|
||||||
|
'<body><p style="mso-margin-top: 0; color: red;">text</p></body>';
|
||||||
|
const result = processEmailContent(html);
|
||||||
|
expect(result).not.toContain("mso-margin-top");
|
||||||
|
expect(result).toContain("color: red");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("removes style attribute entirely when only mso properties remain", () => {
|
||||||
|
const html =
|
||||||
|
'<body><p style="mso-line-height-rule: exactly;">text</p></body>';
|
||||||
|
const result = processEmailContent(html);
|
||||||
|
expect(result).not.toContain("style=");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("preserves style attribute when non-mso properties remain", () => {
|
||||||
|
const html =
|
||||||
|
'<body><p style="mso-font-size: 12pt; font-weight: bold;">text</p></body>';
|
||||||
|
const result = processEmailContent(html);
|
||||||
|
expect(result).toContain("font-weight");
|
||||||
|
expect(result).not.toContain("mso-font-size");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("processEmailContent — inline cid: rewriting", () => {
|
||||||
|
const attachment = (
|
||||||
|
overrides: Partial<AttachmentData> = {},
|
||||||
|
): AttachmentData => ({
|
||||||
|
id: "att-123",
|
||||||
|
filename: "chicken big.png",
|
||||||
|
contentType: "image/png",
|
||||||
|
size: 100,
|
||||||
|
contentId: "ii_mpi85rqy0",
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rewrites cid: src to a relative /files URL when no baseUrl", () => {
|
||||||
|
const html = '<body><img src="cid:ii_mpi85rqy0" alt="x"/></body>';
|
||||||
|
const result = processEmailContent(html, [attachment()]);
|
||||||
|
expect(result).toContain('src="/files/att-123/chicken%20big.png"');
|
||||||
|
expect(result).not.toContain("cid:");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rewrites cid: src to an absolute URL when baseUrl is given", () => {
|
||||||
|
const html = '<body><img src="cid:ii_mpi85rqy0"/></body>';
|
||||||
|
const result = processEmailContent(
|
||||||
|
html,
|
||||||
|
[attachment()],
|
||||||
|
"https://feed.example",
|
||||||
|
);
|
||||||
|
expect(result).toContain(
|
||||||
|
'src="https://feed.example/files/att-123/chicken%20big.png"',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("matches a stored Content-ID that has angle brackets", () => {
|
||||||
|
const html = '<body><img src="cid:ii_mpi85rqy0"/></body>';
|
||||||
|
const result = processEmailContent(html, [
|
||||||
|
attachment({ contentId: "<ii_mpi85rqy0>" }),
|
||||||
|
]);
|
||||||
|
expect(result).toContain('src="/files/att-123/chicken%20big.png"');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("is case-insensitive on the cid: scheme", () => {
|
||||||
|
const html = '<body><img src="CID:ii_mpi85rqy0"/></body>';
|
||||||
|
const result = processEmailContent(html, [attachment()]);
|
||||||
|
expect(result).toContain('src="/files/att-123/chicken%20big.png"');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("leaves unknown cid references unchanged", () => {
|
||||||
|
const html = '<body><img src="cid:unknown"/></body>';
|
||||||
|
const result = processEmailContent(html, [attachment()]);
|
||||||
|
expect(result).toContain('src="cid:unknown"');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("leaves cid references unchanged when no attachments are provided", () => {
|
||||||
|
const html = '<body><img src="cid:ii_mpi85rqy0"/></body>';
|
||||||
|
const result = processEmailContent(html);
|
||||||
|
expect(result).toContain('src="cid:ii_mpi85rqy0"');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ignores attachments without a contentId", () => {
|
||||||
|
const html = '<body><img src="cid:ii_mpi85rqy0"/></body>';
|
||||||
|
const result = processEmailContent(html, [
|
||||||
|
attachment({ contentId: undefined }),
|
||||||
|
]);
|
||||||
|
expect(result).toContain('src="cid:ii_mpi85rqy0"');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not touch normal http image sources", () => {
|
||||||
|
const html = '<body><img src="https://example.com/a.png"/></body>';
|
||||||
|
const result = processEmailContent(html, [attachment()]);
|
||||||
|
expect(result).toContain('src="https://example.com/a.png"');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("processEmailContent — lazy image promotion", () => {
|
||||||
|
it("promotes data-src to src when src is missing", () => {
|
||||||
|
const html = '<body><img data-src="https://x.com/a.png"/></body>';
|
||||||
|
const result = processEmailContent(html);
|
||||||
|
expect(result).toContain('src="https://x.com/a.png"');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("promotes data-src over a data: placeholder src", () => {
|
||||||
|
const html =
|
||||||
|
'<body><img src="data:image/gif;base64,AAAA" data-src="https://x.com/a.png"/></body>';
|
||||||
|
const result = processEmailContent(html);
|
||||||
|
expect(result).toContain('src="https://x.com/a.png"');
|
||||||
|
expect(result).not.toContain("data:image/gif");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not clobber a real src with data-src", () => {
|
||||||
|
const html =
|
||||||
|
'<body><img src="https://real.com/a.png" data-src="https://lazy.com/b.png"/></body>';
|
||||||
|
const result = processEmailContent(html);
|
||||||
|
expect(result).toContain('src="https://real.com/a.png"');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("promotes data-srcset when srcset is absent", () => {
|
||||||
|
const html = '<body><img data-srcset="https://x.com/a.png 2x"/></body>';
|
||||||
|
const result = processEmailContent(html);
|
||||||
|
expect(result).toContain('srcset="https://x.com/a.png 2x"');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("strips loading=lazy", () => {
|
||||||
|
const html = '<body><img src="https://x.com/a.png" loading="lazy"/></body>';
|
||||||
|
const result = processEmailContent(html);
|
||||||
|
expect(result).not.toContain("loading");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("processEmailContent — relative URL absolutization", () => {
|
||||||
|
const base = "https://news.example.com/";
|
||||||
|
|
||||||
|
it("absolutizes a root-relative href against the sender base", () => {
|
||||||
|
const html = '<body><a href="/path">link</a></body>';
|
||||||
|
const result = processEmailContent(html, undefined, "", base);
|
||||||
|
expect(result).toContain('href="https://news.example.com/path"');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("absolutizes a relative img src against the sender base", () => {
|
||||||
|
const html = '<body><img src="img/a.png"/></body>';
|
||||||
|
const result = processEmailContent(html, undefined, "", base);
|
||||||
|
expect(result).toContain('src="https://news.example.com/img/a.png"');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("resolves protocol-relative URLs using https", () => {
|
||||||
|
const html = '<body><img src="//cdn.example.com/a.png"/></body>';
|
||||||
|
const result = processEmailContent(html, undefined, "", base);
|
||||||
|
expect(result).toContain('src="https://cdn.example.com/a.png"');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("leaves absolute URLs unchanged", () => {
|
||||||
|
const html = '<body><a href="https://other.com/x">l</a></body>';
|
||||||
|
const result = processEmailContent(html, undefined, "", base);
|
||||||
|
expect(result).toContain('href="https://other.com/x"');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not touch relative URLs when no sender base is given", () => {
|
||||||
|
const html = '<body><a href="/path">link</a></body>';
|
||||||
|
const result = processEmailContent(html);
|
||||||
|
expect(result).toContain('href="/path"');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not absolutize mailto: or anchors", () => {
|
||||||
|
const html =
|
||||||
|
'<body><a href="mailto:x@y.com">m</a><a href="#top">t</a></body>';
|
||||||
|
const result = processEmailContent(html, undefined, "", base);
|
||||||
|
expect(result).toContain('href="mailto:x@y.com"');
|
||||||
|
expect(result).toContain('href="#top"');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("htmlToText", () => {
|
||||||
|
it("strips HTML tags", () => {
|
||||||
|
expect(htmlToText("<b>Bold</b> text")).toBe("Bold text");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("decodes HTML entities", () => {
|
||||||
|
expect(htmlToText("Tom & Jerry <3")).toBe("Tom & Jerry <3");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("collapses whitespace and trims", () => {
|
||||||
|
expect(htmlToText(" a\n\n b ")).toBe("a b");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns empty string for empty input", () => {
|
||||||
|
expect(htmlToText("")).toBe("");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("leaves plain text untouched", () => {
|
||||||
|
expect(htmlToText("Just a subject")).toBe("Just a subject");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("extractInlineCids", () => {
|
||||||
|
it("collects normalized cids referenced by cid: image sources", () => {
|
||||||
|
const html = '<body><img src="cid:ii_abc"/><img src="CID:ii_def"/></body>';
|
||||||
|
expect(extractInlineCids(html)).toEqual(new Set(["ii_abc", "ii_def"]));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ignores non-cid sources", () => {
|
||||||
|
const html = '<body><img src="https://example.com/a.png"/></body>';
|
||||||
|
expect(extractInlineCids(html).size).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns an empty set for plain text", () => {
|
||||||
|
expect(extractInlineCids("just text, no html").size).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns an empty set for empty input", () => {
|
||||||
|
expect(extractInlineCids("").size).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("extractLinks", () => {
|
||||||
|
it("collects anchor href + text from HTML", () => {
|
||||||
|
const links = extractLinks(
|
||||||
|
'<p>hi <a href="https://x.example/confirm?t=1">Confirm</a> and <a href="https://x.example/home">Home</a></p>',
|
||||||
|
);
|
||||||
|
expect(links).toEqual([
|
||||||
|
{ href: "https://x.example/confirm?t=1", text: "Confirm" },
|
||||||
|
{ href: "https://x.example/home", text: "Home" },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("falls back to regex URL extraction for plain text", () => {
|
||||||
|
const links = extractLinks(
|
||||||
|
"Confirm here: https://x.example/verify/abc thanks",
|
||||||
|
);
|
||||||
|
expect(links).toEqual([
|
||||||
|
{
|
||||||
|
href: "https://x.example/verify/abc",
|
||||||
|
text: "https://x.example/verify/abc",
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns an empty array for empty content", () => {
|
||||||
|
expect(extractLinks("")).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("extractFeedLinks", () => {
|
||||||
|
it("extracts rel=alternate links that carry a type", () => {
|
||||||
|
const html = `<html><head>
|
||||||
|
<link rel="alternate" type="application/rss+xml" href="https://blog.example.com/feed.xml">
|
||||||
|
<link rel="alternate" type="application/atom+xml" href="https://blog.example.com/atom.xml">
|
||||||
|
</head><body>hi</body></html>`;
|
||||||
|
expect(extractFeedLinks(html)).toEqual([
|
||||||
|
{
|
||||||
|
href: "https://blog.example.com/feed.xml",
|
||||||
|
type: "application/rss+xml",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
href: "https://blog.example.com/atom.xml",
|
||||||
|
type: "application/atom+xml",
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ignores non-alternate rels and links without a type", () => {
|
||||||
|
const html = `<head>
|
||||||
|
<link rel="stylesheet" type="text/css" href="https://x.com/a.css">
|
||||||
|
<link rel="alternate" href="https://x.com/notype">
|
||||||
|
</head>`;
|
||||||
|
expect(extractFeedLinks(html)).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("absolutizes a relative href against the base", () => {
|
||||||
|
const html = `<head><link rel="alternate" type="application/rss+xml" href="/feed.xml"></head>`;
|
||||||
|
expect(extractFeedLinks(html, "https://blog.example.com")).toEqual([
|
||||||
|
{
|
||||||
|
href: "https://blog.example.com/feed.xml",
|
||||||
|
type: "application/rss+xml",
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("drops a relative href when no base is given", () => {
|
||||||
|
const html = `<head><link rel="alternate" type="application/rss+xml" href="/feed.xml"></head>`;
|
||||||
|
expect(extractFeedLinks(html)).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns [] for plain-text bodies", () => {
|
||||||
|
expect(extractFeedLinks("just text https://x.com/feed")).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,265 @@
|
|||||||
|
import { parseHTML } from "linkedom";
|
||||||
|
import escapeHtml from "escape-html";
|
||||||
|
import type { AttachmentData } from "../types";
|
||||||
|
|
||||||
|
type ParsedDocument = ReturnType<typeof parseHTML>["document"];
|
||||||
|
|
||||||
|
// Strip surrounding angle brackets and whitespace from a Content-ID so that a
|
||||||
|
// stored value like "<ii_mpi85rqy0>" matches an HTML reference "cid:ii_mpi85rqy0".
|
||||||
|
export function normalizeCid(
|
||||||
|
cid: string | null | undefined,
|
||||||
|
): string | undefined {
|
||||||
|
if (!cid) return undefined;
|
||||||
|
const trimmed = cid.trim().replace(/^<|>$/g, "").trim();
|
||||||
|
return trimmed || undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Collect the normalized Content-IDs referenced by `cid:` image sources in the
|
||||||
|
// email body — exactly the set rewriteCidSrc would turn into inline <img> URLs.
|
||||||
|
// Used at ingest to flag those attachments as inline (rendered in place, hidden
|
||||||
|
// from the downloadable attachment lists).
|
||||||
|
export function extractInlineCids(content: string): Set<string> {
|
||||||
|
const cids = new Set<string>();
|
||||||
|
if (!content || isPlainText(content)) return cids;
|
||||||
|
const { document } = parseHTML(content);
|
||||||
|
document.querySelectorAll("[src]").forEach((el: Element) => {
|
||||||
|
const match = (el.getAttribute("src") ?? "").match(/^\s*cid:(.+)$/i);
|
||||||
|
const cid = match ? normalizeCid(match[1]) : undefined;
|
||||||
|
if (cid) cids.add(cid);
|
||||||
|
});
|
||||||
|
return cids;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Render an HTML fragment (or already-plain string) down to plain text: strips
|
||||||
|
// tags and decodes entities. Used for feed <title>s, which must be plain text —
|
||||||
|
// raw markup/entities show literally in readers.
|
||||||
|
export function htmlToText(value: string): string {
|
||||||
|
if (!value) return "";
|
||||||
|
const { document } = parseHTML(`<body>${value}</body>`);
|
||||||
|
return (document.documentElement?.textContent ?? "")
|
||||||
|
.replace(/\s+/g, " ")
|
||||||
|
.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Collect the links from an email body for confirmation detection: anchor href +
|
||||||
|
// visible text from HTML, or a regex URL sweep for plain-text bodies. Infra owns
|
||||||
|
// the DOM parse; the domain detector receives plain tuples.
|
||||||
|
export function extractLinks(
|
||||||
|
content: string,
|
||||||
|
): { href: string; text: string }[] {
|
||||||
|
if (!content) return [];
|
||||||
|
|
||||||
|
if (isPlainText(content)) {
|
||||||
|
const urls = content.match(/https?:\/\/[^\s<>"')]+/gi) ?? [];
|
||||||
|
return urls.map((url) => ({ href: url, text: url }));
|
||||||
|
}
|
||||||
|
|
||||||
|
const { document } = parseHTML(content);
|
||||||
|
const links: { href: string; text: string }[] = [];
|
||||||
|
document.querySelectorAll("a[href]").forEach((el: Element) => {
|
||||||
|
const href = (el.getAttribute("href") ?? "").trim();
|
||||||
|
if (!href) return;
|
||||||
|
links.push({
|
||||||
|
href,
|
||||||
|
text: ((el as unknown as { textContent?: string }).textContent ?? "")
|
||||||
|
.replace(/\s+/g, " ")
|
||||||
|
.trim(),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return links;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Collect a newsletter's self-advertised feed declarations from
|
||||||
|
// <link rel="alternate" type="…"> tags. Returns raw href+type tuples; the
|
||||||
|
// domain decides which MIME types count as a feed. Relative hrefs are
|
||||||
|
// absolutized against the sender base (best-effort); only http(s) URLs survive.
|
||||||
|
// Plain-text bodies have no <link> → [].
|
||||||
|
export function extractFeedLinks(
|
||||||
|
content: string,
|
||||||
|
base = "",
|
||||||
|
): { href: string; type: string }[] {
|
||||||
|
if (!content || isPlainText(content)) return [];
|
||||||
|
|
||||||
|
const { document } = parseHTML(content);
|
||||||
|
const links: { href: string; type: string }[] = [];
|
||||||
|
document
|
||||||
|
.querySelectorAll('link[rel~="alternate"][type]')
|
||||||
|
.forEach((el: Element) => {
|
||||||
|
const type = (el.getAttribute("type") ?? "").trim();
|
||||||
|
const rawHref = (el.getAttribute("href") ?? "").trim();
|
||||||
|
if (!type || !rawHref) return;
|
||||||
|
// toAbsolute() skips already-absolute hrefs (returns null), so keep those as-is.
|
||||||
|
const href = /^https?:\/\//i.test(rawHref)
|
||||||
|
? rawHref
|
||||||
|
: (toAbsolute(rawHref, base) ?? "");
|
||||||
|
if (!/^https?:\/\//i.test(href)) return;
|
||||||
|
links.push({ href, type });
|
||||||
|
});
|
||||||
|
return links;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Newsletters frequently defer images via data-src/loading="lazy"; readers don't
|
||||||
|
// run the lazy-loader, so the image renders blank. Promote the real source.
|
||||||
|
function promoteLazyImages(document: ParsedDocument): void {
|
||||||
|
document.querySelectorAll("img").forEach((img: Element) => {
|
||||||
|
const lazySrc =
|
||||||
|
img.getAttribute("data-src") ||
|
||||||
|
img.getAttribute("data-original") ||
|
||||||
|
img.getAttribute("data-lazy-src");
|
||||||
|
if (lazySrc) {
|
||||||
|
const current = (img.getAttribute("src") ?? "").trim();
|
||||||
|
if (!current || /^data:/i.test(current)) {
|
||||||
|
img.setAttribute("src", lazySrc);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const lazySrcset = img.getAttribute("data-srcset");
|
||||||
|
if (lazySrcset && !img.getAttribute("srcset")) {
|
||||||
|
img.setAttribute("srcset", lazySrcset);
|
||||||
|
}
|
||||||
|
img.removeAttribute("loading");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve a single URL against the sender base. Returns null for values that are
|
||||||
|
// already absolute or should never be rewritten (mailto:, data:, cid:, anchors).
|
||||||
|
function toAbsolute(value: string, base: string): string | null {
|
||||||
|
const v = value.trim();
|
||||||
|
if (!v || /^(https?:|mailto:|tel:|data:|cid:|#)/i.test(v)) return null;
|
||||||
|
try {
|
||||||
|
return new URL(v, base).href;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Most readers ignore xml:base, so relative href/src in content break. Absolutize
|
||||||
|
// them against the sender's site (best-effort, derived from its email domain).
|
||||||
|
// Protocol-relative //host/x are resolved too (they pick up the base's https:).
|
||||||
|
function absolutizeUrls(document: ParsedDocument, base: string): void {
|
||||||
|
if (!base) return;
|
||||||
|
document.querySelectorAll("a[href], area[href]").forEach((el: Element) => {
|
||||||
|
const abs = toAbsolute(el.getAttribute("href") ?? "", base);
|
||||||
|
if (abs) el.setAttribute("href", abs);
|
||||||
|
});
|
||||||
|
document.querySelectorAll("img[src]").forEach((el: Element) => {
|
||||||
|
const abs = toAbsolute(el.getAttribute("src") ?? "", base);
|
||||||
|
if (abs) el.setAttribute("src", abs);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function cleanMsoStyles(style: string): string {
|
||||||
|
return style
|
||||||
|
.split(";")
|
||||||
|
.map((p) => p.trim())
|
||||||
|
.filter((p) => p && !/^mso-/i.test(p))
|
||||||
|
.join("; ");
|
||||||
|
}
|
||||||
|
|
||||||
|
function isPlainText(content: string): boolean {
|
||||||
|
return !/<[a-z][\s\S]*>/i.test(content);
|
||||||
|
}
|
||||||
|
|
||||||
|
function rewriteCidSrc(
|
||||||
|
el: Element,
|
||||||
|
cidMap: Map<string, AttachmentData>,
|
||||||
|
baseUrl: string,
|
||||||
|
): void {
|
||||||
|
const src = el.getAttribute("src") ?? "";
|
||||||
|
const match = src.match(/^\s*cid:(.+)$/i);
|
||||||
|
if (!match) return;
|
||||||
|
const attachment = cidMap.get(normalizeCid(match[1]) ?? "");
|
||||||
|
if (!attachment) return;
|
||||||
|
el.setAttribute(
|
||||||
|
"src",
|
||||||
|
`${baseUrl}/files/${attachment.id}/${encodeURIComponent(attachment.filename)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function sanitizeElement(el: Element): void {
|
||||||
|
// Snapshot attribute names before mutating (linkedom attributes is array-like)
|
||||||
|
const attrs = Array.from(
|
||||||
|
el.attributes as unknown as ArrayLike<{ name: string }>,
|
||||||
|
).map((a) => a.name);
|
||||||
|
for (const attr of attrs) {
|
||||||
|
// Remove event handlers (onclick, onerror, onload, …)
|
||||||
|
if (/^on/i.test(attr)) {
|
||||||
|
el.removeAttribute(attr);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// Remove javascript: URLs
|
||||||
|
if (["href", "src", "action"].includes(attr.toLowerCase())) {
|
||||||
|
const val = el.getAttribute(attr) ?? "";
|
||||||
|
if (/^\s*javascript:/i.test(val)) {
|
||||||
|
el.removeAttribute(attr);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Strip mso-* inline style properties (Office HTML noise)
|
||||||
|
const style = el.getAttribute("style");
|
||||||
|
if (style !== null) {
|
||||||
|
const cleaned = cleanMsoStyles(style);
|
||||||
|
if (cleaned) {
|
||||||
|
el.setAttribute("style", cleaned);
|
||||||
|
} else {
|
||||||
|
el.removeAttribute("style");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Processes email content for safe display in feeds and entry pages:
|
||||||
|
* - Detects plain text and wraps it in a <pre> block
|
||||||
|
* - Extracts the <body> fragment from full HTML documents
|
||||||
|
* - Removes dangerous elements: <script>, <iframe>, <object>, <embed>
|
||||||
|
* - Removes event handler attributes and javascript: URLs
|
||||||
|
* - Strips mso-* inline style properties (Office HTML)
|
||||||
|
* - Rewrites inline cid: image refs to the stored attachment URL. baseUrl=""
|
||||||
|
* yields relative URLs (entry page, same origin); a baseUrl yields absolute
|
||||||
|
* URLs (feeds, for external RSS readers).
|
||||||
|
* - Promotes lazy-loaded images (data-src → src, strips loading="lazy").
|
||||||
|
* - Absolutizes relative href/src against senderBaseUrl (the sender's site,
|
||||||
|
* best-effort) so links/images don't break in readers that ignore xml:base.
|
||||||
|
*/
|
||||||
|
export function processEmailContent(
|
||||||
|
content: string,
|
||||||
|
attachments?: AttachmentData[],
|
||||||
|
baseUrl = "",
|
||||||
|
senderBaseUrl = "",
|
||||||
|
): string {
|
||||||
|
if (!content) return "";
|
||||||
|
|
||||||
|
if (isPlainText(content)) {
|
||||||
|
return `<pre style="white-space: pre-wrap; word-break: break-word;">${escapeHtml(content)}</pre>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const cidMap = new Map<string, AttachmentData>();
|
||||||
|
for (const att of attachments ?? []) {
|
||||||
|
const cid = normalizeCid(att.contentId);
|
||||||
|
if (cid) cidMap.set(cid, att);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { document } = parseHTML(content);
|
||||||
|
|
||||||
|
document
|
||||||
|
.querySelectorAll("script, object, embed, iframe, frame, frameset")
|
||||||
|
.forEach((el: Element) => el.remove());
|
||||||
|
|
||||||
|
document.querySelectorAll("*").forEach((el: Element) => sanitizeElement(el));
|
||||||
|
|
||||||
|
promoteLazyImages(document);
|
||||||
|
// Absolutize first: cid: refs are skipped here (not http(s)), then rewritten
|
||||||
|
// below to our /files/ URL — which must NOT be absolutized to the sender.
|
||||||
|
absolutizeUrls(document, senderBaseUrl);
|
||||||
|
|
||||||
|
if (cidMap.size > 0) {
|
||||||
|
document
|
||||||
|
.querySelectorAll("[src]")
|
||||||
|
.forEach((el: Element) => rewriteCidSrc(el, cidMap, baseUrl));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Full documents expose a <body>; bodyless fragments are serialized directly
|
||||||
|
// so that sanitization and cid rewriting still apply to their nodes.
|
||||||
|
const body = document.querySelector("body");
|
||||||
|
return body ? body.innerHTML : document.toString();
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import { FeedConfig, EmailData } from "../types";
|
||||||
|
|
||||||
|
export interface FeedValidators {
|
||||||
|
etag: string;
|
||||||
|
lastModified: string;
|
||||||
|
maxReceivedAt: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compute HTTP cache validators (ETag + Last-Modified) for a feed.
|
||||||
|
* The ETag is derived from the feed format prefix, feedId, email count, and max
|
||||||
|
* receivedAt, making it a strong deterministic validator that changes whenever
|
||||||
|
* the feed content changes.
|
||||||
|
*/
|
||||||
|
export function computeFeedValidators(
|
||||||
|
format: "rss" | "atom",
|
||||||
|
feedId: string,
|
||||||
|
feedConfig: FeedConfig,
|
||||||
|
emails: EmailData[],
|
||||||
|
): FeedValidators {
|
||||||
|
const maxReceivedAt =
|
||||||
|
emails.length > 0
|
||||||
|
? Math.max(...emails.map((e) => e.receivedAt))
|
||||||
|
: (feedConfig.created_at ?? 0);
|
||||||
|
|
||||||
|
const hash = `${format}-${feedId}-${emails.length}-${maxReceivedAt}`;
|
||||||
|
const etag = `"${hash}"`;
|
||||||
|
const lastModified = new Date(maxReceivedAt).toUTCString();
|
||||||
|
|
||||||
|
return { etag, lastModified, maxReceivedAt };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns true if the request carries a matching conditional GET header,
|
||||||
|
* meaning a 304 Not Modified response is appropriate.
|
||||||
|
*/
|
||||||
|
export function isNotModified(
|
||||||
|
req: Request,
|
||||||
|
validators: FeedValidators,
|
||||||
|
): boolean {
|
||||||
|
const ifNoneMatch = req.headers.get("If-None-Match");
|
||||||
|
if (ifNoneMatch !== null) {
|
||||||
|
return ifNoneMatch === validators.etag;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ifModifiedSince = req.headers.get("If-Modified-Since");
|
||||||
|
if (ifModifiedSince !== null) {
|
||||||
|
const clientTime = new Date(ifModifiedSince).getTime();
|
||||||
|
return !isNaN(clientTime) && clientTime >= validators.maxReceivedAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build a 304 Not Modified response with the standard cache validator headers.
|
||||||
|
*/
|
||||||
|
export function notModifiedResponse(validators: FeedValidators): Response {
|
||||||
|
return new Response(null, {
|
||||||
|
status: 304,
|
||||||
|
headers: {
|
||||||
|
ETag: validators.etag,
|
||||||
|
"Last-Modified": validators.lastModified,
|
||||||
|
"Cache-Control": "max-age=1800",
|
||||||
|
"X-Robots-Tag": "noindex",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import { createMockEnv } from "../test/setup";
|
||||||
|
import { IconRepository } from "./icon-repository";
|
||||||
|
import type { Env } from "../types";
|
||||||
|
|
||||||
|
const mockEnv = () => createMockEnv() as unknown as Env;
|
||||||
|
|
||||||
|
describe("IconRepository", () => {
|
||||||
|
it("stores and reads favicons as text or json under the icon: key", async () => {
|
||||||
|
const repo = new IconRepository(mockEnv().EMAIL_STORAGE);
|
||||||
|
expect(await repo.getText("example.com")).toBeNull();
|
||||||
|
await repo.put("example.com", JSON.stringify({ data: null }), 60);
|
||||||
|
expect(await repo.getText("example.com")).toBe('{"data":null}');
|
||||||
|
expect(await repo.getJson<{ data: null }>("example.com")).toEqual({
|
||||||
|
data: null,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import { Env } from "../types";
|
||||||
|
import { feedKeys } from "../domain/feed-keys";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* KV access for cached per-domain favicons (`icon:<domain>`). Entries may be
|
||||||
|
* positive (base64 bytes) or negative (a sentinel marking a failed fetch), and
|
||||||
|
* always carry a TTL — the cache's sole expiry mechanism.
|
||||||
|
*/
|
||||||
|
export class IconRepository {
|
||||||
|
constructor(private readonly kv: KVNamespace) {}
|
||||||
|
|
||||||
|
static from(env: Env): IconRepository {
|
||||||
|
return new IconRepository(env.EMAIL_STORAGE);
|
||||||
|
}
|
||||||
|
|
||||||
|
getText(domain: string): Promise<string | null> {
|
||||||
|
return this.kv.get(feedKeys.icon(domain), "text");
|
||||||
|
}
|
||||||
|
|
||||||
|
async getJson<T>(domain: string): Promise<T | null> {
|
||||||
|
return (await this.kv.get(feedKeys.icon(domain), {
|
||||||
|
type: "json",
|
||||||
|
})) as T | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async put(domain: string, value: string, ttlSeconds: number): Promise<void> {
|
||||||
|
await this.kv.put(feedKeys.icon(domain), value, {
|
||||||
|
expirationTtl: ttlSeconds,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import { http, HttpResponse } from "msw";
|
||||||
|
import { server, createMockEnv } from "../test/setup";
|
||||||
|
import {
|
||||||
|
parseOneClickUnsubscribe,
|
||||||
|
sendOneClickUnsubscribe,
|
||||||
|
sendUnsubscribes,
|
||||||
|
} from "./unsubscribe";
|
||||||
|
import { getCounters } from "../application/stats";
|
||||||
|
import type { Env } from "../types";
|
||||||
|
|
||||||
|
const POST_HEADER = "List-Unsubscribe=One-Click";
|
||||||
|
|
||||||
|
describe("parseOneClickUnsubscribe", () => {
|
||||||
|
it("returns the https URL when the one-click Post header is present", () => {
|
||||||
|
expect(
|
||||||
|
parseOneClickUnsubscribe({
|
||||||
|
"list-unsubscribe": "<https://news.example.com/u?t=abc>",
|
||||||
|
"list-unsubscribe-post": POST_HEADER,
|
||||||
|
}),
|
||||||
|
).toBe("https://news.example.com/u?t=abc");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("prefers the https URL when both https and mailto are present", () => {
|
||||||
|
expect(
|
||||||
|
parseOneClickUnsubscribe({
|
||||||
|
"list-unsubscribe":
|
||||||
|
"<mailto:unsub@example.com>, <https://example.com/u/1>",
|
||||||
|
"list-unsubscribe-post": POST_HEADER,
|
||||||
|
}),
|
||||||
|
).toBe("https://example.com/u/1");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns null for a mailto-only header", () => {
|
||||||
|
expect(
|
||||||
|
parseOneClickUnsubscribe({
|
||||||
|
"list-unsubscribe": "<mailto:unsub@example.com>",
|
||||||
|
"list-unsubscribe-post": POST_HEADER,
|
||||||
|
}),
|
||||||
|
).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns null when the Post header is missing", () => {
|
||||||
|
expect(
|
||||||
|
parseOneClickUnsubscribe({
|
||||||
|
"list-unsubscribe": "<https://example.com/u/1>",
|
||||||
|
}),
|
||||||
|
).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns null when the Post header has the wrong value", () => {
|
||||||
|
expect(
|
||||||
|
parseOneClickUnsubscribe({
|
||||||
|
"list-unsubscribe": "<https://example.com/u/1>",
|
||||||
|
"list-unsubscribe-post": "List-Unsubscribe=Something",
|
||||||
|
}),
|
||||||
|
).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("matches headers and Post value case-insensitively", () => {
|
||||||
|
expect(
|
||||||
|
parseOneClickUnsubscribe({
|
||||||
|
"List-Unsubscribe": "<https://example.com/u/1>",
|
||||||
|
"List-Unsubscribe-Post": "list-unsubscribe=ONE-CLICK",
|
||||||
|
}),
|
||||||
|
).toBe("https://example.com/u/1");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ignores plaintext http URLs", () => {
|
||||||
|
expect(
|
||||||
|
parseOneClickUnsubscribe({
|
||||||
|
"list-unsubscribe": "<http://example.com/u/1>",
|
||||||
|
"list-unsubscribe-post": POST_HEADER,
|
||||||
|
}),
|
||||||
|
).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns null when there are no headers", () => {
|
||||||
|
expect(parseOneClickUnsubscribe({})).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("sendOneClickUnsubscribe", () => {
|
||||||
|
it("POSTs the one-click body and returns true on success", async () => {
|
||||||
|
let captured: { method: string; contentType: string; body: string } | null =
|
||||||
|
null;
|
||||||
|
server.use(
|
||||||
|
http.post("https://example.com/u/1", async ({ request }) => {
|
||||||
|
captured = {
|
||||||
|
method: request.method,
|
||||||
|
contentType: request.headers.get("content-type") ?? "",
|
||||||
|
body: await request.text(),
|
||||||
|
};
|
||||||
|
return HttpResponse.text("ok");
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const ok = await sendOneClickUnsubscribe("https://example.com/u/1");
|
||||||
|
|
||||||
|
expect(ok).toBe(true);
|
||||||
|
expect(captured).toEqual({
|
||||||
|
method: "POST",
|
||||||
|
contentType: "application/x-www-form-urlencoded",
|
||||||
|
body: POST_HEADER,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns false on a non-ok response", async () => {
|
||||||
|
server.use(
|
||||||
|
http.post("https://example.com/u/1", () =>
|
||||||
|
HttpResponse.text("nope", { status: 404 }),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(await sendOneClickUnsubscribe("https://example.com/u/1")).toBe(
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns false (no throw) on a network error", async () => {
|
||||||
|
server.use(
|
||||||
|
http.post("https://example.com/u/1", () => HttpResponse.error()),
|
||||||
|
);
|
||||||
|
expect(await sendOneClickUnsubscribe("https://example.com/u/1")).toBe(
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("sendUnsubscribes", () => {
|
||||||
|
it("de-dupes URLs and bumps unsubscribes_sent by the success count", async () => {
|
||||||
|
const env = createMockEnv() as unknown as Env;
|
||||||
|
let hitsOne = 0;
|
||||||
|
let hitsTwo = 0;
|
||||||
|
server.use(
|
||||||
|
http.post("https://example.com/a", () => {
|
||||||
|
hitsOne += 1;
|
||||||
|
return HttpResponse.text("ok");
|
||||||
|
}),
|
||||||
|
http.post("https://example.com/b", () => {
|
||||||
|
hitsTwo += 1;
|
||||||
|
return HttpResponse.text("ok");
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await sendUnsubscribes(
|
||||||
|
[
|
||||||
|
"https://example.com/a",
|
||||||
|
"https://example.com/a",
|
||||||
|
"https://example.com/b",
|
||||||
|
],
|
||||||
|
env,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(hitsOne).toBe(1);
|
||||||
|
expect(hitsTwo).toBe(1);
|
||||||
|
const counters = await getCounters(env.EMAIL_STORAGE);
|
||||||
|
expect(counters.unsubscribes_sent).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("only counts successful requests", async () => {
|
||||||
|
const env = createMockEnv() as unknown as Env;
|
||||||
|
server.use(
|
||||||
|
http.post("https://example.com/ok", () => HttpResponse.text("ok")),
|
||||||
|
http.post("https://example.com/bad", () =>
|
||||||
|
HttpResponse.text("no", { status: 500 }),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
await sendUnsubscribes(
|
||||||
|
["https://example.com/ok", "https://example.com/bad"],
|
||||||
|
env,
|
||||||
|
);
|
||||||
|
|
||||||
|
const counters = await getCounters(env.EMAIL_STORAGE);
|
||||||
|
expect(counters.unsubscribes_sent).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does nothing for an empty list", async () => {
|
||||||
|
const env = createMockEnv() as unknown as Env;
|
||||||
|
await sendUnsubscribes([], env);
|
||||||
|
const counters = await getCounters(env.EMAIL_STORAGE);
|
||||||
|
expect(counters.unsubscribes_sent).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import { Env } from "../types";
|
||||||
|
import { UNSUBSCRIBE_TIMEOUT_MS } from "../config/constants";
|
||||||
|
import { bumpCounters } from "../application/stats";
|
||||||
|
import { logger } from "../infrastructure/logger";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extract a one-click unsubscribe URL from a stored email's headers per
|
||||||
|
* RFC 8058. Returns the first `https:` URL in `List-Unsubscribe` only when
|
||||||
|
* `List-Unsubscribe-Post: List-Unsubscribe=One-Click` is also present — that
|
||||||
|
* Post header is what authorises an unattended one-click POST. `mailto:` and
|
||||||
|
* plaintext `http:` links are ignored (Workers cannot send SMTP and we never
|
||||||
|
* unsubscribe over plaintext). Header keys are matched case-insensitively;
|
||||||
|
* `EmailData.headers` already lowercases them, but we don't rely on it.
|
||||||
|
*/
|
||||||
|
export function parseOneClickUnsubscribe(
|
||||||
|
headers: Record<string, string>,
|
||||||
|
): string | null {
|
||||||
|
let listUnsubscribe = "";
|
||||||
|
let post = "";
|
||||||
|
for (const [key, value] of Object.entries(headers)) {
|
||||||
|
const k = key.toLowerCase();
|
||||||
|
if (k === "list-unsubscribe") listUnsubscribe = value;
|
||||||
|
else if (k === "list-unsubscribe-post") post = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (post.trim().toLowerCase() !== "list-unsubscribe=one-click") return null;
|
||||||
|
|
||||||
|
const matches = listUnsubscribe.match(/<([^>]+)>/g);
|
||||||
|
if (!matches) return null;
|
||||||
|
for (const token of matches) {
|
||||||
|
const url = token.slice(1, -1).trim();
|
||||||
|
if (/^https:\/\//i.test(url)) return url;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fire a single RFC 8058 one-click unsubscribe POST. Returns whether the
|
||||||
|
* endpoint accepted it. Never throws: network/timeout errors are logged and
|
||||||
|
* reported as a failure so callers can keep going.
|
||||||
|
*/
|
||||||
|
export async function sendOneClickUnsubscribe(url: string): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
const res = await fetch(url, {
|
||||||
|
method: "POST",
|
||||||
|
redirect: "follow",
|
||||||
|
signal: AbortSignal.timeout(UNSUBSCRIBE_TIMEOUT_MS),
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/x-www-form-urlencoded",
|
||||||
|
"User-Agent": "kill-the-news/1.0",
|
||||||
|
},
|
||||||
|
body: "List-Unsubscribe=One-Click",
|
||||||
|
});
|
||||||
|
return res.ok;
|
||||||
|
} catch (error) {
|
||||||
|
logger.warn("One-click unsubscribe failed", { url, error: String(error) });
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send one-click unsubscribe requests for a batch of URLs (de-duplicated) and
|
||||||
|
* record the number that succeeded in the `unsubscribes_sent` counter. Never
|
||||||
|
* throws — intended to run in the background via ctx.waitUntil on feed deletion.
|
||||||
|
*/
|
||||||
|
export async function sendUnsubscribes(
|
||||||
|
urls: string[],
|
||||||
|
env: Env,
|
||||||
|
): Promise<void> {
|
||||||
|
const unique = Array.from(new Set(urls.filter(Boolean)));
|
||||||
|
if (unique.length === 0) return;
|
||||||
|
|
||||||
|
const results = await Promise.allSettled(
|
||||||
|
unique.map((url) => sendOneClickUnsubscribe(url)),
|
||||||
|
);
|
||||||
|
const succeeded = results.filter(
|
||||||
|
(r) => r.status === "fulfilled" && r.value,
|
||||||
|
).length;
|
||||||
|
|
||||||
|
if (succeeded > 0) {
|
||||||
|
await bumpCounters(env.EMAIL_STORAGE, { unsubscribes_sent: succeeded });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import {
|
||||||
|
feedRssUrl,
|
||||||
|
feedAtomUrl,
|
||||||
|
feedJsonUrl,
|
||||||
|
feedFormatUrl,
|
||||||
|
feedValidatorUrl,
|
||||||
|
} from "./urls";
|
||||||
|
import { Env } from "../types";
|
||||||
|
|
||||||
|
const env = { DOMAIN: "getmynews.app" } as Env;
|
||||||
|
const feedId = "gAf6wiKyanpppcKX9o3B_Q";
|
||||||
|
|
||||||
|
describe("feed URL builders", () => {
|
||||||
|
it("builds RSS/Atom/JSON feed URLs", () => {
|
||||||
|
expect(feedRssUrl(feedId, env)).toBe(
|
||||||
|
"https://getmynews.app/rss/gAf6wiKyanpppcKX9o3B_Q",
|
||||||
|
);
|
||||||
|
expect(feedAtomUrl(feedId, env)).toBe(
|
||||||
|
"https://getmynews.app/atom/gAf6wiKyanpppcKX9o3B_Q",
|
||||||
|
);
|
||||||
|
expect(feedJsonUrl(feedId, env)).toBe(
|
||||||
|
"https://getmynews.app/json/gAf6wiKyanpppcKX9o3B_Q",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("resolves a format to its feed URL", () => {
|
||||||
|
expect(feedFormatUrl("rss", feedId, env)).toBe(feedRssUrl(feedId, env));
|
||||||
|
expect(feedFormatUrl("atom", feedId, env)).toBe(feedAtomUrl(feedId, env));
|
||||||
|
expect(feedFormatUrl("json", feedId, env)).toBe(feedJsonUrl(feedId, env));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("feedValidatorUrl", () => {
|
||||||
|
it("points JSON feeds at validator.jsonfeed.org with the encoded feed URL", () => {
|
||||||
|
expect(feedValidatorUrl("json", feedId, env)).toBe(
|
||||||
|
"https://validator.jsonfeed.org/?url=" +
|
||||||
|
encodeURIComponent(feedJsonUrl(feedId, env)),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("points RSS and Atom feeds at the W3C feed validator", () => {
|
||||||
|
expect(feedValidatorUrl("rss", feedId, env)).toBe(
|
||||||
|
"https://validator.w3.org/feed/check.cgi?url=" +
|
||||||
|
encodeURIComponent(feedRssUrl(feedId, env)),
|
||||||
|
);
|
||||||
|
expect(feedValidatorUrl("atom", feedId, env)).toBe(
|
||||||
|
"https://validator.w3.org/feed/check.cgi?url=" +
|
||||||
|
encodeURIComponent(feedAtomUrl(feedId, env)),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("percent-encodes the feed URL so the validator query is well-formed", () => {
|
||||||
|
const url = feedValidatorUrl("json", feedId, env);
|
||||||
|
expect(url).toContain("https%3A%2F%2Fgetmynews.app%2Fjson%2F");
|
||||||
|
expect(url).not.toContain("?url=https://");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import { Env } from "../types";
|
||||||
|
import { MailboxId } from "../domain/value-objects/mailbox-id";
|
||||||
|
|
||||||
|
export function baseUrl(env: Env): string {
|
||||||
|
return `https://${env.DOMAIN}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function feedRssUrl(feedId: string, env: Env): string {
|
||||||
|
return `${baseUrl(env)}/rss/${feedId}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function feedAtomUrl(feedId: string, env: Env): string {
|
||||||
|
return `${baseUrl(env)}/atom/${feedId}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function feedJsonUrl(feedId: string, env: Env): string {
|
||||||
|
return `${baseUrl(env)}/json/${feedId}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Path of an email's public HTML view. The single source of truth for the
|
||||||
|
* `/entries/:feedId/:entryId` route shape (entryId = the email's receivedAt). */
|
||||||
|
export function entryPath(feedId: string, receivedAt: number): string {
|
||||||
|
return `/entries/${feedId}/${receivedAt}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function feedUrl(
|
||||||
|
format: "rss" | "atom",
|
||||||
|
feedId: string,
|
||||||
|
env: Env,
|
||||||
|
): string {
|
||||||
|
return format === "rss" ? feedRssUrl(feedId, env) : feedAtomUrl(feedId, env);
|
||||||
|
}
|
||||||
|
|
||||||
|
export type FeedFormat = "rss" | "atom" | "json";
|
||||||
|
|
||||||
|
export function feedFormatUrl(
|
||||||
|
format: FeedFormat,
|
||||||
|
feedId: string,
|
||||||
|
env: Env,
|
||||||
|
): string {
|
||||||
|
if (format === "atom") return feedAtomUrl(feedId, env);
|
||||||
|
if (format === "json") return feedJsonUrl(feedId, env);
|
||||||
|
return feedRssUrl(feedId, env);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Link to a third-party validator for the public feed URL: the W3C Feed
|
||||||
|
* Validator for RSS/Atom, validator.jsonfeed.org for JSON Feed. Used in the
|
||||||
|
* admin UI so an operator can confirm a feed parses in real readers.
|
||||||
|
*/
|
||||||
|
export function feedValidatorUrl(
|
||||||
|
format: FeedFormat,
|
||||||
|
feedId: string,
|
||||||
|
env: Env,
|
||||||
|
): string {
|
||||||
|
const encoded = encodeURIComponent(feedFormatUrl(format, feedId, env));
|
||||||
|
return format === "json"
|
||||||
|
? `https://validator.jsonfeed.org/?url=${encoded}`
|
||||||
|
: `https://validator.w3.org/feed/check.cgi?url=${encoded}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function feedEmailAddress(mailboxId: string, env: Env): string {
|
||||||
|
// The mailbox→address shape lives on the VO; this edge only resolves the domain.
|
||||||
|
return MailboxId.unchecked(mailboxId).emailAddress(
|
||||||
|
env.EMAIL_DOMAIN ?? env.DOMAIN,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function feedTopicPattern(env: Env): RegExp {
|
||||||
|
const escaped = env.DOMAIN.replaceAll(".", "\\.");
|
||||||
|
return new RegExp(`^https://${escaped}/(rss|atom)/([^/]+)$`);
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import { createMockEnv } from "../test/setup";
|
||||||
|
import { WebSubSubscriptionRepository } from "./websub-subscription-repository";
|
||||||
|
import { FeedId } from "../domain/value-objects/feed-id";
|
||||||
|
import type { Env, WebSubSubscription } from "../types";
|
||||||
|
|
||||||
|
const mockEnv = () => createMockEnv() as unknown as Env;
|
||||||
|
const fid = FeedId.unchecked("a.b.42");
|
||||||
|
|
||||||
|
describe("WebSubSubscriptionRepository", () => {
|
||||||
|
it("round-trips subscriptions and counts feeds with subscribers", async () => {
|
||||||
|
const repo = new WebSubSubscriptionRepository(mockEnv().EMAIL_STORAGE);
|
||||||
|
expect(await repo.get(fid)).toEqual([]);
|
||||||
|
const subs: WebSubSubscription[] = [
|
||||||
|
{ callbackUrl: "https://r.example/cb", expiresAt: 9999 },
|
||||||
|
];
|
||||||
|
await repo.save(fid, subs);
|
||||||
|
expect(await repo.get(fid)).toEqual(subs);
|
||||||
|
expect(await repo.countKeys()).toBe(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { Env, WebSubSubscription } from "../types";
|
||||||
|
import { feedKeys } from "../domain/feed-keys";
|
||||||
|
import { FeedId } from "../domain/value-objects/feed-id";
|
||||||
|
import { logger } from "./logger";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* KV access for per-feed WebSub subscriber lists (`websub:subs:<feedId>`).
|
||||||
|
*/
|
||||||
|
export class WebSubSubscriptionRepository {
|
||||||
|
constructor(private readonly kv: KVNamespace) {}
|
||||||
|
|
||||||
|
static from(env: Env): WebSubSubscriptionRepository {
|
||||||
|
return new WebSubSubscriptionRepository(env.EMAIL_STORAGE);
|
||||||
|
}
|
||||||
|
|
||||||
|
async get(feedId: FeedId): Promise<WebSubSubscription[]> {
|
||||||
|
const raw = await this.kv.get(feedKeys.websub(feedId.value), "json");
|
||||||
|
return (raw as WebSubSubscription[] | null) ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
async save(
|
||||||
|
feedId: FeedId,
|
||||||
|
subscriptions: WebSubSubscription[],
|
||||||
|
): Promise<void> {
|
||||||
|
await this.kv.put(
|
||||||
|
feedKeys.websub(feedId.value),
|
||||||
|
JSON.stringify(subscriptions),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Number of feeds that currently hold at least one WebSub subscription. */
|
||||||
|
async countKeys(): Promise<number> {
|
||||||
|
const prefix = feedKeys.websubPrefix();
|
||||||
|
let total = 0;
|
||||||
|
let cursor: string | undefined;
|
||||||
|
try {
|
||||||
|
do {
|
||||||
|
const listed = await this.kv.list({ prefix, cursor, limit: 1000 });
|
||||||
|
total += listed.keys.length;
|
||||||
|
cursor = listed.list_complete ? undefined : listed.cursor;
|
||||||
|
} while (cursor);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error("Error counting subscription keys", {
|
||||||
|
error: String(error),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return total;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,11 +8,12 @@ import {
|
|||||||
notifySubscribers,
|
notifySubscribers,
|
||||||
verifyAndStoreSubscription,
|
verifyAndStoreSubscription,
|
||||||
verifyAndDeleteSubscription,
|
verifyAndDeleteSubscription,
|
||||||
subscriptionKey,
|
|
||||||
} from "./websub";
|
} from "./websub";
|
||||||
|
import { FeedId } from "../domain/value-objects/feed-id";
|
||||||
import type { Env, WebSubSubscription } from "../types";
|
import type { Env, WebSubSubscription } from "../types";
|
||||||
|
|
||||||
const mockEnv = () => createMockEnv() as unknown as Env;
|
const mockEnv = () => createMockEnv() as unknown as Env;
|
||||||
|
const fid = (value: string) => FeedId.unchecked(value);
|
||||||
|
|
||||||
describe("buildHmacSignature", () => {
|
describe("buildHmacSignature", () => {
|
||||||
it("returns sha256= prefixed hex", async () => {
|
it("returns sha256= prefixed hex", async () => {
|
||||||
@@ -36,7 +37,7 @@ describe("buildHmacSignature", () => {
|
|||||||
describe("getSubscriptions / saveSubscriptions", () => {
|
describe("getSubscriptions / saveSubscriptions", () => {
|
||||||
it("returns empty array when no subs exist", async () => {
|
it("returns empty array when no subs exist", async () => {
|
||||||
const env = mockEnv();
|
const env = mockEnv();
|
||||||
expect(await getSubscriptions("feed1", env)).toEqual([]);
|
expect(await getSubscriptions(fid("feed1"), env)).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("round-trips stored subscriptions", async () => {
|
it("round-trips stored subscriptions", async () => {
|
||||||
@@ -47,12 +48,16 @@ describe("getSubscriptions / saveSubscriptions", () => {
|
|||||||
expiresAt: Date.now() + 60000,
|
expiresAt: Date.now() + 60000,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
await saveSubscriptions("feed1", subs, env);
|
await saveSubscriptions(fid("feed1"), subs, env);
|
||||||
expect(await getSubscriptions("feed1", env)).toEqual(subs);
|
expect(await getSubscriptions(fid("feed1"), env)).toEqual(subs);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("uses the correct KV key", () => {
|
it("uses the correct KV key", async () => {
|
||||||
expect(subscriptionKey("abc")).toBe("websub:subs:abc");
|
const env = mockEnv();
|
||||||
|
await saveSubscriptions(fid("abc"), [], env);
|
||||||
|
expect(
|
||||||
|
await env.EMAIL_STORAGE.get("websub:subs:abc", { type: "json" }),
|
||||||
|
).toEqual([]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -66,7 +71,7 @@ describe("notifySubscribers", () => {
|
|||||||
return HttpResponse.text("ok");
|
return HttpResponse.text("ok");
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
await notifySubscribers("feed1", env);
|
await notifySubscribers(fid("feed1"), env);
|
||||||
expect(called).toBe(false);
|
expect(called).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -78,7 +83,7 @@ describe("notifySubscribers", () => {
|
|||||||
expiresAt: Date.now() + 60000,
|
expiresAt: Date.now() + 60000,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
await saveSubscriptions("feed1", subs, env);
|
await saveSubscriptions(fid("feed1"), subs, env);
|
||||||
let called = false;
|
let called = false;
|
||||||
server.use(
|
server.use(
|
||||||
http.post("https://reader.example/callback", () => {
|
http.post("https://reader.example/callback", () => {
|
||||||
@@ -86,7 +91,7 @@ describe("notifySubscribers", () => {
|
|||||||
return HttpResponse.text("ok");
|
return HttpResponse.text("ok");
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
await notifySubscribers("feed1", env);
|
await notifySubscribers(fid("feed1"), env);
|
||||||
expect(called).toBe(false);
|
expect(called).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -110,7 +115,7 @@ describe("notifySubscribers", () => {
|
|||||||
expiresAt: Date.now() + 60000,
|
expiresAt: Date.now() + 60000,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
await saveSubscriptions("feed1", subs, env);
|
await saveSubscriptions(fid("feed1"), subs, env);
|
||||||
|
|
||||||
let receivedBody = "";
|
let receivedBody = "";
|
||||||
let receivedContentType = "";
|
let receivedContentType = "";
|
||||||
@@ -122,7 +127,7 @@ describe("notifySubscribers", () => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
await notifySubscribers("feed1", env);
|
await notifySubscribers(fid("feed1"), env);
|
||||||
|
|
||||||
expect(receivedBody).toContain("<?xml");
|
expect(receivedBody).toContain("<?xml");
|
||||||
expect(receivedContentType).toContain("application/rss+xml");
|
expect(receivedContentType).toContain("application/rss+xml");
|
||||||
@@ -149,7 +154,7 @@ describe("notifySubscribers", () => {
|
|||||||
secret: "mysecret",
|
secret: "mysecret",
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
await saveSubscriptions("feed1", subs, env);
|
await saveSubscriptions(fid("feed1"), subs, env);
|
||||||
|
|
||||||
let receivedSig256 = "";
|
let receivedSig256 = "";
|
||||||
let receivedSig = "";
|
let receivedSig = "";
|
||||||
@@ -161,7 +166,7 @@ describe("notifySubscribers", () => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
await notifySubscribers("feed1", env);
|
await notifySubscribers(fid("feed1"), env);
|
||||||
expect(receivedSig256).toMatch(/^sha256=[0-9a-f]{64}$/);
|
expect(receivedSig256).toMatch(/^sha256=[0-9a-f]{64}$/);
|
||||||
expect(receivedSig).toBe(""); // legacy header should NOT be sent
|
expect(receivedSig).toBe(""); // legacy header should NOT be sent
|
||||||
});
|
});
|
||||||
@@ -187,7 +192,7 @@ describe("notifySubscribers", () => {
|
|||||||
format: "atom",
|
format: "atom",
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
await saveSubscriptions("feed1", subs, env);
|
await saveSubscriptions(fid("feed1"), subs, env);
|
||||||
|
|
||||||
let receivedContentType = "";
|
let receivedContentType = "";
|
||||||
let receivedLink = "";
|
let receivedLink = "";
|
||||||
@@ -199,7 +204,7 @@ describe("notifySubscribers", () => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
await notifySubscribers("feed1", env);
|
await notifySubscribers(fid("feed1"), env);
|
||||||
expect(receivedContentType).toContain("application/atom+xml");
|
expect(receivedContentType).toContain("application/atom+xml");
|
||||||
expect(receivedLink).toContain(`/atom/feed1`);
|
expect(receivedLink).toContain(`/atom/feed1`);
|
||||||
expect(receivedLink).toContain(`rel="self"`);
|
expect(receivedLink).toContain(`rel="self"`);
|
||||||
@@ -231,7 +236,7 @@ describe("notifySubscribers", () => {
|
|||||||
format: "atom",
|
format: "atom",
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
await saveSubscriptions("feed1", subs, env);
|
await saveSubscriptions(fid("feed1"), subs, env);
|
||||||
|
|
||||||
const received: Record<string, string> = {};
|
const received: Record<string, string> = {};
|
||||||
server.use(
|
server.use(
|
||||||
@@ -245,7 +250,7 @@ describe("notifySubscribers", () => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
await notifySubscribers("feed1", env);
|
await notifySubscribers(fid("feed1"), env);
|
||||||
expect(received.rss).toContain("application/rss+xml");
|
expect(received.rss).toContain("application/rss+xml");
|
||||||
expect(received.atom).toContain("application/atom+xml");
|
expect(received.atom).toContain("application/atom+xml");
|
||||||
});
|
});
|
||||||
@@ -274,7 +279,7 @@ describe("notifySubscribers", () => {
|
|||||||
expiresAt: Date.now() + 60000,
|
expiresAt: Date.now() + 60000,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
await saveSubscriptions("feed1", subs, env);
|
await saveSubscriptions(fid("feed1"), subs, env);
|
||||||
|
|
||||||
const notified: string[] = [];
|
const notified: string[] = [];
|
||||||
server.use(
|
server.use(
|
||||||
@@ -288,10 +293,10 @@ describe("notifySubscribers", () => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
await notifySubscribers("feed1", env);
|
await notifySubscribers(fid("feed1"), env);
|
||||||
expect(notified).toEqual(["active"]);
|
expect(notified).toEqual(["active"]);
|
||||||
|
|
||||||
const remaining = await getSubscriptions("feed1", env);
|
const remaining = await getSubscriptions(fid("feed1"), env);
|
||||||
expect(remaining).toHaveLength(1);
|
expect(remaining).toHaveLength(1);
|
||||||
expect(remaining[0].callbackUrl).toBe("https://active.example/callback");
|
expect(remaining[0].callbackUrl).toBe("https://active.example/callback");
|
||||||
});
|
});
|
||||||
@@ -309,7 +314,7 @@ describe("verifyAndStoreSubscription", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const result = await verifyAndStoreSubscription(
|
const result = await verifyAndStoreSubscription(
|
||||||
"feed1",
|
fid("feed1"),
|
||||||
"https://reader.example/callback",
|
"https://reader.example/callback",
|
||||||
undefined,
|
undefined,
|
||||||
86400,
|
86400,
|
||||||
@@ -318,7 +323,7 @@ describe("verifyAndStoreSubscription", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
expect(result).toBe(true);
|
expect(result).toBe(true);
|
||||||
const subs = await getSubscriptions("feed1", env);
|
const subs = await getSubscriptions(fid("feed1"), env);
|
||||||
expect(subs).toHaveLength(1);
|
expect(subs).toHaveLength(1);
|
||||||
expect(subs[0].callbackUrl).toBe("https://reader.example/callback");
|
expect(subs[0].callbackUrl).toBe("https://reader.example/callback");
|
||||||
expect(subs[0].expiresAt).toBeGreaterThan(Date.now());
|
expect(subs[0].expiresAt).toBeGreaterThan(Date.now());
|
||||||
@@ -337,7 +342,7 @@ describe("verifyAndStoreSubscription", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const result = await verifyAndStoreSubscription(
|
const result = await verifyAndStoreSubscription(
|
||||||
"feed1",
|
fid("feed1"),
|
||||||
"https://reader.example/callback",
|
"https://reader.example/callback",
|
||||||
undefined,
|
undefined,
|
||||||
86400,
|
86400,
|
||||||
@@ -347,7 +352,7 @@ describe("verifyAndStoreSubscription", () => {
|
|||||||
|
|
||||||
expect(result).toBe(true);
|
expect(result).toBe(true);
|
||||||
expect(receivedTopic).toContain("/atom/feed1");
|
expect(receivedTopic).toContain("/atom/feed1");
|
||||||
const subs = await getSubscriptions("feed1", env);
|
const subs = await getSubscriptions(fid("feed1"), env);
|
||||||
expect(subs[0].format).toBe("atom");
|
expect(subs[0].format).toBe("atom");
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -360,7 +365,7 @@ describe("verifyAndStoreSubscription", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const result = await verifyAndStoreSubscription(
|
const result = await verifyAndStoreSubscription(
|
||||||
"feed1",
|
fid("feed1"),
|
||||||
"https://reader.example/callback",
|
"https://reader.example/callback",
|
||||||
undefined,
|
undefined,
|
||||||
86400,
|
86400,
|
||||||
@@ -369,7 +374,7 @@ describe("verifyAndStoreSubscription", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
expect(result).toBe(false);
|
expect(result).toBe(false);
|
||||||
const subs = await getSubscriptions("feed1", env);
|
const subs = await getSubscriptions(fid("feed1"), env);
|
||||||
expect(subs).toHaveLength(0);
|
expect(subs).toHaveLength(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -378,7 +383,7 @@ describe("verifyAndStoreSubscription", () => {
|
|||||||
const existing: WebSubSubscription[] = [
|
const existing: WebSubSubscription[] = [
|
||||||
{ callbackUrl: "https://reader.example/callback", expiresAt: 1000 },
|
{ callbackUrl: "https://reader.example/callback", expiresAt: 1000 },
|
||||||
];
|
];
|
||||||
await saveSubscriptions("feed1", existing, env);
|
await saveSubscriptions(fid("feed1"), existing, env);
|
||||||
|
|
||||||
server.use(
|
server.use(
|
||||||
http.get("https://reader.example/callback", ({ request }) => {
|
http.get("https://reader.example/callback", ({ request }) => {
|
||||||
@@ -389,7 +394,7 @@ describe("verifyAndStoreSubscription", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const result = await verifyAndStoreSubscription(
|
const result = await verifyAndStoreSubscription(
|
||||||
"feed1",
|
fid("feed1"),
|
||||||
"https://reader.example/callback",
|
"https://reader.example/callback",
|
||||||
"newsecret",
|
"newsecret",
|
||||||
3600,
|
3600,
|
||||||
@@ -398,7 +403,7 @@ describe("verifyAndStoreSubscription", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
expect(result).toBe(true);
|
expect(result).toBe(true);
|
||||||
const subs = await getSubscriptions("feed1", env);
|
const subs = await getSubscriptions(fid("feed1"), env);
|
||||||
expect(subs).toHaveLength(1);
|
expect(subs).toHaveLength(1);
|
||||||
expect(subs[0].secret).toBe("newsecret");
|
expect(subs[0].secret).toBe("newsecret");
|
||||||
});
|
});
|
||||||
@@ -410,7 +415,7 @@ describe("verifyAndStoreSubscription", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const result = await verifyAndStoreSubscription(
|
const result = await verifyAndStoreSubscription(
|
||||||
"feed1",
|
fid("feed1"),
|
||||||
"https://reader.example/callback",
|
"https://reader.example/callback",
|
||||||
undefined,
|
undefined,
|
||||||
86400,
|
86400,
|
||||||
@@ -419,7 +424,7 @@ describe("verifyAndStoreSubscription", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
expect(result).toBe(false);
|
expect(result).toBe(false);
|
||||||
const subs = await getSubscriptions("feed1", env);
|
const subs = await getSubscriptions(fid("feed1"), env);
|
||||||
expect(subs).toHaveLength(0);
|
expect(subs).toHaveLength(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -434,7 +439,7 @@ describe("verifyAndStoreSubscription", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const result = await verifyAndStoreSubscription(
|
const result = await verifyAndStoreSubscription(
|
||||||
"feed1",
|
fid("feed1"),
|
||||||
"https://reader.example/callback",
|
"https://reader.example/callback",
|
||||||
undefined,
|
undefined,
|
||||||
86400,
|
86400,
|
||||||
@@ -443,7 +448,7 @@ describe("verifyAndStoreSubscription", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
expect(result).toBe(false);
|
expect(result).toBe(false);
|
||||||
const subs = await getSubscriptions("feed1", env);
|
const subs = await getSubscriptions(fid("feed1"), env);
|
||||||
expect(subs).toHaveLength(0);
|
expect(subs).toHaveLength(0);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -452,7 +457,7 @@ describe("verifyAndDeleteSubscription", () => {
|
|||||||
it("removes subscription and returns true when callback echoes challenge", async () => {
|
it("removes subscription and returns true when callback echoes challenge", async () => {
|
||||||
const env = mockEnv();
|
const env = mockEnv();
|
||||||
await saveSubscriptions(
|
await saveSubscriptions(
|
||||||
"feed1",
|
fid("feed1"),
|
||||||
[
|
[
|
||||||
{
|
{
|
||||||
callbackUrl: "https://reader.example/callback",
|
callbackUrl: "https://reader.example/callback",
|
||||||
@@ -471,19 +476,19 @@ describe("verifyAndDeleteSubscription", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const result = await verifyAndDeleteSubscription(
|
const result = await verifyAndDeleteSubscription(
|
||||||
"feed1",
|
fid("feed1"),
|
||||||
"https://reader.example/callback",
|
"https://reader.example/callback",
|
||||||
env,
|
env,
|
||||||
);
|
);
|
||||||
expect(result).toBe(true);
|
expect(result).toBe(true);
|
||||||
const subs = await getSubscriptions("feed1", env);
|
const subs = await getSubscriptions(fid("feed1"), env);
|
||||||
expect(subs).toHaveLength(0);
|
expect(subs).toHaveLength(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("returns false and leaves subscription intact when callback returns wrong challenge", async () => {
|
it("returns false and leaves subscription intact when callback returns wrong challenge", async () => {
|
||||||
const env = mockEnv();
|
const env = mockEnv();
|
||||||
await saveSubscriptions(
|
await saveSubscriptions(
|
||||||
"feed1",
|
fid("feed1"),
|
||||||
[
|
[
|
||||||
{
|
{
|
||||||
callbackUrl: "https://reader.example/callback",
|
callbackUrl: "https://reader.example/callback",
|
||||||
@@ -500,19 +505,19 @@ describe("verifyAndDeleteSubscription", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const result = await verifyAndDeleteSubscription(
|
const result = await verifyAndDeleteSubscription(
|
||||||
"feed1",
|
fid("feed1"),
|
||||||
"https://reader.example/callback",
|
"https://reader.example/callback",
|
||||||
env,
|
env,
|
||||||
);
|
);
|
||||||
expect(result).toBe(false);
|
expect(result).toBe(false);
|
||||||
const subs = await getSubscriptions("feed1", env);
|
const subs = await getSubscriptions(fid("feed1"), env);
|
||||||
expect(subs).toHaveLength(1);
|
expect(subs).toHaveLength(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("returns false and leaves subscription intact when callback fetch fails", async () => {
|
it("returns false and leaves subscription intact when callback fetch fails", async () => {
|
||||||
const env = mockEnv();
|
const env = mockEnv();
|
||||||
await saveSubscriptions(
|
await saveSubscriptions(
|
||||||
"feed1",
|
fid("feed1"),
|
||||||
[
|
[
|
||||||
{
|
{
|
||||||
callbackUrl: "https://reader.example/callback",
|
callbackUrl: "https://reader.example/callback",
|
||||||
@@ -527,12 +532,12 @@ describe("verifyAndDeleteSubscription", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const result = await verifyAndDeleteSubscription(
|
const result = await verifyAndDeleteSubscription(
|
||||||
"feed1",
|
fid("feed1"),
|
||||||
"https://reader.example/callback",
|
"https://reader.example/callback",
|
||||||
env,
|
env,
|
||||||
);
|
);
|
||||||
expect(result).toBe(false);
|
expect(result).toBe(false);
|
||||||
const subs = await getSubscriptions("feed1", env);
|
const subs = await getSubscriptions(fid("feed1"), env);
|
||||||
expect(subs).toHaveLength(1);
|
expect(subs).toHaveLength(1);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -1,36 +1,23 @@
|
|||||||
import {
|
import { Env, FeedConfig, EmailData, WebSubSubscription } from "../types";
|
||||||
Env,
|
|
||||||
FeedConfig,
|
|
||||||
FeedMetadata,
|
|
||||||
EmailData,
|
|
||||||
WebSubSubscription,
|
|
||||||
} from "../types";
|
|
||||||
import { generateRssFeed, generateAtomFeed } from "./feed-generator";
|
import { generateRssFeed, generateAtomFeed } from "./feed-generator";
|
||||||
import { baseUrl, feedRssUrl, feedAtomUrl, feedUrl } from "./urls";
|
import { baseUrl, feedRssUrl, feedAtomUrl, feedUrl } from "./urls";
|
||||||
|
import { FeedRepository } from "./feed-repository";
|
||||||
const KV_PREFIX = "websub:subs:";
|
import { WebSubSubscriptionRepository } from "./websub-subscription-repository";
|
||||||
|
import { FeedId } from "../domain/value-objects/feed-id";
|
||||||
export function subscriptionKey(feedId: string): string {
|
|
||||||
return `${KV_PREFIX}${feedId}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getSubscriptions(
|
export async function getSubscriptions(
|
||||||
feedId: string,
|
feedId: FeedId,
|
||||||
env: Env,
|
env: Env,
|
||||||
): Promise<WebSubSubscription[]> {
|
): Promise<WebSubSubscription[]> {
|
||||||
const raw = await env.EMAIL_STORAGE.get(subscriptionKey(feedId), "json");
|
return WebSubSubscriptionRepository.from(env).get(feedId);
|
||||||
return (raw as WebSubSubscription[] | null) ?? [];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function saveSubscriptions(
|
export async function saveSubscriptions(
|
||||||
feedId: string,
|
feedId: FeedId,
|
||||||
subscriptions: WebSubSubscription[],
|
subscriptions: WebSubSubscription[],
|
||||||
env: Env,
|
env: Env,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
await env.EMAIL_STORAGE.put(
|
await WebSubSubscriptionRepository.from(env).save(feedId, subscriptions);
|
||||||
subscriptionKey(feedId),
|
|
||||||
JSON.stringify(subscriptions),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function buildHmacSignature(
|
export async function buildHmacSignature(
|
||||||
@@ -56,34 +43,30 @@ export async function buildHmacSignature(
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function buildFeedXml(
|
async function buildFeedXml(
|
||||||
feedId: string,
|
feedId: FeedId,
|
||||||
env: Env,
|
env: Env,
|
||||||
format: "rss" | "atom" = "rss",
|
format: "rss" | "atom" = "rss",
|
||||||
): Promise<string | null> {
|
): Promise<string | null> {
|
||||||
const [rawMetadata, rawConfig] = await Promise.all([
|
const repo = FeedRepository.from(env);
|
||||||
env.EMAIL_STORAGE.get(`feed:${feedId}:metadata`, "json"),
|
const [feedMetadata, rawConfig] = await Promise.all([
|
||||||
env.EMAIL_STORAGE.get(`feed:${feedId}:config`, "json"),
|
repo.getMetadata(feedId),
|
||||||
|
repo.getConfig(feedId),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const feedMetadata = rawMetadata as FeedMetadata | null;
|
|
||||||
if (!feedMetadata) return null;
|
if (!feedMetadata) return null;
|
||||||
|
|
||||||
const base = baseUrl(env);
|
const base = baseUrl(env);
|
||||||
const feedConfig = (rawConfig as FeedConfig | null) ?? {
|
const feedConfig: FeedConfig = rawConfig ?? {
|
||||||
title: `Newsletter Feed ${feedId}`,
|
title: `Newsletter Feed ${feedId.value}`,
|
||||||
description: "Converted email newsletter",
|
description: "Converted email newsletter",
|
||||||
language: "en",
|
language: "en",
|
||||||
|
mailbox_id: "",
|
||||||
created_at: Date.now(),
|
created_at: Date.now(),
|
||||||
};
|
};
|
||||||
|
|
||||||
const emails = feedMetadata.emails.slice(0, 20);
|
const emails = feedMetadata.emails.slice(0, 20);
|
||||||
const emailsData = (
|
const emailsData = (
|
||||||
await Promise.all(
|
await Promise.all(emails.map((m) => repo.getEmail(m.key)))
|
||||||
emails.map(
|
|
||||||
(m) =>
|
|
||||||
env.EMAIL_STORAGE.get(m.key, "json") as Promise<EmailData | null>,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
).filter((d): d is EmailData => d !== null);
|
).filter((d): d is EmailData => d !== null);
|
||||||
|
|
||||||
if (format === "atom") {
|
if (format === "atom") {
|
||||||
@@ -91,15 +74,15 @@ async function buildFeedXml(
|
|||||||
feedConfig,
|
feedConfig,
|
||||||
emailsData,
|
emailsData,
|
||||||
base,
|
base,
|
||||||
feedId,
|
feedId.value,
|
||||||
feedAtomUrl(feedId, env),
|
feedAtomUrl(feedId.value, env),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return generateRssFeed(feedConfig, emailsData, base, feedId);
|
return generateRssFeed(feedConfig, emailsData, base, feedId.value);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function notifySubscribers(
|
export async function notifySubscribers(
|
||||||
feedId: string,
|
feedId: FeedId,
|
||||||
env: Env,
|
env: Env,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const subs = await getSubscriptions(feedId, env);
|
const subs = await getSubscriptions(feedId, env);
|
||||||
@@ -157,12 +140,17 @@ export async function notifySubscribers(
|
|||||||
await Promise.allSettled([
|
await Promise.allSettled([
|
||||||
...(rssFeed
|
...(rssFeed
|
||||||
? rssSubs.map((sub) =>
|
? rssSubs.map((sub) =>
|
||||||
deliver(sub, rssFeed, "application/rss+xml", `/rss/${feedId}`),
|
deliver(sub, rssFeed, "application/rss+xml", `/rss/${feedId.value}`),
|
||||||
)
|
)
|
||||||
: []),
|
: []),
|
||||||
...(atomFeed
|
...(atomFeed
|
||||||
? atomSubs.map((sub) =>
|
? atomSubs.map((sub) =>
|
||||||
deliver(sub, atomFeed, "application/atom+xml", `/atom/${feedId}`),
|
deliver(
|
||||||
|
sub,
|
||||||
|
atomFeed,
|
||||||
|
"application/atom+xml",
|
||||||
|
`/atom/${feedId.value}`,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
: []),
|
: []),
|
||||||
]);
|
]);
|
||||||
@@ -193,7 +181,7 @@ async function verifyCallback(
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function verifyAndStoreSubscription(
|
export async function verifyAndStoreSubscription(
|
||||||
feedId: string,
|
feedId: FeedId,
|
||||||
callbackUrl: string,
|
callbackUrl: string,
|
||||||
secret: string | undefined,
|
secret: string | undefined,
|
||||||
leaseSeconds: number,
|
leaseSeconds: number,
|
||||||
@@ -202,7 +190,7 @@ export async function verifyAndStoreSubscription(
|
|||||||
): Promise<boolean> {
|
): Promise<boolean> {
|
||||||
const verified = await verifyCallback(callbackUrl, {
|
const verified = await verifyCallback(callbackUrl, {
|
||||||
"hub.mode": "subscribe",
|
"hub.mode": "subscribe",
|
||||||
"hub.topic": feedUrl(format, feedId, env),
|
"hub.topic": feedUrl(format, feedId.value, env),
|
||||||
"hub.lease_seconds": String(leaseSeconds),
|
"hub.lease_seconds": String(leaseSeconds),
|
||||||
});
|
});
|
||||||
if (!verified) return false;
|
if (!verified) return false;
|
||||||
@@ -225,13 +213,13 @@ export async function verifyAndStoreSubscription(
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function verifyAndDeleteSubscription(
|
export async function verifyAndDeleteSubscription(
|
||||||
feedId: string,
|
feedId: FeedId,
|
||||||
callbackUrl: string,
|
callbackUrl: string,
|
||||||
env: Env,
|
env: Env,
|
||||||
): Promise<boolean> {
|
): Promise<boolean> {
|
||||||
const verified = await verifyCallback(callbackUrl, {
|
const verified = await verifyCallback(callbackUrl, {
|
||||||
"hub.mode": "unsubscribe",
|
"hub.mode": "unsubscribe",
|
||||||
"hub.topic": feedRssUrl(feedId, env),
|
"hub.topic": feedRssUrl(feedId.value, env),
|
||||||
});
|
});
|
||||||
if (!verified) return false;
|
if (!verified) return false;
|
||||||
|
|
||||||
@@ -1,5 +1,12 @@
|
|||||||
import { Context } from "hono";
|
import { Context } from "hono";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Schedules a fire-and-forget background task. The HTTP edge adapts this over
|
||||||
|
* `ctx.waitUntil`; the application/domain layers depend on this plain function
|
||||||
|
* type instead of Hono's `Context`.
|
||||||
|
*/
|
||||||
|
export type BackgroundScheduler = (task: Promise<unknown>) => void;
|
||||||
|
|
||||||
/** Calls ctx.waitUntil() without throwing when the ExecutionContext is absent (e.g. Node tests). */
|
/** Calls ctx.waitUntil() without throwing when the ExecutionContext is absent (e.g. Node tests). */
|
||||||
export function waitUntilSafe(c: Context, promise: Promise<unknown>): void {
|
export function waitUntilSafe(c: Context, promise: Promise<unknown>): void {
|
||||||
try {
|
try {
|
||||||
@@ -1,126 +0,0 @@
|
|||||||
import { describe, it, expect, beforeEach } from "vitest";
|
|
||||||
import "../test/setup";
|
|
||||||
import { createMockEnv } from "../test/setup";
|
|
||||||
import { handleCloudflareEmail } from "./cloudflare-email";
|
|
||||||
|
|
||||||
const VALID_FEED_ID = "apple.mountain.42";
|
|
||||||
const DOMAIN = "test.getmynews.app";
|
|
||||||
|
|
||||||
const RAW_EMAIL = [
|
|
||||||
"From: Sender Name <sender@example.com>",
|
|
||||||
`To: ${VALID_FEED_ID}@${DOMAIN}`,
|
|
||||||
"Subject: Hello World",
|
|
||||||
"Date: Thu, 01 Jan 2026 12:00:00 +0000",
|
|
||||||
"MIME-Version: 1.0",
|
|
||||||
"Content-Type: text/plain; charset=utf-8",
|
|
||||||
"",
|
|
||||||
"This is the email body.",
|
|
||||||
].join("\r\n");
|
|
||||||
|
|
||||||
function makeMessage(
|
|
||||||
overrides: Partial<{ from: string; to: string; rawText: string }> = {},
|
|
||||||
): ForwardableEmailMessage {
|
|
||||||
const rawText = overrides.rawText ?? RAW_EMAIL;
|
|
||||||
const encoder = new TextEncoder();
|
|
||||||
const bytes = encoder.encode(rawText);
|
|
||||||
const stream = new ReadableStream<Uint8Array>({
|
|
||||||
start(controller) {
|
|
||||||
controller.enqueue(bytes);
|
|
||||||
controller.close();
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
from: overrides.from ?? "sender@example.com",
|
|
||||||
to: overrides.to ?? `${VALID_FEED_ID}@${DOMAIN}`,
|
|
||||||
headers: new Headers(),
|
|
||||||
raw: stream,
|
|
||||||
rawSize: bytes.length,
|
|
||||||
forward: async () => {},
|
|
||||||
reply: async () => {},
|
|
||||||
setReject: () => {},
|
|
||||||
} as unknown as ForwardableEmailMessage;
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("handleCloudflareEmail", () => {
|
|
||||||
let env: ReturnType<typeof createMockEnv>;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
env = createMockEnv();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("stores email in KV when feed exists", async () => {
|
|
||||||
await env.EMAIL_STORAGE.put(
|
|
||||||
`feed:${VALID_FEED_ID}:config`,
|
|
||||||
JSON.stringify({}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await handleCloudflareEmail(
|
|
||||||
makeMessage(),
|
|
||||||
env as any,
|
|
||||||
{ waitUntil: () => {} } as any,
|
|
||||||
);
|
|
||||||
|
|
||||||
const metadata = await env.EMAIL_STORAGE.get(
|
|
||||||
`feed:${VALID_FEED_ID}:metadata`,
|
|
||||||
"json",
|
|
||||||
);
|
|
||||||
expect(metadata.emails).toHaveLength(1);
|
|
||||||
expect(metadata.emails[0].subject).toBe("Hello World");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("does not throw when feed does not exist", async () => {
|
|
||||||
await expect(
|
|
||||||
handleCloudflareEmail(
|
|
||||||
makeMessage(),
|
|
||||||
env as any,
|
|
||||||
{ waitUntil: () => {} } as any,
|
|
||||||
),
|
|
||||||
).resolves.toBeUndefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("does not throw when email is malformed", async () => {
|
|
||||||
const msg = makeMessage({ rawText: "not a valid email" });
|
|
||||||
await expect(
|
|
||||||
handleCloudflareEmail(msg, env as any, { waitUntil: () => {} } as any),
|
|
||||||
).resolves.toBeUndefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("uses sender from message.from for allowlist check", async () => {
|
|
||||||
await env.EMAIL_STORAGE.put(
|
|
||||||
`feed:${VALID_FEED_ID}:config`,
|
|
||||||
JSON.stringify({ allowed_senders: ["sender@example.com"] }),
|
|
||||||
);
|
|
||||||
|
|
||||||
await handleCloudflareEmail(
|
|
||||||
makeMessage(),
|
|
||||||
env as any,
|
|
||||||
{ waitUntil: () => {} } as any,
|
|
||||||
);
|
|
||||||
|
|
||||||
const metadata = await env.EMAIL_STORAGE.get(
|
|
||||||
`feed:${VALID_FEED_ID}:metadata`,
|
|
||||||
"json",
|
|
||||||
);
|
|
||||||
expect(metadata.emails).toHaveLength(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rejects email when sender is not in allowlist (stored nothing)", async () => {
|
|
||||||
await env.EMAIL_STORAGE.put(
|
|
||||||
`feed:${VALID_FEED_ID}:config`,
|
|
||||||
JSON.stringify({ allowed_senders: ["other@example.com"] }),
|
|
||||||
);
|
|
||||||
|
|
||||||
await handleCloudflareEmail(
|
|
||||||
makeMessage(),
|
|
||||||
env as any,
|
|
||||||
{ waitUntil: () => {} } as any,
|
|
||||||
);
|
|
||||||
|
|
||||||
const metadata = await env.EMAIL_STORAGE.get(
|
|
||||||
`feed:${VALID_FEED_ID}:metadata`,
|
|
||||||
"json",
|
|
||||||
);
|
|
||||||
expect(metadata).toBeNull();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
import PostalMime from "postal-mime";
|
|
||||||
import { Env } from "../types";
|
|
||||||
import { processEmail, RawAttachment } from "./email-processor";
|
|
||||||
|
|
||||||
export async function handleCloudflareEmail(
|
|
||||||
message: ForwardableEmailMessage,
|
|
||||||
env: Env,
|
|
||||||
ctx: ExecutionContext,
|
|
||||||
): Promise<void> {
|
|
||||||
try {
|
|
||||||
const email = await PostalMime.parse(message.raw);
|
|
||||||
|
|
||||||
const fromAddress = email.from?.address ?? message.from;
|
|
||||||
const from =
|
|
||||||
email.from?.name && email.from.address
|
|
||||||
? `${email.from.name} <${email.from.address}>`
|
|
||||||
: fromAddress;
|
|
||||||
|
|
||||||
const headers: Record<string, string> = {};
|
|
||||||
for (const h of email.headers) {
|
|
||||||
headers[h.key] = h.value;
|
|
||||||
}
|
|
||||||
|
|
||||||
const rawAttachments: RawAttachment[] = (email.attachments ?? [])
|
|
||||||
.filter((a) => a.content instanceof ArrayBuffer)
|
|
||||||
.map((a) => ({
|
|
||||||
filename: a.filename || "attachment",
|
|
||||||
contentType: a.mimeType || "application/octet-stream",
|
|
||||||
content: a.content as ArrayBuffer,
|
|
||||||
}));
|
|
||||||
|
|
||||||
await processEmail(
|
|
||||||
{
|
|
||||||
toAddress: message.to,
|
|
||||||
from,
|
|
||||||
senders: [message.from],
|
|
||||||
subject: email.subject ?? "(no subject)",
|
|
||||||
content: email.html ?? email.text ?? "",
|
|
||||||
receivedAt: email.date ? new Date(email.date).getTime() : Date.now(),
|
|
||||||
headers,
|
|
||||||
attachments: rawAttachments,
|
|
||||||
},
|
|
||||||
env,
|
|
||||||
ctx,
|
|
||||||
);
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error processing Cloudflare email:", error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,469 +0,0 @@
|
|||||||
import { describe, it, expect, beforeEach } from "vitest";
|
|
||||||
import "../test/setup";
|
|
||||||
import { createMockEnv, MockR2 } from "../test/setup";
|
|
||||||
import {
|
|
||||||
processEmail,
|
|
||||||
ProcessEmailInput,
|
|
||||||
RawAttachment,
|
|
||||||
} from "./email-processor";
|
|
||||||
|
|
||||||
const VALID_FEED_ID = "apple.mountain.42";
|
|
||||||
const VALID_TO = `${VALID_FEED_ID}@test.getmynews.app`;
|
|
||||||
|
|
||||||
function makeInput(
|
|
||||||
overrides: Partial<ProcessEmailInput> = {},
|
|
||||||
): ProcessEmailInput {
|
|
||||||
return {
|
|
||||||
toAddress: VALID_TO,
|
|
||||||
from: "Sender <sender@example.com>",
|
|
||||||
senders: ["sender@example.com"],
|
|
||||||
subject: "Test Subject",
|
|
||||||
content: "<p>Hello</p>",
|
|
||||||
receivedAt: 1700000000000,
|
|
||||||
...overrides,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("processEmail", () => {
|
|
||||||
let env: ReturnType<typeof createMockEnv>;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
env = createMockEnv();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns 400 when toAddress has no valid feedId", async () => {
|
|
||||||
const res = await processEmail(
|
|
||||||
makeInput({ toAddress: "invalid@domain.com" }),
|
|
||||||
env as any,
|
|
||||||
);
|
|
||||||
expect(res.status).toBe(400);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns 404 when feed does not exist", async () => {
|
|
||||||
const res = await processEmail(makeInput(), env as any);
|
|
||||||
expect(res.status).toBe(404);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns 403 when sender is not in allowlist", async () => {
|
|
||||||
await env.EMAIL_STORAGE.put(
|
|
||||||
`feed:${VALID_FEED_ID}:config`,
|
|
||||||
JSON.stringify({ allowed_senders: ["allowed@example.com"] }),
|
|
||||||
);
|
|
||||||
const res = await processEmail(
|
|
||||||
makeInput({ senders: ["other@example.com"] }),
|
|
||||||
env as any,
|
|
||||||
);
|
|
||||||
expect(res.status).toBe(403);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns 200 and stores email when sender is allowed by exact match", async () => {
|
|
||||||
await env.EMAIL_STORAGE.put(
|
|
||||||
`feed:${VALID_FEED_ID}:config`,
|
|
||||||
JSON.stringify({ allowed_senders: ["sender@example.com"] }),
|
|
||||||
);
|
|
||||||
const res = await processEmail(makeInput(), env as any);
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns 200 and stores email when sender matches by domain", async () => {
|
|
||||||
await env.EMAIL_STORAGE.put(
|
|
||||||
`feed:${VALID_FEED_ID}:config`,
|
|
||||||
JSON.stringify({ allowed_senders: ["example.com"] }),
|
|
||||||
);
|
|
||||||
const res = await processEmail(
|
|
||||||
makeInput({ senders: ["anyone@example.com"] }),
|
|
||||||
env as any,
|
|
||||||
);
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns 200 when no allowlist is set", async () => {
|
|
||||||
await env.EMAIL_STORAGE.put(
|
|
||||||
`feed:${VALID_FEED_ID}:config`,
|
|
||||||
JSON.stringify({ allowed_senders: [] }),
|
|
||||||
);
|
|
||||||
const res = await processEmail(makeInput(), env as any);
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns 403 when sender is in blocklist by exact address", async () => {
|
|
||||||
await env.EMAIL_STORAGE.put(
|
|
||||||
`feed:${VALID_FEED_ID}:config`,
|
|
||||||
JSON.stringify({ blocked_senders: ["sender@example.com"] }),
|
|
||||||
);
|
|
||||||
const res = await processEmail(makeInput(), env as any);
|
|
||||||
expect(res.status).toBe(403);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns 403 when sender is in blocklist by domain", async () => {
|
|
||||||
await env.EMAIL_STORAGE.put(
|
|
||||||
`feed:${VALID_FEED_ID}:config`,
|
|
||||||
JSON.stringify({ blocked_senders: ["example.com"] }),
|
|
||||||
);
|
|
||||||
const res = await processEmail(makeInput(), env as any);
|
|
||||||
expect(res.status).toBe(403);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns 200 when sender is not in blocklist", async () => {
|
|
||||||
await env.EMAIL_STORAGE.put(
|
|
||||||
`feed:${VALID_FEED_ID}:config`,
|
|
||||||
JSON.stringify({ blocked_senders: ["other@example.com"] }),
|
|
||||||
);
|
|
||||||
const res = await processEmail(makeInput(), env as any);
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("exact block takes precedence over domain allow", async () => {
|
|
||||||
await env.EMAIL_STORAGE.put(
|
|
||||||
`feed:${VALID_FEED_ID}:config`,
|
|
||||||
JSON.stringify({
|
|
||||||
allowed_senders: ["example.com"],
|
|
||||||
blocked_senders: ["sender@example.com"],
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
const res = await processEmail(makeInput(), env as any);
|
|
||||||
expect(res.status).toBe(403);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("exact allow overrides domain block (exception use case)", async () => {
|
|
||||||
await env.EMAIL_STORAGE.put(
|
|
||||||
`feed:${VALID_FEED_ID}:config`,
|
|
||||||
JSON.stringify({
|
|
||||||
allowed_senders: ["sender@example.com"],
|
|
||||||
blocked_senders: ["example.com"],
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
const res = await processEmail(makeInput(), env as any);
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("exact block takes precedence over exact allow", async () => {
|
|
||||||
await env.EMAIL_STORAGE.put(
|
|
||||||
`feed:${VALID_FEED_ID}:config`,
|
|
||||||
JSON.stringify({
|
|
||||||
allowed_senders: ["sender@example.com"],
|
|
||||||
blocked_senders: ["sender@example.com"],
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
const res = await processEmail(makeInput(), env as any);
|
|
||||||
expect(res.status).toBe(403);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("stores email data and updates metadata in KV", async () => {
|
|
||||||
await env.EMAIL_STORAGE.put(
|
|
||||||
`feed:${VALID_FEED_ID}:config`,
|
|
||||||
JSON.stringify({}),
|
|
||||||
);
|
|
||||||
|
|
||||||
const input = makeInput({ subject: "My Subject", content: "<b>body</b>" });
|
|
||||||
await processEmail(input, env as any);
|
|
||||||
|
|
||||||
const metadata = await env.EMAIL_STORAGE.get(
|
|
||||||
`feed:${VALID_FEED_ID}:metadata`,
|
|
||||||
"json",
|
|
||||||
);
|
|
||||||
expect(metadata.emails).toHaveLength(1);
|
|
||||||
expect(metadata.emails[0].subject).toBe("My Subject");
|
|
||||||
|
|
||||||
const emailData = await env.EMAIL_STORAGE.get(
|
|
||||||
metadata.emails[0].key,
|
|
||||||
"json",
|
|
||||||
);
|
|
||||||
expect(emailData.subject).toBe("My Subject");
|
|
||||||
expect(emailData.content).toBe("<b>body</b>");
|
|
||||||
expect(emailData.from).toBe("Sender <sender@example.com>");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("prepends to existing metadata", async () => {
|
|
||||||
await env.EMAIL_STORAGE.put(
|
|
||||||
`feed:${VALID_FEED_ID}:config`,
|
|
||||||
JSON.stringify({}),
|
|
||||||
);
|
|
||||||
await env.EMAIL_STORAGE.put(
|
|
||||||
`feed:${VALID_FEED_ID}:metadata`,
|
|
||||||
JSON.stringify({
|
|
||||||
emails: [{ key: "old-key", subject: "Old", receivedAt: 1, size: 100 }],
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await processEmail(makeInput({ subject: "New" }), env as any);
|
|
||||||
|
|
||||||
const metadata = await env.EMAIL_STORAGE.get(
|
|
||||||
`feed:${VALID_FEED_ID}:metadata`,
|
|
||||||
"json",
|
|
||||||
);
|
|
||||||
expect(metadata.emails).toHaveLength(2);
|
|
||||||
expect(metadata.emails[0].subject).toBe("New");
|
|
||||||
expect(metadata.emails[1].subject).toBe("Old");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("trims oldest emails when total size exceeds FEED_MAX_SIZE_BYTES", async () => {
|
|
||||||
await env.EMAIL_STORAGE.put(
|
|
||||||
`feed:${VALID_FEED_ID}:config`,
|
|
||||||
JSON.stringify({}),
|
|
||||||
);
|
|
||||||
|
|
||||||
const oldKey1 = `feed:${VALID_FEED_ID}:111`;
|
|
||||||
const oldKey2 = `feed:${VALID_FEED_ID}:222`;
|
|
||||||
const bigContent = "x".repeat(200);
|
|
||||||
const email1 = JSON.stringify({
|
|
||||||
subject: "Old1",
|
|
||||||
from: "a@b.com",
|
|
||||||
content: bigContent,
|
|
||||||
receivedAt: 111,
|
|
||||||
headers: {},
|
|
||||||
});
|
|
||||||
const email2 = JSON.stringify({
|
|
||||||
subject: "Old2",
|
|
||||||
from: "a@b.com",
|
|
||||||
content: bigContent,
|
|
||||||
receivedAt: 222,
|
|
||||||
headers: {},
|
|
||||||
});
|
|
||||||
await env.EMAIL_STORAGE.put(oldKey1, email1);
|
|
||||||
await env.EMAIL_STORAGE.put(oldKey2, email2);
|
|
||||||
await env.EMAIL_STORAGE.put(
|
|
||||||
`feed:${VALID_FEED_ID}:metadata`,
|
|
||||||
JSON.stringify({
|
|
||||||
emails: [
|
|
||||||
{
|
|
||||||
key: oldKey2,
|
|
||||||
subject: "Old2",
|
|
||||||
receivedAt: 222,
|
|
||||||
size: email2.length,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: oldKey1,
|
|
||||||
subject: "Old1",
|
|
||||||
receivedAt: 111,
|
|
||||||
size: email1.length,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
const tinyEnv = { ...env, FEED_MAX_SIZE_BYTES: "50" };
|
|
||||||
const res = await processEmail(
|
|
||||||
makeInput({ subject: "New" }),
|
|
||||||
tinyEnv as any,
|
|
||||||
);
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
|
|
||||||
const metadata = await env.EMAIL_STORAGE.get(
|
|
||||||
`feed:${VALID_FEED_ID}:metadata`,
|
|
||||||
"json",
|
|
||||||
);
|
|
||||||
expect(metadata.emails).toHaveLength(1);
|
|
||||||
expect(metadata.emails[0].subject).toBe("New");
|
|
||||||
|
|
||||||
const deleted1 = await env.EMAIL_STORAGE.get(oldKey1, "json");
|
|
||||||
const deleted2 = await env.EMAIL_STORAGE.get(oldKey2, "json");
|
|
||||||
expect(deleted1).toBeNull();
|
|
||||||
expect(deleted2).toBeNull();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("keeps entries within size budget untouched", async () => {
|
|
||||||
await env.EMAIL_STORAGE.put(
|
|
||||||
`feed:${VALID_FEED_ID}:config`,
|
|
||||||
JSON.stringify({}),
|
|
||||||
);
|
|
||||||
const bigEnv = { ...env, FEED_MAX_SIZE_BYTES: String(10 * 1024 * 1024) };
|
|
||||||
await processEmail(makeInput({ subject: "First" }), bigEnv as any);
|
|
||||||
await processEmail(makeInput({ subject: "Second" }), bigEnv as any);
|
|
||||||
const metadata = await env.EMAIL_STORAGE.get(
|
|
||||||
`feed:${VALID_FEED_ID}:metadata`,
|
|
||||||
"json",
|
|
||||||
);
|
|
||||||
expect(metadata.emails).toHaveLength(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("calls ctx.waitUntil with notifySubscribers when ctx is provided", async () => {
|
|
||||||
await env.EMAIL_STORAGE.put(
|
|
||||||
`feed:${VALID_FEED_ID}:config`,
|
|
||||||
JSON.stringify({
|
|
||||||
title: "Test",
|
|
||||||
language: "en",
|
|
||||||
created_at: Date.now(),
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
await env.EMAIL_STORAGE.put(
|
|
||||||
`feed:${VALID_FEED_ID}:metadata`,
|
|
||||||
JSON.stringify({ emails: [] }),
|
|
||||||
);
|
|
||||||
|
|
||||||
let waitUntilCalled = false;
|
|
||||||
const ctx = {
|
|
||||||
waitUntil: (p: Promise<unknown>) => {
|
|
||||||
waitUntilCalled = true;
|
|
||||||
void p; // don't actually await it
|
|
||||||
},
|
|
||||||
passThroughOnException: () => {},
|
|
||||||
} as unknown as ExecutionContext;
|
|
||||||
|
|
||||||
const res = await processEmail(makeInput(), env as any, ctx);
|
|
||||||
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
expect(waitUntilCalled).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("does not call ctx.waitUntil on error paths (feed not found)", async () => {
|
|
||||||
let waitUntilCalled = false;
|
|
||||||
const ctx = {
|
|
||||||
waitUntil: (p: Promise<unknown>) => {
|
|
||||||
waitUntilCalled = true;
|
|
||||||
void p;
|
|
||||||
},
|
|
||||||
passThroughOnException: () => {},
|
|
||||||
} as unknown as ExecutionContext;
|
|
||||||
|
|
||||||
// Feed ID is valid format but config doesn't exist → 404
|
|
||||||
const res = await processEmail(
|
|
||||||
makeInput({ toAddress: `no.such.99@test.getmynews.app` }),
|
|
||||||
env as any,
|
|
||||||
ctx,
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(res.status).toBe(404);
|
|
||||||
expect(waitUntilCalled).toBe(false);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("processEmail — attachments", () => {
|
|
||||||
const pdfContent = new TextEncoder().encode("PDF bytes")
|
|
||||||
.buffer as ArrayBuffer;
|
|
||||||
|
|
||||||
const pdfAttachment: RawAttachment = {
|
|
||||||
filename: "report.pdf",
|
|
||||||
contentType: "application/pdf",
|
|
||||||
content: pdfContent,
|
|
||||||
};
|
|
||||||
|
|
||||||
it("skips R2 upload when ATTACHMENT_BUCKET is not configured", async () => {
|
|
||||||
const env = createMockEnv();
|
|
||||||
await env.EMAIL_STORAGE.put(
|
|
||||||
`feed:${VALID_FEED_ID}:config`,
|
|
||||||
JSON.stringify({}),
|
|
||||||
);
|
|
||||||
const res = await processEmail(
|
|
||||||
makeInput({ attachments: [pdfAttachment] }),
|
|
||||||
env as any,
|
|
||||||
);
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
|
|
||||||
const metadata = await env.EMAIL_STORAGE.get(
|
|
||||||
`feed:${VALID_FEED_ID}:metadata`,
|
|
||||||
"json",
|
|
||||||
);
|
|
||||||
const emailData = await env.EMAIL_STORAGE.get(
|
|
||||||
metadata.emails[0].key,
|
|
||||||
"json",
|
|
||||||
);
|
|
||||||
expect(emailData.attachments).toBeUndefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("uploads attachments to R2 and stores AttachmentData in emailData", async () => {
|
|
||||||
const env = createMockEnv({ withR2: true });
|
|
||||||
const mockR2 = (env as any).ATTACHMENT_BUCKET as unknown as MockR2;
|
|
||||||
await env.EMAIL_STORAGE.put(
|
|
||||||
`feed:${VALID_FEED_ID}:config`,
|
|
||||||
JSON.stringify({}),
|
|
||||||
);
|
|
||||||
const res = await processEmail(
|
|
||||||
makeInput({ attachments: [pdfAttachment] }),
|
|
||||||
env as any,
|
|
||||||
);
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
|
|
||||||
const metadata = await env.EMAIL_STORAGE.get(
|
|
||||||
`feed:${VALID_FEED_ID}:metadata`,
|
|
||||||
"json",
|
|
||||||
);
|
|
||||||
const emailData = await env.EMAIL_STORAGE.get(
|
|
||||||
metadata.emails[0].key,
|
|
||||||
"json",
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(emailData.attachments).toHaveLength(1);
|
|
||||||
expect(emailData.attachments[0].filename).toBe("report.pdf");
|
|
||||||
expect(emailData.attachments[0].contentType).toBe("application/pdf");
|
|
||||||
expect(emailData.attachments[0].size).toBe(pdfContent.byteLength);
|
|
||||||
|
|
||||||
const id = emailData.attachments[0].id;
|
|
||||||
expect(mockR2._has(id)).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("stores attachmentIds in EmailMetadata for trim-time cleanup", async () => {
|
|
||||||
const env = createMockEnv({ withR2: true });
|
|
||||||
await env.EMAIL_STORAGE.put(
|
|
||||||
`feed:${VALID_FEED_ID}:config`,
|
|
||||||
JSON.stringify({}),
|
|
||||||
);
|
|
||||||
await processEmail(makeInput({ attachments: [pdfAttachment] }), env as any);
|
|
||||||
|
|
||||||
const metadata = await env.EMAIL_STORAGE.get(
|
|
||||||
`feed:${VALID_FEED_ID}:metadata`,
|
|
||||||
"json",
|
|
||||||
);
|
|
||||||
expect(metadata.emails[0].attachmentIds).toHaveLength(1);
|
|
||||||
expect(typeof metadata.emails[0].attachmentIds[0]).toBe("string");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("deletes R2 objects when a trimmed email had attachments", async () => {
|
|
||||||
const env = createMockEnv({ withR2: true });
|
|
||||||
const mockR2 = (env as any).ATTACHMENT_BUCKET as unknown as MockR2;
|
|
||||||
await env.EMAIL_STORAGE.put(
|
|
||||||
`feed:${VALID_FEED_ID}:config`,
|
|
||||||
JSON.stringify({}),
|
|
||||||
);
|
|
||||||
|
|
||||||
// Store an old email with attachment in KV and metadata
|
|
||||||
const oldKey = `feed:${VALID_FEED_ID}:111`;
|
|
||||||
const oldAttachmentId = "old-attachment-uuid";
|
|
||||||
const bigContent = "x".repeat(200);
|
|
||||||
const oldEmail = JSON.stringify({
|
|
||||||
subject: "Old",
|
|
||||||
from: "a@b.com",
|
|
||||||
content: bigContent,
|
|
||||||
receivedAt: 111,
|
|
||||||
headers: {},
|
|
||||||
attachments: [
|
|
||||||
{
|
|
||||||
id: oldAttachmentId,
|
|
||||||
filename: "old.pdf",
|
|
||||||
contentType: "application/pdf",
|
|
||||||
size: 100,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
await env.EMAIL_STORAGE.put(oldKey, oldEmail);
|
|
||||||
|
|
||||||
// Also put the attachment in mock R2
|
|
||||||
await mockR2.put(oldAttachmentId, new ArrayBuffer(100));
|
|
||||||
|
|
||||||
await env.EMAIL_STORAGE.put(
|
|
||||||
`feed:${VALID_FEED_ID}:metadata`,
|
|
||||||
JSON.stringify({
|
|
||||||
emails: [
|
|
||||||
{
|
|
||||||
key: oldKey,
|
|
||||||
subject: "Old",
|
|
||||||
receivedAt: 111,
|
|
||||||
size: oldEmail.length,
|
|
||||||
attachmentIds: [oldAttachmentId],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
// Process with tight size budget to force trimming
|
|
||||||
const tinyEnv = { ...env, FEED_MAX_SIZE_BYTES: "50" };
|
|
||||||
const res = await processEmail(
|
|
||||||
makeInput({ subject: "New" }),
|
|
||||||
tinyEnv as any,
|
|
||||||
);
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
|
|
||||||
// Old attachment should be deleted from R2
|
|
||||||
expect(mockR2._has(oldAttachmentId)).toBe(false);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,245 +0,0 @@
|
|||||||
import { EmailParser } from "../utils/email-parser";
|
|
||||||
import {
|
|
||||||
AttachmentData,
|
|
||||||
EmailMetadata,
|
|
||||||
Env,
|
|
||||||
FeedConfig,
|
|
||||||
FeedMetadata,
|
|
||||||
} from "../types";
|
|
||||||
import { notifySubscribers } from "../utils/websub";
|
|
||||||
import { logger } from "./logger";
|
|
||||||
import { FEED_MAX_BYTES } from "../config/constants";
|
|
||||||
|
|
||||||
export interface RawAttachment {
|
|
||||||
filename: string;
|
|
||||||
contentType: string;
|
|
||||||
content: ArrayBuffer;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ProcessEmailInput {
|
|
||||||
toAddress: string;
|
|
||||||
from: string;
|
|
||||||
senders: string[];
|
|
||||||
subject: string;
|
|
||||||
content: string;
|
|
||||||
receivedAt: number;
|
|
||||||
headers?: Record<string, string>;
|
|
||||||
attachments?: RawAttachment[];
|
|
||||||
}
|
|
||||||
|
|
||||||
type ValidationSuccess = { ok: true; feedId: string; feedConfig: FeedConfig };
|
|
||||||
type ValidationFailure = { ok: false; response: Response };
|
|
||||||
type ValidationResult = ValidationSuccess | ValidationFailure;
|
|
||||||
|
|
||||||
function normalizeEmail(value: string): string {
|
|
||||||
return value.trim().toLowerCase();
|
|
||||||
}
|
|
||||||
|
|
||||||
type SenderDecision = "blocked" | "allowed" | "neutral";
|
|
||||||
|
|
||||||
function evaluateSender(
|
|
||||||
sender: string,
|
|
||||||
allowedSenders: string[],
|
|
||||||
blockedSenders: string[],
|
|
||||||
): SenderDecision {
|
|
||||||
const normalized = normalizeEmail(sender);
|
|
||||||
const domain = normalized.split("@")[1] || "";
|
|
||||||
|
|
||||||
const normalizeDomain = (e: string) => (e.startsWith("@") ? e.slice(1) : e);
|
|
||||||
|
|
||||||
const exactBlocked = blockedSenders.filter((e) => e.includes("@"));
|
|
||||||
const exactAllowed = allowedSenders.filter((e) => e.includes("@"));
|
|
||||||
const domainBlocked = blockedSenders
|
|
||||||
.filter((e) => !e.includes("@"))
|
|
||||||
.map(normalizeDomain);
|
|
||||||
const domainAllowed = allowedSenders
|
|
||||||
.filter((e) => !e.includes("@"))
|
|
||||||
.map(normalizeDomain);
|
|
||||||
|
|
||||||
if (exactBlocked.includes(normalized)) return "blocked";
|
|
||||||
if (exactAllowed.includes(normalized)) return "allowed";
|
|
||||||
if (domain && domainBlocked.includes(domain)) return "blocked";
|
|
||||||
if (domain && domainAllowed.includes(domain)) return "allowed";
|
|
||||||
return "neutral";
|
|
||||||
}
|
|
||||||
|
|
||||||
async function uploadAttachments(
|
|
||||||
attachments: RawAttachment[],
|
|
||||||
bucket: R2Bucket,
|
|
||||||
): Promise<AttachmentData[]> {
|
|
||||||
return Promise.all(
|
|
||||||
attachments.map(async (att) => {
|
|
||||||
const id = crypto.randomUUID();
|
|
||||||
await bucket.put(id, att.content, {
|
|
||||||
httpMetadata: {
|
|
||||||
contentType: att.contentType,
|
|
||||||
contentDisposition: `attachment; filename="${att.filename}"`,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
filename: att.filename,
|
|
||||||
contentType: att.contentType,
|
|
||||||
size: att.content.byteLength,
|
|
||||||
};
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function validateEmail(
|
|
||||||
input: ProcessEmailInput,
|
|
||||||
env: Env,
|
|
||||||
): Promise<ValidationResult> {
|
|
||||||
const feedId = EmailParser.extractFeedId(input.toAddress);
|
|
||||||
if (!feedId) {
|
|
||||||
logger.error("Invalid email address format", {
|
|
||||||
toAddress: input.toAddress,
|
|
||||||
});
|
|
||||||
return {
|
|
||||||
ok: false,
|
|
||||||
response: new Response("Invalid email address format", { status: 400 }),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const feedConfig = (await env.EMAIL_STORAGE.get(
|
|
||||||
`feed:${feedId}:config`,
|
|
||||||
"json",
|
|
||||||
)) as FeedConfig | null;
|
|
||||||
if (!feedConfig) {
|
|
||||||
logger.error("Feed not found", { feedId });
|
|
||||||
return {
|
|
||||||
ok: false,
|
|
||||||
response: new Response("Feed does not exist", { status: 404 }),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const allowedSenders = (feedConfig.allowed_senders || [])
|
|
||||||
.map(normalizeEmail)
|
|
||||||
.filter(Boolean);
|
|
||||||
const blockedSenders = (feedConfig.blocked_senders || [])
|
|
||||||
.map(normalizeEmail)
|
|
||||||
.filter(Boolean);
|
|
||||||
|
|
||||||
if (allowedSenders.length > 0 || blockedSenders.length > 0) {
|
|
||||||
const hasAllowlist = allowedSenders.length > 0;
|
|
||||||
const accepted = input.senders.some((sender) => {
|
|
||||||
const decision = evaluateSender(sender, allowedSenders, blockedSenders);
|
|
||||||
if (decision === "allowed") return true;
|
|
||||||
if (decision === "blocked") return false;
|
|
||||||
return !hasAllowlist;
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!accepted) {
|
|
||||||
logger.warn("Rejected email: sender filter", {
|
|
||||||
feedId,
|
|
||||||
senders: input.senders,
|
|
||||||
allowedSenders,
|
|
||||||
blockedSenders,
|
|
||||||
});
|
|
||||||
return {
|
|
||||||
ok: false,
|
|
||||||
response: new Response("Sender not allowed for this feed", {
|
|
||||||
status: 403,
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return { ok: true, feedId, feedConfig };
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function storeEmail(
|
|
||||||
feedId: string,
|
|
||||||
input: ProcessEmailInput,
|
|
||||||
env: Env,
|
|
||||||
ctx?: ExecutionContext,
|
|
||||||
): Promise<void> {
|
|
||||||
const storedAttachments: AttachmentData[] =
|
|
||||||
env.ATTACHMENT_BUCKET && input.attachments?.length
|
|
||||||
? await uploadAttachments(input.attachments, env.ATTACHMENT_BUCKET)
|
|
||||||
: [];
|
|
||||||
|
|
||||||
const emailData = {
|
|
||||||
subject: input.subject,
|
|
||||||
from: input.from,
|
|
||||||
content: input.content,
|
|
||||||
receivedAt: input.receivedAt,
|
|
||||||
headers: input.headers ?? {},
|
|
||||||
...(storedAttachments.length > 0 ? { attachments: storedAttachments } : {}),
|
|
||||||
};
|
|
||||||
|
|
||||||
const emailKey = `feed:${feedId}:${Date.now()}`;
|
|
||||||
const feedMetadataKey = `feed:${feedId}:metadata`;
|
|
||||||
|
|
||||||
const [, rawMetadata] = await Promise.all([
|
|
||||||
env.EMAIL_STORAGE.put(emailKey, JSON.stringify(emailData)),
|
|
||||||
env.EMAIL_STORAGE.get(feedMetadataKey, "json"),
|
|
||||||
]);
|
|
||||||
|
|
||||||
// Note: KV has no atomic compare-and-swap. Concurrent invocations for the
|
|
||||||
// same feed can read stale metadata and produce orphaned KV entries or
|
|
||||||
// duplicate trim deletions. This is an accepted limitation given Cloudflare
|
|
||||||
// KV's eventual-consistency model.
|
|
||||||
// TODO: Migrate feed metadata writes to Cloudflare Durable Objects to serialise
|
|
||||||
// concurrent writes and eliminate this race condition.
|
|
||||||
const feedMetadata = ((rawMetadata as FeedMetadata | null) || {
|
|
||||||
emails: [],
|
|
||||||
}) as FeedMetadata;
|
|
||||||
|
|
||||||
const maxBytes =
|
|
||||||
parseInt(env.FEED_MAX_SIZE_BYTES ?? "", 10) || FEED_MAX_BYTES;
|
|
||||||
|
|
||||||
const serialised = JSON.stringify(emailData);
|
|
||||||
const serialisedSize = new TextEncoder().encode(serialised).byteLength;
|
|
||||||
const newEntry: EmailMetadata = {
|
|
||||||
key: emailKey,
|
|
||||||
subject: emailData.subject,
|
|
||||||
receivedAt: emailData.receivedAt,
|
|
||||||
size: serialisedSize,
|
|
||||||
...(storedAttachments.length > 0
|
|
||||||
? { attachmentIds: storedAttachments.map((a) => a.id) }
|
|
||||||
: {}),
|
|
||||||
};
|
|
||||||
feedMetadata.emails.unshift(newEntry);
|
|
||||||
|
|
||||||
let totalSize = feedMetadata.emails.reduce(
|
|
||||||
(sum, e) => sum + (e.size ?? 0),
|
|
||||||
0,
|
|
||||||
);
|
|
||||||
const toDelete: EmailMetadata[] = [];
|
|
||||||
while (totalSize > maxBytes && feedMetadata.emails.length > 1) {
|
|
||||||
const dropped = feedMetadata.emails.pop()!;
|
|
||||||
totalSize -= dropped.size ?? 0;
|
|
||||||
toDelete.push(dropped);
|
|
||||||
}
|
|
||||||
|
|
||||||
const r2Deletions =
|
|
||||||
env.ATTACHMENT_BUCKET && toDelete.length > 0
|
|
||||||
? toDelete
|
|
||||||
.flatMap((e) => e.attachmentIds ?? [])
|
|
||||||
.map((id) => env.ATTACHMENT_BUCKET!.delete(id))
|
|
||||||
: [];
|
|
||||||
|
|
||||||
await Promise.all([
|
|
||||||
env.EMAIL_STORAGE.put(feedMetadataKey, JSON.stringify(feedMetadata)),
|
|
||||||
...toDelete.map((e) => env.EMAIL_STORAGE.delete(e.key)),
|
|
||||||
...r2Deletions,
|
|
||||||
]);
|
|
||||||
|
|
||||||
logger.info("Email processed", { feedId });
|
|
||||||
if (ctx) {
|
|
||||||
ctx.waitUntil(notifySubscribers(feedId, env));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function processEmail(
|
|
||||||
input: ProcessEmailInput,
|
|
||||||
env: Env,
|
|
||||||
ctx?: ExecutionContext,
|
|
||||||
): Promise<Response> {
|
|
||||||
const validation = await validateEmail(input, env);
|
|
||||||
if (!validation.ok) return validation.response;
|
|
||||||
|
|
||||||
await storeEmail(validation.feedId, input, env, ctx);
|
|
||||||
return new Response("Email processed successfully", { status: 200 });
|
|
||||||
}
|
|
||||||
+988
-3
File diff suppressed because it is too large
Load Diff
+232
-230
@@ -2,15 +2,26 @@ import { Context, Hono } from "hono";
|
|||||||
import { deleteCookie, getSignedCookie, setSignedCookie } from "hono/cookie";
|
import { deleteCookie, getSignedCookie, setSignedCookie } from "hono/cookie";
|
||||||
import { zValidator } from "@hono/zod-validator";
|
import { zValidator } from "@hono/zod-validator";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { Env, FeedConfig } from "../types";
|
import { Env } from "../types";
|
||||||
import { csrf } from "hono/csrf";
|
import { csrf } from "hono/csrf";
|
||||||
import { ADMIN_COOKIE_MAX_AGE } from "../config/constants";
|
import { ADMIN_COOKIE_MAX_AGE } from "../config/constants";
|
||||||
import { logger } from "../lib/logger";
|
import { logger } from "../infrastructure/logger";
|
||||||
import { Layout, clampText } from "./admin/ui";
|
import { timingSafeEqual, checkProxyAuth } from "../infrastructure/auth";
|
||||||
import { listAllFeeds, updateFeedInList } from "./admin/helpers";
|
import {
|
||||||
import { feedRssUrl, feedAtomUrl, feedEmailAddress } from "../utils/urls";
|
Layout,
|
||||||
|
clampText,
|
||||||
|
CopyIcon,
|
||||||
|
CheckIcon,
|
||||||
|
FeedFormats,
|
||||||
|
ExpiryBadge,
|
||||||
|
} from "./admin/ui";
|
||||||
|
import { FeedRepository } from "../infrastructure/feed-repository";
|
||||||
|
import { FeedId } from "../domain/value-objects/feed-id";
|
||||||
|
import { editFeedDetails } from "../application/feed-service";
|
||||||
|
import { feedEmailAddress } from "../infrastructure/urls";
|
||||||
import { feedsRouter } from "./admin/feeds";
|
import { feedsRouter } from "./admin/feeds";
|
||||||
import { emailsRouter } from "./admin/emails";
|
import { emailsRouter } from "./admin/emails";
|
||||||
|
import { handleOpml } from "./opml";
|
||||||
import { dashboardScript } from "../scripts/generated/dashboard";
|
import { dashboardScript } from "../scripts/generated/dashboard";
|
||||||
|
|
||||||
type AppEnv = { Bindings: Env };
|
type AppEnv = { Bindings: Env };
|
||||||
@@ -37,27 +48,6 @@ app.use("*", async (c, next) => {
|
|||||||
await next();
|
await next();
|
||||||
});
|
});
|
||||||
|
|
||||||
function timingSafeEqual(a: string, b: string): boolean {
|
|
||||||
const enc = new TextEncoder();
|
|
||||||
const aBytes = enc.encode(a);
|
|
||||||
const bBytes = enc.encode(b);
|
|
||||||
// Try native timing-safe implementation first (Cloudflare Workers runtime)
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
const subtle = crypto.subtle as any;
|
|
||||||
if (typeof subtle.timingSafeEqual === "function") {
|
|
||||||
if (aBytes.length !== bBytes.length) return false;
|
|
||||||
return subtle.timingSafeEqual(aBytes, bBytes);
|
|
||||||
}
|
|
||||||
// Constant-time fallback for Node (test environment): encode length
|
|
||||||
// mismatch into `diff` so the loop always runs over the full length.
|
|
||||||
const len = Math.max(aBytes.length, bBytes.length);
|
|
||||||
let diff = aBytes.length ^ bBytes.length;
|
|
||||||
for (let i = 0; i < len; i++) {
|
|
||||||
diff |= (aBytes[i] ?? 0) ^ (bBytes[i] ?? 0);
|
|
||||||
}
|
|
||||||
return diff === 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Authentication middleware for admin routes
|
// Authentication middleware for admin routes
|
||||||
async function authMiddleware(c: Context, next: () => Promise<void>) {
|
async function authMiddleware(c: Context, next: () => Promise<void>) {
|
||||||
const env = c.env;
|
const env = c.env;
|
||||||
@@ -69,22 +59,8 @@ async function authMiddleware(c: Context, next: () => Promise<void>) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Proxy auth: only active when both env vars are present
|
// Proxy auth: only active when both env vars are present
|
||||||
if (env.PROXY_AUTH_SECRET && env.PROXY_TRUSTED_IPS) {
|
if (checkProxyAuth(c, env)) {
|
||||||
const trustedIps = env.PROXY_TRUSTED_IPS.split(",")
|
return next();
|
||||||
.map((s: string) => s.trim())
|
|
||||||
.filter(Boolean);
|
|
||||||
const clientIp = c.req.header("CF-Connecting-IP") ?? "";
|
|
||||||
const providedSecret = c.req.header("X-Auth-Proxy-Secret") ?? "";
|
|
||||||
const remoteUser =
|
|
||||||
c.req.header("Remote-User") || c.req.header("X-Forwarded-User") || "";
|
|
||||||
|
|
||||||
if (
|
|
||||||
trustedIps.includes(clientIp) &&
|
|
||||||
timingSafeEqual(providedSecret, env.PROXY_AUTH_SECRET) &&
|
|
||||||
remoteUser.length > 0
|
|
||||||
) {
|
|
||||||
return next();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fallback: signed cookie
|
// Fallback: signed cookie
|
||||||
@@ -145,7 +121,12 @@ app.get("/login", (c) => {
|
|||||||
fill="none"
|
fill="none"
|
||||||
xmlns="http://www.w3.org/2000/svg"
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
>
|
>
|
||||||
<rect width="24" height="24" rx="12" fill="var(--color-primary)" />
|
<rect
|
||||||
|
width="24"
|
||||||
|
height="24"
|
||||||
|
rx="12"
|
||||||
|
fill="var(--color-primary)"
|
||||||
|
/>
|
||||||
<path
|
<path
|
||||||
d="M17 9C17 7.89543 16.1046 7 15 7H9C7.89543 7 7 7.89543 7 9V15C7 16.1046 7.89543 17 9 17H15C16.1046 17 17 16.1046 17 15V9Z"
|
d="M17 9C17 7.89543 16.1046 7 15 7H9C7.89543 7 7 7.89543 7 9V15C7 16.1046 7.89543 17 9 17H15C16.1046 17 17 16.1046 17 15V9Z"
|
||||||
stroke="white"
|
stroke="white"
|
||||||
@@ -161,9 +142,7 @@ app.get("/login", (c) => {
|
|||||||
</svg>
|
</svg>
|
||||||
</div>
|
</div>
|
||||||
<h1 class="auth-title">kill-the-news</h1>
|
<h1 class="auth-title">kill-the-news</h1>
|
||||||
{errorMessage && (
|
{errorMessage && <div class="auth-error">{errorMessage}</div>}
|
||||||
<div class="auth-error">{errorMessage}</div>
|
|
||||||
)}
|
|
||||||
<form class="auth-form" action="/admin/login" method="post">
|
<form class="auth-form" action="/admin/login" method="post">
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label for="password">Password</label>
|
<label for="password">Password</label>
|
||||||
@@ -225,41 +204,6 @@ app.get("/logout", (c) => {
|
|||||||
// dashboardScript is compiled from src/scripts/client/dashboard.ts via `npm run build:client`.
|
// dashboardScript is compiled from src/scripts/client/dashboard.ts via `npm run build:client`.
|
||||||
// It is imported from src/scripts/generated/dashboard.ts above.
|
// It is imported from src/scripts/generated/dashboard.ts above.
|
||||||
|
|
||||||
// ── Shared SVG icons ──────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
const CopyIcon = () => (
|
|
||||||
<svg
|
|
||||||
class="copy-icon copy-icon-original"
|
|
||||||
width="16"
|
|
||||||
height="16"
|
|
||||||
viewBox="0 0 24 24"
|
|
||||||
fill="none"
|
|
||||||
stroke="currentColor"
|
|
||||||
stroke-width="2"
|
|
||||||
stroke-linecap="round"
|
|
||||||
stroke-linejoin="round"
|
|
||||||
>
|
|
||||||
<rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
|
|
||||||
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
|
|
||||||
</svg>
|
|
||||||
);
|
|
||||||
|
|
||||||
const CheckIcon = () => (
|
|
||||||
<svg
|
|
||||||
class="copy-icon copy-icon-success"
|
|
||||||
width="16"
|
|
||||||
height="16"
|
|
||||||
viewBox="0 0 24 24"
|
|
||||||
fill="none"
|
|
||||||
stroke="currentColor"
|
|
||||||
stroke-width="2"
|
|
||||||
stroke-linecap="round"
|
|
||||||
stroke-linejoin="round"
|
|
||||||
>
|
|
||||||
<path d="M20 6L9 17l-5-5"></path>
|
|
||||||
</svg>
|
|
||||||
);
|
|
||||||
|
|
||||||
type CopyFieldInlineProps = {
|
type CopyFieldInlineProps = {
|
||||||
value: string;
|
value: string;
|
||||||
emailAddress?: string;
|
emailAddress?: string;
|
||||||
@@ -279,18 +223,29 @@ const CopyFieldInline = ({ value }: CopyFieldInlineProps) => (
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const ConfirmationPill = ({ feedId }: { feedId: string }) => (
|
||||||
|
<a class="pill pill-confirmation" href={`/admin/feeds/${feedId}/emails`}>
|
||||||
|
Confirmation pending
|
||||||
|
</a>
|
||||||
|
);
|
||||||
|
|
||||||
|
const NativeFeedPill = ({ feedId }: { feedId: string }) => (
|
||||||
|
<a class="pill pill-native" href={`/admin/feeds/${feedId}/emails`}>
|
||||||
|
Native feed available
|
||||||
|
</a>
|
||||||
|
);
|
||||||
|
|
||||||
// Admin dashboard route
|
// Admin dashboard route
|
||||||
app.get("/", async (c) => {
|
app.get("/", async (c) => {
|
||||||
// Type assertion for environment variables
|
// Type assertion for environment variables
|
||||||
const env = c.env;
|
const env = c.env;
|
||||||
const emailStorage = env.EMAIL_STORAGE;
|
|
||||||
const url = new URL(c.req.url);
|
const url = new URL(c.req.url);
|
||||||
const view = url.searchParams.get("view") === "table" ? "table" : "list";
|
const view = url.searchParams.get("view") === "table" ? "table" : "list";
|
||||||
const message = url.searchParams.get("message");
|
const message = url.searchParams.get("message");
|
||||||
const count = Number(url.searchParams.get("count") || "0");
|
const count = Number(url.searchParams.get("count") || "0");
|
||||||
|
|
||||||
// List all feeds
|
// List all feeds
|
||||||
const feedList = await listAllFeeds(emailStorage);
|
const feedList = await FeedRepository.from(env).listFeeds();
|
||||||
|
|
||||||
// Keep the dashboard fast: avoid N KV reads for N feeds.
|
// Keep the dashboard fast: avoid N KV reads for N feeds.
|
||||||
// We store title/description in `feeds:list` (description is optional for older data).
|
// We store title/description in `feeds:list` (description is optional for older data).
|
||||||
@@ -345,14 +300,22 @@ app.get("/", async (c) => {
|
|||||||
<p>Manage your email newsletter feeds</p>
|
<p>Manage your email newsletter feeds</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-actions">
|
<div class="header-actions">
|
||||||
|
<a href="/" class="button button-secondary">
|
||||||
|
Status
|
||||||
|
</a>
|
||||||
<a href="/admin/logout" class="button button-logout">
|
<a href="/admin/logout" class="button button-logout">
|
||||||
Logout
|
Logout
|
||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="card">
|
<details
|
||||||
<h2>Create New Feed</h2>
|
class="card create-feed-card"
|
||||||
|
open={feedsWithConfig.length === 0}
|
||||||
|
>
|
||||||
|
<summary class="create-feed-summary">
|
||||||
|
<h2>Create New Feed</h2>
|
||||||
|
</summary>
|
||||||
<form action="/admin/feeds/create" method="post">
|
<form action="/admin/feeds/create" method="post">
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label for="title">Feed Title</label>
|
<label for="title">Feed Title</label>
|
||||||
@@ -396,6 +359,29 @@ app.get("/", async (c) => {
|
|||||||
</small>
|
</small>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="lifetime_hours">
|
||||||
|
Lifetime (hours{env.FEED_TTL_HOURS ? "" : ", optional"})
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
id="lifetime_hours"
|
||||||
|
name="lifetime_hours"
|
||||||
|
min="1"
|
||||||
|
value={env.FEED_TTL_HOURS || ""}
|
||||||
|
disabled={!!env.FEED_TTL_HOURS}
|
||||||
|
placeholder={env.FEED_TTL_HOURS ? undefined : "No expiry"}
|
||||||
|
/>
|
||||||
|
{env.FEED_TTL_HOURS ? (
|
||||||
|
<small>
|
||||||
|
Feed lifetime is fixed to {env.FEED_TTL_HOURS}h by server
|
||||||
|
configuration.
|
||||||
|
</small>
|
||||||
|
) : (
|
||||||
|
<small>Leave empty for no expiry.</small>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
<input type="hidden" id="language" name="language" value="en" />
|
<input type="hidden" id="language" name="language" value="en" />
|
||||||
<input type="hidden" name="view" value={view} />
|
<input type="hidden" name="view" value={view} />
|
||||||
|
|
||||||
@@ -403,7 +389,7 @@ app.get("/", async (c) => {
|
|||||||
Create Feed
|
Create Feed
|
||||||
</button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</details>
|
||||||
|
|
||||||
{message === "bulkDeleted" && (
|
{message === "bulkDeleted" && (
|
||||||
<div class="card">
|
<div class="card">
|
||||||
@@ -416,7 +402,7 @@ app.get("/", async (c) => {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div class="toolbar">
|
<div class="toolbar" id="your-feeds">
|
||||||
<div class="toolbar-group">
|
<div class="toolbar-group">
|
||||||
<h2 style="margin: 0;">Your Feeds</h2>
|
<h2 style="margin: 0;">Your Feeds</h2>
|
||||||
<span class="pill" id="feed-total-count">
|
<span class="pill" id="feed-total-count">
|
||||||
@@ -487,8 +473,8 @@ app.get("/", async (c) => {
|
|||||||
<col data-col="title" style="width: 280px;" />
|
<col data-col="title" style="width: 280px;" />
|
||||||
<col data-col="feedId" style="width: 150px;" />
|
<col data-col="feedId" style="width: 150px;" />
|
||||||
<col data-col="email" style="width: 200px;" />
|
<col data-col="email" style="width: 200px;" />
|
||||||
<col data-col="rss" style="width: 190px;" />
|
<col data-col="formats" style="width: 230px;" />
|
||||||
<col data-col="atom" style="width: 190px;" />
|
<col data-col="expires" style="width: 130px;" />
|
||||||
<col data-col="actions" style="width: 170px;" />
|
<col data-col="actions" style="width: 170px;" />
|
||||||
</colgroup>
|
</colgroup>
|
||||||
<thead>
|
<thead>
|
||||||
@@ -566,43 +552,19 @@ app.get("/", async (c) => {
|
|||||||
title="Resize"
|
title="Resize"
|
||||||
></div>
|
></div>
|
||||||
</th>
|
</th>
|
||||||
<th
|
<th class="th-resizable">
|
||||||
class="th-resizable"
|
<span>Formats</span>
|
||||||
data-sort-key="rss"
|
|
||||||
aria-sort="none"
|
|
||||||
>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="th-button"
|
|
||||||
data-sort-key="rss"
|
|
||||||
>
|
|
||||||
RSS
|
|
||||||
<span
|
|
||||||
class="sort-indicator"
|
|
||||||
aria-hidden="true"
|
|
||||||
></span>
|
|
||||||
</button>
|
|
||||||
<div
|
<div
|
||||||
class="col-resizer"
|
class="col-resizer"
|
||||||
data-col="rss"
|
data-col="formats"
|
||||||
title="Resize"
|
title="Resize"
|
||||||
></div>
|
></div>
|
||||||
</th>
|
</th>
|
||||||
<th class="th-resizable" data-sort-key="atom" aria-sort="none">
|
<th class="th-resizable">
|
||||||
<button
|
<span>Expires</span>
|
||||||
type="button"
|
|
||||||
class="th-button"
|
|
||||||
data-sort-key="atom"
|
|
||||||
>
|
|
||||||
Atom
|
|
||||||
<span
|
|
||||||
class="sort-indicator"
|
|
||||||
aria-hidden="true"
|
|
||||||
></span>
|
|
||||||
</button>
|
|
||||||
<div
|
<div
|
||||||
class="col-resizer"
|
class="col-resizer"
|
||||||
data-col="atom"
|
data-col="expires"
|
||||||
title="Resize"
|
title="Resize"
|
||||||
></div>
|
></div>
|
||||||
</th>
|
</th>
|
||||||
@@ -618,31 +580,34 @@ app.get("/", async (c) => {
|
|||||||
</thead>
|
</thead>
|
||||||
<tbody id="feed-table-body">
|
<tbody id="feed-table-body">
|
||||||
{feedsWithConfig.map((feed) => {
|
{feedsWithConfig.map((feed) => {
|
||||||
const emailAddress = feedEmailAddress(feed.id, env);
|
const emailAddress = feedEmailAddress(
|
||||||
const rssUrl = feedRssUrl(feed.id, env);
|
feed.mailbox_id,
|
||||||
const atomUrl = feedAtomUrl(feed.id, env);
|
env,
|
||||||
|
);
|
||||||
const titleDisplay = clampText(feed.title, 160);
|
const titleDisplay = clampText(feed.title, 160);
|
||||||
const titleHover = clampText(feed.title, 1000);
|
const titleHover = clampText(feed.title, 1000);
|
||||||
const sortTitle = titleHover.toLowerCase();
|
const sortTitle = titleHover.toLowerCase();
|
||||||
const sortFeedId = feed.id.toLowerCase();
|
const sortFeedId = feed.id.toLowerCase();
|
||||||
const sortEmail = emailAddress.toLowerCase();
|
const sortEmail = emailAddress.toLowerCase();
|
||||||
const sortRss = rssUrl.toLowerCase();
|
const descDisplay = clampText(
|
||||||
const sortAtom = atomUrl.toLowerCase();
|
feed.description || "",
|
||||||
const descDisplay = clampText(feed.description || "", 220);
|
220,
|
||||||
|
);
|
||||||
const descHover = clampText(feed.description || "", 1000);
|
const descHover = clampText(feed.description || "", 1000);
|
||||||
const searchHaystack =
|
const searchHaystack =
|
||||||
`${clampText(feed.title, 320)} ${feed.id} ${clampText(feed.description || "", 320)}`.toLowerCase();
|
`${clampText(feed.title, 320)} ${feed.id} ${clampText(feed.description || "", 320)}`.toLowerCase();
|
||||||
|
const isExpired =
|
||||||
|
feed.expires_at !== undefined &&
|
||||||
|
feed.expires_at <= Date.now();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<tr
|
<tr
|
||||||
class="feed-row"
|
class={`feed-row${isExpired ? " feed-expired" : ""}`}
|
||||||
data-feed-id={feed.id}
|
data-feed-id={feed.id}
|
||||||
data-search={searchHaystack}
|
data-search={searchHaystack}
|
||||||
data-sort-title={sortTitle}
|
data-sort-title={sortTitle}
|
||||||
data-sort-feed-id={sortFeedId}
|
data-sort-feed-id={sortFeedId}
|
||||||
data-sort-email={sortEmail}
|
data-sort-email={sortEmail}
|
||||||
data-sort-rss={sortRss}
|
|
||||||
data-sort-atom={sortAtom}
|
|
||||||
>
|
>
|
||||||
<td>
|
<td>
|
||||||
<input
|
<input
|
||||||
@@ -654,18 +619,36 @@ app.get("/", async (c) => {
|
|||||||
/>
|
/>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<strong class="truncate" title={titleHover}>
|
<div class="feed-title-cell">
|
||||||
{titleDisplay}
|
<img
|
||||||
</strong>
|
class="feed-icon"
|
||||||
{feed.description && (
|
src={`/favicon/${feed.id}`}
|
||||||
<div
|
alt=""
|
||||||
class="muted truncate"
|
width="20"
|
||||||
style="font-size: var(--font-size-sm); margin-top: 4px;"
|
height="20"
|
||||||
title={descHover}
|
loading="lazy"
|
||||||
>
|
/>
|
||||||
{descDisplay}
|
<div>
|
||||||
|
<strong class="truncate" title={titleHover}>
|
||||||
|
{titleDisplay}
|
||||||
|
</strong>
|
||||||
|
{feed.description && (
|
||||||
|
<div
|
||||||
|
class="muted truncate"
|
||||||
|
style="font-size: var(--font-size-sm); margin-top: 4px;"
|
||||||
|
title={descHover}
|
||||||
|
>
|
||||||
|
{descDisplay}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
{feed.pendingConfirmation && (
|
||||||
|
<ConfirmationPill feedId={feed.id} />
|
||||||
|
)}
|
||||||
|
{feed.hasNativeFeed && (
|
||||||
|
<NativeFeedPill feedId={feed.id} />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<code>{feed.id}</code>
|
<code>{feed.id}</code>
|
||||||
@@ -674,25 +657,50 @@ app.get("/", async (c) => {
|
|||||||
<CopyFieldInline value={emailAddress} />
|
<CopyFieldInline value={emailAddress} />
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<CopyFieldInline value={rssUrl} />
|
<FeedFormats feedId={feed.id} env={env} compact />
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<CopyFieldInline value={atomUrl} />
|
{feed.expires_at ? (
|
||||||
|
<ExpiryBadge expiresAt={feed.expires_at} />
|
||||||
|
) : (
|
||||||
|
<span class="muted">—</span>
|
||||||
|
)}
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<div class="row-actions">
|
<div class="row-actions">
|
||||||
<a
|
{isExpired ? (
|
||||||
href={`/admin/feeds/${feed.id}/edit`}
|
<>
|
||||||
class="button button-small"
|
<span
|
||||||
>
|
class="button button-small button-disabled"
|
||||||
Edit
|
aria-disabled="true"
|
||||||
</a>
|
tabindex={-1}
|
||||||
<a
|
>
|
||||||
href={`/admin/feeds/${feed.id}/emails`}
|
Edit
|
||||||
class="button button-small"
|
</span>
|
||||||
>
|
<span
|
||||||
Emails
|
class="button button-small button-disabled"
|
||||||
</a>
|
aria-disabled="true"
|
||||||
|
tabindex={-1}
|
||||||
|
>
|
||||||
|
Emails
|
||||||
|
</span>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<a
|
||||||
|
href={`/admin/feeds/${feed.id}/edit`}
|
||||||
|
class="button button-small"
|
||||||
|
>
|
||||||
|
Edit
|
||||||
|
</a>
|
||||||
|
<a
|
||||||
|
href={`/admin/feeds/${feed.id}/emails`}
|
||||||
|
class="button button-small"
|
||||||
|
>
|
||||||
|
Emails
|
||||||
|
</a>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
class="button button-small button-danger button-delete"
|
class="button button-small button-danger button-delete"
|
||||||
@@ -729,26 +737,44 @@ app.get("/", async (c) => {
|
|||||||
|
|
||||||
<ul class="feed-list">
|
<ul class="feed-list">
|
||||||
{feedsWithConfig.map((feed) => {
|
{feedsWithConfig.map((feed) => {
|
||||||
const emailAddress = feedEmailAddress(feed.id, env);
|
const emailAddress = feedEmailAddress(feed.mailbox_id, env);
|
||||||
const rssUrl = feedRssUrl(feed.id, env);
|
|
||||||
const atomUrl = feedAtomUrl(feed.id, env);
|
|
||||||
const titleDisplay = clampText(feed.title, 140);
|
const titleDisplay = clampText(feed.title, 140);
|
||||||
const titleHover = clampText(feed.title, 1000);
|
const titleHover = clampText(feed.title, 1000);
|
||||||
const descDisplay = clampText(feed.description || "", 240);
|
const descDisplay = clampText(feed.description || "", 240);
|
||||||
const descHover = clampText(feed.description || "", 1000);
|
const descHover = clampText(feed.description || "", 1000);
|
||||||
const searchHaystack =
|
const searchHaystack =
|
||||||
`${clampText(feed.title, 320)} ${feed.id} ${clampText(feed.description || "", 320)}`.toLowerCase();
|
`${clampText(feed.title, 320)} ${feed.id} ${clampText(feed.description || "", 320)}`.toLowerCase();
|
||||||
|
const isExpired =
|
||||||
|
feed.expires_at !== undefined &&
|
||||||
|
feed.expires_at <= Date.now();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<li
|
<li
|
||||||
class="feed-item card feed-row"
|
class={`feed-item card feed-row${isExpired ? " feed-expired" : ""}`}
|
||||||
data-feed-id={feed.id}
|
data-feed-id={feed.id}
|
||||||
data-search={searchHaystack}
|
data-search={searchHaystack}
|
||||||
>
|
>
|
||||||
<div class="feed-header">
|
<div class="feed-header">
|
||||||
<h3 class="feed-title" title={titleHover}>
|
<h3 class="feed-title" title={titleHover}>
|
||||||
|
<img
|
||||||
|
class="feed-icon"
|
||||||
|
src={`/favicon/${feed.id}`}
|
||||||
|
alt=""
|
||||||
|
width="20"
|
||||||
|
height="20"
|
||||||
|
loading="lazy"
|
||||||
|
/>
|
||||||
{titleDisplay}
|
{titleDisplay}
|
||||||
</h3>
|
</h3>
|
||||||
|
{feed.expires_at && (
|
||||||
|
<ExpiryBadge expiresAt={feed.expires_at} />
|
||||||
|
)}
|
||||||
|
{feed.pendingConfirmation && (
|
||||||
|
<ConfirmationPill feedId={feed.id} />
|
||||||
|
)}
|
||||||
|
{feed.hasNativeFeed && (
|
||||||
|
<NativeFeedPill feedId={feed.id} />
|
||||||
|
)}
|
||||||
{feed.description && (
|
{feed.description && (
|
||||||
<p class="feed-description">
|
<p class="feed-description">
|
||||||
<span title={descHover}>{descDisplay}</span>
|
<span title={descHover}>{descDisplay}</span>
|
||||||
@@ -773,54 +799,44 @@ app.get("/", async (c) => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="copyable">
|
<FeedFormats feedId={feed.id} env={env} />
|
||||||
<span class="copyable-label">RSS Feed:</span>
|
|
||||||
<div class="copyable-content">
|
|
||||||
<span
|
|
||||||
class="copyable-value"
|
|
||||||
data-copy={rssUrl}
|
|
||||||
title={rssUrl}
|
|
||||||
>
|
|
||||||
{rssUrl}
|
|
||||||
</span>
|
|
||||||
<div class="copy-icon-container">
|
|
||||||
<CopyIcon />
|
|
||||||
<CheckIcon />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="copyable">
|
|
||||||
<span class="copyable-label">Atom Feed:</span>
|
|
||||||
<div class="copyable-content">
|
|
||||||
<span
|
|
||||||
class="copyable-value"
|
|
||||||
data-copy={atomUrl}
|
|
||||||
title={atomUrl}
|
|
||||||
>
|
|
||||||
{atomUrl}
|
|
||||||
</span>
|
|
||||||
<div class="copy-icon-container">
|
|
||||||
<CopyIcon />
|
|
||||||
<CheckIcon />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="feed-buttons">
|
<div class="feed-buttons">
|
||||||
<div class="feed-buttons-left">
|
<div class="feed-buttons-left">
|
||||||
<a
|
{isExpired ? (
|
||||||
href={`/admin/feeds/${feed.id}/edit`}
|
<>
|
||||||
class="button button-small"
|
<span
|
||||||
>
|
class="button button-small button-disabled"
|
||||||
Edit
|
aria-disabled="true"
|
||||||
</a>
|
tabindex={-1}
|
||||||
<a
|
>
|
||||||
href={`/admin/feeds/${feed.id}/emails`}
|
Edit
|
||||||
class="button button-small"
|
</span>
|
||||||
>
|
<span
|
||||||
Emails
|
class="button button-small button-disabled"
|
||||||
</a>
|
aria-disabled="true"
|
||||||
|
tabindex={-1}
|
||||||
|
>
|
||||||
|
Emails
|
||||||
|
</span>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<a
|
||||||
|
href={`/admin/feeds/${feed.id}/edit`}
|
||||||
|
class="button button-small"
|
||||||
|
>
|
||||||
|
Edit
|
||||||
|
</a>
|
||||||
|
<a
|
||||||
|
href={`/admin/feeds/${feed.id}/emails`}
|
||||||
|
class="button button-small"
|
||||||
|
>
|
||||||
|
Emails
|
||||||
|
</a>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div class="feed-buttons-right">
|
<div class="feed-buttons-right">
|
||||||
<button
|
<button
|
||||||
@@ -847,6 +863,9 @@ app.get("/", async (c) => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// OPML export (admin-protected)
|
||||||
|
app.get("/opml", handleOpml);
|
||||||
|
|
||||||
// Mount sub-routers
|
// Mount sub-routers
|
||||||
app.route("/feeds", feedsRouter);
|
app.route("/feeds", feedsRouter);
|
||||||
app.route("/", emailsRouter);
|
app.route("/", emailsRouter);
|
||||||
@@ -863,45 +882,28 @@ app.post(
|
|||||||
},
|
},
|
||||||
),
|
),
|
||||||
async (c) => {
|
async (c) => {
|
||||||
// Type assertion for environment variables
|
|
||||||
const env = c.env;
|
const env = c.env;
|
||||||
const emailStorage = env.EMAIL_STORAGE;
|
|
||||||
const feedId = c.req.param("feedId");
|
const feedId = c.req.param("feedId");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { title, description } = c.req.valid("json");
|
const { title, description } = c.req.valid("json");
|
||||||
const parsedData = { title, description, language: "en" as const };
|
|
||||||
|
|
||||||
// Get existing feed config
|
// Quick-edit: only title/description, expiry untouched.
|
||||||
const feedConfigKey = `feed:${feedId}:config`;
|
const result = await editFeedDetails(env, FeedId.unchecked(feedId), {
|
||||||
const existingConfig = (await emailStorage.get(feedConfigKey, {
|
title,
|
||||||
type: "json",
|
description,
|
||||||
})) as FeedConfig | null;
|
});
|
||||||
|
|
||||||
if (!existingConfig) {
|
if (result.status === "not_found") {
|
||||||
return c.json({ error: "Feed not found" }, 404);
|
return c.json({ error: "Feed not found" }, 404);
|
||||||
}
|
}
|
||||||
|
if (result.status === "expired") {
|
||||||
|
return c.json(
|
||||||
|
{ error: "Feed has expired and cannot be modified." },
|
||||||
|
403,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Update feed configuration
|
|
||||||
await emailStorage.put(
|
|
||||||
feedConfigKey,
|
|
||||||
JSON.stringify({
|
|
||||||
...existingConfig,
|
|
||||||
title: parsedData.title,
|
|
||||||
description: parsedData.description,
|
|
||||||
updated_at: Date.now(),
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
// Update feed in the list of all feeds
|
|
||||||
await updateFeedInList(
|
|
||||||
emailStorage,
|
|
||||||
feedId,
|
|
||||||
parsedData.title,
|
|
||||||
parsedData.description,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Return success response
|
|
||||||
return c.json({ success: true });
|
return c.json({ success: true });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error("Error updating feed via API", { error: String(error) });
|
logger.error("Error updating feed via API", { error: String(error) });
|
||||||
|
|||||||
+286
-152
@@ -1,56 +1,37 @@
|
|||||||
import { Hono } from "hono";
|
import { Hono } from "hono";
|
||||||
|
import { Env, EmailMetadata } from "../../types";
|
||||||
|
import { logger } from "../../infrastructure/logger";
|
||||||
import {
|
import {
|
||||||
Env,
|
Layout,
|
||||||
FeedConfig,
|
clampText,
|
||||||
FeedMetadata,
|
CopyIcon,
|
||||||
EmailData,
|
CheckIcon,
|
||||||
EmailMetadata,
|
FeedFormats,
|
||||||
} from "../../types";
|
ExpiryBadge,
|
||||||
import { logger } from "../../lib/logger";
|
NativeFeeds,
|
||||||
import { Layout, clampText } from "./ui";
|
} from "./ui";
|
||||||
import { deleteKeysWithConcurrency } from "./helpers";
|
import { unionNativeFeeds } from "../../domain/native-feed";
|
||||||
import { feedRssUrl, feedAtomUrl, feedEmailAddress } from "../../utils/urls";
|
import {
|
||||||
|
deleteAttachmentsForEmails,
|
||||||
|
deleteKeysWithConcurrency,
|
||||||
|
} from "../../application/feed-cleanup";
|
||||||
|
import { FeedRepository } from "../../infrastructure/feed-repository";
|
||||||
|
import { FeedId } from "../../domain/value-objects/feed-id";
|
||||||
|
import {
|
||||||
|
feedEmailAddress,
|
||||||
|
baseUrl,
|
||||||
|
entryPath,
|
||||||
|
} from "../../infrastructure/urls";
|
||||||
|
import { processEmailContent } from "../../infrastructure/html-processor";
|
||||||
|
import { formatBytes } from "../../domain/format";
|
||||||
|
import { EmailAddress } from "../../domain/value-objects/email-address";
|
||||||
import { emailsPageScript } from "../../scripts/generated/emails-page";
|
import { emailsPageScript } from "../../scripts/generated/emails-page";
|
||||||
|
import emailPreviewCss from "../../styles/email-preview.css";
|
||||||
|
|
||||||
type AppEnv = { Bindings: Env };
|
type AppEnv = { Bindings: Env };
|
||||||
|
|
||||||
export const emailsRouter = new Hono<AppEnv>();
|
export const emailsRouter = new Hono<AppEnv>();
|
||||||
|
|
||||||
// ── Shared SVG icons ──────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
const CopyIcon = () => (
|
|
||||||
<svg
|
|
||||||
class="copy-icon copy-icon-original"
|
|
||||||
width="16"
|
|
||||||
height="16"
|
|
||||||
viewBox="0 0 24 24"
|
|
||||||
fill="none"
|
|
||||||
stroke="currentColor"
|
|
||||||
stroke-width="2"
|
|
||||||
stroke-linecap="round"
|
|
||||||
stroke-linejoin="round"
|
|
||||||
>
|
|
||||||
<rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
|
|
||||||
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
|
|
||||||
</svg>
|
|
||||||
);
|
|
||||||
|
|
||||||
const CheckIcon = () => (
|
|
||||||
<svg
|
|
||||||
class="copy-icon copy-icon-success"
|
|
||||||
width="16"
|
|
||||||
height="16"
|
|
||||||
viewBox="0 0 24 24"
|
|
||||||
fill="none"
|
|
||||||
stroke="currentColor"
|
|
||||||
stroke-width="2"
|
|
||||||
stroke-linecap="round"
|
|
||||||
stroke-linejoin="round"
|
|
||||||
>
|
|
||||||
<path d="M20 6L9 17l-5-5"></path>
|
|
||||||
</svg>
|
|
||||||
);
|
|
||||||
|
|
||||||
type CopyFieldProps = {
|
type CopyFieldProps = {
|
||||||
label: string;
|
label: string;
|
||||||
value: string;
|
value: string;
|
||||||
@@ -72,19 +53,15 @@ const CopyField = ({ label, value, display }: CopyFieldProps) => (
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|
||||||
function extractSenderEmail(from: string): string {
|
|
||||||
const match = from.match(/<([^>]+@[^>]+)>/);
|
|
||||||
return match ? match[1].trim().toLowerCase() : from.trim().toLowerCase();
|
|
||||||
}
|
|
||||||
|
|
||||||
type SenderFieldProps = {
|
type SenderFieldProps = {
|
||||||
from: string;
|
from: string;
|
||||||
feedId: string;
|
feedId: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
const SenderField = ({ from, feedId }: SenderFieldProps) => {
|
const SenderField = ({ from, feedId }: SenderFieldProps) => {
|
||||||
const senderEmail = extractSenderEmail(from);
|
const parsed = EmailAddress.parse(from);
|
||||||
const senderDomain = senderEmail.split("@")[1] || "";
|
const senderEmail = parsed?.normalized ?? from.trim().toLowerCase();
|
||||||
|
const senderDomain = parsed?.domain.value ?? "";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div class="copyable">
|
<div class="copyable">
|
||||||
@@ -152,25 +129,21 @@ const SenderField = ({ from, feedId }: SenderFieldProps) => {
|
|||||||
|
|
||||||
emailsRouter.get("/feeds/:feedId/emails", async (c) => {
|
emailsRouter.get("/feeds/:feedId/emails", async (c) => {
|
||||||
const env = c.env;
|
const env = c.env;
|
||||||
const emailStorage = env.EMAIL_STORAGE;
|
const repo = FeedRepository.from(env);
|
||||||
const feedId = c.req.param("feedId");
|
const feedId = c.req.param("feedId");
|
||||||
const message = c.req.query("message");
|
const message = c.req.query("message");
|
||||||
const count = Number(c.req.query("count") || "0");
|
const count = Number(c.req.query("count") || "0");
|
||||||
|
|
||||||
const feedConfig = (await emailStorage.get(`feed:${feedId}:config`, {
|
const id = FeedId.unchecked(feedId);
|
||||||
type: "json",
|
const feedConfig = await repo.getConfig(id);
|
||||||
})) as FeedConfig | null;
|
const feedMetadata = await repo.getMetadata(id);
|
||||||
const feedMetadata = (await emailStorage.get(`feed:${feedId}:metadata`, {
|
|
||||||
type: "json",
|
|
||||||
})) as FeedMetadata | null;
|
|
||||||
|
|
||||||
if (!feedConfig || !feedMetadata) {
|
if (!feedConfig || !feedMetadata) {
|
||||||
return c.text("Feed not found", 404);
|
return c.text("Feed not found", 404);
|
||||||
}
|
}
|
||||||
|
|
||||||
const emailAddress = feedEmailAddress(feedId, env);
|
const nativeFeeds = unionNativeFeeds(feedMetadata.nativeFeeds);
|
||||||
const rssUrl = feedRssUrl(feedId, env);
|
const emailAddress = feedEmailAddress(feedConfig.mailbox_id, env);
|
||||||
const atomUrl = feedAtomUrl(feedId, env);
|
|
||||||
|
|
||||||
return c.html(
|
return c.html(
|
||||||
<Layout title={`${feedConfig.title} - Emails`}>
|
<Layout title={`${feedConfig.title} - Emails`}>
|
||||||
@@ -187,38 +160,57 @@ emailsRouter.get("/feeds/:feedId/emails", async (c) => {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<h2>Feed Details</h2>
|
{feedConfig.expires_at && (
|
||||||
<div>
|
<div class="feed-header">
|
||||||
<CopyField label="Email Address:" value={emailAddress} />
|
<ExpiryBadge expiresAt={feedConfig.expires_at} />
|
||||||
<CopyField label="RSS Feed:" value={rssUrl} />
|
</div>
|
||||||
<CopyField label="Atom Feed:" value={atomUrl} />
|
)}
|
||||||
</div>
|
<CopyField label="Email:" value={emailAddress} />
|
||||||
<div class="feed-validate">
|
<FeedFormats feedId={feedId} env={env} />
|
||||||
<a
|
<NativeFeeds feeds={nativeFeeds} />
|
||||||
href={`https://validator.w3.org/feed/check.cgi?url=${encodeURIComponent(atomUrl)}`}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
>
|
|
||||||
<img
|
|
||||||
src="https://validator.w3.org/feed/images/valid-atom.png"
|
|
||||||
alt="[Valid Atom 1.0]"
|
|
||||||
title="Validate my Atom 1.0 feed"
|
|
||||||
/>
|
|
||||||
</a>
|
|
||||||
<a
|
|
||||||
href={`https://validator.w3.org/feed/check.cgi?url=${encodeURIComponent(rssUrl)}`}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
>
|
|
||||||
<img
|
|
||||||
src="https://validator.w3.org/feed/images/valid-rss-rogers.png"
|
|
||||||
alt="[Valid RSS]"
|
|
||||||
title="Validate my RSS feed"
|
|
||||||
/>
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{feedMetadata.pendingConfirmation && (
|
||||||
|
<div
|
||||||
|
class="confirmation-banner"
|
||||||
|
id="confirmation-banner"
|
||||||
|
data-feed-id={feedId}
|
||||||
|
>
|
||||||
|
<span>A subscription-confirmation email was detected.</span>
|
||||||
|
<div class="confirmation-banner-actions">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="button button-small"
|
||||||
|
id="confirmation-dismiss"
|
||||||
|
>
|
||||||
|
Mark as confirmed
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{nativeFeeds.length > 0 && !feedMetadata.nativeFeedDismissed && (
|
||||||
|
<div
|
||||||
|
class="confirmation-banner"
|
||||||
|
id="native-feed-banner"
|
||||||
|
data-feed-id={feedId}
|
||||||
|
>
|
||||||
|
<span>
|
||||||
|
This newsletter publishes its own feed — subscribe to it directly
|
||||||
|
from "Native feeds" above.
|
||||||
|
</span>
|
||||||
|
<div class="confirmation-banner-actions">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="button button-small"
|
||||||
|
id="native-feed-dismiss"
|
||||||
|
>
|
||||||
|
Dismiss
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<h2>
|
<h2>
|
||||||
Emails (
|
Emails (
|
||||||
<span id="email-total-count">{feedMetadata.emails.length}</span>)
|
<span id="email-total-count">{feedMetadata.emails.length}</span>)
|
||||||
@@ -349,6 +341,11 @@ emailsRouter.get("/feeds/:feedId/emails", async (c) => {
|
|||||||
{feedMetadata.emails.map((email: EmailMetadata) => {
|
{feedMetadata.emails.map((email: EmailMetadata) => {
|
||||||
const subjectDisplay = clampText(email.subject, 180);
|
const subjectDisplay = clampText(email.subject, 180);
|
||||||
const subjectHover = clampText(email.subject, 1000);
|
const subjectHover = clampText(email.subject, 1000);
|
||||||
|
const attachmentCount = email.attachmentIds?.length ?? 0;
|
||||||
|
const attachmentLabel = `${attachmentCount} attachment${
|
||||||
|
attachmentCount > 1 ? "s" : ""
|
||||||
|
}`;
|
||||||
|
const isConfirmation = !!email.confirmation;
|
||||||
const sortSubject = subjectHover.toLowerCase();
|
const sortSubject = subjectHover.toLowerCase();
|
||||||
const sortReceivedAt = String(email.receivedAt);
|
const sortReceivedAt = String(email.receivedAt);
|
||||||
const searchHaystack = clampText(
|
const searchHaystack = clampText(
|
||||||
@@ -373,9 +370,40 @@ emailsRouter.get("/feeds/:feedId/emails", async (c) => {
|
|||||||
/>
|
/>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<span class="truncate" title={subjectHover}>
|
<div class="subject-cell">
|
||||||
{subjectDisplay}
|
{attachmentCount > 0 ? (
|
||||||
</span>
|
<span
|
||||||
|
class="attachment-indicator"
|
||||||
|
title={attachmentLabel}
|
||||||
|
aria-label={attachmentLabel}
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
width="14"
|
||||||
|
height="14"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
stroke-width="2"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
<path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48" />
|
||||||
|
</svg>
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
{isConfirmation ? (
|
||||||
|
<span
|
||||||
|
class="confirmation-badge"
|
||||||
|
title="Subscription confirmation"
|
||||||
|
>
|
||||||
|
Confirmation
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
<span class="truncate" title={subjectHover}>
|
||||||
|
{subjectDisplay}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
</td>
|
</td>
|
||||||
<td>{new Date(email.receivedAt).toLocaleString()}</td>
|
<td>{new Date(email.receivedAt).toLocaleString()}</td>
|
||||||
<td>
|
<td>
|
||||||
@@ -415,7 +443,11 @@ emailsRouter.get("/feeds/:feedId/emails", async (c) => {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Config bootstrap — injects dynamic server-side data before the static compiled script */}
|
{/* Config bootstrap — injects dynamic server-side data before the static compiled script */}
|
||||||
<script dangerouslySetInnerHTML={{ __html: `window.__APP_CONFIG__=${JSON.stringify({ feedId })}` }} />
|
<script
|
||||||
|
dangerouslySetInnerHTML={{
|
||||||
|
__html: `window.__APP_CONFIG__=${JSON.stringify({ feedId })}`,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
{/* Emails page logic compiled from src/scripts/client/emails-page.ts */}
|
{/* Emails page logic compiled from src/scripts/client/emails-page.ts */}
|
||||||
<script dangerouslySetInnerHTML={{ __html: emailsPageScript }} />
|
<script dangerouslySetInnerHTML={{ __html: emailsPageScript }} />
|
||||||
</Layout>,
|
</Layout>,
|
||||||
@@ -426,18 +458,33 @@ emailsRouter.get("/feeds/:feedId/emails", async (c) => {
|
|||||||
|
|
||||||
emailsRouter.get("/emails/:emailKey", async (c) => {
|
emailsRouter.get("/emails/:emailKey", async (c) => {
|
||||||
const env = c.env;
|
const env = c.env;
|
||||||
const emailStorage = env.EMAIL_STORAGE;
|
const repo = FeedRepository.from(env);
|
||||||
const emailKey = c.req.param("emailKey");
|
const emailKey = c.req.param("emailKey");
|
||||||
|
|
||||||
const emailData = (await emailStorage.get(emailKey, {
|
const emailData = await repo.getEmail(emailKey);
|
||||||
type: "json",
|
|
||||||
})) as EmailData | null;
|
|
||||||
|
|
||||||
if (!emailData) return c.text("Email not found", 404);
|
if (!emailData) return c.text("Email not found", 404);
|
||||||
|
|
||||||
const feedId = emailKey.split(":")[1];
|
const feedId = repo.feedIdFromEmailKey(emailKey);
|
||||||
|
const feedConfig = await repo.getConfig(FeedId.unchecked(feedId));
|
||||||
|
if (!feedConfig) return c.text("Feed not found", 404);
|
||||||
|
|
||||||
const htmlContent = `<!DOCTYPE html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><style>body{font-family:-apple-system,BlinkMacSystemFont,'SF Pro Text','SF Pro Display','Helvetica Neue',Arial,sans-serif;line-height:1.5;padding:16px;margin:0;color:#333;box-sizing:border-box}img{max-width:100%;height:auto}a{color:#0070f3}@media(prefers-color-scheme:dark){body{background-color:#1c1c1e;color:#ffffff}a{color:#0a84ff}}</style></head><body>${emailData.content}</body></html>`;
|
const feedMetadata = await repo.getMetadata(FeedId.unchecked(feedId));
|
||||||
|
const confirmationLinks =
|
||||||
|
feedMetadata?.emails.find((e) => e.key === emailKey)?.confirmation?.links ??
|
||||||
|
[];
|
||||||
|
// Inline images render in place; only downloadable attachments go in the list.
|
||||||
|
const attachments = (emailData.attachments ?? []).filter((a) => !a.inline);
|
||||||
|
|
||||||
|
// The rendered preview lives in a `data:` iframe, which has no origin to
|
||||||
|
// resolve relative URLs against — so cid: refs must be rewritten to absolute
|
||||||
|
// /files URLs (and the content sanitized) before embedding.
|
||||||
|
const renderedBody = processEmailContent(
|
||||||
|
emailData.content,
|
||||||
|
emailData.attachments,
|
||||||
|
baseUrl(env),
|
||||||
|
);
|
||||||
|
const htmlContent = `<!DOCTYPE html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><style>${emailPreviewCss}</style></head><body>${renderedBody}</body></html>`;
|
||||||
|
|
||||||
const encodedHtmlContent = (() => {
|
const encodedHtmlContent = (() => {
|
||||||
const encoder = new TextEncoder();
|
const encoder = new TextEncoder();
|
||||||
@@ -445,9 +492,7 @@ emailsRouter.get("/emails/:emailKey", async (c) => {
|
|||||||
return btoa(String.fromCharCode(...new Uint8Array(bytes)));
|
return btoa(String.fromCharCode(...new Uint8Array(bytes)));
|
||||||
})();
|
})();
|
||||||
|
|
||||||
const rawHtml = emailData.content
|
const rawHtml = emailData.content.replace(/</g, "<").replace(/>/g, ">");
|
||||||
.replace(/</g, "<")
|
|
||||||
.replace(/>/g, ">");
|
|
||||||
|
|
||||||
const viewScript = `
|
const viewScript = `
|
||||||
function showRendered() {
|
function showRendered() {
|
||||||
@@ -548,11 +593,36 @@ emailsRouter.get("/emails/:emailKey", async (c) => {
|
|||||||
<SenderField from={emailData.from} feedId={feedId} />
|
<SenderField from={emailData.from} feedId={feedId} />
|
||||||
<CopyField
|
<CopyField
|
||||||
label="To:"
|
label="To:"
|
||||||
value={feedEmailAddress(feedId, env)}
|
value={feedEmailAddress(feedConfig.mailbox_id, env)}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{confirmationLinks.length > 0 && (
|
||||||
|
<div class="confirmation-section">
|
||||||
|
<h2>Confirm your subscription</h2>
|
||||||
|
<p class="muted">
|
||||||
|
This looks like a subscription-confirmation email. Open the link
|
||||||
|
to confirm.
|
||||||
|
</p>
|
||||||
|
<a
|
||||||
|
class="button confirmation-primary"
|
||||||
|
href={confirmationLinks[0]}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
>
|
||||||
|
Confirm subscription
|
||||||
|
</a>
|
||||||
|
<div class="confirmation-links">
|
||||||
|
{confirmationLinks.map((link) => (
|
||||||
|
<a href={link} target="_blank" rel="noopener noreferrer">
|
||||||
|
{link}
|
||||||
|
</a>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<div class="toggle-view">
|
<div class="toggle-view">
|
||||||
<button
|
<button
|
||||||
id="rendered-button"
|
id="rendered-button"
|
||||||
@@ -564,6 +634,14 @@ emailsRouter.get("/emails/:emailKey", async (c) => {
|
|||||||
<button id="raw-button" class="toggle-button" onclick="showRaw()">
|
<button id="raw-button" class="toggle-button" onclick="showRaw()">
|
||||||
Raw HTML
|
Raw HTML
|
||||||
</button>
|
</button>
|
||||||
|
<a
|
||||||
|
class="toggle-view-link"
|
||||||
|
href={entryPath(feedId, emailData.receivedAt)}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
>
|
||||||
|
Public page ↗
|
||||||
|
</a>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="email-content">
|
<div class="email-content">
|
||||||
@@ -577,6 +655,38 @@ emailsRouter.get("/emails/:emailKey", async (c) => {
|
|||||||
<pre dangerouslySetInnerHTML={{ __html: rawHtml }}></pre>
|
<pre dangerouslySetInnerHTML={{ __html: rawHtml }}></pre>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{attachments.length > 0 && (
|
||||||
|
<div class="attachments">
|
||||||
|
<h2>Attachments</h2>
|
||||||
|
<ul class="attachment-list">
|
||||||
|
{attachments.map((a) => (
|
||||||
|
<li>
|
||||||
|
<svg
|
||||||
|
width="14"
|
||||||
|
height="14"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
stroke-width="2"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
<path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48" />
|
||||||
|
</svg>
|
||||||
|
<a
|
||||||
|
href={`/files/${a.id}/${encodeURIComponent(a.filename)}`}
|
||||||
|
download
|
||||||
|
>
|
||||||
|
{a.filename}
|
||||||
|
</a>
|
||||||
|
<span class="attachment-size">{formatBytes(a.size)}</span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -589,7 +699,7 @@ emailsRouter.get("/emails/:emailKey", async (c) => {
|
|||||||
|
|
||||||
emailsRouter.post("/emails/:emailKey/delete", async (c) => {
|
emailsRouter.post("/emails/:emailKey/delete", async (c) => {
|
||||||
const env = c.env;
|
const env = c.env;
|
||||||
const emailStorage = env.EMAIL_STORAGE;
|
const repo = FeedRepository.from(env);
|
||||||
const emailKey = c.req.param("emailKey");
|
const emailKey = c.req.param("emailKey");
|
||||||
const wantsJson = (c.req.header("Accept") || "").includes("application/json");
|
const wantsJson = (c.req.header("Accept") || "").includes("application/json");
|
||||||
|
|
||||||
@@ -601,26 +711,13 @@ emailsRouter.post("/emails/:emailKey/delete", async (c) => {
|
|||||||
return c.text("Feed ID is required", 400);
|
return c.text("Feed ID is required", 400);
|
||||||
}
|
}
|
||||||
|
|
||||||
const feedMetadataKey = `feed:${feedId}:metadata`;
|
const feed = await repo.load(FeedId.unchecked(feedId));
|
||||||
const feedMetadata = (await emailStorage.get(feedMetadataKey, {
|
|
||||||
type: "json",
|
|
||||||
})) as FeedMetadata | null;
|
|
||||||
const attachmentIds =
|
|
||||||
feedMetadata?.emails.find((e) => e.key === emailKey)?.attachmentIds ?? [];
|
|
||||||
|
|
||||||
await emailStorage.delete(emailKey);
|
await repo.deleteEmail(emailKey);
|
||||||
|
if (feed) {
|
||||||
if (feedMetadata) {
|
const { removed } = feed.removeEmails([emailKey]);
|
||||||
feedMetadata.emails = feedMetadata.emails.filter(
|
await deleteAttachmentsForEmails(env, removed, [emailKey]);
|
||||||
(email) => email.key !== emailKey,
|
await repo.saveMetadata(feed);
|
||||||
);
|
|
||||||
await emailStorage.put(feedMetadataKey, JSON.stringify(feedMetadata));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (env.ATTACHMENT_BUCKET && attachmentIds.length > 0) {
|
|
||||||
await Promise.allSettled(
|
|
||||||
attachmentIds.map((id) => env.ATTACHMENT_BUCKET!.delete(id)),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (wantsJson) return c.json({ ok: true, emailKey, feedId });
|
if (wantsJson) return c.json({ ok: true, emailKey, feedId });
|
||||||
@@ -636,11 +733,64 @@ emailsRouter.post("/emails/:emailKey/delete", async (c) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ── Dismiss confirmation ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
emailsRouter.post("/feeds/:feedId/confirmation/dismiss", async (c) => {
|
||||||
|
const env = c.env;
|
||||||
|
const repo = FeedRepository.from(env);
|
||||||
|
const feedId = c.req.param("feedId");
|
||||||
|
const wantsJson = (
|
||||||
|
c.req.header("Accept") ||
|
||||||
|
c.req.header("Content-Type") ||
|
||||||
|
""
|
||||||
|
).includes("application/json");
|
||||||
|
|
||||||
|
const feed = await repo.load(FeedId.unchecked(feedId));
|
||||||
|
if (!feed) {
|
||||||
|
return wantsJson
|
||||||
|
? c.json({ ok: false, error: "Feed not found" }, 404)
|
||||||
|
: c.text("Feed not found", 404);
|
||||||
|
}
|
||||||
|
feed.dismissConfirmation();
|
||||||
|
await repo.saveMetadata(feed);
|
||||||
|
|
||||||
|
return wantsJson
|
||||||
|
? c.json({ ok: true })
|
||||||
|
: c.redirect(`/admin/feeds/${feedId}/emails`);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── Dismiss native-feed notice ───────────────────────────────────────────────
|
||||||
|
|
||||||
|
emailsRouter.post("/feeds/:feedId/native-feed/dismiss", async (c) => {
|
||||||
|
const env = c.env;
|
||||||
|
const repo = FeedRepository.from(env);
|
||||||
|
const feedId = c.req.param("feedId");
|
||||||
|
const wantsJson = (
|
||||||
|
c.req.header("Accept") ||
|
||||||
|
c.req.header("Content-Type") ||
|
||||||
|
""
|
||||||
|
).includes("application/json");
|
||||||
|
|
||||||
|
const feed = await repo.load(FeedId.unchecked(feedId));
|
||||||
|
if (!feed) {
|
||||||
|
return wantsJson
|
||||||
|
? c.json({ ok: false, error: "Feed not found" }, 404)
|
||||||
|
: c.text("Feed not found", 404);
|
||||||
|
}
|
||||||
|
feed.dismissNativeFeed();
|
||||||
|
await repo.saveMetadata(feed);
|
||||||
|
|
||||||
|
return wantsJson
|
||||||
|
? c.json({ ok: true })
|
||||||
|
: c.redirect(`/admin/feeds/${feedId}/emails`);
|
||||||
|
});
|
||||||
|
|
||||||
// ── Bulk delete emails ────────────────────────────────────────────────────────
|
// ── Bulk delete emails ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
emailsRouter.post("/feeds/:feedId/emails/bulk-delete", async (c) => {
|
emailsRouter.post("/feeds/:feedId/emails/bulk-delete", async (c) => {
|
||||||
const env = c.env;
|
const env = c.env;
|
||||||
const emailStorage = env.EMAIL_STORAGE;
|
const emailStorage = env.EMAIL_STORAGE;
|
||||||
|
const repo = new FeedRepository(emailStorage);
|
||||||
const feedId = c.req.param("feedId");
|
const feedId = c.req.param("feedId");
|
||||||
const contentType = c.req.header("Content-Type") || "";
|
const contentType = c.req.header("Content-Type") || "";
|
||||||
const wantsJson =
|
const wantsJson =
|
||||||
@@ -648,18 +798,15 @@ emailsRouter.post("/feeds/:feedId/emails/bulk-delete", async (c) => {
|
|||||||
(c.req.header("Accept") || "").includes("application/json");
|
(c.req.header("Accept") || "").includes("application/json");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const feedMetadataKey = `feed:${feedId}:metadata`;
|
const feed = await repo.load(FeedId.unchecked(feedId));
|
||||||
const feedMetadata = (await emailStorage.get(feedMetadataKey, {
|
|
||||||
type: "json",
|
|
||||||
})) as FeedMetadata | null;
|
|
||||||
|
|
||||||
if (!feedMetadata) {
|
if (!feed) {
|
||||||
return wantsJson
|
return wantsJson
|
||||||
? c.json({ ok: false, error: "Feed not found" }, 404)
|
? c.json({ ok: false, error: "Feed not found" }, 404)
|
||||||
: c.text("Feed not found", 404);
|
: c.text("Feed not found", 404);
|
||||||
}
|
}
|
||||||
|
|
||||||
const allowedKeys = new Set(feedMetadata.emails.map((email) => email.key));
|
const allowedKeys = new Set(feed.emails.map((email) => email.key));
|
||||||
|
|
||||||
if (wantsJson) {
|
if (wantsJson) {
|
||||||
const body = (await c.req.json().catch(() => null)) as {
|
const body = (await c.req.json().catch(() => null)) as {
|
||||||
@@ -686,25 +833,13 @@ emailsRouter.post("/feeds/:feedId/emails/bulk-delete", async (c) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const candidates = emailKeys.filter((key) => allowedKeys.has(key));
|
const candidates = emailKeys.filter((key) => allowedKeys.has(key));
|
||||||
const candidateSet = new Set(candidates);
|
|
||||||
const r2AttachmentIds = feedMetadata.emails
|
|
||||||
.filter((e) => candidateSet.has(e.key))
|
|
||||||
.flatMap((e) => e.attachmentIds ?? []);
|
|
||||||
|
|
||||||
const { ok: deletedOk, failed: failedEmailKeys } =
|
const { ok: deletedOk, failed: failedEmailKeys } =
|
||||||
await deleteKeysWithConcurrency(emailStorage, candidates, 35);
|
await deleteKeysWithConcurrency(emailStorage, candidates, 35);
|
||||||
|
await deleteAttachmentsForEmails(env, feed.emails, candidates);
|
||||||
|
|
||||||
const deletedSet = new Set(deletedOk);
|
feed.removeEmails(deletedOk);
|
||||||
feedMetadata.emails = feedMetadata.emails.filter(
|
await repo.saveMetadata(feed);
|
||||||
(email) => !deletedSet.has(email.key),
|
|
||||||
);
|
|
||||||
await emailStorage.put(feedMetadataKey, JSON.stringify(feedMetadata));
|
|
||||||
|
|
||||||
if (env.ATTACHMENT_BUCKET && r2AttachmentIds.length > 0) {
|
|
||||||
await Promise.allSettled(
|
|
||||||
r2AttachmentIds.map((id) => env.ATTACHMENT_BUCKET!.delete(id)),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.json({
|
return c.json({
|
||||||
ok: failedEmailKeys.length === 0,
|
ok: failedEmailKeys.length === 0,
|
||||||
@@ -723,17 +858,16 @@ emailsRouter.post("/feeds/:feedId/emails/bulk-delete", async (c) => {
|
|||||||
return c.redirect(`/admin/feeds/${feedId}/emails?message=bulkDeleteNoop`);
|
return c.redirect(`/admin/feeds/${feedId}/emails?message=bulkDeleteNoop`);
|
||||||
|
|
||||||
const candidates = emailKeys.filter((key) => allowedKeys.has(key));
|
const candidates = emailKeys.filter((key) => allowedKeys.has(key));
|
||||||
|
|
||||||
const { ok: deletedOk } = await deleteKeysWithConcurrency(
|
const { ok: deletedOk } = await deleteKeysWithConcurrency(
|
||||||
emailStorage,
|
emailStorage,
|
||||||
candidates,
|
candidates,
|
||||||
35,
|
35,
|
||||||
);
|
);
|
||||||
|
await deleteAttachmentsForEmails(env, feed.emails, candidates);
|
||||||
|
|
||||||
const deletedSet = new Set(deletedOk);
|
feed.removeEmails(deletedOk);
|
||||||
feedMetadata.emails = feedMetadata.emails.filter(
|
await repo.saveMetadata(feed);
|
||||||
(email) => !deletedSet.has(email.key),
|
|
||||||
);
|
|
||||||
await emailStorage.put(feedMetadataKey, JSON.stringify(feedMetadata));
|
|
||||||
|
|
||||||
return c.redirect(
|
return c.redirect(
|
||||||
`/admin/feeds/${feedId}/emails?message=bulkDeleted&count=${deletedOk.length}`,
|
`/admin/feeds/${feedId}/emails?message=bulkDeleted&count=${deletedOk.length}`,
|
||||||
|
|||||||
+207
-208
@@ -1,18 +1,25 @@
|
|||||||
import { Hono } from "hono";
|
import { Hono } from "hono";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { Env, FeedConfig, FeedMetadata, EmailData } from "../../types";
|
import { Env } from "../../types";
|
||||||
import { generateFeedId } from "../../utils/id-generator";
|
import { bumpCounters } from "../../application/stats";
|
||||||
import { waitUntilSafe } from "../../utils/worker";
|
import { waitUntilSafe } from "../../infrastructure/worker";
|
||||||
import { feedRssUrl, feedEmailAddress } from "../../utils/urls";
|
import { feedRssUrl, feedEmailAddress } from "../../infrastructure/urls";
|
||||||
import { logger } from "../../lib/logger";
|
import { logger } from "../../infrastructure/logger";
|
||||||
|
import { sendUnsubscribes } from "../../infrastructure/unsubscribe";
|
||||||
|
import { getAttachmentBucket } from "../../infrastructure/attachments";
|
||||||
import { Layout } from "./ui";
|
import { Layout } from "./ui";
|
||||||
import {
|
import {
|
||||||
addFeedToList,
|
purgeFeedKeysStep,
|
||||||
updateFeedInList,
|
collectUnsubscribeUrls,
|
||||||
removeFeedFromList,
|
} from "../../application/feed-cleanup";
|
||||||
removeFeedsFromListBulk,
|
import { FeedRepository } from "../../infrastructure/feed-repository";
|
||||||
deleteKeysWithConcurrency,
|
import { FeedId } from "../../domain/value-objects/feed-id";
|
||||||
} from "./helpers";
|
import {
|
||||||
|
createFeedRecord,
|
||||||
|
editFeed,
|
||||||
|
deleteFeedRecord,
|
||||||
|
deleteFeedFastDetailed,
|
||||||
|
} from "../../application/feed-service";
|
||||||
|
|
||||||
type AppEnv = { Bindings: Env };
|
type AppEnv = { Bindings: Env };
|
||||||
|
|
||||||
@@ -43,117 +50,19 @@ const updateFeedSchema = z.object({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const senderFilterSchema = z.object({
|
const senderFilterSchema = z.object({
|
||||||
action: z.enum(["allow_sender", "allow_domain", "block_sender", "block_domain"]),
|
action: z.enum([
|
||||||
|
"allow_sender",
|
||||||
|
"allow_domain",
|
||||||
|
"block_sender",
|
||||||
|
"block_domain",
|
||||||
|
]),
|
||||||
value: z.string().min(1),
|
value: z.string().min(1),
|
||||||
});
|
});
|
||||||
|
|
||||||
// ── Delete helpers ────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
type DeleteFeedFastResult = {
|
|
||||||
ok: boolean;
|
|
||||||
configDeleted: boolean;
|
|
||||||
metadataDeleted: boolean;
|
|
||||||
errors: string[];
|
|
||||||
};
|
|
||||||
|
|
||||||
async function deleteFeedFastDetailed(
|
|
||||||
emailStorage: KVNamespace,
|
|
||||||
feedId: string,
|
|
||||||
): Promise<DeleteFeedFastResult> {
|
|
||||||
const feedConfigKey = `feed:${feedId}:config`;
|
|
||||||
const feedMetadataKey = `feed:${feedId}:metadata`;
|
|
||||||
|
|
||||||
const errors: string[] = [];
|
|
||||||
let configDeleted = false;
|
|
||||||
let metadataDeleted = false;
|
|
||||||
|
|
||||||
try {
|
|
||||||
await emailStorage.delete(feedConfigKey);
|
|
||||||
configDeleted = true;
|
|
||||||
} catch (error) {
|
|
||||||
errors.push(`config delete failed: ${String(error)}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
await emailStorage.delete(feedMetadataKey);
|
|
||||||
metadataDeleted = true;
|
|
||||||
} catch (error) {
|
|
||||||
errors.push(`metadata delete failed: ${String(error)}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return { ok: configDeleted, configDeleted, metadataDeleted, errors };
|
|
||||||
}
|
|
||||||
|
|
||||||
async function deleteFeedFast(
|
|
||||||
emailStorage: KVNamespace,
|
|
||||||
feedId: string,
|
|
||||||
): Promise<boolean> {
|
|
||||||
const result = await deleteFeedFastDetailed(emailStorage, feedId);
|
|
||||||
return result.ok;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function purgeFeedKeysStep(
|
|
||||||
emailStorage: KVNamespace,
|
|
||||||
feedId: string,
|
|
||||||
options: { cursor?: string; limit?: number; bucket?: R2Bucket } = {},
|
|
||||||
): Promise<{
|
|
||||||
deletedKeys: string[];
|
|
||||||
failedKeys: string[];
|
|
||||||
cursor: string;
|
|
||||||
listComplete: boolean;
|
|
||||||
}> {
|
|
||||||
const prefix = `feed:${feedId}:`;
|
|
||||||
const limit = Math.min(1000, Math.max(1, Math.floor(options.limit || 100)));
|
|
||||||
const cursor = options.cursor || undefined;
|
|
||||||
|
|
||||||
const listed = await emailStorage.list({ prefix, cursor, limit });
|
|
||||||
const keys = (listed.keys || []).map((k) => k.name);
|
|
||||||
|
|
||||||
if (options.bucket && keys.length > 0) {
|
|
||||||
const emailKeys = keys.filter((k) => {
|
|
||||||
const suffix = k.slice(prefix.length);
|
|
||||||
return suffix !== "config" && suffix !== "metadata";
|
|
||||||
});
|
|
||||||
if (emailKeys.length > 0) {
|
|
||||||
const emailDataResults = await Promise.allSettled(
|
|
||||||
emailKeys.map(
|
|
||||||
(k) =>
|
|
||||||
emailStorage.get(k, { type: "json" }) as Promise<EmailData | null>,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
const attachmentIds = emailDataResults
|
|
||||||
.filter(
|
|
||||||
(r): r is PromiseFulfilledResult<EmailData | null> =>
|
|
||||||
r.status === "fulfilled",
|
|
||||||
)
|
|
||||||
.flatMap((r) => r.value?.attachments?.map((a) => a.id) ?? []);
|
|
||||||
if (attachmentIds.length > 0) {
|
|
||||||
await Promise.allSettled(
|
|
||||||
attachmentIds.map((id) => options.bucket!.delete(id)),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const { ok, failed } = await deleteKeysWithConcurrency(
|
|
||||||
emailStorage,
|
|
||||||
keys,
|
|
||||||
35,
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
|
||||||
deletedKeys: ok,
|
|
||||||
failedKeys: failed,
|
|
||||||
cursor: listed.cursor || "",
|
|
||||||
listComplete: !!listed.list_complete,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Routes ────────────────────────────────────────────────────────────────────
|
// ── Routes ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
feedsRouter.post("/create", async (c) => {
|
feedsRouter.post("/create", async (c) => {
|
||||||
const env = c.env;
|
const env = c.env;
|
||||||
const emailStorage = env.EMAIL_STORAGE;
|
|
||||||
const isJson =
|
const isJson =
|
||||||
c.req.header("Content-Type")?.includes("application/json") ?? false;
|
c.req.header("Content-Type")?.includes("application/json") ?? false;
|
||||||
|
|
||||||
@@ -161,9 +70,9 @@ feedsRouter.post("/create", async (c) => {
|
|||||||
let title: string;
|
let title: string;
|
||||||
let description: string | undefined;
|
let description: string | undefined;
|
||||||
let language: string;
|
let language: string;
|
||||||
let view: string;
|
|
||||||
let allowedSenders: string[];
|
let allowedSenders: string[];
|
||||||
let blockedSenders: string[];
|
let blockedSenders: string[];
|
||||||
|
let lifetimeHoursRaw: string | undefined;
|
||||||
|
|
||||||
if (isJson) {
|
if (isJson) {
|
||||||
const body = await c.req.json<Record<string, unknown>>();
|
const body = await c.req.json<Record<string, unknown>>();
|
||||||
@@ -171,7 +80,6 @@ feedsRouter.post("/create", async (c) => {
|
|||||||
description =
|
description =
|
||||||
body.description != null ? String(body.description) : undefined;
|
body.description != null ? String(body.description) : undefined;
|
||||||
language = String(body.language ?? "en");
|
language = String(body.language ?? "en");
|
||||||
view = "list";
|
|
||||||
allowedSenders = Array.isArray(body.allowedSenders)
|
allowedSenders = Array.isArray(body.allowedSenders)
|
||||||
? normalizeAllowedSenders(
|
? normalizeAllowedSenders(
|
||||||
(body.allowedSenders as unknown[]).map(String),
|
(body.allowedSenders as unknown[]).map(String),
|
||||||
@@ -182,18 +90,20 @@ feedsRouter.post("/create", async (c) => {
|
|||||||
(body.blockedSenders as unknown[]).map(String),
|
(body.blockedSenders as unknown[]).map(String),
|
||||||
)
|
)
|
||||||
: [];
|
: [];
|
||||||
|
lifetimeHoursRaw =
|
||||||
|
body.lifetimeHours != null ? String(body.lifetimeHours) : undefined;
|
||||||
} else {
|
} else {
|
||||||
const formData = await c.req.formData();
|
const formData = await c.req.formData();
|
||||||
title = formData.get("title")?.toString() || "";
|
title = formData.get("title")?.toString() || "";
|
||||||
description = formData.get("description")?.toString();
|
description = formData.get("description")?.toString();
|
||||||
language = formData.get("language")?.toString() || "en";
|
language = formData.get("language")?.toString() || "en";
|
||||||
view = formData.get("view")?.toString() === "table" ? "table" : "list";
|
|
||||||
allowedSenders = parseAllowedSenders(
|
allowedSenders = parseAllowedSenders(
|
||||||
formData.get("allowed_senders")?.toString() || "",
|
formData.get("allowed_senders")?.toString() || "",
|
||||||
);
|
);
|
||||||
blockedSenders = parseAllowedSenders(
|
blockedSenders = parseAllowedSenders(
|
||||||
formData.get("blocked_senders")?.toString() || "",
|
formData.get("blocked_senders")?.toString() || "",
|
||||||
);
|
);
|
||||||
|
lifetimeHoursRaw = formData.get("lifetime_hours")?.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
const parsedData = createFeedSchema.parse({
|
const parsedData = createFeedSchema.parse({
|
||||||
@@ -204,41 +114,28 @@ feedsRouter.post("/create", async (c) => {
|
|||||||
blockedSenders,
|
blockedSenders,
|
||||||
});
|
});
|
||||||
|
|
||||||
const feedId = generateFeedId();
|
const lifetimeHours = lifetimeHoursRaw
|
||||||
|
? parseInt(lifetimeHoursRaw, 10)
|
||||||
|
: undefined;
|
||||||
|
|
||||||
const feedConfig: FeedConfig = {
|
const { feedId, mailboxId } = await createFeedRecord(env, {
|
||||||
title: parsedData.title,
|
title: parsedData.title,
|
||||||
description: parsedData.description,
|
description: parsedData.description,
|
||||||
language: parsedData.language,
|
language: parsedData.language,
|
||||||
allowed_senders: parsedData.allowedSenders,
|
allowedSenders: parsedData.allowedSenders,
|
||||||
blocked_senders: parsedData.blockedSenders,
|
blockedSenders: parsedData.blockedSenders,
|
||||||
created_at: Date.now(),
|
lifetimeHours,
|
||||||
updated_at: Date.now(),
|
});
|
||||||
};
|
|
||||||
|
|
||||||
const feedMetadata: FeedMetadata = { emails: [] };
|
|
||||||
|
|
||||||
await Promise.all([
|
|
||||||
emailStorage.put(`feed:${feedId}:config`, JSON.stringify(feedConfig)),
|
|
||||||
emailStorage.put(`feed:${feedId}:metadata`, JSON.stringify(feedMetadata)),
|
|
||||||
]);
|
|
||||||
|
|
||||||
await addFeedToList(
|
|
||||||
emailStorage,
|
|
||||||
feedId,
|
|
||||||
parsedData.title,
|
|
||||||
parsedData.description,
|
|
||||||
);
|
|
||||||
|
|
||||||
if (isJson) {
|
if (isJson) {
|
||||||
return c.json({
|
return c.json({
|
||||||
feedId,
|
feedId,
|
||||||
email: feedEmailAddress(feedId, env),
|
email: feedEmailAddress(mailboxId, env),
|
||||||
feedUrl: feedRssUrl(feedId, env),
|
feedUrl: feedRssUrl(feedId, env),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.redirect(`/admin?view=${view}`);
|
return c.redirect(`/admin/feeds/${feedId}/emails`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error("Error creating feed", { error: String(error) });
|
logger.error("Error creating feed", { error: String(error) });
|
||||||
if (c.req.header("Content-Type")?.includes("application/json")) {
|
if (c.req.header("Content-Type")?.includes("application/json")) {
|
||||||
@@ -250,17 +147,32 @@ feedsRouter.post("/create", async (c) => {
|
|||||||
|
|
||||||
feedsRouter.get("/:feedId/edit", async (c) => {
|
feedsRouter.get("/:feedId/edit", async (c) => {
|
||||||
const env = c.env;
|
const env = c.env;
|
||||||
const emailStorage = env.EMAIL_STORAGE;
|
|
||||||
const feedId = c.req.param("feedId");
|
const feedId = c.req.param("feedId");
|
||||||
|
|
||||||
const feedConfig = (await emailStorage.get(`feed:${feedId}:config`, {
|
const feedConfig = await FeedRepository.from(env).getConfig(
|
||||||
type: "json",
|
FeedId.unchecked(feedId),
|
||||||
})) as FeedConfig | null;
|
);
|
||||||
|
|
||||||
if (!feedConfig) {
|
if (!feedConfig) {
|
||||||
return c.text("Feed not found", 404);
|
return c.text("Feed not found", 404);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const now = Date.now();
|
||||||
|
const isExpired =
|
||||||
|
feedConfig.expires_at !== undefined && feedConfig.expires_at <= now;
|
||||||
|
const ttlLocked = !!env.FEED_TTL_HOURS;
|
||||||
|
|
||||||
|
// Remaining hours: ceil so we don't show 0 when there's still time left
|
||||||
|
const remainingHours =
|
||||||
|
feedConfig.expires_at !== undefined && feedConfig.expires_at > now
|
||||||
|
? Math.ceil((feedConfig.expires_at - now) / 3_600_000)
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
const lifetimeFieldValue =
|
||||||
|
ttlLocked && !isExpired
|
||||||
|
? (env.FEED_TTL_HOURS ?? "")
|
||||||
|
: (remainingHours?.toString() ?? "");
|
||||||
|
|
||||||
return c.html(
|
return c.html(
|
||||||
<Layout title="Edit Feed">
|
<Layout title="Edit Feed">
|
||||||
<div class="container fade-in">
|
<div class="container fade-in">
|
||||||
@@ -275,7 +187,25 @@ feedsRouter.get("/:feedId/edit", async (c) => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="card">
|
{isExpired && (
|
||||||
|
<div class="card card-warning">
|
||||||
|
<p>
|
||||||
|
<strong>This feed has expired.</strong> It no longer accepts
|
||||||
|
emails and its content is no longer publicly accessible.
|
||||||
|
</p>
|
||||||
|
<form
|
||||||
|
action={`/admin/feeds/${feedId}/delete`}
|
||||||
|
method="post"
|
||||||
|
style="margin-top: 0.75rem;"
|
||||||
|
>
|
||||||
|
<button type="submit" class="button button-danger">
|
||||||
|
Delete this feed
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div class={`card${isExpired ? " card-disabled" : ""}`}>
|
||||||
<form action={`/admin/feeds/${feedId}/edit`} method="post">
|
<form action={`/admin/feeds/${feedId}/edit`} method="post">
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label for="title">Feed Title</label>
|
<label for="title">Feed Title</label>
|
||||||
@@ -285,12 +215,18 @@ feedsRouter.get("/:feedId/edit", async (c) => {
|
|||||||
name="title"
|
name="title"
|
||||||
value={feedConfig.title}
|
value={feedConfig.title}
|
||||||
required
|
required
|
||||||
|
disabled={isExpired}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label for="description">Description</label>
|
<label for="description">Description</label>
|
||||||
<textarea id="description" name="description" rows={3}>
|
<textarea
|
||||||
|
id="description"
|
||||||
|
name="description"
|
||||||
|
rows={3}
|
||||||
|
disabled={isExpired}
|
||||||
|
>
|
||||||
{feedConfig.description || ""}
|
{feedConfig.description || ""}
|
||||||
</textarea>
|
</textarea>
|
||||||
</div>
|
</div>
|
||||||
@@ -304,6 +240,7 @@ feedsRouter.get("/:feedId/edit", async (c) => {
|
|||||||
name="allowed_senders"
|
name="allowed_senders"
|
||||||
rows={3}
|
rows={3}
|
||||||
placeholder={"newsletter@example.com\ntechmeme.com"}
|
placeholder={"newsletter@example.com\ntechmeme.com"}
|
||||||
|
disabled={isExpired}
|
||||||
>
|
>
|
||||||
{(feedConfig.allowed_senders || []).join("\n")}
|
{(feedConfig.allowed_senders || []).join("\n")}
|
||||||
</textarea>
|
</textarea>
|
||||||
@@ -322,6 +259,7 @@ feedsRouter.get("/:feedId/edit", async (c) => {
|
|||||||
name="blocked_senders"
|
name="blocked_senders"
|
||||||
rows={3}
|
rows={3}
|
||||||
placeholder={"spam@example.com\nunwanted.com"}
|
placeholder={"spam@example.com\nunwanted.com"}
|
||||||
|
disabled={isExpired}
|
||||||
>
|
>
|
||||||
{(feedConfig.blocked_senders || []).join("\n")}
|
{(feedConfig.blocked_senders || []).join("\n")}
|
||||||
</textarea>
|
</textarea>
|
||||||
@@ -331,11 +269,54 @@ feedsRouter.get("/:feedId/edit", async (c) => {
|
|||||||
</small>
|
</small>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label class="checkbox-label">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
name="sender_in_title"
|
||||||
|
value="true"
|
||||||
|
checked={feedConfig.sender_in_title ?? false}
|
||||||
|
disabled={isExpired}
|
||||||
|
/>
|
||||||
|
Show sender in entry titles
|
||||||
|
</label>
|
||||||
|
<small>
|
||||||
|
Render each entry's title as <code>[Sender] Subject</code> for
|
||||||
|
at-a-glance scanning in your reader.
|
||||||
|
</small>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="lifetime_hours">Lifetime (hours)</label>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
id="lifetime_hours"
|
||||||
|
name="lifetime_hours"
|
||||||
|
min="1"
|
||||||
|
value={lifetimeFieldValue}
|
||||||
|
disabled={isExpired || ttlLocked}
|
||||||
|
placeholder={feedConfig.expires_at ? undefined : "No expiry"}
|
||||||
|
/>
|
||||||
|
{ttlLocked ? (
|
||||||
|
<small>
|
||||||
|
Feed lifetime is fixed to {env.FEED_TTL_HOURS}h by server
|
||||||
|
configuration.
|
||||||
|
</small>
|
||||||
|
) : (
|
||||||
|
<small>
|
||||||
|
Hours from now until this feed expires. Leave empty to keep
|
||||||
|
the current expiry (or no expiry).
|
||||||
|
</small>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
<input type="hidden" id="language" name="language" value="en" />
|
<input type="hidden" id="language" name="language" value="en" />
|
||||||
|
|
||||||
<button type="submit" class="button">
|
{!isExpired && (
|
||||||
Update Feed
|
<button type="submit" class="button">
|
||||||
</button>
|
Update Feed
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -345,7 +326,6 @@ feedsRouter.get("/:feedId/edit", async (c) => {
|
|||||||
|
|
||||||
feedsRouter.post("/:feedId/edit", async (c) => {
|
feedsRouter.post("/:feedId/edit", async (c) => {
|
||||||
const env = c.env;
|
const env = c.env;
|
||||||
const emailStorage = env.EMAIL_STORAGE;
|
|
||||||
const feedId = c.req.param("feedId");
|
const feedId = c.req.param("feedId");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -359,6 +339,8 @@ feedsRouter.post("/:feedId/edit", async (c) => {
|
|||||||
const blockedSenders = parseAllowedSenders(
|
const blockedSenders = parseAllowedSenders(
|
||||||
formData.get("blocked_senders")?.toString() || "",
|
formData.get("blocked_senders")?.toString() || "",
|
||||||
);
|
);
|
||||||
|
const senderInTitle = formData.get("sender_in_title") === "true";
|
||||||
|
const lifetimeHoursRaw = formData.get("lifetime_hours")?.toString();
|
||||||
|
|
||||||
const parsedData = updateFeedSchema.parse({
|
const parsedData = updateFeedSchema.parse({
|
||||||
title,
|
title,
|
||||||
@@ -368,34 +350,24 @@ feedsRouter.post("/:feedId/edit", async (c) => {
|
|||||||
blockedSenders,
|
blockedSenders,
|
||||||
});
|
});
|
||||||
|
|
||||||
const feedConfigKey = `feed:${feedId}:config`;
|
const result = await editFeed(env, FeedId.unchecked(feedId), {
|
||||||
const existingConfig = (await emailStorage.get(feedConfigKey, {
|
title: parsedData.title,
|
||||||
type: "json",
|
description: parsedData.description,
|
||||||
})) as FeedConfig | null;
|
language: parsedData.language,
|
||||||
|
allowedSenders: parsedData.allowedSenders,
|
||||||
|
blockedSenders: parsedData.blockedSenders,
|
||||||
|
senderInTitle,
|
||||||
|
lifetimeHours: lifetimeHoursRaw
|
||||||
|
? parseInt(lifetimeHoursRaw, 10)
|
||||||
|
: undefined,
|
||||||
|
});
|
||||||
|
|
||||||
if (!existingConfig) {
|
if (result.status === "not_found") {
|
||||||
return c.text("Feed not found", 404);
|
return c.text("Feed not found", 404);
|
||||||
}
|
}
|
||||||
|
if (result.status === "expired") {
|
||||||
await emailStorage.put(
|
return c.text("Feed has expired and cannot be modified.", 403);
|
||||||
feedConfigKey,
|
}
|
||||||
JSON.stringify({
|
|
||||||
...existingConfig,
|
|
||||||
title: parsedData.title,
|
|
||||||
description: parsedData.description,
|
|
||||||
language: parsedData.language,
|
|
||||||
allowed_senders: parsedData.allowedSenders,
|
|
||||||
blocked_senders: parsedData.blockedSenders,
|
|
||||||
updated_at: Date.now(),
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await updateFeedInList(
|
|
||||||
emailStorage,
|
|
||||||
feedId,
|
|
||||||
parsedData.title,
|
|
||||||
parsedData.description,
|
|
||||||
);
|
|
||||||
|
|
||||||
return c.redirect("/admin");
|
return c.redirect("/admin");
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -409,7 +381,8 @@ feedsRouter.post("/:feedId/edit", async (c) => {
|
|||||||
feedsRouter.post("/:feedId/sender-filter", async (c) => {
|
feedsRouter.post("/:feedId/sender-filter", async (c) => {
|
||||||
const env = c.env;
|
const env = c.env;
|
||||||
const feedId = c.req.param("feedId");
|
const feedId = c.req.param("feedId");
|
||||||
const feedConfigKey = `feed:${feedId}:config`;
|
const id = FeedId.unchecked(feedId);
|
||||||
|
const repo = FeedRepository.from(env);
|
||||||
|
|
||||||
const body = await c.req.json().catch(() => null);
|
const body = await c.req.json().catch(() => null);
|
||||||
const parsed = senderFilterSchema.safeParse(body);
|
const parsed = senderFilterSchema.safeParse(body);
|
||||||
@@ -420,9 +393,7 @@ feedsRouter.post("/:feedId/sender-filter", async (c) => {
|
|||||||
const { action, value } = parsed.data;
|
const { action, value } = parsed.data;
|
||||||
const normalized = value.trim().toLowerCase();
|
const normalized = value.trim().toLowerCase();
|
||||||
|
|
||||||
const feedConfig = (await env.EMAIL_STORAGE.get(feedConfigKey, {
|
const feedConfig = await repo.getConfig(id);
|
||||||
type: "json",
|
|
||||||
})) as FeedConfig | null;
|
|
||||||
if (!feedConfig) return c.json({ ok: false, error: "Feed not found" }, 404);
|
if (!feedConfig) return c.json({ ok: false, error: "Feed not found" }, 404);
|
||||||
|
|
||||||
const allowedSenders = (feedConfig.allowed_senders || []).map((s) =>
|
const allowedSenders = (feedConfig.allowed_senders || []).map((s) =>
|
||||||
@@ -449,15 +420,12 @@ feedsRouter.post("/:feedId/sender-filter", async (c) => {
|
|||||||
|
|
||||||
if (!targetList.includes(normalized)) {
|
if (!targetList.includes(normalized)) {
|
||||||
targetList.push(normalized);
|
targetList.push(normalized);
|
||||||
await env.EMAIL_STORAGE.put(
|
await repo.putConfig(id, {
|
||||||
feedConfigKey,
|
...feedConfig,
|
||||||
JSON.stringify({
|
allowed_senders: allowedSenders,
|
||||||
...feedConfig,
|
blocked_senders: blockedSenders,
|
||||||
allowed_senders: allowedSenders,
|
updated_at: Date.now(),
|
||||||
blocked_senders: blockedSenders,
|
});
|
||||||
updated_at: Date.now(),
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.json({ ok: true });
|
return c.json({ ok: true });
|
||||||
@@ -465,20 +433,13 @@ feedsRouter.post("/:feedId/sender-filter", async (c) => {
|
|||||||
|
|
||||||
feedsRouter.post("/:feedId/delete", async (c) => {
|
feedsRouter.post("/:feedId/delete", async (c) => {
|
||||||
const env = c.env;
|
const env = c.env;
|
||||||
const emailStorage = env.EMAIL_STORAGE;
|
|
||||||
const feedId = c.req.param("feedId");
|
const feedId = c.req.param("feedId");
|
||||||
const view = c.req.query("view") === "table" ? "table" : "list";
|
const view = c.req.query("view") === "table" ? "table" : "list";
|
||||||
const wantsJson = (c.req.header("Accept") || "").includes("application/json");
|
const wantsJson = (c.req.header("Accept") || "").includes("application/json");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await deleteFeedFast(emailStorage, feedId);
|
await deleteFeedRecord(env, FeedId.unchecked(feedId), (p) =>
|
||||||
await removeFeedFromList(emailStorage, feedId);
|
waitUntilSafe(c, p),
|
||||||
|
|
||||||
waitUntilSafe(
|
|
||||||
c,
|
|
||||||
purgeFeedKeysStep(emailStorage, feedId, {
|
|
||||||
bucket: env.ATTACHMENT_BUCKET,
|
|
||||||
}),
|
|
||||||
);
|
);
|
||||||
|
|
||||||
if (wantsJson) {
|
if (wantsJson) {
|
||||||
@@ -513,11 +474,15 @@ feedsRouter.post("/:feedId/purge", async (c) => {
|
|||||||
? Number(body?.limit)
|
? Number(body?.limit)
|
||||||
: 100;
|
: 100;
|
||||||
|
|
||||||
const step = await purgeFeedKeysStep(emailStorage, feedId, {
|
const step = await purgeFeedKeysStep(
|
||||||
cursor,
|
emailStorage,
|
||||||
limit,
|
FeedId.unchecked(feedId),
|
||||||
bucket: env.ATTACHMENT_BUCKET,
|
{
|
||||||
});
|
cursor,
|
||||||
|
limit,
|
||||||
|
bucket: getAttachmentBucket(env),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
return c.json({
|
return c.json({
|
||||||
ok: step.failedKeys.length === 0,
|
ok: step.failedKeys.length === 0,
|
||||||
@@ -569,10 +534,14 @@ feedsRouter.post("/bulk-delete", async (c) => {
|
|||||||
const okIds: string[] = [];
|
const okIds: string[] = [];
|
||||||
const failures: Array<{ feedId: string; error: string }> = [];
|
const failures: Array<{ feedId: string; error: string }> = [];
|
||||||
const warnings: Array<{ feedId: string; warning: string }> = [];
|
const warnings: Array<{ feedId: string; warning: string }> = [];
|
||||||
|
const unsubscribeUrls: string[] = [];
|
||||||
|
|
||||||
for (const feedId of parsedFeedIds) {
|
for (const feedId of parsedFeedIds) {
|
||||||
try {
|
try {
|
||||||
const result = await deleteFeedFastDetailed(emailStorage, feedId);
|
const id = FeedId.unchecked(feedId);
|
||||||
|
// Read unsubscribe URLs before the feed metadata is deleted.
|
||||||
|
const urls = await collectUnsubscribeUrls(emailStorage, id);
|
||||||
|
const result = await deleteFeedFastDetailed(emailStorage, id);
|
||||||
if (!result.ok) {
|
if (!result.ok) {
|
||||||
failures.push({
|
failures.push({
|
||||||
feedId,
|
feedId,
|
||||||
@@ -591,6 +560,7 @@ feedsRouter.post("/bulk-delete", async (c) => {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
unsubscribeUrls.push(...urls);
|
||||||
okIds.push(feedId);
|
okIds.push(feedId);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error("Error bulk deleting feed", {
|
logger.error("Error bulk deleting feed", {
|
||||||
@@ -601,7 +571,18 @@ feedsRouter.post("/bulk-delete", async (c) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const deletedFeedIds = await removeFeedsFromListBulk(emailStorage, okIds);
|
const deletedFeedIds = await new FeedRepository(
|
||||||
|
emailStorage,
|
||||||
|
).removeFromListBulk(okIds);
|
||||||
|
if (deletedFeedIds.length > 0) {
|
||||||
|
await bumpCounters(emailStorage, {
|
||||||
|
feeds_deleted: deletedFeedIds.length,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (unsubscribeUrls.length > 0) {
|
||||||
|
waitUntilSafe(c, sendUnsubscribes(unsubscribeUrls, env));
|
||||||
|
}
|
||||||
|
|
||||||
const removed = new Set(deletedFeedIds);
|
const removed = new Set(deletedFeedIds);
|
||||||
okIds.forEach((feedId) => {
|
okIds.forEach((feedId) => {
|
||||||
@@ -637,11 +618,18 @@ feedsRouter.post("/bulk-delete", async (c) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const okIds: string[] = [];
|
const okIds: string[] = [];
|
||||||
|
const unsubscribeUrls: string[] = [];
|
||||||
|
|
||||||
for (const feedId of parsedFeedIds) {
|
for (const feedId of parsedFeedIds) {
|
||||||
try {
|
try {
|
||||||
const result = await deleteFeedFastDetailed(emailStorage, feedId);
|
const id = FeedId.unchecked(feedId);
|
||||||
if (result.ok) okIds.push(feedId);
|
// Read unsubscribe URLs before the feed metadata is deleted.
|
||||||
|
const urls = await collectUnsubscribeUrls(emailStorage, id);
|
||||||
|
const result = await deleteFeedFastDetailed(emailStorage, id);
|
||||||
|
if (result.ok) {
|
||||||
|
unsubscribeUrls.push(...urls);
|
||||||
|
okIds.push(feedId);
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error("Error bulk deleting feed", {
|
logger.error("Error bulk deleting feed", {
|
||||||
feedId,
|
feedId,
|
||||||
@@ -650,7 +638,18 @@ feedsRouter.post("/bulk-delete", async (c) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const deletedFeedIds = await removeFeedsFromListBulk(emailStorage, okIds);
|
const deletedFeedIds = await new FeedRepository(
|
||||||
|
emailStorage,
|
||||||
|
).removeFromListBulk(okIds);
|
||||||
|
if (deletedFeedIds.length > 0) {
|
||||||
|
await bumpCounters(emailStorage, {
|
||||||
|
feeds_deleted: deletedFeedIds.length,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (unsubscribeUrls.length > 0) {
|
||||||
|
waitUntilSafe(c, sendUnsubscribes(unsubscribeUrls, env));
|
||||||
|
}
|
||||||
|
|
||||||
return c.redirect(
|
return c.redirect(
|
||||||
`${redirectBase}&message=bulkDeleted&count=${deletedFeedIds.length}`,
|
`${redirectBase}&message=bulkDeleted&count=${deletedFeedIds.length}`,
|
||||||
|
|||||||
@@ -1,130 +0,0 @@
|
|||||||
import { FeedList, FeedListItem } from "../../types";
|
|
||||||
import { FEEDS_LIST_KEY } from "../../config/constants";
|
|
||||||
import { logger } from "../../lib/logger";
|
|
||||||
|
|
||||||
export async function deleteKeysWithConcurrency(
|
|
||||||
emailStorage: KVNamespace,
|
|
||||||
keys: string[],
|
|
||||||
concurrency: number,
|
|
||||||
): Promise<{ ok: string[]; failed: string[] }> {
|
|
||||||
const uniqueKeys = Array.from(new Set(keys.filter(Boolean)));
|
|
||||||
const ok: string[] = [];
|
|
||||||
const failed: string[] = [];
|
|
||||||
const limit = Math.max(1, Math.floor(concurrency) || 1);
|
|
||||||
|
|
||||||
for (let i = 0; i < uniqueKeys.length; i += limit) {
|
|
||||||
const batch = uniqueKeys.slice(i, i + limit);
|
|
||||||
const results = await Promise.allSettled(
|
|
||||||
batch.map((key) => emailStorage.delete(key)),
|
|
||||||
);
|
|
||||||
results.forEach((result, idx) => {
|
|
||||||
const key = batch[idx];
|
|
||||||
if (result.status === "fulfilled") {
|
|
||||||
ok.push(key);
|
|
||||||
} else {
|
|
||||||
failed.push(key);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return { ok, failed };
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function listAllFeeds(
|
|
||||||
emailStorage: KVNamespace,
|
|
||||||
): Promise<FeedListItem[]> {
|
|
||||||
try {
|
|
||||||
const feedList = (await emailStorage.get(FEEDS_LIST_KEY, {
|
|
||||||
type: "json",
|
|
||||||
})) as FeedList | null;
|
|
||||||
return feedList?.feeds || [];
|
|
||||||
} catch (error) {
|
|
||||||
logger.error("Error listing feeds", { error: String(error) });
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function addFeedToList(
|
|
||||||
emailStorage: KVNamespace,
|
|
||||||
feedId: string,
|
|
||||||
title: string,
|
|
||||||
description?: string,
|
|
||||||
): Promise<void> {
|
|
||||||
try {
|
|
||||||
const feedList = ((await emailStorage.get(FEEDS_LIST_KEY, {
|
|
||||||
type: "json",
|
|
||||||
})) as FeedList | null) || { feeds: [] };
|
|
||||||
|
|
||||||
feedList.feeds.push({ id: feedId, title, description });
|
|
||||||
await emailStorage.put(FEEDS_LIST_KEY, JSON.stringify(feedList));
|
|
||||||
} catch (error) {
|
|
||||||
logger.error("Error adding feed to list", { feedId, error: String(error) });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function updateFeedInList(
|
|
||||||
emailStorage: KVNamespace,
|
|
||||||
feedId: string,
|
|
||||||
title: string,
|
|
||||||
description?: string,
|
|
||||||
): Promise<void> {
|
|
||||||
try {
|
|
||||||
const feedList = ((await emailStorage.get(FEEDS_LIST_KEY, {
|
|
||||||
type: "json",
|
|
||||||
})) as FeedList | null) || { feeds: [] };
|
|
||||||
|
|
||||||
const feedIndex = feedList.feeds.findIndex((feed) => feed.id === feedId);
|
|
||||||
if (feedIndex !== -1) {
|
|
||||||
feedList.feeds[feedIndex].title = title;
|
|
||||||
feedList.feeds[feedIndex].description = description;
|
|
||||||
await emailStorage.put(FEEDS_LIST_KEY, JSON.stringify(feedList));
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
logger.error("Error updating feed in list", {
|
|
||||||
feedId,
|
|
||||||
error: String(error),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function removeFeedsFromListBulk(
|
|
||||||
emailStorage: KVNamespace,
|
|
||||||
feedIds: string[],
|
|
||||||
): Promise<string[]> {
|
|
||||||
try {
|
|
||||||
const feedList = ((await emailStorage.get(FEEDS_LIST_KEY, {
|
|
||||||
type: "json",
|
|
||||||
})) as FeedList | null) || { feeds: [] };
|
|
||||||
|
|
||||||
const toRemove = new Set(feedIds.filter(Boolean));
|
|
||||||
if (toRemove.size === 0) return [];
|
|
||||||
|
|
||||||
const removed: string[] = [];
|
|
||||||
const nextFeeds: FeedListItem[] = [];
|
|
||||||
|
|
||||||
for (const feed of feedList.feeds) {
|
|
||||||
if (toRemove.has(feed.id)) {
|
|
||||||
removed.push(feed.id);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
nextFeeds.push(feed);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (removed.length === 0) return [];
|
|
||||||
|
|
||||||
feedList.feeds = nextFeeds;
|
|
||||||
await emailStorage.put(FEEDS_LIST_KEY, JSON.stringify(feedList));
|
|
||||||
return removed;
|
|
||||||
} catch (error) {
|
|
||||||
logger.error("Error removing feeds from list", { error: String(error) });
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function removeFeedFromList(
|
|
||||||
emailStorage: KVNamespace,
|
|
||||||
feedId: string,
|
|
||||||
): Promise<boolean> {
|
|
||||||
const removed = await removeFeedsFromListBulk(emailStorage, [feedId]);
|
|
||||||
return removed.includes(feedId);
|
|
||||||
}
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user