Skip to content

Build your personal knowledge base with Trilium Notes

refactor(server): get rid of dead code

Elian Doranea65c0e634e8
diff --git a/apps/server/src/services/encryption/my_scrypt.spec.ts b/apps/server/src/services/encryption/my_scrypt.spec.ts
index 63eb2dc53c..6577b418c4 100644
--- a/apps/server/src/services/encryption/my_scrypt.spec.ts
+++ b/apps/server/src/services/encryption/my_scrypt.spec.ts
@@ -1,58 +1,20 @@
-import { beforeAll, describe, expect, it, vi } from "vitest";
+import { describe, expect, it } from "vitest";
-import sql from "../sql.js";
-import sql_init from "../sql_init.js";
import myScrypt from "./my_scrypt.js";
describe("my_scrypt (OpenID scrypt helpers)", () => {
- beforeAll(async () => {
- sql_init.initializeDb();
- await sql_init.dbReady;
- });
-
- it("derives deterministic, salt-dependent hashes when salt is given explicitly", () => {
+ it("derives deterministic, salt-dependent hashes", () => {
const a = myScrypt.getSubjectIdentifierVerificationHash("subject", "salt-one");
const a2 = myScrypt.getSubjectIdentifierVerificationHash("subject", "salt-one");
const b = myScrypt.getSubjectIdentifierVerificationHash("subject", "salt-two");
expect(a).toBeInstanceOf(Buffer);
expect(a).toHaveLength(32);
- expect(a!.equals(a2!)).toBe(true);
- expect(a!.equals(b!)).toBe(false);
-
- // createSubjectIdentifierDerivedKey shares the same underlying sync hash
- const derived = myScrypt.createSubjectIdentifierDerivedKey("subject", "salt-one");
- expect(derived.equals(a!)).toBe(true);
+ expect(a.equals(a2)).toBe(true);
+ expect(a.equals(b)).toBe(false);
- // getSubjectIdentifierDerivedKey with explicit salt matches as well
+ // getSubjectIdentifierDerivedKey shares the same underlying sync hash
const derivedKey = myScrypt.getSubjectIdentifierDerivedKey("subject", "salt-one");
- expect(derivedKey!.equals(a!)).toBe(true);
- });
-
- it("reads salt from user_data when none is given", () => {
- sql.transactional(() => {
- sql.execute("DELETE FROM user_data");
- sql.upsert("user_data", "tmpID", { tmpID: 0, salt: "db-salt" });
- });
-
- const fromDb = myScrypt.getSubjectIdentifierVerificationHash("subject");
- const explicit = myScrypt.getSubjectIdentifierVerificationHash("subject", "db-salt");
- expect(fromDb!.equals(explicit!)).toBe(true);
-
- const derivedFromDb = myScrypt.getSubjectIdentifierDerivedKey("subject");
- expect(derivedFromDb!.equals(explicit!)).toBe(true);
- });
-
- it("returns undefined and logs when no salt is stored", () => {
- const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
- sql.transactional(() => {
- sql.execute("DELETE FROM user_data");
- });
-
- expect(myScrypt.getSubjectIdentifierVerificationHash("subject")).toBeUndefined();
- expect(errorSpy).toHaveBeenCalled();
- expect(myScrypt.getSubjectIdentifierDerivedKey("subject")).toBeUndefined();
-
- errorSpy.mockRestore();
+ expect(derivedKey.equals(a)).toBe(true);
});
});
diff --git a/apps/server/src/services/encryption/my_scrypt.ts b/apps/server/src/services/encryption/my_scrypt.ts
index 8db65d2810..3577d60fdb 100644
--- a/apps/server/src/services/encryption/my_scrypt.ts
+++ b/apps/server/src/services/encryption/my_scrypt.ts
@@ -7,11 +7,9 @@
* import { scrypt } from "@triliumnext/core";
* await scrypt.getVerificationHash(password);
*
- * This file only contains OpenID-specific functions that use synchronous crypto
- * and access the user_data table directly.
+ * This file only contains OpenID-specific functions that use synchronous crypto.
*/
import crypto from "crypto";
-import sql from "../sql.js";
const SCRYPT_OPTIONS = { N: 16384, r: 8, p: 1 };
@@ -24,52 +22,25 @@ function getScryptHashSync(password: crypto.BinaryLike, salt: crypto.BinaryLike)
/**
* Gets the verification hash for an OpenID subject identifier.
- * Uses the salt from user_data table if not provided.
*/
function getSubjectIdentifierVerificationHash(
guessedUserId: string | crypto.BinaryLike,
- salt?: string
-): Buffer | undefined {
- if (salt != null) return getScryptHashSync(guessedUserId, salt);
-
- const savedSalt = sql.getValue("SELECT salt FROM user_data;");
- if (!savedSalt) {
- console.error("User salt undefined!");
- return undefined;
- }
- return getScryptHashSync(guessedUserId, savedSalt.toString());
+ salt: string
+): Buffer {
+ return getScryptHashSync(guessedUserId, salt);
}
/**
* Gets the derived key for an OpenID subject identifier.
- * Uses the salt from user_data table if not provided.
*/
function getSubjectIdentifierDerivedKey(
subjectIdentifer: crypto.BinaryLike,
- givenSalt?: string
-): Buffer | undefined {
- if (givenSalt !== undefined) {
- return getScryptHashSync(subjectIdentifer, givenSalt.toString());
- }
-
- const salt = sql.getValue("SELECT salt FROM user_data;");
- if (!salt) return undefined;
-
- return getScryptHashSync(subjectIdentifer, salt.toString());
-}
-
-/**
- * Creates a derived key for an OpenID subject identifier with the given salt.
- */
-function createSubjectIdentifierDerivedKey(
- subjectIdentifer: string | crypto.BinaryLike,
- salt: string | crypto.BinaryLike
+ salt: string
): Buffer {
return getScryptHashSync(subjectIdentifer, salt);
}
export default {
getSubjectIdentifierVerificationHash,
- getSubjectIdentifierDerivedKey,
- createSubjectIdentifierDerivedKey
+ getSubjectIdentifierDerivedKey
};
diff --git a/apps/server/src/services/encryption/open_id_encryption.spec.ts b/apps/server/src/services/encryption/open_id_encryption.spec.ts
index da3200f195..4c7e58d00b 100644
--- a/apps/server/src/services/encryption/open_id_encryption.spec.ts
+++ b/apps/server/src/services/encryption/open_id_encryption.spec.ts
@@ -1,8 +1,7 @@
import { data_encryption } from "@triliumnext/core";
-import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeAll, beforeEach, describe, expect, it } from "vitest";
import sql from "../sql.js";
-import sqlInit from "../sql_init.js";
import myScrypt from "./my_scrypt.js";
import openIDEncryption from "./open_id_encryption.js";
@@ -32,136 +31,18 @@ describe("open_id_encryption", () => {
expect(saved).toBe(true);
expect(openIDEncryption.isSubjectIdentifierSaved()).toBe(true);
- // once a user is set up, verifyOpenIDSubjectIdentifier short-circuits to false
- expect(openIDEncryption.verifyOpenIDSubjectIdentifier("subject-123")).toBe(false);
// a second save short-circuits because a user already exists
expect(openIDEncryption.saveUser("other", "Bob", "[email protected]")).toBe(false);
});
- it("setDataKey / getDataKey round-trips the plaintext data key", () => {
+ it("setDataKey encrypts the data key so it can be recovered with the derived key", () => {
const salt = "fixed-salt";
const plainKey = "0123456789abcdef";
const encrypted = openIDEncryption.setDataKey("subject-xyz", plainKey, salt);
expect(typeof encrypted).toBe("string");
- sql.transactional(() => {
- sql.upsert("user_data", "tmpID", {
- tmpID: 0,
- salt,
- userIDEncryptedDataKey: encrypted
- });
- });
-
- const decrypted = openIDEncryption.getDataKey("subject-xyz");
- expect(Buffer.from(decrypted as Uint8Array).toString()).toBe(plainKey);
- });
-
- it("getDataKey returns undefined when no encrypted data key is stored", () => {
- const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
- sql.transactional(() => {
- sql.upsert("user_data", "tmpID", { tmpID: 0, salt: "s" });
- });
- expect(openIDEncryption.getDataKey("subject")).toBeUndefined();
- expect(errorSpy).toHaveBeenCalled();
- errorSpy.mockRestore();
- });
-
- it("getDataKey returns undefined when the derived key cannot be produced", () => {
- const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
- sql.transactional(() => {
- sql.upsert("user_data", "tmpID", { tmpID: 0, salt: "s", userIDEncryptedDataKey: "abc" });
- });
- const spy = vi.spyOn(myScrypt, "getSubjectIdentifierDerivedKey").mockReturnValue(undefined);
- expect(openIDEncryption.getDataKey("subject")).toBeUndefined();
- expect(errorSpy).toHaveBeenCalled();
- spy.mockRestore();
- errorSpy.mockRestore();
- });
-
- it("setDataKey returns undefined when the derived key cannot be produced", () => {
- const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
- const spy = vi
- .spyOn(myScrypt, "getSubjectIdentifierDerivedKey")
- .mockReturnValue(undefined);
- expect(openIDEncryption.setDataKey("subject", "key", "salt")).toBeUndefined();
- expect(errorSpy).toHaveBeenCalled();
- spy.mockRestore();
- errorSpy.mockRestore();
- });
-
- describe("verifyOpenIDSubjectIdentifier", () => {
- it("throws when the database is not initialized", () => {
- const spy = vi.spyOn(sqlInit, "isDbInitialized").mockReturnValue(false);
- expect(() => openIDEncryption.verifyOpenIDSubjectIdentifier("subject")).toThrow();
- spy.mockRestore();
- });
-
- it("returns undefined when salt is missing", () => {
- const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
- // row exists (so isUserSaved=false) but salt is null
- sql.transactional(() => {
- sql.upsert("user_data", "tmpID", { tmpID: 0, isSetup: "false" });
- });
- expect(openIDEncryption.verifyOpenIDSubjectIdentifier("subject")).toBeUndefined();
- // Disambiguate from the other undefined-returning branch (hash undefined):
- // this must be the missing-salt branch.
- expect(logSpy).toHaveBeenCalledWith("Salt undefined");
- logSpy.mockRestore();
- });
-
- it("returns the constant-time comparison of stored vs computed hashes", () => {
- const subject = "subject-verify";
- const salt = "the-salt";
- const hash = myScrypt.getSubjectIdentifierVerificationHash(subject, salt)!.toString("base64");
- sql.transactional(() => {
- sql.upsert("user_data", "tmpID", {
- tmpID: 0,
- isSetup: "false",
- salt,
- userIDVerificationHash: hash
- });
- });
-
- expect(openIDEncryption.verifyOpenIDSubjectIdentifier(subject)).toBe(true);
- expect(openIDEncryption.verifyOpenIDSubjectIdentifier("wrong-subject")).toBe(false);
- });
-
- it("returns undefined when the computed subject-id hash is undefined", () => {
- const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
- sql.transactional(() => {
- sql.upsert("user_data", "tmpID", { tmpID: 0, isSetup: "false", salt: "s" });
- });
- const spy = vi
- .spyOn(myScrypt, "getSubjectIdentifierVerificationHash")
- .mockReturnValue(undefined);
- expect(openIDEncryption.verifyOpenIDSubjectIdentifier("subject")).toBeUndefined();
- spy.mockRestore();
- logSpy.mockRestore();
- });
-
- });
-
- describe("saveUser defensive branches", () => {
- it("throws when the verification hash cannot be computed", () => {
- const spy = vi
- .spyOn(myScrypt, "getSubjectIdentifierVerificationHash")
- .mockReturnValue(undefined);
- expect(() => openIDEncryption.saveUser("s", "n", "[email protected]")).toThrow();
- spy.mockRestore();
- });
-
- it("returns undefined when the encrypted data key cannot be produced", () => {
- const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
- const encryptSpy = vi.spyOn(data_encryption, "encrypt");
- const derivedSpy = vi
- .spyOn(myScrypt, "getSubjectIdentifierDerivedKey")
- .mockReturnValue(undefined);
- expect(openIDEncryption.saveUser("s", "n", "[email protected]")).toBeUndefined();
- expect(encryptSpy).not.toHaveBeenCalled();
- derivedSpy.mockRestore();
- encryptSpy.mockRestore();
- errorSpy.mockRestore();
- });
+ const derivedKey = myScrypt.getSubjectIdentifierDerivedKey("subject-xyz", salt);
+ expect(data_encryption.decryptString(derivedKey, encrypted)).toBe(plainKey);
});
});
diff --git a/apps/server/src/services/encryption/open_id_encryption.ts b/apps/server/src/services/encryption/open_id_encryption.ts
index c5d351b587..d56ed87f25 100644
--- a/apps/server/src/services/encryption/open_id_encryption.ts
+++ b/apps/server/src/services/encryption/open_id_encryption.ts
@@ -1,8 +1,7 @@
-import { data_encryption, OpenIdError } from "@triliumnext/core";
+import { data_encryption } from "@triliumnext/core";
import sql from "../sql.js";
-import sqlInit from "../sql_init.js";
-import utils, { constantTimeCompare } from "../utils.js";
+import utils from "../utils.js";
import myScryptService from "./my_scrypt.js";
function saveUser(subjectIdentifier: string, name: string, email: string) {
@@ -15,9 +14,6 @@ function saveUser(subjectIdentifier: string, name: string, email: string) {
subjectIdentifier,
verificationSalt
);
- if (!verificationHash) {
- throw new OpenIdError("Verification hash undefined!");
- }
const userIDEncryptedDataKey = setDataKey(
subjectIdentifier,
@@ -25,11 +21,6 @@ function saveUser(subjectIdentifier: string, name: string, email: string) {
verificationSalt
);
- if (!userIDEncryptedDataKey) {
- console.error("UserID encrypted data key null");
- return undefined;
- }
-
const data = {
tmpID: 0,
userIDVerificationHash: utils.toBase64(verificationHash),
@@ -56,43 +47,6 @@ function isUserSaved() {
return isSaved === "true";
}
-function verifyOpenIDSubjectIdentifier(subjectIdentifier: string) {
- if (!sqlInit.isDbInitialized()) {
- throw new OpenIdError("Database not initialized!");
- }
-
- if (isUserSaved()) {
- return false;
- }
-
- const salt = sql.getValue("SELECT salt FROM user_data;");
- if (salt == undefined) {
- console.log("Salt undefined");
- return undefined;
- }
-
- const givenHash = myScryptService
- .getSubjectIdentifierVerificationHash(subjectIdentifier)
- ?.toString("base64");
- if (givenHash === undefined) {
- console.log("Sub id hash undefined!");
- return undefined;
- }
-
- const savedHash = sql.getValue(
- "SELECT userIDVerificationHash FROM user_data"
- );
- /* v8 ignore next 4 -- unreachable: the same single user_data row already
- yielded a non-null salt above, so this column query cannot return undefined
- (a NULL column yields null, not undefined). */
- if (savedHash === undefined) {
- console.log("verification hash undefined");
- return undefined;
- }
-
- return constantTimeCompare(givenHash, savedHash as string);
-}
-
function setDataKey(
subjectIdentifier: string,
plainTextDataKey: string | Buffer,
@@ -101,46 +55,10 @@ function setDataKey(
const subjectIdentifierDerivedKey =
myScryptService.getSubjectIdentifierDerivedKey(subjectIdentifier, salt);
- if (subjectIdentifierDerivedKey === undefined) {
- console.error("SOMETHING WENT WRONG SAVING USER ID DERIVED KEY");
- return undefined;
- }
- const newEncryptedDataKey = data_encryption.encrypt(
- subjectIdentifierDerivedKey,
- plainTextDataKey
- );
-
- return newEncryptedDataKey;
-}
-
-function getDataKey(subjectIdentifier: string) {
- const subjectIdentifierDerivedKey =
- myScryptService.getSubjectIdentifierDerivedKey(subjectIdentifier);
-
- const encryptedDataKey = sql.getValue(
- "SELECT userIDEncryptedDataKey FROM user_data"
- );
-
- if (!encryptedDataKey) {
- console.error("Encrypted data key empty!");
- return undefined;
- }
-
- if (!subjectIdentifierDerivedKey) {
- console.error("SOMETHING WENT WRONG SAVING USER ID DERIVED KEY");
- return undefined;
- }
- const decryptedDataKey = data_encryption.decrypt(
- subjectIdentifierDerivedKey,
- encryptedDataKey.toString()
- );
-
- return decryptedDataKey;
+ return data_encryption.encrypt(subjectIdentifierDerivedKey, plainTextDataKey);
}
export default {
- verifyOpenIDSubjectIdentifier,
- getDataKey,
setDataKey,
saveUser,
isSubjectIdentifierSaved,