Commit Graph
55 Commits
Author SHA1 Message Date
ksmithandClaude Sonnet 5.5 2a3e9f632e Make the banner and sidebar counts live on every page
One 5-minute poll (/new-since/) now drives the new-articles banner, the
tab dot and the sidebar counts, across all subscriptions rather than the
selected feed/tag. The banner lives in the base layout with a
server-rendered baseline id and reloads the current view on click; new
articles are never inserted automatically.

Sidebar counts are patched in place by the poll, and immediately after
reading or starring (HX-Trigger: countsChanged). Ingestion, filter rules
and subscription changes now drop the cached counts instead of waiting
out the TTL.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-03 07:39:36 -07:00
ksmithandClaude Sonnet 5.5 ac5e951749 Harden the login throttle and cache readiness aggregates (R2-S4, R2-C5; #36, #45)
S4: the throttle keyed on the first X-Forwarded-For entry, which a client
or a proxy that appends can choose, and disabled itself entirely when
Redis was down.

EVECTION_TRUSTED_PROXIES (IPs/CIDRs of your reverse proxy) makes it
strict: X-Forwarded-For is only believed when the TCP peer is a trusted
proxy, and the rightmost entry that isn't itself a trusted proxy — the
address the proxy actually saw — is used instead of the spoofable first
one. Unset keeps the previous behavior so existing installs don't
suddenly share one bucket behind a proxy, and `manage.py check --deploy`
warns (evection.W001) until it's set. During a Redis outage the throttle
now falls back to a bounded in-process limiter instead of switching off.

C5: /health/ready/ reuses its queue/feed aggregates for 15s
(EVECTION_HEALTH_CACHE_SECONDS) so a fast-polling monitor can't create
steady load; the database, Redis and poller probes stay live. Docs
cover both settings, restricting the endpoint at the proxy, and the
tombstone/purge behavior from the previous changes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 12:08:13 -07:00
ksmithandClaude Sonnet 5.5 aacb41d1d3 Purge the PWA page cache on every login/logout/expiry transition (R2-S3, #35)
The service worker cached authenticated pages in one origin-wide cache
and only purged it when the logout request itself passed through it —
not on session expiry, externally cleared cookies, or an account
switch, so a shared device could show the previous session's pages
offline.

Every HTML response now carries X-Evection-Auth: an opaque HMAC of the
user (or "anon"), via a small middleware. The service worker remembers
the marker its cached pages belong to and, whenever a navigation brings
a different one, deletes the pages cache before storing anything; "anon"
responses (the login page) are never cached. So the cache always holds
exactly one session's pages, and any transition the worker can observe
online clears it. (What no design can detect is a session ending while
the device stays offline.)

Verified in a real browser: pages cached after login; expiring the
session server-side (no logout request) and loading a page left the
cache deleted and the marker "anon"; logging in as a second user
afterward cached only that user's pages, none of the first user's.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 12:05:45 -07:00
ksmithandClaude Sonnet 5.5 91a4c360a4 Retry transient fetch failures promptly instead of waiting a poll interval (R2-T5, #41)
An unexpected exception while fetching was recorded and re-raised, then
the feed waited for its next scheduled poll — which under error backoff
can be hours — even for a locked SQLite file or a dropped database
connection that clears in seconds.

fetch_feed now retries OperationalError/InterfaceError up to three times
with doubling delays (30s, 60s, 120s), holding the feed's claim so the
poller can't also fetch it and without counting it against the feed.
Anything else, and a transient error after the retries are spent, keep
the existing path: record the error, back off, release the claim,
re-raise. Time limits are unchanged.

Verified with a real Celery worker against a real Redis broker, with
the fetch rigged to fail twice: retries fired after 1s and 2s (delays
shortened for the probe), the third attempt succeeded, and the feed
ended healthy, unclaimed and scheduled. (Celery's eager test mode
mishandles retries, so the unit tests mock retry() and assert the
countdowns, claim and error-count behavior instead.)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 12:04:01 -07:00
ksmithandClaude Sonnet 5.5 d6e310b127 Make the Postgres search migration online-safe (R2-T3, #39)
One migration did a full-table UPDATE, a blocking GIN build and the
trigger install together — long locks and a deploy that could outlast
its health-check window on a large archive.

Now two stages. 0002 only adds the nullable column and the trigger
(metadata-only; new and updated rows get a vector from then on). 0003
is non-atomic: it backfills in 5,000-id batches, each its own short
transaction and only touching rows still NULL, then builds the index
with CREATE INDEX CONCURRENTLY (dropping a stale INVALID one from a
failed earlier run first). Re-running is safe, and it's a cheap no-op on
an install that applied the earlier single-step version.

Measured on a real PostgreSQL 16 with 150,000 existing articles while a
second connection kept inserting/updating: the migration took ~20s, the
slowest concurrent write was 37ms (nothing blocked), no NULL vectors
remained, the index was valid, and unapply/re-apply worked. Full suite
passes on Postgres.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 12:02:20 -07:00
ksmithandClaude Sonnet 5.5 72bffbe97f Expire purge tombstones and time-box the retention purge (R2-T2, R2-T4; #38, #40)
Tombstones were kept forever, so enabling retention left a permanent row
per deleted article. They now expire after 365 days (cleaned up by the
same nightly task, even when retention is off); the documented price is
that an entry a feed still lists after a year, with no or a recent
publish date, can reappear.

The purge looped until every eligible row was gone with no run budget.
A run now works for at most four minutes, then queues a continuation, so
a huge first purge can't monopolise a worker or starve polling; hard
time limits back that up, and each chunk is its own transaction so an
interrupted run just resumes. Adds indexes on Article.fetched_at and
PurgedArticle.purged_at for the scans these do.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 12:00:52 -07:00
ksmithandClaude Sonnet 5.5 2e1c0e31a8 Pin feed connections to the address that was validated (R2-S2, #34)
The SSRF guard checked that a hostname resolved to public addresses,
then let requests resolve it again to connect — so a DNS answer that
changed in between (DNS rebinding) could point the connection at an
internal address.

Connections now go through a pinned adapter whose socket factory
resolves, checks and connects inside one function: whatever the name
resolves to at connect time is what gets validated and used. Only the
socket is replaced, so TLS still verifies against the original
hostname. The up-front validate_fetch_url check stays as defense in
depth. Tests cover a rebinding answer at connect time being refused and
a real loopback round trip with the original Host header preserved;
checked live: a real HTTPS feed fetches, 127.0.0.1/169.254.169.254/
localhost are blocked, and a wrong-hostname certificate is still
rejected.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 12:00:03 -07:00
ksmithandClaude Sonnet 5.5 698940763f Bound OPML uploads in size, depth, count and broker payload (R2-S5, #37)
An OPML upload was read fully into memory, parsed into a whole tree,
walked recursively, and (for large imports) embedded in a Celery
message. Nothing bounded raw size, ZIP entries, nesting depth, outline
count or feed count.

Uploads are capped at 5 MB (checked on the reported size before reading)
and ZIPs at 50 entries, with the decompressed member bounded by what it
actually yields rather than only its header. Parsing now streams with
iterparse and aborts the moment a limit is crossed — 24 levels deep,
20,000 outlines, 5,000 feeds — so a hostile file never builds a huge or
deep tree; a 50,000-level nesting bomb is rejected cleanly. Limit errors
are shown to the user. Large imports go to the worker by cache reference
(deleted once read, expires after an hour) instead of as the whole
document inside the broker message.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 11:58:49 -07:00
ksmithandClaude Sonnet 5.5 41f99e9405 Allow only http(s) URLs from feeds and OPML, at storage and render (R2-S1, #33)
A feed's channel link, an entry's link and an OPML htmlUrl were stored
as given and rendered in href attributes (bulk writes skip model
validation), so a malicious feed could supply a javascript: or data:
link. CSP is a second layer, not the control.

apps.core.urlutils accepts only absolute http(s) URLs. Fetching stores
channel/entry links through it — relative links now resolve against the
feed's own URL instead of being stored as dead relative paths — OPML
import skips non-http(s) feed URLs and blanks unsafe htmlUrl, and the
add-feed form rejects non-http(s) (URLField also allows ftp). A
safe_http_url template filter guards the two places a feed-supplied URL
becomes a link (the article's "Original" link and the dashboard), so
values already in the database from before this fix are neutralized too.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 11:57:23 -07:00
ksmithandClaude Sonnet 5.5 85914f9107 Route every feed fetch through one atomic claim (R2-T1, #32)
Adding a feed and the admin retry queued fetch_feed directly without
claiming the feed, so the periodic poller (which sees a never-fetched
or just-reset feed as due) could claim and fetch it too: duplicate
fetches, and one task overwriting another's claim/ETag/next-fetch state.
The retry path also queued the backoff reset and the fetch as two
independent tasks that could run in either order.

claim_feed/enqueue_fetch in apps.feeds.tasks are now the only way a
fetch gets dispatched — the poller, add-feed and retry all use them, so
a feed can only have one fetch in flight. If queueing fails the claim is
released (the poller recovers it), and add-feed still saves the
subscription during a broker outage. The retry resets backoff
synchronously before claiming, and says so when a fetch is already
running.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 11:56:23 -07:00
ksmithandClaude Sonnet 5.5 0975a7634b Mark the browser tab with a red dot when new articles arrive (#31)
The in-page "new articles" banner is invisible from a background tab.
Every authenticated page now polls a small JSON endpoint
(reader:new_since, every 30s) and redraws the tab's favicon with a red
dot when unread, non-hidden articles from the user's feeds have
appeared since the page loaded. A reload (which is what clicking the
banner does) resets the baseline and the icon.

The endpoint is deliberately not scoped to the stream's current
filter/tag/feed, so the tab lights up for anything new whichever page
is open. Scope is the dot only: no desktop notifications, per the
request. Verified in a dev server enforcing the production CSP: the
icon swapped to the dotted version after a new article arrived and
reset on reload.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 10:18:29 -07:00
ksmithandClaude Sonnet 5.5 fd494a9c08 Make the readiness check catch fetching that is scheduled but failing (#27)
/health/ready/ proved beat and a worker were alive but not that
fetching worked: every feed could be failing, or the queue could be
hours behind, and it would still report ok.

apps.core.health adds three checks: Celery queue depth (real Redis list
length, over 1000 fails), a successful fetch within three poll intervals
(30 min minimum, with a grace period for a brand-new install), and the
share of active feeds failing (over half, once there are at least four).
The payload also reports queue depth, active/failing feed counts, and
the age of the last successful fetch. Verified against real Redis with
queued Celery tasks, and the suite on PostgreSQL. docs/install.md lists
each check.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 09:30:00 -07:00
ksmithandClaude Sonnet 5.5 f8cd1eb33e Stop retention from bringing deleted articles back (#29)
The nightly purge deleted articles, but a feed that still listed an
entry would re-insert it on its next poll as a brand-new, unread
article. For feeds with long archives, old items could reappear after
every retention run.

The purge now leaves a (feed, guid) tombstone per deleted article, and
ingestion skips tombstoned guids. With retention on, entries whose own
publish date is already outside the window are not ingested at all, so
a long archive isn't fetched only to be purged and tombstoned the same
night. Undated entries rely on the tombstone.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 09:30:00 -07:00
ksmithandClaude Sonnet 5.5 6c6227af57 Treat an article with no publish date as published when we fetched it
Feeds that give no publish date left the row with no time at all and
grouped the article under "Undated". The stream's sort order already
fell back to fetched_at; the list row, its date-group header, and the
open article's header now use the same fallback. The article's own
published_at stays empty — nothing is invented in the database, so a
later refetch can't see a spurious change.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 09:14:09 -07:00
ksmithandClaude Sonnet 5.5 7afda7d0ba Fix inline article expand and back-to-stream scope in production
Clicking an article title opened the detail page instead of expanding
it inline, and "Back to stream" then reset to every feed. Cause: the
title (and the new-articles banner) used inline onclick= handlers,
which production's CSP (script-src 'self') blocks — dev sends no CSP,
so it worked there. The title link just fell through to its href.

Behavior moves to delegated listeners in static/js/stream.js (modified
clicks still open in a new tab). A test now fails if any template gains
an inline on*= handler. The stream also passes its filter/tag/feed
scope through the article link so the detail page's back link returns
to it. Verified in a dev server enforcing the same CSP: title click
expands and collapses in place, URL unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 09:02:51 -07:00
ksmithandClaude Sonnet 5.5 37e658c49a Add configurable article retention (C7)
Articles and full HTML bodies accumulated forever, growing the
database, search index, and backups without bound. Site settings gets
a "Retention days" field (0, the default, keeps everything); a nightly
beat task deletes articles fetched longer ago than that in bounded
chunks, always keeping anything a user starred or saved for later.
Read state and tags cascade with the article and the FTS triggers drop
search entries. The dashboard shows the article count and oldest
article's age, and docs/install.md covers retention, the readiness
check, and SQLite's WAL tuning.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 08:51:20 -07:00
ksmithandClaude Sonnet 5.5 e5f1277014 Batch feed ingestion, add a readiness check, fail open without Redis (C2, C8)
Ingestion did a get_or_create per entry. It now prefetches existing
articles for the poll in one query, bulk-inserts new ones and
bulk-updates changed ones (falling back to row-by-row only if a
concurrent fetch wins a race), and dispatches rule evaluation in
bounded chunks so a huge first fetch is several small tasks.

/health/ stays a DB-only liveness check (upgrade.sh gates on it right
after restart). New /health/ready/ also checks Redis and that
poll_due_feeds ticked within five minutes — proving beat and a worker
are both alive — and returns 503 with per-check detail otherwise.

The sidebar unread-count cache and login throttle now degrade instead
of erroring when Redis is unreachable: every authenticated page and
every login would otherwise 500 during a cache outage. Found while
verifying in a sandbox with no Redis.

Also includes the dashboard's oldest-article metric (core/views.py).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 08:51:20 -07:00
ksmithandClaude Sonnet 5.5 8d2900424a Use keyset pagination for the stream (C4)
The stream did a COUNT(*) and OFFSET slice on every request, ordered by
a non-unique (published_at, fetched_at) — deep pages got slower and
articles sharing a timestamp could repeat or vanish across pages.

It now orders by (Coalesce(published_at, fetched_at), id) and pages with
before/after cursors, fetching one extra row to know whether another
page exists instead of counting. Pagination links also keep the feed
scope, which the old links silently dropped.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 08:51:20 -07:00
ksmithandClaude Sonnet 5.5 70b0d4f277 Index Postgres search and harden SQLite search/concurrency (C5, C6)
Postgres recomputed a tsvector over every article's full text on every
search. A migration now adds a stored, GIN-indexed search_vector column
kept current by a trigger (so no ingest/update path can forget it), and
the backend reads that column. Untested here: no Postgres in the dev
sandbox, so the SQL is reviewed but not executed — worth one run of the
(skipped-on-SQLite) Postgres test module against a real instance.

SQLite search built one bound parameter per subscribed feed, so enough
feeds would exceed the variable limit, and the OperationalError was
swallowed into "no results". It now scopes through a subquery on
Subscription and logs failures. SQLite connections also get WAL mode,
a 20s busy timeout, and IMMEDIATE transactions so gunicorn, Celery, and
the FTS triggers stop tripping over each other.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 08:51:20 -07:00
ksmithandClaude Sonnet 5 cb0ce5a336 Batch rule/tag lookups and index FilterRule for the ingest query (C9)
FilterRule had no indexes beyond the default primary/foreign-key ones,
and apply_filter_rules_for_feed issued 2 queries per subscriber (its
enabled rules, its subscription tags) inside a loop over every
subscriber of the feed — both cost grew with subscriber/rule count on
every single feed poll.

Adds a composite index on (user, is_enabled, priority), matching the
exact filter+order shape every caller already uses (this task,
apps.rules.tasks' backlog re-apply). apply_filter_rules_for_feed now
fetches rules and subscription tags once for the whole feed's subscriber
set, grouped by user/subscription in Python, instead of once per
subscriber.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-31 16:09:36 -06:00
ksmithandClaude Sonnet 5 abf4cef55b Cache sidebar unread counts for a short TTL (C3)
apps.core.context_processors.sidebar runs on every authenticated page
render and called unread_counts_by_feed, a join/group-by over the
user's whole article corpus, every single time — cost grew with the
archive's size regardless of which page was being viewed.

unread_counts_by_feed now caches its {feed_id: count} result per user
for 30 seconds (apps.core.cache_utils). The reader views that change
the current user's own read state (toggle_read, mark_all_read, viewing
an article) invalidate it immediately so the sidebar never visibly lags
behind the action that just caused it; other paths (rule-driven state
changes during background ingestion) aren't explicitly invalidated and
simply self-heal within the TTL, which is an acceptable tradeoff
already made elsewhere in this app (the stream's own "new articles"
banner polls on the same 30s cadence).

Also adds a global cache.clear() autouse fixture (conftest.py) — the
test CACHES backend (LocMemCache) lives in process memory and survives
Django's per-test DB rollback, so a cached count keyed by a user's pk
could otherwise leak into an unrelated later test reusing that pk.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-31 16:09:28 -06:00
ksmithandClaude Sonnet 5 b33fe905d2 Push due-feed scheduling into an indexed DB query (C1)
poll_due_feeds loaded every active feed's timing fields and recomputed
each one's error-backoff due-ness in Python on every beat tick (every
1-2 minutes) — scheduler CPU and DB reads grew linearly with total feed
count regardless of how many were actually due.

Feed.next_fetch_at (indexed together with is_active) is now set by
fetch_feed itself right after every fetch attempt, success or error,
using the same backoff formula that used to run per-feed in
poll_due_feeds. The scheduler's query is now a direct indexed range
scan (next_fetch_at <= now), ordered so the most overdue feeds claim
first, and bounded to POLL_BATCH_SIZE so a large backlog spreads across
several ticks instead of dispatching everything at once. A migration
backfills next_fetch_at for existing feeds using the same formula.
reset_feed_backoff also clears next_fetch_at so a manually-reset feed
is immediately due again, matching its prior behavior.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-31 16:09:18 -06:00
ksmithandClaude Sonnet 5 03dd37e69d Notify the open stream when new articles arrive
The stream had no way to learn about articles the background poll
ingested while the page was open — only a manual reload or navigation
ever picked them up.

Adds a lightweight "N new articles — click to show" banner: the stream
records the highest article id in its current scope (filter/tag/feed)
when rendered, and an htmx poll every 30s checks reader:check_new for
anything newer in that same scope. It never swaps the list out from
under you mid-read — clicking the banner is what actually reloads it.
id, not published_at, is the cursor, since a feed can backdate an
entry's published date below everything currently on screen while it's
still genuinely new to this stream.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-31 15:04:55 -06:00
ksmithandClaude Sonnet 5 17e7f63e61 Update link/author/summary/published_at on refetch, not just title (T6)
A changed guid's article only ever had its title/content_html/
content_hash refreshed on a subsequent poll — legitimate feed edits to
an entry's link, author, summary, or publication date were silently
ignored forever, which can affect navigation, ordering, and rules that
key off those fields.

content_hash is now computed over every mutable field feedparser gives
us for an entry (title, link, author, summary, content_html,
published_at), and all of them are written together when the hash
changes. Per-user read/star state is untouched either way, same as
before.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-31 14:44:15 -06:00
ksmithandClaude Sonnet 5 0bfe9c8076 Enqueue the initial feed fetch instead of running it inline (T3)
add_feed ran fetch_and_ingest synchronously during the POST request, so
a slow or large feed tied up a Gunicorn worker for the duration of the
fetch (up to the 15s HTTP timeout, plus parse/ingest time) and a user
could repeat it with distinct URLs to reduce request capacity.

The subscription is now created synchronously as before, but the first
fetch is dispatched via fetch_feed.delay() — the same task the periodic
poll uses, so the save/error bookkeeping is unchanged. The user sees an
immediate redirect with a message that the fetch is in progress rather
than waiting on it in the request/response cycle.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-31 14:44:09 -06:00
ksmithandClaude Sonnet 5 7bb981b545 Rebuild stream date-group headers in the viewer's local timezone
The server still groups articles into "Received today/yesterday/<date>"
headers using UTC, so an article published near UTC midnight could land
in a mismatched day group. Each article row now ships its raw UTC
instant (data-published-utc); static/js/date-groups.js discards the
server-rendered headers on load and rebuilds them using the browser's
own local calendar day, same approach as the article-time localization
this follows up on.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-31 14:36:27 -06:00
ksmithandClaude Sonnet 5 90837b339c Make the Site settings admin page go straight to the edit form
It's a true singleton, not a collection, so the normal changelist (an
"Add" link, a list with 0 or 1 rows, an extra click to get to the one
row) was just friction — and visually inconsistent with every other
app's admin section, which do show an "Add" link. The changelist view
now redirects straight to the single row's change form (creating it
first if this is a fresh install), and "Add" is never offered at all.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-31 13:23:47 -06:00
ksmithandClaude Sonnet 5 dc8b9ff83b Make the feed-poll interval site-wide instead of per-feed
Replaces Feed.fetch_interval_minutes with a single admin-editable
SiteSettings.fetch_interval_minutes (apps.core), following the same
singleton-row pattern as accounts.SetupLock. Per-feed error backoff is
unchanged — only the configured baseline interval is now shared across
every feed, loaded once per poll_due_feeds run rather than queried per
feed. EVECTION_MIN_FETCH_INTERVAL_MINUTES keeps working as the floor
underneath it.

SiteSettings is registered in Django admin as a singleton: "Add" is
only offered when no row exists yet, and delete is always refused.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-31 12:59:47 -06:00
ksmithandClaude Sonnet 5 a1ea2e5662 Add login rate limiting (S6)
Django's default LoginView had no throttle — an internet-facing
instance was exposed to unlimited password-guessing/credential-
stuffing attempts. apps.accounts.views.LoginView adds two independent,
Redis-cache-backed throttles (shared across all gunicorn workers,
unlike the per-process default LocMemCache): by client address (catches
one attacker spraying many usernames) and by the submitted username
(catches a distributed attack on one specific account). Either blocks
further attempts for a 5-minute window; both are generous enough not
to lock out a user who's just mistyped their own password a few times.

Client address prefers X-Forwarded-For's first hop, falling back to
REMOTE_ADDR — the same reverse-proxy trust boundary config.settings.prod
already relies on for X-Forwarded-Proto (gunicorn is never meant to be
reachable except through that proxy).

CACHES now points at Redis (already a hard install requirement for
Celery) instead of Django's implicit per-process default, since the
whole point is a shared counter across every gunicorn worker; test
settings override it back to LocMemCache so the suite doesn't need a
real Redis instance.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-31 12:46:49 -06:00
ksmithandClaude Sonnet 5 9241a54958 Cap entries per poll and stored content size (T4)
ssrf_guard.MAX_RESPONSE_BYTES (S1) already bounds the raw download, but
a feed within that byte cap can still carry an unreasonable number of
entries, or one entry with an unreasonably large body — both cost real
CPU/DB time (nh3 sanitization, an Article row/UPDATE) per entry.
fetch_and_ingest now processes at most MAX_ENTRIES_PER_POLL (200)
entries per poll (logging a warning when truncated) and sanitize_html
bounds both its input (sanitizer cost) and output (what's actually
stored/rendered) length.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-31 12:46:40 -06:00
ksmithandClaude Sonnet 5 64f25789f5 Isolate unexpected fetch failures and harden task durability (T2)
fetch_feed had no time limit and no handling for anything beyond the
network/parse errors fetch_and_ingest already catches internally — an
unexpected exception (a parser/sanitizer bug, a DB error) crashed the
task with no error recorded on the Feed, the claim left held for the
full CLAIM_STALE_MINUTES, and no visibility beyond a bare traceback.
fetch_feed now catches that, records it the same way a handled failure
would be (reusing fetcher.record_fetch_error, promoted from a private
helper), clears the claim, and re-raises so Celery still marks the task
FAILED. soft_time_limit/time_limit bound a single fetch that somehow
outruns FETCH_TIMEOUT_SECONDS + ssrf_guard's response cap during
parsing/ingestion.

Also: a worker process killed mid-task (OOM, deploy restart, crash)
previously lost that task silently — Celery's default is to ack a
message the moment a worker *starts* it. CELERY_TASK_ACKS_LATE +
CELERY_TASK_REJECT_ON_WORKER_LOST (config/settings/base.py) make the
message redeliverable instead, and CELERY_WORKER_PREFETCH_MULTIPLIER=1
keeps a worker from grabbing a batch of tasks it could lose all at once.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-31 12:46:29 -06:00
ksmithandClaude Sonnet 5 e760eeda1d Show each tag's total unread count and remember collapsed sections
Closes gitea#24: the sidebar's per-feed unread counts were already
computed by sidebar() (apps.core.context_processors); each tag group's
total is now the sum of its own feeds' counts (a feed can carry more
than one tag, so this reuses the same per-feed data rather than a
second query) and renders next to the tag name like a feed's own
count.

Closes gitea#25: each sidebar <details> section (one per tag, plus
"Untagged") now carries a stable data-sidebar-key, and
static/js/sidebar-state.js remembers which ones are collapsed in
localStorage — this isn't a SPA, so every click re-renders the sidebar
server-side, and previously every section reset back to expanded on
the next page load. Per-browser, same pattern as theme.js/theme-init.js,
not synced across devices/accounts.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-31 12:34:57 -06:00
ksmithandClaude Sonnet 5 9439f9cc59 Add SSRF protection to feed fetching: validate scheme/address, bound redirects and response size (S1)
fetch_and_ingest fetched a feed_url supplied straight from the "add
feed" form or an uploaded OPML file, with requests following redirects
on its own and no check that the target (or a redirect's target) was
actually a public, fetchable feed rather than an internal service,
localhost, or a cloud metadata endpoint — reachable from wherever this
app runs, on any authenticated user's behalf.

apps.feeds.services.ssrf_guard.safe_get() replaces the direct
requests.get() call: it resolves and validates the hostname (rejecting
anything that isn't a globally routable address) before the initial
request and before following each redirect hop manually, caps the
number of hops, and bounds the response body size by streaming it
instead of buffering it unbounded. OPML-imported feeds go through the
same check the first time poll_due_feeds fetches them, since this is
the one chokepoint every feed URL passes through regardless of which
path created the Feed row.

Known residual gap, documented in ssrf_guard.py: this validates then
connects rather than pinning the TCP connection to the exact address it
validated, so a narrow DNS-rebinding race isn't closed. Fixing that
needs a custom transport and felt like more machinery than this
self-hosted app's threat model currently justifies.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-31 12:25:20 -06:00
ksmithandClaude Sonnet 5 fd8eeb605e Scope backlog re-apply per-feed and always queue it through Celery (T5, S5)
Completes the T5 fix: reapply_rules_for_user_backlog now computes each
feed's subscription-tag ids up front and passes them to
evaluate_rules_for_article per article, so a feed/tag-scoped rule from
a different feed can't fire on this backlog (see the previous commit's
rule_in_scope() in apps.rules.engine).

Also completes S5's second half: the "Re-apply" view now always
dispatches reapply_rules_for_user.delay() instead of calling the
backlog function inline from the request — a large backlog or a
regex that outruns the new timeout guard no longer risks tying up a
web worker.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-31 12:20:25 -06:00
ksmithandClaude Sonnet 5 91c0b1dd26 Centralize rule feed/tag scoping in the engine and fix backlog re-apply (T5)
reapply_rules_for_user_backlog narrowed its *backlog* to the triggering
rule's feed/tag scope, but then loaded every enabled rule for the user
and ran all of them against that backlog with no per-rule scope check
— so re-applying one feed- or tag-scoped rule could also fire an
unrelated rule scoped to a different feed/tag, if it happened to match.

rule_in_scope() moves the feed/tag scope check into the engine itself
(apply_filter_rules_for_feed already computed this per-subscription via
query filters; it now just passes the tag ids and lets the engine
decide), so backlog re-apply and ingest-time dispatch can't drift into
scoping rules differently again.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-31 12:19:56 -06:00
ksmithandClaude Sonnet 5 b7d9ee672c Add an atomic per-feed claim to poll_due_feeds (T1)
poll_due_feeds scanned for due feeds and dispatched fetch_feed without
marking them claimed, so overlapping beat ticks or a slow-running
fetch could dispatch the same feed twice, racing on ETag/status/error-
count writes. Feed.claimed_at is now set via an UPDATE ... WHERE
claimed_at IS NULL OR claimed_at < stale-cutoff, so only one caller's
UPDATE can ever match a given row; fetch_feed clears it when done.
A claim older than CLAIM_STALE_MINUTES is treated as abandoned so a
worker dying mid-fetch doesn't wedge the feed forever.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-31 12:03:18 -06:00
ksmithandClaude Sonnet 5 d7b433e580 Purge the service worker's authenticated-page cache on logout (S3)
PAGES_CACHE held every cached navigation response (including
authenticated article pages) with no logout-time purge, so a later
offline navigation on a shared or account-switched device could still
serve another user's cached pages. Logout is a plain POST, so the
fetch handler now special-cases that request: it deletes PAGES_CACHE
and lets the real logout request through, with no race against the
navigation that follows since it's synchronous with the same request.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-31 12:03:10 -06:00
ksmithandClaude Sonnet 5 b52ba2be8a Make first-run setup race-safe with an atomic SetupLock claim (S4)
The setup view's User.objects.exists() check and the admin account's
save() weren't in the same transaction, so two concurrent requests
during first deployment could both pass the check and both create an
admin account. SetupLock is a singleton row (pk=1); claiming it and
creating the admin now happen in one atomic block, so only the first
of any racing requests can succeed — the rest hit IntegrityError and
are sent to the login page instead.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-31 12:03:05 -06:00
ksmithandClaude Sonnet 5 2e4674a18f Make the updater deploy tagged releases, like ds-chat's upgrade.sh
scripts/upgrade.sh now fetches tags and does a detached-HEAD checkout of
the latest one (git tag --sort=-creatordate | head -n1), matching the
ds-chat project's deploy/upgrade.sh exactly rather than a plain git pull
on whatever branch happened to be checked out. Errors clearly if the repo
has no tags yet (true for Evection right now — nothing to deploy until a
release is tagged and pushed), and no-ops cleanly if already on the
latest tag. scripts/install.sh does the same tag pin on first install
(falling back to whatever's checked out if no tags exist yet), so the
very first deploy is consistent with every upgrade after it.

Added a GET /health/ endpoint (apps.core.views.health) that checks DB
connectivity and is exempt from the first-run setup redirect, for the
upgrade script's post-restart verification (curled over the gunicorn
unix socket, same as ds-chat's curl-based check) and for any external
uptime monitor.

While wiring the setup-wizard exemption for /health/, found that
SetupWizardMiddleware._a_user_exists's reset fixture was scoped only to
apps/accounts/tests.py, so a test anywhere else that creates a user and
makes a request could leak a stale "a user exists" into later test files
with no reset — confirmed this concretely by temporarily breaking the new
exemption and watching the "works before setup" test still pass purely
from accounts/tests.py leaving the module-order-adjacent apps/articles
tests to poison the shared class attribute. Moved the fixture to a new
top-level conftest.py so it's autouse across every test file, which also
makes the new health-check test meaningful regardless of run order.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-30 22:15:37 -06:00
ksmithandClaude Sonnet 5 1a8ae95db0 Fix logout 405 — Django's LogoutView only accepts POST
The sidebar's "Log out" was a plain <a href> GET link. Django 5's
LogoutView stopped accepting GET (CSRF hardening — a bare link or even an
<img> tag could otherwise log someone out), so clicking it 405'd instead
of logging out. Changed it to a POST form, matching every other
state-changing action in the sidebar/app (unsubscribe, delete tag, etc.).

Extended .sidebar-top-nav's styling to cover a <button> the same as an
<a>, so the form-submit button looks identical to the other nav items.

No existing test exercised logout at all — added one for the POST case
and one confirming GET now correctly 405s, then verified end-to-end
against the running dev server (login, POST /logout/, confirm the session
is gone).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-30 22:01:06 -06:00
ksmithandClaude Sonnet 5 f818b11041 Accept a FreshRSS "Export" .zip directly for OPML import
FreshRSS's Export feature produces a .zip (an .opml.xml plus a starred-
articles .json this app doesn't import) rather than a bare .opml file —
uploading that zip as-is failed with "That file doesn't look like a valid
OPML export" since defusedxml can't parse a zip as XML.

apps.feeds.opml.extract_opml_bytes detects a zip upload and pulls the
.opml/.opml.xml member out of it before parsing; a bare .opml upload is
returned unchanged, so existing behavior is untouched. Verified against
the reporter's actual FreshRSS export (18 feeds across 6 categories) both
directly through extract_opml_bytes/parse_opml and as a real upload
through the running app.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-30 21:45:16 -06:00
ksmithandClaude Sonnet 5 753ae9efc7 Make Starred and Saved-for-later pre-configured system tags
UserArticleState.is_starred/is_saved_for_later/starred_at are gone —
starring and saving now add/remove an ArticleTag against a per-user
"Starred" / "Saved for later" Tag, created lazily on first use and marked
Tag.is_system=True. is_read/is_hidden stay on UserArticleState since
they're genuine reading state, not categorization, which is what made
these two candidates for unifying into the general tag mechanism.

System tags are excluded from the Manage Tags page and from delete_tag
(get_object_or_404 now requires is_system=False, so attempting to delete
one 404s) and from the subscription-tag autocomplete, since they
categorize articles, not feeds. The star/save icons are still exactly
where they were — this only changes what powers them.

apps.rules.engine's star action now does get_system_tag + ArticleTag.
get_or_create instead of setting a boolean field. A data migration
converts every existing is_starred=True/is_saved_for_later=True row into
its ArticleTag equivalent before the fields are dropped — verified by
seeding the pre-removal schema directly (including a row with both flags
set) and confirming the migration produces the right tags.

apps.articles.queries.with_user_state gained one more query (tag lookup
for the current page's articles) to stay in the same "fixed number of
queries regardless of article count" shape it already had.

Verified end to end against a running dev server: toggling star/saved,
the starred/saved filters, the sidebar's Favourites count, and that the
Starred tag doesn't appear on the Manage Tags page.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-30 21:36:44 -06:00
ksmithandClaude Sonnet 5 0e132e9ab9 Remove folders; feeds are organized by tags now
Folders are gone — organization is tags-only, via the SubscriptionTag
model added last commit. A migration converts every existing Folder into
a same-named Tag applied to its feeds, and every folder-scoped FilterRule
into an equivalent tag-scoped one, before the Folder table is dropped, so
upgrading an existing instance loses nothing (verified by seeding the
pre-removal schema directly and running the migration chain against it).

Unlike folders, a feed can carry more than one tag, so:
- apps.articles.tasks.apply_filter_rules_for_feed and apps.rules.tasks's
  backlog re-apply now scope by "does this feed carry tag X" rather than
  "does this feed belong to folder X".
- apps.feeds.opml: a feed's tags export as a comma-separated "category"
  attribute (the standard OPML way to represent multiple categories)
  instead of nesting under one folder outline. Import reads both that
  attribute and nested category outlines, turning each enclosing level
  into its own tag rather than collapsing to the nearest one.
- The sidebar groups feeds by tag instead of folder, so a feed with two
  tags now appears in both groups; untagged feeds fall into "Untagged".

AddFeedForm gained a comma-separated tag_names field for parity with the
old add-time folder picker. EditSubscriptionForm dropped its folder
field entirely — tagging a subscription happens through the tag editor
already on that page.

Verified end to end: the migration chain from empty, the data migration
against a seeded pre-removal schema (folder/subscription/rule all convert
correctly), and the running app's sidebar grouping, OPML export category
attributes, and tag editor.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-30 21:30:06 -06:00
ksmithandClaude Sonnet 5 3b58fdcb7e Add subscription editing, feed-level tags, and a remembered stream filter
Subscription editing was a real gap: there was no way to rename a feed's
display title, move it between folders, or create a folder at all outside
OPML import. Added an edit page (apps/feeds/views.py:edit_subscription,
EditSubscriptionForm) reachable from the subscriptions list.

Added feed-level tagging via a new SubscriptionTag model (apps/articles/
models.py), mirroring the existing ArticleTag — tag a whole feed on its
edit page, and every one of its articles surfaces under that tag in the
stream alongside individually-tagged articles (apps.reader.views._apply_
scope now matches either). Renamed AddTagToArticleForm to AddTagForm
since it's shared by both now.

The stream also now remembers the last filter (unread/all/starred/saved)
in the session instead of always defaulting to "unread" when a sidebar
feed/folder/tag link omits ?filter= — sidebar links no longer force
?filter=all, letting the remembered choice apply.

Verified end to end against a running dev server: editing a subscription's
title/folder, creating a folder inline, tagging a feed and seeing its
articles appear under that tag, and the remembered-filter behavior across
requests with no ?filter= param.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-30 21:20:37 -06:00
ksmithandClaude Sonnet 5 cfa64b5485 Rebuild the reader UI to match FreshRSS's two-column layout
The previous UI was plain unstyled lists. Rebuilt around what FreshRSS
actually looks like (per reference screenshots): a persistent left sidebar
(folders/feeds with unread counts, favourites, tags) and a single main
column with a date-grouped article list, where clicking a title expands
the full article inline in place rather than navigating to a separate page.

- apps/core/context_processors.py: feeds the sidebar's folder/feed tree,
  tags, and starred count to every authenticated page in one shared query
  set, so base.html can render it without each view wiring it up.
- apps/reader/views.py: date-grouped stream (itertools.groupby over the
  already-ordered queryset), ?feed=/?folder= scoping alongside the existing
  ?tag=, a bulk mark-all-read endpoint (bulk_create/update, not one
  UserArticleState per article), and article_inline — the htmx endpoint
  behind the inline expand, sharing its mark-read logic with the full
  article_detail view via _load_article_and_mark_read.
- templates/reader/_article_inline.html returns the article content plus
  an out-of-band swap of _article_actions.html, so the row's read/star
  icons update immediately when an article is expanded and marked read.
- static/js/stream.js: the accordion toggle (one article open at a time),
  calling htmx.ajax() directly rather than hx-* attributes so a second
  click on an already-open row can collapse it without re-fetching.
- static/css/base.css: full FreshRSS-like dark theme (with a light
  variant under prefers-color-scheme) replacing the previous unstyled
  pass — sidebar, topbar search, row/icon states, inline-expand styling.

Verified end to end against a running dev server: folder/feed/tag scoping,
mark-all-read, the inline-expand mark-read side effect and its icon
update, and — against config.settings.prod specifically — that no inline
<script> crept back in anywhere (would silently break under the CSP added
in the previous commit) and the CSP header is still present on every page.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-30 21:11:17 -06:00
ksmithandClaude Sonnet 5 4c20558525 Fix CSP blocking the service worker registration and tag colors
script-src 'self' blocks any inline <script> block outright, which would
have silently broken the service-worker registration snippet in base.html
in production — the exact feature this whole project exists to support.
Moved it to static/js/register-sw.js, loaded via <script src>, so script-src
can stay strict with no 'unsafe-inline' exception. style-src needed
'unsafe-inline' regardless, since tag pills set a per-tag color via a
dynamic inline style attribute.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-30 20:11:55 -06:00
ksmithandClaude Sonnet 5 3f6474ce94 Add hardening and deployment: admin dashboard, security headers, install docs
Adds an admin-only dashboard (apps/core) surfacing feeds that are failing to
fetch, with error messages, subscriber counts, and a one-click retry that
resets backoff and re-queues the fetch.

Hardens config/settings/prod.py with the remaining standard Django security
settings (HSTS preload, nosniff, referrer-policy, frame-options, SameSite
cookies) plus a Content-Security-Policy header via django-csp, as a second
layer behind nh3's HTML sanitization of feed content.

Adds docs/install.md (pip + gunicorn + systemd + nginx, SQLite and Postgres
both covered) plus the systemd units and nginx snippet it references,
LICENSE (AGPL-3.0-or-later, matching pyproject.toml), and an updated README.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-30 20:10:31 -06:00
ksmithandClaude Sonnet 5 7577110238 Add the PWA layer: manifest, service worker, icons, offline page
Implements installable-PWA support per the plan: a manifest.webmanifest
view (name/short_name "Evection", standalone display, 192/512/maskable
icons), a service worker served at domain root (/sw.js, with
Service-Worker-Allowed: / so its scope covers the whole app, not just
/static/), and an offline fallback page.

The service worker ignores all non-GET requests outright (so mutations
like mark-read/star/OPML upload stay network-only without special-
casing every endpoint), does network-first-with-cache-fallback for
navigations (bounded to the 60 most recently viewed pages, trimmed
oldest-first), and cache-first for /static/ assets, with the cache
name keyed by EVECTION_PWA_CACHE_VERSION so a deploy can invalidate
old caches. Per the earlier decision, embedded remote images in
article content are not cached for offline reading — text/HTML only.

Generates a simple RSS-glyph icon set (192/512/maskable/apple-touch)
with a throwaway Pillow script (not a project dependency). Adds iOS
meta tags and service-worker registration to base.html. Fixed a real
bug found during this work: the first-run setup-wizard middleware was
redirecting /manifest.webmanifest, /sw.js, and /offline/ to /setup/
before an admin account existed, which would have broken a browser's
very first visit to a fresh install.

Verified: manifest JSON validity and required fields, sw.js delivery
(content-type, Service-Worker-Allowed header, correct body) via both
curl and automated tests (112 passing). Actual service-worker
registration could not be verified in this sandboxed browser pane —
confirmed via a control test (even a trivial unrelated static file
fails to register here with an opaque "unknown error fetching script")
that this is an environment limitation of locally-started dev servers
in this tool, not an application bug; registration, install-prompt,
and offline behavior need confirming in a real browser.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-30 16:46:06 -06:00
ksmithandClaude Sonnet 5 ea214dd9ce Add OPML import/export and a subscriptions management page
Implements OPML parsing with defusedxml (untrusted upload, XXE risk)
and export with the stdlib's plain ElementTree (trusted, app-generated
output). Nesting deeper than one level flattens into its nearest
enclosing folder, matching the app's flat-folder model. Import reuses
existing Feed/Subscription rows via get_or_create, so re-importing the
same file is idempotent and cross-user Feed dedup is preserved.

Large imports (>50 entries) dispatch to a Celery task instead of
blocking the request; newly imported feeds aren't fetched immediately
since they have no last_fetched_at, so the next poll_due_feeds beat
cycle picks them up naturally.

Adds a Subscriptions page (replacing the standalone "Add feed" link in
nav) listing current subscriptions with unsubscribe, plus Import/
Export OPML actions.

Verified live: imported a 2-feed/1-folder OPML file against the
running dev server (via an authenticated session, since this browser
tool has no file-picker automation), confirmed the resulting
subscriptions and folder in the UI, exported and inspected the
resulting OPML structure, and unsubscribed from one feed.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-30 16:41:18 -06:00
ksmithandClaude Sonnet 5 8653dbeaf9 Add full-text search with per-backend SQLite/Postgres implementations
Implements the backend-agnostic search interface from the plan,
selected at runtime by connection.vendor:

- SQLite: an FTS5 virtual table (external-content, mirroring
  Article.title/content_html) created via a vendor-conditional
  migration, kept in sync by insert/update/delete triggers. Queries
  wrap the whole user input as a single FTS5 phrase so punctuation in
  a search box can't break MATCH syntax. `reindex_search` management
  command rebuilds it after bulk imports.
- Postgres: computes the search vector on the fly per the plan's
  decision (title weighted above content, no stored/indexed column)
  rather than diverging the schema from SQLite.

Both backends scope results to the requesting user's own subscriptions
and share the stream/detail article-row template and read/star/save
actions via a new apps.articles.queries.with_user_state() helper,
extracted from apps.reader.views to avoid duplicating that annotation
logic for search results.

Verified live: the SQLite path end-to-end in-browser against the real
Hacker News subscription (search UI, phrase matching, no-match case),
and the Postgres path against a throwaway Postgres container (search,
feed-scoping, and title-vs-content ranking), torn down afterward — not
part of this project's own infrastructure.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-30 16:37:22 -06:00