diff --git a/docs/guide/server-routing.md b/docs/guide/server-routing.md index fc2a55e8b..9ccc1ab53 100644 --- a/docs/guide/server-routing.md +++ b/docs/guide/server-routing.md @@ -42,7 +42,7 @@ routes/ report.prod.jsx → production only, with JSX ``` -`.dev` routes run only in development; `.prod` routes run in builds, deployments, and production previews. A resource used only by `.dev` routes is not provisioned for production. +`.dev` routes run only in development; `.prod` routes run in builds, deployments, and production previews. A resource imported only in `.dev` route files is not provisioned for production. Imports in directory middleware and other helper files count for both environments. Suffixes apply in `routes/` and [`pages/`](./pages-routing/overview.md#environment-only-pages), not in `middleware/`, `crons/`, or `queues/`. `void prepare` generates types for both environments. @@ -212,7 +212,7 @@ import { cors } from 'hono/cors'; const allowDashboard = cors({ origin: 'https://app.example.com' }); ``` -You can apply middleware globally or per-route. +You can apply middleware globally, to a route directory, or to a single handler. ### Global middleware @@ -260,6 +260,41 @@ For app-specific bypasses such as health checks or public webhooks, compose that Use `c.set()` to share data with downstream handlers. Augment `CloudContextVariables` for typed access with `c.get()`. See [Context variables](./type-safety.md#context-variables). +### Protecting a Pages section + +Put a section guard in `middleware/`. For an admin section, check `c.req.path === '/admin' || c.req.path.startsWith('/admin/')` before allowing the request to proceed. The check must match the route that ultimately serves the request, because configured rewrites run before application middleware. Return 401 when sign-in is required and 403 when a signed-in user lacks permission. The same guard covers document requests, navigation data and action submissions. + +You can also share a guard across each affected page's [loader](./pages-routing/loaders.md) and [actions](./pages-routing/actions-and-forms.md), including default and named actions. Prefer this approach for sections that use rewrites. Void reports `_middleware.*` files under `pages/` during development and build. + +Keep private content out of public assets and [prerendered output](./edge/prerendering.md). Disable [shared ISR](./edge/revalidation.md) for protected URLs and any rewrite sources that serve them. + +### Directory middleware + +Put a guard next to the route files it protects. This example requires sign-in for the files under `routes/admin/`. Check the user's admin permission before calling `next()` if the section requires it. + +```ts +// routes/admin/_middleware.ts +import { defineMiddleware } from 'void'; +import { getUser } from 'void/auth'; + +export default defineMiddleware(async (c, next) => { + if (!getUser()) return c.text('Unauthorized', 401); + await next(); +}); +``` + +Use one `_middleware.ts`, `_middleware.mts`, `_middleware.js`, or `_middleware.mjs` per directory with an active route below it. Default-export a callable middleware. Return a response, set `c.res`, or await `next()` once. Rename an existing helper with one of these filenames if you want to keep importing it yourself. + +After global middleware, Void runs the guards from `routes/` down to the directory containing the selected file. Guards see that file's route params and can edit the response after `await next()`, in reverse order. For example, `routes/admin.ts` and `routes/admin/index.ts` can answer different methods at `/admin`. Only the second uses `routes/admin/_middleware.ts`. + +HEAD selects GET and omits the body. OPTIONS uses an explicit OPTIONS or all-method handler when it matches. An unmatched request has no directory chain. An HTTP rewrite dispatches the destination, which can run globals and common ancestors again. Return a 404 directly to keep its body, or return `c.notFound()` to render a not-found response. + +On Cloudflare, guards also run before a WebSocket upgrade or an ordinary request handled by the WebSocket file. When a rewrite reaches that file, its guard runs on the destination. Use direct upgrade URLs in development, where an allowed rewritten upgrade can return 500. Durable Object hooks and direct `getRoom()` calls do not go through route middleware. + +The guard runs when Void dispatches the route, including after a host server strips a mount prefix. Vite CORS can answer a preflight first. Node production and preview send GET and HEAD under `/assets/*` directly to the asset handler. Provider-served files and reserved endpoints also use their own serving paths. Removing the last global middleware can allow Cloudflare to serve disjoint fingerprinted assets without invoking the Worker. + +Keep private content out of public files and [prerendered output](./edge/prerendering.md). Set `routing.isr: false` or use an effective ISR TTL of zero for protected URLs and any rewrite sources that serve them. [ISR](./edge/revalidation.md) also applies to eligible HTTP routes and can answer before middleware runs. + ### Per-route middleware Pass middleware to `defineHandler` before the final route handler: diff --git a/packages/void/src/application-analysis.ts b/packages/void/src/application-analysis.ts index 84fcb011c..39ff34b43 100644 --- a/packages/void/src/application-analysis.ts +++ b/packages/void/src/application-analysis.ts @@ -12,6 +12,8 @@ import { scanPages } from './pages/scan.ts'; import { detectFramework, FRAMEWORK_SCAN_DIRS, inferProjectBindings } from './plugin-inference.ts'; import { resolveProjectPaths } from './project-paths.ts'; import { scanQueuesSync } from './queues/scan.ts'; +import { scanDirectoryMiddleware } from './router/directory-middleware.ts'; +import type { DirectoryMiddlewareScan } from './router/directory-middleware.ts'; import { scanEmailHandlersSync } from './router/email.ts'; import { isRouteEnabledForEnvironment } from './router/parse-filename.ts'; import type { RouteEnvironment } from './router/parse-filename.ts'; @@ -48,6 +50,7 @@ export type ApplicationAnalysis = { email: ReturnType; routes: ReturnType; middleware: ReturnType; + directoryMiddleware?: DirectoryMiddlewareScan; reasons: ApplicationReasons; }; @@ -67,9 +70,14 @@ export async function getNativeWorkerSourceFiles( if (analysis.email.defaultHandler !== undefined) { emailFiles.push(analysis.email.defaultHandler); } + const routes = [...analysis.routes, ...analysis.websockets].filter((route) => + isRouteEnabledForEnvironment(route, 'dev'), + ); + const guards = analysis.framework ? undefined : scanDirectoryMiddleware(paths, routes); return [ - ...[...analysis.routes, ...analysis.websockets].flatMap((route) => - isRouteEnabledForEnvironment(route, 'dev') ? [join(paths.routesDir, route.filePath)] : [], + ...routes.map((route) => join(paths.routesDir, route.filePath)), + ...Array.from(new Set(Object.values(guards?.chains ?? {}).flat()), (file) => + join(paths.routesDir, file), ), ...pages.flatMap(({ serverPath }) => serverPath === null ? [] : [join(paths.pagesDir, serverPath)], @@ -144,6 +152,10 @@ export function analyzeApplicationSync( const websockets = allWebsockets.filter((route) => isRouteEnabledForEnvironment(route, environment), ); + const routes = scanRoutePatternsSync(root, paths, environment); + const directoryMiddleware = framework + ? undefined + : scanDirectoryMiddleware(paths, [...routes, ...websockets]); // Typed durable modules currently use the root convention on every target. const durableObjects = scanDurableObjectModules(root); const email = scanEmailHandlersSync(paths.sourceRoot); @@ -194,8 +206,9 @@ export function analyzeApplicationSync( durableObjects, workflows, email, - routes: scanRoutePatternsSync(root, paths, environment), + routes, middleware: scanMiddlewareSync(root, paths), + directoryMiddleware, reasons, }; } diff --git a/packages/void/src/application-routing.ts b/packages/void/src/application-routing.ts index 305fc7f28..7764c48c6 100644 --- a/packages/void/src/application-routing.ts +++ b/packages/void/src/application-routing.ts @@ -19,6 +19,7 @@ export async function completeApplicationAnalysis( inventory: { routes: analysis.routes, middleware: analysis.middleware, + directoryMiddleware: analysis.directoryMiddleware, jobs: analysis.jobs, queues: analysis.queues, websockets: analysis.websockets, diff --git a/packages/void/src/pages/scan.ts b/packages/void/src/pages/scan.ts index 84b8d3a01..627803109 100644 --- a/packages/void/src/pages/scan.ts +++ b/packages/void/src/pages/scan.ts @@ -1,6 +1,6 @@ import { existsSync } from 'node:fs'; import { join, dirname, basename, extname, toSlash } from 'pathslash'; -import { glob } from 'tinyglobby'; +import { glob, globSync } from 'tinyglobby'; import { parseSync } from 'vite'; import { readConfig } from '../config.ts'; import { voidWarn } from '../log.ts'; @@ -84,7 +84,7 @@ type PageScanOptions = { output?: 'server' | 'static'; paths?: ProjectPaths; pagesDir?: string; - /** Report pages that share a route. Off when another framework owns pages/ (Nuxt nests users.vue and users/index.vue). */ + /** Check Void Pages conventions. Off when another framework owns pages/. */ checkRoutes?: boolean; /** Keep only pages for this environment (`.dev` / `.prod` suffix). Unset keeps every page. */ environment?: RouteEnvironment; @@ -350,6 +350,10 @@ export function pageFileEnvironment(relativePath: string): RouteEnvironment | nu return env; } +export function scanMisplacedPageMiddleware(pagesDir: string): Array { + return globSync('**/_middleware.*', { cwd: pagesDir, dot: true }).sort(); +} + export async function scanPages(root: string, options?: PageScanOptions): Promise { const trailingSlash = options?.trailingSlash ?? readConfig(root).routing?.trailingSlash; const pagesDir = options?.pagesDir ?? options?.paths?.pagesDir ?? readProjectPaths(root).pagesDir; @@ -631,7 +635,15 @@ export async function scanPages(root: string, options?: PageScanOptions): Promis } } - return { pages, layouts, namedLayouts, ...(boundaries.length ? { boundaries } : {}) }; + const misplacedMiddleware = + options?.checkRoutes === false ? [] : scanMisplacedPageMiddleware(pagesDir); + return { + pages, + layouts, + namedLayouts, + ...(boundaries.length ? { boundaries } : {}), + ...(misplacedMiddleware.length ? { misplacedMiddleware } : {}), + }; } function compareText(left: string, right: string): number { diff --git a/packages/void/src/pages/types.ts b/packages/void/src/pages/types.ts index a436d379b..b4d3686e4 100644 --- a/packages/void/src/pages/types.ts +++ b/packages/void/src/pages/types.ts @@ -69,6 +69,7 @@ export type PageScanResult = { layouts: Array; namedLayouts: Array; boundaries?: Array; + misplacedMiddleware?: Array; }; export type PageBoundaryDefinition = { diff --git a/packages/void/src/plugin-node-target.ts b/packages/void/src/plugin-node-target.ts index 28f002e8f..f056832b6 100644 --- a/packages/void/src/plugin-node-target.ts +++ b/packages/void/src/plugin-node-target.ts @@ -26,13 +26,17 @@ const CF_ONLY_REGEX = new RegExp( ); type NodeTarget = 'node' | 'bun' | 'deno'; +type HonoApp = { + fetch: (request: Request) => Promise; + __voidIsDirectoryDenial?: (request: Request) => boolean; +}; /** * Bridge Node.js HTTP to Web API and serve via a Hono app. * Used by both dev server and preview server middleware. */ function honoMiddleware( - getApp: () => Promise<{ fetch: (req: Request) => Promise } | null>, + getApp: () => Promise, isViteFile?: (request: Request) => Promise, ) { return async (req: IncomingMessage, res: ServerResponse, next: (err?: unknown) => void) => { @@ -78,6 +82,7 @@ function honoMiddleware( // requests still fall through so Vite can serve assets and dev resources. if ( response.status === 404 && + !app.__voidIsDirectoryDenial?.(request) && ((await isViteFile?.(request)) || (!response.headers.get('content-type')?.includes('text/html') && !response.headers.has('X-VoidPages'))) @@ -292,8 +297,12 @@ export function nodeTargetPlugin( default: { fetch(request: Request, env: { ASSETS: typeof assets }): Promise; }; + __voidIsDirectoryDenial?: HonoApp['__voidIsDirectoryDenial']; + }; + return { + fetch: (request: Request) => mod.default.fetch(request, { ASSETS: assets }), + __voidIsDirectoryDenial: mod.__voidIsDirectoryDenial, }; - return { fetch: (request: Request) => mod.default.fetch(request, { ASSETS: assets }) }; }, async (request) => { try { @@ -311,14 +320,20 @@ export function nodeTargetPlugin( configurePreviewServer(server) { // Import the built app module (not index.js which starts a server). const entryPath = join(process.cwd(), 'dist', 'ssr', 'app.js'); - let appPromise: Promise<{ fetch: (req: Request) => Promise } | null> | null = null; + let appPromise: Promise | null = null; server.middlewares.use( honoMiddleware(() => { if (!appPromise) { const entryUrl = pathToFileURL(entryPath).href; appPromise = import(/* @vite-ignore */ entryUrl).then( - (m: { default: { fetch: (req: Request) => Promise } }) => m.default, + (m: { + default: HonoApp; + __voidIsDirectoryDenial?: HonoApp['__voidIsDirectoryDenial']; + }) => ({ + fetch: (request) => m.default.fetch(request), + __voidIsDirectoryDenial: m.__voidIsDirectoryDenial, + }), () => null, ); } diff --git a/packages/void/src/plugin-routing.ts b/packages/void/src/plugin-routing.ts index 32144a945..e6e9db84b 100644 --- a/packages/void/src/plugin-routing.ts +++ b/packages/void/src/plugin-routing.ts @@ -2,14 +2,14 @@ import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } import { homedir } from 'node:os'; import { fileURLToPath } from 'node:url'; import { isDeepStrictEqual } from 'node:util'; -import { dirname, join, relative, resolve } from 'pathslash'; +import { basename, dirname, join, relative, resolve } from 'pathslash'; import { createRunnableDevEnvironment, isRunnableDevEnvironment, normalizePath, parseSync, } from 'vite'; -import type { Plugin, ResolvedConfig, RunnableDevEnvironment } from 'vite'; +import type { DevEnvironment, Plugin, ResolvedConfig, RunnableDevEnvironment } from 'vite'; import type { ApplicationAnalysis } from './application-analysis.ts'; import { completeApplicationAnalysis } from './application-routing.ts'; import { hasApiRoutes, hasDocumentRoutes, resolveAssetRoutingPolicy } from './asset-routing.ts'; @@ -37,6 +37,7 @@ import { getDatabaseAuthDateType, getDatabaseDialect, readConfig } from './confi import type { VoidConfig } from './config.ts'; import { collectPages, collectRevalidate, hasRevalidate } from './isr-config.ts'; import type { VoidMdPlugin } from './pages/islands-plugin.ts'; +import { scanMisplacedPageMiddleware } from './pages/scan.ts'; import { readProjectPaths } from './project-paths.ts'; import { readDeployBuildQueueNames } from './queues/cloudflare-names.ts'; import { @@ -138,6 +139,16 @@ function isInDirectory(path: string, directory: string): boolean { return path === directory || path.startsWith(directory + '/'); } +function invalidateRouteModule(environment: DevEnvironment, structural: boolean): void { + const module = environment.moduleGraph.getModuleById(VIRTUAL_ROUTES_ID); + if (module) { + environment.moduleGraph.invalidateModule(module); + if (structural) { + environment.hot.send({ type: 'full-reload' }); + } + } +} + /** * Vite plugin that provides file-based routing. * - Scans routes/ and middleware/ directories @@ -160,6 +171,7 @@ export function routingPlugin( api: { finalizeCloudflareAssets(clientDir: string, assetsDir: string): void }; } { let scan: ScanResult | null = null; + let directoryMiddleware: ScanResult['directoryMiddleware']; let routeEnvironment: RouteEnvironment = 'prod'; let platformBuild = false; let previewing = false; @@ -213,6 +225,17 @@ export function routingPlugin( ), ); + function pageMiddlewareMessage( + files = scanMisplacedPageMiddleware(pagesDir), + ): string | undefined { + if (files.length > 0) { + const locations = files + .map((file) => `"${paths.sourceRelative(`pages/${file}`)}"`) + .join(', '); + return `pages: Directory middleware is unsupported in Void Pages (${locations}). Use global middleware in ${paths.sourceRelative('middleware/')} or a shared guard in page loaders and actions.`; + } + } + function hasEmailHandlers(): boolean { const email = scan?.email; return Boolean(email && (email.addresses.length > 0 || email.defaultHandler)); @@ -238,6 +261,7 @@ export function routingPlugin( async function rescan(refresh = false) { const analysis = options.getApplicationAnalysis(routeEnvironment, refresh); + directoryMiddleware = analysis.directoryMiddleware; const nextScan = (await completeApplicationAnalysis(analysis)).scan; const entries = validateSsrEntries(root, paths); scan = nextScan; @@ -863,6 +887,20 @@ export function routingPlugin( return regenerateInOrder(async () => { generatedRouteInputs = undefined; await rescan(); + if (!compileOptions.dev) { + const misplacedMiddleware = completedScan().pages.misplacedMiddleware ?? []; + if (this.meta.watchMode && existsSync(pagesDir)) { + this.addWatchFile(pagesDir); + for (const file of misplacedMiddleware) { + this.addWatchFile(join(pagesDir, file)); + } + } + const diagnostic = + directoryMiddleware?.diagnostic ?? pageMiddlewareMessage(misplacedMiddleware); + if (diagnostic) { + throw new Error(diagnostic); + } + } if (options.target && (scan?.websockets?.length ?? 0) > 0) { throw new Error('routing: WebSocket routes require the default Cloudflare target.'); } @@ -1005,7 +1043,7 @@ export function routingPlugin( await regenerateInOrder(() => rescan()); } return compileRouteTable( - completedScan(), + { ...completedScan(), directoryMiddleware }, routesDir, middlewareDir, jobsDir, @@ -1036,6 +1074,23 @@ export function routingPlugin( // Watch the source convention directories for file changes const watcher = devServer.watcher; + function refreshPageMiddlewareDiagnostic() { + const diagnostic = pageMiddlewareMessage(); + if (diagnostic !== compileOptions.pageMiddlewareDiagnostic) { + compileOptions.pageMiddlewareDiagnostic = diagnostic; + if (diagnostic) { + devServer.config.logger.error(diagnostic, { timestamp: true }); + } else { + devServer.config.logger.info('Void Pages middleware error cleared.', { + timestamp: true, + }); + } + for (const environment of Object.values(devServer.environments)) { + invalidateRouteModule(environment, true); + } + } + } + const handleFileChange = async (path: string, event: 'add' | 'change' | 'unlink') => { const normalizedPath = normalizePath(path); invalidateSourceAnalysis(normalizedPath); @@ -1066,6 +1121,14 @@ export function routingPlugin( const shouldRestart = await regenerateInOrder(async () => { invalidateSourceAnalysis(normalizedPath); + if ( + isInDirectory(normalizedPath, normalizedPagesDir) && + basename(normalizedPath).startsWith('_middleware.') + ) { + // A filename diagnostic must take effect even if another route cannot be scanned. + refreshPageMiddlewareDiagnostic(); + return; + } if (workflowChanged && !isDeepStrictEqual(options.workflows, scanWorkflowModules(root))) { return true; } @@ -1076,8 +1139,15 @@ export function routingPlugin( // Re-scan and invalidate the virtual module in ALL environments. // The route table virtual module lives in the workerd environment, // not the client — so we must iterate all environments. + const guardChanged = + isInDirectory(normalizedPath, normalizedRoutesDir) && + basename(normalizedPath).startsWith('_middleware.') && + Object.values(directoryMiddleware?.chains ?? {}).some((chain) => + chain.includes(relative(normalizedRoutesDir, normalizedPath)), + ); const forceRegeneration = event !== 'change' || + guardChanged || authConfigChanged || isPotentialEnvFilePath(normalizedPath) || ssrEntryAbsPaths.has(normalizedPath); @@ -1086,9 +1156,18 @@ export function routingPlugin( generatedRouteInputs = undefined; } + const previousDirectoryMiddleware = directoryMiddleware; try { await rescan(true); } catch (error) { + if ( + guardChanged || + !isDeepStrictEqual(previousDirectoryMiddleware, directoryMiddleware) + ) { + for (const environment of Object.values(devServer.environments)) { + invalidateRouteModule(environment, event !== 'change'); + } + } // Keep the last good route table; the next change rescans. const message = error instanceof Error ? error.message : String(error); // An adapter's pages plugin rescans page adds, removals and .md saves @@ -1163,12 +1242,8 @@ export function routingPlugin( } } } - const mod = env.moduleGraph.getModuleById(VIRTUAL_ROUTES_ID); - if (mod && routeInputsChanged) { - env.moduleGraph.invalidateModule(mod); - if (structural) { - env.hot.send({ type: 'full-reload' }); - } + if (routeInputsChanged) { + invalidateRouteModule(env, structural); } } @@ -1201,6 +1276,10 @@ export function routingPlugin( watcher.on('add', (path) => onFileChange(path, 'add')); watcher.on('change', (path) => onFileChange(path, 'change')); watcher.on('unlink', (path) => onFileChange(path, 'unlink')); + // Seed before later plugins import the routes. Vite ignores initial add + // events, so reconcile again once the watcher has finished its scan. + watcher.on('ready', refreshPageMiddlewareDiagnostic); + refreshPageMiddlewareDiagnostic(); // File-based routing rule HMR: `public/_redirects` / `public/_headers` // changes re-merge + invalidate the route module so rules take effect diff --git a/packages/void/src/router/compile.ts b/packages/void/src/router/compile.ts index 5d6a6e83a..bbbce12f0 100644 --- a/packages/void/src/router/compile.ts +++ b/packages/void/src/router/compile.ts @@ -18,11 +18,19 @@ import type { ScanResult } from './scan.ts'; const FETCH_SERVER_PATH = fileURLToPath(import.meta.resolve('#self/runtime/fetch-server')); const ROUTING_RUNTIME_PATH = fileURLToPath(import.meta.resolve('#self/runtime/routing')); -function pushDefaultErrorPageHelpers(lines: Array, options: CompileOptions): void { +function pushDefaultErrorPageHelpers( + lines: Array, + options: CompileOptions, + pages = true, +): void { lines.push( `const __errorRenderer = __createErrorRenderer(${JSON.stringify({ dev: options.dev === true, projectRoot: options.projectRoot, homeDir: options.homeDir })});`, - 'app.onError(__createPageErrorHandler(__matchedRoutes, __errorRenderer.onError));', ); + if (pages) { + lines.push( + '__routingRuntime.onError(__createPageErrorHandler(__matchedRoutes, __errorRenderer.onError));', + ); + } } export type AuthCompileOptions = { @@ -53,6 +61,8 @@ export type CompileOptions = { * `x-void-dev-trigger`; every build uses the proxy token or build key. */ dev?: boolean; + /** Misplaced Pages middleware reported by the dev app on requests. */ + pageMiddlewareDiagnostic?: string; /** * Token for local dev manual trigger endpoints (`x-void-dev-trigger`). * Stable for a dev-server process so tooling can print paste-ready curl @@ -186,6 +196,24 @@ export function compileRouteTable( const lines: Array = []; const auth = options.auth; const webSockets = scan.websockets ?? []; + const directoryDiagnostic = scan.directoryMiddleware?.diagnostic; + if (directoryDiagnostic && !options.dev) { + throw new Error(directoryDiagnostic); + } + const directory = directoryDiagnostic ? undefined : scan.directoryMiddleware; + const guardFiles = new Set(Object.values(directory?.chains ?? {}).flat()); + const guardNames = new Map(Array.from(guardFiles, (file, i) => [file, `__directoryGuard${i}`])); + const wrapWithDirectoryMiddleware = (file: string, handler: string): string => { + const chain = directory?.chains[file]; + if (!chain) { + return handler; + } + const guards = chain.map( + (guard) => + `[${JSON.stringify(relative(options.projectRoot, `${routesDir}/${guard}`))}, ${guardNames.get(guard)}${options.dev ? '.default' : ''}]`, + ); + return `__routingRuntime.directoryMiddleware([${guards.join(', ')}], ${handler}, __directoryNotFound)`; + }; const managedDispatch = options.nodeTarget !== true && options.dev !== true && options.managedDispatch === true; @@ -237,6 +265,11 @@ export function compileRouteTable( const mw = scan.middleware[i]; lines.push(`import middleware${i} from ${JSON.stringify(`${middlewareDir}/${mw.filePath}`)};`); } + for (const [file, name] of guardNames) { + lines.push( + `import ${options.dev ? '* as ' : ''}${name} from ${JSON.stringify(`${routesDir}/${file}`)};`, + ); + } for (let i = 0; i < webSockets.length; i++) { const route = webSockets[i]; lines.push(`import websocket${i} from ${JSON.stringify(`${routesDir}/${route.filePath}`)};`); @@ -281,7 +314,7 @@ export function compileRouteTable( } const blockedExts = ASSET_EXTENSIONS.filter((e) => !usedExts.has(e)); lines.push( - `const __routingRuntime = __createRoutingRuntime(app, ${JSON.stringify({ dev: options.dev === true, nodeTarget: options.nodeTarget === true, managedDispatch, blockedAssetExtensions: blockedExts })});`, + `const __routingRuntime = __createRoutingRuntime(app, ${JSON.stringify({ dev: options.dev === true, nodeTarget: options.nodeTarget === true, managedDispatch, blockedAssetExtensions: blockedExts, middlewareDiagnostic: options.pageMiddlewareDiagnostic ?? directoryDiagnostic })});`, 'export const requestContext = __routingRuntime.requestContext;', 'app.use(__routingRuntime.contextMiddleware);', 'app.use(__routingRuntime.requestMiddleware);', @@ -345,13 +378,20 @@ export function compileRouteTable( // middleware run before the Durable Object receives the request. Register // them before HTTP routes to preserve WebSocket priority when both route // kinds share a path, while non-upgrade requests continue through normally. + if (webSockets.length > 0) { + lines.push( + 'const __isWebSocketUpgrade = (c) => c.req.raw.headers.get("upgrade")?.toLowerCase() === "websocket";', + ); + } for (let i = 0; i < webSockets.length; i++) { const route = webSockets[i]; + const forward = `(c) => __forwardWebSocketRequest(c.req.raw, c.env, __voidWebSocketRoutes[${i}])`; lines.push( - `app.all(${JSON.stringify(route.pattern)}, async (c, next) => {`, - ` if (c.req.raw.headers.get("upgrade")?.toLowerCase() !== "websocket") return next();`, - ` return __forwardWebSocketRequest(c.req.raw, c.env, __voidWebSocketRoutes[${i}]);`, - '});', + `const __wsHandler${i} = ${wrapWithDirectoryMiddleware(route.filePath, forward)};`, + `app.all(${JSON.stringify(route.pattern)}, __markRouteHandler((c, next) => {`, + ' if (!__isWebSocketUpgrade(c)) return next();', + ` return __wsHandler${i}(c);`, + '}, __isWebSocketUpgrade));', ); } if (webSockets.length > 0) { @@ -385,17 +425,18 @@ export function compileRouteTable( ); } + const handler = (method: string) => { + const unguarded = `__createHttpRouteHandler(${loaderName}, ${JSON.stringify(method)})`; + const guarded = wrapWithDirectoryMiddleware(route.filePath, unguarded); + return guarded === unguarded ? unguarded : `__markRouteHandler(${guarded})`; + }; if (route.methods.length === 0) { // No recognized HTTP exports — register as all() - lines.push( - `app.all(${JSON.stringify(route.pattern)}, __createHttpRouteHandler(${loaderName}, "default"));`, - ); + lines.push(`app.all(${JSON.stringify(route.pattern)}, ${handler('default')});`); } else { for (const method of route.methods) { const honoMethod = method.toLowerCase(); - lines.push( - `app.${honoMethod}(${JSON.stringify(route.pattern)}, __createHttpRouteHandler(${loaderName}, ${JSON.stringify(method)}));`, - ); + lines.push(`app.${honoMethod}(${JSON.stringify(route.pattern)}, ${handler(method)});`); } } } @@ -454,6 +495,8 @@ export function compileRouteTable( // Pages mode — generate page route handlers const pageNames = createIdentifierNames(); + const rootNotFound = pages && createBoundaryManifest(scan.pages).root; + const hasPageRoutes = pages && (scan.pages.pages.length > 0 || rootNotFound); if ( pages && (scan.pages.pages.length > 0 || @@ -463,6 +506,20 @@ export function compileRouteTable( ) { compilePageRoutes(lines, scan, pages, options, pageNames); } + if (guardFiles.size) { + if (!hasPageRoutes) { + pushDefaultErrorPageHelpers(lines, options, false); + } + lines.push( + `import { renderDirectoryNotFound as __renderDirectoryNotFound } from ${JSON.stringify(ROUTING_RUNTIME_PATH)};`, + `function __directoryNotFound(c) { return __renderDirectoryNotFound(c, __errorRenderer${rootNotFound ? ', __voidRootNotFound' : ''}); }`, + ); + } + if (options.nodeTarget) { + lines.push( + `export { isDirectoryDenial as __voidIsDirectoryDenial } from ${JSON.stringify(ROUTING_RUNTIME_PATH)};`, + ); + } if (!pages || !createBoundaryManifest(scan.pages).root) { lines.push( @@ -474,7 +531,7 @@ export function compileRouteTable( // Pages handlers win for their methods; upgrades were forwarded above. for (let i = 0; i < webSockets.length; i++) { lines.push( - `app.all(${JSON.stringify(webSockets[i].pattern)}, __markRouteHandler((c) => __forwardWebSocketRequest(c.req.raw, c.env, __voidWebSocketRoutes[${i}])));`, + `app.all(${JSON.stringify(webSockets[i].pattern)}, __markRouteHandler(__wsHandler${i}));`, ); } if (webSockets.length > 0) { @@ -1615,6 +1672,7 @@ import { parseAccept } from ${JSON.stringify(fileURLToPath(import.meta.resolve(' return `${staticImport} ${precompressedImport}import { fileURLToPath } from "node:url"; import innerApp, { __voidCollectPrerenderPaths, __voidRenderStaticNotFound } from "virtual:void-routes"; +export { __voidIsDirectoryDenial } from "virtual:void-routes"; import { Hono, prerenderPathsResponse as __prerenderPathsResponse } from ${JSON.stringify(ROUTING_RUNTIME_PATH)}; ${envSchemaImport} // dist/client, created on first use so a server that supplies its own ASSETS diff --git a/packages/void/src/router/directory-middleware.ts b/packages/void/src/router/directory-middleware.ts new file mode 100644 index 000000000..549d184d0 --- /dev/null +++ b/packages/void/src/router/directory-middleware.ts @@ -0,0 +1,54 @@ +import { statSync } from 'node:fs'; +import { dirname, join } from 'pathslash'; +import type { ProjectPaths } from '../project-paths.ts'; + +const GUARD_NAMES = ['_middleware.ts', '_middleware.mts', '_middleware.js', '_middleware.mjs']; + +export type DirectoryMiddlewareScan = { + chains: Record>; + diagnostic?: string; +}; + +export function scanDirectoryMiddleware( + paths: ProjectPaths, + routes: ReadonlyArray<{ filePath: string }>, +): DirectoryMiddlewareScan | undefined { + const guards = new Map(); + let diagnostic: string | undefined; + const lookup = (dir: string) => { + if (!guards.has(dir)) { + const files = GUARD_NAMES.flatMap((name) => { + const file = join(dir, name); + return statSync(join(paths.routesDir, file), { throwIfNoEntry: false })?.isFile() + ? [file] + : []; + }); + if (files.length > 1) { + diagnostic ??= `routes: multiple directory middleware files: ${files + .map((file) => paths.sourceRelative(`routes/${file}`)) + .join(', ')}. Keep one _middleware file per directory.`; + } + guards.set(dir, files[0]); + } + return guards.get(dir); + }; + const chains: DirectoryMiddlewareScan['chains'] = {}; + for (const { filePath } of routes) { + const chain: Array = []; + let dir = dirname(filePath.replaceAll('\\', '/')); + while (true) { + const guard = lookup(dir); + if (guard) { + chain.push(guard); + } + if (dir === '.') { + break; + } + dir = dirname(dir); + } + if (chain.length) { + chains[filePath] = chain.reverse(); + } + } + return Object.keys(chains).length ? { chains, ...(diagnostic && { diagnostic }) } : undefined; +} diff --git a/packages/void/src/router/scan.ts b/packages/void/src/router/scan.ts index 10714ed39..cb62b9fac 100644 --- a/packages/void/src/router/scan.ts +++ b/packages/void/src/router/scan.ts @@ -8,6 +8,7 @@ import type { ProjectPaths } from '../project-paths.ts'; import type { QueueDefinition } from '../queues/scan.ts'; import { listRouteFiles } from '../shared/convention-files.ts'; import { detectHttpExports } from './detect-exports.ts'; +import type { DirectoryMiddlewareScan } from './directory-middleware.ts'; import type { EmailHandlersScan } from './email.ts'; import { isRouteEnabledForEnvironment, parseRouteFilename } from './parse-filename.ts'; import type { RouteDefinition, RouteEnvironment } from './parse-filename.ts'; @@ -19,6 +20,7 @@ export type ScanResult = { routes: Array; websockets?: Array; middleware: Array; + directoryMiddleware?: DirectoryMiddlewareScan; jobs: Array; queues: Array; pages: PageScanResult; diff --git a/packages/void/src/runtime/routing/index.ts b/packages/void/src/runtime/routing/index.ts index f1a01123d..d9d0c4ec6 100644 --- a/packages/void/src/runtime/routing/index.ts +++ b/packages/void/src/runtime/routing/index.ts @@ -6,7 +6,7 @@ import { mergeQueryIntoLocation, substituteParams, } from '@void/edge'; -import type { Context, Hono, MiddlewareHandler, NotFoundHandler } from 'hono'; +import type { Context, ErrorHandler, Hono, MiddlewareHandler, Next, NotFoundHandler } from 'hono'; import type { TypedResponse } from 'hono'; import type { RedirectStatusCode } from 'hono/utils/http-status'; import type { RouteDestination, RouteUrlInput } from 'void/routes'; @@ -54,6 +54,7 @@ export type RoutingContext = Context & { originalUrl: () => URL | null; isRewritten: () => boolean; }; +type DirectoryGuard = (c: Context, next: Next) => Response | void | Promise; export type RoutingRuntime = { requestContext: AsyncLocalStorage; contextMiddleware: MiddlewareHandler; @@ -64,6 +65,27 @@ export type RoutingRuntime = { headerMiddleware: (rules: Array, phase?: 'auth-error') => MiddlewareHandler; applyFallback: (context: Context, rules: Array) => Promise; markNoMatch: (request: Request, response: Response) => Response; + onError: (handler: ErrorHandler) => void; + directoryMiddleware: ( + guards: ReadonlyArray, + terminal: (c: Context) => Response | Promise, + notFound: NotFoundHandler, + ) => (c: Context) => Promise; +}; + +const directoryDenials = new WeakSet(); +export const isDirectoryDenial = (request: Request): boolean => directoryDenials.has(request); + +type NotFoundOrigin = 'miss' | 'guard' | 'endpoint'; + +// Match Hono's default response for apps that do not install a Pages error handler. +const defaultDirectoryError: ErrorHandler = (error, c) => { + if ('getResponse' in error) { + const response = error.getResponse(); + return c.newResponse(response.body, response); + } + console.error(error); + return c.text('Internal Server Error', 500); }; /** One state owner per generated app: recursive dispatch shares rewrite and fallback guards. */ @@ -74,6 +96,7 @@ export function createRoutingRuntime( nodeTarget?: boolean; managedDispatch?: boolean; blockedAssetExtensions?: Array; + middlewareDiagnostic?: string; } = {}, ): RoutingRuntime { const originalUrls = new WeakMap(); @@ -86,90 +109,131 @@ export function createRoutingRuntime( const headerApplied = new WeakSet(); const explicitNotFound = new WeakSet(); let trackAssetMisses = false; + let trackDirectoryDenials = false; + let middlewareDiagnostic = options.middlewareDiagnostic; const intentionalResponses = new WeakSet(); - const routeMisses = new WeakMap>(); - const missBodies = new WeakMap>(); - const trackMissBody = (c: Context, body: ReadableStream | null): void => { + const responseOrigins = new WeakMap>(); + const bodyOrigins = new WeakMap>(); + const responseContext = new AsyncLocalStorage(); + const trackedCopies = new WeakSet(); + const compressedHeadCandidates = new WeakSet(); + const guardErrors = new WeakMap(); + let onError = defaultDirectoryError; + const trackBody = (c: Context, body: ReadableStream | null, origin: NotFoundOrigin): void => { if (!body) { return; } - let bodies = missBodies.get(c); + let bodies = bodyOrigins.get(c); if (!bodies) { - bodies = new WeakSet(); - missBodies.set(c, bodies); + bodies = new WeakMap(); + bodyOrigins.set(c, bodies); } if (bodies.has(body)) { return; } - bodies.add(body); - // Middleware such as Hono's compress() replaces the body with a transform - // of this stream. That still carries a miss; an unrelated replacement does not. - if (Object.isExtensible(body)) { - // oxlint-disable-next-line typescript/unbound-method -- The wrapper calls the original with its own receiver. + bodies.set(body, origin); + // Compression can transform the same body into a new stream. + if (Object.isExtensible(body) && !trackedCopies.has(body)) { + trackedCopies.add(body); + // oxlint-disable-next-line typescript/unbound-method -- Call the original with its receiver. const pipeThrough = body.pipeThrough; Object.defineProperty(body, 'pipeThrough', { configurable: true, writable: true, value(this: ReadableStream, ...args: Parameters) { const transformed = pipeThrough.apply(this, args); - if (this === body) { - trackMissBody(c, transformed); + const current = responseContext.getStore(); + const source = current && bodyOrigins.get(current)?.get(this); + if (current && source) { + trackBody(current, transformed, source); } return transformed; }, }); } }; - const recordMiss = (c: Context, response: Response): void => { - const misses = routeMisses.get(c) ?? []; - if (misses.includes(response)) { + const markOrigin = (c: Context, response: Response, origin: NotFoundOrigin): void => { + let responses = responseOrigins.get(c); + if (!responses) { + responses = new WeakMap(); + responseOrigins.set(c, responses); + } + if (responses.has(response)) { return; } - misses.push(response); - routeMisses.set(c, misses); - trackMissBody(c, response.body); + responses.set(response, origin); + trackBody(c, response.body, origin); trackResponseCopies(c); // Fetch's clone tees the body, so neither clone shares its former stream. - if (Object.isExtensible(response)) { - // oxlint-disable-next-line typescript/unbound-method -- The wrapper calls the original with its own receiver. + if (Object.isExtensible(response) && !trackedCopies.has(response)) { + trackedCopies.add(response); + // oxlint-disable-next-line typescript/unbound-method -- Call the original with its receiver. const clone = response.clone; Object.defineProperty(response, 'clone', { configurable: true, writable: true, value(this: Response) { const copy = clone.call(this); - if (this === response) { - trackMissBody(c, this.body); - recordMiss(c, copy); + const current = responseContext.getStore(); + const source = current && responseOrigins.get(current)?.get(this); + if (current && source) { + trackBody(current, this.body, source); + markOrigin(current, copy, source); } return copy; }, }); } }; - const isRouteMiss = (c: Context, response: Response): boolean => - routeMisses - .get(c) - ?.some((miss) => miss === response || (miss.body !== null && miss.body === response.body)) === - true || - (response.body !== null && missBodies.get(c)?.has(response.body) === true); + const originOf = (c: Context, response: Response): NotFoundOrigin | undefined => { + if ( + compressedHeadCandidates.has(response) && + /^(gzip|deflate)$/.test(response.headers.get('Content-Encoding') ?? '') + ) { + return 'guard'; + } + return ( + responseOrigins.get(c)?.get(response) ?? + (response.body ? bodyOrigins.get(c)?.get(response.body) : undefined) + ); + }; const tracksResponseCopies = new WeakSet(); const trackResponseCopies = (c: Context): void => { if (tracksResponseCopies.has(c)) { return; } tracksResponseCopies.add(c); - // Carry provenance to the response Hono exposes after assignment or a header edit. + // Carry provenance through Hono assignment and header edits. const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(c), 'res'); if (descriptor?.get && descriptor.set) { - // oxlint-disable-next-line typescript/unbound-method -- The original setter is called with the Hono context below. + // oxlint-disable-next-line typescript/unbound-method -- Call the original on the Hono context. const set = descriptor.set; Object.defineProperty(c, 'res', { ...descriptor, set(response: Response | undefined) { + const before = c.finalized ? c.res : undefined; set.call(c, response); - if (response && isRouteMiss(c, response) && c.res !== response) { - recordMiss(c, c.res); + if (!response) { + return; + } + const fromError = c.error && guardErrors.get(c) === c.error; + if (fromError) { + guardErrors.delete(c); + } + const origin = fromError && response.status === 404 ? 'guard' : originOf(c, response); + if (origin) { + markOrigin(c, c.res, origin); + } else if ( + c.req.method === 'HEAD' && + response.status === 404 && + !response.body && + before?.body && + originOf(c, before) === 'guard' && + !before.headers.has('Content-Encoding') + ) { + // Hono compress() assigns a bodyless copy, then sets Content-Encoding on it. + // An independent replacement with the same original headers stays unmarked. + compressedHeadCandidates.add(c.res); } }, }); @@ -178,8 +242,11 @@ export function createRoutingRuntime( c.header = (...args) => { const before = c.finalized ? c.res : undefined; header(...args); - if (before && c.res !== before && isRouteMiss(c, before)) { - recordMiss(c, c.res); + if (before && c.res !== before) { + const origin = originOf(c, before); + if (origin) { + markOrigin(c, c.res, origin); + } } }; }; @@ -212,11 +279,17 @@ export function createRoutingRuntime( // The enclosing response may depend on auth even if middleware clones or replaces it. authDependentRequests.add(c.req.raw); } - if (trackAssetMisses && response.status === 404) { - if (intentionalNotFoundRequests.has(request)) { + if (response.status === 404 && (trackAssetMisses || trackDirectoryDenials)) { + if (isDirectoryDenial(request)) { + markOrigin(c, response, 'guard'); + intentionalResponses.add(response); + } else if (trackAssetMisses && intentionalNotFoundRequests.has(request)) { intentionalResponses.add(response); + if (trackDirectoryDenials) { + markOrigin(c, response, 'endpoint'); + } } else { - recordMiss(c, response); + markOrigin(c, response, 'miss'); } } return response; @@ -288,6 +361,9 @@ export function createRoutingRuntime( }; const contextMiddleware: MiddlewareHandler = async (context, next) => { const c = context as RoutingContext; + if (directoryDenials.delete(c.req.raw)) { + intentionalNotFoundRequests.delete(c.req.raw); + } if (trackAssetMisses) { intentionalNotFoundRequests.delete(c.req.raw); const notFound = c.notFound.bind(c); @@ -349,13 +425,19 @@ export function createRoutingRuntime( }; c.originalUrl = () => originalUrls.get(c.req.raw) ?? null; c.isRewritten = () => originalUrls.has(c.req.raw); - await next(); + await responseContext.run(c, next); c.res = pagesRedirectResponse(c.req.raw, c.res); - if (!trackAssetMisses) { - return; - } - if (c.res.status === 404 && !isRouteMiss(c, c.res)) { - intentionalNotFoundRequests.add(c.req.raw); + if (c.res.status === 404) { + const origin = originOf(c, c.res); + if (origin === 'guard') { + // Hono's final HEAD copy retains this request object. + directoryDenials.add(c.req.raw); + intentionalNotFoundRequests.add(c.req.raw); + c.header('X-Void-No-Match', undefined); + } + if (trackAssetMisses && origin !== 'miss') { + intentionalNotFoundRequests.add(c.req.raw); + } } }; return { @@ -371,7 +453,7 @@ export function createRoutingRuntime( } return Promise.resolve(response).then((miss) => { if (miss.status === 404 && !intentionalResponses.has(miss)) { - recordMiss(c, miss); + markOrigin(c, miss, 'miss'); } return miss; }); @@ -383,7 +465,113 @@ export function createRoutingRuntime( } return response; }, + onError: (handler) => { + onError = handler; + app.onError(handler); + }, + directoryMiddleware: (guards, terminal, notFound) => { + for (const [file, handler] of guards) { + if (typeof handler !== 'function') { + const message = `routes: '${file}' must have a callable default export.`; + if (!options.dev) { + throw new TypeError(message); + } + middlewareDiagnostic ??= message; + } + } + trackDirectoryDenials = true; + return async (c) => { + const originalNotFound = c.notFound; + const denyNotFound = () => notFound(c); + const renderError = async (error: unknown) => { + if (!(error instanceof Error)) { + throw error; + } + c.error = error; + c.notFound = originalNotFound; + try { + const response = await onError(error, c); + if (response.status === 404 && guardErrors.get(c) !== error && !originOf(c, response)) { + markOrigin(c, response, 'endpoint'); + } + c.res = response; + } finally { + c.notFound = denyNotFound; + } + }; + const run = async (index: number): Promise => { + const entry = guards[index]; + if (!entry) { + c.notFound = originalNotFound; + try { + const result = await terminal(c); + const response = c.finalized ? c.res : result; + if (response.status === 404 && !originOf(c, response)) { + markOrigin(c, response, 'endpoint'); + } + if (!c.finalized) { + c.res = response; + } + } finally { + c.notFound = denyNotFound; + } + return; + } + const [file, handler] = entry; + const before = c.finalized ? c.res : undefined; + let nextCalled = false; + let nextError: unknown; + try { + const response = await handler(c, async () => { + if (nextCalled) { + throw new Error(`routes: '${file}' called next() more than once.`); + } + nextCalled = true; + try { + await run(index + 1).catch(renderError); + } catch (error) { + nextError = error; + throw error; + } + }); + if (response instanceof Response) { + // Hono keeps the response once the context is finalized. + if (!c.finalized) { + if (response.status === 404 && !originOf(c, response)) { + markOrigin(c, response, 'guard'); + } + c.res = response; + } + } else if (!c.finalized || (!nextCalled && c.res === before)) { + throw new Error( + `routes: '${file}' must return a response, set c.res, or call next().`, + ); + } + if (c.res.status === 404 && !originOf(c, c.res)) { + markOrigin(c, c.res, 'guard'); + } + } catch (error) { + if (error instanceof Error && error !== nextError) { + guardErrors.set(c, error); + trackResponseCopies(c); + } + throw error; + } + }; + c.notFound = denyNotFound; + try { + await run(0); + guardErrors.delete(c); + return c.res; + } finally { + c.notFound = originalNotFound; + } + }; + }, requestMiddleware: async (c, next) => { + if (middlewareDiagnostic) { + return c.text(middlewareDiagnostic, 500, { 'Cache-Control': 'no-store' }); + } await requestContext.run( options.nodeTarget ? { request: c.req.raw } @@ -586,6 +774,7 @@ export { createStaticNotFound, createPageMutationHandler, createPagesFallback, + renderDirectoryNotFound, createNamedActionMarker, markRouteHandler, } from './pages.ts'; diff --git a/packages/void/src/runtime/routing/pages.ts b/packages/void/src/runtime/routing/pages.ts index d620f38e2..9e439b112 100644 --- a/packages/void/src/runtime/routing/pages.ts +++ b/packages/void/src/runtime/routing/pages.ts @@ -91,15 +91,23 @@ function actionNameOf(request: Request): string | undefined { type MatchedRoutes = typeof honoMatchedRoutes; type RouteHandler = ReturnType[number]['handler']; -const routeHandlers = new WeakSet(); +const routeHandlers = new WeakMap boolean)>(); const namedActionHandlers = new WeakSet(); const pageGetOptions = new WeakMap(); /** Records a handler that answers a route, so the marker can tell it from middleware. */ -export function markRouteHandler(handler: T): T { - routeHandlers.add(handler); +export function markRouteHandler( + handler: T, + matches?: (c: Context) => boolean, +): T { + routeHandlers.set(handler, matches ?? true); return handler; } +function isRouteHandler(handler: RouteHandler, c: Context): boolean { + const matches = routeHandlers.get(handler); + return matches === true || matches?.(c) === true; +} + /** Hono catches middleware throws itself, before the page endpoint can run. */ export function createPageErrorHandler( matchedRoutes: MatchedRoutes, @@ -112,7 +120,7 @@ export function createPageErrorHandler( } // Use the first endpoint, not a broad Pages pattern that follows an API route. const routes = matchedRoutes(c); - const endpointIndex = routes.findIndex((route) => routeHandlers.has(route.handler)); + const endpointIndex = routes.findIndex((route) => isRouteHandler(route.handler, c)); const options = endpointIndex < 0 ? undefined : pageGetOptions.get(routes[endpointIndex].handler); // The endpoint already tried its nearest boundary; do not retry it as a middleware failure. @@ -162,7 +170,7 @@ export function createNamedActionMarker(matchedRoutes: MatchedRoutes): Middlewar return async (c, next) => { const answer = matchedRoutes(c) .slice(c.req.routeIndex + 1) - .find((route) => routeHandlers.has(route.handler)); + .find((route) => isRouteHandler(route.handler, c)); if (answer && namedActionHandlers.has(answer.handler) && actionNameOf(c.req.raw)) { markActionKey(c.req.raw); } @@ -283,6 +291,36 @@ export function createPageMutationHandler( return markRouteHandler(mutationHandler); } +function isPageDocumentRequest(c: Context): boolean { + const destination = c.req.header('Sec-Fetch-Dest'); + const accept = c.req.header('Accept'); + return ( + c.req.header('X-VoidPages') === 'true' || + ((!destination || destination === 'document' || destination === 'empty') && + (!accept || accept.includes('text/html') || accept.includes('*/*'))) + ); +} + +export async function renderDirectoryNotFound( + c: Context, + errors: ErrorRenderer, + pageNotFound?: (c: Context) => Promise, +): Promise { + const path = c.req.path; + if (path === '/api' || path.startsWith('/api/') || !['GET', 'HEAD'].includes(c.req.method)) { + return c.text('Not Found', 404); + } + const filePath = path.includes('/.') || path.slice(path.lastIndexOf('/') + 1).includes('.'); + if (pageNotFound && !filePath && isPageDocumentRequest(c)) { + const response = await pageNotFound(c); + if (response.status === 404) { + return response; + } + return errors.createResponse(c.req.raw, 404, 'Not Found'); + } + return errors.serveCustomPage(c, 404, 'Not Found'); +} + export function createPagesFallback(options: { pageNotFound?: (c: Context) => Promise; trailingSlash?: boolean; @@ -370,15 +408,9 @@ export function createPagesFallback(options: { url.pathname = options.trailingSlash ? `${path}/` : path.slice(0, -1); return Response.redirect(url.href, 301); } - const destination = c.req.header('Sec-Fetch-Dest'); - const accept = c.req.header('Accept'); - const pageRequest = - c.req.header('X-VoidPages') === 'true' || - ((!destination || destination === 'document' || destination === 'empty') && - (!accept || accept.includes('text/html') || accept.includes('*/*'))); return options.routing.markNoMatch( c.req.raw, - await (options.pageNotFound && pageRequest + await (options.pageNotFound && isPageDocumentRequest(c) ? options.pageNotFound(c) : options.errors.serveCustomPage(c, 404, 'Not Found')), ); diff --git a/packages/void/test/fixtures/managed-fallback-worker.ts b/packages/void/test/fixtures/managed-fallback-worker.ts new file mode 100644 index 000000000..dd4c58402 --- /dev/null +++ b/packages/void/test/fixtures/managed-fallback-worker.ts @@ -0,0 +1,29 @@ +import { + createErrorRenderer, + createPagesFallback, + createRoutingRuntime, + Hono, + renderDirectoryNotFound, +} from '../../src/runtime/routing/index.ts'; + +export function createManagedFallbackWorker( + pages: boolean, +): (request: Request) => Response | Promise { + const errors = createErrorRenderer({ projectRoot: '/project', homeDir: '/home' }); + const worker = new Hono(); + const routing = createRoutingRuntime(worker, { managedDispatch: true }); + worker.use(routing.contextMiddleware); + worker.get('/fallback', (c) => c.text('fallback')); + worker.get( + '/private', + routing.directoryMiddleware( + [['routes/_middleware.ts', (c) => c.notFound()]], + (c) => c.text('private'), + (c) => renderDirectoryNotFound(c, errors), + ), + ); + if (pages) { + worker.notFound(createPagesFallback({ errors, routing })); + } + return (request: Request) => worker.fetch(request); +} diff --git a/packages/void/test/integration/cloudflare-deploy-seed.test.ts b/packages/void/test/integration/cloudflare-deploy-seed.test.ts index 3fc90d90d..0698a6334 100644 --- a/packages/void/test/integration/cloudflare-deploy-seed.test.ts +++ b/packages/void/test/integration/cloudflare-deploy-seed.test.ts @@ -148,6 +148,29 @@ function readJson(root: string, path: string) { return JSON.parse(readFileSync(join(root, path), 'utf8')) as Record; } +it('builds a Worker with a plain directory guard and no Containers probe', async () => { + const parent = createPackageFixtureDir(packageRoot, 'cloudflare-directory-guard-'); + roots.push(parent); + const name = 'directory-guard'; + const root = project(parent, name); + writeFileSync(join(root, 'routes/_middleware.ts'), 'export default (_c, next) => next();'); + + await withProvider(async (api, requests) => { + const output = await deploy(root, api); + expect( + requests.filter((request) => request.includes('/containers/')), + output, + ).toEqual([]); + expect(output).toContain(`Could not verify existing Cloudflare Worker "${name}"`); + const { config } = readGeneratedDeployConfig(root); + expect(config.containers ?? []).toEqual([]); + expect(config.durable_objects).toHaveProperty('bindings', [ + { name: 'COUNTER', class_name: 'CounterDurableObject' }, + { name: 'ChatWs', class_name: 'ChatWs' }, + ]); + }); +}); + it('reuses a committed KV create after the first deploy loses its reply and the project moves', async () => { const parent = createPackageFixtureDir(packageRoot, 'cloudflare-seed-'); roots.push(parent); diff --git a/packages/void/test/integration/directory-middleware.test.ts b/packages/void/test/integration/directory-middleware.test.ts new file mode 100644 index 000000000..0246630ea --- /dev/null +++ b/packages/void/test/integration/directory-middleware.test.ts @@ -0,0 +1,408 @@ +import { mkdirSync, rmSync, writeFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { createServer } from 'vite'; +import { describe, expect, it, vi } from 'vite-plus/test'; +import { createPackageFixtureDir } from '../../../../test/integration-helpers.ts'; +import { voidPlugin } from '../../src/index.ts'; + +async function withServer( + setup: (write: (file: string, source: string) => void) => void, + test: ( + load: (path: string, init?: RequestInit) => Promise, + root: string, + ) => Promise, +): Promise { + const root = createPackageFixtureDir(join(import.meta.dirname, '../..'), 'directory-middleware-'); + const write = (file: string, source: string) => { + const path = join(root, file); + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, source); + }; + const cwd = vi.spyOn(process, 'cwd').mockReturnValue(root); + try { + write('package.json', '{"type":"module"}'); + write('void.config.ts', 'export default { target: "node", sourceDir: "app" };'); + setup(write); + const server = await createServer({ + root, + configFile: false, + logLevel: 'silent', + plugins: [voidPlugin()], + server: { host: '127.0.0.1', port: 0 }, + }); + try { + await server.listen(); + await test((path, init) => fetch(new URL(path, server.resolvedUrls!.local[0]), init), root); + } finally { + await server.close(); + } + } finally { + cwd.mockRestore(); + rmSync(root, { recursive: true, force: true }); + } +} + +const textRoute = 'export const GET = c => c.text("route");'; +const notFoundGuard = 'export default c => c.text("directory denial", 404, {"x-denied": "yes"});'; + +describe('directory middleware on actual Node dev requests', () => { + it('keeps the response a route assigns before returning void', async () => { + await withServer( + (write) => { + const route = "export const GET = c => { c.res = c.text('created', 201); };"; + write('app/routes/plain.ts', route); + write('app/routes/guarded/index.ts', route); + write( + 'app/routes/guarded/_middleware.ts', + 'export default async (c, next) => { await next(); };', + ); + }, + async (load) => { + for (const path of ['/plain', '/guarded']) { + const response = await load(path); + expect(response.status, path).toBe(201); + expect(await response.text(), path).toBe('created'); + } + }, + ); + }); + + it.each([ + ['c.text()', "c.text('nope', 404)"], + [ + 'new Response()', + "new Response('nope', { status: 404, headers: { 'Cache-Control': 'no-store' } })", + ], + ])('matches global middleware when returning %s after next', async (_label, replacement) => { + await withServer( + (write) => { + write( + 'app/after-next.ts', + `export default async (c, next) => { + await next(); + return ${replacement}; +};`, + ); + write( + 'app/middleware/01.after-next.ts', + `import guard from '../after-next.ts'; +export default (c, next) => c.req.path === '/global' ? guard(c, next) : next();`, + ); + write( + 'app/routes/directory/_middleware.ts', + 'export { default } from "../../after-next.ts";', + ); + const route = `export const GET = c => c.text('discarded endpoint body', 200, { + 'Cache-Control': 'public, max-age=60', + 'Content-Length': '23', +});`; + write('app/routes/global.ts', route); + write('app/routes/directory/index.ts', route); + }, + async (load) => { + const read = async (path: string) => { + const response = await load(path, { signal: AbortSignal.timeout(2500) }); + return { + status: response.status, + cacheControl: response.headers.get('Cache-Control'), + contentLength: response.headers.get('Content-Length'), + body: await response.text().catch(() => null), + }; + }; + const globalResponse = await read('/global'); + expect(globalResponse).toEqual({ + status: 200, + cacheControl: 'public, max-age=60', + contentLength: '23', + body: 'discarded endpoint body', + }); + expect(await read('/directory')).toEqual(globalResponse); + }, + ); + }); + + it('resumes the outer directory middleware with the rendered error response', async () => { + await withServer( + (write) => { + write( + 'app/routes/guarded/_middleware.ts', + `export default async (c, next) => { + await next(); + c.header('x-observed-error', c.res.status + ' ' + c.error?.message); +};`, + ); + const errorImport = "import { HTTPException } from 'hono/http-exception';"; + write( + 'app/routes/guarded/endpoint.ts', + errorImport + + "export const GET = () => { throw new HTTPException(401, { message: 'endpoint' }); };", + ); + write( + 'app/routes/guarded/inner/_middleware.ts', + errorImport + + "export default () => { throw new HTTPException(403, { message: 'inner guard' }); };", + ); + write('app/routes/guarded/inner/index.ts', textRoute); + }, + async (load) => { + for (const [path, status, message] of [ + ['/guarded/endpoint', 401, 'endpoint'], + ['/guarded/inner', 403, 'inner guard'], + ] as const) { + const response = await load(path); + expect(response.status, path).toBe(status); + expect(await response.text(), path).toBe(message); + expect(response.headers.get('x-observed-error'), path).toBe(`${status} ${message}`); + } + }, + ); + }); + + it('uses the winning file ancestry in method selection and unwinds root to leaf', async () => { + await withServer( + (write) => { + for (const [file, label] of [ + ['middleware/01.global.ts', 'global'], + ['routes/_middleware.ts', 'root'], + ['routes/admin/_middleware.mts', 'admin'], + ['routes/admin/[id]/_middleware.js', 'param'], + ]) { + write( + `app/${file}`, + `export default async (c, next) => { + if (c.req.header('x-global-deny') && ${JSON.stringify(label)} === 'global') return c.text('global denial', 403); + c.set('calls', [...(c.get('calls') ?? []), ${JSON.stringify(label)} + ':' + (c.req.param('id') ?? '-')]); + await next(); + c.header('x-unwind', [...(c.res.headers.get('x-unwind')?.split(',') ?? []), ${JSON.stringify(label)}].join(',')); +};`, + ); + } + write('app/routes/admin.ts', 'export const GET = c => c.json(c.get("calls"));'); + write( + 'app/routes/admin/index.ts', + `export const POST = c => c.json(c.get("calls")); +export const OPTIONS = c => c.json(c.get("calls"));`, + ); + write('app/routes/admin/[id].ts', 'export const GET = c => c.text(c.req.param("id"));'); + write( + 'app/routes/admin/special/index.ts', + 'export const GET = c => c.text("static file");', + ); + write( + 'app/routes/admin/special/_middleware.ts', + 'export default (c) => c.text("static directory guard", 403);', + ); + write('app/routes/admin/[id]/detail.ts', 'export const GET = c => c.json(c.get("calls"));'); + write( + 'app/routes/admin/private.ts', + 'export const GET = () => { throw new Error("endpoint loaded"); };', + ); + }, + async (load) => { + const get = await load('/admin'); + expect(await get.json()).toEqual(['global:-', 'root:-']); + expect(get.headers.get('x-unwind')).toBe('root,global'); + const post = await load('/admin', { method: 'POST' }); + expect(await post.json()).toEqual(['global:-', 'root:-', 'admin:-']); + expect(post.headers.get('x-unwind')).toBe('admin,root,global'); + const child = await load('/admin/32/detail'); + expect((await child.json>()).slice(1)).toEqual([ + 'root:32', + 'admin:32', + 'param:32', + ]); + expect(child.headers.get('x-unwind')).toBe('param,admin,root,global'); + const options = await load('/admin', { method: 'OPTIONS' }); + expect(await options.json()).toEqual(['global:-', 'root:-', 'admin:-']); + const miss = await load('/admin', { method: 'DELETE' }); + expect(miss.status).toBe(404); + expect(miss.headers.get('x-unwind') ?? '').not.toContain('root'); + const staticWinner = await load('/admin/special'); + expect(staticWinner.status).toBe(403); + expect(await staticWinner.text()).toBe('static directory guard'); + expect(await (await load('/admin/dynamic')).text()).toBe('dynamic'); + const denied = await load('/admin/private', { headers: { 'x-global-deny': 'yes' } }); + expect(denied.status).toBe(403); + }, + ); + }); + + it('keeps a compressed HEAD denial and lets an independent replacement fall through', async () => { + await withServer( + (write) => { + write( + 'app/middleware/01.head.ts', + `import { compress } from 'hono/compress'; +const compression = compress({ threshold: 0 }); +export default async (c, next) => { + if (c.req.path.endsWith('/compressed.txt')) return compression(c, next); + await next(); + if (c.req.method === 'HEAD') { + c.header('Vary', 'Accept-Encoding'); + c.res = new Response(null, { status: c.res.status, headers: c.res.headers }); + } +};`, + ); + write('app/routes/hidden/_middleware.ts', notFoundGuard); + for (const name of ['compressed.txt', 'replacement.txt']) { + write( + `app/routes/hidden/${name}.ts`, + 'throw new Error("endpoint evaluated");\n' + textRoute, + ); + write(`hidden/${name}`, 'same-path Vite file'); + } + }, + async (load) => { + const get = await load('/hidden/compressed.txt'); + expect(get.status).toBe(404); + expect(await get.text()).toBe('directory denial'); + const head = { method: 'HEAD', headers: { 'Accept-Encoding': 'gzip' } }; + const compressed = await load('/hidden/compressed.txt', head); + expect(compressed.status).toBe(404); + expect(compressed.headers.get('content-encoding')).toBe('gzip'); + expect(compressed.headers.get('x-denied')).toBe('yes'); + expect(await compressed.text()).toBe(''); + const replacement = await load('/hidden/replacement.txt', head); + expect(replacement.status).toBe(200); + expect(replacement.headers.get('x-denied')).toBeNull(); + }, + ); + }); + + it('preserves chosen denials through rewrites and leaves genuine misses unowned', async () => { + await withServer( + (write) => { + write( + 'void.config.ts', + `export default { + target: 'node', sourceDir: 'app', + routing: { + rewrites: { '/forced': '/protected/rendered' }, + fallbacks: { '/fallback': '/protected/thrown', '/protected/rendered': '/wrong' }, + }, +};`, + ); + write('public/404.html', '

Dedicated 404

'); + write('app/routes/code.ts', 'export const GET = c => c.rewrite("/protected/rendered");'); + write('app/routes/wrong.ts', 'export const GET = c => c.text("wrong fallback");'); + write( + 'app/routes/protected/_middleware.ts', + `export default async c => { + const path = c.req.path; + if (path.endsWith('/rendered')) return c.notFound(); + if (path.endsWith('/thrown')) throw Object.assign(new Error('guard'), { + status: 404, getResponse: () => c.text('thrown 404', 404), + }); + const miss = await c.rewrite('/missing'); + return path.endsWith('/returned') ? miss : c.text('chosen 404', 404); +};`, + ); + for (const name of ['rendered', 'thrown', 'returned', 'discarded']) { + write(`app/routes/protected/${name}.ts`, textRoute); + write(`public/protected/${name}`, 'same-path Vite file'); + } + for (const name of ['code', 'forced']) { + write(`public/${name}`, 'same-path Vite file'); + } + }, + async (load) => { + for (const [url, body] of [ + ['/protected/rendered', 'Dedicated 404'], + ['/code', 'Dedicated 404'], + ['/forced', 'Dedicated 404'], + ['/fallback', 'thrown 404'], + ['/protected/discarded', 'chosen 404'], + ]) { + const response = await load(url); + expect(response.status, url).toBe(404); + expect(await response.text(), url).toContain(body); + const head = await load(url, { method: 'HEAD' }); + expect(head.status, url).toBe(404); + expect(await head.text(), url).toBe(''); + } + const returned = await load('/protected/returned'); + expect(returned.status).toBe(200); + expect(await returned.text()).toBe('same-path Vite file'); + }, + ); + }); + + it('rejects guards that do nothing or advance twice', async () => { + await withServer( + (write) => { + write('app/routes/empty/_middleware.ts', 'export default () => undefined;'); + write('app/routes/empty/item.ts', textRoute); + write( + 'app/routes/twice/_middleware.ts', + `export default async (_c, next) => { + await next(); + await next(); +};`, + ); + write( + 'app/routes/twice/item.ts', + `export const GET = c => { + globalThis.directoryMiddlewareReads = (globalThis.directoryMiddlewareReads ?? 0) + 1; + return c.text('route'); +};`, + ); + write( + 'app/routes/count.ts', + 'export const GET = c => c.json(globalThis.directoryMiddlewareReads ?? 0);', + ); + }, + async (load) => { + expect((await load('/empty/item')).status).toBe(500); + expect((await load('/twice/item')).status).toBe(500); + expect(await (await load('/count')).json()).toBe(1); + }, + ); + }); + + it('reports invalid conventions during a failed rescan and recovers on the same server', async () => { + await withServer( + (write) => { + write('app/routes/admin/record.ts', textRoute); + write('app/routes/admin/_middleware.ts', 'export default c => c.text("guard", 401);'); + write('app/routes/unrelated.ts', textRoute); + }, + async (load, root) => { + const read = () => load('/admin/record'); + expect((await read()).status).toBe(401); + writeFileSync( + join(root, 'app/routes/unrelated.ts'), + 'export const HEAD = () => new Response();', + ); + const duplicate = join(root, 'app/routes/admin/_middleware.mjs'); + writeFileSync(duplicate, 'export default (c, next) => next();'); + await vi.waitFor( + async () => { + const response = await read(); + expect(response.status).toBe(500); + expect(await response.text()).toContain('_middleware.mjs'); + }, + { timeout: 10_000 }, + ); + rmSync(duplicate); + writeFileSync(join(root, 'app/routes/unrelated.ts'), textRoute); + await vi.waitFor(async () => expect((await read()).status).toBe(401)); + const guard = join(root, 'app/routes/admin/_middleware.ts'); + for (const source of ['export const value = 1;', 'export default 4;']) { + writeFileSync(guard, source); + await vi.waitFor( + async () => { + const response = await read(); + expect(response.status).toBe(500); + expect(await response.text()).toContain('_middleware.ts'); + }, + { timeout: 10_000 }, + ); + writeFileSync(guard, 'export default c => c.text("fixed", 403);'); + await vi.waitFor(async () => expect((await read()).status).toBe(403)); + } + rmSync(guard); + await vi.waitFor(async () => expect(await (await read()).text()).toBe('route')); + }, + ); + }); +}); diff --git a/packages/void/test/integration/pages-middleware-diagnostic.test.ts b/packages/void/test/integration/pages-middleware-diagnostic.test.ts new file mode 100644 index 000000000..3c66f309a --- /dev/null +++ b/packages/void/test/integration/pages-middleware-diagnostic.test.ts @@ -0,0 +1,193 @@ +import { mkdirSync, rmSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { createServer } from 'vite'; +import { expect, it, vi } from 'vite-plus/test'; +import { createPackageFixtureDir } from '../../../../test/fixture-dir.ts'; +import { + collectServerOutput, + killChild, + spawnTestServer, +} from '../../../../test/integration-helpers.ts'; +import { voidPlugin } from '../../src/index.ts'; + +const phases = ['startup', 'live add', 'Cloudflare startup', 'late config']; + +it.each(phases)('reports misplaced Pages middleware on dev %s', async (phase) => { + const root = createPackageFixtureDir(join(import.meta.dirname, '../..'), 'pages-middleware-'); + const pageDir = join(root, 'src', 'pages', 'admin'); + const routesDir = join(root, 'src', 'routes'); + const misplaced = join(pageDir, '_middleware.prod.d.ts'); + const broken = join(routesDir, 'broken.ts'); + const cwd = vi.spyOn(process, 'cwd').mockReturnValue(root); + try { + writeFileSync(join(root, 'package.json'), '{"type":"module"}'); + writeFileSync( + join(root, 'void.json'), + phase === 'Cloudflare startup' + ? '{"sourceDir":"src"}' + : '{"sourceDir":"src","target":"node"}', + ); + mkdirSync(pageDir, { recursive: true }); + mkdirSync(routesDir, { recursive: true }); + writeFileSync(join(routesDir, 'ready.ts'), 'export const GET = () => new Response("ready");'); + if (phase === 'startup' || phase === 'Cloudflare startup') { + writeFileSync(misplaced, 'export {};'); + } + + const server = await createServer({ + root, + configFile: false, + logLevel: 'silent', + plugins: [ + voidPlugin(), + phase === 'late config' && { + name: 'test:create-misplaced-middleware', + configResolved: { + order: 'post', + handler() { + writeFileSync(misplaced, 'export {};'); + }, + }, + }, + ], + server: { host: '127.0.0.1', port: 0 }, + }); + try { + await server.listen(); + const request = async (path: string) => { + const response = await fetch(new URL(path, server.resolvedUrls!.local[0])); + return { status: response.status, body: await response.text() }; + }; + const waitOptions = { timeout: 5000 }; + const diagnostic = + 'Directory middleware is unsupported in Void Pages ("src/pages/admin/_middleware.prod.d.ts")'; + const logError = vi.spyOn(server.config.logger, 'error'); + const logInfo = vi.spyOn(server.config.logger, 'info'); + if (phase === 'live add') { + expect(await request('/ready')).toEqual({ status: 200, body: 'ready' }); + writeFileSync(broken, 'export const HEAD = () => new Response("broken");'); + await vi.waitFor( + () => + expect(logError).toHaveBeenCalledWith( + expect.stringContaining("'broken.ts' exports HEAD"), + expect.anything(), + ), + waitOptions, + ); + writeFileSync(misplaced, 'export {};'); + await vi.waitFor( + () => + expect(logError).toHaveBeenCalledWith( + expect.stringContaining(diagnostic), + expect.anything(), + ), + waitOptions, + ); + } + + const assertDiagnostic = async () => { + const response = await request('/ready'); + expect(response.status, response.body).toBe(500); + expect(response.body).toContain('src/pages/admin/_middleware.prod.d.ts'); + expect(response.body).toContain('Use global middleware in src/middleware/'); + }; + if (phase === 'Cloudflare startup' || phase === 'late config') { + await assertDiagnostic(); + } else { + await vi.waitFor(assertDiagnostic, waitOptions); + } + if (phase === 'live add') { + await assertDiagnostic(); + } + + await vi.waitFor( + () => + expect(Object.values(server.watcher.getWatched()).flat()).toContain( + '_middleware.prod.d.ts', + ), + waitOptions, + ); + rmSync(misplaced); + await vi.waitFor( + async () => expect(await request('/ready')).toEqual({ status: 200, body: 'ready' }), + waitOptions, + ); + if (phase === 'live add') { + expect( + logError.mock.calls.filter(([message]) => message.includes(diagnostic)), + ).toHaveLength(1); + expect( + logInfo.mock.calls.filter( + ([message]) => message === 'Void Pages middleware error cleared.', + ), + ).toHaveLength(1); + writeFileSync(broken, 'export const GET = () => new Response("repaired");'); + await vi.waitFor( + async () => expect(await request('/broken')).toEqual({ status: 200, body: 'repaired' }), + waitOptions, + ); + } + } finally { + await server.close(); + } + } finally { + cwd.mockRestore(); + rmSync(root, { recursive: true, force: true }); + } +}); + +it.each(['add after success', 'remove after failure'])( + 'reports misplaced Pages middleware in build watch mode on %s', + async (transition) => { + const root = createPackageFixtureDir(join(import.meta.dirname, '../..'), 'pages-watch-'); + const pageDir = join(root, 'src', 'pages', 'admin'); + const routesDir = join(root, 'src', 'routes'); + const misplaced = join(pageDir, '_middleware.prod.d.ts'); + try { + writeFileSync(join(root, 'package.json'), '{"type":"module"}'); + writeFileSync(join(root, 'void.json'), '{"sourceDir":"src","target":"node"}'); + writeFileSync( + join(root, 'vite.config.mts'), + "import { voidPlugin } from '../../../dist/index.mjs'; export default { plugins: [voidPlugin()] };", + ); + writeFileSync(join(root, 'index.html'), 'Watch fixture'); + mkdirSync(pageDir, { recursive: true }); + mkdirSync(routesDir, { recursive: true }); + writeFileSync(join(routesDir, 'ready.ts'), 'export const GET = () => new Response("ready");'); + if (transition === 'remove after failure') { + writeFileSync(misplaced, 'export {};'); + } + + const child = spawnTestServer('vp', ['build', '--watch', '--configLoader', 'native'], { + cwd: root, + env: { ...process.env, NO_COLOR: '1' }, + }); + const output = collectServerOutput(child); + const built = /built in \d+ms\./g; + const rejected = + /Directory middleware is unsupported in Void Pages \("src\/pages\/admin\/_middleware\.prod\.d\.ts"\)/g; + // The Node target builds both SSR and client when the Pages directory exists. + const waitForBuilds = (message: RegExp) => + vi.waitFor( + () => expect(output().match(message)?.length ?? 0, output()).toBeGreaterThanOrEqual(2), + { timeout: 10_000 }, + ); + try { + if (transition === 'add after success') { + await waitForBuilds(built); + writeFileSync(misplaced, 'export {};'); + await waitForBuilds(rejected); + } else { + await waitForBuilds(rejected); + rmSync(misplaced); + await waitForBuilds(built); + } + } finally { + await killChild(child); + } + } finally { + rmSync(root, { recursive: true, force: true }); + } + }, + 30_000, +); diff --git a/packages/void/test/integration/websocket-middleware.test.ts b/packages/void/test/integration/websocket-middleware.test.ts index ebeaf4d2f..64a7c664b 100644 --- a/packages/void/test/integration/websocket-middleware.test.ts +++ b/packages/void/test/integration/websocket-middleware.test.ts @@ -6,7 +6,10 @@ import { join } from 'node:path'; import { Miniflare, convertV4MiniflareOptions } from 'miniflare'; import { build } from 'vite'; import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test'; +import { scanPages } from '../../src/pages/scan.ts'; +import { resolveProjectPaths } from '../../src/project-paths.ts'; import { compileRouteTable, compileWorkerEntry } from '../../src/router/compile.ts'; +import { scanDirectoryMiddleware } from '../../src/router/directory-middleware.ts'; import type { ScanResult } from '../../src/router/scan.ts'; const root = join(import.meta.dirname, '..', '..', '..', '..'); @@ -24,7 +27,10 @@ type MiniflareInstance = { let miniflare: MiniflareInstance; -async function rejectedUpgrade(url: URL): Promise<{ status: number | undefined; body: string }> { +async function rejectedUpgrade( + url: URL, + headers: Record = {}, +): Promise<{ status: number | undefined; body: string }> { const upgrade = request(url, { agent: false, headers: { @@ -32,6 +38,7 @@ async function rejectedUpgrade(url: URL): Promise<{ status: number | undefined; Upgrade: 'websocket', 'Sec-WebSocket-Version': '13', 'Sec-WebSocket-Key': 'dGhlIHNhbXBsZSBub25jZQ==', + ...headers, }, }); const socket = once(upgrade, 'socket').then(async ([socket]) => { @@ -66,11 +73,13 @@ describe('generated worker WebSocket middleware', () => { beforeAll(async () => { const routesDir = join(temporary, 'routes'); const middlewareDir = join(temporary, 'middleware'); - const websocketPath = join(routesDir, 'chat.ws.ts'); + const websocketPath = join(routesDir, 'chat', 'index.ws.ts'); const httpRoutePath = join(routesDir, 'chat.ts'); const middlewarePath = join(middlewareDir, '01.auth.ts'); const runtimeEnvPath = join(temporary, 'runtime-env.ts'); - mkdirSync(routesDir, { recursive: true }); + mkdirSync(join(routesDir, 'chat'), { recursive: true }); + mkdirSync(join(routesDir, 'upgrade-only'), { recursive: true }); + mkdirSync(join(temporary, 'pages', 'upgrade-only'), { recursive: true }); mkdirSync(middlewareDir, { recursive: true }); writeFileSync( @@ -85,6 +94,9 @@ export default { async onRequest({ storage }) { return Response.json({ dispatches: (await storage.get("dispatches")) ?? 0 }); }, + async onMessage({ socket }, event) { + await socket.send(event); + }, };\n`, ); writeFileSync( @@ -107,16 +119,46 @@ export default { ); } writeFileSync( - join(routesDir, 'upgrade-only.ws.ts'), + join(routesDir, 'upgrade-only', '[id].ws.ts'), `const schema = { "~standard": { version: 1, vendor: "test", validate: value => ({ value }) } }; export default { __kind: "socket", messages: { client: schema, server: schema } };\n`, ); + const directoryGuard = `export default async (c, next) => { + if (c.req.header('x-directory-deny') === 'throw') { + throw Object.assign(new Error('directory blocked'), { + status: 404, getResponse: () => new Response('directory blocked', { status: 404 }), + }); + } + if (c.req.header('x-directory-deny')) return c.text('directory blocked', 404); + await next(); + c.header('x-directory-guard', 'passed'); +};`; + for (const dir of ['chat', 'upgrade-only']) { + writeFileSync(join(routesDir, dir, '_middleware.ts'), directoryGuard); + } + writeFileSync( + join(routesDir, 'chat', 'check.ts'), + 'export const GET = (c) => c.text("nested HTTP");', + ); + writeFileSync( + join(temporary, 'pages', 'upgrade-only', 'overlap.tsx'), + 'export default () => null;', + ); + writeFileSync( + join(temporary, 'pages', 'upgrade-only', 'overlap.server.ts'), + 'export const actions = { save: () => undefined };', + ); writeFileSync( middlewarePath, `export default async function auth(c, next) { if (c.req.raw.headers.get("authorization") !== "Bearer allowed") { return c.text("Unauthorized", 401); } + if (c.req.path === '/code-rewrite') return c.rewrite('/upgrade-only/overlap'); + if (c.req.header('x-page-error')) throw Object.assign(new Error('page middleware'), { + status: 404, getResponse: () => new Response('fallback error', { status: 404 }), + }); + if (c.req.header('x-page-redirect')) return c.redirect('/done', 303); return next(); }\n`, ); @@ -132,6 +174,14 @@ export default { __kind: "socket", messages: { client: schema, server: schema } env: null, filePath: 'chat.ts', }, + { + pattern: '/chat/check', + methods: ['GET'], + params: [], + catchAll: false, + env: null, + filePath: 'chat/check.ts', + }, ], websockets: [ { @@ -140,7 +190,7 @@ export default { __kind: "socket", messages: { client: schema, server: schema } params: [], catchAll: false, env: null, - filePath: 'chat.ws.ts', + filePath: 'chat/index.ws.ts', className: 'ChatWs', bindingName: 'CHAT_WS', mode: 'socket', @@ -152,7 +202,7 @@ export default { __kind: "socket", messages: { client: schema, server: schema } params: ['id'], catchAll: false, env: null, - filePath: `${mode}.ws.ts`, + filePath: mode === 'upgrade-only' ? 'upgrade-only/[id].ws.ts' : `${mode}.ws.ts`, className: mode === 'room' ? 'RoomWs' : mode === 'socket' ? 'SocketWs' : 'UpgradeOnlyWs', bindingName: mode === 'room' ? 'ROOM_WS' : mode === 'socket' ? 'SOCKET_WS' : 'UPGRADE_ONLY_WS', @@ -163,19 +213,47 @@ export default { __kind: "socket", messages: { client: schema, server: schema } middleware: [{ order: 1, filePath: '01.auth.ts' }], jobs: [], queues: [], - pages: { pages: [], layouts: [], namedLayouts: [] }, + pages: await scanPages(temporary), }; + scan.directoryMiddleware = scanDirectoryMiddleware(resolveProjectPaths(temporary), [ + ...scan.routes, + ...(scan.websockets ?? []), + ]); writeFileSync( routeTablePath, - compileRouteTable(scan, routesDir, middlewareDir, temporary, temporary, null, { - runtimeEnvPath, - webSocketRuntimePath: join(root, 'packages/void/src/runtime/ws/server.ts'), - projectRoot: temporary, - homeDir: temporary, - reactRefresh: false, - auth: null, - }), + compileRouteTable( + scan, + routesDir, + middlewareDir, + temporary, + temporary, + null, + { + runtimeEnvPath, + webSocketRuntimePath: join(root, 'packages/void/src/runtime/ws/server.ts'), + projectRoot: temporary, + homeDir: temporary, + reactRefresh: false, + auth: null, + redirectRules: [ + { + source: '/forced-rewrite', + destination: '/upgrade-only/overlap', + status: 200, + force: true, + }, + ], + fallbackRules: [ + { source: '/fallback-rewrite', destination: '/upgrade-only/overlap', status: 200 }, + ], + }, + { + pagesDir: join(temporary, 'pages'), + pagesDirRelative: 'pages', + clientEntryId: 'virtual:test-client', + }, + ), ); writeFileSync( workerPath, @@ -192,7 +270,17 @@ export default { __kind: "socket", messages: { client: schema, server: schema } { name: 'void-websocket-middleware-test', resolveId(id) { - return id === 'virtual:void-routes' ? routeTablePath : null; + if (id === 'virtual:void-routes') { + return routeTablePath; + } + if (id === 'virtual:void-pages-renderer') { + return '\0fixture-pages-renderer'; + } + }, + load(id) { + if (id === '\0fixture-pages-renderer') { + return 'export const renderPage = () => "

Page winner

";'; + } }, }, ], @@ -249,20 +337,89 @@ export default { __kind: "socket", messages: { client: schema, server: schema } }); expect(authorized.status).toBe(101); - expect(authorized.webSocket).not.toBeNull(); - const afterAuthorized = await stub.fetch('http://localhost/chat'); - expect(await afterAuthorized.json()).toEqual({ dispatches: 1 }); const socket = authorized.webSocket!; const closed = new Promise((resolve) => { socket.addEventListener('close', (event) => resolve(event), { once: true }); }); socket.accept(); - socket.close(1000, 'test complete'); - // Finish the close handshake before disposing workerd. Killing it while - // the upgrade transport is open can emit an unhandled Windows ECONNRESET. - const closeEvent = await closed; - expect(closeEvent.code).toBe(1000); - expect(closeEvent.reason).toBe('test complete'); + try { + expect(authorized.headers.get('x-directory-guard')).toBe('passed'); + const afterAuthorized = await stub.fetch('http://localhost/chat'); + expect(await afterAuthorized.json()).toEqual({ dispatches: 1 }); + const timeout = AbortSignal.timeout(5000); + const echoed = new Promise((resolve, reject) => { + socket.addEventListener('message', resolve, { once: true }); + timeout.addEventListener('abort', () => reject(timeout.reason), { once: true }); + }); + socket.send(JSON.stringify({ value: 'round trip' })); + expect(JSON.parse(String((await echoed).data))).toEqual({ value: 'round trip' }); + } finally { + socket.close(1000, 'test complete'); + // Disposing workerd before this handshake can emit a Windows ECONNRESET. + const closeEvent = await closed; + expect(closeEvent.code).toBe(1000); + expect(closeEvent.reason).toBe('test complete'); + } + }); + + it('uses the file guard for upgrades and ordinary fallbacks with zero dispatches on denial', async () => { + const credentials = { Authorization: 'Bearer allowed', 'x-directory-deny': 'return' }; + const { CHAT_WS } = await miniflare.getBindings<{ CHAT_WS: DurableObjectNamespace }>(); + const stub = CHAT_WS.get(CHAT_WS.idFromName('default')); + const before = await (await stub.fetch('http://localhost/chat')).json(); + const denied = await rejectedUpgrade(new URL('/chat', await miniflare.ready), credentials); + expect(denied).toEqual({ status: 404, body: 'directory blocked' }); + for (const [url, method, status] of [ + ['/chat', 'GET', 200], + ['/chat', 'POST', 404], + ['/chat/check', 'GET', 404], + ['/upgrade-only/ordinary', 'GET', 404], + ] as const) { + const response = await miniflare.dispatchFetch(`http://localhost${url}`, { + headers: credentials, + method, + }); + expect(response.status, `${method} ${url}`).toBe(status); + } + expect(await (await stub.fetch('http://localhost/chat')).json()).toEqual(before); + }); + + it('keeps a thrown upgrade denial out of legacy Pages recovery through every rewrite', async () => { + const headers = { + Authorization: 'Bearer allowed', + 'x-directory-deny': 'throw', + 'X-VoidPages': 'true', + }; + for (const url of [ + '/upgrade-only/overlap', + '/code-rewrite', + '/forced-rewrite', + '/fallback-rewrite', + ]) { + const response = await rejectedUpgrade(new URL(url, await miniflare.ready), headers); + expect(response, url).toEqual({ status: 404, body: 'directory blocked' }); + } + const page = await miniflare.dispatchFetch('http://localhost/upgrade-only/overlap', { + headers: { Authorization: headers.Authorization }, + }); + expect(page.status).toBe(200); + expect(await page.text()).toContain('Page winner'); + expect(page.headers.get('x-directory-guard')).toBeNull(); + const legacy = await miniflare.dispatchFetch('http://localhost/upgrade-only/overlap', { + headers: { Authorization: headers.Authorization, 'X-VoidPages': 'true', 'x-page-error': '1' }, + }); + expect(legacy.status).toBe(200); + expect(await legacy.text()).toBe(''); + const action = await miniflare.dispatchFetch( + 'http://localhost/upgrade-only/overlap?save&page=2', + { + method: 'POST', + redirect: 'manual', + headers: { Authorization: headers.Authorization, 'x-page-redirect': '1' }, + }, + ); + expect(action.status).toBe(303); + expect(action.headers.get('Location')).toBe('/done?page=2'); }); it('continues non-upgrade requests to an HTTP route at the same path', async () => { diff --git a/packages/void/test/unit/application-analysis.test.ts b/packages/void/test/unit/application-analysis.test.ts index bc8806b8d..91b86d90b 100644 --- a/packages/void/test/unit/application-analysis.test.ts +++ b/packages/void/test/unit/application-analysis.test.ts @@ -209,6 +209,23 @@ describe('shared application analysis', () => { expect(prod.websockets[0]?.className).toBe(dev.websockets[0]?.className); }); + it('infers directory middleware bindings in both environments', () => { + const applicationRoot = root(); + source(applicationRoot, 'app/routes/admin/index.dev.ts', 'export const GET = () => {};'); + source( + applicationRoot, + 'app/routes/admin/_middleware.ts', + 'import { getSandbox } from "void/sandbox"; import { kv } from "void/kv"; export default (c, next) => { c.set("getSandbox", getSandbox); c.set("kv", kv); return next(); };', + ); + + const config: VoidConfig = { sourceDir: 'app' }; + const dev = analyzeApplicationSync(applicationRoot, { config, environment: 'dev' }); + const prod = analyzeApplicationSync(applicationRoot, { config, environment: 'prod' }); + expect(dev.bindings).toMatchObject({ needsSandbox: true, needsKV: true }); + expect(prod.routes).toEqual([]); + expect(prod.bindings).toMatchObject({ needsSandbox: true, needsKV: true }); + }); + it('uses framework directories by default and honors custom directories without losing src helpers', () => { const applicationRoot = root(); source(applicationRoot, 'package.json', JSON.stringify({ dependencies: { astro: '*' } })); diff --git a/packages/void/test/unit/compile.test.ts b/packages/void/test/unit/compile.test.ts index bb08c90e3..4504b9ee6 100644 --- a/packages/void/test/unit/compile.test.ts +++ b/packages/void/test/unit/compile.test.ts @@ -170,14 +170,13 @@ describe('compileRouteTable', () => { code.indexOf('__registerWebSocketRoutes(__voidWebSocketRoutes);'), ); expect(code).toContain('app.all("/chat/:room"'); - expect(code).toContain( - 'if (c.req.raw.headers.get("upgrade")?.toLowerCase() !== "websocket") return next()', - ); + expect(code).toContain('if (!__isWebSocketUpgrade(c)) return next()'); + expect(code).toContain('}, __isWebSocketUpgrade));'); expect(code).toContain('__forwardWebSocketRequest'); expect(code.indexOf('app.use(middleware0)')).toBeLessThan( code.indexOf('app.all("/chat/:room"'), ); - const fallback = 'app.all("/chat/:room", __markRouteHandler((c) => __forwardWebSocketRequest'; + const fallback = 'app.all("/chat/:room", __markRouteHandler(__wsHandler0));'; expect(code.indexOf('app.get("/chat/:room"')).toBeGreaterThan( code.indexOf('app.all("/chat/:room"'), ); @@ -241,6 +240,8 @@ describe('compileRouteTable', () => { }); }); +const namedExportStatement = /^export\s+\{[^}]*\}(?:\s+from\s+["'][^"']+["'])?;?\s*$/gm; + /** Evaluate a compiled route table with its imports supplied and return its Hono app. */ function evalCompiledApp(code: string): Hono { // Drop imports, the node-target `withRuntimeEnv` const and `export` keywords so @@ -250,7 +251,7 @@ function evalCompiledApp(code: string): Hono { .replaceAll(/^const\s+withRuntimeEnv\s+=.*$/gm, '') .replaceAll(/^export\s+default\s+app;?\s*$/gm, '') .replaceAll(/^export\s+(const|async\s+function|function)\s+/gm, '$1 ') - .replaceAll(/^export\s+\{[^}]*\};?\s*$/gm, ''); + .replaceAll(namedExportStatement, ''); const factory = new Function( 'Hono', @@ -1113,6 +1114,7 @@ describe('compileNodeApp', () => { innerApp.get('*', (c) => c.env.ASSETS.fetch(c.req.raw)); const code = compileNodeApp(target, { precompress: false }) .replaceAll(/^import .*;$/gm, '') + .replaceAll(namedExportStatement, '') .replace('import.meta.voidClientDirectory', '"client"') .replace('export default app;', 'return app;'); // oxlint-disable-next-line typescript/no-unsafe-call -- Execute the generated fixture with its test bindings. diff --git a/packages/void/test/unit/pages-compile.test.ts b/packages/void/test/unit/pages-compile.test.ts index 713414a26..5696dd696 100644 --- a/packages/void/test/unit/pages-compile.test.ts +++ b/packages/void/test/unit/pages-compile.test.ts @@ -116,7 +116,7 @@ describe('Pages metadata wiring', () => { ); expect( code.includes( - 'app.onError(__createPageErrorHandler(__matchedRoutes, __errorRenderer.onError))', + '__routingRuntime.onError(__createPageErrorHandler(__matchedRoutes, __errorRenderer.onError))', ), ).toBe(true); expect(code).toContain('import { matchedRoutes as __matchedRoutes }'); @@ -138,7 +138,7 @@ describe('Pages metadata wiring', () => { '__createErrorRenderer({"dev":true,"projectRoot":"/project","homeDir":"/Users/test"})', ); expect(code).toContain( - 'app.onError(__createPageErrorHandler(__matchedRoutes, __errorRenderer.onError))', + '__routingRuntime.onError(__createPageErrorHandler(__matchedRoutes, __errorRenderer.onError))', ); expect(code).toContain('app.notFound(__routingRuntime.trackNotFound(__createPagesFallback('); expect(code).not.toContain('function __voidRenderDevErrorOverlay'); diff --git a/packages/void/test/unit/pages-scan.test.ts b/packages/void/test/unit/pages-scan.test.ts index 948a49ca8..92aaf1896 100644 --- a/packages/void/test/unit/pages-scan.test.ts +++ b/packages/void/test/unit/pages-scan.test.ts @@ -101,6 +101,28 @@ describe('scanPages', () => { expect(result).toEqual({ pages: [], layouts: [], namedLayouts: [] }); }); + it.each(['dev', 'prod'] as const)( + 'reports misplaced Pages middleware in an empty %s Pages tree', + async (environment) => { + writeFile('admin/_middleware.prod.d.ts', 'export {};'); + writeFile('admin/_middleware.css', ''); + writeFile('.drafts/_middleware.yml', ''); + writeFile('admin/_middleware/notes.txt', ''); + writeFile('admin/_middleware.txt/notes.txt', ''); + + const result = await scanPages(TMP, { environment }); + expect(result.pages).toEqual([]); + expect(result.misplacedMiddleware).toEqual([ + '.drafts/_middleware.yml', + 'admin/_middleware.css', + 'admin/_middleware.prod.d.ts', + ]); + expect( + (await scanPages(TMP, { environment, checkRoutes: false })).misplacedMiddleware, + ).toBeUndefined(); + }, + ); + it('scans .vue files and produces correct patterns', async () => { writeFile('index.vue', ''); writeFile('about.vue', ''); diff --git a/packages/void/test/unit/plugin-routing.test.ts b/packages/void/test/unit/plugin-routing.test.ts index 1152872fe..c5d520879 100644 --- a/packages/void/test/unit/plugin-routing.test.ts +++ b/packages/void/test/unit/plugin-routing.test.ts @@ -71,7 +71,9 @@ function resolveConfig( } async function runBuildStart(plugin: RoutingPlugin): Promise { - await (getHookHandler(plugin.buildStart) as () => Promise).call({} as never); + await (getHookHandler(plugin.buildStart) as () => Promise).call({ + meta: { watchMode: false }, + } as never); } function fakeDevServer( @@ -139,6 +141,38 @@ describe('routingPlugin', () => { } }); + it('reports misplaced Pages middleware in the configured sourceDir at build start', async () => { + const root = createBareTempRoot(); + writeFileSync(join(root, 'void.json'), JSON.stringify({ sourceDir: 'src' })); + mkdirSync(join(root, 'pages'), { recursive: true }); + mkdirSync(join(root, 'src', 'pages', 'admin'), { recursive: true }); + mkdirSync(join(root, 'src', 'routes'), { recursive: true }); + writeFileSync(join(root, 'pages', '_middleware.ts'), 'export {};'); + for (const name of ['_middleware.dev.ts', '_middleware.tsx', '__root.tsx']) { + writeFileSync(join(root, 'src', 'routes', name), 'export {};'); + } + const plugin = createRoutingPlugin(root, { isAuthEnabled: () => false }); + resolveConfig(plugin, 'build'); + await runBuildStart(plugin); + + writeFileSync(join(root, 'src', 'pages', 'admin', '_middleware.prod.d.ts'), 'export {};'); + await expect(runBuildStart(plugin)).rejects.toThrow('src/pages/admin/_middleware.prod.d.ts'); + }); + + it('keeps prepare declarations identical with misplaced Pages middleware', async () => { + const root = createTempRoot(); + const pageDir = join(root, 'pages', 'admin'); + mkdirSync(pageDir, { recursive: true }); + writeFileSync(join(pageDir, 'index.tsx'), 'export default () => null;'); + writeFileSync(join(root, 'routes', 'api.ts'), 'export const GET = () => "ok";'); + await prepareProject(root); + const typesPath = join(root, '.void', 'routes.d.ts'); + const prepared = readFileSync(typesPath); + writeFileSync(join(pageDir, '_middleware.prod.d.ts'), 'export {};'); + await prepareProject(root); + expect(readFileSync(typesPath)).toEqual(prepared); + }); + it('enables the worker SPA fallback for websocket-only routes', async () => { const root = createTempRoot(); writeFileSync( diff --git a/packages/void/test/unit/plugin-version-metadata.test.ts b/packages/void/test/unit/plugin-version-metadata.test.ts index c0aca608a..c655c3bc3 100644 --- a/packages/void/test/unit/plugin-version-metadata.test.ts +++ b/packages/void/test/unit/plugin-version-metadata.test.ts @@ -59,7 +59,10 @@ async function generate(resolved: Record, command: 'build' | 's if (!buildStart) { throw new Error('Void routing hook missing'); } - await (buildStart as () => Promise)(); + await buildStart.call( + { meta: { watchMode: false } } as ThisParameterType, + {} as Parameters[0], + ); return { patch, entry: readFileSync(join(root, '.void/entry.ts'), 'utf8') }; } diff --git a/packages/void/test/unit/routing-runtime.test.ts b/packages/void/test/unit/routing-runtime.test.ts index b61f63f31..53237afc4 100644 --- a/packages/void/test/unit/routing-runtime.test.ts +++ b/packages/void/test/unit/routing-runtime.test.ts @@ -20,6 +20,7 @@ import { createHttpRouteHandler, createModuleLoader, createRoutingRuntime, + isDirectoryDenial, } from '../../src/runtime/routing/index.ts'; import type { RoutingContext, @@ -56,6 +57,64 @@ declare module 'void/routes' { } describe('typed HTTP execution', () => { + it('keeps directory denials out of the native asset fallback', async () => { + const app = new Hono(); + const routing = createRoutingRuntime(app); + app.use(routing.contextMiddleware); + app.notFound(routing.trackNotFound()); + app.get( + '/private', + routing.directoryMiddleware( + [['_middleware.ts', (c) => c.text('hidden', 404)]], + (c) => c.text('private'), + (c) => c.text('not found', 404), + ), + ); + const files = vi.fn(async () => new Response('same-path asset')); + const env = { ASSETS: { fetch: files } }; + const assets = createAssetFallback(); + const read = async (path: string, method: string) => { + const request = new Request(`https://app.test${path}`, { method }); + return assets(request, env, await app.fetch(request, env)); + }; + const denial = await read('/private', 'GET'); + expect(denial.status).toBe(404); + expect(await denial.text()).toBe('hidden'); + expect((await read('/private', 'HEAD')).status).toBe(404); + expect(files).not.toHaveBeenCalled(); + expect(await (await read('/missing', 'GET')).text()).toBe('same-path asset'); + }); + + it('keeps a reused bodyless denial from accumulating clone wrappers', async () => { + const app = new Hono(); + const routing = createRoutingRuntime(app); + const denial = new Response(null, { status: 404 }); + app.use(routing.contextMiddleware); + app.use(async (c, next) => { + await next(); + c.res = c.res.clone(); + }); + app.get( + '/private', + routing.directoryMiddleware( + [['_middleware.ts', () => denial]], + (c) => c.text('private'), + (c) => c.text('not found', 404), + ), + ); + const request = async () => { + const req = new Request('https://app.test/private'); + const response = await app.fetch(req); + expect(response.status).toBe(404); + expect(response.body).toBeNull(); + expect(isDirectoryDenial(req)).toBe(true); + }; + await request(); + const clone = Object.getOwnPropertyDescriptor(denial, 'clone'); + await Promise.all(Array.from({ length: 4 }, request)); + expect(Object.getOwnPropertyDescriptor(denial, 'clone')).toEqual(clone); + }); + it.each([undefined, 301, 303, 307, 308] as const)( 'redirects typed destinations with status %s', async (status) => { diff --git a/packages/void/test/unit/scan.test.ts b/packages/void/test/unit/scan.test.ts index b31e4506b..9152db83f 100644 --- a/packages/void/test/unit/scan.test.ts +++ b/packages/void/test/unit/scan.test.ts @@ -2,6 +2,7 @@ import { mkdirSync, writeFileSync, rmSync } from 'node:fs'; import { join } from 'node:path'; import { describe, expect, it, beforeEach, afterEach } from 'vite-plus/test'; import { packageFixturePath } from '../../../../test/fixture-dir.ts'; +import { getNativeWorkerSourceFiles } from '../../src/application-analysis.ts'; import { analyzeApplication } from '../../src/application-routing.ts'; import { generateRouteTypes } from '../../src/codegen/route-types.ts'; import { readConfig } from '../../src/config.ts'; @@ -49,6 +50,54 @@ describe('scanRoutes', () => { } }); + it('finds directory middleware only for environment-active file ancestry', async () => { + createFile('void.config.ts', 'export default { sourceDir: "app" };'); + const guard = 'export default (_c, next) => next();'; + for (const file of [ + '_middleware.ts', + 'admin/_middleware.mts', + 'admin/(group)/[id]/_middleware.js', + '.well-known/_middleware.mjs', + 'dev/_middleware.ts', + 'dev/_middleware.mjs', + '_middleware.dev.ts', + '_middleware.tsx', + ]) { + createFile(`app/routes/${file}`, guard); + } + for (const endpoint of [ + 'admin.ts', + 'admin/(group)/[id]/[...rest].ts', + '.well-known/status.ts', + 'dev/only.dev.ts', + ]) { + createFile(`app/routes/${endpoint}`); + } + + const prod = await scanRoutes(TMP, { environment: 'prod' }); + expect(prod.directoryMiddleware).toEqual({ + chains: { + 'admin.ts': ['_middleware.ts'], + 'admin/(group)/[id]/[...rest].ts': [ + '_middleware.ts', + 'admin/_middleware.mts', + 'admin/(group)/[id]/_middleware.js', + ], + '.well-known/status.ts': ['_middleware.ts', '.well-known/_middleware.mjs'], + }, + }); + const dev = await scanRoutes(TMP, { environment: 'dev' }); + expect(dev.directoryMiddleware?.diagnostic).toContain('app/routes/dev/_middleware.ts'); + expect(dev.directoryMiddleware?.diagnostic).toContain('app/routes/dev/_middleware.mjs'); + const paths = [TMP, 'app', 'routes']; + const declarations = (scan: Awaited>) => + generateRouteTypes(scan, join(...paths), join(TMP, '.void')).dts; + const previous = declarations(dev); + rmSync(join(...paths, 'dev', '_middleware.mjs')); + rmSync(join(...paths, 'dev', '_middleware.ts')); + expect(declarations(await scanRoutes(TMP, { environment: 'dev' }))).toBe(previous); + }); + it('discovers route files with methods from exports', async () => { createFile('routes/api/hello.ts', 'export const GET = () => {}'); createFile( @@ -377,6 +426,21 @@ export default () => {};`, expect(prod.websockets?.map((r) => r.filePath)).toEqual(['chat.prod.ws.ts']); }); + it('follows an environment-active WebSocket-only guard in the native optimizer', async () => { + createFile('routes/chat/index.dev.ws.ts', 'export default defineWebSocket({})'); + createFile('routes/chat/_middleware.ts', 'export default (_c, next) => next();'); + const config = readConfig(TMP); + const dev = await analyzeApplication(TMP, { config, environment: 'dev' }); + expect(dev.scan.directoryMiddleware?.chains).toEqual({ + 'chat/index.dev.ws.ts': ['chat/_middleware.ts'], + }); + expect(await getNativeWorkerSourceFiles(dev)).toContain( + join(TMP, 'routes/chat/_middleware.ts'), + ); + const prod = await scanRoutes(TMP, { environment: 'prod' }); + expect(prod.directoryMiddleware).toBeUndefined(); + }); + it('discovers all WebSocket route extensions separately from HTTP handlers', async () => { createFile('routes/tsx.tsx', 'export const GET = () =>

TSX

;'); createFile('routes/jsx.jsx', 'export const GET = () =>

JSX

;'); diff --git a/platform/packages/dispatch/test/unit/fallback-rules.test.ts b/platform/packages/dispatch/test/unit/fallback-rules.test.ts index e746c5ed2..4613578c3 100644 --- a/platform/packages/dispatch/test/unit/fallback-rules.test.ts +++ b/platform/packages/dispatch/test/unit/fallback-rules.test.ts @@ -587,6 +587,38 @@ describe('fallbackRules rewrite — WfP/framework branch', () => { expect(res.headers.get('X-Void-No-Match')).toBeNull(); }); + it('preserves marked and unmarked managed misses and a directory denial', async () => { + // Void's runtime needs the SDK's types, so Vitest loads this fixture at runtime. + const { createManagedFallbackWorker } = await vi.importActual<{ + createManagedFallbackWorker( + pages: boolean, + ): (request: Request) => Response | Promise; + }>('../../../../../packages/void/test/fixtures/managed-fallback-worker.ts'); + for (const { pages, path, calls, status } of [ + { pages: true, path: '/missing', calls: 2, status: 200 }, + { pages: false, path: '/missing', calls: 1, status: 404 }, + { pages: true, path: '/private', calls: 1, status: 404 }, + ]) { + const { env, workerFetch } = createWorkerEnv({ + routing: { + workerName: 'middleware-test', + projectId: 'proj_1', + type: 'void', + fallbackRules: [{ source: '/*', destination: '/fallback', status: 200 }], + }, + workerHandler: createManagedFallbackWorker(pages), + }); + const response = await app.fetch( + new Request(`https://test.void.app${path}`), + env, + createCtx(), + ); + expect(response.status).toBe(status); + expect(workerFetch).toHaveBeenCalledTimes(calls); + expect(response.headers.get('X-Void-No-Match')).toBeNull(); + } + }); + it('preserves the request body across worker fallback re-dispatch on POST', async () => { // Regression: the first `worker.fetch(dispatchReq)` consumes the body // stream. Without cloning, the fallback re-dispatch would receive an