@stvor/sdk 2.2.1 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,160 @@
1
+ import { initializeCrypto, establishSession, encryptMessage, decryptMessage } from '../index';
2
+ import { validateMessage } from '../replay-protection';
3
+ import { generateFingerprint, verifyFingerprint } from '../tofu';
4
+ import { randomBytes } from 'crypto';
5
+ describe('Ratchet Tests', () => {
6
+ beforeAll(async () => {
7
+ await initializeCrypto();
8
+ });
9
+ test('Forward Secrecy: Old keys cannot decrypt', () => {
10
+ const session = establishSession({ publicKey: randomBytes(32), privateKey: randomBytes(32) }, { publicKey: randomBytes(32), privateKey: randomBytes(32) }, randomBytes(32), randomBytes(32), randomBytes(32), randomBytes(32));
11
+ const message1 = encryptMessage('Hello, World!', session);
12
+ const message2 = encryptMessage('Goodbye, World!', session);
13
+ // Simulate key rotation
14
+ session.chainKey = randomBytes(32);
15
+ expect(() => decryptMessage(message1.ciphertext, message1.header, session)).toThrow();
16
+ });
17
+ test('Replay Protection: Reject duplicate nonces', async () => {
18
+ const userId = 'user1';
19
+ const nonce = 'unique-nonce';
20
+ const timestamp = Math.floor(Date.now() / 1000);
21
+ await validateMessage(userId, nonce, timestamp);
22
+ await expect(validateMessage(userId, nonce, timestamp)).rejects.toThrow('Message rejected: replay detected');
23
+ });
24
+ test('MITM Detection: Fingerprint mismatch', async () => {
25
+ const userId = 'user1';
26
+ const publicKey1 = randomBytes(32);
27
+ const publicKey2 = randomBytes(32);
28
+ const fingerprint1 = generateFingerprint(publicKey1);
29
+ const fingerprint2 = generateFingerprint(publicKey2);
30
+ await verifyFingerprint(userId, fingerprint1);
31
+ const result = await verifyFingerprint(userId, fingerprint2);
32
+ expect(result).toBe(false);
33
+ });
34
+ });
35
+ describe('2-Man Rule Tests', () => {
36
+ test('Recovery shares lifecycle', () => {
37
+ const userId = 'user1';
38
+ const recoveryKey = randomBytes(32);
39
+ const shares = generateRecoveryShares(recoveryKey);
40
+ storeRecoveryShares(userId, shares);
41
+ const retrievedShares = retrieveRecoveryShares(userId);
42
+ expect(retrievedShares.length).toBe(2);
43
+ expect(combineRecoveryShares(retrievedShares)).toEqual(recoveryKey);
44
+ revokeRecoveryShares(userId);
45
+ expect(() => retrieveRecoveryShares(userId)).toThrow('No recovery shares found for user');
46
+ });
47
+ test('Admin authentication', () => {
48
+ process.env.ADMIN_TOKEN = 'secure-token';
49
+ expect(authenticateAdmin('secure-token')).toBe(true);
50
+ expect(authenticateAdmin('invalid-token')).toBe(false);
51
+ });
52
+ });
53
+ describe('Double Ratchet Edge Cases', () => {
54
+ test('Skipped keys DoS protection', () => {
55
+ const session = {
56
+ skippedMessageKeys: new Map(),
57
+ };
58
+ for (let i = 0; i < MAX_SKIPPED_KEYS; i++) {
59
+ addSkippedKey(session, { publicKey: randomBytes(32), nonce: randomBytes(12) }, randomBytes(32));
60
+ }
61
+ expect(() => addSkippedKey(session, { publicKey: randomBytes(32), nonce: randomBytes(12) }, randomBytes(32))).toThrow('Skipped keys limit exceeded');
62
+ });
63
+ test('Simultaneous send handling', () => {
64
+ const session = {
65
+ sendingChainKey: randomBytes(32),
66
+ receivingChainKey: randomBytes(32),
67
+ };
68
+ handleSimultaneousSend(session, true);
69
+ expect(session.sendingChainKey).not.toEqual(session.receivingChainKey);
70
+ });
71
+ });
72
+ describe('X3DH Edge Cases', () => {
73
+ test('OPK exhaustion', () => {
74
+ generateOPKPool();
75
+ for (let i = 0; i < OPK_POOL_SIZE; i++) {
76
+ consumeOPK();
77
+ }
78
+ expect(() => consumeOPK()).toThrow('OPK pool exhausted');
79
+ });
80
+ test('Partial handshake completion', () => {
81
+ const identityKeyPair = { publicKey: randomBytes(32), privateKey: randomBytes(32) };
82
+ const signedPreKeyPair = { publicKey: randomBytes(32), privateKey: randomBytes(32) };
83
+ const oneTimePreKey = randomBytes(32);
84
+ const recipientIdentityKey = randomBytes(32);
85
+ const recipientSignedPreKey = randomBytes(32);
86
+ const recipientOneTimePreKey = randomBytes(32);
87
+ const recipientSPKSignature = randomBytes(64);
88
+ expect(() => {
89
+ establishSession(identityKeyPair, signedPreKeyPair, oneTimePreKey, recipientIdentityKey, recipientSignedPreKey, recipientOneTimePreKey, recipientSPKSignature, '1.0', 'AES-GCM');
90
+ }).toThrow('Invalid SPK signature');
91
+ });
92
+ test('Abort ordering', () => {
93
+ const identityKeyPair = { publicKey: randomBytes(32), privateKey: randomBytes(32) };
94
+ const signedPreKeyPair = { publicKey: randomBytes(32), privateKey: randomBytes(32) };
95
+ const oneTimePreKey = randomBytes(32);
96
+ const recipientIdentityKey = randomBytes(32);
97
+ const recipientSignedPreKey = randomBytes(32);
98
+ const recipientOneTimePreKey = randomBytes(32);
99
+ const recipientSPKSignature = randomBytes(64);
100
+ try {
101
+ establishSession(identityKeyPair, signedPreKeyPair, oneTimePreKey, recipientIdentityKey, recipientSignedPreKey, recipientOneTimePreKey, recipientSPKSignature, '1.0', 'AES-GCM');
102
+ }
103
+ catch (error) {
104
+ expect(error.message).toBe('Invalid SPK signature');
105
+ }
106
+ });
107
+ });
108
+ describe('2-Man Rule Integrity', () => {
109
+ test('Tamper-evidence for recovery shares', () => {
110
+ const share = randomBytes(32);
111
+ const hash = generateShareHash(share);
112
+ expect(verifyShareIntegrity(share, hash)).toBe(true);
113
+ expect(verifyShareIntegrity(randomBytes(32), hash)).toBe(false);
114
+ });
115
+ });
116
+ describe('Post-Compromise Security (PCS)', () => {
117
+ test('PCS recovery after compromise', () => {
118
+ const session = establishSession({ publicKey: randomBytes(32), privateKey: randomBytes(32) }, { publicKey: randomBytes(32), privateKey: randomBytes(32) }, randomBytes(32), randomBytes(32), randomBytes(32), randomBytes(32));
119
+ const remotePublicKey = randomBytes(32);
120
+ // Simulate compromise
121
+ session.rootKey = randomBytes(32);
122
+ session.sendingChainKey = randomBytes(32);
123
+ session.receivingChainKey = randomBytes(32);
124
+ // Attacker can decrypt messages before recovery
125
+ const compromisedMessage = encryptMessage('Compromised!', session);
126
+ expect(() => decryptMessage(compromisedMessage.ciphertext, compromisedMessage.header, session)).not.toThrow();
127
+ // Perform forced DH ratchet
128
+ forceDHRatchet(session, remotePublicKey);
129
+ // Attacker cannot decrypt new messages
130
+ const recoveredMessage = encryptMessage('Recovered!', session);
131
+ expect(() => decryptMessage(compromisedMessage.ciphertext, compromisedMessage.header, session)).toThrow();
132
+ expect(() => decryptMessage(recoveredMessage.ciphertext, recoveredMessage.header, session)).not.toThrow();
133
+ });
134
+ test('PCS policy enforcement', () => {
135
+ const session = establishSession({ publicKey: randomBytes(32), privateKey: randomBytes(32) }, { publicKey: randomBytes(32), privateKey: randomBytes(32) }, randomBytes(32), randomBytes(32), randomBytes(32), randomBytes(32));
136
+ const remotePublicKey = randomBytes(32);
137
+ // Simulate message sending
138
+ for (let i = 0; i < 50; i++) {
139
+ incrementMessageCounter(session, remotePublicKey);
140
+ }
141
+ // Ensure DH ratchet was triggered
142
+ expect(messageCounter).toBe(0);
143
+ });
144
+ });
145
+ describe('PCS Security Proofs', () => {
146
+ test('rootKeyₜ ≠ rootKeyₜ₊₁ even with full attacker knowledge', () => {
147
+ const session = establishSession({ publicKey: randomBytes(32), privateKey: randomBytes(32) }, { publicKey: randomBytes(32), privateKey: randomBytes(32) }, randomBytes(32), randomBytes(32), randomBytes(32), randomBytes(32));
148
+ const remotePublicKey = randomBytes(32);
149
+ // Simulate attacker knowledge
150
+ const attackerRootKey = session.rootKey;
151
+ const attackerChainKey = session.sendingChainKey;
152
+ const attackerReceivingKey = session.receivingChainKey;
153
+ // Perform DH ratchet
154
+ receiveNewDHPublicKey(session, remotePublicKey);
155
+ // Assert that attacker cannot derive the new root key
156
+ expect(session.rootKey).not.toEqual(attackerRootKey);
157
+ expect(session.sendingChainKey).not.toEqual(attackerChainKey);
158
+ expect(session.receivingChainKey).not.toEqual(attackerReceivingKey);
159
+ });
160
+ });
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Generate a SHA-256 fingerprint for a given public key.
3
+ * @param publicKey - The public key to fingerprint.
4
+ * @returns The fingerprint as a hex string.
5
+ */
6
+ export declare function generateFingerprint(publicKey: Uint8Array): string;
7
+ /**
8
+ * Store the fingerprint in the database.
9
+ * @param userId - The user ID associated with the fingerprint.
10
+ * @param fingerprint - The fingerprint to store.
11
+ */
12
+ export declare function storeFingerprint(userId: string, fingerprint: string): Promise<void>;
13
+ /**
14
+ * Verify the fingerprint against the stored value.
15
+ * @param userId - The user ID associated with the fingerprint.
16
+ * @param fingerprint - The fingerprint to verify.
17
+ * @returns True if the fingerprint matches, false otherwise.
18
+ */
19
+ export declare function verifyFingerprint(userId: string, fingerprint: string): Promise<boolean>;
20
+ /**
21
+ * Honest TOFU Limitations
22
+ *
23
+ * 1. First-session MITM risk: The first connection assumes trust.
24
+ * 2. Fingerprint mismatches result in hard failure.
25
+ * 3. No automatic recovery from key substitution attacks.
26
+ */
27
+ export declare function handleFingerprintMismatch(userId: string): void;
@@ -0,0 +1,62 @@
1
+ import { createHash } from 'crypto';
2
+ import { Pool } from 'pg';
3
+ // PostgreSQL connection pool
4
+ const pool = new Pool({
5
+ connectionString: process.env.DATABASE_URL, // Ensure DATABASE_URL is set in the environment
6
+ });
7
+ /**
8
+ * Generate a SHA-256 fingerprint for a given public key.
9
+ * @param publicKey - The public key to fingerprint.
10
+ * @returns The fingerprint as a hex string.
11
+ */
12
+ export function generateFingerprint(publicKey) {
13
+ const hash = createHash('sha256');
14
+ hash.update(publicKey);
15
+ return hash.digest('hex');
16
+ }
17
+ /**
18
+ * Store the fingerprint in the database.
19
+ * @param userId - The user ID associated with the fingerprint.
20
+ * @param fingerprint - The fingerprint to store.
21
+ */
22
+ export async function storeFingerprint(userId, fingerprint) {
23
+ const client = await pool.connect();
24
+ try {
25
+ await client.query('INSERT INTO fingerprints (user_id, fingerprint) VALUES ($1, $2) ON CONFLICT (user_id) DO UPDATE SET fingerprint = $2', [userId, fingerprint]);
26
+ }
27
+ finally {
28
+ client.release();
29
+ }
30
+ }
31
+ /**
32
+ * Verify the fingerprint against the stored value.
33
+ * @param userId - The user ID associated with the fingerprint.
34
+ * @param fingerprint - The fingerprint to verify.
35
+ * @returns True if the fingerprint matches, false otherwise.
36
+ */
37
+ export async function verifyFingerprint(userId, fingerprint) {
38
+ const client = await pool.connect();
39
+ try {
40
+ const result = await client.query('SELECT fingerprint FROM fingerprints WHERE user_id = $1', [userId]);
41
+ if (result.rows.length === 0) {
42
+ // First use: store the fingerprint
43
+ await storeFingerprint(userId, fingerprint);
44
+ return true;
45
+ }
46
+ return result.rows[0].fingerprint === fingerprint;
47
+ }
48
+ finally {
49
+ client.release();
50
+ }
51
+ }
52
+ /**
53
+ * Honest TOFU Limitations
54
+ *
55
+ * 1. First-session MITM risk: The first connection assumes trust.
56
+ * 2. Fingerprint mismatches result in hard failure.
57
+ * 3. No automatic recovery from key substitution attacks.
58
+ */
59
+ export function handleFingerprintMismatch(userId) {
60
+ console.error(`SECURITY ALERT: Fingerprint mismatch detected for user ${userId}`);
61
+ throw new Error('Fingerprint mismatch detected. Connection aborted.');
62
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stvor/sdk",
3
- "version": "2.2.1",
3
+ "version": "2.3.0",
4
4
  "description": "Stvor DX Facade - Simple E2EE SDK for client-side encryption",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",