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: password recovery

Nikolai Giman791b9d1c6e55
diff --git a/api/src/App.ts b/api/src/App.ts
index 91c0232..eda1cb0 100644
--- a/api/src/App.ts
+++ b/api/src/App.ts
@@ -1,25 +1,13 @@
-import cors from 'cors';
import express, { type Request, type Response } from 'express';
import helmet from 'helmet';
import { appUserMiddleware } from './middlewares/app-user-middleware';
+import { corsMiddleware } from './middlewares/cors';
import errorHandler from './middlewares/error-handler';
import routes from './routes';
import passport, { initPassportLogin } from './tv-modules/auth/strategies/passport-login';
import cookieParser from 'cookie-parser';
import { registerAllEventHandlers, startAllWorkers } from './core/all-events';
-const allow = new Set([
- ...(process.env.CORS_REMOVE_DEFAULT_ALLOWED_ORIGINS === 'true' ? [] : [
- // default allowed origins for official TaskView apps
- "https://app.taskview.tech",
- "https://taskview.handscream.com",
- "capacitor://taskview.handscream.com",
- "capacitor://app.taskview.tech",
- "https://appleid.apple.com"
- ]),
- ...(process.env.CORS_ALLOWED_ORIGINS?.split(',') || []),
-]);
-
export default class App {
public app: express.Application;
public port: number;
@@ -52,19 +40,9 @@ export default class App {
next();
});
- this.app.use(cookieParser());
- this.app.use(appUserMiddleware);
-
- this.app.use(cors({
- credentials: true,
- origin(origin, cb) {
- if (!origin || origin === 'null') return cb(null, true);
- if (allow.has(origin)) return cb(null, true);
- return cb(new Error(`CORS blocked origin: ${origin}`), false);
- },
- }));
-
this.app.use(helmet());
+ this.app.use(corsMiddleware);
+ this.app.use(cookieParser());
this.app.use(express.json({
verify: (req: any, _res, buf) => {
// Store raw body for webhook signature verification github and gitlab integrations
@@ -74,6 +52,7 @@ export default class App {
},
}));
this.app.use(express.urlencoded({ extended: true }));
+ this.app.use(appUserMiddleware);
}
private initializeRoutes() {
diff --git a/api/src/middlewares/app-user-middleware.ts b/api/src/middlewares/app-user-middleware.ts
index f64ffef..dac7793 100644
--- a/api/src/middlewares/app-user-middleware.ts
+++ b/api/src/middlewares/app-user-middleware.ts
@@ -6,6 +6,11 @@ import { getApiTokensManager } from '../tv-modules/api-tokens/ApiTokensManager';
import { TOKEN_PREFIX } from '../tv-modules/api-tokens/types';
export const appUserMiddleware = async (req: Request, res: Response, next: NextFunction) => {
+ if (req.method === 'OPTIONS') {
+ req.appUser = new AppUser();
+ return next();
+ }
+
const token = req.headers['authorization']?.split(' ')[1];
if (token && token.startsWith(TOKEN_PREFIX)) {
diff --git a/api/src/middlewares/cors.ts b/api/src/middlewares/cors.ts
new file mode 100644
index 0000000..e30aebd
--- /dev/null
+++ b/api/src/middlewares/cors.ts
@@ -0,0 +1,22 @@
+import cors from 'cors';
+
+const allow = new Set([
+ ...(process.env.CORS_REMOVE_DEFAULT_ALLOWED_ORIGINS === 'true' ? [] : [
+ 'https://app.taskview.tech',
+ 'https://taskview.handscream.com',
+ 'capacitor://taskview.handscream.com',
+ 'capacitor://app.taskview.tech',
+ 'https://appleid.apple.com',
+ ]),
+ ...(process.env.CORS_ALLOWED_ORIGINS?.split(',') || []),
+]);
+
+export const corsMiddleware = cors({
+ credentials: true,
+ maxAge: 600,
+ origin(origin, cb) {
+ if (!origin || origin === 'null') 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/middlewares/error-handler.ts b/api/src/middlewares/error-handler.ts
index d31a5b0..963cc2a 100644
--- a/api/src/middlewares/error-handler.ts
+++ b/api/src/middlewares/error-handler.ts
@@ -1,18 +1,26 @@
import type { NextFunction, Request, Response } from 'express';
+import { corsMiddleware } from './cors';
interface CustomError extends Error {
status?: number;
}
-const errorHandler = (err: CustomError, _req: Request, res: Response, _next: NextFunction) => {
+const sendError = (err: CustomError, res: Response) => {
const statusCode = err.status || 500;
-
const isProduction = process.env.NODE_ENV === 'production';
const userMessage = isProduction ? 'Internal Server Error' : err.message || 'Something went wrong';
+ res.status(statusCode).json({ message: userMessage });
+};
- res.status(statusCode).json({
- message: userMessage,
- });
+const errorHandler = (err: CustomError, req: Request, res: Response, _next: NextFunction) => {
+ // Re-run the same cors middleware so error responses get CORS headers even when
+ // the original pass was bypassed (error thrown before it ran). Reusing the actual
+ // middleware preserves the allowlist policy — disallowed origins still get no headers.
+ if (res.getHeader('Access-Control-Allow-Origin')) {
+ sendError(err, res);
+ return;
+ }
+ corsMiddleware(req, res, () => sendError(err, res));
};
export default errorHandler;
diff --git a/api/src/tv-modules/auth/AuthController.ts b/api/src/tv-modules/auth/AuthController.ts
index 5e02972..0c34f7c 100644
--- a/api/src/tv-modules/auth/AuthController.ts
+++ b/api/src/tv-modules/auth/AuthController.ts
@@ -507,48 +507,42 @@ export default class AuthController {
return res.status(400).send();
}
- const userData = await req.appUser.authManager.repository.getUserByLogin(data.data.email, true);
+ // Always respond 200 to avoid user-enumeration. SMTP send runs in background,
+ // so the response never races the browser preflight/timeout.
+ const respond = () => res.status(200).send({ sent: true });
- if (!userData) {
- return res.status(400).send();
- }
-
- if (!this.canSendRemindEmail(userData)) {
- return res.status(400).send();
+ const userData = await req.appUser.authManager.repository.getUserByLogin(data.data.email, true);
+ if (!userData || !this.canSendRemindEmail(userData)) {
+ return respond();
}
const code = generateString(18);
const seconds = time();
const result = await req.appUser.authManager.repository.setReminderCodeAndTime(userData.email, code, seconds);
-
if (!result) {
- $logger.error(`Can not set remind_code and time for user`);
- return res.status(500).send();
+ $logger.error('Can not set remind_code and time for user');
+ return respond();
}
const remindPasswordUrl = `${process.env.APP_URL}/login/?resetCode=${code}&login=${userData.login}`;
-
const remindPasswordBody = `<html>
<body>
<p><a href="${remindPasswordUrl}"> Reset password link! </a></p>
</body>
</html>`;
- const sendResult = await Email.send({
+ Email.send({
text: null,
- to: userData.email, //'[email protected]',
+ to: userData.email,
subject: 'Remind password!',
from: process.env.SMTP_FROM_EMAIL as string,
attachment: [{ data: remindPasswordBody, alternative: true }],
+ }).catch((err) => {
+ $logger.error({ err, to: userData.email }, 'Failed to send remind password email');
});
- // const sendResult = await Email.send('', 'Remind password', '[email protected]', remindPasswordBody);
- if (sendResult) {
- return res.status(200).send({ sent: true });
- }
-
- return res.status(500).send();
+ return respond();
};
changeRemindedPassword = async (req: Request, res: Response) => {
@@ -580,6 +574,8 @@ export default class AuthController {
return res.status(500).send();
}
+ await req.appUser.authManager.repository.setReminderCodeAndTime(userData.email, null, null);
+
return res.status(200).send({ reset: true });
};
diff --git a/web/src/pages/login.vue b/web/src/pages/login.vue
index 38313de..6498ab4 100644
--- a/web/src/pages/login.vue
+++ b/web/src/pages/login.vue
@@ -43,6 +43,12 @@ async function loginByCode(code: string, email: string) {
}
onMounted(async () => {
+ // Handle password reset link from email (redirects to /reset-password preserving query)
+ if (route.query.resetCode) {
+ await router.replace({ path: '/reset-password', query: route.query })
+ return
+ }
+
// If user already has a valid token, redirect to dashboard
const existingToken = await $ls.getToken()
if (existingToken) {