feat: Shade E2EE library — M1-M3 complete
Signal Protocol implementation with full X3DH + Double Ratchet: - M1: Core types, CryptoProvider interface, KDF chain functions, SubtleCrypto+noble/curves provider, MemoryStorage - M2: X3DH key agreement (identity keys, signed prekeys, one-time prekeys, bundle processing for both initiator and responder) - M3: Double Ratchet (symmetric-key ratchet, DH ratchet, skipped message key cache, out-of-order delivery, AAD-bound headers) 68 tests, 0 failures — including full integration test of X3DH handshake → Double Ratchet conversation. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
12
packages/shade-crypto-web/package.json
Normal file
12
packages/shade-crypto-web/package.json
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"name": "@shade/crypto-web",
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
"dependencies": {
|
||||
"@noble/curves": "^2.0.1",
|
||||
"@noble/hashes": "^2.0.1",
|
||||
"@shade/core": "workspace:*"
|
||||
}
|
||||
}
|
||||
2
packages/shade-crypto-web/src/index.ts
Normal file
2
packages/shade-crypto-web/src/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export { SubtleCryptoProvider } from './provider.js';
|
||||
export { MemoryStorage } from './memory-storage.js';
|
||||
98
packages/shade-crypto-web/src/memory-storage.ts
Normal file
98
packages/shade-crypto-web/src/memory-storage.ts
Normal file
@@ -0,0 +1,98 @@
|
||||
import type { StorageProvider, IdentityKeyPair, SignedPreKey, OneTimePreKey, SessionState } from '@shade/core';
|
||||
|
||||
/**
|
||||
* In-memory StorageProvider for testing and embedded use.
|
||||
* All data is lost when the instance is garbage collected.
|
||||
*/
|
||||
export class MemoryStorage implements StorageProvider {
|
||||
private identityKeyPair: IdentityKeyPair | null = null;
|
||||
private registrationId: number = 0;
|
||||
private signedPreKeys = new Map<number, SignedPreKey>();
|
||||
private oneTimePreKeys = new Map<number, OneTimePreKey>();
|
||||
private sessions = new Map<string, SessionState>();
|
||||
private trustedIdentities = new Map<string, Uint8Array>();
|
||||
|
||||
// ─── Identity ──────────────────────────────────────────────
|
||||
|
||||
async getIdentityKeyPair(): Promise<IdentityKeyPair | null> {
|
||||
return this.identityKeyPair;
|
||||
}
|
||||
|
||||
async saveIdentityKeyPair(keyPair: IdentityKeyPair): Promise<void> {
|
||||
this.identityKeyPair = keyPair;
|
||||
}
|
||||
|
||||
async getLocalRegistrationId(): Promise<number> {
|
||||
return this.registrationId;
|
||||
}
|
||||
|
||||
async saveLocalRegistrationId(id: number): Promise<void> {
|
||||
this.registrationId = id;
|
||||
}
|
||||
|
||||
// ─── Signed Pre-Keys ──────────────────────────────────────
|
||||
|
||||
async getSignedPreKey(keyId: number): Promise<SignedPreKey | null> {
|
||||
return this.signedPreKeys.get(keyId) ?? null;
|
||||
}
|
||||
|
||||
async saveSignedPreKey(key: SignedPreKey): Promise<void> {
|
||||
this.signedPreKeys.set(key.keyId, key);
|
||||
}
|
||||
|
||||
async removeSignedPreKey(keyId: number): Promise<void> {
|
||||
this.signedPreKeys.delete(keyId);
|
||||
}
|
||||
|
||||
// ─── One-Time Pre-Keys ────────────────────────────────────
|
||||
|
||||
async getOneTimePreKey(keyId: number): Promise<OneTimePreKey | null> {
|
||||
return this.oneTimePreKeys.get(keyId) ?? null;
|
||||
}
|
||||
|
||||
async saveOneTimePreKey(key: OneTimePreKey): Promise<void> {
|
||||
this.oneTimePreKeys.set(key.keyId, key);
|
||||
}
|
||||
|
||||
async removeOneTimePreKey(keyId: number): Promise<void> {
|
||||
this.oneTimePreKeys.delete(keyId);
|
||||
}
|
||||
|
||||
async getOneTimePreKeyCount(): Promise<number> {
|
||||
return this.oneTimePreKeys.size;
|
||||
}
|
||||
|
||||
// ─── Sessions ─────────────────────────────────────────────
|
||||
|
||||
async getSession(address: string): Promise<SessionState | null> {
|
||||
return this.sessions.get(address) ?? null;
|
||||
}
|
||||
|
||||
async saveSession(address: string, state: SessionState): Promise<void> {
|
||||
this.sessions.set(address, state);
|
||||
}
|
||||
|
||||
async removeSession(address: string): Promise<void> {
|
||||
this.sessions.delete(address);
|
||||
}
|
||||
|
||||
// ─── Trust ────────────────────────────────────────────────
|
||||
|
||||
async isTrustedIdentity(address: string, identityKey: Uint8Array): Promise<boolean> {
|
||||
const stored = this.trustedIdentities.get(address);
|
||||
if (!stored) return true; // TOFU: trust on first use
|
||||
return arraysEqual(stored, identityKey);
|
||||
}
|
||||
|
||||
async saveTrustedIdentity(address: string, identityKey: Uint8Array): Promise<void> {
|
||||
this.trustedIdentities.set(address, identityKey);
|
||||
}
|
||||
}
|
||||
|
||||
function arraysEqual(a: Uint8Array, b: Uint8Array): boolean {
|
||||
if (a.length !== b.length) return false;
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
if (a[i] !== b[i]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
118
packages/shade-crypto-web/src/provider.ts
Normal file
118
packages/shade-crypto-web/src/provider.ts
Normal file
@@ -0,0 +1,118 @@
|
||||
import type { CryptoProvider } from '@shade/core';
|
||||
import { x25519 } from '@noble/curves/ed25519.js';
|
||||
import { ed25519 } from '@noble/curves/ed25519.js';
|
||||
|
||||
/**
|
||||
* SubtleCrypto + noble/curves implementation of CryptoProvider.
|
||||
*
|
||||
* Uses @noble/curves for X25519 and Ed25519 (reliable across all runtimes)
|
||||
* and Web Crypto API for AES-256-GCM, HKDF, and HMAC (hardware-accelerated).
|
||||
*/
|
||||
export class SubtleCryptoProvider implements CryptoProvider {
|
||||
private readonly subtle: SubtleCrypto;
|
||||
|
||||
constructor(subtle?: SubtleCrypto) {
|
||||
this.subtle = subtle ?? globalThis.crypto.subtle;
|
||||
}
|
||||
|
||||
// ─── X25519 (via @noble/curves) ────────────────────────────
|
||||
|
||||
async generateX25519KeyPair(): Promise<{ publicKey: Uint8Array; privateKey: Uint8Array }> {
|
||||
const privateKey = this.randomBytes(32);
|
||||
const publicKey = x25519.getPublicKey(privateKey);
|
||||
return { publicKey, privateKey };
|
||||
}
|
||||
|
||||
async x25519(privateKey: Uint8Array, publicKey: Uint8Array): Promise<Uint8Array> {
|
||||
return x25519.getSharedSecret(privateKey, publicKey);
|
||||
}
|
||||
|
||||
// ─── Ed25519 (via @noble/curves) ───────────────────────────
|
||||
|
||||
async generateEd25519KeyPair(): Promise<{ publicKey: Uint8Array; privateKey: Uint8Array }> {
|
||||
const privateKey = this.randomBytes(32);
|
||||
const publicKey = ed25519.getPublicKey(privateKey);
|
||||
return { publicKey, privateKey };
|
||||
}
|
||||
|
||||
async sign(privateKey: Uint8Array, message: Uint8Array): Promise<Uint8Array> {
|
||||
return ed25519.sign(message, privateKey);
|
||||
}
|
||||
|
||||
async verify(publicKey: Uint8Array, message: Uint8Array, signature: Uint8Array): Promise<boolean> {
|
||||
try {
|
||||
return ed25519.verify(signature, message, publicKey);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── AES-256-GCM (via SubtleCrypto) ───────────────────────
|
||||
|
||||
async aesGcmEncrypt(
|
||||
key: Uint8Array,
|
||||
plaintext: Uint8Array,
|
||||
aad?: Uint8Array,
|
||||
): Promise<{ ciphertext: Uint8Array; nonce: Uint8Array }> {
|
||||
const nonce = this.randomBytes(12);
|
||||
const aesKey = await this.subtle.importKey('raw', key, 'AES-GCM', false, ['encrypt']);
|
||||
const encrypted = await this.subtle.encrypt(
|
||||
{ name: 'AES-GCM', iv: nonce, additionalData: aad },
|
||||
aesKey,
|
||||
plaintext,
|
||||
);
|
||||
return { ciphertext: new Uint8Array(encrypted), nonce };
|
||||
}
|
||||
|
||||
async aesGcmDecrypt(
|
||||
key: Uint8Array,
|
||||
ciphertext: Uint8Array,
|
||||
nonce: Uint8Array,
|
||||
aad?: Uint8Array,
|
||||
): Promise<Uint8Array> {
|
||||
const aesKey = await this.subtle.importKey('raw', key, 'AES-GCM', false, ['decrypt']);
|
||||
const decrypted = await this.subtle.decrypt(
|
||||
{ name: 'AES-GCM', iv: nonce, additionalData: aad },
|
||||
aesKey,
|
||||
ciphertext,
|
||||
);
|
||||
return new Uint8Array(decrypted);
|
||||
}
|
||||
|
||||
// ─── Key Derivation (via SubtleCrypto) ─────────────────────
|
||||
|
||||
async hkdf(
|
||||
ikm: Uint8Array,
|
||||
salt: Uint8Array,
|
||||
info: Uint8Array,
|
||||
length: number,
|
||||
): Promise<Uint8Array> {
|
||||
const baseKey = await this.subtle.importKey('raw', ikm, 'HKDF', false, ['deriveBits']);
|
||||
const bits = await this.subtle.deriveBits(
|
||||
{ name: 'HKDF', hash: 'SHA-256', salt, info },
|
||||
baseKey,
|
||||
length * 8,
|
||||
);
|
||||
return new Uint8Array(bits);
|
||||
}
|
||||
|
||||
async hmacSha256(key: Uint8Array, data: Uint8Array): Promise<Uint8Array> {
|
||||
const hmacKey = await this.subtle.importKey(
|
||||
'raw',
|
||||
key,
|
||||
{ name: 'HMAC', hash: 'SHA-256' },
|
||||
false,
|
||||
['sign'],
|
||||
);
|
||||
const sig = await this.subtle.sign('HMAC', hmacKey, data);
|
||||
return new Uint8Array(sig);
|
||||
}
|
||||
|
||||
// ─── Random ────────────────────────────────────────────────
|
||||
|
||||
randomBytes(length: number): Uint8Array {
|
||||
const buf = new Uint8Array(length);
|
||||
globalThis.crypto.getRandomValues(buf);
|
||||
return buf;
|
||||
}
|
||||
}
|
||||
236
packages/shade-crypto-web/tests/provider.test.ts
Normal file
236
packages/shade-crypto-web/tests/provider.test.ts
Normal file
@@ -0,0 +1,236 @@
|
||||
import { describe, test, expect } from 'bun:test';
|
||||
import { SubtleCryptoProvider } from '../src/provider.js';
|
||||
|
||||
const crypto = new SubtleCryptoProvider();
|
||||
|
||||
describe('SubtleCryptoProvider', () => {
|
||||
// ─── X25519 ──────────────────────────────────────────────
|
||||
|
||||
describe('X25519', () => {
|
||||
test('generates keypair with correct byte lengths', async () => {
|
||||
const kp = await crypto.generateX25519KeyPair();
|
||||
expect(kp.publicKey).toBeInstanceOf(Uint8Array);
|
||||
expect(kp.privateKey).toBeInstanceOf(Uint8Array);
|
||||
expect(kp.publicKey.length).toBe(32);
|
||||
expect(kp.privateKey.length).toBe(32);
|
||||
});
|
||||
|
||||
test('two keypairs produce different keys', async () => {
|
||||
const a = await crypto.generateX25519KeyPair();
|
||||
const b = await crypto.generateX25519KeyPair();
|
||||
expect(a.publicKey).not.toEqual(b.publicKey);
|
||||
expect(a.privateKey).not.toEqual(b.privateKey);
|
||||
});
|
||||
|
||||
test('DH agreement: both sides derive same shared secret', async () => {
|
||||
const alice = await crypto.generateX25519KeyPair();
|
||||
const bob = await crypto.generateX25519KeyPair();
|
||||
|
||||
const secretA = await crypto.x25519(alice.privateKey, bob.publicKey);
|
||||
const secretB = await crypto.x25519(bob.privateKey, alice.publicKey);
|
||||
|
||||
expect(secretA.length).toBe(32);
|
||||
expect(secretA).toEqual(secretB);
|
||||
});
|
||||
|
||||
test('DH with different peers produces different secrets', async () => {
|
||||
const alice = await crypto.generateX25519KeyPair();
|
||||
const bob = await crypto.generateX25519KeyPair();
|
||||
const charlie = await crypto.generateX25519KeyPair();
|
||||
|
||||
const secretAB = await crypto.x25519(alice.privateKey, bob.publicKey);
|
||||
const secretAC = await crypto.x25519(alice.privateKey, charlie.publicKey);
|
||||
|
||||
expect(secretAB).not.toEqual(secretAC);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Ed25519 ─────────────────────────────────────────────
|
||||
|
||||
describe('Ed25519', () => {
|
||||
test('generates keypair with correct byte lengths', async () => {
|
||||
const kp = await crypto.generateEd25519KeyPair();
|
||||
expect(kp.publicKey.length).toBe(32);
|
||||
expect(kp.privateKey.length).toBe(32);
|
||||
});
|
||||
|
||||
test('sign and verify roundtrip', async () => {
|
||||
const kp = await crypto.generateEd25519KeyPair();
|
||||
const message = new TextEncoder().encode('hello shade');
|
||||
|
||||
const sig = await crypto.sign(kp.privateKey, message);
|
||||
expect(sig.length).toBe(64);
|
||||
|
||||
const valid = await crypto.verify(kp.publicKey, message, sig);
|
||||
expect(valid).toBe(true);
|
||||
});
|
||||
|
||||
test('verify fails with wrong public key', async () => {
|
||||
const alice = await crypto.generateEd25519KeyPair();
|
||||
const bob = await crypto.generateEd25519KeyPair();
|
||||
const message = new TextEncoder().encode('hello shade');
|
||||
|
||||
const sig = await crypto.sign(alice.privateKey, message);
|
||||
const valid = await crypto.verify(bob.publicKey, message, sig);
|
||||
expect(valid).toBe(false);
|
||||
});
|
||||
|
||||
test('verify fails with tampered message', async () => {
|
||||
const kp = await crypto.generateEd25519KeyPair();
|
||||
const message = new TextEncoder().encode('hello shade');
|
||||
const tampered = new TextEncoder().encode('hello SHADE');
|
||||
|
||||
const sig = await crypto.sign(kp.privateKey, message);
|
||||
const valid = await crypto.verify(kp.publicKey, tampered, sig);
|
||||
expect(valid).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── AES-256-GCM ────────────────────────────────────────
|
||||
|
||||
describe('AES-256-GCM', () => {
|
||||
test('encrypt/decrypt roundtrip', async () => {
|
||||
const key = crypto.randomBytes(32);
|
||||
const plaintext = new TextEncoder().encode('secret message');
|
||||
|
||||
const { ciphertext, nonce } = await crypto.aesGcmEncrypt(key, plaintext);
|
||||
expect(nonce.length).toBe(12);
|
||||
expect(ciphertext.length).toBeGreaterThan(plaintext.length); // includes auth tag
|
||||
|
||||
const decrypted = await crypto.aesGcmDecrypt(key, ciphertext, nonce);
|
||||
expect(decrypted).toEqual(plaintext);
|
||||
});
|
||||
|
||||
test('each encryption produces unique nonce', async () => {
|
||||
const key = crypto.randomBytes(32);
|
||||
const plaintext = new TextEncoder().encode('same message');
|
||||
|
||||
const a = await crypto.aesGcmEncrypt(key, plaintext);
|
||||
const b = await crypto.aesGcmEncrypt(key, plaintext);
|
||||
|
||||
expect(a.nonce).not.toEqual(b.nonce);
|
||||
expect(a.ciphertext).not.toEqual(b.ciphertext);
|
||||
});
|
||||
|
||||
test('wrong key fails decryption', async () => {
|
||||
const key1 = crypto.randomBytes(32);
|
||||
const key2 = crypto.randomBytes(32);
|
||||
const plaintext = new TextEncoder().encode('secret');
|
||||
|
||||
const { ciphertext, nonce } = await crypto.aesGcmEncrypt(key1, plaintext);
|
||||
|
||||
expect(crypto.aesGcmDecrypt(key2, ciphertext, nonce)).rejects.toThrow();
|
||||
});
|
||||
|
||||
test('tampered ciphertext fails decryption', async () => {
|
||||
const key = crypto.randomBytes(32);
|
||||
const plaintext = new TextEncoder().encode('secret');
|
||||
|
||||
const { ciphertext, nonce } = await crypto.aesGcmEncrypt(key, plaintext);
|
||||
ciphertext[0] ^= 0xff; // flip a byte
|
||||
|
||||
expect(crypto.aesGcmDecrypt(key, ciphertext, nonce)).rejects.toThrow();
|
||||
});
|
||||
|
||||
test('associated data (AAD) is authenticated', async () => {
|
||||
const key = crypto.randomBytes(32);
|
||||
const plaintext = new TextEncoder().encode('secret');
|
||||
const aad = new TextEncoder().encode('header data');
|
||||
const wrongAad = new TextEncoder().encode('wrong header');
|
||||
|
||||
const { ciphertext, nonce } = await crypto.aesGcmEncrypt(key, plaintext, aad);
|
||||
|
||||
// Correct AAD works
|
||||
const decrypted = await crypto.aesGcmDecrypt(key, ciphertext, nonce, aad);
|
||||
expect(decrypted).toEqual(plaintext);
|
||||
|
||||
// Wrong AAD fails
|
||||
expect(crypto.aesGcmDecrypt(key, ciphertext, nonce, wrongAad)).rejects.toThrow();
|
||||
|
||||
// Missing AAD fails
|
||||
expect(crypto.aesGcmDecrypt(key, ciphertext, nonce)).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── HKDF ───────────────────────────────────────────────
|
||||
|
||||
describe('HKDF-SHA256', () => {
|
||||
test('produces correct output length', async () => {
|
||||
const ikm = crypto.randomBytes(32);
|
||||
const salt = crypto.randomBytes(32);
|
||||
const info = new TextEncoder().encode('test');
|
||||
|
||||
const out32 = await crypto.hkdf(ikm, salt, info, 32);
|
||||
expect(out32.length).toBe(32);
|
||||
|
||||
const out64 = await crypto.hkdf(ikm, salt, info, 64);
|
||||
expect(out64.length).toBe(64);
|
||||
});
|
||||
|
||||
test('deterministic: same inputs produce same output', async () => {
|
||||
const ikm = new Uint8Array(32).fill(0xab);
|
||||
const salt = new Uint8Array(32).fill(0xcd);
|
||||
const info = new TextEncoder().encode('deterministic test');
|
||||
|
||||
const a = await crypto.hkdf(ikm, salt, info, 32);
|
||||
const b = await crypto.hkdf(ikm, salt, info, 32);
|
||||
expect(a).toEqual(b);
|
||||
});
|
||||
|
||||
test('different info produces different output', async () => {
|
||||
const ikm = crypto.randomBytes(32);
|
||||
const salt = crypto.randomBytes(32);
|
||||
|
||||
const a = await crypto.hkdf(ikm, salt, new TextEncoder().encode('info-a'), 32);
|
||||
const b = await crypto.hkdf(ikm, salt, new TextEncoder().encode('info-b'), 32);
|
||||
expect(a).not.toEqual(b);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── HMAC-SHA256 ────────────────────────────────────────
|
||||
|
||||
describe('HMAC-SHA256', () => {
|
||||
test('produces 32-byte output', async () => {
|
||||
const key = crypto.randomBytes(32);
|
||||
const data = new TextEncoder().encode('test data');
|
||||
|
||||
const mac = await crypto.hmacSha256(key, data);
|
||||
expect(mac.length).toBe(32);
|
||||
});
|
||||
|
||||
test('deterministic: same inputs produce same MAC', async () => {
|
||||
const key = new Uint8Array(32).fill(0x42);
|
||||
const data = new TextEncoder().encode('deterministic');
|
||||
|
||||
const a = await crypto.hmacSha256(key, data);
|
||||
const b = await crypto.hmacSha256(key, data);
|
||||
expect(a).toEqual(b);
|
||||
});
|
||||
|
||||
test('different key produces different MAC', async () => {
|
||||
const key1 = crypto.randomBytes(32);
|
||||
const key2 = crypto.randomBytes(32);
|
||||
const data = new TextEncoder().encode('test');
|
||||
|
||||
const a = await crypto.hmacSha256(key1, data);
|
||||
const b = await crypto.hmacSha256(key2, data);
|
||||
expect(a).not.toEqual(b);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── randomBytes ────────────────────────────────────────
|
||||
|
||||
describe('randomBytes', () => {
|
||||
test('produces correct length', () => {
|
||||
expect(crypto.randomBytes(16).length).toBe(16);
|
||||
expect(crypto.randomBytes(32).length).toBe(32);
|
||||
expect(crypto.randomBytes(64).length).toBe(64);
|
||||
});
|
||||
|
||||
test('produces different values each call', () => {
|
||||
const a = crypto.randomBytes(32);
|
||||
const b = crypto.randomBytes(32);
|
||||
expect(a).not.toEqual(b);
|
||||
});
|
||||
});
|
||||
});
|
||||
8
packages/shade-crypto-web/tsconfig.json
Normal file
8
packages/shade-crypto-web/tsconfig.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "dist",
|
||||
"rootDir": "src"
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
Reference in New Issue
Block a user