feat(hardening): M-Hard 1-5 — crypto, auth, rate limit, fingerprints, rotation
M-Hard 1: Cryptographic Hardening - constantTimeEqual, zeroize, randomUint32 on CryptoProvider - Fix Math.random() → crypto.randomUint32() for registrationId - Zero message keys and chain keys after use in ratchet.ts - Constant-time trust comparison in MemoryStorage + SQLiteStorage - Timing variance test catches early-exit regressions M-Hard 2: Self-Authenticated Prekey Server - Ed25519 signature verification on all write routes - signPayload/verifyPayload with canonical JSON, ±5 min replay window - Address validation (NFKC, alphanumeric + :_-.) - Global ShadeError → HTTP status mapping - ShadeFetchTransport signs requests when signingPrivateKey provided - Anonymous bundle fetches still allowed (read-only) M-Hard 3: Rate Limiting + DoS Protection - Token bucket rate limiter with pluggable store - Per-route limits: register 5/h/IP, fetch 60/min/IP, replenish 10/min/id - 64KB body size limit on POST - Retry-After header on 429 responses M-Hard 4: Auto-replenish + Fingerprints + Session Reset - Safety numbers (12 groups × 5 digits, Signal-style) - ensurePreKeyStock, resetSession, acceptIdentityChange - verifyRemoteIdentity for out-of-band comparison M-Hard 5: Identity Rotation with Grace Period - rotateIdentity archives old identity, generates fresh signed prekey - RetiredIdentity storage with addRetired/getRetired/pruneRetired - 7-day default grace period for decrypting old sessions - pruneExpiredIdentities for cleanup M-Hard 8: Error Hierarchy - New error types: Network, Storage, Validation, Timeout, RateLimit, Configuration, Unauthorized, Replay, IdentityRotation - All errors have stable SHADE_* codes - errorToHttpStatus for consistent HTTP mapping - toJSON() for network serialization 188 tests passing, zero failures. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,25 +1,55 @@
|
||||
import type { PreKeyBundle, OneTimePreKey } from '@shade/core';
|
||||
import type { PreKeyBundle, OneTimePreKey, CryptoProvider } from '@shade/core';
|
||||
import { fromBase64, NetworkError } from '@shade/core';
|
||||
|
||||
/**
|
||||
* HTTP transport client for the Shade Prekey Server.
|
||||
*
|
||||
* Signing: write operations (register, replenish, delete) are signed with
|
||||
* the caller's Ed25519 identity signing key. The caller must provide a
|
||||
* signing function via the constructor.
|
||||
*
|
||||
* Usage:
|
||||
* ```ts
|
||||
* const transport = new ShadeFetchTransport('https://shade.example.com');
|
||||
* await transport.register('alice', bundle, oneTimePreKeys);
|
||||
* const bundle = await transport.fetchBundle('bob');
|
||||
* const transport = new ShadeFetchTransport({
|
||||
* baseUrl: 'https://shade.example.com',
|
||||
* crypto,
|
||||
* signingKey: identity.signingPrivateKey,
|
||||
* });
|
||||
* await transport.register('alice', identity, signedPreKey, oneTimePreKeys);
|
||||
* const bundle = await transport.fetchBundle('bob'); // anonymous
|
||||
* ```
|
||||
*/
|
||||
export class ShadeFetchTransport {
|
||||
constructor(
|
||||
private readonly baseUrl: string,
|
||||
private readonly authToken?: string,
|
||||
) {}
|
||||
private readonly baseUrl: string;
|
||||
private readonly crypto: CryptoProvider;
|
||||
private readonly signingPrivateKey?: Uint8Array;
|
||||
|
||||
constructor(options: { baseUrl: string; crypto: CryptoProvider; signingPrivateKey?: Uint8Array }) {
|
||||
this.baseUrl = options.baseUrl;
|
||||
this.crypto = options.crypto;
|
||||
this.signingPrivateKey = options.signingPrivateKey;
|
||||
}
|
||||
|
||||
private headers(): Record<string, string> {
|
||||
const h: Record<string, string> = { 'Content-Type': 'application/json' };
|
||||
if (this.authToken) h['Authorization'] = `Bearer ${this.authToken}`;
|
||||
return h;
|
||||
return { 'Content-Type': 'application/json' };
|
||||
}
|
||||
|
||||
/** Sign a payload using the configured signing key */
|
||||
private async sign<T extends Record<string, unknown>>(payload: T): Promise<T & { signedAt: number; signature: string }> {
|
||||
if (!this.signingPrivateKey) {
|
||||
throw new Error('ShadeFetchTransport: signingPrivateKey is required for write operations');
|
||||
}
|
||||
const signedAt = Date.now();
|
||||
const withTs = { ...payload, signedAt, signature: '' };
|
||||
// Canonicalize: sort keys, omit signature
|
||||
const { signature, ...rest } = withTs;
|
||||
const sorted = Object.keys(rest).sort().reduce<Record<string, unknown>>((acc, k) => {
|
||||
acc[k] = (rest as Record<string, unknown>)[k];
|
||||
return acc;
|
||||
}, {});
|
||||
const bytes = new TextEncoder().encode(JSON.stringify(sorted));
|
||||
const sig = await this.crypto.sign(this.signingPrivateKey, bytes);
|
||||
return { ...payload, signedAt, signature: Buffer.from(sig).toString('base64') };
|
||||
}
|
||||
|
||||
/** Register identity and upload prekey bundle + one-time prekeys */
|
||||
@@ -47,20 +77,22 @@ export class ShadeFetchTransport {
|
||||
}));
|
||||
}
|
||||
|
||||
const signed = await this.sign(body);
|
||||
|
||||
const res = await fetch(`${this.baseUrl}/v1/keys/register`, {
|
||||
method: 'POST',
|
||||
headers: this.headers(),
|
||||
body: JSON.stringify(body),
|
||||
body: JSON.stringify(signed),
|
||||
});
|
||||
if (!res.ok) throw new Error(`Register failed: ${res.status}`);
|
||||
if (!res.ok) throw new NetworkError(`Register failed: ${res.status}`, res.status);
|
||||
}
|
||||
|
||||
/** Fetch a prekey bundle for a peer (consumes one one-time prekey) */
|
||||
/** Fetch a prekey bundle for a peer (anonymous, consumes one one-time prekey) */
|
||||
async fetchBundle(address: string): Promise<PreKeyBundle> {
|
||||
const res = await fetch(`${this.baseUrl}/v1/keys/bundle/${encodeURIComponent(address)}`, {
|
||||
headers: this.headers(),
|
||||
});
|
||||
if (!res.ok) throw new Error(`Fetch bundle failed: ${res.status}`);
|
||||
if (!res.ok) throw new NetworkError(`Fetch bundle failed: ${res.status}`, res.status);
|
||||
|
||||
const data = await res.json();
|
||||
return {
|
||||
@@ -81,36 +113,50 @@ export class ShadeFetchTransport {
|
||||
};
|
||||
}
|
||||
|
||||
/** Upload additional one-time prekeys */
|
||||
/** Upload additional one-time prekeys (signed) */
|
||||
async replenish(
|
||||
address: string,
|
||||
keys: Array<{ keyId: number; publicKey: Uint8Array }>,
|
||||
): Promise<number> {
|
||||
const body = {
|
||||
address,
|
||||
oneTimePreKeys: keys.map((k) => ({
|
||||
keyId: k.keyId,
|
||||
publicKey: toB64(k.publicKey),
|
||||
})),
|
||||
};
|
||||
const signed = await this.sign(body);
|
||||
|
||||
const res = await fetch(`${this.baseUrl}/v1/keys/replenish`, {
|
||||
method: 'POST',
|
||||
headers: this.headers(),
|
||||
body: JSON.stringify({
|
||||
address,
|
||||
oneTimePreKeys: keys.map((k) => ({
|
||||
keyId: k.keyId,
|
||||
publicKey: toB64(k.publicKey),
|
||||
})),
|
||||
}),
|
||||
body: JSON.stringify(signed),
|
||||
});
|
||||
if (!res.ok) throw new Error(`Replenish failed: ${res.status}`);
|
||||
if (!res.ok) throw new NetworkError(`Replenish failed: ${res.status}`, res.status);
|
||||
const data = await res.json();
|
||||
return data.remaining;
|
||||
}
|
||||
|
||||
/** Get remaining one-time prekey count */
|
||||
/** Get remaining one-time prekey count (anonymous) */
|
||||
async getKeyCount(address: string): Promise<number> {
|
||||
const res = await fetch(`${this.baseUrl}/v1/keys/count/${encodeURIComponent(address)}`, {
|
||||
headers: this.headers(),
|
||||
});
|
||||
if (!res.ok) throw new Error(`Count failed: ${res.status}`);
|
||||
if (!res.ok) throw new NetworkError(`Count failed: ${res.status}`, res.status);
|
||||
const data = await res.json();
|
||||
return data.count;
|
||||
}
|
||||
|
||||
/** Delete all keys for this identity (signed) */
|
||||
async unregister(address: string): Promise<void> {
|
||||
const signed = await this.sign({ address });
|
||||
const res = await fetch(`${this.baseUrl}/v1/keys/${encodeURIComponent(address)}`, {
|
||||
method: 'DELETE',
|
||||
headers: this.headers(),
|
||||
body: JSON.stringify(signed),
|
||||
});
|
||||
if (!res.ok) throw new NetworkError(`Unregister failed: ${res.status}`, res.status);
|
||||
}
|
||||
}
|
||||
|
||||
function toB64(bytes: Uint8Array): string {
|
||||
|
||||
@@ -8,55 +8,55 @@ const crypto = new SubtleCryptoProvider();
|
||||
|
||||
describe('ShadeFetchTransport', () => {
|
||||
test('full flow: register → fetch bundle → establish session → talk', async () => {
|
||||
// Start in-process prekey server
|
||||
const store = new MemoryPrekeyStore();
|
||||
const server = createPrekeyServer({ store });
|
||||
const server = createPrekeyServer({ crypto, store, disableRateLimit: true });
|
||||
|
||||
// We'll use Hono's request() method directly instead of actual HTTP
|
||||
// But ShadeFetchTransport uses fetch(), so let's start a real server
|
||||
const port = 19000 + Math.floor(Math.random() * 1000);
|
||||
const handle = Bun.serve({ port, fetch: server.fetch });
|
||||
|
||||
try {
|
||||
const baseUrl = `http://localhost:${port}`;
|
||||
const transport = new ShadeFetchTransport(baseUrl);
|
||||
|
||||
// ─── Bob: register with prekey server ────────────────
|
||||
// ─── Bob: set up session manager, register with transport ──
|
||||
const bobStorage = new MemoryStorage();
|
||||
const bobManager = new ShadeSessionManager(crypto, bobStorage);
|
||||
await bobManager.initialize();
|
||||
|
||||
const bobIdentity = await bobStorage.getIdentityKeyPair();
|
||||
const bobTransport = new ShadeFetchTransport({
|
||||
baseUrl,
|
||||
crypto,
|
||||
signingPrivateKey: bobIdentity!.signingPrivateKey,
|
||||
});
|
||||
|
||||
const bobOTPKs = await bobManager.generateOneTimePreKeys(5);
|
||||
const bobBundle = await bobManager.createPreKeyBundle();
|
||||
|
||||
await transport.register(
|
||||
await bobTransport.register(
|
||||
'bob',
|
||||
bobManager.getPublicIdentity(),
|
||||
bobBundle.signedPreKey,
|
||||
bobOTPKs,
|
||||
);
|
||||
|
||||
// Verify count
|
||||
const count = await transport.getKeyCount('bob');
|
||||
expect(count).toBe(5);
|
||||
expect(await bobTransport.getKeyCount('bob')).toBe(5);
|
||||
|
||||
// ─── Alice: fetch bundle and establish session ───────
|
||||
// ─── Alice: anonymous fetch + establish session ───────
|
||||
const aliceStorage = new MemoryStorage();
|
||||
const aliceManager = new ShadeSessionManager(crypto, aliceStorage);
|
||||
await aliceManager.initialize();
|
||||
|
||||
const fetchedBundle = await transport.fetchBundle('bob');
|
||||
// Alice doesn't need a signing key to fetch bundles
|
||||
const aliceTransport = new ShadeFetchTransport({ baseUrl, crypto });
|
||||
|
||||
const fetchedBundle = await aliceTransport.fetchBundle('bob');
|
||||
expect(fetchedBundle.identityDHKey).toEqual(bobManager.getPublicIdentity().dhKey);
|
||||
expect(fetchedBundle.signedPreKey.keyId).toBe(bobBundle.signedPreKey.keyId);
|
||||
|
||||
// One OTP key consumed
|
||||
const countAfter = await transport.getKeyCount('bob');
|
||||
expect(countAfter).toBe(4);
|
||||
expect(await aliceTransport.getKeyCount('bob')).toBe(4);
|
||||
|
||||
// Alice establishes session
|
||||
await aliceManager.initSessionFromBundle('bob', fetchedBundle);
|
||||
|
||||
// ─── Alice → Bob encrypted message ───────────────────
|
||||
// ─── Alice → Bob encrypted ───────────────────────────
|
||||
const env1 = await aliceManager.encrypt('bob', 'Hello via transport!');
|
||||
const plain1 = await bobManager.decrypt('alice', env1);
|
||||
expect(plain1).toBe('Hello via transport!');
|
||||
@@ -66,12 +66,16 @@ describe('ShadeFetchTransport', () => {
|
||||
const plain2 = await aliceManager.decrypt('bob', env2);
|
||||
expect(plain2).toBe('Got it!');
|
||||
|
||||
// ─── Replenish ───────────────────────────────────────
|
||||
const remaining = await transport.replenish('bob', [
|
||||
// ─── Replenish (signed) ──────────────────────────────
|
||||
const remaining = await bobTransport.replenish('bob', [
|
||||
{ keyId: 200, publicKey: crypto.randomBytes(32) },
|
||||
{ keyId: 201, publicKey: crypto.randomBytes(32) },
|
||||
]);
|
||||
expect(remaining).toBe(6); // 4 remaining + 2 new
|
||||
expect(remaining).toBe(6);
|
||||
|
||||
// ─── Unregister (signed) ─────────────────────────────
|
||||
await bobTransport.unregister('bob');
|
||||
await expect(aliceTransport.fetchBundle('bob')).rejects.toThrow();
|
||||
|
||||
} finally {
|
||||
handle.stop();
|
||||
|
||||
Reference in New Issue
Block a user