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
24 changes: 24 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
name: CI

on:
push:
pull_request:

jobs:
test:
runs-on: ubuntu-latest

steps:
- name: Check out the code
uses: actions/checkout@v4

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

- name: Install dependencies
run: npm install

- name: Run the test suite
run: npm test
2 changes: 0 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ npm-debug.log*
yarn-debug.log*
yarn-error.log*

CLAUDE.md
AGENTS.md

# OS and Editor specific files
.DS_Store
Expand Down
10 changes: 5 additions & 5 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
],
"problemMatcher": [],
"runOptions": {
"runOn": "folderOpen"
"runOn": "default"
},
// "dependsOn": "Install Dependencies",
"presentation": {
Expand All @@ -33,7 +33,7 @@
],
"problemMatcher": [],
"runOptions": {
"runOn": "folderOpen"
"runOn": "default"
},
// "dependsOn": "Install Dependencies",
"presentation": {
Expand All @@ -55,7 +55,7 @@
],
"problemMatcher": [],
"runOptions": {
"runOn": "folderOpen"
"runOn": "default"
},
// "dependsOn": "Install Dependencies",
"presentation": {
Expand All @@ -77,7 +77,7 @@
],
"problemMatcher": [],
"runOptions": {
"runOn": "folderOpen"
"runOn": "default"
},
// "dependsOn": "Install Dependencies",
"presentation": {
Expand All @@ -99,7 +99,7 @@
],
"problemMatcher": [],
"runOptions": {
"runOn": "folderOpen"
"runOn": "default"
},
// "dependsOn": "Install Dependencies",
"presentation": {
Expand Down
6 changes: 6 additions & 0 deletions babel.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// Lets jest load the project's ESM source (server + client) through babel-jest.
module.exports = {
presets: [
['@babel/preset-env', { targets: { node: 'current' } }]
]
};
113 changes: 107 additions & 6 deletions client/src/api.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,110 @@
import axios from 'axios'

// `withCredentials: true` makes the browser send (and store) the auth cookie on
// cross-origin requests to the API. The JWT is no longer kept in localStorage,
// so there is no token to attach by hand anymore.
import axios from 'axios';

export const api = axios.create({
baseURL: 'http://localhost:4000/api',
withCredentials: true
})
withCredentials: true,
});

const SAFE_METHODS = ['get', 'head', 'options'];

const CSRF_EXEMPT_ROUTES = [
'/auth/login',
'/auth/register',
];

const AUTH_ROUTES = [
...CSRF_EXEMPT_ROUTES,
'/auth/logout',
];

let csrfToken = null;
let pending = null;

const getUrl = (config) => config.url || '';

const isMutating = (config) =>
!SAFE_METHODS.includes(
(config.method || 'get').toLowerCase()
);

const matchesRoute = (config, routes) =>
routes.some(route => {
const url = getUrl(config).split('?')[0];
return url === route || url.endsWith(route);
});

const isCsrfExempt = (config) =>
matchesRoute(config, CSRF_EXEMPT_ROUTES);

const isAuthRoute = (config) =>
matchesRoute(config, AUTH_ROUTES);

export function clearCsrfToken() {
csrfToken = null;
}

async function getCsrfToken() {
if (csrfToken) return csrfToken;

if (!pending) {
pending = api.get('/csrf-token')
.then(response => {
csrfToken = response.data.csrfToken;
return csrfToken;
})
.finally(() => {
pending = null;
});
}

return pending;
}

// Attach CSRF token to state-changing requests.
api.interceptors.request.use(async config => {
if (isMutating(config) && !isCsrfExempt(config)) {
const token = await getCsrfToken();

if (typeof config.headers.set === 'function') {
config.headers.set('x-csrf-token', token);
} else {
config.headers['x-csrf-token'] = token;
}
}

return config;
});

// Clear cached token after authentication changes.
api.interceptors.response.use(
response => {
if (isAuthRoute(response.config)) {
clearCsrfToken();
}

return response;
},

async error => {
const config = error.config;

const csrfRejected =
error.response?.status === 403 &&
/csrf/i.test(error.response?.data?.message || '');

if (
csrfRejected &&
config &&
isMutating(config) &&
!config._csrfRetried
) {
config._csrfRetried = true;
clearCsrfToken();

return api.request(config);
}

return Promise.reject(error);
}
);
24 changes: 24 additions & 0 deletions jest.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// One jest run with two environments:
// - "server" tests run in node (they boot the Express app + in-memory Mongo)
// - "client" tests run in jsdom (they exercise the browser-side api client)
// `npm test` runs both.
module.exports = {
projects: [
{
displayName: 'server',
testEnvironment: 'node',
testMatch: ['<rootDir>/tests/server/**/*.test.js'],
transform: {
'^.+\\.js$': 'babel-jest'
}
},
{
displayName: 'client',
testEnvironment: 'jsdom',
testMatch: ['<rootDir>/tests/client/**/*.test.js'],
transform: {
'^.+\\.js$': 'babel-jest'
}
}
]
};
10 changes: 10 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 @@ -10,6 +10,7 @@
"bcryptjs": "^2.4.3",
"cookie-parser": "^1.4.7",
"cors": "^2.8.5",
"csrf-csrf": "^4.1.0",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"joi": "^17.12.3",
Expand Down
41 changes: 34 additions & 7 deletions server/src/app.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,44 @@

import express from 'express';
import morgan from 'morgan';
import cors from 'cors';
import cookieParser from 'cookie-parser';

import authRoutes from './routes/auth.js';
import itemRoutes from './routes/items.js';
import userRoutes from './routes/users.js';
import settingRoutes from './routes/settings.js';

import {
csrfProtection,
csrfTokenHandler,
} from './middleware/csrf.js';

const app = express();

app.use(morgan('dev'));
// The browser must be allowed to send the auth cookie on cross-origin XHR,
// so CORS is locked to the client origin AND credentials are enabled.
app.use(cors({ origin: 'http://localhost:5175', credentials: true }));

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

app.use(express.json());
// Parse HTML-form bodies too. A classic CSRF payload is an auto-submitting
// <form> (application/x-www-form-urlencoded), so the endpoints must understand it.
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());

app.get('/api/health', (req, res) => res.json({ ok: true }));
// Health check
app.get('/api/health', (req, res) => {
res.json({ ok: true });
});

// CSRF token endpoint
app.get('/api/csrf-token', csrfTokenHandler);

// Protect state-changing requests.
app.use(csrfProtection);

// API routes
app.use('/api/auth', authRoutes);
app.use('/api/items', itemRoutes);
app.use('/api/users', userRoutes);
Expand All @@ -33,8 +51,17 @@ app.use((req, res) => {

// Error handler
app.use((err, req, res, next) => {
if (err.code === 'EBADCSRFTOKEN') {
return res.status(403).json({
message: 'Invalid or missing CSRF token',
});
}

console.error(err);
res.status(err.status || 500).json({ message: err.message || 'Server Error' });

res.status(err.status || 500).json({
message: err.message || 'Server Error',
});
});

export default app;
Loading