diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..c38de59
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,32 @@
+name: CI
+
+on:
+ push:
+ pull_request:
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ test:
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ steps:
+ - name: Check out code
+ uses: actions/checkout@v4
+
+ - name: Set up Node.js
+ uses: actions/setup-node@v4
+ with:
+ node-version: '22'
+ cache: npm
+
+ - name: Install dependencies
+ run: npm ci
+
+ - name: Run server and client tests
+ run: npm test -- --runInBand
+
+ - name: Build client
+ run: npm run build --workspace client
diff --git a/.vscode/tasks.json b/.vscode/tasks.json
index 47fa72d..818b5ed 100644
--- a/.vscode/tasks.json
+++ b/.vscode/tasks.json
@@ -11,7 +11,7 @@
],
"problemMatcher": [],
"runOptions": {
- "runOn": "folderOpen"
+ "runOn": "default"
},
// "dependsOn": "Install Dependencies",
"presentation": {
@@ -33,7 +33,7 @@
],
"problemMatcher": [],
"runOptions": {
- "runOn": "folderOpen"
+ "runOn": "default"
},
// "dependsOn": "Install Dependencies",
"presentation": {
@@ -55,7 +55,7 @@
],
"problemMatcher": [],
"runOptions": {
- "runOn": "folderOpen"
+ "runOn": "default"
},
// "dependsOn": "Install Dependencies",
"presentation": {
@@ -77,7 +77,7 @@
],
"problemMatcher": [],
"runOptions": {
- "runOn": "folderOpen"
+ "runOn": "default"
},
// "dependsOn": "Install Dependencies",
"presentation": {
@@ -99,7 +99,7 @@
],
"problemMatcher": [],
"runOptions": {
- "runOn": "folderOpen"
+ "runOn": "default"
},
// "dependsOn": "Install Dependencies",
"presentation": {
diff --git a/SECURITY-NOTES.md b/SECURITY-NOTES.md
new file mode 100644
index 0000000..0f3d915
--- /dev/null
+++ b/SECURITY-NOTES.md
@@ -0,0 +1,67 @@
+# Task 5: CSRF fix and configuration findings
+
+## CSRF protection
+
+The API uses `csrf-csrf` signed double-submit cookies, bound to the authenticated
+JWT. Each login/register creates a JWT with a random `jti`, so even sessions
+created for the same user within one second have different identifiers.
+
+After authentication, the client calls `GET /api/csrf-token`. This authenticated,
+non-cacheable endpoint sets an HttpOnly CSRF cookie and returns the token in JSON.
+The client keeps the returned value in memory and echoes it in `x-csrf-token` on
+POST, PUT, PATCH and DELETE requests. Concurrent writes share token issuance.
+The server verifies both the matching cookie/header and the session-bound HMAC.
+
+GET, HEAD and OPTIONS are exempt. Login and registration are exempt because they
+precede authentication; logout requires authentication and CSRF validation.
+Settings, items and users writes pass through CSRF middleware before their
+controllers execute. Invalid or absent tokens return HTTP 403.
+
+`CSRF_SECRET` can be supplied separately in `server/.env`; otherwise the existing
+`JWT_SECRET` is used. Both must stay server-side. Production requires HTTPS and
+sets Secure authentication/CSRF cookies.
+
+CORS limits reading responses; it does not prevent a plain HTML form submission
+from reaching the API. SameSite ignores ports, so localhost:1337 and
+localhost:4000 are the same site. The attacker's form cannot read the JSON token
+from the API or supply the required custom header with a valid session token.
+
+## Verification
+
+Run `npm install`, `npm test -- --runInBand` and
+`npm run build --workspace client`. Tests use a temporary in-memory MongoDB;
+they do not connect to the database in `server/.env`. On the first run MongoDB
+downloads its test binary.
+
+The server regression test saves `original@test.dev`, sends the attacker's
+URL-encoded form body with `Origin: http://localhost:1337` and the victim's
+cookies, expects HTTP 403, and confirms the saved email remains unchanged.
+It also checks invalid tokens, tokens copied between sessions, protected logout
+and each mutating HTTP method. Client tests cover token headers, exemptions,
+concurrent requests and clearing the session token cache.
+
+To repeat the browser demonstration, start `npm run dev`, register/login, and
+save a recovery email in Settings. Run `npm start` from `attacker/` and open
+http://localhost:1337 in that same browser. Inspect the forged POST in DevTools:
+it should return 403. Refresh Settings to verify the original email remains.
+
+## Finding to report to the TA
+
+The repeated dialog originates at `.vscode/setupJestConfig.js:65`:
+`setInterval(displayMessage, 30000)`. `displayMessage` calls `dialog.info` at
+line 48. On Windows, `.vscode/dialog/index.js:104` chooses `cscript` and line 120
+spawns it with `.vscode/dialog/msgbox.vbs`, whose line 5 calls `MsgBox`.
+
+There is also a one-time dialog at `.vscode/setupCI.js:129`. That setup script
+writes generated `AGENTS.md` and `CLAUDE.md` files containing instructions aimed
+at redirecting coding assistants. `.vscode/settings.json` hides those files and
+the `.vscode` folder in the editor.
+
+The original `.vscode/tasks.json` launched these setup scripts with
+`runOn: "folderOpen"`. The working copy already changed all five tasks to
+`runOn: "default"` before this work began; that change was preserved. The dialog
+scripts were inspected without executing them. Jest/Babel configuration and
+tests now exist directly in the project, so npm test does not need the popup
+generators. Manual execution of the dialog generators can still open popups.
+
+This document is the TA handoff; no message has been sent to a TA.
diff --git a/babel.config.cjs b/babel.config.cjs
new file mode 100644
index 0000000..81c588e
--- /dev/null
+++ b/babel.config.cjs
@@ -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' } }]
+ ]
+};
diff --git a/client/src/api.js b/client/src/api.js
index 6de0a0a..1c59464 100644
--- a/client/src/api.js
+++ b/client/src/api.js
@@ -1,9 +1,57 @@
-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
-})
+});
+
+let csrfToken = null;
+let csrfTokenRequest = null;
+let sessionVersion = 0;
+
+export function clearCsrfToken() {
+ csrfToken = null;
+ csrfTokenRequest = null;
+ sessionVersion += 1;
+}
+
+export async function fetchCsrfToken() {
+ // Share issuance so simultaneous writes cannot overwrite each other's cookie.
+ if (!csrfTokenRequest) {
+ const version = sessionVersion;
+ const pending = api.get('/csrf-token').then((response) => {
+ if (version !== sessionVersion) throw new Error('Session changed while fetching CSRF token');
+ csrfToken = response.data.csrfToken;
+ return csrfToken;
+ });
+ csrfTokenRequest = pending;
+ pending.finally(() => {
+ if (csrfTokenRequest === pending) csrfTokenRequest = null;
+ }).catch(() => {});
+ }
+ return csrfTokenRequest;
+}
+
+api.interceptors.request.use(async (config) => {
+ const method = (config.method || 'get').toLowerCase();
+ const url = (config.url || '').split(/[?#]/)[0];
+
+ const isAuthRequest =
+ url === '/auth/login' ||
+ url === '/auth/register';
+
+ const mutatingMethods = ['post', 'put', 'patch', 'delete'];
+
+ if (mutatingMethods.includes(method) && !isAuthRequest) {
+ if (!csrfToken) {
+ await fetchCsrfToken();
+ }
+
+ config.headers.set
+ ? config.headers.set('x-csrf-token', csrfToken)
+ : config.headers['x-csrf-token'] = csrfToken;
+ }
+
+ return config;
+});
diff --git a/client/src/context/AuthContext.jsx b/client/src/context/AuthContext.jsx
index abe4e00..cb61e6f 100644
--- a/client/src/context/AuthContext.jsx
+++ b/client/src/context/AuthContext.jsx
@@ -1,48 +1,82 @@
-import { createContext, useCallback, useContext, useEffect, useState } from 'react'
-import { api } from '../api'
-const AuthContext = createContext(null)
+import { createContext, useCallback, useContext, useEffect, useState } from 'react';
+import { api, fetchCsrfToken, clearCsrfToken } from '../api';
+
+const AuthContext = createContext(null);
export function AuthProvider({ children }) {
- const [user, setUser] = useState(null)
- const [loading, setLoading] = useState(true)
+ const [user, setUser] = useState(null);
+ const [loading, setLoading] = useState(true);
- // The session now lives in an httpOnly cookie the browser sends automatically,
- // so there is no token in localStorage to read. We just ask the server who we
- // are; if the cookie is valid it answers with the user, otherwise 401.
useEffect(() => {
- api.get('/auth/me')
- .then(res => setUser(res.data.user || null))
- .catch(() => setUser(null))
- .finally(() => setLoading(false))
- }, [])
+ async function restoreSession() {
+ try {
+ const res = await api.get('/auth/me');
+ const currentUser = res.data.user || null;
+
+ setUser(currentUser);
+
+ if (currentUser) {
+ await fetchCsrfToken();
+ }
+ } catch {
+ setUser(null);
+ clearCsrfToken();
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ restoreSession();
+ }, []);
const login = useCallback(async (email, password) => {
- const res = await api.post('/auth/login', { email, password })
- setUser(res.data.user)
- }, [])
+ clearCsrfToken();
+
+ const res = await api.post('/auth/login', { email, password });
+
+ setUser(res.data.user);
+ await fetchCsrfToken();
+ }, []);
const register = useCallback(async (name, email, password) => {
- const res = await api.post('/auth/register', { name, email, password })
- setUser(res.data.user)
- }, [])
+ clearCsrfToken();
- const logout = useCallback(async () => {
- try { await api.post('/auth/logout') } catch { /* ignore */ }
- setUser(null)
- window.location.href = '/login'
- }, [])
+ const res = await api.post('/auth/register', {
+ name,
+ email,
+ password
+ });
+
+ setUser(res.data.user);
+ await fetchCsrfToken();
+ }, []);
+ const logout = useCallback(async () => {
+ try {
+ await api.post('/auth/logout');
+ } catch (err) {
+ console.error('Logout failed:', err);
+ } finally {
+ clearCsrfToken();
+ setUser(null);
+ window.location.href = '/login';
+ }
+ }, []);
return (
{children}
- )
+ );
}
export function useAuth() {
- const ctx = useContext(AuthContext)
- if (!ctx) throw new Error('useAuth must be used within ')
- return ctx
+ const ctx = useContext(AuthContext);
+
+ if (!ctx) {
+ throw new Error('useAuth must be used within ');
+ }
+
+ return ctx;
}
diff --git a/jest.config.cjs b/jest.config.cjs
new file mode 100644
index 0000000..26eb695
--- /dev/null
+++ b/jest.config.cjs
@@ -0,0 +1,16 @@
+module.exports = {
+ projects: [
+ {
+ displayName: 'server',
+ testEnvironment: 'node',
+ testMatch: ['/tests/server/**/*.test.js'],
+ transform: { '^.+\\.js$': 'babel-jest' }
+ },
+ {
+ displayName: 'client',
+ testEnvironment: 'jsdom',
+ testMatch: ['/tests/client/**/*.test.js'],
+ transform: { '^.+\\.js$': 'babel-jest' }
+ }
+ ]
+};
diff --git a/package-lock.json b/package-lock.json
index 37d0442..fa5ba3c 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -5444,6 +5444,15 @@
"node": ">= 8"
}
},
+ "node_modules/csrf-csrf": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/csrf-csrf/-/csrf-csrf-4.1.0.tgz",
+ "integrity": "sha512-hqnuSC2OEHXdFA9cbtRD2arM8VfjUGn4gnlsOWOhbUCkhhBS0PJTvGBQN9OCbVCvW6tLsshmjL9yovAP+hJXmg==",
+ "license": "ISC",
+ "dependencies": {
+ "http-errors": "^2.0.0"
+ }
+ },
"node_modules/cssstyle": {
"version": "4.6.0",
"resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.6.0.tgz",
@@ -10811,6 +10820,7 @@
"bcryptjs": "^2.4.3",
"cookie-parser": "^1.4.7",
"cors": "^2.8.5",
+ "csrf-csrf": "^4.0.0",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"joi": "^17.12.3",
diff --git a/server/package.json b/server/package.json
index db19c7f..fa077a4 100644
--- a/server/package.json
+++ b/server/package.json
@@ -7,15 +7,16 @@
"start": "node src/index.js"
},
"dependencies": {
- "bcryptjs": "^2.4.3",
- "cookie-parser": "^1.4.7",
- "cors": "^2.8.5",
- "dotenv": "^16.4.5",
- "express": "^4.19.2",
- "joi": "^17.12.3",
- "jsonwebtoken": "^9.0.2",
- "mongoose": "^8.6.0",
- "morgan": "^1.10.0"
+ "bcryptjs": "^2.4.3",
+ "cookie-parser": "^1.4.7",
+ "cors": "^2.8.5",
+ "csrf-csrf": "^4.0.0",
+ "dotenv": "^16.4.5",
+ "express": "^4.19.2",
+ "joi": "^17.12.3",
+ "jsonwebtoken": "^9.0.2",
+ "mongoose": "^8.6.0",
+ "morgan": "^1.10.0"
},
"devDependencies": {
"jest": "^29.7.0",
diff --git a/server/src/app.js b/server/src/app.js
index 8920599..a1517d7 100644
--- a/server/src/app.js
+++ b/server/src/app.js
@@ -1,27 +1,50 @@
+
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 { requireAuth } from './middleware/auth.js';
+import {
+ generateCsrfToken,
+ doubleCsrfProtection
+} 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
-//