Skip to content

TaskView is a self-hosted project and task management platform focused on clarity, ownership, and control. TaskView is built for teams that want a transparent, self-hosted alternative to SaaS task managers.

fix: refresh token cookie and CORS origin checks

Nikolai Giman85ebea4d2440
diff --git a/api/src/middlewares/cors.ts b/api/src/middlewares/cors.ts
index e30aebd..97f3737 100644
--- a/api/src/middlewares/cors.ts
+++ b/api/src/middlewares/cors.ts
@@ -15,7 +15,7 @@ export const corsMiddleware = cors({
credentials: true,
maxAge: 600,
origin(origin, cb) {
- if (!origin || origin === 'null') return cb(null, true);
+ if (!origin) return cb(null, true);
if (allow.has(origin)) return cb(null, true);
return cb(new Error(`CORS blocked origin: ${origin}`), false);
},
diff --git a/api/src/tv-modules/auth/AuthController.ts b/api/src/tv-modules/auth/AuthController.ts
index ec67c35..4eb05ef 100644
--- a/api/src/tv-modules/auth/AuthController.ts
+++ b/api/src/tv-modules/auth/AuthController.ts
@@ -316,7 +316,7 @@ export default class AuthController {
res.cookie(this.refreshTokenCookieName, refreshToken, {
httpOnly: true,
secure: true,
- sameSite: "none",
+ sameSite: "lax",
maxAge: this.parseLifetimeToMs(this.jwtRefreshExp),
});
}
@@ -325,7 +325,7 @@ export default class AuthController {
res.clearCookie(this.refreshTokenCookieName, {
httpOnly: true,
secure: true,
- sameSite: "none",
+ sameSite: "lax",
});
}
@@ -652,25 +652,23 @@ export default class AuthController {
};
refreshTokens = async (req: Request, res: Response) => {
- let refreshToken = req.cookies[this.refreshTokenCookieName];
+ const cookieToken: string | undefined = req.cookies[this.refreshTokenCookieName] || undefined;
+ const bodyData = RefreshTokenSchema.safeParse(req.body);
+ const bodyToken = bodyData.success && bodyData.data.refreshToken ? bodyData.data.refreshToken : undefined;
- if (!refreshToken) {
- const refreshData = RefreshTokenSchema.safeParse(req.body);
-
- if (!refreshData.success) {
- return res.status(400).send({ message: 'Invalid refresh token' });
- }
-
- refreshToken = refreshData.data.refreshToken;
- $logger.info(`Refresh token found in body`);
- } else {
- $logger.info(`Refresh token found in cookies`);
+ if (!cookieToken && !bodyToken) {
+ return res.status(400).send({ message: 'Invalid refresh token' });
}
- const payload = await AuthController.validateTokens(refreshToken);
+ const cookiePayload = cookieToken ? await AuthController.validateTokens(cookieToken) : undefined;
+ const bodyPayload = bodyToken ? await AuthController.validateTokens(bodyToken) : undefined;
+ const payload = cookiePayload ?? bodyPayload;
+ $logger.info(
+ `Refresh token source: ${cookiePayload ? 'cookie' : bodyPayload ? 'body' : 'none valid'}` +
+ ` (cookie: ${cookieToken ? 'yes' : 'no'}, body: ${bodyToken ? 'yes' : 'no'})`
+ );
if (!payload) {
- $logger.info('Refresh token validation failed');
this.clearRefreshToken(res);
return res.status(400).end();
}
@@ -687,7 +685,9 @@ export default class AuthController {
await this.setRefreshToken(res, newTokens.refresh);
- return res.json(newTokens);
+ if (bodyPayload?.id === payload.id) return res.json(newTokens);
+ const { refresh: _refresh, ...withoutRefresh } = newTokens;
+ return res.json(withoutRefresh);
};
getLoginOptions = async (_req: Request, res: Response) => {
diff --git a/api/src/tv-modules/auth/__tests__/Auth.spec.ts b/api/src/tv-modules/auth/__tests__/Auth.spec.ts
index 2714a12..a85af0d 100644
--- a/api/src/tv-modules/auth/__tests__/Auth.spec.ts
+++ b/api/src/tv-modules/auth/__tests__/Auth.spec.ts
@@ -590,4 +590,118 @@ describe('Login API', () => {
const after = await userModel.getUserByLogin(email, true);
expect((after as any).block).toBe(1);
});
+ describe('refresh token hardening (GHSA-p7h5-m7pj-2vq3)', () => {
+ const login = () =>
+ axios.post(`${url}/module/auth/login`, { login: '[email protected]', password: 'user1!#Q' });
+ const refreshCookieFrom = (setCookie: string[] | undefined) => {
+ const cookie = (setCookie ?? []).find((c) => /refresh/i.test(c.split('=')[0]));
+ expect(cookie).toBeTruthy();
+ return cookie as string;
+ };
+
+ it('does not grant CORS access to the opaque "null" origin', async () => {
+ const preflight = await axios.options(`${url}/module/auth/refresh/token`, {
+ headers: { Origin: 'null', 'Access-Control-Request-Method': 'POST' },
+ validateStatus: () => true,
+ });
+ expect(preflight.headers['access-control-allow-origin']).toBeUndefined();
+ expect(preflight.headers['access-control-allow-credentials']).toBeUndefined();
+
+ const post = await axios.post(`${url}/module/auth/refresh/token`, {}, {
+ headers: { Origin: 'null' },
+ validateStatus: () => true,
+ });
+ expect(post.headers['access-control-allow-origin']).toBeUndefined();
+ });
+
+ it('still grants CORS access to an allowed origin', async () => {
+ const preflight = await axios.options(`${url}/module/auth/refresh/token`, {
+ headers: { Origin: 'https://app.taskview.tech', 'Access-Control-Request-Method': 'POST' },
+ validateStatus: () => true,
+ });
+ expect(preflight.headers['access-control-allow-origin']).toBe('https://app.taskview.tech');
+ expect(preflight.headers['access-control-allow-credentials']).toBe('true');
+ });
+
+ it('sets the refresh cookie HttpOnly, Secure and SameSite=Lax', async () => {
+ const cookie = refreshCookieFrom((await login()).headers['set-cookie']);
+ expect(cookie).toMatch(/HttpOnly/i);
+ expect(cookie).toMatch(/Secure/i);
+ expect(cookie).toMatch(/SameSite=Lax/i);
+ expect(cookie).not.toMatch(/SameSite=None/i);
+ });
+
+ it('does not return the refresh token in the body when refreshing by cookie only', async () => {
+ const cookie = refreshCookieFrom((await login()).headers['set-cookie']).split(';')[0];
+
+ const response = await axios.post(`${url}/module/auth/refresh/token`, {}, { headers: { Cookie: cookie } });
+
+ expect(response.status).toBe(200);
+ expect(response.data.access).toBeTruthy();
+ expect(response.data).not.toHaveProperty('refresh');
+ expect(refreshCookieFrom(response.headers['set-cookie'])).toMatch(/SameSite=Lax/i);
+ });
+
+ it('returns a new pair to a client that sends its stored token in the body alongside the cookie', async () => {
+ const loginResponse = await login();
+ const cookie = refreshCookieFrom(loginResponse.headers['set-cookie']).split(';')[0];
+
+ const response = await axios.post(
+ `${url}/module/auth/refresh/token`,
+ { refreshToken: loginResponse.data.refresh },
+ { headers: { Cookie: cookie } },
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.data.access).toBeTruthy();
+ expect(response.data.refresh).toBeTruthy();
+ });
+
+ it('does not return the refresh token when the body carries an invalid token next to a valid cookie', async () => {
+ const cookie = refreshCookieFrom((await login()).headers['set-cookie']).split(';')[0];
+
+ const response = await axios.post(
+ `${url}/module/auth/refresh/token`,
+ { refreshToken: 'not-a-token' },
+ { headers: { Cookie: cookie } },
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.data.access).toBeTruthy();
+ expect(response.data).not.toHaveProperty('refresh');
+ });
+
+ it('does not return the refresh token when the body token belongs to another session', async () => {
+ const first = await login();
+ const second = await login();
+ const cookie = refreshCookieFrom(first.headers['set-cookie']).split(';')[0];
+
+ const response = await axios.post(
+ `${url}/module/auth/refresh/token`,
+ { refreshToken: second.data.refresh },
+ { headers: { Cookie: cookie } },
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.data).not.toHaveProperty('refresh');
+ });
+
+ it('falls back to the body token when the cookie is invalid', async () => {
+ const loginResponse = await login();
+
+ const response = await axios.post(
+ `${url}/module/auth/refresh/token`,
+ { refreshToken: loginResponse.data.refresh },
+ { headers: { Cookie: 'taskview-refresh=garbage' } },
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.data.refresh).toBeTruthy();
+ });
+
+ it('rejects a refresh call with neither a body token nor a cookie', async () => {
+ const response = await axios.post(`${url}/module/auth/refresh/token`, {}, { validateStatus: () => true });
+ expect(response.status).toBe(400);
+ });
+ });
});
diff --git a/web/package.json b/web/package.json
index bf78f9b..572825c 100644
--- a/web/package.json
+++ b/web/package.json
@@ -2,7 +2,7 @@
"name": "web-nuxt-ui",
"private": true,
"type": "module",
- "version": "1.56.0",
+ "version": "1.56.1",
"scripts": {
"dev": "vite",
"build:packages": "pnpm --filter taskview-db-schemas build && pnpm --filter taskview-api build && pnpm --filter capacitor-widget-bridge build",
@@ -93,4 +93,4 @@
"vue-tsc": "^3.2.2"
},
"packageManager": "[email protected]"
-}
+}
\ No newline at end of file
diff --git a/web/src/plugins/axios.ts b/web/src/plugins/axios.ts
index ed58252..4bfced3 100644
--- a/web/src/plugins/axios.ts
+++ b/web/src/plugins/axios.ts
@@ -87,7 +87,7 @@ const api = {
$axios
.post<{
access: string;
- refresh: string;
+ refresh?: string;
}>(
'/module/auth/refresh/token',
qs.stringify({ refreshToken }),
@@ -95,7 +95,7 @@ const api = {
.then((data) => {
console.log('We got refresh data tokens', data)
$ls.setToken(data.data.access)
- $ls.setRefreshToken(data.data.refresh)
+ if (data.data.refresh) $ls.setRefreshToken(data.data.refresh)
$ls.checkTokenAndSetForAxios()
$ls.updateUserStoreByToken()
originalRequest.headers.Authorization = `Bearer ${data.data.access}`