Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

feat(web): security headers and disable x-powered-by (#346)

Egor Vasilyev160be7a098ba
diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts
index 433f9776..677a4633 100644
--- a/apps/web/next.config.ts
+++ b/apps/web/next.config.ts
@@ -9,9 +9,31 @@ const tracingRoot = process.env.WEB_TRACING_ROOT ?? path.join(import.meta.dirnam
// self-hosted instance runs.
const cloudUiEntry = process.env.CLOUD_UI_ENTRY;
+// Fixed on every response. The Content-Security-Policy is not here: it names the api
+// origin, which is read from the environment at startup (utils/runtimeEnv), while this
+// list is frozen into the build. It is set per request in src/proxy.ts.
+// HSTS is sent on plain http too, where browsers ignore it, so a local instance is
+// unaffected and one behind TLS gets it without a second setting.
+const SECURITY_HEADERS = [
+ { key: 'Strict-Transport-Security', value: 'max-age=63072000; includeSubDomains' },
+ { key: 'X-Frame-Options', value: 'DENY' },
+ { key: 'X-Content-Type-Options', value: 'nosniff' },
+ { key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
+ // Passkeys are the one powerful feature the app uses; the rest is switched off for
+ // this origin and for anything it might embed.
+ {
+ key: 'Permissions-Policy',
+ value:
+ 'camera=(), microphone=(), geolocation=(), payment=(), usb=(), ' +
+ 'publickey-credentials-get=(self), publickey-credentials-create=(self)',
+ },
+];
+
const nextConfig: NextConfig = {
// standalone build for a lean docker image.
output: 'standalone',
+ poweredByHeader: false,
+ headers: async () => [{ source: '/(.*)', headers: SECURITY_HEADERS }],
// Monorepo: include the repo root in file tracing for standalone.
outputFileTracingRoot: tracingRoot,
// isomorphic-dompurify loads jsdom on the server, and jsdom reads its own data
diff --git a/apps/web/src/features/api-docs/components/ScalarReference.tsx b/apps/web/src/features/api-docs/components/ScalarReference.tsx
index 5eac9db3..5f76e098 100644
--- a/apps/web/src/features/api-docs/components/ScalarReference.tsx
+++ b/apps/web/src/features/api-docs/components/ScalarReference.tsx
@@ -19,6 +19,10 @@ export default function ScalarReference({ dark }: { dark: boolean }) {
url: SPEC_URL,
forceDarkModeState: dark ? 'dark' : 'light',
hideDarkModeToggle: true,
+ // Scalar's default fonts are loaded from fonts.scalar.com, which the
+ // Content-Security-Policy blocks. The theme maps --scalar-font to the app
+ // font anyway, so its own faces are not needed.
+ withDefaultFonts: false,
agent: { disabled: true },
// The app already exposes its own MCP server; hide Scalar's built-in
// "Generate MCP" button.
diff --git a/apps/web/src/proxy.test.ts b/apps/web/src/proxy.test.ts
index 372fef10..2b2f7635 100644
--- a/apps/web/src/proxy.test.ts
+++ b/apps/web/src/proxy.test.ts
@@ -40,3 +40,24 @@ describe('proxy', () => {
assert.equal(res.headers.get('location'), 'http://localhost/login');
});
});
+
+describe('proxy security headers', () => {
+ it('serves every page with a content security policy naming the api origin', () => {
+ process.env.API_URL = 'http://api.test:3000/';
+ const csp = run('/login').headers.get('content-security-policy');
+ assert.match(csp!, /(^|; )connect-src 'self' http:\/\/api\.test:3000(;|$)/);
+ assert.match(csp!, /(^|; )frame-ancestors 'none'(;|$)/);
+ assert.match(csp!, /(^|; )object-src 'none'(;|$)/);
+ });
+
+ it('keeps the policy on a redirect and on the expired screen', () => {
+ assert.ok(run('/', undefined).headers.get('content-security-policy'));
+ assert.ok(run('/login?expired=1', COOKIE).headers.get('content-security-policy'));
+ });
+
+ it('leaves the media routes to the headers the api sends', () => {
+ assert.equal(run('/media/avatars/u1', COOKIE).headers.get('content-security-policy'), null);
+ const document = '/protected-media/projects/KEY/documents/1/assets/x/raw';
+ assert.equal(run(document, COOKIE).headers.get('content-security-policy'), null);
+ });
+});
diff --git a/apps/web/src/proxy.ts b/apps/web/src/proxy.ts
index 42854f68..834f5005 100644
--- a/apps/web/src/proxy.ts
+++ b/apps/web/src/proxy.ts
@@ -1,5 +1,6 @@
import { NextResponse, type NextRequest } from 'next/server';
import { getSessionCookie } from 'better-auth/cookies';
+import { contentSecurityPolicy } from '@/utils/contentSecurityPolicy';
// Routes reachable without a session, and that bounce a signed-in user back to
// the app. Everything else requires one.
@@ -17,6 +18,15 @@ const PUBLIC_PATHS = ['/login', '/register'];
// content and must pass this session gate before their route forwards the cookie.
const OPEN_PATHS = ['/invite', '/forgot-password', '/reset-password', '/share', '/media'];
+// Routes that stream bytes from the api and pass its headers through, including the
+// sandbox policy it puts on a download. The document policy is for html only, and set
+// here it would replace the api's.
+const MEDIA_PATHS = ['/media', '/protected-media'];
+
+function matcher(pathname: string) {
+ return (path: string) => pathname === path || pathname.startsWith(`${path}/`);
+}
+
// Expires every better-auth cookie the request carries. A `__Secure-` name is only
// accepted back with `secure`, so the deletion carries it too.
function clearSession(request: NextRequest): NextResponse {
@@ -28,6 +38,14 @@ function clearSession(request: NextRequest): NextResponse {
return response;
}
+export function proxy(request: NextRequest) {
+ const response = gate(request);
+ if (!MEDIA_PATHS.some(matcher(request.nextUrl.pathname))) {
+ response.headers.set('Content-Security-Policy', contentSecurityPolicy());
+ }
+ return response;
+}
+
// Gate the whole app behind a session. This is an optimistic check: it only looks
// for the presence of the better-auth session cookie, not its validity — the API
// does the real validation on every request. It keeps unauthenticated users out of
@@ -35,10 +53,10 @@ function clearSession(request: NextRequest): NextResponse {
// A cookie the API no longer accepts passes this check, so the client handles that
// case: `apiFailure` in `lib/api/core/client.ts` signs out on a 401 and lands on
// `/login?expired=1`, where the cookie is cleared for good.
-export function proxy(request: NextRequest) {
+function gate(request: NextRequest): NextResponse {
const { pathname } = request.nextUrl;
const hasSession = getSessionCookie(request) != null;
- const matches = (path: string) => pathname === path || pathname.startsWith(`${path}/`);
+ const matches = matcher(pathname);
if (OPEN_PATHS.some(matches)) return NextResponse.next();
diff --git a/apps/web/src/utils/contentSecurityPolicy.test.ts b/apps/web/src/utils/contentSecurityPolicy.test.ts
new file mode 100644
index 00000000..38f2a289
--- /dev/null
+++ b/apps/web/src/utils/contentSecurityPolicy.test.ts
@@ -0,0 +1,15 @@
+import assert from 'node:assert/strict';
+import { describe, it } from 'node:test';
+import { contentSecurityPolicy } from './contentSecurityPolicy';
+
+describe('contentSecurityPolicy', () => {
+ it('allows requests to the api origin only, without its path', () => {
+ process.env.API_URL = 'https://api.example.com/base/';
+ assert.match(contentSecurityPolicy(), /connect-src 'self' https:\/\/api\.example\.com;/);
+ });
+
+ it('falls back to same-origin requests when the api url is not absolute', () => {
+ process.env.API_URL = 'not a url';
+ assert.match(contentSecurityPolicy(), /connect-src 'self';/);
+ });
+});
diff --git a/apps/web/src/utils/contentSecurityPolicy.ts b/apps/web/src/utils/contentSecurityPolicy.ts
new file mode 100644
index 00000000..2d988b04
--- /dev/null
+++ b/apps/web/src/utils/contentSecurityPolicy.ts
@@ -0,0 +1,39 @@
+import { serverRuntimeEnv } from '@/utils/runtimeEnv';
+
+// The api origin is read from the running server, so the policy is built per
+// request (src/proxy.ts) rather than frozen into the build with the other headers
+// in next.config.ts. A value that is not an absolute URL contributes nothing: the
+// policy then only allows same-origin requests.
+function apiOrigin(): string {
+ try {
+ return new URL(serverRuntimeEnv().apiUrl).origin;
+ } catch {
+ return '';
+ }
+}
+
+// Inline scripts stay allowed: Next's own flight payload, the next-themes bootstrap
+// and RuntimeEnvScript are inline and carry no nonce. A nonce policy is the step
+// after this one. Inline styles are what tiptap, Radix, recharts and Scalar emit.
+// Images and media come from anywhere: markdown embeds by URL, OAuth profile
+// pictures, and the /media proxy on this origin. React evals in development only,
+// to rebuild server error stacks in the browser.
+export function contentSecurityPolicy(): string {
+ const scriptSources =
+ process.env.NODE_ENV === 'development'
+ ? "'self' 'unsafe-inline' 'unsafe-eval'"
+ : "'self' 'unsafe-inline'";
+ return [
+ "default-src 'self'",
+ `script-src ${scriptSources}`,
+ "style-src 'self' 'unsafe-inline'",
+ "img-src 'self' data: blob: https: http:",
+ "media-src 'self' data: blob: https: http:",
+ "font-src 'self' data:",
+ `connect-src 'self' ${apiOrigin()}`.trimEnd(),
+ "object-src 'none'",
+ "base-uri 'self'",
+ "form-action 'self'",
+ "frame-ancestors 'none'",
+ ].join('; ');
+}