From a7fe9d04f13e778738307f8908d9d6263fc0a246 Mon Sep 17 00:00:00 2001 From: Michael Herzner Date: Mon, 31 Jul 2023 11:48:26 +0200 Subject: [PATCH] feat(server): add safety checks during `dev` (#1489) Co-authored-by: Reed von Redwitz --- docs/latest/concepts/islands.md | 3 +- src/server/context.ts | 59 +++-- src/server/deps.ts | 5 + src/server/dev_checks.ts | 214 ++++++++++++++++++ src/server/types.ts | 13 ++ .../custom_static/custom.txt | 1 + tests/fixture_dev_checks/deno.json | 16 ++ tests/fixture_dev_checks/dev.ts | 5 + tests/fixture_dev_checks/fresh.gen.ts | 25 ++ tests/fixture_dev_checks/main.ts | 15 ++ .../plugins/not_calling_ctx_render.ts | 11 + .../plugins/not_having_modules.ts | 15 ++ tests/fixture_dev_checks/routes/_app.tsx | 9 + tests/fixture_dev_checks/routes/custom.txt.ts | 5 + tests/fixture_dev_checks/routes/index.tsx | 3 + .../fixture_dev_checks/routes/nested/_app.tsx | 9 + tests/fixture_dev_checks/routes/test.tsx | 3 + .../fixture_dev_checks/routes/test/index.tsx | 3 + tests/fixture_dev_checks/static/custom.txt | 1 + .../utils/css-inject-plugin-async.ts | 1 - 20 files changed, 398 insertions(+), 18 deletions(-) create mode 100644 src/server/dev_checks.ts create mode 100644 tests/fixture_dev_checks/custom_static/custom.txt create mode 100644 tests/fixture_dev_checks/deno.json create mode 100755 tests/fixture_dev_checks/dev.ts create mode 100644 tests/fixture_dev_checks/fresh.gen.ts create mode 100644 tests/fixture_dev_checks/main.ts create mode 100644 tests/fixture_dev_checks/plugins/not_calling_ctx_render.ts create mode 100644 tests/fixture_dev_checks/plugins/not_having_modules.ts create mode 100644 tests/fixture_dev_checks/routes/_app.tsx create mode 100644 tests/fixture_dev_checks/routes/custom.txt.ts create mode 100644 tests/fixture_dev_checks/routes/index.tsx create mode 100644 tests/fixture_dev_checks/routes/nested/_app.tsx create mode 100644 tests/fixture_dev_checks/routes/test.tsx create mode 100644 tests/fixture_dev_checks/routes/test/index.tsx create mode 100644 tests/fixture_dev_checks/static/custom.txt diff --git a/docs/latest/concepts/islands.md b/docs/latest/concepts/islands.md index 2de11c08..e532f0d5 100644 --- a/docs/latest/concepts/islands.md +++ b/docs/latest/concepts/islands.md @@ -8,8 +8,7 @@ components that are rendered on the client. This is different from all other components in Fresh, as they are usually just rendered on the server. Islands are defined by creating a file in the `islands/` folder in a Fresh -project. The name of this file must be a PascalCase or kebab-case name of the -island. +project. ```tsx // islands/MyIsland.tsx diff --git a/src/server/context.ts b/src/server/context.ts index 14deda06..586bbda1 100644 --- a/src/server/context.ts +++ b/src/server/context.ts @@ -38,6 +38,7 @@ import { RouterOptions, RouterState, ServeHandlerInfo, + StaticFile, UnknownPage, UnknownPageModule, } from "./types.ts"; @@ -55,6 +56,18 @@ import { JSXConfig, } from "../build/mod.ts"; import { InternalRoute } from "./router.ts"; +import { + assertModuleExportsDefault, + assertNoStaticRouteConflicts, + assertPluginsCallRender, + assertPluginsCallRenderAsync, + assertPluginsInjectModules, + assertRoutesHaveHandlerOrComponent, + assertSingleModule, + assertSingleRoutePattern, + assertStaticDirSafety, + CheckFunction, +} from "$fresh/src/server/dev_checks.ts"; const DEFAULT_CONN_INFO: ServeHandlerInfo = { localAddr: { transport: "tcp", hostname: "localhost", port: 8080 }, @@ -71,20 +84,6 @@ function isDevMode() { // Env var is only set in prod (on Deploy). return Deno.env.get("DENO_DEPLOYMENT_ID") === undefined; } - -interface StaticFile { - /** The URL to the static file on disk. */ - localUrl: URL; - /** The path to the file as it would be in the incoming request. */ - path: string; - /** The size of the file. */ - size: number; - /** The content-type of the file. */ - contentType: string; - /** Hash of the file contents. */ - etag: string; -} - export class ServerContext { #dev: boolean; #routes: Route[]; @@ -146,6 +145,7 @@ export class ServerContext { ): Promise { // Get the manifest' base URL. const baseUrl = new URL("./", manifest.baseUrl).href; + const defaultStaticDir = "./static"; const { config, path: configPath } = await readDenoConfig( fromFileUrl(baseUrl), @@ -183,7 +183,9 @@ export class ServerContext { let app: AppModule = DEFAULT_APP; const layouts: LayoutRoute[] = []; let notFound: UnknownPage = DEFAULT_NOT_FOUND; + let unknownModule: UnknownPageModule | null = null; let error: ErrorPage = DEFAULT_ERROR; + let errorModule: ErrorPageModule | null = null; const allRoutes = [ ...Object.entries(manifest.routes), ...Object.entries(getMiddlewareRoutesFromPlugins(opts.plugins || [])), @@ -268,6 +270,7 @@ export class ServerContext { path === "/_404.tsx" || path === "/_404.ts" || path === "/_404.jsx" || path === "/_404.js" ) { + unknownModule = module as UnknownPageModule; const { default: component, config } = module as UnknownPageModule; let { handler } = module as UnknownPageModule; if (component && handler === undefined) { @@ -286,6 +289,7 @@ export class ServerContext { path === "/_500.tsx" || path === "/_500.ts" || path === "/_500.jsx" || path === "/_500.js" ) { + errorModule = module as ErrorPageModule; const { default: component, config } = module as ErrorPageModule; let { handler } = module as ErrorPageModule; if (component && handler === undefined) { @@ -334,7 +338,7 @@ export class ServerContext { const staticFiles: StaticFile[] = []; try { const staticFolder = new URL( - opts.staticDir ?? "./static", + opts.staticDir ?? defaultStaticDir, manifest.baseUrl, ); const entries = walk(fromFileUrl(staticFolder), { @@ -376,6 +380,31 @@ export class ServerContext { const dev = isDevMode(); if (dev) { + const checks: CheckFunction[] = [ + () => assertModuleExportsDefault(app, "_app"), + () => assertSingleModule(routes, "_app"), + () => assertModuleExportsDefault(unknownModule, "_404"), + () => assertSingleModule(routes, "_404"), + () => assertSingleRoutePattern(routes), + () => assertModuleExportsDefault(errorModule, "_500"), + () => assertSingleModule(routes, "_500"), + () => assertRoutesHaveHandlerOrComponent(routes), + () => assertStaticDirSafety(opts.staticDir ?? "", defaultStaticDir), + () => assertNoStaticRouteConflicts(routes, staticFiles), + () => assertPluginsCallRender(opts.plugins ?? []), + () => assertPluginsCallRenderAsync(opts.plugins ?? []), + () => assertPluginsInjectModules(opts.plugins ?? []), + ]; + + const results = checks.flatMap((check) => check()); + + results.forEach((result) => { + console.log(`[${result.category}] ${result.message}`); + if (result.fileLink) { + console.log(`See: ${result.fileLink}`); + } + }); + // Ensure that debugging hooks are set up for SSR rendering await import("preact/debug"); } diff --git a/src/server/deps.ts b/src/server/deps.ts index 94eb5700..76ca0f0d 100644 --- a/src/server/deps.ts +++ b/src/server/deps.ts @@ -8,6 +8,7 @@ export { } from "https://deno.land/std@0.193.0/path/mod.ts"; export { walk } from "https://deno.land/std@0.193.0/fs/walk.ts"; export * as colors from "https://deno.land/std@0.193.0/fmt/colors.ts"; +export { existsSync } from "https://deno.land/std@0.193.0/fs/mod.ts"; export { type Handler as ServeHandler, serve, @@ -20,3 +21,7 @@ export { export { toHashString } from "https://deno.land/std@0.193.0/crypto/to_hash_string.ts"; export { escape } from "https://deno.land/std@0.193.0/regexp/escape.ts"; export * as JSONC from "https://deno.land/std@0.193.0/jsonc/mod.ts"; +export { + assertSpyCalls, + spy, +} from "https://deno.land/std@0.193.0/testing/mock.ts"; diff --git a/src/server/dev_checks.ts b/src/server/dev_checks.ts new file mode 100644 index 00000000..12427d75 --- /dev/null +++ b/src/server/dev_checks.ts @@ -0,0 +1,214 @@ +import { assertSpyCalls, existsSync, spy } from "./deps.ts"; +import { + AppModule, + ErrorPageModule, + Route, + StaticFile, + UnknownPageModule, +} from "$fresh/src/server/types.ts"; +import { knownMethods } from "$fresh/src/server/router.ts"; +import { Plugin } from "$fresh/src/server/mod.ts"; + +export type CheckFunction = () => CheckResult[]; + +interface CheckResult { + category: string; + message: string; + fileLink?: string; +} + +export function assertModuleExportsDefault( + module: AppModule | UnknownPageModule | ErrorPageModule | null, + moduleName: string, +): CheckResult[] { + if (module && !module.default) { + return [{ + category: "Module Export", + message: `Your ${moduleName} file does not have a default export.`, + fileLink: moduleName, + }]; + } + return []; +} + +export function assertSingleModule( + routes: Route[], + moduleName: string, +): CheckResult[] { + const moduleRoutes = routes.filter((route) => + route.name.includes(moduleName) + ); + + if (moduleRoutes.length > 0) { + return [{ + category: "Multiple Modules", + message: + `Only one ${moduleName} is allowed per application. It must be in the root of the /routes/ folder.`, + }]; + } + return []; +} + +export function assertSingleRoutePattern(routes: Route[]) { + const routeNames = new Set(routes.map((route) => route.pattern)); + + return routes.flatMap((route) => { + if (routeNames.has(route.pattern)) { + routeNames.delete(route.pattern); + } else { + return [{ + category: "Duplicate Route Patterns", + message: + `Duplicate route pattern: ${route.pattern}. Please rename the route to resolve the route conflicts.`, + }]; + } + return []; + }); +} + +export function assertRoutesHaveHandlerOrComponent( + routes: Route[], +): CheckResult[] { + return routes.flatMap((route) => { + const hasComponent = !!route.component; + + let hasHandlerMethod = false; + if (typeof route.handler === "object") { + for (const method of knownMethods) { + if (method in route.handler) { + hasHandlerMethod = true; + break; + } + } + } + + if (!hasComponent && !hasHandlerMethod) { + return [{ + category: "Handler or Component", + message: + `Route at ${route.url} must have a handler or component. It's possible you're missing a default export.`, + fileLink: route.name, + }]; + } + return []; + }); +} + +export function assertStaticDirSafety( + dir: string, + defaultDir: string, +): CheckResult[] { + const results: CheckResult[] = []; + + if (dir === defaultDir) { + results.push({ + category: "Static Directory", + message: + "You cannot use the default static directory as a static override. Please choose a different directory.", + }); + } + + if (existsSync(defaultDir)) { + results.push({ + category: "Static Directory", + message: + "You cannot have both a static override and a default static directory. Please remove the default static directory.", + }); + } + + return results; +} + +export function assertNoStaticRouteConflicts( + routes: Route[], + staticFiles: StaticFile[], +): CheckResult[] { + const routePatterns = new Set(routes.map((route) => route.pattern)); + + return staticFiles.flatMap((staticFile) => { + if (routePatterns.has(staticFile.path)) { + return [{ + category: "Static File Conflict", + message: + `Static file conflict: A file exists at '${staticFile.path}' which matches a route pattern. Please rename the file or change the route pattern.`, + fileLink: staticFile.path, + }]; + } + return []; + }); +} + +export function assertPluginsCallRender(plugins: Plugin[]): CheckResult[] { + const results: CheckResult[] = []; + + plugins.forEach((plugin) => { + if (typeof plugin.render === "function") { + const renderSpy = spy(() => ({ + htmlText: "", + requiresHydration: false, + })); + plugin.render({ render: renderSpy }); + try { + assertSpyCalls(renderSpy, 1); + } catch { + results.push({ + category: "Plugin Render", + message: + `Plugin '${plugin.name}' must call ctx.render() exactly once.`, + }); + } + } + }); + + return results; +} + +export function assertPluginsCallRenderAsync( + plugins: Plugin[], +): CheckResult[] { + const results: CheckResult[] = []; + + for (const plugin of plugins) { + if (typeof plugin.renderAsync === "function") { + const renderAsyncSpy = spy(() => + Promise.resolve({ + htmlText: "", + requiresHydration: false, + }) + ); + plugin.renderAsync({ renderAsync: renderAsyncSpy }).then( + () => { + try { + assertSpyCalls(renderAsyncSpy, 1); + } catch { + results.push({ + category: "Plugin RenderAsync", + message: + `Plugin '${plugin.name}' must call ctx.render() exactly once.`, + }); + } + }, + ); + } + } + + return results; +} + +export function assertPluginsInjectModules(plugins: Plugin[]): CheckResult[] { + const results: CheckResult[] = []; + + plugins.forEach((plugin) => { + Object.values(plugin.entrypoints ?? {}).forEach((script) => { + if (!script.includes("export default")) { + results.push({ + category: "Plugin Inject Modules", + message: + `Plugin '${plugin.name}' must export a default function from its entrypoint.`, + }); + } + }); + }); + + return results; +} diff --git a/src/server/types.ts b/src/server/types.ts index 8334466b..c9f32145 100644 --- a/src/server/types.ts +++ b/src/server/types.ts @@ -427,3 +427,16 @@ export interface PluginRoute { // deno-lint-ignore no-explicit-any handler?: Handler | Handlers; } + +export interface StaticFile { + /** The URL to the static file on disk. */ + localUrl: URL; + /** The path to the file as it would be in the incoming request. */ + path: string; + /** The size of the file. */ + size: number; + /** The content-type of the file. */ + contentType: string; + /** Hash of the file contents. */ + etag: string; +} diff --git a/tests/fixture_dev_checks/custom_static/custom.txt b/tests/fixture_dev_checks/custom_static/custom.txt new file mode 100644 index 00000000..c784e5e1 --- /dev/null +++ b/tests/fixture_dev_checks/custom_static/custom.txt @@ -0,0 +1 @@ +This is from a text file in the modified static directory. diff --git a/tests/fixture_dev_checks/deno.json b/tests/fixture_dev_checks/deno.json new file mode 100644 index 00000000..79b6c858 --- /dev/null +++ b/tests/fixture_dev_checks/deno.json @@ -0,0 +1,16 @@ +{ + "lock": false, + "tasks": { + "start": "deno run -A --watch=static/,routes/ dev.ts" + }, + "imports": { + "$fresh/": "../../", + "preact": "https://esm.sh/preact@10.15.1", + "preact/": "https://esm.sh/preact@10.15.1/", + "preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.2.0" + }, + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "preact" + } +} diff --git a/tests/fixture_dev_checks/dev.ts b/tests/fixture_dev_checks/dev.ts new file mode 100755 index 00000000..2d85d6c1 --- /dev/null +++ b/tests/fixture_dev_checks/dev.ts @@ -0,0 +1,5 @@ +#!/usr/bin/env -S deno run -A --watch=static/,routes/ + +import dev from "$fresh/dev.ts"; + +await dev(import.meta.url, "./main.ts"); diff --git a/tests/fixture_dev_checks/fresh.gen.ts b/tests/fixture_dev_checks/fresh.gen.ts new file mode 100644 index 00000000..aa3b1e5c --- /dev/null +++ b/tests/fixture_dev_checks/fresh.gen.ts @@ -0,0 +1,25 @@ +// DO NOT EDIT. This file is generated by Fresh. +// This file SHOULD be checked into source version control. +// This file is automatically updated during development when running `dev.ts`. + +import * as $0 from "./routes/_app.tsx"; +import * as $1 from "./routes/custom.txt.ts"; +import * as $2 from "./routes/index.tsx"; +import * as $3 from "./routes/nested/_app.tsx"; +import * as $4 from "./routes/test.tsx"; +import * as $5 from "./routes/test/index.tsx"; + +const manifest = { + routes: { + "./routes/_app.tsx": $0, + "./routes/custom.txt.ts": $1, + "./routes/index.tsx": $2, + "./routes/nested/_app.tsx": $3, + "./routes/test.tsx": $4, + "./routes/test/index.tsx": $5, + }, + islands: {}, + baseUrl: import.meta.url, +}; + +export default manifest; diff --git a/tests/fixture_dev_checks/main.ts b/tests/fixture_dev_checks/main.ts new file mode 100644 index 00000000..fa8fb856 --- /dev/null +++ b/tests/fixture_dev_checks/main.ts @@ -0,0 +1,15 @@ +/// +/// +/// +/// +/// + +import { start } from "$fresh/server.ts"; +import manifest from "./fresh.gen.ts"; +import notCallingCtxRender from "./plugins/not_calling_ctx_render.ts"; +import notHavingModules from "./plugins/not_having_modules.ts"; + +await start(manifest, { + plugins: [notHavingModules(), notCallingCtxRender()], + staticDir: "./custom_static", +}); diff --git a/tests/fixture_dev_checks/plugins/not_calling_ctx_render.ts b/tests/fixture_dev_checks/plugins/not_calling_ctx_render.ts new file mode 100644 index 00000000..c85bbf90 --- /dev/null +++ b/tests/fixture_dev_checks/plugins/not_calling_ctx_render.ts @@ -0,0 +1,11 @@ +import { Plugin } from "$fresh/server.ts"; + +export default function notCallingCtxRender(): Plugin { + return { + name: "not_calling_ctx_render", + entrypoints: {}, + render() { + return {}; + }, + }; +} diff --git a/tests/fixture_dev_checks/plugins/not_having_modules.ts b/tests/fixture_dev_checks/plugins/not_having_modules.ts new file mode 100644 index 00000000..d2496e18 --- /dev/null +++ b/tests/fixture_dev_checks/plugins/not_having_modules.ts @@ -0,0 +1,15 @@ +import { Plugin } from "$fresh/server.ts"; + +export default function notHavingModules(): Plugin { + return { + name: "not_having_modules", + entrypoints: { "main": "() => {}" }, + render(ctx) { + ctx.render(); + + return { + scripts: [{ entrypoint: "main", state: [] }], + }; + }, + }; +} diff --git a/tests/fixture_dev_checks/routes/_app.tsx b/tests/fixture_dev_checks/routes/_app.tsx new file mode 100644 index 00000000..86a3c584 --- /dev/null +++ b/tests/fixture_dev_checks/routes/_app.tsx @@ -0,0 +1,9 @@ +import { AppProps } from "$fresh/server.ts"; + +export function App(props: AppProps) { + return ( + <> + + + ); +} diff --git a/tests/fixture_dev_checks/routes/custom.txt.ts b/tests/fixture_dev_checks/routes/custom.txt.ts new file mode 100644 index 00000000..c68dbd6a --- /dev/null +++ b/tests/fixture_dev_checks/routes/custom.txt.ts @@ -0,0 +1,5 @@ +export const handler = { + GET() { + return new Response("This is from the handler!"); + }, +}; diff --git a/tests/fixture_dev_checks/routes/index.tsx b/tests/fixture_dev_checks/routes/index.tsx new file mode 100644 index 00000000..fcaf0efc --- /dev/null +++ b/tests/fixture_dev_checks/routes/index.tsx @@ -0,0 +1,3 @@ +export default function Home(): null { + throw new Error("boom!"); +} diff --git a/tests/fixture_dev_checks/routes/nested/_app.tsx b/tests/fixture_dev_checks/routes/nested/_app.tsx new file mode 100644 index 00000000..109ad01e --- /dev/null +++ b/tests/fixture_dev_checks/routes/nested/_app.tsx @@ -0,0 +1,9 @@ +import { AppProps } from "$fresh/server.ts"; + +export default function App(props: AppProps) { + return ( + <> + + + ); +} diff --git a/tests/fixture_dev_checks/routes/test.tsx b/tests/fixture_dev_checks/routes/test.tsx new file mode 100644 index 00000000..3cdf8196 --- /dev/null +++ b/tests/fixture_dev_checks/routes/test.tsx @@ -0,0 +1,3 @@ +export function Test() { + return
hello
; +} diff --git a/tests/fixture_dev_checks/routes/test/index.tsx b/tests/fixture_dev_checks/routes/test/index.tsx new file mode 100644 index 00000000..0ef992a1 --- /dev/null +++ b/tests/fixture_dev_checks/routes/test/index.tsx @@ -0,0 +1,3 @@ +export default function Test() { + return
hello
; +} diff --git a/tests/fixture_dev_checks/static/custom.txt b/tests/fixture_dev_checks/static/custom.txt new file mode 100644 index 00000000..fe3595d4 --- /dev/null +++ b/tests/fixture_dev_checks/static/custom.txt @@ -0,0 +1 @@ +This is from a text file. diff --git a/tests/fixture_plugin/utils/css-inject-plugin-async.ts b/tests/fixture_plugin/utils/css-inject-plugin-async.ts index 356ad1d4..78294ea4 100644 --- a/tests/fixture_plugin/utils/css-inject-plugin-async.ts +++ b/tests/fixture_plugin/utils/css-inject-plugin-async.ts @@ -5,7 +5,6 @@ let CSS_TO_INJECT = "h1 { text-decoration: underline; }"; export default { name: "css-inject-async", async renderAsync(ctx) { - await new Promise((res) => setTimeout(res, 50)); const res = await ctx.renderAsync(); if (res.requiresHydration) { CSS_TO_INJECT += " h1 { font-style: italic; }";