Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
chore(core): reintroduce encryption and password reset
Elian Doran8f3f2cc8c1d4
diff --git a/apps/server/src/routes/api/login.ts b/apps/server/src/routes/api/login.tsindex feea6d81c2..fc46c19617 100644--- a/apps/server/src/routes/api/login.ts+++ b/apps/server/src/routes/api/login.ts@@ -1,4 +1,10 @@-import { events as eventService, getInstanceId } from "@triliumnext/core";+/**+ * Server-only login routes.+ *+ * Protected session routes (loginToProtectedSession, logoutFromProtectedSession,+ * touchProtectedSession) are now in core and registered via buildSharedApiRoutes.+ */+import { getInstanceId } from "@triliumnext/core";import type { Request } from "express";import appInfo from "../../services/app_info.js";@@ -7,12 +13,10 @@ import passwordEncryptionService from "../../services/encryption/password_encrypimport recoveryCodeService from "../../services/encryption/recovery_codes";import etapiTokenService from "../../services/etapi_tokens.js";import options from "../../services/options.js";-import protectedSessionService from "../../services/protected_session.js";import sql from "../../services/sql.js";import sqlInit from "../../services/sql_init.js";import totp from "../../services/totp";import utils from "../../services/utils.js";-import ws from "../../services/ws.js";/*** @swagger@@ -118,48 +122,7 @@ function loginSync(req: Request) {};}-async function loginToProtectedSession(req: Request) {- const password = req.body.password;-- if (!(await passwordEncryptionService.verifyPassword(password))) {- return {- success: false,- message: "Given current password doesn't match hash"- };- }-- const decryptedDataKey = await passwordEncryptionService.getDataKey(password);- if (!decryptedDataKey) {- return {- success: false,- message: "Unable to obtain data key."- };- }-- protectedSessionService.setDataKey(decryptedDataKey);-- eventService.emit(eventService.ENTER_PROTECTED_SESSION);-- ws.sendMessageToAllClients({ type: "protectedSessionLogin" });-- return {- success: true- };-}--function logoutFromProtectedSession() {- protectedSessionService.resetDataKey();-- eventService.emit(eventService.LEAVE_PROTECTED_SESSION);-- ws.sendMessageToAllClients({ type: "protectedSessionLogout" });-}--function touchProtectedSession() {- protectedSessionService.touchProtectedSession();-}--function token(req: Request) {+async function token(req: Request) {const password = req.body.password;const submittedTotpToken = req.body.totpToken;@@ -169,7 +132,7 @@ function token(req: Request) {}}- if (!passwordEncryptionService.verifyPassword(password)) {+ if (!(await passwordEncryptionService.verifyPassword(password))) {return [401, "Incorrect credential"];}@@ -191,8 +154,5 @@ function verifyTOTP(submittedTotpToken: string) {export default {loginSync,- loginToProtectedSession,- logoutFromProtectedSession,- touchProtectedSession,token};diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.tsindex 6510b03cff..b8168583aa 100644--- a/apps/server/src/routes/routes.ts+++ b/apps/server/src/routes/routes.ts@@ -28,7 +28,6 @@ import llmSpecialNotesRoute from "./api/llm_special_notes.js";import loginApiRoute from "./api/login.js";import metricsRoute from "./api/metrics.js";import ocrRoute from "./api/ocr.js";-import passwordApiRoute from "./api/password.js";import recoveryCodes from './api/recovery_codes.js';import senderRoute from "./api/sender.js";import systemInfoRoute from "./api/system_info.js";@@ -124,9 +123,6 @@ function register(app: express.Application) {// TODO: Re-enable once we support route()// route(GET, "/api/revisions/:revisionId/download", [auth.checkApiAuthOrElectron], revisionsApiRoute.downloadRevision);- asyncApiRoute(PST, "/api/password/change", passwordApiRoute.changePassword);- apiRoute(PST, "/api/password/reset", passwordApiRoute.resetPassword);-apiRoute(GET, "/api/metrics", metricsRoute.getMetrics);apiRoute(GET, "/api/system-checks", systemInfoRoute.systemChecks);@@ -134,12 +130,7 @@ function register(app: express.Application) {route(GET, "/api/health-check", [], () => ({ status: "ok" }), apiResultHandler);route(PST, "/api/login/sync", [loginRateLimiter], loginApiRoute.loginSync, apiResultHandler);- // this is for entering protected mode so user has to be already logged-in (that's the reason we don't require username)- asyncApiRoute(PST, "/api/login/protected", loginApiRoute.loginToProtectedSession);- apiRoute(PST, "/api/login/protected/touch", loginApiRoute.touchProtectedSession);- apiRoute(PST, "/api/logout/protected", loginApiRoute.logoutFromProtectedSession);-- route(PST, "/api/login/token", [loginRateLimiter], loginApiRoute.token, apiResultHandler);+ asyncRoute(PST, "/api/login/token", [loginRateLimiter], loginApiRoute.token, apiResultHandler);apiRoute(GET, "/api/etapi-tokens", etapiTokensApiRoutes.getTokens);apiRoute(PST, "/api/etapi-tokens", etapiTokensApiRoutes.createToken);@@ -180,7 +171,7 @@ function register(app: express.Application) {apiRoute(GET, "/api/llm-chat/models", llmChatRoute.getModels);// no CSRF since this is called from android app- route(PST, "/api/sender/login", [loginRateLimiter], loginApiRoute.token, apiResultHandler);+ asyncRoute(PST, "/api/sender/login", [loginRateLimiter], loginApiRoute.token, apiResultHandler);asyncRoute(PST, "/api/sender/image", [auth.checkEtapiToken, uploadMiddlewareWithErrorHandling], senderRoute.uploadImage, apiResultHandler);asyncRoute(PST, "/api/sender/note", [auth.checkEtapiToken], senderRoute.saveNote, apiResultHandler);diff --git a/packages/trilium-core/src/routes/api/login.ts b/packages/trilium-core/src/routes/api/login.tsnew file mode 100644index 0000000000..e7fe0b95fb--- /dev/null+++ b/packages/trilium-core/src/routes/api/login.ts@@ -0,0 +1,52 @@+import type { Request } from "express";+import events from "../../services/events.js";+import passwordEncryptionService from "../../services/encryption/password_encryption.js";+import protectedSession from "../../services/protected_session.js";+import ws from "../../services/ws.js";++async function loginToProtectedSession(req: Request) {+ const password = req.body.password;++ if (!(await passwordEncryptionService.verifyPassword(password))) {+ return {+ success: false,+ message: "Given current password doesn't match hash"+ };+ }++ const decryptedDataKey = await passwordEncryptionService.getDataKey(password);+ if (!decryptedDataKey) {+ return {+ success: false,+ message: "Unable to obtain data key."+ };+ }++ protectedSession.setDataKey(decryptedDataKey);++ events.emit(events.ENTER_PROTECTED_SESSION);++ ws.sendMessageToAllClients({ type: "protectedSessionLogin" });++ return {+ success: true+ };+}++function logoutFromProtectedSession() {+ protectedSession.resetDataKey();++ events.emit(events.LEAVE_PROTECTED_SESSION);++ ws.sendMessageToAllClients({ type: "protectedSessionLogout" });+}++function touchProtectedSession() {+ protectedSession.touchProtectedSession();+}++export default {+ loginToProtectedSession,+ logoutFromProtectedSession,+ touchProtectedSession+};diff --git a/packages/trilium-core/src/routes/api/password.ts b/packages/trilium-core/src/routes/api/password.tsnew file mode 100644index 0000000000..9ce57a66ca--- /dev/null+++ b/packages/trilium-core/src/routes/api/password.ts@@ -0,0 +1,25 @@+import type { ChangePasswordResponse } from "@triliumnext/commons";+import type { Request } from "express";+import passwordService from "../../services/encryption/password.js";+import { ValidationError } from "../../errors.js";++async function changePassword(req: Request): Promise<ChangePasswordResponse> {+ if (passwordService.isPasswordSet()) {+ return await passwordService.changePassword(req.body.current_password, req.body.new_password);+ }+ return await passwordService.setPassword(req.body.new_password);+}++function resetPassword(req: Request) {+ // protection against accidental call (not a security measure)+ if (req.query.really !== "yesIReallyWantToResetPasswordAndLoseAccessToMyProtectedNotes") {+ throw new ValidationError("Incorrect password reset confirmation");+ }++ return passwordService.resetPassword();+}++export default {+ changePassword,+ resetPassword+};diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.tsindex f3da081822..107add4acd 100644--- a/packages/trilium-core/src/routes/index.ts+++ b/packages/trilium-core/src/routes/index.ts@@ -30,6 +30,8 @@ import exportRoute from "./api/export";import scriptRoute from "./api/script";import backendLogRoute from "./api/backend_log";import backupRoute from "./api/backup";+import passwordApiRoute from "./api/password";+import loginApiRoute from "./api/login";// TODO: Deduplicate with routes.tsconst GET = "get",@@ -237,6 +239,15 @@ export function buildSharedApiRoutes({ route, asyncRoute, apiRoute, asyncApiRoutapiRoute(PST, "/api/script/bundle/:noteId", scriptRoute.getBundle);apiRoute(GET, "/api/script/relation/:noteId/:relationName", scriptRoute.getRelationBundles);//#endregion++ //#region Password and protected session+ asyncApiRoute(PST, "/api/password/change", passwordApiRoute.changePassword);+ apiRoute(PST, "/api/password/reset", passwordApiRoute.resetPassword);++ asyncApiRoute(PST, "/api/login/protected", loginApiRoute.loginToProtectedSession);+ apiRoute(PST, "/api/login/protected/touch", loginApiRoute.touchProtectedSession);+ apiRoute(PST, "/api/logout/protected", loginApiRoute.logoutFromProtectedSession);+ //#endregion}/** Handling common patterns. If entity is not caught, serialization to JSON will fail */diff --git a/packages/trilium-core/src/services/sql_init.ts b/packages/trilium-core/src/services/sql_init.tsindex 9157be2953..b360a02747 100644--- a/packages/trilium-core/src/services/sql_init.ts+++ b/packages/trilium-core/src/services/sql_init.ts@@ -12,6 +12,7 @@ import hidden_subtree from "./hidden_subtree";import TaskContext from "./task_context";import BOption from "../becca/entities/boption";import migrationService from "./migration";+import passwordService from "./encryption/password";export const dbReady = deferred<void>();@@ -166,7 +167,7 @@ async function createInitialDatabase(skipDemoDb?: boolean) {initDocumentOptions();initNotSyncedOptions(true, {});initStartupOptions();- // password.resetPassword();+ passwordService.resetPassword();});// Check hidden subtree.