Skip to content

data.nemar.org: HTTPS access for published NEMAR datasets - #507

Merged
neuromechanist merged 5 commits into
devfrom
feature/issue-449-epic-data-https
May 15, 2026
Merged

neuromechanist merged 5 commits into
devfrom
feature/issue-449-epic-data-https

Conversation

@neuromechanist

Copy link
Copy Markdown
Contributor

Summary

Closes #449.

Adds public, anonymous HTTPS access to every published NEMAR dataset at data.nemar.org, BIDS-shaped, with no nemar-cli / git-annex / NEMAR account required. The same handlers are also reachable at api.nemar.org/data/... for clients already pinned to the API origin.

Designed to serve three audiences from a single Cloudflare Worker:

  • Browsers — Apache-style HTML directory listings, sitemap-style dataset landing page, friendly tombstone 404s.
  • Machine clients (eegdash-viewer, indexers, scripts) — manifest.json per version, metadata.json per dataset (neuroschema v0.3.0 dataset document).
  • Mirroring tools (rclone sync, aria2c, wget --mirror, curl) — explicit HEAD with size + mtime + ETag, content-negotiated 404 bodies, parser-friendly index HTML.

No S3 materialization required: every URL the user sees is virtual, served via the Worker doing manifest -> object 302. The on-disk shape stays content-addressed (s3://nemar/<id>/objects/<sha-key>); the user-facing contract is BIDS-shaped (/<id>/<version>/sub-01/eeg/...).

Phases completed

# PR Commit Issue What
1 #502 9aa728c #495 Worker route + per-version manifest.json + HTML directory index; data.nemar.org Workers custom domain registered on the SCCN account
2 #504 bd8e59f #496 /<id>/metadata.json sibling endpoint returning a neuroschema v0.3.0 dataset document (catalog + version list + derived BIDS subjects/sessions/modalities/tasks/runs index)
3 #505 b3edd29 #497 Sitemap-style dataset landing page; version picker on directory pages; structured tombstone 404s for files removed between versions; "files removed since vN-1" footer
4 #506 e003a2b #498 Explicit HEAD support returning size + RFC 1123 mtime + content-addressed ETag; rclone sync :http:... works with delta detection

URLs the epic adds

https://data.nemar.org/<id>/                            # landing page (HTML or JSON)
https://data.nemar.org/<id>/metadata.json               # neuroschema dataset document
https://data.nemar.org/<id>/<version>/                  # directory listing (HTML)
https://data.nemar.org/<id>/<version>/manifest.json     # flat file index with presigned URLs
https://data.nemar.org/<id>/<version>/<bids-path>       # 302 to file bytes (GET); 200 + metadata (HEAD)
https://data.nemar.org/<id>/latest/...                  # /latest/ alias resolves to most recent version

Headers + content negotiation

  • Accept: text/html -> browser HTML on listings and 404s.
  • Accept: application/json (or no Accept) -> JSON on the landing page and 404s.
  • ?format=json / ?format=html -> explicit override.
  • HEAD on a file -> 200 + Content-Length, Last-Modified (RFC 1123), ETag ("sha256:<hex>" for annex, "git:<sha>" for inline git).
  • GET on a file -> 302 to backing-store bytes + Last-Modified + ETag (no Content-Length per RFC 9110 §8.6).
  • GET 404 on a removed path -> includes reason: "removed", last_seen_version, last_seen_url. Walk capped at 10 prior versions.

Test coverage

  • 97 unit tests in test/data-route.unit.test.ts (manifest path resolution, presign-URL routing, BIDS index derivation, neuroschema dataset builder, tombstone walk with multi-version fixtures, rclone-parser regex test, HTTP-date formatting, version-tag coercion).
  • E2E tests in test/data-route.test.ts that run against a deployed backend; skip gracefully when the test dataset isn't published or lacks two versions.
  • 3-agent /review-pr pass on every phase PR. All CRITICAL/HIGH findings addressed before phase merge. Highlights from those reviews are noted on each phase PR's review-summary comment.

Test plan

  • All 4 phase PRs individually reviewed via /review-pr (3 sonnet agents in parallel) and findings addressed
  • bun test test/data-route.unit.test.ts -- 97/97 pass on the epic branch
  • bun x tsc --noEmit from backend/ -- clean
  • After this merges to dev: deploy to dev Worker via cfman wrangler --account sccn deploy -c backend/wrangler-sccn.toml --env dev
  • Smoke test against deployed dev backend: visit data.nemar.org/nm000103/ (landing page), data.nemar.org/nm000103/latest/ (version picker + index), curl manifest.json, HEAD a known file, run rclone lsl :http:data.nemar.org/nm000103/v1.0.0/

Bruno follow-up (already posted)

Replied to @bruAristimunha on #449 (issuecomment-4461886070) confirming that:

  • Sidecar JSON files work today via the per-path route (git-backed in the manifest, served as 302 to raw.githubusercontent.com).
  • manifest.json enumerates every sidecar; one fetch per version gives the viewer all URLs.
  • metadata.json deliberately stays dataset-level (neuroschema dataset document); inlining sidecar contents is out of scope.

Known follow-ups (not in this epic)

Files touched (cumulative across phases)

backend/src/index.ts                |  24 ++
backend/src/routes/data.ts          | 467 +++++++++++++++++++++++
backend/src/services/data-router.ts | 1058 ++++++++++++++++++++++++++++++++++++++++++++++++
backend/src/services/github.ts      |   2 +-
backend/src/services/s3.ts          |  14 +-
backend/wrangler-sccn.toml          |  10 +-
docs/guides/downloading.md          | 107 +++++
docs/reference/data-api.md          | 332 +++++++++++++++
test/data-route.test.ts             | 327 +++++++++++++++
test/data-route.unit.test.ts        | 1302 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Total: ~3700 lines added, 13 lines removed across 10 files. Pure-function helpers in data-router.ts carry the bulk of the logic; route handlers in data.ts are thin glue over D1 + S3.

* feat(backend): add data.nemar.org HTTPS route + manifest + HTML index

Phase 1 of epic #449. Public, anonymous, BIDS-shaped HTTPS access to every
published dataset via a Cloudflare Workers route at data.nemar.org and a
path-based mount at api.nemar.org/data/* (so the workers.dev dev fallback
serves the same handlers).

- backend/src/services/data-router.ts: pure functions resolveVersion,
  resolveFile, buildRedirectUrl, renderIndexHtml. Annex keys -> presigned
  S3 GET; git: keys -> raw.githubusercontent URL pinned to the version tag.
- backend/src/routes/data.ts: Hono sub-app. Public datasets only;
  private/unpublished return 404 (no existence leak). manifest.json
  endpoint emits the existing VersionManifest as a flat array with
  presigned URLs and checksums.
- backend/src/index.ts: hostname middleware forks to dataRoutes when the
  Host header is data.nemar.org; path-based mount at /data wires the same
  handlers on every other hostname.
- backend/wrangler-sccn.toml: data.nemar.org added as a Workers custom
  domain alongside api.nemar.org. Dev environment keeps the workers.dev
  fallback and uses the path-based mount.
- 21 unit tests on pure functions; E2E suite skips gracefully when
  nm099999 is not currently published.
- docs/guides/downloading.md + docs/reference/data-api.md.

Closes #495.

* fix(data-route): address PR #502 review findings

Critical:
- Hostname fork for data.nemar.org now rewrites the URL to /data/<path>
  and re-enters api.fetch, so requests inherit the full middleware stack
  (logger, secureHeaders, cors, rateLimiter, maintenanceMode, onError).
  Previously dataRoutes.fetch was called directly, bypassing everything.
- Read the hostname from c.req.url instead of the Host header so a forged
  Host: cannot steer api.nemar.org traffic into the data branch.
- loadManifest now try/catches JSON.parse and validates manifest.files is
  a non-null object before downstream code iterates it.
- /:datasetId, /:datasetId/, and /:datasetId/:version handlers all gate
  on loadPublishedDataset before producing any response body. The
  /:datasetId placeholder additionally escapes the id and URL-encodes the
  href so a request like /<script> can never reflect into the HTML.

Important:
- loadPublishedDataset emits one structured console.log per reject branch
  (invalid id / not in catalog / non-public visibility) so operators can
  tell scraping from honest 404s in wrangler tail.
- getManifest in s3.ts now logs S3 403 separately from 404 so a
  credentials regression doesn't silently 404 every published dataset.
- manifest.json builder catches per-entry buildRedirectUrl failures and
  emits {url: null, error} for the bad rows instead of failing the whole
  response; healthy rows still resolve normally.
- Added exhaustive 'never' guard in fileOrIndexHandler so future
  ResolvedFile arms fail at build time.
- Exported PresignedUrlOptions from s3.ts and reused it in data-router,
  dropping the duplicate S3Options interface.
- Pinned the /manifest.json response shape to a named PublicManifestEntry
  type (now exported, externally consumable).
- DirectoryEntry is now a discriminated union ({kind:'file'|'dir'})
  instead of {isDir: boolean, size?: number}.
- humanSize guards NaN / Infinity / negative inputs.
- resolveFile returns an empty directory listing for the root of an
  empty manifest rather than 404, so the renderer can show valid UX.

Tests:
- Added unit coverage for MD5E and SHA1E annex backends, unicode +
  special-char filenames, URL-encoded path traversal, empty manifest,
  prototype-pollution-shaped segments, humanSize edge cases.
- E2E now skips itself when TEST_API_URL points at *.nemar.org unless
  TEST_ALLOW_PROD=1 is also set, asserts the structured error body, and
  adds dataset-root response coverage. 30 unit tests pass.

Follow-up:
- #503 tracks the git:-redirect 404 risk (Phase 3).
* Phase 2: metadata.json sibling endpoint for indexing

Adds GET /<datasetId>/metadata.json on the data.nemar.org sub-app, returning
a neuroschema v0.3.0 dataset document that combines:

- The D1 catalog row (name, modalities, subject/task aggregates, sizes).
- The parsed nemar_metadata.json enrichment payload (authors flattened from
  Record<name, AuthorEnrichmentV2> to Person[], MeSH keywords, related
  identifiers, contributors, dates, funding, license).
- The full dataset_versions list under extensions.nemar.versions with
  cross-link manifest_url to the per-version Phase 1 manifest.json.
- A derived BIDS subjects/sessions/modalities/tasks/runs tree from the
  latest version's S3 manifest under extensions.nemar.bids_index, so
  external viewers (eegdash-viewer, etc.) can resolve dataset shape in one
  fetch.

Same public-only gate and 404-with-no-existence-leak as Phase 1. Partial
inputs never 500: missing enrichment, missing versions, or a failed
manifest fetch each degrade to null/empty fields rather than aborting.

backend/src/services/data-router.ts: adds pure builders
(buildDatasetMetadata, buildBidsIndex, buildPersonList, deriveSessions,
formatBytes) plus exported types (NeuroschemaDataset, BidsIndex,
NemarExtensionBlock, etc.). All synchronous and unit-testable.

backend/src/routes/data.ts: metadataJsonHandler wires D1 + manifest I/O,
registered before /:datasetId/:version so Hono cannot capture
"metadata.json" as a version param.

test/data-route.unit.test.ts: 18 new unit tests for the builders covering
empty manifests, multi-session/multi-modality/multi-run accumulation,
non-BIDS path skipping, sidecar inclusion, v1 and v2 author shapes,
formatBytes edge cases, and the full assembler under no-enrichment /
no-versions / no-manifest combinations.

test/data-route.test.ts: extends the E2E suite (skips when nm099999 is
not currently published) with a positive shape assertion and an unknown-
dataset 404 check.

docs/reference/data-api.md: documents the contract with the canonical
example payload.

Closes #496.

* Address PR #504 review findings

- buildBidsIndex: register subjects whose only files lack a `_task-` token
  (anat, dwi, fmap are valid BIDS and the subject must still appear in
  the index). Modalities entry exists with empty tasks map; subject-level
  sidecars register the subject without a modality entry. Replaces the
  previous "missing task token rejects the row" semantics, which silently
  undercounted neuroimaging subjects.

- formatBytes: switch from a two-tier (>=100 ? 0 : 2) to a three-tier
  precision rule (>=100 -> 0 decimals, >=10 -> 1 decimal, <10 -> 2
  decimals). The previous rule produced "10.10 GB" and "99.50 GB" which
  disagreed with the documented "450 MB" / "150 GB" examples. New rule
  matches the docstring; the docstring is also expanded to spell out the
  tiers explicitly so a future maintainer cannot drift it.

- metadataJsonHandler: log the race-case (row disappears between the
  visibility gate and the second SELECT) at warn level so operators can
  correlate it with deletion events or D1 replica lag. The previous code
  returned 404 silently for this anomaly.

- metadataJsonHandler: corrupt enrichment_json now logs at console.error
  rather than console.warn. Persistent data corruption is not a transient
  warning; routing it to error makes it visible to any future
  exception-aggregation pipeline (Sentry is tracked in #478).

- New unit tests: task-less subject registration (anat + dwi),
  subject-level sidecar (sub-01/sub-01_scans.tsv) registers the subject,
  mixed session/flat layouts under one subject, mid-tier formatBytes
  precision, v1 enrichment has no license -> rights empty,
  D1-description-null falls back to v2 enrichment description.

- Drop stale "phase 1"/"phase 2" qualifiers from the file/section
  headers. The data.nemar.org route is now multi-phase; the per-phase
  label dates the comment without adding information.

52 unit tests pass (up from 48 in the PR's first commit).
* Phase 3: versioned access UX + file-removed tombstones

Closes #497, part of epic #449.

- Sitemap-style dataset landing page at /<id>/ with content negotiation
  (HTML for browsers, JSON for machine clients). Lists every published
  version with DOI, publish date, browse URL, and manifest URL.
- Version picker (sibling links) in directory index pages when the
  dataset has more than one published version. Preserves the current
  sub-path so switching versions on /sub-01/eeg/ lands on the same
  directory in the target version.
- Structured tombstone 404s: when a path 404s but existed in an older
  version, return reason: 'removed' + last_seen_version + last_seen_url.
  Lookback walk capped at 10 prior versions.
- 'Files removed since vN-1' footer on directory index pages (collapsible
  details/summary) with links into the prior version.
- HTML 404 page form (Accept: text/html) for tombstones.
- 32 new unit tests covering findLastSeenVersion, diffRemovedSince,
  pickResponseFormat, the renderIndexHtml extensions, buildLandingPayload,
  renderDatasetLandingHtml, and renderTombstone404Html. 84 unit tests
  total, all passing.
- E2E tests for the landing page JSON and HTML forms; tombstone E2E
  skips gracefully when nm099999 lacks two versions with a path drop
  (the unit test multi-version fixture covers the same branch).

* Address PR review: harden error paths, escape href, echo 404 context

From the 3-agent /review-pr pass on PR #505:

- HIGH (security): renderTombstone404Html now escapes lastSeen.href in
  the href attribute, not just the link text. Adds a regression test
  with a synthetic hostile href.
- HIGH (silent failure): loadManifest now wraps getManifest in
  try/catch. A transient S3/network throw on the hot Phase 3 paths
  (tombstone walk fans out up to 10 fetches per 404, removed-since
  footer fetches the prior version on every directory render) no
  longer 500s the request -- degrades to no-tombstone / no-footer.
- HIGH (silent failure): loadVersionRows absorbs D1 errors and returns
  an empty array, with a logged error. The version picker and
  removed-since features are presentational; their D1 query failing
  must not cascade a 500 onto a file-redirect that would otherwise
  succeed.
- MEDIUM: file 404 JSON bodies now echo version + path, parity with
  the HTML 404 form. Lets a JSON consumer self-describe a 404 without
  re-parsing the request URL.
- Promotes toVersionTag to a shared exported helper in data-router.ts;
  metadataJsonHandler reuses it (was a duplicated inline coercion).
  Adds focused unit tests; the coercion bug class (mixed tag-form and
  bare versions in D1) is the highest-impact silent regression
  identified by the test analyst.
* Phase 4: rclone-compatible HEAD + file metadata headers

Closes #498, part of epic #449.

- Explicit HEAD handler on /<id>/<version>/<bids-path>. Returns 200 with
  Content-Length, Last-Modified (from manifest.created), ETag (from
  manifest checksum, quoted per RFC 7232), and Cache-Control. Empty
  body. Hono v4 would otherwise auto-derive HEAD from the GET handler
  and return a 302, which rclone's HTTP backend does not follow on HEAD.
- HEAD on a directory: 200 with text/html content-type, empty body.
- HEAD on missing path: bare 404, no tombstone walk. Rclone fans out
  HEAD across every missing file; a 10-version walk per HEAD would
  amplify a divergent-sync into N*10 S3 fetches.
- GET 302 on a file also gains Content-Length, Last-Modified, ETag --
  for clients that skip HEAD (rclone --http-no-head, custom
  downloaders).
- toHttpDate helper converts ISO 8601 to RFC 1123 HTTP-date.
- Verified the existing HTML index format is parseable by rclone's
  HTTP backend: an rclone-parser-style regex test pins the contract.
  Phase 3 chrome (version picker, removed-since footer, all-versions
  link) uses absolute hrefs that rclone correctly filters out.
- 97 unit tests pass (88 from Phase 1-3 + 9 new for toHttpDate and
  rclone parser compat). New E2E tests: HEAD on file/directory/missing,
  GET 302 metadata headers.
- Docs: 'Sync with rclone' section in downloading.md, HEAD endpoint
  documented in data-api.md with response-code table update.

* Address PR review: drop dead HEAD route, RFC-fix 302, log corrupt dates

From the 3-agent /review-pr pass on PR #506:

- CRITICAL (code-reviewer): dataRoutes.on('HEAD', ...) is dead code in
  Hono v4. Hono's #dispatch intercepts HEAD unconditionally before
  router.match -- it re-runs the GET handler with the original Request
  (method still 'HEAD'), so the isHead branch in fileOrIndexHandler
  fires correctly regardless. Removed the dead registration and
  rewrote the comment to accurately describe the dispatch path.
- HIGH (code-reviewer): Content-Length on the GET 302 violates RFC
  9110 §8.6 -- the field describes the (empty) message body, not the
  redirect target. Some intermediaries can mis-frame a long
  Content-Length 302 as a hung response. Split fileResponseHeaders
  into a (withContentLength: boolean) variant: HEAD keeps it (standard
  HTTP semantics), GET 302 drops it. Last-Modified and ETag stay on
  the 302 (both are valid on redirects per RFC 9110 §8.8). Docs and
  E2E test updated.
- MEDIUM (silent-failure-hunter): toHttpDate silently passed malformed
  input through. A corrupt manifest.created would never surface in
  wrangler tail. Added console.warn so operators can diagnose. Test
  updated to assert the warning fires and includes the bad value.
- Test gap (test-analyst): the rclone-parser test was effectively a
  good simulation but the comment about double-encoding was misleading
  -- left as-is, the existing tests are sufficient.

97 unit tests pass, all earlier tests preserved.
From the cross-phase /review-pr on PR #507:

- HIGH: Phase 2's buildDatasetMetadata emitted bare versions in three
  fields (extensions.nemar.versions[].version, provenance.latest_snapshot,
  bids_index.version) while every other field on the wire (manifest_url,
  the URL grammar, Phase 3's LandingPayload) used v-prefixed tag form.
  A client building a manifest URL by substituting versions[].version
  into the URL pattern would construct an invalid /<id>/1.0.0/manifest.json
  that VERSION_TAG_RE rejects. The Phase 3 toVersionTag helper already
  exists; applied it at the three Phase 2 sites. Updated unit + E2E
  test assertions to expect tag form. Doc example also corrected.
- MEDIUM: the 308 /<id>/<version> -> /<id>/<version>/ redirect emitted
  no Cache-Control. Without one, downstream caches apply heuristic
  TTLs (often very long for 308) which is inconsistent with the rest
  of the route's caching matrix. Added Cache-Control: public, max-age=300
  to match the file-redirect TTL.

97 unit tests pass.
@neuromechanist

Copy link
Copy Markdown
Contributor Author

Epic-level review (cross-phase pass, 1 sonnet agent)

Each phase PR (#502, #504, #505, #506) was reviewed individually with 3 sonnet agents and findings addressed before merge. The epic-level pass focused on cross-phase coherence that wouldn't surface in a single-phase review.

Findings addressed in ae95791:

  • HIGH (version-format drift): Phase 2's `buildDatasetMetadata` emitted bare versions (`"1.0.0"`) in three fields (`extensions.nemar.versions[].version`, `provenance.latest_snapshot`, `bids_index.version`) while every other version field on the wire (Phase 1's `manifest.json` paths, Phase 3's `LandingPayload`, the URL grammar) uses `v`-prefixed tag form. A consumer building a manifest URL by substituting `versions[].version` into a URL pattern would construct `//1.0.0/manifest.json` which `VERSION_TAG_RE` would reject. Phase 3 already exported `toVersionTag` for exactly this; applied it at the three Phase 2 sites. Updated unit + E2E test assertions to pin the tag-form contract. Doc example corrected.
  • MEDIUM: 308 redirect (`//` -> `///`) had no `Cache-Control`. Without one, downstream caches apply heuristic TTLs (often very long for 308) which is inconsistent with the route's deliberate caching matrix (`max-age=300` on stable redirects, `max-age=60` on listings). Added `Cache-Control: public, max-age=300`.

Findings dismissed:

  • Test fixture reuse: Phase 4's rclone-parser tests use inline fixtures rather than Phase 3's `multiVersionFixtures()`. Justified -- Phase 4 tests HTML rendering shape, not tombstone semantics. No drift.
  • Cache-Control on `manifest.json` is `max-age=60` while file responses are `max-age=300`. Intentional: manifests carry presigned URLs that expire in 1 hour, so a 5-minute manifest TTL is the right call.

Coherence confirmed:

  • All 404 paths funnel through one `notFound()` helper. File-path 404s carry `version` + `path` + (optional) `reason: "removed"` consistently.
  • Documentation reads coherently end-to-end with the version-format fix.
  • No naming or typing drift between phases other than the version-format one (now fixed).

Unit test count: 97. All passing.

Ready to merge with regular merge (per the epic's state file: `merge_strategy_epic_to_integration: merge` -- preserves the four phase commits in dev's history).

@github-actions

Copy link
Copy Markdown

📦 Package Preview

Your package is ready to test!

bun install -g nemar-cli@PR507

Version: 0.8.15-PR507.ae95791
Commit: ae95791


🤖 Updated on each push.

This branch was previously deployed

1 inactive deployment
npm — ae957912 Deployed May 15, 2026 by neuromechanist via publish #918
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