Skip to content

Conversation

@schiller-manuel
Copy link
Contributor

@schiller-manuel schiller-manuel commented Dec 13, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced runtime validation for server function IDs in development, producing clearer errors for invalid IDs and preventing downstream failures.
    • Validation now runs before server function access to catch issues earlier.
  • Chores

    • Relaxed update guard for directive-backed server functions so multiple updates are accepted during development, improving iteration/hot-reload reliability.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 13, 2025

Walkthrough

Introduces runtime validation for server function IDs via a virtual module and parsing helper, injects a dynamic import of that validator into the dev-mode getServerFnById flow, relaxes the directiveFnsById update guard to allow multiple updates, and adds assertion-based guards in the validation loader.

Changes

Cohort / File(s) Summary
Server functions plugin (dev/runtime validation)
packages/server-functions-plugin/src/index.ts
Added validateServerFnIdVirtualModule and parseIdQuery to extract/validate ID query params; serve-only loader asserts parsed id against directiveFnsById and errors on unknown ids. Injects dynamic import of the validate virtual module in non-build getServerFnById path. Removed early-return guard in onDirectiveFnsById, added assert import, and cleaned up unused imports.

Sequence Diagram(s)

sequenceDiagram
    participant DevImporter as Importer (dev code)
    participant DevServer as Vite Dev Server / Plugin
    participant VirtualModule as validate:server-fn-id?query=...
    participant InMemoryMap as directiveFnsById

    DevImporter->>DevServer: request getServerFnById(id)
    DevServer-->>DevServer: construct validate virtual-module id (with query)
    DevServer->>VirtualModule: dynamic import validate module (id)
    VirtualModule->>InMemoryMap: check if id exists
    alt id found
        VirtualModule-->>DevServer: return empty export (validation passed)
        DevServer-->>DevImporter: proceed to load target server fn
    else id missing
        VirtualModule-->>DevServer: throw error (invalid server fn id)
        DevServer-->>DevImporter: propagate error
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Inspect virtual module loader logic and error messages.
  • Verify parseIdQuery correctly handles encoded query strings and edge cases.
  • Check that relaxing the directiveFnsById guard won't allow duplicate/conflicting updates during dev.
  • Ensure dynamic import injection doesn't affect build-mode code paths.

Possibly related PRs

Poem

🐰 I hopped a little virtual trail,
Sniffed IDs in query without fail,
If known — I grin and step aside,
If lost — I thump and loudly chide.
✨🫧

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix: validate server fn id during dev' directly describes the main change: adding runtime validation for server function IDs during development mode.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch validate-serverfn-id

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f24c30a and f3c7ab2.

📒 Files selected for processing (1)
  • packages/server-functions-plugin/src/index.ts (4 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Use TypeScript strict mode with extensive type safety for all code

Files:

  • packages/server-functions-plugin/src/index.ts
**/*.{js,ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Implement ESLint rules for router best practices using the ESLint plugin router

Files:

  • packages/server-functions-plugin/src/index.ts
🧬 Code graph analysis (1)
packages/server-functions-plugin/src/index.ts (1)
packages/router-core/src/route.ts (1)
  • id (1549-1551)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Test
  • GitHub Check: Preview
🔇 Additional comments (3)
packages/server-functions-plugin/src/index.ts (3)

43-55: LGTM!

The validateServerFnIdVirtualModule constant and parseIdQuery helper are well-implemented. The function correctly handles the case where no query string is present and safely parses query parameters using URLSearchParams.


220-232: LGTM!

The dev-mode validation integration is well-designed. The dynamic import with /@id/__x00__ correctly handles Vite's virtual module resolution, and the validation occurs before the actual server function is loaded, ensuring invalid IDs are caught early.


173-181: [rewritten review comment]
[classification tag]


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

@nx-cloud
Copy link

nx-cloud bot commented Dec 13, 2025

View your CI Pipeline Execution ↗ for commit f3c7ab2

Command Status Duration Result
nx affected --targets=test:eslint,test:unit,tes... ✅ Succeeded 8m 26s View ↗
nx run-many --target=build --exclude=examples/*... ✅ Succeeded 23s View ↗

☁️ Nx Cloud last updated this comment at 2025-12-13 00:26:33 UTC

@pkg-pr-new
Copy link

pkg-pr-new bot commented Dec 13, 2025

More templates

@tanstack/arktype-adapter

npm i https://pkg.pr.new/TanStack/router/@tanstack/arktype-adapter@6087

@tanstack/directive-functions-plugin

npm i https://pkg.pr.new/TanStack/router/@tanstack/directive-functions-plugin@6087

@tanstack/eslint-plugin-router

npm i https://pkg.pr.new/TanStack/router/@tanstack/eslint-plugin-router@6087

@tanstack/history

npm i https://pkg.pr.new/TanStack/router/@tanstack/history@6087

@tanstack/nitro-v2-vite-plugin

npm i https://pkg.pr.new/TanStack/router/@tanstack/nitro-v2-vite-plugin@6087

@tanstack/react-router

npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router@6087

@tanstack/react-router-devtools

npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-devtools@6087

@tanstack/react-router-ssr-query

npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-ssr-query@6087

@tanstack/react-start

npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start@6087

@tanstack/react-start-client

npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-client@6087

@tanstack/react-start-server

npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-server@6087

@tanstack/router-cli

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-cli@6087

@tanstack/router-core

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-core@6087

@tanstack/router-devtools

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools@6087

@tanstack/router-devtools-core

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools-core@6087

@tanstack/router-generator

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-generator@6087

@tanstack/router-plugin

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-plugin@6087

@tanstack/router-ssr-query-core

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-ssr-query-core@6087

@tanstack/router-utils

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-utils@6087

@tanstack/router-vite-plugin

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-vite-plugin@6087

@tanstack/server-functions-plugin

npm i https://pkg.pr.new/TanStack/router/@tanstack/server-functions-plugin@6087

@tanstack/solid-router

npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router@6087

@tanstack/solid-router-devtools

npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router-devtools@6087

@tanstack/solid-router-ssr-query

npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router-ssr-query@6087

@tanstack/solid-start

npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start@6087

@tanstack/solid-start-client

npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-client@6087

@tanstack/solid-start-server

npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-server@6087

@tanstack/start-client-core

npm i https://pkg.pr.new/TanStack/router/@tanstack/start-client-core@6087

@tanstack/start-plugin-core

npm i https://pkg.pr.new/TanStack/router/@tanstack/start-plugin-core@6087

@tanstack/start-server-core

npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-core@6087

@tanstack/start-static-server-functions

npm i https://pkg.pr.new/TanStack/router/@tanstack/start-static-server-functions@6087

@tanstack/start-storage-context

npm i https://pkg.pr.new/TanStack/router/@tanstack/start-storage-context@6087

@tanstack/valibot-adapter

npm i https://pkg.pr.new/TanStack/router/@tanstack/valibot-adapter@6087

@tanstack/virtual-file-routes

npm i https://pkg.pr.new/TanStack/router/@tanstack/virtual-file-routes@6087

@tanstack/vue-router

npm i https://pkg.pr.new/TanStack/router/@tanstack/vue-router@6087

@tanstack/vue-router-devtools

npm i https://pkg.pr.new/TanStack/router/@tanstack/vue-router-devtools@6087

@tanstack/vue-router-ssr-query

npm i https://pkg.pr.new/TanStack/router/@tanstack/vue-router-ssr-query@6087

@tanstack/vue-start

npm i https://pkg.pr.new/TanStack/router/@tanstack/vue-start@6087

@tanstack/vue-start-client

npm i https://pkg.pr.new/TanStack/router/@tanstack/vue-start-client@6087

@tanstack/vue-start-server

npm i https://pkg.pr.new/TanStack/router/@tanstack/vue-start-server@6087

@tanstack/zod-adapter

npm i https://pkg.pr.new/TanStack/router/@tanstack/zod-adapter@6087

commit: f3c7ab2

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
packages/server-functions-plugin/src/index.ts (1)

224-230: Avoid relying on '/@id/__x00__' if possible; at least document why it’s required.

await import(/* @vite-ignore */ '/@id/__x00__' + validateIdImport) (Line 226) bakes in a Vite dev-server internal path encoding. If you can instead resolveId the virtual module (or otherwise make import(validateIdImport) resolvable without the /@id/__x00__ prefix), the validation mechanism will be less coupled to Vite internals. If that’s not possible in this plugin architecture, a short comment explaining the necessity would help prevent future “cleanup” regressions.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 19ecfe3 and f24c30a.

📒 Files selected for processing (1)
  • packages/server-functions-plugin/src/index.ts (4 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Use TypeScript strict mode with extensive type safety for all code

Files:

  • packages/server-functions-plugin/src/index.ts
**/*.{js,ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Implement ESLint rules for router best practices using the ESLint plugin router

Files:

  • packages/server-functions-plugin/src/index.ts
🪛 ast-grep (0.40.0)
packages/server-functions-plugin/src/index.ts

[warning] 170-172: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(
^${resolveViteId(validateServerFnIdVirtualModule)}?.+,
)
Note: [CWE-1333] Inefficient Regular Expression Complexity [REFERENCES]
- https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
- https://cwe.mitre.org/data/definitions/1333.html

(regexp-from-variable)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Test
  • GitHub Check: Preview

Comment on lines +43 to +55
const validateServerFnIdVirtualModule = `virtual:tanstack-start-validate-server-fn-id`

function parseIdQuery(id: string): {
filename: string
query: {
[k: string]: string
}
} {
if (!id.includes('?')) return { filename: id, query: {} }
const [filename, rawQuery] = id.split(`?`, 2) as [string, string]
const query = Object.fromEntries(new URLSearchParams(rawQuery))
return { filename, query }
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

parseIdQuery is fine, but it makes “missing id” look like an assertion failure.

parseIdQuery never returns falsy, so assert(parsed) (Line 177) is redundant, and assert(parsed.query.id) will throw an AssertionError instead of a clear Vite error. Prefer an explicit check and this.error('Missing ...') for consistency with the invalid-id path.

🤖 Prompt for AI Agents
In packages/server-functions-plugin/src/index.ts around lines 43 to 55, remove
the redundant assert(parsed) usage and replace the assertion that
parsed.query.id exists with an explicit runtime check that calls
this.error('Missing id in virtual module request') (or a message matching the
invalid-id path) when parsed.query.id is absent; since parseIdQuery always
returns an object, rely on that and use this.error to raise a clear Vite error
instead of throwing an AssertionError.

Comment on lines 166 to 183
{
name: 'tanstack-start-server-fn-vite-plugin-validate-serverfn-id',
apply: 'serve',
load: {
filter: {
id: new RegExp(
`^${resolveViteId(validateServerFnIdVirtualModule)}?.+`,
),
},
handler(id) {
const parsed = parseIdQuery(id)
assert(parsed)
assert(parsed.query.id)
if (directiveFnsById[parsed.query.id]) {
return `export {}`
}
this.error(`Invalid server function ID: ${parsed.query.id}`)
},
},
},
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Fix the load.filter.id regex pattern: the quantifier ? is positioned incorrectly and unescaped strings are unsafe in RegExp.

The current pattern `^${resolveViteId(validateServerFnIdVirtualModule)}?.+` makes the last character of the resolved ID optional rather than making the query string optional. This is a logic error that can silently match unintended IDs or fail to match valid ones. The unescaped dynamic string is also brittle; if special regex characters appear, the pattern breaks silently.

Additionally, the assertions at lines 177–178 (assert(parsed) and assert(parsed.query.id)) will throw cryptic errors instead of returning proper validation failures. Use explicit error checks instead:

 id: new RegExp(
-  `^${resolveViteId(validateServerFnIdVirtualModule)}?.+`,
+  `^${escapeRegExp(resolveViteId(validateServerFnIdVirtualModule))}\\?id=.+$`,
 ),
 
 handler(id) {
   const parsed = parseIdQuery(id)
-  assert(parsed)
-  assert(parsed.query.id)
-  if (directiveFnsById[parsed.query.id]) {
+  const serverFnId = parsed?.query?.id
+  if (!serverFnId) {
+    this.error(`Missing server function ID in: ${id}`)
+  }
+  if (directiveFnsById[serverFnId]) {
     return `export {}`
   }
-  this.error(`Invalid server function ID: ${parsed.query.id}`)
+  this.error(`Invalid server function ID: ${serverFnId}`)
 }

Also add the escaping helper at the top of the file:

+function escapeRegExp(s: string) {
+  return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+}

Finally: verify that directiveFnsById is populated before this load hook can run in dev mode. If a module's load hook executes before its corresponding resolveId hook completes, all validations will fail. If that's possible, add a guard to detect uninitialized state.

🧰 Tools
🪛 ast-grep (0.40.0)

[warning] 170-172: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(
^${resolveViteId(validateServerFnIdVirtualModule)}?.+,
)
Note: [CWE-1333] Inefficient Regular Expression Complexity [REFERENCES]
- https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
- https://cwe.mitre.org/data/definitions/1333.html

(regexp-from-variable)

🤖 Prompt for AI Agents
In packages/server-functions-plugin/src/index.ts around lines 166 to 185, the
load.filter.id RegExp is incorrect and unsafe: the `?` is applied to the last
character of the resolved ID instead of making the query part optional, and the
dynamic string must be escaped before insertion into a RegExp to avoid
special-character injection; replace the pattern with a RegExp that escapes the
resolved ID and matches an optional query suffix (e.g. make the query portion
optional as a whole, not the last character). Replace assert(parsed) and
assert(parsed.query.id) with explicit runtime checks that call this.error with a
clear message when parsed or parsed.query.id are missing. Finally add a guard
that ensures directiveFnsById is initialized/populated before validating IDs in
the load hook and, if not ready, either skip validation or return a safe
fallback to avoid false negatives during dev-mode load ordering.

@schiller-manuel schiller-manuel merged commit e08e7ae into main Dec 13, 2025
6 checks passed
@schiller-manuel schiller-manuel deleted the validate-serverfn-id branch December 13, 2025 00:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants