Skip to content

News posts: storage, public read, admin CRUD, image upload - #1553

Merged
neuromechanist merged 9 commits into
devfrom
feature/issue-1551-news-posts
Sep 29, 2026
Merged

neuromechanist merged 9 commits into
devfrom
feature/issue-1551-news-posts

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Refs #1551. Website half: nemarOrg/website#371.

Closes keywords do not fire on dev (GitHub only honors them for PRs into the default branch), so #1551 has to be closed by hand after this merges.

What changed

  • Migration 0087_news_posts.sql. New news_posts table and (status, published_at DESC) index. published_at is stored in datetime() form, enforced by a CHECK, so the visibility filter status = 'published' AND published_at <= datetime('now') compares correctly on the same day (the Notices: same-day expiry never takes effect (ISO vs datetime('now') string compare) #1024 bug). CHECKs also backstop the reserved slug media, slug length, and "banner needs alt text".
  • R2 binding NEWS_MEDIA in wrangler-sccn.toml: nemar-news-media (production) and nemar-news-media-dev ([env.dev]). Both buckets must exist before the next deploy that carries this config, or that deploy fails:
    • bunx cfman wrangler --account sccn r2 bucket create nemar-news-media
    • bunx cfman wrangler --account sccn r2 bucket create nemar-news-media-dev
  • Services. services/news.ts (CRUD; RFC3339 UTC projections, as NOTICE_COLUMNS does; NewsSlugTakenError) and services/news-media.ts (type and magic-byte checks, size-capped body reader, content-addressed R2 put that skips an existing key).
  • Public routes on the api app (so also under /nemar):
    • GET /news?limit=&offset=: visible posts, published_at DESC, id DESC; limit defaults to 10 with a max of 50, and bad values are clamped, never a 400.
    • GET /news/:slug: 404 not_found for a missing, draft, or scheduled post.
    • GET /news/media/:file: streams from R2 with Cache-Control: public, max-age=31536000, immutable, X-Content-Type-Options: nosniff, the object's ETag, and a 304 on a matching If-None-Match.
  • Admin routes (registered on the shared admin router like notices): GET/POST /admin/news, GET/PUT/DELETE /admin/news/:id (409 slug_taken on create and update; PUT bumps updated_at and updated_by), and POST /admin/news/media, which takes a raw body and returns 415, 413, empty_body or type_mismatch before anything is written. The route inventory pin goes from 117 to 125 entries.
  • ADR 0076 (renumbered from 0075, which Enrichment: Sonnet 5.5 and stricter data-paper relation typing #1550 took): news images live in their own R2 bucket and are served by the Worker; dataset bytes stay in S3.
  • hasRealUtcOffset in routes/admin/notices.ts is now exported and reused for published_at. R2Bucket, R2Object and R2ObjectBody are added to the Biome globals. miniflare is pinned as a backend dev dependency, at the version wrangler already ships.

Small tightenings beyond the contract: summary and banner_alt are trimmed like title; a whitespace-only body is refused (the body is stored as sent); PNG is checked against the full 8-byte signature. Error bodies carry a message alongside the contract's error code.

How it was tested

  • backend/test/news-routes.test.ts (64 tests) and backend/test/news-media-routes.test.ts (20 tests), driven through worker.fetch. Posts run against every migration applied to bun:sqlite. Images run against Miniflare's local R2 simulator, not a fake.
  • Each guarded line was mutated once (26 mutations, including the visibility filter, id DESC tiebreak, updated_at bump, datetime(?) normalization, clamps, reserved slug, banner/alt rule, magic bytes, size cap, head-skip, onlyIf, and the file-name gate). The suite failed every time, and the tree was restored.
  • The one branch Bun cannot run is the 200 image body: reading .body from Miniflare's proxy throws DataCloneError. I checked it by hand against wrangler dev --local with local D1 and local R2. Upload, then GET, returned identical bytes with the expected headers, including Content-Length. A 304 on revalidation, HEAD, 409, type_mismatch and 413 also behaved as expected.
  • bun test in backend/: 4318 pass, 0 fail.
  • bun run typecheck (CLI and backend) passes. Biome passes on every changed file. backend/src still has pre-existing findings in zenodo.ts and doi-orcid-discovery.ts, which this PR does not touch.
  • bun run migrations:d1-check replayed all 89 migrations on real local D1, and the schema matches bun:sqlite.

Local run note

wrangler dev on this backend cannot start locally as-is (#1324: src/index.ts exports non-handler constants). A one-file wrapper entry outside the repo that re-exports only the default handler works around it; see #1324.

Admin-authored news posts for nemar.org/news (#1551). published_at is
stored in datetime() form, enforced by a CHECK, so the visibility filter's
comparison with datetime('now') is correct on the same day (the #1024 bug).
The slug 'media' is reserved for the image path.

Tested: replayed on real local D1 via migrations:d1-check (schema matches
bun:sqlite); constraints probed with wrangler d1 execute --local.
nemar-news-media in production, nemar-news-media-dev in [env.dev]
(bindings are not inherited by wrangler environments). Both buckets must
exist before the next deploy that carries the binding. Declares the R2
types as Biome globals alongside the other Workers types.
services/news.ts: CRUD over news_posts. published_at is written through
datetime(?) and every timestamp is projected as RFC3339 UTC, as notices
do. A duplicate slug surfaces as NewsSlugTakenError.

services/news-media.ts: content-type and magic-byte checks (PNG full
8-byte signature, JPEG, GIF87a/89a, RIFF....WEBP), a size-capped body
reader, and a content-addressed put to the R2 bucket that skips the write
when the key already exists.
GET /news (visible posts, newest first, limit/offset clamped rather than
refused), GET /news/:slug, and GET /news/media/:file, which streams the
image from R2 with immutable caching, nosniff and the object's ETag, and
answers a matching If-None-Match with 304. Mounted on the api app, so
also under /nemar.
GET/POST /admin/news, GET/PUT/DELETE /admin/news/:id, and
POST /admin/news/media (raw body: 415, 413, empty_body and type_mismatch
before anything is written; the key is the sha256 of the bytes).
409 slug_taken on create and update. Reuses the notices route's
UTC-offset check for published_at, now exported.

Route inventory updated: six routes, eight entries (117 -> 125).
Both suites drive the worker entry. Posts run on every migration applied
to bun:sqlite; images use Miniflare's local R2 simulator (pinned as a
dev dependency at the version wrangler already ships), not a fake. The
one uncovered branch, the 200 image body, cannot run under bun (reading
.body from Miniflare's proxy throws DataCloneError) and was checked by
hand against wrangler dev.

Tested: 84 pass; each guarded line was mutated once and the suite
failed.
Records why news images use a dedicated R2 bucket served by the Worker
while dataset bytes stay in S3, and what that commits us to (buckets
exist before deploy, the 5 MiB cap, content-addressed keys).
@github-actions

github-actions Bot commented Sep 29, 2026 •

Copy link
Copy Markdown

📦 Package Preview

Your package is ready to test!

bun install -g nemar-cli@PR1553

Version: 0.10.10-PR1553.741fb85
Commit: 741fb85


🤖 Updated on each push.

@neuromechanist

neuromechanist commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor Author

End-to-end check with the website half (nemarOrg/website#372), run locally: this branch's newsRoutes, adminRoutes, and authWebRoutes on a fully migrated in-memory D1 (freshDb) and Miniflare's local R2, with a real admin web session and an admin API key.

  • The website's seed script created five posts through POST /admin/news/media and POST /admin/news, and a re-run skipped all five
  • GET /news, GET /news/:slug (404 for a missing slug and for a scheduled post), and GET /admin/news behave as specified
  • A post saved at 09:00 local on 2026-11-14 was stored as 2026-11-14T17:00:00Z, listed as scheduled for admins, and hidden publicly
  • PUT with another post's slug answered 409 slug_taken; DELETE removed the post
  • GET /news/media/:file answered 304 to a matching If-None-Match

The 200 streaming branch of GET /news/media/:file cannot run under Bun (a Miniflare R2 object's .body throws DataCloneError, as the test file notes), so this local harness handed the route a stream over arrayBuffer(). That branch was verified by hand in wrangler dev (identical bytes, expected headers); a curl -sI https://api-test.nemar.org/news/media/<file> after the dev deploy confirms it on real R2.

Before merge: nemar-news-media-dev must exist or the dev deploy fails, and nemar-news-media before the production promotion.

Review findings on #1553: clamp the public offset (a 20-digit value was a D1 500), require every field on PUT so a partial body cannot unpublish or re-date a post, reject an unparseable published_at in the CHECK (datetime() of junk is NULL, which a CHECK lets through), match declared image types on own keys only, and short-cache the public JSON reads (404s stay no-store). Tests cover each; news suites 88 pass.
@neuromechanist

Copy link
Copy Markdown
Contributor Author

Review round (Sonnet review, all findings addressed in 9864d25):

  • GET /news?offset=<20 digits> was a D1 500 (past SQLite's int64); offset is clamped to 1,000,000.
  • PUT now requires every field. With POST's defaults, a body carrying only the text to fix silently unpublished the post and re-dated it to now.
  • The published_at CHECK now also demands datetime(published_at) IS NOT NULL; datetime('garbage') is NULL and a NULL CHECK passes.
  • declaredImageType matches own keys only (constructor no longer passes the 415 gate).
  • Public JSON reads carry public, max-age=30, s-maxage=300, stale-while-revalidate=600, like /datasets (Cache dataset GETs + raise rate-limit caps (Worker-egress IP pooling) #639); a 404 is no-store so a scheduled post appears on time.

Each has a test; the news suites pass (90), tsc is clean, and migrations:d1-check replays all migrations on real local D1. Not addressed in code: a deploy fails if the R2 buckets are missing. Create nemar-news-media-dev before merging this, and nemar-news-media before the production promotion.

dev took ADR 0075 (#1550), so the news images ADR is renumbered 0076, with the migration comment and the index updated. Typecheck, news suites (90), and migrations:d1-check pass after the merge.
@neuromechanist neuromechanist mentioned this pull request Sep 29, 2026
@neuromechanist
neuromechanist merged commit 53f3a24 into dev Sep 29, 2026
12 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-1551-news-posts branch September 29, 2026 18:11
neuromechanist added a commit that referenced this pull request Sep 29, 2026
Added (#1553, #1559), Migrations (0087), and Deploy coupling (the R2
binding, biosigio 1.2.10 on Hallu, the re-enrichment sweep). Changelog
format test passes.
neuromechanist added a commit that referenced this pull request Sep 29, 2026
Added (#1553, #1559), Migrations (0087), and Deploy coupling (the R2
binding, biosigio 1.2.10 on Hallu, the re-enrichment sweep). Changelog
format test passes.

This branch was previously deployed

1 inactive deployment
npm — 741fb851 Deployed Sep 29, 2026 by neuromechanist via publish #2974
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant