release(v4.3.0): browser persistence via @shade/storage-indexeddb
Ship an official IndexedDB-backed StorageProvider so browser-based Shade
consumers persist identity, prekeys, sessions, retired identities,
peer-verification state and stream-resume rows across tab refresh and
browser restart. Closes the gap that forced browser apps onto
storage:"memory" (regenerated identity each load, orphaned device
records server-side).
- New package @shade/storage-indexeddb (4.3.0): full StorageProvider
conformance, schema v1, idb-backed; bumpPeerIdentityVersion is wrapped
in a single readwrite IDB transaction (atomic, vs SQLite's
read-then-upsert race).
- @shade/sdk resolveStorage() accepts { type: 'indexeddb', dbName? } via
dynamic import (lazy, optional dep — same pattern as
@shade/storage-postgres). Named StorageSpec type now reused by
ResolvedConfig.
- Tests: 16 new tests in shade-storage-indexeddb (StorageProvider
surface + peer-verifications + full E2EE conversation surviving a
simulated tab reload). Run on fake-indexeddb.
- Lockstep version bump 4.2.1 → 4.3.0 across all 25 packages.
- Publish scripts updated to include the new package.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
15
packages/shade-storage-indexeddb/package.json
Normal file
15
packages/shade-storage-indexeddb/package.json
Normal file
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"name": "@shade/storage-indexeddb",
|
||||
"version": "4.3.0",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
"dependencies": {
|
||||
"@shade/core": "workspace:*",
|
||||
"idb": "^8.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@shade/crypto-web": "workspace:*",
|
||||
"fake-indexeddb": "^6.0.0"
|
||||
}
|
||||
}
|
||||
1
packages/shade-storage-indexeddb/src/index.ts
Normal file
1
packages/shade-storage-indexeddb/src/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { IndexedDBStorage } from './indexeddb-storage.js';
|
||||
435
packages/shade-storage-indexeddb/src/indexeddb-storage.ts
Normal file
435
packages/shade-storage-indexeddb/src/indexeddb-storage.ts
Normal file
@@ -0,0 +1,435 @@
|
||||
import { openDB, type IDBPDatabase, type DBSchema } from 'idb';
|
||||
import type {
|
||||
StorageProvider,
|
||||
IdentityKeyPair,
|
||||
SignedPreKey,
|
||||
OneTimePreKey,
|
||||
SessionState,
|
||||
RetiredIdentity,
|
||||
PersistedStreamState,
|
||||
PeerVerification,
|
||||
PeerVerificationSource,
|
||||
} from '@shade/core';
|
||||
import {
|
||||
toBase64, fromBase64,
|
||||
constantTimeEqual,
|
||||
serializeSessionState, deserializeSessionState,
|
||||
serializeSignedPreKey, deserializeSignedPreKey,
|
||||
serializeOneTimePreKey, deserializeOneTimePreKey,
|
||||
serializeIdentityKeyPair, deserializeIdentityKeyPair,
|
||||
} from '@shade/core';
|
||||
|
||||
/**
|
||||
* IndexedDB-backed StorageProvider for browser-side Shade clients.
|
||||
*
|
||||
* Persists identity, prekeys, sessions, retired identities, peer
|
||||
* verifications and stream-resume state across tab refresh and browser
|
||||
* restart. Same data shapes as `@shade/storage-sqlite` so cross-adapter
|
||||
* import/export remains feasible.
|
||||
*
|
||||
* Usage:
|
||||
* ```ts
|
||||
* const storage = await IndexedDBStorage.create({ dbName: 'my-app-shade' });
|
||||
* const manager = new ShadeSessionManager(crypto, storage);
|
||||
* ```
|
||||
*/
|
||||
export class IndexedDBStorage implements StorageProvider {
|
||||
private constructor(private db: IDBPDatabase<ShadeSchema>) {}
|
||||
|
||||
/**
|
||||
* Open (or create) the IndexedDB database. Idempotent — repeated calls
|
||||
* with the same dbName resolve to a fresh connection sharing the same
|
||||
* underlying object stores.
|
||||
*/
|
||||
static async create(opts: { dbName?: string } = {}): Promise<IndexedDBStorage> {
|
||||
const dbName = opts.dbName ?? 'shade';
|
||||
const db = await openDB<ShadeSchema>(dbName, SCHEMA_VERSION, {
|
||||
upgrade(db, oldVersion) {
|
||||
if (oldVersion < 1) {
|
||||
db.createObjectStore('identity', { keyPath: 'id' });
|
||||
db.createObjectStore('config', { keyPath: 'key' });
|
||||
db.createObjectStore('signedPreKeys', { keyPath: 'keyId' });
|
||||
db.createObjectStore('oneTimePreKeys', { keyPath: 'keyId' });
|
||||
db.createObjectStore('sessions', { keyPath: 'address' });
|
||||
db.createObjectStore('trustedIdentities', { keyPath: 'address' });
|
||||
|
||||
const retired = db.createObjectStore('retiredIdentities', {
|
||||
keyPath: 'id',
|
||||
autoIncrement: true,
|
||||
});
|
||||
retired.createIndex('byRetiredAt', 'retiredAt');
|
||||
|
||||
const stream = db.createObjectStore('streamStates', { keyPath: 'streamId' });
|
||||
stream.createIndex('byStatus', 'status');
|
||||
stream.createIndex('byPeerAddress', 'peerAddress');
|
||||
stream.createIndex('byUpdatedAt', 'updatedAt');
|
||||
|
||||
db.createObjectStore('peerVerifications', { keyPath: 'peerAddress' });
|
||||
db.createObjectStore('peerIdentityVersions', { keyPath: 'peerAddress' });
|
||||
}
|
||||
},
|
||||
});
|
||||
return new IndexedDBStorage(db);
|
||||
}
|
||||
|
||||
/** Cleanly close the underlying connection. */
|
||||
async close(): Promise<void> {
|
||||
this.db.close();
|
||||
}
|
||||
|
||||
// ─── Identity ──────────────────────────────────────────────
|
||||
|
||||
async getIdentityKeyPair(): Promise<IdentityKeyPair | null> {
|
||||
const row = await this.db.get('identity', 1);
|
||||
if (!row) return null;
|
||||
return {
|
||||
signingPublicKey: fromBase64(row.signingPublicKey),
|
||||
signingPrivateKey: fromBase64(row.signingPrivateKey),
|
||||
dhPublicKey: fromBase64(row.dhPublicKey),
|
||||
dhPrivateKey: fromBase64(row.dhPrivateKey),
|
||||
};
|
||||
}
|
||||
|
||||
async saveIdentityKeyPair(kp: IdentityKeyPair): Promise<void> {
|
||||
await this.db.put('identity', {
|
||||
id: 1,
|
||||
signingPublicKey: toBase64(kp.signingPublicKey),
|
||||
signingPrivateKey: toBase64(kp.signingPrivateKey),
|
||||
dhPublicKey: toBase64(kp.dhPublicKey),
|
||||
dhPrivateKey: toBase64(kp.dhPrivateKey),
|
||||
});
|
||||
}
|
||||
|
||||
async getLocalRegistrationId(): Promise<number> {
|
||||
const row = await this.db.get('config', 'registrationId');
|
||||
return row ? parseInt(row.value, 10) : 0;
|
||||
}
|
||||
|
||||
async saveLocalRegistrationId(id: number): Promise<void> {
|
||||
await this.db.put('config', { key: 'registrationId', value: String(id) });
|
||||
}
|
||||
|
||||
// ─── Signed PreKeys ───────────────────────────────────────
|
||||
|
||||
async getSignedPreKey(keyId: number): Promise<SignedPreKey | null> {
|
||||
const row = await this.db.get('signedPreKeys', keyId);
|
||||
if (!row) return null;
|
||||
return deserializeSignedPreKey(row.dataJson);
|
||||
}
|
||||
|
||||
async saveSignedPreKey(key: SignedPreKey): Promise<void> {
|
||||
await this.db.put('signedPreKeys', {
|
||||
keyId: key.keyId,
|
||||
dataJson: serializeSignedPreKey(key),
|
||||
});
|
||||
}
|
||||
|
||||
async removeSignedPreKey(keyId: number): Promise<void> {
|
||||
await this.db.delete('signedPreKeys', keyId);
|
||||
}
|
||||
|
||||
// ─── One-Time PreKeys ─────────────────────────────────────
|
||||
|
||||
async getOneTimePreKey(keyId: number): Promise<OneTimePreKey | null> {
|
||||
const row = await this.db.get('oneTimePreKeys', keyId);
|
||||
if (!row) return null;
|
||||
return deserializeOneTimePreKey(row.dataJson);
|
||||
}
|
||||
|
||||
async saveOneTimePreKey(key: OneTimePreKey): Promise<void> {
|
||||
await this.db.put('oneTimePreKeys', {
|
||||
keyId: key.keyId,
|
||||
dataJson: serializeOneTimePreKey(key),
|
||||
});
|
||||
}
|
||||
|
||||
async removeOneTimePreKey(keyId: number): Promise<void> {
|
||||
await this.db.delete('oneTimePreKeys', keyId);
|
||||
}
|
||||
|
||||
async getOneTimePreKeyCount(): Promise<number> {
|
||||
return this.db.count('oneTimePreKeys');
|
||||
}
|
||||
|
||||
// ─── Sessions ─────────────────────────────────────────────
|
||||
|
||||
async getSession(address: string): Promise<SessionState | null> {
|
||||
const row = await this.db.get('sessions', address);
|
||||
if (!row) return null;
|
||||
return deserializeSessionState(row.stateJson);
|
||||
}
|
||||
|
||||
async saveSession(address: string, state: SessionState): Promise<void> {
|
||||
await this.db.put('sessions', { address, stateJson: serializeSessionState(state) });
|
||||
}
|
||||
|
||||
async removeSession(address: string): Promise<void> {
|
||||
await this.db.delete('sessions', address);
|
||||
}
|
||||
|
||||
// ─── Trust ────────────────────────────────────────────────
|
||||
|
||||
async isTrustedIdentity(address: string, identityKey: Uint8Array): Promise<boolean> {
|
||||
const row = await this.db.get('trustedIdentities', address);
|
||||
if (!row) return true; // TOFU
|
||||
const stored = fromBase64(row.identityKey);
|
||||
return constantTimeEqual(stored, identityKey);
|
||||
}
|
||||
|
||||
async saveTrustedIdentity(address: string, identityKey: Uint8Array): Promise<void> {
|
||||
await this.db.put('trustedIdentities', { address, identityKey: toBase64(identityKey) });
|
||||
}
|
||||
|
||||
// ─── Identity History ─────────────────────────────────────
|
||||
|
||||
async addRetiredIdentity(identity: RetiredIdentity): Promise<void> {
|
||||
// autoIncrement: omit `id` so IDB assigns one
|
||||
await this.db.add('retiredIdentities', {
|
||||
dataJson: serializeIdentityKeyPair(identity.keyPair),
|
||||
retiredAt: identity.retiredAt,
|
||||
} as RetiredIdentityRow);
|
||||
}
|
||||
|
||||
async getRetiredIdentities(): Promise<RetiredIdentity[]> {
|
||||
// Mirror SQLite's `ORDER BY retired_at DESC`
|
||||
const rows = await this.db.getAllFromIndex('retiredIdentities', 'byRetiredAt');
|
||||
rows.reverse();
|
||||
return rows.map((r) => ({
|
||||
keyPair: deserializeIdentityKeyPair(r.dataJson),
|
||||
retiredAt: r.retiredAt,
|
||||
}));
|
||||
}
|
||||
|
||||
async pruneRetiredIdentities(olderThan: number): Promise<void> {
|
||||
const tx = this.db.transaction('retiredIdentities', 'readwrite');
|
||||
const idx = tx.store.index('byRetiredAt');
|
||||
const range = IDBKeyRange.upperBound(olderThan, true);
|
||||
let cursor = await idx.openCursor(range);
|
||||
while (cursor) {
|
||||
await cursor.delete();
|
||||
cursor = await cursor.continue();
|
||||
}
|
||||
await tx.done;
|
||||
}
|
||||
|
||||
// ─── Stream-transfer resume state ─────────────────────────
|
||||
|
||||
async saveStreamState(state: PersistedStreamState): Promise<void> {
|
||||
await this.db.put('streamStates', persistedToRow(state));
|
||||
}
|
||||
|
||||
async getStreamState(streamId: string): Promise<PersistedStreamState | null> {
|
||||
const row = await this.db.get('streamStates', streamId);
|
||||
if (!row) return null;
|
||||
return rowToPersisted(row);
|
||||
}
|
||||
|
||||
async removeStreamState(streamId: string): Promise<void> {
|
||||
await this.db.delete('streamStates', streamId);
|
||||
}
|
||||
|
||||
async listActiveStreamStates(direction?: 'send' | 'receive'): Promise<PersistedStreamState[]> {
|
||||
const idx = this.db.transaction('streamStates').store.index('byStatus');
|
||||
const active = await idx.getAll(IDBKeyRange.only('active'));
|
||||
const paused = await idx.getAll(IDBKeyRange.only('paused'));
|
||||
const merged = [...active, ...paused];
|
||||
const filtered = direction === undefined
|
||||
? merged
|
||||
: merged.filter((r) => r.direction === direction);
|
||||
filtered.sort((a, b) => b.updatedAt - a.updatedAt);
|
||||
return filtered.map(rowToPersisted);
|
||||
}
|
||||
|
||||
async pruneStreamStates(olderThan: number): Promise<void> {
|
||||
const tx = this.db.transaction('streamStates', 'readwrite');
|
||||
const idx = tx.store.index('byUpdatedAt');
|
||||
const range = IDBKeyRange.upperBound(olderThan, true);
|
||||
let cursor = await idx.openCursor(range);
|
||||
while (cursor) {
|
||||
const row = cursor.value;
|
||||
if (row.status === 'finished' || row.status === 'aborted') {
|
||||
await cursor.delete();
|
||||
}
|
||||
cursor = await cursor.continue();
|
||||
}
|
||||
await tx.done;
|
||||
}
|
||||
|
||||
// ─── Peer verifications (V3.3) ────────────────────────────
|
||||
|
||||
async savePeerVerification(v: PeerVerification): Promise<void> {
|
||||
await this.db.put('peerVerifications', { ...v });
|
||||
}
|
||||
|
||||
async getPeerVerification(address: string): Promise<PeerVerification | null> {
|
||||
const row = await this.db.get('peerVerifications', address);
|
||||
if (!row) return null;
|
||||
return {
|
||||
peerAddress: row.peerAddress,
|
||||
fingerprint: row.fingerprint,
|
||||
verifiedAt: row.verifiedAt,
|
||||
verifiedBy: row.verifiedBy as PeerVerificationSource,
|
||||
identityVersion: row.identityVersion,
|
||||
};
|
||||
}
|
||||
|
||||
async removePeerVerification(address: string): Promise<void> {
|
||||
await this.db.delete('peerVerifications', address);
|
||||
}
|
||||
|
||||
async getPeerIdentityVersion(address: string): Promise<number> {
|
||||
const row = await this.db.get('peerIdentityVersions', address);
|
||||
return row ? row.version : 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomic read-modify-write under one IDB transaction. SQLite's version
|
||||
* is a non-atomic read-then-upsert; the IDB version closes that race
|
||||
* because IDB transactions auto-commit only when control returns to
|
||||
* the event loop without pending requests.
|
||||
*/
|
||||
async bumpPeerIdentityVersion(address: string): Promise<number> {
|
||||
const tx = this.db.transaction('peerIdentityVersions', 'readwrite');
|
||||
const existing = await tx.store.get(address);
|
||||
const next = (existing ? existing.version : 1) + 1;
|
||||
await tx.store.put({ peerAddress: address, version: next });
|
||||
await tx.done;
|
||||
return next;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Schema ────────────────────────────────────────────────
|
||||
|
||||
const SCHEMA_VERSION = 1;
|
||||
|
||||
interface IdentityRow {
|
||||
id: 1;
|
||||
signingPublicKey: string;
|
||||
signingPrivateKey: string;
|
||||
dhPublicKey: string;
|
||||
dhPrivateKey: string;
|
||||
}
|
||||
|
||||
interface ConfigRow {
|
||||
key: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
interface SignedPreKeyRow {
|
||||
keyId: number;
|
||||
dataJson: string;
|
||||
}
|
||||
|
||||
interface OneTimePreKeyRow {
|
||||
keyId: number;
|
||||
dataJson: string;
|
||||
}
|
||||
|
||||
interface SessionRow {
|
||||
address: string;
|
||||
stateJson: string;
|
||||
}
|
||||
|
||||
interface TrustedIdentityRow {
|
||||
address: string;
|
||||
identityKey: string;
|
||||
}
|
||||
|
||||
interface RetiredIdentityRow {
|
||||
id?: number;
|
||||
dataJson: string;
|
||||
retiredAt: number;
|
||||
}
|
||||
|
||||
interface StreamStateRow {
|
||||
streamId: string;
|
||||
direction: 'send' | 'receive';
|
||||
peerAddress: string;
|
||||
status: 'active' | 'paused' | 'finished' | 'aborted';
|
||||
metadataJson: string;
|
||||
partitionJson: string;
|
||||
laneStateJson: string;
|
||||
ioDescriptorJson: string;
|
||||
secretEnc: Uint8Array;
|
||||
secretNonce: Uint8Array;
|
||||
overallHashState: string | null;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
interface PeerVerificationRow {
|
||||
peerAddress: string;
|
||||
fingerprint: string;
|
||||
verifiedAt: number;
|
||||
verifiedBy: string;
|
||||
identityVersion: number;
|
||||
}
|
||||
|
||||
interface PeerIdentityVersionRow {
|
||||
peerAddress: string;
|
||||
version: number;
|
||||
}
|
||||
|
||||
interface ShadeSchema extends DBSchema {
|
||||
identity: { key: number; value: IdentityRow };
|
||||
config: { key: string; value: ConfigRow };
|
||||
signedPreKeys: { key: number; value: SignedPreKeyRow };
|
||||
oneTimePreKeys: { key: number; value: OneTimePreKeyRow };
|
||||
sessions: { key: string; value: SessionRow };
|
||||
trustedIdentities: { key: string; value: TrustedIdentityRow };
|
||||
retiredIdentities: {
|
||||
key: number;
|
||||
value: RetiredIdentityRow;
|
||||
indexes: { byRetiredAt: number };
|
||||
};
|
||||
streamStates: {
|
||||
key: string;
|
||||
value: StreamStateRow;
|
||||
indexes: {
|
||||
byStatus: string;
|
||||
byPeerAddress: string;
|
||||
byUpdatedAt: number;
|
||||
};
|
||||
};
|
||||
peerVerifications: { key: string; value: PeerVerificationRow };
|
||||
peerIdentityVersions: { key: string; value: PeerIdentityVersionRow };
|
||||
}
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────
|
||||
|
||||
function persistedToRow(s: PersistedStreamState): StreamStateRow {
|
||||
return {
|
||||
streamId: s.streamId,
|
||||
direction: s.direction,
|
||||
peerAddress: s.peerAddress,
|
||||
status: s.status,
|
||||
metadataJson: s.metadataJson,
|
||||
partitionJson: s.partitionJson,
|
||||
laneStateJson: s.laneStateJson,
|
||||
ioDescriptorJson: s.ioDescriptorJson,
|
||||
secretEnc: s.secretEnc,
|
||||
secretNonce: s.secretNonce,
|
||||
overallHashState: s.overallHashState ?? null,
|
||||
createdAt: s.createdAt,
|
||||
updatedAt: s.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function rowToPersisted(r: StreamStateRow): PersistedStreamState {
|
||||
const out: PersistedStreamState = {
|
||||
streamId: r.streamId,
|
||||
direction: r.direction,
|
||||
peerAddress: r.peerAddress,
|
||||
status: r.status,
|
||||
metadataJson: r.metadataJson,
|
||||
partitionJson: r.partitionJson,
|
||||
laneStateJson: r.laneStateJson,
|
||||
ioDescriptorJson: r.ioDescriptorJson,
|
||||
secretEnc: r.secretEnc,
|
||||
secretNonce: r.secretNonce,
|
||||
createdAt: r.createdAt,
|
||||
updatedAt: r.updatedAt,
|
||||
};
|
||||
if (r.overallHashState !== null) out.overallHashState = r.overallHashState;
|
||||
return out;
|
||||
}
|
||||
272
packages/shade-storage-indexeddb/tests/indexeddb-storage.test.ts
Normal file
272
packages/shade-storage-indexeddb/tests/indexeddb-storage.test.ts
Normal file
@@ -0,0 +1,272 @@
|
||||
import 'fake-indexeddb/auto';
|
||||
import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
|
||||
import { IndexedDBStorage } from '../src/indexeddb-storage.js';
|
||||
import { SubtleCryptoProvider, MemoryStorage as _MemoryStorage } from '@shade/crypto-web';
|
||||
import { ShadeSessionManager } from '@shade/core';
|
||||
import type { IdentityKeyPair, SignedPreKey, OneTimePreKey } from '@shade/core';
|
||||
|
||||
void _MemoryStorage; // keep import side-effect-free reference shape
|
||||
|
||||
const crypto = new SubtleCryptoProvider();
|
||||
|
||||
function randBytes(n: number): Uint8Array {
|
||||
const buf = new Uint8Array(n);
|
||||
globalThis.crypto.getRandomValues(buf);
|
||||
return buf;
|
||||
}
|
||||
|
||||
function uniqueDbName(): string {
|
||||
return `shade-test-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
||||
}
|
||||
|
||||
async function deleteDb(dbName: string): Promise<void> {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const req = indexedDB.deleteDatabase(dbName);
|
||||
req.onsuccess = () => resolve();
|
||||
req.onerror = () => reject(req.error);
|
||||
req.onblocked = () => resolve();
|
||||
});
|
||||
}
|
||||
|
||||
describe('IndexedDBStorage', () => {
|
||||
let dbName: string;
|
||||
let storage: IndexedDBStorage;
|
||||
|
||||
beforeEach(async () => {
|
||||
dbName = uniqueDbName();
|
||||
storage = await IndexedDBStorage.create({ dbName });
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await storage.close();
|
||||
await deleteDb(dbName);
|
||||
});
|
||||
|
||||
// ─── Identity ──────────────────────────────────────────────
|
||||
|
||||
describe('identity', () => {
|
||||
test('returns null when no identity stored', async () => {
|
||||
expect(await storage.getIdentityKeyPair()).toBeNull();
|
||||
});
|
||||
|
||||
test('save and retrieve identity keypair', async () => {
|
||||
const ikp: IdentityKeyPair = {
|
||||
signingPublicKey: randBytes(32),
|
||||
signingPrivateKey: randBytes(32),
|
||||
dhPublicKey: randBytes(32),
|
||||
dhPrivateKey: randBytes(32),
|
||||
};
|
||||
await storage.saveIdentityKeyPair(ikp);
|
||||
const restored = await storage.getIdentityKeyPair();
|
||||
expect(restored).not.toBeNull();
|
||||
expect(restored!.signingPublicKey).toEqual(ikp.signingPublicKey);
|
||||
expect(restored!.dhPrivateKey).toEqual(ikp.dhPrivateKey);
|
||||
});
|
||||
|
||||
test('registration ID roundtrip', async () => {
|
||||
expect(await storage.getLocalRegistrationId()).toBe(0);
|
||||
await storage.saveLocalRegistrationId(42);
|
||||
expect(await storage.getLocalRegistrationId()).toBe(42);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Signed PreKeys ───────────────────────────────────────
|
||||
|
||||
describe('signed prekeys', () => {
|
||||
test('save, get, remove', async () => {
|
||||
const spk: SignedPreKey = {
|
||||
keyId: 1,
|
||||
keyPair: { publicKey: randBytes(32), privateKey: randBytes(32) },
|
||||
signature: randBytes(64),
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
await storage.saveSignedPreKey(spk);
|
||||
const restored = await storage.getSignedPreKey(1);
|
||||
expect(restored).not.toBeNull();
|
||||
expect(restored!.keyId).toBe(1);
|
||||
expect(restored!.keyPair.publicKey).toEqual(spk.keyPair.publicKey);
|
||||
|
||||
await storage.removeSignedPreKey(1);
|
||||
expect(await storage.getSignedPreKey(1)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── One-Time PreKeys ─────────────────────────────────────
|
||||
|
||||
describe('one-time prekeys', () => {
|
||||
test('save, get, remove, count', async () => {
|
||||
const otpk: OneTimePreKey = {
|
||||
keyId: 100,
|
||||
keyPair: { publicKey: randBytes(32), privateKey: randBytes(32) },
|
||||
};
|
||||
await storage.saveOneTimePreKey(otpk);
|
||||
expect(await storage.getOneTimePreKeyCount()).toBe(1);
|
||||
|
||||
const restored = await storage.getOneTimePreKey(100);
|
||||
expect(restored!.keyId).toBe(100);
|
||||
|
||||
await storage.removeOneTimePreKey(100);
|
||||
expect(await storage.getOneTimePreKeyCount()).toBe(0);
|
||||
expect(await storage.getOneTimePreKey(100)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Sessions ─────────────────────────────────────────────
|
||||
|
||||
describe('sessions', () => {
|
||||
test('save and restore session with skipped keys', async () => {
|
||||
const state = {
|
||||
remoteIdentityKey: randBytes(32),
|
||||
rootKey: randBytes(32),
|
||||
sendChain: { chainKey: randBytes(32), counter: 5 },
|
||||
receiveChain: { chainKey: randBytes(32), counter: 3 },
|
||||
dhSend: { publicKey: randBytes(32), privateKey: randBytes(32) },
|
||||
dhReceive: randBytes(32),
|
||||
previousSendCounter: 4,
|
||||
skippedKeys: new Map([['key:1', randBytes(32)]]),
|
||||
};
|
||||
|
||||
await storage.saveSession('bob', state);
|
||||
const restored = await storage.getSession('bob');
|
||||
expect(restored).not.toBeNull();
|
||||
expect(restored!.sendChain.counter).toBe(5);
|
||||
expect(restored!.skippedKeys.size).toBe(1);
|
||||
expect(restored!.skippedKeys.get('key:1')).toEqual(state.skippedKeys.get('key:1')!);
|
||||
});
|
||||
|
||||
test('remove session', async () => {
|
||||
await storage.saveSession('bob', {
|
||||
remoteIdentityKey: randBytes(32),
|
||||
rootKey: randBytes(32),
|
||||
sendChain: { chainKey: randBytes(32), counter: 0 },
|
||||
receiveChain: null,
|
||||
dhSend: { publicKey: randBytes(32), privateKey: randBytes(32) },
|
||||
dhReceive: null,
|
||||
previousSendCounter: 0,
|
||||
skippedKeys: new Map(),
|
||||
});
|
||||
await storage.removeSession('bob');
|
||||
expect(await storage.getSession('bob')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Trust ────────────────────────────────────────────────
|
||||
|
||||
describe('trust', () => {
|
||||
test('TOFU: first use is trusted', async () => {
|
||||
expect(await storage.isTrustedIdentity('bob', randBytes(32))).toBe(true);
|
||||
});
|
||||
|
||||
test('saved identity matches', async () => {
|
||||
const key = randBytes(32);
|
||||
await storage.saveTrustedIdentity('bob', key);
|
||||
expect(await storage.isTrustedIdentity('bob', key)).toBe(true);
|
||||
expect(await storage.isTrustedIdentity('bob', randBytes(32))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Retired identities ───────────────────────────────────
|
||||
|
||||
describe('retired identities', () => {
|
||||
test('add, list (newest first), prune', async () => {
|
||||
const mk = (retiredAt: number): { keyPair: IdentityKeyPair; retiredAt: number } => ({
|
||||
keyPair: {
|
||||
signingPublicKey: randBytes(32),
|
||||
signingPrivateKey: randBytes(32),
|
||||
dhPublicKey: randBytes(32),
|
||||
dhPrivateKey: randBytes(32),
|
||||
},
|
||||
retiredAt,
|
||||
});
|
||||
|
||||
await storage.addRetiredIdentity(mk(100));
|
||||
await storage.addRetiredIdentity(mk(300));
|
||||
await storage.addRetiredIdentity(mk(200));
|
||||
|
||||
const list = await storage.getRetiredIdentities();
|
||||
expect(list.map((r) => r.retiredAt)).toEqual([300, 200, 100]);
|
||||
|
||||
await storage.pruneRetiredIdentities(250);
|
||||
const after = await storage.getRetiredIdentities();
|
||||
expect(after.map((r) => r.retiredAt)).toEqual([300]);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Crash Recovery ───────────────────────────────────────
|
||||
|
||||
describe('persistence across close/reopen', () => {
|
||||
test('data survives close and reopen', async () => {
|
||||
const ikp: IdentityKeyPair = {
|
||||
signingPublicKey: randBytes(32),
|
||||
signingPrivateKey: randBytes(32),
|
||||
dhPublicKey: randBytes(32),
|
||||
dhPrivateKey: randBytes(32),
|
||||
};
|
||||
await storage.saveIdentityKeyPair(ikp);
|
||||
await storage.saveLocalRegistrationId(99);
|
||||
await storage.saveSession('alice', {
|
||||
remoteIdentityKey: randBytes(32),
|
||||
rootKey: randBytes(32),
|
||||
sendChain: { chainKey: randBytes(32), counter: 7 },
|
||||
receiveChain: null,
|
||||
dhSend: { publicKey: randBytes(32), privateKey: randBytes(32) },
|
||||
dhReceive: null,
|
||||
previousSendCounter: 0,
|
||||
skippedKeys: new Map(),
|
||||
});
|
||||
|
||||
// Close and reopen against the same dbName
|
||||
await storage.close();
|
||||
storage = await IndexedDBStorage.create({ dbName });
|
||||
|
||||
const restored = await storage.getIdentityKeyPair();
|
||||
expect(restored!.signingPublicKey).toEqual(ikp.signingPublicKey);
|
||||
expect(await storage.getLocalRegistrationId()).toBe(99);
|
||||
const session = await storage.getSession('alice');
|
||||
expect(session!.sendChain.counter).toBe(7);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Full E2EE with IndexedDBStorage ──────────────────────
|
||||
|
||||
describe('full E2EE conversation with persistent storage', () => {
|
||||
test('encrypt, close, reopen, continue conversation', async () => {
|
||||
const bobDbName = uniqueDbName();
|
||||
let bobStorage = await IndexedDBStorage.create({ dbName: bobDbName });
|
||||
|
||||
try {
|
||||
const alice = new ShadeSessionManager(crypto, storage);
|
||||
let bob = new ShadeSessionManager(crypto, bobStorage);
|
||||
await alice.initialize();
|
||||
await bob.initialize();
|
||||
|
||||
const otpks = await bob.generateOneTimePreKeys(5);
|
||||
const bundle = await bob.createPreKeyBundle();
|
||||
bundle.oneTimePreKey = { keyId: otpks[0]!.keyId, publicKey: otpks[0]!.keyPair.publicKey };
|
||||
|
||||
await alice.initSessionFromBundle('bob', bundle);
|
||||
|
||||
const env1 = await alice.encrypt('bob', 'Hello persistent!');
|
||||
expect(await bob.decrypt('alice', env1)).toBe('Hello persistent!');
|
||||
|
||||
const env2 = await bob.encrypt('alice', 'Got it!');
|
||||
expect(await alice.decrypt('bob', env2)).toBe('Got it!');
|
||||
|
||||
// "Crash" Bob — close the IDB and reopen
|
||||
await bobStorage.close();
|
||||
bobStorage = await IndexedDBStorage.create({ dbName: bobDbName });
|
||||
bob = new ShadeSessionManager(crypto, bobStorage);
|
||||
await bob.initialize();
|
||||
|
||||
const env3 = await alice.encrypt('bob', 'After your restart');
|
||||
expect(await bob.decrypt('alice', env3)).toBe('After your restart');
|
||||
|
||||
const env4 = await bob.encrypt('alice', 'I survived!');
|
||||
expect(await alice.decrypt('bob', env4)).toBe('I survived!');
|
||||
} finally {
|
||||
await bobStorage.close();
|
||||
await deleteDb(bobDbName);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
import 'fake-indexeddb/auto';
|
||||
import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
|
||||
import { IndexedDBStorage } from '../src/index.js';
|
||||
|
||||
function uniqueDbName(): string {
|
||||
return `shade-test-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
||||
}
|
||||
|
||||
async function deleteDb(dbName: string): Promise<void> {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const req = indexedDB.deleteDatabase(dbName);
|
||||
req.onsuccess = () => resolve();
|
||||
req.onerror = () => reject(req.error);
|
||||
req.onblocked = () => resolve();
|
||||
});
|
||||
}
|
||||
|
||||
describe('IndexedDBStorage — peer_verifications (V3.3)', () => {
|
||||
let dbName: string;
|
||||
let storage: IndexedDBStorage;
|
||||
|
||||
beforeEach(async () => {
|
||||
dbName = uniqueDbName();
|
||||
storage = await IndexedDBStorage.create({ dbName });
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await storage.close();
|
||||
await deleteDb(dbName);
|
||||
});
|
||||
|
||||
test('round trip: save → get → remove', async () => {
|
||||
await storage.savePeerVerification({
|
||||
peerAddress: 'bob',
|
||||
fingerprint: '12345 67890 12345 67890 12345 67890 12345 67890 12345 67890 12345 67890',
|
||||
verifiedAt: 1_700_000_000_000,
|
||||
verifiedBy: 'user',
|
||||
identityVersion: 1,
|
||||
});
|
||||
|
||||
const v = await storage.getPeerVerification('bob');
|
||||
expect(v).not.toBeNull();
|
||||
expect(v!.peerAddress).toBe('bob');
|
||||
expect(v!.verifiedBy).toBe('user');
|
||||
expect(v!.identityVersion).toBe(1);
|
||||
|
||||
await storage.removePeerVerification('bob');
|
||||
expect(await storage.getPeerVerification('bob')).toBeNull();
|
||||
});
|
||||
|
||||
test('upsert overwrites on duplicate peer_address', async () => {
|
||||
await storage.savePeerVerification({
|
||||
peerAddress: 'bob',
|
||||
fingerprint: 'fp-1',
|
||||
verifiedAt: 1,
|
||||
verifiedBy: 'user',
|
||||
identityVersion: 1,
|
||||
});
|
||||
await storage.savePeerVerification({
|
||||
peerAddress: 'bob',
|
||||
fingerprint: 'fp-2',
|
||||
verifiedAt: 2,
|
||||
verifiedBy: 'transitive',
|
||||
identityVersion: 2,
|
||||
});
|
||||
|
||||
const v = await storage.getPeerVerification('bob');
|
||||
expect(v!.fingerprint).toBe('fp-2');
|
||||
expect(v!.verifiedBy).toBe('transitive');
|
||||
expect(v!.identityVersion).toBe(2);
|
||||
});
|
||||
|
||||
test('identity-version starts at 1 and increments via bump', async () => {
|
||||
expect(await storage.getPeerIdentityVersion('alice')).toBe(1);
|
||||
expect(await storage.bumpPeerIdentityVersion('alice')).toBe(2);
|
||||
expect(await storage.bumpPeerIdentityVersion('alice')).toBe(3);
|
||||
expect(await storage.getPeerIdentityVersion('alice')).toBe(3);
|
||||
// Independent counter per peer
|
||||
expect(await storage.getPeerIdentityVersion('bob')).toBe(1);
|
||||
});
|
||||
|
||||
test('survives reopen', async () => {
|
||||
await storage.savePeerVerification({
|
||||
peerAddress: 'bob',
|
||||
fingerprint: 'fp',
|
||||
verifiedAt: 42,
|
||||
verifiedBy: 'user',
|
||||
identityVersion: 5,
|
||||
});
|
||||
await storage.bumpPeerIdentityVersion('bob');
|
||||
await storage.close();
|
||||
|
||||
storage = await IndexedDBStorage.create({ dbName });
|
||||
const v = await storage.getPeerVerification('bob');
|
||||
expect(v!.fingerprint).toBe('fp');
|
||||
expect(v!.identityVersion).toBe(5);
|
||||
expect(await storage.getPeerIdentityVersion('bob')).toBe(2);
|
||||
});
|
||||
});
|
||||
9
packages/shade-storage-indexeddb/tsconfig.json
Normal file
9
packages/shade-storage-indexeddb/tsconfig.json
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"lib": ["ES2022", "DOM"]
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
Reference in New Issue
Block a user