Skip to content

fix(router): do not serve SPA HTML for API and ops paths - #6299

Closed
xvyimu wants to merge 1 commit into
QuantumNous:mainfrom
xvyimu:pr/b3-spa-nonroute-guards
Closed

xvyimu wants to merge 1 commit into
QuantumNous:mainfrom
xvyimu:pr/b3-spa-nonroute-guards

Conversation

@xvyimu

@xvyimu xvyimu commented Jul 18, 2026 •

Copy link
Copy Markdown

Summary

Third small PR from the withdrawn hardening effort: SPA NoRoute hygiene.

Embedded frontend NoRoute previously only excluded /api, /v1, and /assets. Unregistered ops/relay paths such as /metrics could fall through to index.html with HTTP 200, which breaks monitoring and masks missing routes.

This PR:

  • Adds an explicit non-SPA prefix list (/metrics, relay prefixes, health probes, /dashboard/billing, …).
  • Returns API-style 404 for those paths instead of SPA HTML.
  • Keeps /dashboard and /dashboard/{section} as SPA routes (console), while still treating OpenAI-compatible /dashboard/billing as non-SPA.

Test plan

  • go test ./router -run 'NonSPA|Metrics'
  • Manual embedded mode: GET /metrics → non-HTML 404 when metrics disabled
  • Manual: GET /dashboard/overview still serves SPA after login redirect

Notes

Summary by CodeRabbit

  • Bug Fixes

    • Backend, metrics, and API requests now return appropriate 404 responses instead of displaying the web app.
    • Valid SPA routes continue to load the selected default or classic theme correctly.
    • Theme asset availability is now detected more reliably.
  • Tests

    • Added coverage for non-SPA endpoint handling, metrics responses, and SPA route fallback behavior.

Expand NoRoute guards beyond /api /v1 /assets so unregistered /metrics,
relay prefixes, health probes, and /dashboard/billing return JSON 404
instead of index.html. Keep /dashboard and /dashboard/* console routes
as SPA so login redirects still work.
@coderabbitai

coderabbitai Bot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

The web router now classifies operational paths separately from SPA routes, relays 404 responses for non-SPA paths, preserves themed SPA fallback behavior, and adds tests for classification and metrics handling.

Changes

Web router non-SPA handling

Layer / File(s) Summary
Path classification and coverage
router/web-router.go, router/web_router_nonspa_test.go
Adds theme asset availability reporting, expanded non-SPA path matching, and tests covering backend, operational, API, and SPA routes.
NoRoute fallback behavior
router/web-router.go, router/web_router_nonspa_test.go
Routes metrics requests to a 404 response while preserving theme index fallback for dashboard SPA routes.

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

Sequence Diagram(s)

sequenceDiagram
  participant HTTPClient
  participant NoRoute
  participant isNonSPARequestPath
  participant RelayNotFound
  participant ThemeAssets
  HTTPClient->>NoRoute: request unmatched path
  NoRoute->>isNonSPARequestPath: classify request URI
  alt non-SPA path
    isNonSPARequestPath-->>NoRoute: true
    NoRoute->>RelayNotFound: relay 404 response
  else SPA-capable path
    isNonSPARequestPath-->>NoRoute: false
    NoRoute->>ThemeAssets: select theme index
    ThemeAssets-->>HTTPClient: return index.html
  end
Loading

Poem

I’m a rabbit guarding routes tonight,
Keeping API paths from HTML light.
Metrics get a proper 404,
While dashboards hop through the SPA door.
Tests nibble every path just right.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: preventing SPA HTML from being served for API and ops paths.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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: 2

🤖 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 `@router/web_router_nonspa_test.go`:
- Around line 8-9: Update the theme-dependent SPA route tests in the affected
fixture to use assert-based route checks, explicitly configure the expected
theme, and register t.Cleanup to restore the prior theme after each test.
Replace the permissive alternative-theme assertion with an exact comparison
against the expected index payload.

In `@router/web-router.go`:
- Around line 90-91: Update the non-SPA classification in the web router to pass
c.Request.URL.Path instead of c.Request.RequestURI to isNonSPARequestPath,
preserving JSON 404 handling for unregistered backend and operations paths. Add
a test covering an encoded API prefix such as /%61pi/missing and verify it does
not fall back to HTML.
🪄 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

Run ID: 363babe8-0a40-4867-867a-30f36c919507

📥 Commits

Reviewing files that changed from the base of the PR and between 5a6c53d and 096a83a.

📒 Files selected for processing (2)
  • router/web-router.go
  • router/web_router_nonspa_test.go

Comment on lines +8 to +9
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"

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.

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Locate the repository's theme setter/fixture pattern and existing assert usage.
rg -n -C3 --type=go '\b(SetTheme|GetTheme)\s*\(' common router
rg -n -C2 --type=go 'testify/assert|assert\.(Equal|True|NotContains)' router

Repository: QuantumNous/new-api

Length of output: 3135


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n== router/web_router_nonspa_test.go ==\n'
sed -n '1,220p' router/web_router_nonspa_test.go

printf '\n== common/constants.go ==\n'
sed -n '1,120p' common/constants.go

printf '\n== router/web_router.go ==\n'
sed -n '80,115p' router/web_router.go

Repository: QuantumNous/new-api

Length of output: 5396


🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n -C2 --type=go 'testify/assert|assert\.(Equal|True|False|Contains|Empty|NotEmpty|Nil|NotNil)' router/web_router_nonspa_test.go router/*.go

Repository: QuantumNous/new-api

Length of output: 938


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '1,180p' router/web_router_nonspa_test.go

Repository: QuantumNous/new-api

Length of output: 1993


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '1,160p' router/web-router.go

Repository: QuantumNous/new-api

Length of output: 2808


Make the theme-dependent SPA assertion deterministic
Use assert for the route cases, set the theme explicitly in the fixture and restore it with t.Cleanup, then assert the exact expected index payload instead of accepting either theme.

🤖 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 `@router/web_router_nonspa_test.go` around lines 8 - 9, Update the
theme-dependent SPA route tests in the affected fixture to use assert-based
route checks, explicitly configure the expected theme, and register t.Cleanup to
restore the prior theme after each test. Replace the permissive
alternative-theme assertion with an exact comparison against the expected index
payload.

Source: Coding guidelines

Comment thread router/web-router.go
Comment on lines +90 to +91
if isNonSPARequestPath(c.Request.RequestURI) {
// 未注册的后端/运维路径返回 JSON 404,禁止回退 HTML。

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Confirm whether the router overrides Gin's default decoded-path behavior.
rg -n -C3 --type=go '\b(UseRawPath|UnescapePathValues|RemoveExtraSlash)\b' .

Repository: QuantumNous/new-api

Length of output: 157


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the router file and path classifier.
git ls-files 'router/web-router.go' '*/*.go' | sed -n '1,120p'
echo '--- router/web-router.go (around cited lines) ---'
nl -ba router/web-router.go | sed -n '1,180p'
echo '--- search isNonSPARequestPath ---'
rg -n -C3 'isNonSPARequestPath|RequestURI|URL.Path|UseRawPath|UnescapePathValues|RemoveExtraSlash' router .

Repository: QuantumNous/new-api

Length of output: 3172


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- router/web-router.go (around cited lines) ---'
sed -n '1,220p' router/web-router.go

echo '--- search isNonSPARequestPath ---'
rg -n -C3 'isNonSPARequestPath|RequestURI|URL.Path|UseRawPath|UnescapePathValues|RemoveExtraSlash' router .

Repository: QuantumNous/new-api

Length of output: 50375


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from urllib.parse import urlparse, unquote
u = urlparse("http://example.com/%61pi/missing?x=1")
print("python parsed path:", u.path)
print("python raw path:", u.path.encode())
print("python unquoted:", unquote(u.path))
PY

cat <<'EOF' >/tmp/urlcheck.go
package main

import (
  "fmt"
  "net/http"
)

func main() {
  req, err := http.NewRequest("GET", "http://example.com/%61pi/missing?x=1", nil)
  if err != nil { panic(err) }
  fmt.Println("go URL.Path:", req.URL.Path)
  fmt.Println("go URL.RawPath:", req.URL.RawPath)
  fmt.Println("go RequestURI:", req.RequestURI)
}
EOF
go run /tmp/urlcheck.go

Repository: QuantumNous/new-api

Length of output: 330


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from urllib.parse import urlparse, unquote
u = urlparse("http://example.com/%61pi/missing?x=1")
print("python parsed path:", u.path)
print("python unquoted:", unquote(u.path))
PY

cat <<'EOF' >/tmp/urlcheck.go
package main

import (
  "fmt"
  "net/http"
)

func main() {
  req, err := http.NewRequest("GET", "http://example.com/%61pi/missing?x=1", nil)
  if err != nil { panic(err) }
  fmt.Println("go URL.Path:", req.URL.Path)
  fmt.Println("go URL.RawPath:", req.URL.RawPath)
  fmt.Println("go RequestURI:", req.RequestURI)
}
EOF
go run /tmp/urlcheck.go

Repository: QuantumNous/new-api

Length of output: 295


Classify against c.Request.URL.Path, not RequestURI. RequestURI stays raw, so an encoded API prefix like /%61pi/missing can skip the non-SPA check and fall back to HTML instead of JSON 404. Add coverage for the encoded-prefix case. router/web-router.go:90-91

🤖 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 `@router/web-router.go` around lines 90 - 91, Update the non-SPA classification
in the web router to pass c.Request.URL.Path instead of c.Request.RequestURI to
isNonSPARequestPath, preserving JSON 404 handling for unregistered backend and
operations paths. Add a test covering an encoded API prefix such as
/%61pi/missing and verify it does not fall back to HTML.

@xvyimu

xvyimu commented Jul 19, 2026

Copy link
Copy Markdown
Author

CodeRabbit notes are mainly test fixture / path-decoding edge cases. No functional change in this pass; open for maintainer review.

JacksonsY added a commit to JacksonsY/new-api that referenced this pull request Jul 19, 2026
移植自上游 PR QuantumNous#6299。NoRoute 只排除 /v1、/api、/assets,导致
/metrics、/kling 等未注册路径被 index.html 伪装成 200 HTML。
改为 isNonSPARequestPath 白名单前缀判定:API/Relay/运维路径返回
JSON 404,/dashboard/billing 之外的 /dashboard 仍走 SPA。

与原 PR 差异:nonSPAPathPrefixes 增补本 fork 的 /seedance(火山
ARK 视频入口);未移植未被调用的 ThemeAssets.Available()(死代码)。
补路径判定与 /metrics 不返回 HTML 的路由测试。

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@xvyimu

xvyimu commented Jul 23, 2026

Copy link
Copy Markdown
Author

Withdrawing this contribution. No further action needed from maintainers. Closing and deleting the head branch.

@xvyimu xvyimu closed this Jul 23, 2026
@xvyimu
xvyimu deleted the pr/b3-spa-nonroute-guards branch July 23, 2026 05:44
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.

2 participants