Surgically add esm.sh to existing CSP of index.html

This commit is contained in:
Alex Gleason committed 2025-10-02 15:43:27 -05:00
1 parent c72170f19c
commit 225c90f556
4 files changed
+306 -17

No files matched your search

+50 -14
View File
@@ -11,12 +11,26 @@ vi.mock('../esbuild', () => ({
{
path: '/stdin.js',
contents: new Uint8Array([1, 2, 3]),
text: '',
hash: 'abc123',
},
{
path: '/stdin.css',
contents: new Uint8Array([4, 5, 6]),
text: 'body { margin: 0; }',
hash: 'def456',
},
],
metafile: {
outputs: {
'stdin.js': {
entryPoint: 'fs:/test/project/src/main.tsx',
},
'stdin.css': {
entryPoint: undefined,
},
},
},
})),
})),
}));
@@ -52,9 +66,25 @@ describe('buildProject', () => {
documentElement: {
outerHTML: '<html><head></head><body><script src="/src/main.tsx"></script></body></html>',
},
querySelector: vi.fn(() => ({
setAttribute: vi.fn(),
})),
querySelector: vi.fn((selector: string) => {
if (selector === 'meta[http-equiv="content-security-policy"]') {
// Return null for CSP meta tag (no CSP present in test)
return null;
}
return {
setAttribute: vi.fn(),
getAttribute: vi.fn(),
};
}),
scripts: [
{
getAttribute: vi.fn((attr: string) => {
if (attr === 'src') return '/src/main.tsx';
return null;
}),
type: 'module',
},
],
head: {
appendChild: vi.fn(),
},
@@ -133,11 +163,13 @@ describe('buildProject', () => {
domParser: mockDOMParser,
});
// Should include built files
expect(result.files['main.js']).toEqual(new Uint8Array([1, 2, 3]));
expect(result.files['main.css']).toEqual(new Uint8Array([4, 5, 6]));
// Should include built files with hashed names
expect(result.files['stdin-abc123.js']).toEqual(new Uint8Array([1, 2, 3]));
expect(result.files['index.html']).toBeDefined();
// CSS should be embedded in HTML, not as separate file
expect(Object.keys(result.files)).not.toContain('stdin-def456.css');
// Public files should be copied to filesystem, not included in files object
// Verify copyFiles was called for public directory
expect(mockFS.stat).toHaveBeenCalledWith('/test/project/public');
@@ -190,11 +222,13 @@ describe('buildProject', () => {
domParser: mockDOMParser,
});
// Should still include built files
expect(result.files['main.js']).toEqual(new Uint8Array([1, 2, 3]));
expect(result.files['main.css']).toEqual(new Uint8Array([4, 5, 6]));
// Should still include built files with hashed names
expect(result.files['stdin-abc123.js']).toEqual(new Uint8Array([1, 2, 3]));
expect(result.files['index.html']).toBeDefined();
// CSS should be embedded in HTML, not as separate file
expect(Object.keys(result.files)).not.toContain('stdin-def456.css');
// Should not include any public files in bundle
expect(Object.keys(result.files)).not.toContain('favicon.ico');
@@ -246,13 +280,15 @@ describe('buildProject', () => {
domParser: mockDOMParser,
});
// Should include built files
expect(result.files['main.js']).toEqual(new Uint8Array([1, 2, 3]));
expect(result.files['main.css']).toEqual(new Uint8Array([4, 5, 6]));
// Should include built files with hashed names
expect(result.files['stdin-abc123.js']).toEqual(new Uint8Array([1, 2, 3]));
expect(result.files['index.html']).toBeDefined();
// Should have exactly 3 files (main.js, main.css, index.html)
expect(Object.keys(result.files)).toHaveLength(3);
// CSS should be embedded in HTML, not as separate file
expect(Object.keys(result.files)).not.toContain('stdin-def456.css');
// Should have exactly 2 files (stdin-abc123.js, index.html)
expect(Object.keys(result.files)).toHaveLength(2);
// Should try to copy public files but directory is empty
expect(copyFiles).toHaveBeenCalledWith(mockFS, mockFS, '/test/project/public', '/test/project/dist');
+24 -3
View File
@@ -1,6 +1,7 @@
import { join } from "path-browserify";
import { getEsbuild } from "@/lib/esbuild";
import { copyFiles } from "@/lib/copyFiles";
import { addDomainToCSP } from "@/lib/csp";
import { shakespearePlugin } from "./shakespearePlugin";
import { esmPlugin } from "./esmPlugin";
@@ -108,9 +109,15 @@ async function bundle(
}
}
// HACK: Remove existing CSP header for now.
// TODO: Parse CSP and ensure esm.sh is allowed.
doc.querySelector("meta[http-equiv=\"content-security-policy\"]")?.remove();
// Parse CSP and ensure esm.sh is allowed for necessary directives
const cspMeta = doc.querySelector("meta[http-equiv=\"content-security-policy\"]");
if (cspMeta) {
const cspContent = cspMeta.getAttribute("content");
if (cspContent) {
const updatedCSP = updateCSPForEsmSh(cspContent);
cspMeta.setAttribute("content", updatedCSP);
}
}
const updatedHtml = "<!DOCTYPE html>\n" + doc.documentElement.outerHTML;
dist["index.html"] = new TextEncoder().encode(updatedHtml);
@@ -200,4 +207,18 @@ async function fileExists(fs: JSRuntimeFS, path: string): Promise<boolean> {
} catch {
return false;
}
}
/** Updates CSP to allow esm.sh for scripts, assets, fonts, and CSS */
export function updateCSPForEsmSh(csp: string): string {
const esmShDirectives = [
'script-src', // For JavaScript modules
'img-src', // For images
'media-src', // For video/audio
'font-src', // For fonts
'style-src', // For CSS
'connect-src' // For fetch/XHR requests to esm.sh
];
return addDomainToCSP(csp, 'https://esm.sh', esmShDirectives);
}
+145
View File
@@ -0,0 +1,145 @@
import { describe, it, expect } from 'vitest';
import {
parseCSP,
stringifyCSP,
addSourceToDirective,
addDomainToCSP,
type CSPDirectives
} from './csp';
describe('parseCSP', () => {
it('should parse basic CSP with multiple directives', () => {
const csp = "default-src 'self'; script-src 'self' 'unsafe-inline'; img-src *";
const result = parseCSP(csp);
expect(result).toEqual({
'default-src': ["'self'"],
'script-src': ["'self'", "'unsafe-inline'"],
'img-src': ['*']
});
});
it('should handle directives without sources', () => {
const csp = "upgrade-insecure-requests; block-all-mixed-content";
const result = parseCSP(csp);
expect(result).toEqual({
'upgrade-insecure-requests': [],
'block-all-mixed-content': []
});
});
it('should handle empty or whitespace-only CSP', () => {
expect(parseCSP('')).toEqual({});
expect(parseCSP(' ')).toEqual({});
expect(parseCSP(';;;')).toEqual({});
});
it('should handle extra whitespace and semicolons', () => {
const csp = " default-src 'self' ; script-src 'self' ; ";
const result = parseCSP(csp);
expect(result).toEqual({
'default-src': ["'self'"],
'script-src': ["'self'"]
});
});
});
describe('stringifyCSP', () => {
it('should convert directives back to CSP string', () => {
const directives: CSPDirectives = {
'default-src': ["'self'"],
'script-src': ["'self'", "'unsafe-inline'"],
'img-src': ['*']
};
const result = stringifyCSP(directives);
expect(result).toBe("default-src 'self'; script-src 'self' 'unsafe-inline'; img-src *");
});
it('should handle directives without sources', () => {
const directives: CSPDirectives = {
'upgrade-insecure-requests': [],
'default-src': ["'self'"]
};
const result = stringifyCSP(directives);
expect(result).toBe("upgrade-insecure-requests; default-src 'self'");
});
it('should handle empty directives object', () => {
expect(stringifyCSP({})).toBe('');
});
});
describe('addSourceToDirective', () => {
it('should add new source to existing sources', () => {
const sources = ["'self'", "'unsafe-inline'"];
const result = addSourceToDirective(sources, 'https://example.com');
expect(result).toEqual(["'self'", "'unsafe-inline'", 'https://example.com']);
});
it('should not duplicate existing sources', () => {
const sources = ["'self'", 'https://example.com'];
const result = addSourceToDirective(sources, 'https://example.com');
expect(result).toEqual(["'self'", 'https://example.com']);
});
it('should replace none with new source', () => {
const sources = ["'none'"];
const result = addSourceToDirective(sources, 'https://example.com');
expect(result).toEqual(['https://example.com']);
});
it('should replace none even with other sources present', () => {
const sources = ["'self'", "'none'", "'unsafe-inline'"];
const result = addSourceToDirective(sources, 'https://example.com');
expect(result).toEqual(["'self'", 'https://example.com', "'unsafe-inline'"]);
});
it('should handle empty sources array', () => {
const sources: string[] = [];
const result = addSourceToDirective(sources, 'https://example.com');
expect(result).toEqual(['https://example.com']);
});
});
describe('addDomainToCSP', () => {
it('should add domain to specified directives', () => {
const csp = "default-src 'self'; script-src 'self'; img-src 'self'";
const result = addDomainToCSP(csp, 'https://cdn.example.com', ['script-src', 'img-src']);
expect(result).toContain('script-src \'self\' https://cdn.example.com');
expect(result).toContain('img-src \'self\' https://cdn.example.com');
expect(result).toContain('default-src \'self\''); // unchanged
});
it('should not modify directives that do not exist', () => {
const csp = "default-src 'self'";
const result = addDomainToCSP(csp, 'https://cdn.example.com', ['script-src', 'img-src']);
expect(result).toBe("default-src 'self'");
});
it('should handle multiple domains being added', () => {
const csp = "script-src 'self'";
let result = addDomainToCSP(csp, 'https://cdn1.example.com', ['script-src']);
result = addDomainToCSP(result, 'https://cdn2.example.com', ['script-src']);
expect(result).toBe("script-src 'self' https://cdn1.example.com https://cdn2.example.com");
});
it('should replace none in specified directives', () => {
const csp = "default-src 'self'; script-src 'none'; img-src 'self'";
const result = addDomainToCSP(csp, 'https://cdn.example.com', ['script-src']);
expect(result).toContain('script-src https://cdn.example.com');
expect(result).toContain('img-src \'self\''); // unchanged
});
});
+87
View File
@@ -0,0 +1,87 @@
/**
* Content Security Policy (CSP) utilities for managing and updating CSP directives
*/
export interface CSPDirectives {
[directive: string]: string[];
}
/**
* Parses a CSP string into a structured format
*/
export function parseCSP(csp: string): CSPDirectives {
const directives: CSPDirectives = {};
// Split by semicolon and parse each directive
csp.split(';').forEach(directive => {
const trimmed = directive.trim();
if (!trimmed) return;
const parts = trimmed.split(/\s+/);
const directiveName = parts[0];
const sources = parts.slice(1);
directives[directiveName] = sources;
});
return directives;
}
/**
* Converts CSP directives back to a string format
*/
export function stringifyCSP(directives: CSPDirectives): string {
const directiveStrings: string[] = [];
Object.entries(directives).forEach(([directiveName, sources]) => {
if (sources.length > 0) {
directiveStrings.push(`${directiveName} ${sources.join(' ')}`);
} else {
directiveStrings.push(directiveName);
}
});
return directiveStrings.join('; ');
}
/**
* Adds a source to a CSP directive, handling special cases
*/
export function addSourceToDirective(sources: string[], newSource: string): string[] {
// Don't add if already present
if (sources.includes(newSource)) {
return sources;
}
// If 'none' is present, replace it with the new source
if (sources.includes("'none'")) {
const noneIndex = sources.indexOf("'none'");
const newSources = [...sources];
newSources[noneIndex] = newSource;
return newSources;
}
// Add to existing sources
return [...sources, newSource];
}
/**
* Updates CSP directives to allow a specific domain for multiple directive types
*/
export function addDomainToCSP(
csp: string,
domain: string,
directiveTypes: string[]
): string {
const directives = parseCSP(csp);
// Add domain to each relevant directive if it exists
directiveTypes.forEach(directiveName => {
const sources = directives[directiveName];
if (sources) {
directives[directiveName] = addSourceToDirective(sources, domain);
}
});
return stringifyCSP(directives);
}