
Implementing Content Security Policy in Tempo Labs: A Comprehensive Guide
Implementing Content Security Policy in Tempo Labs Applications
Content Security Policy (CSP) is one of the most powerful security features available to web developers, yet it remains underutilized in many vibe coding applications. In Tempo Labs environments, where rapid development is prioritized, security measures like CSP are often overlooked or improperly implemented. This blog post explores how to effectively implement Content Security Policy in Tempo Labs applications to protect against cross-site scripting (XSS) attacks and other code injection vulnerabilities.
Understanding Content Security Policy
Content Security Policy is a security standard that helps prevent cross-site scripting (XSS) attacks and other code injection attacks by allowing you to specify which content sources are considered trusted. When properly implemented, CSP can significantly reduce the risk of XSS vulnerabilities by restricting the types of content that browsers will execute or render.
In Tempo Labs applications, where frontend components are often generated based on natural language prompts, the risk of XSS vulnerabilities is particularly high. According to recent studies, applications built with AI coding assistants are 42% more likely to contain XSS vulnerabilities compared to traditionally coded applications. This makes implementing CSP even more critical for Tempo Labs projects.
Common CSP Vulnerabilities in Tempo Labs Applications
Before diving into implementation solutions, let’s examine the most common CSP-related vulnerabilities in Tempo Labs applications:
1. Missing CSP Headers
The most basic vulnerability is simply not implementing CSP at all. By default, Tempo Labs doesn’t automatically add CSP headers to your applications, leaving them vulnerable to various injection attacks.
// Example of a Tempo Labs application without CSP
app.get('/', (req, res) => {
res.render('index', {
title: 'Welcome',
user: req.user
});
});
Without CSP headers, browsers will execute any script that makes it into your page, whether it’s from your domain or injected by an attacker.
2. Overly Permissive CSP Policies
Another common issue is implementing CSP with overly permissive directives, such as using unsafe-inline
or wildcard sources (*
), which effectively nullify the protection CSP is meant to provide.
// Example of a Tempo Labs application with overly permissive CSP
app.use((req, res, next) => {
res.setHeader(
'Content-Security-Policy',
"default-src 'self' * 'unsafe-inline' 'unsafe-eval'"
);
next();
});
This policy allows inline scripts, eval functions, and content from any domain, defeating the purpose of CSP.
3. Incomplete CSP Implementation
Partial CSP implementation is also common, where developers might secure script sources but forget about other resource types like styles, fonts, or frames.
// Example of incomplete CSP in Tempo Labs
app.use((req, res, next) => {
res.setHeader(
'Content-Security-Policy',
"script-src 'self'"
);
next();
});
This policy only restricts script sources but leaves other resource types unrestricted.
Implementing Robust CSP in Tempo Labs
Now, let’s look at how to properly implement CSP in Tempo Labs applications with specific prompts you can use to generate secure code.
Prompt 1: Implementing Basic CSP Headers
When asking Tempo Labs to generate code for your application’s security configuration, use this prompt to ensure proper CSP implementation:
Create a middleware function for my Tempo Labs Express application that implements a comprehensive Content Security Policy. The policy should:
1. Restrict scripts to only load from my domain and trusted CDNs (specifically cdnjs.cloudflare.com)
2. Prevent inline scripts and eval() from executing
3. Restrict styles to only load from my domain
4. Restrict images, fonts, and other media to only load from my domain
5. Prevent my site from being framed by other sites
6. Enable reporting of CSP violations to a local endpoint
This prompt will generate code similar to:
// CSP middleware for Tempo Labs application
const cspMiddleware = (req, res, next) => {
res.setHeader(
'Content-Security-Policy',
"default-src 'none'; " +
"script-src 'self' https://cdnjs.cloudflare.com; " +
"style-src 'self'; " +
"img-src 'self'; " +
"font-src 'self'; " +
"connect-src 'self'; " +
"media-src 'self'; " +
"frame-src 'self'; " +
"frame-ancestors 'none'; " +
"form-action 'self'; " +
"base-uri 'self'; " +
"report-uri /csp-violation-report"
);
next();
};
// CSP violation reporting endpoint
app.post('/csp-violation-report', (req, res) => {
console.log('CSP Violation:', req.body);
res.status(204).end();
});
// Apply middleware
app.use(cspMiddleware);
This implementation provides a strong baseline security policy that restricts all resource types to your domain (with the exception of scripts from a trusted CDN), prevents framing, and sets up violation reporting.
Prompt 2: Implementing Nonce-Based CSP for Inline Scripts
If your Tempo Labs application requires inline scripts (which is common in many web applications), you can use nonces to allow specific inline scripts while maintaining security:
Create a middleware function for my Tempo Labs Express application that implements a nonce-based Content Security Policy. The middleware should:
1. Generate a unique cryptographic nonce for each request
2. Add the nonce to the CSP header for script-src and style-src directives
3. Make the nonce available to templates for use in inline scripts and styles
4. Prevent any inline scripts or styles without the correct nonce
5. Block eval() and other unsafe JavaScript features
6. Implement strict CSP for all other resource types
This prompt will generate code similar to:
const crypto = require('crypto');
// Nonce-based CSP middleware for Tempo Labs
const nonceBasedCspMiddleware = (req, res, next) => {
// Generate a unique nonce for this request
const nonce = crypto.randomBytes(16).toString('base64');
// Set CSP header with nonce
res.setHeader(
'Content-Security-Policy',
`default-src 'none'; ` +
`script-src 'self' 'nonce-${nonce}'; ` +
`style-src 'self' 'nonce-${nonce}'; ` +
`img-src 'self'; ` +
`font-src 'self'; ` +
`connect-src 'self'; ` +
`media-src 'self'; ` +
`frame-ancestors 'none'; ` +
`form-action 'self'; ` +
`base-uri 'self'`
);
// Make nonce available to templates
res.locals.cspNonce = nonce;
next();
};
// Apply middleware
app.use(nonceBasedCspMiddleware);
// Example route with template that uses the nonce
app.get('/', (req, res) => {
res.render('index', {
title: 'Secure Page',
nonce: res.locals.cspNonce
});
});
In your templates, you would then use the nonce like this:
<!-- In your EJS, Handlebars, or other template -->
<script nonce="<%= nonce %>">
// Your inline JavaScript here
document.getElementById('greeting').textContent = 'Hello, world!';
</script>
This approach allows you to use inline scripts when necessary while still maintaining strong CSP protection.
Prompt 3: Implementing CSP with Report-Only Mode for Testing
When first implementing CSP in an existing Tempo Labs application, it’s often best to start in report-only mode to avoid breaking functionality:
Create a middleware function for my Tempo Labs Express application that implements Content Security Policy in Report-Only mode. The middleware should:
1. Set up a strict CSP policy that doesn't actually block content but reports violations
2. Log all violations to a local endpoint and console
3. Include all major CSP directives with reasonable defaults
4. Allow for easy transition to enforcement mode once testing is complete
This prompt will generate code similar to:
// CSP Report-Only middleware for Tempo Labs
const cspReportOnlyMiddleware = (req, res, next) => {
res.setHeader(
'Content-Security-Policy-Report-Only',
"default-src 'none'; " +
"script-src 'self'; " +
"style-src 'self'; " +
"img-src 'self'; " +
"font-src 'self'; " +
"connect-src 'self'; " +
"media-src 'self'; " +
"frame-ancestors 'none'; " +
"form-action 'self'; " +
"base-uri 'self'; " +
"report-uri /csp-violation-report"
);
next();
};
// CSP violation reporting endpoint
app.post('/csp-violation-report', (req, res) => {
console.log('CSP Violation (Report-Only):', req.body);
// You could also store these in a database for analysis
res.status(204).end();
});
// Apply middleware
app.use(cspReportOnlyMiddleware);
// Function to switch to enforcement mode when ready
const enableCspEnforcement = () => {
app.use((req, res, next) => {
// Get the current report-only policy
const reportOnlyPolicy = res.getHeader('Content-Security-Policy-Report-Only');
// Set it as an enforced policy
if (reportOnlyPolicy) {
res.setHeader('Content-Security-Policy', reportOnlyPolicy);
res.removeHeader('Content-Security-Policy-Report-Only');
}
next();
});
};
// Call this when ready to enforce
// enableCspEnforcement();
This implementation allows you to monitor CSP violations without breaking your application, making it easier to identify and fix issues before enforcing the policy.
Best Practices for CSP in Tempo Labs Applications
To ensure your Content Security Policy provides maximum protection in Tempo Labs applications, follow these best practices:
1. Avoid Unsafe Directives
Avoid using unsafe-inline
and unsafe-eval
in your CSP. These directives significantly weaken your security posture. Instead, use nonces or hashes for inline scripts and refactor code to avoid eval().
2. Use Specific Sources
Be as specific as possible with your source directives. Instead of allowing all subdomains with wildcards, list exactly which domains are needed:
// Good practice
"script-src 'self' https://specific-cdn.example.com";
// Avoid this
"script-src 'self' https://*.example.com";
3. Implement Subresource Integrity
For external resources, combine CSP with Subresource Integrity (SRI) to ensure the content hasn’t been tampered with:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ=="
crossorigin="anonymous"></script>
4. Use report-uri or report-to
Always include a reporting mechanism to monitor for CSP violations:
"report-uri /csp-violation-report"
5. Consider Using Helmet.js
For Tempo Labs applications built with Express, consider using the Helmet.js library, which simplifies CSP implementation:
const helmet = require('helmet');
app.use(
helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'none'"],
scriptSrc: ["'self'", "https://cdnjs.cloudflare.com"],
styleSrc: ["'self'"],
imgSrc: ["'self'"],
connectSrc: ["'self'"],
fontSrc: ["'self'"],
objectSrc: ["'none'"],
mediaSrc: ["'self'"],
frameSrc: ["'self'"],
frameAncestors: ["'none'"],
formAction: ["'self'"],
baseUri: ["'self'"],
reportUri: '/csp-violation-report',
},
})
);
Testing Your CSP Implementation
After implementing CSP in your Tempo Labs application, it’s crucial to test it thoroughly. Here are some methods:
1. Use Browser Developer Tools
Modern browsers will report CSP violations in the console, making it easy to identify issues during development.
2. Use the CSP Evaluator
Google’s CSP Evaluator is a valuable tool for analyzing your CSP policy for weaknesses.
3. Use Automated Security Testing
Incorporate CSP testing into your CI/CD pipeline using tools like OWASP ZAP or Burp Suite to automatically detect CSP issues.
Conclusion
Implementing Content Security Policy in Tempo Labs applications is a critical step in protecting against XSS and other injection attacks. By using the prompts provided in this blog post, you can generate secure CSP implementations that provide robust protection while maintaining the functionality of your applications.
Remember that CSP is just one layer in a comprehensive security strategy. It should be combined with other security measures such as input validation, output encoding, and regular security testing to provide defense in depth for your Tempo Labs applications.
By taking the time to properly implement CSP, you can significantly reduce the risk of security vulnerabilities in your vibe-coded applications, ensuring that the speed and convenience of Tempo Labs doesn’t come at the expense of security.