Repository navigation
News posts: storage, public read, admin CRUD, image upload - #1553
Conversation
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).
📦 Package PreviewYour package is ready to test! bun install -g nemar-cli@PR1553Version: 🤖 Updated on each push. |
|
End-to-end check with the website half (nemarOrg/website#372), run locally: this branch's
The 200 streaming branch of Before merge: |
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.
|
Review round (Sonnet review, all findings addressed in 9864d25):
Each has a test; the news suites pass (90), |
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.
Refs #1551. Website half: nemarOrg/website#371.
Closeskeywords do not fire ondev(GitHub only honors them for PRs into the default branch), so #1551 has to be closed by hand after this merges.What changed
0087_news_posts.sql. Newnews_poststable and(status, published_at DESC)index.published_atis stored indatetime()form, enforced by a CHECK, so the visibility filterstatus = '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 slugmedia, slug length, and "banner needs alt text".NEWS_MEDIAinwrangler-sccn.toml:nemar-news-media(production) andnemar-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-mediabunx cfman wrangler --account sccn r2 bucket create nemar-news-media-devservices/news.ts(CRUD; RFC3339 UTC projections, asNOTICE_COLUMNSdoes;NewsSlugTakenError) andservices/news-media.ts(type and magic-byte checks, size-capped body reader, content-addressed R2 put that skips an existing key).apiapp (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: 404not_foundfor a missing, draft, or scheduled post.GET /news/media/:file: streams from R2 withCache-Control: public, max-age=31536000, immutable,X-Content-Type-Options: nosniff, the object'sETag, and a 304 on a matchingIf-None-Match.GET/POST /admin/news,GET/PUT/DELETE /admin/news/:id(409slug_takenon create and update; PUT bumpsupdated_atandupdated_by), andPOST /admin/news/media, which takes a raw body and returns 415, 413,empty_bodyortype_mismatchbefore anything is written. The route inventory pin goes from 117 to 125 entries.hasRealUtcOffsetinroutes/admin/notices.tsis now exported and reused forpublished_at.R2Bucket,R2ObjectandR2ObjectBodyare added to the Biome globals.miniflareis pinned as a backend dev dependency, at the version wrangler already ships.Small tightenings beyond the contract:
summaryandbanner_altare trimmed liketitle; a whitespace-onlybodyis refused (the body is stored as sent); PNG is checked against the full 8-byte signature. Error bodies carry amessagealongside the contract'serrorcode.How it was tested
backend/test/news-routes.test.ts(64 tests) andbackend/test/news-media-routes.test.ts(20 tests), driven throughworker.fetch. Posts run against every migration applied to bun:sqlite. Images run against Miniflare's local R2 simulator, not a fake.id DESCtiebreak,updated_atbump,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..bodyfrom Miniflare's proxy throwsDataCloneError. I checked it by hand againstwrangler dev --localwith local D1 and local R2. Upload, then GET, returned identical bytes with the expected headers, includingContent-Length. A 304 on revalidation, HEAD, 409,type_mismatchand 413 also behaved as expected.bun testinbackend/: 4318 pass, 0 fail.bun run typecheck(CLI and backend) passes. Biome passes on every changed file.backend/srcstill has pre-existing findings inzenodo.tsanddoi-orcid-discovery.ts, which this PR does not touch.bun run migrations:d1-checkreplayed all 89 migrations on real local D1, and the schema matches bun:sqlite.Local run note
wrangler devon this backend cannot start locally as-is (#1324:src/index.tsexports non-handler constants). A one-file wrapper entry outside the repo that re-exports only the default handler works around it; see #1324.