Repository navigation
data.nemar.org: HTTPS access for published NEMAR datasets - #507
Merged
Merged
Conversation
* 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.
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:
Findings dismissed:
Coherence confirmed:
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). |
📦 Package PreviewYour package is ready to test! bun install -g nemar-cli@PR507Version: 🤖 Updated on each push. |
This was referenced May 15, 2026
This branch was previously deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Closes #449.
Adds public, anonymous HTTPS access to every published NEMAR dataset at
data.nemar.org, BIDS-shaped, with nonemar-cli/ git-annex / NEMAR account required. The same handlers are also reachable atapi.nemar.org/data/...for clients already pinned to the API origin.Designed to serve three audiences from a single Cloudflare Worker:
manifest.jsonper version,metadata.jsonper dataset (neuroschema v0.3.0datasetdocument).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
manifest.json+ HTML directory index;data.nemar.orgWorkers custom domain registered on the SCCN account/<id>/metadata.jsonsibling endpoint returning a neuroschema v0.3.0datasetdocument (catalog + version list + derived BIDS subjects/sessions/modalities/tasks/runs index)rclone sync :http:...works with delta detectionURLs the epic adds
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.200+Content-Length,Last-Modified(RFC 1123),ETag("sha256:<hex>"for annex,"git:<sha>"for inline git).302to backing-store bytes +Last-Modified+ETag(noContent-Lengthper RFC 9110 §8.6).reason: "removed",last_seen_version,last_seen_url. Walk capped at 10 prior versions.Test coverage
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).test/data-route.test.tsthat run against a deployed backend; skip gracefully when the test dataset isn't published or lacks two versions.Test plan
/review-pr(3 sonnet agents in parallel) and findings addressedbun test test/data-route.unit.test.ts-- 97/97 pass on the epic branchbun x tsc --noEmitfrombackend/-- cleancfman wrangler --account sccn deploy -c backend/wrangler-sccn.toml --env devdata.nemar.org/nm000103/(landing page),data.nemar.org/nm000103/latest/(version picker + index), curl manifest.json, HEAD a known file, runrclone lsl :http:data.nemar.org/nm000103/v1.0.0/Bruno follow-up (already posted)
Replied to @bruAristimunha on #449 (issuecomment-4461886070) confirming that:
raw.githubusercontent.com).manifest.jsonenumerates every sidecar; one fetch per version gives the viewer all URLs.metadata.jsondeliberately stays dataset-level (neuroschemadatasetdocument); inlining sidecar contents is out of scope.Known follow-ups (not in this epic)
git:-keyed manifest entries whose backing tag/file is missing on GitHub (Phase 3 candidate, deferred).?format=htmlon the landing page is unit-tested viapickResponseFormatbut lacks a direct E2E assertion.nm099999only has one version; unit-test multi-version fixture covers the same branch.Files touched (cumulative across phases)
Total: ~3700 lines added, 13 lines removed across 10 files. Pure-function helpers in
data-router.tscarry the bulk of the logic; route handlers indata.tsare thin glue over D1 + S3.