Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

fix(extension): hold mobile-login RSA private key as non-extractable CryptoKey

AmarBego85881c89a165
diff --git a/apps/browser-extension/src/entrypoints/popup/utils/MobileLoginUtility.ts b/apps/browser-extension/src/entrypoints/popup/utils/MobileLoginUtility.ts
index 249a4c281..245758b6b 100644
--- a/apps/browser-extension/src/entrypoints/popup/utils/MobileLoginUtility.ts
+++ b/apps/browser-extension/src/entrypoints/popup/utils/MobileLoginUtility.ts
@@ -14,7 +14,7 @@ export class MobileLoginUtility {
private webApi: WebApiService;
private pollingInterval: NodeJS.Timeout | null = null;
private requestId: string | null = null;
- private privateKey: string | null = null;
+ private privateKey: CryptoKey | null = null;
private publicKeyHash: string | null = null;
/**
@@ -46,12 +46,11 @@ export class MobileLoginUtility {
*/
public async initiate(): Promise<{ requestId: string; publicKeyHash: string }> {
try {
- // Generate RSA key pair
- const keyPair = await EncryptionUtility.generateRsaKeyPair();
- this.privateKey = keyPair.privateKey;
+ const { publicKeyJwk, privateKey } = await EncryptionUtility.generateRsaKeyPairNonExtractable();
+ this.privateKey = privateKey;
// Compute hash of public key for QR code binding
- this.publicKeyHash = await this.computePublicKeyHash(keyPair.publicKey);
+ this.publicKeyHash = await this.computePublicKeyHash(publicKeyJwk);
// Send public key to server (no auth required)
const response = await this.webApi.rawFetch('auth/mobile-login/initiate', {
@@ -60,7 +59,7 @@ export class MobileLoginUtility {
'Content-Type': 'application/json',
},
body: JSON.stringify({
- clientPublicKey: keyPair.publicKey,
+ clientPublicKey: publicKeyJwk,
}),
});
@@ -116,7 +115,6 @@ export class MobileLoginUtility {
if (response.status === 404) {
// Request expired or not found
this.stopPolling();
- this.privateKey = null;
this.requestId = null;
onError(MobileLoginErrorCode.TIMEOUT);
return;
@@ -127,23 +125,22 @@ export class MobileLoginUtility {
const data = await response.json() as MobileLoginPollResponse;
if (data.fulfilled && data.encryptedSymmetricKey) {
- // Stop polling
+ // Capture key locally; stopPolling() nulls the field.
+ const privateKey = this.privateKey!;
this.stopPolling();
// Decrypt the encrypted decryption key with RSA private key
- const decryptionKeyBytes = await EncryptionUtility.decryptWithPrivateKey(data.encryptedDecryptionKey!, this.privateKey!);
+ const decryptionKeyBytes = await EncryptionUtility.decryptWithPrivateKeyObject(data.encryptedDecryptionKey!, privateKey);
const decryptionKey = Buffer.from(decryptionKeyBytes).toString('base64');
// Decrypt the other encrypted fields with the symmetric key
- const symmetricKeyBytes = await EncryptionUtility.decryptWithPrivateKey(data.encryptedSymmetricKey, this.privateKey!);
+ const symmetricKeyBytes = await EncryptionUtility.decryptWithPrivateKeyObject(data.encryptedSymmetricKey, privateKey);
const symmetricKey = Buffer.from(symmetricKeyBytes).toString('base64');
const token = await EncryptionUtility.symmetricDecrypt(data.encryptedToken!, symmetricKey);
const refreshToken = await EncryptionUtility.symmetricDecrypt(data.encryptedRefreshToken!, symmetricKey);
const username = await EncryptionUtility.symmetricDecrypt(data.encryptedUsername!, symmetricKey);
- // Clear sensitive data
- this.privateKey = null;
this.requestId = null;
// Call /login endpoint with username to get salt and encryption settings
@@ -181,7 +178,6 @@ export class MobileLoginUtility {
}
} catch {
this.stopPolling();
- this.privateKey = null;
this.requestId = null;
onError(MobileLoginErrorCode.GENERIC);
}
@@ -194,7 +190,6 @@ export class MobileLoginUtility {
setTimeout(() => {
if (this.pollingInterval) {
this.stopPolling();
- this.privateKey = null;
this.requestId = null;
onError(MobileLoginErrorCode.TIMEOUT);
}
@@ -202,13 +197,14 @@ export class MobileLoginUtility {
}
/**
- * Stops polling the server
+ * Stops polling the server and drops the private key reference.
*/
public stopPolling(): void {
if (this.pollingInterval) {
clearInterval(this.pollingInterval);
this.pollingInterval = null;
}
+ this.privateKey = null;
}
/**
@@ -216,7 +212,6 @@ export class MobileLoginUtility {
*/
public cleanup(): void {
this.stopPolling();
- this.privateKey = null;
this.requestId = null;
this.publicKeyHash = null;
}
diff --git a/apps/browser-extension/src/utils/EncryptionUtility.ts b/apps/browser-extension/src/utils/EncryptionUtility.ts
index b4a5ed95c..acfac8cb5 100644
--- a/apps/browser-extension/src/utils/EncryptionUtility.ts
+++ b/apps/browser-extension/src/utils/EncryptionUtility.ts
@@ -154,11 +154,6 @@ export class EncryptionUtility {
* Generates a new RSA key pair for asymmetric encryption
*/
public static async generateRsaKeyPair(): Promise<{ publicKey: string, privateKey: string }> {
- /**
- * TODO: this method is currently unused. When we enable the browser extension to actually generate keys,
- * check if the key pair is generated in the correct format where private key is in expected JWK format
- * that the WASM app already outputs.
- */
const keyPair = await crypto.subtle.generateKey(
{
name: "RSA-OAEP",
@@ -179,6 +174,30 @@ export class EncryptionUtility {
};
}
+ /**
+ * Generates a new RSA key pair with a non-extractable private key
+ * Private key stays inside WebCrypto and public key is returned as JWK string for transport
+ */
+ public static async generateRsaKeyPairNonExtractable(): Promise<{ publicKeyJwk: string, privateKey: CryptoKey }> {
+ const keyPair = await crypto.subtle.generateKey(
+ {
+ name: "RSA-OAEP",
+ modulusLength: 2048,
+ publicExponent: new Uint8Array([1, 0, 1]),
+ hash: "SHA-256",
+ },
+ false,
+ ["encrypt", "decrypt"]
+ );
+
+ const publicKey = await crypto.subtle.exportKey("jwk", keyPair.publicKey);
+
+ return {
+ publicKeyJwk: JSON.stringify(publicKey),
+ privateKey: keyPair.privateKey,
+ };
+ }
+
/**
* Encrypts data using RSA-OAEP asymmetric encryption with a public key
*/
@@ -207,7 +226,7 @@ export class EncryptionUtility {
}
/**
- * Decrypts data using RSA-OAEP asymmetric encryption with a private key
+ * Decrypts data using RSA-OAEP asymmetric encryption with a JWK private key
*/
public static async decryptWithPrivateKey(ciphertext: string, privateKey: string): Promise<Uint8Array> {
try {
@@ -218,26 +237,33 @@ export class EncryptionUtility {
name: "RSA-OAEP",
hash: "SHA-256",
},
- true,
+ false,
["decrypt"]
);
- const cipherBuffer = Uint8Array.from(atob(ciphertext), c => c.charCodeAt(0));
- const plaintextBuffer = await crypto.subtle.decrypt(
- {
- name: "RSA-OAEP",
- },
- privateKeyObj,
- cipherBuffer
- );
-
- return new Uint8Array(plaintextBuffer);
+ return await EncryptionUtility.decryptWithPrivateKeyObject(ciphertext, privateKeyObj);
} catch (error) {
console.error('RSA decryption failed:', error);
throw new Error(`Failed to decrypt: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
+ /**
+ * Decrypts data using RSA-OAEP asymmetric encryption with a CryptoKey private key.
+ */
+ public static async decryptWithPrivateKeyObject(ciphertext: string, privateKey: CryptoKey): Promise<Uint8Array> {
+ const cipherBuffer = Uint8Array.from(atob(ciphertext), c => c.charCodeAt(0));
+ const plaintextBuffer = await crypto.subtle.decrypt(
+ {
+ name: "RSA-OAEP",
+ },
+ privateKey,
+ cipherBuffer
+ );
+
+ return new Uint8Array(plaintextBuffer);
+ }
+
/**
* Decrypts an individual email based on the provided public/private key pairs.
*/
diff --git a/apps/browser-extension/src/utils/__tests__/EncryptionUtility.crypto.test.ts b/apps/browser-extension/src/utils/__tests__/EncryptionUtility.crypto.test.ts
new file mode 100644
index 000000000..719acb264
--- /dev/null
+++ b/apps/browser-extension/src/utils/__tests__/EncryptionUtility.crypto.test.ts
@@ -0,0 +1,61 @@
+import { describe, it, expect } from 'vitest';
+
+import EncryptionUtility from '@/utils/EncryptionUtility';
+
+describe('generateRsaKeyPairNonExtractable', () => {
+ it('returns a non-extractable CryptoKey for the private half', async () => {
+ const { privateKey } = await EncryptionUtility.generateRsaKeyPairNonExtractable();
+
+ expect(privateKey).toBeInstanceOf(CryptoKey);
+ expect(privateKey.type).toBe('private');
+ expect(privateKey.extractable).toBe(false);
+ });
+
+ it('rejects every attempt to export the private key', async () => {
+ const { privateKey } = await EncryptionUtility.generateRsaKeyPairNonExtractable();
+
+ await expect(crypto.subtle.exportKey('jwk', privateKey)).rejects.toBeDefined();
+ await expect(crypto.subtle.exportKey('pkcs8', privateKey)).rejects.toBeDefined();
+ });
+
+ it('returns the public key as a JWK string without private fields', async () => {
+ const { publicKeyJwk } = await EncryptionUtility.generateRsaKeyPairNonExtractable();
+
+ const jwk = JSON.parse(publicKeyJwk);
+ expect(jwk.kty).toBe('RSA');
+ expect(jwk.n).toBeDefined();
+ expect(jwk.e).toBeDefined();
+ expect(jwk.d).toBeUndefined();
+ expect(jwk.p).toBeUndefined();
+ expect(jwk.q).toBeUndefined();
+ });
+
+ it('round-trips: encrypt with JWK public key, decrypt with CryptoKey', async () => {
+ const { publicKeyJwk, privateKey } = await EncryptionUtility.generateRsaKeyPairNonExtractable();
+
+ const ciphertext = await EncryptionUtility.encryptWithPublicKey('hello mobile login', publicKeyJwk);
+ const plaintextBytes = await EncryptionUtility.decryptWithPrivateKeyObject(ciphertext, privateKey);
+
+ expect(new TextDecoder().decode(plaintextBytes)).toBe('hello mobile login');
+ });
+});
+
+describe('generateRsaKeyPair (legacy JWK path, used by vault email decrypt)', () => {
+ it('still round-trips through the JWK-string decrypt path', async () => {
+ const { publicKey, privateKey } = await EncryptionUtility.generateRsaKeyPair();
+
+ const ciphertext = await EncryptionUtility.encryptWithPublicKey('email body', publicKey);
+ const plaintextBytes = await EncryptionUtility.decryptWithPrivateKey(ciphertext, privateKey);
+
+ expect(new TextDecoder().decode(plaintextBytes)).toBe('email body');
+ });
+
+ it('exposes private fields in JS string (leak surface the non-extractable variant closes)', async () => {
+ const { privateKey } = await EncryptionUtility.generateRsaKeyPair();
+
+ const jwk = JSON.parse(privateKey);
+ expect(jwk.d).toBeDefined();
+ expect(jwk.p).toBeDefined();
+ expect(jwk.q).toBeDefined();
+ });
+});