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
32 changes: 32 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -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
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
67 changes: 67 additions & 0 deletions SECURITY-NOTES.md
Original file line number Diff line number Diff line change
@@ -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.
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' } }]
]
};
58 changes: 53 additions & 5 deletions client/src/api.js
Original file line number Diff line number Diff line change
@@ -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;
});
90 changes: 62 additions & 28 deletions client/src/context/AuthContext.jsx
Original file line number Diff line number Diff line change
@@ -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 (
<AuthContext.Provider value={{ user, loading, login, register, logout }}>
{children}
</AuthContext.Provider>
)
);
}

export function useAuth() {
const ctx = useContext(AuthContext)
if (!ctx) throw new Error('useAuth must be used within <AuthProvider>')
return ctx
const ctx = useContext(AuthContext);

if (!ctx) {
throw new Error('useAuth must be used within <AuthProvider>');
}

return ctx;
}
16 changes: 16 additions & 0 deletions jest.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
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.

19 changes: 10 additions & 9 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Loading