Skip to content

Phase 1: data.nemar.org route + manifest + HTML index - #502

Merged
neuromechanist merged 2 commits into
feature/issue-449-epic-data-httpsfrom
feature/issue-495-phase1-route
May 15, 2026
Merged

neuromechanist merged 2 commits into
feature/issue-449-epic-data-httpsfrom
feature/issue-495-phase1-route

Conversation

@neuromechanist

Copy link
Copy Markdown
Contributor

Summary

Phase 1 of epic #449. Public, anonymous, BIDS-shaped HTTPS access to every published dataset over Cloudflare Workers at `data.nemar.org`. The same handlers are also reachable under `/data/...` on every hostname (api.nemar.org, workers.dev dev fallback) so dev testing doesn't need a separate custom domain.

  • Worker reads the existing per-version manifest from `s3://nemar//version/vX.Y.Z.json` and 302s to the file bytes.
  • Two backends: annex-keyed files presign through S3; `git:`-keyed inline files redirect to `raw.githubusercontent.com` pinned to the version tag.
  • HTML directory index at every non-leaf path. `manifest.json` endpoint emits a flat array with `{path, size, checksum, url}`.
  • Public datasets only; private/unpublished -> 404 (no existence leak).
  • Anonymous reads wired in directly via the existing `optionalAuthMiddleware`; does not depend on the public-access epic landing first.

Closes #495.
Part of epic #449.

Files

  • `backend/src/services/data-router.ts` (new) - pure functions
  • `backend/src/routes/data.ts` (new) - Hono sub-app
  • `backend/src/index.ts` - hostname fork + `/data` mount
  • `backend/wrangler-sccn.toml` - `data.nemar.org` custom domain added
  • `test/data-route.unit.test.ts` (new) - 21 tests, all green
  • `test/data-route.test.ts` (new) - E2E suite, skips gracefully when nm099999 is unpublished
  • `docs/guides/downloading.md` - HTTPS access section + parallel-downloader table
  • `docs/reference/data-api.md` (new) - contract spec

Test plan

Out of scope (later phases)

Manual prereq before prod deploy

The `data.nemar.org` zone must be added to the SCCN Cloudflare account; `custom_domain = true` then auto-manages DNS + TLS. One-time dashboard step.

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.
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).
@neuromechanist

Copy link
Copy Markdown
Contributor Author

Review-round 1 applied (commit fe662aa)

Addressed all Critical and Important findings from the four-agent review. Summary:

Critical fixes

  • C1: Hostname fork now rewrites URL to /data/<path> and re-enters api.fetch, inheriting the full middleware stack (logger, secureHeaders/CSP, cors, rateLimiter, maintenanceMode, onError sanitization).
  • C2: loadManifest try/catches JSON.parse and validates manifest.files shape; malformed manifests now log + return null → 404.
  • C3: /:datasetId, /:datasetId/, and /:datasetId/:version gate on loadPublishedDataset before responding. The placeholder additionally escapes the id and URL-encodes the href, eliminating the reflected-XSS surface even on hostnames where CSP is present.

Important

  • Per-reject-branch console.log in loadPublishedDataset.
  • 403 from getManifest now logs separately from 404.
  • manifest.json builder catches per-entry failures: bad rows emit {url: null, error} instead of failing the whole listing.
  • Exhaustive never guard added in fileOrIndexHandler.
  • Exported PresignedUrlOptions from s3.ts, dropped the duplicate S3Options.
  • Pinned manifest.json response shape to PublicManifestEntry.
  • DirectoryEntry now {kind: 'file' | 'dir'} discriminated union.
  • humanSize guards NaN/Infinity/negative.
  • resolveFile returns empty directory (not 404) for the root of an empty manifest.
  • Hostname now read from new URL(c.req.url).hostname instead of Host: (cannot be spoofed).

Tests

  • 30 unit tests pass (was 21). Added: MD5E + SHA1E backends, unicode + special-char filenames, URL-encoded .. traversal, prototype-pollution segments, empty manifest, humanSize edge cases.
  • E2E suite now skips on *.nemar.org unless TEST_ALLOW_PROD=1, asserts the structured error body, and adds dataset-root response coverage.

Deferred (with reasoning)

Ready for re-review.

@github-actions

Copy link
Copy Markdown

📦 Package Preview

Your package is ready to test!

bun install -g nemar-cli@PR502

Version: 0.8.15-PR502.fe662aa
Commit: fe662aa


🤖 Updated on each push.

@neuromechanist
neuromechanist merged commit 9aa728c into feature/issue-449-epic-data-https May 15, 2026
1 check passed
@neuromechanist
neuromechanist deleted the feature/issue-495-phase1-route branch May 18, 2026 11:11

This branch was previously deployed

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