From 44a0d490fe8fe3455e38ed85399cda037b17c995 Mon Sep 17 00:00:00 2001 From: Luca Casonato Date: Mon, 1 Nov 2021 12:58:13 +0100 Subject: [PATCH] feat: add support for CSP (#72) This commit adds support for running with CSP. CSP can be enabled on a per page basis. If this is done, fresh will set a default CSP that is very restrictive. Users can modify the CSP with the `useCSP` hook. Fresh will add its own script resources to the CSP automatically. --- examples/todo-app/pages/index.tsx | 4 +- runtime.ts | 1 + src/runtime/csp.ts | 139 ++++++++++++++++++++++++++++++ src/runtime/types.ts | 8 ++ src/server/context.ts | 62 +++++++++++-- src/server/render.tsx | 89 +++++++++++++++---- src/server/types.ts | 1 + 7 files changed, 276 insertions(+), 28 deletions(-) create mode 100644 src/runtime/csp.ts diff --git a/examples/todo-app/pages/index.tsx b/examples/todo-app/pages/index.tsx index 7bc5bb2b..03e2dd6e 100644 --- a/examples/todo-app/pages/index.tsx +++ b/examples/todo-app/pages/index.tsx @@ -1,5 +1,5 @@ /** @jsx h */ -import { h, HandlerContext, Suspense, useData } from "../deps.ts"; +import { h, HandlerContext, PageConfig, Suspense, useData } from "../deps.ts"; import { getDatabase, Todo } from "../utils/database.ts"; export default function TodoListPage() { @@ -48,3 +48,5 @@ export const handler = { return Response.redirect(ctx.req.url, 303); }, }; + +export const config: PageConfig = { csp: true }; diff --git a/runtime.ts b/runtime.ts index fd307424..b35eb535 100644 --- a/runtime.ts +++ b/runtime.ts @@ -4,3 +4,4 @@ export * from "./src/runtime/suspense.ts"; export * from "./src/runtime/utils.ts"; export * from "./src/runtime/hooks.ts"; export * from "./src/runtime/head.ts"; +export * from "./src/runtime/csp.ts"; diff --git a/src/runtime/csp.ts b/src/runtime/csp.ts new file mode 100644 index 00000000..9955b054 --- /dev/null +++ b/src/runtime/csp.ts @@ -0,0 +1,139 @@ +import { createContext, useContext } from "./deps.ts"; + +export const SELF = "'self'"; +export const UNSAFE_INLINE = "'unsafe-inline'"; +export const UNSAFE_EVAL = "'unsafe-eval'"; +export const UNSAFE_HASHES = "'unsafe-hashes'"; +export const NONE = "'none'"; +export const STRICT_DYNAMIC = "'strict-dynamic'"; + +export function nonce(val: string) { + return `'nonce-${val}'`; +} + +export interface ContentSecurityPolicy { + directives: ContentSecurityPolicyDirectives; + reportOnly: boolean; +} + +export interface ContentSecurityPolicyDirectives { + // Fetch directives + /** + * Defines the valid sources for web workers and nested browsing contexts + * loaded using elements such as and