snapshot of https://github.com/RocketChat/Rocket.Chat.git (develop, 2026-09-16; blobs > 131072B omitted)
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 1s

This commit is contained in:
upstream-mirror
2026-09-16 01:21:02 +05:00
commit 30810eecd7
10161 changed files with 987110 additions and 0 deletions

View File

@@ -0,0 +1 @@
export type E2EEState = 'NOT_STARTED' | 'DISABLED' | 'LOADING_KEYS' | 'READY' | 'SAVE_PASSWORD' | 'ENTER_PASSWORD' | 'ERROR';

View File

@@ -0,0 +1,2 @@
export type E2ERoomState =
'NOT_STARTED' | 'DISABLED' | 'ESTABLISHING' | 'CREATING_KEYS' | 'WAITING_KEYS' | 'KEYS_RECEIVED' | 'READY' | 'ERROR';

View File

@@ -0,0 +1,37 @@
import { Binary } from './binary';
describe('Binary', () => {
describe('toString', () => {
it('should convert ArrayBuffer to string', () => {
const array = new Uint8Array([72, 101, 108, 108, 111]); // "Hello"
const result = Binary.encode(array.buffer);
expect(result).toBe('Hello');
});
it('should handle empty ArrayBuffer', () => {
const buffer = new ArrayBuffer(0);
const result = Binary.encode(buffer);
expect(result).toBe('');
});
});
describe('toArrayBuffer', () => {
it('should convert string to ArrayBuffer', () => {
const str = 'Hello';
const buffer = Binary.decode(str);
const uint8 = new Uint8Array(buffer);
expect(Array.from(uint8)).toEqual([72, 101, 108, 108, 111]);
});
it('should handle empty string', () => {
const str = '';
const buffer = Binary.decode(str);
expect(buffer.byteLength).toBe(0);
});
it('should throw RangeError for illegal char code', () => {
const str = 'Hello\u0100'; // Character with char code 256
expect(() => Binary.decode(str)).toThrowErrorMatchingInlineSnapshot(`"illegal char code: 256"`);
});
});
});

View File

@@ -0,0 +1,32 @@
import type { ICodec } from './codec';
export const Binary: ICodec<string, ArrayBuffer> = {
encode(buffer: ArrayBuffer): string {
const uint8 = new Uint8Array(buffer);
const CHUNK_SIZE = 8192; // Process in chunks for performance
let result = '';
for (let i = 0; i < uint8.length; i += CHUNK_SIZE) {
const chunk = uint8.subarray(i, i + CHUNK_SIZE);
result += String.fromCharCode(...chunk);
}
return result;
},
decode(str: string): ArrayBuffer {
// Create a Uint8Array of the same length as the string.
// This will be a view on the new ArrayBuffer.
const buffer = new ArrayBuffer(str.length);
const uint8 = new Uint8Array(buffer);
// Iterate through the string, getting the character code for each
// character and setting it as the value for the corresponding byte.
for (let i = 0; i < str.length; i++) {
const charCode = str.charCodeAt(i);
if (charCode > 0xff) {
throw new RangeError(`illegal char code: ${charCode}`);
}
uint8[i] = charCode;
}
return buffer;
},
};

View File

@@ -0,0 +1,4 @@
export interface ICodec<TIn, TOut, TEnc = TIn> {
decode: (data: TIn) => TOut;
encode: (data: TOut) => TEnc;
}

View File

@@ -0,0 +1,144 @@
import { decodeEncryptedContent } from './content';
import { importKey, decrypt, type Key } from './crypto/aes';
describe('content', () => {
const msgv1web = Object.freeze({
_id: 'JfAxN6Ncsw2XS9eiY',
rid: '68dad82a10815056615446aa',
e2eMentions: {
e2eUserMentions: [],
e2eChannelMentions: [],
},
content: Object.freeze({
algorithm: 'rc.v1.aes-sha2',
ciphertext: '32c9e7917b78LHjHfqLMeDn+2UK1PhD/soFe8CVwvFdLkslcfxNHby4=',
}),
t: 'e2e',
ts: {
$date: '2025-09-29T19:07:07.908Z',
},
u: {
_id: 'bm4cAAcN92jgXe2jN',
username: 'alice',
name: 'alice',
},
msg: '',
_updatedAt: {
$date: '2025-09-29T19:07:07.929Z',
},
urls: [],
mentions: [],
channels: [],
});
const msgv1mob = Object.freeze({
_id: 'AZF8Myj605B3f7ZPL',
rid: '68dad82a10815056615446aa',
msg: '32c9e7917b783JpM8aOVludqIRzx+DOqjEU9Mj3NUWb+/GLRl7sdkvTtCMChH1LBjMjJJvVJ6Rlw4dI8BYFftZWiCOiR7TPwriCoSPiZ7dY5C4H2q8MVSdR95ZiyG7eWQ5j5/rxzAYsSWDA9LkumW8JBb+WQ1hD9JMfQd4IXtlFMnaDgEhZhe/s=',
t: 'e2e',
e2e: 'pending',
e2eMentions: {
e2eUserMentions: [],
e2eChannelMentions: [],
},
content: Object.freeze({
algorithm: 'rc.v1.aes-sha2',
ciphertext:
'32c9e7917b783JpM8aOVludqIRzx+DOqjEU9Mj3NUWb+/GLRl7sdkvTtCMChH1LBjMjJJvVJ6Rlw4dI8BYFftZWiCOiR7TPwriCoSPiZ7dY5C4H2q8MVSdR95ZiyG7eWQ5j5/rxzAYsSWDA9LkumW8JBb+WQ1hD9JMfQd4IXtlFMnaDgEhZhe/s=',
}),
ts: {
$date: '2025-09-29T19:28:35.261Z',
},
u: {
_id: 'RQTYT5RJoDKZFwDhk',
username: 'bob',
name: 'bob',
},
_updatedAt: {
$date: '2025-09-29T19:28:35.274Z',
},
urls: [],
mentions: [],
channels: [],
});
describe('v1 messages', () => {
let key: Key<{ name: 'AES-CBC'; length: 128 }>;
beforeAll(async () => {
key = await importKey({
alg: 'A128CBC',
ext: true,
k: 'qb8In0Rpa9nwSusvxxDcbQ',
key_ops: ['encrypt', 'decrypt'],
kty: 'oct',
});
});
test('parse v1 web message', async () => {
const parsed = decodeEncryptedContent(msgv1web.content);
const decrypted = await decrypt(key, parsed);
expect(decrypted).toMatchInlineSnapshot(`"{"msg":"hello"}"`);
});
test('parse v1 mobile message', async () => {
const parsed = decodeEncryptedContent(msgv1mob.content);
const decrypted = await decrypt(key, parsed);
expect(decrypted).toMatchInlineSnapshot(
`"{"_id":"AZF8Myj605B3f7ZPL","text":"world","userId":"RQTYT5RJoDKZFwDhk","ts":{"$date":1759174115076}}"`,
);
});
test('parse v1 mobile message from msg field', async () => {
const parsed = decodeEncryptedContent(msgv1mob.msg);
const decrypted = await decrypt(key, parsed);
expect(decrypted).toMatchInlineSnapshot(
`"{"_id":"AZF8Myj605B3f7ZPL","text":"world","userId":"RQTYT5RJoDKZFwDhk","ts":{"$date":1759174115076}}"`,
);
});
});
const msgv2web = Object.freeze({
_id: 'h6sXWTiKcWfcgkhgo',
rid: '68c9da1b0427bc33b429207e',
e2eMentions: {
e2eUserMentions: [],
e2eChannelMentions: [],
},
content: Object.freeze({
algorithm: 'rc.v2.aes-sha2',
kid: 'f46d2864-0384-4a87-8815-51fba2cad216',
iv: 'wXbYQ8q9sYRCHtNp',
ciphertext: 'cIDO9mXzCCrrl/wORP0Jf6oWeusqzSCXVGGvY7CHrA==',
}),
t: 'e2e',
ts: {
$date: '2025-09-30T18:05:30.876Z',
},
u: {
_id: 'Ctk47kkuzJihnmvZE',
username: 'alice',
name: 'Alice',
},
msg: '',
_updatedAt: {
$date: '2025-09-30T18:05:30.887Z',
},
urls: [],
mentions: [],
channels: [],
});
test('parse v2 web message', async () => {
const parsed = decodeEncryptedContent(msgv2web.content);
const key = await importKey({
alg: 'A256GCM',
ext: true,
k: '9o1xoHt4OamRJvnaLna-5akUb5L98S_iWYGGaXPZ1Yg',
key_ops: ['encrypt', 'decrypt'],
kty: 'oct',
});
const decrypted = await decrypt(key, parsed);
expect(decrypted).toMatchInlineSnapshot(`"{"msg":"hello"}"`);
});
});

View File

@@ -0,0 +1,92 @@
import { Base64 } from '@rocket.chat/base64';
import type { EncryptedContent } from '@rocket.chat/core-typings';
type DecodedContent = {
kid: string;
iv: Uint8Array<ArrayBuffer>;
ciphertext: Uint8Array<ArrayBuffer>;
};
interface ISlice {
slice(start: number, end?: number): this;
}
/**
* Splits a slice of data into two parts at the specified index.
* @param data The data to split.
* @param index The index at which to split the data.
* @returns A tuple containing the two parts of the split data.
*/
const split = <T extends ISlice>(data: T, index: number): [T, T] => [data.slice(0, index), data.slice(index)];
/**
* Decodes an encrypted content string in the format "kid + base64(iv + ciphertext)".
* @param payload The encrypted content string.
* @returns An object containing the key ID (kid), initialization vector (iv), and ciphertext.
*/
const decodeV1EncryptedContent = (
payload: Omit<Extract<EncryptedContent, { algorithm: 'rc.v1.aes-sha2' }>, 'algorithm'>,
): DecodedContent => {
if (payload.ciphertext.length < 12) {
throw new Error('Invalid v1 ciphertext: too short for kid extraction');
}
const [kid, base64] = split(payload.ciphertext, 12);
const decoded = Base64.decode(base64);
if (decoded.length < 16) {
throw new Error('Invalid v1 ciphertext: too short for iv extraction');
}
const [iv, ciphertext] = split(decoded, 16);
return {
kid,
iv,
ciphertext,
};
};
/**
* Decodes an encrypted content object with separate fields for kid, iv, and ciphertext.
* @param payload The encrypted content object.
* @returns An object containing the key ID (kid), initialization vector (iv), and ciphertext.
*/
const decodeV2EncryptedContent = (payload: Extract<EncryptedContent, { algorithm: 'rc.v2.aes-sha2' }>): DecodedContent => {
if (!payload.kid || !payload.iv || !payload.ciphertext) {
throw new Error('Invalid v2 payload: kid, iv, and ciphertext must be non-empty');
}
const iv = Base64.decode(payload.iv);
const ciphertext = Base64.decode(payload.ciphertext);
return { kid: payload.kid, iv, ciphertext };
};
const normalizePayload = (payload: string | EncryptedContent): EncryptedContent => {
if (typeof payload === 'string') {
return { algorithm: 'rc.v1.aes-sha2', ciphertext: payload } as const;
}
return payload;
};
/**
* Parses encrypted content from either a string or an object and decodes it into its components.
* @param payload The encrypted content, either as a string or an object.
* @returns An object containing the key ID (kid), initialization vector (iv), and ciphertext.
* @throws Will throw an error if the encryption algorithm is unsupported.
*/
export const decodeEncryptedContent = (payload: string | EncryptedContent): DecodedContent => {
payload = normalizePayload(payload);
const { algorithm } = payload;
switch (algorithm) {
case 'rc.v1.aes-sha2':
return decodeV1EncryptedContent(payload);
case 'rc.v2.aes-sha2':
return decodeV2EncryptedContent(payload);
default:
throw new Error(`Unsupported encryption algorithm: ${algorithm}`);
}
};

View File

@@ -0,0 +1,97 @@
import { generate, decrypt, encrypt, exportJwk, importKey, type Key } from './aes';
describe('aes', () => {
describe('256-gcm', () => {
let key: Key<{ name: 'AES-GCM'; length: 256 }>;
beforeAll(async () => {
key = await generate();
});
it('generate a key with correct properties', async () => {
expect<256>(key.algorithm.length).toBe(256);
expect<'AES-GCM'>(key.algorithm.name).toBe('AES-GCM');
expect<true>(key.extractable).toBe(true);
expect<'secret'>(key.type).toBe('secret');
expect<2>(key.usages.length).toBe(2);
expect<['encrypt', 'decrypt'] | ['decrypt', 'encrypt']>(key.usages).toEqual(['encrypt', 'decrypt']);
});
it('should encrypt and decrypt data correctly', async () => {
const plaintext = new TextEncoder().encode('Hello, world!');
const ciphertext = await encrypt(key, plaintext);
const decrypted = await decrypt(key, ciphertext);
expect(decrypted).toBe('Hello, world!');
});
it('should export and re-import the key correctly', async () => {
const jwk = await exportJwk(key);
const importedKey = await importKey(jwk);
expect<256>(importedKey.algorithm.length).toBe(256);
expect<'AES-GCM'>(importedKey.algorithm.name).toBe('AES-GCM');
expect<true>(importedKey.extractable).toBe(true);
expect<'secret'>(importedKey.type).toBe('secret');
expect<2>(importedKey.usages.length).toBe(2);
expect<['encrypt', 'decrypt'] | ['decrypt', 'encrypt']>(importedKey.usages).toEqual(['encrypt', 'decrypt']);
});
});
describe('128-cbc', () => {
let key: Key<{ name: 'AES-CBC'; length: 128 }>;
beforeAll(async () => {
key = await importKey({ alg: 'A128CBC', ext: true, k: 'qb8In0Rpa9nwSusvxxDcbQ', key_ops: ['encrypt', 'decrypt'], kty: 'oct' });
});
it('import a key with correct properties', async () => {
expect<128>(key.algorithm.length).toBe(128);
expect<'AES-CBC'>(key.algorithm.name).toBe('AES-CBC');
expect<true>(key.extractable).toBe(true);
expect<'secret'>(key.type).toBe('secret');
expect<2>(key.usages.length).toBe(2);
expect<['encrypt', 'decrypt'] | ['decrypt', 'encrypt']>(key.usages).toEqual(['encrypt', 'decrypt']);
});
it('should encrypt and decrypt data correctly', async () => {
const plaintext = new TextEncoder().encode('Hello, AES-CBC!');
const ciphertext = await encrypt(key, plaintext);
const decrypted = await decrypt(key, ciphertext);
expect(decrypted).toBe('Hello, AES-CBC!');
});
it('should export and re-import the key correctly', async () => {
const jwk = await exportJwk(key);
const importedKey = await importKey(jwk);
expect<128>(importedKey.algorithm.length).toBe(128);
expect<'AES-CBC'>(importedKey.algorithm.name).toBe('AES-CBC');
expect<true>(importedKey.extractable).toBe(true);
expect<'secret'>(importedKey.type).toBe('secret');
expect<2>(importedKey.usages.length).toBe(2);
expect<['encrypt', 'decrypt'] | ['decrypt', 'encrypt']>(importedKey.usages).toEqual(['encrypt', 'decrypt']);
});
});
it('should throw on unsupported JWK alg', async () => {
await expect(
importKey({
// @ts-expect-error testing invalid alg
alg: 'A128GCM',
ext: true,
k: 'qb8In0Rpa9nwSusvxxDcbQ',
key_ops: ['encrypt', 'decrypt'],
kty: 'oct',
}),
).rejects.toThrow('Unrecognized algorithm name');
await expect(
importKey({
// @ts-expect-error testing invalid alg
alg: 'A256CBC',
ext: true,
k: '9o1xoHt4OamRJvnaLna-5akUb5L98S_iWYGGaXPZ1Yg',
key_ops: ['encrypt', 'decrypt'],
kty: 'oct',
}),
).rejects.toThrow('Unrecognized algorithm name');
});
});

View File

@@ -0,0 +1,62 @@
import { importJwk, exportKey, getRandomValues, generateKey, type IKey, type Exported, encryptBuffer, decryptBuffer } from './shared';
type AlgorithmMap = {
A256GCM: { name: 'AES-GCM'; length: 256 };
A128CBC: { name: 'AES-CBC'; length: 128 };
};
const ALGORITHM_MAP: AlgorithmMap = {
A256GCM: { name: 'AES-GCM', length: 256 },
A128CBC: { name: 'AES-CBC', length: 128 },
};
type Jwa = keyof AlgorithmMap;
type Algorithms = AlgorithmMap[Jwa];
export type Key<TAlgorithm extends Algorithms = Algorithms, TExtractable extends CryptoKey['extractable'] = true> = IKey<
TAlgorithm,
TExtractable,
'secret',
['encrypt', 'decrypt']
>;
export type Jwk<TJwa extends Jwa = Jwa> = {
kty: 'oct';
k: string;
key_ops: ['encrypt', 'decrypt'] | ['decrypt', 'encrypt'];
ext: true;
alg: TJwa;
};
type AesEncryptedContent = {
iv: Uint8Array<ArrayBuffer>;
ciphertext: Uint8Array<ArrayBuffer>;
};
export const importKey = <const TJwa extends Jwa>(jwk: Jwk<TJwa>): Promise<Key<AlgorithmMap[(typeof jwk)['alg']]>> => {
return importJwk(jwk, ALGORITHM_MAP[jwk.alg], true, ['encrypt', 'decrypt']);
};
export const exportJwk = <TAlgorithm extends Algorithms>(key: Key<TAlgorithm>): Promise<Exported<'jwk', Key<TAlgorithm>>> => {
return exportKey('jwk', key);
};
export const generate = (): Promise<Key<{ name: 'AES-GCM'; length: 256 }>> => {
return generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt', 'decrypt']);
};
export const decrypt = async (key: Key, content: AesEncryptedContent): Promise<string> => {
const decrypted = await decryptBuffer(
key,
{ name: key.algorithm.name, iv: content.iv } satisfies AesGcmParams | AesCbcParams,
content.ciphertext,
);
return new TextDecoder().decode(decrypted);
};
export const encrypt = async (key: Key, plaintext: Uint8Array<ArrayBuffer>): Promise<AesEncryptedContent> => {
const ivLength = key.algorithm.name === 'AES-GCM' ? 12 : 16;
const iv = getRandomValues(new Uint8Array(ivLength));
const ciphertext = await encryptBuffer(key, { name: key.algorithm.name, iv }, plaintext);
return { iv, ciphertext: new Uint8Array(ciphertext) };
};

View File

@@ -0,0 +1,49 @@
import { importBaseKey, derive, importKey } from './pbkdf2';
describe('pbkdf2', () => {
it('should import a base key', async () => {
const keyData = new Uint8Array([1, 2, 3, 4, 5]);
const baseKey = await importBaseKey(keyData);
expect<'PBKDF2'>(baseKey.algorithm.name).toBe('PBKDF2');
expect<false>(baseKey.extractable).toBe(false);
expect<'secret'>(baseKey.type).toBe('secret');
expect<1>(baseKey.usages.length).toBe(1);
expect<'deriveBits'>(baseKey.usages[0]).toBe('deriveBits');
});
it('should derive bits from a base key', async () => {
const keyData = new Uint8Array([1, 2, 3, 4, 5]);
const salt = new Uint8Array([5, 4, 3, 2, 1]);
const iterations = 1000;
const baseKey = await importBaseKey(keyData);
const derivedBits = await derive(baseKey, { salt, iterations });
expect<false>(derivedBits.detached).toBe(false);
expect<false>(derivedBits.resizable).toBe(false);
expect<32>(derivedBits.byteLength).toBe(32);
expect<32>(derivedBits.maxByteLength).toBe(32);
expect<() => never>(() => derivedBits.resize(32)).toThrow();
});
it('should import a derived key for AES-CBC', async () => {
const baseKey = await importBaseKey(new Uint8Array([1, 2, 3, 4, 5]));
const derivedBits = await derive(baseKey, { salt: new Uint8Array([5, 4, 3, 2, 1]), iterations: 1000 });
const derivedKey = await importKey(derivedBits, { name: 'AES-CBC', length: 256 });
expect<256>(derivedKey.algorithm.length).toBe(256);
expect<'AES-CBC'>(derivedKey.algorithm.name).toBe('AES-CBC');
expect<false>(derivedKey.extractable).toBe(false);
expect<'secret'>(derivedKey.type).toBe('secret');
expect<1>(derivedKey.usages.length).toBe(1);
expect<['decrypt']>(derivedKey.usages).toEqual(['decrypt']);
});
it('should import a derived key for AES-GCM', async () => {
const baseKey = await importBaseKey(new Uint8Array([1, 2, 3, 4, 5]));
const derivedBits = await derive(baseKey, { salt: new Uint8Array([5, 4, 3, 2, 1]), iterations: 1000 });
const derivedKey = await importKey(derivedBits, { name: 'AES-GCM', length: 256 });
expect<256>(derivedKey.algorithm.length).toBe(256);
expect<'AES-GCM'>(derivedKey.algorithm.name).toBe('AES-GCM');
expect<false>(derivedKey.extractable).toBe(false);
expect<'secret'>(derivedKey.type).toBe('secret');
expect<['encrypt', 'decrypt'] | ['decrypt', 'encrypt']>(derivedKey.usages).toEqual(['encrypt', 'decrypt']);
});
});

View File

@@ -0,0 +1,87 @@
import { importRaw, getRandomValues, decryptBuffer, encryptBuffer, deriveBits, type IKey } from './shared';
type Algorithms = { name: 'AES-GCM'; length: 256 } | { name: 'AES-CBC'; length: 256 };
export type DerivedKey<TAlgorithm extends Algorithms = Algorithms> = IKey<
TAlgorithm,
false,
'secret',
TAlgorithm['name'] extends 'AES-CBC' ? ['decrypt'] : ['encrypt', 'decrypt']
>;
export type Options = {
salt: Uint8Array<ArrayBuffer>;
iterations: number;
};
export type EncryptedContent = {
iv: Uint8Array<ArrayBuffer>;
ciphertext: Uint8Array<ArrayBuffer>;
};
type Narrow<T, U extends { [P in keyof T]?: T[P] }> = {
[P in keyof T]: P extends keyof U ? U[P] : T[P];
};
export type BaseKey = IKey<
{
readonly name: 'PBKDF2';
},
false,
'secret',
['deriveBits']
>;
export const importBaseKey = async (keyData: Uint8Array<ArrayBuffer>): Promise<BaseKey> => {
const baseKey = await importRaw(keyData, { name: 'PBKDF2' }, false, ['deriveBits']);
return baseKey;
};
type Throws<F> = F extends (...args: infer TArgs) => infer TRet ? (...args: TArgs) => TRet & never : never;
type FixedSizeArrayBuffer<N extends number> = Narrow<
ArrayBuffer,
{
resize: Throws<ArrayBuffer['resize']>;
readonly byteLength: N;
get maxByteLength(): N;
get resizable(): false;
get detached(): false;
}
>;
export type DerivedBits = FixedSizeArrayBuffer<32>;
export const derive = async (key: BaseKey, options: Options): Promise<DerivedBits> => {
const bits = await deriveBits(
{ name: key.algorithm.name, hash: 'SHA-256', salt: options.salt, iterations: options.iterations },
key,
256,
);
return bits as DerivedBits;
};
export const importKey = async <T extends Algorithms>(derivedBits: DerivedBits, algorithm: T): Promise<DerivedKey<T>> => {
const usages: ['decrypt'] | ['encrypt', 'decrypt'] = algorithm.name === 'AES-CBC' ? ['decrypt'] : ['encrypt', 'decrypt'];
const key = await importRaw(derivedBits, algorithm satisfies AesKeyGenParams, false, usages);
return key as DerivedKey<T>;
};
export const decrypt = async (key: DerivedKey, content: EncryptedContent): Promise<Uint8Array<ArrayBuffer>> => {
const decrypted = await decryptBuffer(
key,
{ name: key.algorithm.name, iv: content.iv } satisfies AesCbcParams | AesGcmParams,
content.ciphertext,
);
return new Uint8Array(decrypted);
};
export const encrypt = async (
key: DerivedKey<{ name: 'AES-GCM'; length: 256 }>,
data: Uint8Array<ArrayBuffer>,
): Promise<EncryptedContent> => {
// Always use AES-GCM for new data
const iv = getRandomValues(new Uint8Array(12));
const ciphertext = await encryptBuffer(key, { name: 'AES-GCM', iv }, data);
return { iv, ciphertext: new Uint8Array(ciphertext) };
};

View File

@@ -0,0 +1,65 @@
import { generate, decrypt, encrypt, exportPublicKey, exportPrivateKey, importPrivateKey, importPublicKey, type KeyPair } from './rsa';
describe('rsa', () => {
let keyPair: KeyPair;
beforeAll(async () => {
keyPair = await generate();
});
it('generate a key pair with correct properties', async () => {
expect<'RSA-OAEP'>(keyPair.publicKey.algorithm.name).toBe('RSA-OAEP');
expect<2048>(keyPair.publicKey.algorithm.modulusLength).toBe(2048);
expect<true>(keyPair.publicKey.extractable).toBe(true);
expect<'public'>(keyPair.publicKey.type).toBe('public');
expect<1>(keyPair.publicKey.usages.length).toBe(1);
expect<['encrypt']>(keyPair.publicKey.usages).toEqual(['encrypt']);
expect<'RSA-OAEP'>(keyPair.privateKey.algorithm.name).toBe('RSA-OAEP');
expect<2048>(keyPair.privateKey.algorithm.modulusLength).toBe(2048);
expect<true>(keyPair.privateKey.extractable).toBe(true);
expect<'private'>(keyPair.privateKey.type).toBe('private');
expect<1>(keyPair.privateKey.usages.length).toBe(1);
expect<['decrypt']>(keyPair.privateKey.usages).toEqual(['decrypt']);
});
it('should encrypt and decrypt data correctly', async () => {
const plaintext = new TextEncoder().encode('Hello, RSA-OAEP!');
const ciphertext = await encrypt(keyPair.publicKey, plaintext);
const decrypted = await decrypt(keyPair.privateKey, ciphertext);
expect(new TextDecoder().decode(decrypted)).toBe('Hello, RSA-OAEP!');
});
it('should export and re-import the keys correctly', async () => {
const publicJwk = await exportPublicKey(keyPair.publicKey);
const privateJwk = await exportPrivateKey(keyPair.privateKey);
expect<'RSA-OAEP-256'>(publicJwk.alg).toBe('RSA-OAEP-256');
expect<'RSA'>(publicJwk.kty).toBe('RSA');
expect<true>(publicJwk.ext).toBe(true);
expect<'AQAB'>(publicJwk.e).toBe('AQAB');
expect<'RSA-OAEP-256'>(privateJwk.alg).toBe('RSA-OAEP-256');
expect<'RSA'>(privateJwk.kty).toBe('RSA');
expect<true>(privateJwk.ext).toBe(true);
expect<'AQAB'>(privateJwk.e).toBe('AQAB');
expect(privateJwk.n).toEqual(publicJwk.n);
const importedPublicKey = await importPublicKey(publicJwk);
expect<2048>(importedPublicKey.algorithm.modulusLength).toBe(2048);
expect<'RSA-OAEP'>(importedPublicKey.algorithm.name).toBe('RSA-OAEP');
expect<true>(importedPublicKey.extractable).toBe(true);
expect<'public'>(importedPublicKey.type).toBe('public');
expect<1>(importedPublicKey.usages.length).toBe(1);
expect<['encrypt']>(importedPublicKey.usages).toEqual(['encrypt']);
const importedPrivateKey = await importPrivateKey(privateJwk);
expect<2048>(importedPrivateKey.algorithm.modulusLength).toBe(2048);
expect<'RSA-OAEP'>(importedPrivateKey.algorithm.name).toBe('RSA-OAEP');
expect<true>(importedPrivateKey.extractable).toBe(true);
expect<'private'>(importedPrivateKey.type).toBe('private');
expect<1>(importedPrivateKey.usages.length).toBe(1);
expect<['decrypt']>(importedPrivateKey.usages).toEqual(['decrypt']);
});
});

View File

@@ -0,0 +1,109 @@
import { generateKeyPair, exportKey, importJwk, type IKeyPair, encryptBuffer, decryptBuffer } from './shared';
export type KeyPair = IKeyPair<
{
readonly name: 'RSA-OAEP';
readonly modulusLength: 2048;
readonly publicExponent: Uint8Array<ArrayBuffer>;
readonly hash: {
readonly name: 'SHA-256';
};
},
true,
['encrypt', 'decrypt']
>;
export type PublicKey = KeyPair['publicKey'];
export type PrivateKey = KeyPair['privateKey'];
export const generate = async (): Promise<KeyPair> => {
const keyPair = await generateKeyPair(
{
name: 'RSA-OAEP',
modulusLength: 2048,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: { name: 'SHA-256' },
},
true,
['encrypt', 'decrypt'],
);
return keyPair;
};
type Base64Url = string;
export interface IPublicJwk {
kty: 'RSA';
alg: 'RSA-OAEP-256';
e: 'AQAB';
ext: true;
key_ops: ['encrypt'];
n: Base64Url;
}
export interface IPrivateJwk {
kty: 'RSA';
alg: 'RSA-OAEP-256';
e: 'AQAB';
ext: true;
d: Base64Url;
dp: Base64Url;
dq: Base64Url;
key_ops: ['decrypt'];
n: Base64Url;
p: Base64Url;
q: Base64Url;
qi: Base64Url;
}
export const exportPublicKey = async (key: PublicKey): Promise<IPublicJwk> => {
const jwk = await exportKey('jwk', key);
return jwk as IPublicJwk;
};
export const exportPrivateKey = async (key: PrivateKey): Promise<IPrivateJwk> => {
const jwk = await exportKey('jwk', key);
return jwk as IPrivateJwk;
};
export const importPrivateKey = async (keyData: IPrivateJwk): Promise<PrivateKey> => {
const key = await importJwk(
keyData,
{
name: 'RSA-OAEP',
hash: { name: 'SHA-256' },
modulusLength: 2048,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
},
true,
['decrypt'],
);
return key as PrivateKey;
};
export const importPublicKey = async (keyData: IPublicJwk): Promise<PublicKey> => {
const key = await importJwk(
keyData,
{
name: 'RSA-OAEP',
hash: { name: 'SHA-256' },
modulusLength: 2048,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
},
true,
['encrypt'],
);
return key as PublicKey;
};
export const encrypt = async (key: PublicKey, data: BufferSource): Promise<Uint8Array<ArrayBuffer>> => {
const encrypted = await encryptBuffer(key, { name: key.algorithm.name }, data);
return new Uint8Array(encrypted);
};
export const decrypt = async (key: PrivateKey, data: BufferSource): Promise<Uint8Array<ArrayBuffer>> => {
const decrypted = await decryptBuffer(key, { name: key.algorithm.name }, data);
return new Uint8Array(decrypted);
};

View File

@@ -0,0 +1,141 @@
import { generateKey, generateKeyPair, exportKey, importJwk, encryptBuffer, decryptBuffer, getRandomValues } from './shared';
describe('Shared Crypto Functions', () => {
describe('generateKey', () => {
it('should generate an AES key with correct properties', async () => {
const key = await generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt', 'decrypt']);
expect<'AES-GCM'>(key.algorithm.name).toBe('AES-GCM');
expect<256>(key.algorithm.length).toBe(256);
expect<true>(key.extractable).toBe(true);
expect<'secret'>(key.type).toBe('secret');
expect<2>(key.usages.length).toBe(2);
expect<['encrypt', 'decrypt'] | ['decrypt', 'encrypt']>(key.usages).toEqual(expect.arrayContaining(['encrypt', 'decrypt']));
});
it('should export a key to JWK format', async () => {
const key = await generateKey({ name: 'AES-CBC', length: 128 }, true, ['encrypt']);
const exportedKey = await exportKey('jwk', key);
expect(Object.keys(exportedKey)).toHaveLength(5);
expect<true>(exportedKey.ext).toBe(true);
expect<'oct'>(exportedKey.kty).toBe('oct');
expect<string>(exportedKey.k).toHaveLength(22); // 128 bits in base64url
expect<`A128CBC`>(exportedKey.alg).toBe('A128CBC');
expect<['encrypt']>(exportedKey.key_ops).toEqual(['encrypt']);
});
});
describe('generateKeyPair', () => {
it('should generate an RSA key pair with correct properties', async () => {
const keyPair = await generateKeyPair(
{
name: 'RSA-OAEP',
modulusLength: 2048,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: { name: 'SHA-256' },
},
true,
['encrypt', 'decrypt'],
);
expect<'RSA-OAEP'>(keyPair.publicKey.algorithm.name).toBe('RSA-OAEP');
expect<2048>(keyPair.publicKey.algorithm.modulusLength).toBe(2048);
expect<true>(keyPair.publicKey.extractable).toBe(true);
expect<'public'>(keyPair.publicKey.type).toBe('public');
expect<1>(keyPair.publicKey.usages.length).toBe(1);
expect<['encrypt']>(keyPair.publicKey.usages).toEqual(['encrypt']);
expect<'RSA-OAEP'>(keyPair.privateKey.algorithm.name).toBe('RSA-OAEP');
expect<2048>(keyPair.privateKey.algorithm.modulusLength).toBe(2048);
expect<true>(keyPair.privateKey.extractable).toBe(true);
expect<'private'>(keyPair.privateKey.type).toBe('private');
expect<1>(keyPair.privateKey.usages.length).toBe(1);
expect<['decrypt']>(keyPair.privateKey.usages).toEqual(['decrypt']);
});
});
describe('importKey', () => {
it('should import an AES key from JWK format', async () => {
const key = await importJwk(
{
kty: 'oct' as const,
k: 'qb8In0Rpa9nwSusvxxDcbQ',
key_ops: ['encrypt', 'decrypt'] as const,
ext: true,
alg: 'A128CBC' as const,
},
{ name: 'AES-CBC', length: 128 },
true,
['encrypt', 'decrypt'],
);
expect<128>(key.algorithm.length).toBe(128);
expect<'AES-CBC'>(key.algorithm.name).toBe('AES-CBC');
expect<true>(key.extractable).toBe(true);
expect<'secret'>(key.type).toBe('secret');
expect<2>(key.usages.length).toBe(2);
expect<['encrypt', 'decrypt'] | ['decrypt', 'encrypt']>(key.usages).toEqual(expect.arrayContaining(['encrypt', 'decrypt']));
});
});
describe('exportKey', () => {
it('should export an RSA public key to JWK format', async () => {
const keyPair = await generateKeyPair(
{
name: 'RSA-OAEP',
modulusLength: 2048,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: { name: 'SHA-256' },
},
true,
['encrypt', 'decrypt'],
);
const exportedKey = await exportKey('jwk', keyPair.publicKey);
expect(Object.keys(exportedKey).toSorted()).toEqual(['alg', 'e', 'ext', 'key_ops', 'kty', 'n'].toSorted());
expect<true>(exportedKey.ext).toBe(true);
expect<'RSA'>(exportedKey.kty).toBe('RSA');
expect<`RSA-OAEP-256`>(exportedKey.alg).toBe('RSA-OAEP-256');
expect<['encrypt']>(exportedKey.key_ops).toEqual(['encrypt']);
expect<string>(exportedKey.n).toBeDefined();
expect<string>(exportedKey.e).toBeDefined();
});
it('should export an RSA private key to JWK format', async () => {
const keyPair = await generateKeyPair(
{
name: 'RSA-OAEP',
modulusLength: 2048,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: { name: 'SHA-256' },
},
true,
['encrypt', 'decrypt'],
);
const exportedKey = await exportKey('jwk', keyPair.privateKey);
expect(Object.keys(exportedKey).toSorted()).toEqual(
['alg', 'd', 'dp', 'dq', 'e', 'ext', 'key_ops', 'kty', 'n', 'p', 'q', 'qi'].toSorted(),
);
expect<true>(exportedKey.ext).toBe(true);
expect<'RSA'>(exportedKey.kty).toBe('RSA');
expect<`RSA-OAEP-256`>(exportedKey.alg).toBe('RSA-OAEP-256');
expect<['decrypt']>(exportedKey.key_ops).toEqual(['decrypt']);
expect<string>(exportedKey.n).toBeDefined();
expect<string>(exportedKey.e).toBeDefined();
expect<string>(exportedKey.d).toBeDefined();
expect<string>(exportedKey.p).toBeDefined();
expect<string>(exportedKey.q).toBeDefined();
expect<string>(exportedKey.dp).toBeDefined();
expect<string>(exportedKey.dq).toBeDefined();
expect<string>(exportedKey.qi).toBeDefined();
});
});
describe('encryptBuffer', () => {
it('should encrypt and decrypt data correctly', async () => {
const key = await generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt', 'decrypt']);
const plaintext = new TextEncoder().encode('Test encryption');
const iv = getRandomValues(new Uint8Array(12));
const ciphertext = await encryptBuffer(key, { name: 'AES-GCM', iv }, plaintext);
const decrypted = await decryptBuffer(key, { name: 'AES-GCM', iv }, ciphertext);
expect(new TextDecoder().decode(decrypted)).toBe('Test encryption');
});
});
});

View File

@@ -0,0 +1,198 @@
const { subtle } = crypto;
export const randomUUID = () => crypto.randomUUID();
export const getRandomValues = crypto.getRandomValues.bind(crypto);
interface IAesGcmParams extends AesGcmParams {
name: 'AES-GCM';
}
interface IAesCbcParams extends AesCbcParams {
name: 'AES-CBC';
}
interface IAesCtrParams extends AesCtrParams {
name: 'AES-CTR';
}
interface IRsaOaepParams extends RsaOaepParams {
name: 'RSA-OAEP';
}
type ParamsMap = {
'AES-GCM': IAesGcmParams;
'AES-CTR': IAesCtrParams;
'AES-CBC': IAesCbcParams;
'RSA-OAEP': IRsaOaepParams;
};
type ParamsOf<TKey extends IKey> = TKey['algorithm'] extends { name: infer TName extends keyof ParamsMap } ? ParamsMap[TName] : never;
type HasUsage<TKey extends IKey, TUsage extends KeyUsage> = TUsage extends TKey['usages'][number]
? TKey
: TKey & `The provided key cannot be used for ${TUsage}`;
export const encryptBuffer = <TKey extends IKey, TParams extends ParamsOf<TKey>>(
key: HasUsage<TKey, 'encrypt'>,
params: TParams,
data: BufferSource,
): Promise<ArrayBuffer> => subtle.encrypt(params, key, data);
export const decryptBuffer = <TKey extends IKey>(
key: HasUsage<TKey, 'decrypt'>,
params: ParamsOf<TKey>,
data: BufferSource,
): Promise<ArrayBuffer> => subtle.decrypt(params, key, data);
export const deriveBits = (...args: Parameters<typeof subtle.deriveBits>) => subtle.deriveBits(...args);
type AesParams = {
name: 'AES-CBC' | 'AES-GCM' | 'AES-CTR';
length: 128 | 256;
};
type ModeOf<T extends `AES-${'CBC' | 'GCM' | 'CTR'}`> = T extends `AES-${infer Mode}` ? Mode : never;
type Permutations<T> = T extends [infer First]
? [First]
: T extends [infer First, infer Second]
? [First, Second] | [Second, First]
: never;
export interface IKey<
TAlgorithm extends CryptoKey['algorithm'] = CryptoKey['algorithm'],
TExtractable extends CryptoKey['extractable'] = CryptoKey['extractable'],
TType extends CryptoKey['type'] = CryptoKey['type'],
TUsages extends CryptoKey['usages'] = CryptoKey['usages'],
> extends CryptoKey {
readonly algorithm: TAlgorithm;
readonly extractable: TExtractable;
readonly type: TType;
readonly usages: Permutations<TUsages>;
}
export async function generateKey<
const T extends AesParams,
const TExtractable extends boolean = boolean,
const TUsages extends KeyUsage[] = KeyUsage[],
>(algorithm: T, extractable: TExtractable, keyUsages: TUsages): Promise<IKey<T, TExtractable, 'secret', TUsages>> {
const key = await subtle.generateKey(algorithm, extractable, keyUsages);
return key as IKey<T, TExtractable, 'secret', TUsages>;
}
type Filter<TItem extends KeyUsage, TArray extends KeyUsage[], Out extends KeyUsage[] = []> = TArray extends [
infer First extends KeyUsage,
...infer Rest extends KeyUsage[],
]
? First extends TItem
? Filter<TItem, Rest, [...Out, First]>
: Filter<TItem, Rest, Out>
: Out;
export interface IKeyPair<
T extends KeyAlgorithm = KeyAlgorithm,
TExtractable extends boolean = boolean,
TUsages extends KeyUsage[] = KeyUsage[],
> extends CryptoKeyPair {
publicKey: IKey<T, TExtractable, 'public', Filter<'encrypt', TUsages>>;
privateKey: IKey<T, TExtractable, 'private', Filter<'decrypt', TUsages>>;
}
type RsaParams = {
name: 'RSA-OAEP';
modulusLength: 2048;
publicExponent: Uint8Array<ArrayBuffer>;
hash: { name: 'SHA-256' };
};
export async function generateKeyPair<
const T extends RsaParams,
const TExtractable extends boolean = boolean,
const TUsages extends KeyUsage[] = KeyUsage[],
>(algorithm: T, extractable: TExtractable, keyUsages: TUsages): Promise<IKeyPair<T, TExtractable, TUsages>> {
const keyPair = await subtle.generateKey(algorithm, extractable, keyUsages);
return keyPair as IKeyPair<T, TExtractable, TUsages>;
}
type KeyToJwk<T extends IKey> = T['extractable'] extends false
? never
: T['algorithm'] extends AesParams
? {
kty: 'oct';
alg: `A${T['algorithm']['length']}${ModeOf<T['algorithm']['name']>}`;
ext: true;
k: string;
key_ops: T['usages'];
}
: [T['algorithm'], T['type']] extends [RsaParams, 'public']
? {
kty: 'RSA';
alg: 'RSA-OAEP-256';
e: string;
ext: true;
key_ops: T['usages'];
n: string;
}
: [T['algorithm'], T['type']] extends [RsaParams, 'private']
? {
kty: 'RSA';
alg: 'RSA-OAEP-256';
e: string;
ext: true;
d: string;
dp: string;
dq: string;
key_ops: T['usages'];
n: string;
p: string;
q: string;
qi: string;
}
: never;
export type Exported<TFormat extends KeyFormat, TKey extends IKey = IKey> = TFormat extends 'jwk' ? KeyToJwk<TKey> : ArrayBuffer;
export async function exportKey<const TFormat extends KeyFormat = KeyFormat, const TKey extends IKey = IKey>(
format: TFormat,
key: TKey,
): Promise<Exported<TFormat, TKey>> {
const exportedKey = await subtle.exportKey(format, key);
return exportedKey as Exported<TFormat, TKey>;
}
type KtyParams = {
oct: AesParams;
RSA: RsaParams;
};
export async function importJwk<
const TKeyData extends JsonWebKey,
const TAlgorithm extends (TKeyData extends { kty: infer Kty extends keyof KtyParams } ? KtyParams[Kty] : KeyAlgorithm),
const TExtractable extends boolean = boolean,
const TUsages extends KeyUsage[] = KeyUsage[],
const TKeyType extends KeyType = TKeyData extends { kty: 'oct' }
? 'secret'
: TKeyData extends { kty: 'RSA'; key_ops: [infer Op] }
? Op extends 'encrypt'
? 'public'
: 'private'
: KeyType,
>(
jwk: TKeyData,
algorithm: TAlgorithm,
extractable: TExtractable,
keyUsages: TUsages,
): Promise<IKey<TAlgorithm, TExtractable, TKeyType, TUsages>> {
const key = await subtle.importKey('jwk', jwk, algorithm, extractable, keyUsages);
return key as IKey<TAlgorithm, TExtractable, TKeyType, TUsages>;
}
export async function importRaw<
const TAlgorithm extends KeyAlgorithm = KeyAlgorithm,
const TExtractable extends boolean = boolean,
const TUsages extends KeyUsage[] = KeyUsage[],
>(
rawKey: BufferSource,
algorithm: TAlgorithm,
extractable: TExtractable,
keyUsages: TUsages,
): Promise<IKey<TAlgorithm, TExtractable, 'secret', TUsages>> {
const key = await subtle.importKey('raw', rawKey, algorithm, extractable, keyUsages);
return key as IKey<TAlgorithm, TExtractable, 'secret', TUsages>;
}

View File

@@ -0,0 +1,53 @@
export async function encryptAESCTR(counter: BufferSource, key: CryptoKey, data: BufferSource) {
return crypto.subtle.encrypt({ name: 'AES-CTR', counter, length: 64 }, key, data);
}
export function generateAESCTRKey(): Promise<CryptoKey> {
return crypto.subtle.generateKey({ name: 'AES-CTR', length: 256 }, true, ['encrypt', 'decrypt']);
}
/**
* Generates 12 uniformly random words from the word list.
*
* @remarks
* Uses {@link https://en.wikipedia.org/wiki/Rejection_sampling | rejection sampling} to ensure uniform distribution.
*
* @returns A space-separated passphrase.
*/
export async function generatePassphrase() {
const { wordlist } = await import('./wordList');
// Number of words in the passphrase
const WORD_COUNT = 12;
// We use 32-bit random numbers, so the maximum value is 2^32 - 1
const MAX_UINT32 = 0xffffffff;
const range = wordlist.length;
const rejectionThreshold = Math.floor(MAX_UINT32 / range) * range;
const words: string[] = [];
const buf = new Uint32Array(1);
for (let i = 0; i < WORD_COUNT; i++) {
let v: number;
do {
crypto.getRandomValues(buf);
v = buf[0];
} while (v >= rejectionThreshold);
words.push(wordlist[v % range]);
}
return words.join(' ');
}
export async function createSha256HashFromText(data: string) {
const hash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(data));
return Array.from(new Uint8Array(hash))
.map((b) => b.toString(16).padStart(2, '0'))
.join('');
}
export async function sha256HashFromArrayBuffer(arrayBuffer: ArrayBuffer) {
const hashArray = Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', arrayBuffer)));
return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
}

View File

@@ -0,0 +1 @@
export * from './rocketchat.e2e';

View File

@@ -0,0 +1,57 @@
import { Keychain } from './keychain';
describe('Keychain', () => {
/**
* Calculates the length of a base64-encoded string given the length of the original byte array.
*
* @param byteLength The length of the byte array to be encoded.
* @returns The length of the resulting base64-encoded string.
*/
const base64Length = (byteLength: number) => {
return ((4 * byteLength) / 3 + 3) & ~3;
};
const pwdv1web = {
userId: 'userE2EE',
persisted:
'{"$binary":"JtJhD4JHyNS5dnf5+qj1IxbEGa6bmxlgvX6r0+LhvbnD15KmyTN/HBi0qip4GYJaolVhk7Y5YuB5qT/cRxKv6+2Qe+4Rc6DorInx1+V2tdI2JWkQoVi91GpN7ezy8ghOJ5nbsPn4xkv8jVZU2itAIAuqurKvL1hPUMsGsSnxazC6zEsInv0R/9Y2sdtm5L6ISSjo6iIqUaUEPw0gqt6y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m_Hyhlnh4etNlHEiCXBzJWbqMwOZ6pz_JuZY2HiqbLmSfBtpvwBKZvcmP92BqLl-qZuLV_bJD_11UBS3gR6ykgU-RsTz1L-V8vA2QZEyULP4DqkMcRCV_7WE_sn_ScePgKszx1284gnngct_1Tv37zB6Ifz7gb1THRwAqOGcE2htea4yQEhyX8ZAl_-95DTWLbXqEAuofqDpXMcQo487VezBWIaDdfw2VX0qi6kM-pt03Gx8uMniyAjhK1G8Dro3wgAtz4PNIwOsdXEvWTSyoXLVMsIuZeO9OGdJKXnZFtVEMzXLyQTD1LjXlsM_TF09fbkN41Tz12ojmQ","p":"0GJaXeKlxgcz6pX0DdwtWG38x9vN2wfLrN3F8N_0stzyPMjMpLGXOdGq1k1V6FROYvLHZsqdCpziwJ3a1PQaGUg2lO-KeBghlbDk4xfYbzSSPhVdwvUT27dysd3-_TsBvNpVCqCLb9Wgl8f0jrrRmRTSztYSLw3ckL939OJoe0M","q":"0AOMQqdGlz0Tm81uqpzCuQcQLMj-IhmPIMuuTnIU55KCmEwmlf0mkgesj-EEBsC1h6ScC5fvznGNvSGqVQAP5ANNZxGiB73q-2YgH3FpuEeHekufl260E_9tgIuqjtCv-eT_cLUhnRNyuP2ZiqRZsBWLuaQYkTubyGRi6izoofM","qi":"FXbIXivKdh0VBgMtLe5f1OjzyrSW_IfIvz8ZM66F4tUTxnNKk5vSb_q2NPyIOVYbdonuVguX-0VO54Ct16k8VdpQSMmUxGbyQAtIck2IzEzpfbRJgn06wiAI3j8q1nRFhrzhfrpJWVyuTiXBgaeOLWBz8fBpjDU7rptmcoU3tZ4"}',
passphrase: 'minus mobile dexter forest elvis',
};
test('decrypt v1 private key', async () => {
const keychain = new Keychain(pwdv1web.userId);
const decrypted = await keychain.decryptKey(pwdv1web.persisted, pwdv1web.passphrase);
expect(decrypted).toBe(pwdv1web.private_key);
const encrypted = await keychain.encryptKey(decrypted, pwdv1web.passphrase);
expect(encrypted.iv).toHaveLength(base64Length(12));
});
const pwdv2web: typ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xApFuaxGjsnufe1QY9jitSo8SPGBmcFfZOWdNgtEHK3HfrrSH30H4aMI9wRcbni36RjeRo9LjRgcPFeTljLo44323EjWk1UJ4P+h+zz5LLjXEFDKLPUyFe+AA/blisN1XRbwpvmAWBPVrZuZ4s=","salt":"v2:BFqA4FAHKX4qEywfJ:5b36c4cc-4e7a-497d-b4b0-a1df863c65c4","iterations":100000}',
public_key:
'{"alg":"RSA-OAEP-256","e":"AQAB","ext":true,"key_ops":["encrypt"],"kty":"RSA","n":"r0NSQ6ZOz2F-lXBRTwGBACu5dih-wQBDGf7gkvTASzqtC545BNRjLO9aGbhma-zBUc8JSJdZzpJUiKx0vHh9RG_RjE5znE9HgK66J1lSJNJQMjM0WZSRs1C95A-93k_MwrwJmIoWVr3a1xlOw1eO0Fwc0pr4LQsIDnfrkmxZQJTlzQXoetFlZv4HmJlM0yeMoeBBgMo-ZNKSJW_MtlwbV6SXpHLYE9I1bWO8ooIi84J8xGsjmHK3DAdmD_wNqISFK4Da3YoNSlPa_jdakAYy3nhlR0DEzz_bcxb_jXwpAH3G2DCMEYwRSap25ZytXVfN9mOkT7NYEMiVVdH4nrBEYQ"}',
private_key:
'{"alg":"RSA-OAEP-256","d":"BfaLapcFxwaKxDjeSCR4wb6H5xF5QCw36QvqX8JvqUX_NA4xFtn6RqgdVhMXep3DW641cA1xb8oIxRGt2YL1kb0gN97fdINtOMXSumebZODtYf5EZ-inJtIdDXcy2MjsSMZIqUwuQ5gRq90SxSpKE9eRrEfuuh5nxF5BWwNp65ZW4rCsEiInmnrFW4ERtyTHJ1catbJ_lj71lcVzC-1St6jeXcdinG2FtH0hJ4_ijzp6sAqm1xC9XMhF2g4tZeyvVg9dGBzyLyxq78zNAPJ93ungjc0ITJ27g3IaP7EUX7SxjHasU37j7KOIOGmTswkxIEoVQrlep6xU1RFkPphJNQ","dp":"sJhWI8YfVUr1N5vTr255xJ3Bo84320NWAl9MUhd87XoV3soGO0lmC1bYdrNvIU7wjJ3PxdpSrJ2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Mpk6w4pqkIdmnSSw19feNCXDv4QHFv4eSsTvBD8g_zmwIkMFyJzeC34J5bgafteZ1RpXsxN5CAAjyhJObEll3CY9B9zZTCLuZDr_616RWDvK1_w4"}',
passphrase: 'prize fluid crystal small jaguar lunar bonus absent destroy settle carbon ignore',
};
test('decrypt v2 private key', async () => {
const keychain = new Keychain(pwdv2web.userId);
const decrypted = await keychain.decryptKey(pwdv2web.persisted, pwdv2web.passphrase);
expect(decrypted).toBe(pwdv2web.private_key);
});
test('roundtrip v2 private key', async () => {
const keychain = new Keychain(pwdv2web.userId);
const decrypted = await keychain.decryptKey(pwdv2web.persisted, pwdv2web.passphrase);
expect(decrypted).toBe(pwdv2web.private_key);
const encrypted = await keychain.encryptKey(decrypted, pwdv2web.passphrase);
expect(encrypted.iv).toHaveLength(base64Length(12));
});
});

View File

@@ -0,0 +1,163 @@
import { Base64 } from '@rocket.chat/base64';
import { Binary } from './binary';
import type { ICodec } from './codec';
import * as Pbkdf2 from './crypto/pbkdf2';
import { randomUUID } from './crypto/shared';
/**
* Version 1 format:
* ```
* json({ $binary: base64(iv[16] + ciphertext) })
* ```
*/
interface IStoredKeyV1 {
/**
* Base64-encoded binary data
* - first 16 bytes are the IV
* - remaining bytes are the ciphertext
*/
$binary: string;
}
/**
* Version 2 format:
* ```typescript
* json({ iv: base64(iv[12]), ciphertext: base64(data[...]), salt: string(), iterations: number() })
* ```
*/
interface IStoredKeyV2 {
iv: string;
ciphertext: string;
salt: string;
iterations: number;
}
type StoredKey = IStoredKeyV1 | IStoredKeyV2;
// eslint-disable-next-line @typescript-eslint/no-redeclare
const StoredKey: ICodec<string, StoredKey> = {
decode: (data) => {
const json: unknown = JSON.parse(data);
if (typeof json !== 'object' || json === null) {
throw new TypeError('Invalid private key format');
}
if ('$binary' in json && typeof json.$binary === 'string') {
return { $binary: json.$binary } satisfies IStoredKeyV1;
}
if (
'iv' in json &&
typeof json.iv === 'string' &&
'ciphertext' in json &&
typeof json.ciphertext === 'string' &&
'salt' in json &&
typeof json.salt === 'string' &&
'iterations' in json &&
typeof json.iterations === 'number'
) {
return { iv: json.iv, ciphertext: json.ciphertext, salt: json.salt, iterations: json.iterations } satisfies IStoredKeyV2;
}
throw new TypeError('Invalid private key format');
},
encode: (data) => JSON.stringify(data),
};
type EncryptedKeyContent = {
iv: Uint8Array<ArrayBuffer>;
ciphertext: Uint8Array<ArrayBuffer>;
};
type EncryptedKeyOptions = {
salt: string;
iterations: number;
};
type EncryptedKey = {
content: EncryptedKeyContent;
options: EncryptedKeyOptions;
};
class EncryptedKeyCodec implements ICodec<string, EncryptedKey, IStoredKeyV2> {
userId: string;
constructor(userId: string) {
this.userId = userId;
}
encode(encryptedKey: EncryptedKey): IStoredKeyV2 {
return {
iv: Base64.encode(encryptedKey.content.iv),
ciphertext: Base64.encode(encryptedKey.content.ciphertext),
salt: encryptedKey.options.salt,
iterations: encryptedKey.options.iterations,
};
}
decode(storedKey: string): EncryptedKey {
const storedKeyObj = StoredKey.decode(storedKey);
if ('$binary' in storedKeyObj) {
// v1
const binary = Base64.decode(storedKeyObj.$binary);
return {
content: { iv: binary.slice(0, 16), ciphertext: binary.slice(16) },
options: {
salt: this.userId,
iterations: 1000,
},
};
}
// v2
const { iv, ciphertext, salt, iterations } = storedKeyObj;
return {
content: {
iv: Base64.decode(iv),
ciphertext: Base64.decode(ciphertext),
},
options: {
salt,
iterations,
},
};
}
}
export class Keychain {
private readonly userId: string;
private readonly codec: EncryptedKeyCodec;
constructor(userId: string) {
this.userId = userId;
this.codec = new EncryptedKeyCodec(userId);
}
async decryptKey(privateKey: string, password: string): Promise<string> {
const { content, options } = this.codec.decode(privateKey);
const algorithm = content.iv.length === 16 ? 'AES-CBC' : 'AES-GCM';
const baseKey = await Pbkdf2.importBaseKey(new Uint8Array(Binary.decode(password)));
const derivedBits = await Pbkdf2.derive(baseKey, {
salt: new Uint8Array(Binary.decode(options.salt)),
iterations: options.iterations,
});
const key = await Pbkdf2.importKey(derivedBits, { name: algorithm, length: 256 });
const decrypted = await Pbkdf2.decrypt(key, content);
return Binary.encode(decrypted.buffer);
}
async encryptKey(privateKey: string, password: string): Promise<IStoredKeyV2> {
const salt = `v2:${this.userId}:${randomUUID()}`;
const iterations = 100_000;
const algorithm = 'AES-GCM';
const baseKey = await Pbkdf2.importBaseKey(new Uint8Array(Binary.decode(password)));
const derivedBits = await Pbkdf2.derive(baseKey, { salt: new Uint8Array(Binary.decode(salt)), iterations });
const key = await Pbkdf2.importKey(derivedBits, { name: algorithm, length: 256 });
const content = await Pbkdf2.encrypt(key, new Uint8Array(Binary.decode(privateKey)));
return this.codec.encode({ content, options: { salt, iterations } });
}
}

View File

@@ -0,0 +1,100 @@
import { getConfig } from '../utils/getConfig';
let debug: boolean | undefined = undefined;
const isDebugEnabled = (): boolean => {
if (debug === undefined) {
debug = getConfig('debug') === 'true' || getConfig('debug-e2e') === 'true';
}
return debug;
};
const noopSpan: ISpan = {
set(_key: string, _value: unknown) {
return this;
},
info(_message: string) {
/**/
},
warn(_message: string) {
/**/
},
error(_message: string, _error?: unknown) {
/**/
},
};
class Logger {
title: string;
constructor(title: string) {
this.title = title;
}
span(label: string): ISpan {
return isDebugEnabled() ? new Span(new WeakRef(this), label, console) : noopSpan;
}
}
interface ISpan {
set(key: string, value: unknown): this;
info(message: string): void;
warn(message: string): void;
error(message: string, error?: unknown): void;
}
type LogLevel = 'info' | 'warn' | 'error';
const styles: Record<LogLevel, string> = {
info: 'font-weight: bold;',
warn: 'color: black; background-color: yellow; font-weight: bold;',
error: 'color: white; background-color: red; font-weight: bold;',
};
class Span {
private logger: WeakRef<Logger>;
private label: string;
private attributes = new Map<string, unknown>();
private console: Console;
constructor(logger: WeakRef<Logger>, label: string, console: Console) {
this.logger = logger;
this.label = label;
this.console = console;
}
private log(level: LogLevel, message: string) {
this.console.groupCollapsed(`%c[${this.logger.deref()?.title}:${this.label}]%c ${message}`, styles[level], 'font-weight: normal;');
this.console.dir(Object.fromEntries(this.attributes.entries()), {});
this.console.trace();
this.console.groupEnd();
}
set(key: string, value: unknown) {
this.attributes.set(key, value);
return this;
}
info(message: string) {
this.log('info', message);
}
warn(message: string) {
this.log('warn', message);
}
error(message: string, error?: unknown) {
if (error) {
this.set('error', error);
}
this.log('error', message);
}
}
export const createLogger = (title: string) => {
return new Logger(title);
};

View File

@@ -0,0 +1,39 @@
import { Base64 } from '@rocket.chat/base64';
import { PrefixedBase64 } from './prefixed';
const prefix = '32c9e7917b78';
const base64 =
'ibtLAKG9zcQ/NTp+86nVelUjewPbPNW+EC+eagVPVVlbxvWNXkgltrBQB4gDao1Fp6fHUibQB3dirJ4rzy7CViww0o4QjAwPPQMIxZ9DLJhjKnu6bkkOp6Z0/a9g/8Wf/cvP9/bp7tUt7Et4XMmJwIe5iyJZ35lsyduLc8V+YyK8sJiGf4BRagJoBr8xEBgqBWqg6Vwn3qtbbiTs65PqErbaUmSM3Hn6tfkcS6ukLG/DbptW1B9U66IX3fQesj50zWZiJyvxOoxDeHRH9UEStyv9SP8nrFjEKM3TDiakBeDxja6LoN8l3CjP9K/5eg25YqANZAQjlwaCaeTTHndTgQ==';
const prefixed = `${prefix}${base64}`;
describe('PrefixedBase64', () => {
it('should roundtrip', () => {
const [kid, decodedKey] = PrefixedBase64.decode(prefixed);
expect(kid).toBe(prefix);
const reencoded = PrefixedBase64.encode([kid, decodedKey]);
expect(reencoded).toBe(prefixed);
});
it('should throw on invalid decode input length', () => {
expect(() => PrefixedBase64.decode('too-short')).toThrow(RangeError);
});
it('should throw on invalid decoded data length', () => {
const invalidPrefixed = `32c9e7917b78${'A'.repeat(343)}`; // One character short
expect(() => PrefixedBase64.decode(invalidPrefixed)).toThrow(RangeError);
});
it('should throw on invalid encode input data length', () => {
const invalidData = new Uint8Array(255); // One byte short
expect(() => PrefixedBase64.encode([prefix, invalidData])).toThrow(RangeError);
});
it('should throw on invalid encoded Base64 length', () => {
// This is a bit contrived since our encode implementation always produces valid length,
// but we include it for completeness.
const invalidData = new Uint8Array(256);
jest.spyOn(Base64, 'encode').mockReturnValue('A'.repeat(343)); // One character short
expect(() => PrefixedBase64.encode([prefix, invalidData])).toThrow(RangeError);
});
});

View File

@@ -0,0 +1,55 @@
import { Base64 } from '@rocket.chat/base64';
import type { ICodec } from './codec';
// A 256-byte array always encodes to 344 characters in Base64.
const DECODED_LENGTH = 256;
// ((4 * 256 / 3) + 3) & ~3 = 344
const ENCODED_LENGTH = 344;
/**
* A codec for strings formatted as "prefix + base64(data)", where:
* - `prefix` is an arbitrary-length string
* - `data` is a 256-byte Uint8Array encoded in Base64
* - the total length of the Base64-encoded data is always 344 characters
* This is used for encoding/decoding E2EE keys with a key ID prefix.
*/
export const PrefixedBase64: ICodec<string, [prefix: string, data: Uint8Array<ArrayBuffer>]> = {
decode: (input) => {
// 1. Validate the input string length
if (input.length < ENCODED_LENGTH) {
throw new RangeError('Invalid input length.');
}
// 2. Split the string into its two parts
const prefix = input.slice(0, -ENCODED_LENGTH);
const base64Data = input.slice(-ENCODED_LENGTH);
// 3. Decode the Base64 string. atob() decodes to a "binary string".
const bytes = Base64.decode(base64Data);
if (bytes.length !== DECODED_LENGTH) {
// This is a sanity check in case the Base64 string was valid but didn't decode to 256 bytes.
throw new RangeError('Decoded data length is too short.');
}
return [prefix, bytes];
},
encode: ([prefix, data]) => {
// 1. Validate the input data length
if (data.length !== DECODED_LENGTH) {
throw new RangeError(`Input data length is ${data.length}, but expected ${DECODED_LENGTH} bytes.`);
}
// 2. Convert the byte array (Uint8Array) into a Base64 string
const base64 = Base64.encode(data);
if (base64.length !== ENCODED_LENGTH) {
// This is a sanity check in case something went wrong during encoding.
throw new RangeError(`Encoded Base64 length is ${base64.length}, but expected ${ENCODED_LENGTH} characters.`);
}
// 3. Concatenate the prefix and the Base64 string
return prefix + base64;
},
};

View File

@@ -0,0 +1,81 @@
import * as Aes from './crypto/aes';
import { E2ERoom } from './rocketchat.e2e.room';
import { sdk } from '../SDKClient';
jest.mock('./crypto/aes');
jest.mock('../../../client/lib/SDKClient', () => ({
sdk: { rest: { post: jest.fn() } },
}));
jest.mock('../../../app/utils/rocketchat.info', () => ({
Info: { version: '8.7.0' },
}));
class FakeResponse {
constructor(
private readonly body: unknown,
public readonly status = 400,
) {}
clone() {
return this;
}
async json() {
return this.body;
}
}
(global as any).Response = FakeResponse;
const makeRoom = () => new E2ERoom('user-1', { _id: 'room-1', t: 'p', encrypted: true } as any);
describe('E2ERoom.createGroupKey', () => {
beforeEach(() => {
jest.clearAllMocks();
(Aes.generate as jest.Mock).mockResolvedValue('group-key');
(Aes.exportJwk as jest.Mock).mockResolvedValue({ k: 'jwk' });
});
afterEach(() => {
jest.restoreAllMocks();
});
it('should discard the local key and not distribute it when it loses the race', async () => {
(sdk.rest.post as jest.Mock).mockRejectedValueOnce(
new (global as any).Response({ success: false, errorType: 'error-room-e2e-key-already-exists' }),
);
const e2eRoom = makeRoom();
const result = await e2eRoom.createGroupKey();
expect(result).toBe(false);
expect(e2eRoom.groupSessionKey).toBeNull();
expect(e2eRoom.keyID).toBeUndefined();
expect(sdk.rest.post).toHaveBeenCalledTimes(1); // only setRoomKeyID was called
expect(sdk.rest.post).toHaveBeenCalledWith('/v1/e2e.setRoomKeyID', { rid: e2eRoom.roomId, keyID: expect.any(String) });
});
it('should return true and distribute the key when it wins the race', async () => {
(sdk.rest.post as jest.Mock).mockResolvedValue({});
jest.spyOn(E2ERoom.prototype as any, 'encryptGroupKeyForParticipant').mockResolvedValue('mykey');
const encryptForOthersSpy = jest.spyOn(E2ERoom.prototype as any, 'encryptKeyForOtherParticipants').mockResolvedValue(undefined);
const e2eRoom = makeRoom();
const result = await e2eRoom.createGroupKey();
expect(result).toBe(true);
expect(e2eRoom.groupSessionKey).not.toBeNull();
expect(sdk.rest.post).toHaveBeenCalledWith('/v1/e2e.setRoomKeyID', {
rid: e2eRoom.roomId,
keyID: expect.any(String),
});
expect(sdk.rest.post).toHaveBeenCalledWith('/v1/e2e.updateGroupKey', {
rid: e2eRoom.roomId,
uid: e2eRoom.userId,
key: 'mykey',
});
expect(encryptForOthersSpy).toHaveBeenCalledTimes(1);
expect(sdk.rest.post).toHaveBeenCalledTimes(2); // both setRoomKeyID and updateGroupKey are called
});
});

View File

@@ -0,0 +1,846 @@
import { Base64 } from '@rocket.chat/base64';
import type {
IE2EEMessage,
IMessage,
IRoom,
ISubscription,
IUser,
AtLeast,
EncryptedMessageContent,
EncryptedContent,
} from '@rocket.chat/core-typings';
import { isEncryptedMessageContent, isFileAttachment, isRemovedFileAttachment } from '@rocket.chat/core-typings';
import { Emitter } from '@rocket.chat/emitter';
import type { Optional } from '@tanstack/react-query';
import EJSON from 'ejson';
import type { E2ERoomState } from './E2ERoomState';
import { Binary } from './binary';
import { decodeEncryptedContent } from './content';
import * as Aes from './crypto/aes';
import * as Rsa from './crypto/rsa';
import { encryptAESCTR, generateAESCTRKey, sha256HashFromArrayBuffer, createSha256HashFromText } from './helper';
import { createLogger } from './logger';
import { PrefixedBase64 } from './prefixed';
import { e2e } from './rocketchat.e2e';
import { t } from '../../../app/utils/lib/i18n';
import { RoomSettingsEnum } from '../../../definition/IRoomTypeConfig';
import { Messages, Rooms, Subscriptions } from '../../stores';
import { sdk } from '../SDKClient';
import { roomCoordinator } from '../rooms/roomCoordinator';
const log = createLogger('E2E:Room');
const KEY_ID = Symbol('keyID');
const PAUSED = Symbol('PAUSED');
const isRoomKeyAlreadyExistsError = async (error: Response): Promise<boolean> => {
try {
const body = await error.clone().json();
return body?.errorType === 'error-room-e2e-key-already-exists';
} catch {
return false;
}
};
type Mutations = { [k in E2ERoomState]?: E2ERoomState[] };
const permitedMutations: Mutations = {
NOT_STARTED: ['ESTABLISHING', 'DISABLED', 'KEYS_RECEIVED'],
READY: ['DISABLED', 'CREATING_KEYS', 'WAITING_KEYS'],
ERROR: ['KEYS_RECEIVED', 'NOT_STARTED'],
WAITING_KEYS: ['KEYS_RECEIVED', 'ERROR', 'DISABLED'],
ESTABLISHING: ['READY', 'KEYS_RECEIVED', 'ERROR', 'DISABLED', 'WAITING_KEYS', 'CREATING_KEYS'],
};
const filterMutation = (currentState: E2ERoomState | undefined, nextState: E2ERoomState): E2ERoomState | false => {
// When state is undefined, allow it to be moved
if (!currentState) {
return nextState;
}
if (currentState === nextState) {
return nextState === 'ERROR' ? 'ERROR' : false;
}
if (!(currentState in permitedMutations)) {
return nextState;
}
if (permitedMutations?.[currentState]?.includes(nextState)) {
return nextState;
}
return false;
};
export class E2ERoom extends Emitter {
state: E2ERoomState | undefined = undefined;
[PAUSED]: boolean | undefined = undefined;
[KEY_ID]: string;
userId: string;
roomId: string;
typeOfRoom: string;
roomKeyId: string | undefined;
groupSessionKey: Aes.Key | null = null;
oldKeys: { E2EKey: Aes.Key | null; ts: Date; e2eKeyId: string }[] | undefined;
sessionKeyExportedString: string | undefined;
sessionKeyExported: Aes.Jwk | undefined;
constructor(userId: string, room: IRoom) {
super();
this.userId = userId;
this.roomId = room._id;
this.typeOfRoom = room.t;
this.roomKeyId = room.e2eKeyId;
this.once('READY', async () => {
await this.decryptOldRoomKeys();
return this.decryptPendingMessages();
});
this.once('READY', () => this.decryptSubscription());
this.on('STATE_CHANGED', () => this.handshake());
this.setState('NOT_STARTED');
}
hasSessionKey() {
return !!this.groupSessionKey;
}
getState() {
return this.state;
}
setState(requestedState: E2ERoomState) {
const span = log.span('setState');
const currentState = this.state;
const nextState = filterMutation(currentState, requestedState);
if (!nextState) {
span.error(`${currentState} -> ${requestedState}`);
return;
}
this.state = nextState;
span.info(`${currentState} -> ${nextState}`);
this.emit('STATE_CHANGED', currentState);
this.emit(nextState, this);
}
isReady() {
return this.state === 'READY';
}
isDisabled() {
return this.state === 'DISABLED';
}
enable() {
if (this.state === 'READY') {
return;
}
this.setState('READY');
}
disable() {
this.setState('DISABLED');
}
pause() {
this[PAUSED] = true;
this.emit('PAUSED', true);
}
resume() {
this[PAUSED] = false;
this.emit('PAUSED', false);
}
keyReceived() {
this.setState('KEYS_RECEIVED');
}
async shouldConvertSentMessages(message: { msg?: string }) {
if (!this.isReady() || this[PAUSED]) {
return false;
}
if (this[PAUSED] === undefined) {
return new Promise((resolve) => {
this.once('PAUSED', resolve);
});
}
if (message.msg?.[0] === '/') {
return false;
}
return true;
}
shouldConvertReceivedMessages() {
return this.isReady();
}
isWaitingKeys() {
return this.state === 'WAITING_KEYS';
}
get keyID() {
return this[KEY_ID];
}
set keyID(keyID) {
this[KEY_ID] = keyID;
}
async decryptSubscription() {
const span = log.span('decryptSubscription');
const subscription = Subscriptions.state.find((record) => record.rid === this.roomId);
if (!subscription) {
span.warn('no subscription found');
return;
}
const { lastMessage } = subscription;
if (lastMessage === undefined) {
span.warn('no lastMessage found');
return;
}
if (lastMessage.t !== 'e2e') {
span.warn('nothing to do');
return;
}
const message = await this.decryptMessage(lastMessage);
if (message.msg !== subscription.lastMessage?.msg) {
span.info('decryptSubscriptions updating lastMessage');
Subscriptions.state.store({
...subscription,
lastMessage: message,
});
}
span.info('decryptSubscriptions Done');
}
async decryptOldRoomKeys() {
const span = log.span('decryptOldRoomKeys');
const sub = Subscriptions.state.find((record) => record.rid === this.roomId);
if (!sub?.oldRoomKeys || sub?.oldRoomKeys.length === 0) {
span.info('Nothing to do');
return;
}
const keys = [];
for await (const key of sub.oldRoomKeys) {
try {
const k = await this.decryptSessionKey(key.E2EKey);
keys.push({
...key,
E2EKey: k,
});
} catch (error) {
span.error(
`Cannot decrypt old room key with id ${key.e2eKeyId}. This is likely because user private key changed or is missing. Skipping`,
error,
);
keys.push({ ...key, E2EKey: null });
}
}
this.oldKeys = keys;
}
async exportOldRoomKeys(oldKeys: ISubscription['oldRoomKeys']) {
const span = log.span('exportOldRoomKeys').set('oldKeys', oldKeys);
if (!oldKeys || oldKeys.length === 0) {
span.info('Nothing to do');
return;
}
const keys = [];
for await (const key of oldKeys) {
try {
if (!key.E2EKey) {
continue;
}
const k = await this.exportSessionKey(key.E2EKey);
keys.push({
...key,
E2EKey: k,
});
} catch (e) {
span.set('error', e);
span.error(
`Cannot decrypt old room key with id ${key.e2eKeyId}. This is likely because user private key changed or is missing. Skipping.`,
);
}
}
span.info(`Done: ${keys.length} keys exported`);
return keys;
}
async decryptPendingMessages() {
await Messages.state.updateAsync(
(record) => record.rid === this.roomId && record.t === 'e2e' && record.e2e === 'pending',
(record) => this.decryptMessage(record as IE2EEMessage),
);
}
// Initiates E2E Encryption
async handshake() {
const span = log.span('handshake');
if (!e2e.isReady()) {
return;
}
if (this.state !== 'KEYS_RECEIVED' && this.state !== 'NOT_STARTED') {
return;
}
this.setState('ESTABLISHING');
try {
const groupKey = Subscriptions.state.find((record) => record.rid === this.roomId)?.E2EKey;
if (groupKey) {
await this.importGroupKey(groupKey);
this.setState('READY');
span.info('Group key imported');
return;
}
} catch (error) {
this.setState('ERROR');
span.error('Error fetching group key', error);
return;
}
try {
const room = Rooms.state.get(this.roomId);
span.set('room', room);
if (!room?.e2eKeyId) {
this.setState('CREATING_KEYS');
const created = await this.createGroupKey();
if (!created) {
// another member won the race
this.setState('WAITING_KEYS');
return;
}
this.setState('READY');
return;
}
this.setState('WAITING_KEYS');
span.info('Requesting room key');
sdk.publish('notify-room-users', [`${this.roomId}/e2ekeyRequest`, this.roomId, room.e2eKeyId]);
} catch (error) {
span.set('error', error);
span.error('Error during handshake');
this.setState('ERROR');
}
}
isSupportedRoomType(type: string) {
return roomCoordinator.getRoomDirectives(type).allowRoomSettingChange({}, RoomSettingsEnum.E2E);
}
async decryptSessionKey(key: string) {
return Aes.importKey(JSON.parse(await this.exportSessionKey(key)));
}
async exportSessionKey(key: string) {
const span = log.span('exportSessionKey');
const [prefix, decodedKey] = PrefixedBase64.decode(key);
span.set('prefix', prefix);
if (!e2e.privateKey) {
span.error('Private key not found');
throw new Error('Private key not found');
}
const decryptedKey = await Rsa.decrypt(e2e.privateKey, decodedKey);
span.info('Key decrypted');
return Binary.encode(decryptedKey.buffer);
}
async importGroupKey(groupKey: string) {
const span = log.span('importGroupKey');
const [kid, decodedKey] = PrefixedBase64.decode(groupKey);
span.set('kid', kid);
if (this.keyID === kid && this.groupSessionKey) {
span.info('Key already imported');
return true;
}
// Decrypt obtained encrypted session key
try {
if (!e2e.privateKey) {
throw new Error('Private key not found');
}
const decryptedKey = await Rsa.decrypt(e2e.privateKey, decodedKey);
this.sessionKeyExportedString = Binary.encode(decryptedKey.buffer);
} catch (error) {
span.set('error', error).error('Error decrypting group key');
return false;
}
// When a new e2e room is created, it will be initialized without an e2e key id
// This will prevent new rooms from storing `undefined` as the keyid
if (!this.keyID) {
this.keyID = this.roomKeyId || kid || crypto.randomUUID();
}
// Import session key for use.
try {
const key = await Aes.importKey(JSON.parse(this.sessionKeyExportedString));
// Key has been obtained. E2E is now in session.
this.groupSessionKey = key;
span.info('Group key imported');
} catch (error) {
span.set('error', error).error('Error importing group key');
return false;
}
return true;
}
async createNewGroupKey() {
this.groupSessionKey = await Aes.generate();
const sessionKeyExported = await Aes.exportJwk(this.groupSessionKey);
this.sessionKeyExportedString = JSON.stringify(sessionKeyExported);
this.keyID = crypto.randomUUID();
}
private discardGroupKey() {
this.groupSessionKey = null;
this.sessionKeyExportedString = undefined;
this.keyID = undefined as unknown as string;
}
async createGroupKey(): Promise<boolean> {
const span = log.span('createGroupKey');
await this.createNewGroupKey();
try {
await sdk.rest.post('/v1/e2e.setRoomKeyID', { rid: this.roomId, keyID: this.keyID });
} catch (error) {
if (error instanceof Response && (await isRoomKeyAlreadyExistsError(error))) {
span.info('Room key already established by another member; discarding local key');
this.discardGroupKey();
return false;
}
throw error;
}
const myKey = await this.encryptGroupKeyForParticipant(e2e.publicKey!);
if (myKey) {
await sdk.rest.post('/v1/e2e.updateGroupKey', {
rid: this.roomId,
uid: this.userId,
key: myKey,
});
await this.encryptKeyForOtherParticipants();
}
return true;
}
async resetRoomKey() {
const span = log.span('resetRoomKey');
if (!e2e.publicKey) {
span.error('No public key found');
return;
}
this.setState('CREATING_KEYS');
try {
await this.createNewGroupKey();
const e2eNewKeys = { e2eKeyId: this.keyID, e2eKey: await this.encryptGroupKeyForParticipant(e2e.publicKey) };
this.setState('READY');
span.set('kid', this.keyID).info('Room key reset successfully');
return e2eNewKeys;
} catch (error) {
span.error('Error resetting room key', error);
throw error;
}
}
onRoomKeyReset(keyID: string) {
const span = log.span('onRoomKeyReset').set('key_id', keyID);
if (this.keyID === keyID) {
span.warn('Key ID matches current key, nothing to do');
return;
}
span.set('new_key_id', keyID).info('Room key has been reset');
this.setState('WAITING_KEYS');
this.keyID = keyID;
this.groupSessionKey = null;
this.sessionKeyExportedString = undefined;
this.sessionKeyExported = undefined;
this.oldKeys = undefined;
}
async encryptKeyForOtherParticipants() {
const span = log.span('encryptKeyForOtherParticipants');
// Encrypt generated session key for every user in room and publish to subscription model.
try {
const mySub = Subscriptions.state.find((record) => record.rid === this.roomId);
const decryptedOldGroupKeys = await this.exportOldRoomKeys(mySub?.oldRoomKeys);
const users = (await sdk.rest.get('/v1/e2e.getUsersOfRoomWithoutKey', { rid: this.roomId })).users.filter(
(user) => user?.e2e?.public_key,
);
if (!users.length) {
span.info('No users to encrypt the key for');
return;
}
const usersSuggestedGroupKeys: Record<
string,
{
_id: IUser['_id'];
key: string;
oldKeys: ISubscription['suggestedOldRoomKeys'];
}[]
> = { [this.roomId]: [] };
for await (const user of users) {
const encryptedGroupKey = await this.encryptGroupKeyForParticipant(user.e2e!.public_key);
if (!encryptedGroupKey) {
span.warn(`Could not encrypt group key for user ${user._id}`);
return;
}
if (decryptedOldGroupKeys) {
const oldKeys = await this.encryptOldKeysForParticipant(user.e2e!.public_key, decryptedOldGroupKeys);
if (oldKeys) {
usersSuggestedGroupKeys[this.roomId].push({ _id: user._id, key: encryptedGroupKey, oldKeys });
continue;
}
}
usersSuggestedGroupKeys[this.roomId].push({ _id: user._id, key: encryptedGroupKey, oldKeys: undefined });
}
await sdk.rest.post('/v1/e2e.provideUsersSuggestedGroupKeys', { usersSuggestedGroupKeys });
} catch (error) {
return span.set('error', error).error('Error getting room users');
}
}
async encryptOldKeysForParticipant(publicKey: string, oldRoomKeys: { E2EKey: string; e2eKeyId: string; ts: Date }[]) {
const span = log.span('encryptOldKeysForParticipant');
if (!oldRoomKeys || oldRoomKeys.length === 0) {
span.info('Nothing to do');
return;
}
let userKey;
try {
userKey = await Rsa.importPublicKey(JSON.parse(publicKey));
} catch (error) {
return span.set('error', error).error('Error importing user key');
}
try {
const keys = [];
for await (const oldRoomKey of oldRoomKeys) {
if (!oldRoomKey.E2EKey) {
continue;
}
const encryptedKey = await Rsa.encrypt(userKey, Binary.decode(oldRoomKey.E2EKey));
const encryptedKeyToString = PrefixedBase64.encode([oldRoomKey.e2eKeyId, encryptedKey]);
keys.push({ ...oldRoomKey, E2EKey: encryptedKeyToString });
}
return keys;
} catch (error) {
return span.set('error', error).error('failed to encrypt old keys for participant');
}
}
async encryptGroupKeyForParticipant(publicKey: string) {
const span = log.span('encryptGroupKeyForParticipant');
let userKey;
try {
userKey = await Rsa.importPublicKey(JSON.parse(publicKey));
} catch (error) {
return span.set('error', error).error('Error importing user key');
}
// Encrypt session key for this user with his/her public key
try {
const encryptedUserKey = await Rsa.encrypt(userKey, Binary.decode(this.sessionKeyExportedString!));
const encryptedUserKeyToString = PrefixedBase64.encode([this.keyID, encryptedUserKey]);
span.info('Group key encrypted for participant');
return encryptedUserKeyToString;
} catch (error) {
return span.error('Error encrypting user key', error);
}
}
// Encrypts files before upload. I/O is in arraybuffers.
async encryptFile(file: File) {
const span = log.span('encryptFile');
const fileArrayBuffer = await file.arrayBuffer();
const hash = await sha256HashFromArrayBuffer(fileArrayBuffer);
const vector = crypto.getRandomValues(new Uint8Array(16));
const key = await generateAESCTRKey();
let result;
try {
result = await encryptAESCTR(vector, key, fileArrayBuffer);
} catch (error) {
return span.set('error', error).error('Error encrypting group key');
}
const exportedKey = await window.crypto.subtle.exportKey('jwk', key);
const fileName = await createSha256HashFromText(file.name);
const encryptedFile = new File([result], fileName);
return {
file: encryptedFile,
key: exportedKey,
iv: Base64.encode(vector),
type: file.type,
hash,
};
}
// Encrypts messages
async encryptText(data: Uint8Array<ArrayBuffer>) {
const span = log.span('encryptText');
try {
if (!this.groupSessionKey) {
throw new Error('No group session key found.');
}
const { iv, ciphertext } = await Aes.encrypt(this.groupSessionKey, data);
const encryptedData = {
kid: this.keyID,
iv: Base64.encode(iv),
ciphertext: Base64.encode(ciphertext),
};
span.info('message encrypted');
return encryptedData;
} catch (error) {
span.error('Error encrypting message', error);
throw error;
}
}
// Helper function for encryption of content
async encryptMessageContent(
contentToBeEncrypted: Pick<IMessage, 'attachments' | 'files' | 'file'> & Optional<Pick<IMessage, 'msg'>, 'msg'>,
) {
const data = new TextEncoder().encode(EJSON.stringify(contentToBeEncrypted));
return {
algorithm: 'rc.v2.aes-sha2',
...(await this.encryptText(data)),
} as const;
}
// Helper function for encryption of content
async encryptMessage(message: AtLeast<IMessage, '_id' | 'rid' | 'msg'>): Promise<IE2EEMessage> {
const { msg, attachments, ...rest } = message;
const content = await this.encryptMessageContent({ msg, attachments });
// E2EMessages remove the `msg` property. It's stored in `content` instead.
// Making the property optional can open a small can of worms, but just ignoring it in here should be fine ;)
return {
...rest,
content,
t: 'e2e' as const,
e2e: 'pending' as const,
} as IE2EEMessage;
}
async decryptContent<T extends EncryptedMessageContent>(data: T) {
const content = await this.decrypt(data.content);
Object.assign(data, content);
return data;
}
async decryptMessageContent(message: IE2EEMessage): Promise<IE2EEMessage> {
const { attachments } = message;
const deletedAttachments = attachments?.filter((att) => isRemovedFileAttachment(att)) || [];
const deletedAllAttachment = deletedAttachments.find((att) => !att.fileId);
const content = await this.decrypt(message.content);
Object.assign(message, content);
// If the encrypted message had deleted files and the decrypted message has files, compare both lists to remove from the final result any file that was flagged as deleted
if (!deletedAttachments.length || !message.attachments?.length || !content.attachments?.length) {
return message;
}
message.attachments = message.attachments.map((att) => {
if (!isFileAttachment(att)) {
return att;
}
if (deletedAllAttachment) {
return deletedAllAttachment;
}
const fileId = att.fileId || message.file?._id;
if (!fileId) {
return att;
}
for (const removedAttachment of deletedAttachments) {
if (removedAttachment.fileId === fileId) {
return removedAttachment;
}
}
return att;
});
return message;
}
// Decrypt messages
async decryptMessage(message: IMessage | IE2EEMessage): Promise<IE2EEMessage | IMessage> {
if (message.t !== 'e2e' || message.e2e === 'done') {
return message;
}
if (isEncryptedMessageContent(message)) {
return {
...(await this.decryptMessageContent({ ...message })),
e2e: 'done' as const,
};
}
if (!message.msg) {
return {
...message,
e2e: 'done' as const,
};
}
// TODO(@cardoso): review backward compatibility
const data = await this.decrypt(message.msg);
return {
...message,
msg: typeof data.msg === 'string' ? data.msg : message.msg,
e2e: 'done' as const,
};
}
async decrypt(message: string | EncryptedContent): Promise<Pick<Partial<IMessage>, 'attachments' | 'files' | 'file' | 'msg'>> {
const span = log.span('decrypt').set('rid', this.roomId);
const payload = decodeEncryptedContent(message);
span.set('payload', payload);
const { kid, iv, ciphertext } = payload;
const key = this.retrieveDecryptionKey(kid);
if (!key) {
span.error('No decryption key found.');
return { msg: t('E2E_indecipherable') };
}
span.set('algorithm', key.algorithm.name);
span.set('extractable', key.extractable);
span.set('type', key.type);
span.set('usages', key.usages.toString());
try {
const result = await Aes.decrypt(key, { iv, ciphertext });
const ret: unknown = EJSON.parse(result);
if (typeof ret !== 'object' || ret === null) {
span.error('Decrypted message is not an object');
return { msg: t('E2E_indecipherable') };
}
if ('text' in ret && typeof ret.text === 'string' && !('msg' in ret)) {
const { text, ...rest } = ret;
return { msg: text, ...rest };
}
if ('msg' in ret && typeof ret.msg === 'string') {
const { msg, ...rest } = ret;
return { msg, ...rest };
}
return { ...ret };
} catch (error) {
span.set('error', error).error('Error decrypting message');
return { msg: t('E2E_Key_Error') };
}
}
private retrieveDecryptionKey(kid: string): Aes.Key | null {
const oldRoomKey = this.oldKeys?.find((key) => key.e2eKeyId === kid);
return oldRoomKey?.E2EKey ?? this.groupSessionKey;
}
provideKeyToUser(keyId: string) {
if (this.keyID !== keyId) {
return;
}
void this.encryptKeyForOtherParticipants();
this.setState('READY');
}
onStateChange(cb: () => void) {
this.on('STATE_CHANGED', cb);
return () => this.off('STATE_CHANGED', cb);
}
async encryptGroupKeyForParticipantsWaitingForTheKeys(users: { _id: IUser['_id']; public_key: string }[]) {
if (!this.isReady()) {
return;
}
const mySub = Subscriptions.state.find((record) => record.rid === this.roomId);
const decryptedOldGroupKeys = await this.exportOldRoomKeys(mySub?.oldRoomKeys);
const usersWithKeys = await Promise.all(
users.map(async (user) => {
const { _id, public_key } = user;
const key = await this.encryptGroupKeyForParticipant(public_key);
if (decryptedOldGroupKeys) {
const oldKeys = await this.encryptOldKeysForParticipant(public_key, decryptedOldGroupKeys);
return { _id, key, oldKeys };
}
return { _id, key };
}),
);
return usersWithKeys;
}
}

View File

@@ -0,0 +1,70 @@
import { imperativeModal } from '@rocket.chat/ui-client';
import * as banners from '../banners';
import { e2e } from './rocketchat.e2e';
import { dispatchToastMessage } from '../toast';
jest.mock('@rocket.chat/ui-client', () => ({
imperativeModal: {
open: jest.fn(),
close: jest.fn(),
},
}));
jest.mock('../../../client/lib/getUserAvatarURL', () => ({
getUserAvatarURL: jest.fn(),
}));
jest.mock('../../../app/utils/lib/i18n', () => ({
t: (key: string) => key,
}));
jest.mock('../toast', () => ({
dispatchToastMessage: jest.fn(),
}));
jest.mock('../banners', () => ({
closeById: jest.fn(),
open: jest.fn(),
}));
describe('E2E password modal', () => {
const getModalProps = () => (imperativeModal.open as jest.Mock).mock.calls.at(-1)?.[0].props;
afterEach(() => {
jest.restoreAllMocks();
jest.clearAllMocks();
});
it('keeps the E2EE alert open when the modal header close button is used', () => {
e2e.openEnterE2EEPasswordModal(jest.fn());
getModalProps().onClose();
expect(imperativeModal.close).toHaveBeenCalledTimes(1);
expect(banners.closeById).not.toHaveBeenCalled();
});
it('dismisses the E2EE alert when the user explicitly cancels entering the password', () => {
e2e.openEnterE2EEPasswordModal(jest.fn());
getModalProps().onCancel();
expect(dispatchToastMessage).toHaveBeenCalledWith({ type: 'info', message: 'End_To_End_Encryption_Not_Enabled' });
expect(imperativeModal.close).toHaveBeenCalledTimes(1);
expect(banners.closeById).toHaveBeenCalledWith('e2e');
});
it('dismisses the E2EE alert after the password is entered successfully', async () => {
const onEnterE2EEPassword = jest.fn().mockResolvedValue(undefined);
e2e.openEnterE2EEPasswordModal(onEnterE2EEPassword);
await getModalProps().onConfirm('password');
expect(onEnterE2EEPassword).toHaveBeenCalledWith('password');
expect(dispatchToastMessage).toHaveBeenCalledWith({ type: 'success', message: 'E2E_encryption_enabled' });
expect(imperativeModal.close).toHaveBeenCalledTimes(1);
expect(banners.closeById).toHaveBeenCalledWith('e2e');
});
});

View File

@@ -0,0 +1,884 @@
import type { IE2EEMessage, IMessage, IRoom, IUser, IUploadWithUser, Serialized, IE2EEPinnedMessage } from '@rocket.chat/core-typings';
import { isE2EEMessage, isEncryptedMessageContent } from '@rocket.chat/core-typings';
import { Emitter } from '@rocket.chat/emitter';
import { isTruthy } from '@rocket.chat/tools';
import { imperativeModal } from '@rocket.chat/ui-client';
import type { SubscriptionWithRoom } from '@rocket.chat/ui-contexts';
import sampleSize from 'lodash/sampleSize';
import type { E2EEState } from './E2EEState';
import * as Rsa from './crypto/rsa';
import { generatePassphrase } from './helper';
import { Keychain } from './keychain';
import { createLogger } from './logger';
import { E2ERoom } from './rocketchat.e2e.room';
import { t } from '../../../app/utils/lib/i18n';
import { createQuoteAttachment } from '../../../lib/createQuoteAttachment';
import { getMessageUrlRegex } from '../../../lib/getMessageUrlRegex';
import { Rooms, Subscriptions } from '../../stores';
import EnterE2EPasswordModal from '../../views/e2e/EnterE2EPasswordModal';
import SaveE2EPasswordModal from '../../views/e2e/SaveE2EPasswordModal';
import { sdk } from '../SDKClient';
import * as banners from '../banners';
import type { LegacyBannerPayload } from '../banners';
import { getUserAvatarURL } from '../getUserAvatarURL';
import { limitQuoteChain } from '../limitQuoteChain';
import { getDdpSdk } from '../sdk/ddpSdk';
import { STORAGE_KEYS, getStoredItem, removeStoredItem, setStoredItem } from '../sdk/storage';
import { settings } from '../settings';
import { dispatchToastMessage } from '../toast';
import { mapMessageFromApi } from '../utils/mapMessageFromApi';
let failedToDecodeKey = false;
const log = createLogger('E2E');
type KeyPair = {
public_key: string | null;
private_key: string | null;
};
const ROOM_KEY_EXCHANGE_SIZE = 10;
class E2E extends Emitter {
private userId: string | false = false;
private keychain: Keychain;
private instancesByRoomId: Record<IRoom['_id'], E2ERoom> = {};
private db_public_key: string | null | undefined;
private db_private_key: string | null | undefined;
public privateKey: Rsa.PrivateKey | undefined;
public publicKey: string | undefined;
private keyDistributionInterval: ReturnType<typeof setInterval> | null = null;
private state: E2EEState;
constructor() {
super();
this.on('READY', async () => {
await this.onE2EEReady();
});
this.on('SAVE_PASSWORD', async () => {
await this.onE2EEReady();
});
this.on('DISABLED', () => {
this.unsubscribeFromSubscriptions?.();
});
this.on('NOT_STARTED', () => {
this.unsubscribeFromSubscriptions?.();
});
this.on('ERROR', () => {
this.unsubscribeFromSubscriptions?.();
});
this.setState('NOT_STARTED');
}
getState() {
return this.state;
}
isEnabled(): boolean {
return this.state !== 'DISABLED';
}
isReady(): boolean {
// Save_Password state is also a ready state for E2EE
return this.state === 'READY' || this.state === 'SAVE_PASSWORD';
}
async onE2EEReady() {
this.initiateHandshake();
await this.handleAsyncE2EESuggestedKey();
await this.decryptSubscriptions();
await this.initiateKeyDistribution();
this.observeSubscriptions();
}
async onSubscriptionChanged(sub: SubscriptionWithRoom): Promise<void> {
const span = log.span('onSubscriptionChanged').set('subscription_id', sub._id).set('room_id', sub.rid).set('encrypted', sub.encrypted);
if (!sub.encrypted && !sub.E2EKey) {
this.removeInstanceByRoomId(sub.rid);
return;
}
const e2eRoom = await this.getInstanceByRoomId(sub.rid);
if (!e2eRoom) {
span.warn('no e2eRoom found');
return;
}
if (sub.E2ESuggestedKey) {
if (await e2eRoom.importGroupKey(sub.E2ESuggestedKey)) {
await this.acceptSuggestedKey(sub.rid);
e2eRoom.keyReceived();
} else {
span.warn('rejected');
await this.rejectSuggestedKey(sub.rid);
}
}
if (sub.encrypted) {
e2eRoom.resume();
} else {
e2eRoom.pause();
}
// Cover private groups and direct messages
if (!e2eRoom.isSupportedRoomType(sub.t)) {
e2eRoom.disable();
return;
}
if (sub.E2EKey && e2eRoom.isWaitingKeys()) {
e2eRoom.keyReceived();
return;
}
if (!e2eRoom.isReady()) {
return;
}
if (sub.lastMessage?.e2e !== 'done') {
await e2eRoom.decryptSubscription();
}
}
private unsubscribeFromSubscriptions: (() => void) | undefined;
observeSubscriptions() {
const span = log.span('observeSubscriptions');
this.unsubscribeFromSubscriptions?.();
this.unsubscribeFromSubscriptions = Subscriptions.use.subscribe((state) => {
const subscriptions = Array.from(state.records.values()).filter((sub) => sub.encrypted || sub.E2EKey);
const subscribed = new Set(subscriptions.map((sub) => sub.rid));
const instatiated = new Set(Object.keys(this.instancesByRoomId));
const excess = instatiated.difference(subscribed);
if (excess.size) {
span.info('Unsubscribing from excess instances');
excess.forEach((rid) => this.removeInstanceByRoomId(rid));
}
for (const sub of subscriptions) {
void this.onSubscriptionChanged(sub);
}
});
}
setState(nextState: E2EEState) {
const span = log.span('setState').set('prevState', this.state).set('nextState', nextState);
const prevState = this.state;
this.state = nextState;
span.info(`${prevState} -> ${nextState}`);
this.emit('E2E_STATE_CHANGED', { prevState, nextState });
this.emit(nextState);
}
async handleAsyncE2EESuggestedKey() {
const span = log.span('handleAsyncE2EESuggestedKey');
const subs = Subscriptions.state.filter((sub) => typeof sub.E2ESuggestedKey !== 'undefined');
await Promise.all(
subs
.filter((sub) => sub.E2ESuggestedKey && !sub.E2EKey)
.map(async (sub) => {
const e2eRoom = await e2e.getInstanceByRoomId(sub.rid);
span.set('subscription_id', sub._id).set('room_id', sub.rid);
if (!e2eRoom) {
return;
}
if (sub.E2ESuggestedKey && (await e2eRoom.importGroupKey(sub.E2ESuggestedKey))) {
span.info('importedE2ESuggestedKey');
await e2e.acceptSuggestedKey(sub.rid);
e2eRoom.keyReceived();
} else {
span.error('invalidE2ESuggestedKey');
await e2e.rejectSuggestedKey(sub.rid);
}
if (sub.encrypted) {
e2eRoom.resume();
} else {
e2eRoom.pause();
}
}),
);
span.info('handledAsyncE2ESuggestedKey');
}
private waitForRoom(rid: IRoom['_id']): Promise<IRoom> {
return new Promise((resolve) => {
const room = Rooms.state.get(rid);
if (room) resolve(room);
const unsubscribe = Rooms.use.subscribe((state) => {
const room = state.get(rid);
if (room) {
unsubscribe();
resolve(room);
}
});
});
}
async getInstanceByRoomId(rid: IRoom['_id']): Promise<E2ERoom | null> {
if (!this.userId) {
return null;
}
const room = await this.waitForRoom(rid);
if (room.t !== 'd' && room.t !== 'p') {
return null;
}
if (!room.encrypted) {
return null;
}
if (!this.instancesByRoomId[rid] && this.userId) {
this.instancesByRoomId[rid] = new E2ERoom(this.userId, room);
}
// When the key was already set and is changed via an update, we update the room instance
if (
this.instancesByRoomId[rid].keyID !== undefined &&
room.e2eKeyId !== undefined &&
this.instancesByRoomId[rid].keyID !== room.e2eKeyId
) {
// KeyID was changed, update instance with new keyID and put room in waiting keys status
this.instancesByRoomId[rid].onRoomKeyReset(room.e2eKeyId);
}
return this.instancesByRoomId[rid] ?? null;
}
removeInstanceByRoomId(rid: IRoom['_id']): void {
delete this.instancesByRoomId[rid];
}
private async persistKeys(
{ public_key, private_key }: KeyPair,
password: string,
{ force }: { force: boolean } = { force: false },
): Promise<void> {
if (typeof public_key !== 'string' || typeof private_key !== 'string') {
throw new Error('Failed to persist keys as they are not strings.');
}
const encodedPrivateKey = await this.keychain.encryptKey(private_key, password);
if (!encodedPrivateKey) {
throw new Error('Failed to encode private key with provided password.');
}
await sdk.rest.post('/v1/e2e.setUserPublicAndPrivateKeys', {
public_key,
private_key: JSON.stringify(encodedPrivateKey),
force,
});
}
async acceptSuggestedKey(rid: string): Promise<void> {
await sdk.rest.post('/v1/e2e.acceptSuggestedGroupKey', {
rid,
});
}
async rejectSuggestedKey(rid: string): Promise<void> {
await sdk.rest.post('/v1/e2e.rejectSuggestedGroupKey', {
rid,
});
}
getKeysFromLocalStorage(): KeyPair {
return {
public_key: getStoredItem(STORAGE_KEYS.E2EE_PUBLIC_KEY),
private_key: getStoredItem(STORAGE_KEYS.E2EE_PRIVATE_KEY),
};
}
initiateHandshake() {
Object.keys(this.instancesByRoomId).map((key) => this.instancesByRoomId[key].handshake());
}
openSaveE2EEPasswordModal(randomPassword: string) {
imperativeModal.open({
component: SaveE2EPasswordModal,
props: {
randomPassword,
onClose: imperativeModal.close,
onCancel: () => {
this.closeAlert();
imperativeModal.close();
},
onConfirm: () => {
removeStoredItem(STORAGE_KEYS.E2EE_RANDOM_PASSWORD);
this.setState('READY');
dispatchToastMessage({ type: 'success', message: t('E2E_encryption_enabled') });
this.closeAlert();
imperativeModal.close();
},
},
});
}
async startClient(userId: string): Promise<void> {
if (!isSecureContext) {
throw new Error('E2E encryption can only be enabled in secure contexts (HTTPS)');
}
const span = log.span('startClient');
if (this.userId === userId) {
return;
}
span.info(this.state);
this.userId = userId;
this.keychain = new Keychain(userId);
let { public_key, private_key } = this.getKeysFromLocalStorage();
await this.loadKeysFromDB();
if (!public_key && this.db_public_key) {
public_key = this.db_public_key;
}
if (this.db_private_key && !private_key) {
try {
this.setState('ENTER_PASSWORD');
private_key = await this.decodePrivateKey(this.db_private_key);
} catch (error) {
this.userId = false;
failedToDecodeKey = true;
this.openAlert({
title: "Wasn't possible to decode your encryption key to be imported.", // TODO: missing translation
html: '<div>Your encryption password seems wrong. Click here to try again.</div>', // TODO: missing translation
modifiers: ['large', 'danger'],
closable: true,
icon: 'key',
action: async () => {
await this.startClient(userId);
this.closeAlert();
},
});
return span.error('E2E -> Error decoding private key: ', error);
}
}
if (public_key && private_key) {
await this.loadKeys({ public_key, private_key });
this.setState('READY');
} else {
await this.createAndLoadKeys();
this.setState('READY');
}
if (!this.db_public_key || !this.db_private_key) {
this.setState('LOADING_KEYS');
await this.persistKeys(this.getKeysFromLocalStorage(), await this.createRandomPassword());
}
const randomPassword = getStoredItem(STORAGE_KEYS.E2EE_RANDOM_PASSWORD);
if (randomPassword) {
this.setState('SAVE_PASSWORD');
this.openAlert({
title: () => t('Save_your_new_E2EE_password'),
html: () => t('Click_here_to_view_and_save_your_new_E2EE_password'),
modifiers: ['large'],
closable: false,
icon: 'key',
action: () => this.openSaveE2EEPasswordModal(randomPassword),
});
}
}
async stopClient(): Promise<void> {
const span = log.span('stopClient');
span.info(this.state);
this.closeAlert();
removeStoredItem(STORAGE_KEYS.E2EE_PUBLIC_KEY);
removeStoredItem(STORAGE_KEYS.E2EE_PRIVATE_KEY);
this.instancesByRoomId = {};
this.privateKey = undefined;
this.publicKey = undefined;
this.userId = false;
if (this.keyDistributionInterval) {
clearInterval(this.keyDistributionInterval);
}
this.keyDistributionInterval = null;
this.setState('DISABLED');
}
async changePassword(newPassword: string): Promise<void> {
await this.persistKeys(this.getKeysFromLocalStorage(), newPassword, { force: true });
if (getStoredItem(STORAGE_KEYS.E2EE_RANDOM_PASSWORD)) {
setStoredItem(STORAGE_KEYS.E2EE_RANDOM_PASSWORD, newPassword);
}
}
async loadKeysFromDB(): Promise<void> {
const span = log.span('loadKeysFromDB');
try {
this.setState('LOADING_KEYS');
const { public_key, private_key } = await sdk.rest.get('/v1/e2e.fetchMyKeys');
this.db_public_key = public_key;
this.db_private_key = private_key;
span.info('fetched keys from db');
} catch (error) {
this.setState('ERROR');
span.error('Error fetching RSA keys: ', error);
// Stop any process since we can't communicate with the server
// to get the keys. This prevents new key generation
throw error;
}
}
async loadKeys({ public_key, private_key }: { public_key: string; private_key: string }): Promise<void> {
const span = log.span('loadKeys');
setStoredItem(STORAGE_KEYS.E2EE_PUBLIC_KEY, public_key);
this.publicKey = public_key;
try {
this.privateKey = await Rsa.importPrivateKey(JSON.parse(private_key));
setStoredItem(STORAGE_KEYS.E2EE_PRIVATE_KEY, private_key);
} catch (error) {
this.setState('ERROR');
return span.error('Error importing private key: ', error);
}
}
async createAndLoadKeys(): Promise<void> {
const span = log.span('createAndLoadKeys');
// Could not obtain public-private keypair from server.
this.setState('LOADING_KEYS');
let keyPair;
try {
keyPair = await Rsa.generate();
this.privateKey = keyPair.privateKey;
} catch (error) {
this.setState('ERROR');
return span.set('error', error).error('Error generating key');
}
try {
const publicKey = await Rsa.exportPublicKey(keyPair.publicKey);
this.publicKey = JSON.stringify(publicKey);
setStoredItem(STORAGE_KEYS.E2EE_PUBLIC_KEY, JSON.stringify(publicKey));
} catch (error) {
this.setState('ERROR');
return span.set('error', error).error('Error exporting public key');
}
try {
const privateKey = await Rsa.exportPrivateKey(keyPair.privateKey);
setStoredItem(STORAGE_KEYS.E2EE_PRIVATE_KEY, JSON.stringify(privateKey));
} catch (error) {
this.setState('ERROR');
return span.set('error', error).error('Error exporting private key');
}
await this.requestSubscriptionKeys();
}
async requestSubscriptionKeys(): Promise<void> {
await sdk.rest.post('/v1/e2e.requestSubscriptionKeys');
}
async createRandomPassword(): Promise<string> {
const randomPassword = await generatePassphrase();
setStoredItem(STORAGE_KEYS.E2EE_RANDOM_PASSWORD, randomPassword);
return randomPassword;
}
openEnterE2EEPasswordModal(onEnterE2EEPassword: (password: string) => Promise<void>) {
const close = () => {
imperativeModal.close();
};
const dismiss = () => {
this.closeAlert();
imperativeModal.close();
};
imperativeModal.open({
component: EnterE2EPasswordModal,
props: {
onClose: close,
onCancel: () => {
failedToDecodeKey = false;
dispatchToastMessage({ type: 'info', message: t('End_To_End_Encryption_Not_Enabled') });
dismiss();
},
onConfirm: async (password) => {
await onEnterE2EEPassword(password);
dispatchToastMessage({ type: 'success', message: t('E2E_encryption_enabled') });
dismiss();
},
},
});
}
async requestPasswordAlert(validatePassword: (password: string) => Promise<void>): Promise<void> {
return new Promise((resolve) => {
const showModal = () =>
this.openEnterE2EEPasswordModal(async (password) => {
await validatePassword(password);
resolve();
});
const showAlert = () => {
this.openAlert({
title: () => t('Enter_your_E2E_password'),
html: () => t('Click_here_to_enter_your_password'),
modifiers: ['large'],
closable: false,
icon: 'key',
action() {
showModal();
},
});
};
if (failedToDecodeKey) {
showModal();
} else {
showAlert();
}
});
}
async requestPasswordModal(validatePassword: (password: string) => Promise<void>): Promise<void> {
return new Promise((resolve) => {
this.openEnterE2EEPasswordModal(async (password) => {
await validatePassword(password);
resolve();
});
});
}
async decodePrivateKeyFlow() {
if (!this.db_private_key) {
return;
}
try {
let privateKey: string | undefined;
await this.requestPasswordModal(async (password) => {
privateKey = await this.keychain.decryptKey(this.db_private_key as string, password);
});
if (this.db_public_key && privateKey) {
await this.loadKeys({ public_key: this.db_public_key, private_key: privateKey });
} else {
await this.createAndLoadKeys();
}
this.setState('READY');
dispatchToastMessage({ type: 'success', message: t('E2E_encryption_enabled') });
} catch (error) {
this.setState('ENTER_PASSWORD');
dispatchToastMessage({ type: 'info', message: t('End_To_End_Encryption_Not_Enabled') });
throw new Error('E2E -> Error loading keys', { cause: error });
}
}
async decodePrivateKey(privateKey: string): Promise<string> {
let decryptedKey: string | undefined;
await this.requestPasswordAlert(async (password) => {
decryptedKey = await this.keychain.decryptKey(privateKey, password);
});
return decryptedKey as string;
}
async decryptFileContent(file: IUploadWithUser): Promise<IUploadWithUser> {
if (!file.rid || !isEncryptedMessageContent(file)) {
return file;
}
const e2eRoom = await this.getInstanceByRoomId(file.rid);
if (!e2eRoom) {
return file;
}
return e2eRoom.decryptContent(file);
}
async decryptMessage(message: IMessage | IE2EEMessage): Promise<IMessage> {
if (!isE2EEMessage(message) || message.e2e === 'done') {
return message;
}
const e2eRoom = await this.getInstanceByRoomId(message.rid);
if (!e2eRoom) {
return message;
}
const decryptedMessage = (await e2eRoom.decryptMessage(message)) as IE2EEMessage;
const decryptedMessageWithQuote = await this.parseQuoteAttachment(decryptedMessage);
return decryptedMessageWithQuote;
}
async decryptPinnedMessage(message: IE2EEPinnedMessage) {
const span = log.span('decryptPinnedMessage');
const [pinnedMessage] = message.attachments;
if (!pinnedMessage) {
span.warn('No pinned message found');
return message;
}
const e2eRoom = await this.getInstanceByRoomId(message.rid);
if (!e2eRoom) {
span.warn('No e2eRoom found');
return message;
}
const data = await e2eRoom.decrypt(pinnedMessage.content);
// TODO(@cardoso): review backward compatibility
message.attachments[0].text = data.msg;
span.info('pinned message decrypted');
return message;
}
async decryptSubscription(subscription: SubscriptionWithRoom): Promise<void> {
const span = log.span('decryptSubscription');
const e2eRoom = await this.getInstanceByRoomId(subscription.rid);
span.info(subscription._id);
if (!e2eRoom) {
span.warn('no e2eRoom found');
return;
}
if (e2eRoom.isReady()) {
span.info('e2e room ready');
await e2eRoom.decryptSubscription();
return;
}
e2eRoom.once('READY', async () => {
span.info('e2e room ready');
await e2eRoom.decryptSubscription();
});
}
async decryptSubscriptions(): Promise<void> {
const subscriptions = Subscriptions.state.filter((subscription) => !!subscription.encrypted);
await Promise.all(
subscriptions.map(async (subscription) => {
await this.decryptSubscription(subscription);
}),
);
}
openAlert(config: Omit<LegacyBannerPayload, 'id'>): void {
banners.open({ id: 'e2e', ...config });
}
closeAlert(): void {
banners.closeById('e2e');
}
async parseQuoteAttachment(message: IE2EEMessage): Promise<IE2EEMessage> {
if (!message?.msg) {
return message;
}
const urls = message.msg.match(getMessageUrlRegex()) || [];
const siteUrl = settings.peek<string>('Site_Url');
await Promise.all(
urls.map(async (url) => {
if (siteUrl && !url.includes(siteUrl)) {
return;
}
// URLs come from regex-matched message content, so they may be malformed; skip those instead of throwing
let urlObj: URL;
try {
urlObj = new URL(url);
} catch (error) {
return;
}
const [msgId, ...extraMsgIds] = urlObj.searchParams.getAll('msg');
// skip if the msg param is missing, empty, or duplicated
if (!msgId || extraMsgIds.length) {
return;
}
let quotedMessage: Serialized<IMessage>;
try {
const getQuotedMessage = await sdk.rest.get('/v1/chat.getMessage', { msgId });
quotedMessage = getQuotedMessage?.message;
} catch (error) {
console.error(`Error getting quoted message: ${error}`);
return;
}
if (!quotedMessage) {
return;
}
const decryptedQuoteMessage = await this.decryptMessage(mapMessageFromApi(quotedMessage));
message.attachments = message.attachments || [];
const useRealName = settings.peek('UI_Use_Real_Name');
const quoteAttachment = createQuoteAttachment(
decryptedQuoteMessage,
url,
useRealName,
getUserAvatarURL(decryptedQuoteMessage.u.username || '') as string,
);
message.attachments.push(limitQuoteChain(quoteAttachment, settings.peek('Message_QuoteChainLimit') ?? 2));
}),
);
return message;
}
async getSuggestedE2EEKeys(usersWaitingForE2EKeys: Record<IRoom['_id'], { _id: IUser['_id']; public_key: string }[]>) {
const roomIds = Object.keys(usersWaitingForE2EKeys);
return Object.fromEntries(
(
await Promise.all(
roomIds.map(async (room) => {
const e2eRoom = await this.getInstanceByRoomId(room);
if (!e2eRoom) {
return;
}
const usersWithKeys = await e2eRoom.encryptGroupKeyForParticipantsWaitingForTheKeys(usersWaitingForE2EKeys[room]);
if (!usersWithKeys) {
return;
}
return [room, usersWithKeys];
}),
)
).filter(isTruthy),
);
}
async getSample(roomIds: string[], limit = 3): Promise<string[]> {
if (limit === 0) {
return [];
}
const randomRoomIds = sampleSize(roomIds, ROOM_KEY_EXCHANGE_SIZE);
const sampleIds: string[] = [];
for await (const roomId of randomRoomIds) {
const e2eroom = await this.getInstanceByRoomId(roomId);
if (!e2eroom?.hasSessionKey()) {
continue;
}
sampleIds.push(roomId);
}
if (!sampleIds.length) {
return this.getSample(roomIds, limit - 1);
}
return sampleIds;
}
getUserId(): string {
if (!this.userId) {
throw new Error('No userId found');
}
return this.userId;
}
async initiateKeyDistribution() {
if (this.keyDistributionInterval) {
return;
}
const predicate = (record: IRoom) =>
Boolean('usersWaitingForE2EKeys' in record && record.usersWaitingForE2EKeys?.every((user) => user.userId !== this.getUserId()));
const span = log.span('initiateKeyDistribution');
const keyDistribution = async () => {
const roomIds = Rooms.state.filter(predicate).map((room) => room._id);
if (!roomIds.length) {
return;
}
// Prevent function from running and doing nothing when theres something to do
const sampleIds = await this.getSample(roomIds);
if (!sampleIds.length) {
return;
}
const { usersWaitingForE2EKeys = {} } = await sdk.rest.get('/v1/e2e.fetchUsersWaitingForGroupKey', { roomIds: sampleIds });
if (!Object.keys(usersWaitingForE2EKeys).length) {
return;
}
const userKeysWithRooms = await this.getSuggestedE2EEKeys(usersWaitingForE2EKeys);
if (!Object.keys(userKeysWithRooms).length) {
return;
}
try {
await sdk.rest.post('/v1/e2e.provideUsersSuggestedGroupKeys', { usersSuggestedGroupKeys: userKeysWithRooms });
} catch (error) {
return span.error('provideUsersSuggestedGroupKeys', error);
}
};
// Run first call right away, then schedule for 10s in the future
await keyDistribution();
this.keyDistributionInterval = setInterval(keyDistribution, 10000);
}
}
export const e2e = new E2E();
getDdpSdk().account.onLogout(() => {
void e2e.stopClient();
});

File diff suppressed because it is too large Load Diff