diff --git a/app/typings/index.d.ts b/app/typings/index.d.ts index 72c3d97303..9c4d1f8862 100644 --- a/app/typings/index.d.ts +++ b/app/typings/index.d.ts @@ -6,8 +6,6 @@ declare module "emoji-mart"; declare module "string-replace-to-array"; -declare module "sequelize-encrypted"; - declare module "styled-components-breakpoint"; declare module "command-score"; diff --git a/package.json b/package.json index b60b6bf10c..c2c7171cf1 100644 --- a/package.json +++ b/package.json @@ -242,7 +242,6 @@ "semver": "^7.8.1", "sequelize": "^6.37.8", "sequelize-cli": "^6.6.5", - "sequelize-encrypted": "^1.0.0", "sequelize-strict-attributes": "^1.0.2", "sequelize-typescript": "^2.1.6", "slug": "^5.3.0", diff --git a/server/models/decorators/Encrypted.test.ts b/server/models/decorators/Encrypted.test.ts new file mode 100644 index 0000000000..8bd3a70433 --- /dev/null +++ b/server/models/decorators/Encrypted.test.ts @@ -0,0 +1,72 @@ +import env from "@server/env"; +import { encrypt, decrypt } from "./Encrypted"; + +describe("Encrypted", () => { + it("should round-trip a simple string", () => { + const value = JSON.stringify("hello world"); + expect(decrypt(encrypt(value))).toEqual(value); + }); + + it("should round-trip an object", () => { + const value = JSON.stringify({ + token: "abc123", + scopes: ["read", "write"], + }); + expect(JSON.parse(decrypt(encrypt(value)))).toEqual({ + token: "abc123", + scopes: ["read", "write"], + }); + }); + + it("should round-trip unicode and emoji", () => { + const value = JSON.stringify("héllo 🌍 こんにちは"); + expect(decrypt(encrypt(value))).toEqual(value); + }); + + it("should round-trip an empty string", () => { + const value = JSON.stringify(""); + expect(decrypt(encrypt(value))).toEqual(value); + }); + + it("should round-trip a long value across multiple cipher blocks", () => { + // A value longer than a single AES block (16 bytes) to guard against + // ciphertext truncation regressions. + const value = JSON.stringify("a".repeat(1024)); + expect(decrypt(encrypt(value))).toEqual(value); + }); + + it("should produce a different IV (and ciphertext) each time", () => { + const value = JSON.stringify("hello world"); + expect(encrypt(value).equals(encrypt(value))).toBe(false); + }); + + it("should fail to decrypt tampered data", () => { + const encrypted = encrypt(JSON.stringify("hello world")); + encrypted[encrypted.length - 1] ^= 0xff; + expect(() => decrypt(encrypted)).toThrow(); + }); + + it("should fail to decrypt with a different key", () => { + const originalKey = env.SECRET_KEY; + const encrypted = encrypt(JSON.stringify("hello world")); + try { + env.SECRET_KEY = + "a593e7f567d01031d153b5af6d9a25766b95926cff91c6be3438c7f7ac37230f"; + expect(() => decrypt(encrypted)).toThrow(/bad decrypt/); + } finally { + env.SECRET_KEY = originalKey; + } + }); + + it("should throw on an incorrectly sized key", () => { + const originalKey = env.SECRET_KEY; + try { + env.SECRET_KEY = "abcd"; + expect(() => encrypt(JSON.stringify("hello world"))).toThrow( + /Invalid key length/ + ); + } finally { + env.SECRET_KEY = originalKey; + } + }); +}); diff --git a/server/models/decorators/Encrypted.ts b/server/models/decorators/Encrypted.ts index 3174db87db..750ba80a12 100644 --- a/server/models/decorators/Encrypted.ts +++ b/server/models/decorators/Encrypted.ts @@ -1,15 +1,57 @@ +import crypto from "node:crypto"; import { isEmpty, isNil } from "es-toolkit/compat"; import { getAttributes } from "sequelize-typescript"; import { toError, errToString } from "@shared/utils/error"; +import env from "@server/env"; import Logger from "@server/logging/Logger"; -import vaults from "@server/storage/vaults"; -const key = "sequelize:vault"; +const algorithm = "aes-256-cbc"; +const ivLength = 16; /** - * A decorator that stores the encrypted vault for a particular database column - * so that it can be used by getters and setters. Must be accompanied by a - * @Column(DataType.BLOB) annotation. + * Encrypt a string value for storage in a database column. The returned buffer + * is the initialization vector followed by the ciphertext (`iv || ciphertext`) + * using AES-256-CBC, matching the on-disk format of previously encrypted data. + * + * @param value The plaintext value to encrypt. + * @returns A buffer containing the IV concatenated with the ciphertext. + */ +export function encrypt(value: string): Buffer { + const iv = crypto.randomBytes(ivLength); + const cipher = crypto.createCipheriv( + algorithm, + Buffer.from(env.SECRET_KEY, "hex"), + iv + ); + const ciphertext = Buffer.concat([ + cipher.update(value, "utf-8"), + cipher.final(), + ]); + return Buffer.concat([iv, ciphertext]); +} + +/** + * Decrypt a buffer produced by `encrypt` back into its original string value. + * + * @param value A buffer containing the IV concatenated with the ciphertext. + * @returns The decrypted plaintext value. + */ +export function decrypt(value: Buffer): string { + const iv = value.subarray(0, ivLength); + const ciphertext = value.subarray(ivLength); + const decipher = crypto.createDecipheriv( + algorithm, + Buffer.from(env.SECRET_KEY, "hex"), + iv + ); + return ( + decipher.update(ciphertext, undefined, "utf-8") + decipher.final("utf-8") + ); +} + +/** + * A decorator that transparently encrypts and decrypts the value of a database + * column. Must be accompanied by a @Column(DataType.BLOB) annotation. */ export default function Encrypted(target: object, propertyKey: string) { // Ensure that the Encrypted decorator is the first decorator applied to the property, we can check @@ -21,23 +63,20 @@ export default function Encrypted(target: object, propertyKey: string) { ); } - Reflect.defineMetadata(key, vaults().vault(propertyKey), target, propertyKey); - return { get() { const attributeOptions = getAttributes(target); const defaultValue = attributeOptions[propertyKey].allowNull ? null : ""; - if (!this.getDataValue(propertyKey)) { + const previous = this.getDataValue(propertyKey); + if (!previous) { return defaultValue; } try { - const value = Reflect.getMetadata(key, this, propertyKey).get.call( - this - ); + const value = JSON.parse(decrypt(previous)); - // `value` equals to `{}` instead of `null` if column value in db is `null`. Possibly explained by: - // https://github.com/defunctzombie/sequelize-encrypted/blob/c3854e76ae4b80318c8f10f94e6c898c67659ca6/index.js#L30-L33 + // An empty object can be the result of a `null` column value, in which + // case we return the default value instead. return isEmpty(value) && typeof value === "object" ? defaultValue : value; @@ -60,7 +99,7 @@ export default function Encrypted(target: object, propertyKey: string) { if (isNil(value)) { this.setDataValue(propertyKey, value); } else { - Reflect.getMetadata(key, this, propertyKey).set.call(this, value); + this.setDataValue(propertyKey, encrypt(JSON.stringify(value))); } } catch (err) { if ( diff --git a/server/storage/vaults.ts b/server/storage/vaults.ts deleted file mode 100644 index 637f8fce50..0000000000 --- a/server/storage/vaults.ts +++ /dev/null @@ -1,10 +0,0 @@ -import SequelizeEncrypted from "sequelize-encrypted"; -import { Sequelize } from "sequelize-typescript"; -import env from "@server/env"; - -/** - * Encrypted field storage, use via the Encrypted decorator, not directly. - */ -export default function vaults() { - return SequelizeEncrypted(Sequelize, env.SECRET_KEY); -} diff --git a/server/typings/index.d.ts b/server/typings/index.d.ts index 4535ba5ba7..39630108d5 100644 --- a/server/typings/index.d.ts +++ b/server/typings/index.d.ts @@ -1,5 +1,3 @@ -declare module "sequelize-encrypted"; - declare module "styled-components-breakpoint"; declare module "formidable/lib/file"; diff --git a/yarn.lock b/yarn.lock index e24d473001..249dfa89c5 100644 --- a/yarn.lock +++ b/yarn.lock @@ -15241,7 +15241,6 @@ __metadata: semver: "npm:^7.8.1" sequelize: "npm:^6.37.8" sequelize-cli: "npm:^6.6.5" - sequelize-encrypted: "npm:^1.0.0" sequelize-strict-attributes: "npm:^1.0.2" sequelize-typescript: "npm:^2.1.6" slug: "npm:^5.3.0" @@ -17832,13 +17831,6 @@ __metadata: languageName: node linkType: hard -"sequelize-encrypted@npm:^1.0.0": - version: 1.0.0 - resolution: "sequelize-encrypted@npm:1.0.0" - checksum: 10c0/be6861ac71a6986ec3a06d3b41056ceff6f9a2a258d7954e38bf82be327d61b1d67d34bb303296f1b0e43e9c117f86dfbc20ac2b85450c715beaa1cdf36ad503 - languageName: node - linkType: hard - "sequelize-pool@npm:^7.1.0": version: 7.1.0 resolution: "sequelize-pool@npm:7.1.0"