diff --git a/.changeset/start-server-fn-custom-id-check.md b/.changeset/start-server-fn-custom-id-check.md new file mode 100644 index 00000000000..384f0ade068 --- /dev/null +++ b/.changeset/start-server-fn-custom-id-check.md @@ -0,0 +1,7 @@ +--- +'@tanstack/start-plugin-core': minor +--- + +A server function id that a custom `serverFns.generateFunctionId` returns and that never worked over HTTP now fails the build, with an error naming the file, the function and the id: whitespace, a control or non-ASCII character, any of `"`, `#`, `/`, `<`, `>`, `?`, `\`, `^`, `` ` ``, `{`, `}`, the ids `.` and `..`, and a percent-encoding the server reads as another id (`%41`, lowercase hex, `%2E`) or rejects. The client puts the id in the URL unencoded, so a `#` or `?` ended the path and a `/` cut the id short (the call silently ran another server function of the file or none), and the other characters reached the server percent-encoded and matched no function. An id embedding a non-ASCII `functionName` is one of these. One case did work and now fails the build: such an id on a server function only SSR code called. + +Ids with `%` or the other characters URLs allow (such as `:`, `@`, `+`, `=`, `,`, `;`, `!`, `*`, `(`, `)`, `&`, `'`, `|`, `[`, `]`) still build and reach their handler, with a deprecation warning (from the Vite plugin; the Rsbuild plugin does not print compiler warnings yet): the next major version rejects them, since proxies and servers may decode or rewrite them (hash the inputs instead, as the documented example does). An id with `'` no longer breaks the server bundle. diff --git a/docs/start/framework/react/guide/server-functions.md b/docs/start/framework/react/guide/server-functions.md index 68a6b8ac72d..879aa9e8670 100644 --- a/docs/start/framework/react/guide/server-functions.md +++ b/docs/start/framework/react/guide/server-functions.md @@ -425,7 +425,9 @@ Customization: You can customize function ID generation for the production build by providing a `generateFunctionId` function when configuring the TanStack Start build tool plugin. -Prefer deterministic inputs (filename + functionName) so IDs remain stable between builds. +Return `undefined` (or an empty string) to use the default ID. Prefer deterministic inputs (filename + functionName) so IDs remain stable between builds. + +The ID becomes one segment of the server function's URL (`/_serverFn/`), unencoded, so use only ASCII letters, digits, `-`, `.`, `_`, `~` and `$`, and not `.` or `..`. An ID with whitespace, a control or non-ASCII character, or any of `"`, `#`, `/`, `<`, `>`, `?`, `\`, `^`, `` ` ``, `{` and `}`, an ID that is `.` or `..`, or one with a percent-encoding the server reads as another ID (`%41` for `A`, lowercase hex, `%2E`) or rejects, fails the build with an error naming the file, the function and the ID: the request would reach another function or none. Other characters (`%`, `+`, `:`, `;`, `@`, `'`, `|`, `[`, `]`, …) still work, with a deprecation warning: the next major version rejects them, since proxies and servers may encode or normalise them in the URL. `filename` contains `/`, so hash it (as in the example below) rather than embedding it as is. Please note that this customization is **experimental** and subject to change. diff --git a/packages/start-plugin-core/src/start-compiler/compiler.ts b/packages/start-plugin-core/src/start-compiler/compiler.ts index 64dc24df343..13193f7249a 100644 --- a/packages/start-plugin-core/src/start-compiler/compiler.ts +++ b/packages/start-plugin-core/src/start-compiler/compiler.ts @@ -16,6 +16,11 @@ import { handleCreateIsomorphicFn } from './handleCreateIsomorphicFn' import { handleEnvOnlyFn } from './handleEnvOnly' import { handleClientOnlyJSX } from './handleClientOnlyJSX' import { cleanId } from './utils' +import { + customIdCheck, + customIdError, + customIdWarning, +} from './server-fn-id-check' import type { CompilationContext, DevServerFnModuleSpecifierEncoder, @@ -631,11 +636,15 @@ export class StartCompiler { * In dev mode, uses a base64-encoded JSON with file path and export name. * In build mode, uses SHA256 hash or custom generator. */ - private generateFunctionId(opts: { - filename: string - functionName: string - extractedFilename: string - }): string { + private generateFunctionId( + opts: { + filename: string + functionName: string + variableName: string + extractedFilename: string + }, + warn: ((message: string) => void) | undefined, + ): string { if (this.mode === 'dev') { // In dev, encode the file path and export name for direct lookup. // Each bundler adapter supplies its own strategy for encoding @@ -673,11 +682,25 @@ export class StartCompiler { functionId = knownFn.functionId } - if (this.options.generateFunctionId) { - functionId ??= this.options.generateFunctionId({ + if (functionId === undefined && this.options.generateFunctionId) { + functionId = this.options.generateFunctionId({ filename: opts.filename, functionName: opts.functionName, }) + if (functionId) { + const subject = { + name: opts.variableName, + functionName: opts.functionName, + rootRel: opts.filename, + } + const check = customIdCheck(functionId) + if (check === 'error') { + throw new Error(customIdError(subject, functionId)) + } + if (check === 'deprecated') { + warn?.(customIdWarning(subject, functionId)) + } + } } if (!functionId) { functionId = crypto.createHash('sha256').update(entryId).digest('hex') @@ -1400,7 +1423,7 @@ export class StartCompiler { })(), warn: warnFn, - generateFunctionId: (opts) => this.generateFunctionId(opts), + generateFunctionId: (opts) => this.generateFunctionId(opts, warnFn), getKnownServerFns: this.options.getKnownServerFns, serverFnProviderModuleDirectives: this.options.serverFnProviderModuleDirectives, diff --git a/packages/start-plugin-core/src/start-compiler/handleCreateServerFn.ts b/packages/start-plugin-core/src/start-compiler/handleCreateServerFn.ts index dd441bcc243..dd152bdaa46 100644 --- a/packages/start-plugin-core/src/start-compiler/handleCreateServerFn.ts +++ b/packages/start-plugin-core/src/start-compiler/handleCreateServerFn.ts @@ -255,6 +255,7 @@ export function handleCreateServerFn( const functionId = context.generateFunctionId({ filename: relativeFilename, functionName, + variableName: existingVariableName, extractedFilename, }) diff --git a/packages/start-plugin-core/src/start-compiler/server-fn-id-check.ts b/packages/start-plugin-core/src/start-compiler/server-fn-id-check.ts new file mode 100644 index 00000000000..7ddaafce5b1 --- /dev/null +++ b/packages/start-plugin-core/src/start-compiler/server-fn-id-check.ts @@ -0,0 +1,75 @@ +/** + * Which ids a custom `serverFns.generateFunctionId` may return. The client + * puts the id after `TSS_SERVER_FN_BASE` unencoded and the server reads that + * path segment back, so an id has to survive that trip whole. + */ + +interface CustomIdSubject { + /** The server function's variable name. */ + name: string + /** The `functionName` the generator received. */ + functionName: string + /** The defining file, relative to the root. */ + rootRel: string +} + +/** + * `error`: the id never reached its handler: a character that splits or + * ends the path or that a client percent-encodes, a dot segment, which URL + * parsing removes, or a percent-encoding the server decodes to another id + * or rejects (`readBack`). `deprecated`: an ASCII character outside RFC + * 3986's unreserved set and `$`, which reaches the server but which proxies + * and servers may encode or normalise. + */ +export function customIdCheck(id: string): 'ok' | 'deprecated' | 'error' { + if ( + id === '.' || + id === '..' || + /[^\x21-\x7e]|["#/<>?\\^`{}]/.test(id) || + (id.includes('%') && readBack(id) !== id) + ) { + return 'error' + } + return /^[A-Za-z0-9\-._~$]+$/.test(id) ? 'ok' : 'deprecated' +} + +/** + * The id the server reads from the URL of an id holding `%`: the request + * URL's path, decoded as Start's server does when the path holds `%` + * (router-core `getNormalizedURL`, `decodePath`: `decodeURI` keeping `%25` + * and `%5C`, then control characters and `"<>\`{}` encoded again) and + * parsed again; `undefined` when the decode throws (the server answers 400). + */ +function readBack(id: string): string | undefined { + const base = '/_/' + const { pathname } = new URL(base + id, 'http://localhost') + let decoded = '' + try { + for (const part of pathname.split(/(%25|%5C)/i)) { + decoded += /^%(25|5C)$/i.test(part) + ? part + : decodeURI(part).replace( + // eslint-disable-next-line no-control-regex + /[\x00-\x1f\x7f"<>`{}]/g, + (ch) => + `%${ch.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0')}`, + ) + } + } catch { + return undefined + } + const read = new URL(decoded, 'http://localhost').pathname + return read.startsWith(base) + ? read.slice(base.length).split('/')[0] + : undefined +} + +/** The build error of a custom id `customIdCheck` refuses. */ +export function customIdError(fn: CustomIdSubject, id: string): string { + return `[tanstack-start] serverFns.generateFunctionId returned ${JSON.stringify(id)} for the server function ${fn.name} (functionName "${fn.functionName}") of ${fn.rootRel}. A server function id is one path segment of its URL: it cannot hold whitespace, control or non-ASCII characters or any of " # / < > ? \\ ^ \` { }, cannot be "." or "..", and cannot hold a percent-encoding the server reads as another id ("%41") or rejects. Use ASCII letters, digits, "-", ".", "_", "~" and "$".` +} + +/** The build warning of a custom id `customIdCheck` deprecates. */ +export function customIdWarning(fn: CustomIdSubject, id: string): string { + return `[tanstack-start] serverFns.generateFunctionId returned ${JSON.stringify(id)} for the server function ${fn.name} (functionName "${fn.functionName}") of ${fn.rootRel}. Server function ids with characters other than ASCII letters, digits, "-", ".", "_", "~" and "$" are deprecated, and the next major version of TanStack Start rejects them: proxies and servers may encode or normalise them in the URL.` +} diff --git a/packages/start-plugin-core/src/start-compiler/server-fn-resolver-module.ts b/packages/start-plugin-core/src/start-compiler/server-fn-resolver-module.ts index d03bec33413..2d50376a39e 100644 --- a/packages/start-plugin-core/src/start-compiler/server-fn-resolver-module.ts +++ b/packages/start-plugin-core/src/start-compiler/server-fn-resolver-module.ts @@ -31,7 +31,8 @@ export function generateServerFnResolverModule( ? `,\n isClientReferenced: ${fn.isClientReferenced ?? true}` : '' - return `'${id}': { + // (a custom id can hold `'`) + return `'${id.replace(/[\\']/g, '\\$&')}': { functionName: '${fn.functionName}', ${moduleAccess}${clientReferenced} }` diff --git a/packages/start-plugin-core/src/start-compiler/types.ts b/packages/start-plugin-core/src/start-compiler/types.ts index 0dde184961a..91b39f5f8a4 100644 --- a/packages/start-plugin-core/src/start-compiler/types.ts +++ b/packages/start-plugin-core/src/start-compiler/types.ts @@ -90,6 +90,8 @@ export interface ServerFn { export type GenerateFunctionIdFn = (opts: { filename: string functionName: string + /** The server function's variable name, for diagnostics. */ + variableName: string extractedFilename: string }) => string @@ -97,7 +99,10 @@ export type GenerateFunctionIdFn = (opts: { * Optional version that allows returning undefined to use default ID generation. */ export type GenerateFunctionIdFnOptional = ( - opts: Omit[0], 'extractedFilename'>, + opts: Omit< + Parameters[0], + 'extractedFilename' | 'variableName' + >, ) => string | undefined /** diff --git a/packages/start-plugin-core/tests/createServerFn/createServerFn.test.ts b/packages/start-plugin-core/tests/createServerFn/createServerFn.test.ts index 29557e7b9c2..e80f292891a 100644 --- a/packages/start-plugin-core/tests/createServerFn/createServerFn.test.ts +++ b/packages/start-plugin-core/tests/createServerFn/createServerFn.test.ts @@ -790,6 +790,60 @@ describe('createServerFn compiles correctly', async () => { expect(secondResult!.code).toContain('createSsrRpc("constant_id_1"') }) + // The client puts the id in the URL unencoded and the server reads that + // path segment back: a `/`, `#` or `?` cut it short (the call ran another + // server function of the file or none), a client percent-encodes `"`, + // `\`, whitespace, control and non-ASCII characters, URL parsing removes + // dot segments, and the server decodes a percent-encoding to another id or + // rejects it. + test.each([ + 'users/get', + 'users#get', + 'users?get', + 'users"get', + 'users\\get', + 'users get', + 'users\u0007get', + 'utilisateurs-é', + '..', + 'users%41get', + 'x%c3%a9', + '%2E', + 'users%zz', + ])( + 'a custom id the URL never carries whole fails the build: %j', + async (id) => { + const compiler = new StartCompiler({ + env: 'client', + ...getDefaultTestOptions('client'), + mode: 'build', + loadModule: async () => {}, + lookupKinds: new Set(['ServerFn']), + lookupConfigurations: [ + { + libName: '@tanstack/react-start', + rootExport: 'createServerFn', + kind: 'Root', + }, + ], + resolveId: async (id) => id, + generateFunctionId: () => id, + getKnownServerFns: () => ({}), + }) + await expect( + compiler.compile({ + code: ` + import { createServerFn } from '@tanstack/react-start' + export const getUser = createServerFn().handler(async () => 'user') + `, + id: '/test/src/users.ts', + }), + ).rejects.toThrow( + `[tanstack-start] serverFns.generateFunctionId returned ${JSON.stringify(id)} for the server function getUser (functionName "getUser_createServerFn_handler") of src/users.ts.`, + ) + }, + ) + test('should resolve createServerFn from the same binding as a known root export', async () => { const virtualModules: Record = { '@tanstack/start-client-core': ` diff --git a/packages/start-plugin-core/tests/integration/start-app.ts b/packages/start-plugin-core/tests/integration/start-app.ts index 94ef27774f0..ca5603ac2c6 100644 --- a/packages/start-plugin-core/tests/integration/start-app.ts +++ b/packages/start-plugin-core/tests/integration/start-app.ts @@ -23,7 +23,7 @@ import os from 'node:os' import path from 'node:path' import { fileURLToPath, pathToFileURL } from 'node:url' import { createRsbuild } from '@rsbuild/core' -import { createBuilder, createServer } from 'vite' +import { createBuilder, createLogger, createServer } from 'vite' import { onTestFinished } from 'vitest' import type { ViteDevServer } from 'vite' @@ -129,6 +129,8 @@ export interface StartBuild { client: string /** The server build's JavaScript. */ server: string + /** The warnings a Vite build logged (not collected for Rsbuild). */ + warnings: Array } /** Builds the app as `vite build` or `rsbuild build` does. */ @@ -138,11 +140,15 @@ export async function buildStartApp( options: StartOptions = {}, ): Promise { const plugin = await startPlugin(bundler, options) + const warnings: Array = [] if (bundler === 'vite') { + const customLogger = createLogger('error') + customLogger.warn = (message) => warnings.push(message) + customLogger.warnOnce = customLogger.warn const builder = await createBuilder({ root: app.root, configFile: false, - logLevel: 'error', + customLogger, plugins: [plugin], }) await builder.buildApp() @@ -157,6 +163,7 @@ export async function buildStartApp( return { client: await emittedCode(path.join(app.root, 'dist/client')), server: await emittedCode(path.join(app.root, 'dist/server')), + warnings, } } diff --git a/packages/start-plugin-core/tests/integration/start-build-function-id-url.test.ts b/packages/start-plugin-core/tests/integration/start-build-function-id-url.test.ts new file mode 100644 index 00000000000..a5a2b229fc1 --- /dev/null +++ b/packages/start-plugin-core/tests/integration/start-build-function-id-url.test.ts @@ -0,0 +1,130 @@ +/** + * The client puts a server function's id in its URL unencoded, as one path + * segment, and the server reads that segment back. An id a custom + * `serverFns.generateFunctionId` returns with an ASCII character outside + * RFC 3986's unreserved set and `$` (`'`, `:`, `%`…) reaches its handler, + * but proxies and servers may encode or normalise it: it builds, with a + * deprecation warning naming the file. An id of unreserved characters and + * `$` builds without one. (Ids that never reached their handler fail the + * build: `tests/createServerFn/createServerFn.test.ts`.) + */ +import { execFile } from 'node:child_process' +import { readdir } from 'node:fs/promises' +import path from 'node:path' +import { pathToFileURL } from 'node:url' +import { promisify } from 'node:util' +import { describe, expect, test } from 'vitest' +import { appFiles, buildStartApp, createStartApp } from './start-app' + +const timeout = 60_000 + +const execFileAsync = promisify(execFile) + +/** Ids that reach their handler, deprecated, by file. */ +const deprecated: Record = { + 'src/fns/apostrophe.ts': "users'get", + 'src/fns/colon.ts': 'users:get', + 'src/fns/percent.ts': 'users%2Fget', + 'src/fns/brackets.ts': 'users[get]', +} + +const fine: Record = { 'src/fns/fine.ts': 'Users-get.v1_~$' } + +const ids = { ...deprecated, ...fine } + +/** A route whose component references a server function of each file, which returns the file's name. */ +function app() { + const files: Record = {} + const imports: Array = [] + Object.keys(ids).forEach((file, index) => { + files[file] = `import { createServerFn } from '@tanstack/react-start' +export const fn = createServerFn().handler(async () => new Response(${JSON.stringify(file)})) +` + imports.push( + `import { fn as fn${index} } from '${file.replace(/^src\/(.*)\.ts$/, '../$1')}'`, + ) + }) + files['src/routes/index.tsx'] = + `import { createFileRoute } from '@tanstack/react-router' +${imports.join('\n')} +export const Route = createFileRoute('/')({ + component: () => , +}) +` + return appFiles(files) +} + +/** + * Sends a request for each id (`/_serverFn/`, as a page of the same + * origin does) to the server build's entry, in a Node process of its own, + * and gives each response's text. + */ +async function callServer(root: string, ids: Array) { + const dir = path.join(root, 'dist/server') + const entry = (await readdir(dir)).find((file) => + /^(server|index)\.m?js$/.test(file), + ) + if (entry === undefined) { + throw new Error(`no server entry in ${dir}`) + } + const script = `const { default: server } = await import(${JSON.stringify(pathToFileURL(path.join(dir, entry)).href)}) +const texts = [] +for (const id of ${JSON.stringify(ids)}) { + const response = await server.fetch( + new Request(new URL('/_serverFn/' + id, 'http://localhost'), { + headers: { 'sec-fetch-site': 'same-origin' }, + }), + ) + texts.push(await response.text()) +} +process.stdout.write(JSON.stringify(texts)) +` + const { stdout } = await execFileAsync( + process.execPath, + ['--input-type=module', '-e', script], + { cwd: root, env: { ...process.env, NODE_ENV: 'production' } }, + ) + return JSON.parse(stdout) as Array +} + +const options = { + serverFns: { + generateFunctionId: ({ filename }: { filename: string }) => ids[filename], + }, +} + +describe.each(['vite', 'rsbuild'] as const)('%s build', (bundler) => { + // `'` broke the server bundle: the resolver's manifest key was quoted with it + test( + 'a custom id with characters outside the unreserved set builds and reaches its handler', + async () => { + const start = await createStartApp(app()) + await buildStartApp(start, bundler, options) + expect(await callServer(start.root, Object.values(ids))).toEqual( + Object.keys(ids), + ) + }, + timeout, + ) +}) + +// (Rsbuild's transform context has no channel for the compiler's warnings) +describe('vite build', () => { + test( + 'a custom id with characters outside the unreserved set warns, naming the file and the id', + async () => { + const start = await createStartApp(app()) + const build = await buildStartApp(start, 'vite', options) + for (const [file, id] of Object.entries(ids)) { + expect( + build.warnings.some( + (warning) => + warning.includes(file) && warning.includes(JSON.stringify(id)), + ), + `a warning naming ${file}`, + ).toBe(file in deprecated) + } + }, + timeout, + ) +})