Skip to content

fix: harden anonymous quotas and metadata origins#550

Merged
BigSimmo merged 7 commits into
mainfrom
codex/fix-48h-review-findings
Jul 13, 2026
Merged

fix: harden anonymous quotas and metadata origins#550
BigSimmo merged 7 commits into
mainfrom
codex/fix-48h-review-findings

Conversation

@BigSimmo

@BigSimmo BigSimmo commented Jul 13, 2026

Copy link
Copy Markdown
Owner

Summary

  • clear stale evidence chunks when useful-page links jump to a different PDF page
  • use deployment-owned proxy identity for anonymous quotas and keep the aggregate anonymous upload ceiling
  • derive production metadata URLs only from validated configured or Railway-owned deployment origins
  • retain the already-merged bounded-body, JSON 429, and bare cross-reference protections from current main

Verification

  • Ran node node_modules/vitest/vitest.mjs run tests/source-backed-recovery-cross-reference.test.ts tests/bounded-json-body.test.ts tests/document-viewer-navigation-source.test.ts tests/production-metadata-source.test.ts tests/public-api-access.test.ts tests/api-rate-limit-fallback.test.ts tests/private-access-routes.test.ts --reporter=dot: passed (7 files, 131 tests) on final source behavior.
  • Ran node node_modules/vitest/vitest.mjs run tests/production-metadata-source.test.ts tests/public-api-access.test.ts --reporter=dot: passed (2 files, 10 tests) after the documentation-only follow-up.
  • Ran node node_modules/eslint/bin/eslint.js src/app/layout.tsx src/lib/document-viewer-navigation.ts src/lib/metadata-base.ts src/lib/public-api-access.ts tests/document-viewer-navigation-source.test.ts tests/production-metadata-source.test.ts tests/public-api-access.test.ts --max-warnings 0: passed on final source behavior.
  • Ran npm run typecheck: passed on final source behavior.
  • Ran node node_modules/prettier/bin/prettier.cjs --check src/lib/document-viewer-navigation.ts src/lib/metadata-base.ts src/lib/public-api-access.ts tests/document-viewer-navigation-source.test.ts tests/production-metadata-source.test.ts tests/public-api-access.test.ts: passed on final source behavior.
  • Ran git diff --check: passed on final local changes.
  • Ran node node_modules/eslint/bin/eslint.js tests/ui-tools-collapse.spec.ts --max-warnings 0: passed after correcting the stale split-pane assertion.
  • Ran node node_modules/prettier/bin/prettier.cjs --check tests/ui-tools-collapse.spec.ts: passed after correcting the stale split-pane assertion.
  • Ran npm run verify:cheap: passed on the integrated branch (195 files passed, 1 skipped; 1,757 tests passed, 1 skipped).
  • Ran npm run format:check: passed on the integrated branch.
  • Ran npm run check:production-readiness:ci: passed (READY; provider configuration warnings only).
  • Not run locally: npm run verify:pr-local; its production-build stage rejects this isolated worktree's external dependency junction.
  • GitHub Actions Build ran npm run build on head a035fa7d7: passed.
  • Not run locally: npm run verify:ui; npm run ensure failed because Turbopack rejects the isolated worktree's external dependency junction.
  • GitHub Actions Critical UI smoke ran npm run test:e2e:critical on head a035fa7d7: passed (8 tests). GitHub Actions Advisory UI regression ran npm run test:e2e:advisory on the same head: passed (129 tests).
  • Not run: npm run verify:release; provider/release workflow remains confirmation-gated.

Retrieval/ranking/scoring behavior is unchanged, so the live retrieval-quality gate is not applicable. The branch does not invoke provider-backed answer generation.

Clinical Governance Preflight

  • Source-backed claims still require linked source verification before clinical use
  • No patient-identifiable document workflow was introduced or expanded without explicit governance approval
  • Supabase target remains Clinical KB Database (sjrfecxgysukkwxsowpy)
  • Service-role keys and private document access remain server-only
  • Demo/synthetic content remains clearly separated from real clinical sources
  • Source metadata, review status, and outdated/unknown-source behavior remain conservative
  • Deployment classification/TGA SaMD impact checked; the net branch does not change clinical decision-support logic

Review findings resolved

  1. Bare cross-reference recovery: retained current main guard and regression coverage from fix(rag): don't rescue bare cross-reference answers in source-backed recovery #538.
  2. Useful-page jump: destination links no longer preserve the incoming chunk; the URL helper now has behavior-level tests and normalizes non-finite page inputs.
  3. Anonymous quota identity: ignores caller-controlled cf-connecting-ip, uses the proxy-appended right edge of x-forwarded-for, and retains the global upload ceiling.
  4. JSON body bound: retained current main bounded reader and 413 regression coverage.
  5. Stream 429 contract: retained current main shared JSON rate-limit response.
  6. Metadata origin: production uses a valid configured URL or Railway-owned deployment domain; request-derived origins are restricted to non-production development.

BigSimmo added 2 commits July 13, 2026 14:16
…findings

# Conflicts:
#	docs/branch-review-ledger.md
#	src/lib/rag-extractive-answer.ts
#	tests/bounded-json-body.test.ts
#	tests/private-access-routes.test.ts
#	tests/source-backed-recovery-cross-reference.test.ts
@supabase

supabase Bot commented Jul 13, 2026

Copy link
Copy Markdown

This pull request has been ignored for the connected project sjrfecxgysukkwxsowpy because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 459e7ea8-be36-4e1a-af72-9e82faa7d2aa

📥 Commits

Reviewing files that changed from the base of the PR and between 4973566 and a035fa7.

📒 Files selected for processing (13)
  • .env.example
  • src/app/layout.tsx
  • src/components/DocumentViewer.tsx
  • src/lib/api-rate-limit.ts
  • src/lib/document-viewer-navigation.ts
  • src/lib/metadata-base.ts
  • src/lib/public-api-access.ts
  • tests/api-rate-limit-fallback.test.ts
  • tests/document-viewer-navigation-source.test.ts
  • tests/production-metadata-source.test.ts
  • tests/public-api-access.test.ts
  • tests/ui-smoke.spec.ts
  • tests/ui-tools-collapse.spec.ts

📝 Walkthrough

Summary by CodeRabbit

  • New Features

    • Added reliable document viewer page navigation with normalized page links.
    • Added configurable site URL support for accurate generated metadata.
  • Bug Fixes

    • Improved metadata origin selection across production and development environments.
    • Strengthened anonymous upload rate limiting.
    • Improved request identity detection behind deployment proxies.
  • Tests

    • Added coverage for navigation, metadata resolution, rate limits, proxy identity handling, and updated UI state persistence.

Walkthrough

Metadata origins now resolve per request, document navigation URLs use a shared helper, anonymous upload quotas apply a global ceiling, API identity derivation trusts deployment proxy headers, and UI smoke tests use owner-scoped session storage.

Changes

Request behavior updates

Layer / File(s) Summary
Per-request metadata origins
.env.example, src/app/layout.tsx, src/lib/metadata-base.ts, tests/production-metadata-source.test.ts
Metadata resolves from a valid configured URL, trusted deployment domain, or explicitly allowed request origin; environment documentation and resolution behavior are tested.
Document page navigation
src/lib/document-viewer-navigation.ts, src/components/DocumentViewer.tsx, tests/document-viewer-navigation-source.test.ts
Page links use a shared helper that encodes the document ID, normalizes page numbers, and adds the page query parameter and PDF preview fragment.
Proxy-derived anonymous identity
src/lib/public-api-access.ts, tests/public-api-access.test.ts
Anonymous API keys derive identity from deployment proxy forwarding headers, ignoring Cloudflare identity values, with tests covering stable and changed forwarded addresses.
Global document upload quota
src/lib/api-rate-limit.ts, tests/api-rate-limit-fallback.test.ts
Anonymous document uploads perform both subject-specific and bucket-scoped global durable quota checks.
Session-scoped UI smoke state
tests/ui-smoke.spec.ts, tests/ui-tools-collapse.spec.ts
Smoke tests seed and verify owner-scoped answer-thread and recent-query data in session storage, and use an updated filtered-result assertion.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant RootLayout
  participant RequestHeaders
  participant ResolveMetadataBase
  RootLayout->>RequestHeaders: read request headers
  RootLayout->>ResolveMetadataBase: resolve metadata origin
  ResolveMetadataBase-->>RootLayout: return metadataBase
Loading

Possibly related PRs

  • BigSimmo/Database#457: Introduces the client environment module referenced by related DocumentViewer environment wiring.
🚥 Pre-merge checks | ✅ 4 | ❌ 7

❌ Failed checks (1 warning, 6 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 70.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Generated And Sensitive Files ❓ Inconclusive Repository clone failed, so this custom check could not run with code access. Retry the review run. If this persists, inspect pre-merge custom-check logs for infrastructure or agent runtime failures.
Verification Claims ❓ Inconclusive Repository clone failed, so this custom check could not run with code access. Retry the review run. If this persists, inspect pre-merge custom-check logs for infrastructure or agent runtime failures.
Risky Git Or Deployment Actions ❓ Inconclusive Repository clone failed, so this custom check could not run with code access. Retry the review run. If this persists, inspect pre-merge custom-check logs for infrastructure or agent runtime failures.
Supabase Project And Schema Safety ❓ Inconclusive Repository clone failed, so this custom check could not run with code access. Retry the review run. If this persists, inspect pre-merge custom-check logs for infrastructure or agent runtime failures.
Runtime And Package Manager Integrity ❓ Inconclusive Repository clone failed, so this custom check could not run with code access. Retry the review run. If this persists, inspect pre-merge custom-check logs for infrastructure or agent runtime failures.
Api Route Failure Handling ❓ Inconclusive Repository clone failed, so this custom check could not run with code access. Retry the review run. If this persists, inspect pre-merge custom-check logs for infrastructure or agent runtime failures.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main changes around anonymous quota hardening and metadata origin handling.
Description check ✅ Passed The description covers Summary, Verification, and Clinical Governance Preflight with substantial detail and test results.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/fix-48h-review-findings
✨ Simplify code
  • Create PR with simplified code
  • Commit simplified code in branch codex/fix-48h-review-findings

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/app/layout.tsx`:
- Around line 30-34: Update the NEXT_PUBLIC_SITE_URL parsing in the metadata
generation flow to handle malformed non-empty values without allowing new
URL(configured) to throw unexpectedly. Catch the parse failure and fall back to
the request origin, while preserving the existing http/https validation for
successfully parsed URLs.

In `@tests/document-viewer-navigation-source.test.ts`:
- Around line 6-9: Update the regression test around documentPageHref to assert
the helper regex match succeeds instead of defaulting to an empty body. Prefer
invoking the extracted helper to verify its generated URL contains the document
route and page parameter while omitting the unrelated chunk parameter; otherwise
strengthen the source assertion to validate that contract rather than only one
exact string.

In `@tests/production-metadata-source.test.ts`:
- Around line 4-11: Replace the source-text assertions in the production
metadata test with behavior-level tests for the metadata resolver used by
generateMetadata. Cover configured HTTP and HTTPS origins, forwarded
host/protocol fallback when configuration is absent, and malformed
NEXT_PUBLIC_SITE_URL handling without throwing; extract a pure resolver if
needed and assert the resulting metadata origin.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 4c47e1a0-7437-4a78-889f-aedac8ce81df

📥 Commits

Reviewing files that changed from the base of the PR and between 4973566 and cc76ff4.

📒 Files selected for processing (9)
  • .env.example
  • src/app/layout.tsx
  • src/components/DocumentViewer.tsx
  • src/lib/api-rate-limit.ts
  • src/lib/public-api-access.ts
  • tests/api-rate-limit-fallback.test.ts
  • tests/document-viewer-navigation-source.test.ts
  • tests/production-metadata-source.test.ts
  • tests/public-api-access.test.ts
💤 Files with no reviewable changes (1)
  • src/components/DocumentViewer.tsx

Comment thread src/app/layout.tsx Outdated
Comment thread tests/document-viewer-navigation-source.test.ts Outdated
Comment thread tests/production-metadata-source.test.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
tests/document-viewer-navigation-source.test.ts (1)

13-14: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Cover non-finite page inputs

Add assertions for NaN and Infinity after normalizing them in the helper; otherwise those invalid runtime values can regress to page=NaN or page=Infinity without test coverage.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/document-viewer-navigation-source.test.ts` around lines 13 - 14, Add
assertions in the “normalizes invalid page numbers to the first page” test for
documentPageHref with NaN and Infinity inputs, verifying both normalize to the
first-page URL with page=1.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/lib/document-viewer-navigation.ts`:
- Around line 2-4: Update documentPageHref to normalize non-finite page values
to page 1 before applying truncation and the existing minimum-page clamp, so NaN
and Infinity produce ?page=1. Add coverage for non-finite inputs, preserving the
current behavior for finite page values.

---

Nitpick comments:
In `@tests/document-viewer-navigation-source.test.ts`:
- Around line 13-14: Add assertions in the “normalizes invalid page numbers to
the first page” test for documentPageHref with NaN and Infinity inputs,
verifying both normalize to the first-page URL with page=1.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: bc5f81c9-45ea-4dc1-a5f0-368ac89223d1

📥 Commits

Reviewing files that changed from the base of the PR and between cc76ff4 and 9cd4554.

📒 Files selected for processing (6)
  • src/app/layout.tsx
  • src/components/DocumentViewer.tsx
  • src/lib/document-viewer-navigation.ts
  • src/lib/metadata-base.ts
  • tests/document-viewer-navigation-source.test.ts
  • tests/production-metadata-source.test.ts

Comment thread src/lib/document-viewer-navigation.ts

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9cd455492f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/lib/public-api-access.ts Outdated
Comment thread src/lib/metadata-base.ts
@BigSimmo
BigSimmo enabled auto-merge (squash) July 13, 2026 06:57
@BigSimmo

Copy link
Copy Markdown
Owner Author

@codex please fix all opened comments, then mark as resolved

@chatgpt-codex-connector

Copy link
Copy Markdown

Summary

Git / PR

  • Committed changes on current branch work: e70c394 fix: resolve PR review follow-ups.
  • Created PR metadata with title: fix: resolve PR review follow-ups.

Testing

  • npm ci — passed; installed dependencies and reported found 0 vulnerabilities.
  • npm run test -- tests/document-viewer-navigation-source.test.ts tests/public-api-access.test.ts tests/production-metadata-source.test.ts --reporter=dot — passed; 3 files, 11 tests.
  • npm run typecheck — passed.
  • npm run lint — passed.

View task →

@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

Note

Unit test generation is a beta feature. Expect some limitations and changes as we gather feedback and continue to improve it.


Generating unit tests... This may take up to 20 minutes.

@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

Note

Docstrings generation - SUCCESS
Generated docstrings for this pull request at #554

@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

Note

Unit test generation is a beta feature. Expect some limitations and changes as we gather feedback and continue to improve it.


Generating unit tests... This may take up to 20 minutes.

coderabbitai Bot added a commit that referenced this pull request Jul 13, 2026
Docstrings generation was requested by @BigSimmo.

* #550 (comment)

The following files were modified:

* `src/app/layout.tsx`
* `src/components/DocumentViewer.tsx`
* `src/lib/api-rate-limit.ts`
* `src/lib/document-viewer-navigation.ts`
* `src/lib/metadata-base.ts`
* `src/lib/public-api-access.ts`
@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

✅ Created PR with unit tests: #555

@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

✅ Created PR with unit tests: #556

@BigSimmo BigSimmo changed the title fix: close 48-hour review findings fix: harden anonymous quotas and metadata origins Jul 13, 2026
@BigSimmo

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@BigSimmo

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@BigSimmo

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@BigSimmo

Copy link
Copy Markdown
Owner Author

@coderabbitai run pre-merge checks

@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Running Pre-merge checks. Results will be posted in the summary comment once complete.

@BigSimmo
BigSimmo merged commit 75d7ac4 into main Jul 13, 2026
14 of 15 checks passed
@BigSimmo

Copy link
Copy Markdown
Owner Author

@coderabbitai run pre-merge checks

@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Running Pre-merge checks. Results will be posted in the summary comment once complete.

@BigSimmo

Copy link
Copy Markdown
Owner Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Full review finished.

@BigSimmo

Copy link
Copy Markdown
Owner Author

@coderabbitai ignore pre-merge checks

@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor
ℹ️ No Pre-Merge checks found.

No Per-Merge checks were run on this pull request. No override is required.

BigSimmo pushed a commit that referenced this pull request Jul 13, 2026
Docstrings generation was requested by @BigSimmo.

* #550 (comment)

The following files were modified:

* `src/app/layout.tsx`
* `src/components/DocumentViewer.tsx`
* `src/lib/api-rate-limit.ts`
* `src/lib/document-viewer-navigation.ts`
* `src/lib/metadata-base.ts`
* `src/lib/public-api-access.ts`

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
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