Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions api/subscribe.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { randomUUID } from 'node:crypto';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { SUBSCRIBE_API_SECURITY_HEADERS } from '../src/utils/security-headers';

/**
* Vercel serverless function — not part of the Vite/tsc build (only `src` is
Expand Down Expand Up @@ -83,8 +84,10 @@ function logEvent(requestId: string, event: string, status: number) {

function sendJson(res: ServerResponse, requestId: string, status: number, payload: unknown) {
res.statusCode = status;
res.setHeader('Content-Type', 'application/json');
res.setHeader('Cache-Control', 'no-store');
for (const [key, value] of Object.entries(SUBSCRIBE_API_SECURITY_HEADERS)) {
res.setHeader(key, value);
}
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.setHeader('X-Request-Id', requestId);
res.end(JSON.stringify(payload));
}
Expand Down
3 changes: 2 additions & 1 deletion middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
CACHE_CONTROL,
OG_LOCALE_TAGS,
} from './src/utils/og-metadata';
import { PAGE_SECURITY_HEADERS } from './src/utils/security-headers';

export const config = {
matcher: ['/:path*'],
Expand Down Expand Up @@ -95,7 +96,7 @@ export default async function middleware(request: Request) {

html = html.replace(/<html lang="(en|es|pt)"\s*>/i, `<html lang="${metadata.locale}">`);

const headers = new Headers();
const headers = new Headers(PAGE_SECURITY_HEADERS);
headers.set('content-type', 'text/html;charset=UTF-8');
headers.set('cache-control', CACHE_CONTROL);

Expand Down
32 changes: 25 additions & 7 deletions scripts/preview-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ import { createServer, type IncomingMessage, type ServerResponse } from 'node:ht
import { readFile } from 'node:fs/promises';
import { dirname, extname, join, normalize, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
import {
PAGE_SECURITY_HEADERS,
SUBSCRIBE_API_SECURITY_HEADERS,
resolveStaticRouteHeaders,
} from '../src/utils/security-headers.ts';

const __dirname = dirname(fileURLToPath(import.meta.url));
const rootDir = join(__dirname, '..');
Expand Down Expand Up @@ -78,6 +83,12 @@ function contentType(filePath: string): string {
return MIME_TYPES[extname(filePath).toLowerCase()] ?? 'application/octet-stream';
}

function applyHeaders(res: ServerResponse, headers: Record<string, string>): void {
for (const [key, value] of Object.entries(headers)) {
res.setHeader(key, value);
}
}

// ─── Edge-runtime shims ─────────────────────────────────────────────────────

const realFetch = globalThis.fetch;
Expand Down Expand Up @@ -167,7 +178,9 @@ function decodePath(rawPath: string): string | null {

function badRequest(res: ServerResponse): void {
res.statusCode = 400;
applyHeaders(res, PAGE_SECURITY_HEADERS);
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.setHeader('Cache-Control', 'no-store');
res.end('Bad request');
}

Expand All @@ -190,12 +203,12 @@ async function serveStatic(req: IncomingMessage, res: ServerResponse): Promise<v
if (!data) {
continue;
}
const candidateExt = extname(candidate).toLowerCase();
const resolved = resolveStaticRouteHeaders(urlPath, candidateExt);
res.statusCode = 200;
res.setHeader('Content-Type', contentType(candidate));
res.setHeader(
'Cache-Control',
extname(candidate) === '.html' ? 'no-store' : 'public, max-age=3600',
);
applyHeaders(res, resolved.headers);
res.setHeader('Content-Type', resolved.contentType ?? contentType(candidate));
res.setHeader('Cache-Control', resolved.cacheControl);
res.end(data);
return;
}
Expand All @@ -205,16 +218,20 @@ async function serveStatic(req: IncomingMessage, res: ServerResponse): Promise<v
if (!urlPath.startsWith('/api/') && !urlPath.startsWith('/press-kit/')) {
const shell = await readFileOrNull(join(distDir, 'index.html'));
if (shell) {
const resolved = resolveStaticRouteHeaders(urlPath, '.html');
res.statusCode = 200;
applyHeaders(res, resolved.headers);
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.setHeader('Cache-Control', 'no-store');
res.setHeader('Cache-Control', resolved.cacheControl);
res.end(shell);
return;
}
}

res.statusCode = 404;
applyHeaders(res, PAGE_SECURITY_HEADERS);
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.setHeader('Cache-Control', 'no-store');
res.end('Not found');
}

Expand All @@ -236,7 +253,8 @@ async function handleSubscribe(req: IncomingMessage, res: ServerResponse): Promi
(req as IncomingMessage & { body?: unknown }).body = JSON.parse(raw);
} catch {
res.statusCode = 400;
res.setHeader('Content-Type', 'application/json');
applyHeaders(res, SUBSCRIBE_API_SECURITY_HEADERS);
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.end(JSON.stringify({ error: 'Invalid JSON body' }));
return;
}
Expand Down
208 changes: 208 additions & 0 deletions src/__tests__/security-headers.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
import { describe, expect, it, vi } from 'vitest';
import middleware from '../../middleware';
import vercelJson from '../../vercel.json';
import {
API_CONTENT_SECURITY_POLICY,
FEED_CONTENT_SECURITY_POLICY,
FEED_SECURITY_HEADERS,
FONT_ASSET_HEADERS,
IMMUTABLE_ASSET_HEADERS,
PAGE_CONTENT_SECURITY_POLICY,
PAGE_SECURITY_HEADERS,
STATIC_MEDIA_HEADERS,
resolveStaticRouteHeaders,
} from '../utils/security-headers';

interface VercelHeaderEntry {
key: string;
value: string;
}

interface VercelHeaderRule {
source: string;
headers: VercelHeaderEntry[];
}

interface VercelConfig {
headers?: VercelHeaderRule[];
rewrites?: Array<{ source: string; destination: string }>;
}

const vercelConfig = vercelJson as VercelConfig;

function headersForSource(source: string): Record<string, string> {
const rule = vercelConfig.headers?.find((entry) => entry.source === source);
expect(rule, `Missing vercel.json header rule for ${source}`).toBeDefined();
return Object.fromEntries(rule!.headers.map(({ key, value }) => [key, value]));
}

function parseCsp(csp: string): Record<string, string[]> {
return Object.fromEntries(
csp
.split(';')
.map((part) => part.trim())
.filter(Boolean)
.map((part) => {
const [directive, ...tokens] = part.split(/\s+/);
return [directive!, tokens];
}),
);
}

describe('vercel.json production security headers', () => {
it('defines global security headers on /(.*) matching PAGE_SECURITY_HEADERS', () => {
const globalHeaders = headersForSource('/(.*)');
expect(globalHeaders).toEqual(PAGE_SECURITY_HEADERS);
expect(globalHeaders['Strict-Transport-Security']).toBe(
'max-age=63072000; includeSubDomains; preload',
);
expect(globalHeaders['X-Content-Type-Options']).toBe('nosniff');
expect(globalHeaders['X-Frame-Options']).toBe('DENY');
expect(globalHeaders['Referrer-Policy']).toBe('strict-origin-when-cross-origin');
expect(globalHeaders['Cross-Origin-Opener-Policy']).toBe('same-origin');
expect(globalHeaders['Permissions-Policy']).toContain('camera=()');
});

it('defines route-appropriate headers for feeds, sitemaps, assets, and API routes', () => {
expect(headersForSource('/assets/(.*)')).toEqual({
'Cache-Control': IMMUTABLE_ASSET_HEADERS['Cache-Control']!,
});

expect(headersForSource('/fonts/(.*)')).toEqual({
'Cache-Control': FONT_ASSET_HEADERS['Cache-Control']!,
'Access-Control-Allow-Origin': '*',
});

for (const mediaSource of ['/og/(.*)', '/press-kit/(.*)', '/press-kit.zip']) {
expect(headersForSource(mediaSource)).toEqual({
'Cache-Control': STATIC_MEDIA_HEADERS['Cache-Control']!,
});
}

for (const feedSource of ['/feed.xml', '/feed/tag/(.*)']) {
expect(headersForSource(feedSource)).toEqual({
'Content-Type': 'application/rss+xml; charset=utf-8',
'Cache-Control': FEED_SECURITY_HEADERS['Cache-Control']!,
'Content-Security-Policy': FEED_CONTENT_SECURITY_POLICY,
});
}

expect(headersForSource('/sitemap.xml')).toEqual({
'Content-Type': 'application/xml; charset=utf-8',
'Cache-Control': FEED_SECURITY_HEADERS['Cache-Control']!,
'Content-Security-Policy': FEED_CONTENT_SECURITY_POLICY,
});

expect(headersForSource('/api/(.*)')).toEqual({
'Content-Security-Policy': API_CONTENT_SECURITY_POLICY,
});

expect(headersForSource('/api/subscribe')).toEqual({
'Cache-Control': 'no-store',
'Referrer-Policy': 'no-referrer',
});

expect(headersForSource('/api/og')).toEqual({
'Cache-Control': 'public, max-age=31536000, immutable',
});
});
});

describe('Content-Security-Policy compatibility', () => {
const directives = parseCsp(PAGE_CONTENT_SECURITY_POLICY);

it('allows self-hosted fonts and data: font URIs', () => {
expect(directives['font-src']).toEqual(expect.arrayContaining(["'self'", 'data:']));
});

it('allows Plausible analytics script and event beacon endpoints', () => {
expect(directives['script-src']).toEqual(
expect.arrayContaining(["'self'", "'unsafe-inline'", 'https://plausible.io']),
);
expect(directives['connect-src']).toEqual(expect.arrayContaining(['https://plausible.io']));
});

it('allows Soroban/Horizon RPC and Wraith status endpoints used by interactive tools', () => {
expect(directives['connect-src']).toEqual(
expect.arrayContaining([
"'self'",
'https://soroban-testnet.stellar.org',
'https://soroban-rpc.stellar.org',
'https://horizon-testnet.stellar.org',
'https://horizon.stellar.org',
'https://status.usewraith.xyz',
]),
);
});

it('stays compatible with inline critical CSS, bootstrap scripts, and generated JSON-LD blocks', () => {
expect(directives['style-src']).toEqual(expect.arrayContaining(["'self'", "'unsafe-inline'"]));
expect(directives['script-src']).toEqual(expect.arrayContaining(["'self'", "'unsafe-inline'"]));
// Ensure CSP does not contain a sha256-* or nonce-* token in script-src or
// style-src that would cause browsers to ignore 'unsafe-inline' for static HTML.
for (const token of [...(directives['script-src'] ?? []), ...(directives['style-src'] ?? [])]) {
expect(token).not.toMatch(/^'(sha256|sha384|sha512|nonce)-/);
}
});

it('hardens framing, object embedding, base-uri, and form-action', () => {
expect(directives['frame-ancestors']).toEqual(["'none'"]);
expect(directives['object-src']).toEqual(["'none'"]);
expect(directives['base-uri']).toEqual(["'self'"]);
expect(directives['form-action']).toEqual(["'self'"]);
});
});

describe('resolveStaticRouteHeaders', () => {
it('resolves route-appropriate headers for pages, feeds, fonts, bundles, and media', () => {
const page = resolveStaticRouteHeaders('/stellar', '.html');
expect(page.contentType).toBe('text/html; charset=utf-8');
expect(page.cacheControl).toBe('no-store');
expect(page.headers['Content-Security-Policy']).toBe(PAGE_CONTENT_SECURITY_POLICY);
expect(page.headers['X-Content-Type-Options']).toBe('nosniff');

const rss = resolveStaticRouteHeaders('/feed.xml', '.xml');
expect(rss.contentType).toBe('application/rss+xml; charset=utf-8');
expect(rss.headers['Content-Security-Policy']).toBe(FEED_CONTENT_SECURITY_POLICY);

const tagRss = resolveStaticRouteHeaders('/feed/tag/wave-7.xml', '.xml');
expect(tagRss.contentType).toBe('application/rss+xml; charset=utf-8');

const sitemap = resolveStaticRouteHeaders('/sitemap.xml', '.xml');
expect(sitemap.contentType).toBe('application/xml; charset=utf-8');

const font = resolveStaticRouteHeaders('/fonts/space-grotesk-700-normal.woff2', '.woff2');
expect(font.cacheControl).toBe('public, max-age=31536000, immutable');
expect(font.headers['Access-Control-Allow-Origin']).toBe('*');

const bundle = resolveStaticRouteHeaders('/assets/index-abc123.js', '.js');
expect(bundle.cacheControl).toBe('public, max-age=31536000, immutable');

const ogImage = resolveStaticRouteHeaders('/og/home.png', '.png');
expect(ogImage.cacheControl).toBe('public, max-age=86400, stale-while-revalidate=604800');
});
});

describe('edge middleware security headers', () => {
it('attaches PAGE_SECURITY_HEADERS on bot responses from middleware.ts', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({
text: () => Promise.resolve('<html lang="en"><head><title>Default</title></head></html>'),
}),
);

const response = await middleware(
new Request('https://usewraith.xyz/stellar', {
headers: { 'user-agent': 'TwitterBot/1.0' },
}),
);

expect(response).toBeDefined();
for (const [key, value] of Object.entries(PAGE_SECURITY_HEADERS)) {
expect(response!.headers.get(key)).toBe(value);
}

vi.unstubAllGlobals();
});
});
11 changes: 10 additions & 1 deletion src/api/og.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { ImageResponse } from '@vercel/og';
import { OG_API_SECURITY_HEADERS } from '../utils/security-headers';

export const config = {
runtime: 'edge',
Expand Down Expand Up @@ -66,6 +67,7 @@ export default async function handler(req: Request) {
{
width: 1200,
height: 630,
headers: OG_API_SECURITY_HEADERS,
fonts: [
{
name: 'Inter',
Expand All @@ -78,6 +80,13 @@ export default async function handler(req: Request) {
);
} catch (e: any) {
console.error(`${e.message}`);
return new Response(`Failed to generate the image`, { status: 500 });
return new Response(`Failed to generate the image`, {
status: 500,
headers: {
...OG_API_SECURITY_HEADERS,
'Content-Type': 'text/plain; charset=utf-8',
'Cache-Control': 'no-store',
},
});
}
}
Loading